From 9a65f1b1c0b41469c0269c904581568f3ddf5c46 Mon Sep 17 00:00:00 2001 From: wangmengc Date: Wed, 16 Aug 2023 08:31:22 +0800 Subject: [PATCH] =?UTF-8?q?=20fix:193535.history=20-p=20mount=E5=92=8C?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E4=B8=AD=E9=A2=84=E6=9C=9F=E4=B8=8D=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bash-5.1/.cargo/config.toml | 6 +- bash-5.1/Cargo.toml | 8 - bash-5.1/Makefile.in | 4 +- bash-5.1/builtins/exit.def | 1 - bash-5.1/builtins_rust/history/src/lib.rs | 6 +- bash-5.1/parse.y | 5 +- .../vendor/aho-corasick/.cargo-checksum.json | 1 + bash-5.1/vendor/aho-corasick/COPYING | 3 + bash-5.1/vendor/aho-corasick/Cargo.toml | 72 + bash-5.1/vendor/aho-corasick/LICENSE-MIT | 21 + bash-5.1/vendor/aho-corasick/README.md | 55 + bash-5.1/vendor/aho-corasick/UNLICENSE | 24 + bash-5.1/vendor/aho-corasick/benches/bench.rs | 373 + .../vendor/aho-corasick/benches/random.txt | 513 ++ .../aho-corasick/examples/dict-search.rs | 138 + bash-5.1/vendor/aho-corasick/src/autiter.rs | 530 ++ bash-5.1/vendor/aho-corasick/src/full.rs | 145 + bash-5.1/vendor/aho-corasick/src/lib.rs | 1116 +++ bash-5.1/vendor/aho-corasick/src/main.rs | 13 + .../vendor/ansi_term/.cargo-checksum.json | 1 + bash-5.1/vendor/ansi_term/Cargo.toml | 43 + bash-5.1/vendor/ansi_term/LICENCE | 21 + bash-5.1/vendor/ansi_term/README.md | 183 + .../vendor/ansi_term/examples/256_colours.rs | 73 + .../ansi_term/examples/basic_colours.rs | 18 + .../vendor/ansi_term/examples/rgb_colours.rs | 23 + bash-5.1/vendor/ansi_term/src/ansi.rs | 374 + bash-5.1/vendor/ansi_term/src/debug.rs | 134 + bash-5.1/vendor/ansi_term/src/difference.rs | 179 + bash-5.1/vendor/ansi_term/src/display.rs | 296 + bash-5.1/vendor/ansi_term/src/lib.rs | 271 + bash-5.1/vendor/ansi_term/src/style.rs | 521 ++ bash-5.1/vendor/ansi_term/src/util.rs | 81 + bash-5.1/vendor/ansi_term/src/windows.rs | 61 + bash-5.1/vendor/ansi_term/src/write.rs | 40 + bash-5.1/vendor/aster/.cargo-checksum.json | 1 + bash-5.1/vendor/aster/Cargo.toml | 21 + bash-5.1/vendor/aster/src/arm.rs | 241 + bash-5.1/vendor/aster/src/attr.rs | 349 + bash-5.1/vendor/aster/src/block.rs | 110 + bash-5.1/vendor/aster/src/constant.rs | 88 + bash-5.1/vendor/aster/src/ctx.rs | 17 + bash-5.1/vendor/aster/src/expr.rs | 2181 ++++++ bash-5.1/vendor/aster/src/fn_decl.rs | 262 + bash-5.1/vendor/aster/src/generics.rs | 254 + bash-5.1/vendor/aster/src/ident.rs | 45 + bash-5.1/vendor/aster/src/invoke.rs | 16 + bash-5.1/vendor/aster/src/item.rs | 1551 +++++ bash-5.1/vendor/aster/src/lib.rs | 222 + bash-5.1/vendor/aster/src/lifetime.rs | 118 + bash-5.1/vendor/aster/src/lit.rs | 160 + bash-5.1/vendor/aster/src/mac.rs | 144 + bash-5.1/vendor/aster/src/method.rs | 103 + bash-5.1/vendor/aster/src/pat.rs | 558 ++ bash-5.1/vendor/aster/src/path.rs | 378 + bash-5.1/vendor/aster/src/qpath.rs | 161 + bash-5.1/vendor/aster/src/self_.rs | 81 + bash-5.1/vendor/aster/src/stmt.rs | 360 + bash-5.1/vendor/aster/src/struct_field.rs | 115 + bash-5.1/vendor/aster/src/symbol.rs | 44 + bash-5.1/vendor/aster/src/ty.rs | 646 ++ bash-5.1/vendor/aster/src/ty_param.rs | 304 + bash-5.1/vendor/aster/src/variant.rs | 107 + bash-5.1/vendor/aster/src/variant_data.rs | 166 + bash-5.1/vendor/aster/src/where_predicate.rs | 338 + bash-5.1/vendor/async-trait/src/bound.rs | 48 + .../tests/ui/lifetime-defined-here.rs | 23 + .../tests/ui/lifetime-defined-here.stderr | 29 + bash-5.1/vendor/atty/.cargo-checksum.json | 1 + bash-5.1/vendor/atty/CHANGELOG.md | 73 + bash-5.1/vendor/atty/Cargo.toml | 34 + bash-5.1/vendor/atty/LICENSE | 20 + bash-5.1/vendor/atty/README.md | 74 + bash-5.1/vendor/atty/examples/atty.rs | 9 + bash-5.1/vendor/atty/rustfmt.toml | 4 + bash-5.1/vendor/atty/src/lib.rs | 210 + .../vendor/autocfg-0.1.8/.cargo-checksum.json | 1 + bash-5.1/vendor/autocfg-0.1.8/Cargo.toml | 28 + bash-5.1/vendor/autocfg-0.1.8/LICENSE-APACHE | 201 + bash-5.1/vendor/autocfg-0.1.8/LICENSE-MIT | 25 + bash-5.1/vendor/autocfg-0.1.8/README.md | 87 + bash-5.1/vendor/autocfg-0.1.8/src/lib.rs | 6 + bash-5.1/vendor/bindgen/.cargo-checksum.json | 1 + bash-5.1/vendor/bindgen/CONTRIBUTING.md | 234 + bash-5.1/vendor/bindgen/Cargo.toml | 71 + bash-5.1/vendor/bindgen/LICENSE | 28 + bash-5.1/vendor/bindgen/README.md | 227 + bash-5.1/vendor/bindgen/build.rs | 58 + bash-5.1/vendor/bindgen/ci/before_install.sh | 26 + bash-5.1/vendor/bindgen/rustfmt.toml | 10 + bash-5.1/vendor/bindgen/src/chooser.rs | 26 + bash-5.1/vendor/bindgen/src/clang.rs | 1376 ++++ .../vendor/bindgen/src/codegen/helpers.rs | 190 + bash-5.1/vendor/bindgen/src/codegen/mod.rs | 2434 +++++++ bash-5.1/vendor/bindgen/src/ir/annotations.rs | 188 + bash-5.1/vendor/bindgen/src/ir/comp.rs | 986 +++ bash-5.1/vendor/bindgen/src/ir/context.rs | 1269 ++++ bash-5.1/vendor/bindgen/src/ir/derive.rs | 67 + bash-5.1/vendor/bindgen/src/ir/enum_ty.rs | 183 + bash-5.1/vendor/bindgen/src/ir/function.rs | 316 + bash-5.1/vendor/bindgen/src/ir/int.rs | 113 + bash-5.1/vendor/bindgen/src/ir/item.rs | 1375 ++++ bash-5.1/vendor/bindgen/src/ir/item_kind.rs | 114 + bash-5.1/vendor/bindgen/src/ir/layout.rs | 91 + bash-5.1/vendor/bindgen/src/ir/mod.rs | 19 + bash-5.1/vendor/bindgen/src/ir/module.rs | 78 + bash-5.1/vendor/bindgen/src/ir/ty.rs | 937 +++ .../vendor/bindgen/src/ir/type_collector.rs | 22 + bash-5.1/vendor/bindgen/src/ir/var.rs | 317 + bash-5.1/vendor/bindgen/src/lib.rs | 868 +++ bash-5.1/vendor/bindgen/src/log_stubs.rs | 30 + bash-5.1/vendor/bindgen/src/main.rs | 59 + bash-5.1/vendor/bindgen/src/options.rs | 347 + bash-5.1/vendor/bindgen/src/parse.rs | 104 + bash-5.1/vendor/bindgen/src/regex_set.rs | 69 + bash-5.1/vendor/bindgen/src/uses.rs | 102 + .../bindgen/tests/headers/16-byte-alignment.h | 33 + .../bindgen/tests/headers/accessors.hpp | 46 + .../bindgen/tests/headers/annotation_hide.hpp | 16 + .../bindgen/tests/headers/anon_enum.hpp | 10 + .../bindgen/tests/headers/anon_enum_trait.hpp | 22 + .../tests/headers/anon_enum_whitelist.h | 6 + .../bindgen/tests/headers/anon_union.hpp | 20 + .../bindgen/tests/headers/arg_keyword.hpp | 1 + .../vendor/bindgen/tests/headers/auto.hpp | 19 + .../bad-namespace-parenthood-inheritance.hpp | 15 + .../bindgen/tests/headers/base-to-derived.hpp | 19 + .../tests/headers/bitfield-enum-basic.hpp | 27 + .../tests/headers/bitfield_method_mangling.h | 5 + .../vendor/bindgen/tests/headers/blocks.h | 3 + .../canonical_path_without_namespacing.hpp | 7 + .../vendor/bindgen/tests/headers/class.hpp | 29 + .../bindgen/tests/headers/class_nested.hpp | 24 + .../tests/headers/class_no_members.hpp | 16 + .../bindgen/tests/headers/class_static.hpp | 7 + .../tests/headers/class_static_const.hpp | 8 + .../bindgen/tests/headers/class_use_as.hpp | 15 + .../bindgen/tests/headers/class_with_dtor.hpp | 13 + .../tests/headers/class_with_inner_struct.hpp | 43 + .../tests/headers/class_with_typedef.hpp | 22 + .../vendor/bindgen/tests/headers/complex.h | 16 + .../bindgen/tests/headers/complex_global.h | 3 + .../bindgen/tests/headers/const_bool.hpp | 9 + .../tests/headers/const_enum_unnamed.hpp | 9 + .../bindgen/tests/headers/const_ptr.hpp | 3 + .../bindgen/tests/headers/const_resolved_ty.h | 3 + .../bindgen/tests/headers/const_tparam.hpp | 5 + .../bindgen/tests/headers/constant-evaluate.h | 19 + .../tests/headers/constify-all-enums.h | 11 + .../bindgen/tests/headers/constify-enum.h | 13 + .../bindgen/tests/headers/constructor-tp.hpp | 26 + .../bindgen/tests/headers/constructors.hpp | 13 + .../bindgen/tests/headers/convert-floats.h | 9 + .../vendor/bindgen/tests/headers/crtp.hpp | 12 + .../bindgen/tests/headers/dash_language.h | 6 + .../tests/headers/decl_extern_int_twice.h | 2 + .../bindgen/tests/headers/decl_ptr_to_array.h | 1 + .../tests/headers/disable-namespacing.hpp | 9 + .../duplicated-namespaces-definitions.hpp | 18 + .../tests/headers/duplicated-namespaces.hpp | 4 + .../headers/duplicated_constants_in_ns.hpp | 7 + .../bindgen/tests/headers/elaborated.hpp | 5 + .../headers/empty_template_param_name.hpp | 6 + bash-5.1/vendor/bindgen/tests/headers/enum.h | 9 + .../bindgen/tests/headers/enum_alias.hpp | 7 + .../headers/enum_and_vtable_mangling.hpp | 11 + .../vendor/bindgen/tests/headers/enum_dupe.h | 4 + .../tests/headers/enum_explicit_type.hpp | 28 + .../headers/enum_in_template_with_typedef.hpp | 16 + .../bindgen/tests/headers/enum_negative.h | 4 + .../bindgen/tests/headers/enum_packed.h | 14 + .../eval-variadic-template-parameter.hpp | 8 + .../vendor/bindgen/tests/headers/extern.hpp | 3 + .../vendor/bindgen/tests/headers/float128.hpp | 13 + .../headers/forward-declaration-autoptr.hpp | 10 + .../forward-inherit-struct-with-fields.hpp | 8 + .../tests/headers/forward-inherit-struct.hpp | 5 + .../forward_declared_complex_types.hpp | 16 + .../tests/headers/forward_declared_struct.h | 11 + .../vendor/bindgen/tests/headers/func_proto.h | 1 + .../vendor/bindgen/tests/headers/func_ptr.h | 1 + .../tests/headers/func_ptr_in_struct.h | 6 + .../tests/headers/func_with_array_arg.h | 1 + .../tests/headers/func_with_func_ptr_arg.h | 1 + .../tests/headers/in_class_typedef.hpp | 10 + .../tests/headers/inherit-namespaced.hpp | 4 + .../bindgen/tests/headers/inherit_named.hpp | 5 + .../bindgen/tests/headers/inherit_typedef.hpp | 5 + .../bindgen/tests/headers/inline-function.h | 6 + .../tests/headers/inline_namespace.hpp | 11 + .../headers/inline_namespace_conservative.hpp | 12 + .../headers/inline_namespace_whitelist.hpp | 7 + .../bindgen/tests/headers/inner_const.hpp | 6 + .../tests/headers/inner_template_self.hpp | 10 + .../vendor/bindgen/tests/headers/int128_t.h | 7 + .../bindgen/tests/headers/issue-358.hpp | 8 + .../bindgen/tests/headers/issue-372.hpp | 16 + .../bindgen/tests/headers/issue-410.hpp | 12 + .../bindgen/tests/headers/issue-447.hpp | 27 + .../bindgen/tests/headers/issue_311.hpp | 5 + .../bindgen/tests/headers/issue_315.hpp | 2 + .../tests/headers/jsval_layout_opaque.hpp | 424 ++ .../vendor/bindgen/tests/headers/keywords.h | 49 + .../bindgen/tests/headers/macro-expr-basic.h | 14 + .../bindgen/tests/headers/macro-redef.h | 5 + .../bindgen/tests/headers/macro_const.h | 7 + .../tests/headers/maddness-is-avoidable.hpp | 9 + .../bindgen/tests/headers/method-mangling.hpp | 5 + .../tests/headers/module-whitelisted.hpp | 2 + .../bindgen/tests/headers/msvc-no-usr.hpp | 8 + .../multiple-inherit-empty-correct-layout.hpp | 3 + .../vendor/bindgen/tests/headers/mutable.hpp | 14 + .../bindgen/tests/headers/namespace.hpp | 47 + .../vendor/bindgen/tests/headers/nested.hpp | 15 + .../bindgen/tests/headers/nested_vtable.hpp | 8 + .../tests/headers/nested_within_namespace.hpp | 15 + .../bindgen/tests/headers/no-comments.h | 5 + .../bindgen/tests/headers/no-derive-debug.h | 15 + .../tests/headers/no-recursive-whitelisting.h | 7 + .../vendor/bindgen/tests/headers/no-std.h | 5 + .../vendor/bindgen/tests/headers/no_copy.hpp | 6 + .../tests/headers/nsStyleAutoArray.hpp | 57 + .../bindgen/tests/headers/only_bitfields.hpp | 5 + .../bindgen/tests/headers/opaque-tracing.hpp | 21 + .../tests/headers/opaque_in_struct.hpp | 10 + .../bindgen/tests/headers/opaque_pointer.hpp | 22 + .../bindgen/tests/headers/opaque_typedef.hpp | 17 + .../bindgen/tests/headers/overflowed_enum.hpp | 12 + .../bindgen/tests/headers/overloading.hpp | 9 + .../vendor/bindgen/tests/headers/private.hpp | 21 + .../bindgen/tests/headers/public-dtor.hpp | 15 + .../bindgen/tests/headers/redeclaration.hpp | 7 + .../tests/headers/ref_argument_array.hpp | 6 + .../tests/headers/reparented_replacement.hpp | 16 + .../tests/headers/replace_template_alias.hpp | 23 + .../bindgen/tests/headers/replace_use.hpp | 15 + .../bindgen/tests/headers/replaces_double.hpp | 20 + .../headers/resolved_type_def_function.h | 2 + ...me_struct_name_in_different_namespaces.hpp | 12 + .../bindgen/tests/headers/size_t_template.hpp | 8 + ...truct_containing_forward_declared_struct.h | 7 + .../tests/headers/struct_with_anon_struct.h | 6 + .../headers/struct_with_anon_struct_array.h | 10 + .../headers/struct_with_anon_struct_pointer.h | 6 + .../tests/headers/struct_with_anon_union.h | 6 + .../headers/struct_with_anon_unnamed_struct.h | 6 + .../headers/struct_with_anon_unnamed_union.h | 6 + .../tests/headers/struct_with_bitfields.h | 13 + .../tests/headers/struct_with_derive_debug.h | 15 + .../tests/headers/struct_with_nesting.h | 17 + .../tests/headers/struct_with_packing.h | 4 + .../tests/headers/struct_with_struct.h | 6 + .../struct_with_typedef_template_arg.hpp | 4 + .../vendor/bindgen/tests/headers/template.hpp | 144 + .../bindgen/tests/headers/template_alias.hpp | 13 + .../tests/headers/template_alias_basic.hpp | 4 + .../headers/template_alias_namespace.hpp | 13 + .../template_typedef_transitive_param.hpp | 7 + .../tests/headers/template_typedefs.hpp | 8 + .../tests/headers/templateref_opaque.hpp | 11 + .../type-referenced-by-whitelisted-function.h | 7 + .../tests/headers/type_alias_empty.hpp | 10 + ...alias_partial_template_especialization.hpp | 7 + .../type_alias_template_specialized.hpp | 9 + .../headers/typedefd-array-as-function-arg.h | 3 + .../vendor/bindgen/tests/headers/typeref.hpp | 28 + .../bindgen/tests/headers/union-in-ns.hpp | 5 + .../bindgen/tests/headers/union_dtor.hpp | 5 + .../bindgen/tests/headers/union_fields.hpp | 5 + .../bindgen/tests/headers/union_template.hpp | 19 + .../tests/headers/union_with_anon_struct.h | 6 + .../headers/union_with_anon_struct_bitfield.h | 8 + .../tests/headers/union_with_anon_union.h | 6 + .../headers/union_with_anon_unnamed_struct.h | 9 + .../headers/union_with_anon_unnamed_union.h | 7 + .../tests/headers/union_with_big_member.h | 14 + .../tests/headers/union_with_nesting.h | 14 + .../bindgen/tests/headers/unknown_attr.h | 6 + .../vendor/bindgen/tests/headers/use-core.h | 8 + .../vendor/bindgen/tests/headers/using.hpp | 11 + .../bindgen/tests/headers/var-tracing.hpp | 10 + .../bindgen/tests/headers/variadic-method.hpp | 6 + .../headers/variadic_template_function.hpp | 6 + .../vendor/bindgen/tests/headers/vector.hpp | 3 + .../bindgen/tests/headers/virtual_dtor.hpp | 3 + .../tests/headers/virtual_inheritance.hpp | 16 + .../tests/headers/virtual_overloaded.hpp | 5 + .../tests/headers/vtable_recursive_sig.hpp | 11 + .../bindgen/tests/headers/weird_bitfields.hpp | 35 + .../tests/headers/what_is_going_on.hpp | 19 + .../headers/whitelist-namespaces-basic.hpp | 10 + .../tests/headers/whitelist-namespaces.hpp | 10 + .../bindgen/tests/headers/whitelist_basic.hpp | 16 + .../bindgen/tests/headers/whitelist_fix.hpp | 4 + .../bindgen/tests/headers/whitelist_vars.h | 4 + bash-5.1/vendor/bindgen/tests/tests.rs | 140 + .../bitflags-0.7.0/.cargo-checksum.json | 1 + bash-5.1/vendor/bitflags-0.7.0/Cargo.toml | 13 + bash-5.1/vendor/bitflags-0.7.0/LICENSE-APACHE | 201 + bash-5.1/vendor/bitflags-0.7.0/LICENSE-MIT | 25 + bash-5.1/vendor/bitflags-0.7.0/README.md | 24 + bash-5.1/vendor/bitflags-0.7.0/src/lib.rs | 808 +++ .../vendor/bitflags-0.7.0/tests/external.rs | 21 + .../bitflags-0.7.0/tests/external_no_std.rs | 22 + bash-5.1/vendor/cexpr/.cargo-checksum.json | 1 + bash-5.1/vendor/cexpr/Cargo.toml | 26 + bash-5.1/vendor/cexpr/LICENSE-APACHE | 201 + bash-5.1/vendor/cexpr/LICENSE-MIT | 25 + bash-5.1/vendor/cexpr/src/expr.rs | 578 ++ bash-5.1/vendor/cexpr/src/lib.rs | 57 + bash-5.1/vendor/cexpr/src/literal.rs | 239 + bash-5.1/vendor/cexpr/src/token.rs | 40 + bash-5.1/vendor/cexpr/tests/clang.rs | 246 + bash-5.1/vendor/cexpr/tests/input/chars.h | 3 + bash-5.1/vendor/cexpr/tests/input/fail.h | 9 + bash-5.1/vendor/cexpr/tests/input/floats.h | 8 + .../vendor/cexpr/tests/input/int_signed.h | 3 + .../vendor/cexpr/tests/input/int_unsigned.h | 26 + bash-5.1/vendor/cexpr/tests/input/strings.h | 12 + .../cexpr/tests/input/test_llvm_bug_9069.h | 4 + .../vendor/cfg-if-0.1.10/.cargo-checksum.json | 1 + bash-5.1/vendor/cfg-if-0.1.10/Cargo.toml | 36 + bash-5.1/vendor/cfg-if-0.1.10/LICENSE-APACHE | 201 + bash-5.1/vendor/cfg-if-0.1.10/LICENSE-MIT | 25 + bash-5.1/vendor/cfg-if-0.1.10/README.md | 47 + bash-5.1/vendor/cfg-if-0.1.10/src/lib.rs | 176 + bash-5.1/vendor/cfg-if-0.1.10/tests/xcrate.rs | 14 + .../vendor/clang-sys/.cargo-checksum.json | 1 + bash-5.1/vendor/clang-sys/CHANGELOG.md | 175 + bash-5.1/vendor/clang-sys/CONTRIBUTING.md | 14 + bash-5.1/vendor/clang-sys/Cargo.toml | 48 + bash-5.1/vendor/clang-sys/LICENSE.txt | 202 + bash-5.1/vendor/clang-sys/README.md | 96 + bash-5.1/vendor/clang-sys/appveyor.yml | 12 + bash-5.1/vendor/clang-sys/build.rs | 288 + .../vendor/clang-sys/ci/before_install.sh | 32 + bash-5.1/vendor/clang-sys/ci/install.bat | 8 + bash-5.1/vendor/clang-sys/ci/script.sh | 13 + bash-5.1/vendor/clang-sys/ci/test_script.bat | 3 + bash-5.1/vendor/clang-sys/clippy.toml | 1 + bash-5.1/vendor/clang-sys/src/lib.rs | 1740 +++++ bash-5.1/vendor/clang-sys/src/link.rs | 184 + bash-5.1/vendor/clang-sys/src/support.rs | 171 + bash-5.1/vendor/clang-sys/tests/header.h | 6 + bash-5.1/vendor/clang-sys/tests/lib.rs | 46 + bash-5.1/vendor/clap/.cargo-checksum.json | 1 + bash-5.1/vendor/clap/CHANGELOG.md | 2902 ++++++++ bash-5.1/vendor/clap/CONTRIBUTORS.md | 91 + bash-5.1/vendor/clap/Cargo.toml | 132 + bash-5.1/vendor/clap/LICENSE-MIT | 21 + bash-5.1/vendor/clap/README.md | 542 ++ bash-5.1/vendor/clap/SPONSORS.md | 17 + bash-5.1/vendor/clap/clap-test.rs | 86 + bash-5.1/vendor/clap/justfile | 39 + bash-5.1/vendor/clap/src/app/help.rs | 1032 +++ bash-5.1/vendor/clap/src/app/meta.rs | 35 + bash-5.1/vendor/clap/src/app/mod.rs | 1909 +++++ bash-5.1/vendor/clap/src/app/parser.rs | 2236 ++++++ bash-5.1/vendor/clap/src/app/settings.rs | 1192 ++++ bash-5.1/vendor/clap/src/app/usage.rs | 493 ++ bash-5.1/vendor/clap/src/app/validator.rs | 584 ++ bash-5.1/vendor/clap/src/args/any_arg.rs | 139 + bash-5.1/vendor/clap/src/args/arg.rs | 3961 +++++++++++ .../vendor/clap/src/args/arg_builder/base.rs | 48 + .../vendor/clap/src/args/arg_builder/flag.rs | 216 + .../vendor/clap/src/args/arg_builder/mod.rs | 13 + .../clap/src/args/arg_builder/option.rs | 295 + .../clap/src/args/arg_builder/positional.rs | 284 + .../clap/src/args/arg_builder/switched.rs | 40 + .../clap/src/args/arg_builder/valued.rs | 70 + bash-5.1/vendor/clap/src/args/arg_matcher.rs | 274 + bash-5.1/vendor/clap/src/args/arg_matches.rs | 1001 +++ bash-5.1/vendor/clap/src/args/group.rs | 637 ++ bash-5.1/vendor/clap/src/args/macros.rs | 121 + bash-5.1/vendor/clap/src/args/matched_arg.rs | 29 + bash-5.1/vendor/clap/src/args/mod.rs | 21 + bash-5.1/vendor/clap/src/args/settings.rs | 237 + bash-5.1/vendor/clap/src/args/subcommand.rs | 71 + bash-5.1/vendor/clap/src/completions/bash.rs | 223 + .../vendor/clap/src/completions/elvish.rs | 127 + bash-5.1/vendor/clap/src/completions/fish.rs | 103 + .../vendor/clap/src/completions/macros.rs | 28 + bash-5.1/vendor/clap/src/completions/mod.rs | 182 + .../vendor/clap/src/completions/powershell.rs | 165 + bash-5.1/vendor/clap/src/completions/shell.rs | 56 + bash-5.1/vendor/clap/src/completions/zsh.rs | 484 ++ bash-5.1/vendor/clap/src/errors.rs | 933 +++ bash-5.1/vendor/clap/src/fmt.rs | 192 + bash-5.1/vendor/clap/src/lib.rs | 638 ++ bash-5.1/vendor/clap/src/macros.rs | 1130 +++ bash-5.1/vendor/clap/src/map.rs | 88 + bash-5.1/vendor/clap/src/osstringext.rs | 203 + bash-5.1/vendor/clap/src/strext.rs | 16 + bash-5.1/vendor/clap/src/suggestions.rs | 141 + bash-5.1/vendor/clap/src/usage_parser.rs | 1356 ++++ bash-5.1/vendor/cloudabi/.cargo-checksum.json | 1 + bash-5.1/vendor/cloudabi/Cargo.toml | 31 + bash-5.1/vendor/cloudabi/bitflags.rs | 51 + bash-5.1/vendor/cloudabi/cloudabi.rs | 2847 ++++++++ .../vendor/displaydoc/.cargo-checksum.json | 1 + bash-5.1/vendor/displaydoc/CHANGELOG.md | 39 + bash-5.1/vendor/displaydoc/Cargo.toml | 98 + bash-5.1/vendor/displaydoc/LICENSE-APACHE | 201 + bash-5.1/vendor/displaydoc/LICENSE-MIT | 23 + bash-5.1/vendor/displaydoc/README.md | 99 + bash-5.1/vendor/displaydoc/README.tpl | 23 + bash-5.1/vendor/displaydoc/examples/simple.rs | 36 + bash-5.1/vendor/displaydoc/src/attr.rs | 134 + bash-5.1/vendor/displaydoc/src/expand.rs | 145 + bash-5.1/vendor/displaydoc/src/fmt.rs | 159 + bash-5.1/vendor/displaydoc/src/lib.rs | 122 + .../vendor/displaydoc/tests/compile_tests.rs | 29 + bash-5.1/vendor/displaydoc/tests/happy.rs | 152 + .../displaydoc/tests/no_std/enum_prefix.rs | 36 + .../tests/no_std/enum_prefix_missing.rs | 35 + .../tests/no_std/enum_prefix_missing.stderr | 19 + .../displaydoc/tests/no_std/multi_line.rs | 37 + .../displaydoc/tests/no_std/multi_line.stderr | 19 + .../tests/no_std/multi_line_allow.rs | 38 + .../vendor/displaydoc/tests/no_std/with.rs | 32 + .../vendor/displaydoc/tests/no_std/without.rs | 28 + .../displaydoc/tests/no_std/without.stderr | 19 + .../vendor/displaydoc/tests/num_in_field.rs | 22 + .../displaydoc/tests/std/enum_prefix.rs | 36 + .../tests/std/enum_prefix_missing.rs | 35 + .../tests/std/enum_prefix_missing.stderr | 19 + .../vendor/displaydoc/tests/std/multi_line.rs | 37 + .../displaydoc/tests/std/multi_line.stderr | 19 + .../displaydoc/tests/std/multi_line_allow.rs | 38 + .../vendor/displaydoc/tests/std/multiple.rs | 38 + .../vendor/displaydoc/tests/std/without.rs | 28 + .../displaydoc/tests/std/without.stderr | 19 + bash-5.1/vendor/dtoa/.cargo-checksum.json | 1 + bash-5.1/vendor/dtoa/Cargo.toml | 25 + bash-5.1/vendor/dtoa/LICENSE-APACHE | 201 + bash-5.1/vendor/dtoa/LICENSE-MIT | 23 + bash-5.1/vendor/dtoa/README.md | 80 + bash-5.1/vendor/dtoa/benches/bench.rs | 54 + bash-5.1/vendor/dtoa/src/diyfp.rs | 253 + bash-5.1/vendor/dtoa/src/dtoa.rs | 509 ++ bash-5.1/vendor/dtoa/src/lib.rs | 205 + bash-5.1/vendor/dtoa/tests/test.rs | 38 + .../vendor/env_logger/.cargo-checksum.json | 1 + bash-5.1/vendor/env_logger/Cargo.toml | 35 + bash-5.1/vendor/env_logger/LICENSE-APACHE | 201 + bash-5.1/vendor/env_logger/LICENSE-MIT | 25 + bash-5.1/vendor/env_logger/src/lib.rs | 652 ++ bash-5.1/vendor/env_logger/src/regex.rs | 28 + bash-5.1/vendor/env_logger/src/string.rs | 21 + .../vendor/env_logger/tests/regexp_filter.rs | 51 + .../vendor/fuchsia-cprng/.cargo-checksum.json | 1 + bash-5.1/vendor/fuchsia-cprng/AUTHORS | 10 + bash-5.1/vendor/fuchsia-cprng/Cargo.toml | 22 + bash-5.1/vendor/fuchsia-cprng/LICENSE | 27 + bash-5.1/vendor/fuchsia-cprng/PATENTS | 22 + bash-5.1/vendor/fuchsia-cprng/src/lib.rs | 57 + .../futures-channel/tests/mpsc-size_hint.rs | 40 + bash-5.1/vendor/futures/tests/future_join.rs | 32 + bash-5.1/vendor/glob/.cargo-checksum.json | 1 + bash-5.1/vendor/glob/Cargo.toml | 15 + bash-5.1/vendor/glob/LICENSE-APACHE | 201 + bash-5.1/vendor/glob/LICENSE-MIT | 25 + bash-5.1/vendor/glob/README.md | 24 + bash-5.1/vendor/glob/src/lib.rs | 1312 ++++ bash-5.1/vendor/glob/tests/glob-std.rs | 278 + .../vendor/hermit-abi/.cargo-checksum.json | 1 + bash-5.1/vendor/hermit-abi/Cargo.toml | 44 + bash-5.1/vendor/hermit-abi/LICENSE-APACHE | 201 + bash-5.1/vendor/hermit-abi/LICENSE-MIT | 23 + bash-5.1/vendor/hermit-abi/README.md | 22 + bash-5.1/vendor/hermit-abi/rust-toolchain | 1 + bash-5.1/vendor/hermit-abi/src/lib.rs | 490 ++ bash-5.1/vendor/hermit-abi/src/tcplistener.rs | 13 + bash-5.1/vendor/hermit-abi/src/tcpstream.rs | 109 + bash-5.1/vendor/itoa/.cargo-checksum.json | 1 + bash-5.1/vendor/itoa/Cargo.toml | 26 + bash-5.1/vendor/itoa/LICENSE-APACHE | 201 + bash-5.1/vendor/itoa/LICENSE-MIT | 25 + bash-5.1/vendor/itoa/README.md | 71 + bash-5.1/vendor/itoa/benches/bench.rs | 68 + bash-5.1/vendor/itoa/src/lib.rs | 196 + bash-5.1/vendor/itoa/src/udiv128.rs | 62 + bash-5.1/vendor/itoa/tests/test.rs | 43 + .../vendor/kernel32-sys/.cargo-checksum.json | 1 + bash-5.1/vendor/kernel32-sys/Cargo.toml | 17 + bash-5.1/vendor/kernel32-sys/README.md | 13 + bash-5.1/vendor/kernel32-sys/build.rs | 6 + bash-5.1/vendor/kernel32-sys/src/lib.rs | 2754 ++++++++ .../lazy_static-0.2.11/.cargo-checksum.json | 1 + bash-5.1/vendor/lazy_static-0.2.11/Cargo.toml | 43 + .../vendor/lazy_static-0.2.11/LICENSE-APACHE | 201 + .../vendor/lazy_static-0.2.11/LICENSE-MIT | 25 + bash-5.1/vendor/lazy_static-0.2.11/README.md | 69 + .../vendor/lazy_static-0.2.11/appveyor.yml | 59 + .../lazy_static-0.2.11/src/core_lazy.rs | 33 + .../vendor/lazy_static-0.2.11/src/lazy.rs | 39 + bash-5.1/vendor/lazy_static-0.2.11/src/lib.rs | 212 + .../lazy_static-0.2.11/src/nightly_lazy.rs | 43 + .../tests/compile-fail/README.md | 22 + .../incorrect_visibility_restriction.rs | 10 + .../tests/compile-fail/static_is_private.rs | 14 + .../tests/compile-fail/static_is_sized.rs | 11 + .../tests/compile-fail/static_never_used.rs | 10 + .../lazy_static-0.2.11/tests/compile_tests.rs | 18 + .../vendor/lazy_static-0.2.11/tests/no_std.rs | 21 + .../vendor/lazy_static-0.2.11/tests/test.rs | 164 + bash-5.1/vendor/libc/.cargo-checksum.json | 2 +- bash-5.1/vendor/libc/CONTRIBUTING.md | 4 + bash-5.1/vendor/libc/Cargo.toml | 2 +- bash-5.1/vendor/libc/README.md | 8 +- bash-5.1/vendor/libc/build.rs | 15 +- bash-5.1/vendor/libc/src/fuchsia/mod.rs | 38 +- bash-5.1/vendor/libc/src/lib.rs | 10 +- bash-5.1/vendor/libc/src/macros.rs | 16 - bash-5.1/vendor/libc/src/unix/aix/mod.rs | 2314 ++++++ .../vendor/libc/src/unix/aix/powerpc64.rs | 570 ++ .../src/unix/bsd/apple/b64/aarch64/align.rs | 1 + .../libc/src/unix/bsd/apple/long_array.rs | 8 + .../vendor/libc/src/unix/bsd/apple/mod.rs | 404 +- .../src/unix/bsd/freebsdlike/dragonfly/mod.rs | 80 + .../bsd/freebsdlike/freebsd/freebsd11/mod.rs | 8 + .../bsd/freebsdlike/freebsd/freebsd12/mod.rs | 13 + .../bsd/freebsdlike/freebsd/freebsd13/mod.rs | 13 + .../bsd/freebsdlike/freebsd/freebsd14/mod.rs | 13 + .../src/unix/bsd/freebsdlike/freebsd/mod.rs | 181 +- .../libc/src/unix/bsd/freebsdlike/mod.rs | 55 + bash-5.1/vendor/libc/src/unix/bsd/mod.rs | 6 + .../libc/src/unix/bsd/netbsdlike/mod.rs | 11 - .../src/unix/bsd/netbsdlike/netbsd/mod.rs | 197 +- .../src/unix/bsd/netbsdlike/openbsd/mod.rs | 27 + bash-5.1/vendor/libc/src/unix/haiku/mod.rs | 92 +- .../src/unix/linux_like/android/b64/mod.rs | 3 + .../unix/linux_like/android/b64/x86_64/mod.rs | 2 + .../libc/src/unix/linux_like/android/mod.rs | 238 +- .../src/unix/linux_like/emscripten/mod.rs | 6 +- .../unix/linux_like/linux/arch/generic/mod.rs | 7 + .../unix/linux_like/linux/gnu/b32/arm/mod.rs | 8 + .../unix/linux_like/linux/gnu/b32/mips/mod.rs | 8 + .../unix/linux_like/linux/gnu/b32/powerpc.rs | 8 + .../linux_like/linux/gnu/b32/riscv32/mod.rs | 8 + .../linux_like/linux/gnu/b32/sparc/mod.rs | 8 + .../unix/linux_like/linux/gnu/b32/x86/mod.rs | 8 + .../linux_like/linux/gnu/b64/aarch64/align.rs | 22 + .../linux_like/linux/gnu/b64/aarch64/mod.rs | 24 + .../linux_like/linux/gnu/b64/mips64/mod.rs | 8 + .../linux_like/linux/gnu/b64/powerpc64/mod.rs | 8 + .../linux_like/linux/gnu/b64/riscv64/mod.rs | 8 + .../unix/linux_like/linux/gnu/b64/s390x.rs | 8 + .../linux_like/linux/gnu/b64/sparc64/mod.rs | 8 + .../linux_like/linux/gnu/b64/x86_64/align.rs | 17 + .../linux_like/linux/gnu/b64/x86_64/mod.rs | 22 + .../linux/gnu/b64/x86_64/not_x32.rs | 8 + .../linux_like/linux/gnu/b64/x86_64/x32.rs | 8 + .../libc/src/unix/linux_like/linux/gnu/mod.rs | 30 + .../libc/src/unix/linux_like/linux/mod.rs | 328 +- .../unix/linux_like/linux/musl/b32/arm/mod.rs | 8 + .../linux_like/linux/musl/b32/mips/mod.rs | 8 + .../src/unix/linux_like/linux/musl/b32/mod.rs | 1 + .../unix/linux_like/linux/musl/b32/powerpc.rs | 8 + .../linux_like/linux/musl/b32/riscv32/mod.rs | 1 + .../unix/linux_like/linux/musl/b32/x86/mod.rs | 8 + .../linux/musl/b64/aarch64/align.rs | 15 + .../linux_like/linux/musl/b64/aarch64/mod.rs | 9 + .../unix/linux_like/linux/musl/b64/mips64.rs | 11 +- .../linux_like/linux/musl/b64/powerpc64.rs | 9 + .../linux_like/linux/musl/b64/riscv64/mod.rs | 1 + .../unix/linux_like/linux/musl/b64/s390x.rs | 10 + .../linux_like/linux/musl/b64/x86_64/align.rs | 18 + .../linux_like/linux/musl/b64/x86_64/mod.rs | 9 + .../src/unix/linux_like/linux/musl/mod.rs | 5 + .../unix/linux_like/linux/uclibc/arm/mod.rs | 1 + .../src/unix/linux_like/linux/uclibc/mod.rs | 2 + .../linux_like/linux/uclibc/x86_64/mod.rs | 1 + .../vendor/libc/src/unix/linux_like/mod.rs | 15 +- bash-5.1/vendor/libc/src/unix/mod.rs | 16 +- .../vendor/libc/src/unix/newlib/espidf/mod.rs | 5 + bash-5.1/vendor/libc/src/unix/newlib/mod.rs | 2 +- bash-5.1/vendor/libc/src/unix/nto/aarch64.rs | 36 + bash-5.1/vendor/libc/src/unix/nto/mod.rs | 3285 +++++++++ bash-5.1/vendor/libc/src/unix/nto/neutrino.rs | 1288 ++++ bash-5.1/vendor/libc/src/unix/nto/x86_64.rs | 132 + .../vendor/libc/src/unix/solarish/illumos.rs | 5 + bash-5.1/vendor/libc/src/unix/solarish/mod.rs | 18 +- .../vendor/libc/src/unix/solarish/solaris.rs | 11 +- .../vendor/libc/src/unix/solarish/x86_64.rs | 31 + bash-5.1/vendor/libc/src/windows/mod.rs | 12 +- bash-5.1/vendor/libc/src/xous.rs | 49 + .../libloading-0.3.4/.cargo-checksum.json | 1 + bash-5.1/vendor/libloading-0.3.4/Cargo.toml | 20 + bash-5.1/vendor/libloading-0.3.4/LICENSE | 12 + bash-5.1/vendor/libloading-0.3.4/README.mkd | 27 + bash-5.1/vendor/libloading-0.3.4/appveyor.yml | 19 + bash-5.1/vendor/libloading-0.3.4/build.rs | 47 + .../vendor/libloading-0.3.4/src/changelog.rs | 51 + bash-5.1/vendor/libloading-0.3.4/src/lib.rs | 281 + .../vendor/libloading-0.3.4/src/os/mod.rs | 45 + .../libloading-0.3.4/src/os/unix/mod.rs | 271 + .../libloading-0.3.4/src/os/windows/mod.rs | 242 + .../libloading-0.3.4/src/test_helpers.rs | 49 + bash-5.1/vendor/libloading-0.3.4/src/util.rs | 61 + .../libloading-0.3.4/tests/functions.rs | 85 + .../vendor/libloading-0.3.4/tests/markers.rs | 79 + .../libloading-0.3.4/tests/nagisa32.dll | Bin 0 -> 3072 bytes .../libloading-0.3.4/tests/nagisa64.dll | Bin 0 -> 2560 bytes .../vendor/libloading-0.3.4/tests/statics.rs | 44 + .../vendor/libloading-0.3.4/tests/windows.rs | 56 + .../vendor/log-0.3.9/.cargo-checksum.json | 1 + bash-5.1/vendor/log-0.3.9/Cargo.toml | 45 + bash-5.1/vendor/log-0.3.9/LICENSE-APACHE | 201 + bash-5.1/vendor/log-0.3.9/LICENSE-MIT | 25 + bash-5.1/vendor/log-0.3.9/README.md | 160 + bash-5.1/vendor/log-0.3.9/appveyor.yml | 18 + bash-5.1/vendor/log-0.3.9/src/lib.rs | 1091 +++ bash-5.1/vendor/log-0.3.9/src/macros.rs | 155 + bash-5.1/vendor/log/.cargo-checksum.json | 1 + bash-5.1/vendor/log/CHANGELOG.md | 241 + bash-5.1/vendor/log/Cargo.toml | 112 + bash-5.1/vendor/log/LICENSE-APACHE | 201 + bash-5.1/vendor/log/LICENSE-MIT | 25 + bash-5.1/vendor/log/README.md | 117 + bash-5.1/vendor/log/benches/value.rs | 30 + bash-5.1/vendor/log/build.rs | 46 + bash-5.1/vendor/log/src/kv/error.rs | 90 + bash-5.1/vendor/log/src/kv/key.rs | 172 + bash-5.1/vendor/log/src/kv/mod.rs | 26 + bash-5.1/vendor/log/src/kv/source.rs | 754 ++ bash-5.1/vendor/log/src/kv/value.rs | 1034 +++ bash-5.1/vendor/log/src/lib.rs | 1971 ++++++ bash-5.1/vendor/log/src/macros.rs | 280 + bash-5.1/vendor/log/src/serde.rs | 400 ++ bash-5.1/vendor/log/triagebot.toml | 1 + .../vendor/memchr-1.0.2/.cargo-checksum.json | 1 + bash-5.1/vendor/memchr-1.0.2/COPYING | 3 + bash-5.1/vendor/memchr-1.0.2/Cargo.toml | 44 + bash-5.1/vendor/memchr-1.0.2/LICENSE-MIT | 21 + bash-5.1/vendor/memchr-1.0.2/Makefile | 14 + bash-5.1/vendor/memchr-1.0.2/README.md | 36 + bash-5.1/vendor/memchr-1.0.2/UNLICENSE | 24 + bash-5.1/vendor/memchr-1.0.2/appveyor.yml | 19 + bash-5.1/vendor/memchr-1.0.2/benches/bench.rs | 117 + bash-5.1/vendor/memchr-1.0.2/ctags.rust | 11 + bash-5.1/vendor/memchr-1.0.2/session.vim | 1 + bash-5.1/vendor/memchr-1.0.2/src/lib.rs | 881 +++ bash-5.1/vendor/nix/.cargo-checksum.json | 2 +- bash-5.1/vendor/nix/CHANGELOG.md | 76 +- bash-5.1/vendor/nix/Cargo.toml | 27 +- bash-5.1/vendor/nix/README.md | 5 +- bash-5.1/vendor/nix/src/dir.rs | 18 +- bash-5.1/vendor/nix/src/env.rs | 1 - bash-5.1/vendor/nix/src/errno.rs | 2979 ++++---- bash-5.1/vendor/nix/src/fcntl.rs | 43 +- bash-5.1/vendor/nix/src/features.rs | 1 + bash-5.1/vendor/nix/src/lib.rs | 65 +- bash-5.1/vendor/nix/src/macros.rs | 9 +- bash-5.1/vendor/nix/src/mount/bsd.rs | 5 +- bash-5.1/vendor/nix/src/mqueue.rs | 29 +- bash-5.1/vendor/nix/src/net/if_.rs | 4 +- bash-5.1/vendor/nix/src/poll.rs | 8 +- bash-5.1/vendor/nix/src/sched.rs | 4 +- bash-5.1/vendor/nix/src/sys/aio.rs | 1841 ++--- bash-5.1/vendor/nix/src/sys/event.rs | 15 +- bash-5.1/vendor/nix/src/sys/ioctl/bsd.rs | 38 +- bash-5.1/vendor/nix/src/sys/ioctl/linux.rs | 64 +- bash-5.1/vendor/nix/src/sys/ioctl/mod.rs | 50 +- bash-5.1/vendor/nix/src/sys/mman.rs | 3 + bash-5.1/vendor/nix/src/sys/mod.rs | 90 +- bash-5.1/vendor/nix/src/sys/personality.rs | 2 +- bash-5.1/vendor/nix/src/sys/ptrace/linux.rs | 21 + bash-5.1/vendor/nix/src/sys/quota.rs | 4 +- bash-5.1/vendor/nix/src/sys/resource.rs | 186 +- bash-5.1/vendor/nix/src/sys/signal.rs | 408 +- bash-5.1/vendor/nix/src/sys/signalfd.rs | 10 +- bash-5.1/vendor/nix/src/sys/socket/addr.rs | 108 +- bash-5.1/vendor/nix/src/sys/socket/mod.rs | 72 +- bash-5.1/vendor/nix/src/sys/socket/sockopt.rs | 33 +- bash-5.1/vendor/nix/src/sys/stat.rs | 114 +- bash-5.1/vendor/nix/src/sys/statfs.rs | 104 +- bash-5.1/vendor/nix/src/sys/statvfs.rs | 2 + bash-5.1/vendor/nix/src/sys/sysinfo.rs | 6 +- bash-5.1/vendor/nix/src/sys/termios.rs | 32 +- bash-5.1/vendor/nix/src/sys/time.rs | 229 +- bash-5.1/vendor/nix/src/sys/timer.rs | 4 + bash-5.1/vendor/nix/src/sys/timerfd.rs | 4 + bash-5.1/vendor/nix/src/sys/uio.rs | 8 +- bash-5.1/vendor/nix/src/unistd.rs | 352 +- bash-5.1/vendor/nix/test/common/mod.rs | 40 +- bash-5.1/vendor/nix/test/sys/mod.rs | 53 +- bash-5.1/vendor/nix/test/sys/test_aio.rs | 1076 +-- bash-5.1/vendor/nix/test/sys/test_aio_drop.rs | 33 +- bash-5.1/vendor/nix/test/sys/test_epoll.rs | 11 +- bash-5.1/vendor/nix/test/sys/test_inotify.rs | 16 +- bash-5.1/vendor/nix/test/sys/test_ioctl.rs | 83 +- bash-5.1/vendor/nix/test/sys/test_mman.rs | 118 +- bash-5.1/vendor/nix/test/sys/test_pthread.rs | 4 +- bash-5.1/vendor/nix/test/sys/test_ptrace.rs | 140 +- bash-5.1/vendor/nix/test/sys/test_select.rs | 5 +- bash-5.1/vendor/nix/test/sys/test_signal.rs | 50 +- bash-5.1/vendor/nix/test/sys/test_signalfd.rs | 2 +- bash-5.1/vendor/nix/test/sys/test_socket.rs | 1340 ++-- bash-5.1/vendor/nix/test/sys/test_sockopt.rs | 228 +- bash-5.1/vendor/nix/test/sys/test_sysinfo.rs | 12 +- bash-5.1/vendor/nix/test/sys/test_termios.rs | 28 +- bash-5.1/vendor/nix/test/sys/test_timerfd.rs | 18 +- bash-5.1/vendor/nix/test/sys/test_uio.rs | 137 +- bash-5.1/vendor/nix/test/sys/test_wait.rs | 154 +- bash-5.1/vendor/nix/test/test.rs | 64 +- bash-5.1/vendor/nix/test/test_dir.rs | 21 +- bash-5.1/vendor/nix/test/test_fcntl.rs | 158 +- bash-5.1/vendor/nix/test/test_kmod/mod.rs | 58 +- bash-5.1/vendor/nix/test/test_mount.rs | 167 +- bash-5.1/vendor/nix/test/test_mq.rs | 49 +- bash-5.1/vendor/nix/test/test_net.rs | 11 +- bash-5.1/vendor/nix/test/test_nix_path.rs | 1 + bash-5.1/vendor/nix/test/test_nmount.rs | 20 +- bash-5.1/vendor/nix/test/test_poll.rs | 22 +- bash-5.1/vendor/nix/test/test_pty.rs | 34 +- .../vendor/nix/test/test_ptymaster_drop.rs | 2 +- bash-5.1/vendor/nix/test/test_resource.rs | 17 +- bash-5.1/vendor/nix/test/test_sched.rs | 5 +- bash-5.1/vendor/nix/test/test_sendfile.rs | 42 +- bash-5.1/vendor/nix/test/test_stat.rs | 249 +- bash-5.1/vendor/nix/test/test_time.rs | 15 +- bash-5.1/vendor/nix/test/test_timer.rs | 25 +- bash-5.1/vendor/nix/test/test_unistd.rs | 502 +- bash-5.1/vendor/nom/.cargo-checksum.json | 1 + bash-5.1/vendor/nom/CHANGELOG.md | 825 +++ bash-5.1/vendor/nom/Cargo.toml | 50 + bash-5.1/vendor/nom/LICENSE | 20 + bash-5.1/vendor/nom/src/bits.rs | 394 ++ bash-5.1/vendor/nom/src/branch.rs | 871 +++ bash-5.1/vendor/nom/src/bytes.rs | 1119 +++ bash-5.1/vendor/nom/src/character.rs | 143 + bash-5.1/vendor/nom/src/internal.rs | 515 ++ bash-5.1/vendor/nom/src/lib.rs | 491 ++ bash-5.1/vendor/nom/src/macros.rs | 1342 ++++ bash-5.1/vendor/nom/src/methods.rs | 500 ++ bash-5.1/vendor/nom/src/multi.rs | 1614 +++++ bash-5.1/vendor/nom/src/nom.rs | 1225 ++++ bash-5.1/vendor/nom/src/regexp.rs | 683 ++ bash-5.1/vendor/nom/src/sequence.rs | 889 +++ bash-5.1/vendor/nom/src/simple_errors.rs | 153 + bash-5.1/vendor/nom/src/str.rs | 658 ++ bash-5.1/vendor/nom/src/stream.rs | 1062 +++ bash-5.1/vendor/nom/src/traits.rs | 623 ++ bash-5.1/vendor/nom/src/util.rs | 738 ++ bash-5.1/vendor/nom/src/verbose_errors.rs | 227 + bash-5.1/vendor/nom/src/whitespace.rs | 1056 +++ bash-5.1/vendor/nom/tests/arithmetic.rs | 87 + bash-5.1/vendor/nom/tests/arithmetic_ast.rs | 137 + .../vendor/nom/tests/blockbuf-arithmetic.rs | 321 + .../nom/tests/cross_function_backtracking.rs | 147 + bash-5.1/vendor/nom/tests/float.rs | 46 + bash-5.1/vendor/nom/tests/ini.rs | 219 + bash-5.1/vendor/nom/tests/ini_str.rs | 240 + bash-5.1/vendor/nom/tests/issues.rs | 157 + bash-5.1/vendor/nom/tests/json.rs | 130 + bash-5.1/vendor/nom/tests/mp4.rs | 528 ++ bash-5.1/vendor/nom/tests/multiline.rs | 21 + bash-5.1/vendor/nom/tests/named_args.rs | 108 + bash-5.1/vendor/nom/tests/omnom.rs | 160 + bash-5.1/vendor/nom/tests/overflow.rs | 99 + bash-5.1/vendor/nom/tests/reborrow_fold.rs | 16 + bash-5.1/vendor/nom/tests/test1.rs | 44 + .../num-traits-0.1.43/.cargo-checksum.json | 1 + bash-5.1/vendor/num-traits-0.1.43/Cargo.toml | 29 + .../vendor/num-traits-0.1.43/LICENSE-APACHE | 201 + bash-5.1/vendor/num-traits-0.1.43/LICENSE-MIT | 25 + bash-5.1/vendor/num-traits-0.1.43/README.md | 33 + bash-5.1/vendor/num-traits-0.1.43/RELEASES.md | 41 + bash-5.1/vendor/num-traits-0.1.43/bors.toml | 3 + .../vendor/num-traits-0.1.43/ci/rustup.sh | 12 + .../vendor/num-traits-0.1.43/ci/test_full.sh | 11 + bash-5.1/vendor/num-traits-0.1.43/src/lib.rs | 88 + .../vendor/num-traits/.cargo-checksum.json | 1 + bash-5.1/vendor/num-traits/Cargo.toml | 51 + bash-5.1/vendor/num-traits/LICENSE-APACHE | 201 + bash-5.1/vendor/num-traits/LICENSE-MIT | 25 + bash-5.1/vendor/num-traits/README.md | 63 + bash-5.1/vendor/num-traits/RELEASES.md | 259 + bash-5.1/vendor/num-traits/build.rs | 29 + bash-5.1/vendor/num-traits/src/bounds.rs | 153 + bash-5.1/vendor/num-traits/src/cast.rs | 814 +++ bash-5.1/vendor/num-traits/src/float.rs | 2351 +++++++ bash-5.1/vendor/num-traits/src/identities.rs | 206 + bash-5.1/vendor/num-traits/src/int.rs | 568 ++ bash-5.1/vendor/num-traits/src/lib.rs | 640 ++ bash-5.1/vendor/num-traits/src/macros.rs | 44 + bash-5.1/vendor/num-traits/src/ops/checked.rs | 277 + bash-5.1/vendor/num-traits/src/ops/euclid.rs | 347 + bash-5.1/vendor/num-traits/src/ops/inv.rs | 47 + bash-5.1/vendor/num-traits/src/ops/mod.rs | 7 + bash-5.1/vendor/num-traits/src/ops/mul_add.rs | 151 + .../vendor/num-traits/src/ops/overflowing.rs | 104 + .../vendor/num-traits/src/ops/saturating.rs | 137 + .../vendor/num-traits/src/ops/wrapping.rs | 337 + bash-5.1/vendor/num-traits/src/pow.rs | 262 + bash-5.1/vendor/num-traits/src/real.rs | 834 +++ bash-5.1/vendor/num-traits/src/sign.rs | 224 + bash-5.1/vendor/num-traits/tests/cast.rs | 397 ++ .../vendor/once_cell/.cargo-checksum.json | 2 +- bash-5.1/vendor/once_cell/CHANGELOG.md | 12 + bash-5.1/vendor/once_cell/Cargo.toml | 6 +- .../vendor/once_cell/examples/lazy_static.rs | 2 +- bash-5.1/vendor/once_cell/src/imp_cs.rs | 78 + bash-5.1/vendor/once_cell/src/lib.rs | 80 +- bash-5.1/vendor/once_cell/tests/it.rs | 35 + bash-5.1/vendor/phf/.cargo-checksum.json | 1 + bash-5.1/vendor/phf/Cargo.toml | 35 + bash-5.1/vendor/phf/src/lib.rs | 92 + bash-5.1/vendor/phf/src/map.rs | 198 + bash-5.1/vendor/phf/src/ordered_map.rs | 228 + bash-5.1/vendor/phf/src/ordered_set.rs | 137 + bash-5.1/vendor/phf/src/set.rs | 115 + .../vendor/phf_codegen/.cargo-checksum.json | 1 + bash-5.1/vendor/phf_codegen/Cargo.toml | 24 + bash-5.1/vendor/phf_codegen/src/lib.rs | 341 + .../vendor/phf_generator/.cargo-checksum.json | 1 + bash-5.1/vendor/phf_generator/Cargo.toml | 24 + bash-5.1/vendor/phf_generator/src/lib.rs | 124 + .../vendor/phf_shared/.cargo-checksum.json | 1 + bash-5.1/vendor/phf_shared/Cargo.toml | 33 + bash-5.1/vendor/phf_shared/src/lib.rs | 200 + .../vendor/proc-macro2/.cargo-checksum.json | 2 +- bash-5.1/vendor/proc-macro2/Cargo.toml | 2 +- bash-5.1/vendor/proc-macro2/build.rs | 5 +- bash-5.1/vendor/proc-macro2/src/fallback.rs | 28 +- bash-5.1/vendor/proc-macro2/src/lib.rs | 25 +- bash-5.1/vendor/proc-macro2/src/location.rs | 29 + bash-5.1/vendor/proc-macro2/src/parse.rs | 9 +- bash-5.1/vendor/proc-macro2/src/wrapper.rs | 16 + bash-5.1/vendor/proc-macro2/tests/test.rs | 13 + bash-5.1/vendor/quasi/.cargo-checksum.json | 1 + bash-5.1/vendor/quasi/Cargo.toml | 17 + bash-5.1/vendor/quasi/src/lib.rs | 592 ++ .../vendor/quasi_codegen/.cargo-checksum.json | 1 + bash-5.1/vendor/quasi_codegen/Cargo.toml | 20 + bash-5.1/vendor/quasi_codegen/src/lib.rs | 858 +++ bash-5.1/vendor/rand/.cargo-checksum.json | 1 + bash-5.1/vendor/rand/CHANGELOG.md | 522 ++ bash-5.1/vendor/rand/COPYRIGHT | 12 + bash-5.1/vendor/rand/Cargo.toml | 90 + bash-5.1/vendor/rand/LICENSE-APACHE | 201 + bash-5.1/vendor/rand/LICENSE-MIT | 26 + bash-5.1/vendor/rand/README.md | 122 + bash-5.1/vendor/rand/benches/distributions.rs | 259 + bash-5.1/vendor/rand/benches/generators.rs | 240 + bash-5.1/vendor/rand/benches/misc.rs | 160 + bash-5.1/vendor/rand/benches/seq.rs | 174 + bash-5.1/vendor/rand/build.rs | 10 + bash-5.1/vendor/rand/examples/monte-carlo.rs | 51 + bash-5.1/vendor/rand/examples/monty-hall.rs | 116 + bash-5.1/vendor/rand/src/deprecated.rs | 544 ++ .../rand/src/distributions/bernoulli.rs | 165 + .../vendor/rand/src/distributions/binomial.rs | 177 + .../vendor/rand/src/distributions/cauchy.rs | 115 + .../rand/src/distributions/dirichlet.rs | 137 + .../rand/src/distributions/exponential.rs | 124 + .../vendor/rand/src/distributions/float.rs | 259 + .../vendor/rand/src/distributions/gamma.rs | 413 ++ .../vendor/rand/src/distributions/integer.rs | 161 + bash-5.1/vendor/rand/src/distributions/mod.rs | 608 ++ .../vendor/rand/src/distributions/normal.rs | 197 + .../vendor/rand/src/distributions/other.rs | 219 + .../vendor/rand/src/distributions/pareto.rs | 74 + .../vendor/rand/src/distributions/poisson.rs | 157 + .../rand/src/distributions/triangular.rs | 86 + .../vendor/rand/src/distributions/uniform.rs | 1283 ++++ .../rand/src/distributions/unit_circle.rs | 101 + .../rand/src/distributions/unit_sphere.rs | 99 + .../vendor/rand/src/distributions/utils.rs | 504 ++ .../vendor/rand/src/distributions/weibull.rs | 71 + .../vendor/rand/src/distributions/weighted.rs | 230 + .../rand/src/distributions/ziggurat_tables.rs | 279 + bash-5.1/vendor/rand/src/lib.rs | 830 +++ bash-5.1/vendor/rand/src/prelude.rs | 27 + bash-5.1/vendor/rand/src/prng/mod.rs | 37 + bash-5.1/vendor/rand/src/rngs/adapter/mod.rs | 15 + bash-5.1/vendor/rand/src/rngs/adapter/read.rs | 136 + .../vendor/rand/src/rngs/adapter/reseeding.rs | 370 + bash-5.1/vendor/rand/src/rngs/entropy.rs | 248 + bash-5.1/vendor/rand/src/rngs/mock.rs | 59 + bash-5.1/vendor/rand/src/rngs/mod.rs | 167 + bash-5.1/vendor/rand/src/rngs/small.rs | 106 + bash-5.1/vendor/rand/src/rngs/std.rs | 85 + bash-5.1/vendor/rand/src/rngs/thread.rs | 137 + bash-5.1/vendor/rand/src/seq/index.rs | 378 + bash-5.1/vendor/rand/src/seq/mod.rs | 829 +++ bash-5.1/vendor/rand/tests/uniformity.rs | 67 + .../vendor/rand_chacha/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_chacha/CHANGELOG.md | 12 + bash-5.1/vendor/rand_chacha/COPYRIGHT | 12 + bash-5.1/vendor/rand_chacha/Cargo.toml | 35 + bash-5.1/vendor/rand_chacha/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_chacha/LICENSE-MIT | 26 + bash-5.1/vendor/rand_chacha/README.md | 45 + bash-5.1/vendor/rand_chacha/build.rs | 7 + bash-5.1/vendor/rand_chacha/src/chacha.rs | 449 ++ bash-5.1/vendor/rand_chacha/src/lib.rs | 25 + .../rand_core-0.3.1/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_core-0.3.1/CHANGELOG.md | 36 + bash-5.1/vendor/rand_core-0.3.1/COPYRIGHT | 12 + bash-5.1/vendor/rand_core-0.3.1/Cargo.toml | 37 + .../vendor/rand_core-0.3.1/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_core-0.3.1/LICENSE-MIT | 26 + bash-5.1/vendor/rand_core-0.3.1/README.md | 65 + bash-5.1/vendor/rand_core-0.3.1/src/block.rs | 499 ++ bash-5.1/vendor/rand_core-0.3.1/src/error.rs | 177 + bash-5.1/vendor/rand_core-0.3.1/src/impls.rs | 165 + bash-5.1/vendor/rand_core-0.3.1/src/le.rs | 68 + bash-5.1/vendor/rand_core-0.3.1/src/lib.rs | 46 + .../vendor/rand_core/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_core/CHANGELOG.md | 41 + bash-5.1/vendor/rand_core/COPYRIGHT | 12 + bash-5.1/vendor/rand_core/Cargo.toml | 41 + bash-5.1/vendor/rand_core/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_core/LICENSE-MIT | 26 + bash-5.1/vendor/rand_core/README.md | 77 + bash-5.1/vendor/rand_core/src/block.rs | 433 ++ bash-5.1/vendor/rand_core/src/error.rs | 177 + bash-5.1/vendor/rand_core/src/impls.rs | 165 + bash-5.1/vendor/rand_core/src/le.rs | 68 + bash-5.1/vendor/rand_core/src/lib.rs | 477 ++ bash-5.1/vendor/rand_hc/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_hc/CHANGELOG.md | 8 + bash-5.1/vendor/rand_hc/COPYRIGHT | 12 + bash-5.1/vendor/rand_hc/Cargo.toml | 32 + bash-5.1/vendor/rand_hc/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_hc/LICENSE-MIT | 25 + bash-5.1/vendor/rand_hc/README.md | 44 + bash-5.1/vendor/rand_hc/src/hc128.rs | 462 ++ bash-5.1/vendor/rand_hc/src/lib.rs | 25 + .../vendor/rand_isaac/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_isaac/CHANGELOG.md | 12 + bash-5.1/vendor/rand_isaac/COPYRIGHT | 12 + bash-5.1/vendor/rand_isaac/Cargo.toml | 45 + bash-5.1/vendor/rand_isaac/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_isaac/LICENSE-MIT | 26 + bash-5.1/vendor/rand_isaac/README.md | 47 + bash-5.1/vendor/rand_isaac/src/isaac.rs | 484 ++ bash-5.1/vendor/rand_isaac/src/isaac64.rs | 481 ++ bash-5.1/vendor/rand_isaac/src/isaac_array.rs | 136 + bash-5.1/vendor/rand_isaac/src/lib.rs | 36 + .../vendor/rand_jitter/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_jitter/CHANGELOG.md | 21 + bash-5.1/vendor/rand_jitter/COPYRIGHT | 12 + bash-5.1/vendor/rand_jitter/Cargo.toml | 42 + bash-5.1/vendor/rand_jitter/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_jitter/LICENSE-MIT | 26 + bash-5.1/vendor/rand_jitter/README.md | 104 + bash-5.1/vendor/rand_jitter/benches/mod.rs | 18 + bash-5.1/vendor/rand_jitter/src/dummy_log.rs | 10 + bash-5.1/vendor/rand_jitter/src/error.rs | 70 + bash-5.1/vendor/rand_jitter/src/lib.rs | 718 ++ bash-5.1/vendor/rand_jitter/src/platform.rs | 44 + bash-5.1/vendor/rand_jitter/tests/mod.rs | 31 + bash-5.1/vendor/rand_os/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_os/CHANGELOG.md | 22 + bash-5.1/vendor/rand_os/COPYRIGHT | 12 + bash-5.1/vendor/rand_os/Cargo.toml | 53 + bash-5.1/vendor/rand_os/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_os/LICENSE-MIT | 26 + bash-5.1/vendor/rand_os/README.md | 33 + bash-5.1/vendor/rand_os/src/cloudabi.rs | 39 + .../rand_os/src/dragonfly_haiku_emscripten.rs | 39 + bash-5.1/vendor/rand_os/src/dummy_log.rs | 10 + bash-5.1/vendor/rand_os/src/freebsd.rs | 45 + bash-5.1/vendor/rand_os/src/fuchsia.rs | 28 + bash-5.1/vendor/rand_os/src/lib.rs | 440 ++ bash-5.1/vendor/rand_os/src/linux_android.rs | 186 + bash-5.1/vendor/rand_os/src/macos.rs | 53 + bash-5.1/vendor/rand_os/src/netbsd.rs | 57 + bash-5.1/vendor/rand_os/src/openbsd_bitrig.rs | 40 + bash-5.1/vendor/rand_os/src/random_device.rs | 70 + bash-5.1/vendor/rand_os/src/redox.rs | 30 + bash-5.1/vendor/rand_os/src/sgx.rs | 38 + bash-5.1/vendor/rand_os/src/solarish.rs | 195 + bash-5.1/vendor/rand_os/src/wasm32_bindgen.rs | 92 + bash-5.1/vendor/rand_os/src/wasm32_stdweb.rs | 107 + bash-5.1/vendor/rand_os/src/windows.rs | 44 + bash-5.1/vendor/rand_os/tests/mod.rs | 80 + bash-5.1/vendor/rand_pcg/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_pcg/CHANGELOG.md | 19 + bash-5.1/vendor/rand_pcg/COPYRIGHT | 12 + bash-5.1/vendor/rand_pcg/Cargo.toml | 47 + bash-5.1/vendor/rand_pcg/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_pcg/LICENSE-MIT | 26 + bash-5.1/vendor/rand_pcg/README.md | 43 + bash-5.1/vendor/rand_pcg/build.rs | 7 + bash-5.1/vendor/rand_pcg/src/lib.rs | 48 + bash-5.1/vendor/rand_pcg/src/pcg128.rs | 122 + bash-5.1/vendor/rand_pcg/src/pcg64.rs | 141 + bash-5.1/vendor/rand_pcg/tests/lcg64xsh32.rs | 58 + bash-5.1/vendor/rand_pcg/tests/mcg128xsl64.rs | 59 + .../vendor/rand_xorshift/.cargo-checksum.json | 1 + bash-5.1/vendor/rand_xorshift/CHANGELOG.md | 11 + bash-5.1/vendor/rand_xorshift/COPYRIGHT | 12 + bash-5.1/vendor/rand_xorshift/Cargo.toml | 45 + bash-5.1/vendor/rand_xorshift/LICENSE-APACHE | 201 + bash-5.1/vendor/rand_xorshift/LICENSE-MIT | 26 + bash-5.1/vendor/rand_xorshift/README.md | 45 + bash-5.1/vendor/rand_xorshift/src/lib.rs | 123 + bash-5.1/vendor/rand_xorshift/tests/mod.rs | 92 + bash-5.1/vendor/rdrand/.cargo-checksum.json | 1 + bash-5.1/vendor/rdrand/Cargo.toml | 28 + bash-5.1/vendor/rdrand/LICENSE | 12 + bash-5.1/vendor/rdrand/README.mkd | 8 + bash-5.1/vendor/rdrand/appveyor.yml | 27 + bash-5.1/vendor/rdrand/benches/rdrand.rs | 49 + bash-5.1/vendor/rdrand/benches/rdseed.rs | 49 + bash-5.1/vendor/rdrand/benches/std.rs | 31 + bash-5.1/vendor/rdrand/src/changelog.rs | 25 + bash-5.1/vendor/rdrand/src/lib.rs | 472 ++ .../vendor/regex-syntax/.cargo-checksum.json | 1 + bash-5.1/vendor/regex-syntax/Cargo.toml | 23 + bash-5.1/vendor/regex-syntax/LICENSE-APACHE | 201 + bash-5.1/vendor/regex-syntax/LICENSE-MIT | 25 + bash-5.1/vendor/regex-syntax/benches/bench.rs | 73 + bash-5.1/vendor/regex-syntax/src/ast/mod.rs | 1515 ++++ bash-5.1/vendor/regex-syntax/src/ast/parse.rs | 5365 ++++++++++++++ bash-5.1/vendor/regex-syntax/src/ast/print.rs | 586 ++ .../vendor/regex-syntax/src/ast/visitor.rs | 557 ++ bash-5.1/vendor/regex-syntax/src/either.rs | 8 + bash-5.1/vendor/regex-syntax/src/error.rs | 297 + .../vendor/regex-syntax/src/hir/interval.rs | 490 ++ .../regex-syntax/src/hir/literal/mod.rs | 1553 +++++ bash-5.1/vendor/regex-syntax/src/hir/mod.rs | 2055 ++++++ bash-5.1/vendor/regex-syntax/src/hir/print.rs | 359 + .../vendor/regex-syntax/src/hir/translate.rs | 2537 +++++++ .../vendor/regex-syntax/src/hir/visitor.rs | 222 + bash-5.1/vendor/regex-syntax/src/lib.rs | 222 + bash-5.1/vendor/regex-syntax/src/parser.rs | 206 + bash-5.1/vendor/regex-syntax/src/unicode.rs | 472 ++ .../regex-syntax/src/unicode_tables/age.rs | 424 ++ .../src/unicode_tables/case_folding_simple.rs | 662 ++ .../src/unicode_tables/general_category.rs | 1844 +++++ .../regex-syntax/src/unicode_tables/mod.rs | 9 + .../src/unicode_tables/perl_word.rs | 179 + .../src/unicode_tables/property_bool.rs | 2576 +++++++ .../src/unicode_tables/property_names.rs | 145 + .../src/unicode_tables/property_values.rs | 277 + .../regex-syntax/src/unicode_tables/script.rs | 765 ++ .../src/unicode_tables/script_extension.rs | 785 +++ bash-5.1/vendor/regex/.cargo-checksum.json | 1 + bash-5.1/vendor/regex/CHANGELOG.md | 445 ++ bash-5.1/vendor/regex/Cargo.toml | 100 + bash-5.1/vendor/regex/HACKING.md | 330 + bash-5.1/vendor/regex/LICENSE-APACHE | 201 + bash-5.1/vendor/regex/LICENSE-MIT | 25 + bash-5.1/vendor/regex/PERFORMANCE.md | 279 + bash-5.1/vendor/regex/README.md | 222 + bash-5.1/vendor/regex/UNICODE.md | 250 + bash-5.1/vendor/regex/appveyor.yml | 19 + bash-5.1/vendor/regex/build.rs | 27 + bash-5.1/vendor/regex/ci/after_success.sh | 25 + bash-5.1/vendor/regex/ci/run-kcov | 44 + bash-5.1/vendor/regex/ci/run-shootout-test | 18 + bash-5.1/vendor/regex/ci/script.sh | 46 + .../vendor/regex/examples/regexdna-input.txt | 1671 +++++ .../vendor/regex/examples/regexdna-output.txt | 13 + .../examples/shootout-regex-dna-bytes.rs | 66 + .../examples/shootout-regex-dna-cheat.rs | 88 + .../examples/shootout-regex-dna-replace.rs | 19 + .../shootout-regex-dna-single-cheat.rs | 73 + .../examples/shootout-regex-dna-single.rs | 55 + .../regex/examples/shootout-regex-dna.rs | 66 + bash-5.1/vendor/regex/scripts/frequencies.py | 82 + .../vendor/regex/scripts/regex-match-tests.py | 107 + bash-5.1/vendor/regex/src/backtrack.rs | 302 + bash-5.1/vendor/regex/src/compile.rs | 1151 +++ bash-5.1/vendor/regex/src/dfa.rs | 1894 +++++ bash-5.1/vendor/regex/src/error.rs | 92 + bash-5.1/vendor/regex/src/exec.rs | 1352 ++++ bash-5.1/vendor/regex/src/expand.rs | 215 + bash-5.1/vendor/regex/src/freqs.rs | 271 + bash-5.1/vendor/regex/src/input.rs | 420 ++ bash-5.1/vendor/regex/src/lib.rs | 672 ++ bash-5.1/vendor/regex/src/literal/mod.rs | 1141 +++ .../regex/src/literal/teddy_avx2/fallback.rs | 20 + .../regex/src/literal/teddy_avx2/imp.rs | 468 ++ .../regex/src/literal/teddy_avx2/mod.rs | 16 + .../regex/src/literal/teddy_ssse3/fallback.rs | 20 + .../regex/src/literal/teddy_ssse3/imp.rs | 776 +++ .../regex/src/literal/teddy_ssse3/mod.rs | 16 + bash-5.1/vendor/regex/src/pattern.rs | 62 + bash-5.1/vendor/regex/src/pikevm.rs | 377 + bash-5.1/vendor/regex/src/prog.rs | 425 ++ bash-5.1/vendor/regex/src/re_builder.rs | 346 + bash-5.1/vendor/regex/src/re_bytes.rs | 1072 +++ bash-5.1/vendor/regex/src/re_set.rs | 423 ++ bash-5.1/vendor/regex/src/re_trait.rs | 268 + bash-5.1/vendor/regex/src/re_unicode.rs | 1116 +++ bash-5.1/vendor/regex/src/sparse.rs | 78 + bash-5.1/vendor/regex/src/testdata/LICENSE | 19 + bash-5.1/vendor/regex/src/testdata/README | 17 + bash-5.1/vendor/regex/src/testdata/basic.dat | 221 + .../vendor/regex/src/testdata/nullsubexpr.dat | 79 + .../vendor/regex/src/testdata/repetition.dat | 163 + bash-5.1/vendor/regex/src/utf8.rs | 290 + bash-5.1/vendor/regex/src/vector/avx2.rs | 195 + bash-5.1/vendor/regex/src/vector/mod.rs | 4 + bash-5.1/vendor/regex/src/vector/ssse3.rs | 200 + bash-5.1/vendor/regex/tests/api.rs | 182 + bash-5.1/vendor/regex/tests/api_str.rs | 31 + bash-5.1/vendor/regex/tests/bytes.rs | 62 + bash-5.1/vendor/regex/tests/crazy.rs | 401 ++ bash-5.1/vendor/regex/tests/flags.rs | 11 + bash-5.1/vendor/regex/tests/fowler.rs | 371 + bash-5.1/vendor/regex/tests/macros.rs | 149 + bash-5.1/vendor/regex/tests/macros_bytes.rs | 38 + bash-5.1/vendor/regex/tests/macros_str.rs | 35 + bash-5.1/vendor/regex/tests/misc.rs | 14 + bash-5.1/vendor/regex/tests/multiline.rs | 49 + bash-5.1/vendor/regex/tests/noparse.rs | 50 + bash-5.1/vendor/regex/tests/regression.rs | 99 + bash-5.1/vendor/regex/tests/replace.rs | 44 + bash-5.1/vendor/regex/tests/searcher.rs | 66 + bash-5.1/vendor/regex/tests/set.rs | 32 + bash-5.1/vendor/regex/tests/shortest_match.rs | 14 + bash-5.1/vendor/regex/tests/suffix_reverse.rs | 16 + bash-5.1/vendor/regex/tests/test_backtrack.rs | 64 + .../regex/tests/test_backtrack_bytes.rs | 65 + .../regex/tests/test_backtrack_utf8bytes.rs | 65 + bash-5.1/vendor/regex/tests/test_default.rs | 77 + .../vendor/regex/tests/test_default_bytes.rs | 73 + bash-5.1/vendor/regex/tests/test_nfa.rs | 60 + bash-5.1/vendor/regex/tests/test_nfa_bytes.rs | 65 + .../vendor/regex/tests/test_nfa_utf8bytes.rs | 61 + bash-5.1/vendor/regex/tests/unicode.rs | 110 + bash-5.1/vendor/regex/tests/word_boundary.rs | 89 + .../vendor/regex/tests/word_boundary_ascii.rs | 9 + .../regex/tests/word_boundary_unicode.rs | 8 + .../rustc-serialize/.cargo-checksum.json | 1 + bash-5.1/vendor/rustc-serialize/Cargo.toml | 18 + .../vendor/rustc-serialize/LICENSE-APACHE | 201 + bash-5.1/vendor/rustc-serialize/LICENSE-MIT | 25 + bash-5.1/vendor/rustc-serialize/README.md | 31 + bash-5.1/vendor/rustc-serialize/appveyor.yml | 17 + .../vendor/rustc-serialize/benches/base64.rs | 48 + .../vendor/rustc-serialize/benches/hex.rs | 28 + .../vendor/rustc-serialize/benches/json.rs | 84 + bash-5.1/vendor/rustc-serialize/src/base64.rs | 489 ++ .../rustc-serialize/src/collection_impls.rs | 186 + bash-5.1/vendor/rustc-serialize/src/hex.rs | 221 + bash-5.1/vendor/rustc-serialize/src/json.rs | 3999 +++++++++++ bash-5.1/vendor/rustc-serialize/src/lib.rs | 79 + .../vendor/rustc-serialize/src/serialize.rs | 1671 +++++ bash-5.1/vendor/serde/.cargo-checksum.json | 1 + bash-5.1/vendor/serde/Cargo.toml | 35 + bash-5.1/vendor/serde/LICENSE-APACHE | 201 + bash-5.1/vendor/serde/LICENSE-MIT | 25 + bash-5.1/vendor/serde/README.md | 76 + bash-5.1/vendor/serde/src/bytes.rs | 315 + bash-5.1/vendor/serde/src/de/content.rs | 1338 ++++ .../vendor/serde/src/de/from_primitive.rs | 409 ++ bash-5.1/vendor/serde/src/de/impls.rs | 1635 +++++ bash-5.1/vendor/serde/src/de/mod.rs | 1535 ++++ bash-5.1/vendor/serde/src/de/private.rs | 44 + bash-5.1/vendor/serde/src/de/value.rs | 1107 +++ bash-5.1/vendor/serde/src/error.rs | 17 + bash-5.1/vendor/serde/src/export.rs | 36 + bash-5.1/vendor/serde/src/iter.rs | 73 + bash-5.1/vendor/serde/src/lib.rs | 155 + bash-5.1/vendor/serde/src/macros.rs | 207 + bash-5.1/vendor/serde/src/ser/content.rs | 607 ++ bash-5.1/vendor/serde/src/ser/impls.rs | 818 +++ bash-5.1/vendor/serde/src/ser/impossible.rs | 156 + bash-5.1/vendor/serde/src/ser/mod.rs | 919 +++ bash-5.1/vendor/serde/src/ser/private.rs | 315 + bash-5.1/vendor/serde/src/utils.rs | 74 + .../vendor/serde_json/.cargo-checksum.json | 1 + bash-5.1/vendor/serde_json/Cargo.toml | 28 + bash-5.1/vendor/serde_json/LICENSE-APACHE | 201 + bash-5.1/vendor/serde_json/LICENSE-MIT | 25 + bash-5.1/vendor/serde_json/README.md | 252 + bash-5.1/vendor/serde_json/src/de.rs | 1091 +++ bash-5.1/vendor/serde_json/src/error.rs | 373 + bash-5.1/vendor/serde_json/src/lib.rs | 291 + bash-5.1/vendor/serde_json/src/macros.rs | 271 + bash-5.1/vendor/serde_json/src/map.rs | 775 +++ bash-5.1/vendor/serde_json/src/number.rs | 235 + bash-5.1/vendor/serde_json/src/read.rs | 624 ++ bash-5.1/vendor/serde_json/src/ser.rs | 1411 ++++ bash-5.1/vendor/serde_json/src/value.rs | 2267 ++++++ .../vendor/siphasher/.cargo-checksum.json | 1 + bash-5.1/vendor/siphasher/COPYING | 6 + bash-5.1/vendor/siphasher/Cargo.toml | 30 + bash-5.1/vendor/siphasher/README.md | 37 + bash-5.1/vendor/siphasher/src/lib.rs | 13 + bash-5.1/vendor/siphasher/src/sip.rs | 411 ++ bash-5.1/vendor/siphasher/src/sip128.rs | 482 ++ bash-5.1/vendor/siphasher/src/tests.rs | 322 + bash-5.1/vendor/siphasher/src/tests128.rs | 116 + bash-5.1/vendor/slab/src/builder.rs | 63 + bash-5.1/vendor/smallvec/.cargo-checksum.json | 2 +- bash-5.1/vendor/smallvec/Cargo.toml | 31 +- .../vendor/smallvec/debug_metadata/README.md | 111 + .../smallvec/debug_metadata/smallvec.natvis | 35 + bash-5.1/vendor/smallvec/scripts/run_miri.sh | 3 + bash-5.1/vendor/smallvec/src/lib.rs | 7 + .../smallvec/tests/debugger_visualizer.rs | 68 + .../static_assertions/.cargo-checksum.json | 1 + .../vendor/static_assertions/CHANGELOG.md | 181 + bash-5.1/vendor/static_assertions/Cargo.toml | 39 + .../vendor/static_assertions/LICENSE-APACHE | 202 + bash-5.1/vendor/static_assertions/LICENSE-MIT | 21 + bash-5.1/vendor/static_assertions/README.md | 188 + .../static_assertions/src/assert_cfg.rs | 49 + .../static_assertions/src/assert_eq_align.rs | 45 + .../static_assertions/src/assert_eq_size.rs | 123 + .../static_assertions/src/assert_fields.rs | 72 + .../static_assertions/src/assert_impl.rs | 356 + .../static_assertions/src/assert_obj_safe.rs | 76 + .../static_assertions/src/assert_trait.rs | 105 + .../static_assertions/src/assert_type.rs | 101 + .../static_assertions/src/const_assert.rs | 109 + bash-5.1/vendor/static_assertions/src/lib.rs | 97 + bash-5.1/vendor/strsim/.cargo-checksum.json | 1 + bash-5.1/vendor/strsim/CHANGELOG.md | 123 + bash-5.1/vendor/strsim/Cargo.toml | 28 + bash-5.1/vendor/strsim/LICENSE | 23 + bash-5.1/vendor/strsim/README.md | 69 + bash-5.1/vendor/strsim/appveyor.yml | 13 + bash-5.1/vendor/strsim/benches/benches.rs | 84 + bash-5.1/vendor/strsim/dev | 41 + bash-5.1/vendor/strsim/src/lib.rs | 786 +++ bash-5.1/vendor/strsim/tests/lib.rs | 49 + bash-5.1/vendor/syn/.cargo-checksum.json | 2 +- bash-5.1/vendor/syn/Cargo.toml | 4 +- bash-5.1/vendor/syn/benches/file.rs | 2 +- bash-5.1/vendor/syn/benches/rust.rs | 11 +- bash-5.1/vendor/syn/src/buffer.rs | 215 +- bash-5.1/vendor/syn/src/drops.rs | 58 + bash-5.1/vendor/syn/src/expr.rs | 21 +- bash-5.1/vendor/syn/src/gen/clone.rs | 2 +- bash-5.1/vendor/syn/src/gen/debug.rs | 10 +- bash-5.1/vendor/syn/src/gen/eq.rs | 6 +- bash-5.1/vendor/syn/src/gen/fold.rs | 6 +- bash-5.1/vendor/syn/src/gen/hash.rs | 6 +- bash-5.1/vendor/syn/src/gen/visit.rs | 6 +- bash-5.1/vendor/syn/src/gen/visit_mut.rs | 6 +- bash-5.1/vendor/syn/src/item.rs | 14 +- bash-5.1/vendor/syn/src/lib.rs | 11 +- bash-5.1/vendor/syn/src/lit.rs | 2 +- bash-5.1/vendor/syn/src/parse_macro_input.rs | 4 +- bash-5.1/vendor/syn/src/pat.rs | 35 +- bash-5.1/vendor/syn/src/path.rs | 46 +- bash-5.1/vendor/syn/src/stmt.rs | 6 +- bash-5.1/vendor/syn/src/ty.rs | 53 +- bash-5.1/vendor/syn/tests/common/eq.rs | 64 +- .../vendor/syn/tests/regression/issue1108.rs | 2 +- .../vendor/syn/tests/regression/issue1235.rs | 32 + bash-5.1/vendor/syn/tests/repo/mod.rs | 77 +- .../vendor/syn/tests/test_parse_stream.rs | 8 +- bash-5.1/vendor/syn/tests/test_precedence.rs | 19 +- bash-5.1/vendor/syn/tests/test_size.rs | 8 +- bash-5.1/vendor/syntex/.cargo-checksum.json | 1 + bash-5.1/vendor/syntex/Cargo.toml | 13 + bash-5.1/vendor/syntex/src/error.rs | 46 + bash-5.1/vendor/syntex/src/lib.rs | 11 + bash-5.1/vendor/syntex/src/registry.rs | 234 + bash-5.1/vendor/syntex/src/resolver.rs | 92 + bash-5.1/vendor/syntex/src/stack.rs | 63 + .../vendor/syntex_errors/.cargo-checksum.json | 1 + bash-5.1/vendor/syntex_errors/Cargo.toml | 16 + .../vendor/syntex_errors/src/diagnostic.rs | 202 + .../syntex_errors/src/diagnostic_builder.rs | 196 + bash-5.1/vendor/syntex_errors/src/emitter.rs | 1219 ++++ bash-5.1/vendor/syntex_errors/src/lib.rs | 533 ++ bash-5.1/vendor/syntex_errors/src/lock.rs | 115 + bash-5.1/vendor/syntex_errors/src/registry.rs | 26 + bash-5.1/vendor/syntex_errors/src/snippet.rs | 188 + .../vendor/syntex_errors/src/styled_buffer.rs | 145 + .../vendor/syntex_pos/.cargo-checksum.json | 1 + bash-5.1/vendor/syntex_pos/Cargo.toml | 11 + bash-5.1/vendor/syntex_pos/src/lib.rs | 725 ++ .../vendor/syntex_syntax/.cargo-checksum.json | 1 + bash-5.1/vendor/syntex_syntax/Cargo.toml | 18 + bash-5.1/vendor/syntex_syntax/src/abi.rs | 178 + bash-5.1/vendor/syntex_syntax/src/ast.rs | 1924 +++++ bash-5.1/vendor/syntex_syntax/src/attr.rs | 1037 +++ bash-5.1/vendor/syntex_syntax/src/codemap.rs | 1278 ++++ bash-5.1/vendor/syntex_syntax/src/config.rs | 312 + .../syntex_syntax/src/diagnostic_list.rs | 205 + .../syntex_syntax/src/diagnostics/macros.rs | 138 + .../syntex_syntax/src/diagnostics/metadata.rs | 101 + .../syntex_syntax/src/diagnostics/plugin.rs | 241 + bash-5.1/vendor/syntex_syntax/src/entry.rs | 44 + bash-5.1/vendor/syntex_syntax/src/ext/base.rs | 849 +++ .../vendor/syntex_syntax/src/ext/build.rs | 1208 ++++ .../vendor/syntex_syntax/src/ext/decorator.rs | 316 + bash-5.1/vendor/syntex_syntax/src/ext/env.rs | 99 + .../vendor/syntex_syntax/src/ext/expand.rs | 1008 +++ .../vendor/syntex_syntax/src/ext/hygiene.rs | 134 + .../syntex_syntax/src/ext/placeholders.rs | 236 + .../syntex_syntax/src/ext/proc_macro_shim.rs | 72 + .../vendor/syntex_syntax/src/ext/quote.rs | 950 +++ .../syntex_syntax/src/ext/source_util.rs | 196 + .../syntex_syntax/src/ext/tt/macro_parser.rs | 547 ++ .../syntex_syntax/src/ext/tt/macro_rules.rs | 810 +++ .../syntex_syntax/src/ext/tt/transcribe.rs | 300 + .../vendor/syntex_syntax/src/feature_gate.rs | 1489 ++++ bash-5.1/vendor/syntex_syntax/src/fold.rs | 1399 ++++ bash-5.1/vendor/syntex_syntax/src/json.rs | 356 + bash-5.1/vendor/syntex_syntax/src/lib.rs | 135 + .../vendor/syntex_syntax/src/parse/attr.rs | 266 + .../syntex_syntax/src/parse/classify.rs | 56 + .../vendor/syntex_syntax/src/parse/common.rs | 36 + .../syntex_syntax/src/parse/lexer/comments.rs | 456 ++ .../syntex_syntax/src/parse/lexer/mod.rs | 1929 ++++++ .../src/parse/lexer/unicode_chars.rs | 253 + .../vendor/syntex_syntax/src/parse/mod.rs | 1006 +++ .../syntex_syntax/src/parse/obsolete.rs | 66 + .../vendor/syntex_syntax/src/parse/parser.rs | 6172 +++++++++++++++++ .../vendor/syntex_syntax/src/parse/token.rs | 334 + bash-5.1/vendor/syntex_syntax/src/print/pp.rs | 640 ++ .../vendor/syntex_syntax/src/print/pprust.rs | 3126 +++++++++ bash-5.1/vendor/syntex_syntax/src/ptr.rs | 217 + .../vendor/syntex_syntax/src/show_span.rs | 86 + .../vendor/syntex_syntax/src/std_inject.rs | 94 + bash-5.1/vendor/syntex_syntax/src/str.rs | 24 + bash-5.1/vendor/syntex_syntax/src/symbol.rs | 312 + bash-5.1/vendor/syntex_syntax/src/test.rs | 718 ++ .../vendor/syntex_syntax/src/test_snippet.rs | 546 ++ .../vendor/syntex_syntax/src/tokenstream.rs | 1128 +++ .../syntex_syntax/src/util/lev_distance.rs | 84 + .../vendor/syntex_syntax/src/util/move_map.rs | 77 + .../syntex_syntax/src/util/node_count.rs | 156 + .../vendor/syntex_syntax/src/util/parser.rs | 217 + .../syntex_syntax/src/util/parser_testing.rs | 172 + .../syntex_syntax/src/util/small_vector.rs | 329 + .../vendor/syntex_syntax/src/util/thin_vec.rs | 59 + bash-5.1/vendor/syntex_syntax/src/visit.rs | 812 +++ .../target_build_utils/.cargo-checksum.json | 1 + bash-5.1/vendor/target_build_utils/Cargo.toml | 20 + bash-5.1/vendor/target_build_utils/README.md | 62 + .../vendor/target_build_utils/appveyor.yml | 20 + bash-5.1/vendor/target_build_utils/build.rs | 111 + .../target_build_utils/src/changelog.rs | 46 + bash-5.1/vendor/target_build_utils/src/lib.rs | 568 ++ .../src/my-great-target.json | 10 + bash-5.1/vendor/term/.cargo-checksum.json | 1 + bash-5.1/vendor/term/Cargo.toml | 31 + bash-5.1/vendor/term/LICENSE-APACHE | 201 + bash-5.1/vendor/term/LICENSE-MIT | 25 + bash-5.1/vendor/term/README.md | 36 + bash-5.1/vendor/term/appveyor.yml | 17 + bash-5.1/vendor/term/rustfmt.toml | 3 + bash-5.1/vendor/term/scripts/id_rsa.enc | Bin 0 -> 1680 bytes .../vendor/term/scripts/travis-doc-upload.cfg | 3 + bash-5.1/vendor/term/src/lib.rs | 401 ++ bash-5.1/vendor/term/src/terminfo/mod.rs | 403 ++ bash-5.1/vendor/term/src/terminfo/parm.rs | 698 ++ .../term/src/terminfo/parser/compiled.rs | 199 + .../vendor/term/src/terminfo/parser/names.rs | 553 ++ bash-5.1/vendor/term/src/terminfo/searcher.rs | 91 + bash-5.1/vendor/term/src/win.rs | 301 + bash-5.1/vendor/term/tests/data/dumb | Bin 0 -> 308 bytes bash-5.1/vendor/term/tests/data/linux | Bin 0 -> 1780 bytes bash-5.1/vendor/term/tests/data/linux-16color | Bin 0 -> 1858 bytes bash-5.1/vendor/term/tests/data/linux-basic | Bin 0 -> 1664 bytes bash-5.1/vendor/term/tests/data/linux-c | Bin 0 -> 2120 bytes bash-5.1/vendor/term/tests/data/linux-c-nc | Bin 0 -> 1766 bytes bash-5.1/vendor/term/tests/data/linux-koi8 | Bin 0 -> 1808 bytes bash-5.1/vendor/term/tests/data/linux-koi8r | Bin 0 -> 1814 bytes bash-5.1/vendor/term/tests/data/linux-lat | Bin 0 -> 1822 bytes bash-5.1/vendor/term/tests/data/linux-m | Bin 0 -> 1770 bytes bash-5.1/vendor/term/tests/data/linux-nic | Bin 0 -> 1810 bytes bash-5.1/vendor/term/tests/data/linux-vt | Bin 0 -> 1702 bytes bash-5.1/vendor/term/tests/data/linux2.2 | Bin 0 -> 1788 bytes bash-5.1/vendor/term/tests/data/linux2.6 | Bin 0 -> 1785 bytes bash-5.1/vendor/term/tests/data/linux2.6.26 | Bin 0 -> 1789 bytes bash-5.1/vendor/term/tests/data/linux3.0 | Bin 0 -> 1788 bytes bash-5.1/vendor/term/tests/data/rxvt | Bin 0 -> 2285 bytes bash-5.1/vendor/term/tests/data/rxvt-16color | Bin 0 -> 2497 bytes bash-5.1/vendor/term/tests/data/rxvt-256color | Bin 0 -> 2427 bytes bash-5.1/vendor/term/tests/data/rxvt-88color | Bin 0 -> 2425 bytes bash-5.1/vendor/term/tests/data/rxvt-basic | Bin 0 -> 2145 bytes bash-5.1/vendor/term/tests/data/rxvt-color | Bin 0 -> 2229 bytes bash-5.1/vendor/term/tests/data/rxvt-cygwin | Bin 0 -> 2251 bytes .../vendor/term/tests/data/rxvt-cygwin-native | Bin 0 -> 2269 bytes bash-5.1/vendor/term/tests/data/rxvt-xpm | Bin 0 -> 2227 bytes bash-5.1/vendor/term/tests/data/screen | Bin 0 -> 1587 bytes .../vendor/term/tests/data/screen-256color | Bin 0 -> 1912 bytes bash-5.1/vendor/term/tests/data/xterm | Bin 0 -> 3412 bytes .../vendor/term/tests/data/xterm-256color | Bin 0 -> 3462 bytes bash-5.1/vendor/term/tests/terminfo.rs | 32 + bash-5.1/vendor/textwrap/.cargo-checksum.json | 1 + bash-5.1/vendor/textwrap/Cargo.toml | 56 + bash-5.1/vendor/textwrap/LICENSE | 21 + bash-5.1/vendor/textwrap/README.md | 337 + bash-5.1/vendor/textwrap/benches/linear.rs | 122 + bash-5.1/vendor/textwrap/examples/layout.rs | 38 + .../vendor/textwrap/examples/termwidth.rs | 41 + bash-5.1/vendor/textwrap/src/indentation.rs | 294 + bash-5.1/vendor/textwrap/src/lib.rs | 987 +++ bash-5.1/vendor/textwrap/src/splitting.rs | 139 + .../vendor/textwrap/tests/version-numbers.rs | 17 + .../thiserror-impl/.cargo-checksum.json | 2 +- bash-5.1/vendor/thiserror-impl/Cargo.toml | 2 +- bash-5.1/vendor/thiserror-impl/src/expand.rs | 18 +- .../vendor/thiserror/.cargo-checksum.json | 2 +- bash-5.1/vendor/thiserror/Cargo.toml | 6 +- bash-5.1/vendor/thiserror/README.md | 30 +- bash-5.1/vendor/thiserror/build.rs | 66 + bash-5.1/vendor/thiserror/src/aserror.rs | 9 +- bash-5.1/vendor/thiserror/src/lib.rs | 39 +- bash-5.1/vendor/thiserror/src/provide.rs | 15 + .../vendor/thiserror/tests/test_backtrace.rs | 46 + .../vendor/thiserror/tests/test_deprecated.rs | 10 + .../tests/ui/source-enum-not-error.stderr | 6 +- .../tests/ui/source-struct-not-error.stderr | 4 +- .../vendor/thread_local/.cargo-checksum.json | 1 + bash-5.1/vendor/thread_local/Cargo.toml | 26 + bash-5.1/vendor/thread_local/LICENSE-APACHE | 201 + bash-5.1/vendor/thread_local/LICENSE-MIT | 25 + bash-5.1/vendor/thread_local/README.md | 41 + .../thread_local/benches/thread_local.rs | 18 + bash-5.1/vendor/thread_local/src/lib.rs | 757 ++ bash-5.1/vendor/thread_local/src/thread_id.rs | 61 + .../vendor/thread_local/src/unreachable.rs | 74 + bash-5.1/vendor/tinystr/LICENSE | 51 + bash-5.1/vendor/tinystr/benches/common/mod.rs | 79 + bash-5.1/vendor/tinystr/benches/overview.rs | 165 + bash-5.1/vendor/tinystr/benches/read.rs | 34 + bash-5.1/vendor/tinystr/benches/serde.rs | 37 + bash-5.1/vendor/tinystr/src/ascii.rs | 982 +++ bash-5.1/vendor/tinystr/src/asciibyte.rs | 145 + bash-5.1/vendor/tinystr/src/databake.rs | 21 + bash-5.1/vendor/tinystr/src/error.rs | 19 + bash-5.1/vendor/tinystr/src/int_ops.rs | 315 + bash-5.1/vendor/tinystr/src/macros.rs | 32 + bash-5.1/vendor/tinystr/src/serde.rs | 91 + bash-5.1/vendor/tinystr/src/ule.rs | 76 + bash-5.1/vendor/tinystr/tests/serde.rs | 39 + bash-5.1/vendor/ucd-util/.cargo-checksum.json | 1 + bash-5.1/vendor/ucd-util/Cargo.toml | 30 + bash-5.1/vendor/ucd-util/LICENSE-APACHE | 201 + bash-5.1/vendor/ucd-util/LICENSE-MIT | 21 + bash-5.1/vendor/ucd-util/LICENSE-UNICODE | 57 + bash-5.1/vendor/ucd-util/README.md | 27 + bash-5.1/vendor/ucd-util/src/hangul.rs | 99 + bash-5.1/vendor/ucd-util/src/ideograph.rs | 82 + bash-5.1/vendor/ucd-util/src/lib.rs | 30 + bash-5.1/vendor/ucd-util/src/name.rs | 203 + bash-5.1/vendor/ucd-util/src/property.rs | 132 + .../src/unicode_tables/jamo_short_name.rs | 77 + .../vendor/ucd-util/src/unicode_tables/mod.rs | 5 + .../src/unicode_tables/property_names.rs | 264 + .../src/unicode_tables/property_values.rs | 3041 ++++++++ .../tests/canonicalize_test.rs | 13 + .../vendor/unic-langid-impl/tests/fixtures.rs | 75 + .../tests/language_identifier_test.rs | 192 + .../unic-langid-impl/tests/likelysubtags.rs | 113 + .../vendor/unicode-ident/.cargo-checksum.json | 2 +- bash-5.1/vendor/unicode-ident/Cargo.toml | 13 +- bash-5.1/vendor/unicode-ident/README.md | 8 +- bash-5.1/vendor/unicode-ident/src/tables.rs | 111 +- .../unicode-ident/tests/fst/xid_continue.fst | Bin 70255 -> 72750 bytes .../unicode-ident/tests/fst/xid_start.fst | Bin 62642 -> 64999 bytes .../vendor/unicode-ident/tests/static_size.rs | 8 +- .../vendor/unicode-ident/tests/tables/mod.rs | 7 + .../unicode-ident/tests/tables/tables.rs | 347 + .../vendor/unicode-ident/tests/trie/trie.rs | 222 +- .../vendor/unicode-width/.cargo-checksum.json | 1 + bash-5.1/vendor/unicode-width/COPYRIGHT | 7 + bash-5.1/vendor/unicode-width/Cargo.toml | 60 + bash-5.1/vendor/unicode-width/LICENSE-APACHE | 201 + bash-5.1/vendor/unicode-width/LICENSE-MIT | 25 + bash-5.1/vendor/unicode-width/README.md | 58 + .../vendor/unicode-width/scripts/unicode.py | 505 ++ bash-5.1/vendor/unicode-width/src/lib.rs | 131 + bash-5.1/vendor/unicode-width/src/tables.rs | 540 ++ bash-5.1/vendor/unicode-width/src/tests.rs | 191 + .../vendor/unicode-xid/.cargo-checksum.json | 1 + bash-5.1/vendor/unicode-xid/COPYRIGHT | 7 + bash-5.1/vendor/unicode-xid/Cargo.toml | 26 + bash-5.1/vendor/unicode-xid/LICENSE-APACHE | 201 + bash-5.1/vendor/unicode-xid/LICENSE-MIT | 25 + bash-5.1/vendor/unicode-xid/README.md | 34 + .../vendor/unicode-xid/scripts/unicode.py | 187 + bash-5.1/vendor/unicode-xid/src/lib.rs | 87 + bash-5.1/vendor/unicode-xid/src/tables.rs | 426 ++ bash-5.1/vendor/unicode-xid/src/tests.rs | 113 + .../vendor/utf8-ranges/.cargo-checksum.json | 1 + bash-5.1/vendor/utf8-ranges/COPYING | 3 + bash-5.1/vendor/utf8-ranges/Cargo.toml | 41 + bash-5.1/vendor/utf8-ranges/LICENSE-MIT | 21 + bash-5.1/vendor/utf8-ranges/README.md | 57 + bash-5.1/vendor/utf8-ranges/UNLICENSE | 24 + bash-5.1/vendor/utf8-ranges/benches/bench.rs | 25 + bash-5.1/vendor/utf8-ranges/src/char_utf8.rs | 36 + bash-5.1/vendor/utf8-ranges/src/lib.rs | 532 ++ bash-5.1/vendor/vec_map/.cargo-checksum.json | 1 + bash-5.1/vendor/vec_map/Cargo.toml | 31 + bash-5.1/vendor/vec_map/LICENSE-APACHE | 201 + bash-5.1/vendor/vec_map/LICENSE-MIT | 25 + bash-5.1/vendor/vec_map/README.md | 15 + bash-5.1/vendor/vec_map/src/lib.rs | 1623 +++++ .../vendor/winapi-0.2.8/.cargo-checksum.json | 1 + bash-5.1/vendor/winapi-0.2.8/Cargo.toml | 61 + bash-5.1/vendor/winapi-0.2.8/LICENSE.md | 21 + .../vendor/winapi-0.2.8/src/activation.rs | 5 + .../vendor/winapi-0.2.8/src/audioclient.rs | 71 + .../winapi-0.2.8/src/audiosessiontypes.rs | 11 + bash-5.1/vendor/winapi-0.2.8/src/basetsd.rs | 99 + bash-5.1/vendor/winapi-0.2.8/src/bcrypt.rs | 356 + bash-5.1/vendor/winapi-0.2.8/src/cfg.rs | 134 + bash-5.1/vendor/winapi-0.2.8/src/cfgmgr32.rs | 758 ++ .../vendor/winapi-0.2.8/src/combaseapi.rs | 17 + bash-5.1/vendor/winapi-0.2.8/src/commctrl.rs | 3578 ++++++++++ bash-5.1/vendor/winapi-0.2.8/src/commdlg.rs | 583 ++ bash-5.1/vendor/winapi-0.2.8/src/corsym.rs | 79 + bash-5.1/vendor/winapi-0.2.8/src/d2d1.rs | 734 ++ .../vendor/winapi-0.2.8/src/d2dbasetypes.rs | 61 + .../vendor/winapi-0.2.8/src/d3d10shader.rs | 110 + bash-5.1/vendor/winapi-0.2.8/src/d3d11.rs | 2665 +++++++ .../vendor/winapi-0.2.8/src/d3d11shader.rs | 320 + bash-5.1/vendor/winapi-0.2.8/src/d3d12.rs | 2324 +++++++ .../vendor/winapi-0.2.8/src/d3d12sdklayers.rs | 1063 +++ .../vendor/winapi-0.2.8/src/d3d12shader.rs | 320 + bash-5.1/vendor/winapi-0.2.8/src/d3d9.rs | 713 ++ bash-5.1/vendor/winapi-0.2.8/src/d3d9caps.rs | 349 + bash-5.1/vendor/winapi-0.2.8/src/d3d9types.rs | 1397 ++++ bash-5.1/vendor/winapi-0.2.8/src/d3dcommon.rs | 753 ++ .../vendor/winapi-0.2.8/src/d3dcompiler.rs | 74 + bash-5.1/vendor/winapi-0.2.8/src/dbghelp.rs | 340 + bash-5.1/vendor/winapi-0.2.8/src/dcommon.rs | 18 + .../vendor/winapi-0.2.8/src/devpropdef.rs | 71 + bash-5.1/vendor/winapi-0.2.8/src/docobj.rs | 22 + bash-5.1/vendor/winapi-0.2.8/src/dpapi.rs | 11 + bash-5.1/vendor/winapi-0.2.8/src/dsgetdc.rs | 113 + bash-5.1/vendor/winapi-0.2.8/src/dsound.rs | 132 + bash-5.1/vendor/winapi-0.2.8/src/dsrole.rs | 50 + bash-5.1/vendor/winapi-0.2.8/src/dwmapi.rs | 9 + bash-5.1/vendor/winapi-0.2.8/src/dwrite.rs | 1038 +++ bash-5.1/vendor/winapi-0.2.8/src/dxgi.rs | 240 + bash-5.1/vendor/winapi-0.2.8/src/dxgi1_2.rs | 288 + bash-5.1/vendor/winapi-0.2.8/src/dxgi1_3.rs | 131 + bash-5.1/vendor/winapi-0.2.8/src/dxgi1_4.rs | 82 + .../vendor/winapi-0.2.8/src/dxgiformat.rs | 124 + bash-5.1/vendor/winapi-0.2.8/src/dxgitype.rs | 86 + .../vendor/winapi-0.2.8/src/errhandlingapi.rs | 7 + bash-5.1/vendor/winapi-0.2.8/src/excpt.rs | 14 + bash-5.1/vendor/winapi-0.2.8/src/fileapi.rs | 152 + bash-5.1/vendor/winapi-0.2.8/src/gl.rs | 35 + bash-5.1/vendor/winapi-0.2.8/src/guiddef.rs | 20 + bash-5.1/vendor/winapi-0.2.8/src/heapapi.rs | 12 + bash-5.1/vendor/winapi-0.2.8/src/hidclass.rs | 56 + bash-5.1/vendor/winapi-0.2.8/src/hidpi.rs | 182 + bash-5.1/vendor/winapi-0.2.8/src/hidsdi.rs | 15 + bash-5.1/vendor/winapi-0.2.8/src/hidusage.rs | 270 + bash-5.1/vendor/winapi-0.2.8/src/hstring.rs | 16 + bash-5.1/vendor/winapi-0.2.8/src/http.rs | 828 +++ bash-5.1/vendor/winapi-0.2.8/src/imm.rs | 3 + bash-5.1/vendor/winapi-0.2.8/src/inaddr.rs | 22 + .../vendor/winapi-0.2.8/src/inspectable.rs | 15 + bash-5.1/vendor/winapi-0.2.8/src/ksmedia.rs | 18 + bash-5.1/vendor/winapi-0.2.8/src/lib.rs | 368 + .../vendor/winapi-0.2.8/src/libloaderapi.rs | 23 + bash-5.1/vendor/winapi-0.2.8/src/lmaccess.rs | 853 +++ bash-5.1/vendor/winapi-0.2.8/src/lmcons.rs | 55 + bash-5.1/vendor/winapi-0.2.8/src/lmdfs.rs | 311 + bash-5.1/vendor/winapi-0.2.8/src/lmerrlog.rs | 263 + bash-5.1/vendor/winapi-0.2.8/src/lmjoin.rs | 80 + bash-5.1/vendor/winapi-0.2.8/src/lsalookup.rs | 69 + bash-5.1/vendor/winapi-0.2.8/src/macros.rs | 270 + bash-5.1/vendor/winapi-0.2.8/src/memoryapi.rs | 19 + .../vendor/winapi-0.2.8/src/minschannel.rs | 56 + .../vendor/winapi-0.2.8/src/minwinbase.rs | 253 + bash-5.1/vendor/winapi-0.2.8/src/minwindef.rs | 89 + .../vendor/winapi-0.2.8/src/mmdeviceapi.rs | 63 + bash-5.1/vendor/winapi-0.2.8/src/mmreg.rs | 304 + bash-5.1/vendor/winapi-0.2.8/src/mmsystem.rs | 259 + bash-5.1/vendor/winapi-0.2.8/src/mscat.rs | 28 + bash-5.1/vendor/winapi-0.2.8/src/mssip.rs | 103 + bash-5.1/vendor/winapi-0.2.8/src/nb30.rs | 200 + bash-5.1/vendor/winapi-0.2.8/src/ncrypt.rs | 9 + bash-5.1/vendor/winapi-0.2.8/src/ntdef.rs | 7 + bash-5.1/vendor/winapi-0.2.8/src/ntsecapi.rs | 1589 +++++ bash-5.1/vendor/winapi-0.2.8/src/ntstatus.rs | 2474 +++++++ bash-5.1/vendor/winapi-0.2.8/src/oaidl.rs | 590 ++ bash-5.1/vendor/winapi-0.2.8/src/objbase.rs | 5 + bash-5.1/vendor/winapi-0.2.8/src/objidl.rs | 100 + .../vendor/winapi-0.2.8/src/objidlbase.rs | 93 + bash-5.1/vendor/winapi-0.2.8/src/olectl.rs | 10 + bash-5.1/vendor/winapi-0.2.8/src/pdh.rs | 52 + .../vendor/winapi-0.2.8/src/playsoundapi.rs | 19 + .../winapi-0.2.8/src/processsnapshot.rs | 58 + .../winapi-0.2.8/src/processthreadsapi.rs | 62 + bash-5.1/vendor/winapi-0.2.8/src/propidl.rs | 10 + bash-5.1/vendor/winapi-0.2.8/src/propsys.rs | 4 + bash-5.1/vendor/winapi-0.2.8/src/prsht.rs | 262 + bash-5.1/vendor/winapi-0.2.8/src/psapi.rs | 166 + bash-5.1/vendor/winapi-0.2.8/src/qos.rs | 16 + bash-5.1/vendor/winapi-0.2.8/src/reason.rs | 63 + .../winapi-0.2.8/src/restrictederrorinfo.rs | 9 + bash-5.1/vendor/winapi-0.2.8/src/roapi.rs | 13 + .../vendor/winapi-0.2.8/src/roerrorapi.rs | 11 + bash-5.1/vendor/winapi-0.2.8/src/rpc.rs | 5 + bash-5.1/vendor/winapi-0.2.8/src/rpcdce.rs | 535 ++ bash-5.1/vendor/winapi-0.2.8/src/sapi.rs | 2431 +++++++ bash-5.1/vendor/winapi-0.2.8/src/schannel.rs | 333 + bash-5.1/vendor/winapi-0.2.8/src/servprov.rs | 11 + bash-5.1/vendor/winapi-0.2.8/src/setupapi.rs | 1301 ++++ bash-5.1/vendor/winapi-0.2.8/src/shellapi.rs | 62 + .../winapi-0.2.8/src/shellscalingapi.rs | 19 + bash-5.1/vendor/winapi-0.2.8/src/shlguid.rs | 2 + bash-5.1/vendor/winapi-0.2.8/src/shlobj.rs | 94 + bash-5.1/vendor/winapi-0.2.8/src/shobjidl.rs | 652 ++ bash-5.1/vendor/winapi-0.2.8/src/shtypes.rs | 40 + bash-5.1/vendor/winapi-0.2.8/src/spapidef.rs | 48 + bash-5.1/vendor/winapi-0.2.8/src/sql.rs | 179 + bash-5.1/vendor/winapi-0.2.8/src/sqltypes.rs | 130 + bash-5.1/vendor/winapi-0.2.8/src/sspi.rs | 657 ++ bash-5.1/vendor/winapi-0.2.8/src/strmif.rs | 4 + bash-5.1/vendor/winapi-0.2.8/src/subauth.rs | 198 + bash-5.1/vendor/winapi-0.2.8/src/synchapi.rs | 14 + .../vendor/winapi-0.2.8/src/sysinfoapi.rs | 46 + .../vendor/winapi-0.2.8/src/threadpoolapi.rs | 7 + .../vendor/winapi-0.2.8/src/timezoneapi.rs | 27 + bash-5.1/vendor/winapi-0.2.8/src/tlhelp32.rs | 104 + .../vendor/winapi-0.2.8/src/unknwnbase.rs | 29 + bash-5.1/vendor/winapi-0.2.8/src/urlhist.rs | 56 + bash-5.1/vendor/winapi-0.2.8/src/urlmon.rs | 6 + bash-5.1/vendor/winapi-0.2.8/src/usb.rs | 18 + bash-5.1/vendor/winapi-0.2.8/src/usbspec.rs | 41 + bash-5.1/vendor/winapi-0.2.8/src/usp10.rs | 201 + bash-5.1/vendor/winapi-0.2.8/src/vadefs.rs | 7 + bash-5.1/vendor/winapi-0.2.8/src/vsbackup.rs | 303 + bash-5.1/vendor/winapi-0.2.8/src/vss.rs | 256 + bash-5.1/vendor/winapi-0.2.8/src/vsserror.rs | 85 + bash-5.1/vendor/winapi-0.2.8/src/vswriter.rs | 241 + bash-5.1/vendor/winapi-0.2.8/src/werapi.rs | 8 + bash-5.1/vendor/winapi-0.2.8/src/winbase.rs | 552 ++ bash-5.1/vendor/winapi-0.2.8/src/wincon.rs | 198 + bash-5.1/vendor/winapi-0.2.8/src/wincred.rs | 209 + bash-5.1/vendor/winapi-0.2.8/src/wincrypt.rs | 2206 ++++++ bash-5.1/vendor/winapi-0.2.8/src/windef.rs | 57 + .../vendor/winapi-0.2.8/src/windowscodecs.rs | 363 + bash-5.1/vendor/winapi-0.2.8/src/windowsx.rs | 22 + bash-5.1/vendor/winapi-0.2.8/src/winerror.rs | 6065 ++++++++++++++++ bash-5.1/vendor/winapi-0.2.8/src/winevt.rs | 40 + bash-5.1/vendor/winapi-0.2.8/src/wingdi.rs | 1238 ++++ bash-5.1/vendor/winapi-0.2.8/src/winhttp.rs | 441 ++ bash-5.1/vendor/winapi-0.2.8/src/winioctl.rs | 754 ++ bash-5.1/vendor/winapi-0.2.8/src/winnetwk.rs | 275 + bash-5.1/vendor/winapi-0.2.8/src/winnls.rs | 164 + bash-5.1/vendor/winapi-0.2.8/src/winnt.rs | 2368 +++++++ bash-5.1/vendor/winapi-0.2.8/src/winreg.rs | 41 + bash-5.1/vendor/winapi-0.2.8/src/winscard.rs | 269 + bash-5.1/vendor/winapi-0.2.8/src/winsmcrd.rs | 157 + bash-5.1/vendor/winapi-0.2.8/src/winsock2.rs | 429 ++ bash-5.1/vendor/winapi-0.2.8/src/winspool.rs | 29 + bash-5.1/vendor/winapi-0.2.8/src/winstring.rs | 3 + bash-5.1/vendor/winapi-0.2.8/src/winsvc.rs | 200 + bash-5.1/vendor/winapi-0.2.8/src/winusb.rs | 33 + bash-5.1/vendor/winapi-0.2.8/src/winusbio.rs | 18 + bash-5.1/vendor/winapi-0.2.8/src/winuser.rs | 2334 +++++++ bash-5.1/vendor/winapi-0.2.8/src/ws2def.rs | 279 + bash-5.1/vendor/winapi-0.2.8/src/ws2ipdef.rs | 42 + bash-5.1/vendor/winapi-0.2.8/src/ws2spi.rs | 57 + bash-5.1/vendor/winapi-0.2.8/src/ws2tcpip.rs | 27 + bash-5.1/vendor/winapi-0.2.8/src/wtypes.rs | 75 + .../vendor/winapi-0.2.8/src/wtypesbase.rs | 37 + bash-5.1/vendor/winapi-0.2.8/src/xinput.rs | 118 + .../vendor/winapi-build/.cargo-checksum.json | 1 + bash-5.1/vendor/winapi-build/Cargo.toml | 11 + bash-5.1/vendor/winapi-build/src/lib.rs | 14 + record.txt | 1 + 1669 files changed, 347806 insertions(+), 5378 deletions(-) create mode 100644 bash-5.1/vendor/aho-corasick/.cargo-checksum.json create mode 100644 bash-5.1/vendor/aho-corasick/COPYING create mode 100644 bash-5.1/vendor/aho-corasick/Cargo.toml create mode 100644 bash-5.1/vendor/aho-corasick/LICENSE-MIT create mode 100644 bash-5.1/vendor/aho-corasick/README.md create mode 100644 bash-5.1/vendor/aho-corasick/UNLICENSE create mode 100644 bash-5.1/vendor/aho-corasick/benches/bench.rs create mode 100644 bash-5.1/vendor/aho-corasick/benches/random.txt create mode 100644 bash-5.1/vendor/aho-corasick/examples/dict-search.rs create mode 100644 bash-5.1/vendor/aho-corasick/src/autiter.rs create mode 100644 bash-5.1/vendor/aho-corasick/src/full.rs create mode 100644 bash-5.1/vendor/aho-corasick/src/lib.rs create mode 100644 bash-5.1/vendor/aho-corasick/src/main.rs create mode 100644 bash-5.1/vendor/ansi_term/.cargo-checksum.json create mode 100644 bash-5.1/vendor/ansi_term/Cargo.toml create mode 100644 bash-5.1/vendor/ansi_term/LICENCE create mode 100644 bash-5.1/vendor/ansi_term/README.md create mode 100644 bash-5.1/vendor/ansi_term/examples/256_colours.rs create mode 100644 bash-5.1/vendor/ansi_term/examples/basic_colours.rs create mode 100644 bash-5.1/vendor/ansi_term/examples/rgb_colours.rs create mode 100644 bash-5.1/vendor/ansi_term/src/ansi.rs create mode 100644 bash-5.1/vendor/ansi_term/src/debug.rs create mode 100644 bash-5.1/vendor/ansi_term/src/difference.rs create mode 100644 bash-5.1/vendor/ansi_term/src/display.rs create mode 100644 bash-5.1/vendor/ansi_term/src/lib.rs create mode 100644 bash-5.1/vendor/ansi_term/src/style.rs create mode 100644 bash-5.1/vendor/ansi_term/src/util.rs create mode 100644 bash-5.1/vendor/ansi_term/src/windows.rs create mode 100644 bash-5.1/vendor/ansi_term/src/write.rs create mode 100644 bash-5.1/vendor/aster/.cargo-checksum.json create mode 100644 bash-5.1/vendor/aster/Cargo.toml create mode 100644 bash-5.1/vendor/aster/src/arm.rs create mode 100644 bash-5.1/vendor/aster/src/attr.rs create mode 100644 bash-5.1/vendor/aster/src/block.rs create mode 100644 bash-5.1/vendor/aster/src/constant.rs create mode 100644 bash-5.1/vendor/aster/src/ctx.rs create mode 100644 bash-5.1/vendor/aster/src/expr.rs create mode 100644 bash-5.1/vendor/aster/src/fn_decl.rs create mode 100644 bash-5.1/vendor/aster/src/generics.rs create mode 100644 bash-5.1/vendor/aster/src/ident.rs create mode 100644 bash-5.1/vendor/aster/src/invoke.rs create mode 100644 bash-5.1/vendor/aster/src/item.rs create mode 100644 bash-5.1/vendor/aster/src/lib.rs create mode 100644 bash-5.1/vendor/aster/src/lifetime.rs create mode 100644 bash-5.1/vendor/aster/src/lit.rs create mode 100644 bash-5.1/vendor/aster/src/mac.rs create mode 100644 bash-5.1/vendor/aster/src/method.rs create mode 100644 bash-5.1/vendor/aster/src/pat.rs create mode 100644 bash-5.1/vendor/aster/src/path.rs create mode 100644 bash-5.1/vendor/aster/src/qpath.rs create mode 100644 bash-5.1/vendor/aster/src/self_.rs create mode 100644 bash-5.1/vendor/aster/src/stmt.rs create mode 100644 bash-5.1/vendor/aster/src/struct_field.rs create mode 100644 bash-5.1/vendor/aster/src/symbol.rs create mode 100644 bash-5.1/vendor/aster/src/ty.rs create mode 100644 bash-5.1/vendor/aster/src/ty_param.rs create mode 100644 bash-5.1/vendor/aster/src/variant.rs create mode 100644 bash-5.1/vendor/aster/src/variant_data.rs create mode 100644 bash-5.1/vendor/aster/src/where_predicate.rs create mode 100644 bash-5.1/vendor/async-trait/src/bound.rs create mode 100644 bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.rs create mode 100644 bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.stderr create mode 100644 bash-5.1/vendor/atty/.cargo-checksum.json create mode 100644 bash-5.1/vendor/atty/CHANGELOG.md create mode 100644 bash-5.1/vendor/atty/Cargo.toml create mode 100644 bash-5.1/vendor/atty/LICENSE create mode 100644 bash-5.1/vendor/atty/README.md create mode 100644 bash-5.1/vendor/atty/examples/atty.rs create mode 100644 bash-5.1/vendor/atty/rustfmt.toml create mode 100644 bash-5.1/vendor/atty/src/lib.rs create mode 100644 bash-5.1/vendor/autocfg-0.1.8/.cargo-checksum.json create mode 100644 bash-5.1/vendor/autocfg-0.1.8/Cargo.toml create mode 100644 bash-5.1/vendor/autocfg-0.1.8/LICENSE-APACHE create mode 100644 bash-5.1/vendor/autocfg-0.1.8/LICENSE-MIT create mode 100644 bash-5.1/vendor/autocfg-0.1.8/README.md create mode 100644 bash-5.1/vendor/autocfg-0.1.8/src/lib.rs create mode 100644 bash-5.1/vendor/bindgen/.cargo-checksum.json create mode 100644 bash-5.1/vendor/bindgen/CONTRIBUTING.md create mode 100644 bash-5.1/vendor/bindgen/Cargo.toml create mode 100644 bash-5.1/vendor/bindgen/LICENSE create mode 100644 bash-5.1/vendor/bindgen/README.md create mode 100644 bash-5.1/vendor/bindgen/build.rs create mode 100644 bash-5.1/vendor/bindgen/ci/before_install.sh create mode 100644 bash-5.1/vendor/bindgen/rustfmt.toml create mode 100644 bash-5.1/vendor/bindgen/src/chooser.rs create mode 100644 bash-5.1/vendor/bindgen/src/clang.rs create mode 100644 bash-5.1/vendor/bindgen/src/codegen/helpers.rs create mode 100644 bash-5.1/vendor/bindgen/src/codegen/mod.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/annotations.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/comp.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/context.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/derive.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/enum_ty.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/function.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/int.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/item.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/item_kind.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/layout.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/mod.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/module.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/ty.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/type_collector.rs create mode 100644 bash-5.1/vendor/bindgen/src/ir/var.rs create mode 100644 bash-5.1/vendor/bindgen/src/lib.rs create mode 100644 bash-5.1/vendor/bindgen/src/log_stubs.rs create mode 100644 bash-5.1/vendor/bindgen/src/main.rs create mode 100644 bash-5.1/vendor/bindgen/src/options.rs create mode 100644 bash-5.1/vendor/bindgen/src/parse.rs create mode 100644 bash-5.1/vendor/bindgen/src/regex_set.rs create mode 100644 bash-5.1/vendor/bindgen/src/uses.rs create mode 100644 bash-5.1/vendor/bindgen/tests/headers/16-byte-alignment.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/accessors.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/annotation_hide.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/anon_enum.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/anon_enum_trait.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/anon_enum_whitelist.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/anon_union.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/arg_keyword.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/auto.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/bad-namespace-parenthood-inheritance.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/base-to-derived.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/bitfield-enum-basic.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/bitfield_method_mangling.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/blocks.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/canonical_path_without_namespacing.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_nested.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_no_members.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_static.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_static_const.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_use_as.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_with_dtor.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_with_inner_struct.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/class_with_typedef.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/complex.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/complex_global.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/const_bool.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/const_enum_unnamed.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/const_ptr.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/const_resolved_ty.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/const_tparam.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/constant-evaluate.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/constify-all-enums.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/constify-enum.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/constructor-tp.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/constructors.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/convert-floats.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/crtp.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/dash_language.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/decl_extern_int_twice.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/decl_ptr_to_array.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/disable-namespacing.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces-definitions.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/duplicated_constants_in_ns.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/elaborated.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/empty_template_param_name.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_alias.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_and_vtable_mangling.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_dupe.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_explicit_type.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_in_template_with_typedef.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_negative.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/enum_packed.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/eval-variadic-template-parameter.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/extern.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/float128.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/forward-declaration-autoptr.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct-with-fields.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/forward_declared_complex_types.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/forward_declared_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/func_proto.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/func_ptr.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/func_ptr_in_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/func_with_array_arg.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/func_with_func_ptr_arg.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/in_class_typedef.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inherit-namespaced.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inherit_named.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inherit_typedef.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inline-function.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inline_namespace.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inline_namespace_conservative.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inline_namespace_whitelist.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inner_const.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/inner_template_self.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/int128_t.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/issue-358.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/issue-372.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/issue-410.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/issue-447.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/issue_311.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/issue_315.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/jsval_layout_opaque.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/keywords.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/macro-expr-basic.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/macro-redef.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/macro_const.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/maddness-is-avoidable.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/method-mangling.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/module-whitelisted.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/msvc-no-usr.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/multiple-inherit-empty-correct-layout.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/mutable.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/namespace.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/nested.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/nested_vtable.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/nested_within_namespace.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/no-comments.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/no-derive-debug.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/no-recursive-whitelisting.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/no-std.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/no_copy.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/nsStyleAutoArray.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/only_bitfields.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/opaque-tracing.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/opaque_in_struct.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/opaque_pointer.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/opaque_typedef.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/overflowed_enum.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/overloading.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/private.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/public-dtor.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/redeclaration.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/ref_argument_array.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/reparented_replacement.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/replace_template_alias.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/replace_use.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/replaces_double.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/resolved_type_def_function.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/same_struct_name_in_different_namespaces.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/size_t_template.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_containing_forward_declared_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_array.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_pointer.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_union.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_union.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_bitfields.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_derive_debug.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_nesting.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_packing.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/struct_with_typedef_template_arg.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/template.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/template_alias.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/template_alias_basic.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/template_alias_namespace.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/template_typedef_transitive_param.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/template_typedefs.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/templateref_opaque.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/type-referenced-by-whitelisted-function.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/type_alias_empty.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/type_alias_partial_template_especialization.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/type_alias_template_specialized.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/typedefd-array-as-function-arg.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/typeref.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union-in-ns.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_dtor.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_fields.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_template.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct_bitfield.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_anon_union.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_struct.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_union.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_big_member.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/union_with_nesting.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/unknown_attr.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/use-core.h create mode 100644 bash-5.1/vendor/bindgen/tests/headers/using.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/var-tracing.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/variadic-method.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/variadic_template_function.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/vector.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/virtual_dtor.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/virtual_inheritance.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/virtual_overloaded.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/vtable_recursive_sig.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/weird_bitfields.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/what_is_going_on.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces-basic.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/whitelist_basic.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/whitelist_fix.hpp create mode 100644 bash-5.1/vendor/bindgen/tests/headers/whitelist_vars.h create mode 100644 bash-5.1/vendor/bindgen/tests/tests.rs create mode 100644 bash-5.1/vendor/bitflags-0.7.0/.cargo-checksum.json create mode 100644 bash-5.1/vendor/bitflags-0.7.0/Cargo.toml create mode 100644 bash-5.1/vendor/bitflags-0.7.0/LICENSE-APACHE create mode 100644 bash-5.1/vendor/bitflags-0.7.0/LICENSE-MIT create mode 100644 bash-5.1/vendor/bitflags-0.7.0/README.md create mode 100644 bash-5.1/vendor/bitflags-0.7.0/src/lib.rs create mode 100644 bash-5.1/vendor/bitflags-0.7.0/tests/external.rs create mode 100644 bash-5.1/vendor/bitflags-0.7.0/tests/external_no_std.rs create mode 100644 bash-5.1/vendor/cexpr/.cargo-checksum.json create mode 100644 bash-5.1/vendor/cexpr/Cargo.toml create mode 100644 bash-5.1/vendor/cexpr/LICENSE-APACHE create mode 100644 bash-5.1/vendor/cexpr/LICENSE-MIT create mode 100644 bash-5.1/vendor/cexpr/src/expr.rs create mode 100644 bash-5.1/vendor/cexpr/src/lib.rs create mode 100644 bash-5.1/vendor/cexpr/src/literal.rs create mode 100644 bash-5.1/vendor/cexpr/src/token.rs create mode 100644 bash-5.1/vendor/cexpr/tests/clang.rs create mode 100644 bash-5.1/vendor/cexpr/tests/input/chars.h create mode 100644 bash-5.1/vendor/cexpr/tests/input/fail.h create mode 100644 bash-5.1/vendor/cexpr/tests/input/floats.h create mode 100644 bash-5.1/vendor/cexpr/tests/input/int_signed.h create mode 100644 bash-5.1/vendor/cexpr/tests/input/int_unsigned.h create mode 100644 bash-5.1/vendor/cexpr/tests/input/strings.h create mode 100644 bash-5.1/vendor/cexpr/tests/input/test_llvm_bug_9069.h create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/.cargo-checksum.json create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/Cargo.toml create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/LICENSE-APACHE create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/LICENSE-MIT create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/README.md create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/src/lib.rs create mode 100644 bash-5.1/vendor/cfg-if-0.1.10/tests/xcrate.rs create mode 100644 bash-5.1/vendor/clang-sys/.cargo-checksum.json create mode 100644 bash-5.1/vendor/clang-sys/CHANGELOG.md create mode 100644 bash-5.1/vendor/clang-sys/CONTRIBUTING.md create mode 100644 bash-5.1/vendor/clang-sys/Cargo.toml create mode 100644 bash-5.1/vendor/clang-sys/LICENSE.txt create mode 100644 bash-5.1/vendor/clang-sys/README.md create mode 100644 bash-5.1/vendor/clang-sys/appveyor.yml create mode 100644 bash-5.1/vendor/clang-sys/build.rs create mode 100755 bash-5.1/vendor/clang-sys/ci/before_install.sh create mode 100644 bash-5.1/vendor/clang-sys/ci/install.bat create mode 100755 bash-5.1/vendor/clang-sys/ci/script.sh create mode 100644 bash-5.1/vendor/clang-sys/ci/test_script.bat create mode 100644 bash-5.1/vendor/clang-sys/clippy.toml create mode 100644 bash-5.1/vendor/clang-sys/src/lib.rs create mode 100644 bash-5.1/vendor/clang-sys/src/link.rs create mode 100644 bash-5.1/vendor/clang-sys/src/support.rs create mode 100644 bash-5.1/vendor/clang-sys/tests/header.h create mode 100644 bash-5.1/vendor/clang-sys/tests/lib.rs create mode 100644 bash-5.1/vendor/clap/.cargo-checksum.json create mode 100644 bash-5.1/vendor/clap/CHANGELOG.md create mode 100644 bash-5.1/vendor/clap/CONTRIBUTORS.md create mode 100644 bash-5.1/vendor/clap/Cargo.toml create mode 100644 bash-5.1/vendor/clap/LICENSE-MIT create mode 100644 bash-5.1/vendor/clap/README.md create mode 100644 bash-5.1/vendor/clap/SPONSORS.md create mode 100644 bash-5.1/vendor/clap/clap-test.rs create mode 100644 bash-5.1/vendor/clap/justfile create mode 100644 bash-5.1/vendor/clap/src/app/help.rs create mode 100644 bash-5.1/vendor/clap/src/app/meta.rs create mode 100644 bash-5.1/vendor/clap/src/app/mod.rs create mode 100644 bash-5.1/vendor/clap/src/app/parser.rs create mode 100644 bash-5.1/vendor/clap/src/app/settings.rs create mode 100644 bash-5.1/vendor/clap/src/app/usage.rs create mode 100644 bash-5.1/vendor/clap/src/app/validator.rs create mode 100644 bash-5.1/vendor/clap/src/args/any_arg.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/base.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/flag.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/mod.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/option.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/positional.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/switched.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_builder/valued.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_matcher.rs create mode 100644 bash-5.1/vendor/clap/src/args/arg_matches.rs create mode 100644 bash-5.1/vendor/clap/src/args/group.rs create mode 100644 bash-5.1/vendor/clap/src/args/macros.rs create mode 100644 bash-5.1/vendor/clap/src/args/matched_arg.rs create mode 100644 bash-5.1/vendor/clap/src/args/mod.rs create mode 100644 bash-5.1/vendor/clap/src/args/settings.rs create mode 100644 bash-5.1/vendor/clap/src/args/subcommand.rs create mode 100644 bash-5.1/vendor/clap/src/completions/bash.rs create mode 100644 bash-5.1/vendor/clap/src/completions/elvish.rs create mode 100644 bash-5.1/vendor/clap/src/completions/fish.rs create mode 100644 bash-5.1/vendor/clap/src/completions/macros.rs create mode 100644 bash-5.1/vendor/clap/src/completions/mod.rs create mode 100644 bash-5.1/vendor/clap/src/completions/powershell.rs create mode 100644 bash-5.1/vendor/clap/src/completions/shell.rs create mode 100644 bash-5.1/vendor/clap/src/completions/zsh.rs create mode 100644 bash-5.1/vendor/clap/src/errors.rs create mode 100644 bash-5.1/vendor/clap/src/fmt.rs create mode 100644 bash-5.1/vendor/clap/src/lib.rs create mode 100644 bash-5.1/vendor/clap/src/macros.rs create mode 100644 bash-5.1/vendor/clap/src/map.rs create mode 100644 bash-5.1/vendor/clap/src/osstringext.rs create mode 100644 bash-5.1/vendor/clap/src/strext.rs create mode 100644 bash-5.1/vendor/clap/src/suggestions.rs create mode 100644 bash-5.1/vendor/clap/src/usage_parser.rs create mode 100644 bash-5.1/vendor/cloudabi/.cargo-checksum.json create mode 100644 bash-5.1/vendor/cloudabi/Cargo.toml create mode 100644 bash-5.1/vendor/cloudabi/bitflags.rs create mode 100644 bash-5.1/vendor/cloudabi/cloudabi.rs create mode 100644 bash-5.1/vendor/displaydoc/.cargo-checksum.json create mode 100644 bash-5.1/vendor/displaydoc/CHANGELOG.md create mode 100644 bash-5.1/vendor/displaydoc/Cargo.toml create mode 100644 bash-5.1/vendor/displaydoc/LICENSE-APACHE create mode 100644 bash-5.1/vendor/displaydoc/LICENSE-MIT create mode 100644 bash-5.1/vendor/displaydoc/README.md create mode 100644 bash-5.1/vendor/displaydoc/README.tpl create mode 100644 bash-5.1/vendor/displaydoc/examples/simple.rs create mode 100644 bash-5.1/vendor/displaydoc/src/attr.rs create mode 100644 bash-5.1/vendor/displaydoc/src/expand.rs create mode 100644 bash-5.1/vendor/displaydoc/src/fmt.rs create mode 100644 bash-5.1/vendor/displaydoc/src/lib.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/compile_tests.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/happy.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.stderr create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/multi_line.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/multi_line.stderr create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/multi_line_allow.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/with.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/without.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/no_std/without.stderr create mode 100644 bash-5.1/vendor/displaydoc/tests/num_in_field.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/enum_prefix.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.stderr create mode 100644 bash-5.1/vendor/displaydoc/tests/std/multi_line.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/multi_line.stderr create mode 100644 bash-5.1/vendor/displaydoc/tests/std/multi_line_allow.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/multiple.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/without.rs create mode 100644 bash-5.1/vendor/displaydoc/tests/std/without.stderr create mode 100644 bash-5.1/vendor/dtoa/.cargo-checksum.json create mode 100644 bash-5.1/vendor/dtoa/Cargo.toml create mode 100644 bash-5.1/vendor/dtoa/LICENSE-APACHE create mode 100644 bash-5.1/vendor/dtoa/LICENSE-MIT create mode 100644 bash-5.1/vendor/dtoa/README.md create mode 100644 bash-5.1/vendor/dtoa/benches/bench.rs create mode 100644 bash-5.1/vendor/dtoa/src/diyfp.rs create mode 100644 bash-5.1/vendor/dtoa/src/dtoa.rs create mode 100644 bash-5.1/vendor/dtoa/src/lib.rs create mode 100644 bash-5.1/vendor/dtoa/tests/test.rs create mode 100644 bash-5.1/vendor/env_logger/.cargo-checksum.json create mode 100644 bash-5.1/vendor/env_logger/Cargo.toml create mode 100644 bash-5.1/vendor/env_logger/LICENSE-APACHE create mode 100644 bash-5.1/vendor/env_logger/LICENSE-MIT create mode 100644 bash-5.1/vendor/env_logger/src/lib.rs create mode 100644 bash-5.1/vendor/env_logger/src/regex.rs create mode 100644 bash-5.1/vendor/env_logger/src/string.rs create mode 100644 bash-5.1/vendor/env_logger/tests/regexp_filter.rs create mode 100644 bash-5.1/vendor/fuchsia-cprng/.cargo-checksum.json create mode 100644 bash-5.1/vendor/fuchsia-cprng/AUTHORS create mode 100644 bash-5.1/vendor/fuchsia-cprng/Cargo.toml create mode 100644 bash-5.1/vendor/fuchsia-cprng/LICENSE create mode 100644 bash-5.1/vendor/fuchsia-cprng/PATENTS create mode 100644 bash-5.1/vendor/fuchsia-cprng/src/lib.rs create mode 100644 bash-5.1/vendor/futures-channel/tests/mpsc-size_hint.rs create mode 100644 bash-5.1/vendor/futures/tests/future_join.rs create mode 100644 bash-5.1/vendor/glob/.cargo-checksum.json create mode 100644 bash-5.1/vendor/glob/Cargo.toml create mode 100644 bash-5.1/vendor/glob/LICENSE-APACHE create mode 100644 bash-5.1/vendor/glob/LICENSE-MIT create mode 100644 bash-5.1/vendor/glob/README.md create mode 100644 bash-5.1/vendor/glob/src/lib.rs create mode 100644 bash-5.1/vendor/glob/tests/glob-std.rs create mode 100644 bash-5.1/vendor/hermit-abi/.cargo-checksum.json create mode 100644 bash-5.1/vendor/hermit-abi/Cargo.toml create mode 100644 bash-5.1/vendor/hermit-abi/LICENSE-APACHE create mode 100644 bash-5.1/vendor/hermit-abi/LICENSE-MIT create mode 100644 bash-5.1/vendor/hermit-abi/README.md create mode 100644 bash-5.1/vendor/hermit-abi/rust-toolchain create mode 100644 bash-5.1/vendor/hermit-abi/src/lib.rs create mode 100644 bash-5.1/vendor/hermit-abi/src/tcplistener.rs create mode 100644 bash-5.1/vendor/hermit-abi/src/tcpstream.rs create mode 100644 bash-5.1/vendor/itoa/.cargo-checksum.json create mode 100644 bash-5.1/vendor/itoa/Cargo.toml create mode 100644 bash-5.1/vendor/itoa/LICENSE-APACHE create mode 100644 bash-5.1/vendor/itoa/LICENSE-MIT create mode 100644 bash-5.1/vendor/itoa/README.md create mode 100644 bash-5.1/vendor/itoa/benches/bench.rs create mode 100644 bash-5.1/vendor/itoa/src/lib.rs create mode 100644 bash-5.1/vendor/itoa/src/udiv128.rs create mode 100644 bash-5.1/vendor/itoa/tests/test.rs create mode 100644 bash-5.1/vendor/kernel32-sys/.cargo-checksum.json create mode 100644 bash-5.1/vendor/kernel32-sys/Cargo.toml create mode 100644 bash-5.1/vendor/kernel32-sys/README.md create mode 100644 bash-5.1/vendor/kernel32-sys/build.rs create mode 100644 bash-5.1/vendor/kernel32-sys/src/lib.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/.cargo-checksum.json create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/Cargo.toml create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/LICENSE-APACHE create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/LICENSE-MIT create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/README.md create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/appveyor.yml create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/src/core_lazy.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/src/lazy.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/src/lib.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/src/nightly_lazy.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/README.md create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/compile_tests.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/no_std.rs create mode 100644 bash-5.1/vendor/lazy_static-0.2.11/tests/test.rs create mode 100644 bash-5.1/vendor/libc/src/unix/aix/mod.rs create mode 100644 bash-5.1/vendor/libc/src/unix/aix/powerpc64.rs create mode 100644 bash-5.1/vendor/libc/src/unix/bsd/apple/long_array.rs create mode 100644 bash-5.1/vendor/libc/src/unix/nto/aarch64.rs create mode 100644 bash-5.1/vendor/libc/src/unix/nto/mod.rs create mode 100644 bash-5.1/vendor/libc/src/unix/nto/neutrino.rs create mode 100644 bash-5.1/vendor/libc/src/unix/nto/x86_64.rs create mode 100644 bash-5.1/vendor/libc/src/xous.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/.cargo-checksum.json create mode 100644 bash-5.1/vendor/libloading-0.3.4/Cargo.toml create mode 100644 bash-5.1/vendor/libloading-0.3.4/LICENSE create mode 100644 bash-5.1/vendor/libloading-0.3.4/README.mkd create mode 100644 bash-5.1/vendor/libloading-0.3.4/appveyor.yml create mode 100644 bash-5.1/vendor/libloading-0.3.4/build.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/changelog.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/lib.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/os/mod.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/os/unix/mod.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/os/windows/mod.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/test_helpers.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/src/util.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/tests/functions.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/tests/markers.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/tests/nagisa32.dll create mode 100644 bash-5.1/vendor/libloading-0.3.4/tests/nagisa64.dll create mode 100644 bash-5.1/vendor/libloading-0.3.4/tests/statics.rs create mode 100644 bash-5.1/vendor/libloading-0.3.4/tests/windows.rs create mode 100644 bash-5.1/vendor/log-0.3.9/.cargo-checksum.json create mode 100644 bash-5.1/vendor/log-0.3.9/Cargo.toml create mode 100644 bash-5.1/vendor/log-0.3.9/LICENSE-APACHE create mode 100644 bash-5.1/vendor/log-0.3.9/LICENSE-MIT create mode 100644 bash-5.1/vendor/log-0.3.9/README.md create mode 100644 bash-5.1/vendor/log-0.3.9/appveyor.yml create mode 100644 bash-5.1/vendor/log-0.3.9/src/lib.rs create mode 100644 bash-5.1/vendor/log-0.3.9/src/macros.rs create mode 100644 bash-5.1/vendor/log/.cargo-checksum.json create mode 100644 bash-5.1/vendor/log/CHANGELOG.md create mode 100644 bash-5.1/vendor/log/Cargo.toml create mode 100644 bash-5.1/vendor/log/LICENSE-APACHE create mode 100644 bash-5.1/vendor/log/LICENSE-MIT create mode 100644 bash-5.1/vendor/log/README.md create mode 100644 bash-5.1/vendor/log/benches/value.rs create mode 100644 bash-5.1/vendor/log/build.rs create mode 100644 bash-5.1/vendor/log/src/kv/error.rs create mode 100644 bash-5.1/vendor/log/src/kv/key.rs create mode 100644 bash-5.1/vendor/log/src/kv/mod.rs create mode 100644 bash-5.1/vendor/log/src/kv/source.rs create mode 100644 bash-5.1/vendor/log/src/kv/value.rs create mode 100644 bash-5.1/vendor/log/src/lib.rs create mode 100644 bash-5.1/vendor/log/src/macros.rs create mode 100644 bash-5.1/vendor/log/src/serde.rs create mode 100644 bash-5.1/vendor/log/triagebot.toml create mode 100644 bash-5.1/vendor/memchr-1.0.2/.cargo-checksum.json create mode 100644 bash-5.1/vendor/memchr-1.0.2/COPYING create mode 100644 bash-5.1/vendor/memchr-1.0.2/Cargo.toml create mode 100644 bash-5.1/vendor/memchr-1.0.2/LICENSE-MIT create mode 100644 bash-5.1/vendor/memchr-1.0.2/Makefile create mode 100644 bash-5.1/vendor/memchr-1.0.2/README.md create mode 100644 bash-5.1/vendor/memchr-1.0.2/UNLICENSE create mode 100644 bash-5.1/vendor/memchr-1.0.2/appveyor.yml create mode 100644 bash-5.1/vendor/memchr-1.0.2/benches/bench.rs create mode 100644 bash-5.1/vendor/memchr-1.0.2/ctags.rust create mode 100644 bash-5.1/vendor/memchr-1.0.2/session.vim create mode 100644 bash-5.1/vendor/memchr-1.0.2/src/lib.rs create mode 100644 bash-5.1/vendor/nom/.cargo-checksum.json create mode 100644 bash-5.1/vendor/nom/CHANGELOG.md create mode 100644 bash-5.1/vendor/nom/Cargo.toml create mode 100644 bash-5.1/vendor/nom/LICENSE create mode 100644 bash-5.1/vendor/nom/src/bits.rs create mode 100644 bash-5.1/vendor/nom/src/branch.rs create mode 100644 bash-5.1/vendor/nom/src/bytes.rs create mode 100644 bash-5.1/vendor/nom/src/character.rs create mode 100644 bash-5.1/vendor/nom/src/internal.rs create mode 100644 bash-5.1/vendor/nom/src/lib.rs create mode 100644 bash-5.1/vendor/nom/src/macros.rs create mode 100644 bash-5.1/vendor/nom/src/methods.rs create mode 100644 bash-5.1/vendor/nom/src/multi.rs create mode 100644 bash-5.1/vendor/nom/src/nom.rs create mode 100644 bash-5.1/vendor/nom/src/regexp.rs create mode 100644 bash-5.1/vendor/nom/src/sequence.rs create mode 100644 bash-5.1/vendor/nom/src/simple_errors.rs create mode 100644 bash-5.1/vendor/nom/src/str.rs create mode 100644 bash-5.1/vendor/nom/src/stream.rs create mode 100644 bash-5.1/vendor/nom/src/traits.rs create mode 100644 bash-5.1/vendor/nom/src/util.rs create mode 100644 bash-5.1/vendor/nom/src/verbose_errors.rs create mode 100644 bash-5.1/vendor/nom/src/whitespace.rs create mode 100644 bash-5.1/vendor/nom/tests/arithmetic.rs create mode 100644 bash-5.1/vendor/nom/tests/arithmetic_ast.rs create mode 100644 bash-5.1/vendor/nom/tests/blockbuf-arithmetic.rs create mode 100644 bash-5.1/vendor/nom/tests/cross_function_backtracking.rs create mode 100644 bash-5.1/vendor/nom/tests/float.rs create mode 100644 bash-5.1/vendor/nom/tests/ini.rs create mode 100644 bash-5.1/vendor/nom/tests/ini_str.rs create mode 100644 bash-5.1/vendor/nom/tests/issues.rs create mode 100644 bash-5.1/vendor/nom/tests/json.rs create mode 100644 bash-5.1/vendor/nom/tests/mp4.rs create mode 100644 bash-5.1/vendor/nom/tests/multiline.rs create mode 100644 bash-5.1/vendor/nom/tests/named_args.rs create mode 100644 bash-5.1/vendor/nom/tests/omnom.rs create mode 100644 bash-5.1/vendor/nom/tests/overflow.rs create mode 100644 bash-5.1/vendor/nom/tests/reborrow_fold.rs create mode 100644 bash-5.1/vendor/nom/tests/test1.rs create mode 100644 bash-5.1/vendor/num-traits-0.1.43/.cargo-checksum.json create mode 100644 bash-5.1/vendor/num-traits-0.1.43/Cargo.toml create mode 100644 bash-5.1/vendor/num-traits-0.1.43/LICENSE-APACHE create mode 100644 bash-5.1/vendor/num-traits-0.1.43/LICENSE-MIT create mode 100644 bash-5.1/vendor/num-traits-0.1.43/README.md create mode 100644 bash-5.1/vendor/num-traits-0.1.43/RELEASES.md create mode 100644 bash-5.1/vendor/num-traits-0.1.43/bors.toml create mode 100755 bash-5.1/vendor/num-traits-0.1.43/ci/rustup.sh create mode 100755 bash-5.1/vendor/num-traits-0.1.43/ci/test_full.sh create mode 100644 bash-5.1/vendor/num-traits-0.1.43/src/lib.rs create mode 100644 bash-5.1/vendor/num-traits/.cargo-checksum.json create mode 100644 bash-5.1/vendor/num-traits/Cargo.toml create mode 100644 bash-5.1/vendor/num-traits/LICENSE-APACHE create mode 100644 bash-5.1/vendor/num-traits/LICENSE-MIT create mode 100644 bash-5.1/vendor/num-traits/README.md create mode 100644 bash-5.1/vendor/num-traits/RELEASES.md create mode 100644 bash-5.1/vendor/num-traits/build.rs create mode 100644 bash-5.1/vendor/num-traits/src/bounds.rs create mode 100644 bash-5.1/vendor/num-traits/src/cast.rs create mode 100644 bash-5.1/vendor/num-traits/src/float.rs create mode 100644 bash-5.1/vendor/num-traits/src/identities.rs create mode 100644 bash-5.1/vendor/num-traits/src/int.rs create mode 100644 bash-5.1/vendor/num-traits/src/lib.rs create mode 100644 bash-5.1/vendor/num-traits/src/macros.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/checked.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/euclid.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/inv.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/mod.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/mul_add.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/overflowing.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/saturating.rs create mode 100644 bash-5.1/vendor/num-traits/src/ops/wrapping.rs create mode 100644 bash-5.1/vendor/num-traits/src/pow.rs create mode 100644 bash-5.1/vendor/num-traits/src/real.rs create mode 100644 bash-5.1/vendor/num-traits/src/sign.rs create mode 100644 bash-5.1/vendor/num-traits/tests/cast.rs create mode 100644 bash-5.1/vendor/once_cell/src/imp_cs.rs create mode 100644 bash-5.1/vendor/phf/.cargo-checksum.json create mode 100644 bash-5.1/vendor/phf/Cargo.toml create mode 100644 bash-5.1/vendor/phf/src/lib.rs create mode 100644 bash-5.1/vendor/phf/src/map.rs create mode 100644 bash-5.1/vendor/phf/src/ordered_map.rs create mode 100644 bash-5.1/vendor/phf/src/ordered_set.rs create mode 100644 bash-5.1/vendor/phf/src/set.rs create mode 100644 bash-5.1/vendor/phf_codegen/.cargo-checksum.json create mode 100644 bash-5.1/vendor/phf_codegen/Cargo.toml create mode 100644 bash-5.1/vendor/phf_codegen/src/lib.rs create mode 100644 bash-5.1/vendor/phf_generator/.cargo-checksum.json create mode 100644 bash-5.1/vendor/phf_generator/Cargo.toml create mode 100644 bash-5.1/vendor/phf_generator/src/lib.rs create mode 100644 bash-5.1/vendor/phf_shared/.cargo-checksum.json create mode 100644 bash-5.1/vendor/phf_shared/Cargo.toml create mode 100644 bash-5.1/vendor/phf_shared/src/lib.rs create mode 100644 bash-5.1/vendor/proc-macro2/src/location.rs create mode 100644 bash-5.1/vendor/quasi/.cargo-checksum.json create mode 100644 bash-5.1/vendor/quasi/Cargo.toml create mode 100644 bash-5.1/vendor/quasi/src/lib.rs create mode 100644 bash-5.1/vendor/quasi_codegen/.cargo-checksum.json create mode 100644 bash-5.1/vendor/quasi_codegen/Cargo.toml create mode 100644 bash-5.1/vendor/quasi_codegen/src/lib.rs create mode 100644 bash-5.1/vendor/rand/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand/COPYRIGHT create mode 100644 bash-5.1/vendor/rand/Cargo.toml create mode 100644 bash-5.1/vendor/rand/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand/README.md create mode 100644 bash-5.1/vendor/rand/benches/distributions.rs create mode 100644 bash-5.1/vendor/rand/benches/generators.rs create mode 100644 bash-5.1/vendor/rand/benches/misc.rs create mode 100644 bash-5.1/vendor/rand/benches/seq.rs create mode 100644 bash-5.1/vendor/rand/build.rs create mode 100644 bash-5.1/vendor/rand/examples/monte-carlo.rs create mode 100644 bash-5.1/vendor/rand/examples/monty-hall.rs create mode 100644 bash-5.1/vendor/rand/src/deprecated.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/bernoulli.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/binomial.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/cauchy.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/dirichlet.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/exponential.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/float.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/gamma.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/integer.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/mod.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/normal.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/other.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/pareto.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/poisson.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/triangular.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/uniform.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/unit_circle.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/unit_sphere.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/utils.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/weibull.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/weighted.rs create mode 100644 bash-5.1/vendor/rand/src/distributions/ziggurat_tables.rs create mode 100644 bash-5.1/vendor/rand/src/lib.rs create mode 100644 bash-5.1/vendor/rand/src/prelude.rs create mode 100644 bash-5.1/vendor/rand/src/prng/mod.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/adapter/mod.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/adapter/read.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/adapter/reseeding.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/entropy.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/mock.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/mod.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/small.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/std.rs create mode 100644 bash-5.1/vendor/rand/src/rngs/thread.rs create mode 100644 bash-5.1/vendor/rand/src/seq/index.rs create mode 100644 bash-5.1/vendor/rand/src/seq/mod.rs create mode 100644 bash-5.1/vendor/rand/tests/uniformity.rs create mode 100644 bash-5.1/vendor/rand_chacha/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_chacha/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_chacha/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_chacha/Cargo.toml create mode 100644 bash-5.1/vendor/rand_chacha/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_chacha/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_chacha/README.md create mode 100644 bash-5.1/vendor/rand_chacha/build.rs create mode 100644 bash-5.1/vendor/rand_chacha/src/chacha.rs create mode 100644 bash-5.1/vendor/rand_chacha/src/lib.rs create mode 100644 bash-5.1/vendor/rand_core-0.3.1/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_core-0.3.1/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_core-0.3.1/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_core-0.3.1/Cargo.toml create mode 100644 bash-5.1/vendor/rand_core-0.3.1/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_core-0.3.1/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_core-0.3.1/README.md create mode 100644 bash-5.1/vendor/rand_core-0.3.1/src/block.rs create mode 100644 bash-5.1/vendor/rand_core-0.3.1/src/error.rs create mode 100644 bash-5.1/vendor/rand_core-0.3.1/src/impls.rs create mode 100644 bash-5.1/vendor/rand_core-0.3.1/src/le.rs create mode 100644 bash-5.1/vendor/rand_core-0.3.1/src/lib.rs create mode 100644 bash-5.1/vendor/rand_core/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_core/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_core/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_core/Cargo.toml create mode 100644 bash-5.1/vendor/rand_core/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_core/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_core/README.md create mode 100644 bash-5.1/vendor/rand_core/src/block.rs create mode 100644 bash-5.1/vendor/rand_core/src/error.rs create mode 100644 bash-5.1/vendor/rand_core/src/impls.rs create mode 100644 bash-5.1/vendor/rand_core/src/le.rs create mode 100644 bash-5.1/vendor/rand_core/src/lib.rs create mode 100644 bash-5.1/vendor/rand_hc/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_hc/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_hc/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_hc/Cargo.toml create mode 100644 bash-5.1/vendor/rand_hc/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_hc/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_hc/README.md create mode 100644 bash-5.1/vendor/rand_hc/src/hc128.rs create mode 100644 bash-5.1/vendor/rand_hc/src/lib.rs create mode 100644 bash-5.1/vendor/rand_isaac/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_isaac/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_isaac/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_isaac/Cargo.toml create mode 100644 bash-5.1/vendor/rand_isaac/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_isaac/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_isaac/README.md create mode 100644 bash-5.1/vendor/rand_isaac/src/isaac.rs create mode 100644 bash-5.1/vendor/rand_isaac/src/isaac64.rs create mode 100644 bash-5.1/vendor/rand_isaac/src/isaac_array.rs create mode 100644 bash-5.1/vendor/rand_isaac/src/lib.rs create mode 100644 bash-5.1/vendor/rand_jitter/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_jitter/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_jitter/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_jitter/Cargo.toml create mode 100644 bash-5.1/vendor/rand_jitter/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_jitter/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_jitter/README.md create mode 100644 bash-5.1/vendor/rand_jitter/benches/mod.rs create mode 100644 bash-5.1/vendor/rand_jitter/src/dummy_log.rs create mode 100644 bash-5.1/vendor/rand_jitter/src/error.rs create mode 100644 bash-5.1/vendor/rand_jitter/src/lib.rs create mode 100644 bash-5.1/vendor/rand_jitter/src/platform.rs create mode 100644 bash-5.1/vendor/rand_jitter/tests/mod.rs create mode 100644 bash-5.1/vendor/rand_os/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_os/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_os/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_os/Cargo.toml create mode 100644 bash-5.1/vendor/rand_os/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_os/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_os/README.md create mode 100644 bash-5.1/vendor/rand_os/src/cloudabi.rs create mode 100644 bash-5.1/vendor/rand_os/src/dragonfly_haiku_emscripten.rs create mode 100644 bash-5.1/vendor/rand_os/src/dummy_log.rs create mode 100644 bash-5.1/vendor/rand_os/src/freebsd.rs create mode 100644 bash-5.1/vendor/rand_os/src/fuchsia.rs create mode 100644 bash-5.1/vendor/rand_os/src/lib.rs create mode 100644 bash-5.1/vendor/rand_os/src/linux_android.rs create mode 100644 bash-5.1/vendor/rand_os/src/macos.rs create mode 100644 bash-5.1/vendor/rand_os/src/netbsd.rs create mode 100644 bash-5.1/vendor/rand_os/src/openbsd_bitrig.rs create mode 100644 bash-5.1/vendor/rand_os/src/random_device.rs create mode 100644 bash-5.1/vendor/rand_os/src/redox.rs create mode 100644 bash-5.1/vendor/rand_os/src/sgx.rs create mode 100644 bash-5.1/vendor/rand_os/src/solarish.rs create mode 100644 bash-5.1/vendor/rand_os/src/wasm32_bindgen.rs create mode 100644 bash-5.1/vendor/rand_os/src/wasm32_stdweb.rs create mode 100644 bash-5.1/vendor/rand_os/src/windows.rs create mode 100644 bash-5.1/vendor/rand_os/tests/mod.rs create mode 100644 bash-5.1/vendor/rand_pcg/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_pcg/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_pcg/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_pcg/Cargo.toml create mode 100644 bash-5.1/vendor/rand_pcg/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_pcg/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_pcg/README.md create mode 100644 bash-5.1/vendor/rand_pcg/build.rs create mode 100644 bash-5.1/vendor/rand_pcg/src/lib.rs create mode 100644 bash-5.1/vendor/rand_pcg/src/pcg128.rs create mode 100644 bash-5.1/vendor/rand_pcg/src/pcg64.rs create mode 100644 bash-5.1/vendor/rand_pcg/tests/lcg64xsh32.rs create mode 100644 bash-5.1/vendor/rand_pcg/tests/mcg128xsl64.rs create mode 100644 bash-5.1/vendor/rand_xorshift/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rand_xorshift/CHANGELOG.md create mode 100644 bash-5.1/vendor/rand_xorshift/COPYRIGHT create mode 100644 bash-5.1/vendor/rand_xorshift/Cargo.toml create mode 100644 bash-5.1/vendor/rand_xorshift/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rand_xorshift/LICENSE-MIT create mode 100644 bash-5.1/vendor/rand_xorshift/README.md create mode 100644 bash-5.1/vendor/rand_xorshift/src/lib.rs create mode 100644 bash-5.1/vendor/rand_xorshift/tests/mod.rs create mode 100644 bash-5.1/vendor/rdrand/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rdrand/Cargo.toml create mode 100644 bash-5.1/vendor/rdrand/LICENSE create mode 100644 bash-5.1/vendor/rdrand/README.mkd create mode 100644 bash-5.1/vendor/rdrand/appveyor.yml create mode 100644 bash-5.1/vendor/rdrand/benches/rdrand.rs create mode 100644 bash-5.1/vendor/rdrand/benches/rdseed.rs create mode 100644 bash-5.1/vendor/rdrand/benches/std.rs create mode 100644 bash-5.1/vendor/rdrand/src/changelog.rs create mode 100644 bash-5.1/vendor/rdrand/src/lib.rs create mode 100644 bash-5.1/vendor/regex-syntax/.cargo-checksum.json create mode 100644 bash-5.1/vendor/regex-syntax/Cargo.toml create mode 100644 bash-5.1/vendor/regex-syntax/LICENSE-APACHE create mode 100644 bash-5.1/vendor/regex-syntax/LICENSE-MIT create mode 100644 bash-5.1/vendor/regex-syntax/benches/bench.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/ast/mod.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/ast/parse.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/ast/print.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/ast/visitor.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/either.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/error.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/hir/interval.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/hir/literal/mod.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/hir/mod.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/hir/print.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/hir/translate.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/hir/visitor.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/lib.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/parser.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/age.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/case_folding_simple.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/general_category.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/mod.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/perl_word.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/property_bool.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/property_names.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/property_values.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/script.rs create mode 100644 bash-5.1/vendor/regex-syntax/src/unicode_tables/script_extension.rs create mode 100644 bash-5.1/vendor/regex/.cargo-checksum.json create mode 100644 bash-5.1/vendor/regex/CHANGELOG.md create mode 100644 bash-5.1/vendor/regex/Cargo.toml create mode 100644 bash-5.1/vendor/regex/HACKING.md create mode 100644 bash-5.1/vendor/regex/LICENSE-APACHE create mode 100644 bash-5.1/vendor/regex/LICENSE-MIT create mode 100644 bash-5.1/vendor/regex/PERFORMANCE.md create mode 100644 bash-5.1/vendor/regex/README.md create mode 100644 bash-5.1/vendor/regex/UNICODE.md create mode 100644 bash-5.1/vendor/regex/appveyor.yml create mode 100644 bash-5.1/vendor/regex/build.rs create mode 100755 bash-5.1/vendor/regex/ci/after_success.sh create mode 100755 bash-5.1/vendor/regex/ci/run-kcov create mode 100755 bash-5.1/vendor/regex/ci/run-shootout-test create mode 100755 bash-5.1/vendor/regex/ci/script.sh create mode 100644 bash-5.1/vendor/regex/examples/regexdna-input.txt create mode 100644 bash-5.1/vendor/regex/examples/regexdna-output.txt create mode 100644 bash-5.1/vendor/regex/examples/shootout-regex-dna-bytes.rs create mode 100644 bash-5.1/vendor/regex/examples/shootout-regex-dna-cheat.rs create mode 100644 bash-5.1/vendor/regex/examples/shootout-regex-dna-replace.rs create mode 100644 bash-5.1/vendor/regex/examples/shootout-regex-dna-single-cheat.rs create mode 100644 bash-5.1/vendor/regex/examples/shootout-regex-dna-single.rs create mode 100644 bash-5.1/vendor/regex/examples/shootout-regex-dna.rs create mode 100755 bash-5.1/vendor/regex/scripts/frequencies.py create mode 100755 bash-5.1/vendor/regex/scripts/regex-match-tests.py create mode 100644 bash-5.1/vendor/regex/src/backtrack.rs create mode 100644 bash-5.1/vendor/regex/src/compile.rs create mode 100644 bash-5.1/vendor/regex/src/dfa.rs create mode 100644 bash-5.1/vendor/regex/src/error.rs create mode 100644 bash-5.1/vendor/regex/src/exec.rs create mode 100644 bash-5.1/vendor/regex/src/expand.rs create mode 100644 bash-5.1/vendor/regex/src/freqs.rs create mode 100644 bash-5.1/vendor/regex/src/input.rs create mode 100644 bash-5.1/vendor/regex/src/lib.rs create mode 100644 bash-5.1/vendor/regex/src/literal/mod.rs create mode 100644 bash-5.1/vendor/regex/src/literal/teddy_avx2/fallback.rs create mode 100644 bash-5.1/vendor/regex/src/literal/teddy_avx2/imp.rs create mode 100644 bash-5.1/vendor/regex/src/literal/teddy_avx2/mod.rs create mode 100644 bash-5.1/vendor/regex/src/literal/teddy_ssse3/fallback.rs create mode 100644 bash-5.1/vendor/regex/src/literal/teddy_ssse3/imp.rs create mode 100644 bash-5.1/vendor/regex/src/literal/teddy_ssse3/mod.rs create mode 100644 bash-5.1/vendor/regex/src/pattern.rs create mode 100644 bash-5.1/vendor/regex/src/pikevm.rs create mode 100644 bash-5.1/vendor/regex/src/prog.rs create mode 100644 bash-5.1/vendor/regex/src/re_builder.rs create mode 100644 bash-5.1/vendor/regex/src/re_bytes.rs create mode 100644 bash-5.1/vendor/regex/src/re_set.rs create mode 100644 bash-5.1/vendor/regex/src/re_trait.rs create mode 100644 bash-5.1/vendor/regex/src/re_unicode.rs create mode 100644 bash-5.1/vendor/regex/src/sparse.rs create mode 100644 bash-5.1/vendor/regex/src/testdata/LICENSE create mode 100644 bash-5.1/vendor/regex/src/testdata/README create mode 100644 bash-5.1/vendor/regex/src/testdata/basic.dat create mode 100644 bash-5.1/vendor/regex/src/testdata/nullsubexpr.dat create mode 100644 bash-5.1/vendor/regex/src/testdata/repetition.dat create mode 100644 bash-5.1/vendor/regex/src/utf8.rs create mode 100644 bash-5.1/vendor/regex/src/vector/avx2.rs create mode 100644 bash-5.1/vendor/regex/src/vector/mod.rs create mode 100644 bash-5.1/vendor/regex/src/vector/ssse3.rs create mode 100644 bash-5.1/vendor/regex/tests/api.rs create mode 100644 bash-5.1/vendor/regex/tests/api_str.rs create mode 100644 bash-5.1/vendor/regex/tests/bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/crazy.rs create mode 100644 bash-5.1/vendor/regex/tests/flags.rs create mode 100644 bash-5.1/vendor/regex/tests/fowler.rs create mode 100644 bash-5.1/vendor/regex/tests/macros.rs create mode 100644 bash-5.1/vendor/regex/tests/macros_bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/macros_str.rs create mode 100644 bash-5.1/vendor/regex/tests/misc.rs create mode 100644 bash-5.1/vendor/regex/tests/multiline.rs create mode 100644 bash-5.1/vendor/regex/tests/noparse.rs create mode 100644 bash-5.1/vendor/regex/tests/regression.rs create mode 100644 bash-5.1/vendor/regex/tests/replace.rs create mode 100644 bash-5.1/vendor/regex/tests/searcher.rs create mode 100644 bash-5.1/vendor/regex/tests/set.rs create mode 100644 bash-5.1/vendor/regex/tests/shortest_match.rs create mode 100644 bash-5.1/vendor/regex/tests/suffix_reverse.rs create mode 100644 bash-5.1/vendor/regex/tests/test_backtrack.rs create mode 100644 bash-5.1/vendor/regex/tests/test_backtrack_bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/test_backtrack_utf8bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/test_default.rs create mode 100644 bash-5.1/vendor/regex/tests/test_default_bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/test_nfa.rs create mode 100644 bash-5.1/vendor/regex/tests/test_nfa_bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/test_nfa_utf8bytes.rs create mode 100644 bash-5.1/vendor/regex/tests/unicode.rs create mode 100644 bash-5.1/vendor/regex/tests/word_boundary.rs create mode 100644 bash-5.1/vendor/regex/tests/word_boundary_ascii.rs create mode 100644 bash-5.1/vendor/regex/tests/word_boundary_unicode.rs create mode 100644 bash-5.1/vendor/rustc-serialize/.cargo-checksum.json create mode 100644 bash-5.1/vendor/rustc-serialize/Cargo.toml create mode 100644 bash-5.1/vendor/rustc-serialize/LICENSE-APACHE create mode 100644 bash-5.1/vendor/rustc-serialize/LICENSE-MIT create mode 100644 bash-5.1/vendor/rustc-serialize/README.md create mode 100644 bash-5.1/vendor/rustc-serialize/appveyor.yml create mode 100644 bash-5.1/vendor/rustc-serialize/benches/base64.rs create mode 100644 bash-5.1/vendor/rustc-serialize/benches/hex.rs create mode 100644 bash-5.1/vendor/rustc-serialize/benches/json.rs create mode 100644 bash-5.1/vendor/rustc-serialize/src/base64.rs create mode 100644 bash-5.1/vendor/rustc-serialize/src/collection_impls.rs create mode 100644 bash-5.1/vendor/rustc-serialize/src/hex.rs create mode 100644 bash-5.1/vendor/rustc-serialize/src/json.rs create mode 100644 bash-5.1/vendor/rustc-serialize/src/lib.rs create mode 100644 bash-5.1/vendor/rustc-serialize/src/serialize.rs create mode 100644 bash-5.1/vendor/serde/.cargo-checksum.json create mode 100644 bash-5.1/vendor/serde/Cargo.toml create mode 100644 bash-5.1/vendor/serde/LICENSE-APACHE create mode 100644 bash-5.1/vendor/serde/LICENSE-MIT create mode 100644 bash-5.1/vendor/serde/README.md create mode 100644 bash-5.1/vendor/serde/src/bytes.rs create mode 100644 bash-5.1/vendor/serde/src/de/content.rs create mode 100644 bash-5.1/vendor/serde/src/de/from_primitive.rs create mode 100644 bash-5.1/vendor/serde/src/de/impls.rs create mode 100644 bash-5.1/vendor/serde/src/de/mod.rs create mode 100644 bash-5.1/vendor/serde/src/de/private.rs create mode 100644 bash-5.1/vendor/serde/src/de/value.rs create mode 100644 bash-5.1/vendor/serde/src/error.rs create mode 100644 bash-5.1/vendor/serde/src/export.rs create mode 100644 bash-5.1/vendor/serde/src/iter.rs create mode 100644 bash-5.1/vendor/serde/src/lib.rs create mode 100644 bash-5.1/vendor/serde/src/macros.rs create mode 100644 bash-5.1/vendor/serde/src/ser/content.rs create mode 100644 bash-5.1/vendor/serde/src/ser/impls.rs create mode 100644 bash-5.1/vendor/serde/src/ser/impossible.rs create mode 100644 bash-5.1/vendor/serde/src/ser/mod.rs create mode 100644 bash-5.1/vendor/serde/src/ser/private.rs create mode 100644 bash-5.1/vendor/serde/src/utils.rs create mode 100644 bash-5.1/vendor/serde_json/.cargo-checksum.json create mode 100644 bash-5.1/vendor/serde_json/Cargo.toml create mode 100644 bash-5.1/vendor/serde_json/LICENSE-APACHE create mode 100644 bash-5.1/vendor/serde_json/LICENSE-MIT create mode 100644 bash-5.1/vendor/serde_json/README.md create mode 100644 bash-5.1/vendor/serde_json/src/de.rs create mode 100644 bash-5.1/vendor/serde_json/src/error.rs create mode 100644 bash-5.1/vendor/serde_json/src/lib.rs create mode 100644 bash-5.1/vendor/serde_json/src/macros.rs create mode 100644 bash-5.1/vendor/serde_json/src/map.rs create mode 100644 bash-5.1/vendor/serde_json/src/number.rs create mode 100644 bash-5.1/vendor/serde_json/src/read.rs create mode 100644 bash-5.1/vendor/serde_json/src/ser.rs create mode 100644 bash-5.1/vendor/serde_json/src/value.rs create mode 100644 bash-5.1/vendor/siphasher/.cargo-checksum.json create mode 100644 bash-5.1/vendor/siphasher/COPYING create mode 100644 bash-5.1/vendor/siphasher/Cargo.toml create mode 100644 bash-5.1/vendor/siphasher/README.md create mode 100644 bash-5.1/vendor/siphasher/src/lib.rs create mode 100644 bash-5.1/vendor/siphasher/src/sip.rs create mode 100644 bash-5.1/vendor/siphasher/src/sip128.rs create mode 100644 bash-5.1/vendor/siphasher/src/tests.rs create mode 100644 bash-5.1/vendor/siphasher/src/tests128.rs create mode 100644 bash-5.1/vendor/slab/src/builder.rs create mode 100644 bash-5.1/vendor/smallvec/debug_metadata/README.md create mode 100644 bash-5.1/vendor/smallvec/debug_metadata/smallvec.natvis create mode 100644 bash-5.1/vendor/smallvec/tests/debugger_visualizer.rs create mode 100644 bash-5.1/vendor/static_assertions/.cargo-checksum.json create mode 100644 bash-5.1/vendor/static_assertions/CHANGELOG.md create mode 100644 bash-5.1/vendor/static_assertions/Cargo.toml create mode 100644 bash-5.1/vendor/static_assertions/LICENSE-APACHE create mode 100644 bash-5.1/vendor/static_assertions/LICENSE-MIT create mode 100644 bash-5.1/vendor/static_assertions/README.md create mode 100644 bash-5.1/vendor/static_assertions/src/assert_cfg.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_eq_align.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_eq_size.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_fields.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_impl.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_obj_safe.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_trait.rs create mode 100644 bash-5.1/vendor/static_assertions/src/assert_type.rs create mode 100644 bash-5.1/vendor/static_assertions/src/const_assert.rs create mode 100644 bash-5.1/vendor/static_assertions/src/lib.rs create mode 100644 bash-5.1/vendor/strsim/.cargo-checksum.json create mode 100644 bash-5.1/vendor/strsim/CHANGELOG.md create mode 100644 bash-5.1/vendor/strsim/Cargo.toml create mode 100644 bash-5.1/vendor/strsim/LICENSE create mode 100644 bash-5.1/vendor/strsim/README.md create mode 100644 bash-5.1/vendor/strsim/appveyor.yml create mode 100644 bash-5.1/vendor/strsim/benches/benches.rs create mode 100755 bash-5.1/vendor/strsim/dev create mode 100644 bash-5.1/vendor/strsim/src/lib.rs create mode 100644 bash-5.1/vendor/strsim/tests/lib.rs create mode 100644 bash-5.1/vendor/syn/src/drops.rs create mode 100644 bash-5.1/vendor/syn/tests/regression/issue1235.rs create mode 100644 bash-5.1/vendor/syntex/.cargo-checksum.json create mode 100644 bash-5.1/vendor/syntex/Cargo.toml create mode 100644 bash-5.1/vendor/syntex/src/error.rs create mode 100644 bash-5.1/vendor/syntex/src/lib.rs create mode 100644 bash-5.1/vendor/syntex/src/registry.rs create mode 100644 bash-5.1/vendor/syntex/src/resolver.rs create mode 100644 bash-5.1/vendor/syntex/src/stack.rs create mode 100644 bash-5.1/vendor/syntex_errors/.cargo-checksum.json create mode 100644 bash-5.1/vendor/syntex_errors/Cargo.toml create mode 100644 bash-5.1/vendor/syntex_errors/src/diagnostic.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/diagnostic_builder.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/emitter.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/lib.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/lock.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/registry.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/snippet.rs create mode 100644 bash-5.1/vendor/syntex_errors/src/styled_buffer.rs create mode 100644 bash-5.1/vendor/syntex_pos/.cargo-checksum.json create mode 100644 bash-5.1/vendor/syntex_pos/Cargo.toml create mode 100644 bash-5.1/vendor/syntex_pos/src/lib.rs create mode 100644 bash-5.1/vendor/syntex_syntax/.cargo-checksum.json create mode 100644 bash-5.1/vendor/syntex_syntax/Cargo.toml create mode 100644 bash-5.1/vendor/syntex_syntax/src/abi.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ast.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/attr.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/codemap.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/config.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/diagnostic_list.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/diagnostics/macros.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/diagnostics/metadata.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/diagnostics/plugin.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/entry.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/base.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/build.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/decorator.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/env.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/expand.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/hygiene.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/placeholders.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/proc_macro_shim.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/quote.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/source_util.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_parser.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_rules.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ext/tt/transcribe.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/feature_gate.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/fold.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/json.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/lib.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/attr.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/classify.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/common.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/lexer/comments.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/lexer/mod.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/lexer/unicode_chars.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/mod.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/obsolete.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/parser.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/parse/token.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/print/pp.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/print/pprust.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/ptr.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/show_span.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/std_inject.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/str.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/symbol.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/test.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/test_snippet.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/tokenstream.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/lev_distance.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/move_map.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/node_count.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/parser.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/parser_testing.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/small_vector.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/util/thin_vec.rs create mode 100644 bash-5.1/vendor/syntex_syntax/src/visit.rs create mode 100644 bash-5.1/vendor/target_build_utils/.cargo-checksum.json create mode 100644 bash-5.1/vendor/target_build_utils/Cargo.toml create mode 100644 bash-5.1/vendor/target_build_utils/README.md create mode 100644 bash-5.1/vendor/target_build_utils/appveyor.yml create mode 100644 bash-5.1/vendor/target_build_utils/build.rs create mode 100644 bash-5.1/vendor/target_build_utils/src/changelog.rs create mode 100644 bash-5.1/vendor/target_build_utils/src/lib.rs create mode 100644 bash-5.1/vendor/target_build_utils/src/my-great-target.json create mode 100644 bash-5.1/vendor/term/.cargo-checksum.json create mode 100644 bash-5.1/vendor/term/Cargo.toml create mode 100644 bash-5.1/vendor/term/LICENSE-APACHE create mode 100644 bash-5.1/vendor/term/LICENSE-MIT create mode 100644 bash-5.1/vendor/term/README.md create mode 100644 bash-5.1/vendor/term/appveyor.yml create mode 100644 bash-5.1/vendor/term/rustfmt.toml create mode 100644 bash-5.1/vendor/term/scripts/id_rsa.enc create mode 100644 bash-5.1/vendor/term/scripts/travis-doc-upload.cfg create mode 100644 bash-5.1/vendor/term/src/lib.rs create mode 100644 bash-5.1/vendor/term/src/terminfo/mod.rs create mode 100644 bash-5.1/vendor/term/src/terminfo/parm.rs create mode 100644 bash-5.1/vendor/term/src/terminfo/parser/compiled.rs create mode 100644 bash-5.1/vendor/term/src/terminfo/parser/names.rs create mode 100644 bash-5.1/vendor/term/src/terminfo/searcher.rs create mode 100644 bash-5.1/vendor/term/src/win.rs create mode 100644 bash-5.1/vendor/term/tests/data/dumb create mode 100644 bash-5.1/vendor/term/tests/data/linux create mode 100644 bash-5.1/vendor/term/tests/data/linux-16color create mode 100644 bash-5.1/vendor/term/tests/data/linux-basic create mode 100644 bash-5.1/vendor/term/tests/data/linux-c create mode 100644 bash-5.1/vendor/term/tests/data/linux-c-nc create mode 100644 bash-5.1/vendor/term/tests/data/linux-koi8 create mode 100644 bash-5.1/vendor/term/tests/data/linux-koi8r create mode 100644 bash-5.1/vendor/term/tests/data/linux-lat create mode 100644 bash-5.1/vendor/term/tests/data/linux-m create mode 100644 bash-5.1/vendor/term/tests/data/linux-nic create mode 100644 bash-5.1/vendor/term/tests/data/linux-vt create mode 100644 bash-5.1/vendor/term/tests/data/linux2.2 create mode 100644 bash-5.1/vendor/term/tests/data/linux2.6 create mode 100644 bash-5.1/vendor/term/tests/data/linux2.6.26 create mode 100644 bash-5.1/vendor/term/tests/data/linux3.0 create mode 100644 bash-5.1/vendor/term/tests/data/rxvt create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-16color create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-256color create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-88color create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-basic create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-color create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-cygwin create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-cygwin-native create mode 100644 bash-5.1/vendor/term/tests/data/rxvt-xpm create mode 100644 bash-5.1/vendor/term/tests/data/screen create mode 100644 bash-5.1/vendor/term/tests/data/screen-256color create mode 100644 bash-5.1/vendor/term/tests/data/xterm create mode 100644 bash-5.1/vendor/term/tests/data/xterm-256color create mode 100644 bash-5.1/vendor/term/tests/terminfo.rs create mode 100644 bash-5.1/vendor/textwrap/.cargo-checksum.json create mode 100644 bash-5.1/vendor/textwrap/Cargo.toml create mode 100644 bash-5.1/vendor/textwrap/LICENSE create mode 100644 bash-5.1/vendor/textwrap/README.md create mode 100644 bash-5.1/vendor/textwrap/benches/linear.rs create mode 100644 bash-5.1/vendor/textwrap/examples/layout.rs create mode 100644 bash-5.1/vendor/textwrap/examples/termwidth.rs create mode 100644 bash-5.1/vendor/textwrap/src/indentation.rs create mode 100644 bash-5.1/vendor/textwrap/src/lib.rs create mode 100644 bash-5.1/vendor/textwrap/src/splitting.rs create mode 100644 bash-5.1/vendor/textwrap/tests/version-numbers.rs create mode 100644 bash-5.1/vendor/thiserror/build.rs create mode 100644 bash-5.1/vendor/thiserror/src/provide.rs create mode 100644 bash-5.1/vendor/thiserror/tests/test_deprecated.rs create mode 100644 bash-5.1/vendor/thread_local/.cargo-checksum.json create mode 100644 bash-5.1/vendor/thread_local/Cargo.toml create mode 100644 bash-5.1/vendor/thread_local/LICENSE-APACHE create mode 100644 bash-5.1/vendor/thread_local/LICENSE-MIT create mode 100644 bash-5.1/vendor/thread_local/README.md create mode 100644 bash-5.1/vendor/thread_local/benches/thread_local.rs create mode 100644 bash-5.1/vendor/thread_local/src/lib.rs create mode 100644 bash-5.1/vendor/thread_local/src/thread_id.rs create mode 100644 bash-5.1/vendor/thread_local/src/unreachable.rs create mode 100644 bash-5.1/vendor/tinystr/LICENSE create mode 100644 bash-5.1/vendor/tinystr/benches/common/mod.rs create mode 100644 bash-5.1/vendor/tinystr/benches/overview.rs create mode 100644 bash-5.1/vendor/tinystr/benches/read.rs create mode 100644 bash-5.1/vendor/tinystr/benches/serde.rs create mode 100644 bash-5.1/vendor/tinystr/src/ascii.rs create mode 100644 bash-5.1/vendor/tinystr/src/asciibyte.rs create mode 100644 bash-5.1/vendor/tinystr/src/databake.rs create mode 100644 bash-5.1/vendor/tinystr/src/error.rs create mode 100644 bash-5.1/vendor/tinystr/src/int_ops.rs create mode 100644 bash-5.1/vendor/tinystr/src/macros.rs create mode 100644 bash-5.1/vendor/tinystr/src/serde.rs create mode 100644 bash-5.1/vendor/tinystr/src/ule.rs create mode 100644 bash-5.1/vendor/tinystr/tests/serde.rs create mode 100644 bash-5.1/vendor/ucd-util/.cargo-checksum.json create mode 100644 bash-5.1/vendor/ucd-util/Cargo.toml create mode 100644 bash-5.1/vendor/ucd-util/LICENSE-APACHE create mode 100644 bash-5.1/vendor/ucd-util/LICENSE-MIT create mode 100644 bash-5.1/vendor/ucd-util/LICENSE-UNICODE create mode 100644 bash-5.1/vendor/ucd-util/README.md create mode 100644 bash-5.1/vendor/ucd-util/src/hangul.rs create mode 100644 bash-5.1/vendor/ucd-util/src/ideograph.rs create mode 100644 bash-5.1/vendor/ucd-util/src/lib.rs create mode 100644 bash-5.1/vendor/ucd-util/src/name.rs create mode 100644 bash-5.1/vendor/ucd-util/src/property.rs create mode 100644 bash-5.1/vendor/ucd-util/src/unicode_tables/jamo_short_name.rs create mode 100644 bash-5.1/vendor/ucd-util/src/unicode_tables/mod.rs create mode 100644 bash-5.1/vendor/ucd-util/src/unicode_tables/property_names.rs create mode 100644 bash-5.1/vendor/ucd-util/src/unicode_tables/property_values.rs create mode 100644 bash-5.1/vendor/unic-langid-impl/tests/canonicalize_test.rs create mode 100644 bash-5.1/vendor/unic-langid-impl/tests/fixtures.rs create mode 100644 bash-5.1/vendor/unic-langid-impl/tests/language_identifier_test.rs create mode 100644 bash-5.1/vendor/unic-langid-impl/tests/likelysubtags.rs create mode 100644 bash-5.1/vendor/unicode-ident/tests/tables/mod.rs create mode 100644 bash-5.1/vendor/unicode-ident/tests/tables/tables.rs create mode 100644 bash-5.1/vendor/unicode-width/.cargo-checksum.json create mode 100644 bash-5.1/vendor/unicode-width/COPYRIGHT create mode 100644 bash-5.1/vendor/unicode-width/Cargo.toml create mode 100644 bash-5.1/vendor/unicode-width/LICENSE-APACHE create mode 100644 bash-5.1/vendor/unicode-width/LICENSE-MIT create mode 100644 bash-5.1/vendor/unicode-width/README.md create mode 100755 bash-5.1/vendor/unicode-width/scripts/unicode.py create mode 100644 bash-5.1/vendor/unicode-width/src/lib.rs create mode 100644 bash-5.1/vendor/unicode-width/src/tables.rs create mode 100644 bash-5.1/vendor/unicode-width/src/tests.rs create mode 100644 bash-5.1/vendor/unicode-xid/.cargo-checksum.json create mode 100644 bash-5.1/vendor/unicode-xid/COPYRIGHT create mode 100644 bash-5.1/vendor/unicode-xid/Cargo.toml create mode 100644 bash-5.1/vendor/unicode-xid/LICENSE-APACHE create mode 100644 bash-5.1/vendor/unicode-xid/LICENSE-MIT create mode 100644 bash-5.1/vendor/unicode-xid/README.md create mode 100755 bash-5.1/vendor/unicode-xid/scripts/unicode.py create mode 100644 bash-5.1/vendor/unicode-xid/src/lib.rs create mode 100644 bash-5.1/vendor/unicode-xid/src/tables.rs create mode 100644 bash-5.1/vendor/unicode-xid/src/tests.rs create mode 100644 bash-5.1/vendor/utf8-ranges/.cargo-checksum.json create mode 100644 bash-5.1/vendor/utf8-ranges/COPYING create mode 100644 bash-5.1/vendor/utf8-ranges/Cargo.toml create mode 100644 bash-5.1/vendor/utf8-ranges/LICENSE-MIT create mode 100644 bash-5.1/vendor/utf8-ranges/README.md create mode 100644 bash-5.1/vendor/utf8-ranges/UNLICENSE create mode 100644 bash-5.1/vendor/utf8-ranges/benches/bench.rs create mode 100644 bash-5.1/vendor/utf8-ranges/src/char_utf8.rs create mode 100644 bash-5.1/vendor/utf8-ranges/src/lib.rs create mode 100644 bash-5.1/vendor/vec_map/.cargo-checksum.json create mode 100644 bash-5.1/vendor/vec_map/Cargo.toml create mode 100644 bash-5.1/vendor/vec_map/LICENSE-APACHE create mode 100644 bash-5.1/vendor/vec_map/LICENSE-MIT create mode 100644 bash-5.1/vendor/vec_map/README.md create mode 100644 bash-5.1/vendor/vec_map/src/lib.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/.cargo-checksum.json create mode 100644 bash-5.1/vendor/winapi-0.2.8/Cargo.toml create mode 100644 bash-5.1/vendor/winapi-0.2.8/LICENSE.md create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/activation.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/audioclient.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/audiosessiontypes.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/basetsd.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/bcrypt.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/cfg.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/cfgmgr32.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/combaseapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/commctrl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/commdlg.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/corsym.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d2d1.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d2dbasetypes.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d10shader.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d11.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d11shader.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d12.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d12sdklayers.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d12shader.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d9.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d9caps.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3d9types.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3dcommon.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/d3dcompiler.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dbghelp.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dcommon.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/devpropdef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/docobj.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dpapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dsgetdc.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dsound.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dsrole.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dwmapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dwrite.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dxgi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dxgi1_2.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dxgi1_3.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dxgi1_4.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dxgiformat.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/dxgitype.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/errhandlingapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/excpt.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/fileapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/gl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/guiddef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/heapapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/hidclass.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/hidpi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/hidsdi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/hidusage.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/hstring.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/http.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/imm.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/inaddr.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/inspectable.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ksmedia.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lib.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/libloaderapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lmaccess.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lmcons.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lmdfs.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lmerrlog.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lmjoin.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/lsalookup.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/macros.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/memoryapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/minschannel.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/minwinbase.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/minwindef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/mmdeviceapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/mmreg.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/mmsystem.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/mscat.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/mssip.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/nb30.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ncrypt.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ntdef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ntsecapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ntstatus.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/oaidl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/objbase.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/objidl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/objidlbase.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/olectl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/pdh.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/playsoundapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/processsnapshot.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/processthreadsapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/propidl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/propsys.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/prsht.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/psapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/qos.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/reason.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/restrictederrorinfo.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/roapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/roerrorapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/rpc.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/rpcdce.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/sapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/schannel.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/servprov.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/setupapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/shellapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/shellscalingapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/shlguid.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/shlobj.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/shobjidl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/shtypes.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/spapidef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/sql.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/sqltypes.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/sspi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/strmif.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/subauth.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/synchapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/sysinfoapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/threadpoolapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/timezoneapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/tlhelp32.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/unknwnbase.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/urlhist.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/urlmon.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/usb.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/usbspec.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/usp10.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/vadefs.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/vsbackup.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/vss.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/vsserror.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/vswriter.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/werapi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winbase.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/wincon.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/wincred.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/wincrypt.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/windef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/windowscodecs.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/windowsx.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winerror.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winevt.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/wingdi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winhttp.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winioctl.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winnetwk.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winnls.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winnt.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winreg.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winscard.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winsmcrd.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winsock2.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winspool.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winstring.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winsvc.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winusb.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winusbio.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/winuser.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ws2def.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ws2ipdef.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ws2spi.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/ws2tcpip.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/wtypes.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/wtypesbase.rs create mode 100644 bash-5.1/vendor/winapi-0.2.8/src/xinput.rs create mode 100644 bash-5.1/vendor/winapi-build/.cargo-checksum.json create mode 100644 bash-5.1/vendor/winapi-build/Cargo.toml create mode 100644 bash-5.1/vendor/winapi-build/src/lib.rs diff --git a/bash-5.1/.cargo/config.toml b/bash-5.1/.cargo/config.toml index cdf1653..75e93c3 100644 --- a/bash-5.1/.cargo/config.toml +++ b/bash-5.1/.cargo/config.toml @@ -1,9 +1,5 @@ -[source.crates-io] -replace-with = "vendored-sources" -[source."https://github.com/shadowsocks/crypto"] -git = "https://github.com/shadowsocks/crypto" -branch = "master" +[source.crates-io] replace-with = "vendored-sources" [source.vendored-sources] diff --git a/bash-5.1/Cargo.toml b/bash-5.1/Cargo.toml index 68e7298..87ccd3a 100644 --- a/bash-5.1/Cargo.toml +++ b/bash-5.1/Cargo.toml @@ -2,10 +2,6 @@ name = "rsbash" version = "0.1.0" edition = "2018" -build = "build.rs" - -[build-dependencies] -bindgen = "0.20.0" [lib] name = "rsbash" @@ -66,12 +62,10 @@ members=[ "builtins_rust/setattr", "builtins_rust/source", "builtins_rust/exec_cmd", - "u_src", ] [dependencies] libc = "*" - bindgen = "*" rread = {path = "./builtins_rust/read"} rhistory = {path = "./builtins_rust/history"} rkill = {path = "./builtins_rust/kill"} @@ -108,5 +102,3 @@ members=[ rwait = {path = "./builtins_rust/wait"} rdeclare = {path = "./builtins_rust/declare"} rexec_cmd = {path = "./builtins_rust/exec_cmd"} - - r_main = {path = "./u_src"} diff --git a/bash-5.1/Makefile.in b/bash-5.1/Makefile.in index d94c718..dd1c8a4 100644 --- a/bash-5.1/Makefile.in +++ b/bash-5.1/Makefile.in @@ -139,7 +139,7 @@ LOCALE_DEFS = -DLOCALEDIR='"$(localedir)"' -DPACKAGE='"$(PACKAGE)"' LOCAL_LIBS = @LOCAL_LIBS@ -LIBS = $(BUILTINS_LIB) $(LIBRARIES) @LIBS@ -lrt -lpthread -L./target/debug -lralias -lrbind -lrbreak -lrbuiltin -lrcaller -lrcd -lrcolon -lrcommon -lcommand -lrcomplete -lrdeclare -lrecho -lrenable -lreval -lrexec -lrexit -lrfc -lrfg_bg -lrgetopts -lrhash -lrexit -lrhelp -lrhistory -lrjobs -lrkill -lrmapfile -lrpushd -lrread -lrlet -lrreturn -lrset -lrsetattr -lrshift -lrshopt -lrsource -lrsuspend -lrtest -lrtimes -lrtrap -lrtype -lrulimit -lrumask -lrwait -lrprintf -lrexec_cmd -lr_main +LIBS = $(BUILTINS_LIB) $(LIBRARIES) @LIBS@ -lrt -lpthread -L./target/debug -lralias -lrbind -lrbreak -lrbuiltin -lrcaller -lrcd -lrcolon -lrcommon -lcommand -lrcomplete -lrdeclare -lrecho -lrenable -lreval -lrexec -lrexit -lrfc -lrfg_bg -lrgetopts -lrhash -lrexit -lrhelp -lrhistory -lrjobs -lrkill -lrmapfile -lrpushd -lrread -lrlet -lrreturn -lrset -lrsetattr -lrshift -lrshopt -lrsource -lrsuspend -lrtest -lrtimes -lrtrap -lrtype -lrulimit -lrumask -lrwait -lrprintf -lrexec_cmd LIBS_FOR_BUILD = STATIC_LD = @STATIC_LD@ @@ -571,7 +571,7 @@ LANGSRC = $(srcdir)/$(LANGSUBDIR) RUST_DIR = $(top_builddir)/builtins_rust #RUST_TARGET_LIB = $(top_builddir)/target/debug/librjobs.a $(top_builddir)/target/debug/librread.a -RUST_BUILTINS_DIRS = $(RUST_DIR)/alias $(RUST_DIR)/bind $(RUST_DIR)/break_1 $(RUST_DIR)/builtin $(RUST_DIR)/caller $(RUST_DIR)/cd $(RUST_DIR)/colon $(RUST_DIR)/command $(RUST_DIR)/common $(RUST_DIR)/complete $(RUST_DIR)/declare $(RUST_DIR)/echo $(RUST_DIR)/enable $(RUST_DIR)/eval $(RUST_DIR)/exit $(RUST_DIR)/fc $(RUST_DIR)/fg_bg $(RUST_DIR)/getopts $(RUST_DIR)/hash $(RUST_DIR)/help $(RUST_DIR)/history $(RUST_DIR)/jobs $(RUST_DIR)/kill $(RUST_DIR)/mapfile $(RUST_DIR)/printf $(RUST_DIR)/pushd $(RUST_DIR)/read $(RUST_DIR)/rlet $(RUST_DIR)/rreturn $(RUST_DIR)/set $(RUST_DIR)/setattr $(RUST_DIR)/shift $(RUST_DIR)/shopt $(RUST_DIR)/source $(RUST_DIR)/suspend $(RUST_DIR)/test $(RUST_DIR)/times $(RUST_DIR)/trap $(RUST_DIR)/type $(RUST_DIR)/ulimit $(RUST_DIR)/umask $(RUST_DIR)/wait $(RUST_DIR)/exec $(RUST_DIR)/exec_cmd $(RUST_DIR)/u_src +RUST_BUILTINS_DIRS = $(RUST_DIR)/alias $(RUST_DIR)/bind $(RUST_DIR)/break_1 $(RUST_DIR)/builtin $(RUST_DIR)/caller $(RUST_DIR)/cd $(RUST_DIR)/colon $(RUST_DIR)/command $(RUST_DIR)/common $(RUST_DIR)/complete $(RUST_DIR)/declare $(RUST_DIR)/echo $(RUST_DIR)/enable $(RUST_DIR)/eval $(RUST_DIR)/exit $(RUST_DIR)/fc $(RUST_DIR)/fg_bg $(RUST_DIR)/getopts $(RUST_DIR)/hash $(RUST_DIR)/help $(RUST_DIR)/history $(RUST_DIR)/jobs $(RUST_DIR)/kill $(RUST_DIR)/mapfile $(RUST_DIR)/printf $(RUST_DIR)/pushd $(RUST_DIR)/read $(RUST_DIR)/rlet $(RUST_DIR)/rreturn $(RUST_DIR)/set $(RUST_DIR)/setattr $(RUST_DIR)/shift $(RUST_DIR)/shopt $(RUST_DIR)/source $(RUST_DIR)/suspend $(RUST_DIR)/test $(RUST_DIR)/times $(RUST_DIR)/trap $(RUST_DIR)/type $(RUST_DIR)/ulimit $(RUST_DIR)/umask $(RUST_DIR)/wait $(RUST_DIR)/exec $(RUST_DIR)/exec_cmd # Keep GNU Make from exporting the entire environment for small machines. diff --git a/bash-5.1/builtins/exit.def b/bash-5.1/builtins/exit.def index d79bcd6..72d9dcb 100644 --- a/bash-5.1/builtins/exit.def +++ b/bash-5.1/builtins/exit.def @@ -58,7 +58,6 @@ int exit_builtin (list) WORD_LIST *list; { -printf("exit_builtin\n"); r_exit_builtin(list); CHECK_HELPOPT (list); diff --git a/bash-5.1/builtins_rust/history/src/lib.rs b/bash-5.1/builtins_rust/history/src/lib.rs index e1d9fd7..31a3205 100644 --- a/bash-5.1/builtins_rust/history/src/lib.rs +++ b/bash-5.1/builtins_rust/history/src/lib.rs @@ -328,8 +328,10 @@ unsafe { builtin_error( c_err.as_ptr(), (*((*list).word)).word); result = EXECUTION_FAILURE; } else { - std::io::stdout().lock().write_all(CStr::from_ptr(s).to_bytes()).unwrap(); - libc::putchar(b'\n' as c_int); + println!("{}",CStr::from_ptr(s).to_str().unwrap()); + //println!("{}",String::from(CStr::from_ptr(s).to_str().unwrap())); + //std::io::stdout().lock().write_all(CStr::from_ptr(s).to_bytes()).unwrap(); + //libc::putchar(b'\n' as c_int); } if !s.is_null() { libc::free(s as *mut c_void); diff --git a/bash-5.1/parse.y b/bash-5.1/parse.y index 2449fa8..ffda9f8 100644 --- a/bash-5.1/parse.y +++ b/bash-5.1/parse.y @@ -323,6 +323,7 @@ static REDIRECTEE redir; static FILE *yyoutstream; static FILE *yyerrstream; +extern int r_exit_builtin ( WORD_LIST *list); %} %union { @@ -6443,8 +6444,8 @@ handle_eof_input_unit () reset_parser (); last_shell_builtin = this_shell_builtin; - this_shell_builtin = exit_builtin; - exit_builtin ((WORD_LIST *)NULL); + this_shell_builtin = r_exit_builtin; + r_exit_builtin ((WORD_LIST *)NULL); } else { diff --git a/bash-5.1/vendor/aho-corasick/.cargo-checksum.json b/bash-5.1/vendor/aho-corasick/.cargo-checksum.json new file mode 100644 index 0000000..b41f859 --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYING":"01c266bced4a434da0051174d6bee16a4c82cf634e2679b6155d40d75012390f","Cargo.toml":"bbc07b82832ec4c2f64daa403bd17b8bc807d1344495d7616848c67ba843d2b4","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","README.md":"fe558ce496eb36dacb88ae744a58c6eb7a65021676dde34779796a8fc8f4ac1e","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","benches/bench.rs":"c74b297ed2217e4784614573a8b44c61dfe5173985c43616e43a3f608973ff2e","benches/random.txt":"9386fb3efedc7ffbd09fb49088347f1056bc2d90a861009fa2f804cdb714efcb","examples/dict-search.rs":"0dac88736039262dfb8df9ff85ece18de90dd4da9b8b895cf4d57bf33167b224","src/autiter.rs":"b3bd067bf6c25708109870afbb5d09e9a04d0f2f596f59c368e42ddbc7c65f93","src/full.rs":"acb6389d210e7bc4125f0ebb6f268b712e60ec50b58b9c4094a8083bb8f4caf2","src/lib.rs":"76014f2b0fa86ff4d08adfda31a431911e9032f6e40c40fe00fcbc1331073d5b","src/main.rs":"fc867cb5f0b02d0f49ecab06b72c05a247cbcf3bf9228c235de8e787bda7bef5"},"package":"81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5"} \ No newline at end of file diff --git a/bash-5.1/vendor/aho-corasick/COPYING b/bash-5.1/vendor/aho-corasick/COPYING new file mode 100644 index 0000000..bb9c20a --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/COPYING @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff --git a/bash-5.1/vendor/aho-corasick/Cargo.toml b/bash-5.1/vendor/aho-corasick/Cargo.toml new file mode 100644 index 0000000..0e79959 --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/Cargo.toml @@ -0,0 +1,72 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "aho-corasick" +version = "0.6.10" +authors = ["Andrew Gallant "] +exclude = ["/benches/sherlock.txt", "/ci/*", "/.travis.yml", "/Makefile", "/ctags.rust", "/session.vim"] +description = "Fast multiple substring searching with finite state machines." +homepage = "https://github.com/BurntSushi/aho-corasick" +readme = "README.md" +keywords = ["string", "search", "text", "aho", "corasick"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/aho-corasick" +[profile.test] +debug = true + +[profile.bench] +debug = true + +[profile.release] +debug = true + +[lib] +name = "aho_corasick" + +[[bin]] +name = "aho-corasick-dot" +path = "src/main.rs" +test = false +bench = false +doc = false + +[[bench]] +name = "bench" +path = "benches/bench.rs" +test = false +bench = true +[dependencies.memchr] +version = "2" +[dev-dependencies.csv] +version = "1" + +[dev-dependencies.docopt] +version = "1" + +[dev-dependencies.memmap] +version = "0.6" + +[dev-dependencies.quickcheck] +version = "0.7" +default-features = false + +[dev-dependencies.rand] +version = "0.5" + +[dev-dependencies.serde] +version = "1" + +[dev-dependencies.serde_derive] +version = "1" +[badges.travis-ci] +repository = "BurntSushi/aho-corasick" diff --git a/bash-5.1/vendor/aho-corasick/LICENSE-MIT b/bash-5.1/vendor/aho-corasick/LICENSE-MIT new file mode 100644 index 0000000..3b0a5dc --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bash-5.1/vendor/aho-corasick/README.md b/bash-5.1/vendor/aho-corasick/README.md new file mode 100644 index 0000000..1ce40d5 --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/README.md @@ -0,0 +1,55 @@ +This crate provides an implementation of the +[Aho-Corasick](http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm) +algorithm. Its intended use case is for fast substring matching, particularly +when matching multiple substrings in a search text. This is achieved by +compiling the substrings into a finite state machine. + +This implementation provides optimal algorithmic time complexity. Construction +of the finite state machine is `O(p)` where `p` is the length of the substrings +concatenated. Matching against search text is `O(n + p + m)`, where `n` is +the length of the search text and `m` is the number of matches. + +[![Build status](https://api.travis-ci.org/BurntSushi/aho-corasick.png)](https://travis-ci.org/BurntSushi/aho-corasick) +[![](http://meritbadge.herokuapp.com/aho-corasick)](https://crates.io/crates/aho-corasick) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + + +### Documentation + +[https://docs.rs/aho-corasick/](https://docs.rs/aho-corasick/). + + +### Example + +The documentation contains several examples, and there is a more complete +example as a full program in `examples/dict-search.rs`. + +Here is a quick example showing simple substring matching: + +```rust +use aho_corasick::{Automaton, AcAutomaton, Match}; + +let aut = AcAutomaton::new(vec!["apple", "maple"]); +let mut it = aut.find("I like maple apples."); +assert_eq!(it.next(), Some(Match { + pati: 1, + start: 7, + end: 12, +})); +assert_eq!(it.next(), Some(Match { + pati: 0, + start: 13, + end: 18, +})); +assert_eq!(it.next(), None); +``` + + +### Alternatives + +Aho-Corasick is useful for matching multiple substrings against many long +strings. If your long string is fixed, then you might consider building a +[suffix array](https://github.com/BurntSushi/suffix) +of the search text (which takes `O(n)` time). Matches can then be found in +`O(p log(n))` time. diff --git a/bash-5.1/vendor/aho-corasick/UNLICENSE b/bash-5.1/vendor/aho-corasick/UNLICENSE new file mode 100644 index 0000000..68a49da --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/bash-5.1/vendor/aho-corasick/benches/bench.rs b/bash-5.1/vendor/aho-corasick/benches/bench.rs new file mode 100644 index 0000000..0e68e2a --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/benches/bench.rs @@ -0,0 +1,373 @@ +#![feature(test)] + +extern crate aho_corasick; +extern crate test; + +use std::iter; + +use aho_corasick::{Automaton, AcAutomaton, Transitions}; +use test::Bencher; + +const HAYSTACK_RANDOM: &'static str = include_str!("random.txt"); +const HAYSTACK_SHERLOCK: &'static str = include_str!("sherlock.txt"); + +fn bench_aut_no_match, T: Transitions>( + b: &mut Bencher, + aut: AcAutomaton, + haystack: &str, +) { + b.bytes = haystack.len() as u64; + b.iter(|| assert!(aut.find(haystack).next().is_none())); +} + +fn bench_box_aut_no_match, T: Transitions>( + b: &mut Bencher, + aut: AcAutomaton, + haystack: &str, +) { + b.bytes = haystack.len() as u64; + let aut: &Automaton

= &aut; + b.iter(|| assert!(Automaton::find(&aut, haystack).next().is_none())); +} + +fn bench_full_aut_no_match, T: Transitions>( + b: &mut Bencher, + aut: AcAutomaton, + haystack: &str, +) { + let aut = aut.into_full(); + b.bytes = haystack.len() as u64; + b.iter(|| assert!(aut.find(haystack).next().is_none())); +} + +fn bench_full_aut_overlapping_no_match, T: Transitions>( + b: &mut Bencher, + aut: AcAutomaton, + haystack: &str, +) { + let aut = aut.into_full(); + b.bytes = haystack.len() as u64; + b.iter(|| assert!(aut.find_overlapping(haystack).count() == 0)); +} + +fn bench_naive_no_match(b: &mut Bencher, needles: Vec, haystack: &str) + where S: Into { + b.bytes = haystack.len() as u64; + let needles: Vec = needles.into_iter().map(Into::into).collect(); + b.iter(|| assert!(!naive_find(&needles, haystack))); +} + +#[bench] +fn bench_construction(b: &mut Bencher) { + b.iter(|| { + AcAutomaton::new(test::black_box( + [ + "ADL", "ADl", "AdL", "Adl", "BAK", "BAk", "BAK", "BaK", "Bak", "BaK", "HOL", + "HOl", "HoL", "Hol", "IRE", "IRe", "IrE", "Ire", "JOH", "JOh", "JoH", "Joh", "SHE", + "SHe", "ShE", "She", "WAT", "WAt", "WaT", "Wat", "aDL", "aDl", "adL", "adl", "bAK", + "bAk", "bAK", "baK", "bak", "baK", "hOL", "hOl", "hoL", "hol", "iRE", "iRe", + "irE", "ire", "jOH", "jOh", "joH", "joh", "sHE", "sHe", "shE", "she", "wAT", "wAt", + "waT", "wat", "ſHE", "ſHe", "ſhE", "ſhe", + ].iter() + .map(|x| *x), + )) + }) +} + +#[bench] +fn bench_full_construction(b: &mut Bencher) { + b.iter(|| { + AcAutomaton::new(test::black_box( + [ + "ADL", "ADl", "AdL", "Adl", "BAK", "BAk", "BAK", "BaK", "Bak", "BaK", "HOL", + "HOl", "HoL", "Hol", "IRE", "IRe", "IrE", "Ire", "JOH", "JOh", "JoH", "Joh", "SHE", + "SHe", "ShE", "She", "WAT", "WAt", "WaT", "Wat", "aDL", "aDl", "adL", "adl", "bAK", + "bAk", "bAK", "baK", "bak", "baK", "hOL", "hOl", "hoL", "hol", "iRE", "iRe", + "irE", "ire", "jOH", "jOh", "joH", "joh", "sHE", "sHe", "shE", "she", "wAT", "wAt", + "waT", "wat", "ſHE", "ſHe", "ſhE", "ſhe", + ].iter() + .map(|x| *x), + )).into_full() + }) +} + +fn haystack_same(letter: char) -> String { + iter::repeat(letter).take(10000).collect() +} + +macro_rules! aut_benches { + ($prefix:ident, $aut:expr, $bench:expr) => { + mod $prefix { +#![allow(unused_imports)] +use aho_corasick::{Automaton, AcAutomaton, Sparse}; +use test::Bencher; + +use super::{ + HAYSTACK_RANDOM, haystack_same, + bench_aut_no_match, bench_box_aut_no_match, + bench_full_aut_no_match, bench_full_aut_overlapping_no_match, +}; + +#[bench] +fn ac_one_byte(b: &mut Bencher) { + let aut = $aut(vec!["a"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_one_prefix_byte_no_match(b: &mut Bencher) { + let aut = $aut(vec!["zbc"]); + $bench(b, aut, &haystack_same('y')); +} + +#[bench] +fn ac_one_prefix_byte_every_match(b: &mut Bencher) { + // We lose the benefit of `memchr` because the first byte matches + // in every position in the haystack. + let aut = $aut(vec!["zbc"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_one_prefix_byte_random(b: &mut Bencher) { + let aut = $aut(vec!["zbc\x00"]); + $bench(b, aut, HAYSTACK_RANDOM); +} + +#[bench] +fn ac_two_bytes(b: &mut Bencher) { + let aut = $aut(vec!["a", "b"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_two_diff_prefix(b: &mut Bencher) { + let aut = $aut(vec!["abcdef", "bmnopq"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_two_one_prefix_byte_every_match(b: &mut Bencher) { + let aut = $aut(vec!["zbcdef", "zmnopq"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_two_one_prefix_byte_no_match(b: &mut Bencher) { + let aut = $aut(vec!["zbcdef", "zmnopq"]); + $bench(b, aut, &haystack_same('y')); +} + +#[bench] +fn ac_two_one_prefix_byte_random(b: &mut Bencher) { + let aut = $aut(vec!["zbcdef\x00", "zmnopq\x00"]); + $bench(b, aut, HAYSTACK_RANDOM); +} + +#[bench] +fn ac_ten_bytes(b: &mut Bencher) { + let aut = $aut(vec!["a", "b", "c", "d", "e", + "f", "g", "h", "i", "j"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_ten_diff_prefix(b: &mut Bencher) { + let aut = $aut(vec!["abcdef", "bbcdef", "cbcdef", "dbcdef", + "ebcdef", "fbcdef", "gbcdef", "hbcdef", + "ibcdef", "jbcdef"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_ten_one_prefix_byte_every_match(b: &mut Bencher) { + let aut = $aut(vec!["zacdef", "zbcdef", "zccdef", "zdcdef", + "zecdef", "zfcdef", "zgcdef", "zhcdef", + "zicdef", "zjcdef"]); + $bench(b, aut, &haystack_same('z')); +} + +#[bench] +fn ac_ten_one_prefix_byte_no_match(b: &mut Bencher) { + let aut = $aut(vec!["zacdef", "zbcdef", "zccdef", "zdcdef", + "zecdef", "zfcdef", "zgcdef", "zhcdef", + "zicdef", "zjcdef"]); + $bench(b, aut, &haystack_same('y')); +} + +#[bench] +fn ac_ten_one_prefix_byte_random(b: &mut Bencher) { + let aut = $aut(vec!["zacdef\x00", "zbcdef\x00", "zccdef\x00", + "zdcdef\x00", "zecdef\x00", "zfcdef\x00", + "zgcdef\x00", "zhcdef\x00", "zicdef\x00", + "zjcdef\x00"]); + $bench(b, aut, HAYSTACK_RANDOM); +} + } + } +} + +aut_benches!(dense, AcAutomaton::new, bench_aut_no_match); +aut_benches!(dense_boxed, AcAutomaton::new, bench_box_aut_no_match); +aut_benches!(sparse, AcAutomaton::<&str, Sparse>::with_transitions, + bench_aut_no_match); +aut_benches!(full, AcAutomaton::new, bench_full_aut_no_match); +aut_benches!(full_overlap, AcAutomaton::new, bench_full_aut_overlapping_no_match); + +// A naive multi-pattern search. +// We use this to benchmark *throughput*, so it should never match anything. +fn naive_find(needles: &[String], haystack: &str) -> bool { + for hi in 0..haystack.len() { + let rest = &haystack.as_bytes()[hi..]; + for needle in needles { + let needle = needle.as_bytes(); + if needle.len() > rest.len() { + continue; + } + if needle == &rest[..needle.len()] { + // should never happen in throughput benchmarks. + return true; + } + } + } + false +} + +#[bench] +fn naive_one_byte(b: &mut Bencher) { + bench_naive_no_match(b, vec!["a"], &haystack_same('z')); +} + +#[bench] +fn naive_one_prefix_byte_no_match(b: &mut Bencher) { + bench_naive_no_match(b, vec!["zbc"], &haystack_same('y')); +} + +#[bench] +fn naive_one_prefix_byte_every_match(b: &mut Bencher) { + bench_naive_no_match(b, vec!["zbc"], &haystack_same('z')); +} + +#[bench] +fn naive_one_prefix_byte_random(b: &mut Bencher) { + bench_naive_no_match(b, vec!["zbc\x00"], HAYSTACK_RANDOM); +} + +#[bench] +fn naive_two_bytes(b: &mut Bencher) { + bench_naive_no_match(b, vec!["a", "b"], &haystack_same('z')); +} + +#[bench] +fn naive_two_diff_prefix(b: &mut Bencher) { + bench_naive_no_match(b, vec!["abcdef", "bmnopq"], &haystack_same('z')); +} + +#[bench] +fn naive_two_one_prefix_byte_every_match(b: &mut Bencher) { + bench_naive_no_match(b, vec!["zbcdef", "zmnopq"], &haystack_same('z')); +} + +#[bench] +fn naive_two_one_prefix_byte_no_match(b: &mut Bencher) { + bench_naive_no_match(b, vec!["zbcdef", "zmnopq"], &haystack_same('y')); +} + +#[bench] +fn naive_two_one_prefix_byte_random(b: &mut Bencher) { + bench_naive_no_match(b, vec!["zbcdef\x00", "zmnopq\x00"], HAYSTACK_RANDOM); +} + +#[bench] +fn naive_ten_bytes(b: &mut Bencher) { + let needles = vec!["a", "b", "c", "d", "e", + "f", "g", "h", "i", "j"]; + bench_naive_no_match(b, needles, &haystack_same('z')); +} + +#[bench] +fn naive_ten_diff_prefix(b: &mut Bencher) { + let needles = vec!["abcdef", "bbcdef", "cbcdef", "dbcdef", + "ebcdef", "fbcdef", "gbcdef", "hbcdef", + "ibcdef", "jbcdef"]; + bench_naive_no_match(b, needles, &haystack_same('z')); +} + +#[bench] +fn naive_ten_one_prefix_byte_every_match(b: &mut Bencher) { + let needles = vec!["zacdef", "zbcdef", "zccdef", "zdcdef", + "zecdef", "zfcdef", "zgcdef", "zhcdef", + "zicdef", "zjcdef"]; + bench_naive_no_match(b, needles, &haystack_same('z')); +} + +#[bench] +fn naive_ten_one_prefix_byte_no_match(b: &mut Bencher) { + let needles = vec!["zacdef", "zbcdef", "zccdef", "zdcdef", + "zecdef", "zfcdef", "zgcdef", "zhcdef", + "zicdef", "zjcdef"]; + bench_naive_no_match(b, needles, &haystack_same('y')); +} + +#[bench] +fn naive_ten_one_prefix_byte_random(b: &mut Bencher) { + let needles = vec!["zacdef\x00", "zbcdef\x00", "zccdef\x00", + "zdcdef\x00", "zecdef\x00", "zfcdef\x00", + "zgcdef\x00", "zhcdef\x00", "zicdef\x00", + "zjcdef\x00"]; + bench_naive_no_match(b, needles, HAYSTACK_RANDOM); +} + + +// The organization above is just awful. Let's start over... + +mod sherlock { + use aho_corasick::{Automaton, AcAutomaton}; + use test::Bencher; + use super::HAYSTACK_SHERLOCK; + + macro_rules! sherlock { + ($name:ident, $count:expr, $pats:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let haystack = HAYSTACK_SHERLOCK; + let aut = AcAutomaton::new($pats).into_full(); + b.bytes = haystack.len() as u64; + b.iter(|| assert_eq!($count, aut.find(haystack).count())); + } + } + } + + sherlock!(name_alt1, 158, vec!["Sherlock", "Street"]); + + sherlock!(name_alt2, 558, vec!["Sherlock", "Holmes"]); + + sherlock!(name_alt3, 740, vec![ + "Sherlock", "Holmes", "Watson", "Irene", "Adler", "John", "Baker", + ]); + + sherlock!(name_alt3_nocase, 1764, vec![ + "ADL", "ADl", "AdL", "Adl", "BAK", "BAk", "BAK", "BaK", "Bak", "BaK", + "HOL", "HOl", "HoL", "Hol", "IRE", "IRe", "IrE", "Ire", "JOH", "JOh", + "JoH", "Joh", "SHE", "SHe", "ShE", "She", "WAT", "WAt", "WaT", "Wat", + "aDL", "aDl", "adL", "adl", "bAK", "bAk", "bAK", "baK", "bak", "baK", + "hOL", "hOl", "hoL", "hol", "iRE", "iRe", "irE", "ire", "jOH", "jOh", + "joH", "joh", "sHE", "sHe", "shE", "she", "wAT", "wAt", "waT", "wat", + "ſHE", "ſHe", "ſhE", "ſhe", + ]); + + sherlock!(name_alt4, 582, vec!["Sher", "Hol"]); + + sherlock!(name_alt4_nocase, 1307, vec![ + "HOL", "HOl", "HoL", "Hol", "SHE", "SHe", "ShE", "She", "hOL", "hOl", + "hoL", "hol", "sHE", "sHe", "shE", "she", "ſHE", "ſHe", "ſhE", "ſhe", + ]); + + sherlock!(name_alt5, 639, vec!["Sherlock", "Holmes", "Watson"]); + + sherlock!(name_alt5_nocase, 1442, vec![ + "HOL", "HOl", "HoL", "Hol", "SHE", "SHe", "ShE", "She", "WAT", "WAt", + "WaT", "Wat", "hOL", "hOl", "hoL", "hol", "sHE", "sHe", "shE", "she", + "wAT", "wAt", "waT", "wat", "ſHE", "ſHe", "ſhE", "ſhe", + ]); +} diff --git a/bash-5.1/vendor/aho-corasick/benches/random.txt b/bash-5.1/vendor/aho-corasick/benches/random.txt new file mode 100644 index 0000000..dfae5cd --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/benches/random.txt @@ -0,0 +1,513 @@ + +mnxnsynfvuugtbxsxbfxwreuspglnplefzwsp +tacfqcwnmodnmgnyiuvqoco +z + +qjuozfkexn +zoaxzncje +sldhqtmgxzyurfyzwazmmu +bbeuv +mzsrihycwcb +xzfqozfmlnpmrzpxxxytqs +xrg +mcplby +nmslhfgjowhzfxsvyddydnsyehdskbydbjksqtpet +indvfw +bvjvvw + +pddufodyqtyixbndtumndyz +xjjhtuvmsxhuwqulqtjhqrdqrmtbcphvyuqllocrnkpfv +zemshhz +wss +xewlrxfmgxnwgphcgefa +mbgsgbzrtthxweimcqzcaaheurdmd +osqefupespvh +z +tvvlakwzwjbrgjzfgubsmmonav +pjdskxcfgapsm +zqktqgkrcdrlskx +zwwfebhguskho +zlvvw +czwm +gojnpmboehlsazbexjjnuscqftrfufngygjdxcydib +d +afigycivicnknfxl +ljuwuopctiftfwctxecwipjnljyef +jonwbkodomzhqvlf +jdkizhognqsdogunwedjsmsdzho +zxvni +oynfjf +muvokjuqz +azuwrwtuxzfopwrcex +ixrjinlvxjmn +blaegnmbhsgsbmebwazaeguugtkowexgnqtbfkldadddv +tzabyoftyov +ctbtqbzscxzviuvcigwuwusrdro +ljynr +gnnnyyxslrhsbj +hhzlw +hijalf +rxlfqk +mhaofforwznvmcgplinludpgkucpa +gvvxsqqfmu +xxqhoyosixjfhjuxpv +faadjpvamjekreepizurntvwdynozfawsfawyms + +lcbutr +aqyxvpozkjrecrkl +lfmochahrr +ptqyomjlwo +vcmslulznx +lmlsskcihrmxauztuarydlp +beiqsrfnmvmlmybmwpektjbikvpggthpabqsgmjhnthvysuhwbigillugjsp +dfsuegseffwcsnvsrqedytblbpzbfeyfsq +kypvqctrkuds +ylqeduokzgdqaxelhftxnxbidu +bprzyayfopxdsmfhhfqowa +ymiutdtlfaaxpbtaeslv +ggago + +owpbicekdeykzfgcbgzobdvvrtetvcv +xsrlgingstiez +gyncqvq +xasohmeiwyscpehctmzmsnjklg +xsudghakxlw +dzqlfptjogzpkvwuticcyugnyopypuqqc +wlxshxbhdvuherumoppcc + +znyaptivzncvkpeyeipynqefjxjjcsgfqbnezeebtowdrbjaqjlbxwvyikrmxjwoxngqgvfpbniftnmszuxg +umwpwwyvufy +pallkjtnrmtauqxauewgygwkjjwebbkabhtxticxmxfujpxlrpzlrozfslkzfdsswlmmsbdgjwmjnummk +dhsxylejzityahtqqzmohrpzjprrsraztpnuagtyzfjdekthvdogfidksrdppr +ybc +fyukknoqfnkllkwflwempjijxgo +dltvlau +rhvrvlwsribfctuzodfqkdczfzxnetqqzflnhiyl +goxmcasmq +wljbhwkpahdotqhhrbhqzijv +lszewkgdmkezvgmbmllhpksdkoiwgkvqjmurshrptlctqsosuurndcuzjfwherotv +dudxxihygxblhgchbgzyzffb +eht +fvwxvqoltdcsd +rkuig +e +axhsacsmnicugul +rubtdlhjqndxdzzwfnkuzy +swxteuyxxsktkjgv +hzwwodlqaq +vxgecev +qnwla +vdxjuzpyoqhpmuunyffptopmeauhycs +dkzo +awrfzatzohslgvqlaezepmli +qgxatixvpkkhvkumbwmwcagtgyfljdok +amdnzstpvcqj +xsrvwvhjirzfgkessve +qezwbfltfbikbmoasvoflozsjhrljnszqiciuqmflrlqowwkoevuumh +babskcvavmtvsxqsewirucwzajjcfcqwsydydqo +ywfurpsl +edacsjjkjjewkxfoh +dcgkfpcjezurnuhiatrczcp +xsatnimwbcciu +grzmbrsvvcyigcbmcqfwiiknrohveubhyijxeyzfm +kqyewccgcqrrrznwxmoztlyseagbpyho +najju +nis +awgzdvfjkzlrsjcqfeacx +oisuflfigrjaex +desbdulyuwqxuxianyypybxwlql +ekmqgspvqpftpwswayh +egbyj +fznzprhvnnwcxgcc +wfdsueieosmugirxbymbpmfrspvrktjzguxm +qkjrufshwnfwwpbhukdjlaqvljlgubmqmhnha +hwqpudgnblhlxppbrmbznotteivuzguuwlhtkytky +w +yofkyzbpg +cenolnfnllkvhikrpttcxgqxmufvorekjruyjxmr + +hyexmpjijgzumawp +cdbevdilgopbzlo +fivelagckslkugdxprjxkylizewcptwxfhomzuituujixchadmnjoktnqa +csojvlinzmmkkfzqueamnuwkanzdzsavgohposbuoamoevehqrmcxdsuyelvvctoejzoertqormhaaxwofvjzekwt +sbkghhnhutrvwtyjaxndzyjamrhx +jjyqy +majwbnrhveuhrsbbbjrwpwuplifeseylqh +wyvutpxnkrnkuxxetjkkifpqb +dyzucmbcvgnjeecm +hz +uhnuipthxrzkqluosvk +lwqqzsdwiwvwaqfwlvubadlyizlo +jbd +oyzjeu +kydjkbsqxnbfiuesc +smeubjqrcxdvhsabzceyglqjzbfmoacmwvwjbhhxbr +uabipgecujfdfxpmdzrscdyvefizabgspqjrrkmgjt +xgvdgzryz +lw +uimob +ifhn +bqph +ole +g +wt +k +yslzrkwkundxfdibwqvucemepqxlmlpyngabbeciuzhptpjdetyngrtxrdtzmvq +ccwapidp + +bwvrgvmtshevrophy +ni +fdkplu +mdykey +i +rhsrenoetdggpjb +djmkplpeabsholx +judxtub +fooakqwvocvpcrvxqhvtmpvhkrecy +uuxscjillynilbkrgt +evtinrmilniguarqritpeipwochmdw +sxaqzjybydyvnmmjtdcgkjnqfcklbfpkdfyewgcukqoiegyfp +kg +ovrwieqhy +jcxqtkerzjwhs +xeonglszbgypafhmqcaseimzjgebkvigbqwsayrnrprtuvhsxyitfqygohgorcdnufbcyvevvgzmjrgjqqquwkszplogx +zdketqqv +yebckucwayckeezfvtnavglpjh +zorkfrwk +pad +xqaquxudybwtgixbfktinctfirjfdayh +rieknj +ebk +qzbcfywfdmhsdruhopovemafijbscagllkmhmof + +asbsnbddlobwoqatfhkbhhsymzqxjuixwreheugvngmgcuqpkjhhfwpbarqaxrwgwnjbanljlds +etevdvlc +lqyjrnmenhn +k +tsf +zczgeavcexh +jlpuxywtsrvnvluruqhecjca +ir +rikrgkmhwaosodkxgcnrexfmdrszhnmutpvwztg +bffjqovvkemctnsgeh +weysbhzixiipfithjfsk +usyzvaiyuhmksfluoirfbnsu +o +cgawpdakaszeafdtbdkqtlzkrpnoqomqvuaqcfmzgvfegovtfaonelpv +izmrcjlk +xmzemniyrzy +knqexaafsdlimdamcrprlshq +qkmqw +dntgjwsibclvposdwjuklvtejjjdjibgpyynqpgprvvaetshhmvfkcpb +otvazkrkklrxfotpopyjte +fghkcnpi +rulyaihsowvcgbzeiblhuhhfbmncqsuuqcxvseorn +exirzfmojnxcoqom +zsgpgtokun +zvamxfocorganbtlafifwdqmqtsnktbwwtewborq + +cxlnaspjqvsitjyzyriqsuorjsrvzqenisprttudxntsbqrpjtdkxnwcwgjyxmgtqljcrmrbrmyvosojzlumcmjcgfjsdehec +mvx +mt +mckr +teulvroifk +laaicc +koufy +bexmwsvyarnznebdfy +ripvviosbqijsxnjilwddaqaqemzsdarnxmfooxghoypizwtbueo +ljycycuqwfnzbambibqdixmkkvwtubepla +cis +kcg +vmbbiuuoamenzepuagpfujevfstqtndjxjchdvycfrrrowochtjdmkklgnhf +pmorrwguxkvdxpluatagaziin + +uwvzbmkmykjkmknzppklx +pnzxuvsrjunqxercsnvayhykcazdeclomdsasgkpqpiufyfqsxhj +yceizkddwojgweegcllaagpvrpo +ek +kuxxgbezqyxvfaxdwnqdgqsmneijunxzlwxkrs +ldldbrxmvtjlqxifngmactzqcygkvuteffcmvphevilabgukatqakamjlridznodcvblvlogulmcixxfimh +iuzjootuywjqklolzzhpeaynydjwtufjavbozxnzckuzdodkvkjfmhinelv +swlfkcufscfcovmghqwcrtxjukwafoeogrkgubbqgwzm +gjcylkwgzroubdssuqeykqjcmguso +fzq +srfvysoxtlylctp + +pbfeiuzwoyixews +ocvvunfsjnrtklmuuzjojw +xdjcnrpqhmpmpcwacpcdtmbsczvhllkqapzjuaf +nfnuvjz +fwnuiyqpn +wshxxxpzzxp +hibrxcfeqca + +wqhlllarl +bukcbojv +plrytapy +xm +vlgfqoyzdczqbbaxjwbjjevjhxgopuqvqcrj +vpjqfbdnsdxlbuuiqocvrhap +mgumjbvnnzgnrdru +gcgzugazxdcamrhczfzhtmdjj +uislwq +vooai +zjuqfmebuzsqngzekyajujkopvayxtdzvugwwucvlsbrnhitfotmhhmgddlzlvqrkcponictrfweuilfjiuoabkfdvpjiqjrrgi +aptjfhmrnxaq +hbs +w +mwmoxqvucwygunplzvxtxpk +fgmqmtlorfzytjdzffsosfccnfwugrsrynuej +rpmpenrhsxoefnblyumjqwvuyszyppnttuyvazjdug +zdzxraxkroknkmqgvuoqeqdtvclsvvuwmdwzfugcpteohlogxubyoebvrzbqzklvehfcqadtdrkpubfhmokzwyosogepwragcpwxo +ax +dz +de + +thvkdmnbdws + +ejmubw +umvwkaubzurf +wyxtxeluaoox +wwbioobtgmkebxo +miglgnafmdarzkeblyjctuayzyoeqnfnbtrcbymdzkzg +loavxq +kzhllgsenxlbgdbfzwbg +yxflogzsohlcycbyzegeubfflouvtuatixhjvicjegltjiy +jigqfjppafdiarc +mcnmwtachgearonfcymvjbrnljjxmlzkudvzqsarnfysmxlfrtlvjxwvpdbhvwysnvcdozfcruhjwnucdzakkilmlfgjiolcatpfusm + +n +pdjunfcz +dc +edxkkxabsbvmvifiinnoccki +bc +gwtwsvorwzfqpz +exidmexstfflkhi +s +s +c +wtcjfywlayhpbqktcepoybowtkrmnumqsg +ozclkgjdmdk +jmegtbunyexurvfexhqptnqzie +tkoenpagzwqfawlxvzaijsjqhmg +swodqfjpdqcbkc +ujokogocyaygdibgpglecis +shlmdmgonvpuaxlhrymkxtiytmv +brhk +jmsyiuomiywxhegilycjprkyfgojdo + +wzdzrgpdiosdsvkcw +odlnmsfnjrcsnflviwvawybpczdkzvdocpwrmavz +p +ubowamlskcqhdxuckrxa +fawhntiwhmdwkddnahmtajqqazpdygttqivhdiodkcpcwv +gmxujmmaufmbipaiulhurzkfdg +eixjhmbaeoybiwk +kumntgrgiofcmujlzbcopuobambsw +mnjkqiyb +iktwnsnv +hfuzcl +tqiyqvagbqgtowpjbedgjot +dfemvamelxadkztogliizdtsddoboafawficudlefo +raecmxiiibljryswntpfed +mbwrtsebkeegw +x +epp +he + +vnztrswhiusokqdkmsnpuswucvfhcthjbtam +baxlwidsgbdpzvnlj +tcbjjoadrzo +aiidahyllzzsg + +igebuubweicbssgddpmqxunrawavuglmpxrtkqsvjjtscibqiejjfgfnovokodmqcqitlteiakooupvzkwucucrfdzjvjbqbkgutoybmpfvhbutigdxhfiqfplyciz +cnrhbjdnjftwfwlwzrdkwhajgsizsi +qfntnt +okqyfnbresp +asyg +mjqdkdyggdxzwuzglays +h +ifaqcazoy +fol +vvsusbnugduxsceozmsarbp +epjwtorx +bwiuxxiyc +cw +bwogruhctwkfvbexjnwircykxyzjmats +kygiochfwlpsvmxcgmtjrgvfdptd +q +qmpqe + +z +jghffhqfoecmszunhxmzmzhlmbrvjabhrkihgjmvckhkfpaygjkg + +kfiyfgounmhlvhupswqdgws +ezzdpyqucqoocsdcjtruqpokldfkmjhqzoynirybsifyaxnaxppthjoqy +nwetlgzwrhkhtuubbkbepuhbllxspvagxrqokwnrhkbwdwtp +hlazomrhqogoaxypqaszwfxxmutvbpuuvpdffuqskcbzlwyzcssnflkwiydoveyxjnzllzhyozbsa +hwnitkwbxcyibbqsluuqywbk + +ozpfjsdrc +yoepefuy +lvmspzepnetra +genbrcrmuqfvkaouvuymoxhcxotjjhk +pcshyqgbmqdubsdajnyfqvxkqvywffzn +ukhcbyzwslqeq +otfrmcbnhbyffxqregqoufdxucjunwdhlqqeiiawbxlpqeyzzopfungrryqdykgizrhqodirvazm +dhpfhzyq +cloz +eduupqifolfekve +qiec +ishnjukvomntmdthlkajxpiwk +y +axl +tmyskjqkjsvumizlal +wvvolwewsfxhhdieuagdcuhwsgqvswpbkdkpxskloalmr +ryfmhe +z +mmbpgsyrfvzdatbjrjhuipwt +llzwizmmuulgwocowwmugtaoewkhnqxparvtynlffffdfcocdbba + +pyczkzbmcgrdnxnmezsx +gsqe +mcocxcolcynhpecstsn +opnpplkccobjuhtbhirpzfxuktmpsiwbvsgiaavvdge +wpaldxzasnrbvtugjwytvtfttrh +zxecurevkjiyxy +wtnovebcmglkktic +fdpwfgvlvovxrwh +bmwgdullzy +uzwhagxinwqifxjbcntqzqoxkmpqxhe +jrfizsnwxwnnhb +inapddlahrp + +ndtvkceobe +buskgghihdjmjlwfc +j +rkvffxwtmzoeruhlsurwtnuh +cbvkhfepkdishfpqvijzrpleuy +jzdpxjhcgqnybssfegvrnpgyehdqpgjwudbwrjbavp +xzzvgqdrdwajmdmj +vfatwsxvwfdbdhnijdujoyotwvwjipuuetichcfmvgrsnjpqaaezjtkvc +lbfoqgfshrtwgdqufwnfuitdrjydqctqixlzufkdbp +zgau +qefdpmtkecvtj +kuphldkvnzdtpd +dti +fpd +gfrliyegxsb +i +qsddsrmkyfgzrjeqnitmnypbcakh +vfbvbrpuogzhzrbmklvhji +nkz +xlufbaoblbmeub +alwuzxzmobwdukvwnkiwmuqhuxfhevogdnqtmxjptqznrk +cngpoty + +ms +qvenfg +dmeaffm +jycfgnanbmoamhmarkmjcagbp +ysqmbhopgx +jczbzgwedsp + +zxzwjrxcwdtleizjlvifjwgxiibezwxhtzywqdi +mtgnlu +xboxirdchurkfnklnpkapnqfxnhrxyseiujrznjm + +zm +atddskbghcahlhql +szshwzmmvu +befdtpouamwhiisyybispkchpjhownatawjfbx + +ennkzbrlygd +zbt +upphzpdwzmlhhhbqvjsfmbnrar +ddcs +ipbxgzyudjyongtcyygncojdufnufqpdppgvq +gc +isu +foa +wf +jdlvqxgfbowhohhyyngbcs +zjuwjyucdwblatsnywaaoftlcamfbcnw +lzrioesuhoeevczuwrnltmkahfwiu +uicggfbddqltnjyxfltbnaekncnyxsit +zkxsqkqrwrzrxgxbsgxatybfr + +ptvmfyxdcglbfipcguqthjygzqnpqssscukzawynidtchjrrxwuxifoe +w +ohu +vg +zagpowezvbniybgold +lhqseqcxteiqtgnpanpvrmvvlltxh +mtfnxn +wyodtg + +rawpbgtpbaktqzmmpzxmrlwpvvmdsl +widcfbirvswraukbmkhf +vplrueuxomjkqrtjgyxjdkexttzyozawyq +hrpbahllznvmjudzxpbbv +tlavfrxygjfipkupwnbacltcfepeg +icu +otxcu +aewazy +hl + +fmrp +qaacthwzohenzjr +xbyebba +rvkph +mkhhmh +swme +zjmdoypaktglcyzobquunvthcdwegtbywpijxd +jvkuhnxqc +gibhqgjojsxt +bodbktzomiqujtbstqiyquwvqgufphqstenxvddkvtdh +bpusrxkfi +zgp +pmxvgamydyakituvvsucsuidrlznupcsinltmrahulhepxmhoqtfvpjkxzhrrinncuh +jzgkjjhjqykzelaszvcwvvwbnzsxdeaerfnaravk +ynanrqyrxo +zsmuxofullob +brklgrcqefdyoczy +qkpls +snhqumae +iqdtzjadzzvnqvdvjfsaf +nfqfdqiramueblxkaqxbbkxwywzgdbndjjiqk +tc +kp +cpuckbjsxhtxmomfesgxdpz +oseif +ybhxbvyxrpkrexrhjzoaxxohrhsniewsrktjnaztn +ggelspdzhzbchruhbjbjidgjwdlhdycetqaswh +jkgivsngygkbqtlmoj +dwpnanfvitxg +ospxbwxp +wgvmvrnjescemdoiralbkvemalifxnyhrbdgodml +hjtsnkzknkplbzsiwmneefdkihnhsamjsrxggclyjqgpqltizi + + +sykgbuypwwhweab +nvdkkkskmtiwpoerkon +sx +sbyflwwiqylbskdlxesmylpaz +dnwcjenaluwesyywfaezznwkdwpoesxpu +kie +dslccwfryol +gfhomgfn +zprjtfqvkotktzidmoyrivall +bunvsqkysdelozemnjoeqfolruulpbipm +ullyzfahpkhkja +hwd +kvyqtprpuulgsk +zotbkcadnxmfvqmtlbxalhughceyfcibtzzj +vvpjbgxygl +hpic +mhrqd +dv +thehuzdbaacoidjoljbysnqwrrxxplrdznmgiukkvjqbopb +moszjt +rmtbunktkywqirveeqfa +kse +wbfflnatgzobjrxghjgvcsyxoruenxhyomutbptswjajawqjpqafpdcstkiyjuilimecgejpqmyciolgcmdpcstzdozbmnza diff --git a/bash-5.1/vendor/aho-corasick/examples/dict-search.rs b/bash-5.1/vendor/aho-corasick/examples/dict-search.rs new file mode 100644 index 0000000..b620cc2 --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/examples/dict-search.rs @@ -0,0 +1,138 @@ +// This example demonstrates how to use the Aho-Corasick algorithm to rapidly +// scan text for matches in a large dictionary of keywords. This example by +// default reads your system's dictionary (~120,000 words). +extern crate aho_corasick; +extern crate csv; +extern crate docopt; +extern crate memmap; +extern crate serde; +#[macro_use] +extern crate serde_derive; + +use std::error::Error; +use std::fs::File; +use std::io::{self, BufRead, Write}; +use std::process; + +use aho_corasick::{Automaton, AcAutomaton, Match}; +use docopt::Docopt; +use memmap::Mmap; + +static USAGE: &'static str = " +Usage: dict-search [options] + dict-search --help + +Options: + -d , --dict Path to dictionary of keywords to search. + [default: /usr/share/dict/words] + -m , --min-len The minimum length for a keyword in UTF-8 + encoded bytes. [default: 5] + --overlapping Report overlapping matches. + -c, --count Show only the numebr of matches. + --memory-usage Show memory usage of automaton. + --full Use fully expanded transition matrix. + Warning: may use lots of memory. + -h, --help Show this usage message. +"; + +#[derive(Clone, Debug, Deserialize)] +struct Args { + arg_input: String, + flag_dict: String, + flag_min_len: usize, + flag_overlapping: bool, + flag_memory_usage: bool, + flag_full: bool, + flag_count: bool, +} + +fn main() { + let args: Args = Docopt::new(USAGE) + .and_then(|d| d.deserialize()) + .unwrap_or_else(|e| e.exit()); + match run(&args) { + Ok(()) => {} + Err(err) => { + writeln!(&mut io::stderr(), "{}", err).unwrap(); + process::exit(1); + } + } +} + +fn run(args: &Args) -> Result<(), Box> { + let aut = try!(build_automaton(&args.flag_dict, args.flag_min_len)); + if args.flag_memory_usage { + let (bytes, states) = if args.flag_full { + let aut = aut.into_full(); + (aut.heap_bytes(), aut.num_states()) + } else { + (aut.heap_bytes(), aut.num_states()) + }; + println!("{} bytes, {} states", bytes, states); + return Ok(()); + } + + let rdr = try!(File::open(&args.arg_input)); + if args.flag_full { + let aut = aut.into_full(); + if args.flag_overlapping { + if args.flag_count { + let mmap = unsafe { try!(Mmap::map(&rdr)) }; + println!("{}", aut.find_overlapping(&*mmap).count()); + } else { + try!(write_matches(&aut, aut.stream_find_overlapping(rdr))); + } + } else { + if args.flag_count { + let mmap = unsafe { try!(Mmap::map(&rdr)) }; + println!("{}", aut.find(&*mmap).count()); + } else { + try!(write_matches(&aut, aut.stream_find(rdr))); + } + } + } else { + if args.flag_overlapping { + if args.flag_count { + let mmap = unsafe { try!(Mmap::map(&rdr)) }; + println!("{}", aut.find_overlapping(&*mmap).count()); + } else { + try!(write_matches(&aut, aut.stream_find_overlapping(rdr))); + } + } else { + if args.flag_count { + let mmap = unsafe { try!(Mmap::map(&rdr)) }; + println!("{}", aut.find(&*mmap).count()); + } else { + try!(write_matches(&aut, aut.stream_find(rdr))); + } + } + } + Ok(()) +} + +fn write_matches(aut: &A, it: I) -> Result<(), Box> + where A: Automaton, I: Iterator> { + let mut wtr = csv::Writer::from_writer(io::stdout()); + try!(wtr.serialize(("pattern", "start", "end"))); + for m in it { + let m = try!(m); + try!(wtr.serialize((aut.pattern(m.pati), m.start, m.end))); + } + try!(wtr.flush()); + Ok(()) +} + +fn build_automaton( + dict_path: &str, + min_len: usize, +) -> Result, Box> { + let buf = io::BufReader::new(try!(File::open(dict_path))); + let mut lines = Vec::with_capacity(1 << 10); + for line in buf.lines() { + let line = try!(line); + if line.len() >= min_len { + lines.push(line); + } + } + Ok(AcAutomaton::with_transitions(lines)) +} diff --git a/bash-5.1/vendor/aho-corasick/src/autiter.rs b/bash-5.1/vendor/aho-corasick/src/autiter.rs new file mode 100644 index 0000000..dfad28f --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/src/autiter.rs @@ -0,0 +1,530 @@ +use std::io::{self, BufRead}; +use std::marker::PhantomData; + +use memchr::{memchr, memchr2, memchr3}; + +use super::{ROOT_STATE, StateIdx}; + +/// An abstraction over automatons and their corresponding iterators. +/// The type parameter `P` is the type of the pattern that was used to +/// construct this Automaton. +pub trait Automaton

{ + /// Return the next state given the current state and next character. + fn next_state(&self, si: StateIdx, b: u8) -> StateIdx; + + /// Return true if and only if the given state and current pattern index + /// indicate a match. + fn has_match(&self, si: StateIdx, outi: usize) -> bool; + + /// Build a match given the current state, pattern index and input index. + fn get_match(&self, si: StateIdx, outi: usize, texti: usize) -> Match; + + /// Return the set of bytes that have transitions in the root state. + fn start_bytes(&self) -> &[u8]; + + /// Returns all of the patterns matched by this automaton. + /// + /// The order of the patterns is the order in which they were added. + fn patterns(&self) -> &[P]; + + /// Returns the pattern indexed at `i`. + /// + /// The index corresponds to the position at which the pattern was added + /// to the automaton, starting at `0`. + fn pattern(&self, i: usize) -> &P; + + /// Return the number of patterns in the automaton. + #[inline] + fn len(&self) -> usize { + self.patterns().len() + } + + /// Returns true if the automaton has no patterns. + #[inline] + fn is_empty(&self) -> bool { + self.patterns().is_empty() + } + + /// Returns an iterator of non-overlapping matches in `s`. + fn find<'a, 's, Q: ?Sized + AsRef<[u8]>>( + &'a self, + s: &'s Q, + ) -> Matches<'a, 's, P, Self> + where Self: Sized { + Matches { + aut: self, + text: s.as_ref(), + texti: 0, + si: ROOT_STATE, + _m: PhantomData, + } + } + + /// Returns an iterator of overlapping matches in `s`. + fn find_overlapping<'a, 's, Q: ?Sized + AsRef<[u8]>>( + &'a self, + s: &'s Q, + ) -> MatchesOverlapping<'a, 's, P, Self> + where Self: Sized { + MatchesOverlapping { + aut: self, + text: s.as_ref(), + texti: 0, + si: ROOT_STATE, + outi: 0, + _m: PhantomData, + } + } + + /// Returns an iterator of non-overlapping matches in the given reader. + fn stream_find<'a, R: io::Read>( + &'a self, + rdr: R, + ) -> StreamMatches<'a, R, P, Self> + where Self: Sized { + StreamMatches { + aut: self, + buf: io::BufReader::new(rdr), + texti: 0, + si: ROOT_STATE, + _m: PhantomData, + } + } + + /// Returns an iterator of overlapping matches in the given reader. + fn stream_find_overlapping<'a, R: io::Read>( + &'a self, + rdr: R, + ) -> StreamMatchesOverlapping<'a, R, P, Self> + where Self: Sized { + StreamMatchesOverlapping { + aut: self, + buf: io::BufReader::new(rdr), + texti: 0, + si: ROOT_STATE, + outi: 0, + _m: PhantomData, + } + } +} + +impl<'a, P: AsRef<[u8]>, A: 'a + Automaton

+ ?Sized> + Automaton

for &'a A { + fn next_state(&self, si: StateIdx, b: u8) -> StateIdx { + (**self).next_state(si, b) + } + + fn has_match(&self, si: StateIdx, outi: usize) -> bool { + (**self).has_match(si, outi) + } + + fn start_bytes(&self) -> &[u8] { + (**self).start_bytes() + } + + fn patterns(&self) -> &[P] { + (**self).patterns() + } + + fn pattern(&self, i: usize) -> &P { + (**self).pattern(i) + } + + fn get_match(&self, si: StateIdx, outi: usize, texti: usize) -> Match { + (**self).get_match(si, outi, texti) + } +} + +/// Records a match in the search text. +#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] +pub struct Match { + /// The pattern index. + /// + /// This corresponds to the ordering in which the matched pattern was + /// added to the automaton, starting at `0`. + pub pati: usize, + /// The starting byte offset of the match in the search text. + pub start: usize, + /// The ending byte offset of the match in the search text. + /// + /// (This can be re-captiulated with `pati` and adding the pattern's + /// length to `start`, but it is convenient to have it here.) + pub end: usize, +} + +/// An iterator of non-overlapping matches for in-memory text. +/// +/// This iterator yields `Match` values. +/// +/// `'a` is the lifetime of the automaton, `'s` is the lifetime of the +/// search text, and `P` is the type of the Automaton's pattern. +#[derive(Debug)] +pub struct Matches<'a, 's, P, A: 'a + Automaton

+ ?Sized> { + aut: &'a A, + text: &'s [u8], + texti: usize, + si: StateIdx, + _m: PhantomData

, +} + +// When there's an initial lone start byte, it is usually worth it +// to use `memchr` to skip along the input. The problem is that +// the skipping function is called in the inner match loop, which +// can be quite costly if the skipping condition is never met. +// Therefore, we lift the case analysis outside of the inner loop at +// the cost of repeating code. +// +// `step_to_match` is the version of the inner loop without skipping, +// and `skip_to_match` is the version with skipping. +#[inline(never)] +fn step_to_match + ?Sized>( + aut: &A, + text: &[u8], + mut texti: usize, + mut si: StateIdx +) -> Option<(usize, StateIdx)> { + while texti < text.len() { + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + if texti + 4 < text.len() { + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + } + } + None +} + +fn skip_to_match + ?Sized, F: Fn(&A, &[u8], usize) -> usize>( + aut: &A, + text: &[u8], + mut texti: usize, + mut si: StateIdx, + skip: F, +) -> Option<(usize, StateIdx)> { + if si == ROOT_STATE { + texti = skip(aut, text, texti); + } + while texti < text.len() { + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + if si == ROOT_STATE { + texti = skip(aut, text, texti + 1); + } else { + texti += 1; + if texti + 4 < text.len() { + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + si = aut.next_state(si, text[texti]); + if aut.has_match(si, 0) { + return Some((texti, si)); + } + texti += 1; + } + } + } + None +} + +#[inline] +fn skip1 + ?Sized>( + aut: &A, + text: &[u8], + at: usize, +) -> usize { + debug_assert!(aut.start_bytes().len() == 1); + let b = aut.start_bytes()[0]; + match memchr(b, &text[at..]) { + None => text.len(), + Some(i) => at + i, + } +} + +#[inline] +fn skip2 + ?Sized>( + aut: &A, + text: &[u8], + at: usize, +) -> usize { + debug_assert!(aut.start_bytes().len() == 2); + let (b1, b2) = (aut.start_bytes()[0], aut.start_bytes()[1]); + match memchr2(b1, b2, &text[at..]) { + None => text.len(), + Some(i) => at + i, + } +} + +#[inline] +fn skip3 + ?Sized>( + aut: &A, + text: &[u8], + at: usize, +) -> usize { + debug_assert!(aut.start_bytes().len() == 3); + let (b1, b2, b3) = ( + aut.start_bytes()[0], aut.start_bytes()[1], aut.start_bytes()[2], + ); + match memchr3(b1, b2, b3, &text[at..]) { + None => text.len(), + Some(i) => at + i, + } +} + +impl<'a, 's, P, A: Automaton

+ ?Sized> Iterator for Matches<'a, 's, P, A> { + type Item = Match; + + fn next(&mut self) -> Option { + if self.aut.start_bytes().len() == 1 { + let skip = skip_to_match( + self.aut, self.text, self.texti, self.si, skip1); + if let Some((texti, si)) = skip { + self.texti = texti + 1; + self.si = ROOT_STATE; + return Some(self.aut.get_match(si, 0, texti)); + } + } else if self.aut.start_bytes().len() == 2 { + let skip = skip_to_match( + self.aut, self.text, self.texti, self.si, skip2); + if let Some((texti, si)) = skip { + self.texti = texti + 1; + self.si = ROOT_STATE; + return Some(self.aut.get_match(si, 0, texti)); + } + } else if self.aut.start_bytes().len() == 3 { + let skip = skip_to_match( + self.aut, self.text, self.texti, self.si, skip3); + if let Some((texti, si)) = skip { + self.texti = texti + 1; + self.si = ROOT_STATE; + return Some(self.aut.get_match(si, 0, texti)); + } + } else { + let step = step_to_match(self.aut, self.text, self.texti, self.si); + if let Some((texti, si)) = step { + self.texti = texti + 1; + self.si = ROOT_STATE; + return Some(self.aut.get_match(si, 0, texti)); + } + } + None + } +} + +/// An iterator of non-overlapping matches for streaming text. +/// +/// This iterator yields `io::Result` values. +/// +/// `'a` is the lifetime of the automaton, `R` is the type of the underlying +/// `io::Read`er, and P is the type of the Automaton's pattern. +#[derive(Debug)] +pub struct StreamMatches<'a, R, P, A: 'a + Automaton

+ ?Sized> { + aut: &'a A, + buf: io::BufReader, + texti: usize, + si: StateIdx, + _m: PhantomData

, +} + +impl<'a, R: io::Read, P, A: Automaton

> + Iterator for StreamMatches<'a, R, P, A> { + type Item = io::Result; + + fn next(&mut self) -> Option> { + let mut m = None; + let mut consumed = 0; +'LOOP: loop { + self.buf.consume(consumed); + let bs = match self.buf.fill_buf() { + Err(err) => return Some(Err(err)), + Ok(bs) if bs.is_empty() => break, + Ok(bs) => bs, + }; + consumed = bs.len(); // is shortened if we find a match + for (i, &b) in bs.iter().enumerate() { + self.si = self.aut.next_state(self.si, b); + if self.aut.has_match(self.si, 0) { + m = Some(Ok(self.aut.get_match(self.si, 0, self.texti))); + consumed = i + 1; + self.texti += 1; + self.si = ROOT_STATE; + break 'LOOP; + } + self.texti += 1; + } + } + self.buf.consume(consumed); + m + } +} + +/// An iterator of overlapping matches for in-memory text. +/// +/// This iterator yields `Match` values. +/// +/// `'a` is the lifetime of the automaton, `'s` is the lifetime of the +/// search text, and `P` is the type of the Automaton's pattern. +#[derive(Debug)] +pub struct MatchesOverlapping<'a, 's, P, A: 'a + Automaton

+ ?Sized> { + aut: &'a A, + text: &'s [u8], + texti: usize, + si: StateIdx, + outi: usize, + _m: PhantomData

, +} + +impl<'a, 's, P, A: Automaton

+ ?Sized> + Iterator for MatchesOverlapping<'a, 's, P, A> { + type Item = Match; + + fn next(&mut self) -> Option { + if self.aut.has_match(self.si, self.outi) { + let m = self.aut.get_match(self.si, self.outi, self.texti); + self.outi += 1; + if !self.aut.has_match(self.si, self.outi) { + self.texti += 1; + } + return Some(m); + } + + self.outi = 0; + if self.aut.start_bytes().len() == 1 { + let skip = skip_to_match( + self.aut, self.text, self.texti, self.si, skip1); + if let Some((texti, si)) = skip { + self.texti = texti; + self.si = si; + return self.next(); + } + } else if self.aut.start_bytes().len() == 2 { + let skip = skip_to_match( + self.aut, self.text, self.texti, self.si, skip2); + if let Some((texti, si)) = skip { + self.texti = texti; + self.si = si; + return self.next(); + } + } else if self.aut.start_bytes().len() == 3 { + let skip = skip_to_match( + self.aut, self.text, self.texti, self.si, skip3); + if let Some((texti, si)) = skip { + self.texti = texti; + self.si = si; + return self.next(); + } + } else { + let step = step_to_match(self.aut, self.text, self.texti, self.si); + if let Some((texti, si)) = step { + self.texti = texti; + self.si = si; + return self.next(); + } + } + None + } +} + +/// An iterator of overlapping matches for streaming text. +/// +/// This iterator yields `io::Result` values. +/// +/// `'a` is the lifetime of the automaton, `R` is the type of the underlying +/// `io::Read`er, and P is the type of the Automaton's pattern. +#[derive(Debug)] +pub struct StreamMatchesOverlapping<'a, R, P, A: 'a + Automaton

+ ?Sized> { + aut: &'a A, + buf: io::BufReader, + texti: usize, + si: StateIdx, + outi: usize, + _m: PhantomData

, +} + +impl<'a, R: io::Read, P, A: Automaton

+ ?Sized> + Iterator for StreamMatchesOverlapping<'a, R, P, A> { + type Item = io::Result; + + fn next(&mut self) -> Option> { + if self.aut.has_match(self.si, self.outi) { + let m = self.aut.get_match(self.si, self.outi, self.texti); + self.outi += 1; + if !self.aut.has_match(self.si, self.outi) { + self.texti += 1; + } + return Some(Ok(m)); + } + let mut m = None; + let mut consumed = 0; + self.outi = 0; +'LOOP: loop { + self.buf.consume(consumed); + let bs = match self.buf.fill_buf() { + Err(err) => return Some(Err(err)), + Ok(bs) if bs.is_empty() => break, + Ok(bs) => bs, + }; + consumed = bs.len(); // is shortened if we find a match + for (i, &b) in bs.iter().enumerate() { + self.si = self.aut.next_state(self.si, b); + if self.aut.has_match(self.si, self.outi) { + m = Some(Ok(self.aut.get_match( + self.si, self.outi, self.texti))); + consumed = i + 1; + self.outi += 1; + if !self.aut.has_match(self.si, self.outi) { + self.texti += 1; + } + break 'LOOP; + } + self.texti += 1; + } + } + self.buf.consume(consumed); + m + } +} diff --git a/bash-5.1/vendor/aho-corasick/src/full.rs b/bash-5.1/vendor/aho-corasick/src/full.rs new file mode 100644 index 0000000..377940a --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/src/full.rs @@ -0,0 +1,145 @@ +use std::fmt; +use std::mem; + +use super::{ + FAIL_STATE, + StateIdx, AcAutomaton, Transitions, Match, + usize_bytes, vec_bytes, +}; +use super::autiter::Automaton; + +/// A complete Aho-Corasick automaton. +/// +/// This uses a single transition matrix that permits each input character +/// to move to the next state with a single lookup in the matrix. +/// +/// This is as fast as it gets, but it is guaranteed to use a lot of memory. +/// Namely, it will use at least `4 * 256 * #states`, where the number of +/// states is capped at length of all patterns concatenated. +#[derive(Clone)] +pub struct FullAcAutomaton

{ + pats: Vec

, + trans: Vec, // row-major, where states are rows + out: Vec>, // indexed by StateIdx + start_bytes: Vec, +} + +impl> FullAcAutomaton

{ + /// Build a new expanded Aho-Corasick automaton from an existing + /// Aho-Corasick automaton. + pub fn new(ac: AcAutomaton) -> FullAcAutomaton

{ + let mut fac = FullAcAutomaton { + pats: vec![], + trans: vec![FAIL_STATE; 256 * ac.states.len()], + out: vec![vec![]; ac.states.len()], + start_bytes: vec![], + }; + fac.build_matrix(&ac); + fac.pats = ac.pats; + fac.start_bytes = ac.start_bytes; + fac + } + + #[doc(hidden)] + pub fn memory_usage(&self) -> usize { + self.pats.iter() + .map(|p| vec_bytes() + p.as_ref().len()) + .sum::() + + (4 * self.trans.len()) + + self.out.iter() + .map(|v| vec_bytes() + (usize_bytes() * v.len())) + .sum::() + + self.start_bytes.len() + } + + #[doc(hidden)] + pub fn heap_bytes(&self) -> usize { + self.pats.iter() + .map(|p| mem::size_of::

() + p.as_ref().len()) + .sum::() + + (4 * self.trans.len()) + + self.out.iter() + .map(|v| vec_bytes() + (usize_bytes() * v.len())) + .sum::() + + self.start_bytes.len() + } + + fn set(&mut self, si: StateIdx, i: u8, goto: StateIdx) { + let ns = self.num_states(); + self.trans[i as usize * ns + si as usize] = goto; + } + + #[doc(hidden)] + #[inline] + pub fn num_states(&self) -> usize { + self.out.len() + } +} + +impl> Automaton

for FullAcAutomaton

{ + #[inline] + fn next_state(&self, si: StateIdx, i: u8) -> StateIdx { + let at = i as usize * self.num_states() + si as usize; + unsafe { *self.trans.get_unchecked(at) } + } + + #[inline] + fn get_match(&self, si: StateIdx, outi: usize, texti: usize) -> Match { + let pati = self.out[si as usize][outi]; + let patlen = self.pats[pati].as_ref().len(); + let start = texti + 1 - patlen; + Match { + pati: pati, + start: start, + end: start + patlen, + } + } + + #[inline] + fn has_match(&self, si: StateIdx, outi: usize) -> bool { + unsafe { outi < self.out.get_unchecked(si as usize).len() } + } + + #[inline] + fn start_bytes(&self) -> &[u8] { + &self.start_bytes + } + + #[inline] + fn patterns(&self) -> &[P] { + &self.pats + } + + #[inline] + fn pattern(&self, i: usize) -> &P { + &self.pats[i] + } +} + +impl> FullAcAutomaton

{ + fn build_matrix(&mut self, ac: &AcAutomaton) { + for (si, s) in ac.states.iter().enumerate().skip(1) { + self.set_states(ac, si as StateIdx); + self.out[si].extend_from_slice(&s.out); + } + } + + fn set_states(&mut self, ac: &AcAutomaton, si: StateIdx) { + let current_state = &ac.states[si as usize]; + let first_fail_state = current_state.fail; + current_state.for_each_transition(move |b, maybe_si| { + let goto = if maybe_si == FAIL_STATE { + ac.memoized_next_state(self, si, first_fail_state, b) + } else { + maybe_si + }; + self.set(si, b, goto); + }); + } +} + +impl + fmt::Debug> fmt::Debug for FullAcAutomaton

{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "FullAcAutomaton({:?})", self.pats) + } +} diff --git a/bash-5.1/vendor/aho-corasick/src/lib.rs b/bash-5.1/vendor/aho-corasick/src/lib.rs new file mode 100644 index 0000000..cd71073 --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/src/lib.rs @@ -0,0 +1,1116 @@ +/*! +An implementation of the +[Aho-Corasick string search algorithm](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm). + +The Aho-Corasick algorithm is principally useful when you need to search many +large texts for a fixed (possibly large) set of keywords. In particular, the +Aho-Corasick algorithm preprocesses the set of keywords by constructing a +finite state machine. The search phase is then a quick linear scan through the +text. Each character in the search text causes a state transition in the +automaton. Matches are reported when the automaton enters a match state. + +# Examples + +The main type exposed by this crate is `AcAutomaton`, which can be constructed +from an iterator of pattern strings: + +```rust +use aho_corasick::{Automaton, AcAutomaton}; + +let aut = AcAutomaton::new(vec!["apple", "maple"]); + +// AcAutomaton also implements `FromIterator`: +let aut: AcAutomaton<&str> = ["apple", "maple"].iter().cloned().collect(); +``` + +Finding matches can be done with `find`: + +```rust +use aho_corasick::{Automaton, AcAutomaton, Match}; + +let aut = AcAutomaton::new(vec!["apple", "maple"]); +let mut it = aut.find("I like maple apples."); +assert_eq!(it.next(), Some(Match { + pati: 1, + start: 7, + end: 12, +})); +assert_eq!(it.next(), Some(Match { + pati: 0, + start: 13, + end: 18, +})); +assert_eq!(it.next(), None); +``` + +Use `find_overlapping` if you want to report all matches, even if they +overlap with each other. + +```rust +use aho_corasick::{Automaton, AcAutomaton, Match}; + +let aut = AcAutomaton::new(vec!["abc", "a"]); +let matches: Vec<_> = aut.find_overlapping("abc").collect(); +assert_eq!(matches, vec![ + Match { pati: 1, start: 0, end: 1}, Match { pati: 0, start: 0, end: 3 }, +]); + +// Regular `find` will report only one match: +let matches: Vec<_> = aut.find("abc").collect(); +assert_eq!(matches, vec![Match { pati: 1, start: 0, end: 1}]); +``` + +Finally, there are also methods for finding matches on *streams*. Namely, the +search text does not have to live in memory. It's useful to run this on files +that can't fit into memory: + +```no_run +use std::fs::File; + +use aho_corasick::{Automaton, AcAutomaton}; + +let aut = AcAutomaton::new(vec!["foo", "bar", "baz"]); +let rdr = File::open("search.txt").unwrap(); +for m in aut.stream_find(rdr) { + let m = m.unwrap(); // could be an IO error + println!("Pattern '{}' matched at: ({}, {})", + aut.pattern(m.pati), m.start, m.end); +} +``` + +There is also `stream_find_overlapping`, which is just like `find_overlapping`, +but it operates on streams. + +Please see `dict-search.rs` in this crate's `examples` directory for a more +complete example. It creates a large automaton from a dictionary and can do a +streaming match over arbitrarily large data. + +# Memory usage + +A key aspect of an Aho-Corasick implementation is how the state transitions +are represented. The easiest way to make the automaton fast is to store a +sparse 256-slot map in each state. It maps an input byte to a state index. +This makes the matching loop extremely fast, since it translates to a simple +pointer read. + +The problem is that as the automaton accumulates more states, you end up paying +a `256 * 4` (`4` is for the `u32` state index) byte penalty for every state +regardless of how many transitions it has. + +To solve this, only states near the root of the automaton have this sparse +map representation. States near the leaves of the automaton use a dense mapping +that requires a linear scan. + +(The specific limit currently set is `3`, so that states with a depth less than +or equal to `3` are less memory efficient. The result is that the memory usage +of the automaton stops growing rapidly past ~60MB, even for automatons with +thousands of patterns.) + +If you'd like to opt for the less-memory-efficient-but-faster version, then +you can construct an `AcAutomaton` with a `Sparse` transition strategy: + +```rust +use aho_corasick::{Automaton, AcAutomaton, Match, Sparse}; + +let aut = AcAutomaton::<&str, Sparse>::with_transitions(vec!["abc", "a"]); +let matches: Vec<_> = aut.find("abc").collect(); +assert_eq!(matches, vec![Match { pati: 1, start: 0, end: 1}]); +``` +*/ + +#![deny(missing_docs)] + +extern crate memchr; +#[cfg(test)] +extern crate quickcheck; +#[cfg(test)] +extern crate rand; + +use std::collections::VecDeque; +use std::fmt; +use std::iter::FromIterator; +use std::mem; + +pub use self::autiter::{ + Automaton, Match, + Matches, MatchesOverlapping, StreamMatches, StreamMatchesOverlapping, +}; +pub use self::full::FullAcAutomaton; + +// We're specifying paths explicitly so that we can use +// these modules simultaneously from `main.rs`. +// Should probably make just make `main.rs` a separate crate. +#[path = "autiter.rs"] +mod autiter; +#[path = "full.rs"] +mod full; + +/// The integer type used for the state index. +/// +/// Limiting this to 32 bit integers can have a big impact on memory usage +/// when using the `Sparse` transition representation. +pub type StateIdx = u32; + +// Constants for special state indexes. +const FAIL_STATE: u32 = 0; +const ROOT_STATE: u32 = 1; + +// Limit the depth at which we use a sparse alphabet map. Once the limit is +// reached, a dense set is used (and lookup becomes O(n)). +// +// This does have a performance hit, but the (straight forward) alternative +// is to have a `256 * 4` byte overhead for every state. +// Given that Aho-Corasick is typically used for dictionary searching, this +// can lead to dramatic memory bloat. +// +// This limit should only be increased at your peril. Namely, in the worst +// case, `256^DENSE_DEPTH_THRESHOLD * 4` corresponds to the memory usage in +// bytes. A value of `1` gives us a good balance. This is also a happy point +// in the benchmarks. A value of `0` gives considerably worse times on certain +// benchmarks (e.g., `ac_ten_one_prefix_byte_every_match`) than even a value +// of `1`. A value of `2` is slightly better than `1` and it looks like gains +// level off at that point with not much observable difference when set to +// `3`. +// +// Why not make this user configurable? Well, it doesn't make much sense +// because we pay for it with case analysis in the matching loop. Increasing it +// doesn't have much impact on performance (outside of pathological cases?). +// +// N.B. Someone else seems to have discovered an alternative, but I haven't +// grokked it yet: https://github.com/mischasan/aho-corasick +const DENSE_DEPTH_THRESHOLD: u32 = 1; + +/// An Aho-Corasick finite automaton. +/// +/// The type parameter `P` is the type of the pattern that was used to +/// construct this AcAutomaton. +#[derive(Clone)] +pub struct AcAutomaton { + pats: Vec

, + states: Vec>, + start_bytes: Vec, +} + +#[derive(Clone)] +struct State { + out: Vec, + fail: StateIdx, + goto: T, + depth: u32, +} + +impl> AcAutomaton

{ + /// Create a new automaton from an iterator of patterns. + /// + /// The patterns must be convertible to bytes (`&[u8]`) via the `AsRef` + /// trait. + pub fn new(pats: I) -> AcAutomaton + where I: IntoIterator { + AcAutomaton::with_transitions(pats) + } +} + +impl, T: Transitions> AcAutomaton { + /// Create a new automaton from an iterator of patterns. + /// + /// This constructor allows one to choose the transition representation. + /// + /// The patterns must be convertible to bytes (`&[u8]`) via the `AsRef` + /// trait. + pub fn with_transitions(pats: I) -> AcAutomaton + where I: IntoIterator { + AcAutomaton { + pats: vec![], // filled in later, avoid wrath of borrow checker + states: vec![State::new(0), State::new(0)], // empty and root + start_bytes: vec![], // also filled in later + }.build(pats.into_iter().collect()) + } + + /// Build out the entire automaton into a single matrix. + /// + /// This will make searching as fast as possible at the expense of using + /// at least `4 * 256 * #states` bytes of memory. + pub fn into_full(self) -> FullAcAutomaton

{ + FullAcAutomaton::new(self) + } + + #[doc(hidden)] + pub fn num_states(&self) -> usize { + self.states.len() + } + + #[doc(hidden)] + pub fn heap_bytes(&self) -> usize { + self.pats.iter() + .map(|p| mem::size_of::

() + p.as_ref().len()) + .sum::() + + self.states.iter() + .map(|s| mem::size_of::>() + s.heap_bytes()) + .sum::() + + self.start_bytes.len() + } + + // The states of `full_automaton` should be set for all states < si + fn memoized_next_state( + &self, + full_automaton: &FullAcAutomaton

, + current_si: StateIdx, + mut si: StateIdx, + b: u8, + ) -> StateIdx { + loop { + if si < current_si { + return full_automaton.next_state(si, b); + } + let state = &self.states[si as usize]; + let maybe_si = state.goto(b); + if maybe_si != FAIL_STATE { + return maybe_si; + } else { + si = state.fail; + } + } + } +} + +impl, T: Transitions> Automaton

for AcAutomaton { + #[inline] + fn next_state(&self, mut si: StateIdx, b: u8) -> StateIdx { + loop { + let state = &self.states[si as usize]; + let maybe_si = state.goto(b); + if maybe_si != FAIL_STATE { + si = maybe_si; + break; + } else { + si = state.fail; + } + } + si + } + + #[inline] + fn get_match(&self, si: StateIdx, outi: usize, texti: usize) -> Match { + let pati = self.states[si as usize].out[outi]; + let patlen = self.pats[pati].as_ref().len(); + let start = texti + 1 - patlen; + Match { + pati: pati, + start: start, + end: start + patlen, + } + } + + #[inline] + fn has_match(&self, si: StateIdx, outi: usize) -> bool { + outi < self.states[si as usize].out.len() + } + + #[inline] + fn start_bytes(&self) -> &[u8] { + &self.start_bytes + } + + #[inline] + fn patterns(&self) -> &[P] { + &self.pats + } + + #[inline] + fn pattern(&self, i: usize) -> &P { + &self.pats[i] + } +} + +// `(0..256).map(|b| b as u8)` optimizes poorly in debug builds so +// we use this small explicit iterator instead +struct AllBytesIter(i32); +impl Iterator for AllBytesIter { + type Item = u8; + #[inline] + fn next(&mut self) -> Option { + if self.0 < 256 { + let b = self.0 as u8; + self.0 += 1; + Some(b) + } else { + None + } + } +} + +impl AllBytesIter { + fn new() -> AllBytesIter { + AllBytesIter(0) + } +} + +// Below contains code for *building* the automaton. It's a reasonably faithful +// translation of the description/psuedo-code from: +// http://www.cs.uku.fi/~kilpelai/BSA05/lectures/slides04.pdf + +impl, T: Transitions> AcAutomaton { + // This is the first phase and builds the initial keyword tree. + fn build(mut self, pats: Vec

) -> AcAutomaton { + for (pati, pat) in pats.iter().enumerate() { + if pat.as_ref().is_empty() { + continue; + } + let mut previ = ROOT_STATE; + for &b in pat.as_ref() { + if self.states[previ as usize].goto(b) != FAIL_STATE { + previ = self.states[previ as usize].goto(b); + } else { + let depth = self.states[previ as usize].depth + 1; + let nexti = self.add_state(State::new(depth)); + self.states[previ as usize].set_goto(b, nexti); + previ = nexti; + } + } + self.states[previ as usize].out.push(pati); + } + { + let root_state = &mut self.states[ROOT_STATE as usize]; + for c in AllBytesIter::new() { + if root_state.goto(c) == FAIL_STATE { + root_state.set_goto(c, ROOT_STATE); + } else { + self.start_bytes.push(c); + } + } + } + // If any of the start bytes are non-ASCII, then remove them all, + // because we don't want to be calling memchr on non-ASCII bytes. + // (Well, we could, but it requires being more clever. Simply using + // the prefix byte isn't good enough.) + if self.start_bytes.iter().any(|&b| b > 0x7F) { + self.start_bytes.clear(); + } + self.pats = pats; + self.fill() + } + + // The second phase that fills in the back links. + fn fill(mut self) -> AcAutomaton { + // Fill up the queue with all non-root transitions out of the root + // node. Then proceed by breadth first traversal. + let mut q = VecDeque::new(); + self.states[ROOT_STATE as usize].for_each_transition(|_, si| { + if si != ROOT_STATE { + q.push_front(si); + } + }); + + let mut transitions = Vec::new(); + + while let Some(si) = q.pop_back() { + self.states[si as usize].for_each_ok_transition(|c, u| { + transitions.push((c, u)); + q.push_front(u); + }); + + for (c, u) in transitions.drain(..) { + let mut v = self.states[si as usize].fail; + loop { + let state = &self.states[v as usize]; + if state.goto(c) == FAIL_STATE { + v = state.fail; + } else { + break; + } + } + let ufail = self.states[v as usize].goto(c); + self.states[u as usize].fail = ufail; + + fn get_two(xs: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) { + if i < j { + let (before, after) = xs.split_at_mut(j); + (&mut before[i], &mut after[0]) + } else { + let (before, after) = xs.split_at_mut(i); + (&mut after[0], &mut before[j]) + } + } + + let (ufail_out, out) = get_two(&mut self.states, ufail as usize, u as usize); + out.out.extend_from_slice(&ufail_out.out); + } + } + self + } + + fn add_state(&mut self, state: State) -> StateIdx { + let i = self.states.len(); + self.states.push(state); + i as StateIdx + } +} + +impl State { + fn new(depth: u32) -> State { + State { + out: vec![], + fail: 1, + goto: Transitions::new(depth), + depth: depth, + } + } + + fn goto(&self, b: u8) -> StateIdx { + self.goto.goto(b) + } + + fn set_goto(&mut self, b: u8, si: StateIdx) { + self.goto.set_goto(b, si); + } + + fn heap_bytes(&self) -> usize { + (self.out.len() * usize_bytes()) + + self.goto.heap_bytes() + } + + fn for_each_transition(&self, f: F) + where F: FnMut(u8, StateIdx) + { + self.goto.for_each_transition(f) + } + + fn for_each_ok_transition(&self, f: F) + where F: FnMut(u8, StateIdx) + { + self.goto.for_each_ok_transition(f) + } +} + +/// An abstraction over state transition strategies. +/// +/// This is an attempt to let the caller choose the space/time trade offs +/// used for state transitions. +/// +/// (It's possible that this interface is merely good enough for just the two +/// implementations in this crate.) +pub trait Transitions { + /// Return a new state at the given depth. + fn new(depth: u32) -> Self; + /// Return the next state index given the next character. + fn goto(&self, alpha: u8) -> StateIdx; + /// Set the next state index for the character given. + fn set_goto(&mut self, alpha: u8, si: StateIdx); + /// The memory use in bytes (on the heap) of this set of transitions. + fn heap_bytes(&self) -> usize; + + /// Iterates over each state + fn for_each_transition(&self, mut f: F) + where F: FnMut(u8, StateIdx) + { + for b in AllBytesIter::new() { + f(b, self.goto(b)); + } + } + + /// Iterates over each non-fail state + fn for_each_ok_transition(&self, mut f: F) + where + F: FnMut(u8, StateIdx), + { + self.for_each_transition(|b, si| { + if si != FAIL_STATE { + f(b, si); + } + }); + } +} + +/// State transitions that can be stored either sparsely or densely. +/// +/// This uses less space but at the expense of slower matching. +#[derive(Clone, Debug)] +pub struct Dense(DenseChoice); + +#[derive(Clone, Debug)] +enum DenseChoice { + Sparse(Box), + Dense(Vec<(u8, StateIdx)>), +} + +impl Transitions for Dense { + fn new(depth: u32) -> Dense { + if depth <= DENSE_DEPTH_THRESHOLD { + Dense(DenseChoice::Sparse(Box::new(Sparse::new(depth)))) + } else { + Dense(DenseChoice::Dense(vec![])) + } + } + + fn goto(&self, b1: u8) -> StateIdx { + match self.0 { + DenseChoice::Sparse(ref m) => m.goto(b1), + DenseChoice::Dense(ref m) => { + for &(b2, si) in m { + if b1 == b2 { + return si; + } + } + FAIL_STATE + } + } + } + + fn set_goto(&mut self, b: u8, si: StateIdx) { + match self.0 { + DenseChoice::Sparse(ref mut m) => m.set_goto(b, si), + DenseChoice::Dense(ref mut m) => { + match m.binary_search_by_key(&b, |&(b, _)| b) { + Ok(i) => m[i] = (b, si), + Err(i) => m.insert(i, (b, si)), + } + } + } + } + + fn heap_bytes(&self) -> usize { + match self.0 { + DenseChoice::Sparse(_) => mem::size_of::(), + DenseChoice::Dense(ref m) => m.len() * (1 + 4), + } + } + + fn for_each_transition(&self, mut f: F) + where F: FnMut(u8, StateIdx) + { + match self.0 { + DenseChoice::Sparse(ref m) => m.for_each_transition(f), + DenseChoice::Dense(ref m) => { + let mut iter = m.iter(); + let mut b = 0i32; + while let Some(&(next_b, next_si)) = iter.next() { + while (b as u8) < next_b { + f(b as u8, FAIL_STATE); + b += 1; + } + f(b as u8, next_si); + b += 1; + } + while b < 256 { + f(b as u8, FAIL_STATE); + b += 1; + } + } + } + } + fn for_each_ok_transition(&self, mut f: F) + where + F: FnMut(u8, StateIdx), + { + match self.0 { + DenseChoice::Sparse(ref m) => m.for_each_ok_transition(f), + DenseChoice::Dense(ref m) => for &(b, si) in m { + f(b, si) + } + } + } +} + +/// State transitions that are always sparse. +/// +/// This can use enormous amounts of memory when there are many patterns, +/// but matching is very fast. +pub struct Sparse([StateIdx; 256]); + +impl Clone for Sparse { + fn clone(&self) -> Sparse { + Sparse(self.0) + } +} + +impl fmt::Debug for Sparse { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Sparse").field(&&self.0[..]).finish() + } +} + +impl Transitions for Sparse { + fn new(_: u32) -> Sparse { + Sparse([0; 256]) + } + + #[inline] + fn goto(&self, b: u8) -> StateIdx { + self.0[b as usize] + } + + fn set_goto(&mut self, b: u8, si: StateIdx) { + self.0[b as usize] = si; + } + + fn heap_bytes(&self) -> usize { + 0 + } +} + +impl> FromIterator for AcAutomaton { + /// Create an automaton from an iterator of strings. + fn from_iter(it: T) -> AcAutomaton where T: IntoIterator { + AcAutomaton::new(it) + } +} + +// Provide some question debug impls for viewing automatons. +// The custom impls mostly exist for special showing of sparse maps. + +impl + fmt::Debug, T: Transitions> + fmt::Debug for AcAutomaton { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::iter::repeat; + + try!(writeln!(f, "{}", repeat('-').take(79).collect::())); + try!(writeln!(f, "Patterns: {:?}", self.pats)); + for (i, state) in self.states.iter().enumerate().skip(1) { + try!(writeln!(f, "{:3}: {}", i, state.debug(i == 1))); + } + write!(f, "{}", repeat('-').take(79).collect::()) + } +} + +impl State { + fn debug(&self, root: bool) -> String { + format!("State {{ depth: {:?}, out: {:?}, fail: {:?}, goto: {{{}}} }}", + self.depth, self.out, self.fail, self.goto_string(root)) + } + + fn goto_string(&self, root: bool) -> String { + let mut goto = vec![]; + for b in AllBytesIter::new() { + let si = self.goto(b); + if (!root && si == FAIL_STATE) || (root && si == ROOT_STATE) { + continue; + } + goto.push(format!("{} => {}", b as char, si)); + } + goto.join(", ") + } +} + +impl fmt::Debug for State { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.debug(false)) + } +} + +impl AcAutomaton { + #[doc(hidden)] + pub fn dot(&self) -> String { + use std::fmt::Write; + let mut out = String::new(); + macro_rules! w { + ($w:expr, $($tt:tt)*) => { {write!($w, $($tt)*)}.unwrap() } + } + + w!(out, r#" +digraph automaton {{ + label=<{}>; + labelloc="l"; + labeljust="l"; + rankdir="LR"; +"#, self.pats.join(", ")); + for (i, s) in self.states.iter().enumerate().skip(1) { + let i = i as u32; + if s.out.is_empty() { + w!(out, " {};\n", i); + } else { + w!(out, " {} [peripheries=2];\n", i); + } + w!(out, " {} -> {} [style=dashed];\n", i, s.fail); + for b in AllBytesIter::new() { + let si = s.goto(b); + if si == FAIL_STATE || (i == ROOT_STATE && si == ROOT_STATE) { + continue; + } + w!(out, " {} -> {} [label={}];\n", i, si, b as char); + } + } + w!(out, "}}"); + out + } +} + +fn vec_bytes() -> usize { + usize_bytes() * 3 +} + +fn usize_bytes() -> usize { + let bits = usize::max_value().count_ones() as usize; + bits / 8 +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + use std::io; + + use quickcheck::{Arbitrary, Gen, quickcheck}; + use rand::Rng; + + use super::{AcAutomaton, Automaton, Match, AllBytesIter}; + + fn aut_find(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + AcAutomaton::new(xs.to_vec()).find(&haystack).collect() + } + + fn aut_finds(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + let cur = io::Cursor::new(haystack.as_bytes()); + AcAutomaton::new(xs.to_vec()) + .stream_find(cur).map(|r| r.unwrap()).collect() + } + + fn aut_findf(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + AcAutomaton::new(xs.to_vec()).into_full().find(haystack).collect() + } + + fn aut_findfs(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + let cur = io::Cursor::new(haystack.as_bytes()); + AcAutomaton::new(xs.to_vec()) + .into_full() + .stream_find(cur).map(|r| r.unwrap()).collect() + } + + fn aut_findo(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + AcAutomaton::new(xs.to_vec()).find_overlapping(haystack).collect() + } + + fn aut_findos(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + let cur = io::Cursor::new(haystack.as_bytes()); + AcAutomaton::new(xs.to_vec()) + .stream_find_overlapping(cur).map(|r| r.unwrap()).collect() + } + + fn aut_findfo(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + AcAutomaton::new(xs.to_vec()) + .into_full().find_overlapping(haystack).collect() + } + + fn aut_findfos(xs: &[S], haystack: &str) -> Vec + where S: Clone + AsRef<[u8]> { + let cur = io::Cursor::new(haystack.as_bytes()); + AcAutomaton::new(xs.to_vec()) + .into_full() + .stream_find_overlapping(cur).map(|r| r.unwrap()).collect() + } + + #[test] + fn one_pattern_one_match() { + let ns = vec!["a"]; + let hay = "za"; + let matches = vec![ + Match { pati: 0, start: 1, end: 2 }, + ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn one_pattern_many_match() { + let ns = vec!["a"]; + let hay = "zazazzzza"; + let matches = vec![ + Match { pati: 0, start: 1, end: 2 }, + Match { pati: 0, start: 3, end: 4 }, + Match { pati: 0, start: 8, end: 9 }, + ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn one_longer_pattern_one_match() { + let ns = vec!["abc"]; + let hay = "zazabcz"; + let matches = vec![ Match { pati: 0, start: 3, end: 6 } ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn one_longer_pattern_many_match() { + let ns = vec!["abc"]; + let hay = "zazabczzzzazzzabc"; + let matches = vec![ + Match { pati: 0, start: 3, end: 6 }, + Match { pati: 0, start: 14, end: 17 }, + ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn many_pattern_one_match() { + let ns = vec!["a", "b"]; + let hay = "zb"; + let matches = vec![ Match { pati: 1, start: 1, end: 2 } ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn many_pattern_many_match() { + let ns = vec!["a", "b"]; + let hay = "zbzazzzzb"; + let matches = vec![ + Match { pati: 1, start: 1, end: 2 }, + Match { pati: 0, start: 3, end: 4 }, + Match { pati: 1, start: 8, end: 9 }, + ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn many_longer_pattern_one_match() { + let ns = vec!["abc", "xyz"]; + let hay = "zazxyzz"; + let matches = vec![ Match { pati: 1, start: 3, end: 6 } ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn many_longer_pattern_many_match() { + let ns = vec!["abc", "xyz"]; + let hay = "zazxyzzzzzazzzabcxyz"; + let matches = vec![ + Match { pati: 1, start: 3, end: 6 }, + Match { pati: 0, start: 14, end: 17 }, + Match { pati: 1, start: 17, end: 20 }, + ]; + assert_eq!(&aut_find(&ns, hay), &matches); + assert_eq!(&aut_finds(&ns, hay), &matches); + assert_eq!(&aut_findf(&ns, hay), &matches); + assert_eq!(&aut_findfs(&ns, hay), &matches); + } + + #[test] + fn many_longer_pattern_overlap_one_match() { + let ns = vec!["abc", "bc"]; + let hay = "zazabcz"; + let matches = vec![ + Match { pati: 0, start: 3, end: 6 }, + Match { pati: 1, start: 4, end: 6 }, + ]; + assert_eq!(&aut_findo(&ns, hay), &matches); + assert_eq!(&aut_findos(&ns, hay), &matches); + assert_eq!(&aut_findfo(&ns, hay), &matches); + assert_eq!(&aut_findfos(&ns, hay), &matches); + } + + #[test] + fn many_longer_pattern_overlap_one_match_reverse() { + let ns = vec!["abc", "bc"]; + let hay = "xbc"; + let matches = vec![ Match { pati: 1, start: 1, end: 3 } ]; + assert_eq!(&aut_findo(&ns, hay), &matches); + assert_eq!(&aut_findos(&ns, hay), &matches); + assert_eq!(&aut_findfo(&ns, hay), &matches); + assert_eq!(&aut_findfos(&ns, hay), &matches); + } + + #[test] + fn many_longer_pattern_overlap_many_match() { + let ns = vec!["abc", "bc", "c"]; + let hay = "zzzabczzzbczzzc"; + let matches = vec![ + Match { pati: 0, start: 3, end: 6 }, + Match { pati: 1, start: 4, end: 6 }, + Match { pati: 2, start: 5, end: 6 }, + Match { pati: 1, start: 9, end: 11 }, + Match { pati: 2, start: 10, end: 11 }, + Match { pati: 2, start: 14, end: 15 }, + ]; + assert_eq!(&aut_findo(&ns, hay), &matches); + assert_eq!(&aut_findos(&ns, hay), &matches); + assert_eq!(&aut_findfo(&ns, hay), &matches); + assert_eq!(&aut_findfos(&ns, hay), &matches); + } + + #[test] + fn many_longer_pattern_overlap_many_match_reverse() { + let ns = vec!["abc", "bc", "c"]; + let hay = "zzzczzzbczzzabc"; + let matches = vec![ + Match { pati: 2, start: 3, end: 4 }, + Match { pati: 1, start: 7, end: 9 }, + Match { pati: 2, start: 8, end: 9 }, + Match { pati: 0, start: 12, end: 15 }, + Match { pati: 1, start: 13, end: 15 }, + Match { pati: 2, start: 14, end: 15 }, + ]; + assert_eq!(&aut_findo(&ns, hay), &matches); + assert_eq!(&aut_findos(&ns, hay), &matches); + assert_eq!(&aut_findfo(&ns, hay), &matches); + assert_eq!(&aut_findfos(&ns, hay), &matches); + } + + #[test] + fn pattern_returns_original_type() { + let aut = AcAutomaton::new(vec!["apple", "maple"]); + + // Explicitly given this type to assert that the thing returned + // from the function is our original type. + let pat: &str = aut.pattern(0); + assert_eq!(pat, "apple"); + + // Also check the return type of the `patterns` function. + let pats: &[&str] = aut.patterns(); + assert_eq!(pats, &["apple", "maple"]); + } + + // Quickcheck time. + + // This generates very small ascii strings, which makes them more likely + // to interact in interesting ways with larger haystack strings. + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] + pub struct SmallAscii(String); + + impl Arbitrary for SmallAscii { + fn arbitrary(g: &mut G) -> SmallAscii { + use std::char::from_u32; + SmallAscii((0..2) + .map(|_| from_u32(g.gen_range(97, 123)).unwrap()) + .collect()) + } + + fn shrink(&self) -> Box> { + Box::new(self.0.shrink().map(SmallAscii)) + } + } + + impl From for String { + fn from(s: SmallAscii) -> String { s.0 } + } + + impl AsRef<[u8]> for SmallAscii { + fn as_ref(&self) -> &[u8] { self.0.as_ref() } + } + + // This is the same arbitrary impl as `String`, except it has a bias toward + // ASCII characters. + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] + pub struct BiasAscii(String); + + impl Arbitrary for BiasAscii { + fn arbitrary(g: &mut G) -> BiasAscii { + use std::char::from_u32; + let size = { let s = g.size(); g.gen_range(0, s) }; + let mut s = String::with_capacity(size); + for _ in 0..size { + if g.gen_bool(0.3) { + s.push(char::arbitrary(g)); + } else { + for _ in 0..5 { + s.push(from_u32(g.gen_range(97, 123)).unwrap()); + } + } + } + BiasAscii(s) + } + + fn shrink(&self) -> Box> { + Box::new(self.0.shrink().map(BiasAscii)) + } + } + + fn naive_find(xs: &[S], haystack: &str) -> Vec + where S: Clone + Into { + let needles: Vec = + xs.to_vec().into_iter().map(Into::into).collect(); + let mut matches = vec![]; + for hi in 0..haystack.len() { + for (pati, needle) in needles.iter().enumerate() { + let needle = needle.as_bytes(); + if needle.len() == 0 || needle.len() > haystack.len() - hi { + continue; + } + if needle == &haystack.as_bytes()[hi..hi+needle.len()] { + matches.push(Match { + pati: pati, + start: hi, + end: hi + needle.len(), + }); + } + } + } + matches + } + + #[test] + fn qc_ac_equals_naive() { + fn prop(needles: Vec, haystack: BiasAscii) -> bool { + let aut_matches = aut_findo(&needles, &haystack.0); + let naive_matches = naive_find(&needles, &haystack.0); + // Ordering isn't always the same. I don't think we care, so do + // an unordered comparison. + let aset: HashSet = aut_matches.iter().cloned().collect(); + let nset: HashSet = naive_matches.iter().cloned().collect(); + aset == nset + } + quickcheck(prop as fn(Vec, BiasAscii) -> bool); + } + + + #[test] + fn all_bytes_iter() { + let all_bytes = AllBytesIter::new().collect::>(); + assert_eq!(all_bytes[0], 0); + assert_eq!(all_bytes[255], 255); + assert!(AllBytesIter::new().enumerate().all(|(i, b)| b as usize == i)); + } + + #[test] + fn regression_full_order1() { + let matches1 = aut_findfo(&["inf", "ind"], "infind") + .into_iter() + .map(|m| (m.start, m.end)) + .collect::>(); + let matches2 = aut_findfo(&["ind", "inf"], "infind") + .into_iter() + .map(|m| (m.start, m.end)) + .collect::>(); + assert_eq!(matches1, matches2); + } + + // See: https://github.com/BurntSushi/aho-corasick/issues/37 + #[test] + fn regression_full_order2() { + let haystack = "libcore/char/methods.rs"; + + let matches1 = aut_findfo(&["libcore/", "libstd/"], haystack) + .into_iter() + .map(|m| (m.start, m.end)) + .collect::>(); + let matches2 = aut_findfo(&["libstd/", "libcore/"], haystack) + .into_iter() + .map(|m| (m.start, m.end)) + .collect::>(); + assert_eq!(matches1, matches2); + } +} diff --git a/bash-5.1/vendor/aho-corasick/src/main.rs b/bash-5.1/vendor/aho-corasick/src/main.rs new file mode 100644 index 0000000..60562ac --- /dev/null +++ b/bash-5.1/vendor/aho-corasick/src/main.rs @@ -0,0 +1,13 @@ +extern crate memchr; + +use std::env; + +use lib::AcAutomaton; + +#[allow(dead_code)] +mod lib; + +fn main() { + let aut = AcAutomaton::new(env::args().skip(1)); + println!("{}", aut.dot().trim()); +} diff --git a/bash-5.1/vendor/ansi_term/.cargo-checksum.json b/bash-5.1/vendor/ansi_term/.cargo-checksum.json new file mode 100644 index 0000000..ee41459 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"31bb7b361278d99a00595cbd916c444e6fd193b5f0b1ea0cf2d9454440739501","Cargo.toml":"4ca681d6949661455ac88541ffa68ebc7db50cb2b6e9a2134e6d0687da4997c3","LICENCE":"2762990c7fbba9d550802a2593c1d857dcd52596bb0f9f192a97e9a7ac5f4f9e","README.md":"8d983e1bb3cc99724010d9073a5be6452cd49bd57a877525fd0a5dd41e6591d5","examples/256_colours.rs":"5f2845068bc2d93cff4a61f18ffa44fbbbc91be771dfd686d537d343f37041da","examples/basic_colours.rs":"d610795f3743d10d90ec4e5ab32cc09fb16640896cecd2f93fca434a0920397c","examples/rgb_colours.rs":"8399e5131e959a56c932036b790e601fb4ad658856112daf87f933889b443f2c","src/ansi.rs":"988fb87936064fa006fcc9474ac62099c8d6e98d38bb80cec2cd864066482a08","src/debug.rs":"61343f8bf13695020102c033aeaacd9ccd3ec830eacbf9011127e61829451d20","src/difference.rs":"9b4b8f91c72932bfda262abdceff0ec124a5a8dd27d07bd4d2e5e7889135c6c9","src/display.rs":"c04f2397d1d1d86a5e2188c2840c505cb0baeaf9706a88d4bbe56eadc67811b9","src/lib.rs":"b85df4b9b8832cda777db049efa2ec84b9847438fa3feaf8540e597ce2532a47","src/style.rs":"1042fc973f5ea8bbb2a2faec334aad530520b53edc9b3296174ae38c1060490b","src/util.rs":"07c127f732887573a1c9126fc0288e13e7a8f1f803513b95e50aac2905171b0d","src/windows.rs":"7ce7dd6738b9728fcd3908c284b6f29a9bdfb34af761b4c7385cf7e3e1b20e64","src/write.rs":"c9ec03764ad1ecea8b680243c9cafc5e70919fcea7500cc18246ffd8f6bb4b33"},"package":"d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"} \ No newline at end of file diff --git a/bash-5.1/vendor/ansi_term/Cargo.toml b/bash-5.1/vendor/ansi_term/Cargo.toml new file mode 100644 index 0000000..0e5feba --- /dev/null +++ b/bash-5.1/vendor/ansi_term/Cargo.toml @@ -0,0 +1,43 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "ansi_term" +version = "0.12.1" +authors = ["ogham@bsago.me", "Ryan Scheel (Havvy) ", "Josh Triplett "] +description = "Library for ANSI terminal colours and styles (bold, underline)" +homepage = "https://github.com/ogham/rust-ansi-term" +documentation = "https://docs.rs/ansi_term" +readme = "README.md" +license = "MIT" +repository = "https://github.com/ogham/rust-ansi-term" + +[lib] +name = "ansi_term" +[dependencies.serde] +version = "1.0.90" +features = ["derive"] +optional = true +[dev-dependencies.doc-comment] +version = "0.3" + +[dev-dependencies.regex] +version = "1.1.9" + +[dev-dependencies.serde_json] +version = "1.0.39" + +[features] +derive_serde_style = ["serde"] +[target."cfg(target_os=\"windows\")".dependencies.winapi] +version = "0.3.4" +features = ["consoleapi", "errhandlingapi", "fileapi", "handleapi", "processenv"] diff --git a/bash-5.1/vendor/ansi_term/LICENCE b/bash-5.1/vendor/ansi_term/LICENCE new file mode 100644 index 0000000..3228cc9 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/LICENCE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Benjamin Sago + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bash-5.1/vendor/ansi_term/README.md b/bash-5.1/vendor/ansi_term/README.md new file mode 100644 index 0000000..30d52ab --- /dev/null +++ b/bash-5.1/vendor/ansi_term/README.md @@ -0,0 +1,183 @@ +# rust-ansi-term [![ansi-term on crates.io](http://meritbadge.herokuapp.com/ansi-term)](https://crates.io/crates/ansi_term) [![Build status](https://img.shields.io/travis/ogham/rust-ansi-term/master.svg?style=flat)](https://travis-ci.org/ogham/rust-ansi-term) [![Build status](https://img.shields.io/appveyor/ci/ogham/rust-ansi-term/master.svg?style=flat&logo=AppVeyor&logoColor=silver)](https://ci.appveyor.com/project/ogham/rust-ansi-term) [![Coverage status](https://coveralls.io/repos/ogham/rust-ansi-term/badge.svg?branch=master&service=github)](https://coveralls.io/github/ogham/rust-ansi-term?branch=master) + +This is a library for controlling colours and formatting, such as red bold text or blue underlined text, on ANSI terminals. + +### [View the Rustdoc](https://docs.rs/ansi_term/) + + +# Installation + +This crate works with [Cargo](http://crates.io). Add the following to your `Cargo.toml` dependencies section: + +```toml +[dependencies] +ansi_term = "0.12" +``` + + +## Basic usage + +There are three main types in this crate that you need to be concerned with: `ANSIString`, `Style`, and `Colour`. + +A `Style` holds stylistic information: foreground and background colours, whether the text should be bold, or blinking, or other properties. +The `Colour` enum represents the available colours. +And an `ANSIString` is a string paired with a `Style`. + +`Color` is also available as an alias to `Colour`. + +To format a string, call the `paint` method on a `Style` or a `Colour`, passing in the string you want to format as the argument. +For example, here’s how to get some red text: + +```rust +use ansi_term::Colour::Red; + +println!("This is in red: {}", Red.paint("a red string")); +``` + +It’s important to note that the `paint` method does *not* actually return a string with the ANSI control characters surrounding it. +Instead, it returns an `ANSIString` value that has a `Display` implementation that, when formatted, returns the characters. +This allows strings to be printed with a minimum of `String` allocations being performed behind the scenes. + +If you *do* want to get at the escape codes, then you can convert the `ANSIString` to a string as you would any other `Display` value: + +```rust +use ansi_term::Colour::Red; + +let red_string = Red.paint("a red string").to_string(); +``` + +**Note for Windows 10 users:** On Windows 10, the application must enable ANSI support first: + +```rust,ignore +let enabled = ansi_term::enable_ansi_support(); +``` + +## Bold, underline, background, and other styles + +For anything more complex than plain foreground colour changes, you need to construct `Style` values themselves, rather than beginning with a `Colour`. +You can do this by chaining methods based on a new `Style`, created with `Style::new()`. +Each method creates a new style that has that specific property set. +For example: + +```rust +use ansi_term::Style; + +println!("How about some {} and {}?", + Style::new().bold().paint("bold"), + Style::new().underline().paint("underline")); +``` + +For brevity, these methods have also been implemented for `Colour` values, so you can give your styles a foreground colour without having to begin with an empty `Style` value: + +```rust +use ansi_term::Colour::{Blue, Yellow}; + +println!("Demonstrating {} and {}!", + Blue.bold().paint("blue bold"), + Yellow.underline().paint("yellow underline")); + +println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!")); +``` + +The complete list of styles you can use are: +`bold`, `dimmed`, `italic`, `underline`, `blink`, `reverse`, `hidden`, and `on` for background colours. + +In some cases, you may find it easier to change the foreground on an existing `Style` rather than starting from the appropriate `Colour`. +You can do this using the `fg` method: + +```rust +use ansi_term::Style; +use ansi_term::Colour::{Blue, Cyan, Yellow}; + +println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!")); +println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!")); +``` + +You can turn a `Colour` into a `Style` with the `normal` method. +This will produce the exact same `ANSIString` as if you just used the `paint` method on the `Colour` directly, but it’s useful in certain cases: for example, you may have a method that returns `Styles`, and need to represent both the “red bold” and “red, but not bold” styles with values of the same type. The `Style` struct also has a `Default` implementation if you want to have a style with *nothing* set. + +```rust +use ansi_term::Style; +use ansi_term::Colour::Red; + +Red.normal().paint("yet another red string"); +Style::default().paint("a completely regular string"); +``` + + +## Extended colours + +You can access the extended range of 256 colours by using the `Colour::Fixed` variant, which takes an argument of the colour number to use. +This can be included wherever you would use a `Colour`: + +```rust +use ansi_term::Colour::Fixed; + +Fixed(134).paint("A sort of light purple"); +Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup"); +``` + +The first sixteen of these values are the same as the normal and bold standard colour variants. +There’s nothing stopping you from using these as `Fixed` colours instead, but there’s nothing to be gained by doing so either. + +You can also access full 24-bit colour by using the `Colour::RGB` variant, which takes separate `u8` arguments for red, green, and blue: + +```rust +use ansi_term::Colour::RGB; + +RGB(70, 130, 180).paint("Steel blue"); +``` + +## Combining successive coloured strings + +The benefit of writing ANSI escape codes to the terminal is that they *stack*: you do not need to end every coloured string with a reset code if the text that follows it is of a similar style. +For example, if you want to have some blue text followed by some blue bold text, it’s possible to send the ANSI code for blue, followed by the ANSI code for bold, and finishing with a reset code without having to have an extra one between the two strings. + +This crate can optimise the ANSI codes that get printed in situations like this, making life easier for your terminal renderer. +The `ANSIStrings` struct takes a slice of several `ANSIString` values, and will iterate over each of them, printing only the codes for the styles that need to be updated as part of its formatting routine. + +The following code snippet uses this to enclose a binary number displayed in red bold text inside some red, but not bold, brackets: + +```rust +use ansi_term::Colour::Red; +use ansi_term::{ANSIString, ANSIStrings}; + +let some_value = format!("{:b}", 42); +let strings: &[ANSIString<'static>] = &[ + Red.paint("["), + Red.bold().paint(some_value), + Red.paint("]"), +]; + +println!("Value: {}", ANSIStrings(strings)); +``` + +There are several things to note here. +Firstly, the `paint` method can take *either* an owned `String` or a borrowed `&str`. +Internally, an `ANSIString` holds a copy-on-write (`Cow`) string value to deal with both owned and borrowed strings at the same time. +This is used here to display a `String`, the result of the `format!` call, using the same mechanism as some statically-available `&str` slices. +Secondly, that the `ANSIStrings` value works in the same way as its singular counterpart, with a `Display` implementation that only performs the formatting when required. + +## Byte strings + +This library also supports formatting `[u8]` byte strings; this supports applications working with text in an unknown encoding. +`Style` and `Colour` support painting `[u8]` values, resulting in an `ANSIByteString`. +This type does not implement `Display`, as it may not contain UTF-8, but it does provide a method `write_to` to write the result to any value that implements `Write`: + +```rust +use ansi_term::Colour::Green; + +Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap(); +``` + +Similarly, the type `ANSIByteStrings` supports writing a list of `ANSIByteString` values with minimal escape sequences: + +```rust +use ansi_term::Colour::Green; +use ansi_term::ANSIByteStrings; + +ANSIByteStrings(&[ + Green.paint("user data 1\n".as_bytes()), + Green.bold().paint("user data 2\n".as_bytes()), +]).write_to(&mut std::io::stdout()).unwrap(); +``` diff --git a/bash-5.1/vendor/ansi_term/examples/256_colours.rs b/bash-5.1/vendor/ansi_term/examples/256_colours.rs new file mode 100644 index 0000000..92fe2f1 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/examples/256_colours.rs @@ -0,0 +1,73 @@ +extern crate ansi_term; +use ansi_term::Colour; + +// This example prints out the 256 colours. +// They're arranged like this: +// +// - 0 to 8 are the eight standard colours. +// - 9 to 15 are the eight bold colours. +// - 16 to 231 are six blocks of six-by-six colour squares. +// - 232 to 255 are shades of grey. + +fn main() { + + // First two lines + for c in 0..8 { + glow(c, c != 0); + print!(" "); + } + print!("\n"); + for c in 8..16 { + glow(c, c != 8); + print!(" "); + } + print!("\n\n"); + + // Six lines of the first three squares + for row in 0..6 { + for square in 0..3 { + for column in 0..6 { + glow(16 + square * 36 + row * 6 + column, row >= 3); + print!(" "); + } + + print!(" "); + } + + print!("\n"); + } + print!("\n"); + + // Six more lines of the other three squares + for row in 0..6 { + for square in 0..3 { + for column in 0..6 { + glow(124 + square * 36 + row * 6 + column, row >= 3); + print!(" "); + } + + print!(" "); + } + + print!("\n"); + } + print!("\n"); + + // The last greyscale lines + for c in 232..=243 { + glow(c, false); + print!(" "); + } + print!("\n"); + for c in 244..=255 { + glow(c, true); + print!(" "); + } + print!("\n"); +} + +fn glow(c: u8, light_bg: bool) { + let base = if light_bg { Colour::Black } else { Colour::White }; + let style = base.on(Colour::Fixed(c)); + print!("{}", style.paint(&format!(" {:3} ", c))); +} diff --git a/bash-5.1/vendor/ansi_term/examples/basic_colours.rs b/bash-5.1/vendor/ansi_term/examples/basic_colours.rs new file mode 100644 index 0000000..ba88156 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/examples/basic_colours.rs @@ -0,0 +1,18 @@ +extern crate ansi_term; +use ansi_term::{Style, Colour::*}; + +// This example prints out the 16 basic colours. + +fn main() { + let normal = Style::default(); + + println!("{} {}", normal.paint("Normal"), normal.bold().paint("bold")); + println!("{} {}", Black.paint("Black"), Black.bold().paint("bold")); + println!("{} {}", Red.paint("Red"), Red.bold().paint("bold")); + println!("{} {}", Green.paint("Green"), Green.bold().paint("bold")); + println!("{} {}", Yellow.paint("Yellow"), Yellow.bold().paint("bold")); + println!("{} {}", Blue.paint("Blue"), Blue.bold().paint("bold")); + println!("{} {}", Purple.paint("Purple"), Purple.bold().paint("bold")); + println!("{} {}", Cyan.paint("Cyan"), Cyan.bold().paint("bold")); + println!("{} {}", White.paint("White"), White.bold().paint("bold")); +} diff --git a/bash-5.1/vendor/ansi_term/examples/rgb_colours.rs b/bash-5.1/vendor/ansi_term/examples/rgb_colours.rs new file mode 100644 index 0000000..fd2cc7a --- /dev/null +++ b/bash-5.1/vendor/ansi_term/examples/rgb_colours.rs @@ -0,0 +1,23 @@ +extern crate ansi_term; +use ansi_term::{Style, Colour}; + +// This example prints out a colour gradient in a grid by calculating each +// character’s red, green, and blue components, and using 24-bit colour codes +// to display them. + +const WIDTH: i32 = 80; +const HEIGHT: i32 = 24; + +fn main() { + for row in 0 .. HEIGHT { + for col in 0 .. WIDTH { + let r = (row * 255 / HEIGHT) as u8; + let g = (col * 255 / WIDTH) as u8; + let b = 128; + + print!("{}", Style::default().on(Colour::RGB(r, g, b)).paint(" ")); + } + + print!("\n"); + } +} diff --git a/bash-5.1/vendor/ansi_term/src/ansi.rs b/bash-5.1/vendor/ansi_term/src/ansi.rs new file mode 100644 index 0000000..aaf2152 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/ansi.rs @@ -0,0 +1,374 @@ +use style::{Colour, Style}; + +use std::fmt; + +use write::AnyWrite; + + +// ---- generating ANSI codes ---- + +impl Style { + + /// Write any bytes that go *before* a piece of text to the given writer. + fn write_prefix(&self, f: &mut W) -> Result<(), W::Error> { + + // If there are actually no styles here, then don’t write *any* codes + // as the prefix. An empty ANSI code may not affect the terminal + // output at all, but a user may just want a code-free string. + if self.is_plain() { + return Ok(()); + } + + // Write the codes’ prefix, then write numbers, separated by + // semicolons, for each text style we want to apply. + write!(f, "\x1B[")?; + let mut written_anything = false; + + { + let mut write_char = |c| { + if written_anything { write!(f, ";")?; } + written_anything = true; + write!(f, "{}", c)?; + Ok(()) + }; + + if self.is_bold { write_char('1')? } + if self.is_dimmed { write_char('2')? } + if self.is_italic { write_char('3')? } + if self.is_underline { write_char('4')? } + if self.is_blink { write_char('5')? } + if self.is_reverse { write_char('7')? } + if self.is_hidden { write_char('8')? } + if self.is_strikethrough { write_char('9')? } + } + + // The foreground and background colours, if specified, need to be + // handled specially because the number codes are more complicated. + // (see `write_background_code` and `write_foreground_code`) + if let Some(bg) = self.background { + if written_anything { write!(f, ";")?; } + written_anything = true; + bg.write_background_code(f)?; + } + + if let Some(fg) = self.foreground { + if written_anything { write!(f, ";")?; } + fg.write_foreground_code(f)?; + } + + // All the codes end with an `m`, because reasons. + write!(f, "m")?; + + Ok(()) + } + + /// Write any bytes that go *after* a piece of text to the given writer. + fn write_suffix(&self, f: &mut W) -> Result<(), W::Error> { + if self.is_plain() { + Ok(()) + } + else { + write!(f, "{}", RESET) + } + } +} + + +/// The code to send to reset all styles and return to `Style::default()`. +pub static RESET: &str = "\x1B[0m"; + + + +impl Colour { + fn write_foreground_code(&self, f: &mut W) -> Result<(), W::Error> { + match *self { + Colour::Black => write!(f, "30"), + Colour::Red => write!(f, "31"), + Colour::Green => write!(f, "32"), + Colour::Yellow => write!(f, "33"), + Colour::Blue => write!(f, "34"), + Colour::Purple => write!(f, "35"), + Colour::Cyan => write!(f, "36"), + Colour::White => write!(f, "37"), + Colour::Fixed(num) => write!(f, "38;5;{}", &num), + Colour::RGB(r,g,b) => write!(f, "38;2;{};{};{}", &r, &g, &b), + } + } + + fn write_background_code(&self, f: &mut W) -> Result<(), W::Error> { + match *self { + Colour::Black => write!(f, "40"), + Colour::Red => write!(f, "41"), + Colour::Green => write!(f, "42"), + Colour::Yellow => write!(f, "43"), + Colour::Blue => write!(f, "44"), + Colour::Purple => write!(f, "45"), + Colour::Cyan => write!(f, "46"), + Colour::White => write!(f, "47"), + Colour::Fixed(num) => write!(f, "48;5;{}", &num), + Colour::RGB(r,g,b) => write!(f, "48;2;{};{};{}", &r, &g, &b), + } + } +} + + +/// Like `ANSIString`, but only displays the style prefix. +/// +/// This type implements the `Display` trait, meaning it can be written to a +/// `std::fmt` formatting without doing any extra allocation, and written to a +/// string with the `.to_string()` method. For examples, see +/// [`Style::prefix`](struct.Style.html#method.prefix). +#[derive(Clone, Copy, Debug)] +pub struct Prefix(Style); + +/// Like `ANSIString`, but only displays the difference between two +/// styles. +/// +/// This type implements the `Display` trait, meaning it can be written to a +/// `std::fmt` formatting without doing any extra allocation, and written to a +/// string with the `.to_string()` method. For examples, see +/// [`Style::infix`](struct.Style.html#method.infix). +#[derive(Clone, Copy, Debug)] +pub struct Infix(Style, Style); + +/// Like `ANSIString`, but only displays the style suffix. +/// +/// This type implements the `Display` trait, meaning it can be written to a +/// `std::fmt` formatting without doing any extra allocation, and written to a +/// string with the `.to_string()` method. For examples, see +/// [`Style::suffix`](struct.Style.html#method.suffix). +#[derive(Clone, Copy, Debug)] +pub struct Suffix(Style); + + +impl Style { + + /// The prefix bytes for this style. These are the bytes that tell the + /// terminal to use a different colour or font style. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::{Style, Colour::Blue}; + /// + /// let style = Style::default().bold(); + /// assert_eq!("\x1b[1m", + /// style.prefix().to_string()); + /// + /// let style = Blue.bold(); + /// assert_eq!("\x1b[1;34m", + /// style.prefix().to_string()); + /// + /// let style = Style::default(); + /// assert_eq!("", + /// style.prefix().to_string()); + /// ``` + pub fn prefix(self) -> Prefix { + Prefix(self) + } + + /// The infix bytes between this style and `next` style. These are the bytes + /// that tell the terminal to change the style to `next`. These may include + /// a reset followed by the next colour and style, depending on the two styles. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::{Style, Colour::Green}; + /// + /// let style = Style::default().bold(); + /// assert_eq!("\x1b[32m", + /// style.infix(Green.bold()).to_string()); + /// + /// let style = Green.normal(); + /// assert_eq!("\x1b[1m", + /// style.infix(Green.bold()).to_string()); + /// + /// let style = Style::default(); + /// assert_eq!("", + /// style.infix(style).to_string()); + /// ``` + pub fn infix(self, next: Style) -> Infix { + Infix(self, next) + } + + /// The suffix for this style. These are the bytes that tell the terminal + /// to reset back to its normal colour and font style. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::{Style, Colour::Green}; + /// + /// let style = Style::default().bold(); + /// assert_eq!("\x1b[0m", + /// style.suffix().to_string()); + /// + /// let style = Green.normal().bold(); + /// assert_eq!("\x1b[0m", + /// style.suffix().to_string()); + /// + /// let style = Style::default(); + /// assert_eq!("", + /// style.suffix().to_string()); + /// ``` + pub fn suffix(self) -> Suffix { + Suffix(self) + } +} + + +impl Colour { + + /// The prefix bytes for this colour as a `Style`. These are the bytes + /// that tell the terminal to use a different colour or font style. + /// + /// See also [`Style::prefix`](struct.Style.html#method.prefix). + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour::Green; + /// + /// assert_eq!("\x1b[0m", + /// Green.suffix().to_string()); + /// ``` + pub fn prefix(self) -> Prefix { + Prefix(self.normal()) + } + + /// The infix bytes between this colour and `next` colour. These are the bytes + /// that tell the terminal to use the `next` colour, or to do nothing if + /// the two colours are equal. + /// + /// See also [`Style::infix`](struct.Style.html#method.infix). + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour::{Red, Yellow}; + /// + /// assert_eq!("\x1b[33m", + /// Red.infix(Yellow).to_string()); + /// ``` + pub fn infix(self, next: Colour) -> Infix { + Infix(self.normal(), next.normal()) + } + + /// The suffix for this colour as a `Style`. These are the bytes that + /// tell the terminal to reset back to its normal colour and font style. + /// + /// See also [`Style::suffix`](struct.Style.html#method.suffix). + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour::Purple; + /// + /// assert_eq!("\x1b[0m", + /// Purple.suffix().to_string()); + /// ``` + pub fn suffix(self) -> Suffix { + Suffix(self.normal()) + } +} + + +impl fmt::Display for Prefix { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let f: &mut fmt::Write = f; + self.0.write_prefix(f) + } +} + + +impl fmt::Display for Infix { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use difference::Difference; + + match Difference::between(&self.0, &self.1) { + Difference::ExtraStyles(style) => { + let f: &mut fmt::Write = f; + style.write_prefix(f) + }, + Difference::Reset => { + let f: &mut fmt::Write = f; + write!(f, "{}{}", RESET, self.1.prefix()) + }, + Difference::NoDifference => { + Ok(()) // nothing to write + }, + } + } +} + + +impl fmt::Display for Suffix { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let f: &mut fmt::Write = f; + self.0.write_suffix(f) + } +} + + + +#[cfg(test)] +mod test { + use style::Style; + use style::Colour::*; + + macro_rules! test { + ($name: ident: $style: expr; $input: expr => $result: expr) => { + #[test] + fn $name() { + assert_eq!($style.paint($input).to_string(), $result.to_string()); + + let mut v = Vec::new(); + $style.paint($input.as_bytes()).write_to(&mut v).unwrap(); + assert_eq!(v.as_slice(), $result.as_bytes()); + } + }; + } + + test!(plain: Style::default(); "text/plain" => "text/plain"); + test!(red: Red; "hi" => "\x1B[31mhi\x1B[0m"); + test!(black: Black.normal(); "hi" => "\x1B[30mhi\x1B[0m"); + test!(yellow_bold: Yellow.bold(); "hi" => "\x1B[1;33mhi\x1B[0m"); + test!(yellow_bold_2: Yellow.normal().bold(); "hi" => "\x1B[1;33mhi\x1B[0m"); + test!(blue_underline: Blue.underline(); "hi" => "\x1B[4;34mhi\x1B[0m"); + test!(green_bold_ul: Green.bold().underline(); "hi" => "\x1B[1;4;32mhi\x1B[0m"); + test!(green_bold_ul_2: Green.underline().bold(); "hi" => "\x1B[1;4;32mhi\x1B[0m"); + test!(purple_on_white: Purple.on(White); "hi" => "\x1B[47;35mhi\x1B[0m"); + test!(purple_on_white_2: Purple.normal().on(White); "hi" => "\x1B[47;35mhi\x1B[0m"); + test!(yellow_on_blue: Style::new().on(Blue).fg(Yellow); "hi" => "\x1B[44;33mhi\x1B[0m"); + test!(yellow_on_blue_2: Cyan.on(Blue).fg(Yellow); "hi" => "\x1B[44;33mhi\x1B[0m"); + test!(cyan_bold_on_white: Cyan.bold().on(White); "hi" => "\x1B[1;47;36mhi\x1B[0m"); + test!(cyan_ul_on_white: Cyan.underline().on(White); "hi" => "\x1B[4;47;36mhi\x1B[0m"); + test!(cyan_bold_ul_on_white: Cyan.bold().underline().on(White); "hi" => "\x1B[1;4;47;36mhi\x1B[0m"); + test!(cyan_ul_bold_on_white: Cyan.underline().bold().on(White); "hi" => "\x1B[1;4;47;36mhi\x1B[0m"); + test!(fixed: Fixed(100); "hi" => "\x1B[38;5;100mhi\x1B[0m"); + test!(fixed_on_purple: Fixed(100).on(Purple); "hi" => "\x1B[45;38;5;100mhi\x1B[0m"); + test!(fixed_on_fixed: Fixed(100).on(Fixed(200)); "hi" => "\x1B[48;5;200;38;5;100mhi\x1B[0m"); + test!(rgb: RGB(70,130,180); "hi" => "\x1B[38;2;70;130;180mhi\x1B[0m"); + test!(rgb_on_blue: RGB(70,130,180).on(Blue); "hi" => "\x1B[44;38;2;70;130;180mhi\x1B[0m"); + test!(blue_on_rgb: Blue.on(RGB(70,130,180)); "hi" => "\x1B[48;2;70;130;180;34mhi\x1B[0m"); + test!(rgb_on_rgb: RGB(70,130,180).on(RGB(5,10,15)); "hi" => "\x1B[48;2;5;10;15;38;2;70;130;180mhi\x1B[0m"); + test!(bold: Style::new().bold(); "hi" => "\x1B[1mhi\x1B[0m"); + test!(underline: Style::new().underline(); "hi" => "\x1B[4mhi\x1B[0m"); + test!(bunderline: Style::new().bold().underline(); "hi" => "\x1B[1;4mhi\x1B[0m"); + test!(dimmed: Style::new().dimmed(); "hi" => "\x1B[2mhi\x1B[0m"); + test!(italic: Style::new().italic(); "hi" => "\x1B[3mhi\x1B[0m"); + test!(blink: Style::new().blink(); "hi" => "\x1B[5mhi\x1B[0m"); + test!(reverse: Style::new().reverse(); "hi" => "\x1B[7mhi\x1B[0m"); + test!(hidden: Style::new().hidden(); "hi" => "\x1B[8mhi\x1B[0m"); + test!(stricken: Style::new().strikethrough(); "hi" => "\x1B[9mhi\x1B[0m"); + + #[test] + fn test_infix() { + assert_eq!(Style::new().dimmed().infix(Style::new()).to_string(), "\x1B[0m"); + assert_eq!(White.dimmed().infix(White.normal()).to_string(), "\x1B[0m\x1B[37m"); + assert_eq!(White.normal().infix(White.bold()).to_string(), "\x1B[1m"); + assert_eq!(White.normal().infix(Blue.normal()).to_string(), "\x1B[34m"); + assert_eq!(Blue.bold().infix(Blue.bold()).to_string(), ""); + } +} diff --git a/bash-5.1/vendor/ansi_term/src/debug.rs b/bash-5.1/vendor/ansi_term/src/debug.rs new file mode 100644 index 0000000..4877323 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/debug.rs @@ -0,0 +1,134 @@ +use std::fmt; + +use style::Style; + +/// Styles have a special `Debug` implementation that only shows the fields that +/// are set. Fields that haven’t been touched aren’t included in the output. +/// +/// This behaviour gets bypassed when using the alternate formatting mode +/// `format!("{:#?}")`. +/// +/// use ansi_term::Colour::{Red, Blue}; +/// assert_eq!("Style { fg(Red), on(Blue), bold, italic }", +/// format!("{:?}", Red.on(Blue).bold().italic())); +impl fmt::Debug for Style { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + if fmt.alternate() { + fmt.debug_struct("Style") + .field("foreground", &self.foreground) + .field("background", &self.background) + .field("blink", &self.is_blink) + .field("bold", &self.is_bold) + .field("dimmed", &self.is_dimmed) + .field("hidden", &self.is_hidden) + .field("italic", &self.is_italic) + .field("reverse", &self.is_reverse) + .field("strikethrough", &self.is_strikethrough) + .field("underline", &self.is_underline) + .finish() + } + else if self.is_plain() { + fmt.write_str("Style {}") + } + else { + fmt.write_str("Style { ")?; + + let mut written_anything = false; + + if let Some(fg) = self.foreground { + if written_anything { fmt.write_str(", ")? } + written_anything = true; + write!(fmt, "fg({:?})", fg)? + } + + if let Some(bg) = self.background { + if written_anything { fmt.write_str(", ")? } + written_anything = true; + write!(fmt, "on({:?})", bg)? + } + + { + let mut write_flag = |name| { + if written_anything { fmt.write_str(", ")? } + written_anything = true; + fmt.write_str(name) + }; + + if self.is_blink { write_flag("blink")? } + if self.is_bold { write_flag("bold")? } + if self.is_dimmed { write_flag("dimmed")? } + if self.is_hidden { write_flag("hidden")? } + if self.is_italic { write_flag("italic")? } + if self.is_reverse { write_flag("reverse")? } + if self.is_strikethrough { write_flag("strikethrough")? } + if self.is_underline { write_flag("underline")? } + } + + write!(fmt, " }}") + } + } +} + + +#[cfg(test)] +mod test { + use style::Colour::*; + use style::Style; + + fn style() -> Style { + Style::new() + } + + macro_rules! test { + ($name: ident: $obj: expr => $result: expr) => { + #[test] + fn $name() { + assert_eq!($result, format!("{:?}", $obj)); + } + }; + } + + test!(empty: style() => "Style {}"); + test!(bold: style().bold() => "Style { bold }"); + test!(italic: style().italic() => "Style { italic }"); + test!(both: style().bold().italic() => "Style { bold, italic }"); + + test!(red: Red.normal() => "Style { fg(Red) }"); + test!(redblue: Red.normal().on(RGB(3, 2, 4)) => "Style { fg(Red), on(RGB(3, 2, 4)) }"); + + test!(everything: + Red.on(Blue).blink().bold().dimmed().hidden().italic().reverse().strikethrough().underline() => + "Style { fg(Red), on(Blue), blink, bold, dimmed, hidden, italic, reverse, strikethrough, underline }"); + + #[test] + fn long_and_detailed() { + extern crate regex; + let expected_debug = "Style { fg(Blue), bold }"; + let expected_pretty_repat = r##"(?x) + Style\s+\{\s+ + foreground:\s+Some\(\s+ + Blue,?\s+ + \),\s+ + background:\s+None,\s+ + blink:\s+false,\s+ + bold:\s+true,\s+ + dimmed:\s+false,\s+ + hidden:\s+false,\s+ + italic:\s+false,\s+ + reverse:\s+false,\s+ + strikethrough:\s+ + false,\s+ + underline:\s+false,?\s+ + \}"##; + let re = regex::Regex::new(expected_pretty_repat).unwrap(); + + let style = Blue.bold(); + let style_fmt_debug = format!("{:?}", style); + let style_fmt_pretty = format!("{:#?}", style); + println!("style_fmt_debug:\n{}", style_fmt_debug); + println!("style_fmt_pretty:\n{}", style_fmt_pretty); + + assert_eq!(expected_debug, style_fmt_debug); + assert!(re.is_match(&style_fmt_pretty)); + } +} diff --git a/bash-5.1/vendor/ansi_term/src/difference.rs b/bash-5.1/vendor/ansi_term/src/difference.rs new file mode 100644 index 0000000..b0de07f --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/difference.rs @@ -0,0 +1,179 @@ +use super::Style; + + +/// When printing out one coloured string followed by another, use one of +/// these rules to figure out which *extra* control codes need to be sent. +#[derive(PartialEq, Clone, Copy, Debug)] +pub enum Difference { + + /// Print out the control codes specified by this style to end up looking + /// like the second string's styles. + ExtraStyles(Style), + + /// Converting between these two is impossible, so just send a reset + /// command and then the second string's styles. + Reset, + + /// The before style is exactly the same as the after style, so no further + /// control codes need to be printed. + NoDifference, +} + + +impl Difference { + + /// Compute the 'style difference' required to turn an existing style into + /// the given, second style. + /// + /// For example, to turn green text into green bold text, it's redundant + /// to write a reset command then a second green+bold command, instead of + /// just writing one bold command. This method should see that both styles + /// use the foreground colour green, and reduce it to a single command. + /// + /// This method returns an enum value because it's not actually always + /// possible to turn one style into another: for example, text could be + /// made bold and underlined, but you can't remove the bold property + /// without also removing the underline property. So when this has to + /// happen, this function returns None, meaning that the entire set of + /// styles should be reset and begun again. + pub fn between(first: &Style, next: &Style) -> Difference { + use self::Difference::*; + + // XXX(Havvy): This algorithm is kind of hard to replicate without + // having the Plain/Foreground enum variants, so I'm just leaving + // it commented out for now, and defaulting to Reset. + + if first == next { + return NoDifference; + } + + // Cannot un-bold, so must Reset. + if first.is_bold && !next.is_bold { + return Reset; + } + + if first.is_dimmed && !next.is_dimmed { + return Reset; + } + + if first.is_italic && !next.is_italic { + return Reset; + } + + // Cannot un-underline, so must Reset. + if first.is_underline && !next.is_underline { + return Reset; + } + + if first.is_blink && !next.is_blink { + return Reset; + } + + if first.is_reverse && !next.is_reverse { + return Reset; + } + + if first.is_hidden && !next.is_hidden { + return Reset; + } + + if first.is_strikethrough && !next.is_strikethrough { + return Reset; + } + + // Cannot go from foreground to no foreground, so must Reset. + if first.foreground.is_some() && next.foreground.is_none() { + return Reset; + } + + // Cannot go from background to no background, so must Reset. + if first.background.is_some() && next.background.is_none() { + return Reset; + } + + let mut extra_styles = Style::default(); + + if first.is_bold != next.is_bold { + extra_styles.is_bold = true; + } + + if first.is_dimmed != next.is_dimmed { + extra_styles.is_dimmed = true; + } + + if first.is_italic != next.is_italic { + extra_styles.is_italic = true; + } + + if first.is_underline != next.is_underline { + extra_styles.is_underline = true; + } + + if first.is_blink != next.is_blink { + extra_styles.is_blink = true; + } + + if first.is_reverse != next.is_reverse { + extra_styles.is_reverse = true; + } + + if first.is_hidden != next.is_hidden { + extra_styles.is_hidden = true; + } + + if first.is_strikethrough != next.is_strikethrough { + extra_styles.is_strikethrough = true; + } + + if first.foreground != next.foreground { + extra_styles.foreground = next.foreground; + } + + if first.background != next.background { + extra_styles.background = next.background; + } + + ExtraStyles(extra_styles) + } +} + + +#[cfg(test)] +mod test { + use super::*; + use super::Difference::*; + use style::Colour::*; + use style::Style; + + fn style() -> Style { + Style::new() + } + + macro_rules! test { + ($name: ident: $first: expr; $next: expr => $result: expr) => { + #[test] + fn $name() { + assert_eq!($result, Difference::between(&$first, &$next)); + } + }; + } + + test!(nothing: Green.normal(); Green.normal() => NoDifference); + test!(uppercase: Green.normal(); Green.bold() => ExtraStyles(style().bold())); + test!(lowercase: Green.bold(); Green.normal() => Reset); + test!(nothing2: Green.bold(); Green.bold() => NoDifference); + + test!(colour_change: Red.normal(); Blue.normal() => ExtraStyles(Blue.normal())); + + test!(addition_of_blink: style(); style().blink() => ExtraStyles(style().blink())); + test!(addition_of_dimmed: style(); style().dimmed() => ExtraStyles(style().dimmed())); + test!(addition_of_hidden: style(); style().hidden() => ExtraStyles(style().hidden())); + test!(addition_of_reverse: style(); style().reverse() => ExtraStyles(style().reverse())); + test!(addition_of_strikethrough: style(); style().strikethrough() => ExtraStyles(style().strikethrough())); + + test!(removal_of_strikethrough: style().strikethrough(); style() => Reset); + test!(removal_of_reverse: style().reverse(); style() => Reset); + test!(removal_of_hidden: style().hidden(); style() => Reset); + test!(removal_of_dimmed: style().dimmed(); style() => Reset); + test!(removal_of_blink: style().blink(); style() => Reset); +} diff --git a/bash-5.1/vendor/ansi_term/src/display.rs b/bash-5.1/vendor/ansi_term/src/display.rs new file mode 100644 index 0000000..17c54f0 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/display.rs @@ -0,0 +1,296 @@ +use std::borrow::Cow; +use std::fmt; +use std::io; +use std::ops::Deref; + +use ansi::RESET; +use difference::Difference; +use style::{Style, Colour}; +use write::AnyWrite; + + +/// An `ANSIGenericString` includes a generic string type and a `Style` to +/// display that string. `ANSIString` and `ANSIByteString` are aliases for +/// this type on `str` and `\[u8]`, respectively. +#[derive(PartialEq, Debug)] +pub struct ANSIGenericString<'a, S: 'a + ToOwned + ?Sized> +where ::Owned: fmt::Debug { + style: Style, + string: Cow<'a, S>, +} + + +/// Cloning an `ANSIGenericString` will clone its underlying string. +/// +/// # Examples +/// +/// ``` +/// use ansi_term::ANSIString; +/// +/// let plain_string = ANSIString::from("a plain string"); +/// let clone_string = plain_string.clone(); +/// assert_eq!(clone_string, plain_string); +/// ``` +impl<'a, S: 'a + ToOwned + ?Sized> Clone for ANSIGenericString<'a, S> +where ::Owned: fmt::Debug { + fn clone(&self) -> ANSIGenericString<'a, S> { + ANSIGenericString { + style: self.style, + string: self.string.clone(), + } + } +} + +// You might think that the hand-written Clone impl above is the same as the +// one that gets generated with #[derive]. But it’s not *quite* the same! +// +// `str` is not Clone, and the derived Clone implementation puts a Clone +// constraint on the S type parameter (generated using --pretty=expanded): +// +// ↓_________________↓ +// impl <'a, S: ::std::clone::Clone + 'a + ToOwned + ?Sized> ::std::clone::Clone +// for ANSIGenericString<'a, S> where +// ::Owned: fmt::Debug { ... } +// +// This resulted in compile errors when you tried to derive Clone on a type +// that used it: +// +// #[derive(PartialEq, Debug, Clone, Default)] +// pub struct TextCellContents(Vec>); +// ^^^^^^^^^^^^^^^^^^^^^^^^^ +// error[E0277]: the trait `std::clone::Clone` is not implemented for `str` +// +// The hand-written impl above can ignore that constraint and still compile. + + + +/// An ANSI String is a string coupled with the `Style` to display it +/// in a terminal. +/// +/// Although not technically a string itself, it can be turned into +/// one with the `to_string` method. +/// +/// # Examples +/// +/// ``` +/// use ansi_term::ANSIString; +/// use ansi_term::Colour::Red; +/// +/// let red_string = Red.paint("a red string"); +/// println!("{}", red_string); +/// ``` +/// +/// ``` +/// use ansi_term::ANSIString; +/// +/// let plain_string = ANSIString::from("a plain string"); +/// assert_eq!(&*plain_string, "a plain string"); +/// ``` +pub type ANSIString<'a> = ANSIGenericString<'a, str>; + +/// An `ANSIByteString` represents a formatted series of bytes. Use +/// `ANSIByteString` when styling text with an unknown encoding. +pub type ANSIByteString<'a> = ANSIGenericString<'a, [u8]>; + +impl<'a, I, S: 'a + ToOwned + ?Sized> From for ANSIGenericString<'a, S> +where I: Into>, + ::Owned: fmt::Debug { + fn from(input: I) -> ANSIGenericString<'a, S> { + ANSIGenericString { + string: input.into(), + style: Style::default(), + } + } +} + +impl<'a, S: 'a + ToOwned + ?Sized> ANSIGenericString<'a, S> + where ::Owned: fmt::Debug { + + /// Directly access the style + pub fn style_ref(&self) -> &Style { + &self.style + } + + /// Directly access the style mutably + pub fn style_ref_mut(&mut self) -> &mut Style { + &mut self.style + } +} + +impl<'a, S: 'a + ToOwned + ?Sized> Deref for ANSIGenericString<'a, S> +where ::Owned: fmt::Debug { + type Target = S; + + fn deref(&self) -> &S { + self.string.deref() + } +} + + +/// A set of `ANSIGenericString`s collected together, in order to be +/// written with a minimum of control characters. +#[derive(Debug, PartialEq)] +pub struct ANSIGenericStrings<'a, S: 'a + ToOwned + ?Sized> + (pub &'a [ANSIGenericString<'a, S>]) + where ::Owned: fmt::Debug, S: PartialEq; + +/// A set of `ANSIString`s collected together, in order to be written with a +/// minimum of control characters. +pub type ANSIStrings<'a> = ANSIGenericStrings<'a, str>; + +/// A function to construct an `ANSIStrings` instance. +#[allow(non_snake_case)] +pub fn ANSIStrings<'a>(arg: &'a [ANSIString<'a>]) -> ANSIStrings<'a> { + ANSIGenericStrings(arg) +} + +/// A set of `ANSIByteString`s collected together, in order to be +/// written with a minimum of control characters. +pub type ANSIByteStrings<'a> = ANSIGenericStrings<'a, [u8]>; + +/// A function to construct an `ANSIByteStrings` instance. +#[allow(non_snake_case)] +pub fn ANSIByteStrings<'a>(arg: &'a [ANSIByteString<'a>]) -> ANSIByteStrings<'a> { + ANSIGenericStrings(arg) +} + + +// ---- paint functions ---- + +impl Style { + + /// Paints the given text with this colour, returning an ANSI string. + #[must_use] + pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(self, input: I) -> ANSIGenericString<'a, S> + where I: Into>, + ::Owned: fmt::Debug { + ANSIGenericString { + string: input.into(), + style: self, + } + } +} + + +impl Colour { + + /// Paints the given text with this colour, returning an ANSI string. + /// This is a short-cut so you don’t have to use `Blue.normal()` just + /// to get blue text. + /// + /// ``` + /// use ansi_term::Colour::Blue; + /// println!("{}", Blue.paint("da ba dee")); + /// ``` + #[must_use] + pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(self, input: I) -> ANSIGenericString<'a, S> + where I: Into>, + ::Owned: fmt::Debug { + ANSIGenericString { + string: input.into(), + style: self.normal(), + } + } +} + + +// ---- writers for individual ANSI strings ---- + +impl<'a> fmt::Display for ANSIString<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let w: &mut fmt::Write = f; + self.write_to_any(w) + } +} + +impl<'a> ANSIByteString<'a> { + /// Write an `ANSIByteString` to an `io::Write`. This writes the escape + /// sequences for the associated `Style` around the bytes. + pub fn write_to(&self, w: &mut W) -> io::Result<()> { + let w: &mut io::Write = w; + self.write_to_any(w) + } +} + +impl<'a, S: 'a + ToOwned + ?Sized> ANSIGenericString<'a, S> +where ::Owned: fmt::Debug, &'a S: AsRef<[u8]> { + fn write_to_any + ?Sized>(&self, w: &mut W) -> Result<(), W::Error> { + write!(w, "{}", self.style.prefix())?; + w.write_str(self.string.as_ref())?; + write!(w, "{}", self.style.suffix()) + } +} + + +// ---- writers for combined ANSI strings ---- + +impl<'a> fmt::Display for ANSIStrings<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let f: &mut fmt::Write = f; + self.write_to_any(f) + } +} + +impl<'a> ANSIByteStrings<'a> { + /// Write `ANSIByteStrings` to an `io::Write`. This writes the minimal + /// escape sequences for the associated `Style`s around each set of + /// bytes. + pub fn write_to(&self, w: &mut W) -> io::Result<()> { + let w: &mut io::Write = w; + self.write_to_any(w) + } +} + +impl<'a, S: 'a + ToOwned + ?Sized + PartialEq> ANSIGenericStrings<'a, S> +where ::Owned: fmt::Debug, &'a S: AsRef<[u8]> { + fn write_to_any + ?Sized>(&self, w: &mut W) -> Result<(), W::Error> { + use self::Difference::*; + + let first = match self.0.first() { + None => return Ok(()), + Some(f) => f, + }; + + write!(w, "{}", first.style.prefix())?; + w.write_str(first.string.as_ref())?; + + for window in self.0.windows(2) { + match Difference::between(&window[0].style, &window[1].style) { + ExtraStyles(style) => write!(w, "{}", style.prefix())?, + Reset => write!(w, "{}{}", RESET, window[1].style.prefix())?, + NoDifference => {/* Do nothing! */}, + } + + w.write_str(&window[1].string)?; + } + + // Write the final reset string after all of the ANSIStrings have been + // written, *except* if the last one has no styles, because it would + // have already been written by this point. + if let Some(last) = self.0.last() { + if !last.style.is_plain() { + write!(w, "{}", RESET)?; + } + } + + Ok(()) + } +} + + +// ---- tests ---- + +#[cfg(test)] +mod tests { + pub use super::super::ANSIStrings; + pub use style::Style; + pub use style::Colour::*; + + #[test] + fn no_control_codes_for_plain() { + let one = Style::default().paint("one"); + let two = Style::default().paint("two"); + let output = format!("{}", ANSIStrings( &[ one, two ] )); + assert_eq!(&*output, "onetwo"); + } +} diff --git a/bash-5.1/vendor/ansi_term/src/lib.rs b/bash-5.1/vendor/ansi_term/src/lib.rs new file mode 100644 index 0000000..2d2f83a --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/lib.rs @@ -0,0 +1,271 @@ +//! This is a library for controlling colours and formatting, such as +//! red bold text or blue underlined text, on ANSI terminals. +//! +//! +//! ## Basic usage +//! +//! There are three main types in this crate that you need to be +//! concerned with: [`ANSIString`], [`Style`], and [`Colour`]. +//! +//! A `Style` holds stylistic information: foreground and background colours, +//! whether the text should be bold, or blinking, or other properties. The +//! [`Colour`] enum represents the available colours. And an [`ANSIString`] is a +//! string paired with a [`Style`]. +//! +//! [`Color`] is also available as an alias to `Colour`. +//! +//! To format a string, call the `paint` method on a `Style` or a `Colour`, +//! passing in the string you want to format as the argument. For example, +//! here’s how to get some red text: +//! +//! ``` +//! use ansi_term::Colour::Red; +//! +//! println!("This is in red: {}", Red.paint("a red string")); +//! ``` +//! +//! It’s important to note that the `paint` method does *not* actually return a +//! string with the ANSI control characters surrounding it. Instead, it returns +//! an [`ANSIString`] value that has a [`Display`] implementation that, when +//! formatted, returns the characters. This allows strings to be printed with a +//! minimum of [`String`] allocations being performed behind the scenes. +//! +//! If you *do* want to get at the escape codes, then you can convert the +//! [`ANSIString`] to a string as you would any other `Display` value: +//! +//! ``` +//! use ansi_term::Colour::Red; +//! +//! let red_string = Red.paint("a red string").to_string(); +//! ``` +//! +//! +//! ## Bold, underline, background, and other styles +//! +//! For anything more complex than plain foreground colour changes, you need to +//! construct `Style` values themselves, rather than beginning with a `Colour`. +//! You can do this by chaining methods based on a new `Style`, created with +//! [`Style::new()`]. Each method creates a new style that has that specific +//! property set. For example: +//! +//! ``` +//! use ansi_term::Style; +//! +//! println!("How about some {} and {}?", +//! Style::new().bold().paint("bold"), +//! Style::new().underline().paint("underline")); +//! ``` +//! +//! For brevity, these methods have also been implemented for `Colour` values, +//! so you can give your styles a foreground colour without having to begin with +//! an empty `Style` value: +//! +//! ``` +//! use ansi_term::Colour::{Blue, Yellow}; +//! +//! println!("Demonstrating {} and {}!", +//! Blue.bold().paint("blue bold"), +//! Yellow.underline().paint("yellow underline")); +//! +//! println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!")); +//! ``` +//! +//! The complete list of styles you can use are: [`bold`], [`dimmed`], [`italic`], +//! [`underline`], [`blink`], [`reverse`], [`hidden`], [`strikethrough`], and [`on`] for +//! background colours. +//! +//! In some cases, you may find it easier to change the foreground on an +//! existing `Style` rather than starting from the appropriate `Colour`. +//! You can do this using the [`fg`] method: +//! +//! ``` +//! use ansi_term::Style; +//! use ansi_term::Colour::{Blue, Cyan, Yellow}; +//! +//! println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!")); +//! println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!")); +//! ``` +//! +//! You can turn a `Colour` into a `Style` with the [`normal`] method. +//! This will produce the exact same `ANSIString` as if you just used the +//! `paint` method on the `Colour` directly, but it’s useful in certain cases: +//! for example, you may have a method that returns `Styles`, and need to +//! represent both the “red bold” and “red, but not bold” styles with values of +//! the same type. The `Style` struct also has a [`Default`] implementation if you +//! want to have a style with *nothing* set. +//! +//! ``` +//! use ansi_term::Style; +//! use ansi_term::Colour::Red; +//! +//! Red.normal().paint("yet another red string"); +//! Style::default().paint("a completely regular string"); +//! ``` +//! +//! +//! ## Extended colours +//! +//! You can access the extended range of 256 colours by using the `Colour::Fixed` +//! variant, which takes an argument of the colour number to use. This can be +//! included wherever you would use a `Colour`: +//! +//! ``` +//! use ansi_term::Colour::Fixed; +//! +//! Fixed(134).paint("A sort of light purple"); +//! Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup"); +//! ``` +//! +//! The first sixteen of these values are the same as the normal and bold +//! standard colour variants. There’s nothing stopping you from using these as +//! `Fixed` colours instead, but there’s nothing to be gained by doing so +//! either. +//! +//! You can also access full 24-bit colour by using the `Colour::RGB` variant, +//! which takes separate `u8` arguments for red, green, and blue: +//! +//! ``` +//! use ansi_term::Colour::RGB; +//! +//! RGB(70, 130, 180).paint("Steel blue"); +//! ``` +//! +//! ## Combining successive coloured strings +//! +//! The benefit of writing ANSI escape codes to the terminal is that they +//! *stack*: you do not need to end every coloured string with a reset code if +//! the text that follows it is of a similar style. For example, if you want to +//! have some blue text followed by some blue bold text, it’s possible to send +//! the ANSI code for blue, followed by the ANSI code for bold, and finishing +//! with a reset code without having to have an extra one between the two +//! strings. +//! +//! This crate can optimise the ANSI codes that get printed in situations like +//! this, making life easier for your terminal renderer. The [`ANSIStrings`] +//! type takes a slice of several [`ANSIString`] values, and will iterate over +//! each of them, printing only the codes for the styles that need to be updated +//! as part of its formatting routine. +//! +//! The following code snippet uses this to enclose a binary number displayed in +//! red bold text inside some red, but not bold, brackets: +//! +//! ``` +//! use ansi_term::Colour::Red; +//! use ansi_term::{ANSIString, ANSIStrings}; +//! +//! let some_value = format!("{:b}", 42); +//! let strings: &[ANSIString<'static>] = &[ +//! Red.paint("["), +//! Red.bold().paint(some_value), +//! Red.paint("]"), +//! ]; +//! +//! println!("Value: {}", ANSIStrings(strings)); +//! ``` +//! +//! There are several things to note here. Firstly, the [`paint`] method can take +//! *either* an owned [`String`] or a borrowed [`&str`]. Internally, an [`ANSIString`] +//! holds a copy-on-write ([`Cow`]) string value to deal with both owned and +//! borrowed strings at the same time. This is used here to display a `String`, +//! the result of the `format!` call, using the same mechanism as some +//! statically-available `&str` slices. Secondly, that the [`ANSIStrings`] value +//! works in the same way as its singular counterpart, with a [`Display`] +//! implementation that only performs the formatting when required. +//! +//! ## Byte strings +//! +//! This library also supports formatting `\[u8]` byte strings; this supports +//! applications working with text in an unknown encoding. [`Style`] and +//! [`Colour`] support painting `\[u8]` values, resulting in an [`ANSIByteString`]. +//! This type does not implement [`Display`], as it may not contain UTF-8, but +//! it does provide a method [`write_to`] to write the result to any value that +//! implements [`Write`]: +//! +//! ``` +//! use ansi_term::Colour::Green; +//! +//! Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap(); +//! ``` +//! +//! Similarly, the type [`ANSIByteStrings`] supports writing a list of +//! [`ANSIByteString`] values with minimal escape sequences: +//! +//! ``` +//! use ansi_term::Colour::Green; +//! use ansi_term::ANSIByteStrings; +//! +//! ANSIByteStrings(&[ +//! Green.paint("user data 1\n".as_bytes()), +//! Green.bold().paint("user data 2\n".as_bytes()), +//! ]).write_to(&mut std::io::stdout()).unwrap(); +//! ``` +//! +//! [`Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html +//! [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html +//! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html +//! [`String`]: https://doc.rust-lang.org/std/string/struct.String.html +//! [`&str`]: https://doc.rust-lang.org/std/primitive.str.html +//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +//! [`Style`]: struct.Style.html +//! [`Style::new()`]: struct.Style.html#method.new +//! [`Color`]: enum.Color.html +//! [`Colour`]: enum.Colour.html +//! [`ANSIString`]: type.ANSIString.html +//! [`ANSIStrings`]: type.ANSIStrings.html +//! [`ANSIByteString`]: type.ANSIByteString.html +//! [`ANSIByteStrings`]: type.ANSIByteStrings.html +//! [`write_to`]: type.ANSIByteString.html#method.write_to +//! [`paint`]: type.ANSIByteString.html#method.write_to +//! [`normal`]: enum.Colour.html#method.normal +//! +//! [`bold`]: struct.Style.html#method.bold +//! [`dimmed`]: struct.Style.html#method.dimmed +//! [`italic`]: struct.Style.html#method.italic +//! [`underline`]: struct.Style.html#method.underline +//! [`blink`]: struct.Style.html#method.blink +//! [`reverse`]: struct.Style.html#method.reverse +//! [`hidden`]: struct.Style.html#method.hidden +//! [`strikethrough`]: struct.Style.html#method.strikethrough +//! [`fg`]: struct.Style.html#method.fg +//! [`on`]: struct.Style.html#method.on + +#![crate_name = "ansi_term"] +#![crate_type = "rlib"] +#![crate_type = "dylib"] + +#![warn(missing_copy_implementations)] +#![warn(missing_docs)] +#![warn(trivial_casts, trivial_numeric_casts)] +#![warn(unused_extern_crates, unused_qualifications)] + +#[cfg(target_os="windows")] +extern crate winapi; +#[cfg(test)] +#[macro_use] +extern crate doc_comment; + +#[cfg(test)] +doctest!("../README.md"); + +mod ansi; +pub use ansi::{Prefix, Infix, Suffix}; + +mod style; +pub use style::{Colour, Style}; + +/// Color is a type alias for `Colour`. +pub use Colour as Color; + +mod difference; +mod display; +pub use display::*; + +mod write; + +mod windows; +pub use windows::*; + +mod util; +pub use util::*; + +mod debug; diff --git a/bash-5.1/vendor/ansi_term/src/style.rs b/bash-5.1/vendor/ansi_term/src/style.rs new file mode 100644 index 0000000..1bee4d9 --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/style.rs @@ -0,0 +1,521 @@ +/// A style is a collection of properties that can format a string +/// using ANSI escape codes. +/// +/// # Examples +/// +/// ``` +/// use ansi_term::{Style, Colour}; +/// +/// let style = Style::new().bold().on(Colour::Black); +/// println!("{}", style.paint("Bold on black")); +/// ``` +#[derive(PartialEq, Clone, Copy)] +#[cfg_attr(feature = "derive_serde_style", derive(serde::Deserialize, serde::Serialize))] +pub struct Style { + + /// The style's foreground colour, if it has one. + pub foreground: Option, + + /// The style's background colour, if it has one. + pub background: Option, + + /// Whether this style is bold. + pub is_bold: bool, + + /// Whether this style is dimmed. + pub is_dimmed: bool, + + /// Whether this style is italic. + pub is_italic: bool, + + /// Whether this style is underlined. + pub is_underline: bool, + + /// Whether this style is blinking. + pub is_blink: bool, + + /// Whether this style has reverse colours. + pub is_reverse: bool, + + /// Whether this style is hidden. + pub is_hidden: bool, + + /// Whether this style is struckthrough. + pub is_strikethrough: bool +} + +impl Style { + + /// Creates a new Style with no properties set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new(); + /// println!("{}", style.paint("hi")); + /// ``` + pub fn new() -> Style { + Style::default() + } + + /// Returns a `Style` with the bold property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().bold(); + /// println!("{}", style.paint("hey")); + /// ``` + pub fn bold(&self) -> Style { + Style { is_bold: true, .. *self } + } + + /// Returns a `Style` with the dimmed property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().dimmed(); + /// println!("{}", style.paint("sup")); + /// ``` + pub fn dimmed(&self) -> Style { + Style { is_dimmed: true, .. *self } + } + + /// Returns a `Style` with the italic property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().italic(); + /// println!("{}", style.paint("greetings")); + /// ``` + pub fn italic(&self) -> Style { + Style { is_italic: true, .. *self } + } + + /// Returns a `Style` with the underline property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().underline(); + /// println!("{}", style.paint("salutations")); + /// ``` + pub fn underline(&self) -> Style { + Style { is_underline: true, .. *self } + } + + /// Returns a `Style` with the blink property set. + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().blink(); + /// println!("{}", style.paint("wazzup")); + /// ``` + pub fn blink(&self) -> Style { + Style { is_blink: true, .. *self } + } + + /// Returns a `Style` with the reverse property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().reverse(); + /// println!("{}", style.paint("aloha")); + /// ``` + pub fn reverse(&self) -> Style { + Style { is_reverse: true, .. *self } + } + + /// Returns a `Style` with the hidden property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().hidden(); + /// println!("{}", style.paint("ahoy")); + /// ``` + pub fn hidden(&self) -> Style { + Style { is_hidden: true, .. *self } + } + + /// Returns a `Style` with the strikethrough property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// let style = Style::new().strikethrough(); + /// println!("{}", style.paint("yo")); + /// ``` + pub fn strikethrough(&self) -> Style { + Style { is_strikethrough: true, .. *self } + } + + /// Returns a `Style` with the foreground colour property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::{Style, Colour}; + /// + /// let style = Style::new().fg(Colour::Yellow); + /// println!("{}", style.paint("hi")); + /// ``` + pub fn fg(&self, foreground: Colour) -> Style { + Style { foreground: Some(foreground), .. *self } + } + + /// Returns a `Style` with the background colour property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::{Style, Colour}; + /// + /// let style = Style::new().on(Colour::Blue); + /// println!("{}", style.paint("eyyyy")); + /// ``` + pub fn on(&self, background: Colour) -> Style { + Style { background: Some(background), .. *self } + } + + /// Return true if this `Style` has no actual styles, and can be written + /// without any control characters. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Style; + /// + /// assert_eq!(true, Style::default().is_plain()); + /// assert_eq!(false, Style::default().bold().is_plain()); + /// ``` + pub fn is_plain(self) -> bool { + self == Style::default() + } +} + +impl Default for Style { + + /// Returns a style with *no* properties set. Formatting text using this + /// style returns the exact same text. + /// + /// ``` + /// use ansi_term::Style; + /// assert_eq!(None, Style::default().foreground); + /// assert_eq!(None, Style::default().background); + /// assert_eq!(false, Style::default().is_bold); + /// assert_eq!("txt", Style::default().paint("txt").to_string()); + /// ``` + fn default() -> Style { + Style { + foreground: None, + background: None, + is_bold: false, + is_dimmed: false, + is_italic: false, + is_underline: false, + is_blink: false, + is_reverse: false, + is_hidden: false, + is_strikethrough: false, + } + } +} + + +// ---- colours ---- + +/// A colour is one specific type of ANSI escape code, and can refer +/// to either the foreground or background colour. +/// +/// These use the standard numeric sequences. +/// See +#[derive(PartialEq, Clone, Copy, Debug)] +#[cfg_attr(feature = "derive_serde_style", derive(serde::Deserialize, serde::Serialize))] +pub enum Colour { + + /// Colour #0 (foreground code `30`, background code `40`). + /// + /// This is not necessarily the background colour, and using it as one may + /// render the text hard to read on terminals with dark backgrounds. + Black, + + /// Colour #1 (foreground code `31`, background code `41`). + Red, + + /// Colour #2 (foreground code `32`, background code `42`). + Green, + + /// Colour #3 (foreground code `33`, background code `43`). + Yellow, + + /// Colour #4 (foreground code `34`, background code `44`). + Blue, + + /// Colour #5 (foreground code `35`, background code `45`). + Purple, + + /// Colour #6 (foreground code `36`, background code `46`). + Cyan, + + /// Colour #7 (foreground code `37`, background code `47`). + /// + /// As above, this is not necessarily the foreground colour, and may be + /// hard to read on terminals with light backgrounds. + White, + + /// A colour number from 0 to 255, for use in 256-colour terminal + /// environments. + /// + /// - Colours 0 to 7 are the `Black` to `White` variants respectively. + /// These colours can usually be changed in the terminal emulator. + /// - Colours 8 to 15 are brighter versions of the eight colours above. + /// These can also usually be changed in the terminal emulator, or it + /// could be configured to use the original colours and show the text in + /// bold instead. It varies depending on the program. + /// - Colours 16 to 231 contain several palettes of bright colours, + /// arranged in six squares measuring six by six each. + /// - Colours 232 to 255 are shades of grey from black to white. + /// + /// It might make more sense to look at a [colour chart][cc]. + /// + /// [cc]: https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg + Fixed(u8), + + /// A 24-bit RGB color, as specified by ISO-8613-3. + RGB(u8, u8, u8), +} + + +impl Colour { + + /// Returns a `Style` with the foreground colour set to this colour. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Red.normal(); + /// println!("{}", style.paint("hi")); + /// ``` + pub fn normal(self) -> Style { + Style { foreground: Some(self), .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// bold property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Green.bold(); + /// println!("{}", style.paint("hey")); + /// ``` + pub fn bold(self) -> Style { + Style { foreground: Some(self), is_bold: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// dimmed property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Yellow.dimmed(); + /// println!("{}", style.paint("sup")); + /// ``` + pub fn dimmed(self) -> Style { + Style { foreground: Some(self), is_dimmed: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// italic property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Blue.italic(); + /// println!("{}", style.paint("greetings")); + /// ``` + pub fn italic(self) -> Style { + Style { foreground: Some(self), is_italic: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// underline property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Purple.underline(); + /// println!("{}", style.paint("salutations")); + /// ``` + pub fn underline(self) -> Style { + Style { foreground: Some(self), is_underline: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// blink property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Cyan.blink(); + /// println!("{}", style.paint("wazzup")); + /// ``` + pub fn blink(self) -> Style { + Style { foreground: Some(self), is_blink: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// reverse property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Black.reverse(); + /// println!("{}", style.paint("aloha")); + /// ``` + pub fn reverse(self) -> Style { + Style { foreground: Some(self), is_reverse: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// hidden property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::White.hidden(); + /// println!("{}", style.paint("ahoy")); + /// ``` + pub fn hidden(self) -> Style { + Style { foreground: Some(self), is_hidden: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// strikethrough property set. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::Fixed(244).strikethrough(); + /// println!("{}", style.paint("yo")); + /// ``` + pub fn strikethrough(self) -> Style { + Style { foreground: Some(self), is_strikethrough: true, .. Style::default() } + } + + /// Returns a `Style` with the foreground colour set to this colour and the + /// background colour property set to the given colour. + /// + /// # Examples + /// + /// ``` + /// use ansi_term::Colour; + /// + /// let style = Colour::RGB(31, 31, 31).on(Colour::White); + /// println!("{}", style.paint("eyyyy")); + /// ``` + pub fn on(self, background: Colour) -> Style { + Style { foreground: Some(self), background: Some(background), .. Style::default() } + } +} + +impl From for Style { + + /// You can turn a `Colour` into a `Style` with the foreground colour set + /// with the `From` trait. + /// + /// ``` + /// use ansi_term::{Style, Colour}; + /// let green_foreground = Style::default().fg(Colour::Green); + /// assert_eq!(green_foreground, Colour::Green.normal()); + /// assert_eq!(green_foreground, Colour::Green.into()); + /// assert_eq!(green_foreground, Style::from(Colour::Green)); + /// ``` + fn from(colour: Colour) -> Style { + colour.normal() + } +} + +#[cfg(test)] +#[cfg(feature = "derive_serde_style")] +mod serde_json_tests { + use super::{Style, Colour}; + + #[test] + fn colour_serialization() { + + let colours = &[ + Colour::Red, + Colour::Blue, + Colour::RGB(123, 123, 123), + Colour::Fixed(255), + ]; + + assert_eq!(serde_json::to_string(&colours).unwrap(), String::from("[\"Red\",\"Blue\",{\"RGB\":[123,123,123]},{\"Fixed\":255}]")); + } + + #[test] + fn colour_deserialization() { + let colours = &[ + Colour::Red, + Colour::Blue, + Colour::RGB(123, 123, 123), + Colour::Fixed(255), + ]; + + for colour in colours.into_iter() { + let serialized = serde_json::to_string(&colour).unwrap(); + let deserialized: Colour = serde_json::from_str(&serialized).unwrap(); + + assert_eq!(colour, &deserialized); + } + } + + #[test] + fn style_serialization() { + let style = Style::default(); + + assert_eq!(serde_json::to_string(&style).unwrap(), "{\"foreground\":null,\"background\":null,\"is_bold\":false,\"is_dimmed\":false,\"is_italic\":false,\"is_underline\":false,\"is_blink\":false,\"is_reverse\":false,\"is_hidden\":false,\"is_strikethrough\":false}".to_string()); + } +} diff --git a/bash-5.1/vendor/ansi_term/src/util.rs b/bash-5.1/vendor/ansi_term/src/util.rs new file mode 100644 index 0000000..ba0f12a --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/util.rs @@ -0,0 +1,81 @@ +use display::*; +use std::ops::Deref; + +/// Return a substring of the given ANSIStrings sequence, while keeping the formatting. +pub fn sub_string<'a>(start: usize, len: usize, strs: &ANSIStrings<'a>) -> Vec> { + let mut vec = Vec::new(); + let mut pos = start; + let mut len_rem = len; + + for i in strs.0.iter() { + let fragment = i.deref(); + let frag_len = fragment.len(); + if pos >= frag_len { + pos -= frag_len; + continue; + } + if len_rem <= 0 { + break; + } + + let end = pos + len_rem; + let pos_end = if end >= frag_len { frag_len } else { end }; + + vec.push(i.style_ref().paint(String::from(&fragment[pos..pos_end]))); + + if end <= frag_len { + break; + } + + len_rem -= pos_end - pos; + pos = 0; + } + + vec +} + +/// Return a concatenated copy of `strs` without the formatting, as an allocated `String`. +pub fn unstyle(strs: &ANSIStrings) -> String { + let mut s = String::new(); + + for i in strs.0.iter() { + s += &i.deref(); + } + + s +} + +/// Return the unstyled length of ANSIStrings. This is equaivalent to `unstyle(strs).len()`. +pub fn unstyled_len(strs: &ANSIStrings) -> usize { + let mut l = 0; + for i in strs.0.iter() { + l += i.deref().len(); + } + l +} + +#[cfg(test)] +mod test { + use Colour::*; + use display::*; + use super::*; + + #[test] + fn test() { + let l = [ + Black.paint("first"), + Red.paint("-second"), + White.paint("-third"), + ]; + let a = ANSIStrings(&l); + assert_eq!(unstyle(&a), "first-second-third"); + assert_eq!(unstyled_len(&a), 18); + + let l2 = [ + Black.paint("st"), + Red.paint("-second"), + White.paint("-t"), + ]; + assert_eq!(sub_string(3, 11, &a).as_slice(), &l2); + } +} diff --git a/bash-5.1/vendor/ansi_term/src/windows.rs b/bash-5.1/vendor/ansi_term/src/windows.rs new file mode 100644 index 0000000..fcf02ec --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/windows.rs @@ -0,0 +1,61 @@ +/// Enables ANSI code support on Windows 10. +/// +/// This uses Windows API calls to alter the properties of the console that +/// the program is running in. +/// +/// https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx +/// +/// Returns a `Result` with the Windows error code if unsuccessful. +#[cfg(windows)] +pub fn enable_ansi_support() -> Result<(), u32> { + // ref: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#EXAMPLE_OF_ENABLING_VIRTUAL_TERMINAL_PROCESSING @@ https://archive.is/L7wRJ#76% + + use std::ffi::OsStr; + use std::iter::once; + use std::os::windows::ffi::OsStrExt; + use std::ptr::null_mut; + use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; + use winapi::um::errhandlingapi::GetLastError; + use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING}; + use winapi::um::handleapi::INVALID_HANDLE_VALUE; + use winapi::um::winnt::{FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE}; + + const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004; + + unsafe { + // ref: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew + // Using `CreateFileW("CONOUT$", ...)` to retrieve the console handle works correctly even if STDOUT and/or STDERR are redirected + let console_out_name: Vec = OsStr::new("CONOUT$").encode_wide().chain(once(0)).collect(); + let console_handle = CreateFileW( + console_out_name.as_ptr(), + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_WRITE, + null_mut(), + OPEN_EXISTING, + 0, + null_mut(), + ); + if console_handle == INVALID_HANDLE_VALUE + { + return Err(GetLastError()); + } + + // ref: https://docs.microsoft.com/en-us/windows/console/getconsolemode + let mut console_mode: u32 = 0; + if 0 == GetConsoleMode(console_handle, &mut console_mode) + { + return Err(GetLastError()); + } + + // VT processing not already enabled? + if console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0 { + // https://docs.microsoft.com/en-us/windows/console/setconsolemode + if 0 == SetConsoleMode(console_handle, console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) + { + return Err(GetLastError()); + } + } + } + + return Ok(()); +} diff --git a/bash-5.1/vendor/ansi_term/src/write.rs b/bash-5.1/vendor/ansi_term/src/write.rs new file mode 100644 index 0000000..65a64fe --- /dev/null +++ b/bash-5.1/vendor/ansi_term/src/write.rs @@ -0,0 +1,40 @@ +use std::fmt; +use std::io; + + +pub trait AnyWrite { + type wstr: ?Sized; + type Error; + + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Self::Error>; + + fn write_str(&mut self, s: &Self::wstr) -> Result<(), Self::Error>; +} + + +impl<'a> AnyWrite for fmt::Write + 'a { + type wstr = str; + type Error = fmt::Error; + + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Self::Error> { + fmt::Write::write_fmt(self, fmt) + } + + fn write_str(&mut self, s: &Self::wstr) -> Result<(), Self::Error> { + fmt::Write::write_str(self, s) + } +} + + +impl<'a> AnyWrite for io::Write + 'a { + type wstr = [u8]; + type Error = io::Error; + + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Self::Error> { + io::Write::write_fmt(self, fmt) + } + + fn write_str(&mut self, s: &Self::wstr) -> Result<(), Self::Error> { + io::Write::write_all(self, s) + } +} diff --git a/bash-5.1/vendor/aster/.cargo-checksum.json b/bash-5.1/vendor/aster/.cargo-checksum.json new file mode 100644 index 0000000..0432bf1 --- /dev/null +++ b/bash-5.1/vendor/aster/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"a5b1192b97986381fc06f9e4c7b857867296efe0c585b3a7daff04c991b15e11","src/arm.rs":"83b6ba22ded921ae45e02888e879b2ae73d4659db53e6552675433c3c2e0ed21","src/attr.rs":"7c6d6ff66cfbfa23e5857192db1c7e97c3b2826f4434ea7bd5d4b1ded1fe8b5e","src/block.rs":"71e2268ba151b7ee60a2fe0b0b3a7cf3e2ce3bff4fb0ee260db70ad9b1cd8826","src/constant.rs":"471b0ffc52684733a598a43e08b1719bf6852c26eca74e7f5105f0f964543980","src/ctx.rs":"738213a64a96cfe3beba6d08d82d89d48dc384b37fe726621b324bac5c017859","src/expr.rs":"6e74fc51fe53dada39f4be3371562a015869f29cff37b186fc574aae703251ae","src/fn_decl.rs":"85c30d78942bb7cda0c6bddcf55f1a35b3581a99fb15e33f3abf2763b84f8073","src/generics.rs":"3d8198e7d1b8de295ed8ee5203e6676cbd588a2975ab09709abe51991fc16e21","src/ident.rs":"31ebf657a9c267e24e66ed5e83cc76056e8d2564a8f60883871490e414154223","src/invoke.rs":"03f52dd0b135e8ffcc52c3802cdf8d516ef4a53e393ce4bdd82ced19fd106b88","src/item.rs":"43dec8003165eefaddb7effc7c8664088661c992e96b550a0624ec04e380da9e","src/lib.rs":"64faae6667ed9702bd06fd942dc27e53b7dd484aabe15396ef3c212c0b255316","src/lifetime.rs":"1801727768d88328b816a6aafe92add956d2399a82e794ca2eeac47d5f5bd681","src/lit.rs":"5420333f97ab32d9f373336851c1791802ef73fa5f1bc5139288f503c28a1ba6","src/mac.rs":"ac9569bf0f87a043dcb31063a64cff405b7f6996efaa8d9059cbc4b18781e356","src/method.rs":"bce543c148022170decd0cff9af3b37781323bcdf0dc35e23beec5f200dbc549","src/pat.rs":"0c3c0cb22054d09a2b7df277e4c05023c079d655d54b66a6bf732d56d58971e0","src/path.rs":"6f3f4e4c6f26f01674ca91635516448318f69b94061ce5694eaac15428336b51","src/qpath.rs":"b01bfe2b391754d00f32b7691ae7d65d0d91d78d69c4dfa9250e34d27b5315cf","src/self_.rs":"565780ba85ba851675331cd60dbe8a43f5eb87c318f6cc3b11bb7ba77a0d53fa","src/stmt.rs":"99e577b1417ff66c3057454ca27266a19329c6896b0f36259dcbdba0ff0005fb","src/struct_field.rs":"189fa910e236fea815d85c6b4535a76e6e7151a9d113a806bb60c6a192c7042b","src/symbol.rs":"ecab71523e9a819e063ce4231520bb7b46ba2ac8f2e2212f4f4e189d2988792e","src/ty.rs":"8d698e030192cb85207a3a4b7505af31b457360946e502673ade99dbfb30c32e","src/ty_param.rs":"a89a656a01db3d710dfbf3248b75683734eaf24c329ea241b3e54f39c8fc278f","src/variant.rs":"7fed49d694e029c81b4b70095e00704f1c67ef6357d122157d305f85dd95a512","src/variant_data.rs":"346198e982a2549ed4942ac7c6581f222f6284392afd9c0898acbfa53f58ffd3","src/where_predicate.rs":"e1645a51d5c396055629bdd351a38204f5cf81b9e2c142798ed098df99712298"},"package":"2c9b49e42a449c0b79d8acb91db37621de0978064dca7d3288ddcf030123e5b3"} \ No newline at end of file diff --git a/bash-5.1/vendor/aster/Cargo.toml b/bash-5.1/vendor/aster/Cargo.toml new file mode 100644 index 0000000..d486952 --- /dev/null +++ b/bash-5.1/vendor/aster/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "aster" +version = "0.38.0" +authors = ["Erick Tryzelaar "] +license = "MIT/Apache-2.0" +description = "A libsyntax ast builder" +repository = "https://github.com/serde-rs/aster" +include = ["Cargo.toml", "src/**/*.rs"] + +[features] +with-syntex = ["syntex_syntax"] +unstable-testing = ["clippy", "compiletest_rs"] + +[dependencies] +syntex_syntax = { version = "^0.54.0", optional = true } +clippy = { version = "0.*", optional = true } +compiletest_rs = { version = "^0.2.0", optional = true } + +[[test]] +name = "test" +path = "tests/test.rs" diff --git a/bash-5.1/vendor/aster/src/arm.rs b/bash-5.1/vendor/aster/src/arm.rs new file mode 100644 index 0000000..5bb6e2e --- /dev/null +++ b/bash-5.1/vendor/aster/src/arm.rs @@ -0,0 +1,241 @@ +#![cfg_attr(feature = "unstable", allow(should_implement_trait))] + +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use attr::AttrBuilder; +use expr::ExprBuilder; +use invoke::{Invoke, Identity}; +use pat::PatBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct ArmBuilder { + callback: F, + span: Span, + attrs: Vec, +} + +impl ArmBuilder { + pub fn new() -> Self { + ArmBuilder::with_callback(Identity) + } +} + +impl ArmBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + ArmBuilder { + callback: callback, + span: DUMMY_SP, + attrs: Vec::new(), + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn with_pats(self, iter: I) -> ArmPatBuilder + where I: IntoIterator>, + { + ArmPatBuilder { + callback: self.callback, + span: self.span, + attrs: self.attrs, + pats: iter.into_iter().collect(), + } + } + + pub fn with_pat(self, pat: P) -> ArmPatBuilder { + ArmPatBuilder { + callback: self.callback, + span: self.span, + attrs: self.attrs, + pats: vec![pat], + } + } + + pub fn pat(self) -> PatBuilder { + PatBuilder::with_callback(self) + } + + /* + pub fn with_guard(self, guard: Option>) -> ExprBuilder> { + ExprBuilder::with_callback(ArmBodyBuilder { + builder: self, + guard: guard, + }) + } + + pub fn guard(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn body(self) -> ExprBuilder> { + self.with_guard(None) + } + + pub fn build_arm_(self, + guard: Option>, + body: P) -> F::Result { + self.callback.invoke(ast::Arm { + attrs: self.attrs, + pats: self.pats, + guard: guard, + body: body, + }) + } + */ +} + +impl Invoke for ArmBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +impl Invoke> for ArmBuilder + where F: Invoke, +{ + type Result = ArmPatBuilder; + + fn invoke(self, pat: P) -> ArmPatBuilder { + self.with_pat(pat) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ArmPatBuilder { + callback: F, + span: Span, + attrs: Vec, + pats: Vec>, +} + +impl ArmPatBuilder + where F: Invoke, +{ + pub fn with_pats(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.pats.extend(iter); + self + } + + pub fn with_pat(mut self, pat: P) -> Self { + self.pats.push(pat); + self + } + + pub fn pat(self) -> PatBuilder { + let span = self.span; + PatBuilder::with_callback(self).span(span) + } + + pub fn with_guard(self, guard: Option>) -> ArmBodyBuilder { + ArmBodyBuilder { + builder: self, + guard: guard, + } + } + + pub fn guard(self) -> ExprBuilder { + let span = self.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn body(self) -> ExprBuilder> { + ArmBodyBuilder { + builder: self, + guard: None, + }.body() + } + + pub fn build_arm_(self, + guard: Option>, + body: P) -> F::Result { + self.callback.invoke(ast::Arm { + attrs: self.attrs, + pats: self.pats, + guard: guard, + body: body, + }) + } +} + +impl Invoke> for ArmPatBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, pat: P) -> Self { + self.with_pat(pat) + } +} + +impl Invoke> for ArmPatBuilder + where F: Invoke, +{ + type Result = ArmBodyBuilder; + + fn invoke(self, guard: P) -> ArmBodyBuilder { + self.with_guard(Some(guard)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ArmBodyBuilder { + builder: ArmPatBuilder, + guard: Option>, +} + +impl ArmBodyBuilder + where F: Invoke, +{ + pub fn body(self) -> ExprBuilder> { + let span = self.builder.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build(self, body: P) -> F::Result { + self.builder.build_arm_(self.guard, body) + } +} + +impl Invoke> for ArmBodyBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, body: P) -> F::Result { + self.build(body) + } +} diff --git a/bash-5.1/vendor/aster/src/attr.rs b/bash-5.1/vendor/aster/src/attr.rs new file mode 100644 index 0000000..9c2b621 --- /dev/null +++ b/bash-5.1/vendor/aster/src/attr.rs @@ -0,0 +1,349 @@ +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::attr; +use syntax::codemap::{DUMMY_SP, Span, respan}; +use syntax::ptr::P; +use syntax::symbol::Symbol; + +use invoke::{Invoke, Identity}; +use lit::LitBuilder; +use symbol::ToSymbol; + +////////////////////////////////////////////////////////////////////////////// + +pub struct AttrBuilder { + callback: F, + span: Span, + style: ast::AttrStyle, + is_sugared_doc: bool, +} + +impl AttrBuilder { + pub fn new() -> Self { + AttrBuilder::with_callback(Identity) + } +} + +impl AttrBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + AttrBuilder { + callback: callback, + span: DUMMY_SP, + style: ast::AttrStyle::Outer, + is_sugared_doc: false, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn inner(mut self) -> Self { + self.style = ast::AttrStyle::Inner; + self + } + + pub fn outer(mut self) -> Self { + self.style = ast::AttrStyle::Outer; + self + } + + pub fn build_meta_item(self, item: ast::MetaItem) -> F::Result { + let attr = ast::Attribute { + id: attr::mk_attr_id(), + style: self.style, + value: item, + is_sugared_doc: self.is_sugared_doc, + span: self.span, + }; + self.callback.invoke(attr) + } + + pub fn named(self, name: N) -> NamedAttrBuilder + where N: ToSymbol + { + NamedAttrBuilder::with_callback(name, self) + } + + pub fn word(self, word: T) -> F::Result + where T: ToSymbol + { + let item = ast::MetaItem { + name: word.to_symbol(), + node: ast::MetaItemKind::Word, + span: self.span, + }; + self.build_meta_item(item) + } + + pub fn list(self, word: T) -> AttrListBuilder + where T: ToSymbol + { + AttrListBuilder::with_callback(word, self) + } + + pub fn name_value(self, name: T) -> LitBuilder> + where T: ToSymbol, + { + LitBuilder::with_callback(AttrNameValueBuilder::with_callback(name, self)) + } + + pub fn automatically_derived(self) -> F::Result { + self.word("automatically_derived") + } + + pub fn inline(self) -> F::Result { + self.word("inline") + } + + pub fn test(self) -> F::Result { + self.word("test") + } + + pub fn allow(self, iter: I) -> F::Result + where I: IntoIterator, + T: ToSymbol, + { + self.list("allow").words(iter).build() + } + + pub fn warn(self, iter: I) -> F::Result + where I: IntoIterator, + T: ToSymbol, + { + self.list("warn").words(iter).build() + } + + pub fn deny(self, iter: I) -> F::Result + where I: IntoIterator, + T: ToSymbol, + { + self.list("deny").words(iter).build() + } + + pub fn features(self, iter: I) -> F::Result + where I: IntoIterator, + T: ToSymbol, + { + self.list("feature").words(iter).build() + } + + pub fn plugins(self, iter: I) -> F::Result + where I: IntoIterator, + T: ToSymbol, + { + self.list("plugin").words(iter).build() + } + + /** + * Create a #[doc = "..."] node. Note that callers of this must make sure to prefix their + * comments with either "///" or "/\*\*" if an outer comment, or "//!" or "/\*!" if an inner + * comment. + */ + pub fn doc(mut self, doc: T) -> F::Result + where T: ToSymbol, + { + self.is_sugared_doc = true; + self.name_value("doc").str(doc) + } +} + +impl Invoke for AttrBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, item: ast::MetaItem) -> F::Result { + self.build_meta_item(item) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct NamedAttrBuilder { + callback: F, + span: Span, + name: Symbol, +} + +impl NamedAttrBuilder + where F: Invoke +{ + pub fn with_callback(name: T, callback: F) -> Self + where T: ToSymbol + { + NamedAttrBuilder { + callback: callback, + span: DUMMY_SP, + name: name.to_symbol(), + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn word(self) -> F::Result { + let item = ast::MetaItem { + name: self.name, + node: ast::MetaItemKind::Word, + span: self.span, + }; + self.callback.invoke(item) + } + + pub fn list(self) -> AttrListBuilder { + AttrListBuilder::with_callback(self.name, self.callback).span(self.span) + } + + pub fn name_value(self) -> LitBuilder> { + LitBuilder::with_callback(AttrNameValueBuilder::with_callback(self.name, self.callback)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct AttrListBuilder { + callback: F, + span: Span, + name: Symbol, + items: Vec, +} + +impl AttrListBuilder + where F: Invoke, +{ + pub fn with_callback(name: T, callback: F) -> Self + where T: ToSymbol, + { + AttrListBuilder { + callback: callback, + span: DUMMY_SP, + name: name.to_symbol(), + items: vec![], + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_meta_items(mut self, iter: I) -> Self + where I: IntoIterator, + { + let span = self.span; + self.items.extend(iter.into_iter().map(|meta_item| { + respan(span, ast::NestedMetaItemKind::MetaItem(meta_item)) + })); + self + } + + pub fn with_meta_item(mut self, item: ast::MetaItem) -> Self { + self.items.push(respan(self.span, ast::NestedMetaItemKind::MetaItem(item))); + self + } + + pub fn words(self, iter: I) -> Self + where I: IntoIterator, + T: ToSymbol, + { + let iter = iter.into_iter(); + let span = self.span; + self.with_meta_items(iter.map(|item| ast::MetaItem { + name: item.to_symbol(), + node: ast::MetaItemKind::Word, + span: span, + })) + } + + pub fn word(self, word: T) -> Self + where T: ToSymbol, + { + let span = self.span; + self.with_meta_item(ast::MetaItem { + name: word.to_symbol(), + node: ast::MetaItemKind::Word, + span: span, + }) + } + + pub fn list(self, name: T) -> AttrListBuilder + where T: ToSymbol, + { + AttrListBuilder::with_callback(name, self) + } + + pub fn name_value(self, name: T) -> LitBuilder> + where T: ToSymbol, + { + let span = self.span; + LitBuilder::with_callback(AttrNameValueBuilder { + callback: self, + name: name.to_symbol(), + span: span, + }) + } + + pub fn build(self) -> F::Result { + let item = ast::MetaItem { + name: self.name, + node: ast::MetaItemKind::List(self.items), + span: self.span, + }; + self.callback.invoke(item) + } +} + +impl Invoke for AttrListBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, item: ast::MetaItem) -> Self { + self.with_meta_item(item) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct AttrNameValueBuilder { + callback: F, + span: Span, + name: Symbol, +} + +impl AttrNameValueBuilder { + pub fn with_callback(name: T, callback: F) -> Self + where T: ToSymbol + { + AttrNameValueBuilder { + callback: callback, + span: DUMMY_SP, + name: name.to_symbol(), + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } +} + +impl> Invoke> for AttrNameValueBuilder { + type Result = F::Result; + + fn invoke(self, value: P) -> F::Result { + let item = ast::MetaItem { + name: self.name, + node: ast::MetaItemKind::NameValue((*value).clone()), + span: self.span, + }; + self.callback.invoke(item) + } +} diff --git a/bash-5.1/vendor/aster/src/block.rs b/bash-5.1/vendor/aster/src/block.rs new file mode 100644 index 0000000..744b73f --- /dev/null +++ b/bash-5.1/vendor/aster/src/block.rs @@ -0,0 +1,110 @@ +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use expr::ExprBuilder; +use invoke::{Invoke, Identity}; +use stmt::StmtBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct BlockBuilder { + callback: F, + span: Span, + stmts: Vec, + block_check_mode: ast::BlockCheckMode, +} + +impl BlockBuilder { + pub fn new() -> Self { + BlockBuilder::with_callback(Identity) + } +} + +impl BlockBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + BlockBuilder { + callback: callback, + span: DUMMY_SP, + stmts: Vec::new(), + block_check_mode: ast::BlockCheckMode::Default, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn unsafe_(mut self) -> Self { + let source = ast::UnsafeSource::CompilerGenerated; + self.block_check_mode = ast::BlockCheckMode::Unsafe(source); + self + } + + pub fn with_stmts(mut self, iter: I) -> Self + where I: IntoIterator + { + self.stmts.extend(iter); + self + } + + pub fn with_stmt(mut self, stmt: ast::Stmt) -> Self { + self.stmts.push(stmt); + self + } + + pub fn stmt(self) -> StmtBuilder { + let span = self.span; + StmtBuilder::with_callback(self).span(span) + } + + pub fn build_expr(self, expr: P) -> F::Result { + self.build_(Some(expr)) + } + + pub fn expr(self) -> ExprBuilder { + let span = self.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.build_(None) + } + + fn build_(mut self, expr: Option>) -> F::Result { + self.stmts.extend(expr.map(|expr| { + StmtBuilder::new().span(expr.span).build_expr(expr) + })); + self.callback.invoke(P(ast::Block { + stmts: self.stmts, + id: ast::DUMMY_NODE_ID, + rules: self.block_check_mode, + span: self.span, + })) + } +} + +impl Invoke for BlockBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, stmt: ast::Stmt) -> Self { + self.with_stmt(stmt) + } +} + +impl Invoke> for BlockBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.build_expr(expr) + } +} diff --git a/bash-5.1/vendor/aster/src/constant.rs b/bash-5.1/vendor/aster/src/constant.rs new file mode 100644 index 0000000..9491bf1 --- /dev/null +++ b/bash-5.1/vendor/aster/src/constant.rs @@ -0,0 +1,88 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use expr::ExprBuilder; +use invoke::{Invoke, Identity}; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct Const { + pub ty: P, + pub expr: Option>, +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ConstBuilder { + callback: F, + span: Span, + expr: Option>, +} + +impl ConstBuilder { + pub fn new() -> Self { + ConstBuilder::with_callback(Identity) + } +} + +impl ConstBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self + where F: Invoke, + { + ConstBuilder { + callback: callback, + span: DUMMY_SP, + expr: None, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_expr(mut self, expr: P) -> Self { + self.expr = Some(expr); + self + } + + pub fn expr(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build(self, ty: P) -> F::Result { + self.callback.invoke(Const { + ty: ty, + expr: self.expr, + }) + } +} + +impl Invoke> for ConstBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, expr: P) -> Self { + self.with_expr(expr) + } +} + +impl Invoke> for ConstBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build(ty) + } +} diff --git a/bash-5.1/vendor/aster/src/ctx.rs b/bash-5.1/vendor/aster/src/ctx.rs new file mode 100644 index 0000000..4918780 --- /dev/null +++ b/bash-5.1/vendor/aster/src/ctx.rs @@ -0,0 +1,17 @@ +use syntax::ast; +use syntax::parse::token; + +////////////////////////////////////////////////////////////////////////////// + +#[derive(Copy)] +pub struct Ctx; + +impl Ctx { + pub fn new() -> Ctx { + Ctx + } + + pub fn intern(&self, name: &str) -> ast::Name { + token::intern(name) + } +} diff --git a/bash-5.1/vendor/aster/src/expr.rs b/bash-5.1/vendor/aster/src/expr.rs new file mode 100644 index 0000000..4944954 --- /dev/null +++ b/bash-5.1/vendor/aster/src/expr.rs @@ -0,0 +1,2181 @@ +#![cfg_attr(feature = "clippy", allow(should_implement_trait))] + +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span, Spanned, respan}; +use syntax::ptr::P; + +use arm::ArmBuilder; +use attr::AttrBuilder; +use block::BlockBuilder; +use fn_decl::FnDeclBuilder; +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use lit::LitBuilder; +use mac::MacBuilder; +use pat::PatBuilder; +use path::{IntoPath, PathBuilder}; +use qpath::QPathBuilder; +use symbol::ToSymbol; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprBuilder { + callback: F, + span: Span, + attrs: Vec, +} + +impl ExprBuilder { + pub fn new() -> Self { + ExprBuilder::with_callback(Identity) + } +} + +macro_rules! signed_int_method { + ($ty:ident, $unsigned:ident) => { + pub fn $ty(self, val: $ty) -> F::Result { + if val == ::std::$ty::MIN { + self.neg().lit().$ty(val as $unsigned) + } else if val < 0 { + self.neg().lit().$ty(-val as $unsigned) + } else { + self.lit().$ty(val as $unsigned) + } + } + }; +} + +impl ExprBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + ExprBuilder { + callback: callback, + span: DUMMY_SP, + attrs: vec![], + } + } + + pub fn build(self, expr: P) -> F::Result { + self.callback.invoke(expr) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn build_expr_kind(self, expr: ast::ExprKind) -> F::Result { + let expr = P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: expr, + span: self.span, + attrs: self.attrs.clone().into(), + }); + self.build(expr) + } + + pub fn build_path(self, path: ast::Path) -> F::Result { + self.build_expr_kind(ast::ExprKind::Path(None, path)) + } + + pub fn build_qpath(self, qself: ast::QSelf, path: ast::Path) -> F::Result { + self.build_expr_kind(ast::ExprKind::Path(Some(qself), path)) + } + + pub fn path(self) -> PathBuilder { + let span = self.span; + PathBuilder::with_callback(self).span(span) + } + + pub fn qpath(self) -> QPathBuilder { + let span = self.span; + QPathBuilder::with_callback(self).span(span) + } + + pub fn id(self, id: I) -> F::Result + where I: ToIdent + { + self.path().id(id).build() + } + + pub fn build_lit(self, lit: P) -> F::Result { + self.build_expr_kind(ast::ExprKind::Lit(lit)) + } + + pub fn lit(self) -> LitBuilder { + LitBuilder::with_callback(self) + } + + pub fn bool(self, value: bool) -> F::Result { + self.lit().bool(value) + } + + pub fn true_(self) -> F::Result { + self.bool(true) + } + + pub fn false_(self) -> F::Result { + self.bool(false) + } + + pub fn int(self, value: i64) -> F::Result { + if value == ::std::i64::MIN { + self.neg().lit().int(value as u64) + } else if value < 0 { + self.neg().lit().int(-value as u64) + } else { + self.lit().int(value as u64) + } + } + + pub fn uint(self, value: u64) -> F::Result { + self.lit().uint(value as u64) + } + + signed_int_method!(i8, u8); + signed_int_method!(i16, u16); + signed_int_method!(i32, u32); + signed_int_method!(i64, u64); + signed_int_method!(isize, usize); + + pub fn usize(self, value: usize) -> F::Result { + self.lit().usize(value) + } + + pub fn u8(self, value: u8) -> F::Result { + self.lit().u8(value) + } + + pub fn u16(self, value: u16) -> F::Result { + self.lit().u16(value) + } + + pub fn u32(self, value: u32) -> F::Result { + self.lit().u32(value) + } + + pub fn u64(self, value: u64) -> F::Result { + self.lit().u64(value) + } + + pub fn f32(self, value: S) -> F::Result + where S: ToSymbol, + { + self.lit().f32(value) + } + + pub fn f64(self, value: S) -> F::Result + where S: ToSymbol, + { + self.lit().f64(value) + } + + pub fn str(self, value: S) -> F::Result + where S: ToSymbol, + { + self.lit().str(value) + } + + pub fn build_unary(self, unop: ast::UnOp, expr: P) -> F::Result { + self.build_expr_kind(ast::ExprKind::Unary(unop, expr)) + } + + pub fn build_deref(self, expr: P) -> F::Result { + self.build_unary(ast::UnOp::Deref, expr) + } + + pub fn build_not(self, expr: P) -> F::Result { + self.build_unary(ast::UnOp::Not, expr) + } + + pub fn build_neg(self, expr: P) -> F::Result { + self.build_unary(ast::UnOp::Neg, expr) + } + + pub fn unary(self, unop: ast::UnOp) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(ExprUnaryBuilder { + builder: self, + unop: unop, + }).span(span) + } + + pub fn deref(self) -> ExprBuilder> { + self.unary(ast::UnOp::Deref) + } + + pub fn not(self) -> ExprBuilder> { + self.unary(ast::UnOp::Not) + } + + pub fn neg(self) -> ExprBuilder> { + self.unary(ast::UnOp::Neg) + } + + pub fn build_binary(self, + binop: ast::BinOpKind, + lhs: P, + rhs: P) -> F::Result { + let binop = respan(self.span, binop); + self.build_expr_kind(ast::ExprKind::Binary(binop, lhs, rhs)) + } + + pub fn build_add(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Add, lhs, rhs) + } + + pub fn build_sub(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Sub, lhs, rhs) + } + + pub fn build_mul(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Mul, lhs, rhs) + } + + pub fn build_div(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Div, lhs, rhs) + } + + pub fn build_rem(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Rem, lhs, rhs) + } + + pub fn build_and(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::And, lhs, rhs) + } + + pub fn build_or(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Or, lhs, rhs) + } + + pub fn build_bit_xor(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::BitXor, lhs, rhs) + } + + pub fn build_bit_and(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::BitAnd, lhs, rhs) + } + + pub fn build_bit_or(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::BitOr, lhs, rhs) + } + + pub fn build_shl(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Shl, lhs, rhs) + } + + pub fn build_shr(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Shr, lhs, rhs) + } + + pub fn build_eq(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Eq, lhs, rhs) + } + + pub fn build_lt(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Lt, lhs, rhs) + } + + pub fn build_le(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Le, lhs, rhs) + } + + pub fn build_ne(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Ne, lhs, rhs) + } + + pub fn build_ge(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Ge, lhs, rhs) + } + + pub fn build_gt(self, lhs: P, rhs: P) -> F::Result { + self.build_binary(ast::BinOpKind::Gt, lhs, rhs) + } + + pub fn binary(self, binop: ast::BinOpKind) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(ExprBinaryLhsBuilder { + builder: self, + binop: binop, + }).span(span) + } + + pub fn add(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Add) + } + + pub fn sub(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Sub) + } + + pub fn mul(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Mul) + } + + pub fn div(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Div) + } + + pub fn rem(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Rem) + } + + pub fn and(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::And) + } + + pub fn or(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Or) + } + + pub fn bit_xor(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::BitXor) + } + + pub fn bit_and(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::BitAnd) + } + + pub fn bit_or(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::BitOr) + } + + pub fn shl(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Shl) + } + + pub fn shr(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Shr) + } + + pub fn eq(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Eq) + } + + pub fn lt(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Lt) + } + + pub fn le(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Le) + } + + pub fn ne(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Ne) + } + + pub fn ge(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Ge) + } + + pub fn gt(self) -> ExprBuilder> { + self.binary(ast::BinOpKind::Gt) + } + + pub fn ref_(self) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(ExprRefBuilder { + builder: self, + mutability: ast::Mutability::Immutable, + }).span(span) + } + + pub fn mut_ref(self) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(ExprRefBuilder { + builder: self, + mutability: ast::Mutability::Mutable, + }).span(span) + } + + pub fn break_(self) -> F::Result { + self.build_expr_kind(ast::ExprKind::Break(None, None)) + } + + pub fn break_to(self, label: I) -> F::Result + where I: ToIdent, + { + let label = respan(self.span, label.to_ident()); + self.build_expr_kind(ast::ExprKind::Break(Some(label), None)) + } + + pub fn continue_(self) -> F::Result { + self.build_expr_kind(ast::ExprKind::Continue(None)) + } + + pub fn continue_to(self, label: I) -> F::Result + where I: ToIdent, + { + let label = respan(self.span, label.to_ident()); + self.build_expr_kind(ast::ExprKind::Continue(Some(label))) + } + + pub fn return_(self) -> F::Result { + self.build_expr_kind(ast::ExprKind::Ret(None)) + } + + pub fn return_expr(self) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(ExprReturnBuilder { + builder: self, + }).span(span) + } + + pub fn unit(self) -> F::Result { + self.tuple().build() + } + + pub fn tuple(self) -> ExprTupleBuilder { + ExprTupleBuilder { + builder: self, + exprs: Vec::new(), + } + } + + pub fn struct_path

(self, path: P) -> ExprStructPathBuilder + where P: IntoPath, + { + let span = self.span; + let path = path.into_path(); + ExprStructPathBuilder { + builder: self, + span: span, + path: path, + fields: vec![], + } + } + + pub fn struct_id(self, id: T) -> ExprStructPathBuilder + where T: ToIdent, + { + self.struct_().id(id).build() + } + + pub fn struct_(self) -> PathBuilder> { + PathBuilder::with_callback(ExprStructBuilder { + builder: self, + }) + } + + pub fn self_(self) -> F::Result { + self.id("self") + } + + pub fn none(self) -> F::Result { + self.path() + .global() + .id("std").id("option").id("Option").id("None") + .build() + } + + pub fn some(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std").id("option").id("Option").id("Some") + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn ok(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std").id("result").id("Result").id("Ok") + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn err(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std").id("result").id("Result").id("Err") + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + /// Implement a call for `::std::convert::From::from(value)` + pub fn from(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .ids(&["std", "convert", "From", "from"]) + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn phantom_data(self) -> F::Result { + self.path() + .global() + .ids(&["std", "marker", "PhantomData"]) + .build() + } + + pub fn call(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprCallBuilder { + builder: self, + }).span(span) + } + + pub fn method_call(self, id: I) -> ExprBuilder> + where I: ToIdent, + { + let id = respan(self.span, id.to_ident()); + let span = self.span; + + ExprBuilder::with_callback(ExprMethodCallBuilder { + builder: self, + id: id, + }).span(span) + } + + pub fn build_block(self, block: P) -> F::Result { + self.build_expr_kind(ast::ExprKind::Block(block)) + } + + pub fn block(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } + + pub fn build_assign(self, lhs: P, rhs: P) -> F::Result { + self.build_expr_kind(ast::ExprKind::Assign(lhs, rhs)) + } + + pub fn assign(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprAssignBuilder { + builder: self, + }).span(span) + } + + pub fn build_assign_op(self, + binop: ast::BinOpKind, + lhs: P, + rhs: P) -> F::Result { + let binop = respan(self.span, binop); + self.build_expr_kind(ast::ExprKind::AssignOp(binop, lhs, rhs)) + } + + pub fn assign_op(self, binop: ast::BinOpKind) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprAssignOpBuilder { + builder: self, + binop: binop, + }).span(span) + } + + pub fn add_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Add) + } + + pub fn sub_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Sub) + } + + pub fn mul_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Mul) + } + + pub fn rem_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Rem) + } + + pub fn and_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::And) + } + + pub fn or_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Or) + } + + pub fn bit_xor_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::BitXor) + } + + pub fn bit_and_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::BitAnd) + } + + pub fn bit_or_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::BitOr) + } + + pub fn bit_shl_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Shl) + } + + pub fn bit_shr_assign(self) -> ExprBuilder> { + self.assign_op(ast::BinOpKind::Shr) + } + + pub fn build_index(self, lhs: P, rhs: P) -> F::Result { + self.build_expr_kind(ast::ExprKind::Index(lhs, rhs)) + } + + pub fn index(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprIndexBuilder { + builder: self, + }).span(span) + } + + pub fn range(self) -> ExprRangeBuilder { + ExprRangeBuilder { + builder: self, + } + } + + pub fn build_repeat(self, lhs: P, rhs: P) -> F::Result { + self.build_expr_kind(ast::ExprKind::Repeat(lhs, rhs)) + } + + pub fn repeat(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprRepeatBuilder { + builder: self, + }).span(span) + } + + pub fn loop_(self) -> ExprLoopBuilder { + let span = self.span; + + ExprLoopBuilder { + builder: self, + span: span, + label: None, + } + } + + pub fn if_(self) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(ExprIfBuilder { + builder: self, + }).span(span) + } + + pub fn match_(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprMatchBuilder { + builder: self, + }).span(span) + } + + pub fn paren(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprParenBuilder { + builder: self, + }).span(span) + } + + pub fn field(self, id: I) -> ExprBuilder> + where I: ToIdent, + { + let id = respan(self.span, id.to_ident()); + let span = self.span; + + ExprBuilder::with_callback(ExprFieldBuilder { + builder: self, + id: id, + }).span(span) + } + + pub fn tup_field(self, index: usize) -> ExprBuilder> { + let index = respan(self.span, index); + let span = self.span; + + ExprBuilder::with_callback(ExprTupFieldBuilder { + builder: self, + index: index, + }).span(span) + } + + pub fn box_(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std").id("boxed").id("Box").id("new") + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn rc(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std").id("rc").id("Rc").id("new") + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn arc(self) -> ExprBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std").id("arc").id("Arc").id("new") + .build(); + let span = self.span; + + ExprBuilder::with_callback(ExprPathBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn default(self) -> F::Result { + let path = PathBuilder::new() + .span(self.span) + .global() + .ids(&["std", "default", "Default", "default"]) + .build(); + + self.call() + .build_path(path) + .build() + } + + pub fn slice(self) -> ExprSliceBuilder { + ExprSliceBuilder { + builder: self, + exprs: Vec::new(), + } + } + + pub fn vec(self) -> ExprSliceBuilder> { + ExprBuilder::with_callback(ExprVecBuilder { + builder: self, + }).slice() + } + + /// Represents an equivalent to `try!(...)`. Generates: + /// + /// match $expr { + /// ::std::result::Result::Ok(expr) => expr, + /// ::std::result::Result::Err(err) => { + /// return ::std::result::Result::Err(::std::convert::From::from(err)) + /// } + /// } + pub fn try(self) -> ExprBuilder> { + let span = self.span; + + ExprBuilder::with_callback(ExprTryBuilder { + builder: self, + }).span(span) + } + + pub fn closure(self) -> ExprClosureBuilder { + ExprClosureBuilder { + span: self.span, + builder: self, + capture_by: ast::CaptureBy::Ref, + } + } + + pub fn while_(self) -> ExprBuilder> { + ExprBuilder::with_callback(ExprWhileBuilder { + builder: self, + }) + } + + pub fn type_(self) -> ExprBuilder> { + ExprBuilder::with_callback(ExprTypeBuilder { + builder: self, + }) + } + + pub fn build_mac(self, mac: ast::Mac) -> F::Result { + self.build_expr_kind(ast::ExprKind::Mac(mac)) + } + + pub fn mac(self) -> MacBuilder { + let span = self.span; + MacBuilder::with_callback(self).span(span) + } +} + +impl Invoke for ExprBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +impl Invoke> for ExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, lit: P) -> F::Result { + self.build_lit(lit) + } +} + +impl Invoke for ExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, path: ast::Path) -> F::Result { + self.build_path(path) + } +} + +impl Invoke<(ast::QSelf, ast::Path)> for ExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, (qself, path): (ast::QSelf, ast::Path)) -> F::Result { + self.build_qpath(qself, path) + } +} + +impl Invoke> for ExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> F::Result { + self.build_block(block) + } +} + +impl Invoke for ExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, mac: ast::Mac) -> F::Result { + self.build_mac(mac) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprUnaryBuilder { + builder: ExprBuilder, + unop: ast::UnOp, +} + +impl Invoke> for ExprUnaryBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.build_unary(self.unop, expr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprBinaryLhsBuilder { + builder: ExprBuilder, + binop: ast::BinOpKind, +} + +impl Invoke> for ExprBinaryLhsBuilder + where F: Invoke>, +{ + type Result = ExprBuilder>; + + fn invoke(self, lhs: P) -> ExprBuilder> { + ExprBuilder::with_callback(ExprBinaryRhsBuilder { + builder: self.builder, + binop: self.binop, + lhs: lhs, + }) + } +} + +pub struct ExprBinaryRhsBuilder { + builder: ExprBuilder, + binop: ast::BinOpKind, + lhs: P, +} + +impl Invoke> for ExprBinaryRhsBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, rhs: P) -> F::Result { + self.builder.build_binary(self.binop, self.lhs, rhs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprReturnBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprReturnBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Ret(Some(expr))) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprTupleBuilder { + builder: ExprBuilder, + exprs: Vec>, +} + +impl>> ExprTupleBuilder + where F: Invoke> +{ + pub fn with_exprs(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.exprs.extend(iter); + self + } + + pub fn expr(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn build(self) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Tup(self.exprs)) + } +} + +impl Invoke> for ExprTupleBuilder + where F: Invoke> +{ + type Result = ExprTupleBuilder; + + fn invoke(mut self, expr: P) -> Self { + self.exprs.push(expr); + self + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprStructBuilder { + builder: ExprBuilder, +} + +impl Invoke for ExprStructBuilder + where F: Invoke> +{ + type Result = ExprStructPathBuilder; + + fn invoke(self, path: ast::Path) -> ExprStructPathBuilder { + self.builder.struct_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprStructPathBuilder { + builder: ExprBuilder, + span: Span, + path: ast::Path, + fields: Vec, +} + +impl ExprStructPathBuilder + where F: Invoke> +{ + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_fields(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.fields.extend(iter); + self + } + + pub fn with_id_exprs(mut self, iter: I) -> Self + where I: IntoIterator)>, + { + for (id, expr) in iter { + self = self.field(id).build(expr); + } + + self + } + + pub fn field(self, id: I) -> ExprBuilder> + where I: ToIdent, + { + let span = self.span; + + ExprBuilder::with_callback(ExprStructFieldBuilder { + builder: self, + id: id, + }).span(span) + } + + pub fn build_with(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn build(self) -> F::Result { + let expr_kind = ast::ExprKind::Struct(self.path, self.fields, None); + self.builder.build_expr_kind(expr_kind) + } +} + +impl Invoke> for ExprStructPathBuilder + where F: Invoke> +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + let expr_kind = ast::ExprKind::Struct(self.path, self.fields, Some(expr)); + self.builder.build_expr_kind(expr_kind) + } +} + +pub struct ExprStructFieldBuilder { + builder: ExprStructPathBuilder, + id: I, +} + +impl Invoke> for ExprStructFieldBuilder + where I: ToIdent, + F: Invoke>, +{ + type Result = ExprStructPathBuilder; + + fn invoke(mut self, expr: P) -> ExprStructPathBuilder { + let field = ast::Field { + ident: respan(self.builder.span, self.id.to_ident()), + expr: expr, + span: self.builder.span, + is_shorthand: false, + }; + self.builder.fields.push(field); + self.builder + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprCallBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprCallBuilder + where F: Invoke>, +{ + type Result = ExprCallArgsBuilder; + + fn invoke(self, expr: P) -> ExprCallArgsBuilder { + ExprCallArgsBuilder { + builder: self.builder, + fn_: expr, + args: vec![], + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprCallArgsBuilder { + builder: ExprBuilder, + fn_: P, + args: Vec>, +} + +impl ExprCallArgsBuilder + where F: Invoke>, +{ + pub fn with_args(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.args.extend(iter); + self + } + + pub fn with_arg(mut self, arg: P) -> Self { + self.args.push(arg); + self + } + + pub fn arg(self) -> ExprBuilder { + let span = self.builder.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Call(self.fn_, self.args)) + } +} + +impl Invoke> for ExprCallArgsBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, arg: P) -> Self { + self.with_arg(arg) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprMethodCallBuilder { + builder: ExprBuilder, + id: ast::SpannedIdent, +} + +impl Invoke> for ExprMethodCallBuilder + where F: Invoke>, +{ + type Result = ExprMethodCallArgsBuilder; + + fn invoke(self, expr: P) -> ExprMethodCallArgsBuilder { + ExprMethodCallArgsBuilder { + builder: self.builder, + id: self.id, + tys: vec![], + args: vec![expr], + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprMethodCallArgsBuilder { + builder: ExprBuilder, + id: ast::SpannedIdent, + tys: Vec>, + args: Vec>, +} + +impl ExprMethodCallArgsBuilder + where F: Invoke>, +{ + pub fn with_tys(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.tys.extend(iter); + self + } + + pub fn with_ty(mut self, ty: P) -> Self { + self.tys.push(ty); + self + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn with_args(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.args.extend(iter); + self + } + + pub fn with_arg(mut self, arg: P) -> Self { + self.args.push(arg); + self + } + + pub fn arg(self) -> ExprBuilder { + let span = self.builder.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::MethodCall(self.id, self.tys, self.args)) + } +} + +impl Invoke> for ExprMethodCallArgsBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, ty: P) -> Self { + self.with_ty(ty) + } +} + +impl Invoke> for ExprMethodCallArgsBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, arg: P) -> Self { + self.with_arg(arg) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprRefBuilder { + builder: ExprBuilder, + mutability: ast::Mutability, +} + +impl Invoke> for ExprRefBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::AddrOf(self.mutability, expr)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprPathBuilder { + builder: ExprBuilder, + path: ast::Path, +} + +impl Invoke> for ExprPathBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, arg: P) -> F::Result { + self.builder.call() + .build_path(self.path) + .with_arg(arg) + .build() + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprAssignBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprAssignBuilder + where F: Invoke>, +{ + type Result = ExprBuilder>; + + fn invoke(self, lhs: P) -> ExprBuilder> { + let span = self.builder.span; + ExprBuilder::with_callback(ExprAssignLhsBuilder { + builder: self.builder, + lhs: lhs, + }).span(span) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprAssignLhsBuilder { + builder: ExprBuilder, + lhs: P, +} + +impl Invoke> for ExprAssignLhsBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, rhs: P) -> F::Result { + self.builder.build_assign(self.lhs, rhs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprAssignOpBuilder { + builder: ExprBuilder, + binop: ast::BinOpKind, +} + +impl Invoke> for ExprAssignOpBuilder + where F: Invoke>, +{ + type Result = ExprBuilder>; + + fn invoke(self, lhs: P) -> ExprBuilder> { + let span = self.builder.span; + ExprBuilder::with_callback(ExprAssignOpLhsBuilder { + builder: self.builder, + binop: self.binop, + lhs: lhs, + }).span(span) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprAssignOpLhsBuilder { + builder: ExprBuilder, + binop: ast::BinOpKind, + lhs: P, +} + +impl Invoke> for ExprAssignOpLhsBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, rhs: P) -> F::Result { + self.builder.build_assign_op(self.binop, self.lhs, rhs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprIndexBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprIndexBuilder + where F: Invoke>, +{ + type Result = ExprBuilder>; + + fn invoke(self, lhs: P) -> ExprBuilder> { + let span = self.builder.span; + ExprBuilder::with_callback(ExprIndexLhsBuilder { + builder: self.builder, + lhs: lhs, + }).span(span) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprIndexLhsBuilder { + builder: ExprBuilder, + lhs: P, +} + +impl Invoke> for ExprIndexLhsBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, rhs: P) -> F::Result { + self.builder.build_index(self.lhs, rhs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprRangeBuilder { + builder: ExprBuilder, +} + +impl ExprRangeBuilder + where F: Invoke>, +{ + pub fn from(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn to(self) -> ExprBuilder> { + self.from_opt(None).to() + } + + pub fn to_inclusive(self) -> ExprBuilder> { + self.from_opt(None).to_inclusive() + } + + pub fn from_opt(self, from: Option>) -> ExprRangeFromBuilder { + ExprRangeFromBuilder { + builder: self.builder, + from: from, + } + } + + pub fn build(self) -> F::Result { + self.from_opt(None).build() + } +} + +impl Invoke> for ExprRangeBuilder + where F: Invoke>, +{ + type Result = ExprRangeFromBuilder; + + fn invoke(self, from: P) -> ExprRangeFromBuilder { + self.from_opt(Some(from)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprRangeFromBuilder { + builder: ExprBuilder, + from: Option>, +} + +impl ExprRangeFromBuilder + where F: Invoke>, +{ + pub fn to(self) -> ExprBuilder> { + ExprBuilder::with_callback(ExprRangeToBuilder { + builder: self, + limit: ast::RangeLimits::HalfOpen, + }) + } + + pub fn to_inclusive(self) -> ExprBuilder> { + ExprBuilder::with_callback(ExprRangeToBuilder { + builder: self, + limit: ast::RangeLimits::Closed, + }) + } + + pub fn build(self) -> F::Result { + self.to_opt(None, ast::RangeLimits::HalfOpen) + } + + pub fn to_opt(self, to: Option>, limit: ast::RangeLimits) -> F::Result { + let kind = ast::ExprKind::Range(self.from, to, limit); + self.builder.build_expr_kind(kind) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprRangeToBuilder { + builder: ExprRangeFromBuilder, + limit: ast::RangeLimits, +} + +impl Invoke> for ExprRangeToBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.to_opt(Some(expr), self.limit) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprRepeatBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprRepeatBuilder + where F: Invoke>, +{ + type Result = ExprBuilder>; + + fn invoke(self, lhs: P) -> ExprBuilder> { + let span = self.builder.span; + ExprBuilder::with_callback(ExprRepeatLhsBuilder { + builder: self.builder, + lhs: lhs, + }).span(span) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprRepeatLhsBuilder { + builder: ExprBuilder, + lhs: P, +} + +impl Invoke> for ExprRepeatLhsBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, rhs: P) -> F::Result { + self.builder.build_repeat(self.lhs, rhs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprLoopBuilder { + builder: ExprBuilder, + span: Span, + label: Option>, +} + +impl ExprLoopBuilder + where F: Invoke>, +{ + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn label(mut self, id: I) -> Self + where I: ToIdent, + { + self.label = Some(respan(self.span, id.to_ident())); + self + } + + pub fn block(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } +} + +impl Invoke> for ExprLoopBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Loop(block, self.label)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprIfBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprIfBuilder + where F: Invoke>, +{ + type Result = ExprIfThenBuilder; + + fn invoke(self, condition: P) -> ExprIfThenBuilder { + ExprIfThenBuilder { + builder: self.builder, + condition: condition, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprIfThenBuilder { + builder: ExprBuilder, + condition: P, +} + +impl ExprIfThenBuilder + where F: Invoke>, +{ + pub fn build_then(self, block: P) -> ExprIfThenElseBuilder { + ExprIfThenElseBuilder { + builder: self.builder, + condition: self.condition, + then: block, + else_ifs: Vec::new(), + } + } + + pub fn then(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } +} + +impl Invoke> for ExprIfThenBuilder + where F: Invoke>, +{ + type Result = ExprIfThenElseBuilder; + + fn invoke(self, block: P) -> ExprIfThenElseBuilder { + self.build_then(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprIfThenElseBuilder { + builder: ExprBuilder, + condition: P, + then: P, + else_ifs: Vec<(P, P)>, +} + +impl ExprIfThenElseBuilder + where F: Invoke>, +{ + pub fn else_if(self) -> ExprBuilder> { + let span = self.builder.span; + ExprBuilder::with_callback(ExprElseIfBuilder { + builder: self, + }).span(span) + } + + fn build_else_expr(self, mut else_: P) -> F::Result { + for (cond, block) in self.else_ifs.into_iter().rev() { + else_ = ExprBuilder::new().if_() + .build(cond) + .build_then(block) + .build_else_expr(else_); + } + + self.builder.build_expr_kind(ast::ExprKind::If(self.condition, self.then, Some(else_))) + } + + pub fn build_else(self, block: P) -> F::Result { + let else_ = ExprBuilder::new().build_block(block); + self.build_else_expr(else_) + } + + pub fn else_(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } + + pub fn build(self) -> F::Result { + let mut else_ifs = self.else_ifs.into_iter().rev(); + + let else_ = match else_ifs.next() { + Some((cond, block)) => { + let mut else_ = ExprBuilder::new().if_() + .build(cond) + .build_then(block) + .build(); + + for (cond, block) in else_ifs.into_iter().rev() { + else_ = ExprBuilder::new().if_() + .build(cond) + .build_then(block) + .build_else_expr(else_); + } + + Some(else_) + } + None => None + }; + + self.builder.build_expr_kind(ast::ExprKind::If(self.condition, self.then, else_)) + } +} + +impl Invoke> for ExprIfThenElseBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> F::Result { + self.build_else(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprElseIfBuilder { + builder: ExprIfThenElseBuilder, +} + +impl Invoke> for ExprElseIfBuilder + where F: Invoke>, +{ + type Result = ExprElseIfThenBuilder; + + fn invoke(self, expr: P) -> ExprElseIfThenBuilder { + ExprElseIfThenBuilder { + builder: self.builder, + condition: expr, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprElseIfThenBuilder { + builder: ExprIfThenElseBuilder, + condition: P, +} + +impl ExprElseIfThenBuilder + where F: Invoke>, +{ + pub fn build_then(mut self, block: P) -> ExprIfThenElseBuilder { + self.builder.else_ifs.push((self.condition, block)); + self.builder + } + + pub fn then(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } +} + +impl Invoke> for ExprElseIfThenBuilder + where F: Invoke>, +{ + type Result = ExprIfThenElseBuilder; + + fn invoke(self, block: P) -> ExprIfThenElseBuilder { + self.build_then(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprMatchBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprMatchBuilder + where F: Invoke>, +{ + type Result = ExprMatchArmBuilder; + + fn invoke(self, expr: P) -> ExprMatchArmBuilder { + ExprMatchArmBuilder { + builder: self.builder, + expr: expr, + arms: Vec::new(), + } + } +} + +///////////////////////////////////////////////////////////////////////////// + +pub struct ExprMatchArmBuilder { + builder: ExprBuilder, + expr: P, + arms: Vec, +} + +impl ExprMatchArmBuilder + where F: Invoke>, +{ + pub fn with_arms(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.arms.extend(iter); + self + } + + pub fn with_arm(mut self, arm: ast::Arm) -> Self { + self.arms.push(arm); + self + } + + pub fn arm(self) -> ArmBuilder { + ArmBuilder::with_callback(self) + } + + pub fn build(self) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Match(self.expr, self.arms)) + } +} + +impl Invoke for ExprMatchArmBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, arm: ast::Arm) -> Self { + self.with_arm(arm) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprParenBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprParenBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Paren(expr)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprFieldBuilder { + builder: ExprBuilder, + id: ast::SpannedIdent, +} + +impl Invoke> for ExprFieldBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Field(expr, self.id)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprTupFieldBuilder { + builder: ExprBuilder, + index: Spanned, +} + +impl Invoke> for ExprTupFieldBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::TupField(expr, self.index)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprSliceBuilder { + builder: ExprBuilder, + exprs: Vec>, +} + +impl>> ExprSliceBuilder + where F: Invoke> +{ + pub fn with_exprs(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.exprs.extend(iter); + self + } + + pub fn expr(self) -> ExprBuilder { + let span = self.builder.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Vec(self.exprs)) + } +} + +impl Invoke> for ExprSliceBuilder + where F: Invoke> +{ + type Result = ExprSliceBuilder; + + fn invoke(mut self, expr: P) -> Self { + self.exprs.push(expr); + self + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprVecBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprVecBuilder + where F: Invoke> +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + let qpath = ExprBuilder::new().qpath() + .ty().slice().infer() + .id("into_vec"); + + self.builder.call() + .build(qpath) + .arg().box_().build(expr) + .build() + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprTryBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprTryBuilder + where F: Invoke> +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + // ::std::result::Result::Ok(value) => value, + let ok_arm = ArmBuilder::new().span(self.builder.span) + .pat().ok().id("value") + .body().id("value"); + + // ::std::result::Result::Err(err) => + // return ::std::convert::From::from(err), + let err_arm = ArmBuilder::new().span(self.builder.span) + .pat().err().id("err") + .body().return_expr().err().from().id("err"); + + // match $expr { + // $ok_arm, + // $err_arm, + // } + self.builder.match_().build(expr.clone()) + .with_arm(ok_arm) + .with_arm(err_arm) + .build() + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprClosureBuilder { + builder: ExprBuilder, + capture_by: ast::CaptureBy, + span: Span, +} + +impl ExprClosureBuilder { + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn by_value(mut self) -> Self { + self.capture_by = ast::CaptureBy::Value; + self + } + + pub fn by_ref(mut self) -> Self { + self.capture_by = ast::CaptureBy::Ref; + self + } + + pub fn fn_decl(self) -> FnDeclBuilder { + FnDeclBuilder::with_callback(self) + } + + pub fn build_fn_decl(self, fn_decl: P) -> ExprClosureExprBuilder { + ExprClosureExprBuilder { + builder: self.builder, + capture_by: self.capture_by, + fn_decl: fn_decl, + span: self.span, + } + } +} + +impl Invoke> for ExprClosureBuilder { + type Result = ExprClosureExprBuilder; + + fn invoke(self, fn_decl: P) -> ExprClosureExprBuilder { + self.build_fn_decl(fn_decl) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprClosureExprBuilder { + builder: ExprBuilder, + capture_by: ast::CaptureBy, + fn_decl: P, + span: Span, +} + +impl ExprClosureExprBuilder + where F: Invoke>, +{ + pub fn expr(self) -> ExprBuilder { + let span = self.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build_expr(self, expr: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Closure(self.capture_by, self.fn_decl, expr, self.span)) + } +} + +impl Invoke> for ExprClosureExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.build_expr(expr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprWhileBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprWhileBuilder + where F: Invoke>, +{ + type Result = ExprWhileBlockBuilder; + + fn invoke(self, condition: P) -> ExprWhileBlockBuilder { + ExprWhileBlockBuilder { + span: self.builder.span, + builder: self.builder, + condition: condition, + pat: None, + label: None, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprWhileBlockBuilder { + builder: ExprBuilder, + condition: P, + pat: Option>, + span: Span, + label: Option, +} + +impl ExprWhileBlockBuilder { + pub fn pat(self) -> PatBuilder { + PatBuilder::with_callback(self) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn label(mut self, id: I) -> Self + where I: ToIdent, + { + self.label = Some(respan(self.span, id.to_ident())); + self + } + + pub fn build_pat(mut self, pat: P) -> Self { + self.pat = Some(pat); + self + } +} + +impl ExprWhileBlockBuilder + where F: Invoke>, +{ + pub fn block(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } + + pub fn build_block(self, block: P) -> F::Result { + match self.pat { + Some(p) => self.builder.build_expr_kind(ast::ExprKind::WhileLet( + p, self.condition, block, self.label)), + None => self.builder.build_expr_kind(ast::ExprKind::While( + self.condition, block, self.label)), + } + } +} + +impl Invoke> for ExprWhileBlockBuilder { + type Result = Self; + + fn invoke(self, pat: P) -> Self { + self.build_pat(pat) + } +} + +impl Invoke> for ExprWhileBlockBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> F::Result { + self.build_block(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprTypeBuilder { + builder: ExprBuilder, +} + +impl Invoke> for ExprTypeBuilder + where F: Invoke>, +{ + type Result = TyBuilder>; + + fn invoke(self, expr: P) -> TyBuilder> { + TyBuilder::with_callback(ExprTypeTyBuilder { + builder: self.builder, + expr: expr, + }) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ExprTypeTyBuilder { + builder: ExprBuilder, + expr: P, +} + +impl Invoke> for ExprTypeTyBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.builder.build_expr_kind(ast::ExprKind::Type(self.expr, ty)) + } +} diff --git a/bash-5.1/vendor/aster/src/fn_decl.rs b/bash-5.1/vendor/aster/src/fn_decl.rs new file mode 100644 index 0000000..b5bf983 --- /dev/null +++ b/bash-5.1/vendor/aster/src/fn_decl.rs @@ -0,0 +1,262 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span, respan}; +use syntax::ptr::P; + +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use pat::PatBuilder; +use self_::SelfBuilder; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct FnDeclBuilder { + callback: F, + span: Span, + args: Vec, + variadic: bool, +} + +impl FnDeclBuilder { + pub fn new() -> FnDeclBuilder { + FnDeclBuilder::with_callback(Identity) + } +} + +impl FnDeclBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + FnDeclBuilder { + callback: callback, + span: DUMMY_SP, + args: Vec::new(), + variadic: false, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn variadic(mut self) -> Self { + self.variadic = true; + self + } + + pub fn with_self(self, explicit_self: ast::ExplicitSelf) -> Self { + let self_ident = respan(self.span, "self".to_ident()); + self.with_arg(ast::Arg::from_self(explicit_self, self_ident)) + } + + pub fn self_(self) -> SelfBuilder { + SelfBuilder::with_callback(self) + } + + pub fn with_arg(mut self, arg: ast::Arg) -> Self { + self.args.push(arg); + self + } + + pub fn with_args(mut self, iter: I) -> Self + where I: IntoIterator + { + self.args.extend(iter); + self + } + + pub fn arg(self) -> ArgBuilder { + ArgBuilder::with_callback(self) + } + + pub fn arg_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.arg().pat().id(id) + } + + pub fn arg_ref_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.arg().ref_id(id) + } + + pub fn arg_mut_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.arg().mut_id(id) + } + + pub fn arg_ref_mut_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.arg().ref_mut_id(id) + } + + pub fn no_return(self) -> F::Result { + self.return_().never() + } + + pub fn default_return(self) -> F::Result { + let ret_ty = ast::FunctionRetTy::Default(self.span); + self.build(ret_ty) + } + + pub fn build_return(self, ty: P) -> F::Result { + self.build(ast::FunctionRetTy::Ty(ty)) + } + + pub fn return_(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build(self, output: ast::FunctionRetTy) -> F::Result { + self.callback.invoke(P(ast::FnDecl { + inputs: self.args, + output: output, + variadic: self.variadic, + })) + } +} + +impl Invoke for FnDeclBuilder + where F: Invoke> +{ + type Result = Self; + + fn invoke(self, arg: ast::Arg) -> Self { + self.with_arg(arg) + } +} + +impl Invoke> for FnDeclBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build_return(ty) + } +} + +impl Invoke for FnDeclBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, explicit_self: ast::ExplicitSelf) -> Self { + self.with_self(explicit_self) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ArgBuilder { + callback: F, + span: Span, +} + +impl ArgBuilder { + pub fn new() -> Self { + ArgBuilder::with_callback( Identity) + } +} + +impl ArgBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> ArgBuilder { + ArgBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_pat(self, pat: P) -> ArgPatBuilder { + ArgPatBuilder { + callback: self.callback, + span: self.span, + pat: pat, + } + } + + pub fn pat(self) -> PatBuilder { + PatBuilder::with_callback(self) + } + + pub fn id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.pat().id(id) + } + + pub fn ref_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.pat().ref_id(id) + } + + pub fn mut_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.pat().mut_id(id) + } + + pub fn ref_mut_id(self, id: T) -> ArgPatBuilder + where T: ToIdent, + { + self.pat().ref_mut_id(id) + } +} + +impl Invoke> for ArgBuilder + where F: Invoke +{ + type Result = ArgPatBuilder; + + fn invoke(self, pat: P) -> Self::Result { + self.with_pat(pat) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ArgPatBuilder { + callback: F, + span: Span, + pat: P, +} + +impl ArgPatBuilder + where F: Invoke +{ + pub fn with_ty(self, ty: P) -> F::Result { + self.callback.invoke(ast::Arg { + id: ast::DUMMY_NODE_ID, + ty: ty, + pat: self.pat, + }) + } + + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } +} + +impl Invoke> for ArgPatBuilder + where F: Invoke +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.with_ty(ty) + } +} diff --git a/bash-5.1/vendor/aster/src/generics.rs b/bash-5.1/vendor/aster/src/generics.rs new file mode 100644 index 0000000..10cfffc --- /dev/null +++ b/bash-5.1/vendor/aster/src/generics.rs @@ -0,0 +1,254 @@ +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use lifetime::{IntoLifetime, IntoLifetimeDef, LifetimeDefBuilder}; +use path::IntoPath; +use symbol::ToSymbol; +use ty_param::TyParamBuilder; +use where_predicate::WherePredicateBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct GenericsBuilder { + callback: F, + span: Span, + lifetimes: Vec, + ty_params: Vec, + predicates: Vec, +} + +impl GenericsBuilder { + pub fn new() -> Self { + GenericsBuilder::with_callback(Identity) + } + + pub fn from_generics(generics: ast::Generics) -> Self { + GenericsBuilder::from_generics_with_callback(generics, Identity) + } +} + +impl GenericsBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + GenericsBuilder { + callback: callback, + span: DUMMY_SP, + lifetimes: Vec::new(), + ty_params: Vec::new(), + predicates: Vec::new(), + } + } + + pub fn from_generics_with_callback(generics: ast::Generics, callback: F) -> Self { + GenericsBuilder { + callback: callback, + span: DUMMY_SP, + lifetimes: generics.lifetimes, + ty_params: generics.ty_params.into_vec(), + predicates: generics.where_clause.predicates, + } + } + + pub fn with(self, generics: ast::Generics) -> Self { + self.with_lifetimes(generics.lifetimes.into_iter()) + .with_ty_params(generics.ty_params.into_iter()) + .with_predicates(generics.where_clause.predicates.into_iter()) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_lifetimes(mut self, iter: I) -> Self + where I: IntoIterator, + L: IntoLifetimeDef, + { + let iter = iter.into_iter().map(|lifetime_def| lifetime_def.into_lifetime_def()); + self.lifetimes.extend(iter); + self + } + + pub fn with_lifetime_names(mut self, iter: I) -> Self + where I: IntoIterator, + N: ToSymbol, + { + for name in iter { + self = self.lifetime_name(name); + } + self + } + + pub fn with_lifetime(mut self, lifetime: ast::LifetimeDef) -> Self { + self.lifetimes.push(lifetime); + self + } + + pub fn lifetime_name(self, name: N) -> Self + where N: ToSymbol, + { + self.lifetime(name).build() + } + + pub fn lifetime(self, name: N) -> LifetimeDefBuilder + where N: ToSymbol, + { + LifetimeDefBuilder::with_callback(name, self) + } + + pub fn with_ty_params(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.ty_params.extend(iter); + self + } + + pub fn with_ty_param_ids(mut self, iter: I) -> Self + where I: IntoIterator, + T: ToIdent, + { + for id in iter { + self = self.ty_param_id(id); + } + self + } + + pub fn with_ty_param(mut self, ty_param: ast::TyParam) -> Self { + self.ty_params.push(ty_param); + self + } + + pub fn ty_param_id(self, id: I) -> Self + where I: ToIdent, + { + self.ty_param(id).build() + } + + pub fn ty_param(self, id: I) -> TyParamBuilder + where I: ToIdent, + { + let span = self.span; + TyParamBuilder::with_callback(id, self).span(span) + } + + pub fn with_predicates(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.predicates.extend(iter); + self + } + + pub fn with_predicate(mut self, predicate: ast::WherePredicate) -> Self { + self.predicates.push(predicate); + self + } + + pub fn predicate(self) -> WherePredicateBuilder { + WherePredicateBuilder::with_callback(self) + } + + pub fn add_lifetime_bound(mut self, lifetime: L) -> Self + where L: IntoLifetime, + { + let lifetime = lifetime.into_lifetime(); + + for lifetime_def in &mut self.lifetimes { + lifetime_def.bounds.push(lifetime); + } + + for ty_param in &mut self.ty_params { + *ty_param = TyParamBuilder::from_ty_param(ty_param.clone()) + .lifetime_bound(lifetime) + .build(); + } + + self + } + + pub fn add_ty_param_bound

(mut self, path: P) -> Self + where P: IntoPath, + { + let path = path.into_path(); + + for ty_param in &mut self.ty_params { + *ty_param = TyParamBuilder::from_ty_param(ty_param.clone()) + .trait_bound(path.clone()).build() + .build(); + } + + self + } + + pub fn strip_bounds(self) -> Self { + self.strip_lifetimes() + .strip_ty_params() + .strip_predicates() + } + + pub fn strip_lifetimes(mut self) -> Self { + for lifetime in &mut self.lifetimes { + lifetime.bounds = vec![]; + } + self + } + + pub fn strip_ty_params(mut self) -> Self { + for ty_param in &mut self.ty_params { + ty_param.bounds = P::new(); + } + self + } + + pub fn strip_predicates(mut self) -> Self { + self.predicates = vec![]; + self + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::Generics { + lifetimes: self.lifetimes, + ty_params: P::from_vec(self.ty_params), + where_clause: ast::WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: self.predicates, + }, + span: self.span, + }) + } +} + +impl Invoke for GenericsBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, lifetime: ast::LifetimeDef) -> Self { + self.with_lifetime(lifetime) + } +} + +impl Invoke for GenericsBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, ty_param: ast::TyParam) -> Self { + self.with_ty_param(ty_param) + } +} + +impl Invoke for GenericsBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, predicate: ast::WherePredicate) -> Self { + self.with_predicate(predicate) + } +} diff --git a/bash-5.1/vendor/aster/src/ident.rs b/bash-5.1/vendor/aster/src/ident.rs new file mode 100644 index 0000000..d7d02ef --- /dev/null +++ b/bash-5.1/vendor/aster/src/ident.rs @@ -0,0 +1,45 @@ +use syntax::ast; + +use symbol::ToSymbol; + +////////////////////////////////////////////////////////////////////////////// + +pub trait ToIdent { + fn to_ident(&self) -> ast::Ident; +} + +impl ToIdent for ast::Ident { + fn to_ident(&self) -> ast::Ident { + *self + } +} + +impl ToIdent for ast::Name { + fn to_ident(&self) -> ast::Ident { + ast::Ident::with_empty_ctxt(*self) + } +} + +impl<'a> ToIdent for &'a str { + fn to_ident(&self) -> ast::Ident { + self.to_symbol().to_ident() + } +} + +impl ToIdent for String { + fn to_ident(&self) -> ast::Ident { + (&**self).to_ident() + } +} + +impl<'a, T> ToIdent for &'a T where T: ToIdent { + fn to_ident(&self) -> ast::Ident { + (**self).to_ident() + } +} + +impl<'a, T> ToIdent for &'a mut T where T: ToIdent { + fn to_ident(&self) -> ast::Ident { + (**self).to_ident() + } +} diff --git a/bash-5.1/vendor/aster/src/invoke.rs b/bash-5.1/vendor/aster/src/invoke.rs new file mode 100644 index 0000000..daf5175 --- /dev/null +++ b/bash-5.1/vendor/aster/src/invoke.rs @@ -0,0 +1,16 @@ +pub trait Invoke { + type Result; + + fn invoke(self, arg: A) -> Self::Result; +} + +////////////////////////////////////////////////////////////////////////////// + +#[derive(Copy, Clone)] +pub struct Identity; + +impl Invoke for Identity { + type Result = A; + + fn invoke(self, arg: A) -> A { arg } +} diff --git a/bash-5.1/vendor/aster/src/item.rs b/bash-5.1/vendor/aster/src/item.rs new file mode 100644 index 0000000..8dd1b4c --- /dev/null +++ b/bash-5.1/vendor/aster/src/item.rs @@ -0,0 +1,1551 @@ +#![cfg_attr(feature = "unstable", allow(wrong_self_convention))] + +use std::iter::IntoIterator; + +use syntax::abi::Abi; +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span, respan}; +use syntax::ptr::P; +use syntax::symbol::keywords; + +use attr::AttrBuilder; +use block::BlockBuilder; +use constant::{Const, ConstBuilder}; +use fn_decl::FnDeclBuilder; +use generics::GenericsBuilder; +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use mac::MacBuilder; +use method::MethodSigBuilder; +use path::PathBuilder; +use struct_field::StructFieldBuilder; +use symbol::ToSymbol; +use ty::TyBuilder; +use ty_param::TyParamBoundBuilder; +use variant::VariantBuilder; +use variant_data::{ + VariantDataBuilder, + VariantDataStructBuilder, + VariantDataTupleBuilder, +}; + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemBuilder { + callback: F, + span: Span, + attrs: Vec, + vis: ast::Visibility, +} + +impl ItemBuilder { + pub fn new() -> Self { + ItemBuilder::with_callback(Identity) + } +} + +impl ItemBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + ItemBuilder { + callback: callback, + span: DUMMY_SP, + attrs: vec![], + vis: ast::Visibility::Inherited, + } + } + + pub fn build(self, item: P) -> F::Result { + self.callback.invoke(item) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn pub_(mut self) -> Self { + self.vis = ast::Visibility::Public; + self + } + + pub fn build_item_kind(self, id: T, item_kind: ast::ItemKind) -> F::Result + where T: ToIdent, + { + let item = ast::Item { + ident: id.to_ident(), + attrs: self.attrs, + id: ast::DUMMY_NODE_ID, + node: item_kind, + vis: self.vis, + span: self.span, + }; + self.callback.invoke(P(item)) + } + + pub fn fn_(self, id: T) -> FnDeclBuilder> + where T: ToIdent, + { + let id = id.to_ident(); + let span = self.span; + FnDeclBuilder::with_callback(ItemFnDeclBuilder { + builder: self, + span: span, + id: id, + }) + } + + pub fn mod_(self, id: T) -> ItemModBuilder + where T: ToIdent, + { + ItemModBuilder { + ident: id.to_ident(), + vis: self.vis.clone(), + attrs: vec![], + span: self.span, + items: vec![], + builder: self, + } + } + + pub fn build_use(self, view_path: ast::ViewPath_) -> F::Result { + let item = ast::ItemKind::Use(P(respan(self.span, view_path))); + self.build_item_kind(keywords::Invalid.ident(), item) + } + + pub fn use_(self) -> PathBuilder> { + PathBuilder::with_callback(ItemUseBuilder { + builder: self, + }) + } + + pub fn struct_(self, id: T) -> ItemStructBuilder + where T: ToIdent, + { + let id = id.to_ident(); + let generics = GenericsBuilder::new().build(); + + ItemStructBuilder { + is_union: false, + builder: self, + id: id, + generics: generics, + } + } + + pub fn union_(self, id: T) -> ItemStructBuilder + where T: ToIdent, + { + let id = id.to_ident(); + let generics = GenericsBuilder::new().build(); + + ItemStructBuilder { + is_union: true, + builder: self, + id: id, + generics: generics, + } + } + + pub fn unit_struct(self, id: T) -> F::Result + where T: ToIdent, + { + let id = id.to_ident(); + let data = VariantDataBuilder::new().unit(); + let generics = GenericsBuilder::new().build(); + + let struct_ = ast::ItemKind::Struct(data, generics); + self.build_item_kind(id, struct_) + } + + pub fn tuple_struct(self, id: T) -> ItemTupleStructBuilder + where T: ToIdent, + { + let id = id.to_ident(); + let generics = GenericsBuilder::new().build(); + + ItemTupleStructBuilder { + builder: self, + id: id, + generics: generics, + fields: vec![], + } + } + + pub fn enum_(self, id: T) -> ItemEnumBuilder + where T: ToIdent, + { + let id = id.to_ident(); + let span = self.span; + let generics = GenericsBuilder::new().span(span).build(); + + ItemEnumBuilder { + builder: self, + id: id, + generics: generics, + variants: vec![], + } + } + + pub fn extern_crate(self, id: T) -> ItemExternCrateBuilder + where T: ToIdent, + { + let id = id.to_ident(); + + ItemExternCrateBuilder { + builder: self, + id: id, + } + } + + pub fn mac(self) -> MacBuilder> { + self.mac_id(keywords::Invalid.ident()) + } + + pub fn mac_id(self, id: T) -> MacBuilder> + where T: ToIdent, + { + let span = self.span; + MacBuilder::with_callback(ItemMacBuilder { + builder: self, + id: id.to_ident(), + }).span(span) + } + + pub fn type_(self, id: T) -> ItemTyBuilder + where T: ToIdent, + { + let id = id.to_ident(); + let generics = GenericsBuilder::new().build(); + + ItemTyBuilder { + builder: self, + id: id, + generics: generics, + } + } + + pub fn trait_(self, id: T) -> ItemTraitBuilder + where T: ToIdent, + { + ItemTraitBuilder { + builder: self, + id: id.to_ident(), + unsafety: ast::Unsafety::Normal, + generics: GenericsBuilder::new().build(), + bounds: vec![], + items: vec![], + } + } + + pub fn impl_(self) -> ItemImplBuilder { + let generics = GenericsBuilder::new().build(); + + ItemImplBuilder { + builder: self, + unsafety: ast::Unsafety::Normal, + polarity: ast::ImplPolarity::Positive, + generics: generics, + trait_ref: None, + items: vec![], + } + } + + pub fn const_(self, id: T) -> ConstBuilder> + where T: ToIdent, + { + ConstBuilder::with_callback(ItemConstBuilder { + builder: self, + id: id.to_ident(), + }) + } +} + +impl Invoke for ItemBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemFnDeclBuilder { + builder: ItemBuilder, + span: Span, + id: ast::Ident, +} + +impl Invoke> for ItemFnDeclBuilder + where F: Invoke>, +{ + type Result = ItemFnBuilder; + + fn invoke(self, fn_decl: P) -> ItemFnBuilder { + let generics = GenericsBuilder::new().build(); + + ItemFnBuilder { + builder: self.builder, + span: self.span, + id: self.id, + fn_decl: fn_decl, + unsafety: ast::Unsafety::Normal, + constness: ast::Constness::NotConst, + abi: Abi::Rust, + generics: generics, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemFnBuilder { + builder: ItemBuilder, + span: Span, + id: ast::Ident, + fn_decl: P, + unsafety: ast::Unsafety, + constness: ast::Constness, + abi: Abi, + generics: ast::Generics, +} + +impl ItemFnBuilder + where F: Invoke>, +{ + pub fn unsafe_(mut self) -> Self { + self.unsafety = ast::Unsafety::Unsafe; + self + } + + pub fn const_(mut self) -> Self { + self.constness = ast::Constness::Const; + self + } + + pub fn abi(mut self, abi: Abi) -> Self { + self.abi = abi; + self + } + + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn build(self, block: P) -> F::Result { + self.builder.build_item_kind(self.id, ast::ItemKind::Fn( + self.fn_decl, + self.unsafety, + respan(self.span, self.constness), + self.abi, + self.generics, + block, + )) + } + + pub fn block(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } +} + +impl Invoke for ItemFnBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } +} + +impl Invoke> for ItemFnBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> F::Result { + self.build(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemUseBuilder { + builder: ItemBuilder, +} + +impl Invoke for ItemUseBuilder + where F: Invoke>, +{ + type Result = ItemUsePathBuilder; + + fn invoke(self, path: ast::Path) -> ItemUsePathBuilder { + ItemUsePathBuilder { + builder: self.builder, + path: path, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemUsePathBuilder { + builder: ItemBuilder, + path: ast::Path, +} + +impl ItemUsePathBuilder + where F: Invoke>, +{ + pub fn as_(self, id: T) -> F::Result + where T: ToIdent, + { + self.builder.build_use(ast::ViewPathSimple(id.to_ident(), self.path)) + } + + pub fn build(self) -> F::Result { + let id = { + let segment = self.path.segments.last().expect("path with no segments!"); + segment.identifier + }; + self.as_(id) + } + + pub fn glob(self) -> F::Result { + self.builder.build_use(ast::ViewPathGlob(self.path)) + } + + pub fn list(self) -> ItemUsePathListBuilder { + let span = self.builder.span; + ItemUsePathListBuilder { + builder: self.builder, + span: span, + path: self.path, + idents: Vec::new(), + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemUsePathListBuilder { + builder: ItemBuilder, + span: Span, + path: ast::Path, + idents: Vec, +} + +impl ItemUsePathListBuilder + where F: Invoke>, +{ + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn self_(mut self) -> Self { + self.idents.push(respan(self.span, ast::PathListItem_ { + name: keywords::SelfValue.ident(), + rename: None, + id: ast::DUMMY_NODE_ID, + })); + self + } + + pub fn id(mut self, id: T) -> Self + where T: ToIdent, + { + self.idents.push(respan(self.span, ast::PathListItem_ { + name: id.to_ident(), + rename: None, + id: ast::DUMMY_NODE_ID, + })); + self + } + + pub fn build(self) -> F::Result { + self.builder.build_use(ast::ViewPathList(self.path, self.idents)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemStructBuilder { + is_union: bool, + builder: ItemBuilder, + id: ast::Ident, + generics: ast::Generics, +} + +impl ItemStructBuilder + where F: Invoke>, +{ + pub fn with_generics(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } + + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn with_fields(self, iter: I) -> VariantDataStructBuilder + where I: IntoIterator, + { + let span = self.builder.span; + VariantDataBuilder::with_callback(self).span(span).struct_().with_fields(iter) + } + + pub fn with_field(self, field: ast::StructField) -> VariantDataStructBuilder { + let span = self.builder.span; + VariantDataBuilder::with_callback(self).span(span).struct_().with_field(field) + } + + pub fn field(self, id: T) -> StructFieldBuilder> + where T: ToIdent, + { + let span = self.builder.span; + VariantDataBuilder::with_callback(self).span(span).struct_().field(id) + } + + pub fn build(self) -> F::Result { + VariantDataBuilder::with_callback(self).struct_().build() + } +} + +impl Invoke for ItemStructBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, generics: ast::Generics) -> Self { + self.with_generics(generics) + } +} + +impl Invoke for ItemStructBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, data: ast::VariantData) -> F::Result { + let kind = if self.is_union { + ast::ItemKind::Union(data, self.generics) + } else { + ast::ItemKind::Struct(data, self.generics) + }; + + self.builder.build_item_kind(self.id, kind) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemTupleStructBuilder { + builder: ItemBuilder, + id: ast::Ident, + generics: ast::Generics, + fields: Vec, +} + +impl ItemTupleStructBuilder + where F: Invoke>, +{ + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn with_tys(mut self, iter: I) -> Self + where I: IntoIterator>, + { + for ty in iter { + self = self.ty().build(ty); + } + self + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn field(self) -> StructFieldBuilder { + let span = self.builder.span; + StructFieldBuilder::unnamed_with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + let data = ast::VariantData::Tuple(self.fields, ast::DUMMY_NODE_ID); + let struct_ = ast::ItemKind::Struct(data, self.generics); + self.builder.build_item_kind(self.id, struct_) + } +} + +impl Invoke for ItemTupleStructBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } +} + +impl Invoke> for ItemTupleStructBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, ty: P) -> Self { + self.field().build_ty(ty) + } +} + +impl Invoke for ItemTupleStructBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(mut self, field: ast::StructField) -> Self { + self.fields.push(field); + self + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemEnumBuilder { + builder: ItemBuilder, + id: ast::Ident, + generics: ast::Generics, + variants: Vec, +} + +impl ItemEnumBuilder + where F: Invoke>, +{ + pub fn generics(self) -> GenericsBuilder { + let span = self.builder.span; + GenericsBuilder::with_callback(self).span(span) + } + + pub fn with_variants(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.variants.extend(iter); + self + } + + pub fn with_variant(mut self, variant: ast::Variant) -> Self { + self.variants.push(variant); + self + } + + pub fn with_variant_(self, variant: ast::Variant_) -> Self { + let variant = respan(self.builder.span, variant); + self.with_variant(variant) + } + + pub fn ids(mut self, ids: I) -> Self + where I: IntoIterator, + T: ToIdent, + { + for id in ids { + self = self.id(id); + } + self + } + + pub fn id(self, id: T) -> Self + where T: ToIdent, + { + self.variant(id).unit() + } + + pub fn tuple(self, id: T) -> StructFieldBuilder>> + where T: ToIdent, + { + self.variant(id).tuple() + } + + pub fn struct_(self, id: T) -> VariantDataStructBuilder> + where T: ToIdent, + { + self.variant(id).struct_() + } + + pub fn variant(self, id: T) -> VariantBuilder + where T: ToIdent, + { + let span = self.builder.span; + VariantBuilder::with_callback(id, self).span(span) + } + + pub fn build(self) -> F::Result { + let enum_def = ast::EnumDef { + variants: self.variants, + }; + let enum_ = ast::ItemKind::Enum(enum_def, self.generics); + self.builder.build_item_kind(self.id, enum_) + } +} + +impl Invoke for ItemEnumBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } +} + +impl Invoke for ItemEnumBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, variant: ast::Variant) -> Self { + self.with_variant(variant) + } +} + +////////////////////////////////////////////////////////////////////////////// + +/// A builder for extern crate items +pub struct ItemExternCrateBuilder { + builder: ItemBuilder, + id: ast::Ident, +} + +impl ItemExternCrateBuilder + where F: Invoke>, +{ + pub fn with_name(self, name: N) -> F::Result + where N: ToSymbol + { + let extern_ = ast::ItemKind::ExternCrate(Some(name.to_symbol())); + self.builder.build_item_kind(self.id, extern_) + } + + pub fn build(self) -> F::Result { + let extern_ = ast::ItemKind::ExternCrate(None); + self.builder.build_item_kind(self.id, extern_) + } +} + +////////////////////////////////////////////////////////////////////////////// + +/// A builder for macro invocation items. +/// +/// Specifying the macro path returns a `MacBuilder`, which is used to +/// add expressions to the macro invocation. +pub struct ItemMacBuilder { + builder: ItemBuilder, + id: ast::Ident, +} + +impl Invoke for ItemMacBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, mac: ast::Mac) -> F::Result { + self.builder.build_item_kind(self.id, ast::ItemKind::Mac(mac)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemTyBuilder { + builder: ItemBuilder, + id: ast::Ident, + generics: ast::Generics, +} + +impl ItemTyBuilder + where F: Invoke>, +{ + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build_ty(self, ty: P) -> F::Result { + let ty_ = ast::ItemKind::Ty(ty, self.generics); + self.builder.build_item_kind(self.id, ty_) + } +} + +impl Invoke for ItemTyBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } +} + +impl Invoke> for ItemTyBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build_ty(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemTraitBuilder { + builder: ItemBuilder, + id: ast::Ident, + unsafety: ast::Unsafety, + generics: ast::Generics, + bounds: Vec, + items: Vec, +} + +impl ItemTraitBuilder + where F: Invoke>, +{ + pub fn unsafe_(mut self) -> Self { + self.unsafety = ast::Unsafety::Unsafe; + self + } + + pub fn with_generics(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } + + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn with_bounds(mut self, iter: I) -> Self + where I: Iterator, + { + self.bounds.extend(iter); + self + } + + pub fn with_bound(mut self, bound: ast::TyParamBound) -> Self { + self.bounds.push(bound); + self + } + + pub fn bound(self) -> TyParamBoundBuilder { + TyParamBoundBuilder::with_callback(self) + } + + pub fn with_items(mut self, items: I) -> Self + where I: IntoIterator, + { + self.items.extend(items); + self + } + + pub fn with_item(mut self, item: ast::TraitItem) -> Self { + self.items.push(item); + self + } + + pub fn item(self, id: T) -> ItemTraitItemBuilder + where T: ToIdent, + { + ItemTraitItemBuilder::with_callback(id, self) + } + + pub fn const_(self, id: T) -> ConstBuilder> + where T: ToIdent, + { + self.item(id).const_() + } + + pub fn method(self, id: T) -> MethodSigBuilder> + where T: ToIdent, + { + self.item(id).method() + } + + pub fn type_(self, id: T) -> ItemTraitTypeBuilder + where T: ToIdent, + { + self.item(id).type_() + } + + pub fn build(self) -> F::Result { + self.builder.build_item_kind(self.id, ast::ItemKind::Trait( + self.unsafety, + self.generics, + P::from_vec(self.bounds), + self.items, + )) + } +} + +impl Invoke for ItemTraitBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, generics: ast::Generics) -> Self { + self.with_generics(generics) + } +} + +impl Invoke for ItemTraitBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, bound: ast::TyParamBound) -> Self { + self.with_bound(bound) + } +} + +impl Invoke for ItemTraitBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, item: ast::TraitItem) -> Self { + self.with_item(item) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemTraitItemBuilder { + callback: F, + id: ast::Ident, + attrs: Vec, + span: Span, +} + +impl ItemTraitItemBuilder { + pub fn new(id: T) -> Self + where T: ToIdent, + { + Self::with_callback(id, Identity) + } +} + +impl ItemTraitItemBuilder + where F: Invoke, +{ + pub fn with_callback(id: T, callback: F) -> Self + where F: Invoke, + T: ToIdent, + { + ItemTraitItemBuilder { + callback: callback, + id: id.to_ident(), + attrs: vec![], + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn const_(self) -> ConstBuilder { + ConstBuilder::with_callback(self) + } + + pub fn method(self) -> MethodSigBuilder { + MethodSigBuilder::with_callback(self) + } + + pub fn type_(self) -> ItemTraitTypeBuilder { + ItemTraitTypeBuilder { + builder: self, + bounds: vec![], + } + } + + pub fn build_item(self, node: ast::TraitItemKind) -> F::Result { + let item = ast::TraitItem { + id: ast::DUMMY_NODE_ID, + ident: self.id, + attrs: self.attrs, + node: node, + span: self.span, + }; + self.callback.invoke(item) + } +} + +impl Invoke for ItemTraitItemBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +impl Invoke for ItemTraitItemBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, const_: Const) -> F::Result { + let node = ast::TraitItemKind::Const( + const_.ty, + const_.expr); + self.build_item(node) + } +} + +impl Invoke for ItemTraitItemBuilder + where F: Invoke, +{ + type Result = ItemTraitMethodBuilder; + + fn invoke(self, method: ast::MethodSig) -> Self::Result { + ItemTraitMethodBuilder { + builder: self, + method: method, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemTraitMethodBuilder { + builder: ItemTraitItemBuilder, + method: ast::MethodSig, +} + +impl ItemTraitMethodBuilder + where F: Invoke, +{ + pub fn build_option_block(self, block: Option>) -> F::Result { + let node = ast::TraitItemKind::Method(self.method, block); + self.builder.build_item(node) + } + + pub fn build_block(self, block: P) -> F::Result { + self.build_option_block(Some(block)) + } + + pub fn build(self) -> F::Result { + self.build_option_block(None) + } +} + +impl Invoke> for ItemTraitMethodBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> Self::Result { + self.build_block(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemTraitTypeBuilder { + builder: ItemTraitItemBuilder, + bounds: Vec, +} + +impl ItemTraitTypeBuilder + where F: Invoke, +{ + pub fn with_bounds(mut self, iter: I) -> Self + where I: Iterator, + { + self.bounds.extend(iter); + self + } + + pub fn with_bound(mut self, bound: ast::TyParamBound) -> Self { + self.bounds.push(bound); + self + } + + pub fn bound(self) -> TyParamBoundBuilder { + TyParamBoundBuilder::with_callback(self) + } + + pub fn build_option_ty(self, ty: Option>) -> F::Result { + let bounds = P::from_vec(self.bounds); + let node = ast::TraitItemKind::Type(bounds, ty); + self.builder.build_item(node) + } + + pub fn build_ty(self, ty: P) -> F::Result { + self.build_option_ty(Some(ty)) + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.build_option_ty(None) + } +} + +impl Invoke for ItemTraitTypeBuilder + where F: Invoke, +{ + type Result = ItemTraitTypeBuilder; + + fn invoke(self, bound: ast::TyParamBound) -> Self::Result { + self.with_bound(bound) + } +} + +impl Invoke> for ItemTraitTypeBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> Self::Result { + self.build_ty(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemImplBuilder { + builder: ItemBuilder, + unsafety: ast::Unsafety, + polarity: ast::ImplPolarity, + generics: ast::Generics, + trait_ref: Option, + items: Vec, +} + +impl ItemImplBuilder + where F: Invoke>, +{ + pub fn unsafe_(mut self) -> Self { + self.unsafety = ast::Unsafety::Unsafe; + self + } + + pub fn negative(mut self) -> Self { + self.polarity = ast::ImplPolarity::Negative; + self + } + + pub fn with_generics(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } + + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn with_trait(mut self, trait_ref: ast::TraitRef) -> Self { + self.trait_ref = Some(trait_ref); + self + } + + pub fn trait_(self) -> PathBuilder { + PathBuilder::with_callback(self) + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build_ty(self, ty: P) -> F::Result { + let ty_ = ast::ItemKind::Impl( + self.unsafety, + self.polarity, + self.generics, + self.trait_ref, + ty, + self.items); + self.builder.build_item_kind(keywords::Invalid.ident(), ty_) + } + + pub fn with_items(mut self, items: I) -> Self + where I: IntoIterator, + { + self.items.extend(items); + self + } + + pub fn with_item(mut self, item: ast::ImplItem) -> Self { + self.items.push(item); + self + } + + pub fn item(self, id: T) -> ItemImplItemBuilder + where T: ToIdent, + { + ItemImplItemBuilder::with_callback(id, self) + } + + pub fn const_(self, id: T) -> ConstBuilder> + where T: ToIdent, + { + self.item(id).const_() + } + + pub fn method(self, id: T) -> MethodSigBuilder> + where T: ToIdent, + { + self.item(id).method() + } + + pub fn type_(self, id: T) -> TyBuilder> + where T: ToIdent, + { + self.item(id).type_() + } +} + +impl Invoke for ItemImplBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, generics: ast::Generics) -> Self { + self.with_generics(generics) + } +} + +impl Invoke for ItemImplBuilder + where F: Invoke> +{ + type Result = Self; + + fn invoke(self, path: ast::Path) -> Self { + self.with_trait(ast::TraitRef { + path: path, + ref_id: ast::DUMMY_NODE_ID, + }) + } +} + +impl Invoke for ItemImplBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, item: ast::ImplItem) -> Self { + self.with_item(item) + } +} + +impl Invoke> for ItemImplBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build_ty(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemImplItemBuilder { + callback: F, + id: ast::Ident, + vis: ast::Visibility, + defaultness: ast::Defaultness, + attrs: Vec, + span: Span, +} + +impl ItemImplItemBuilder { + pub fn new(id: T) -> Self + where T: ToIdent, + { + Self::with_callback(id, Identity) + } +} + +impl ItemImplItemBuilder + where F: Invoke, +{ + pub fn with_callback(id: T, callback: F) -> Self + where F: Invoke, + T: ToIdent, + { + ItemImplItemBuilder { + callback: callback, + id: id.to_ident(), + vis: ast::Visibility::Inherited, + defaultness: ast::Defaultness::Final, + attrs: vec![], + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn pub_(mut self) -> Self { + self.vis = ast::Visibility::Public; + self + } + + pub fn default(mut self) -> Self { + self.defaultness = ast::Defaultness::Default; + self + } + + pub fn const_(self) -> ConstBuilder { + ConstBuilder::with_callback(self) + } + + pub fn build_method(self, method: ast::MethodSig) -> ItemImplMethodBuilder { + ItemImplMethodBuilder { + builder: self, + method: method, + } + } + + pub fn method(self) -> MethodSigBuilder { + MethodSigBuilder::with_callback(self) + } + + pub fn type_(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn mac(self) -> MacBuilder { + MacBuilder::with_callback(self) + } + + pub fn build_item(self, node: ast::ImplItemKind) -> F::Result { + let item = ast::ImplItem { + id: ast::DUMMY_NODE_ID, + ident: self.id, + vis: self.vis, + defaultness: self.defaultness, + attrs: self.attrs, + node: node, + span: self.span, + }; + self.callback.invoke(item) + } +} + +impl Invoke for ItemImplItemBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +impl Invoke for ItemImplItemBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, const_: Const) -> F::Result { + let node = ast::ImplItemKind::Const(const_.ty, const_.expr.expect("an expr is required for a const impl item")); + self.build_item(node) + } +} + +impl Invoke for ItemImplItemBuilder + where F: Invoke, +{ + type Result = ItemImplMethodBuilder; + + fn invoke(self, method: ast::MethodSig) -> Self::Result { + self.build_method(method) + } +} + +impl Invoke> for ItemImplItemBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let node = ast::ImplItemKind::Type(ty); + self.build_item(node) + } +} + +impl Invoke for ItemImplItemBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, mac: ast::Mac) -> F::Result { + let node = ast::ImplItemKind::Macro(mac); + self.build_item(node) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemImplMethodBuilder { + builder: ItemImplItemBuilder, + method: ast::MethodSig, +} + +impl ItemImplMethodBuilder + where F: Invoke, +{ + pub fn build_block(self, block: P) -> F::Result { + let node = ast::ImplItemKind::Method(self.method, block); + self.builder.build_item(node) + } + + pub fn block(self) -> BlockBuilder { + BlockBuilder::with_callback(self) + } +} + +impl Invoke> for ItemImplMethodBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, block: P) -> Self::Result { + self.build_block(block) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemConstBuilder { + builder: ItemBuilder, + id: ast::Ident, +} + +impl Invoke for ItemConstBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, const_: Const) -> F::Result { + let ty = ast::ItemKind::Const(const_.ty, const_.expr.expect("an expr is required for a const item")); + self.builder.build_item_kind(self.id, ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct ItemModBuilder { + builder: ItemBuilder, + ident: ast::Ident, + vis: ast::Visibility, + attrs: Vec, + span: Span, + items: Vec>, +} + +impl ItemModBuilder +{ + pub fn item(self) -> ItemBuilder { + ItemBuilder::with_callback(self) + } + + pub fn build(self) -> F::Result + where F: Invoke>, + { + let item = ast::Item { + ident: self.ident, + attrs: self.attrs, + id: ast::DUMMY_NODE_ID, + vis: self.vis, + span: self.span, + node: ast::ItemKind::Mod(ast::Mod { + inner: DUMMY_SP, + items: self.items + }), + }; + + self.builder.callback.invoke(P(item)) + } +} + +impl Invoke> for ItemModBuilder { + type Result = Self; + + fn invoke(mut self, item: P) -> Self { + self.items.push(item); + self + } +} diff --git a/bash-5.1/vendor/aster/src/lib.rs b/bash-5.1/vendor/aster/src/lib.rs new file mode 100644 index 0000000..e38a6d5 --- /dev/null +++ b/bash-5.1/vendor/aster/src/lib.rs @@ -0,0 +1,222 @@ +#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, i128_type))] +#![cfg_attr(feature = "clippy", feature(plugin))] +#![cfg_attr(feature = "clippy", plugin(clippy))] +#![cfg_attr(feature = "clippy", allow(wrong_self_convention))] + +#[cfg(feature = "with-syntex")] +extern crate syntex_syntax as syntax; + +#[cfg(not(feature = "with-syntex"))] +extern crate syntax; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; + +pub mod arm; +pub mod attr; +pub mod block; +pub mod constant; +pub mod expr; +pub mod fn_decl; +pub mod generics; +pub mod ident; +pub mod invoke; +pub mod item; +pub mod lifetime; +pub mod lit; +pub mod mac; +pub mod method; +pub mod pat; +pub mod path; +pub mod qpath; +pub mod self_; +pub mod stmt; +pub mod struct_field; +pub mod symbol; +pub mod ty; +pub mod ty_param; +pub mod variant; +pub mod variant_data; +pub mod where_predicate; + +////////////////////////////////////////////////////////////////////////////// + +#[derive(Copy, Clone)] +pub struct AstBuilder { + span: Span, +} + +impl AstBuilder { + pub fn new() -> AstBuilder { + AstBuilder { + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn interned_string(&self, s: S) -> syntax::symbol::InternedString + where S: symbol::ToSymbol + { + s.to_symbol().as_str() + } + + pub fn id(&self, id: I) -> ast::Ident + where I: ident::ToIdent + { + id.to_ident() + } + + pub fn symbol(&self, name: N) -> syntax::symbol::Symbol + where N: symbol::ToSymbol + { + name.to_symbol() + } + + pub fn lifetime(&self, lifetime: L) -> ast::Lifetime + where L: lifetime::IntoLifetime + { + lifetime.into_lifetime() + } + + pub fn arm(&self) -> arm::ArmBuilder { + arm::ArmBuilder::new().span(self.span) + } + + pub fn attr(&self) -> attr::AttrBuilder { + attr::AttrBuilder::new().span(self.span) + } + + pub fn mac(&self) -> mac::MacBuilder { + mac::MacBuilder::new().span(self.span) + } + + pub fn path(&self) -> path::PathBuilder { + path::PathBuilder::new().span(self.span) + } + + pub fn qpath(&self) -> qpath::QPathBuilder { + qpath::QPathBuilder::new().span(self.span) + } + + pub fn ty(&self) -> ty::TyBuilder { + ty::TyBuilder::new().span(self.span) + } + + pub fn lifetime_def(&self, name: N) -> lifetime::LifetimeDefBuilder + where N: symbol::ToSymbol, + { + lifetime::LifetimeDefBuilder::new(name) + } + + pub fn ty_param(&self, id: I) -> ty_param::TyParamBuilder + where I: ident::ToIdent, + { + ty_param::TyParamBuilder::new(id).span(self.span) + } + + pub fn ty_param_bound(&self) -> ty_param::TyParamBoundBuilder { + ty_param::TyParamBoundBuilder::new().span(self.span) + } + + pub fn from_ty_param(&self, ty_param: ast::TyParam) -> ty_param::TyParamBuilder { + ty_param::TyParamBuilder::from_ty_param(ty_param) + } + + pub fn generics(&self) -> generics::GenericsBuilder { + generics::GenericsBuilder::new().span(self.span) + } + + pub fn where_predicate(&self) -> where_predicate::WherePredicateBuilder { + where_predicate::WherePredicateBuilder::new().span(self.span) + } + + pub fn from_generics(&self, generics: ast::Generics) -> generics::GenericsBuilder { + generics::GenericsBuilder::from_generics(generics).span(self.span) + } + + pub fn lit(&self) -> lit::LitBuilder { + lit::LitBuilder::new().span(self.span) + } + + pub fn expr(&self) -> expr::ExprBuilder { + expr::ExprBuilder::new().span(self.span) + } + + pub fn stmt(&self) -> stmt::StmtBuilder { + stmt::StmtBuilder::new().span(self.span) + } + + pub fn block(&self) -> block::BlockBuilder { + block::BlockBuilder::new().span(self.span) + } + + pub fn pat(&self) -> pat::PatBuilder { + pat::PatBuilder::new().span(self.span) + } + + pub fn fn_decl(&self) -> fn_decl::FnDeclBuilder { + fn_decl::FnDeclBuilder::new().span(self.span) + } + + pub fn method_sig(&self) -> method::MethodSigBuilder { + method::MethodSigBuilder::new().span(self.span) + } + + pub fn self_(&self) -> self_::SelfBuilder { + self_::SelfBuilder::new().span(self.span) + } + + pub fn arg(&self) -> fn_decl::ArgBuilder { + fn_decl::ArgBuilder::new().span(self.span) + } + + pub fn variant_data(&self) -> variant_data::VariantDataBuilder { + variant_data::VariantDataBuilder::new().span(self.span) + } + + pub fn variant(&self, id: T) -> variant::VariantBuilder + where T: ident::ToIdent, + { + variant::VariantBuilder::new(id).span(self.span) + } + + pub fn struct_field(&self, id: T) -> struct_field::StructFieldBuilder + where T: ident::ToIdent, + { + struct_field::StructFieldBuilder::named(id).span(self.span) + } + + pub fn tuple_field(&self) -> struct_field::StructFieldBuilder { + struct_field::StructFieldBuilder::unnamed().span(self.span) + } + + pub fn item(&self) -> item::ItemBuilder { + item::ItemBuilder::new().span(self.span) + } + + pub fn trait_item(&self, id: T) -> item::ItemTraitItemBuilder + where T: ident::ToIdent, + { + item::ItemTraitItemBuilder::new(id).span(self.span) + } + + pub fn impl_item(&self, id: T) -> item::ItemImplItemBuilder + where T: ident::ToIdent, + { + item::ItemImplItemBuilder::new(id).span(self.span) + } + + pub fn const_(&self) -> constant::ConstBuilder { + constant::ConstBuilder::new().span(self.span) + } +} + +impl Default for AstBuilder { + fn default() -> Self { + AstBuilder::new() + } +} diff --git a/bash-5.1/vendor/aster/src/lifetime.rs b/bash-5.1/vendor/aster/src/lifetime.rs new file mode 100644 index 0000000..20ee845 --- /dev/null +++ b/bash-5.1/vendor/aster/src/lifetime.rs @@ -0,0 +1,118 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP}; + +use invoke::{Invoke, Identity}; +use symbol::ToSymbol; + +////////////////////////////////////////////////////////////////////////////// + +pub trait IntoLifetime { + fn into_lifetime(self) -> ast::Lifetime; +} + +impl IntoLifetime for ast::Lifetime { + fn into_lifetime(self) -> ast::Lifetime { + self + } +} + +impl<'a> IntoLifetime for &'a str { + fn into_lifetime(self) -> ast::Lifetime { + ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: DUMMY_SP, + name: self.to_symbol(), + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub trait IntoLifetimeDef { + fn into_lifetime_def(self) -> ast::LifetimeDef; +} + +impl IntoLifetimeDef for ast::LifetimeDef { + fn into_lifetime_def(self) -> ast::LifetimeDef { + self + } +} + +impl IntoLifetimeDef for ast::Lifetime { + fn into_lifetime_def(self) -> ast::LifetimeDef { + ast::LifetimeDef { + attrs: ast::ThinVec::new(), + lifetime: self, + bounds: vec![], + } + } +} + +impl<'a> IntoLifetimeDef for &'a str { + fn into_lifetime_def(self) -> ast::LifetimeDef { + self.into_lifetime().into_lifetime_def() + } +} + +impl IntoLifetimeDef for String { + fn into_lifetime_def(self) -> ast::LifetimeDef { + (*self).into_lifetime().into_lifetime_def() + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct LifetimeDefBuilder { + callback: F, + lifetime: ast::Lifetime, + bounds: Vec, +} + +impl LifetimeDefBuilder { + pub fn new(name: N) -> Self + where N: ToSymbol, + { + LifetimeDefBuilder::with_callback(name, Identity) + } +} + +impl LifetimeDefBuilder + where F: Invoke, +{ + pub fn with_callback(name: N, callback: F) -> Self + where N: ToSymbol, + { + let lifetime = ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: DUMMY_SP, + name: name.to_symbol(), + }; + + LifetimeDefBuilder { + callback: callback, + lifetime: lifetime, + bounds: Vec::new(), + } + } + + pub fn bound(mut self, name: N) -> Self + where N: ToSymbol, + { + let lifetime = ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: DUMMY_SP, + name: name.to_symbol(), + }; + + self.bounds.push(lifetime); + self + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::LifetimeDef { + attrs: ast::ThinVec::new(), + lifetime: self.lifetime, + bounds: self.bounds, + }) + } +} diff --git a/bash-5.1/vendor/aster/src/lit.rs b/bash-5.1/vendor/aster/src/lit.rs new file mode 100644 index 0000000..fcbc419 --- /dev/null +++ b/bash-5.1/vendor/aster/src/lit.rs @@ -0,0 +1,160 @@ +use std::convert::Into; +use std::rc::Rc; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use invoke::{Invoke, Identity}; + +use symbol::ToSymbol; + +#[cfg(feature = "with-syntex")] +#[allow(non_camel_case_types)] +type umax = u64; +#[cfg(not(feature = "with-syntex"))] +#[allow(non_camel_case_types)] +type umax = u128; + +////////////////////////////////////////////////////////////////////////////// + +pub struct LitBuilder { + callback: F, + span: Span, +} + +impl LitBuilder { + pub fn new() -> LitBuilder { + LitBuilder::with_callback(Identity) + } +} + +impl LitBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + LitBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> LitBuilder { + self.span = span; + self + } + + pub fn build_lit(self, lit: ast::LitKind) -> F::Result { + self.callback.invoke(P(ast::Lit { + span: self.span, + node: lit, + })) + } + + pub fn bool(self, value: bool) -> F::Result { + self.build_lit(ast::LitKind::Bool(value)) + } + + pub fn true_(self) -> F::Result { + self.bool(true) + } + + pub fn false_(self) -> F::Result { + self.bool(false) + } + + pub fn int(self, value: u64) -> F::Result { + self.build_lit(ast::LitKind::Int(value as umax, ast::LitIntType::Unsuffixed)) + } + + fn build_int(self, value: u64, ty: ast::IntTy) -> F::Result { + self.build_lit(ast::LitKind::Int(value as umax, ast::LitIntType::Signed(ty))) + } + + pub fn isize(self, value: usize) -> F::Result { + self.build_int(value as u64, ast::IntTy::Is) + } + + pub fn i8(self, value: u8) -> F::Result { + self.build_int(value as u64, ast::IntTy::I8) + } + + pub fn i16(self, value: u16) -> F::Result { + self.build_int(value as u64, ast::IntTy::I16) + } + + pub fn i32(self, value: u32) -> F::Result { + self.build_int(value as u64, ast::IntTy::I32) + } + + pub fn i64(self, value: u64) -> F::Result { + self.build_int(value as u64, ast::IntTy::I64) + } + + pub fn uint(self, value: u64) -> F::Result { + self.build_lit(ast::LitKind::Int(value as umax, ast::LitIntType::Unsuffixed)) + } + + fn build_uint(self, value: u64, ty: ast::UintTy) -> F::Result { + self.build_lit(ast::LitKind::Int(value as umax, ast::LitIntType::Unsigned(ty))) + } + + pub fn usize(self, value: usize) -> F::Result { + self.build_uint(value as u64, ast::UintTy::Us) + } + + pub fn u8(self, value: u8) -> F::Result { + self.build_uint(value as u64, ast::UintTy::U8) + } + + pub fn u16(self, value: u16) -> F::Result { + self.build_uint(value as u64, ast::UintTy::U16) + } + + pub fn u32(self, value: u32) -> F::Result { + self.build_uint(value as u64, ast::UintTy::U32) + } + + pub fn u64(self, value: u64) -> F::Result { + self.build_uint(value, ast::UintTy::U64) + } + + fn build_float(self, value: S, ty: ast::FloatTy) -> F::Result + where S: ToSymbol, + { + self.build_lit(ast::LitKind::Float(value.to_symbol(), ty)) + } + + pub fn f32(self, value: S) -> F::Result + where S: ToSymbol, + { + self.build_float(value, ast::FloatTy::F32) + } + + pub fn f64(self, value: S) -> F::Result + where S: ToSymbol, + { + self.build_float(value, ast::FloatTy::F64) + } + + pub fn char(self, value: char) -> F::Result { + self.build_lit(ast::LitKind::Char(value)) + } + + pub fn byte(self, value: u8) -> F::Result { + self.build_lit(ast::LitKind::Byte(value)) + } + + pub fn str(self, value: S) -> F::Result + where S: ToSymbol, + { + let value = value.to_symbol(); + self.build_lit(ast::LitKind::Str(value, ast::StrStyle::Cooked)) + } + + pub fn byte_str(self, value: T) -> F::Result + where T: Into>, + { + self.build_lit(ast::LitKind::ByteStr(Rc::new(value.into()))) + } +} diff --git a/bash-5.1/vendor/aster/src/mac.rs b/bash-5.1/vendor/aster/src/mac.rs new file mode 100644 index 0000000..28df86d --- /dev/null +++ b/bash-5.1/vendor/aster/src/mac.rs @@ -0,0 +1,144 @@ +use syntax::ast; +use syntax::codemap::{self, DUMMY_SP, Span, respan}; +use syntax::ext::base::{DummyResolver, ExtCtxt}; +use syntax::ext::expand; +use syntax::ext::quote::rt::ToTokens; +use syntax::parse::ParseSess; +use syntax::ptr::P; +use syntax::tokenstream::TokenTree; + +use expr::ExprBuilder; +use invoke::{Invoke, Identity}; +use path::PathBuilder; +use symbol::ToSymbol; + +/// A Builder for macro invocations. +/// +/// Note that there are no commas added between args, as otherwise +/// that macro invocations that could be expressed would be limited. +/// You will need to add all required symbols with `with_arg` or +/// `with_argss`. +pub struct MacBuilder { + callback: F, + span: Span, +} + +impl MacBuilder { + pub fn new() -> Self { + MacBuilder::with_callback(Identity) + } +} + +impl MacBuilder + where F: Invoke +{ + pub fn with_callback(callback: F) -> Self { + MacBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn build_path(self, path: ast::Path) -> MacPathBuilder { + MacPathBuilder { + callback: self.callback, + span: self.span, + path: path, + tokens: vec![], + } + } + + pub fn path(self) -> PathBuilder { + let span = self.span; + PathBuilder::with_callback(self).span(span) + } +} + +impl Invoke for MacBuilder + where F: Invoke, +{ + type Result = MacPathBuilder; + + fn invoke(self, path: ast::Path) -> Self::Result { + self.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct MacPathBuilder { + callback: F, + span: Span, + path: ast::Path, + tokens: Vec, +} + +impl MacPathBuilder + where F: Invoke, +{ + pub fn with_args(self, iter: I) -> Self + where I: IntoIterator, T: ToTokens + { + iter.into_iter().fold(self, |self_, expr| self_.with_arg(expr)) + } + + pub fn with_arg(mut self, expr: T) -> Self + where T: ToTokens + { + let parse_sess = ParseSess::new(); + let mut macro_loader = DummyResolver; + let cx = make_ext_ctxt(&parse_sess, &mut macro_loader); + let tokens = expr.to_tokens(&cx); + assert!(tokens.len() == 1); + self.tokens.push(tokens[0].clone()); + self + } + + pub fn expr(self) -> ExprBuilder { + let span = self.span; + ExprBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + let mac = ast::Mac_ { + path: self.path, + tts: self.tokens, + }; + self.callback.invoke(respan(self.span, mac)) + } +} + +impl Invoke> for MacPathBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, expr: P) -> Self { + self.with_arg(expr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +fn make_ext_ctxt<'a>(sess: &'a ParseSess, + macro_loader: &'a mut DummyResolver) -> ExtCtxt<'a> { + let info = codemap::ExpnInfo { + call_site: codemap::DUMMY_SP, + callee: codemap::NameAndSpan { + format: codemap::MacroAttribute("test".to_symbol()), + allow_internal_unstable: false, + span: None + } + }; + + let ecfg = expand::ExpansionConfig::default(String::new()); + let mut cx = ExtCtxt::new(sess, ecfg, macro_loader); + cx.bt_push(info); + + cx +} diff --git a/bash-5.1/vendor/aster/src/method.rs b/bash-5.1/vendor/aster/src/method.rs new file mode 100644 index 0000000..a6df4b0 --- /dev/null +++ b/bash-5.1/vendor/aster/src/method.rs @@ -0,0 +1,103 @@ +use syntax::abi::Abi; +use syntax::ast; +use syntax::codemap::{DUMMY_SP, respan, Span}; +use syntax::ptr::P; + +use fn_decl::FnDeclBuilder; +use generics::GenericsBuilder; +use invoke::{Invoke, Identity}; + +////////////////////////////////////////////////////////////////////////////// + +pub struct MethodSigBuilder { + callback: F, + span: Span, + abi: Abi, + generics: ast::Generics, + unsafety: ast::Unsafety, + constness: ast::Constness, +} + +impl MethodSigBuilder { + pub fn new() -> Self { + MethodSigBuilder::with_callback(Identity) + } +} + +impl MethodSigBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + MethodSigBuilder { + callback: callback, + span: DUMMY_SP, + abi: Abi::Rust, + generics: GenericsBuilder::new().build(), + unsafety: ast::Unsafety::Normal, + constness: ast::Constness::NotConst, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn unsafe_(mut self) -> Self { + self.unsafety = ast::Unsafety::Unsafe; + self + } + + pub fn const_(mut self) -> Self { + self.constness = ast::Constness::Const; + self + } + + pub fn abi(mut self, abi: Abi) -> Self { + self.abi = abi; + self + } + + pub fn with_generics(mut self, generics: ast::Generics) -> Self { + self.generics = generics; + self + } + + pub fn generics(self) -> GenericsBuilder { + GenericsBuilder::with_callback(self) + } + + pub fn build_fn_decl(self, fn_decl: P) -> F::Result { + self.callback.invoke(ast::MethodSig { + unsafety: self.unsafety, + constness: respan(self.span, self.constness), + abi: self.abi, + decl: fn_decl, + generics: self.generics, + }) + } + + pub fn fn_decl(self) -> FnDeclBuilder { + FnDeclBuilder::with_callback(self) + } +} + +impl Invoke for MethodSigBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, generics: ast::Generics) -> Self { + self.with_generics(generics) + } +} + +impl Invoke> for MethodSigBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, fn_decl: P) -> Self::Result { + self.build_fn_decl(fn_decl) + } +} diff --git a/bash-5.1/vendor/aster/src/pat.rs b/bash-5.1/vendor/aster/src/pat.rs new file mode 100644 index 0000000..ce74fe7 --- /dev/null +++ b/bash-5.1/vendor/aster/src/pat.rs @@ -0,0 +1,558 @@ +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span, Spanned, respan}; +use syntax::ptr::P; + +use invoke::{Invoke, Identity}; + +use expr::ExprBuilder; +use ident::ToIdent; +use path::PathBuilder; +use qpath::QPathBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatBuilder { + callback: F, + span: Span, +} + +impl PatBuilder { + pub fn new() -> Self { + PatBuilder::with_callback(Identity) + } +} + +impl PatBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + PatBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn build(self, pat: P) -> F::Result { + self.callback.invoke(pat) + } + + pub fn build_pat_kind(self, pat_kind: ast::PatKind) -> F::Result { + let span = self.span; + self.build(P(ast::Pat { + id: ast::DUMMY_NODE_ID, + node: pat_kind, + span: span, + })) + } + + pub fn wild(self) -> F::Result { + self.build_pat_kind(ast::PatKind::Wild) + } + + pub fn build_id(self, mode: ast::BindingMode, id: I, sub: Option>) -> F::Result + where I: ToIdent, + { + let id = respan(self.span, id.to_ident()); + + self.build_pat_kind(ast::PatKind::Ident(mode, id, sub)) + } + + pub fn id(self, id: I) -> F::Result + where I: ToIdent + { + let mode = ast::BindingMode::ByValue(ast::Mutability::Immutable); + self.build_id(mode, id, None) + } + + pub fn mut_id(self, id: I) -> F::Result + where I: ToIdent + { + let mode = ast::BindingMode::ByValue(ast::Mutability::Mutable); + self.build_id(mode, id, None) + } + + pub fn ref_id(self, id: I) -> F::Result + where I: ToIdent + { + let mode = ast::BindingMode::ByRef(ast::Mutability::Immutable); + self.build_id(mode, id, None) + } + + pub fn ref_mut_id(self, id: I) -> F::Result + where I: ToIdent + { + let mode = ast::BindingMode::ByRef(ast::Mutability::Mutable); + self.build_id(mode, id, None) + } + + pub fn enum_(self) -> PathBuilder> { + PathBuilder::with_callback(PatEnumBuilder(self)) + } + + pub fn struct_(self) -> PathBuilder> { + PathBuilder::with_callback(PatStructBuilder(self)) + } + + pub fn expr(self) -> ExprBuilder> { + ExprBuilder::with_callback(PatExprBuilder(self)) + } + + pub fn build_path(self, path: ast::Path) -> F::Result { + self.build_pat_kind(ast::PatKind::Path(None, path)) + } + + pub fn build_qpath(self, qself: ast::QSelf, path: ast::Path) -> F::Result { + self.build_pat_kind(ast::PatKind::Path(Some(qself), path)) + } + + pub fn path(self) -> PathBuilder { + PathBuilder::with_callback(self) + } + + pub fn qpath(self) -> QPathBuilder { + QPathBuilder::with_callback(self) + } + + pub fn build_range(self, lhs: P, rhs: P) -> F::Result { + self.build_pat_kind(ast::PatKind::Range(lhs, rhs)) + } + + pub fn range(self) -> ExprBuilder> { + ExprBuilder::with_callback(PatRangeBuilder(self)) + } + + pub fn tuple(self) -> PatTupleBuilder { + PatTupleBuilder { + builder: self, + pats: Vec::new(), + wild: None, + } + } + + pub fn ref_(self) -> PatBuilder> { + PatBuilder::with_callback(PatRefBuilder { + builder: self, + mutability: ast::Mutability::Immutable, + }) + } + + pub fn ref_mut(self) -> PatBuilder> { + PatBuilder::with_callback(PatRefBuilder { + builder: self, + mutability: ast::Mutability::Mutable, + }) + } + + pub fn some(self) -> PatBuilder> { + let path = PathBuilder::new().span(self.span) + .global() + .ids(&["std", "option", "Option", "Some"]) + .build(); + + let span = self.span; + PatBuilder::with_callback(PatEnumPathPatBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn none(self) -> F::Result { + let path = PathBuilder::new().span(self.span) + .global() + .ids(&["std", "option", "Option", "None"]) + .build(); + + self.enum_() + .build(path) + .build() + } + + pub fn ok(self) -> PatBuilder> { + let path = PathBuilder::new().span(self.span) + .global() + .ids(&["std", "result", "Result", "Ok"]) + .build(); + + let span = self.span; + PatBuilder::with_callback(PatEnumPathPatBuilder { + builder: self, + path: path, + }).span(span) + } + + pub fn err(self) -> PatBuilder> { + let path = PathBuilder::new().span(self.span) + .global() + .ids(&["std", "result", "Result", "Err"]) + .build(); + + let span = self.span; + PatBuilder::with_callback(PatEnumPathPatBuilder { + builder: self, + path: path, + }).span(span) + } +} + +impl Invoke for PatBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, path: ast::Path) -> F::Result { + self.build_path(path) + } +} + +impl Invoke<(ast::QSelf, ast::Path)> for PatBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, (qself, path): (ast::QSelf, ast::Path)) -> F::Result { + self.build_qpath(qself, path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatRangeBuilder(PatBuilder); + +impl Invoke> for PatRangeBuilder + where F: Invoke> +{ + type Result = ExprBuilder>; + + fn invoke(self, lhs: P) -> Self::Result { + ExprBuilder::with_callback(PatRangeExprBuilder { + builder: self.0, + lhs: lhs, + }) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatRangeExprBuilder { + builder: PatBuilder, + lhs: P, +} + +impl Invoke> for PatRangeExprBuilder + where F: Invoke> +{ + type Result = F::Result; + + fn invoke(self, rhs: P) -> Self::Result { + self.builder.build_range(self.lhs, rhs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatEnumBuilder(PatBuilder); + +impl Invoke for PatEnumBuilder { + type Result = PatEnumPathBuilder; + + fn invoke(self, path: ast::Path) -> PatEnumPathBuilder { + PatEnumPathBuilder { + builder: self.0, + path: path, + pats: Vec::new(), + wild: None, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatEnumPathBuilder { + builder: PatBuilder, + path: ast::Path, + pats: Vec>, + wild: Option, +} + +impl PatEnumPathBuilder + where F: Invoke>, +{ + pub fn with_pats(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.pats.extend(iter); + self + } + + pub fn with_pat(mut self, pat: P) -> Self { + self.pats.push(pat); + self + } + + pub fn pat(self) -> PatBuilder { + PatBuilder::with_callback(self) + } + + pub fn with_ids(mut self, iter: I) -> Self + where I: IntoIterator, + T: ToIdent, + { + for id in iter { + self = self.id(id); + } + self + } + + pub fn id(self, id: I) -> Self + where I: ToIdent + { + self.pat().id(id) + } + + pub fn wild(mut self) -> Self { + self.wild = Some(self.pats.len()); + self + } + + pub fn build(self) -> F::Result { + self.builder.build_pat_kind(ast::PatKind::TupleStruct( + self.path, + self.pats, + self.wild)) + } +} + +impl Invoke> for PatEnumPathBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(mut self, pat: P) -> Self { + self.pats.push(pat); + self + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatEnumPathPatBuilder { + builder: PatBuilder, + path: ast::Path, +} + +impl Invoke> for PatEnumPathPatBuilder + where F: Invoke> +{ + type Result = F::Result; + + fn invoke(self, pat: P) -> F::Result { + self.builder.enum_() + .build(self.path) + .with_pat(pat) + .build() + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatStructBuilder(PatBuilder); + +impl Invoke for PatStructBuilder { + type Result = PatStructPathBuilder; + + fn invoke(self, path: ast::Path) -> PatStructPathBuilder { + PatStructPathBuilder { + builder: self.0, + path: path, + pats: Vec::new(), + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatStructPathBuilder { + builder: PatBuilder, + path: ast::Path, + pats: Vec>, +} + +impl PatStructPathBuilder + where F: Invoke>, +{ + pub fn with_field_pat(mut self, pat: ast::FieldPat) -> Self { + self.pats.push(respan(self.builder.span, pat)); + self + } + + pub fn with_pats(mut self, iter: I) -> Self + where I: IntoIterator)>, + T: ToIdent, + { + for (id, pat) in iter { + self = self.pat(id).build(pat); + } + self + } + + pub fn pat(self, id: I) -> PatBuilder> + where I: ToIdent, + { + PatBuilder::with_callback(PatStructFieldBuilder { + builder: self, + id: id.to_ident(), + }) + } + + pub fn with_ids(mut self, iter: I) -> Self + where I: IntoIterator, + T: ToIdent, + { + for id in iter { + self = self.id(id); + } + self + } + + pub fn mut_id(self, id: I) -> Self + where I: ToIdent, + { + let id = id.to_ident(); + let span = self.builder.span; + let pat = PatBuilder::new().span(span).mut_id(id); + + self.with_field_pat(ast::FieldPat { + ident: id, + pat: pat, + is_shorthand: true, + }) + } + + pub fn id(self, id: I) -> Self + where I: ToIdent, + { + let id = id.to_ident(); + let span = self.builder.span; + let pat = PatBuilder::new().span(span).id(id); + + self.with_field_pat(ast::FieldPat { + ident: id, + pat: pat, + is_shorthand: true, + }) + } + + pub fn etc(self) -> F::Result { + self.builder.build_pat_kind(ast::PatKind::Struct(self.path, self.pats, true)) + } + + pub fn build(self) -> F::Result { + self.builder.build_pat_kind(ast::PatKind::Struct(self.path, self.pats, false)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatStructFieldBuilder { + builder: PatStructPathBuilder, + id: ast::Ident, +} + +impl Invoke> for PatStructFieldBuilder + where F: Invoke>, +{ + type Result = PatStructPathBuilder; + + fn invoke(self, pat: P) -> PatStructPathBuilder { + self.builder.with_field_pat(ast::FieldPat { + ident: self.id, + pat: pat, + is_shorthand: false, + }) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatExprBuilder(PatBuilder); + +impl Invoke> for PatExprBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.0.build_pat_kind(ast::PatKind::Lit(expr)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatTupleBuilder { + builder: PatBuilder, + pats: Vec>, + wild: Option, +} + +impl>> PatTupleBuilder + where F: Invoke> +{ + pub fn with_pats(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.pats.extend(iter); + self + } + + pub fn with_pat(mut self, pat: P) -> Self { + self.pats.push(pat); + self + } + + pub fn pat(self) -> PatBuilder { + PatBuilder::with_callback(self) + } + + pub fn wild(mut self) -> Self { + self.wild = Some(self.pats.len()); + self + } + + pub fn build(self) -> F::Result { + self.builder.build_pat_kind(ast::PatKind::Tuple(self.pats, self.wild)) + } +} + +impl Invoke> for PatTupleBuilder + where F: Invoke> +{ + type Result = PatTupleBuilder; + + fn invoke(self, pat: P) -> Self { + self.with_pat(pat) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PatRefBuilder { + builder: PatBuilder, + mutability: ast::Mutability, +} + +impl Invoke> for PatRefBuilder + where F: Invoke> +{ + type Result = F::Result; + + fn invoke(self, pat: P) -> F::Result { + self.builder.build_pat_kind(ast::PatKind::Ref(pat, self.mutability)) + } +} diff --git a/bash-5.1/vendor/aster/src/path.rs b/bash-5.1/vendor/aster/src/path.rs new file mode 100644 index 0000000..ab7d5d5 --- /dev/null +++ b/bash-5.1/vendor/aster/src/path.rs @@ -0,0 +1,378 @@ +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use invoke::{Invoke, Identity}; + +use ident::ToIdent; +use symbol::ToSymbol; +use ty::TyBuilder; + +use lifetime::IntoLifetime; + +////////////////////////////////////////////////////////////////////////////// + +pub trait IntoPath { + fn into_path(self) -> ast::Path; +} + +impl IntoPath for ast::Path { + fn into_path(self) -> ast::Path { + self + } +} + +impl IntoPath for ast::Ident { + fn into_path(self) -> ast::Path { + PathBuilder::new().id(self).build() + } +} + +impl<'a> IntoPath for &'a str { + fn into_path(self) -> ast::Path { + PathBuilder::new().id(self).build() + } +} + +impl IntoPath for String { + fn into_path(self) -> ast::Path { + (&*self).into_path() + } +} + +impl<'a, T> IntoPath for &'a [T] where T: ToIdent { + fn into_path(self) -> ast::Path { + PathBuilder::new().ids(self).build() + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PathBuilder { + callback: F, + span: Span, + global: bool, +} + +impl PathBuilder { + pub fn new() -> Self { + PathBuilder::with_callback(Identity) + } +} + +impl PathBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + PathBuilder { + callback: callback, + span: DUMMY_SP, + global: false, + } + } + + pub fn build(self, path: ast::Path) -> F::Result { + self.callback.invoke(path) + } + + /// Update the span to start from this location. + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn global(mut self) -> Self { + self.global = true; + self + } + + pub fn ids(self, ids: I) -> PathSegmentsBuilder + where I: IntoIterator, + T: ToIdent, + { + let mut ids = ids.into_iter(); + let id = ids.next().expect("passed path with no id"); + + self.id(id).ids(ids) + } + + pub fn id(self, id: I) -> PathSegmentsBuilder + where I: ToIdent, + { + self.segment(id).build() + } + + pub fn segment(self, id: I) + -> PathSegmentBuilder> + where I: ToIdent, + { + let mut segments = vec![]; + + if self.global { + segments.push(ast::PathSegment::crate_root()); + } + + PathSegmentBuilder::with_callback(id, PathSegmentsBuilder { + callback: self.callback, + span: self.span, + segments: segments, + }) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PathSegmentsBuilder { + callback: F, + span: Span, + segments: Vec, +} + +impl PathSegmentsBuilder + where F: Invoke, +{ + pub fn ids(mut self, ids: I) -> PathSegmentsBuilder + where I: IntoIterator, + T: ToIdent, + { + for id in ids { + self = self.id(id); + } + + self + } + + pub fn id(self, id: T) -> PathSegmentsBuilder + where T: ToIdent, + { + self.segment(id).build() + } + + pub fn segment(self, id: T) -> PathSegmentBuilder + where T: ToIdent, + { + let span = self.span; + PathSegmentBuilder::with_callback(id, self).span(span) + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::Path { + span: self.span, + segments: self.segments, + }) + } +} + +impl Invoke for PathSegmentsBuilder { + type Result = Self; + + fn invoke(mut self, segment: ast::PathSegment) -> Self { + self.segments.push(segment); + self + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PathSegmentBuilder { + callback: F, + span: Span, + id: ast::Ident, + lifetimes: Vec, + tys: Vec>, + bindings: Vec, +} + +impl PathSegmentBuilder + where F: Invoke, +{ + pub fn with_callback(id: I, callback: F) -> Self + where I: ToIdent, + { + PathSegmentBuilder { + callback: callback, + span: DUMMY_SP, + id: id.to_ident(), + lifetimes: Vec::new(), + tys: Vec::new(), + bindings: Vec::new(), + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_generics(self, generics: ast::Generics) -> Self { + // Strip off the bounds. + let lifetimes = generics.lifetimes.iter() + .map(|lifetime_def| lifetime_def.lifetime); + + let span = self.span; + + let tys = generics.ty_params.iter() + .map(|ty_param| TyBuilder::new().span(span).id(ty_param.ident)); + + self.with_lifetimes(lifetimes) + .with_tys(tys) + } + + pub fn with_lifetimes(mut self, iter: I) -> Self + where I: IntoIterator, + L: IntoLifetime, + { + let iter = iter.into_iter().map(|lifetime| lifetime.into_lifetime()); + self.lifetimes.extend(iter); + self + } + + pub fn with_lifetime(mut self, lifetime: L) -> Self + where L: IntoLifetime, + { + self.lifetimes.push(lifetime.into_lifetime()); + self + } + + pub fn lifetime(self, name: N) -> Self + where N: ToSymbol, + { + let lifetime = ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: self.span, + name: name.to_symbol(), + }; + self.with_lifetime(lifetime) + } + + pub fn with_tys(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.tys.extend(iter); + self + } + + pub fn with_ty(mut self, ty: P) -> Self { + self.tys.push(ty); + self + } + + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn with_binding(mut self, binding: ast::TypeBinding) -> Self { + self.bindings.push(binding); + self + } + + pub fn binding(self, id: T) -> TyBuilder> + where T: ToIdent, + { + let span = self.span; + TyBuilder::with_callback(TypeBindingBuilder { + id: id.to_ident(), + builder: self, + }).span(span) + } + + pub fn no_return(self) -> F::Result { + self.build_return(None) + } + + pub fn return_(self) -> TyBuilder> { + TyBuilder::with_callback(PathSegmentReturnBuilder(self)) + } + + pub fn build_return(self, output: Option>) -> F::Result { + let parameters = if self.tys.is_empty() { + None + } else { + let data = ast::ParenthesizedParameterData { + span: self.span, + inputs: self.tys, + output: output, + }; + + Some(P(ast::PathParameters::Parenthesized(data))) + }; + + self.callback.invoke(ast::PathSegment { + identifier: self.id, + parameters: parameters, + }) + } + + pub fn build(self) -> F::Result { + let parameters = if self.lifetimes.is_empty() && + self.tys.is_empty() && + self.bindings.is_empty() { + None + } else { + let data = ast::AngleBracketedParameterData { + lifetimes: self.lifetimes, + types: P::from_vec(self.tys), + bindings: P::from_vec(self.bindings), + }; + + Some(P(ast::PathParameters::AngleBracketed(data))) + }; + + self.callback.invoke(ast::PathSegment { + identifier: self.id, + parameters: parameters, + }) + } +} + +impl Invoke> for PathSegmentBuilder + where F: Invoke +{ + type Result = Self; + + fn invoke(self, ty: P) -> Self { + self.with_ty(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TypeBindingBuilder { + id: ast::Ident, + builder: PathSegmentBuilder, +} + +impl Invoke> for TypeBindingBuilder + where F: Invoke +{ + type Result = PathSegmentBuilder; + + fn invoke(self, ty: P) -> Self::Result { + let id = self.id; + let span = self.builder.span; + + self.builder.with_binding(ast::TypeBinding { + id: ast::DUMMY_NODE_ID, + ident: id, + ty: ty, + span: span, + }) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PathSegmentReturnBuilder(PathSegmentBuilder); + +impl Invoke> for PathSegmentReturnBuilder + where F: Invoke +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> Self::Result { + self.0.build_return(Some(ty)) + } +} diff --git a/bash-5.1/vendor/aster/src/qpath.rs b/bash-5.1/vendor/aster/src/qpath.rs new file mode 100644 index 0000000..dcd1a1f --- /dev/null +++ b/bash-5.1/vendor/aster/src/qpath.rs @@ -0,0 +1,161 @@ +#![cfg_attr(feature = "unstable", allow(wrong_self_convention))] + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use invoke::{Invoke, Identity}; + +use ident::ToIdent; +use path::{PathBuilder, PathSegmentBuilder}; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct QPathBuilder { + callback: F, + span: Span, +} + +impl QPathBuilder { + pub fn new() -> Self { + QPathBuilder::with_callback(Identity) + } +} + +impl QPathBuilder + where F: Invoke<(ast::QSelf, ast::Path)>, +{ + /// Construct a `QPathBuilder` that will call the `callback` with a constructed `ast::QSelf` + /// and `ast::Path`. + pub fn with_callback(callback: F) -> Self { + QPathBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + /// Update the span to start from this location. + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + /// Build a qualified path first by starting with a type builder. + pub fn with_ty(self, ty: P) -> QPathTyBuilder { + QPathTyBuilder { + builder: self, + ty: ty, + } + } + + /// Build a qualified path first by starting with a type builder. + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + /// Build a qualified path with a concrete type and path. + pub fn build(self, qself: ast::QSelf, path: ast::Path) -> F::Result { + self.callback.invoke((qself, path)) + } +} + +impl Invoke> for QPathBuilder + where F: Invoke<(ast::QSelf, ast::Path)>, +{ + type Result = QPathTyBuilder; + + fn invoke(self, ty: P) -> QPathTyBuilder { + self.with_ty(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct QPathTyBuilder { + builder: QPathBuilder, + ty: P, +} + +impl QPathTyBuilder + where F: Invoke<(ast::QSelf, ast::Path)>, +{ + /// Build a qualified path with a path builder. + pub fn as_(self) -> PathBuilder { + let span = self.builder.span; + PathBuilder::with_callback(self).span(span) + } + + pub fn id(self, id: T) -> F::Result + where T: ToIdent, + { + let path = ast::Path { + span: self.builder.span, + segments: vec![], + }; + self.as_().build(path).id(id) + } + + pub fn segment(self, id: T) -> PathSegmentBuilder> + where T: ToIdent, + { + let path = ast::Path { + span: self.builder.span, + segments: vec![], + }; + self.as_().build(path).segment(id) + } +} + +impl Invoke for QPathTyBuilder + where F: Invoke<(ast::QSelf, ast::Path)>, +{ + type Result = QPathQSelfBuilder; + + fn invoke(self, path: ast::Path) -> QPathQSelfBuilder { + QPathQSelfBuilder { + builder: self.builder, + qself: ast::QSelf { + ty: self.ty, + position: path.segments.len(), + }, + path: path, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct QPathQSelfBuilder { + builder: QPathBuilder, + qself: ast::QSelf, + path: ast::Path, +} + +impl QPathQSelfBuilder + where F: Invoke<(ast::QSelf, ast::Path)>, +{ + pub fn id(self, id: T) -> F::Result + where T: ToIdent, + { + self.segment(id).build() + } + + pub fn segment(self, id: T) -> PathSegmentBuilder> + where T: ToIdent, + { + PathSegmentBuilder::with_callback(id, self) + } +} + +impl Invoke for QPathQSelfBuilder + where F: Invoke<(ast::QSelf, ast::Path)>, +{ + type Result = F::Result; + + fn invoke(mut self, segment: ast::PathSegment) -> F::Result { + self.path.segments.push(segment); + self.builder.build(self.qself, self.path) + } +} diff --git a/bash-5.1/vendor/aster/src/self_.rs b/bash-5.1/vendor/aster/src/self_.rs new file mode 100644 index 0000000..ca5c762 --- /dev/null +++ b/bash-5.1/vendor/aster/src/self_.rs @@ -0,0 +1,81 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span, respan}; +use syntax::ptr::P; + +use invoke::{Invoke, Identity}; +use lifetime::IntoLifetime; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct SelfBuilder { + callback: F, + span: Span, + mutable: ast::Mutability, +} + +impl SelfBuilder { + pub fn new() -> Self { + SelfBuilder::with_callback(Identity) + } +} + +impl SelfBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + SelfBuilder { + callback: callback, + span: DUMMY_SP, + mutable: ast::Mutability::Immutable, + } + } + + pub fn build(self, self_: ast::SelfKind) -> F::Result { + let self_ = respan(self.span, self_); + self.callback.invoke(self_) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn mut_(mut self) -> Self { + self.mutable = ast::Mutability::Mutable; + self + } + + pub fn value(self) -> F::Result { + let self_ = ast::SelfKind::Value(self.mutable); + self.build(self_) + } + + pub fn ref_(self) -> F::Result { + let self_ = ast::SelfKind::Region(None, self.mutable); + self.build(self_) + } + + pub fn ref_lifetime(self, lifetime: L) -> F::Result + where L: IntoLifetime, + { + let self_ = ast::SelfKind::Region(Some(lifetime.into_lifetime()), self.mutable); + self.build(self_) + } + + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } +} + +impl Invoke> for SelfBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let explicit_self = ast::SelfKind::Explicit(ty, self.mutable); + self.build(explicit_self) + } +} diff --git a/bash-5.1/vendor/aster/src/stmt.rs b/bash-5.1/vendor/aster/src/stmt.rs new file mode 100644 index 0000000..9f8dc2f --- /dev/null +++ b/bash-5.1/vendor/aster/src/stmt.rs @@ -0,0 +1,360 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; +use syntax::util::ThinVec; + +use attr::AttrBuilder; +use expr::ExprBuilder; +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use item::ItemBuilder; +use mac::MacBuilder; +use pat::PatBuilder; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtBuilder { + callback: F, + span: Span, +} + +impl StmtBuilder { + pub fn new() -> StmtBuilder { + StmtBuilder::with_callback(Identity) + } +} + +impl StmtBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + StmtBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn build(self, stmt: ast::Stmt) -> F::Result { + self.callback.invoke(stmt) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn build_stmt_kind(self, stmt_: ast::StmtKind) -> F::Result { + let stmt = ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: stmt_, + span: self.span, + }; + self.build(stmt) + } + + pub fn build_let(self, + pat: P, + ty: Option>, + init: Option>, + attrs: Vec) -> F::Result { + let local = ast::Local { + pat: pat, + ty: ty, + init: init, + id: ast::DUMMY_NODE_ID, + span: self.span, + attrs: ThinVec::from(attrs), + }; + + self.build_stmt_kind(ast::StmtKind::Local(P(local))) + } + + pub fn let_(self) -> PatBuilder { + let span = self.span; + PatBuilder::with_callback(self).span(span) + } + + pub fn let_id(self, id: I) -> StmtLetBuilder + where I: ToIdent, + { + self.let_().id(id) + } + + pub fn build_expr(self, expr: P) -> F::Result { + self.build_stmt_kind(ast::StmtKind::Expr(expr)) + } + + pub fn expr(self) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(StmtExprBuilder(self)).span(span) + } + + pub fn semi(self) -> ExprBuilder> { + let span = self.span; + ExprBuilder::with_callback(StmtSemiBuilder(self)).span(span) + } + + pub fn build_item(self, item: P) -> F::Result { + self.build_stmt_kind(ast::StmtKind::Item(item)) + } + + pub fn item(self) -> ItemBuilder> { + let span = self.span; + ItemBuilder::with_callback(StmtItemBuilder(self)).span(span) + } + + pub fn build_mac(self, + mac: ast::Mac, + style: ast::MacStmtStyle, + attrs: Vec) -> F::Result { + let attrs = ThinVec::from(attrs); + self.build_stmt_kind(ast::StmtKind::Mac(P((mac, style, attrs)))) + } + + pub fn mac(self) -> StmtMacBuilder { + StmtMacBuilder { + builder: self, + attrs: vec![], + } + } +} + +impl Invoke> for StmtBuilder + where F: Invoke, +{ + type Result = StmtLetBuilder; + + fn invoke(self, pat: P) -> StmtLetBuilder { + StmtLetBuilder { + builder: self, + attrs: vec![], + pat: pat, + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtMacBuilder { + builder: StmtBuilder, + attrs: Vec, +} + +impl StmtMacBuilder + where F: Invoke, +{ + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn style(self, style: ast::MacStmtStyle) -> MacBuilder> { + let span = self.builder.span; + MacBuilder::with_callback(StmtMacStyleBuilder { + builder: self.builder, + style: style, + attrs: self.attrs, + }).span(span) + } +} + +impl Invoke for StmtMacBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtMacStyleBuilder { + builder: StmtBuilder, + style: ast::MacStmtStyle, + attrs: Vec, +} + +impl Invoke for StmtMacStyleBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, mac: ast::Mac) -> F::Result { + self.builder.build_mac(mac, self.style, self.attrs) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtExprBuilder(StmtBuilder); + +impl Invoke> for StmtExprBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.0.build_expr(expr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtSemiBuilder(StmtBuilder); + +impl Invoke> for StmtSemiBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.0.build_stmt_kind(ast::StmtKind::Semi(expr)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtLetBuilder { + builder: StmtBuilder, + attrs: Vec, + pat: P, +} + +impl StmtLetBuilder + where F: Invoke, +{ + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn with_attr(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } + + pub fn attr(self) -> AttrBuilder { + AttrBuilder::with_callback(self) + } + + pub fn build_option_ty(self, ty: Option>) -> StmtLetTyBuilder { + StmtLetTyBuilder { + builder: self.builder, + attrs: self.attrs, + pat: self.pat, + ty: ty, + } + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build_expr(self, init: P) -> F::Result { + self.builder.build_let(self.pat, None, Some(init), self.attrs) + } + + pub fn expr(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn build(self) -> F::Result { + self.builder.build_let(self.pat, None, None, self.attrs) + } +} + +impl Invoke for StmtLetBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, attr: ast::Attribute) -> Self { + self.with_attr(attr) + } +} + +impl Invoke> for StmtLetBuilder + where F: Invoke, +{ + type Result = StmtLetTyBuilder; + + fn invoke(self, ty: P) -> StmtLetTyBuilder { + self.build_option_ty(Some(ty)) + } +} + +impl Invoke> for StmtLetBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, expr: P) -> F::Result { + self.build_expr(expr) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtLetTyBuilder { + builder: StmtBuilder, + attrs: Vec, + pat: P, + ty: Option>, +} + +impl StmtLetTyBuilder + where F: Invoke, +{ + pub fn expr(self) -> ExprBuilder { + ExprBuilder::with_callback(self) + } + + pub fn build_option_expr(self, expr: Option>) -> F::Result { + self.builder.build_let(self.pat, self.ty, expr, self.attrs) + } + + pub fn build(self) -> F::Result { + self.build_option_expr(None) + } +} + +impl Invoke> for StmtLetTyBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, init: P) -> F::Result { + self.build_option_expr(Some(init)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct StmtItemBuilder(StmtBuilder); + +impl Invoke> for StmtItemBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, item: P) -> F::Result { + self.0.build_item(item) + } +} diff --git a/bash-5.1/vendor/aster/src/struct_field.rs b/bash-5.1/vendor/aster/src/struct_field.rs new file mode 100644 index 0000000..27cb7c4 --- /dev/null +++ b/bash-5.1/vendor/aster/src/struct_field.rs @@ -0,0 +1,115 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use attr::AttrBuilder; +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct StructFieldBuilder { + callback: F, + span: Span, + ident: Option, + vis: ast::Visibility, + attrs: Vec, +} + +impl StructFieldBuilder { + pub fn named(name: T) -> Self + where T: ToIdent, + { + StructFieldBuilder::named_with_callback(name, Identity) + } + + pub fn unnamed() -> Self { + StructFieldBuilder::unnamed_with_callback(Identity) + } +} + +impl StructFieldBuilder + where F: Invoke, +{ + pub fn named_with_callback(id: T, callback: F) -> Self + where T: ToIdent, + { + let id = id.to_ident(); + StructFieldBuilder { + callback: callback, + span: DUMMY_SP, + ident: Some(id), + vis: ast::Visibility::Inherited, + attrs: vec![], + } + } + + pub fn unnamed_with_callback(callback: F) -> Self { + StructFieldBuilder { + callback: callback, + span: DUMMY_SP, + ident: None, + vis: ast::Visibility::Inherited, + attrs: vec![], + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn pub_(mut self) -> Self { + self.vis = ast::Visibility::Public; + self + } + + pub fn with_attrs(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.attrs.extend(iter); + self + } + + pub fn attr(self) -> AttrBuilder { + let span = self.span; + AttrBuilder::with_callback(self).span(span) + } + + pub fn build_ty(self, ty: P) -> F::Result { + let field = ast::StructField { + id: ast::DUMMY_NODE_ID, + span: self.span, + ident: self.ident, + vis: self.vis, + ty: ty, + attrs: self.attrs, + }; + self.callback.invoke(field) + } + + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } +} + +impl Invoke for StructFieldBuilder { + type Result = Self; + + fn invoke(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } +} + +impl Invoke> for StructFieldBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build_ty(ty) + } +} diff --git a/bash-5.1/vendor/aster/src/symbol.rs b/bash-5.1/vendor/aster/src/symbol.rs new file mode 100644 index 0000000..01b9263 --- /dev/null +++ b/bash-5.1/vendor/aster/src/symbol.rs @@ -0,0 +1,44 @@ +use syntax::ast; +use syntax::symbol::{InternedString, Symbol}; + +////////////////////////////////////////////////////////////////////////////// + +pub trait ToSymbol { + fn to_symbol(&self) -> Symbol; +} + +impl ToSymbol for Symbol { + fn to_symbol(&self) -> Symbol { + *self + } +} + +impl<'a> ToSymbol for &'a str { + fn to_symbol(&self) -> Symbol { + Symbol::intern(self) + } +} + +impl ToSymbol for ast::Ident { + fn to_symbol(&self) -> Symbol { + self.name + } +} + +impl ToSymbol for InternedString { + fn to_symbol(&self) -> Symbol { + Symbol::intern(self) + } +} + +impl<'a, T> ToSymbol for &'a T where T: ToSymbol { + fn to_symbol(&self) -> Symbol { + (**self).to_symbol() + } +} + +impl<'a, T> ToSymbol for &'a mut T where T: ToSymbol { + fn to_symbol(&self) -> Symbol { + (**self).to_symbol() + } +} diff --git a/bash-5.1/vendor/aster/src/ty.rs b/bash-5.1/vendor/aster/src/ty.rs new file mode 100644 index 0000000..af688f2 --- /dev/null +++ b/bash-5.1/vendor/aster/src/ty.rs @@ -0,0 +1,646 @@ +use std::iter::IntoIterator; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use expr::ExprBuilder; +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use lifetime::IntoLifetime; +use path::PathBuilder; +use qpath::QPathBuilder; +use symbol::ToSymbol; +use ty_param::TyParamBoundBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyBuilder { + callback: F, + span: Span, +} + +impl TyBuilder { + pub fn new() -> Self { + TyBuilder::with_callback(Identity) + } +} + +impl TyBuilder + where F: Invoke>, +{ + pub fn with_callback(callback: F) -> Self { + TyBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn build(self, ty: P) -> F::Result { + self.callback.invoke(ty) + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn build_ty_kind(self, ty_: ast::TyKind) -> F::Result { + let span = self.span; + self.build(P(ast::Ty { + id: ast::DUMMY_NODE_ID, + node: ty_, + span: span, + })) + } + + pub fn id(self, id: I) -> F::Result + where I: ToIdent, + { + self.path().id(id).build() + } + + pub fn build_path(self, path: ast::Path) -> F::Result { + self.build_ty_kind(ast::TyKind::Path(None, path)) + } + + pub fn build_qpath(self, qself: ast::QSelf, path: ast::Path) -> F::Result { + self.build_ty_kind(ast::TyKind::Path(Some(qself), path)) + } + + pub fn path(self) -> PathBuilder> { + PathBuilder::with_callback(TyPathBuilder(self)) + } + + pub fn qpath(self) -> QPathBuilder> { + QPathBuilder::with_callback(TyQPathBuilder(self)) + } + + pub fn isize(self) -> F::Result { + self.id("isize") + } + + pub fn i8(self) -> F::Result { + self.id("i8") + } + + pub fn i16(self) -> F::Result { + self.id("i16") + } + + pub fn i32(self) -> F::Result { + self.id("i32") + } + + pub fn i64(self) -> F::Result { + self.id("i64") + } + + pub fn usize(self) -> F::Result { + self.id("usize") + } + + pub fn u8(self) -> F::Result { + self.id("u8") + } + + pub fn u16(self) -> F::Result { + self.id("u16") + } + + pub fn u32(self) -> F::Result { + self.id("u32") + } + + pub fn u64(self) -> F::Result { + self.id("u64") + } + + pub fn f32(self) -> F::Result { + self.id("f32") + } + + pub fn f64(self) -> F::Result { + self.id("f64") + } + + pub fn bool(self) -> F::Result { + self.id("bool") + } + + pub fn unit(self) -> F::Result { + self.tuple().build() + } + + pub fn tuple(self) -> TyTupleBuilder { + TyTupleBuilder { + builder: self, + tys: vec![], + } + } + + pub fn array(self, len: usize) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyArrayBuilder(self, len)).span(span) + } + + pub fn build_slice(self, ty: P) -> F::Result { + self.build_ty_kind(ast::TyKind::Slice(ty)) + } + + pub fn build_array(self, ty: P, len: usize) -> F::Result { + let len_expr = ExprBuilder::new().usize(len); + self.build_ty_kind(ast::TyKind::Array(ty, len_expr)) + } + + pub fn slice(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TySliceBuilder(self)).span(span) + } + + pub fn ref_(self) -> TyRefBuilder { + TyRefBuilder { + builder: self, + lifetime: None, + mutability: ast::Mutability::Immutable, + } + } + + pub fn never(self) -> F::Result { + self.build_ty_kind(ast::TyKind::Never) + } + + pub fn infer(self) -> F::Result { + self.build_ty_kind(ast::TyKind::Infer) + } + + pub fn option(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyOptionBuilder(self)).span(span) + } + + pub fn result(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyResultOkBuilder(self)).span(span) + } + + pub fn phantom_data(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyPhantomDataBuilder(self)).span(span) + } + + pub fn box_(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyBoxBuilder(self)).span(span) + } + + pub fn iterator(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyIteratorBuilder(self)).span(span) + } + + pub fn object_sum(self) -> TyBuilder> { + let span = self.span; + TyBuilder::with_callback(TyObjectSumBuilder { + builder: self, + }).span(span) + } + + pub fn impl_trait(self) -> TyImplTraitTyBuilder { + TyImplTraitTyBuilder { builder: self, bounds: Vec::new() } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyPathBuilder(TyBuilder); + +impl Invoke for TyPathBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, path: ast::Path) -> F::Result { + self.0.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyQPathBuilder(TyBuilder); + +impl Invoke<(ast::QSelf, ast::Path)> for TyQPathBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, (qself, path): (ast::QSelf, ast::Path)) -> F::Result { + self.0.build_qpath(qself, path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TySliceBuilder(TyBuilder); + +impl Invoke> for TySliceBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.0.build_slice(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyArrayBuilder(TyBuilder, usize); + +impl Invoke> for TyArrayBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.0.build_array(ty, self.1) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyRefBuilder { + builder: TyBuilder, + lifetime: Option, + mutability: ast::Mutability, +} + +impl TyRefBuilder + where F: Invoke>, +{ + pub fn mut_(mut self) -> Self { + self.mutability = ast::Mutability::Mutable; + self + } + + pub fn lifetime(mut self, name: N) -> Self + where N: ToSymbol, + { + self.lifetime = Some(ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: self.builder.span, + name: name.to_symbol(), + }); + self + } + + pub fn build_ty(self, ty: P) -> F::Result { + let ty = ast::MutTy { + ty: ty, + mutbl: self.mutability, + }; + self.builder.build_ty_kind(ast::TyKind::Rptr(self.lifetime, ty)) + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } +} + +impl Invoke> for TyRefBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build_ty(ty) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyOptionBuilder(TyBuilder); + +impl Invoke> for TyOptionBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let path = PathBuilder::new() + .span(self.0.span) + .global() + .id("std") + .id("option") + .segment("Option") + .with_ty(ty) + .build() + .build(); + + self.0.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyResultOkBuilder(TyBuilder); + +impl Invoke> for TyResultOkBuilder + where F: Invoke>, +{ + type Result = TyBuilder>; + + fn invoke(self, ty: P) -> TyBuilder> { + let span = self.0.span; + TyBuilder::with_callback(TyResultErrBuilder(self.0, ty)).span(span) + } +} + +pub struct TyResultErrBuilder(TyBuilder, P); + +impl Invoke> for TyResultErrBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let path = PathBuilder::new() + .span(self.0.span) + .global() + .id("std") + .id("result") + .segment("Result") + .with_ty(self.1) + .with_ty(ty) + .build() + .build(); + + self.0.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyPhantomDataBuilder(TyBuilder); + +impl Invoke> for TyPhantomDataBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let path = PathBuilder::new() + .span(self.0.span) + .global() + .id("std") + .id("marker") + .segment("PhantomData") + .with_ty(ty) + .build() + .build(); + + self.0.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyBoxBuilder(TyBuilder); + +impl Invoke> for TyBoxBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let path = PathBuilder::new() + .span(self.0.span) + .global() + .id("std") + .id("boxed") + .segment("Box") + .with_ty(ty) + .build() + .build(); + + self.0.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyIteratorBuilder(TyBuilder); + +impl Invoke> for TyIteratorBuilder + where F: Invoke>, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + let path = PathBuilder::new() + .span(self.0.span) + .global() + .id("std") + .id("iter") + .segment("Iterator") + .binding("Item").build(ty.clone()) + .build() + .build(); + + self.0.build_path(path) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyObjectSumBuilder { + builder: TyBuilder, +} + +impl Invoke> for TyObjectSumBuilder + where F: Invoke>, +{ + type Result = TyObjectSumTyBuilder; + + fn invoke(self, ty: P) -> Self::Result { + TyObjectSumTyBuilder { + builder: self.builder, + ty: ty, + bounds: Vec::new(), + } + } +} + +pub struct TyObjectSumTyBuilder { + builder: TyBuilder, + ty: P, + bounds: Vec, +} + +impl TyObjectSumTyBuilder + where F: Invoke>, +{ + pub fn with_bounds(mut self, iter: I) -> Self + where I: Iterator, + { + self.bounds.extend(iter); + self + } + + pub fn with_bound(mut self, bound: ast::TyParamBound) -> Self { + self.bounds.push(bound); + self + } + + pub fn bound(self) -> TyParamBoundBuilder { + TyParamBoundBuilder::with_callback(self) + } + + pub fn with_generics(self, generics: ast::Generics) -> Self { + self.with_lifetimes( + generics.lifetimes.into_iter() + .map(|def| def.lifetime) + ) + } + + pub fn with_lifetimes(mut self, lifetimes: I) -> Self + where I: Iterator, + L: IntoLifetime, + { + for lifetime in lifetimes { + self = self.lifetime(lifetime); + } + + self + } + + pub fn lifetime(self, lifetime: L) -> Self + where L: IntoLifetime, + { + self.bound().lifetime(lifetime) + } + + pub fn build(self) -> F::Result { + let bounds = P::from_vec(self.bounds); + self.builder.build_ty_kind(ast::TyKind::ObjectSum(self.ty, bounds)) + } +} + +impl Invoke for TyObjectSumTyBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, bound: ast::TyParamBound) -> Self { + self.with_bound(bound) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyImplTraitTyBuilder { + builder: TyBuilder, + bounds: Vec, +} + +impl TyImplTraitTyBuilder + where F: Invoke>, +{ + pub fn with_bounds(mut self, iter: I) -> Self + where I: Iterator, + { + self.bounds.extend(iter); + self + } + + pub fn with_bound(mut self, bound: ast::TyParamBound) -> Self { + self.bounds.push(bound); + self + } + + pub fn bound(self) -> TyParamBoundBuilder { + TyParamBoundBuilder::with_callback(self) + } + + pub fn with_generics(self, generics: ast::Generics) -> Self { + self.with_lifetimes( + generics.lifetimes.into_iter() + .map(|def| def.lifetime) + ) + } + + pub fn with_lifetimes(mut self, lifetimes: I) -> Self + where I: Iterator, + L: IntoLifetime, + { + for lifetime in lifetimes { + self = self.lifetime(lifetime); + } + + self + } + + pub fn lifetime(self, lifetime: L) -> Self + where L: IntoLifetime, + { + self.bound().lifetime(lifetime) + } + + pub fn build(self) -> F::Result { + let bounds = P::from_vec(self.bounds); + self.builder.build_ty_kind(ast::TyKind::ImplTrait(bounds)) + } +} + +impl Invoke for TyImplTraitTyBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, bound: ast::TyParamBound) -> Self { + self.with_bound(bound) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyTupleBuilder { + builder: TyBuilder, + tys: Vec>, +} + +impl TyTupleBuilder + where F: Invoke>, +{ + pub fn with_tys(mut self, iter: I) -> Self + where I: IntoIterator>, + { + self.tys.extend(iter); + self + } + + pub fn with_ty(mut self, ty: P) -> Self { + self.tys.push(ty); + self + } + + pub fn ty(self) -> TyBuilder { + let span = self.builder.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.builder.build_ty_kind(ast::TyKind::Tup(self.tys)) + } +} + +impl Invoke> for TyTupleBuilder + where F: Invoke>, +{ + type Result = Self; + + fn invoke(self, ty: P) -> Self { + self.with_ty(ty) + } +} diff --git a/bash-5.1/vendor/aster/src/ty_param.rs b/bash-5.1/vendor/aster/src/ty_param.rs new file mode 100644 index 0000000..74290d3 --- /dev/null +++ b/bash-5.1/vendor/aster/src/ty_param.rs @@ -0,0 +1,304 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use lifetime::{IntoLifetime, IntoLifetimeDef, LifetimeDefBuilder}; +use path::{IntoPath, PathBuilder}; +use symbol::ToSymbol; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyParamBuilder { + callback: F, + span: Span, + id: ast::Ident, + bounds: Vec, + default: Option>, +} + +impl TyParamBuilder { + pub fn new(id: I) -> Self + where I: ToIdent, + { + TyParamBuilder::with_callback(id, Identity) + } + + pub fn from_ty_param(ty_param: ast::TyParam) -> Self { + TyParamBuilder::from_ty_param_with_callback(Identity, ty_param) + } +} + +impl TyParamBuilder + where F: Invoke, +{ + pub fn with_callback(id: I, callback: F) -> Self + where I: ToIdent + { + TyParamBuilder { + callback: callback, + span: DUMMY_SP, + id: id.to_ident(), + bounds: Vec::new(), + default: None, + } + } + + pub fn from_ty_param_with_callback(callback: F, ty_param: ast::TyParam) -> Self { + TyParamBuilder { + callback: callback, + span: ty_param.span, + id: ty_param.ident, + bounds: ty_param.bounds.into_vec(), + default: ty_param.default, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_default(mut self, ty: P) -> Self { + self.default = Some(ty); + self + } + + pub fn default(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn with_bound(mut self, bound: ast::TyParamBound) -> Self { + self.bounds.push(bound); + self + } + + pub fn bound(self) -> TyParamBoundBuilder { + TyParamBoundBuilder::with_callback(self) + } + + pub fn with_trait_bound(self, trait_ref: ast::PolyTraitRef) -> Self { + self.bound().build_trait(trait_ref, ast::TraitBoundModifier::None) + } + + pub fn trait_bound

(self, path: P) -> PolyTraitRefBuilder + where P: IntoPath, + { + PolyTraitRefBuilder::with_callback(path, self) + } + + pub fn lifetime_bound(mut self, lifetime: L) -> Self + where L: IntoLifetime, + { + let lifetime = lifetime.into_lifetime(); + + self.bounds.push(ast::TyParamBound::RegionTyParamBound(lifetime)); + self + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::TyParam { + attrs: ast::ThinVec::new(), + ident: self.id, + id: ast::DUMMY_NODE_ID, + bounds: P::from_vec(self.bounds), + default: self.default, + span: self.span, + }) + } +} + +impl Invoke> for TyParamBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, ty: P) -> Self { + self.with_default(ty) + } +} + +impl Invoke for TyParamBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, bound: ast::TyParamBound) -> Self { + self.with_bound(bound) + } +} + +impl Invoke for TyParamBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, trait_ref: ast::PolyTraitRef) -> Self { + self.with_trait_bound(trait_ref) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TyParamBoundBuilder { + callback: F, + span: Span, +} + +impl TyParamBoundBuilder { + pub fn new() -> Self { + TyParamBoundBuilder::with_callback(Identity) + } +} + +impl TyParamBoundBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + TyParamBoundBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn build_trait(self, + poly_trait: ast::PolyTraitRef, + modifier: ast::TraitBoundModifier) -> F::Result { + let bound = ast::TyParamBound::TraitTyParamBound(poly_trait, modifier); + self.callback.invoke(bound) + } + + pub fn trait_

(self, path: P) -> PolyTraitRefBuilder> + where P: IntoPath, + { + let span = self.span; + let builder = TraitTyParamBoundBuilder { + builder: self, + modifier: ast::TraitBoundModifier::None, + }; + + PolyTraitRefBuilder::with_callback(path, builder).span(span) + } + + pub fn maybe_trait

(self, path: P) -> PolyTraitRefBuilder> + where P: IntoPath, + { + let span = self.span; + let builder = TraitTyParamBoundBuilder { + builder: self, + modifier: ast::TraitBoundModifier::Maybe, + }; + + PolyTraitRefBuilder::with_callback(path, builder).span(span) + } + + pub fn iterator(self, ty: P) -> PolyTraitRefBuilder> { + let path = PathBuilder::new() + .span(self.span) + .global() + .id("std") + .id("iter") + .segment("Iterator") + .binding("Item").build(ty) + .build() + .build(); + self.trait_(path) + } + + pub fn lifetime(self, lifetime: L) -> F::Result + where L: IntoLifetime, + { + let lifetime = lifetime.into_lifetime(); + self.callback.invoke(ast::TyParamBound::RegionTyParamBound(lifetime)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct TraitTyParamBoundBuilder { + builder: TyParamBoundBuilder, + modifier: ast::TraitBoundModifier, +} + +impl Invoke for TraitTyParamBoundBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, poly_trait: ast::PolyTraitRef) -> Self::Result { + self.builder.build_trait(poly_trait, self.modifier) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct PolyTraitRefBuilder { + callback: F, + span: Span, + trait_ref: ast::TraitRef, + lifetimes: Vec, +} + +impl PolyTraitRefBuilder + where F: Invoke, +{ + pub fn with_callback

(path: P, callback: F) -> Self + where P: IntoPath, + { + let trait_ref = ast::TraitRef { + path: path.into_path(), + ref_id: ast::DUMMY_NODE_ID, + }; + + PolyTraitRefBuilder { + callback: callback, + span: DUMMY_SP, + trait_ref: trait_ref, + lifetimes: Vec::new(), + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn with_lifetime(mut self, lifetime: L) -> Self + where L: IntoLifetimeDef, + { + self.lifetimes.push(lifetime.into_lifetime_def()); + self + } + + pub fn lifetime(self, name: N) -> LifetimeDefBuilder + where N: ToSymbol, + { + LifetimeDefBuilder::with_callback(name, self) + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::PolyTraitRef { + bound_lifetimes: self.lifetimes, + trait_ref: self.trait_ref, + span: self.span, + }) + } +} + +impl Invoke for PolyTraitRefBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, lifetime: ast::LifetimeDef) -> Self { + self.with_lifetime(lifetime) + } +} diff --git a/bash-5.1/vendor/aster/src/variant.rs b/bash-5.1/vendor/aster/src/variant.rs new file mode 100644 index 0000000..d297f02 --- /dev/null +++ b/bash-5.1/vendor/aster/src/variant.rs @@ -0,0 +1,107 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span, respan}; + +use attr::AttrBuilder; +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use struct_field::StructFieldBuilder; +use variant_data::{ + VariantDataBuilder, + VariantDataStructBuilder, + VariantDataTupleBuilder, +}; + +////////////////////////////////////////////////////////////////////////////// + +pub struct VariantBuilder { + callback: F, + span: Span, + attrs: Vec, + id: ast::Ident, +} + +impl VariantBuilder { + pub fn new(id: T) -> Self + where T: ToIdent, + { + VariantBuilder::with_callback(id, Identity) + } +} + +impl VariantBuilder + where F: Invoke, +{ + pub fn with_callback(id: T, callback: F) -> Self + where T: ToIdent, + { + VariantBuilder { + callback: callback, + span: DUMMY_SP, + attrs: vec![], + id: id.to_ident(), + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn attr(self) -> AttrBuilder { + let span = self.span; + AttrBuilder::with_callback(self).span(span) + } + + pub fn unit(self) -> F::Result { + VariantDataBuilder::with_callback(self).unit() + } + + pub fn tuple(self) -> StructFieldBuilder> { + VariantDataBuilder::with_callback(self).tuple() + } + + pub fn struct_(self) -> VariantDataStructBuilder { + VariantDataBuilder::with_callback(self).struct_() + } + + pub fn build_variant_data(self, data: ast::VariantData) -> F::Result { + let variant_ = ast::Variant_ { + name: self.id, + attrs: self.attrs, + data: data, + disr_expr: None, + }; + let variant = respan(self.span, variant_); + self.callback.invoke(variant) + } + + pub fn build_variant_(self, variant: ast::Variant_) -> F::Result { + let variant = respan(self.span, variant); + self.build(variant) + } + + pub fn build(self, variant: ast::Variant) -> F::Result { + self.callback.invoke(variant) + } +} + +impl Invoke for VariantBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(mut self, attr: ast::Attribute) -> Self { + self.attrs.push(attr); + self + } +} + +impl Invoke for VariantBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, data: ast::VariantData) -> F::Result { + self.build_variant_data(data) + } +} diff --git a/bash-5.1/vendor/aster/src/variant_data.rs b/bash-5.1/vendor/aster/src/variant_data.rs new file mode 100644 index 0000000..c5f7b8c --- /dev/null +++ b/bash-5.1/vendor/aster/src/variant_data.rs @@ -0,0 +1,166 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use ident::ToIdent; +use invoke::{Invoke, Identity}; +use struct_field::StructFieldBuilder; +use ty::TyBuilder; + +////////////////////////////////////////////////////////////////////////////// + +pub struct VariantDataBuilder { + callback: F, + span: Span, +} + +impl VariantDataBuilder { + pub fn new() -> Self { + VariantDataBuilder::with_callback(Identity) + } +} + +impl VariantDataBuilder + where F: Invoke +{ + pub fn with_callback(callback: F) -> Self { + VariantDataBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn tuple(self) -> StructFieldBuilder> { + // tuple variants with no arguments are illegal, so force the user to define at least one + // field. + let builder = VariantDataTupleBuilder { + callback: self.callback, + span: self.span, + fields: Vec::new(), + }; + + builder.field() + } + + pub fn struct_(self) -> VariantDataStructBuilder { + VariantDataStructBuilder { + callback: self.callback, + span: self.span, + fields: Vec::new(), + } + } + + pub fn unit(self) -> F::Result { + self.callback.invoke(ast::VariantData::Unit(ast::DUMMY_NODE_ID)) + } +} + +pub struct VariantDataTupleBuilder { + callback: F, + span: Span, + fields: Vec, +} + +impl VariantDataTupleBuilder + where F: Invoke +{ + pub fn with_fields(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.fields.extend(iter); + self + } + + pub fn with_field(mut self, field: ast::StructField) -> Self { + self.fields.push(field); + self + } + + pub fn field(self) -> StructFieldBuilder { + let span = self.span; + StructFieldBuilder::unnamed_with_callback(self).span(span) + } + + pub fn with_ty(self, ty: P) -> Self { + self.field().build_ty(ty) + } + + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::VariantData::Tuple(self.fields, ast::DUMMY_NODE_ID)) + } +} + +impl Invoke> for VariantDataTupleBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, ty: P) -> Self { + self.with_ty(ty) + } +} + +impl Invoke for VariantDataTupleBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, field: ast::StructField) -> Self { + self.with_field(field) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct VariantDataStructBuilder { + callback: F, + span: Span, + fields: Vec, +} + +impl VariantDataStructBuilder + where F: Invoke, +{ + pub fn with_fields(mut self, iter: I) -> Self + where I: IntoIterator, + { + self.fields.extend(iter); + self + } + + pub fn with_field(mut self, field: ast::StructField) -> Self { + self.fields.push(field); + self + } + + pub fn field(self, id: T) -> StructFieldBuilder + where T: ToIdent, + { + let span = self.span; + StructFieldBuilder::named_with_callback(id, self).span(span) + } + + pub fn build(self) -> F::Result { + self.callback.invoke(ast::VariantData::Struct(self.fields, ast::DUMMY_NODE_ID)) + } +} + +impl Invoke for VariantDataStructBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, field: ast::StructField) -> Self { + self.with_field(field) + } +} diff --git a/bash-5.1/vendor/aster/src/where_predicate.rs b/bash-5.1/vendor/aster/src/where_predicate.rs new file mode 100644 index 0000000..e7bcf1e --- /dev/null +++ b/bash-5.1/vendor/aster/src/where_predicate.rs @@ -0,0 +1,338 @@ +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ptr::P; + +use invoke::{Invoke, Identity}; +use lifetime::{IntoLifetime, IntoLifetimeDef, LifetimeDefBuilder}; +use path::IntoPath; +use symbol::ToSymbol; +use ty::TyBuilder; +use ty_param::{TyParamBoundBuilder, PolyTraitRefBuilder, TraitTyParamBoundBuilder}; + +////////////////////////////////////////////////////////////////////////////// + +pub struct WherePredicateBuilder { + callback: F, + span: Span, +} + +impl WherePredicateBuilder { + pub fn new() -> Self { + WherePredicateBuilder::with_callback(Identity) + } +} + +impl WherePredicateBuilder + where F: Invoke, +{ + pub fn with_callback(callback: F) -> Self { + WherePredicateBuilder { + callback: callback, + span: DUMMY_SP, + } + } + + pub fn span(mut self, span: Span) -> Self { + self.span = span; + self + } + + pub fn bound(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn lifetime(self, lifetime: L) -> WhereRegionPredicateBuilder + where L: IntoLifetime, + { + WhereRegionPredicateBuilder { + callback: self.callback, + span: self.span, + lifetime: lifetime.into_lifetime(), + bounds: Vec::new(), + } + } + + pub fn eq

(self, path: P) -> WhereEqPredicateBuilder + where P: IntoPath, + { + WhereEqPredicateBuilder { + callback: self.callback, + span: self.span, + path: path.into_path(), + } + } +} + +impl Invoke> for WherePredicateBuilder + where F: Invoke, +{ + type Result = WhereBoundPredicateTyBuilder; + + fn invoke(self, ty: P) -> Self::Result { + WhereBoundPredicateTyBuilder { + callback: self.callback, + span: self.span, + ty: ty, + bound_lifetimes: Vec::new(), + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct WhereBoundPredicateBuilder { + callback: F, + span: Span, +} + +impl Invoke> for WhereBoundPredicateBuilder + where F: Invoke, +{ + type Result = WhereBoundPredicateTyBuilder; + + fn invoke(self, ty: P) -> Self::Result { + WhereBoundPredicateTyBuilder { + callback: self.callback, + span: self.span, + ty: ty, + bound_lifetimes: Vec::new(), + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct WhereBoundPredicateTyBuilder { + callback: F, + span: Span, + ty: P, + bound_lifetimes: Vec, +} + +impl WhereBoundPredicateTyBuilder + where F: Invoke, +{ + pub fn with_for_lifetime(mut self, lifetime: L) -> Self + where L: IntoLifetimeDef, + { + self.bound_lifetimes.push(lifetime.into_lifetime_def()); + self + } + + pub fn for_lifetime(self, name: N) -> LifetimeDefBuilder + where N: ToSymbol, + { + LifetimeDefBuilder::with_callback(name, self) + } + + pub fn with_bound(self, bound: ast::TyParamBound) -> WhereBoundPredicateTyBoundsBuilder { + WhereBoundPredicateTyBoundsBuilder { + callback: self.callback, + span: self.span, + ty: self.ty, + bound_lifetimes: self.bound_lifetimes, + bounds: vec![bound], + } + } + + pub fn bound(self) -> TyParamBoundBuilder> { + let span = self.span; + let builder = WhereBoundPredicateTyBoundsBuilder { + callback: self.callback, + span: self.span, + ty: self.ty, + bound_lifetimes: self.bound_lifetimes, + bounds: vec![], + }; + TyParamBoundBuilder::with_callback(builder).span(span) + } + + pub fn trait_

(self, path: P) + -> PolyTraitRefBuilder< + TraitTyParamBoundBuilder< + WhereBoundPredicateTyBoundsBuilder + > + > + where P: IntoPath, + { + self.bound().trait_(path) + } + + pub fn lifetime(self, lifetime: L) -> WhereBoundPredicateTyBoundsBuilder + where L: IntoLifetime, + { + self.bound().lifetime(lifetime) + } +} + +impl Invoke for WhereBoundPredicateTyBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, lifetime: ast::LifetimeDef) -> Self { + self.with_for_lifetime(lifetime) + } +} + +impl Invoke for WhereBoundPredicateTyBuilder + where F: Invoke, +{ + type Result = WhereBoundPredicateTyBoundsBuilder; + + fn invoke(self, bound: ast::TyParamBound) -> Self::Result { + self.with_bound(bound) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct WhereBoundPredicateTyBoundsBuilder { + callback: F, + span: Span, + ty: P, + bound_lifetimes: Vec, + bounds: Vec, +} + +impl WhereBoundPredicateTyBoundsBuilder + where F: Invoke, +{ + pub fn with_for_lifetime(mut self, lifetime: L) -> Self + where L: IntoLifetimeDef, + { + self.bound_lifetimes.push(lifetime.into_lifetime_def()); + self + } + + pub fn for_lifetime(self, name: N) -> LifetimeDefBuilder + where N: ToSymbol, + { + LifetimeDefBuilder::with_callback(name, self) + } + + pub fn with_bound(mut self, bound: ast::TyParamBound) -> Self { + self.bounds.push(bound); + self + } + + pub fn bound(self) -> TyParamBoundBuilder { + let span = self.span; + TyParamBoundBuilder::with_callback(self).span(span) + } + + pub fn trait_

(self, path: P) + -> PolyTraitRefBuilder> + where P: IntoPath, + { + self.bound().trait_(path) + } + + pub fn lifetime(self, lifetime: L) -> Self + where L: IntoLifetime, + { + self.bound().lifetime(lifetime) + } + + pub fn build(self) -> F::Result { + let predicate = ast::WhereBoundPredicate { + span: self.span, + bound_lifetimes: self.bound_lifetimes, + bounded_ty: self.ty, + bounds: P::from_vec(self.bounds), + }; + + self.callback.invoke(ast::WherePredicate::BoundPredicate(predicate)) + } +} + +impl Invoke for WhereBoundPredicateTyBoundsBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, lifetime: ast::LifetimeDef) -> Self { + self.with_for_lifetime(lifetime) + } +} + +impl Invoke for WhereBoundPredicateTyBoundsBuilder + where F: Invoke, +{ + type Result = Self; + + fn invoke(self, bound: ast::TyParamBound) -> Self { + self.with_bound(bound) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct WhereRegionPredicateBuilder { + callback: F, + span: Span, + lifetime: ast::Lifetime, + bounds: Vec, +} + +impl WhereRegionPredicateBuilder + where F: Invoke, +{ + pub fn bound(mut self, lifetime: L) -> Self + where L: IntoLifetime, + { + self.bounds.push(lifetime.into_lifetime()); + self + } + + pub fn build(self) -> F::Result { + let predicate = ast::WhereRegionPredicate { + span: self.span, + lifetime: self.lifetime, + bounds: self.bounds, + }; + + self.callback.invoke(ast::WherePredicate::RegionPredicate(predicate)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +pub struct WhereEqPredicateBuilder { + callback: F, + span: Span, + path: ast::Path, +} + +impl WhereEqPredicateBuilder + where F: Invoke, +{ + pub fn ty(self) -> TyBuilder { + let span = self.span; + TyBuilder::with_callback(self).span(span) + } + + pub fn build_ty(self, ty: P) -> F::Result { + let WhereEqPredicateBuilder { callback, span, path } = self; + + let predicate = ast::WhereEqPredicate { + id: ast::DUMMY_NODE_ID, + span: span, + path: path, + ty: ty, + }; + + callback.invoke(ast::WherePredicate::EqPredicate(predicate)) + } +} + +impl Invoke> for WhereEqPredicateBuilder + where F: Invoke, +{ + type Result = F::Result; + + fn invoke(self, ty: P) -> F::Result { + self.build_ty(ty) + } +} diff --git a/bash-5.1/vendor/async-trait/src/bound.rs b/bash-5.1/vendor/async-trait/src/bound.rs new file mode 100644 index 0000000..50182f6 --- /dev/null +++ b/bash-5.1/vendor/async-trait/src/bound.rs @@ -0,0 +1,48 @@ +use proc_macro2::{Ident, Span, TokenStream}; +use quote::quote_spanned; +use syn::punctuated::Punctuated; +use syn::{Token, TypeParamBound}; + +pub type Supertraits = Punctuated; + +pub enum InferredBound { + Send, + Sync, +} + +pub fn has_bound(supertraits: &Supertraits, bound: &InferredBound) -> bool { + for supertrait in supertraits { + if let TypeParamBound::Trait(supertrait) = supertrait { + if supertrait.path.is_ident(bound) + || supertrait.path.segments.len() == 3 + && (supertrait.path.segments[0].ident == "std" + || supertrait.path.segments[0].ident == "core") + && supertrait.path.segments[1].ident == "marker" + && supertrait.path.segments[2].ident == *bound + { + return true; + } + } + } + false +} + +impl InferredBound { + fn as_str(&self) -> &str { + match self { + InferredBound::Send => "Send", + InferredBound::Sync => "Sync", + } + } + + pub fn spanned_path(&self, span: Span) -> TokenStream { + let ident = Ident::new(self.as_str(), span); + quote_spanned!(span=> ::core::marker::#ident) + } +} + +impl PartialEq for Ident { + fn eq(&self, bound: &InferredBound) -> bool { + self == bound.as_str() + } +} diff --git a/bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.rs b/bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.rs new file mode 100644 index 0000000..237cf66 --- /dev/null +++ b/bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.rs @@ -0,0 +1,23 @@ +use async_trait::async_trait; + +#[async_trait] +trait Foo { + async fn bar(&self, x: &str, y: &'_ str) -> &'static str; +} + +struct S(String); + +#[async_trait] +impl Foo for S { + async fn bar(&self, x: &str, y: &'_ str) -> &'static str { + if false { + &self.0 + } else if false { + x + } else { + y + } + } +} + +fn main() {} diff --git a/bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.stderr b/bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.stderr new file mode 100644 index 0000000..9ffef5b --- /dev/null +++ b/bash-5.1/vendor/async-trait/tests/ui/lifetime-defined-here.stderr @@ -0,0 +1,29 @@ +error: lifetime may not live long enough + --> tests/ui/lifetime-defined-here.rs:12:49 + | +12 | async fn bar(&self, x: &str, y: &'_ str) -> &'static str { + | - ^^^^^^^^^^^^ type annotation requires that `'life0` must outlive `'static` + | | + | lifetime `'life0` defined here + +error: lifetime may not live long enough + --> tests/ui/lifetime-defined-here.rs:12:49 + | +12 | async fn bar(&self, x: &str, y: &'_ str) -> &'static str { + | - ^^^^^^^^^^^^ type annotation requires that `'life1` must outlive `'static` + | | + | lifetime `'life1` defined here + +error: lifetime may not live long enough + --> tests/ui/lifetime-defined-here.rs:12:49 + | +12 | async fn bar(&self, x: &str, y: &'_ str) -> &'static str { + | -- ^^^^^^^^^^^^ type annotation requires that `'life2` must outlive `'static` + | | + | lifetime `'life2` defined here + +help: the following changes may resolve your lifetime errors + | + = help: replace `'life0` with `'static` + = help: replace `'life1` with `'static` + = help: replace `'life2` with `'static` diff --git a/bash-5.1/vendor/atty/.cargo-checksum.json b/bash-5.1/vendor/atty/.cargo-checksum.json new file mode 100644 index 0000000..a68b85b --- /dev/null +++ b/bash-5.1/vendor/atty/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"70db121262d72acc472ad1a90b78c42de570820e65b566c6b9339b62e636d572","Cargo.lock":"6868f02a96413bcba37a06f01c6bf87e6331dea9461681a47a561cec6acd2546","Cargo.toml":"3af88a07af6a4adb84373fc3cd4920884b0b12b338cdb55ef598fd512ee1a790","LICENSE":"99fa95ba4e4cdaf71c27d73260ea069fc4515b3d02fde3020c5b562280006cbc","README.md":"e559a69c0b2bd20bffcede64fd548df6c671b0d1504613c5e3e5d884d759caea","examples/atty.rs":"1551387a71474d9ac1b5153231f884e9e05213badcfaa3494ad2cb7ea958374a","rustfmt.toml":"8e6ea1bcb79c505490034020c98e9b472f4ac4113f245bae90f5e1217b1ec65a","src/lib.rs":"d5abf6a54e8c496c486572bdc91eef10480f6ad126c4287f039df5feff7a9bbb"},"package":"d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"} \ No newline at end of file diff --git a/bash-5.1/vendor/atty/CHANGELOG.md b/bash-5.1/vendor/atty/CHANGELOG.md new file mode 100644 index 0000000..4e9673f --- /dev/null +++ b/bash-5.1/vendor/atty/CHANGELOG.md @@ -0,0 +1,73 @@ +# 0.2.14 + +* add support for [RustyHermit](https://github.com/hermitcore/libhermit-rs), a Rust-based unikernel [#41](https://github.com/softprops/atty/pull/41) + +# 0.2.13 + +* support older versions of rust that do now support 2018 edition + +# 0.2.12 + +* Redox is now in the unix family so redox cfg is no longer needed [#35](https://github.com/softprops/atty/pull/35) + +# 0.2.11 + +* fix msys detection with `winapi@0.3.5` [#28](https://github.com/softprops/atty/pull/28) + +# 0.2.10 + +* fix wasm regression [#27](https://github.com/softprops/atty/pull/27) + +# 0.2.9 + +* Fix fix pty detection [#25](https://github.com/softprops/atty/pull/25) + +# 0.2.8 + +* Fix an inverted condition on MinGW [#22](https://github.com/softprops/atty/pull/22) + +# 0.2.7 + +* Change `||` to `&&` for whether MSYS is a tty [#24](https://github.com/softprops/atty/pull/24/) + +# 0.2.6 + +* updated winapi dependency to [0.3](https://retep998.github.io/blog/winapi-0.3/) [#18](https://github.com/softprops/atty/pull/18) + +# 0.2.5 + +* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17) + +# 0.2.4 + +* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17) + +# 0.2.3 + +* added support for Redox OS [#14](https://github.com/softprops/atty/pull/14) + +# 0.2.2 + +* use target specific dependencies [#11](https://github.com/softprops/atty/pull/11) +* Add tty detection for MSYS terminals [#12](https://github.com/softprops/atty/pull/12) + +# 0.2.1 + +* fix windows bug + +# 0.2.0 + +* support for various stream types + +# 0.1.2 + +* windows support (with automated testing) +* automated code coverage + +# 0.1.1 + +* bumped libc dep from `0.1` to `0.2` + +# 0.1.0 + +* initial release diff --git a/bash-5.1/vendor/atty/Cargo.toml b/bash-5.1/vendor/atty/Cargo.toml new file mode 100644 index 0000000..d6bf2d0 --- /dev/null +++ b/bash-5.1/vendor/atty/Cargo.toml @@ -0,0 +1,34 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "atty" +version = "0.2.14" +authors = ["softprops "] +exclude = ["/.travis.yml", "/appveyor.yml"] +description = "A simple interface for querying atty" +homepage = "https://github.com/softprops/atty" +documentation = "http://softprops.github.io/atty" +readme = "README.md" +keywords = ["terminal", "tty", "isatty"] +license = "MIT" +repository = "https://github.com/softprops/atty" +[target."cfg(target_os = \"hermit\")".dependencies.hermit-abi] +version = "0.1.6" +[target."cfg(unix)".dependencies.libc] +version = "0.2" +default-features = false +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["consoleapi", "processenv", "minwinbase", "minwindef", "winbase"] +[badges.travis-ci] +repository = "softprops/atty" diff --git a/bash-5.1/vendor/atty/LICENSE b/bash-5.1/vendor/atty/LICENSE new file mode 100644 index 0000000..b9da76b --- /dev/null +++ b/bash-5.1/vendor/atty/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2015-2019 Doug Tangren + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/atty/README.md b/bash-5.1/vendor/atty/README.md new file mode 100644 index 0000000..cd85593 --- /dev/null +++ b/bash-5.1/vendor/atty/README.md @@ -0,0 +1,74 @@ +# atty + +[![Build Status](https://travis-ci.org/softprops/atty.svg?branch=master)](https://travis-ci.org/softprops/atty) [![Build status](https://ci.appveyor.com/api/projects/status/geggrsnsjsuse8cv?svg=true)](https://ci.appveyor.com/project/softprops/atty) [![Coverage Status](https://coveralls.io/repos/softprops/atty/badge.svg?branch=master&service=github)](https://coveralls.io/github/softprops/atty?branch=master) [![crates.io](https://img.shields.io/crates/v/atty.svg)](https://crates.io/crates/atty) [![Released API docs](https://docs.rs/atty/badge.svg)](http://docs.rs/atty) [![Master API docs](https://img.shields.io/badge/docs-master-green.svg)](https://softprops.github.io/atty) + +> are you or are you not a tty? + + +## install + +Add the following to your `Cargo.toml` + +```toml +[dependencies] +atty = "0.2" +``` + +## usage + +```rust +use atty::Stream; + +fn main() { + if atty::is(Stream::Stdout) { + println!("I'm a terminal"); + } else { + println!("I'm not"); + } +} +``` + +## testing + +This library has been unit tested on both unix and windows platforms (via appveyor). + + +A simple example program is provided in this repo to test various tty's. By default. + +It prints + +```bash +$ cargo run --example atty +stdout? true +stderr? true +stdin? true +``` + +To test std in, pipe some text to the program + +```bash +$ echo "test" | cargo run --example atty +stdout? true +stderr? true +stdin? false +``` + +To test std out, pipe the program to something + +```bash +$ cargo run --example atty | grep std +stdout? false +stderr? true +stdin? true +``` + +To test std err, pipe the program to something redirecting std err + +```bash +$ cargo run --example atty 2>&1 | grep std +stdout? false +stderr? false +stdin? true +``` + +Doug Tangren (softprops) 2015-2019 diff --git a/bash-5.1/vendor/atty/examples/atty.rs b/bash-5.1/vendor/atty/examples/atty.rs new file mode 100644 index 0000000..3b3635e --- /dev/null +++ b/bash-5.1/vendor/atty/examples/atty.rs @@ -0,0 +1,9 @@ +extern crate atty; + +use atty::{is, Stream}; + +fn main() { + println!("stdout? {}", is(Stream::Stdout)); + println!("stderr? {}", is(Stream::Stderr)); + println!("stdin? {}", is(Stream::Stdin)); +} diff --git a/bash-5.1/vendor/atty/rustfmt.toml b/bash-5.1/vendor/atty/rustfmt.toml new file mode 100644 index 0000000..899a094 --- /dev/null +++ b/bash-5.1/vendor/atty/rustfmt.toml @@ -0,0 +1,4 @@ +# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#fn_args_layout +fn_args_layout = "Vertical" +# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#merge_imports +merge_imports = true \ No newline at end of file diff --git a/bash-5.1/vendor/atty/src/lib.rs b/bash-5.1/vendor/atty/src/lib.rs new file mode 100644 index 0000000..501cad6 --- /dev/null +++ b/bash-5.1/vendor/atty/src/lib.rs @@ -0,0 +1,210 @@ +//! atty is a simple utility that answers one question +//! > is this a tty? +//! +//! usage is just as simple +//! +//! ``` +//! if atty::is(atty::Stream::Stdout) { +//! println!("i'm a tty") +//! } +//! ``` +//! +//! ``` +//! if atty::isnt(atty::Stream::Stdout) { +//! println!("i'm not a tty") +//! } +//! ``` + +#![cfg_attr(unix, no_std)] + +#[cfg(unix)] +extern crate libc; +#[cfg(windows)] +extern crate winapi; + +#[cfg(windows)] +use winapi::shared::minwindef::DWORD; +#[cfg(windows)] +use winapi::shared::ntdef::WCHAR; + +/// possible stream sources +#[derive(Clone, Copy, Debug)] +pub enum Stream { + Stdout, + Stderr, + Stdin, +} + +/// returns true if this is a tty +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub fn is(stream: Stream) -> bool { + extern crate libc; + + let fd = match stream { + Stream::Stdout => libc::STDOUT_FILENO, + Stream::Stderr => libc::STDERR_FILENO, + Stream::Stdin => libc::STDIN_FILENO, + }; + unsafe { libc::isatty(fd) != 0 } +} + +/// returns true if this is a tty +#[cfg(target_os = "hermit")] +pub fn is(stream: Stream) -> bool { + extern crate hermit_abi; + + let fd = match stream { + Stream::Stdout => hermit_abi::STDOUT_FILENO, + Stream::Stderr => hermit_abi::STDERR_FILENO, + Stream::Stdin => hermit_abi::STDIN_FILENO, + }; + hermit_abi::isatty(fd) +} + +/// returns true if this is a tty +#[cfg(windows)] +pub fn is(stream: Stream) -> bool { + use winapi::um::winbase::{ + STD_ERROR_HANDLE as STD_ERROR, STD_INPUT_HANDLE as STD_INPUT, + STD_OUTPUT_HANDLE as STD_OUTPUT, + }; + + let (fd, others) = match stream { + Stream::Stdin => (STD_INPUT, [STD_ERROR, STD_OUTPUT]), + Stream::Stderr => (STD_ERROR, [STD_INPUT, STD_OUTPUT]), + Stream::Stdout => (STD_OUTPUT, [STD_INPUT, STD_ERROR]), + }; + if unsafe { console_on_any(&[fd]) } { + // False positives aren't possible. If we got a console then + // we definitely have a tty on stdin. + return true; + } + + // At this point, we *could* have a false negative. We can determine that + // this is true negative if we can detect the presence of a console on + // any of the other streams. If another stream has a console, then we know + // we're in a Windows console and can therefore trust the negative. + if unsafe { console_on_any(&others) } { + return false; + } + + // Otherwise, we fall back to a very strange msys hack to see if we can + // sneakily detect the presence of a tty. + unsafe { msys_tty_on(fd) } +} + +/// returns true if this is _not_ a tty +pub fn isnt(stream: Stream) -> bool { + !is(stream) +} + +/// Returns true if any of the given fds are on a console. +#[cfg(windows)] +unsafe fn console_on_any(fds: &[DWORD]) -> bool { + use winapi::um::{consoleapi::GetConsoleMode, processenv::GetStdHandle}; + + for &fd in fds { + let mut out = 0; + let handle = GetStdHandle(fd); + if GetConsoleMode(handle, &mut out) != 0 { + return true; + } + } + false +} + +/// Returns true if there is an MSYS tty on the given handle. +#[cfg(windows)] +unsafe fn msys_tty_on(fd: DWORD) -> bool { + use std::{mem, slice}; + + use winapi::{ + ctypes::c_void, + shared::minwindef::MAX_PATH, + um::{ + fileapi::FILE_NAME_INFO, minwinbase::FileNameInfo, processenv::GetStdHandle, + winbase::GetFileInformationByHandleEx, + }, + }; + + let size = mem::size_of::(); + let mut name_info_bytes = vec![0u8; size + MAX_PATH * mem::size_of::()]; + let res = GetFileInformationByHandleEx( + GetStdHandle(fd), + FileNameInfo, + &mut *name_info_bytes as *mut _ as *mut c_void, + name_info_bytes.len() as u32, + ); + if res == 0 { + return false; + } + let name_info: &FILE_NAME_INFO = &*(name_info_bytes.as_ptr() as *const FILE_NAME_INFO); + let s = slice::from_raw_parts( + name_info.FileName.as_ptr(), + name_info.FileNameLength as usize / 2, + ); + let name = String::from_utf16_lossy(s); + // This checks whether 'pty' exists in the file name, which indicates that + // a pseudo-terminal is attached. To mitigate against false positives + // (e.g., an actual file name that contains 'pty'), we also require that + // either the strings 'msys-' or 'cygwin-' are in the file name as well.) + let is_msys = name.contains("msys-") || name.contains("cygwin-"); + let is_pty = name.contains("-pty"); + is_msys && is_pty +} + +/// returns true if this is a tty +#[cfg(target_arch = "wasm32")] +pub fn is(_stream: Stream) -> bool { + false +} + +#[cfg(test)] +mod tests { + use super::{is, Stream}; + + #[test] + #[cfg(windows)] + fn is_err() { + // appveyor pipes its output + assert!(!is(Stream::Stderr)) + } + + #[test] + #[cfg(windows)] + fn is_out() { + // appveyor pipes its output + assert!(!is(Stream::Stdout)) + } + + #[test] + #[cfg(windows)] + fn is_in() { + assert!(is(Stream::Stdin)) + } + + #[test] + #[cfg(unix)] + fn is_err() { + assert!(is(Stream::Stderr)) + } + + #[test] + #[cfg(unix)] + fn is_out() { + assert!(is(Stream::Stdout)) + } + + #[test] + #[cfg(target_os = "macos")] + fn is_in() { + // macos on travis seems to pipe its input + assert!(is(Stream::Stdin)) + } + + #[test] + #[cfg(all(not(target_os = "macos"), unix))] + fn is_in() { + assert!(is(Stream::Stdin)) + } +} diff --git a/bash-5.1/vendor/autocfg-0.1.8/.cargo-checksum.json b/bash-5.1/vendor/autocfg-0.1.8/.cargo-checksum.json new file mode 100644 index 0000000..3183d47 --- /dev/null +++ b/bash-5.1/vendor/autocfg-0.1.8/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"4953f554c55611965cee146371c0a47acf26595692608f5d06f0e285425ed803","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"27995d58ad5c1145c1a8cd86244ce844886958a35eb2b78c6b772748669999ac","README.md":"7c0401bcd220566d72e54b52143bbcf9a21723c9495f1fbcf7086f38471d0976","src/lib.rs":"5df5c10f34099bc38b6ebe8c506af31b3d01783d0c89c830fa79edd4655c9dc6"},"package":"0dde43e75fd43e8a1bf86103336bc699aa8d17ad1be60c76c0bdfd4828e19b78"} \ No newline at end of file diff --git a/bash-5.1/vendor/autocfg-0.1.8/Cargo.toml b/bash-5.1/vendor/autocfg-0.1.8/Cargo.toml new file mode 100644 index 0000000..c1565ca --- /dev/null +++ b/bash-5.1/vendor/autocfg-0.1.8/Cargo.toml @@ -0,0 +1,28 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "autocfg" +version = "0.1.8" +authors = ["Josh Stone "] +description = "Automatic cfg for Rust compiler features" +readme = "README.md" +keywords = ["rustc", "build", "autoconf"] +categories = ["development-tools::build-utils"] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/cuviper/autocfg" + +[lib] +name = "autocfg" +test = false +doctest = false +[dependencies.autocfg] +version = "1.1.0" diff --git a/bash-5.1/vendor/autocfg-0.1.8/LICENSE-APACHE b/bash-5.1/vendor/autocfg-0.1.8/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/autocfg-0.1.8/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/autocfg-0.1.8/LICENSE-MIT b/bash-5.1/vendor/autocfg-0.1.8/LICENSE-MIT new file mode 100644 index 0000000..44fbc4d --- /dev/null +++ b/bash-5.1/vendor/autocfg-0.1.8/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Josh Stone + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/autocfg-0.1.8/README.md b/bash-5.1/vendor/autocfg-0.1.8/README.md new file mode 100644 index 0000000..ef7134b --- /dev/null +++ b/bash-5.1/vendor/autocfg-0.1.8/README.md @@ -0,0 +1,87 @@ +autocfg +======= + +[![autocfg crate](https://img.shields.io/crates/v/autocfg.svg)](https://crates.io/crates/autocfg) +[![autocfg documentation](https://docs.rs/autocfg/badge.svg)](https://docs.rs/autocfg) +![minimum rustc 1.0](https://img.shields.io/badge/rustc-1.0+-red.svg) +![build status](https://github.com/cuviper/autocfg/workflows/master/badge.svg) + +A Rust library for build scripts to automatically configure code based on +compiler support. Code snippets are dynamically tested to see if the `rustc` +will accept them, rather than hard-coding specific version support. + + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[build-dependencies] +autocfg = "0.1" +``` + +Then use it in your `build.rs` script to detect compiler features. For +example, to test for 128-bit integer support, it might look like: + +```rust +extern crate autocfg; + +fn main() { + let ac = autocfg::new(); + ac.emit_has_type("i128"); + + // (optional) We don't need to rerun for anything external. + autocfg::rerun_path("build.rs"); +} +``` + +If the type test succeeds, this will write a `cargo:rustc-cfg=has_i128` line +for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the +rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that +should only be used when the compiler supports it. + + +## Release Notes + +- 0.1.8 (2022-02-07) + - Re-export from autocfg 1.1.0 -- please upgrade! + +- 0.1.7 (2019-10-20) + - Apply `RUSTFLAGS` when probing `$TARGET != $HOST`, mainly for sysroot, by @roblabla. + +- 0.1.6 (2019-08-19) + - Add `probe`/`emit_sysroot_crate`, by @leo60228. + +- 0.1.5 (2019-07-16) + - Mask some warnings from newer rustc. + +- 0.1.4 (2019-05-22) + - Relax `std`/`no_std` probing to a warning instead of an error. + - Improve `rustc` bootstrap compatibility. + +- 0.1.3 (2019-05-21) + - Auto-detects if `#![no_std]` is needed for the `$TARGET`. + +- 0.1.2 (2019-01-16) + - Add `rerun_env(ENV)` to print `cargo:rerun-if-env-changed=ENV`. + - Add `rerun_path(PATH)` to print `cargo:rerun-if-changed=PATH`. + + +## Minimum Rust version policy + +This crate's minimum supported `rustc` version is `1.0.0`. Compatibility is +its entire reason for existence, so this crate will be extremely conservative +about raising this requirement. If this is ever deemed necessary, it will be +treated as a major breaking change for semver purposes. + + +## License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. diff --git a/bash-5.1/vendor/autocfg-0.1.8/src/lib.rs b/bash-5.1/vendor/autocfg-0.1.8/src/lib.rs new file mode 100644 index 0000000..e45bbad --- /dev/null +++ b/bash-5.1/vendor/autocfg-0.1.8/src/lib.rs @@ -0,0 +1,6 @@ +//! As of autocfg 0.1.8, this is simply re-exporting from autocfg 1.1.0 or later. +//! Please upgrade and refer to the newer version for current documentation! + +extern crate autocfg; + +pub use autocfg::{emit, new, rerun_env, rerun_path, AutoCfg, Error}; diff --git a/bash-5.1/vendor/bindgen/.cargo-checksum.json b/bash-5.1/vendor/bindgen/.cargo-checksum.json new file mode 100644 index 0000000..1085268 --- /dev/null +++ b/bash-5.1/vendor/bindgen/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CONTRIBUTING.md":"dcafe7b1b12b9901218883e402260d17c8fddd6e9796bde1df51cd79a59f0de4","Cargo.toml":"27621e759e008945fd5259fd8c063ac7724f79995c15ba93454e5641ab50946d","LICENSE":"1d2e4bdb9d94ab020e9550136cae9ec73fc699c3c96a9d98078c542e9b93d294","README.md":"b0fdf3ed4ec467b9f1e4251935af3bdb7b1c5c585ea8d6cbd06cf2eb64107050","build.rs":"a6e333bda22a396c7c84761b63b4b6ee3ede6c505bff7776d076f96b1a627457","ci/before_install.sh":"3ba09d266dba5df9fe763848af7f664a5bb4fa09e8b1d5ee1eeb3e5bf47181bc","rustfmt.toml":"c4f3b593bdd634590df22aaf7b0872244d5c2169aacd0274a05e4aca4708a8d3","src/chooser.rs":"f49216d47ae579c882d272a19ef5146f415223749cbbeee7d582fc18ae47b100","src/clang.rs":"8b15a2e721234c2a26542be5af44c4343f293b5b864f2430767f430836812061","src/codegen/helpers.rs":"910ba3d539437ef5559aba45a98b0251bf483d7481f6220c63aba2320f1d3fa0","src/codegen/mod.rs":"6e6d1449b2ba3f0efd281f5e68505ab8a23682b1a238696261562fe7fd5c6632","src/ir/annotations.rs":"887ad7beaa43eddd60337b67951a109c2e7f51cb8e757b35cad45f744b7ba919","src/ir/comp.rs":"0810fd03495fffddf33bd68eade521730275997d460cb4789f624fbdb86fe54f","src/ir/context.rs":"ff7f60133f55cdb276a3f6ab3d5e73008a231501f45b310fdfcd82f6f0729319","src/ir/derive.rs":"3593a370a8f56dc0fa1f1924b1652c74055bdbb22d5b20b9ed3493ba1d6bca74","src/ir/enum_ty.rs":"bf6b7c24c32b37157c28ece3358907e32ed13cb811c55feb7acb6e60bad63d9d","src/ir/function.rs":"1d5c182919d80b357806e523d9f53a0d56704580dfc2f60e55c98afd43c5cdf6","src/ir/int.rs":"dd467b79a642f8ab90b1316981e3ea7f29e697b7fa0f4d88c33b3a8f0f48bf4e","src/ir/item.rs":"e053bcb367850a4a3a3ec17b6ed78293a8ca29ae6c1b0c497d6fbe4ee731ec36","src/ir/item_kind.rs":"ad12a6dbea06fc61df8c91858d23114cbf56750c4307db51b3b16b0c982255de","src/ir/layout.rs":"ffd7261556ebaac00f12b6a8f0a0824d37e7dc2215b715b2aa16580befb55a84","src/ir/mod.rs":"b7a22a01dcea572fe6bd067916d669e4659e6f18fbb90c33847cf62a9b0fb9ba","src/ir/module.rs":"00fdea203ed7c026aba2030f7c7b29f27f349d55afb4376717d9400d8ad643a2","src/ir/ty.rs":"62afa09a1964c8ddbb5381cf272d45b5b8ef991f6143aa5abc7759e770fc9f35","src/ir/type_collector.rs":"c054fe3bcd390427f958f9cffb20ad51cf610a99d052b649ef5a387ac7aaa0cf","src/ir/var.rs":"966c748a84cad83cc0e8aa394ee2c3295cb4cacfcc89e0332ddfde5584c440f2","src/lib.rs":"20cdb763d74abaef20377389d5d3d17e7fd7e9dd7b06d729dacd9baf2d51c64a","src/log_stubs.rs":"e1e52b0b03397de90995afd5ddefc77e99eced2968c2203a393003435dbc436b","src/main.rs":"bc00cf18cbc392107e9a4db84f934288bb15ec77f43cb50d431eecc96dbc77eb","src/options.rs":"35bce465ee71b99934f5ee1c5198d296a579fda0b8288ddeb8e52a1db138093b","src/parse.rs":"e7ea915a836e52d8d79043afebd0c694a7c44b0cfc530d2601d242febb00ee4c","src/regex_set.rs":"9315449442f74df820cdb85412fa7eab5dd61fd3d040295d9d5166a62551314f","src/uses.rs":"872c23f4cf2ae8e51b558853caaafa79eff0eb12a2981243612fbaeba855e48f","tests/headers/16-byte-alignment.h":"00d82adc7f58a875da5f2be2d3d5104e30528e2c6781f268c0eb912d0b152f94","tests/headers/accessors.hpp":"7300e99f0bdf614af462a6e9c0bbdd01d5f2053c96bcfe19d55e3f9a078cbe0d","tests/headers/annotation_hide.hpp":"128644863239b73c5ac0c18aeaeb3f3a791feac10b53ff15d044bb83f0789b61","tests/headers/anon_enum.hpp":"dd5bf5a3959b73eef283c861b72e391961b37378ff130247ef62807a6973446d","tests/headers/anon_enum_trait.hpp":"2275f9c070ed690ec48947779fea0d8f7102121abcd3a80865869090310fac90","tests/headers/anon_enum_whitelist.h":"723fc9f71a353b6b40c5c418c8d1ac7d064f2eb160e204e8a7d3e41092a063e7","tests/headers/anon_union.hpp":"67ec069c869a293225e4d70fb8736c00439da092a551e4e5d674454a51763e8d","tests/headers/arg_keyword.hpp":"e100654db2124fb95d3dd139f4972f1f4b3a295bf5a8a48d374a43266a687325","tests/headers/auto.hpp":"612feab94728cf4c8e99aa8564afbed9be4aa4229b682e3da98eea43c6aee604","tests/headers/bad-namespace-parenthood-inheritance.hpp":"afb9098bc986809839817e5c3e9b58807d3998a110873910690b3107b738b774","tests/headers/base-to-derived.hpp":"82225b95e38cff09cea3d2f553cd336d854285dd20f20f75c023ecd00823cbf1","tests/headers/bitfield-enum-basic.hpp":"9a46e1ab84a5b1fa166f8bf7d6385c322a970d244ecf39656606a5e3a4d90e01","tests/headers/bitfield_method_mangling.h":"ae54e014be753a5a38f7b878120cf98ee051693a167283256a55307fc4eb07fd","tests/headers/blocks.h":"9a66d2119f8d08a9788f341a6abcdbe94aa1ae76936141cb5b89b4fe77f4e284","tests/headers/canonical_path_without_namespacing.hpp":"78e7937a13dd17fa8f2467bf226540ed8e04ec721d98c327636616d3be0610fc","tests/headers/class.hpp":"38ed538a8dda4a9c11fd04b67c634d9a6f58fcfd91684c97ac094ce9658e218d","tests/headers/class_nested.hpp":"645265163e897bd51ce12876a779808ab2abca82dd4856fde287abf837bd53f6","tests/headers/class_no_members.hpp":"c466313e6157f567e62fa1323dd4243bdc9ee3bf94ef43f599f5ba612e074961","tests/headers/class_static.hpp":"8bdd7d3b31722cba32af72b7a5d469b43ef69ee710fc80127de8262364ac8ab6","tests/headers/class_static_const.hpp":"cf7860a7f1649300a1ae4e294847187cb4a01c4b7d4108cc9dd8b37780d137b5","tests/headers/class_use_as.hpp":"c9f8816493461046fcafc494c6a51a6c7871f65f5ecb1bae6cf5c6a45d83635c","tests/headers/class_with_dtor.hpp":"1ff087a703278628f7954f93d58e72e5f421540936ea341035d244e1a98ae503","tests/headers/class_with_inner_struct.hpp":"4191f3bd5dfb778aff73beccd4e3fa5a578bf9b825e90114379cf6fb1fbfc676","tests/headers/class_with_typedef.hpp":"697bb7a0f2b0dac7e5552b5567bd13e90e707e14a5901cf32bec9642ba991bf9","tests/headers/complex.h":"470b172b3980c57bb1bbe2df9562083749716b7345fd1543a715c101f38e6964","tests/headers/complex_global.h":"e8d9de67b33a73120ffa3ef676e24def347834f2567e75fa967da8917ca05e5f","tests/headers/const_bool.hpp":"e147050b90b28f261640dc9e19819b9166f943dfce3a1101a71066f8a13230d6","tests/headers/const_enum_unnamed.hpp":"e5dd66225fc721943dd8706f930ba9dc04c9e9a535c9d2b70215e563eb23359c","tests/headers/const_ptr.hpp":"f55a4a914bf4cde1c9be63a99ea58acd3a4d6b722b9d6b4d570de91aa90a861d","tests/headers/const_resolved_ty.h":"572c999b6224bdb34fe807d75f27b49c9ca5d737150bbdbc18a4fdfa4c00ad1c","tests/headers/const_tparam.hpp":"32101adfd9b408ed29ebe330219cb66da199d194c54397cf0a6a51bf40d5770b","tests/headers/constant-evaluate.h":"f1f3dd8a07f7e45ad46ae1801406b989f3d731294149520675ddf4a7dd262766","tests/headers/constify-all-enums.h":"e6756535ff5ff68c122a0c40e621a61c968e6870128d9002d77a0f59d373aa3d","tests/headers/constify-enum.h":"f6fc217be7558f4cd25c6f7b7286f99e5124596364fcf0167133fcbf66377292","tests/headers/constructor-tp.hpp":"4d7e4e7f8642e2341679c84bc36eb609fd257b5475ad5ca216ffee974297e94f","tests/headers/constructors.hpp":"5ee56a7b05b71dc55bb9dfbf8816b5045142dc22f1c6d286319a6d4653a4984d","tests/headers/convert-floats.h":"b771a2ee9ed87b132494315b7a48449f783d903e96583a7642e61785b60d576e","tests/headers/crtp.hpp":"5ad7d00d2cbf243a89a8935eab5ab2997d7e828cbd54a5699a56064a37656152","tests/headers/dash_language.h":"acccf995806466b4f7ed7e4ef454ca1c8e849011a2bf52e5825a29ea52e01133","tests/headers/decl_extern_int_twice.h":"6ed5703307ac0712871a0e2e4cab19ebf26e3114e06b495274031376ae4027aa","tests/headers/decl_ptr_to_array.h":"76157bc1b4650bbec96ae52d672d42b71d0d0a16dbf9edc24b9e19d3e9d0ee52","tests/headers/disable-namespacing.hpp":"35e390e7aa60d675b2fa6a1737a48688fdcb05c7d2dc5506a5cd1d00a64bced6","tests/headers/duplicated-namespaces-definitions.hpp":"2940fc83895551c01969bb23432df847443fca306e26d9fb1bca8483887a3d23","tests/headers/duplicated-namespaces.hpp":"18b9fbbdbdea4952aaf0e308a95ba9453b92dc2b7e0c28e2175d8d9fc4db3c10","tests/headers/duplicated_constants_in_ns.hpp":"c3d2950b1e105c8c6ddd419999d20352ffd7d0ded0243cf14e1651dbf87adf42","tests/headers/elaborated.hpp":"d818eb9d298fc296fd35ef50e1b10658a66327748ba568c2b3e1e88e52651391","tests/headers/empty_template_param_name.hpp":"c9364c8a071bceecc0d6e4a764193a5cd653f688e9fbf543fff57b4263f0305c","tests/headers/enum.h":"513c9462f908150540fd4c31cf486c4e855b8b690786b02aa62ec86f969b637b","tests/headers/enum_alias.hpp":"684150ee62e3a1c9deb169c76bf32ac907751fc667d0a8ce8c2715371021c03f","tests/headers/enum_and_vtable_mangling.hpp":"dcfebe04ad23eb146f43ce3912aceb3170dff62552808cb7ce069946dc7868b4","tests/headers/enum_dupe.h":"d8c3ccd7155412ba5cc1cd37e0ae0005ca8460e570f5a8d8d7318615f19c264c","tests/headers/enum_explicit_type.hpp":"6295f549659449d977d451d6c07046af23309e8ac7d8be40c335f2fe79f897e1","tests/headers/enum_in_template_with_typedef.hpp":"6a1c37c7464b6ceb3916893698420cd339e55be17bf546381d5a4e020921c148","tests/headers/enum_negative.h":"9ddbe83fab84947ad2b8292a722ac7f5c3e1bfd1d1ad1ce08434ddee52f0e338","tests/headers/enum_packed.h":"1c8b49061675f9cf83c429eccc63725631883832d7e5ab30554accc6db7dc09b","tests/headers/eval-variadic-template-parameter.hpp":"d9190b6b7f96f678206c328161617d847e53b7356833c7ca32fc7ed4dddf6dee","tests/headers/extern.hpp":"68f1eba8b60316cd8bf52731a5dd29c84559342e7b66daffe6b769dc98f837ec","tests/headers/float128.hpp":"f0a676919df69373828a2a32f10b3b22a6c978c08864099603b10ddf444c26b7","tests/headers/forward-declaration-autoptr.hpp":"8c808baeac1af6c9e3efe0ee78d9ca76580502c713621e3f6ad2f298f0808bd8","tests/headers/forward-inherit-struct-with-fields.hpp":"3d63ec1d66bb080c4617fa945890cf70cf02f2af7b190e6a28fcf196fc8ea1f6","tests/headers/forward-inherit-struct.hpp":"c3869d51ecae6ff5ee6bd5d6f9710be60f93aea09e73d9b97a6c9068eb94e4de","tests/headers/forward_declared_complex_types.hpp":"deba01c271881fb324170c78ed26d37904cf6da0185b1d4472a9e3354be024ae","tests/headers/forward_declared_struct.h":"e31acf91e4d112e31bcba7040f2a1366853b442c52b9b04a40c73e0f2903bfe2","tests/headers/func_proto.h":"bf9519b408ee057b71bf72ad4ce910a5b75a15ae8daf12f536b65f9f9478c461","tests/headers/func_ptr.h":"9723273d527c1be57d6517cf8123e424225cd9d25a801f42618395ab5258d2fa","tests/headers/func_ptr_in_struct.h":"ce517145afed4eb8f9d14233248bc479a88a2fdcc52dc23029c498aa306f129c","tests/headers/func_with_array_arg.h":"1f6fff4283d90e96ba44dc7c64a778ad5e725fbf8167f04697bca20176eb6d2d","tests/headers/func_with_func_ptr_arg.h":"938475e53aafa207ebef7f4a84a9ec009d8dc4fa258fcab446318f5b0f1cc07b","tests/headers/in_class_typedef.hpp":"3bdc8ad6b9013b993dccec2d1bdec69801062fb41e251790bb5f93d89a562bd0","tests/headers/inherit-namespaced.hpp":"7636ac3a56620b20a8991b1a6d228fda174cbab02ddfb3117163700d8514fa55","tests/headers/inherit_named.hpp":"3fec93dcb2359d9acfb284acc39f7050362d8ecf05d828eb20eeb81d96f98f3c","tests/headers/inherit_typedef.hpp":"3ca1a4993c29282a18a0ba72186f3297ae26efa32cf22d05c1613fc799c9c466","tests/headers/inline-function.h":"028efdd98df34a85d9631357e95e7a6809ef6e8206ab3c00ad5181ca88826aed","tests/headers/inline_namespace.hpp":"ac8c6091fe3611877918ddfcf8a02934497ea4291c91ade237206f67fafd5cfe","tests/headers/inline_namespace_conservative.hpp":"820857eac505fc4bb3e5ba76d8cfc358d84b737ddbf99a2938522ee0fd59fba7","tests/headers/inline_namespace_whitelist.hpp":"6372a42e6c419d7e096b6fad3636d4076080951b6078120fa954869fa40c7b15","tests/headers/inner_const.hpp":"7325eb025bf4923ef4f8df164037d9398895b36107a1ed444bdcc5b419a56747","tests/headers/inner_template_self.hpp":"3a356ef1a1fefe9ec891bfdd9f2341b8094246caa2bf9fb321a6b061069f84ac","tests/headers/int128_t.h":"f460a6823e171a42be7bdcc6d7212b2821b01b8b887e3055fc6484a59f050789","tests/headers/issue-358.hpp":"4abe91b5721875d99c4102b174400b1ad365ea82f7367a6266c5e6dc21e26bbc","tests/headers/issue-372.hpp":"9ecf1029c04e3ec7462416a422172360c0a3ed5eb99a1536bafb5e3264ce23e9","tests/headers/issue-410.hpp":"dff6dbf8763017d35ab103ce15c19c9aa3ce61253dda7b8e313238b30214be68","tests/headers/issue-447.hpp":"e96fe1ee3215196413903c0d2e63b53352c8d83077f661edf5dc5b257b2cb0fa","tests/headers/issue_311.hpp":"b25e14cfa72cd5425f2cadfc0868d2bcacf6ac4c019945a840d19d7bb1811a67","tests/headers/issue_315.hpp":"6ebb5e7aeded8cf9b63f25478445432f8c76af731f7d587cff9932167fd32a75","tests/headers/jsval_layout_opaque.hpp":"5a82a83ee9e27d67641ad2805d616ea02a9828c4ab31aac9a08710f6b9f70b87","tests/headers/keywords.h":"9782ce81a46a25744ffbcf1970c0944f7230b9967085c3181ee3085ca7b2b2f0","tests/headers/macro-expr-basic.h":"bce59cdefb620457295199dd7b2839e1e397292d9bab10d54b5360b0574b17d6","tests/headers/macro-redef.h":"a5b95e2b26425119c567f45bfc3ad7d298c2efcad0132e9a9bfc3078dd0c4bcf","tests/headers/macro_const.h":"ec5c8d2009ad818c0fc242f76eaa8d3562633c50e50c0444fe293b3f8ed10ef0","tests/headers/maddness-is-avoidable.hpp":"8ba98872bf4292d014729e7b8248e750412a75cebdf2edbb684173aa0db7cf87","tests/headers/method-mangling.hpp":"b7ffe0e3b002bc032fab6b7785b03e635c0595bbc03d73fae4164611473dae2a","tests/headers/module-whitelisted.hpp":"a88e2a3e2f0f3edb205e60f9b08f4b1f7e017c15dc12e0541697006ba947025b","tests/headers/msvc-no-usr.hpp":"2b11fc139685e78a11bc224967360cb06f768b09e033a8be01d97002587383d9","tests/headers/multiple-inherit-empty-correct-layout.hpp":"7559184da00f812c7679bc5a863e5720447bd2b38a42310a2ec3114f405398a0","tests/headers/mutable.hpp":"cb85dc019dcf866ebf4e092d5c6ace509957c64c18eb48ccfb7b47116bc06c2c","tests/headers/namespace.hpp":"c0417b68013beb38ce781e385d0c7125b895d75e27a07ea6f05209050b9b5a19","tests/headers/nested.hpp":"0f56cd4d50004a75d8b54226f631db939ad918b7e68d48d4ebaaaab7dffc5eb4","tests/headers/nested_vtable.hpp":"c1a7f59161dda9429ccd146407a3899a27b1749c2feb4edf5537fe912f7f423d","tests/headers/nested_within_namespace.hpp":"841c9aae50dc4303e468878514939562870dabb94da909c82fa19bb2a35d1bfe","tests/headers/no-comments.h":"6dc35a97a702a99f43ac716dc6879137600b7f88961deaa7a148de505b3c2b4f","tests/headers/no-derive-debug.h":"69ea2990e44fc7d22499f672758b03e445bb08bd76bc0f5ff52ad51cd1ada1b0","tests/headers/no-recursive-whitelisting.h":"5153922c341e809cab973c5def7c503dc9c69d28275e0a30255fdbcc51c4210a","tests/headers/no-std.h":"3b7b5fabdf51588a48f11ff8a6961b652b4251125db45a32fd743a973ed929f4","tests/headers/no_copy.hpp":"b07c1dbc2f70aced75cee5421e78a1501cf6193508169c966394d86521b5c6bc","tests/headers/nsStyleAutoArray.hpp":"a80160e314377d8d5083165e9fd42e2e5ca31b211afca51b4b0e761f41e40824","tests/headers/only_bitfields.hpp":"bc9e1be2d946e5ac4116fa000c55fcbece500e98425404fc9d3b0cb9726ff7ba","tests/headers/opaque-tracing.hpp":"bf3326089c275be21b336cd4fb7ee5456d89c8444265daf49c3c5440b30f4264","tests/headers/opaque_in_struct.hpp":"31907f11d4b2d6fab2871b0d3314d2a3f5ebff5acae37f1071b5efd8090f8d58","tests/headers/opaque_pointer.hpp":"a7f97c2e2a6ef6433eba296b62d176568daa1383201631dbbcf081775b7a747e","tests/headers/opaque_typedef.hpp":"204404343f0050f8028678555ab6624777c678ce69ddbb9f54552011ea4e1a38","tests/headers/overflowed_enum.hpp":"0d927f0366546eb6459e5c81fcdd497ae8ba113ddc039af79847f0a05281a835","tests/headers/overloading.hpp":"2f0e0f44a6b1a7c4a72ab9e33863568ee7d24d2a271a701739aeac82c2d1ecc9","tests/headers/private.hpp":"2eae7fa2dd83fe3607e291746b3025b1e4265a0e1e584013fbea41fdfbd91725","tests/headers/public-dtor.hpp":"ed884a9c93569d1ad98c0af942dfc5f65e7cc67f579b2d1e6f940f25d4864f7c","tests/headers/redeclaration.hpp":"e9fc6785054ac6f6d4574f1846aefe933b09e26d398bd4cb47dad4ab8fb524ff","tests/headers/ref_argument_array.hpp":"c70b8b9ca935e2c9d0e78075f66220b33960fc4244c642d35cfcbe3c585e4371","tests/headers/reparented_replacement.hpp":"4f7a9cf64897155795abb0a55be2fde6512ff2108d7b3fd2495194efb2e1ca43","tests/headers/replace_template_alias.hpp":"982e0d2b7e6b9a7df1aa34d89df2520cc5d6b2b9c16f56c1369fe0ca3a88cb18","tests/headers/replace_use.hpp":"5bac44653be912b5af5062cfc4561e30cfcb7f91d321f8a6285656e2893cc349","tests/headers/replaces_double.hpp":"be76785b1742d8c2ae7011b230dd11e3c9d1b3b8218c2a76e4fe73c2870b5e80","tests/headers/resolved_type_def_function.h":"e080509e0cea0eb09262113b0f90d147928ffdd9a7cd9c3158628f5df5ecb426","tests/headers/same_struct_name_in_different_namespaces.hpp":"90a923bf707ef9de241cefba6397c088b6ffbad5ca7c997c4460af3876fedd04","tests/headers/size_t_template.hpp":"7e73bedf712c9f4b80f6e7f5e1411b91e01a3ea47bf2d261550ca785aae0c912","tests/headers/struct_containing_forward_declared_struct.h":"c66f635e39ee5b8fda94e9499b2fd682181ab819728ac268aa2ec40b62ac0e13","tests/headers/struct_with_anon_struct.h":"4ce9c56a41b2fde0ae0062e5c87315dd69adc3ef79575b267256f47a9bd531b1","tests/headers/struct_with_anon_struct_array.h":"cb13830919d4039fd8a64b5aa972c05c21f5bd5d1f8722aa865bcd394f9f3c0c","tests/headers/struct_with_anon_struct_pointer.h":"4e0b669af481100125bd0bf1a4e17bd9ee1e03fb6cc8ee36875d71ecf6d63adb","tests/headers/struct_with_anon_union.h":"542567e8d54e51f43eb6699503d857fe5177ecd51b6ad5d5667a4992aa438f28","tests/headers/struct_with_anon_unnamed_struct.h":"0ae74d3b11fc64b30fed7f217f0cc51488c93b88a62755628699affdeeb8f5ef","tests/headers/struct_with_anon_unnamed_union.h":"71c9fa48a80fa5ee3714f76eb4faacae096f30ccaacbe51e8099760abf601aa9","tests/headers/struct_with_bitfields.h":"f8faa67dc47a88b0bd0b45d42ea170a714a67f0ef90b6f2e4870006bb499fd21","tests/headers/struct_with_derive_debug.h":"c4afb2aa9ae08b2e55270118f162cb611f011a64fa5b37e87aba7efd6a515a9b","tests/headers/struct_with_nesting.h":"695cdad138a59713aeee75050a8cf6f19bc1c16af7c49bb65e7a1fd6924e549a","tests/headers/struct_with_packing.h":"409c1b58233f45f65d4c6dc9bc233feea13549630b7267a320635fff0afce563","tests/headers/struct_with_struct.h":"f1d2c84e45396a4f5c16dbdd2db59d8bd4004d24e9287387bf55d532c7e4820e","tests/headers/struct_with_typedef_template_arg.hpp":"a620d87c5138d8b24842cddf906a00b2c74a95ee68d67d3b25a993264704f62d","tests/headers/template.hpp":"92517022906ea22b58f8edc58f4b2cf438e586c8b34b9b24f5a93f509fe6c45d","tests/headers/template_alias.hpp":"1df4a71f910aca9e6971927d48927baa777782e8a24c3880a68f97af41bb17d3","tests/headers/template_alias_basic.hpp":"676cb84ef33cd1ea7c0d4490304cb5f8d26f792035970aec6a81a1bed5fbdbc7","tests/headers/template_alias_namespace.hpp":"49e66046de03ffa6c00713cf184f80eb5182284b43bfa4457bc8657e2504ebc6","tests/headers/template_typedef_transitive_param.hpp":"6c6ff83e79eb8c882f6fc8340ae3e21727205dbea882e9f7092ed1127775967d","tests/headers/template_typedefs.hpp":"12b5892aadbe8529e7fdecf2956f9e276824818ba6f3fbbde41cc5c7e628337a","tests/headers/templateref_opaque.hpp":"6ea0675c05821e4cd023e6541d8e33d6e762e1b30e55b1aa4f81360dcd93d324","tests/headers/type-referenced-by-whitelisted-function.h":"40ea5086de6ca2219c18db7b32846614737405eea8a3c3d70b198f1b1475d281","tests/headers/type_alias_empty.hpp":"f28175e7b5b843bbb35fe6214f0834ce9c8e6d0da52432cea252e2ed9a1c7d3c","tests/headers/type_alias_partial_template_especialization.hpp":"8c21d219cca03735d2a94bc0b9e9ecbee781d8c1655bd9caf7bedd51a6b77e95","tests/headers/type_alias_template_specialized.hpp":"15ceec92f8ccbacae71d7c8b59ecd8d81347cbcd0b4e0ed4366f17bdbbe95f1d","tests/headers/typedefd-array-as-function-arg.h":"7069fbb775a6b8af548ed0de2d24f3e2e35e10ebf8eed3c8841a220f58efa10b","tests/headers/typeref.hpp":"e314362ebff945a823b4a65bcd4931aaee3f93bc50baa57771da15fbf36c0b58","tests/headers/union-in-ns.hpp":"adb1d203918accd7177e55dd97ee64d1e908403c1e5c8c8f9ba4af5f50d6e522","tests/headers/union_dtor.hpp":"4ce6c54758690778348f84f8a876b8d0bb9cfecec95668147f815bb13d57d801","tests/headers/union_fields.hpp":"4f91a0013e39abbe0e10667f72ae902441ac2f1d9245c79ae182ae606794ceba","tests/headers/union_template.hpp":"142a263ee4db89573dade811057b0e5a4e0deae61c6859612068ebb5edd05503","tests/headers/union_with_anon_struct.h":"201c566f923d41e2b9cbc788f22d084e480d73ae1be9eed7096f1bac2870a034","tests/headers/union_with_anon_struct_bitfield.h":"2a7396f341ec34fa82f4705b3867d8546cbf8d2e62e790a70169bd807a70c8cb","tests/headers/union_with_anon_union.h":"5634be743d250fbfdacfc07a3bfc3b4d7659e8e201d0801e2d956aa0e1350a7e","tests/headers/union_with_anon_unnamed_struct.h":"5df9ec8170a3f712757a1000cc6f6883b95506dcaf8c94c59f03c7f26d3cc2df","tests/headers/union_with_anon_unnamed_union.h":"563f09841597a93f956a75db20261b8a9d290d88a385be343c6bc4cff6ecd66d","tests/headers/union_with_big_member.h":"d4622757fea8ff6ff7fb67de83e0e2511b078d3a74769bb847dfe1459317e5fe","tests/headers/union_with_nesting.h":"8e800c0fc5449d2317b51ec8a3e39e7680b7b0f29d00fe917e6c9d6da3854f0a","tests/headers/unknown_attr.h":"f65c88592a105bbbe3bd98bd46b15ea7c2cc82dcf9fbda6eceecc9c341228bf3","tests/headers/use-core.h":"691b075c045236aeb38b06755519f823f2a86ddf1d567f12887b240aeba6c813","tests/headers/using.hpp":"5021a2a1ff4eaa6dabf5dd914a71357562d4a81573d2680342a3b193e9951496","tests/headers/var-tracing.hpp":"8b93ed99969a7a32ed1e49c52df77eee4ef077db758c0f58666c46efddff3adf","tests/headers/variadic-method.hpp":"9947eda68dfb6ddcd59b558f2fcdb2356bea27cfa9f22c6a46114ee937fb88b9","tests/headers/variadic_template_function.hpp":"232d2112a60f18e5704b64df573e814f91e45dd4d7be14d8b00a11ef436ee042","tests/headers/vector.hpp":"0a80c8886beaa6a9fc83e6652be26be1e6b23e1db006111a45b2c8a7f98e7dd1","tests/headers/virtual_dtor.hpp":"b1a3928a25c62d51d394e2192f91e250298c0357330241609103329f43185ae7","tests/headers/virtual_inheritance.hpp":"d92e8a26a939e9a7d575f3af0caf3081a30b3409f6f320432e13719cb7ddbad1","tests/headers/virtual_overloaded.hpp":"fea58d5f4a1814f7907e0066d1019e334ae0798454448eb825fb3f81dafd1a8d","tests/headers/vtable_recursive_sig.hpp":"5aae5edd330622207e6a803ad880b421d1530aa81fd57b8e10fe7faca186bd01","tests/headers/weird_bitfields.hpp":"86d0c0ddd64f812874889f21c395df49001bd91b114613c650806d46da0063b9","tests/headers/what_is_going_on.hpp":"8a7ccdcab365c12f176114a223da9aba83ecf6c98f349a56b74579bd0d9128ee","tests/headers/whitelist-namespaces-basic.hpp":"fae14a96e1d7fc9a32972d182869f0e64ff098ab7a9596bfdfd1ab14c7eb3950","tests/headers/whitelist-namespaces.hpp":"22c965df52d5641a16588eb8d718f523ba7fb16fed2f0a13847abcd78786af9a","tests/headers/whitelist_basic.hpp":"f63a40850cbf2cae91e804f89df184bfc352e222e6256c3c7055950d0c5d0fe9","tests/headers/whitelist_fix.hpp":"19f34cbdd375a43709fb73786814eccc5510ec902d5d645d7550dd4e70c5d9e0","tests/headers/whitelist_vars.h":"926f3437b49cb7434a0c9964a60182a4fd4ab29c25217621ee3510ab5e9ad282","tests/tests.rs":"bb4d9457b49ceb55abc56dc4d04c76a3f34e3f6f1f40a23a1de7a63772a463c8"},"package":"e3dc42e1889c6b5b78c5c5b000e4855f7c996d3e54bde789fa96d58c4b5aed13"} \ No newline at end of file diff --git a/bash-5.1/vendor/bindgen/CONTRIBUTING.md b/bash-5.1/vendor/bindgen/CONTRIBUTING.md new file mode 100644 index 0000000..cfcee65 --- /dev/null +++ b/bash-5.1/vendor/bindgen/CONTRIBUTING.md @@ -0,0 +1,234 @@ +# Contributing to `bindgen` + +Hi! We'd love to have your contributions! If you want help or mentorship, reach +out to us in a GitHub issue, or stop by +[#servo on irc.mozilla.org](irc://irc.mozilla.org#servo) and introduce yourself. + + + + + +- [Code of Conduct](#code-of-conduct) +- [Filing an Issue](#filing-an-issue) +- [Building](#building) +- [Testing](#testing) + - [Overview](#overview) + - [Running All Tests](#running-all-tests) + - [Authoring New Tests](#authoring-new-tests) +- [Automatic code formatting](#automatic-code-formatting) +- [Debug Logging](#debug-logging) +- [Using `creduce` to Minimize Test Cases](#using-creduce-to-minimize-test-cases) + - [Isolating Your Test Case](#isolating-your-test-case) + - [Writing a Predicate Script](#writing-a-predicate-script) + + + +## Code of Conduct + +We abide by the [Rust Code of Conduct][coc] and ask that you do as well. + +[coc]: https://www.rust-lang.org/en-US/conduct.html + +## Filing an Issue + +Think you've found a bug? File an issue! To help us understand and reproduce the +issue, provide us with: + +* A (preferrably reduced) C/C++ header file that reproduces the issue +* The `bindgen` flags used to reproduce the issue with the header file +* The expected `bindgen` output +* The actual `bindgen` output +* The [debugging logs](#logs) generated when running `bindgen` on this testcase + +## Building + +To build the `bindgen` library and the `bindgen` executable: + +``` +$ cargo build +``` + +If you installed multiple versions of llvm, it may not be able to locate the +latest version of libclang. In that case, you may want to either uninstall other +versions of llvm, or specify the path of the desired libclang explicitly: + +``` +$ export LIBCLANG_PATH=path/to/clang-3.9/lib +``` + +On Linux and macOS, you may also need to add a path to `libclang.so` (usually +the same path as above) to library search path. This can be done as below: + +``` +$ export LD_LIBRARY_PATH=path/to/clang-3.9/lib # for Linux +$ export DYLD_LIBRARY_PATH=path/to/clang-3.9/lib # for macOS +``` + +Additionally, you may want to build and test with the `docs_` feature to ensure +that you aren't forgetting to document types and functions. CI will catch it if +you forget, but the turn around will be a lot slower ;) + +``` +$ cargo build --features "llvm_stable _docs" +``` + +## Testing + +Code for binding generation and testing thereof is in the `bindgen` crate. +The following sections assume you are working in that subdirectory. + +### Overview + +Input C/C++ test headers reside in the `tests/headers` directory. Expected +output Rust bindings live in `tests/expectations/tests`. + +For example, `tests/headers/my_header.h`'s expected generated Rust bindings +would be `tests/expectations/tests/my_header.rs`. + +Run `cargo test` to compare generated Rust bindings to the expectations. + +### Running All Tests + +``` +$ cargo test [--features llvm_stable] +``` + +### Authoring New Tests + +To add a new test header to the suite, simply put it in the `tests/headers` +directory. Next, run `bindgen` to generate the initial expected output Rust +bindings. Put those in `tests/expectations/tests`. + +If your new test requires certain flags to be passed to `bindgen`, you can +specify them at the top of the test header, with a comment like this: + +```c +// bindgen-flags: --enable-cxx-namespaces -- -std=c++14 +``` + +Then verify the new Rust bindings compile and pass some basic tests: + +``` +$ cargo test -p tests_expectations +``` + +## Automatic code formatting + +There's a `rustfmt.toml` file in the repo. Ideally changes should be consistent +with the style, though that's not enforced right now. + +[`rustfmt`](https://github.com/rust-lang-nursery/rustfmt) can catch and fix +automatically all the coding style issues it finds. In order to use it it +suffices to do: + +``` +$ cargo fmt +``` + +For it to work, you need to have `rustfmt` installed. To do so: + +``` +$ cargo install rustfmt +``` + +And ensure `~/.cargo/bin` is on your path. + +## Debug Logging + +To help debug what `bindgen` is doing, you can define the environment variable +`RUST_LOG=bindgen` to get a bunch of debugging log spew. + +``` +$ RUST_LOG=bindgen ./target/debug/bindgen [flags...] ~/path/to/some/header.h +``` + +This logging can also be used when debugging failing tests: + +``` +$ RUST_LOG=bindgen cargo test +``` + +## Using `creduce` to Minimize Test Cases + +If you are hacking on `bindgen` and find a test case that causes an unexpected +panic, results in bad Rust bindings, or some other incorrectness in `bindgen`, +then using `creduce` can help reduce the test case to a minimal one. + +[Follow these instructions for building and/or installing `creduce`.](https://github.com/csmith-project/creduce/blob/master/INSTALL) + +Running `creduce` requires two things: + +1. Your isolated test case, and + +2. A script to act as a predicate script describing whether the behavior you're + trying to isolate occurred. + +With those two things in hand, running `creduce` looks like this: + + $ creduce ./predicate.sh ./isolated_test_case.h + +### Isolating Your Test Case + +Use the `-save-temps` flag to make Clang spit out its intermediate +representations when compiling the test case into an object file. + + $ clang[++ -x c++ --std=c++14] -save-temps -c my_test_case.h + +There should now be a `my_test_case.ii` file, which is the results after the C +pre-processor has processed all the `#include`s, `#define`s, and `#ifdef`s. This +is generally what we're looking for. + +### Writing a Predicate Script + +Writing a `predicate.sh` script for a `bindgen` test case is fairly +straightforward. One potential gotcha is that `creduce` can and will attempt to +reduce test cases into invalid C/C++ code. That might be useful for C/C++ +compilers, but we generally only care about valid C/C++ input headers. + +Here is a skeleton predicate script: + +```bash +#!/usr/bin/env bash + +# Exit the script with a nonzero exit code if: +# * any individual command finishes with a nonzero exit code, or +# * we access any undefined variable. +set -eu + +# Print out Rust backtraces on panic. Useful for minimizing a particular panic. +export RUST_BACKTRACE=1 + +# If the `libclang.so` you're using for `bindgen` isn't the system +# `libclang.so`, let the linker find it. +export LD_LIBRARY_PATH=~/path/to/your/directory/containing/libclang + +# Make sure that the reduced test case is valid C/C++ by compiling it. If it +# isn't valid C/C++, this command will exit with a nonzero exit code and cause +# the whole script to do the same. +clang[++ --std=c++14] -c ./pre_processed_header.hpp + +# Run `bindgen` and `grep` for the thing your hunting down! Make sure to include +# `2>&1` to get at stderr if you're hunting down a panic. +~/src/rust-bindgen/target/debug/bindgen \ + ./pre_processed_header.hpp \ + [ ] \ + 2>&1 \ + | grep "" +``` + +When hunting down a panic, I `grep`ed like this: + + ... | grep "thread main panicked at ''" + +When hunting down bad codegen for a base member, I `grep`ed like this: + + ... | grep "pub _base: MyInvalidBaseTypeThatShouldntBeHere" + +That's pretty much it! I want to impress upon you that `creduce` is *really* +helpful and has enabled me to reduce 30k lines of test case into 5 lines. And it +works pretty quickly too. Super valuable tool to have in your belt when hacking +on `bindgen`! + +Happy bug hunting and test case reducing! + +[More information on using `creduce`.](https://embed.cs.utah.edu/creduce/using/) diff --git a/bash-5.1/vendor/bindgen/Cargo.toml b/bash-5.1/vendor/bindgen/Cargo.toml new file mode 100644 index 0000000..8ee91b0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/Cargo.toml @@ -0,0 +1,71 @@ +[package] +authors = [ + "Jyun-Yan You ", + "Emilio Cobos Álvarez ", + "Nick Fitzgerald ", + "The Servo project developers", +] +description = "Automatically generates Rust FFI bindings to C and C++ libraries." +keywords = ["bindings", "ffi", "code-generation"] +categories = ["external-ffi-bindings", "development-tools::ffi"] +license = "BSD-3-Clause" +name = "bindgen" +readme = "README.md" +repository = "https://github.com/servo/rust-bindgen" +documentation = "https://docs.rs/bindgen" +version = "0.20.5" +build = "build.rs" + +[badges] +travis-ci = { repository = "servo/rust-bindgen" } + +[lib] +path = "src/lib.rs" + +[[bin]] +name = "bindgen" +path = "src/main.rs" + +[dev-dependencies] +diff = "0.1" +clap = "2" +shlex = "0.1" + +[build-dependencies] +quasi_codegen = "0.29" + +[dependencies] +cexpr = "0.2" +cfg-if = "0.1.0" +clang-sys = { version = "0.12", features = ["runtime", "clang_3_9"] } +lazy_static = "0.2.1" +rustc-serialize = "0.3.19" +syntex_syntax = "0.54" +regex = "0.2" +# This kinda sucks: https://github.com/rust-lang/cargo/issues/1982 +clap = "2" + +[dependencies.aster] +features = ["with-syntex"] +version = "0.38" + +[dependencies.env_logger] +optional = true +version = "0.4" + +[dependencies.log] +optional = true +version = "0.3" + +[dependencies.quasi] +features = ["with-syntex"] +version = "0.29" + +[features] +assert_no_dangling_items = [] +default = ["logging"] +llvm_stable = [] +logging = ["env_logger", "log"] +static = [] +# This feature only exists for CI -- don't use it! +docs_ = [] diff --git a/bash-5.1/vendor/bindgen/LICENSE b/bash-5.1/vendor/bindgen/LICENSE new file mode 100644 index 0000000..589b532 --- /dev/null +++ b/bash-5.1/vendor/bindgen/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2013, Jyun-Yan You + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the author nor the names of his contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/bash-5.1/vendor/bindgen/README.md b/bash-5.1/vendor/bindgen/README.md new file mode 100644 index 0000000..f0104fc --- /dev/null +++ b/bash-5.1/vendor/bindgen/README.md @@ -0,0 +1,227 @@ +# `bindgen` + +Automatically generates Rust FFI bindings to C and C++ libraries. + + + + + +- [Usage](#usage) + - [Requirements](#requirements) + - [Installing Clang 3.9](#installing-clang-39) + - [Windows](#windows) + - [OSX](#osx) + - [Debian-based Linuxes](#debian-based-linuxes) + - [Arch](#arch) + - [From source](#from-source) + - [Library usage with `build.rs`](#library-usage-with-buildrs) + - [`build.rs` Tutorial](#buildrs-tutorial) + - [Simple Example: `./bindgen-integration`](#simple-example-bindgen-integration) + - [Real World Example: Stylo](#real-world-example-stylo) + - [Command Line Usage](#command-line-usage) + - [C++](#c) + - [Annotations](#annotations) + - [`opaque`](#opaque) + - [`hide`](#hide) + - [`replaces`](#replaces) + - [`nocopy`](#nocopy) + + + +## Usage + +### Requirements + +It is recommended to use Clang 3.9 or greater, however `bindgen` can run with +older Clangs with some features disabled. + +#### Installing Clang 3.9 + +##### Windows + +Download and install the official pre-built binary from +[LLVM download page](http://releases.llvm.org/download.html). + +##### OSX + +If you use Homebrew: + +``` +$ brew install llvm +``` + +If you use MacPorts: + +``` +$ port install clang-3.9 +``` + +##### Debian-based Linuxes + +``` +# apt-get install llvm-3.9-dev libclang-3.9-dev +``` + +Ubuntu 16.10 provides the necessary packages directly. If you are using older +version of Ubuntu or other Debian-based distros, you may need to add the LLVM +repos to get version 3.9. See http://apt.llvm.org/. + +##### Arch + +``` +# pacman -S clang +``` + +##### From source + +If your package manager doesn't yet offer Clang 3.9, you'll need to build from +source. For that, follow the instructions +[here](http://clang.llvm.org/get_started.html). + +Those instructions list optional steps. For bindgen: + +* Checkout and build clang +* Checkout and build the extra-clang-tools +* Checkout and build the compiler-rt +* You do not need to checkout or build libcxx + +### Library usage with `build.rs` + +💡 This is the recommended way to use `bindgen`. 💡 + +#### `build.rs` Tutorial + +[Here is a step-by-step tutorial for generating FFI bindings to the `bzip2` C library.][tutorial] + +[tutorial]: http://fitzgeraldnick.com/2016/12/14/using-libbindgen-in-build-rs.html + +#### Simple Example: `./bindgen-integration` + +The [`./bindgen-integration`][integration] directory has an example crate that +generates FFI bindings in `build.rs` and can be used a template for new +projects. + +[integration]: ./bindgen-integration + +#### Real World Example: Stylo + +A real world example is [the Stylo build script][stylo-script] used for +integrating Servo's layout system into Gecko. + +[stylo-script]: https://github.com/servo/servo/blob/master/components/style/build_gecko.rs + +In `Cargo.toml`: + +```toml +[package] +# ... +build = "build.rs" + +[build-dependencies] +bindgen = "0.20" +``` + +In `build.rs`: + +```rust +extern crate bindgen; + +use std::env; +use std::path::Path; + +fn main() { + let out_dir = env::var("OUT_DIR").unwrap(); + let _ = bindgen::builder() + .header("example.h") + .use_core() + .generate().unwrap() + .write_to_file(Path::new(&out_dir).join("example.rs")); +} +``` + +In `src/main.rs`: + +```rust +include!(concat!(env!("OUT_DIR"), "/example.rs")); +``` + +### Command Line Usage + +``` +$ cargo install bindgen +``` + +There are a few options documented when running `./bindgen --help`. + +### C++ + +`bindgen` can handle most C++ features, but not all of them (C++ is hard!) + +Notable C++ features that are unsupported or only partially supported: + +* Partial template specialization +* Traits templates +* SFINAE +* Instantiating new template specializations + +When passing in header files, the file will automatically be treated as C++ if +it ends in ``.hpp``. If it doesn't, ``-x c++`` can be used to force C++ mode. + +You must use whitelisting when working with C++ to avoid pulling in all of the +`std::*` types, some of which `bindgen` cannot handle. Additionally, you may +want to blacklist other types that `bindgen` stumbles on, or make `bindgen` +treat certain types as opaque. + +### Annotations + +The translation of classes, structs, enums, and typedefs can be adjusted using +annotations. Annotations are specifically formatted html tags inside doxygen +style comments. + +#### `opaque` + +The `opaque` annotation instructs bindgen to ignore all fields defined in +a struct/class. + +```cpp +///

+``` + +#### `hide` + +The `hide` annotation instructs bindgen to ignore the struct/class/field/enum +completely. + +```cpp +///
+``` + +#### `replaces` + +The `replaces` annotation can be used to use a type as a replacement for other +(presumably more complex) type. This is used in Stylo to generate bindings for +structures that for multiple reasons are too complex for bindgen to understand. + +For example, in a C++ header: + +```cpp +/** + *
+ */ +template +class nsTArray_Simple { + T* mBuffer; +public: + // The existence of a destructor here prevents bindgen from deriving the Clone + // trait via a simple memory copy. + ~nsTArray_Simple() {}; +}; +``` + +That way, after code generation, the bindings for the `nsTArray` type are +the ones that would be generated for `nsTArray_Simple`. + +#### `nocopy` + +The `nocopy` annotation is used to prevent bindgen to autoderive the `Copy` +and `Clone` traits for a type. diff --git a/bash-5.1/vendor/bindgen/build.rs b/bash-5.1/vendor/bindgen/build.rs new file mode 100644 index 0000000..c3633cd --- /dev/null +++ b/bash-5.1/vendor/bindgen/build.rs @@ -0,0 +1,58 @@ +mod codegen { + extern crate quasi_codegen; + use std::env; + use std::path::{Path, PathBuf}; + + pub fn main() { + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let src = Path::new("src/codegen/mod.rs"); + let dst = Path::new(&out_dir).join("codegen.rs"); + + quasi_codegen::expand(&src, &dst).unwrap(); + println!("cargo:rerun-if-changed=src/codegen/mod.rs"); + println!("cargo:rerun-if-changed=src/codegen/helpers.rs"); + } +} + +mod testgen { + use std::char; + use std::env; + use std::ffi::OsStr; + use std::fs::{self, File}; + use std::io::Write; + use std::path::{Path, PathBuf}; + + pub fn main() { + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let mut dst = File::create(Path::new(&out_dir).join("tests.rs")).unwrap(); + + println!("cargo:rerun-if-changed=tests/headers"); + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let headers_dir = manifest_dir.join("tests").join("headers"); + + let entries = fs::read_dir(headers_dir) + .expect("Couldn't read headers dir") + .map(|result| result.expect("Couldn't read header file")); + + for entry in entries { + match entry.path().extension().and_then(OsStr::to_str) { + Some("h") | Some("hpp") => { + let func = entry.file_name().to_str().unwrap() + .replace(|c| !char::is_alphanumeric(c), "_") + .replace("__", "_") + .to_lowercase(); + writeln!(dst, "test_header!(header_{}, {:?});", + func, entry.path()).unwrap(); + } + _ => {} + } + } + + dst.flush().unwrap(); + } +} + +fn main() { + codegen::main(); + testgen::main(); +} diff --git a/bash-5.1/vendor/bindgen/ci/before_install.sh b/bash-5.1/vendor/bindgen/ci/before_install.sh new file mode 100644 index 0000000..06c7521 --- /dev/null +++ b/bash-5.1/vendor/bindgen/ci/before_install.sh @@ -0,0 +1,26 @@ +set -e +pushd ~ + +function llvm_version_triple() { + if [ "$1" == "3.8" ]; then + echo "3.8.0" + elif [ "$1" == "3.9" ]; then + echo "3.9.0" + fi +} + +function llvm_download() { + export LLVM_VERSION_TRIPLE=`llvm_version_triple ${LLVM_VERSION}` + export LLVM=clang+llvm-${LLVM_VERSION_TRIPLE}-x86_64-$1 + + wget http://llvm.org/releases/${LLVM_VERSION_TRIPLE}/${LLVM}.tar.xz + mkdir llvm + tar -xf ${LLVM}.tar.xz -C llvm --strip-components=1 + + export LLVM_CONFIG_PATH=`pwd`/llvm/bin/llvm-config +} + +llvm_download linux-gnu-ubuntu-14.04 + +popd +set +e diff --git a/bash-5.1/vendor/bindgen/rustfmt.toml b/bash-5.1/vendor/bindgen/rustfmt.toml new file mode 100644 index 0000000..96d4ae4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/rustfmt.toml @@ -0,0 +1,10 @@ +max_width = 80 +format_strings = false +fn_brace_style = "SameLineWhere" +item_brace_style = "SameLineWhere" +struct_lit_multiline_style = "ForceMulti" +where_trailing_comma = true +reorder_imports = true +reorder_imported_names = true +normalize_comments = false +write_mode = "Overwrite" diff --git a/bash-5.1/vendor/bindgen/src/chooser.rs b/bash-5.1/vendor/bindgen/src/chooser.rs new file mode 100644 index 0000000..51392d7 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/chooser.rs @@ -0,0 +1,26 @@ +//! A public API for more fine-grained customization of bindgen behavior. + +pub use ir::int::IntKind; +pub use ir::enum_ty::{EnumVariantValue, EnumVariantCustomBehavior}; +use std::fmt; + +/// A trait to allow configuring different kinds of types in different +/// situations. +pub trait TypeChooser: fmt::Debug { + /// The integer kind an integer macro should have, given a name and the + /// value of that macro, or `None` if you want the default to be chosen. + fn int_macro(&self, _name: &str, _value: i64) -> Option { + None + } + + /// This function should return whether, given the a given enum variant + /// name, and value, returns whether this enum variant will forcibly be a + /// constant. + fn enum_variant_behavior(&self, + _enum_name: Option<&str>, + _variant_name: &str, + _variant_value: EnumVariantValue) + -> Option { + None + } +} diff --git a/bash-5.1/vendor/bindgen/src/clang.rs b/bash-5.1/vendor/bindgen/src/clang.rs new file mode 100644 index 0000000..9cf5143 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/clang.rs @@ -0,0 +1,1376 @@ +//! A higher level Clang API built on top of the generated bindings in the +//! `clang_sys` module. + +#![allow(non_upper_case_globals, dead_code)] + + +use cexpr; +use clang_sys::*; +use std::{mem, ptr, slice}; +use std::ffi::{CStr, CString}; +use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; +use std::os::raw::{c_char, c_int, c_uint, c_ulong}; + +/// A cursor into the Clang AST, pointing to an AST node. +/// +/// We call the AST node pointed to by the cursor the cursor's "referent". +#[derive(Copy, Clone)] +pub struct Cursor { + x: CXCursor, +} + +impl fmt::Debug for Cursor { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, + "Cursor({} kind: {}, loc: {}, usr: {:?})", + self.spelling(), + kind_to_str(self.kind()), + self.location(), + self.usr()) + } +} + +impl Cursor { + /// Get the Unified Symbol Resolution for this cursor's referent, if + /// available. + /// + /// The USR can be used to compare entities across translation units. + pub fn usr(&self) -> Option { + let s = unsafe { cxstring_into_string(clang_getCursorUSR(self.x)) }; + if s.is_empty() { None } else { Some(s) } + } + + /// Is this cursor's referent a declaration? + pub fn is_declaration(&self) -> bool { + unsafe { clang_isDeclaration(self.kind()) != 0 } + } + + /// Get the null cursor, which has no referent. + pub fn null() -> Self { + Cursor { + x: unsafe { clang_getNullCursor() }, + } + } + + /// Get this cursor's referent's spelling. + pub fn spelling(&self) -> String { + unsafe { cxstring_into_string(clang_getCursorSpelling(self.x)) } + } + + /// Get this cursor's referent's display name. + /// + /// This is not necessarily a valid identifier. It includes extra + /// information, such as parameters for a function, etc. + pub fn display_name(&self) -> String { + unsafe { cxstring_into_string(clang_getCursorDisplayName(self.x)) } + } + + /// Get the mangled name of this cursor's referent. + pub fn mangling(&self) -> String { + unsafe { cxstring_into_string(clang_Cursor_getMangling(self.x)) } + } + + /// Get the `Cursor` for this cursor's referent's lexical parent. + /// + /// The lexical parent is the parent of the definition. The semantic parent + /// is the parent of the declaration. Generally, the lexical parent doesn't + /// have any effect on semantics, while the semantic parent does. + /// + /// In the following snippet, the `Foo` class would be the semantic parent + /// of the out-of-line `method` definition, while the lexical parent is the + /// translation unit. + /// + /// ```c++ + /// class Foo { + /// void method(); + /// }; + /// + /// void Foo::method() { /* ... */ } + /// ``` + pub fn lexical_parent(&self) -> Cursor { + unsafe { + Cursor { + x: clang_getCursorLexicalParent(self.x), + } + } + } + + /// Get the referent's semantic parent, if one is available. + /// + /// See documentation for `lexical_parent` for details on semantic vs + /// lexical parents. + pub fn fallible_semantic_parent(&self) -> Option { + let sp = unsafe { + Cursor { + x: clang_getCursorSemanticParent(self.x), + } + }; + if sp == *self || !sp.is_valid() { + return None; + } + Some(sp) + } + + /// Get the referent's semantic parent. + /// + /// See documentation for `lexical_parent` for details on semantic vs + /// lexical parents. + pub fn semantic_parent(&self) -> Cursor { + self.fallible_semantic_parent().unwrap() + } + + /// Return the number of template arguments used by this cursor's referent, + /// if the referent is either a template specialization or + /// declaration. Returns -1 otherwise. + /// + /// NOTE: This may not return `Some` for some non-fully specialized + /// templates, see #193 and #194. + pub fn num_template_args(&self) -> Option { + let n: c_int = unsafe { clang_Cursor_getNumTemplateArguments(self.x) }; + + if n >= 0 { + Some(n as u32) + } else { + debug_assert_eq!(n, -1); + None + } + } + + /// Get a cursor pointing to this referent's containing translation unit. + /// + /// Note that we shouldn't create a `TranslationUnit` struct here, because + /// bindgen assumes there will only be one of them alive at a time, and + /// disposes it on drop. That can change if this would be required, but I + /// think we can survive fine without it. + pub fn translation_unit(&self) -> Cursor { + assert!(self.is_valid()); + unsafe { + let tu = clang_Cursor_getTranslationUnit(self.x); + let cursor = Cursor { + x: clang_getTranslationUnitCursor(tu), + }; + assert!(cursor.is_valid()); + cursor + } + } + + /// Is the referent a top level construct? + pub fn is_toplevel(&self) -> bool { + let mut semantic_parent = self.fallible_semantic_parent(); + + while semantic_parent.is_some() && + (semantic_parent.unwrap().kind() == CXCursor_Namespace || + semantic_parent.unwrap().kind() == CXCursor_NamespaceAlias || + semantic_parent.unwrap().kind() == CXCursor_NamespaceRef) { + semantic_parent = semantic_parent.unwrap() + .fallible_semantic_parent(); + } + + let tu = self.translation_unit(); + // Yes, this can happen with, e.g., macro definitions. + semantic_parent == tu.fallible_semantic_parent() + } + + /// There are a few kinds of types that we need to treat specially, mainly + /// not tracking the type declaration but the location of the cursor, given + /// clang doesn't expose a proper declaration for these types. + pub fn is_template_like(&self) -> bool { + match self.kind() { + CXCursor_ClassTemplate | + CXCursor_ClassTemplatePartialSpecialization | + CXCursor_TypeAliasTemplateDecl => true, + _ => false, + } + } + + /// Get the kind of referent this cursor is pointing to. + pub fn kind(&self) -> CXCursorKind { + unsafe { clang_getCursorKind(self.x) } + } + + /// Returns true is the cursor is a definition + pub fn is_definition(&self) -> bool { + unsafe { clang_isCursorDefinition(self.x) != 0 } + } + + /// Is the referent an anonymous record definition? + pub fn is_anonymous(&self) -> bool { + unsafe { clang_Cursor_isAnonymous(self.x) != 0 } + } + + /// Is the referent a template specialization? + pub fn is_template(&self) -> bool { + self.specialized().is_some() + } + + /// Is the referent a fully specialized template specialization without any + /// remaining free template arguments? + pub fn is_fully_specialized_template(&self) -> bool { + self.is_template() && self.num_template_args().unwrap_or(0) > 0 + } + + /// Is the referent a template specialization that still has remaining free + /// template arguments? + pub fn is_in_non_fully_specialized_template(&self) -> bool { + if self.is_toplevel() { + return false; + } + let parent = self.semantic_parent(); + (parent.is_template() && !parent.is_fully_specialized_template()) || + parent.is_in_non_fully_specialized_template() + } + + /// Is this cursor pointing a valid referent? + pub fn is_valid(&self) -> bool { + unsafe { clang_isInvalid(self.kind()) == 0 } + } + + /// Get the source location for the referent. + pub fn location(&self) -> SourceLocation { + unsafe { + SourceLocation { + x: clang_getCursorLocation(self.x), + } + } + } + + /// Get the source location range for the referent. + pub fn extent(&self) -> CXSourceRange { + unsafe { clang_getCursorExtent(self.x) } + } + + /// Get the raw declaration comment for this referent, if one exists. + pub fn raw_comment(&self) -> Option { + let s = unsafe { + cxstring_into_string(clang_Cursor_getRawCommentText(self.x)) + }; + if s.is_empty() { None } else { Some(s) } + } + + /// Get the referent's parsed comment. + pub fn comment(&self) -> Comment { + unsafe { + Comment { + x: clang_Cursor_getParsedComment(self.x), + } + } + } + + /// Get the referent's type. + pub fn cur_type(&self) -> Type { + unsafe { + Type { + x: clang_getCursorType(self.x), + } + } + } + + /// Given that this cursor's referent is a reference to another type, or is + /// a declaration, get the cursor pointing to the referenced type or type of + /// the declared thing. + pub fn definition(&self) -> Option { + unsafe { + let ret = Cursor { + x: clang_getCursorDefinition(self.x), + }; + + if ret.is_valid() { Some(ret) } else { None } + } + } + + /// Given that this cursor's referent is reference type, get the cursor + /// pointing to the referenced type. + pub fn referenced(&self) -> Option { + unsafe { + let ret = Cursor { + x: clang_getCursorReferenced(self.x), + }; + + if ret.is_valid() { Some(ret) } else { None } + } + } + + /// Get the canonical cursor for this referent. + /// + /// Many types can be declared multiple times before finally being properly + /// defined. This method allows us to get the canonical cursor for the + /// referent type. + pub fn canonical(&self) -> Cursor { + unsafe { + Cursor { + x: clang_getCanonicalCursor(self.x), + } + } + } + + /// Given that this cursor points to a template specialization, get a cursor + /// pointing to the template definition that is being specialized. + pub fn specialized(&self) -> Option { + unsafe { + let ret = Cursor { + x: clang_getSpecializedCursorTemplate(self.x), + }; + if ret.is_valid() { Some(ret) } else { None } + } + } + + /// Assuming that this cursor's referent is a template declaration, get the + /// kind of cursor that would be generated for its specializations. + pub fn template_kind(&self) -> CXCursorKind { + unsafe { clang_getTemplateCursorKind(self.x) } + } + + /// Traverse this cursor's referent and its children. + /// + /// Call the given function on each AST node traversed. + pub fn visit(&self, mut visitor: Visitor) + where Visitor: FnMut(Cursor) -> CXChildVisitResult, + { + unsafe { + clang_visitChildren(self.x, + visit_children::, + mem::transmute(&mut visitor)); + } + } + + /// Returns whether the given location contains a cursor with the given + /// kind in the first level of nesting underneath (doesn't look + /// recursively). + pub fn contains_cursor(&self, kind: CXCursorKind) -> bool { + let mut found = false; + + self.visit(|c| { + if c.kind() == kind { + found = true; + CXChildVisit_Break + } else { + CXChildVisit_Continue + } + }); + + found + } + + /// Is the referent an inlined function? + pub fn is_inlined_function(&self) -> bool { + clang_Cursor_isFunctionInlined::is_loaded() && + unsafe { clang_Cursor_isFunctionInlined(self.x) != 0 } + } + + /// Get the width of this cursor's referent bit field, or `None` if the + /// referent is not a bit field. + pub fn bit_width(&self) -> Option { + unsafe { + let w = clang_getFieldDeclBitWidth(self.x); + if w == -1 { None } else { Some(w as u32) } + } + } + + /// Get the integer representation type used to hold this cursor's referent + /// enum type. + pub fn enum_type(&self) -> Option { + unsafe { + let t = Type { + x: clang_getEnumDeclIntegerType(self.x), + }; + if t.is_valid() { Some(t) } else { None } + } + } + + /// Get the signed constant value for this cursor's enum variant referent. + /// + /// Returns None if the cursor's referent is not an enum variant. + pub fn enum_val_signed(&self) -> Option { + unsafe { + if self.kind() == CXCursor_EnumConstantDecl { + Some(clang_getEnumConstantDeclValue(self.x) as i64) + } else { + None + } + } + } + + /// Get the unsigned constant value for this cursor's enum variant referent. + /// + /// Returns None if the cursor's referent is not an enum variant. + pub fn enum_val_unsigned(&self) -> Option { + unsafe { + if self.kind() == CXCursor_EnumConstantDecl { + Some(clang_getEnumConstantDeclUnsignedValue(self.x) as u64) + } else { + None + } + } + } + + /// Given that this cursor's referent is a `typedef`, get the `Type` that is + /// being aliased. + pub fn typedef_type(&self) -> Option { + let inner = Type { + x: unsafe { clang_getTypedefDeclUnderlyingType(self.x) }, + }; + + if inner.is_valid() { Some(inner) } else { None } + } + + /// Get the linkage kind for this cursor's referent. + /// + /// This only applies to functions and variables. + pub fn linkage(&self) -> CXLinkageKind { + unsafe { clang_getCursorLinkage(self.x) } + } + + /// Get the visibility of this cursor's referent. + pub fn visibility(&self) -> CXVisibilityKind { + unsafe { clang_getCursorVisibility(self.x) } + } + + /// Given that this cursor's referent is a function, return cursors to its + /// parameters. + pub fn args(&self) -> Option> { + // XXX: We might want to use and keep num_args + // match self.kind() { + // CXCursor_FunctionDecl | + // CXCursor_CXXMethod => { + unsafe { + let w = clang_Cursor_getNumArguments(self.x); + if w == -1 { + None + } else { + let num = w as u32; + + let mut args = vec![]; + for i in 0..num { + args.push(Cursor { + x: clang_Cursor_getArgument(self.x, i as c_uint), + }); + } + Some(args) + } + } + } + + /// Given that this cursor's referent is a function/method call or + /// declaration, return the number of arguments it takes. + /// + /// Returns -1 if the cursor's referent is not a function/method call or + /// declaration. + pub fn num_args(&self) -> Result { + unsafe { + let w = clang_Cursor_getNumArguments(self.x); + if w == -1 { Err(()) } else { Ok(w as u32) } + } + } + + /// Get the access specifier for this cursor's referent. + pub fn access_specifier(&self) -> CX_CXXAccessSpecifier { + unsafe { clang_getCXXAccessSpecifier(self.x) } + } + + /// Is this cursor's referent a field declaration that is marked as + /// `mutable`? + pub fn is_mutable_field(&self) -> bool { + unsafe { clang_CXXField_isMutable(self.x) != 0 } + } + + /// Is this cursor's referent a member function that is declared `static`? + pub fn method_is_static(&self) -> bool { + unsafe { clang_CXXMethod_isStatic(self.x) != 0 } + } + + /// Is this cursor's referent a member function that is declared `const`? + pub fn method_is_const(&self) -> bool { + unsafe { clang_CXXMethod_isConst(self.x) != 0 } + } + + /// Is this cursor's referent a member function that is declared `const`? + pub fn method_is_virtual(&self) -> bool { + unsafe { clang_CXXMethod_isVirtual(self.x) != 0 } + } + + /// Is this cursor's referent a struct or class with virtual members? + pub fn is_virtual_base(&self) -> bool { + unsafe { clang_isVirtualBase(self.x) != 0 } + } + + /// Try to evaluate this cursor. + pub fn evaluate(&self) -> Option { + EvalResult::new(*self) + } +} + +extern "C" fn visit_children(cur: CXCursor, + _parent: CXCursor, + data: CXClientData) + -> CXChildVisitResult + where Visitor: FnMut(Cursor) -> CXChildVisitResult, +{ + let func: &mut Visitor = unsafe { mem::transmute(data) }; + let child = Cursor { + x: cur, + }; + + (*func)(child) +} + +impl PartialEq for Cursor { + fn eq(&self, other: &Cursor) -> bool { + unsafe { clang_equalCursors(self.x, other.x) == 1 } + } +} + +impl Eq for Cursor {} + +impl Hash for Cursor { + fn hash(&self, state: &mut H) { + unsafe { clang_hashCursor(self.x) }.hash(state) + } +} + +/// The type of a node in clang's AST. +#[derive(Clone)] +pub struct Type { + x: CXType, +} + +impl PartialEq for Type { + fn eq(&self, other: &Self) -> bool { + unsafe { clang_equalTypes(self.x, other.x) != 0 } + } +} + +impl Eq for Type {} + +impl fmt::Debug for Type { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, + "Type({}, kind: {}, decl: {:?}, canon: {:?})", + self.spelling(), + type_to_str(self.kind()), + self.declaration(), + self.declaration().canonical()) + } +} + +/// An error about the layout of a struct, class, or type. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum LayoutError { + /// Asked for the layout of an invalid type. + Invalid, + /// Asked for the layout of an incomplete type. + Incomplete, + /// Asked for the layout of a dependent type. + Dependent, + /// Asked for the layout of a type that does not have constant size. + NotConstantSize, + /// Asked for the layout of a field in a type that does not have such a + /// field. + InvalidFieldName, + /// An unknown layout error. + Unknown, +} + +impl ::std::convert::From for LayoutError { + fn from(val: i32) -> Self { + use self::LayoutError::*; + let val = match CXTypeLayoutError::from_raw(val) { + Some(val) => val, + None => return Unknown, + }; + + match val { + CXTypeLayoutError_Invalid => Invalid, + CXTypeLayoutError_Incomplete => Incomplete, + CXTypeLayoutError_Dependent => Dependent, + CXTypeLayoutError_NotConstantSize => NotConstantSize, + CXTypeLayoutError_InvalidFieldName => InvalidFieldName, + _ => Unknown, + } + } +} + +impl Type { + /// Get this type's kind. + pub fn kind(&self) -> CXTypeKind { + self.x.kind + } + + /// Get a cursor pointing to this type's declaration. + pub fn declaration(&self) -> Cursor { + unsafe { + Cursor { + x: clang_getTypeDeclaration(self.x), + } + } + } + + /// Get a raw display name for this type. + pub fn spelling(&self) -> String { + unsafe { cxstring_into_string(clang_getTypeSpelling(self.x)) } + } + + /// Is this type const qualified? + pub fn is_const(&self) -> bool { + unsafe { clang_isConstQualifiedType(self.x) != 0 } + } + + /// What is the size of this type? Paper over invalid types by returning `0` + /// for them. + pub fn size(&self) -> usize { + unsafe { + let val = clang_Type_getSizeOf(self.x); + if val < 0 { 0 } else { val as usize } + } + } + + /// What is the size of this type? + pub fn fallible_size(&self) -> Result { + let val = unsafe { clang_Type_getSizeOf(self.x) }; + if val < 0 { + Err(LayoutError::from(val as i32)) + } else { + Ok(val as usize) + } + } + + /// What is the alignment of this type? Paper over invalid types by + /// returning `0`. + pub fn align(&self) -> usize { + unsafe { + let val = clang_Type_getAlignOf(self.x); + if val < 0 { 0 } else { val as usize } + } + } + + /// What is the alignment of this type? + pub fn fallible_align(&self) -> Result { + unsafe { + let val = clang_Type_getAlignOf(self.x); + if val < 0 { + Err(LayoutError::from(val as i32)) + } else { + Ok(val as usize) + } + } + } + + /// Get the layout for this type, or an error describing why it does not + /// have a valid layout. + pub fn fallible_layout(&self) -> Result<::ir::layout::Layout, LayoutError> { + use ir::layout::Layout; + let size = try!(self.fallible_size()); + let align = try!(self.fallible_align()); + Ok(Layout::new(size, align)) + } + + /// If this type is a class template specialization, return its + /// template arguments. Otherwise, return None. + pub fn template_args(&self) -> Option { + let n = unsafe { clang_Type_getNumTemplateArguments(self.x) }; + if n >= 0 { + Some(TypeTemplateArgIterator { + x: self.x, + length: n as u32, + index: 0, + }) + } else { + debug_assert_eq!(n, -1); + None + } + } + + /// Given that this type is a pointer type, return the type that it points + /// to. + pub fn pointee_type(&self) -> Option { + match self.kind() { + CXType_Pointer | + CXType_RValueReference | + CXType_LValueReference | + CXType_MemberPointer => { + let ret = Type { + x: unsafe { clang_getPointeeType(self.x) }, + }; + debug_assert!(ret.is_valid()); + Some(ret) + } + _ => None, + } + } + + /// Given that this type is an array, vector, or complex type, return the + /// type of its elements. + pub fn elem_type(&self) -> Option { + let current_type = Type { + x: unsafe { clang_getElementType(self.x) }, + }; + if current_type.is_valid() { + Some(current_type) + } else { + None + } + } + + /// Given that this type is an array or vector type, return its number of + /// elements. + pub fn num_elements(&self) -> Option { + let num_elements_returned = unsafe { clang_getNumElements(self.x) }; + if num_elements_returned != -1 { + Some(num_elements_returned as usize) + } else { + None + } + } + + /// Get the canonical version of this type. This sees through `typdef`s and + /// aliases to get the underlying, canonical type. + pub fn canonical_type(&self) -> Type { + unsafe { + Type { + x: clang_getCanonicalType(self.x), + } + } + } + + /// Is this type a variadic function type? + pub fn is_variadic(&self) -> bool { + unsafe { clang_isFunctionTypeVariadic(self.x) != 0 } + } + + /// Given that this type is a function type, get the type of its return + /// value. + pub fn ret_type(&self) -> Option { + let rt = Type { + x: unsafe { clang_getResultType(self.x) }, + }; + if rt.is_valid() { Some(rt) } else { None } + } + + /// Given that this type is a function type, get its calling convention. If + /// this is not a function type, `CXCallingConv_Invalid` is returned. + pub fn call_conv(&self) -> CXCallingConv { + unsafe { clang_getFunctionTypeCallingConv(self.x) } + } + + /// For elaborated types (types which use `class`, `struct`, or `union` to + /// disambiguate types from local bindings), get the underlying type. + pub fn named(&self) -> Type { + unsafe { + Type { + x: clang_Type_getNamedType(self.x), + } + } + } + + /// Is this a valid type? + pub fn is_valid(&self) -> bool { + self.kind() != CXType_Invalid + } + + /// Is this a valid and exposed type? + pub fn is_valid_and_exposed(&self) -> bool { + self.is_valid() && self.kind() != CXType_Unexposed + } + + /// Is this type a fully specialized template? + pub fn is_fully_specialized_template(&self) -> bool { + // Yep, the spelling of this containing type-parameter is extremely + // nasty... But can happen in . Unfortunately I couldn't + // reduce it enough :( + !self.spelling().contains("type-parameter") && + self.template_args() + .map_or(false, |mut args| { + args.len() > 0 && + !args.any(|t| t.spelling().contains("type-parameter")) + }) + } +} + +/// An iterator for a type's template arguments. +pub struct TypeTemplateArgIterator { + x: CXType, + length: u32, + index: u32, +} + +impl Iterator for TypeTemplateArgIterator { + type Item = Type; + fn next(&mut self) -> Option { + if self.index < self.length { + let idx = self.index as c_uint; + self.index += 1; + Some(Type { + x: unsafe { clang_Type_getTemplateArgumentAsType(self.x, idx) }, + }) + } else { + None + } + } +} + +impl ExactSizeIterator for TypeTemplateArgIterator { + fn len(&self) -> usize { + assert!(self.index <= self.length); + (self.length - self.index) as usize + } +} + +/// A `SourceLocation` is a file, line, column, and byte offset location for +/// some source text. +pub struct SourceLocation { + x: CXSourceLocation, +} + +impl SourceLocation { + /// Get the (file, line, column, byte offset) tuple for this source + /// location. + pub fn location(&self) -> (File, usize, usize, usize) { + unsafe { + let mut file = mem::zeroed(); + let mut line = 0; + let mut col = 0; + let mut off = 0; + clang_getSpellingLocation(self.x, + &mut file, + &mut line, + &mut col, + &mut off); + (File { + x: file, + }, + line as usize, + col as usize, + off as usize) + } + } +} + +impl fmt::Display for SourceLocation { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let (file, line, col, _) = self.location(); + if let Some(name) = file.name() { + write!(f, "{}:{}:{}", name, line, col) + } else { + "builtin definitions".fmt(f) + } + } +} + +/// A comment in the source text. +/// +/// Comments are sort of parsed by Clang, and have a tree structure. +pub struct Comment { + x: CXComment, +} + +impl Comment { + /// What kind of comment is this? + pub fn kind(&self) -> CXCommentKind { + unsafe { clang_Comment_getKind(self.x) } + } + + /// Get this comment's children comment + pub fn get_children(&self) -> CommentChildrenIterator { + CommentChildrenIterator { + parent: self.x, + length: unsafe { clang_Comment_getNumChildren(self.x) }, + index: 0, + } + } + + /// Given that this comment is the start or end of an HTML tag, get its tag + /// name. + pub fn get_tag_name(&self) -> String { + unsafe { cxstring_into_string(clang_HTMLTagComment_getTagName(self.x)) } + } + + /// Given that this comment is an HTML start tag, get its attributes. + pub fn get_tag_attrs(&self) -> CommentAttributesIterator { + CommentAttributesIterator { + x: self.x, + length: unsafe { clang_HTMLStartTag_getNumAttrs(self.x) }, + index: 0, + } + } +} + +/// An iterator for a comment's children +pub struct CommentChildrenIterator { + parent: CXComment, + length: c_uint, + index: c_uint, +} + +impl Iterator for CommentChildrenIterator { + type Item = Comment; + fn next(&mut self) -> Option { + if self.index < self.length { + let idx = self.index; + self.index += 1; + Some(Comment { + x: unsafe { clang_Comment_getChild(self.parent, idx) }, + }) + } else { + None + } + } +} + +/// An HTML start tag comment attribute +pub struct CommentAttribute { + /// HTML start tag attribute name + pub name: String, + /// HTML start tag attribute value + pub value: String, +} + +/// An iterator for a comment's attributes +pub struct CommentAttributesIterator { + x: CXComment, + length: c_uint, + index: c_uint, +} + +impl Iterator for CommentAttributesIterator { + type Item = CommentAttribute; + fn next(&mut self) -> Option { + if self.index < self.length { + let idx = self.index; + self.index += 1; + Some(CommentAttribute { + name: unsafe { + cxstring_into_string( + clang_HTMLStartTag_getAttrName(self.x, idx)) + }, + value: unsafe { + cxstring_into_string( + clang_HTMLStartTag_getAttrValue(self.x, idx)) + }, + }) + } else { + None + } + } +} + +/// A source file. +pub struct File { + x: CXFile, +} + +impl File { + /// Get the name of this source file. + pub fn name(&self) -> Option { + if self.x.is_null() { + return None; + } + Some(unsafe { cxstring_into_string(clang_getFileName(self.x)) }) + } +} + +fn cxstring_into_string(s: CXString) -> String { + if s.data.is_null() { + return "".to_owned(); + } + unsafe { + let c_str = CStr::from_ptr(clang_getCString(s) as *const _); + let ret = c_str.to_string_lossy().into_owned(); + clang_disposeString(s); + ret + } +} + +/// An `Index` is an environment for a set of translation units that will +/// typically end up linked together in one final binary. +pub struct Index { + x: CXIndex, +} + +impl Index { + /// Construct a new `Index`. + /// + /// The `pch` parameter controls whether declarations in pre-compiled + /// headers are included when enumerating a translation unit's "locals". + /// + /// The `diag` parameter controls whether debugging diagnostics are enabled. + pub fn new(pch: bool, diag: bool) -> Index { + unsafe { + Index { + x: clang_createIndex(pch as c_int, diag as c_int), + } + } + } +} + +impl fmt::Debug for Index { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "Index {{ }}") + } +} + +impl Drop for Index { + fn drop(&mut self) { + unsafe { + clang_disposeIndex(self.x); + } + } +} + +/// A token emitted by clang's lexer. +#[derive(Debug)] +pub struct Token { + /// The kind of token this is. + pub kind: CXTokenKind, + /// A display name for this token. + pub spelling: String, +} + +/// A translation unit (or "compilation unit"). +pub struct TranslationUnit { + x: CXTranslationUnit, +} + +impl fmt::Debug for TranslationUnit { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "TranslationUnit {{ }}") + } +} + +impl TranslationUnit { + /// Parse a source file into a translation unit. + pub fn parse(ix: &Index, + file: &str, + cmd_args: &[String], + unsaved: &[UnsavedFile], + opts: CXTranslationUnit_Flags) + -> Option { + let fname = CString::new(file).unwrap(); + let _c_args: Vec = + cmd_args.iter().map(|s| CString::new(s.clone()).unwrap()).collect(); + let c_args: Vec<*const c_char> = + _c_args.iter().map(|s| s.as_ptr()).collect(); + let mut c_unsaved: Vec = + unsaved.iter().map(|f| f.x).collect(); + let tu = unsafe { + clang_parseTranslationUnit(ix.x, + fname.as_ptr(), + c_args.as_ptr(), + c_args.len() as c_int, + c_unsaved.as_mut_ptr(), + c_unsaved.len() as c_uint, + opts) + }; + if tu.is_null() { + None + } else { + Some(TranslationUnit { + x: tu, + }) + } + } + + /// Get the Clang diagnostic information associated with this translation + /// unit. + pub fn diags(&self) -> Vec { + unsafe { + let num = clang_getNumDiagnostics(self.x) as usize; + let mut diags = vec![]; + for i in 0..num { + diags.push(Diagnostic { + x: clang_getDiagnostic(self.x, i as c_uint), + }); + } + diags + } + } + + /// Get a cursor pointing to the root of this translation unit's AST. + pub fn cursor(&self) -> Cursor { + unsafe { + Cursor { + x: clang_getTranslationUnitCursor(self.x), + } + } + } + + /// Is this the null translation unit? + pub fn is_null(&self) -> bool { + self.x.is_null() + } + + /// Invoke Clang's lexer on this translation unit and get the stream of + /// tokens that come out. + pub fn tokens(&self, cursor: &Cursor) -> Option> { + let range = cursor.extent(); + let mut tokens = vec![]; + unsafe { + let mut token_ptr = ptr::null_mut(); + let mut num_tokens: c_uint = 0; + clang_tokenize(self.x, range, &mut token_ptr, &mut num_tokens); + if token_ptr.is_null() { + return None; + } + + let token_array = slice::from_raw_parts(token_ptr, + num_tokens as usize); + for &token in token_array.iter() { + let kind = clang_getTokenKind(token); + let spelling = + cxstring_into_string(clang_getTokenSpelling(self.x, token)); + + tokens.push(Token { + kind: kind, + spelling: spelling, + }); + } + clang_disposeTokens(self.x, token_ptr, num_tokens); + } + Some(tokens) + } + + /// Convert a set of tokens from clang into `cexpr` tokens, for further + /// processing. + pub fn cexpr_tokens(&self, + cursor: &Cursor) + -> Option> { + use cexpr::token; + + let mut tokens = match self.tokens(cursor) { + Some(tokens) => tokens, + None => return None, + }; + + // FIXME(emilio): LLVM 3.9 at least always include an extra token for no + // good reason (except if we're at EOF). So we do this kind of hack, + // where we skip known-to-cause problems trailing punctuation and + // trailing keywords. + // + // This is sort of unfortunate, though :(. + // + // I'll try to get it fixed in LLVM if I have the time to submit a + // patch. + let mut trim_last_token = false; + if let Some(token) = tokens.last() { + // The starting of the next macro. + trim_last_token |= token.spelling == "#" && + token.kind == CXToken_Punctuation; + + // A following keyword of any kind, like a following declaration. + trim_last_token |= token.kind == CXToken_Keyword; + } + + if trim_last_token { + tokens.pop().unwrap(); + } + + Some(tokens.into_iter() + .filter_map(|token| { + let kind = match token.kind { + CXToken_Punctuation => token::Kind::Punctuation, + CXToken_Literal => token::Kind::Literal, + CXToken_Identifier => token::Kind::Identifier, + CXToken_Keyword => token::Kind::Keyword, + // NB: cexpr is not too happy about comments inside + // expressions, so we strip them down here. + CXToken_Comment => return None, + _ => { + panic!("Found unexpected token kind: {:?}", token.kind) + } + }; + + Some(token::Token { + kind: kind, + raw: token.spelling.into_bytes().into_boxed_slice(), + }) + }) + .collect::>()) + } +} + +impl Drop for TranslationUnit { + fn drop(&mut self) { + unsafe { + clang_disposeTranslationUnit(self.x); + } + } +} + + +/// A diagnostic message generated while parsing a translation unit. +pub struct Diagnostic { + x: CXDiagnostic, +} + +impl Diagnostic { + /// Format this diagnostic message as a string, using the given option bit + /// flags. + pub fn format(&self) -> String { + unsafe { + let opts = clang_defaultDiagnosticDisplayOptions(); + cxstring_into_string(clang_formatDiagnostic(self.x, opts)) + } + } + + /// What is the severity of this diagnostic message? + pub fn severity(&self) -> CXDiagnosticSeverity { + unsafe { clang_getDiagnosticSeverity(self.x) } + } +} + +impl Drop for Diagnostic { + /// Destroy this diagnostic message. + fn drop(&mut self) { + unsafe { + clang_disposeDiagnostic(self.x); + } + } +} + +/// A file which has not been saved to disk. +pub struct UnsavedFile { + x: CXUnsavedFile, + name: CString, + contents: CString, +} + +impl UnsavedFile { + /// Construct a new unsaved file with the given `name` and `contents`. + pub fn new(name: &str, contents: &str) -> UnsavedFile { + let name = CString::new(name).unwrap(); + let contents = CString::new(contents).unwrap(); + let x = CXUnsavedFile { + Filename: name.as_ptr(), + Contents: contents.as_ptr(), + Length: contents.as_bytes().len() as c_ulong, + }; + UnsavedFile { + x: x, + name: name, + contents: contents, + } + } +} + +/// Convert a cursor kind into a static string. +pub fn kind_to_str(x: CXCursorKind) -> String { + unsafe { cxstring_into_string(clang_getCursorKindSpelling(x)) } +} + +/// Convert a type kind to a static string. +pub fn type_to_str(x: CXTypeKind) -> String { + unsafe { cxstring_into_string(clang_getTypeKindSpelling(x)) } +} + +/// Dump the Clang AST to stdout for debugging purposes. +pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { + fn print_indent(depth: isize, s: &str) { + for _ in 0..depth { + print!("\t"); + } + println!("{}", s); + } + + print_indent(depth, + &format!("(kind: {}, spelling: {}, type: {}", + kind_to_str(c.kind()), + c.spelling(), + type_to_str(c.cur_type().kind()))); + + // Recurse. + c.visit(|s| ast_dump(&s, depth + 1)); + + print_indent(depth, ")"); + + CXChildVisit_Continue +} + +/// Try to extract the clang version to a string +pub fn extract_clang_version() -> String { + unsafe { cxstring_into_string(clang_getClangVersion()) } +} + +/// A wrapper for the result of evaluating an expression. +#[derive(Debug)] +pub struct EvalResult { + x: CXEvalResult, +} + +impl EvalResult { + /// Evaluate `cursor` and return the result. + pub fn new(cursor: Cursor) -> Option { + if !clang_Cursor_Evaluate::is_loaded() { + return None; + } + + // Clang has an internal assertion we can trigger if we try to evaluate + // a cursor containing a variadic template type reference. Triggering + // the assertion aborts the process, and we don't want that. Clang + // *also* doesn't expose any API for finding variadic vs non-variadic + // template type references, let alone whether a type referenced is a + // template type, instead they seem to show up as type references to an + // unexposed type. Our solution is to just flat out ban all + // `CXType_Unexposed` from evaluation. + let mut found_cant_eval = false; + cursor.visit(|c| { + if c.kind() == CXCursor_TypeRef && + c.cur_type().kind() == CXType_Unexposed { + found_cant_eval = true; + CXChildVisit_Break + } else { + CXChildVisit_Recurse + } + }); + if found_cant_eval { + return None; + } + + Some(EvalResult { + x: unsafe { clang_Cursor_Evaluate(cursor.x) }, + }) + } + + fn kind(&self) -> CXEvalResultKind { + unsafe { clang_EvalResult_getKind(self.x) } + } + + /// Try to get back the result as a double. + pub fn as_double(&self) -> Option { + match self.kind() { + CXEval_Float => { + Some(unsafe { clang_EvalResult_getAsDouble(self.x) } as f64) + } + _ => None, + } + } + + /// Try to get back the result as an integer. + pub fn as_int(&self) -> Option { + match self.kind() { + CXEval_Int => { + Some(unsafe { clang_EvalResult_getAsInt(self.x) } as i32) + } + _ => None, + } + } + + /// Evaluates the expression as a literal string, that may or may not be + /// valid utf-8. + pub fn as_literal_string(&self) -> Option> { + match self.kind() { + CXEval_StrLiteral => { + let ret = unsafe { + CStr::from_ptr(clang_EvalResult_getAsStr(self.x)) + }; + Some(ret.to_bytes().to_vec()) + } + _ => None, + } + } +} + +impl Drop for EvalResult { + fn drop(&mut self) { + unsafe { clang_EvalResult_dispose(self.x) }; + } +} diff --git a/bash-5.1/vendor/bindgen/src/codegen/helpers.rs b/bash-5.1/vendor/bindgen/src/codegen/helpers.rs new file mode 100644 index 0000000..06dadab --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/codegen/helpers.rs @@ -0,0 +1,190 @@ +//! Helpers for code generation that don't need macro expansion. + +use aster; +use ir::layout::Layout; +use syntax::ast; +use syntax::ptr::P; + + +pub mod attributes { + use aster; + use syntax::ast; + + pub fn repr(which: &str) -> ast::Attribute { + aster::AstBuilder::new().attr().list("repr").words(&[which]).build() + } + + pub fn repr_list(which_ones: &[&str]) -> ast::Attribute { + aster::AstBuilder::new().attr().list("repr").words(which_ones).build() + } + + pub fn derives(which_ones: &[&str]) -> ast::Attribute { + aster::AstBuilder::new().attr().list("derive").words(which_ones).build() + } + + pub fn inline() -> ast::Attribute { + aster::AstBuilder::new().attr().word("inline") + } + + pub fn doc(comment: &str) -> ast::Attribute { + aster::AstBuilder::new().attr().doc(comment) + } + + pub fn link_name(name: &str) -> ast::Attribute { + aster::AstBuilder::new().attr().name_value("link_name").str(name) + } +} + +/// Generates a proper type for a field or type with a given `Layout`, that is, +/// a type with the correct size and alignment restrictions. +pub struct BlobTyBuilder { + layout: Layout, +} + +impl BlobTyBuilder { + pub fn new(layout: Layout) -> Self { + BlobTyBuilder { + layout: layout, + } + } + + pub fn build(self) -> P { + let opaque = self.layout.opaque(); + + // FIXME(emilio, #412): We fall back to byte alignment, but there are + // some things that legitimately are more than 8-byte aligned. + // + // Eventually we should be able to `unwrap` here, but... + let ty_name = match opaque.known_rust_type_for_array() { + Some(ty) => ty, + None => { + warn!("Found unknown alignment on code generation!"); + "u8" + } + }; + + let data_len = opaque.array_size().unwrap_or(self.layout.size); + + let inner_ty = aster::AstBuilder::new().ty().path().id(ty_name).build(); + if data_len == 1 { + inner_ty + } else { + aster::ty::TyBuilder::new().array(data_len).build(inner_ty) + } + } +} + +pub mod ast_ty { + use aster; + use ir::context::BindgenContext; + use ir::function::FunctionSig; + use ir::ty::FloatKind; + use syntax::ast; + use syntax::ptr::P; + + pub fn raw_type(ctx: &BindgenContext, name: &str) -> P { + let ident = ctx.rust_ident_raw(&name); + match ctx.options().ctypes_prefix { + Some(ref prefix) => { + let prefix = ctx.rust_ident_raw(prefix); + quote_ty!(ctx.ext_cx(), $prefix::$ident) + } + None => quote_ty!(ctx.ext_cx(), ::std::os::raw::$ident), + } + } + + pub fn float_kind_rust_type(ctx: &BindgenContext, + fk: FloatKind) + -> P { + // TODO: we probably should just take the type layout into + // account? + // + // Also, maybe this one shouldn't be the default? + // + // FIXME: `c_longdouble` doesn't seem to be defined in some + // systems, so we use `c_double` directly. + match (fk, ctx.options().convert_floats) { + (FloatKind::Float, true) => aster::ty::TyBuilder::new().f32(), + (FloatKind::Double, true) | + (FloatKind::LongDouble, true) => aster::ty::TyBuilder::new().f64(), + (FloatKind::Float, false) => raw_type(ctx, "c_float"), + (FloatKind::Double, false) | + (FloatKind::LongDouble, false) => raw_type(ctx, "c_double"), + (FloatKind::Float128, _) => { + aster::ty::TyBuilder::new().array(16).u8() + } + } + } + + pub fn int_expr(val: i64) -> P { + use std::i64; + let expr = aster::AstBuilder::new().expr(); + + // This is not representable as an i64 if it's negative, so we + // special-case it. + // + // Fix in aster incoming. + if val == i64::MIN { + expr.neg().uint(1u64 << 63) + } else { + expr.int(val) + } + } + + pub fn bool_expr(val: bool) -> P { + aster::AstBuilder::new().expr().bool(val) + } + + pub fn byte_array_expr(bytes: &[u8]) -> P { + let mut vec = Vec::with_capacity(bytes.len() + 1); + for byte in bytes { + vec.push(int_expr(*byte as i64)); + } + vec.push(int_expr(0)); + + let kind = ast::ExprKind::Vec(vec); + + aster::AstBuilder::new().expr().build_expr_kind(kind) + } + + pub fn cstr_expr(mut string: String) -> P { + string.push('\0'); + aster::AstBuilder::new() + .expr() + .build_lit(aster::AstBuilder::new().lit().byte_str(string)) + } + + pub fn float_expr(f: f64) -> P { + use aster::symbol::ToSymbol; + let mut string = f.to_string(); + + // So it gets properly recognised as a floating point constant. + if !string.contains('.') { + string.push('.'); + } + + let kind = ast::LitKind::FloatUnsuffixed(string.as_str().to_symbol()); + aster::AstBuilder::new().expr().lit().build_lit(kind) + } + + pub fn arguments_from_signature(signature: &FunctionSig, + ctx: &BindgenContext) + -> Vec> { + // TODO: We need to keep in sync the argument names, so we should unify + // this with the other loop that decides them. + let mut unnamed_arguments = 0; + signature.argument_types() + .iter() + .map(|&(ref name, _ty)| { + let arg_name = match *name { + Some(ref name) => ctx.rust_mangle(name).into_owned(), + None => { + unnamed_arguments += 1; + format!("arg{}", unnamed_arguments) + } + }; + aster::expr::ExprBuilder::new().id(arg_name) + }) + .collect::>() + } +} diff --git a/bash-5.1/vendor/bindgen/src/codegen/mod.rs b/bash-5.1/vendor/bindgen/src/codegen/mod.rs new file mode 100644 index 0000000..7af70e9 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/codegen/mod.rs @@ -0,0 +1,2434 @@ +mod helpers; + +use aster; + +use ir::annotations::FieldAccessorKind; +use ir::comp::{Base, CompInfo, CompKind, Field, Method, MethodKind}; +use ir::context::{BindgenContext, ItemId}; +use ir::derive::{CanDeriveCopy, CanDeriveDebug}; +use ir::enum_ty::{Enum, EnumVariant, EnumVariantValue}; +use ir::function::{Function, FunctionSig}; +use ir::int::IntKind; +use ir::item::{Item, ItemAncestors, ItemCanonicalName, ItemCanonicalPath}; +use ir::item_kind::ItemKind; +use ir::layout::Layout; +use ir::module::Module; +use ir::ty::{Type, TypeKind}; +use ir::type_collector::ItemSet; +use ir::var::Var; +use self::helpers::{BlobTyBuilder, attributes}; + +use std::borrow::Cow; +use std::cell::Cell; +use std::collections::{HashSet, VecDeque}; +use std::collections::hash_map::{Entry, HashMap}; +use std::fmt::Write; +use std::mem; +use std::ops; +use syntax::abi::Abi; +use syntax::ast; +use syntax::codemap::{Span, respan}; +use syntax::ptr::P; + +fn root_import_depth(ctx: &BindgenContext, item: &Item) -> usize { + if !ctx.options().enable_cxx_namespaces { + return 0; + } + + item.ancestors(ctx) + .filter(|id| ctx.resolve_item(*id).is_module()) + .fold(1, |i, _| i + 1) +} + +fn top_level_path(ctx: &BindgenContext, item: &Item) -> Vec { + let mut path = vec![ctx.rust_ident_raw("self")]; + + if ctx.options().enable_cxx_namespaces { + let super_ = ctx.rust_ident_raw("super"); + + for _ in 0..root_import_depth(ctx, item) { + path.push(super_.clone()); + } + } + + path +} + +fn root_import(ctx: &BindgenContext, module: &Item) -> P { + assert!(ctx.options().enable_cxx_namespaces, "Somebody messed it up"); + assert!(module.is_module()); + + let mut path = top_level_path(ctx, module); + + let root = ctx.root_module().canonical_name(ctx); + let root_ident = ctx.rust_ident(&root); + path.push(root_ident); + + let use_root = aster::AstBuilder::new() + .item() + .use_() + .ids(path) + .build() + .build(); + + quote_item!(ctx.ext_cx(), #[allow(unused_imports)] $use_root).unwrap() +} + +struct CodegenResult<'a> { + items: Vec>, + + /// A monotonic counter used to add stable unique id's to stuff that doesn't + /// need to be referenced by anything. + codegen_id: &'a Cell, + + /// Whether an union has been generated at least once. + saw_union: bool, + + items_seen: HashSet, + /// The set of generated function/var names, needed because in C/C++ is + /// legal to do something like: + /// + /// ```c++ + /// extern "C" { + /// void foo(); + /// extern int bar; + /// } + /// + /// extern "C" { + /// void foo(); + /// extern int bar; + /// } + /// ``` + /// + /// Being these two different declarations. + functions_seen: HashSet, + vars_seen: HashSet, + + /// Used for making bindings to overloaded functions. Maps from a canonical + /// function name to the number of overloads we have already codegen'd for + /// that name. This lets us give each overload a unique suffix. + overload_counters: HashMap, +} + +impl<'a> CodegenResult<'a> { + fn new(codegen_id: &'a Cell) -> Self { + CodegenResult { + items: vec![], + saw_union: false, + codegen_id: codegen_id, + items_seen: Default::default(), + functions_seen: Default::default(), + vars_seen: Default::default(), + overload_counters: Default::default(), + } + } + + fn next_id(&mut self) -> usize { + self.codegen_id.set(self.codegen_id.get() + 1); + self.codegen_id.get() + } + + fn saw_union(&mut self) { + self.saw_union = true; + } + + fn seen(&self, item: ItemId) -> bool { + self.items_seen.contains(&item) + } + + fn set_seen(&mut self, item: ItemId) { + self.items_seen.insert(item); + } + + fn seen_function(&self, name: &str) -> bool { + self.functions_seen.contains(name) + } + + fn saw_function(&mut self, name: &str) { + self.functions_seen.insert(name.into()); + } + + /// Get the overload number for the given function name. Increments the + /// counter internally so the next time we ask for the overload for this + /// name, we get the incremented value, and so on. + fn overload_number(&mut self, name: &str) -> u32 { + let mut counter = + self.overload_counters.entry(name.into()).or_insert(0); + let number = *counter; + *counter += 1; + number + } + + fn seen_var(&self, name: &str) -> bool { + self.vars_seen.contains(name) + } + + fn saw_var(&mut self, name: &str) { + self.vars_seen.insert(name.into()); + } + + fn inner(&mut self, cb: F) -> Vec> + where F: FnOnce(&mut Self), + { + let mut new = Self::new(self.codegen_id); + + cb(&mut new); + + self.saw_union |= new.saw_union; + + new.items + } +} + +impl<'a> ops::Deref for CodegenResult<'a> { + type Target = Vec>; + + fn deref(&self) -> &Self::Target { + &self.items + } +} + +impl<'a> ops::DerefMut for CodegenResult<'a> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.items + } +} + +struct ForeignModBuilder { + inner: ast::ForeignMod, +} + +impl ForeignModBuilder { + fn new(abi: Abi) -> Self { + ForeignModBuilder { + inner: ast::ForeignMod { + abi: abi, + items: vec![], + }, + } + } + + fn with_foreign_item(mut self, item: ast::ForeignItem) -> Self { + self.inner.items.push(item); + self + } + + #[allow(dead_code)] + fn with_foreign_items(mut self, items: I) -> Self + where I: IntoIterator, + { + self.inner.items.extend(items.into_iter()); + self + } + + fn build(self, ctx: &BindgenContext) -> P { + use syntax::codemap::DUMMY_SP; + P(ast::Item { + ident: ctx.rust_ident(""), + id: ast::DUMMY_NODE_ID, + node: ast::ItemKind::ForeignMod(self.inner), + vis: ast::Visibility::Public, + attrs: vec![], + span: DUMMY_SP, + }) + } +} + +/// A trait to convert a rust type into a pointer, optionally const, to the same +/// type. +/// +/// This is done due to aster's lack of pointer builder, I guess I should PR +/// there. +trait ToPtr { + fn to_ptr(self, is_const: bool, span: Span) -> P; +} + +impl ToPtr for P { + fn to_ptr(self, is_const: bool, span: Span) -> Self { + let ty = ast::TyKind::Ptr(ast::MutTy { + ty: self, + mutbl: if is_const { + ast::Mutability::Immutable + } else { + ast::Mutability::Mutable + }, + }); + P(ast::Ty { + id: ast::DUMMY_NODE_ID, + node: ty, + span: span, + }) + } +} + +trait CodeGenerator { + /// Extra information from the caller. + type Extra; + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + extra: &Self::Extra); +} + +impl CodeGenerator for Item { + type Extra = (); + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + _extra: &()) { + if self.is_hidden(ctx) || result.seen(self.id()) { + debug!("::codegen: Ignoring hidden or seen: \ + self = {:?}", self); + return; + } + + debug!("::codegen: self = {:?}", self); + if !whitelisted_items.contains(&self.id()) { + // TODO(emilio, #453): Figure out what to do when this happens + // legitimately, we could track the opaque stuff and disable the + // assertion there I guess. + error!("Found non-whitelisted item in code generation: {:?}", self); + } + + result.set_seen(self.id()); + + match *self.kind() { + ItemKind::Module(ref module) => { + module.codegen(ctx, result, whitelisted_items, self); + } + ItemKind::Function(ref fun) => { + if ctx.options().codegen_config.functions { + fun.codegen(ctx, result, whitelisted_items, self); + } + } + ItemKind::Var(ref var) => { + if ctx.options().codegen_config.vars { + var.codegen(ctx, result, whitelisted_items, self); + } + } + ItemKind::Type(ref ty) => { + if ctx.options().codegen_config.types { + ty.codegen(ctx, result, whitelisted_items, self); + } + } + } + } +} + +impl CodeGenerator for Module { + type Extra = Item; + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + item: &Item) { + debug!("::codegen: item = {:?}", item); + + let codegen_self = |result: &mut CodegenResult, + found_any: &mut bool| { + for child in self.children() { + if whitelisted_items.contains(child) { + *found_any = true; + ctx.resolve_item(*child) + .codegen(ctx, result, whitelisted_items, &()); + } + } + + if item.id() == ctx.root_module() { + let saw_union = result.saw_union; + if saw_union && !ctx.options().unstable_rust { + utils::prepend_union_types(ctx, &mut *result); + } + if ctx.need_bindegen_complex_type() { + utils::prepend_complex_type(ctx, &mut *result); + } + } + }; + + if !ctx.options().enable_cxx_namespaces || + (self.is_inline() && !ctx.options().conservative_inline_namespaces) { + codegen_self(result, &mut false); + return; + } + + let mut found_any = false; + let inner_items = result.inner(|result| { + result.push(root_import(ctx, item)); + codegen_self(result, &mut found_any); + }); + + // Don't bother creating an empty module. + if !found_any { + return; + } + + let module = ast::ItemKind::Mod(ast::Mod { + inner: ctx.span(), + items: inner_items, + }); + + let name = item.canonical_name(ctx); + let item = aster::AstBuilder::new() + .item() + .pub_() + .build_item_kind(name, module); + + result.push(item); + } +} + +impl CodeGenerator for Var { + type Extra = Item; + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + _whitelisted_items: &ItemSet, + item: &Item) { + use ir::var::VarType; + debug!("::codegen: item = {:?}", item); + + let canonical_name = item.canonical_name(ctx); + + if result.seen_var(&canonical_name) { + return; + } + result.saw_var(&canonical_name); + + let ty = self.ty().to_rust_ty(ctx); + + if let Some(val) = self.val() { + let const_item = aster::AstBuilder::new() + .item() + .pub_() + .const_(canonical_name) + .expr(); + let item = match *val { + VarType::Bool(val) => { + const_item.build(helpers::ast_ty::bool_expr(val)) + .build(ty) + } + VarType::Int(val) => { + const_item.build(helpers::ast_ty::int_expr(val)).build(ty) + } + VarType::String(ref bytes) => { + // Account the trailing zero. + // + // TODO: Here we ignore the type we just made up, probably + // we should refactor how the variable type and ty id work. + let len = bytes.len() + 1; + let ty = quote_ty!(ctx.ext_cx(), [u8; $len]); + + match String::from_utf8(bytes.clone()) { + Ok(string) => { + const_item.build(helpers::ast_ty::cstr_expr(string)) + .build(quote_ty!(ctx.ext_cx(), &'static $ty)) + } + Err(..) => { + const_item + .build(helpers::ast_ty::byte_array_expr(bytes)) + .build(ty) + } + } + } + VarType::Float(f) => { + const_item.build(helpers::ast_ty::float_expr(f)) + .build(ty) + } + VarType::Char(c) => { + const_item + .build(aster::AstBuilder::new().expr().lit().byte(c)) + .build(ty) + } + }; + + result.push(item); + } else { + let mut attrs = vec![]; + if let Some(mangled) = self.mangled_name() { + attrs.push(attributes::link_name(mangled)); + } else if canonical_name != self.name() { + attrs.push(attributes::link_name(self.name())); + } + + let item = ast::ForeignItem { + ident: ctx.rust_ident_raw(&canonical_name), + attrs: attrs, + node: ast::ForeignItemKind::Static(ty, !self.is_const()), + id: ast::DUMMY_NODE_ID, + span: ctx.span(), + vis: ast::Visibility::Public, + }; + + let item = ForeignModBuilder::new(Abi::C) + .with_foreign_item(item) + .build(ctx); + result.push(item); + } + } +} + +impl CodeGenerator for Type { + type Extra = Item; + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + item: &Item) { + debug!("::codegen: item = {:?}", item); + + match *self.kind() { + TypeKind::Void | + TypeKind::NullPtr | + TypeKind::Int(..) | + TypeKind::Float(..) | + TypeKind::Complex(..) | + TypeKind::Array(..) | + TypeKind::Pointer(..) | + TypeKind::BlockPointer | + TypeKind::Reference(..) | + TypeKind::TemplateRef(..) | + TypeKind::Function(..) | + TypeKind::ResolvedTypeRef(..) | + TypeKind::Named(..) => { + // These items don't need code generation, they only need to be + // converted to rust types in fields, arguments, and such. + return; + } + TypeKind::Comp(ref ci) => { + ci.codegen(ctx, result, whitelisted_items, item) + } + // NB: The code below will pick the correct + // applicable_template_args. + TypeKind::TemplateAlias(ref spelling, inner, _) | + TypeKind::Alias(ref spelling, inner) => { + let inner_item = ctx.resolve_item(inner); + let name = item.canonical_name(ctx); + + // Try to catch the common pattern: + // + // typedef struct foo { ... } foo; + // + // here. + // + if inner_item.canonical_name(ctx) == name { + return; + } + + // If this is a known named type, disallow generating anything + // for it too. + if utils::type_from_named(ctx, spelling, inner).is_some() { + return; + } + + let mut applicable_template_args = + item.applicable_template_args(ctx); + let inner_rust_type = if item.is_opaque(ctx) { + applicable_template_args.clear(); + // Pray if there's no layout. + let layout = self.layout(ctx).unwrap_or_else(Layout::zero); + BlobTyBuilder::new(layout).build() + } else { + inner_item.to_rust_ty(ctx) + }; + + let rust_name = ctx.rust_ident(&name); + let mut typedef = aster::AstBuilder::new().item().pub_(); + + if ctx.options().generate_comments { + if let Some(comment) = item.comment() { + typedef = typedef.attr().doc(comment); + } + } + + // We prefer using `pub use` over `pub type` because of: + // https://github.com/rust-lang/rust/issues/26264 + let simple_enum_path = match inner_rust_type.node { + ast::TyKind::Path(None, ref p) => { + if applicable_template_args.is_empty() && + inner_item.expect_type().canonical_type(ctx).is_enum() && + p.segments.iter().all(|p| p.parameters.is_none()) { + Some(p.clone()) + } else { + None + } + }, + _ => None, + }; + + let typedef = if let Some(mut p) = simple_enum_path { + for ident in top_level_path(ctx, item).into_iter().rev() { + p.segments.insert(0, ast::PathSegment { + identifier: ident, + parameters: None, + }); + } + typedef.use_().build(p).as_(rust_name) + } else { + let mut generics = typedef.type_(rust_name).generics(); + for template_arg in applicable_template_args.iter() { + let template_arg = ctx.resolve_type(*template_arg); + if template_arg.is_named() { + let name = template_arg.name().unwrap(); + if name.contains("typename ") { + warn!("Item contained `typename`'d template \ + parameter: {:?}", item); + return; + } + generics = + generics.ty_param_id(template_arg.name().unwrap()); + } + } + generics.build().build_ty(inner_rust_type) + }; + result.push(typedef) + } + TypeKind::Enum(ref ei) => { + ei.codegen(ctx, result, whitelisted_items, item) + } + ref u @ TypeKind::UnresolvedTypeRef(..) => { + unreachable!("Should have been resolved after parsing {:?}!", u) + } + } + } +} + +struct Vtable<'a> { + item_id: ItemId, + #[allow(dead_code)] + methods: &'a [Method], + #[allow(dead_code)] + base_classes: &'a [Base], +} + +impl<'a> Vtable<'a> { + fn new(item_id: ItemId, + methods: &'a [Method], + base_classes: &'a [Base]) + -> Self { + Vtable { + item_id: item_id, + methods: methods, + base_classes: base_classes, + } + } +} + +impl<'a> CodeGenerator for Vtable<'a> { + type Extra = Item; + + fn codegen<'b>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'b>, + _whitelisted_items: &ItemSet, + item: &Item) { + assert_eq!(item.id(), self.item_id); + // For now, generate an empty struct, later we should generate function + // pointers and whatnot. + let vtable = aster::AstBuilder::new() + .item() + .pub_() + .with_attr(attributes::repr("C")) + .struct_(self.canonical_name(ctx)) + .build(); + result.push(vtable); + } +} + +impl<'a> ItemCanonicalName for Vtable<'a> { + fn canonical_name(&self, ctx: &BindgenContext) -> String { + format!("{}__bindgen_vtable", self.item_id.canonical_name(ctx)) + } +} + +impl<'a> ItemToRustTy for Vtable<'a> { + fn to_rust_ty(&self, ctx: &BindgenContext) -> P { + aster::ty::TyBuilder::new().id(self.canonical_name(ctx)) + } +} + +struct Bitfield<'a> { + index: usize, + fields: Vec<&'a Field>, +} + +impl<'a> Bitfield<'a> { + fn new(index: usize, fields: Vec<&'a Field>) -> Self { + Bitfield { + index: index, + fields: fields, + } + } + + fn codegen_fields(self, + ctx: &BindgenContext, + fields: &mut Vec, + methods: &mut Vec) { + use aster::struct_field::StructFieldBuilder; + use std::cmp; + let mut total_width = self.fields + .iter() + .fold(0u32, |acc, f| acc + f.bitfield().unwrap()); + + if !total_width.is_power_of_two() || total_width < 8 { + total_width = cmp::max(8, total_width.next_power_of_two()); + } + debug_assert_eq!(total_width % 8, 0); + let total_width_in_bytes = total_width as usize / 8; + + let bitfield_type = + BlobTyBuilder::new(Layout::new(total_width_in_bytes, + total_width_in_bytes)) + .build(); + let field_name = format!("_bitfield_{}", self.index); + let field_ident = ctx.ext_cx().ident_of(&field_name); + let field = StructFieldBuilder::named(&field_name) + .pub_() + .build_ty(bitfield_type.clone()); + fields.push(field); + + + let mut offset = 0; + for field in self.fields { + let width = field.bitfield().unwrap(); + let field_name = field.name() + .map(ToOwned::to_owned) + .unwrap_or_else(|| format!("at_offset_{}", offset)); + + let field_item = ctx.resolve_item(field.ty()); + let field_ty_layout = field_item.kind() + .expect_type() + .layout(ctx) + .expect("Bitfield without layout? Gah!"); + + let field_type = field_item.to_rust_ty(ctx); + let int_type = BlobTyBuilder::new(field_ty_layout).build(); + + let getter_name = ctx.rust_ident(&field_name); + let setter_name = ctx.ext_cx() + .ident_of(&format!("set_{}", &field_name)); + let mask = ((1usize << width) - 1) << offset; + let prefix = ctx.trait_prefix(); + // The transmute is unfortunate, but it's needed for enums in + // bitfields. + let item = quote_item!(ctx.ext_cx(), + impl X { + #[inline] + pub fn $getter_name(&self) -> $field_type { + unsafe { + ::$prefix::mem::transmute( + ( + (self.$field_ident & + ($mask as $bitfield_type)) + >> $offset + ) as $int_type + ) + } + } + + #[inline] + pub fn $setter_name(&mut self, val: $field_type) { + self.$field_ident &= !($mask as $bitfield_type); + self.$field_ident |= + (val as $int_type as $bitfield_type << $offset) & + ($mask as $bitfield_type); + } + } + ) + .unwrap(); + + let items = match item.unwrap().node { + ast::ItemKind::Impl(_, _, _, _, _, items) => items, + _ => unreachable!(), + }; + + methods.extend(items.into_iter()); + offset += width; + } + } +} + +impl CodeGenerator for CompInfo { + type Extra = Item; + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + item: &Item) { + use aster::struct_field::StructFieldBuilder; + + debug!("::codegen: item = {:?}", item); + + // Don't output classes with template parameters that aren't types, and + // also don't output template specializations, neither total or partial. + if self.has_non_type_template_params() { + return; + } + + let applicable_template_args = item.applicable_template_args(ctx); + + // generate tuple struct if struct or union is a forward declaration, + // skip for now if template parameters are needed. + if self.is_forward_declaration() && applicable_template_args.is_empty(){ + let struct_name = item.canonical_name(ctx); + let struct_name = ctx.rust_ident_raw(&struct_name); + let tuple_struct = quote_item!(ctx.ext_cx(), + #[repr(C)] + #[derive(Debug, Copy, Clone)] + pub struct $struct_name([u8; 0]); + ) + .unwrap(); + result.push(tuple_struct); + return; + } + + if self.is_template_specialization() { + let layout = item.kind().expect_type().layout(ctx); + + if let Some(layout) = layout { + let fn_name = format!("__bindgen_test_layout_template_{}", + result.next_id()); + let fn_name = ctx.rust_ident_raw(&fn_name); + let ident = item.to_rust_ty(ctx); + let prefix = ctx.trait_prefix(); + let size_of_expr = quote_expr!(ctx.ext_cx(), + ::$prefix::mem::size_of::<$ident>()); + let align_of_expr = quote_expr!(ctx.ext_cx(), + ::$prefix::mem::align_of::<$ident>()); + let size = layout.size; + let align = layout.align; + let item = quote_item!(ctx.ext_cx(), + #[test] + fn $fn_name() { + assert_eq!($size_of_expr, $size); + assert_eq!($align_of_expr, $align); + }) + .unwrap(); + result.push(item); + } + return; + } + + let mut attributes = vec![]; + let mut needs_clone_impl = false; + if ctx.options().generate_comments { + if let Some(comment) = item.comment() { + attributes.push(attributes::doc(comment)); + } + } + if self.packed() { + attributes.push(attributes::repr_list(&["C", "packed"])); + } else { + attributes.push(attributes::repr("C")); + } + + let is_union = self.kind() == CompKind::Union; + let mut derives = vec![]; + if item.can_derive_debug(ctx, ()) { + derives.push("Debug"); + } + + if item.can_derive_copy(ctx, ()) && + !item.annotations().disallow_copy() { + derives.push("Copy"); + if !applicable_template_args.is_empty() { + // FIXME: This requires extra logic if you have a big array in a + // templated struct. The reason for this is that the magic: + // fn clone(&self) -> Self { *self } + // doesn't work for templates. + // + // It's not hard to fix though. + derives.push("Clone"); + } else { + needs_clone_impl = true; + } + } + + if !derives.is_empty() { + attributes.push(attributes::derives(&derives)) + } + + let mut template_args_used = + vec![false; applicable_template_args.len()]; + let canonical_name = item.canonical_name(ctx); + let builder = if is_union && ctx.options().unstable_rust { + aster::AstBuilder::new() + .item() + .pub_() + .with_attrs(attributes) + .union_(&canonical_name) + } else { + aster::AstBuilder::new() + .item() + .pub_() + .with_attrs(attributes) + .struct_(&canonical_name) + }; + + // Generate the vtable from the method list if appropriate. + // + // TODO: I don't know how this could play with virtual methods that are + // not in the list of methods found by us, we'll see. Also, could the + // order of the vtable pointers vary? + // + // FIXME: Once we generate proper vtables, we need to codegen the + // vtable, but *not* generate a field for it in the case that + // needs_explicit_vtable is false but has_vtable is true. + // + // Also, we need to generate the vtable in such a way it "inherits" from + // the parent too. + let mut fields = vec![]; + if self.needs_explicit_vtable(ctx) { + let vtable = + Vtable::new(item.id(), self.methods(), self.base_members()); + vtable.codegen(ctx, result, whitelisted_items, item); + + let vtable_type = vtable.to_rust_ty(ctx).to_ptr(true, ctx.span()); + + let vtable_field = StructFieldBuilder::named("vtable_") + .pub_() + .build_ty(vtable_type); + + fields.push(vtable_field); + } + + for (i, base) in self.base_members().iter().enumerate() { + // Virtual bases are already taken into account by the vtable + // pointer. + // + // FIXME(emilio): Is this always right? + if base.is_virtual() { + continue; + } + + let base_ty = ctx.resolve_type(base.ty); + // NB: We won't include unsized types in our base chain because they + // would contribute to our size given the dummy field we insert for + // unsized types. + if base_ty.is_unsized(ctx) { + continue; + } + + for (i, ty_id) in applicable_template_args.iter().enumerate() { + let template_arg_ty = ctx.resolve_type(*ty_id); + if base_ty.signature_contains_named_type(ctx, template_arg_ty) { + template_args_used[i] = true; + } + } + + let inner = base.ty.to_rust_ty(ctx); + let field_name = if i == 0 { + "_base".into() + } else { + format!("_base_{}", i) + }; + + let field = StructFieldBuilder::named(field_name) + .pub_() + .build_ty(inner); + fields.push(field); + } + if is_union { + result.saw_union(); + } + + let layout = item.kind().expect_type().layout(ctx); + + let mut current_bitfield_width = None; + let mut current_bitfield_layout: Option = None; + let mut current_bitfield_fields = vec![]; + let mut bitfield_count = 0; + let struct_fields = self.fields(); + let fields_should_be_private = item.annotations() + .private_fields() + .unwrap_or(false); + let struct_accessor_kind = item.annotations() + .accessor_kind() + .unwrap_or(FieldAccessorKind::None); + + let mut methods = vec![]; + let mut anonymous_field_count = 0; + for field in struct_fields { + debug_assert_eq!(current_bitfield_width.is_some(), + current_bitfield_layout.is_some()); + debug_assert_eq!(current_bitfield_width.is_some(), + !current_bitfield_fields.is_empty()); + + let field_ty = ctx.resolve_type(field.ty()); + + // Try to catch a bitfield contination early. + if let (Some(ref mut bitfield_width), Some(width)) = + (current_bitfield_width, field.bitfield()) { + let layout = current_bitfield_layout.unwrap(); + debug!("Testing bitfield continuation {} {} {:?}", + *bitfield_width, width, layout); + if *bitfield_width + width <= (layout.size * 8) as u32 { + *bitfield_width += width; + current_bitfield_fields.push(field); + continue; + } + } + + // Flush the current bitfield. + if current_bitfield_width.is_some() { + debug_assert!(!current_bitfield_fields.is_empty()); + let bitfield_fields = + mem::replace(&mut current_bitfield_fields, vec![]); + bitfield_count += 1; + Bitfield::new(bitfield_count, bitfield_fields) + .codegen_fields(ctx, &mut fields, &mut methods); + current_bitfield_width = None; + current_bitfield_layout = None; + } + debug_assert!(current_bitfield_fields.is_empty()); + + if let Some(width) = field.bitfield() { + let layout = field_ty.layout(ctx) + .expect("Bitfield type without layout?"); + current_bitfield_width = Some(width); + current_bitfield_layout = Some(layout); + current_bitfield_fields.push(field); + continue; + } + + for (i, ty_id) in applicable_template_args.iter().enumerate() { + let template_arg = ctx.resolve_type(*ty_id); + if field_ty.signature_contains_named_type(ctx, template_arg) { + template_args_used[i] = true; + } + } + + let ty = field.ty().to_rust_ty(ctx); + + // NB: In unstable rust we use proper `union` types. + let ty = if is_union && !ctx.options().unstable_rust { + if ctx.options().enable_cxx_namespaces { + quote_ty!(ctx.ext_cx(), root::__BindgenUnionField<$ty>) + } else { + quote_ty!(ctx.ext_cx(), __BindgenUnionField<$ty>) + } + } else { + ty + }; + + let mut attrs = vec![]; + if ctx.options().generate_comments { + if let Some(comment) = field.comment() { + attrs.push(attributes::doc(comment)); + } + } + let field_name = match field.name() { + Some(name) => ctx.rust_mangle(name).into_owned(), + None => { + anonymous_field_count += 1; + format!("__bindgen_anon_{}", anonymous_field_count) + } + }; + + let is_private = field.annotations() + .private_fields() + .unwrap_or(fields_should_be_private); + + let accessor_kind = field.annotations() + .accessor_kind() + .unwrap_or(struct_accessor_kind); + + let mut field = StructFieldBuilder::named(&field_name); + + if !is_private { + field = field.pub_(); + } + + let field = field.with_attrs(attrs) + .build_ty(ty.clone()); + + fields.push(field); + + // TODO: Factor the following code out, please! + if accessor_kind == FieldAccessorKind::None { + continue; + } + + let getter_name = + ctx.rust_ident_raw(&format!("get_{}", field_name)); + let mutable_getter_name = + ctx.rust_ident_raw(&format!("get_{}_mut", field_name)); + let field_name = ctx.rust_ident_raw(&field_name); + + let accessor_methods_impl = match accessor_kind { + FieldAccessorKind::None => unreachable!(), + FieldAccessorKind::Regular => { + quote_item!(ctx.ext_cx(), + impl X { + #[inline] + pub fn $getter_name(&self) -> &$ty { + &self.$field_name + } + + #[inline] + pub fn $mutable_getter_name(&mut self) -> &mut $ty { + &mut self.$field_name + } + } + ) + } + FieldAccessorKind::Unsafe => { + quote_item!(ctx.ext_cx(), + impl X { + #[inline] + pub unsafe fn $getter_name(&self) -> &$ty { + &self.$field_name + } + + #[inline] + pub unsafe fn $mutable_getter_name(&mut self) + -> &mut $ty { + &mut self.$field_name + } + } + ) + } + FieldAccessorKind::Immutable => { + quote_item!(ctx.ext_cx(), + impl X { + #[inline] + pub fn $getter_name(&self) -> &$ty { + &self.$field_name + } + } + ) + } + }; + + match accessor_methods_impl.unwrap().node { + ast::ItemKind::Impl(_, _, _, _, _, ref items) => { + methods.extend(items.clone()) + } + _ => unreachable!(), + } + } + + // Flush the last bitfield if any. + // + // FIXME: Reduce duplication with the loop above. + // FIXME: May need to pass current_bitfield_layout too. + if current_bitfield_width.is_some() { + debug_assert!(!current_bitfield_fields.is_empty()); + let bitfield_fields = mem::replace(&mut current_bitfield_fields, + vec![]); + bitfield_count += 1; + Bitfield::new(bitfield_count, bitfield_fields) + .codegen_fields(ctx, &mut fields, &mut methods); + } + debug_assert!(current_bitfield_fields.is_empty()); + + if is_union && !ctx.options().unstable_rust { + let layout = layout.expect("Unable to get layout information?"); + let ty = BlobTyBuilder::new(layout).build(); + let field = StructFieldBuilder::named("bindgen_union_field") + .pub_() + .build_ty(ty); + fields.push(field); + } + + // Yeah, sorry about that. + if item.is_opaque(ctx) { + fields.clear(); + methods.clear(); + for i in 0..template_args_used.len() { + template_args_used[i] = false; + } + + match layout { + Some(l) => { + let ty = BlobTyBuilder::new(l).build(); + let field = + StructFieldBuilder::named("_bindgen_opaque_blob") + .pub_() + .build_ty(ty); + fields.push(field); + } + None => { + warn!("Opaque type without layout! Expect dragons!"); + } + } + } + + // C requires every struct to be addressable, so what C compilers do is + // making the struct 1-byte sized. + // + // NOTE: This check is conveniently here to avoid the dummy fields we + // may add for unused template parameters. + if self.is_unsized(ctx) { + let ty = BlobTyBuilder::new(Layout::new(1, 1)).build(); + let field = StructFieldBuilder::named("_address") + .pub_() + .build_ty(ty); + fields.push(field); + } + + // Append any extra template arguments that nobody has used so far. + for (i, ty) in applicable_template_args.iter().enumerate() { + if !template_args_used[i] { + let name = ctx.resolve_type(*ty).name().unwrap(); + let ident = ctx.rust_ident(name); + let prefix = ctx.trait_prefix(); + let phantom = quote_ty!(ctx.ext_cx(), + ::$prefix::marker::PhantomData<$ident>); + let field = + StructFieldBuilder::named(format!("_phantom_{}", i)) + .pub_() + .build_ty(phantom); + fields.push(field) + } + } + + + let mut generics = aster::AstBuilder::new().generics(); + for template_arg in applicable_template_args.iter() { + // Take into account that here only arrive named types, not + // template specialisations that would need to be + // instantiated. + // + // TODO: Add template args from the parent, here and in + // `to_rust_ty`!! + let template_arg = ctx.resolve_type(*template_arg); + generics = generics.ty_param_id(template_arg.name().unwrap()); + } + + let generics = generics.build(); + + let rust_struct = builder.with_generics(generics.clone()) + .with_fields(fields) + .build(); + result.push(rust_struct); + + // Generate the inner types and all that stuff. + // + // TODO: In the future we might want to be smart, and use nested + // modules, and whatnot. + for ty in self.inner_types() { + let child_item = ctx.resolve_item(*ty); + // assert_eq!(child_item.parent_id(), item.id()); + child_item.codegen(ctx, result, whitelisted_items, &()); + } + + // NOTE: Some unexposed attributes (like alignment attributes) may + // affect layout, so we're bad and pray to the gods for avoid sending + // all the tests to shit when parsing things like max_align_t. + if self.found_unknown_attr() { + warn!("Type {} has an unkown attribute that may affect layout", + canonical_name); + } + + if applicable_template_args.is_empty() && !self.found_unknown_attr() { + for var in self.inner_vars() { + ctx.resolve_item(*var) + .codegen(ctx, result, whitelisted_items, &()); + } + + if let Some(layout) = layout { + let fn_name = format!("bindgen_test_layout_{}", canonical_name); + let fn_name = ctx.rust_ident_raw(&fn_name); + let ident = ctx.rust_ident_raw(&canonical_name); + let prefix = ctx.trait_prefix(); + let size_of_expr = quote_expr!(ctx.ext_cx(), + ::$prefix::mem::size_of::<$ident>()); + let align_of_expr = quote_expr!(ctx.ext_cx(), + ::$prefix::mem::align_of::<$ident>()); + let size = layout.size; + let align = layout.align; + let item = quote_item!(ctx.ext_cx(), + #[test] + fn $fn_name() { + assert_eq!($size_of_expr, $size); + assert_eq!($align_of_expr, $align); + }) + .unwrap(); + result.push(item); + } + + let mut method_names = Default::default(); + if ctx.options().codegen_config.methods { + for method in self.methods() { + assert!(method.kind() != MethodKind::Constructor); + method.codegen_method(ctx, + &mut methods, + &mut method_names, + result, + whitelisted_items, + self); + } + } + + if ctx.options().codegen_config.constructors { + for sig in self.constructors() { + Method::new(MethodKind::Constructor, + *sig, + /* const */ + false) + .codegen_method(ctx, + &mut methods, + &mut method_names, + result, + whitelisted_items, + self); + } + } + } + + // NB: We can't use to_rust_ty here since for opaque types this tries to + // use the specialization knowledge to generate a blob field. + let ty_for_impl = + aster::AstBuilder::new().ty().path().id(&canonical_name).build(); + if needs_clone_impl { + let impl_ = quote_item!(ctx.ext_cx(), + impl X { + fn clone(&self) -> Self { *self } + } + ); + + let impl_ = match impl_.unwrap().node { + ast::ItemKind::Impl(_, _, _, _, _, ref items) => items.clone(), + _ => unreachable!(), + }; + + let clone_impl = aster::AstBuilder::new() + .item() + .impl_() + .trait_() + .id("Clone") + .build() + .with_generics(generics.clone()) + .with_items(impl_) + .build_ty(ty_for_impl.clone()); + + result.push(clone_impl); + } + + if !methods.is_empty() { + let methods = aster::AstBuilder::new() + .item() + .impl_() + .with_generics(generics) + .with_items(methods) + .build_ty(ty_for_impl); + result.push(methods); + } + } +} + +trait MethodCodegen { + fn codegen_method<'a>(&self, + ctx: &BindgenContext, + methods: &mut Vec, + method_names: &mut HashMap, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + parent: &CompInfo); +} + +impl MethodCodegen for Method { + fn codegen_method<'a>(&self, + ctx: &BindgenContext, + methods: &mut Vec, + method_names: &mut HashMap, + result: &mut CodegenResult<'a>, + whitelisted_items: &ItemSet, + _parent: &CompInfo) { + if self.is_virtual() { + return; // FIXME + } + // First of all, output the actual function. + let function_item = ctx.resolve_item(self.signature()); + function_item.codegen(ctx, result, whitelisted_items, &()); + + let function = function_item.expect_function(); + let signature_item = ctx.resolve_item(function.signature()); + let mut name = match self.kind() { + MethodKind::Constructor => "new".into(), + _ => function.name().to_owned(), + }; + + let signature = match *signature_item.expect_type().kind() { + TypeKind::Function(ref sig) => sig, + _ => panic!("How in the world?"), + }; + + // Do not generate variadic methods, since rust does not allow + // implementing them, and we don't do a good job at it anyway. + if signature.is_variadic() { + return; + } + + let count = { + let mut count = method_names.entry(name.clone()) + .or_insert(0); + *count += 1; + *count - 1 + }; + + if count != 0 { + name.push_str(&count.to_string()); + } + + let function_name = function_item.canonical_name(ctx); + let mut fndecl = utils::rust_fndecl_from_signature(ctx, signature_item) + .unwrap(); + if !self.is_static() && !self.is_constructor() { + let mutability = if self.is_const() { + ast::Mutability::Immutable + } else { + ast::Mutability::Mutable + }; + + assert!(!fndecl.inputs.is_empty()); + + // FIXME: use aster here. + fndecl.inputs[0] = ast::Arg { + ty: P(ast::Ty { + id: ast::DUMMY_NODE_ID, + node: ast::TyKind::Rptr(None, ast::MutTy { + ty: P(ast::Ty { + id: ast::DUMMY_NODE_ID, + node: ast::TyKind::ImplicitSelf, + span: ctx.span() + }), + mutbl: mutability, + }), + span: ctx.span(), + }), + pat: P(ast::Pat { + id: ast::DUMMY_NODE_ID, + node: ast::PatKind::Ident( + ast::BindingMode::ByValue(ast::Mutability::Immutable), + respan(ctx.span(), ctx.ext_cx().ident_of("self")), + None + ), + span: ctx.span(), + }), + id: ast::DUMMY_NODE_ID, + }; + } + + // If it's a constructor, we always return `Self`, and we inject the + // "this" parameter, so there's no need to ask the user for it. + // + // Note that constructors in Clang are represented as functions with + // return-type = void. + if self.is_constructor() { + fndecl.inputs.remove(0); + fndecl.output = + ast::FunctionRetTy::Ty(quote_ty!(ctx.ext_cx(), Self)); + } + + let sig = ast::MethodSig { + unsafety: ast::Unsafety::Unsafe, + abi: Abi::Rust, + decl: P(fndecl), + generics: ast::Generics::default(), + constness: respan(ctx.span(), ast::Constness::NotConst), + }; + + let mut exprs = helpers::ast_ty::arguments_from_signature(&signature, + ctx); + + let mut stmts = vec![]; + + // If it's a constructor, we need to insert an extra parameter with a + // variable called `__bindgen_tmp` we're going to create. + if self.is_constructor() { + let tmp_variable_decl = + quote_stmt!(ctx.ext_cx(), + let mut __bindgen_tmp = ::std::mem::uninitialized()) + .unwrap(); + stmts.push(tmp_variable_decl); + exprs[0] = quote_expr!(ctx.ext_cx(), &mut __bindgen_tmp); + } else if !self.is_static() { + assert!(!exprs.is_empty()); + exprs[0] = if self.is_const() { + quote_expr!(ctx.ext_cx(), &*self) + } else { + quote_expr!(ctx.ext_cx(), &mut *self) + }; + }; + + let call = aster::expr::ExprBuilder::new() + .call() + .id(function_name) + .with_args(exprs) + .build(); + + stmts.push(ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: ast::StmtKind::Expr(call), + span: ctx.span(), + }); + + if self.is_constructor() { + stmts.push(quote_stmt!(ctx.ext_cx(), __bindgen_tmp).unwrap()); + } + + let block = ast::Block { + stmts: stmts, + id: ast::DUMMY_NODE_ID, + rules: ast::BlockCheckMode::Default, + span: ctx.span(), + }; + + let mut attrs = vec![]; + attrs.push(attributes::inline()); + + let item = ast::ImplItem { + id: ast::DUMMY_NODE_ID, + ident: ctx.rust_ident(&name), + vis: ast::Visibility::Public, + attrs: attrs, + node: ast::ImplItemKind::Method(sig, P(block)), + defaultness: ast::Defaultness::Final, + span: ctx.span(), + }; + + methods.push(item); + } +} + +/// A helper type to construct enums, either bitfield ones or rust-style ones. +enum EnumBuilder<'a> { + Rust(aster::item::ItemEnumBuilder), + Bitfield { + canonical_name: &'a str, + aster: P, + }, + Consts { aster: P, } +} + +impl<'a> EnumBuilder<'a> { + /// Create a new enum given an item builder, a canonical name, a name for + /// the representation, and whether it should be represented as a rust enum. + fn new(aster: aster::item::ItemBuilder, + name: &'a str, + repr: P, + bitfield_like: bool, + constify: bool) + -> Self { + if bitfield_like { + EnumBuilder::Bitfield { + canonical_name: name, + aster: aster.tuple_struct(name) + .field() + .pub_() + .build_ty(repr) + .build(), + } + } else if constify { + EnumBuilder::Consts { + aster: aster.type_(name).build_ty(repr), + } + } else { + EnumBuilder::Rust(aster.enum_(name)) + } + } + + /// Add a variant to this enum. + fn with_variant<'b>(self, + ctx: &BindgenContext, + variant: &EnumVariant, + mangling_prefix: Option<&String>, + rust_ty: P, + result: &mut CodegenResult<'b>) + -> Self { + let variant_name = ctx.rust_mangle(variant.name()); + let expr = aster::AstBuilder::new().expr(); + let expr = match variant.val() { + EnumVariantValue::Signed(v) => helpers::ast_ty::int_expr(v), + EnumVariantValue::Unsigned(v) => expr.uint(v), + }; + + match self { + EnumBuilder::Rust(b) => { + EnumBuilder::Rust(b.with_variant_(ast::Variant_ { + name: ctx.rust_ident(&*variant_name), + attrs: vec![], + data: ast::VariantData::Unit(ast::DUMMY_NODE_ID), + disr_expr: Some(expr), + })) + } + EnumBuilder::Bitfield { canonical_name, .. } => { + let constant_name = match mangling_prefix { + Some(prefix) => { + Cow::Owned(format!("{}_{}", prefix, variant_name)) + } + None => variant_name, + }; + + let constant = aster::AstBuilder::new() + .item() + .pub_() + .const_(&*constant_name) + .expr() + .call() + .id(canonical_name) + .arg() + .build(expr) + .build() + .build(rust_ty); + result.push(constant); + self + } + EnumBuilder::Consts { .. } => { + let constant_name = match mangling_prefix { + Some(prefix) => { + Cow::Owned(format!("{}_{}", prefix, variant_name)) + } + None => variant_name, + }; + + let constant = aster::AstBuilder::new() + .item() + .pub_() + .const_(&*constant_name) + .expr() + .build(expr) + .build(rust_ty); + + result.push(constant); + self + } + } + } + + fn build<'b>(self, + ctx: &BindgenContext, + rust_ty: P, + result: &mut CodegenResult<'b>) + -> P { + match self { + EnumBuilder::Rust(b) => b.build(), + EnumBuilder::Bitfield { canonical_name, aster } => { + let rust_ty_name = ctx.rust_ident_raw(canonical_name); + let prefix = ctx.trait_prefix(); + + let impl_ = quote_item!(ctx.ext_cx(), + impl ::$prefix::ops::BitOr<$rust_ty> for $rust_ty { + type Output = Self; + + #[inline] + fn bitor(self, other: Self) -> Self { + $rust_ty_name(self.0 | other.0) + } + } + ) + .unwrap(); + + result.push(impl_); + aster + } + EnumBuilder::Consts { aster, .. } => aster, + } + } +} + +impl CodeGenerator for Enum { + type Extra = Item; + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + _whitelisted_items: &ItemSet, + item: &Item) { + debug!("::codegen: item = {:?}", item); + + let name = item.canonical_name(ctx); + let enum_ty = item.expect_type(); + let layout = enum_ty.layout(ctx); + + let repr = self.repr().map(|repr| ctx.resolve_type(repr)); + let repr = match repr { + Some(repr) => { + match *repr.canonical_type(ctx).kind() { + TypeKind::Int(int_kind) => int_kind, + _ => panic!("Unexpected type as enum repr"), + } + } + None => { + warn!("Guessing type of enum! Forward declarations of enums \ + shouldn't be legal!"); + IntKind::Int + } + }; + + let signed = repr.is_signed(); + let size = layout.map(|l| l.size) + .or_else(|| repr.known_size()) + .unwrap_or(0); + + let repr_name = match (signed, size) { + (true, 1) => "i8", + (false, 1) => "u8", + (true, 2) => "i16", + (false, 2) => "u16", + (true, 4) => "i32", + (false, 4) => "u32", + (true, 8) => "i64", + (false, 8) => "u64", + _ => { + warn!("invalid enum decl: signed: {}, size: {}", signed, size); + "i32" + } + }; + + let mut builder = aster::AstBuilder::new().item().pub_(); + + // FIXME(emilio): These should probably use the path so it can + // disambiguate between namespaces, just like is_opaque etc. + let is_bitfield = { + ctx.options().bitfield_enums.matches(&name) || + (enum_ty.name().is_none() && + self.variants() + .iter() + .any(|v| ctx.options().bitfield_enums.matches(&v.name()))) + }; + + let is_constified_enum = { + ctx.options().constified_enums.matches(&name) || + (enum_ty.name().is_none() && + self.variants() + .iter() + .any(|v| ctx.options().constified_enums.matches(&v.name()))) + }; + + let is_rust_enum = !is_bitfield && !is_constified_enum; + + // FIXME: Rust forbids repr with empty enums. Remove this condition when + // this is allowed. + // + // TODO(emilio): Delegate this to the builders? + if is_rust_enum { + if !self.variants().is_empty() { + builder = builder.with_attr(attributes::repr(repr_name)); + } + } else if is_bitfield { + builder = builder.with_attr(attributes::repr("C")); + } + + if ctx.options().generate_comments { + if let Some(comment) = item.comment() { + builder = builder.with_attr(attributes::doc(comment)); + } + } + + if !is_constified_enum { + let derives = attributes::derives(&["Debug", + "Copy", + "Clone", + "PartialEq", + "Eq", + "Hash"]); + + builder = builder.with_attr(derives); + } + + fn add_constant<'a>(enum_: &Type, + // Only to avoid recomputing every time. + enum_canonical_name: &str, + // May be the same as "variant" if it's because the + // enum is unnamed and we still haven't seen the + // value. + variant_name: &str, + referenced_name: &str, + enum_rust_ty: P, + result: &mut CodegenResult<'a>) { + let constant_name = if enum_.name().is_some() { + format!("{}_{}", enum_canonical_name, variant_name) + } else { + variant_name.into() + }; + + let constant = aster::AstBuilder::new() + .item() + .pub_() + .const_(constant_name) + .expr() + .path() + .ids(&[&*enum_canonical_name, referenced_name]) + .build() + .build(enum_rust_ty); + result.push(constant); + } + + let repr = self.repr() + .map(|repr| repr.to_rust_ty(ctx)) + .unwrap_or_else(|| helpers::ast_ty::raw_type(ctx, repr_name)); + + let mut builder = + EnumBuilder::new(builder, + &name, + repr, + is_bitfield, + is_constified_enum); + + // A map where we keep a value -> variant relation. + let mut seen_values = HashMap::<_, String>::new(); + let enum_rust_ty = item.to_rust_ty(ctx); + let is_toplevel = item.is_toplevel(ctx); + + // Used to mangle the constants we generate in the unnamed-enum case. + let parent_canonical_name = if is_toplevel { + None + } else { + Some(item.parent_id().canonical_name(ctx)) + }; + + let constant_mangling_prefix = if enum_ty.name().is_none() { + parent_canonical_name.as_ref().map(|n| &*n) + } else { + Some(&name) + }; + + // NB: We defer the creation of constified variants, in case we find + // another variant with the same value (which is the common thing to + // do). + let mut constified_variants = VecDeque::new(); + + let mut iter = self.variants().iter().peekable(); + while let Some(variant) = iter.next().or_else(|| constified_variants.pop_front()) { + if variant.hidden() { + continue; + } + + if variant.force_constification() && iter.peek().is_some() { + constified_variants.push_back(variant); + continue; + } + + match seen_values.entry(variant.val()) { + Entry::Occupied(ref entry) => { + if is_rust_enum { + let variant_name = ctx.rust_mangle(variant.name()); + let mangled_name = if is_toplevel || + enum_ty.name().is_some() { + variant_name + } else { + let parent_name = parent_canonical_name.as_ref() + .unwrap(); + + Cow::Owned( + format!("{}_{}", parent_name, variant_name)) + }; + + let existing_variant_name = entry.get(); + add_constant(enum_ty, + &name, + &*mangled_name, + existing_variant_name, + enum_rust_ty.clone(), + result); + } else { + builder = builder.with_variant(ctx, + variant, + constant_mangling_prefix, + enum_rust_ty.clone(), + result); + } + } + Entry::Vacant(entry) => { + builder = builder.with_variant(ctx, + variant, + constant_mangling_prefix, + enum_rust_ty.clone(), + result); + + let variant_name = ctx.rust_mangle(variant.name()); + + // If it's an unnamed enum, or constification is enforced, + // we also generate a constant so it can be properly + // accessed. + if (is_rust_enum && enum_ty.name().is_none()) || + variant.force_constification() { + let mangled_name = if is_toplevel { + variant_name.clone() + } else { + let parent_name = parent_canonical_name.as_ref() + .unwrap(); + + Cow::Owned( + format!("{}_{}", parent_name, variant_name)) + }; + + add_constant(enum_ty, + &name, + &mangled_name, + &variant_name, + enum_rust_ty.clone(), + result); + } + + entry.insert(variant_name.into_owned()); + } + } + } + + let enum_ = builder.build(ctx, enum_rust_ty, result); + result.push(enum_); + } +} + +trait ToRustTy { + type Extra; + + fn to_rust_ty(&self, + ctx: &BindgenContext, + extra: &Self::Extra) + -> P; +} + +trait ItemToRustTy { + fn to_rust_ty(&self, ctx: &BindgenContext) -> P; +} + +// Convenience implementation. +impl ItemToRustTy for ItemId { + fn to_rust_ty(&self, ctx: &BindgenContext) -> P { + ctx.resolve_item(*self).to_rust_ty(ctx) + } +} + +impl ItemToRustTy for Item { + fn to_rust_ty(&self, ctx: &BindgenContext) -> P { + self.kind().expect_type().to_rust_ty(ctx, self) + } +} + +impl ToRustTy for Type { + type Extra = Item; + + fn to_rust_ty(&self, ctx: &BindgenContext, item: &Item) -> P { + use self::helpers::ast_ty::*; + + match *self.kind() { + TypeKind::Void => raw_type(ctx, "c_void"), + // TODO: we should do something smart with nullptr, or maybe *const + // c_void is enough? + TypeKind::NullPtr => { + raw_type(ctx, "c_void").to_ptr(true, ctx.span()) + } + TypeKind::Int(ik) => { + match ik { + IntKind::Bool => aster::ty::TyBuilder::new().bool(), + IntKind::Char => raw_type(ctx, "c_char"), + IntKind::UChar => raw_type(ctx, "c_uchar"), + IntKind::Short => raw_type(ctx, "c_short"), + IntKind::UShort => raw_type(ctx, "c_ushort"), + IntKind::Int => raw_type(ctx, "c_int"), + IntKind::UInt => raw_type(ctx, "c_uint"), + IntKind::Long => raw_type(ctx, "c_long"), + IntKind::ULong => raw_type(ctx, "c_ulong"), + IntKind::LongLong => raw_type(ctx, "c_longlong"), + IntKind::ULongLong => raw_type(ctx, "c_ulonglong"), + + IntKind::I8 => aster::ty::TyBuilder::new().i8(), + IntKind::U8 => aster::ty::TyBuilder::new().u8(), + IntKind::I16 => aster::ty::TyBuilder::new().i16(), + IntKind::U16 => aster::ty::TyBuilder::new().u16(), + IntKind::I32 => aster::ty::TyBuilder::new().i32(), + IntKind::U32 => aster::ty::TyBuilder::new().u32(), + IntKind::I64 => aster::ty::TyBuilder::new().i64(), + IntKind::U64 => aster::ty::TyBuilder::new().u64(), + IntKind::Custom { name, .. } => { + let ident = ctx.rust_ident_raw(name); + quote_ty!(ctx.ext_cx(), $ident) + } + // FIXME: This doesn't generate the proper alignment, but we + // can't do better right now. We should be able to use + // i128/u128 when they're available. + IntKind::U128 | IntKind::I128 => { + aster::ty::TyBuilder::new().array(2).u64() + } + } + } + TypeKind::Float(fk) => float_kind_rust_type(ctx, fk), + TypeKind::Complex(fk) => { + let float_path = float_kind_rust_type(ctx, fk); + + ctx.generated_bindegen_complex(); + if ctx.options().enable_cxx_namespaces { + quote_ty!(ctx.ext_cx(), root::__BindgenComplex<$float_path>) + } else { + quote_ty!(ctx.ext_cx(), __BindgenComplex<$float_path>) + } + } + TypeKind::Function(ref fs) => { + let ty = fs.to_rust_ty(ctx, item); + let prefix = ctx.trait_prefix(); + quote_ty!(ctx.ext_cx(), ::$prefix::option::Option<$ty>) + } + TypeKind::Array(item, len) => { + let inner = item.to_rust_ty(ctx); + aster::ty::TyBuilder::new().array(len).build(inner) + } + TypeKind::Enum(..) => { + let path = item.namespace_aware_canonical_path(ctx); + aster::AstBuilder::new().ty().path().ids(path).build() + } + TypeKind::TemplateRef(inner, ref template_args) => { + // PS: Sorry for the duplication here. + let mut inner_ty = inner.to_rust_ty(ctx).unwrap(); + + if let ast::TyKind::Path(_, ref mut path) = inner_ty.node { + let template_args = template_args.iter() + .map(|arg| arg.to_rust_ty(ctx)) + .collect::>(); + + path.segments.last_mut().unwrap().parameters = if template_args.is_empty() { + None + } else { + Some(P(ast::PathParameters::AngleBracketed( + ast::AngleBracketedParameterData { + lifetimes: vec![], + types: P::from_vec(template_args), + bindings: P::from_vec(vec![]), + } + ))) + } + } + + P(inner_ty) + } + TypeKind::ResolvedTypeRef(inner) => inner.to_rust_ty(ctx), + TypeKind::TemplateAlias(ref spelling, inner, _) | + TypeKind::Alias(ref spelling, inner) => { + let applicable_named_args = + item.applicable_template_args(ctx) + .into_iter() + .filter(|arg| ctx.resolve_type(*arg).is_named()) + .collect::>(); + + if item.is_opaque(ctx) && !applicable_named_args.is_empty() { + // Pray if there's no available layout. + let layout = self.layout(ctx).unwrap_or_else(Layout::zero); + BlobTyBuilder::new(layout).build() + } else if let Some(ty) = utils::type_from_named(ctx, + spelling, + inner) { + ty + } else { + utils::build_templated_path(item, + ctx, + applicable_named_args) + } + } + TypeKind::Comp(ref info) => { + let template_args = item.applicable_template_args(ctx); + if info.has_non_type_template_params() || + (item.is_opaque(ctx) && !template_args.is_empty()) { + return match self.layout(ctx) { + Some(layout) => BlobTyBuilder::new(layout).build(), + None => { + warn!("Couldn't compute layout for a type with non \ + type template params or opaque, expect \ + dragons!"); + aster::AstBuilder::new().ty().unit() + } + }; + } + + utils::build_templated_path(item, ctx, template_args) + } + TypeKind::BlockPointer => { + let void = raw_type(ctx, "c_void"); + void.to_ptr(/* is_const = */ + false, + ctx.span()) + } + TypeKind::Pointer(inner) | + TypeKind::Reference(inner) => { + let inner = ctx.resolve_item(inner); + let inner_ty = inner.expect_type(); + let ty = inner.to_rust_ty(ctx); + + // Avoid the first function pointer level, since it's already + // represented in Rust. + if inner_ty.canonical_type(ctx).is_function() { + ty + } else { + let is_const = self.is_const() || + inner.expect_type().is_const(); + ty.to_ptr(is_const, ctx.span()) + } + } + TypeKind::Named(..) => { + let name = item.canonical_name(ctx); + let ident = ctx.rust_ident(&name); + quote_ty!(ctx.ext_cx(), $ident) + } + ref u @ TypeKind::UnresolvedTypeRef(..) => { + unreachable!("Should have been resolved after parsing {:?}!", u) + } + } + } +} + +impl ToRustTy for FunctionSig { + type Extra = Item; + + fn to_rust_ty(&self, ctx: &BindgenContext, _item: &Item) -> P { + // TODO: we might want to consider ignoring the reference return value. + let return_item = ctx.resolve_item(self.return_type()); + let ret = + if let TypeKind::Void = *return_item.kind().expect_type().kind() { + ast::FunctionRetTy::Default(ctx.span()) + } else { + ast::FunctionRetTy::Ty(return_item.to_rust_ty(ctx)) + }; + + let mut unnamed_arguments = 0; + let arguments = self.argument_types().iter().map(|&(ref name, ty)| { + let arg_item = ctx.resolve_item(ty); + let arg_ty = arg_item.kind().expect_type(); + + // From the C90 standard[1]: + // + // A declaration of a parameter as "array of type" shall be + // adjusted to "qualified pointer to type", where the type + // qualifiers (if any) are those specified within the [ and ] of + // the array type derivation. + // + // [1]: http://c0x.coding-guidelines.com/6.7.5.3.html + let arg_ty = if let TypeKind::Array(t, _) = *arg_ty.canonical_type(ctx).kind() { + t.to_rust_ty(ctx).to_ptr(arg_ty.is_const(), ctx.span()) + } else { + arg_item.to_rust_ty(ctx) + }; + + let arg_name = match *name { + Some(ref name) => ctx.rust_mangle(name).into_owned(), + None => { + unnamed_arguments += 1; + format!("arg{}", unnamed_arguments) + } + }; + + assert!(!arg_name.is_empty()); + + ast::Arg { + ty: arg_ty, + pat: aster::AstBuilder::new().pat().id(arg_name), + id: ast::DUMMY_NODE_ID, + } + }).collect::>(); + + let decl = P(ast::FnDecl { + inputs: arguments, + output: ret, + variadic: self.is_variadic(), + }); + + let fnty = ast::TyKind::BareFn(P(ast::BareFnTy { + unsafety: ast::Unsafety::Unsafe, + abi: self.abi(), + lifetimes: vec![], + decl: decl, + })); + + P(ast::Ty { + id: ast::DUMMY_NODE_ID, + node: fnty, + span: ctx.span(), + }) + } +} + +impl CodeGenerator for Function { + type Extra = Item; + + fn codegen<'a>(&self, + ctx: &BindgenContext, + result: &mut CodegenResult<'a>, + _whitelisted_items: &ItemSet, + item: &Item) { + debug!("::codegen: item = {:?}", item); + + let name = self.name(); + let mut canonical_name = item.canonical_name(ctx); + let mangled_name = self.mangled_name(); + + { + let seen_symbol_name = mangled_name.unwrap_or(&canonical_name); + + // TODO: Maybe warn here if there's a type/argument mismatch, or + // something? + if result.seen_function(seen_symbol_name) { + return; + } + result.saw_function(seen_symbol_name); + } + + let signature_item = ctx.resolve_item(self.signature()); + let signature = signature_item.kind().expect_type().canonical_type(ctx); + let signature = match *signature.kind() { + TypeKind::Function(ref sig) => sig, + _ => panic!("Signature kind is not a Function: {:?}", signature), + }; + + let fndecl = utils::rust_fndecl_from_signature(ctx, signature_item); + + let mut attributes = vec![]; + + if ctx.options().generate_comments { + if let Some(comment) = item.comment() { + attributes.push(attributes::doc(comment)); + } + } + + if let Some(mangled) = mangled_name { + attributes.push(attributes::link_name(mangled)); + } else if name != canonical_name { + attributes.push(attributes::link_name(name)); + } + + let foreign_item_kind = + ast::ForeignItemKind::Fn(fndecl, ast::Generics::default()); + + // Handle overloaded functions by giving each overload its own unique + // suffix. + let times_seen = result.overload_number(&canonical_name); + if times_seen > 0 { + write!(&mut canonical_name, "{}", times_seen).unwrap(); + } + + let foreign_item = ast::ForeignItem { + ident: ctx.rust_ident_raw(&canonical_name), + attrs: attributes, + node: foreign_item_kind, + id: ast::DUMMY_NODE_ID, + span: ctx.span(), + vis: ast::Visibility::Public, + }; + + let item = ForeignModBuilder::new(signature.abi()) + .with_foreign_item(foreign_item) + .build(ctx); + + result.push(item); + } +} + +pub fn codegen(context: &mut BindgenContext) -> Vec> { + context.gen(|context| { + let counter = Cell::new(0); + let mut result = CodegenResult::new(&counter); + + debug!("codegen: {:?}", context.options()); + + let whitelisted_items: ItemSet = context.whitelisted_items().collect(); + + if context.options().emit_ir { + for &id in whitelisted_items.iter() { + let item = context.resolve_item(id); + println!("ir: {:?} = {:#?}", id, item); + } + } + + context.resolve_item(context.root_module()) + .codegen(context, &mut result, &whitelisted_items, &()); + + result.items + }) +} + +mod utils { + use aster; + use ir::context::{BindgenContext, ItemId}; + use ir::item::{Item, ItemCanonicalPath}; + use ir::ty::TypeKind; + use std::mem; + use super::ItemToRustTy; + use syntax::ast; + use syntax::ptr::P; + + pub fn prepend_union_types(ctx: &BindgenContext, + result: &mut Vec>) { + let prefix = ctx.trait_prefix(); + + // TODO(emilio): The fmt::Debug impl could be way nicer with + // std::intrinsics::type_name, but... + let union_field_decl = quote_item!(ctx.ext_cx(), + #[repr(C)] + pub struct __BindgenUnionField( + ::$prefix::marker::PhantomData); + ) + .unwrap(); + + let union_field_impl = quote_item!(&ctx.ext_cx(), + impl __BindgenUnionField { + #[inline] + pub fn new() -> Self { + __BindgenUnionField(::$prefix::marker::PhantomData) + } + + #[inline] + pub unsafe fn as_ref(&self) -> &T { + ::$prefix::mem::transmute(self) + } + + #[inline] + pub unsafe fn as_mut(&mut self) -> &mut T { + ::$prefix::mem::transmute(self) + } + } + ) + .unwrap(); + + let union_field_default_impl = quote_item!(&ctx.ext_cx(), + impl ::$prefix::default::Default for __BindgenUnionField { + #[inline] + fn default() -> Self { + Self::new() + } + } + ) + .unwrap(); + + let union_field_clone_impl = quote_item!(&ctx.ext_cx(), + impl ::$prefix::clone::Clone for __BindgenUnionField { + #[inline] + fn clone(&self) -> Self { + Self::new() + } + } + ) + .unwrap(); + + let union_field_copy_impl = quote_item!(&ctx.ext_cx(), + impl ::$prefix::marker::Copy for __BindgenUnionField {} + ) + .unwrap(); + + let union_field_debug_impl = quote_item!(ctx.ext_cx(), + impl ::std::fmt::Debug for __BindgenUnionField { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter) + -> ::std::fmt::Result { + fmt.write_str("__BindgenUnionField") + } + } + ) + .unwrap(); + + let items = vec![ + union_field_decl, union_field_impl, + union_field_default_impl, + union_field_clone_impl, + union_field_copy_impl, + union_field_debug_impl, + ]; + + let old_items = mem::replace(result, items); + result.extend(old_items.into_iter()); + } + + pub fn prepend_complex_type(ctx: &BindgenContext, + result: &mut Vec>) { + let complex_type = quote_item!(ctx.ext_cx(), + #[derive(PartialEq, Copy, Clone, Hash, Debug, Default)] + #[repr(C)] + pub struct __BindgenComplex { + pub re: T, + pub im: T + } + ) + .unwrap(); + + let items = vec![complex_type]; + let old_items = mem::replace(result, items); + result.extend(old_items.into_iter()); + } + + pub fn build_templated_path(item: &Item, + ctx: &BindgenContext, + template_args: Vec) + -> P { + let path = item.namespace_aware_canonical_path(ctx); + let builder = aster::AstBuilder::new().ty().path(); + + let template_args = template_args + .iter() + .map(|arg| arg.to_rust_ty(ctx)) + .collect::>(); + + // XXX: I suck at aster. + if path.len() == 1 { + return builder.segment(&path[0]) + .with_tys(template_args) + .build() + .build(); + } + + let mut builder = builder.id(&path[0]); + for (i, segment) in path.iter().skip(1).enumerate() { + // Take into account the skip(1) + builder = if i == path.len() - 2 { + // XXX Extra clone courtesy of the borrow checker. + builder.segment(&segment) + .with_tys(template_args.clone()) + .build() + } else { + builder.segment(&segment).build() + } + } + + builder.build() + } + + fn primitive_ty(ctx: &BindgenContext, name: &str) -> P { + let ident = ctx.rust_ident_raw(&name); + quote_ty!(ctx.ext_cx(), $ident) + } + + pub fn type_from_named(ctx: &BindgenContext, + name: &str, + _inner: ItemId) + -> Option> { + // FIXME: We could use the inner item to check this is really a + // primitive type but, who the heck overrides these anyway? + Some(match name { + "int8_t" => primitive_ty(ctx, "i8"), + "uint8_t" => primitive_ty(ctx, "u8"), + "int16_t" => primitive_ty(ctx, "i16"), + "uint16_t" => primitive_ty(ctx, "u16"), + "int32_t" => primitive_ty(ctx, "i32"), + "uint32_t" => primitive_ty(ctx, "u32"), + "int64_t" => primitive_ty(ctx, "i64"), + "uint64_t" => primitive_ty(ctx, "u64"), + + "uintptr_t" | "size_t" => primitive_ty(ctx, "usize"), + + "intptr_t" | "ptrdiff_t" | "ssize_t" => primitive_ty(ctx, "isize"), + _ => return None, + }) + } + + pub fn rust_fndecl_from_signature(ctx: &BindgenContext, + sig: &Item) + -> P { + use codegen::ToRustTy; + + let signature = sig.kind().expect_type().canonical_type(ctx); + let signature = match *signature.kind() { + TypeKind::Function(ref sig) => sig, + _ => panic!("How?"), + }; + + let decl_ty = signature.to_rust_ty(ctx, sig); + match decl_ty.unwrap().node { + ast::TyKind::BareFn(bare_fn) => bare_fn.unwrap().decl, + _ => panic!("How did this happen exactly?"), + } + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/annotations.rs b/bash-5.1/vendor/bindgen/src/ir/annotations.rs new file mode 100644 index 0000000..98be054 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/annotations.rs @@ -0,0 +1,188 @@ +//! Types and functions related to bindgen annotation comments. +//! +//! Users can add annotations in doc comments to types that they would like to +//! replace other types with, mark as opaque, etc. This module deals with all of +//! that stuff. + +use clang; + +/// What kind of accessor should we provide for a field? +#[derive(Copy, PartialEq, Clone, Debug)] +pub enum FieldAccessorKind { + /// No accessor. + None, + /// Plain accessor. + Regular, + /// Unsafe accessor. + Unsafe, + /// Immutable accessor. + Immutable, +} + +/// Annotations for a given item, or a field. +/// +/// You can see the kind of comments that are accepted in the Doxygen +/// documentation: +/// +/// http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html +#[derive(Clone, PartialEq, Debug)] +pub struct Annotations { + /// Whether this item is marked as opaque. Only applies to types. + opaque: bool, + /// Whether this item should be hidden from the output. Only applies to + /// types, or enum variants. + hide: bool, + /// Whether this type should be replaced by another. The name is a + /// namespace-aware path. + use_instead_of: Option>, + /// Manually disable deriving copy/clone on this type. Only applies to + /// struct or union types. + disallow_copy: bool, + /// Whether fields should be marked as private or not. You can set this on + /// structs (it will apply to all the fields), or individual fields. + private_fields: Option, + /// The kind of accessor this field will have. Also can be applied to + /// structs so all the fields inside share it by default. + accessor_kind: Option, + /// Whether this enum variant should be constified. + /// + /// This is controlled by the `constant` attribute, this way: + /// + /// ```cpp + /// enum Foo { + /// Bar = 0, /**<
*/ + /// Baz = 0, + /// }; + /// ``` + /// + /// In that case, bindgen will generate a constant for `Bar` instead of + /// `Baz`. + constify_enum_variant: bool, +} + +fn parse_accessor(s: &str) -> FieldAccessorKind { + match s { + "false" => FieldAccessorKind::None, + "unsafe" => FieldAccessorKind::Unsafe, + "immutable" => FieldAccessorKind::Immutable, + _ => FieldAccessorKind::Regular, + } +} + +impl Default for Annotations { + fn default() -> Self { + Annotations { + opaque: false, + hide: false, + use_instead_of: None, + disallow_copy: false, + private_fields: None, + accessor_kind: None, + constify_enum_variant: false, + } + } +} + +impl Annotations { + /// Construct new annotations for the given cursor and its bindgen comments + /// (if any). + pub fn new(cursor: &clang::Cursor) -> Option { + let mut anno = Annotations::default(); + let mut matched_one = false; + anno.parse(&cursor.comment(), &mut matched_one); + + if matched_one { Some(anno) } else { None } + } + + /// Should this type be hidden? + pub fn hide(&self) -> bool { + self.hide + } + + /// Should this type be opaque? + pub fn opaque(&self) -> bool { + self.opaque + } + + /// For a given type, indicates the type it should replace. + /// + /// For example, in the following code: + /// + /// ```cpp + /// + /// /**
*/ + /// struct Foo { int x; }; + /// + /// struct Bar { char foo; }; + /// ``` + /// + /// the generated code would look something like: + /// + /// ``` + /// /**
*/ + /// struct Bar { + /// x: ::std::os::raw::c_int, + /// }; + /// ``` + /// + /// That is, code for `Foo` is used to generate `Bar`. + pub fn use_instead_of(&self) -> Option<&[String]> { + self.use_instead_of.as_ref().map(|s| &**s) + } + + /// Should we avoid implementing the `Copy` trait? + pub fn disallow_copy(&self) -> bool { + self.disallow_copy + } + + /// Should the fields be private? + pub fn private_fields(&self) -> Option { + self.private_fields + } + + /// What kind of accessors should we provide for this type's fields? + pub fn accessor_kind(&self) -> Option { + self.accessor_kind + } + + fn parse(&mut self, comment: &clang::Comment, matched: &mut bool) { + use clang_sys::CXComment_HTMLStartTag; + if comment.kind() == CXComment_HTMLStartTag && + comment.get_tag_name() == "div" && + comment.get_tag_attrs() + .next() + .map_or(false, |attr| attr.name == "rustbindgen") { + *matched = true; + for attr in comment.get_tag_attrs() { + match attr.name.as_str() { + "opaque" => self.opaque = true, + "hide" => self.hide = true, + "nocopy" => self.disallow_copy = true, + "replaces" => { + self.use_instead_of = Some(attr.value + .split("::") + .map(Into::into) + .collect()) + } + "private" => { + self.private_fields = Some(attr.value != "false") + } + "accessor" => { + self.accessor_kind = Some(parse_accessor(&attr.value)) + } + "constant" => self.constify_enum_variant = true, + _ => {} + } + } + } + + for child in comment.get_children() { + self.parse(&child, matched); + } + } + + /// Returns whether we've parsed a "constant" attribute. + pub fn constify_enum_variant(&self) -> bool { + self.constify_enum_variant + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/comp.rs b/bash-5.1/vendor/bindgen/src/ir/comp.rs new file mode 100644 index 0000000..bad661d --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/comp.rs @@ -0,0 +1,986 @@ +//! Compound types (unions and structs) in our intermediate representation. + +use clang; +use parse::{ClangItemParser, ParseError}; +use std::cell::Cell; +use super::annotations::Annotations; +use super::context::{BindgenContext, ItemId}; +use super::derive::{CanDeriveCopy, CanDeriveDebug}; +use super::item::Item; +use super::layout::Layout; +use super::ty::Type; +use super::type_collector::{ItemSet, TypeCollector}; + +/// The kind of compound type. +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum CompKind { + /// A struct. + Struct, + /// A union. + Union, +} + +/// The kind of C++ method. +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum MethodKind { + /// A constructor. We represent it as method for convenience, to avoid code + /// duplication. + Constructor, + /// A static method. + Static, + /// A normal method. + Normal, + /// A virtual method. + Virtual, +} + +/// A struct representing a C++ method, either static, normal, or virtual. +#[derive(Debug)] +pub struct Method { + kind: MethodKind, + /// The signature of the method. Take into account this is not a `Type` + /// item, but a `Function` one. + /// + /// This is tricky and probably this field should be renamed. + signature: ItemId, + is_const: bool, +} + +impl Method { + /// Construct a new `Method`. + pub fn new(kind: MethodKind, signature: ItemId, is_const: bool) -> Self { + Method { + kind: kind, + signature: signature, + is_const: is_const, + } + } + + /// What kind of method is this? + pub fn kind(&self) -> MethodKind { + self.kind + } + + /// Is this a constructor? + pub fn is_constructor(&self) -> bool { + self.kind == MethodKind::Constructor + } + + /// Is this a virtual method? + pub fn is_virtual(&self) -> bool { + self.kind == MethodKind::Virtual + } + + /// Is this a static method? + pub fn is_static(&self) -> bool { + self.kind == MethodKind::Static + } + + /// Get the `ItemId` for the `Function` signature for this method. + pub fn signature(&self) -> ItemId { + self.signature + } + + /// Is this a const qualified method? + pub fn is_const(&self) -> bool { + self.is_const + } +} + +/// A struct representing a C++ field. +#[derive(Clone, Debug)] +pub struct Field { + /// The name of the field, empty if it's an unnamed bitfield width. + name: Option, + /// The inner type. + ty: ItemId, + /// The doc comment on the field if any. + comment: Option, + /// Annotations for this field, or the default. + annotations: Annotations, + /// If this field is a bitfield, and how many bits does it contain if it is. + bitfield: Option, + /// If the C++ field is marked as `mutable` + mutable: bool, +} + +impl Field { + /// Construct a new `Field`. + pub fn new(name: Option, + ty: ItemId, + comment: Option, + annotations: Option, + bitfield: Option, + mutable: bool) + -> Field { + Field { + name: name, + ty: ty, + comment: comment, + annotations: annotations.unwrap_or_default(), + bitfield: bitfield, + mutable: mutable, + } + } + + /// Get the name of this field. + pub fn name(&self) -> Option<&str> { + self.name.as_ref().map(|n| &**n) + } + + /// Get the type of this field. + pub fn ty(&self) -> ItemId { + self.ty + } + + /// Get the comment for this field. + pub fn comment(&self) -> Option<&str> { + self.comment.as_ref().map(|c| &**c) + } + + /// If this is a bitfield, how many bits does it need? + pub fn bitfield(&self) -> Option { + self.bitfield + } + + /// Is this field marked as `mutable`? + pub fn is_mutable(&self) -> bool { + self.mutable + } + + /// Get the annotations for this field. + pub fn annotations(&self) -> &Annotations { + &self.annotations + } +} + +impl CanDeriveDebug for Field { + type Extra = (); + + fn can_derive_debug(&self, ctx: &BindgenContext, _: ()) -> bool { + self.ty.can_derive_debug(ctx, ()) + } +} + +impl<'a> CanDeriveCopy<'a> for Field { + type Extra = (); + + fn can_derive_copy(&self, ctx: &BindgenContext, _: ()) -> bool { + self.ty.can_derive_copy(ctx, ()) + } + + fn can_derive_copy_in_array(&self, ctx: &BindgenContext, _: ()) -> bool { + self.ty.can_derive_copy_in_array(ctx, ()) + } +} + + +/// The kind of inheritance a base class is using. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BaseKind { + /// Normal inheritance, like: + /// + /// ```cpp + /// class A : public B {}; + /// ``` + Normal, + /// Virtual inheritance, like: + /// + /// ```cpp + /// class A: public virtual B {}; + /// ``` + Virtual, +} + +/// A base class. +#[derive(Clone, Debug)] +pub struct Base { + /// The type of this base class. + pub ty: ItemId, + /// The kind of inheritance we're doing. + pub kind: BaseKind, +} + +impl Base { + /// Whether this base class is inheriting virtually. + pub fn is_virtual(&self) -> bool { + self.kind == BaseKind::Virtual + } +} + +/// A compound type. +/// +/// Either a struct or union, a compound type is built up from the combination +/// of fields which also are associated with their own (potentially compound) +/// type. +#[derive(Debug)] +pub struct CompInfo { + /// Whether this is a struct or a union. + kind: CompKind, + + /// The members of this struct or union. + fields: Vec, + + /// The template parameters of this class. These are non-concrete, and + /// should always be a Type(TypeKind::Named(name)), but still they need to + /// be registered with an unique type id in the context. + template_args: Vec, + + /// The method declarations inside this class, if in C++ mode. + methods: Vec, + + /// The different constructors this struct or class contains. + constructors: Vec, + + /// Vector of classes this one inherits from. + base_members: Vec, + + /// The parent reference template if any. + ref_template: Option, + + /// The inner types that were declared inside this class, in something like: + /// + /// class Foo { + /// typedef int FooTy; + /// struct Bar { + /// int baz; + /// }; + /// } + /// + /// static Foo::Bar const = {3}; + inner_types: Vec, + + /// Set of static constants declared inside this class. + inner_vars: Vec, + + /// Whether this type should generate an vtable (TODO: Should be able to + /// look at the virtual methods and ditch this field). + has_vtable: bool, + + /// Whether this type has destructor. + has_destructor: bool, + + /// Whether this type has a base type with more than one member. + /// + /// TODO: We should be able to compute this. + has_nonempty_base: bool, + + /// If this type has a template parameter which is not a type (e.g.: a + /// size_t) + has_non_type_template_params: bool, + + /// Whether this struct layout is packed. + packed: bool, + + /// Whether this struct is anonymous. + is_anonymous: bool, + + /// Used to know if we've found an opaque attribute that could cause us to + /// generate a type with invalid layout. This is explicitly used to avoid us + /// generating bad alignments when parsing types like max_align_t. + /// + /// It's not clear what the behavior should be here, if generating the item + /// and pray, or behave as an opaque type. + found_unknown_attr: bool, + + /// Used to detect if we've run in a can_derive_debug cycle while cycling + /// around the template arguments. + detect_derive_debug_cycle: Cell, + + /// Used to detect if we've run in a has_destructor cycle while cycling + /// around the template arguments. + detect_has_destructor_cycle: Cell, + + /// Used to indicate when a struct has been forward declared. Usually used + /// in headers so that APIs can't modify them directly. + is_forward_declaration: bool, +} + +impl CompInfo { + /// Construct a new compound type. + pub fn new(kind: CompKind) -> Self { + CompInfo { + kind: kind, + fields: vec![], + template_args: vec![], + methods: vec![], + constructors: vec![], + base_members: vec![], + ref_template: None, + inner_types: vec![], + inner_vars: vec![], + has_vtable: false, + has_destructor: false, + has_nonempty_base: false, + has_non_type_template_params: false, + packed: false, + is_anonymous: false, + found_unknown_attr: false, + detect_derive_debug_cycle: Cell::new(false), + detect_has_destructor_cycle: Cell::new(false), + is_forward_declaration: false, + } + } + + /// Is this compound type unsized? + pub fn is_unsized(&self, ctx: &BindgenContext) -> bool { + !self.has_vtable(ctx) && self.fields.is_empty() && + self.base_members.iter().all(|base| { + ctx.resolve_type(base.ty).canonical_type(ctx).is_unsized(ctx) + }) && + self.ref_template + .map_or(true, |template| ctx.resolve_type(template).is_unsized(ctx)) + } + + /// Does this compound type have a destructor? + pub fn has_destructor(&self, ctx: &BindgenContext) -> bool { + if self.detect_has_destructor_cycle.get() { + warn!("Cycle detected looking for destructors"); + // Assume no destructor, since we don't have an explicit one. + return false; + } + + self.detect_has_destructor_cycle.set(true); + + let has_destructor = self.has_destructor || + match self.kind { + CompKind::Union => false, + CompKind::Struct => { + // NB: We can't rely on a type with type parameters + // not having destructor. + // + // This is unfortunate, but... + self.ref_template.as_ref().map_or(false, |t| { + ctx.resolve_type(*t).has_destructor(ctx) + }) || + self.template_args.iter().any(|t| { + ctx.resolve_type(*t).has_destructor(ctx) + }) || + self.base_members.iter().any(|base| { + ctx.resolve_type(base.ty).has_destructor(ctx) + }) || + self.fields.iter().any(|field| { + ctx.resolve_type(field.ty) + .has_destructor(ctx) + }) + } + }; + + self.detect_has_destructor_cycle.set(false); + + has_destructor + } + + /// Is this type a template specialization? + pub fn is_template_specialization(&self) -> bool { + self.ref_template.is_some() + } + + /// Get the template declaration this specialization is specializing. + pub fn specialized_template(&self) -> Option { + self.ref_template + } + + /// Compute the layout of this type. + /// + /// This is called as a fallback under some circumstances where LLVM doesn't + /// give us the correct layout. + /// + /// If we're a union without known layout, we try to compute it from our + /// members. This is not ideal, but clang fails to report the size for these + /// kind of unions, see test/headers/template_union.hpp + pub fn layout(&self, ctx: &BindgenContext) -> Option { + use std::cmp; + + // We can't do better than clang here, sorry. + if self.kind == CompKind::Struct { + return None; + } + + let mut max_size = 0; + let mut max_align = 0; + for field in &self.fields { + let field_layout = ctx.resolve_type(field.ty) + .layout(ctx); + + if let Some(layout) = field_layout { + max_size = cmp::max(max_size, layout.size); + max_align = cmp::max(max_align, layout.align); + } + } + + Some(Layout::new(max_size, max_align)) + } + + /// Get this type's set of fields. + pub fn fields(&self) -> &[Field] { + &self.fields + } + + /// Get this type's set of free template arguments. Empty if this is not a + /// template. + pub fn template_args(&self) -> &[ItemId] { + &self.template_args + } + + /// Does this type have any template parameters that aren't types + /// (e.g. int)? + pub fn has_non_type_template_params(&self) -> bool { + self.has_non_type_template_params + } + + /// Does this type have a virtual table? + pub fn has_vtable(&self, ctx: &BindgenContext) -> bool { + self.has_vtable || + self.base_members().iter().any(|base| { + ctx.resolve_type(base.ty) + .has_vtable(ctx) + }) || + self.ref_template.map_or(false, |template| { + ctx.resolve_type(template).has_vtable(ctx) + }) + } + + /// Get this type's set of methods. + pub fn methods(&self) -> &[Method] { + &self.methods + } + + /// Get this type's set of constructors. + pub fn constructors(&self) -> &[ItemId] { + &self.constructors + } + + /// What kind of compound type is this? + pub fn kind(&self) -> CompKind { + self.kind + } + + /// The set of types that this one inherits from. + pub fn base_members(&self) -> &[Base] { + &self.base_members + } + + /// Construct a new compound type from a Clang type. + pub fn from_ty(potential_id: ItemId, + ty: &clang::Type, + location: Option, + ctx: &mut BindgenContext) + -> Result { + use clang_sys::*; + // Sigh... For class templates we want the location, for + // specialisations, we want the declaration... So just try both. + // + // TODO: Yeah, this code reads really bad. + let mut cursor = ty.declaration(); + let mut kind = Self::kind_from_cursor(&cursor); + if kind.is_err() { + if let Some(location) = location { + kind = Self::kind_from_cursor(&location); + cursor = location; + } + } + + let kind = try!(kind); + + debug!("CompInfo::from_ty({:?}, {:?})", kind, cursor); + + let mut ci = CompInfo::new(kind); + ci.is_forward_declaration = location.map_or(true, |cur| { + match cur.kind() { + CXCursor_StructDecl | + CXCursor_UnionDecl | + CXCursor_ClassDecl => !cur.is_definition(), + _ => false, + } + }); + ci.is_anonymous = cursor.is_anonymous(); + ci.template_args = match ty.template_args() { + // In forward declarations and not specializations, + // etc, they are in + // the ast, we'll meet them in + // CXCursor_TemplateTypeParameter + None => vec![], + Some(arg_types) => { + let num_arg_types = arg_types.len(); + let mut specialization = true; + + let args = arg_types.filter(|t| t.kind() != CXType_Invalid) + .filter_map(|t| { + if t.spelling().starts_with("type-parameter") { + specialization = false; + None + } else { + Some(Item::from_ty_or_ref(t, None, None, ctx)) + } + }) + .collect::>(); + + if specialization && args.len() != num_arg_types { + ci.has_non_type_template_params = true; + warn!("warning: Template parameter is not a type"); + } + + if specialization { args } else { vec![] } + } + }; + + ci.ref_template = cursor.specialized() + .and_then(|c| Item::parse(c, None, ctx).ok()); + + let mut maybe_anonymous_struct_field = None; + cursor.visit(|cur| { + if cur.kind() != CXCursor_FieldDecl { + if let Some((ty, _)) = maybe_anonymous_struct_field { + let field = Field::new(None, ty, None, None, None, false); + ci.fields.push(field); + } + maybe_anonymous_struct_field = None; + } + + match cur.kind() { + CXCursor_FieldDecl => { + match maybe_anonymous_struct_field.take() { + Some((ty, clang_ty)) => { + let mut used = false; + cur.visit(|child| { + if child.cur_type() == clang_ty { + used = true; + } + CXChildVisit_Continue + }); + if !used { + let field = Field::new(None, + ty, + None, + None, + None, + false); + ci.fields.push(field); + } + } + None => {} + } + + let bit_width = cur.bit_width(); + let field_type = Item::from_ty_or_ref(cur.cur_type(), + Some(cur), + Some(potential_id), + ctx); + + let comment = cur.raw_comment(); + let annotations = Annotations::new(&cur); + let name = cur.spelling(); + let is_mutable = cursor.is_mutable_field(); + + // Name can be empty if there are bitfields, for example, + // see tests/headers/struct_with_bitfields.h + assert!(!name.is_empty() || bit_width.is_some(), + "Empty field name?"); + + let name = if name.is_empty() { None } else { Some(name) }; + + let field = Field::new(name, + field_type, + comment, + annotations, + bit_width, + is_mutable); + ci.fields.push(field); + + // No we look for things like attributes and stuff. + cur.visit(|cur| { + if cur.kind() == CXCursor_UnexposedAttr { + ci.found_unknown_attr = true; + } + CXChildVisit_Continue + }); + + } + CXCursor_UnexposedAttr => { + ci.found_unknown_attr = true; + } + CXCursor_EnumDecl | + CXCursor_TypeAliasDecl | + CXCursor_TypedefDecl | + CXCursor_StructDecl | + CXCursor_UnionDecl | + CXCursor_ClassTemplate | + CXCursor_ClassDecl => { + let inner = Item::parse(cur, Some(potential_id), ctx) + .expect("Inner ClassDecl"); + if !ci.inner_types.contains(&inner) { + ci.inner_types.push(inner); + } + // A declaration of an union or a struct without name could + // also be an unnamed field, unfortunately. + if cur.spelling().is_empty() && + cur.kind() != CXCursor_EnumDecl { + let ty = cur.cur_type(); + maybe_anonymous_struct_field = Some((inner, ty)); + } + } + CXCursor_PackedAttr => { + ci.packed = true; + } + CXCursor_TemplateTypeParameter => { + // Yes! You can arrive here with an empty template parameter + // name! Awesome, isn't it? + // + // see tests/headers/empty_template_param_name.hpp + if cur.spelling().is_empty() { + return CXChildVisit_Continue; + } + + let param = + Item::named_type(cur.spelling(), potential_id, ctx); + ci.template_args.push(param); + } + CXCursor_CXXBaseSpecifier => { + let is_virtual_base = cur.is_virtual_base(); + ci.has_vtable |= is_virtual_base; + + let kind = if is_virtual_base { + BaseKind::Virtual + } else { + BaseKind::Normal + }; + + let type_id = Item::from_ty_or_ref(cur.cur_type(), + Some(cur), + None, + ctx); + ci.base_members.push(Base { + ty: type_id, + kind: kind, + }); + } + CXCursor_Constructor | + CXCursor_Destructor | + CXCursor_CXXMethod => { + let is_virtual = cur.method_is_virtual(); + let is_static = cur.method_is_static(); + debug_assert!(!(is_static && is_virtual), "How?"); + + ci.has_destructor |= cur.kind() == CXCursor_Destructor; + ci.has_vtable |= is_virtual; + + // This used to not be here, but then I tried generating + // stylo bindings with this (without path filters), and + // cried a lot with a method in gfx/Point.h + // (ToUnknownPoint), that somehow was causing the same type + // to be inserted in the map two times. + // + // I couldn't make a reduced test case, but anyway... + // Methods of template functions not only use to be inlined, + // but also instantiated, and we wouldn't be able to call + // them, so just bail out. + if !ci.template_args.is_empty() { + return CXChildVisit_Continue; + } + + // NB: This gets us an owned `Function`, not a + // `FunctionSig`. + let signature = match Item::parse(cur, Some(potential_id), ctx) { + Ok(item) if ctx.resolve_item(item).kind().is_function() => item, + _ => return CXChildVisit_Continue, + }; + + match cur.kind() { + CXCursor_Constructor => { + ci.constructors.push(signature); + } + // TODO(emilio): Bind the destructor? + CXCursor_Destructor => {} + CXCursor_CXXMethod => { + let is_const = cur.method_is_const(); + let method_kind = if is_static { + MethodKind::Static + } else if is_virtual { + MethodKind::Virtual + } else { + MethodKind::Normal + }; + + let method = + Method::new(method_kind, signature, is_const); + + ci.methods.push(method); + } + _ => unreachable!("How can we see this here?"), + } + } + CXCursor_NonTypeTemplateParameter => { + ci.has_non_type_template_params = true; + } + CXCursor_VarDecl => { + let linkage = cur.linkage(); + if linkage != CXLinkage_External && + linkage != CXLinkage_UniqueExternal { + return CXChildVisit_Continue; + } + + let visibility = cur.visibility(); + if visibility != CXVisibility_Default { + return CXChildVisit_Continue; + } + + if let Ok(item) = Item::parse(cur, + Some(potential_id), + ctx) { + ci.inner_vars.push(item); + } + } + // Intentionally not handled + CXCursor_CXXAccessSpecifier | + CXCursor_CXXFinalAttr | + CXCursor_FunctionTemplate | + CXCursor_ConversionFunction => {} + _ => { + warn!("unhandled comp member `{}` (kind {:?}) in `{}` ({})", + cur.spelling(), + cur.kind(), + cursor.spelling(), + cur.location()); + } + } + CXChildVisit_Continue + }); + + if let Some((ty, _)) = maybe_anonymous_struct_field { + let field = Field::new(None, ty, None, None, None, false); + ci.fields.push(field); + } + + Ok(ci) + } + + fn kind_from_cursor(cursor: &clang::Cursor) + -> Result { + use clang_sys::*; + Ok(match cursor.kind() { + CXCursor_UnionDecl => CompKind::Union, + CXCursor_ClassDecl | + CXCursor_StructDecl => CompKind::Struct, + CXCursor_CXXBaseSpecifier | + CXCursor_ClassTemplatePartialSpecialization | + CXCursor_ClassTemplate => { + match cursor.template_kind() { + CXCursor_UnionDecl => CompKind::Union, + _ => CompKind::Struct, + } + } + _ => { + warn!("Unknown kind for comp type: {:?}", cursor); + return Err(ParseError::Continue); + } + }) + } + + /// Do any of the types that participate in this type's "signature" use the + /// named type `ty`? + /// + /// See also documentation for `ir::Item::signature_contains_named_type`. + pub fn signature_contains_named_type(&self, + ctx: &BindgenContext, + ty: &Type) + -> bool { + // We don't generate these, so rather don't make the codegen step to + // think we got it covered. + if self.has_non_type_template_params() { + return false; + } + self.template_args.iter().any(|arg| { + ctx.resolve_type(*arg) + .signature_contains_named_type(ctx, ty) + }) + } + + /// Get the set of types that were declared within this compound type + /// (e.g. nested class definitions). + pub fn inner_types(&self) -> &[ItemId] { + &self.inner_types + } + + /// Get the set of static variables declared within this compound type. + pub fn inner_vars(&self) -> &[ItemId] { + &self.inner_vars + } + + /// Have we found a field with an opaque type that could potentially mess up + /// the layout of this compound type? + pub fn found_unknown_attr(&self) -> bool { + self.found_unknown_attr + } + + /// Is this compound type packed? + pub fn packed(&self) -> bool { + self.packed + } + + /// Returns whether this type needs an explicit vtable because it has + /// virtual methods and none of its base classes has already a vtable. + pub fn needs_explicit_vtable(&self, ctx: &BindgenContext) -> bool { + self.has_vtable(ctx) && + !self.base_members.iter().any(|base| { + // NB: Ideally, we could rely in all these types being `comp`, and + // life would be beautiful. + // + // Unfortunately, given the way we implement --match-pat, and also + // that you can inherit from templated types, we need to handle + // other cases here too. + ctx.resolve_type(base.ty) + .canonical_type(ctx) + .as_comp() + .map_or(false, |ci| ci.has_vtable(ctx)) + }) + } + + /// Returns true if compound type has been forward declared + pub fn is_forward_declaration(&self) -> bool { + self.is_forward_declaration + } +} + +impl CanDeriveDebug for CompInfo { + type Extra = Option; + + fn can_derive_debug(&self, + ctx: &BindgenContext, + layout: Option) + -> bool { + if self.has_non_type_template_params() { + return layout.map_or(false, |l| l.opaque().can_derive_debug(ctx, ())); + } + + // We can reach here recursively via template parameters of a member, + // for example. + if self.detect_derive_debug_cycle.get() { + warn!("Derive debug cycle detected!"); + return true; + } + + if self.kind == CompKind::Union { + if ctx.options().unstable_rust { + return false; + } + + return layout.unwrap_or_else(Layout::zero) + .opaque() + .can_derive_debug(ctx, ()); + } + + self.detect_derive_debug_cycle.set(true); + + let can_derive_debug = { + self.base_members + .iter() + .all(|base| base.ty.can_derive_debug(ctx, ())) && + self.template_args + .iter() + .all(|id| id.can_derive_debug(ctx, ())) && + self.fields + .iter() + .all(|f| f.can_derive_debug(ctx, ())) && + self.ref_template.map_or(true, |id| id.can_derive_debug(ctx, ())) + }; + + self.detect_derive_debug_cycle.set(false); + + can_derive_debug + } +} + +impl<'a> CanDeriveCopy<'a> for CompInfo { + type Extra = (&'a Item, Option); + + fn can_derive_copy(&self, + ctx: &BindgenContext, + (item, layout): (&Item, Option)) + -> bool { + if self.has_non_type_template_params() { + return layout.map_or(false, |l| l.opaque().can_derive_copy(ctx, ())); + } + + // NOTE: Take into account that while unions in C and C++ are copied by + // default, the may have an explicit destructor in C++, so we can't + // defer this check just for the union case. + if self.has_destructor(ctx) { + return false; + } + + if self.kind == CompKind::Union { + if !ctx.options().unstable_rust { + // NOTE: If there's no template parameters we can derive copy + // unconditionally, since arrays are magical for rustc, and + // __BindgenUnionField always implements copy. + return true; + } + + // https://github.com/rust-lang/rust/issues/36640 + if !self.template_args.is_empty() || self.ref_template.is_some() || + !item.applicable_template_args(ctx).is_empty() { + return false; + } + } + + // With template args, use a safe subset of the types, + // since copyability depends on the types itself. + self.ref_template + .as_ref() + .map_or(true, |t| t.can_derive_copy(ctx, ())) && + self.base_members + .iter() + .all(|base| base.ty.can_derive_copy(ctx, ())) && + self.fields.iter().all(|field| field.can_derive_copy(ctx, ())) + } + + fn can_derive_copy_in_array(&self, + ctx: &BindgenContext, + extra: (&Item, Option)) + -> bool { + self.can_derive_copy(ctx, extra) + } +} + +impl TypeCollector for CompInfo { + type Extra = Item; + + fn collect_types(&self, + context: &BindgenContext, + types: &mut ItemSet, + item: &Item) { + if let Some(template) = self.specialized_template() { + types.insert(template); + } + + let applicable_template_args = item.applicable_template_args(context); + for arg in applicable_template_args { + types.insert(arg); + } + + for base in self.base_members() { + types.insert(base.ty); + } + + for field in self.fields() { + types.insert(field.ty()); + } + + for &ty in self.inner_types() { + types.insert(ty); + } + + for &var in self.inner_vars() { + types.insert(var); + } + + for method in self.methods() { + types.insert(method.signature); + } + + for &ctor in self.constructors() { + types.insert(ctor); + } + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/context.rs b/bash-5.1/vendor/bindgen/src/ir/context.rs new file mode 100644 index 0000000..50774a4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/context.rs @@ -0,0 +1,1269 @@ +//! Common context that is passed around during parsing and codegen. + +use BindgenOptions; +use cexpr; +use chooser::TypeChooser; +use clang::{self, Cursor}; +use parse::ClangItemParser; +use std::borrow::Cow; +use std::cell::Cell; +use std::collections::{HashMap, VecDeque, hash_map}; +use std::collections::btree_map::{self, BTreeMap}; +use std::fmt; +use super::derive::{CanDeriveCopy, CanDeriveDebug}; +use super::int::IntKind; +use super::item::{Item, ItemCanonicalPath}; +use super::item_kind::ItemKind; +use super::module::{Module, ModuleKind}; +use super::ty::{FloatKind, Type, TypeKind}; +use super::type_collector::{ItemSet, TypeCollector}; +use syntax::ast::Ident; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::ext::base::ExtCtxt; + +/// A single identifier for an item. +/// +/// TODO: Build stronger abstractions on top of this, like TypeId(ItemId)? +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ItemId(usize); + +impl ItemId { + /// Get a numeric representation of this id. + pub fn as_usize(&self) -> usize { + self.0 + } +} + +impl CanDeriveDebug for ItemId { + type Extra = (); + + fn can_derive_debug(&self, ctx: &BindgenContext, _: ()) -> bool { + ctx.resolve_item(*self).can_derive_debug(ctx, ()) + } +} + +impl<'a> CanDeriveCopy<'a> for ItemId { + type Extra = (); + + fn can_derive_copy(&self, ctx: &BindgenContext, _: ()) -> bool { + ctx.resolve_item(*self).can_derive_copy(ctx, ()) + } + + fn can_derive_copy_in_array(&self, ctx: &BindgenContext, _: ()) -> bool { + ctx.resolve_item(*self).can_derive_copy_in_array(ctx, ()) + } +} + +/// A key used to index a resolved type, so we only process it once. +/// +/// This is almost always a USR string (an unique identifier generated by +/// clang), but it can also be the canonical declaration if the type is unnamed, +/// in which case clang may generate the same USR for multiple nested unnamed +/// types. +#[derive(Eq, PartialEq, Hash, Debug)] +enum TypeKey { + USR(String), + Declaration(Cursor), +} + +// This is just convenience to avoid creating a manual debug impl for the +// context. +struct GenContext<'ctx>(ExtCtxt<'ctx>); + +impl<'ctx> fmt::Debug for GenContext<'ctx> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "GenContext {{ ... }}") + } +} + +/// A context used during parsing and generation of structs. +#[derive(Debug)] +pub struct BindgenContext<'ctx> { + /// The map of all the items parsed so far. + /// + /// It's a BTreeMap because we want the keys to be sorted to have consistent + /// output. + items: BTreeMap, + + /// The next item id to use during this bindings regeneration. + next_item_id: ItemId, + + /// Clang USR to type map. This is needed to be able to associate types with + /// item ids during parsing. + types: HashMap, + + /// A cursor to module map. Similar reason than above. + modules: HashMap, + + /// The root module, this is guaranteed to be an item of kind Module. + root_module: ItemId, + + /// Current module being traversed. + current_module: ItemId, + + /// A stack with the current type declarations and types we're parsing. This + /// is needed to avoid infinite recursion when parsing a type like: + /// + /// struct c { struct c* next; }; + /// + /// This means effectively, that a type has a potential ID before knowing if + /// it's a correct type. But that's not important in practice. + /// + /// We could also use the `types` HashMap, but my intention with it is that + /// only valid types and declarations end up there, and this could + /// potentially break that assumption. + /// + /// FIXME: Should not be public, though... meh. + pub currently_parsed_types: Vec<(Cursor, ItemId)>, + + /// A HashSet with all the already parsed macro names. This is done to avoid + /// hard errors while parsing duplicated macros, as well to allow macro + /// expression parsing. + parsed_macros: HashMap, cexpr::expr::EvalResult>, + + /// The active replacements collected from replaces="xxx" annotations. + replacements: HashMap, ItemId>, + + collected_typerefs: bool, + + /// Dummy structures for code generation. + gen_ctx: Option<&'ctx GenContext<'ctx>>, + span: Span, + + /// The clang index for parsing. + index: clang::Index, + + /// The translation unit for parsing. + translation_unit: clang::TranslationUnit, + + /// The options given by the user via cli or other medium. + options: BindgenOptions, + + /// Whether a bindgen complex was generated + generated_bindegen_complex: Cell, +} + +impl<'ctx> BindgenContext<'ctx> { + /// Construct the context for the given `options`. + pub fn new(options: BindgenOptions) -> Self { + use clang_sys; + + let index = clang::Index::new(false, true); + + let parse_options = + clang_sys::CXTranslationUnit_DetailedPreprocessingRecord; + let translation_unit = + clang::TranslationUnit::parse(&index, + "", + &options.clang_args, + &[], + parse_options) + .expect("TranslationUnit::parse"); + + let root_module = Self::build_root_module(ItemId(0)); + let mut me = BindgenContext { + items: Default::default(), + types: Default::default(), + modules: Default::default(), + next_item_id: ItemId(1), + root_module: root_module.id(), + current_module: root_module.id(), + currently_parsed_types: vec![], + parsed_macros: Default::default(), + replacements: Default::default(), + collected_typerefs: false, + gen_ctx: None, + span: DUMMY_SP, + index: index, + translation_unit: translation_unit, + options: options, + generated_bindegen_complex: Cell::new(false), + }; + + me.add_item(root_module, None, None); + + me + } + + /// Get the user-provided type chooser by reference, if any. + pub fn type_chooser(&self) -> Option<&TypeChooser> { + self.options().type_chooser.as_ref().map(|t| &**t) + } + + /// Define a new item. + /// + /// This inserts it into the internal items set, and its type into the + /// internal types set. + pub fn add_item(&mut self, + item: Item, + declaration: Option, + location: Option) { + debug!("BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}", + item, + declaration, + location); + debug_assert!(declaration.is_some() || !item.kind().is_type() || + item.kind().expect_type().is_builtin_or_named(), + "Adding a type without declaration?"); + + let id = item.id(); + let is_type = item.kind().is_type(); + let is_unnamed = is_type && item.expect_type().name().is_none(); + + // Be sure to track all the generated children under namespace, even + // those generated after resolving typerefs, etc. + if item.id() != item.parent_id() { + if let Some(mut parent) = self.items.get_mut(&item.parent_id()) { + if let Some(mut module) = parent.as_module_mut() { + module.children_mut().push(item.id()); + } + } + } + + let old_item = self.items.insert(id, item); + assert!(old_item.is_none(), "Inserted type twice?"); + + // Unnamed items can have an USR, but they can't be referenced from + // other sites explicitly and the USR can match if the unnamed items are + // nested, so don't bother tracking them. + if is_type && declaration.is_some() { + let mut declaration = declaration.unwrap(); + if !declaration.is_valid() { + if let Some(location) = location { + if location.is_template_like() { + declaration = location; + } + } + } + declaration = declaration.canonical(); + if !declaration.is_valid() { + // This could happen, for example, with types like `int*` or + // similar. + // + // Fortunately, we don't care about those types being + // duplicated, so we can just ignore them. + debug!("Invalid declaration {:?} found for type {:?}", + declaration, + self.items.get(&id).unwrap().kind().expect_type()); + return; + } + + let key = if is_unnamed { + TypeKey::Declaration(declaration) + } else if let Some(usr) = declaration.usr() { + TypeKey::USR(usr) + } else { + warn!("Valid declaration with no USR: {:?}, {:?}", + declaration, + location); + TypeKey::Declaration(declaration) + }; + + let old = self.types.insert(key, id); + debug_assert_eq!(old, None); + } + } + + // TODO: Move all this syntax crap to other part of the code. + + /// Given that we are in the codegen phase, get the syntex context. + pub fn ext_cx(&self) -> &ExtCtxt<'ctx> { + &self.gen_ctx.expect("Not in gen phase").0 + } + + /// Given that we are in the codegen phase, get the current syntex span. + pub fn span(&self) -> Span { + self.span + } + + /// Mangles a name so it doesn't conflict with any keyword. + pub fn rust_mangle<'a>(&self, name: &'a str) -> Cow<'a, str> { + use syntax::parse::token; + let ident = self.rust_ident_raw(name); + let token = token::Ident(ident); + if token.is_any_keyword() || name.contains("@") || + name.contains("?") || name.contains("$") || + "bool" == name { + let mut s = name.to_owned(); + s = s.replace("@", "_"); + s = s.replace("?", "_"); + s = s.replace("$", "_"); + s.push_str("_"); + return Cow::Owned(s); + } + Cow::Borrowed(name) + } + + /// Returns a mangled name as a rust identifier. + pub fn rust_ident(&self, name: &str) -> Ident { + self.rust_ident_raw(&self.rust_mangle(name)) + } + + /// Returns a mangled name as a rust identifier. + pub fn rust_ident_raw(&self, name: &str) -> Ident { + self.ext_cx().ident_of(name) + } + + /// Iterate over all items that have been defined. + pub fn items<'a>(&'a self) -> btree_map::Iter<'a, ItemId, Item> { + self.items.iter() + } + + /// Have we collected all unresolved type references yet? + pub fn collected_typerefs(&self) -> bool { + self.collected_typerefs + } + + /// Gather all the unresolved type references. + fn collect_typerefs + (&mut self) + -> Vec<(ItemId, clang::Type, Option, Option)> { + debug_assert!(!self.collected_typerefs); + self.collected_typerefs = true; + let mut typerefs = vec![]; + for (id, ref mut item) in &mut self.items { + let kind = item.kind(); + let ty = match kind.as_type() { + Some(ty) => ty, + None => continue, + }; + + match *ty.kind() { + TypeKind::UnresolvedTypeRef(ref ty, loc, parent_id) => { + typerefs.push((*id, ty.clone(), loc, parent_id)); + } + _ => {} + }; + } + typerefs + } + + /// Collect all of our unresolved type references and resolve them. + fn resolve_typerefs(&mut self) { + let typerefs = self.collect_typerefs(); + + for (id, ty, loc, parent_id) in typerefs { + let _resolved = { + let resolved = Item::from_ty(&ty, loc, parent_id, self) + .expect("What happened?"); + let mut item = self.items.get_mut(&id).unwrap(); + + *item.kind_mut().as_type_mut().unwrap().kind_mut() = + TypeKind::ResolvedTypeRef(resolved); + resolved + }; + + // Something in the STL is trolling me. I don't need this assertion + // right now, but worth investigating properly once this lands. + // + // debug_assert!(self.items.get(&resolved).is_some(), "How?"); + } + } + + /// Iterate over all items and replace any item that has been named in a + /// `replaces="SomeType"` annotation with the replacement type. + fn process_replacements(&mut self) { + if self.replacements.is_empty() { + debug!("No replacements to process"); + return; + } + + // FIXME: This is linear, but the replaces="xxx" annotation was already + // there, and for better or worse it's useful, sigh... + // + // We leverage the ResolvedTypeRef thing, though, which is cool :P. + + let mut replacements = vec![]; + + for (id, item) in self.items.iter() { + if item.annotations().use_instead_of().is_some() { + continue; + } + + // Calls to `canonical_name` are expensive, so eagerly filter out + // items that cannot be replaced. + let ty = match item.kind().as_type() { + Some(ty) => ty, + None => continue, + }; + + match *ty.kind() { + TypeKind::Comp(ref ci) if !ci.is_template_specialization() => {} + TypeKind::TemplateAlias(..) | + TypeKind::Alias(..) => {} + _ => continue, + } + + let path = item.canonical_path(self); + let replacement = self.replacements.get(&path[1..]); + + if let Some(replacement) = replacement { + if replacement != id { + // We set this just after parsing the annotation. It's + // very unlikely, but this can happen. + if self.items.get(replacement).is_some() { + replacements.push((*id, *replacement)); + } + } + } + } + + for (id, replacement) in replacements { + debug!("Replacing {:?} with {:?}", id, replacement); + + let new_parent = { + let mut item = self.items.get_mut(&id).unwrap(); + *item.kind_mut().as_type_mut().unwrap().kind_mut() = + TypeKind::ResolvedTypeRef(replacement); + item.parent_id() + }; + + + // Reparent the item. + let old_parent = self.resolve_item(replacement).parent_id(); + + if new_parent == old_parent { + continue; + } + + if let Some(mut module) = self.items + .get_mut(&old_parent) + .unwrap() + .as_module_mut() { + // Deparent the replacement. + let position = module.children() + .iter() + .position(|id| *id == replacement) + .unwrap(); + module.children_mut().remove(position); + } + + if let Some(mut module) = self.items + .get_mut(&new_parent) + .unwrap() + .as_module_mut() { + module.children_mut().push(replacement); + } + + self.items + .get_mut(&replacement) + .unwrap() + .set_parent_for_replacement(new_parent); + self.items + .get_mut(&id) + .unwrap() + .set_parent_for_replacement(old_parent); + } + } + + /// Enter the code generation phase, invoke the given callback `cb`, and + /// leave the code generation phase. + pub fn gen(&mut self, cb: F) -> Out + where F: FnOnce(&Self) -> Out, + { + use aster::symbol::ToSymbol; + use syntax::ext::expand::ExpansionConfig; + use syntax::codemap::{ExpnInfo, MacroBang, NameAndSpan}; + use syntax::ext::base; + use syntax::parse; + use std::mem; + + let cfg = ExpansionConfig::default("xxx".to_owned()); + let sess = parse::ParseSess::new(); + let mut loader = base::DummyResolver; + let mut ctx = GenContext(base::ExtCtxt::new(&sess, cfg, &mut loader)); + + ctx.0.bt_push(ExpnInfo { + call_site: self.span, + callee: NameAndSpan { + format: MacroBang("".to_symbol()), + allow_internal_unstable: false, + span: None, + }, + }); + + // FIXME: This is evil, we should move code generation to use a wrapper + // of BindgenContext instead, I guess. Even though we know it's fine + // because we remove it before the end of this function. + self.gen_ctx = Some(unsafe { mem::transmute(&ctx) }); + + self.assert_no_dangling_references(); + + if !self.collected_typerefs() { + self.resolve_typerefs(); + self.process_replacements(); + } + + let ret = cb(self); + self.gen_ctx = None; + ret + } + + /// This function trying to find any dangling references inside of `items` + fn assert_no_dangling_references(&self) { + if cfg!(feature = "assert_no_dangling_items") { + for _ in self.assert_no_dangling_item_traversal() { + // The iterator's next method does the asserting for us. + } + } + } + + fn assert_no_dangling_item_traversal<'me> + (&'me self) + -> AssertNoDanglingItemIter<'me, 'ctx> { + assert!(self.in_codegen_phase()); + assert!(self.current_module == self.root_module); + + let mut roots = self.items().map(|(&id, _)| id); + + let mut seen = BTreeMap::::new(); + let next_child = roots.next().map(|id| id).unwrap(); + seen.insert(next_child, next_child); + + let to_iterate = seen.iter().map(|(&id, _)| id).rev().collect(); + + AssertNoDanglingItemIter { + ctx: self, + seen: seen, + to_iterate: to_iterate, + } + } + + // This deserves a comment. Builtin types don't get a valid declaration, so + // we can't add it to the cursor->type map. + // + // That being said, they're not generated anyway, and are few, so the + // duplication and special-casing is fine. + // + // If at some point we care about the memory here, probably a map TypeKind + // -> builtin type ItemId would be the best to improve that. + fn add_builtin_item(&mut self, item: Item) { + debug!("add_builtin_item: item = {:?}", item); + debug_assert!(item.kind().is_type()); + let id = item.id(); + let old_item = self.items.insert(id, item); + assert!(old_item.is_none(), "Inserted type twice?"); + } + + fn build_root_module(id: ItemId) -> Item { + let module = Module::new(Some("root".into()), ModuleKind::Normal); + Item::new(id, None, None, id, ItemKind::Module(module)) + } + + /// Get the root module. + pub fn root_module(&self) -> ItemId { + self.root_module + } + + /// Resolve the given `ItemId` as a type. + /// + /// Panics if there is no item for the given `ItemId` or if the resolved + /// item is not a `Type`. + pub fn resolve_type(&self, type_id: ItemId) -> &Type { + self.items.get(&type_id).unwrap().kind().expect_type() + } + + /// Resolve the given `ItemId` as a type, or `None` if there is no item with + /// the given id. + /// + /// Panics if the id resolves to an item that is not a type. + pub fn safe_resolve_type(&self, type_id: ItemId) -> Option<&Type> { + self.items.get(&type_id).map(|t| t.kind().expect_type()) + } + + /// Resolve the given `ItemId` into an `Item`, or `None` if no such item + /// exists. + pub fn resolve_item_fallible(&self, item_id: ItemId) -> Option<&Item> { + self.items.get(&item_id) + } + + /// Resolve the given `ItemId` into an `Item`. + /// + /// Panics if the given id does not resolve to any item. + pub fn resolve_item(&self, item_id: ItemId) -> &Item { + match self.items.get(&item_id) { + Some(item) => item, + None => panic!("Not an item: {:?}", item_id), + } + } + + /// Get the current module. + pub fn current_module(&self) -> ItemId { + self.current_module + } + + /// This is one of the hackiest methods in all the parsing code. This method + /// is used to allow having templates with another argument names instead of + /// the canonical ones. + /// + /// This is surprisingly difficult to do with libclang, due to the fact that + /// partial template specializations don't provide explicit template + /// argument information. + /// + /// The only way to do this as far as I know, is inspecting manually the + /// AST, looking for TypeRefs inside. This, unfortunately, doesn't work for + /// more complex cases, see the comment on the assertion below. + /// + /// To see an example of what this handles: + /// + /// ```c++ + /// template + /// class Incomplete { + /// T p; + /// }; + /// + /// template + /// class Foo { + /// Incomplete bar; + /// }; + /// ``` + fn build_template_wrapper(&mut self, + with_id: ItemId, + wrapping: ItemId, + parent_id: ItemId, + ty: &clang::Type, + location: clang::Cursor, + declaration: clang::Cursor) + -> ItemId { + use clang_sys::*; + let mut args = vec![]; + location.visit(|c| { + if c.kind() == CXCursor_TypeRef { + // The `with_id` id will potentially end up unused if we give up + // on this type (for example, its a tricky partial template + // specialization), so if we pass `with_id` as the parent, it is + // potentially a dangling reference. Instead, use the canonical + // template declaration as the parent. It is already parsed and + // has a known-resolvable `ItemId`. + let new_ty = Item::from_ty_or_ref(c.cur_type(), + Some(c), + Some(wrapping), + self); + args.push(new_ty); + } + CXChildVisit_Continue + }); + + let item = { + let wrapping_type = self.resolve_type(wrapping); + if let TypeKind::Comp(ref ci) = *wrapping_type.kind() { + let old_args = ci.template_args(); + + // The following assertion actually fails with partial template + // specialization. But as far as I know there's no way at all to + // grab the specialized types from neither the AST or libclang, + // which sucks. The same happens for specialized type alias + // template declarations, where we have that ugly hack up there. + // + // This flaw was already on the old parser, but I now think it + // has no clear solution (apart from patching libclang to + // somehow expose them, of course). + // + // For an easy example in which there's no way at all of getting + // the `int` type, except manually parsing the spelling: + // + // template + // class Incomplete { + // T d; + // U p; + // }; + // + // template + // class Foo { + // Incomplete bar; + // }; + // + // debug_assert_eq!(old_args.len(), args.len()); + // + // That being said, this is not so common, so just error! and + // hope for the best, returning the previous type, who knows. + if old_args.len() != args.len() { + error!("Found partial template specialization, \ + expect dragons!"); + return wrapping; + } + } else { + assert_eq!(declaration.kind(), + ::clang_sys::CXCursor_TypeAliasTemplateDecl, + "Expected wrappable type"); + } + + let type_kind = TypeKind::TemplateRef(wrapping, args); + let name = ty.spelling(); + let name = if name.is_empty() { None } else { Some(name) }; + let ty = Type::new(name, + ty.fallible_layout().ok(), + type_kind, + ty.is_const()); + Item::new(with_id, None, None, parent_id, ItemKind::Type(ty)) + }; + + // Bypass all the validations in add_item explicitly. + debug!("build_template_wrapper: inserting item: {:?}", item); + debug_assert!(with_id == item.id()); + self.items.insert(with_id, item); + with_id + } + + /// Looks up for an already resolved type, either because it's builtin, or + /// because we already have it in the map. + pub fn builtin_or_resolved_ty(&mut self, + with_id: ItemId, + parent_id: Option, + ty: &clang::Type, + location: Option) + -> Option { + use clang_sys::{CXCursor_TypeAliasTemplateDecl, CXCursor_TypeRef}; + debug!("builtin_or_resolved_ty: {:?}, {:?}, {:?}", + ty, + location, + parent_id); + let mut declaration = ty.declaration(); + if !declaration.is_valid() { + if let Some(location) = location { + if location.is_template_like() { + declaration = location; + } + } + } + let canonical_declaration = declaration.canonical(); + if canonical_declaration.is_valid() { + let id = self.types + .get(&TypeKey::Declaration(canonical_declaration)) + .map(|id| *id) + .or_else(|| { + canonical_declaration.usr() + .and_then(|usr| self.types.get(&TypeKey::USR(usr))) + .map(|id| *id) + }); + if let Some(id) = id { + debug!("Already resolved ty {:?}, {:?}, {:?} {:?}", + id, + declaration, + ty, + location); + + // If the declaration existed, we *might* be done, but it's not + // the case for class templates, where the template arguments + // may vary. + // + // In this case, we create a TemplateRef with the new template + // arguments, pointing to the canonical template. + // + // Note that we only do it if parent_id is some, and we have a + // location for building the new arguments, the template + // argument names don't matter in the global context. + if declaration.is_template_like() && + *ty != canonical_declaration.cur_type() && + location.is_some() && + parent_id.is_some() { + // For specialized type aliases, there's no way to get the + // template parameters as of this writing (for a struct + // specialization we wouldn't be in this branch anyway). + // + // Explicitly return `None` if there aren't any + // unspecialized parameters (contains any `TypeRef`) so we + // resolve the canonical type if there is one and it's + // exposed. + // + // This is _tricky_, I know :( + if declaration.kind() == CXCursor_TypeAliasTemplateDecl && + !location.unwrap().contains_cursor(CXCursor_TypeRef) && + ty.canonical_type().is_valid_and_exposed() { + return None; + } + + return Some(self.build_template_wrapper(with_id, + id, + parent_id.unwrap(), + ty, + location.unwrap(), + declaration)); + } + + return Some(self.build_ty_wrapper(with_id, id, parent_id, ty)); + } + } + + debug!("Not resolved, maybe builtin?"); + + // Else, build it. + self.build_builtin_ty(ty, declaration) + } + + // This is unfortunately a lot of bloat, but is needed to properly track + // constness et. al. + // + // We should probably make the constness tracking separate, so it doesn't + // bloat that much, but hey, we already bloat the heck out of builtin types. + fn build_ty_wrapper(&mut self, + with_id: ItemId, + wrapped_id: ItemId, + parent_id: Option, + ty: &clang::Type) + -> ItemId { + let spelling = ty.spelling(); + let is_const = ty.is_const(); + let layout = ty.fallible_layout().ok(); + let type_kind = TypeKind::ResolvedTypeRef(wrapped_id); + let ty = Type::new(Some(spelling), layout, type_kind, is_const); + let item = Item::new(with_id, + None, + None, + parent_id.unwrap_or(self.current_module), + ItemKind::Type(ty)); + self.add_builtin_item(item); + with_id + } + + /// Returns the next item id to be used for an item. + pub fn next_item_id(&mut self) -> ItemId { + let ret = self.next_item_id; + self.next_item_id = ItemId(self.next_item_id.0 + 1); + ret + } + + fn build_builtin_ty(&mut self, + ty: &clang::Type, + _declaration: Cursor) + -> Option { + use clang_sys::*; + let type_kind = match ty.kind() { + CXType_NullPtr => TypeKind::NullPtr, + CXType_Void => TypeKind::Void, + CXType_Bool => TypeKind::Int(IntKind::Bool), + CXType_Int => TypeKind::Int(IntKind::Int), + CXType_UInt => TypeKind::Int(IntKind::UInt), + CXType_SChar | CXType_Char_S => TypeKind::Int(IntKind::Char), + CXType_UChar | CXType_Char_U => TypeKind::Int(IntKind::UChar), + CXType_Short => TypeKind::Int(IntKind::Short), + CXType_UShort => TypeKind::Int(IntKind::UShort), + CXType_WChar | CXType_Char16 => TypeKind::Int(IntKind::U16), + CXType_Char32 => TypeKind::Int(IntKind::U32), + CXType_Long => TypeKind::Int(IntKind::Long), + CXType_ULong => TypeKind::Int(IntKind::ULong), + CXType_LongLong => TypeKind::Int(IntKind::LongLong), + CXType_ULongLong => TypeKind::Int(IntKind::ULongLong), + CXType_Int128 => TypeKind::Int(IntKind::I128), + CXType_UInt128 => TypeKind::Int(IntKind::U128), + CXType_Float => TypeKind::Float(FloatKind::Float), + CXType_Double => TypeKind::Float(FloatKind::Double), + CXType_LongDouble => TypeKind::Float(FloatKind::LongDouble), + CXType_Float128 => TypeKind::Float(FloatKind::Float128), + CXType_Complex => { + let float_type = ty.elem_type() + .expect("Not able to resolve complex type?"); + let float_kind = match float_type.kind() { + CXType_Float => FloatKind::Float, + CXType_Double => FloatKind::Double, + CXType_LongDouble => FloatKind::LongDouble, + _ => panic!("Non floating-type complex?"), + }; + TypeKind::Complex(float_kind) + } + _ => return None, + }; + + let spelling = ty.spelling(); + let is_const = ty.is_const(); + let layout = ty.fallible_layout().ok(); + let ty = Type::new(Some(spelling), layout, type_kind, is_const); + let id = self.next_item_id(); + let item = + Item::new(id, None, None, self.root_module, ItemKind::Type(ty)); + self.add_builtin_item(item); + Some(id) + } + + /// Get the current Clang translation unit that is being processed. + pub fn translation_unit(&self) -> &clang::TranslationUnit { + &self.translation_unit + } + + /// Have we parsed the macro named `macro_name` already? + pub fn parsed_macro(&self, macro_name: &[u8]) -> bool { + self.parsed_macros.contains_key(macro_name) + } + + /// Get the currently parsed macros. + pub fn parsed_macros(&self) -> &HashMap, cexpr::expr::EvalResult> { + debug_assert!(!self.in_codegen_phase()); + &self.parsed_macros + } + + /// Mark the macro named `macro_name` as parsed. + pub fn note_parsed_macro(&mut self, + id: Vec, + value: cexpr::expr::EvalResult) { + self.parsed_macros.insert(id, value); + } + + /// Are we in the codegen phase? + pub fn in_codegen_phase(&self) -> bool { + self.gen_ctx.is_some() + } + + /// Mark the type with the given `name` as replaced by the type with id + /// `potential_ty`. + /// + /// Replacement types are declared using the `replaces="xxx"` annotation, + /// and implies that the original type is hidden. + pub fn replace(&mut self, name: &[String], potential_ty: ItemId) { + match self.replacements.entry(name.into()) { + hash_map::Entry::Vacant(entry) => { + debug!("Defining replacement for {:?} as {:?}", + name, + potential_ty); + entry.insert(potential_ty); + } + hash_map::Entry::Occupied(occupied) => { + warn!("Replacement for {:?} already defined as {:?}; \ + ignoring duplicate replacement definition as {:?}", + name, + occupied.get(), + potential_ty); + } + } + } + + /// Is the item with the given `name` hidden? Or is the item with the given + /// `name` and `id` replaced by another type, and effectively hidden? + pub fn hidden_by_name(&self, path: &[String], id: ItemId) -> bool { + debug_assert!(self.in_codegen_phase(), + "You're not supposed to call this yet"); + self.options.hidden_types.matches(&path[1..].join("::")) || + self.is_replaced_type(path, id) + } + + /// Has the item with the given `name` and `id` been replaced by another + /// type? + pub fn is_replaced_type(&self, path: &[String], id: ItemId) -> bool { + match self.replacements.get(path) { + Some(replaced_by) if *replaced_by != id => true, + _ => false, + } + } + + /// Is the type with the given `name` marked as opaque? + pub fn opaque_by_name(&self, path: &[String]) -> bool { + debug_assert!(self.in_codegen_phase(), + "You're not supposed to call this yet"); + self.options.opaque_types.matches(&path[1..].join("::")) + } + + /// Get the options used to configure this bindgen context. + pub fn options(&self) -> &BindgenOptions { + &self.options + } + + /// Tokenizes a namespace cursor in order to get the name and kind of the + /// namespace, + fn tokenize_namespace(&self, + cursor: &clang::Cursor) + -> (Option, ModuleKind) { + assert_eq!(cursor.kind(), ::clang_sys::CXCursor_Namespace, + "Be a nice person"); + let tokens = match self.translation_unit.tokens(&cursor) { + Some(tokens) => tokens, + None => return (None, ModuleKind::Normal), + }; + + let mut iter = tokens.iter(); + let mut kind = ModuleKind::Normal; + let mut found_namespace_keyword = false; + let mut module_name = None; + while let Some(token) = iter.next() { + match &*token.spelling { + "inline" => { + assert!(!found_namespace_keyword); + assert!(kind != ModuleKind::Inline); + kind = ModuleKind::Inline; + } + "namespace" => { + found_namespace_keyword = true; + } + "{" => { + assert!(found_namespace_keyword); + break; + } + name if found_namespace_keyword => { + module_name = Some(name.to_owned()); + break; + } + _ => { + panic!("Unknown token while processing namespace: {:?}", + token); + } + } + }; + + (module_name, kind) + } + + /// Given a CXCursor_Namespace cursor, return the item id of the + /// corresponding module, or create one on the fly. + pub fn module(&mut self, cursor: clang::Cursor) -> ItemId { + use clang_sys::*; + assert_eq!(cursor.kind(), CXCursor_Namespace, "Be a nice person"); + let cursor = cursor.canonical(); + if let Some(id) = self.modules.get(&cursor) { + return *id; + } + + let (module_name, kind) = self.tokenize_namespace(&cursor); + + let module_id = self.next_item_id(); + let module = Module::new(module_name, kind); + let module = Item::new(module_id, + None, + None, + self.current_module, + ItemKind::Module(module)); + + self.modules.insert(cursor, module.id()); + + self.add_item(module, None, None); + + module_id + } + + /// Start traversing the module with the given `module_id`, invoke the + /// callback `cb`, and then return to traversing the original module. + pub fn with_module(&mut self, module_id: ItemId, cb: F) + where F: FnOnce(&mut Self), + { + debug_assert!(self.resolve_item(module_id).kind().is_module(), "Wat"); + + let previous_id = self.current_module; + self.current_module = module_id; + + cb(self); + + self.current_module = previous_id; + } + + /// Iterate over all (explicitly or transitively) whitelisted items. + /// + /// If no items are explicitly whitelisted, then all items are considered + /// whitelisted. + pub fn whitelisted_items<'me>(&'me self) + -> WhitelistedItemsIter<'me, 'ctx> { + assert!(self.in_codegen_phase()); + assert!(self.current_module == self.root_module); + + let roots = self.items() + .filter(|&(_, item)| { + // If nothing is explicitly whitelisted, then everything is fair + // game. + if self.options().whitelisted_types.is_empty() && + self.options().whitelisted_functions.is_empty() && + self.options().whitelisted_vars.is_empty() { + return true; + } + + // If this is a type that explicitly replaces another, we assume + // you know what you're doing. + if item.annotations().use_instead_of().is_some() { + return true; + } + + let name = item.canonical_path(self)[1..].join("::"); + debug!("whitelisted_items: testing {:?}", name); + match *item.kind() { + ItemKind::Module(..) => true, + ItemKind::Function(_) => { + self.options().whitelisted_functions.matches(&name) + } + ItemKind::Var(_) => { + self.options().whitelisted_vars.matches(&name) + } + ItemKind::Type(ref ty) => { + if self.options().whitelisted_types.matches(&name) { + return true; + } + + let parent = self.resolve_item(item.parent_id()); + if parent.is_module() { + let mut prefix_path = parent.canonical_path(self); + + // Unnamed top-level enums are special and we + // whitelist them via the `whitelisted_vars` filter, + // since they're effectively top-level constants, + // and there's no way for them to be referenced + // consistently. + if let TypeKind::Enum(ref enum_) = *ty.kind() { + if ty.name().is_none() && + enum_.variants().iter().any(|variant| { + prefix_path.push(variant.name().into()); + let name = prefix_path[1..].join("::"); + prefix_path.pop().unwrap(); + self.options() + .whitelisted_vars + .matches(&name) + }) { + return true; + } + } + } + + false + } + } + }) + .map(|(&id, _)| id); + + let seen: ItemSet = roots.collect(); + + // The .rev() preserves the expected ordering traversal, resulting in + // more stable-ish bindgen-generated names for anonymous types (like + // unions). + let to_iterate = seen.iter().cloned().rev().collect(); + + WhitelistedItemsIter { + ctx: self, + seen: seen, + to_iterate: to_iterate, + } + } + + /// Convenient method for getting the prefix to use for most traits in + /// codegen depending on the `use_core` option. + pub fn trait_prefix(&self) -> Ident { + if self.options().use_core { + self.rust_ident_raw("core") + } else { + self.rust_ident_raw("std") + } + } + + /// Call if a binden complex is generated + pub fn generated_bindegen_complex(&self) { + self.generated_bindegen_complex.set(true) + } + + /// Whether we need to generate the binden complex type + pub fn need_bindegen_complex_type(&self) -> bool { + self.generated_bindegen_complex.get() + } +} + +/// An iterator over whitelisted items. +/// +/// See `BindgenContext::whitelisted_items` for more information. +pub struct WhitelistedItemsIter<'ctx, 'gen> + where 'gen: 'ctx, +{ + ctx: &'ctx BindgenContext<'gen>, + + /// The set of whitelisted items we have seen. If you think of traversing + /// whitelisted items like GC tracing, this is the mark bits, and contains + /// both black and gray items. + seen: ItemSet, + + /// The set of whitelisted items that we have seen but have yet to iterate + /// over and collect transitive references from. To return to the GC analogy, + /// this is the mark stack, containing the set of gray items which we have + /// not finished tracing yet. + to_iterate: Vec, +} + +impl<'ctx, 'gen> Iterator for WhitelistedItemsIter<'ctx, 'gen> + where 'gen: 'ctx, +{ + type Item = ItemId; + + fn next(&mut self) -> Option { + let id = match self.to_iterate.pop() { + None => return None, + Some(id) => id, + }; + + debug_assert!(self.seen.contains(&id)); + debug_assert!(self.ctx.items.contains_key(&id)); + + if self.ctx.options().whitelist_recursively { + let mut sub_types = ItemSet::new(); + id.collect_types(self.ctx, &mut sub_types, &()); + + for id in sub_types { + if self.seen.insert(id) { + self.to_iterate.push(id); + } + } + } + + Some(id) + } +} + +/// An iterator to find any dangling items. +/// +/// See `BindgenContext::assert_no_dangling_item_traversal` for more +/// information. +pub struct AssertNoDanglingItemIter<'ctx, 'gen> + where 'gen: 'ctx, +{ + ctx: &'ctx BindgenContext<'gen>, + seen: BTreeMap, + to_iterate: VecDeque, +} + +impl<'ctx, 'gen> Iterator for AssertNoDanglingItemIter<'ctx, 'gen> + where 'gen: 'ctx, +{ + type Item = ItemId; + + fn next(&mut self) -> Option { + let id = match self.to_iterate.pop_front() { + None => { + // We've traversed everything reachable from the previous + // root(s), see if we have any more roots. + match self.ctx + .items() + .filter(|&(id, _)| !self.seen.contains_key(id)) + .next() + .map(|(id, _)| *id) { + None => return None, + Some(id) => { + // This is a new root. + self.seen.insert(id, id); + id + } + } + } + Some(id) => id, + }; + + let mut sub_types = ItemSet::new(); + id.collect_types(self.ctx, &mut sub_types, &()); + + if self.ctx.resolve_item_fallible(id).is_none() { + let mut path = vec![]; + let mut current = id; + loop { + let predecessor = *self.seen + .get(¤t) + .expect("We know we found this item id, so it must have a \ + predecessor"); + if predecessor == current { + break; + } + path.push(predecessor); + current = predecessor; + } + path.reverse(); + panic!("Found reference to dangling id = {:?}\nvia path = {:?}", + id, + path); + } + + for sub_id in sub_types { + if self.seen.insert(sub_id, id).is_none() { + // We've never visited this sub item before. + self.to_iterate.push_back(sub_id); + } + } + + Some(id) + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/derive.rs b/bash-5.1/vendor/bindgen/src/ir/derive.rs new file mode 100644 index 0000000..d13a811 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/derive.rs @@ -0,0 +1,67 @@ +//! Traits for determining whether we can derive traits for a thing or not. + +use super::context::BindgenContext; + +/// A trait that encapsulates the logic for whether or not we can derive `Debug` +/// for a given thing. +/// +/// This should ideally be a no-op that just returns `true`, but instead needs +/// to be a recursive method that checks whether all the proper members can +/// derive debug or not, because of the limit rust has on 32 items as max in the +/// array. +pub trait CanDeriveDebug { + /// Implementations can define this type to get access to any extra + /// information required to determine whether they can derive `Debug`. If + /// extra information is unneeded, then this should simply be the unit type. + type Extra; + + /// Return `true` if `Debug` can be derived for this thing, `false` + /// otherwise. + fn can_derive_debug(&self, + ctx: &BindgenContext, + extra: Self::Extra) + -> bool; +} + +/// A trait that encapsulates the logic for whether or not we can derive `Copy` +/// for a given thing. +pub trait CanDeriveCopy<'a> { + /// Implementations can define this type to get access to any extra + /// information required to determine whether they can derive `Copy`. If + /// extra information is unneeded, then this should simply be the unit type. + type Extra; + + /// Return `true` if `Copy` can be derived for this thing, `false` + /// otherwise. + fn can_derive_copy(&'a self, + ctx: &'a BindgenContext, + extra: Self::Extra) + -> bool; + + /// For some reason, deriving copies of an array of a type that is not known + /// to be `Copy` is a compile error. e.g.: + /// + /// ```rust + /// #[derive(Copy, Clone)] + /// struct A { + /// member: T, + /// } + /// ``` + /// + /// is fine, while: + /// + /// ```rust,ignore + /// #[derive(Copy, Clone)] + /// struct A { + /// member: [T; 1], + /// } + /// ``` + /// + /// is an error. + /// + /// That's the whole point of the existence of `can_derive_copy_in_array`. + fn can_derive_copy_in_array(&'a self, + ctx: &'a BindgenContext, + extra: Self::Extra) + -> bool; +} diff --git a/bash-5.1/vendor/bindgen/src/ir/enum_ty.rs b/bash-5.1/vendor/bindgen/src/ir/enum_ty.rs new file mode 100644 index 0000000..ca4e77d --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/enum_ty.rs @@ -0,0 +1,183 @@ +//! Intermediate representation for C/C++ enumerations. + +use clang; +use ir::annotations::Annotations; +use parse::{ClangItemParser, ParseError}; +use super::context::{BindgenContext, ItemId}; +use super::item::Item; +use super::ty::TypeKind; + +/// An enum representing custom handling that can be given to a variant. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum EnumVariantCustomBehavior { + /// This variant will be constified, that is, forced to generate a constant. + Constify, + /// This variant will be hidden entirely from the resulting enum. + Hide, +} + +/// A C/C++ enumeration. +#[derive(Debug)] +pub struct Enum { + /// The representation used for this enum; it should be an `IntKind` type or + /// an alias to one. + /// + /// It's `None` if the enum is a forward declaration and isn't defined + /// anywhere else, see `tests/headers/func_ptr_in_struct.h`. + repr: Option, + + /// The different variants, with explicit values. + variants: Vec, +} + +impl Enum { + /// Construct a new `Enum` with the given representation and variants. + pub fn new(repr: Option, variants: Vec) -> Self { + Enum { + repr: repr, + variants: variants, + } + } + + /// Get this enumeration's representation. + pub fn repr(&self) -> Option { + self.repr + } + + /// Get this enumeration's variants. + pub fn variants(&self) -> &[EnumVariant] { + &self.variants + } + + /// Construct an enumeration from the given Clang type. + pub fn from_ty(ty: &clang::Type, + ctx: &mut BindgenContext) + -> Result { + use clang_sys::*; + if ty.kind() != CXType_Enum { + return Err(ParseError::Continue); + } + + let declaration = ty.declaration().canonical(); + let repr = declaration.enum_type() + .and_then(|et| Item::from_ty(&et, None, None, ctx).ok()); + let mut variants = vec![]; + + // Assume signedness since the default type by the C standard is an int. + let is_signed = + repr.and_then(|r| ctx.resolve_type(r).safe_canonical_type(ctx)) + .map_or(true, |ty| { + match *ty.kind() { + TypeKind::Int(ref int_kind) => int_kind.is_signed(), + ref other => { + panic!("Since when enums can be non-integers? {:?}", + other) + } + } + }); + + let type_name = ty.spelling(); + let type_name = if type_name.is_empty() { None } else { Some(type_name) }; + let type_name = type_name.as_ref().map(String::as_str); + + declaration.visit(|cursor| { + if cursor.kind() == CXCursor_EnumConstantDecl { + let value = if is_signed { + cursor.enum_val_signed().map(EnumVariantValue::Signed) + } else { + cursor.enum_val_unsigned().map(EnumVariantValue::Unsigned) + }; + if let Some(val) = value { + let name = cursor.spelling(); + let custom_behavior = ctx.type_chooser() + .and_then(|t| { + t.enum_variant_behavior(type_name, &name, val) + }) + .or_else(|| { + Annotations::new(&cursor).and_then(|anno| { + if anno.hide() { + Some(EnumVariantCustomBehavior::Hide) + } else if anno.constify_enum_variant() { + Some(EnumVariantCustomBehavior::Constify) + } else { + None + } + }) + }); + + let comment = cursor.raw_comment(); + variants.push( + EnumVariant::new(name, comment, val, custom_behavior)); + } + } + CXChildVisit_Continue + }); + Ok(Enum::new(repr, variants)) + } +} + +/// A single enum variant, to be contained only in an enum. +#[derive(Debug)] +pub struct EnumVariant { + /// The name of the variant. + name: String, + + /// An optional doc comment. + comment: Option, + + /// The integer value of the variant. + val: EnumVariantValue, + + /// The custom behavior this variant may have, if any. + custom_behavior: Option, +} + +/// A constant value assigned to an enumeration variant. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum EnumVariantValue { + /// A signed constant. + Signed(i64), + + /// An unsigned constant. + Unsigned(u64), +} + +impl EnumVariant { + /// Construct a new enumeration variant from the given parts. + pub fn new(name: String, + comment: Option, + val: EnumVariantValue, + custom_behavior: Option) + -> Self { + EnumVariant { + name: name, + comment: comment, + val: val, + custom_behavior: custom_behavior, + } + } + + /// Get this variant's name. + pub fn name(&self) -> &str { + &self.name + } + + /// Get this variant's value. + pub fn val(&self) -> EnumVariantValue { + self.val + } + + /// Returns whether this variant should be enforced to be a constant by code + /// generation. + pub fn force_constification(&self) -> bool { + self.custom_behavior + .map_or(false, |b| b == EnumVariantCustomBehavior::Constify) + } + + /// Returns whether the current variant should be hidden completely from the + /// resulting rust enum. + pub fn hidden(&self) -> bool { + self.custom_behavior + .map_or(false, |b| b == EnumVariantCustomBehavior::Hide) + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/function.rs b/bash-5.1/vendor/bindgen/src/ir/function.rs new file mode 100644 index 0000000..6e205f1 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/function.rs @@ -0,0 +1,316 @@ +//! Intermediate representation for C/C++ functions and methods. + +use clang; +use clang_sys::CXCallingConv; +use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; +use super::context::{BindgenContext, ItemId}; +use super::item::Item; +use super::ty::TypeKind; +use super::type_collector::{ItemSet, TypeCollector}; +use syntax::abi; + +/// A function declaration, with a signature, arguments, and argument names. +/// +/// The argument names vector must be the same length as the ones in the +/// signature. +#[derive(Debug)] +pub struct Function { + /// The name of this function. + name: String, + + /// The mangled name, that is, the symbol. + mangled_name: Option, + + /// The id pointing to the current function signature. + signature: ItemId, + + /// The doc comment on the function, if any. + comment: Option, +} + +impl Function { + /// Construct a new function. + pub fn new(name: String, + mangled_name: Option, + sig: ItemId, + comment: Option) + -> Self { + Function { + name: name, + mangled_name: mangled_name, + signature: sig, + comment: comment, + } + } + + /// Get this function's name. + pub fn name(&self) -> &str { + &self.name + } + + /// Get this function's name. + pub fn mangled_name(&self) -> Option<&str> { + self.mangled_name.as_ref().map(|n| &**n) + } + + /// Get this function's signature. + pub fn signature(&self) -> ItemId { + self.signature + } +} + +/// A function signature. +#[derive(Debug)] +pub struct FunctionSig { + /// The return type of the function. + return_type: ItemId, + + /// The type of the arguments, optionally with the name of the argument when + /// declared. + argument_types: Vec<(Option, ItemId)>, + + /// Whether this function is variadic. + is_variadic: bool, + + /// The ABI of this function. + abi: abi::Abi, +} + +fn get_abi(cc: CXCallingConv) -> abi::Abi { + use clang_sys::*; + match cc { + CXCallingConv_Default => abi::Abi::C, + CXCallingConv_C => abi::Abi::C, + CXCallingConv_X86StdCall => abi::Abi::Stdcall, + CXCallingConv_X86FastCall => abi::Abi::Fastcall, + CXCallingConv_AAPCS => abi::Abi::Aapcs, + CXCallingConv_X86_64Win64 => abi::Abi::Win64, + other => panic!("unsupported calling convention: {:?}", other), + } +} + +/// Get the mangled name for the cursor's referent. +pub fn cursor_mangling(cursor: &clang::Cursor) -> Option { + // We early return here because libclang may crash in some case + // if we pass in a variable inside a partial specialized template. + // See servo/rust-bindgen#67. + if cursor.is_in_non_fully_specialized_template() { + return None; + } + + let mut mangling = cursor.mangling(); + if mangling.is_empty() { + return None; + } + + // Try to undo backend linkage munging (prepended _, generally) + if cfg!(target_os = "macos") { + mangling.remove(0); + } + + Some(mangling) +} + +impl FunctionSig { + /// Construct a new function signature. + pub fn new(return_type: ItemId, + arguments: Vec<(Option, ItemId)>, + is_variadic: bool, + abi: abi::Abi) + -> Self { + FunctionSig { + return_type: return_type, + argument_types: arguments, + is_variadic: is_variadic, + abi: abi, + } + } + + /// Construct a new function signature from the given Clang type. + pub fn from_ty(ty: &clang::Type, + cursor: &clang::Cursor, + ctx: &mut BindgenContext) + -> Result { + use clang_sys::*; + debug!("FunctionSig::from_ty {:?} {:?}", ty, cursor); + + // Skip function templates + if cursor.kind() == CXCursor_FunctionTemplate { + return Err(ParseError::Continue); + } + + // Don't parse operatorxx functions in C++ + let spelling = cursor.spelling(); + if spelling.starts_with("operator") { + return Err(ParseError::Continue); + } + + let cursor = if cursor.is_valid() { + *cursor + } else { + ty.declaration() + }; + + let mut args: Vec<_> = match cursor.kind() { + CXCursor_FunctionDecl | + CXCursor_Constructor | + CXCursor_CXXMethod => { + // For CXCursor_FunctionDecl, cursor.args() is the reliable way + // to get parameter names and types. + cursor.args() + .unwrap() + .iter() + .map(|arg| { + let arg_ty = arg.cur_type(); + let name = arg.spelling(); + let name = + if name.is_empty() { None } else { Some(name) }; + let ty = Item::from_ty_or_ref(arg_ty, Some(*arg), None, ctx); + (name, ty) + }) + .collect() + } + _ => { + // For non-CXCursor_FunctionDecl, visiting the cursor's children + // is the only reliable way to get parameter names. + let mut args = vec![]; + cursor.visit(|c| { + if c.kind() == CXCursor_ParmDecl { + let ty = + Item::from_ty_or_ref(c.cur_type(), Some(c), None, ctx); + let name = c.spelling(); + let name = + if name.is_empty() { None } else { Some(name) }; + args.push((name, ty)); + } + CXChildVisit_Continue + }); + args + } + }; + + let is_method = cursor.kind() == CXCursor_CXXMethod; + let is_constructor = cursor.kind() == CXCursor_Constructor; + if (is_constructor || is_method) && + cursor.lexical_parent() != cursor.semantic_parent() { + // Only parse constructors once. + return Err(ParseError::Continue); + } + + if is_method || is_constructor { + let is_const = is_method && cursor.method_is_const(); + let is_virtual = is_method && cursor.method_is_virtual(); + let is_static = is_method && cursor.method_is_static(); + if !is_static && !is_virtual { + let class = Item::parse(cursor.semantic_parent(), None, ctx) + .expect("Expected to parse the class"); + let ptr = + Item::builtin_type(TypeKind::Pointer(class), is_const, ctx); + args.insert(0, (Some("this".into()), ptr)); + } else if is_virtual { + let void = Item::builtin_type(TypeKind::Void, false, ctx); + let ptr = + Item::builtin_type(TypeKind::Pointer(void), false, ctx); + args.insert(0, (Some("this".into()), ptr)); + } + } + + let ty_ret_type = try!(ty.ret_type().ok_or(ParseError::Continue)); + let ret = Item::from_ty_or_ref(ty_ret_type, None, None, ctx); + let abi = get_abi(ty.call_conv()); + + Ok(Self::new(ret, args, ty.is_variadic(), abi)) + } + + /// Get this function signature's return type. + pub fn return_type(&self) -> ItemId { + self.return_type + } + + /// Get this function signature's argument (name, type) pairs. + pub fn argument_types(&self) -> &[(Option, ItemId)] { + &self.argument_types + } + + /// Get this function signature's ABI. + pub fn abi(&self) -> abi::Abi { + self.abi + } + + /// Is this function signature variadic? + pub fn is_variadic(&self) -> bool { + // Clang reports some functions as variadic when they *might* be + // variadic. We do the argument check because rust doesn't codegen well + // variadic functions without an initial argument. + self.is_variadic && !self.argument_types.is_empty() + } +} + +impl ClangSubItemParser for Function { + fn parse(cursor: clang::Cursor, + context: &mut BindgenContext) + -> Result, ParseError> { + use clang_sys::*; + match cursor.kind() { + // FIXME(emilio): Generate destructors properly. + CXCursor_FunctionDecl | + CXCursor_Constructor | + CXCursor_CXXMethod => {} + _ => return Err(ParseError::Continue), + }; + + debug!("Function::parse({:?}, {:?})", cursor, cursor.cur_type()); + + let visibility = cursor.visibility(); + if visibility != CXVisibility_Default { + return Err(ParseError::Continue); + } + + if cursor.access_specifier() == CX_CXXPrivate { + return Err(ParseError::Continue); + } + + if cursor.is_inlined_function() { + return Err(ParseError::Continue); + } + + let linkage = cursor.linkage(); + if linkage != CXLinkage_External && linkage != CXLinkage_UniqueExternal { + return Err(ParseError::Continue); + } + + // Grab the signature using Item::from_ty. + let sig = try!(Item::from_ty(&cursor.cur_type(), + Some(cursor), + None, + context)); + + let name = cursor.spelling(); + assert!(!name.is_empty(), "Empty function name?"); + + let mut mangled_name = cursor_mangling(&cursor); + if mangled_name.as_ref() == Some(&name) { + mangled_name = None; + } + + let comment = cursor.raw_comment(); + + let function = Self::new(name, mangled_name, sig, comment); + Ok(ParseResult::New(function, Some(cursor))) + } +} + +impl TypeCollector for FunctionSig { + type Extra = Item; + + fn collect_types(&self, + _context: &BindgenContext, + types: &mut ItemSet, + _item: &Item) { + types.insert(self.return_type()); + + for &(_, ty) in self.argument_types() { + types.insert(ty); + } + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/int.rs b/bash-5.1/vendor/bindgen/src/ir/int.rs new file mode 100644 index 0000000..89068e0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/int.rs @@ -0,0 +1,113 @@ +//! Intermediate representation for integral types. + +/// Which integral type are we dealing with? +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum IntKind { + /// A `bool`. + Bool, + + /// A `char`. + Char, + + /// An `unsigned char`. + UChar, + + /// A `short`. + Short, + + /// An `unsigned short`. + UShort, + + /// An `int`. + Int, + + /// An `unsigned int`. + UInt, + + /// A `long`. + Long, + + /// An `unsigned long`. + ULong, + + /// A `long long`. + LongLong, + + /// An `unsigned long long`. + ULongLong, + + /// A 8-bit signed integer. + I8, + + /// A 8-bit unsigned integer. + U8, + + /// A 16-bit signed integer. + I16, + + /// Either a `char16_t` or a `wchar_t`. + U16, + + /// A 32-bit signed integer. + I32, + + /// A 32-bit unsigned integer. + U32, + + /// A 64-bit signed integer. + I64, + + /// A 64-bit unsigned integer. + U64, + + /// An `int128_t` + I128, + + /// A `uint128_t`. + U128, + + /// A custom integer type, used to allow custom macro types depending on + /// range. + Custom { + /// The name of the type, which would be used without modification. + name: &'static str, + /// Whether the type is signed or not. + is_signed: bool, + }, +} + +impl IntKind { + /// Is this integral type signed? + pub fn is_signed(&self) -> bool { + use self::IntKind::*; + match *self { + Bool | UChar | UShort | UInt | ULong | ULongLong | U8 | U16 | + U32 | U64 | U128 => false, + + Char | Short | Int | Long | LongLong | I8 | I16 | I32 | I64 | + I128 => true, + + Custom { is_signed, .. } => is_signed, + } + } + + /// If this type has a known size, return it (in bytes). This is to + /// alleviate libclang sometimes not giving us a layout (like in the case + /// when an enum is defined inside a class with template parameters). + pub fn known_size(&self) -> Option { + use self::IntKind::*; + Some(match *self { + Bool | UChar | Char | U8 | I8 => 1, + U16 | I16 => 2, + U32 | I32 => 4, + U64 | I64 => 8, + I128 | U128 => 16, + _ => return None, + }) + } + + /// Whether this type's signedness matches the value. + pub fn signedness_matches(&self, val: i64) -> bool { + val >= 0 || self.is_signed() + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/item.rs b/bash-5.1/vendor/bindgen/src/ir/item.rs new file mode 100644 index 0000000..7b18b33 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/item.rs @@ -0,0 +1,1375 @@ +//! Bindgen's core intermediate representation type. + +use clang; +use clang_sys; +use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; +use std::cell::{Cell, RefCell}; +use std::fmt::Write; +use std::iter; +use super::annotations::Annotations; +use super::context::{BindgenContext, ItemId}; +use super::derive::{CanDeriveCopy, CanDeriveDebug}; +use super::function::Function; +use super::item_kind::ItemKind; +use super::module::Module; +use super::ty::{Type, TypeKind}; +use super::type_collector::{ItemSet, TypeCollector}; + +/// A trait to get the canonical name from an item. +/// +/// This is the trait that will eventually isolate all the logic related to name +/// mangling and that kind of stuff. +/// +/// This assumes no nested paths, at some point I'll have to make it a more +/// complex thing. +/// +/// This name is required to be safe for Rust, that is, is not expected to +/// return any rust keyword from here. +pub trait ItemCanonicalName { + /// Get the canonical name for this item. + fn canonical_name(&self, ctx: &BindgenContext) -> String; +} + +/// The same, but specifies the path that needs to be followed to reach an item. +/// +/// To contrast with canonical_name, here's an example: +/// +/// ```c++ +/// namespace foo { +/// const BAR = 3; +/// } +/// ``` +/// +/// For bar, the canonical path is `vec!["foo", "BAR"]`, while the canonical +/// name is just `"BAR"`. +pub trait ItemCanonicalPath { + /// Get the namespace-aware canonical path for this item. This means that if + /// namespaces are disabled, you'll get a single item, and otherwise you get + /// the whole path. + fn namespace_aware_canonical_path(&self, + ctx: &BindgenContext) + -> Vec; + + /// Get the canonical path for this item. + fn canonical_path(&self, ctx: &BindgenContext) -> Vec; +} + +/// A trait for iterating over an item and its parents and up its ancestor chain +/// up to (but not including) the implicit root module. +pub trait ItemAncestors { + /// Get an iterable over this item's ancestors. + fn ancestors<'a, 'b>(&self, + ctx: &'a BindgenContext<'b>) + -> ItemAncestorsIter<'a, 'b>; +} + +cfg_if! { + if #[cfg(debug_assertions)] { + type DebugOnlyItemSet = ItemSet; + } else { + struct DebugOnlyItemSet; + + impl DebugOnlyItemSet { + fn new() -> Self { + DebugOnlyItemSet + } + + fn contains(&self,_id: &ItemId) -> bool { + false + } + + fn insert(&mut self, _id: ItemId) {} + } + } +} + +/// An iterator over an item and its ancestors. +pub struct ItemAncestorsIter<'a, 'b> + where 'b: 'a, +{ + item: ItemId, + ctx: &'a BindgenContext<'b>, + seen: DebugOnlyItemSet, +} + +impl<'a, 'b> ItemAncestorsIter<'a, 'b> + where 'b: 'a, +{ + fn new(ctx: &'a BindgenContext<'b>, item: ItemId) -> Self { + ItemAncestorsIter { + item: item, + ctx: ctx, + seen: DebugOnlyItemSet::new(), + } + } +} + +impl<'a, 'b> Iterator for ItemAncestorsIter<'a, 'b> + where 'b: 'a, +{ + type Item = ItemId; + + fn next(&mut self) -> Option { + let item = self.ctx.resolve_item(self.item); + + if item.parent_id() == self.item { + None + } else { + self.item = item.parent_id(); + + debug_assert!(!self.seen.contains(&item.id())); + self.seen.insert(item.id()); + + Some(item.id()) + } + } +} + +// Pure convenience +impl ItemCanonicalName for ItemId { + fn canonical_name(&self, ctx: &BindgenContext) -> String { + debug_assert!(ctx.in_codegen_phase(), + "You're not supposed to call this yet"); + ctx.resolve_item(*self).canonical_name(ctx) + } +} + +impl ItemCanonicalPath for ItemId { + fn namespace_aware_canonical_path(&self, + ctx: &BindgenContext) + -> Vec { + debug_assert!(ctx.in_codegen_phase(), + "You're not supposed to call this yet"); + ctx.resolve_item(*self).namespace_aware_canonical_path(ctx) + } + + fn canonical_path(&self, ctx: &BindgenContext) -> Vec { + debug_assert!(ctx.in_codegen_phase(), + "You're not supposed to call this yet"); + ctx.resolve_item(*self).canonical_path(ctx) + } +} + +impl ItemAncestors for ItemId { + fn ancestors<'a, 'b>(&self, + ctx: &'a BindgenContext<'b>) + -> ItemAncestorsIter<'a, 'b> { + ItemAncestorsIter::new(ctx, *self) + } +} + +impl ItemAncestors for Item { + fn ancestors<'a, 'b>(&self, + ctx: &'a BindgenContext<'b>) + -> ItemAncestorsIter<'a, 'b> { + self.id().ancestors(ctx) + } +} + +impl TypeCollector for ItemId { + type Extra = (); + + fn collect_types(&self, + ctx: &BindgenContext, + types: &mut ItemSet, + extra: &()) { + ctx.resolve_item(*self).collect_types(ctx, types, extra); + } +} + +impl TypeCollector for Item { + type Extra = (); + + fn collect_types(&self, + ctx: &BindgenContext, + types: &mut ItemSet, + _extra: &()) { + if self.is_hidden(ctx) || types.contains(&self.id()) { + return; + } + + match *self.kind() { + ItemKind::Type(ref ty) => { + // There are some types, like resolved type references, where we + // don't want to stop collecting types even though they may be + // opaque. + if ty.should_be_traced_unconditionally() || !self.is_opaque(ctx) { + ty.collect_types(ctx, types, self); + } + } + ItemKind::Function(ref fun) => { + // Just the same way, it has not real meaning for a function to + // be opaque, so we trace across it. + types.insert(fun.signature()); + } + ItemKind::Var(ref var) => { + types.insert(var.ty()); + } + ItemKind::Module(_) => { + // Module -> children edges are "weak", and we do not want to + // trace them. If we did, then whitelisting wouldn't work as + // expected: everything in every module would end up + // whitelisted. + } + } + } +} + +impl CanDeriveDebug for Item { + type Extra = (); + + fn can_derive_debug(&self, ctx: &BindgenContext, _: ()) -> bool { + ctx.options().derive_debug && match self.kind { + ItemKind::Type(ref ty) => { + if self.is_opaque(ctx) { + ty.layout(ctx) + .map_or(true, |l| l.opaque().can_derive_debug(ctx, ())) + } else { + ty.can_derive_debug(ctx, ()) + } + } + _ => false, + } + } +} + +impl<'a> CanDeriveCopy<'a> for Item { + type Extra = (); + + fn can_derive_copy(&self, ctx: &BindgenContext, _: ()) -> bool { + match self.kind { + ItemKind::Type(ref ty) => { + if self.is_opaque(ctx) { + ty.layout(ctx) + .map_or(true, |l| l.opaque().can_derive_copy(ctx, ())) + } else { + ty.can_derive_copy(ctx, self) + } + } + _ => false, + } + } + + fn can_derive_copy_in_array(&self, ctx: &BindgenContext, _: ()) -> bool { + match self.kind { + ItemKind::Type(ref ty) => { + if self.is_opaque(ctx) { + ty.layout(ctx) + .map_or(true, |l| l.opaque().can_derive_copy_in_array(ctx, ())) + } else { + ty.can_derive_copy_in_array(ctx, self) + } + } + _ => false, + } + } +} + +/// An item is the base of the bindgen representation, it can be either a +/// module, a type, a function, or a variable (see `ItemKind` for more +/// information). +/// +/// Items refer to each other by `ItemId`. Every item has its parent's +/// id. Depending on the kind of item this is, it may also refer to other items, +/// such as a compound type item referring to other types. Collectively, these +/// references form a graph. +/// +/// The entry-point to this graph is the "root module": a meta-item used to hold +/// all top-level items. +/// +/// An item may have a comment, and annotations (see the `annotations` module). +/// +/// Note that even though we parse all the types of annotations in comments, not +/// all of them apply to every item. Those rules are described in the +/// `annotations` module. +#[derive(Debug)] +pub struct Item { + /// This item's id. + id: ItemId, + + /// The item's local id, unique only amongst its siblings. Only used for + /// anonymous items. + /// + /// Lazily initialized in local_id(). + /// + /// Note that only structs, unions, and enums get a local type id. In any + /// case this is an implementation detail. + local_id: Cell>, + + /// The next local id to use for a child.. + next_child_local_id: Cell, + + /// A cached copy of the canonical name, as returned by `canonical_name`. + /// + /// This is a fairly used operation during codegen so this makes bindgen + /// considerably faster in those cases. + canonical_name_cache: RefCell>, + + /// A doc comment over the item, if any. + comment: Option, + /// Annotations extracted from the doc comment, or the default ones + /// otherwise. + annotations: Annotations, + /// An item's parent id. This will most likely be a class where this item + /// was declared, or a module, etc. + /// + /// All the items have a parent, except the root module, in which case the + /// parent id is its own id. + parent_id: ItemId, + /// The item kind. + kind: ItemKind, +} + +impl Item { + /// Construct a new `Item`. + pub fn new(id: ItemId, + comment: Option, + annotations: Option, + parent_id: ItemId, + kind: ItemKind) + -> Self { + debug_assert!(id != parent_id || kind.is_module()); + Item { + id: id, + local_id: Cell::new(None), + next_child_local_id: Cell::new(1), + canonical_name_cache: RefCell::new(None), + parent_id: parent_id, + comment: comment, + annotations: annotations.unwrap_or_default(), + kind: kind, + } + } + + /// Get this `Item`'s identifier. + pub fn id(&self) -> ItemId { + self.id + } + + /// Get this `Item`'s parent's identifier. + /// + /// For the root module, the parent's ID is its own ID. + pub fn parent_id(&self) -> ItemId { + self.parent_id + } + + /// Set this item's parent id. + /// + /// This is only used so replacements get generated in the proper module. + pub fn set_parent_for_replacement(&mut self, id: ItemId) { + self.parent_id = id; + } + + /// Get this `Item`'s comment, if it has any. + pub fn comment(&self) -> Option<&str> { + self.comment.as_ref().map(|c| &**c) + } + + /// What kind of item is this? + pub fn kind(&self) -> &ItemKind { + &self.kind + } + + /// Get a mutable reference to this item's kind. + pub fn kind_mut(&mut self) -> &mut ItemKind { + &mut self.kind + } + + /// Get an identifier that differentiates this item from its siblings. + /// + /// This should stay relatively stable in the face of code motion outside or + /// below this item's lexical scope, meaning that this can be useful for + /// generating relatively stable identifiers within a scope. + pub fn local_id(&self, ctx: &BindgenContext) -> usize { + if self.local_id.get().is_none() { + let parent = ctx.resolve_item(self.parent_id); + let local_id = parent.next_child_local_id.get(); + parent.next_child_local_id.set(local_id + 1); + self.local_id.set(Some(local_id)); + } + self.local_id.get().unwrap() + } + + /// Returns whether this item is a top-level item, from the point of view of + /// bindgen. + /// + /// This point of view changes depending on whether namespaces are enabled + /// or not. That way, in the following example: + /// + /// ```c++ + /// namespace foo { + /// static int var; + /// } + /// ``` + /// + /// `var` would be a toplevel item if namespaces are disabled, but won't if + /// they aren't. + /// + /// This function is used to determine when the codegen phase should call + /// `codegen` on an item, since any item that is not top-level will be + /// generated by its parent. + pub fn is_toplevel(&self, ctx: &BindgenContext) -> bool { + // FIXME: Workaround for some types falling behind when parsing weird + // stl classes, for example. + if ctx.options().enable_cxx_namespaces && self.kind().is_module() && + self.id() != ctx.root_module() { + return false; + } + + let mut parent = self.parent_id; + loop { + let parent_item = match ctx.resolve_item_fallible(parent) { + Some(item) => item, + None => return false, + }; + + if parent_item.id() == ctx.root_module() { + return true; + } else if ctx.options().enable_cxx_namespaces || + !parent_item.kind().is_module() { + return false; + } + + parent = parent_item.parent_id(); + } + } + + /// Get a reference to this item's underlying `Type`. Panic if this is some + /// other kind of item. + pub fn expect_type(&self) -> &Type { + self.kind().expect_type() + } + + /// Get a reference to this item's underlying `Type`, or `None` if this is + /// some other kind of item. + pub fn as_type(&self) -> Option<&Type> { + self.kind().as_type() + } + + /// Get a reference to this item's underlying `Function`. Panic if this is + /// some other kind of item. + pub fn expect_function(&self) -> &Function { + self.kind().expect_function() + } + + /// Checks whether an item contains in its "type signature" some named type. + /// + /// This function is used to avoid unused template parameter errors in Rust + /// when generating typedef declarations, and also to know whether we need + /// to generate a `PhantomData` member for a template parameter. + /// + /// For example, in code like the following: + /// + /// ```c++ + /// template + /// struct Foo { + /// T bar; + /// + /// struct Baz { + /// U bas; + /// }; + /// }; + /// ``` + /// + /// Both `Foo` and `Baz` contain both `T` and `U` template parameters in + /// their signature: + /// + /// * `Foo` + /// * `Bar` + /// + /// But the Rust structure for `Foo` would look like: + /// + /// ```rust + /// struct Foo { + /// bar: T, + /// _phantom0: ::std::marker::PhantomData, + /// } + /// ``` + /// + /// because none of its member fields contained the `U` type in the + /// signature. Similarly, `Bar` would contain a `PhantomData` type, for + /// the same reason. + /// + /// Note that this is somewhat similar to `applicable_template_args`, but + /// this also takes into account other kind of types, like arrays, + /// (`[T; 40]`), pointers: `*mut T`, etc... + /// + /// Normally we could do this check just in the `Type` kind, but we also + /// need to check the `applicable_template_args` more generally, since we + /// could need a type transitively from our parent, see the test added in + /// commit 2a3f93074dd2898669dbbce6e97e5cc4405d7cb1. + /// + /// It's kind of unfortunate (in the sense that it's a sort of complex + /// process), but I think it should get all the cases. + fn signature_contains_named_type(&self, + ctx: &BindgenContext, + ty: &Type) + -> bool { + debug_assert!(ty.is_named()); + self.expect_type().signature_contains_named_type(ctx, ty) || + self.applicable_template_args(ctx).iter().any(|template| { + ctx.resolve_type(*template).signature_contains_named_type(ctx, ty) + }) + } + + /// Returns the template arguments that apply to a struct. This is a concept + /// needed because of type declarations inside templates, for example: + /// + /// ```c++ + /// template + /// class Foo { + /// typedef T element_type; + /// typedef int Bar; + /// + /// template + /// class Baz { + /// }; + /// }; + /// ``` + /// + /// In this case, the applicable template arguments for the different types + /// would be: + /// + /// * `Foo`: [`T`] + /// * `Foo::element_type`: [`T`] + /// * `Foo::Bar`: [`T`] + /// * `Foo::Baz`: [`T`, `U`] + /// + /// You might notice that we can't generate something like: + /// + /// ```rust,ignore + /// type Foo_Bar = ::std::os::raw::c_int; + /// ``` + /// + /// since that would be invalid Rust. Still, conceptually, `Bar` *could* use + /// the template parameter type `T`, and that's exactly what this method + /// represents. The unused template parameters get stripped in the + /// `signature_contains_named_type` check. + pub fn applicable_template_args(&self, + ctx: &BindgenContext) + -> Vec { + let ty = match *self.kind() { + ItemKind::Type(ref ty) => ty, + _ => return vec![], + }; + + fn parent_contains(ctx: &BindgenContext, + parent_template_args: &[ItemId], + item: ItemId) + -> bool { + let item_ty = ctx.resolve_type(item); + parent_template_args.iter().any(|parent_item| { + let parent_ty = ctx.resolve_type(*parent_item); + match (parent_ty.kind(), item_ty.kind()) { + (&TypeKind::Named(ref n), &TypeKind::Named(ref i)) => { + n == i + } + _ => false, + } + }) + } + + match *ty.kind() { + TypeKind::Named(..) => vec![self.id()], + TypeKind::Array(inner, _) | + TypeKind::Pointer(inner) | + TypeKind::Reference(inner) | + TypeKind::ResolvedTypeRef(inner) => { + ctx.resolve_item(inner).applicable_template_args(ctx) + } + TypeKind::Alias(_, inner) => { + let parent_args = ctx.resolve_item(self.parent_id()) + .applicable_template_args(ctx); + let inner = ctx.resolve_item(inner); + + // Avoid unused type parameters, sigh. + parent_args.iter() + .cloned() + .filter(|arg| { + let arg = ctx.resolve_type(*arg); + arg.is_named() && + inner.signature_contains_named_type(ctx, arg) + }) + .collect() + } + // XXX Is this completely correct? Partial template specialization + // is hard anyways, sigh... + TypeKind::TemplateAlias(_, _, ref args) | + TypeKind::TemplateRef(_, ref args) => args.clone(), + // In a template specialization we've got all we want. + TypeKind::Comp(ref ci) if ci.is_template_specialization() => { + ci.template_args().iter().cloned().collect() + } + TypeKind::Comp(ref ci) => { + let mut parent_template_args = + ctx.resolve_item(self.parent_id()) + .applicable_template_args(ctx); + + for ty in ci.template_args() { + if !parent_contains(ctx, &parent_template_args, *ty) { + parent_template_args.push(*ty); + } + } + + parent_template_args + } + _ => vec![], + } + } + + /// Is this item a module? + pub fn is_module(&self) -> bool { + match self.kind { + ItemKind::Module(..) => true, + _ => false, + } + } + + /// Get this item's annotations. + pub fn annotations(&self) -> &Annotations { + &self.annotations + } + + /// Whether this item should be hidden. + /// + /// This may be due to either annotations or to other kind of configuration. + pub fn is_hidden(&self, ctx: &BindgenContext) -> bool { + debug_assert!(ctx.in_codegen_phase(), + "You're not supposed to call this yet"); + self.annotations.hide() || + ctx.hidden_by_name(&self.canonical_path(ctx), self.id) + } + + /// Is this item opaque? + pub fn is_opaque(&self, ctx: &BindgenContext) -> bool { + debug_assert!(ctx.in_codegen_phase(), + "You're not supposed to call this yet"); + self.annotations.opaque() || + ctx.opaque_by_name(&self.canonical_path(ctx)) + } + + /// Is this a reference to another type? + pub fn is_type_ref(&self) -> bool { + self.as_type().map_or(false, |ty| ty.is_type_ref()) + } + + /// Is this item a var type? + pub fn is_var(&self) -> bool { + match *self.kind() { + ItemKind::Var(..) => true, + _ => false, + } + } + + /// Take out item NameOptions + pub fn name<'item, 'ctx>(&'item self, + ctx: &'item BindgenContext<'ctx>) + -> NameOptions<'item, 'ctx> { + NameOptions::new(self, ctx) + } + + /// Get the target item id for name generation. + fn name_target(&self, ctx: &BindgenContext) -> ItemId { + let mut targets_seen = DebugOnlyItemSet::new(); + let mut item = self; + + loop { + debug_assert!(!targets_seen.contains(&item.id())); + targets_seen.insert(item.id()); + + if self.annotations().use_instead_of().is_some() { + return self.id(); + } + + match *item.kind() { + ItemKind::Type(ref ty) => { + match *ty.kind() { + // If we're a template specialization, our name is our + // parent's name. + TypeKind::Comp(ref ci) + if ci.is_template_specialization() => { + let specialized = + ci.specialized_template().unwrap(); + item = ctx.resolve_item(specialized); + } + // Same as above. + TypeKind::ResolvedTypeRef(inner) | + TypeKind::TemplateRef(inner, _) => { + item = ctx.resolve_item(inner); + } + _ => return item.id(), + } + } + _ => return item.id(), + } + } + } + + /// Get this function item's name, or `None` if this item is not a function. + fn func_name(&self) -> Option<&str> { + match *self.kind() { + ItemKind::Function(ref func) => Some(func.name()), + _ => None, + } + } + + /// Get the overload index for this method. If this is not a method, return + /// `None`. + fn overload_index(&self, ctx: &BindgenContext) -> Option { + self.func_name().and_then(|func_name| { + let parent = ctx.resolve_item(self.parent_id()); + if let ItemKind::Type(ref ty) = *parent.kind() { + if let TypeKind::Comp(ref ci) = *ty.kind() { + // All the constructors have the same name, so no need to + // resolve and check. + return ci.constructors() + .iter() + .position(|c| *c == self.id()) + .or_else(|| { + ci.methods() + .iter() + .filter(|m| { + let item = ctx.resolve_item(m.signature()); + let func = item.expect_function(); + func.name() == func_name + }) + .position(|m| m.signature() == self.id()) + }); + } + } + + None + }) + } + + /// Get this item's base name (aka non-namespaced name). + fn base_name(&self, ctx: &BindgenContext) -> String { + if let Some(path) = self.annotations().use_instead_of() { + return path.last().unwrap().clone(); + } + + match *self.kind() { + ItemKind::Var(ref var) => var.name().to_owned(), + ItemKind::Module(ref module) => { + module.name() + .map(ToOwned::to_owned) + .unwrap_or_else(|| { + format!("_bindgen_mod_{}", self.exposed_id(ctx)) + }) + } + ItemKind::Type(ref ty) => { + let name = match *ty.kind() { + TypeKind::ResolvedTypeRef(..) => { + panic!("should have resolved this in name_target()") + } + _ => ty.name(), + }; + name.map(ToOwned::to_owned) + .unwrap_or_else(|| { + format!("_bindgen_ty_{}", self.exposed_id(ctx)) + }) + } + ItemKind::Function(ref fun) => { + let mut name = fun.name().to_owned(); + + if let Some(idx) = self.overload_index(ctx) { + if idx > 0 { + write!(&mut name, "{}", idx).unwrap(); + } + } + + name + } + } + } + + /// Get the canonical name without taking into account the replaces + /// annotation. + /// + /// This is the base logic used to implement hiding and replacing via + /// annotations, and also to implement proper name mangling. + /// + /// The idea is that each generated type in the same "level" (read: module + /// or namespace) has a unique canonical name. + /// + /// This name should be derived from the immutable state contained in the + /// type and the parent chain, since it should be consistent. + pub fn real_canonical_name(&self, + ctx: &BindgenContext, + opt: &NameOptions) + -> String { + let target = ctx.resolve_item(self.name_target(ctx)); + + // Short-circuit if the target has an override, and just use that. + if let Some(path) = target.annotations.use_instead_of() { + if ctx.options().enable_cxx_namespaces { + return path.last().unwrap().clone(); + } + return path.join("_").to_owned(); + } + + let base_name = target.base_name(ctx); + + // Named template type arguments are never namespaced, and never + // mangled. + if target.as_type().map_or(false, |ty| ty.is_named()) { + return base_name; + } + + // Concatenate this item's ancestors' names together. + let mut names: Vec<_> = target.parent_id() + .ancestors(ctx) + .filter(|id| *id != ctx.root_module()) + .take_while(|id| { + // Stop iterating ancestors once we reach a namespace. + !opt.within_namespaces || !ctx.resolve_item(*id).is_module() + }) + .map(|id| { + let item = ctx.resolve_item(id); + let target = ctx.resolve_item(item.name_target(ctx)); + target.base_name(ctx) + }) + .filter(|name| !name.is_empty()) + .collect(); + + names.reverse(); + + if !base_name.is_empty() { + names.push(base_name); + } + + let name = names.join("_"); + + ctx.rust_mangle(&name).into_owned() + } + + fn exposed_id(&self, ctx: &BindgenContext) -> String { + // Only use local ids for enums, classes, structs and union types. All + // other items use their global id. + let ty_kind = self.kind().as_type().map(|t| t.kind()); + if let Some(ty_kind) = ty_kind { + match *ty_kind { + TypeKind::Comp(..) | + TypeKind::Enum(..) => return self.local_id(ctx).to_string(), + _ => {} + } + } + + // Note that this `id_` prefix prevents (really unlikely) collisions + // between the global id and the local id of an item with the same + // parent. + format!("id_{}", self.id().as_usize()) + } + + /// Get a reference to this item's `Module`, or `None` if this is not a + /// `Module` item. + pub fn as_module(&self) -> Option<&Module> { + match self.kind { + ItemKind::Module(ref module) => Some(module), + _ => None, + } + } + + /// Get a mutable reference to this item's `Module`, or `None` if this is + /// not a `Module` item. + pub fn as_module_mut(&mut self) -> Option<&mut Module> { + match self.kind { + ItemKind::Module(ref mut module) => Some(module), + _ => None, + } + } +} + +// An utility function to handle recursing inside nested types. +fn visit_child(cur: clang::Cursor, + id: ItemId, + ty: &clang::Type, + parent_id: Option, + ctx: &mut BindgenContext, + result: &mut Result) + -> clang_sys::CXChildVisitResult { + use clang_sys::*; + if result.is_ok() { + return CXChildVisit_Break; + } + + *result = Item::from_ty_with_id(id, ty, Some(cur), parent_id, ctx); + + match *result { + Ok(..) => CXChildVisit_Break, + Err(ParseError::Recurse) => { + cur.visit(|c| visit_child(c, id, ty, parent_id, ctx, result)); + CXChildVisit_Continue + } + Err(ParseError::Continue) => CXChildVisit_Continue, + } +} + +impl ClangItemParser for Item { + fn builtin_type(kind: TypeKind, + is_const: bool, + ctx: &mut BindgenContext) + -> ItemId { + // Feel free to add more here, I'm just lazy. + match kind { + TypeKind::Void | + TypeKind::Int(..) | + TypeKind::Pointer(..) | + TypeKind::Float(..) => {} + _ => panic!("Unsupported builtin type"), + } + + let ty = Type::new(None, None, kind, is_const); + let id = ctx.next_item_id(); + let module = ctx.root_module(); + ctx.add_item(Item::new(id, None, None, module, ItemKind::Type(ty)), + None, + None); + id + } + + + fn parse(cursor: clang::Cursor, + parent_id: Option, + ctx: &mut BindgenContext) + -> Result { + use ir::function::Function; + use ir::module::Module; + use ir::var::Var; + use clang_sys::*; + + if !cursor.is_valid() { + return Err(ParseError::Continue); + } + + let comment = cursor.raw_comment(); + let annotations = Annotations::new(&cursor); + + let current_module = ctx.current_module(); + let relevant_parent_id = parent_id.unwrap_or(current_module); + + macro_rules! try_parse { + ($what:ident) => { + match $what::parse(cursor, ctx) { + Ok(ParseResult::New(item, declaration)) => { + let id = ctx.next_item_id(); + + ctx.add_item(Item::new(id, comment, annotations, + relevant_parent_id, + ItemKind::$what(item)), + declaration, + Some(cursor)); + return Ok(id); + } + Ok(ParseResult::AlreadyResolved(id)) => { + return Ok(id); + } + Err(ParseError::Recurse) => return Err(ParseError::Recurse), + Err(ParseError::Continue) => {}, + } + } + } + + try_parse!(Module); + + // NOTE: Is extremely important to parse functions and vars **before** + // types. Otherwise we can parse a function declaration as a type + // (which is legal), and lose functions to generate. + // + // In general, I'm not totally confident this split between + // ItemKind::Function and TypeKind::FunctionSig is totally worth it, but + // I guess we can try. + try_parse!(Function); + try_parse!(Var); + + // Types are sort of special, so to avoid parsing template classes + // twice, handle them separately. + { + let applicable_cursor = cursor.definition().unwrap_or(cursor); + match Self::from_ty(&applicable_cursor.cur_type(), + Some(applicable_cursor), + parent_id, + ctx) { + Ok(ty) => return Ok(ty), + Err(ParseError::Recurse) => return Err(ParseError::Recurse), + Err(ParseError::Continue) => {} + } + } + + // Guess how does clang treat extern "C" blocks? + if cursor.kind() == CXCursor_UnexposedDecl { + Err(ParseError::Recurse) + } else { + // We whitelist cursors here known to be unhandled, to prevent being + // too noisy about this. + match cursor.kind() { + CXCursor_MacroDefinition | + CXCursor_MacroExpansion | + CXCursor_UsingDeclaration | + CXCursor_UsingDirective | + CXCursor_StaticAssert | + CXCursor_InclusionDirective => { + debug!("Unhandled cursor kind {:?}: {:?}", + cursor.kind(), + cursor); + } + _ => { + // ignore toplevel operator overloads + let spelling = cursor.spelling(); + if !spelling.starts_with("operator") { + error!("Unhandled cursor kind {:?}: {:?}", + cursor.kind(), + cursor); + } + } + } + + Err(ParseError::Continue) + } + } + + fn from_ty_or_ref(ty: clang::Type, + location: Option, + parent_id: Option, + ctx: &mut BindgenContext) + -> ItemId { + let id = ctx.next_item_id(); + Self::from_ty_or_ref_with_id(id, ty, location, parent_id, ctx) + } + + /// Parse a C++ type. If we find a reference to a type that has not been + /// defined yet, use `UnresolvedTypeRef` as a placeholder. + /// + /// This logic is needed to avoid parsing items with the incorrect parent + /// and it's sort of complex to explain, so I'll just point to + /// `tests/headers/typeref.hpp` to see the kind of constructs that forced + /// this. + /// + /// Typerefs are resolved once parsing is completely done, see + /// `BindgenContext::resolve_typerefs`. + fn from_ty_or_ref_with_id(potential_id: ItemId, + ty: clang::Type, + location: Option, + parent_id: Option, + ctx: &mut BindgenContext) + -> ItemId { + debug!("from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}", + potential_id, + ty, + location, + parent_id); + + if ctx.collected_typerefs() { + debug!("refs already collected, resolving directly"); + return Self::from_ty_with_id(potential_id, + &ty, + location, + parent_id, + ctx) + .expect("Unable to resolve type"); + } + + if let Some(ty) = + ctx.builtin_or_resolved_ty(potential_id, parent_id, &ty, location) { + debug!("{:?} already resolved: {:?}", ty, location); + return ty; + } + + debug!("New unresolved type reference: {:?}, {:?}", ty, location); + + let is_const = ty.is_const(); + let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id); + let current_module = ctx.current_module(); + ctx.add_item(Item::new(potential_id, + None, + None, + parent_id.unwrap_or(current_module), + ItemKind::Type(Type::new(None, + None, + kind, + is_const))), + Some(clang::Cursor::null()), + None); + potential_id + } + + + fn from_ty(ty: &clang::Type, + location: Option, + parent_id: Option, + ctx: &mut BindgenContext) + -> Result { + let id = ctx.next_item_id(); + Self::from_ty_with_id(id, ty, location, parent_id, ctx) + } + + /// This is one of the trickiest methods you'll find (probably along with + /// some of the ones that handle templates in `BindgenContext`). + /// + /// This method parses a type, given the potential id of that type (if + /// parsing it was correct), an optional location we're scanning, which is + /// critical some times to obtain information, an optional parent item id, + /// that will, if it's `None`, become the current module id, and the + /// context. + fn from_ty_with_id(id: ItemId, + ty: &clang::Type, + location: Option, + parent_id: Option, + ctx: &mut BindgenContext) + -> Result { + use clang_sys::*; + + let decl = { + let decl = ty.declaration(); + decl.definition().unwrap_or(decl) + }; + + let comment = decl.raw_comment() + .or_else(|| location.as_ref().and_then(|l| l.raw_comment())); + let annotations = Annotations::new(&decl) + .or_else(|| location.as_ref().and_then(|l| Annotations::new(l))); + + if let Some(ref annotations) = annotations { + if let Some(ref replaced) = annotations.use_instead_of() { + ctx.replace(replaced, id); + } + } + + if let Some(ty) = + ctx.builtin_or_resolved_ty(id, parent_id, ty, location) { + return Ok(ty); + } + + // First, check we're not recursing. + let mut valid_decl = decl.kind() != CXCursor_NoDeclFound; + let declaration_to_look_for = if valid_decl { + decl.canonical() + } else if location.is_some() && + location.unwrap().kind() == + CXCursor_ClassTemplate { + valid_decl = true; + location.unwrap() + } else { + decl + }; + + if valid_decl { + if let Some(&(_, item_id)) = ctx.currently_parsed_types + .iter() + .find(|&&(d, _)| d == declaration_to_look_for) { + debug!("Avoiding recursion parsing type: {:?}", ty); + return Ok(item_id); + } + } + + let current_module = ctx.current_module(); + if valid_decl { + ctx.currently_parsed_types.push((declaration_to_look_for, id)); + } + + let result = Type::from_clang_ty(id, ty, location, parent_id, ctx); + let relevant_parent_id = parent_id.unwrap_or(current_module); + let ret = match result { + Ok(ParseResult::AlreadyResolved(ty)) => Ok(ty), + Ok(ParseResult::New(item, declaration)) => { + ctx.add_item(Item::new(id, + comment, + annotations, + relevant_parent_id, + ItemKind::Type(item)), + declaration, + location); + Ok(id) + } + Err(ParseError::Continue) => Err(ParseError::Continue), + Err(ParseError::Recurse) => { + debug!("Item::from_ty recursing in the ast"); + let mut result = Err(ParseError::Recurse); + if let Some(ref location) = location { + // Need to pop here, otherwise we'll get stuck. + // + // TODO: Find a nicer interface, really. Also, the + // declaration_to_look_for suspiciously shares a lot of + // logic with ir::context, so we should refactor that. + if valid_decl { + let (popped_decl, _) = + ctx.currently_parsed_types.pop().unwrap(); + assert_eq!(popped_decl, declaration_to_look_for); + } + + location.visit(|cur| { + visit_child(cur, id, ty, parent_id, ctx, &mut result) + }); + + if valid_decl { + ctx.currently_parsed_types + .push((declaration_to_look_for, id)); + } + } + // If we have recursed into the AST all we know, and we still + // haven't found what we've got, let's just make a named type. + // + // This is what happens with some template members, for example. + // + // FIXME: Maybe we should restrict this to things with parent? + // It's harmless, but if we restrict that, then + // tests/headers/nsStyleAutoArray.hpp crashes. + if let Err(ParseError::Recurse) = result { + warn!("Unknown type, assuming named template type: \ + id = {:?}; spelling = {}", + id, + ty.spelling()); + Ok(Self::named_type_with_id(id, + ty.spelling(), + relevant_parent_id, + ctx)) + } else { + result + } + } + }; + + if valid_decl { + let (popped_decl, _) = ctx.currently_parsed_types.pop().unwrap(); + assert_eq!(popped_decl, declaration_to_look_for); + } + + ret + } + + /// A named type is a template parameter, e.g., the "T" in Foo. They're + /// always local so it's the only exception when there's no declaration for + /// a type. + /// + /// It must have an id, and must not be the current module id. Ideally we + /// could assert the parent id is a Comp(..) type, but that info isn't + /// available yet. + fn named_type_with_id(id: ItemId, + name: S, + parent_id: ItemId, + ctx: &mut BindgenContext) + -> ItemId + where S: Into, + { + // see tests/headers/const_tparam.hpp + // and tests/headers/variadic_tname.hpp + let name = name.into().replace("const ", "").replace(".", ""); + + ctx.add_item(Item::new(id, + None, + None, + parent_id, + ItemKind::Type(Type::named(name))), + None, + None); + + id + } + + fn named_type(name: S, + parent_id: ItemId, + ctx: &mut BindgenContext) + -> ItemId + where S: Into, + { + let id = ctx.next_item_id(); + Self::named_type_with_id(id, name, parent_id, ctx) + } +} + +impl ItemCanonicalName for Item { + fn canonical_name(&self, ctx: &BindgenContext) -> String { + debug_assert!(ctx.in_codegen_phase(), + "You're not supposed to call this yet"); + if self.canonical_name_cache.borrow().is_none() { + let in_namespace = ctx.options().enable_cxx_namespaces || + ctx.options().disable_name_namespacing; + + *self.canonical_name_cache.borrow_mut() = if in_namespace { + Some(self.name(ctx).within_namespaces().get()) + } else { + Some(self.name(ctx).get()) + }; + } + return self.canonical_name_cache.borrow().as_ref().unwrap().clone(); + } +} + +impl ItemCanonicalPath for Item { + fn namespace_aware_canonical_path(&self, + ctx: &BindgenContext) + -> Vec { + let path = self.canonical_path(ctx); + if ctx.options().enable_cxx_namespaces { + return path; + } + if ctx.options().disable_name_namespacing { + return vec![path.last().unwrap().clone()]; + } + return vec![path[1..].join("_")]; + } + + fn canonical_path(&self, ctx: &BindgenContext) -> Vec { + if let Some(path) = self.annotations().use_instead_of() { + let mut ret = + vec![ctx.resolve_item(ctx.root_module()).name(ctx).get()]; + ret.extend_from_slice(path); + return ret; + } + + let target = ctx.resolve_item(self.name_target(ctx)); + let mut path: Vec<_> = target.ancestors(ctx) + .chain(iter::once(ctx.root_module())) + .map(|id| ctx.resolve_item(id)) + .filter(|item| { + item.id() == target.id() || + item.as_module().map_or(false, |module| { + !module.is_inline() || + ctx.options().conservative_inline_namespaces + }) + }) + .map(|item| { + ctx.resolve_item(item.name_target(ctx)) + .name(ctx) + .within_namespaces() + .get() + }) + .collect(); + path.reverse(); + path + } +} + +/// Builder struct for naming variations, which hold inside different +/// flags for naming options. +#[derive(Debug)] +pub struct NameOptions<'item, 'ctx> + where 'ctx: 'item, +{ + item: &'item Item, + ctx: &'item BindgenContext<'ctx>, + within_namespaces: bool, +} + +impl<'item, 'ctx> NameOptions<'item, 'ctx> { + /// Construct a new `NameOptions` + pub fn new(item: &'item Item, ctx: &'item BindgenContext<'ctx>) -> Self { + NameOptions { + item: item, + ctx: ctx, + within_namespaces: false, + } + } + + /// Construct the name without the item's containing C++ namespaces mangled + /// into it. In other words, the item's name within the item's namespace. + pub fn within_namespaces(&mut self) -> &mut Self { + self.within_namespaces = true; + self + } + + /// Construct a name `String` + pub fn get(&self) -> String { + self.item.real_canonical_name(self.ctx, self) + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/item_kind.rs b/bash-5.1/vendor/bindgen/src/ir/item_kind.rs new file mode 100644 index 0000000..d9e4690 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/item_kind.rs @@ -0,0 +1,114 @@ +//! Different variants of an `Item` in our intermediate representation. + +use super::function::Function; +use super::module::Module; +use super::ty::Type; +use super::var::Var; + +/// A item we parse and translate. +#[derive(Debug)] +pub enum ItemKind { + /// A module, created implicitly once (the root module), or via C++ + /// namespaces. + Module(Module), + + /// A type declared in any of the multiple ways it can be declared. + Type(Type), + + /// A function or method declaration. + Function(Function), + + /// A variable declaration, most likely a static. + Var(Var), +} + +impl ItemKind { + /// Get a reference to this `ItemKind`'s underying `Module`, or `None` if it + /// is some other kind. + pub fn as_module(&self) -> Option<&Module> { + match *self { + ItemKind::Module(ref module) => Some(module), + _ => None, + } + } + + /// Is this a module? + pub fn is_module(&self) -> bool { + self.as_module().is_some() + } + + /// Get a reference to this `ItemKind`'s underying `Module`, or panic if it + /// is some other kind. + pub fn expect_module(&self) -> &Module { + self.as_module().expect("Not a module") + } + + /// Get a reference to this `ItemKind`'s underying `Function`, or `None` if + /// it is some other kind. + pub fn as_function(&self) -> Option<&Function> { + match *self { + ItemKind::Function(ref func) => Some(func), + _ => None, + } + } + + /// Is this a function? + pub fn is_function(&self) -> bool { + self.as_function().is_some() + } + + /// Get a reference to this `ItemKind`'s underying `Function`, or panic if + /// it is some other kind. + pub fn expect_function(&self) -> &Function { + self.as_function().expect("Not a function") + } + + /// Get a reference to this `ItemKind`'s underying `Type`, or `None` if + /// it is some other kind. + pub fn as_type(&self) -> Option<&Type> { + match *self { + ItemKind::Type(ref ty) => Some(ty), + _ => None, + } + } + + /// Get a mutable reference to this `ItemKind`'s underying `Type`, or `None` + /// if it is some other kind. + pub fn as_type_mut(&mut self) -> Option<&mut Type> { + match *self { + ItemKind::Type(ref mut ty) => Some(ty), + _ => None, + } + } + + /// Is this a type? + pub fn is_type(&self) -> bool { + self.as_type().is_some() + } + + /// Get a reference to this `ItemKind`'s underying `Type`, or panic if it is + /// some other kind. + pub fn expect_type(&self) -> &Type { + self.as_type().expect("Not a type") + } + + /// Get a reference to this `ItemKind`'s underying `Var`, or `None` if it is + /// some other kind. + pub fn as_var(&self) -> Option<&Var> { + match *self { + ItemKind::Var(ref v) => Some(v), + _ => None, + } + } + + /// Is this a variable? + pub fn is_var(&self) -> bool { + self.as_var().is_some() + } + + /// Get a reference to this `ItemKind`'s underying `Var`, or panic if it is + /// some other kind. + pub fn expect_var(&self) -> &Var { + self.as_var().expect("Not a var") + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/layout.rs b/bash-5.1/vendor/bindgen/src/ir/layout.rs new file mode 100644 index 0000000..033fff6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/layout.rs @@ -0,0 +1,91 @@ +//! Intermediate representation for the physical layout of some type. + +use std::cmp; +use super::context::BindgenContext; +use super::derive::{CanDeriveCopy, CanDeriveDebug}; +use super::ty::RUST_DERIVE_IN_ARRAY_LIMIT; + +/// A type that represents the struct layout of a type. +#[derive(Debug, Clone, Copy)] +pub struct Layout { + /// The size (in bytes) of this layout. + pub size: usize, + /// The alignment (in bytes) of this layout. + pub align: usize, + /// Whether this layout's members are packed or not. + pub packed: bool, +} + +impl Layout { + /// Construct a new `Layout` with the given `size` and `align`. It is not + /// packed. + pub fn new(size: usize, align: usize) -> Self { + Layout { + size: size, + align: align, + packed: false, + } + } + + /// Is this a zero-sized layout? + pub fn is_zero(&self) -> bool { + self.size == 0 && self.align == 0 + } + + /// Construct a zero-sized layout. + pub fn zero() -> Self { + Self::new(0, 0) + } + + /// Get this layout as an opaque type. + pub fn opaque(&self) -> Opaque { + Opaque(*self) + } +} + +/// When we are treating a type as opaque, it is just a blob with a `Layout`. +pub struct Opaque(pub Layout); + +impl Opaque { + /// Return the known rust type we should use to create a correctly-aligned + /// field with this layout. + pub fn known_rust_type_for_array(&self) -> Option<&'static str> { + Some(match self.0.align { + 8 => "u64", + 4 => "u32", + 2 => "u16", + 1 => "u8", + _ => return None, + }) + } + + /// Return the array size that an opaque type for this layout should have if + /// we know the correct type for it, or `None` otherwise. + pub fn array_size(&self) -> Option { + if self.known_rust_type_for_array().is_some() { + Some(self.0.size / cmp::max(self.0.align, 1)) + } else { + None + } + } +} + +impl CanDeriveDebug for Opaque { + type Extra = (); + + fn can_derive_debug(&self, _: &BindgenContext, _: ()) -> bool { + self.array_size().map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + } +} + +impl<'a> CanDeriveCopy<'a> for Opaque { + type Extra = (); + + fn can_derive_copy(&self, _: &BindgenContext, _: ()) -> bool { + self.array_size().map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + } + + fn can_derive_copy_in_array(&self, ctx: &BindgenContext, _: ()) -> bool { + self.can_derive_copy(ctx, ()) + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/mod.rs b/bash-5.1/vendor/bindgen/src/ir/mod.rs new file mode 100644 index 0000000..73793b1 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/mod.rs @@ -0,0 +1,19 @@ +//! The ir module defines bindgen's intermediate representation. +//! +//! Parsing C/C++ generates the IR, while code generation outputs Rust code from +//! the IR. + +pub mod annotations; +pub mod comp; +pub mod context; +pub mod derive; +pub mod enum_ty; +pub mod function; +pub mod int; +pub mod item; +pub mod item_kind; +pub mod layout; +pub mod module; +pub mod ty; +pub mod type_collector; +pub mod var; diff --git a/bash-5.1/vendor/bindgen/src/ir/module.rs b/bash-5.1/vendor/bindgen/src/ir/module.rs new file mode 100644 index 0000000..002fe36 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/module.rs @@ -0,0 +1,78 @@ +//! Intermediate representation for modules (AKA C++ namespaces). + +use clang; +use parse::{ClangSubItemParser, ParseError, ParseResult}; +use parse_one; +use super::context::{BindgenContext, ItemId}; + +/// Whether this module is inline or not. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum ModuleKind { + /// This module is not inline. + Normal, + /// This module is inline, as in `inline namespace foo {}`. + Inline, +} + +/// A module, as in, a C++ namespace. +#[derive(Clone, Debug)] +pub struct Module { + /// The name of the module, or none if it's anonymous. + name: Option, + /// The kind of module this is. + kind: ModuleKind, + /// The children of this module, just here for convenience. + children_ids: Vec, +} + +impl Module { + /// Construct a new `Module`. + pub fn new(name: Option, kind: ModuleKind) -> Self { + Module { + name: name, + kind: kind, + children_ids: vec![], + } + } + + /// Get this module's name. + pub fn name(&self) -> Option<&str> { + self.name.as_ref().map(|n| &**n) + } + + /// Get a mutable reference to this module's children. + pub fn children_mut(&mut self) -> &mut Vec { + &mut self.children_ids + } + + /// Get this module's children. + pub fn children(&self) -> &[ItemId] { + &self.children_ids + } + + /// Whether this namespace is inline. + pub fn is_inline(&self) -> bool { + self.kind == ModuleKind::Inline + } +} + +impl ClangSubItemParser for Module { + fn parse(cursor: clang::Cursor, + ctx: &mut BindgenContext) + -> Result, ParseError> { + use clang_sys::*; + match cursor.kind() { + CXCursor_Namespace => { + let module_id = ctx.module(cursor); + ctx.with_module(module_id, |ctx| { + cursor.visit(|cursor| { + parse_one(ctx, cursor, Some(module_id)) + }) + }); + + Ok(ParseResult::AlreadyResolved(module_id)) + } + _ => Err(ParseError::Continue), + } + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/ty.rs b/bash-5.1/vendor/bindgen/src/ir/ty.rs new file mode 100644 index 0000000..1e87beb --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/ty.rs @@ -0,0 +1,937 @@ +//! Everything related to types in our intermediate representation. + +use clang::{self, Cursor}; +use parse::{ClangItemParser, ParseError, ParseResult}; +use super::comp::CompInfo; +use super::context::{BindgenContext, ItemId}; +use super::derive::{CanDeriveCopy, CanDeriveDebug}; +use super::enum_ty::Enum; +use super::function::FunctionSig; +use super::int::IntKind; +use super::item::Item; +use super::layout::Layout; +use super::type_collector::{ItemSet, TypeCollector}; + +/// The base representation of a type in bindgen. +/// +/// A type has an optional name, which if present cannot be empty, a `layout` +/// (size, alignment and packedness) if known, a `Kind`, which determines which +/// kind of type it is, and whether the type is const. +#[derive(Debug)] +pub struct Type { + /// The name of the type, or None if it was an unnamed struct or union. + name: Option, + /// The layout of the type, if known. + layout: Option, + /// The inner kind of the type + kind: TypeKind, + /// Whether this type is const-qualified. + is_const: bool, +} + +/// The maximum number of items in an array for which Rust implements common +/// traits, and so if we have a type containing an array with more than this +/// many items, we won't be able to derive common traits on that type. +/// +/// We need type-level integers yesterday :'( +pub const RUST_DERIVE_IN_ARRAY_LIMIT: usize = 32; + +impl Type { + /// Get the underlying `CompInfo` for this type, or `None` if this is some + /// other kind of type. + pub fn as_comp(&self) -> Option<&CompInfo> { + match self.kind { + TypeKind::Comp(ref ci) => Some(ci), + _ => None, + } + } + + /// Construct a new `Type`. + pub fn new(name: Option, + layout: Option, + kind: TypeKind, + is_const: bool) + -> Self { + Type { + name: name, + layout: layout, + kind: kind, + is_const: is_const, + } + } + + /// Which kind of type is this? + pub fn kind(&self) -> &TypeKind { + &self.kind + } + + /// Overrides the kind of the item. This is mostly a template alias + /// implementation detail, and debug assertions guard it like so. + pub fn set_kind(&mut self, kind: TypeKind) { + if cfg!(debug_assertions) { + match (&self.kind, &kind) { + (&TypeKind::Alias(ref alias_name, alias_inner), + &TypeKind::TemplateAlias(ref name, inner, _)) => { + assert_eq!(alias_name, name); + assert_eq!(alias_inner, inner); + } + _ => panic!("Unexpected kind in `set_kind`!"), + }; + } + self.kind = kind; + } + + /// Get a mutable reference to this type's kind. + pub fn kind_mut(&mut self) -> &mut TypeKind { + &mut self.kind + } + + /// Get this type's name. + pub fn name(&self) -> Option<&str> { + self.name.as_ref().map(|name| &**name) + } + + /// Is this a compound type? + pub fn is_comp(&self) -> bool { + match self.kind { + TypeKind::Comp(..) => true, + _ => false, + } + } + + /// Is this a named type? + pub fn is_named(&self) -> bool { + match self.kind { + TypeKind::Named(..) => true, + _ => false, + } + } + + /// Is this a template alias type? + pub fn is_template_alias(&self) -> bool { + match self.kind { + TypeKind::TemplateAlias(..) => true, + _ => false, + } + } + + /// Is this a function type? + pub fn is_function(&self) -> bool { + match self.kind { + TypeKind::Function(..) => true, + _ => false, + } + } + + /// Is this an enum type? + pub fn is_enum(&self) -> bool { + match self.kind { + TypeKind::Enum(..) => true, + _ => false, + } + } + + /// Is this either a builtin or named type? + pub fn is_builtin_or_named(&self) -> bool { + match self.kind { + TypeKind::Void | + TypeKind::NullPtr | + TypeKind::Function(..) | + TypeKind::Array(..) | + TypeKind::Reference(..) | + TypeKind::Pointer(..) | + TypeKind::BlockPointer | + TypeKind::Int(..) | + TypeKind::Float(..) | + TypeKind::Named(..) => true, + _ => false, + } + } + + /// Creates a new named type, with name `name`. + pub fn named(name: String) -> Self { + assert!(!name.is_empty()); + // TODO: stop duplicating the name, it's stupid. + let kind = TypeKind::Named(name.clone()); + Self::new(Some(name), None, kind, false) + } + + /// Is this a floating point type? + pub fn is_float(&self) -> bool { + match self.kind { + TypeKind::Float(..) => true, + _ => false, + } + } + + /// Is this a boolean type? + pub fn is_bool(&self) -> bool { + match self.kind { + TypeKind::Int(IntKind::Bool) => true, + _ => false, + } + } + + /// Is this an integer type? + pub fn is_integer(&self) -> bool { + match self.kind { + TypeKind::Int(..) => true, + _ => false, + } + } + + /// Is this a `const` qualified type? + pub fn is_const(&self) -> bool { + self.is_const + } + + /// Is this a reference to another type? + pub fn is_type_ref(&self) -> bool { + match self.kind { + TypeKind::ResolvedTypeRef(_) | + TypeKind::UnresolvedTypeRef(_, _, _) => true, + _ => false, + } + } + + /// What is the layout of this type? + pub fn layout(&self, ctx: &BindgenContext) -> Option { + use std::mem; + + self.layout.or_else(|| { + match self.kind { + TypeKind::Comp(ref ci) => ci.layout(ctx), + // FIXME(emilio): This is a hack for anonymous union templates. + // Use the actual pointer size! + TypeKind::Pointer(..) | + TypeKind::BlockPointer => { + Some(Layout::new(mem::size_of::<*mut ()>(), + mem::align_of::<*mut ()>())) + } + TypeKind::ResolvedTypeRef(inner) => { + ctx.resolve_type(inner).layout(ctx) + } + _ => None, + } + }) + } + + /// Whether this type has a vtable. + pub fn has_vtable(&self, ctx: &BindgenContext) -> bool { + // FIXME: Can we do something about template parameters? Huh... + match self.kind { + TypeKind::TemplateRef(t, _) | + TypeKind::TemplateAlias(_, t, _) | + TypeKind::Alias(_, t) | + TypeKind::ResolvedTypeRef(t) => ctx.resolve_type(t).has_vtable(ctx), + TypeKind::Comp(ref info) => info.has_vtable(ctx), + _ => false, + } + + } + + /// Returns whether this type has a destructor. + pub fn has_destructor(&self, ctx: &BindgenContext) -> bool { + match self.kind { + TypeKind::TemplateRef(t, _) | + TypeKind::TemplateAlias(_, t, _) | + TypeKind::Alias(_, t) | + TypeKind::ResolvedTypeRef(t) => { + ctx.resolve_type(t).has_destructor(ctx) + } + TypeKind::Comp(ref info) => info.has_destructor(ctx), + _ => false, + } + } + + /// See the comment in `Item::signature_contains_named_type`. + pub fn signature_contains_named_type(&self, + ctx: &BindgenContext, + ty: &Type) + -> bool { + let name = match *ty.kind() { + TypeKind::Named(ref name) => name, + ref other @ _ => unreachable!("Not a named type: {:?}", other), + }; + + match self.kind { + TypeKind::Named(ref this_name) => this_name == name, + TypeKind::ResolvedTypeRef(t) | + TypeKind::Array(t, _) | + TypeKind::Pointer(t) | + TypeKind::Alias(_, t) => { + ctx.resolve_type(t) + .signature_contains_named_type(ctx, ty) + } + TypeKind::Function(ref sig) => { + sig.argument_types().iter().any(|&(_, arg)| { + ctx.resolve_type(arg) + .signature_contains_named_type(ctx, ty) + }) || + ctx.resolve_type(sig.return_type()) + .signature_contains_named_type(ctx, ty) + } + TypeKind::TemplateAlias(_, _, ref template_args) | + TypeKind::TemplateRef(_, ref template_args) => { + template_args.iter().any(|arg| { + ctx.resolve_type(*arg) + .signature_contains_named_type(ctx, ty) + }) + } + TypeKind::Comp(ref ci) => ci.signature_contains_named_type(ctx, ty), + _ => false, + } + } + + /// See safe_canonical_type. + pub fn canonical_type<'tr>(&'tr self, + ctx: &'tr BindgenContext) + -> &'tr Type { + self.safe_canonical_type(ctx) + .expect("Should have been resolved after parsing!") + } + + /// Returns the canonical type of this type, that is, the "inner type". + /// + /// For example, for a `typedef`, the canonical type would be the + /// `typedef`ed type, for a template specialization, would be the template + /// its specializing, and so on. Return None if the type is unresolved. + pub fn safe_canonical_type<'tr>(&'tr self, + ctx: &'tr BindgenContext) + -> Option<&'tr Type> { + match self.kind { + TypeKind::Named(..) | + TypeKind::Array(..) | + TypeKind::Comp(..) | + TypeKind::Int(..) | + TypeKind::Float(..) | + TypeKind::Complex(..) | + TypeKind::Function(..) | + TypeKind::Enum(..) | + TypeKind::Reference(..) | + TypeKind::Void | + TypeKind::NullPtr | + TypeKind::BlockPointer | + TypeKind::Pointer(..) => Some(self), + + TypeKind::ResolvedTypeRef(inner) | + TypeKind::Alias(_, inner) | + TypeKind::TemplateAlias(_, inner, _) | + TypeKind::TemplateRef(inner, _) => { + ctx.resolve_type(inner).safe_canonical_type(ctx) + } + + TypeKind::UnresolvedTypeRef(..) => None, + } + } + + /// There are some types we don't want to stop at when finding an opaque + /// item, so we can arrive to the proper item that needs to be generated. + pub fn should_be_traced_unconditionally(&self) -> bool { + match self.kind { + TypeKind::Function(..) | + TypeKind::Pointer(..) | + TypeKind::Array(..) | + TypeKind::Reference(..) | + TypeKind::TemplateRef(..) | + TypeKind::ResolvedTypeRef(..) => true, + _ => false, + } + } +} + +impl CanDeriveDebug for Type { + type Extra = (); + + fn can_derive_debug(&self, ctx: &BindgenContext, _: ()) -> bool { + match self.kind { + TypeKind::Array(t, len) => { + len <= RUST_DERIVE_IN_ARRAY_LIMIT && t.can_derive_debug(ctx, ()) + } + TypeKind::ResolvedTypeRef(t) | + TypeKind::TemplateAlias(_, t, _) | + TypeKind::Alias(_, t) => t.can_derive_debug(ctx, ()), + TypeKind::Comp(ref info) => { + info.can_derive_debug(ctx, self.layout(ctx)) + } + _ => true, + } + } +} + +impl<'a> CanDeriveCopy<'a> for Type { + type Extra = &'a Item; + + fn can_derive_copy(&self, ctx: &BindgenContext, item: &Item) -> bool { + match self.kind { + TypeKind::Array(t, len) => { + len <= RUST_DERIVE_IN_ARRAY_LIMIT && + t.can_derive_copy_in_array(ctx, ()) + } + TypeKind::ResolvedTypeRef(t) | + TypeKind::TemplateAlias(_, t, _) | + TypeKind::TemplateRef(t, _) | + TypeKind::Alias(_, t) => t.can_derive_copy(ctx, ()), + TypeKind::Comp(ref info) => { + info.can_derive_copy(ctx, (item, self.layout(ctx))) + } + _ => true, + } + } + + fn can_derive_copy_in_array(&self, + ctx: &BindgenContext, + item: &Item) + -> bool { + match self.kind { + TypeKind::ResolvedTypeRef(t) | + TypeKind::TemplateAlias(_, t, _) | + TypeKind::Alias(_, t) | + TypeKind::Array(t, _) => t.can_derive_copy_in_array(ctx, ()), + TypeKind::Named(..) => false, + _ => self.can_derive_copy(ctx, item), + } + } +} + +/// The kind of float this type represents. +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum FloatKind { + /// A `float`. + Float, + /// A `double`. + Double, + /// A `long double`. + LongDouble, + /// A `__float128`. + Float128, +} + +/// The different kinds of types that we can parse. +#[derive(Debug)] +pub enum TypeKind { + /// The void type. + Void, + + /// The `nullptr_t` type. + NullPtr, + + /// A compound type, that is, a class, struct, or union. + Comp(CompInfo), + + /// An integer type, of a given kind. `bool` and `char` are also considered + /// integers. + Int(IntKind), + + /// A floating point type. + Float(FloatKind), + + /// A complex floating point type. + Complex(FloatKind), + + /// A type alias, with a name, that points to another type. + Alias(String, ItemId), + + /// A templated alias, pointing to an inner type, just as `Alias`, but with + /// template parameters. + TemplateAlias(String, ItemId, Vec), + + /// An array of a type and a lenght. + Array(ItemId, usize), + + /// A function type, with a given signature. + Function(FunctionSig), + + /// An `enum` type. + Enum(Enum), + + /// A pointer to a type. The bool field represents whether it's const or + /// not. + Pointer(ItemId), + + /// A pointer to an Apple block. + BlockPointer, + + /// A reference to a type, as in: int& foo(). + Reference(ItemId), + + /// A reference to a template, with different template parameter names. To + /// see why this is needed, check out the creation of this variant in + /// `Type::from_clang_ty`. + TemplateRef(ItemId, Vec), + + /// A reference to a yet-to-resolve type. This stores the clang cursor + /// itself, and postpones its resolution. + /// + /// These are gone in a phase after parsing where these are mapped to + /// already known types, and are converted to ResolvedTypeRef. + /// + /// see tests/headers/typeref.hpp to see somewhere where this is a problem. + UnresolvedTypeRef(clang::Type, + Option, + /* parent_id */ + Option), + + /// An indirection to another type. + /// + /// These are generated after we resolve a forward declaration, or when we + /// replace one type with another. + ResolvedTypeRef(ItemId), + + /// A named type, that is, a template parameter. + Named(String), +} + +impl Type { + /// Whether this type is unsized, that is, has no members. This is used to + /// derive whether we should generate a dummy `_address` field for structs, + /// to comply to the C and C++ layouts, that specify that every type needs + /// to be addressable. + pub fn is_unsized(&self, ctx: &BindgenContext) -> bool { + debug_assert!(ctx.in_codegen_phase(), "Not yet"); + + match self.kind { + TypeKind::Void => true, + TypeKind::Comp(ref ci) => ci.is_unsized(ctx), + TypeKind::Array(inner, size) => { + size == 0 || ctx.resolve_type(inner).is_unsized(ctx) + } + TypeKind::ResolvedTypeRef(inner) | + TypeKind::Alias(_, inner) | + TypeKind::TemplateAlias(_, inner, _) | + TypeKind::TemplateRef(inner, _) => { + ctx.resolve_type(inner).is_unsized(ctx) + } + TypeKind::Named(..) | + TypeKind::Int(..) | + TypeKind::Float(..) | + TypeKind::Complex(..) | + TypeKind::Function(..) | + TypeKind::Enum(..) | + TypeKind::Reference(..) | + TypeKind::NullPtr | + TypeKind::BlockPointer | + TypeKind::Pointer(..) => false, + + TypeKind::UnresolvedTypeRef(..) => { + unreachable!("Should have been resolved after parsing!"); + } + } + } + + /// This is another of the nasty methods. This one is the one that takes + /// care of the core logic of converting a clang type to a `Type`. + /// + /// It's sort of nasty and full of special-casing, but hopefully the + /// comments in every special case justify why they're there. + pub fn from_clang_ty(potential_id: ItemId, + ty: &clang::Type, + location: Option, + parent_id: Option, + ctx: &mut BindgenContext) + -> Result, ParseError> { + use clang_sys::*; + { + let already_resolved = + ctx.builtin_or_resolved_ty(potential_id, + parent_id, + ty, + location); + if let Some(ty) = already_resolved { + debug!("{:?} already resolved: {:?}", ty, location); + return Ok(ParseResult::AlreadyResolved(ty)); + } + } + + let layout = ty.fallible_layout().ok(); + let cursor = ty.declaration(); + let mut name = cursor.spelling(); + + debug!("from_clang_ty: {:?}, ty: {:?}, loc: {:?}", + potential_id, + ty, + location); + debug!("currently_parsed_types: {:?}", ctx.currently_parsed_types); + + let canonical_ty = ty.canonical_type(); + let kind = match ty.kind() { + CXType_Unexposed if *ty != canonical_ty && + canonical_ty.kind() != CXType_Invalid => { + debug!("Looking for canonical type: {:?}", canonical_ty); + return Self::from_clang_ty(potential_id, + &canonical_ty, + location, + parent_id, + ctx); + } + CXType_Unexposed | CXType_Invalid => { + // For some reason Clang doesn't give us any hint in some + // situations where we should generate a function pointer (see + // tests/headers/func_ptr_in_struct.h), so we do a guess here + // trying to see if it has a valid return type. + if ty.ret_type().is_some() { + let signature = try!(FunctionSig::from_ty(ty, + &location.unwrap_or(cursor), + ctx)); + TypeKind::Function(signature) + // Same here, with template specialisations we can safely + // assume this is a Comp(..) + } else if ty.is_fully_specialized_template() { + debug!("Template specialization: {:?}", ty); + let complex = + CompInfo::from_ty(potential_id, ty, location, ctx) + .expect("C'mon"); + TypeKind::Comp(complex) + } else if let Some(location) = location { + match location.kind() { + CXCursor_ClassTemplatePartialSpecialization | + CXCursor_CXXBaseSpecifier | + CXCursor_ClassTemplate => { + if location.kind() == CXCursor_CXXBaseSpecifier { + // In the case we're parsing a base specifier + // inside an unexposed or invalid type, it means + // that we're parsing one of two things: + // + // * A template parameter. + // * A complex class that isn't exposed. + // + // This means, unfortunately, that there's no + // good way to differentiate between them. + // + // Probably we could try to look at the + // declaration and complicate more this logic, + // but we'll keep it simple... if it's a valid + // C++ identifier, we'll consider it as a + // template parameter. + // + // This is because: + // + // * We expect every other base that is a + // proper identifier (that is, a simple + // struct/union declaration), to be exposed, + // so this path can't be reached in that + // case. + // + // * Quite conveniently, complex base + // specifiers preserve their full names (that + // is: Foo instead of Foo). We can take + // advantage of this. + // + // If we find some edge case where this doesn't + // work (which I guess is unlikely, see the + // different test cases[1][2][3][4]), we'd need + // to find more creative ways of differentiating + // these two cases. + // + // [1]: inherit_named.hpp + // [2]: forward-inherit-struct-with-fields.hpp + // [3]: forward-inherit-struct.hpp + // [4]: inherit-namespaced.hpp + if location.spelling() + .chars() + .all(|c| c.is_alphanumeric() || c == '_') { + return Err(ParseError::Recurse); + } + } else { + name = location.spelling(); + } + let complex = CompInfo::from_ty(potential_id, + ty, + Some(location), + ctx) + .expect("C'mon"); + TypeKind::Comp(complex) + } + CXCursor_TypeAliasTemplateDecl => { + debug!("TypeAliasTemplateDecl"); + + // We need to manually unwind this one. + let mut inner = Err(ParseError::Continue); + let mut args = vec![]; + + location.visit(|cur| { + match cur.kind() { + CXCursor_TypeAliasDecl => { + let current = cur.cur_type(); + + debug_assert!(current.kind() == + CXType_Typedef); + + name = current.spelling(); + + let inner_ty = cur.typedef_type() + .expect("Not valid Type?"); + inner = + Item::from_ty(&inner_ty, + Some(cur), + Some(potential_id), + ctx); + } + CXCursor_TemplateTypeParameter => { + // See the comment in src/ir/comp.rs + // about the same situation. + if cur.spelling().is_empty() { + return CXChildVisit_Continue; + } + + let param = + Item::named_type(cur.spelling(), + potential_id, + ctx); + args.push(param); + } + _ => {} + } + CXChildVisit_Continue + }); + + let inner_type = match inner { + Ok(inner) => inner, + Err(..) => { + error!("Failed to parse template alias \ + {:?}", + location); + return Err(ParseError::Continue); + } + }; + + TypeKind::TemplateAlias(name.clone(), + inner_type, + args) + } + CXCursor_TemplateRef => { + let referenced = location.referenced().unwrap(); + let referenced_ty = referenced.cur_type(); + + debug!("TemplateRef: location = {:?}; referenced = \ + {:?}; referenced_ty = {:?}", + location, + referenced, + referenced_ty); + + return Self::from_clang_ty(potential_id, + &referenced_ty, + Some(referenced), + parent_id, + ctx); + } + CXCursor_TypeRef => { + let referenced = location.referenced().unwrap(); + let referenced_ty = referenced.cur_type(); + let declaration = referenced_ty.declaration(); + + debug!("TypeRef: location = {:?}; referenced = \ + {:?}; referenced_ty = {:?}", + location, + referenced, + referenced_ty); + + let item = + Item::from_ty_or_ref_with_id(potential_id, + referenced_ty, + Some(declaration), + parent_id, + ctx); + return Ok(ParseResult::AlreadyResolved(item)); + } + CXCursor_NamespaceRef => { + return Err(ParseError::Continue); + } + _ => { + if ty.kind() == CXType_Unexposed { + warn!("Unexposed type {:?}, recursing inside, \ + loc: {:?}", + ty, + location); + return Err(ParseError::Recurse); + } + + // If the type name is empty we're probably + // over-recursing to find a template parameter name + // or something like that, so just don't be too + // noisy with it since it causes confusion, see for + // example the discussion in: + // + // https://github.com/jamesmunns/teensy3-rs/issues/9 + if !ty.spelling().is_empty() { + warn!("invalid type {:?}", ty); + } else { + warn!("invalid type {:?}", ty); + } + return Err(ParseError::Continue); + } + } + } else { + // TODO: Don't duplicate this! + if ty.kind() == CXType_Unexposed { + warn!("Unexposed type {:?}, recursing inside", ty); + return Err(ParseError::Recurse); + } + + if !ty.spelling().is_empty() { + warn!("invalid type {:?}", ty); + } else { + warn!("invalid type {:?}", ty); + } + return Err(ParseError::Continue); + } + } + CXType_Auto => { + if canonical_ty == *ty { + debug!("Couldn't find deduced type: {:?}", ty); + return Err(ParseError::Continue); + } + + return Self::from_clang_ty(potential_id, + &canonical_ty, + location, + parent_id, + ctx); + } + // NOTE: We don't resolve pointers eagerly because the pointee type + // might not have been parsed, and if it contains templates or + // something else we might get confused, see the comment inside + // TypeRef. + // + // We might need to, though, if the context is already in the + // process of resolving them. + CXType_MemberPointer | + CXType_Pointer => { + let inner = Item::from_ty_or_ref(ty.pointee_type().unwrap(), + location, + parent_id, + ctx); + TypeKind::Pointer(inner) + } + CXType_BlockPointer => TypeKind::BlockPointer, + // XXX: RValueReference is most likely wrong, but I don't think we + // can even add bindings for that, so huh. + CXType_RValueReference | + CXType_LValueReference => { + let inner = Item::from_ty_or_ref(ty.pointee_type().unwrap(), + location, + parent_id, + ctx); + TypeKind::Reference(inner) + } + // XXX DependentSizedArray is wrong + CXType_VariableArray | + CXType_DependentSizedArray | + CXType_IncompleteArray => { + let inner = Item::from_ty(ty.elem_type().as_ref().unwrap(), + location, + parent_id, + ctx) + .expect("Not able to resolve array element?"); + TypeKind::Pointer(inner) + } + CXType_FunctionNoProto | + CXType_FunctionProto => { + let signature = try!(FunctionSig::from_ty(ty, + &location.unwrap_or(cursor), + ctx)); + TypeKind::Function(signature) + } + CXType_Typedef => { + let inner = cursor.typedef_type().expect("Not valid Type?"); + let inner = + Item::from_ty_or_ref(inner, location, parent_id, ctx); + TypeKind::Alias(ty.spelling(), inner) + } + CXType_Enum => { + let enum_ = Enum::from_ty(ty, ctx).expect("Not an enum?"); + TypeKind::Enum(enum_) + } + CXType_Record => { + let complex = + CompInfo::from_ty(potential_id, ty, location, ctx) + .expect("Not a complex type?"); + TypeKind::Comp(complex) + } + // FIXME: We stub vectors as arrays since in 99% of the cases the + // layout is going to be correct, and there's no way we can generate + // vector types properly in Rust for now. + // + // That being said, that should be fixed eventually. + CXType_Vector | + CXType_ConstantArray => { + let inner = Item::from_ty(ty.elem_type().as_ref().unwrap(), + location, + parent_id, + ctx) + .expect("Not able to resolve array element?"); + TypeKind::Array(inner, ty.num_elements().unwrap()) + } + CXType_Elaborated => { + return Self::from_clang_ty(potential_id, + &ty.named(), + location, + parent_id, + ctx); + } + _ => { + error!("unsupported type: kind = {:?}; ty = {:?}; at {:?}", + ty.kind(), + ty, + location); + return Err(ParseError::Continue); + } + }; + + let name = if name.is_empty() { None } else { Some(name) }; + let is_const = ty.is_const(); + + let ty = Type::new(name, layout, kind, is_const); + // TODO: maybe declaration.canonical()? + Ok(ParseResult::New(ty, Some(cursor.canonical()))) + } +} + +impl TypeCollector for Type { + type Extra = Item; + + fn collect_types(&self, + context: &BindgenContext, + types: &mut ItemSet, + item: &Item) { + match *self.kind() { + TypeKind::Pointer(inner) | + TypeKind::Reference(inner) | + TypeKind::Array(inner, _) | + TypeKind::Alias(_, inner) | + TypeKind::ResolvedTypeRef(inner) => { + types.insert(inner); + } + + TypeKind::TemplateAlias(_, inner, ref template_args) | + TypeKind::TemplateRef(inner, ref template_args) => { + types.insert(inner); + for &item in template_args { + types.insert(item); + } + } + TypeKind::Comp(ref ci) => ci.collect_types(context, types, item), + TypeKind::Function(ref sig) => { + sig.collect_types(context, types, item) + } + TypeKind::Enum(ref en) => { + if let Some(repr) = en.repr() { + types.insert(repr); + } + } + TypeKind::UnresolvedTypeRef(_, _, Some(id)) => { + types.insert(id); + } + + // None of these variants have edges to other items and types. + TypeKind::UnresolvedTypeRef(_, _, None) | + TypeKind::Named(_) | + TypeKind::Void | + TypeKind::NullPtr | + TypeKind::Int(_) | + TypeKind::Float(_) | + TypeKind::Complex(_) | + TypeKind::BlockPointer => {} + } + } +} diff --git a/bash-5.1/vendor/bindgen/src/ir/type_collector.rs b/bash-5.1/vendor/bindgen/src/ir/type_collector.rs new file mode 100644 index 0000000..0f10152 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/type_collector.rs @@ -0,0 +1,22 @@ +//! Collecting type items. + +use std::collections::BTreeSet; +use super::context::{BindgenContext, ItemId}; + +/// A set of items. +pub type ItemSet = BTreeSet; + +/// Collect all the type items referenced by this item. +pub trait TypeCollector { + /// If a particular type needs extra information beyond what it has in + /// `self` and `context` to find its referenced type items, its + /// implementation can define this associated type, forcing callers to pass + /// the needed information through. + type Extra; + + /// Add each type item referenced by `self` into the `types` set. + fn collect_types(&self, + context: &BindgenContext, + types: &mut ItemSet, + extra: &Self::Extra); +} diff --git a/bash-5.1/vendor/bindgen/src/ir/var.rs b/bash-5.1/vendor/bindgen/src/ir/var.rs new file mode 100644 index 0000000..329393f --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/ir/var.rs @@ -0,0 +1,317 @@ +//! Intermediate representation of variables. + +use cexpr; +use clang; +use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; +use std::num::Wrapping; +use super::context::{BindgenContext, ItemId}; +use super::function::cursor_mangling; +use super::int::IntKind; +use super::item::Item; +use super::ty::{FloatKind, TypeKind}; + +/// The type for a constant variable. +#[derive(Debug)] +pub enum VarType { + /// A boolean. + Bool(bool), + /// An integer. + Int(i64), + /// A floating point number. + Float(f64), + /// A character. + Char(u8), + /// A string, not necessarily well-formed utf-8. + String(Vec), +} + +/// A `Var` is our intermediate representation of a variable. +#[derive(Debug)] +pub struct Var { + /// The name of the variable. + name: String, + /// The mangled name of the variable. + mangled_name: Option, + /// The type of the variable. + ty: ItemId, + /// The value of the variable, that needs to be suitable for `ty`. + val: Option, + /// Whether this variable is const. + is_const: bool, +} + +impl Var { + /// Construct a new `Var`. + pub fn new(name: String, + mangled: Option, + ty: ItemId, + val: Option, + is_const: bool) + -> Var { + assert!(!name.is_empty()); + Var { + name: name, + mangled_name: mangled, + ty: ty, + val: val, + is_const: is_const, + } + } + + /// Is this variable `const` qualified? + pub fn is_const(&self) -> bool { + self.is_const + } + + /// The value of this constant variable, if any. + pub fn val(&self) -> Option<&VarType> { + self.val.as_ref() + } + + /// Get this variable's type. + pub fn ty(&self) -> ItemId { + self.ty + } + + /// Get this variable's name. + pub fn name(&self) -> &str { + &self.name + } + + /// Get this variable's mangled name. + pub fn mangled_name(&self) -> Option<&str> { + self.mangled_name.as_ref().map(|n| &**n) + } +} + +impl ClangSubItemParser for Var { + fn parse(cursor: clang::Cursor, + ctx: &mut BindgenContext) + -> Result, ParseError> { + use clang_sys::*; + use cexpr::expr::EvalResult; + use cexpr::literal::CChar; + match cursor.kind() { + CXCursor_MacroDefinition => { + let value = parse_macro(ctx, &cursor, ctx.translation_unit()); + + let (id, value) = match value { + Some(v) => v, + None => return Err(ParseError::Continue), + }; + + assert!(!id.is_empty(), "Empty macro name?"); + + let previously_defined = ctx.parsed_macro(&id); + + // NB: It's important to "note" the macro even if the result is + // not an integer, otherwise we might loose other kind of + // derived macros. + ctx.note_parsed_macro(id.clone(), value.clone()); + + if previously_defined { + let name = String::from_utf8(id).unwrap(); + warn!("Duplicated macro definition: {}", name); + return Err(ParseError::Continue); + } + + // NOTE: Unwrapping, here and above, is safe, because the + // identifier of a token comes straight from clang, and we + // enforce utf8 there, so we should have already panicked at + // this point. + let name = String::from_utf8(id).unwrap(); + let (type_kind, val) = match value { + EvalResult::Invalid => return Err(ParseError::Continue), + EvalResult::Float(f) => { + (TypeKind::Float(FloatKind::Float), VarType::Float(f)) + } + EvalResult::Char(c) => { + let c = match c { + CChar::Char(c) => { + assert_eq!(c.len_utf8(), 1); + c as u8 + } + CChar::Raw(c) => { + assert!(c <= ::std::u8::MAX as u64); + c as u8 + } + }; + + (TypeKind::Int(IntKind::U8), VarType::Char(c)) + } + EvalResult::Str(val) => { + let char_ty = + Item::builtin_type(TypeKind::Int(IntKind::U8), + true, + ctx); + (TypeKind::Pointer(char_ty), VarType::String(val)) + } + EvalResult::Int(Wrapping(value)) => { + let kind = ctx.type_chooser() + .and_then(|c| c.int_macro(&name, value)) + .unwrap_or_else(|| { + if value < 0 { + if value < i32::min_value() as i64 { + IntKind::LongLong + } else { + IntKind::Int + } + } else if value > u32::max_value() as i64 { + IntKind::ULongLong + } else { + IntKind::UInt + } + }); + + (TypeKind::Int(kind), VarType::Int(value)) + } + }; + + let ty = Item::builtin_type(type_kind, true, ctx); + + Ok(ParseResult::New(Var::new(name, None, ty, Some(val), true), + Some(cursor))) + } + CXCursor_VarDecl => { + let name = cursor.spelling(); + if name.is_empty() { + warn!("Empty constant name?"); + return Err(ParseError::Continue); + } + + let ty = cursor.cur_type(); + + // XXX this is redundant, remove! + let is_const = ty.is_const(); + + let ty = match Item::from_ty(&ty, Some(cursor), None, ctx) { + Ok(ty) => ty, + Err(e) => { + assert_eq!(ty.kind(), CXType_Auto, + "Couldn't resolve constant type, and it \ + wasn't an nondeductible auto type!"); + return Err(e); + } + }; + + // Note: Ty might not be totally resolved yet, see + // tests/headers/inner_const.hpp + // + // That's fine because in that case we know it's not a literal. + let canonical_ty = ctx.safe_resolve_type(ty) + .and_then(|t| t.safe_canonical_type(ctx)); + + let is_integer = canonical_ty.map_or(false, |t| t.is_integer()); + let is_float = canonical_ty.map_or(false, |t| t.is_float()); + + // TODO: We could handle `char` more gracefully. + // TODO: Strings, though the lookup is a bit more hard (we need + // to look at the canonical type of the pointee too, and check + // is char, u8, or i8 I guess). + let value = if is_integer { + let kind = match *canonical_ty.unwrap().kind() { + TypeKind::Int(kind) => kind, + _ => unreachable!(), + }; + + let mut val = cursor.evaluate() + .and_then(|v| v.as_int()) + .map(|val| val as i64); + if val.is_none() || !kind.signedness_matches(val.unwrap()) { + let tu = ctx.translation_unit(); + val = get_integer_literal_from_cursor(&cursor, tu); + } + + val.map(|val| { + if kind == IntKind::Bool { + VarType::Bool(val != 0) + } else { + VarType::Int(val) + } + }) + } else if is_float { + cursor.evaluate() + .and_then(|v| v.as_double()) + .map(VarType::Float) + } else { + cursor.evaluate() + .and_then(|v| v.as_literal_string()) + .map(VarType::String) + }; + + let mangling = cursor_mangling(&cursor); + let var = Var::new(name, mangling, ty, value, is_const); + + Ok(ParseResult::New(var, Some(cursor))) + } + _ => { + /* TODO */ + Err(ParseError::Continue) + } + } + } +} + +/// Try and parse a macro using all the macros parsed until now. +fn parse_macro(ctx: &BindgenContext, + cursor: &clang::Cursor, + unit: &clang::TranslationUnit) + -> Option<(Vec, cexpr::expr::EvalResult)> { + use cexpr::{expr, nom}; + + let cexpr_tokens = match unit.cexpr_tokens(cursor) { + None => return None, + Some(tokens) => tokens, + }; + + let parser = expr::IdentifierParser::new(ctx.parsed_macros()); + let result = parser.macro_definition(&cexpr_tokens); + + match result { + nom::IResult::Done(_, (id, val)) => Some((id.into(), val)), + _ => None, + } +} + +fn parse_int_literal_tokens(cursor: &clang::Cursor, + unit: &clang::TranslationUnit) + -> Option { + use cexpr::{expr, nom}; + use cexpr::expr::EvalResult; + + let cexpr_tokens = match unit.cexpr_tokens(cursor) { + None => return None, + Some(tokens) => tokens, + }; + + // TODO(emilio): We can try to parse other kinds of literals. + match expr::expr(&cexpr_tokens) { + nom::IResult::Done(_, EvalResult::Int(Wrapping(val))) => Some(val), + _ => None, + } +} + +fn get_integer_literal_from_cursor(cursor: &clang::Cursor, + unit: &clang::TranslationUnit) + -> Option { + use clang_sys::*; + let mut value = None; + cursor.visit(|c| { + match c.kind() { + CXCursor_IntegerLiteral | + CXCursor_UnaryOperator => { + value = parse_int_literal_tokens(&c, unit); + } + CXCursor_UnexposedExpr => { + value = get_integer_literal_from_cursor(&c, unit); + } + _ => (), + } + if value.is_some() { + CXChildVisit_Break + } else { + CXChildVisit_Continue + } + }); + value +} diff --git a/bash-5.1/vendor/bindgen/src/lib.rs b/bash-5.1/vendor/bindgen/src/lib.rs new file mode 100644 index 0000000..dabab15 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/lib.rs @@ -0,0 +1,868 @@ +//! Generate Rust bindings for C and C++ libraries. +//! +//! Provide a C/C++ header file, receive Rust FFI code to call into C/C++ +//! functions and use types defined in the header. +//! +//! See the [Builder](./struct.Builder.html) struct for usage. + +#![deny(missing_docs)] +#![deny(warnings)] +#![deny(unused_extern_crates)] + +// We internally use the deprecated BindgenOptions all over the place. Once we +// remove its `pub` declaration, we can un-deprecate it and remove this pragma. +#![allow(deprecated)] + +// To avoid rather annoying warnings when matching with CXCursor_xxx as a +// constant. +#![allow(non_upper_case_globals)] + +#[macro_use] +#[allow(unused_extern_crates)] +extern crate cfg_if; +extern crate cexpr; +extern crate syntex_syntax as syntax; +extern crate aster; +extern crate quasi; +extern crate clang_sys; +extern crate regex; +#[macro_use] +extern crate lazy_static; + +#[cfg(feature = "logging")] +#[macro_use] +extern crate log; + +#[cfg(not(feature = "logging"))] +#[macro_use] +mod log_stubs; + +// A macro to declare an internal module for which we *must* provide +// documentation for. If we are building with the "docs_" feature, then the +// module is declared public, and our `#![deny(missing_docs)]` pragma applies to +// it. This feature is used in CI, so we won't let anything slip by +// undocumented. Normal builds, however, will leave the module private, so that +// we don't expose internals to library consumers. +macro_rules! doc_mod { + ($m:ident, $doc_mod_name:ident) => { + cfg_if! { + if #[cfg(feature = "docs_")] { + pub mod $doc_mod_name { + //! Autogenerated documentation module. + pub use super::$m::*; + } + } else { + } + } + }; +} + +mod clang; +mod ir; +mod parse; +mod regex_set; +mod uses; + +pub mod chooser; + +#[cfg(rustfmt)] +mod codegen; + +doc_mod!(clang, clang_docs); +doc_mod!(ir, ir_docs); +doc_mod!(parse, parse_docs); +doc_mod!(regex_set, regex_set_docs); +doc_mod!(uses, uses_docs); + +mod codegen { + include!(concat!(env!("OUT_DIR"), "/codegen.rs")); +} + +use ir::context::{BindgenContext, ItemId}; +use ir::item::Item; +use parse::{ClangItemParser, ParseError}; +use regex_set::RegexSet; + +use std::fs::OpenOptions; +use std::io::{self, Write}; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Span}; +use syntax::print::pp::eof; +use syntax::print::pprust; +use syntax::ptr::P; + +/// A type used to indicate which kind of items do we have to generate. +/// +/// TODO(emilio): Use `bitflags!` +#[derive(Debug, Clone)] +pub struct CodegenConfig { + /// Whether to generate functions. + pub functions: bool, + /// Whether to generate types. + pub types: bool, + /// Whether to generate constants. + pub vars: bool, + /// Whether to generate methods. + pub methods: bool, + /// Whether to generate constructors. + pub constructors: bool, +} + +impl CodegenConfig { + /// Generate all kinds of items. + pub fn all() -> Self { + CodegenConfig { + functions: true, + types: true, + vars: true, + methods: true, + constructors: true, + } + } + + /// Generate nothing. + pub fn nothing() -> Self { + CodegenConfig { + functions: false, + types: false, + vars: false, + methods: false, + constructors: false, + } + } +} + +impl Default for CodegenConfig { + fn default() -> Self { + CodegenConfig::all() + } +} + +/// Configure and generate Rust bindings for a C/C++ header. +/// +/// This is the main entry point to the library. +/// +/// ```ignore +/// use bindgen::builder; +/// +/// // Configure and generate bindings. +/// let bindings = try!(builder().header("path/to/input/header") +/// .whitelisted_type("SomeCoolClass") +/// .whitelisted_function("do_some_cool_thing") +/// .generate()); +/// +/// // Write the generated bindings to an output file. +/// try!(bindings.write_to_file("path/to/output.rs")); +/// ``` +#[derive(Debug,Default)] +pub struct Builder { + options: BindgenOptions, +} + +/// Construct a new [`Builder`](./struct.Builder.html). +pub fn builder() -> Builder { + Default::default() +} + +impl Builder { + /// Set the input C/C++ header. + pub fn header>(mut self, header: T) -> Builder { + let header = header.into(); + self.options.input_header = Some(header); + self + } + + /// Whether the generated bindings should contain documentation comments or + /// not. + /// + /// This ideally will always be true, but it may need to be false until we + /// implement some processing on comments to work around issues as described + /// in: + /// + /// https://github.com/servo/rust-bindgen/issues/426 + pub fn generate_comments(mut self, doit: bool) -> Self { + self.options.generate_comments = doit; + self + } + + /// Whether to whitelist types recursively or not. Defaults to true. + /// + /// This can be used to get bindgen to generate _exactly_ the types you want + /// in your bindings, and then import other types manually via other means + /// (like `raw_line`). + pub fn whitelist_recursively(mut self, doit: bool) -> Self { + self.options.whitelist_recursively = doit; + self + } + + /// Generate a C/C++ file that includes the header and has dummy uses of + /// every type defined in the header. + pub fn dummy_uses>(mut self, dummy_uses: T) -> Builder { + self.options.dummy_uses = Some(dummy_uses.into()); + self + } + + /// Hide the given type from the generated bindings. Regular expressions are + /// supported. + pub fn hide_type>(mut self, arg: T) -> Builder { + self.options.hidden_types.insert(arg); + self + } + + /// Treat the given type as opaque in the generated bindings. Regular + /// expressions are supported. + pub fn opaque_type>(mut self, arg: T) -> Builder { + self.options.opaque_types.insert(arg); + self + } + + /// Whitelist the given type so that it (and all types that it transitively + /// refers to) appears in the generated bindings. Regular expressions are + /// supported. + pub fn whitelisted_type>(mut self, arg: T) -> Builder { + self.options.whitelisted_types.insert(arg); + self + } + + /// Whitelist the given function so that it (and all types that it + /// transitively refers to) appears in the generated bindings. Regular + /// expressions are supported. + pub fn whitelisted_function>(mut self, arg: T) -> Builder { + self.options.whitelisted_functions.insert(arg); + self + } + + /// Whitelist the given variable so that it (and all types that it + /// transitively refers to) appears in the generated bindings. Regular + /// expressions are supported. + pub fn whitelisted_var>(mut self, arg: T) -> Builder { + self.options.whitelisted_vars.insert(arg); + self + } + + /// Mark the given enum (or set of enums, if using a pattern) as being + /// bitfield-like. Regular expressions are supported. + /// + /// This makes bindgen generate a type that isn't a rust `enum`. Regular + /// expressions are supported. + pub fn bitfield_enum>(mut self, arg: T) -> Builder { + self.options.bitfield_enums.insert(arg); + self + } + + /// Mark the given enum (or set of enums, if using a pattern) as being + /// constant. + /// + /// This makes bindgen generate constants instead of enums. Regular + /// expressions are supported. + pub fn constified_enum>(mut self, arg: T) -> Builder { + self.options.constified_enums.insert(arg); + self + } + + /// Add a string to prepend to the generated bindings. The string is passed + /// through without any modification. + pub fn raw_line>(mut self, arg: T) -> Builder { + self.options.raw_lines.push(arg.into()); + self + } + + /// Add an argument to be passed straight through to clang. + pub fn clang_arg>(mut self, arg: T) -> Builder { + self.options.clang_args.push(arg.into()); + self + } + + /// Make the generated bindings link the given shared library. + pub fn link>(mut self, library: T) -> Builder { + self.options.links.push((library.into(), LinkType::Default)); + self + } + + /// Make the generated bindings link the given static library. + pub fn link_static>(mut self, library: T) -> Builder { + self.options.links.push((library.into(), LinkType::Static)); + self + } + + /// Make the generated bindings link the given framework. + pub fn link_framework>(mut self, library: T) -> Builder { + self.options.links.push((library.into(), LinkType::Framework)); + self + } + + /// Emit bindings for builtin definitions (for example `__builtin_va_list`) + /// in the generated Rust. + pub fn emit_builtins(mut self) -> Builder { + self.options.builtins = true; + self + } + + /// Avoid converting floats to f32/f64 by default. + pub fn no_convert_floats(mut self) -> Self { + self.options.convert_floats = false; + self + } + + /// Set whether `Debug` should be derived by default. + pub fn derive_debug(mut self, doit: bool) -> Self { + self.options.derive_debug = doit; + self + } + + /// Emit Clang AST. + pub fn emit_clang_ast(mut self) -> Builder { + self.options.emit_ast = true; + self + } + + /// Emit IR. + pub fn emit_ir(mut self) -> Builder { + self.options.emit_ir = true; + self + } + + /// Enable C++ namespaces. + pub fn enable_cxx_namespaces(mut self) -> Builder { + self.options.enable_cxx_namespaces = true; + self + } + + /// Disable auto-namespacing of names if namespaces are disabled. + /// + /// By default, if namespaces are disabled, bindgen tries to mangle the + /// names to from `foo::bar::Baz` to look like `foo_bar_Baz`, instead of + /// just `Baz`. + /// + /// This option disables that behavior. + /// + /// Note that this intentionally doesn't change the names using for + /// whitelisting and blacklisting, that should still be mangled with the + /// namespaces. + /// + /// Note, also, that using this option may cause duplicated names to be + /// generated. + pub fn disable_name_namespacing(mut self) -> Builder { + self.options.disable_name_namespacing = true; + self + } + + /// Treat inline namespaces conservatively. + /// + /// This is tricky, because in C++ is technically legal to override an item + /// defined in an inline namespace: + /// + /// ```cpp + /// inline namespace foo { + /// using Bar = int; + /// } + /// using Bar = long; + /// ``` + /// + /// Even though referencing `Bar` is a compiler error. + /// + /// We want to support this (arguably esoteric) use case, but we don't want + /// to make the rest of bindgen users pay an usability penalty for that. + /// + /// To support this, we need to keep all the inline namespaces around, but + /// then bindgen usage is a bit more difficult, because you cannot + /// reference, e.g., `std::string` (you'd need to use the proper inline + /// namespace). + /// + /// We could complicate a lot of the logic to detect name collisions, and if + /// not detected generate a `pub use inline_ns::*` or something like that. + /// + /// That's probably something we can do if we see this option is needed in a + /// lot of cases, to improve it's usability, but my guess is that this is + /// not going to be too useful. + pub fn conservative_inline_namespaces(mut self) -> Builder { + self.options.conservative_inline_namespaces = true; + self + } + + /// Ignore functions. + pub fn ignore_functions(mut self) -> Builder { + self.options.codegen_config.functions = false; + self + } + + /// Ignore methods. + pub fn ignore_methods(mut self) -> Builder { + self.options.codegen_config.methods = false; + self + } + + /// Avoid generating any unstable Rust, such as Rust unions, in the generated bindings. + pub fn no_unstable_rust(mut self) -> Builder { + self.options.unstable_rust = false; + self + } + + /// Use core instead of libstd in the generated bindings. + pub fn use_core(mut self) -> Builder { + self.options.use_core = true; + self + } + + /// Use the given prefix for the raw types instead of `::std::os::raw`. + pub fn ctypes_prefix>(mut self, prefix: T) -> Builder { + self.options.ctypes_prefix = Some(prefix.into()); + self + } + + /// Allows configuring types in different situations, see the `TypeChooser` + /// documentation. + pub fn type_chooser(mut self, cb: Box) -> Self { + self.options.type_chooser = Some(cb); + self + } + + /// Choose what to generate using a CodegenConfig. + pub fn with_codegen_config(mut self, config: CodegenConfig) -> Self { + self.options.codegen_config = config; + self + } + + /// Generate the Rust bindings using the options built up thus far. + pub fn generate<'ctx>(self) -> Result, ()> { + Bindings::generate(self.options, None) + } +} + +/// Configuration options for generated bindings. +/// +/// Deprecated: use a `Builder` instead. +#[derive(Debug)] +#[deprecated] +pub struct BindgenOptions { + /// The set of types that have been blacklisted and should not appear + /// anywhere in the generated code. + pub hidden_types: RegexSet, + + /// The set of types that should be treated as opaque structures in the + /// generated code. + pub opaque_types: RegexSet, + + /// The set of types that we should have bindings for in the generated + /// code. + /// + /// This includes all types transitively reachable from any type in this + /// set. One might think of whitelisted types/vars/functions as GC roots, + /// and the generated Rust code as including everything that gets marked. + pub whitelisted_types: RegexSet, + + /// Whitelisted functions. See docs for `whitelisted_types` for more. + pub whitelisted_functions: RegexSet, + + /// Whitelisted variables. See docs for `whitelisted_types` for more. + pub whitelisted_vars: RegexSet, + + /// The enum patterns to mark an enum as bitfield. + pub bitfield_enums: RegexSet, + + /// The enum patterns to mark an enum as constant. + pub constified_enums: RegexSet, + + /// Whether we should generate builtins or not. + pub builtins: bool, + + /// The set of libraries we should link in the generated Rust code. + pub links: Vec<(String, LinkType)>, + + /// True if we should dump the Clang AST for debugging purposes. + pub emit_ast: bool, + + /// True if we should dump our internal IR for debugging purposes. + pub emit_ir: bool, + + /// True if we should emulate C++ namespaces with Rust modules in the + /// generated bindings. + pub enable_cxx_namespaces: bool, + + /// True if we should avoid mangling names with namespaces. + pub disable_name_namespacing: bool, + + /// True if we shold derive Debug trait implementations for C/C++ structures + /// and types. + pub derive_debug: bool, + + /// True if we can use unstable Rust code in the bindings, false if we + /// cannot. + pub unstable_rust: bool, + + /// True if we should avoid using libstd to use libcore instead. + pub use_core: bool, + + /// An optional prefix for the "raw" types, like `c_int`, `c_void`... + pub ctypes_prefix: Option, + + /// True if we should generate constant names that are **directly** under + /// namespaces. + pub namespaced_constants: bool, + + /// True if we should use MSVC name mangling rules. + pub msvc_mangling: bool, + + /// Whether we should convert float types to f32/f64 types. + pub convert_floats: bool, + + /// The set of raw lines to prepend to the generated Rust code. + pub raw_lines: Vec, + + /// The set of arguments to pass straight through to Clang. + pub clang_args: Vec, + + /// The input header file. + pub input_header: Option, + + + /// Generate a dummy C/C++ file that includes the header and has dummy uses + /// of all types defined therein. See the `uses` module for more. + pub dummy_uses: Option, + + /// A user-provided type chooser to allow customizing different kinds of + /// situations. + pub type_chooser: Option>, + + /// Which kind of items should we generate? By default, we'll generate all + /// of them. + pub codegen_config: CodegenConfig, + + /// Whether to treat inline namespaces conservatively. + /// + /// See the builder method description for more details. + pub conservative_inline_namespaces: bool, + + /// Wether to keep documentation comments in the generated output. See the + /// documentation for more details. + pub generate_comments: bool, + + /// Wether to whitelist types recursively. Defaults to true. + pub whitelist_recursively: bool, +} + +impl BindgenOptions { + fn build(&mut self) { + self.whitelisted_vars.build(); + self.whitelisted_types.build(); + self.whitelisted_functions.build(); + self.hidden_types.build(); + self.opaque_types.build(); + self.bitfield_enums.build(); + self.constified_enums.build(); + } +} + +impl Default for BindgenOptions { + fn default() -> BindgenOptions { + BindgenOptions { + hidden_types: Default::default(), + opaque_types: Default::default(), + whitelisted_types: Default::default(), + whitelisted_functions: Default::default(), + whitelisted_vars: Default::default(), + bitfield_enums: Default::default(), + constified_enums: Default::default(), + builtins: false, + links: vec![], + emit_ast: false, + emit_ir: false, + derive_debug: true, + enable_cxx_namespaces: false, + disable_name_namespacing: false, + unstable_rust: true, + use_core: false, + ctypes_prefix: None, + namespaced_constants: true, + msvc_mangling: false, + convert_floats: true, + raw_lines: vec![], + clang_args: vec![], + input_header: None, + dummy_uses: None, + type_chooser: None, + codegen_config: CodegenConfig::all(), + conservative_inline_namespaces: false, + generate_comments: true, + whitelist_recursively: true, + } + } +} + +/// The linking type to use with a given library. +/// +/// TODO: #104: This is ignored at the moment, but shouldn't be. +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum LinkType { + /// Use shared library linking. This is the default. + Default, + /// Use static linking. + Static, + /// The library is an OSX framework. + Framework, +} + +fn ensure_libclang_is_loaded() { + if clang_sys::is_loaded() { + return; + } + + // XXX (issue #350): Ensure that our dynamically loaded `libclang` + // doesn't get dropped prematurely, nor is loaded multiple times + // across different threads. + + lazy_static! { + static ref LIBCLANG: Mutex>> = { + Mutex::new(None) + }; + } + + let mut libclang = LIBCLANG.lock().unwrap(); + if !clang_sys::is_loaded() { + if libclang.is_none() { + // TODO(emilio): Return meaningful error (breaking). + clang_sys::load().expect("Unable to find libclang"); + *libclang = Some(clang_sys::get_library() + .expect("We just loaded libclang and it had \ + better still be here!")); + } else { + clang_sys::set_library(libclang.clone()); + } + } +} + +/// Generated Rust bindings. +#[derive(Debug)] +pub struct Bindings<'ctx> { + context: BindgenContext<'ctx>, + module: ast::Mod, +} + +impl<'ctx> Bindings<'ctx> { + /// Generate bindings for the given options. + /// + /// Deprecated - use a `Builder` instead + #[deprecated] + pub fn generate(mut options: BindgenOptions, + span: Option) + -> Result, ()> { + let span = span.unwrap_or(DUMMY_SP); + ensure_libclang_is_loaded(); + + options.build(); + + // TODO: Make this path fixup configurable? + if let Some(clang) = clang_sys::support::Clang::find(None) { + // If --target is specified, assume caller knows what they're doing + // and don't mess with include paths for them + let has_target_arg = options.clang_args + .iter() + .rposition(|arg| arg.starts_with("--target")) + .is_some(); + if !has_target_arg { + // TODO: distinguish C and C++ paths? C++'s should be enough, I + // guess. + for path in clang.cpp_search_paths.into_iter() { + if let Ok(path) = path.into_os_string().into_string() { + options.clang_args.push("-isystem".to_owned()); + options.clang_args.push(path); + } + } + } + } + + if let Some(h) = options.input_header.as_ref() { + options.clang_args.push(h.clone()) + } + + let mut context = BindgenContext::new(options); + try!(parse(&mut context)); + + let module = ast::Mod { + inner: span, + items: codegen::codegen(&mut context), + }; + + Ok(Bindings { + context: context, + module: module, + }) + } + + /// Convert these bindings into a Rust AST. + pub fn into_ast(self) -> Vec> { + self.module.items + } + + /// Convert these bindings into source text (with raw lines prepended). + pub fn to_string(&self) -> String { + let mut mod_str = vec![]; + { + let ref_writer = Box::new(mod_str.by_ref()) as Box; + self.write(ref_writer).expect("Could not write bindings to string"); + } + String::from_utf8(mod_str).unwrap() + } + + /// Write these bindings as source text to a file. + pub fn write_to_file>(&self, path: P) -> io::Result<()> { + let file = try!(OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(path)); + self.write(Box::new(file)) + } + + /// Write these bindings as source text to the given `Write`able. + pub fn write<'a>(&self, mut writer: Box) -> io::Result<()> { + try!(writer.write("/* automatically generated by rust-bindgen */\n\n" + .as_bytes())); + + for line in self.context.options().raw_lines.iter() { + try!(writer.write(line.as_bytes())); + try!(writer.write("\n".as_bytes())); + } + if !self.context.options().raw_lines.is_empty() { + try!(writer.write("\n".as_bytes())); + } + + let mut ps = pprust::rust_printer(writer); + try!(ps.print_mod(&self.module, &[])); + try!(ps.print_remaining_comments()); + try!(eof(&mut ps.s)); + ps.s.out.flush() + } + + /// Generate and write dummy uses of all the types we parsed, if we've been + /// requested to do so in the options. + /// + /// See the `uses` module for more information. + pub fn write_dummy_uses(&mut self) -> io::Result<()> { + let file = + if let Some(ref dummy_path) = self.context.options().dummy_uses { + Some(try!(OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(dummy_path))) + } else { + None + }; + + if let Some(file) = file { + try!(uses::generate_dummy_uses(&mut self.context, file)); + } + + Ok(()) + } +} + +/// Determines whether the given cursor is in any of the files matched by the +/// options. +fn filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool { + let (file, _, _, _) = cursor.location().location(); + + match file.name() { + None => ctx.options().builtins, + Some(..) => true, + } +} + +/// Parse one `Item` from the Clang cursor. +pub fn parse_one(ctx: &mut BindgenContext, + cursor: clang::Cursor, + parent: Option) + -> clang_sys::CXChildVisitResult { + if !filter_builtins(ctx, &cursor) { + return CXChildVisit_Continue; + } + + use clang_sys::CXChildVisit_Continue; + match Item::parse(cursor, parent, ctx) { + Ok(..) => {} + Err(ParseError::Continue) => {} + Err(ParseError::Recurse) => { + cursor.visit(|child| parse_one(ctx, child, parent)); + } + } + CXChildVisit_Continue +} + +/// Parse the Clang AST into our `Item` internal representation. +fn parse(context: &mut BindgenContext) -> Result<(), ()> { + use clang_sys::*; + + let mut any_error = false; + for d in context.translation_unit().diags().iter() { + let msg = d.format(); + let is_err = d.severity() >= CXDiagnostic_Error; + println!("{}, err: {}", msg, is_err); + any_error |= is_err; + } + + if any_error { + return Err(()); + } + + let cursor = context.translation_unit().cursor(); + if context.options().emit_ast { + cursor.visit(|cur| clang::ast_dump(&cur, 0)); + } + + let root = context.root_module(); + context.with_module(root, |context| { + cursor.visit(|cursor| parse_one(context, cursor, None)) + }); + + assert!(context.current_module() == context.root_module(), + "How did this happen?"); + Ok(()) +} + +/// Extracted Clang version data +#[derive(Debug)] +pub struct ClangVersion { + /// Major and minor semvar, if parsing was successful + pub parsed: Option<(u32, u32)>, + /// full version string + pub full: String, +} + +/// Get the major and the minor semvar numbers of Clang's version +pub fn clang_version() -> ClangVersion { + if !clang_sys::is_loaded() { + // TODO(emilio): Return meaningful error (breaking). + clang_sys::load().expect("Unable to find libclang"); + } + + let raw_v: String = clang::extract_clang_version(); + let split_v: Option> = raw_v.split_whitespace() + .nth(2) + .map(|v| v.split('.').collect()); + match split_v { + Some(v) => { + if v.len() >= 2 { + let maybe_major = v[0].parse::(); + let maybe_minor = v[1].parse::(); + match (maybe_major, maybe_minor) { + (Ok(major), Ok(minor)) => { + return ClangVersion { + parsed: Some((major, minor)), + full: raw_v.clone(), + } + } + _ => {} + } + } + } + None => {} + }; + ClangVersion { + parsed: None, + full: raw_v.clone(), + } +} diff --git a/bash-5.1/vendor/bindgen/src/log_stubs.rs b/bash-5.1/vendor/bindgen/src/log_stubs.rs new file mode 100644 index 0000000..4262e12 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/log_stubs.rs @@ -0,0 +1,30 @@ +macro_rules! log { + (target: $target:expr, $lvl:expr, $($arg)+) => { + let _ = $target; + let _ = log!($lvl, $($arg)+); + }; + ($lvl:expr, $($arg:tt)+) => { + let _ = $lvl; + let _ = format_args!($($arg)+); + }; +} +macro_rules! error { + (target: $target:expr, $($arg:tt)*) => { log!($target, $($arg)*); }; + ($($arg:tt)*) => { log!("", $($arg)*); }; +} +macro_rules! warn { + (target: $target:expr, $($arg:tt)*) => { log!($target, $($arg)*); }; + ($($arg:tt)*) => { log!("", $($arg)*); }; +} +macro_rules! info { + (target: $target:expr, $($arg:tt)*) => { log!($target, $($arg)*); }; + ($($arg:tt)*) => { log!("", $($arg)*); }; +} +macro_rules! debug { + (target: $target:expr, $($arg:tt)*) => { log!($target, $($arg)*); }; + ($($arg:tt)*) => { log!("", $($arg)*); }; +} +macro_rules! trace { + (target: $target:expr, $($arg:tt)*) => { log!($target, $($arg)*); }; + ($($arg:tt)*) => { log!("", $($arg)*); }; +} diff --git a/bash-5.1/vendor/bindgen/src/main.rs b/bash-5.1/vendor/bindgen/src/main.rs new file mode 100644 index 0000000..a7bd961 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/main.rs @@ -0,0 +1,59 @@ +extern crate bindgen; +extern crate env_logger; +#[macro_use] +extern crate log; +extern crate clang_sys; +extern crate clap; +extern crate rustc_serialize; + +use bindgen::clang_version; +use std::env; + +mod options; +use options::builder_from_flags; + +pub fn main() { + log::set_logger(|max_log_level| { + use env_logger::Logger; + let env_logger = Logger::new(); + max_log_level.set(env_logger.filter()); + Box::new(env_logger) + }) + .expect("Failed to set logger."); + + let bind_args: Vec<_> = env::args().collect(); + + let version = clang_version(); + let expected_version = if cfg!(feature = "llvm_stable") { + (3, 8) + } else { + (3, 9) + }; + + info!("Clang Version: {}", version.full); + + match version.parsed { + None => warn!("Couldn't parse libclang version"), + Some(version) if version != expected_version => { + warn!("Using clang {:?}, expected {:?}", + version, + expected_version); + } + _ => {} + } + + match builder_from_flags(bind_args.into_iter()) { + Ok((builder, output)) => { + let mut bindings = builder.generate() + .expect("Unable to generate bindings"); + bindings.write(output) + .expect("Unable to write output"); + bindings.write_dummy_uses() + .expect("Unable to write dummy uses to file."); + } + Err(error) => { + println!("{}", error); + std::process::exit(1); + } + }; +} diff --git a/bash-5.1/vendor/bindgen/src/options.rs b/bash-5.1/vendor/bindgen/src/options.rs new file mode 100644 index 0000000..307ea6b --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/options.rs @@ -0,0 +1,347 @@ +use clap::{App, Arg}; +use bindgen::{Builder, CodegenConfig, builder}; +use std::fs::File; +use std::io::{self, Error, ErrorKind}; + +/// Construct a new [`Builder`](./struct.Builder.html) from command line flags. +pub fn builder_from_flags(args: I) + -> Result<(Builder, Box), io::Error> + where I: Iterator, +{ + let matches = App::new("bindgen") + .version(env!("CARGO_PKG_VERSION")) + .about("Generates Rust bindings from C/C++ headers.") + .usage("bindgen [FLAGS] [OPTIONS]
-- ...") + .args(&[ + Arg::with_name("header") + .help("C or C++ header file") + .required(true), + Arg::with_name("bitfield-enum") + .long("bitfield-enum") + .help("Mark any enum whose name matches as a set of \ + bitfield flags instead of an enumeration.") + .value_name("regex") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("constified-enum") + .long("constified-enum") + .help("Mark any enum whose name matches as a set of \ + constants instead of an enumeration.") + .value_name("regex") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("blacklist-type") + .long("blacklist-type") + .help("Mark a type as hidden.") + .value_name("type") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("no-derive-debug") + .long("no-derive-debug") + .help("Avoid deriving Debug on any type."), + Arg::with_name("no-doc-comments") + .long("no-doc-comments") + .help("Avoid including doc comments in the output, see: \ + https://github.com/servo/rust-bindgen/issues/426"), + Arg::with_name("no-recursive-whitelist") + .long("no-recursive-whitelist") + .help("Avoid whitelisting types recursively"), + Arg::with_name("builtins") + .long("builtins") + .help("Output bindings for builtin definitions, e.g. \ + __builtin_va_list."), + Arg::with_name("ctypes-prefix") + .long("ctypes-prefix") + .help("Use the given prefix before raw types instead of \ + ::std::os::raw.") + .value_name("prefix") + .takes_value(true), + // All positional arguments after the end of options marker, `--` + Arg::with_name("clang-args") + .multiple(true), + Arg::with_name("dummy-uses") + .long("dummy-uses") + .help("For testing purposes, generate a C/C++ file containing \ + dummy uses of all types defined in the input header.") + .takes_value(true), + Arg::with_name("emit-clang-ast") + .long("emit-clang-ast") + .help("Output the Clang AST for debugging purposes."), + Arg::with_name("emit-ir") + .long("emit-ir") + .help("Output our internal IR for debugging purposes."), + Arg::with_name("enable-cxx-namespaces") + .long("enable-cxx-namespaces") + .help("Enable support for C++ namespaces."), + Arg::with_name("disable-name-namespacing") + .long("disable-name-namespacing") + .help("Disable name namespacing if namespaces are disabled."), + Arg::with_name("framework") + .long("framework-link") + .help("Link to framework.") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("ignore-functions") + .long("ignore-functions") + .help("Do not generate bindings for functions or methods. This \ + is useful when you only care about struct layouts."), + Arg::with_name("generate") + .long("generate") + .help("Generate a given kind of items, split by commas. \ + Valid values are \"functions\",\"types\", \"vars\" and \ + \"methods\".") + .takes_value(true), + Arg::with_name("ignore-methods") + .long("ignore-methods") + .help("Do not generate bindings for methods."), + Arg::with_name("dynamic") + .short("l") + .long("link") + .help("Link to dynamic library.") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("no-convert-floats") + .long("no-convert-floats") + .help("Don't automatically convert floats to f32/f64."), + Arg::with_name("no-unstable-rust") + .long("no-unstable-rust") + .help("Do not generate unstable Rust code.") + .multiple(true), // FIXME: Pass legacy test suite + Arg::with_name("opaque-type") + .long("opaque-type") + .help("Mark a type as opaque.") + .value_name("type") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("output") + .short("o") + .long("output") + .help("Write Rust bindings to .") + .takes_value(true), + Arg::with_name("raw-line") + .long("raw-line") + .help("Add a raw line of Rust code at the beginning of output.") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("static") + .long("static-link") + .help("Link to static library.") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("use-core") + .long("use-core") + .help("Use types from Rust core instead of std."), + Arg::with_name("conservative-inline-namespaces") + .long("conservative-inline-namespaces") + .help("Conservatively generate inline namespaces to avoid name \ + conflicts."), + Arg::with_name("use-msvc-mangling") + .long("use-msvc-mangling") + .help("MSVC C++ ABI mangling. DEPRECATED: Has no effect."), + Arg::with_name("whitelist-function") + .long("whitelist-function") + .help("Whitelist all the free-standing functions matching \ + . Other non-whitelisted functions will not be \ + generated.") + .value_name("regex") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("whitelist-type") + .long("whitelist-type") + .help("Whitelist the type. Other non-whitelisted types will \ + not be generated.") + .value_name("type") + .takes_value(true) + .multiple(true) + .number_of_values(1), + Arg::with_name("whitelist-var") + .long("whitelist-var") + .help("Whitelist all the free-standing variables matching \ + . Other non-whitelisted variables will not be \ + generated.") + .value_name("regex") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ]) // .args() + .get_matches_from(args); + + let mut builder = builder(); + + if let Some(header) = matches.value_of("header") { + builder = builder.header(header); + } else { + return Err(Error::new(ErrorKind::Other, "Header not found")); + } + + if let Some(bitfields) = matches.values_of("bitfield-enum") { + for regex in bitfields { + builder = builder.bitfield_enum(regex); + } + } + + if let Some(bitfields) = matches.values_of("constified-enum") { + for regex in bitfields { + builder = builder.constified_enum(regex); + } + } + + if let Some(hidden_types) = matches.values_of("blacklist-type") { + for ty in hidden_types { + builder = builder.hide_type(ty); + } + } + + if matches.is_present("builtins") { + builder = builder.emit_builtins(); + } + + if matches.is_present("no-derive-debug") { + builder = builder.derive_debug(false); + } + + if let Some(prefix) = matches.value_of("ctypes-prefix") { + builder = builder.ctypes_prefix(prefix); + } + + if let Some(dummy) = matches.value_of("dummy-uses") { + builder = builder.dummy_uses(dummy); + } + + if let Some(links) = matches.values_of("dynamic") { + for library in links { + builder = builder.link(library); + } + } + + if let Some(what_to_generate) = matches.value_of("generate") { + let mut config = CodegenConfig::nothing(); + for what in what_to_generate.split(",") { + match what { + "functions" => config.functions = true, + "types" => config.types = true, + "vars" => config.vars = true, + "methods" => config.methods = true, + _ => { + return Err(Error::new(ErrorKind::Other, + "Unknown generate item")); + } + } + } + builder = builder.with_codegen_config(config); + } + + if matches.is_present("emit-clang-ast") { + builder = builder.emit_clang_ast(); + } + + if matches.is_present("emit-ir") { + builder = builder.emit_ir(); + } + + if matches.is_present("enable-cxx-namespaces") { + builder = builder.enable_cxx_namespaces(); + } + + if matches.is_present("disable-name-namespacing") { + builder = builder.disable_name_namespacing(); + } + + if let Some(links) = matches.values_of("framework") { + for framework in links { + builder = builder.link_framework(framework); + } + } + + if matches.is_present("ignore-functions") { + builder = builder.ignore_functions(); + } + + if matches.is_present("ignore-methods") { + builder = builder.ignore_methods(); + } + + if matches.is_present("no-unstable-rust") { + builder = builder.no_unstable_rust(); + } + + if matches.is_present("no-convert-floats") { + builder = builder.no_convert_floats(); + } + + if matches.is_present("no-doc-comments") { + builder = builder.generate_comments(false); + } + + if matches.is_present("no-recursive-whitelist") { + builder = builder.whitelist_recursively(false); + } + + if let Some(opaque_types) = matches.values_of("opaque-type") { + for ty in opaque_types { + builder = builder.opaque_type(ty); + } + } + + if let Some(lines) = matches.values_of("raw-line") { + for line in lines { + builder = builder.raw_line(line); + } + } + + if let Some(links) = matches.values_of("static") { + for library in links { + builder = builder.link_static(library); + } + } + + if matches.is_present("use-core") { + builder = builder.use_core(); + } + + if matches.is_present("conservative-inline-namespaces") { + builder = builder.conservative_inline_namespaces(); + } + + if let Some(whitelist) = matches.values_of("whitelist-function") { + for regex in whitelist { + builder = builder.whitelisted_function(regex); + } + } + + if let Some(whitelist) = matches.values_of("whitelist-type") { + for regex in whitelist { + builder = builder.whitelisted_type(regex); + } + } + + if let Some(whitelist) = matches.values_of("whitelist-var") { + for regex in whitelist { + builder = builder.whitelisted_var(regex); + } + } + + if let Some(args) = matches.values_of("clang-args") { + for arg in args { + builder = builder.clang_arg(arg); + } + } + + let output = if let Some(path) = matches.value_of("output") { + let file = try!(File::create(path)); + Box::new(io::BufWriter::new(file)) as Box + } else { + Box::new(io::BufWriter::new(io::stdout())) as Box + }; + + Ok((builder, output)) +} diff --git a/bash-5.1/vendor/bindgen/src/parse.rs b/bash-5.1/vendor/bindgen/src/parse.rs new file mode 100644 index 0000000..0e4164f --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/parse.rs @@ -0,0 +1,104 @@ +//! Common traits and types related to parsing our IR from Clang cursors. + +use clang; +use ir::context::{BindgenContext, ItemId}; +use ir::ty::TypeKind; + +/// Not so much an error in the traditional sense, but a control flow message +/// when walking over Clang's AST with a cursor. +#[derive(Debug)] +pub enum ParseError { + /// Recurse down the current AST node's children. + Recurse, + /// Continue on to the next sibling AST node, or back up to the parent's + /// siblings if we've exhausted all of this node's siblings (and so on). + Continue, +} + +/// The result of parsing a Clang AST node. +#[derive(Debug)] +pub enum ParseResult { + /// We've already resolved this item before, here is the extant `ItemId` for + /// it. + AlreadyResolved(ItemId), + + /// This is a newly parsed item. If the cursor is `Some`, it points to the + /// AST node where the new `T` was declared. + New(T, Option), +} + +/// An intermediate representation "sub-item" (i.e. one of the types contained +/// inside an `ItemKind` variant) that can be parsed from a Clang cursor. +pub trait ClangSubItemParser: Sized { + /// Attempt to parse this type from the given cursor. + /// + /// The fact that is a reference guarantees it's held by the context, and + /// allow returning already existing types. + fn parse(cursor: clang::Cursor, + context: &mut BindgenContext) + -> Result, ParseError>; +} + +/// An intermediate representation item that can be parsed from a Clang cursor. +pub trait ClangItemParser: Sized { + /// Parse this item from the given Clang cursor. + fn parse(cursor: clang::Cursor, + parent: Option, + context: &mut BindgenContext) + -> Result; + + /// Parse this item from the given Clang type. + fn from_ty(ty: &clang::Type, + location: Option, + parent: Option, + ctx: &mut BindgenContext) + -> Result; + + /// Identical to `from_ty`, but use the given `id` as the `ItemId` for the + /// newly parsed item. + fn from_ty_with_id(id: ItemId, + ty: &clang::Type, + location: Option, + parent: Option, + ctx: &mut BindgenContext) + -> Result; + + /// Parse this item from the given Clang type, or if we haven't resolved all + /// the other items this one depends on, an unresolved reference. + fn from_ty_or_ref(ty: clang::Type, + location: Option, + parent_id: Option, + context: &mut BindgenContext) + -> ItemId; + + /// Identical to `from_ty_or_ref`, but use the given `potential_id` as the + /// `ItemId` for the newly parsed item. + fn from_ty_or_ref_with_id(potential_id: ItemId, + ty: clang::Type, + location: Option, + parent_id: Option, + context: &mut BindgenContext) + -> ItemId; + + /// Create a named template type. + fn named_type(name: S, + parent: ItemId, + context: &mut BindgenContext) + -> ItemId + where S: Into; + + /// Identical to `named_type`, but use `id` as the resulting item's + /// `ItemId`. + fn named_type_with_id(id: ItemId, + name: S, + parent: ItemId, + context: &mut BindgenContext) + -> ItemId + where S: Into; + + /// Create a builtin type. + fn builtin_type(kind: TypeKind, + is_const: bool, + context: &mut BindgenContext) + -> ItemId; +} diff --git a/bash-5.1/vendor/bindgen/src/regex_set.rs b/bash-5.1/vendor/bindgen/src/regex_set.rs new file mode 100644 index 0000000..dbdb656 --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/regex_set.rs @@ -0,0 +1,69 @@ +//! A type that represents the union of a set of regular expressions. + +use regex::RegexSet as RxSet; + +// Yeah, I'm aware this is sorta crappy, should be cheaper to compile a regex +// ORing all the patterns, I guess... + +/// A dynamic set of regular expressions. +#[derive(Debug)] +pub struct RegexSet { + items: Vec, + set: Option, +} + +impl RegexSet { + /// Is this set empty? + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + /// Extend this set with every regex in the iterator. + pub fn extend(&mut self, iter: I) + where I: IntoIterator, + S: AsRef + { + for s in iter.into_iter() { + self.insert(s) + } + } + + /// Insert a new regex into this set. + pub fn insert(&mut self, string: S) + where S: AsRef + { + self.items.push(format!("^{}$", string.as_ref())); + self.set = None; + } + + /// Construct a RegexSet from the set of entries we've accumulated. + /// + /// Must be called before calling `matches()`, or it will always return + /// false. + pub fn build(&mut self) { + self.set = match RxSet::new(&self.items) { + Ok(x) => Some(x), + Err(e) => { + error!("Invalid regex in {:?}: {:?}", self.items, e); + None + }, + } + } + + /// Does the given `string` match any of the regexes in this set? + pub fn matches(&self, string: S) -> bool + where S: AsRef + { + let s = string.as_ref(); + self.set.as_ref().map(|set| set.is_match(s)).unwrap_or(false) + } +} + +impl Default for RegexSet { + fn default() -> Self { + RegexSet { + items: vec![], + set: None, + } + } +} diff --git a/bash-5.1/vendor/bindgen/src/uses.rs b/bash-5.1/vendor/bindgen/src/uses.rs new file mode 100644 index 0000000..47f72da --- /dev/null +++ b/bash-5.1/vendor/bindgen/src/uses.rs @@ -0,0 +1,102 @@ +//! Take in our IR and output a C/C++ file with dummy uses of each IR type. +//! +//! Say that we had this C++ header, `header.hpp`: +//! +//! ```c++ +//! class Point { +//! int x; +//! int y; +//! } +//! +//! enum Bar { +//! THIS, +//! THAT, +//! OTHER +//! } +//! ``` +//! +//! If we generated dummy uses for this header, we would get a `.cpp` file like +//! this: +//! +//! ```c++ +//! #include "header.hpp" +//! +//! void dummy(Point*) {} +//! void dummy(Bar*) {} +//! ``` +//! +//! This is useful because we can compile this `.cpp` file into an object file, +//! and then compare its debugging information to the debugging information +//! generated for our Rust bindings. These two sets of debugging information had +//! better agree on the C/C++ types' physical layout, or else our bindings are +//! incorrect! +//! +//! "But you still haven't explained why we have to generate the dummy uses" you +//! complain. Well if the types are never used, then they are elided when the +//! C/C++ compiler generates debugging information. + +use ir::context::BindgenContext; +use ir::item::{Item, ItemAncestors, ItemCanonicalName}; +use std::io; + +// Like `canonical_path`, except we always take namespaces into account, ignore +// the generated names of anonymous items, and return a `String`. +// +// TODO: Would it be easier to try and demangle the USR? +fn namespaced_name(ctx: &BindgenContext, item: &Item) -> String { + let mut names: Vec<_> = item.ancestors(ctx) + .map(|id| ctx.resolve_item(id).canonical_name(ctx)) + .filter(|name| !name.starts_with("_bindgen_")) + .collect(); + names.reverse(); + names.join("::") +} + +/// Generate the dummy uses for all the items in the given context, and write +/// the dummy uses to `dest`. +pub fn generate_dummy_uses(ctx: &mut BindgenContext, + mut dest: W) + -> io::Result<()> + where W: io::Write, +{ + ctx.gen(|ctx| { + let input_header = ctx.options() + .input_header + .as_ref() + .expect("Should not generate dummy uses without an input header"); + + try!(writeln!(dest, "/* automatically generated by rust-bindgen */")); + try!(writeln!(dest, "")); + try!(writeln!(dest, "#include \"{}\"", input_header)); + try!(writeln!(dest, "")); + + let type_items = ctx.whitelisted_items() + .map(|id| ctx.resolve_item(id)) + .filter(|item| { + // We only want type items. + if let Some(ty) = item.kind().as_type() { + // However, we don't want anonymous types, as we can't + // generate dummy uses for them. + ty.name().is_some() && + // Nor do we want builtin types or named template type + // arguments. Again, we can't generate dummy uses for + // these. + !ty.is_builtin_or_named() && + // And finally, we won't be creating any dummy + // specializations, so ignore template declarations and + // partial specializations. + item.applicable_template_args(ctx).is_empty() + } else { + false + } + }) + .map(|item| namespaced_name(ctx, item)) + .enumerate(); + + for (idx, name) in type_items { + try!(writeln!(dest, "void dummy{}({}*) {{ }}", idx, name)); + } + + Ok(()) + }) +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/16-byte-alignment.h b/bash-5.1/vendor/bindgen/tests/headers/16-byte-alignment.h new file mode 100644 index 0000000..7a7f754 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/16-byte-alignment.h @@ -0,0 +1,33 @@ + +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; + +struct rte_ipv4_tuple { + uint32_t src_addr; + uint32_t dst_addr; + union { + struct { + uint16_t dport; + uint16_t sport; + }; + uint32_t sctp_tag; + }; +}; + +struct rte_ipv6_tuple { + uint8_t src_addr[16]; + uint8_t dst_addr[16]; + union { + struct { + uint16_t dport; + uint16_t sport; + }; + uint32_t sctp_tag; + }; +}; + +union rte_thash_tuple { + struct rte_ipv4_tuple v4; + struct rte_ipv6_tuple v6; +} __attribute__((aligned(16))); diff --git a/bash-5.1/vendor/bindgen/tests/headers/accessors.hpp b/bash-5.1/vendor/bindgen/tests/headers/accessors.hpp new file mode 100644 index 0000000..4c23e35 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/accessors.hpp @@ -0,0 +1,46 @@ +struct SomeAccessors { + int mNoAccessor; + /**
*/ + int mBothAccessors; + /**
*/ + int mUnsafeAccessors; + /**
*/ + int mImmutableAccessor; +}; + +/**
*/ +struct AllAccessors { + int mBothAccessors; + int mAlsoBothAccessors; +}; + +/**
*/ +struct AllUnsafeAccessors { + int mBothAccessors; + int mAlsoBothAccessors; +}; + +/**
*/ +struct ContradictAccessors { + int mBothAccessors; + /**
*/ + int mNoAccessors; + /**
*/ + int mUnsafeAccessors; + /**
*/ + int mImmutableAccessor; +}; + +/**
*/ +struct Replacing { + int mAccessor; +}; + +struct Replaced { + int noOp; +}; + +/**
*/ +struct Wrapper { + Replaced mReplaced; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/annotation_hide.hpp b/bash-5.1/vendor/bindgen/tests/headers/annotation_hide.hpp new file mode 100644 index 0000000..3c82c9a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/annotation_hide.hpp @@ -0,0 +1,16 @@ + +/** + *
+ */ +struct C; + +/** + *
+ */ +struct D { + int a; +}; + +struct NotAnnotated { + int f; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/anon_enum.hpp b/bash-5.1/vendor/bindgen/tests/headers/anon_enum.hpp new file mode 100644 index 0000000..1961fe6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/anon_enum.hpp @@ -0,0 +1,10 @@ +struct Test { + int foo; + float bar; + enum { T_NONE }; +}; + +typedef enum { + Foo, + Bar, +} Baz; diff --git a/bash-5.1/vendor/bindgen/tests/headers/anon_enum_trait.hpp b/bash-5.1/vendor/bindgen/tests/headers/anon_enum_trait.hpp new file mode 100644 index 0000000..e1ec394 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/anon_enum_trait.hpp @@ -0,0 +1,22 @@ + +template +class DataType { +public: + typedef _Tp value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 1, + depth = -1, + channels = 1, + fmt = 0, + type = -1, + }; +}; + +struct Foo { + enum { + Bar = 0, + Baz = 0, + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/anon_enum_whitelist.h b/bash-5.1/vendor/bindgen/tests/headers/anon_enum_whitelist.h new file mode 100644 index 0000000..15cda6b --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/anon_enum_whitelist.h @@ -0,0 +1,6 @@ +// bindgen-flags: --whitelist-var NODE_.* + +enum { + NODE_FLAG_FOO, + NODE_FLAG_BAR, +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/anon_union.hpp b/bash-5.1/vendor/bindgen/tests/headers/anon_union.hpp new file mode 100644 index 0000000..126f6a6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/anon_union.hpp @@ -0,0 +1,20 @@ +template +struct TErrorResult { + enum UnionState { + HasMessage, + HasException, + }; + int mResult; + struct Message; + struct DOMExceptionInfo; + union { + Message* mMessage; + DOMExceptionInfo* mDOMExceptionInfo; + }; + + bool mMightHaveUnreported; + UnionState mUnionState; +}; + +struct ErrorResult : public TErrorResult { +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/arg_keyword.hpp b/bash-5.1/vendor/bindgen/tests/headers/arg_keyword.hpp new file mode 100644 index 0000000..9f0af85 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/arg_keyword.hpp @@ -0,0 +1 @@ +void foo(const char* type); diff --git a/bash-5.1/vendor/bindgen/tests/headers/auto.hpp b/bash-5.1/vendor/bindgen/tests/headers/auto.hpp new file mode 100644 index 0000000..b5f6d5f --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/auto.hpp @@ -0,0 +1,19 @@ +// bindgen-flags: -- -std=c++14 +// bindgen-unstable + +class Foo { + static constexpr auto kFoo = 2 == 2; +}; + +template +class Bar { + static const constexpr auto kBar = T(1); +}; + +template auto Test1() { + return T(1); +} + +auto Test2() { + return Test1(); +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/bad-namespace-parenthood-inheritance.hpp b/bash-5.1/vendor/bindgen/tests/headers/bad-namespace-parenthood-inheritance.hpp new file mode 100644 index 0000000..ce21a40 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/bad-namespace-parenthood-inheritance.hpp @@ -0,0 +1,15 @@ +namespace std +{ + template < typename > struct char_traits; +} +namespace __gnu_cxx +{ + template < typename > struct char_traits; +} +namespace std +{ + template < class _CharT > struct char_traits:__gnu_cxx::char_traits < + _CharT > + { + }; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/base-to-derived.hpp b/bash-5.1/vendor/bindgen/tests/headers/base-to-derived.hpp new file mode 100644 index 0000000..ea31e0f --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/base-to-derived.hpp @@ -0,0 +1,19 @@ +// bindgen-flags: -- -std=c++11 + +struct false_type {}; + +template +struct __is_base_to_derived_ref; + +template +struct __is_base_to_derived_ref<_From, _To, true> +{ + typedef _To type; + + static constexpr bool value = type::value; +}; + +template +struct __is_base_to_derived_ref<_From, _To, false> +: public false_type +{ }; diff --git a/bash-5.1/vendor/bindgen/tests/headers/bitfield-enum-basic.hpp b/bash-5.1/vendor/bindgen/tests/headers/bitfield-enum-basic.hpp new file mode 100644 index 0000000..364bebf --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/bitfield-enum-basic.hpp @@ -0,0 +1,27 @@ +// bindgen-flags: --bitfield-enum "Foo|Buz|NS_.*|DUMMY_.*" -- -std=c++11 + +enum Foo { + Bar = 1 << 1, + Baz = 1 << 2, + Duplicated = 1 << 2, + Negative = -3, +}; + +enum class Buz : signed char { + Bar = 1 << 1, + Baz = 1 << 2, + Duplicated = 1 << 2, + Negative = -3, +}; + +enum { + NS_FOO = 1 << 0, + NS_BAR = 1 << 1, +}; + +class Dummy { + enum { + DUMMY_FOO = 1 << 0, + DUMMY_BAR = 1 << 1, + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/bitfield_method_mangling.h b/bash-5.1/vendor/bindgen/tests/headers/bitfield_method_mangling.h new file mode 100644 index 0000000..257648e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/bitfield_method_mangling.h @@ -0,0 +1,5 @@ +typedef struct +{ + unsigned int pad3: 24; + unsigned int type: 8; +} mach_msg_type_descriptor_t; diff --git a/bash-5.1/vendor/bindgen/tests/headers/blocks.h b/bash-5.1/vendor/bindgen/tests/headers/blocks.h new file mode 100644 index 0000000..80420e6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/blocks.h @@ -0,0 +1,3 @@ +// bindgen-flags: -- -fblocks + +void atexit_b(void (^)(void)); diff --git a/bash-5.1/vendor/bindgen/tests/headers/canonical_path_without_namespacing.hpp b/bash-5.1/vendor/bindgen/tests/headers/canonical_path_without_namespacing.hpp new file mode 100644 index 0000000..92e8584 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/canonical_path_without_namespacing.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: --disable-name-namespacing + +namespace foo { + struct Bar {}; +} + +void baz(foo::Bar*); diff --git a/bash-5.1/vendor/bindgen/tests/headers/class.hpp b/bash-5.1/vendor/bindgen/tests/headers/class.hpp new file mode 100644 index 0000000..e753f18 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class.hpp @@ -0,0 +1,29 @@ +class C { + int a; + // More than rust limits (32) + char big_array[33]; +}; + +class WithDtor { + int b; + + ~WithDtor() {} +}; + +union Union { + float d; + int i; +}; + +class WithUnion { + Union data; +}; + +class RealAbstractionWithTonsOfMethods { + void foo(); +public: + void bar() const; + void bar(); + void bar(int foo); + static void sta(); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_nested.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_nested.hpp new file mode 100644 index 0000000..ab38d50 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_nested.hpp @@ -0,0 +1,24 @@ +class A { +public: + int member_a; + class B { + int member_b; + }; +}; + +A::B var; + +class D { + A::B member; +}; + +template +class Templated { + T member; + + class Templated_inner { + public: + T* member_ptr; + void get() {} + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_no_members.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_no_members.hpp new file mode 100644 index 0000000..a448355 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_no_members.hpp @@ -0,0 +1,16 @@ +// bindgen-flags: -- -std=c++11 + +class whatever { +}; + +class whatever_child: public whatever { +}; + +class whatever_child_with_member: public whatever { +public: + int m_member; +}; + +static_assert(sizeof(whatever) == 1, "Testing!"); +static_assert(sizeof(whatever_child) == 1, "Testing!"); +static_assert(sizeof(whatever_child_with_member) == 4, "Testing!"); diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_static.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_static.hpp new file mode 100644 index 0000000..21ab232 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_static.hpp @@ -0,0 +1,7 @@ +class MyClass { +public: + static const int* example; + static const int* example_check_no_collision; +}; + +static const int* example_check_no_collision; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_static_const.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_static_const.hpp new file mode 100644 index 0000000..150afe8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_static_const.hpp @@ -0,0 +1,8 @@ +using int32_t = int; +typedef unsigned int uint32_t; + +class A { + static const int a = 0; + static const int32_t b = 077; + static const uint32_t c = 0xff; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_use_as.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_use_as.hpp new file mode 100644 index 0000000..a4e36de --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_use_as.hpp @@ -0,0 +1,15 @@ + +/** + *
+ */ +struct whatever_replacement { + int replacement; +}; + +struct whatever { + int b; +}; + +struct container { + whatever c; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_with_dtor.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_with_dtor.hpp new file mode 100644 index 0000000..b9bf74e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_with_dtor.hpp @@ -0,0 +1,13 @@ + + +template +class HandleWithDtor { + T* ptr; + ~HandleWithDtor() {} +}; + +typedef HandleWithDtor HandleValue; + +class WithoutDtor { + HandleValue shouldBeWithDtor; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_with_inner_struct.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_with_inner_struct.hpp new file mode 100644 index 0000000..ec729fe --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_with_inner_struct.hpp @@ -0,0 +1,43 @@ +// bindgen-flags: -- -std=c++11 + +class A { + unsigned c; + struct Segment { int begin, end; }; + union { + int f; + } named_union; + union { + int d; + }; +}; + +class B { + unsigned d; + struct Segment { int begin, end; }; +}; + + +enum class StepSyntax { + Keyword, // step-start and step-end + FunctionalWithoutKeyword, // steps(...) + FunctionalWithStartKeyword, // steps(..., start) + FunctionalWithEndKeyword, // steps(..., end) +}; + +class C { + unsigned d; + union { + struct { + float mX1; + float mY1; + float mX2; + float mY2; + } mFunc; + struct { + StepSyntax mStepSyntax; + unsigned int mSteps; + }; + }; + // To ensure it doesn't collide + struct Segment { int begin, end; }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/class_with_typedef.hpp b/bash-5.1/vendor/bindgen/tests/headers/class_with_typedef.hpp new file mode 100644 index 0000000..8707cff --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/class_with_typedef.hpp @@ -0,0 +1,22 @@ +typedef int AnotherInt; + +class C { +public: + typedef int MyInt; + typedef const char* Lookup; + MyInt c; + MyInt* ptr; + MyInt arr[10]; + AnotherInt d; + AnotherInt* other_ptr; + + void method(MyInt c); + void methodRef(MyInt& c); + void complexMethodRef(Lookup& c); + void anotherMethod(AnotherInt c); +}; + +class D: public C { +public: + MyInt* ptr; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/complex.h b/bash-5.1/vendor/bindgen/tests/headers/complex.h new file mode 100644 index 0000000..04877a4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/complex.h @@ -0,0 +1,16 @@ + +#define COMPLEX_TEST(ty_, name_) \ + struct Test##name_ { \ + ty_ _Complex mMember; \ + \ + }; \ + struct Test##name_##Ptr { \ + ty_ _Complex* mMember; \ + }; + +COMPLEX_TEST(double, Double) +COMPLEX_TEST(float, Float) + +// FIXME: 128-byte-aligned in some machines +// which we can't support right now in Rust. +// COMPLEX_TEST(long double, LongDouble) diff --git a/bash-5.1/vendor/bindgen/tests/headers/complex_global.h b/bash-5.1/vendor/bindgen/tests/headers/complex_global.h new file mode 100644 index 0000000..d9f9fb0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/complex_global.h @@ -0,0 +1,3 @@ +float _Complex globalValueFloat; +double _Complex globalValueDouble; +long double _Complex globalValueLongDouble; diff --git a/bash-5.1/vendor/bindgen/tests/headers/const_bool.hpp b/bash-5.1/vendor/bindgen/tests/headers/const_bool.hpp new file mode 100644 index 0000000..633a7c9 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/const_bool.hpp @@ -0,0 +1,9 @@ +// bindgen-unstable + +const bool k = true; +struct A { + static const bool k = false; +}; + +typedef bool foo; +const foo k2 = true; diff --git a/bash-5.1/vendor/bindgen/tests/headers/const_enum_unnamed.hpp b/bash-5.1/vendor/bindgen/tests/headers/const_enum_unnamed.hpp new file mode 100644 index 0000000..eb13943 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/const_enum_unnamed.hpp @@ -0,0 +1,9 @@ + +enum { + FOO_BAR, + FOO_BAZ, +}; + +class Foo { + enum { FOO_BAR = 10 }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/const_ptr.hpp b/bash-5.1/vendor/bindgen/tests/headers/const_ptr.hpp new file mode 100644 index 0000000..66744f8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/const_ptr.hpp @@ -0,0 +1,3 @@ +extern "C" { + void foo(const void* bar); +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/const_resolved_ty.h b/bash-5.1/vendor/bindgen/tests/headers/const_resolved_ty.h new file mode 100644 index 0000000..2521e61 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/const_resolved_ty.h @@ -0,0 +1,3 @@ +typedef unsigned char uint8_t; + +void foo(const uint8_t* foo); diff --git a/bash-5.1/vendor/bindgen/tests/headers/const_tparam.hpp b/bash-5.1/vendor/bindgen/tests/headers/const_tparam.hpp new file mode 100644 index 0000000..05f26e4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/const_tparam.hpp @@ -0,0 +1,5 @@ +template +class C { + const T* const foo; + const T* bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/constant-evaluate.h b/bash-5.1/vendor/bindgen/tests/headers/constant-evaluate.h new file mode 100644 index 0000000..f9f1fa6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/constant-evaluate.h @@ -0,0 +1,19 @@ +// bindgen-unstable + +enum { + foo = 4, + bar = 8, +}; + +typedef unsigned long long EasyToOverflow; +const EasyToOverflow k = 0x80000000; + +const EasyToOverflow k_expr = 1ULL << 60; + +const long long BAZ = (1 << foo) | bar; +const double fuzz = (1 + 50.0f); +const char BAZZ = '5'; +const char WAT = '\0'; + +const char* bytestring = "Foo"; +const char* NOT_UTF8 = "\xf0\x28\x8c\x28"; diff --git a/bash-5.1/vendor/bindgen/tests/headers/constify-all-enums.h b/bash-5.1/vendor/bindgen/tests/headers/constify-all-enums.h new file mode 100644 index 0000000..7138bf2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/constify-all-enums.h @@ -0,0 +1,11 @@ +// bindgen-flags: --constified-enum foo + +enum foo { + THIS, + SHOULD_BE, + A_CONSTANT, +}; + +struct bar { + enum foo this_should_work; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/constify-enum.h b/bash-5.1/vendor/bindgen/tests/headers/constify-enum.h new file mode 100644 index 0000000..a5b4052 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/constify-enum.h @@ -0,0 +1,13 @@ + +enum nsCSSPropertyID { + eCSSProperty_a, + eCSSProperty_b, + + eCSSProperty_COUNT, /**<
*/ + eCSSProperty_COUNT_DUMMY2 = eCSSProperty_COUNT - 1, /**<
*/ + + eCSSPropertyAlias_aa, + eCSSPropertyAlias_bb, + + eCSSProperty_COUNT_unexistingVariantValue, /**<
*/ +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/constructor-tp.hpp b/bash-5.1/vendor/bindgen/tests/headers/constructor-tp.hpp new file mode 100644 index 0000000..6e55ea7 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/constructor-tp.hpp @@ -0,0 +1,26 @@ + +template +class Foo { +public: + Foo(); + + void doBaz(); +}; + +template +inline void +Foo::doBaz() { +} + +class Bar { +public: + Bar(); +}; + +template +Foo::Foo() { +} + +inline +Bar::Bar() { +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/constructors.hpp b/bash-5.1/vendor/bindgen/tests/headers/constructors.hpp new file mode 100644 index 0000000..d417488 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/constructors.hpp @@ -0,0 +1,13 @@ + +class TestOverload { + // This one shouldnt' be generated. + TestOverload(); +public: + TestOverload(int); + TestOverload(double); +}; + +class TestPublicNoArgs { +public: + TestPublicNoArgs(); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/convert-floats.h b/bash-5.1/vendor/bindgen/tests/headers/convert-floats.h new file mode 100644 index 0000000..08d9fe0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/convert-floats.h @@ -0,0 +1,9 @@ +// bindgen-flags: --no-convert-floats + +struct foo { + float bar, baz; + double bazz; + long double* bazzz; + float _Complex complexFloat; + double _Complex complexDouble; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/crtp.hpp b/bash-5.1/vendor/bindgen/tests/headers/crtp.hpp new file mode 100644 index 0000000..a5477c5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/crtp.hpp @@ -0,0 +1,12 @@ +template +class Base {}; + +class Derived : public Base {}; + +template +class BaseWithDestructor { + ~BaseWithDestructor(); +}; + +class DerivedFromBaseWithDestructor : + public BaseWithDestructor {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/dash_language.h b/bash-5.1/vendor/bindgen/tests/headers/dash_language.h new file mode 100644 index 0000000..4c8bb58 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/dash_language.h @@ -0,0 +1,6 @@ +// bindgen-flags: -- -x c++ --std=c++11 + +template +struct Foo { + int bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/decl_extern_int_twice.h b/bash-5.1/vendor/bindgen/tests/headers/decl_extern_int_twice.h new file mode 100644 index 0000000..06f80e8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/decl_extern_int_twice.h @@ -0,0 +1,2 @@ +extern int foo; +extern int foo; diff --git a/bash-5.1/vendor/bindgen/tests/headers/decl_ptr_to_array.h b/bash-5.1/vendor/bindgen/tests/headers/decl_ptr_to_array.h new file mode 100644 index 0000000..3222cbd --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/decl_ptr_to_array.h @@ -0,0 +1 @@ +int (*foo)[1]; diff --git a/bash-5.1/vendor/bindgen/tests/headers/disable-namespacing.hpp b/bash-5.1/vendor/bindgen/tests/headers/disable-namespacing.hpp new file mode 100644 index 0000000..1119136 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/disable-namespacing.hpp @@ -0,0 +1,9 @@ +// bindgen-flags: --disable-name-namespacing + +namespace foo { +namespace bar { + +typedef int Baz; + +} +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces-definitions.hpp b/bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces-definitions.hpp new file mode 100644 index 0000000..7c8888d --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces-definitions.hpp @@ -0,0 +1,18 @@ +// bindgen-flags: --enable-cxx-namespaces + +namespace foo { + class Bar; +} + +namespace bar { + struct Foo { + foo::Bar* ptr; + }; +}; + +namespace foo { + class Bar { + int foo; + bool baz; + }; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces.hpp b/bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces.hpp new file mode 100644 index 0000000..10e1933 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/duplicated-namespaces.hpp @@ -0,0 +1,4 @@ +// bindgen-flags: --enable-cxx-namespaces + +namespace std {} +namespace std {} diff --git a/bash-5.1/vendor/bindgen/tests/headers/duplicated_constants_in_ns.hpp b/bash-5.1/vendor/bindgen/tests/headers/duplicated_constants_in_ns.hpp new file mode 100644 index 0000000..bb34364 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/duplicated_constants_in_ns.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: --enable-cxx-namespaces +namespace foo { + const int FOO = 4; +} +namespace bar { + const int FOO = 5; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/elaborated.hpp b/bash-5.1/vendor/bindgen/tests/headers/elaborated.hpp new file mode 100644 index 0000000..4bfbff2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/elaborated.hpp @@ -0,0 +1,5 @@ +namespace whatever { + typedef int whatever_t; +} + +void something(const whatever::whatever_t *wat); diff --git a/bash-5.1/vendor/bindgen/tests/headers/empty_template_param_name.hpp b/bash-5.1/vendor/bindgen/tests/headers/empty_template_param_name.hpp new file mode 100644 index 0000000..0e9f3c3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/empty_template_param_name.hpp @@ -0,0 +1,6 @@ +// bindgen-flags: -- -std=c++11 + +template using __void_t = void; + +template> + struct __iterator_traits { }; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum.h b/bash-5.1/vendor/bindgen/tests/headers/enum.h new file mode 100644 index 0000000..f2d301e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum.h @@ -0,0 +1,9 @@ +enum Foo { + Bar = 0, + Qux +}; + +enum Neg { + MinusOne = -1, + One = 1, +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_alias.hpp b/bash-5.1/vendor/bindgen/tests/headers/enum_alias.hpp new file mode 100644 index 0000000..658f8fd --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_alias.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: -- -std=c++11 + +typedef unsigned char uint8_t; + +enum Bar : uint8_t { + VAL +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_and_vtable_mangling.hpp b/bash-5.1/vendor/bindgen/tests/headers/enum_and_vtable_mangling.hpp new file mode 100644 index 0000000..3abd6a2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_and_vtable_mangling.hpp @@ -0,0 +1,11 @@ + +enum { + match, + whatever_else, +}; + +class C { + int i; +public: + virtual void match() { }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_dupe.h b/bash-5.1/vendor/bindgen/tests/headers/enum_dupe.h new file mode 100644 index 0000000..6d3591d --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_dupe.h @@ -0,0 +1,4 @@ +enum Foo { + Bar = 1, + Dupe = 1 +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_explicit_type.hpp b/bash-5.1/vendor/bindgen/tests/headers/enum_explicit_type.hpp new file mode 100644 index 0000000..78eadd4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_explicit_type.hpp @@ -0,0 +1,28 @@ +// bindgen-flags: -- -std=c++11 + +enum Foo: unsigned char { + Bar = 0, + Qux +}; + +enum Neg: char { + MinusOne = -1, + One = 1, +}; + +enum Bigger: unsigned short { + Much = 255, + Larger +}; + +enum MuchLong: long { + MuchLow = -4294967296, +}; + +enum MuchLongLong: long long { + I64_MIN = 1ll << 63, +}; + +enum MuchULongLong: unsigned long long { + MuchHigh = 4294967296, +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_in_template_with_typedef.hpp b/bash-5.1/vendor/bindgen/tests/headers/enum_in_template_with_typedef.hpp new file mode 100644 index 0000000..ac19b78 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_in_template_with_typedef.hpp @@ -0,0 +1,16 @@ +// bindgen-flags: -- -std=c++11 + +namespace std { + template class fbstring_core; +} + +typedef unsigned char uint8_t; +namespace std { + template class fbstring_core { + typedef uint8_t category_type; + enum Category : category_type { + Foo = 1, + Bar = 4, + }; + }; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_negative.h b/bash-5.1/vendor/bindgen/tests/headers/enum_negative.h new file mode 100644 index 0000000..6cbdfe0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_negative.h @@ -0,0 +1,4 @@ +enum Foo { + Bar = -2, + Qux = 1, +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/enum_packed.h b/bash-5.1/vendor/bindgen/tests/headers/enum_packed.h new file mode 100644 index 0000000..8654d11 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/enum_packed.h @@ -0,0 +1,14 @@ +enum __attribute__((packed)) Foo { + Bar = 0, + Qux +}; + +enum __attribute__((packed)) Neg { + MinusOne = -1, + One = 1, +}; + +enum __attribute__((packed)) Bigger { + Much = 255, + Larger +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/eval-variadic-template-parameter.hpp b/bash-5.1/vendor/bindgen/tests/headers/eval-variadic-template-parameter.hpp new file mode 100644 index 0000000..0a9e51c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/eval-variadic-template-parameter.hpp @@ -0,0 +1,8 @@ +// bindgen-flags: -- -std=c++11 + +template +struct B { + // Can't generate anything meaningful in Rust for this, but we shouldn't + // trigger an assertion inside Clang. + static const long c = sizeof...(T); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/extern.hpp b/bash-5.1/vendor/bindgen/tests/headers/extern.hpp new file mode 100644 index 0000000..0779e03 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/extern.hpp @@ -0,0 +1,3 @@ +extern "C" { +#include "func_proto.h" +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/float128.hpp b/bash-5.1/vendor/bindgen/tests/headers/float128.hpp new file mode 100644 index 0000000..f554e88 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/float128.hpp @@ -0,0 +1,13 @@ +// FIXME: libclang < 3.9 does not expose `__float128` in its interface, so this +// test will fail. Once we remove support for `--features llvm_stable` and +// require libclang >= 3.9, we can reenable this test. +// +// static __float128 global = 1.0; + +// FIXME: We have no way to get 128 bit aligned structs in Rust at the moment, +// and therefore the generated layout tests for this struct will fail. When we +// can enforce 128 bit alignment, we can re-enable this test. +// +// struct A { +// __float128 f; +// }; diff --git a/bash-5.1/vendor/bindgen/tests/headers/forward-declaration-autoptr.hpp b/bash-5.1/vendor/bindgen/tests/headers/forward-declaration-autoptr.hpp new file mode 100644 index 0000000..a26c1cd --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/forward-declaration-autoptr.hpp @@ -0,0 +1,10 @@ +class Foo; + +template +struct RefPtr { + T* m_inner; +}; + +struct Bar { + RefPtr m_member; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct-with-fields.hpp b/bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct-with-fields.hpp new file mode 100644 index 0000000..437fff5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct-with-fields.hpp @@ -0,0 +1,8 @@ +template class Rooted; +namespace js { + template class RootedBase { + T* foo; + Rooted* next; + }; +} +template class Rooted : js::RootedBase {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct.hpp b/bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct.hpp new file mode 100644 index 0000000..ac7aef5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/forward-inherit-struct.hpp @@ -0,0 +1,5 @@ +template class Rooted; +namespace js { + template class RootedBase {}; +} +template class Rooted : js::RootedBase {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/forward_declared_complex_types.hpp b/bash-5.1/vendor/bindgen/tests/headers/forward_declared_complex_types.hpp new file mode 100644 index 0000000..ffc779a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/forward_declared_complex_types.hpp @@ -0,0 +1,16 @@ +struct Foo_empty {}; +struct Foo; + +struct Bar { + Foo *f; +}; + +void baz_struct(Foo* f); + +union Union; + +void baz_union(Union* u); + +class Quux; + +void baz_class(Quux* q); diff --git a/bash-5.1/vendor/bindgen/tests/headers/forward_declared_struct.h b/bash-5.1/vendor/bindgen/tests/headers/forward_declared_struct.h new file mode 100644 index 0000000..2a69450 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/forward_declared_struct.h @@ -0,0 +1,11 @@ +struct a; + +struct a { + int b; +}; + +struct c { + int d; +}; + +struct c; \ No newline at end of file diff --git a/bash-5.1/vendor/bindgen/tests/headers/func_proto.h b/bash-5.1/vendor/bindgen/tests/headers/func_proto.h new file mode 100644 index 0000000..51139ca --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/func_proto.h @@ -0,0 +1 @@ +typedef int foo(int bar); diff --git a/bash-5.1/vendor/bindgen/tests/headers/func_ptr.h b/bash-5.1/vendor/bindgen/tests/headers/func_ptr.h new file mode 100644 index 0000000..a4662f3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/func_ptr.h @@ -0,0 +1 @@ +int (*foo) (int x, int y); diff --git a/bash-5.1/vendor/bindgen/tests/headers/func_ptr_in_struct.h b/bash-5.1/vendor/bindgen/tests/headers/func_ptr_in_struct.h new file mode 100644 index 0000000..988db5b --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/func_ptr_in_struct.h @@ -0,0 +1,6 @@ + +enum baz; + +struct Foo { + enum baz (*bar) (int x, int y); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/func_with_array_arg.h b/bash-5.1/vendor/bindgen/tests/headers/func_with_array_arg.h new file mode 100644 index 0000000..1b81702 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/func_with_array_arg.h @@ -0,0 +1 @@ +void f(int x[2]); diff --git a/bash-5.1/vendor/bindgen/tests/headers/func_with_func_ptr_arg.h b/bash-5.1/vendor/bindgen/tests/headers/func_with_func_ptr_arg.h new file mode 100644 index 0000000..629c84a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/func_with_func_ptr_arg.h @@ -0,0 +1 @@ +void foo(void (*bar)()); diff --git a/bash-5.1/vendor/bindgen/tests/headers/in_class_typedef.hpp b/bash-5.1/vendor/bindgen/tests/headers/in_class_typedef.hpp new file mode 100644 index 0000000..dda7472 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/in_class_typedef.hpp @@ -0,0 +1,10 @@ + +template +class Foo { + typedef T elem_type; + typedef T* ptr_type; + + typedef struct Bar { + int x, y; + } Bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inherit-namespaced.hpp b/bash-5.1/vendor/bindgen/tests/headers/inherit-namespaced.hpp new file mode 100644 index 0000000..61eafd5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inherit-namespaced.hpp @@ -0,0 +1,4 @@ +namespace js { + template class RootedBase {}; +} +template class Rooted : js::RootedBase {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inherit_named.hpp b/bash-5.1/vendor/bindgen/tests/headers/inherit_named.hpp new file mode 100644 index 0000000..9881d1b --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inherit_named.hpp @@ -0,0 +1,5 @@ +template +class Wohoo {}; + +template +class Weeee : public T {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inherit_typedef.hpp b/bash-5.1/vendor/bindgen/tests/headers/inherit_typedef.hpp new file mode 100644 index 0000000..8d699e8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inherit_typedef.hpp @@ -0,0 +1,5 @@ +struct Foo {}; + +typedef Foo TypedefedFoo; + +struct Bar: public TypedefedFoo {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inline-function.h b/bash-5.1/vendor/bindgen/tests/headers/inline-function.h new file mode 100644 index 0000000..02cb7c0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inline-function.h @@ -0,0 +1,6 @@ +// bindgen-unstable + +/** The point of this test is to _not_ generate these functions. */ + +inline static int myadd(const int x, const int y) { return x + y; } +static int mysub(const int x, const int y) { return x - y; } diff --git a/bash-5.1/vendor/bindgen/tests/headers/inline_namespace.hpp b/bash-5.1/vendor/bindgen/tests/headers/inline_namespace.hpp new file mode 100644 index 0000000..2ccf8ab --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inline_namespace.hpp @@ -0,0 +1,11 @@ +// bindgen-flags: --enable-cxx-namespaces -- -std=c++11 + +namespace foo { + inline namespace bar { + using Ty = int; + }; +}; + +class Bar { + foo::Ty baz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inline_namespace_conservative.hpp b/bash-5.1/vendor/bindgen/tests/headers/inline_namespace_conservative.hpp new file mode 100644 index 0000000..50068a2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inline_namespace_conservative.hpp @@ -0,0 +1,12 @@ +// bindgen-flags: --enable-cxx-namespaces --conservative-inline-namespaces -- -std=c++11 + +namespace foo { + inline namespace bar { + using Ty = int; + }; + using Ty = long long; +}; + +class Bar { + foo::bar::Ty baz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inline_namespace_whitelist.hpp b/bash-5.1/vendor/bindgen/tests/headers/inline_namespace_whitelist.hpp new file mode 100644 index 0000000..30047bb --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inline_namespace_whitelist.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: --enable-cxx-namespaces --whitelist-type=std::string -- -std=c++11 + +namespace std { + inline namespace bar { + using string = const char*; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inner_const.hpp b/bash-5.1/vendor/bindgen/tests/headers/inner_const.hpp new file mode 100644 index 0000000..25c2e60 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inner_const.hpp @@ -0,0 +1,6 @@ + +class Foo { + static int BOO; + static Foo whatever; + int bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/inner_template_self.hpp b/bash-5.1/vendor/bindgen/tests/headers/inner_template_self.hpp new file mode 100644 index 0000000..1ae5af0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/inner_template_self.hpp @@ -0,0 +1,10 @@ + +template +class LinkedList { + LinkedList* next; + LinkedList* prev; +}; + +class InstantiateIt { + LinkedList m_list; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/int128_t.h b/bash-5.1/vendor/bindgen/tests/headers/int128_t.h new file mode 100644 index 0000000..eece252 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/int128_t.h @@ -0,0 +1,7 @@ +/** + * FIXME: Uncomment this once we can generate the proper alignment for the type, + * i.e., when we use u128/i128. +struct Foo { + __int128 foo; +}; + */ diff --git a/bash-5.1/vendor/bindgen/tests/headers/issue-358.hpp b/bash-5.1/vendor/bindgen/tests/headers/issue-358.hpp new file mode 100644 index 0000000..b14521b --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/issue-358.hpp @@ -0,0 +1,8 @@ +// bindgen-flags: -- -std=c++11 +namespace JS { +template class PersistentRooted; +} +template class a { a *b; }; +namespace JS { +template class PersistentRooted : a> {}; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/issue-372.hpp b/bash-5.1/vendor/bindgen/tests/headers/issue-372.hpp new file mode 100644 index 0000000..a072f06 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/issue-372.hpp @@ -0,0 +1,16 @@ +// bindgen-flags: --enable-cxx-namespaces +template class c { a e[b]; }; +class d; +template class C { c h; }; +class i { + i *j; + i *k; + bool l; +}; +class d { + i m; +}; +enum n { o, p, q, r, s, t, b, ae, e, ag, ah, ai }; +class F { + C w; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/issue-410.hpp b/bash-5.1/vendor/bindgen/tests/headers/issue-410.hpp new file mode 100644 index 0000000..a7a834c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/issue-410.hpp @@ -0,0 +1,12 @@ +// bindgen-flags: --enable-cxx-namespaces --whitelist-type JS::Value + +namespace JS { +class Value; +} +typedef enum {} JSWhyMagic; +namespace JS { +class Value { +public: + void a(JSWhyMagic); +}; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/issue-447.hpp b/bash-5.1/vendor/bindgen/tests/headers/issue-447.hpp new file mode 100644 index 0000000..017838c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/issue-447.hpp @@ -0,0 +1,27 @@ +// bindgen-flags: --enable-cxx-namespaces --whitelist-type JSAutoCompartment -- -std=c++11 + +namespace mozilla { + template class a {}; + namespace detail { + class GuardObjectNotifier {}; + struct b; + } + class c { + typedef detail::b d; + }; +} +namespace js { + class D { + mozilla::a e; + }; +} +struct f { + js::D g; +}; +namespace js { + struct ContextFriendFields : f {}; +} +class JSAutoCompartment { +public: + JSAutoCompartment(mozilla::detail::GuardObjectNotifier); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/issue_311.hpp b/bash-5.1/vendor/bindgen/tests/headers/issue_311.hpp new file mode 100644 index 0000000..a8d7fd9 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/issue_311.hpp @@ -0,0 +1,5 @@ +// bindgen-flags: --enable-cxx-namespaces + +struct jsval_layout { + struct {}; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/issue_315.hpp b/bash-5.1/vendor/bindgen/tests/headers/issue_315.hpp new file mode 100644 index 0000000..e58cb5e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/issue_315.hpp @@ -0,0 +1,2 @@ +///
+template using b = a; diff --git a/bash-5.1/vendor/bindgen/tests/headers/jsval_layout_opaque.hpp b/bash-5.1/vendor/bindgen/tests/headers/jsval_layout_opaque.hpp new file mode 100644 index 0000000..85c5be6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/jsval_layout_opaque.hpp @@ -0,0 +1,424 @@ +// bindgen-flags: --no-unstable-rust -- -std=c++11 + +/** + * These typedefs are hacky, but keep our tests consistent across 64-bit + * platforms, otherwise the id's change and our CI is unhappy. + */ +typedef unsigned char uint8_t; +typedef int int32_t; +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; +typedef unsigned long long size_t; +typedef unsigned long long uintptr_t; + + +#define JS_PUNBOX64 +#define IS_LITTLE_ENDIAN + +/* + * Try to get jsvals 64-bit aligned. We could almost assert that all values are + * aligned, but MSVC and GCC occasionally break alignment. + */ +#if defined(__GNUC__) || defined(__xlc__) || defined(__xlC__) +# define JSVAL_ALIGNMENT __attribute__((aligned (8))) +#elif defined(_MSC_VER) + /* + * Structs can be aligned with MSVC, but not if they are used as parameters, + * so we just don't try to align. + */ +# define JSVAL_ALIGNMENT +#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# define JSVAL_ALIGNMENT +#elif defined(__HP_cc) || defined(__HP_aCC) +# define JSVAL_ALIGNMENT +#endif + +#if defined(JS_PUNBOX64) +# define JSVAL_TAG_SHIFT 47 +#endif + +/* + * We try to use enums so that printing a jsval_layout in the debugger shows + * nice symbolic type tags, however we can only do this when we can force the + * underlying type of the enum to be the desired size. + */ +#if !defined(__SUNPRO_CC) && !defined(__xlC__) + +#if defined(_MSC_VER) +# define JS_ENUM_HEADER(id, type) enum id : type +# define JS_ENUM_FOOTER(id) +#else +# define JS_ENUM_HEADER(id, type) enum id +# define JS_ENUM_FOOTER(id) __attribute__((packed)) +#endif + +/* Remember to propagate changes to the C defines below. */ +JS_ENUM_HEADER(JSValueType, uint8_t) +{ + JSVAL_TYPE_DOUBLE = 0x00, + JSVAL_TYPE_INT32 = 0x01, + JSVAL_TYPE_UNDEFINED = 0x02, + JSVAL_TYPE_BOOLEAN = 0x03, + JSVAL_TYPE_MAGIC = 0x04, + JSVAL_TYPE_STRING = 0x05, + JSVAL_TYPE_SYMBOL = 0x06, + JSVAL_TYPE_NULL = 0x07, + JSVAL_TYPE_OBJECT = 0x08, + + /* These never appear in a jsval; they are only provided as an out-of-band value. */ + JSVAL_TYPE_UNKNOWN = 0x20, + JSVAL_TYPE_MISSING = 0x21 +} JS_ENUM_FOOTER(JSValueType); + +static_assert(sizeof(JSValueType) == 1, + "compiler typed enum support is apparently buggy"); + +#if defined(JS_NUNBOX32) + +/* Remember to propagate changes to the C defines below. */ +JS_ENUM_HEADER(JSValueTag, uint32_t) +{ + JSVAL_TAG_CLEAR = 0xFFFFFF80, + JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32, + JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED, + JSVAL_TAG_STRING = JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING, + JSVAL_TAG_SYMBOL = JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL, + JSVAL_TAG_BOOLEAN = JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN, + JSVAL_TAG_MAGIC = JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC, + JSVAL_TAG_NULL = JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL, + JSVAL_TAG_OBJECT = JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT +} JS_ENUM_FOOTER(JSValueTag); + +static_assert(sizeof(JSValueTag) == sizeof(uint32_t), + "compiler typed enum support is apparently buggy"); + +#elif defined(JS_PUNBOX64) + +/* Remember to propagate changes to the C defines below. */ +JS_ENUM_HEADER(JSValueTag, uint32_t) +{ + JSVAL_TAG_MAX_DOUBLE = 0x1FFF0, + JSVAL_TAG_INT32 = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32, + JSVAL_TAG_UNDEFINED = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED, + JSVAL_TAG_STRING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING, + JSVAL_TAG_SYMBOL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL, + JSVAL_TAG_BOOLEAN = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN, + JSVAL_TAG_MAGIC = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC, + JSVAL_TAG_NULL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL, + JSVAL_TAG_OBJECT = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT +} JS_ENUM_FOOTER(JSValueTag); + +static_assert(sizeof(JSValueTag) == sizeof(uint32_t), + "compiler typed enum support is apparently buggy"); + +JS_ENUM_HEADER(JSValueShiftedTag, uint64_t) +{ + JSVAL_SHIFTED_TAG_MAX_DOUBLE = ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF), + JSVAL_SHIFTED_TAG_INT32 = (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_UNDEFINED = (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_STRING = (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_SYMBOL = (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_BOOLEAN = (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_MAGIC = (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_NULL = (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT), + JSVAL_SHIFTED_TAG_OBJECT = (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) +} JS_ENUM_FOOTER(JSValueShiftedTag); + +static_assert(sizeof(JSValueShiftedTag) == sizeof(uint64_t), + "compiler typed enum support is apparently buggy"); + +#endif + +/* + * All our supported compilers implement C++11 |enum Foo : T| syntax, so don't + * expose these macros. (This macro exists *only* because gcc bug 51242 + * makes bit-fields of + * typed enums trigger a warning that can't be turned off. Don't expose it + * beyond this file!) + */ +#undef JS_ENUM_HEADER +#undef JS_ENUM_FOOTER + +#else /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ + +typedef uint8_t JSValueType; +#define JSVAL_TYPE_DOUBLE ((uint8_t)0x00) +#define JSVAL_TYPE_INT32 ((uint8_t)0x01) +#define JSVAL_TYPE_UNDEFINED ((uint8_t)0x02) +#define JSVAL_TYPE_BOOLEAN ((uint8_t)0x03) +#define JSVAL_TYPE_MAGIC ((uint8_t)0x04) +#define JSVAL_TYPE_STRING ((uint8_t)0x05) +#define JSVAL_TYPE_SYMBOL ((uint8_t)0x06) +#define JSVAL_TYPE_NULL ((uint8_t)0x07) +#define JSVAL_TYPE_OBJECT ((uint8_t)0x08) +#define JSVAL_TYPE_UNKNOWN ((uint8_t)0x20) + +#if defined(JS_NUNBOX32) + +typedef uint32_t JSValueTag; +#define JSVAL_TAG_CLEAR ((uint32_t)(0xFFFFFF80)) +#define JSVAL_TAG_INT32 ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32)) +#define JSVAL_TAG_UNDEFINED ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED)) +#define JSVAL_TAG_STRING ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING)) +#define JSVAL_TAG_SYMBOL ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL)) +#define JSVAL_TAG_BOOLEAN ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN)) +#define JSVAL_TAG_MAGIC ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC)) +#define JSVAL_TAG_NULL ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL)) +#define JSVAL_TAG_OBJECT ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT)) + +#elif defined(JS_PUNBOX64) + +typedef uint32_t JSValueTag; +#define JSVAL_TAG_MAX_DOUBLE ((uint32_t)(0x1FFF0)) +#define JSVAL_TAG_INT32 (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32) +#define JSVAL_TAG_UNDEFINED (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED) +#define JSVAL_TAG_STRING (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING) +#define JSVAL_TAG_SYMBOL (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL) +#define JSVAL_TAG_BOOLEAN (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN) +#define JSVAL_TAG_MAGIC (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC) +#define JSVAL_TAG_NULL (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL) +#define JSVAL_TAG_OBJECT (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT) + +typedef uint64_t JSValueShiftedTag; +#define JSVAL_SHIFTED_TAG_MAX_DOUBLE ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF) +#define JSVAL_SHIFTED_TAG_INT32 (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_UNDEFINED (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_STRING (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_SYMBOL (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_BOOLEAN (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_MAGIC (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_NULL (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT) +#define JSVAL_SHIFTED_TAG_OBJECT (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) + +#endif /* JS_PUNBOX64 */ +#endif /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ + +#if defined(JS_NUNBOX32) + +#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_CLEAR | (type))) + +#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL +#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT +#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 +#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING + +#elif defined(JS_PUNBOX64) + +#define JSVAL_PAYLOAD_MASK 0x00007FFFFFFFFFFFLL +#define JSVAL_TAG_MASK 0xFFFF800000000000LL +#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_MAX_DOUBLE | (type))) +#define JSVAL_TYPE_TO_SHIFTED_TAG(type) (((uint64_t)JSVAL_TYPE_TO_TAG(type)) << JSVAL_TAG_SHIFT) + +#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL +#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT +#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 +#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING + +#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET JSVAL_SHIFTED_TAG_NULL +#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET JSVAL_SHIFTED_TAG_OBJECT +#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET JSVAL_SHIFTED_TAG_UNDEFINED +#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET JSVAL_SHIFTED_TAG_STRING + +#endif /* JS_PUNBOX64 */ + +typedef enum JSWhyMagic +{ + /** a hole in a native object's elements */ + JS_ELEMENTS_HOLE, + + /** there is not a pending iterator value */ + JS_NO_ITER_VALUE, + + /** exception value thrown when closing a generator */ + JS_GENERATOR_CLOSING, + + /** compiler sentinel value */ + JS_NO_CONSTANT, + + /** used in debug builds to catch tracing errors */ + JS_THIS_POISON, + + /** used in debug builds to catch tracing errors */ + JS_ARG_POISON, + + /** an empty subnode in the AST serializer */ + JS_SERIALIZE_NO_NODE, + + /** lazy arguments value on the stack */ + JS_LAZY_ARGUMENTS, + + /** optimized-away 'arguments' value */ + JS_OPTIMIZED_ARGUMENTS, + + /** magic value passed to natives to indicate construction */ + JS_IS_CONSTRUCTING, + + /** arguments.callee has been overwritten */ + JS_OVERWRITTEN_CALLEE, + + /** value of static block object slot */ + JS_BLOCK_NEEDS_CLONE, + + /** see class js::HashableValue */ + JS_HASH_KEY_EMPTY, + + /** error while running Ion code */ + JS_ION_ERROR, + + /** missing recover instruction result */ + JS_ION_BAILOUT, + + /** optimized out slot */ + JS_OPTIMIZED_OUT, + + /** uninitialized lexical bindings that produce ReferenceError on touch. */ + JS_UNINITIALIZED_LEXICAL, + + /** for local use */ + JS_GENERIC_MAGIC, + + JS_WHY_MAGIC_COUNT +} JSWhyMagic; + +#if defined(IS_LITTLE_ENDIAN) +# if defined(JS_NUNBOX32) +typedef union jsval_layout +{ + uint64_t asBits; + struct { + union { + int32_t i32; + uint32_t u32; + uint32_t boo; // Don't use |bool| -- it must be four bytes. + JSString* str; + JS::Symbol* sym; + JSObject* obj; + js::gc::Cell* cell; + void* ptr; + JSWhyMagic why; + size_t word; + uintptr_t uintptr; + } payload; + JSValueTag tag; + } s; + double asDouble; + void* asPtr; +} JSVAL_ALIGNMENT jsval_layout; +# elif defined(JS_PUNBOX64) +typedef union jsval_layout +{ + uint64_t asBits; +#if !defined(_WIN64) + /* MSVC does not pack these correctly :-( */ + struct { + uint64_t payload47 : 47; + JSValueTag tag : 17; + } debugView; +#endif + struct { + union { + int32_t i32; + uint32_t u32; + JSWhyMagic why; + } payload; + } s; + double asDouble; + void* asPtr; + size_t asWord; + uintptr_t asUIntPtr; +} JSVAL_ALIGNMENT jsval_layout; +# endif /* JS_PUNBOX64 */ +#else /* defined(IS_LITTLE_ENDIAN) */ +# if defined(JS_NUNBOX32) +typedef union jsval_layout +{ + uint64_t asBits; + struct { + JSValueTag tag; + union { + int32_t i32; + uint32_t u32; + uint32_t boo; // Don't use |bool| -- it must be four bytes. + JSString* str; + JS::Symbol* sym; + JSObject* obj; + js::gc::Cell* cell; + void* ptr; + JSWhyMagic why; + size_t word; + uintptr_t uintptr; + } payload; + } s; + double asDouble; + void* asPtr; +} JSVAL_ALIGNMENT jsval_layout; +# elif defined(JS_PUNBOX64) +typedef union jsval_layout +{ + uint64_t asBits; + struct { + JSValueTag tag : 17; + uint64_t payload47 : 47; + } debugView; + struct { + uint32_t padding; + union { + int32_t i32; + uint32_t u32; + JSWhyMagic why; + } payload; + } s; + double asDouble; + void* asPtr; + size_t asWord; + uintptr_t asUIntPtr; +} JSVAL_ALIGNMENT jsval_layout; +# endif /* JS_PUNBOX64 */ +#endif /* defined(IS_LITTLE_ENDIAN) */ + +/* + * For codesize purposes on some platforms, it's important that the + * compiler know that JS::Values constructed from constant values can be + * folded to constant bit patterns at compile time, rather than + * constructed at runtime. Doing this requires a fair amount of C++11 + * features, which are not supported on all of our compilers. Set up + * some defines and helper macros in an attempt to confine the ugliness + * here, rather than scattering it all about the file. The important + * features are: + * + * - constexpr; + * - defaulted functions; + * - C99-style designated initializers. + */ +#if defined(__clang__) +# if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions) +# define JS_VALUE_IS_CONSTEXPR +# endif +#elif defined(__GNUC__) +/* + * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6 + * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because + * versions prior to that have bugs in the C++ front-end that cause crashes. + */ +# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3) +# define JS_VALUE_IS_CONSTEXPR +# endif +#endif + +#if defined(JS_VALUE_IS_CONSTEXPR) +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + return (jsval_layout) { .asBits = (BITS) } +# define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR +#else +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + jsval_layout l; \ + l.asBits = (BITS); \ + return l; +# define JS_VALUE_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR const +#endif + +struct Value { + jsval_layout data; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/keywords.h b/bash-5.1/vendor/bindgen/tests/headers/keywords.h new file mode 100644 index 0000000..8699ce5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/keywords.h @@ -0,0 +1,49 @@ +int u8; +int u16; +int u32; +int u64; +int i8; +int i16; +int i32; +int i64; +int f32; +int f64; +int usize; +int isize; +int as; +int box; +int crate; +int false; +int fn; +int impl; +int in; +int let; +int loop; +int match; +int mod; +int move; +int mut; +int pub; +int ref; +int self; +int Self; +int super; +int trait; +int true; +int type; +int unsafe; +int use; +int where; +int abstract; +int alignof; +int become; +int final; +int macro; +int offsetof; +int override; +int priv; +int proc; +int pure; +int unsized; +int virtual; +int yield; diff --git a/bash-5.1/vendor/bindgen/tests/headers/macro-expr-basic.h b/bash-5.1/vendor/bindgen/tests/headers/macro-expr-basic.h new file mode 100644 index 0000000..d2de7fd --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/macro-expr-basic.h @@ -0,0 +1,14 @@ +#define FOO 1 +#define BAR 4 +#define BAZ (FOO + BAR) + +#define MIN (1 << 63) + +#define BARR (1 << 0) +#define BAZZ ((1 << 1) + BAZ) +#define I_RAN_OUT_OF_DUMB_NAMES (BARR | BAZZ) + +/* I haz a comment */ +#define HAZ_A_COMMENT BARR + +#define HAZ_A_COMMENT_INSIDE (/* comment for real */ BARR + FOO) diff --git a/bash-5.1/vendor/bindgen/tests/headers/macro-redef.h b/bash-5.1/vendor/bindgen/tests/headers/macro-redef.h new file mode 100644 index 0000000..0180d2a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/macro-redef.h @@ -0,0 +1,5 @@ +#define FOO 4 +#define BAR (1 + FOO) +#undef FOO +#define FOO 5 +#define BAZ (1 + FOO) diff --git a/bash-5.1/vendor/bindgen/tests/headers/macro_const.h b/bash-5.1/vendor/bindgen/tests/headers/macro_const.h new file mode 100644 index 0000000..c28a3f6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/macro_const.h @@ -0,0 +1,7 @@ +#define foo "bar" +#define CHAR 'b' +#define CHARR '\0' +#define FLOAT 5.09f +#define FLOAT_EXPR (5 / 1000.0f) + +#define INVALID_UTF8 "\xf0\x28\x8c\x28" diff --git a/bash-5.1/vendor/bindgen/tests/headers/maddness-is-avoidable.hpp b/bash-5.1/vendor/bindgen/tests/headers/maddness-is-avoidable.hpp new file mode 100644 index 0000000..46d7495 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/maddness-is-avoidable.hpp @@ -0,0 +1,9 @@ +// bindgen-flags: --blacklist-type RefPtr_Proxy_member_function + +template +class RefPtr { + template + class Proxy { + typedef R (T::*member_function)(Args...); + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/method-mangling.hpp b/bash-5.1/vendor/bindgen/tests/headers/method-mangling.hpp new file mode 100644 index 0000000..0dac497 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/method-mangling.hpp @@ -0,0 +1,5 @@ + +class Foo { +public: + int type(); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/module-whitelisted.hpp b/bash-5.1/vendor/bindgen/tests/headers/module-whitelisted.hpp new file mode 100644 index 0000000..f41e874 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/module-whitelisted.hpp @@ -0,0 +1,2 @@ +// bindgen-flags: --enable-cxx-namespaces +struct Test {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/msvc-no-usr.hpp b/bash-5.1/vendor/bindgen/tests/headers/msvc-no-usr.hpp new file mode 100644 index 0000000..b15e49f --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/msvc-no-usr.hpp @@ -0,0 +1,8 @@ + +typedef unsigned long long size_t; + +class A { + const size_t foo; + + A() : foo(5) {} +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/multiple-inherit-empty-correct-layout.hpp b/bash-5.1/vendor/bindgen/tests/headers/multiple-inherit-empty-correct-layout.hpp new file mode 100644 index 0000000..1e2b133 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/multiple-inherit-empty-correct-layout.hpp @@ -0,0 +1,3 @@ +struct Foo {}; +struct Bar {}; +struct Baz : public Foo, public Bar {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/mutable.hpp b/bash-5.1/vendor/bindgen/tests/headers/mutable.hpp new file mode 100644 index 0000000..b61a103 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/mutable.hpp @@ -0,0 +1,14 @@ +class C { + mutable int m_member; + int m_other; +}; + +class NonCopiable { + mutable int m_member; + + ~NonCopiable() {}; +}; + +class NonCopiableWithNonCopiableMutableMember { + mutable NonCopiable m_member; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/namespace.hpp b/bash-5.1/vendor/bindgen/tests/headers/namespace.hpp new file mode 100644 index 0000000..6578853 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/namespace.hpp @@ -0,0 +1,47 @@ +// bindgen-flags: --enable-cxx-namespaces + +void top_level(); + +namespace whatever { + typedef int whatever_int_t; + + void in_whatever(); +} + +namespace { + namespace empty {} + + void foo(); + struct A { + whatever::whatever_int_t b; + public: + int lets_hope_this_works(); + }; +} + +template +class C: public A { + T m_c; + T* m_c_ptr; + T m_c_arr[10]; +}; + + +template<> +class C; + + +namespace w { + typedef unsigned int whatever_int_t; + + template + class D { + C m_c; + }; + + whatever_int_t heh(); // this should return w::whatever_int_t, and not whatever::whatever_int_t + + C foo(); + + C barr(); // <- This is the problematic one +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/nested.hpp b/bash-5.1/vendor/bindgen/tests/headers/nested.hpp new file mode 100644 index 0000000..299e176 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/nested.hpp @@ -0,0 +1,15 @@ + +class Calc { + int w; +}; + +class Test { +public: + struct Size; + friend struct Size; + struct Size { + struct Dimension : public Calc { + }; + Dimension mWidth, mHeight; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/nested_vtable.hpp b/bash-5.1/vendor/bindgen/tests/headers/nested_vtable.hpp new file mode 100644 index 0000000..87d6ce1 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/nested_vtable.hpp @@ -0,0 +1,8 @@ +class nsISupports { +public: + virtual nsISupports* QueryInterface(); +}; + +class nsIRunnable : public nsISupports {}; + +class Runnable : public nsIRunnable {}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/nested_within_namespace.hpp b/bash-5.1/vendor/bindgen/tests/headers/nested_within_namespace.hpp new file mode 100644 index 0000000..a9b7c1e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/nested_within_namespace.hpp @@ -0,0 +1,15 @@ +// bindgen-flags: --enable-cxx-namespaces + +namespace foo { + class Bar { + int foo; + + class Baz { + int foo; + }; + }; + + class Baz { + int baz; + }; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/no-comments.h b/bash-5.1/vendor/bindgen/tests/headers/no-comments.h new file mode 100644 index 0000000..1ddb1a3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/no-comments.h @@ -0,0 +1,5 @@ +// bindgen-flags: --no-doc-comments + +struct Foo { + int s; /*!< Including this will prevent rustc for compiling it */ +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/no-derive-debug.h b/bash-5.1/vendor/bindgen/tests/headers/no-derive-debug.h new file mode 100644 index 0000000..4a49e40 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/no-derive-debug.h @@ -0,0 +1,15 @@ +// bindgen-flags: --no-derive-debug --blacklist-type foo --raw-line "#[repr(C)] #[derive(Copy, Clone)] pub struct foo { bar: ::std::os::raw::c_int, }" + +struct foo { + int bar; +}; + +/** + * bar should compile. It will normally derive debug, but our blacklist of foo + * and replacement for another type that doesn't implement it would prevent it + * from building if --no-derive-debug didn't work. + */ +struct bar { + struct foo foo; + int baz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/no-recursive-whitelisting.h b/bash-5.1/vendor/bindgen/tests/headers/no-recursive-whitelisting.h new file mode 100644 index 0000000..1d805d9 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/no-recursive-whitelisting.h @@ -0,0 +1,7 @@ +// bindgen-flags: --no-recursive-whitelist --whitelist-type "Foo" --raw-line "pub enum Bar {}" + +struct Bar; + +struct Foo { + struct Bar* baz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/no-std.h b/bash-5.1/vendor/bindgen/tests/headers/no-std.h new file mode 100644 index 0000000..7bee965 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/no-std.h @@ -0,0 +1,5 @@ +// bindgen-flags: --ctypes-prefix "libc" --use-core --raw-line "#![no_std]" --raw-line "mod libc { pub type c_int = i32; pub enum c_void {} }" +struct foo { + int a, b; + void* bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/no_copy.hpp b/bash-5.1/vendor/bindgen/tests/headers/no_copy.hpp new file mode 100644 index 0000000..349e428 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/no_copy.hpp @@ -0,0 +1,6 @@ + +/**
*/ +template +class CopiableButWait { + int whatever; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/nsStyleAutoArray.hpp b/bash-5.1/vendor/bindgen/tests/headers/nsStyleAutoArray.hpp new file mode 100644 index 0000000..950152c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/nsStyleAutoArray.hpp @@ -0,0 +1,57 @@ + +template +class nsTArray { + T* mBuff; +}; + +template +class nsStyleAutoArray +{ +public: + // This constructor places a single element in mFirstElement. + enum WithSingleInitialElement { WITH_SINGLE_INITIAL_ELEMENT }; + explicit nsStyleAutoArray(WithSingleInitialElement) {} + nsStyleAutoArray(const nsStyleAutoArray& aOther) { *this = aOther; } + nsStyleAutoArray& operator=(const nsStyleAutoArray& aOther) { + mFirstElement = aOther.mFirstElement; + mOtherElements = aOther.mOtherElements; + return *this; + } + + bool operator==(const nsStyleAutoArray& aOther) const { + return Length() == aOther.Length() && + mFirstElement == aOther.mFirstElement && + mOtherElements == aOther.mOtherElements; + } + bool operator!=(const nsStyleAutoArray& aOther) const { + return !(*this == aOther); + } + + unsigned long Length() const { + return mOtherElements.Length() + 1; + } + const T& operator[](unsigned long aIndex) const { + return aIndex == 0 ? mFirstElement : mOtherElements[aIndex - 1]; + } + T& operator[](unsigned long aIndex) { + return aIndex == 0 ? mFirstElement : mOtherElements[aIndex - 1]; + } + + void EnsureLengthAtLeast(unsigned long aMinLen) { + if (aMinLen > 0) { + mOtherElements.EnsureLengthAtLeast(aMinLen - 1); + } + } + + void SetLengthNonZero(unsigned long aNewLen) { + mOtherElements.SetLength(aNewLen - 1); + } + + void TruncateLengthNonZero(unsigned long aNewLen) { + mOtherElements.TruncateLength(aNewLen - 1); + } + +private: + T mFirstElement; + nsTArray mOtherElements; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/only_bitfields.hpp b/bash-5.1/vendor/bindgen/tests/headers/only_bitfields.hpp new file mode 100644 index 0000000..84db058 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/only_bitfields.hpp @@ -0,0 +1,5 @@ +// bindgen-flags: --no-unstable-rust +class C { + bool a: 1; + bool b: 7; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/opaque-tracing.hpp b/bash-5.1/vendor/bindgen/tests/headers/opaque-tracing.hpp new file mode 100644 index 0000000..7356245 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/opaque-tracing.hpp @@ -0,0 +1,21 @@ +// bindgen-flags: --opaque-type=.* --whitelist-function=foo + +class Container; + +// The whitelist tracing should reach the Container type, even though it's +// marked as opaque. +void foo(Container* c); + +template +class Wat { + T foo; +}; + +class OtherOpaque { + int bar; +}; + +class Container { + Wat bar; + OtherOpaque baz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/opaque_in_struct.hpp b/bash-5.1/vendor/bindgen/tests/headers/opaque_in_struct.hpp new file mode 100644 index 0000000..3cffeb2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/opaque_in_struct.hpp @@ -0,0 +1,10 @@ + + +/**
*/ +typedef struct opaque { + int waht; +} opaque; + +struct container { + opaque contained; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/opaque_pointer.hpp b/bash-5.1/vendor/bindgen/tests/headers/opaque_pointer.hpp new file mode 100644 index 0000000..53f8ce1 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/opaque_pointer.hpp @@ -0,0 +1,22 @@ + +/** + *
+ */ +struct OtherOpaque { + int c; +}; + +/** + *
+ */ +template +struct Opaque { + T whatever; +}; + +struct WithOpaquePtr { + Opaque* whatever; + Opaque other; + OtherOpaque t; +}; + diff --git a/bash-5.1/vendor/bindgen/tests/headers/opaque_typedef.hpp b/bash-5.1/vendor/bindgen/tests/headers/opaque_typedef.hpp new file mode 100644 index 0000000..2564073 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/opaque_typedef.hpp @@ -0,0 +1,17 @@ +// bindgen-flags: -- -std=c++11 +template +class RandomTemplate; + +template +class Wat; + +template +class Wat3; + +template<> +class Wat3<3>; + +/**
*/ +typedef RandomTemplate ShouldBeOpaque; + +typedef RandomTemplate ShouldNotBeOpaque; diff --git a/bash-5.1/vendor/bindgen/tests/headers/overflowed_enum.hpp b/bash-5.1/vendor/bindgen/tests/headers/overflowed_enum.hpp new file mode 100644 index 0000000..1f2075a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/overflowed_enum.hpp @@ -0,0 +1,12 @@ +// bindgen-flags: -- -std=c++11 -Wno-narrowing + +enum Foo { + BAP_ARM = 0x93fcb9, + BAP_X86 = 0xb67eed, + BAP_X86_64 = 0xba7b274f, +}; + +enum Bar: unsigned short { + One = 1, + Big = 65538, +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/overloading.hpp b/bash-5.1/vendor/bindgen/tests/headers/overloading.hpp new file mode 100644 index 0000000..3c2b048 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/overloading.hpp @@ -0,0 +1,9 @@ +extern bool Evaluate(char r); +extern bool Evaluate(int x, int y); + +namespace foo { + extern void MyFunction(); +} +namespace bar { + extern void MyFunction(); +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/private.hpp b/bash-5.1/vendor/bindgen/tests/headers/private.hpp new file mode 100644 index 0000000..c0f3ce7 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/private.hpp @@ -0,0 +1,21 @@ + +struct HasPrivate { + int mNotPrivate; + /**
*/ + int mIsPrivate; +}; + + +/**
*/ +struct VeryPrivate { + int mIsPrivate; + int mIsAlsoPrivate; +}; + + +/**
*/ +struct ContradictPrivate { + /**
*/ + int mNotPrivate; + int mIsPrivate; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/public-dtor.hpp b/bash-5.1/vendor/bindgen/tests/headers/public-dtor.hpp new file mode 100644 index 0000000..5d4fb59 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/public-dtor.hpp @@ -0,0 +1,15 @@ + + +namespace cv { +class String { +public: + ~String(); +}; + + +inline +String::~String() +{ +} + +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/redeclaration.hpp b/bash-5.1/vendor/bindgen/tests/headers/redeclaration.hpp new file mode 100644 index 0000000..d536b15 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/redeclaration.hpp @@ -0,0 +1,7 @@ +extern "C" { + void foo(); +} + +extern "C" { + void foo(); +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/ref_argument_array.hpp b/bash-5.1/vendor/bindgen/tests/headers/ref_argument_array.hpp new file mode 100644 index 0000000..dc73fd6 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/ref_argument_array.hpp @@ -0,0 +1,6 @@ + +#define NSID_LENGTH 10 +class nsID { +public: + virtual void ToProvidedString(char (&aDest)[NSID_LENGTH]) = 0; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/reparented_replacement.hpp b/bash-5.1/vendor/bindgen/tests/headers/reparented_replacement.hpp new file mode 100644 index 0000000..4ac2bf0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/reparented_replacement.hpp @@ -0,0 +1,16 @@ +// bindgen-flags: --enable-cxx-namespaces + +namespace foo { + struct Bar { + int baz; + }; +} + +namespace bar { + ///
+ struct Bar_Replacement { + int bazz; + }; +}; + +typedef foo::Bar ReferencesBar; diff --git a/bash-5.1/vendor/bindgen/tests/headers/replace_template_alias.hpp b/bash-5.1/vendor/bindgen/tests/headers/replace_template_alias.hpp new file mode 100644 index 0000000..c325b5a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/replace_template_alias.hpp @@ -0,0 +1,23 @@ +// bindgen-flags: -- --std=c++14 + +namespace JS { +namespace detail { + +/// Notice how this doesn't use T. +template +using MaybeWrapped = int; + +} + +template +class Rooted { + detail::MaybeWrapped ptr; +}; + +} + +/// But the replacement type does use T! +/// +///
+template +using replaces_MaybeWrapped = T; diff --git a/bash-5.1/vendor/bindgen/tests/headers/replace_use.hpp b/bash-5.1/vendor/bindgen/tests/headers/replace_use.hpp new file mode 100644 index 0000000..de44eb1 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/replace_use.hpp @@ -0,0 +1,15 @@ +template +struct nsTArray { + int x; +}; +/** + *
+ */ +template +struct nsTArray_Simple { + unsigned int y; +}; + +struct Test { + nsTArray a; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/replaces_double.hpp b/bash-5.1/vendor/bindgen/tests/headers/replaces_double.hpp new file mode 100644 index 0000000..1a78b0d --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/replaces_double.hpp @@ -0,0 +1,20 @@ +// bindgen-flags: --blacklist-type Wrapper -- --std=c++11 + +template +struct Wrapper { + struct Wrapped { + T t; + }; + using Type = Wrapped; +}; + +template +class Rooted { + using MaybeWrapped = typename Wrapper::Type; + MaybeWrapped ptr; + + /** + *
+ */ + using MaybeWrapped_simple = T; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/resolved_type_def_function.h b/bash-5.1/vendor/bindgen/tests/headers/resolved_type_def_function.h new file mode 100644 index 0000000..139b8c3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/resolved_type_def_function.h @@ -0,0 +1,2 @@ +typedef void (FuncType) (); +extern FuncType Func; \ No newline at end of file diff --git a/bash-5.1/vendor/bindgen/tests/headers/same_struct_name_in_different_namespaces.hpp b/bash-5.1/vendor/bindgen/tests/headers/same_struct_name_in_different_namespaces.hpp new file mode 100644 index 0000000..fe68584 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/same_struct_name_in_different_namespaces.hpp @@ -0,0 +1,12 @@ +namespace JS { + + struct Zone; + + namespace shadow { + + struct Zone { + int x; + int y; + }; + } +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/size_t_template.hpp b/bash-5.1/vendor/bindgen/tests/headers/size_t_template.hpp new file mode 100644 index 0000000..6045c69 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/size_t_template.hpp @@ -0,0 +1,8 @@ +template +class Array { + T inner[N]; +}; + +class C { + Array arr; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_containing_forward_declared_struct.h b/bash-5.1/vendor/bindgen/tests/headers/struct_containing_forward_declared_struct.h new file mode 100644 index 0000000..d38aca2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_containing_forward_declared_struct.h @@ -0,0 +1,7 @@ +struct a { + struct b* val_a; +}; + +struct b { + int val_b; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct.h new file mode 100644 index 0000000..1617d7a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct.h @@ -0,0 +1,6 @@ +struct foo { + struct { + int a; + int b; + } bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_array.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_array.h new file mode 100644 index 0000000..9ea977e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_array.h @@ -0,0 +1,10 @@ +struct foo { + struct { + int a; + int b; + } bar[2]; + struct { + int a; + int b; + } baz[2][3][4]; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_pointer.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_pointer.h new file mode 100644 index 0000000..0c486d8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_struct_pointer.h @@ -0,0 +1,6 @@ +struct foo { + struct { + int a; + int b; + } *bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_union.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_union.h new file mode 100644 index 0000000..3a92b94 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_union.h @@ -0,0 +1,6 @@ +struct foo { + union { + unsigned int a; + unsigned short b; + } bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_struct.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_struct.h new file mode 100644 index 0000000..f8ac422 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_struct.h @@ -0,0 +1,6 @@ +struct foo { + struct { + unsigned int a; + unsigned int b; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_union.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_union.h new file mode 100644 index 0000000..7158e72 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_anon_unnamed_union.h @@ -0,0 +1,6 @@ +struct foo { + union { + unsigned int a; + unsigned short b; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_bitfields.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_bitfields.h new file mode 100644 index 0000000..107fb13 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_bitfields.h @@ -0,0 +1,13 @@ +// bindgen-flags: --no-unstable-rust +struct bitfield { + unsigned short + a :1, + b :1, + c :1, + :1, + :2, + d :2; + int e; + unsigned int f : 2; + unsigned int g : 32; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_derive_debug.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_derive_debug.h new file mode 100644 index 0000000..98ba1b3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_derive_debug.h @@ -0,0 +1,15 @@ +struct LittleArray { + int a[32]; +}; + +struct BigArray{ + int a[33]; +}; + +struct WithLittleArray { + struct LittleArray a; +}; + +struct WithBigArray { + struct BigArray a; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_nesting.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_nesting.h new file mode 100644 index 0000000..9d7fa17 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_nesting.h @@ -0,0 +1,17 @@ +struct foo { + unsigned int a; + union { + unsigned int b; + struct { + unsigned short c1; + unsigned short c2; + }; + + struct { + unsigned char d1; + unsigned char d2; + unsigned char d3; + unsigned char d4; + }; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_packing.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_packing.h new file mode 100644 index 0000000..1b9fe13 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_packing.h @@ -0,0 +1,4 @@ +struct a { + char b; + short c; +} __attribute__((packed)); diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_struct.h b/bash-5.1/vendor/bindgen/tests/headers/struct_with_struct.h new file mode 100644 index 0000000..78b1cc8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_struct.h @@ -0,0 +1,6 @@ +struct foo { + struct { + unsigned int x; + unsigned int y; + } bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/struct_with_typedef_template_arg.hpp b/bash-5.1/vendor/bindgen/tests/headers/struct_with_typedef_template_arg.hpp new file mode 100644 index 0000000..7fed21a --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/struct_with_typedef_template_arg.hpp @@ -0,0 +1,4 @@ +template +struct Proxy { + typedef void (*foo)(T* bar); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/template.hpp b/bash-5.1/vendor/bindgen/tests/headers/template.hpp new file mode 100644 index 0000000..c13643c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/template.hpp @@ -0,0 +1,144 @@ +template class Foo { + T m_member; + T* m_member_ptr; + T m_member_arr[1]; +}; + +void bar(Foo foo); + +template +class D { + typedef Foo MyFoo; + + MyFoo m_foo; + + template + class U { + MyFoo m_nested_foo; + Z m_baz; + }; +}; + +template +class Rooted { + T* prev; + Rooted* next; + T ptr; +}; + +class RootedContainer { + Rooted root; +}; + +template +class WithDtor; + +typedef WithDtor WithDtorIntFwd; + +template +class WithDtor { + T member; + ~WithDtor() {} +}; + +class PODButContainsDtor { + WithDtorIntFwd member; +}; + + +/**
*/ +template +class Opaque { + T member; +}; + +class POD { + Opaque opaque_member; +}; + +/** + *
+ */ +template +class Nested { + T* buff; +}; + +template +class NestedBase { + T* buff; +}; + +template +class NestedReplaced: public NestedBase { +}; + +template +class Incomplete; + +template +class NestedContainer { + T c; +private: + NestedReplaced nested; + Incomplete inc; +}; + +template +class Incomplete { + T d; +}; + +class Untemplated {}; + +template +class Templated { + Untemplated m_untemplated; +}; + +/** + * If the replacement doesn't happen at the parse level the container would be + * copy and the replacement wouldn't, so this wouldn't compile. + * + *
+ */ +template +class ReplacedWithDestructor { + T* buff; + ~ReplacedWithDestructor() {}; +}; + +template +class ReplacedWithoutDestructor { + T* buff; +}; + +template +class ReplacedWithoutDestructorFwd; + +template +class ShouldNotBeCopiable { + ReplacedWithoutDestructor m_member; +}; + +template +class ShouldNotBeCopiableAsWell { + ReplacedWithoutDestructorFwd m_member; +}; + +/** + * If the replacement doesn't happen at the parse level the container would be + * copy and the replacement wouldn't, so this wouldn't compile. + * + *
+ */ +template +class ReplacedWithDestructorDeclaredAfter { + T* buff; + ~ReplacedWithDestructorDeclaredAfter() {}; +}; + +template +class TemplateWithVar { + static T var = 0; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/template_alias.hpp b/bash-5.1/vendor/bindgen/tests/headers/template_alias.hpp new file mode 100644 index 0000000..646d9f4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/template_alias.hpp @@ -0,0 +1,13 @@ +// bindgen-flags: -- -std=c++14 + +namespace JS { +namespace detail { + template + using Wrapped = T; +} + +template +struct Rooted { + detail::Wrapped ptr; +}; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/template_alias_basic.hpp b/bash-5.1/vendor/bindgen/tests/headers/template_alias_basic.hpp new file mode 100644 index 0000000..964f6e2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/template_alias_basic.hpp @@ -0,0 +1,4 @@ +// bindgen-flags: -- -std=c++11 + +template +using Wrapped = T; diff --git a/bash-5.1/vendor/bindgen/tests/headers/template_alias_namespace.hpp b/bash-5.1/vendor/bindgen/tests/headers/template_alias_namespace.hpp new file mode 100644 index 0000000..bd63716 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/template_alias_namespace.hpp @@ -0,0 +1,13 @@ +// bindgen-flags: --enable-cxx-namespaces -- -std=c++14 + +namespace JS { +namespace detail { + template + using Wrapped = T; +} + +template +struct Rooted { + detail::Wrapped ptr; +}; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/template_typedef_transitive_param.hpp b/bash-5.1/vendor/bindgen/tests/headers/template_typedef_transitive_param.hpp new file mode 100644 index 0000000..2269ac3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/template_typedef_transitive_param.hpp @@ -0,0 +1,7 @@ +template +struct Wrapper { + struct Wrapped { + T t; + }; + using Type = Wrapped; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/template_typedefs.hpp b/bash-5.1/vendor/bindgen/tests/headers/template_typedefs.hpp new file mode 100644 index 0000000..5e13dcd --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/template_typedefs.hpp @@ -0,0 +1,8 @@ +typedef void (*foo)(int); + +template +class Foo { + typedef T Char; + typedef Char* FooPtrTypedef; + typedef bool (*nsCOMArrayEnumFunc)(T* aElement, void* aData); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/templateref_opaque.hpp b/bash-5.1/vendor/bindgen/tests/headers/templateref_opaque.hpp new file mode 100644 index 0000000..ca154c3 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/templateref_opaque.hpp @@ -0,0 +1,11 @@ + +namespace detail { +template +struct PointerType { + typedef T* Type; +}; +} +template +class UniquePtr { + typedef typename detail::PointerType Pointer; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/type-referenced-by-whitelisted-function.h b/bash-5.1/vendor/bindgen/tests/headers/type-referenced-by-whitelisted-function.h new file mode 100644 index 0000000..86b0030 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/type-referenced-by-whitelisted-function.h @@ -0,0 +1,7 @@ +// bindgen-flags: --whitelist-function dl_iterate_phdr + +struct dl_phdr_info { + int x; +}; + +int dl_iterate_phdr(struct dl_phdr_info *); diff --git a/bash-5.1/vendor/bindgen/tests/headers/type_alias_empty.hpp b/bash-5.1/vendor/bindgen/tests/headers/type_alias_empty.hpp new file mode 100644 index 0000000..f0760c8 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/type_alias_empty.hpp @@ -0,0 +1,10 @@ +// bindgen-flags: --whitelist-type bool_constant -- -std=c++11 + +// NB: The --whitelist-type is done to trigger the traversal of the types on +// codegen in order to trigger #67. + +template +struct integral_constant {}; + +template +using bool_constant = integral_constant; diff --git a/bash-5.1/vendor/bindgen/tests/headers/type_alias_partial_template_especialization.hpp b/bash-5.1/vendor/bindgen/tests/headers/type_alias_partial_template_especialization.hpp new file mode 100644 index 0000000..dfc3678 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/type_alias_partial_template_especialization.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: -- -std=c++14 +template using MaybeWrapped = A; + +template +class Rooted { + MaybeWrapped ptr; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/type_alias_template_specialized.hpp b/bash-5.1/vendor/bindgen/tests/headers/type_alias_template_specialized.hpp new file mode 100644 index 0000000..a2d32b5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/type_alias_template_specialized.hpp @@ -0,0 +1,9 @@ +// bindgen-flags: --whitelist-type Rooted -- -std=c++14 + +template using MaybeWrapped = a; +class Rooted { + MaybeWrapped ptr; +}; + +///
+template using replaces_MaybeWrapped = a; diff --git a/bash-5.1/vendor/bindgen/tests/headers/typedefd-array-as-function-arg.h b/bash-5.1/vendor/bindgen/tests/headers/typedefd-array-as-function-arg.h new file mode 100644 index 0000000..9379059 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/typedefd-array-as-function-arg.h @@ -0,0 +1,3 @@ +// foo.h +typedef float myVector3[3]; +void modifyVectorFunc(myVector3 v); diff --git a/bash-5.1/vendor/bindgen/tests/headers/typeref.hpp b/bash-5.1/vendor/bindgen/tests/headers/typeref.hpp new file mode 100644 index 0000000..b94c98e --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/typeref.hpp @@ -0,0 +1,28 @@ +struct nsFoo; + +namespace mozilla { + +struct FragmentOrURL { bool mIsLocalRef; }; +struct Position { }; + +} // namespace mozilla + +class Bar { + nsFoo* mFoo; +}; + +namespace mozilla { + +template +struct StyleShapeSource { + union { + Position* mPosition; + FragmentOrURL* mFragmentOrURL; + }; +}; + +} // namespace mozilla + +struct nsFoo { + mozilla::StyleShapeSource mBar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union-in-ns.hpp b/bash-5.1/vendor/bindgen/tests/headers/union-in-ns.hpp new file mode 100644 index 0000000..68b8f72 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union-in-ns.hpp @@ -0,0 +1,5 @@ +// bindgen-flags: --enable-cxx-namespaces + +union bar { + int baz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_dtor.hpp b/bash-5.1/vendor/bindgen/tests/headers/union_dtor.hpp new file mode 100644 index 0000000..399dc89 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_dtor.hpp @@ -0,0 +1,5 @@ +union UnionWithDtor { + ~UnionWithDtor(); + int mFoo; + void* mBar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_fields.hpp b/bash-5.1/vendor/bindgen/tests/headers/union_fields.hpp new file mode 100644 index 0000000..aec3a7f --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_fields.hpp @@ -0,0 +1,5 @@ +typedef union { + int mInt; + float mFloat; + void* mPointer; +} nsStyleUnion; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_template.hpp b/bash-5.1/vendor/bindgen/tests/headers/union_template.hpp new file mode 100644 index 0000000..0d0a9bb --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_template.hpp @@ -0,0 +1,19 @@ +template +struct NastyStruct { + bool mIsSome; + union { + void* mFoo; + unsigned long mDummy; + } mStorage; + + union { + short wat; + int* wut; + }; +}; + +template +union Whatever { + void* mTPtr; + int mInt; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct.h new file mode 100644 index 0000000..7f8dec9 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct.h @@ -0,0 +1,6 @@ +union foo { + struct { + unsigned int a; + unsigned int b; + } bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct_bitfield.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct_bitfield.h new file mode 100644 index 0000000..24c7dce --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_struct_bitfield.h @@ -0,0 +1,8 @@ +// bindgen-flags: --no-unstable-rust +union foo { + int a; + struct { + int b : 7; + int c : 25; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_union.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_union.h new file mode 100644 index 0000000..212431b --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_union.h @@ -0,0 +1,6 @@ +union foo { + union { + unsigned int a; + unsigned short b; + } bar; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_struct.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_struct.h new file mode 100644 index 0000000..7955804 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_struct.h @@ -0,0 +1,9 @@ +union pixel { + unsigned int rgba; + struct { + unsigned char r; + unsigned char g; + unsigned char b; + unsigned char a; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_union.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_union.h new file mode 100644 index 0000000..7580771 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_anon_unnamed_union.h @@ -0,0 +1,7 @@ +union foo { + unsigned int a; + union { + unsigned short b; + unsigned char c; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_big_member.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_big_member.h new file mode 100644 index 0000000..6347d6c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_big_member.h @@ -0,0 +1,14 @@ +union WithBigArray { + int a; + int b[33]; +}; + +union WithBigArray2 { + int a; + char b[33]; +}; + +union WithBigMember { + int a; + union WithBigArray b; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/union_with_nesting.h b/bash-5.1/vendor/bindgen/tests/headers/union_with_nesting.h new file mode 100644 index 0000000..cd907d5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/union_with_nesting.h @@ -0,0 +1,14 @@ +union foo { + unsigned int a; + struct { + union { + unsigned short b1; + unsigned short b2; + }; + + union { + unsigned short c1; + unsigned short c2; + }; + }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/unknown_attr.h b/bash-5.1/vendor/bindgen/tests/headers/unknown_attr.h new file mode 100644 index 0000000..f87e9f0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/unknown_attr.h @@ -0,0 +1,6 @@ +typedef struct { + long long __clang_max_align_nonce1 + __attribute__((__aligned__(__alignof__(long long)))); + long double __clang_max_align_nonce2 + __attribute__((__aligned__(__alignof__(long double)))); +} max_align_t; diff --git a/bash-5.1/vendor/bindgen/tests/headers/use-core.h b/bash-5.1/vendor/bindgen/tests/headers/use-core.h new file mode 100644 index 0000000..42bb10d --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/use-core.h @@ -0,0 +1,8 @@ +// bindgen-flags: --use-core --raw-line "extern crate core;" + +struct foo { + int a, b; + void* bar; +}; + +typedef void (*fooFunction)(int bar); diff --git a/bash-5.1/vendor/bindgen/tests/headers/using.hpp b/bash-5.1/vendor/bindgen/tests/headers/using.hpp new file mode 100644 index 0000000..ba07b9c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/using.hpp @@ -0,0 +1,11 @@ +// bindgen-flags: -- -std=c++11 + +template +class Point { + T x; + T y; +}; + +typedef Point IntPoint2D; + +using IntVec2D = Point; diff --git a/bash-5.1/vendor/bindgen/tests/headers/var-tracing.hpp b/bash-5.1/vendor/bindgen/tests/headers/var-tracing.hpp new file mode 100644 index 0000000..0d0b0cc --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/var-tracing.hpp @@ -0,0 +1,10 @@ +// bindgen-flags: --whitelist-type Baz + +struct Bar { + const int m_baz; + Bar(int baz); +}; + +class Baz { + static const Bar FOO[]; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/variadic-method.hpp b/bash-5.1/vendor/bindgen/tests/headers/variadic-method.hpp new file mode 100644 index 0000000..78a8eb4 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/variadic-method.hpp @@ -0,0 +1,6 @@ + +void foo(const char* fmt, ...); + +struct Bar { + void foo(const char* fmt, ...); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/variadic_template_function.hpp b/bash-5.1/vendor/bindgen/tests/headers/variadic_template_function.hpp new file mode 100644 index 0000000..4942d8f --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/variadic_template_function.hpp @@ -0,0 +1,6 @@ + +template +class VariadicFunctionObject { +public: + int add_em_up(T count,...); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/vector.hpp b/bash-5.1/vendor/bindgen/tests/headers/vector.hpp new file mode 100644 index 0000000..4707f77 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/vector.hpp @@ -0,0 +1,3 @@ +struct foo { + __attribute__((__vector_size__(1 * sizeof(long long)))) long long mMember; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/virtual_dtor.hpp b/bash-5.1/vendor/bindgen/tests/headers/virtual_dtor.hpp new file mode 100644 index 0000000..c35dcab --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/virtual_dtor.hpp @@ -0,0 +1,3 @@ +struct nsSlots { + virtual ~nsSlots(); +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/virtual_inheritance.hpp b/bash-5.1/vendor/bindgen/tests/headers/virtual_inheritance.hpp new file mode 100644 index 0000000..5198c51 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/virtual_inheritance.hpp @@ -0,0 +1,16 @@ + +class A { + int foo; +}; + +class B: public virtual A { + int bar; +}; + +class C: public virtual A { + int baz; +}; + +class D: public C, public B { + int bazz; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/virtual_overloaded.hpp b/bash-5.1/vendor/bindgen/tests/headers/virtual_overloaded.hpp new file mode 100644 index 0000000..8aea8a1 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/virtual_overloaded.hpp @@ -0,0 +1,5 @@ +class C { +public: + virtual void do_thing(char) { }; + virtual void do_thing(int) { }; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/vtable_recursive_sig.hpp b/bash-5.1/vendor/bindgen/tests/headers/vtable_recursive_sig.hpp new file mode 100644 index 0000000..8729be0 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/vtable_recursive_sig.hpp @@ -0,0 +1,11 @@ +// bindgen-flags: -- -std=c++11 + +class Derived; +class Base { +public: + virtual Derived* AsDerived() { return nullptr; } +}; + +class Derived final : public Base { + virtual Derived* AsDerived() override { return this; } +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/weird_bitfields.hpp b/bash-5.1/vendor/bindgen/tests/headers/weird_bitfields.hpp new file mode 100644 index 0000000..755681c --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/weird_bitfields.hpp @@ -0,0 +1,35 @@ +// bindgen-flags: --no-unstable-rust +// You can guess where this is taken from... +enum nsStyleSVGOpacitySource { + eStyleSVGOpacitySource_Normal, + eStyleSVGOpacitySource_ContextFillOpacity, + eStyleSVGOpacitySource_ContextStrokeOpacity +}; + +class Weird { + unsigned int mStrokeDasharrayLength; + unsigned int bitTest: 16; + unsigned int bitTest2: 15; + unsigned char mClipRule; // [inherited] + unsigned char mColorInterpolation; // [inherited] see nsStyleConsts.h + unsigned char mColorInterpolationFilters; // [inherited] see nsStyleConsts.h + unsigned char mFillRule; // [inherited] see nsStyleConsts.h + unsigned char mImageRendering; // [inherited] see nsStyleConsts.h + unsigned char mPaintOrder; // [inherited] see nsStyleConsts.h + unsigned char mShapeRendering; // [inherited] see nsStyleConsts.h + unsigned char mStrokeLinecap; // [inherited] see nsStyleConsts.h + unsigned char mStrokeLinejoin; // [inherited] see nsStyleConsts.h + unsigned char mTextAnchor; // [inherited] see nsStyleConsts.h + unsigned char mTextRendering; // [inherited] see nsStyleConsts.h + + // In SVG glyphs, whether we inherit fill or stroke opacity from the outer + // text object. + // Use 3 bits to avoid signedness problems in MSVC. + nsStyleSVGOpacitySource mFillOpacitySource : 3; + nsStyleSVGOpacitySource mStrokeOpacitySource : 3; + + // SVG glyph outer object inheritance for other properties + bool mStrokeDasharrayFromObject : 1; + bool mStrokeDashoffsetFromObject : 1; + bool mStrokeWidthFromObject : 1; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/what_is_going_on.hpp b/bash-5.1/vendor/bindgen/tests/headers/what_is_going_on.hpp new file mode 100644 index 0000000..078c1ad --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/what_is_going_on.hpp @@ -0,0 +1,19 @@ + +struct UnknownUnits {}; +typedef float Float; + +template +struct PointTyped { + F x; + F y; + + static PointTyped FromUnknownPoint(const PointTyped& aPoint) { + return PointTyped(aPoint.x, aPoint.y); + } + + PointTyped ToUnknownPoint() const { + return PointTyped(this->x, this->y); + } +}; + +typedef PointTyped IntPoint; diff --git a/bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces-basic.hpp b/bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces-basic.hpp new file mode 100644 index 0000000..2eaa874 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces-basic.hpp @@ -0,0 +1,10 @@ +// bindgen-flags: --enable-cxx-namespaces --whitelist-type outer::inner::Helper + +namespace outer { + namespace inner { + struct Helper {}; + } + struct Test { + inner::Helper helper; + }; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces.hpp b/bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces.hpp new file mode 100644 index 0000000..d34cbe9 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/whitelist-namespaces.hpp @@ -0,0 +1,10 @@ +// bindgen-flags: --enable-cxx-namespaces --whitelist-type '.*' + +namespace outer { + namespace inner { + struct Helper {}; + } + struct Test { + inner::Helper helper; + }; +} diff --git a/bash-5.1/vendor/bindgen/tests/headers/whitelist_basic.hpp b/bash-5.1/vendor/bindgen/tests/headers/whitelist_basic.hpp new file mode 100644 index 0000000..8424f75 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/whitelist_basic.hpp @@ -0,0 +1,16 @@ +// bindgen-flags: --whitelist-type WhitelistMe + +template +class WhitelistMe { + class Inner { + T bar; + }; + + int foo; + Inner bar; +}; + +struct DontWhitelistMe { + void* foo; + double _Complex noComplexGenerated; +}; diff --git a/bash-5.1/vendor/bindgen/tests/headers/whitelist_fix.hpp b/bash-5.1/vendor/bindgen/tests/headers/whitelist_fix.hpp new file mode 100644 index 0000000..d0abda5 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/whitelist_fix.hpp @@ -0,0 +1,4 @@ +// bindgen-flags: --whitelist-function 'Servo_.*' --blacklist-type Test --raw-line "pub enum Test {}" + +struct Test {}; +extern "C" void Servo_Test(Test* a); diff --git a/bash-5.1/vendor/bindgen/tests/headers/whitelist_vars.h b/bash-5.1/vendor/bindgen/tests/headers/whitelist_vars.h new file mode 100644 index 0000000..07fa281 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/headers/whitelist_vars.h @@ -0,0 +1,4 @@ +#define NONE 0 +#define FOO 5 +#define FOOB -2 +#define FOOBAR (-10) diff --git a/bash-5.1/vendor/bindgen/tests/tests.rs b/bash-5.1/vendor/bindgen/tests/tests.rs new file mode 100644 index 0000000..05c8ad2 --- /dev/null +++ b/bash-5.1/vendor/bindgen/tests/tests.rs @@ -0,0 +1,140 @@ +extern crate clap; +extern crate diff; +extern crate bindgen; +extern crate shlex; + +use bindgen::Builder; +use std::fs; +use std::io::{BufRead, BufReader, Error, ErrorKind, Read, Write}; +use std::path::PathBuf; + +#[path="../src/options.rs"] +mod options; +use options::builder_from_flags; + +fn compare_generated_header(header: &PathBuf, + builder: Builder) + -> Result<(), Error> { + let file_name = try!(header.file_name() + .ok_or(Error::new(ErrorKind::Other, "spawn_bindgen expects a file"))); + + let mut expected = PathBuf::from(header); + expected.pop(); + expected.pop(); + expected.push("expectations"); + expected.push("tests"); + expected.push(file_name); + expected.set_extension("rs"); + + // We skip the generate() error here so we get a full diff below + let output = match builder.generate() { + Ok(bindings) => bindings.to_string(), + Err(_) => "".to_string(), + }; + + let mut buffer = String::new(); + { + if let Ok(expected_file) = fs::File::open(&expected) { + try!(BufReader::new(expected_file).read_to_string(&mut buffer)); + } + } + + if output == buffer { + if !output.is_empty() { + return Ok(()); + } + return Err(Error::new(ErrorKind::Other, + "Something's gone really wrong!")); + } + + println!("diff expected generated"); + println!("--- expected: {:?}", expected); + println!("+++ generated from: {:?}", header); + + for diff in diff::lines(&buffer, &output) { + match diff { + diff::Result::Left(l) => println!("-{}", l), + diff::Result::Both(l, _) => println!(" {}", l), + diff::Result::Right(r) => println!("+{}", r), + } + } + + // Override the diff. + { + let mut expected_file = try!(fs::File::create(&expected)); + try!(expected_file.write_all(output.as_bytes())); + } + + Err(Error::new(ErrorKind::Other, "Header and binding differ!")) +} + +fn create_bindgen_builder(header: &PathBuf) + -> Result, Error> { + let source = try!(fs::File::open(header)); + let reader = BufReader::new(source); + + // Scoop up bindgen-flags from test header + let mut flags = Vec::with_capacity(2); + + for line in reader.lines().take(2) { + let line = try!(line); + if line.contains("bindgen-flags: ") { + let extra_flags = line.split("bindgen-flags: ") + .last() + .and_then(shlex::split) + .unwrap(); + flags.extend(extra_flags.into_iter()); + } else if line.contains("bindgen-unstable") && + cfg!(feature = "llvm_stable") { + return Ok(None); + } + } + + // Fool builder_from_flags() into believing it has real env::args_os... + // - add "bindgen" as executable name 0th element + // - add header filename as 1st element + // - prepend raw lines so they're in the right order for expected output + // - append the test header's bindgen flags + let header_str = try!(header.to_str() + .ok_or(Error::new(ErrorKind::Other, "Invalid header file name"))); + + let prepend = ["bindgen", + header_str, + "--raw-line", + "", + "--raw-line", + "#![allow(non_snake_case)]", + "--raw-line", + ""]; + + let args = prepend.into_iter() + .map(ToString::to_string) + .chain(flags.into_iter()); + + builder_from_flags(args) + .map(|(builder, _)| Some(builder.no_unstable_rust())) +} + +macro_rules! test_header { + ($function:ident, $header:expr) => ( + #[test] + fn $function() { + let header = PathBuf::from($header); + let result = create_bindgen_builder(&header) + .and_then(|builder| { + if let Some(builder) = builder { + compare_generated_header(&header, builder) + } else { + Ok(()) + } + }); + + if let Err(err) = result { + panic!("{}", err); + } + } + ) +} + +// This file is generated by build.rs +include!(concat!(env!("OUT_DIR"), "/tests.rs")); diff --git a/bash-5.1/vendor/bitflags-0.7.0/.cargo-checksum.json b/bash-5.1/vendor/bitflags-0.7.0/.cargo-checksum.json new file mode 100644 index 0000000..69a203a --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"db8c2e9ea912c5f3d2d89cf4cf936c448300e356b0fb533db8875923cb135256","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"8cfbc986af45867d9e620188af2392320fe6e0d9536753ba415c94ab522f5fb5","src/lib.rs":"618ce383bb219725363fba174fc66beb4874d9682e5da953f9e3e9cb3f786d5f","tests/external.rs":"546e549ec831876a5dc272bd0537adc9e9886c6da54656c825e7bffc079e2c74","tests/external_no_std.rs":"48929f5109aabc156442d5ae2ab07b4bce5d648488bf49dba725f6ab23bcb48a"},"package":"aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d"} \ No newline at end of file diff --git a/bash-5.1/vendor/bitflags-0.7.0/Cargo.toml b/bash-5.1/vendor/bitflags-0.7.0/Cargo.toml new file mode 100644 index 0000000..042497e --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/Cargo.toml @@ -0,0 +1,13 @@ +[package] + +name = "bitflags" +version = "0.7.0" +authors = ["The Rust Project Developers"] +license = "MIT/Apache-2.0" +readme = "README.md" +repository = "https://github.com/rust-lang/bitflags" +homepage = "https://github.com/rust-lang/bitflags" +documentation = "https://doc.rust-lang.org/bitflags" +description = """ +A macro to generate structures which behave like bitflags. +""" diff --git a/bash-5.1/vendor/bitflags-0.7.0/LICENSE-APACHE b/bash-5.1/vendor/bitflags-0.7.0/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/bitflags-0.7.0/LICENSE-MIT b/bash-5.1/vendor/bitflags-0.7.0/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/bitflags-0.7.0/README.md b/bash-5.1/vendor/bitflags-0.7.0/README.md new file mode 100644 index 0000000..3edd8a3 --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/README.md @@ -0,0 +1,24 @@ +bitflags +======== + +A Rust macro to generate structures which behave like a set of bitflags + +[![Build Status](https://travis-ci.org/rust-lang-nursery/bitflags.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/bitflags) + +[Documentation](https://doc.rust-lang.org/bitflags) + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +bitflags = "0.6" +``` + +and this to your crate root: + +```rust +#[macro_use] +extern crate bitflags; +``` diff --git a/bash-5.1/vendor/bitflags-0.7.0/src/lib.rs b/bash-5.1/vendor/bitflags-0.7.0/src/lib.rs new file mode 100644 index 0000000..698799d --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/src/lib.rs @@ -0,0 +1,808 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A typesafe bitmask flag generator. + +#![no_std] + +#[cfg(test)] +#[macro_use] +extern crate std; + +// Re-export libstd/libcore using an alias so that the macros can work in no_std +// crates while remaining compatible with normal crates. +#[allow(private_in_public)] +#[doc(hidden)] +pub use core as __core; + +/// The `bitflags!` macro generates a `struct` that holds a set of C-style +/// bitmask flags. It is useful for creating typesafe wrappers for C APIs. +/// +/// The flags should only be defined for integer types, otherwise unexpected +/// type errors may occur at compile time. +/// +/// # Example +/// +/// ```{.rust} +/// #[macro_use] +/// extern crate bitflags; +/// +/// bitflags! { +/// flags Flags: u32 { +/// const FLAG_A = 0b00000001, +/// const FLAG_B = 0b00000010, +/// const FLAG_C = 0b00000100, +/// const FLAG_ABC = FLAG_A.bits +/// | FLAG_B.bits +/// | FLAG_C.bits, +/// } +/// } +/// +/// fn main() { +/// let e1 = FLAG_A | FLAG_C; +/// let e2 = FLAG_B | FLAG_C; +/// assert_eq!((e1 | e2), FLAG_ABC); // union +/// assert_eq!((e1 & e2), FLAG_C); // intersection +/// assert_eq!((e1 - e2), FLAG_A); // set difference +/// assert_eq!(!e2, FLAG_A); // set complement +/// } +/// ``` +/// +/// The generated `struct`s can also be extended with type and trait +/// implementations: +/// +/// ```{.rust} +/// #[macro_use] +/// extern crate bitflags; +/// +/// use std::fmt; +/// +/// bitflags! { +/// flags Flags: u32 { +/// const FLAG_A = 0b00000001, +/// const FLAG_B = 0b00000010, +/// } +/// } +/// +/// impl Flags { +/// pub fn clear(&mut self) { +/// self.bits = 0; // The `bits` field can be accessed from within the +/// // same module where the `bitflags!` macro was invoked. +/// } +/// } +/// +/// impl fmt::Display for Flags { +/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +/// write!(f, "hi!") +/// } +/// } +/// +/// fn main() { +/// let mut flags = FLAG_A | FLAG_B; +/// flags.clear(); +/// assert!(flags.is_empty()); +/// assert_eq!(format!("{}", flags), "hi!"); +/// assert_eq!(format!("{:?}", FLAG_A | FLAG_B), "FLAG_A | FLAG_B"); +/// assert_eq!(format!("{:?}", FLAG_B), "FLAG_B"); +/// } +/// ``` +/// +/// # Visibility +/// +/// The generated struct and its associated flag constants are not exported +/// out of the current module by default. A definition can be exported out of +/// the current module by adding `pub` before `flags`: +/// +/// ```{.rust},ignore +/// #[macro_use] +/// extern crate bitflags; +/// +/// mod example { +/// bitflags! { +/// pub flags Flags1: u32 { +/// const FLAG_A = 0b00000001, +/// } +/// } +/// bitflags! { +/// flags Flags2: u32 { +/// const FLAG_B = 0b00000010, +/// } +/// } +/// } +/// +/// fn main() { +/// let flag1 = example::FLAG_A; +/// let flag2 = example::FLAG_B; // error: const `FLAG_B` is private +/// } +/// ``` +/// +/// # Attributes +/// +/// Attributes can be attached to the generated `struct` by placing them +/// before the `flags` keyword. +/// +/// # Trait implementations +/// +/// The `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord` and `Hash` +/// traits automatically derived for the `struct` using the `derive` attribute. +/// Additional traits can be derived by providing an explicit `derive` +/// attribute on `flags`. +/// +/// The `Extend` and `FromIterator` traits are implemented for the `struct`, +/// too: `Extend` adds the union of the instances of the `struct` iterated over, +/// while `FromIterator` calculates the union. +/// +/// The `Debug` trait is also implemented by displaying the bits value of the +/// internal struct. +/// +/// ## Operators +/// +/// The following operator traits are implemented for the generated `struct`: +/// +/// - `BitOr` and `BitOrAssign`: union +/// - `BitAnd` and `BitAndAssign`: intersection +/// - `BitXor` and `BitXorAssign`: toggle +/// - `Sub` and `SubAssign`: set difference +/// - `Not`: set complement +/// +/// As long as the assignment operators are unstable rust feature they are only +/// available with the crate feature `assignment_ops` enabled. +/// +/// # Methods +/// +/// The following methods are defined for the generated `struct`: +/// +/// - `empty`: an empty set of flags +/// - `all`: the set of all flags +/// - `bits`: the raw value of the flags currently stored +/// - `from_bits`: convert from underlying bit representation, unless that +/// representation contains bits that do not correspond to a flag +/// - `from_bits_truncate`: convert from underlying bit representation, dropping +/// any bits that do not correspond to flags +/// - `is_empty`: `true` if no flags are currently stored +/// - `is_all`: `true` if all flags are currently set +/// - `intersects`: `true` if there are flags common to both `self` and `other` +/// - `contains`: `true` all of the flags in `other` are contained within `self` +/// - `insert`: inserts the specified flags in-place +/// - `remove`: removes the specified flags in-place +/// - `toggle`: the specified flags will be inserted if not present, and removed +/// if they are. +#[macro_export] +macro_rules! bitflags { + ($(#[$attr:meta])* pub flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + }) => { + #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] + $(#[$attr])* + pub struct $BitFlags { + bits: $T, + } + + $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + + bitflags! { + @_impl flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; + ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + }) => { + #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] + $(#[$attr])* + struct $BitFlags { + bits: $T, + } + + $($(#[$Flag_attr])* const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + + bitflags! { + @_impl flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; + (@_impl flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + }) => { + impl $crate::__core::fmt::Debug for $BitFlags { + fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { + // This convoluted approach is to handle #[cfg]-based flag + // omission correctly. Some of the $Flag variants may not be + // defined in this module so we create an inner module which + // defines *all* flags to the value of 0. We then create a + // second inner module that defines all of the flags with #[cfg] + // to their real values. Afterwards the glob will import + // variants from the second inner module, shadowing all + // defined variants, leaving only the undefined ones with the + // bit value of 0. + #[allow(dead_code)] + #[allow(unused_assignments)] + mod dummy { + // We can't use the real $BitFlags struct because it may be + // private, which prevents us from using it to define + // public constants. + pub struct $BitFlags { + bits: u64, + } + mod real_flags { + use super::$BitFlags; + $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { + bits: super::super::$Flag.bits as u64 + };)+ + } + // Now we define the "undefined" versions of the flags. + // This way, all the names exist, even if some are #[cfg]ed + // out. + $(const $Flag: $BitFlags = $BitFlags { bits: 0 };)+ + + #[inline] + pub fn fmt(self_: u64, + f: &mut $crate::__core::fmt::Formatter) + -> $crate::__core::fmt::Result { + // Now we import the real values for the flags. + // Only ones that are #[cfg]ed out will be 0. + use self::real_flags::*; + + let mut first = true; + $( + // $Flag.bits == 0 means that $Flag doesn't exist + if $Flag.bits != 0 && self_ & $Flag.bits as u64 == $Flag.bits as u64 { + if !first { + try!(f.write_str(" | ")); + } + first = false; + try!(f.write_str(stringify!($Flag))); + } + )+ + Ok(()) + } + } + dummy::fmt(self.bits as u64, f) + } + } + + #[allow(dead_code)] + impl $BitFlags { + /// Returns an empty set of flags. + #[inline] + pub fn empty() -> $BitFlags { + $BitFlags { bits: 0 } + } + + /// Returns the set containing all flags. + #[inline] + pub fn all() -> $BitFlags { + // See above `dummy` module for why this approach is taken. + #[allow(dead_code)] + mod dummy { + pub struct $BitFlags { + bits: u64, + } + mod real_flags { + use super::$BitFlags; + $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { + bits: super::super::$Flag.bits as u64 + };)+ + } + $(const $Flag: $BitFlags = $BitFlags { bits: 0 };)+ + + #[inline] + pub fn all() -> u64 { + use self::real_flags::*; + $($Flag.bits)|+ + } + } + $BitFlags { bits: dummy::all() as $T } + } + + /// Returns the raw value of the flags currently stored. + #[inline] + pub fn bits(&self) -> $T { + self.bits + } + + /// Convert from underlying bit representation, unless that + /// representation contains bits that do not correspond to a flag. + #[inline] + pub fn from_bits(bits: $T) -> $crate::__core::option::Option<$BitFlags> { + if (bits & !$BitFlags::all().bits()) == 0 { + $crate::__core::option::Option::Some($BitFlags { bits: bits }) + } else { + $crate::__core::option::Option::None + } + } + + /// Convert from underlying bit representation, dropping any bits + /// that do not correspond to flags. + #[inline] + pub fn from_bits_truncate(bits: $T) -> $BitFlags { + $BitFlags { bits: bits } & $BitFlags::all() + } + + /// Returns `true` if no flags are currently stored. + #[inline] + pub fn is_empty(&self) -> bool { + *self == $BitFlags::empty() + } + + /// Returns `true` if all flags are currently set. + #[inline] + pub fn is_all(&self) -> bool { + *self == $BitFlags::all() + } + + /// Returns `true` if there are flags common to both `self` and `other`. + #[inline] + pub fn intersects(&self, other: $BitFlags) -> bool { + !(*self & other).is_empty() + } + + /// Returns `true` all of the flags in `other` are contained within `self`. + #[inline] + pub fn contains(&self, other: $BitFlags) -> bool { + (*self & other) == other + } + + /// Inserts the specified flags in-place. + #[inline] + pub fn insert(&mut self, other: $BitFlags) { + self.bits |= other.bits; + } + + /// Removes the specified flags in-place. + #[inline] + pub fn remove(&mut self, other: $BitFlags) { + self.bits &= !other.bits; + } + + /// Toggles the specified flags in-place. + #[inline] + pub fn toggle(&mut self, other: $BitFlags) { + self.bits ^= other.bits; + } + } + + impl $crate::__core::ops::BitOr for $BitFlags { + type Output = $BitFlags; + + /// Returns the union of the two sets of flags. + #[inline] + fn bitor(self, other: $BitFlags) -> $BitFlags { + $BitFlags { bits: self.bits | other.bits } + } + } + + impl $crate::__core::ops::BitOrAssign for $BitFlags { + + /// Adds the set of flags. + #[inline] + fn bitor_assign(&mut self, other: $BitFlags) { + self.bits |= other.bits; + } + } + + impl $crate::__core::ops::BitXor for $BitFlags { + type Output = $BitFlags; + + /// Returns the left flags, but with all the right flags toggled. + #[inline] + fn bitxor(self, other: $BitFlags) -> $BitFlags { + $BitFlags { bits: self.bits ^ other.bits } + } + } + + impl $crate::__core::ops::BitXorAssign for $BitFlags { + + /// Toggles the set of flags. + #[inline] + fn bitxor_assign(&mut self, other: $BitFlags) { + self.bits ^= other.bits; + } + } + + impl $crate::__core::ops::BitAnd for $BitFlags { + type Output = $BitFlags; + + /// Returns the intersection between the two sets of flags. + #[inline] + fn bitand(self, other: $BitFlags) -> $BitFlags { + $BitFlags { bits: self.bits & other.bits } + } + } + + impl $crate::__core::ops::BitAndAssign for $BitFlags { + + /// Disables all flags disabled in the set. + #[inline] + fn bitand_assign(&mut self, other: $BitFlags) { + self.bits &= other.bits; + } + } + + impl $crate::__core::ops::Sub for $BitFlags { + type Output = $BitFlags; + + /// Returns the set difference of the two sets of flags. + #[inline] + fn sub(self, other: $BitFlags) -> $BitFlags { + $BitFlags { bits: self.bits & !other.bits } + } + } + + impl $crate::__core::ops::SubAssign for $BitFlags { + + /// Disables all flags enabled in the set. + #[inline] + fn sub_assign(&mut self, other: $BitFlags) { + self.bits &= !other.bits; + } + } + + impl $crate::__core::ops::Not for $BitFlags { + type Output = $BitFlags; + + /// Returns the complement of this set of flags. + #[inline] + fn not(self) -> $BitFlags { + $BitFlags { bits: !self.bits } & $BitFlags::all() + } + } + + impl $crate::__core::iter::Extend<$BitFlags> for $BitFlags { + fn extend>(&mut self, iterator: T) { + for item in iterator { + self.insert(item) + } + } + } + + impl $crate::__core::iter::FromIterator<$BitFlags> for $BitFlags { + fn from_iter>(iterator: T) -> $BitFlags { + let mut result = Self::empty(); + result.extend(iterator); + result + } + } + }; + ($(#[$attr:meta])* pub flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+, + }) => { + bitflags! { + $(#[$attr])* + pub flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; + ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+, + }) => { + bitflags! { + $(#[$attr])* + flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; +} + +#[cfg(test)] +#[allow(non_upper_case_globals, dead_code)] +mod tests { + use std::hash::{SipHasher, Hash, Hasher}; + + bitflags! { + #[doc = "> The first principle is that you must not fool yourself — and"] + #[doc = "> you are the easiest person to fool."] + #[doc = "> "] + #[doc = "> - Richard Feynman"] + flags Flags: u32 { + const FlagA = 0b00000001, + #[doc = " macros are way better at generating code than trans is"] + const FlagB = 0b00000010, + const FlagC = 0b00000100, + #[doc = "* cmr bed"] + #[doc = "* strcat table"] + #[doc = " wait what?"] + const FlagABC = FlagA.bits + | FlagB.bits + | FlagC.bits, + } + } + + bitflags! { + flags _CfgFlags: u32 { + #[cfg(windows)] + const _CfgA = 0b01, + #[cfg(unix)] + const _CfgB = 0b01, + #[cfg(windows)] + const _CfgC = _CfgA.bits | 0b10, + } + } + + bitflags! { + flags AnotherSetOfFlags: i8 { + const AnotherFlag = -1_i8, + } + } + + #[test] + fn test_bits(){ + assert_eq!(Flags::empty().bits(), 0b00000000); + assert_eq!(FlagA.bits(), 0b00000001); + assert_eq!(FlagABC.bits(), 0b00000111); + + assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00); + assert_eq!(AnotherFlag.bits(), !0_i8); + } + + #[test] + fn test_from_bits() { + assert_eq!(Flags::from_bits(0), Some(Flags::empty())); + assert_eq!(Flags::from_bits(0b1), Some(FlagA)); + assert_eq!(Flags::from_bits(0b10), Some(FlagB)); + assert_eq!(Flags::from_bits(0b11), Some(FlagA | FlagB)); + assert_eq!(Flags::from_bits(0b1000), None); + + assert_eq!(AnotherSetOfFlags::from_bits(!0_i8), Some(AnotherFlag)); + } + + #[test] + fn test_from_bits_truncate() { + assert_eq!(Flags::from_bits_truncate(0), Flags::empty()); + assert_eq!(Flags::from_bits_truncate(0b1), FlagA); + assert_eq!(Flags::from_bits_truncate(0b10), FlagB); + assert_eq!(Flags::from_bits_truncate(0b11), (FlagA | FlagB)); + assert_eq!(Flags::from_bits_truncate(0b1000), Flags::empty()); + assert_eq!(Flags::from_bits_truncate(0b1001), FlagA); + + assert_eq!(AnotherSetOfFlags::from_bits_truncate(0_i8), AnotherSetOfFlags::empty()); + } + + #[test] + fn test_is_empty(){ + assert!(Flags::empty().is_empty()); + assert!(!FlagA.is_empty()); + assert!(!FlagABC.is_empty()); + + assert!(!AnotherFlag.is_empty()); + } + + #[test] + fn test_is_all() { + assert!(Flags::all().is_all()); + assert!(!FlagA.is_all()); + assert!(FlagABC.is_all()); + + assert!(AnotherFlag.is_all()); + } + + #[test] + fn test_two_empties_do_not_intersect() { + let e1 = Flags::empty(); + let e2 = Flags::empty(); + assert!(!e1.intersects(e2)); + + assert!(AnotherFlag.intersects(AnotherFlag)); + } + + #[test] + fn test_empty_does_not_intersect_with_full() { + let e1 = Flags::empty(); + let e2 = FlagABC; + assert!(!e1.intersects(e2)); + } + + #[test] + fn test_disjoint_intersects() { + let e1 = FlagA; + let e2 = FlagB; + assert!(!e1.intersects(e2)); + } + + #[test] + fn test_overlapping_intersects() { + let e1 = FlagA; + let e2 = FlagA | FlagB; + assert!(e1.intersects(e2)); + } + + #[test] + fn test_contains() { + let e1 = FlagA; + let e2 = FlagA | FlagB; + assert!(!e1.contains(e2)); + assert!(e2.contains(e1)); + assert!(FlagABC.contains(e2)); + + assert!(AnotherFlag.contains(AnotherFlag)); + } + + #[test] + fn test_insert(){ + let mut e1 = FlagA; + let e2 = FlagA | FlagB; + e1.insert(e2); + assert_eq!(e1, e2); + + let mut e3 = AnotherSetOfFlags::empty(); + e3.insert(AnotherFlag); + assert_eq!(e3, AnotherFlag); + } + + #[test] + fn test_remove(){ + let mut e1 = FlagA | FlagB; + let e2 = FlagA | FlagC; + e1.remove(e2); + assert_eq!(e1, FlagB); + + let mut e3 = AnotherFlag; + e3.remove(AnotherFlag); + assert_eq!(e3, AnotherSetOfFlags::empty()); + } + + #[test] + fn test_operators() { + let e1 = FlagA | FlagC; + let e2 = FlagB | FlagC; + assert_eq!((e1 | e2), FlagABC); // union + assert_eq!((e1 & e2), FlagC); // intersection + assert_eq!((e1 - e2), FlagA); // set difference + assert_eq!(!e2, FlagA); // set complement + assert_eq!(e1 ^ e2, FlagA | FlagB); // toggle + let mut e3 = e1; + e3.toggle(e2); + assert_eq!(e3, FlagA | FlagB); + + let mut m4 = AnotherSetOfFlags::empty(); + m4.toggle(AnotherSetOfFlags::empty()); + assert_eq!(m4, AnotherSetOfFlags::empty()); + } + + #[test] + fn test_assignment_operators() { + let mut m1 = Flags::empty(); + let e1 = FlagA | FlagC; + // union + m1 |= FlagA; + assert_eq!(m1, FlagA); + // intersection + m1 &= e1; + assert_eq!(m1, FlagA); + // set difference + m1 -= m1; + assert_eq!(m1, Flags::empty()); + // toggle + m1 ^= e1; + assert_eq!(m1, e1); + } + + #[test] + fn test_extend() { + let mut flags; + + flags = Flags::empty(); + flags.extend([].iter().cloned()); + assert_eq!(flags, Flags::empty()); + + flags = Flags::empty(); + flags.extend([FlagA, FlagB].iter().cloned()); + assert_eq!(flags, FlagA | FlagB); + + flags = FlagA; + flags.extend([FlagA, FlagB].iter().cloned()); + assert_eq!(flags, FlagA | FlagB); + + flags = FlagB; + flags.extend([FlagA, FlagABC].iter().cloned()); + assert_eq!(flags, FlagABC); + } + + #[test] + fn test_from_iterator() { + assert_eq!([].iter().cloned().collect::(), Flags::empty()); + assert_eq!([FlagA, FlagB].iter().cloned().collect::(), FlagA | FlagB); + assert_eq!([FlagA, FlagABC].iter().cloned().collect::(), FlagABC); + } + + #[test] + fn test_lt() { + let mut a = Flags::empty(); + let mut b = Flags::empty(); + + assert!(!(a < b) && !(b < a)); + b = FlagB; + assert!(a < b); + a = FlagC; + assert!(!(a < b) && b < a); + b = FlagC | FlagB; + assert!(a < b); + } + + #[test] + fn test_ord() { + let mut a = Flags::empty(); + let mut b = Flags::empty(); + + assert!(a <= b && a >= b); + a = FlagA; + assert!(a > b && a >= b); + assert!(b < a && b <= a); + b = FlagB; + assert!(b > a && b >= a); + assert!(a < b && a <= b); + } + + fn hash(t: &T) -> u64 { + let mut s = SipHasher::new_with_keys(0, 0); + t.hash(&mut s); + s.finish() + } + + #[test] + fn test_hash() { + let mut x = Flags::empty(); + let mut y = Flags::empty(); + assert_eq!(hash(&x), hash(&y)); + x = Flags::all(); + y = FlagABC; + assert_eq!(hash(&x), hash(&y)); + } + + #[test] + fn test_debug() { + assert_eq!(format!("{:?}", FlagA | FlagB), "FlagA | FlagB"); + assert_eq!(format!("{:?}", FlagABC), "FlagA | FlagB | FlagC | FlagABC"); + } + + mod submodule { + bitflags! { + pub flags PublicFlags: i8 { + const FlagX = 0, + } + } + bitflags! { + flags PrivateFlags: i8 { + const FlagY = 0, + } + } + + #[test] + fn test_private() { + let _ = FlagY; + } + } + + #[test] + fn test_public() { + let _ = submodule::FlagX; + } + + mod t1 { + mod foo { + pub type Bar = i32; + } + + bitflags! { + /// baz + flags Flags: foo::Bar { + const A = 0b00000001, + #[cfg(foo)] + const B = 0b00000010, + #[cfg(foo)] + const C = 0b00000010, + } + } + } +} diff --git a/bash-5.1/vendor/bitflags-0.7.0/tests/external.rs b/bash-5.1/vendor/bitflags-0.7.0/tests/external.rs new file mode 100644 index 0000000..0f0c7f6 --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/tests/external.rs @@ -0,0 +1,21 @@ +#![allow(dead_code)] + +#[macro_use] +extern crate bitflags; + +bitflags! { + /// baz + flags Flags: u32 { + const A = 0b00000001, + #[doc = "bar"] + const B = 0b00000010, + const C = 0b00000100, + #[doc = "foo"] + const ABC = A.bits | B.bits | C.bits, + } +} + +#[test] +fn smoke() { + assert_eq!(ABC, A | B | C); +} diff --git a/bash-5.1/vendor/bitflags-0.7.0/tests/external_no_std.rs b/bash-5.1/vendor/bitflags-0.7.0/tests/external_no_std.rs new file mode 100644 index 0000000..46526fd --- /dev/null +++ b/bash-5.1/vendor/bitflags-0.7.0/tests/external_no_std.rs @@ -0,0 +1,22 @@ +#![allow(dead_code)] +#![no_std] + +#[macro_use] +extern crate bitflags; + +bitflags! { + /// baz + flags Flags: u32 { + const A = 0b00000001, + #[doc = "bar"] + const B = 0b00000010, + const C = 0b00000100, + #[doc = "foo"] + const ABC = A.bits | B.bits | C.bits, + } +} + +#[test] +fn smoke() { + assert_eq!(ABC, A | B | C); +} diff --git a/bash-5.1/vendor/cexpr/.cargo-checksum.json b/bash-5.1/vendor/cexpr/.cargo-checksum.json new file mode 100644 index 0000000..9469ba7 --- /dev/null +++ b/bash-5.1/vendor/cexpr/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"22914a43154e0b38bbe265a67024c1f98af9087ca561448ac0f13ed57c9311ae","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"d9771b8c6cf4426d3846de54c1febe20907f1eeadf7adfb5ade89a83bd9ea77f","src/expr.rs":"b888963ab9eb344c93c0654286231b4204809a971682155fade5c69a4493636f","src/lib.rs":"78bbde89e803cf931216e38bdd992e13894cd898868478a258eac5155bdf4de9","src/literal.rs":"fb80a7b43d96bedfd47bc2d39eaf588c5cef6a2374132fbdfe5146dd56a1894c","src/token.rs":"52d42deb2a2575bb8631e2e821593d8288fed16e21bab3ceeacb6a7b06c40087","tests/clang.rs":"a650cde69ab2e801f994f15e4cb32c538e53abefcdd862865ce277ce9a055242","tests/input/chars.h":"69c8141870872b795b5174bad125b748732c2b01d0e98ffcfc37b19f3f791f69","tests/input/fail.h":"b0b6cffd2dd17410b5eb02ee79ab75754820480b960db8a9866cc9983bd36b65","tests/input/floats.h":"28ec664e793c494e1a31f3bc5b790014e9921fc741bf475a86319b9a9eee5915","tests/input/int_signed.h":"934199eded85dd7820ca08c0beb1381ee6d9339970d2720a69c23025571707ce","tests/input/int_unsigned.h":"f47c1ccb6c69856162639277d7552090055420155df55f65581e57217cccce76","tests/input/strings.h":"75c60527068172b97983d2b8361938e856ea394002d5bef05de1adc6a0f5fc01","tests/input/test_llvm_bug_9069.h":"8d9ae1d1eadc8f6d5c14296f984547fe894d0f2ce5cd6d7aa8caad40a56bc5e1"},"package":"42aac45e9567d97474a834efdee3081b3c942b2205be932092f53354ce503d6c"} \ No newline at end of file diff --git a/bash-5.1/vendor/cexpr/Cargo.toml b/bash-5.1/vendor/cexpr/Cargo.toml new file mode 100644 index 0000000..c298389 --- /dev/null +++ b/bash-5.1/vendor/cexpr/Cargo.toml @@ -0,0 +1,26 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "cexpr" +version = "0.2.3" +authors = ["Jethro Beekman "] +description = "A C expression parser and evaluator" +documentation = "https://docs.rs/cexpr/" +keywords = ["C", "expression", "parser"] +license = "Apache-2.0/MIT" +repository = "https://github.com/jethrogb/rust-cexpr" +[dependencies.nom] +version = "^3" +features = ["verbose-errors"] +[dev-dependencies.clang-sys] +version = "0.11.0" diff --git a/bash-5.1/vendor/cexpr/LICENSE-APACHE b/bash-5.1/vendor/cexpr/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/cexpr/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/cexpr/LICENSE-MIT b/bash-5.1/vendor/cexpr/LICENSE-MIT new file mode 100644 index 0000000..ed958e7 --- /dev/null +++ b/bash-5.1/vendor/cexpr/LICENSE-MIT @@ -0,0 +1,25 @@ +(C) Copyright 2016 Jethro G. Beekman + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/cexpr/src/expr.rs b/bash-5.1/vendor/cexpr/src/expr.rs new file mode 100644 index 0000000..63d2b27 --- /dev/null +++ b/bash-5.1/vendor/cexpr/src/expr.rs @@ -0,0 +1,578 @@ +// (C) Copyright 2016 Jethro G. Beekman +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! Evaluating C expressions from tokens. +//! +//! Numerical operators are supported. All numerical values are treated as +//! `i64` or `f64`. Type casting is not supported. `i64` are converted to +//! `f64` when used in conjunction with a `f64`. Right shifts are always +//! arithmetic shifts. +//! +//! The `sizeof` operator is not supported. +//! +//! String concatenation is supported, but width prefixes are ignored; all +//! strings are treated as narrow strings. +//! +//! Use the `IdentifierParser` to substitute identifiers found in expressions. + +use std::collections::HashMap; +use std::ops::{AddAssign,BitAndAssign,BitOrAssign,BitXorAssign,DivAssign,MulAssign,RemAssign,ShlAssign,ShrAssign,SubAssign}; +use std::num::Wrapping; + +use literal::{self,CChar}; +use token::{Token,Kind as TokenKind}; +use nom_crate::*; + +/// Expression parser/evaluator that supports identifiers. +#[derive(Debug)] +pub struct IdentifierParser<'ident> { + identifiers: &'ident HashMap,EvalResult>, +} +#[derive(Copy,Clone)] +struct PRef<'a>(&'a IdentifierParser<'a>); + +pub type CResult<'a,R:'a> = IResult<&'a [Token],R,::Error>; + +/// The result of parsing a literal or evaluating an expression. +#[derive(Debug,Clone,PartialEq)] +pub enum EvalResult { + Int(Wrapping), + Float(f64), + Char(CChar), + Str(Vec), + Invalid, +} + +macro_rules! result_opt ( + (fn $n:ident: $e:ident -> $t:ty) => ( + #[allow(dead_code)] + fn $n(self) -> Option<$t> { + if let EvalResult::$e(v) = self { + Some(v) + } else { + None + } + } + ); +); + +impl EvalResult { + result_opt!(fn as_int: Int -> Wrapping); + result_opt!(fn as_float: Float -> f64); + result_opt!(fn as_char: Char -> CChar); + result_opt!(fn as_str: Str -> Vec); + + fn as_numeric(self) -> Option { + match self { + EvalResult::Int(_) | EvalResult::Float(_) => Some(self), + _ => None, + } + } +} + +impl From> for EvalResult { + fn from(s: Vec) -> EvalResult { + EvalResult::Str(s) + } +} + +// =========================================== +// ============= Clang tokens ================ +// =========================================== + +macro_rules! exact_token ( + ($i:expr, $k:ident, $c:expr) => ({ + if $i.is_empty() { + let res: CResult<&[u8]> = IResult::Incomplete(Needed::Size($c.len())); + res + } else { + if $i[0].kind==TokenKind::$k && &$i[0].raw[..]==$c { + IResult::Done(&$i[1..], &$i[0].raw[..]) + } else { + IResult::Error(Err::Position(ErrorKind::Custom(::Error::ExactToken(TokenKind::$k,$c)), $i)) + } + } + }); +); + +macro_rules! typed_token ( + ($i:expr, $k:ident) => ({ + if $i.is_empty() { + let res: CResult<&[u8]> = IResult::Incomplete(Needed::Size(1)); + res + } else { + if $i[0].kind==TokenKind::$k { + IResult::Done(&$i[1..], &$i[0].raw[..]) + } else { + IResult::Error(Err::Position(ErrorKind::Custom(::Error::TypedToken(TokenKind::$k)), $i)) + } + } + }); +); + +#[allow(unused_macros)] +macro_rules! any_token ( + ($i:expr,) => ({ + if $i.is_empty() { + let res: CResult<&Token> = IResult::Incomplete(Needed::Size(1)); + res + } else { + IResult::Done(&$i[1..], &$i[0]) + } + }); +); + +macro_rules! p ( + ($i:expr, $c:expr) => (exact_token!($i,Punctuation,$c.as_bytes())) +); + +macro_rules! one_of_punctuation ( + ($i:expr, $c:expr) => ({ + if $i.is_empty() { + let min = $c.iter().map(|opt|opt.len()).min().expect("at least one option"); + let res: CResult<&[u8]> = IResult::Incomplete(Needed::Size(min)); + res + } else { + if $i[0].kind==TokenKind::Punctuation && $c.iter().any(|opt|opt.as_bytes()==&$i[0].raw[..]) { + IResult::Done(&$i[1..], &$i[0].raw[..]) + } else { + const VAILD_VALUES: &'static [&'static str] = &$c; + IResult::Error(Err::Position(ErrorKind::Custom(::Error::ExactTokens(TokenKind::Punctuation,VAILD_VALUES)), $i)) + } + } + }); +); + +// ================================================== +// ============= Numeric expressions ================ +// ================================================== + +impl<'a> AddAssign<&'a EvalResult> for EvalResult { + fn add_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a), &Int(b)) => Int(a+b), + (&Float(a),&Int(b)) => Float(a+(b.0 as f64)), + (&Int(a), &Float(b)) => Float(a.0 as f64+b), + (&Float(a),&Float(b)) => Float(a+b), + _ => Invalid + }; + } +} +impl<'a> BitAndAssign<&'a EvalResult> for EvalResult { + fn bitand_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a),&Int(b)) => Int(a&b), + _ => Invalid + }; } +} +impl<'a> BitOrAssign<&'a EvalResult> for EvalResult { + fn bitor_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a),&Int(b)) => Int(a|b), + _ => Invalid + }; + } +} +impl<'a> BitXorAssign<&'a EvalResult> for EvalResult { + fn bitxor_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a),&Int(b)) => Int(a^b), + _ => Invalid + }; + } +} +impl<'a> DivAssign<&'a EvalResult> for EvalResult { + fn div_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a), &Int(b)) => Int(a/b), + (&Float(a),&Int(b)) => Float(a/(b.0 as f64)), + (&Int(a), &Float(b)) => Float(a.0 as f64/b), + (&Float(a),&Float(b)) => Float(a/b), + _ => Invalid + }; + } +} +impl<'a> MulAssign<&'a EvalResult> for EvalResult { + fn mul_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a), &Int(b)) => Int(a*b), + (&Float(a),&Int(b)) => Float(a*(b.0 as f64)), + (&Int(a), &Float(b)) => Float(a.0 as f64*b), + (&Float(a),&Float(b)) => Float(a*b), + _ => Invalid + }; + } +} +impl<'a> RemAssign<&'a EvalResult> for EvalResult { + fn rem_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a), &Int(b)) => Int(a%b), + (&Float(a),&Int(b)) => Float(a%(b.0 as f64)), + (&Int(a), &Float(b)) => Float(a.0 as f64%b), + (&Float(a),&Float(b)) => Float(a%b), + _ => Invalid + }; + } +} +impl<'a> ShlAssign<&'a EvalResult> for EvalResult { + fn shl_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a),&Int(b)) => Int(a<<(b.0 as usize)), + _ => Invalid + }; + } +} +impl<'a> ShrAssign<&'a EvalResult> for EvalResult { + fn shr_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a),&Int(b)) => Int(a>>(b.0 as usize)), + _ => Invalid + }; + } +} +impl<'a> SubAssign<&'a EvalResult> for EvalResult { + fn sub_assign(&mut self, rhs: &'a EvalResult) { + use self::EvalResult::*; + *self=match (&*self,rhs) { + (&Int(a), &Int(b)) => Int(a-b), + (&Float(a),&Int(b)) => Float(a-(b.0 as f64)), + (&Int(a), &Float(b)) => Float(a.0 as f64-b), + (&Float(a),&Float(b)) => Float(a-b), + _ => Invalid + }; + } +} + +fn unary_op(input: (&[u8],EvalResult)) -> Option { + use self::EvalResult::*; + assert_eq!(input.0.len(),1); + match (input.0[0],input.1) { + (b'+',i) => Some(i), + (b'-',Int(i)) => Some(Int(Wrapping(i.0.wrapping_neg()))), // impl Neg for Wrapping not until rust 1.10... + (b'-',Float(i)) => Some(Float(-i)), + (b'-',_) => unreachable!("non-numeric unary op"), + (b'~',Int(i)) => Some(Int(!i)), + (b'~',Float(_)) => None, + (b'~',_) => unreachable!("non-numeric unary op"), + _ => unreachable!("invalid unary op"), + } +} + +macro_rules! numeric ( + ($i:expr, $submac:ident!( $($args:tt)* )) => (map_opt!($i,$submac!($($args)*),EvalResult::as_numeric)); + ($i:expr, $f:expr ) => (map_opt!($i,call!($f),EvalResult::as_numeric)); +); + +impl<'a> PRef<'a> { + method!(unary,&[Token],EvalResult,::Error>, mut self, + alt!( + delimited!(p!("("),call_m!(self.numeric_expr),p!(")")) | + numeric!(call_m!(self.literal)) | + numeric!(call_m!(self.identifier)) | + map_opt!(pair!(one_of_punctuation!(["+", "-", "~"]),call_m!(self.unary)),unary_op) + ) + ); + + method!(mul_div_rem,&[Token],EvalResult,::Error>, mut self, + do_parse!( + acc: call_m!(self.unary) >> + res: fold_many0!( + pair!(one_of_punctuation!(["*", "/", "%"]), call_m!(self.unary)), + acc, + |mut acc, (op, val): (&[u8], EvalResult)| { + match op[0] as char { + '*' => acc *= &val, + '/' => acc /= &val, + '%' => acc %= &val, + _ => unreachable!() + }; + acc + } + ) >> (res) + ) + ); + + method!(add_sub,&[Token],EvalResult,::Error>, mut self, + do_parse!( + acc: call_m!(self.mul_div_rem) >> + res: fold_many0!( + pair!(one_of_punctuation!(["+", "-"]), call_m!(self.mul_div_rem)), + acc, + |mut acc, (op, val): (&[u8], EvalResult)| { + match op[0] as char { + '+' => acc += &val, + '-' => acc -= &val, + _ => unreachable!() + }; + acc + } + ) >> (res) + ) + ); + + method!(shl_shr,&[Token],EvalResult,::Error>, mut self, + numeric!(do_parse!( + acc: call_m!(self.add_sub) >> + res: fold_many0!( + pair!(one_of_punctuation!(["<<", ">>"]), call_m!(self.add_sub)), + acc, + |mut acc, (op, val): (&[u8], EvalResult)| { + match op { + b"<<" => acc <<= &val, + b">>" => acc >>= &val, + _ => unreachable!() + }; + acc + } + ) >> (res) + )) + ); + + method!(and,&[Token],EvalResult,::Error>, mut self, + numeric!(do_parse!( + acc: call_m!(self.shl_shr) >> + res: fold_many0!( + preceded!(p!("&"), call_m!(self.shl_shr)), + acc, + |mut acc, val: EvalResult| { + acc &= &val; + acc + } + ) >> (res) + )) + ); + + method!(xor,&[Token],EvalResult,::Error>, mut self, + numeric!(do_parse!( + acc: call_m!(self.and) >> + res: fold_many0!( + preceded!(p!("^"), call_m!(self.and)), + acc, + |mut acc, val: EvalResult| { + acc ^= &val; + acc + } + ) >> (res) + )) + ); + + method!(or,&[Token],EvalResult,::Error>, mut self, + numeric!(do_parse!( + acc: call_m!(self.xor) >> + res: fold_many0!( + preceded!(p!("|"), call_m!(self.xor)), + acc, + |mut acc, val: EvalResult| { + acc |= &val; + acc + } + ) >> (res) + )) + ); + + #[inline(always)] + fn numeric_expr(self, input: &[Token]) -> (Self,CResult) { + self.or(input) + } +} + +// ======================================================= +// ============= Literals and identifiers ================ +// ======================================================= + +impl<'a> PRef<'a> { + fn identifier(self, input: &[Token]) -> (Self,CResult) { + (self,match input.split_first() { + None => + IResult::Incomplete(Needed::Size(1)), + Some((&Token{kind:TokenKind::Identifier,ref raw},rest)) => { + if let Some(r) = self.identifiers.get(&raw[..]) { + IResult::Done(rest, r.clone()) + } else { + IResult::Error(Err::Position(ErrorKind::Custom(::Error::UnknownIdentifier), input)) + } + }, + Some(_) => + IResult::Error(Err::Position(ErrorKind::Custom(::Error::TypedToken(TokenKind::Identifier)), input)), + }) + } + + fn literal(self, input: &[Token]) -> (Self,CResult) { + (self,match input.split_first() { + None => + IResult::Incomplete(Needed::Size(1)), + Some((&Token{kind:TokenKind::Literal,ref raw},rest)) => + match literal::parse(raw) { + IResult::Done(_,result) => IResult::Done(rest, result), + _ => IResult::Error(Err::Position(ErrorKind::Custom(::Error::InvalidLiteral), input)) + }, + Some(_) => + IResult::Error(Err::Position(ErrorKind::Custom(::Error::TypedToken(TokenKind::Literal)), input)), + }) + } + + method!(string,&[Token],Vec,::Error>, mut self, + alt!( + map_opt!(call_m!(self.literal),EvalResult::as_str) | + map_opt!(call_m!(self.identifier),EvalResult::as_str) + ) + ); + + // "string1" "string2" etc... + method!(concat_str,&[Token],EvalResult,::Error>, mut self, + map!( + pair!(call_m!(self.string),many0!(call_m!(self.string))), + |(first,v)| Vec::into_iter(v).fold(first,|mut s,elem|{Vec::extend_from_slice(&mut s,Vec::::as_slice(&elem));s}).into() + ) + ); + + method!(expr,&[Token],EvalResult,::Error>, mut self, + alt!( + call_m!(self.numeric_expr) | + delimited!(p!("("),call_m!(self.expr),p!(")")) | + call_m!(self.concat_str) | + call_m!(self.literal) | + call_m!(self.identifier) + ) + ); + + method!(macro_definition,&[Token],(&[u8],EvalResult),::Error>, mut self, + pair!(typed_token!(Identifier),call_m!(self.expr)) + ); +} + +impl<'a> ::std::ops::Deref for PRef<'a> { + type Target=IdentifierParser<'a>; + fn deref(&self) -> &IdentifierParser<'a> { + self.0 + } +} + +impl<'ident> IdentifierParser<'ident> { + fn as_ref(&self) -> PRef { + PRef(self) + } + + /// Create a new `IdentifierParser` with a set of known identifiers. When + /// a known identifier is encountered during parsing, it is substituted + /// for the value specified. + pub fn new(identifiers: &HashMap,EvalResult>) -> IdentifierParser { + IdentifierParser{identifiers:identifiers} + } + + /// Parse and evalute an expression of a list of tokens. + /// + /// Returns an error if the input is not a valid expression or if the token + /// stream contains comments, keywords or unknown identifiers. + pub fn expr<'a>(&self,input: &'a [Token]) -> CResult<'a,EvalResult> { + self.as_ref().expr(input).1 + } + + /// Parse and evaluate a macro definition from of a list of tokens. + /// + /// Returns the identifier for the macro and its replacement evaluated as an + /// expression. The input should not include `#define`. + /// + /// Returns an error if the replacement is not a valid expression, if called + /// on most function-like macros, or if the token stream contains comments, + /// keywords or unknown identifiers. + /// + /// N.B. This is intended to fail on function-like macros, but if it the + /// macro takes a single argument, the argument name is defined as an + /// identifier, and the macro otherwise parses as an expression, it will + /// return a result even on function-like macros. + /// + /// ```ignore + /// // will evaluate into IDENTIFIER + /// #define DELETE(IDENTIFIER) + /// // will evaluate into IDENTIFIER-3 + /// #define NEGATIVE_THREE(IDENTIFIER) -3 + /// ``` + pub fn macro_definition<'a>(&self,input: &'a [Token]) -> CResult<'a,(&'a [u8],EvalResult)> { + ::assert_full_parse(self.as_ref().macro_definition(input).1) + } +} + +/// Parse and evalute an expression of a list of tokens. +/// +/// Returns an error if the input is not a valid expression or if the token +/// stream contains comments, keywords or identifiers. +pub fn expr<'a>(input: &'a [Token]) -> CResult<'a,EvalResult> { + IdentifierParser::new(&HashMap::new()).expr(input) +} + +/// Parse and evaluate a macro definition from of a list of tokens. +/// +/// Returns the identifier for the macro and its replacement evaluated as an +/// expression. The input should not include `#define`. +/// +/// Returns an error if the replacement is not a valid expression, if called +/// on a function-like macro, or if the token stream contains comments, +/// keywords or identifiers. +pub fn macro_definition<'a>(input: &'a [Token]) -> CResult<'a,(&'a [u8],EvalResult)> { + IdentifierParser::new(&HashMap::new()).macro_definition(input) +} + +named_attr!( +/// Parse a functional macro declaration from a list of tokens. +/// +/// Returns the identifier for the macro and the argument list (in order). The +/// input should not include `#define`. The actual definition is not parsed and +/// may be obtained from the unparsed data returned. +/// +/// Returns an error if the input is not a functional macro or if the token +/// stream contains comments. +/// +/// # Example +/// ``` +/// use cexpr::expr::{IdentifierParser, EvalResult, fn_macro_declaration}; +/// use cexpr::assert_full_parse; +/// use cexpr::token::Kind::*; +/// use cexpr::token::Token; +/// +/// // #define SUFFIX(arg) arg "suffix" +/// let tokens = vec![ +/// (Identifier, &b"SUFFIX"[..]).into(), +/// (Punctuation, &b"("[..]).into(), +/// (Identifier, &b"arg"[..]).into(), +/// (Punctuation, &b")"[..]).into(), +/// (Identifier, &b"arg"[..]).into(), +/// (Literal, &br#""suffix""#[..]).into(), +/// ]; +/// +/// // Try to parse the functional part +/// let (expr, (ident, args)) = fn_macro_declaration(&tokens).unwrap(); +/// assert_eq!(ident, b"SUFFIX"); +/// +/// // Create dummy arguments +/// let idents = args.into_iter().map(|arg| +/// (arg.to_owned(), EvalResult::Str(b"test".to_vec())) +/// ).collect(); +/// +/// // Evaluate the macro +/// let (_, evaluated) = assert_full_parse(IdentifierParser::new(&idents).expr(expr)).unwrap(); +/// assert_eq!(evaluated, EvalResult::Str(b"testsuffix".to_vec())); +/// ``` +,pub fn_macro_declaration<&[Token],(&[u8],Vec<&[u8]>),::Error>, + pair!( + typed_token!(Identifier), + delimited!( + p!("("), + separated_list!(p!(","), typed_token!(Identifier)), + p!(")") + ) + ) +); diff --git a/bash-5.1/vendor/cexpr/src/lib.rs b/bash-5.1/vendor/cexpr/src/lib.rs new file mode 100644 index 0000000..db30964 --- /dev/null +++ b/bash-5.1/vendor/cexpr/src/lib.rs @@ -0,0 +1,57 @@ +// (C) Copyright 2016 Jethro G. Beekman +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[macro_use] +extern crate nom as nom_crate; + +pub mod nom { + //! nom's result types, re-exported. + pub use nom_crate::{IResult,Needed,Err,ErrorKind}; +} +pub mod literal; +pub mod expr; +pub mod token; + +use nom::*; + +#[derive(Debug)] +/// Parsing errors specific to C parsing +pub enum Error { + /// Expected the specified token + ExactToken(token::Kind,&'static [u8]), + /// Expected one of the specified tokens + ExactTokens(token::Kind,&'static [&'static str]), + /// Expected a token of the specified kind + TypedToken(token::Kind), + /// An unknown identifier was encountered + UnknownIdentifier, + /// An invalid literal was encountered. + /// + /// When encountered, this generally means a bug exists in the data that + /// was passed in or the parsing logic. + InvalidLiteral, + /// A full parse was requested, but data was left over after parsing finished. + Partial, +} + +macro_rules! identity ( + ($i:expr,$e:expr) => ($e); +); + +/// If the input result indicates a succesful parse, but there is data left, +/// return an `Error::Partial` instead. +pub fn assert_full_parse(result: IResult<&[I],O,E>) -> IResult<&[I],O,::Error> { + match fix_error!((),::Error,identity!(result)) { + IResult::Done(rem,output) => if rem.len()==0 { + IResult::Done(rem, output) + } else { + IResult::Error(Err::Position(ErrorKind::Custom(::Error::Partial), rem)) + }, + r => r, + } +} diff --git a/bash-5.1/vendor/cexpr/src/literal.rs b/bash-5.1/vendor/cexpr/src/literal.rs new file mode 100644 index 0000000..7b90afd --- /dev/null +++ b/bash-5.1/vendor/cexpr/src/literal.rs @@ -0,0 +1,239 @@ +// (C) Copyright 2016 Jethro G. Beekman +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! Parsing C literals from byte slices. +//! +//! This will parse a representation of a C literal into a Rust type. +//! +//! # characters +//! Character literals are stored into the `CChar` type, which can hold values +//! that are not valid Unicode code points. ASCII characters are represented as +//! `char`, literal bytes with the high byte set are converted into the raw +//! representation. Escape sequences are supported. If hex and octal escapes +//! map to an ASCII character, that is used, otherwise, the raw encoding is +//! used, including for values over 255. Unicode escapes are checked for +//! validity and mapped to `char`. Character sequences are not supported. Width +//! prefixes are ignored. +//! +//! # strings +//! Strings are interpreted as byte vectors. Escape sequences are supported. If +//! hex and octal escapes map onto multi-byte characters, they are truncated to +//! one 8-bit character. Unicode escapes are converted into their UTF-8 +//! encoding. Width prefixes are ignored. +//! +//! # integers +//! Integers are read into `i64`. Binary, octal, decimal and hexadecimal are +//! all supported. If the literal value is between `i64::MAX` and `u64::MAX`, +//! it is bit-cast to `i64`. Values over `u64::MAX` cannot be parsed. Width and +//! sign suffixes are ignored. Sign prefixes are not supported. +//! +//! # real numbers +//! Reals are read into `f64`. Width suffixes are ignored. Sign prefixes are +//! not supported in the significand. Hexadecimal floating points are not +//! supported. + +use std::char; +use std::str::{self,FromStr}; + +use nom_crate::*; + +use expr::EvalResult; + +#[derive(Debug,Copy,Clone,PartialEq,Eq)] +/// Representation of a C character +pub enum CChar { + /// A character that can be represented as a `char` + Char(char), + /// Any other character (8-bit characters, unicode surrogates, etc.) + Raw(u64), +} + +impl From for CChar { + fn from(i: u8) -> CChar { + match i { + 0 ... 0x7f => CChar::Char(i as u8 as char), + _ => CChar::Raw(i as u64), + } + } +} + +// A non-allocating version of this would be nice... +impl Into> for CChar { + fn into(self) -> Vec { + match self { + CChar::Char(c) => { + let mut s=String::with_capacity(4); + s.extend(&[c]); + s.into_bytes() + } + CChar::Raw(i) => { + let mut v=Vec::with_capacity(1); + v.push(i as u8); + v + } + } + } +} + +// ==================================================== +// ======== macros that shouldn't be necessary ======== +// ==================================================== + +macro_rules! force_type ( + ($input:expr,IResult<$i:ty,$o:ty,$e:ty>) => (IResult::Error::<$i,$o,$e>(Err::Position(ErrorKind::Fix,$input))) +); + + +// ================================= +// ======== matching digits ======== +// ================================= + +macro_rules! byte ( + ($i:expr, $($p: pat)|* ) => ({ + match $i.split_first() { + $(Some((&c @ $p,rest)))|* => IResult::Done::<&[_],u8,u32>(rest,c), + Some(_) => IResult::Error(Err::Position(ErrorKind::OneOf,$i)), + None => IResult::Incomplete(Needed::Size(1)), + } + }) +); + +named!(binary,byte!(b'0' ... b'1')); +named!(octal,byte!(b'0' ... b'7')); +named!(decimal,byte!(b'0' ... b'9')); +named!(hexadecimal,byte!(b'0' ... b'9' | b'a' ... b'f' | b'A' ... b'F')); + + +// ======================================== +// ======== characters and strings ======== +// ======================================== + +fn escape2char(c: char) -> CChar { + CChar::Char(match c { + 'a' => '\x07', + 'b' => '\x08', + 'f' => '\x0c', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'v' => '\x0b', + _ => unreachable!("invalid escape {}",c) + }) +} + +fn c_raw_escape(n: Vec, radix: u32) -> Option { + str::from_utf8(&n).ok() + .and_then(|i|u64::from_str_radix(i,radix).ok()) + .map(|i|match i { + 0 ... 0x7f => CChar::Char(i as u8 as char), + _ => CChar::Raw(i), + }) +} + +fn c_unicode_escape(n: Vec) -> Option { + str::from_utf8(&n).ok() + .and_then(|i|u32::from_str_radix(i,16).ok()) + .and_then(char::from_u32) + .map(CChar::Char) +} + +named!(escaped_char, + preceded!(char!('\\'),alt!( + map!(one_of!(r#"'"?\"#),CChar::Char) | + map!(one_of!("abfnrtv"),escape2char) | + map_opt!(many_m_n!(1,3,octal),|v|c_raw_escape(v,8)) | + map_opt!(preceded!(char!('x'),many1!(hexadecimal)),|v|c_raw_escape(v,16)) | + map_opt!(preceded!(char!('u'),many_m_n!(4,4,hexadecimal)),c_unicode_escape) | + map_opt!(preceded!(char!('U'),many_m_n!(8,8,hexadecimal)),c_unicode_escape) + )) +); + +named!(c_width_prefix, + alt!( + tag!("u8") | + tag!("u") | + tag!("U") | + tag!("L") + ) +); + +named!(c_char, + delimited!( + terminated!(opt!(c_width_prefix),char!('\'')), + alt!( escaped_char | map!(byte!(0 ... 91 /* \=92 */ | 93 ... 255),CChar::from) ), + char!('\'') + ) +); + +named!(c_string >, + delimited!( + alt!( preceded!(c_width_prefix,char!('"')) | char!('"') ), + fold_many0!( + alt!(map!(escaped_char, |c:CChar| c.into()) | map!(is_not!("\""), |c: &[u8]| c.into())), + Vec::new(), + |mut v: Vec, res:Vec| { v.extend_from_slice(&res); v } + ), + char!('"') + ) +); + +// ================================ +// ======== parse integers ======== +// ================================ + +fn c_int_radix(n: Vec, radix: u32) -> Option { + str::from_utf8(&n).ok() + .and_then(|i|u64::from_str_radix(i,radix).ok()) +} + +named!(c_int, + map!(terminated!(alt_complete!( + map_opt!(preceded!(tag!("0x"),many1!(hexadecimal)),|v|c_int_radix(v,16)) | + map_opt!(preceded!(tag!("0b"),many1!(binary)),|v|c_int_radix(v,2)) | + map_opt!(preceded!(char!('0'),many1!(octal)),|v|c_int_radix(v,8)) | + map_opt!(many1!(decimal),|v|c_int_radix(v,10)) | + force_type!(IResult<_,_,u32>) + ),is_a!("ulUL")),|i|i as i64) +); + +// ============================== +// ======== parse floats ======== +// ============================== + +named!(float_width,complete!(byte!(b'f' | b'l' | b'F' | b'L'))); +named!(float_exp<(Option,Vec)>,preceded!(byte!(b'e'|b'E'),pair!(opt!(byte!(b'-'|b'+')),many1!(decimal)))); + +named!(c_float, + map_opt!(alt!( + terminated!(recognize!(tuple!(many1!(decimal),byte!(b'.'),many0!(decimal))),opt!(float_width)) | + terminated!(recognize!(tuple!(many0!(decimal),byte!(b'.'),many1!(decimal))),opt!(float_width)) | + terminated!(recognize!(tuple!(many0!(decimal),opt!(byte!(b'.')),many1!(decimal),float_exp)),opt!(float_width)) | + terminated!(recognize!(tuple!(many1!(decimal),opt!(byte!(b'.')),many0!(decimal),float_exp)),opt!(float_width)) | + terminated!(recognize!(many1!(decimal)),float_width) + ),|v|str::from_utf8(v).ok().and_then(|i|f64::from_str(i).ok())) +); + +// ================================ +// ======== main interface ======== +// ================================ + +named!(one_literal<&[u8],EvalResult,::Error>, + fix_error!(::Error,alt_complete!( + map!(c_char,EvalResult::Char) | + map!(c_int,|i|EvalResult::Int(::std::num::Wrapping(i))) | + map!(c_float,EvalResult::Float) | + map!(c_string,EvalResult::Str) + )) +); + +/// Parse a C literal. +/// +/// The input must contain exactly the representation of a single literal +/// token, and in particular no whitespace or sign prefixes. +pub fn parse(input: &[u8]) -> IResult<&[u8],EvalResult,::Error> { + ::assert_full_parse(one_literal(input)) +} diff --git a/bash-5.1/vendor/cexpr/src/token.rs b/bash-5.1/vendor/cexpr/src/token.rs new file mode 100644 index 0000000..f2bbca2 --- /dev/null +++ b/bash-5.1/vendor/cexpr/src/token.rs @@ -0,0 +1,40 @@ +// (C) Copyright 2016 Jethro G. Beekman +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! Representation of a C token +//! +//! This is designed to map onto a libclang CXToken. + +#[derive(Debug,Copy,Clone,PartialEq,Eq)] +pub enum Kind { + Punctuation, + Keyword, + Identifier, + Literal, + Comment, +} + +#[derive(Debug,Clone,PartialEq,Eq)] +pub struct Token { + pub kind: Kind, + pub raw: Box<[u8]>, +} + +impl<'a> From<(Kind, &'a [u8])> for Token { + fn from((kind, value): (Kind, &'a [u8])) -> Token { + Token { + kind: kind, + raw: value.to_owned().into_boxed_slice() + } + } +} + +/// Remove all comment tokens from a vector of tokens +pub fn remove_comments(v: &mut Vec) -> &mut Vec { + v.retain(|t|t.kind!=Kind::Comment); + v +} diff --git a/bash-5.1/vendor/cexpr/tests/clang.rs b/bash-5.1/vendor/cexpr/tests/clang.rs new file mode 100644 index 0000000..121b1a3 --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/clang.rs @@ -0,0 +1,246 @@ +// (C) Copyright 2016 Jethro G. Beekman +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +extern crate cexpr; +extern crate clang_sys; + +use std::{ptr,mem,ffi,slice,char}; +use std::str::{self,FromStr}; +use std::collections::HashMap; + +use clang_sys::*; +use cexpr::token::Token; +use cexpr::expr::{IdentifierParser,EvalResult,fn_macro_declaration}; +use cexpr::literal::CChar; +use cexpr::assert_full_parse; + +// main testing routine +fn test_definition(ident: Vec, tokens: &[Token], idents: &mut HashMap,EvalResult>) -> bool { + fn bytes_to_int(value: &[u8]) -> Option { + str::from_utf8(value).ok() + .map(|s|s.replace("n","-")) + .map(|s|s.replace("_","")) + .and_then(|v|i64::from_str(&v).ok()) + .map(::std::num::Wrapping) + .map(Int) + } + + use cexpr::expr::EvalResult::*; + + let display_name=String::from_utf8_lossy(&ident).into_owned(); + + let functional; + let test={ + // Split name such as Str_test_string into (Str,test_string) + let pos=ident.iter().position(|c|*c==b'_').expect(&format!("Invalid definition in testcase: {}",display_name)); + let mut expected=&ident[..pos]; + let mut value=&ident[(pos+1)..]; + + functional=expected==b"Fn"; + + if functional { + let ident=value; + let pos=ident.iter().position(|c|*c==b'_').expect(&format!("Invalid definition in testcase: {}",display_name)); + expected=&ident[..pos]; + value=&ident[(pos+1)..]; + } + + if expected==b"Str" { + Some(Str(value.to_owned())) + } else if expected==b"Int" { + bytes_to_int(value) + } else if expected==b"Float" { + str::from_utf8(value).ok().map(|s|s.replace("n","-").replace("p",".")).and_then(|v|f64::from_str(&v).ok()).map(Float) + } else if expected==b"CharRaw" { + str::from_utf8(value).ok().and_then(|v|u64::from_str(v).ok()).map(CChar::Raw).map(Char) + } else if expected==b"CharChar" { + str::from_utf8(value).ok().and_then(|v|u32::from_str(v).ok()).and_then(char::from_u32).map(CChar::Char).map(Char) + } else { + Some(Invalid) + }.expect(&format!("Invalid definition in testcase: {}",display_name)) + }; + + let result = if functional { + let mut fnidents; + let expr_tokens; + match fn_macro_declaration(&tokens) { + cexpr::nom::IResult::Done(rest,(_,args)) => { + fnidents=idents.clone(); + expr_tokens=rest; + for arg in args { + let val = match test { + Int(_) => bytes_to_int(&arg), + Str(_) => Some(Str(arg.to_owned())), + _ => unimplemented!() + }.expect(&format!("Invalid argument in functional macro testcase: {}",display_name)); + fnidents.insert(arg.to_owned(), val); + } + }, + e => { + println!("Failed test for {}, unable to parse functional macro declaration: {:?}",display_name,e); + return false; + } + } + assert_full_parse(IdentifierParser::new(&fnidents).expr(&expr_tokens)) + } else { + IdentifierParser::new(idents).macro_definition(&tokens).map(|(_,val)|val) + }; + + match result { + cexpr::nom::IResult::Done(_,val) => { + if val==test { + if let Some(_)=idents.insert(ident,val) { + panic!("Duplicate definition for testcase: {}",display_name); + } + true + } else { + println!("Failed test for {}, expected {:?}, got {:?}",display_name,test,val); + false + } + }, + e => { + if test==Invalid { + true + } else { + println!("Failed test for {}, expected {:?}, got {:?}",display_name,test,e); + false + } + } + } +} + +// support code for the clang lexer +unsafe fn clang_str_to_vec(s: CXString) -> Vec { + let vec=ffi::CStr::from_ptr(clang_getCString(s)).to_bytes().to_owned(); + clang_disposeString(s); + vec +} + +#[allow(non_upper_case_globals)] +unsafe fn token_clang_to_cexpr(tu: CXTranslationUnit, orig: &CXToken) -> Token { + Token { + kind:match clang_getTokenKind(*orig) { + CXToken_Comment => cexpr::token::Kind::Comment, + CXToken_Identifier => cexpr::token::Kind::Identifier, + CXToken_Keyword => cexpr::token::Kind::Keyword, + CXToken_Literal => cexpr::token::Kind::Literal, + CXToken_Punctuation => cexpr::token::Kind::Punctuation, + _ => panic!("invalid token kind: {:?}", *orig), + }, + raw:clang_str_to_vec(clang_getTokenSpelling(tu,*orig)).into_boxed_slice() + } +} + +extern "C" fn visit_children_thunk(cur: CXCursor, parent: CXCursor, closure: CXClientData) -> CXChildVisitResult + where F: FnMut(CXCursor,CXCursor) -> CXChildVisitResult +{ + unsafe{(&mut *(closure as *mut F))(cur,parent)} +} + +unsafe fn visit_children(cursor: CXCursor, mut f: F) + where F: FnMut(CXCursor,CXCursor) -> CXChildVisitResult +{ + clang_visitChildren(cursor, visit_children_thunk:: as _, &mut f as *mut F as CXClientData); +} + +unsafe fn location_in_scope(r: CXSourceRange) -> bool { + let start=clang_getRangeStart(r); + let mut file=CXFile(ptr::null_mut()); + clang_getSpellingLocation(start,&mut file,ptr::null_mut(),ptr::null_mut(),ptr::null_mut()); + clang_Location_isFromMainFile(start)!=0 + && clang_Location_isInSystemHeader(start)==0 + && file.0!=ptr::null_mut() +} + +/// tokenize_range_adjust can be used to work around LLVM bug 9069 +/// https://bugs.llvm.org//show_bug.cgi?id=9069 +fn file_visit_macros, Vec)>(file: &str, tokenize_range_adjust: bool, mut visitor: F) { + unsafe { + let tu={ + let index=clang_createIndex(true as _, false as _); + let cfile=ffi::CString::new(file).unwrap(); + let mut tu=mem::uninitialized(); + assert!(clang_parseTranslationUnit2( + index, + cfile.as_ptr(), + [b"-std=c11\0".as_ptr() as *const ::std::os::raw::c_char].as_ptr(),1, + ptr::null_mut(),0, + CXTranslationUnit_DetailedPreprocessingRecord, + &mut tu + )==CXError_Success,"Failure reading test case {}",file); + tu + }; + visit_children(clang_getTranslationUnitCursor(tu),|cur,_parent| { + if cur.kind==CXCursor_MacroDefinition { + let mut range=clang_getCursorExtent(cur); + if !location_in_scope(range) { return CXChildVisit_Continue } + range.end_int_data-=if tokenize_range_adjust { 1 } else { 0 }; + let mut token_ptr=ptr::null_mut(); + let mut num=0; + clang_tokenize(tu,range,&mut token_ptr,&mut num); + if token_ptr!=ptr::null_mut() { + let tokens=slice::from_raw_parts(token_ptr,num as usize); + let tokens: Vec<_>=tokens.iter().filter_map(|t| + if clang_getTokenKind(*t)!=CXToken_Comment { + Some(token_clang_to_cexpr(tu,t)) + } else { + None + } + ).collect(); + clang_disposeTokens(tu,token_ptr,num); + visitor(clang_str_to_vec(clang_getCursorSpelling(cur)),tokens) + } + } + CXChildVisit_Continue + }); + clang_disposeTranslationUnit(tu); + }; +} + +fn test_file(file: &str) -> bool { + let mut idents=HashMap::new(); + let mut all_succeeded=true; + file_visit_macros(file, fix_bug_9069(), |ident, tokens| all_succeeded&=test_definition(ident, &tokens, &mut idents)); + all_succeeded +} + +fn fix_bug_9069() -> bool { + fn check_bug_9069() -> bool { + let mut token_sets = vec![]; + file_visit_macros("tests/input/test_llvm_bug_9069.h", false, |ident, tokens| { + assert_eq!(&ident, b"A"); + token_sets.push(tokens); + }); + assert_eq!(token_sets.len(), 2); + token_sets[0] != token_sets[1] + } + + use std::sync::{Once, ONCE_INIT}; + use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; + + static CHECK_FIX: Once = ONCE_INIT; + static FIX: AtomicBool = ATOMIC_BOOL_INIT; + + CHECK_FIX.call_once(|| FIX.store(check_bug_9069(), Ordering::SeqCst)); + + FIX.load(Ordering::SeqCst) +} + +macro_rules! test_file { + ($f:ident) => { + #[test] fn $f() { + assert!(test_file(concat!("tests/input/",stringify!($f),".h")),"test_file") + } + } +} + +test_file!(floats); +test_file!(chars); +test_file!(strings); +test_file!(int_signed); +test_file!(int_unsigned); +test_file!(fail); diff --git a/bash-5.1/vendor/cexpr/tests/input/chars.h b/bash-5.1/vendor/cexpr/tests/input/chars.h new file mode 100644 index 0000000..45351d3 --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/chars.h @@ -0,0 +1,3 @@ +#define CharChar_65 'A' +#define CharChar_127849 '\U0001f369' // 🍩 +#define CharRaw_255 U'\xff' diff --git a/bash-5.1/vendor/cexpr/tests/input/fail.h b/bash-5.1/vendor/cexpr/tests/input/fail.h new file mode 100644 index 0000000..fd416bc --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/fail.h @@ -0,0 +1,9 @@ +#define FAIL_function_like(x) 3 +#define FAIL_empty +#define FAIL_invalid_for_radix 0b2 +#define FAIL_shift_by_float 3<<1f +#define FAIL_unknown_identifier UNKNOWN +#define Int_0 0 +#define Str_str "str" +#define FAIL_concat_integer "test" Str_str Int_0 +#define FAIL_too_large_int 18446744073709551616 diff --git a/bash-5.1/vendor/cexpr/tests/input/floats.h b/bash-5.1/vendor/cexpr/tests/input/floats.h new file mode 100644 index 0000000..61942cf --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/floats.h @@ -0,0 +1,8 @@ +#define Float_0 0. +#define Float_1 1f +#define Float_p1 .1 +#define Float_2 2.0 +#define Float_1000 1e3 +#define Float_2000 2e+3 +#define Float_p001 1e-3 +#define Float_80 10.0*(1<<3) diff --git a/bash-5.1/vendor/cexpr/tests/input/int_signed.h b/bash-5.1/vendor/cexpr/tests/input/int_signed.h new file mode 100644 index 0000000..65854a6 --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/int_signed.h @@ -0,0 +1,3 @@ +#define Int_n3 -(-(-3)) +#define Int_n5 -3-2 +#define Int_n9223372036854775808 -9223372036854775808 diff --git a/bash-5.1/vendor/cexpr/tests/input/int_unsigned.h b/bash-5.1/vendor/cexpr/tests/input/int_unsigned.h new file mode 100644 index 0000000..d072ac0 --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/int_unsigned.h @@ -0,0 +1,26 @@ +#define Int_456 456 +#define Int_0 0 +#define Int_1 0b1 +#define Int_2 0x2 +#define Int_63 077 +#define Int_123 123 +#define Int_124 124u +#define Int_125 125uL +#define Int_126 126LuL +#define Int_16 (((1)<<4ULL))/*comment*/ +#define Int_13 1|8^6&2<<1 + +#define Int_47 32|15 +#define Int_38 (32|15)^9 +#define Int_6 ((32|15)^9)&7 +#define Int_12 (((32|15)^9)&7)<<1 +#define Int_17 ((((32|15)^9)&7)<<1)+5 +#define Int_15 (((((32|15)^9)&7)<<1)+5)-2 +#define Int_60 ((((((32|15)^9)&7)<<1)+5)-2)*4 +#define Int_30 (((((((32|15)^9)&7)<<1)+5)-2)*4)/2 +#define Int_39 32|15^9&7<<1+5-2*4/2 + +#define Int_n1 18446744073709551615 /*2^64-1*/ +#define Int_n9223372036854775808 9223372036854775808 + +#define Fn_Int_9(_3) _3*3 diff --git a/bash-5.1/vendor/cexpr/tests/input/strings.h b/bash-5.1/vendor/cexpr/tests/input/strings.h new file mode 100644 index 0000000..e30bb64 --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/strings.h @@ -0,0 +1,12 @@ +#define Str_ "" +#define Str_str "str" +#define Str_unicode u"unicode" +#define Str_long L"long" +#define Str_concat u"con" L"cat" +#define Str_concat_parens ("concat" U"_parens") +#define Str_concat_identifier (Str_concat L"_identifier") +#define Fn_Str_no_args() "no_args" +#define Fn_Str_no_args_concat() "no_args_" Str_concat +#define Fn_Str_prepend_arg(arg) "prepend_" arg +#define Fn_Str_two_args(two, args) two "_" args +#define Fn_Str_three_args(three, _, args) three _ args diff --git a/bash-5.1/vendor/cexpr/tests/input/test_llvm_bug_9069.h b/bash-5.1/vendor/cexpr/tests/input/test_llvm_bug_9069.h new file mode 100644 index 0000000..a92374e --- /dev/null +++ b/bash-5.1/vendor/cexpr/tests/input/test_llvm_bug_9069.h @@ -0,0 +1,4 @@ +// The following two definitions should yield the same list of tokens. +// If https://bugs.llvm.org//show_bug.cgi?id=9069 is not fixed, they don't. +#define A 1 +#define A 1 diff --git a/bash-5.1/vendor/cfg-if-0.1.10/.cargo-checksum.json b/bash-5.1/vendor/cfg-if-0.1.10/.cargo-checksum.json new file mode 100644 index 0000000..c0c9f9d --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"2cb2370b62c56a7d51b51f9e405b2f377b3ad6f7f8d33bc69e20eb819ad66012","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"2406e83ee174e30aa67f8ab266836fa78545012b196395aff37c152321e2c713","src/lib.rs":"8dfd667d32d8b06e529643c975dfa14c29ce9a894a80e381a1bd867252e65e56","tests/xcrate.rs":"c0734dae6e63beafcd60bf53546115a2320735b51035c9e2387fdf9301580934"},"package":"4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"} \ No newline at end of file diff --git a/bash-5.1/vendor/cfg-if-0.1.10/Cargo.toml b/bash-5.1/vendor/cfg-if-0.1.10/Cargo.toml new file mode 100644 index 0000000..5da1d1b --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/Cargo.toml @@ -0,0 +1,36 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "cfg-if" +version = "0.1.10" +authors = ["Alex Crichton "] +description = "A macro to ergonomically define an item depending on a large number of #[cfg]\nparameters. Structured like an if-else chain, the first matching branch is the\nitem that gets emitted.\n" +homepage = "https://github.com/alexcrichton/cfg-if" +documentation = "https://docs.rs/cfg-if" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/cfg-if" +[dependencies.compiler_builtins] +version = "0.1.2" +optional = true + +[dependencies.core] +version = "1.0.0" +optional = true +package = "rustc-std-workspace-core" + +[features] +rustc-dep-of-std = ["core", "compiler_builtins"] +[badges.travis-ci] +repository = "alexcrichton/cfg-if" diff --git a/bash-5.1/vendor/cfg-if-0.1.10/LICENSE-APACHE b/bash-5.1/vendor/cfg-if-0.1.10/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/cfg-if-0.1.10/LICENSE-MIT b/bash-5.1/vendor/cfg-if-0.1.10/LICENSE-MIT new file mode 100644 index 0000000..39e0ed6 --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/cfg-if-0.1.10/README.md b/bash-5.1/vendor/cfg-if-0.1.10/README.md new file mode 100644 index 0000000..50b5e3b --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/README.md @@ -0,0 +1,47 @@ +# cfg-if + +[Documentation](https://docs.rs/cfg-if) + +A macro to ergonomically define an item depending on a large number of #[cfg] +parameters. Structured like an if-else chain, the first matching branch is the +item that gets emitted. + +```toml +[dependencies] +cfg-if = "0.1" +``` + +## Example + +```rust +cfg_if::cfg_if! { + if #[cfg(unix)] { + fn foo() { /* unix specific functionality */ } + } else if #[cfg(target_pointer_width = "32")] { + fn foo() { /* non-unix, 32-bit functionality */ } + } else { + fn foo() { /* fallback implementation */ } + } +} + +fn main() { + foo(); +} +``` + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in `cfg-if` by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bash-5.1/vendor/cfg-if-0.1.10/src/lib.rs b/bash-5.1/vendor/cfg-if-0.1.10/src/lib.rs new file mode 100644 index 0000000..6c5058d --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/src/lib.rs @@ -0,0 +1,176 @@ +//! A macro for defining `#[cfg]` if-else statements. +//! +//! The macro provided by this crate, `cfg_if`, is similar to the `if/elif` C +//! preprocessor macro by allowing definition of a cascade of `#[cfg]` cases, +//! emitting the implementation which matches first. +//! +//! This allows you to conveniently provide a long list `#[cfg]`'d blocks of code +//! without having to rewrite each clause multiple times. +//! +//! # Example +//! +//! ``` +//! cfg_if::cfg_if! { +//! if #[cfg(unix)] { +//! fn foo() { /* unix specific functionality */ } +//! } else if #[cfg(target_pointer_width = "32")] { +//! fn foo() { /* non-unix, 32-bit functionality */ } +//! } else { +//! fn foo() { /* fallback implementation */ } +//! } +//! } +//! +//! # fn main() {} +//! ``` + +#![no_std] +#![doc(html_root_url = "https://docs.rs/cfg-if")] +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] + +/// The main macro provided by this crate. See crate documentation for more +/// information. +#[macro_export] +macro_rules! cfg_if { + // match if/else chains with a final `else` + ($( + if #[cfg($($meta:meta),*)] { $($tokens:tt)* } + ) else * else { + $($tokens2:tt)* + }) => { + $crate::cfg_if! { + @__items + () ; + $( ( ($($meta),*) ($($tokens)*) ), )* + ( () ($($tokens2)*) ), + } + }; + + // match if/else chains lacking a final `else` + ( + if #[cfg($($i_met:meta),*)] { $($i_tokens:tt)* } + $( + else if #[cfg($($e_met:meta),*)] { $($e_tokens:tt)* } + )* + ) => { + $crate::cfg_if! { + @__items + () ; + ( ($($i_met),*) ($($i_tokens)*) ), + $( ( ($($e_met),*) ($($e_tokens)*) ), )* + ( () () ), + } + }; + + // Internal and recursive macro to emit all the items + // + // Collects all the negated cfgs in a list at the beginning and after the + // semicolon is all the remaining items + (@__items ($($not:meta,)*) ; ) => {}; + (@__items ($($not:meta,)*) ; ( ($($m:meta),*) ($($tokens:tt)*) ), $($rest:tt)*) => { + // Emit all items within one block, applying an appropriate #[cfg]. The + // #[cfg] will require all `$m` matchers specified and must also negate + // all previous matchers. + #[cfg(all($($m,)* not(any($($not),*))))] $crate::cfg_if! { @__identity $($tokens)* } + + // Recurse to emit all other items in `$rest`, and when we do so add all + // our `$m` matchers to the list of `$not` matchers as future emissions + // will have to negate everything we just matched as well. + $crate::cfg_if! { @__items ($($not,)* $($m,)*) ; $($rest)* } + }; + + // Internal macro to make __apply work out right for different match types, + // because of how macros matching/expand stuff. + (@__identity $($tokens:tt)*) => { + $($tokens)* + }; +} + +#[cfg(test)] +mod tests { + cfg_if! { + if #[cfg(test)] { + use core::option::Option as Option2; + fn works1() -> Option2 { Some(1) } + } else { + fn works1() -> Option { None } + } + } + + cfg_if! { + if #[cfg(foo)] { + fn works2() -> bool { false } + } else if #[cfg(test)] { + fn works2() -> bool { true } + } else { + fn works2() -> bool { false } + } + } + + cfg_if! { + if #[cfg(foo)] { + fn works3() -> bool { false } + } else { + fn works3() -> bool { true } + } + } + + cfg_if! { + if #[cfg(test)] { + use core::option::Option as Option3; + fn works4() -> Option3 { Some(1) } + } + } + + cfg_if! { + if #[cfg(foo)] { + fn works5() -> bool { false } + } else if #[cfg(test)] { + fn works5() -> bool { true } + } + } + + #[test] + fn it_works() { + assert!(works1().is_some()); + assert!(works2()); + assert!(works3()); + assert!(works4().is_some()); + assert!(works5()); + } + + #[test] + #[allow(clippy::assertions_on_constants)] + fn test_usage_within_a_function() { + cfg_if! {if #[cfg(debug_assertions)] { + // we want to put more than one thing here to make sure that they + // all get configured properly. + assert!(cfg!(debug_assertions)); + assert_eq!(4, 2+2); + } else { + assert!(works1().is_some()); + assert_eq!(10, 5+5); + }} + } + + trait Trait { + fn blah(&self); + } + + #[allow(dead_code)] + struct Struct; + + impl Trait for Struct { + cfg_if! { + if #[cfg(feature = "blah")] { + fn blah(&self) { + unimplemented!(); + } + } else { + fn blah(&self) { + unimplemented!(); + } + } + } + } +} diff --git a/bash-5.1/vendor/cfg-if-0.1.10/tests/xcrate.rs b/bash-5.1/vendor/cfg-if-0.1.10/tests/xcrate.rs new file mode 100644 index 0000000..e7b4a36 --- /dev/null +++ b/bash-5.1/vendor/cfg-if-0.1.10/tests/xcrate.rs @@ -0,0 +1,14 @@ +cfg_if::cfg_if! { + if #[cfg(foo)] { + fn works() -> bool { false } + } else if #[cfg(test)] { + fn works() -> bool { true } + } else { + fn works() -> bool { false } + } +} + +#[test] +fn smoke() { + assert!(works()); +} diff --git a/bash-5.1/vendor/clang-sys/.cargo-checksum.json b/bash-5.1/vendor/clang-sys/.cargo-checksum.json new file mode 100644 index 0000000..f008f5f --- /dev/null +++ b/bash-5.1/vendor/clang-sys/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"37b2280e140dde6b05ba6e9d40485c6f895681b5c8ccdbee806965901e004673","CONTRIBUTING.md":"51b266af19f050c21549e2ae17445397d9d81eec30bc82490c01a69e288883e6","Cargo.toml":"c6cc9d08f5fdb7681a30704c6a9e0e33f4e4fc48f54775d283afb92fba1fd5fe","LICENSE.txt":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","README.md":"2a21a5fcc9bde7e34984f7d2c65e3fa7c49dcb064944418a58fc77d0ef1f311f","appveyor.yml":"612ad2e0be15a8d339fb8be2fc6ac317d5e6da84886f0f322af399bb1bc28591","build.rs":"804982dacd98f85c0b64d85cb4e96e4f4789a1522e6443674447a1359d6f3e9a","ci/before_install.sh":"025b6b7ac157ea43ab602bf770740929ee45aa6bf6832674c06356c380640230","ci/install.bat":"a81cc40ad9f75fd8448f0f15536c426352ad8ad6809eaf564925b709c458aade","ci/script.sh":"1bb1cd29bd9635cc126cdcbd6c02f3500620a231a86726bf2165a4b74baaf433","ci/test_script.bat":"6240fb92d8d70126deedcf38cab49a31e5fc5364a3b13e7d4bb3e4654b352446","clippy.toml":"acef14b9acffa18d1069ae08a4e8fe824a614f91b0bc71a6b1c68e4d885397e6","src/lib.rs":"67783882b446e3d732fb23e7e5d18986b9546abf8fefbfcec99da12f9b1279cd","src/link.rs":"2f4b9fadc4d565702aa3ef9bc4a9945cd6b68a1e7bd7d0daf74067a4cc624b60","src/support.rs":"c44373478c7ad699740ada941735f9bc49d3e17e5bf3c553683d0143d97171b0","tests/header.h":"b1cf564b21d76db78529d1934e1481a5f0452fdedc6e32954608293c310498b6","tests/lib.rs":"9225ffcaa892a3901c0dce9f8190421db8fb17651499b4de765b87f08daaf5b2"},"package":"822ea22bbbef9f5934e9477860545fb0311a1759e43a276de42e2856c605aa2b"} \ No newline at end of file diff --git a/bash-5.1/vendor/clang-sys/CHANGELOG.md b/bash-5.1/vendor/clang-sys/CHANGELOG.md new file mode 100644 index 0000000..4e40dee --- /dev/null +++ b/bash-5.1/vendor/clang-sys/CHANGELOG.md @@ -0,0 +1,175 @@ +## [0.12.0] - 2016-12-13 + +### Changed +- Altered the runtime linking API to allow for testing the presence of functions + +## [0.11.1] - 2016-12-07 + +### Added +- Added support for linking to Clang on Windows from unofficial LLVM sources such as MSYS and MinGW + +## [0.11.0] - 2016-10-07 + +### Changed +- Changed all enums from Rust enums to typed constants to avoid + [undefined behavior](https://github.com/KyleMayes/clang-sys/issues/42) + +## [0.10.1] - 2016-08-21 + +### Changed +- Changed static linking on FreeBSD and OS X to link against `libc++` instead of `libstd++` + +## [0.10.0] - 2016-08-01 + +### Changed +- Added `runtime` Cargo feature that links to `libclang` shared library at runtime +- Added `from_raw` method to `CXTypeLayoutError` enum +- Added implementations of `Deref` for opaque FFI structs +- Changed `Default` implementations for structs to zero out the struct + +## [0.9.0] - 2016-07-21 + +### Added +- Added documentation bindings + +## [0.8.1] - 2016-07-20 + +### Changed +- Added `CLANG_PATH` environment variable for providing a path to `clang` executable +- Added usage of `llvm-config` to search for `clang` +- Added usage of `xcodebuild` to search for `clang` on OS X + +## [0.8.0] - 2016-07-18 + +### Added +- Added support for `clang` 3.9.x + +### Changed +- Bumped `libc` version to `0.2.14` + +### Fixed +- Fixed `LIBCLANG_PATH` usage on Windows to search both the `bin` and `lib` directories +- Fixed search path parsing on OS X +- Fixed search path parsing on Windows +- Fixed default search path ordering on OS X + +## [0.7.2] - 2016-06-17 + +### Fixed +- Fixed finding of `clang` executables when system has executables matching `clang-*` + (e.g., `clang-format`) + +## [0.7.1] - 2016-06-10 + +### Changed +- Bumped `libc` version to `0.2.12` + +### Fixed +- Fixed finding of `clang` executables suffixed by their version (e.g., `clang-3.5`) + +## [0.7.0] - 2016-05-31 + +### Changed +- Changed `Clang` struct `version` field type to `Option` + +## [0.6.0] - 2016-05-26 + +### Added +- Added `support` module + +### Fixed +- Fixed `libclang` linking on FreeBSD +- Fixed `libclang` linking on Windows with the MSVC toolchain +- Improved `libclang` static linking + +## [0.5.4] - 20160-5-19 + +### Changed +- Added implementations of `Default` for FFI structs + +## [0.5.3] - 2016-05-17 + +### Changed +- Bumped `bitflags` version to `0.7.0` + +## [0.5.2] - 2016-05-12 + +### Fixed +- Fixed `libclang` static linking + +## [0.5.1] - 2016-05-10 + +### Fixed +- Fixed `libclang` linking on OS X +- Fixed `libclang` linking on Windows + +## [0.5.0] - 2016-05-10 + +### Removed +- Removed `rustc_version` dependency +- Removed support for `LIBCLANG_STATIC` environment variable + +### Changed +- Bumped `bitflags` version to `0.6.0` +- Bumped `libc` version to `0.2.11` +- Improved `libclang` search path +- Improved `libclang` static linking + +## [0.4.2] - 2016-04-20 + +### Changed +- Bumped `libc` version to `0.2.10` + +## [0.4.1] - 2016-04-02 + +### Changed +- Bumped `libc` version to `0.2.9` +- Bumped `rustc_version` version to `0.1.7` + +## [0.4.0] - 2016-03-28 + +### Removed +- Removed support for `clang` 3.4.x + +## [0.3.1] - 2016-03-21 + +### Added +- Added support for finding `libclang` + +## [0.3.0] - 2016-03-16 + +### Removed +- Removed build system types and functions + +### Added +- Added support for `clang` 3.4.x + +### Changed +- Bumped `bitflags` version to `0.5.0` +- Bumped `libc` version to `0.2.8` + +## [0.2.1] - 2016-02-13 + +### Changed +- Simplified internal usage of conditional compilation +- Bumped `bitflags` version to `0.4.0` +- Bumped `libc` version to `0.2.7` +- Bumped `rustc_version` version to `0.1.6` + +## [0.2.0] - 2016-02-12 + +### Added +- Added support for `clang` 3.8.x + +## [0.1.2] - 2015-12-29 + +### Added +- Added derivations of `Debug` for FFI structs + +## [0.1.1] - 2015-12-26 + +### Added +- Added derivations of `PartialOrd` and `Ord` for FFI enums + +## [0.1.0] - 2015-12-22 +- Initial release diff --git a/bash-5.1/vendor/clang-sys/CONTRIBUTING.md b/bash-5.1/vendor/clang-sys/CONTRIBUTING.md new file mode 100644 index 0000000..185af05 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/CONTRIBUTING.md @@ -0,0 +1,14 @@ +Contributing to clang-sys +========================= + +Issues +------ + +Please include the output of `rustc --version --verbose` in your issue. + +Pull Requests +------------- + +If you are intending to make a pull request, please make your changes in a branch that originated +from the `development` branch, not the `master` branch. Then, make your pull request against the +`development` branch. diff --git a/bash-5.1/vendor/clang-sys/Cargo.toml b/bash-5.1/vendor/clang-sys/Cargo.toml new file mode 100644 index 0000000..f8e2167 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/Cargo.toml @@ -0,0 +1,48 @@ +[package] + +name = "clang-sys" +authors = ["Kyle Mayes "] + +version = "0.12.0" + +readme = "README.md" +license = "Apache-2.0" + +description = "Rust bindings for libclang." + +documentation = "https://kylemayes.github.io/clang-sys/3_5/clang_sys" +repository = "https://github.com/KyleMayes/clang-sys" + +build = "build.rs" + +[features] + +clang_3_5 = [] +clang_3_6 = ["gte_clang_3_6"] +clang_3_7 = ["gte_clang_3_6", "gte_clang_3_7"] +clang_3_8 = ["gte_clang_3_6", "gte_clang_3_7", "gte_clang_3_8"] +clang_3_9 = ["gte_clang_3_6", "gte_clang_3_7", "gte_clang_3_8", "gte_clang_3_9"] + +gte_clang_3_6 = [] +gte_clang_3_7 = [] +gte_clang_3_8 = [] +gte_clang_3_9 = [] + +runtime = ["lazy_static", "libloading"] +static = [] + +[dependencies] + +bitflags = "0.7.0" +glob = "0.2.11" +lazy_static = { version = "0.2.1", optional = true } +libc = "0.2.14" +libloading = { version = "0.3.0", optional = true } + +clippy = { version = "0.0.*", optional = true } + +[build-dependencies] + +glob = "0.2.11" + +clippy = { version = "0.0.*", optional = true } diff --git a/bash-5.1/vendor/clang-sys/LICENSE.txt b/bash-5.1/vendor/clang-sys/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/bash-5.1/vendor/clang-sys/README.md b/bash-5.1/vendor/clang-sys/README.md new file mode 100644 index 0000000..2ba1d19 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/README.md @@ -0,0 +1,96 @@ +# clang-sys + +[![crates.io](https://img.shields.io/crates/v/clang-sys.svg)](https://crates.io/crates/clang-sys) +[![Travis CI](https://travis-ci.org/KyleMayes/clang-sys.svg?branch=master)](https://travis-ci.org/KyleMayes/clang-sys) +[![AppVeyor](https://ci.appveyor.com/api/projects/status/7tv5mjyg55rof356/branch/master?svg=true)](https://ci.appveyor.com/project/KyleMayes/clang-sys-vtvy5/branch/master) + +Rust bindings for `libclang`. + +If you are interested in a Rust wrapper for these bindings, see +[clang-rs](https://github.com/KyleMayes/clang-rs). + +Supported on the stable, beta, and nightly Rust channels. + +Released under the Apache License 2.0. + +## Supported Versions + +To target a version of `libclang`, enable one of the following Cargo features: + +* `clang_3_5` - requires `libclang` 3.5 or later + ([Documentation](https://kylemayes.github.io/clang-sys/3_5/clang_sys)) +* `clang_3_6` - requires `libclang` 3.6 or later + ([Documentation](https://kylemayes.github.io/clang-sys/3_6/clang_sys)) +* `clang_3_7` - requires `libclang` 3.7 or later + ([Documentation](https://kylemayes.github.io/clang-sys/3_7/clang_sys)) +* `clang_3_8` - requires `libclang` 3.8 or later + ([Documentation](https://kylemayes.github.io/clang-sys/3_8/clang_sys)) +* `clang_3_9` - requires `libclang` 3.9 or later + ([Documentation](https://kylemayes.github.io/clang-sys/3_9/clang_sys)) + +If you do not enable one of these features, the API provided by `libclang` 3.5 will be available by +default. + +## Dependencies + +By default, this crate will attempt to link to `libclang` dynamically. In this case, this crate +depends on the `libclang` shared library (`libclang.so` on Linux, `libclang.dylib` on OS X, +`libclang.dll` on Windows). If you want to link to `libclang` statically instead, enable the +`static` Cargo feature. In this case, this crate depends on the LLVM and Clang static libraries. If +you don't want to link to `libclang` at compiletime but instead want to load it at runtime, enable +the `runtime` Cargo feature. + +These libraries can be either be installed as a part of Clang or downloaded +[here](http://llvm.org/releases/download.html). + +**Note:** Installing `libclang` through a package manager might install the `libclang` shared +library as something like `libclang.so.1` instead of `libclang.so`. In this case, you need to make a +symbolic link from the versioned shared library to `libclang.so`. + +**Note:** The downloads for LLVM and Clang 3.8 and later do not include the `libclang.a` static +library. This means you cannot link to any of these versions of `libclang` statically unless you +build it from source. + +## Environment Variables + +The following environment variables, if set, are used by this crate to find the required libraries +and executables: + +* `LLVM_CONFIG_PATH` **(compile time)** - provides a path to an `llvm-config` executable +* `LIBCLANG_PATH` **(compile time)** - provides a path to a directory containing a `libclang` shared + library +* `LIBCLANG_STATIC_PATH` **(compile time)** - provides a path to a directory containing LLVM and + Clang static libraries +* `CLANG_PATH` **(run time)** - provides a path to a `clang` executable + +## Linking + +### Dynamic + +First, the `libclang` shared library will be searched for in the directory provided by the +`LIBCLANG_PATH` environment variable if it was set. If this fails, the directory returned by +`llvm-config --libdir` will be searched. If neither of these approaches is successful, a list of +likely directories will be searched (e.g., `/usr/local/lib` on Linux). + +On Linux, running an executable that has been dynamically linked to `libclang` may require you to +add a path to `libclang.so` to the `LD_LIBRARY_PATH` environment variable. The same is true on OS +X, except the `DYLD_LIBRARY_PATH` environment variable is used instead. + +On Windows, running an executable that has been dynamically linked to `libclang` requires that +`libclang.dll` can be found by the executable at runtime. See +[here](https://msdn.microsoft.com/en-us/library/7d83bc18.aspx) for more information. + +### Static + +The availability of `llvm-config` is not optional for static linking. Ensure that an instance of +this executable can be found on your system's path or set the `LLVM_CONFIG_PATH` environment +variable. The required LLVM and Clang static libraries will be searched for in the same way as the +shared library is searched for, except the `LIBCLANG_STATIC_PATH` environment variable is used in +place of the `LIBCLANG_PATH` environment variable. + +### Runtime + +The `clang_sys::load` function is used to load a `libclang` shared library for use in the thread in +which it is called. The `clang_sys::unload` function will unload the `libclang` shared library. +`clang_sys::load` searches for a `libclang` shared library in the same way one is searched for when +linking to `libclang` dynamically at compiletime. diff --git a/bash-5.1/vendor/clang-sys/appveyor.yml b/bash-5.1/vendor/clang-sys/appveyor.yml new file mode 100644 index 0000000..a0b1c05 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/appveyor.yml @@ -0,0 +1,12 @@ +environment: + matrix: + - LLVM_VERSION: 3.9 + CLANG_VERSION: clang_3_9 + +install: + - .\ci\install.bat + +build: false + +test_script: + - .\ci\test_script.bat diff --git a/bash-5.1/vendor/clang-sys/build.rs b/bash-5.1/vendor/clang-sys/build.rs new file mode 100644 index 0000000..ba0a733 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/build.rs @@ -0,0 +1,288 @@ +// Copyright 2016 Kyle Mayes +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Finds and links to the required `libclang` libraries. + +#![cfg_attr(feature="clippy", feature(plugin))] +#![cfg_attr(feature="clippy", plugin(clippy))] +#![cfg_attr(feature="clippy", warn(clippy))] + +extern crate glob; + +use std::env; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command}; + +use glob::{MatchOptions}; + +// Environment variables: +// +// * LLVM_CONFIG_PATH - provides a path to an `llvm-config` executable +// * LIBCLANG_PATH - provides a path to a directory containing a `libclang` shared library +// * LIBCLANG_STATIC_PATH - provides a path to a directory containing LLVM and Clang static libraries + +/// Returns a path to one of the supplied files if such a file can be found in the supplied directory. +fn contains>(directory: D, files: &[String]) -> Option { + files.iter().map(|file| directory.as_ref().join(file)).find(|file| file.exists()) +} + +/// Runs a console command, returning the output if the command was successfully executed. +fn run(command: &str, arguments: &[&str]) -> Option { + Command::new(command).args(arguments).output().map(|o| { + String::from_utf8_lossy(&o.stdout).into_owned() + }).ok() +} + +/// Runs `llvm-config`, returning the output if the command was successfully executed. +fn run_llvm_config(arguments: &[&str]) -> Option { + run(&env::var("LLVM_CONFIG_PATH").unwrap_or("llvm-config".into()), arguments) +} + +/// Backup search directory globs for FreeBSD and Linux. +const SEARCH_LINUX: &'static [&'static str] = &[ + "/usr/lib*", + "/usr/lib*/*", + "/usr/lib*/*/*", + "/usr/local/lib*", + "/usr/local/lib*/*", + "/usr/local/lib*/*/*", + "/usr/local/llvm*/lib", +]; + +/// Backup search directory globs for OS X. +const SEARCH_OSX: &'static [&'static str] = &[ + "/usr/local/opt/llvm*/lib", + "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib", + "/Library/Developer/CommandLineTools/usr/lib", + "/usr/local/opt/llvm*/lib/llvm*/lib", +]; + +/// Backup search directory globs for Windows. +const SEARCH_WINDOWS: &'static [&'static str] = &[ + "C:\\LLVM\\lib", + "C:\\Program Files*\\LLVM\\lib", + "C:\\MSYS*\\MinGW*\\lib", +]; + +/// Searches for a library, returning the directory it can be found in if the search was successful. +fn find(files: &[String], env: &str) -> Result { + /// Searches the supplied directory and, on Windows, any relevant sibling directories. + macro_rules! search_directory { + ($directory:ident) => { + if let Some(file) = contains(&$directory, files) { + return Ok(file); + } + + // On Windows, `libclang.dll` is usually found in the LLVM `bin` directory while + // `libclang.lib` is usually found in the LLVM `lib` directory. To keep things + // consistent with other platforms, only LLVM `lib` directories are included in the + // backup search directory globs so we need to search the LLVM `bin` directory here. + if cfg!(target_os="windows") && $directory.ends_with("lib") { + let sibling = $directory.parent().unwrap().join("bin"); + if let Some(file) = contains(&sibling, files) { + return Ok(file); + } + } + } + } + + // Search the directory provided by the relevant environment variable if it is set. + if let Ok(directory) = env::var(env).map(|d| Path::new(&d).to_path_buf()) { + search_directory!(directory); + } + + // Search the `bin` and `lib` subdirectories in the directory returned by + // `llvm-config --prefix` if `llvm-config` is available. + if let Some(output) = run_llvm_config(&["--prefix"]) { + let directory = Path::new(output.lines().next().unwrap()).to_path_buf(); + let bin = directory.join("bin"); + if let Some(file) = contains(&bin, files) { + return Ok(file); + } + let lib = directory.join("lib"); + if let Some(file) = contains(&lib, files) { + return Ok(file); + } + } + + // Search the backup directories. + let search = if cfg!(any(target_os="freebsd", target_os="linux")) { + SEARCH_LINUX + } else if cfg!(target_os="macos") { + SEARCH_OSX + } else if cfg!(target_os="windows") { + SEARCH_WINDOWS + } else { + &[] + }; + for pattern in search { + let mut options = MatchOptions::new(); + options.case_sensitive = false; + options.require_literal_separator = true; + if let Ok(paths) = glob::glob_with(pattern, &options) { + for path in paths.filter_map(Result::ok).filter(|p| p.is_dir()) { + search_directory!(path); + } + } + } + + let message = format!( + "couldn't find any of {}, set the {} environment variable to a path where one of these \ + files can be found", + files.iter().map(|f| format!("'{}'", f)).collect::>().join(", "), + env, + ); + Err(message) +} + +/// Searches for a `libclang` shared library, returning the path to such a shared library if the +/// search was successful. +pub fn find_shared_library() -> Result { + let mut files = vec![]; + if cfg!(target_os="windows") { + // The official LLVM build uses `libclang.dll` on Windows instead of `clang.dll`. However, + // unofficial builds such as MinGW use `clang.dll`. + files.push("libclang.dll".into()); + } + files.push(format!("{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX)); + find(&files, "LIBCLANG_PATH") +} + +/// Returns the name of an LLVM or Clang library from a path to such a library. +fn get_library_name(path: &Path) -> Option { + path.file_stem().map(|l| l.to_string_lossy()[3..].into()) +} + +/// Returns the LLVM libraries required to link to `libclang` statically. +fn get_llvm_libraries() -> Vec { + run_llvm_config(&["--libs"]).expect( + "couldn't execute `llvm-config --libs`, set the LLVM_CONFIG_PATH environment variable to a \ + path to an `llvm-config` executable" + ).split_whitespace().filter_map(|p| { + // Depending on the version of `llvm-config` in use, listed libraries may be in one of two + // forms, a full path to the library or simply prefixed with `-l`. + if p.starts_with("-l") { + Some(p[2..].into()) + } else { + get_library_name(Path::new(p)) + } + }).collect() +} + +/// Clang libraries required to link to `libclang` 3.5 and later statically. +const CLANG_LIBRARIES: &'static [&'static str] = &[ + "clang", + "clangAST", + "clangAnalysis", + "clangBasic", + "clangDriver", + "clangEdit", + "clangFrontend", + "clangIndex", + "clangLex", + "clangParse", + "clangRewrite", + "clangSema", + "clangSerialization", +]; + +/// Returns the Clang libraries required to link to `libclang` statically. +fn get_clang_libraries>(directory: P) -> Vec { + let pattern = directory.as_ref().join("libclang*.a").to_string_lossy().to_string(); + if let Ok(libraries) = glob::glob(&pattern) { + libraries.filter_map(|l| l.ok().and_then(|l| get_library_name(&l))).collect() + } else { + CLANG_LIBRARIES.iter().map(|l| l.to_string()).collect() + } +} + +/// Find and link to `libclang` statically. +#[cfg_attr(feature="runtime", allow(dead_code))] +fn link_static() { + let file = find(&["libclang.a".into()], "LIBCLANG_STATIC_PATH").unwrap(); + let directory = file.parent().unwrap(); + print!("cargo:rustc-flags="); + + // Specify required LLVM and Clang static libraries. + print!("-L {} ", directory.display()); + for library in get_llvm_libraries() { + print!("-l static={} ", library); + } + for library in get_clang_libraries(&directory) { + print!("-l static={} ", library); + } + + // Specify required system libraries. + if cfg!(target_os="freebsd") { + println!("-l ffi -l ncursesw -l c++ -l z"); + } else if cfg!(target_os="linux") { + println!("-l ffi -l ncursesw -l stdc++ -l z"); + } else if cfg!(target_os="macos") { + println!("-l ffi -l ncurses -l c++ -l z"); + } else { + panic!("unsupported operating system for static linking"); + } +} + +/// Find and link to `libclang` dynamically. +#[cfg_attr(feature="runtime", allow(dead_code))] +fn link_dynamic() { + let file = find_shared_library().unwrap(); + let directory = file.parent().unwrap(); + println!("cargo:rustc-link-search={}", directory.display()); + + if cfg!(all(target_os="windows", target_env="msvc")) { + // Find the `libclang` stub static library required for the MSVC toolchain. + let libdir = if !directory.ends_with("bin") { + directory.to_owned() + } else { + directory.parent().unwrap().join("lib") + }; + if libdir.join("libclang.lib").exists() { + println!("cargo:rustc-link-search={}", libdir.display()); + } else if libdir.join("libclang.dll.a").exists() { + // MSYS and MinGW use `libclang.dll.a` instead of `libclang.lib`. It is linkable with + // the MSVC linker, but Rust doesn't recognize the `.a` suffix, so we need to copy it + // with a different name. + // + // FIXME: Maybe we can just hardlink or symlink it? + let out = env::var("OUT_DIR").unwrap(); + fs::copy(libdir.join("libclang.dll.a"), Path::new(&out).join("libclang.lib")).unwrap(); + println!("cargo:rustc-link-search=native={}", out); + } else { + panic!( + "using '{}', so 'libclang.lib' or 'libclang.dll.a' must be available in {}", + file.display(), + libdir.display(), + ); + } + println!("cargo:rustc-link-lib=dylib=libclang"); + } else { + println!("cargo:rustc-link-lib=dylib=clang"); + } +} + +#[cfg_attr(feature="runtime", allow(dead_code))] +fn main() { + if cfg!(feature="runtime") { + if cfg!(feature="static") { + panic!("`runtime` and `static` features can't be combined"); + } + } else if cfg!(feature="static") { + link_static(); + } else { + link_dynamic(); + } +} diff --git a/bash-5.1/vendor/clang-sys/ci/before_install.sh b/bash-5.1/vendor/clang-sys/ci/before_install.sh new file mode 100755 index 0000000..da4166e --- /dev/null +++ b/bash-5.1/vendor/clang-sys/ci/before_install.sh @@ -0,0 +1,32 @@ +set -e + +function llvm_version_triple() { + if [ "$1" == "3.5" ]; then + echo "3.5.2" + elif [ "$1" == "3.6" ]; then + echo "3.6.2" + elif [ "$1" == "3.7" ]; then + echo "3.7.1" + elif [ "$1" == "3.8" ]; then + echo "3.8.1" + elif [ "$1" == "3.9" ]; then + echo "3.9.0" + fi +} + +function llvm_download() { + export LLVM_VERSION_TRIPLE=`llvm_version_triple ${LLVM_VERSION}` + export LLVM=clang+llvm-${LLVM_VERSION_TRIPLE}-x86_64-$1 + + wget http://llvm.org/releases/${LLVM_VERSION_TRIPLE}/${LLVM}.tar.xz + mkdir llvm + tar -xf ${LLVM}.tar.xz -C llvm --strip-components=1 + + export LLVM_CONFIG_PATH=`pwd`/llvm/bin/llvm-config +} + +if [ "${TRAVIS_OS_NAME}" == "linux" ]; then + llvm_download linux-gnu-ubuntu-14.04 +else + llvm_download apple-darwin +fi diff --git a/bash-5.1/vendor/clang-sys/ci/install.bat b/bash-5.1/vendor/clang-sys/ci/install.bat new file mode 100644 index 0000000..07d72c6 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/ci/install.bat @@ -0,0 +1,8 @@ +curl -sSf https://static.rust-lang.org/dist/rust-1.10.0-i686-pc-windows-msvc.exe -o rust.exe +rust.exe /VERYSILENT /NORESTART /DIR="C:\Rust" +set PATH=%PATH%;C:\Rust\bin + +curl -sSf http://llvm.org/releases/%LLVM_VERSION%.0/LLVM-%LLVM_VERSION%.0-win32.exe -o LLVM.exe +7z x LLVM.exe -oC:\LLVM +set PATH=%PATH%;C:\LLVM\bin +set LIBCLANG_PATH=C:\LLVM\bin diff --git a/bash-5.1/vendor/clang-sys/ci/script.sh b/bash-5.1/vendor/clang-sys/ci/script.sh new file mode 100755 index 0000000..47ca439 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/ci/script.sh @@ -0,0 +1,13 @@ +if [ "${TRAVIS_OS_NAME}" == "osx" ]; then + rvm get head || true +fi + +set -e + +RUST_BACKTRACE=1 cargo test --verbose --features $CLANG_VERSION -- --nocapture + +if [ "${CLANG_VERSION}" \< "clang_3_7" ]; then + RUST_BACKTRACE=1 cargo test --verbose --features "$CLANG_VERSION static" -- --nocapture +fi + +RUST_BACKTRACE=1 cargo test --verbose --features "$CLANG_VERSION runtime" -- --nocapture diff --git a/bash-5.1/vendor/clang-sys/ci/test_script.bat b/bash-5.1/vendor/clang-sys/ci/test_script.bat new file mode 100644 index 0000000..62eed5e --- /dev/null +++ b/bash-5.1/vendor/clang-sys/ci/test_script.bat @@ -0,0 +1,3 @@ +set RUST_BACKTRACE=1 +cargo test --verbose --features %CLANG_VERSION% -- --nocapture +cargo test --verbose --features "%CLANG_VERSION% runtime" -- --nocapture diff --git a/bash-5.1/vendor/clang-sys/clippy.toml b/bash-5.1/vendor/clang-sys/clippy.toml new file mode 100644 index 0000000..006bfc4 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/clippy.toml @@ -0,0 +1 @@ +doc-valid-idents = ["FreeBSD"] diff --git a/bash-5.1/vendor/clang-sys/src/lib.rs b/bash-5.1/vendor/clang-sys/src/lib.rs new file mode 100644 index 0000000..9f6eda8 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/src/lib.rs @@ -0,0 +1,1740 @@ +// Copyright 2016 Kyle Mayes +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Rust bindings for `libclang`. +//! +//! ## Supported Versions +//! +//! * 3.5 - [Documentation](https://kylemayes.github.io/clang-sys/3_5/clang_sys) +//! * 3.6 - [Documentation](https://kylemayes.github.io/clang-sys/3_6/clang_sys) +//! * 3.7 - [Documentation](https://kylemayes.github.io/clang-sys/3_7/clang_sys) +//! * 3.8 - [Documentation](https://kylemayes.github.io/clang-sys/3_8/clang_sys) +//! * 3.9 - [Documentation](https://kylemayes.github.io/clang-sys/3_9/clang_sys) + +#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] + +#![cfg_attr(feature="clippy", feature(plugin))] +#![cfg_attr(feature="clippy", plugin(clippy))] +#![cfg_attr(feature="clippy", warn(clippy))] + +#[macro_use] +extern crate bitflags; +#[cfg(feature="runtime")] +#[macro_use] +extern crate lazy_static; + +extern crate glob; +extern crate libc; +#[cfg(feature="runtime")] +extern crate libloading; + +pub mod support; + +#[macro_use] +mod link; + +use std::mem; +use std::ptr; + +use libc::{c_char, c_int, c_longlong, c_uint, c_ulong, c_ulonglong, c_void, time_t}; + +pub type CXClientData = *mut c_void; +pub type CXCursorVisitor = extern fn(CXCursor, CXCursor, CXClientData) -> CXChildVisitResult; +#[cfg(feature="gte_clang_3_7")] +pub type CXFieldVisitor = extern fn(CXCursor, CXClientData) -> CXVisitorResult; +pub type CXInclusionVisitor = extern fn(CXFile, *mut CXSourceLocation, c_uint, CXClientData); + +//================================================ +// Macros +//================================================ + +// cenum! ________________________________________ + +/// Defines a type-safe C enum as a series of constants. +macro_rules! cenum { + ($(#[$meta:meta])* enum $name:ident { + $($(#[$vmeta:meta])* const $variant:ident = $value:expr), +, + }) => ( + #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] + #[repr(C)] + pub struct $name(c_int); + + impl $name { + //- Constructors --------------------- + + /// Constructs an instance of this C enum from the supplied discriminant if possible. + pub fn from_raw(discriminant: c_int) -> Option<$name> { + $(if discriminant == $value { return Some($variant); })+ + None + } + + //- Accessors ------------------------ + + /// Returns the discriminant for this C enum. + pub fn to_raw(self) -> c_int { + self.0 + } + } + + $($(#[$vmeta])* pub const $variant: $name = $name($value);)+ + ); +} + +// default! ______________________________________ + +/// Implements a zeroing implementation of `Default` for the supplied type. +macro_rules! default { + (#[$meta:meta] $ty:ty) => { + #[$meta] + impl Default for $ty { + fn default() -> $ty { + unsafe { mem::zeroed() } + } + } + }; + + ($ty:ty) => { + impl Default for $ty { + fn default() -> $ty { + unsafe { mem::zeroed() } + } + } + }; +} + +//================================================ +// Enums +//================================================ + +cenum! { + enum CXAvailabilityKind { + const CXAvailability_Available = 0, + const CXAvailability_Deprecated = 1, + const CXAvailability_NotAvailable = 2, + const CXAvailability_NotAccessible = 3, + } +} + +cenum! { + enum CXCallingConv { + const CXCallingConv_Default = 0, + const CXCallingConv_C = 1, + const CXCallingConv_X86StdCall = 2, + const CXCallingConv_X86FastCall = 3, + const CXCallingConv_X86ThisCall = 4, + const CXCallingConv_X86Pascal = 5, + const CXCallingConv_AAPCS = 6, + const CXCallingConv_AAPCS_VFP = 7, + const CXCallingConv_IntelOclBicc = 9, + const CXCallingConv_X86_64Win64 = 10, + const CXCallingConv_X86_64SysV = 11, + /// Only produced by `libclang` 3.6 and later. + const CXCallingConv_X86VectorCall = 12, + /// Only produced by `libclang` 3.9 and later. + const CXCallingConv_Swift = 13, + /// Only produced by `libclang` 3.9 and later. + const CXCallingConv_PreserveMost = 14, + /// Only produced by `libclang` 3.9 and later. + const CXCallingConv_PreserveAll = 15, + const CXCallingConv_Invalid = 100, + const CXCallingConv_Unexposed = 200, + } +} + +cenum! { + enum CXChildVisitResult { + const CXChildVisit_Break = 0, + const CXChildVisit_Continue = 1, + const CXChildVisit_Recurse = 2, + } +} + +cenum! { + enum CXCommentInlineCommandRenderKind { + const CXCommentInlineCommandRenderKind_Normal = 0, + const CXCommentInlineCommandRenderKind_Bold = 1, + const CXCommentInlineCommandRenderKind_Monospaced = 2, + const CXCommentInlineCommandRenderKind_Emphasized = 3, + } +} + +cenum! { + enum CXCommentKind { + const CXComment_Null = 0, + const CXComment_Text = 1, + const CXComment_InlineCommand = 2, + const CXComment_HTMLStartTag = 3, + const CXComment_HTMLEndTag = 4, + const CXComment_Paragraph = 5, + const CXComment_BlockCommand = 6, + const CXComment_ParamCommand = 7, + const CXComment_TParamCommand = 8, + const CXComment_VerbatimBlockCommand = 9, + const CXComment_VerbatimBlockLine = 10, + const CXComment_VerbatimLine = 11, + const CXComment_FullComment = 12, + } +} + +cenum! { + enum CXCommentParamPassDirection { + const CXCommentParamPassDirection_In = 0, + const CXCommentParamPassDirection_Out = 1, + const CXCommentParamPassDirection_InOut = 2, + } +} + +cenum! { + enum CXCompilationDatabase_Error { + const CXCompilationDatabase_NoError = 0, + const CXCompilationDatabase_CanNotLoadDatabase = 1, + } +} + +cenum! { + enum CXCompletionChunkKind { + const CXCompletionChunk_Optional = 0, + const CXCompletionChunk_TypedText = 1, + const CXCompletionChunk_Text = 2, + const CXCompletionChunk_Placeholder = 3, + const CXCompletionChunk_Informative = 4, + const CXCompletionChunk_CurrentParameter = 5, + const CXCompletionChunk_LeftParen = 6, + const CXCompletionChunk_RightParen = 7, + const CXCompletionChunk_LeftBracket = 8, + const CXCompletionChunk_RightBracket = 9, + const CXCompletionChunk_LeftBrace = 10, + const CXCompletionChunk_RightBrace = 11, + const CXCompletionChunk_LeftAngle = 12, + const CXCompletionChunk_RightAngle = 13, + const CXCompletionChunk_Comma = 14, + const CXCompletionChunk_ResultType = 15, + const CXCompletionChunk_Colon = 16, + const CXCompletionChunk_SemiColon = 17, + const CXCompletionChunk_Equal = 18, + const CXCompletionChunk_HorizontalSpace = 19, + const CXCompletionChunk_VerticalSpace = 20, + } +} + +cenum! { + enum CXCursorKind { + const CXCursor_UnexposedDecl = 1, + const CXCursor_StructDecl = 2, + const CXCursor_UnionDecl = 3, + const CXCursor_ClassDecl = 4, + const CXCursor_EnumDecl = 5, + const CXCursor_FieldDecl = 6, + const CXCursor_EnumConstantDecl = 7, + const CXCursor_FunctionDecl = 8, + const CXCursor_VarDecl = 9, + const CXCursor_ParmDecl = 10, + const CXCursor_ObjCInterfaceDecl = 11, + const CXCursor_ObjCCategoryDecl = 12, + const CXCursor_ObjCProtocolDecl = 13, + const CXCursor_ObjCPropertyDecl = 14, + const CXCursor_ObjCIvarDecl = 15, + const CXCursor_ObjCInstanceMethodDecl = 16, + const CXCursor_ObjCClassMethodDecl = 17, + const CXCursor_ObjCImplementationDecl = 18, + const CXCursor_ObjCCategoryImplDecl = 19, + const CXCursor_TypedefDecl = 20, + const CXCursor_CXXMethod = 21, + const CXCursor_Namespace = 22, + const CXCursor_LinkageSpec = 23, + const CXCursor_Constructor = 24, + const CXCursor_Destructor = 25, + const CXCursor_ConversionFunction = 26, + const CXCursor_TemplateTypeParameter = 27, + const CXCursor_NonTypeTemplateParameter = 28, + const CXCursor_TemplateTemplateParameter = 29, + const CXCursor_FunctionTemplate = 30, + const CXCursor_ClassTemplate = 31, + const CXCursor_ClassTemplatePartialSpecialization = 32, + const CXCursor_NamespaceAlias = 33, + const CXCursor_UsingDirective = 34, + const CXCursor_UsingDeclaration = 35, + const CXCursor_TypeAliasDecl = 36, + const CXCursor_ObjCSynthesizeDecl = 37, + const CXCursor_ObjCDynamicDecl = 38, + const CXCursor_CXXAccessSpecifier = 39, + const CXCursor_ObjCSuperClassRef = 40, + const CXCursor_ObjCProtocolRef = 41, + const CXCursor_ObjCClassRef = 42, + const CXCursor_TypeRef = 43, + const CXCursor_CXXBaseSpecifier = 44, + const CXCursor_TemplateRef = 45, + const CXCursor_NamespaceRef = 46, + const CXCursor_MemberRef = 47, + const CXCursor_LabelRef = 48, + const CXCursor_OverloadedDeclRef = 49, + const CXCursor_VariableRef = 50, + const CXCursor_InvalidFile = 70, + const CXCursor_NoDeclFound = 71, + const CXCursor_NotImplemented = 72, + const CXCursor_InvalidCode = 73, + const CXCursor_UnexposedExpr = 100, + const CXCursor_DeclRefExpr = 101, + const CXCursor_MemberRefExpr = 102, + const CXCursor_CallExpr = 103, + const CXCursor_ObjCMessageExpr = 104, + const CXCursor_BlockExpr = 105, + const CXCursor_IntegerLiteral = 106, + const CXCursor_FloatingLiteral = 107, + const CXCursor_ImaginaryLiteral = 108, + const CXCursor_StringLiteral = 109, + const CXCursor_CharacterLiteral = 110, + const CXCursor_ParenExpr = 111, + const CXCursor_UnaryOperator = 112, + const CXCursor_ArraySubscriptExpr = 113, + const CXCursor_BinaryOperator = 114, + const CXCursor_CompoundAssignOperator = 115, + const CXCursor_ConditionalOperator = 116, + const CXCursor_CStyleCastExpr = 117, + const CXCursor_CompoundLiteralExpr = 118, + const CXCursor_InitListExpr = 119, + const CXCursor_AddrLabelExpr = 120, + const CXCursor_StmtExpr = 121, + const CXCursor_GenericSelectionExpr = 122, + const CXCursor_GNUNullExpr = 123, + const CXCursor_CXXStaticCastExpr = 124, + const CXCursor_CXXDynamicCastExpr = 125, + const CXCursor_CXXReinterpretCastExpr = 126, + const CXCursor_CXXConstCastExpr = 127, + const CXCursor_CXXFunctionalCastExpr = 128, + const CXCursor_CXXTypeidExpr = 129, + const CXCursor_CXXBoolLiteralExpr = 130, + const CXCursor_CXXNullPtrLiteralExpr = 131, + const CXCursor_CXXThisExpr = 132, + const CXCursor_CXXThrowExpr = 133, + const CXCursor_CXXNewExpr = 134, + const CXCursor_CXXDeleteExpr = 135, + const CXCursor_UnaryExpr = 136, + const CXCursor_ObjCStringLiteral = 137, + const CXCursor_ObjCEncodeExpr = 138, + const CXCursor_ObjCSelectorExpr = 139, + const CXCursor_ObjCProtocolExpr = 140, + const CXCursor_ObjCBridgedCastExpr = 141, + const CXCursor_PackExpansionExpr = 142, + const CXCursor_SizeOfPackExpr = 143, + const CXCursor_LambdaExpr = 144, + const CXCursor_ObjCBoolLiteralExpr = 145, + const CXCursor_ObjCSelfExpr = 146, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_OMPArraySectionExpr = 147, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_ObjCAvailabilityCheckExpr = 148, + const CXCursor_UnexposedStmt = 200, + const CXCursor_LabelStmt = 201, + const CXCursor_CompoundStmt = 202, + const CXCursor_CaseStmt = 203, + const CXCursor_DefaultStmt = 204, + const CXCursor_IfStmt = 205, + const CXCursor_SwitchStmt = 206, + const CXCursor_WhileStmt = 207, + const CXCursor_DoStmt = 208, + const CXCursor_ForStmt = 209, + const CXCursor_GotoStmt = 210, + const CXCursor_IndirectGotoStmt = 211, + const CXCursor_ContinueStmt = 212, + const CXCursor_BreakStmt = 213, + const CXCursor_ReturnStmt = 214, + /// Duplicate of `CXCursor_GccAsmStmt`. + const CXCursor_AsmStmt = 215, + const CXCursor_ObjCAtTryStmt = 216, + const CXCursor_ObjCAtCatchStmt = 217, + const CXCursor_ObjCAtFinallyStmt = 218, + const CXCursor_ObjCAtThrowStmt = 219, + const CXCursor_ObjCAtSynchronizedStmt = 220, + const CXCursor_ObjCAutoreleasePoolStmt = 221, + const CXCursor_ObjCForCollectionStmt = 222, + const CXCursor_CXXCatchStmt = 223, + const CXCursor_CXXTryStmt = 224, + const CXCursor_CXXForRangeStmt = 225, + const CXCursor_SEHTryStmt = 226, + const CXCursor_SEHExceptStmt = 227, + const CXCursor_SEHFinallyStmt = 228, + const CXCursor_MSAsmStmt = 229, + const CXCursor_NullStmt = 230, + const CXCursor_DeclStmt = 231, + const CXCursor_OMPParallelDirective = 232, + const CXCursor_OMPSimdDirective = 233, + const CXCursor_OMPForDirective = 234, + const CXCursor_OMPSectionsDirective = 235, + const CXCursor_OMPSectionDirective = 236, + const CXCursor_OMPSingleDirective = 237, + const CXCursor_OMPParallelForDirective = 238, + const CXCursor_OMPParallelSectionsDirective = 239, + const CXCursor_OMPTaskDirective = 240, + const CXCursor_OMPMasterDirective = 241, + const CXCursor_OMPCriticalDirective = 242, + const CXCursor_OMPTaskyieldDirective = 243, + const CXCursor_OMPBarrierDirective = 244, + const CXCursor_OMPTaskwaitDirective = 245, + const CXCursor_OMPFlushDirective = 246, + const CXCursor_SEHLeaveStmt = 247, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_OMPOrderedDirective = 248, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_OMPAtomicDirective = 249, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_OMPForSimdDirective = 250, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_OMPParallelForSimdDirective = 251, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_OMPTargetDirective = 252, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_OMPTeamsDirective = 253, + /// Only produced by `libclang` 3.7 and later. + const CXCursor_OMPTaskgroupDirective = 254, + /// Only produced by `libclang` 3.7 and later. + const CXCursor_OMPCancellationPointDirective = 255, + /// Only produced by `libclang` 3.7 and later. + const CXCursor_OMPCancelDirective = 256, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_OMPTargetDataDirective = 257, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_OMPTaskLoopDirective = 258, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_OMPTaskLoopSimdDirective = 259, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_OMPDistributeDirective = 260, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPTargetEnterDataDirective = 261, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPTargetExitDataDirective = 262, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPTargetParallelDirective = 263, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPTargetParallelForDirective = 264, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPTargetUpdateDirective = 265, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPDistributeParallelForDirective = 266, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPDistributeParallelForSimdDirective = 267, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPDistributeSimdDirective = 268, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_OMPTargetParallelForSimdDirective = 269, + const CXCursor_TranslationUnit = 300, + const CXCursor_UnexposedAttr = 400, + const CXCursor_IBActionAttr = 401, + const CXCursor_IBOutletAttr = 402, + const CXCursor_IBOutletCollectionAttr = 403, + const CXCursor_CXXFinalAttr = 404, + const CXCursor_CXXOverrideAttr = 405, + const CXCursor_AnnotateAttr = 406, + const CXCursor_AsmLabelAttr = 407, + const CXCursor_PackedAttr = 408, + const CXCursor_PureAttr = 409, + const CXCursor_ConstAttr = 410, + const CXCursor_NoDuplicateAttr = 411, + const CXCursor_CUDAConstantAttr = 412, + const CXCursor_CUDADeviceAttr = 413, + const CXCursor_CUDAGlobalAttr = 414, + const CXCursor_CUDAHostAttr = 415, + /// Only produced by `libclang` 3.6 and later. + const CXCursor_CUDASharedAttr = 416, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_VisibilityAttr = 417, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_DLLExport = 418, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_DLLImport = 419, + const CXCursor_PreprocessingDirective = 500, + const CXCursor_MacroDefinition = 501, + /// Duplicate of `CXCursor_MacroInstantiation`. + const CXCursor_MacroExpansion = 502, + const CXCursor_InclusionDirective = 503, + const CXCursor_ModuleImportDecl = 600, + /// Only produced by `libclang` 3.8 and later. + const CXCursor_TypeAliasTemplateDecl = 601, + /// Only produced by `libclang` 3.9 and later. + const CXCursor_StaticAssert = 602, + /// Only produced by `libclang` 3.7 and later. + const CXCursor_OverloadCandidate = 700, + } +} + +cenum! { + enum CXDiagnosticSeverity { + const CXDiagnostic_Ignored = 0, + const CXDiagnostic_Note = 1, + const CXDiagnostic_Warning = 2, + const CXDiagnostic_Error = 3, + const CXDiagnostic_Fatal = 4, + } +} + +cenum! { + enum CXErrorCode { + const CXError_Success = 0, + const CXError_Failure = 1, + const CXError_Crashed = 2, + const CXError_InvalidArguments = 3, + const CXError_ASTReadError = 4, + } +} + +cenum! { + enum CXEvalResultKind { + const CXEval_UnExposed = 0, + const CXEval_Int = 1 , + const CXEval_Float = 2, + const CXEval_ObjCStrLiteral = 3, + const CXEval_StrLiteral = 4, + const CXEval_CFStr = 5, + const CXEval_Other = 6, + } +} + +cenum! { + enum CXIdxAttrKind { + const CXIdxAttr_Unexposed = 0, + const CXIdxAttr_IBAction = 1, + const CXIdxAttr_IBOutlet = 2, + const CXIdxAttr_IBOutletCollection = 3, + } +} + +cenum! { + enum CXIdxEntityCXXTemplateKind { + const CXIdxEntity_NonTemplate = 0, + const CXIdxEntity_Template = 1, + const CXIdxEntity_TemplatePartialSpecialization = 2, + const CXIdxEntity_TemplateSpecialization = 3, + } +} + +cenum! { + enum CXIdxEntityKind { + const CXIdxEntity_Unexposed = 0, + const CXIdxEntity_Typedef = 1, + const CXIdxEntity_Function = 2, + const CXIdxEntity_Variable = 3, + const CXIdxEntity_Field = 4, + const CXIdxEntity_EnumConstant = 5, + const CXIdxEntity_ObjCClass = 6, + const CXIdxEntity_ObjCProtocol = 7, + const CXIdxEntity_ObjCCategory = 8, + const CXIdxEntity_ObjCInstanceMethod = 9, + const CXIdxEntity_ObjCClassMethod = 10, + const CXIdxEntity_ObjCProperty = 11, + const CXIdxEntity_ObjCIvar = 12, + const CXIdxEntity_Enum = 13, + const CXIdxEntity_Struct = 14, + const CXIdxEntity_Union = 15, + const CXIdxEntity_CXXClass = 16, + const CXIdxEntity_CXXNamespace = 17, + const CXIdxEntity_CXXNamespaceAlias = 18, + const CXIdxEntity_CXXStaticVariable = 19, + const CXIdxEntity_CXXStaticMethod = 20, + const CXIdxEntity_CXXInstanceMethod = 21, + const CXIdxEntity_CXXConstructor = 22, + const CXIdxEntity_CXXDestructor = 23, + const CXIdxEntity_CXXConversionFunction = 24, + const CXIdxEntity_CXXTypeAlias = 25, + const CXIdxEntity_CXXInterface = 26, + } +} + +cenum! { + enum CXIdxEntityLanguage { + const CXIdxEntityLang_None = 0, + const CXIdxEntityLang_C = 1, + const CXIdxEntityLang_ObjC = 2, + const CXIdxEntityLang_CXX = 3, + } +} + +cenum! { + enum CXIdxEntityRefKind { + const CXIdxEntityRef_Direct = 1, + const CXIdxEntityRef_Implicit = 2, + } +} + +cenum! { + enum CXIdxObjCContainerKind { + const CXIdxObjCContainer_ForwardRef = 0, + const CXIdxObjCContainer_Interface = 1, + const CXIdxObjCContainer_Implementation = 2, + } +} + +cenum! { + enum CXLanguageKind { + const CXLanguage_Invalid = 0, + const CXLanguage_C = 1, + const CXLanguage_ObjC = 2, + const CXLanguage_CPlusPlus = 3, + } +} + +cenum! { + enum CXLinkageKind { + const CXLinkage_Invalid = 0, + const CXLinkage_NoLinkage = 1, + const CXLinkage_Internal = 2, + const CXLinkage_UniqueExternal = 3, + const CXLinkage_External = 4, + } +} + +cenum! { + enum CXLoadDiag_Error { + const CXLoadDiag_None = 0, + const CXLoadDiag_Unknown = 1, + const CXLoadDiag_CannotLoad = 2, + const CXLoadDiag_InvalidFile = 3, + } +} + +cenum! { + enum CXRefQualifierKind { + const CXRefQualifier_None = 0, + const CXRefQualifier_LValue = 1, + const CXRefQualifier_RValue = 2, + } +} + +cenum! { + enum CXResult { + const CXResult_Success = 0, + const CXResult_Invalid = 1, + const CXResult_VisitBreak = 2, + } +} + +cenum! { + enum CXSaveError { + const CXSaveError_None = 0, + const CXSaveError_Unknown = 1, + const CXSaveError_TranslationErrors = 2, + const CXSaveError_InvalidTU = 3, + } +} + +cenum! { + enum CXTUResourceUsageKind { + const CXTUResourceUsage_AST = 1, + const CXTUResourceUsage_Identifiers = 2, + const CXTUResourceUsage_Selectors = 3, + const CXTUResourceUsage_GlobalCompletionResults = 4, + const CXTUResourceUsage_SourceManagerContentCache = 5, + const CXTUResourceUsage_AST_SideTables = 6, + const CXTUResourceUsage_SourceManager_Membuffer_Malloc = 7, + const CXTUResourceUsage_SourceManager_Membuffer_MMap = 8, + const CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc = 9, + const CXTUResourceUsage_ExternalASTSource_Membuffer_MMap = 10, + const CXTUResourceUsage_Preprocessor = 11, + const CXTUResourceUsage_PreprocessingRecord = 12, + const CXTUResourceUsage_SourceManager_DataStructures = 13, + const CXTUResourceUsage_Preprocessor_HeaderSearch = 14, + } +} + +cenum! { + #[cfg(feature="gte_clang_3_6")] + enum CXTemplateArgumentKind { + const CXTemplateArgumentKind_Null = 0, + const CXTemplateArgumentKind_Type = 1, + const CXTemplateArgumentKind_Declaration = 2, + const CXTemplateArgumentKind_NullPtr = 3, + const CXTemplateArgumentKind_Integral = 4, + const CXTemplateArgumentKind_Template = 5, + const CXTemplateArgumentKind_TemplateExpansion = 6, + const CXTemplateArgumentKind_Expression = 7, + const CXTemplateArgumentKind_Pack = 8, + const CXTemplateArgumentKind_Invalid = 9, + } +} + +cenum! { + enum CXTokenKind { + const CXToken_Punctuation = 0, + const CXToken_Keyword = 1, + const CXToken_Identifier = 2, + const CXToken_Literal = 3, + const CXToken_Comment = 4, + } +} + +cenum! { + enum CXTypeKind { + const CXType_Invalid = 0, + const CXType_Unexposed = 1, + const CXType_Void = 2, + const CXType_Bool = 3, + const CXType_Char_U = 4, + const CXType_UChar = 5, + const CXType_Char16 = 6, + const CXType_Char32 = 7, + const CXType_UShort = 8, + const CXType_UInt = 9, + const CXType_ULong = 10, + const CXType_ULongLong = 11, + const CXType_UInt128 = 12, + const CXType_Char_S = 13, + const CXType_SChar = 14, + const CXType_WChar = 15, + const CXType_Short = 16, + const CXType_Int = 17, + const CXType_Long = 18, + const CXType_LongLong = 19, + const CXType_Int128 = 20, + const CXType_Float = 21, + const CXType_Double = 22, + const CXType_LongDouble = 23, + const CXType_NullPtr = 24, + const CXType_Overload = 25, + const CXType_Dependent = 26, + const CXType_ObjCId = 27, + const CXType_ObjCClass = 28, + const CXType_ObjCSel = 29, + /// Only produced by `libclang` 3.9 and later. + const CXType_Float128 = 30, + const CXType_Complex = 100, + const CXType_Pointer = 101, + const CXType_BlockPointer = 102, + const CXType_LValueReference = 103, + const CXType_RValueReference = 104, + const CXType_Record = 105, + const CXType_Enum = 106, + const CXType_Typedef = 107, + const CXType_ObjCInterface = 108, + const CXType_ObjCObjectPointer = 109, + const CXType_FunctionNoProto = 110, + const CXType_FunctionProto = 111, + const CXType_ConstantArray = 112, + const CXType_Vector = 113, + const CXType_IncompleteArray = 114, + const CXType_VariableArray = 115, + const CXType_DependentSizedArray = 116, + const CXType_MemberPointer = 117, + /// Only produced by `libclang` 3.8 and later. + const CXType_Auto = 118, + /// Only produced by `libclang` 3.9 and later. + const CXType_Elaborated = 119, + } +} + +cenum! { + enum CXTypeLayoutError { + const CXTypeLayoutError_Invalid = -1, + const CXTypeLayoutError_Incomplete = -2, + const CXTypeLayoutError_Dependent = -3, + const CXTypeLayoutError_NotConstantSize = -4, + const CXTypeLayoutError_InvalidFieldName = -5, + } +} + +cenum! { + #[cfg(feature="gte_clang_3_8")] + enum CXVisibilityKind { + const CXVisibility_Invalid = 0, + const CXVisibility_Hidden = 1, + const CXVisibility_Protected = 2, + const CXVisibility_Default = 3, + } +} + +cenum! { + enum CXVisitorResult { + const CXVisit_Break = 0, + const CXVisit_Continue = 1, + } +} + +cenum! { + enum CX_CXXAccessSpecifier { + const CX_CXXInvalidAccessSpecifier = 0, + const CX_CXXPublic = 1, + const CX_CXXProtected = 2, + const CX_CXXPrivate = 3, + } +} + +cenum! { + #[cfg(feature="gte_clang_3_6")] + enum CX_StorageClass { + const CX_SC_Invalid = 0, + const CX_SC_None = 1, + const CX_SC_Extern = 2, + const CX_SC_Static = 3, + const CX_SC_PrivateExtern = 4, + const CX_SC_OpenCLWorkGroupLocal = 5, + const CX_SC_Auto = 6, + const CX_SC_Register = 7, + } +} + +//================================================ +// Flags +//================================================ + +bitflags! { + #[repr(C)] + pub flags CXCodeComplete_Flags: c_uint { + const CXCodeComplete_IncludeMacros = 1, + const CXCodeComplete_IncludeCodePatterns = 2, + const CXCodeComplete_IncludeBriefComments = 4, + } +} + +bitflags! { + #[repr(C)] + pub flags CXCompletionContext: c_uint { + const CXCompletionContext_Unexposed = 0, + const CXCompletionContext_AnyType = 1, + const CXCompletionContext_AnyValue = 2, + const CXCompletionContext_ObjCObjectValue = 4, + const CXCompletionContext_ObjCSelectorValue = 8, + const CXCompletionContext_CXXClassTypeValue = 16, + const CXCompletionContext_DotMemberAccess = 32, + const CXCompletionContext_ArrowMemberAccess = 64, + const CXCompletionContext_ObjCPropertyAccess = 128, + const CXCompletionContext_EnumTag = 256, + const CXCompletionContext_UnionTag = 512, + const CXCompletionContext_StructTag = 1024, + const CXCompletionContext_ClassTag = 2048, + const CXCompletionContext_Namespace = 4096, + const CXCompletionContext_NestedNameSpecifier = 8192, + const CXCompletionContext_ObjCInterface = 16384, + const CXCompletionContext_ObjCProtocol = 32768, + const CXCompletionContext_ObjCCategory = 65536, + const CXCompletionContext_ObjCInstanceMessage = 131072, + const CXCompletionContext_ObjCClassMessage = 262144, + const CXCompletionContext_ObjCSelectorName = 524288, + const CXCompletionContext_MacroName = 1048576, + const CXCompletionContext_NaturalLanguage = 2097152, + const CXCompletionContext_Unknown = 4194303, + } +} + +bitflags! { + #[repr(C)] + pub flags CXDiagnosticDisplayOptions: c_uint { + const CXDiagnostic_DisplaySourceLocation = 1, + const CXDiagnostic_DisplayColumn = 2, + const CXDiagnostic_DisplaySourceRanges = 4, + const CXDiagnostic_DisplayOption = 8, + const CXDiagnostic_DisplayCategoryId = 16, + const CXDiagnostic_DisplayCategoryName = 32, + } +} + +bitflags! { + #[repr(C)] + pub flags CXGlobalOptFlags: c_uint { + const CXGlobalOpt_None = 0, + const CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 1, + const CXGlobalOpt_ThreadBackgroundPriorityForEditing = 2, + const CXGlobalOpt_ThreadBackgroundPriorityForAll = 3, + } +} + +bitflags! { + #[repr(C)] + pub flags CXIdxDeclInfoFlags: c_uint { + const CXIdxDeclFlag_Skipped = 1, + } +} + +bitflags! { + #[repr(C)] + pub flags CXIndexOptFlags: c_uint { + const CXIndexOptNone = 0, + const CXIndexOptSuppressRedundantRefs = 1, + const CXIndexOptIndexFunctionLocalSymbols = 2, + const CXIndexOptIndexImplicitTemplateInstantiations = 4, + const CXIndexOptSuppressWarnings = 8, + const CXIndexOptSkipParsedBodiesInSession = 16, + } +} + +bitflags! { + #[repr(C)] + pub flags CXNameRefFlags: c_uint { + const CXNameRange_WantQualifier = 1, + const CXNameRange_WantTemplateArgs = 2, + const CXNameRange_WantSinglePiece = 4 + } +} + +bitflags! { + #[repr(C)] + pub flags CXObjCDeclQualifierKind: c_uint { + const CXObjCDeclQualifier_None = 0, + const CXObjCDeclQualifier_In = 1, + const CXObjCDeclQualifier_Inout = 2, + const CXObjCDeclQualifier_Out = 4, + const CXObjCDeclQualifier_Bycopy = 8, + const CXObjCDeclQualifier_Byref = 16, + const CXObjCDeclQualifier_Oneway = 32, + } +} + +bitflags! { + #[repr(C)] + pub flags CXObjCPropertyAttrKind: c_uint { + const CXObjCPropertyAttr_noattr = 0, + const CXObjCPropertyAttr_readonly = 1, + const CXObjCPropertyAttr_getter = 2, + const CXObjCPropertyAttr_assign = 4, + const CXObjCPropertyAttr_readwrite = 8, + const CXObjCPropertyAttr_retain = 16, + const CXObjCPropertyAttr_copy = 32, + const CXObjCPropertyAttr_nonatomic = 64, + const CXObjCPropertyAttr_setter = 128, + const CXObjCPropertyAttr_atomic = 256, + const CXObjCPropertyAttr_weak = 512, + const CXObjCPropertyAttr_strong = 1024, + const CXObjCPropertyAttr_unsafe_unretained = 2048, + #[cfg(feature="gte_clang_3_9")] + const CXObjCPropertyAttr_class = 4096, + } +} + +bitflags! { + #[repr(C)] + pub flags CXReparse_Flags: c_uint { + const CXReparse_None = 0, + } +} + +bitflags! { + #[repr(C)] + pub flags CXSaveTranslationUnit_Flags: c_uint { + const CXSaveTranslationUnit_None = 0, + } +} + +bitflags! { + #[repr(C)] + pub flags CXTranslationUnit_Flags: c_uint { + const CXTranslationUnit_None = 0, + const CXTranslationUnit_DetailedPreprocessingRecord = 1, + const CXTranslationUnit_Incomplete = 2, + const CXTranslationUnit_PrecompiledPreamble = 4, + const CXTranslationUnit_CacheCompletionResults = 8, + const CXTranslationUnit_ForSerialization = 16, + const CXTranslationUnit_CXXChainedPCH = 32, + const CXTranslationUnit_SkipFunctionBodies = 64, + const CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 128, + #[cfg(feature="gte_clang_3_8")] + const CXTranslationUnit_CreatePreambleOnFirstParse = 256, + #[cfg(feature="gte_clang_3_9")] + const CXTranslationUnit_KeepGoing = 512, + } +} + +//================================================ +// Structs +//================================================ + +// Opaque ________________________________________ + +macro_rules! opaque { + ($name:ident) => ( + #[derive(Copy, Clone, Debug)] + #[repr(C)] + pub struct $name(pub *mut c_void); + + impl Default for $name { + fn default() -> $name { + $name(ptr::null_mut()) + } + } + + impl std::ops::Deref for $name { + type Target = *mut c_void; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + ); +} + +opaque!(CXCompilationDatabase); +opaque!(CXCompileCommand); +opaque!(CXCompileCommands); +opaque!(CXCompletionString); +opaque!(CXCursorSet); +opaque!(CXDiagnostic); +opaque!(CXDiagnosticSet); +#[cfg(feature="gte_clang_3_9")] +opaque!(CXEvalResult); +opaque!(CXFile); +opaque!(CXIdxClientASTFile); +opaque!(CXIdxClientContainer); +opaque!(CXIdxClientEntity); +opaque!(CXIdxClientFile); +opaque!(CXIndex); +opaque!(CXIndexAction); +opaque!(CXModule); +opaque!(CXRemapping); +opaque!(CXTranslationUnit); + +// Transparent ___________________________________ + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXCodeCompleteResults { + pub Results: *mut CXCompletionResult, + pub NumResults: c_uint, +} + +default!(CXCodeCompleteResults); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXComment { + pub ASTNode: *const c_void, + pub TranslationUnit: CXTranslationUnit, +} + +default!(CXComment); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXCompletionResult { + pub CursorKind: CXCursorKind, + pub CompletionString: CXCompletionString, +} + +default!(CXCompletionResult); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXCursor { + pub kind: CXCursorKind, + pub xdata: c_int, + pub data: [*const c_void; 3], +} + +default!(CXCursor); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXCursorAndRangeVisitor { + pub context: *mut c_void, + pub visit: extern fn(*mut c_void, CXCursor, CXSourceRange) -> CXVisitorResult, +} + +default!(CXCursorAndRangeVisitor); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXFileUniqueID { + pub data: [c_ulonglong; 3], +} + +default!(CXFileUniqueID); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxAttrInfo { + pub kind: CXIdxAttrKind, + pub cursor: CXCursor, + pub loc: CXIdxLoc, +} + +default!(CXIdxAttrInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxBaseClassInfo { + pub base: *const CXIdxEntityInfo, + pub cursor: CXCursor, + pub loc: CXIdxLoc, +} + +default!(CXIdxBaseClassInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxCXXClassDeclInfo { + pub declInfo: *const CXIdxDeclInfo, + pub bases: *const *const CXIdxBaseClassInfo, + pub numBases: c_uint, +} + +default!(CXIdxCXXClassDeclInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxContainerInfo { + pub cursor: CXCursor, +} + +default!(CXIdxContainerInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxDeclInfo { + pub entityInfo: *const CXIdxEntityInfo, + pub cursor: CXCursor, + pub loc: CXIdxLoc, + pub semanticContainer: *const CXIdxContainerInfo, + pub lexicalContainer: *const CXIdxContainerInfo, + pub isRedeclaration: c_int, + pub isDefinition: c_int, + pub isContainer: c_int, + pub declAsContainer: *const CXIdxContainerInfo, + pub isImplicit: c_int, + pub attributes: *const *const CXIdxAttrInfo, + pub numAttributes: c_uint, + pub flags: c_uint, +} + +default!(CXIdxDeclInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxEntityInfo { + pub kind: CXIdxEntityKind, + pub templateKind: CXIdxEntityCXXTemplateKind, + pub lang: CXIdxEntityLanguage, + pub name: *const c_char, + pub USR: *const c_char, + pub cursor: CXCursor, + pub attributes: *const *const CXIdxAttrInfo, + pub numAttributes: c_uint, +} + +default!(CXIdxEntityInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxEntityRefInfo { + pub kind: CXIdxEntityRefKind, + pub cursor: CXCursor, + pub loc: CXIdxLoc, + pub referencedEntity: *const CXIdxEntityInfo, + pub parentEntity: *const CXIdxEntityInfo, + pub container: *const CXIdxContainerInfo, +} + +default!(CXIdxEntityRefInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxIBOutletCollectionAttrInfo { + pub attrInfo: *const CXIdxAttrInfo, + pub objcClass: *const CXIdxEntityInfo, + pub classCursor: CXCursor, + pub classLoc: CXIdxLoc, +} + +default!(CXIdxIBOutletCollectionAttrInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxImportedASTFileInfo { + pub file: CXFile, + pub module: CXModule, + pub loc: CXIdxLoc, + pub isImplicit: c_int, +} + +default!(CXIdxImportedASTFileInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxIncludedFileInfo { + pub hashLoc: CXIdxLoc, + pub filename: *const c_char, + pub file: CXFile, + pub isImport: c_int, + pub isAngled: c_int, + pub isModuleImport: c_int, +} + +default!(CXIdxIncludedFileInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxLoc { + pub ptr_data: [*mut c_void; 2], + pub int_data: c_uint, +} + +default!(CXIdxLoc); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxObjCCategoryDeclInfo { + pub containerInfo: *const CXIdxObjCContainerDeclInfo, + pub objcClass: *const CXIdxEntityInfo, + pub classCursor: CXCursor, + pub classLoc: CXIdxLoc, + pub protocols: *const CXIdxObjCProtocolRefListInfo, +} + +default!(CXIdxObjCCategoryDeclInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxObjCContainerDeclInfo { + pub declInfo: *const CXIdxDeclInfo, + pub kind: CXIdxObjCContainerKind, +} + +default!(CXIdxObjCContainerDeclInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxObjCInterfaceDeclInfo { + pub containerInfo: *const CXIdxObjCContainerDeclInfo, + pub superInfo: *const CXIdxBaseClassInfo, + pub protocols: *const CXIdxObjCProtocolRefListInfo, +} + +default!(CXIdxObjCInterfaceDeclInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxObjCPropertyDeclInfo { + pub declInfo: *const CXIdxDeclInfo, + pub getter: *const CXIdxEntityInfo, + pub setter: *const CXIdxEntityInfo, +} + +default!(CXIdxObjCPropertyDeclInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxObjCProtocolRefInfo { + pub protocol: *const CXIdxEntityInfo, + pub cursor: CXCursor, + pub loc: CXIdxLoc, +} + +default!(CXIdxObjCProtocolRefInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXIdxObjCProtocolRefListInfo { + pub protocols: *const *const CXIdxObjCProtocolRefInfo, + pub numProtocols: c_uint, +} + +default!(CXIdxObjCProtocolRefListInfo); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXPlatformAvailability { + pub Platform: CXString, + pub Introduced: CXVersion, + pub Deprecated: CXVersion, + pub Obsoleted: CXVersion, + pub Unavailable: c_int, + pub Message: CXString, +} + +default!(CXPlatformAvailability); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXSourceLocation { + pub ptr_data: [*const c_void; 2], + pub int_data: c_uint, +} + +default!(CXSourceLocation); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXSourceRange { + pub ptr_data: [*const c_void; 2], + pub begin_int_data: c_uint, + pub end_int_data: c_uint, +} + +default!(CXSourceRange); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXSourceRangeList { + pub count: c_uint, + pub ranges: *mut CXSourceRange, +} + +default!(CXSourceRangeList); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXString { + pub data: *const c_void, + pub private_flags: c_uint, +} + +default!(CXString); + +#[cfg(feature="gte_clang_3_8")] +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXStringSet { + pub Strings: *mut CXString, + pub Count: c_uint, +} + +default!(#[cfg(feature="gte_clang_3_8")] CXStringSet); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXTUResourceUsage { + pub data: *mut c_void, + pub numEntries: c_uint, + pub entries: *mut CXTUResourceUsageEntry, +} + +default!(CXTUResourceUsage); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXTUResourceUsageEntry { + pub kind: CXTUResourceUsageKind, + pub amount: c_ulong, +} + +default!(CXTUResourceUsageEntry); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXToken { + pub int_data: [c_uint; 4], + pub ptr_data: *mut c_void, +} + +default!(CXToken); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXType { + pub kind: CXTypeKind, + pub data: [*mut c_void; 2], +} + +default!(CXType); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXUnsavedFile { + pub Filename: *const c_char, + pub Contents: *const c_char, + pub Length: c_ulong, +} + +default!(CXUnsavedFile); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct CXVersion { + pub Major: c_int, + pub Minor: c_int, + pub Subminor: c_int, +} + +default!(CXVersion); + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct IndexerCallbacks { + pub abortQuery: extern fn(CXClientData, *mut c_void) -> c_int, + pub diagnostic: extern fn(CXClientData, CXDiagnosticSet, *mut c_void), + pub enteredMainFile: extern fn(CXClientData, CXFile, *mut c_void) -> CXIdxClientFile, + pub ppIncludedFile: extern fn(CXClientData, *const CXIdxIncludedFileInfo) -> CXIdxClientFile, + pub importedASTFile: extern fn(CXClientData, *const CXIdxImportedASTFileInfo) -> CXIdxClientASTFile, + pub startedTranslationUnit: extern fn(CXClientData, *mut c_void) -> CXIdxClientContainer, + pub indexDeclaration: extern fn(CXClientData, *const CXIdxDeclInfo), + pub indexEntityReference: extern fn(CXClientData, *const CXIdxEntityRefInfo), +} + +default!(IndexerCallbacks); + +//================================================ +// Functions +//================================================ + +link! { + pub fn clang_CXCursorSet_contains(set: CXCursorSet, cursor: CXCursor) -> c_uint; + pub fn clang_CXCursorSet_insert(set: CXCursorSet, cursor: CXCursor) -> c_uint; + pub fn clang_CXIndex_getGlobalOptions(index: CXIndex) -> CXGlobalOptFlags; + pub fn clang_CXIndex_setGlobalOptions(index: CXIndex, flags: CXGlobalOptFlags); + #[cfg(feature="gte_clang_3_9")] + pub fn clang_CXXConstructor_isConvertingConstructor(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_CXXConstructor_isCopyConstructor(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_CXXConstructor_isDefaultConstructor(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_CXXConstructor_isMoveConstructor(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_CXXField_isMutable(cursor: CXCursor) -> c_uint; + pub fn clang_CXXMethod_isConst(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_CXXMethod_isDefaulted(cursor: CXCursor) -> c_uint; + pub fn clang_CXXMethod_isPureVirtual(cursor: CXCursor) -> c_uint; + pub fn clang_CXXMethod_isStatic(cursor: CXCursor) -> c_uint; + pub fn clang_CXXMethod_isVirtual(cursor: CXCursor) -> c_uint; + pub fn clang_CompilationDatabase_dispose(database: CXCompilationDatabase); + pub fn clang_CompilationDatabase_fromDirectory(directory: *const c_char, error: *mut CXCompilationDatabase_Error) -> CXCompilationDatabase; + pub fn clang_CompilationDatabase_getAllCompileCommands(database: CXCompilationDatabase) -> CXCompileCommands; + pub fn clang_CompilationDatabase_getCompileCommands(database: CXCompilationDatabase, filename: *const c_char) -> CXCompileCommands; + pub fn clang_CompileCommand_getArg(command: CXCompileCommand, index: c_uint) -> CXString; + pub fn clang_CompileCommand_getDirectory(command: CXCompileCommand) -> CXString; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_CompileCommand_getFilename(command: CXCompileCommand) -> CXString; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_CompileCommand_getMappedSourceContent(command: CXCompileCommand, index: c_uint) -> CXString; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_CompileCommand_getMappedSourcePath(command: CXCompileCommand, index: c_uint) -> CXString; + pub fn clang_CompileCommand_getNumArgs(command: CXCompileCommand) -> c_uint; + pub fn clang_CompileCommands_dispose(command: CXCompileCommands); + pub fn clang_CompileCommands_getCommand(command: CXCompileCommands, index: c_uint) -> CXCompileCommand; + pub fn clang_CompileCommands_getSize(command: CXCompileCommands) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Cursor_Evaluate(cursor: CXCursor) -> CXEvalResult; + pub fn clang_Cursor_getArgument(cursor: CXCursor, index: c_uint) -> CXCursor; + pub fn clang_Cursor_getBriefCommentText(cursor: CXCursor) -> CXString; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_Cursor_getCXXManglings(cursor: CXCursor) -> *mut CXStringSet; + pub fn clang_Cursor_getCommentRange(cursor: CXCursor) -> CXSourceRange; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getMangling(cursor: CXCursor) -> CXString; + pub fn clang_Cursor_getModule(cursor: CXCursor) -> CXModule; + pub fn clang_Cursor_getNumArguments(cursor: CXCursor) -> c_int; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getNumTemplateArguments(cursor: CXCursor) -> c_int; + pub fn clang_Cursor_getObjCDeclQualifiers(cursor: CXCursor) -> CXObjCDeclQualifierKind; + pub fn clang_Cursor_getObjCPropertyAttributes(cursor: CXCursor, reserved: c_uint) -> CXObjCPropertyAttrKind; + pub fn clang_Cursor_getObjCSelectorIndex(cursor: CXCursor) -> c_int; + #[cfg(feature="gte_clang_3_7")] + pub fn clang_Cursor_getOffsetOfField(cursor: CXCursor) -> c_longlong; + pub fn clang_Cursor_getRawCommentText(cursor: CXCursor) -> CXString; + pub fn clang_Cursor_getReceiverType(cursor: CXCursor) -> CXType; + pub fn clang_Cursor_getSpellingNameRange(cursor: CXCursor, index: c_uint, reserved: c_uint) -> CXSourceRange; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getStorageClass(cursor: CXCursor) -> CX_StorageClass; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getTemplateArgumentKind(cursor: CXCursor, index: c_uint) -> CXTemplateArgumentKind; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getTemplateArgumentType(cursor: CXCursor, index: c_uint) -> CXType; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getTemplateArgumentUnsignedValue(cursor: CXCursor, index: c_uint) -> c_ulonglong; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_Cursor_getTemplateArgumentValue(cursor: CXCursor, index: c_uint) -> c_longlong; + pub fn clang_Cursor_getTranslationUnit(cursor: CXCursor) -> CXTranslationUnit; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Cursor_hasAttrs(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_7")] + pub fn clang_Cursor_isAnonymous(cursor: CXCursor) -> c_uint; + pub fn clang_Cursor_isBitField(cursor: CXCursor) -> c_uint; + pub fn clang_Cursor_isDynamicCall(cursor: CXCursor) -> c_int; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Cursor_isFunctionInlined(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Cursor_isMacroBuiltin(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Cursor_isMacroFunctionLike(cursor: CXCursor) -> c_uint; + pub fn clang_Cursor_isNull(cursor: CXCursor) -> c_int; + pub fn clang_Cursor_isObjCOptional(cursor: CXCursor) -> c_uint; + pub fn clang_Cursor_isVariadic(cursor: CXCursor) -> c_uint; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_EvalResult_dispose(result: CXEvalResult); + #[cfg(feature="gte_clang_3_9")] + pub fn clang_EvalResult_getAsDouble(result: CXEvalResult) -> libc::c_double; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_EvalResult_getAsInt(result: CXEvalResult) -> c_int; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_EvalResult_getAsStr(result: CXEvalResult) -> *const c_char; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_EvalResult_getKind(result: CXEvalResult) -> CXEvalResultKind; + #[cfg(feature="gte_clang_3_6")] + pub fn clang_File_isEqual(left: CXFile, right: CXFile) -> c_int; + pub fn clang_IndexAction_create(index: CXIndex) -> CXIndexAction; + pub fn clang_IndexAction_dispose(index: CXIndexAction); + pub fn clang_Location_isFromMainFile(location: CXSourceLocation) -> c_int; + pub fn clang_Location_isInSystemHeader(location: CXSourceLocation) -> c_int; + pub fn clang_Module_getASTFile(module: CXModule) -> CXFile; + pub fn clang_Module_getFullName(module: CXModule) -> CXString; + pub fn clang_Module_getName(module: CXModule) -> CXString; + pub fn clang_Module_getNumTopLevelHeaders(tu: CXTranslationUnit, module: CXModule) -> c_uint; + pub fn clang_Module_getParent(module: CXModule) -> CXModule; + pub fn clang_Module_getTopLevelHeader(tu: CXTranslationUnit, module: CXModule, index: c_uint) -> CXFile; + pub fn clang_Module_isSystem(module: CXModule) -> c_int; + pub fn clang_Range_isNull(range: CXSourceRange) -> c_int; + pub fn clang_Type_getAlignOf(type_: CXType) -> c_longlong; + pub fn clang_Type_getCXXRefQualifier(type_: CXType) -> CXRefQualifierKind; + pub fn clang_Type_getClassType(type_: CXType) -> CXType; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Type_getNamedType(type_: CXType) -> CXType; + pub fn clang_Type_getNumTemplateArguments(type_: CXType) -> c_int; + #[cfg(feature="gte_clang_3_9")] + pub fn clang_Type_getObjCEncoding(type_: CXType) -> CXString; + pub fn clang_Type_getOffsetOf(type_: CXType, field: *const c_char) -> c_longlong; + pub fn clang_Type_getSizeOf(type_: CXType) -> c_longlong; + pub fn clang_Type_getTemplateArgumentAsType(type_: CXType, index: c_uint) -> CXType; + #[cfg(feature="gte_clang_3_7")] + pub fn clang_Type_visitFields(type_: CXType, visitor: CXFieldVisitor, data: CXClientData) -> CXVisitorResult; + pub fn clang_annotateTokens(tu: CXTranslationUnit, tokens: *mut CXToken, n_tokens: c_uint, cursors: *mut CXCursor); + pub fn clang_codeCompleteAt(tu: CXTranslationUnit, file: *const c_char, line: c_uint, column: c_uint, unsaved: *mut CXUnsavedFile, n_unsaved: c_uint, flags: CXCodeComplete_Flags) -> *mut CXCodeCompleteResults; + pub fn clang_codeCompleteGetContainerKind(results: *mut CXCodeCompleteResults, incomplete: *mut c_uint) -> CXCursorKind; + pub fn clang_codeCompleteGetContainerUSR(results: *mut CXCodeCompleteResults) -> CXString; + pub fn clang_codeCompleteGetContexts(results: *mut CXCodeCompleteResults) -> c_ulonglong; + pub fn clang_codeCompleteGetDiagnostic(results: *mut CXCodeCompleteResults, index: c_uint) -> CXDiagnostic; + pub fn clang_codeCompleteGetNumDiagnostics(results: *mut CXCodeCompleteResults) -> c_uint; + pub fn clang_codeCompleteGetObjCSelector(results: *mut CXCodeCompleteResults) -> CXString; + pub fn clang_constructUSR_ObjCCategory(class: *const c_char, category: *const c_char) -> CXString; + pub fn clang_constructUSR_ObjCClass(class: *const c_char) -> CXString; + pub fn clang_constructUSR_ObjCIvar(name: *const c_char, usr: CXString) -> CXString; + pub fn clang_constructUSR_ObjCMethod(name: *const c_char, instance: c_uint, usr: CXString) -> CXString; + pub fn clang_constructUSR_ObjCProperty(property: *const c_char, usr: CXString) -> CXString; + pub fn clang_constructUSR_ObjCProtocol(protocol: *const c_char) -> CXString; + pub fn clang_createCXCursorSet() -> CXCursorSet; + pub fn clang_createIndex(exclude: c_int, display: c_int) -> CXIndex; + pub fn clang_createTranslationUnit(index: CXIndex, file: *const c_char) -> CXTranslationUnit; + pub fn clang_createTranslationUnit2(index: CXIndex, file: *const c_char, tu: *mut CXTranslationUnit) -> CXErrorCode; + pub fn clang_createTranslationUnitFromSourceFile(index: CXIndex, file: *const c_char, n_arguments: c_int, arguments: *const *const c_char, n_unsaved: c_uint, unsaved: *mut CXUnsavedFile) -> CXTranslationUnit; + pub fn clang_defaultCodeCompleteOptions() -> CXCodeComplete_Flags; + pub fn clang_defaultDiagnosticDisplayOptions() -> CXDiagnosticDisplayOptions; + pub fn clang_defaultEditingTranslationUnitOptions() -> CXTranslationUnit_Flags; + pub fn clang_defaultReparseOptions(tu: CXTranslationUnit) -> CXReparse_Flags; + pub fn clang_defaultSaveOptions(tu: CXTranslationUnit) -> CXSaveTranslationUnit_Flags; + pub fn clang_disposeCXCursorSet(set: CXCursorSet); + pub fn clang_disposeCXPlatformAvailability(availability: *mut CXPlatformAvailability); + pub fn clang_disposeCXTUResourceUsage(usage: CXTUResourceUsage); + pub fn clang_disposeCodeCompleteResults(results: *mut CXCodeCompleteResults); + pub fn clang_disposeDiagnostic(diagnostic: CXDiagnostic); + pub fn clang_disposeDiagnosticSet(diagnostic: CXDiagnosticSet); + pub fn clang_disposeIndex(index: CXIndex); + pub fn clang_disposeOverriddenCursors(cursors: *mut CXCursor); + pub fn clang_disposeSourceRangeList(list: *mut CXSourceRangeList); + pub fn clang_disposeString(string: CXString); + #[cfg(feature="gte_clang_3_8")] + pub fn clang_disposeStringSet(set: *mut CXStringSet); + pub fn clang_disposeTokens(tu: CXTranslationUnit, tokens: *mut CXToken, n_tokens: c_uint); + pub fn clang_disposeTranslationUnit(tu: CXTranslationUnit); + pub fn clang_enableStackTraces(); + pub fn clang_equalCursors(left: CXCursor, right: CXCursor) -> c_uint; + pub fn clang_equalLocations(left: CXSourceLocation, right: CXSourceLocation) -> c_uint; + pub fn clang_equalRanges(left: CXSourceRange, right: CXSourceRange) -> c_uint; + pub fn clang_equalTypes(left: CXType, right: CXType) -> c_uint; + pub fn clang_executeOnThread(function: extern fn(*mut c_void), data: *mut c_void, stack: c_uint); + pub fn clang_findIncludesInFile(tu: CXTranslationUnit, file: CXFile, cursor: CXCursorAndRangeVisitor) -> CXResult; + pub fn clang_findReferencesInFile(cursor: CXCursor, file: CXFile, visitor: CXCursorAndRangeVisitor) -> CXResult; + pub fn clang_formatDiagnostic(diagnostic: CXDiagnostic, flags: CXDiagnosticDisplayOptions) -> CXString; + #[cfg(feature="gte_clang_3_7")] + pub fn clang_free(buffer: *mut c_void); + pub fn clang_getArgType(type_: CXType, index: c_uint) -> CXType; + pub fn clang_getArrayElementType(type_: CXType) -> CXType; + pub fn clang_getArraySize(type_: CXType) -> c_longlong; + pub fn clang_getCString(string: CXString) -> *const c_char; + pub fn clang_getCXTUResourceUsage(tu: CXTranslationUnit) -> CXTUResourceUsage; + pub fn clang_getCXXAccessSpecifier(cursor: CXCursor) -> CX_CXXAccessSpecifier; + pub fn clang_getCanonicalCursor(cursor: CXCursor) -> CXCursor; + pub fn clang_getCanonicalType(type_: CXType) -> CXType; + pub fn clang_getChildDiagnostics(diagnostic: CXDiagnostic) -> CXDiagnosticSet; + pub fn clang_getClangVersion() -> CXString; + pub fn clang_getCompletionAnnotation(string: CXCompletionString, index: c_uint) -> CXString; + pub fn clang_getCompletionAvailability(string: CXCompletionString) -> CXAvailabilityKind; + pub fn clang_getCompletionBriefComment(string: CXCompletionString) -> CXString; + pub fn clang_getCompletionChunkCompletionString(string: CXCompletionString, index: c_uint) -> CXCompletionString; + pub fn clang_getCompletionChunkKind(string: CXCompletionString, index: c_uint) -> CXCompletionChunkKind; + pub fn clang_getCompletionChunkText(string: CXCompletionString, index: c_uint) -> CXString; + pub fn clang_getCompletionNumAnnotations(string: CXCompletionString) -> c_uint; + pub fn clang_getCompletionParent(string: CXCompletionString, kind: *mut CXCursorKind) -> CXString; + pub fn clang_getCompletionPriority(string: CXCompletionString) -> c_uint; + pub fn clang_getCursor(tu: CXTranslationUnit, location: CXSourceLocation) -> CXCursor; + pub fn clang_getCursorAvailability(cursor: CXCursor) -> CXAvailabilityKind; + pub fn clang_getCursorCompletionString(cursor: CXCursor) -> CXCompletionString; + pub fn clang_getCursorDefinition(cursor: CXCursor) -> CXCursor; + pub fn clang_getCursorDisplayName(cursor: CXCursor) -> CXString; + pub fn clang_getCursorExtent(cursor: CXCursor) -> CXSourceRange; + pub fn clang_getCursorKind(cursor: CXCursor) -> CXCursorKind; + pub fn clang_getCursorKindSpelling(kind: CXCursorKind) -> CXString; + pub fn clang_getCursorLanguage(cursor: CXCursor) -> CXLanguageKind; + pub fn clang_getCursorLexicalParent(cursor: CXCursor) -> CXCursor; + pub fn clang_getCursorLinkage(cursor: CXCursor) -> CXLinkageKind; + pub fn clang_getCursorLocation(cursor: CXCursor) -> CXSourceLocation; + pub fn clang_getCursorPlatformAvailability(cursor: CXCursor, deprecated: *mut c_int, deprecated_message: *mut CXString, unavailable: *mut c_int, unavailable_message: *mut CXString, availability: *mut CXPlatformAvailability, n_availability: c_int) -> c_int; + pub fn clang_getCursorReferenceNameRange(cursor: CXCursor, flags: CXNameRefFlags, index: c_uint) -> CXSourceRange; + pub fn clang_getCursorReferenced(cursor: CXCursor) -> CXCursor; + pub fn clang_getCursorResultType(cursor: CXCursor) -> CXType; + pub fn clang_getCursorSemanticParent(cursor: CXCursor) -> CXCursor; + pub fn clang_getCursorSpelling(cursor: CXCursor) -> CXString; + pub fn clang_getCursorType(cursor: CXCursor) -> CXType; + pub fn clang_getCursorUSR(cursor: CXCursor) -> CXString; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_getCursorVisibility(cursor: CXCursor) -> CXVisibilityKind; + pub fn clang_getDeclObjCTypeEncoding(cursor: CXCursor) -> CXString; + pub fn clang_getDefinitionSpellingAndExtent(cursor: CXCursor, start: *mut *const c_char, end: *mut *const c_char, start_line: *mut c_uint, start_column: *mut c_uint, end_line: *mut c_uint, end_column: *mut c_uint); + pub fn clang_getDiagnostic(tu: CXTranslationUnit, index: c_uint) -> CXDiagnostic; + pub fn clang_getDiagnosticCategory(diagnostic: CXDiagnostic) -> c_uint; + pub fn clang_getDiagnosticCategoryName(category: c_uint) -> CXString; + pub fn clang_getDiagnosticCategoryText(diagnostic: CXDiagnostic) -> CXString; + pub fn clang_getDiagnosticFixIt(diagnostic: CXDiagnostic, index: c_uint, range: *mut CXSourceRange) -> CXString; + pub fn clang_getDiagnosticInSet(diagnostic: CXDiagnosticSet, index: c_uint) -> CXDiagnostic; + pub fn clang_getDiagnosticLocation(diagnostic: CXDiagnostic) -> CXSourceLocation; + pub fn clang_getDiagnosticNumFixIts(diagnostic: CXDiagnostic) -> c_uint; + pub fn clang_getDiagnosticNumRanges(diagnostic: CXDiagnostic) -> c_uint; + pub fn clang_getDiagnosticOption(diagnostic: CXDiagnostic, option: *mut CXString) -> CXString; + pub fn clang_getDiagnosticRange(diagnostic: CXDiagnostic, index: c_uint) -> CXSourceRange; + pub fn clang_getDiagnosticSetFromTU(tu: CXTranslationUnit) -> CXDiagnosticSet; + pub fn clang_getDiagnosticSeverity(diagnostic: CXDiagnostic) -> CXDiagnosticSeverity; + pub fn clang_getDiagnosticSpelling(diagnostic: CXDiagnostic) -> CXString; + pub fn clang_getElementType(type_: CXType) -> CXType; + pub fn clang_getEnumConstantDeclUnsignedValue(cursor: CXCursor) -> c_ulonglong; + pub fn clang_getEnumConstantDeclValue(cursor: CXCursor) -> c_longlong; + pub fn clang_getEnumDeclIntegerType(cursor: CXCursor) -> CXType; + pub fn clang_getExpansionLocation(location: CXSourceLocation, file: *mut CXFile, line: *mut c_uint, column: *mut c_uint, offset: *mut c_uint); + pub fn clang_getFieldDeclBitWidth(cursor: CXCursor) -> c_int; + pub fn clang_getFile(tu: CXTranslationUnit, file: *const c_char) -> CXFile; + pub fn clang_getFileLocation(location: CXSourceLocation, file: *mut CXFile, line: *mut c_uint, column: *mut c_uint, offset: *mut c_uint); + pub fn clang_getFileName(file: CXFile) -> CXString; + pub fn clang_getFileTime(file: CXFile) -> time_t; + pub fn clang_getFileUniqueID(file: CXFile, id: *mut CXFileUniqueID) -> c_int; + pub fn clang_getFunctionTypeCallingConv(type_: CXType) -> CXCallingConv; + pub fn clang_getIBOutletCollectionType(cursor: CXCursor) -> CXType; + pub fn clang_getIncludedFile(cursor: CXCursor) -> CXFile; + pub fn clang_getInclusions(tu: CXTranslationUnit, visitor: CXInclusionVisitor, data: CXClientData); + pub fn clang_getInstantiationLocation(location: CXSourceLocation, file: *mut CXFile, line: *mut c_uint, column: *mut c_uint, offset: *mut c_uint); + pub fn clang_getLocation(tu: CXTranslationUnit, file: CXFile, line: c_uint, column: c_uint) -> CXSourceLocation; + pub fn clang_getLocationForOffset(tu: CXTranslationUnit, file: CXFile, offset: c_uint) -> CXSourceLocation; + pub fn clang_getModuleForFile(tu: CXTranslationUnit, file: CXFile) -> CXModule; + pub fn clang_getNullCursor() -> CXCursor; + pub fn clang_getNullLocation() -> CXSourceLocation; + pub fn clang_getNullRange() -> CXSourceRange; + pub fn clang_getNumArgTypes(type_: CXType) -> c_int; + pub fn clang_getNumCompletionChunks(string: CXCompletionString) -> c_uint; + pub fn clang_getNumDiagnostics(tu: CXTranslationUnit) -> c_uint; + pub fn clang_getNumDiagnosticsInSet(diagnostic: CXDiagnosticSet) -> c_uint; + pub fn clang_getNumElements(type_: CXType) -> c_longlong; + pub fn clang_getNumOverloadedDecls(cursor: CXCursor) -> c_uint; + pub fn clang_getOverloadedDecl(cursor: CXCursor, index: c_uint) -> CXCursor; + pub fn clang_getOverriddenCursors(cursor: CXCursor, cursors: *mut *mut CXCursor, n_cursors: *mut c_uint); + pub fn clang_getPointeeType(type_: CXType) -> CXType; + pub fn clang_getPresumedLocation(location: CXSourceLocation, file: *mut CXString, line: *mut c_uint, column: *mut c_uint); + pub fn clang_getRange(start: CXSourceLocation, end: CXSourceLocation) -> CXSourceRange; + pub fn clang_getRangeEnd(range: CXSourceRange) -> CXSourceLocation; + pub fn clang_getRangeStart(range: CXSourceRange) -> CXSourceLocation; + pub fn clang_getRemappings(file: *const c_char) -> CXRemapping; + pub fn clang_getRemappingsFromFileList(files: *mut *const c_char, n_files: c_uint) -> CXRemapping; + pub fn clang_getResultType(type_: CXType) -> CXType; + pub fn clang_getSkippedRanges(tu: CXTranslationUnit, file: CXFile) -> *mut CXSourceRangeList; + pub fn clang_getSpecializedCursorTemplate(cursor: CXCursor) -> CXCursor; + pub fn clang_getSpellingLocation(location: CXSourceLocation, file: *mut CXFile, line: *mut c_uint, column: *mut c_uint, offset: *mut c_uint); + pub fn clang_getTUResourceUsageName(kind: CXTUResourceUsageKind) -> *const c_char; + pub fn clang_getTemplateCursorKind(cursor: CXCursor) -> CXCursorKind; + pub fn clang_getTokenExtent(tu: CXTranslationUnit, token: CXToken) -> CXSourceRange; + pub fn clang_getTokenKind(token: CXToken) -> CXTokenKind; + pub fn clang_getTokenLocation(tu: CXTranslationUnit, token: CXToken) -> CXSourceLocation; + pub fn clang_getTokenSpelling(tu: CXTranslationUnit, token: CXToken) -> CXString; + pub fn clang_getTranslationUnitCursor(tu: CXTranslationUnit) -> CXCursor; + pub fn clang_getTranslationUnitSpelling(tu: CXTranslationUnit) -> CXString; + pub fn clang_getTypeDeclaration(type_: CXType) -> CXCursor; + pub fn clang_getTypeKindSpelling(type_: CXTypeKind) -> CXString; + pub fn clang_getTypeSpelling(type_: CXType) -> CXString; + pub fn clang_getTypedefDeclUnderlyingType(cursor: CXCursor) -> CXType; + pub fn clang_hashCursor(cursor: CXCursor) -> c_uint; + pub fn clang_indexLoc_getCXSourceLocation(location: CXIdxLoc) -> CXSourceLocation; + pub fn clang_indexLoc_getFileLocation(location: CXIdxLoc, index_file: *mut CXIdxClientFile, file: *mut CXFile, line: *mut c_uint, column: *mut c_uint, offset: *mut c_uint); + pub fn clang_indexSourceFile(index: CXIndexAction, data: CXClientData, callbacks: *mut IndexerCallbacks, n_callbacks: c_uint, index_flags: CXIndexOptFlags, file: *const c_char, arguments: *const *const c_char, n_arguments: c_int, unsaved: *mut CXUnsavedFile, n_unsaved: c_uint, tu: *mut CXTranslationUnit, tu_flags: CXTranslationUnit_Flags) -> CXErrorCode; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_indexSourceFileFullArgv(index: CXIndexAction, data: CXClientData, callbacks: *mut IndexerCallbacks, n_callbacks: c_uint, index_flags: CXIndexOptFlags, file: *const c_char, arguments: *const *const c_char, n_arguments: c_int, unsaved: *mut CXUnsavedFile, n_unsaved: c_uint, tu: *mut CXTranslationUnit, tu_flags: CXTranslationUnit_Flags) -> CXErrorCode; + pub fn clang_indexTranslationUnit(index: CXIndexAction, data: CXClientData, callbacks: *mut IndexerCallbacks, n_callbacks: c_uint, flags: CXIndexOptFlags, tu: CXTranslationUnit) -> c_int; + pub fn clang_index_getCXXClassDeclInfo(info: *const CXIdxDeclInfo) -> *const CXIdxCXXClassDeclInfo; + pub fn clang_index_getClientContainer(info: *const CXIdxContainerInfo) -> CXIdxClientContainer; + pub fn clang_index_getClientEntity(info: *const CXIdxEntityInfo) -> CXIdxClientEntity; + pub fn clang_index_getIBOutletCollectionAttrInfo(info: *const CXIdxAttrInfo) -> *const CXIdxIBOutletCollectionAttrInfo; + pub fn clang_index_getObjCCategoryDeclInfo(info: *const CXIdxDeclInfo) -> *const CXIdxObjCCategoryDeclInfo; + pub fn clang_index_getObjCContainerDeclInfo(info: *const CXIdxDeclInfo) -> *const CXIdxObjCContainerDeclInfo; + pub fn clang_index_getObjCInterfaceDeclInfo(info: *const CXIdxDeclInfo) -> *const CXIdxObjCInterfaceDeclInfo; + pub fn clang_index_getObjCPropertyDeclInfo(info: *const CXIdxDeclInfo) -> *const CXIdxObjCPropertyDeclInfo; + pub fn clang_index_getObjCProtocolRefListInfo(info: *const CXIdxDeclInfo) -> *const CXIdxObjCProtocolRefListInfo; + pub fn clang_index_isEntityObjCContainerKind(info: CXIdxEntityKind) -> c_int; + pub fn clang_index_setClientContainer(info: *const CXIdxContainerInfo, container: CXIdxClientContainer); + pub fn clang_index_setClientEntity(info: *const CXIdxEntityInfo, entity: CXIdxClientEntity); + pub fn clang_isAttribute(kind: CXCursorKind) -> c_uint; + pub fn clang_isConstQualifiedType(type_: CXType) -> c_uint; + pub fn clang_isCursorDefinition(cursor: CXCursor) -> c_uint; + pub fn clang_isDeclaration(kind: CXCursorKind) -> c_uint; + pub fn clang_isExpression(kind: CXCursorKind) -> c_uint; + pub fn clang_isFileMultipleIncludeGuarded(tu: CXTranslationUnit, file: CXFile) -> c_uint; + pub fn clang_isFunctionTypeVariadic(type_: CXType) -> c_uint; + pub fn clang_isInvalid(kind: CXCursorKind) -> c_uint; + pub fn clang_isPODType(type_: CXType) -> c_uint; + pub fn clang_isPreprocessing(kind: CXCursorKind) -> c_uint; + pub fn clang_isReference(kind: CXCursorKind) -> c_uint; + pub fn clang_isRestrictQualifiedType(type_: CXType) -> c_uint; + pub fn clang_isStatement(kind: CXCursorKind) -> c_uint; + pub fn clang_isTranslationUnit(kind: CXCursorKind) -> c_uint; + pub fn clang_isUnexposed(kind: CXCursorKind) -> c_uint; + pub fn clang_isVirtualBase(cursor: CXCursor) -> c_uint; + pub fn clang_isVolatileQualifiedType(type_: CXType) -> c_uint; + pub fn clang_loadDiagnostics(file: *const c_char, error: *mut CXLoadDiag_Error, message: *mut CXString) -> CXDiagnosticSet; + pub fn clang_parseTranslationUnit(index: CXIndex, file: *const c_char, arguments: *const *const c_char, n_arguments: c_int, unsaved: *mut CXUnsavedFile, n_unsaved: c_uint, flags: CXTranslationUnit_Flags) -> CXTranslationUnit; + pub fn clang_parseTranslationUnit2(index: CXIndex, file: *const c_char, arguments: *const *const c_char, n_arguments: c_int, unsaved: *mut CXUnsavedFile, n_unsaved: c_uint, flags: CXTranslationUnit_Flags, tu: *mut CXTranslationUnit) -> CXErrorCode; + #[cfg(feature="gte_clang_3_8")] + pub fn clang_parseTranslationUnit2FullArgv(index: CXIndex, file: *const c_char, arguments: *const *const c_char, n_arguments: c_int, unsaved: *mut CXUnsavedFile, n_unsaved: c_uint, flags: CXTranslationUnit_Flags, tu: *mut CXTranslationUnit) -> CXErrorCode; + pub fn clang_remap_dispose(remapping: CXRemapping); + pub fn clang_remap_getFilenames(remapping: CXRemapping, index: c_uint, original: *mut CXString, transformed: *mut CXString); + pub fn clang_remap_getNumFiles(remapping: CXRemapping) -> c_uint; + pub fn clang_reparseTranslationUnit(tu: CXTranslationUnit, n_unsaved: c_uint, unsaved: *mut CXUnsavedFile, flags: CXReparse_Flags) -> CXErrorCode; + pub fn clang_saveTranslationUnit(tu: CXTranslationUnit, file: *const c_char, options: CXSaveTranslationUnit_Flags) -> CXSaveError; + pub fn clang_sortCodeCompletionResults(results: *mut CXCompletionResult, n_results: c_uint); + pub fn clang_toggleCrashRecovery(recovery: c_uint); + pub fn clang_tokenize(tu: CXTranslationUnit, range: CXSourceRange, tokens: *mut *mut CXToken, n_tokens: *mut c_uint); + pub fn clang_visitChildren(cursor: CXCursor, visitor: CXCursorVisitor, data: CXClientData) -> c_uint; + + // Documentation + pub fn clang_BlockCommandComment_getArgText(comment: CXComment, index: c_uint) -> CXString; + pub fn clang_BlockCommandComment_getCommandName(comment: CXComment) -> CXString; + pub fn clang_BlockCommandComment_getNumArgs(comment: CXComment) -> c_uint; + pub fn clang_BlockCommandComment_getParagraph(comment: CXComment) -> CXComment; + pub fn clang_Comment_getChild(comment: CXComment, index: c_uint) -> CXComment; + pub fn clang_Comment_getKind(comment: CXComment) -> CXCommentKind; + pub fn clang_Comment_getNumChildren(comment: CXComment) -> c_uint; + pub fn clang_Comment_isWhitespace(comment: CXComment) -> c_uint; + pub fn clang_Cursor_getParsedComment(C: CXCursor) -> CXComment; + pub fn clang_FullComment_getAsHTML(comment: CXComment) -> CXString; + pub fn clang_FullComment_getAsXML(comment: CXComment) -> CXString; + pub fn clang_HTMLStartTagComment_isSelfClosing(comment: CXComment) -> c_uint; + pub fn clang_HTMLStartTag_getAttrName(comment: CXComment, index: c_uint) -> CXString; + pub fn clang_HTMLStartTag_getAttrValue(comment: CXComment, index: c_uint) -> CXString; + pub fn clang_HTMLStartTag_getNumAttrs(comment: CXComment) -> c_uint; + pub fn clang_HTMLTagComment_getAsString(comment: CXComment) -> CXString; + pub fn clang_HTMLTagComment_getTagName(comment: CXComment) -> CXString; + pub fn clang_InlineCommandComment_getArgText(comment: CXComment, index: c_uint) -> CXString; + pub fn clang_InlineCommandComment_getCommandName(comment: CXComment) -> CXString; + pub fn clang_InlineCommandComment_getNumArgs(comment: CXComment) -> c_uint; + pub fn clang_InlineCommandComment_getRenderKind(comment: CXComment) -> CXCommentInlineCommandRenderKind; + pub fn clang_InlineContentComment_hasTrailingNewline(comment: CXComment) -> c_uint; + pub fn clang_ParamCommandComment_getDirection(comment: CXComment) -> CXCommentParamPassDirection; + pub fn clang_ParamCommandComment_getParamIndex(comment: CXComment) -> c_uint; + pub fn clang_ParamCommandComment_getParamName(comment: CXComment) -> CXString; + pub fn clang_ParamCommandComment_isDirectionExplicit(comment: CXComment) -> c_uint; + pub fn clang_ParamCommandComment_isParamIndexValid(comment: CXComment) -> c_uint; + pub fn clang_TParamCommandComment_getDepth(comment: CXComment) -> c_uint; + pub fn clang_TParamCommandComment_getIndex(comment: CXComment, depth: c_uint) -> c_uint; + pub fn clang_TParamCommandComment_getParamName(comment: CXComment) -> CXString; + pub fn clang_TParamCommandComment_isParamPositionValid(comment: CXComment) -> c_uint; + pub fn clang_TextComment_getText(comment: CXComment) -> CXString; + pub fn clang_VerbatimBlockLineComment_getText(comment: CXComment) -> CXString; + pub fn clang_VerbatimLineComment_getText(comment: CXComment) -> CXString; +} diff --git a/bash-5.1/vendor/clang-sys/src/link.rs b/bash-5.1/vendor/clang-sys/src/link.rs new file mode 100644 index 0000000..7155182 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/src/link.rs @@ -0,0 +1,184 @@ +// Copyright 2016 Kyle Mayes +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//================================================ +// Macros +//================================================ + +// link! _________________________________________ + +#[cfg(feature="runtime")] +macro_rules! link { + (@LOAD: #[cfg($cfg:meta)] fn $name:ident($($pname:ident: $pty:ty), *) $(-> $ret:ty)*) => ( + #[cfg($cfg)] + pub fn $name(library: &mut super::SharedLibrary) { + let symbol = unsafe { library.library.get(stringify!($name).as_bytes()) }.ok(); + library.functions.$name = symbol.map(|s| *s); + } + + #[cfg(not($cfg))] + pub fn $name(_: &mut super::SharedLibrary) {} + ); + + (@LOAD: fn $name:ident($($pname:ident: $pty:ty), *) $(-> $ret:ty)*) => ( + link!(@LOAD: #[cfg(feature="runtime")] fn $name($($pname: $pty), *) $(-> $ret)*); + ); + + ($($(#[cfg($cfg:meta)])* pub fn $name:ident($($pname:ident: $pty:ty), *) $(-> $ret:ty)*;)+) => ( + use std::cell::{RefCell}; + use std::sync::{Arc}; + + /// The set of functions loaded dynamically. + #[derive(Debug)] + pub struct Functions { + $($(#[cfg($cfg)])* pub $name: Option $ret)*>,)+ + } + + impl Default for Functions { + fn default() -> Functions { + unsafe { std::mem::zeroed() } + } + } + + /// A dynamically loaded instance of the `libclang` library. + #[derive(Debug)] + pub struct SharedLibrary { + library: libloading::Library, + pub functions: Functions, + } + + impl SharedLibrary { + //- Constructors ----------------------------- + + fn new(library: libloading::Library) -> SharedLibrary { + SharedLibrary { library: library, functions: Functions::default() } + } + } + + thread_local!(static LIBRARY: RefCell>> = RefCell::new(None)); + + /// Returns whether a `libclang` shared library is loaded on this thread. + pub fn is_loaded() -> bool { + LIBRARY.with(|l| l.borrow().is_some()) + } + + fn with_library(f: F) -> Option where F: FnOnce(&SharedLibrary) -> T { + LIBRARY.with(|l| { + match l.borrow().as_ref() { + Some(library) => Some(f(&library)), + _ => None, + } + }) + } + + $( + $(#[cfg($cfg)])* + pub unsafe fn $name($($pname: $pty), *) $(-> $ret)* { + let f = with_library(|l| { + match l.functions.$name { + Some(f) => f, + _ => panic!(concat!("function not loaded: ", stringify!($name))), + } + }).expect("a `libclang` shared library is not loaded on this thread"); + f($($pname), *) + } + + $(#[cfg($cfg)])* + pub mod $name { + pub fn is_loaded() -> bool { + super::with_library(|l| l.functions.$name.is_some()).unwrap_or(false) + } + } + )+ + + mod load { + $(link!(@LOAD: $(#[cfg($cfg)])* fn $name($($pname: $pty), *) $(-> $ret)*);)+ + } + + /// Loads a `libclang` shared library and returns the library instance. + /// + /// This function does not attempt to load any functions from the shared library. The caller + /// is responsible for loading the functions they require. + /// + /// # Failures + /// + /// * a `libclang` shared library could not be found + /// * the `libclang` shared library could not be opened + pub fn load_manually() -> Result { + #[path="../build.rs"] + mod build; + + let file = try!(build::find_shared_library()); + let library = libloading::Library::new(&file).map_err(|_| { + format!("the `libclang` shared library could not be opened: {}", file.display()) + }); + let mut library = SharedLibrary::new(try!(library)); + $(load::$name(&mut library);)+ + Ok(library) + } + + /// Loads a `libclang` shared library for use in the current thread. + /// + /// This functions attempts to load all the functions in the shared library. Whether a + /// function has been loaded can be tested by calling the `is_loaded` function on the + /// module with the same name as the function (e.g., `clang_createIndex::is_loaded()` for + /// the `clang_createIndex` function). + /// + /// # Failures + /// + /// * a `libclang` shared library could not be found + /// * the `libclang` shared library could not be opened + #[allow(dead_code)] + pub fn load() -> Result<(), String> { + let library = Arc::new(try!(load_manually())); + LIBRARY.with(|l| *l.borrow_mut() = Some(library)); + Ok(()) + } + + /// Unloads the `libclang` shared library in use in the current thread. + /// + /// # Failures + /// + /// * a `libclang` shared library is not in use in the current thread + pub fn unload() -> Result<(), String> { + let library = set_library(None); + if library.is_some() { + Ok(()) + } else { + Err("a `libclang` shared library is not in use in the current thread".into()) + } + } + + /// Returns the library instance stored in TLS. + /// + /// This functions allows for sharing library instances between threads. + pub fn get_library() -> Option> { + LIBRARY.with(|l| l.borrow_mut().clone()) + } + + /// Sets the library instance stored in TLS and returns the previous library. + /// + /// This functions allows for sharing library instances between threads. + pub fn set_library(library: Option>) -> Option> { + LIBRARY.with(|l| mem::replace(&mut *l.borrow_mut(), library)) + } + ) +} + +#[cfg(not(feature="runtime"))] +macro_rules! link { + ($($(#[cfg($cfg:meta)])* pub fn $name:ident($($pname:ident: $pty:ty), *) $(-> $ret:ty)*;)+) => ( + extern { $($(#[cfg($cfg)])* pub fn $name($($pname: $pty), *) $(-> $ret)*;)+ } + ) +} diff --git a/bash-5.1/vendor/clang-sys/src/support.rs b/bash-5.1/vendor/clang-sys/src/support.rs new file mode 100644 index 0000000..83fd937 --- /dev/null +++ b/bash-5.1/vendor/clang-sys/src/support.rs @@ -0,0 +1,171 @@ +// Copyright 2016 Kyle Mayes +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Provides helper functionality. + +use std::env; +use std::process::{Command}; +use std::path::{Path, PathBuf}; + +use glob; + +use libc::{c_int}; + +use super::{CXVersion}; + +//================================================ +// Macros +//================================================ + +// try_opt! ______________________________________ + +macro_rules! try_opt { + ($option:expr) => ({ + match $option { + Some(some) => some, + None => return None, + } + }); +} + +//================================================ +// Structs +//================================================ + +/// A `clang` executable. +#[derive(Clone, Debug)] +pub struct Clang { + /// The path to this `clang` executable. + pub path: PathBuf, + /// The version of this `clang` executable if it could be parsed. + pub version: Option, + /// The directories searched by this `clang` executable for C headers. + pub c_search_paths: Vec, + /// The directories searched by this `clang` executable for C++ headers. + pub cpp_search_paths: Vec, +} + +impl Clang { + //- Constructors ----------------------------- + + fn new(path: PathBuf) -> Clang { + let version = parse_version(&path); + let c_search_paths = parse_search_paths(&path, "c"); + let cpp_search_paths = parse_search_paths(&path, "c++"); + Clang { + path: path, + version: version, + c_search_paths: c_search_paths, + cpp_search_paths: cpp_search_paths, + } + } + + /// Returns a `clang` executable if one can be found. + /// + /// If the `CLANG_PATH` environment variable is set, that is the instance of `clang` used. + /// Otherwise, a series of directories are searched. First, If a path is supplied, that is the + /// first directory searched. Then, the directory returned by `llvm-config --bindir` is + /// searched. On OS X systems, `xcodebuild -find clang` will next be queried. Last, the + /// directories in the system's `PATH` are searched. + pub fn find(path: Option<&Path>) -> Option { + if let Ok(path) = env::var("CLANG_PATH") { + return Some(Clang::new(path.into())); + } + + let mut paths = vec![]; + if let Some(path) = path { + paths.push(path.into()); + } + if let Ok(path) = run_llvm_config(&["--bindir"]) { + paths.push(path.into()); + } + if cfg!(target_os="macos") { + if let Ok((path, _)) = run("xcodebuild", &["-find", "clang"]) { + paths.push(path.into()); + } + } + paths.extend(env::split_paths(&env::var("PATH").unwrap())); + + let default = format!("clang{}", env::consts::EXE_SUFFIX); + let versioned = format!("clang-[0-9]*{}", env::consts::EXE_SUFFIX); + let patterns = &[&default[..], &versioned[..]]; + for path in paths { + if let Some(path) = find(&path, patterns) { + return Some(Clang::new(path)); + } + } + None + } +} + +//================================================ +// Functions +//================================================ + +/// Returns the first match to the supplied glob patterns in the supplied directory if there are any +/// matches. +fn find(directory: &Path, patterns: &[&str]) -> Option { + for pattern in patterns { + let pattern = directory.join(pattern).to_string_lossy().into_owned(); + if let Some(path) = try_opt!(glob::glob(&pattern).ok()).filter_map(|p| p.ok()).next() { + return Some(path); + } + } + None +} + +/// Attempts to run an executable, returning the `stdout` and `stderr` output if successful. +fn run(executable: &str, arguments: &[&str]) -> Result<(String, String), String> { + Command::new(executable).args(arguments).output().map(|o| { + let stdout = String::from_utf8_lossy(&o.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&o.stderr).into_owned(); + (stdout, stderr) + }).map_err(|_| format!("could not run executable: `{}`", executable)) +} + +/// Runs `clang`, returning the `stdout` and `stderr` output. +fn run_clang(path: &Path, arguments: &[&str]) -> (String, String) { + run(&path.to_string_lossy().into_owned(), arguments).unwrap() +} + +/// Runs `llvm-config`, returning the `stdout` output if successful. +fn run_llvm_config(arguments: &[&str]) -> Result { + run(&env::var("LLVM_CONFIG_PATH").unwrap_or("llvm-config".into()), arguments).map(|(o, _)| o) +} + +/// Parses a version number if possible, ignoring trailing non-digit characters. +fn parse_version_number(number: &str) -> Option { + number.chars().take_while(|c| c.is_digit(10)).collect::().parse().ok() +} + +/// Parses the version from the output of a `clang` executable if possible. +fn parse_version(path: &Path) -> Option { + let output = run_clang(path, &["--version"]).0; + let start = try_opt!(output.find("version ")) + 8; + let mut numbers = try_opt!(output[start..].split_whitespace().nth(0)).split('.'); + let major = try_opt!(numbers.next().and_then(parse_version_number)); + let minor = try_opt!(numbers.next().and_then(parse_version_number)); + let subminor = numbers.next().and_then(parse_version_number).unwrap_or(0); + Some(CXVersion { Major: major, Minor: minor, Subminor: subminor }) +} + +/// Parses the search paths from the output of a `clang` executable. +fn parse_search_paths(path: &Path, language: &str) -> Vec { + let output = run_clang(path, &["-E", "-x", language, "-", "-v"]).1; + let include_start = "#include <...> search starts here:"; + let start = output.find(include_start).expect(include_start) + include_start.len(); + let end = output.find("End of search list.").expect("End of search list"); + let paths = output[start..end].replace("(framework directory)", ""); + paths.lines().filter(|l| !l.is_empty()).map(|l| Path::new(l.trim()).into()).collect() +} diff --git a/bash-5.1/vendor/clang-sys/tests/header.h b/bash-5.1/vendor/clang-sys/tests/header.h new file mode 100644 index 0000000..3767c8e --- /dev/null +++ b/bash-5.1/vendor/clang-sys/tests/header.h @@ -0,0 +1,6 @@ +#ifndef HEADER_H_ +#define HEADER_H_ + +int add(int a, int b); + +#endif diff --git a/bash-5.1/vendor/clang-sys/tests/lib.rs b/bash-5.1/vendor/clang-sys/tests/lib.rs new file mode 100644 index 0000000..6e2e73c --- /dev/null +++ b/bash-5.1/vendor/clang-sys/tests/lib.rs @@ -0,0 +1,46 @@ +extern crate clang_sys; +extern crate libc; + +use std::ptr; + +use clang_sys::*; + +use libc::{c_char}; + +fn parse() { + unsafe { + let index = clang_createIndex(0, 0); + assert!(!index.is_null()); + + let tu = clang_parseTranslationUnit( + index, + "tests/header.h\0".as_ptr() as *const c_char, + ptr::null_mut(), + 0, + ptr::null_mut(), + 0, + CXTranslationUnit_Flags::empty(), + ); + assert!(!tu.is_null()); + } +} + +#[cfg(feature="runtime")] +#[test] +fn test() { + load().unwrap(); + parse(); + unload().unwrap(); +} + +#[cfg(not(feature="runtime"))] +#[test] +fn test() { + parse(); +} + +#[test] +fn test_support() { + let clang = support::Clang::find(None).unwrap(); + println!("{:?}", clang); +} diff --git a/bash-5.1/vendor/clap/.cargo-checksum.json b/bash-5.1/vendor/clap/.cargo-checksum.json new file mode 100644 index 0000000..f70b25f --- /dev/null +++ b/bash-5.1/vendor/clap/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"623d43f94b419a5e79f7bc103d4de47f60daf7803d49e63058ba9e24f8f8c6cc","CONTRIBUTORS.md":"9b0d3eee116dda23705b732c19b777ebb2b998a6e4554027ae3f61715376b4bc","Cargo.toml":"e7d0b7019b86f3a6901416714ac94702f666c8de0bf197d717abb8a2f86e7e6a","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"6a836ddd7544962b33ae76b03e0f550ace4e4c967aee23e24ce14fc31e58e885","SPONSORS.md":"640b56e535db654d7bf14b1fe63bc837dcfde37a85f14eb4f404663fe1b72af9","clap-test.rs":"b5ca72dedfe1e71c250c42a01a52a3f5f9ea2bb14d9fe09093e73b71880f79fd","justfile":"9ee43d53fda234044fee4edd1ecdac9f19864c7f00a4ea5cb2b6a8a0287c93e3","src/app/help.rs":"037094b39990115fdac105f550c2f6eb1cbbfc8ff8f65b6ca34c65634902c3ab","src/app/meta.rs":"d15a4118e9de562cacf9d2063f1f491e3c3ce4092b4e8ea5d4d92e2631ca247b","src/app/mod.rs":"0aee709776d1be519a5587258b433ba0b54d5ebda14bb0544ce32c0505d5dcec","src/app/parser.rs":"83917c7e8f39f1e5d1807095f0856be3c3450aa88a6abb8e4d7c1d1fe9dbb2c4","src/app/settings.rs":"b29e3f90c282a27865b27674bb5b0a4def2966646f0e70b4f78e587c9649e379","src/app/usage.rs":"65f6b5d6f068a8ded0e78faf59575202bc8729a079e9806d0afeba87fa6ba9fc","src/app/validator.rs":"3124617cbaf959466241f4ba1a9837c1184a7a06325c5cbe3d613a7786febd4e","src/args/any_arg.rs":"5a34d363ce5d74e1829c4feb2a8044e0d3c31d5af2094933cf61d6579e548ecf","src/args/arg.rs":"e9ad38d43bef8d36e96ae6edb2dc6ea2258c6a7287f6479aad5a21b8ed197fd6","src/args/arg_builder/base.rs":"989952f8b827bd60db85bebb09b23de4d3e1296cc1f195e9da447b154f10cd09","src/args/arg_builder/flag.rs":"3c90fc16079b3f921c9e9b3a9607467eb5afddfdc8da53e9528987a43d883e36","src/args/arg_builder/mod.rs":"31844ad665171a2d49d551debd3d1a20e8a77dd74d02f9ff6fc22f63b019db02","src/args/arg_builder/option.rs":"d882e07dc1d6a77aae06fc5dad5502b7a4c1fc6e8124e6ab08b6ec037cb08b85","src/args/arg_builder/positional.rs":"fd6720931b9622a6d6576494dfbe67ae40416b6083d0302c1a0d9e9a86bb2d3d","src/args/arg_builder/switched.rs":"bc4c5acb77741562c4258b643a3dddd6b22e5b1874b71919d333c7d1e03e0ccb","src/args/arg_builder/valued.rs":"5f19d8e84e3d0bd3aee4b6fbb124206a6ab234492fe2ffc7279043e983522765","src/args/arg_matcher.rs":"a3cbe567cab3817c3ec7e37eb36641c9b9af1056b0002748b99a3ce255d65fd5","src/args/arg_matches.rs":"2058c1b0276db9d345b66d0531159fa05677ef865823ac8ec9831473359b64a8","src/args/group.rs":"6f08b7ebcbe2968a6d8462ab7c32dfc36c6b862a00853e9dc13af827196bc923","src/args/macros.rs":"4686d5929c760d2dace4110e96179d6aa7e43d7f911938199b07cb5728dc319b","src/args/matched_arg.rs":"28754509ea5493b66b4a5648d977f7cd9b379507b6eff89d76931be91509e6fe","src/args/mod.rs":"66cc0bb745fafd6387db72caa5ac414514990a07421270bfb5d8aff77ff01600","src/args/settings.rs":"f52313e363c1a928d65a52fbb7abb04b2ae00bd1e319fe267cf809363618fce8","src/args/subcommand.rs":"518418bb276c9758e3f82fc73341d69a242836ce163cd2ef6198075acf6594ba","src/completions/bash.rs":"d086d1e477ed14702650e2e7e0d2d33ba0a977f0a5c9f4e5d3cdb23b6ae5529f","src/completions/elvish.rs":"91e6f6685c258bfa4cdd4d428fa84ec9b59b2133e3d75f0e88072a37454430dc","src/completions/fish.rs":"3a828f824bde8dbe6bfa2d9ea52259b8b534bc547e9d96aec46f56e430b118e4","src/completions/macros.rs":"fd449b9d5fc6c591feb419d209f72cddfff0dd0345a8ec9787c361be6e5275f8","src/completions/mod.rs":"96b1115d6973b68dbbb1b50929f281e4ba9943995bc69dbb0ef08311d623ae33","src/completions/powershell.rs":"738a642a074c74ea28af66de3973b132de97587192c996bed436d54f6dfb6179","src/completions/shell.rs":"f6e132d8ea06ee30435c977f0040a6eb804bfe7a802181041dee8a4f69f64bd1","src/completions/zsh.rs":"0a06b25521714c70bfb943e8a11be62b8010ddb8676a426c2b30b00daccef9fa","src/errors.rs":"7c755e43fa743a9f5071ce30fee224e84684ca7b948ce128844552fbd36cde75","src/fmt.rs":"02c640020993b439133ba6a336f5f6d79d80ca9ede8b81b115c429b0aa2b6944","src/lib.rs":"b55c29b8b6d36b3ff1e4230bbce533d8170139a72a28cf5e0fc26789bbc3383e","src/macros.rs":"86977f1557b943678c1b6feeb4b63b17692e35601075a6be841a40fa0da7acd4","src/map.rs":"0b53139bf9eb768843a478b905929153ae6837082d846d97c81dd0a98d2c5d55","src/osstringext.rs":"92be9bb46ce1673a71bd1e809585621a00e9b38d9eb8caf70f0f29c4a47e0c74","src/strext.rs":"9847933a25ccf757dbcbb1c5a4921a5f8cdaa9dfcd451961bc37d1023d8dd1e1","src/suggestions.rs":"98f6ad3aa5df6cc6c8a1d31a5d1bea9a33cc8fed2b0f5f38255f3878b3cfce37","src/usage_parser.rs":"90b41f753d26cd6dfbf97613a8325c9034c1d98e55cee339c792f0b70baa6595"},"package":"a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"} \ No newline at end of file diff --git a/bash-5.1/vendor/clap/CHANGELOG.md b/bash-5.1/vendor/clap/CHANGELOG.md new file mode 100644 index 0000000..7f61b84 --- /dev/null +++ b/bash-5.1/vendor/clap/CHANGELOG.md @@ -0,0 +1,2902 @@ +
+## v2.34.0 (2021-11-30) + +- Updates to Rust 2018 edition and bumps the MSRV to Rust 1.46 + + +### v2.33.4 (2021-11-29) + +#### Bug Fixes + +* **prevents `panic`:** swallows broken pipe errors on error output ([7a729bc4](https://github.com/kbknapp/clap-rs/commit/7a729bc4df2646b05f6bf15f001124cd39d076ce)) + + +### v2.33.3 (2020-08-13) + +#### Improvements + +* Suppress deprecation warnings when using `crate_*` macros. + + +### v2.33.2 (2020-08-5) + +#### Documentation + +* Fixed links to `2.x` examples. Now they point to the right place. + + +### v2.33.1 (2020-05-11) + +#### Bug Fixes + +* Windows: Prevent some panics when parsing invalid Unicode on Windows ([922c645](https://github.com/clap-rs/clap/commit/922c64508389170c9c77f1c8a4e597d14d3ed2f0), closes [#1905](https://github.com/clap-rs/clap/issues/1905)) + +#### Documentation + +* fixes versions referenced in the README ([d307466a](https://github.com/kbknapp/clap-rs/commit/d307466af1013f172b8ec0252f01a473e2192d6b)) +* **README.md:** + * cuts down the number of examples to reduce confusion ([6e508ee0](https://github.com/kbknapp/clap-rs/commit/6e508ee09e7153de4adf4e88b0aa6418a537dadd)) + +#### Improvements + +* **Deps:** doesnt compile ansi_term on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155)) + +#### Minimum Required Rust + +* As of this release, `clap` requires `rustc 1.36.0` or greater. + + +## v2.33.0 (2019-04-06) + +#### New Sponsor + +* Stephen Oats is now a sponsor \o/ ([823457c0](https://github.com/kbknapp/clap-rs/commit/823457c0ef5e994ed7080cf62addbfe1aa3b1833)) +* **SPONSORS.md:** fixes Josh Triplett's info in the sponsor document ([24cb5740](https://github.com/kbknapp/clap-rs/commit/24cb574090a11159b48bba105d5ec2dfb0a20e4e)) + +#### Features + +* **Completions:** adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9)) +* There is a new setting to disable automatic building of `--help` and `-h` flags (`AppSettings::DisableAutoHelp`) + +#### Improvements + +* **arg_matches.rs:** add Debug implementations ([47192b7a](https://github.com/kbknapp/clap-rs/commit/47192b7a2d84ec716b81ae4af621e008a8762dc9)) +* **macros:** Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559)) + +#### Documentation + +* Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c)) +* **README.md:** use https for all links ([96a7639a](https://github.com/kbknapp/clap-rs/commit/96a7639a36bcb184c3f45348986883115ef1ab3a)) + +#### Bug Fixes + +* add debug assertion for missing args in subcommand ArgGroup ([2699d9e5](https://github.com/kbknapp/clap-rs/commit/2699d9e51e7eadc258ba64c4e347c5d1fef61343)) +* Restore compat with Rust 1.21 ([6b263de1](https://github.com/kbknapp/clap-rs/commit/6b263de1d42ede692ec5ee55019ad2fc6386f92e)) +* Dont mention unused subcommands ([ef92e2b6](https://github.com/kbknapp/clap-rs/commit/ef92e2b639ed305bdade4741f60fa85cb0101c5a)) +* **OsValues:** Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4)) +* **arg_enum!:** + * Fix comma position for valid values. ([1f1f9ff3](https://github.com/kbknapp/clap-rs/commit/1f1f9ff3fa38a43231ef8be9cfea89a32e53f518)) + * Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862)) +* **completions:** improve correctness of completions when whitespace is involved ([5a08ff29](https://github.com/kbknapp/clap-rs/commit/5a08ff295b2aa6ce29420df6252a0e3ff4441bdc)) +* **help message:** Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897)) +* **macros:** fixes broken pattern which prevented calling multi-argument Arg methods ([9e7a352e](https://github.com/kbknapp/clap-rs/commit/9e7a352e13aaf8025d80f2bac5c47fb32528672b)) +* **parser:** Better interaction between AllowExternalSubcommands and SubcommandRequired ([9601c95a](https://github.com/kbknapp/clap-rs/commit/9601c95a03d2b82bf265c328b4769238f1b79002)) + +#### Minimum Required Rust + +* As of this release, `clap` requires `rustc 1.31.0` or greater. + + +## v2.32.0 (2018-06-26) + +#### Minimum Required Rust + +* As of this release, `clap` requires `rustc 1.21.0` or greater. + + +#### Features + +* **Completions:** adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9)) + +#### Improvements + +* **macros:** Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559)) + +#### Bug Fixes + +* **OsValues:** Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4)) +* **arg_enum!:** Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862)) +* **help message:** Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897)) + +#### Documentation + +* Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c)) + + + + +### v2.31.2 (2018-03-19) + +#### Bug Fixes + +* **Fish Completions:** fixes a bug that only allowed a single completion in in Fish Shell ([e8774a8](https://github.com/kbknapp/clap-rs/pull/1214/commits/e8774a84ee4a319c888036e7c595ab46451d8e48), closes [#1212](https://github.com/kbknapp/clap-rs/issues/1212)) +* **AllowExternalSubcommands**: fixes a bug where external subcommands would be blocked by a similarly named subcommand (suggestions were getting in the way). ([a410e85](https://github.com/kbknapp/clap-rs/pull/1215/commits/a410e855bcd82b05f9efa73fa8b9774dc8842c6b)) + +#### Documentation + +* Fixes some typos in the `README.md` ([c8e685d7](https://github.com/kbknapp/clap-rs/commit/c8e685d76adee2a3cc06cac6952ffcf6f9548089)) + + +### v2.31.1 (2018-03-06) + + +#### Improvements + +* **AllowMissingPositional:** improves the ability of AllowMissingPositional to allow 'skipping' to the last positional arg with '--' ([df20e6e2](https://github.com/kbknapp/clap-rs/commit/df20e6e24b4e782be0b423b484b9798e3e2efe2f)) + + + +## v2.31.0 (2018-03-04) + + +#### Features + +* **Arg Indices:** adds the ability to query argument value indices ([f58d0576](https://github.com/kbknapp/clap-rs/commit/f58d05767ec8133c8eb2de117cb642b9ae29ccbc)) +* **Indices:** implements an Indices iterator ([1e67be44](https://github.com/kbknapp/clap-rs/commit/1e67be44f0ccf161cc84c4e6082382072e89c302)) +* **Raw Args** adds a convenience function to `Arg` that allows implying all of `Arg::last` `Arg::allow_hyphen_values` and `Arg::multiple(true)` ([66a78f29](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2)) + +#### Documentation + +* Fix some typos and markdown issues. ([935ba0dd](https://github.com/kbknapp/clap-rs/commit/935ba0dd547a69c3f636c5486795012019408794)) +* **Arg Indices:** adds the documentation for the arg index querying methods ([50bc0047](https://github.com/kbknapp/clap-rs/commit/50bc00477afa64dc6cdc5de161d3de3ba1d105a7)) +* **CONTRIBUTING.md:** fix url to clippy upstream repo to point to https://github.com/rust-lang-nursery/rust-clippy instead of https://github.com/Manishearth/rust-clippy ([42407d7f](https://github.com/kbknapp/clap-rs/commit/42407d7f21d794103cda61f49d2615aae0a4bcd9)) +* **Values:** improves the docs example of the Values iterator ([74075d65](https://github.com/kbknapp/clap-rs/commit/74075d65e8db1ddb5e2a4558009a5729d749d1b6)) +* Updates readme to hint that the `wrap_help` feature is a thing ([fc7ab227](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2)) + +### Improvements + +* Cargo.toml: use codegen-units = 1 in release and bench profiles ([19f425ea](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2)) +* Adds WASM support (clap now compiles on WASM!) ([689949e5](https://github.com/kbknapp/clap-rs/commit/689949e57d390bb61bc69f3ed91f60a2105738d0)) +* Uses the short help tool-tip for PowerShell completion scripts ([ecda22ce](https://github.com/kbknapp/clap-rs/commit/ecda22ce7210ce56d7b2d1a5445dd1b8a2959656)) + + + +## v2.30.0 (2018-02-13) + +#### Bug Fixes + +* **YAML:** Adds a missing conversion from `Arg::last` when instantiating from a YAML file ([aab77c81a5](https://github.com/kbknapp/clap-rs/pull/1175/commits/aab77c81a519b045f95946ae0dd3e850f9b93070), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1173)) + +#### Improvements + +* **Bash Completions:** instead of completing a generic option name, all bash completions fall back to file completions UNLESS `Arg::possible_values` was used ([872f02ae](https://github.com/kbknapp/clap-rs/commit/872f02aea900ffa376850a279eb164645e1234fa)) +* **Deps:** No longer needlessly compiles `ansi_term` on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155)) +* **Help Message:** changes the `[values: foo bar baz]` array to `[possible values: foo bar baz]` for consistency with the API ([414707e4e97](https://github.com/kbknapp/clap-rs/pull/1176/commits/414707e4e979d07bfe555247e5d130c546673708), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1160)) + + + +### v2.29.4 (2018-02-06) + + +#### Bug Fixes + +* **Overrides Self:** fixes a bug where options with multiple values couldnt ever have multiple values ([d95907cf](https://github.com/kbknapp/clap-rs/commit/d95907cff6d011a901fe35fa00b0f4e18547a1fb)) + + + + +### v2.29.3 (2018-02-05) + + +#### Improvements + +* **Overrides:** clap now supports arguments which override with themselves ([6c7a0010](https://github.com/kbknapp/clap-rs/commit/6c7a001023ca1eac1cc6ffe6c936b4c4a2aa3c45), closes [#976](https://github.com/kbknapp/clap-rs/issues/976)) + +#### Bug Fixes + +* **Requirements:** fixes an issue where conflicting args would still show up as required ([e06cefac](https://github.com/kbknapp/clap-rs/commit/e06cefac97083838c0a4e1444dcad02a5c3f911e), closes [#1158](https://github.com/kbknapp/clap-rs/issues/1158)) +* Fixes a bug which disallows proper nesting of `--` ([73993fe](https://github.com/kbknapp/clap-rs/commit/73993fe30d135f682e763ec93dcb0814ed518011), closes [#1161](https://github.com/kbknapp/clap-rs/issues/1161)) + +#### New Settings + +* **AllArgsOverrideSelf:** adds a new convenience setting to allow all args to override themselves ([4670325d](https://github.com/kbknapp/clap-rs/commit/4670325d1bf0369addec2ae2bcb56f1be054c924)) + + + + +### v2.29.2 (2018-01-16) + + +#### Features + +* **completions/zsh.rs:** + * Escape possible values for options ([25561dec](https://github.com/kbknapp/clap-rs/commit/25561decf147d329b64634a14d9695673c2fc78f)) + * Implement postional argument possible values completion ([f3b0afd2](https://github.com/kbknapp/clap-rs/commit/f3b0afd2bef8b7be97162f8a7802ddf7603dff36)) + * Complete positional arguments properly ([e39aeab8](https://github.com/kbknapp/clap-rs/commit/e39aeab8487596046fbdbc6a226e5c8820585245)) + +#### Bug Fixes + +* **completions/zsh.rs:** + * Add missing autoload for is-at-least ([a6522607](https://github.com/kbknapp/clap-rs/commit/a652260795d1519f6ec2a7a09ccc1258499cad7b)) + * Don't pass -S to _arguments if Zsh is too old ([16b4f143](https://github.com/kbknapp/clap-rs/commit/16b4f143ff466b7ef18a267bc44ade0f9639109b)) + * Maybe fix completions with mixed positionals and subcommands ([1146f0da](https://github.com/kbknapp/clap-rs/commit/1146f0da154d6796fbfcb09db8efa3593cb0d898)) +* **completions/zsh.zsh:** Remove redundant code from output ([0e185b92](https://github.com/kbknapp/clap-rs/commit/0e185b922ed1e0fd653de00b4cd8d567d72ff68e), closes [#1142](https://github.com/kbknapp/clap-rs/issues/1142)) + + + + +### 2.29.1 (2018-01-09) + + +#### Documentation + +* fixes broken links. ([56e734b8](https://github.com/kbknapp/clap-rs/commit/56e734b839303d733d2e5baf7dac39bd7b97b8e4)) +* updates contributors list ([e1313a5a](https://github.com/kbknapp/clap-rs/commit/e1313a5a0f69d8f4016f73b860a63af8318a6676)) + +#### Performance + +* further debloating by removing generics from error cases ([eb8d919e](https://github.com/kbknapp/clap-rs/commit/eb8d919e6f3443db279ba0c902f15d76676c02dc)) +* debloats clap by deduplicating logic and refactors ([03e413d7](https://github.com/kbknapp/clap-rs/commit/03e413d7175d35827cd7d8908d47dbae15a849a3)) + +#### Bug Fixes + +* fixes the ripgrep benchmark by adding a value to a flag that expects it ([d26ab2b9](https://github.com/kbknapp/clap-rs/commit/d26ab2b97cf9c0ea675b440b7b0eaf6ac3ad01f4)) +* **bash completion:** Change the bash completion script code generation to support hyphens. ([ba7f1d18](https://github.com/kbknapp/clap-rs/commit/ba7f1d18eba7a07ce7f57e0981986f66c994b639)) +* **completions/zsh.rs:** Fix completion of long option values ([46365cf8](https://github.com/kbknapp/clap-rs/commit/46365cf8be5331ba04c895eb183e2f230b5aad51)) + + + +## 2.29.0 (2017-12-02) + + +#### API Additions + +* **Arg:** adds Arg::hide_env_values(bool) which allows one to hide any current env values and display only the key in help messages ([fb41d062](https://github.com/kbknapp/clap-rs/commit/fb41d062eedf37cb4f805c90adca29909bd197d7)) + + + + +## 2.28.0 (2017-11-28) + +The minimum required Rust is now 1.20. This was done to start using bitflags 1.0 and having >1.0 deps is a *very good* thing! + +#### Documentation + +* changes the demo version to 2.28 to stay in sync ([ce6ca492](https://github.com/kbknapp/clap-rs/commit/ce6ca492c7510ab6474075806360b96081b021a9)) +* Fix URL path to github hosted files ([ce72aada](https://github.com/kbknapp/clap-rs/commit/ce72aada56a9581d4a6cb4bf9bdb861c3906f8df), closes [#1106](https://github.com/kbknapp/clap-rs/issues/1106)) +* fix typo ([002b07fc](https://github.com/kbknapp/clap-rs/commit/002b07fc98a1c85acb66296b1eec0b2aba906125)) +* **README.md:** updates the readme and pulls out some redundant sections ([db6caf86](https://github.com/kbknapp/clap-rs/commit/db6caf8663747e679d2f4ed3bd127f33476754aa)) + +#### Improvements + +* adds '[SUBCOMMAND]' to usage strings with only AppSettings::AllowExternalSubcommands is used with no other subcommands ([e78bb757](https://github.com/kbknapp/clap-rs/commit/e78bb757a3df16e82d539e450c06767a6bfcf859), closes [#1093](https://github.com/kbknapp/clap-rs/issues/1093)) + +#### API Additions + +* Adds Arg::case_insensitive(bool) which allows matching Arg::possible_values without worrying about ASCII case ([1fec268e](https://github.com/kbknapp/clap-rs/commit/1fec268e51736602e38e67c76266f439e2e0ef12), closes [#1118](https://github.com/kbknapp/clap-rs/issues/1118)) +* Adds the traits to be used with the clap-derive crate to be able to use Custom Derive ([6f4c3412](https://github.com/kbknapp/clap-rs/commit/6f4c3412415e882f5ca2cc3fbd6d4dce79440828)) + +#### Bug Fixes + +* Fixes a regression where --help couldn't be overridden ([a283d69f](https://github.com/kbknapp/clap-rs/commit/a283d69fc08aa016ae1bf9ba010012abecc7ba69), closes [#1112](https://github.com/kbknapp/clap-rs/issues/1112)) +* fixes a bug that allowed options to pass parsing when no value was provided ([2fb75821](https://github.com/kbknapp/clap-rs/commit/2fb758219c7a60d639da67692e100b855a8165ac), closes [#1105](https://github.com/kbknapp/clap-rs/issues/1105)) +* ignore PropagateGlobalValuesDown deprecation warning ([f61ce3f5](https://github.com/kbknapp/clap-rs/commit/f61ce3f55fe65e16b3db0bd4facdc4575de22767), closes [#1086](https://github.com/kbknapp/clap-rs/issues/1086)) + +#### Deps + +* Updates `bitflags` to 1.0 + + + + +## v2.27.1 (2017-10-24) + + +#### Bug Fixes + +* Adds `term_size` as an optional dependency (with feature `wrap_help`) to fix compile bug + + +## v2.27.0 (2017-10-24) + +** This release raises the minimum required version of Rust to 1.18 ** + +** This release also contains a very minor breaking change to fix a bug ** + +The only CLIs affected will be those using unrestrained multiple values and subcommands where the +subcommand name can coincide with one of the multiple values. + +See the commit [0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31) for full details. + + +#### Bug Fixes + +* Values from global args are now propagated UP and DOWN! +* fixes a bug where using AppSettings::AllowHyphenValues would allow invalid arguments even when there is no way for them to be valid ([77ed4684](https://github.com/kbknapp/clap-rs/commit/77ed46841fc0263d7aa32fcc5cc49ef703b37c04), closes [#1066](https://github.com/kbknapp/clap-rs/issues/1066)) +* when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/)) +* fixes a bug that prevented number_of_values and default_values to be used together ([5eb342a9](https://github.com/kbknapp/clap-rs/commit/5eb342a99dde07b0f011048efde3e283bc1110fc), closes [#1050](https://github.com/kbknapp/clap-rs/issues/1050), [#1056](https://github.com/kbknapp/clap-rs/issues/1056)) +* fixes a bug that didn't allow args with default values to have conflicts ([58b5b4be](https://github.com/kbknapp/clap-rs/commit/58b5b4be315280888d50d9b15119b91a9028f050), closes [#1071](https://github.com/kbknapp/clap-rs/issues/1071)) +* fixes a panic when using global args and calling App::get_matches_from_safe_borrow multiple times ([d86ec797](https://github.com/kbknapp/clap-rs/commit/d86ec79742c77eb3f663fb30e225954515cf25bb), closes [#1076](https://github.com/kbknapp/clap-rs/issues/1076)) +* fixes issues and potential regressions with global args values not being propagated properly or at all ([a43f9dd4](https://github.com/kbknapp/clap-rs/commit/a43f9dd4aaf1864dd14a3c28dec89ccdd70c61e5), closes [#1010](https://github.com/kbknapp/clap-rs/issues/1010), [#1061](https://github.com/kbknapp/clap-rs/issues/1061), [#978](https://github.com/kbknapp/clap-rs/issues/978)) +* fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047)) + +#### Documentation + +* adds addtional blurbs about using multiples with subcommands ([03455b77](https://github.com/kbknapp/clap-rs/commit/03455b7751a757e7b2f6ffaf2d16168539c99661)) +* updates the docs to reflect changes to global args and that global args values can now be propagated back up the stack ([ead076f0](https://github.com/kbknapp/clap-rs/commit/ead076f03ada4c322bf3e34203925561ec496d87)) +* add html_root_url attribute ([e67a061b](https://github.com/kbknapp/clap-rs/commit/e67a061bcf567c6518d6c2f58852e01f02764b22)) +* sync README version numbers with crate version ([5536361b](https://github.com/kbknapp/clap-rs/commit/5536361bcda29887ed86bb68e43d0b603cbc423f)) + +#### Improvements + +* args that have require_delimiter(true) is now reflected in help and usage strings ([dce61699](https://github.com/kbknapp/clap-rs/commit/dce616998ed9bd95e8ed3bec1f09a4883da47b85), closes [#1052](https://github.com/kbknapp/clap-rs/issues/1052)) +* if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046)) + +#### Breaking Changes + +* when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/)) + +#### Deprecations + +* **AppSettings::PropagateGlobalValuesDown:** this setting is no longer required to propagate values down or up ([2bb5ddce](https://github.com/kbknapp/clap-rs/commit/2bb5ddcee61c791ca1aaca494fbeb4bd5e277488)) + + + + +### v2.26.2 (2017-09-14) + + +#### Improvements + +* if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046)) + +#### Bug Fixes + +* fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047)) + + + + +### v2.26.1 (2017-09-14) + + +#### Bug Fixes + +* fixes using require_equals(true) and min_values(0) together ([10ae208f](https://github.com/kbknapp/clap-rs/commit/10ae208f68518eff6e98166724065745f4083174), closes [#1044](https://github.com/kbknapp/clap-rs/issues/1044)) +* escape special characters in zsh and fish completions ([87e019fc](https://github.com/kbknapp/clap-rs/commit/87e019fc84ba6193a8c4ddc26c61eb99efffcd25)) +* avoid panic generating default help msg if term width set to 0 due to bug in textwrap 0.7.0 ([b3eadb0d](https://github.com/kbknapp/clap-rs/commit/b3eadb0de516106db4e08f078ad32e8f6d6e7a57)) +* Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349)) +* adds a debug assertion to ensure all args added to groups actually exist ([7ad123e2](https://github.com/kbknapp/clap-rs/commit/7ad123e2c02577e3ca30f7e205181e896b157d11), closes [#917](https://github.com/kbknapp/clap-rs/issues/917)) +* fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ab2f4c9e](https://github.com/kbknapp/clap-rs/commit/ab2f4c9e563e36ec739a4b55d5a5b76fdb9e9fa4), closes [#960](https://github.com/kbknapp/clap-rs/issues/960)) +* fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21)) +* **Help Message:** fixes long_about not being usable ([a8257ea0](https://github.com/kbknapp/clap-rs/commit/a8257ea0ffb812e552aca256c4a3d2aebfd8065b), closes [#1043](https://github.com/kbknapp/clap-rs/issues/1043)) +* **Suggestions:** output for flag after subcommand ([434ea5ba](https://github.com/kbknapp/clap-rs/commit/434ea5ba71395d8c1afcf88e69f0b0d8339b01a1)) + + + + +## v2.26.0 (2017-07-29) + +Minimum version of Rust is now v1.13.0 (Stable) + + +#### Improvements + +* bumps unicode-segmentation to v1.2 ([cd7b40a2](https://github.com/kbknapp/clap-rs/commit/cd7b40a21c77bae17ba453c5512cb82b7d1ce474)) + + +#### Performance + +* update textwrap to version 0.7.0 ([c2d4e637](https://github.com/kbknapp/clap-rs/commit/c2d4e63756a6f070e38c16dff846e9b0a53d6f93)) + + + + + +### v2.25.1 (2017-07-21) + +#### Improvements + +* impl Default for Values + OsValues for any lifetime. ([fb7d6231f1](https://github.com/kbknapp/clap-rs/commit/fb7d6231f13a2f79f411e62dca210b7dc9994c18)) + +#### Documentation + +* Various documentation typos and grammar fixes + + +### v2.25.0 (2017-06-20) + + +#### Features + +* use textwrap crate for wrapping help texts ([b93870c1](https://github.com/kbknapp/clap-rs/commit/b93870c10ae3bd90d233c586a33e086803117285)) + +#### Improvements + +* **Suggestions:** suggests to use flag after subcommand when applicable ([2671ca72](https://github.com/kbknapp/clap-rs/commit/2671ca7260119d4311d21c4075466aafdd9da734)) +* Bumps bitflags crate to v0.9 + +#### Documentation + +* Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349)) + +#### Documentation + +* **App::template:** adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cbea3d5a](https://github.com/kbknapp/clap-rs/commit/cbea3d5acf3271a7a734498c4d99c709941c331e), closes [#949](https://github.com/kbknapp/clap-rs/issues/949)) +* **Arg::allow_hyphen_values:** updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([f9b0d657](https://github.com/kbknapp/clap-rs/commit/f9b0d657835d3f517f313d70962177dc30acf4a7)) +* **README.md:** + * added a warning about using ~ deps ([821929b5](https://github.com/kbknapp/clap-rs/commit/821929b51bd60213955705900a436c9a64fcb79f), closes [#964](https://github.com/kbknapp/clap-rs/issues/964)) +* **clap_app!:** adds using the @group specifier to the macro docs ([826048cb](https://github.com/kbknapp/clap-rs/commit/826048cb3cbc0280169303f1498ff0a2b7395883), closes [#932](https://github.com/kbknapp/clap-rs/issues/932)) + + + + +### v2.24.2 (2017-05-15) + + +#### Bug Fixes + +* adds a debug assertion to ensure all args added to groups actually exist ([14f6b8f3](https://github.com/kbknapp/clap-rs/commit/14f6b8f3a2f6df73aeeec9c54a54909b1acfc158), closes [#917](https://github.com/kbknapp/clap-rs/issues/917)) +* fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ebf73a09](https://github.com/kbknapp/clap-rs/commit/ebf73a09db6f3c03c19cdd76b1ba6113930e1643), closes [#960](https://github.com/kbknapp/clap-rs/issues/960)) +* fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21)) + +#### Documentation + +* **App::template:** adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cf569438](https://github.com/kbknapp/clap-rs/commit/cf569438f309c199800bb8e46c9f140187de69d7), closes [#949](https://github.com/kbknapp/clap-rs/issues/949)) +* **Arg::allow_hyphen_values:** updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([ded5a2f1](https://github.com/kbknapp/clap-rs/commit/ded5a2f15474d4a5bd46a67b130ccb8b6781bd01)) +* **clap_app!:** adds using the @group specifier to the macro docs ([fe85fcb1](https://github.com/kbknapp/clap-rs/commit/fe85fcb1772b61f13b20b7ea5290e2437a76190c), closes [#932](https://github.com/kbknapp/clap-rs/issues/932)) + + + + +### v2.24.0 (2017-05-07) + + +#### Bug Fixes + +* fixes a bug where args with last(true) and required(true) set were not being printed in the usage string ([3ac533fe](https://github.com/kbknapp/clap-rs/commit/3ac533fedabf713943eedf006f830a5a486bbe80), closes [#944](https://github.com/kbknapp/clap-rs/issues/944)) +* fixes a bug that was printing the arg name, instead of value name when Arg::last(true) was used ([e1fe8ac3](https://github.com/kbknapp/clap-rs/commit/e1fe8ac3bc1f9cf4e36df0d881f8419755f1787b), closes [#940](https://github.com/kbknapp/clap-rs/issues/940)) +* fixes a bug where flags were parsed as flags AND positional values when specific combinations of settings were used ([20f83292](https://github.com/kbknapp/clap-rs/commit/20f83292d070038b8cee2a6b47e91f6b0a2f7871), closes [#946](https://github.com/kbknapp/clap-rs/issues/946)) + + + + +## v2.24.0 (2017-05-05) + + +#### Documentation + +* **README.md:** fix some typos ([fa34deac](https://github.com/kbknapp/clap-rs/commit/fa34deac079f334c3af97bb7fb151880ba8887f8)) + +#### API Additions + +* **Arg:** add `default_value_os` ([d5ef8955](https://github.com/kbknapp/clap-rs/commit/d5ef8955414b1587060f7218385256105b639c88)) +* **arg_matches.rs:** Added a Default implementation for Values and OsValues iterators. ([0a4384e3](https://github.com/kbknapp/clap-rs/commit/0a4384e350eed74c2a4dc8964c203f21ac64897f)) + + + +### v2.23.2 (2017-04-19) + + +#### Bug Fixes + +* **PowerShell Completions:** fixes a bug where powershells completions cant be used if no subcommands are defined ([a8bce558](https://github.com/kbknapp/clap-rs/commit/a8bce55837dc4e0fb187dc93180884a40ae09c6f), closes [#931](https://github.com/kbknapp/clap-rs/issues/931)) + +#### Improvements + +* bumps term_size to take advantage of better terminal dimension handling ([e05100b7](https://github.com/kbknapp/clap-rs/commit/e05100b73d74066a90876bf38f952adf5e8ee422)) +* **PowerShell Completions:** massively dedups subcommand names in the generate script to make smaller scripts that are still functionally equiv ([85b0e1cc](https://github.com/kbknapp/clap-rs/commit/85b0e1cc4b9755dda75a93d898d79bc38631552b)) + +#### Documentation + +* Fix a typo the minimum rust version required ([71dabba3](https://github.com/kbknapp/clap-rs/commit/71dabba3ea0a17c88b0e2199c9d99f0acbf3bc17)) + + +### v2.23.1 (2017-04-05) + + +#### Bug Fixes + +* fixes a missing newline character in the autogenerated help and version messages in some instances ([5ae9007d](https://github.com/kbknapp/clap-rs/commit/5ae9007d984ae94ae2752df51bcbaeb0ec89bc15)) + + + +## v2.23.0 (2017-04-05) + + +#### API Additions + +* `App::long_about` +* `App::long_version` +* `App::print_long_help` +* `App::write_long_help` +* `App::print_long_version` +* `App::write_long_version` +* `Arg::long_help` + +#### Features + +* allows distinguishing between short and long version messages (-V/short or --version/long) ([59272b06](https://github.com/kbknapp/clap-rs/commit/59272b06cc213289dc604dbc694cb95d383a5d68)) +* allows distinguishing between short and long help with subcommands in the same manner as args ([6b371891](https://github.com/kbknapp/clap-rs/commit/6b371891a1702173a849d1e95f9fecb168bf6fc4)) +* allows specifying a short help vs a long help (i.e. varying levels of detail depending on if -h or --help was used) ([ef1b24c3](https://github.com/kbknapp/clap-rs/commit/ef1b24c3a0dff2f58c5e2e90880fbc2b69df20ee)) +* **clap_app!:** adds support for arg names with hyphens similar to longs with hyphens ([f7a88779](https://github.com/kbknapp/clap-rs/commit/f7a8877978c8f90e6543d4f0d9600c086cf92cd7), closes [#869](https://github.com/kbknapp/clap-rs/issues/869)) + +#### Bug Fixes + +* fixes a bug that wasn't allowing help and version to be properly overridden ([8b2ceb83](https://github.com/kbknapp/clap-rs/commit/8b2ceb8368bcb70689fadf1c7f4b9549184926c1), closes [#922](https://github.com/kbknapp/clap-rs/issues/922)) + +#### Documentation + +* **clap_app!:** documents the `--("some-arg")` method for using args with hyphens inside them ([bc08ef3e](https://github.com/kbknapp/clap-rs/commit/bc08ef3e185393073d969d301989b6319c616c1f), closes [#919](https://github.com/kbknapp/clap-rs/issues/919)) + + + + +### v2.22.2 (2017-03-30) + + +#### Bug Fixes + +* **Custom Usage Strings:** fixes the usage string regression when using help templates ([0e4fd96d](https://github.com/kbknapp/clap-rs/commit/0e4fd96d74280d306d09e60ac44f938a82321769)) + + + + +### v2.22.1 (2017-03-24) + + +#### Bug Fixes + +* **usage:** fixes a big regression with custom usage strings ([2c41caba](https://github.com/kbknapp/clap-rs/commit/2c41caba3c7d723a2894e315d04da796b0e97759)) + + +## v2.22.0 (2017-03-23) + +#### API Additions + +* **App::name:** adds the ability to change the name of the App instance after creation ([d49e8292](https://github.com/kbknapp/clap-rs/commit/d49e8292b026b06e2b70447cd9f08299f4fcba76), closes [#908](https://github.com/kbknapp/clap-rs/issues/908)) +* **Arg::hide_default_value:** adds ability to hide the default value of an argument from the help string ([89e6ea86](https://github.com/kbknapp/clap-rs/commit/89e6ea861e16a1ad56757ca12f6b32d02253e44a), closes [#902](https://github.com/kbknapp/clap-rs/issues/902)) + + + +### v2.21.3 (2017-03-23) + +#### Bug Fixes + +* **yaml:** adds support for loading author info from yaml ([e04c390c](https://github.com/kbknapp/clap-rs/commit/e04c390c597a55fa27e724050342f16c42f1c5c9)) + + + +### v2.21.2 (2017-03-17) + + +#### Improvements + +* add fish subcommand help support ([f8f68cf8](https://github.com/kbknapp/clap-rs/commit/f8f68cf8251669aef4539a25a7c1166f0ac81ea6)) +* options that use `require_equals(true)` now display the equals sign in help messages, usage strings, and errors" ([c8eb0384](https://github.com/kbknapp/clap-rs/commit/c8eb0384d394d2900ccdc1593099c97808a3fa05), closes [#903](https://github.com/kbknapp/clap-rs/issues/903)) + + +#### Bug Fixes + +* setting the max term width now correctly propagates down through child subcommands + + + + +### v2.21.1 (2017-03-12) + + +#### Bug Fixes + +* **ArgRequiredElseHelp:** fixes the precedence of this error to prioritize over other error messages ([74b751ff](https://github.com/kbknapp/clap-rs/commit/74b751ff2e3631e337b7946347c1119829a41c53), closes [#895](https://github.com/kbknapp/clap-rs/issues/895)) +* **Positionals:** fixes some regression bugs resulting from old asserts in debug mode. ([9a3bc98e](https://github.com/kbknapp/clap-rs/commit/9a3bc98e9b55e7514b74b73374c5ac8b6e5e0508), closes [#896](https://github.com/kbknapp/clap-rs/issues/896)) + + + + +## v2.21.0 (2017-03-09) + +#### Performance + +* doesn't run `arg_post_processing` on multiple values anymore ([ec516182](https://github.com/kbknapp/clap-rs/commit/ec5161828729f6a53f0fccec8648f71697f01f78)) +* changes internal use of `VecMap` to `Vec` for matched values of `Arg`s ([22bf137a](https://github.com/kbknapp/clap-rs/commit/22bf137ac581684c6ed460d2c3c640c503d62621)) +* vastly reduces the amount of cloning when adding non-global args minus when they're added from `App::args` which is forced to clone ([8da0303b](https://github.com/kbknapp/clap-rs/commit/8da0303bc02db5fe047cfc0631a9da41d9dc60f7)) +* refactor to remove unneeded vectors and allocations and checks for significant performance increases ([0efa4119](https://github.com/kbknapp/clap-rs/commit/0efa4119632f134fc5b8b9695b007dd94b76735d)) + +#### Documentation + +* Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1)) + +#### Improvements + +* when `AppSettings::SubcommandsNegateReqs` and `ArgsNegateSubcommands` are used, a new more accurate double line usage string is shown ([50f02300](https://github.com/kbknapp/clap-rs/commit/50f02300d81788817acefef0697e157e01b6ca32), closes [#871](https://github.com/kbknapp/clap-rs/issues/871)) + +#### API Additions + +* **Arg::last:** adds the ability to mark a positional argument as 'last' which means it should be used with `--` syntax and can be accessed early ([6a7aea90](https://github.com/kbknapp/clap-rs/commit/6a7aea9043b83badd9ab038b4ecc4c787716147e), closes [#888](https://github.com/kbknapp/clap-rs/issues/888)) +* provides `default_value_os` and `default_value_if[s]_os` ([0f2a3782](https://github.com/kbknapp/clap-rs/commit/0f2a378219a6930748d178ba350fe5925be5dad5), closes [#849](https://github.com/kbknapp/clap-rs/issues/849)) +* provides `App::help_message` and `App::version_message` which allows one to override the auto-generated help/version flag associated help ([389c413](https://github.com/kbknapp/clap-rs/commit/389c413b7023dccab8c76aa00577ea1d048e7a99), closes [#889](https://github.com/kbknapp/clap-rs/issues/889)) + +#### New Settings + +* **InferSubcommands:** adds a setting to allow one to infer shortened subcommands or aliases (i.e. for subcommmand "test", "t", "te", or "tes" would be allowed assuming no other ambiguities) ([11602032](https://github.com/kbknapp/clap-rs/commit/11602032f6ff05881e3adf130356e37d5e66e8f9), closes [#863](https://github.com/kbknapp/clap-rs/issues/863)) + +#### Bug Fixes + +* doesn't print the argument sections in the help message if all args in that section are hidden ([ce5ee5f5](https://github.com/kbknapp/clap-rs/commit/ce5ee5f5a76f838104aeddd01c8ec956dd347f50)) +* doesn't include the various [ARGS] [FLAGS] or [OPTIONS] if the only ones available are hidden ([7b4000af](https://github.com/kbknapp/clap-rs/commit/7b4000af97637703645c5fb2ac8bb65bd546b95b), closes [#882](https://github.com/kbknapp/clap-rs/issues/882)) +* now correctly shows subcommand as required in the usage string when AppSettings::SubcommandRequiredElseHelp is used ([8f0884c1](https://github.com/kbknapp/clap-rs/commit/8f0884c1764983a49b45de52a1eddf8d721564d8)) +* fixes some memory leaks when an error is detected and clap exits ([8c2dd287](https://github.com/kbknapp/clap-rs/commit/8c2dd28718262ace4ae0db98563809548e02a86b)) +* fixes a trait that's marked private accidentlly, but should be crate internal public ([1ae21108](https://github.com/kbknapp/clap-rs/commit/1ae21108015cea87e5360402e1747025116c7878)) +* **Completions:** fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846)) + +#### Features + +* **Options:** adds the ability to require the equals syntax with options --opt=val ([f002693d](https://github.com/kbknapp/clap-rs/commit/f002693dec6a6959c4e9590cb7b7bfffd6d6e5bc), closes [#833](https://github.com/kbknapp/clap-rs/issues/833)) + + + + +### v2.20.5 (2017-02-18) + + +#### Bug Fixes + +* **clap_app!:** fixes a critical bug of a missing fragment specifier when using `!property` style tags. ([5635c1f94](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94)) + + + +### v2.20.4 (2017-02-15) + + +#### Bug Fixes + +* **Completions:** fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846)) + +#### Documentation + +* Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1)) + + + +### v2.20.3 (2017-02-03) + + +#### Documentation + +* **Macros:** adds a warning about changing values in Cargo.toml not triggering a rebuild automatically ([112aea3e](https://github.com/kbknapp/clap-rs/commit/112aea3e42ae9e0c0a2d33ebad89496dbdd95e5d), closes [#838](https://github.com/kbknapp/clap-rs/issues/838)) + +#### Bug Fixes + +* fixes a println->debugln typo ([279aa62e](https://github.com/kbknapp/clap-rs/commit/279aa62eaf08f56ce090ba16b937bc763cbb45be)) +* fixes bash completions for commands that have an underscore in the name ([7f5cfa72](https://github.com/kbknapp/clap-rs/commit/7f5cfa724f0ac4e098f5fe466c903febddb2d994), closes [#581](https://github.com/kbknapp/clap-rs/issues/581)) +* fixes a bug where ZSH completions would panic if the binary name had an underscore in it ([891a2a00](https://github.com/kbknapp/clap-rs/commit/891a2a006f775e92c556dda48bb32fac9807c4fb), closes [#581](https://github.com/kbknapp/clap-rs/issues/581)) +* allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828)) +* fixes a bug where global args weren't included in the generated completion scripts ([9a1e006e](https://github.com/kbknapp/clap-rs/commit/9a1e006eb75ad5a6057ebd119aa90f7e06c0ace8), closes [#841](https://github.com/kbknapp/clap-rs/issues/841)) + + + + +### v2.20.2 (2017-02-03) + +#### Bug Fixes + +* fixes a critical bug where subcommand settings were being propogated too far ([74648c94](https://github.com/kbknapp/clap-rs/commit/74648c94b893df542bfa5bb595e68c7bb8167e36), closes [#832](https://github.com/kbknapp/clap-rs/issues/832)) + + +#### Improvements + +* adds ArgGroup::multiple to the supported YAML fields for building ArgGroups from YAML ([d8590037](https://github.com/kbknapp/clap-rs/commit/d8590037ce07dafd8cd5b26928aa4a9fd3018288), closes [#840](https://github.com/kbknapp/clap-rs/issues/840)) + + +### v2.20.1 (2017-01-31) + +#### Bug Fixes + +* allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828)) +* actually show character in debug output ([84d8c547](https://github.com/kbknapp/clap-rs/commit/84d8c5476de95b7f37d61888bc4f13688b712434)) +* include final character in line lenght ([aff4ba18](https://github.com/kbknapp/clap-rs/commit/aff4ba18da8147e1259b04b0bfbc1fcb5c78a3c0)) + +#### Improvements + +* updates libc and term_size deps for the libc version conflict ([6802ac4a](https://github.com/kbknapp/clap-rs/commit/6802ac4a59c142cda9ec55ca0c45ae5cb9a6ab55)) + +#### Documentation + +* fix link from app_from_crate! to crate_authors! (#822) ([5b29be9b](https://github.com/kbknapp/clap-rs/commit/5b29be9b073330ab1f7227cdd19fe4aab39d5dcb)) +* fix spelling of "guaranteed" ([4f30a65b](https://github.com/kbknapp/clap-rs/commit/4f30a65b9c03eb09607eb91a929a6396637dc105)) + + + +#### New Settings + +* **ArgsNegateSubcommands:** disables args being allowed between subcommands ([5e2af8c9](https://github.com/kbknapp/clap-rs/commit/5e2af8c96adb5ab75fa2d1536237ebcb41869494), closes [#793](https://github.com/kbknapp/clap-rs/issues/793)) +* **DontCollapseArgsInUsage:** disables the collapsing of positional args into `[ARGS]` in the usage string ([c2978afc](https://github.com/kbknapp/clap-rs/commit/c2978afc61fb46d5263ab3b2d87ecde1c9ce1553), closes [#769](https://github.com/kbknapp/clap-rs/issues/769)) +* **DisableHelpSubcommand:** disables building the `help` subcommand ([a10fc859](https://github.com/kbknapp/clap-rs/commit/a10fc859ee20159fbd9ff4337be59b76467a64f2)) +* **AllowMissingPositional:** allows one to implement `$ prog [optional] ` style CLIs where the second postional argument is required, but the first is optional ([1110fdc7](https://github.com/kbknapp/clap-rs/commit/1110fdc7a345c108820dc45783a9bf893fa4c214), closes [#636](https://github.com/kbknapp/clap-rs/issues/636)) +* **PropagateGlobalValuesDown:** automatically propagats global arg's values down through *used* subcommands ([985536c8](https://github.com/kbknapp/clap-rs/commit/985536c8ebcc09af98aac835f42a8072ad58c262), closes [#694](https://github.com/kbknapp/clap-rs/issues/694)) + +#### API Additions + +##### Arg + +* **Arg::value_terminator:** adds the ability to terminate multiple values with a given string or char ([be64ce0c](https://github.com/kbknapp/clap-rs/commit/be64ce0c373efc106384baca3f487ea99fe7b8cf), closes [#782](https://github.com/kbknapp/clap-rs/issues/782)) +* **Arg::default_value_if[s]:** adds new methods for *conditional* default values (such as a particular value from another argument was used) ([eb4010e7](https://github.com/kbknapp/clap-rs/commit/eb4010e7b21724447ef837db11ac441915728f22)) +* **Arg::requires_if[s]:** adds the ability to *conditionally* require additional args (such as if a particular value was used) ([198449d6](https://github.com/kbknapp/clap-rs/commit/198449d64393c265f0bc327aaeac23ec4bb97226)) +* **Arg::required_if[s]:** adds the ability for an arg to be *conditionally* required (i.e. "arg X is only required if arg Y was used with value Z") ([ee9cfddf](https://github.com/kbknapp/clap-rs/commit/ee9cfddf345a6b5ae2af42ba72aa5c89e2ca7f59)) +* **Arg::validator_os:** adds ability to validate values which may contain invalid UTF-8 ([47232498](https://github.com/kbknapp/clap-rs/commit/47232498a813db4f3366ccd3e9faf0bff56433a4)) + +##### Macros + +* **crate_description!:** Uses the `Cargo.toml` description field to fill in the `App::about` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778)) +* **crate_name!:** Uses the `Cargo.toml` name field to fill in the `App::new` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778)) +* **app_from_crate!:** Combines `crate_version!`, `crate_name!`, `crate_description!`, and `crate_authors!` into a single macro call to build a default `App` instance from the `Cargo.toml` fields ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778)) + + +#### Features + +* **no_cargo:** adds a `no_cargo` feature to disable Cargo-env-var-dependent macros for those *not* using `cargo` to build their crates (#786) ([6fdd2f9d](https://github.com/kbknapp/clap-rs/commit/6fdd2f9d693aaf1118fc61bd362273950703f43d)) + +#### Bug Fixes + +* **Options:** fixes a critical bug where options weren't forced to have a value ([5a5f2b1e](https://github.com/kbknapp/clap-rs/commit/5a5f2b1e9f598a0d0280ef3e98abbbba2bc41132), closes [#665](https://github.com/kbknapp/clap-rs/issues/665)) +* fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([d3d34a2b](https://github.com/kbknapp/clap-rs/commit/d3d34a2b51ef31004055b0ab574f766d801c3adf), closes [#789](https://github.com/kbknapp/clap-rs/issues/789)) +* **Help Subcommand:** fixes a bug where the help subcommand couldn't be overriden ([d34ec3e0](https://github.com/kbknapp/clap-rs/commit/d34ec3e032d03e402d8e87af9b2942fe2819b2da), closes [#787](https://github.com/kbknapp/clap-rs/issues/787)) +* **Low Index Multiples:** fixes a bug which caused combinations of LowIndexMultiples and `Arg::allow_hyphen_values` to fail parsing ([26c670ca](https://github.com/kbknapp/clap-rs/commit/26c670ca16d2c80dc26d5c1ce83380ace6357318)) + +#### Improvements + +* **Default Values:** improves the error message when default values are involved ([1f33de54](https://github.com/kbknapp/clap-rs/commit/1f33de545036e7fd2f80faba251fca009bd519b8), closes [#774](https://github.com/kbknapp/clap-rs/issues/774)) +* **YAML:** adds conditional requirements and conditional default values to YAML ([9a4df327](https://github.com/kbknapp/clap-rs/commit/9a4df327893486adb5558ffefba790c634ccdc6e), closes [#764](https://github.com/kbknapp/clap-rs/issues/764)) +* Support `--("some-arg-name")` syntax for defining long arg names when using `clap_app!` macro ([f41ec962](https://github.com/kbknapp/clap-rs/commit/f41ec962c243a5ffff8b1be1ae2ad63970d3d1d4)) +* Support `("some app name")` syntax for defining app names when using `clap_app!` macro ([9895b671](https://github.com/kbknapp/clap-rs/commit/9895b671cff784f35cf56abcd8270f7c2ba09699), closes [#759](https://github.com/kbknapp/clap-rs/issues/759)) +* **Help Wrapping:** long app names (with spaces), authors, and descriptions are now wrapped appropriately ([ad4691b7](https://github.com/kbknapp/clap-rs/commit/ad4691b71a63e951ace346318238d8834e04ad8a), closes [#777](https://github.com/kbknapp/clap-rs/issues/777)) + + +#### Documentation + +* **Conditional Default Values:** fixes the failing doc tests of Arg::default_value_ifs ([4ef09101](https://github.com/kbknapp/clap-rs/commit/4ef091019c083b4db1a0c13f1c1e95ac363259f2)) +* **Conditional Requirements:** adds docs for Arg::requires_ifs ([7f296e29](https://github.com/kbknapp/clap-rs/commit/7f296e29db7d9036e76e5dbcc9c8b20dfe7b25bd)) +* **README.md:** fix some typos ([f22c21b4](https://github.com/kbknapp/clap-rs/commit/f22c21b422d5b287d1a1ac183a379ee02eebf54f)) +* **src/app/mod.rs:** fix some typos ([5c9b0d47](https://github.com/kbknapp/clap-rs/commit/5c9b0d47ca78dea285c5b9dec79063d24c3e451a)) + + +### v2.19.3 (2016-12-28) + + +#### Bug Fixes + +* fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([a0ee4993](https://github.com/kbknapp/clap-rs/commit/a0ee4993015ea97b06b5bc9f378d8bcb18f1c51c), closes [#789](https://github.com/kbknapp/clap-rs/issues/789)) + + + + +### v2.19.2 (2016-12-08) + +#### Bug Fixes + +* **ZSH Completions:** escapes square brackets in ZSH completions ([7e17d5a3](https://github.com/kbknapp/clap-rs/commit/7e17d5a36b2cc2cc77e7b15796b14d639ed3cbf7), closes [#771](https://github.com/kbknapp/clap-rs/issues/771)) + +#### Documentation + +* **Examples:** adds subcommand examples ([0e0f3354](https://github.com/kbknapp/clap-rs/commit/0e0f33547a6901425afc1d9fbe19f7ae3832d9a4), closes [#766](https://github.com/kbknapp/clap-rs/issues/766)) +* **README.md:** adds guidance on when to use ~ in version pinning, and clarifies breaking change policy ([591eaefc](https://github.com/kbknapp/clap-rs/commit/591eaefc7319142ba921130e502bb0729feed907), closes [#765](https://github.com/kbknapp/clap-rs/issues/765)) + + + + +### v2.19.1 (2016-12-01) + + +#### Bug Fixes + +* **Help Messages:** fixes help message alignment when specific settings are used on options ([cd94b318](https://github.com/kbknapp/clap-rs/commit/cd94b3188d63b63295a319e90e826bca46befcd2), closes [#760](https://github.com/kbknapp/clap-rs/issues/760)) + +#### Improvements + +* **Bash Completion:** allows bash completion to fall back to traidtional bash completion upon no matching completing function ([b1b16d56](https://github.com/kbknapp/clap-rs/commit/b1b16d56d8fddf819bdbe24b3724bb6a9f3fa613))) + + + +## v2.19.0 (2016-11-21) + +#### Features + +* allows specifying AllowLeadingHyphen style values, but only for specific args vice command wide ([c0d70feb](https://github.com/kbknapp/clap-rs/commit/c0d70febad9996a77a54107054daf1914c50d4ef), closes [#742](https://github.com/kbknapp/clap-rs/issues/742)) + +#### Bug Fixes + +* **Required Unless:** fixes a bug where having required_unless set doesn't work when conflicts are also set ([d20331b6](https://github.com/kbknapp/clap-rs/commit/d20331b6f7940ac3a4e919999f8bb4780875125d), closes [#753](https://github.com/kbknapp/clap-rs/issues/753)) +* **ZSH Completions:** fixes an issue where zsh completions caused panics if there were no subcommands ([49e7cdab](https://github.com/kbknapp/clap-rs/commit/49e7cdab76dd1ccc07221e360f07808ec62648aa), closes [#754](https://github.com/kbknapp/clap-rs/issues/754)) + +#### Improvements + +* **Validators:** improves the error messages for validators ([65eb3385](https://github.com/kbknapp/clap-rs/commit/65eb33859d3ff53e7d3277f02a9d3fd9038a9dfb), closes [#744](https://github.com/kbknapp/clap-rs/issues/744)) + +#### Documentation + +* updates the docs landing page ([01e1e33f](https://github.com/kbknapp/clap-rs/commit/01e1e33f377934099a4a725fab5cd6c5ff50eaa2)) +* adds the macro version back to the readme ([45eb9bf1](https://github.com/kbknapp/clap-rs/commit/45eb9bf130329c3f3853aba0342c2fe3c64ff80f)) +* fix broken docs links ([808e7cee](https://github.com/kbknapp/clap-rs/commit/808e7ceeb86d4a319bdc270f51c23a64621dbfb3)) +* **Compatibility Policy:** adds an official compatibility policy to ([760d66dc](https://github.com/kbknapp/clap-rs/commit/760d66dc17310b357f257776624151da933cd25d), closes [#740](https://github.com/kbknapp/clap-rs/issues/740)) +* **Contributing:** updates the readme to improve the readability and contributing sections ([eb51316c](https://github.com/kbknapp/clap-rs/commit/eb51316cdfdc7258d287ba13b67ef2f42bd2b8f6)) + + +## v2.18.0 (2016-11-05) + + +#### Features + +* **Completions:** adds completion support for PowerShell. ([cff82c88](https://github.com/kbknapp/clap-rs/commit/cff82c880e21064fca63351507b80350df6caadf), closes [#729](https://github.com/kbknapp/clap-rs/issues/729)) + + + + +### v2.17.1 (2016-11-02) + + +#### Bug Fixes + +* **Low Index Multiples:** fixes a bug where using low index multiples was propagated to subcommands ([33924e88](https://github.com/kbknapp/clap-rs/commit/33924e884461983c4e6b5ea1330fecc769a4ade7), closes [#725](https://github.com/kbknapp/clap-rs/issues/725)) + + + + +## v2.17.0 (2016-11-01) + + +#### Features + +* **Positional Args:** allows specifying the second to last positional argument as multiple(true) ([1ced2a74](https://github.com/kbknapp/clap-rs/commit/1ced2a7433ea8937a1b260ea65d708f32ca7c95e), closes [#725](https://github.com/kbknapp/clap-rs/issues/725)) + + + + +### v2.16.4 (2016-10-31) + + +#### Improvements + +* **Error Output:** conflicting errors are now symetrical, meaning more consistent and less confusing ([3d37001d](https://github.com/kbknapp/clap-rs/commit/3d37001d1dc647d73cc597ff172f1072d4beb80d), closes [#718](https://github.com/kbknapp/clap-rs/issues/718)) + +#### Documentation + +* Fix typo in example `13a_enum_values_automatic` ([c22fbc07](https://github.com/kbknapp/clap-rs/commit/c22fbc07356e556ffb5d1a79ec04597d149b915e)) +* **README.md:** fixes failing yaml example (#715) ([21fba9e6](https://github.com/kbknapp/clap-rs/commit/21fba9e6cd8c163012999cd0ce271ec8780c5695)) + +#### Bug Fixes + +* **ZSH Completions:** fixes bug that caused panic on subcommands with aliases ([5c70e1a0](https://github.com/kbknapp/clap-rs/commit/5c70e1a01bc977e44c10015d18bb8e215c32dfc8), closes [#714](https://github.com/kbknapp/clap-rs/issues/714)) +* **debug:** fixes the debug feature (#716) ([6c11ccf4](https://github.com/kbknapp/clap-rs/commit/6c11ccf443d46258d51f7cda33fbcc81e7fe8e90)) + + + + +### v2.16.3 (2016-10-28) + + +#### Bug Fixes + +* Derive display order after propagation ([9cb6facf](https://github.com/kbknapp/clap-rs/commit/9cb6facf507aff7cddd124b8c29714d2b0e7bd13), closes [#706](https://github.com/kbknapp/clap-rs/issues/706)) +* **yaml-example:** inconsistent args ([847f7199](https://github.com/kbknapp/clap-rs/commit/847f7199219ead5065561d91d64780d99ae4b587)) + + + + +### v2.16.2 (2016-10-25) + + +#### Bug Fixes + +* **Fish Completions:** fixes a bug where single quotes are not escaped ([780b4a18](https://github.com/kbknapp/clap-rs/commit/780b4a18281b6f7f7071e1b9db2290fae653c406), closes [#704](https://github.com/kbknapp/clap-rs/issues/704)) + + + +### v2.16.1 (2016-10-24) + + +#### Bug Fixes + +* **Help Message:** fixes a regression bug where args with multiple(true) threw off alignment ([ebddac79](https://github.com/kbknapp/clap-rs/commit/ebddac791f3ceac193d5ad833b4b734b9643a7af), closes [#702](https://github.com/kbknapp/clap-rs/issues/702)) + + + + +## v2.16.0 (2016-10-23) + + +#### Features + +* **Completions:** adds ZSH completion support ([3e36b0ba](https://github.com/kbknapp/clap-rs/commit/3e36b0bac491d3f6194aee14604caf7be26b3d56), closes [#699](https://github.com/kbknapp/clap-rs/issues/699)) + + + + +## v2.15.0 (2016-10-21) + + +#### Features + +* **AppSettings:** adds new setting `AppSettings::AllowNegativeNumbers` ([ab064546](https://github.com/kbknapp/clap-rs/commit/ab06454677fb6aa9b9f804644fcca2168b1eaee3), closes [#696](https://github.com/kbknapp/clap-rs/issues/696)) + +#### Documentation + +* **app/settings.rs:** moves variants to roughly alphabetical order ([9ed4d4d7](https://github.com/kbknapp/clap-rs/commit/9ed4d4d7957a23357aef60081e45639ab9e3905f)) + + + +### v2.14.1 (2016-10-20) + + +#### Documentation + +* Improve documentation around features ([4ee85b95](https://github.com/kbknapp/clap-rs/commit/4ee85b95d2d16708a016a3ba4e6e2c93b89b7fad)) +* reword docs for ErrorKind and app::Settings ([3ccde7a4](https://github.com/kbknapp/clap-rs/commit/3ccde7a4b8f7a2ea8b916a5415c04a8ff4b5cb7a)) +* fix tests that fail when the "suggestions" feature is disabled ([996fc381](https://github.com/kbknapp/clap-rs/commit/996fc381763a48d125c7ea8a58fed057fd0b4ac6)) +* fix the OsString-using doc-tests ([af9e1a39](https://github.com/kbknapp/clap-rs/commit/af9e1a393ce6cdda46a03c8a4f48df222b015a24)) +* tag non-rust code blocks as such instead of ignoring them ([0ba9f4b1](https://github.com/kbknapp/clap-rs/commit/0ba9f4b123f281952581b6dec948f7e51dd22890)) +* **ErrorKind:** improve some errors about subcommands ([9f6217a4](https://github.com/kbknapp/clap-rs/commit/9f6217a424da823343d7b801b9c350dee3cd1906)) +* **yaml:** make sure the doc-tests don't fail before "missing file" ([8c0f5551](https://github.com/kbknapp/clap-rs/commit/8c0f55516f4910c78c9f8a2bdbd822729574f95b)) + +#### Improvements + +* Stabilize clap_app! ([cd516006](https://github.com/kbknapp/clap-rs/commit/cd516006e35c37b005f329338560a0a53d1f3e00)) +* **with_defaults:** Deprecate App::with_defaults() ([26085409](https://github.com/kbknapp/clap-rs/commit/2608540940c8bb66e517b65706bc7dea55510682), closes [#638](https://github.com/kbknapp/clap-rs/issues/638)) + +#### Bug Fixes + +* fixes a bug that made determining when to auto-wrap long help messages inconsistent ([468baadb](https://github.com/kbknapp/clap-rs/commit/468baadb8398fc1d37897b0c49374aef4cf97dca), closes [#688](https://github.com/kbknapp/clap-rs/issues/688)) +* **Completions:** fish completions for nested subcommands ([a61eaf8a](https://github.com/kbknapp/clap-rs/commit/a61eaf8aade76cfe90ccc0f7125751ebf60e3254)) +* **features:** Make lints not enable other nightly-requiring features ([835f75e3](https://github.com/kbknapp/clap-rs/commit/835f75e3ba20999117363ed9f916464d777f36ef)) + + + + +## v2.14.0 (2016-10-05) + + +#### Features + +* **arg_aliases:** Ability to alias arguments ([33b5f6ef](https://github.com/kbknapp/clap-rs/commit/33b5f6ef2c9612ecabb31f96b824793e46bfd3dd), closes [#669](https://github.com/kbknapp/clap-rs/issues/669)) +* **flag_aliases:** Ability to alias flags ([40d6dac9](https://github.com/kbknapp/clap-rs/commit/40d6dac973927dded6ab423481634ef47ee7bfd7)) + +#### Bug Fixes + +* **UsageParser:** Handle non-ascii names / options. ([1d6a7c6e](https://github.com/kbknapp/clap-rs/commit/1d6a7c6e7e6aadc527346aa822f19d8587f714f3), closes [#664](https://github.com/kbknapp/clap-rs/issues/664)) + +#### Documentation + +* typo ([bac417fa](https://github.com/kbknapp/clap-rs/commit/bac417fa1cea3d32308334c7cccfcf54546cd9d8)) + + + +## v2.13.0 (2016-09-18) + + +#### Documentation + +* updates README.md with new website information and updated video tutorials info ([0c19c580](https://github.com/kbknapp/clap-rs/commit/0c19c580cf50f1b82ff32f70b36708ae2bcac132)) +* updates the docs about removing implicit value_delimiter(true) ([c81bc722](https://github.com/kbknapp/clap-rs/commit/c81bc722ebb8a86d22be89b5aec98df9fe222a08)) +* **Default Values:** adds better examples on using default values ([57a8d9ab](https://github.com/kbknapp/clap-rs/commit/57a8d9abb2f973c235a8a14f8fc031673d7a7460), closes [#418](https://github.com/kbknapp/clap-rs/issues/418)) + +#### Bug Fixes + +* **Value Delimiters:** fixes the confusion around implicitly setting value delimiters. (default is now `false`) ([09d4d0a9](https://github.com/kbknapp/clap-rs/commit/09d4d0a9038d7ce2df55c2aec95e16f36189fcee), closes [#666](https://github.com/kbknapp/clap-rs/issues/666)) + + + + +### v2.12.1 (2016-09-13) + + +#### Bug Fixes + +* **Help Wrapping:** fixes a regression-bug where the old {n} newline char stopped working ([92ac353b](https://github.com/kbknapp/clap-rs/commit/92ac353b48b7caa2511ad2a046d94da93c236cf6), closes [#661](https://github.com/kbknapp/clap-rs/issues/661)) + + + + +## v2.12.0 (2016-09-13) + + +#### Features + +* **Help:** adds ability to hide the possible values on a per argument basis ([9151ef73](https://github.com/kbknapp/clap-rs/commit/9151ef739871f2e74910c342299c0de196b95dec), closes [#640](https://github.com/kbknapp/clap-rs/issues/640)) +* **help:** allow for limiting detected terminal width ([a43e28af](https://github.com/kbknapp/clap-rs/commit/a43e28af85c9a9deaedd5ef735f4f13008daab29), closes [#653](https://github.com/kbknapp/clap-rs/issues/653)) + +#### Documentation + +* **Help Wrapping:** removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611)) +* **Value Delimiters:** updates the docs for the Arg::multiple method WRT value delimiters and default settings ([f9d17a06](https://github.com/kbknapp/clap-rs/commit/f9d17a060aa53f10d0a6e1a7eed5d989d1a59533)) +* **appsettings:** Document AppSetting::DisableVersion ([94501965](https://github.com/kbknapp/clap-rs/commit/945019654d2ca67eb2b1d6014fdf80b84d528d30), closes [#589](https://github.com/kbknapp/clap-rs/issues/589)) + +#### Bug Fixes + +* **AllowLeadingHyphen:** fixes a bug where valid args aren't recognized with this setting ([a9699e4d](https://github.com/kbknapp/clap-rs/commit/a9699e4d7cdc9a06e73b845933ff1fe6d76f016a), closes [#588](https://github.com/kbknapp/clap-rs/issues/588)) + +#### Improvements + +* **Help Wrapping:** + * clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617)) + * makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f)) +* **Value Delimiters:** changes the default value delimiter rules ([f9e69254](https://github.com/kbknapp/clap-rs/commit/f9e692548e8c94de15f909432de301407d6bb834), closes [#655](https://github.com/kbknapp/clap-rs/issues/655)) +* **YAML:** supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816)) + +#### Performance + +* **help:** fix redundant contains() checks ([a8afed74](https://github.com/kbknapp/clap-rs/commit/a8afed7428bf0733f8e93bb11ad6c00d9e970fcc)) + + + + +### v2.11.3 (2016-09-07) + + +#### Documentation + +* **Help Wrapping:** removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611)) + +#### Improvements + +* **Help Wrapping:** + * clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617)) + * makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f)) +* **YAML:** supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816)) + + + + + +### v2.11.2 (2016-09-06) + +#### Improvements + +* **Help Wrapping:** makes some minor changes to when next line help is automatically used ([5658b117](https://github.com/kbknapp/clap-rs/commit/5658b117aec3e03adff9c8c52a4c4bc1fcb4e1ff)) + + + +### v2.11.1 (2016-09-05) + + +#### Bug Fixes + +* **Settings:** fixes an issue where settings weren't propogated down through grand-child subcommands ([b3efc107](https://github.com/kbknapp/clap-rs/commit/b3efc107515d78517b20798ff3890b8a2b04498e), closes [#638](https://github.com/kbknapp/clap-rs/issues/638)) + +#### Features + +* **Errors:** Errors with custom description ([58512f2f](https://github.com/kbknapp/clap-rs/commit/58512f2fcb430745f1ee6ee8f1c67f62dc216c73)) + +#### Improvements + +* **help:** use term_size instead of home-grown solution ([fc7327e9](https://github.com/kbknapp/clap-rs/commit/fc7327e9dcf4258ef2baebf0a8714d9c0622855b)) + + + + +### v2.11.0 (2016-08-28) + + +#### Bug Fixes + +* **Groups:** fixes some usage strings that contain both args in groups and ones that conflict with each other ([3d782def](https://github.com/kbknapp/clap-rs/commit/3d782def57725e2de26ca5a5bc5cc2e40ddebefb), closes [#616](https://github.com/kbknapp/clap-rs/issues/616)) + +#### Documentation + +* moves docs to docs.rs ([03209d5e](https://github.com/kbknapp/clap-rs/commit/03209d5e1300906f00bafec1869c2047a92e5071), closes [#634](https://github.com/kbknapp/clap-rs/issues/634)) + +#### Improvements + +* **Completions:** uses standard conventions for bash completion files, namely '{bin}.bash-completion' ([27f5bbfb](https://github.com/kbknapp/clap-rs/commit/27f5bbfbcc9474c2f57c2b92b1feb898ae46ee70), closes [#567](https://github.com/kbknapp/clap-rs/issues/567)) +* **Help:** automatically moves help text to the next line and wraps when term width is determined to be too small, or help text is too long ([150964c4](https://github.com/kbknapp/clap-rs/commit/150964c4e7124d54476c9d9b4b3f2406f0fd00e5), closes [#597](https://github.com/kbknapp/clap-rs/issues/597)) +* **YAML Errors:** vastly improves error messages when using YAML ([f43b7c65](https://github.com/kbknapp/clap-rs/commit/f43b7c65941c53adc0616b8646a21dc255862eb2), closes [#574](https://github.com/kbknapp/clap-rs/issues/574)) + +#### Features + +* adds App::with_defaults to automatically use crate_authors! and crate_version! macros ([5520bb01](https://github.com/kbknapp/clap-rs/commit/5520bb012c127dfd299fd55699443c744d8dcd5b), closes [#600](https://github.com/kbknapp/clap-rs/issues/600)) + + + + +### v2.10.4 (2016-08-25) + + +#### Bug Fixes + +* **Help Wrapping:** fixes a bug where help is wrapped incorrectly and causing a panic with some non-English characters ([d0b442c7](https://github.com/kbknapp/clap-rs/commit/d0b442c7beeecac9764406bc3bd171ced0b8825e), closes [#626](https://github.com/kbknapp/clap-rs/issues/626)) + + + + +### v2.10.3 (2016-08-25) + +#### Features + +* **Help:** adds new short hand way to use source formatting and ignore term width in help messages ([7dfdaf20](https://github.com/kbknapp/clap-rs/commit/7dfdaf200ebb5c431351a045b48f5e0f0d3f31db), closes [#625](https://github.com/kbknapp/clap-rs/issues/625)) + +#### Documentation + +* **Term Width:** adds details about set_term_width(0) ([00b8205d](https://github.com/kbknapp/clap-rs/commit/00b8205d22639d1b54b9c453c55c785aace52cb2)) + +#### Bug Fixes + +* **Unicode:** fixes two bugs where non-English characters were stripped or caused a panic with help wrapping ([763a5c92](https://github.com/kbknapp/clap-rs/commit/763a5c920e23efc74d190af0cb8b5dd714b2d67a), closes [#626](https://github.com/kbknapp/clap-rs/issues/626)) + + + + +### v2.10.2 (2016-08-22) + + +#### Bug Fixes + +* fixes a bug where the help is printed twice ([a643fb28](https://github.com/kbknapp/clap-rs/commit/a643fb283acd9905dc727c4579c5c9fa2ceaa7e7), closes [#623](https://github.com/kbknapp/clap-rs/issues/623)) + + + + +### v2.10.1 (2016-08-21) + + +#### Bug Fixes + +* **Help Subcommand:** fixes misleading usage string when using multi-level subcommmands ([e203515e](https://github.com/kbknapp/clap-rs/commit/e203515e3ac495b405dbba4f78fb6af148fd282e), closes [#618](https://github.com/kbknapp/clap-rs/issues/618)) + +#### Features + +* **YAML:** allows using lists or single values with arg declarations ([9ade2cd4](https://github.com/kbknapp/clap-rs/commit/9ade2cd4b268d6d7fe828319ce6a523c641b9c38), closes [#614](https://github.com/kbknapp/clap-rs/issues/614), [#613](https://github.com/kbknapp/clap-rs/issues/613)) + + + + +## v2.10.0 (2016-07-29) + + +#### Features + +* **Completions:** one can generate a basic fish completions script at compile time ([1979d2f2](https://github.com/kbknapp/clap-rs/commit/1979d2f2f3216e57d02a97e624a8a8f6cf867ed9)) + +#### Bug Fixes + +* **parser:** preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635)) + +#### Breaking Changes + +* **parser:** preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635)) + +#### Documentation + +* **YAML:** fixes example 17's incorrect reference to arg_groups instead of groups ([b6c99e13](https://github.com/kbknapp/clap-rs/commit/b6c99e1377f918e78c16c8faced70a71607da931), closes [#601](https://github.com/kbknapp/clap-rs/issues/601)) + + + + +### 2.9.3 (2016-07-24) + + +#### Bug Fixes + +* fixes bug where only first arg in list of required_unless_one is recognized ([1fc3b55b](https://github.com/kbknapp/clap-rs/commit/1fc3b55bd6c8653b02e7c4253749c6b77737d2ac), closes [#575](https://github.com/kbknapp/clap-rs/issues/575)) +* **Settings:** fixes typo subcommandsrequired->subcommandrequired ([fc72cdf5](https://github.com/kbknapp/clap-rs/commit/fc72cdf591d30f5d9375d0b5cc2a2ff3e812f9f6), closes [#593](https://github.com/kbknapp/clap-rs/issues/593)) + +#### Features + +* **Completions:** adds the ability to generate completions to io::Write object ([9f62cf73](https://github.com/kbknapp/clap-rs/commit/9f62cf7378ba5acb5ce8c5bac89b4aa60c30755f)) +* **Settings:** Add unset_setting and unset_settings fns to App (#598) ([0ceba231](https://github.com/kbknapp/clap-rs/commit/0ceba231c6767cd6d88fdb1feeeea41deadf77ff), closes [#590](https://github.com/kbknapp/clap-rs/issues/590)) + + + +### 2.9.2 (2016-07-03) + + +#### Documentation + +* **Completions:** fixes the formatting of the Cargo.toml excerpt in the completions example ([722f2607](https://github.com/kbknapp/clap-rs/commit/722f2607beaef56b6a0e433db5fd09492d9f028c)) + +#### Bug Fixes + +* **Completions:** fixes bug where --help and --version short weren't added to the completion list ([e9f2438e](https://github.com/kbknapp/clap-rs/commit/e9f2438e2ce99af0ae570a2eaf541fc7f55b771b), closes [#536](https://github.com/kbknapp/clap-rs/issues/536)) + + + + +### 2.9.1 (2016-07-02) + + +#### Improvements + +* **Completions:** allows multiple completions to be built by namespacing with bin name ([57484b2d](https://github.com/kbknapp/clap-rs/commit/57484b2daeaac01c1026e8c84efc8bf099e0eb31)) + + + +## v2.9.0 (2016-07-01) + + +#### Documentation + +* **Completions:** + * fixes some errors in the completion docs ([9b359bf0](https://github.com/kbknapp/clap-rs/commit/9b359bf06255d3dad8f489308044b60a9d1e6a87)) + * adds documentation for completion scripts ([c6c519e4](https://github.com/kbknapp/clap-rs/commit/c6c519e40efd6c4533a9ef5efe8e74fd150391b7)) + +#### Features + +* **Completions:** + * one can now generate a bash completions script at compile time! ([e75b6c7b](https://github.com/kbknapp/clap-rs/commit/e75b6c7b75f729afb9eb1d2a2faf61dca7674634), closes [#376](https://github.com/kbknapp/clap-rs/issues/376)) + * completions now include aliases to subcommands, including all subcommand options ([0ab9f840](https://github.com/kbknapp/clap-rs/commit/0ab9f84052a8cf65b5551657f46c0c270841e634), closes [#556](https://github.com/kbknapp/clap-rs/issues/556)) + * completions now continue completing even after first completion ([18fc2e5b](https://github.com/kbknapp/clap-rs/commit/18fc2e5b5af63bf54a94b72cec5e1223d49f4806)) + * allows matching on possible values in options ([89cc2026](https://github.com/kbknapp/clap-rs/commit/89cc2026ba9ac69cf44c5254360bbf99236d4f89), closes [#557](https://github.com/kbknapp/clap-rs/issues/557)) + +#### Bug Fixes + +* **AllowLeadingHyphen:** fixes an issue where isn't ignored like it should be with this setting ([96c24c9a](https://github.com/kbknapp/clap-rs/commit/96c24c9a8fa1f85e06138d3cdd133e51659e19d2), closes [#558](https://github.com/kbknapp/clap-rs/issues/558)) + + +## v2.8.0 (2016-06-30) + + +#### Features + +* **Arg:** adds new setting `Arg::require_delimiter` which requires val delimiter to parse multiple values ([920b5595](https://github.com/kbknapp/clap-rs/commit/920b5595ed72abfb501ce054ab536067d8df2a66)) + +#### Bug Fixes + +* Declare term::Winsize as repr(C) ([5d663d90](https://github.com/kbknapp/clap-rs/commit/5d663d905c9829ce6e7a164f1f0896cdd70236dd)) + +#### Documentation + +* **Arg:** adds docs for ([49af4e38](https://github.com/kbknapp/clap-rs/commit/49af4e38a5dae2ab0a7fc3b4147e2c053d532484)) + + + + +### v2.7.1 (2016-06-29) + + +#### Bug Fixes + +* **Options:** + * options with multiple values and using delimiters no longer parse additional values after a trailing space ([cdc500bd](https://github.com/kbknapp/clap-rs/commit/cdc500bdde6abe238c36ade406ddafc2bafff583)) + * using options with multiple values and with an = no longer parse args after the trailing space as values ([290f61d0](https://github.com/kbknapp/clap-rs/commit/290f61d07177413cf082ada55526d83405f6d011)) + + + + +## v2.7.0 (2016-06-28) + + +#### Documentation + +* fix typos ([43b3d40b](https://github.com/kbknapp/clap-rs/commit/43b3d40b8c38b1571da75af86b5088be96cccec2)) +* **ArgGroup:** vastly improves ArgGroup docs by adding better examples ([9e5f4f5d](https://github.com/kbknapp/clap-rs/commit/9e5f4f5d734d630bca5535c3a0aa4fd4f9db3e39), closes [#534](https://github.com/kbknapp/clap-rs/issues/534)) + +#### Features + +* **ArgGroup:** one can now specify groups which require AT LEAST one of the args ([33689acc](https://github.com/kbknapp/clap-rs/commit/33689acc689b217a8c0ee439f1b1225590c38355), closes [#533](https://github.com/kbknapp/clap-rs/issues/533)) + +#### Bug Fixes + +* **App:** using `App::print_help` now prints the same as would have been printed by `--help` or the like ([e84cc018](https://github.com/kbknapp/clap-rs/commit/e84cc01836bbe0527e97de6db9889bd9e0fd6ba1), closes [#536](https://github.com/kbknapp/clap-rs/issues/536)) +* **Help:** + * prevents invoking help help and displaying incorrect help message ([e3d2893f](https://github.com/kbknapp/clap-rs/commit/e3d2893f377942a2d4cf3c6ff04524d0346e6fdb), closes [#538](https://github.com/kbknapp/clap-rs/issues/538)) + * subcommand help messages requested via help now correctly match --help ([08ad1cff](https://github.com/kbknapp/clap-rs/commit/08ad1cff4fec57224ea957a2891a057b323c01bc), closes [#539](https://github.com/kbknapp/clap-rs/issues/539)) + +#### Improvements + +* **ArgGroup:** Add multiple ArgGroups per Arg ([902e182f](https://github.com/kbknapp/clap-rs/commit/902e182f7a58aff11ff01e0a452abcdbdb2262aa), closes [#426](https://github.com/kbknapp/clap-rs/issues/426)) +* **Usage Strings:** `[FLAGS]` and `[ARGS]` are no longer blindly added to usage strings ([9b2e45b1](https://github.com/kbknapp/clap-rs/commit/9b2e45b170aff567b038d8b3368880b6046c10c6), closes [#537](https://github.com/kbknapp/clap-rs/issues/537)) +* **arg_enum!:** allows using meta items like repr(C) with arg_enum!s ([edf9b233](https://github.com/kbknapp/clap-rs/commit/edf9b2331c17a2cbcc13f961add4c55c2778e773), closes [#543](https://github.com/kbknapp/clap-rs/issues/543)) + + + + +## v2.6.0 (2016-06-14) + + +#### Improvements + +* removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115)) +* allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724)) +* removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589)) +* **Aliases:** improves readability of asliases in help messages ([ca511de7](https://github.com/kbknapp/clap-rs/commit/ca511de71f5b8c2ac419f1b188658e8c63b67846), closes [#526](https://github.com/kbknapp/clap-rs/issues/526), [#529](https://github.com/kbknapp/clap-rs/issues/529)) +* **Usage Strings:** improves the default usage string when only a single positional arg is present ([ec86f2da](https://github.com/kbknapp/clap-rs/commit/ec86f2dada1545a63fc72355e22fcdc4c466c215), closes [#518](https://github.com/kbknapp/clap-rs/issues/518)) + +#### Features + +* **Help:** allows wrapping at specified term width (Even on Windows!) ([1761dc0d](https://github.com/kbknapp/clap-rs/commit/1761dc0d27d0d621229d792be40c36fbf65c3014), closes [#451](https://github.com/kbknapp/clap-rs/issues/451)) +* **Settings:** + * adds new setting to stop delimiting values with -- or TrailingVarArg ([fc3e0f5a](https://github.com/kbknapp/clap-rs/commit/fc3e0f5afda6d24cdb3c4676614beebe13e1e870), closes [#511](https://github.com/kbknapp/clap-rs/issues/511)) + * one can now set an AppSetting which is propogated down through child subcommands ([e2341835](https://github.com/kbknapp/clap-rs/commit/e23418351a3b98bf08dfd7744bc14377c70d59ee), closes [#519](https://github.com/kbknapp/clap-rs/issues/519)) +* **Subcommands:** adds support for visible aliases ([7b10e7f8](https://github.com/kbknapp/clap-rs/commit/7b10e7f8937a07fdb8d16a6d8df79ce78d080cd3), closes [#522](https://github.com/kbknapp/clap-rs/issues/522)) + +#### Bug Fixes + +* fixes bug where args are printed out of order with templates ([05abb534](https://github.com/kbknapp/clap-rs/commit/05abb534864764102031a0d402e64ac65867aa87)) +* fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514)) +* fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106)) +* **Help:** `App::before_help` and `App::after_help` now correctly wrap ([1f4da767](https://github.com/kbknapp/clap-rs/commit/1f4da7676e6e71aa8dda799f3eeefad105a47819), closes [#516](https://github.com/kbknapp/clap-rs/issues/516)) +* **Settings:** fixes bug where new color settings couldn't be converted from strs ([706a7c11](https://github.com/kbknapp/clap-rs/commit/706a7c11b0900be594de6d5a3121938eff197602)) +* **Subcommands:** subcommands with aliases now display help of the aliased subcommand ([5354d14b](https://github.com/kbknapp/clap-rs/commit/5354d14b51f189885ba110e01e6b76cca3752992), closes [#521](https://github.com/kbknapp/clap-rs/issues/521)) +* **Windows:** fixes a failing windows build ([01e7dfd6](https://github.com/kbknapp/clap-rs/commit/01e7dfd6c07228c0be6695b3c7bf9370d82860d4)) +* **YAML:** adds missing YAML methods for App and Arg ([e468faf3](https://github.com/kbknapp/clap-rs/commit/e468faf3f05950fd9f72d84b69aa2061e91c6c64), closes [#528](https://github.com/kbknapp/clap-rs/issues/528)) + + + + +### v2.5.2 (2016-05-31) + + +#### Improvements + +* removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115)) +* allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724)) +* removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589)) + +#### Bug Fixes + +* fixes bug where args are printed out of order with templates ([3935431d](https://github.com/kbknapp/clap-rs/commit/3935431d5633f577c0826ae2142794b301f4b8ca)) +* fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514)) +* fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106)) + +#### Documentation + +* inter-links all types and pages ([3312893d](https://github.com/kbknapp/clap-rs/commit/3312893ddaef3f44d68d8d26ed3d08010be50d97), closes [#505](https://github.com/kbknapp/clap-rs/issues/505)) +* makes all publicly available types viewable in docs ([52ca6505](https://github.com/kbknapp/clap-rs/commit/52ca6505b4fec7b5c2d53d160c072d395eb21da6)) + + +### v2.5.1 (2016-05-11) + + +#### Bug Fixes + +* **Subcommand Aliases**: fixes lifetime issue when setting multiple aliases at once ([ac42f6cf0](https://github.com/kbknapp/clap-rs/commit/ac42f6cf0de6c4920f703807d63061803930b18d)) + + +## v2.5.0 (2016-05-10) + + +#### Improvements + +* **SubCommand Aliases:** adds feature to yaml configs too ([69592195](https://github.com/kbknapp/clap-rs/commit/695921954dde46dfd483399dcdef482c9dd7f34a)) + +#### Features + +* **SubCommands:** adds support for subcommand aliases ([66b4dea6](https://github.com/kbknapp/clap-rs/commit/66b4dea65c44d8f77ff522238a9237aed1bcab6d), closes [#469](https://github.com/kbknapp/clap-rs/issues/469)) + + + +### v2.4.3 (2016-05-10) + + +#### Bug Fixes + +* **Usage Strings:** + * now properly dedups args that are also in groups ([3ca0947c](https://github.com/kbknapp/clap-rs/commit/3ca0947c166b4f8525752255e3a4fa6565eb9689), closes [#498](https://github.com/kbknapp/clap-rs/issues/498)) + * removes duplicate groups from usage strings ([f574fb8a](https://github.com/kbknapp/clap-rs/commit/f574fb8a7cde4d4a2fa4c4481d59be2d0f135427)) + +#### Improvements + +* **Groups:** formats positional args in groups in a better way ([fef11154](https://github.com/kbknapp/clap-rs/commit/fef11154fb7430d1cbf04a672aabb366e456a368)) +* **Help:** + * moves positionals to standard <> formatting ([03dfe5ce](https://github.com/kbknapp/clap-rs/commit/03dfe5ceff1d63f172788ff688567ddad9fe119b)) + * default help subcommand string has been shortened ([5b7fe8e4](https://github.com/kbknapp/clap-rs/commit/5b7fe8e4161e43ab19e2e5fcf55fbe46791134e9), closes [#494](https://github.com/kbknapp/clap-rs/issues/494)) + + +### v2.4.3 (2016-05-10) + +* Ghost Release + + +### v2.4.3 (2016-05-10) + +* Ghost Release + + +## v2.4.0 (2016-05-02) + + +#### Features + +* **Help:** adds support for displaying info before help message ([29fbfa3b](https://github.com/kbknapp/clap-rs/commit/29fbfa3b963f2f3ca7704bf5d3e1201531baa373)) +* **Required:** adds allowing args that are required unless certain args are present ([af1f7916](https://github.com/kbknapp/clap-rs/commit/af1f79168390ea7da4074d0d9777de458ea64971)) + +#### Documentation + +* hides formatting from docs ([cb708093](https://github.com/kbknapp/clap-rs/commit/cb708093a7cd057f08c98b7bd1ed54c2db86ae7e)) +* **required_unless:** adds docs and examples for required_unless ([ca727b52](https://github.com/kbknapp/clap-rs/commit/ca727b52423b9883acd88b2f227b2711bc144573)) + +#### Bug Fixes + +* **Required Args:** fixes issue where missing required args are sometimes duplicatd in error messages ([3beebd81](https://github.com/kbknapp/clap-rs/commit/3beebd81e7bc2faa4115ac109cf570e512c5477f), closes [#492](https://github.com/kbknapp/clap-rs/issues/492)) + + + +## v2.3.0 (2016-04-18) + + +#### Improvements + +* **macros.rs:** Added write_nspaces macro (a new version of write_spaces) ([9d757e86](https://github.com/kbknapp/clap-rs/commit/9d757e8678e334e5a740ac750c76a9ed4e785cba)) +* **parser.rs:** + * Provide a way to create a usage string without the USAGE: title ([a91d378b](https://github.com/kbknapp/clap-rs/commit/a91d378ba0c91b5796457f8c6e881b13226ab735)) + * Make Parser's create_usage public allowing to have function outside the parser to generate the help ([d51945f8](https://github.com/kbknapp/clap-rs/commit/d51945f8b82ebb0963f4f40b384a9e8335783091)) + * Expose Parser's flags, opts and positionals argument as iterators ([9b23e7ee](https://github.com/kbknapp/clap-rs/commit/9b23e7ee40e51f7a823644c4496be955dc6c9d3a)) +* **src/args:** Exposes argument display order by introducing a new Trait ([1321630e](https://github.com/kbknapp/clap-rs/commit/1321630ef56955f152c73376d4d85cceb0bb4a12)) +* **srs/args:** Added longest_filter to AnyArg trait ([65b3f667](https://github.com/kbknapp/clap-rs/commit/65b3f667532685f854c699ddd264d326599cf7e5)) + +#### Features + +* **Authors Macro:** adds a crate_authors macro ([38fb59ab](https://github.com/kbknapp/clap-rs/commit/38fb59abf480eb2b6feca269097412f8b00b5b54), closes [#447](https://github.com/kbknapp/clap-rs/issues/447)) +* **HELP:** + * implements optional colored help messages ([abc8f669](https://github.com/kbknapp/clap-rs/commit/abc8f669c3c8193ffc3a3b0ac6c3ac2198794d4f), closes [#483](https://github.com/kbknapp/clap-rs/issues/483)) + * Add a Templated Help system. ([81e121ed](https://github.com/kbknapp/clap-rs/commit/81e121edd616f7285593f11120c63bcccae0d23e)) + +#### Bug Fixes + +* **HELP:** Adjust Help to semantic changes introduced in 6933b84 ([8d23806b](https://github.com/kbknapp/clap-rs/commit/8d23806bd67530ad412c34a1dcdcb1435555573d)) + + +### v2.2.6 (2016-04-11) + +#### Bug Fixes + +* **Arg Groups**: fixes bug where arg name isn't printed properly ([3019a685](https://github.com/kbknapp/clap-rs/commit/3019a685eee747ccbe6be09ad5dddce0b1d1d4db), closes [#476](https://github.com/kbknapp/clap-rs/issues/476)) + + + +### v2.2.5 (2016-04-03) + + +#### Bug Fixes + +* **Empty Values:** fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470)) +* **Help Message:** fixes bug where arg name is printed twice ([71acf1d5](https://github.com/kbknapp/clap-rs/commit/71acf1d576946658b8bbdb5ae79e6716c43a030f), closes [#472](https://github.com/kbknapp/clap-rs/issues/472)) + + + +### v2.2.4 (2016-03-30) + + +#### Bug Fixes + +* fixes compiling with debug cargo feature ([d4b55450](https://github.com/kbknapp/clap-rs/commit/d4b554509928031ac0808076178075bb21f8c1da)) +* **Empty Values:** fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470)) + + + + +### v2.2.3 (2016-03-28) + + +#### Bug Fixes + +* **Help Subcommand:** fixes issue where help and version flags weren't properly displayed ([205b07bf](https://github.com/kbknapp/clap-rs/commit/205b07bf2e6547851f1290f8cd6b169145e144f1), closes [#466](https://github.com/kbknapp/clap-rs/issues/466)) + + +### v2.2.2 (2016-03-27) + + +#### Bug Fixes + +* **Help Message:** fixes bug with wrapping in the middle of a unicode sequence ([05365ddc](https://github.com/kbknapp/clap-rs/commit/05365ddcc252e4b49e7a75e199d6001a430bd84d), closes [#456](https://github.com/kbknapp/clap-rs/issues/456)) +* **Usage Strings:** fixes small bug where -- would appear needlessly in usage strings ([6933b849](https://github.com/kbknapp/clap-rs/commit/6933b8491c2a7e28cdb61b47dcf10caf33c2f78a), closes [#461](https://github.com/kbknapp/clap-rs/issues/461)) + + + +### 2.2.1 (2016-03-16) + + +#### Features + +* **Help Message:** wraps and aligns the help message of subcommands ([813d75d0](https://github.com/kbknapp/clap-rs/commit/813d75d06fbf077c65762608c0fa5e941cfc393c), closes [#452](https://github.com/kbknapp/clap-rs/issues/452)) + +#### Bug Fixes + +* **Help Message:** fixes a bug where small terminal sizes causing a loop ([1d73b035](https://github.com/kbknapp/clap-rs/commit/1d73b0355236923aeaf6799abc759762ded7e1d0), closes [#453](https://github.com/kbknapp/clap-rs/issues/453)) + + + +## v2.2.0 (2016-03-15) + + +#### Features + +* **Help Message:** can auto wrap and aligning help text to term width ([e36af026](https://github.com/kbknapp/clap-rs/commit/e36af0266635f23e85e951b9088d561e9a5d1bf6), closes [#428](https://github.com/kbknapp/clap-rs/issues/428)) +* **Help Subcommand:** adds support passing additional subcommands to help subcommand ([2c12757b](https://github.com/kbknapp/clap-rs/commit/2c12757bbdf34ce481f3446c074e24c09c2e60fd), closes [#416](https://github.com/kbknapp/clap-rs/issues/416)) +* **Opts and Flags:** adds support for custom ordering in help messages ([9803b51e](https://github.com/kbknapp/clap-rs/commit/9803b51e799904c0befaac457418ee766ccc1ab9)) +* **Settings:** adds support for automatically deriving custom display order of args ([ad86e433](https://github.com/kbknapp/clap-rs/commit/ad86e43334c4f70e86909689a088fb87e26ff95a), closes [#444](https://github.com/kbknapp/clap-rs/issues/444)) +* **Subcommands:** adds support for custom ordering in help messages ([7d2a2ed4](https://github.com/kbknapp/clap-rs/commit/7d2a2ed413f5517d45988eef0765cdcd663b6372), closes [#442](https://github.com/kbknapp/clap-rs/issues/442)) + +#### Bug Fixes + +* **From Usage:** fixes a bug where adding empty lines werent ignored ([c5c58c86](https://github.com/kbknapp/clap-rs/commit/c5c58c86b9c503d8de19da356a5a5cffb59fbe84)) + +#### Documentation + +* **Groups:** explains required ArgGroups better ([4ff0205b](https://github.com/kbknapp/clap-rs/commit/4ff0205b85a45151b59bbaf090a89df13438380f), closes [#439](https://github.com/kbknapp/clap-rs/issues/439)) + + +### v2.1.2 (2016-02-24) + +#### Bug Fixes + +* **Nightly:** fixes failing nightly build ([d752c170](https://github.com/kbknapp/clap-rs/commit/d752c17029598b19037710f204b7943f0830ae75), closes [#434](https://github.com/kbknapp/clap-rs/issues/434)) + + + +### v2.1.1 (2016-02-19) + + +#### Documentation + +* **AppSettings:** clarifies that AppSettings do not propagate ([3c8db0e9](https://github.com/kbknapp/clap-rs/commit/3c8db0e9be1d24edaad364359513cbb02abb4186), closes [#429](https://github.com/kbknapp/clap-rs/issues/429)) +* **Arg Examples:** adds better examples ([1e79cccc](https://github.com/kbknapp/clap-rs/commit/1e79cccc12937bc0e7cd2aad8e404410798e9fff)) + +#### Improvements + +* **Help:** adds setting for next line help by arg ([066df748](https://github.com/kbknapp/clap-rs/commit/066df7486e684cf50a8479a356a12ba972c34ce1), closes [#427](https://github.com/kbknapp/clap-rs/issues/427)) + + + +## v2.1.0 (2016-02-10) + + +#### Features + +* **Defult Values:** adds support for default values in args ([73211952](https://github.com/kbknapp/clap-rs/commit/73211952964a79d97b434dd567e6d7d34be7feb5), closes [#418](https://github.com/kbknapp/clap-rs/issues/418)) + +#### Documentation + +* **Default Values:** adds better examples and notes for default values ([9facd74f](https://github.com/kbknapp/clap-rs/commit/9facd74f843ef3807c5d35259558a344e6c25905)) + + + +### v2.0.6 (2016-02-09) + + +#### Improvements + +* **Positional Arguments:** now displays value name if appropriate ([f0a99916](https://github.com/kbknapp/clap-rs/commit/f0a99916c59ce675515c6dcdfe9a40b130510908), closes [#420](https://github.com/kbknapp/clap-rs/issues/420)) + + + +### v2.0.5 (2016-02-05) + + +#### Bug Fixes + +* **Multiple Values:** fixes bug where number_of_values wasnt respected ([72c387da](https://github.com/kbknapp/clap-rs/commit/72c387da0bb8a6f526f863770f08bb8ca0d3de03)) + + + +### v2.0.4 (2016-02-04) + + +#### Bug Fixes + +* adds support for building ArgGroups from standalone YAML ([fcbc7e12](https://github.com/kbknapp/clap-rs/commit/fcbc7e12f5d7b023b8f30cba8cad28a01cf6cd26)) +* Stop lonely hyphens from causing panic ([85b11468](https://github.com/kbknapp/clap-rs/commit/85b11468b0189d5cc15f1cfac5db40d17a0077dc), closes [#410](https://github.com/kbknapp/clap-rs/issues/410)) +* **AppSettings:** fixes bug where subcmds didn't receive parent ver ([a62e4527](https://github.com/kbknapp/clap-rs/commit/a62e452754b3b0e3ac9a15aa8b5330636229ead1)) + + +### v2.0.3 (2016-02-02) + + +#### Improvements + +* **values:** adds support for up to u64::max values per arg ([c7abf7d7](https://github.com/kbknapp/clap-rs/commit/c7abf7d7611e317b0d31d97632e3d2e13570947c)) +* **occurrences:** Allow for more than 256 occurrences of an argument. ([3731ddb3](https://github.com/kbknapp/clap-rs/commit/3731ddb361163f3d6b86844362871e48c80fa530)) + +#### Features + +* **AppSettings:** adds HidePossibleValuesInHelp to skip writing those values ([cdee7a0e](https://github.com/kbknapp/clap-rs/commit/cdee7a0eb2beeec723cb98acfacf03bf629c1da3)) + +#### Bug Fixes + +* **value_t_or_exit:** fixes typo which causes value_t_or_exit to return a Result ([ee96baff](https://github.com/kbknapp/clap-rs/commit/ee96baffd306cb8d20ddc5575cf739bb1a6354e8)) + + + +### v2.0.2 (2016-01-31) + + +#### Improvements + +* **arg_enum:** enum declared with arg_enum returns [&'static str; #] instead of Vec ([9c4b8a1a](https://github.com/kbknapp/clap-rs/commit/9c4b8a1a6b12949222f17d1074578ad7676b9c0d)) + +#### Bug Fixes + +* clap_app! should be gated by unstable, not nightly feature ([0c8b84af](https://github.com/kbknapp/clap-rs/commit/0c8b84af6161d5baf683688eafc00874846f83fa)) +* **SubCommands:** fixed where subcmds weren't recognized after mult args ([c19c17a8](https://github.com/kbknapp/clap-rs/commit/c19c17a8850602990e24347aeb4427cf43316223), closes [#405](https://github.com/kbknapp/clap-rs/issues/405)) +* **Usage Parser:** fixes a bug where literal single quotes weren't allowed in help strings ([0bcc7120](https://github.com/kbknapp/clap-rs/commit/0bcc71206478074769e311479b34a9f74fe80f5c), closes [#406](https://github.com/kbknapp/clap-rs/issues/406)) + + + +### v2.0.1 (2016-01-30) + + +#### Bug Fixes + +* fixes cargo features to NOT require nightly with unstable features ([dcbcc60c](https://github.com/kbknapp/clap-rs/commit/dcbcc60c9ba17894be636472ea4b07a82d86a9db), closes [#402](https://github.com/kbknapp/clap-rs/issues/402)) + + + +## v2.0.0 (2016-01-28) + + +#### Improvements + +* **From Usage:** vastly improves the usage parser ([fa3a2f86](https://github.com/kbknapp/clap-rs/commit/fa3a2f86bd674c5eb07128c95098fab7d1437247), closes [#350](https://github.com/kbknapp/clap-rs/issues/350)) + +#### Features + +* adds support for external subcommands ([177fe5cc](https://github.com/kbknapp/clap-rs/commit/177fe5cce745c2164a8e38c23be4c4460d2d7211), closes [#372](https://github.com/kbknapp/clap-rs/issues/372)) +* adds support values with a leading hyphen ([e4d429b9](https://github.com/kbknapp/clap-rs/commit/e4d429b9d52e95197bd0b572d59efacecf305a59), closes [#385](https://github.com/kbknapp/clap-rs/issues/385)) +* adds support for turning off the value delimiter ([508db850](https://github.com/kbknapp/clap-rs/commit/508db850a87c2e251cf6b6ddead9ad56b29f9e57), closes [#352](https://github.com/kbknapp/clap-rs/issues/352)) +* adds support changing the value delimiter ([dafeae8a](https://github.com/kbknapp/clap-rs/commit/dafeae8a526162640f6a68da434370c64d190889), closes [#353](https://github.com/kbknapp/clap-rs/issues/353)) +* adds support for comma separated values ([e69da6af](https://github.com/kbknapp/clap-rs/commit/e69da6afcd2fe48a3c458ca031db40997f860eda), closes [#348](https://github.com/kbknapp/clap-rs/issues/348)) +* adds support with options with optional values ([4555736c](https://github.com/kbknapp/clap-rs/commit/4555736cad01441dcde4ea84a285227e0844c16e), closes [#367](https://github.com/kbknapp/clap-rs/issues/367)) +* **UTF-8:** adds support for invalid utf8 in values ([c5c59dec](https://github.com/kbknapp/clap-rs/commit/c5c59dec0bc33b86b2e99d30741336f17ec84282), closes [#269](https://github.com/kbknapp/clap-rs/issues/269)) +* **v2:** implementing the base of 2.x ([a3536054](https://github.com/kbknapp/clap-rs/commit/a3536054512ba833533dc56615ce3663d884381c)) + +#### Bug Fixes + +* fixes nightly build with new lints ([17599195](https://github.com/kbknapp/clap-rs/commit/175991956c37dc83ba9c49396e927a1cb65c5b11)) +* fixes Windows build for 2x release ([674c9b48](https://github.com/kbknapp/clap-rs/commit/674c9b48c7c92079cb180cc650a9e39f34781c32), closes [#392](https://github.com/kbknapp/clap-rs/issues/392)) +* fixes yaml build for 2x base ([adceae64](https://github.com/kbknapp/clap-rs/commit/adceae64c8556d00ab715677377b216f9f468ad7)) + +#### Documentation + +* updates examples for 2x release ([1303b360](https://github.com/kbknapp/clap-rs/commit/1303b3607468f362ab1b452d5614c1a064dc69b4), closes [#394](https://github.com/kbknapp/clap-rs/issues/394)) +* updates examples for 2x release ([0a011f31](https://github.com/kbknapp/clap-rs/commit/0a011f3142aec338d388a6c8bfe22fa7036021bb), closes [#394](https://github.com/kbknapp/clap-rs/issues/394)) +* updates documentation for v2 release ([8d51724e](https://github.com/kbknapp/clap-rs/commit/8d51724ef73dfde5bb94fb9466bc5463a1cc1502)) +* updating docs for 2x release ([576d0e0e](https://github.com/kbknapp/clap-rs/commit/576d0e0e2c7b8f386589179bbf7419b93abacf1c)) +* **README.md:** + * updates readme for v2 release ([acaba01a](https://github.com/kbknapp/clap-rs/commit/acaba01a353c12144b9cd9a3ce447400691849b0), closes [#393](https://github.com/kbknapp/clap-rs/issues/393)) + * fix typo and make documentation conspicuous ([07b9f614](https://github.com/kbknapp/clap-rs/commit/07b9f61495d927f69f7abe6c0d85253f0f4e6107)) + +#### BREAKING CHANGES + +* **Fewer liftimes! Yay!** + * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>` + * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>` + * `ArgMatches<'a, 'b>` => `ArgMatches<'a>` +* **Simply Renamed** + * `App::arg_group` => `App::group` + * `App::arg_groups` => `App::groups` + * `ArgGroup::add` => `ArgGroup::arg` + * `ArgGroup::add_all` => `ArgGroup::args` + * `ClapError` => `Error` + * struct field `ClapError::error_type` => `Error::kind` + * `ClapResult` => `Result` + * `ClapErrorType` => `ErrorKind` +* **Removed Deprecated Functions and Methods** + * `App::subcommands_negate_reqs` + * `App::subcommand_required` + * `App::arg_required_else_help` + * `App::global_version(bool)` + * `App::versionless_subcommands` + * `App::unified_help_messages` + * `App::wait_on_error` + * `App::subcommand_required_else_help` + * `SubCommand::new` + * `App::error_on_no_subcommand` + * `Arg::new` + * `Arg::mutually_excludes` + * `Arg::mutually_excludes_all` + * `Arg::mutually_overrides_with` + * `simple_enum!` +* **Renamed Error Variants** + * `InvalidUnicode` => `InvalidUtf8` + * `InvalidArgument` => `UnknownArgument` +* **Usage Parser** + * Value names can now be specified inline, i.e. `-o, --option 'some option which takes two files'` + * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code** +* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code) +* `crate_version!` returns `&'static str` instead of `String` +* Using the `clap_app!` macro requires compiling with the `unstable` feature because the syntax could change slightly in the future + + + +### v1.5.5 (2016-01-04) + + +#### Bug Fixes + +* fixes an issue where invalid short args didn't cause an error ([c9bf7e44](https://github.com/kbknapp/clap-rs/commit/c9bf7e4440bd2f9b524ea955311d433c40a7d1e0)) +* prints the name in version and help instead of binary name ([8f3817f6](https://github.com/kbknapp/clap-rs/commit/8f3817f665c0cab6726bc16c56a53b6a61e44448), closes [#368](https://github.com/kbknapp/clap-rs/issues/368)) +* fixes an intentional panic issue discovered via clippy ([ea83a3d4](https://github.com/kbknapp/clap-rs/commit/ea83a3d421ea8856d4cac763942834d108b71406)) + + + +### v1.5.4 (2015-12-18) + + +#### Examples + +* **17_yaml:** conditinonally compile 17_yaml example ([575de089](https://github.com/kbknapp/clap-rs/commit/575de089a3e240c398cb10e6cf5a5c6b68662c01)) + +#### Improvements + +* clippy improvements ([99cdebc2](https://github.com/kbknapp/clap-rs/commit/99cdebc23da3a45a165f14b27bebeb2ed828a2ce)) + +#### Bug Fixes + + +* **errors:** return correct error type in WrongNumValues error builder ([5ba8ba9d](https://github.com/kbknapp/clap-rs/commit/5ba8ba9dcccdfa74dd1c44260e64b359bbb36be6)) +* ArgRequiredElseHelp setting now takes precedence over missing required args ([faad83fb](https://github.com/kbknapp/clap-rs/commit/faad83fbef6752f3093b6e98fca09a9449b830f4), closes [#362](https://github.com/kbknapp/clap-rs/issues/362)) + + + +### v1.5.3 (2015-11-20) + + +#### Bug Fixes + +* **Errors:** fixes some instances when errors are missing a final newline ([c4d2b171](https://github.com/kbknapp/clap-rs/commit/c4d2b1711994479ad64ee52b6b49d2ceccbf2118)) + + + + + +### v1.5.2 (2015-11-14) + + +#### Bug Fixes + +* **Errors:** fixes a compiling bug when built on Windows or without the color feature ([a35f7634](https://github.com/kbknapp/clap-rs/commit/a35f76346fe6ecc88dda6a1eb13627186e7ce185)) + + + + +### v1.5.1 (2015-11-13) + + +#### Bug Fixes + +* **Required Args:** fixes a bug where required args are not correctly accounted for ([f03b88a9](https://github.com/kbknapp/clap-rs/commit/f03b88a9766b331a63879bcd747687f2e5a2661b), closes [#343](https://github.com/kbknapp/clap-rs/issues/343)) + + + + +## v1.5.0 (2015-11-13) + + +#### Bug Fixes + +* fixes a bug with required positional args in usage strings ([c6858f78](https://github.com/kbknapp/clap-rs/commit/c6858f78755f8e860204323c828c8355a066dc83)) + +#### Documentation + +* **FAQ:** updates readme with slight changes to FAQ ([a4ef0fab](https://github.com/kbknapp/clap-rs/commit/a4ef0fab73c8dc68f1b138965d1340459c113398)) + +#### Improvements + +* massive errors overhaul ([cdc29175](https://github.com/kbknapp/clap-rs/commit/cdc29175bc9c53e5b4aec86cbc04c1743154dae6)) +* **ArgMatcher:** huge refactor and deduplication of code ([8988853f](https://github.com/kbknapp/clap-rs/commit/8988853fb8825e8f841fde349834cc12cdbad081)) +* **Errors:** errors have been vastly improved ([e59bc0c1](https://github.com/kbknapp/clap-rs/commit/e59bc0c16046db156a88ba71a037db05028e995c)) +* **Traits:** refactoring some configuration into traits ([5800cdec](https://github.com/kbknapp/clap-rs/commit/5800cdec6dce3def4242b9f7bd136308afb19685)) + +#### Performance + +* **App:** + * more BTreeMap->Vec, Opts and SubCmds ([bc4495b3](https://github.com/kbknapp/clap-rs/commit/bc4495b32ec752b6c4b29719e831c043ef2a26ce)) + * changes flags BTreeMap->Vec ([d357640f](https://github.com/kbknapp/clap-rs/commit/d357640fab55e5964fe83efc3c771e53aa3222fd)) + * removed unneeded BTreeMap ([78971fd6](https://github.com/kbknapp/clap-rs/commit/78971fd68d7dc5c8e6811b4520cdc54e4188f733)) + * changes BTreeMap to VecMap in some instances ([64b921d0](https://github.com/kbknapp/clap-rs/commit/64b921d087fdd03775c95ba0bcf65d3f5d36f812)) + * removed excess clones ([ec0089d4](https://github.com/kbknapp/clap-rs/commit/ec0089d42ed715d293fb668d3a90b0db0aa3ec39)) + + + + +### v1.4.7 (2015-11-03) + + +#### Documentation + +* Clarify behavior of Arg::multiple with options. ([434f497a](https://github.com/kbknapp/clap-rs/commit/434f497ab6d831f8145cf09278c97ca6ee6c6fe7)) +* Fix typos and improve grammar. ([c1f66b5d](https://github.com/kbknapp/clap-rs/commit/c1f66b5de7b5269fbf8760a005ef8c645edd3229)) + +#### Bug Fixes + +* **Error Status:** fixes bug where --help and --version return non-zero exit code ([89b51fdf](https://github.com/kbknapp/clap-rs/commit/89b51fdf8b1ab67607567344e2317ff1a757cb12)) + + + + +### v1.4.6 (2015-10-29) + + +#### Features + +* allows parsing without a binary name for daemons and interactive CLIs ([aff89d57](https://github.com/kbknapp/clap-rs/commit/aff89d579b5b85c3dc81b64f16d5865299ec39a2), closes [#318](https://github.com/kbknapp/clap-rs/issues/318)) + +#### Bug Fixes + +* **Errors:** tones down quoting in some error messages ([34ce59ed](https://github.com/kbknapp/clap-rs/commit/34ce59ede53bfa2eef722c74881cdba7419fd9c7), closes [#309](https://github.com/kbknapp/clap-rs/issues/309)) +* **Help and Version:** only builds help and version once ([e3be87cf](https://github.com/kbknapp/clap-rs/commit/e3be87cfc095fc41c9811adcdc6d2b079f237d5e)) +* **Option Args:** fixes bug with args and multiple values ([c9a9548a](https://github.com/kbknapp/clap-rs/commit/c9a9548a8f96cef8a3dd9a980948325fbbc1b91b), closes [#323](https://github.com/kbknapp/clap-rs/issues/323)) +* **POSIX Overrides:** fixes bug where required args are overridden ([40ed2b50](https://github.com/kbknapp/clap-rs/commit/40ed2b50c3a9fe88bfdbaa43cef9fd6493ecaa8e)) +* **Safe Matches:** using 'safe' forms of the get_matches family no longer exit the process ([c47025dc](https://github.com/kbknapp/clap-rs/commit/c47025dca2b3305dea0a0acfdd741b09af0c0d05), closes [#256](https://github.com/kbknapp/clap-rs/issues/256)) +* **Versionless SubCommands:** fixes a bug where the -V flag was needlessly built ([27df8b9d](https://github.com/kbknapp/clap-rs/commit/27df8b9d98d13709dad3929a009f40ebff089a1a), closes [#329](https://github.com/kbknapp/clap-rs/issues/329)) + +#### Documentation + +* adds comparison in readme ([1a8bf31e](https://github.com/kbknapp/clap-rs/commit/1a8bf31e7a6b87ce48a66af2cde1645b2dd5bc95), closes [#325](https://github.com/kbknapp/clap-rs/issues/325)) + + + + +### v1.4.5 (2015-10-06) + + +#### Bug Fixes + +* fixes crash on invalid arg error ([c78ce128](https://github.com/kbknapp/clap-rs/commit/c78ce128ebbe7b8f730815f8176c29d76f4ade8c)) + + + + +### v1.4.4 (2015-10-06) + + +#### Documentation + +* clean up some formatting ([b7df92d7](https://github.com/kbknapp/clap-rs/commit/b7df92d7ea25835701dd22ddff984b9749f48a00)) +* move the crate-level docs to top of the lib.rs file ([d7233bf1](https://github.com/kbknapp/clap-rs/commit/d7233bf122dbf80ba8fc79e5641be2df8af10e7a)) +* changes doc comments to rustdoc comments ([34b601be](https://github.com/kbknapp/clap-rs/commit/34b601be5fdde76c1a0859385b359b96d66b8732)) +* fixes panic in 14_groups example ([945b00a0](https://github.com/kbknapp/clap-rs/commit/945b00a0c27714b63bdca48d003fe205fcfdc578), closes [#295](https://github.com/kbknapp/clap-rs/issues/295)) +* avoid suggesting star dependencies. ([d33228f4](https://github.com/kbknapp/clap-rs/commit/d33228f40b5fefb84cf3dd51546bfb340dcd9f5a)) +* **Rustdoc:** adds portions of the readme to main rustdoc page ([6f9ee181](https://github.com/kbknapp/clap-rs/commit/6f9ee181e69d90bd4206290e59d6f3f1e8f0cbb2), closes [#293](https://github.com/kbknapp/clap-rs/issues/293)) + +#### Bug Fixes + +* grammar error in some conflicting option errors ([e73b07e1](https://github.com/kbknapp/clap-rs/commit/e73b07e19474323ad2260da66abbf6a6d4ecbd4f)) +* **Unified Help:** sorts both flags and options as a unified category ([2a223dad](https://github.com/kbknapp/clap-rs/commit/2a223dad82901fa2e74baad3bfc4c7b94509300f)) +* **Usage:** fixes a bug where required args aren't filtered properly ([72b453dc](https://github.com/kbknapp/clap-rs/commit/72b453dc170af3050bb123d35364f6da77fc06d7), closes [#277](https://github.com/kbknapp/clap-rs/issues/277)) +* **Usage Strings:** fixes a bug ordering of elements in usage strings ([aaf0d6fe](https://github.com/kbknapp/clap-rs/commit/aaf0d6fe7aa2403e76096c16204d254a9ee61ee2), closes [#298](https://github.com/kbknapp/clap-rs/issues/298)) + +#### Features + +* supports -aValue style options ([0e3733e4](https://github.com/kbknapp/clap-rs/commit/0e3733e4fec2015c2d566a51432dcd92cb69cad3)) +* **Trailing VarArg:** adds opt-in setting for final arg being vararg ([27018b18](https://github.com/kbknapp/clap-rs/commit/27018b1821a4bcd5235cfe92abe71b3c99efc24d), closes [#278](https://github.com/kbknapp/clap-rs/issues/278)) + + + + +### v1.4.3 (2015-09-30) + + +#### Features + +* allows accessing arg values by group name ([c92a4b9e](https://github.com/kbknapp/clap-rs/commit/c92a4b9eff2d679957f61c0c41ff404b40d38a91)) + +#### Documentation + +* use links to examples instead of plain text ([bb4fe237](https://github.com/kbknapp/clap-rs/commit/bb4fe237858535627271465147add537e4556b43)) + +#### Bug Fixes + +* **Help Message:** required args no longer double list in usage ([1412e639](https://github.com/kbknapp/clap-rs/commit/1412e639e0a79df84936d1101a837f90077d1c83), closes [#277](https://github.com/kbknapp/clap-rs/issues/277)) +* **Possible Values:** possible value validation is restored ([f121ae74](https://github.com/kbknapp/clap-rs/commit/f121ae749f8f4bfe754ef2e8a6dfc286504b5b75), closes [#287](https://github.com/kbknapp/clap-rs/issues/287)) + + + + +### v1.4.2 (2015-09-23) + + +#### Bug Fixes + +* **Conflicts:** fixes bug with conflicts not removing required args ([e17fcec5](https://github.com/kbknapp/clap-rs/commit/e17fcec53b3216ad047a13dddc6f740473fad1a1), closes [#271](https://github.com/kbknapp/clap-rs/issues/271)) + + + + +### v1.4.1 (2015-09-22) + + +#### Examples + +* add clap_app quick example ([4ba6249c](https://github.com/kbknapp/clap-rs/commit/4ba6249c3cf4d2e083370d1fe4dcc7025282c28a)) + +#### Features + +* **Unicode:** allows non-panicing on invalid unicode characters ([c5bf7ddc](https://github.com/kbknapp/clap-rs/commit/c5bf7ddc8cfb876ec928a5aaf5591232bbb32e5d)) + +#### Documentation + +* properly names Examples section for rustdoc ([87ba5445](https://github.com/kbknapp/clap-rs/commit/87ba54451d7ec7b1c9b9ef134f90bbe39e6fac69)) +* fixes various typos and spelling ([f85640f9](https://github.com/kbknapp/clap-rs/commit/f85640f9f6d8fd3821a40e9b8b7a34fabb789d02)) +* **Arg:** unhides fields of the Arg struct ([931aea88](https://github.com/kbknapp/clap-rs/commit/931aea88427edf43a3da90d5a500c1ff2b2c3614)) + +#### Bug Fixes + +* flush the buffer in App::print_version() ([cbc42a37](https://github.com/kbknapp/clap-rs/commit/cbc42a37d212d84d22b1777d08e584ff191934e7)) +* Macro benchmarks ([13712da1](https://github.com/kbknapp/clap-rs/commit/13712da1d36dc7614eec3a10ad488257ba615751)) + + + + +## v1.4.0 (2015-09-09) + + +#### Features + +* allows printing help message by library consumers ([56b95f32](https://github.com/kbknapp/clap-rs/commit/56b95f320875c62dda82cb91b29059671e120ed1)) +* allows defining hidden args and subcmds ([2cab4d03](https://github.com/kbknapp/clap-rs/commit/2cab4d0334ea3c2439a1d4bfca5bf9905c7ea9ac), closes [#231](https://github.com/kbknapp/clap-rs/issues/231)) +* Builder macro to assist with App/Arg/Group/SubCommand building ([443841b0](https://github.com/kbknapp/clap-rs/commit/443841b012a8d795cd5c2bd69ae6e23ef9b16477)) +* **Errors:** allows consumers to write to stderr and exit on error ([1e6403b6](https://github.com/kbknapp/clap-rs/commit/1e6403b6a863574fa3cb6946b1fb58f034e8664c)) + + + + +### v1.3.2 (2015-09-08) + + +#### Documentation + +* fixed ErrorKind docs ([dd057843](https://github.com/kbknapp/clap-rs/commit/dd05784327fa070eb6ce5ce89a8507e011d8db94)) +* **ErrorKind:** changed examples content ([b9ca2616](https://github.com/kbknapp/clap-rs/commit/b9ca261634b89613bbf3d98fd74d55cefbb31a8c)) + +#### Bug Fixes + +* fixes a bug where the help subcommand wasn't overridable ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745)) + +#### Features + +* adds abiltiy not consume self when parsing matches and/or exit on help ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745)) +* **App:** Added ability for users to handle errors themselves ([934e6fbb](https://github.com/kbknapp/clap-rs/commit/934e6fbb643b2385efc23444fe6fce31494dc288)) + + + + +### v1.3.1 (2015-09-04) + + +#### Examples + +* **17_yaml:** fixed example ([9b848622](https://github.com/kbknapp/clap-rs/commit/9b848622296c8c5c7b9a39b93ddd41f51df790b5)) + +#### Performance + +* changes ArgGroup HashSets to Vec ([3cb4a48e](https://github.com/kbknapp/clap-rs/commit/3cb4a48ebd15c20692f4f3a2a924284dc7fd5e10)) +* changes BTreeSet for Vec in some instances ([baab2e3f](https://github.com/kbknapp/clap-rs/commit/baab2e3f4060e811abee14b1654cbcd5cf3b5fea)) + + + + +## v1.3.0 (2015-09-01) + + +#### Features + +* **YAML:** allows building a CLI from YAML files ([86cf4c45](https://github.com/kbknapp/clap-rs/commit/86cf4c45626a36b8115446952f9069f73c1debc3)) +* **ArgGroups:** adds support for building ArgGroups from yaml ([ecf88665](https://github.com/kbknapp/clap-rs/commit/ecf88665cbff367018b29161a1b75d44a212707d)) +* **Subcommands:** adds support for subcommands from yaml ([e415cf78](https://github.com/kbknapp/clap-rs/commit/e415cf78ba916052d118a8648deba2b9c16b1530)) + +#### Documentation + +* **YAML:** adds examples for using YAML to build a CLI ([ab41d7f3](https://github.com/kbknapp/clap-rs/commit/ab41d7f38219544750e6e1426076dc498073191b)) +* **Args from YAML:** fixes doc examples ([19b348a1](https://github.com/kbknapp/clap-rs/commit/19b348a10050404cd93888dbbbe4f396681b67d0)) +* **Examples:** adds better usage examples instead of having unused variables ([8cbacd88](https://github.com/kbknapp/clap-rs/commit/8cbacd8883004fe71a8ea036ec4391c7dd8efe94)) + +#### Examples + +* Add AppSettings example ([12705079](https://github.com/kbknapp/clap-rs/commit/12705079ca96a709b4dd94f7ddd20a833b26838c)) + +#### Bug Fixes + +* **Unified Help Messages:** fixes a crash from this setting and no opts ([169ffec1](https://github.com/kbknapp/clap-rs/commit/169ffec1003d58d105d7ef2585b3425e57980000), closes [#210](https://github.com/kbknapp/clap-rs/issues/210)) + + + + +### v1.2.5 (2015-08-27) + + +#### Examples + +* add custom validator example ([b9997d1f](https://github.com/kbknapp/clap-rs/commit/b9997d1fca74d4d8f93971f2a01bdf9798f913d5)) +* fix indentation ([d4f1b740](https://github.com/kbknapp/clap-rs/commit/d4f1b740ede410fd2528b9ecd89592c2fd8b1e20)) + +#### Features + +* **Args:** allows opts and args to define a name for help and usage msgs ([ad962ec4](https://github.com/kbknapp/clap-rs/commit/ad962ec478da999c7dba0afdb84c266f4d09b1bd)) + + + + +### v1.2.4 (2015-08-26) + + +#### Bug Fixes + +* **Possible Values:** fixes a bug where suggestions arent made when using --long=value format ([3d5e9a6c](https://github.com/kbknapp/clap-rs/commit/3d5e9a6cedb26668839b481c9978e2fbbab8be6f), closes [#192](https://github.com/kbknapp/clap-rs/issues/192)) + + + + +### v1.2.3 (2015-08-24) + + +#### Bug Fixes + +* **App, Args:** fixed subcommand reqs negation ([b41afa8c](https://github.com/kbknapp/clap-rs/commit/b41afa8c3ded3d1be12f7a2f8ea06cc44afc9458), closes [#188](https://github.com/kbknapp/clap-rs/issues/188)) + + + + +### v1.2.2 (2015-08-23) + + +#### Bug Fixes + +* fixed confusing error message, also added test for it ([fc7a31a7](https://github.com/kbknapp/clap-rs/commit/fc7a31a745efbf1768ee2c62cd3bb72bfe30c708)) +* **App:** fixed requirmets overriding ([9c135eb7](https://github.com/kbknapp/clap-rs/commit/9c135eb790fa16183e5bdb2009ddc3cf9e25f99f)) + + + + +### v1.2.1 (2015-08-20) + + +#### Documentation + +* **README.md:** updates for new features ([16cf9245](https://github.com/kbknapp/clap-rs/commit/16cf9245fb5fc4cf6face898e358368bf9961cbb)) + +#### Features + +* implements posix compatible conflicts for long args ([8c2d48ac](https://github.com/kbknapp/clap-rs/commit/8c2d48acf5473feebd721a9049a9c9b7051e70f9)) +* added overrides to support conflicts in POSIX compatible manner ([0b916a00](https://github.com/kbknapp/clap-rs/commit/0b916a00de26f6941538f6bc5f3365fa302083c1)) +* **Args:** allows defining POSIX compatible argument conflicts ([d715646e](https://github.com/kbknapp/clap-rs/commit/d715646e69759ccd95e01f49b04f489827ecf502)) + +#### Bug Fixes + +* fixed links in cargo and license buttons ([6d9837ad](https://github.com/kbknapp/clap-rs/commit/6d9837ad9a9e006117cd7372fdc60f9a3889c7e2)) + +#### Performance + +* **Args and Apps:** changes HashSet->Vec in some instances for increased performance ([d0c3b379](https://github.com/kbknapp/clap-rs/commit/d0c3b379700757e0a9b0c40af709f8af1f5b4949)) + + + + +### v1.2.0 (2015-08-15) + + +#### Bug Fixes + +* fixed misspell and enum name ([7df170d7](https://github.com/kbknapp/clap-rs/commit/7df170d7f4ecff06608317655d1e0c4298f62076)) +* fixed use for clap crate ([dc3ada73](https://github.com/kbknapp/clap-rs/commit/dc3ada738667d4b689678f79d14251ee82004ece)) + +#### Documentation + +* updates docs for new features ([03496547](https://github.com/kbknapp/clap-rs/commit/034965471782d872ca495045b58d34b31807c5b1)) +* fixed docs for previous changes ([ade36778](https://github.com/kbknapp/clap-rs/commit/ade367780c366425de462506d256e0f554ed3b9c)) + +#### Improvements + +* **AppSettings:** adds ability to add multiple settings at once ([4a00e251](https://github.com/kbknapp/clap-rs/commit/4a00e2510d0ca8d095d5257d51691ba3b61c1374)) + +#### Features + +* Replace application level settings with enum variants ([618dc4e2](https://github.com/kbknapp/clap-rs/commit/618dc4e2c205bf26bc43146164e65eb1f6b920ed)) +* **Args:** allows for custom argument value validations to be defined ([84ae2ddb](https://github.com/kbknapp/clap-rs/commit/84ae2ddbceda34b5cbda98a6959edaa52fde2e1a), closes [#170](https://github.com/kbknapp/clap-rs/issues/170)) + + + + +### v1.1.6 (2015-08-01) + + +#### Bug Fixes + +* fixes two bugs in App when printing newlines in help and subcommands required error ([d63c0136](https://github.com/kbknapp/clap-rs/commit/d63c0136310db9dd2b1c7b4745938311601d8938)) + + + + +### v1.1.5 (2015-07-29) + +#### Performance + +* removes some unneeded allocations ([93e915df](https://github.com/kbknapp/clap-rs/commit/93e915dfe300f7b7d6209ca93323c6a46f89a8c1)) + + +### v1.1.4 (2015-07-20) + + +#### Improvements + +* **Usage Strings** displays a [--] when it may be helpful ([86c3be85](https://github.com/kbknapp/clap-rs/commit/86c3be85fb6f77f83b5a6d2df40ae60937486984)) + +#### Bug Fixes + +* **Macros** fixes a typo in a macro generated error message ([c9195c5f](https://github.com/kbknapp/clap-rs/commit/c9195c5f92abb8cd6a37b4f4fbb2f1fee2a8e368)) +* **Type Errors** fixes formatting of error output when failed type parsing ([fe5d95c6](https://github.com/kbknapp/clap-rs/commit/fe5d95c64f3296e6eddcbec0cb8b86659800145f)) + + + + +### v1.1.3 (2015-07-18) + + +#### Documentation + +* updates README.md to include lack of color support on Windows ([52f81e17](https://github.com/kbknapp/clap-rs/commit/52f81e17377b18d2bd0f34693b642b7f358998ee)) + +#### Bug Fixes + +* fixes formatting bug which prevented compiling on windows ([9cb5dceb](https://github.com/kbknapp/clap-rs/commit/9cb5dceb3e5fe5e0e7b24619ff77e5040672b723), closes [#163](https://github.com/kbknapp/clap-rs/issues/163)) + + + + +### v1.1.2 (2015-07-17) + + +#### Bug Fixes + +* fixes a bug when parsing multiple {n} newlines inside help strings ([6d214b54](https://github.com/kbknapp/clap-rs/commit/6d214b549a9b7e189a94e5fa2b7c92cc333ca637)) + + + + +## v1.1.1 (2015-07-17) + + +#### Bug Fixes + +* fixes a logic bug and allows setting Arg::number_of_values() < 2 ([42b6d1fc](https://github.com/kbknapp/clap-rs/commit/42b6d1fc3c519c92dfb3af15276e7d3b635e6cfe), closes [#161](https://github.com/kbknapp/clap-rs/issues/161)) + + + + +## v1.1.0 (2015-07-16) + + +#### Features + +* allows creating unified help messages, a la docopt or getopts ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1), closes [#158](https://github.com/kbknapp/clap-rs/issues/158)) +* allows stating all subcommands should *not* have --version flags ([336c476f](https://github.com/kbknapp/clap-rs/commit/336c476f631d512b54ac56fdca6f29ebdc2c00c5), closes [#156](https://github.com/kbknapp/clap-rs/issues/156)) +* allows setting version number to auto-propagate through subcommands ([bc66d3c6](https://github.com/kbknapp/clap-rs/commit/bc66d3c6deedeca62463fff95369ab1cfcdd366b), closes [#157](https://github.com/kbknapp/clap-rs/issues/157)) + +#### Improvements + +* **Help Strings** properly aligns and handles newlines in long help strings ([f9800a29](https://github.com/kbknapp/clap-rs/commit/f9800a29696dd2cc0b0284bf693b3011831e556f), closes [#145](https://github.com/kbknapp/clap-rs/issues/145)) + + +#### Performance + +* **Help Messages** big performance improvements when printing help messages ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1)) + +#### Documentation + +* updates readme with new features ([8232f7bb](https://github.com/kbknapp/clap-rs/commit/8232f7bb52e88862bc13c3d4f99ee4f56cfe4bc0)) +* fix incorrect code example for `App::subcommand_required` ([8889689d](https://github.com/kbknapp/clap-rs/commit/8889689dc6336ccc45b2c9f2cf8e2e483a639e93)) + + + +### v1.0.3 (2015-07-11) + + +#### Improvements + +* **Errors** writes errors to stderr ([cc76ab8c](https://github.com/kbknapp/clap-rs/commit/cc76ab8c2b77c67b42f4717ded530df7806142cf), closes [#154](https://github.com/kbknapp/clap-rs/issues/154)) + +#### Documentation + +* **README.md** updates example help message to new format ([0aca29bd](https://github.com/kbknapp/clap-rs/commit/0aca29bd5d6d1a4e9971bdc88d946ffa58606efa)) + + + + +### v1.0.2 (2015-07-09) + + +#### Improvements + +* **Usage** re-orders optional arguments and required to natural standard ([dc7e1fce](https://github.com/kbknapp/clap-rs/commit/dc7e1fcea5c85d317018fb201d2a9262249131b4), closes [#147](https://github.com/kbknapp/clap-rs/issues/147)) + + + + +### v1.0.1 (2015-07-08) + + +#### Bug Fixes + +* allows empty values when using --long='' syntax ([083f82d3](https://github.com/kbknapp/clap-rs/commit/083f82d333b69720a6ef30074875310921d964d1), closes [#151](https://github.com/kbknapp/clap-rs/issues/151)) + + + + +## v1.0.0 (2015-07-08) + + +#### Documentation + +* **README.md** adds new features to what's new list ([938f7f01](https://github.com/kbknapp/clap-rs/commit/938f7f01340f521969376cf4e2e3d9436bca21f7)) +* **README.md** use with_name for subcommands ([28b7e316](https://github.com/kbknapp/clap-rs/commit/28b7e3161fb772e5309042648fe8c3a420645bac)) + +#### Features + +* args can now be parsed from arbitrary locations, not just std::env::args() ([75312528](https://github.com/kbknapp/clap-rs/commit/753125282b1b9bfff875f1557ce27610edcc59e1)) + + + + +## v1.0.0-beta (2015-06-30) + + +#### Features + +* allows waiting for user input on error ([d0da3bdd](https://github.com/kbknapp/clap-rs/commit/d0da3bdd9d1871541907ea9c645322a74d260e07), closes [#140](https://github.com/kbknapp/clap-rs/issues/140)) +* **Help** allows one to fully override the auto-generated help message ([26d5ae3e](https://github.com/kbknapp/clap-rs/commit/26d5ae3e330d1e150811d5b60b2b01a8f8df854e), closes [#141](https://github.com/kbknapp/clap-rs/issues/141)) + +#### Documentation + +* adds "whats new" section to readme ([ff149a29](https://github.com/kbknapp/clap-rs/commit/ff149a29dd9e179865e6d577cd7dc87c54f8f95c)) + +#### Improvements + +* removes deprecated functions in prep for 1.0 ([274484df](https://github.com/kbknapp/clap-rs/commit/274484dfd08fff4859cefd7e9bef3b73d3a9cb5f)) + + + + +## v0.11.0 (2015-06-17) - BREAKING CHANGE + + +#### Documentation + +* updates docs to new version flag defaults ([ebf442eb](https://github.com/kbknapp/clap-rs/commit/ebf442ebebbcd2ec6bfe2c06566c9d362bccb112)) + +#### Features + +* **Help and Version** default short for version is now `-V` but can be overridden (only breaks manual documentation) (**BREAKING CHANGE** [eb1d9320](https://github.com/kbknapp/clap-rs/commit/eb1d9320c509c1e4e57d7c7959da82bcfe06ada0)) + + + + +### v0.10.5 (2015-06-06) + + +#### Bug Fixes + +* **Global Args** global arguments propogate fully now ([1f377960](https://github.com/kbknapp/clap-rs/commit/1f377960a48c82f54ca5f39eb56bcb393140b046), closes [#137](https://github.com/kbknapp/clap-rs/issues/137)) + + + + +### v0.10.4 (2015-06-06) + + +#### Bug Fixes + +* **Global Args** global arguments propogate fully now ([8f2c0160](https://github.com/kbknapp/clap-rs/commit/8f2c0160c8d844daef375a33dbaec7d89de00a00), closes [#137](https://github.com/kbknapp/clap-rs/issues/137)) + + + + +### v0.10.3 (2015-05-31) + + +#### Bug Fixes + +* **Global Args** fixes a bug where globals only transfer to one subcommand ([a37842ee](https://github.com/kbknapp/clap-rs/commit/a37842eec1ee3162b86fdbda23420b221cdb1e3b), closes [#135](https://github.com/kbknapp/clap-rs/issues/135)) + + + + +### v0.10.2 (2015-05-30) + + +#### Improvements + +* **Binary Names** allows users to override the system determined bin name ([2191fe94](https://github.com/kbknapp/clap-rs/commit/2191fe94bda35771383b52872fb7f5421b178be1), closes [#134](https://github.com/kbknapp/clap-rs/issues/134)) + +#### Documentation + +* adds contributing guidelines ([6f76bd0a](https://github.com/kbknapp/clap-rs/commit/6f76bd0a07e8b7419b391243ab2d6687cd8a9c5f)) + + + + +### v0.10.1 (2015-05-26) + + +#### Features + +* can now specify that an app or subcommand should display help on no args or subcommands ([29ca7b2f](https://github.com/kbknapp/clap-rs/commit/29ca7b2f74376ca0cdb9d8ee3bfa99f7640cc404), closes [#133](https://github.com/kbknapp/clap-rs/issues/133)) + + + + +## v0.10.0 (2015-05-23) + + +#### Features + +* **Global Args** allows args that propagate down to child commands ([2bcc6137](https://github.com/kbknapp/clap-rs/commit/2bcc6137a83cb07757771a0afea953e68e692f0b), closes [#131](https://github.com/kbknapp/clap-rs/issues/131)) + +#### Improvements + +* **Colors** implements more structured colored output ([d6c3ed54](https://github.com/kbknapp/clap-rs/commit/d6c3ed54d21cf7b40d9f130d4280ff5448522fc5), closes [#129](https://github.com/kbknapp/clap-rs/issues/129)) + +#### Deprecations + +* **SubCommand/App** several methods and functions for stable release ([28b73855](https://github.com/kbknapp/clap-rs/commit/28b73855523ad170544afdb20665db98702fbe70)) + +#### Documentation + +* updates for deprecations and new features ([743eefe8](https://github.com/kbknapp/clap-rs/commit/743eefe8dd40c1260065ce086d572e9e9358bc4c)) + + + + +## v0.9.2 (2015-05-20) + + +#### Bug Fixes + +* **help** allows parent requirements to be ignored with help and version ([52218cc1](https://github.com/kbknapp/clap-rs/commit/52218cc1fdb06a42456c964d98cc2c7ac3432412), closes [#124](https://github.com/kbknapp/clap-rs/issues/124)) + + + + +## v0.9.1 (2015-05-18) + + +#### Bug Fixes + +* **help** fixes a bug where requirements are included as program name in help and version ([08ba3f25](https://github.com/kbknapp/clap-rs/commit/08ba3f25cf38b149229ba8b9cb37a5804fe6b789)) + + + + +## v0.9.0 (2015-05-17) + + +#### Improvements + +* **usage** usage strings now include parent command requirements ([dd8f21c7](https://github.com/kbknapp/clap-rs/commit/dd8f21c7c15cde348fdcf44fa7c205f0e98d2e4a), closes [#125](https://github.com/kbknapp/clap-rs/issues/125)) +* **args** allows consumer of clap to decide if empty values are allowed or not ([ab4ec609](https://github.com/kbknapp/clap-rs/commit/ab4ec609ccf692b9b72cccef5c9f74f5577e360d), closes [#122](https://github.com/kbknapp/clap-rs/issues/122)) + +#### Features + +* **subcommands** + * allows optionally specifying that no subcommand is an error ([7554f238](https://github.com/kbknapp/clap-rs/commit/7554f238fd3afdd60b7e4dcf00ff4a9eccf842c1), closes [#126](https://github.com/kbknapp/clap-rs/issues/126)) + * subcommands can optionally negate parent requirements ([4a4229f5](https://github.com/kbknapp/clap-rs/commit/4a4229f500e21c350e1ef78dd09ef27559653288), closes [#123](https://github.com/kbknapp/clap-rs/issues/123)) + + + + +## v0.8.6 (2015-05-17) + + +#### Bug Fixes + +* **args** `-` can now be parsed as a value for an argument ([bc12e78e](https://github.com/kbknapp/clap-rs/commit/bc12e78eadd7eaf9d008a8469fdd2dfd7990cb5d), closes [#121](https://github.com/kbknapp/clap-rs/issues/121)) + + + + +## v0.8.5 (2015-05-15) + + +#### Bug Fixes + +* **macros** makes macro errors consistent with others ([0c264a8c](https://github.com/kbknapp/clap-rs/commit/0c264a8ca57ec1cfdcb74dae79145d766cdc9b97), closes [#118](https://github.com/kbknapp/clap-rs/issues/118)) + +#### Features + +* **macros** + * arg_enum! and simple_enum! provide a Vec<&str> of variant names ([30fa87ba](https://github.com/kbknapp/clap-rs/commit/30fa87ba4e0f3189351d8f4f78b72e616a30d0bd), closes [#119](https://github.com/kbknapp/clap-rs/issues/119)) + * arg_enum! and simple_enum! auto-implement Display ([d1219f0d](https://github.com/kbknapp/clap-rs/commit/d1219f0d1371d872061bd0718057eca4ef47b739), closes [#120](https://github.com/kbknapp/clap-rs/issues/120)) + + + + +## v0.8.4 (2015-05-12) + + +#### Bug Fixes + +* **suggestions** --help and --version now get suggestions ([d2b3b1fa](https://github.com/kbknapp/clap-rs/commit/d2b3b1faa0bdc1c5d2350cc4635aba81e02e9d96), closes [#116](https://github.com/kbknapp/clap-rs/issues/116)) + + + + +## v0.8.3 (2015-05-10) + + +#### Bug Fixes + +* **usage** groups unfold their members in usage strings ([55d15582](https://github.com/kbknapp/clap-rs/commit/55d155827ea4a6b077a83669701e797ce1ad68f4), closes [#114](https://github.com/kbknapp/clap-rs/issues/114)) + +#### Performance + +* **usage** removes unneeded allocations ([fd53cd18](https://github.com/kbknapp/clap-rs/commit/fd53cd188555f5c3dc8bc341c5d7eb04b761a70f)) + + + + +## v0.8.2 (2015-05-08) + + +#### Bug Fixes + +* **usage strings** positional arguments are presented in index order ([eb0e374e](https://github.com/kbknapp/clap-rs/commit/eb0e374ecf952f1eefbc73113f21e0705936e40b), closes [#112](https://github.com/kbknapp/clap-rs/issues/112)) + + + + +## v0.8.1 (2015-05-06) + + +#### Bug Fixes + +* **subcommands** stops parsing multiple values when subcommands are found ([fc79017e](https://github.com/kbknapp/clap-rs/commit/fc79017eced04fd41cc1801331e5054df41fac17), closes [#109](https://github.com/kbknapp/clap-rs/issues/109)) + +#### Improvements + +* **color** reduces color in error messages ([aab44cca](https://github.com/kbknapp/clap-rs/commit/aab44cca6352f47e280c296e50c535f5d752dd46), closes [#110](https://github.com/kbknapp/clap-rs/issues/110)) +* **suggestions** adds suggested arguments to usage strings ([99447414](https://github.com/kbknapp/clap-rs/commit/994474146e9fb8b701af773a52da71553d74d4b7)) + + + + +## v0.8.0 (2015-05-06) + + +#### Bug Fixes + +* **did-you-mean** for review ([0535cfb0](https://github.com/kbknapp/clap-rs/commit/0535cfb0c711331568b4de8080eeef80bd254b68)) +* **Positional** positionals were ignored if they matched a subcmd, even after '--' ([90e7b081](https://github.com/kbknapp/clap-rs/commit/90e7b0818741668b47cbe3becd029bab588e3553)) +* **help** fixes bug where space between arg and help is too long ([632fb115](https://github.com/kbknapp/clap-rs/commit/632fb11514c504999ea86bdce47cdd34f8ebf646)) + +#### Features + +* **from_usage** adds ability to add value names or num of vals in usage string ([3d581976](https://github.com/kbknapp/clap-rs/commit/3d58197674ed7886ca315efb76e411608a327501), closes [#98](https://github.com/kbknapp/clap-rs/issues/98)) +* **did-you-mean** + * gate it behind 'suggestions' ([c0e38351](https://github.com/kbknapp/clap-rs/commit/c0e383515d01bdd5ca459af9c2f7e2cf49e2488b)) + * for possible values ([1cc2deb2](https://github.com/kbknapp/clap-rs/commit/1cc2deb29158e0e4e8b434e4ce26b3d819301a7d)) + * for long flags (i.e. --long) ([52a0b850](https://github.com/kbknapp/clap-rs/commit/52a0b8505c99354bdf5fd1cd256cf41197ac2d81)) + * for subcommands ([06e869b5](https://github.com/kbknapp/clap-rs/commit/06e869b5180258047ed3c60ba099de818dd25fff)) +* **Flags** adds sugestions functionality ([8745071c](https://github.com/kbknapp/clap-rs/commit/8745071c3257dd327c497013516f12a823df9530)) +* **errors** colorizes output red on error ([f8b26b13](https://github.com/kbknapp/clap-rs/commit/f8b26b13da82ba3ba9a932d3d1ab4ea45d1ab036)) + +#### Improvements + +* **arg_enum** allows ascii case insensitivity for enum variants ([b249f965](https://github.com/kbknapp/clap-rs/commit/b249f9657c6921c004764bd80d13ebca81585eec), closes [#104](https://github.com/kbknapp/clap-rs/issues/104)) +* **clap-test** simplified `make test` invocation ([d17dcb29](https://github.com/kbknapp/clap-rs/commit/d17dcb2920637a1f58c61c596b7bd362fd53047c)) + +#### Documentation + +* **README** adds details about optional and new features ([960389de](https://github.com/kbknapp/clap-rs/commit/960389de02c9872aaee9adabe86987f71f986e39)) +* **clap** fix typos caught by codespell ([8891d929](https://github.com/kbknapp/clap-rs/commit/8891d92917aa1a069cca67272be41b99e548356e)) +* **from_usage** explains new usage strings with multiple values ([05476fc6](https://github.com/kbknapp/clap-rs/commit/05476fc61cd1e5f4a4e750d258c878732a3a9c64)) + + + + +## v0.7.6 (2015-05-05) + + +#### Improvements + +* **Options** adds number of values to options in help/usage ([c1c993c4](https://github.com/kbknapp/clap-rs/commit/c1c993c419d18e35c443785053d8de9a2ef88073)) + +#### Features + +* **from_usage** adds ability to add value names or num of vals in usage string ([ad55748c](https://github.com/kbknapp/clap-rs/commit/ad55748c265cf27935c7b210307d2040b6a09125), closes [#98](https://github.com/kbknapp/clap-rs/issues/98)) + +#### Bug Fixes + +* **MultipleValues** properly distinguishes between multiple values and multiple occurrences ([dd2a7564](https://github.com/kbknapp/clap-rs/commit/dd2a75640ca68a91b973faad15f04df891356cef), closes [#99](https://github.com/kbknapp/clap-rs/issues/99)) +* **help** fixes tab alignment with multiple values ([847001ff](https://github.com/kbknapp/clap-rs/commit/847001ff6d8f4d9518e810fefb8edf746dd0f31e)) + +#### Documentation + +* **from_usage** explains new usage strings with multiple values ([5a3a42df](https://github.com/kbknapp/clap-rs/commit/5a3a42dfa3a783537f88dedc0fd5f0edcb8ea372)) + + + + +## v0.7.5 (2015-05-04) + + +#### Bug Fixes + +* **Options** fixes bug where options with no value don't error out ([a1fb94be](https://github.com/kbknapp/clap-rs/commit/a1fb94be53141572ffd97aad037295d4ffec82d0)) + + + + +## v0.7.4 (2015-05-03) + + +#### Bug Fixes + +* **Options** fixes a bug where option arguments in succession get their values skipped ([f66334d0](https://github.com/kbknapp/clap-rs/commit/f66334d0ce984e2b56e5c19abb1dd536fae9342a)) + + + + +## v0.7.3 (2015-05-03) + + +#### Bug Fixes + +* **RequiredValues** fixes a bug where missing values are parsed as missing arguments ([93c4a723](https://github.com/kbknapp/clap-rs/commit/93c4a7231ba1a08152648598f7aa4503ea82e4de)) + +#### Improvements + +* **ErrorMessages** improves error messages and corrections ([a29c3983](https://github.com/kbknapp/clap-rs/commit/a29c3983c4229906655a29146ec15a0e46dd942d)) +* **ArgGroups** improves requirement and confliction support for groups ([c236dc5f](https://github.com/kbknapp/clap-rs/commit/c236dc5ff475110d2a1b80e62903f80296163ad3)) + + + + +## v0.7.2 (2015-05-03) + + +#### Bug Fixes + +* **RequiredArgs** fixes bug where required-by-default arguments are not listed in usage ([12aea961](https://github.com/kbknapp/clap-rs/commit/12aea9612d290845ba86515c240aeeb0a21198db), closes [#96](https://github.com/kbknapp/clap-rs/issues/96)) + + + + +## v0.7.1 (2015-05-01) + + +#### Bug Fixes + +* **MultipleValues** stops evaluating values if the max or exact number of values was reached ([86d92c9f](https://github.com/kbknapp/clap-rs/commit/86d92c9fdbf9f422442e9562977bbaf268dbbae1)) + + + + +## v0.7.0 (2015-04-30) - BREAKING CHANGE + + +#### Bug Fixes + +* **from_usage** removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83)) + +#### Features + +* **MultipleValues** + * add support for minimum and maximum number of values ([53f6b8c9](https://github.com/kbknapp/clap-rs/commit/53f6b8c9d8dc408b4fa9f833fc3a63683873c42f)) + * adds support limited number and named values ([ae09f05e](https://github.com/kbknapp/clap-rs/commit/ae09f05e92251c1b39a83d372736fcc7b504e432)) + * implement shorthand for options with multiple values ([6669f0a9](https://github.com/kbknapp/clap-rs/commit/6669f0a9687d4f668523145d7bd5c007d1eb59a8)) +* **arg** allow other types besides Vec for multiple value settings (**BREAKING CHANGE** [0cc2f698](https://github.com/kbknapp/clap-rs/commit/0cc2f69839b9b1db5d06330771b494783049a88e), closes [#87](https://github.com/kbknapp/clap-rs/issues/87)) +* **usage** implement smart usage strings on errors ([d77048ef](https://github.com/kbknapp/clap-rs/commit/d77048efb1e595ffe831f1a2bea2f2700db53b9f), closes [#88](https://github.com/kbknapp/clap-rs/issues/88)) + + + + +## v0.6.9 (2015-04-29) + + +#### Bug Fixes + +* **from_usage** removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83)) + + + + +## 0.6.8 (2015-04-27) + + +#### Bug Fixes + +* **help** change long help --long=long -> --long ([1e25abfc](https://github.com/kbknapp/clap-rs/commit/1e25abfc36679ab89eae71bf98ced4de81992d00)) +* **RequiredArgs** required by default args should no longer be required when their exclusions are present ([4bb4c3cc](https://github.com/kbknapp/clap-rs/commit/4bb4c3cc076b49e86720e882bf8c489877199f2d)) + +#### Features + +* **ArgGroups** add ability to create arg groups ([09eb4d98](https://github.com/kbknapp/clap-rs/commit/09eb4d9893af40c347e50e2b717e1adef552357d)) + + + + +## v0.6.7 (2015-04-22) + + +#### Bug Fixes + +* **from_usage** fix bug causing args to not be required ([b76129e9](https://github.com/kbknapp/clap-rs/commit/b76129e9b71a63365d5c77a7f57b58dbd1e94d49)) + +#### Features + +* **apps** add ability to display additional help info after auto-gen'ed help msg ([65cc259e](https://github.com/kbknapp/clap-rs/commit/65cc259e4559cbe3653c865ec0c4b1e42a389b07)) + + + + +## v0.6.6 (2015-04-19) + + +#### Bug Fixes + +* **from_usage** tabs and spaces should be treated equally ([4fd44181](https://github.com/kbknapp/clap-rs/commit/4fd44181d55d8eb88caab1e625231cfa3129e347)) + +#### Features + +* **macros.rs** add macro to get version from Cargo.toml ([c630969a](https://github.com/kbknapp/clap-rs/commit/c630969aa3bbd386379219cae27ba1305b117f3e)) + + + + +## v0.6.5 (2015-04-19) + + +#### Bug Fixes + +* **macros.rs** fix use statements for trait impls ([86e4075e](https://github.com/kbknapp/clap-rs/commit/86e4075eb111937c8a7bdb344e866e350429f042)) + + + + +## v0.6.4 (2015-04-17) + + +#### Features + +* **macros** add ability to create enums pub or priv with derives ([2c499f80](https://github.com/kbknapp/clap-rs/commit/2c499f8015a199827cdf1fa3ec4f6f171722f8c7)) + + + + +## v0.6.3 (2015-04-16) + + +#### Features + +* **macros** add macro to create custom enums to use as types ([fb672aff](https://github.com/kbknapp/clap-rs/commit/fb672aff561c29db2e343d6c607138f141aca8b6)) + + + + +## v0.6.2 (2015-04-14) + + +#### Features + +* **macros** + * add ability to get multiple typed values or exit ([0b87251f](https://github.com/kbknapp/clap-rs/commit/0b87251fc088234bee51c323c2b652d7254f7a59)) + * add ability to get a typed multiple values ([e243fe38](https://github.com/kbknapp/clap-rs/commit/e243fe38ddbbf845a46c0b9baebaac3778c80927)) + * add convenience macro to get a typed value or exit ([4b7cd3ea](https://github.com/kbknapp/clap-rs/commit/4b7cd3ea4947780d9daa39f3e1ddab53ad4c7fef)) + * add convenience macro to get a typed value ([8752700f](https://github.com/kbknapp/clap-rs/commit/8752700fbb30e89ee68adbce24489ae9a24d33a9)) + + + + +## v0.6.1 (2015-04-13) + + +#### Bug Fixes + +* **from_usage** trim all whitespace before parsing ([91d29045](https://github.com/kbknapp/clap-rs/commit/91d2904599bd602deef2e515dfc65dc2863bdea0)) + + + + +## v0.6.0 (2015-04-13) + + +#### Bug Fixes + +* **tests** fix failing doc tests ([3710cd69](https://github.com/kbknapp/clap-rs/commit/3710cd69162f87221a62464f63437c1ce843ad3c)) + +#### Features + +* **app** add support for building args from usage strings ([d5d48bcf](https://github.com/kbknapp/clap-rs/commit/d5d48bcf463a4e494ef758836bd69a4c220bbbb5)) +* **args** add ability to create basic arguments from a usage string ([ab409a8f](https://github.com/kbknapp/clap-rs/commit/ab409a8f1db9e37cc70200f6f4a84a162692e618)) + + + + +## v0.5.14 (2015-04-10) + + +#### Bug Fixes + +* **usage** + * remove unneeded space ([51372789](https://github.com/kbknapp/clap-rs/commit/5137278942121bc2593ce6e5dc224ec2682549e6)) + * remove warning about unused variables ([ba817b9d](https://github.com/kbknapp/clap-rs/commit/ba817b9d815e37320650973f1bea0e7af3030fd7)) + +#### Features + +* **usage** add ability to get usage string for subcommands too ([3636afc4](https://github.com/kbknapp/clap-rs/commit/3636afc401c2caa966efb5b1869ef4f1ed3384aa)) + + + + +## v0.5.13 (2015-04-09) + + +#### Features + +* **SubCommands** add method to get name and subcommand matches together ([64e53928](https://github.com/kbknapp/clap-rs/commit/64e539280e23e567cf5de393b346eb0ca20e7eb5)) +* **ArgMatches** add method to get default usage string ([02462150](https://github.com/kbknapp/clap-rs/commit/02462150ca750bdc7012627d7e8d96379d494d7f)) + + + + +## v0.5.12 (2015-04-08) + + +#### Features + +* **help** sort arguments by name so as to not display a random order ([f4b2bf57](https://github.com/kbknapp/clap-rs/commit/f4b2bf5767386013069fb74862e6e938dacf44d2)) + + + + +## v0.5.11 (2015-04-08) + + +#### Bug Fixes + +* **flags** fix bug not allowing users to specify -v or -h ([90e72cff](https://github.com/kbknapp/clap-rs/commit/90e72cffdee321b79eea7a2207119533540062b4)) + + + + +## v0.5.10 (2015-04-08) + + +#### Bug Fixes + +* **help** fix spacing when option argument has not long version ([ca17fa49](https://github.com/kbknapp/clap-rs/commit/ca17fa494b68e92da83ee364bf64b0687006824b)) + + + + +## v0.5.9 (2015-04-08) + + +#### Bug Fixes + +* **positional args** all previous positional args become required when a latter one is required ([c14c3f31](https://github.com/kbknapp/clap-rs/commit/c14c3f31fd557c165570b60911d8ee483d89d6eb), closes [#50](https://github.com/kbknapp/clap-rs/issues/50)) +* **clap** remove unstable features for Rust 1.0 ([9abdb438](https://github.com/kbknapp/clap-rs/commit/9abdb438e36e364d41550e7f5d44ebcaa8ee6b10)) +* **args** improve error messages for arguments with mutual exclusions ([18dbcf37](https://github.com/kbknapp/clap-rs/commit/18dbcf37024daf2b76ca099a6f118b53827aa339), closes [#51](https://github.com/kbknapp/clap-rs/issues/51)) + + + + +## v0.5.8 (2015-04-08) + + +#### Bug Fixes + +* **option args** fix bug in getting the wrong number of occurrences for options ([82ad6ad7](https://github.com/kbknapp/clap-rs/commit/82ad6ad77539cf9f9a03b78db466f575ebd972cc)) +* **help** fix formatting for option arguments with no long ([e8691004](https://github.com/kbknapp/clap-rs/commit/e869100423d93fa3acff03c4620cbcc0d0e790a1)) +* **flags** add assertion to catch flags with specific value sets ([a0a2a40f](https://github.com/kbknapp/clap-rs/commit/a0a2a40fed57f7c5ad9d68970d090e9856306c7d), closes [#52](https://github.com/kbknapp/clap-rs/issues/52)) +* **args** improve error messages for arguments with mutual exclusions ([bff945fc](https://github.com/kbknapp/clap-rs/commit/bff945fc5d03bba4266533340adcffb002508d1b), closes [#51](https://github.com/kbknapp/clap-rs/issues/51)) +* **tests** add missing .takes_value(true) to option2 ([bdb0e88f](https://github.com/kbknapp/clap-rs/commit/bdb0e88f696c8595c3def3bfb0e52d538c7be085)) +* **positional args** all previous positional args become required when a latter one is required ([343d47dc](https://github.com/kbknapp/clap-rs/commit/343d47dcbf83786a45c0d0f01b27fd9dd76725de), closes [#50](https://github.com/kbknapp/clap-rs/issues/50)) + + + + +## v0.5.7 (2015-04-08) + + +#### Bug Fixes + +* **args** fix bug in arguments who are required and mutually exclusive ([6ceb88a5](https://github.com/kbknapp/clap-rs/commit/6ceb88a594caae825605abc1cdad95204996bf29)) + + + + +## v0.5.6 (2015-04-08) + + +#### Bug Fixes + +* **help** fix formatting of help and usage ([28691b52](https://github.com/kbknapp/clap-rs/commit/28691b52f67e65c599e10e4ea2a0f6f9765a06b8)) + + + + +## v0.5.5 (2015-04-08) + + +#### Bug Fixes + +* **help** fix formatting of help for flags and options ([6ec10115](https://github.com/kbknapp/clap-rs/commit/6ec1011563a746f0578a93b76d45e63878e0f9a8)) + + + + +## v0.5.4 (2015-04-08) + + +#### Features + +* **help** add '...' to indicate multiple values supported ([297ddba7](https://github.com/kbknapp/clap-rs/commit/297ddba77000e2228762ab0eca50b480f7467386)) + + + + +## v0.5.3 (2015-04-08) + + +#### Features + +* **positionals** + * add assertions for positional args with multiple vals ([b7fa72d4](https://github.com/kbknapp/clap-rs/commit/b7fa72d40f18806ec2042dd67a518401c2cf5681)) + * add support for multiple values ([80784009](https://github.com/kbknapp/clap-rs/commit/807840094109fbf90b348039ae22669ef27889ba)) + + + + +## v0.5.2 (2015-04-08) + + +#### Bug Fixes + +* **apps** allow use of hyphens in application and subcommand names ([da549dcb](https://github.com/kbknapp/clap-rs/commit/da549dcb6c7e0d773044ab17829744483a8b0f7f)) + + + + +## v0.5.1 (2015-04-08) + + +#### Bug Fixes + +* **args** determine if the only arguments allowed are also required ([0a09eb36](https://github.com/kbknapp/clap-rs/commit/0a09eb365ced9a03faf8ed24f083ef730acc90e8)) + + + + +## v0.5.0 (2015-04-08) + + +#### Features + +* **args** add support for a specific set of allowed values on options or positional arguments ([270eb889](https://github.com/kbknapp/clap-rs/commit/270eb88925b6dc2881bff1f31ee344f085d31809)) + + + + +## v0.4.18 (2015-04-08) + + +#### Bug Fixes + +* **usage** display required args in usage, even if only required by others ([1b7316d4](https://github.com/kbknapp/clap-rs/commit/1b7316d4a8df70b0aa584ccbfd33f68966ad2a54)) + +#### Features + +* **subcommands** properly list subcommands in help and usage ([4ee02344](https://github.com/kbknapp/clap-rs/commit/4ee023442abc3dba54b68138006a52b714adf331)) + + + + +## v0.4.17 (2015-04-08) + + +#### Bug Fixes + +* **tests** remove cargo test from claptests makefile ([1cf73817](https://github.com/kbknapp/clap-rs/commit/1cf73817d6fb1dccb5b6a23b46c2efa8b567ad62)) + + + + +## v0.4.16 (2015-04-08) + + +#### Bug Fixes + +* **option** fix bug with option occurrence values ([9af52e93](https://github.com/kbknapp/clap-rs/commit/9af52e93cef9e17ac9974963f132013d0b97b946)) +* **tests** fix testing script bug and formatting ([d8f03a55](https://github.com/kbknapp/clap-rs/commit/d8f03a55c4f74d126710ee06aad5a667246a8001)) + +#### Features + +* **arg** allow lifetimes other than 'static in arguments ([9e8c1fb9](https://github.com/kbknapp/clap-rs/commit/9e8c1fb9406f8448873ca58bab07fe905f1551e5)) diff --git a/bash-5.1/vendor/clap/CONTRIBUTORS.md b/bash-5.1/vendor/clap/CONTRIBUTORS.md new file mode 100644 index 0000000..f0fd777 --- /dev/null +++ b/bash-5.1/vendor/clap/CONTRIBUTORS.md @@ -0,0 +1,91 @@ +the following is a list of contributors: + + +[kbknapp](https://github.com/kbknapp) |[homu](https://github.com/homu) |[Vinatorul](https://github.com/Vinatorul) |[tormol](https://github.com/tormol) |[willmurphyscode](https://github.com/willmurphyscode) |[little-dude](https://github.com/little-dude) | +:---: |:---: |:---: |:---: |:---: |:---: | +[kbknapp](https://github.com/kbknapp) |[homu](https://github.com/homu) |[Vinatorul](https://github.com/Vinatorul) |[tormol](https://github.com/tormol) |[willmurphyscode](https://github.com/willmurphyscode) |[little-dude](https://github.com/little-dude) | + +[sru](https://github.com/sru) |[mgeisler](https://github.com/mgeisler) |[nabijaczleweli](https://github.com/nabijaczleweli) |[Byron](https://github.com/Byron) |[hgrecco](https://github.com/hgrecco) |[bluejekyll](https://github.com/bluejekyll) | +:---: |:---: |:---: |:---: |:---: |:---: | +[sru](https://github.com/sru) |[mgeisler](https://github.com/mgeisler) |[nabijaczleweli](https://github.com/nabijaczleweli) |[Byron](https://github.com/Byron) |[hgrecco](https://github.com/hgrecco) |[bluejekyll](https://github.com/bluejekyll) | + +[segevfiner](https://github.com/segevfiner) |[ignatenkobrain](https://github.com/ignatenkobrain) |[james-darkfox](https://github.com/james-darkfox) |[H2CO3](https://github.com/H2CO3) |[nateozem](https://github.com/nateozem) |[glowing-chemist](https://github.com/glowing-chemist) | +:---: |:---: |:---: |:---: |:---: |:---: | +[segevfiner](https://github.com/segevfiner) |[ignatenkobrain](https://github.com/ignatenkobrain) |[james-darkfox](https://github.com/james-darkfox) |[H2CO3](https://github.com/H2CO3) |[nateozem](https://github.com/nateozem) |[glowing-chemist](https://github.com/glowing-chemist) | + +[discosultan](https://github.com/discosultan) |[rtaycher](https://github.com/rtaycher) |[Arnavion](https://github.com/Arnavion) |[japaric](https://github.com/japaric) |[untitaker](https://github.com/untitaker) |[afiune](https://github.com/afiune) | +:---: |:---: |:---: |:---: |:---: |:---: | +[discosultan](https://github.com/discosultan) |[rtaycher](https://github.com/rtaycher) |[Arnavion](https://github.com/Arnavion) |[japaric](https://github.com/japaric) |[untitaker](https://github.com/untitaker) |[afiune](https://github.com/afiune) | + +[crazymerlyn](https://github.com/crazymerlyn) |[SuperFluffy](https://github.com/SuperFluffy) |[matthiasbeyer](https://github.com/matthiasbeyer) |[malbarbo](https://github.com/malbarbo) |[tshepang](https://github.com/tshepang) |[golem131](https://github.com/golem131) | +:---: |:---: |:---: |:---: |:---: |:---: | +[crazymerlyn](https://github.com/crazymerlyn) |[SuperFluffy](https://github.com/SuperFluffy) |[matthiasbeyer](https://github.com/matthiasbeyer) |[malbarbo](https://github.com/malbarbo) |[tshepang](https://github.com/tshepang) |[golem131](https://github.com/golem131) | + +[jimmycuadra](https://github.com/jimmycuadra) |[Nemo157](https://github.com/Nemo157) |[severen](https://github.com/severen) |[Eijebong](https://github.com/Eijebong) |[cstorey](https://github.com/cstorey) |[wdv4758h](https://github.com/wdv4758h) | +:---: |:---: |:---: |:---: |:---: |:---: | +[jimmycuadra](https://github.com/jimmycuadra) |[Nemo157](https://github.com/Nemo157) |[severen](https://github.com/severen) |[Eijebong](https://github.com/Eijebong) |[cstorey](https://github.com/cstorey) |[wdv4758h](https://github.com/wdv4758h) | + +[frewsxcv](https://github.com/frewsxcv) |[hoodie](https://github.com/hoodie) |[huonw](https://github.com/huonw) |[GrappigPanda](https://github.com/GrappigPanda) |[shepmaster](https://github.com/shepmaster) |[starkat99](https://github.com/starkat99) | +:---: |:---: |:---: |:---: |:---: |:---: | +[frewsxcv](https://github.com/frewsxcv) |[hoodie](https://github.com/hoodie) |[huonw](https://github.com/huonw) |[GrappigPanda](https://github.com/GrappigPanda) |[shepmaster](https://github.com/shepmaster) |[starkat99](https://github.com/starkat99) | + +[porglezomp](https://github.com/porglezomp) |[kraai](https://github.com/kraai) |[musoke](https://github.com/musoke) |[nelsonjchen](https://github.com/nelsonjchen) |[pkgw](https://github.com/pkgw) |[Deedasmi](https://github.com/Deedasmi) | +:---: |:---: |:---: |:---: |:---: |:---: | +[porglezomp](https://github.com/porglezomp) |[kraai](https://github.com/kraai) |[musoke](https://github.com/musoke) |[nelsonjchen](https://github.com/nelsonjchen) |[pkgw](https://github.com/pkgw) |[Deedasmi](https://github.com/Deedasmi) | + +[vmchale](https://github.com/vmchale) |[etopiei](https://github.com/etopiei) |[messense](https://github.com/messense) |[Keats](https://github.com/Keats) |[kieraneglin](https://github.com/kieraneglin) |[durka](https://github.com/durka) | +:---: |:---: |:---: |:---: |:---: |:---: | +[vmchale](https://github.com/vmchale) |[etopiei](https://github.com/etopiei) |[messense](https://github.com/messense) |[Keats](https://github.com/Keats) |[kieraneglin](https://github.com/kieraneglin) |[durka](https://github.com/durka) | + +[alex-gulyas](https://github.com/alex-gulyas) |[cite-reader](https://github.com/cite-reader) |[alexbool](https://github.com/alexbool) |[AluisioASG](https://github.com/AluisioASG) |[BurntSushi](https://github.com/BurntSushi) |[AndrewGaspar](https://github.com/AndrewGaspar) | +:---: |:---: |:---: |:---: |:---: |:---: | +[alex-gulyas](https://github.com/alex-gulyas) |[cite-reader](https://github.com/cite-reader) |[alexbool](https://github.com/alexbool) |[AluisioASG](https://github.com/AluisioASG) |[BurntSushi](https://github.com/BurntSushi) |[AndrewGaspar](https://github.com/AndrewGaspar) | + +[nox](https://github.com/nox) |[mitsuhiko](https://github.com/mitsuhiko) |[pixelistik](https://github.com/pixelistik) |[ogham](https://github.com/ogham) |[Bilalh](https://github.com/Bilalh) |[dotdash](https://github.com/dotdash) | +:---: |:---: |:---: |:---: |:---: |:---: | +[nox](https://github.com/nox) |[mitsuhiko](https://github.com/mitsuhiko) |[pixelistik](https://github.com/pixelistik) |[ogham](https://github.com/ogham) |[Bilalh](https://github.com/Bilalh) |[dotdash](https://github.com/dotdash) | + +[bradurani](https://github.com/bradurani) |[Seeker14491](https://github.com/Seeker14491) |[brianp](https://github.com/brianp) |[cldershem](https://github.com/cldershem) |[casey](https://github.com/casey) |[volks73](https://github.com/volks73) | +:---: |:---: |:---: |:---: |:---: |:---: | +[bradurani](https://github.com/bradurani) |[Seeker14491](https://github.com/Seeker14491) |[brianp](https://github.com/brianp) |[cldershem](https://github.com/cldershem) |[casey](https://github.com/casey) |[volks73](https://github.com/volks73) | + +[daboross](https://github.com/daboross) |[da-x](https://github.com/da-x) |[mernen](https://github.com/mernen) |[dguo](https://github.com/dguo) |[davidszotten](https://github.com/davidszotten) |[drusellers](https://github.com/drusellers) | +:---: |:---: |:---: |:---: |:---: |:---: | +[daboross](https://github.com/daboross) |[da-x](https://github.com/da-x) |[mernen](https://github.com/mernen) |[dguo](https://github.com/dguo) |[davidszotten](https://github.com/davidszotten) |[drusellers](https://github.com/drusellers) | + +[eddyb](https://github.com/eddyb) |[Enet4](https://github.com/Enet4) |[Fraser999](https://github.com/Fraser999) |[birkenfeld](https://github.com/birkenfeld) |[guanqun](https://github.com/guanqun) |[tanakh](https://github.com/tanakh) | +:---: |:---: |:---: |:---: |:---: |:---: | +[eddyb](https://github.com/eddyb) |[Enet4](https://github.com/Enet4) |[Fraser999](https://github.com/Fraser999) |[birkenfeld](https://github.com/birkenfeld) |[guanqun](https://github.com/guanqun) |[tanakh](https://github.com/tanakh) | + +[SirVer](https://github.com/SirVer) |[idmit](https://github.com/idmit) |[archer884](https://github.com/archer884) |[jacobmischka](https://github.com/jacobmischka) |[jespino](https://github.com/jespino) |[jfrankenau](https://github.com/jfrankenau) | +:---: |:---: |:---: |:---: |:---: |:---: | +[SirVer](https://github.com/SirVer) |[idmit](https://github.com/idmit) |[archer884](https://github.com/archer884) |[jacobmischka](https://github.com/jacobmischka) |[jespino](https://github.com/jespino) |[jfrankenau](https://github.com/jfrankenau) | + +[jtdowney](https://github.com/jtdowney) |[andete](https://github.com/andete) |[joshtriplett](https://github.com/joshtriplett) |[Kalwyn](https://github.com/Kalwyn) |[manuel-rhdt](https://github.com/manuel-rhdt) |[Marwes](https://github.com/Marwes) | +:---: |:---: |:---: |:---: |:---: |:---: | +[jtdowney](https://github.com/jtdowney) |[andete](https://github.com/andete) |[joshtriplett](https://github.com/joshtriplett) |[Kalwyn](https://github.com/Kalwyn) |[manuel-rhdt](https://github.com/manuel-rhdt) |[Marwes](https://github.com/Marwes) | + +[mdaffin](https://github.com/mdaffin) |[iliekturtles](https://github.com/iliekturtles) |[nicompte](https://github.com/nicompte) |[NickeZ](https://github.com/NickeZ) |[nvzqz](https://github.com/nvzqz) |[nuew](https://github.com/nuew) | +:---: |:---: |:---: |:---: |:---: |:---: | +[mdaffin](https://github.com/mdaffin) |[iliekturtles](https://github.com/iliekturtles) |[nicompte](https://github.com/nicompte) |[NickeZ](https://github.com/NickeZ) |[nvzqz](https://github.com/nvzqz) |[nuew](https://github.com/nuew) | + +[Geogi](https://github.com/Geogi) |[focusaurus](https://github.com/focusaurus) |[flying-sheep](https://github.com/flying-sheep) |[Phlosioneer](https://github.com/Phlosioneer) |[peppsac](https://github.com/peppsac) |[golddranks](https://github.com/golddranks) | +:---: |:---: |:---: |:---: |:---: |:---: | +[Geogi](https://github.com/Geogi) |[focusaurus](https://github.com/focusaurus) |[flying-sheep](https://github.com/flying-sheep) |[Phlosioneer](https://github.com/Phlosioneer) |[peppsac](https://github.com/peppsac) |[golddranks](https://github.com/golddranks) | + +[hexjelly](https://github.com/hexjelly) |[rom1v](https://github.com/rom1v) |[rnelson](https://github.com/rnelson) |[swatteau](https://github.com/swatteau) |[tchajed](https://github.com/tchajed) |[tspiteri](https://github.com/tspiteri) | +:---: |:---: |:---: |:---: |:---: |:---: | +[hexjelly](https://github.com/hexjelly) |[rom1v](https://github.com/rom1v) |[rnelson](https://github.com/rnelson) |[swatteau](https://github.com/swatteau) |[tchajed](https://github.com/tchajed) |[tspiteri](https://github.com/tspiteri) | + +[siiptuo](https://github.com/siiptuo) |[vks](https://github.com/vks) |[vsupalov](https://github.com/vsupalov) |[mineo](https://github.com/mineo) |[wabain](https://github.com/wabain) |[grossws](https://github.com/grossws) | +:---: |:---: |:---: |:---: |:---: |:---: | +[siiptuo](https://github.com/siiptuo) |[vks](https://github.com/vks) |[vsupalov](https://github.com/vsupalov) |[mineo](https://github.com/mineo) |[wabain](https://github.com/wabain) |[grossws](https://github.com/grossws) | + +[kennytm](https://github.com/kennytm) |[king6cong](https://github.com/king6cong) |[mvaude](https://github.com/mvaude) |[panicbit](https://github.com/panicbit) |[brennie](https://github.com/brennie) | +:---: |:---: |:---: |:---: |:---: | +[kennytm](https://github.com/kennytm) |[king6cong](https://github.com/king6cong) |[mvaude](https://github.com/mvaude) |[panicbit](https://github.com/panicbit) |[brennie](https://github.com/brennie) | + + + + +This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list) diff --git a/bash-5.1/vendor/clap/Cargo.toml b/bash-5.1/vendor/clap/Cargo.toml new file mode 100644 index 0000000..bb6bf09 --- /dev/null +++ b/bash-5.1/vendor/clap/Cargo.toml @@ -0,0 +1,132 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "clap" +version = "2.34.0" +authors = ["Kevin K. "] +exclude = ["examples/*", "clap-test/*", "tests/*", "benches/*", "*.png", "clap-perf/*", "*.dot"] +description = "A simple to use, efficient, and full-featured Command Line Argument Parser\n" +homepage = "https://clap.rs/" +documentation = "https://docs.rs/clap/" +readme = "README.md" +keywords = ["argument", "cli", "arg", "parser", "parse"] +categories = ["command-line-interface"] +license = "MIT" +repository = "https://github.com/clap-rs/clap" +[package.metadata.docs.rs] +features = ["doc"] +[profile.bench] +opt-level = 3 +lto = true +codegen-units = 1 +debug = false +debug-assertions = false +rpath = false + +[profile.dev] +opt-level = 0 +lto = false +codegen-units = 4 +debug = true +debug-assertions = true +rpath = false + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +debug = false +debug-assertions = false +rpath = false + +[profile.test] +opt-level = 1 +lto = false +codegen-units = 4 +debug = true +debug-assertions = true +rpath = false +[dependencies.atty] +version = "0.2.2" +optional = true + +[dependencies.bitflags] +version = "1.0" + +[dependencies.clippy] +version = "~0.0.166" +optional = true + +[dependencies.strsim] +version = "0.8" +optional = true + +[dependencies.term_size] +version = "0.3.0" +optional = true + +[dependencies.textwrap] +version = "0.11.0" + +[dependencies.unicode-width] +version = "0.1.4" + +[dependencies.vec_map] +version = "0.8" +optional = true + +[dependencies.yaml-rust] +version = "0.3.5" +optional = true +[dev-dependencies.lazy_static] +version = "1.3" + +[dev-dependencies.regex] +version = "1" + +[dev-dependencies.version-sync] +version = "0.8" + +[features] +color = ["ansi_term", "atty"] +debug = [] +default = ["suggestions", "color", "vec_map"] +doc = ["yaml"] +nightly = [] +no_cargo = [] +suggestions = ["strsim"] +unstable = [] +wrap_help = ["term_size", "textwrap/term_size"] +yaml = ["yaml-rust"] +[target."cfg(not(windows))".dependencies.ansi_term] +version = "0.12" +optional = true +[badges.appveyor] +repository = "clap-rs/clap" + +[badges.coveralls] +branch = "master" +repository = "clap-rs/clap" + +[badges.is-it-maintained-issue-resolution] +repository = "clap-rs/clap" + +[badges.is-it-maintained-open-issues] +repository = "clap-rs/clap" + +[badges.maintenance] +status = "actively-developed" + +[badges.travis-ci] +repository = "clap-rs/clap" diff --git a/bash-5.1/vendor/clap/LICENSE-MIT b/bash-5.1/vendor/clap/LICENSE-MIT new file mode 100644 index 0000000..5acedf0 --- /dev/null +++ b/bash-5.1/vendor/clap/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Kevin B. Knapp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bash-5.1/vendor/clap/README.md b/bash-5.1/vendor/clap/README.md new file mode 100644 index 0000000..64085b9 --- /dev/null +++ b/bash-5.1/vendor/clap/README.md @@ -0,0 +1,542 @@ +clap +==== + +[![Crates.io](https://img.shields.io/crates/v/clap.svg)](https://crates.io/crates/clap) [![Crates.io](https://img.shields.io/crates/d/clap.svg)](https://crates.io/crates/clap) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/clap-rs/clap/blob/master/LICENSE-MIT) [![Coverage Status](https://coveralls.io/repos/kbknapp/clap-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/kbknapp/clap-rs?branch=master) [![Join the chat at https://gitter.im/kbknapp/clap-rs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kbknapp/clap-rs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +Linux: [![Build Status](https://travis-ci.org/clap-rs/clap.svg?branch=master)](https://travis-ci.org/clap-rs/clap) +Windows: [![Build status](https://ci.appveyor.com/api/projects/status/ejg8c33dn31nhv36/branch/master?svg=true)](https://ci.appveyor.com/project/kbknapp/clap-rs/branch/master) + +Command Line Argument Parser for Rust + +It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcommands when writing console/terminal applications. + +* [documentation](https://docs.rs/clap/) +* [website](https://clap.rs/) +* [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U) + +Table of Contents +================= + +* [About](#about) +* [FAQ](#faq) +* [Features](#features) +* [Quick Example](#quick-example) +* [Try it!](#try-it) + * [Pre-Built Test](#pre-built-test) + * [BYOB (Build Your Own Binary)](#byob-build-your-own-binary) +* [Usage](#usage) + * [Optional Dependencies / Features](#optional-dependencies--features) + * [Dependencies Tree](#dependencies-tree) + * [More Information](#more-information) + * [Video Tutorials](#video-tutorials) +* [How to Contribute](#how-to-contribute) + * [Compatibility Policy](#compatibility-policy) + * [Minimum Version of Rust](#minimum-version-of-rust) +* [Related Crates](#related-crates) +* [License](#license) +* [Recent Breaking Changes](#recent-breaking-changes) + * [Deprecations](#deprecations) + +Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc) + +## About + +`clap` is used to parse *and validate* the string of command line arguments provided by a user at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means you focus on your *applications* functionality, and less on the parsing and validating of arguments. + +`clap` provides many things 'for free' (with no configuration) including the traditional version and help switches (or flags) along with associated messages. If you are using subcommands, `clap` will also auto-generate a `help` subcommand and separate associated help messages. + +Once `clap` parses the user provided string of arguments, it returns the matches along with any applicable values. If the user made an error or typo, `clap` informs them with a friendly message and exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to exit). Because of this, you can make reasonable assumptions in your code about the validity of the arguments prior to your applications main execution. + +## FAQ + +For a full FAQ and more in depth details, see [the wiki page](https://github.com/clap-rs/clap/wiki/FAQ) + +### Comparisons + +First, let me say that these comparisons are highly subjective, and not meant in a critical or harsh manner. All the argument parsing libraries out there (to include `clap`) have their own strengths and weaknesses. Sometimes it just comes down to personal taste when all other factors are equal. When in doubt, try them all and pick one that you enjoy :) There's plenty of room in the Rust community for multiple implementations! + +#### How does `clap` compare to [getopts](https://github.com/rust-lang-nursery/getopts)? + +`getopts` is a very basic, fairly minimalist argument parsing library. This isn't a bad thing, sometimes you don't need tons of features, you just want to parse some simple arguments, and have some help text generated for you based on valid arguments you specify. The downside to this approach is that you must manually implement most of the common features (such as checking to display help messages, usage strings, etc.). If you want a highly custom argument parser, and don't mind writing the majority of the functionality yourself, `getopts` is an excellent base. + +`getopts` also doesn't allocate much, or at all. This gives it a very small performance boost. Although, as you start implementing additional features, that boost quickly disappears. + +Personally, I find many, many uses of `getopts` are manually implementing features that `clap` provides by default. Using `clap` simplifies your codebase allowing you to focus on your application, and not argument parsing. + +#### How does `clap` compare to [docopt.rs](https://github.com/docopt/docopt.rs)? + +I first want to say I'm a big a fan of BurntSushi's work, the creator of `Docopt.rs`. I aspire to produce the quality of libraries that this man does! When it comes to comparing these two libraries they are very different. `docopt` tasks you with writing a help message, and then it parsers that message for you to determine all valid arguments and their use. Some people LOVE this approach, others do not. If you're willing to write a detailed help message, it's nice that you can stick that in your program and have `docopt` do the rest. On the downside, it's far less flexible. + +`docopt` is also excellent at translating arguments into Rust types automatically. There is even a syntax extension which will do all this for you, if you're willing to use a nightly compiler (use of a stable compiler requires you to somewhat manually translate from arguments to Rust types). To use BurntSushi's words, `docopt` is also a sort of black box. You get what you get, and it's hard to tweak implementation or customize the experience for your use case. + +Because `docopt` is doing a ton of work to parse your help messages and determine what you were trying to communicate as valid arguments, it's also one of the more heavy weight parsers performance-wise. For most applications this isn't a concern and this isn't to say `docopt` is slow, in fact far from it. This is just something to keep in mind while comparing. + +#### All else being equal, what are some reasons to use `clap`? (The Pitch) + +`clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap` when just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex, and advanced requirements, without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs. + +#### All else being equal, what are some reasons *not* to use `clap`? (The Anti Pitch) + +Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many fine-tuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways which may be contrary to some users use-cases. Finally, `clap` is "stringly typed" when referring to arguments which can cause typos in code. This particular paper-cut is being actively worked on, and should be gone in v3.x. + +## Features + +Below are a few of the features which `clap` supports, full descriptions and usage can be found in the [documentation](https://docs.rs/clap/) and [examples/](examples) directory + +* **Auto-generated Help, Version, and Usage information** + - Can optionally be fully, or partially overridden if you want a custom help, version, or usage statements +* **Auto-generated completion scripts at compile time (Bash, Zsh, Fish, and PowerShell)** + - Even works through many multiple levels of subcommands + - Works with options which only accept certain values + - Works with subcommand aliases +* **Flags / Switches** (i.e. bool fields) + - Both short and long versions supported (i.e. `-f` and `--flag` respectively) + - Supports combining short versions (i.e. `-fBgoZ` is the same as `-f -B -g -o -Z`) + - Supports multiple occurrences (i.e. `-vvv` or `-v -v -v`) +* **Positional Arguments** (i.e. those which are based off an index from the program name) + - Supports multiple values (i.e. `myprog ...` such as `myprog file1.txt file2.txt` being two values for the same "file" argument) + - Supports Specific Value Sets (See below) + - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values) + - Can set custom validations on values to extend the argument parsing capability to truly custom domains +* **Option Arguments** (i.e. those that take values) + - Both short and long versions supported (i.e. `-o value`, `-ovalue`, `-o=value` and `--option value` or `--option=value` respectively) + - Supports multiple values (i.e. `-o -o ` or `-o `) + - Supports delimited values (i.e. `-o=val1,val2,val3`, can also change the delimiter) + - Supports Specific Value Sets (See below) + - Supports named values so that the usage/help info appears as `-o ` etc. for when you require specific multiple values + - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values) + - Can set custom validations on values to extend the argument parsing capability to truly custom domains +* **Sub-Commands** (i.e. `git add ` where `add` is a sub-command of `git`) + - Support their own sub-arguments, and sub-sub-commands independent of the parent + - Get their own auto-generated Help, Version, and Usage independent of parent +* **Support for building CLIs from YAML** - This keeps your Rust source nice and tidy and makes supporting localized translation very simple! +* **Requirement Rules**: Arguments can define the following types of requirement rules + - Can be required by default + - Can be required only if certain arguments are present + - Can require other arguments to be present + - Can be required only if certain values of other arguments are used +* **Confliction Rules**: Arguments can optionally define the following types of exclusion rules + - Can be disallowed when certain arguments are present + - Can disallow use of other arguments when present +* **Groups**: Arguments can be made part of a group + - Fully compatible with other relational rules (requirements, conflicts, and overrides) which allows things like requiring the use of any arg in a group, or denying the use of an entire group conditionally +* **Specific Value Sets**: Positional or Option Arguments can define a specific set of allowed values (i.e. imagine a `--mode` option which may *only* have one of two values `fast` or `slow` such as `--mode fast` or `--mode slow`) +* **Default Values** + - Also supports conditional default values (i.e. a default which only applies if specific arguments are used, or specific values of those arguments) +* **Automatic Version from Cargo.toml**: `clap` is fully compatible with Rust's `env!()` macro for automatically setting the version of your application to the version in your Cargo.toml. See [09_auto_version example](examples/09_auto_version.rs) for how to do this (Thanks to [jhelwig](https://github.com/jhelwig) for pointing this out) +* **Typed Values**: You can use several convenience macros provided by `clap` to get typed values (i.e. `i32`, `u8`, etc.) from positional or option arguments so long as the type you request implements `std::str::FromStr` See the [12_typed_values example](examples/12_typed_values.rs). You can also use `clap`s `arg_enum!` macro to create an enum with variants that automatically implement `std::str::FromStr`. See [13a_enum_values_automatic example](examples/13a_enum_values_automatic.rs) for details +* **Suggestions**: Suggests corrections when the user enters a typo. For example, if you defined a `--myoption` argument, and the user mistakenly typed `--moyption` (notice `y` and `o` transposed), they would receive a `Did you mean '--myoption'?` error and exit gracefully. This also works for subcommands and flags. (Thanks to [Byron](https://github.com/Byron) for the implementation) (This feature can optionally be disabled, see 'Optional Dependencies / Features') +* **Colorized Errors (Non Windows OS only)**: Error message are printed in in colored text (this feature can optionally be disabled, see 'Optional Dependencies / Features'). +* **Global Arguments**: Arguments can optionally be defined once, and be available to all child subcommands. There values will also be propagated up/down throughout all subcommands. +* **Custom Validations**: You can define a function to use as a validator of argument values. Imagine defining a function to validate IP addresses, or fail parsing upon error. This means your application logic can be solely focused on *using* values. +* **POSIX Compatible Conflicts/Overrides** - In POSIX args can be conflicting, but not fail parsing because whichever arg comes *last* "wins" so to speak. This allows things such as aliases (i.e. `alias ls='ls -l'` but then using `ls -C` in your terminal which ends up passing `ls -l -C` as the final arguments. Since `-l` and `-C` aren't compatible, this effectively runs `ls -C` in `clap` if you choose...`clap` also supports hard conflicts that fail parsing). (Thanks to [Vinatorul](https://github.com/Vinatorul)!) +* Supports the Unix `--` meaning, only positional arguments follow + +## Quick Example + +The following examples show a quick example of some of the very basic functionality of `clap`. For more advanced usage, such as requirements, conflicts, groups, multiple values and occurrences see the [documentation](https://docs.rs/clap/), [examples/](examples) directory of this repository or the [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U). + + **NOTE:** All of these examples are functionally the same, but show different styles in which to use `clap`. These different styles are purely a matter of personal preference. + +The first example shows a method using the 'Builder Pattern' which allows more advanced configuration options (not shown in this small example), or even dynamically generating arguments when desired. + +```rust +// (Full example with detailed comments in examples/01b_quick_example.rs) +// +// This example demonstrates clap's full 'builder pattern' style of creating arguments which is +// more verbose, but allows easier editing, and at times more advanced options, or the possibility +// to generate arguments dynamically. +extern crate clap; +use clap::{Arg, App, SubCommand}; + +fn main() { + let matches = App::new("My Super Program") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .arg(Arg::with_name("config") + .short("c") + .long("config") + .value_name("FILE") + .help("Sets a custom config file") + .takes_value(true)) + .arg(Arg::with_name("INPUT") + .help("Sets the input file to use") + .required(true) + .index(1)) + .arg(Arg::with_name("v") + .short("v") + .multiple(true) + .help("Sets the level of verbosity")) + .subcommand(SubCommand::with_name("test") + .about("controls testing features") + .version("1.3") + .author("Someone E. ") + .arg(Arg::with_name("debug") + .short("d") + .help("print debug information verbosely"))) + .get_matches(); + + // Gets a value for config if supplied by user, or defaults to "default.conf" + let config = matches.value_of("config").unwrap_or("default.conf"); + println!("Value for config: {}", config); + + // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't + // required we could have used an 'if let' to conditionally get the value) + println!("Using input file: {}", matches.value_of("INPUT").unwrap()); + + // Vary the output based on how many times the user used the "verbose" flag + // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v' + match matches.occurrences_of("v") { + 0 => println!("No verbose info"), + 1 => println!("Some verbose info"), + 2 => println!("Tons of verbose info"), + 3 | _ => println!("Don't be crazy"), + } + + // You can handle information about subcommands by requesting their matches by name + // (as below), requesting just the name used, or both at the same time + if let Some(matches) = matches.subcommand_matches("test") { + if matches.is_present("debug") { + println!("Printing debug info..."); + } else { + println!("Printing normally..."); + } + } + + // more program logic goes here... +} +``` + +One could also optionally declare their CLI in YAML format and keep your Rust source tidy +or support multiple localized translations by having different YAML files for each localization. + +First, create the `cli.yml` file to hold your CLI options, but it could be called anything we like: + +```yaml +name: myapp +version: "1.0" +author: Kevin K. +about: Does awesome things +args: + - config: + short: c + long: config + value_name: FILE + help: Sets a custom config file + takes_value: true + - INPUT: + help: Sets the input file to use + required: true + index: 1 + - verbose: + short: v + multiple: true + help: Sets the level of verbosity +subcommands: + - test: + about: controls testing features + version: "1.3" + author: Someone E. + args: + - debug: + short: d + help: print debug information +``` + +Since this feature requires additional dependencies that not everyone may want, it is *not* compiled in by default and we need to enable a feature flag in Cargo.toml: + +Simply change your `clap = "2.34"` to `clap = {version = "2.34", features = ["yaml"]}`. + +Finally we create our `main.rs` file just like we would have with the previous two examples: + +```rust +// (Full example with detailed comments in examples/17_yaml.rs) +// +// This example demonstrates clap's building from YAML style of creating arguments which is far +// more clean, but takes a very small performance hit compared to the other two methods. +#[macro_use] +extern crate clap; +use clap::App; + +fn main() { + // The YAML file is found relative to the current file, similar to how modules are found + let yaml = load_yaml!("cli.yml"); + let matches = App::from_yaml(yaml).get_matches(); + + // Same as previous examples... +} +``` + +If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or `help` subcommand, since we defined `test` as a subcommand) the following would be output + +```sh +$ myprog --help +My Super Program 1.0 +Kevin K. +Does awesome things + +USAGE: + MyApp [FLAGS] [OPTIONS] [SUBCOMMAND] + +FLAGS: + -h, --help Prints help information + -v Sets the level of verbosity + -V, --version Prints version information + +OPTIONS: + -c, --config Sets a custom config file + +ARGS: + INPUT The input file to use + +SUBCOMMANDS: + help Prints this message or the help of the given subcommand(s) + test Controls testing features +``` + +**NOTE:** You could also run `myapp test --help` or `myapp help test` to see the help message for the `test` subcommand. + +There are also two other methods to create CLIs. Which style you choose is largely a matter of personal preference. The two other methods are: + +* Using [usage strings (examples/01a_quick_example.rs)](examples/01a_quick_example.rs) similar to (but not exact) docopt style usage statements. This is far less verbose than the above methods, but incurs a slight runtime penalty. +* Using [a macro (examples/01c_quick_example.rs)](examples/01c_quick_example.rs) which is like a hybrid of the builder and usage string style. It's less verbose, but doesn't incur the runtime penalty of the usage string style. The downside is that it's harder to debug, and more opaque. + +Examples of each method can be found in the [examples/](examples) directory of this repository. + +## Try it! + +### Pre-Built Test + +To try out the pre-built examples, use the following steps: + +* Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/` +* Compile the example `$ cargo build --example ` +* Run the help info `$ ./target/debug/examples/ --help` +* Play with the arguments! +* You can also do a onetime run via `$ cargo run --example -- [args to example]` + +### BYOB (Build Your Own Binary) + +To test out `clap`'s default auto-generated help/version follow these steps: +* Create a new cargo project `$ cargo new fake --bin && cd fake` +* Add `clap` to your `Cargo.toml` + +```toml +[dependencies] +clap = "2" +``` + +* Add the following to your `src/main.rs` + +```rust +extern crate clap; +use clap::App; + +fn main() { + App::new("fake").version("v1.0-beta").get_matches(); +} +``` + +* Build your program `$ cargo build --release` +* Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake --version` + +## Usage + +For full usage, add `clap` as a dependency in your `Cargo.toml` () to use from crates.io: + +```toml +[dependencies] +clap = "~2.34" +``` + +(**note**: If you are concerned with supporting a minimum version of Rust that is *older* than the current stable Rust minus 2 stable releases, it's recommended to use the `~major.minor.patch` style versions in your `Cargo.toml` which will only update the patch version automatically. For more information see the [Compatibility Policy](#compatibility-policy)) + +Then add `extern crate clap;` to your crate root. + +Define a list of valid arguments for your program (see the [documentation](https://docs.rs/clap/) or [examples/](examples) directory of this repo) + +Then run `cargo build` or `cargo update && cargo build` for your project. + +### Optional Dependencies / Features + +#### Features enabled by default + +* **"suggestions"**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`) +* **"color"**: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` only on non-Windows targets) +* **"vec_map"**: Use [`VecMap`](https://crates.io/crates/vec_map) internally instead of a [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html). This feature provides a _slight_ performance improvement. (builds dependency `vec_map`) + +To disable these, add this to your `Cargo.toml`: + +```toml +[dependencies.clap] +version = "2.34" +default-features = false +``` + +You can also selectively enable only the features you'd like to include, by adding: + +```toml +[dependencies.clap] +version = "2.34" +default-features = false + +# Cherry-pick the features you'd like to use +features = [ "suggestions", "color" ] +``` + +#### Opt-in features + +* **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`) +* **"unstable"**: Enables unstable `clap` features that may change from release to release +* **"wrap_help"**: Turns on the help text wrapping feature, based on the terminal size. (builds dependency `term-size`) + +### Dependencies Tree + +The following graphic depicts `clap`s dependency graph (generated using [cargo-graph](https://github.com/kbknapp/cargo-graph)). + + * **Dashed** Line: Optional dependency + * **Red** Color: **NOT** included by default (must use cargo `features` to enable) + * **Blue** Color: Dev dependency, only used while developing. + +![clap dependencies](clap_dep_graph.png) + +### More Information + +You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project. + +You can also find usage examples in the [examples/](examples) directory of this repo. + +#### Video Tutorials + +There's also the video tutorial series [Argument Parsing with Rust v2](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U). + +These videos slowly trickle out as I finish them and currently a work in progress. + +## How to Contribute + +Details on how to contribute can be found in the [CONTRIBUTING.md](.github/CONTRIBUTING.md) file. + +### Compatibility Policy + +Because `clap` takes SemVer and compatibility seriously, this is the official policy regarding breaking changes and minimum required versions of Rust. + +`clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version of `clap` will be bumped. + +In order to keep from being surprised of breaking changes, it is **highly** recommended to use the `~major.minor.patch` style in your `Cargo.toml` only if you wish to target a version of Rust that is *older* than current stable minus two releases: + +```toml +[dependencies] +clap = "~2.34" +``` + +This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore cannot break due to new features, or bumped minimum versions of Rust. + +#### Warning about '~' Dependencies + +Using `~` can cause issues in certain circumstances. + +From @alexcrichton: + +Right now Cargo's version resolution is pretty naive, it's just a brute-force search of the solution space, returning the first resolvable graph. This also means that it currently won't terminate until it proves there is not possible resolvable graph. This leads to situations where workspaces with multiple binaries, for example, have two different dependencies such as: + +```toml,no_sync + +# In one Cargo.toml +[dependencies] +clap = "~2.34.0" + +# In another Cargo.toml +[dependencies] +clap = "2.34.0" +``` + +This is inherently an unresolvable crate graph in Cargo right now. Cargo requires there's only one major version of a crate, and being in the same workspace these two crates must share a version. This is impossible in this location, though, as these version constraints cannot be met. + +#### Minimum Version of Rust + +`clap` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.41.0, meaning `clap` is guaranteed to compile with 1.39.0 and beyond. + +At the 1.42.0 stable release, `clap` will be guaranteed to compile with 1.40.0 and beyond, etc. + +Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be clearly annotated in the `CHANGELOG.md` + +#### Breaking Changes + +`clap` takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions: + + * The breaking change is to fix a security concern + * The breaking change is to be fixing a bug (i.e. relying on a bug as a feature) + * The breaking change is a feature isn't used in the wild, or all users of said feature have given approval *prior* to the change + +#### Compatibility with Wasm + +A best effort is made to ensure that `clap` will work on projects targeting `wasm32-unknown-unknown`. However there is no dedicated CI build +covering this specific target. + +## License + +`clap` is licensed under the MIT license. Please read the [LICENSE-MIT](LICENSE-MIT) file in this repository for more information. + +## Related Crates + +There are several excellent crates which can be used with `clap`, I recommend checking them all out! If you've got a crate that would be a good fit to be used with `clap` open an issue and let me know, I'd love to add it! + +* [`structopt`](https://github.com/TeXitoi/structopt) - This crate allows you to define a struct, and build a CLI from it! No more "stringly typed" and it uses `clap` behind the scenes! (*Note*: There is work underway to pull this crate into mainline `clap`). +* [`assert_cli`](https://github.com/assert-rs/assert_cli) - This crate allows you test your CLIs in a very intuitive and functional way! + +## Recent Breaking Changes + +`clap` follows semantic versioning, so breaking changes should only happen upon major version bumps. The only exception to this rule is breaking changes that happen due to implementation that was deemed to be a bug, security concerns, or it can be reasonably proved to affect no code. For the full details, see [CHANGELOG.md](./CHANGELOG.md). + +As of 2.27.0: + +* Argument values now take precedence over subcommand names. This only arises by using unrestrained multiple values and subcommands together where the subcommand name can coincide with one of the multiple values. Such as `$ prog ... `. The fix is to place restraints on number of values, or disallow the use of `$ prog ` structure. + +As of 2.0.0 (From 1.x) + +* **Fewer lifetimes! Yay!** + * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>` + * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>` + * `ArgMatches<'a, 'b>` => `ArgMatches<'a>` +* **Simply Renamed** + * `App::arg_group` => `App::group` + * `App::arg_groups` => `App::groups` + * `ArgGroup::add` => `ArgGroup::arg` + * `ArgGroup::add_all` => `ArgGroup::args` + * `ClapError` => `Error` + * struct field `ClapError::error_type` => `Error::kind` + * `ClapResult` => `Result` + * `ClapErrorType` => `ErrorKind` +* **Removed Deprecated Functions and Methods** + * `App::subcommands_negate_reqs` + * `App::subcommand_required` + * `App::arg_required_else_help` + * `App::global_version(bool)` + * `App::versionless_subcommands` + * `App::unified_help_messages` + * `App::wait_on_error` + * `App::subcommand_required_else_help` + * `SubCommand::new` + * `App::error_on_no_subcommand` + * `Arg::new` + * `Arg::mutually_excludes` + * `Arg::mutually_excludes_all` + * `Arg::mutually_overrides_with` + * `simple_enum!` +* **Renamed Error Variants** + * `InvalidUnicode` => `InvalidUtf8` + * `InvalidArgument` => `UnknownArgument` +* **Usage Parser** + * Value names can now be specified inline, i.e. `-o, --option 'some option which takes two files'` + * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code** +* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code) +* `crate_version!` returns `&'static str` instead of `String` + +### Deprecations + +Old method names will be left around for several minor version bumps, or one major version bump. + +As of 2.27.0: + +* **AppSettings::PropagateGlobalValuesDown:** this setting deprecated and is no longer required to propagate values down or up diff --git a/bash-5.1/vendor/clap/SPONSORS.md b/bash-5.1/vendor/clap/SPONSORS.md new file mode 100644 index 0000000..67f5544 --- /dev/null +++ b/bash-5.1/vendor/clap/SPONSORS.md @@ -0,0 +1,17 @@ +Below is a list of sponsors for the clap-rs project + +If you are interested in becoming a sponsor for this project please our [sponsorship page](https://clap.rs/sponsorship/). + +## Recurring Sponsors: + +| [Noelia Seva-Gonzalez](https://noeliasg.com/about/) | [messense](https://github.com/messense) | [Josh](https://joshtriplett.org) | Stephen Oats | +|:-:|:-:|:-:|:-:| +|Noelia Seva-Gonzalez | Messense | Josh Triplett | Stephen Oats | + + +## Single-Donation and Former Sponsors: + +| [Rob Tsuk](https://github.com/rtsuk)| | | +|:-:|:-:|:-:| +|Rob Tsuk| | | + diff --git a/bash-5.1/vendor/clap/clap-test.rs b/bash-5.1/vendor/clap/clap-test.rs new file mode 100644 index 0000000..7d57ac4 --- /dev/null +++ b/bash-5.1/vendor/clap/clap-test.rs @@ -0,0 +1,86 @@ +#[allow(unused_imports, dead_code)] +mod test { + use std::str; + use std::io::{Cursor, Write}; + + use regex::Regex; + + use clap::{App, Arg, SubCommand, ArgGroup}; + + fn compare(l: S, r: S2) -> bool + where S: AsRef, + S2: AsRef + { + let re = Regex::new("\x1b[^m]*m").unwrap(); + // Strip out any mismatching \r character on windows that might sneak in on either side + let ls = l.as_ref().trim().replace("\r", ""); + let rs = r.as_ref().trim().replace("\r", ""); + let left = re.replace_all(&*ls, ""); + let right = re.replace_all(&*rs, ""); + let b = left == right; + if !b { + println!(); + println!("--> left"); + println!("{}", left); + println!("--> right"); + println!("{}", right); + println!("--") + } + b + } + + pub fn compare_output(l: App, args: &str, right: &str, stderr: bool) -> bool { + let mut buf = Cursor::new(Vec::with_capacity(50)); + let res = l.get_matches_from_safe(args.split(' ').collect::>()); + let err = res.unwrap_err(); + err.write_to(&mut buf).unwrap(); + let content = buf.into_inner(); + let left = String::from_utf8(content).unwrap(); + assert_eq!(stderr, err.use_stderr()); + compare(left, right) + } + pub fn compare_output2(l: App, args: &str, right1: &str, right2: &str, stderr: bool) -> bool { + let mut buf = Cursor::new(Vec::with_capacity(50)); + let res = l.get_matches_from_safe(args.split(' ').collect::>()); + let err = res.unwrap_err(); + err.write_to(&mut buf).unwrap(); + let content = buf.into_inner(); + let left = String::from_utf8(content).unwrap(); + assert_eq!(stderr, err.use_stderr()); + compare(&*left, right1) || compare(&*left, right2) + } + + // Legacy tests from the Python script days + + pub fn complex_app() -> App<'static, 'static> { + let args = "-o --option=[opt]... 'tests options' + [positional] 'tests positionals'"; + let opt3_vals = ["fast", "slow"]; + let pos3_vals = ["vi", "emacs"]; + App::new("clap-test") + .version("v1.4.8") + .about("tests clap library") + .author("Kevin K. ") + .args_from_usage(args) + .arg(Arg::from_usage("-f --flag... 'tests flags'") + .global(true)) + .args(&[ + Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("long-option-2"), + Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"), + Arg::from_usage("[positional2] 'tests positionals with exclusions'"), + Arg::from_usage("-O --Option [option3] 'specific vals'").possible_values(&opt3_vals), + Arg::from_usage("[positional3]... 'tests specific values'").possible_values(&pos3_vals), + Arg::from_usage("--multvals [one] [two] 'Tests multiple values, not mult occs'"), + Arg::from_usage("--multvalsmo... [one] [two] 'Tests multiple values, and mult occs'"), + Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2), + Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3) + ]) + .subcommand(SubCommand::with_name("subcmd") + .about("tests subcommands") + .version("0.1") + .author("Kevin K. ") + .arg_from_usage("-o --option [scoption]... 'tests options'") + .arg_from_usage("-s --subcmdarg [subcmdarg] 'tests other args'") + .arg_from_usage("[scpositional] 'tests positionals'")) + } +} diff --git a/bash-5.1/vendor/clap/justfile b/bash-5.1/vendor/clap/justfile new file mode 100644 index 0000000..0768764 --- /dev/null +++ b/bash-5.1/vendor/clap/justfile @@ -0,0 +1,39 @@ +@update-contributors: + echo 'Removing old CONTRIBUTORS.md' + mv CONTRIBUTORS.md CONTRIBUTORS.md.bak + echo 'Downloading a list of new contributors' + echo "the following is a list of contributors:" > CONTRIBUTORS.md + echo "" >> CONTRIBUTORS.md + echo "" >> CONTRIBUTORS.md + githubcontrib --owner clap-rs --repo clap --sha master --cols 6 --format md --showlogin true --sortBy contributions --sortOrder desc >> CONTRIBUTORS.md + echo "" >> CONTRIBUTORS.md + echo "" >> CONTRIBUTORS.md + echo "This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)" >> CONTRIBUTORS.md + rm CONTRIBUTORS.md.bak + +run-test TEST: + cargo test --test {{TEST}} + +debug TEST: + cargo test --test {{TEST}} --features debug + +run-tests: + cargo test --features "yaml unstable" + +@bench: nightly + cargo bench && just remove-nightly + +nightly: + rustup override add nightly + +remove-nightly: + rustup override remove + +@lint: nightly + cargo build --features lints && just remove-nightly + +clean: + cargo clean + find . -type f -name "*.orig" -exec rm {} \; + find . -type f -name "*.bk" -exec rm {} \; + find . -type f -name ".*~" -exec rm {} \; diff --git a/bash-5.1/vendor/clap/src/app/help.rs b/bash-5.1/vendor/clap/src/app/help.rs new file mode 100644 index 0000000..e5f2a60 --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/help.rs @@ -0,0 +1,1032 @@ +// Std +use std::{ + borrow::Cow, + cmp, + collections::BTreeMap, + fmt::Display, + io::{self, Cursor, Read, Write}, + usize, +}; + +// Third Party +#[cfg(feature = "wrap_help")] +use term_size; +#[cfg(feature = "wrap_help")] +use textwrap; +use unicode_width::UnicodeWidthStr; + +// Internal +use crate::{ + app::{parser::Parser, usage, App, AppSettings}, + args::{AnyArg, ArgSettings, DispOrder}, + errors::{Error, Result as ClapResult}, + fmt::{Colorizer, ColorizerOption, Format}, + map::VecMap, + INTERNAL_ERROR_MSG, +}; + +#[cfg(not(feature = "wrap_help"))] +mod term_size { + pub fn dimensions() -> Option<(usize, usize)> { + None + } +} + +fn str_width(s: &str) -> usize { + UnicodeWidthStr::width(s) +} + +const TAB: &str = " "; + +// These are just convenient traits to make the code easier to read. +trait ArgWithDisplay<'b, 'c>: AnyArg<'b, 'c> + Display {} +impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T where T: AnyArg<'b, 'c> + Display {} + +trait ArgWithOrder<'b, 'c>: ArgWithDisplay<'b, 'c> + DispOrder { + fn as_base(&self) -> &ArgWithDisplay<'b, 'c>; +} +impl<'b, 'c, T> ArgWithOrder<'b, 'c> for T +where + T: ArgWithDisplay<'b, 'c> + DispOrder, +{ + fn as_base(&self) -> &ArgWithDisplay<'b, 'c> { + self + } +} + +fn as_arg_trait<'a, 'b, T: ArgWithOrder<'a, 'b>>(x: &T) -> &ArgWithOrder<'a, 'b> { + x +} + +impl<'b, 'c> DispOrder for App<'b, 'c> { + fn disp_ord(&self) -> usize { + 999 + } +} + +macro_rules! color { + ($_self:ident, $s:expr, $c:ident) => { + if $_self.color { + write!($_self.writer, "{}", $_self.cizer.$c($s)) + } else { + write!($_self.writer, "{}", $s) + } + }; + ($_self:ident, $fmt_s:expr, $v:expr, $c:ident) => { + if $_self.color { + write!($_self.writer, "{}", $_self.cizer.$c(format!($fmt_s, $v))) + } else { + write!($_self.writer, $fmt_s, $v) + } + }; +} + +/// `clap` Help Writer. +/// +/// Wraps a writer stream providing different methods to generate help for `clap` objects. +pub struct Help<'a> { + writer: &'a mut Write, + next_line_help: bool, + hide_pv: bool, + term_w: usize, + color: bool, + cizer: Colorizer, + longest: usize, + force_next_line: bool, + use_long: bool, +} + +// Public Functions +impl<'a> Help<'a> { + /// Create a new `Help` instance. + #[cfg_attr(feature = "cargo-clippy", allow(clippy::too_many_arguments))] + pub fn new( + w: &'a mut Write, + next_line_help: bool, + hide_pv: bool, + color: bool, + cizer: Colorizer, + term_w: Option, + max_w: Option, + use_long: bool, + ) -> Self { + debugln!("Help::new;"); + Help { + writer: w, + next_line_help, + hide_pv, + term_w: match term_w { + Some(width) => { + if width == 0 { + usize::MAX + } else { + width + } + } + None => cmp::min( + term_size::dimensions().map_or(120, |(w, _)| w), + match max_w { + None | Some(0) => usize::MAX, + Some(mw) => mw, + }, + ), + }, + color, + cizer, + longest: 0, + force_next_line: false, + use_long, + } + } + + /// Reads help settings from an App + /// and write its help to the wrapped stream. + pub fn write_app_help(w: &'a mut Write, app: &App, use_long: bool) -> ClapResult<()> { + debugln!("Help::write_app_help;"); + Self::write_parser_help(w, &app.p, use_long) + } + + /// Reads help settings from a Parser + /// and write its help to the wrapped stream. + pub fn write_parser_help(w: &'a mut Write, parser: &Parser, use_long: bool) -> ClapResult<()> { + debugln!("Help::write_parser_help;"); + Self::_write_parser_help(w, parser, false, use_long) + } + + /// Reads help settings from a Parser + /// and write its help to the wrapped stream which will be stderr. This method prevents + /// formatting when required. + pub fn write_parser_help_to_stderr(w: &'a mut Write, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_parser_help;"); + Self::_write_parser_help(w, parser, true, false) + } + + #[doc(hidden)] + pub fn _write_parser_help( + w: &'a mut Write, + parser: &Parser, + stderr: bool, + use_long: bool, + ) -> ClapResult<()> { + debugln!("Help::write_parser_help;"); + let nlh = parser.is_set(AppSettings::NextLineHelp); + let hide_v = parser.is_set(AppSettings::HidePossibleValuesInHelp); + let color = parser.is_set(AppSettings::ColoredHelp); + let cizer = Colorizer::new(ColorizerOption { + use_stderr: stderr, + when: parser.color(), + }); + Self::new( + w, + nlh, + hide_v, + color, + cizer, + parser.meta.term_w, + parser.meta.max_w, + use_long, + ) + .write_help(parser) + } + + /// Writes the parser help to the wrapped stream. + pub fn write_help(&mut self, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_help;"); + if let Some(h) = parser.meta.help_str { + write!(self.writer, "{}", h).map_err(Error::from)?; + } else if let Some(tmpl) = parser.meta.template { + self.write_templated_help(parser, tmpl)?; + } else { + self.write_default_help(parser)?; + } + Ok(()) + } +} + +// Methods to write AnyArg help. +impl<'a> Help<'a> { + /// Writes help for each argument in the order they were declared to the wrapped stream. + fn write_args_unsorted<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()> + where + I: Iterator>, + { + debugln!("Help::write_args_unsorted;"); + // The shortest an arg can legally be is 2 (i.e. '-x') + self.longest = 2; + let mut arg_v = Vec::with_capacity(10); + let use_long = self.use_long; + for arg in args.filter(|arg| should_show_arg(use_long, *arg)) { + if arg.longest_filter() { + self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); + } + arg_v.push(arg) + } + let mut first = true; + for arg in arg_v { + if first { + first = false; + } else { + self.writer.write_all(b"\n")?; + } + self.write_arg(arg.as_base())?; + } + Ok(()) + } + + /// Sorts arguments by length and display order and write their help to the wrapped stream. + fn write_args<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()> + where + I: Iterator>, + { + debugln!("Help::write_args;"); + // The shortest an arg can legally be is 2 (i.e. '-x') + self.longest = 2; + let mut ord_m = VecMap::new(); + let use_long = self.use_long; + // Determine the longest + for arg in args.filter(|arg| { + // If it's NextLineHelp, but we don't care to compute how long because it may be + // NextLineHelp on purpose *because* it's so long and would throw off all other + // args alignment + should_show_arg(use_long, *arg) + }) { + if arg.longest_filter() { + debugln!("Help::write_args: Current Longest...{}", self.longest); + self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); + debugln!("Help::write_args: New Longest...{}", self.longest); + } + let btm = ord_m.entry(arg.disp_ord()).or_insert(BTreeMap::new()); + btm.insert(arg.name(), arg); + } + let mut first = true; + for btm in ord_m.values() { + for arg in btm.values() { + if first { + first = false; + } else { + self.writer.write_all(b"\n")?; + } + self.write_arg(arg.as_base())?; + } + } + Ok(()) + } + + /// Writes help for an argument to the wrapped stream. + fn write_arg<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { + debugln!("Help::write_arg;"); + self.short(arg)?; + self.long(arg)?; + let spec_vals = self.val(arg)?; + self.help(arg, &*spec_vals)?; + Ok(()) + } + + /// Writes argument's short command to the wrapped stream. + fn short<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { + debugln!("Help::short;"); + write!(self.writer, "{}", TAB)?; + if let Some(s) = arg.short() { + color!(self, "-{}", s, good) + } else if arg.has_switch() { + write!(self.writer, "{}", TAB) + } else { + Ok(()) + } + } + + /// Writes argument's long command to the wrapped stream. + fn long<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { + debugln!("Help::long;"); + if !arg.has_switch() { + return Ok(()); + } + if arg.takes_value() { + if let Some(l) = arg.long() { + if arg.short().is_some() { + write!(self.writer, ", ")?; + } + color!(self, "--{}", l, good)? + } + + let sep = if arg.is_set(ArgSettings::RequireEquals) { + "=" + } else { + " " + }; + write!(self.writer, "{}", sep)?; + } else if let Some(l) = arg.long() { + if arg.short().is_some() { + write!(self.writer, ", ")?; + } + color!(self, "--{}", l, good)?; + } + Ok(()) + } + + /// Writes argument's possible values to the wrapped stream. + fn val<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> Result { + debugln!("Help::val: arg={}", arg); + if arg.takes_value() { + let delim = if arg.is_set(ArgSettings::RequireDelimiter) { + arg.val_delim().expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }; + if let Some(vec) = arg.val_names() { + let mut it = vec.iter().peekable(); + while let Some((_, val)) = it.next() { + color!(self, "<{}>", val, good)?; + if it.peek().is_some() { + write!(self.writer, "{}", delim)?; + } + } + let num = vec.len(); + if arg.is_set(ArgSettings::Multiple) && num == 1 { + color!(self, "...", good)?; + } + } else if let Some(num) = arg.num_vals() { + let mut it = (0..num).peekable(); + while let Some(_) = it.next() { + color!(self, "<{}>", arg.name(), good)?; + if it.peek().is_some() { + write!(self.writer, "{}", delim)?; + } + } + if arg.is_set(ArgSettings::Multiple) && num == 1 { + color!(self, "...", good)?; + } + } else if arg.has_switch() { + color!(self, "<{}>", arg.name(), good)?; + if arg.is_set(ArgSettings::Multiple) { + color!(self, "...", good)?; + } + } else { + color!(self, "{}", arg, good)?; + } + } + + let spec_vals = self.spec_vals(arg); + let h = arg.help().unwrap_or(""); + let h_w = str_width(h) + str_width(&*spec_vals); + let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp); + let taken = self.longest + 12; + self.force_next_line = !nlh + && self.term_w >= taken + && (taken as f32 / self.term_w as f32) > 0.40 + && h_w > (self.term_w - taken); + + debug!("Help::val: Has switch..."); + if arg.has_switch() { + sdebugln!("Yes"); + debugln!("Help::val: force_next_line...{:?}", self.force_next_line); + debugln!("Help::val: nlh...{:?}", nlh); + debugln!("Help::val: taken...{}", taken); + debugln!( + "Help::val: help_width > (width - taken)...{} > ({} - {})", + h_w, + self.term_w, + taken + ); + debugln!("Help::val: longest...{}", self.longest); + debug!("Help::val: next_line..."); + if !(nlh || self.force_next_line) { + sdebugln!("No"); + let self_len = str_width(arg.to_string().as_str()); + // subtract ourself + let mut spcs = self.longest - self_len; + // Since we're writing spaces from the tab point we first need to know if we + // had a long and short, or just short + if arg.long().is_some() { + // Only account 4 after the val + spcs += 4; + } else { + // Only account for ', --' + 4 after the val + spcs += 8; + } + + write_nspaces!(self.writer, spcs); + } else { + sdebugln!("Yes"); + } + } else if !(nlh || self.force_next_line) { + sdebugln!("No, and not next_line"); + write_nspaces!( + self.writer, + self.longest + 4 - (str_width(arg.to_string().as_str())) + ); + } else { + sdebugln!("No"); + } + Ok(spec_vals) + } + + fn write_before_after_help(&mut self, h: &str) -> io::Result<()> { + debugln!("Help::write_before_after_help;"); + let mut help = String::from(h); + // determine if our help fits or needs to wrap + debugln!( + "Help::write_before_after_help: Term width...{}", + self.term_w + ); + let too_long = str_width(h) >= self.term_w; + + debug!("Help::write_before_after_help: Too long..."); + if too_long || h.contains("{n}") { + sdebugln!("Yes"); + debugln!("Help::write_before_after_help: help: {}", help); + debugln!( + "Help::write_before_after_help: help width: {}", + str_width(&*help) + ); + // Determine how many newlines we need to insert + debugln!( + "Help::write_before_after_help: Usable space: {}", + self.term_w + ); + help = wrap_help(&help.replace("{n}", "\n"), self.term_w); + } else { + sdebugln!("No"); + } + write!(self.writer, "{}", help)?; + Ok(()) + } + + /// Writes argument's help to the wrapped stream. + fn help<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>, spec_vals: &str) -> io::Result<()> { + debugln!("Help::help;"); + let h = if self.use_long && arg.name() != "" { + arg.long_help().unwrap_or_else(|| arg.help().unwrap_or("")) + } else { + arg.help().unwrap_or_else(|| arg.long_help().unwrap_or("")) + }; + let mut help = String::from(h) + spec_vals; + let nlh = self.next_line_help + || arg.is_set(ArgSettings::NextLineHelp) + || (self.use_long && arg.name() != ""); + debugln!("Help::help: Next Line...{:?}", nlh); + + let spcs = if nlh || self.force_next_line { + 12 // "tab" * 3 + } else { + self.longest + 12 + }; + + let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w; + + // Is help on next line, if so then indent + if nlh || self.force_next_line { + write!(self.writer, "\n{}{}{}", TAB, TAB, TAB)?; + } + + debug!("Help::help: Too long..."); + if too_long && spcs <= self.term_w || h.contains("{n}") { + sdebugln!("Yes"); + debugln!("Help::help: help...{}", help); + debugln!("Help::help: help width...{}", str_width(&*help)); + // Determine how many newlines we need to insert + let avail_chars = self.term_w - spcs; + debugln!("Help::help: Usable space...{}", avail_chars); + help = wrap_help(&help.replace("{n}", "\n"), avail_chars); + } else { + sdebugln!("No"); + } + if let Some(part) = help.lines().next() { + write!(self.writer, "{}", part)?; + } + for part in help.lines().skip(1) { + writeln!(self.writer)?; + if nlh || self.force_next_line { + write!(self.writer, "{}{}{}", TAB, TAB, TAB)?; + } else if arg.has_switch() { + write_nspaces!(self.writer, self.longest + 12); + } else { + write_nspaces!(self.writer, self.longest + 8); + } + write!(self.writer, "{}", part)?; + } + if !help.contains('\n') && (nlh || self.force_next_line) { + writeln!(self.writer)?; + } + Ok(()) + } + + fn spec_vals(&self, a: &ArgWithDisplay) -> String { + debugln!("Help::spec_vals: a={}", a); + let mut spec_vals = vec![]; + if let Some(ref env) = a.env() { + debugln!( + "Help::spec_vals: Found environment variable...[{:?}:{:?}]", + env.0, + env.1 + ); + let env_val = if !a.is_set(ArgSettings::HideEnvValues) { + format!( + "={}", + env.1.map_or(Cow::Borrowed(""), |val| val.to_string_lossy()) + ) + } else { + String::new() + }; + let env_info = format!(" [env: {}{}]", env.0.to_string_lossy(), env_val); + spec_vals.push(env_info); + } + if !a.is_set(ArgSettings::HideDefaultValue) { + if let Some(pv) = a.default_val() { + debugln!("Help::spec_vals: Found default value...[{:?}]", pv); + spec_vals.push(format!( + " [default: {}]", + if self.color { + self.cizer.good(pv.to_string_lossy()) + } else { + Format::None(pv.to_string_lossy()) + } + )); + } + } + if let Some(ref aliases) = a.aliases() { + debugln!("Help::spec_vals: Found aliases...{:?}", aliases); + spec_vals.push(format!( + " [aliases: {}]", + if self.color { + aliases + .iter() + .map(|v| format!("{}", self.cizer.good(v))) + .collect::>() + .join(", ") + } else { + aliases.join(", ") + } + )); + } + if !self.hide_pv && !a.is_set(ArgSettings::HidePossibleValues) { + if let Some(pv) = a.possible_vals() { + debugln!("Help::spec_vals: Found possible vals...{:?}", pv); + spec_vals.push(if self.color { + format!( + " [possible values: {}]", + pv.iter() + .map(|v| format!("{}", self.cizer.good(v))) + .collect::>() + .join(", ") + ) + } else { + format!(" [possible values: {}]", pv.join(", ")) + }); + } + } + spec_vals.join(" ") + } +} + +fn should_show_arg(use_long: bool, arg: &ArgWithOrder) -> bool { + if arg.is_set(ArgSettings::Hidden) { + return false; + } + + (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long) + || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long) + || arg.is_set(ArgSettings::NextLineHelp) +} + +// Methods to write Parser help. +impl<'a> Help<'a> { + /// Writes help for all arguments (options, flags, args, subcommands) + /// including titles of a Parser Object to the wrapped stream. + pub fn write_all_args(&mut self, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_all_args;"); + let flags = parser.has_flags(); + let pos = parser + .positionals() + .filter(|arg| !arg.is_set(ArgSettings::Hidden)) + .count() + > 0; + let opts = parser.has_opts(); + let subcmds = parser.has_visible_subcommands(); + + let unified_help = parser.is_set(AppSettings::UnifiedHelpMessage); + + let mut first = true; + + if unified_help && (flags || opts) { + let opts_flags = parser + .flags() + .map(as_arg_trait) + .chain(parser.opts().map(as_arg_trait)); + color!(self, "OPTIONS:\n", warning)?; + self.write_args(opts_flags)?; + first = false; + } else { + if flags { + color!(self, "FLAGS:\n", warning)?; + self.write_args(parser.flags().map(as_arg_trait))?; + first = false; + } + if opts { + if !first { + self.writer.write_all(b"\n\n")?; + } + color!(self, "OPTIONS:\n", warning)?; + self.write_args(parser.opts().map(as_arg_trait))?; + first = false; + } + } + + if pos { + if !first { + self.writer.write_all(b"\n\n")?; + } + color!(self, "ARGS:\n", warning)?; + self.write_args_unsorted(parser.positionals().map(as_arg_trait))?; + first = false; + } + + if subcmds { + if !first { + self.writer.write_all(b"\n\n")?; + } + color!(self, "SUBCOMMANDS:\n", warning)?; + self.write_subcommands(parser)?; + } + + Ok(()) + } + + /// Writes help for subcommands of a Parser Object to the wrapped stream. + fn write_subcommands(&mut self, parser: &Parser) -> io::Result<()> { + debugln!("Help::write_subcommands;"); + // The shortest an arg can legally be is 2 (i.e. '-x') + self.longest = 2; + let mut ord_m = VecMap::new(); + for sc in parser + .subcommands + .iter() + .filter(|s| !s.p.is_set(AppSettings::Hidden)) + { + let btm = ord_m.entry(sc.p.meta.disp_ord).or_insert(BTreeMap::new()); + self.longest = cmp::max(self.longest, str_width(sc.p.meta.name.as_str())); + //self.longest = cmp::max(self.longest, sc.p.meta.name.len()); + btm.insert(sc.p.meta.name.clone(), sc.clone()); + } + + let mut first = true; + for btm in ord_m.values() { + for sc in btm.values() { + if first { + first = false; + } else { + self.writer.write_all(b"\n")?; + } + self.write_arg(sc)?; + } + } + Ok(()) + } + + /// Writes version of a Parser Object to the wrapped stream. + fn write_version(&mut self, parser: &Parser) -> io::Result<()> { + debugln!("Help::write_version;"); + write!(self.writer, "{}", parser.meta.version.unwrap_or(""))?; + Ok(()) + } + + /// Writes binary name of a Parser Object to the wrapped stream. + fn write_bin_name(&mut self, parser: &Parser) -> io::Result<()> { + debugln!("Help::write_bin_name;"); + macro_rules! write_name { + () => {{ + let mut name = parser.meta.name.clone(); + name = name.replace("{n}", "\n"); + color!(self, wrap_help(&name, self.term_w), good)?; + }}; + } + if let Some(bn) = parser.meta.bin_name.as_ref() { + if bn.contains(' ') { + // Incase we're dealing with subcommands i.e. git mv is translated to git-mv + color!(self, bn.replace(" ", "-"), good)? + } else { + write_name!(); + } + } else { + write_name!(); + } + Ok(()) + } + + /// Writes default help for a Parser Object to the wrapped stream. + pub fn write_default_help(&mut self, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_default_help;"); + if let Some(h) = parser.meta.pre_help { + self.write_before_after_help(h)?; + self.writer.write_all(b"\n\n")?; + } + + macro_rules! write_thing { + ($thing:expr) => {{ + let mut owned_thing = $thing.to_owned(); + owned_thing = owned_thing.replace("{n}", "\n"); + write!(self.writer, "{}\n", wrap_help(&owned_thing, self.term_w))? + }}; + } + // Print the version + self.write_bin_name(parser)?; + self.writer.write_all(b" ")?; + self.write_version(parser)?; + self.writer.write_all(b"\n")?; + if let Some(author) = parser.meta.author { + write_thing!(author) + } + // if self.use_long { + // if let Some(about) = parser.meta.long_about { + // debugln!("Help::write_default_help: writing long about"); + // write_thing!(about) + // } else if let Some(about) = parser.meta.about { + // debugln!("Help::write_default_help: writing about"); + // write_thing!(about) + // } + // } else + if let Some(about) = parser.meta.long_about { + debugln!("Help::write_default_help: writing long about"); + write_thing!(about) + } else if let Some(about) = parser.meta.about { + debugln!("Help::write_default_help: writing about"); + write_thing!(about) + } + + color!(self, "\nUSAGE:", warning)?; + write!( + self.writer, + "\n{}{}\n\n", + TAB, + usage::create_usage_no_title(parser, &[]) + )?; + + let flags = parser.has_flags(); + let pos = parser.has_positionals(); + let opts = parser.has_opts(); + let subcmds = parser.has_subcommands(); + + if flags || opts || pos || subcmds { + self.write_all_args(parser)?; + } + + if let Some(h) = parser.meta.more_help { + if flags || opts || pos || subcmds { + self.writer.write_all(b"\n\n")?; + } + self.write_before_after_help(h)?; + } + + self.writer.flush().map_err(Error::from) + } +} + +/// Possible results for a copying function that stops when a given +/// byte was found. +enum CopyUntilResult { + DelimiterFound(usize), + DelimiterNotFound(usize), + ReaderEmpty, + ReadError(io::Error), + WriteError(io::Error), +} + +/// Copies the contents of a reader into a writer until a delimiter byte is found. +/// On success, the total number of bytes that were +/// copied from reader to writer is returned. +fn copy_until(r: &mut R, w: &mut W, delimiter_byte: u8) -> CopyUntilResult { + debugln!("copy_until;"); + + let mut count = 0; + for wb in r.bytes() { + match wb { + Ok(b) => { + if b == delimiter_byte { + return CopyUntilResult::DelimiterFound(count); + } + match w.write(&[b]) { + Ok(c) => count += c, + Err(e) => return CopyUntilResult::WriteError(e), + } + } + Err(e) => return CopyUntilResult::ReadError(e), + } + } + if count > 0 { + CopyUntilResult::DelimiterNotFound(count) + } else { + CopyUntilResult::ReaderEmpty + } +} + +/// Copies the contents of a reader into a writer until a {tag} is found, +/// copying the tag content to a buffer and returning its size. +/// In addition to errors, there are three possible outputs: +/// - `None`: The reader was consumed. +/// - `Some(Ok(0))`: No tag was captured but the reader still contains data. +/// - `Some(Ok(length>0))`: a tag with `length` was captured to the `tag_buffer`. +fn copy_and_capture( + r: &mut R, + w: &mut W, + tag_buffer: &mut Cursor>, +) -> Option> { + use self::CopyUntilResult::*; + debugln!("copy_and_capture;"); + + // Find the opening byte. + match copy_until(r, w, b'{') { + // The end of the reader was reached without finding the opening tag. + // (either with or without having copied data to the writer) + // Return None indicating that we are done. + ReaderEmpty | DelimiterNotFound(_) => None, + + // Something went wrong. + ReadError(e) | WriteError(e) => Some(Err(e)), + + // The opening byte was found. + // (either with or without having copied data to the writer) + DelimiterFound(_) => { + // Lets reset the buffer first and find out how long it is. + tag_buffer.set_position(0); + let buffer_size = tag_buffer.get_ref().len(); + + // Find the closing byte,limiting the reader to the length of the buffer. + let mut rb = r.take(buffer_size as u64); + match copy_until(&mut rb, tag_buffer, b'}') { + // We were already at the end of the reader. + // Return None indicating that we are done. + ReaderEmpty => None, + + // The closing tag was found. + // Return the tag_length. + DelimiterFound(tag_length) => Some(Ok(tag_length)), + + // The end of the reader was found without finding the closing tag. + // Write the opening byte and captured text to the writer. + // Return 0 indicating that nothing was captured but the reader still contains data. + DelimiterNotFound(not_tag_length) => match w.write(b"{") { + Err(e) => Some(Err(e)), + _ => match w.write(&tag_buffer.get_ref()[0..not_tag_length]) { + Err(e) => Some(Err(e)), + _ => Some(Ok(0)), + }, + }, + + ReadError(e) | WriteError(e) => Some(Err(e)), + } + } + } +} + +// Methods to write Parser help using templates. +impl<'a> Help<'a> { + /// Write help to stream for the parser in the format defined by the template. + /// + /// Tags arg given inside curly brackets: + /// Valid tags are: + /// * `{bin}` - Binary name. + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments, + /// and subcommands) including titles. + /// * `{unified}` - Unified help for options and flags. + /// * `{flags}` - Help for flags. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positionals arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{after-help}` - Info to be displayed after the help message. + /// * `{before-help}` - Info to be displayed before the help message. + /// + /// The template system is, on purpose, very simple. Therefore the tags have to written + /// in the lowercase and without spacing. + fn write_templated_help(&mut self, parser: &Parser, template: &str) -> ClapResult<()> { + debugln!("Help::write_templated_help;"); + let mut tmplr = Cursor::new(&template); + let mut tag_buf = Cursor::new(vec![0u8; 15]); + + // The strategy is to copy the template from the reader to wrapped stream + // until a tag is found. Depending on its value, the appropriate content is copied + // to the wrapped stream. + // The copy from template is then resumed, repeating this sequence until reading + // the complete template. + + loop { + let tag_length = match copy_and_capture(&mut tmplr, &mut self.writer, &mut tag_buf) { + None => return Ok(()), + Some(Err(e)) => return Err(Error::from(e)), + Some(Ok(val)) if val > 0 => val, + _ => continue, + }; + + debugln!("Help::write_template_help:iter: tag_buf={};", unsafe { + String::from_utf8_unchecked( + tag_buf.get_ref()[0..tag_length] + .iter() + .map(|&i| i) + .collect::>(), + ) + }); + match &tag_buf.get_ref()[0..tag_length] { + b"?" => { + self.writer.write_all(b"Could not decode tag name")?; + } + b"bin" => { + self.write_bin_name(parser)?; + } + b"version" => { + write!( + self.writer, + "{}", + parser.meta.version.unwrap_or("unknown version") + )?; + } + b"author" => { + write!( + self.writer, + "{}", + parser.meta.author.unwrap_or("unknown author") + )?; + } + b"about" => { + write!( + self.writer, + "{}", + parser.meta.about.unwrap_or("unknown about") + )?; + } + b"long-about" => { + write!( + self.writer, + "{}", + parser.meta.long_about.unwrap_or("unknown about") + )?; + } + b"usage" => { + write!(self.writer, "{}", usage::create_usage_no_title(parser, &[]))?; + } + b"all-args" => { + self.write_all_args(parser)?; + } + b"unified" => { + let opts_flags = parser + .flags() + .map(as_arg_trait) + .chain(parser.opts().map(as_arg_trait)); + self.write_args(opts_flags)?; + } + b"flags" => { + self.write_args(parser.flags().map(as_arg_trait))?; + } + b"options" => { + self.write_args(parser.opts().map(as_arg_trait))?; + } + b"positionals" => { + self.write_args(parser.positionals().map(as_arg_trait))?; + } + b"subcommands" => { + self.write_subcommands(parser)?; + } + b"after-help" => { + write!( + self.writer, + "{}", + parser.meta.more_help.unwrap_or("unknown after-help") + )?; + } + b"before-help" => { + write!( + self.writer, + "{}", + parser.meta.pre_help.unwrap_or("unknown before-help") + )?; + } + // Unknown tag, write it back. + r => { + self.writer.write_all(b"{")?; + self.writer.write_all(r)?; + self.writer.write_all(b"}")?; + } + } + } + } +} + +fn wrap_help(help: &str, avail_chars: usize) -> String { + let wrapper = textwrap::Wrapper::new(avail_chars).break_words(false); + help.lines() + .map(|line| wrapper.fill(line)) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod test { + use super::wrap_help; + + #[test] + fn wrap_help_last_word() { + let help = String::from("foo bar baz"); + assert_eq!(wrap_help(&help, 5), "foo\nbar\nbaz"); + } +} diff --git a/bash-5.1/vendor/clap/src/app/meta.rs b/bash-5.1/vendor/clap/src/app/meta.rs new file mode 100644 index 0000000..8916101 --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/meta.rs @@ -0,0 +1,35 @@ +#[doc(hidden)] +#[allow(missing_debug_implementations)] +#[derive(Default, Clone)] +pub struct AppMeta<'b> { + pub name: String, + pub bin_name: Option, + pub author: Option<&'b str>, + pub version: Option<&'b str>, + pub long_version: Option<&'b str>, + pub about: Option<&'b str>, + pub long_about: Option<&'b str>, + pub more_help: Option<&'b str>, + pub pre_help: Option<&'b str>, + pub aliases: Option>, // (name, visible) + pub usage_str: Option<&'b str>, + pub usage: Option, + pub help_str: Option<&'b str>, + pub disp_ord: usize, + pub term_w: Option, + pub max_w: Option, + pub template: Option<&'b str>, +} + +impl<'b> AppMeta<'b> { + pub fn new() -> Self { + Default::default() + } + pub fn with_name(s: String) -> Self { + AppMeta { + name: s, + disp_ord: 999, + ..Default::default() + } + } +} diff --git a/bash-5.1/vendor/clap/src/app/mod.rs b/bash-5.1/vendor/clap/src/app/mod.rs new file mode 100644 index 0000000..c8ae912 --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/mod.rs @@ -0,0 +1,1909 @@ +mod help; +mod meta; +pub mod parser; +mod settings; +mod usage; +mod validator; + +// Std +use std::result::Result as StdResult; +use std::{ + env, + ffi::{OsStr, OsString}, + fmt, + io::{self, BufRead, BufWriter, Write}, + path::Path, + process, + rc::Rc, +}; + +// Third Party +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::errors::Result as ClapResult; +use crate::{ + app::{help::Help, parser::Parser}, + args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings}, + completions::Shell, + map::{self, VecMap}, +}; +pub use settings::AppSettings; + +/// Used to create a representation of a command line program and all possible command line +/// arguments. Application settings are set using the "builder pattern" with the +/// [`App::get_matches`] family of methods being the terminal methods that starts the +/// runtime-parsing process. These methods then return information about the user supplied +/// arguments (or lack there of). +/// +/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may +/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method +/// called). +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{App, Arg}; +/// let m = App::new("My Program") +/// .author("Me, me@mail.com") +/// .version("1.0.2") +/// .about("Explains in brief what the program does") +/// .arg( +/// Arg::with_name("in_file").index(1) +/// ) +/// .after_help("Longer explanation to appear after the options when \ +/// displaying the help information from --help or -h") +/// .get_matches(); +/// +/// // Your program logic starts here... +/// ``` +/// [`App::get_matches`]: ./struct.App.html#method.get_matches +#[allow(missing_debug_implementations)] +pub struct App<'a, 'b> +where + 'a: 'b, +{ + #[doc(hidden)] + pub p: Parser<'a, 'b>, +} + +impl<'a, 'b> App<'a, 'b> { + /// Creates a new instance of an application requiring a name. The name may be, but doesn't + /// have to be same as the binary. The name will be displayed to the user when they request to + /// print version or help and usage information. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let prog = App::new("My Program") + /// # ; + /// ``` + pub fn new>(n: S) -> Self { + App { + p: Parser::with_name(n.into()), + } + } + + /// Get the name of the app + pub fn get_name(&self) -> &str { + &self.p.meta.name + } + + /// Get the name of the binary + pub fn get_bin_name(&self) -> Option<&str> { + self.p.meta.bin_name.as_deref() + } + + /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`] + /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let prog = App::with_defaults("My Program") + /// # ; + /// ``` + /// [`crate_authors!`]: ./macro.crate_authors!.html + /// [`crate_version!`]: ./macro.crate_version!.html + /// [`App::author`]: ./struct.App.html#method.author + /// [`App::version`]: ./struct.App.html#method.author + #[deprecated( + since = "2.14.1", + note = "Can never work; use explicit App::author() and App::version() calls instead" + )] + pub fn with_defaults>(n: S) -> Self { + let mut a = App { + p: Parser::with_name(n.into()), + }; + a.p.meta.author = Some("Kevin K. "); + a.p.meta.version = Some("2.19.2"); + a + } + + /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML + /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use + /// for using YAML is when supporting multiple languages and dialects, as each language could + /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your + /// `Cargo.toml` + /// + /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in + /// your settings for the `[dependencies.clap]` table of your `Cargo.toml` + /// + /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading + /// the YAML file at compile time (relative to the current file, like modules work). That YAML + /// object can then be passed to this function. + /// + /// # Panics + /// + /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to + /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes + /// without error, you needn't worry because the YAML is properly formatted. + /// + /// # Examples + /// + /// The following example shows how to load a properly formatted YAML file to build an instance + /// of an [`App`] struct. + /// + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::App; + /// # fn main() { + /// let yml = load_yaml!("app.yml"); + /// let app = App::from_yaml(yml); + /// + /// // continued logic goes here, such as `app.get_matches()` etc. + /// # } + /// ``` + /// [`App`]: ./struct.App.html + /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.rs + /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.yml + /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html + #[cfg(feature = "yaml")] + pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> { + App::from(yaml) + } + + /// Sets a string of author(s) that will be displayed to the user when they + /// request the help information with `--help` or `-h`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to automatically set your + /// application's author(s) to the same thing as your crate at compile time. See the [`examples/`] + /// directory for more information + /// + /// See the [`examples/`] + /// directory for more information + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .author("Me, me@mymain.com") + /// # ; + /// ``` + /// [`crate_authors!`]: ./macro.crate_authors!.html + /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples + pub fn author>(mut self, author: S) -> Self { + self.p.meta.author = Some(author.into()); + self + } + + /// Overrides the system-determined binary name. This should only be used when absolutely + /// necessary, such as when the binary name for your application is misleading, or perhaps + /// *not* how the user should invoke your program. + /// + /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting + /// **should** be used! + /// + /// **NOTE:** This command **should not** be used for [`SubCommand`]s. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("My Program") + /// .bin_name("my_binary") + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn bin_name>(mut self, name: S) -> Self { + self.p.meta.bin_name = Some(name.into()); + self + } + + /// Sets a string describing what the program does. This will be displayed when displaying help + /// information with `-h`. + /// + /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests + /// `--help` clap will still display the contents of `about` appropriately + /// + /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be + /// concise + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .about("Does really amazing things to great people") + /// # ; + /// ``` + /// [`App::long_about`]: ./struct.App.html#method.long_about + pub fn about>(mut self, about: S) -> Self { + self.p.meta.about = Some(about.into()); + self + } + + /// Sets a string describing what the program does. This will be displayed when displaying help + /// information. + /// + /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests + /// `-h` clap will still display the contents of `long_about` appropriately + /// + /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be + /// concise + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .long_about( + /// "Does really amazing things to great people. Now let's talk a little + /// more in depth about how this subcommand really works. It may take about + /// a few lines of text, but that's ok!") + /// # ; + /// ``` + /// [`App::about`]: ./struct.App.html#method.about + pub fn long_about>(mut self, about: S) -> Self { + self.p.meta.long_about = Some(about.into()); + self + } + + /// Sets the program's name. This will be displayed when displaying help information. + /// + /// **Pro-top:** This function is particularly useful when configuring a program via + /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's + /// name from its `Cargo.toml`. + /// + /// # Examples + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::App; + /// # fn main() { + /// let yml = load_yaml!("app.yml"); + /// let app = App::from_yaml(yml) + /// .name(crate_name!()); + /// + /// // continued logic goes here, such as `app.get_matches()` etc. + /// # } + /// ``` + /// + /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml + /// [`crate_name!`]: ./macro.crate_name.html + pub fn name>(mut self, name: S) -> Self { + self.p.meta.name = name.into(); + self + } + + /// Adds additional help information to be displayed in addition to auto-generated help. This + /// information is displayed **after** the auto-generated help information. This is often used + /// to describe how to use the arguments, or caveats to be noted. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .after_help("Does really amazing things to great people...but be careful with -R") + /// # ; + /// ``` + pub fn after_help>(mut self, help: S) -> Self { + self.p.meta.more_help = Some(help.into()); + self + } + + /// Adds additional help information to be displayed in addition to auto-generated help. This + /// information is displayed **before** the auto-generated help information. This is often used + /// for header information. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .before_help("Some info I'd like to appear before the help info") + /// # ; + /// ``` + pub fn before_help>(mut self, help: S) -> Self { + self.p.meta.pre_help = Some(help.into()); + self + } + + /// Sets a string of the version number to be displayed when displaying version or help + /// information with `-V`. + /// + /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user + /// requests `--version` clap will still display the contents of `version` appropriately + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your + /// application's version to the same thing as your crate at compile time. See the [`examples/`] + /// directory for more information + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version("v0.1.24") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples + /// [`App::long_version`]: ./struct.App.html#method.long_version + pub fn version>(mut self, ver: S) -> Self { + self.p.meta.version = Some(ver.into()); + self + } + + /// Sets a string of the version number to be displayed when displaying version or help + /// information with `--version`. + /// + /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user + /// requests `-V` clap will still display the contents of `long_version` appropriately + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your + /// application's version to the same thing as your crate at compile time. See the [`examples/`] + /// directory for more information + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .long_version( + /// "v0.1.24 + /// commit: abcdef89726d + /// revision: 123 + /// release: 2 + /// binary: myprog") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples + /// [`App::version`]: ./struct.App.html#method.version + pub fn long_version>(mut self, ver: S) -> Self { + self.p.meta.long_version = Some(ver.into()); + self + } + + /// Sets a custom usage string to override the auto-generated usage string. + /// + /// This will be displayed to the user when errors are found in argument parsing, or when you + /// call [`ArgMatches::usage`] + /// + /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage strings. After this + /// setting is set, this will be the only usage string displayed to the user! + /// + /// **NOTE:** You do not need to specify the "USAGE: \n\t" portion, as that will + /// still be applied by `clap`, you only need to specify the portion starting + /// with the binary name. + /// + /// **NOTE:** This will not replace the entire help message, *only* the portion + /// showing the usage. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .usage("myapp [-clDas] ") + /// # ; + /// ``` + /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage + pub fn usage>(mut self, usage: S) -> Self { + self.p.meta.usage_str = Some(usage.into()); + self + } + + /// Sets a custom help message and overrides the auto-generated one. This should only be used + /// when the auto-generated message does not suffice. + /// + /// This will be displayed to the user when they use `--help` or `-h` + /// + /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated. + /// + /// **NOTE:** This **only** replaces the help message for the current command, meaning if you + /// are using subcommands, those help messages will still be auto-generated unless you + /// specify a [`Arg::help`] for them as well. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myapp") + /// .help("myapp v1.0\n\ + /// Does awesome things\n\ + /// (C) me@mail.com\n\n\ + /// + /// USAGE: myapp \n\n\ + /// + /// Options:\n\ + /// -h, --help Display this message\n\ + /// -V, --version Display version info\n\ + /// -s Do something with stuff\n\ + /// -v Be verbose\n\n\ + /// + /// Commmands:\n\ + /// help Prints this message\n\ + /// work Do some work") + /// # ; + /// ``` + /// [`Arg::help`]: ./struct.Arg.html#method.help + pub fn help>(mut self, help: S) -> Self { + self.p.meta.help_str = Some(help.into()); + self + } + + /// Sets the [`short`] for the auto-generated `help` argument. + /// + /// By default `clap` automatically assigns `h`, but this can be overridden if you have a + /// different argument which you'd prefer to use the `-h` short with. This can be done by + /// defining your own argument with a lowercase `h` as the [`short`]. + /// + /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of + /// your own. + /// + /// **NOTE:** Any leading `-` characters will be stripped, and only the first + /// non `-` character will be used as the [`short`] version + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h` + /// # ; + /// ``` + /// [`short`]: ./struct.Arg.html#method.short + pub fn help_short + 'b>(mut self, s: S) -> Self { + self.p.help_short(s.as_ref()); + self + } + + /// Sets the [`short`] for the auto-generated `version` argument. + /// + /// By default `clap` automatically assigns `V`, but this can be overridden if you have a + /// different argument which you'd prefer to use the `-V` short with. This can be done by + /// defining your own argument with an uppercase `V` as the [`short`]. + /// + /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of + /// your own. + /// + /// **NOTE:** Any leading `-` characters will be stripped, and only the first + /// non `-` character will be used as the `short` version + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version_short("v") // Using a lowercase `v` instead of the default capital `V` + /// # ; + /// ``` + /// [`short`]: ./struct.Arg.html#method.short + pub fn version_short>(mut self, s: S) -> Self { + self.p.version_short(s.as_ref()); + self + } + + /// Sets the help text for the auto-generated `help` argument. + /// + /// By default `clap` sets this to `"Prints help information"`, but if you're using a + /// different convention for your help messages and would prefer a different phrasing you can + /// override it. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .help_message("Print help information") // Perhaps you want imperative help messages + /// + /// # ; + /// ``` + pub fn help_message>(mut self, s: S) -> Self { + self.p.help_message = Some(s.into()); + self + } + + /// Sets the help text for the auto-generated `version` argument. + /// + /// By default `clap` sets this to `"Prints version information"`, but if you're using a + /// different convention for your help messages and would prefer a different phrasing then you + /// can change it. + /// + /// # Examples + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version_message("Print version information") // Perhaps you want imperative help messages + /// # ; + /// ``` + pub fn version_message>(mut self, s: S) -> Self { + self.p.version_message = Some(s.into()); + self + } + + /// Sets the help template to be used, overriding the default format. + /// + /// Tags arg given inside curly brackets. + /// + /// Valid tags are: + /// + /// * `{bin}` - Binary name. + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{about}` - General description (from [`App::about`]) + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments, + /// and subcommands) including titles. + /// * `{unified}` - Unified help for options and flags. Note, you must *also* set + /// [`AppSettings::UnifiedHelpMessage`] to fully merge both options and + /// flags, otherwise the ordering is "best effort" + /// * `{flags}` - Help for flags. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positionals arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{after-help}` - Help from [`App::after_help`] + /// * `{before-help}` - Help from [`App::before_help`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version("1.0") + /// .template("{bin} ({version}) - {usage}") + /// # ; + /// ``` + /// **NOTE:** The template system is, on purpose, very simple. Therefore the tags have to be + /// written in lowercase and without spacing. + /// + /// [`App::about`]: ./struct.App.html#method.about + /// [`App::after_help`]: ./struct.App.html#method.after_help + /// [`App::before_help`]: ./struct.App.html#method.before_help + /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage + pub fn template>(mut self, s: S) -> Self { + self.p.meta.template = Some(s.into()); + self + } + + /// Enables a single command, or [`SubCommand`], level settings. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::WaitOnError) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn setting(mut self, setting: AppSettings) -> Self { + self.p.set(setting); + self + } + + /// Enables multiple command, or [`SubCommand`], level settings + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .settings(&[AppSettings::SubcommandRequired, + /// AppSettings::WaitOnError]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.p.set(*s); + } + self + } + + /// Enables a single setting that is propagated down through all child [`SubCommand`]s. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::SubcommandRequired) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn global_setting(mut self, setting: AppSettings) -> Self { + self.p.set(setting); + self.p.g_settings.set(setting); + self + } + + /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_settings(&[AppSettings::SubcommandRequired, + /// AppSettings::ColoredHelp]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn global_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.p.set(*s); + self.p.g_settings.set(*s) + } + self + } + + /// Disables a single command, or [`SubCommand`], level setting. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .unset_setting(AppSettings::ColorAuto) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn unset_setting(mut self, setting: AppSettings) -> Self { + self.p.unset(setting); + self + } + + /// Disables multiple command, or [`SubCommand`], level settings. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .unset_settings(&[AppSettings::ColorAuto, + /// AppSettings::AllowInvalidUtf8]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.p.unset(*s); + } + self + } + + /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will + /// ignore terminal widths and use source formatting. + /// + /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows + /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width + /// cannot be determined, `clap` defaults to `120`. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// **NOTE:** This setting must be set **before** any subcommands are added! + /// + /// # Platform Specific + /// + /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width. + /// Even on those platforms, this setting is useful if for any reason the terminal width + /// cannot be determined. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .set_term_width(80) + /// # ; + /// ``` + pub fn set_term_width(mut self, width: usize) -> Self { + self.p.meta.term_w = Some(width); + self + } + + /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal + /// widths and use source formatting. + /// + /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows + /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to + /// limit the size (e.g. when the terminal is running fullscreen). + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// **NOTE:** This setting must be set **before** any subcommands are added! + /// + /// # Platform Specific + /// + /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .max_term_width(100) + /// # ; + /// ``` + pub fn max_term_width(mut self, w: usize) -> Self { + self.p.meta.max_w = Some(w); + self + } + + /// Adds an [argument] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// // Adding a single "flag" argument with a short and help text, using Arg::with_name() + /// .arg( + /// Arg::with_name("debug") + /// .short("d") + /// .help("turns on debugging mode") + /// ) + /// // Adding a single "option" argument with a short, a long, and help text using the less + /// // verbose Arg::from_usage() + /// .arg( + /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'") + /// ) + /// # ; + /// ``` + /// [argument]: ./struct.Arg.html + pub fn arg>>(mut self, a: A) -> Self { + self.p.add_arg(a.into()); + self + } + + /// Adds multiple [arguments] to the list of valid possibilities + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .args( + /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"), + /// Arg::with_name("input").index(1).help("the input file to use")] + /// ) + /// # ; + /// ``` + /// [arguments]: ./struct.Arg.html + pub fn args(mut self, args: &[Arg<'a, 'b>]) -> Self { + for arg in args { + self.p.add_arg_ref(arg); + } + self + } + + /// A convenience method for adding a single [argument] from a usage type string. The string + /// used follows the same rules and syntax as [`Arg::from_usage`] + /// + /// **NOTE:** The downside to using this method is that you can not set any additional + /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .arg_from_usage("-c --config= 'Sets a configuration file to use'") + /// # ; + /// ``` + /// [argument]: ./struct.Arg.html + /// [`Arg`]: ./struct.Arg.html + /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage + pub fn arg_from_usage(mut self, usage: &'a str) -> Self { + self.p.add_arg(Arg::from_usage(usage)); + self + } + + /// Adds multiple [arguments] at once from a usage string, one per line. See + /// [`Arg::from_usage`] for details on the syntax and rules supported. + /// + /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the + /// [`Arg`]s which [`Arg::from_usage`] supports. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .args_from_usage( + /// "-c --config=[FILE] 'Sets a configuration file to use' + /// [debug]... -d 'Sets the debugging level' + /// 'The input file to use'" + /// ) + /// # ; + /// ``` + /// [arguments]: ./struct.Arg.html + /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage + /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage + /// [`Arg`]: ./struct.Arg.html + pub fn args_from_usage(mut self, usage: &'a str) -> Self { + for line in usage.lines() { + let l = line.trim(); + if l.is_empty() { + continue; + } + self.p.add_arg(Arg::from_usage(l)); + } + self + } + + /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that + /// automatically dispatch as if this subcommand was used. This is more efficient, and easier + /// than creating multiple hidden subcommands as one only needs to check for the existence of + /// this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn alias>(mut self, name: S) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + als.push((name.into(), false)); + } else { + self.p.meta.aliases = Some(vec![(name.into(), false)]); + } + self + } + + /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that + /// automatically dispatch as if this subcommand was used. This is more efficient, and easier + /// than creating multiple hidden subcommands as one only needs to check for the existence of + /// this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .aliases(&["do-stuff", "do-tests", "tests"])) + /// .arg(Arg::with_name("input") + /// .help("the file to add") + /// .index(1) + /// .required(false)) + /// .get_matches_from(vec!["myprog", "do-tests"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn aliases(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + for n in names { + als.push((n, false)); + } + } else { + self.p.meta.aliases = Some(names.iter().map(|n| (*n, false)).collect::>()); + } + self + } + + /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with + /// [`App::alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .visible_alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App::alias`]: ./struct.App.html#method.alias + pub fn visible_alias>(mut self, name: S) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + als.push((name.into(), true)); + } else { + self.p.meta.aliases = Some(vec![(name.into(), true)]); + } + self + } + + /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined + /// with [`App::aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .visible_aliases(&["do-stuff", "tests"])) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App::aliases`]: ./struct.App.html#method.aliases + pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + for n in names { + als.push((n, true)); + } + } else { + self.p.meta.aliases = Some(names.iter().map(|n| (*n, true)).collect::>()); + } + self + } + + /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments. + /// By placing them in a logical group, you can build easier requirement and exclusion rules. + /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only* + /// one) argument from that group must be present at runtime. + /// + /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument. + /// Meaning any of the arguments that belong to that group will cause a failure if present with + /// the conflicting argument. + /// + /// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead + /// of determining exactly which argument was used. + /// + /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common + /// use + /// + /// # Examples + /// + /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, + /// of the arguments from the specified group is present at runtime. + /// + /// ```no_run + /// # use clap::{App, ArgGroup}; + /// App::new("app") + /// .args_from_usage( + /// "--set-ver [ver] 'set the version manually' + /// --major 'auto increase major' + /// --minor 'auto increase minor' + /// --patch 'auto increase patch'") + /// .group(ArgGroup::with_name("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true)) + /// # ; + /// ``` + /// [`ArgGroup`]: ./struct.ArgGroup.html + pub fn group(mut self, group: ArgGroup<'a>) -> Self { + self.p.add_group(group); + self + } + + /// Adds multiple [`ArgGroup`]s to the [`App`] at once. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, ArgGroup}; + /// App::new("app") + /// .args_from_usage( + /// "--set-ver [ver] 'set the version manually' + /// --major 'auto increase major' + /// --minor 'auto increase minor' + /// --patch 'auto increase patch' + /// -c [FILE] 'a config file' + /// -i [IFACE] 'an interface'") + /// .groups(&[ + /// ArgGroup::with_name("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true), + /// ArgGroup::with_name("input") + /// .args(&["c", "i"]) + /// ]) + /// # ; + /// ``` + /// [`ArgGroup`]: ./struct.ArgGroup.html + /// [`App`]: ./struct.App.html + pub fn groups(mut self, groups: &[ArgGroup<'a>]) -> Self { + for g in groups { + self = self.group(g.into()); + } + self + } + + /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively + /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage, + /// etc. They also function just like [`App`]s, in that they get their own auto generated help, + /// version, and usage. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// App::new("myprog") + /// .subcommand(SubCommand::with_name("config") + /// .about("Controls configuration features") + /// .arg_from_usage(" 'Required configuration file to use'")) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + pub fn subcommand(mut self, subcmd: App<'a, 'b>) -> Self { + self.p.add_subcommand(subcmd); + self + } + + /// Adds multiple subcommands to the list of valid possibilities by iterating over an + /// [`IntoIterator`] of [`SubCommand`]s + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// # App::new("myprog") + /// .subcommands( vec![ + /// SubCommand::with_name("config").about("Controls configuration functionality") + /// .arg(Arg::with_name("config_file").index(1)), + /// SubCommand::with_name("debug").about("Controls debug functionality")]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html + pub fn subcommands(mut self, subcmds: I) -> Self + where + I: IntoIterator>, + { + for subcmd in subcmds { + self.p.add_subcommand(subcmd); + } + self + } + + /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower + /// value will be displayed first in the help message. This is helpful when one would like to + /// emphasise frequently used subcommands, or prioritize those towards the top of the list. + /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be + /// displayed in alphabetical order. + /// + /// **NOTE:** The default is 999 for all subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, SubCommand}; + /// let m = App::new("cust-ord") + /// .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped + /// // alphabetically by name. Subcommands + /// // without a display_order have a value of + /// // 999 and are displayed alphabetically with + /// // all other 999 subcommands + /// .about("Some help and text")) + /// .subcommand(SubCommand::with_name("beta") + /// .display_order(1) // In order to force this subcommand to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other subcommands with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .about("I should be first!")) + /// .get_matches_from(vec![ + /// "cust-ord", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// USAGE: + /// cust-ord [FLAGS] [OPTIONS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// + /// SUBCOMMANDS: + /// beta I should be first! + /// alpha Some help and text + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn display_order(mut self, ord: usize) -> Self { + self.p.meta.disp_ord = ord; + self + } + + /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same + /// method as if someone ran `-h` to request the help message + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// let mut app = App::new("myprog"); + /// app.print_help(); + /// ``` + /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html + /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn print_help(&mut self) -> ClapResult<()> { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self.p.propagate_globals(); + self.p.propagate_settings(); + self.p.derive_display_order(); + + self.p.create_help_and_version(); + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + self.write_help(&mut buf_w) + } + + /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same + /// method as if someone ran `--help` to request the help message + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// let mut app = App::new("myprog"); + /// app.print_long_help(); + /// ``` + /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html + /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn print_long_help(&mut self) -> ClapResult<()> { + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + self.write_long_help(&mut buf_w) + } + + /// Writes the full help message to the user to a [`io::Write`] object in the same method as if + /// the user ran `-h` + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// **NOTE:** There is a known bug where this method does not write propagated global arguments + /// or autogenerated arguments (i.e. the default help/version args). Prefer + /// [`App::write_long_help`] instead if possible! + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn write_help(&self, w: &mut W) -> ClapResult<()> { + // PENDING ISSUE: 808 + // https://github.com/clap-rs/clap/issues/808 + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + // self.p.propagate_globals(); + // self.p.propagate_settings(); + // self.p.derive_display_order(); + // self.p.create_help_and_version(); + + Help::write_app_help(w, self, false) + } + + /// Writes the full help message to the user to a [`io::Write`] object in the same method as if + /// the user ran `--help` + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_long_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn write_long_help(&mut self, w: &mut W) -> ClapResult<()> { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self.p.propagate_globals(); + self.p.propagate_settings(); + self.p.derive_display_order(); + self.p.create_help_and_version(); + + Help::write_app_help(w, self, true) + } + + /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`. + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages + /// depending on if the user ran [`-V` (short)] or [`--version` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_version(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-V` (short)]: ./struct.App.html#method.version + /// [`--version` (long)]: ./struct.App.html#method.long_version + pub fn write_version(&self, w: &mut W) -> ClapResult<()> { + self.p.write_version(w, false).map_err(From::from) + } + + /// Writes the version message to the user to a [`io::Write`] object + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages + /// depending on if the user ran [`-V` (short)] or [`--version` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_long_version(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-V` (short)]: ./struct.App.html#method.version + /// [`--version` (long)]: ./struct.App.html#method.long_version + pub fn write_long_version(&self, w: &mut W) -> ClapResult<()> { + self.p.write_version(w, true).map_err(From::from) + } + + /// Generate a completions file for a specified shell at compile time. + /// + /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script" + /// + /// # Examples + /// + /// The following example generates a bash completion script via a `build.rs` script. In this + /// simple example, we'll demo a very small application with only a single subcommand and two + /// args. Real applications could be many multiple levels deep in subcommands, and have tens or + /// potentially hundreds of arguments. + /// + /// First, it helps if we separate out our `App` definition into a separate file. Whether you + /// do this as a function, or bare App definition is a matter of personal preference. + /// + /// ``` + /// // src/cli.rs + /// + /// use clap::{App, Arg, SubCommand}; + /// + /// pub fn build_cli() -> App<'static, 'static> { + /// App::new("compl") + /// .about("Tests completions") + /// .arg(Arg::with_name("file") + /// .help("some input file")) + /// .subcommand(SubCommand::with_name("test") + /// .about("tests things") + /// .arg(Arg::with_name("case") + /// .long("case") + /// .takes_value(true) + /// .help("the case to test"))) + /// } + /// ``` + /// + /// In our regular code, we can simply call this `build_cli()` function, then call + /// `get_matches()`, or any of the other normal methods directly after. For example: + /// + /// ```ignore + /// // src/main.rs + /// + /// mod cli; + /// + /// fn main() { + /// let m = cli::build_cli().get_matches(); + /// + /// // normal logic continues... + /// } + /// ``` + /// + /// Next, we set up our `Cargo.toml` to use a `build.rs` build script. + /// + /// ```toml + /// # Cargo.toml + /// build = "build.rs" + /// + /// [build-dependencies] + /// clap = "2.23" + /// ``` + /// + /// Next, we place a `build.rs` in our project root. + /// + /// ```ignore + /// extern crate clap; + /// + /// use clap::Shell; + /// + /// include!("src/cli.rs"); + /// + /// fn main() { + /// let outdir = match env::var_os("OUT_DIR") { + /// None => return, + /// Some(outdir) => outdir, + /// }; + /// let mut app = build_cli(); + /// app.gen_completions("myapp", // We need to specify the bin name manually + /// Shell::Bash, // Then say which shell to build completions for + /// outdir); // Then say where write the completions to + /// } + /// ``` + /// Now, once we compile there will be a `{bin_name}.bash` file in the directory. + /// Assuming we compiled with debug mode, it would be somewhere similar to + /// `/target/debug/build/myapp-/out/myapp.bash`. + /// + /// Fish shell completions will use the file format `{bin_name}.fish` + pub fn gen_completions, S: Into>( + &mut self, + bin_name: S, + for_shell: Shell, + out_dir: T, + ) { + self.p.meta.bin_name = Some(bin_name.into()); + self.p.gen_completions(for_shell, out_dir.into()); + } + + /// Generate a completions file for a specified shell at runtime. Until `cargo install` can + /// install extra files like a completion script, this may be used e.g. in a command that + /// outputs the contents of the completion script, to be redirected into a file by the user. + /// + /// # Examples + /// + /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions), + /// we can let users generate a completion script using a command: + /// + /// ```ignore + /// // src/main.rs + /// + /// mod cli; + /// use std::io; + /// + /// fn main() { + /// let matches = cli::build_cli().get_matches(); + /// + /// if matches.is_present("generate-bash-completions") { + /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout()); + /// } + /// + /// // normal logic continues... + /// } + /// + /// ``` + /// + /// Usage: + /// + /// ```shell + /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash + /// ``` + pub fn gen_completions_to>( + &mut self, + bin_name: S, + for_shell: Shell, + buf: &mut W, + ) { + self.p.meta.bin_name = Some(bin_name.into()); + self.p.gen_completions_to(for_shell, buf); + } + + /// Starts the parsing process, upon a failed parse an error will be displayed to the user and + /// the process will exit with the appropriate error code. By default this method gets all user + /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points, + /// which are legal on many platforms. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches(); + /// ``` + /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html + pub fn get_matches(self) -> ArgMatches<'a> { + self.get_matches_from(&mut env::args_os()) + } + + /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting + /// the process on failed parse. By default this method gets matches from [`env::args_os`] + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a + /// [`ErrorKind::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call + /// [`Error::exit`] or perform a [`std::process::exit`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_safe() + /// .unwrap_or_else( |e| e.exit() ); + /// ``` + /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html + /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed + /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed + /// [`Error::exit`]: ./struct.Error.html#method.exit + /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html + /// [`clap::Result`]: ./type.Result.html + /// [`clap::Error`]: ./struct.Error.html + /// [`kind`]: ./struct.Error.html + pub fn get_matches_safe(self) -> ClapResult> { + // Start the parsing + self.get_matches_from_safe(&mut env::args_os()) + } + + /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`] + /// and will automatically exit with an error message. This method, however, lets you specify + /// what iterator to use when performing matches, such as a [`Vec`] of your making. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`AppSettings::NoBinaryName`] is used + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_from(arg_vec); + /// ``` + /// [`App::get_matches`]: ./struct.App.html#method.get_matches + /// [`clap::Result`]: ./type.Result.html + /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html + /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName + pub fn get_matches_from(mut self, itr: I) -> ArgMatches<'a> + where + I: IntoIterator, + T: Into + Clone, + { + self.get_matches_from_safe_borrow(itr).unwrap_or_else(|e| { + // Otherwise, write to stderr and exit + if e.use_stderr() { + wlnerr!("{}", e.message); + if self.p.is_set(AppSettings::WaitOnError) { + wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); + let mut s = String::new(); + let i = io::stdin(); + i.lock().read_line(&mut s).unwrap(); + } + drop(self); + drop(e); + process::exit(1); + } + + drop(self); + e.exit() + }) + } + + /// Starts the parsing process. A combination of [`App::get_matches_from`], and + /// [`App::get_matches_safe`] + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::HelpDisplayed`] + /// or [`ErrorKind::VersionDisplayed`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`AppSettings::NoBinaryName`] is used + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_from_safe(arg_vec) + /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) }); + /// ``` + /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from + /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe + /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed + /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed + /// [`Error::exit`]: ./struct.Error.html#method.exit + /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html + /// [`clap::Error`]: ./struct.Error.html + /// [`Error::exit`]: ./struct.Error.html#method.exit + /// [`kind`]: ./struct.Error.html + /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName + pub fn get_matches_from_safe(mut self, itr: I) -> ClapResult> + where + I: IntoIterator, + T: Into + Clone, + { + self.get_matches_from_safe_borrow(itr) + } + + /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not + /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does* + /// consume `self`. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`AppSettings::NoBinaryName`] is used + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let mut app = App::new("myprog"); + /// // Args and options go here... + /// let matches = app.get_matches_from_safe_borrow(arg_vec) + /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) }); + /// ``` + /// [`App`]: ./struct.App.html + /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe + /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName + pub fn get_matches_from_safe_borrow(&mut self, itr: I) -> ClapResult> + where + I: IntoIterator, + T: Into + Clone, + { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + if !self.p.is_set(AppSettings::Propagated) { + self.p.propagate_globals(); + self.p.propagate_settings(); + self.p.derive_display_order(); + self.p.set(AppSettings::Propagated); + } + + let mut matcher = ArgMatcher::new(); + + let mut it = itr.into_iter(); + // Get the name of the program (argument 1 of env::args()) and determine the + // actual file + // that was used to execute the program. This is because a program called + // ./target/release/my_prog -a + // will have two arguments, './target/release/my_prog', '-a' but we don't want + // to display + // the full path when displaying help messages and such + if !self.p.is_set(AppSettings::NoBinaryName) { + if let Some(name) = it.next() { + let bn_os = name.into(); + let p = Path::new(&*bn_os); + if let Some(f) = p.file_name() { + if let Some(s) = f.to_os_string().to_str() { + if self.p.meta.bin_name.is_none() { + self.p.meta.bin_name = Some(s.to_owned()); + } + } + } + } + } + + // do the real parsing + if let Err(e) = self.p.get_matches_with(&mut matcher, &mut it.peekable()) { + return Err(e); + } + + let global_arg_vec: Vec<&str> = self.p.global_args.iter().map(|ga| ga.b.name).collect(); + matcher.propagate_globals(&global_arg_vec); + + Ok(matcher.into()) + } +} + +#[cfg(feature = "yaml")] +impl<'a> From<&'a Yaml> for App<'a, 'a> { + fn from(mut yaml: &'a Yaml) -> Self { + use crate::args::SubCommand; + // We WANT this to panic on error...so expect() is good. + let mut is_sc = None; + let mut a = if let Some(name) = yaml["name"].as_str() { + App::new(name) + } else { + let yaml_hash = yaml.as_hash().unwrap(); + let sc_key = yaml_hash.keys().nth(0).unwrap(); + is_sc = Some(yaml_hash.get(sc_key).unwrap()); + App::new(sc_key.as_str().unwrap()) + }; + yaml = if let Some(sc) = is_sc { sc } else { yaml }; + + macro_rules! yaml_str { + ($a:ident, $y:ident, $i:ident) => { + if let Some(v) = $y[stringify!($i)].as_str() { + $a = $a.$i(v); + } else if $y[stringify!($i)] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a string", + $y[stringify!($i)] + ); + } + }; + } + + yaml_str!(a, yaml, version); + yaml_str!(a, yaml, long_version); + yaml_str!(a, yaml, author); + yaml_str!(a, yaml, bin_name); + yaml_str!(a, yaml, about); + yaml_str!(a, yaml, long_about); + yaml_str!(a, yaml, before_help); + yaml_str!(a, yaml, after_help); + yaml_str!(a, yaml, template); + yaml_str!(a, yaml, usage); + yaml_str!(a, yaml, help); + yaml_str!(a, yaml, help_short); + yaml_str!(a, yaml, version_short); + yaml_str!(a, yaml, help_message); + yaml_str!(a, yaml, version_message); + yaml_str!(a, yaml, alias); + yaml_str!(a, yaml, visible_alias); + + if let Some(v) = yaml["display_order"].as_i64() { + a = a.display_order(v as usize); + } else if yaml["display_order"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a u64", + yaml["display_order"] + ); + } + if let Some(v) = yaml["setting"].as_str() { + a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["setting"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to an AppSetting", + yaml["setting"] + ); + } + if let Some(v) = yaml["settings"].as_vec() { + for ys in v { + if let Some(s) = ys.as_str() { + a = a.setting(s.parse().expect("unknown AppSetting found in YAML file")); + } + } + } else if let Some(v) = yaml["settings"].as_str() { + a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["settings"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a string", + yaml["settings"] + ); + } + if let Some(v) = yaml["global_setting"].as_str() { + a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["global_setting"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to an AppSetting", + yaml["setting"] + ); + } + if let Some(v) = yaml["global_settings"].as_vec() { + for ys in v { + if let Some(s) = ys.as_str() { + a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file")); + } + } + } else if let Some(v) = yaml["global_settings"].as_str() { + a = a.global_setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["global_settings"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a string", + yaml["global_settings"] + ); + } + + macro_rules! vec_or_str { + ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{ + let maybe_vec = $y[stringify!($as_vec)].as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { + $a = $a.$as_single(s); + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + } + } else { + if let Some(s) = $y[stringify!($as_vec)].as_str() { + $a = $a.$as_single(s); + } else if $y[stringify!($as_vec)] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to either a vec or string", + $y[stringify!($as_vec)] + ); + } + } + $a + }}; + } + + a = vec_or_str!(a, yaml, aliases, alias); + a = vec_or_str!(a, yaml, visible_aliases, visible_alias); + + if let Some(v) = yaml["args"].as_vec() { + for arg_yaml in v { + a = a.arg(Arg::from_yaml(arg_yaml.as_hash().unwrap())); + } + } + if let Some(v) = yaml["subcommands"].as_vec() { + for sc_yaml in v { + a = a.subcommand(SubCommand::from_yaml(sc_yaml)); + } + } + if let Some(v) = yaml["groups"].as_vec() { + for ag_yaml in v { + a = a.group(ArgGroup::from(ag_yaml.as_hash().unwrap())); + } + } + + a + } +} + +impl<'a, 'b> Clone for App<'a, 'b> { + fn clone(&self) -> Self { + App { p: self.p.clone() } + } +} + +impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> { + fn name(&self) -> &'n str { + "" + } + fn overrides(&self) -> Option<&[&'e str]> { + None + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + None + } + fn blacklist(&self) -> Option<&[&'e str]> { + None + } + fn required_unless(&self) -> Option<&[&'e str]> { + None + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + None + } + fn is_set(&self, _: ArgSettings) -> bool { + false + } + fn val_terminator(&self) -> Option<&'e str> { + None + } + fn set(&mut self, _: ArgSettings) { + unreachable!("App struct does not support AnyArg::set, this is a bug!") + } + fn has_switch(&self) -> bool { + false + } + fn max_vals(&self) -> Option { + None + } + fn num_vals(&self) -> Option { + None + } + fn possible_vals(&self) -> Option<&[&'e str]> { + None + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator(&self) -> Option<&Rc StdResult<(), String>>> { + None + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { + None + } + fn min_vals(&self) -> Option { + None + } + fn short(&self) -> Option { + None + } + fn long(&self) -> Option<&'e str> { + None + } + fn val_delim(&self) -> Option { + None + } + fn takes_value(&self) -> bool { + true + } + fn help(&self) -> Option<&'e str> { + self.p.meta.about + } + fn long_help(&self) -> Option<&'e str> { + self.p.meta.long_about + } + fn default_val(&self) -> Option<&'e OsStr> { + None + } + fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { + None + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + None + } + fn longest_filter(&self) -> bool { + true + } + fn aliases(&self) -> Option> { + if let Some(ref aliases) = self.p.meta.aliases { + let vis_aliases: Vec<_> = aliases + .iter() + .filter_map(|&(n, v)| if v { Some(n) } else { None }) + .collect(); + if vis_aliases.is_empty() { + None + } else { + Some(vis_aliases) + } + } else { + None + } + } +} + +impl<'n, 'e> fmt::Display for App<'n, 'e> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.p.meta.name) + } +} diff --git a/bash-5.1/vendor/clap/src/app/parser.rs b/bash-5.1/vendor/clap/src/app/parser.rs new file mode 100644 index 0000000..12cb2c1 --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/parser.rs @@ -0,0 +1,2236 @@ +// Std +#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] +use std::os::unix::ffi::OsStrExt; +use std::{ + cell::Cell, + ffi::{OsStr, OsString}, + fmt::Display, + fs::File, + io::{self, BufWriter, Write}, + iter::Peekable, + path::PathBuf, + slice::Iter, +}; + +// Internal +#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))] +use crate::osstringext::OsStrExt3; +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +use crate::osstringext::OsStrExt3; +use crate::{ + app::{ + help::Help, meta::AppMeta, settings::AppFlags, settings::AppSettings as AS, usage, + validator::Validator, App, + }, + args::{ + settings::ArgSettings, AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder, + PosBuilder, Switched, + }, + completions::{ComplGen, Shell}, + errors::Result as ClapResult, + errors::{Error, ErrorKind}, + fmt::ColorWhen, + map::{self, VecMap}, + osstringext::OsStrExt2, + suggestions, SubCommand, INTERNAL_ERROR_MSG, INVALID_UTF8, +}; + +#[derive(Debug, PartialEq, Copy, Clone)] +#[doc(hidden)] +pub enum ParseResult<'a> { + Flag, + Opt(&'a str), + Pos(&'a str), + MaybeHyphenValue, + MaybeNegNum, + NotFound, + ValuesDone, +} + +#[allow(missing_debug_implementations)] +#[doc(hidden)] +#[derive(Clone, Default)] +pub struct Parser<'a, 'b> +where + 'a: 'b, +{ + pub meta: AppMeta<'b>, + settings: AppFlags, + pub g_settings: AppFlags, + pub flags: Vec>, + pub opts: Vec>, + pub positionals: VecMap>, + pub subcommands: Vec>, + pub groups: Vec>, + pub global_args: Vec>, + pub required: Vec<&'a str>, + pub r_ifs: Vec<(&'a str, &'b str, &'a str)>, + pub overrides: Vec<(&'b str, &'a str)>, + help_short: Option, + version_short: Option, + cache: Option<&'a str>, + pub help_message: Option<&'a str>, + pub version_message: Option<&'a str>, + cur_idx: Cell, +} + +impl<'a, 'b> Parser<'a, 'b> +where + 'a: 'b, +{ + pub fn with_name(n: String) -> Self { + Parser { + meta: AppMeta::with_name(n), + g_settings: AppFlags::zeroed(), + cur_idx: Cell::new(0), + ..Default::default() + } + } + + pub fn help_short(&mut self, s: &str) { + let c = s + .trim_left_matches(|c| c == '-') + .chars() + .next() + .unwrap_or('h'); + self.help_short = Some(c); + } + + pub fn version_short(&mut self, s: &str) { + let c = s + .trim_left_matches(|c| c == '-') + .chars() + .next() + .unwrap_or('V'); + self.version_short = Some(c); + } + + pub fn gen_completions_to(&mut self, for_shell: Shell, buf: &mut W) { + if !self.is_set(AS::Propagated) { + self.propagate_help_version(); + self.build_bin_names(); + self.propagate_globals(); + self.propagate_settings(); + self.set(AS::Propagated); + } + + ComplGen::new(self).generate(for_shell, buf) + } + + pub fn gen_completions(&mut self, for_shell: Shell, od: OsString) { + use std::error::Error; + + let out_dir = PathBuf::from(od); + let name = &*self.meta.bin_name.as_ref().unwrap().clone(); + let file_name = match for_shell { + Shell::Bash => format!("{}.bash", name), + Shell::Fish => format!("{}.fish", name), + Shell::Zsh => format!("_{}", name), + Shell::PowerShell => format!("_{}.ps1", name), + Shell::Elvish => format!("{}.elv", name), + }; + + let mut file = match File::create(out_dir.join(file_name)) { + Err(why) => panic!("couldn't create completion file: {}", why.description()), + Ok(file) => file, + }; + self.gen_completions_to(for_shell, &mut file) + } + + #[inline] + fn app_debug_asserts(&self) -> bool { + assert!(self.verify_positionals()); + let should_err = self.groups.iter().all(|g| { + g.args.iter().all(|arg| { + self.flags.iter().any(|f| &f.b.name == arg) + || self.opts.iter().any(|o| &o.b.name == arg) + || self.positionals.values().any(|p| &p.b.name == arg) + || self.groups.iter().any(|g| &g.name == arg) + }) + }); + let g = self.groups.iter().find(|g| { + g.args.iter().any(|arg| { + !(self.flags.iter().any(|f| &f.b.name == arg) + || self.opts.iter().any(|o| &o.b.name == arg) + || self.positionals.values().any(|p| &p.b.name == arg) + || self.groups.iter().any(|g| &g.name == arg)) + }) + }); + assert!( + should_err, + "The group '{}' contains the arg '{}' that doesn't actually exist.", + g.unwrap().name, + g.unwrap() + .args + .iter() + .find(|arg| !(self.flags.iter().any(|f| &&f.b.name == arg) + || self.opts.iter().any(|o| &&o.b.name == arg) + || self.positionals.values().any(|p| &&p.b.name == arg) + || self.groups.iter().any(|g| &&g.name == arg))) + .unwrap() + ); + true + } + + #[inline] + fn debug_asserts(&self, a: &Arg) -> bool { + assert!( + !arg_names!(self).any(|name| name == a.b.name), + "Non-unique argument name: {} is already in use", + a.b.name + ); + if let Some(l) = a.s.long { + assert!( + !self.contains_long(l), + "Argument long must be unique\n\n\t--{} is already in use", + l + ); + } + if let Some(s) = a.s.short { + assert!( + !self.contains_short(s), + "Argument short must be unique\n\n\t-{} is already in use", + s + ); + } + let i = if a.index.is_none() { + self.positionals.len() + 1 + } else { + a.index.unwrap() as usize + }; + assert!( + !self.positionals.contains_key(i), + "Argument \"{}\" has the same index as another positional \ + argument\n\n\tPerhaps try .multiple(true) to allow one positional argument \ + to take multiple values", + a.b.name + ); + assert!( + !(a.is_set(ArgSettings::Required) && a.is_set(ArgSettings::Global)), + "Global arguments cannot be required.\n\n\t'{}' is marked as \ + global and required", + a.b.name + ); + if a.b.is_set(ArgSettings::Last) { + assert!( + !self + .positionals + .values() + .any(|p| p.b.is_set(ArgSettings::Last)), + "Only one positional argument may have last(true) set. Found two." + ); + assert!(a.s.long.is_none(), + "Flags or Options may not have last(true) set. {} has both a long and last(true) set.", + a.b.name); + assert!(a.s.short.is_none(), + "Flags or Options may not have last(true) set. {} has both a short and last(true) set.", + a.b.name); + } + true + } + + #[inline] + fn add_conditional_reqs(&mut self, a: &Arg<'a, 'b>) { + if let Some(ref r_ifs) = a.r_ifs { + for &(arg, val) in r_ifs { + self.r_ifs.push((arg, val, a.b.name)); + } + } + } + + #[inline] + fn add_arg_groups(&mut self, a: &Arg<'a, 'b>) { + if let Some(ref grps) = a.b.groups { + for g in grps { + let mut found = false; + if let Some(ref mut ag) = self.groups.iter_mut().find(|grp| &grp.name == g) { + ag.args.push(a.b.name); + found = true; + } + if !found { + let mut ag = ArgGroup::with_name(g); + ag.args.push(a.b.name); + self.groups.push(ag); + } + } + } + } + + #[inline] + fn add_reqs(&mut self, a: &Arg<'a, 'b>) { + if a.is_set(ArgSettings::Required) { + // If the arg is required, add all it's requirements to master required list + self.required.push(a.b.name); + if let Some(ref areqs) = a.b.requires { + for name in areqs + .iter() + .filter(|&&(val, _)| val.is_none()) + .map(|&(_, name)| name) + { + self.required.push(name); + } + } + } + } + + #[inline] + fn implied_settings(&mut self, a: &Arg<'a, 'b>) { + if a.is_set(ArgSettings::Last) { + // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args + // in the usage string don't get confused or left out. + self.set(AS::DontCollapseArgsInUsage); + self.set(AS::ContainsLast); + } + if let Some(l) = a.s.long { + if l == "version" { + self.unset(AS::NeedsLongVersion); + } else if l == "help" { + self.unset(AS::NeedsLongHelp); + } + } + } + + // actually adds the arguments + pub fn add_arg(&mut self, a: Arg<'a, 'b>) { + // if it's global we have to clone anyways + if a.is_set(ArgSettings::Global) { + return self.add_arg_ref(&a); + } + debug_assert!(self.debug_asserts(&a)); + self.add_conditional_reqs(&a); + self.add_arg_groups(&a); + self.add_reqs(&a); + self.implied_settings(&a); + if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) { + let i = if a.index.is_none() { + self.positionals.len() + 1 + } else { + a.index.unwrap() as usize + }; + self.positionals + .insert(i, PosBuilder::from_arg(a, i as u64)); + } else if a.is_set(ArgSettings::TakesValue) { + let mut ob = OptBuilder::from(a); + ob.s.unified_ord = self.flags.len() + self.opts.len(); + self.opts.push(ob); + } else { + let mut fb = FlagBuilder::from(a); + fb.s.unified_ord = self.flags.len() + self.opts.len(); + self.flags.push(fb); + } + } + // actually adds the arguments but from a borrow (which means we have to do some cloning) + pub fn add_arg_ref(&mut self, a: &Arg<'a, 'b>) { + debug_assert!(self.debug_asserts(a)); + self.add_conditional_reqs(a); + self.add_arg_groups(a); + self.add_reqs(a); + self.implied_settings(a); + if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) { + let i = if a.index.is_none() { + self.positionals.len() + 1 + } else { + a.index.unwrap() as usize + }; + let pb = PosBuilder::from_arg_ref(a, i as u64); + self.positionals.insert(i, pb); + } else if a.is_set(ArgSettings::TakesValue) { + let mut ob = OptBuilder::from(a); + ob.s.unified_ord = self.flags.len() + self.opts.len(); + self.opts.push(ob); + } else { + let mut fb = FlagBuilder::from(a); + fb.s.unified_ord = self.flags.len() + self.opts.len(); + self.flags.push(fb); + } + if a.is_set(ArgSettings::Global) { + self.global_args.push(a.into()); + } + } + + pub fn add_group(&mut self, group: ArgGroup<'a>) { + if group.required { + self.required.push(group.name); + if let Some(ref reqs) = group.requires { + self.required.extend_from_slice(reqs); + } + // if let Some(ref bl) = group.conflicts { + // self.blacklist.extend_from_slice(bl); + // } + } + if self.groups.iter().any(|g| g.name == group.name) { + let grp = self + .groups + .iter_mut() + .find(|g| g.name == group.name) + .expect(INTERNAL_ERROR_MSG); + grp.args.extend_from_slice(&group.args); + grp.requires = group.requires.clone(); + grp.conflicts = group.conflicts.clone(); + grp.required = group.required; + } else { + self.groups.push(group); + } + } + + pub fn add_subcommand(&mut self, mut subcmd: App<'a, 'b>) { + debugln!( + "Parser::add_subcommand: term_w={:?}, name={}", + self.meta.term_w, + subcmd.p.meta.name + ); + subcmd.p.meta.term_w = self.meta.term_w; + if subcmd.p.meta.name == "help" { + self.unset(AS::NeedsSubcommandHelp); + } + + self.subcommands.push(subcmd); + } + + pub fn propagate_settings(&mut self) { + debugln!( + "Parser::propagate_settings: self={}, g_settings={:#?}", + self.meta.name, + self.g_settings + ); + for sc in &mut self.subcommands { + debugln!( + "Parser::propagate_settings: sc={}, settings={:#?}, g_settings={:#?}", + sc.p.meta.name, + sc.p.settings, + sc.p.g_settings + ); + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + let vsc = self.settings.is_set(AS::VersionlessSubcommands); + let gv = self.settings.is_set(AS::GlobalVersion); + + if vsc { + sc.p.set(AS::DisableVersion); + } + if gv && sc.p.meta.version.is_none() && self.meta.version.is_some() { + sc.p.set(AS::GlobalVersion); + sc.p.meta.version = Some(self.meta.version.unwrap()); + } + sc.p.settings = sc.p.settings | self.g_settings; + sc.p.g_settings = sc.p.g_settings | self.g_settings; + sc.p.meta.term_w = self.meta.term_w; + sc.p.meta.max_w = self.meta.max_w; + } + sc.p.propagate_settings(); + } + } + + pub fn derive_display_order(&mut self) { + if self.is_set(AS::DeriveDisplayOrder) { + let unified = self.is_set(AS::UnifiedHelpMessage); + for (i, o) in self + .opts + .iter_mut() + .enumerate() + .filter(|&(_, ref o)| o.s.disp_ord == 999) + { + o.s.disp_ord = if unified { o.s.unified_ord } else { i }; + } + for (i, f) in self + .flags + .iter_mut() + .enumerate() + .filter(|&(_, ref f)| f.s.disp_ord == 999) + { + f.s.disp_ord = if unified { f.s.unified_ord } else { i }; + } + for (i, sc) in &mut self + .subcommands + .iter_mut() + .enumerate() + .filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999) + { + sc.p.meta.disp_ord = i; + } + } + for sc in &mut self.subcommands { + sc.p.derive_display_order(); + } + } + + pub fn required(&self) -> Iter<&str> { + self.required.iter() + } + + #[inline] + pub fn has_args(&self) -> bool { + !(self.flags.is_empty() && self.opts.is_empty() && self.positionals.is_empty()) + } + + #[inline] + pub fn has_opts(&self) -> bool { + !self.opts.is_empty() + } + + #[inline] + pub fn has_flags(&self) -> bool { + !self.flags.is_empty() + } + + #[inline] + pub fn has_positionals(&self) -> bool { + !self.positionals.is_empty() + } + + #[inline] + pub fn has_subcommands(&self) -> bool { + !self.subcommands.is_empty() + } + + #[inline] + pub fn has_visible_opts(&self) -> bool { + if self.opts.is_empty() { + return false; + } + self.opts.iter().any(|o| !o.is_set(ArgSettings::Hidden)) + } + + #[inline] + pub fn has_visible_flags(&self) -> bool { + if self.flags.is_empty() { + return false; + } + self.flags.iter().any(|f| !f.is_set(ArgSettings::Hidden)) + } + + #[inline] + pub fn has_visible_positionals(&self) -> bool { + if self.positionals.is_empty() { + return false; + } + self.positionals + .values() + .any(|p| !p.is_set(ArgSettings::Hidden)) + } + + #[inline] + pub fn has_visible_subcommands(&self) -> bool { + self.has_subcommands() + && self + .subcommands + .iter() + .filter(|sc| sc.p.meta.name != "help") + .any(|sc| !sc.p.is_set(AS::Hidden)) + } + + #[inline] + pub fn is_set(&self, s: AS) -> bool { + self.settings.is_set(s) + } + + #[inline] + pub fn set(&mut self, s: AS) { + self.settings.set(s) + } + + #[inline] + pub fn unset(&mut self, s: AS) { + self.settings.unset(s) + } + + pub fn verify_positionals(&self) -> bool { + // Because you must wait until all arguments have been supplied, this is the first chance + // to make assertions on positional argument indexes + // + // First we verify that the index highest supplied index, is equal to the number of + // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 + // but no 2) + if let Some((idx, p)) = self.positionals.iter().rev().next() { + assert!( + !(idx != self.positionals.len()), + "Found positional argument \"{}\" whose index is {} but there \ + are only {} positional arguments defined", + p.b.name, + idx, + self.positionals.len() + ); + } + + // Next we verify that only the highest index has a .multiple(true) (if any) + if self.positionals.values().any(|a| { + a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) + }) { + let mut it = self.positionals.values().rev(); + let last = it.next().unwrap(); + let second_to_last = it.next().unwrap(); + // Either the final positional is required + // Or the second to last has a terminator or .last(true) set + let ok = last.is_set(ArgSettings::Required) + || (second_to_last.v.terminator.is_some() + || second_to_last.b.is_set(ArgSettings::Last)) + || last.is_set(ArgSettings::Last); + assert!( + ok, + "When using a positional argument with .multiple(true) that is *not the \ + last* positional argument, the last positional argument (i.e the one \ + with the highest index) *must* have .required(true) or .last(true) set." + ); + let ok = second_to_last.is_set(ArgSettings::Multiple) || last.is_set(ArgSettings::Last); + assert!( + ok, + "Only the last positional argument, or second to last positional \ + argument may be set to .multiple(true)" + ); + + let count = self + .positionals + .values() + .filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none()) + .count(); + let ok = count <= 1 + || (last.is_set(ArgSettings::Last) + && last.is_set(ArgSettings::Multiple) + && second_to_last.is_set(ArgSettings::Multiple) + && count == 2); + assert!( + ok, + "Only one positional argument with .multiple(true) set is allowed per \ + command, unless the second one also has .last(true) set" + ); + } + + let mut found = false; + if self.is_set(AS::AllowMissingPositional) { + // Check that if a required positional argument is found, all positions with a lower + // index are also required. + let mut foundx2 = false; + for p in self.positionals.values().rev() { + if foundx2 && !p.b.settings.is_set(ArgSettings::Required) { + assert!( + p.b.is_set(ArgSettings::Required), + "Found positional argument which is not required with a lower \ + index than a required positional argument by two or more: {:?} \ + index {}", + p.b.name, + p.index + ); + } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog [opt1] -- + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + if found { + foundx2 = true; + continue; + } + found = true; + continue; + } else { + found = false; + } + } + } else { + // Check that if a required positional argument is found, all positions with a lower + // index are also required + for p in self.positionals.values().rev() { + if found { + assert!( + p.b.is_set(ArgSettings::Required), + "Found positional argument which is not required with a lower \ + index than a required positional argument: {:?} index {}", + p.b.name, + p.index + ); + } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog [opt1] -- + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + found = true; + continue; + } + } + } + if self + .positionals + .values() + .any(|p| p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required)) + && self.has_subcommands() + && !self.is_set(AS::SubcommandsNegateReqs) + { + panic!( + "Having a required positional argument with .last(true) set *and* child \ + subcommands without setting SubcommandsNegateReqs isn't compatible." + ); + } + + true + } + + pub fn propagate_globals(&mut self) { + for sc in &mut self.subcommands { + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + for a in &self.global_args { + sc.p.add_arg_ref(a); + } + } + sc.p.propagate_globals(); + } + } + + // Checks if the arg matches a subcommand name, or any of it's aliases (if defined) + fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) { + debugln!("Parser::possible_subcommand: arg={:?}", arg_os); + fn starts(h: &str, n: &OsStr) -> bool { + let n_bytes = n.as_bytes(); + let h_bytes = OsStr::new(h).as_bytes(); + + h_bytes.starts_with(n_bytes) + } + + if self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound) { + return (false, None); + } + if !self.is_set(AS::InferSubcommands) { + if let Some(sc) = find_subcmd!(self, arg_os) { + return (true, Some(&sc.p.meta.name)); + } + } else { + let v = self + .subcommands + .iter() + .filter(|s| { + starts(&s.p.meta.name[..], &*arg_os) + || (s.p.meta.aliases.is_some() + && s.p + .meta + .aliases + .as_ref() + .unwrap() + .iter() + .filter(|&&(a, _)| starts(a, &*arg_os)) + .count() + == 1) + }) + .map(|sc| &sc.p.meta.name) + .collect::>(); + + for sc in &v { + if OsStr::new(sc) == arg_os { + return (true, Some(sc)); + } + } + + if v.len() == 1 { + return (true, Some(v[0])); + } + } + (false, None) + } + + fn parse_help_subcommand(&self, it: &mut I) -> ClapResult> + where + I: Iterator, + T: Into, + { + debugln!("Parser::parse_help_subcommand;"); + let cmds: Vec = it.map(|c| c.into()).collect(); + let mut help_help = false; + let mut bin_name = self + .meta + .bin_name + .as_ref() + .unwrap_or(&self.meta.name) + .clone(); + let mut sc = { + let mut sc: &Parser = self; + for (i, cmd) in cmds.iter().enumerate() { + if &*cmd.to_string_lossy() == "help" { + // cmd help help + help_help = true; + } + if let Some(c) = sc + .subcommands + .iter() + .find(|s| &*s.p.meta.name == cmd) + .map(|sc| &sc.p) + { + sc = c; + if i == cmds.len() - 1 { + break; + } + } else if let Some(c) = sc + .subcommands + .iter() + .find(|s| { + if let Some(ref als) = s.p.meta.aliases { + als.iter().any(|&(a, _)| a == &*cmd.to_string_lossy()) + } else { + false + } + }) + .map(|sc| &sc.p) + { + sc = c; + if i == cmds.len() - 1 { + break; + } + } else { + return Err(Error::unrecognized_subcommand( + cmd.to_string_lossy().into_owned(), + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + self.color(), + )); + } + bin_name = format!("{} {}", bin_name, &*sc.meta.name); + } + sc.clone() + }; + if help_help { + let mut pb = PosBuilder::new("subcommand", 1); + pb.b.help = Some("The subcommand whose help message to display"); + pb.set(ArgSettings::Multiple); + sc.positionals.insert(1, pb); + sc.settings = sc.settings | self.g_settings; + } else { + sc.create_help_and_version(); + } + if sc.meta.bin_name != self.meta.bin_name { + sc.meta.bin_name = Some(format!("{} {}", bin_name, sc.meta.name)); + } + Err(sc._help(false)) + } + + // allow wrong self convention due to self.valid_neg_num = true and it's a private method + #[cfg_attr(feature = "lints", allow(wrong_self_convention))] + fn is_new_arg(&mut self, arg_os: &OsStr, needs_val_of: ParseResult) -> bool { + debugln!("Parser::is_new_arg:{:?}:{:?}", arg_os, needs_val_of); + let app_wide_settings = if self.is_set(AS::AllowLeadingHyphen) { + true + } else if self.is_set(AS::AllowNegativeNumbers) { + let a = arg_os.to_string_lossy(); + if a.parse::().is_ok() || a.parse::().is_ok() { + self.set(AS::ValidNegNumFound); + true + } else { + false + } + } else { + false + }; + let arg_allows_tac = match needs_val_of { + ParseResult::Opt(name) => { + let o = self + .opts + .iter() + .find(|o| o.b.name == name) + .expect(INTERNAL_ERROR_MSG); + o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings + } + ParseResult::Pos(name) => { + let p = self + .positionals + .values() + .find(|p| p.b.name == name) + .expect(INTERNAL_ERROR_MSG); + p.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings + } + ParseResult::ValuesDone => return true, + _ => false, + }; + debugln!("Parser::is_new_arg: arg_allows_tac={:?}", arg_allows_tac); + + // Is this a new argument, or values from a previous option? + let mut ret = if arg_os.starts_with(b"--") { + debugln!("Parser::is_new_arg: -- found"); + if arg_os.len() == 2 && !arg_allows_tac { + return true; // We have to return true so override everything else + } else if arg_allows_tac { + return false; + } + true + } else if arg_os.starts_with(b"-") { + debugln!("Parser::is_new_arg: - found"); + // a singe '-' by itself is a value and typically means "stdin" on unix systems + arg_os.len() != 1 + } else { + debugln!("Parser::is_new_arg: probably value"); + false + }; + + ret = ret && !arg_allows_tac; + + debugln!("Parser::is_new_arg: starts_new_arg={:?}", ret); + ret + } + + // The actual parsing function + #[cfg_attr( + feature = "cargo-clippy", + allow(clippy::while_let_on_iterator, clippy::nonminimal_bool) + )] + pub fn get_matches_with( + &mut self, + matcher: &mut ArgMatcher<'a>, + it: &mut Peekable, + ) -> ClapResult<()> + where + I: Iterator, + T: Into + Clone, + { + debugln!("Parser::get_matches_with;"); + // Verify all positional assertions pass + debug_assert!(self.app_debug_asserts()); + if self.positionals.values().any(|a| { + a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) + }) && self + .positionals + .values() + .last() + .map_or(false, |p| !p.is_set(ArgSettings::Last)) + { + self.settings.set(AS::LowIndexMultiplePositional); + } + let has_args = self.has_args(); + + // Next we create the `--help` and `--version` arguments and add them if + // necessary + self.create_help_and_version(); + + let mut subcmd_name: Option = None; + let mut needs_val_of: ParseResult<'a> = ParseResult::NotFound; + let mut pos_counter = 1; + let mut sc_is_external = false; + while let Some(arg) = it.next() { + let arg_os = arg.into(); + debugln!( + "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", + arg_os, + &*arg_os.as_bytes() + ); + + self.unset(AS::ValidNegNumFound); + // Is this a new argument, or values from a previous option? + let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of); + if !self.is_set(AS::TrailingValues) + && arg_os.starts_with(b"--") + && arg_os.len() == 2 + && starts_new_arg + { + debugln!("Parser::get_matches_with: setting TrailingVals=true"); + self.set(AS::TrailingValues); + continue; + } + + // Has the user already passed '--'? Meaning only positional args follow + if !self.is_set(AS::TrailingValues) { + // Does the arg match a subcommand name, or any of it's aliases (if defined) + { + match needs_val_of { + ParseResult::Opt(_) | ParseResult::Pos(_) => (), + _ => { + let (is_match, sc_name) = self.possible_subcommand(&arg_os); + debugln!( + "Parser::get_matches_with: possible_sc={:?}, sc={:?}", + is_match, + sc_name + ); + if is_match { + let sc_name = sc_name.expect(INTERNAL_ERROR_MSG); + if sc_name == "help" && self.is_set(AS::NeedsSubcommandHelp) { + self.parse_help_subcommand(it)?; + } + subcmd_name = Some(sc_name.to_owned()); + break; + } + } + } + } + + if starts_new_arg { + let check_all = self.is_set(AS::AllArgsOverrideSelf); + { + let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); + matcher.process_arg_overrides( + any_arg, + &mut self.overrides, + &mut self.required, + check_all, + ); + } + + if arg_os.starts_with(b"--") { + needs_val_of = self.parse_long_arg(matcher, &arg_os, it)?; + debugln!( + "Parser:get_matches_with: After parse_long_arg {:?}", + needs_val_of + ); + match needs_val_of { + ParseResult::Flag | ParseResult::Opt(..) | ParseResult::ValuesDone => { + continue + } + _ => (), + } + } else if arg_os.starts_with(b"-") && arg_os.len() != 1 { + // Try to parse short args like normal, if AllowLeadingHyphen or + // AllowNegativeNumbers is set, parse_short_arg will *not* throw + // an error, and instead return Ok(None) + needs_val_of = self.parse_short_arg(matcher, &arg_os)?; + // If it's None, we then check if one of those two AppSettings was set + debugln!( + "Parser:get_matches_with: After parse_short_arg {:?}", + needs_val_of + ); + match needs_val_of { + ParseResult::MaybeNegNum => { + if !(arg_os.to_string_lossy().parse::().is_ok() + || arg_os.to_string_lossy().parse::().is_ok()) + { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + ParseResult::Opt(..) | ParseResult::Flag | ParseResult::ValuesDone => { + continue + } + _ => (), + } + } + } else if let ParseResult::Opt(name) = needs_val_of { + // Check to see if parsing a value from a previous arg + let arg = self + .opts + .iter() + .find(|o| o.b.name == name) + .expect(INTERNAL_ERROR_MSG); + // get the OptBuilder so we can check the settings + needs_val_of = self.add_val_to_arg(arg, &arg_os, matcher)?; + // get the next value from the iterator + continue; + } + } + + if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound)) + && !self.is_set(AS::InferSubcommands) + && !self.is_set(AS::AllowExternalSubcommands) + { + if let Some(cdate) = + suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) + { + return Err(Error::invalid_subcommand( + arg_os.to_string_lossy().into_owned(), + cdate, + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + + let low_index_mults = self.is_set(AS::LowIndexMultiplePositional) + && pos_counter == (self.positionals.len() - 1); + let missing_pos = self.is_set(AS::AllowMissingPositional) + && (pos_counter == (self.positionals.len() - 1) + && !self.is_set(AS::TrailingValues)); + debugln!( + "Parser::get_matches_with: Positional counter...{}", + pos_counter + ); + debugln!( + "Parser::get_matches_with: Low index multiples...{:?}", + low_index_mults + ); + if low_index_mults || missing_pos { + if let Some(na) = it.peek() { + let n = (*na).clone().into(); + needs_val_of = if needs_val_of != ParseResult::ValuesDone { + if let Some(p) = self.positionals.get(pos_counter) { + ParseResult::Pos(p.b.name) + } else { + ParseResult::ValuesDone + } + } else { + ParseResult::ValuesDone + }; + let sc_match = { self.possible_subcommand(&n).0 }; + if self.is_new_arg(&n, needs_val_of) + || sc_match + || suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self)) + .is_some() + { + debugln!("Parser::get_matches_with: Bumping the positional counter..."); + pos_counter += 1; + } + } else { + debugln!("Parser::get_matches_with: Bumping the positional counter..."); + pos_counter += 1; + } + } else if (self.is_set(AS::AllowMissingPositional) && self.is_set(AS::TrailingValues)) + || (self.is_set(AS::ContainsLast) && self.is_set(AS::TrailingValues)) + { + // Came to -- and one postional has .last(true) set, so we go immediately + // to the last (highest index) positional + debugln!("Parser::get_matches_with: .last(true) and --, setting last pos"); + pos_counter = self.positionals.len(); + } + if let Some(p) = self.positionals.get(pos_counter) { + if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + if !self.is_set(AS::TrailingValues) + && (self.is_set(AS::TrailingVarArg) && pos_counter == self.positionals.len()) + { + self.settings.set(AS::TrailingValues); + } + if self.cache.map_or(true, |name| name != p.b.name) { + let check_all = self.is_set(AS::AllArgsOverrideSelf); + { + let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); + matcher.process_arg_overrides( + any_arg, + &mut self.overrides, + &mut self.required, + check_all, + ); + } + self.cache = Some(p.b.name); + } + let _ = self.add_val_to_arg(p, &arg_os, matcher)?; + + matcher.inc_occurrence_of(p.b.name); + let _ = self + .groups_for_arg(p.b.name) + .map(|vec| matcher.inc_occurrences_of(&*vec)); + + self.settings.set(AS::ValidArgFound); + // Only increment the positional counter if it doesn't allow multiples + if !p.b.settings.is_set(ArgSettings::Multiple) { + pos_counter += 1; + } + self.settings.set(AS::ValidArgFound); + } else if self.is_set(AS::AllowExternalSubcommands) { + // Get external subcommand name + let sc_name = match arg_os.to_str() { + Some(s) => s.to_string(), + None => { + if !self.is_set(AS::StrictUtf8) { + return Err(Error::invalid_utf8( + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + arg_os.to_string_lossy().into_owned() + } + }; + + // Collect the external subcommand args + let mut sc_m = ArgMatcher::new(); + // Due to borrow rules, this has to be a while let... + #[cfg_attr(feature = "cargo-clippy", allow(clippy::while_let_on_iterator))] + while let Some(v) = it.next() { + let a = v.into(); + if a.to_str().is_none() && !self.is_set(AS::StrictUtf8) { + return Err(Error::invalid_utf8( + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + sc_m.add_val_to("", &a); + } + + matcher.subcommand(SubCommand { + name: sc_name, + matches: sc_m.into(), + }); + sc_is_external = true; + } else if !((self.is_set(AS::AllowLeadingHyphen) + || self.is_set(AS::AllowNegativeNumbers)) + && arg_os.starts_with(b"-")) + && !self.is_set(AS::InferSubcommands) + { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else if !has_args || self.is_set(AS::InferSubcommands) && self.has_subcommands() { + if let Some(cdate) = + suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) + { + return Err(Error::invalid_subcommand( + arg_os.to_string_lossy().into_owned(), + cdate, + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else { + return Err(Error::unrecognized_subcommand( + arg_os.to_string_lossy().into_owned(), + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + self.color(), + )); + } + } else { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + + if !sc_is_external { + if let Some(ref pos_sc_name) = subcmd_name { + let sc_name = { + find_subcmd!(self, pos_sc_name) + .expect(INTERNAL_ERROR_MSG) + .p + .meta + .name + .clone() + }; + self.parse_subcommand(&*sc_name, matcher, it)?; + } else if self.is_set(AS::SubcommandRequired) { + let bn = self.meta.bin_name.as_ref().unwrap_or(&self.meta.name); + return Err(Error::missing_subcommand( + bn, + &usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else if self.is_set(AS::SubcommandRequiredElseHelp) { + debugln!("Parser::get_matches_with: SubcommandRequiredElseHelp=true"); + let mut out = vec![]; + self.write_help_err(&mut out)?; + return Err(Error { + message: String::from_utf8_lossy(&*out).into_owned(), + kind: ErrorKind::MissingArgumentOrSubcommand, + info: None, + }); + } + } + + // In case the last arg was new, we need to process it's overrides + let check_all = self.is_set(AS::AllArgsOverrideSelf); + { + let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); + matcher.process_arg_overrides( + any_arg, + &mut self.overrides, + &mut self.required, + check_all, + ); + } + + self.remove_overrides(matcher); + + Validator::new(self).validate(needs_val_of, subcmd_name, matcher) + } + + fn remove_overrides(&mut self, matcher: &mut ArgMatcher) { + debugln!("Parser::remove_overrides:{:?};", self.overrides); + for &(overr, name) in &self.overrides { + debugln!("Parser::remove_overrides:iter:({},{});", overr, name); + if matcher.is_present(overr) { + debugln!( + "Parser::remove_overrides:iter:({},{}): removing {};", + overr, + name, + name + ); + matcher.remove(name); + for i in (0..self.required.len()).rev() { + debugln!( + "Parser::remove_overrides:iter:({},{}): removing required {};", + overr, + name, + name + ); + if self.required[i] == name { + self.required.swap_remove(i); + break; + } + } + } + } + } + + fn propagate_help_version(&mut self) { + debugln!("Parser::propagate_help_version;"); + self.create_help_and_version(); + for sc in &mut self.subcommands { + sc.p.propagate_help_version(); + } + } + + fn build_bin_names(&mut self) { + debugln!("Parser::build_bin_names;"); + for sc in &mut self.subcommands { + debug!("Parser::build_bin_names:iter: bin_name set..."); + if sc.p.meta.bin_name.is_none() { + sdebugln!("No"); + let bin_name = format!( + "{}{}{}", + self.meta + .bin_name + .as_ref() + .unwrap_or(&self.meta.name.clone()), + if self.meta.bin_name.is_some() { + " " + } else { + "" + }, + &*sc.p.meta.name + ); + debugln!( + "Parser::build_bin_names:iter: Setting bin_name of {} to {}", + self.meta.name, + bin_name + ); + sc.p.meta.bin_name = Some(bin_name); + } else { + sdebugln!("yes ({:?})", sc.p.meta.bin_name); + } + debugln!( + "Parser::build_bin_names:iter: Calling build_bin_names from...{}", + sc.p.meta.name + ); + sc.p.build_bin_names(); + } + } + + fn parse_subcommand( + &mut self, + sc_name: &str, + matcher: &mut ArgMatcher<'a>, + it: &mut Peekable, + ) -> ClapResult<()> + where + I: Iterator, + T: Into + Clone, + { + use std::fmt::Write; + debugln!("Parser::parse_subcommand;"); + let mut mid_string = String::new(); + if !self.is_set(AS::SubcommandsNegateReqs) { + let mut hs: Vec<&str> = self.required.iter().map(|n| &**n).collect(); + for k in matcher.arg_names() { + hs.push(k); + } + let reqs = usage::get_required_usage_from(self, &hs, Some(matcher), None, false); + + for s in &reqs { + write!(&mut mid_string, " {}", s).expect(INTERNAL_ERROR_MSG); + } + } + mid_string.push(' '); + if let Some(ref mut sc) = self + .subcommands + .iter_mut() + .find(|s| s.p.meta.name == sc_name) + { + let mut sc_matcher = ArgMatcher::new(); + // bin_name should be parent's bin_name + [] + the sc's name separated by + // a space + sc.p.meta.usage = Some(format!( + "{}{}{}", + self.meta.bin_name.as_ref().unwrap_or(&String::new()), + if self.meta.bin_name.is_some() { + &*mid_string + } else { + "" + }, + &*sc.p.meta.name + )); + sc.p.meta.bin_name = Some(format!( + "{}{}{}", + self.meta.bin_name.as_ref().unwrap_or(&String::new()), + if self.meta.bin_name.is_some() { + " " + } else { + "" + }, + &*sc.p.meta.name + )); + debugln!( + "Parser::parse_subcommand: About to parse sc={}", + sc.p.meta.name + ); + debugln!("Parser::parse_subcommand: sc settings={:#?}", sc.p.settings); + sc.p.get_matches_with(&mut sc_matcher, it)?; + matcher.subcommand(SubCommand { + name: sc.p.meta.name.clone(), + matches: sc_matcher.into(), + }); + } + Ok(()) + } + + pub fn groups_for_arg(&self, name: &str) -> Option> { + debugln!("Parser::groups_for_arg: name={}", name); + + if self.groups.is_empty() { + debugln!("Parser::groups_for_arg: No groups defined"); + return None; + } + let mut res = vec![]; + debugln!("Parser::groups_for_arg: Searching through groups..."); + for grp in &self.groups { + for a in &grp.args { + if a == &name { + sdebugln!("\tFound '{}'", grp.name); + res.push(&*grp.name); + } + } + } + if res.is_empty() { + return None; + } + + Some(res) + } + + pub fn args_in_group(&self, group: &str) -> Vec { + debug_assert!(self.app_debug_asserts()); + + let mut g_vec = vec![]; + let mut args = vec![]; + + for n in &self + .groups + .iter() + .find(|g| g.name == group) + .expect(INTERNAL_ERROR_MSG) + .args + { + if let Some(f) = self.flags.iter().find(|f| &f.b.name == n) { + args.push(f.to_string()); + } else if let Some(f) = self.opts.iter().find(|o| &o.b.name == n) { + args.push(f.to_string()); + } else if let Some(p) = self.positionals.values().find(|p| &p.b.name == n) { + args.push(p.b.name.to_owned()); + } else { + g_vec.push(*n); + } + } + + for av in g_vec.iter().map(|g| self.args_in_group(g)) { + args.extend(av); + } + args.dedup(); + args.iter().map(ToOwned::to_owned).collect() + } + + pub fn arg_names_in_group(&self, group: &str) -> Vec<&'a str> { + let mut g_vec = vec![]; + let mut args = vec![]; + + for n in &self + .groups + .iter() + .find(|g| g.name == group) + .expect(INTERNAL_ERROR_MSG) + .args + { + if self.groups.iter().any(|g| g.name == *n) { + args.extend(self.arg_names_in_group(n)); + g_vec.push(*n); + } else if !args.contains(n) { + args.push(*n); + } + } + + args.iter().copied().collect() + } + + pub fn create_help_and_version(&mut self) { + debugln!("Parser::create_help_and_version;"); + // name is "hclap_help" because flags are sorted by name + if !self.is_set(AS::DisableHelpFlags) && !self.contains_long("help") { + debugln!("Parser::create_help_and_version: Building --help"); + if self.help_short.is_none() && !self.contains_short('h') { + self.help_short = Some('h'); + } + let arg = FlagBuilder { + b: Base { + name: "hclap_help", + help: self.help_message.or(Some("Prints help information")), + ..Default::default() + }, + s: Switched { + short: self.help_short, + long: Some("help"), + ..Default::default() + }, + }; + self.flags.push(arg); + } + if !self.is_set(AS::DisableVersion) && !self.contains_long("version") { + debugln!("Parser::create_help_and_version: Building --version"); + if self.version_short.is_none() && !self.contains_short('V') { + self.version_short = Some('V'); + } + // name is "vclap_version" because flags are sorted by name + let arg = FlagBuilder { + b: Base { + name: "vclap_version", + help: self.version_message.or(Some("Prints version information")), + ..Default::default() + }, + s: Switched { + short: self.version_short, + long: Some("version"), + ..Default::default() + }, + }; + self.flags.push(arg); + } + if !self.subcommands.is_empty() + && !self.is_set(AS::DisableHelpSubcommand) + && self.is_set(AS::NeedsSubcommandHelp) + { + debugln!("Parser::create_help_and_version: Building help"); + self.subcommands.push( + App::new("help") + .about("Prints this message or the help of the given subcommand(s)"), + ); + } + } + + // Retrieves the names of all args the user has supplied thus far, except required ones + // because those will be listed in self.required + fn check_for_help_and_version_str(&self, arg: &OsStr) -> ClapResult<()> { + debugln!("Parser::check_for_help_and_version_str;"); + debug!( + "Parser::check_for_help_and_version_str: Checking if --{} is help or version...", + arg.to_str().unwrap() + ); + if arg == "help" && self.is_set(AS::NeedsLongHelp) { + sdebugln!("Help"); + return Err(self._help(true)); + } + if arg == "version" && self.is_set(AS::NeedsLongVersion) { + sdebugln!("Version"); + return Err(self._version(true)); + } + sdebugln!("Neither"); + + Ok(()) + } + + fn check_for_help_and_version_char(&self, arg: char) -> ClapResult<()> { + debugln!("Parser::check_for_help_and_version_char;"); + debug!( + "Parser::check_for_help_and_version_char: Checking if -{} is help or version...", + arg + ); + if let Some(h) = self.help_short { + if arg == h && self.is_set(AS::NeedsLongHelp) { + sdebugln!("Help"); + return Err(self._help(false)); + } + } + if let Some(v) = self.version_short { + if arg == v && self.is_set(AS::NeedsLongVersion) { + sdebugln!("Version"); + return Err(self._version(false)); + } + } + sdebugln!("Neither"); + Ok(()) + } + + fn use_long_help(&self) -> bool { + // In this case, both must be checked. This allows the retention of + // original formatting, but also ensures that the actual -h or --help + // specified by the user is sent through. If HiddenShortHelp is not included, + // then items specified with hidden_short_help will also be hidden. + let should_long = |v: &Base| { + v.long_help.is_some() + || v.is_set(ArgSettings::HiddenLongHelp) + || v.is_set(ArgSettings::HiddenShortHelp) + }; + + self.meta.long_about.is_some() + || self.flags.iter().any(|f| should_long(&f.b)) + || self.opts.iter().any(|o| should_long(&o.b)) + || self.positionals.values().any(|p| should_long(&p.b)) + || self + .subcommands + .iter() + .any(|s| s.p.meta.long_about.is_some()) + } + + fn _help(&self, mut use_long: bool) -> Error { + debugln!("Parser::_help: use_long={:?}", use_long); + use_long = use_long && self.use_long_help(); + let mut buf = vec![]; + match Help::write_parser_help(&mut buf, self, use_long) { + Err(e) => e, + _ => Error { + message: String::from_utf8(buf).unwrap_or_default(), + kind: ErrorKind::HelpDisplayed, + info: None, + }, + } + } + + fn _version(&self, use_long: bool) -> Error { + debugln!("Parser::_version: "); + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + match self.print_version(&mut buf_w, use_long) { + Err(e) => e, + _ => Error { + message: String::new(), + kind: ErrorKind::VersionDisplayed, + info: None, + }, + } + } + + fn parse_long_arg( + &mut self, + matcher: &mut ArgMatcher<'a>, + full_arg: &OsStr, + it: &mut Peekable, + ) -> ClapResult> + where + I: Iterator, + T: Into + Clone, + { + // maybe here lifetime should be 'a + debugln!("Parser::parse_long_arg;"); + + // Update the current index + self.cur_idx.set(self.cur_idx.get() + 1); + + let mut val = None; + debug!("Parser::parse_long_arg: Does it contain '='..."); + let arg = if full_arg.contains_byte(b'=') { + let (p0, p1) = full_arg.trim_left_matches(b'-').split_at_byte(b'='); + sdebugln!("Yes '{:?}'", p1); + val = Some(p1); + p0 + } else { + sdebugln!("No"); + full_arg.trim_left_matches(b'-') + }; + + if let Some(opt) = find_opt_by_long!(@os self, arg) { + debugln!( + "Parser::parse_long_arg: Found valid opt '{}'", + opt.to_string() + ); + self.settings.set(AS::ValidArgFound); + let ret = self.parse_opt(val, opt, val.is_some(), matcher)?; + if self.cache.map_or(true, |name| name != opt.b.name) { + self.cache = Some(opt.b.name); + } + + return Ok(ret); + } else if let Some(flag) = find_flag_by_long!(@os self, arg) { + debugln!( + "Parser::parse_long_arg: Found valid flag '{}'", + flag.to_string() + ); + self.settings.set(AS::ValidArgFound); + // Only flags could be help or version, and we need to check the raw long + // so this is the first point to check + self.check_for_help_and_version_str(arg)?; + + self.parse_flag(flag, matcher)?; + + // Handle conflicts, requirements, etc. + if self.cache.map_or(true, |name| name != flag.b.name) { + self.cache = Some(flag.b.name); + } + + return Ok(ParseResult::Flag); + } else if self.is_set(AS::AllowLeadingHyphen) { + return Ok(ParseResult::MaybeHyphenValue); + } else if self.is_set(AS::ValidNegNumFound) { + return Ok(ParseResult::MaybeNegNum); + } + + debugln!("Parser::parse_long_arg: Didn't match anything"); + + let args_rest: Vec<_> = it.map(|x| x.into()).collect(); + let args_rest2: Vec<_> = args_rest + .iter() + .map(|x| x.to_str().expect(INVALID_UTF8)) + .collect(); + self.did_you_mean_error(arg.to_str().expect(INVALID_UTF8), matcher, &args_rest2[..]) + .map(|_| ParseResult::NotFound) + } + + fn parse_short_arg( + &mut self, + matcher: &mut ArgMatcher<'a>, + full_arg: &OsStr, + ) -> ClapResult> { + debugln!("Parser::parse_short_arg: full_arg={:?}", full_arg); + let arg_os = full_arg.trim_left_matches(b'-'); + let arg = arg_os.to_string_lossy(); + + // If AllowLeadingHyphen is set, we want to ensure `-val` gets parsed as `-val` and not + // `-v` `-a` `-l` assuming `v` `a` and `l` are all, or mostly, valid shorts. + if self.is_set(AS::AllowLeadingHyphen) { + if arg.chars().any(|c| !self.contains_short(c)) { + debugln!( + "Parser::parse_short_arg: LeadingHyphenAllowed yet -{} isn't valid", + arg + ); + return Ok(ParseResult::MaybeHyphenValue); + } + } else if self.is_set(AS::ValidNegNumFound) { + // TODO: Add docs about having AllowNegativeNumbers and `-2` as a valid short + // May be better to move this to *after* not finding a valid flag/opt? + debugln!("Parser::parse_short_arg: Valid negative num..."); + return Ok(ParseResult::MaybeNegNum); + } + + let mut ret = ParseResult::NotFound; + for c in arg.chars() { + debugln!("Parser::parse_short_arg:iter:{}", c); + + // update each index because `-abcd` is four indices to clap + self.cur_idx.set(self.cur_idx.get() + 1); + + // Check for matching short options, and return the name if there is no trailing + // concatenated value: -oval + // Option: -o + // Value: val + if let Some(opt) = find_opt_by_short!(self, c) { + debugln!("Parser::parse_short_arg:iter:{}: Found valid opt", c); + self.settings.set(AS::ValidArgFound); + // Check for trailing concatenated value + let p: Vec<_> = arg.splitn(2, c).collect(); + debugln!( + "Parser::parse_short_arg:iter:{}: p[0]={:?}, p[1]={:?}", + c, + p[0].as_bytes(), + p[1].as_bytes() + ); + let i = p[0].as_bytes().len() + 1; + let val = if !p[1].as_bytes().is_empty() { + debugln!( + "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii)", + c, + arg_os.split_at(i).1.as_bytes(), + arg_os.split_at(i).1 + ); + Some(arg_os.split_at(i).1) + } else { + None + }; + + // Default to "we're expecting a value later" + let ret = self.parse_opt(val, opt, false, matcher)?; + + if self.cache.map_or(true, |name| name != opt.b.name) { + self.cache = Some(opt.b.name); + } + + return Ok(ret); + } else if let Some(flag) = find_flag_by_short!(self, c) { + debugln!("Parser::parse_short_arg:iter:{}: Found valid flag", c); + self.settings.set(AS::ValidArgFound); + // Only flags can be help or version + self.check_for_help_and_version_char(c)?; + ret = self.parse_flag(flag, matcher)?; + + // Handle conflicts, requirements, overrides, etc. + // Must be called here due to mutabililty + if self.cache.map_or(true, |name| name != flag.b.name) { + self.cache = Some(flag.b.name); + } + } else { + let arg = format!("-{}", c); + return Err(Error::unknown_argument( + &*arg, + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + Ok(ret) + } + + fn parse_opt( + &self, + val: Option<&OsStr>, + opt: &OptBuilder<'a, 'b>, + had_eq: bool, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult> { + debugln!("Parser::parse_opt; opt={}, val={:?}", opt.b.name, val); + debugln!("Parser::parse_opt; opt.settings={:?}", opt.b.settings); + let mut has_eq = false; + let no_val = val.is_none(); + let empty_vals = opt.is_set(ArgSettings::EmptyValues); + let min_vals_zero = opt.v.min_vals.unwrap_or(1) == 0; + let needs_eq = opt.is_set(ArgSettings::RequireEquals); + + debug!("Parser::parse_opt; Checking for val..."); + if let Some(fv) = val { + has_eq = fv.starts_with(&[b'=']) || had_eq; + let v = fv.trim_left_matches(b'='); + if !empty_vals && (v.is_empty() || (needs_eq && !has_eq)) { + sdebugln!("Found Empty - Error"); + return Err(Error::empty_value( + opt, + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + sdebugln!("Found - {:?}, len: {}", v, v.len()); + debugln!( + "Parser::parse_opt: {:?} contains '='...{:?}", + fv, + fv.starts_with(&[b'=']) + ); + self.add_val_to_arg(opt, v, matcher)?; + } else if needs_eq && !(empty_vals || min_vals_zero) { + sdebugln!("None, but requires equals...Error"); + return Err(Error::empty_value( + opt, + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else { + sdebugln!("None"); + } + + matcher.inc_occurrence_of(opt.b.name); + // Increment or create the group "args" + if let Some(vec) = self.groups_for_arg(opt.b.name) { + matcher.inc_occurrences_of(&*vec); + } + + let needs_delim = opt.is_set(ArgSettings::RequireDelimiter); + let mult = opt.is_set(ArgSettings::Multiple); + if no_val && min_vals_zero && !has_eq && needs_eq { + debugln!("Parser::parse_opt: More arg vals not required..."); + return Ok(ParseResult::ValuesDone); + } else if no_val || (mult && !needs_delim) && !has_eq && matcher.needs_more_vals(opt) { + debugln!("Parser::parse_opt: More arg vals required..."); + return Ok(ParseResult::Opt(opt.b.name)); + } + debugln!("Parser::parse_opt: More arg vals not required..."); + Ok(ParseResult::ValuesDone) + } + + fn add_val_to_arg( + &self, + arg: &A, + val: &OsStr, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name(), val); + debugln!( + "Parser::add_val_to_arg; trailing_vals={:?}, DontDelimTrailingVals={:?}", + self.is_set(AS::TrailingValues), + self.is_set(AS::DontDelimitTrailingValues) + ); + if !(self.is_set(AS::TrailingValues) && self.is_set(AS::DontDelimitTrailingValues)) { + if let Some(delim) = arg.val_delim() { + if val.is_empty() { + Ok(self.add_single_val_to_arg(arg, val, matcher)?) + } else { + let mut iret = ParseResult::ValuesDone; + for v in val.split(delim as u32 as u8) { + iret = self.add_single_val_to_arg(arg, v, matcher)?; + } + // If there was a delimiter used, we're not looking for more values + if val.contains_byte(delim as u32 as u8) + || arg.is_set(ArgSettings::RequireDelimiter) + { + iret = ParseResult::ValuesDone; + } + Ok(iret) + } + } else { + self.add_single_val_to_arg(arg, val, matcher) + } + } else { + self.add_single_val_to_arg(arg, val, matcher) + } + } + + fn add_single_val_to_arg( + &self, + arg: &A, + v: &OsStr, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Parser::add_single_val_to_arg;"); + debugln!("Parser::add_single_val_to_arg: adding val...{:?}", v); + + // update the current index because each value is a distinct index to clap + self.cur_idx.set(self.cur_idx.get() + 1); + + // @TODO @docs @p4: docs for indices should probably note that a terminator isn't a value + // and therefore not reported in indices + if let Some(t) = arg.val_terminator() { + if t == v { + return Ok(ParseResult::ValuesDone); + } + } + + matcher.add_val_to(arg.name(), v); + matcher.add_index_to(arg.name(), self.cur_idx.get()); + + // Increment or create the group "args" + if let Some(grps) = self.groups_for_arg(arg.name()) { + for grp in grps { + matcher.add_val_to(&*grp, v); + } + } + + if matcher.needs_more_vals(arg) { + return Ok(ParseResult::Opt(arg.name())); + } + Ok(ParseResult::ValuesDone) + } + + fn parse_flag( + &self, + flag: &FlagBuilder<'a, 'b>, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult> { + debugln!("Parser::parse_flag;"); + + matcher.inc_occurrence_of(flag.b.name); + matcher.add_index_to(flag.b.name, self.cur_idx.get()); + + // Increment or create the group "args" + if let Some(vec) = self.groups_for_arg(flag.b.name) { + matcher.inc_occurrences_of(&*vec); + } + + Ok(ParseResult::Flag) + } + + fn did_you_mean_error( + &self, + arg: &str, + matcher: &mut ArgMatcher<'a>, + args_rest: &[&str], + ) -> ClapResult<()> { + // Didn't match a flag or option + let suffix = + suggestions::did_you_mean_flag_suffix(arg, args_rest, longs!(self), &self.subcommands); + + // Add the arg to the matches to build a proper usage string + if let Some(name) = suffix.1 { + if let Some(opt) = find_opt_by_long!(self, name) { + if let Some(grps) = self.groups_for_arg(&*opt.b.name) { + matcher.inc_occurrences_of(&*grps); + } + matcher.insert(&*opt.b.name); + } else if let Some(flg) = find_flag_by_long!(self, name) { + if let Some(grps) = self.groups_for_arg(&*flg.b.name) { + matcher.inc_occurrences_of(&*grps); + } + matcher.insert(&*flg.b.name); + } + } + + let used_arg = format!("--{}", arg); + Err(Error::unknown_argument( + &*used_arg, + &*suffix.0, + &*usage::create_error_usage(self, matcher, None), + self.color(), + )) + } + + // Prints the version to the user and exits if quit=true + fn print_version(&self, w: &mut W, use_long: bool) -> ClapResult<()> { + self.write_version(w, use_long)?; + w.flush().map_err(Error::from) + } + + pub fn write_version(&self, w: &mut W, use_long: bool) -> io::Result<()> { + let ver = if use_long { + self.meta + .long_version + .unwrap_or_else(|| self.meta.version.unwrap_or("")) + } else { + self.meta + .version + .unwrap_or_else(|| self.meta.long_version.unwrap_or("")) + }; + if let Some(bn) = self.meta.bin_name.as_ref() { + if bn.contains(' ') { + // Incase we're dealing with subcommands i.e. git mv is translated to git-mv + write!(w, "{} {}", bn.replace(" ", "-"), ver) + } else { + write!(w, "{} {}", &self.meta.name[..], ver) + } + } else { + write!(w, "{} {}", &self.meta.name[..], ver) + } + } + + pub fn print_help(&self) -> ClapResult<()> { + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + self.write_help(&mut buf_w) + } + + pub fn write_help(&self, w: &mut W) -> ClapResult<()> { + Help::write_parser_help(w, self, false) + } + + pub fn write_long_help(&self, w: &mut W) -> ClapResult<()> { + Help::write_parser_help(w, self, true) + } + + pub fn write_help_err(&self, w: &mut W) -> ClapResult<()> { + Help::write_parser_help_to_stderr(w, self) + } + + pub fn add_defaults(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { + debugln!("Parser::add_defaults;"); + macro_rules! add_val { + (@default $_self:ident, $a:ident, $m:ident) => { + if let Some(ref val) = $a.v.default_val { + debugln!("Parser::add_defaults:iter:{}: has default vals", $a.b.name); + if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) { + debugln!("Parser::add_defaults:iter:{}: has no user defined vals", $a.b.name); + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } else if $m.get($a.b.name).is_some() { + debugln!("Parser::add_defaults:iter:{}: has user defined vals", $a.b.name); + } else { + debugln!("Parser::add_defaults:iter:{}: wasn't used", $a.b.name); + + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } + } else { + debugln!("Parser::add_defaults:iter:{}: doesn't have default vals", $a.b.name); + } + }; + ($_self:ident, $a:ident, $m:ident) => { + if let Some(ref vm) = $a.v.default_vals_ifs { + sdebugln!(" has conditional defaults"); + let mut done = false; + if $m.get($a.b.name).is_none() { + for &(arg, val, default) in vm.values() { + let add = if let Some(a) = $m.get(arg) { + if let Some(v) = val { + a.vals.iter().any(|value| v == value) + } else { + true + } + } else { + false + }; + if add { + $_self.add_val_to_arg($a, OsStr::new(default), $m)?; + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + done = true; + break; + } + } + } + + if done { + continue; // outer loop (outside macro) + } + } else { + sdebugln!(" doesn't have conditional defaults"); + } + add_val!(@default $_self, $a, $m) + }; + } + + for o in &self.opts { + debug!("Parser::add_defaults:iter:{}:", o.b.name); + add_val!(self, o, matcher); + } + for p in self.positionals.values() { + debug!("Parser::add_defaults:iter:{}:", p.b.name); + add_val!(self, p, matcher); + } + Ok(()) + } + + pub fn add_env(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { + macro_rules! add_val { + ($_self:ident, $a:ident, $m:ident) => { + if let Some(ref val) = $a.v.env { + if $m + .get($a.b.name) + .map(|ma| ma.vals.len()) + .map(|len| len == 0) + .unwrap_or(false) + { + if let Some(ref val) = val.1 { + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } + } else { + if let Some(ref val) = val.1 { + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } + } + } + }; + } + + for o in &self.opts { + add_val!(self, o, matcher); + } + for p in self.positionals.values() { + add_val!(self, p, matcher); + } + Ok(()) + } + + pub fn flags(&self) -> Iter> { + self.flags.iter() + } + + pub fn opts(&self) -> Iter> { + self.opts.iter() + } + + pub fn positionals(&self) -> map::Values> { + self.positionals.values() + } + + pub fn subcommands(&self) -> Iter { + self.subcommands.iter() + } + + // Should we color the output? None=determined by output location, true=yes, false=no + #[doc(hidden)] + pub fn color(&self) -> ColorWhen { + debugln!("Parser::color;"); + debug!("Parser::color: Color setting..."); + if self.is_set(AS::ColorNever) { + sdebugln!("Never"); + ColorWhen::Never + } else if self.is_set(AS::ColorAlways) { + sdebugln!("Always"); + ColorWhen::Always + } else { + sdebugln!("Auto"); + ColorWhen::Auto + } + } + + pub fn find_any_arg(&self, name: &str) -> Option<&AnyArg<'a, 'b>> { + if let Some(f) = find_by_name!(self, name, flags, iter) { + return Some(f); + } + if let Some(o) = find_by_name!(self, name, opts, iter) { + return Some(o); + } + if let Some(p) = find_by_name!(self, name, positionals, values) { + return Some(p); + } + None + } + + /// Check is a given string matches the binary name for this parser + fn is_bin_name(&self, value: &str) -> bool { + self.meta + .bin_name + .as_ref() + .map(|name| value == name) + .unwrap_or(false) + } + + /// Check is a given string is an alias for this parser + fn is_alias(&self, value: &str) -> bool { + self.meta + .aliases + .as_ref() + .map(|aliases| { + for alias in aliases { + if alias.0 == value { + return true; + } + } + false + }) + .unwrap_or(false) + } + + // Only used for completion scripts due to bin_name messiness + #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))] + pub fn find_subcommand(&'b self, sc: &str) -> Option<&'b App<'a, 'b>> { + debugln!("Parser::find_subcommand: sc={}", sc); + debugln!( + "Parser::find_subcommand: Currently in Parser...{}", + self.meta.bin_name.as_ref().unwrap() + ); + for s in &self.subcommands { + if s.p.is_bin_name(sc) { + return Some(s); + } + // XXX: why do we split here? + // isn't `sc` supposed to be single word already? + let last = sc.split(' ').rev().next().expect(INTERNAL_ERROR_MSG); + if s.p.is_alias(last) { + return Some(s); + } + + if let Some(app) = s.p.find_subcommand(sc) { + return Some(app); + } + } + None + } + + #[inline] + fn contains_long(&self, l: &str) -> bool { + longs!(self).any(|al| al == &l) + } + + #[inline] + fn contains_short(&self, s: char) -> bool { + shorts!(self).any(|arg_s| arg_s == &s) + } +} diff --git a/bash-5.1/vendor/clap/src/app/settings.rs b/bash-5.1/vendor/clap/src/app/settings.rs new file mode 100644 index 0000000..e387d9e --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/settings.rs @@ -0,0 +1,1192 @@ +// Std +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; +use std::ops::BitOr; +use std::str::FromStr; + +bitflags! { + struct Flags: u64 { + const SC_NEGATE_REQS = 1; + const SC_REQUIRED = 1 << 1; + const A_REQUIRED_ELSE_HELP = 1 << 2; + const GLOBAL_VERSION = 1 << 3; + const VERSIONLESS_SC = 1 << 4; + const UNIFIED_HELP = 1 << 5; + const WAIT_ON_ERROR = 1 << 6; + const SC_REQUIRED_ELSE_HELP= 1 << 7; + const NEEDS_LONG_HELP = 1 << 8; + const NEEDS_LONG_VERSION = 1 << 9; + const NEEDS_SC_HELP = 1 << 10; + const DISABLE_VERSION = 1 << 11; + const HIDDEN = 1 << 12; + const TRAILING_VARARG = 1 << 13; + const NO_BIN_NAME = 1 << 14; + const ALLOW_UNK_SC = 1 << 15; + const UTF8_STRICT = 1 << 16; + const UTF8_NONE = 1 << 17; + const LEADING_HYPHEN = 1 << 18; + const NO_POS_VALUES = 1 << 19; + const NEXT_LINE_HELP = 1 << 20; + const DERIVE_DISP_ORDER = 1 << 21; + const COLORED_HELP = 1 << 22; + const COLOR_ALWAYS = 1 << 23; + const COLOR_AUTO = 1 << 24; + const COLOR_NEVER = 1 << 25; + const DONT_DELIM_TRAIL = 1 << 26; + const ALLOW_NEG_NUMS = 1 << 27; + const LOW_INDEX_MUL_POS = 1 << 28; + const DISABLE_HELP_SC = 1 << 29; + const DONT_COLLAPSE_ARGS = 1 << 30; + const ARGS_NEGATE_SCS = 1 << 31; + const PROPAGATE_VALS_DOWN = 1 << 32; + const ALLOW_MISSING_POS = 1 << 33; + const TRAILING_VALUES = 1 << 34; + const VALID_NEG_NUM_FOUND = 1 << 35; + const PROPAGATED = 1 << 36; + const VALID_ARG_FOUND = 1 << 37; + const INFER_SUBCOMMANDS = 1 << 38; + const CONTAINS_LAST = 1 << 39; + const ARGS_OVERRIDE_SELF = 1 << 40; + const DISABLE_HELP_FLAGS = 1 << 41; + } +} + +#[doc(hidden)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct AppFlags(Flags); + +impl BitOr for AppFlags { + type Output = Self; + fn bitor(self, rhs: Self) -> Self { + AppFlags(self.0 | rhs.0) + } +} + +impl Default for AppFlags { + fn default() -> Self { + AppFlags( + Flags::NEEDS_LONG_VERSION + | Flags::NEEDS_LONG_HELP + | Flags::NEEDS_SC_HELP + | Flags::UTF8_NONE + | Flags::COLOR_AUTO, + ) + } +} + +#[allow(deprecated)] +impl AppFlags { + pub fn new() -> Self { + AppFlags::default() + } + pub fn zeroed() -> Self { + AppFlags(Flags::empty()) + } + + impl_settings! { AppSettings, + ArgRequiredElseHelp => Flags::A_REQUIRED_ELSE_HELP, + ArgsNegateSubcommands => Flags::ARGS_NEGATE_SCS, + AllArgsOverrideSelf => Flags::ARGS_OVERRIDE_SELF, + AllowExternalSubcommands => Flags::ALLOW_UNK_SC, + AllowInvalidUtf8 => Flags::UTF8_NONE, + AllowLeadingHyphen => Flags::LEADING_HYPHEN, + AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS, + AllowMissingPositional => Flags::ALLOW_MISSING_POS, + ColoredHelp => Flags::COLORED_HELP, + ColorAlways => Flags::COLOR_ALWAYS, + ColorAuto => Flags::COLOR_AUTO, + ColorNever => Flags::COLOR_NEVER, + DontDelimitTrailingValues => Flags::DONT_DELIM_TRAIL, + DontCollapseArgsInUsage => Flags::DONT_COLLAPSE_ARGS, + DeriveDisplayOrder => Flags::DERIVE_DISP_ORDER, + DisableHelpFlags => Flags::DISABLE_HELP_FLAGS, + DisableHelpSubcommand => Flags::DISABLE_HELP_SC, + DisableVersion => Flags::DISABLE_VERSION, + GlobalVersion => Flags::GLOBAL_VERSION, + HidePossibleValuesInHelp => Flags::NO_POS_VALUES, + Hidden => Flags::HIDDEN, + LowIndexMultiplePositional => Flags::LOW_INDEX_MUL_POS, + NeedsLongHelp => Flags::NEEDS_LONG_HELP, + NeedsLongVersion => Flags::NEEDS_LONG_VERSION, + NeedsSubcommandHelp => Flags::NEEDS_SC_HELP, + NoBinaryName => Flags::NO_BIN_NAME, + PropagateGlobalValuesDown=> Flags::PROPAGATE_VALS_DOWN, + StrictUtf8 => Flags::UTF8_STRICT, + SubcommandsNegateReqs => Flags::SC_NEGATE_REQS, + SubcommandRequired => Flags::SC_REQUIRED, + SubcommandRequiredElseHelp => Flags::SC_REQUIRED_ELSE_HELP, + TrailingVarArg => Flags::TRAILING_VARARG, + UnifiedHelpMessage => Flags::UNIFIED_HELP, + NextLineHelp => Flags::NEXT_LINE_HELP, + VersionlessSubcommands => Flags::VERSIONLESS_SC, + WaitOnError => Flags::WAIT_ON_ERROR, + TrailingValues => Flags::TRAILING_VALUES, + ValidNegNumFound => Flags::VALID_NEG_NUM_FOUND, + Propagated => Flags::PROPAGATED, + ValidArgFound => Flags::VALID_ARG_FOUND, + InferSubcommands => Flags::INFER_SUBCOMMANDS, + ContainsLast => Flags::CONTAINS_LAST + } +} + +/// Application level settings, which affect how [`App`] operates +/// +/// **NOTE:** When these settings are used, they apply only to current command, and are *not* +/// propagated down or up through child or parent subcommands +/// +/// [`App`]: ./struct.App.html +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum AppSettings { + /// Specifies that any invalid UTF-8 code points should *not* be treated as an error. + /// This is the default behavior of `clap`. + /// + /// **NOTE:** Using argument values with invalid UTF-8 code points requires using + /// [`ArgMatches::os_value_of`], [`ArgMatches::os_values_of`], [`ArgMatches::lossy_value_of`], + /// or [`ArgMatches::lossy_values_of`] for those particular arguments which may contain invalid + /// UTF-8 values + /// + /// **NOTE:** This rule only applies to argument values, as flags, options, and + /// [`SubCommand`]s themselves only allow valid UTF-8 code points. + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, AppSettings}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let r = App::new("myprog") + /// //.setting(AppSettings::AllowInvalidUtf8) + /// .arg_from_usage(" 'some positional arg'") + /// .get_matches_from_safe( + /// vec![ + /// OsString::from("myprog"), + /// OsString::from_vec(vec![0xe9])]); + /// + /// assert!(r.is_ok()); + /// let m = r.unwrap(); + /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]); + /// ``` + /// [`ArgMatches::os_value_of`]: ./struct.ArgMatches.html#method.os_value_of + /// [`ArgMatches::os_values_of`]: ./struct.ArgMatches.html#method.os_values_of + /// [`ArgMatches::lossy_value_of`]: ./struct.ArgMatches.html#method.lossy_value_of + /// [`ArgMatches::lossy_values_of`]: ./struct.ArgMatches.html#method.lossy_values_of + /// [`SubCommand`]: ./struct.SubCommand.html + AllowInvalidUtf8, + + /// Essentially sets [`Arg::overrides_with("itself")`] for all arguments. + /// + /// **WARNING:** Positional arguments cannot override themselves (or we would never be able + /// to advance to the next positional). This setting ignores positional arguments. + /// [`Arg::overrides_with("itself")`]: ./struct.Arg.html#method.overrides_with + AllArgsOverrideSelf, + + /// Specifies that leading hyphens are allowed in argument *values*, such as negative numbers + /// like `-10`. (which would otherwise be parsed as another flag or option) + /// + /// **NOTE:** Use this setting with caution as it silences certain circumstances which would + /// otherwise be an error (such as accidentally forgetting to specify a value for leading + /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Arg, App, AppSettings}; + /// // Imagine you needed to represent negative numbers as well, such as -10 + /// let m = App::new("nums") + /// .setting(AppSettings::AllowLeadingHyphen) + /// .arg(Arg::with_name("neg").index(1)) + /// .get_matches_from(vec![ + /// "nums", "-20" + /// ]); + /// + /// assert_eq!(m.value_of("neg"), Some("-20")); + /// # ; + /// ``` + /// [`Arg::allow_hyphen_values`]: ./struct.Arg.html#method.allow_hyphen_values + AllowLeadingHyphen, + + /// Allows negative numbers to pass as values. This is similar to + /// `AllowLeadingHyphen` except that it only allows numbers, all + /// other undefined leading hyphens will fail to parse. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::AllowNegativeNumbers) + /// .arg(Arg::with_name("num")) + /// .get_matches_from_safe(vec![ + /// "myprog", "-20" + /// ]); + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("num").unwrap(), "-20"); + /// ``` + /// [`AllowLeadingHyphen`]: ./enum.AppSettings.html#variant.AllowLeadingHyphen + AllowNegativeNumbers, + + /// Allows one to implement two styles of CLIs where positionals can be used out of order. + /// + /// The first example is a CLI where the second to last positional argument is optional, but + /// the final positional argument is required. Such as `$ prog [optional] ` where one + /// of the two following usages is allowed: + /// + /// * `$ prog [optional] ` + /// * `$ prog ` + /// + /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. + /// + /// **Note:** when using this style of "missing positionals" the final positional *must* be + /// [required] if `--` will not be used to skip to the final positional argument. + /// + /// **Note:** This style also only allows a single positional argument to be "skipped" without + /// the use of `--`. To skip more than one, see the second example. + /// + /// The second example is when one wants to skip multiple optional positional arguments, and use + /// of the `--` operator is OK (but not required if all arguments will be specified anyways). + /// + /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where + /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). + /// + /// With this setting the following invocations are possible: + /// + /// * `$ prog foo bar baz1 baz2 baz3` + /// * `$ prog foo -- baz1 baz2 baz3` + /// * `$ prog -- baz1 baz2 baz3` + /// + /// # Examples + /// + /// Style number one from above: + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("arg1")) + /// .arg(Arg::with_name("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), None); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// + /// Now the same example, but using a default value for the first optional positional argument + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("arg1") + /// .default_value("something")) + /// .arg(Arg::with_name("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), Some("something")); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// Style number two from above: + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("foo")) + /// .arg(Arg::with_name("bar")) + /// .arg(Arg::with_name("baz").multiple(true)) + /// .get_matches_from(vec![ + /// "prog", "foo", "bar", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), Some("foo")); + /// assert_eq!(m.value_of("bar"), Some("bar")); + /// assert_eq!(m.values_of("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// Now notice if we don't specify `foo` or `baz` but use the `--` operator. + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("foo")) + /// .arg(Arg::with_name("bar")) + /// .arg(Arg::with_name("baz").multiple(true)) + /// .get_matches_from(vec![ + /// "prog", "--", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), None); + /// assert_eq!(m.value_of("bar"), None); + /// assert_eq!(m.values_of("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// [required]: ./struct.Arg.html#method.required + AllowMissingPositional, + + /// Specifies that an unexpected positional argument, + /// which would otherwise cause a [`ErrorKind::UnknownArgument`] error, + /// should instead be treated as a [`SubCommand`] within the [`ArgMatches`] struct. + /// + /// **NOTE:** Use this setting with caution, + /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) + /// will **not** cause an error and instead be treated as a potential subcommand. + /// One should check for such cases manually and inform the user appropriately. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowExternalSubcommands) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// (external, Some(ext_m)) => { + /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// [`ErrorKind::UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`ArgMatches`]: ./struct.ArgMatches.html + AllowExternalSubcommands, + + /// Specifies that use of a valid [argument] negates [subcommands] being used after. By default + /// `clap` allows arguments between subcommands such as + /// ` [cmd_args] [cmd2_args] [cmd3_args]`. This setting disables that + /// functionality and says that arguments can only follow the *final* subcommand. For instance + /// using this setting makes only the following invocations possible: + /// + /// * ` [cmd3_args]` + /// * ` [cmd2_args]` + /// * ` [cmd_args]` + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ArgsNegateSubcommands) + /// # ; + /// ``` + /// [subcommands]: ./struct.SubCommand.html + /// [argument]: ./struct.Arg.html + ArgsNegateSubcommands, + + /// Specifies that the help text should be displayed (and then exit gracefully), + /// if no arguments are present at runtime (i.e. an empty run such as, `$ myprog`. + /// + /// **NOTE:** [`SubCommand`]s count as arguments + /// + /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will + /// ensure that some argument is always present. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ArgRequiredElseHelp) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value + ArgRequiredElseHelp, + + /// Uses colorized help messages. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColoredHelp) + /// .get_matches(); + /// ``` + ColoredHelp, + + /// Enables colored output only when the output is going to a terminal or TTY. + /// + /// **NOTE:** This is the default behavior of `clap`. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColorAuto) + /// .get_matches(); + /// ``` + ColorAuto, + + /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColorAlways) + /// .get_matches(); + /// ``` + ColorAlways, + + /// Disables colored output no matter if the output is going to a terminal/TTY, or not. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColorNever) + /// .get_matches(); + /// ``` + ColorNever, + + /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DontCollapseArgsInUsage) + /// .get_matches(); + /// ``` + DontCollapseArgsInUsage, + + /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`] + /// was used. + /// + /// **NOTE:** The same thing can be done manually by setting the final positional argument to + /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate + /// when making changes. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DontDelimitTrailingValues) + /// .get_matches(); + /// ``` + /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg + /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter + DontDelimitTrailingValues, + + /// Disables `-h` and `--help` [`App`] without affecting any of the [`SubCommand`]s + /// (Defaults to `false`; application *does* have help flags) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableHelpFlags) + /// .get_matches_from_safe(vec![ + /// "myprog", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// + /// ```rust + /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableHelpFlags) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::HelpDisplayed); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + DisableHelpFlags, + + /// Disables the `help` subcommand + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind, SubCommand}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::DisableHelpSubcommand) + /// // Normally, creating a subcommand causes a `help` subcommand to automatically + /// // be generated as well + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "help" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + DisableHelpSubcommand, + + /// Disables `-V` and `--version` [`App`] without affecting any of the [`SubCommand`]s + /// (Defaults to `false`; application *does* have a version flag) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::DisableVersion) + /// .get_matches_from_safe(vec![ + /// "myprog", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// + /// ```rust + /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::DisableVersion) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + DisableVersion, + + /// Displays the arguments and [`SubCommand`]s in the help message in the order that they were + /// declared in, and not alphabetically which is the default. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DeriveDisplayOrder) + /// .get_matches(); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + DeriveDisplayOrder, + + /// Specifies to use the version of the current command for all child [`SubCommand`]s. + /// (Defaults to `false`; subcommands have independent version strings from their parents.) + /// + /// **NOTE:** The version for the current command **and** this setting must be set **prior** to + /// adding any child subcommands + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::GlobalVersion) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches(); + /// // running `$ myprog test --version` will display + /// // "myprog-test v1.1" + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + GlobalVersion, + + /// Specifies that this [`SubCommand`] should be hidden from help messages + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand}; + /// App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .setting(AppSettings::Hidden)) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + Hidden, + + /// Tells `clap` *not* to print possible values when displaying help information. + /// This can be useful if there are many values, or they are explained elsewhere. + HidePossibleValuesInHelp, + + /// Tries to match unknown args to partial [`subcommands`] or their [aliases]. For example to + /// match a subcommand named `test`, one could use `t`, `te`, `tes`, and `test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` + /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` + /// + /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when + /// designing CLIs which allow inferred subcommands and have potential positional/free + /// arguments whose values could start with the same characters as subcommands. If this is the + /// case, it's recommended to use settings such as [`AppSeettings::ArgsNegateSubcommands`] in + /// conjunction with this setting. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// let m = App::new("prog") + /// .setting(AppSettings::InferSubcommands) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from(vec![ + /// "prog", "te" + /// ]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`subcommands`]: ./struct.SubCommand.html + /// [positional/free arguments]: ./struct.Arg.html#method.index + /// [aliases]: ./struct.App.html#method.alias + /// [`AppSeettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands + InferSubcommands, + + /// Specifies that the parser should not assume the first argument passed is the binary name. + /// This is normally the case when using a "daemon" style mode, or an interactive CLI where one + /// one would not normally type the binary or program name for each command. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let m = App::new("myprog") + /// .setting(AppSettings::NoBinaryName) + /// .arg(Arg::from_usage("... 'commands to run'")) + /// .get_matches_from(vec!["command", "set"]); + /// + /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(cmds, ["command", "set"]); + /// ``` + NoBinaryName, + + /// Places the help string for all arguments on the line after the argument. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::NextLineHelp) + /// .get_matches(); + /// ``` + NextLineHelp, + + /// **DEPRECATED**: This setting is no longer required in order to propagate values up or down + /// + /// Specifies that the parser should propagate global arg's values down or up through any *used* + /// child subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated to + /// said subcommand. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand}; + /// let m = App::new("myprog") + /// .arg(Arg::from_usage("[cmd] 'command to run'") + /// .global(true)) + /// .subcommand(SubCommand::with_name("foo")) + /// .get_matches_from(vec!["myprog", "set", "foo"]); + /// + /// assert_eq!(m.value_of("cmd"), Some("set")); + /// + /// let sub_m = m.subcommand_matches("foo").unwrap(); + /// assert_eq!(sub_m.value_of("cmd"), Some("set")); + /// ``` + /// Now doing the same thing, but *not* using any subcommands will result in the value not being + /// propagated down. + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand}; + /// let m = App::new("myprog") + /// .arg(Arg::from_usage("[cmd] 'command to run'") + /// .global(true)) + /// .subcommand(SubCommand::with_name("foo")) + /// .get_matches_from(vec!["myprog", "set"]); + /// + /// assert_eq!(m.value_of("cmd"), Some("set")); + /// + /// assert!(m.subcommand_matches("foo").is_none()); + /// ``` + #[deprecated(since = "2.27.0", note = "No longer required to propagate values")] + PropagateGlobalValuesDown, + + /// Allows [`SubCommand`]s to override all requirements of the parent command. + /// For example if you had a subcommand or top level application with a required argument + /// that is only required as long as there is no subcommand present, + /// using this setting would allow you to set those arguments to [`Arg::required(true)`] + /// and yet receive no error so long as the user uses a valid subcommand instead. + /// + /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) + /// + /// # Examples + /// + /// This first example shows that it is an error to not use a required argument + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind}; + /// let err = App::new("myprog") + /// .setting(AppSettings::SubcommandsNegateReqs) + /// .arg(Arg::with_name("opt").required(true)) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog" + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// # ; + /// ``` + /// + /// This next example shows that it is no longer error to not use a required argument if a + /// valid subcommand is used. + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind}; + /// let noerr = App::new("myprog") + /// .setting(AppSettings::SubcommandsNegateReqs) + /// .arg(Arg::with_name("opt").required(true)) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test" + /// ]); + /// assert!(noerr.is_ok()); + /// # ; + /// ``` + /// [`Arg::required(true)`]: ./struct.Arg.html#method.required + /// [`SubCommand`]: ./struct.SubCommand.html + SubcommandsNegateReqs, + + /// Specifies that the help text should be displayed (before exiting gracefully) if no + /// [`SubCommand`]s are present at runtime (i.e. an empty run such as `$ myprog`). + /// + /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do + /// nearly same thing; this prints the help text, and the other prints an error. + /// + /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will + /// still be displayed and exit. If this is *not* the desired result, consider using + /// [`AppSettings::ArgRequiredElseHelp`] instead. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::SubcommandRequiredElseHelp) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired + /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp + SubcommandRequiredElseHelp, + + /// Specifies that any invalid UTF-8 code points should be treated as an error and fail + /// with a [`ErrorKind::InvalidUtf8`] error. + /// + /// **NOTE:** This rule only applies to argument values; Things such as flags, options, and + /// [`SubCommand`]s themselves only allow valid UTF-8 code points. + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, AppSettings, ErrorKind}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::OsStringExt; + /// + /// let m = App::new("myprog") + /// .setting(AppSettings::StrictUtf8) + /// .arg_from_usage(" 'some positional arg'") + /// .get_matches_from_safe( + /// vec![ + /// OsString::from("myprog"), + /// OsString::from_vec(vec![0xe9])]); + /// + /// assert!(m.is_err()); + /// assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`ErrorKind::InvalidUtf8`]: ./enum.ErrorKind.html#variant.InvalidUtf8 + StrictUtf8, + + /// Allows specifying that if no [`SubCommand`] is present at runtime, + /// error and exit gracefully. + /// + /// **NOTE:** This defaults to `false` (subcommands do *not* need to be present) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, SubCommand, ErrorKind}; + /// let err = App::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + SubcommandRequired, + + /// Specifies that the final positional argument is a "VarArg" and that `clap` should not + /// attempt to parse any further args. + /// + /// The values of the trailing positional argument will contain all args from itself on. + /// + /// **NOTE:** The final positional argument **must** have [`Arg::multiple(true)`] or the usage + /// string equivalent. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let m = App::new("myprog") + /// .setting(AppSettings::TrailingVarArg) + /// .arg(Arg::from_usage("... 'commands to run'")) + /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + /// + /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(trail, ["arg1", "-r", "val1"]); + /// ``` + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + TrailingVarArg, + + /// Groups flags and options together, presenting a more unified help message + /// (a la `getopts` or `docopt` style). + /// + /// The default is that the auto-generated help message will group flags, and options + /// separately. + /// + /// **NOTE:** This setting is cosmetic only and does not affect any functionality. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::UnifiedHelpMessage) + /// .get_matches(); + /// // running `myprog --help` will display a unified "docopt" or "getopts" style help message + /// ``` + UnifiedHelpMessage, + + /// Disables `-V` and `--version` for all [`SubCommand`]s + /// (Defaults to `false`; subcommands *do* have version flags.) + /// + /// **NOTE:** This setting must be set **prior** to adding any subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::VersionlessSubcommands) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + VersionlessSubcommands, + + /// Will display a message "Press \[ENTER\]/\[RETURN\] to continue..." and wait for user before + /// exiting + /// + /// This is most useful when writing an application which is run from a GUI shortcut, or on + /// Windows where a user tries to open the binary by double-clicking instead of using the + /// command line. + /// + /// **NOTE:** This setting is **not** recursive with [`SubCommand`]s, meaning if you wish this + /// behavior for all subcommands, you must set this on each command (needing this is extremely + /// rare) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::WaitOnError) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + WaitOnError, + + #[doc(hidden)] + NeedsLongVersion, + + #[doc(hidden)] + NeedsLongHelp, + + #[doc(hidden)] + NeedsSubcommandHelp, + + #[doc(hidden)] + LowIndexMultiplePositional, + + #[doc(hidden)] + TrailingValues, + + #[doc(hidden)] + ValidNegNumFound, + + #[doc(hidden)] + Propagated, + + #[doc(hidden)] + ValidArgFound, + + #[doc(hidden)] + ContainsLast, +} + +impl FromStr for AppSettings { + type Err = String; + fn from_str(s: &str) -> Result::Err> { + match &*s.to_ascii_lowercase() { + "disablehelpflags" => Ok(AppSettings::DisableHelpFlags), + "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp), + "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands), + "allowinvalidutf8" => Ok(AppSettings::AllowInvalidUtf8), + "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen), + "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands), + "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers), + "colorauto" => Ok(AppSettings::ColorAuto), + "coloralways" => Ok(AppSettings::ColorAlways), + "colornever" => Ok(AppSettings::ColorNever), + "coloredhelp" => Ok(AppSettings::ColoredHelp), + "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder), + "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage), + "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues), + "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand), + "disableversion" => Ok(AppSettings::DisableVersion), + "globalversion" => Ok(AppSettings::GlobalVersion), + "hidden" => Ok(AppSettings::Hidden), + "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp), + "infersubcommands" => Ok(AppSettings::InferSubcommands), + "lowindexmultiplepositional" => Ok(AppSettings::LowIndexMultiplePositional), + "nobinaryname" => Ok(AppSettings::NoBinaryName), + "nextlinehelp" => Ok(AppSettings::NextLineHelp), + "strictutf8" => Ok(AppSettings::StrictUtf8), + "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs), + "subcommandrequired" => Ok(AppSettings::SubcommandRequired), + "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp), + "trailingvararg" => Ok(AppSettings::TrailingVarArg), + "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage), + "versionlesssubcommands" => Ok(AppSettings::VersionlessSubcommands), + "waitonerror" => Ok(AppSettings::WaitOnError), + "validnegnumfound" => Ok(AppSettings::ValidNegNumFound), + "validargfound" => Ok(AppSettings::ValidArgFound), + "propagated" => Ok(AppSettings::Propagated), + "trailingvalues" => Ok(AppSettings::TrailingValues), + _ => Err("unknown AppSetting, cannot convert from str".to_owned()), + } + } +} + +#[cfg(test)] +mod test { + use super::AppSettings; + + #[test] + fn app_settings_fromstr() { + assert_eq!( + "disablehelpflags".parse::().unwrap(), + AppSettings::DisableHelpFlags + ); + assert_eq!( + "argsnegatesubcommands".parse::().unwrap(), + AppSettings::ArgsNegateSubcommands + ); + assert_eq!( + "argrequiredelsehelp".parse::().unwrap(), + AppSettings::ArgRequiredElseHelp + ); + assert_eq!( + "allowexternalsubcommands".parse::().unwrap(), + AppSettings::AllowExternalSubcommands + ); + assert_eq!( + "allowinvalidutf8".parse::().unwrap(), + AppSettings::AllowInvalidUtf8 + ); + assert_eq!( + "allowleadinghyphen".parse::().unwrap(), + AppSettings::AllowLeadingHyphen + ); + assert_eq!( + "allownegativenumbers".parse::().unwrap(), + AppSettings::AllowNegativeNumbers + ); + assert_eq!( + "coloredhelp".parse::().unwrap(), + AppSettings::ColoredHelp + ); + assert_eq!( + "colorauto".parse::().unwrap(), + AppSettings::ColorAuto + ); + assert_eq!( + "coloralways".parse::().unwrap(), + AppSettings::ColorAlways + ); + assert_eq!( + "colornever".parse::().unwrap(), + AppSettings::ColorNever + ); + assert_eq!( + "disablehelpsubcommand".parse::().unwrap(), + AppSettings::DisableHelpSubcommand + ); + assert_eq!( + "disableversion".parse::().unwrap(), + AppSettings::DisableVersion + ); + assert_eq!( + "dontcollapseargsinusage".parse::().unwrap(), + AppSettings::DontCollapseArgsInUsage + ); + assert_eq!( + "dontdelimittrailingvalues".parse::().unwrap(), + AppSettings::DontDelimitTrailingValues + ); + assert_eq!( + "derivedisplayorder".parse::().unwrap(), + AppSettings::DeriveDisplayOrder + ); + assert_eq!( + "globalversion".parse::().unwrap(), + AppSettings::GlobalVersion + ); + assert_eq!( + "hidden".parse::().unwrap(), + AppSettings::Hidden + ); + assert_eq!( + "hidepossiblevaluesinhelp".parse::().unwrap(), + AppSettings::HidePossibleValuesInHelp + ); + assert_eq!( + "lowindexmultiplePositional".parse::().unwrap(), + AppSettings::LowIndexMultiplePositional + ); + assert_eq!( + "nobinaryname".parse::().unwrap(), + AppSettings::NoBinaryName + ); + assert_eq!( + "nextlinehelp".parse::().unwrap(), + AppSettings::NextLineHelp + ); + assert_eq!( + "subcommandsnegatereqs".parse::().unwrap(), + AppSettings::SubcommandsNegateReqs + ); + assert_eq!( + "subcommandrequired".parse::().unwrap(), + AppSettings::SubcommandRequired + ); + assert_eq!( + "subcommandrequiredelsehelp".parse::().unwrap(), + AppSettings::SubcommandRequiredElseHelp + ); + assert_eq!( + "strictutf8".parse::().unwrap(), + AppSettings::StrictUtf8 + ); + assert_eq!( + "trailingvararg".parse::().unwrap(), + AppSettings::TrailingVarArg + ); + assert_eq!( + "unifiedhelpmessage".parse::().unwrap(), + AppSettings::UnifiedHelpMessage + ); + assert_eq!( + "versionlesssubcommands".parse::().unwrap(), + AppSettings::VersionlessSubcommands + ); + assert_eq!( + "waitonerror".parse::().unwrap(), + AppSettings::WaitOnError + ); + assert_eq!( + "validnegnumfound".parse::().unwrap(), + AppSettings::ValidNegNumFound + ); + assert_eq!( + "validargfound".parse::().unwrap(), + AppSettings::ValidArgFound + ); + assert_eq!( + "propagated".parse::().unwrap(), + AppSettings::Propagated + ); + assert_eq!( + "trailingvalues".parse::().unwrap(), + AppSettings::TrailingValues + ); + assert_eq!( + "infersubcommands".parse::().unwrap(), + AppSettings::InferSubcommands + ); + assert!("hahahaha".parse::().is_err()); + } +} diff --git a/bash-5.1/vendor/clap/src/app/usage.rs b/bash-5.1/vendor/clap/src/app/usage.rs new file mode 100644 index 0000000..e68f2f4 --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/usage.rs @@ -0,0 +1,493 @@ +// std +use std::collections::{BTreeMap, VecDeque}; + +// Internal +use crate::{ + app::{parser::Parser, settings::AppSettings as AS}, + args::{settings::ArgSettings, AnyArg, ArgMatcher, PosBuilder}, + INTERNAL_ERROR_MSG, +}; + +// Creates a usage string for display. This happens just after all arguments were parsed, but before +// any subcommands have been parsed (so as to give subcommands their own usage recursively) +pub fn create_usage_with_title(p: &Parser, used: &[&str]) -> String { + debugln!("usage::create_usage_with_title;"); + let mut usage = String::with_capacity(75); + usage.push_str("USAGE:\n "); + usage.push_str(&*create_usage_no_title(p, used)); + usage +} + +// Creates a usage string to be used in error message (i.e. one with currently used args) +pub fn create_error_usage<'a, 'b>( + p: &Parser<'a, 'b>, + matcher: &'b ArgMatcher<'a>, + extra: Option<&str>, +) -> String { + let mut args: Vec<_> = matcher + .arg_names() + .iter() + .filter(|n| { + if let Some(o) = find_by_name!(p, **n, opts, iter) { + !o.b.is_set(ArgSettings::Required) && !o.b.is_set(ArgSettings::Hidden) + } else if let Some(p) = find_by_name!(p, **n, positionals, values) { + !p.b.is_set(ArgSettings::Required) && p.b.is_set(ArgSettings::Hidden) + } else { + true // flags can't be required, so they're always true + } + }) + .copied() + .collect(); + if let Some(r) = extra { + args.push(r); + } + create_usage_with_title(p, &*args) +} + +// Creates a usage string (*without title*) if one was not provided by the user manually. +pub fn create_usage_no_title(p: &Parser, used: &[&str]) -> String { + debugln!("usage::create_usage_no_title;"); + if let Some(u) = p.meta.usage_str { + String::from(&*u) + } else if used.is_empty() { + create_help_usage(p, true) + } else { + create_smart_usage(p, used) + } +} + +// Creates a usage string for display in help messages (i.e. not for errors) +pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String { + let mut usage = String::with_capacity(75); + let name = p + .meta + .usage + .as_ref() + .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name)); + usage.push_str(&*name); + let req_string = if incl_reqs { + let mut reqs: Vec<&str> = p.required().map(|r| &**r).collect(); + reqs.sort_unstable(); + reqs.dedup(); + get_required_usage_from(p, &reqs, None, None, false) + .iter() + .fold(String::new(), |a, s| a + &format!(" {}", s)[..]) + } else { + String::new() + }; + + let flags = needs_flags_tag(p); + if flags && !p.is_set(AS::UnifiedHelpMessage) { + usage.push_str(" [FLAGS]"); + } else if flags { + usage.push_str(" [OPTIONS]"); + } + if !p.is_set(AS::UnifiedHelpMessage) + && p.opts + .iter() + .any(|o| !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden)) + { + usage.push_str(" [OPTIONS]"); + } + + usage.push_str(&req_string[..]); + + let has_last = p.positionals.values().any(|p| p.is_set(ArgSettings::Last)); + // places a '--' in the usage string if there are args and options + // supporting multiple values + if p.opts.iter().any(|o| o.is_set(ArgSettings::Multiple)) + && p.positionals + .values() + .any(|p| !p.is_set(ArgSettings::Required)) + && !(p.has_visible_subcommands() || p.is_set(AS::AllowExternalSubcommands)) + && !has_last + { + usage.push_str(" [--]"); + } + let not_req_or_hidden = |p: &PosBuilder| { + (!p.is_set(ArgSettings::Required) || p.is_set(ArgSettings::Last)) + && !p.is_set(ArgSettings::Hidden) + }; + if p.has_positionals() && p.positionals.values().any(not_req_or_hidden) { + if let Some(args_tag) = get_args_tag(p, incl_reqs) { + usage.push_str(&*args_tag); + } else { + usage.push_str(" [ARGS]"); + } + if has_last && incl_reqs { + let pos = p + .positionals + .values() + .find(|p| p.b.is_set(ArgSettings::Last)) + .expect(INTERNAL_ERROR_MSG); + debugln!("usage::create_help_usage: '{}' has .last(true)", pos.name()); + let req = pos.is_set(ArgSettings::Required); + if req + && p.positionals + .values() + .any(|p| !p.is_set(ArgSettings::Required)) + { + usage.push_str(" -- <"); + } else if req { + usage.push_str(" [--] <"); + } else { + usage.push_str(" [-- <"); + } + usage.push_str(&*pos.name_no_brackets()); + usage.push('>'); + usage.push_str(pos.multiple_str()); + if !req { + usage.push(']'); + } + } + } + + // incl_reqs is only false when this function is called recursively + if p.has_visible_subcommands() && incl_reqs || p.is_set(AS::AllowExternalSubcommands) { + if p.is_set(AS::SubcommandsNegateReqs) || p.is_set(AS::ArgsNegateSubcommands) { + usage.push_str("\n "); + if !p.is_set(AS::ArgsNegateSubcommands) { + usage.push_str(&*create_help_usage(p, false)); + } else { + usage.push_str(&*name); + } + usage.push_str(" "); + } else if p.is_set(AS::SubcommandRequired) || p.is_set(AS::SubcommandRequiredElseHelp) { + usage.push_str(" "); + } else { + usage.push_str(" [SUBCOMMAND]"); + } + } + usage.shrink_to_fit(); + debugln!("usage::create_help_usage: usage={}", usage); + usage +} + +// Creates a context aware usage string, or "smart usage" from currently used +// args, and requirements +fn create_smart_usage(p: &Parser, used: &[&str]) -> String { + debugln!("usage::smart_usage;"); + let mut usage = String::with_capacity(75); + let mut hs: Vec<&str> = p.required().map(|s| &**s).collect(); + hs.extend_from_slice(used); + + let r_string = get_required_usage_from(p, &hs, None, None, false) + .iter() + .fold(String::new(), |acc, s| acc + &format!(" {}", s)[..]); + + usage.push_str( + &p.meta + .usage + .as_ref() + .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name))[..], + ); + usage.push_str(&*r_string); + if p.is_set(AS::SubcommandRequired) { + usage.push_str(" "); + } + usage.shrink_to_fit(); + usage +} + +// Gets the `[ARGS]` tag for the usage string +fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option { + debugln!("usage::get_args_tag;"); + let mut count = 0; + 'outer: for pos in p + .positionals + .values() + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + { + debugln!("usage::get_args_tag:iter:{}:", pos.b.name); + if let Some(g_vec) = p.groups_for_arg(pos.b.name) { + for grp_s in &g_vec { + debugln!("usage::get_args_tag:iter:{}:iter:{};", pos.b.name, grp_s); + // if it's part of a required group we don't want to count it + if p.groups.iter().any(|g| g.required && (&g.name == grp_s)) { + continue 'outer; + } + } + } + count += 1; + debugln!( + "usage::get_args_tag:iter: {} Args not required or hidden", + count + ); + } + if !p.is_set(AS::DontCollapseArgsInUsage) && count > 1 { + debugln!("usage::get_args_tag:iter: More than one, returning [ARGS]"); + return None; // [ARGS] + } else if count == 1 && incl_reqs { + let pos = p + .positionals + .values() + .find(|pos| { + !pos.is_set(ArgSettings::Required) + && !pos.is_set(ArgSettings::Hidden) + && !pos.is_set(ArgSettings::Last) + }) + .expect(INTERNAL_ERROR_MSG); + debugln!( + "usage::get_args_tag:iter: Exactly one, returning '{}'", + pos.name() + ); + return Some(format!( + " [{}]{}", + pos.name_no_brackets(), + pos.multiple_str() + )); + } else if p.is_set(AS::DontCollapseArgsInUsage) && !p.positionals.is_empty() && incl_reqs { + debugln!("usage::get_args_tag:iter: Don't collapse returning all"); + return Some( + p.positionals + .values() + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) + .collect::>() + .join(""), + ); + } else if !incl_reqs { + debugln!("usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); + let highest_req_pos = p + .positionals + .iter() + .filter_map(|(idx, pos)| { + if pos.b.is_set(ArgSettings::Required) && !pos.b.is_set(ArgSettings::Last) { + Some(idx) + } else { + None + } + }) + .max() + .unwrap_or_else(|| p.positionals.len()); + return Some( + p.positionals + .iter() + .filter_map(|(idx, pos)| { + if idx <= highest_req_pos { + Some(pos) + } else { + None + } + }) + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) + .collect::>() + .join(""), + ); + } + Some("".into()) +} + +// Determines if we need the `[FLAGS]` tag in the usage string +fn needs_flags_tag(p: &Parser) -> bool { + debugln!("usage::needs_flags_tag;"); + 'outer: for f in &p.flags { + debugln!("usage::needs_flags_tag:iter: f={};", f.b.name); + if let Some(l) = f.s.long { + if l == "help" || l == "version" { + // Don't print `[FLAGS]` just for help or version + continue; + } + } + if let Some(g_vec) = p.groups_for_arg(f.b.name) { + for grp_s in &g_vec { + debugln!("usage::needs_flags_tag:iter:iter: grp_s={};", grp_s); + if p.groups.iter().any(|g| &g.name == grp_s && g.required) { + debugln!("usage::needs_flags_tag:iter:iter: Group is required"); + continue 'outer; + } + } + } + if f.is_set(ArgSettings::Hidden) { + continue; + } + debugln!("usage::needs_flags_tag:iter: [FLAGS] required"); + return true; + } + + debugln!("usage::needs_flags_tag: [FLAGS] not required"); + false +} + +// Returns the required args in usage string form by fully unrolling all groups +pub fn get_required_usage_from<'a, 'b>( + p: &Parser<'a, 'b>, + reqs: &[&'a str], + matcher: Option<&ArgMatcher<'a>>, + extra: Option<&str>, + incl_last: bool, +) -> VecDeque { + debugln!( + "usage::get_required_usage_from: reqs={:?}, extra={:?}", + reqs, + extra + ); + let mut desc_reqs: Vec<&str> = vec![]; + desc_reqs.extend(extra); + let mut new_reqs: Vec<&str> = vec![]; + macro_rules! get_requires { + (@group $a: ident, $v:ident, $p:ident) => {{ + if let Some(rl) = p + .groups + .iter() + .filter(|g| g.requires.is_some()) + .find(|g| &g.name == $a) + .map(|g| g.requires.as_ref().unwrap()) + { + for r in rl { + if !$p.contains(&r) { + debugln!( + "usage::get_required_usage_from:iter:{}: adding group req={:?}", + $a, + r + ); + $v.push(r); + } + } + } + }}; + ($a:ident, $what:ident, $how:ident, $v:ident, $p:ident) => {{ + if let Some(rl) = p + .$what + .$how() + .filter(|a| a.b.requires.is_some()) + .find(|arg| &arg.b.name == $a) + .map(|a| a.b.requires.as_ref().unwrap()) + { + for &(_, r) in rl.iter() { + if !$p.contains(&r) { + debugln!( + "usage::get_required_usage_from:iter:{}: adding arg req={:?}", + $a, + r + ); + $v.push(r); + } + } + } + }}; + } + // initialize new_reqs + for a in reqs { + get_requires!(a, flags, iter, new_reqs, reqs); + get_requires!(a, opts, iter, new_reqs, reqs); + get_requires!(a, positionals, values, new_reqs, reqs); + get_requires!(@group a, new_reqs, reqs); + } + desc_reqs.extend_from_slice(&*new_reqs); + debugln!( + "usage::get_required_usage_from: after init desc_reqs={:?}", + desc_reqs + ); + loop { + let mut tmp = vec![]; + for a in &new_reqs { + get_requires!(a, flags, iter, tmp, desc_reqs); + get_requires!(a, opts, iter, tmp, desc_reqs); + get_requires!(a, positionals, values, tmp, desc_reqs); + get_requires!(@group a, tmp, desc_reqs); + } + if tmp.is_empty() { + debugln!("usage::get_required_usage_from: no more children"); + break; + } else { + debugln!("usage::get_required_usage_from: after iter tmp={:?}", tmp); + debugln!( + "usage::get_required_usage_from: after iter new_reqs={:?}", + new_reqs + ); + desc_reqs.extend_from_slice(&*new_reqs); + new_reqs.clear(); + new_reqs.extend_from_slice(&*tmp); + debugln!( + "usage::get_required_usage_from: after iter desc_reqs={:?}", + desc_reqs + ); + } + } + desc_reqs.extend_from_slice(reqs); + desc_reqs.sort_unstable(); + desc_reqs.dedup(); + debugln!( + "usage::get_required_usage_from: final desc_reqs={:?}", + desc_reqs + ); + let mut ret_val = VecDeque::new(); + let args_in_groups = p + .groups + .iter() + .filter(|gn| desc_reqs.contains(&gn.name)) + .flat_map(|g| p.arg_names_in_group(g.name)) + .collect::>(); + + let pmap = if let Some(m) = matcher { + desc_reqs + .iter() + .filter(|a| p.positionals.values().any(|p| &&p.b.name == a)) + .filter(|&pos| !m.contains(pos)) + .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos)) + .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) + .filter(|pos| !args_in_groups.contains(&pos.b.name)) + .map(|pos| (pos.index, pos)) + .collect::>() // sort by index + } else { + desc_reqs + .iter() + .filter(|a| p.positionals.values().any(|pos| &&pos.b.name == a)) + .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos)) + .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) + .filter(|pos| !args_in_groups.contains(&pos.b.name)) + .map(|pos| (pos.index, pos)) + .collect::>() // sort by index + }; + debugln!( + "usage::get_required_usage_from: args_in_groups={:?}", + args_in_groups + ); + for &p in pmap.values() { + let s = p.to_string(); + if args_in_groups.is_empty() || !args_in_groups.contains(&&*s) { + ret_val.push_back(s); + } + } + for a in desc_reqs + .iter() + .filter(|name| !p.positionals.values().any(|p| &&p.b.name == name)) + .filter(|name| !p.groups.iter().any(|g| &&g.name == name)) + .filter(|name| !args_in_groups.contains(name)) + .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name))) + { + debugln!("usage::get_required_usage_from:iter:{}:", a); + let arg = find_by_name!(p, *a, flags, iter) + .map(|f| f.to_string()) + .unwrap_or_else(|| { + find_by_name!(p, *a, opts, iter) + .map(|o| o.to_string()) + .expect(INTERNAL_ERROR_MSG) + }); + ret_val.push_back(arg); + } + let mut g_vec: Vec = vec![]; + for g in desc_reqs + .iter() + .filter(|n| p.groups.iter().any(|g| &&g.name == n)) + { + let g_string = p.args_in_group(g).join("|"); + let elem = format!("<{}>", &g_string[..g_string.len()]); + if !g_vec.contains(&elem) { + g_vec.push(elem); + } + } + for g in g_vec { + ret_val.push_back(g); + } + + ret_val +} diff --git a/bash-5.1/vendor/clap/src/app/validator.rs b/bash-5.1/vendor/clap/src/app/validator.rs new file mode 100644 index 0000000..1deb67d --- /dev/null +++ b/bash-5.1/vendor/clap/src/app/validator.rs @@ -0,0 +1,584 @@ +// std +#[allow(deprecated, unused_imports)] +use std::{ascii::AsciiExt, fmt::Display}; + +// Internal +use crate::{ + app::{ + parser::{ParseResult, Parser}, + settings::AppSettings as AS, + usage, + }, + args::{settings::ArgSettings, AnyArg, ArgMatcher, MatchedArg}, + errors::{Error, ErrorKind, Result as ClapResult}, + fmt::{Colorizer, ColorizerOption}, + INTERNAL_ERROR_MSG, INVALID_UTF8, +}; + +pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>) +where + 'a: 'b, + 'b: 'z; + +impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { + pub fn new(p: &'z mut Parser<'a, 'b>) -> Self { + Validator(p) + } + + pub fn validate( + &mut self, + needs_val_of: ParseResult<'a>, + subcmd_name: Option, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult<()> { + debugln!("Validator::validate;"); + let mut reqs_validated = false; + self.0.add_env(matcher)?; + self.0.add_defaults(matcher)?; + if let ParseResult::Opt(a) = needs_val_of { + debugln!("Validator::validate: needs_val_of={:?}", a); + let o = { + self.0 + .opts + .iter() + .find(|o| o.b.name == a) + .expect(INTERNAL_ERROR_MSG) + .clone() + }; + self.validate_required(matcher)?; + reqs_validated = true; + let should_err = if let Some(v) = matcher.0.args.get(&*o.b.name) { + v.vals.is_empty() && !(o.v.min_vals.is_some() && o.v.min_vals.unwrap() == 0) + } else { + true + }; + if should_err { + return Err(Error::empty_value( + &o, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + + if matcher.is_empty() + && matcher.subcommand_name().is_none() + && self.0.is_set(AS::ArgRequiredElseHelp) + { + let mut out = vec![]; + self.0.write_help_err(&mut out)?; + return Err(Error { + message: String::from_utf8_lossy(&*out).into_owned(), + kind: ErrorKind::MissingArgumentOrSubcommand, + info: None, + }); + } + self.validate_blacklist(matcher)?; + if !(reqs_validated || self.0.is_set(AS::SubcommandsNegateReqs) && subcmd_name.is_some()) { + self.validate_required(matcher)?; + } + self.validate_matched_args(matcher)?; + matcher.usage(usage::create_usage_with_title(self.0, &[])); + + Ok(()) + } + + fn validate_arg_values( + &self, + arg: &A, + ma: &MatchedArg, + matcher: &ArgMatcher<'a>, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_values: arg={:?}", arg.name()); + for val in &ma.vals { + if self.0.is_set(AS::StrictUtf8) && val.to_str().is_none() { + debugln!( + "Validator::validate_arg_values: invalid UTF-8 found in val {:?}", + val + ); + return Err(Error::invalid_utf8( + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + if let Some(p_vals) = arg.possible_vals() { + debugln!("Validator::validate_arg_values: possible_vals={:?}", p_vals); + let val_str = val.to_string_lossy(); + let ok = if arg.is_set(ArgSettings::CaseInsensitive) { + p_vals.iter().any(|pv| pv.eq_ignore_ascii_case(&*val_str)) + } else { + p_vals.contains(&&*val_str) + }; + if !ok { + return Err(Error::invalid_value( + val_str, + p_vals, + arg, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + if !arg.is_set(ArgSettings::EmptyValues) + && val.is_empty() + && matcher.contains(&*arg.name()) + { + debugln!("Validator::validate_arg_values: illegal empty val found"); + return Err(Error::empty_value( + arg, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + if let Some(vtor) = arg.validator() { + debug!("Validator::validate_arg_values: checking validator..."); + if let Err(e) = vtor(val.to_string_lossy().into_owned()) { + sdebugln!("error"); + return Err(Error::value_validation(Some(arg), e, self.0.color())); + } else { + sdebugln!("good"); + } + } + if let Some(vtor) = arg.validator_os() { + debug!("Validator::validate_arg_values: checking validator_os..."); + if let Err(e) = vtor(val) { + sdebugln!("error"); + return Err(Error::value_validation( + Some(arg), + (*e).to_string_lossy().to_string(), + self.0.color(), + )); + } else { + sdebugln!("good"); + } + } + } + Ok(()) + } + + fn build_err(&self, name: &str, matcher: &ArgMatcher) -> ClapResult<()> { + debugln!("build_err!: name={}", name); + let mut c_with = find_from!(self.0, &name, blacklist, matcher); + c_with = c_with.or_else(|| { + self.0 + .find_any_arg(name) + .and_then(|aa| aa.blacklist()) + .and_then(|bl| bl.iter().find(|arg| matcher.contains(arg))) + .and_then(|an| self.0.find_any_arg(an)) + .map(|aa| format!("{}", aa)) + }); + debugln!("build_err!: '{:?}' conflicts with '{}'", c_with, &name); + // matcher.remove(&name); + let usg = usage::create_error_usage(self.0, matcher, None); + if let Some(f) = find_by_name!(self.0, name, flags, iter) { + debugln!("build_err!: It was a flag..."); + Err(Error::argument_conflict(f, c_with, &*usg, self.0.color())) + } else if let Some(o) = find_by_name!(self.0, name, opts, iter) { + debugln!("build_err!: It was an option..."); + Err(Error::argument_conflict(o, c_with, &*usg, self.0.color())) + } else { + match find_by_name!(self.0, name, positionals, values) { + Some(p) => { + debugln!("build_err!: It was a positional..."); + Err(Error::argument_conflict(p, c_with, &*usg, self.0.color())) + } + None => panic!("{}", INTERNAL_ERROR_MSG), + } + } + } + + fn validate_blacklist(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { + debugln!("Validator::validate_blacklist;"); + let mut conflicts: Vec<&str> = vec![]; + for (&name, _) in matcher.iter() { + debugln!("Validator::validate_blacklist:iter:{};", name); + if let Some(grps) = self.0.groups_for_arg(name) { + for grp in &grps { + if let Some(g) = self.0.groups.iter().find(|g| &g.name == grp) { + if !g.multiple { + for arg in &g.args { + if arg == &name { + continue; + } + conflicts.push(arg); + } + } + if let Some(ref gc) = g.conflicts { + conflicts.extend(&*gc); + } + } + } + } + if let Some(arg) = find_any_by_name!(self.0, name) { + if let Some(bl) = arg.blacklist() { + for conf in bl { + if matcher.get(conf).is_some() { + conflicts.push(conf); + } + } + } + } else { + debugln!("Validator::validate_blacklist:iter:{}:group;", name); + let args = self.0.arg_names_in_group(name); + for arg in &args { + debugln!( + "Validator::validate_blacklist:iter:{}:group:iter:{};", + name, + arg + ); + if let Some(bl) = find_any_by_name!(self.0, *arg).unwrap().blacklist() { + for conf in bl { + if matcher.get(conf).is_some() { + conflicts.push(conf); + } + } + } + } + } + } + + for name in &conflicts { + debugln!( + "Validator::validate_blacklist:iter:{}: Checking blacklisted arg", + name + ); + let mut should_err = false; + if self.0.groups.iter().any(|g| &g.name == name) { + debugln!( + "Validator::validate_blacklist:iter:{}: groups contains it...", + name + ); + for n in self.0.arg_names_in_group(name) { + debugln!( + "Validator::validate_blacklist:iter:{}:iter:{}: looking in group...", + name, + n + ); + if matcher.contains(n) { + debugln!( + "Validator::validate_blacklist:iter:{}:iter:{}: matcher contains it...", + name, + n + ); + return self.build_err(n, matcher); + } + } + } else if let Some(ma) = matcher.get(name) { + debugln!( + "Validator::validate_blacklist:iter:{}: matcher contains it...", + name + ); + should_err = ma.occurs > 0; + } + if should_err { + return self.build_err(*name, matcher); + } + } + Ok(()) + } + + fn validate_matched_args(&self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { + debugln!("Validator::validate_matched_args;"); + for (name, ma) in matcher.iter() { + debugln!( + "Validator::validate_matched_args:iter:{}: vals={:#?}", + name, + ma.vals + ); + if let Some(opt) = find_by_name!(self.0, *name, opts, iter) { + self.validate_arg_num_vals(opt, ma, matcher)?; + self.validate_arg_values(opt, ma, matcher)?; + self.validate_arg_requires(opt, ma, matcher)?; + self.validate_arg_num_occurs(opt, ma, matcher)?; + } else if let Some(flag) = find_by_name!(self.0, *name, flags, iter) { + self.validate_arg_requires(flag, ma, matcher)?; + self.validate_arg_num_occurs(flag, ma, matcher)?; + } else if let Some(pos) = find_by_name!(self.0, *name, positionals, values) { + self.validate_arg_num_vals(pos, ma, matcher)?; + self.validate_arg_num_occurs(pos, ma, matcher)?; + self.validate_arg_values(pos, ma, matcher)?; + self.validate_arg_requires(pos, ma, matcher)?; + } else { + let grp = self + .0 + .groups + .iter() + .find(|g| &g.name == name) + .expect(INTERNAL_ERROR_MSG); + if let Some(ref g_reqs) = grp.requires { + if g_reqs.iter().any(|&n| !matcher.contains(n)) { + return self.missing_required_error(matcher, None); + } + } + } + } + Ok(()) + } + + fn validate_arg_num_occurs( + &self, + a: &A, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_num_occurs: a={};", a.name()); + if ma.occurs > 1 && !a.is_set(ArgSettings::Multiple) { + // Not the first time, and we don't allow multiples + return Err(Error::unexpected_multiple_usage( + a, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + Ok(()) + } + + fn validate_arg_num_vals( + &self, + a: &A, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_num_vals:{}", a.name()); + if let Some(num) = a.num_vals() { + debugln!("Validator::validate_arg_num_vals: num_vals set...{}", num); + let should_err = if a.is_set(ArgSettings::Multiple) { + ((ma.vals.len() as u64) % num) != 0 + } else { + num != (ma.vals.len() as u64) + }; + if should_err { + debugln!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); + return Err(Error::wrong_number_of_values( + a, + num, + if a.is_set(ArgSettings::Multiple) { + ma.vals.len() % num as usize + } else { + ma.vals.len() + }, + if ma.vals.len() == 1 + || (a.is_set(ArgSettings::Multiple) && (ma.vals.len() % num as usize) == 1) + { + "as" + } else { + "ere" + }, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + if let Some(num) = a.max_vals() { + debugln!("Validator::validate_arg_num_vals: max_vals set...{}", num); + if (ma.vals.len() as u64) > num { + debugln!("Validator::validate_arg_num_vals: Sending error TooManyValues"); + return Err(Error::too_many_values( + ma.vals + .iter() + .last() + .expect(INTERNAL_ERROR_MSG) + .to_str() + .expect(INVALID_UTF8), + a, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + let min_vals_zero = if let Some(num) = a.min_vals() { + debugln!("Validator::validate_arg_num_vals: min_vals set: {}", num); + if (ma.vals.len() as u64) < num && num != 0 { + debugln!("Validator::validate_arg_num_vals: Sending error TooFewValues"); + return Err(Error::too_few_values( + a, + num, + ma.vals.len(), + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + num == 0 + } else { + false + }; + // Issue 665 (https://github.com/clap-rs/clap/issues/665) + // Issue 1105 (https://github.com/clap-rs/clap/issues/1105) + if a.takes_value() && !min_vals_zero && ma.vals.is_empty() { + return Err(Error::empty_value( + a, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + Ok(()) + } + + fn validate_arg_requires( + &self, + a: &A, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_requires:{};", a.name()); + if let Some(a_reqs) = a.requires() { + for &(val, name) in a_reqs.iter().filter(|&&(val, _)| val.is_some()) { + let missing_req = + |v| v == val.expect(INTERNAL_ERROR_MSG) && !matcher.contains(name); + if ma.vals.iter().any(missing_req) { + return self.missing_required_error(matcher, None); + } + } + for &(_, name) in a_reqs.iter().filter(|&&(val, _)| val.is_none()) { + if !matcher.contains(name) { + return self.missing_required_error(matcher, Some(name)); + } + } + } + Ok(()) + } + + fn validate_required(&mut self, matcher: &ArgMatcher) -> ClapResult<()> { + debugln!( + "Validator::validate_required: required={:?};", + self.0.required + ); + + let mut should_err = false; + let mut to_rem = Vec::new(); + for name in &self.0.required { + debugln!("Validator::validate_required:iter:{}:", name); + if matcher.contains(name) { + continue; + } + if to_rem.contains(name) { + continue; + } else if let Some(a) = find_any_by_name!(self.0, *name) { + if self.is_missing_required_ok(a, matcher) { + to_rem.push(a.name()); + if let Some(reqs) = a.requires() { + for r in reqs + .iter() + .filter(|&&(val, _)| val.is_none()) + .map(|&(_, name)| name) + { + to_rem.push(r); + } + } + continue; + } + } + should_err = true; + break; + } + if should_err { + for r in &to_rem { + 'inner: for i in (0..self.0.required.len()).rev() { + if &self.0.required[i] == r { + self.0.required.swap_remove(i); + break 'inner; + } + } + } + return self.missing_required_error(matcher, None); + } + + // Validate the conditionally required args + for &(a, v, r) in &self.0.r_ifs { + if let Some(ma) = matcher.get(a) { + if matcher.get(r).is_none() && ma.vals.iter().any(|val| val == v) { + return self.missing_required_error(matcher, Some(r)); + } + } + } + Ok(()) + } + + fn validate_arg_conflicts(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option { + debugln!("Validator::validate_arg_conflicts: a={:?};", a.name()); + a.blacklist().map(|bl| { + bl.iter().any(|conf| { + matcher.contains(conf) + || self + .0 + .groups + .iter() + .find(|g| &g.name == conf) + .map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg))) + }) + }) + } + + fn validate_required_unless(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option { + debugln!("Validator::validate_required_unless: a={:?};", a.name()); + macro_rules! check { + ($how:ident, $_self:expr, $a:ident, $m:ident) => {{ + $a.required_unless().map(|ru| { + ru.iter().$how(|n| { + $m.contains(n) || { + if let Some(grp) = $_self.groups.iter().find(|g| &g.name == n) { + grp.args.iter().any(|arg| $m.contains(arg)) + } else { + false + } + } + }) + }) + }}; + } + if a.is_set(ArgSettings::RequiredUnlessAll) { + check!(all, self.0, a, matcher) + } else { + check!(any, self.0, a, matcher) + } + } + + fn missing_required_error(&self, matcher: &ArgMatcher, extra: Option<&str>) -> ClapResult<()> { + debugln!("Validator::missing_required_error: extra={:?}", extra); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: self.0.color(), + }); + let mut reqs = self.0.required.iter().map(|&r| &*r).collect::>(); + if let Some(r) = extra { + reqs.push(r); + } + reqs.retain(|n| !matcher.contains(n)); + reqs.dedup(); + debugln!("Validator::missing_required_error: reqs={:#?}", reqs); + let req_args = + usage::get_required_usage_from(self.0, &reqs[..], Some(matcher), extra, true) + .iter() + .fold(String::new(), |acc, s| { + acc + &format!("\n {}", c.error(s))[..] + }); + debugln!( + "Validator::missing_required_error: req_args={:#?}", + req_args + ); + Err(Error::missing_required_argument( + &*req_args, + &*usage::create_error_usage(self.0, matcher, extra), + self.0.color(), + )) + } + + #[inline] + fn is_missing_required_ok(&self, a: &AnyArg, matcher: &ArgMatcher) -> bool { + debugln!("Validator::is_missing_required_ok: a={}", a.name()); + self.validate_arg_conflicts(a, matcher).unwrap_or(false) + || self.validate_required_unless(a, matcher).unwrap_or(false) + } +} diff --git a/bash-5.1/vendor/clap/src/args/any_arg.rs b/bash-5.1/vendor/clap/src/args/any_arg.rs new file mode 100644 index 0000000..b1c3a6a --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/any_arg.rs @@ -0,0 +1,139 @@ +// Std +use std::{ + ffi::{OsStr, OsString}, + fmt as std_fmt, + rc::Rc, +}; + +// Internal +use crate::{ + args::settings::ArgSettings, + map::{self, VecMap}, + INTERNAL_ERROR_MSG, +}; + +#[doc(hidden)] +pub trait AnyArg<'n, 'e>: std_fmt::Display { + fn name(&self) -> &'n str; + fn overrides(&self) -> Option<&[&'e str]>; + fn aliases(&self) -> Option>; + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]>; + fn blacklist(&self) -> Option<&[&'e str]>; + fn required_unless(&self) -> Option<&[&'e str]>; + fn is_set(&self, setting: ArgSettings) -> bool; + fn set(&mut self, setting: ArgSettings); + fn has_switch(&self) -> bool; + fn max_vals(&self) -> Option; + fn min_vals(&self) -> Option; + fn num_vals(&self) -> Option; + fn possible_vals(&self) -> Option<&[&'e str]>; + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator(&self) -> Option<&Rc Result<(), String>>>; + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator_os(&self) -> Option<&Rc Result<(), OsString>>>; + fn short(&self) -> Option; + fn long(&self) -> Option<&'e str>; + fn val_delim(&self) -> Option; + fn takes_value(&self) -> bool; + fn val_names(&self) -> Option<&VecMap<&'e str>>; + fn help(&self) -> Option<&'e str>; + fn long_help(&self) -> Option<&'e str>; + fn default_val(&self) -> Option<&'e OsStr>; + fn default_vals_ifs(&self) -> Option, &'e OsStr)>>; + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)>; + fn longest_filter(&self) -> bool; + fn val_terminator(&self) -> Option<&'e str>; +} + +pub trait DispOrder { + fn disp_ord(&self) -> usize; +} + +impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T +where + T: AnyArg<'n, 'e> + 'z, +{ + fn name(&self) -> &'n str { + (*self).name() + } + fn overrides(&self) -> Option<&[&'e str]> { + (*self).overrides() + } + fn aliases(&self) -> Option> { + (*self).aliases() + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + (*self).requires() + } + fn blacklist(&self) -> Option<&[&'e str]> { + (*self).blacklist() + } + fn required_unless(&self) -> Option<&[&'e str]> { + (*self).required_unless() + } + fn is_set(&self, a: ArgSettings) -> bool { + (*self).is_set(a) + } + fn set(&mut self, _: ArgSettings) { + panic!("{}", INTERNAL_ERROR_MSG) + } + fn has_switch(&self) -> bool { + (*self).has_switch() + } + fn max_vals(&self) -> Option { + (*self).max_vals() + } + fn min_vals(&self) -> Option { + (*self).min_vals() + } + fn num_vals(&self) -> Option { + (*self).num_vals() + } + fn possible_vals(&self) -> Option<&[&'e str]> { + (*self).possible_vals() + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator(&self) -> Option<&Rc Result<(), String>>> { + (*self).validator() + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator_os(&self) -> Option<&Rc Result<(), OsString>>> { + (*self).validator_os() + } + fn short(&self) -> Option { + (*self).short() + } + fn long(&self) -> Option<&'e str> { + (*self).long() + } + fn val_delim(&self) -> Option { + (*self).val_delim() + } + fn takes_value(&self) -> bool { + (*self).takes_value() + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + (*self).val_names() + } + fn help(&self) -> Option<&'e str> { + (*self).help() + } + fn long_help(&self) -> Option<&'e str> { + (*self).long_help() + } + fn default_val(&self) -> Option<&'e OsStr> { + (*self).default_val() + } + fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { + (*self).default_vals_ifs() + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + (*self).env() + } + fn longest_filter(&self) -> bool { + (*self).longest_filter() + } + fn val_terminator(&self) -> Option<&'e str> { + (*self).val_terminator() + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg.rs b/bash-5.1/vendor/clap/src/args/arg.rs new file mode 100644 index 0000000..27db8ee --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg.rs @@ -0,0 +1,3961 @@ +#[cfg(feature = "yaml")] +use std::collections::BTreeMap; +#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] +use std::os::unix::ffi::OsStrExt; +use std::{ + env, + ffi::{OsStr, OsString}, + rc::Rc, +}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +use crate::osstringext::OsStrExt3; +use crate::{ + args::{ + arg_builder::{Base, Switched, Valued}, + settings::ArgSettings, + }, + map::VecMap, + usage_parser::UsageParser, +}; + +/// The abstract representation of a command line argument. Used to set all the options and +/// relationships that define a valid argument for the program. +/// +/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options +/// manually, or using a usage string which is far less verbose but has fewer options. You can also +/// use a combination of the two methods to achieve the best of both worlds. +/// +/// # Examples +/// +/// ```rust +/// # use clap::Arg; +/// // Using the traditional builder pattern and setting each option manually +/// let cfg = Arg::with_name("config") +/// .short("c") +/// .long("config") +/// .takes_value(true) +/// .value_name("FILE") +/// .help("Provides a config file to myprog"); +/// // Using a usage string (setting a similar argument to the one above) +/// let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'"); +/// ``` +/// [`Arg`]: ./struct.Arg.html +#[allow(missing_debug_implementations)] +#[derive(Default, Clone)] +pub struct Arg<'a, 'b> +where + 'a: 'b, +{ + #[doc(hidden)] + pub b: Base<'a, 'b>, + #[doc(hidden)] + pub s: Switched<'b>, + #[doc(hidden)] + pub v: Valued<'a, 'b>, + #[doc(hidden)] + pub index: Option, + #[doc(hidden)] + pub r_ifs: Option>, +} + +impl<'a, 'b> Arg<'a, 'b> { + /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get + /// information about whether or not the argument was used at runtime, get values, set + /// relationships with other args, etc.. + /// + /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`]) + /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also + /// be displayed when the user prints the usage/help information of the program. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// # ; + /// ``` + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + /// [`Arg`]: ./struct.Arg.html + pub fn with_name(n: &'a str) -> Self { + Arg { + b: Base::new(n), + ..Default::default() + } + } + + /// Creates a new instance of [`Arg`] from a .yml (YAML) file. + /// + /// # Examples + /// + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::Arg; + /// # fn main() { + /// let yml = load_yaml!("arg.yml"); + /// let arg = Arg::from_yaml(yml); + /// # } + /// ``` + /// [`Arg`]: ./struct.Arg.html + #[cfg(feature = "yaml")] + pub fn from_yaml(y: &BTreeMap) -> Arg { + // We WANT this to panic on error...so expect() is good. + let name_yml = y.keys().nth(0).unwrap(); + let name_str = name_yml.as_str().unwrap(); + let mut a = Arg::with_name(name_str); + let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap(); + + for (k, v) in arg_settings.iter() { + a = match k.as_str().unwrap() { + "short" => yaml_to_str!(a, v, short), + "long" => yaml_to_str!(a, v, long), + "aliases" => yaml_vec_or_str!(v, a, alias), + "help" => yaml_to_str!(a, v, help), + "long_help" => yaml_to_str!(a, v, long_help), + "required" => yaml_to_bool!(a, v, required), + "required_if" => yaml_tuple2!(a, v, required_if), + "required_ifs" => yaml_tuple2!(a, v, required_if), + "takes_value" => yaml_to_bool!(a, v, takes_value), + "index" => yaml_to_u64!(a, v, index), + "global" => yaml_to_bool!(a, v, global), + "multiple" => yaml_to_bool!(a, v, multiple), + "hidden" => yaml_to_bool!(a, v, hidden), + "next_line_help" => yaml_to_bool!(a, v, next_line_help), + "empty_values" => yaml_to_bool!(a, v, empty_values), + "group" => yaml_to_str!(a, v, group), + "number_of_values" => yaml_to_u64!(a, v, number_of_values), + "max_values" => yaml_to_u64!(a, v, max_values), + "min_values" => yaml_to_u64!(a, v, min_values), + "value_name" => yaml_to_str!(a, v, value_name), + "use_delimiter" => yaml_to_bool!(a, v, use_delimiter), + "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values), + "last" => yaml_to_bool!(a, v, last), + "require_delimiter" => yaml_to_bool!(a, v, require_delimiter), + "value_delimiter" => yaml_to_str!(a, v, value_delimiter), + "required_unless" => yaml_to_str!(a, v, required_unless), + "display_order" => yaml_to_usize!(a, v, display_order), + "default_value" => yaml_to_str!(a, v, default_value), + "default_value_if" => yaml_tuple3!(a, v, default_value_if), + "default_value_ifs" => yaml_tuple3!(a, v, default_value_if), + "env" => yaml_to_str!(a, v, env), + "value_names" => yaml_vec_or_str!(v, a, value_name), + "groups" => yaml_vec_or_str!(v, a, group), + "requires" => yaml_vec_or_str!(v, a, requires), + "requires_if" => yaml_tuple2!(a, v, requires_if), + "requires_ifs" => yaml_tuple2!(a, v, requires_if), + "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), + "overrides_with" => yaml_vec_or_str!(v, a, overrides_with), + "possible_values" => yaml_vec_or_str!(v, a, possible_value), + "case_insensitive" => yaml_to_bool!(a, v, case_insensitive), + "required_unless_one" => yaml_vec_or_str!(v, a, required_unless), + "required_unless_all" => { + a = yaml_vec_or_str!(v, a, required_unless); + a.setb(ArgSettings::RequiredUnlessAll); + a + } + s => panic!( + "Unknown Arg setting '{}' in YAML file for arg '{}'", + s, name_str + ), + } + } + + a + } + + /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings + /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow. + /// + /// **NOTE**: Not all settings may be set using the usage string method. Some properties are + /// only available via the builder pattern. + /// + /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some + /// UTF-8 codepoints may work just fine, but this is not guaranteed. + /// + /// # Syntax + /// + /// Usage strings typically following the form: + /// + /// ```notrust + /// [explicit name] [short] [long] [value names] [help string] + /// ``` + /// + /// This is not a hard rule as the attributes can appear in other orders. There are also + /// several additional sigils which denote additional settings. Below are the details of each + /// portion of the string. + /// + /// ### Explicit Name + /// + /// This is an optional field, if it's omitted the argument will use one of the additional + /// fields as the name using the following priority order: + /// + /// * Explicit Name (This always takes precedence when present) + /// * Long + /// * Short + /// * Value Name + /// + /// `clap` determines explicit names as the first string of characters between either `[]` or + /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning + /// the argument is required. + /// + /// Explicit names may be followed by: + /// * The multiple denotation `...` + /// + /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a + /// required argument): + /// + /// ```notrust + /// [ename] -s, --long 'some flag' + /// -r, --longer 'some other flag' + /// ``` + /// + /// ### Short + /// + /// This is set by placing a single character after a leading `-`. + /// + /// Shorts may be followed by + /// * The multiple denotation `...` + /// * An optional comma `,` which is cosmetic only + /// * Value notation + /// + /// Example shorts are as follows (`-s`, and `-r`): + /// + /// ```notrust + /// -s, --long 'some flag' + /// -r [val], --longer 'some option' + /// ``` + /// + /// ### Long + /// + /// This is set by placing a word (no spaces) after a leading `--`. + /// + /// Shorts may be followed by + /// * The multiple denotation `...` + /// * Value notation + /// + /// Example longs are as follows (`--some`, and `--rapid`): + /// + /// ```notrust + /// -s, --some 'some flag' + /// --rapid=[FILE] 'some option' + /// ``` + /// + /// ### Values (Value Notation) + /// + /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this + /// is cosmetic only and does not affect functionality). If an explicit name has **not** been + /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument + /// + /// Values may be followed by + /// * The multiple denotation `...` + /// * More Value notation + /// + /// More than one value will also implicitly set the arguments number of values, i.e. having + /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it + /// must receive exactly two values + /// + /// Example values are as follows (`FILE`, and `SPEED`): + /// + /// ```notrust + /// -s, --some [FILE] 'some option' + /// --rapid=... 'some required multiple option' + /// ``` + /// + /// ### Help String + /// + /// The help string is denoted between a pair of single quotes `''` and may contain any + /// characters. + /// + /// Example help strings are as follows: + /// + /// ```notrust + /// -s, --some [FILE] 'some option' + /// --rapid=... 'some required multiple option' + /// ``` + /// + /// ### Additional Sigils + /// + /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may + /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values. + /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is + /// multiple occurrences (and then you can obviously have instances of both as well) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// App::new("prog") + /// .args(&[ + /// Arg::from_usage("--config 'a required file for the configuration and no short'"), + /// Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"), + /// Arg::from_usage("[input] 'an optional input file to use'") + /// ]) + /// # ; + /// ``` + /// [`Arg`]: ./struct.Arg.html + /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage + pub fn from_usage(u: &'a str) -> Self { + let parser = UsageParser::from_usage(u); + parser.parse() + } + + /// Sets the short version of the argument without the preceding `-`. + /// + /// By default `clap` automatically assigns `V` and `h` to the auto-generated `version` and + /// `help` arguments respectively. You may use the uppercase `V` or lowercase `h` for your own + /// arguments, in which case `clap` simply will not assign those to the auto-generated + /// `version` or `help` arguments. + /// + /// **NOTE:** Any leading `-` characters will be stripped, and only the first + /// non `-` character will be used as the [`short`] version + /// + /// # Examples + /// + /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as + /// `-c`, the `-` will be stripped. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .short("c") + /// # ; + /// ``` + /// + /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("config") + /// .short("c")) + /// .get_matches_from(vec![ + /// "prog", "-c" + /// ]); + /// + /// assert!(m.is_present("config")); + /// ``` + /// [`short`]: ./struct.Arg.html#method.short + pub fn short>(mut self, s: S) -> Self { + self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().next(); + self + } + + /// Sets the long version of the argument without the preceding `--`. + /// + /// By default `clap` automatically assigns `version` and `help` to the auto-generated + /// `version` and `help` arguments respectively. You may use the word `version` or `help` for + /// the long form of your own arguments, in which case `clap` simply will not assign those to + /// the auto-generated `version` or `help` arguments. + /// + /// **NOTE:** Any leading `-` characters will be stripped + /// + /// # Examples + /// + /// To set `long` use a word containing valid UTF-8 codepoints. If you supply a double leading + /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, + /// will *not* be stripped (i.e. `config-file` is allowed) + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("cfg") + /// .long("config") + /// # ; + /// ``` + /// + /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config")) + /// .get_matches_from(vec![ + /// "prog", "--config" + /// ]); + /// + /// assert!(m.is_present("cfg")); + /// ``` + pub fn long(mut self, l: &'b str) -> Self { + self.s.long = Some(l.trim_left_matches(|c| c == '-')); + self + } + + /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that + /// automatically dispatch as if this argument was used. This is more efficient, and easier + /// than creating multiple hidden arguments as one only needs to check for the existence of + /// this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("test") + /// .long("test") + /// .alias("alias") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--alias", "cool" + /// ]); + /// assert!(m.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("cool")); + /// ``` + /// [`Arg`]: ./struct.Arg.html + pub fn alias>(mut self, name: S) -> Self { + if let Some(ref mut als) = self.s.aliases { + als.push((name.into(), false)); + } else { + self.s.aliases = Some(vec![(name.into(), false)]); + } + self + } + + /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that + /// automatically dispatch as if this argument was used. This is more efficient, and easier + /// than creating multiple hidden subcommands as one only needs to check for the existence of + /// this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("test") + /// .long("test") + /// .aliases(&["do-stuff", "do-tests", "tests"]) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "--do-tests" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + /// [`Arg`]: ./struct.Arg.html + pub fn aliases(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut als) = self.s.aliases { + for n in names { + als.push((n, false)); + } + } else { + self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::>()); + } + self + } + + /// Allows adding a [`Arg`] alias that functions exactly like those defined with + /// [`Arg::alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("test") + /// .visible_alias("something-awesome") + /// .long("test") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--something-awesome", "coffee" + /// ]); + /// assert!(m.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("coffee")); + /// ``` + /// [`Arg`]: ./struct.Arg.html + /// [`App::alias`]: ./struct.Arg.html#method.alias + pub fn visible_alias>(mut self, name: S) -> Self { + if let Some(ref mut als) = self.s.aliases { + als.push((name.into(), true)); + } else { + self.s.aliases = Some(vec![(name.into(), true)]); + } + self + } + + /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined + /// with [`Arg::aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("test") + /// .long("test") + /// .visible_aliases(&["something", "awesome", "cool"])) + /// .get_matches_from(vec![ + /// "prog", "--awesome" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + /// [`Arg`]: ./struct.Arg.html + /// [`App::aliases`]: ./struct.Arg.html#method.aliases + pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut als) = self.s.aliases { + for n in names { + als.push((n, true)); + } + } else { + self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::>()); + } + self + } + + /// Sets the short help text of the argument that will be displayed to the user when they print + /// the help information with `-h`. Typically, this is a short (one line) description of the + /// arg. + /// + /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests + /// `--help` clap will still display the contents of `help` appropriately + /// + /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .help("The config file used by the myprog") + /// # ; + /// ``` + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// --config Some help text describing the --config arg + /// -h, --help Prints help information + /// -V, --version Prints version information + /// ``` + /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help + pub fn help(mut self, h: &'b str) -> Self { + self.b.help = Some(h); + self + } + + /// Sets the long help text of the argument that will be displayed to the user when they print + /// the help information with `--help`. Typically this a more detailed (multi-line) message + /// that describes the arg. + /// + /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h` + /// clap will still display the contents of `long_help` appropriately + /// + /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .long_help( + /// "The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now.") + /// # ; + /// ``` + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .long_help( + /// "The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now.")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// --config + /// The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now. + /// + /// -h, --help + /// Prints help information + /// + /// -V, --version + /// Prints version information + /// ``` + /// [`Arg::help`]: ./struct.Arg.html#method.help + pub fn long_help(mut self, h: &'b str) -> Self { + self.b.long_help = Some(h); + self + } + + /// Specifies that this arg is the last, or final, positional argument (i.e. has the highest + /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- + /// last_arg`). Even, if no other arguments are left to parse, if the user omits the `--` syntax + /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also + /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with + /// the `--` syntax is otherwise not possible. + /// + /// **NOTE:** This will change the usage string to look like `$ prog [FLAGS] [-- ]` if + /// `ARG` is marked as `.last(true)`. + /// + /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing + /// to set this can make the usage string very confusing. + /// + /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS / + /// OPTIONS + /// + /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not + /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`] + /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also + /// marked [`.required(true)`]) + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("args") + /// .last(true) + /// # ; + /// ``` + /// + /// Setting [`Arg::last(true)`] ensures the arg has the highest [index] of all positional args + /// and requires that the `--` syntax be used to access it early. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("first")) + /// .arg(Arg::with_name("second")) + /// .arg(Arg::with_name("third").last(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "one", "--", "three" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("third"), Some("three")); + /// assert!(m.value_of("second").is_none()); + /// ``` + /// + /// Even if the positional argument marked `.last(true)` is the only argument left to parse, + /// failing to use the `--` syntax results in an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("first")) + /// .arg(Arg::with_name("second")) + /// .arg(Arg::with_name("third").last(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "one", "two", "three" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::last(true)`]: ./struct.Arg.html#method.last + /// [index]: ./struct.Arg.html#method.index + /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage + /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands + /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs + /// [`.required(true)`]: ./struct.Arg.html#method.required + /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument + pub fn last(self, l: bool) -> Self { + if l { + self.set(ArgSettings::Last) + } else { + self.unset(ArgSettings::Last) + } + } + + /// Sets whether or not the argument is required by default. Required by default means it is + /// required, when no other conflicting rules have been evaluated. Conflicting rules take + /// precedence over being required. **Default:** `false` + /// + /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by + /// default. This is simply because if a flag should be required, it should simply be implied + /// as no additional information is required from user. Flags by their very nature are simply + /// yes/no, or true/false. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .required(true) + /// # ; + /// ``` + /// + /// Setting [`Arg::required(true)`] requires that the argument be used at runtime. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required(true) + /// .takes_value(true) + /// .long("config")) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required(true) + /// .takes_value(true) + /// .long("config")) + /// .get_matches_from_safe(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::required(true)`]: ./struct.Arg.html#method.required + pub fn required(self, r: bool) -> Self { + if r { + self.set(ArgSettings::Required) + } else { + self.unset(ArgSettings::Required) + } + } + + /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and + /// associated value) **Default:** `false` + /// + /// **NOTE:** This setting also removes the default of allowing empty values and implies + /// [`Arg::empty_values(false)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .long("config") + /// .takes_value(true) + /// .require_equals(true) + /// # ; + /// ``` + /// + /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between + /// it and the associated value. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .require_equals(true) + /// .takes_value(true) + /// .long("config")) + /// .get_matches_from_safe(vec![ + /// "prog", "--config=file.conf" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error + /// unless [`Arg::empty_values(true)`] is set. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .require_equals(true) + /// .takes_value(true) + /// .long("config")) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); + /// ``` + /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals + /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values + /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values + pub fn require_equals(mut self, r: bool) -> Self { + if r { + self.unsetb(ArgSettings::EmptyValues); + self.set(ArgSettings::RequireEquals) + } else { + self.unset(ArgSettings::RequireEquals) + } + } + + /// Allows values which start with a leading hyphen (`-`) + /// + /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], as + /// this becomes ambiguous `$ prog --arg -- -- val`. All three `--, --, val` will be values + /// when the user may have thought the second `--` would constitute the normal, "Only + /// positional args follow" idiom. To fix this, consider using [`Arg::number_of_values(1)`] + /// + /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and + /// the user passing in a value that matches a valid short. For example `prog -opt -F` where + /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. Care should + /// should be taken when designing these args. This is compounded by the ability to "stack" + /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid + /// shorts. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("pattern") + /// .allow_hyphen_values(true) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("pat") + /// .allow_hyphen_values(true) + /// .takes_value(true) + /// .long("pattern")) + /// .get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert_eq!(m.value_of("pat"), Some("-file")); + /// ``` + /// + /// Not setting [`Arg::allow_hyphen_values(true)`] and supplying a value which starts with a + /// hyphen is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("pat") + /// .takes_value(true) + /// .long("pattern")) + /// .get_matches_from_safe(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values + pub fn allow_hyphen_values(self, a: bool) -> Self { + if a { + self.set(ArgSettings::AllowLeadingHyphen) + } else { + self.unset(ArgSettings::AllowLeadingHyphen) + } + } + /// Sets an arg that override this arg's required setting. (i.e. this arg will be required + /// unless this other argument is present). + /// + /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not + /// mandatory to also set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .required_unless("debug") + /// # ; + /// ``` + /// + /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime + /// *unless* `name` is present. In the following example, the required argument is *not* + /// provided, but it's not an error because the `unless` arg has been supplied. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_unless("dbg") + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("dbg") + /// .long("debug")) + /// .get_matches_from_safe(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_unless("dbg") + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("dbg") + /// .long("debug")) + /// .get_matches_from_safe(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless + /// [`Arg::required`]: ./struct.Arg.html#method.required + /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless + pub fn required_unless(mut self, name: &'a str) -> Self { + if let Some(ref mut vec) = self.b.r_unless { + vec.push(name); + } else { + self.b.r_unless = Some(vec![name]); + } + self.required(true) + } + + /// Sets args that override this arg's required setting. (i.e. this arg will be required unless + /// all these other arguments are present). + /// + /// **NOTE:** If you wish for this argument to only be required if *one of* these args are + /// present see [`Arg::required_unless_one`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .required_unless_all(&["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime + /// *unless* *all* the args in `names` are present. In the following example, the required + /// argument is *not* provided, but it's not an error because all the `unless` args have been + /// supplied. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_unless_all(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("dbg") + /// .long("debug")) + /// .arg(Arg::with_name("infile") + /// .short("i") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "--debug", "-i", "file" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this + /// arg is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_unless_all(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("dbg") + /// .long("debug")) + /// .arg(Arg::with_name("infile") + /// .short("i") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one + /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all + pub fn required_unless_all(mut self, names: &[&'a str]) -> Self { + if let Some(ref mut vec) = self.b.r_unless { + for s in names { + vec.push(s); + } + } else { + self.b.r_unless = Some(names.iter().copied().collect()); + } + self.setb(ArgSettings::RequiredUnlessAll); + self.required(true) + } + + /// Sets args that override this arg's [required] setting. (i.e. this arg will be required + /// unless *at least one of* these other arguments are present). + /// + /// **NOTE:** If you wish for this argument to only be required if *all of* these args are + /// present see [`Arg::required_unless_all`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .required_unless_all(&["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// Setting [`Arg::required_unless_one(names)`] requires that the argument be used at runtime + /// *unless* *at least one of* the args in `names` are present. In the following example, the + /// required argument is *not* provided, but it's not an error because one the `unless` args + /// have been supplied. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_unless_one(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("dbg") + /// .long("debug")) + /// .arg(Arg::with_name("infile") + /// .short("i") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names` + /// or this arg is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_unless_one(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("dbg") + /// .long("debug")) + /// .arg(Arg::with_name("infile") + /// .short("i") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: ./struct.Arg.html#method.required + /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one + /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all + pub fn required_unless_one(mut self, names: &[&'a str]) -> Self { + if let Some(ref mut vec) = self.b.r_unless { + for s in names { + vec.push(s); + } + } else { + self.b.r_unless = Some(names.iter().copied().collect()); + } + self.required(true) + } + + /// Sets a conflicting argument by name. I.e. when using this argument, + /// the following argument can't be present and vice versa. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need + /// need to also do B.conflicts_with(A)) + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .conflicts_with("debug") + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having both arguments present at runtime is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .conflicts_with("debug") + /// .long("config")) + /// .arg(Arg::with_name("debug") + /// .long("debug")) + /// .get_matches_from_safe(vec![ + /// "prog", "--debug", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); + /// ``` + pub fn conflicts_with(mut self, name: &'a str) -> Self { + if let Some(ref mut vec) = self.b.blacklist { + vec.push(name); + } else { + self.b.blacklist = Some(vec![name]); + } + self + } + + /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per + /// argument. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need + /// need to also do B.conflicts_with(A)) + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .conflicts_with_all(&["debug", "input"]) + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having any of the arguments present at runtime with a + /// conflicting argument is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .conflicts_with_all(&["debug", "input"]) + /// .long("config")) + /// .arg(Arg::with_name("debug") + /// .long("debug")) + /// .arg(Arg::with_name("input") + /// .index(1)) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); + /// ``` + /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with + pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self { + if let Some(ref mut vec) = self.b.blacklist { + for s in names { + vec.push(s); + } + } else { + self.b.blacklist = Some(names.iter().copied().collect()); + } + self + } + + /// Sets a overridable argument by name. I.e. this argument and the following argument + /// will override each other in POSIX style (whichever argument was specified at runtime + /// **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **WARNING:** Positional arguments cannot override themselves (or we would never be able + /// to advance to the next positional). If a positional agument lists itself as an override, + /// it is simply ignored. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::from_usage("-f, --flag 'some flag'") + /// .conflicts_with("debug")) + /// .arg(Arg::from_usage("-d, --debug 'other flag'")) + /// .arg(Arg::from_usage("-c, --color 'third flag'") + /// .overrides_with("flag")) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color + /// + /// assert!(m.is_present("color")); + /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag + /// // was never used because it was overridden with color + /// assert!(!m.is_present("flag")); + /// ``` + /// Care must be taken when using this setting, and having an arg override with itself. This + /// is common practice when supporting things like shell aliases, config files, etc. + /// However, when combined with multiple values, it can get dicy. + /// Here is how clap handles such situations: + /// + /// When a flag overrides itself, it's as if the flag was only ever used once (essentially + /// preventing a "Unexpected multiple usage" error): + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("posix") + /// .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) + /// .get_matches_from(vec!["posix", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// assert_eq!(m.occurrences_of("flag"), 1); + /// ``` + /// Making a arg `multiple(true)` and override itself is essentially meaningless. Therefore + /// clap ignores an override of self if it's a flag and it already accepts multiple occurrences. + /// + /// ``` + /// # use clap::{App, Arg}; + /// let m = App::new("posix") + /// .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) + /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// assert_eq!(m.occurrences_of("flag"), 4); + /// ``` + /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last + /// occurrence happened. + /// + /// ``` + /// # use clap::{App, Arg}; + /// let m = App::new("posix") + /// .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) + /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// assert_eq!(m.value_of("opt"), Some("other")); + /// ``` + /// + /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting. + /// + /// ``` + /// # use clap::{App, Arg}; + /// let m = App::new("posix") + /// .arg(Arg::from_usage("--opt [val]... 'some option'") + /// .overrides_with("opt")) + /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 2); + /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["first", "over", "other", "val"]); + /// ``` + /// + /// A safe thing to do if you'd like to support an option which supports multiple values, but + /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use + /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`) + /// + /// ``` + /// # use clap::{App, Arg}; + /// let m = App::new("posix") + /// .arg(Arg::from_usage("--opt [val] 'some option'") + /// .overrides_with("opt") + /// .use_delimiter(false)) + /// .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["one,two"]); + /// ``` + pub fn overrides_with(mut self, name: &'a str) -> Self { + if let Some(ref mut vec) = self.b.overrides { + vec.push(name); + } else { + self.b.overrides = Some(vec![name]); + } + self + } + + /// Sets multiple mutually overridable arguments by name. I.e. this argument and the following + /// argument will override each other in POSIX style (whichever argument was specified at + /// runtime **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::from_usage("-f, --flag 'some flag'") + /// .conflicts_with("color")) + /// .arg(Arg::from_usage("-d, --debug 'other flag'")) + /// .arg(Arg::from_usage("-c, --color 'third flag'") + /// .overrides_with_all(&["flag", "debug"])) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color + /// + /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag + /// // and debug were never used because they were overridden + /// // with color + /// assert!(!m.is_present("debug")); + /// assert!(!m.is_present("flag")); + /// ``` + pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self { + if let Some(ref mut vec) = self.b.overrides { + for s in names { + vec.push(s); + } + } else { + self.b.overrides = Some(names.iter().copied().collect()); + } + self + } + + /// Sets an argument by name that is required when this one is present I.e. when + /// using this argument, the following argument *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .requires("input") + /// # ; + /// ``` + /// + /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the + /// defining argument is used. If the defining argument isn't used, the other argument isn't + /// required + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::with_name("input") + /// .index(1)) + /// .get_matches_from_safe(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required + /// ``` + /// + /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::with_name("input") + /// .index(1)) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires + /// [Conflicting]: ./struct.Arg.html#method.conflicts_with + /// [override]: ./struct.Arg.html#method.overrides_with + pub fn requires(mut self, name: &'a str) -> Self { + if let Some(ref mut vec) = self.b.requires { + vec.push((None, name)); + } else { + self.b.requires = Some(vec![(None, name)]); + } + self + } + + /// Allows a conditional requirement. The requirement will only become valid if this arg's value + /// equals `val`. + /// + /// **NOTE:** If using YAML the values should be laid out as follows + /// + /// ```yaml + /// requires_if: + /// - [val, arg] + /// ``` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .requires_if("val", "arg") + /// # ; + /// ``` + /// + /// Setting [`Arg::requires_if(val, arg)`] requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument is anything other than + /// `val`, the other argument isn't required. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires_if("my.cfg", "other") + /// .long("config")) + /// .arg(Arg::with_name("other")) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "some.cfg" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required + /// ``` + /// + /// Setting [`Arg::requires_if(val, arg)`] and setting the value to `val` but *not* supplying + /// `arg` is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires_if("my.cfg", "input") + /// .long("config")) + /// .arg(Arg::with_name("input")) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "my.cfg" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires + /// [Conflicting]: ./struct.Arg.html#method.conflicts_with + /// [override]: ./struct.Arg.html#method.overrides_with + pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self { + if let Some(ref mut vec) = self.b.requires { + vec.push((Some(val), arg)); + } else { + self.b.requires = Some(vec![(Some(val), arg)]); + } + self + } + + /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value + /// equals `val`. + /// + /// **NOTE:** If using YAML the values should be laid out as follows + /// + /// ```yaml + /// requires_if: + /// - [val, arg] + /// - [val2, arg2] + /// ``` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .requires_ifs(&[ + /// ("val", "arg"), + /// ("other_val", "arg2"), + /// ]) + /// # ; + /// ``` + /// + /// Setting [`Arg::requires_ifs(&["val", "arg"])`] requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument's value is anything other + /// than `val`, `arg` isn't required. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires_ifs(&[ + /// ("special.conf", "opt"), + /// ("other.conf", "other"), + /// ]) + /// .long("config")) + /// .arg(Arg::with_name("opt") + /// .long("option") + /// .takes_value(true)) + /// .arg(Arg::with_name("other")) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "special.conf" + /// ]); + /// + /// assert!(res.is_err()); // We used --config=special.conf so --option is required + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires + /// [Conflicting]: ./struct.Arg.html#method.conflicts_with + /// [override]: ./struct.Arg.html#method.overrides_with + pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self { + if let Some(ref mut vec) = self.b.requires { + for &(val, arg) in ifs { + vec.push((Some(val), arg)); + } + } else { + let mut vec = vec![]; + for &(val, arg) in ifs { + vec.push((Some(val), arg)); + } + self.b.requires = Some(vec); + } + self + } + + /// Allows specifying that an argument is [required] conditionally. The requirement will only + /// become valid if the specified `arg`'s value equals `val`. + /// + /// **NOTE:** If using YAML the values should be laid out as follows + /// + /// ```yaml + /// required_if: + /// - [arg, val] + /// ``` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .required_if("other_arg", "value") + /// # ; + /// ``` + /// + /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at + /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`, + /// this argument isn't required. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .required_if("other", "special") + /// .long("config")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "--other", "not-special" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required + /// ``` + /// + /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not* + /// using this arg is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .required_if("other", "special") + /// .long("config")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "--other", "special" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires + /// [Conflicting]: ./struct.Arg.html#method.conflicts_with + /// [required]: ./struct.Arg.html#method.required + pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self { + if let Some(ref mut vec) = self.r_ifs { + vec.push((arg, val)); + } else { + self.r_ifs = Some(vec![(arg, val)]); + } + self + } + + /// Allows specifying that an argument is [required] based on multiple conditions. The + /// conditions are set up in a `(arg, val)` style tuple. The requirement will only become valid + /// if one of the specified `arg`'s value equals it's corresponding `val`. + /// + /// **NOTE:** If using YAML the values should be laid out as follows + /// + /// ```yaml + /// required_if: + /// - [arg, val] + /// - [arg2, val2] + /// ``` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .required_ifs(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting [`Arg::required_ifs(&[(arg, val)])`] makes this arg required if any of the `arg`s + /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_ifs(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::with_name("option") + /// .takes_value(true) + /// .long("option")) + /// .get_matches_from_safe(vec![ + /// "prog", "--option", "other" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting [`Arg::required_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .required_ifs(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::with_name("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::with_name("option") + /// .takes_value(true) + /// .long("option")) + /// .get_matches_from_safe(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires + /// [Conflicting]: ./struct.Arg.html#method.conflicts_with + /// [required]: ./struct.Arg.html#method.required + pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self { + if let Some(ref mut vec) = self.r_ifs { + for r_if in ifs { + vec.push((r_if.0, r_if.1)); + } + } else { + let mut vec = vec![]; + for r_if in ifs { + vec.push((r_if.0, r_if.1)); + } + self.r_ifs = Some(vec); + } + self + } + + /// Sets multiple arguments by names that are required when this one is present I.e. when + /// using this argument, the following arguments *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// by default. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::with_name("config") + /// .requires_all(&["input", "output"]) + /// # ; + /// ``` + /// + /// Setting [`Arg::requires_all(&[arg, arg2])`] requires that all the arguments be used at + /// runtime if the defining argument is used. If the defining argument isn't used, the other + /// argument isn't required + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::with_name("input") + /// .index(1)) + /// .arg(Arg::with_name("output") + /// .index(2)) + /// .get_matches_from_safe(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required + /// ``` + /// + /// Setting [`Arg::requires_all(&[arg, arg2])`] and *not* supplying all the arguments is an + /// error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .takes_value(true) + /// .requires_all(&["input", "output"]) + /// .long("config")) + /// .arg(Arg::with_name("input") + /// .index(1)) + /// .arg(Arg::with_name("output") + /// .index(2)) + /// .get_matches_from_safe(vec![ + /// "prog", "--config", "file.conf", "in.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// // We didn't use output + /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [Conflicting]: ./struct.Arg.html#method.conflicts_with + /// [override]: ./struct.Arg.html#method.overrides_with + /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all + pub fn requires_all(mut self, names: &[&'a str]) -> Self { + if let Some(ref mut vec) = self.b.requires { + for s in names { + vec.push((None, s)); + } + } else { + let mut vec = vec![]; + for s in names { + vec.push((None, *s)); + } + self.b.requires = Some(vec); + } + self + } + + /// Specifies that the argument takes a value at run time. + /// + /// **NOTE:** values for arguments may be specified in any of the following methods + /// + /// * Using a space such as `-o value` or `--option value` + /// * Using an equals and no space such as `-o=value` or `--option=value` + /// * Use a short and no space such as `-ovalue` + /// + /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning + /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to + /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`], + /// alternatively you can turn delimiting values **OFF** by using [`Arg::use_delimiter(false)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .takes_value(true) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .long("mode") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter + /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter + /// [multiple values]: ./struct.Arg.html#method.multiple + pub fn takes_value(self, tv: bool) -> Self { + if tv { + self.set(ArgSettings::TakesValue) + } else { + self.unset(ArgSettings::TakesValue) + } + } + + /// Specifies if the possible values of an argument should be displayed in the help text or + /// not. Defaults to `false` (i.e. show possible values) + /// + /// This is useful for args with many values, or ones which are explained elsewhere in the + /// help text. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .hide_possible_values(true) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .long("mode") + /// .possible_values(&["fast", "slow"]) + /// .takes_value(true) + /// .hide_possible_values(true)); + /// + /// ``` + /// + /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of + /// the help text would be omitted. + pub fn hide_possible_values(self, hide: bool) -> Self { + if hide { + self.set(ArgSettings::HidePossibleValues) + } else { + self.unset(ArgSettings::HidePossibleValues) + } + } + + /// Specifies if the default value of an argument should be displayed in the help text or + /// not. Defaults to `false` (i.e. show default value) + /// + /// This is useful when default behavior of an arg is explained elsewhere in the help text. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .hide_default_value(true) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("connect") + /// .arg(Arg::with_name("host") + /// .long("host") + /// .default_value("localhost") + /// .hide_default_value(true)); + /// + /// ``` + /// + /// If we were to run the above program with `--help` the `[default: localhost]` portion of + /// the help text would be omitted. + pub fn hide_default_value(self, hide: bool) -> Self { + if hide { + self.set(ArgSettings::HideDefaultValue) + } else { + self.unset(ArgSettings::HideDefaultValue) + } + } + + /// Specifies the index of a positional argument **starting at** 1. + /// + /// **NOTE:** The index refers to position according to **other positional argument**. It does + /// not define position in the argument list as a whole. + /// + /// **NOTE:** If no [`Arg::short`], or [`Arg::long`] have been defined, you can optionally + /// leave off the `index` method, and the index will be assigned in order of evaluation. + /// Utilizing the `index` method allows for setting indexes out of order + /// + /// **NOTE:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument + /// may be defined as multiple (i.e. with the highest index) + /// + /// # Panics + /// + /// Although not in this method directly, [`App`] will [`panic!`] if indexes are skipped (such + /// as defining `index(1)` and `index(3)` but not `index(2)`, or a positional argument is + /// defined as multiple and is not the highest index + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("config") + /// .index(1) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .index(1)) + /// .arg(Arg::with_name("debug") + /// .long("debug")) + /// .get_matches_from(vec![ + /// "prog", "--debug", "fast" + /// ]); + /// + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" + /// // *not* first argument + /// ``` + /// [`Arg::short`]: ./struct.Arg.html#method.short + /// [`Arg::long`]: ./struct.Arg.html#method.long + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + /// [`App`]: ./struct.App.html + /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html + pub fn index(mut self, idx: u64) -> Self { + self.index = Some(idx); + self + } + + /// Specifies that the argument may appear more than once. For flags, this results + /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d` + /// would count as three occurrences. For options there is a distinct difference in multiple + /// occurrences vs multiple values. + /// + /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas + /// `--opt val1 --opt val2` is two occurrences. + /// + /// **WARNING:** + /// + /// Setting `multiple(true)` for an [option] with no other details, allows multiple values + /// **and** multiple occurrences because it isn't possible to have more occurrences than values + /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly + /// valid, be careful when designing a CLI where positional arguments are expected after a + /// option which accepts multiple values, as `clap` will continue parsing *values* until it + /// reaches the max or specific number of values defined, or another flag or option. + /// + /// **Pro Tip**: + /// + /// It's possible to define an option which allows multiple occurrences, but only one value per + /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with + /// [`Arg::multiple(true)`]. + /// + /// **WARNING:** + /// + /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that + /// accept values) and [subcommands], one needs to consider the possibility of an argument value + /// being the same as a valid subcommand. By default `clap` will parse the argument in question + /// as a value *only if* a value is possible at that moment. Otherwise it will be parsed as a + /// subcommand. In effect, this means using `multiple(true)` with no additional parameters and + /// a possible value that coincides with a subcommand name, the subcommand cannot be called + /// unless another argument is passed first. + /// + /// As an example, consider a CLI with an option `--ui-paths=...` and subcommand `signer` + /// + /// The following would be parsed as values to `--ui-paths`. + /// + /// ```notrust + /// $ program --ui-paths path1 path2 signer + /// ``` + /// + /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values + /// until another argument is reached and it knows `--ui-paths` is done. + /// + /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding + /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer` + /// is parsed as both a subcommand and a value in the second case. + /// + /// ```notrust + /// $ program --ui-paths path1 signer + /// $ program --ui-paths path1 --ui-paths signer signer + /// ``` + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .short("d") + /// .multiple(true) + /// # ; + /// ``` + /// An example with flags + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("verbose") + /// .multiple(true) + /// .short("v")) + /// .get_matches_from(vec![ + /// "prog", "-v", "-v", "-v" // note, -vvv would have same result + /// ]); + /// + /// assert!(m.is_present("verbose")); + /// assert_eq!(m.occurrences_of("verbose"), 3); + /// ``` + /// + /// An example with options + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("file") + /// .multiple(true) + /// .takes_value(true) + /// .short("F")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(m.is_present("file")); + /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// This is functionally equivalent to the example above + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("file") + /// .multiple(true) + /// .takes_value(true) + /// .short("F")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" + /// ]); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// + /// assert!(m.is_present("file")); + /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// + /// A common mistake is to define an option which allows multiples, and a positional argument + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("file") + /// .multiple(true) + /// .takes_value(true) + /// .short("F")) + /// .arg(Arg::with_name("word") + /// .index(1)) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(m.is_present("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! + /// assert!(!m.is_present("word")); // but we clearly used word! + /// ``` + /// The problem is clap doesn't know when to stop parsing values for "files". This is further + /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would + /// appear to only fail sometimes...not good! + /// + /// A solution for the example above is to specify that `-F` only accepts one value, but is + /// allowed to appear multiple times + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("file") + /// .multiple(true) + /// .takes_value(true) + /// .number_of_values(1) + /// .short("F")) + /// .arg(Arg::with_name("word") + /// .index(1)) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" + /// ]); + /// + /// assert!(m.is_present("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert!(m.is_present("word")); + /// assert_eq!(m.value_of("word"), Some("word")); + /// ``` + /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the + /// problem example above, it would have been a runtime error with a pretty message to the + /// user :) + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .multiple(true) + /// .takes_value(true) + /// .number_of_values(1) + /// .short("F")) + /// .arg(Arg::with_name("word") + /// .index(1)) + /// .get_matches_from_safe(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [option]: ./struct.Arg.html#method.takes_value + /// [options]: ./struct.Arg.html#method.takes_value + /// [subcommands]: ./struct.SubCommand.html + /// [positionals]: ./struct.Arg.html#method.index + /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + pub fn multiple(self, multi: bool) -> Self { + if multi { + self.set(ArgSettings::Multiple) + } else { + self.unset(ArgSettings::Multiple) + } + } + + /// Specifies a value that *stops* parsing multiple values of a give argument. By default when + /// one sets [`multiple(true)`] on an argument, clap will continue parsing values for that + /// argument until it reaches another valid argument, or one of the other more specific settings + /// for multiple values is used (such as [`min_values`], [`max_values`] or + /// [`number_of_values`]). + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one + /// of the values + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("vals") + /// .takes_value(true) + /// .multiple(true) + /// .value_terminator(";") + /// # ; + /// ``` + /// The following example uses two arguments, a sequence of commands, and the location in which + /// to perform them + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cmds") + /// .multiple(true) + /// .allow_hyphen_values(true) + /// .value_terminator(";")) + /// .arg(Arg::with_name("location")) + /// .get_matches_from(vec![ + /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" + /// ]); + /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); + /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); + /// assert_eq!(m.value_of("location"), Some("/home/clap")); + /// ``` + /// [options]: ./struct.Arg.html#method.takes_value + /// [positional arguments]: ./struct.Arg.html#method.index + /// [`multiple(true)`]: ./struct.Arg.html#method.multiple + /// [`min_values`]: ./struct.Arg.html#method.min_values + /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values + /// [`max_values`]: ./struct.Arg.html#method.max_values + pub fn value_terminator(mut self, term: &'b str) -> Self { + self.setb(ArgSettings::TakesValue); + self.v.terminator = Some(term); + self + } + + /// Specifies that an argument can be matched to all child [`SubCommand`]s. + /// + /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however + /// their values once a user uses them will be propagated back up to parents. In effect, this + /// means one should *define* all global arguments at the top level, however it doesn't matter + /// where the user *uses* the global argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .short("d") + /// .global(true) + /// # ; + /// ``` + /// + /// For example, assume an application with two subcommands, and you'd like to define a + /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't + /// want to clutter the source with three duplicate [`Arg`] definitions. + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("verb") + /// .long("verbose") + /// .short("v") + /// .global(true)) + /// .subcommand(SubCommand::with_name("test")) + /// .subcommand(SubCommand::with_name("do-stuff")) + /// .get_matches_from(vec![ + /// "prog", "do-stuff", "--verbose" + /// ]); + /// + /// assert_eq!(m.subcommand_name(), Some("do-stuff")); + /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); + /// assert!(sub_m.is_present("verb")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [required]: ./struct.Arg.html#method.required + /// [`ArgMatches`]: ./struct.ArgMatches.html + /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present + /// [`Arg`]: ./struct.Arg.html + pub fn global(self, g: bool) -> Self { + if g { + self.set(ArgSettings::Global) + } else { + self.unset(ArgSettings::Global) + } + } + + /// Allows an argument to accept explicitly empty values. An empty value must be specified at + /// the command line with an explicit `""`, or `''` + /// + /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed) + /// + /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false` + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("file") + /// .long("file") + /// .empty_values(false) + /// # ; + /// ``` + /// The default is to allow empty values, such as `--option ""` would be an empty value. But + /// we can change to make empty values become an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .short("v") + /// .empty_values(false)) + /// .get_matches_from_safe(vec![ + /// "prog", "--config=" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); + /// ``` + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + pub fn empty_values(mut self, ev: bool) -> Self { + if ev { + self.set(ArgSettings::EmptyValues) + } else { + self = self.set(ArgSettings::TakesValue); + self.unset(ArgSettings::EmptyValues) + } + } + + /// Hides an argument from help message output. + /// + /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`] + /// when set to true + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .hidden(true) + /// # ; + /// ``` + /// Setting `hidden(true)` will hide the argument when displaying help text + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .hidden(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// ``` + /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help + /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help + pub fn hidden(self, h: bool) -> Self { + if h { + self.set(ArgSettings::Hidden) + } else { + self.unset(ArgSettings::Hidden) + } + } + + /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that + /// only one of the specified values was used, or fails with an error message. + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("mode") + /// .takes_value(true) + /// .possible_values(&["fast", "slow", "medium"]) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_values(&["fast", "slow", "medium"])) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// + /// The next example shows a failed parse from using a value which wasn't defined as one of the + /// possible values. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_values(&["fast", "slow", "medium"])) + /// .get_matches_from_safe(vec![ + /// "prog", "--mode", "wrong" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); + /// ``` + /// [options]: ./struct.Arg.html#method.takes_value + /// [positional arguments]: ./struct.Arg.html#method.index + pub fn possible_values(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut vec) = self.v.possible_vals { + for s in names { + vec.push(s); + } + } else { + self.v.possible_vals = Some(names.iter().copied().collect()); + } + self + } + + /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies + /// that only one of the specified values was used, or fails with error message. + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium")) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// + /// The next example shows a failed parse from using a value which wasn't defined as one of the + /// possible values. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium")) + /// .get_matches_from_safe(vec![ + /// "prog", "--mode", "wrong" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); + /// ``` + /// [options]: ./struct.Arg.html#method.takes_value + /// [positional arguments]: ./struct.Arg.html#method.index + pub fn possible_value(mut self, name: &'b str) -> Self { + if let Some(ref mut vec) = self.v.possible_vals { + vec.push(name); + } else { + self.v.possible_vals = Some(vec![name]); + } + self + } + + /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if + /// the case differs from that of the specified `possible_value`. + /// + /// **Pro Tip:** Use this setting with [`arg_enum!`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// # use std::ascii::AsciiExt; + /// let m = App::new("pv") + /// .arg(Arg::with_name("option") + /// .long("--option") + /// .takes_value(true) + /// .possible_value("test123") + /// .case_insensitive(true)) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", + /// ]); + /// + /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123")); + /// ``` + /// + /// This setting also works when multiple values can be defined: + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("pv") + /// .arg(Arg::with_name("option") + /// .short("-o") + /// .long("--option") + /// .takes_value(true) + /// .possible_value("test123") + /// .possible_value("test321") + /// .multiple(true) + /// .case_insensitive(true)) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", "teST123", "tESt321" + /// ]); + /// + /// let matched_vals = m.values_of("option").unwrap().collect::>(); + /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); + /// ``` + /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values + /// [`arg_enum!`]: ./macro.arg_enum.html + pub fn case_insensitive(self, ci: bool) -> Self { + if ci { + self.set(ArgSettings::CaseInsensitive) + } else { + self.unset(ArgSettings::CaseInsensitive) + } + } + + /// Specifies the name of the [`ArgGroup`] the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .long("debug") + /// .group("mode") + /// # ; + /// ``` + /// + /// Multiple arguments can be a member of a single group and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("debug") + /// .long("debug") + /// .group("mode")) + /// .arg(Arg::with_name("verbose") + /// .long("verbose") + /// .group("mode")) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.is_present("mode")); + /// ``` + /// [`ArgGroup`]: ./struct.ArgGroup.html + pub fn group(mut self, name: &'a str) -> Self { + if let Some(ref mut vec) = self.b.groups { + vec.push(name); + } else { + self.b.groups = Some(vec![name]); + } + self + } + + /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .long("debug") + /// .groups(&["mode", "verbosity"]) + /// # ; + /// ``` + /// + /// Arguments can be members of multiple groups and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("debug") + /// .long("debug") + /// .groups(&["mode", "verbosity"])) + /// .arg(Arg::with_name("verbose") + /// .long("verbose") + /// .groups(&["mode", "verbosity"])) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.is_present("mode")); + /// assert!(m.is_present("verbosity")); + /// ``` + /// [`ArgGroup`]: ./struct.ArgGroup.html + pub fn groups(mut self, names: &[&'a str]) -> Self { + if let Some(ref mut vec) = self.b.groups { + for s in names { + vec.push(s); + } + } else { + self.b.groups = Some(names.iter().copied().collect()); + } + self + } + + /// Specifies how many values are required to satisfy this argument. For example, if you had a + /// `-f ` argument where you wanted exactly 3 'files' you would set + /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided + /// 3 and only 3 values. + /// + /// **NOTE:** Does *not* require [`Arg::multiple(true)`] to be set. Setting + /// [`Arg::multiple(true)`] would allow `-f -f ` where + /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("file") + /// .short("f") + /// .number_of_values(3) + /// # ; + /// ``` + /// + /// Not supplying the correct number of values is an error + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .takes_value(true) + /// .number_of_values(2) + /// .short("F")) + /// .get_matches_from_safe(vec![ + /// "prog", "-F", "file1" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues); + /// ``` + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + pub fn number_of_values(mut self, qty: u64) -> Self { + self.setb(ArgSettings::TakesValue); + self.v.num_vals = Some(qty); + self + } + + /// Allows one to perform a custom validation on the argument value. You provide a closure + /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a + /// message displayed to the user. + /// + /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the + /// message as all errors will appear as + /// `error: Invalid value for '': ` where `` is replaced by the actual + /// arg, and `` is the `String` you return as the error. + /// + /// **NOTE:** There is a small performance hit for using validators, as they are implemented + /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order + /// to to be passed to the closure. This performance hit is extremely minimal in the grand + /// scheme of things. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// fn has_at(v: String) -> Result<(), String> { + /// if v.contains("@") { return Ok(()); } + /// Err(String::from("The value did not contain the required @ sigil")) + /// } + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .index(1) + /// .validator(has_at)) + /// .get_matches_from_safe(vec![ + /// "prog", "some@file" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("file"), Some("some@file")); + /// ``` + /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html + /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html + /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err + /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html + pub fn validator(mut self, f: F) -> Self + where + F: Fn(String) -> Result<(), String> + 'static, + { + self.v.validator = Some(Rc::new(f)); + self + } + + /// Works identically to Validator but is intended to be used with values that could + /// contain non UTF-8 formatted strings. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```rust")] + /// # use clap::{App, Arg}; + /// # use std::ffi::{OsStr, OsString}; + /// # use std::os::unix::ffi::OsStrExt; + /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> { + /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } + /// Err(OsString::from("The value did not contain the required & sigil")) + /// } + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .index(1) + /// .validator_os(has_ampersand)) + /// .get_matches_from_safe(vec![ + /// "prog", "Fish & chips" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips")); + /// ``` + /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html + /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html + /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html + /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html + /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err + /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html + pub fn validator_os(mut self, f: F) -> Self + where + F: Fn(&OsStr) -> Result<(), OsString> + 'static, + { + self.v.validator_os = Some(Rc::new(f)); + self + } + + /// Specifies the *maximum* number of values are for this argument. For example, if you had a + /// `-f ` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and + /// this argument would be satisfied if the user provided, 1, 2, or 3 values. + /// + /// **NOTE:** This does *not* implicitly set [`Arg::multiple(true)`]. This is because + /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single + /// occurrence with multiple values. For positional arguments this **does** set + /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple + /// occurrences and multiple values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("file") + /// .short("f") + /// .max_values(3) + /// # ; + /// ``` + /// + /// Supplying less than the maximum number of values is allowed + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .takes_value(true) + /// .max_values(3) + /// .short("F")) + /// .get_matches_from_safe(vec![ + /// "prog", "-F", "file1", "file2" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2"]); + /// ``` + /// + /// Supplying more than the maximum number of values is an error + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .takes_value(true) + /// .max_values(2) + /// .short("F")) + /// .get_matches_from_safe(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues); + /// ``` + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + pub fn max_values(mut self, qty: u64) -> Self { + self.setb(ArgSettings::TakesValue); + self.v.max_vals = Some(qty); + self + } + + /// Specifies the *minimum* number of values for this argument. For example, if you had a + /// `-f ` argument where you wanted at least 2 'files' you would set + /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more + /// values. + /// + /// **NOTE:** This does not implicitly set [`Arg::multiple(true)`]. This is because + /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single + /// occurrence with multiple values. For positional arguments this **does** set + /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple + /// occurrences and multiple values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("file") + /// .short("f") + /// .min_values(3) + /// # ; + /// ``` + /// + /// Supplying more than the minimum number of values is allowed + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .takes_value(true) + /// .min_values(2) + /// .short("F")) + /// .get_matches_from_safe(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// + /// Supplying less than the minimum number of values is an error + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("file") + /// .takes_value(true) + /// .min_values(2) + /// .short("F")) + /// .get_matches_from_safe(vec![ + /// "prog", "-F", "file1" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues); + /// ``` + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + pub fn min_values(mut self, qty: u64) -> Self { + self.v.min_vals = Some(qty); + self.set(ArgSettings::TakesValue) + } + + /// Specifies whether or not an argument should allow grouping of multiple values via a + /// delimiter. I.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, + /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the + /// value delimiter for all arguments that accept values (options and positional arguments) + /// + /// **NOTE:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`] + /// is the comma `,`. + /// + /// # Examples + /// + /// The following example shows the default behavior. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let delims = App::new("prog") + /// .arg(Arg::with_name("option") + /// .long("option") + /// .use_delimiter(true) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(delims.is_present("option")); + /// assert_eq!(delims.occurrences_of("option"), 1); + /// assert_eq!(delims.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + /// The next example shows the difference when turning delimiters off. This is the default + /// behavior + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let nodelims = App::new("prog") + /// .arg(Arg::with_name("option") + /// .long("option") + /// .use_delimiter(false) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(nodelims.is_present("option")); + /// assert_eq!(nodelims.occurrences_of("option"), 1); + /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); + /// ``` + /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter + pub fn use_delimiter(mut self, d: bool) -> Self { + if d { + if self.v.val_delim.is_none() { + self.v.val_delim = Some(','); + } + self.setb(ArgSettings::TakesValue); + self.setb(ArgSettings::UseValueDelimiter); + } else { + self.v.val_delim = None; + self.unsetb(ArgSettings::UseValueDelimiter); + } + self.unset(ArgSettings::ValueDelimiterNotSet) + } + + /// Specifies that *multiple values* may only be set using the delimiter. This means if an + /// if an option is encountered, and no delimiter is found, it automatically assumed that no + /// additional values for that option follow. This is unlike the default, where it is generally + /// assumed that more values will follow regardless of whether or not a delimiter is used. + /// + /// **NOTE:** The default is `false`. + /// + /// **NOTE:** Setting this to true implies [`Arg::use_delimiter(true)`] + /// + /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either + /// through help text or other means. + /// + /// # Examples + /// + /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice + /// everything works in this first example, as we use a delimiter, as expected. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let delims = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .short("o") + /// .takes_value(true) + /// .multiple(true) + /// .require_delimiter(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1,val2,val3", + /// ]); + /// + /// assert!(delims.is_present("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + /// In this next example, we will *not* use a delimiter. Notice it's now an error. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .short("o") + /// .takes_value(true) + /// .multiple(true) + /// .require_delimiter(true)) + /// .get_matches_from_safe(vec![ + /// "prog", "-o", "val1", "val2", "val3", + /// ]); + /// + /// assert!(res.is_err()); + /// let err = res.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::UnknownArgument); + /// ``` + /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none + /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no + /// positional arguments have been defined, it's an error of an unexpected argument. + /// + /// In this final example, we contrast the above with `clap`'s default behavior where the above + /// is *not* an error. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let delims = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .short("o") + /// .takes_value(true) + /// .multiple(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1", "val2", "val3", + /// ]); + /// + /// assert!(delims.is_present("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter + pub fn require_delimiter(mut self, d: bool) -> Self { + if d { + self = self.use_delimiter(true); + self.unsetb(ArgSettings::ValueDelimiterNotSet); + self.setb(ArgSettings::UseValueDelimiter); + self.set(ArgSettings::RequireDelimiter) + } else { + self = self.use_delimiter(false); + self.unsetb(ArgSettings::UseValueDelimiter); + self.unset(ArgSettings::RequireDelimiter) + } + } + + /// Specifies the separator to use when values are clumped together, defaults to `,` (comma). + /// + /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`] + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("config") + /// .short("c") + /// .long("config") + /// .value_delimiter(";")) + /// .get_matches_from(vec![ + /// "prog", "--config=val1;val2;val3" + /// ]); + /// + /// assert_eq!(m.values_of("config").unwrap().collect::>(), ["val1", "val2", "val3"]) + /// ``` + /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + pub fn value_delimiter(mut self, d: &str) -> Self { + self.unsetb(ArgSettings::ValueDelimiterNotSet); + self.setb(ArgSettings::TakesValue); + self.setb(ArgSettings::UseValueDelimiter); + self.v.val_delim = Some( + d.chars() + .next() + .expect("Failed to get value_delimiter from arg"), + ); + self + } + + /// Specify multiple names for values of option arguments. These names are cosmetic only, used + /// for help and usage strings only. The names are **not** used to access arguments. The values + /// of the arguments are accessed in numeric order (i.e. if you specify two names `one` and + /// `two` `one` will be the first matched value, `two` will be the second). + /// + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or + /// multiple value names in order to not throw off the help text alignment of all options. + /// + /// **NOTE:** This implicitly sets [`Arg::number_of_values`] if the number of value names is + /// greater than one. I.e. be aware that the number of "names" you set for the values, will be + /// the *exact* number of values required to satisfy this argument + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("speed") + /// .short("s") + /// .value_names(&["fast", "slow"]) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("io") + /// .long("io-files") + /// .value_names(&["INFILE", "OUTFILE"])) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// Running the above program produces the following output + /// + /// ```notrust + /// valnames + /// + /// USAGE: + /// valnames [FLAGS] [OPTIONS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// + /// OPTIONS: + /// --io-files Some help text + /// ``` + /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help + /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + pub fn value_names(mut self, names: &[&'b str]) -> Self { + self.setb(ArgSettings::TakesValue); + if self.is_set(ArgSettings::ValueDelimiterNotSet) { + self.unsetb(ArgSettings::ValueDelimiterNotSet); + self.setb(ArgSettings::UseValueDelimiter); + } + if let Some(ref mut vals) = self.v.val_names { + let mut l = vals.len(); + for s in names { + vals.insert(l, s); + l += 1; + } + } else { + let mut vm = VecMap::new(); + for (i, n) in names.iter().enumerate() { + vm.insert(i, *n); + } + self.v.val_names = Some(vm); + } + self + } + + /// Specifies the name for value of [option] or [positional] arguments inside of help + /// documentation. This name is cosmetic only, the name is **not** used to access arguments. + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("cfg") + /// .long("config") + /// .value_name("FILE") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("config") + /// .long("config") + /// .value_name("FILE")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// Running the above program produces the following output + /// + /// ```notrust + /// valnames + /// + /// USAGE: + /// valnames [FLAGS] [OPTIONS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// + /// OPTIONS: + /// --config Some help text + /// ``` + /// [option]: ./struct.Arg.html#method.takes_value + /// [positional]: ./struct.Arg.html#method.index + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + pub fn value_name(mut self, name: &'b str) -> Self { + self.setb(ArgSettings::TakesValue); + if let Some(ref mut vals) = self.v.val_names { + let l = vals.len(); + vals.insert(l, name); + } else { + let mut vm = VecMap::new(); + vm.insert(0, name); + self.v.val_names = Some(vm); + } + self + } + + /// Specifies the value of the argument when *not* specified at runtime. + /// + /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] + /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. + /// + /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will + /// still return `true`. If you wish to determine whether the argument was used at runtime or + /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not* + /// used at runtime. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly + /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg + /// at runtime. `Arg::default_value_if` however only takes affect when the user has not provided + /// a value at runtime **and** these other conditions are met as well. If you have set + /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide a this + /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the + /// `Arg::default_value` will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in + /// conjunction as it ensures that some argument will always be present. + /// + /// # Examples + /// + /// First we use the default value without providing any value at runtime. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("opt"), Some("myval")); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 0); + /// ``` + /// + /// Next we provide a value at runtime to override the default. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog", "--myopt=non_default" + /// ]); + /// + /// assert_eq!(m.value_of("opt"), Some("non_default")); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// ``` + /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of + /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present + /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if + pub fn default_value(self, val: &'a str) -> Self { + self.default_value_os(OsStr::from_bytes(val.as_bytes())) + } + + /// Provides a default value in the exact same manner as [`Arg::default_value`] + /// only using [`OsStr`]s instead. + /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value + /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html + pub fn default_value_os(mut self, val: &'a OsStr) -> Self { + self.setb(ArgSettings::TakesValue); + self.v.default_val = Some(val); + self + } + + /// Specifies the value of the argument if `arg` has been used at runtime. If `val` is set to + /// `None`, `arg` only needs to be present. If `val` is set to `"some-val"` then `arg` must be + /// present at runtime **and** have the value `val`. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly + /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg + /// at runtime. This setting however only takes affect when the user has not provided a value at + /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` + /// and `Arg::default_value_if`, and the user **did not** provide a this arg at runtime, nor did + /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be + /// applied. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented + /// as `null` in YAML) + /// + /// ```yaml + /// default_value_if: + /// - [arg, val, default] + /// ``` + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_if("flag", None, "default")) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_if("flag", None, "default")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// Now lets only use the default value if `--opt` contains the value `special`. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .takes_value(true) + /// .long("opt")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_if("opt", Some("special"), "default")) + /// .get_matches_from(vec![ + /// "prog", "--opt", "special" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// + /// We can run the same test and provide any value *other than* `special` and we won't get a + /// default value. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .takes_value(true) + /// .long("opt")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_if("opt", Some("special"), "default")) + /// .get_matches_from(vec![ + /// "prog", "--opt", "hahaha" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value + pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self { + self.default_value_if_os( + arg, + val.map(str::as_bytes).map(OsStr::from_bytes), + OsStr::from_bytes(default.as_bytes()), + ) + } + + /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] + /// only using [`OsStr`]s instead. + /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if + /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html + pub fn default_value_if_os( + mut self, + arg: &'a str, + val: Option<&'b OsStr>, + default: &'b OsStr, + ) -> Self { + self.setb(ArgSettings::TakesValue); + if let Some(ref mut vm) = self.v.default_vals_ifs { + let l = vm.len(); + vm.insert(l, (arg, val, default)); + } else { + let mut vm = VecMap::new(); + vm.insert(0, (arg, val, default)); + self.v.default_vals_ifs = Some(vm); + } + self + } + + /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. + /// The method takes a slice of tuples in the `(arg, Option, default)` format. + /// + /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first + /// if multiple conditions are true, the first one found will be applied and the ultimate value. + /// + /// **NOTE:** If using YAML the values should be laid out as follows + /// + /// ```yaml + /// default_value_if: + /// - [arg, val, default] + /// - [arg2, null, default2] + /// ``` + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag")) + /// .arg(Arg::with_name("opt") + /// .long("opt") + /// .takes_value(true)) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, "default"), + /// ("opt", Some("channal"), "chan"), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("chan")); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag")) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, "default"), + /// ("opt", Some("channal"), "chan"), + /// ])) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// We can also see that these values are applied in order, and if more than one condition is + /// true, only the first evaluated "wins" + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag")) + /// .arg(Arg::with_name("opt") + /// .long("opt") + /// .takes_value(true)) + /// .arg(Arg::with_name("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, "default"), + /// ("opt", Some("channal"), "chan"), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value + pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self { + for &(arg, val, default) in ifs { + self = self.default_value_if_os( + arg, + val.map(str::as_bytes).map(OsStr::from_bytes), + OsStr::from_bytes(default.as_bytes()), + ); + } + self + } + + /// Provides multiple conditional default values in the exact same manner as + /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead. + /// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs + /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html + pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self { + for &(arg, val, default) in ifs { + self = self.default_value_if_os(arg, val, default); + } + self + } + + /// Specifies that if the value is not passed in as an argument, that it should be retrieved + /// from the environment, if available. If it is not present in the environment, then default + /// rules will apply. + /// + /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] + /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. + /// + /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will + /// return `true` if the variable is present in the environment . If you wish to determine whether + /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will + /// return `0` if the argument was *not* used at runtime. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be + /// set. Otherwise, only a single argument will be returned from the environment variable. The + /// default delimiter is `,` and follows all the other delimiter rules. + /// + /// # Examples + /// + /// In this example, we show the variable coming from the environment: + /// + /// ```rust + /// # use std::env; + /// # use clap::{App, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag") + /// .env("MY_FLAG")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("env")); + /// ``` + /// + /// In this example, we show the variable coming from an option on the CLI: + /// + /// ```rust + /// # use std::env; + /// # use clap::{App, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag") + /// .env("MY_FLAG")) + /// .get_matches_from(vec![ + /// "prog", "--flag", "opt" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("opt")); + /// ``` + /// + /// In this example, we show the variable coming from the environment even with the + /// presence of a default: + /// + /// ```rust + /// # use std::env; + /// # use clap::{App, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .default_value("default")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("env")); + /// ``` + /// + /// In this example, we show the use of multiple values in a single environment variable: + /// + /// ```rust + /// # use std::env; + /// # use clap::{App, Arg}; + /// + /// env::set_var("MY_FLAG_MULTI", "env1,env2"); + /// + /// let m = App::new("prog") + /// .arg(Arg::with_name("flag") + /// .long("flag") + /// .env("MY_FLAG_MULTI") + /// .multiple(true) + /// .use_delimiter(true)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.values_of("flag").unwrap().collect::>(), vec!["env1", "env2"]); + /// ``` + /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of + /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of + /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present + /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter + pub fn env(self, name: &'a str) -> Self { + self.env_os(OsStr::new(name)) + } + + /// Specifies that if the value is not passed in as an argument, that it should be retrieved + /// from the environment if available in the exact same manner as [`Arg::env`] only using + /// [`OsStr`]s instead. + pub fn env_os(mut self, name: &'a OsStr) -> Self { + self.setb(ArgSettings::TakesValue); + + self.v.env = Some((name, env::var_os(name))); + self + } + + /// @TODO @p2 @docs @release: write docs + pub fn hide_env_values(self, hide: bool) -> Self { + if hide { + self.set(ArgSettings::HideEnvValues) + } else { + self.unset(ArgSettings::HideEnvValues) + } + } + + /// When set to `true` the help string will be displayed on the line after the argument and + /// indented once. This can be helpful for arguments with very long or complex help messages. + /// This can also be helpful for arguments with very long flag names, or many/long value names. + /// + /// **NOTE:** To apply this setting to all arguments consider using + /// [`AppSettings::NextLineHelp`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("opt") + /// .long("long-option-flag") + /// .short("o") + /// .takes_value(true) + /// .value_names(&["value1", "value2"]) + /// .help("Some really long help and complex\n\ + /// help that makes more sense to be\n\ + /// on a line after the option") + /// .next_line_help(true)) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```notrust + /// nlh + /// + /// USAGE: + /// nlh [FLAGS] [OPTIONS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// + /// OPTIONS: + /// -o, --long-option-flag + /// Some really long help and complex + /// help that makes more sense to be + /// on a line after the option + /// ``` + /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp + pub fn next_line_help(mut self, nlh: bool) -> Self { + if nlh { + self.setb(ArgSettings::NextLineHelp); + } else { + self.unsetb(ArgSettings::NextLineHelp); + } + self + } + + /// Allows custom ordering of args within the help message. Args with a lower value will be + /// displayed first in the help message. This is helpful when one would like to emphasise + /// frequently used args, or prioritize those towards the top of the list. Duplicate values + /// **are** allowed. Args with duplicate display orders will be displayed in alphabetical + /// order. + /// + /// **NOTE:** The default is 999 for all arguments. + /// + /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in + /// [index] order. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name. + /// // Args without a display_order have a value of 999 and are + /// // displayed alphabetically with all other 999 valued args. + /// .long("long-option") + /// .short("o") + /// .takes_value(true) + /// .help("Some help and text")) + /// .arg(Arg::with_name("b") + /// .long("other-option") + /// .short("O") + /// .takes_value(true) + /// .display_order(1) // In order to force this arg to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other args with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .help("I should be first!")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```notrust + /// cust-ord + /// + /// USAGE: + /// cust-ord [FLAGS] [OPTIONS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// + /// OPTIONS: + /// -O, --other-option I should be first! + /// -o, --long-option Some help and text + /// ``` + /// [positional arguments]: ./struct.Arg.html#method.index + /// [index]: ./struct.Arg.html#method.index + pub fn display_order(mut self, ord: usize) -> Self { + self.s.disp_ord = ord; + self + } + + /// Indicates that all parameters passed after this should not be parsed + /// individually, but rather passed in their entirety. It is worth noting + /// that setting this requires all values to come after a `--` to indicate they + /// should all be captured. For example: + /// + /// ```notrust + /// --foo something -- -v -v -v -b -b -b --baz -q -u -x + /// ``` + /// Will result in everything after `--` to be considered one raw argument. This behavior + /// may not be exactly what you are expecting and using [`AppSettings::TrailingVarArg`] + /// may be more appropriate. + /// + /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and + /// [`Arg::last(true)`] when set to `true` + /// + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values + /// [`Arg::last(true)`]: ./struct.Arg.html#method.last + /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg + pub fn raw(self, raw: bool) -> Self { + self.multiple(raw).allow_hyphen_values(raw).last(raw) + } + + /// Hides an argument from short help message output. + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .hidden_short_help(true) + /// # ; + /// ``` + /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .hidden_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// ``` + /// + /// However, when --help is called + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .hidden_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// --config Some help text describing the --config arg + /// -h, --help Prints help information + /// -V, --version Prints version information + /// ``` + pub fn hidden_short_help(self, hide: bool) -> Self { + if hide { + self.set(ArgSettings::HiddenShortHelp) + } else { + self.unset(ArgSettings::HiddenShortHelp) + } + } + + /// Hides an argument from long help message output. + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::with_name("debug") + /// .hidden_long_help(true) + /// # ; + /// ``` + /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .hidden_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// ``` + /// + /// However, when -h is called + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::with_name("cfg") + /// .long("config") + /// .hidden_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [FLAGS] + /// + /// FLAGS: + /// --config Some help text describing the --config arg + /// -h, --help Prints help information + /// -V, --version Prints version information + /// ``` + pub fn hidden_long_help(self, hide: bool) -> Self { + if hide { + self.set(ArgSettings::HiddenLongHelp) + } else { + self.unset(ArgSettings::HiddenLongHelp) + } + } + + /// Checks if one of the [`ArgSettings`] settings is set for the argument. + /// + /// [`ArgSettings`]: ./enum.ArgSettings.html + pub fn is_set(&self, s: ArgSettings) -> bool { + self.b.is_set(s) + } + + /// Sets one of the [`ArgSettings`] settings for the argument. + /// + /// [`ArgSettings`]: ./enum.ArgSettings.html + pub fn set(mut self, s: ArgSettings) -> Self { + self.setb(s); + self + } + + /// Unsets one of the [`ArgSettings`] settings for the argument. + /// + /// [`ArgSettings`]: ./enum.ArgSettings.html + pub fn unset(mut self, s: ArgSettings) -> Self { + self.unsetb(s); + self + } + + #[doc(hidden)] + pub fn setb(&mut self, s: ArgSettings) { + self.b.set(s); + } + + #[doc(hidden)] + pub fn unsetb(&mut self, s: ArgSettings) { + self.b.unset(s); + } +} + +impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> { + fn from(a: &'z Arg<'a, 'b>) -> Self { + Arg { + b: a.b.clone(), + v: a.v.clone(), + s: a.s.clone(), + index: a.index, + r_ifs: a.r_ifs.clone(), + } + } +} + +impl<'n, 'e> PartialEq for Arg<'n, 'e> { + fn eq(&self, other: &Arg<'n, 'e>) -> bool { + self.b == other.b + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/base.rs b/bash-5.1/vendor/clap/src/args/arg_builder/base.rs new file mode 100644 index 0000000..ae1a2f6 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/base.rs @@ -0,0 +1,48 @@ +use crate::args::{Arg, ArgFlags, ArgSettings}; + +#[derive(Debug, Clone, Default)] +pub struct Base<'a, 'b> +where + 'a: 'b, +{ + pub name: &'a str, + pub help: Option<&'b str>, + pub long_help: Option<&'b str>, + pub blacklist: Option>, + pub settings: ArgFlags, + pub r_unless: Option>, + pub overrides: Option>, + pub groups: Option>, + pub requires: Option, &'a str)>>, +} + +impl<'n, 'e> Base<'n, 'e> { + pub fn new(name: &'n str) -> Self { + Base { + name, + ..Default::default() + } + } + + pub fn set(&mut self, s: ArgSettings) { + self.settings.set(s); + } + pub fn unset(&mut self, s: ArgSettings) { + self.settings.unset(s); + } + pub fn is_set(&self, s: ArgSettings) -> bool { + self.settings.is_set(s) + } +} + +impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Base<'n, 'e> { + fn from(a: &'z Arg<'n, 'e>) -> Self { + a.b.clone() + } +} + +impl<'n, 'e> PartialEq for Base<'n, 'e> { + fn eq(&self, other: &Base<'n, 'e>) -> bool { + self.name == other.name + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/flag.rs b/bash-5.1/vendor/clap/src/args/arg_builder/flag.rs new file mode 100644 index 0000000..e991a6c --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/flag.rs @@ -0,0 +1,216 @@ +// Std +use std::{ + convert::From, + ffi::{OsStr, OsString}, + fmt::{Display, Formatter, Result}, + mem, + rc::Rc, + result::Result as StdResult, +}; + +// Internal +use crate::{ + args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched}, + map::{self, VecMap}, +}; + +#[derive(Default, Clone, Debug)] +#[doc(hidden)] +pub struct FlagBuilder<'n, 'e> +where + 'n: 'e, +{ + pub b: Base<'n, 'e>, + pub s: Switched<'e>, +} + +impl<'n, 'e> FlagBuilder<'n, 'e> { + pub fn new(name: &'n str) -> Self { + FlagBuilder { + b: Base::new(name), + ..Default::default() + } + } +} + +impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> { + fn from(a: &'z Arg<'a, 'b>) -> Self { + FlagBuilder { + b: Base::from(a), + s: Switched::from(a), + } + } +} + +impl<'a, 'b> From> for FlagBuilder<'a, 'b> { + fn from(mut a: Arg<'a, 'b>) -> Self { + FlagBuilder { + b: mem::take(&mut a.b), + s: mem::take(&mut a.s), + } + } +} + +impl<'n, 'e> Display for FlagBuilder<'n, 'e> { + fn fmt(&self, f: &mut Formatter) -> Result { + if let Some(l) = self.s.long { + write!(f, "--{}", l)?; + } else { + write!(f, "-{}", self.s.short.unwrap())?; + } + + Ok(()) + } +} + +impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { + fn name(&self) -> &'n str { + self.b.name + } + fn overrides(&self) -> Option<&[&'e str]> { + self.b.overrides.as_ref().map(|o| &o[..]) + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + self.b.requires.as_ref().map(|o| &o[..]) + } + fn blacklist(&self) -> Option<&[&'e str]> { + self.b.blacklist.as_ref().map(|o| &o[..]) + } + fn required_unless(&self) -> Option<&[&'e str]> { + self.b.r_unless.as_ref().map(|o| &o[..]) + } + fn is_set(&self, s: ArgSettings) -> bool { + self.b.settings.is_set(s) + } + fn has_switch(&self) -> bool { + true + } + fn takes_value(&self) -> bool { + false + } + fn set(&mut self, s: ArgSettings) { + self.b.settings.set(s) + } + fn max_vals(&self) -> Option { + None + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + None + } + fn num_vals(&self) -> Option { + None + } + fn possible_vals(&self) -> Option<&[&'e str]> { + None + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator(&self) -> Option<&Rc StdResult<(), String>>> { + None + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { + None + } + fn min_vals(&self) -> Option { + None + } + fn short(&self) -> Option { + self.s.short + } + fn long(&self) -> Option<&'e str> { + self.s.long + } + fn val_delim(&self) -> Option { + None + } + fn help(&self) -> Option<&'e str> { + self.b.help + } + fn long_help(&self) -> Option<&'e str> { + self.b.long_help + } + fn val_terminator(&self) -> Option<&'e str> { + None + } + fn default_val(&self) -> Option<&'e OsStr> { + None + } + fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { + None + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + None + } + fn longest_filter(&self) -> bool { + self.s.long.is_some() + } + fn aliases(&self) -> Option> { + if let Some(ref aliases) = self.s.aliases { + let vis_aliases: Vec<_> = aliases + .iter() + .filter_map(|&(n, v)| if v { Some(n) } else { None }) + .collect(); + if vis_aliases.is_empty() { + None + } else { + Some(vis_aliases) + } + } else { + None + } + } +} + +impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> { + fn disp_ord(&self) -> usize { + self.s.disp_ord + } +} + +impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> { + fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool { + self.b == other.b + } +} + +#[cfg(test)] +mod test { + use super::FlagBuilder; + use crate::args::settings::ArgSettings; + + #[test] + fn flagbuilder_display() { + let mut f = FlagBuilder::new("flg"); + f.b.settings.set(ArgSettings::Multiple); + f.s.long = Some("flag"); + + assert_eq!(&*format!("{}", f), "--flag"); + + let mut f2 = FlagBuilder::new("flg"); + f2.s.short = Some('f'); + + assert_eq!(&*format!("{}", f2), "-f"); + } + + #[test] + fn flagbuilder_display_single_alias() { + let mut f = FlagBuilder::new("flg"); + f.s.long = Some("flag"); + f.s.aliases = Some(vec![("als", true)]); + + assert_eq!(&*format!("{}", f), "--flag"); + } + + #[test] + fn flagbuilder_display_multiple_aliases() { + let mut f = FlagBuilder::new("flg"); + f.s.short = Some('f'); + f.s.aliases = Some(vec![ + ("alias_not_visible", false), + ("f2", true), + ("f3", true), + ("f4", true), + ]); + assert_eq!(&*format!("{}", f), "-f"); + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/mod.rs b/bash-5.1/vendor/clap/src/args/arg_builder/mod.rs new file mode 100644 index 0000000..2d79208 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/mod.rs @@ -0,0 +1,13 @@ +pub use self::base::Base; +pub use self::flag::FlagBuilder; +pub use self::option::OptBuilder; +pub use self::positional::PosBuilder; +pub use self::switched::Switched; +pub use self::valued::Valued; + +mod base; +mod flag; +mod option; +mod positional; +mod switched; +mod valued; diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/option.rs b/bash-5.1/vendor/clap/src/args/arg_builder/option.rs new file mode 100644 index 0000000..3894914 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/option.rs @@ -0,0 +1,295 @@ +// Std +use std::{ + ffi::{OsStr, OsString}, + fmt::{Display, Formatter, Result}, + mem, + rc::Rc, + result::Result as StdResult, +}; + +// Internal +use crate::{ + args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched, Valued}, + map::{self, VecMap}, + INTERNAL_ERROR_MSG, +}; + +#[allow(missing_debug_implementations)] +#[doc(hidden)] +#[derive(Default, Clone)] +pub struct OptBuilder<'n, 'e> +where + 'n: 'e, +{ + pub b: Base<'n, 'e>, + pub s: Switched<'e>, + pub v: Valued<'n, 'e>, +} + +impl<'n, 'e> OptBuilder<'n, 'e> { + pub fn new(name: &'n str) -> Self { + OptBuilder { + b: Base::new(name), + ..Default::default() + } + } +} + +impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for OptBuilder<'n, 'e> { + fn from(a: &'z Arg<'n, 'e>) -> Self { + OptBuilder { + b: Base::from(a), + s: Switched::from(a), + v: Valued::from(a), + } + } +} + +impl<'n, 'e> From> for OptBuilder<'n, 'e> { + fn from(mut a: Arg<'n, 'e>) -> Self { + a.v.fill_in(); + OptBuilder { + b: mem::take(&mut a.b), + s: mem::take(&mut a.s), + v: mem::take(&mut a.v), + } + } +} + +impl<'n, 'e> Display for OptBuilder<'n, 'e> { + fn fmt(&self, f: &mut Formatter) -> Result { + debugln!("OptBuilder::fmt:{}", self.b.name); + let sep = if self.b.is_set(ArgSettings::RequireEquals) { + "=" + } else { + " " + }; + // Write the name such --long or -l + if let Some(l) = self.s.long { + write!(f, "--{}{}", l, sep)?; + } else { + write!(f, "-{}{}", self.s.short.unwrap(), sep)?; + } + let delim = if self.is_set(ArgSettings::RequireDelimiter) { + self.v.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }; + + // Write the values such as + if let Some(ref vec) = self.v.val_names { + let mut it = vec.iter().peekable(); + while let Some((_, val)) = it.next() { + write!(f, "<{}>", val)?; + if it.peek().is_some() { + write!(f, "{}", delim)?; + } + } + let num = vec.len(); + if self.is_set(ArgSettings::Multiple) && num == 1 { + write!(f, "...")?; + } + } else if let Some(num) = self.v.num_vals { + let mut it = (0..num).peekable(); + while let Some(_) = it.next() { + write!(f, "<{}>", self.b.name)?; + if it.peek().is_some() { + write!(f, "{}", delim)?; + } + } + if self.is_set(ArgSettings::Multiple) && num == 1 { + write!(f, "...")?; + } + } else { + write!( + f, + "<{}>{}", + self.b.name, + if self.is_set(ArgSettings::Multiple) { + "..." + } else { + "" + } + )?; + } + + Ok(()) + } +} + +impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> { + fn name(&self) -> &'n str { + self.b.name + } + fn overrides(&self) -> Option<&[&'e str]> { + self.b.overrides.as_ref().map(|o| &o[..]) + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + self.b.requires.as_ref().map(|o| &o[..]) + } + fn blacklist(&self) -> Option<&[&'e str]> { + self.b.blacklist.as_ref().map(|o| &o[..]) + } + fn required_unless(&self) -> Option<&[&'e str]> { + self.b.r_unless.as_ref().map(|o| &o[..]) + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + self.v.val_names.as_ref() + } + fn is_set(&self, s: ArgSettings) -> bool { + self.b.settings.is_set(s) + } + fn has_switch(&self) -> bool { + true + } + fn set(&mut self, s: ArgSettings) { + self.b.settings.set(s) + } + fn max_vals(&self) -> Option { + self.v.max_vals + } + fn val_terminator(&self) -> Option<&'e str> { + self.v.terminator + } + fn num_vals(&self) -> Option { + self.v.num_vals + } + fn possible_vals(&self) -> Option<&[&'e str]> { + self.v.possible_vals.as_ref().map(|o| &o[..]) + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator(&self) -> Option<&Rc StdResult<(), String>>> { + self.v.validator.as_ref() + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { + self.v.validator_os.as_ref() + } + fn min_vals(&self) -> Option { + self.v.min_vals + } + fn short(&self) -> Option { + self.s.short + } + fn long(&self) -> Option<&'e str> { + self.s.long + } + fn val_delim(&self) -> Option { + self.v.val_delim + } + fn takes_value(&self) -> bool { + true + } + fn help(&self) -> Option<&'e str> { + self.b.help + } + fn long_help(&self) -> Option<&'e str> { + self.b.long_help + } + fn default_val(&self) -> Option<&'e OsStr> { + self.v.default_val + } + fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { + self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + self.v + .env + .as_ref() + .map(|&(key, ref value)| (key, value.as_ref())) + } + fn longest_filter(&self) -> bool { + true + } + fn aliases(&self) -> Option> { + if let Some(ref aliases) = self.s.aliases { + let vis_aliases: Vec<_> = aliases + .iter() + .filter_map(|&(n, v)| if v { Some(n) } else { None }) + .collect(); + if vis_aliases.is_empty() { + None + } else { + Some(vis_aliases) + } + } else { + None + } + } +} + +impl<'n, 'e> DispOrder for OptBuilder<'n, 'e> { + fn disp_ord(&self) -> usize { + self.s.disp_ord + } +} + +impl<'n, 'e> PartialEq for OptBuilder<'n, 'e> { + fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool { + self.b == other.b + } +} + +#[cfg(test)] +mod test { + use super::OptBuilder; + use crate::{args::settings::ArgSettings, map::VecMap}; + + #[test] + fn optbuilder_display1() { + let mut o = OptBuilder::new("opt"); + o.s.long = Some("option"); + o.b.settings.set(ArgSettings::Multiple); + + assert_eq!(&*format!("{}", o), "--option ..."); + } + + #[test] + fn optbuilder_display2() { + let mut v_names = VecMap::new(); + v_names.insert(0, "file"); + v_names.insert(1, "name"); + + let mut o2 = OptBuilder::new("opt"); + o2.s.short = Some('o'); + o2.v.val_names = Some(v_names); + + assert_eq!(&*format!("{}", o2), "-o "); + } + + #[test] + fn optbuilder_display3() { + let mut v_names = VecMap::new(); + v_names.insert(0, "file"); + v_names.insert(1, "name"); + + let mut o2 = OptBuilder::new("opt"); + o2.s.short = Some('o'); + o2.v.val_names = Some(v_names); + o2.b.settings.set(ArgSettings::Multiple); + + assert_eq!(&*format!("{}", o2), "-o "); + } + + #[test] + fn optbuilder_display_single_alias() { + let mut o = OptBuilder::new("opt"); + o.s.long = Some("option"); + o.s.aliases = Some(vec![("als", true)]); + + assert_eq!(&*format!("{}", o), "--option "); + } + + #[test] + fn optbuilder_display_multiple_aliases() { + let mut o = OptBuilder::new("opt"); + o.s.long = Some("option"); + o.s.aliases = Some(vec![ + ("als_not_visible", false), + ("als2", true), + ("als3", true), + ("als4", true), + ]); + assert_eq!(&*format!("{}", o), "--option "); + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/positional.rs b/bash-5.1/vendor/clap/src/args/arg_builder/positional.rs new file mode 100644 index 0000000..9699fb6 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/positional.rs @@ -0,0 +1,284 @@ +// Std +use std::{ + borrow::Cow, + ffi::{OsStr, OsString}, + fmt::{Display, Formatter, Result}, + mem, + rc::Rc, + result::Result as StdResult, +}; + +// Internal +use crate::{ + args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Valued}, + map::{self, VecMap}, + INTERNAL_ERROR_MSG, +}; + +#[allow(missing_debug_implementations)] +#[doc(hidden)] +#[derive(Clone, Default)] +pub struct PosBuilder<'n, 'e> +where + 'n: 'e, +{ + pub b: Base<'n, 'e>, + pub v: Valued<'n, 'e>, + pub index: u64, +} + +impl<'n, 'e> PosBuilder<'n, 'e> { + pub fn new(name: &'n str, idx: u64) -> Self { + PosBuilder { + b: Base::new(name), + index: idx, + ..Default::default() + } + } + + pub fn from_arg_ref(a: &Arg<'n, 'e>, idx: u64) -> Self { + let mut pb = PosBuilder { + b: Base::from(a), + v: Valued::from(a), + index: idx, + }; + if a.v.max_vals.is_some() + || a.v.min_vals.is_some() + || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) + { + pb.b.settings.set(ArgSettings::Multiple); + } + pb + } + + pub fn from_arg(mut a: Arg<'n, 'e>, idx: u64) -> Self { + if a.v.max_vals.is_some() + || a.v.min_vals.is_some() + || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) + { + a.b.settings.set(ArgSettings::Multiple); + } + PosBuilder { + b: mem::take(&mut a.b), + v: mem::take(&mut a.v), + index: idx, + } + } + + pub fn multiple_str(&self) -> &str { + let mult_vals = self + .v + .val_names + .as_ref() + .map_or(true, |names| names.len() < 2); + if self.is_set(ArgSettings::Multiple) && mult_vals { + "..." + } else { + "" + } + } + + pub fn name_no_brackets(&self) -> Cow { + debugln!("PosBuilder::name_no_brackets;"); + let mut delim = String::new(); + delim.push(if self.is_set(ArgSettings::RequireDelimiter) { + self.v.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }); + if let Some(ref names) = self.v.val_names { + debugln!("PosBuilder:name_no_brackets: val_names={:#?}", names); + if names.len() > 1 { + Cow::Owned( + names + .values() + .map(|n| format!("<{}>", n)) + .collect::>() + .join(&*delim), + ) + } else { + Cow::Borrowed(names.values().next().expect(INTERNAL_ERROR_MSG)) + } + } else { + debugln!("PosBuilder:name_no_brackets: just name"); + Cow::Borrowed(self.b.name) + } + } +} + +impl<'n, 'e> Display for PosBuilder<'n, 'e> { + fn fmt(&self, f: &mut Formatter) -> Result { + let mut delim = String::new(); + delim.push(if self.is_set(ArgSettings::RequireDelimiter) { + self.v.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }); + if let Some(ref names) = self.v.val_names { + write!( + f, + "{}", + names + .values() + .map(|n| format!("<{}>", n)) + .collect::>() + .join(&*delim) + )?; + } else { + write!(f, "<{}>", self.b.name)?; + } + if self.b.settings.is_set(ArgSettings::Multiple) + && (self.v.val_names.is_none() || self.v.val_names.as_ref().unwrap().len() == 1) + { + write!(f, "...")?; + } + + Ok(()) + } +} + +impl<'n, 'e> AnyArg<'n, 'e> for PosBuilder<'n, 'e> { + fn name(&self) -> &'n str { + self.b.name + } + fn overrides(&self) -> Option<&[&'e str]> { + self.b.overrides.as_ref().map(|o| &o[..]) + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + self.b.requires.as_ref().map(|o| &o[..]) + } + fn blacklist(&self) -> Option<&[&'e str]> { + self.b.blacklist.as_ref().map(|o| &o[..]) + } + fn required_unless(&self) -> Option<&[&'e str]> { + self.b.r_unless.as_ref().map(|o| &o[..]) + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + self.v.val_names.as_ref() + } + fn is_set(&self, s: ArgSettings) -> bool { + self.b.settings.is_set(s) + } + fn set(&mut self, s: ArgSettings) { + self.b.settings.set(s) + } + fn has_switch(&self) -> bool { + false + } + fn max_vals(&self) -> Option { + self.v.max_vals + } + fn val_terminator(&self) -> Option<&'e str> { + self.v.terminator + } + fn num_vals(&self) -> Option { + self.v.num_vals + } + fn possible_vals(&self) -> Option<&[&'e str]> { + self.v.possible_vals.as_ref().map(|o| &o[..]) + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator(&self) -> Option<&Rc StdResult<(), String>>> { + self.v.validator.as_ref() + } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { + self.v.validator_os.as_ref() + } + fn min_vals(&self) -> Option { + self.v.min_vals + } + fn short(&self) -> Option { + None + } + fn long(&self) -> Option<&'e str> { + None + } + fn val_delim(&self) -> Option { + self.v.val_delim + } + fn takes_value(&self) -> bool { + true + } + fn help(&self) -> Option<&'e str> { + self.b.help + } + fn long_help(&self) -> Option<&'e str> { + self.b.long_help + } + fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { + self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) + } + fn default_val(&self) -> Option<&'e OsStr> { + self.v.default_val + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + self.v + .env + .as_ref() + .map(|&(key, ref value)| (key, value.as_ref())) + } + fn longest_filter(&self) -> bool { + true + } + fn aliases(&self) -> Option> { + None + } +} + +impl<'n, 'e> DispOrder for PosBuilder<'n, 'e> { + fn disp_ord(&self) -> usize { + self.index as usize + } +} + +impl<'n, 'e> PartialEq for PosBuilder<'n, 'e> { + fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool { + self.b == other.b + } +} + +#[cfg(test)] +mod test { + use super::PosBuilder; + use crate::{args::settings::ArgSettings, map::VecMap}; + + #[test] + fn display_mult() { + let mut p = PosBuilder::new("pos", 1); + p.b.settings.set(ArgSettings::Multiple); + + assert_eq!(&*format!("{}", p), "..."); + } + + #[test] + fn display_required() { + let mut p2 = PosBuilder::new("pos", 1); + p2.b.settings.set(ArgSettings::Required); + + assert_eq!(&*format!("{}", p2), ""); + } + + #[test] + fn display_val_names() { + let mut p2 = PosBuilder::new("pos", 1); + let mut vm = VecMap::new(); + vm.insert(0, "file1"); + vm.insert(1, "file2"); + p2.v.val_names = Some(vm); + + assert_eq!(&*format!("{}", p2), " "); + } + + #[test] + fn display_val_names_req() { + let mut p2 = PosBuilder::new("pos", 1); + p2.b.settings.set(ArgSettings::Required); + let mut vm = VecMap::new(); + vm.insert(0, "file1"); + vm.insert(1, "file2"); + p2.v.val_names = Some(vm); + + assert_eq!(&*format!("{}", p2), " "); + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/switched.rs b/bash-5.1/vendor/clap/src/args/arg_builder/switched.rs new file mode 100644 index 0000000..78af669 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/switched.rs @@ -0,0 +1,40 @@ +use crate::Arg; + +#[derive(Debug)] +pub struct Switched<'b> { + pub short: Option, + pub long: Option<&'b str>, + pub aliases: Option>, // (name, visible) + pub disp_ord: usize, + pub unified_ord: usize, +} + +impl<'e> Default for Switched<'e> { + fn default() -> Self { + Switched { + short: None, + long: None, + aliases: None, + disp_ord: 999, + unified_ord: 999, + } + } +} + +impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Switched<'e> { + fn from(a: &'z Arg<'n, 'e>) -> Self { + a.s.clone() + } +} + +impl<'e> Clone for Switched<'e> { + fn clone(&self) -> Self { + Switched { + short: self.short, + long: self.long, + aliases: self.aliases.clone(), + disp_ord: self.disp_ord, + unified_ord: self.unified_ord, + } + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_builder/valued.rs b/bash-5.1/vendor/clap/src/args/arg_builder/valued.rs new file mode 100644 index 0000000..ae659f7 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_builder/valued.rs @@ -0,0 +1,70 @@ +use std::{ + ffi::{OsStr, OsString}, + rc::Rc, +}; + +use crate::{map::VecMap, Arg}; + +#[allow(missing_debug_implementations)] +#[derive(Clone)] +pub struct Valued<'a, 'b> +where + 'a: 'b, +{ + pub possible_vals: Option>, + pub val_names: Option>, + pub num_vals: Option, + pub max_vals: Option, + pub min_vals: Option, + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + pub validator: Option Result<(), String>>>, + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + pub validator_os: Option Result<(), OsString>>>, + pub val_delim: Option, + pub default_val: Option<&'b OsStr>, + #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] + pub default_vals_ifs: Option, &'b OsStr)>>, + pub env: Option<(&'a OsStr, Option)>, + pub terminator: Option<&'b str>, +} + +impl<'n, 'e> Default for Valued<'n, 'e> { + fn default() -> Self { + Valued { + possible_vals: None, + num_vals: None, + min_vals: None, + max_vals: None, + val_names: None, + validator: None, + validator_os: None, + val_delim: None, + default_val: None, + default_vals_ifs: None, + env: None, + terminator: None, + } + } +} + +impl<'n, 'e> Valued<'n, 'e> { + pub fn fill_in(&mut self) { + if let Some(ref vec) = self.val_names { + if vec.len() > 1 { + self.num_vals = Some(vec.len() as u64); + } + } + } +} + +impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Valued<'n, 'e> { + fn from(a: &'z Arg<'n, 'e>) -> Self { + let mut v = a.v.clone(); + if let Some(ref vec) = a.v.val_names { + if vec.len() > 1 { + v.num_vals = Some(vec.len() as u64); + } + } + v + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_matcher.rs b/bash-5.1/vendor/clap/src/args/arg_matcher.rs new file mode 100644 index 0000000..5034dcc --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_matcher.rs @@ -0,0 +1,274 @@ +// Std +use std::{ + collections::{ + hash_map::{Entry, Iter}, + HashMap, + }, + ffi::OsStr, + mem, + ops::Deref, +}; + +// Internal +use crate::args::{settings::ArgSettings, AnyArg, ArgMatches, MatchedArg, SubCommand}; + +#[doc(hidden)] +#[allow(missing_debug_implementations)] +pub struct ArgMatcher<'a>(pub ArgMatches<'a>); + +impl<'a> Default for ArgMatcher<'a> { + fn default() -> Self { + ArgMatcher(ArgMatches::default()) + } +} + +impl<'a> ArgMatcher<'a> { + pub fn new() -> Self { + ArgMatcher::default() + } + + pub fn process_arg_overrides<'b>( + &mut self, + a: Option<&AnyArg<'a, 'b>>, + overrides: &mut Vec<(&'b str, &'a str)>, + required: &mut Vec<&'a str>, + check_all: bool, + ) { + debugln!( + "ArgMatcher::process_arg_overrides:{:?};", + a.map_or(None, |a| Some(a.name())) + ); + if let Some(aa) = a { + let mut self_done = false; + if let Some(a_overrides) = aa.overrides() { + for overr in a_overrides { + debugln!("ArgMatcher::process_arg_overrides:iter:{};", overr); + if overr == &aa.name() { + self_done = true; + self.handle_self_overrides(a); + } else if self.is_present(overr) { + debugln!( + "ArgMatcher::process_arg_overrides:iter:{}: removing from matches;", + overr + ); + self.remove(overr); + for i in (0..required.len()).rev() { + if &required[i] == overr { + debugln!( + "ArgMatcher::process_arg_overrides:iter:{}: removing required;", + overr + ); + required.swap_remove(i); + break; + } + } + overrides.push((overr, aa.name())); + } else { + overrides.push((overr, aa.name())); + } + } + } + if check_all && !self_done { + self.handle_self_overrides(a); + } + } + } + + pub fn handle_self_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>) { + debugln!( + "ArgMatcher::handle_self_overrides:{:?};", + a.map_or(None, |a| Some(a.name())) + ); + if let Some(aa) = a { + if !aa.has_switch() || aa.is_set(ArgSettings::Multiple) { + // positional args can't override self or else we would never advance to the next + + // Also flags with --multiple set are ignored otherwise we could never have more + // than one + return; + } + if let Some(ma) = self.get_mut(aa.name()) { + if ma.vals.len() > 1 { + // swap_remove(0) would be O(1) but does not preserve order, which + // we need + ma.vals.remove(0); + ma.occurs = 1; + } else if !aa.takes_value() && ma.occurs > 1 { + ma.occurs = 1; + } + } + } + } + + pub fn is_present(&self, name: &str) -> bool { + self.0.is_present(name) + } + + pub fn propagate_globals(&mut self, global_arg_vec: &[&'a str]) { + debugln!( + "ArgMatcher::get_global_values: global_arg_vec={:?}", + global_arg_vec + ); + let mut vals_map = HashMap::new(); + self.fill_in_global_values(global_arg_vec, &mut vals_map); + } + + fn fill_in_global_values( + &mut self, + global_arg_vec: &[&'a str], + vals_map: &mut HashMap<&'a str, MatchedArg>, + ) { + for global_arg in global_arg_vec { + if let Some(ma) = self.get(global_arg) { + // We have to check if the parent's global arg wasn't used but still exists + // such as from a default value. + // + // For example, `myprog subcommand --global-arg=value` where --global-arg defines + // a default value of `other` myprog would have an existing MatchedArg for + // --global-arg where the value is `other`, however the occurs will be 0. + let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { + if parent_ma.occurs > 0 && ma.occurs == 0 { + parent_ma.clone() + } else { + ma.clone() + } + } else { + ma.clone() + }; + vals_map.insert(global_arg, to_update); + } + } + if let Some(ref mut sc) = self.0.subcommand { + let mut am = ArgMatcher(mem::replace(&mut sc.matches, ArgMatches::new())); + am.fill_in_global_values(global_arg_vec, vals_map); + mem::swap(&mut am.0, &mut sc.matches); + } + + for (name, matched_arg) in vals_map.iter_mut() { + self.0.args.insert(name, matched_arg.clone()); + } + } + + pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> { + self.0.args.get_mut(arg) + } + + pub fn get(&self, arg: &str) -> Option<&MatchedArg> { + self.0.args.get(arg) + } + + pub fn remove(&mut self, arg: &str) { + self.0.args.remove(arg); + } + + pub fn remove_all(&mut self, args: &[&str]) { + for &arg in args { + self.0.args.remove(arg); + } + } + + pub fn insert(&mut self, name: &'a str) { + self.0.args.insert(name, MatchedArg::new()); + } + + pub fn contains(&self, arg: &str) -> bool { + self.0.args.contains_key(arg) + } + + pub fn is_empty(&self) -> bool { + self.0.args.is_empty() + } + + pub fn usage(&mut self, usage: String) { + self.0.usage = Some(usage); + } + + pub fn arg_names(&'a self) -> Vec<&'a str> { + self.0.args.keys().map(Deref::deref).collect() + } + + pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> { + self.0.args.entry(arg) + } + + pub fn subcommand(&mut self, sc: SubCommand<'a>) { + self.0.subcommand = Some(Box::new(sc)); + } + + pub fn subcommand_name(&self) -> Option<&str> { + self.0.subcommand_name() + } + + pub fn iter(&self) -> Iter<&str, MatchedArg> { + self.0.args.iter() + } + + pub fn inc_occurrence_of(&mut self, arg: &'a str) { + debugln!("ArgMatcher::inc_occurrence_of: arg={}", arg); + if let Some(a) = self.get_mut(arg) { + a.occurs += 1; + return; + } + debugln!("ArgMatcher::inc_occurrence_of: first instance"); + self.insert(arg); + } + + pub fn inc_occurrences_of(&mut self, args: &[&'a str]) { + debugln!("ArgMatcher::inc_occurrences_of: args={:?}", args); + for arg in args { + self.inc_occurrence_of(arg); + } + } + + pub fn add_val_to(&mut self, arg: &'a str, val: &OsStr) { + let ma = self.entry(arg).or_insert(MatchedArg { + occurs: 0, + indices: Vec::with_capacity(1), + vals: Vec::with_capacity(1), + }); + ma.vals.push(val.to_owned()); + } + + pub fn add_index_to(&mut self, arg: &'a str, idx: usize) { + let ma = self.entry(arg).or_insert(MatchedArg { + occurs: 0, + indices: Vec::with_capacity(1), + vals: Vec::new(), + }); + ma.indices.push(idx); + } + + pub fn needs_more_vals<'b, A>(&self, o: &A) -> bool + where + A: AnyArg<'a, 'b>, + { + debugln!("ArgMatcher::needs_more_vals: o={}", o.name()); + if let Some(ma) = self.get(o.name()) { + if let Some(num) = o.num_vals() { + debugln!("ArgMatcher::needs_more_vals: num_vals...{}", num); + return if o.is_set(ArgSettings::Multiple) { + ((ma.vals.len() as u64) % num) != 0 + } else { + num != (ma.vals.len() as u64) + }; + } else if let Some(num) = o.max_vals() { + debugln!("ArgMatcher::needs_more_vals: max_vals...{}", num); + return (ma.vals.len() as u64) <= num; + } else if o.min_vals().is_some() { + debugln!("ArgMatcher::needs_more_vals: min_vals...true"); + return true; + } + return o.is_set(ArgSettings::Multiple); + } + true + } +} + +// Not changing to From just to not deal with possible breaking changes on v2 since v3 is coming +// in the future anyways +#[cfg_attr(feature = "cargo-clippy", allow(clippy::from_over_into))] +impl<'a> Into> for ArgMatcher<'a> { + fn into(self) -> ArgMatches<'a> { + self.0 + } +} diff --git a/bash-5.1/vendor/clap/src/args/arg_matches.rs b/bash-5.1/vendor/clap/src/args/arg_matches.rs new file mode 100644 index 0000000..a2c3231 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/arg_matches.rs @@ -0,0 +1,1001 @@ +// Std +use std::{ + borrow::Cow, + collections::HashMap, + ffi::{OsStr, OsString}, + iter::Map, + slice::Iter, +}; + +// Internal +use crate::{ + args::{MatchedArg, SubCommand}, + INVALID_UTF8, +}; + +/// Used to get information about the arguments that were supplied to the program at runtime by +/// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of +/// methods. +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{App, Arg}; +/// let matches = App::new("MyApp") +/// .arg(Arg::with_name("out") +/// .long("output") +/// .required(true) +/// .takes_value(true)) +/// .arg(Arg::with_name("debug") +/// .short("d") +/// .multiple(true)) +/// .arg(Arg::with_name("cfg") +/// .short("c") +/// .takes_value(true)) +/// .get_matches(); // builds the instance of ArgMatches +/// +/// // to get information about the "cfg" argument we created, such as the value supplied we use +/// // various ArgMatches methods, such as ArgMatches::value_of +/// if let Some(c) = matches.value_of("cfg") { +/// println!("Value for -c: {}", c); +/// } +/// +/// // The ArgMatches::value_of method returns an Option because the user may not have supplied +/// // that argument at runtime. But if we specified that the argument was "required" as we did +/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually +/// // used at runtime. +/// println!("Value for --output: {}", matches.value_of("out").unwrap()); +/// +/// // You can check the presence of an argument +/// if matches.is_present("out") { +/// // Another way to check if an argument was present, or if it occurred multiple times is to +/// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the +/// // number of times that it occurred, if it was. To allow an argument to appear more than +/// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0. +/// if matches.occurrences_of("debug") > 2 { +/// println!("Debug mode is REALLY on, don't be crazy"); +/// } else { +/// println!("Debug mode kind of on"); +/// } +/// } +/// ``` +/// [`App::get_matches`]: ./struct.App.html#method.get_matches +#[derive(Debug, Clone)] +pub struct ArgMatches<'a> { + #[doc(hidden)] + pub args: HashMap<&'a str, MatchedArg>, + #[doc(hidden)] + pub subcommand: Option>>, + #[doc(hidden)] + pub usage: Option, +} + +impl<'a> Default for ArgMatches<'a> { + fn default() -> Self { + ArgMatches { + args: HashMap::new(), + subcommand: None, + usage: None, + } + } +} + +impl<'a> ArgMatches<'a> { + #[doc(hidden)] + pub fn new() -> Self { + ArgMatches { + ..Default::default() + } + } + + /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes + /// an additional value at runtime). If the option wasn't present at runtime + /// it returns `None`. + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first* + /// value. + /// + /// # Panics + /// + /// This method will [`panic!`] if the value contains invalid UTF-8 code points. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("output") + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "something"]); + /// + /// assert_eq!(m.value_of("output"), Some("something")); + /// ``` + /// [option]: ./struct.Arg.html#method.takes_value + /// [positional]: ./struct.Arg.html#method.index + /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of + /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html + pub fn value_of>(&self, name: S) -> Option<&str> { + if let Some(arg) = self.args.get(name.as_ref()) { + if let Some(v) = arg.vals.get(0) { + return Some(v.to_str().expect(INVALID_UTF8)); + } + } + None + } + + /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime + /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those + /// invalid points will be replaced with `\u{FFFD}` + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, Arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = App::new("utf8") + /// .arg(Arg::from_usage(" 'some arg'")) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi {0xe9}!" + /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); + /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!"); + /// ``` + /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy + pub fn value_of_lossy>(&'a self, name: S) -> Option> { + if let Some(arg) = self.args.get(name.as_ref()) { + if let Some(v) = arg.vals.get(0) { + return Some(v.to_string_lossy()); + } + } + None + } + + /// Gets the OS version of a string value of a specific argument. If the option wasn't present + /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes, + /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in + /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument + /// value may contain invalid UTF-8 code points. + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first* + /// value. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, Arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = App::new("utf8") + /// .arg(Arg::from_usage(" 'some arg'")) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi {0xe9}!" + /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); + /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); + /// ``` + /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html + /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os + pub fn value_of_os>(&self, name: S) -> Option<&OsStr> { + self.args + .get(name.as_ref()) + .and_then(|arg| arg.vals.get(0).map(|v| v.as_os_str())) + } + + /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument + /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at + /// runtime it returns `None` + /// + /// # Panics + /// + /// This method will panic if any of the values contain invalid UTF-8 code points. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("output") + /// .multiple(true) + /// .short("o") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "myprog", "-o", "val1", "val2", "val3" + /// ]); + /// let vals: Vec<&str> = m.values_of("output").unwrap().collect(); + /// assert_eq!(vals, ["val1", "val2", "val3"]); + /// ``` + /// [`Values`]: ./struct.Values.html + /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html + pub fn values_of>(&'a self, name: S) -> Option> { + if let Some(arg) = self.args.get(name.as_ref()) { + fn to_str_slice(o: &OsString) -> &str { + o.to_str().expect(INVALID_UTF8) + } + let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer + return Some(Values { + iter: arg.vals.iter().map(to_str_slice), + }); + } + None + } + + /// Gets the lossy values of a specific argument. If the option wasn't present at runtime + /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points, + /// those invalid points will be replaced with `\u{FFFD}` + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, Arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::OsStringExt; + /// + /// let m = App::new("utf8") + /// .arg(Arg::from_usage("... 'some arg'")) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi" + /// OsString::from_vec(vec![b'H', b'i']), + /// // "{0xe9}!" + /// OsString::from_vec(vec![0xe9, b'!'])]); + /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter(); + /// assert_eq!(&itr.next().unwrap()[..], "Hi"); + /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!"); + /// assert_eq!(itr.next(), None); + /// ``` + pub fn values_of_lossy>(&'a self, name: S) -> Option> { + if let Some(arg) = self.args.get(name.as_ref()) { + return Some( + arg.vals + .iter() + .map(|v| v.to_string_lossy().into_owned()) + .collect(), + ); + } + None + } + + /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a + /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value + /// on Unix-like systems is any series of bytes, regardless of whether or not they contain + /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid + /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, Arg}; + /// use std::ffi::{OsStr,OsString}; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = App::new("utf8") + /// .arg(Arg::from_usage("... 'some arg'")) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi" + /// OsString::from_vec(vec![b'H', b'i']), + /// // "{0xe9}!" + /// OsString::from_vec(vec![0xe9, b'!'])]); + /// + /// let mut itr = m.values_of_os("arg").unwrap().into_iter(); + /// assert_eq!(itr.next(), Some(OsStr::new("Hi"))); + /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); + /// assert_eq!(itr.next(), None); + /// ``` + /// [`OsValues`]: ./struct.OsValues.html + /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html + /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html + /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html + pub fn values_of_os>(&'a self, name: S) -> Option> { + fn to_str_slice(o: &OsString) -> &OsStr { + &*o + } + let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer + if let Some(arg) = self.args.get(name.as_ref()) { + return Some(OsValues { + iter: arg.vals.iter().map(to_str_slice), + }); + } + None + } + + /// Returns `true` if an argument was present at runtime, otherwise `false`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("debug") + /// .short("d")) + /// .get_matches_from(vec![ + /// "myprog", "-d" + /// ]); + /// + /// assert!(m.is_present("debug")); + /// ``` + pub fn is_present>(&self, name: S) -> bool { + if let Some(ref sc) = self.subcommand { + if sc.name == name.as_ref() { + return true; + } + } + self.args.contains_key(name.as_ref()) + } + + /// Returns the number of times an argument was used at runtime. If an argument isn't present + /// it will return `0`. + /// + /// **NOTE:** This returns the number of times the argument was used, *not* the number of + /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4 + /// values). + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("debug") + /// .short("d") + /// .multiple(true)) + /// .get_matches_from(vec![ + /// "myprog", "-d", "-d", "-d" + /// ]); + /// + /// assert_eq!(m.occurrences_of("debug"), 3); + /// ``` + /// + /// This next example shows that counts actual uses of the argument, not just `-`'s + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("debug") + /// .short("d") + /// .multiple(true)) + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .get_matches_from(vec![ + /// "myprog", "-ddfd" + /// ]); + /// + /// assert_eq!(m.occurrences_of("debug"), 3); + /// assert_eq!(m.occurrences_of("flag"), 1); + /// ``` + pub fn occurrences_of>(&self, name: S) -> u64 { + self.args.get(name.as_ref()).map_or(0, |a| a.occurs) + } + + /// Gets the starting index of the argument in respect to all other arguments. Indices are + /// similar to argv indices, but are not exactly 1:1. + /// + /// For flags (i.e. those arguments which don't have an associated value), indices refer + /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices + /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the + /// index for `val` would be recorded. This is by design. + /// + /// Besides the flag/option descrepancy, the primary difference between an argv index and clap + /// index, is that clap continues counting once all arguments have properly seperated, whereas + /// an argv index does not. + /// + /// The examples should clear this up. + /// + /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first* + /// index. + /// + /// # Examples + /// + /// The argv indices are listed in the comments below. See how they correspond to the clap + /// indices. Note that if it's not listed in a clap index, this is becuase it's not saved in + /// in an `ArgMatches` struct for querying. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); + /// // ARGV idices: ^0 ^1 ^2 ^3 + /// // clap idices: ^1 ^3 + /// + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("option"), Some(3)); + /// ``` + /// + /// Now notice, if we use one of the other styles of options: + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); + /// // ARGV idices: ^0 ^1 ^2 + /// // clap idices: ^1 ^3 + /// + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("option"), Some(3)); + /// ``` + /// + /// Things become much more complicated, or clear if we look at a more complex combination of + /// flags. Let's also throw in the final option style for good measure. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("flag2") + /// .short("F")) + /// .arg(Arg::with_name("flag3") + /// .short("z")) + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); + /// // ARGV idices: ^0 ^1 ^2 + /// // clap idices: ^1,2,3 ^5 + /// // + /// // clap sees the above as 'myapp -f -z -F -o val' + /// // ^0 ^1 ^2 ^3 ^4 ^5 + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("flag2"), Some(3)); + /// assert_eq!(m.index_of("flag3"), Some(2)); + /// assert_eq!(m.index_of("option"), Some(5)); + /// ``` + /// + /// One final combination of flags/options to see how they combine: + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("flag2") + /// .short("F")) + /// .arg(Arg::with_name("flag3") + /// .short("z")) + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true) + /// .multiple(true)) + /// .get_matches_from(vec!["myapp", "-fzFoval"]); + /// // ARGV idices: ^0 ^1 + /// // clap idices: ^1,2,3^5 + /// // + /// // clap sees the above as 'myapp -f -z -F -o val' + /// // ^0 ^1 ^2 ^3 ^4 ^5 + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("flag2"), Some(3)); + /// assert_eq!(m.index_of("flag3"), Some(2)); + /// assert_eq!(m.index_of("option"), Some(5)); + /// ``` + /// + /// The last part to mention is when values are sent in multiple groups with a [delimiter]. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true) + /// .multiple(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV idices: ^0 ^1 + /// // clap idices: ^2 ^3 ^4 + /// // + /// // clap sees the above as 'myapp -o val1 val2 val3' + /// // ^0 ^1 ^2 ^3 ^4 + /// assert_eq!(m.index_of("option"), Some(2)); + /// ``` + /// [`ArgMatches`]: ./struct.ArgMatches.html + /// [delimiter]: ./struct.Arg.html#method.value_delimiter + pub fn index_of>(&self, name: S) -> Option { + if let Some(arg) = self.args.get(name.as_ref()) { + if let Some(i) = arg.indices.get(0) { + return Some(*i); + } + } + None + } + + /// Gets all indices of the argument in respect to all other arguments. Indices are + /// similar to argv indices, but are not exactly 1:1. + /// + /// For flags (i.e. those arguments which don't have an associated value), indices refer + /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices + /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the + /// index for `val` would be recorded. This is by design. + /// + /// *NOTE:* For more information about how clap indices compare to argv indices, see + /// [`ArgMatches::index_of`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true) + /// .use_delimiter(true) + /// .multiple(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV idices: ^0 ^1 + /// // clap idices: ^2 ^3 ^4 + /// // + /// // clap sees the above as 'myapp -o val1 val2 val3' + /// // ^0 ^1 ^2 ^3 ^4 + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 3, 4]); + /// ``` + /// + /// Another quick example is when flags and options are used together + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true) + /// .multiple(true)) + /// .arg(Arg::with_name("flag") + /// .short("f") + /// .multiple(true)) + /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); + /// // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 + /// // clap idices: ^2 ^3 ^5 ^6 + /// + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 5]); + /// assert_eq!(m.indices_of("flag").unwrap().collect::>(), &[3, 6]); + /// ``` + /// + /// One final example, which is an odd case; if we *don't* use value delimiter as we did with + /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they + /// would all be a single value of `val1,val2,val3`, in which case case they'd only receive a + /// single index. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::with_name("option") + /// .short("o") + /// .takes_value(true) + /// .multiple(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV idices: ^0 ^1 + /// // clap idices: ^2 + /// // + /// // clap sees the above as 'myapp -o "val1,val2,val3"' + /// // ^0 ^1 ^2 + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2]); + /// ``` + /// [`ArgMatches`]: ./struct.ArgMatches.html + /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of + /// [delimiter]: ./struct.Arg.html#method.value_delimiter + pub fn indices_of>(&'a self, name: S) -> Option> { + if let Some(arg) = self.args.get(name.as_ref()) { + fn to_usize(i: &usize) -> usize { + *i + } + let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer + return Some(Indices { + iter: arg.indices.iter().map(to_usize), + }); + } + None + } + + /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`] + /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if + /// the subcommand wasn't present at runtime. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// let app_m = App::new("myprog") + /// .arg(Arg::with_name("debug") + /// .short("d")) + /// .subcommand(SubCommand::with_name("test") + /// .arg(Arg::with_name("opt") + /// .long("option") + /// .takes_value(true))) + /// .get_matches_from(vec![ + /// "myprog", "-d", "test", "--option", "val" + /// ]); + /// + /// // Both parent commands, and child subcommands can have arguments present at the same times + /// assert!(app_m.is_present("debug")); + /// + /// // Get the subcommand's ArgMatches instance + /// if let Some(sub_m) = app_m.subcommand_matches("test") { + /// // Use the struct like normal + /// assert_eq!(sub_m.value_of("opt"), Some("val")); + /// } + /// ``` + /// [`Subcommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + /// [`ArgMatches`]: ./struct.ArgMatches.html + pub fn subcommand_matches>(&self, name: S) -> Option<&ArgMatches<'a>> { + if let Some(ref s) = self.subcommand { + if s.name == name.as_ref() { + return Some(&s.matches); + } + } + None + } + + /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`] + /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know + /// which subcommand was actually used. This method returns the name of the subcommand that was + /// used at runtime, or `None` if one wasn't. + /// + /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime, + /// but only a single subcommand from any group of sibling commands may used at once. + /// + /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as + /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is + /// aware these aren't actually all subcommands in the real `git` interface, but it makes + /// explanation easier) + /// + /// ```notrust + /// Top Level App (git) TOP + /// | + /// ----------------------------------------- + /// / | \ \ + /// clone push add commit LEVEL 1 + /// | / \ / \ | + /// url origin remote ref name message LEVEL 2 + /// / /\ + /// path remote local LEVEL 3 + /// ``` + /// + /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all + /// inclusive list, and not including argument options per command for brevity and clarity): + /// + /// ```sh + /// $ git clone url + /// $ git push origin path + /// $ git add ref local + /// $ git commit message + /// ``` + /// + /// Notice only one command per "level" may be used. You could not, for example, do `$ git + /// clone url push origin path` + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let app_m = App::new("git") + /// .subcommand(SubCommand::with_name("clone")) + /// .subcommand(SubCommand::with_name("push")) + /// .subcommand(SubCommand::with_name("commit")) + /// .get_matches(); + /// + /// match app_m.subcommand_name() { + /// Some("clone") => {}, // clone was used + /// Some("push") => {}, // push was used + /// Some("commit") => {}, // commit was used + /// _ => {}, // Either no subcommand or one not tested for... + /// } + /// ``` + /// [`Subcommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + /// [`ArgMatches`]: ./struct.ArgMatches.html + pub fn subcommand_name(&self) -> Option<&str> { + self.subcommand.as_ref().map(|sc| &sc.name[..]) + } + + /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`] + /// by returning a tuple with both pieces of information. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let app_m = App::new("git") + /// .subcommand(SubCommand::with_name("clone")) + /// .subcommand(SubCommand::with_name("push")) + /// .subcommand(SubCommand::with_name("commit")) + /// .get_matches(); + /// + /// match app_m.subcommand() { + /// ("clone", Some(sub_m)) => {}, // clone was used + /// ("push", Some(sub_m)) => {}, // push was used + /// ("commit", Some(sub_m)) => {}, // commit was used + /// _ => {}, // Either no subcommand or one not tested for... + /// } + /// ``` + /// + /// Another useful scenario is when you want to support third party, or external, subcommands. + /// In these cases you can't know the subcommand name ahead of time, so use a variable instead + /// with pattern matching! + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let app_m = App::new("myprog") + /// .setting(AppSettings::AllowExternalSubcommands) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match app_m.subcommand() { + /// (external, Some(sub_m)) => { + /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches + /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name + pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) { + self.subcommand + .as_ref() + .map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches))) + } + + /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let app_m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches(); + /// + /// println!("{}", app_m.usage()); + /// ``` + /// [`Subcommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + pub fn usage(&self) -> &str { + self.usage.as_ref().map_or("", |u| &u[..]) + } +} + +// The following were taken and adapated from vec_map source +// repo: https://github.com/contain-rs/vec-map +// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 +// license: MIT - Copyright (c) 2015 The Rust Project Developers + +/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`] +/// method. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{App, Arg}; +/// let m = App::new("myapp") +/// .arg(Arg::with_name("output") +/// .short("o") +/// .multiple(true) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); +/// +/// let mut values = m.values_of("output").unwrap(); +/// +/// assert_eq!(values.next(), Some("val1")); +/// assert_eq!(values.next(), Some("val2")); +/// assert_eq!(values.next(), None); +/// ``` +/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of +#[derive(Debug, Clone)] +pub struct Values<'a> { + iter: Map, fn(&'a OsString) -> &'a str>, +} + +impl<'a> Iterator for Values<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a> DoubleEndedIterator for Values<'a> { + fn next_back(&mut self) -> Option<&'a str> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for Values<'a> {} + +/// Creates an empty iterator. +impl<'a> Default for Values<'a> { + fn default() -> Self { + static EMPTY: [OsString; 0] = []; + // This is never called because the iterator is empty: + fn to_str_slice(_: &OsString) -> &str { + unreachable!() + } + Values { + iter: EMPTY[..].iter().map(to_str_slice), + } + } +} + +/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`] +/// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike +/// [`Values`]. +/// +/// # Examples +/// +#[cfg_attr(not(unix), doc = " ```ignore")] +#[cfg_attr(unix, doc = " ```")] +/// # use clap::{App, Arg}; +/// use std::ffi::OsString; +/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; +/// +/// let m = App::new("utf8") +/// .arg(Arg::from_usage(" 'some arg'")) +/// .get_matches_from(vec![OsString::from("myprog"), +/// // "Hi {0xe9}!" +/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); +/// ``` +/// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os +/// [`Values`]: ./struct.Values.html +#[derive(Debug, Clone)] +pub struct OsValues<'a> { + iter: Map, fn(&'a OsString) -> &'a OsStr>, +} + +impl<'a> Iterator for OsValues<'a> { + type Item = &'a OsStr; + + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a> DoubleEndedIterator for OsValues<'a> { + fn next_back(&mut self) -> Option<&'a OsStr> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for OsValues<'a> {} + +/// Creates an empty iterator. +impl<'a> Default for OsValues<'a> { + fn default() -> Self { + static EMPTY: [OsString; 0] = []; + // This is never called because the iterator is empty: + fn to_str_slice(_: &OsString) -> &OsStr { + unreachable!() + } + OsValues { + iter: EMPTY[..].iter().map(to_str_slice), + } + } +} + +/// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`] +/// method. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{App, Arg}; +/// let m = App::new("myapp") +/// .arg(Arg::with_name("output") +/// .short("o") +/// .multiple(true) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); +/// +/// let mut indices = m.indices_of("output").unwrap(); +/// +/// assert_eq!(indices.next(), Some(2)); +/// assert_eq!(indices.next(), Some(3)); +/// assert_eq!(indices.next(), None); +/// ``` +/// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of +#[derive(Debug, Clone)] +pub struct Indices<'a> { + // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469 + iter: Map, fn(&'a usize) -> usize>, +} + +impl<'a> Iterator for Indices<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a> DoubleEndedIterator for Indices<'a> { + fn next_back(&mut self) -> Option { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for Indices<'a> {} + +/// Creates an empty iterator. +impl<'a> Default for Indices<'a> { + fn default() -> Self { + static EMPTY: [usize; 0] = []; + // This is never called because the iterator is empty: + fn to_usize(_: &usize) -> usize { + unreachable!() + } + Indices { + iter: EMPTY[..].iter().map(to_usize), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_default_values() { + let mut values: Values = Values::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_values_with_shorter_lifetime() { + let matches = ArgMatches::new(); + let mut values = matches.values_of("").unwrap_or_default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues() { + let mut values: OsValues = OsValues::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues_with_shorter_lifetime() { + let matches = ArgMatches::new(); + let mut values = matches.values_of_os("").unwrap_or_default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_indices() { + let mut indices: Indices = Indices::default(); + assert_eq!(indices.next(), None); + } + + #[test] + fn test_default_indices_with_shorter_lifetime() { + let matches = ArgMatches::new(); + let mut indices = matches.indices_of("").unwrap_or_default(); + assert_eq!(indices.next(), None); + } +} diff --git a/bash-5.1/vendor/clap/src/args/group.rs b/bash-5.1/vendor/clap/src/args/group.rs new file mode 100644 index 0000000..a2992b2 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/group.rs @@ -0,0 +1,637 @@ +#[cfg(feature = "yaml")] +use std::collections::BTreeMap; +use std::fmt::{Debug, Formatter, Result}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +/// `ArgGroup`s are a family of related [arguments] and way for you to express, "Any of these +/// arguments". By placing arguments in a logical group, you can create easier requirement and +/// exclusion rules instead of having to list each argument individually, or when you want a rule +/// to apply "any but not all" arguments. +/// +/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is +/// set, this means that at least one argument from that group must be present. If +/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. +/// +/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for +/// another argument, meaning any of the arguments that belong to that group will cause a failure +/// if present, or must present respectively. +/// +/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be +/// present out of a given set. Imagine that you had multiple arguments, and you want one of them +/// to be required, but making all of them required isn't feasible because perhaps they conflict +/// with each other. For example, lets say that you were building an application where one could +/// set a given version number by supplying a string with an option argument, i.e. +/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number +/// and simply incrementing one of the three numbers. So you create three flags `--major`, +/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to +/// specify that *at least one* of them is used. For this, you can create a group. +/// +/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care +/// exactly which argument was actually used at runtime. +/// +/// # Examples +/// +/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of +/// the arguments from the specified group is present at runtime. +/// +/// ```rust +/// # use clap::{App, ArgGroup, ErrorKind}; +/// let result = App::new("app") +/// .args_from_usage( +/// "--set-ver [ver] 'set the version manually' +/// --major 'auto increase major' +/// --minor 'auto increase minor' +/// --patch 'auto increase patch'") +/// .group(ArgGroup::with_name("vers") +/// .args(&["set-ver", "major", "minor", "patch"]) +/// .required(true)) +/// .get_matches_from_safe(vec!["app", "--major", "--patch"]); +/// // Because we used two args in the group it's an error +/// assert!(result.is_err()); +/// let err = result.unwrap_err(); +/// assert_eq!(err.kind, ErrorKind::ArgumentConflict); +/// ``` +/// This next example shows a passing parse of the same scenario +/// +/// ```rust +/// # use clap::{App, ArgGroup}; +/// let result = App::new("app") +/// .args_from_usage( +/// "--set-ver [ver] 'set the version manually' +/// --major 'auto increase major' +/// --minor 'auto increase minor' +/// --patch 'auto increase patch'") +/// .group(ArgGroup::with_name("vers") +/// .args(&["set-ver", "major", "minor","patch"]) +/// .required(true)) +/// .get_matches_from_safe(vec!["app", "--major"]); +/// assert!(result.is_ok()); +/// let matches = result.unwrap(); +/// // We may not know which of the args was used, so we can test for the group... +/// assert!(matches.is_present("vers")); +/// // we could also alternatively check each arg individually (not shown here) +/// ``` +/// [`ArgGroup::multiple(true)`]: ./struct.ArgGroup.html#method.multiple +/// [arguments]: ./struct.Arg.html +/// [conflict]: ./struct.Arg.html#method.conflicts_with +/// [requirement]: ./struct.Arg.html#method.requires +#[derive(Default)] +pub struct ArgGroup<'a> { + #[doc(hidden)] + pub name: &'a str, + #[doc(hidden)] + pub args: Vec<&'a str>, + #[doc(hidden)] + pub required: bool, + #[doc(hidden)] + pub requires: Option>, + #[doc(hidden)] + pub conflicts: Option>, + #[doc(hidden)] + pub multiple: bool, +} + +impl<'a> ArgGroup<'a> { + /// Creates a new instance of `ArgGroup` using a unique string name. The name will be used to + /// get values from the group or refer to the group inside of conflict and requirement rules. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, ArgGroup}; + /// ArgGroup::with_name("config") + /// # ; + /// ``` + pub fn with_name(n: &'a str) -> Self { + ArgGroup { + name: n, + required: false, + args: vec![], + requires: None, + conflicts: None, + multiple: false, + } + } + + /// Creates a new instance of `ArgGroup` from a .yml (YAML) file. + /// + /// # Examples + /// + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::ArgGroup; + /// # fn main() { + /// let yml = load_yaml!("group.yml"); + /// let ag = ArgGroup::from_yaml(yml); + /// # } + /// ``` + #[cfg(feature = "yaml")] + pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> { + ArgGroup::from(y.as_hash().unwrap()) + } + + /// Adds an [argument] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .group(ArgGroup::with_name("req_flags") + /// .arg("flag") + /// .arg("color")) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.is_present("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.is_present("flag")); + /// ``` + /// [argument]: ./struct.Arg.html + pub fn arg(mut self, n: &'a str) -> Self { + assert!( + self.name != n, + "ArgGroup '{}' can not have same name as arg inside it", + &*self.name + ); + self.args.push(n); + self + } + + /// Adds multiple [arguments] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"])) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.is_present("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.is_present("flag")); + /// ``` + /// [arguments]: ./struct.Arg.html + pub fn args(mut self, ns: &[&'a str]) -> Self { + for n in ns { + self = self.arg(n); + } + self + } + + /// Allows more than one of the ['Arg']s in this group to be used. (Default: `false`) + /// + /// # Examples + /// + /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the + /// group + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup}; + /// let m = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"]) + /// .multiple(true)) + /// .get_matches_from(vec!["myprog", "-f", "-c"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.is_present("req_flags")); + /// ``` + /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw + /// an error if more than one of the args in the group was used. + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup, ErrorKind}; + /// let result = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"])) + /// .get_matches_from_safe(vec!["myprog", "-f", "-c"]); + /// // Because we used both args in the group it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::ArgumentConflict); + /// ``` + /// ['Arg']: ./struct.Arg.html + pub fn multiple(mut self, m: bool) -> Self { + self.multiple = m; + self + } + + /// Sets the group as required or not. A required group will be displayed in the usage string + /// of the application in the format ``. A required `ArgGroup` simply states + /// that one argument from this group *must* be present at runtime (unless + /// conflicting with another argument). + /// + /// **NOTE:** This setting only applies to the current [`App`] / [`SubCommand`], and not + /// globally. + /// + /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with + /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. + /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which + /// states, '*At least* one arg from this group must be used. Using multiple is OK." + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup, ErrorKind}; + /// let result = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"]) + /// .required(true)) + /// .get_matches_from_safe(vec!["myprog"]); + /// // Because we didn't use any of the args in the group, it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [`App`]: ./struct.App.html + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`ArgGroup::multiple`]: ./struct.ArgGroup.html#method.multiple + pub fn required(mut self, r: bool) -> Self { + self.required = r; + self + } + + /// Sets the requirement rules of this group. This is not to be confused with a + /// [required group]. Requirement rules function just like [argument requirement rules], you + /// can name other arguments or groups that must be present when any one of the arguments from + /// this group is used. + /// + /// **NOTE:** The name provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup, ErrorKind}; + /// let result = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .arg(Arg::with_name("debug") + /// .short("d")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"]) + /// .requires("debug")) + /// .get_matches_from_safe(vec!["myprog", "-c"]); + /// // because we used an arg from the group, and the group requires "-d" to be used, it's an + /// // error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ./struct.ArgGroup.html#method.required + /// [argument requirement rules]: ./struct.Arg.html#method.requires + pub fn requires(mut self, n: &'a str) -> Self { + if let Some(ref mut reqs) = self.requires { + reqs.push(n); + } else { + self.requires = Some(vec![n]); + } + self + } + + /// Sets the requirement rules of this group. This is not to be confused with a + /// [required group]. Requirement rules function just like [argument requirement rules], you + /// can name other arguments or groups that must be present when one of the arguments from this + /// group is used. + /// + /// **NOTE:** The names provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup, ErrorKind}; + /// let result = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .arg(Arg::with_name("debug") + /// .short("d")) + /// .arg(Arg::with_name("verb") + /// .short("v")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"]) + /// .requires_all(&["debug", "verb"])) + /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, + /// // yet we only used "-d" it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ./struct.ArgGroup.html#method.required + /// [argument requirement rules]: ./struct.Arg.html#method.requires_all + pub fn requires_all(mut self, ns: &[&'a str]) -> Self { + for n in ns { + self = self.requires(n); + } + self + } + + /// Sets the exclusion rules of this group. Exclusion (aka conflict) rules function just like + /// [argument exclusion rules], you can name other arguments or groups that must *not* be + /// present when one of the arguments from this group are used. + /// + /// **NOTE:** The name provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup, ErrorKind}; + /// let result = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .arg(Arg::with_name("debug") + /// .short("d")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"]) + /// .conflicts_with("debug")) + /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group conflicts with "-d", it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::ArgumentConflict); + /// ``` + /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with + pub fn conflicts_with(mut self, n: &'a str) -> Self { + if let Some(ref mut confs) = self.conflicts { + confs.push(n); + } else { + self.conflicts = Some(vec![n]); + } + self + } + + /// Sets the exclusion rules of this group. Exclusion rules function just like + /// [argument exclusion rules], you can name other arguments or groups that must *not* be + /// present when one of the arguments from this group are used. + /// + /// **NOTE:** The names provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ArgGroup, ErrorKind}; + /// let result = App::new("myprog") + /// .arg(Arg::with_name("flag") + /// .short("f")) + /// .arg(Arg::with_name("color") + /// .short("c")) + /// .arg(Arg::with_name("debug") + /// .short("d")) + /// .arg(Arg::with_name("verb") + /// .short("v")) + /// .group(ArgGroup::with_name("req_flags") + /// .args(&["flag", "color"]) + /// .conflicts_with_all(&["debug", "verb"])) + /// .get_matches_from_safe(vec!["myprog", "-c", "-v"]); + /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" + /// // it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind, ErrorKind::ArgumentConflict); + /// ``` + /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with_all + pub fn conflicts_with_all(mut self, ns: &[&'a str]) -> Self { + for n in ns { + self = self.conflicts_with(n); + } + self + } +} + +impl<'a> Debug for ArgGroup<'a> { + fn fmt(&self, f: &mut Formatter) -> Result { + write!( + f, + "{{\n\ + \tname: {:?},\n\ + \targs: {:?},\n\ + \trequired: {:?},\n\ + \trequires: {:?},\n\ + \tconflicts: {:?},\n\ + }}", + self.name, self.args, self.required, self.requires, self.conflicts + ) + } +} + +impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a> { + fn from(g: &'z ArgGroup<'a>) -> Self { + ArgGroup { + name: g.name, + required: g.required, + args: g.args.clone(), + requires: g.requires.clone(), + conflicts: g.conflicts.clone(), + multiple: g.multiple, + } + } +} + +#[cfg(feature = "yaml")] +impl<'a> From<&'a BTreeMap> for ArgGroup<'a> { + fn from(b: &'a BTreeMap) -> Self { + // We WANT this to panic on error...so expect() is good. + let mut a = ArgGroup::default(); + let group_settings = if b.len() == 1 { + let name_yml = b.keys().nth(0).expect("failed to get name"); + let name_str = name_yml + .as_str() + .expect("failed to convert arg YAML name to str"); + a.name = name_str; + b.get(name_yml) + .expect("failed to get name_str") + .as_hash() + .expect("failed to convert to a hash") + } else { + b + }; + + for (k, v) in group_settings { + a = match k.as_str().unwrap() { + "required" => a.required(v.as_bool().unwrap()), + "multiple" => a.multiple(v.as_bool().unwrap()), + "args" => yaml_vec_or_str!(v, a, arg), + "arg" => { + if let Some(ys) = v.as_str() { + a = a.arg(ys); + } + a + } + "requires" => yaml_vec_or_str!(v, a, requires), + "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), + "name" => { + if let Some(ys) = v.as_str() { + a.name = ys; + } + a + } + s => panic!( + "Unknown ArgGroup setting '{}' in YAML file for \ + ArgGroup '{}'", + s, a.name + ), + } + } + + a + } +} + +#[cfg(test)] +mod test { + use super::ArgGroup; + #[cfg(feature = "yaml")] + use yaml_rust::YamlLoader; + + #[test] + fn groups() { + let g = ArgGroup::with_name("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1", "a4", "a2", "a3"]; + let reqs = vec!["r1", "r2", "r3", "r4"]; + let confs = vec!["c1", "c2", "c3", "c4"]; + + assert_eq!(g.args, args); + assert_eq!(g.requires, Some(reqs)); + assert_eq!(g.conflicts, Some(confs)); + } + + #[test] + fn test_debug() { + let g = ArgGroup::with_name("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1", "a4", "a2", "a3"]; + let reqs = vec!["r1", "r2", "r3", "r4"]; + let confs = vec!["c1", "c2", "c3", "c4"]; + + let debug_str = format!( + "{{\n\ + \tname: \"test\",\n\ + \targs: {:?},\n\ + \trequired: {:?},\n\ + \trequires: {:?},\n\ + \tconflicts: {:?},\n\ + }}", + args, + true, + Some(reqs), + Some(confs) + ); + assert_eq!(&*format!("{:?}", g), &*debug_str); + } + + #[test] + fn test_from() { + let g = ArgGroup::with_name("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1", "a4", "a2", "a3"]; + let reqs = vec!["r1", "r2", "r3", "r4"]; + let confs = vec!["c1", "c2", "c3", "c4"]; + + let g2 = ArgGroup::from(&g); + assert_eq!(g2.args, args); + assert_eq!(g2.requires, Some(reqs)); + assert_eq!(g2.conflicts, Some(confs)); + } + + #[cfg(feature = "yaml")] + #[cfg_attr(feature = "yaml", test)] + fn test_yaml() { + let g_yaml = "name: test +args: +- a1 +- a4 +- a2 +- a3 +conflicts_with: +- c1 +- c2 +- c3 +- c4 +requires: +- r1 +- r2 +- r3 +- r4"; + let yml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0]; + let g = ArgGroup::from_yaml(yml); + let args = vec!["a1", "a4", "a2", "a3"]; + let reqs = vec!["r1", "r2", "r3", "r4"]; + let confs = vec!["c1", "c2", "c3", "c4"]; + assert_eq!(g.args, args); + assert_eq!(g.requires, Some(reqs)); + assert_eq!(g.conflicts, Some(confs)); + } +} + +impl<'a> Clone for ArgGroup<'a> { + fn clone(&self) -> Self { + ArgGroup { + name: self.name, + required: self.required, + args: self.args.clone(), + requires: self.requires.clone(), + conflicts: self.conflicts.clone(), + multiple: self.multiple, + } + } +} diff --git a/bash-5.1/vendor/clap/src/args/macros.rs b/bash-5.1/vendor/clap/src/args/macros.rs new file mode 100644 index 0000000..ac4b1a2 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/macros.rs @@ -0,0 +1,121 @@ +#[cfg(feature = "yaml")] +macro_rules! yaml_tuple2 { + ($a:ident, $v:ident, $c:ident) => {{ + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(2, tup.len()); + $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); + } else { + panic!("Failed to convert YAML value to vec"); + } + } + } else { + panic!("Failed to convert YAML value to vec"); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_tuple3 { + ($a:ident, $v:ident, $c:ident) => {{ + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(3, tup.len()); + $a = $a.$c(yaml_str!(tup[0]), yaml_opt_str!(tup[1]), yaml_str!(tup[2])); + } else { + panic!("Failed to convert YAML value to vec"); + } + } + } else { + panic!("Failed to convert YAML value to vec"); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_vec_or_str { + ($v:ident, $a:ident, $c:ident) => {{ + let maybe_vec = $v.as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { + $a = $a.$c(s); + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + } + } else { + if let Some(s) = $v.as_str() { + $a = $a.$c(s); + } else { + panic!( + "Failed to convert YAML value {:?} to either a vec or string", + $v + ); + } + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_opt_str { + ($v:expr) => {{ + if $v.is_null() { + Some( + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)), + ) + } else { + None + } + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_str { + ($v:expr) => {{ + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_str { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c(yaml_str!($v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_bool { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_bool() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_u64 { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_i64() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + as u64) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_usize { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_i64() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + as usize) + }}; +} diff --git a/bash-5.1/vendor/clap/src/args/matched_arg.rs b/bash-5.1/vendor/clap/src/args/matched_arg.rs new file mode 100644 index 0000000..681e5d2 --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/matched_arg.rs @@ -0,0 +1,29 @@ +// Std +use std::ffi::OsString; + +#[doc(hidden)] +#[derive(Debug, Clone)] +pub struct MatchedArg { + #[doc(hidden)] + pub occurs: u64, + #[doc(hidden)] + pub indices: Vec, + #[doc(hidden)] + pub vals: Vec, +} + +impl Default for MatchedArg { + fn default() -> Self { + MatchedArg { + occurs: 1, + indices: Vec::new(), + vals: Vec::new(), + } + } +} + +impl MatchedArg { + pub fn new() -> Self { + MatchedArg::default() + } +} diff --git a/bash-5.1/vendor/clap/src/args/mod.rs b/bash-5.1/vendor/clap/src/args/mod.rs new file mode 100644 index 0000000..8f076ea --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/mod.rs @@ -0,0 +1,21 @@ +pub use self::any_arg::{AnyArg, DispOrder}; +pub use self::arg::Arg; +pub use self::arg_builder::{Base, FlagBuilder, OptBuilder, PosBuilder, Switched, Valued}; +pub use self::arg_matcher::ArgMatcher; +pub use self::arg_matches::{ArgMatches, OsValues, Values}; +pub use self::group::ArgGroup; +pub use self::matched_arg::MatchedArg; +pub use self::settings::{ArgFlags, ArgSettings}; +pub use self::subcommand::SubCommand; + +#[macro_use] +mod macros; +pub mod any_arg; +mod arg; +mod arg_builder; +mod arg_matcher; +mod arg_matches; +mod group; +mod matched_arg; +pub mod settings; +mod subcommand; diff --git a/bash-5.1/vendor/clap/src/args/settings.rs b/bash-5.1/vendor/clap/src/args/settings.rs new file mode 100644 index 0000000..833a1ea --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/settings.rs @@ -0,0 +1,237 @@ +// Std +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; +use std::str::FromStr; + +bitflags! { + struct Flags: u32 { + const REQUIRED = 1; + const MULTIPLE = 1 << 1; + const EMPTY_VALS = 1 << 2; + const GLOBAL = 1 << 3; + const HIDDEN = 1 << 4; + const TAKES_VAL = 1 << 5; + const USE_DELIM = 1 << 6; + const NEXT_LINE_HELP = 1 << 7; + const R_UNLESS_ALL = 1 << 8; + const REQ_DELIM = 1 << 9; + const DELIM_NOT_SET = 1 << 10; + const HIDE_POS_VALS = 1 << 11; + const ALLOW_TAC_VALS = 1 << 12; + const REQUIRE_EQUALS = 1 << 13; + const LAST = 1 << 14; + const HIDE_DEFAULT_VAL = 1 << 15; + const CASE_INSENSITIVE = 1 << 16; + const HIDE_ENV_VALS = 1 << 17; + const HIDDEN_SHORT_H = 1 << 18; + const HIDDEN_LONG_H = 1 << 19; + } +} + +#[doc(hidden)] +#[derive(Debug, Clone, Copy)] +pub struct ArgFlags(Flags); + +impl ArgFlags { + pub fn new() -> Self { + ArgFlags::default() + } + + impl_settings! {ArgSettings, + Required => Flags::REQUIRED, + Multiple => Flags::MULTIPLE, + EmptyValues => Flags::EMPTY_VALS, + Global => Flags::GLOBAL, + Hidden => Flags::HIDDEN, + TakesValue => Flags::TAKES_VAL, + UseValueDelimiter => Flags::USE_DELIM, + NextLineHelp => Flags::NEXT_LINE_HELP, + RequiredUnlessAll => Flags::R_UNLESS_ALL, + RequireDelimiter => Flags::REQ_DELIM, + ValueDelimiterNotSet => Flags::DELIM_NOT_SET, + HidePossibleValues => Flags::HIDE_POS_VALS, + AllowLeadingHyphen => Flags::ALLOW_TAC_VALS, + RequireEquals => Flags::REQUIRE_EQUALS, + Last => Flags::LAST, + CaseInsensitive => Flags::CASE_INSENSITIVE, + HideEnvValues => Flags::HIDE_ENV_VALS, + HideDefaultValue => Flags::HIDE_DEFAULT_VAL, + HiddenShortHelp => Flags::HIDDEN_SHORT_H, + HiddenLongHelp => Flags::HIDDEN_LONG_H + } +} + +impl Default for ArgFlags { + fn default() -> Self { + ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET) + } +} + +/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter +/// methods [`Arg::set`], [`Arg::unset`], and [`Arg::is_set`] +/// +/// [`Arg::set`]: ./struct.Arg.html#method.set +/// [`Arg::unset`]: ./struct.Arg.html#method.unset +/// [`Arg::is_set`]: ./struct.Arg.html#method.is_set +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum ArgSettings { + /// The argument must be used + Required, + /// The argument may be used multiple times such as `--flag --flag` + Multiple, + /// The argument allows empty values such as `--option ""` + EmptyValues, + /// The argument should be propagated down through all child [`SubCommand`]s + /// + /// [`SubCommand`]: ./struct.SubCommand.html + Global, + /// The argument should **not** be shown in help text + Hidden, + /// The argument accepts a value, such as `--option ` + TakesValue, + /// Determines if the argument allows values to be grouped via a delimiter + UseValueDelimiter, + /// Prints the help text on the line after the argument + NextLineHelp, + /// Requires the use of a value delimiter for all multiple values + RequireDelimiter, + /// Hides the possible values from the help string + HidePossibleValues, + /// Allows vals that start with a '-' + AllowLeadingHyphen, + /// Require options use `--option=val` syntax + RequireEquals, + /// Specifies that the arg is the last positional argument and may be accessed early via `--` + /// syntax + Last, + /// Hides the default value from the help string + HideDefaultValue, + /// Makes `Arg::possible_values` case insensitive + CaseInsensitive, + /// Hides ENV values in the help message + HideEnvValues, + /// The argument should **not** be shown in short help text + HiddenShortHelp, + /// The argument should **not** be shown in long help text + HiddenLongHelp, + #[doc(hidden)] + RequiredUnlessAll, + #[doc(hidden)] + ValueDelimiterNotSet, +} + +impl FromStr for ArgSettings { + type Err = String; + fn from_str(s: &str) -> Result::Err> { + match &*s.to_ascii_lowercase() { + "required" => Ok(ArgSettings::Required), + "multiple" => Ok(ArgSettings::Multiple), + "global" => Ok(ArgSettings::Global), + "emptyvalues" => Ok(ArgSettings::EmptyValues), + "hidden" => Ok(ArgSettings::Hidden), + "takesvalue" => Ok(ArgSettings::TakesValue), + "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter), + "nextlinehelp" => Ok(ArgSettings::NextLineHelp), + "requiredunlessall" => Ok(ArgSettings::RequiredUnlessAll), + "requiredelimiter" => Ok(ArgSettings::RequireDelimiter), + "valuedelimiternotset" => Ok(ArgSettings::ValueDelimiterNotSet), + "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues), + "allowleadinghyphen" => Ok(ArgSettings::AllowLeadingHyphen), + "requireequals" => Ok(ArgSettings::RequireEquals), + "last" => Ok(ArgSettings::Last), + "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue), + "caseinsensitive" => Ok(ArgSettings::CaseInsensitive), + "hideenvvalues" => Ok(ArgSettings::HideEnvValues), + "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp), + "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp), + _ => Err("unknown ArgSetting, cannot convert from str".to_owned()), + } + } +} + +#[cfg(test)] +mod test { + use super::ArgSettings; + + #[test] + fn arg_settings_fromstr() { + assert_eq!( + "allowleadinghyphen".parse::().unwrap(), + ArgSettings::AllowLeadingHyphen + ); + assert_eq!( + "emptyvalues".parse::().unwrap(), + ArgSettings::EmptyValues + ); + assert_eq!( + "global".parse::().unwrap(), + ArgSettings::Global + ); + assert_eq!( + "hidepossiblevalues".parse::().unwrap(), + ArgSettings::HidePossibleValues + ); + assert_eq!( + "hidden".parse::().unwrap(), + ArgSettings::Hidden + ); + assert_eq!( + "multiple".parse::().unwrap(), + ArgSettings::Multiple + ); + assert_eq!( + "nextlinehelp".parse::().unwrap(), + ArgSettings::NextLineHelp + ); + assert_eq!( + "requiredunlessall".parse::().unwrap(), + ArgSettings::RequiredUnlessAll + ); + assert_eq!( + "requiredelimiter".parse::().unwrap(), + ArgSettings::RequireDelimiter + ); + assert_eq!( + "required".parse::().unwrap(), + ArgSettings::Required + ); + assert_eq!( + "takesvalue".parse::().unwrap(), + ArgSettings::TakesValue + ); + assert_eq!( + "usevaluedelimiter".parse::().unwrap(), + ArgSettings::UseValueDelimiter + ); + assert_eq!( + "valuedelimiternotset".parse::().unwrap(), + ArgSettings::ValueDelimiterNotSet + ); + assert_eq!( + "requireequals".parse::().unwrap(), + ArgSettings::RequireEquals + ); + assert_eq!("last".parse::().unwrap(), ArgSettings::Last); + assert_eq!( + "hidedefaultvalue".parse::().unwrap(), + ArgSettings::HideDefaultValue + ); + assert_eq!( + "caseinsensitive".parse::().unwrap(), + ArgSettings::CaseInsensitive + ); + assert_eq!( + "hideenvvalues".parse::().unwrap(), + ArgSettings::HideEnvValues + ); + assert_eq!( + "hiddenshorthelp".parse::().unwrap(), + ArgSettings::HiddenShortHelp + ); + assert_eq!( + "hiddenlonghelp".parse::().unwrap(), + ArgSettings::HiddenLongHelp + ); + assert!("hahahaha".parse::().is_err()); + } +} diff --git a/bash-5.1/vendor/clap/src/args/subcommand.rs b/bash-5.1/vendor/clap/src/args/subcommand.rs new file mode 100644 index 0000000..8ad1c0e --- /dev/null +++ b/bash-5.1/vendor/clap/src/args/subcommand.rs @@ -0,0 +1,71 @@ +// Third Party +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::{App, ArgMatches}; + +/// The abstract representation of a command line subcommand. +/// +/// This struct describes all the valid options of the subcommand for the program. Subcommands are +/// essentially "sub-[`App`]s" and contain all the same possibilities (such as their own +/// [arguments], subcommands, and settings). +/// +/// # Examples +/// +/// ```rust +/// # use clap::{App, Arg, SubCommand}; +/// App::new("myprog") +/// .subcommand( +/// SubCommand::with_name("config") +/// .about("Used for configuration") +/// .arg(Arg::with_name("config_file") +/// .help("The configuration file to use") +/// .index(1))) +/// # ; +/// ``` +/// [`App`]: ./struct.App.html +/// [arguments]: ./struct.Arg.html +#[derive(Debug, Clone)] +pub struct SubCommand<'a> { + #[doc(hidden)] + pub name: String, + #[doc(hidden)] + pub matches: ArgMatches<'a>, +} + +impl<'a> SubCommand<'a> { + /// Creates a new instance of a subcommand requiring a name. The name will be displayed + /// to the user when they print version or help and usage information. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// App::new("myprog") + /// .subcommand( + /// SubCommand::with_name("config")) + /// # ; + /// ``` + pub fn with_name<'b>(name: &str) -> App<'a, 'b> { + App::new(name) + } + + /// Creates a new instance of a subcommand from a YAML (.yml) document + /// + /// # Examples + /// + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::Subcommand; + /// # fn main() { + /// let sc_yaml = load_yaml!("test_subcommand.yml"); + /// let sc = SubCommand::from_yaml(sc_yaml); + /// # } + /// ``` + #[cfg(feature = "yaml")] + pub fn from_yaml(yaml: &Yaml) -> App { + App::from_yaml(yaml) + } +} diff --git a/bash-5.1/vendor/clap/src/completions/bash.rs b/bash-5.1/vendor/clap/src/completions/bash.rs new file mode 100644 index 0000000..5c3df72 --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/bash.rs @@ -0,0 +1,223 @@ +// Std +use std::io::Write; + +// Internal +use crate::{ + app::parser::Parser, + args::{AnyArg, OptBuilder}, + completions, +}; + +pub struct BashGen<'a, 'b> +where + 'a: 'b, +{ + p: &'b Parser<'a, 'b>, +} + +impl<'a, 'b> BashGen<'a, 'b> { + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + BashGen { p } + } + + pub fn generate_to(&self, buf: &mut W) { + w!( + buf, + format!( + r#"_{name}() {{ + local i cur prev opts cmds + COMPREPLY=() + cur="${{COMP_WORDS[COMP_CWORD]}}" + prev="${{COMP_WORDS[COMP_CWORD-1]}}" + cmd="" + opts="" + + for i in ${{COMP_WORDS[@]}} + do + case "${{i}}" in + {name}) + cmd="{name}" + ;; + {subcmds} + *) + ;; + esac + done + + case "${{cmd}}" in + {name}) + opts="{name_opts}" + if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq 1 ]] ; then + COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) + return 0 + fi + case "${{prev}}" in + {name_opts_details} + *) + COMPREPLY=() + ;; + esac + COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) + return 0 + ;; + {subcmd_details} + esac +}} + +complete -F _{name} -o bashdefault -o default {name} +"#, + name = self.p.meta.bin_name.as_ref().unwrap(), + name_opts = self.all_options_for_path(self.p.meta.bin_name.as_ref().unwrap()), + name_opts_details = + self.option_details_for_path(self.p.meta.bin_name.as_ref().unwrap()), + subcmds = self.all_subcommands(), + subcmd_details = self.subcommand_details() + ) + .as_bytes() + ); + } + + fn all_subcommands(&self) -> String { + debugln!("BashGen::all_subcommands;"); + let mut subcmds = String::new(); + let scs = completions::all_subcommand_names(self.p); + + for sc in &scs { + subcmds = format!( + r#"{} + {name}) + cmd+="__{fn_name}" + ;;"#, + subcmds, + name = sc, + fn_name = sc.replace("-", "__") + ); + } + + subcmds + } + + fn subcommand_details(&self) -> String { + debugln!("BashGen::subcommand_details;"); + let mut subcmd_dets = String::new(); + let mut scs = completions::get_all_subcommand_paths(self.p, true); + scs.sort(); + scs.dedup(); + + for sc in &scs { + subcmd_dets = format!( + r#"{} + {subcmd}) + opts="{sc_opts}" + if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then + COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) + return 0 + fi + case "${{prev}}" in + {opts_details} + *) + COMPREPLY=() + ;; + esac + COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) + return 0 + ;;"#, + subcmd_dets, + subcmd = sc.replace("-", "__"), + sc_opts = self.all_options_for_path(&*sc), + level = sc.split("__").count(), + opts_details = self.option_details_for_path(&*sc) + ); + } + + subcmd_dets + } + + fn option_details_for_path(&self, path: &str) -> String { + debugln!("BashGen::option_details_for_path: path={}", path); + let mut p = self.p; + for sc in path.split("__").skip(1) { + debugln!("BashGen::option_details_for_path:iter: sc={}", sc); + p = &find_subcmd!(p, sc).unwrap().p; + } + let mut opts = String::new(); + for o in p.opts() { + if let Some(l) = o.s.long { + opts = format!( + "{} + --{}) + COMPREPLY=({}) + return 0 + ;;", + opts, + l, + self.vals_for(o) + ); + } + if let Some(s) = o.s.short { + opts = format!( + "{} + -{}) + COMPREPLY=({}) + return 0 + ;;", + opts, + s, + self.vals_for(o) + ); + } + } + opts + } + + fn vals_for(&self, o: &OptBuilder) -> String { + debugln!("BashGen::vals_for: o={}", o.b.name); + if let Some(vals) = o.possible_vals() { + format!(r#"$(compgen -W "{}" -- "${{cur}}")"#, vals.join(" ")) + } else { + String::from(r#"$(compgen -f "${cur}")"#) + } + } + + fn all_options_for_path(&self, path: &str) -> String { + debugln!("BashGen::all_options_for_path: path={}", path); + let mut p = self.p; + for sc in path.split("__").skip(1) { + debugln!("BashGen::all_options_for_path:iter: sc={}", sc); + p = &find_subcmd!(p, sc).unwrap().p; + } + let mut opts = shorts!(p).fold(String::new(), |acc, s| format!("{} -{}", acc, s)); + opts = format!( + "{} {}", + opts, + longs!(p).fold(String::new(), |acc, l| format!("{} --{}", acc, l)) + ); + opts = format!( + "{} {}", + opts, + p.positionals + .values() + .fold(String::new(), |acc, p| format!("{} {}", acc, p)) + ); + opts = format!( + "{} {}", + opts, + p.subcommands + .iter() + .fold(String::new(), |acc, s| format!("{} {}", acc, s.p.meta.name)) + ); + for sc in &p.subcommands { + if let Some(ref aliases) = sc.p.meta.aliases { + opts = format!( + "{} {}", + opts, + aliases + .iter() + .map(|&(n, _)| n) + .fold(String::new(), |acc, a| format!("{} {}", acc, a)) + ); + } + } + opts + } +} diff --git a/bash-5.1/vendor/clap/src/completions/elvish.rs b/bash-5.1/vendor/clap/src/completions/elvish.rs new file mode 100644 index 0000000..c6d8bb6 --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/elvish.rs @@ -0,0 +1,127 @@ +// Std +use std::io::Write; + +// Internal +use crate::{app::parser::Parser, INTERNAL_ERROR_MSG}; + +pub struct ElvishGen<'a, 'b> +where + 'a: 'b, +{ + p: &'b Parser<'a, 'b>, +} + +impl<'a, 'b> ElvishGen<'a, 'b> { + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + ElvishGen { p } + } + + pub fn generate_to(&self, buf: &mut W) { + let bin_name = self.p.meta.bin_name.as_ref().unwrap(); + + let mut names = vec![]; + let subcommands_cases = generate_inner(self.p, "", &mut names); + + let result = format!( + r#" +edit:completion:arg-completer[{bin_name}] = [@words]{{ + fn spaces [n]{{ + repeat $n ' ' | joins '' + }} + fn cand [text desc]{{ + edit:complex-candidate $text &display-suffix=' '(spaces (- 14 (wcswidth $text)))$desc + }} + command = '{bin_name}' + for word $words[1:-1] {{ + if (has-prefix $word '-') {{ + break + }} + command = $command';'$word + }} + completions = [{subcommands_cases} + ] + $completions[$command] +}} +"#, + bin_name = bin_name, + subcommands_cases = subcommands_cases + ); + + w!(buf, result.as_bytes()); + } +} + +// Escape string inside single quotes +fn escape_string(string: &str) -> String { + string.replace("'", "''") +} + +fn get_tooltip(help: Option<&str>, data: T) -> String { + match help { + Some(help) => escape_string(help), + _ => data.to_string(), + } +} + +fn generate_inner<'a, 'b, 'p>( + p: &'p Parser<'a, 'b>, + previous_command_name: &str, + names: &mut Vec<&'p str>, +) -> String { + debugln!("ElvishGen::generate_inner;"); + let command_name = if previous_command_name.is_empty() { + p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone() + } else { + format!("{};{}", previous_command_name, &p.meta.name) + }; + + let mut completions = String::new(); + let preamble = String::from("\n cand "); + + for option in p.opts() { + if let Some(data) = option.s.short { + let tooltip = get_tooltip(option.b.help, data); + completions.push_str(&preamble); + completions.push_str(format!("-{} '{}'", data, tooltip).as_str()); + } + if let Some(data) = option.s.long { + let tooltip = get_tooltip(option.b.help, data); + completions.push_str(&preamble); + completions.push_str(format!("--{} '{}'", data, tooltip).as_str()); + } + } + + for flag in p.flags() { + if let Some(data) = flag.s.short { + let tooltip = get_tooltip(flag.b.help, data); + completions.push_str(&preamble); + completions.push_str(format!("-{} '{}'", data, tooltip).as_str()); + } + if let Some(data) = flag.s.long { + let tooltip = get_tooltip(flag.b.help, data); + completions.push_str(&preamble); + completions.push_str(format!("--{} '{}'", data, tooltip).as_str()); + } + } + + for subcommand in &p.subcommands { + let data = &subcommand.p.meta.name; + let tooltip = get_tooltip(subcommand.p.meta.about, data); + completions.push_str(&preamble); + completions.push_str(format!("{} '{}'", data, tooltip).as_str()); + } + + let mut subcommands_cases = format!( + r" + &'{}'= {{{} + }}", + &command_name, completions + ); + + for subcommand in &p.subcommands { + let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names); + subcommands_cases.push_str(&subcommand_subcommands_cases); + } + + subcommands_cases +} diff --git a/bash-5.1/vendor/clap/src/completions/fish.rs b/bash-5.1/vendor/clap/src/completions/fish.rs new file mode 100644 index 0000000..053f56a --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/fish.rs @@ -0,0 +1,103 @@ +// Std +use std::io::Write; + +// Internal +use crate::app::parser::Parser; + +pub struct FishGen<'a, 'b> +where + 'a: 'b, +{ + p: &'b Parser<'a, 'b>, +} + +impl<'a, 'b> FishGen<'a, 'b> { + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + FishGen { p } + } + + pub fn generate_to(&self, buf: &mut W) { + let command = self.p.meta.bin_name.as_ref().unwrap(); + let mut buffer = String::new(); + gen_fish_inner(command, self, command, &mut buffer); + w!(buf, buffer.as_bytes()); + } +} + +// Escape string inside single quotes +fn escape_string(string: &str) -> String { + string.replace("\\", "\\\\").replace("'", "\\'") +} + +fn gen_fish_inner(root_command: &str, comp_gen: &FishGen, subcommand: &str, buffer: &mut String) { + debugln!("FishGen::gen_fish_inner;"); + // example : + // + // complete + // -c {command} + // -d "{description}" + // -s {short} + // -l {long} + // -a "{possible_arguments}" + // -r # if require parameter + // -f # don't use file completion + // -n "__fish_use_subcommand" # complete for command "myprog" + // -n "__fish_seen_subcommand_from subcmd1" # complete for command "myprog subcmd1" + + let mut basic_template = format!("complete -c {} -n ", root_command); + if root_command == subcommand { + basic_template.push_str("\"__fish_use_subcommand\""); + } else { + basic_template.push_str(format!("\"__fish_seen_subcommand_from {}\"", subcommand).as_str()); + } + + for option in comp_gen.p.opts() { + let mut template = basic_template.clone(); + if let Some(data) = option.s.short { + template.push_str(format!(" -s {}", data).as_str()); + } + if let Some(data) = option.s.long { + template.push_str(format!(" -l {}", data).as_str()); + } + if let Some(data) = option.b.help { + template.push_str(format!(" -d '{}'", escape_string(data)).as_str()); + } + if let Some(ref data) = option.v.possible_vals { + template.push_str(format!(" -r -f -a \"{}\"", data.join(" ")).as_str()); + } + buffer.push_str(template.as_str()); + buffer.push('\n'); + } + + for flag in comp_gen.p.flags() { + let mut template = basic_template.clone(); + if let Some(data) = flag.s.short { + template.push_str(format!(" -s {}", data).as_str()); + } + if let Some(data) = flag.s.long { + template.push_str(format!(" -l {}", data).as_str()); + } + if let Some(data) = flag.b.help { + template.push_str(format!(" -d '{}'", escape_string(data)).as_str()); + } + buffer.push_str(template.as_str()); + buffer.push('\n'); + } + + for subcommand in &comp_gen.p.subcommands { + let mut template = basic_template.clone(); + template.push_str(" -f"); + template.push_str(format!(" -a \"{}\"", &subcommand.p.meta.name).as_str()); + if let Some(data) = subcommand.p.meta.about { + template.push_str(format!(" -d '{}'", escape_string(data)).as_str()) + } + buffer.push_str(template.as_str()); + buffer.push('\n'); + } + + // generate options of subcommands + for subcommand in &comp_gen.p.subcommands { + let sub_comp_gen = FishGen::new(&subcommand.p); + gen_fish_inner(root_command, &sub_comp_gen, &subcommand.to_string(), buffer); + } +} diff --git a/bash-5.1/vendor/clap/src/completions/macros.rs b/bash-5.1/vendor/clap/src/completions/macros.rs new file mode 100644 index 0000000..3a69de5 --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/macros.rs @@ -0,0 +1,28 @@ +macro_rules! w { + ($buf:expr, $to_w:expr) => { + match $buf.write_all($to_w) { + Ok(..) => (), + Err(..) => panic!("Failed to write to completions file"), + } + }; +} + +macro_rules! get_zsh_arg_conflicts { + ($p:ident, $arg:ident, $msg:ident) => { + if let Some(conf_vec) = $arg.blacklist() { + let mut v = vec![]; + for arg_name in conf_vec { + let arg = $p.find_any_arg(arg_name).expect($msg); + if let Some(s) = arg.short() { + v.push(format!("-{}", s)); + } + if let Some(l) = arg.long() { + v.push(format!("--{}", l)); + } + } + v.join(" ") + } else { + String::new() + } + }; +} diff --git a/bash-5.1/vendor/clap/src/completions/mod.rs b/bash-5.1/vendor/clap/src/completions/mod.rs new file mode 100644 index 0000000..ede2fa1 --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/mod.rs @@ -0,0 +1,182 @@ +#[macro_use] +mod macros; +mod bash; +mod elvish; +mod fish; +mod powershell; +mod shell; +mod zsh; + +// Std +use std::io::Write; + +// Internal +pub use crate::completions::shell::Shell; +use crate::{ + app::parser::Parser, + completions::{ + bash::BashGen, elvish::ElvishGen, fish::FishGen, powershell::PowerShellGen, zsh::ZshGen, + }, +}; + +pub struct ComplGen<'a, 'b> +where + 'a: 'b, +{ + p: &'b Parser<'a, 'b>, +} + +impl<'a, 'b> ComplGen<'a, 'b> { + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + ComplGen { p } + } + + pub fn generate(&self, for_shell: Shell, buf: &mut W) { + match for_shell { + Shell::Bash => BashGen::new(self.p).generate_to(buf), + Shell::Fish => FishGen::new(self.p).generate_to(buf), + Shell::Zsh => ZshGen::new(self.p).generate_to(buf), + Shell::PowerShell => PowerShellGen::new(self.p).generate_to(buf), + Shell::Elvish => ElvishGen::new(self.p).generate_to(buf), + } + } +} + +// Gets all subcommands including child subcommands in the form of 'name' where the name +// is a single word (i.e. "install") of the path to said subcommand (i.e. +// "rustup toolchain install") +// +// Also note, aliases are treated as their own subcommands but duplicates of whatever they're +// aliasing. +pub fn all_subcommand_names(p: &Parser) -> Vec { + debugln!("all_subcommand_names;"); + let mut subcmds: Vec<_> = subcommands_of(p) + .iter() + .map(|&(ref n, _)| n.clone()) + .collect(); + for sc_v in p.subcommands.iter().map(|s| all_subcommand_names(&s.p)) { + subcmds.extend(sc_v); + } + subcmds.sort(); + subcmds.dedup(); + subcmds +} + +// Gets all subcommands including child subcommands in the form of ('name', 'bin_name') where the name +// is a single word (i.e. "install") of the path and full bin_name of said subcommand (i.e. +// "rustup toolchain install") +// +// Also note, aliases are treated as their own subcommands but duplicates of whatever they're +// aliasing. +pub fn all_subcommands(p: &Parser) -> Vec<(String, String)> { + debugln!("all_subcommands;"); + let mut subcmds: Vec<_> = subcommands_of(p); + for sc_v in p.subcommands.iter().map(|s| all_subcommands(&s.p)) { + subcmds.extend(sc_v); + } + subcmds +} + +// Gets all subcommands excluding child subcommands in the form of (name, bin_name) where the name +// is a single word (i.e. "install") and the bin_name is a space delineated list of the path to said +// subcommand (i.e. "rustup toolchain install") +// +// Also note, aliases are treated as their own subcommands but duplicates of whatever they're +// aliasing. +pub fn subcommands_of(p: &Parser) -> Vec<(String, String)> { + debugln!( + "subcommands_of: name={}, bin_name={}", + p.meta.name, + p.meta.bin_name.as_ref().unwrap() + ); + let mut subcmds = vec![]; + + debugln!( + "subcommands_of: Has subcommands...{:?}", + p.has_subcommands() + ); + if !p.has_subcommands() { + let mut ret = vec![]; + debugln!("subcommands_of: Looking for aliases..."); + if let Some(ref aliases) = p.meta.aliases { + for &(n, _) in aliases { + debugln!("subcommands_of:iter:iter: Found alias...{}", n); + let mut als_bin_name: Vec<_> = + p.meta.bin_name.as_ref().unwrap().split(' ').collect(); + als_bin_name.push(n); + let old = als_bin_name.len() - 2; + als_bin_name.swap_remove(old); + ret.push((n.to_owned(), als_bin_name.join(" "))); + } + } + return ret; + } + for sc in &p.subcommands { + debugln!( + "subcommands_of:iter: name={}, bin_name={}", + sc.p.meta.name, + sc.p.meta.bin_name.as_ref().unwrap() + ); + + debugln!("subcommands_of:iter: Looking for aliases..."); + if let Some(ref aliases) = sc.p.meta.aliases { + for &(n, _) in aliases { + debugln!("subcommands_of:iter:iter: Found alias...{}", n); + let mut als_bin_name: Vec<_> = + p.meta.bin_name.as_ref().unwrap().split(' ').collect(); + als_bin_name.push(n); + let old = als_bin_name.len() - 2; + als_bin_name.swap_remove(old); + subcmds.push((n.to_owned(), als_bin_name.join(" "))); + } + } + subcmds.push(( + sc.p.meta.name.clone(), + sc.p.meta.bin_name.as_ref().unwrap().clone(), + )); + } + subcmds +} + +pub fn get_all_subcommand_paths(p: &Parser, first: bool) -> Vec { + debugln!("get_all_subcommand_paths;"); + let mut subcmds = vec![]; + if !p.has_subcommands() { + if !first { + let name = &*p.meta.name; + let path = p.meta.bin_name.as_ref().unwrap().clone().replace(" ", "__"); + let mut ret = vec![path.clone()]; + if let Some(ref aliases) = p.meta.aliases { + for &(n, _) in aliases { + ret.push(path.replace(name, n)); + } + } + return ret; + } + return vec![]; + } + for sc in &p.subcommands { + let name = &*sc.p.meta.name; + let path = + sc.p.meta + .bin_name + .as_ref() + .unwrap() + .clone() + .replace(" ", "__"); + subcmds.push(path.clone()); + if let Some(ref aliases) = sc.p.meta.aliases { + for &(n, _) in aliases { + subcmds.push(path.replace(name, n)); + } + } + } + for sc_v in p + .subcommands + .iter() + .map(|s| get_all_subcommand_paths(&s.p, false)) + { + subcmds.extend(sc_v); + } + subcmds +} diff --git a/bash-5.1/vendor/clap/src/completions/powershell.rs b/bash-5.1/vendor/clap/src/completions/powershell.rs new file mode 100644 index 0000000..ba1fd77 --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/powershell.rs @@ -0,0 +1,165 @@ +// Std +use std::io::Write; + +// Internal +use crate::{app::parser::Parser, INTERNAL_ERROR_MSG}; + +pub struct PowerShellGen<'a, 'b> +where + 'a: 'b, +{ + p: &'b Parser<'a, 'b>, +} + +impl<'a, 'b> PowerShellGen<'a, 'b> { + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + PowerShellGen { p } + } + + pub fn generate_to(&self, buf: &mut W) { + let bin_name = self.p.meta.bin_name.as_ref().unwrap(); + + let mut names = vec![]; + let subcommands_cases = generate_inner(self.p, "", &mut names); + + let result = format!( + r#" +using namespace System.Management.Automation +using namespace System.Management.Automation.Language + +Register-ArgumentCompleter -Native -CommandName '{bin_name}' -ScriptBlock {{ + param($wordToComplete, $commandAst, $cursorPosition) + + $commandElements = $commandAst.CommandElements + $command = @( + '{bin_name}' + for ($i = 1; $i -lt $commandElements.Count; $i++) {{ + $element = $commandElements[$i] + if ($element -isnot [StringConstantExpressionAst] -or + $element.StringConstantType -ne [StringConstantType]::BareWord -or + $element.Value.StartsWith('-')) {{ + break + }} + $element.Value + }}) -join ';' + + $completions = @(switch ($command) {{{subcommands_cases} + }}) + + $completions.Where{{ $_.CompletionText -like "$wordToComplete*" }} | + Sort-Object -Property ListItemText +}} +"#, + bin_name = bin_name, + subcommands_cases = subcommands_cases + ); + + w!(buf, result.as_bytes()); + } +} + +// Escape string inside single quotes +fn escape_string(string: &str) -> String { + string.replace("'", "''") +} + +fn get_tooltip(help: Option<&str>, data: T) -> String { + match help { + Some(help) => escape_string(help), + _ => data.to_string(), + } +} + +fn generate_inner<'a, 'b, 'p>( + p: &'p Parser<'a, 'b>, + previous_command_name: &str, + names: &mut Vec<&'p str>, +) -> String { + debugln!("PowerShellGen::generate_inner;"); + let command_name = if previous_command_name.is_empty() { + p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone() + } else { + format!("{};{}", previous_command_name, &p.meta.name) + }; + + let mut completions = String::new(); + let preamble = String::from("\n [CompletionResult]::new("); + + for option in p.opts() { + if let Some(data) = option.s.short { + let tooltip = get_tooltip(option.b.help, data); + completions.push_str(&preamble); + completions.push_str( + format!( + "'-{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); + } + if let Some(data) = option.s.long { + let tooltip = get_tooltip(option.b.help, data); + completions.push_str(&preamble); + completions.push_str( + format!( + "'--{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); + } + } + + for flag in p.flags() { + if let Some(data) = flag.s.short { + let tooltip = get_tooltip(flag.b.help, data); + completions.push_str(&preamble); + completions.push_str( + format!( + "'-{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); + } + if let Some(data) = flag.s.long { + let tooltip = get_tooltip(flag.b.help, data); + completions.push_str(&preamble); + completions.push_str( + format!( + "'--{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); + } + } + + for subcommand in &p.subcommands { + let data = &subcommand.p.meta.name; + let tooltip = get_tooltip(subcommand.p.meta.about, data); + completions.push_str(&preamble); + completions.push_str( + format!( + "'{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterValue", tooltip + ) + .as_str(), + ); + } + + let mut subcommands_cases = format!( + r" + '{}' {{{} + break + }}", + &command_name, completions + ); + + for subcommand in &p.subcommands { + let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names); + subcommands_cases.push_str(&subcommand_subcommands_cases); + } + + subcommands_cases +} diff --git a/bash-5.1/vendor/clap/src/completions/shell.rs b/bash-5.1/vendor/clap/src/completions/shell.rs new file mode 100644 index 0000000..aa5034c --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/shell.rs @@ -0,0 +1,56 @@ +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; +use std::fmt; +use std::str::FromStr; + +/// Describes which shell to produce a completions file for +#[derive(Debug, Copy, Clone)] +pub enum Shell { + /// Generates a .bash completion file for the Bourne Again SHell (BASH) + Bash, + /// Generates a .fish completion file for the Friendly Interactive SHell (fish) + Fish, + /// Generates a completion file for the Z SHell (ZSH) + Zsh, + /// Generates a completion file for PowerShell + PowerShell, + /// Generates a completion file for Elvish + Elvish, +} + +impl Shell { + /// A list of possible variants in `&'static str` form + pub fn variants() -> [&'static str; 5] { + ["zsh", "bash", "fish", "powershell", "elvish"] + } +} + +impl FromStr for Shell { + type Err = String; + + #[cfg_attr(feature = "cargo-clippy", allow(clippy::wildcard_in_or_patterns))] + fn from_str(s: &str) -> Result { + match s { + "ZSH" | _ if s.eq_ignore_ascii_case("zsh") => Ok(Shell::Zsh), + "FISH" | _ if s.eq_ignore_ascii_case("fish") => Ok(Shell::Fish), + "BASH" | _ if s.eq_ignore_ascii_case("bash") => Ok(Shell::Bash), + "POWERSHELL" | _ if s.eq_ignore_ascii_case("powershell") => Ok(Shell::PowerShell), + "ELVISH" | _ if s.eq_ignore_ascii_case("elvish") => Ok(Shell::Elvish), + _ => Err(String::from( + "[valid values: bash, fish, zsh, powershell, elvish]", + )), + } + } +} + +impl fmt::Display for Shell { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Shell::Bash => write!(f, "BASH"), + Shell::Fish => write!(f, "FISH"), + Shell::Zsh => write!(f, "ZSH"), + Shell::PowerShell => write!(f, "POWERSHELL"), + Shell::Elvish => write!(f, "ELVISH"), + } + } +} diff --git a/bash-5.1/vendor/clap/src/completions/zsh.rs b/bash-5.1/vendor/clap/src/completions/zsh.rs new file mode 100644 index 0000000..e8ddfbd --- /dev/null +++ b/bash-5.1/vendor/clap/src/completions/zsh.rs @@ -0,0 +1,484 @@ +// Std +#[allow(deprecated, unused_imports)] +use std::{ascii::AsciiExt, io::Write}; + +// Internal +use crate::{ + app::{parser::Parser, App}, + args::{AnyArg, ArgSettings}, + completions, INTERNAL_ERROR_MSG, +}; + +pub struct ZshGen<'a, 'b> +where + 'a: 'b, +{ + p: &'b Parser<'a, 'b>, +} + +impl<'a, 'b> ZshGen<'a, 'b> { + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + debugln!("ZshGen::new;"); + ZshGen { p } + } + + pub fn generate_to(&self, buf: &mut W) { + debugln!("ZshGen::generate_to;"); + w!( + buf, + format!( + "\ +#compdef {name} + +autoload -U is-at-least + +_{name}() {{ + typeset -A opt_args + typeset -a _arguments_options + local ret=1 + + if is-at-least 5.2; then + _arguments_options=(-s -S -C) + else + _arguments_options=(-s -C) + fi + + local context curcontext=\"$curcontext\" state line + {initial_args} + {subcommands} +}} + +{subcommand_details} + +_{name} \"$@\"", + name = self.p.meta.bin_name.as_ref().unwrap(), + initial_args = get_args_of(self.p), + subcommands = get_subcommands_of(self.p), + subcommand_details = subcommand_details(self.p) + ) + .as_bytes() + ); + } +} + +// Displays the commands of a subcommand +// (( $+functions[_[bin_name_underscore]_commands] )) || +// _[bin_name_underscore]_commands() { +// local commands; commands=( +// '[arg_name]:[arg_help]' +// ) +// _describe -t commands '[bin_name] commands' commands "$@" +// +// Where the following variables are present: +// [bin_name_underscore]: The full space delineated bin_name, where spaces have been replaced by +// underscore characters +// [arg_name]: The name of the subcommand +// [arg_help]: The help message of the subcommand +// [bin_name]: The full space delineated bin_name +// +// Here's a snippet from rustup: +// +// (( $+functions[_rustup_commands] )) || +// _rustup_commands() { +// local commands; commands=( +// 'show:Show the active and installed toolchains' +// 'update:Update Rust toolchains' +// # ... snip for brevity +// 'help:Prints this message or the help of the given subcommand(s)' +// ) +// _describe -t commands 'rustup commands' commands "$@" +// +fn subcommand_details(p: &Parser) -> String { + debugln!("ZshGen::subcommand_details;"); + // First we do ourself + let mut ret = vec![format!( + "\ +(( $+functions[_{bin_name_underscore}_commands] )) || +_{bin_name_underscore}_commands() {{ + local commands; commands=( + {subcommands_and_args} + ) + _describe -t commands '{bin_name} commands' commands \"$@\" +}}", + bin_name_underscore = p.meta.bin_name.as_ref().unwrap().replace(" ", "__"), + bin_name = p.meta.bin_name.as_ref().unwrap(), + subcommands_and_args = subcommands_of(p) + )]; + + // Next we start looping through all the children, grandchildren, etc. + let mut all_subcommands = completions::all_subcommands(p); + all_subcommands.sort(); + all_subcommands.dedup(); + for &(_, ref bin_name) in &all_subcommands { + debugln!("ZshGen::subcommand_details:iter: bin_name={}", bin_name); + ret.push(format!( + "\ +(( $+functions[_{bin_name_underscore}_commands] )) || +_{bin_name_underscore}_commands() {{ + local commands; commands=( + {subcommands_and_args} + ) + _describe -t commands '{bin_name} commands' commands \"$@\" +}}", + bin_name_underscore = bin_name.replace(" ", "__"), + bin_name = bin_name, + subcommands_and_args = subcommands_of(parser_of(p, bin_name)) + )); + } + + ret.join("\n") +} + +// Generates subcommand completions in form of +// +// '[arg_name]:[arg_help]' +// +// Where: +// [arg_name]: the subcommand's name +// [arg_help]: the help message of the subcommand +// +// A snippet from rustup: +// 'show:Show the active and installed toolchains' +// 'update:Update Rust toolchains' +fn subcommands_of(p: &Parser) -> String { + debugln!("ZshGen::subcommands_of;"); + let mut ret = vec![]; + fn add_sc(sc: &App, n: &str, ret: &mut Vec) { + debugln!("ZshGen::add_sc;"); + let s = format!( + "\"{name}:{help}\" \\", + name = n, + help = + sc.p.meta + .about + .unwrap_or("") + .replace("[", "\\[") + .replace("]", "\\]") + ); + if !s.is_empty() { + ret.push(s); + } + } + + // The subcommands + for sc in p.subcommands() { + debugln!("ZshGen::subcommands_of:iter: subcommand={}", sc.p.meta.name); + add_sc(sc, &sc.p.meta.name, &mut ret); + if let Some(ref v) = sc.p.meta.aliases { + for alias in v.iter().filter(|&&(_, vis)| vis).map(|&(n, _)| n) { + add_sc(sc, alias, &mut ret); + } + } + } + + ret.join("\n") +} + +// Get's the subcommand section of a completion file +// This looks roughly like: +// +// case $state in +// ([bin_name]_args) +// curcontext=\"${curcontext%:*:*}:[name_hyphen]-command-$words[1]:\" +// case $line[1] in +// +// ([name]) +// _arguments -C -s -S \ +// [subcommand_args] +// && ret=0 +// +// [RECURSIVE_CALLS] +// +// ;;", +// +// [repeat] +// +// esac +// ;; +// esac", +// +// Where the following variables are present: +// [name] = The subcommand name in the form of "install" for "rustup toolchain install" +// [bin_name] = The full space delineated bin_name such as "rustup toolchain install" +// [name_hyphen] = The full space delineated bin_name, but replace spaces with hyphens +// [repeat] = From the same recursive calls, but for all subcommands +// [subcommand_args] = The same as zsh::get_args_of +fn get_subcommands_of(p: &Parser) -> String { + debugln!("get_subcommands_of;"); + + debugln!( + "get_subcommands_of: Has subcommands...{:?}", + p.has_subcommands() + ); + if !p.has_subcommands() { + return String::new(); + } + + let sc_names = completions::subcommands_of(p); + + let mut subcmds = vec![]; + for &(ref name, ref bin_name) in &sc_names { + let mut v = vec![format!("({})", name)]; + let subcommand_args = get_args_of(parser_of(p, &*bin_name)); + if !subcommand_args.is_empty() { + v.push(subcommand_args); + } + let subcommands = get_subcommands_of(parser_of(p, &*bin_name)); + if !subcommands.is_empty() { + v.push(subcommands); + } + v.push(String::from(";;")); + subcmds.push(v.join("\n")); + } + + format!( + "case $state in + ({name}) + words=($line[{pos}] \"${{words[@]}}\") + (( CURRENT += 1 )) + curcontext=\"${{curcontext%:*:*}}:{name_hyphen}-command-$line[{pos}]:\" + case $line[{pos}] in + {subcommands} + esac + ;; +esac", + name = p.meta.name, + name_hyphen = p.meta.bin_name.as_ref().unwrap().replace(" ", "-"), + subcommands = subcmds.join("\n"), + pos = p.positionals().len() + 1 + ) +} + +fn parser_of<'a, 'b>(p: &'b Parser<'a, 'b>, sc: &str) -> &'b Parser<'a, 'b> { + debugln!("parser_of: sc={}", sc); + if sc == p.meta.bin_name.as_ref().unwrap_or(&String::new()) { + return p; + } + &p.find_subcommand(sc).expect(INTERNAL_ERROR_MSG).p +} + +// Writes out the args section, which ends up being the flags, opts and postionals, and a jump to +// another ZSH function if there are subcommands. +// The structer works like this: +// ([conflicting_args]) [multiple] arg [takes_value] [[help]] [: :(possible_values)] +// ^-- list '-v -h' ^--'*' ^--'+' ^-- list 'one two three' +// +// An example from the rustup command: +// +// _arguments -C -s -S \ +// '(-h --help --verbose)-v[Enable verbose output]' \ +// '(-V -v --version --verbose --help)-h[Prints help information]' \ +// # ... snip for brevity +// ':: :_rustup_commands' \ # <-- displays subcommands +// '*::: :->rustup' \ # <-- displays subcommand args and child subcommands +// && ret=0 +// +// The args used for _arguments are as follows: +// -C: modify the $context internal variable +// -s: Allow stacking of short args (i.e. -a -b -c => -abc) +// -S: Do not complete anything after '--' and treat those as argument values +fn get_args_of(p: &Parser) -> String { + debugln!("get_args_of;"); + let mut ret = vec![String::from("_arguments \"${_arguments_options[@]}\" \\")]; + let opts = write_opts_of(p); + let flags = write_flags_of(p); + let positionals = write_positionals_of(p); + let sc_or_a = if p.has_subcommands() { + format!( + "\":: :_{name}_commands\" \\", + name = p.meta.bin_name.as_ref().unwrap().replace(" ", "__") + ) + } else { + String::new() + }; + let sc = if p.has_subcommands() { + format!("\"*::: :->{name}\" \\", name = p.meta.name) + } else { + String::new() + }; + + if !opts.is_empty() { + ret.push(opts); + } + if !flags.is_empty() { + ret.push(flags); + } + if !positionals.is_empty() { + ret.push(positionals); + } + if !sc_or_a.is_empty() { + ret.push(sc_or_a); + } + if !sc.is_empty() { + ret.push(sc); + } + ret.push(String::from("&& ret=0")); + + ret.join("\n") +} + +// Escape help string inside single quotes and brackets +fn escape_help(string: &str) -> String { + string + .replace("\\", "\\\\") + .replace("'", "'\\''") + .replace("[", "\\[") + .replace("]", "\\]") +} + +// Escape value string inside single quotes and parentheses +fn escape_value(string: &str) -> String { + string + .replace("\\", "\\\\") + .replace("'", "'\\''") + .replace("(", "\\(") + .replace(")", "\\)") + .replace(" ", "\\ ") +} + +fn write_opts_of(p: &Parser) -> String { + debugln!("write_opts_of;"); + let mut ret = vec![]; + for o in p.opts() { + debugln!("write_opts_of:iter: o={}", o.name()); + let help = o.help().map_or(String::new(), escape_help); + let mut conflicts = get_zsh_arg_conflicts!(p, o, INTERNAL_ERROR_MSG); + conflicts = if conflicts.is_empty() { + String::new() + } else { + format!("({})", conflicts) + }; + + let multiple = if o.is_set(ArgSettings::Multiple) { + "*" + } else { + "" + }; + let pv = if let Some(pv_vec) = o.possible_vals() { + format!( + ": :({})", + pv_vec + .iter() + .map(|v| escape_value(*v)) + .collect::>() + .join(" ") + ) + } else { + String::new() + }; + if let Some(short) = o.short() { + let s = format!( + "'{conflicts}{multiple}-{arg}+[{help}]{possible_values}' \\", + conflicts = conflicts, + multiple = multiple, + arg = short, + possible_values = pv, + help = help + ); + + debugln!("write_opts_of:iter: Wrote...{}", &*s); + ret.push(s); + } + if let Some(long) = o.long() { + let l = format!( + "'{conflicts}{multiple}--{arg}=[{help}]{possible_values}' \\", + conflicts = conflicts, + multiple = multiple, + arg = long, + possible_values = pv, + help = help + ); + + debugln!("write_opts_of:iter: Wrote...{}", &*l); + ret.push(l); + } + } + + ret.join("\n") +} + +fn write_flags_of(p: &Parser) -> String { + debugln!("write_flags_of;"); + let mut ret = vec![]; + for f in p.flags() { + debugln!("write_flags_of:iter: f={}", f.name()); + let help = f.help().map_or(String::new(), escape_help); + let mut conflicts = get_zsh_arg_conflicts!(p, f, INTERNAL_ERROR_MSG); + conflicts = if conflicts.is_empty() { + String::new() + } else { + format!("({})", conflicts) + }; + + let multiple = if f.is_set(ArgSettings::Multiple) { + "*" + } else { + "" + }; + if let Some(short) = f.short() { + let s = format!( + "'{conflicts}{multiple}-{arg}[{help}]' \\", + multiple = multiple, + conflicts = conflicts, + arg = short, + help = help + ); + + debugln!("write_flags_of:iter: Wrote...{}", &*s); + ret.push(s); + } + + if let Some(long) = f.long() { + let l = format!( + "'{conflicts}{multiple}--{arg}[{help}]' \\", + conflicts = conflicts, + multiple = multiple, + arg = long, + help = help + ); + + debugln!("write_flags_of:iter: Wrote...{}", &*l); + ret.push(l); + } + } + + ret.join("\n") +} + +fn write_positionals_of(p: &Parser) -> String { + debugln!("write_positionals_of;"); + let mut ret = vec![]; + for arg in p.positionals() { + debugln!("write_positionals_of:iter: arg={}", arg.b.name); + let a = format!( + "'{optional}:{name}{help}:{action}' \\", + optional = if !arg.b.is_set(ArgSettings::Required) { + ":" + } else { + "" + }, + name = arg.b.name, + help = arg + .b + .help + .map_or("".to_owned(), |v| " -- ".to_owned() + v) + .replace("[", "\\[") + .replace("]", "\\]"), + action = arg.possible_vals().map_or("_files".to_owned(), |values| { + format!( + "({})", + values + .iter() + .map(|v| escape_value(*v)) + .collect::>() + .join(" ") + ) + }) + ); + + debugln!("write_positionals_of:iter: Wrote...{}", a); + ret.push(a); + } + + ret.join("\n") +} diff --git a/bash-5.1/vendor/clap/src/errors.rs b/bash-5.1/vendor/clap/src/errors.rs new file mode 100644 index 0000000..df01bb1 --- /dev/null +++ b/bash-5.1/vendor/clap/src/errors.rs @@ -0,0 +1,933 @@ +// Std +use std::{ + convert::From, + error::Error as StdError, + fmt as std_fmt, + fmt::Display, + io::{self, Write}, + process, + result::Result as StdResult, +}; + +// Internal +use crate::{ + args::AnyArg, + fmt::{ColorWhen, Colorizer, ColorizerOption}, + suggestions, +}; + +/// Short hand for [`Result`] type +/// +/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html +pub type Result = StdResult; + +/// Command line argument parser kind of error +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum ErrorKind { + /// Occurs when an [`Arg`] has a set of possible values, + /// and the user provides a value which isn't in that set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("speed") + /// .possible_value("fast") + /// .possible_value("slow")) + /// .get_matches_from_safe(vec!["prog", "other"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidValue); + /// ``` + /// [`Arg`]: ./struct.Arg.html + InvalidValue, + + /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::from_usage("--flag 'some flag'")) + /// .get_matches_from_safe(vec!["prog", "--other"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + UnknownArgument, + + /// Occurs when the user provides an unrecognized [`SubCommand`] which meets the threshold for + /// being similar enough to an existing subcommand. + /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, + /// the more general [`UnknownArgument`] error is returned. + /// + /// # Examples + /// + #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] + #[cfg_attr(feature = "suggestions", doc = " ```")] + /// # use clap::{App, Arg, ErrorKind, SubCommand}; + /// let result = App::new("prog") + /// .subcommand(SubCommand::with_name("config") + /// .about("Used for configuration") + /// .arg(Arg::with_name("config_file") + /// .help("The configuration file to use") + /// .index(1))) + /// .get_matches_from_safe(vec!["prog", "confi"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidSubcommand); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument + InvalidSubcommand, + + /// Occurs when the user provides an unrecognized [`SubCommand`] which either + /// doesn't meet the threshold for being similar enough to an existing subcommand, + /// or the 'suggestions' feature is disabled. + /// Otherwise the more detailed [`InvalidSubcommand`] error is returned. + /// + /// This error typically happens when passing additional subcommand names to the `help` + /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind, SubCommand}; + /// let result = App::new("prog") + /// .subcommand(SubCommand::with_name("config") + /// .about("Used for configuration") + /// .arg(Arg::with_name("config_file") + /// .help("The configuration file to use") + /// .index(1))) + /// .get_matches_from_safe(vec!["prog", "help", "nothing"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`InvalidSubcommand`]: ./enum.ErrorKind.html#variant.InvalidSubcommand + /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument + UnrecognizedSubcommand, + + /// Occurs when the user provides an empty value for an option that does not allow empty + /// values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::with_name("color") + /// .long("color") + /// .empty_values(false)) + /// .get_matches_from_safe(vec!["prog", "--color="]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); + /// ``` + EmptyValue, + + /// Occurs when the user provides a value for an argument with a custom validation and the + /// value fails that validation. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// fn is_numeric(val: String) -> Result<(), String> { + /// match val.parse::() { + /// Ok(..) => Ok(()), + /// Err(..) => Err(String::from("Value wasn't a number!")), + /// } + /// } + /// + /// let result = App::new("prog") + /// .arg(Arg::with_name("num") + /// .validator(is_numeric)) + /// .get_matches_from_safe(vec!["prog", "NotANumber"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::ValueValidation); + /// ``` + ValueValidation, + + /// Occurs when a user provides more values for an argument than were defined by setting + /// [`Arg::max_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("arg") + /// .multiple(true) + /// .max_values(2)) + /// .get_matches_from_safe(vec!["prog", "too", "many", "values"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooManyValues); + /// ``` + /// [`Arg::max_values`]: ./struct.Arg.html#method.max_values + TooManyValues, + + /// Occurs when the user provides fewer values for an argument than were defined by setting + /// [`Arg::min_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("some_opt") + /// .long("opt") + /// .min_values(3)) + /// .get_matches_from_safe(vec!["prog", "--opt", "too", "few"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooFewValues); + /// ``` + /// [`Arg::min_values`]: ./struct.Arg.html#method.min_values + TooFewValues, + + /// Occurs when the user provides a different number of values for an argument than what's + /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by + /// [`Arg::value_names`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("some_opt") + /// .long("opt") + /// .takes_value(true) + /// .number_of_values(2)) + /// .get_matches_from_safe(vec!["prog", "--opt", "wrong"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::WrongNumberOfValues); + /// ``` + /// + /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values + /// [`Arg::value_names`]: ./struct.Arg.html#method.value_names + WrongNumberOfValues, + + /// Occurs when the user provides two values which conflict with each other and can't be used + /// together. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("debug") + /// .long("debug") + /// .conflicts_with("color")) + /// .arg(Arg::with_name("color") + /// .long("color")) + /// .get_matches_from_safe(vec!["prog", "--debug", "--color"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::ArgumentConflict); + /// ``` + ArgumentConflict, + + /// Occurs when the user does not provide one or more required arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("debug") + /// .required(true)) + /// .get_matches_from_safe(vec!["prog"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// ``` + MissingRequiredArgument, + + /// Occurs when a subcommand is required (as defined by [`AppSettings::SubcommandRequired`]), + /// but the user does not provide one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, SubCommand, ErrorKind}; + /// let err = App::new("prog") + /// .setting(AppSettings::SubcommandRequired) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired + MissingSubcommand, + + /// Occurs when either an argument or [`SubCommand`] is required, as defined by + /// [`AppSettings::ArgRequiredElseHelp`], but the user did not provide one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, ErrorKind, SubCommand}; + /// let result = App::new("prog") + /// .setting(AppSettings::ArgRequiredElseHelp) + /// .subcommand(SubCommand::with_name("config") + /// .about("Used for configuration") + /// .arg(Arg::with_name("config_file") + /// .help("The configuration file to use"))) + /// .get_matches_from_safe(vec!["prog"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingArgumentOrSubcommand); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp + MissingArgumentOrSubcommand, + + /// Occurs when the user provides multiple values to an argument which doesn't allow that. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::with_name("debug") + /// .long("debug") + /// .multiple(false)) + /// .get_matches_from_safe(vec!["prog", "--debug", "--debug"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnexpectedMultipleUsage); + /// ``` + UnexpectedMultipleUsage, + + /// Occurs when the user provides a value containing invalid UTF-8 for an argument and + /// [`AppSettings::StrictUtf8`] is set. + /// + /// # Platform Specific + /// + /// Non-Windows platforms only (such as Linux, Unix, macOS, etc.) + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, Arg, ErrorKind, AppSettings}; + /// # use std::os::unix::ffi::OsStringExt; + /// # use std::ffi::OsString; + /// let result = App::new("prog") + /// .setting(AppSettings::StrictUtf8) + /// .arg(Arg::with_name("utf8") + /// .short("u") + /// .takes_value(true)) + /// .get_matches_from_safe(vec![OsString::from("myprog"), + /// OsString::from("-u"), + /// OsString::from_vec(vec![0xE9])]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidUtf8); + /// ``` + /// [`AppSettings::StrictUtf8`]: ./enum.AppSettings.html#variant.StrictUtf8 + InvalidUtf8, + + /// Not a true "error" as it means `--help` or similar was used. + /// The help message will be sent to `stdout`. + /// + /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will + /// be sent to `stderr` instead of `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .get_matches_from_safe(vec!["prog", "--help"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::HelpDisplayed); + /// ``` + HelpDisplayed, + + /// Not a true "error" as it means `--version` or similar was used. + /// The message will be sent to `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .get_matches_from_safe(vec!["prog", "--version"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind, ErrorKind::VersionDisplayed); + /// ``` + VersionDisplayed, + + /// Occurs when using the [`value_t!`] and [`values_t!`] macros to convert an argument value + /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument + /// with name `config` to be converted, but `config` wasn't used by the user. + /// [`value_t!`]: ./macro.value_t!.html + /// [`values_t!`]: ./macro.values_t!.html + ArgumentNotFound, + + /// Represents an [I/O error]. + /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. + /// [I/O error]: https://doc.rust-lang.org/std/io/struct.Error.html + Io, + + /// Represents a [Format error] (which is a part of [`Display`]). + /// Typically caused by writing to `stderr` or `stdout`. + /// + /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html + /// [Format error]: https://doc.rust-lang.org/std/fmt/struct.Error.html + Format, +} + +/// Command Line Argument Parser Error +#[derive(Debug)] +pub struct Error { + /// Formatted error message + pub message: String, + /// The type of error + pub kind: ErrorKind, + /// Any additional information passed along, such as the argument name that caused the error + pub info: Option>, +} + +impl Error { + /// Should the message be written to `stdout` or not + pub fn use_stderr(&self) -> bool { + !matches!( + self.kind, + ErrorKind::HelpDisplayed | ErrorKind::VersionDisplayed + ) + } + + /// Prints the error message and exits. If `Error::use_stderr` evaluates to `true`, the message + /// will be written to `stderr` and exits with a status of `1`. Otherwise, `stdout` is used + /// with a status of `0`. + pub fn exit(&self) -> ! { + if self.use_stderr() { + wlnerr!(@nopanic "{}", self.message); + process::exit(1); + } + // We are deliberately dropping errors here. We could match on the error kind, and only + // drop things such as `std::io::ErrorKind::BrokenPipe`, however nothing is being bubbled + // up or reported back to the caller and we will be exit'ing the process anyways. + // Additionally, changing this API to bubble up the result would be a breaking change. + // + // Another approach could be to try and write to stdout, if that fails due to a broken pipe + // then use stderr. However, that would change the semantics in what could be argued is a + // breaking change. Simply dropping the error, can always be changed to this "use stderr if + // stdout is closed" approach later if desired. + // + // A good explanation of the types of errors are SIGPIPE where the read side of the pipe + // closes before the write side. See the README in `calm_io` for a good explanation: + // + // https://github.com/myrrlyn/calm_io/blob/a42845575a04cd8b65e92c19d104627f5fcad3d7/README.md + let _ = writeln!(&mut io::stdout().lock(), "{}", self.message); + process::exit(0); + } + + #[doc(hidden)] + pub fn write_to(&self, w: &mut W) -> io::Result<()> { + write!(w, "{}", self.message) + } + + #[doc(hidden)] + pub fn argument_conflict( + arg: &AnyArg, + other: Option, + usage: U, + color: ColorWhen, + ) -> Self + where + O: Into, + U: Display, + { + let mut v = vec![arg.name().to_owned()]; + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The argument '{}' cannot be used with {}\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(&*arg.to_string()), + match other { + Some(name) => { + let n = name.into(); + v.push(n.clone()); + c.warning(format!("'{}'", n)) + } + None => c.none("one or more of the other specified arguments".to_owned()), + }, + usage, + c.good("--help") + ), + kind: ErrorKind::ArgumentConflict, + info: Some(v), + } + } + + #[doc(hidden)] + pub fn empty_value(arg: &AnyArg, usage: U, color: ColorWhen) -> Self + where + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The argument '{}' requires a value but none was supplied\ + \n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(arg.to_string()), + usage, + c.good("--help") + ), + kind: ErrorKind::EmptyValue, + info: Some(vec![arg.name().to_owned()]), + } + } + + #[doc(hidden)] + pub fn invalid_value( + bad_val: B, + good_vals: &[G], + arg: &AnyArg, + usage: U, + color: ColorWhen, + ) -> Self + where + B: AsRef, + G: AsRef + Display, + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + let suffix = suggestions::did_you_mean_value_suffix(bad_val.as_ref(), good_vals.iter()); + + let mut sorted = vec![]; + for v in good_vals { + let val = format!("{}", c.good(v)); + sorted.push(val); + } + sorted.sort(); + let valid_values = sorted.join(", "); + Error { + message: format!( + "{} '{}' isn't a valid value for '{}'\n\t\ + [possible values: {}]\n\ + {}\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(bad_val.as_ref()), + c.warning(arg.to_string()), + valid_values, + suffix.0, + usage, + c.good("--help") + ), + kind: ErrorKind::InvalidValue, + info: Some(vec![arg.name().to_owned(), bad_val.as_ref().to_owned()]), + } + } + + #[doc(hidden)] + pub fn invalid_subcommand( + subcmd: S, + did_you_mean: D, + name: N, + usage: U, + color: ColorWhen, + ) -> Self + where + S: Into, + D: AsRef + Display, + N: Display, + U: Display, + { + let s = subcmd.into(); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The subcommand '{}' wasn't recognized\n\t\ + Did you mean '{}'?\n\n\ + If you believe you received this message in error, try \ + re-running with '{} {} {}'\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(&*s), + c.good(did_you_mean.as_ref()), + name, + c.good("--"), + &*s, + usage, + c.good("--help") + ), + kind: ErrorKind::InvalidSubcommand, + info: Some(vec![s]), + } + } + + #[doc(hidden)] + pub fn unrecognized_subcommand(subcmd: S, name: N, color: ColorWhen) -> Self + where + S: Into, + N: Display, + { + let s = subcmd.into(); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The subcommand '{}' wasn't recognized\n\n\ + {}\n\t\ + {} help ...\n\n\ + For more information try {}", + c.error("error:"), + c.warning(&*s), + c.warning("USAGE:"), + name, + c.good("--help") + ), + kind: ErrorKind::UnrecognizedSubcommand, + info: Some(vec![s]), + } + } + + #[doc(hidden)] + pub fn missing_required_argument(required: R, usage: U, color: ColorWhen) -> Self + where + R: Display, + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The following required arguments were not provided:{}\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + required, + usage, + c.good("--help") + ), + kind: ErrorKind::MissingRequiredArgument, + info: None, + } + } + + #[doc(hidden)] + pub fn missing_subcommand(name: N, usage: U, color: ColorWhen) -> Self + where + N: AsRef + Display, + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} '{}' requires a subcommand, but one was not provided\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(name), + usage, + c.good("--help") + ), + kind: ErrorKind::MissingSubcommand, + info: None, + } + } + + #[doc(hidden)] + pub fn invalid_utf8(usage: U, color: ColorWhen) -> Self + where + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} Invalid UTF-8 was detected in one or more arguments\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + usage, + c.good("--help") + ), + kind: ErrorKind::InvalidUtf8, + info: None, + } + } + + #[doc(hidden)] + pub fn too_many_values(val: V, arg: &AnyArg, usage: U, color: ColorWhen) -> Self + where + V: AsRef + Display + ToOwned, + U: Display, + { + let v = val.as_ref(); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The value '{}' was provided to '{}', but it wasn't expecting \ + any more values\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(v), + c.warning(arg.to_string()), + usage, + c.good("--help") + ), + kind: ErrorKind::TooManyValues, + info: Some(vec![arg.name().to_owned(), v.to_owned()]), + } + } + + #[doc(hidden)] + pub fn too_few_values( + arg: &AnyArg, + min_vals: u64, + curr_vals: usize, + usage: U, + color: ColorWhen, + ) -> Self + where + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The argument '{}' requires at least {} values, but only {} w{} \ + provided\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(arg.to_string()), + c.warning(min_vals.to_string()), + c.warning(curr_vals.to_string()), + if curr_vals > 1 { "ere" } else { "as" }, + usage, + c.good("--help") + ), + kind: ErrorKind::TooFewValues, + info: Some(vec![arg.name().to_owned()]), + } + } + + #[doc(hidden)] + pub fn value_validation(arg: Option<&AnyArg>, err: String, color: ColorWhen) -> Self { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} Invalid value{}: {}", + c.error("error:"), + if let Some(a) = arg { + format!(" for '{}'", c.warning(a.to_string())) + } else { + "".to_string() + }, + err + ), + kind: ErrorKind::ValueValidation, + info: None, + } + } + + #[doc(hidden)] + pub fn value_validation_auto(err: String) -> Self { + let n: Option<&AnyArg> = None; + Error::value_validation(n, err, ColorWhen::Auto) + } + + #[doc(hidden)] + pub fn wrong_number_of_values( + arg: &AnyArg, + num_vals: u64, + curr_vals: usize, + suffix: S, + usage: U, + color: ColorWhen, + ) -> Self + where + S: Display, + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The argument '{}' requires {} values, but {} w{} \ + provided\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(arg.to_string()), + c.warning(num_vals.to_string()), + c.warning(curr_vals.to_string()), + suffix, + usage, + c.good("--help") + ), + kind: ErrorKind::WrongNumberOfValues, + info: Some(vec![arg.name().to_owned()]), + } + } + + #[doc(hidden)] + pub fn unexpected_multiple_usage(arg: &AnyArg, usage: U, color: ColorWhen) -> Self + where + U: Display, + { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} The argument '{}' was provided more than once, but cannot \ + be used multiple times\n\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(arg.to_string()), + usage, + c.good("--help") + ), + kind: ErrorKind::UnexpectedMultipleUsage, + info: Some(vec![arg.name().to_owned()]), + } + } + + #[doc(hidden)] + pub fn unknown_argument(arg: A, did_you_mean: &str, usage: U, color: ColorWhen) -> Self + where + A: Into, + U: Display, + { + let a = arg.into(); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!( + "{} Found argument '{}' which wasn't expected, or isn't valid in \ + this context{}\n\ + {}\n\n\ + For more information try {}", + c.error("error:"), + c.warning(&*a), + if did_you_mean.is_empty() { + "\n".to_owned() + } else { + format!("{}\n", did_you_mean) + }, + usage, + c.good("--help") + ), + kind: ErrorKind::UnknownArgument, + info: Some(vec![a]), + } + } + + #[doc(hidden)] + pub fn io_error(e: &Error, color: ColorWhen) -> Self { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: color, + }); + Error { + message: format!("{} {}", c.error("error:"), e.description()), + kind: ErrorKind::Io, + info: None, + } + } + + #[doc(hidden)] + pub fn argument_not_found_auto(arg: A) -> Self + where + A: Into, + { + let a = arg.into(); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: ColorWhen::Auto, + }); + Error { + message: format!("{} The argument '{}' wasn't found", c.error("error:"), a), + kind: ErrorKind::ArgumentNotFound, + info: Some(vec![a]), + } + } + + /// Create an error with a custom description. + /// + /// This can be used in combination with `Error::exit` to exit your program + /// with a custom error message. + pub fn with_description(description: &str, kind: ErrorKind) -> Self { + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: ColorWhen::Auto, + }); + Error { + message: format!("{} {}", c.error("error:"), description), + kind, + info: None, + } + } +} + +impl StdError for Error { + fn description(&self) -> &str { + &*self.message + } +} + +impl Display for Error { + fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result { + writeln!(f, "{}", self.message) + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::with_description(e.description(), ErrorKind::Io) + } +} + +impl From for Error { + fn from(e: std_fmt::Error) -> Self { + Error::with_description(e.description(), ErrorKind::Format) + } +} diff --git a/bash-5.1/vendor/clap/src/fmt.rs b/bash-5.1/vendor/clap/src/fmt.rs new file mode 100644 index 0000000..f447565 --- /dev/null +++ b/bash-5.1/vendor/clap/src/fmt.rs @@ -0,0 +1,192 @@ +#[cfg(all(feature = "color", not(target_os = "windows")))] +use ansi_term::ANSIString; + +#[cfg(all(feature = "color", not(target_os = "windows")))] +use ansi_term::Colour::{Green, Red, Yellow}; + +use std::env; +use std::fmt; + +#[doc(hidden)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum ColorWhen { + Auto, + Always, + Never, +} + +#[cfg(feature = "color")] +pub fn is_a_tty(stderr: bool) -> bool { + debugln!("is_a_tty: stderr={:?}", stderr); + let stream = if stderr { + atty::Stream::Stderr + } else { + atty::Stream::Stdout + }; + atty::is(stream) +} + +#[cfg(not(feature = "color"))] +pub fn is_a_tty(_: bool) -> bool { + debugln!("is_a_tty;"); + false +} + +pub fn is_term_dumb() -> bool { + env::var("TERM").ok() == Some(String::from("dumb")) +} + +#[doc(hidden)] +pub struct ColorizerOption { + pub use_stderr: bool, + pub when: ColorWhen, +} + +#[doc(hidden)] +pub struct Colorizer { + when: ColorWhen, +} + +macro_rules! color { + ($_self:ident, $c:ident, $m:expr) => { + match $_self.when { + ColorWhen::Auto => Format::$c($m), + ColorWhen::Always => Format::$c($m), + ColorWhen::Never => Format::None($m), + } + }; +} + +impl Colorizer { + pub fn new(option: ColorizerOption) -> Colorizer { + let is_a_tty = is_a_tty(option.use_stderr); + let is_term_dumb = is_term_dumb(); + Colorizer { + when: match option.when { + ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto, + ColorWhen::Auto => ColorWhen::Never, + when => when, + }, + } + } + + pub fn good(&self, msg: T) -> Format + where + T: fmt::Display + AsRef, + { + debugln!("Colorizer::good;"); + color!(self, Good, msg) + } + + pub fn warning(&self, msg: T) -> Format + where + T: fmt::Display + AsRef, + { + debugln!("Colorizer::warning;"); + color!(self, Warning, msg) + } + + pub fn error(&self, msg: T) -> Format + where + T: fmt::Display + AsRef, + { + debugln!("Colorizer::error;"); + color!(self, Error, msg) + } + + pub fn none(&self, msg: T) -> Format + where + T: fmt::Display + AsRef, + { + debugln!("Colorizer::none;"); + Format::None(msg) + } +} + +impl Default for Colorizer { + fn default() -> Self { + Colorizer::new(ColorizerOption { + use_stderr: true, + when: ColorWhen::Auto, + }) + } +} + +/// Defines styles for different types of error messages. Defaults to Error=Red, Warning=Yellow, +/// and Good=Green +#[derive(Debug)] +#[doc(hidden)] +pub enum Format { + /// Defines the style used for errors, defaults to Red + Error(T), + /// Defines the style used for warnings, defaults to Yellow + Warning(T), + /// Defines the style used for good values, defaults to Green + Good(T), + /// Defines no formatting style + None(T), +} + +#[cfg(all(feature = "color", not(target_os = "windows")))] +impl> Format { + fn format(&self) -> ANSIString { + match *self { + Format::Error(ref e) => Red.bold().paint(e.as_ref()), + Format::Warning(ref e) => Yellow.paint(e.as_ref()), + Format::Good(ref e) => Green.paint(e.as_ref()), + Format::None(ref e) => ANSIString::from(e.as_ref()), + } + } +} + +#[cfg(any(not(feature = "color"), target_os = "windows"))] +#[cfg_attr(feature = "cargo-clippy", allow(clippy::match_same_arms))] +impl Format { + fn format(&self) -> &T { + match *self { + Format::Error(ref e) => e, + Format::Warning(ref e) => e, + Format::Good(ref e) => e, + Format::None(ref e) => e, + } + } +} + +#[cfg(all(feature = "color", not(target_os = "windows")))] +impl> fmt::Display for Format { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", &self.format()) + } +} + +#[cfg(any(not(feature = "color"), target_os = "windows"))] +impl fmt::Display for Format { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", &self.format()) + } +} + +#[cfg(all(test, feature = "color", not(target_os = "windows")))] +mod test { + use super::Format; + use ansi_term::ANSIString; + use ansi_term::Colour::{Green, Red, Yellow}; + + #[test] + fn colored_output() { + let err = Format::Error("error"); + assert_eq!( + &*format!("{}", err), + &*format!("{}", Red.bold().paint("error")) + ); + let good = Format::Good("good"); + assert_eq!(&*format!("{}", good), &*format!("{}", Green.paint("good"))); + let warn = Format::Warning("warn"); + assert_eq!(&*format!("{}", warn), &*format!("{}", Yellow.paint("warn"))); + let none = Format::None("none"); + assert_eq!( + &*format!("{}", none), + &*format!("{}", ANSIString::from("none")) + ); + } +} diff --git a/bash-5.1/vendor/clap/src/lib.rs b/bash-5.1/vendor/clap/src/lib.rs new file mode 100644 index 0000000..8c47b77 --- /dev/null +++ b/bash-5.1/vendor/clap/src/lib.rs @@ -0,0 +1,638 @@ +// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/v2.33.1/CONTRIBUTORS.md). +// Licensed under the MIT license +// (see LICENSE or ) All files in the project carrying such +// notice may not be copied, modified, or distributed except according to those terms. + +//! `clap` is a simple-to-use, efficient, and full-featured library for parsing command line +//! arguments and subcommands when writing console/terminal applications. +//! +//! ## About +//! +//! `clap` is used to parse *and validate* the string of command line arguments provided by the user +//! at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means +//! you focus on your *applications* functionality, and less on the parsing and validating of +//! arguments. +//! +//! `clap` also provides the traditional version and help switches (or flags) 'for free' meaning +//! automatically with no configuration. It does this by checking the list of valid possibilities you +//! supplied and adding only the ones you haven't already defined. If you are using subcommands, +//! `clap` will also auto-generate a `help` subcommand for you in addition to the traditional flags. +//! +//! Once `clap` parses the user provided string of arguments, it returns the matches along with any +//! applicable values. If the user made an error or typo, `clap` informs them of the mistake and +//! exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to +//! exit). Because of this, you can make reasonable assumptions in your code about the validity of +//! the arguments. +//! +//! +//! ## Quick Example +//! +//! The following examples show a quick example of some of the very basic functionality of `clap`. +//! For more advanced usage, such as requirements, conflicts, groups, multiple values and +//! occurrences see the [documentation](https://docs.rs/clap/), [examples/] directory of +//! this repository or the [video tutorials]. +//! +//! **NOTE:** All of these examples are functionally the same, but show different styles in which to +//! use `clap` +//! +//! The first example shows a method that allows more advanced configuration options (not shown in +//! this small example), or even dynamically generating arguments when desired. The downside is it's +//! more verbose. +//! +//! ```no_run +//! // (Full example with detailed comments in examples/01b_quick_example.rs) +//! // +//! // This example demonstrates clap's full 'builder pattern' style of creating arguments which is +//! // more verbose, but allows easier editing, and at times more advanced options, or the possibility +//! // to generate arguments dynamically. +//! extern crate clap; +//! use clap::{Arg, App, SubCommand}; +//! +//! fn main() { +//! let matches = App::new("My Super Program") +//! .version("1.0") +//! .author("Kevin K. ") +//! .about("Does awesome things") +//! .arg(Arg::with_name("config") +//! .short("c") +//! .long("config") +//! .value_name("FILE") +//! .help("Sets a custom config file") +//! .takes_value(true)) +//! .arg(Arg::with_name("INPUT") +//! .help("Sets the input file to use") +//! .required(true) +//! .index(1)) +//! .arg(Arg::with_name("v") +//! .short("v") +//! .multiple(true) +//! .help("Sets the level of verbosity")) +//! .subcommand(SubCommand::with_name("test") +//! .about("controls testing features") +//! .version("1.3") +//! .author("Someone E. ") +//! .arg(Arg::with_name("debug") +//! .short("d") +//! .help("print debug information verbosely"))) +//! .get_matches(); +//! +//! // Gets a value for config if supplied by user, or defaults to "default.conf" +//! let config = matches.value_of("config").unwrap_or("default.conf"); +//! println!("Value for config: {}", config); +//! +//! // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't +//! // required we could have used an 'if let' to conditionally get the value) +//! println!("Using input file: {}", matches.value_of("INPUT").unwrap()); +//! +//! // Vary the output based on how many times the user used the "verbose" flag +//! // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v' +//! match matches.occurrences_of("v") { +//! 0 => println!("No verbose info"), +//! 1 => println!("Some verbose info"), +//! 2 => println!("Tons of verbose info"), +//! 3 | _ => println!("Don't be crazy"), +//! } +//! +//! // You can handle information about subcommands by requesting their matches by name +//! // (as below), requesting just the name used, or both at the same time +//! if let Some(matches) = matches.subcommand_matches("test") { +//! if matches.is_present("debug") { +//! println!("Printing debug info..."); +//! } else { +//! println!("Printing normally..."); +//! } +//! } +//! +//! // more program logic goes here... +//! } +//! ``` +//! +//! The next example shows a far less verbose method, but sacrifices some of the advanced +//! configuration options (not shown in this small example). This method also takes a *very* minor +//! runtime penalty. +//! +//! ```no_run +//! // (Full example with detailed comments in examples/01a_quick_example.rs) +//! // +//! // This example demonstrates clap's "usage strings" method of creating arguments +//! // which is less verbose +//! extern crate clap; +//! use clap::{Arg, App, SubCommand}; +//! +//! fn main() { +//! let matches = App::new("myapp") +//! .version("1.0") +//! .author("Kevin K. ") +//! .about("Does awesome things") +//! .args_from_usage( +//! "-c, --config=[FILE] 'Sets a custom config file' +//! 'Sets the input file to use' +//! -v... 'Sets the level of verbosity'") +//! .subcommand(SubCommand::with_name("test") +//! .about("controls testing features") +//! .version("1.3") +//! .author("Someone E. ") +//! .arg_from_usage("-d, --debug 'Print debug information'")) +//! .get_matches(); +//! +//! // Same as previous example... +//! } +//! ``` +//! +//! This third method shows how you can use a YAML file to build your CLI and keep your Rust source +//! tidy or support multiple localized translations by having different YAML files for each +//! localization. +//! +//! First, create the `cli.yml` file to hold your CLI options, but it could be called anything we +//! like: +//! +//! ```yaml +//! name: myapp +//! version: "1.0" +//! author: Kevin K. +//! about: Does awesome things +//! args: +//! - config: +//! short: c +//! long: config +//! value_name: FILE +//! help: Sets a custom config file +//! takes_value: true +//! - INPUT: +//! help: Sets the input file to use +//! required: true +//! index: 1 +//! - verbose: +//! short: v +//! multiple: true +//! help: Sets the level of verbosity +//! subcommands: +//! - test: +//! about: controls testing features +//! version: "1.3" +//! author: Someone E. +//! args: +//! - debug: +//! short: d +//! help: print debug information +//! ``` +//! +//! Since this feature requires additional dependencies that not everyone may want, it is *not* +//! compiled in by default and we need to enable a feature flag in Cargo.toml: +//! +//! Simply change your `clap = "~2.27.0"` to `clap = {version = "~2.27.0", features = ["yaml"]}`. +//! +//! At last we create our `main.rs` file just like we would have with the previous two examples: +//! +//! ```ignore +//! // (Full example with detailed comments in examples/17_yaml.rs) +//! // +//! // This example demonstrates clap's building from YAML style of creating arguments which is far +//! // more clean, but takes a very small performance hit compared to the other two methods. +//! #[macro_use] +//! extern crate clap; +//! use clap::App; +//! +//! fn main() { +//! // The YAML file is found relative to the current file, similar to how modules are found +//! let yaml = load_yaml!("cli.yml"); +//! let matches = App::from_yaml(yaml).get_matches(); +//! +//! // Same as previous examples... +//! } +//! ``` +//! +//! Finally there is a macro version, which is like a hybrid approach offering the speed of the +//! builder pattern (the first example), but without all the verbosity. +//! +//! ```no_run +//! #[macro_use] +//! extern crate clap; +//! +//! fn main() { +//! let matches = clap_app!(myapp => +//! (version: "1.0") +//! (author: "Kevin K. ") +//! (about: "Does awesome things") +//! (@arg CONFIG: -c --config +takes_value "Sets a custom config file") +//! (@arg INPUT: +required "Sets the input file to use") +//! (@arg debug: -d ... "Sets the level of debugging information") +//! (@subcommand test => +//! (about: "controls testing features") +//! (version: "1.3") +//! (author: "Someone E. ") +//! (@arg verbose: -v --verbose "Print test information verbosely") +//! ) +//! ).get_matches(); +//! +//! // Same as before... +//! } +//! ``` +//! +//! If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or +//! `help` subcommand, since we defined `test` as a subcommand) the following would be output +//! +//! ```text +//! $ myprog --help +//! My Super Program 1.0 +//! Kevin K. +//! Does awesome things +//! +//! USAGE: +//! MyApp [FLAGS] [OPTIONS] [SUBCOMMAND] +//! +//! FLAGS: +//! -h, --help Prints this message +//! -v Sets the level of verbosity +//! -V, --version Prints version information +//! +//! OPTIONS: +//! -c, --config Sets a custom config file +//! +//! ARGS: +//! INPUT The input file to use +//! +//! SUBCOMMANDS: +//! help Prints this message +//! test Controls testing features +//! ``` +//! +//! **NOTE:** You could also run `myapp test --help` to see similar output and options for the +//! `test` subcommand. +//! +//! ## Try it! +//! +//! ### Pre-Built Test +//! +//! To try out the pre-built example, use the following steps: +//! +//! * Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/tests` +//! * Compile the example `$ cargo build --release` +//! * Run the help info `$ ./target/release/claptests --help` +//! * Play with the arguments! +//! +//! ### BYOB (Build Your Own Binary) +//! +//! To test out `clap`'s default auto-generated help/version follow these steps: +//! +//! * Create a new cargo project `$ cargo new fake --bin && cd fake` +//! * Add `clap` to your `Cargo.toml` +//! +//! ```toml +//! [dependencies] +//! clap = "2" +//! ``` +//! +//! * Add the following to your `src/main.rs` +//! +//! ```no_run +//! extern crate clap; +//! use clap::App; +//! +//! fn main() { +//! App::new("fake").version("v1.0-beta").get_matches(); +//! } +//! ``` +//! +//! * Build your program `$ cargo build --release` +//! * Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake +//! --version` +//! +//! ## Usage +//! +//! For full usage, add `clap` as a dependency in your `Cargo.toml` (it is **highly** recommended to +//! use the `~major.minor.patch` style versions in your `Cargo.toml`, for more information see +//! [Compatibility Policy](#compatibility-policy)) to use from crates.io: +//! +//! ```toml +//! [dependencies] +//! clap = "~2.27.0" +//! ``` +//! +//! Or get the latest changes from the master branch at github: +//! +//! ```toml +//! [dependencies.clap] +//! git = "https://github.com/clap-rs/clap.git" +//! ``` +//! +//! Add `extern crate clap;` to your crate root. +//! +//! Define a list of valid arguments for your program (see the +//! [documentation](https://docs.rs/clap/) or [examples/] directory of this repo) +//! +//! Then run `cargo build` or `cargo update && cargo build` for your project. +//! +//! ### Optional Dependencies / Features +//! +//! #### Features enabled by default +//! +//! * `suggestions`: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`) +//! * `color`: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` and `atty`) +//! * `wrap_help`: Wraps the help at the actual terminal width when +//! available, instead of 120 characters. (builds dependency `textwrap` +//! with feature `term_size`) +//! +//! To disable these, add this to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies.clap] +//! version = "~2.27.0" +//! default-features = false +//! ``` +//! +//! You can also selectively enable only the features you'd like to include, by adding: +//! +//! ```toml +//! [dependencies.clap] +//! version = "~2.27.0" +//! default-features = false +//! +//! # Cherry-pick the features you'd like to use +//! features = [ "suggestions", "color" ] +//! ``` +//! +//! #### Opt-in features +//! +//! * **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`) +//! * **"unstable"**: Enables unstable `clap` features that may change from release to release +//! +//! ### Dependencies Tree +//! +//! The following graphic depicts `clap`s dependency graph (generated using +//! [cargo-graph](https://github.com/kbknapp/cargo-graph)). +//! +//! * **Dashed** Line: Optional dependency +//! * **Red** Color: **NOT** included by default (must use cargo `features` to enable) +//! * **Blue** Color: Dev dependency, only used while developing. +//! +//! ![clap dependencies](https://github.com/clap-rs/clap/blob/v2.34.0/clap_dep_graph.png) +//! +//! ### More Information +//! +//! You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project. +//! +//! You can also find usage examples in the [examples/] directory of this repo. +//! +//! #### Video Tutorials +//! +//! There's also the video tutorial series [Argument Parsing with Rust v2][video tutorials]. +//! +//! These videos slowly trickle out as I finish them and currently a work in progress. +//! +//! ## How to Contribute +//! +//! Contributions are always welcome! And there is a multitude of ways in which you can help +//! depending on what you like to do, or are good at. Anything from documentation, code cleanup, +//! issue completion, new features, you name it, even filing issues is contributing and greatly +//! appreciated! +//! +//! Another really great way to help is if you find an interesting, or helpful way in which to use +//! `clap`. You can either add it to the [examples/] directory, or file an issue and tell +//! me. I'm all about giving credit where credit is due :) +//! +//! Please read [CONTRIBUTING.md](https://github.com/clap-rs/clap/blob/v2.34.0/.github/CONTRIBUTING.md) before you start contributing. +//! +//! +//! ### Testing Code +//! +//! To test with all features both enabled and disabled, you can run theese commands: +//! +//! ```text +//! $ cargo test --no-default-features +//! $ cargo test --features "yaml unstable" +//! ``` +//! +//! Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the +//! prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands +//! automatically. +//! +//! For example, to test the code, as above simply run: +//! +//! ```text +//! $ just run-tests +//! ``` +//! +//! From here on, I will list the appropriate `cargo` command as well as the `just` command. +//! +//! Sometimes it's helpful to only run a subset of the tests, which can be done via: +//! +//! ```text +//! $ cargo test --test +//! +//! # Or +//! +//! $ just run-test +//! ``` +//! +//! ### Linting Code +//! +//! During the CI process `clap` runs against many different lints using +//! [`clippy`](https://github.com/Manishearth/rust-clippy). In order to check if these lints pass on +//! your own computer prior to submitting a PR you'll need a nightly compiler. +//! +//! In order to check the code for lints run either: +//! +//! ```text +//! $ rustup override add nightly +//! $ cargo build --features lints +//! $ rustup override remove +//! +//! # Or +//! +//! $ just lint +//! ``` +//! +//! ### Debugging Code +//! +//! Another helpful technique is to see the `clap` debug output while developing features. In order +//! to see the debug output while running the full test suite or individual tests, run: +//! +//! ```text +//! $ cargo test --features debug +//! +//! # Or for individual tests +//! $ cargo test --test --features debug +//! +//! # The corresponding just command for individual debugging tests is: +//! $ just debug +//! ``` +//! +//! ### Goals +//! +//! There are a few goals of `clap` that I'd like to maintain throughout contributions. If your +//! proposed changes break, or go against any of these goals we'll discuss the changes further +//! before merging (but will *not* be ignored, all contributes are welcome!). These are by no means +//! hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by +//! mistake or ignorance). +//! +//! * Remain backwards compatible when possible +//! - If backwards compatibility *must* be broken, use deprecation warnings if at all possible before +//! removing legacy code - This does not apply for security concerns +//! * Parse arguments quickly +//! - Parsing of arguments shouldn't slow down usage of the main program - This is also true of +//! generating help and usage information (although *slightly* less stringent, as the program is about +//! to exit) +//! * Try to be cognizant of memory usage +//! - Once parsing is complete, the memory footprint of `clap` should be low since the main program +//! is the star of the show +//! * `panic!` on *developer* error, exit gracefully on *end-user* error +//! +//! ### Compatibility Policy +//! +//! Because `clap` takes `SemVer` and compatibility seriously, this is the official policy regarding +//! breaking changes and previous versions of Rust. +//! +//! `clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum +//! version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version +//! of `clap` will be bumped. +//! +//! In order to keep from being surprised by breaking changes, it is **highly** recommended to use +//! the `~major.minor.patch` style in your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] clap = "~2.27.0" +//! ``` +//! +//! This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore +//! cannot break due to new features, or bumped minimum versions of Rust. +//! +//! #### Minimum Version of Rust +//! +//! `clap` will officially support current stable Rust, minus two releases, but may work with prior +//! releases as well. For example, current stable Rust at the time of this writing is 1.21.0, +//! meaning `clap` is guaranteed to compile with 1.19.0 and beyond. At the 1.22.0 release, `clap` +//! will be guaranteed to compile with 1.20.0 and beyond, etc. +//! +//! Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be +//! clearly annotated in the `CHANGELOG.md` +//! +//! ## License +//! +//! `clap` is licensed under the MIT license. Please read the [LICENSE-MIT][license] file in +//! this repository for more information. +//! +//! [examples/]: https://github.com/clap-rs/clap/tree/v2.34.0/examples +//! [video tutorials]: https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U +//! [license]: https://github.com/clap-rs/clap/blob/v2.34.0/LICENSE-MIT + +#![crate_type = "lib"] +#![doc(html_root_url = "https://docs.rs/clap/2.34.0")] +#![deny( + missing_docs, + missing_debug_implementations, + missing_copy_implementations, + trivial_casts, + unused_import_braces, + unused_allocation +)] +// Lints we'd like to deny but are currently failing for upstream crates +// unused_qualifications (bitflags, clippy) +// trivial_numeric_casts (bitflags) +#![cfg_attr( + not(any(feature = "cargo-clippy", feature = "nightly")), + forbid(unstable_features) +)] +//#![cfg_attr(feature = "lints", feature(plugin))] +//#![cfg_attr(feature = "lints", plugin(clippy))] +// Need to disable deny(warnings) while deprecations are active +//#![cfg_attr(feature = "cargo-clippy", deny(warnings))] +// Due to our "MSRV for 2.x will remain unchanged" policy, we can't fix these warnings +#![allow(bare_trait_objects, deprecated)] + +#[cfg(all(feature = "color", not(target_os = "windows")))] +extern crate ansi_term; +#[cfg(feature = "color")] +extern crate atty; +#[macro_use] +extern crate bitflags; +#[cfg(feature = "suggestions")] +extern crate strsim; +#[cfg(feature = "wrap_help")] +extern crate term_size; +extern crate textwrap; +extern crate unicode_width; +#[cfg(feature = "vec_map")] +extern crate vec_map; +#[cfg(feature = "yaml")] +extern crate yaml_rust; + +pub use app::{App, AppSettings}; +pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values}; +pub use completions::Shell; +pub use errors::{Error, ErrorKind, Result}; +pub use fmt::Format; +#[cfg(feature = "yaml")] +pub use yaml_rust::YamlLoader; + +#[macro_use] +mod macros; +mod app; +mod args; +mod completions; +mod errors; +mod fmt; +mod map; +mod osstringext; +mod strext; +mod suggestions; +mod usage_parser; + +const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ + report at https://github.com/clap-rs/clap/issues"; +const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point"; + +#[cfg(unstable)] +pub use derive::{ArgEnum, ClapApp, FromArgMatches, IntoApp}; + +#[cfg(unstable)] +mod derive { + /// @TODO @release @docs + pub trait ClapApp: IntoApp + FromArgMatches + Sized { + /// @TODO @release @docs + fn parse() -> Self { + Self::from_argmatches(Self::into_app().get_matches()) + } + + /// @TODO @release @docs + fn parse_from(argv: I) -> Self + where + I: IntoIterator, + T: Into + Clone, + { + Self::from_argmatches(Self::into_app().get_matches_from(argv)) + } + + /// @TODO @release @docs + fn try_parse() -> Result { + Self::try_from_argmatches(Self::into_app().get_matches_safe()?) + } + + /// @TODO @release @docs + fn try_parse_from(argv: I) -> Result + where + I: IntoIterator, + T: Into + Clone, + { + Self::try_from_argmatches(Self::into_app().get_matches_from_safe(argv)?) + } + } + + /// @TODO @release @docs + pub trait IntoApp { + /// @TODO @release @docs + fn into_app<'a, 'b>() -> clap::App<'a, 'b>; + } + + /// @TODO @release @docs + pub trait FromArgMatches: Sized { + /// @TODO @release @docs + fn from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Self; + + /// @TODO @release @docs + fn try_from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Result; + } + + /// @TODO @release @docs + pub trait ArgEnum {} +} diff --git a/bash-5.1/vendor/clap/src/macros.rs b/bash-5.1/vendor/clap/src/macros.rs new file mode 100644 index 0000000..01cbca8 --- /dev/null +++ b/bash-5.1/vendor/clap/src/macros.rs @@ -0,0 +1,1130 @@ +/// A convenience macro for loading the YAML file at compile time (relative to the current file, +/// like modules work). That YAML object can then be passed to this function. +/// +/// # Panics +/// +/// The YAML file must be properly formatted or this function will panic!(). A good way to +/// ensure this doesn't happen is to run your program with the `--help` switch. If this passes +/// without error, you needn't worry because the YAML is properly formatted. +/// +/// # Examples +/// +/// The following example shows how to load a properly formatted YAML file to build an instance +/// of an `App` struct. +/// +/// ```ignore +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let yml = load_yaml!("app.yml"); +/// let app = App::from_yaml(yml); +/// +/// // continued logic goes here, such as `app.get_matches()` etc. +/// # } +/// ``` +#[cfg(feature = "yaml")] +#[macro_export] +macro_rules! load_yaml { + ($yml:expr) => { + &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0] + }; +} + +/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an +/// argument value. This macro returns a `Result` which allows you as the developer to +/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures +/// and those where the argument wasn't present (such as a non-required argument). You can use +/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`] +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let matches = App::new("myapp") +/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") +/// .get_matches(); +/// +/// let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit()); +/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit()); +/// +/// println!("{} + 2: {}", len, len + 2); +/// # } +/// ``` +/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html +/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of +/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html +#[macro_export] +macro_rules! value_t { + ($m:ident, $v:expr, $t:ty) => { + value_t!($m.value_of($v), $t) + }; + ($m:ident.value_of($v:expr), $t:ty) => { + if let Some(v) = $m.value_of($v) { + match v.parse::<$t>() { + Ok(val) => Ok(val), + Err(_) => Err(::clap::Error::value_validation_auto(format!( + "The argument '{}' isn't a valid value", + v + ))), + } + } else { + Err(::clap::Error::argument_not_found_auto($v)) + } + }; +} + +/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or +/// exiting upon error, instead of returning a [`Result`] type. +/// +/// **NOTE:** This macro is for backwards compatibility sake. Prefer +/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`] +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let matches = App::new("myapp") +/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") +/// .get_matches(); +/// +/// let len = value_t_or_exit!(matches.value_of("length"), u32); +/// let also_len = value_t_or_exit!(matches, "length", u32); +/// +/// println!("{} + 2: {}", len, len + 2); +/// # } +/// ``` +/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html +/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html +/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html +#[macro_export] +macro_rules! value_t_or_exit { + ($m:ident, $v:expr, $t:ty) => { + value_t_or_exit!($m.value_of($v), $t) + }; + ($m:ident.value_of($v:expr), $t:ty) => { + if let Some(v) = $m.value_of($v) { + match v.parse::<$t>() { + Ok(val) => val, + Err(_) => ::clap::Error::value_validation_auto(format!( + "The argument '{}' isn't a valid value", + v + )) + .exit(), + } + } else { + ::clap::Error::argument_not_found_auto($v).exit() + } + }; +} + +/// Convenience macro getting a typed value [`Vec`] where `T` implements [`std::str::FromStr`] +/// This macro returns a [`clap::Result>`] which allows you as the developer to decide +/// what you'd like to do on a failed parse. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let matches = App::new("myapp") +/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") +/// .get_matches(); +/// +/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit()); +/// for v in &vals { +/// println!("{} + 2: {}", v, v + 2); +/// } +/// +/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit()); +/// for v in &vals { +/// println!("{} + 2: {}", v, v + 2); +/// } +/// # } +/// ``` +/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html +/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html +/// [`clap::Result>`]: ./type.Result.html +#[macro_export] +macro_rules! values_t { + ($m:ident, $v:expr, $t:ty) => { + values_t!($m.values_of($v), $t) + }; + ($m:ident.values_of($v:expr), $t:ty) => { + if let Some(vals) = $m.values_of($v) { + let mut tmp = vec![]; + let mut err = None; + for pv in vals { + match pv.parse::<$t>() { + Ok(rv) => tmp.push(rv), + Err(..) => { + err = Some(::clap::Error::value_validation_auto(format!( + "The argument '{}' isn't a valid value", + pv + ))); + break; + } + } + } + match err { + Some(e) => Err(e), + None => Ok(tmp), + } + } else { + Err(::clap::Error::argument_not_found_auto($v)) + } + }; +} + +/// Convenience macro getting a typed value [`Vec`] where `T` implements [`std::str::FromStr`] +/// or exiting upon error. +/// +/// **NOTE:** This macro is for backwards compatibility sake. Prefer +/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`] +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let matches = App::new("myapp") +/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") +/// .get_matches(); +/// +/// let vals = values_t_or_exit!(matches.values_of("seq"), u32); +/// for v in &vals { +/// println!("{} + 2: {}", v, v + 2); +/// } +/// +/// // type for example only +/// let vals: Vec = values_t_or_exit!(matches, "seq", u32); +/// for v in &vals { +/// println!("{} + 2: {}", v, v + 2); +/// } +/// # } +/// ``` +/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html +/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html +/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html +#[macro_export] +macro_rules! values_t_or_exit { + ($m:ident, $v:expr, $t:ty) => { + values_t_or_exit!($m.values_of($v), $t) + }; + ($m:ident.values_of($v:expr), $t:ty) => { + if let Some(vals) = $m.values_of($v) { + vals.map(|v| { + v.parse::<$t>().unwrap_or_else(|_| { + ::clap::Error::value_validation_auto(format!( + "One or more arguments aren't valid values" + )) + .exit() + }) + }) + .collect::>() + } else { + ::clap::Error::argument_not_found_auto($v).exit() + } + }; +} + +// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag +// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07 +// License: MIT +// Copyright ⓒ 2015 grabbag contributors. +// Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of +// ), at your option. All +// files in the project carrying such notice may not be copied, modified, +// or distributed except according to those terms. +// +/// Counts the number of comma-delimited expressions passed to it. The result is a compile-time +/// evaluable expression, suitable for use as a static array size, or the value of a `const`. +/// +/// # Examples +/// +/// ``` +/// # #[macro_use] extern crate clap; +/// # fn main() { +/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string()); +/// assert_eq!(COUNT, 3); +/// # } +/// ``` +#[macro_export] +macro_rules! _clap_count_exprs { + () => { 0 }; + ($e:expr) => { 1 }; + ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; +} + +/// Convenience macro to generate more complete enums with variants to be used as a type when +/// parsing arguments. This enum also provides a `variants()` function which can be used to +/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and +/// [`Display`] automatically. +/// +/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to +/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums +/// +/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`] +/// +/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits +/// +/// # Examples +/// +/// ```rust +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::{App, Arg}; +/// arg_enum!{ +/// #[derive(PartialEq, Debug)] +/// pub enum Foo { +/// Bar, +/// Baz, +/// Qux +/// } +/// } +/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc +/// // and implements std::str::FromStr to use with the value_t! macros +/// fn main() { +/// let m = App::new("app") +/// .arg(Arg::from_usage(" 'the foo'") +/// .possible_values(&Foo::variants()) +/// .case_insensitive(true)) +/// .get_matches_from(vec![ +/// "app", "baz" +/// ]); +/// let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit()); +/// +/// assert_eq!(f, Foo::Baz); +/// } +/// ``` +/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html +/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html +/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html +/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html +/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive +#[macro_export] +macro_rules! arg_enum { + (@as_item $($i:item)*) => ($($i)*); + (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { + arg_enum!(@as_item + $($tts)* + + impl ::std::str::FromStr for $e { + type Err = String; + + fn from_str(s: &str) -> ::std::result::Result { + #[allow(deprecated, unused_imports)] + use ::std::ascii::AsciiExt; + match s { + $(stringify!($v) | + _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+, + _ => Err({ + let v = vec![ + $(stringify!($v),)+ + ]; + format!("valid values: {}", + v.join(", ")) + }), + } + } + } + impl ::std::fmt::Display for $e { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + $($e::$v => write!(f, stringify!($v)),)+ + } + } + } + impl $e { + #[allow(dead_code)] + pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] { + [ + $(stringify!($v),)+ + ] + } + }); + }; + ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + arg_enum!(@impls + ($(#[$($m),+])+ + pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + arg_enum!(@impls + ($(#[$($m),+])+ + pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + arg_enum!(@impls + ($(#[$($m),+])+ + enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + arg_enum!(@impls + ($(#[$($m),+])+ + enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + arg_enum!(@impls + (pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + arg_enum!(@impls + (pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + arg_enum!(@impls + (enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + arg_enum!(@impls + (enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; +} + +/// Allows you to pull the version from your Cargo.toml at compile time as +/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let m = App::new("app") +/// .version(crate_version!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(not(feature = "no_cargo"))] +#[macro_export] +macro_rules! crate_version { + () => { + env!("CARGO_PKG_VERSION") + }; +} + +/// Allows you to pull the authors for the app from your Cargo.toml at +/// compile time in the form: +/// `"author1 lastname :author2 lastname "` +/// +/// You can replace the colons with a custom separator by supplying a +/// replacement string, so, for example, +/// `crate_authors!(",\n")` would become +/// `"author1 lastname ,\nauthor2 lastname ,\nauthor3 lastname "` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let m = App::new("app") +/// .author(crate_authors!("\n")) +/// .get_matches(); +/// # } +/// ``` +#[cfg(not(feature = "no_cargo"))] +#[macro_export] +macro_rules! crate_authors { + ($sep:expr) => {{ + use std::ops::Deref; + #[allow(deprecated)] + use std::sync::{Once, ONCE_INIT}; + + #[allow(missing_copy_implementations)] + #[allow(dead_code)] + struct CargoAuthors { + __private_field: (), + }; + + impl Deref for CargoAuthors { + type Target = str; + + #[allow(unsafe_code)] + fn deref(&self) -> &'static str { + #[allow(deprecated)] + static ONCE: Once = ONCE_INIT; + static mut VALUE: *const String = 0 as *const String; + + unsafe { + ONCE.call_once(|| { + let s = env!("CARGO_PKG_AUTHORS").replace(':', $sep); + VALUE = Box::into_raw(Box::new(s)); + }); + + &(*VALUE)[..] + } + } + } + + &*CargoAuthors { + __private_field: (), + } + }}; + () => { + env!("CARGO_PKG_AUTHORS") + }; +} + +/// Allows you to pull the description from your Cargo.toml at compile time. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let m = App::new("app") +/// .about(crate_description!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(not(feature = "no_cargo"))] +#[macro_export] +macro_rules! crate_description { + () => { + env!("CARGO_PKG_DESCRIPTION") + }; +} + +/// Allows you to pull the name from your Cargo.toml at compile time. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::App; +/// # fn main() { +/// let m = App::new(crate_name!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(not(feature = "no_cargo"))] +#[macro_export] +macro_rules! crate_name { + () => { + env!("CARGO_PKG_NAME") + }; +} + +/// Allows you to build the `App` instance from your Cargo.toml at compile time. +/// +/// Equivalent to using the `crate_*!` macros with their respective fields. +/// +/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro, +/// refer to the documentation therefor. +/// +/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, +/// and therefore won't change the generated output until you recompile. +/// +/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your +/// `Cargo.toml` is changed by including this in your `src/main.rs` file +/// `include_str!("../Cargo.toml");` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # fn main() { +/// let m = app_from_crate!().get_matches(); +/// # } +/// ``` +#[cfg(not(feature = "no_cargo"))] +#[macro_export] +macro_rules! app_from_crate { + () => { + $crate::App::new(crate_name!()) + .version(crate_version!()) + .author(crate_authors!()) + .about(crate_description!()) + }; + ($sep:expr) => { + $crate::App::new(crate_name!()) + .version(crate_version!()) + .author(crate_authors!($sep)) + .about(crate_description!()) + }; +} + +/// Build `App`, `Arg`s, `SubCommand`s and `Group`s with Usage-string like input +/// but without the associated parsing runtime cost. +/// +/// `clap_app!` also supports several shorthand syntaxes. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # fn main() { +/// let matches = clap_app!(myapp => +/// (version: "1.0") +/// (author: "Kevin K. ") +/// (about: "Does awesome things") +/// (@arg CONFIG: -c --config +takes_value "Sets a custom config file") +/// (@arg INPUT: +required "Sets the input file to use") +/// (@arg debug: -d ... "Sets the level of debugging information") +/// (@group difficulty => +/// (@arg hard: -h --hard "Sets hard mode") +/// (@arg normal: -n --normal "Sets normal mode") +/// (@arg easy: -e --easy "Sets easy mode") +/// ) +/// (@subcommand test => +/// (about: "controls testing features") +/// (version: "1.3") +/// (author: "Someone E. ") +/// (@arg verbose: -v --verbose "Print test information verbosely") +/// ) +/// ) +/// .get_matches(); +/// # } +/// ``` +/// # Shorthand Syntax for Args +/// +/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`] +/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`] +/// * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you +/// must use `--("config-file")` due to limitations of the Rust macro system. +/// * Three dots (`...`) sets [`Arg::multiple(true)`] +/// * Angled brackets after either a short or long will set [`Arg::value_name`] and +/// `Arg::required(true)` such as `--config ` = `Arg::value_name("FILE")` and +/// `Arg::required(true)` +/// * Square brackets after either a short or long will set [`Arg::value_name`] and +/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and +/// `Arg::required(false)` +/// * There are short hand syntaxes for Arg methods that accept booleans +/// * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)` +/// * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)` +/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`] +/// * An asterisk (`*`) will set `Arg::required(true)` +/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)` +/// * An Arg method that accepts a string followed by square brackets will set that method such as +/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around +/// `FOO` in the macro) +/// * An Arg method that takes a string and can be set multiple times (such as +/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces +/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set +/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")` +/// (note the lack of quotes around the values in the macro) +/// +/// # Shorthand Syntax for Groups +/// +/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans +/// * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)` +/// * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)` +/// +/// [`Arg::short`]: ./struct.Arg.html#method.short +/// [`Arg::long`]: ./struct.Arg.html#method.long +/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple +/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name +/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values +/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values +/// [`Arg::validator`]: ./struct.Arg.html#method.validator +/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with +#[macro_export] +macro_rules! clap_app { + (@app ($builder:expr)) => { $builder }; + (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @app + ($builder.arg( + clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* })) + $($tt)* + } + }; + (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @app + ($builder.arg( + clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* })) + $($tt)* + } + }; + (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { + clap_app!{ @app + ($builder.setting($crate::AppSettings::$setting)) + $($tt)* + } + }; +// Treat the application builder as an argument to set its attributes + (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { + clap_app!{ @app (clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } + }; + (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @app + (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* }) + $($tt)* + } + }; + (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @app + (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* }) + $($tt)* + } + }; + (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @app + (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* }) + $($tt)* + } + }; +// Handle subcommand creation + (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @app + ($builder.subcommand( + clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* } + )) + $($tt)* + } + }; +// Yaml like function calls - used for setting various meta directly against the app + (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => { +// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } + clap_app!{ @app + ($builder.$ident($($v),*)) + $($tt)* + } + }; + +// Add members to group and continue argument handling with the parent builder + (@group ($builder:expr, $group:expr)) => { $builder.group($group) }; + // Treat the group builder as an argument to set its attributes + (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { + clap_app!{ @group ($builder, clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* } + }; + (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { + clap_app!{ @group + (clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, + $group.arg(stringify!($name))) + $($tt)* + } + }; + +// No more tokens to munch + (@arg ($arg:expr) $modes:tt) => { $arg }; +// Shorthand tokens influenced by the usage_string + (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { + clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } + }; + (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { + clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } + }; + (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { + clap_app!{ @arg ($arg.short(stringify!($short))) $modes $($tail)* } + }; + (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { + clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } + }; + (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { + clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + }; + (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { + clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } + }; + (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { + clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + }; + (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { + clap_app!{ @arg ($arg) $modes +multiple $($tail)* } + }; +// Shorthand magic + (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { + clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } + }; + (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { + clap_app!{ @arg ($arg) $modes +required $($tail)* } + }; +// !foo -> .foo(false) + (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { + clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } + }; +// +foo -> .foo(true) + (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { + clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } + }; +// Validator + (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { + clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } + }; + (@as_expr $expr:expr) => { $expr }; +// Help + (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(clap_app!{ @as_expr $desc }) }; +// Handle functions that need to be called multiple times for each argument + (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => { + clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } + }; +// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")` + (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => { + clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + }; +// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)` + (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => { + clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + }; + +// Build a subcommand outside of an app. + (@subcommand $name:ident => $($tail:tt)*) => { + clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* } + }; +// Start the magic + (($name:expr) => $($tail:tt)*) => {{ + clap_app!{ @app ($crate::App::new($name)) $($tail)*} + }}; + + ($name:ident => $($tail:tt)*) => {{ + clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*} + }}; +} + +macro_rules! impl_settings { + ($n:ident, $($v:ident => $c:path),+) => { + pub fn set(&mut self, s: $n) { + match s { + $($n::$v => self.0.insert($c)),+ + } + } + + pub fn unset(&mut self, s: $n) { + match s { + $($n::$v => self.0.remove($c)),+ + } + } + + pub fn is_set(&self, s: $n) -> bool { + match s { + $($n::$v => self.0.contains($c)),+ + } + } + }; +} + +// Convenience for writing to stderr thanks to https://github.com/BurntSushi +macro_rules! wlnerr( + (@nopanic $($arg:tt)*) => ({ + use std::io::{Write, stderr}; + let _ = writeln!(&mut stderr().lock(), $($arg)*); + }); + ($($arg:tt)*) => ({ + use std::io::{Write, stderr}; + writeln!(&mut stderr(), $($arg)*).ok(); + }) +); + +#[cfg(feature = "debug")] +#[cfg_attr(feature = "debug", macro_use)] +#[cfg_attr(feature = "debug", allow(unused_macros))] +mod debug_macros { + macro_rules! debugln { + ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt))); + ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*)); + } + macro_rules! sdebugln { + ($fmt:expr) => (println!($fmt)); + ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*)); + } + macro_rules! debug { + ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt))); + ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*)); + } + macro_rules! sdebug { + ($fmt:expr) => (print!($fmt)); + ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*)); + } +} + +#[cfg(not(feature = "debug"))] +#[cfg_attr(not(feature = "debug"), macro_use)] +mod debug_macros { + macro_rules! debugln { + ($fmt:expr) => {}; + ($fmt:expr, $($arg:tt)*) => {}; + } + macro_rules! sdebugln { + ($fmt:expr) => {}; + ($fmt:expr, $($arg:tt)*) => {}; + } + macro_rules! debug { + ($fmt:expr) => {}; + ($fmt:expr, $($arg:tt)*) => {}; + } +} + +// Helper/deduplication macro for printing the correct number of spaces in help messages +// used in: +// src/args/arg_builder/*.rs +// src/app/mod.rs +macro_rules! write_nspaces { + ($dst:expr, $num:expr) => {{ + debugln!("write_spaces!: num={}", $num); + for _ in 0..$num { + $dst.write_all(b" ")?; + } + }}; +} + +// convenience macro for remove an item from a vec +//macro_rules! vec_remove_all { +// ($vec:expr, $to_rem:expr) => { +// debugln!("vec_remove_all! to_rem={:?}", $to_rem); +// for i in (0 .. $vec.len()).rev() { +// let should_remove = $to_rem.any(|name| name == &$vec[i]); +// if should_remove { $vec.swap_remove(i); } +// } +// }; +//} +macro_rules! find_from { + ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{ + let mut ret = None; + for k in $matcher.arg_names() { + if let Some(f) = find_by_name!($_self, k, flags, iter) { + if let Some(ref v) = f.$from() { + if v.contains($arg_name) { + ret = Some(f.to_string()); + } + } + } + if let Some(o) = find_by_name!($_self, k, opts, iter) { + if let Some(ref v) = o.$from() { + if v.contains(&$arg_name) { + ret = Some(o.to_string()); + } + } + } + if let Some(pos) = find_by_name!($_self, k, positionals, values) { + if let Some(ref v) = pos.$from() { + if v.contains($arg_name) { + ret = Some(pos.b.name.to_owned()); + } + } + } + } + ret + }}; +} + +//macro_rules! find_name_from { +// ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{ +// let mut ret = None; +// for k in $matcher.arg_names() { +// if let Some(f) = find_by_name!($_self, k, flags, iter) { +// if let Some(ref v) = f.$from() { +// if v.contains($arg_name) { +// ret = Some(f.b.name); +// } +// } +// } +// if let Some(o) = find_by_name!($_self, k, opts, iter) { +// if let Some(ref v) = o.$from() { +// if v.contains(&$arg_name) { +// ret = Some(o.b.name); +// } +// } +// } +// if let Some(pos) = find_by_name!($_self, k, positionals, values) { +// if let Some(ref v) = pos.$from() { +// if v.contains($arg_name) { +// ret = Some(pos.b.name); +// } +// } +// } +// } +// ret +// }}; +//} + +macro_rules! find_any_by_name { + ($p:expr, $name:expr) => {{ + fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> { + x + } + find_by_name!($p, $name, flags, iter) + .map(as_trait_obj) + .or(find_by_name!($p, $name, opts, iter) + .map(as_trait_obj) + .or(find_by_name!($p, $name, positionals, values).map(as_trait_obj))) + }}; +} +// Finds an arg by name +macro_rules! find_by_name { + ($p:expr, $name:expr, $what:ident, $how:ident) => { + $p.$what.$how().find(|o| o.b.name == $name) + }; +} + +// Finds an option including if it's aliased +macro_rules! find_opt_by_long { + (@os $_self:ident, $long:expr) => {{ + _find_by_long!($_self, $long, opts) + }}; + ($_self:ident, $long:expr) => {{ + _find_by_long!($_self, $long, opts) + }}; +} + +macro_rules! find_flag_by_long { + (@os $_self:ident, $long:expr) => {{ + _find_by_long!($_self, $long, flags) + }}; + ($_self:ident, $long:expr) => {{ + _find_by_long!($_self, $long, flags) + }}; +} + +macro_rules! _find_by_long { + ($_self:ident, $long:expr, $what:ident) => {{ + $_self + .$what + .iter() + .filter(|a| a.s.long.is_some()) + .find(|a| { + a.s.long.unwrap() == $long + || (a.s.aliases.is_some() + && a.s + .aliases + .as_ref() + .unwrap() + .iter() + .any(|&(alias, _)| alias == $long)) + }) + }}; +} + +// Finds an option +macro_rules! find_opt_by_short { + ($_self:ident, $short:expr) => {{ + _find_by_short!($_self, $short, opts) + }}; +} + +macro_rules! find_flag_by_short { + ($_self:ident, $short:expr) => {{ + _find_by_short!($_self, $short, flags) + }}; +} + +macro_rules! _find_by_short { + ($_self:ident, $short:expr, $what:ident) => {{ + $_self + .$what + .iter() + .filter(|a| a.s.short.is_some()) + .find(|a| a.s.short.unwrap() == $short) + }}; +} + +macro_rules! find_subcmd { + ($_self:expr, $sc:expr) => {{ + $_self.subcommands.iter().find(|s| { + &*s.p.meta.name == $sc + || (s.p.meta.aliases.is_some() + && s.p + .meta + .aliases + .as_ref() + .unwrap() + .iter() + .any(|&(n, _)| n == $sc)) + }) + }}; +} + +macro_rules! shorts { + ($_self:ident) => {{ + _shorts_longs!($_self, short) + }}; +} + +macro_rules! longs { + ($_self:ident) => {{ + _shorts_longs!($_self, long) + }}; +} + +macro_rules! _shorts_longs { + ($_self:ident, $what:ident) => {{ + $_self + .flags + .iter() + .filter(|f| f.s.$what.is_some()) + .map(|f| f.s.$what.as_ref().unwrap()) + .chain( + $_self + .opts + .iter() + .filter(|o| o.s.$what.is_some()) + .map(|o| o.s.$what.as_ref().unwrap()), + ) + }}; +} + +macro_rules! arg_names { + ($_self:ident) => {{ + _names!(@args $_self) + }}; +} + +macro_rules! sc_names { + ($_self:ident) => {{ + _names!(@sc $_self) + }}; +} + +macro_rules! _names { + (@args $_self:ident) => {{ + $_self.flags.iter().map(|f| &*f.b.name).chain( + $_self + .opts + .iter() + .map(|o| &*o.b.name) + .chain($_self.positionals.values().map(|p| &*p.b.name)), + ) + }}; + (@sc $_self:ident) => {{ + $_self.subcommands.iter().map(|s| &*s.p.meta.name).chain( + $_self + .subcommands + .iter() + .filter(|s| s.p.meta.aliases.is_some()) + .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)), + ) + }}; +} diff --git a/bash-5.1/vendor/clap/src/map.rs b/bash-5.1/vendor/clap/src/map.rs new file mode 100644 index 0000000..1349783 --- /dev/null +++ b/bash-5.1/vendor/clap/src/map.rs @@ -0,0 +1,88 @@ +#[cfg(feature = "vec_map")] +pub use vec_map::{Values, VecMap}; + +#[cfg(not(feature = "vec_map"))] +pub use self::vec_map::{Values, VecMap}; + +#[cfg(not(feature = "vec_map"))] +mod vec_map { + use std::collections::btree_map; + use std::collections::BTreeMap; + use std::fmt::{self, Debug, Formatter}; + + #[derive(Clone, Default, Debug)] + pub struct VecMap { + inner: BTreeMap, + } + + impl VecMap { + pub fn new() -> Self { + VecMap { + inner: Default::default(), + } + } + + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + pub fn insert(&mut self, key: usize, value: V) -> Option { + self.inner.insert(key, value) + } + + pub fn values(&self) -> Values { + self.inner.values() + } + + pub fn iter(&self) -> Iter { + Iter { + inner: self.inner.iter(), + } + } + + pub fn contains_key(&self, key: usize) -> bool { + self.inner.contains_key(&key) + } + + pub fn entry(&mut self, key: usize) -> Entry { + self.inner.entry(key) + } + + pub fn get(&self, key: usize) -> Option<&V> { + self.inner.get(&key) + } + } + + pub type Values<'a, V> = btree_map::Values<'a, usize, V>; + + pub type Entry<'a, V> = btree_map::Entry<'a, usize, V>; + + #[derive(Clone)] + pub struct Iter<'a, V: 'a> { + inner: btree_map::Iter<'a, usize, V>, + } + + impl<'a, V: 'a + Debug> Debug for Iter<'a, V> { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + f.debug_list().entries(self.inner.clone()).finish() + } + } + + impl<'a, V: 'a> Iterator for Iter<'a, V> { + type Item = (usize, &'a V); + + fn next(&mut self) -> Option { + self.inner.next().map(|(k, v)| (*k, v)) + } + } + + impl<'a, V: 'a> DoubleEndedIterator for Iter<'a, V> { + fn next_back(&mut self) -> Option { + self.inner.next_back().map(|(k, v)| (*k, v)) + } + } +} diff --git a/bash-5.1/vendor/clap/src/osstringext.rs b/bash-5.1/vendor/clap/src/osstringext.rs new file mode 100644 index 0000000..ef765c8 --- /dev/null +++ b/bash-5.1/vendor/clap/src/osstringext.rs @@ -0,0 +1,203 @@ +use std::ffi::OsStr; +#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] +use std::os::unix::ffi::OsStrExt; +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +use crate::INVALID_UTF8; + +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +pub trait OsStrExt3 { + fn from_bytes(b: &[u8]) -> &Self; + fn as_bytes(&self) -> &[u8]; +} + +#[doc(hidden)] +pub trait OsStrExt2 { + fn starts_with(&self, s: &[u8]) -> bool; + fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr); + fn split_at(&self, i: usize) -> (&OsStr, &OsStr); + fn trim_left_matches(&self, b: u8) -> &OsStr; + fn contains_byte(&self, b: u8) -> bool; + fn split(&self, b: u8) -> OsSplit; +} + +// A starts-with implementation that does not panic when the OsStr contains +// invalid Unicode. +// +// A Windows OsStr is usually UTF-16. If `prefix` is valid UTF-8, we can +// re-encode it as UTF-16, and ask whether `osstr` starts with the same series +// of u16 code units. If `prefix` is not valid UTF-8, then this comparison +// isn't meaningful, and we just return false. +#[cfg(target_os = "windows")] +fn windows_osstr_starts_with(osstr: &OsStr, prefix: &[u8]) -> bool { + use std::os::windows::ffi::OsStrExt; + let prefix_str = if let Ok(s) = std::str::from_utf8(prefix) { + s + } else { + return false; + }; + let mut osstr_units = osstr.encode_wide(); + let mut prefix_units = prefix_str.encode_utf16(); + loop { + match (osstr_units.next(), prefix_units.next()) { + // These code units match. Keep looping. + (Some(o), Some(p)) if o == p => continue, + // We've reached the end of the prefix. It's a match. + (_, None) => return true, + // Otherwise, it's not a match. + _ => return false, + } + } +} + +#[test] +#[cfg(target_os = "windows")] +fn test_windows_osstr_starts_with() { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + + fn from_ascii(ascii: &[u8]) -> OsString { + let u16_vec: Vec = ascii.iter().map(|&c| c as u16).collect(); + OsString::from_wide(&u16_vec) + } + + // Test all the basic cases. + assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abc")); + assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abcdef")); + assert!(!windows_osstr_starts_with(&from_ascii(b"abcdef"), b"def")); + assert!(!windows_osstr_starts_with(&from_ascii(b"abc"), b"abcd")); + + // Test the case where the candidate prefix is not valid UTF-8. Note that a + // standalone \xff byte is valid ASCII but not valid UTF-8. Thus although + // these strings look identical, they do not match. + assert!(!windows_osstr_starts_with(&from_ascii(b"\xff"), b"\xff")); + + // Test the case where the OsString is not valid UTF-16. It should still be + // possible to match the valid characters at the front. + // + // UTF-16 surrogate characters are only valid in pairs. Including one on + // the end by itself makes this invalid UTF-16. + let surrogate_char: u16 = 0xDC00; + let invalid_unicode = + OsString::from_wide(&['a' as u16, 'b' as u16, 'c' as u16, surrogate_char]); + assert!( + invalid_unicode.to_str().is_none(), + "This string is invalid Unicode, and conversion to &str should fail.", + ); + assert!(windows_osstr_starts_with(&invalid_unicode, b"abc")); + assert!(!windows_osstr_starts_with(&invalid_unicode, b"abcd")); +} + +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +impl OsStrExt3 for OsStr { + fn from_bytes(b: &[u8]) -> &Self { + use std::mem; + unsafe { mem::transmute(b) } + } + fn as_bytes(&self) -> &[u8] { + self.to_str().map(|s| s.as_bytes()).expect(INVALID_UTF8) + } +} + +impl OsStrExt2 for OsStr { + fn starts_with(&self, s: &[u8]) -> bool { + #[cfg(target_os = "windows")] + { + // On Windows, the as_bytes() method will panic if the OsStr + // contains invalid Unicode. To avoid this, we use a + // Windows-specific starts-with function that doesn't rely on + // as_bytes(). This is necessary for Windows command line + // applications to handle non-Unicode arguments successfully. This + // allows common cases like `clap.exe [invalid]` to succeed, though + // cases that require string splitting will still fail, like + // `clap.exe --arg=[invalid]`. Note that this entire module is + // replaced in Clap 3.x, so this workaround is specific to the 2.x + // branch. + windows_osstr_starts_with(self, s) + } + #[cfg(not(target_os = "windows"))] + { + self.as_bytes().starts_with(s) + } + } + + fn contains_byte(&self, byte: u8) -> bool { + for b in self.as_bytes() { + if b == &byte { + return true; + } + } + false + } + + fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) { + for (i, b) in self.as_bytes().iter().enumerate() { + if b == &byte { + return ( + OsStr::from_bytes(&self.as_bytes()[..i]), + OsStr::from_bytes(&self.as_bytes()[i + 1..]), + ); + } + } + ( + &*self, + OsStr::from_bytes(&self.as_bytes()[self.len()..self.len()]), + ) + } + + fn trim_left_matches(&self, byte: u8) -> &OsStr { + let mut found = false; + for (i, b) in self.as_bytes().iter().enumerate() { + if b != &byte { + return OsStr::from_bytes(&self.as_bytes()[i..]); + } else { + found = true; + } + } + if found { + return OsStr::from_bytes(&self.as_bytes()[self.len()..]); + } + &*self + } + + fn split_at(&self, i: usize) -> (&OsStr, &OsStr) { + ( + OsStr::from_bytes(&self.as_bytes()[..i]), + OsStr::from_bytes(&self.as_bytes()[i..]), + ) + } + + fn split(&self, b: u8) -> OsSplit { + OsSplit { + sep: b, + val: self.as_bytes(), + pos: 0, + } + } +} + +#[doc(hidden)] +#[derive(Clone, Debug)] +pub struct OsSplit<'a> { + sep: u8, + val: &'a [u8], + pos: usize, +} + +impl<'a> Iterator for OsSplit<'a> { + type Item = &'a OsStr; + + fn next(&mut self) -> Option<&'a OsStr> { + debugln!("OsSplit::next: self={:?}", self); + if self.pos == self.val.len() { + return None; + } + let start = self.pos; + for b in &self.val[start..] { + self.pos += 1; + if *b == self.sep { + return Some(OsStr::from_bytes(&self.val[start..self.pos - 1])); + } + } + Some(OsStr::from_bytes(&self.val[start..])) + } +} diff --git a/bash-5.1/vendor/clap/src/strext.rs b/bash-5.1/vendor/clap/src/strext.rs new file mode 100644 index 0000000..52efab6 --- /dev/null +++ b/bash-5.1/vendor/clap/src/strext.rs @@ -0,0 +1,16 @@ +pub trait _StrExt { + fn _is_char_boundary(&self, index: usize) -> bool; +} + +impl _StrExt for str { + #[inline] + fn _is_char_boundary(&self, index: usize) -> bool { + if index == self.len() { + return true; + } + match self.as_bytes().get(index) { + None => false, + Some(&b) => !(128..192).contains(&b), + } + } +} diff --git a/bash-5.1/vendor/clap/src/suggestions.rs b/bash-5.1/vendor/clap/src/suggestions.rs new file mode 100644 index 0000000..5c54988 --- /dev/null +++ b/bash-5.1/vendor/clap/src/suggestions.rs @@ -0,0 +1,141 @@ +// Internal +use crate::{app::App, fmt::Format}; + +/// Produces a string from a given list of possible values which is similar to +/// the passed in value `v` with a certain confidence. +/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield +/// `Some("foo")`, whereas "blark" would yield `None`. +#[cfg(feature = "suggestions")] +#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_lifetimes))] +pub fn did_you_mean<'a, T: ?Sized, I>(v: &str, possible_values: I) -> Option<&'a str> +where + T: AsRef + 'a, + I: IntoIterator, +{ + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv.as_ref()); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) + { + candidate = Some((confidence, pv.as_ref())); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +#[cfg(not(feature = "suggestions"))] +pub fn did_you_mean<'a, T: ?Sized, I>(_: &str, _: I) -> Option<&'a str> +where + T: AsRef + 'a, + I: IntoIterator, +{ + None +} + +/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase +pub fn did_you_mean_flag_suffix<'z, T, I>( + arg: &str, + args_rest: &'z [&str], + longs: I, + subcommands: &'z [App], +) -> (String, Option<&'z str>) +where + T: AsRef + 'z, + I: IntoIterator, +{ + if let Some(candidate) = did_you_mean(arg, longs) { + let suffix = format!( + "\n\tDid you mean {}{}?", + Format::Good("--"), + Format::Good(candidate) + ); + return (suffix, Some(candidate)); + } + + subcommands + .iter() + .filter_map(|subcommand| { + let opts = subcommand + .p + .flags + .iter() + .filter_map(|f| f.s.long) + .chain(subcommand.p.opts.iter().filter_map(|o| o.s.long)); + + let candidate = match did_you_mean(arg, opts) { + Some(candidate) => candidate, + None => return None, + }; + let score = match args_rest.iter().position(|x| *x == subcommand.get_name()) { + Some(score) => score, + None => return None, + }; + + let suffix = format!( + "\n\tDid you mean to put '{}{}' after the subcommand '{}'?", + Format::Good("--"), + Format::Good(candidate), + Format::Good(subcommand.get_name()) + ); + + Some((score, (suffix, Some(candidate)))) + }) + .min_by_key(|&(score, _)| score) + .map(|(_, suggestion)| suggestion) + .unwrap_or_else(|| (String::new(), None)) +} + +/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase +pub fn did_you_mean_value_suffix<'z, T, I>(arg: &str, values: I) -> (String, Option<&'z str>) +where + T: AsRef + 'z, + I: IntoIterator, +{ + match did_you_mean(arg, values) { + Some(candidate) => { + let suffix = format!("\n\tDid you mean '{}'?", Format::Good(candidate)); + (suffix, Some(candidate)) + } + None => (String::new(), None), + } +} + +#[cfg(all(test, features = "suggestions"))] +mod test { + use super::*; + + #[test] + fn possible_values_match() { + let p_vals = ["test", "possible", "values"]; + assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test")); + } + + #[test] + fn possible_values_nomatch() { + let p_vals = ["test", "possible", "values"]; + assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none()); + } + + #[test] + fn suffix_long() { + let p_vals = ["test", "possible", "values"]; + let suffix = "\n\tDid you mean \'--test\'?"; + assert_eq!( + did_you_mean_flag_suffix("tst", p_vals.iter(), []), + (suffix, Some("test")) + ); + } + + #[test] + fn suffix_enum() { + let p_vals = ["test", "possible", "values"]; + let suffix = "\n\tDid you mean \'test\'?"; + assert_eq!( + did_you_mean_value_suffix("tst", p_vals.iter()), + (suffix, Some("test")) + ); + } +} diff --git a/bash-5.1/vendor/clap/src/usage_parser.rs b/bash-5.1/vendor/clap/src/usage_parser.rs new file mode 100644 index 0000000..d3c1921 --- /dev/null +++ b/bash-5.1/vendor/clap/src/usage_parser.rs @@ -0,0 +1,1356 @@ +// Internal +use crate::{ + args::{settings::ArgSettings, Arg}, + map::VecMap, + INTERNAL_ERROR_MSG, +}; + +#[derive(PartialEq, Debug)] +enum UsageToken { + Name, + ValName, + Short, + Long, + Help, + Multiple, + Unknown, +} + +#[doc(hidden)] +#[derive(Debug)] +pub struct UsageParser<'a> { + usage: &'a str, + pos: usize, + start: usize, + prev: UsageToken, + explicit_name_set: bool, +} + +impl<'a> UsageParser<'a> { + fn new(usage: &'a str) -> Self { + debugln!("UsageParser::new: usage={:?}", usage); + UsageParser { + usage, + pos: 0, + start: 0, + prev: UsageToken::Unknown, + explicit_name_set: false, + } + } + + pub fn from_usage(usage: &'a str) -> Self { + debugln!("UsageParser::from_usage;"); + UsageParser::new(usage) + } + + pub fn parse(mut self) -> Arg<'a, 'a> { + debugln!("UsageParser::parse;"); + let mut arg = Arg::default(); + loop { + debugln!("UsageParser::parse:iter: pos={};", self.pos); + self.stop_at(token); + if let Some(&c) = self.usage.as_bytes().get(self.pos) { + match c { + b'-' => self.short_or_long(&mut arg), + b'.' => self.multiple(&mut arg), + b'\'' => self.help(&mut arg), + _ => self.name(&mut arg), + } + } else { + break; + } + } + debug_assert!( + !arg.b.name.is_empty(), + "No name found for Arg when parsing usage string: {}", + self.usage + ); + arg.v.num_vals = match arg.v.val_names { + Some(ref v) if v.len() >= 2 => Some(v.len() as u64), + _ => None, + }; + debugln!("UsageParser::parse: vals...{:?}", arg.v.val_names); + arg + } + + fn name(&mut self, arg: &mut Arg<'a, 'a>) { + debugln!("UsageParser::name;"); + if *self + .usage + .as_bytes() + .get(self.pos) + .expect(INTERNAL_ERROR_MSG) + == b'<' + && !self.explicit_name_set + { + arg.setb(ArgSettings::Required); + } + self.pos += 1; + self.stop_at(name_end); + let name = &self.usage[self.start..self.pos]; + if self.prev == UsageToken::Unknown { + debugln!("UsageParser::name: setting name...{}", name); + arg.b.name = name; + if arg.s.long.is_none() && arg.s.short.is_none() { + debugln!("UsageParser::name: explicit name set..."); + self.explicit_name_set = true; + self.prev = UsageToken::Name; + } + } else { + debugln!("UsageParser::name: setting val name...{}", name); + if let Some(ref mut v) = arg.v.val_names { + let len = v.len(); + v.insert(len, name); + } else { + let mut v = VecMap::new(); + v.insert(0, name); + arg.v.val_names = Some(v); + arg.setb(ArgSettings::TakesValue); + } + self.prev = UsageToken::ValName; + } + } + + fn stop_at(&mut self, f: F) + where + F: Fn(u8) -> bool, + { + debugln!("UsageParser::stop_at;"); + self.start = self.pos; + self.pos += self.usage[self.start..] + .bytes() + .take_while(|&b| f(b)) + .count(); + } + + fn short_or_long(&mut self, arg: &mut Arg<'a, 'a>) { + debugln!("UsageParser::short_or_long;"); + self.pos += 1; + if *self + .usage + .as_bytes() + .get(self.pos) + .expect(INTERNAL_ERROR_MSG) + == b'-' + { + self.pos += 1; + self.long(arg); + return; + } + self.short(arg) + } + + fn long(&mut self, arg: &mut Arg<'a, 'a>) { + debugln!("UsageParser::long;"); + self.stop_at(long_end); + let name = &self.usage[self.start..self.pos]; + if !self.explicit_name_set { + debugln!("UsageParser::long: setting name...{}", name); + arg.b.name = name; + } + debugln!("UsageParser::long: setting long...{}", name); + arg.s.long = Some(name); + self.prev = UsageToken::Long; + } + + fn short(&mut self, arg: &mut Arg<'a, 'a>) { + debugln!("UsageParser::short;"); + let start = &self.usage[self.pos..]; + let short = start.chars().next().expect(INTERNAL_ERROR_MSG); + debugln!("UsageParser::short: setting short...{}", short); + arg.s.short = Some(short); + if arg.b.name.is_empty() { + // --long takes precedence but doesn't set self.explicit_name_set + let name = &start[..short.len_utf8()]; + debugln!("UsageParser::short: setting name...{}", name); + arg.b.name = name; + } + self.prev = UsageToken::Short; + } + + // "something..." + fn multiple(&mut self, arg: &mut Arg) { + debugln!("UsageParser::multiple;"); + let mut dot_counter = 1; + let start = self.pos; + let mut bytes = self.usage[start..].bytes(); + while bytes.next() == Some(b'.') { + dot_counter += 1; + self.pos += 1; + if dot_counter == 3 { + debugln!("UsageParser::multiple: setting multiple"); + arg.setb(ArgSettings::Multiple); + if arg.is_set(ArgSettings::TakesValue) { + arg.setb(ArgSettings::UseValueDelimiter); + arg.unsetb(ArgSettings::ValueDelimiterNotSet); + if arg.v.val_delim.is_none() { + arg.v.val_delim = Some(','); + } + } + self.prev = UsageToken::Multiple; + self.pos += 1; + break; + } + } + } + + fn help(&mut self, arg: &mut Arg<'a, 'a>) { + debugln!("UsageParser::help;"); + self.stop_at(help_start); + self.start = self.pos + 1; + self.pos = self.usage.len() - 1; + debugln!( + "UsageParser::help: setting help...{}", + &self.usage[self.start..self.pos] + ); + arg.b.help = Some(&self.usage[self.start..self.pos]); + self.pos += 1; // Move to next byte to keep from thinking ending ' is a start + self.prev = UsageToken::Help; + } +} + +#[inline] +fn name_end(b: u8) -> bool { + b != b']' && b != b'>' +} + +#[inline] +fn token(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' +} + +#[inline] +fn long_end(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' ' +} + +#[inline] +fn help_start(b: u8) -> bool { + b != b'\'' +} + +#[cfg(test)] +mod test { + use crate::args::{Arg, ArgSettings}; + + #[test] + fn create_flag_usage() { + let a = Arg::from_usage("[flag] -f 'some help info'"); + assert_eq!(a.b.name, "flag"); + assert_eq!(a.s.short.unwrap(), 'f'); + assert!(a.s.long.is_none()); + assert_eq!(a.b.help.unwrap(), "some help info"); + assert!(!a.is_set(ArgSettings::Multiple)); + assert!(a.v.val_names.is_none()); + assert!(a.v.num_vals.is_none()); + + let b = Arg::from_usage("[flag] --flag 'some help info'"); + assert_eq!(b.b.name, "flag"); + assert_eq!(b.s.long.unwrap(), "flag"); + assert!(b.s.short.is_none()); + assert_eq!(b.b.help.unwrap(), "some help info"); + assert!(!b.is_set(ArgSettings::Multiple)); + assert!(a.v.val_names.is_none()); + assert!(a.v.num_vals.is_none()); + + let b = Arg::from_usage("--flag 'some help info'"); + assert_eq!(b.b.name, "flag"); + assert_eq!(b.s.long.unwrap(), "flag"); + assert!(b.s.short.is_none()); + assert_eq!(b.b.help.unwrap(), "some help info"); + assert!(!b.is_set(ArgSettings::Multiple)); + assert!(b.v.val_names.is_none()); + assert!(b.v.num_vals.is_none()); + + let c = Arg::from_usage("[flag] -f --flag 'some help info'"); + assert_eq!(c.b.name, "flag"); + assert_eq!(c.s.short.unwrap(), 'f'); + assert_eq!(c.s.long.unwrap(), "flag"); + assert_eq!(c.b.help.unwrap(), "some help info"); + assert!(!c.is_set(ArgSettings::Multiple)); + assert!(c.v.val_names.is_none()); + assert!(c.v.num_vals.is_none()); + + let d = Arg::from_usage("[flag] -f... 'some help info'"); + assert_eq!(d.b.name, "flag"); + assert_eq!(d.s.short.unwrap(), 'f'); + assert!(d.s.long.is_none()); + assert_eq!(d.b.help.unwrap(), "some help info"); + assert!(d.is_set(ArgSettings::Multiple)); + assert!(d.v.val_names.is_none()); + assert!(d.v.num_vals.is_none()); + + let e = Arg::from_usage("[flag] -f --flag... 'some help info'"); + assert_eq!(e.b.name, "flag"); + assert_eq!(e.s.long.unwrap(), "flag"); + assert_eq!(e.s.short.unwrap(), 'f'); + assert_eq!(e.b.help.unwrap(), "some help info"); + assert!(e.is_set(ArgSettings::Multiple)); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let e = Arg::from_usage("-f --flag... 'some help info'"); + assert_eq!(e.b.name, "flag"); + assert_eq!(e.s.long.unwrap(), "flag"); + assert_eq!(e.s.short.unwrap(), 'f'); + assert_eq!(e.b.help.unwrap(), "some help info"); + assert!(e.is_set(ArgSettings::Multiple)); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let e = Arg::from_usage("--flags"); + assert_eq!(e.b.name, "flags"); + assert_eq!(e.s.long.unwrap(), "flags"); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let e = Arg::from_usage("--flags..."); + assert_eq!(e.b.name, "flags"); + assert_eq!(e.s.long.unwrap(), "flags"); + assert!(e.is_set(ArgSettings::Multiple)); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let e = Arg::from_usage("[flags] -f"); + assert_eq!(e.b.name, "flags"); + assert_eq!(e.s.short.unwrap(), 'f'); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let e = Arg::from_usage("[flags] -f..."); + assert_eq!(e.b.name, "flags"); + assert_eq!(e.s.short.unwrap(), 'f'); + assert!(e.is_set(ArgSettings::Multiple)); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let a = Arg::from_usage("-f 'some help info'"); + assert_eq!(a.b.name, "f"); + assert_eq!(a.s.short.unwrap(), 'f'); + assert!(a.s.long.is_none()); + assert_eq!(a.b.help.unwrap(), "some help info"); + assert!(!a.is_set(ArgSettings::Multiple)); + assert!(a.v.val_names.is_none()); + assert!(a.v.num_vals.is_none()); + + let e = Arg::from_usage("-f"); + assert_eq!(e.b.name, "f"); + assert_eq!(e.s.short.unwrap(), 'f'); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + + let e = Arg::from_usage("-f..."); + assert_eq!(e.b.name, "f"); + assert_eq!(e.s.short.unwrap(), 'f'); + assert!(e.is_set(ArgSettings::Multiple)); + assert!(e.v.val_names.is_none()); + assert!(e.v.num_vals.is_none()); + } + + #[test] + fn create_option_usage0() { + // Short only + let a = Arg::from_usage("[option] -o [opt] 'some help info'"); + assert_eq!(a.b.name, "option"); + assert_eq!(a.s.short.unwrap(), 'o'); + assert!(a.s.long.is_none()); + assert_eq!(a.b.help.unwrap(), "some help info"); + assert!(!a.is_set(ArgSettings::Multiple)); + assert!(a.is_set(ArgSettings::TakesValue)); + assert!(!a.is_set(ArgSettings::Required)); + assert_eq!( + a.v.val_names.unwrap().values().collect::>(), + [&"opt"] + ); + assert!(a.v.num_vals.is_none()); + } + + #[test] + fn create_option_usage1() { + let b = Arg::from_usage("-o [opt] 'some help info'"); + assert_eq!(b.b.name, "o"); + assert_eq!(b.s.short.unwrap(), 'o'); + assert!(b.s.long.is_none()); + assert_eq!(b.b.help.unwrap(), "some help info"); + assert!(!b.is_set(ArgSettings::Multiple)); + assert!(b.is_set(ArgSettings::TakesValue)); + assert!(!b.is_set(ArgSettings::Required)); + assert_eq!( + b.v.val_names.unwrap().values().collect::>(), + [&"opt"] + ); + assert!(b.v.num_vals.is_none()); + } + + #[test] + fn create_option_usage2() { + let c = Arg::from_usage("Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bash-5.1/vendor/displaydoc/README.tpl b/bash-5.1/vendor/displaydoc/README.tpl new file mode 100644 index 0000000..6206a9e --- /dev/null +++ b/bash-5.1/vendor/displaydoc/README.tpl @@ -0,0 +1,23 @@ +derive(Display) /// `From` +=============== + +[![Latest Version](https://img.shields.io/crates/v/displaydoc.svg)](https://crates.io/crates/displaydoc) +[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/displaydoc) + +{{readme}} + + +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bash-5.1/vendor/displaydoc/examples/simple.rs b/bash-5.1/vendor/displaydoc/examples/simple.rs new file mode 100644 index 0000000..f4aad21 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/examples/simple.rs @@ -0,0 +1,36 @@ +use displaydoc::Display; + +#[derive(Debug, Display)] +pub enum DataStoreError { + /// data store disconnected + Disconnect, + /// the data for key `{0}` is not available + Redaction(String), + /// invalid header (expected {expected:?}, found {found:?}) + InvalidHeader { expected: String, found: String }, + /// unknown data store error + Unknown, +} + +fn main() { + let disconnect = DataStoreError::Disconnect; + println!( + "Enum value `Disconnect` should be printed as:\n\t{}", + disconnect + ); + + let redaction = DataStoreError::Redaction(String::from("Dummy")); + println!( + "Enum value `Redaction` should be printed as:\n\t{}", + redaction + ); + + let invalid_header = DataStoreError::InvalidHeader { + expected: String::from("https"), + found: String::from("http"), + }; + println!( + "Enum value `InvalidHeader` should be printed as:\n\t{}", + invalid_header + ); +} diff --git a/bash-5.1/vendor/displaydoc/src/attr.rs b/bash-5.1/vendor/displaydoc/src/attr.rs new file mode 100644 index 0000000..e145935 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/src/attr.rs @@ -0,0 +1,134 @@ +use proc_macro2::TokenStream; +use quote::{quote, ToTokens}; +use syn::{Attribute, LitStr, Meta, Result}; + +#[derive(Clone)] +pub(crate) struct Display { + pub(crate) fmt: LitStr, + pub(crate) args: TokenStream, +} + +pub(crate) struct VariantDisplay { + pub(crate) r#enum: Option, + pub(crate) variant: Display, +} + +impl ToTokens for Display { + fn to_tokens(&self, tokens: &mut TokenStream) { + let fmt = &self.fmt; + let args = &self.args; + tokens.extend(quote! { + write!(formatter, #fmt #args) + }); + } +} + +impl ToTokens for VariantDisplay { + fn to_tokens(&self, tokens: &mut TokenStream) { + if let Some(ref r#enum) = self.r#enum { + r#enum.to_tokens(tokens); + tokens.extend(quote! { ?; write!(formatter, ": ")?; }); + } + self.variant.to_tokens(tokens); + } +} + +pub(crate) struct AttrsHelper { + ignore_extra_doc_attributes: bool, + prefix_enum_doc_attributes: bool, +} + +impl AttrsHelper { + pub(crate) fn new(attrs: &[Attribute]) -> Self { + let ignore_extra_doc_attributes = attrs + .iter() + .any(|attr| attr.path.is_ident("ignore_extra_doc_attributes")); + let prefix_enum_doc_attributes = attrs + .iter() + .any(|attr| attr.path.is_ident("prefix_enum_doc_attributes")); + + Self { + ignore_extra_doc_attributes, + prefix_enum_doc_attributes, + } + } + + pub(crate) fn display(&self, attrs: &[Attribute]) -> Result> { + let displaydoc_attr = attrs.iter().find(|attr| attr.path.is_ident("displaydoc")); + + if let Some(displaydoc_attr) = displaydoc_attr { + let lit = displaydoc_attr + .parse_args() + .expect("#[displaydoc(\"foo\")] must contain string arguments"); + let mut display = Display { + fmt: lit, + args: TokenStream::new(), + }; + + display.expand_shorthand(); + return Ok(Some(display)); + } + + let num_doc_attrs = attrs + .iter() + .filter(|attr| attr.path.is_ident("doc")) + .count(); + + if !self.ignore_extra_doc_attributes && num_doc_attrs > 1 { + panic!("Multi-line comments are disabled by default by displaydoc. Please consider using block doc comments (/** */) or adding the #[ignore_extra_doc_attributes] attribute to your type next to the derive."); + } + + for attr in attrs { + if attr.path.is_ident("doc") { + let meta = attr.parse_meta()?; + let lit = match meta { + Meta::NameValue(syn::MetaNameValue { + lit: syn::Lit::Str(lit), + .. + }) => lit, + _ => unimplemented!(), + }; + + // Make an attempt and cleaning up multiline doc comments + let doc_str = lit + .value() + .lines() + .map(|line| line.trim().trim_start_matches('*').trim()) + .collect::>() + .join("\n"); + + let lit = LitStr::new(doc_str.trim(), lit.span()); + + let mut display = Display { + fmt: lit, + args: TokenStream::new(), + }; + + display.expand_shorthand(); + return Ok(Some(display)); + } + } + + Ok(None) + } + + pub(crate) fn display_with_input( + &self, + r#enum: &[Attribute], + variant: &[Attribute], + ) -> Result> { + let r#enum = if self.prefix_enum_doc_attributes { + let result = self + .display(r#enum)? + .expect("Missing doc comment on enum with #[prefix_enum_doc_attributes]. Please remove the attribute or add a doc comment to the enum itself."); + + Some(result) + } else { + None + }; + + Ok(self + .display(variant)? + .map(|variant| VariantDisplay { r#enum, variant })) + } +} diff --git a/bash-5.1/vendor/displaydoc/src/expand.rs b/bash-5.1/vendor/displaydoc/src/expand.rs new file mode 100644 index 0000000..6904cbc --- /dev/null +++ b/bash-5.1/vendor/displaydoc/src/expand.rs @@ -0,0 +1,145 @@ +use super::attr::AttrsHelper; +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::{Data, DataEnum, DataStruct, DeriveInput, Error, Fields, Result}; + +pub(crate) fn derive(input: &DeriveInput) -> Result { + let impls = match &input.data { + Data::Struct(data) => impl_struct(input, data), + Data::Enum(data) => impl_enum(input, data), + Data::Union(_) => Err(Error::new_spanned(input, "Unions are not supported")), + }?; + + let helpers = specialization(); + let dummy_const = format_ident!("_DERIVE_Display_FOR_{}", input.ident); + Ok(quote! { + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const #dummy_const: () = { + #helpers + #impls + }; + }) +} + +#[cfg(feature = "std")] +fn specialization() -> TokenStream { + quote! { + trait DisplayToDisplayDoc { + fn __displaydoc_display(&self) -> Self; + } + + impl DisplayToDisplayDoc for &T { + fn __displaydoc_display(&self) -> Self { + self + } + } + + // If the `std` feature gets enabled we want to ensure that any crate + // using displaydoc can still reference the std crate, which is already + // being compiled in by whoever enabled the `std` feature in + // `displaydoc`, even if the crates using displaydoc are no_std. + extern crate std; + + trait PathToDisplayDoc { + fn __displaydoc_display(&self) -> std::path::Display<'_>; + } + + impl PathToDisplayDoc for std::path::Path { + fn __displaydoc_display(&self) -> std::path::Display<'_> { + self.display() + } + } + + impl PathToDisplayDoc for std::path::PathBuf { + fn __displaydoc_display(&self) -> std::path::Display<'_> { + self.display() + } + } + } +} + +#[cfg(not(feature = "std"))] +fn specialization() -> TokenStream { + quote! {} +} + +fn impl_struct(input: &DeriveInput, data: &DataStruct) -> Result { + let ty = &input.ident; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + + let helper = AttrsHelper::new(&input.attrs); + + let display = helper.display(&input.attrs)?.map(|display| { + let pat = match &data.fields { + Fields::Named(fields) => { + let var = fields.named.iter().map(|field| &field.ident); + quote!(Self { #(#var),* }) + } + Fields::Unnamed(fields) => { + let var = (0..fields.unnamed.len()).map(|i| format_ident!("_{}", i)); + quote!(Self(#(#var),*)) + } + Fields::Unit => quote!(_), + }; + quote! { + impl #impl_generics core::fmt::Display for #ty #ty_generics #where_clause { + fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { + #[allow(unused_variables)] + let #pat = self; + #display + } + } + } + }); + + Ok(quote! { #display }) +} + +fn impl_enum(input: &DeriveInput, data: &DataEnum) -> Result { + let ty = &input.ident; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + + let helper = AttrsHelper::new(&input.attrs); + + let displays = data + .variants + .iter() + .map(|variant| helper.display_with_input(&input.attrs, &variant.attrs)) + .collect::>>()?; + + if displays.iter().any(Option::is_some) { + let arms = data + .variants + .iter() + .zip(displays) + .map(|(variant, display)| { + let display = + display.ok_or_else(|| Error::new_spanned(variant, "missing doc comment"))?; + let ident = &variant.ident; + Ok(match &variant.fields { + Fields::Named(fields) => { + let var = fields.named.iter().map(|field| &field.ident); + quote!(#ty::#ident { #(#var),* } => { #display }) + } + Fields::Unnamed(fields) => { + let var = (0..fields.unnamed.len()).map(|i| format_ident!("_{}", i)); + quote!(#ty::#ident(#(#var),*) => { #display }) + } + Fields::Unit => quote!(#ty::#ident => { #display }), + }) + }) + .collect::>>()?; + Ok(quote! { + impl #impl_generics core::fmt::Display for #ty #ty_generics #where_clause { + fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { + #[allow(unused_variables)] + match self { + #(#arms,)* + } + } + } + }) + } else { + Err(Error::new_spanned(input, "Missing doc comments")) + } +} diff --git a/bash-5.1/vendor/displaydoc/src/fmt.rs b/bash-5.1/vendor/displaydoc/src/fmt.rs new file mode 100644 index 0000000..5848557 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/src/fmt.rs @@ -0,0 +1,159 @@ +use crate::attr::Display; +use proc_macro2::TokenStream; +use quote::quote_spanned; +use syn::{Ident, LitStr}; + +macro_rules! peek_next { + ($read:ident) => { + match $read.chars().next() { + Some(next) => next, + None => return, + } + }; +} + +impl Display { + // Transform `"error {var}"` to `"error {}", var`. + pub(crate) fn expand_shorthand(&mut self) { + let span = self.fmt.span(); + let fmt = self.fmt.value(); + let mut read = fmt.as_str(); + let mut out = String::new(); + let mut args = TokenStream::new(); + + while let Some(brace) = read.find('{') { + out += &read[..=brace]; + read = &read[brace + 1..]; + + // skip cases where we find a {{ + if read.starts_with('{') { + out.push('{'); + read = &read[1..]; + continue; + } + + let next = peek_next!(read); + + let var = match next { + '0'..='9' => take_int(&mut read), + 'a'..='z' | 'A'..='Z' | '_' => take_ident(&mut read), + _ => return, + }; + + let ident = Ident::new(&var, span); + + let next = peek_next!(read); + + let arg = if cfg!(feature = "std") && next == '}' { + quote_spanned!(span=> , #ident.__displaydoc_display()) + } else { + quote_spanned!(span=> , #ident) + }; + + args.extend(arg); + } + + out += read; + self.fmt = LitStr::new(&out, self.fmt.span()); + self.args = args; + } +} + +fn take_int(read: &mut &str) -> String { + let mut int = String::new(); + int.push('_'); + for (i, ch) in read.char_indices() { + match ch { + '0'..='9' => int.push(ch), + _ => { + *read = &read[i..]; + break; + } + } + } + int +} + +fn take_ident(read: &mut &str) -> String { + let mut ident = String::new(); + for (i, ch) in read.char_indices() { + match ch { + 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => ident.push(ch), + _ => { + *read = &read[i..]; + break; + } + } + } + ident +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use proc_macro2::Span; + + fn assert(input: &str, fmt: &str, args: &str) { + let mut display = Display { + fmt: LitStr::new(input, Span::call_site()), + args: TokenStream::new(), + }; + display.expand_shorthand(); + assert_eq!(fmt, display.fmt.value()); + assert_eq!(args, display.args.to_string()); + } + + #[test] + fn test_expand() { + assert("fn main() {{ }}", "fn main() {{ }}", ""); + } + + #[test] + #[cfg_attr(not(feature = "std"), ignore)] + fn test_std_expand() { + assert( + "{v} {v:?} {0} {0:?}", + "{} {:?} {} {:?}", + ", v . __displaydoc_display () , v , _0 . __displaydoc_display () , _0", + ); + assert("error {var}", "error {}", ", var . __displaydoc_display ()"); + + assert( + "error {var1}", + "error {}", + ", var1 . __displaydoc_display ()", + ); + + assert( + "error {var1var}", + "error {}", + ", var1var . __displaydoc_display ()", + ); + + assert( + "The path {0}", + "The path {}", + ", _0 . __displaydoc_display ()", + ); + assert("The path {0:?}", "The path {:?}", ", _0"); + } + + #[test] + #[cfg_attr(feature = "std", ignore)] + fn test_nostd_expand() { + assert( + "{v} {v:?} {0} {0:?}", + "{} {:?} {} {:?}", + ", v , v , _0 , _0", + ); + assert("error {var}", "error {}", ", var"); + + assert("The path {0}", "The path {}", ", _0"); + assert("The path {0:?}", "The path {:?}", ", _0"); + + assert("error {var1}", "error {}", ", var1"); + + assert("error {var1var}", "error {}", ", var1var"); + } +} diff --git a/bash-5.1/vendor/displaydoc/src/lib.rs b/bash-5.1/vendor/displaydoc/src/lib.rs new file mode 100644 index 0000000..083c613 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/src/lib.rs @@ -0,0 +1,122 @@ +//! This library provides a convenient derive macro for the standard library's +//! [`core::fmt::Display`] trait. +//! +//! [`core::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html +//! +//! ```toml +//! [dependencies] +//! displaydoc = "0.2" +//! ``` +//! +//! *Compiler support: requires rustc 1.31+* +//! +//!
+//! +//! ## Example +//! +//! ```rust +//! use std::io; +//! use displaydoc::Display; +//! use thiserror::Error; +//! +//! #[derive(Display, Error, Debug)] +//! pub enum DataStoreError { +//! /// data store disconnected +//! Disconnect(#[source] io::Error), +//! /// the data for key `{0}` is not available +//! Redaction(String), +//! /// invalid header (expected {expected:?}, found {found:?}) +//! InvalidHeader { +//! expected: String, +//! found: String, +//! }, +//! /// unknown data store error +//! Unknown, +//! } +//! ``` +//! +//!
+//! +//! ## Details +//! +//! - A `Display` impl is generated for your type if you provide doc comment +//! messages on the struct or each variant of your enum, as shown above in the +//! example. +//! +//! The messages support a shorthand for interpolating fields from the error. +//! +//! - `/// {var}` ⟶ `write!("{}", self.var)` +//! - `/// {0}` ⟶ `write!("{}", self.0)` +//! - `/// {var:?}` ⟶ `write!("{:?}", self.var)` +//! - `/// {0:?}` ⟶ `write!("{:?}", self.0)` +//! +//! - Two optional attributes can be added to your types next to the derive: +//! +//! - `#[ignore_extra_doc_attributes]` makes the macro ignore any doc +//! comment attributes (or `///` lines) after the first. Multi-line +//! comments using `///` are otherwise treated as an error, so use this +//! attribute or consider switching to block doc comments (`/** */`). +//! +//! - `#[prefix_enum_doc_attributes]` combines the doc comment message on +//! your enum itself with the messages for each variant, in the format +//! “enum: variant”. When added to an enum, the doc comment on the enum +//! becomes mandatory. When added to any other type, it has no effect. +//! +//! - In case you want to have an independent doc comment, the +//! `#[displaydoc("...")` atrribute may be used on the variant or struct to +//! override it. +//! +//!
+//! +//! ## FAQ +//! +//! 1. **Is this crate `no_std` compatible?** +//! * Yes! This crate implements the `core::fmt::Display` trait not the `std::fmt::Display` trait so it should work in `std` and `no_std` environments. Just add `default-features = false`. +//! +//! 2. **Does this crate work with `Path` and `PathBuf` via the `Display` trait?** +//! * Yuuup. This crate uses @dtolnay's [autoref specialization technique](https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md) to add a special trait for types to get the display impl, it then specializes for `Path` and `PathBuf` and when either of these types are found it calls `self.display()` to get a `std::path::Display<'_>` type which can be used with the Display format specifier! +#![doc(html_root_url = "https://docs.rs/displaydoc/0.2.3")] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![warn( + rust_2018_idioms, + unreachable_pub, + bad_style, + const_err, + dead_code, + improper_ctypes, + non_shorthand_field_patterns, + no_mangle_generic_items, + overflowing_literals, + path_statements, + patterns_in_fns_without_body, + private_in_public, + unconditional_recursion, + unused, + unused_allocation, + unused_comparisons, + unused_parens, + while_true +)] +#![allow(clippy::try_err)] + +#[allow(unused_extern_crates)] +extern crate proc_macro; + +mod attr; +mod expand; +mod fmt; + +use proc_macro::TokenStream; +use syn::{parse_macro_input, DeriveInput}; + +/// Derive macro for implementing `Display` via doc comment attributes +#[proc_macro_derive( + Display, + attributes(ignore_extra_doc_attributes, prefix_enum_doc_attributes, displaydoc) +)] +pub fn derive_error(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + expand::derive(&input) + .unwrap_or_else(|err| err.to_compile_error()) + .into() +} diff --git a/bash-5.1/vendor/displaydoc/tests/compile_tests.rs b/bash-5.1/vendor/displaydoc/tests/compile_tests.rs new file mode 100644 index 0000000..29c72a8 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/compile_tests.rs @@ -0,0 +1,29 @@ +#[allow(unused_attributes)] +#[rustversion::attr(not(nightly), ignore)] +#[test] +fn no_std() { + let t = trybuild::TestCases::new(); + #[cfg(not(feature = "std"))] + t.compile_fail("tests/no_std/without.rs"); + #[cfg(not(feature = "std"))] + t.compile_fail("tests/no_std/multi_line.rs"); + #[cfg(not(feature = "std"))] + t.pass("tests/no_std/multi_line_allow.rs"); + #[cfg(not(feature = "std"))] + t.compile_fail("tests/no_std/enum_prefix_missing.rs"); + #[cfg(not(feature = "std"))] + t.pass("tests/no_std/enum_prefix.rs"); + #[cfg(feature = "std")] + t.compile_fail("tests/std/without.rs"); + #[cfg(feature = "std")] + t.compile_fail("tests/std/multi_line.rs"); + #[cfg(feature = "std")] + t.pass("tests/std/multi_line_allow.rs"); + #[cfg(feature = "std")] + t.compile_fail("tests/std/enum_prefix_missing.rs"); + #[cfg(feature = "std")] + t.pass("tests/std/enum_prefix.rs"); + #[cfg(feature = "std")] + t.pass("tests/std/multiple.rs"); + t.pass("tests/no_std/with.rs"); +} diff --git a/bash-5.1/vendor/displaydoc/tests/happy.rs b/bash-5.1/vendor/displaydoc/tests/happy.rs new file mode 100644 index 0000000..85aa78f --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/happy.rs @@ -0,0 +1,152 @@ +use displaydoc::Display; + +#[cfg(feature = "std")] +use std::path::PathBuf; + +#[derive(Display)] +/// Just a basic struct {thing} +struct HappyStruct { + thing: &'static str, +} + +#[derive(Display)] +#[ignore_extra_doc_attributes] +/// Just a basic struct {thing} +/// and this line should get ignored +struct HappyStruct2 { + thing: &'static str, +} + +#[derive(Display)] +enum Happy { + /// I really like Variant1 + Variant1, + /// Variant2 is pretty swell 2 + Variant2, + /// Variant3 is okay {sometimes} + Variant3 { sometimes: &'static str }, + /** + * Variant4 wants to have a lot of lines + * + * Lets see how this works out for it + */ + Variant4, + /// Variant5 has a parameter {0} and some regular comments + // A regular comment that won't get picked + Variant5(u32), + + /// The path {0} + #[cfg(feature = "std")] + Variant6(PathBuf), + + /// These docs are ignored + #[displaydoc("Variant7 has a parameter {0} and uses #[displaydoc]")] + /// These docs are also ignored + Variant7(u32), +} + +// Used for testing indented doc comments +mod inner_mod { + use super::Display; + + #[derive(Display)] + pub enum InnerHappy { + /// I really like Variant1 + Variant1, + /// Variant2 is pretty swell 2 + Variant2, + /// Variant3 is okay {sometimes} + Variant3 { sometimes: &'static str }, + /** + * Variant4 wants to have a lot of lines + * + * Lets see how this works out for it + */ + Variant4, + /// Variant5 has a parameter {0} and some regular comments + // A regular comment that won't get picked + Variant5(u32), + + /** what happens if we + * put text on the first line? + */ + Variant6, + + /** + what happens if we don't use *? + */ + Variant7, + + /** + * + * what about extra new lines? + */ + Variant8, + } +} + +fn assert_display(input: T, expected: &'static str) { + let out = format!("{}", input); + assert_eq!(expected, out); +} + +#[test] +fn does_it_print() { + assert_display(Happy::Variant1, "I really like Variant1"); + assert_display(Happy::Variant2, "Variant2 is pretty swell 2"); + assert_display(Happy::Variant3 { sometimes: "hi" }, "Variant3 is okay hi"); + assert_display( + Happy::Variant4, + "Variant4 wants to have a lot of lines\n\nLets see how this works out for it", + ); + assert_display( + Happy::Variant5(2), + "Variant5 has a parameter 2 and some regular comments", + ); + assert_display( + Happy::Variant7(2), + "Variant7 has a parameter 2 and uses #[displaydoc]", + ); + assert_display(HappyStruct { thing: "hi" }, "Just a basic struct hi"); + + assert_display(HappyStruct2 { thing: "hi2" }, "Just a basic struct hi2"); + + assert_display(inner_mod::InnerHappy::Variant1, "I really like Variant1"); + assert_display( + inner_mod::InnerHappy::Variant2, + "Variant2 is pretty swell 2", + ); + assert_display( + inner_mod::InnerHappy::Variant3 { sometimes: "hi" }, + "Variant3 is okay hi", + ); + assert_display( + inner_mod::InnerHappy::Variant4, + "Variant4 wants to have a lot of lines\n\nLets see how this works out for it", + ); + assert_display( + inner_mod::InnerHappy::Variant5(2), + "Variant5 has a parameter 2 and some regular comments", + ); + assert_display( + inner_mod::InnerHappy::Variant6, + "what happens if we\nput text on the first line?", + ); + assert_display( + inner_mod::InnerHappy::Variant7, + "what happens if we don\'t use *?", + ); + assert_display( + inner_mod::InnerHappy::Variant8, + "what about extra new lines?", + ); +} + +#[test] +#[cfg(feature = "std")] +fn does_it_print_path() { + assert_display( + Happy::Variant6(PathBuf::from("/var/log/happy")), + "The path /var/log/happy", + ); +} diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix.rs b/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix.rs new file mode 100644 index 0000000..1c54791 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix.rs @@ -0,0 +1,36 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +#[prefix_enum_doc_attributes] +enum TestType { + /// this variant is too + Variant1, + + /// this variant is two + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.rs b/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.rs new file mode 100644 index 0000000..5cd9e6d --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.rs @@ -0,0 +1,35 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +#[derive(Display)] +#[prefix_enum_doc_attributes] +enum TestType { + /// this variant is too + Variant1, + + /// this variant is two + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.stderr b/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.stderr new file mode 100644 index 0000000..a0db216 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/enum_prefix_missing.stderr @@ -0,0 +1,19 @@ +error: proc-macro derive panicked + --> $DIR/enum_prefix_missing.rs:22:10 + | +22 | #[derive(Display)] + | ^^^^^^^ + | + = help: message: Missing doc comment on enum with #[prefix_enum_doc_attributes]. Please remove the attribute or add a doc comment to the enum itself. + +error[E0277]: `TestType` doesn't implement `Display` + --> $DIR/enum_prefix_missing.rs:32:44 + | +32 | static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + | -------------------------------------------^^^^^^^^---------------------- + | | | + | | `TestType` cannot be formatted with the default formatter + | required by this bound in `assert_impl_all` + | + = help: the trait `Display` is not implemented for `TestType` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/multi_line.rs b/bash-5.1/vendor/displaydoc/tests/no_std/multi_line.rs new file mode 100644 index 0000000..cadb83e --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/multi_line.rs @@ -0,0 +1,37 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +enum TestType { + /// This one is okay + Variant1, + + /// Multi + /// line + /// doc. + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/multi_line.stderr b/bash-5.1/vendor/displaydoc/tests/no_std/multi_line.stderr new file mode 100644 index 0000000..e23d134 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/multi_line.stderr @@ -0,0 +1,19 @@ +error: proc-macro derive panicked + --> $DIR/multi_line.rs:23:10 + | +23 | #[derive(Display)] + | ^^^^^^^ + | + = help: message: Multi-line comments are disabled by default by displaydoc. Please consider using block doc comments (/** */) or adding the #[ignore_extra_doc_attributes] attribute to your type next to the derive. + +error[E0277]: `TestType` doesn't implement `Display` + --> $DIR/multi_line.rs:34:44 + | +34 | static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + | -------------------------------------------^^^^^^^^---------------------- + | | | + | | `TestType` cannot be formatted with the default formatter + | required by this bound in `assert_impl_all` + | + = help: the trait `Display` is not implemented for `TestType` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/multi_line_allow.rs b/bash-5.1/vendor/displaydoc/tests/no_std/multi_line_allow.rs new file mode 100644 index 0000000..05bdcf9 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/multi_line_allow.rs @@ -0,0 +1,38 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +#[ignore_extra_doc_attributes] +enum TestType { + /// This one is okay + Variant1, + + /// Multi + /// line + /// doc. + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/with.rs b/bash-5.1/vendor/displaydoc/tests/no_std/with.rs new file mode 100644 index 0000000..7de3da6 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/with.rs @@ -0,0 +1,32 @@ +#![feature(lang_items, start)] +#![no_std] + +#[start] +#[cfg(not(feature = "std"))] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} + +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} + +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +#[cfg(feature = "std")] +fn main() {} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +struct FakeType; + +static_assertions::assert_impl_all!(label; FakeType, core::fmt::Display); diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/without.rs b/bash-5.1/vendor/displaydoc/tests/no_std/without.rs new file mode 100644 index 0000000..32905aa --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/without.rs @@ -0,0 +1,28 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +struct FakeType; + +static_assertions::assert_impl_all!(label; FakeType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/no_std/without.stderr b/bash-5.1/vendor/displaydoc/tests/no_std/without.stderr new file mode 100644 index 0000000..81de13b --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/no_std/without.stderr @@ -0,0 +1,19 @@ +warning: unused import: `displaydoc::Display` + --> $DIR/without.rs:20:5 + | +20 | use displaydoc::Display; + | ^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` on by default + +error[E0277]: `FakeType` doesn't implement `Display` + --> $DIR/without.rs:25:44 + | +25 | static_assertions::assert_impl_all!(label; FakeType, core::fmt::Display); + | -------------------------------------------^^^^^^^^---------------------- + | | | + | | `FakeType` cannot be formatted with the default formatter + | required by this bound in `assert_impl_all` + | + = help: the trait `Display` is not implemented for `FakeType` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead diff --git a/bash-5.1/vendor/displaydoc/tests/num_in_field.rs b/bash-5.1/vendor/displaydoc/tests/num_in_field.rs new file mode 100644 index 0000000..9510f82 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/num_in_field.rs @@ -0,0 +1,22 @@ +/// {foo1} {foo2} +#[derive(displaydoc::Display)] +pub struct Test { + foo1: String, + foo2: String, +} + +fn assert_display(input: T, expected: &'static str) { + let out = format!("{}", input); + assert_eq!(expected, out); +} + +#[test] +fn does_it_print() { + assert_display( + Test { + foo1: "hi".into(), + foo2: "hello".into(), + }, + "hi hello", + ); +} diff --git a/bash-5.1/vendor/displaydoc/tests/std/enum_prefix.rs b/bash-5.1/vendor/displaydoc/tests/std/enum_prefix.rs new file mode 100644 index 0000000..1c54791 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/enum_prefix.rs @@ -0,0 +1,36 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +#[prefix_enum_doc_attributes] +enum TestType { + /// this variant is too + Variant1, + + /// this variant is two + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.rs b/bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.rs new file mode 100644 index 0000000..5cd9e6d --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.rs @@ -0,0 +1,35 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +#[derive(Display)] +#[prefix_enum_doc_attributes] +enum TestType { + /// this variant is too + Variant1, + + /// this variant is two + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.stderr b/bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.stderr new file mode 100644 index 0000000..7f60f1b --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/enum_prefix_missing.stderr @@ -0,0 +1,19 @@ +error: proc-macro derive panicked + --> $DIR/enum_prefix_missing.rs:22:10 + | +22 | #[derive(Display)] + | ^^^^^^^ + | + = help: message: Missing doc comment on enum with #[prefix_enum_doc_attributes]. Please remove the attribute or add a doc comment to the enum itself. + +error[E0277]: `TestType` doesn't implement `std::fmt::Display` + --> $DIR/enum_prefix_missing.rs:32:44 + | +32 | static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + | -------------------------------------------^^^^^^^^---------------------- + | | | + | | `TestType` cannot be formatted with the default formatter + | required by this bound in `assert_impl_all` + | + = help: the trait `std::fmt::Display` is not implemented for `TestType` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead diff --git a/bash-5.1/vendor/displaydoc/tests/std/multi_line.rs b/bash-5.1/vendor/displaydoc/tests/std/multi_line.rs new file mode 100644 index 0000000..cadb83e --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/multi_line.rs @@ -0,0 +1,37 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +enum TestType { + /// This one is okay + Variant1, + + /// Multi + /// line + /// doc. + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/std/multi_line.stderr b/bash-5.1/vendor/displaydoc/tests/std/multi_line.stderr new file mode 100644 index 0000000..5e41e54 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/multi_line.stderr @@ -0,0 +1,19 @@ +error: proc-macro derive panicked + --> $DIR/multi_line.rs:23:10 + | +23 | #[derive(Display)] + | ^^^^^^^ + | + = help: message: Multi-line comments are disabled by default by displaydoc. Please consider using block doc comments (/** */) or adding the #[ignore_extra_doc_attributes] attribute to your type next to the derive. + +error[E0277]: `TestType` doesn't implement `std::fmt::Display` + --> $DIR/multi_line.rs:34:44 + | +34 | static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + | -------------------------------------------^^^^^^^^---------------------- + | | | + | | `TestType` cannot be formatted with the default formatter + | required by this bound in `assert_impl_all` + | + = help: the trait `std::fmt::Display` is not implemented for `TestType` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead diff --git a/bash-5.1/vendor/displaydoc/tests/std/multi_line_allow.rs b/bash-5.1/vendor/displaydoc/tests/std/multi_line_allow.rs new file mode 100644 index 0000000..05bdcf9 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/multi_line_allow.rs @@ -0,0 +1,38 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +#[ignore_extra_doc_attributes] +enum TestType { + /// This one is okay + Variant1, + + /// Multi + /// line + /// doc. + Variant2, +} + +static_assertions::assert_impl_all!(label; TestType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/std/multiple.rs b/bash-5.1/vendor/displaydoc/tests/std/multiple.rs new file mode 100644 index 0000000..915f9ab --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/multiple.rs @@ -0,0 +1,38 @@ +#![feature(lang_items, start)] +#![no_std] + +#[start] +#[cfg(not(feature = "std"))] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} + +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} + +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +#[cfg(feature = "std")] +fn main() {} + +use displaydoc::Display; + +/// this type is pretty swell +#[derive(Display)] +struct FakeType; + +static_assertions::assert_impl_all!(label; FakeType, core::fmt::Display); + +/// this type is pretty swell2 +#[derive(Display)] +struct FakeType2; + +static_assertions::assert_impl_all!(label2; FakeType2, core::fmt::Display); diff --git a/bash-5.1/vendor/displaydoc/tests/std/without.rs b/bash-5.1/vendor/displaydoc/tests/std/without.rs new file mode 100644 index 0000000..32905aa --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/without.rs @@ -0,0 +1,28 @@ +#![cfg_attr(not(feature = "std"), feature(lang_items, start))] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(not(feature = "std"), start)] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} +#[lang = "eh_personality"] +#[no_mangle] +#[cfg(not(feature = "std"))] +pub extern "C" fn rust_eh_personality() {} +#[panic_handler] +#[cfg(not(feature = "std"))] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unsafe { + libc::abort(); + } +} + +use displaydoc::Display; + +/// this type is pretty swell +struct FakeType; + +static_assertions::assert_impl_all!(label; FakeType, core::fmt::Display); + +#[cfg(feature = "std")] +fn main() {} diff --git a/bash-5.1/vendor/displaydoc/tests/std/without.stderr b/bash-5.1/vendor/displaydoc/tests/std/without.stderr new file mode 100644 index 0000000..9780427 --- /dev/null +++ b/bash-5.1/vendor/displaydoc/tests/std/without.stderr @@ -0,0 +1,19 @@ +warning: unused import: `displaydoc::Display` + --> $DIR/without.rs:20:5 + | +20 | use displaydoc::Display; + | ^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` on by default + +error[E0277]: `FakeType` doesn't implement `std::fmt::Display` + --> $DIR/without.rs:25:44 + | +25 | static_assertions::assert_impl_all!(label; FakeType, core::fmt::Display); + | -------------------------------------------^^^^^^^^---------------------- + | | | + | | `FakeType` cannot be formatted with the default formatter + | required by this bound in `assert_impl_all` + | + = help: the trait `std::fmt::Display` is not implemented for `FakeType` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead diff --git a/bash-5.1/vendor/dtoa/.cargo-checksum.json b/bash-5.1/vendor/dtoa/.cargo-checksum.json new file mode 100644 index 0000000..550d130 --- /dev/null +++ b/bash-5.1/vendor/dtoa/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"657b9f00844e4f422237ebd26991476b160da598894d98d1d0be57e4e553c986","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"3416361ff0af6647a1616cc020766df798d683b8645f0d9270512277ee6cb47e","benches/bench.rs":"ac713ab4e1c668dea70416504955563fcd6bd2982ae1cfa3a1c0043e09dd893f","src/diyfp.rs":"89f685b3beb13dff8d4c2e28e16c4891013f7b387e625c5151267b2cd077df1d","src/dtoa.rs":"c70bb76acde7b749dfc9273fd556c73960027b3534c1f56a32768bf8f25985ff","src/lib.rs":"43eb71b7e5d5f802ad3c49148db4e27f9d911aa69ea77777f95feefc2e1f1e93","tests/test.rs":"296f3c322e08508fd372e436434fdd209bb911cab2124ea654d5f78d90f3eeea"},"package":"56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0"} \ No newline at end of file diff --git a/bash-5.1/vendor/dtoa/Cargo.toml b/bash-5.1/vendor/dtoa/Cargo.toml new file mode 100644 index 0000000..6382cea --- /dev/null +++ b/bash-5.1/vendor/dtoa/Cargo.toml @@ -0,0 +1,25 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "dtoa" +version = "0.4.8" +authors = ["David Tolnay "] +exclude = ["performance.png"] +description = "Fast functions for printing floating-point primitives to an io::Write" +documentation = "https://docs.rs/dtoa" +readme = "README.md" +categories = ["value-formatting"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/dtoa" +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] diff --git a/bash-5.1/vendor/dtoa/LICENSE-APACHE b/bash-5.1/vendor/dtoa/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/dtoa/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/dtoa/LICENSE-MIT b/bash-5.1/vendor/dtoa/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bash-5.1/vendor/dtoa/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/dtoa/README.md b/bash-5.1/vendor/dtoa/README.md new file mode 100644 index 0000000..210d516 --- /dev/null +++ b/bash-5.1/vendor/dtoa/README.md @@ -0,0 +1,80 @@ +dtoa +==== + +[github](https://github.com/dtolnay/dtoa) +[crates.io](https://crates.io/crates/dtoa) +[docs.rs](https://docs.rs/dtoa) +[build status](https://github.com/dtolnay/dtoa/actions?query=branch%3Amaster) + +This crate provides fast functions for printing floating-point primitives to an +[`io::Write`]. The implementation is a straightforward Rust port of [Milo Yip]'s +C++ implementation [dtoa.h]. The original C++ code of each function is included +in comments. + +See also [`itoa`] for printing integer primitives. + +*Version requirement: rustc 1.0+* + +[`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +[Milo Yip]: https://github.com/miloyip +[dtoa.h]: https://github.com/miloyip/rapidjson/blob/master/include/rapidjson/internal/dtoa.h +[`itoa`]: https://github.com/dtolnay/itoa + +```toml +[dependencies] +dtoa = "0.4" +``` + +
+ +## Performance (lower is better) + +![performance](https://raw.githubusercontent.com/dtolnay/dtoa/master/performance.png) + +
+ +## Examples + +```rust +use std::io; + +fn main() -> io::Result<()> { + // Write to a vector or other io::Write. + let mut buf = Vec::new(); + dtoa::write(&mut buf, 2.71828f64)?; + println!("{:?}", buf); + + // Write to a stack buffer. + let mut bytes = [b'\0'; 20]; + let n = dtoa::write(&mut bytes[..], 2.71828f64)?; + println!("{:?}", &bytes[..n]); + + Ok(()) +} +``` + +The function signature is: + +```rust +fn write(writer: W, value: V) -> io::Result<()>; +``` + +where `dtoa::Floating` is implemented for f32 and f64. The return value gives +the number of bytes written. + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bash-5.1/vendor/dtoa/benches/bench.rs b/bash-5.1/vendor/dtoa/benches/bench.rs new file mode 100644 index 0000000..ec57953 --- /dev/null +++ b/bash-5.1/vendor/dtoa/benches/bench.rs @@ -0,0 +1,54 @@ +#![feature(test)] + +extern crate dtoa; +extern crate test; + +macro_rules! benches { + ($($name:ident($value:expr),)*) => { + mod bench_dtoa { + use test::{Bencher, black_box}; + $( + #[bench] + fn $name(b: &mut Bencher) { + use dtoa; + + let mut buf = Vec::with_capacity(20); + + b.iter(|| { + buf.clear(); + dtoa::write(&mut buf, black_box($value)).unwrap() + }); + } + )* + } + + mod bench_fmt { + use test::{Bencher, black_box}; + $( + #[bench] + fn $name(b: &mut Bencher) { + use std::io::Write; + + let mut buf = Vec::with_capacity(20); + + b.iter(|| { + buf.clear(); + write!(&mut buf, "{}", black_box($value)).unwrap() + }); + } + )* + } + } +} + +benches!( + bench_0_f64(0f64), + bench_short_f64(0.1234f64), + bench_e_f64(2.718281828459045f64), + bench_max_f64(::std::f64::MAX), + + bench_0_f32(0f32), + bench_short_f32(0.1234f32), + bench_e_f32(2.718281828459045f32), + bench_max_f32(::std::f32::MAX), +); diff --git a/bash-5.1/vendor/dtoa/src/diyfp.rs b/bash-5.1/vendor/dtoa/src/diyfp.rs new file mode 100644 index 0000000..9d79765 --- /dev/null +++ b/bash-5.1/vendor/dtoa/src/diyfp.rs @@ -0,0 +1,253 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +// +// --- +// +// The C++ implementation preserved here in comments is licensed as follows: +// +// Tencent is pleased to support the open source community by making RapidJSON +// available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All +// rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file +// except in compliance with the License. You may obtain a copy of the License +// at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. + +use std::ops; + +#[derive(Copy, Clone, Debug)] +pub struct DiyFp { + pub f: F, + pub e: E, +} + +impl DiyFp { + pub fn new(f: F, e: E) -> Self { + DiyFp { f: f, e: e } + } +} + +impl ops::Mul for DiyFp { + type Output = Self; + fn mul(self, rhs: Self) -> Self { + let mut tmp = self.f as u64 * rhs.f as u64; + tmp += 1u64 << 31; // mult_round + DiyFp { + f: (tmp >> 32) as u32, + e: self.e + rhs.e + 32, + } + } +} + +impl ops::Mul for DiyFp { + type Output = Self; + fn mul(self, rhs: Self) -> Self { + let m32 = 0xFFFFFFFFu64; + let a = self.f >> 32; + let b = self.f & m32; + let c = rhs.f >> 32; + let d = rhs.f & m32; + let ac = a * c; + let bc = b * c; + let ad = a * d; + let bd = b * d; + let mut tmp = (bd >> 32) + (ad & m32) + (bc & m32); + tmp += 1u64 << 31; // mult_round + DiyFp { + f: ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), + e: self.e + rhs.e + 64, + } + } +} + +#[doc(hidden)] +#[macro_export] +macro_rules! diyfp {( + floating_type: $fty:ty, + significand_type: $sigty:ty, + exponent_type: $expty:ty, + + diy_significand_size: $diy_significand_size:expr, + significand_size: $significand_size:expr, + exponent_bias: $exponent_bias:expr, + mask_type: $mask_type:ty, + exponent_mask: $exponent_mask:expr, + significand_mask: $significand_mask:expr, + hidden_bit: $hidden_bit:expr, + cached_powers_f: $cached_powers_f:expr, + cached_powers_e: $cached_powers_e:expr, + min_power: $min_power:expr, +) => { + +type DiyFp = diyfp::DiyFp<$sigty, $expty>; + +impl DiyFp { + // Preconditions: + // `d` must have a positive sign and must not be infinity or NaN. + /* + explicit DiyFp(double d) { + union { + double d; + uint64_t u64; + } u = { d }; + + int biased_e = static_cast((u.u64 & kDpExponentMask) >> kDpSignificandSize); + uint64_t significand = (u.u64 & kDpSignificandMask); + if (biased_e != 0) { + f = significand + kDpHiddenBit; + e = biased_e - kDpExponentBias; + } + else { + f = significand; + e = kDpMinExponent + 1; + } + } + */ + unsafe fn from(d: $fty) -> Self { + let u: $mask_type = mem::transmute(d); + + let biased_e = ((u & $exponent_mask) >> $significand_size) as $expty; + let significand = u & $significand_mask; + if biased_e != 0 { + DiyFp { + f: significand + $hidden_bit, + e: biased_e - $exponent_bias - $significand_size, + } + } else { + DiyFp { + f: significand, + e: 1 - $exponent_bias - $significand_size, + } + } + } + + // Normalizes so that the highest bit of the diy significand is 1. + /* + DiyFp Normalize() const { + DiyFp res = *this; + while (!(res.f & (static_cast(1) << 63))) { + res.f <<= 1; + res.e--; + } + return res; + } + */ + fn normalize(self) -> DiyFp { + let mut res = self; + while (res.f & (1 << ($diy_significand_size - 1))) == 0 { + res.f <<= 1; + res.e -= 1; + } + res + } + + // Normalizes so that the highest bit of the diy significand is 1. + // + // Precondition: + // `self.f` must be no more than 2 bits longer than the f64 significand. + /* + DiyFp NormalizeBoundary() const { + DiyFp res = *this; + while (!(res.f & (kDpHiddenBit << 1))) { + res.f <<= 1; + res.e--; + } + res.f <<= (kDiySignificandSize - kDpSignificandSize - 2); + res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2); + return res; + } + */ + fn normalize_boundary(self) -> DiyFp { + let mut res = self; + while (res.f & $hidden_bit << 1) == 0 { + res.f <<= 1; + res.e -= 1; + } + res.f <<= $diy_significand_size - $significand_size - 2; + res.e -= $diy_significand_size - $significand_size - 2; + res + } + + // Normalizes `self - e` and `self + e` where `e` is half of the least + // significant digit of `self`. The plus is normalized so that the highest + // bit of the diy significand is 1. The minus is normalized so that it has + // the same exponent as the plus. + // + // Preconditions: + // `self` must have been returned directly from `DiyFp::from_f64`. + // `self.f` must not be zero. + /* + void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { + DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); + DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); + mi.f <<= mi.e - pl.e; + mi.e = pl.e; + *plus = pl; + *minus = mi; + } + */ + fn normalized_boundaries(self) -> (DiyFp, DiyFp) { + let pl = DiyFp::new((self.f << 1) + 1, self.e - 1).normalize_boundary(); + let mut mi = if self.f == $hidden_bit { + DiyFp::new((self.f << 2) - 1, self.e - 2) + } else { + DiyFp::new((self.f << 1) - 1, self.e - 1) + }; + mi.f <<= mi.e - pl.e; + mi.e = pl.e; + (mi, pl) + } +} + +impl ops::Sub for DiyFp { + type Output = Self; + fn sub(self, rhs: Self) -> Self { + DiyFp { + f: self.f - rhs.f, + e: self.e, + } + } +} + +/* +inline DiyFp GetCachedPower(int e, int* K) { + //int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; + double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive + int k = static_cast(dk); + if (dk - k > 0.0) + k++; + + unsigned index = static_cast((k >> 3) + 1); + *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table + + return GetCachedPowerByIndex(index); +} +*/ +#[inline] +fn get_cached_power(e: $expty) -> (DiyFp, isize) { + let dk = (3 - $diy_significand_size - e) as f64 * 0.30102999566398114f64 - ($min_power + 1) as f64; + let mut k = dk as isize; + if dk - k as f64 > 0.0 { + k += 1; + } + + let index = ((k >> 3) + 1) as usize; + let k = -($min_power + (index << 3) as isize); + + (DiyFp::new($cached_powers_f[index], $cached_powers_e[index] as $expty), k) +} + +}} diff --git a/bash-5.1/vendor/dtoa/src/dtoa.rs b/bash-5.1/vendor/dtoa/src/dtoa.rs new file mode 100644 index 0000000..8642a38 --- /dev/null +++ b/bash-5.1/vendor/dtoa/src/dtoa.rs @@ -0,0 +1,509 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +// +// --- +// +// The C++ implementation preserved here in comments is licensed as follows: +// +// Tencent is pleased to support the open source community by making RapidJSON +// available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All +// rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file +// except in compliance with the License. You may obtain a copy of the License +// at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. + +#[doc(hidden)] +#[macro_export] +macro_rules! dtoa {( + floating_type: $fty:ty, + significand_type: $sigty:ty, + exponent_type: $expty:ty, + $($diyfp_param:ident: $diyfp_value:tt,)* +) => { + +diyfp! { + floating_type: $fty, + significand_type: $sigty, + exponent_type: $expty, + $($diyfp_param: $diyfp_value,)* +}; + +/* +inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { + while (rest < wp_w && delta - rest >= ten_kappa && + (rest + ten_kappa < wp_w || /// closer + wp_w - rest > rest + ten_kappa - wp_w)) { + buffer[len - 1]--; + rest += ten_kappa; + } +} +*/ + +#[inline] +unsafe fn grisu_round(buffer: *mut u8, len: isize, delta: $sigty, mut rest: $sigty, ten_kappa: $sigty, wp_w: $sigty) { + while rest < wp_w && delta - rest >= ten_kappa && + (rest + ten_kappa < wp_w || // closer + wp_w - rest > rest + ten_kappa - wp_w) { + *buffer.offset(len - 1) -= 1; + rest += ten_kappa; + } +} + +/* +inline unsigned CountDecimalDigit32(uint32_t n) { + // Simple pure C++ implementation was faster than __builtin_clz version in this situation. + if (n < 10) return 1; + if (n < 100) return 2; + if (n < 1000) return 3; + if (n < 10000) return 4; + if (n < 100000) return 5; + if (n < 1000000) return 6; + if (n < 10000000) return 7; + if (n < 100000000) return 8; + // Will not reach 10 digits in DigitGen() + //if (n < 1000000000) return 9; + //return 10; + return 9; +} +*/ + +#[inline] +fn count_decimal_digit32(n: u32) -> usize { + if n < 10 { 1 } + else if n < 100 { 2 } + else if n < 1000 { 3 } + else if n < 10000 { 4 } + else if n < 100000 { 5 } + else if n < 1000000 { 6 } + else if n < 10000000 { 7 } + else if n < 100000000 { 8 } + // Will not reach 10 digits in digit_gen() + else { 9 } +} + +/* +inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { + static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); + const DiyFp wp_w = Mp - W; + uint32_t p1 = static_cast(Mp.f >> -one.e); + uint64_t p2 = Mp.f & (one.f - 1); + unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9] + *len = 0; +*/ + +// Returns length and k. +#[inline] +unsafe fn digit_gen(w: DiyFp, mp: DiyFp, mut delta: $sigty, buffer: *mut u8, mut k: isize) -> (isize, isize) { + static POW10: [$sigty; 10] = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 ]; + let one = DiyFp::new(1 << -mp.e, mp.e); + let wp_w = mp - w; + let mut p1 = (mp.f >> -one.e) as u32; + let mut p2 = mp.f & (one.f - 1); + let mut kappa = count_decimal_digit32(p1); // kappa in [0, 9] + let mut len = 0; + + /* + while (kappa > 0) { + uint32_t d = 0; + switch (kappa) { + case 9: d = p1 / 100000000; p1 %= 100000000; break; + case 8: d = p1 / 10000000; p1 %= 10000000; break; + case 7: d = p1 / 1000000; p1 %= 1000000; break; + case 6: d = p1 / 100000; p1 %= 100000; break; + case 5: d = p1 / 10000; p1 %= 10000; break; + case 4: d = p1 / 1000; p1 %= 1000; break; + case 3: d = p1 / 100; p1 %= 100; break; + case 2: d = p1 / 10; p1 %= 10; break; + case 1: d = p1; p1 = 0; break; + default:; + } + if (d || *len) + buffer[(*len)++] = static_cast('0' + static_cast(d)); + kappa--; + uint64_t tmp = (static_cast(p1) << -one.e) + p2; + if (tmp <= delta) { + *K += kappa; + GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); + return; + } + } + */ + while kappa > 0 { + let mut d = 0u32; + match kappa { + 9 => { d = p1 / 100000000; p1 %= 100000000; } + 8 => { d = p1 / 10000000; p1 %= 10000000; } + 7 => { d = p1 / 1000000; p1 %= 1000000; } + 6 => { d = p1 / 100000; p1 %= 100000; } + 5 => { d = p1 / 10000; p1 %= 10000; } + 4 => { d = p1 / 1000; p1 %= 1000; } + 3 => { d = p1 / 100; p1 %= 100; } + 2 => { d = p1 / 10; p1 %= 10; } + 1 => { d = p1; p1 = 0; } + _ => {} + } + if d != 0 || len != 0 { + *buffer.offset(len) = b'0' + d as u8; + len += 1; + } + kappa -= 1; + let tmp = (p1 as $sigty << -one.e) + p2; + if tmp <= delta { + k += kappa as isize; + grisu_round(buffer, len, delta, tmp, POW10[kappa] << -one.e, wp_w.f); + return (len, k); + } + } + + // kappa = 0 + /* + for (;;) { + p2 *= 10; + delta *= 10; + char d = static_cast(p2 >> -one.e); + if (d || *len) + buffer[(*len)++] = static_cast('0' + d); + p2 &= one.f - 1; + kappa--; + if (p2 < delta) { + *K += kappa; + int index = -static_cast(kappa); + GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast(kappa)] : 0)); + return; + } + } + */ + loop { + p2 *= 10; + delta *= 10; + let d = (p2 >> -one.e) as u8; + if d != 0 || len != 0 { + *buffer.offset(len) = b'0' + d; + len += 1; + } + p2 &= one.f - 1; + kappa = kappa.wrapping_sub(1); + if p2 < delta { + k += kappa as isize; + let index = -(kappa as isize); + grisu_round(buffer, len, delta, p2, one.f, wp_w.f * if index < 9 { POW10[-(kappa as isize) as usize] } else { 0 }); + return (len, k); + } + } +} + +/* +inline void Grisu2(double value, char* buffer, int* length, int* K) { + const DiyFp v(value); + DiyFp w_m, w_p; + v.NormalizedBoundaries(&w_m, &w_p); + + const DiyFp c_mk = GetCachedPower(w_p.e, K); + const DiyFp W = v.Normalize() * c_mk; + DiyFp Wp = w_p * c_mk; + DiyFp Wm = w_m * c_mk; + Wm.f++; + Wp.f--; + DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); +} +*/ + +// Returns length and k. +#[inline] +unsafe fn grisu2(value: $fty, buffer: *mut u8) -> (isize, isize) { + let v = DiyFp::from(value); + let (w_m, w_p) = v.normalized_boundaries(); + + let (c_mk, k) = get_cached_power(w_p.e); + let w = v.normalize() * c_mk; + let mut wp = w_p * c_mk; + let mut wm = w_m * c_mk; + wm.f += 1; + wp.f -= 1; + digit_gen(w, wp, wp.f - wm.f, buffer, k) +} + +/* +inline char* WriteExponent(int K, char* buffer) { + if (K < 0) { + *buffer++ = '-'; + K = -K; + } + + if (K >= 100) { + *buffer++ = static_cast('0' + static_cast(K / 100)); + K %= 100; + const char* d = GetDigitsLut() + K * 2; + *buffer++ = d[0]; + *buffer++ = d[1]; + } + else if (K >= 10) { + const char* d = GetDigitsLut() + K * 2; + *buffer++ = d[0]; + *buffer++ = d[1]; + } + else + *buffer++ = static_cast('0' + static_cast(K)); + + return buffer; +} +*/ + +#[inline] +unsafe fn write_exponent(mut k: isize, mut buffer: *mut u8) -> *mut u8 { + if k < 0 { + *buffer = b'-'; + buffer = buffer.offset(1); + k = -k; + } + + if k >= 100 { + *buffer = b'0' + (k / 100) as u8; + k %= 100; + let d = DEC_DIGITS_LUT.get_unchecked(k as usize * 2); + ptr::copy_nonoverlapping(d, buffer.offset(1), 2); + buffer.offset(3) + } else if k >= 10 { + let d = DEC_DIGITS_LUT.get_unchecked(k as usize * 2); + ptr::copy_nonoverlapping(d, buffer, 2); + buffer.offset(2) + } else { + *buffer = b'0' + k as u8; + buffer.offset(1) + } +} + +/* +inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) { + const int kk = length + k; // 10^(kk-1) <= v < 10^kk +*/ + +#[inline] +unsafe fn prettify(buffer: *mut u8, length: isize, k: isize) -> *mut u8 { + let kk = length + k; // 10^(kk-1) <= v < 10^kk + + /* + if (0 <= k && kk <= 21) { + // 1234e7 -> 12340000000 + for (int i = length; i < kk; i++) + buffer[i] = '0'; + buffer[kk] = '.'; + buffer[kk + 1] = '0'; + return &buffer[kk + 2]; + } + */ + if 0 <= k && kk <= 21 { + // 1234e7 -> 12340000000 + for i in length..kk { + *buffer.offset(i) = b'0'; + } + *buffer.offset(kk) = b'.'; + *buffer.offset(kk + 1) = b'0'; + buffer.offset(kk + 2) + } + + /* + else if (0 < kk && kk <= 21) { + // 1234e-2 -> 12.34 + std::memmove(&buffer[kk + 1], &buffer[kk], static_cast(length - kk)); + buffer[kk] = '.'; + if (0 > k + maxDecimalPlaces) { + // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 + // Remove extra trailing zeros (at least one) after truncation. + for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) + if (buffer[i] != '0') + return &buffer[i + 1]; + return &buffer[kk + 2]; // Reserve one zero + } + else + return &buffer[length + 1]; + } + */ + else if 0 < kk && kk <= 21 { + // 1234e-2 -> 12.34 + ptr::copy(buffer.offset(kk), buffer.offset(kk + 1), (length - kk) as usize); + *buffer.offset(kk) = b'.'; + if 0 > k + MAX_DECIMAL_PLACES { + // When MAX_DECIMAL_PLACES = 2, 1.2345 -> 1.23, 1.102 -> 1.1 + // Remove extra trailing zeros (at least one) after truncation. + for i in (kk + 2 .. kk + MAX_DECIMAL_PLACES + 1).rev() { + if *buffer.offset(i) != b'0' { + return buffer.offset(i + 1); + } + } + buffer.offset(kk + 2) // Reserve one zero + } else { + buffer.offset(length + 1) + } + } + + /* + else if (-6 < kk && kk <= 0) { + // 1234e-6 -> 0.001234 + const int offset = 2 - kk; + std::memmove(&buffer[offset], &buffer[0], static_cast(length)); + buffer[0] = '0'; + buffer[1] = '.'; + for (int i = 2; i < offset; i++) + buffer[i] = '0'; + if (length - kk > maxDecimalPlaces) { + // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 + // Remove extra trailing zeros (at least one) after truncation. + for (int i = maxDecimalPlaces + 1; i > 2; i--) + if (buffer[i] != '0') + return &buffer[i + 1]; + return &buffer[3]; // Reserve one zero + } + else + return &buffer[length + offset]; + } + */ + else if -6 < kk && kk <= 0 { + // 1234e-6 -> 0.001234 + let offset = 2 - kk; + ptr::copy(buffer, buffer.offset(offset), length as usize); + *buffer = b'0'; + *buffer.offset(1) = b'.'; + for i in 2..offset { + *buffer.offset(i) = b'0'; + } + if length - kk > MAX_DECIMAL_PLACES { + // When MAX_DECIMAL_PLACES = 2, 0.123 -> 0.12, 0.102 -> 0.1 + // Remove extra trailing zeros (at least one) after truncation. + for i in (3 .. MAX_DECIMAL_PLACES + 2).rev() { + if *buffer.offset(i) != b'0' { + return buffer.offset(i + 1); + } + } + buffer.offset(3) // Reserve one zero + } else { + buffer.offset(length + offset) + } + } + + /* + else if (kk < -maxDecimalPlaces) { + // Truncate to zero + buffer[0] = '0'; + buffer[1] = '.'; + buffer[2] = '0'; + return &buffer[3]; + } + */ + else if kk < -MAX_DECIMAL_PLACES { + *buffer = b'0'; + *buffer.offset(1) = b'.'; + *buffer.offset(2) = b'0'; + buffer.offset(3) + } + + /* + else if (length == 1) { + // 1e30 + buffer[1] = 'e'; + return WriteExponent(kk - 1, &buffer[2]); + } + */ + else if length == 1 { + // 1e30 + *buffer.offset(1) = b'e'; + write_exponent(kk - 1, buffer.offset(2)) + } + + /* + else { + // 1234e30 -> 1.234e33 + std::memmove(&buffer[2], &buffer[1], static_cast(length - 1)); + buffer[1] = '.'; + buffer[length + 1] = 'e'; + return WriteExponent(kk - 1, &buffer[0 + length + 2]); + } + */ + else { + // 1234e30 -> 1.234e33 + ptr::copy(buffer.offset(1), buffer.offset(2), (length - 1) as usize); + *buffer.offset(1) = b'.'; + *buffer.offset(length + 1) = b'e'; + write_exponent(kk - 1, buffer.offset(length + 2)) + } +} + +/* +inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) { + RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); + Double d(value); + if (d.IsZero()) { + if (d.Sign()) + *buffer++ = '-'; // -0.0, Issue #289 + buffer[0] = '0'; + buffer[1] = '.'; + buffer[2] = '0'; + return &buffer[3]; + } + else { + if (value < 0) { + *buffer++ = '-'; + value = -value; + } + int length, K; + Grisu2(value, buffer, &length, &K); + return Prettify(buffer, length, K, maxDecimalPlaces); + } +} +*/ + +#[allow(deprecated)] +#[inline] +unsafe fn dtoa(mut wr: W, mut value: $fty) -> io::Result { + if value == 0.0 { + if value.is_sign_negative() { + match wr.write_all(b"-0.0") { + Ok(()) => Ok(4), + Err(e) => Err(e), + } + } else { + match wr.write_all(b"0.0") { + Ok(()) => Ok(3), + Err(e) => Err(e), + } + } + } else { + let negative = value < 0.0; + if negative { + if let Err(e) = wr.write_all(b"-") { + return Err(e); + } + value = -value; + } + let mut buffer: [u8; 24] = mem::uninitialized(); + let buf_ptr = buffer.as_mut_ptr(); + let (length, k) = grisu2(value, buf_ptr); + let end = prettify(buf_ptr, length, k); + let len = end as usize - buf_ptr as usize; + if let Err(e) = wr.write_all(slice::from_raw_parts(buf_ptr, len)) { + return Err(e); + } + if negative { + Ok(len + 1) + } else { + Ok(len) + } + } +} + +}} diff --git a/bash-5.1/vendor/dtoa/src/lib.rs b/bash-5.1/vendor/dtoa/src/lib.rs new file mode 100644 index 0000000..aed62f5 --- /dev/null +++ b/bash-5.1/vendor/dtoa/src/lib.rs @@ -0,0 +1,205 @@ +//! [![github]](https://github.com/dtolnay/dtoa) [![crates-io]](https://crates.io/crates/dtoa) [![docs-rs]](https://docs.rs/dtoa) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K +//! +//!
+//! +//! This crate provides fast functions for printing floating-point primitives to +//! an [`io::Write`]. The implementation is a straightforward Rust port of [Milo +//! Yip]'s C++ implementation [dtoa.h]. The original C++ code of each function +//! is included in comments. +//! +//! See also [`itoa`] for printing integer primitives. +//! +//! [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +//! [Milo Yip]: https://github.com/miloyip +//! [dtoa.h]: https://github.com/miloyip/rapidjson/blob/master/include/rapidjson/internal/dtoa.h +//! [`itoa`]: https://github.com/dtolnay/itoa +//! +//!
+//! +//! ## Performance (lower is better) +//! +//! ![performance](https://raw.githubusercontent.com/dtolnay/dtoa/master/performance.png) +//! +//!
+//! +//! # Examples +//! +//! ```edition2018 +//! use std::io; +//! +//! fn main() -> io::Result<()> { +//! // Write to a vector or other io::Write. +//! let mut buf = Vec::new(); +//! dtoa::write(&mut buf, 2.71828f64)?; +//! println!("{:?}", buf); +//! +//! // Write to a stack buffer. +//! let mut bytes = [b'\0'; 20]; +//! let n = dtoa::write(&mut bytes[..], 2.71828f64)?; +//! println!("{:?}", &bytes[..n]); +//! +//! Ok(()) +//! } +//! ``` + +#![doc(html_root_url = "https://docs.rs/dtoa/0.4.8")] +#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] +#![cfg_attr( + feature = "cargo-clippy", + allow( + cast_lossless, + cast_possible_truncation, + if_not_else, + missing_errors_doc, + range_plus_one, + shadow_unrelated, + transmute_float_to_int, + unreadable_literal, + unseparated_literal_suffix + ) +)] + +#[macro_use] mod diyfp; +#[macro_use] mod dtoa; + +use std::{io, mem, ops, ptr, slice}; + +/// Write float to an `io::Write`. +#[inline] +pub fn write(wr: W, value: V) -> io::Result { + value.write(wr) +} + +/// An floating point number that can be formatted by `dtoa::write`. +pub trait Floating { + fn write(self, wr: W) -> io::Result; +} + +impl Floating for f32 { + fn write(self, wr: W) -> io::Result { + dtoa! { + floating_type: f32, + significand_type: u32, + exponent_type: i32, + + diy_significand_size: 32, + significand_size: 23, + exponent_bias: 0x7F, + mask_type: u32, + exponent_mask: 0x7F800000, + significand_mask: 0x007FFFFF, + hidden_bit: 0x00800000, + cached_powers_f: CACHED_POWERS_F_32, + cached_powers_e: CACHED_POWERS_E_32, + min_power: (-36), + }; + unsafe { dtoa(wr, self) } + } +} + +impl Floating for f64 { + fn write(self, wr: W) -> io::Result { + dtoa! { + floating_type: f64, + significand_type: u64, + exponent_type: isize, + + diy_significand_size: 64, + significand_size: 52, + exponent_bias: 0x3FF, + mask_type: u64, + exponent_mask: 0x7FF0000000000000, + significand_mask: 0x000FFFFFFFFFFFFF, + hidden_bit: 0x0010000000000000, + cached_powers_f: CACHED_POWERS_F_64, + cached_powers_e: CACHED_POWERS_E_64, + min_power: (-348), + }; + unsafe { dtoa(wr, self) } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +const MAX_DECIMAL_PLACES: isize = 324; + +static DEC_DIGITS_LUT: [u8; 200] = *b"\ + 0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; + +// 10^-36, 10^-28, ..., 10^52 +static CACHED_POWERS_F_32: [u32; 12] = [ + 0xaa242499, 0xfd87b5f3, 0xbce50865, 0x8cbccc09, + 0xd1b71759, 0x9c400000, 0xe8d4a510, 0xad78ebc6, + 0x813f3979, 0xc097ce7c, 0x8f7e32ce, 0xd5d238a5, +]; + +static CACHED_POWERS_E_32: [i16; 12] = [ + -151, -125, -98, -71, -45, -18, 8, 35, 62, 88, 115, 141, +]; + +// 10^-348, 10^-340, ..., 10^340 +static CACHED_POWERS_F_64: [u64; 87] = [ + 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, + 0x8b16fb203055ac76, 0xcf42894a5dce35ea, + 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, + 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, + 0xbe5691ef416bd60c, 0x8dd01fad907ffc3c, + 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, + 0xea9c227723ee8bcb, 0xaecc49914078536d, + 0x823c12795db6ce57, 0xc21094364dfb5637, + 0x9096ea6f3848984f, 0xd77485cb25823ac7, + 0xa086cfcd97bf97f4, 0xef340a98172aace5, + 0xb23867fb2a35b28e, 0x84c8d4dfd2c63f3b, + 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, + 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, + 0xf3e2f893dec3f126, 0xb5b5ada8aaff80b8, + 0x87625f056c7c4a8b, 0xc9bcff6034c13053, + 0x964e858c91ba2655, 0xdff9772470297ebd, + 0xa6dfbd9fb8e5b88f, 0xf8a95fcf88747d94, + 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, + 0xcdb02555653131b6, 0x993fe2c6d07b7fac, + 0xe45c10c42a2b3b06, 0xaa242499697392d3, + 0xfd87b5f28300ca0e, 0xbce5086492111aeb, + 0x8cbccc096f5088cc, 0xd1b71758e219652c, + 0x9c40000000000000, 0xe8d4a51000000000, + 0xad78ebc5ac620000, 0x813f3978f8940984, + 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, + 0xd5d238a4abe98068, 0x9f4f2726179a2245, + 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, + 0x83c7088e1aab65db, 0xc45d1df942711d9a, + 0x924d692ca61be758, 0xda01ee641a708dea, + 0xa26da3999aef774a, 0xf209787bb47d6b85, + 0xb454e4a179dd1877, 0x865b86925b9bc5c2, + 0xc83553c5c8965d3d, 0x952ab45cfa97a0b3, + 0xde469fbd99a05fe3, 0xa59bc234db398c25, + 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, + 0x88fcf317f22241e2, 0xcc20ce9bd35c78a5, + 0x98165af37b2153df, 0xe2a0b5dc971f303a, + 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, + 0xbb764c4ca7a44410, 0x8bab8eefb6409c1a, + 0xd01fef10a657842c, 0x9b10a4e5e9913129, + 0xe7109bfba19c0c9d, 0xac2820d9623bf429, + 0x80444b5e7aa7cf85, 0xbf21e44003acdd2d, + 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, + 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, + 0xaf87023b9bf0ee6b, +]; +static CACHED_POWERS_E_64: [i16; 87] = [ + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, + -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, + -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, + -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, + -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, + 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, + 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, + 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, + 907, 933, 960, 986, 1013, 1039, 1066, +]; diff --git a/bash-5.1/vendor/dtoa/tests/test.rs b/bash-5.1/vendor/dtoa/tests/test.rs new file mode 100644 index 0000000..4f92d7e --- /dev/null +++ b/bash-5.1/vendor/dtoa/tests/test.rs @@ -0,0 +1,38 @@ +extern crate dtoa; + +use std::str; + +#[test] +fn test_f64() { + test_write(1.234e20f64, "123400000000000000000.0"); + test_write(1.234e21f64, "1.234e21"); + test_write(2.71828f64, "2.71828"); + test_write(0.0f64, "0.0"); + test_write(-0.0f64, "-0.0"); + test_write(1.1e128f64, "1.1e128"); + test_write(1.1e-64f64, "1.1e-64"); + test_write(2.718281828459045f64, "2.718281828459045"); + test_write(5e-324f64, "5e-324"); + test_write(::std::f64::MAX, "1.7976931348623157e308"); +} + +#[test] +fn test_f32() { + test_write(1.234e20f32, "123400000000000000000.0"); + test_write(1.234e21f32, "1.234e21"); + test_write(2.71828f32, "2.71828"); + test_write(0.0f32, "0.0"); + test_write(-0.0f32, "-0.0"); + test_write(1.1e32f32, "1.1e32"); + test_write(1.1e-32f32, "1.1e-32"); + test_write(2.7182817f32, "2.7182817"); + test_write(1e-45f32, "1e-45"); + test_write(::std::f32::MAX, "3.4028235e38"); +} + +fn test_write(value: F, expected: &'static str) { + let mut buf = [b'\0'; 30]; + let len = dtoa::write(&mut buf[..], value).unwrap(); + let result = str::from_utf8(&buf[..len]).unwrap(); + assert_eq!(result, expected.to_string()); +} diff --git a/bash-5.1/vendor/env_logger/.cargo-checksum.json b/bash-5.1/vendor/env_logger/.cargo-checksum.json new file mode 100644 index 0000000..ff33815 --- /dev/null +++ b/bash-5.1/vendor/env_logger/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"3f4cf313ce063b0d3888a3acdc3a31ed99432415aa4204b143fd39de0d037996","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","src/lib.rs":"5fac719110645152e649993bfd7edb8ca755155844867cbfa8077b486ddde9e1","src/regex.rs":"d8e2a6958d4ed8084867063aae4b5c77ffc5d271dc2e17909d56c5a5e1552034","src/string.rs":"26ede9ab41a2673c3ad6001bc1802c005ce9a4f190f55860a24aa66b6b71bbc7","tests/regexp_filter.rs":"a3f9c01623e90e54b247a62c53b25caf5f502d054f28c0bdf92abbea486a95b5"},"package":"3ddf21e73e016298f5cb37d6ef8e8da8e39f91f9ec8b0df44b7deb16a9f8cd5b"} \ No newline at end of file diff --git a/bash-5.1/vendor/env_logger/Cargo.toml b/bash-5.1/vendor/env_logger/Cargo.toml new file mode 100644 index 0000000..4ac3e2e --- /dev/null +++ b/bash-5.1/vendor/env_logger/Cargo.toml @@ -0,0 +1,35 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "env_logger" +version = "0.4.3" +authors = ["The Rust Project Developers"] +description = "A logging implementation for `log` which is configured via an environment\nvariable.\n" +homepage = "https://github.com/rust-lang/log" +documentation = "http://doc.rust-lang.org/log/env_logger" +categories = ["development-tools::debugging"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/log" + +[[test]] +name = "regexp_filter" +harness = false +[dependencies.regex] +version = "0.2" +optional = true + +[dependencies.log] +version = "0.3" + +[features] +default = ["regex"] diff --git a/bash-5.1/vendor/env_logger/LICENSE-APACHE b/bash-5.1/vendor/env_logger/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/env_logger/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/env_logger/LICENSE-MIT b/bash-5.1/vendor/env_logger/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/env_logger/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/env_logger/src/lib.rs b/bash-5.1/vendor/env_logger/src/lib.rs new file mode 100644 index 0000000..7e2f9da --- /dev/null +++ b/bash-5.1/vendor/env_logger/src/lib.rs @@ -0,0 +1,652 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A logger configured via an environment variable which writes to standard +//! error. +//! +//! ## Example +//! +//! ``` +//! #[macro_use] extern crate log; +//! extern crate env_logger; +//! +//! use log::LogLevel; +//! +//! fn main() { +//! env_logger::init().unwrap(); +//! +//! debug!("this is a debug {}", "message"); +//! error!("this is printed by default"); +//! +//! if log_enabled!(LogLevel::Info) { +//! let x = 3 * 4; // expensive computation +//! info!("the answer was: {}", x); +//! } +//! } +//! ``` +//! +//! Assumes the binary is `main`: +//! +//! ```{.bash} +//! $ RUST_LOG=error ./main +//! ERROR:main: this is printed by default +//! ``` +//! +//! ```{.bash} +//! $ RUST_LOG=info ./main +//! ERROR:main: this is printed by default +//! INFO:main: the answer was: 12 +//! ``` +//! +//! ```{.bash} +//! $ RUST_LOG=debug ./main +//! DEBUG:main: this is a debug message +//! ERROR:main: this is printed by default +//! INFO:main: the answer was: 12 +//! ``` +//! +//! You can also set the log level on a per module basis: +//! +//! ```{.bash} +//! $ RUST_LOG=main=info ./main +//! ERROR:main: this is printed by default +//! INFO:main: the answer was: 12 +//! ``` +//! +//! And enable all logging: +//! +//! ```{.bash} +//! $ RUST_LOG=main ./main +//! DEBUG:main: this is a debug message +//! ERROR:main: this is printed by default +//! INFO:main: the answer was: 12 +//! ``` +//! +//! See the documentation for the log crate for more information about its API. +//! +//! ## Enabling logging +//! +//! Log levels are controlled on a per-module basis, and by default all logging +//! is disabled except for `error!`. Logging is controlled via the `RUST_LOG` +//! environment variable. The value of this environment variable is a +//! comma-separated list of logging directives. A logging directive is of the +//! form: +//! +//! ```text +//! path::to::module=log_level +//! ``` +//! +//! The path to the module is rooted in the name of the crate it was compiled +//! for, so if your program is contained in a file `hello.rs`, for example, to +//! turn on logging for this file you would use a value of `RUST_LOG=hello`. +//! Furthermore, this path is a prefix-search, so all modules nested in the +//! specified module will also have logging enabled. +//! +//! The actual `log_level` is optional to specify. If omitted, all logging will +//! be enabled. If specified, it must be one of the strings `debug`, `error`, +//! `info`, `warn`, or `trace`. +//! +//! As the log level for a module is optional, the module to enable logging for +//! is also optional. If only a `log_level` is provided, then the global log +//! level for all modules is set to this value. +//! +//! Some examples of valid values of `RUST_LOG` are: +//! +//! * `hello` turns on all logging for the 'hello' module +//! * `info` turns on all info logging +//! * `hello=debug` turns on debug logging for 'hello' +//! * `hello,std::option` turns on hello, and std's option logging +//! * `error,hello=warn` turn on global error logging and also warn for hello +//! +//! ## Filtering results +//! +//! A RUST_LOG directive may include a regex filter. The syntax is to append `/` +//! followed by a regex. Each message is checked against the regex, and is only +//! logged if it matches. Note that the matching is done after formatting the +//! log string but before adding any logging meta-data. There is a single filter +//! for all modules. +//! +//! Some examples: +//! +//! * `hello/foo` turns on all logging for the 'hello' module where the log +//! message includes 'foo'. +//! * `info/f.o` turns on all info logging where the log message includes 'foo', +//! 'f1o', 'fao', etc. +//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log +//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. +//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also +//! warn for hello. In both cases the log message must include a single digit +//! number followed by 'scopes'. + +#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "http://www.rust-lang.org/favicon.ico", + html_root_url = "http://doc.rust-lang.org/env_logger/")] +#![cfg_attr(test, deny(warnings))] + +// When compiled for the rustc compiler itself we want to make sure that this is +// an unstable crate +#![cfg_attr(rustbuild, feature(staged_api, rustc_private))] +#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] + +extern crate log; + +use std::env; +use std::io::prelude::*; +use std::io; +use std::mem; + +use log::{Log, LogLevel, LogLevelFilter, LogRecord, SetLoggerError, LogMetadata}; + +#[cfg(feature = "regex")] +#[path = "regex.rs"] +mod filter; + +#[cfg(not(feature = "regex"))] +#[path = "string.rs"] +mod filter; + +/// Log target, either stdout or stderr. +#[derive(Debug)] +pub enum LogTarget { + Stdout, + Stderr, +} + +/// The logger. +pub struct Logger { + directives: Vec, + filter: Option, + format: Box String + Sync + Send>, + target: LogTarget, +} + +/// LogBuilder acts as builder for initializing the Logger. +/// It can be used to customize the log format, change the enviromental variable used +/// to provide the logging directives and also set the default log level filter. +/// +/// ## Example +/// +/// ``` +/// #[macro_use] +/// extern crate log; +/// extern crate env_logger; +/// +/// use std::env; +/// use log::{LogRecord, LogLevelFilter}; +/// use env_logger::LogBuilder; +/// +/// fn main() { +/// let format = |record: &LogRecord| { +/// format!("{} - {}", record.level(), record.args()) +/// }; +/// +/// let mut builder = LogBuilder::new(); +/// builder.format(format).filter(None, LogLevelFilter::Info); +/// +/// if env::var("RUST_LOG").is_ok() { +/// builder.parse(&env::var("RUST_LOG").unwrap()); +/// } +/// +/// builder.init().unwrap(); +/// +/// error!("error message"); +/// info!("info message"); +/// } +/// ``` +pub struct LogBuilder { + directives: Vec, + filter: Option, + format: Box String + Sync + Send>, + target: LogTarget, +} + +impl LogBuilder { + /// Initializes the log builder with defaults + pub fn new() -> LogBuilder { + LogBuilder { + directives: Vec::new(), + filter: None, + format: Box::new(|record: &LogRecord| { + format!("{}:{}: {}", record.level(), + record.location().module_path(), record.args()) + }), + target: LogTarget::Stderr, + } + } + + /// Adds filters to the logger + /// + /// The given module (if any) will log at most the specified level provided. + /// If no module is provided then the filter will apply to all log messages. + pub fn filter(&mut self, + module: Option<&str>, + level: LogLevelFilter) -> &mut Self { + self.directives.push(LogDirective { + name: module.map(|s| s.to_string()), + level: level, + }); + self + } + + /// Sets the format function for formatting the log output. + /// + /// This function is called on each record logged to produce a string which + /// is actually printed out. + pub fn format(&mut self, format: F) -> &mut Self + where F: Fn(&LogRecord) -> String + Sync + Send + { + self.format = Box::new(format); + self + } + + /// Sets the target for the log output. + /// + /// Env logger can log to either stdout or stderr. The default is stderr. + pub fn target(&mut self, target: LogTarget) -> &mut Self { + self.target = target; + self + } + + /// Parses the directives string in the same form as the RUST_LOG + /// environment variable. + /// + /// See the module documentation for more details. + pub fn parse(&mut self, filters: &str) -> &mut Self { + let (directives, filter) = parse_logging_spec(filters); + + self.filter = filter; + + for directive in directives { + self.directives.push(directive); + } + self + } + + /// Initializes the global logger with an env logger. + /// + /// This should be called early in the execution of a Rust program, and the + /// global logger may only be initialized once. Future initialization + /// attempts will return an error. + pub fn init(&mut self) -> Result<(), SetLoggerError> { + log::set_logger(|max_level| { + let logger = self.build(); + max_level.set(logger.filter()); + Box::new(logger) + }) + } + + /// Build an env logger. + pub fn build(&mut self) -> Logger { + if self.directives.is_empty() { + // Adds the default filter if none exist + self.directives.push(LogDirective { + name: None, + level: LogLevelFilter::Error, + }); + } else { + // Sort the directives by length of their name, this allows a + // little more efficient lookup at runtime. + self.directives.sort_by(|a, b| { + let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); + let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); + alen.cmp(&blen) + }); + } + + Logger { + directives: mem::replace(&mut self.directives, Vec::new()), + filter: mem::replace(&mut self.filter, None), + format: mem::replace(&mut self.format, Box::new(|_| String::new())), + target: mem::replace(&mut self.target, LogTarget::Stderr), + } + } +} + +impl Logger { + pub fn new() -> Logger { + let mut builder = LogBuilder::new(); + + if let Ok(s) = env::var("RUST_LOG") { + builder.parse(&s); + } + + builder.build() + } + + pub fn filter(&self) -> LogLevelFilter { + self.directives.iter() + .map(|d| d.level).max() + .unwrap_or(LogLevelFilter::Off) + } + + fn enabled(&self, level: LogLevel, target: &str) -> bool { + // Search for the longest match, the vector is assumed to be pre-sorted. + for directive in self.directives.iter().rev() { + match directive.name { + Some(ref name) if !target.starts_with(&**name) => {}, + Some(..) | None => { + return level <= directive.level + } + } + } + false + } +} + +impl Log for Logger { + fn enabled(&self, metadata: &LogMetadata) -> bool { + self.enabled(metadata.level(), metadata.target()) + } + + fn log(&self, record: &LogRecord) { + if !Log::enabled(self, record.metadata()) { + return; + } + + if let Some(filter) = self.filter.as_ref() { + if !filter.is_match(&*record.args().to_string()) { + return; + } + } + + match self.target { + LogTarget::Stdout => println!("{}", (self.format)(record)), + LogTarget::Stderr => { + let _ = writeln!(&mut io::stderr(), "{}", (self.format)(record)); + }, + }; + } +} + +struct LogDirective { + name: Option, + level: LogLevelFilter, +} + +/// Initializes the global logger with an env logger. +/// +/// This should be called early in the execution of a Rust program, and the +/// global logger may only be initialized once. Future initialization attempts +/// will return an error. +pub fn init() -> Result<(), SetLoggerError> { + let mut builder = LogBuilder::new(); + + if let Ok(s) = env::var("RUST_LOG") { + builder.parse(&s); + } + + builder.init() +} + +/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=error/foo") +/// and return a vector with log directives. +fn parse_logging_spec(spec: &str) -> (Vec, Option) { + let mut dirs = Vec::new(); + + let mut parts = spec.split('/'); + let mods = parts.next(); + let filter = parts.next(); + if parts.next().is_some() { + println!("warning: invalid logging spec '{}', \ + ignoring it (too many '/'s)", spec); + return (dirs, None); + } + mods.map(|m| { for s in m.split(',') { + if s.len() == 0 { continue } + let mut parts = s.split('='); + let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) { + (Some(part0), None, None) => { + // if the single argument is a log-level string or number, + // treat that as a global fallback + match part0.parse() { + Ok(num) => (num, None), + Err(_) => (LogLevelFilter::max(), Some(part0)), + } + } + (Some(part0), Some(""), None) => (LogLevelFilter::max(), Some(part0)), + (Some(part0), Some(part1), None) => { + match part1.parse() { + Ok(num) => (num, Some(part0)), + _ => { + println!("warning: invalid logging spec '{}', \ + ignoring it", part1); + continue + } + } + }, + _ => { + println!("warning: invalid logging spec '{}', \ + ignoring it", s); + continue + } + }; + dirs.push(LogDirective { + name: name.map(|s| s.to_string()), + level: log_level, + }); + }}); + + let filter = filter.map_or(None, |filter| { + match filter::Filter::new(filter) { + Ok(re) => Some(re), + Err(e) => { + println!("warning: invalid regex filter - {}", e); + None + } + } + }); + + return (dirs, filter); +} + +#[cfg(test)] +mod tests { + use log::{LogLevel, LogLevelFilter}; + + use super::{LogBuilder, Logger, LogDirective, parse_logging_spec}; + + fn make_logger(dirs: Vec) -> Logger { + let mut logger = LogBuilder::new().build(); + logger.directives = dirs; + logger + } + + #[test] + fn filter_info() { + let logger = LogBuilder::new().filter(None, LogLevelFilter::Info).build(); + assert!(logger.enabled(LogLevel::Info, "crate1")); + assert!(!logger.enabled(LogLevel::Debug, "crate1")); + } + + #[test] + fn filter_beginning_longest_match() { + let logger = LogBuilder::new() + .filter(Some("crate2"), LogLevelFilter::Info) + .filter(Some("crate2::mod"), LogLevelFilter::Debug) + .filter(Some("crate1::mod1"), LogLevelFilter::Warn) + .build(); + assert!(logger.enabled(LogLevel::Debug, "crate2::mod1")); + assert!(!logger.enabled(LogLevel::Debug, "crate2")); + } + + #[test] + fn parse_default() { + let logger = LogBuilder::new().parse("info,crate1::mod1=warn").build(); + assert!(logger.enabled(LogLevel::Warn, "crate1::mod1")); + assert!(logger.enabled(LogLevel::Info, "crate2::mod2")); + } + + #[test] + fn match_full_path() { + let logger = make_logger(vec![ + LogDirective { + name: Some("crate2".to_string()), + level: LogLevelFilter::Info + }, + LogDirective { + name: Some("crate1::mod1".to_string()), + level: LogLevelFilter::Warn + } + ]); + assert!(logger.enabled(LogLevel::Warn, "crate1::mod1")); + assert!(!logger.enabled(LogLevel::Info, "crate1::mod1")); + assert!(logger.enabled(LogLevel::Info, "crate2")); + assert!(!logger.enabled(LogLevel::Debug, "crate2")); + } + + #[test] + fn no_match() { + let logger = make_logger(vec![ + LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info }, + LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } + ]); + assert!(!logger.enabled(LogLevel::Warn, "crate3")); + } + + #[test] + fn match_beginning() { + let logger = make_logger(vec![ + LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info }, + LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } + ]); + assert!(logger.enabled(LogLevel::Info, "crate2::mod1")); + } + + #[test] + fn match_beginning_longest_match() { + let logger = make_logger(vec![ + LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info }, + LogDirective { name: Some("crate2::mod".to_string()), level: LogLevelFilter::Debug }, + LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } + ]); + assert!(logger.enabled(LogLevel::Debug, "crate2::mod1")); + assert!(!logger.enabled(LogLevel::Debug, "crate2")); + } + + #[test] + fn match_default() { + let logger = make_logger(vec![ + LogDirective { name: None, level: LogLevelFilter::Info }, + LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } + ]); + assert!(logger.enabled(LogLevel::Warn, "crate1::mod1")); + assert!(logger.enabled(LogLevel::Info, "crate2::mod2")); + } + + #[test] + fn zero_level() { + let logger = make_logger(vec![ + LogDirective { name: None, level: LogLevelFilter::Info }, + LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Off } + ]); + assert!(!logger.enabled(LogLevel::Error, "crate1::mod1")); + assert!(logger.enabled(LogLevel::Info, "crate2::mod2")); + } + + #[test] + fn parse_logging_spec_valid() { + let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug"); + assert_eq!(dirs.len(), 3); + assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::Error); + + assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); + assert_eq!(dirs[1].level, LogLevelFilter::max()); + + assert_eq!(dirs[2].name, Some("crate2".to_string())); + assert_eq!(dirs[2].level, LogLevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_logging_spec_invalid_crate() { + // test parse_logging_spec with multiple = in specification + let (dirs, filter) = parse_logging_spec("crate1::mod1=warn=info,crate2=debug"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_logging_spec_invalid_log_level() { + // test parse_logging_spec with 'noNumber' as log level + let (dirs, filter) = parse_logging_spec("crate1::mod1=noNumber,crate2=debug"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_logging_spec_string_log_level() { + // test parse_logging_spec with 'warn' as log level + let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=warn"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::Warn); + assert!(filter.is_none()); + } + + #[test] + fn parse_logging_spec_empty_log_level() { + // test parse_logging_spec with '' as log level + let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2="); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::max()); + assert!(filter.is_none()); + } + + #[test] + fn parse_logging_spec_global() { + // test parse_logging_spec with no crate + let (dirs, filter) = parse_logging_spec("warn,crate2=debug"); + assert_eq!(dirs.len(), 2); + assert_eq!(dirs[0].name, None); + assert_eq!(dirs[0].level, LogLevelFilter::Warn); + assert_eq!(dirs[1].name, Some("crate2".to_string())); + assert_eq!(dirs[1].level, LogLevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_logging_spec_valid_filter() { + let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc"); + assert_eq!(dirs.len(), 3); + assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::Error); + + assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); + assert_eq!(dirs[1].level, LogLevelFilter::max()); + + assert_eq!(dirs[2].name, Some("crate2".to_string())); + assert_eq!(dirs[2].level, LogLevelFilter::Debug); + assert!(filter.is_some() && filter.unwrap().to_string() == "abc"); + } + + #[test] + fn parse_logging_spec_invalid_crate_filter() { + let (dirs, filter) = parse_logging_spec("crate1::mod1=error=warn,crate2=debug/a.c"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::Debug); + assert!(filter.is_some() && filter.unwrap().to_string() == "a.c"); + } + + #[test] + fn parse_logging_spec_empty_with_filter() { + let (dirs, filter) = parse_logging_spec("crate1/a*c"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate1".to_string())); + assert_eq!(dirs[0].level, LogLevelFilter::max()); + assert!(filter.is_some() && filter.unwrap().to_string() == "a*c"); + } +} diff --git a/bash-5.1/vendor/env_logger/src/regex.rs b/bash-5.1/vendor/env_logger/src/regex.rs new file mode 100644 index 0000000..0df03e6 --- /dev/null +++ b/bash-5.1/vendor/env_logger/src/regex.rs @@ -0,0 +1,28 @@ +extern crate regex; + +use std::fmt; + +use self::regex::Regex; + +pub struct Filter { + inner: Regex, +} + +impl Filter { + pub fn new(spec: &str) -> Result { + match Regex::new(spec){ + Ok(r) => Ok(Filter { inner: r }), + Err(e) => Err(e.to_string()), + } + } + + pub fn is_match(&self, s: &str) -> bool { + self.inner.is_match(s) + } +} + +impl fmt::Display for Filter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} diff --git a/bash-5.1/vendor/env_logger/src/string.rs b/bash-5.1/vendor/env_logger/src/string.rs new file mode 100644 index 0000000..74d0e04 --- /dev/null +++ b/bash-5.1/vendor/env_logger/src/string.rs @@ -0,0 +1,21 @@ +use std::fmt; + +pub struct Filter { + inner: String, +} + +impl Filter { + pub fn new(spec: &str) -> Result { + Ok(Filter { inner: spec.to_string() }) + } + + pub fn is_match(&self, s: &str) -> bool { + s.contains(&self.inner) + } +} + +impl fmt::Display for Filter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} diff --git a/bash-5.1/vendor/env_logger/tests/regexp_filter.rs b/bash-5.1/vendor/env_logger/tests/regexp_filter.rs new file mode 100644 index 0000000..5036fb8 --- /dev/null +++ b/bash-5.1/vendor/env_logger/tests/regexp_filter.rs @@ -0,0 +1,51 @@ +#[macro_use] extern crate log; +extern crate env_logger; + +use std::process; +use std::env; +use std::str; + +fn main() { + if env::var("LOG_REGEXP_TEST").ok() == Some(String::from("1")) { + child_main(); + } else { + parent_main() + } +} + +fn child_main() { + env_logger::init().unwrap(); + info!("XYZ Message"); +} + +fn run_child(rust_log: String) -> bool { + let exe = env::current_exe().unwrap(); + let out = process::Command::new(exe) + .env("LOG_REGEXP_TEST", "1") + .env("RUST_LOG", rust_log) + .output() + .unwrap_or_else(|e| panic!("Unable to start child process: {}", e)); + str::from_utf8(out.stderr.as_ref()).unwrap().contains("XYZ Message") +} + +fn assert_message_printed(rust_log: &str) { + if !run_child(rust_log.to_string()) { + panic!("RUST_LOG={} should allow the test log message", rust_log) + } +} + +fn assert_message_not_printed(rust_log: &str) { + if run_child(rust_log.to_string()) { + panic!("RUST_LOG={} should not allow the test log message", rust_log) + } +} + +fn parent_main() { + // test normal log severity levels + assert_message_printed("info"); + assert_message_not_printed("warn"); + + // test of regular expression filters + assert_message_printed("info/XYZ"); + assert_message_not_printed("info/XXX"); +} diff --git a/bash-5.1/vendor/fuchsia-cprng/.cargo-checksum.json b/bash-5.1/vendor/fuchsia-cprng/.cargo-checksum.json new file mode 100644 index 0000000..d92a5f0 --- /dev/null +++ b/bash-5.1/vendor/fuchsia-cprng/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"AUTHORS":"f82920a5bcfc71b86c1de4be4cdea8af2009ba9e5735824f95ed5043a03e46f0","Cargo.toml":"bb2497b2907c3af499ce7ac3722dae044968e13409a372b7760150f8a01c74c5","LICENSE":"03b114f53e6587a398931762ee11e2395bfdba252a329940e2c8c9e81813845b","PATENTS":"52beb3ac72a0e7f5060384d16e4e6f91573016448fbff363c0b01a66fe99f547","src/lib.rs":"3d76c35c13203093ddf7ce2a3be5e98d768a8091cd9d99bd083fe8db35364096"},"package":"a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"} \ No newline at end of file diff --git a/bash-5.1/vendor/fuchsia-cprng/AUTHORS b/bash-5.1/vendor/fuchsia-cprng/AUTHORS new file mode 100644 index 0000000..61ae302 --- /dev/null +++ b/bash-5.1/vendor/fuchsia-cprng/AUTHORS @@ -0,0 +1,10 @@ +# This is the list of Fuchsia Authors. + +# Names should be added to this file as one of +# Organization's name +# Individual's name +# Individual's name + +Google Inc. +The Chromium Authors +The Go Authors diff --git a/bash-5.1/vendor/fuchsia-cprng/Cargo.toml b/bash-5.1/vendor/fuchsia-cprng/Cargo.toml new file mode 100644 index 0000000..917b430 --- /dev/null +++ b/bash-5.1/vendor/fuchsia-cprng/Cargo.toml @@ -0,0 +1,22 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "fuchsia-cprng" +version = "0.1.1" +authors = ["Erick Tryzelaar "] +include = ["src/*.rs", "Cargo.toml", "AUTHORS", "LICENSE", "PATENTS"] +description = "Rust crate for the Fuchsia cryptographically secure pseudorandom number generator" +readme = "README.md" +license-file = "LICENSE" +repository = "https://fuchsia.googlesource.com/fuchsia/+/master/garnet/public/rust/fuchsia-cprng" diff --git a/bash-5.1/vendor/fuchsia-cprng/LICENSE b/bash-5.1/vendor/fuchsia-cprng/LICENSE new file mode 100644 index 0000000..87f152c --- /dev/null +++ b/bash-5.1/vendor/fuchsia-cprng/LICENSE @@ -0,0 +1,27 @@ +Copyright 2019 The Fuchsia Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/bash-5.1/vendor/fuchsia-cprng/PATENTS b/bash-5.1/vendor/fuchsia-cprng/PATENTS new file mode 100644 index 0000000..2746e78 --- /dev/null +++ b/bash-5.1/vendor/fuchsia-cprng/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Fuchsia project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this +section) patent license to make, have made, use, offer to sell, sell, +import, transfer, and otherwise run, modify and propagate the contents +of this implementation of Fuchsia, where such license applies only to +those patent claims, both currently owned by Google and acquired in +the future, licensable by Google that are necessarily infringed by +this implementation. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute +or order or agree to the institution of patent litigation or any other +patent enforcement activity against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that this +implementation of Fuchsia constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of +Fuchsia shall terminate as of the date such litigation is filed. diff --git a/bash-5.1/vendor/fuchsia-cprng/src/lib.rs b/bash-5.1/vendor/fuchsia-cprng/src/lib.rs new file mode 100644 index 0000000..5074690 --- /dev/null +++ b/bash-5.1/vendor/fuchsia-cprng/src/lib.rs @@ -0,0 +1,57 @@ +// Copyright 2019 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for the Zircon kernel's CPRNG. + +#![no_std] +#![deny(warnings)] + +/// Draw random bytes from the kernel's CPRNG to fill the given buffer. +/// +/// Wraps the +/// [zx_cprng_draw](https://fuchsia.googlesource.com/fuchsia/+/master/zircon/docs/syscalls/cprng_draw.md) +/// syscall. +pub fn cprng_draw(buffer: &mut [u8]) { + unsafe { zx_cprng_draw(buffer.as_mut_ptr(), buffer.len()) }; +} + +#[link(name = "zircon")] +extern "C" { + fn zx_cprng_draw(buffer: *mut u8, length: usize); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cprng() { + let mut buffer = [0; 20]; + cprng_draw(&mut buffer); + let mut first_zero = 0; + let mut last_zero = 0; + for _ in 0..30 { + let mut buffer = [0; 20]; + cprng_draw(&mut buffer); + if buffer[0] == 0 { + first_zero += 1; + } + if buffer[19] == 0 { + last_zero += 1; + } + } + assert_ne!(first_zero, 30); + assert_ne!(last_zero, 30); + } + + #[test] + fn cprng_large() { + let mut buffer = [0; 1024]; + cprng_draw(&mut buffer); + + for mut s in buffer.chunks_mut(256) { + cprng_draw(&mut s); + } + } +} diff --git a/bash-5.1/vendor/futures-channel/tests/mpsc-size_hint.rs b/bash-5.1/vendor/futures-channel/tests/mpsc-size_hint.rs new file mode 100644 index 0000000..d9cdaa3 --- /dev/null +++ b/bash-5.1/vendor/futures-channel/tests/mpsc-size_hint.rs @@ -0,0 +1,40 @@ +use futures::channel::mpsc; +use futures::stream::Stream; + +#[test] +fn unbounded_size_hint() { + let (tx, mut rx) = mpsc::unbounded::(); + assert_eq!((0, None), rx.size_hint()); + tx.unbounded_send(1).unwrap(); + assert_eq!((1, None), rx.size_hint()); + rx.try_next().unwrap().unwrap(); + assert_eq!((0, None), rx.size_hint()); + tx.unbounded_send(2).unwrap(); + tx.unbounded_send(3).unwrap(); + assert_eq!((2, None), rx.size_hint()); + drop(tx); + assert_eq!((2, Some(2)), rx.size_hint()); + rx.try_next().unwrap().unwrap(); + assert_eq!((1, Some(1)), rx.size_hint()); + rx.try_next().unwrap().unwrap(); + assert_eq!((0, Some(0)), rx.size_hint()); +} + +#[test] +fn channel_size_hint() { + let (mut tx, mut rx) = mpsc::channel::(10); + assert_eq!((0, None), rx.size_hint()); + tx.try_send(1).unwrap(); + assert_eq!((1, None), rx.size_hint()); + rx.try_next().unwrap().unwrap(); + assert_eq!((0, None), rx.size_hint()); + tx.try_send(2).unwrap(); + tx.try_send(3).unwrap(); + assert_eq!((2, None), rx.size_hint()); + drop(tx); + assert_eq!((2, Some(2)), rx.size_hint()); + rx.try_next().unwrap().unwrap(); + assert_eq!((1, Some(1)), rx.size_hint()); + rx.try_next().unwrap().unwrap(); + assert_eq!((0, Some(0)), rx.size_hint()); +} diff --git a/bash-5.1/vendor/futures/tests/future_join.rs b/bash-5.1/vendor/futures/tests/future_join.rs new file mode 100644 index 0000000..f5df9d7 --- /dev/null +++ b/bash-5.1/vendor/futures/tests/future_join.rs @@ -0,0 +1,32 @@ +use futures::executor::block_on; +use futures::future::Future; +use std::task::Poll; + +/// This tests verifies (through miri) that self-referencing +/// futures are not invalidated when joining them. +#[test] +fn futures_join_macro_self_referential() { + block_on(async { futures::join!(yield_now(), trouble()) }); +} + +async fn trouble() { + let lucky_number = 42; + let problematic_variable = &lucky_number; + + yield_now().await; + + // problematic dereference + let _ = { *problematic_variable }; +} + +fn yield_now() -> impl Future { + let mut yielded = false; + std::future::poll_fn(move |cx| { + if core::mem::replace(&mut yielded, true) { + Poll::Ready(()) + } else { + cx.waker().wake_by_ref(); + Poll::Pending + } + }) +} diff --git a/bash-5.1/vendor/glob/.cargo-checksum.json b/bash-5.1/vendor/glob/.cargo-checksum.json new file mode 100644 index 0000000..d784163 --- /dev/null +++ b/bash-5.1/vendor/glob/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b3862d1373f5f97695d78d54323c0d66a703b930ffa1b21ea015a27e0cabc614","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"48acb43311019bbc775d08c25735c7a0b683d5910b2f63d426529e494289a7f5","src/lib.rs":"8cea6efa77fa8cea99bf56acda967cf99df24160a191ee546d89be1592880405","tests/glob-std.rs":"e630baaf33846cd19dd9d2ee45336d8b565844d1db0cb6fd2dafa9f8a4a49e39"},"package":"8be18de09a56b60ed0edf84bc9df007e30040691af7acd1c41874faac5895bfb"} \ No newline at end of file diff --git a/bash-5.1/vendor/glob/Cargo.toml b/bash-5.1/vendor/glob/Cargo.toml new file mode 100644 index 0000000..48ba719 --- /dev/null +++ b/bash-5.1/vendor/glob/Cargo.toml @@ -0,0 +1,15 @@ +[package] + +name = "glob" +version = "0.2.11" +authors = ["The Rust Project Developers"] +license = "MIT/Apache-2.0" +homepage = "https://github.com/rust-lang/glob" +repository = "https://github.com/rust-lang/glob" +documentation = "https://doc.rust-lang.org/glob" +description = """ +Support for matching file paths against Unix shell style patterns. +""" + +[dev-dependencies] +tempdir = "0.3" diff --git a/bash-5.1/vendor/glob/LICENSE-APACHE b/bash-5.1/vendor/glob/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/glob/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/glob/LICENSE-MIT b/bash-5.1/vendor/glob/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/glob/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/glob/README.md b/bash-5.1/vendor/glob/README.md new file mode 100644 index 0000000..86b112d --- /dev/null +++ b/bash-5.1/vendor/glob/README.md @@ -0,0 +1,24 @@ +glob +==== + +Support for matching file paths against Unix shell style patterns. + +[![Build Status](https://travis-ci.org/rust-lang-nursery/glob.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/glob) + +[Documentation](https://doc.rust-lang.org/glob) + +## Usage + +To use `glob`, add this to your `Cargo.toml`: + +```toml +[dependencies] +glob = "*" +``` + +And add this to your crate root: + +```rust +extern crate glob; +``` + diff --git a/bash-5.1/vendor/glob/src/lib.rs b/bash-5.1/vendor/glob/src/lib.rs new file mode 100644 index 0000000..a26b996 --- /dev/null +++ b/bash-5.1/vendor/glob/src/lib.rs @@ -0,0 +1,1312 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Support for matching file paths against Unix shell style patterns. +//! +//! The `glob` and `glob_with` functions, in concert with the `Paths` +//! type, allow querying the filesystem for all files that match a particular +//! pattern - just like the libc `glob` function (for an example see the `glob` +//! documentation). The methods on the `Pattern` type provide functionality +//! for checking if individual paths match a particular pattern - in a similar +//! manner to the libc `fnmatch` function +//! For consistency across platforms, and for Windows support, this module +//! is implemented entirely in Rust rather than deferring to the libc +//! `glob`/`fnmatch` functions. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/glob/")] +#![cfg_attr(all(test, windows), feature(std_misc))] + +use std::ascii::AsciiExt; +use std::cmp; +use std::fmt; +use std::fs; +use std::io::prelude::*; +use std::io; +use std::path::{self, Path, PathBuf, Component}; +use std::str::FromStr; +use std::error::Error; + +use PatternToken::{Char, AnyChar, AnySequence, AnyRecursiveSequence, AnyWithin}; +use PatternToken::AnyExcept; +use CharSpecifier::{SingleChar, CharRange}; +use MatchResult::{Match, SubPatternDoesntMatch, EntirePatternDoesntMatch}; + +/// An iterator that yields `Path`s from the filesystem that match a particular +/// pattern. +/// +/// Note that it yields `GlobResult` in order to report any `IoErrors` that may +/// arise during iteration. If a directory matches but is unreadable, +/// thereby preventing its contents from being checked for matches, a +/// `GlobError` is returned to express this. +/// +/// See the `glob` function for more details. +pub struct Paths { + dir_patterns: Vec, + require_dir: bool, + options: MatchOptions, + todo: Vec>, + scope: Option, +} + +/// Return an iterator that produces all the Paths that match the given pattern, +/// which may be absolute or relative to the current working directory. +/// +/// This may return an error if the pattern is invalid. +/// +/// This method uses the default match options and is equivalent to calling +/// `glob_with(pattern, MatchOptions::new())`. Use `glob_with` directly if you +/// want to use non-default match options. +/// +/// When iterating, each result is a `GlobResult` which expresses the +/// possibility that there was an `IoError` when attempting to read the contents +/// of the matched path. In other words, each item returned by the iterator +/// will either be an `Ok(Path)` if the path matched, or an `Err(GlobError)` if +/// the path (partially) matched _but_ its contents could not be read in order +/// to determine if its contents matched. +/// +/// See the `Paths` documentation for more information. +/// +/// # Example +/// +/// Consider a directory `/media/pictures` containing only the files +/// `kittens.jpg`, `puppies.jpg` and `hamsters.gif`: +/// +/// ```rust +/// use glob::glob; +/// +/// for entry in glob("/media/pictures/*.jpg").unwrap() { +/// match entry { +/// Ok(path) => println!("{:?}", path.display()), +/// +/// // if the path matched but was unreadable, +/// // thereby preventing its contents from matching +/// Err(e) => println!("{:?}", e), +/// } +/// } +/// ``` +/// +/// The above code will print: +/// +/// ```ignore +/// /media/pictures/kittens.jpg +/// /media/pictures/puppies.jpg +/// ``` +/// +/// If you want to ignore unreadable paths, you can use something like +/// `filter_map`: +/// +/// ```rust +/// use glob::glob; +/// use std::result::Result; +/// +/// for path in glob("/media/pictures/*.jpg").unwrap().filter_map(Result::ok) { +/// println!("{}", path.display()); +/// } +/// ``` +/// +pub fn glob(pattern: &str) -> Result { + glob_with(pattern, &MatchOptions::new()) +} + +/// Return an iterator that produces all the Paths that match the given pattern, +/// which may be absolute or relative to the current working directory. +/// +/// This may return an error if the pattern is invalid. +/// +/// This function accepts Unix shell style patterns as described by +/// `Pattern::new(..)`. The options given are passed through unchanged to +/// `Pattern::matches_with(..)` with the exception that +/// `require_literal_separator` is always set to `true` regardless of the value +/// passed to this function. +/// +/// Paths are yielded in alphabetical order. +pub fn glob_with(pattern: &str, options: &MatchOptions) -> Result { + // make sure that the pattern is valid first, else early return with error + let _compiled = try!(Pattern::new(pattern)); + + #[cfg(windows)] + fn check_windows_verbatim(p: &Path) -> bool { + use std::path::Prefix; + match p.components().next() { + Some(Component::Prefix(ref p)) => p.kind().is_verbatim(), + _ => false, + } + } + #[cfg(not(windows))] + fn check_windows_verbatim(_: &Path) -> bool { + false + } + + #[cfg(windows)] + fn to_scope(p: &Path) -> PathBuf { + // FIXME handle volume relative paths here + p.to_path_buf() + } + #[cfg(not(windows))] + fn to_scope(p: &Path) -> PathBuf { + p.to_path_buf() + } + + let mut components = Path::new(pattern).components().peekable(); + loop { + match components.peek() { + Some(&Component::Prefix(..)) | + Some(&Component::RootDir) => { + components.next(); + } + _ => break, + } + } + let rest = components.map(|s| s.as_os_str()).collect::(); + let normalized_pattern = Path::new(pattern).iter().collect::(); + let root_len = normalized_pattern.to_str().unwrap().len() - rest.to_str().unwrap().len(); + let root = if root_len > 0 { + Some(Path::new(&pattern[..root_len])) + } else { + None + }; + + if root_len > 0 && check_windows_verbatim(root.unwrap()) { + // FIXME: How do we want to handle verbatim paths? I'm inclined to + // return nothing, since we can't very well find all UNC shares with a + // 1-letter server name. + return Ok(Paths { + dir_patterns: Vec::new(), + require_dir: false, + options: options.clone(), + todo: Vec::new(), + scope: None, + }); + } + + let scope = root.map(to_scope).unwrap_or_else(|| PathBuf::from(".")); + + let mut dir_patterns = Vec::new(); + let components = pattern[cmp::min(root_len, pattern.len())..] + .split_terminator(path::is_separator); + + for component in components { + let compiled = try!(Pattern::new(component)); + dir_patterns.push(compiled); + } + + if root_len == pattern.len() { + dir_patterns.push(Pattern { + original: "".to_string(), + tokens: Vec::new(), + is_recursive: false, + }); + } + + let require_dir = pattern.chars().next_back().map(path::is_separator) == Some(true); + let todo = Vec::new(); + + Ok(Paths { + dir_patterns: dir_patterns, + require_dir: require_dir, + options: options.clone(), + todo: todo, + scope: Some(scope), + }) +} + +/// A glob iteration error. +/// +/// This is typically returned when a particular path cannot be read +/// to determine if its contents match the glob pattern. This is possible +/// if the program lacks the permissions, for example. +#[derive(Debug)] +pub struct GlobError { + path: PathBuf, + error: io::Error, +} + +impl GlobError { + /// The Path that the error corresponds to. + pub fn path(&self) -> &Path { + &self.path + } + + /// The error in question. + pub fn error(&self) -> &io::Error { + &self.error + } +} + +impl Error for GlobError { + fn description(&self) -> &str { + self.error.description() + } + fn cause(&self) -> Option<&Error> { + Some(&self.error) + } +} + +impl fmt::Display for GlobError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, + "attempting to read `{}` resulted in an error: {}", + self.path.display(), + self.error) + } +} + +fn is_dir(p: &Path) -> bool { + fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false) +} + +/// An alias for a glob iteration result. +/// +/// This represents either a matched path or a glob iteration error, +/// such as failing to read a particular directory's contents. +pub type GlobResult = Result; + +impl Iterator for Paths { + type Item = GlobResult; + + fn next(&mut self) -> Option { + // the todo buffer hasn't been initialized yet, so it's done at this + // point rather than in glob() so that the errors are unified that is, + // failing to fill the buffer is an iteration error construction of the + // iterator (i.e. glob()) only fails if it fails to compile the Pattern + if let Some(scope) = self.scope.take() { + if self.dir_patterns.len() > 0 { + // Shouldn't happen, but we're using -1 as a special index. + assert!(self.dir_patterns.len() < !0 as usize); + + fill_todo(&mut self.todo, &self.dir_patterns, 0, &scope, &self.options); + } + } + + loop { + if self.dir_patterns.is_empty() || self.todo.is_empty() { + return None; + } + + let (path, mut idx) = match self.todo.pop().unwrap() { + Ok(pair) => pair, + Err(e) => return Some(Err(e)), + }; + + // idx -1: was already checked by fill_todo, maybe path was '.' or + // '..' that we can't match here because of normalization. + if idx == !0 as usize { + if self.require_dir && !is_dir(&path) { + continue; + } + return Some(Ok(path)); + } + + if self.dir_patterns[idx].is_recursive { + let mut next = idx; + + // collapse consecutive recursive patterns + while (next + 1) < self.dir_patterns.len() && + self.dir_patterns[next + 1].is_recursive { + next += 1; + } + + if is_dir(&path) { + // the path is a directory, so it's a match + + // push this directory's contents + fill_todo(&mut self.todo, + &self.dir_patterns, + next, + &path, + &self.options); + + if next == self.dir_patterns.len() - 1 { + // pattern ends in recursive pattern, so return this + // directory as a result + return Some(Ok(path)); + } else { + // advanced to the next pattern for this path + idx = next + 1; + } + } else if next != self.dir_patterns.len() - 1 { + // advanced to the next pattern for this path + idx = next + 1; + } else { + // not a directory and it's the last pattern, meaning no match + continue; + } + } + + // not recursive, so match normally + if self.dir_patterns[idx].matches_with({ + match path.file_name().and_then(|s| s.to_str()) { + // FIXME (#9639): How do we handle non-utf8 filenames? + // Ignore them for now Ideally we'd still match them + // against a * + None => continue, + Some(x) => x + } + }, &self.options) { + if idx == self.dir_patterns.len() - 1 { + // it is not possible for a pattern to match a directory + // *AND* its children so we don't need to check the + // children + + if !self.require_dir || is_dir(&path) { + return Some(Ok(path)); + } + } else { + fill_todo(&mut self.todo, &self.dir_patterns, + idx + 1, &path, &self.options); + } + } + } + } +} + +/// A pattern parsing error. +#[derive(Debug)] +#[allow(missing_copy_implementations)] +pub struct PatternError { + /// The approximate character index of where the error occurred. + pub pos: usize, + + /// A message describing the error. + pub msg: &'static str, +} + +impl Error for PatternError { + fn description(&self) -> &str { + self.msg + } +} + +impl fmt::Display for PatternError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, + "Pattern syntax error near position {}: {}", + self.pos, + self.msg) + } +} + +/// A compiled Unix shell style pattern. +/// +/// `?` matches any single character +/// +/// `*` matches any (possibly empty) sequence of characters +/// +/// `**` matches the current directory and arbitrary subdirectories. This +/// sequence **must** form a single path component, so both `**a` and `b**` are +/// invalid and will result in an error. A sequence of more than two +/// consecutive `*` characters is also invalid. +/// +/// `[...]` matches any character inside the brackets. +/// Character sequences can also specify ranges +/// of characters, as ordered by Unicode, so e.g. `[0-9]` specifies any +/// character between 0 and 9 inclusive. An unclosed bracket is invalid. +/// +/// `[!...]` is the negation of `[...]`, i.e. it matches any characters **not** +/// in the brackets. +/// +/// The metacharacters `?`, `*`, `[`, `]` can be matched by using brackets +/// (e.g. `[?]`). When a `]` occurs immediately following `[` or `[!` then +/// it is interpreted as being part of, rather then ending, the character +/// set, so `]` and NOT `]` can be matched by `[]]` and `[!]]` respectively. +/// The `-` character can be specified inside a character sequence pattern by +/// placing it at the start or the end, e.g. `[abc-]`. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] +pub struct Pattern { + original: String, + tokens: Vec, + is_recursive: bool, +} + +/// Show the original glob pattern. +impl fmt::Display for Pattern { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.original.fmt(f) + } +} + +impl FromStr for Pattern { + type Err = PatternError; + + fn from_str(s: &str) -> Result { + Pattern::new(s) + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +enum PatternToken { + Char(char), + AnyChar, + AnySequence, + AnyRecursiveSequence, + AnyWithin(Vec), + AnyExcept(Vec), +} + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +enum CharSpecifier { + SingleChar(char), + CharRange(char, char), +} + +#[derive(Copy, Clone, PartialEq)] +enum MatchResult { + Match, + SubPatternDoesntMatch, + EntirePatternDoesntMatch, +} + +const ERROR_WILDCARDS: &'static str = "wildcards are either regular `*` or recursive `**`"; +const ERROR_RECURSIVE_WILDCARDS: &'static str = "recursive wildcards must form a single path \ + component"; +const ERROR_INVALID_RANGE: &'static str = "invalid range pattern"; + +impl Pattern { + /// This function compiles Unix shell style patterns. + /// + /// An invalid glob pattern will yield an error. + pub fn new(pattern: &str) -> Result { + + let chars = pattern.chars().collect::>(); + let mut tokens = Vec::new(); + let mut is_recursive = false; + let mut i = 0; + + while i < chars.len() { + match chars[i] { + '?' => { + tokens.push(AnyChar); + i += 1; + } + '*' => { + let old = i; + + while i < chars.len() && chars[i] == '*' { + i += 1; + } + + let count = i - old; + + if count > 2 { + return Err(PatternError { + pos: old + 2, + msg: ERROR_WILDCARDS, + }); + } else if count == 2 { + // ** can only be an entire path component + // i.e. a/**/b is valid, but a**/b or a/**b is not + // invalid matches are treated literally + let is_valid = if i == 2 || path::is_separator(chars[i - count - 1]) { + // it ends in a '/' + if i < chars.len() && path::is_separator(chars[i]) { + i += 1; + true + // or the pattern ends here + // this enables the existing globbing mechanism + } else if i == chars.len() { + true + // `**` ends in non-separator + } else { + return Err(PatternError { + pos: i, + msg: ERROR_RECURSIVE_WILDCARDS, + }); + } + // `**` begins with non-separator + } else { + return Err(PatternError { + pos: old - 1, + msg: ERROR_RECURSIVE_WILDCARDS, + }); + }; + + let tokens_len = tokens.len(); + + if is_valid { + // collapse consecutive AnyRecursiveSequence to a + // single one + if !(tokens_len > 1 && tokens[tokens_len - 1] == AnyRecursiveSequence) { + is_recursive = true; + tokens.push(AnyRecursiveSequence); + } + } + } else { + tokens.push(AnySequence); + } + } + '[' => { + + if i + 4 <= chars.len() && chars[i + 1] == '!' { + match chars[i + 3..].iter().position(|x| *x == ']') { + None => (), + Some(j) => { + let chars = &chars[i + 2..i + 3 + j]; + let cs = parse_char_specifiers(chars); + tokens.push(AnyExcept(cs)); + i += j + 4; + continue; + } + } + } else if i + 3 <= chars.len() && chars[i + 1] != '!' { + match chars[i + 2..].iter().position(|x| *x == ']') { + None => (), + Some(j) => { + let cs = parse_char_specifiers(&chars[i + 1..i + 2 + j]); + tokens.push(AnyWithin(cs)); + i += j + 3; + continue; + } + } + } + + // if we get here then this is not a valid range pattern + return Err(PatternError { + pos: i, + msg: ERROR_INVALID_RANGE, + }); + } + c => { + tokens.push(Char(c)); + i += 1; + } + } + } + + Ok(Pattern { + tokens: tokens, + original: pattern.to_string(), + is_recursive: is_recursive, + }) + } + + /// Escape metacharacters within the given string by surrounding them in + /// brackets. The resulting string will, when compiled into a `Pattern`, + /// match the input string and nothing else. + pub fn escape(s: &str) -> String { + let mut escaped = String::new(); + for c in s.chars() { + match c { + // note that ! does not need escaping because it is only special + // inside brackets + '?' | '*' | '[' | ']' => { + escaped.push('['); + escaped.push(c); + escaped.push(']'); + } + c => { + escaped.push(c); + } + } + } + escaped + } + + /// Return if the given `str` matches this `Pattern` using the default + /// match options (i.e. `MatchOptions::new()`). + /// + /// # Example + /// + /// ```rust + /// use glob::Pattern; + /// + /// assert!(Pattern::new("c?t").unwrap().matches("cat")); + /// assert!(Pattern::new("k[!e]tteh").unwrap().matches("kitteh")); + /// assert!(Pattern::new("d*g").unwrap().matches("doog")); + /// ``` + pub fn matches(&self, str: &str) -> bool { + self.matches_with(str, &MatchOptions::new()) + } + + /// Return if the given `Path`, when converted to a `str`, matches this + /// `Pattern` using the default match options (i.e. `MatchOptions::new()`). + pub fn matches_path(&self, path: &Path) -> bool { + // FIXME (#9639): This needs to handle non-utf8 paths + path.to_str().map_or(false, |s| self.matches(s)) + } + + /// Return if the given `str` matches this `Pattern` using the specified + /// match options. + pub fn matches_with(&self, str: &str, options: &MatchOptions) -> bool { + self.matches_from(true, str.chars(), 0, options) == Match + } + + /// Return if the given `Path`, when converted to a `str`, matches this + /// `Pattern` using the specified match options. + pub fn matches_path_with(&self, path: &Path, options: &MatchOptions) -> bool { + // FIXME (#9639): This needs to handle non-utf8 paths + path.to_str().map_or(false, |s| self.matches_with(s, options)) + } + + /// Access the original glob pattern. + pub fn as_str<'a>(&'a self) -> &'a str { + &self.original + } + + fn matches_from(&self, + mut follows_separator: bool, + mut file: std::str::Chars, + i: usize, + options: &MatchOptions) + -> MatchResult { + + for (ti, token) in self.tokens[i..].iter().enumerate() { + match *token { + AnySequence | AnyRecursiveSequence => { + // ** must be at the start. + debug_assert!(match *token { + AnyRecursiveSequence => follows_separator, + _ => true, + }); + + // Empty match + match self.matches_from(follows_separator, file.clone(), i + ti + 1, options) { + SubPatternDoesntMatch => (), // keep trying + m => return m, + }; + + while let Some(c) = file.next() { + if follows_separator && options.require_literal_leading_dot && c == '.' { + return SubPatternDoesntMatch; + } + follows_separator = path::is_separator(c); + match *token { + AnyRecursiveSequence if !follows_separator => continue, + AnySequence if options.require_literal_separator && + follows_separator => return SubPatternDoesntMatch, + _ => (), + } + match self.matches_from(follows_separator, + file.clone(), + i + ti + 1, + options) { + SubPatternDoesntMatch => (), // keep trying + m => return m, + } + } + } + _ => { + let c = match file.next() { + Some(c) => c, + None => return EntirePatternDoesntMatch, + }; + + let is_sep = path::is_separator(c); + + if !match *token { + AnyChar | AnyWithin(..) | AnyExcept(..) + if (options.require_literal_separator && is_sep) || + (follows_separator && options.require_literal_leading_dot && + c == '.') => false, + AnyChar => true, + AnyWithin(ref specifiers) => in_char_specifiers(&specifiers, c, options), + AnyExcept(ref specifiers) => !in_char_specifiers(&specifiers, c, options), + Char(c2) => chars_eq(c, c2, options.case_sensitive), + AnySequence | AnyRecursiveSequence => unreachable!(), + } { + return SubPatternDoesntMatch; + } + follows_separator = is_sep; + } + } + } + + // Iter is fused. + if file.next().is_none() { + Match + } else { + SubPatternDoesntMatch + } + } +} + +// Fills `todo` with paths under `path` to be matched by `patterns[idx]`, +// special-casing patterns to match `.` and `..`, and avoiding `readdir()` +// calls when there are no metacharacters in the pattern. +fn fill_todo(todo: &mut Vec>, + patterns: &[Pattern], + idx: usize, + path: &Path, + options: &MatchOptions) { + // convert a pattern that's just many Char(_) to a string + fn pattern_as_str(pattern: &Pattern) -> Option { + let mut s = String::new(); + for token in pattern.tokens.iter() { + match *token { + Char(c) => s.push(c), + _ => return None, + } + } + return Some(s); + } + + let add = |todo: &mut Vec<_>, next_path: PathBuf| { + if idx + 1 == patterns.len() { + // We know it's good, so don't make the iterator match this path + // against the pattern again. In particular, it can't match + // . or .. globs since these never show up as path components. + todo.push(Ok((next_path, !0 as usize))); + } else { + fill_todo(todo, patterns, idx + 1, &next_path, options); + } + }; + + let pattern = &patterns[idx]; + let is_dir = is_dir(path); + let curdir = path == Path::new("."); + match pattern_as_str(pattern) { + Some(s) => { + // This pattern component doesn't have any metacharacters, so we + // don't need to read the current directory to know where to + // continue. So instead of passing control back to the iterator, + // we can just check for that one entry and potentially recurse + // right away. + let special = "." == s || ".." == s; + let next_path = if curdir { + PathBuf::from(s) + } else { + path.join(&s) + }; + if (special && is_dir) || (!special && fs::metadata(&next_path).is_ok()) { + add(todo, next_path); + } + } + None if is_dir => { + let dirs = fs::read_dir(path).and_then(|d| { + d.map(|e| { + e.map(|e| { + if curdir { + PathBuf::from(e.path().file_name().unwrap()) + } else { + e.path() + } + }) + }) + .collect::, _>>() + }); + match dirs { + Ok(mut children) => { + children.sort_by(|p1, p2| p2.file_name().cmp(&p1.file_name())); + todo.extend(children.into_iter().map(|x| Ok((x, idx)))); + + // Matching the special directory entries . and .. that + // refer to the current and parent directory respectively + // requires that the pattern has a leading dot, even if the + // `MatchOptions` field `require_literal_leading_dot` is not + // set. + if pattern.tokens.len() > 0 && pattern.tokens[0] == Char('.') { + for &special in [".", ".."].iter() { + if pattern.matches_with(special, options) { + add(todo, path.join(special)); + } + } + } + } + Err(e) => { + todo.push(Err(GlobError { + path: path.to_path_buf(), + error: e, + })); + } + } + } + None => { + // not a directory, nothing more to find + } + } +} + +fn parse_char_specifiers(s: &[char]) -> Vec { + let mut cs = Vec::new(); + let mut i = 0; + while i < s.len() { + if i + 3 <= s.len() && s[i + 1] == '-' { + cs.push(CharRange(s[i], s[i + 2])); + i += 3; + } else { + cs.push(SingleChar(s[i])); + i += 1; + } + } + cs +} + +fn in_char_specifiers(specifiers: &[CharSpecifier], c: char, options: &MatchOptions) -> bool { + + for &specifier in specifiers.iter() { + match specifier { + SingleChar(sc) => { + if chars_eq(c, sc, options.case_sensitive) { + return true; + } + } + CharRange(start, end) => { + + // FIXME: work with non-ascii chars properly (issue #1347) + if !options.case_sensitive && c.is_ascii() && start.is_ascii() && end.is_ascii() { + + let start = start.to_ascii_lowercase(); + let end = end.to_ascii_lowercase(); + + let start_up = start.to_uppercase().next().unwrap(); + let end_up = end.to_uppercase().next().unwrap(); + + // only allow case insensitive matching when + // both start and end are within a-z or A-Z + if start != start_up && end != end_up { + let c = c.to_ascii_lowercase(); + if c >= start && c <= end { + return true; + } + } + } + + if c >= start && c <= end { + return true; + } + } + } + } + + false +} + +/// A helper function to determine if two chars are (possibly case-insensitively) equal. +fn chars_eq(a: char, b: char, case_sensitive: bool) -> bool { + if cfg!(windows) && path::is_separator(a) && path::is_separator(b) { + true + } else if !case_sensitive && a.is_ascii() && b.is_ascii() { + // FIXME: work with non-ascii chars properly (issue #9084) + a.to_ascii_lowercase() == b.to_ascii_lowercase() + } else { + a == b + } +} + + +/// Configuration options to modify the behaviour of `Pattern::matches_with(..)` +#[allow(missing_copy_implementations)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct MatchOptions { + /// Whether or not patterns should be matched in a case-sensitive manner. + /// This currently only considers upper/lower case relationships between + /// ASCII characters, but in future this might be extended to work with + /// Unicode. + pub case_sensitive: bool, + + /// If this is true then path-component separator characters (e.g. `/` on + /// Posix) must be matched by a literal `/`, rather than by `*` or `?` or + /// `[...]` + pub require_literal_separator: bool, + + /// If this is true then paths that contain components that start with a `.` + /// will not match unless the `.` appears literally in the pattern: `*`, `?`, `**`, + /// or `[...]` will not match. This is useful because such files are + /// conventionally considered hidden on Unix systems and it might be + /// desirable to skip them when listing files. + pub require_literal_leading_dot: bool, +} + +impl MatchOptions { + /// Constructs a new `MatchOptions` with default field values. This is used + /// when calling functions that do not take an explicit `MatchOptions` + /// parameter. + /// + /// This function always returns this value: + /// + /// ```rust,ignore + /// MatchOptions { + /// case_sensitive: true, + /// require_literal_separator: false. + /// require_literal_leading_dot: false + /// } + /// ``` + pub fn new() -> MatchOptions { + MatchOptions { + case_sensitive: true, + require_literal_separator: false, + require_literal_leading_dot: false, + } + } +} + +#[cfg(test)] +mod test { + use std::path::Path; + use super::{glob, Pattern, MatchOptions}; + + #[test] + fn test_pattern_from_str() { + assert!("a*b".parse::().unwrap().matches("a_b")); + assert!("a/**b".parse::().unwrap_err().pos == 4); + } + + #[test] + fn test_wildcard_errors() { + assert!(Pattern::new("a/**b").unwrap_err().pos == 4); + assert!(Pattern::new("a/bc**").unwrap_err().pos == 3); + assert!(Pattern::new("a/*****").unwrap_err().pos == 4); + assert!(Pattern::new("a/b**c**d").unwrap_err().pos == 2); + assert!(Pattern::new("a**b").unwrap_err().pos == 0); + } + + #[test] + fn test_unclosed_bracket_errors() { + assert!(Pattern::new("abc[def").unwrap_err().pos == 3); + assert!(Pattern::new("abc[!def").unwrap_err().pos == 3); + assert!(Pattern::new("abc[").unwrap_err().pos == 3); + assert!(Pattern::new("abc[!").unwrap_err().pos == 3); + assert!(Pattern::new("abc[d").unwrap_err().pos == 3); + assert!(Pattern::new("abc[!d").unwrap_err().pos == 3); + assert!(Pattern::new("abc[]").unwrap_err().pos == 3); + assert!(Pattern::new("abc[!]").unwrap_err().pos == 3); + } + + #[test] + fn test_glob_errors() { + assert!(glob("a/**b").err().unwrap().pos == 4); + assert!(glob("abc[def").err().unwrap().pos == 3); + } + + // this test assumes that there is a /root directory and that + // the user running this test is not root or otherwise doesn't + // have permission to read its contents + #[cfg(unix)] + #[test] + fn test_iteration_errors() { + use std::io; + let mut iter = glob("/root/*").unwrap(); + + // GlobErrors shouldn't halt iteration + let next = iter.next(); + assert!(next.is_some()); + + let err = next.unwrap(); + assert!(err.is_err()); + + let err = err.err().unwrap(); + assert!(err.path() == Path::new("/root")); + assert!(err.error().kind() == io::ErrorKind::PermissionDenied); + } + + #[test] + fn test_absolute_pattern() { + assert!(glob("/").unwrap().next().is_some()); + assert!(glob("//").unwrap().next().is_some()); + + // assume that the filesystem is not empty! + assert!(glob("/*").unwrap().next().is_some()); + + #[cfg(not(windows))] + fn win() {} + + #[cfg(windows)] + fn win() { + use std::env::current_dir; + use std::ffi::AsOsStr; + + // check windows absolute paths with host/device components + let root_with_device = current_dir() + .ok() + .and_then(|p| p.prefix().map(|p| p.join("*"))) + .unwrap(); + // FIXME (#9639): This needs to handle non-utf8 paths + assert!(glob(root_with_device.as_os_str().to_str().unwrap()).unwrap().next().is_some()); + } + win() + } + + #[test] + fn test_wildcards() { + assert!(Pattern::new("a*b").unwrap().matches("a_b")); + assert!(Pattern::new("a*b*c").unwrap().matches("abc")); + assert!(!Pattern::new("a*b*c").unwrap().matches("abcd")); + assert!(Pattern::new("a*b*c").unwrap().matches("a_b_c")); + assert!(Pattern::new("a*b*c").unwrap().matches("a___b___c")); + assert!(Pattern::new("abc*abc*abc").unwrap().matches("abcabcabcabcabcabcabc")); + assert!(!Pattern::new("abc*abc*abc").unwrap().matches("abcabcabcabcabcabcabca")); + assert!(Pattern::new("a*a*a*a*a*a*a*a*a") + .unwrap() + .matches("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); + assert!(Pattern::new("a*b[xyz]c*d").unwrap().matches("abxcdbxcddd")); + } + + #[test] + fn test_recursive_wildcards() { + let pat = Pattern::new("some/**/needle.txt").unwrap(); + assert!(pat.matches("some/needle.txt")); + assert!(pat.matches("some/one/needle.txt")); + assert!(pat.matches("some/one/two/needle.txt")); + assert!(pat.matches("some/other/needle.txt")); + assert!(!pat.matches("some/other/notthis.txt")); + + // a single ** should be valid, for globs + // Should accept anything + let pat = Pattern::new("**").unwrap(); + assert!(pat.is_recursive); + assert!(pat.matches("abcde")); + assert!(pat.matches("")); + assert!(pat.matches(".asdf")); + assert!(pat.matches("/x/.asdf")); + + + // collapse consecutive wildcards + let pat = Pattern::new("some/**/**/needle.txt").unwrap(); + assert!(pat.matches("some/needle.txt")); + assert!(pat.matches("some/one/needle.txt")); + assert!(pat.matches("some/one/two/needle.txt")); + assert!(pat.matches("some/other/needle.txt")); + assert!(!pat.matches("some/other/notthis.txt")); + + // ** can begin the pattern + let pat = Pattern::new("**/test").unwrap(); + assert!(pat.matches("one/two/test")); + assert!(pat.matches("one/test")); + assert!(pat.matches("test")); + + // /** can begin the pattern + let pat = Pattern::new("/**/test").unwrap(); + assert!(pat.matches("/one/two/test")); + assert!(pat.matches("/one/test")); + assert!(pat.matches("/test")); + assert!(!pat.matches("/one/notthis")); + assert!(!pat.matches("/notthis")); + + // Only start sub-patterns on start of path segment. + let pat = Pattern::new("**/.*").unwrap(); + assert!(pat.matches(".abc")); + assert!(pat.matches("abc/.abc")); + assert!(!pat.matches("ab.c")); + assert!(!pat.matches("abc/ab.c")); + } + + #[test] + fn test_lots_of_files() { + // this is a good test because it touches lots of differently named files + glob("/*/*/*/*").unwrap().skip(10000).next(); + } + + #[test] + fn test_range_pattern() { + + let pat = Pattern::new("a[0-9]b").unwrap(); + for i in 0..10 { + assert!(pat.matches(&format!("a{}b", i))); + } + assert!(!pat.matches("a_b")); + + let pat = Pattern::new("a[!0-9]b").unwrap(); + for i in 0..10 { + assert!(!pat.matches(&format!("a{}b", i))); + } + assert!(pat.matches("a_b")); + + let pats = ["[a-z123]", "[1a-z23]", "[123a-z]"]; + for &p in pats.iter() { + let pat = Pattern::new(p).unwrap(); + for c in "abcdefghijklmnopqrstuvwxyz".chars() { + assert!(pat.matches(&c.to_string())); + } + for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() { + let options = MatchOptions { case_sensitive: false, ..MatchOptions::new() }; + assert!(pat.matches_with(&c.to_string(), &options)); + } + assert!(pat.matches("1")); + assert!(pat.matches("2")); + assert!(pat.matches("3")); + } + + let pats = ["[abc-]", "[-abc]", "[a-c-]"]; + for &p in pats.iter() { + let pat = Pattern::new(p).unwrap(); + assert!(pat.matches("a")); + assert!(pat.matches("b")); + assert!(pat.matches("c")); + assert!(pat.matches("-")); + assert!(!pat.matches("d")); + } + + let pat = Pattern::new("[2-1]").unwrap(); + assert!(!pat.matches("1")); + assert!(!pat.matches("2")); + + assert!(Pattern::new("[-]").unwrap().matches("-")); + assert!(!Pattern::new("[!-]").unwrap().matches("-")); + } + + #[test] + fn test_pattern_matches() { + let txt_pat = Pattern::new("*hello.txt").unwrap(); + assert!(txt_pat.matches("hello.txt")); + assert!(txt_pat.matches("gareth_says_hello.txt")); + assert!(txt_pat.matches("some/path/to/hello.txt")); + assert!(txt_pat.matches("some\\path\\to\\hello.txt")); + assert!(txt_pat.matches("/an/absolute/path/to/hello.txt")); + assert!(!txt_pat.matches("hello.txt-and-then-some")); + assert!(!txt_pat.matches("goodbye.txt")); + + let dir_pat = Pattern::new("*some/path/to/hello.txt").unwrap(); + assert!(dir_pat.matches("some/path/to/hello.txt")); + assert!(dir_pat.matches("a/bigger/some/path/to/hello.txt")); + assert!(!dir_pat.matches("some/path/to/hello.txt-and-then-some")); + assert!(!dir_pat.matches("some/other/path/to/hello.txt")); + } + + #[test] + fn test_pattern_escape() { + let s = "_[_]_?_*_!_"; + assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_string()); + assert!(Pattern::new(&Pattern::escape(s)).unwrap().matches(s)); + } + + #[test] + fn test_pattern_matches_case_insensitive() { + + let pat = Pattern::new("aBcDeFg").unwrap(); + let options = MatchOptions { + case_sensitive: false, + require_literal_separator: false, + require_literal_leading_dot: false, + }; + + assert!(pat.matches_with("aBcDeFg", &options)); + assert!(pat.matches_with("abcdefg", &options)); + assert!(pat.matches_with("ABCDEFG", &options)); + assert!(pat.matches_with("AbCdEfG", &options)); + } + + #[test] + fn test_pattern_matches_case_insensitive_range() { + + let pat_within = Pattern::new("[a]").unwrap(); + let pat_except = Pattern::new("[!a]").unwrap(); + + let options_case_insensitive = MatchOptions { + case_sensitive: false, + require_literal_separator: false, + require_literal_leading_dot: false, + }; + let options_case_sensitive = MatchOptions { + case_sensitive: true, + require_literal_separator: false, + require_literal_leading_dot: false, + }; + + assert!(pat_within.matches_with("a", &options_case_insensitive)); + assert!(pat_within.matches_with("A", &options_case_insensitive)); + assert!(!pat_within.matches_with("A", &options_case_sensitive)); + + assert!(!pat_except.matches_with("a", &options_case_insensitive)); + assert!(!pat_except.matches_with("A", &options_case_insensitive)); + assert!(pat_except.matches_with("A", &options_case_sensitive)); + } + + #[test] + fn test_pattern_matches_require_literal_separator() { + + let options_require_literal = MatchOptions { + case_sensitive: true, + require_literal_separator: true, + require_literal_leading_dot: false, + }; + let options_not_require_literal = MatchOptions { + case_sensitive: true, + require_literal_separator: false, + require_literal_leading_dot: false, + }; + + assert!(Pattern::new("abc/def").unwrap().matches_with("abc/def", &options_require_literal)); + assert!(!Pattern::new("abc?def") + .unwrap() + .matches_with("abc/def", &options_require_literal)); + assert!(!Pattern::new("abc*def") + .unwrap() + .matches_with("abc/def", &options_require_literal)); + assert!(!Pattern::new("abc[/]def") + .unwrap() + .matches_with("abc/def", &options_require_literal)); + + assert!(Pattern::new("abc/def") + .unwrap() + .matches_with("abc/def", &options_not_require_literal)); + assert!(Pattern::new("abc?def") + .unwrap() + .matches_with("abc/def", &options_not_require_literal)); + assert!(Pattern::new("abc*def") + .unwrap() + .matches_with("abc/def", &options_not_require_literal)); + assert!(Pattern::new("abc[/]def") + .unwrap() + .matches_with("abc/def", &options_not_require_literal)); + } + + #[test] + fn test_pattern_matches_require_literal_leading_dot() { + + let options_require_literal_leading_dot = MatchOptions { + case_sensitive: true, + require_literal_separator: false, + require_literal_leading_dot: true, + }; + let options_not_require_literal_leading_dot = MatchOptions { + case_sensitive: true, + require_literal_separator: false, + require_literal_leading_dot: false, + }; + + let f = |options| Pattern::new("*.txt").unwrap().matches_with(".hello.txt", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(!f(&options_require_literal_leading_dot)); + + let f = |options| Pattern::new(".*.*").unwrap().matches_with(".hello.txt", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(f(&options_require_literal_leading_dot)); + + let f = |options| Pattern::new("aaa/bbb/*").unwrap().matches_with("aaa/bbb/.ccc", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(!f(&options_require_literal_leading_dot)); + + let f = |options| { + Pattern::new("aaa/bbb/*").unwrap().matches_with("aaa/bbb/c.c.c.", options) + }; + assert!(f(&options_not_require_literal_leading_dot)); + assert!(f(&options_require_literal_leading_dot)); + + let f = |options| Pattern::new("aaa/bbb/.*").unwrap().matches_with("aaa/bbb/.ccc", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(f(&options_require_literal_leading_dot)); + + let f = |options| Pattern::new("aaa/?bbb").unwrap().matches_with("aaa/.bbb", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(!f(&options_require_literal_leading_dot)); + + let f = |options| Pattern::new("aaa/[.]bbb").unwrap().matches_with("aaa/.bbb", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(!f(&options_require_literal_leading_dot)); + + let f = |options| Pattern::new("**/*").unwrap().matches_with(".bbb", options); + assert!(f(&options_not_require_literal_leading_dot)); + assert!(!f(&options_require_literal_leading_dot)); + } + + #[test] + fn test_matches_path() { + // on windows, (Path::new("a/b").as_str().unwrap() == "a\\b"), so this + // tests that / and \ are considered equivalent on windows + assert!(Pattern::new("a/b").unwrap().matches_path(&Path::new("a/b"))); + } + + #[test] + fn test_path_join() { + let pattern = Path::new("one").join(&Path::new("**/*.rs")); + assert!(Pattern::new(pattern.to_str().unwrap()).is_ok()); + } +} diff --git a/bash-5.1/vendor/glob/tests/glob-std.rs b/bash-5.1/vendor/glob/tests/glob-std.rs new file mode 100644 index 0000000..c426418 --- /dev/null +++ b/bash-5.1/vendor/glob/tests/glob-std.rs @@ -0,0 +1,278 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// ignore-windows TempDir may cause IoError on windows: #10462 + +#![cfg_attr(test, deny(warnings))] + +extern crate glob; +extern crate tempdir; + +use glob::glob; +use std::env; +use std::path::PathBuf; +use std::fs; +use tempdir::TempDir; + +#[test] +fn main() { + fn mk_file(path: &str, directory: bool) { + if directory { + fs::create_dir(path).unwrap(); + } else { + fs::File::create(path).unwrap(); + } + } + + fn glob_vec(pattern: &str) -> Vec { + glob(pattern).unwrap().map(|r| r.unwrap()).collect() + } + + let root = TempDir::new("glob-tests"); + let root = root.ok().expect("Should have created a temp directory"); + assert!(env::set_current_dir(root.path()).is_ok()); + + mk_file("aaa", true); + mk_file("aaa/apple", true); + mk_file("aaa/orange", true); + mk_file("aaa/tomato", true); + mk_file("aaa/tomato/tomato.txt", false); + mk_file("aaa/tomato/tomoto.txt", false); + mk_file("bbb", true); + mk_file("bbb/specials", true); + mk_file("bbb/specials/!", false); + + // windows does not allow `*` or `?` characters to exist in filenames + if env::consts::FAMILY != "windows" { + mk_file("bbb/specials/*", false); + mk_file("bbb/specials/?", false); + } + + mk_file("bbb/specials/[", false); + mk_file("bbb/specials/]", false); + mk_file("ccc", true); + mk_file("xyz", true); + mk_file("xyz/x", false); + mk_file("xyz/y", false); + mk_file("xyz/z", false); + + mk_file("r", true); + mk_file("r/current_dir.md", false); + mk_file("r/one", true); + mk_file("r/one/a.md", false); + mk_file("r/one/another", true); + mk_file("r/one/another/a.md", false); + mk_file("r/one/another/deep", true); + mk_file("r/one/another/deep/spelunking.md", false); + mk_file("r/another", true); + mk_file("r/another/a.md", false); + mk_file("r/two", true); + mk_file("r/two/b.md", false); + mk_file("r/three", true); + mk_file("r/three/c.md", false); + + // all recursive entities + assert_eq!(glob_vec("r/**"), vec!( + PathBuf::from("r/another"), + PathBuf::from("r/one"), + PathBuf::from("r/one/another"), + PathBuf::from("r/one/another/deep"), + PathBuf::from("r/three"), + PathBuf::from("r/two"))); + + // collapse consecutive recursive patterns + assert_eq!(glob_vec("r/**/**"), vec!( + PathBuf::from("r/another"), + PathBuf::from("r/one"), + PathBuf::from("r/one/another"), + PathBuf::from("r/one/another/deep"), + PathBuf::from("r/three"), + PathBuf::from("r/two"))); + + assert_eq!(glob_vec("r/**/*"), vec!( + PathBuf::from("r/another"), + PathBuf::from("r/another/a.md"), + PathBuf::from("r/current_dir.md"), + PathBuf::from("r/one"), + PathBuf::from("r/one/a.md"), + PathBuf::from("r/one/another"), + PathBuf::from("r/one/another/a.md"), + PathBuf::from("r/one/another/deep"), + PathBuf::from("r/one/another/deep/spelunking.md"), + PathBuf::from("r/three"), + PathBuf::from("r/three/c.md"), + PathBuf::from("r/two"), + PathBuf::from("r/two/b.md"))); + + // followed by a wildcard + assert_eq!(glob_vec("r/**/*.md"), vec!( + PathBuf::from("r/another/a.md"), + PathBuf::from("r/current_dir.md"), + PathBuf::from("r/one/a.md"), + PathBuf::from("r/one/another/a.md"), + PathBuf::from("r/one/another/deep/spelunking.md"), + PathBuf::from("r/three/c.md"), + PathBuf::from("r/two/b.md"))); + + // followed by a precise pattern + assert_eq!(glob_vec("r/one/**/a.md"), vec!( + PathBuf::from("r/one/a.md"), + PathBuf::from("r/one/another/a.md"))); + + // followed by another recursive pattern + // collapses consecutive recursives into one + assert_eq!(glob_vec("r/one/**/**/a.md"), vec!( + PathBuf::from("r/one/a.md"), + PathBuf::from("r/one/another/a.md"))); + + // followed by two precise patterns + assert_eq!(glob_vec("r/**/another/a.md"), vec!( + PathBuf::from("r/another/a.md"), + PathBuf::from("r/one/another/a.md"))); + + assert_eq!(glob_vec(""), Vec::::new()); + assert_eq!(glob_vec("."), vec!(PathBuf::from("."))); + assert_eq!(glob_vec(".."), vec!(PathBuf::from(".."))); + + assert_eq!(glob_vec("aaa"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aaa/"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("a"), Vec::::new()); + assert_eq!(glob_vec("aa"), Vec::::new()); + assert_eq!(glob_vec("aaaa"), Vec::::new()); + + assert_eq!(glob_vec("aaa/apple"), vec!(PathBuf::from("aaa/apple"))); + assert_eq!(glob_vec("aaa/apple/nope"), Vec::::new()); + + // windows should support both / and \ as directory separators + if env::consts::FAMILY == "windows" { + assert_eq!(glob_vec("aaa\\apple"), vec!(PathBuf::from("aaa/apple"))); + } + + assert_eq!(glob_vec("???/"), vec!( + PathBuf::from("aaa"), + PathBuf::from("bbb"), + PathBuf::from("ccc"), + PathBuf::from("xyz"))); + + assert_eq!(glob_vec("aaa/tomato/tom?to.txt"), vec!( + PathBuf::from("aaa/tomato/tomato.txt"), + PathBuf::from("aaa/tomato/tomoto.txt"))); + + assert_eq!(glob_vec("xyz/?"), vec!( + PathBuf::from("xyz/x"), + PathBuf::from("xyz/y"), + PathBuf::from("xyz/z"))); + + assert_eq!(glob_vec("a*"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("*a*"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("a*a"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aaa*"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("*aaa"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("*aaa*"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("*a*a*a*"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aaa*/"), vec!(PathBuf::from("aaa"))); + + assert_eq!(glob_vec("aaa/*"), vec!( + PathBuf::from("aaa/apple"), + PathBuf::from("aaa/orange"), + PathBuf::from("aaa/tomato"))); + + assert_eq!(glob_vec("aaa/*a*"), vec!( + PathBuf::from("aaa/apple"), + PathBuf::from("aaa/orange"), + PathBuf::from("aaa/tomato"))); + + assert_eq!(glob_vec("*/*/*.txt"), vec!( + PathBuf::from("aaa/tomato/tomato.txt"), + PathBuf::from("aaa/tomato/tomoto.txt"))); + + assert_eq!(glob_vec("*/*/t[aob]m?to[.]t[!y]t"), vec!( + PathBuf::from("aaa/tomato/tomato.txt"), + PathBuf::from("aaa/tomato/tomoto.txt"))); + + assert_eq!(glob_vec("./aaa"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("./*"), glob_vec("*")); + assert_eq!(glob_vec("*/..").pop().unwrap(), PathBuf::from("xyz/..")); + assert_eq!(glob_vec("aaa/../bbb"), vec!(PathBuf::from("aaa/../bbb"))); + assert_eq!(glob_vec("nonexistent/../bbb"), Vec::::new()); + assert_eq!(glob_vec("aaa/tomato/tomato.txt/.."), Vec::::new()); + + assert_eq!(glob_vec("aaa/tomato/tomato.txt/"), Vec::::new()); + + assert_eq!(glob_vec("aa[a]"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aa[abc]"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("a[bca]a"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aa[b]"), Vec::::new()); + assert_eq!(glob_vec("aa[xyz]"), Vec::::new()); + assert_eq!(glob_vec("aa[]]"), Vec::::new()); + + assert_eq!(glob_vec("aa[!b]"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aa[!bcd]"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("a[!bcd]a"), vec!(PathBuf::from("aaa"))); + assert_eq!(glob_vec("aa[!a]"), Vec::::new()); + assert_eq!(glob_vec("aa[!abc]"), Vec::::new()); + + assert_eq!(glob_vec("bbb/specials/[[]"), vec!(PathBuf::from("bbb/specials/["))); + assert_eq!(glob_vec("bbb/specials/!"), vec!(PathBuf::from("bbb/specials/!"))); + assert_eq!(glob_vec("bbb/specials/[]]"), vec!(PathBuf::from("bbb/specials/]"))); + + if env::consts::FAMILY != "windows" { + assert_eq!(glob_vec("bbb/specials/[*]"), vec!(PathBuf::from("bbb/specials/*"))); + assert_eq!(glob_vec("bbb/specials/[?]"), vec!(PathBuf::from("bbb/specials/?"))); + } + + if env::consts::FAMILY == "windows" { + + assert_eq!(glob_vec("bbb/specials/[![]"), vec!( + PathBuf::from("bbb/specials/!"), + PathBuf::from("bbb/specials/]"))); + + assert_eq!(glob_vec("bbb/specials/[!]]"), vec!( + PathBuf::from("bbb/specials/!"), + PathBuf::from("bbb/specials/["))); + + assert_eq!(glob_vec("bbb/specials/[!!]"), vec!( + PathBuf::from("bbb/specials/["), + PathBuf::from("bbb/specials/]"))); + + } else { + + assert_eq!(glob_vec("bbb/specials/[![]"), vec!( + PathBuf::from("bbb/specials/!"), + PathBuf::from("bbb/specials/*"), + PathBuf::from("bbb/specials/?"), + PathBuf::from("bbb/specials/]"))); + + assert_eq!(glob_vec("bbb/specials/[!]]"), vec!( + PathBuf::from("bbb/specials/!"), + PathBuf::from("bbb/specials/*"), + PathBuf::from("bbb/specials/?"), + PathBuf::from("bbb/specials/["))); + + assert_eq!(glob_vec("bbb/specials/[!!]"), vec!( + PathBuf::from("bbb/specials/*"), + PathBuf::from("bbb/specials/?"), + PathBuf::from("bbb/specials/["), + PathBuf::from("bbb/specials/]"))); + + assert_eq!(glob_vec("bbb/specials/[!*]"), vec!( + PathBuf::from("bbb/specials/!"), + PathBuf::from("bbb/specials/?"), + PathBuf::from("bbb/specials/["), + PathBuf::from("bbb/specials/]"))); + + assert_eq!(glob_vec("bbb/specials/[!?]"), vec!( + PathBuf::from("bbb/specials/!"), + PathBuf::from("bbb/specials/*"), + PathBuf::from("bbb/specials/["), + PathBuf::from("bbb/specials/]"))); + + } +} diff --git a/bash-5.1/vendor/hermit-abi/.cargo-checksum.json b/bash-5.1/vendor/hermit-abi/.cargo-checksum.json new file mode 100644 index 0000000..ea99879 --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"023c46a92caf2fc7a31fba3e7d4428a287e1fbdef822ed7e9a8f91284a30b387","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"322fadd63e558e5a10caf980cbedf83ac1546ba40fd992f54492e21ce54205af","rust-toolchain":"58bea07cb6d97f9cfcd5c8f98b1feca0fb81cce5b0bf29a8e70ed2641956e9a6","src/lib.rs":"c7dca30b651c91590ff46370bdaa10214062b9456395fb4bd549dedbf457c695","src/tcplistener.rs":"c6e2db06d4265fa0956851e1c965336d60c53ab21573729aae76ecfe0ccc84c3","src/tcpstream.rs":"38a17de54213faf9de217f6146ff86ee75b67d4404a532b1419903269200936b"},"package":"62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"} \ No newline at end of file diff --git a/bash-5.1/vendor/hermit-abi/Cargo.toml b/bash-5.1/vendor/hermit-abi/Cargo.toml new file mode 100644 index 0000000..1f24268 --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/Cargo.toml @@ -0,0 +1,44 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "hermit-abi" +version = "0.1.19" +authors = ["Stefan Lankes"] +description = "hermit-abi is small interface to call functions from the unikernel RustyHermit.\nIt is used to build the target `x86_64-unknown-hermit`.\n" +documentation = "https://hermitcore.github.io/rusty-hermit/hermit_abi" +readme = "README.md" +keywords = ["unikernel", "libos"] +categories = ["os"] +license = "MIT/Apache-2.0" +repository = "https://github.com/hermitcore/libhermit-rs" +[package.metadata.docs.rs] +default-target = "x86_64-unknown-hermit" +features = ["docs"] +[dependencies.compiler_builtins] +version = "0.1" +optional = true + +[dependencies.core] +version = "1.0.0" +optional = true +package = "rustc-std-workspace-core" + +[dependencies.libc] +version = "0.2.51" +default-features = false + +[features] +default = [] +docs = [] +rustc-dep-of-std = ["core", "compiler_builtins/rustc-dep-of-std", "libc/rustc-dep-of-std"] diff --git a/bash-5.1/vendor/hermit-abi/LICENSE-APACHE b/bash-5.1/vendor/hermit-abi/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/hermit-abi/LICENSE-MIT b/bash-5.1/vendor/hermit-abi/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/hermit-abi/README.md b/bash-5.1/vendor/hermit-abi/README.md new file mode 100644 index 0000000..c75bfda --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/README.md @@ -0,0 +1,22 @@ +# hermit-abi + +[![Crates.io](https://img.shields.io/crates/v/hermit-abi.svg)](https://crates.io/crates/hermit-abi) +[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://hermitcore.github.io/rusty-hermit/hermit_abi/) +[![License](https://img.shields.io/crates/l/hermit-abi.svg)](https://img.shields.io/crates/l/hermit-abi.svg) + +This is small interface to call functions from the unikernel [RustyHermit](https://github.com/hermitcore/libhermit-rs). + +Please read the README of [RustyHermit](https://github.com/hermitcore/libhermit-rs) for more information. + +## License + +Licensed under either of + +* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. diff --git a/bash-5.1/vendor/hermit-abi/rust-toolchain b/bash-5.1/vendor/hermit-abi/rust-toolchain new file mode 100644 index 0000000..bf867e0 --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/rust-toolchain @@ -0,0 +1 @@ +nightly diff --git a/bash-5.1/vendor/hermit-abi/src/lib.rs b/bash-5.1/vendor/hermit-abi/src/lib.rs new file mode 100644 index 0000000..9151faf --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/src/lib.rs @@ -0,0 +1,490 @@ +//! `hermit-abi` is small interface to call functions from the unikernel +//! [RustyHermit](https://github.com/hermitcore/libhermit-rs). + +#![no_std] +#![allow(clippy::missing_safety_doc)] +#![allow(clippy::result_unit_err)] + +extern crate libc; + +pub mod tcplistener; +pub mod tcpstream; + +use libc::c_void; + +// sysmbols, which are part of the library operating system + +extern "Rust" { + fn sys_secure_rand64() -> Option; + fn sys_secure_rand32() -> Option; +} + +extern "C" { + fn sys_rand() -> u32; + fn sys_srand(seed: u32); + fn sys_get_processor_count() -> usize; + fn sys_malloc(size: usize, align: usize) -> *mut u8; + fn sys_realloc(ptr: *mut u8, size: usize, align: usize, new_size: usize) -> *mut u8; + fn sys_free(ptr: *mut u8, size: usize, align: usize); + fn sys_init_queue(ptr: usize) -> i32; + fn sys_notify(id: usize, count: i32) -> i32; + fn sys_add_queue(id: usize, timeout_ns: i64) -> i32; + fn sys_wait(id: usize) -> i32; + fn sys_destroy_queue(id: usize) -> i32; + fn sys_read(fd: i32, buf: *mut u8, len: usize) -> isize; + fn sys_write(fd: i32, buf: *const u8, len: usize) -> isize; + fn sys_close(fd: i32) -> i32; + fn sys_sem_init(sem: *mut *const c_void, value: u32) -> i32; + fn sys_sem_destroy(sem: *const c_void) -> i32; + fn sys_sem_post(sem: *const c_void) -> i32; + fn sys_sem_trywait(sem: *const c_void) -> i32; + fn sys_sem_timedwait(sem: *const c_void, ms: u32) -> i32; + fn sys_recmutex_init(recmutex: *mut *const c_void) -> i32; + fn sys_recmutex_destroy(recmutex: *const c_void) -> i32; + fn sys_recmutex_lock(recmutex: *const c_void) -> i32; + fn sys_recmutex_unlock(recmutex: *const c_void) -> i32; + fn sys_getpid() -> u32; + fn sys_exit(arg: i32) -> !; + fn sys_abort() -> !; + fn sys_usleep(usecs: u64); + fn sys_spawn( + id: *mut Tid, + func: extern "C" fn(usize), + arg: usize, + prio: u8, + core_id: isize, + ) -> i32; + fn sys_spawn2( + func: extern "C" fn(usize), + arg: usize, + prio: u8, + stack_size: usize, + core_id: isize, + ) -> Tid; + fn sys_join(id: Tid) -> i32; + fn sys_yield(); + fn sys_clock_gettime(clock_id: u64, tp: *mut timespec) -> i32; + fn sys_open(name: *const i8, flags: i32, mode: i32) -> i32; + fn sys_unlink(name: *const i8) -> i32; + fn sys_network_init() -> i32; + fn sys_block_current_task(); + fn sys_wakeup_task(tid: Tid); + fn sys_get_priority() -> u8; +} + +/// A thread handle type +pub type Tid = u32; + +/// Maximum number of priorities +pub const NO_PRIORITIES: usize = 31; + +/// Priority of a thread +#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)] +pub struct Priority(u8); + +impl Priority { + pub const fn into(self) -> u8 { + self.0 + } + + pub const fn from(x: u8) -> Self { + Priority(x) + } +} + +pub const HIGH_PRIO: Priority = Priority::from(3); +pub const NORMAL_PRIO: Priority = Priority::from(2); +pub const LOW_PRIO: Priority = Priority::from(1); + +/// A handle, identifying a socket +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] +pub struct Handle(usize); + +pub const NSEC_PER_SEC: u64 = 1_000_000_000; +pub const CLOCK_REALTIME: u64 = 1; +pub const CLOCK_MONOTONIC: u64 = 4; +pub const STDIN_FILENO: libc::c_int = 0; +pub const STDOUT_FILENO: libc::c_int = 1; +pub const STDERR_FILENO: libc::c_int = 2; +pub const O_RDONLY: i32 = 0o0; +pub const O_WRONLY: i32 = 0o1; +pub const O_RDWR: i32 = 0o2; +pub const O_CREAT: i32 = 0o100; +pub const O_EXCL: i32 = 0o200; +pub const O_TRUNC: i32 = 0o1000; +pub const O_APPEND: i32 = 0o2000; + +/// returns true if file descriptor `fd` is a tty +pub fn isatty(_fd: libc::c_int) -> bool { + false +} + +/// intialize the network stack +pub fn network_init() -> i32 { + unsafe { sys_network_init() } +} + +/// `timespec` is used by `clock_gettime` to retrieve the +/// current time +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct timespec { + /// seconds + pub tv_sec: i64, + /// nanoseconds + pub tv_nsec: i64, +} + +/// Internet protocol version. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +pub enum Version { + Unspecified, + Ipv4, + Ipv6, +} + +/// A four-octet IPv4 address. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)] +pub struct Ipv4Address(pub [u8; 4]); + +/// A sixteen-octet IPv6 address. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)] +pub struct Ipv6Address(pub [u8; 16]); + +/// An internetworking address. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +pub enum IpAddress { + /// An unspecified address. + /// May be used as a placeholder for storage where the address is not assigned yet. + Unspecified, + /// An IPv4 address. + Ipv4(Ipv4Address), + /// An IPv6 address. + Ipv6(Ipv6Address), +} + +/// determines the number of activated processors +#[inline(always)] +pub unsafe fn get_processor_count() -> usize { + sys_get_processor_count() +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn malloc(size: usize, align: usize) -> *mut u8 { + sys_malloc(size, align) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn realloc(ptr: *mut u8, size: usize, align: usize, new_size: usize) -> *mut u8 { + sys_realloc(ptr, size, align, new_size) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn free(ptr: *mut u8, size: usize, align: usize) { + sys_free(ptr, size, align) +} + +#[inline(always)] +pub unsafe fn notify(id: usize, count: i32) -> i32 { + sys_notify(id, count) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn add_queue(id: usize, timeout_ns: i64) -> i32 { + sys_add_queue(id, timeout_ns) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn wait(id: usize) -> i32 { + sys_wait(id) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn init_queue(id: usize) -> i32 { + sys_init_queue(id) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn destroy_queue(id: usize) -> i32 { + sys_destroy_queue(id) +} + +/// read from a file descriptor +/// +/// read() attempts to read `len` bytes of data from the object +/// referenced by the descriptor `fd` into the buffer pointed +/// to by `buf`. +#[inline(always)] +pub unsafe fn read(fd: i32, buf: *mut u8, len: usize) -> isize { + sys_read(fd, buf, len) +} + +/// write to a file descriptor +/// +/// write() attempts to write `len` of data to the object +/// referenced by the descriptor `fd` from the +/// buffer pointed to by `buf`. +#[inline(always)] +pub unsafe fn write(fd: i32, buf: *const u8, len: usize) -> isize { + sys_write(fd, buf, len) +} + +/// close a file descriptor +/// +/// The close() call deletes a file descriptor `fd` from the object +/// reference table. +#[inline(always)] +pub unsafe fn close(fd: i32) -> i32 { + sys_close(fd) +} + +/// sem_init() initializes the unnamed semaphore at the address +/// pointed to by `sem`. The `value` argument specifies the +/// initial value for the semaphore. +#[inline(always)] +pub unsafe fn sem_init(sem: *mut *const c_void, value: u32) -> i32 { + sys_sem_init(sem, value) +} + +/// sem_destroy() frees the unnamed semaphore at the address +/// pointed to by `sem`. +#[inline(always)] +pub unsafe fn sem_destroy(sem: *const c_void) -> i32 { + sys_sem_destroy(sem) +} + +/// sem_post() increments the semaphore pointed to by `sem`. +/// If the semaphore's value consequently becomes greater +/// than zero, then another thread blocked in a sem_wait call +/// will be woken up and proceed to lock the semaphore. +#[inline(always)] +pub unsafe fn sem_post(sem: *const c_void) -> i32 { + sys_sem_post(sem) +} + +/// try to decrement a semaphore +/// +/// sem_trywait() is the same as sem_timedwait(), except that +/// if the decrement cannot be immediately performed, then call +/// returns a negative value instead of blocking. +#[inline(always)] +pub unsafe fn sem_trywait(sem: *const c_void) -> i32 { + sys_sem_trywait(sem) +} + +/// decrement a semaphore +/// +/// sem_timedwait() decrements the semaphore pointed to by `sem`. +/// If the semaphore's value is greater than zero, then the +/// the function returns immediately. If the semaphore currently +/// has the value zero, then the call blocks until either +/// it becomes possible to perform the decrement of the time limit +/// to wait for the semaphore is expired. A time limit `ms` of +/// means infinity waiting time. +#[inline(always)] +pub unsafe fn sem_timedwait(sem: *const c_void, ms: u32) -> i32 { + sys_sem_timedwait(sem, ms) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn recmutex_init(recmutex: *mut *const c_void) -> i32 { + sys_recmutex_init(recmutex) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn recmutex_destroy(recmutex: *const c_void) -> i32 { + sys_recmutex_destroy(recmutex) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn recmutex_lock(recmutex: *const c_void) -> i32 { + sys_recmutex_lock(recmutex) +} + +#[doc(hidden)] +#[inline(always)] +pub unsafe fn recmutex_unlock(recmutex: *const c_void) -> i32 { + sys_recmutex_unlock(recmutex) +} + +/// Determines the id of the current thread +#[inline(always)] +pub unsafe fn getpid() -> u32 { + sys_getpid() +} + +/// cause normal termination and return `arg` +/// to the host system +#[inline(always)] +pub unsafe fn exit(arg: i32) -> ! { + sys_exit(arg) +} + +/// cause abnormal termination +#[inline(always)] +pub unsafe fn abort() -> ! { + sys_abort() +} + +/// suspend execution for microsecond intervals +/// +/// The usleep() function suspends execution of the calling +/// thread for (at least) `usecs` microseconds. +#[inline(always)] +pub unsafe fn usleep(usecs: u64) { + sys_usleep(usecs) +} + +/// spawn a new thread +/// +/// spawn() starts a new thread. The new thread starts execution +/// by invoking `func(usize)`; `arg` is passed as the argument +/// to `func`. `prio` defines the priority of the new thread, +/// which can be between `LOW_PRIO` and `HIGH_PRIO`. +/// `core_id` defines the core, where the thread is located. +/// A negative value give the operating system the possibility +/// to select the core by its own. +#[inline(always)] +pub unsafe fn spawn( + id: *mut Tid, + func: extern "C" fn(usize), + arg: usize, + prio: u8, + core_id: isize, +) -> i32 { + sys_spawn(id, func, arg, prio, core_id) +} + +/// spawn a new thread with user-specified stack size +/// +/// spawn2() starts a new thread. The new thread starts execution +/// by invoking `func(usize)`; `arg` is passed as the argument +/// to `func`. `prio` defines the priority of the new thread, +/// which can be between `LOW_PRIO` and `HIGH_PRIO`. +/// `core_id` defines the core, where the thread is located. +/// A negative value give the operating system the possibility +/// to select the core by its own. +/// In contrast to spawn(), spawn2() is able to define the +/// stack size. +#[inline(always)] +pub unsafe fn spawn2( + func: extern "C" fn(usize), + arg: usize, + prio: u8, + stack_size: usize, + core_id: isize, +) -> Tid { + sys_spawn2(func, arg, prio, stack_size, core_id) +} + +/// join with a terminated thread +/// +/// The join() function waits for the thread specified by `id` +/// to terminate. +#[inline(always)] +pub unsafe fn join(id: Tid) -> i32 { + sys_join(id) +} + +/// yield the processor +/// +/// causes the calling thread to relinquish the CPU. The thread +/// is moved to the end of the queue for its static priority. +#[inline(always)] +pub unsafe fn yield_now() { + sys_yield() +} + +/// get current time +/// +/// The clock_gettime() functions allow the calling thread +/// to retrieve the value used by a clock which is specified +/// by `clock_id`. +/// +/// `CLOCK_REALTIME`: the system's real time clock, +/// expressed as the amount of time since the Epoch. +/// +/// `CLOCK_MONOTONIC`: clock that increments monotonically, +/// tracking the time since an arbitrary point +#[inline(always)] +pub unsafe fn clock_gettime(clock_id: u64, tp: *mut timespec) -> i32 { + sys_clock_gettime(clock_id, tp) +} + +/// open and possibly create a file +/// +/// The open() system call opens the file specified by `name`. +/// If the specified file does not exist, it may optionally +/// be created by open(). +#[inline(always)] +pub unsafe fn open(name: *const i8, flags: i32, mode: i32) -> i32 { + sys_open(name, flags, mode) +} + +/// delete the file it refers to `name` +#[inline(always)] +pub unsafe fn unlink(name: *const i8) -> i32 { + sys_unlink(name) +} + +/// The largest number `rand` will return +pub const RAND_MAX: u64 = 2_147_483_647; + +/// The function computes a sequence of pseudo-random integers +/// in the range of 0 to RAND_MAX +#[inline(always)] +pub unsafe fn rand() -> u32 { + sys_rand() +} + +/// The function sets its argument as the seed for a new sequence +/// of pseudo-random numbers to be returned by `rand` +#[inline(always)] +pub unsafe fn srand(seed: u32) { + sys_srand(seed); +} + +/// Create a cryptographicly secure 32bit random number with the support of +/// the underlying hardware. If the required hardware isn't available, +/// the function returns `None`. +#[inline(always)] +pub unsafe fn secure_rand32() -> Option { + sys_secure_rand32() +} + +/// Create a cryptographicly secure 64bit random number with the support of +/// the underlying hardware. If the required hardware isn't available, +/// the function returns `None`. +#[inline(always)] +pub unsafe fn secure_rand64() -> Option { + sys_secure_rand64() +} + +/// Add current task to the queue of blocked tasl. After calling `block_current_task`, +/// call `yield_now` to switch to another task. +#[inline(always)] +pub unsafe fn block_current_task() { + sys_block_current_task(); +} + +/// Wakeup task with the thread id `tid` +#[inline(always)] +pub unsafe fn wakeup_task(tid: Tid) { + sys_wakeup_task(tid); +} + +/// Determine the priority of the current thread +#[inline(always)] +pub unsafe fn get_priority() -> Priority { + Priority::from(sys_get_priority()) +} diff --git a/bash-5.1/vendor/hermit-abi/src/tcplistener.rs b/bash-5.1/vendor/hermit-abi/src/tcplistener.rs new file mode 100644 index 0000000..5afe673 --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/src/tcplistener.rs @@ -0,0 +1,13 @@ +//! `tcplistener` provide an interface to establish tcp socket server. + +use crate::{Handle, IpAddress}; + +extern "Rust" { + fn sys_tcp_listener_accept(port: u16) -> Result<(Handle, IpAddress, u16), ()>; +} + +/// Wait for connection at specified address. +#[inline(always)] +pub fn accept(port: u16) -> Result<(Handle, IpAddress, u16), ()> { + unsafe { sys_tcp_listener_accept(port) } +} diff --git a/bash-5.1/vendor/hermit-abi/src/tcpstream.rs b/bash-5.1/vendor/hermit-abi/src/tcpstream.rs new file mode 100644 index 0000000..3024d37 --- /dev/null +++ b/bash-5.1/vendor/hermit-abi/src/tcpstream.rs @@ -0,0 +1,109 @@ +//! `tcpstream` provide an interface to establish tcp socket client. + +use crate::{Handle, IpAddress}; + +extern "Rust" { + fn sys_tcp_stream_connect(ip: &[u8], port: u16, timeout: Option) -> Result; + fn sys_tcp_stream_close(handle: Handle) -> Result<(), ()>; + fn sys_tcp_stream_read(handle: Handle, buffer: &mut [u8]) -> Result; + fn sys_tcp_stream_write(handle: Handle, buffer: &[u8]) -> Result; + fn sys_tcp_stream_set_read_timeout(handle: Handle, timeout: Option) -> Result<(), ()>; + fn sys_tcp_stream_get_read_timeout(handle: Handle) -> Result, ()>; + fn sys_tcp_stream_set_write_timeout(handle: Handle, timeout: Option) -> Result<(), ()>; + fn sys_tcp_stream_get_write_timeout(handle: Handle) -> Result, ()>; + fn sys_tcp_stream_peek(handle: Handle, buf: &mut [u8]) -> Result; + fn sys_tcp_stream_set_nonblocking(handle: Handle, mode: bool) -> Result<(), ()>; + fn sys_tcp_stream_set_tll(handle: Handle, ttl: u32) -> Result<(), ()>; + fn sys_tcp_stream_get_tll(handle: Handle) -> Result; + fn sys_tcp_stream_shutdown(handle: Handle, how: i32) -> Result<(), ()>; + fn sys_tcp_stream_peer_addr(handle: Handle) -> Result<(IpAddress, u16), ()>; +} + +/// Opens a TCP connection to a remote host. +#[inline(always)] +pub fn connect(ip: &[u8], port: u16, timeout: Option) -> Result { + unsafe { sys_tcp_stream_connect(ip, port, timeout) } +} + +/// Close a TCP connection +#[inline(always)] +pub fn close(handle: Handle) -> Result<(), ()> { + unsafe { sys_tcp_stream_close(handle) } +} + +#[inline(always)] +pub fn peek(handle: Handle, buf: &mut [u8]) -> Result { + unsafe { sys_tcp_stream_peek(handle, buf) } +} + +#[inline(always)] +pub fn peer_addr(handle: Handle) -> Result<(IpAddress, u16), ()> { + unsafe { sys_tcp_stream_peer_addr(handle) } +} +#[inline(always)] +pub fn read(handle: Handle, buffer: &mut [u8]) -> Result { + unsafe { sys_tcp_stream_read(handle, buffer) } +} + +#[inline(always)] +pub fn write(handle: Handle, buffer: &[u8]) -> Result { + unsafe { sys_tcp_stream_write(handle, buffer) } +} + +#[inline(always)] +pub fn set_read_timeout(handle: Handle, timeout: Option) -> Result<(), ()> { + unsafe { sys_tcp_stream_set_read_timeout(handle, timeout) } +} + +#[inline(always)] +pub fn set_write_timeout(handle: Handle, timeout: Option) -> Result<(), ()> { + unsafe { sys_tcp_stream_set_write_timeout(handle, timeout) } +} + +#[inline(always)] +pub fn get_read_timeout(handle: Handle) -> Result, ()> { + unsafe { sys_tcp_stream_get_read_timeout(handle) } +} + +#[inline(always)] +pub fn get_write_timeout(handle: Handle) -> Result, ()> { + unsafe { sys_tcp_stream_get_write_timeout(handle) } +} + +#[inline(always)] +pub fn set_nodelay(_: Handle, mode: bool) -> Result<(), ()> { + // smoltcp does not support Nagle's algorithm + // => to enable Nagle's algorithm isn't possible + if mode { + Ok(()) + } else { + Err(()) + } +} + +#[inline(always)] +pub fn nodelay(_: Handle) -> Result { + // smoltcp does not support Nagle's algorithm + // => return always true + Ok(true) +} + +#[inline(always)] +pub fn set_nonblocking(handle: Handle, mode: bool) -> Result<(), ()> { + unsafe { sys_tcp_stream_set_nonblocking(handle, mode) } +} + +#[inline(always)] +pub fn set_tll(handle: Handle, ttl: u32) -> Result<(), ()> { + unsafe { sys_tcp_stream_set_tll(handle, ttl) } +} + +#[inline(always)] +pub fn get_tll(handle: Handle) -> Result { + unsafe { sys_tcp_stream_get_tll(handle) } +} + +#[inline(always)] +pub fn shutdown(handle: Handle, how: i32) -> Result<(), ()> { + unsafe { sys_tcp_stream_shutdown(handle, how) } +} diff --git a/bash-5.1/vendor/itoa/.cargo-checksum.json b/bash-5.1/vendor/itoa/.cargo-checksum.json new file mode 100644 index 0000000..094627a --- /dev/null +++ b/bash-5.1/vendor/itoa/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"f15208d08be5a846e9c39390cec838d3023be8b77b49ccdc1259bd615cb10ea7","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"e18259ab3aa7f39a194795bdad8039b3c5fd544f6dd922526c9326c44842b76d","README.md":"610fb3fbc82edf79762a85d5ec0b324db34c92b0e44dd6003f06a95aad23339d","benches/bench.rs":"23d604664f083f95220a082a926dc6ca782c1f913d0a70073b4a064aef94750d","src/lib.rs":"b8b5a562a03ed4667ce7de0e0fcc3caa36853bae4f413a690e45654992d023bf","src/udiv128.rs":"92734d7475f1a250a739daf4b69d5e6f7efcc5c9710aebe186d5406c8f2720e2","tests/test.rs":"b64b62c964d6985d1a482abd26ab75609d0673336e483f7755a79ca83e891021"},"package":"8324a32baf01e2ae060e9de58ed0bc2320c9a2833491ee36cd3b4c414de4db8c"} \ No newline at end of file diff --git a/bash-5.1/vendor/itoa/Cargo.toml b/bash-5.1/vendor/itoa/Cargo.toml new file mode 100644 index 0000000..00b16c4 --- /dev/null +++ b/bash-5.1/vendor/itoa/Cargo.toml @@ -0,0 +1,26 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "itoa" +version = "0.3.4" +authors = ["David Tolnay "] +exclude = ["performance.png"] +description = "Fast functions for printing integer primitives to an io::Write" +documentation = "https://github.com/dtolnay/itoa" +readme = "README.md" +categories = ["value-formatting"] +license = "MIT/Apache-2.0" +repository = "https://github.com/dtolnay/itoa" + +[features] +i128 = [] diff --git a/bash-5.1/vendor/itoa/LICENSE-APACHE b/bash-5.1/vendor/itoa/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/itoa/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/itoa/LICENSE-MIT b/bash-5.1/vendor/itoa/LICENSE-MIT new file mode 100644 index 0000000..d1c35df --- /dev/null +++ b/bash-5.1/vendor/itoa/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Itoa Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/itoa/README.md b/bash-5.1/vendor/itoa/README.md new file mode 100644 index 0000000..524957b --- /dev/null +++ b/bash-5.1/vendor/itoa/README.md @@ -0,0 +1,71 @@ +itoa +==== + +[![Build Status](https://api.travis-ci.org/dtolnay/itoa.svg?branch=master)](https://travis-ci.org/dtolnay/itoa) +[![Latest Version](https://img.shields.io/crates/v/itoa.svg)](https://crates.io/crates/itoa) + +This crate provides fast functions for printing integer primitives to an +[`io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html). The +implementation comes straight from +[libcore](https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254) +but avoids the performance penalty of going through +[`fmt::Formatter`](https://doc.rust-lang.org/std/fmt/struct.Formatter.html). + +See also [`dtoa`](https://github.com/dtolnay/dtoa) for printing floating point +primitives. + +## Performance (lower is better) + +![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png) + +## Functions + +```rust +extern crate itoa; + +// write to a vector or other io::Write +let mut buf = Vec::new(); +itoa::write(&mut buf, 128u64)?; +println!("{:?}", buf); + +// write to a stack buffer +let mut bytes = [b'\0'; 20]; +let n = itoa::write(&mut bytes[..], 128u64)?; +println!("{:?}", &bytes[..n]); +``` + +The function signature is: + +```rust +fn write(writer: W, value: V) -> io::Result +``` + +where `itoa::Integer` is implemented for `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, +`i64`, `u64`, `i128`, `u128`, `isize` and `usize`. 128-bit integer support is +only available with the nightly compiler when the `i128` feature is enabled for +this crate. The return value gives the number of bytes written. + +## Dependency + +Itoa is available on [crates.io](https://crates.io/crates/itoa). Use the +following in `Cargo.toml`: + +```toml +[dependencies] +itoa = "0.3" +``` + +## License + +Licensed under either of + + * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in itoa by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bash-5.1/vendor/itoa/benches/bench.rs b/bash-5.1/vendor/itoa/benches/bench.rs new file mode 100644 index 0000000..815b5a3 --- /dev/null +++ b/bash-5.1/vendor/itoa/benches/bench.rs @@ -0,0 +1,68 @@ +#![cfg_attr(feature = "i128", feature(i128_type, i128))] + +#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] + +#![feature(test)] +#![allow(non_snake_case)] + +extern crate itoa; +extern crate test; + +macro_rules! benches { + ( + $( + $(#[$attr:meta])* + $name:ident($value:expr) + ),* + ) => { + mod bench_itoa { + use test::{Bencher, black_box}; + $( + $(#[$attr])* + #[bench] + fn $name(b: &mut Bencher) { + use itoa; + + let mut buf = Vec::with_capacity(40); + + b.iter(|| { + buf.clear(); + itoa::write(&mut buf, black_box($value)).unwrap() + }); + } + )* + } + + mod bench_fmt { + use test::{Bencher, black_box}; + $( + $(#[$attr])* + #[bench] + fn $name(b: &mut Bencher) { + use std::io::Write; + + let mut buf = Vec::with_capacity(40); + + b.iter(|| { + buf.clear(); + write!(&mut buf, "{}", black_box($value)).unwrap() + }); + } + )* + } + } +} + +benches!{ + bench_u64_0(0u64), + bench_u64_half(::max_value() as u64), + bench_u64_max(::max_value()), + + bench_i16_0(0i16), + bench_i16_min(::min_value()), + + #[cfg(feature = "i128")] + bench_u128_0(0u128), + #[cfg(feature = "i128")] + bench_u128_max(::max_value()) +} diff --git a/bash-5.1/vendor/itoa/src/lib.rs b/bash-5.1/vendor/itoa/src/lib.rs new file mode 100644 index 0000000..722847f --- /dev/null +++ b/bash-5.1/vendor/itoa/src/lib.rs @@ -0,0 +1,196 @@ +// Copyright 2016 Itoa Developers +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![doc(html_root_url = "https://docs.rs/itoa/0.3.4")] + +#![cfg_attr(feature = "i128", feature(i128_type, i128))] + +#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless, unreadable_literal))] + +#[cfg(feature = "i128")] +mod udiv128; + +use std::{io, mem, ptr, slice}; + +#[inline] +pub fn write(wr: W, value: V) -> io::Result { + value.write(wr) +} + +pub trait Integer { + fn write(self, W) -> io::Result; +} + +trait IntegerPrivate { + fn write_to(self, buf: &mut [u8; MAX_LEN]) -> &[u8]; +} + +const DEC_DIGITS_LUT: &'static[u8] = + b"0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; + +const MAX_LEN: usize = 40; // i128::MIN (including minus sign) + +// Adaptation of the original implementation at +// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266 +macro_rules! impl_Integer { + ($($t:ident),* as $conv_fn:ident) => {$( + impl Integer for $t { + fn write(self, mut wr: W) -> io::Result { + let mut buf = unsafe { mem::uninitialized() }; + let bytes = self.write_to(&mut buf); + try!(wr.write_all(bytes)); + Ok(bytes.len()) + } + } + + impl IntegerPrivate for $t { + #[allow(unused_comparisons)] + fn write_to(self, buf: &mut [u8; MAX_LEN]) -> &[u8] { + let is_nonnegative = self >= 0; + let mut n = if is_nonnegative { + self as $conv_fn + } else { + // convert the negative num to positive by summing 1 to it's 2 complement + (!(self as $conv_fn)).wrapping_add(1) + }; + let mut curr = buf.len() as isize; + let buf_ptr = buf.as_mut_ptr(); + let lut_ptr = DEC_DIGITS_LUT.as_ptr(); + + unsafe { + // need at least 16 bits for the 4-characters-at-a-time to work. + if mem::size_of::<$t>() >= 2 { + // eagerly decode 4 characters at a time + while n >= 10000 { + let rem = (n % 10000) as isize; + n /= 10000; + + let d1 = (rem / 100) << 1; + let d2 = (rem % 100) << 1; + curr -= 4; + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(curr + 2), 2); + } + } + + // if we reach here numbers are <= 9999, so at most 4 chars long + let mut n = n as isize; // possibly reduce 64bit math + + // decode 2 more chars, if > 2 chars + if n >= 100 { + let d1 = (n % 100) << 1; + n /= 100; + curr -= 2; + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + } + + // decode last 1 or 2 chars + if n < 10 { + curr -= 1; + *buf_ptr.offset(curr) = (n as u8) + b'0'; + } else { + let d1 = n << 1; + curr -= 2; + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + } + + if !is_nonnegative { + curr -= 1; + *buf_ptr.offset(curr) = b'-'; + } + } + + let len = buf.len() - curr as usize; + unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) } + } + } + )*}; +} + +impl_Integer!(i8, u8, i16, u16, i32, u32 as u32); +impl_Integer!(i64, u64 as u64); +#[cfg(target_pointer_width = "16")] +impl_Integer!(isize, usize as u16); +#[cfg(target_pointer_width = "32")] +impl_Integer!(isize, usize as u32); +#[cfg(target_pointer_width = "64")] +impl_Integer!(isize, usize as u64); + +#[cfg(all(feature = "i128"))] +macro_rules! impl_Integer128 { + ($($t:ident),*) => {$( + impl Integer for $t { + fn write(self, mut wr: W) -> io::Result { + let mut buf = unsafe { mem::uninitialized() }; + let bytes = self.write_to(&mut buf); + try!(wr.write_all(bytes)); + Ok(bytes.len()) + } + } + + impl IntegerPrivate for $t { + #[allow(unused_comparisons)] + fn write_to(self, buf: &mut [u8; MAX_LEN]) -> &[u8] { + let is_nonnegative = self >= 0; + let n = if is_nonnegative { + self as u128 + } else { + // convert the negative num to positive by summing 1 to it's 2 complement + (!(self as u128)).wrapping_add(1) + }; + let mut curr = buf.len() as isize; + let buf_ptr = buf.as_mut_ptr(); + + unsafe { + // Divide by 10^19 which is the highest power less than 2^64. + let (n, rem) = udiv128::udivmod_1e19(n); + curr -= rem.write_to(buf).len() as isize; + + if n != 0 { + // Memset the base10 leading zeros of rem. + let target = buf.len() as isize - 19; + ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); + curr = target; + + // Divide by 10^19 again. + let (n, rem) = udiv128::udivmod_1e19(n); + let buf2 = buf_ptr.offset(curr - buf.len() as isize) as *mut _; + curr -= rem.write_to(&mut *buf2).len() as isize; + + if n != 0 { + // Memset the leading zeros. + let target = buf.len() as isize - 38; + ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); + curr = target; + + // There is at most one digit left + // because u128::max / 10^19 / 10^19 is 3. + curr -= 1; + *buf_ptr.offset(curr) = (n as u8) + b'0'; + } + } + + if !is_nonnegative { + curr -= 1; + *buf_ptr.offset(curr) = b'-'; + } + + let len = buf.len() - curr as usize; + slice::from_raw_parts(buf_ptr.offset(curr), len) + } + } + } + )*}; +} + +#[cfg(all(feature = "i128"))] +impl_Integer128!(i128, u128); diff --git a/bash-5.1/vendor/itoa/src/udiv128.rs b/bash-5.1/vendor/itoa/src/udiv128.rs new file mode 100644 index 0000000..24233c6 --- /dev/null +++ b/bash-5.1/vendor/itoa/src/udiv128.rs @@ -0,0 +1,62 @@ +// Copyright 2009-2016 compiler-builtins Developers +// +// The compiler-builtins crate is dual licensed under both the University of +// Illinois "BSD-Like" license and the MIT license. As a user of this code you may +// choose to use it under either license. As a contributor, you agree to allow +// your code to be used under both. +// +// Full text of the relevant licenses is found here: +// https://github.com/rust-lang-nursery/compiler-builtins/blob/master/LICENSE.TXT +// +// +// +// The following code is based on Rust’s [compiler-builtins crate] +// (https://github.com/rust-lang-nursery/compiler-builtins) which +// provides runtime functions for the Rust programs. The Rust +// compiler will automatically link your programs against this crate. +// +// We copied the implementation of '__udivmodti4()' which is an intrinsic +// implementing division with remainder for architectures without 128-bit integer support. +// We have done this two reasons, to work around [bad optimization by LLVM] +// (https://github.com/rust-lang/rust/issues/44545) and to allow function +// inlining which doesn’t happen with the intrinsic. + +pub fn udivmod_1e19(n: u128) -> (u128, u64) { + let d = 10_000_000_000_000_000_000_u64; // 10^19 + + let high = (n >> 64) as u64; + if high == 0 { + let low = n as u64; + return ((low / d) as u128, low % d); + } + + let sr = 65 - high.leading_zeros(); + + // 2 <= sr <= 65 + let mut q: u128 = n << (128 - sr); + let mut r: u128 = n >> sr; + let mut carry: u64 = 0; + + // Don't use a range because they may generate references to memcpy in unoptimized code + // + // Loop invariants: r < d; carry is 0 or 1 + let mut i = 0; + while i < sr { + i += 1; + + // r:q = ((r:q) << 1) | carry + r = (r << 1) | (q >> 127); + q = (q << 1) | carry as u128; + + // carry = 0 + // if r >= d { + // r -= d; + // carry = 1; + // } + let s = (d as u128).wrapping_sub(r).wrapping_sub(1) as i128 >> 127; + carry = (s & 1) as u64; + r -= (d as u128) & s as u128; + } + + ((q << 1) | carry as u128, r as u64) +} diff --git a/bash-5.1/vendor/itoa/tests/test.rs b/bash-5.1/vendor/itoa/tests/test.rs new file mode 100644 index 0000000..a360293 --- /dev/null +++ b/bash-5.1/vendor/itoa/tests/test.rs @@ -0,0 +1,43 @@ +#![cfg_attr(feature = "i128", feature(i128_type, i128))] + +#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless, string_lit_as_bytes))] + +#![allow(non_snake_case)] + +extern crate itoa; + +macro_rules! test { + ( + $( + $(#[$attr:meta])* + $name:ident($value:expr, $expected:expr) + ),* + ) => { + $( + $(#[$attr])* + #[test] + fn $name() { + let mut buf = [b'\0'; 40]; + let len = itoa::write(&mut buf[..], $value).unwrap(); + assert_eq!(&buf[0..len], $expected.as_bytes()); + } + )* + } +} + +test!{ + test_u64_0(0u64, "0"), + test_u64_half(::max_value() as u64, "4294967295"), + test_u64_max(::max_value(), "18446744073709551615"), + test_i64_min(::min_value(), "-9223372036854775808"), + + test_i16_0(0i16, "0"), + test_i16_min(::min_value(), "-32768"), + + #[cfg(feature = "i128")] + test_u128_0(0u128, "0"), + #[cfg(feature = "i128")] + test_u128_max(::max_value(), "340282366920938463463374607431768211455"), + #[cfg(feature = "i128")] + test_i128_min(::min_value(), "-170141183460469231731687303715884105728") +} diff --git a/bash-5.1/vendor/kernel32-sys/.cargo-checksum.json b/bash-5.1/vendor/kernel32-sys/.cargo-checksum.json new file mode 100644 index 0000000..55bf9d9 --- /dev/null +++ b/bash-5.1/vendor/kernel32-sys/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"79c920ca9323e28acd5f5a80f2ce0ab81aa6227584397a9f742e78dce36a2117","README.md":"00afb50f0a5a7d548e40feb1f09ce8fa678b46e04c9a72d909fa36fb85fb2200","build.rs":"89e77c6e9e79dcd782fd006431b948d093ec4aeda3b69a280ec857077b7f2020","src/lib.rs":"ab0a8a104a6f747f6389a70d26a62e156ab97cc7c8f4daf1de99b820024da993"},"package":"7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"} \ No newline at end of file diff --git a/bash-5.1/vendor/kernel32-sys/Cargo.toml b/bash-5.1/vendor/kernel32-sys/Cargo.toml new file mode 100644 index 0000000..5d28426 --- /dev/null +++ b/bash-5.1/vendor/kernel32-sys/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "kernel32-sys" +version = "0.2.2" +authors = ["Peter Atashian "] +description = "Contains function definitions for the Windows API library kernel32. See winapi for types and constants." +documentation = "https://retep998.github.io/doc/kernel32/" +repository = "https://github.com/retep998/winapi-rs" +readme = "README.md" +keywords = ["windows", "ffi", "win32"] +license = "MIT" +build = "build.rs" +[lib] +name = "kernel32" +[dependencies] +winapi = { version = "0.2.5", path = "../.." } +[build-dependencies] +winapi-build = { version = "0.1.1", path = "../../build" } diff --git a/bash-5.1/vendor/kernel32-sys/README.md b/bash-5.1/vendor/kernel32-sys/README.md new file mode 100644 index 0000000..07ee5a6 --- /dev/null +++ b/bash-5.1/vendor/kernel32-sys/README.md @@ -0,0 +1,13 @@ +# kernel32 # +Contains function definitions for the Windows API library kernel32. See winapi for types and constants. + +```toml +[dependencies] +kernel32-sys = "0.2.1" +``` + +```rust +extern crate kernel32; +``` + +[Documentation](https://retep998.github.io/doc/kernel32/) diff --git a/bash-5.1/vendor/kernel32-sys/build.rs b/bash-5.1/vendor/kernel32-sys/build.rs new file mode 100644 index 0000000..cf323fc --- /dev/null +++ b/bash-5.1/vendor/kernel32-sys/build.rs @@ -0,0 +1,6 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +extern crate build; +fn main() { + build::link("kernel32", false) +} diff --git a/bash-5.1/vendor/kernel32-sys/src/lib.rs b/bash-5.1/vendor/kernel32-sys/src/lib.rs new file mode 100644 index 0000000..ca76835 --- /dev/null +++ b/bash-5.1/vendor/kernel32-sys/src/lib.rs @@ -0,0 +1,2754 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! FFI bindings to kernel32. +#![cfg(windows)] +extern crate winapi; +use winapi::*; +extern "system" { + pub fn AcquireSRWLockExclusive(SRWLock: PSRWLOCK); + pub fn AcquireSRWLockShared(SRWLock: PSRWLOCK); + pub fn ActivateActCtx(hActCtx: HANDLE, lpCookie: *mut ULONG_PTR) -> BOOL; + pub fn AddAtomA(lpString: LPCSTR) -> ATOM; + pub fn AddAtomW(lpString: LPCWSTR) -> ATOM; + pub fn AddConsoleAliasA(Source: LPSTR, Target: LPSTR, ExeName: LPSTR) -> BOOL; + pub fn AddConsoleAliasW(Source: LPWSTR, Target: LPWSTR, ExeName: LPWSTR) -> BOOL; + pub fn AddDllDirectory(NewDirectory: PCWSTR) -> DLL_DIRECTORY_COOKIE; + pub fn AddIntegrityLabelToBoundaryDescriptor( + BoundaryDescriptor: *mut HANDLE, IntegrityLabel: PSID, + ) -> BOOL; + // pub fn AddLocalAlternateComputerNameA(); + // pub fn AddLocalAlternateComputerNameW(); + pub fn AddRefActCtx(hActCtx: HANDLE); + pub fn AddResourceAttributeAce( + pAcl: PACL, dwAceRevision: DWORD, AceFlags: DWORD, AccessMask: DWORD, pSid: PSID, + pAttributeInfo: PCLAIM_SECURITY_ATTRIBUTES_INFORMATION, pReturnLength: PDWORD, + ) -> BOOL; + pub fn AddSIDToBoundaryDescriptor(BoundaryDescriptor: *mut HANDLE, RequiredSid: PSID) -> BOOL; + pub fn AddScopedPolicyIDAce( + pAcl: PACL, dwAceRevision: DWORD, AceFlags: DWORD, AccessMask: DWORD, pSid: PSID, + ) -> BOOL; + pub fn AddSecureMemoryCacheCallback(pfnCallBack: PSECURE_MEMORY_CACHE_CALLBACK) -> BOOL; + pub fn AddVectoredContinueHandler(First: ULONG, Handler: PVECTORED_EXCEPTION_HANDLER) -> PVOID; + pub fn AddVectoredExceptionHandler( + First: ULONG, Handler: PVECTORED_EXCEPTION_HANDLER, + ) -> PVOID; + pub fn AllocConsole() -> BOOL; + pub fn AllocateUserPhysicalPages( + hProcess: HANDLE, NumberOfPages: PULONG_PTR, PageArray: PULONG_PTR, + ) -> BOOL; + pub fn AllocateUserPhysicalPagesNuma( + hProcess: HANDLE, NumberOfPages: PULONG_PTR, PageArray: PULONG_PTR, nndPreferred: DWORD, + ) -> BOOL; + // pub fn AppXGetOSMaxVersionTested(); + pub fn ApplicationRecoveryFinished(bSuccess: BOOL); + pub fn ApplicationRecoveryInProgress(pbCancelled: PBOOL) -> HRESULT; + pub fn AreFileApisANSI() -> BOOL; + pub fn AssignProcessToJobObject(hJob: HANDLE, hProcess: HANDLE) -> BOOL; + pub fn AttachConsole(dwProcessId: DWORD) -> BOOL; + pub fn BackupRead( + hFile: HANDLE, lpBuffer: LPBYTE, nNumberOfBytesToRead: DWORD, lpNumberOfBytesRead: LPDWORD, + bAbort: BOOL, bProcessSecurity: BOOL, lpContext: *mut LPVOID, + ) -> BOOL; + pub fn BackupSeek( + hFile: HANDLE, dwLowBytesToSeek: DWORD, dwHighBytesToSeek: DWORD, + lpdwLowByteSeeked: LPDWORD, lpdwHighByteSeeked: LPDWORD, lpContext: *mut LPVOID, + ) -> BOOL; + pub fn BackupWrite( + hFile: HANDLE, lpBuffer: LPBYTE, nNumberOfBytesToWrite: DWORD, + lpNumberOfBytesWritten: LPDWORD, bAbort: BOOL, bProcessSecurity: BOOL, + lpContext: *mut LPVOID, + ) -> BOOL; + // pub fn BaseSetLastNTError(); + pub fn Beep(dwFreq: DWORD, dwDuration: DWORD) -> BOOL; + pub fn BeginUpdateResourceA(pFileName: LPCSTR, bDeleteExistingResources: BOOL) -> HANDLE; + pub fn BeginUpdateResourceW(pFileName: LPCWSTR, bDeleteExistingResources: BOOL) -> HANDLE; + pub fn BindIoCompletionCallback( + FileHandle: HANDLE, Function: LPOVERLAPPED_COMPLETION_ROUTINE, Flags: ULONG, + ) -> BOOL; + pub fn BuildCommDCBA(lpDef: LPCSTR, lpDCB: LPDCB) -> BOOL; + pub fn BuildCommDCBAndTimeoutsA( + lpDef: LPCSTR, lpDCB: LPDCB, lpCommTimeouts: LPCOMMTIMEOUTS, + ) -> BOOL; + pub fn BuildCommDCBAndTimeoutsW( + lpDef: LPCWSTR, lpDCB: LPDCB, lpCommTimeouts: LPCOMMTIMEOUTS, + ) -> BOOL; + pub fn BuildCommDCBW(lpDef: LPCWSTR, lpDCB: LPDCB) -> BOOL; + pub fn CallNamedPipeA( + lpNamedPipeName: LPCSTR, lpInBuffer: LPVOID, nInBufferSize: DWORD, lpOutBuffer: LPVOID, + nOutBufferSize: DWORD, lpBytesRead: LPDWORD, nTimeOut: DWORD, + ) -> BOOL; + pub fn CallNamedPipeW( + lpNamedPipeName: LPCWSTR, lpInBuffer: LPVOID, nInBufferSize: DWORD, lpOutBuffer: LPVOID, + nOutBufferSize: DWORD, lpBytesRead: LPDWORD, nTimeOut: DWORD, + ) -> BOOL; + pub fn CallbackMayRunLong(pci: PTP_CALLBACK_INSTANCE) -> BOOL; + pub fn CalloutOnFiberStack( + lpFiber: PVOID, lpStartAddress: PFIBER_CALLOUT_ROUTINE, lpParameter: PVOID, + ) -> PVOID; + pub fn CancelDeviceWakeupRequest(hDevice: HANDLE) -> BOOL; + pub fn CancelIo(hFile: HANDLE) -> BOOL; + pub fn CancelIoEx(hFile: HANDLE, lpOverlapped: LPOVERLAPPED) -> BOOL; + pub fn CancelSynchronousIo(hThread: HANDLE) -> BOOL; + pub fn CancelThreadpoolIo(pio: PTP_IO); + pub fn CancelTimerQueueTimer(TimerQueue: HANDLE, Timer: HANDLE) -> BOOL; + pub fn CancelWaitableTimer(hTimer: HANDLE) -> BOOL; + pub fn CeipIsOptedIn() -> BOOL; + pub fn ChangeTimerQueueTimer( + TimerQueue: HANDLE, Timer: HANDLE, DueTime: ULONG, Period: ULONG, + ) -> BOOL; + // pub fn CheckElevation(); + // pub fn CheckElevationEnabled(); + pub fn CheckNameLegalDOS8Dot3A( + lpName: LPCSTR, lpOemName: LPSTR, OemNameSize: DWORD, pbNameContainsSpaces: PBOOL, + pbNameLegal: PBOOL, + ) -> BOOL; + pub fn CheckNameLegalDOS8Dot3W( + lpName: LPCWSTR, lpOemName: LPSTR, OemNameSize: DWORD, pbNameContainsSpaces: PBOOL, + pbNameLegal: PBOOL, + ) -> BOOL; + pub fn CheckRemoteDebuggerPresent(hProcess: HANDLE, pbDebuggerPresent: PBOOL) -> BOOL; + pub fn CheckTokenCapability( + TokenHandle: HANDLE, CapabilitySidToCheck: PSID, HasCapability: PBOOL, + ) -> BOOL; + pub fn CheckTokenMembershipEx( + TokenHandle: HANDLE, SidToCheck: PSID, Flags: DWORD, IsMember: PBOOL, + ) -> BOOL; + pub fn ClearCommBreak(hFile: HANDLE) -> BOOL; + pub fn ClearCommError(hFile: HANDLE, lpErrors: LPDWORD, lpStat: LPCOMSTAT) -> BOOL; + pub fn CloseHandle(hObject: HANDLE) -> BOOL; + // pub fn ClosePackageInfo(); + pub fn ClosePrivateNamespace(Handle: HANDLE, Flags: ULONG) -> BOOLEAN; + // pub fn CloseState(); + pub fn CloseThreadpool(ptpp: PTP_POOL); + pub fn CloseThreadpoolCleanupGroup(ptpcg: PTP_CLEANUP_GROUP); + pub fn CloseThreadpoolCleanupGroupMembers( + ptpcg: PTP_CLEANUP_GROUP, fCancelPendingCallbacks: BOOL, pvCleanupContext: PVOID, + ); + pub fn CloseThreadpoolIo(pio: PTP_IO); + pub fn CloseThreadpoolTimer(pti: PTP_TIMER); + pub fn CloseThreadpoolWait(pwa: PTP_WAIT); + pub fn CloseThreadpoolWork(pwk: PTP_WORK); + pub fn CommConfigDialogA(lpszName: LPCSTR, hWnd: HWND, lpCC: LPCOMMCONFIG) -> BOOL; + pub fn CommConfigDialogW(lpszName: LPCWSTR, hWnd: HWND, lpCC: LPCOMMCONFIG) -> BOOL; + pub fn CompareFileTime(lpFileTime1: *const FILETIME, lpFileTime2: *const FILETIME) -> LONG; + pub fn CompareStringA( + Locale: LCID, dwCmpFlags: DWORD, lpString1: PCNZCH, cchCount1: c_int, lpString2: PCNZCH, + cchCount2: c_int, + ) -> c_int; + pub fn CompareStringEx( + lpLocaleName: LPCWSTR, dwCmpFlags: DWORD, lpString1: LPCWCH, cchCount1: c_int, + lpString2: LPCWCH, cchCount2: c_int, lpVersionInformation: LPNLSVERSIONINFO, + lpReserved: LPVOID, lParam: LPARAM, + ) -> c_int; + pub fn CompareStringOrdinal( + lpString1: LPCWCH, cchCount1: c_int, lpString2: LPCWCH, cchCount2: c_int, bIgnoreCase: BOOL, + ) -> c_int; + pub fn CompareStringW( + Locale: LCID, dwCmpFlags: DWORD, lpString1: PCNZWCH, cchCount1: c_int, lpString2: PCNZWCH, + cchCount2: c_int, + ) -> c_int; + pub fn ConnectNamedPipe(hNamedPipe: HANDLE, lpOverlapped: LPOVERLAPPED) -> BOOL; + pub fn ContinueDebugEvent( + dwProcessId: DWORD, dwThreadId: DWORD, dwContinueStatus: DWORD, + ) -> BOOL; + pub fn ConvertDefaultLocale(Locale: LCID) -> LCID; + pub fn ConvertFiberToThread() -> BOOL; + pub fn ConvertThreadToFiber(lpParameter: LPVOID) -> LPVOID; + pub fn ConvertThreadToFiberEx(lpParameter: LPVOID, dwFlags: DWORD) -> LPVOID; + pub fn CopyContext(Destination: PCONTEXT, ContextFlags: DWORD, Source: PCONTEXT) -> BOOL; + pub fn CopyFile2( + pwszExistingFileName: PCWSTR, pwszNewFileName: PCWSTR, + pExtendedParameters: *mut COPYFILE2_EXTENDED_PARAMETERS, + ) -> HRESULT; + pub fn CopyFileA( + lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, bFailIfExists: BOOL + ) -> BOOL; + pub fn CopyFileExA( + lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, pbCancel: LPBOOL, dwCopyFlags: DWORD, + ) -> BOOL; + pub fn CopyFileExW( + lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, pbCancel: LPBOOL, dwCopyFlags: DWORD, + ) -> BOOL; + pub fn CopyFileTransactedA( + lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, pbCancel: LPBOOL, dwCopyFlags: DWORD, hTransaction: HANDLE, + ) -> BOOL; + pub fn CopyFileTransactedW( + lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, pbCancel: LPBOOL, dwCopyFlags: DWORD, hTransaction: HANDLE, + ) -> BOOL; + pub fn CopyFileW( + lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, bFailIfExists: BOOL + ) -> BOOL; + pub fn CreateActCtxA(pActCtx: PCACTCTXA) -> HANDLE; + pub fn CreateActCtxW(pActCtx: PCACTCTXW) -> HANDLE; + pub fn CreateBoundaryDescriptorA(Name: LPCSTR, Flags: ULONG) -> HANDLE; + pub fn CreateBoundaryDescriptorW(Name: LPCWSTR, Flags: ULONG) -> HANDLE; + pub fn CreateConsoleScreenBuffer( + dwDesiredAccess: DWORD, dwShareMode: DWORD, + lpSecurityAttributes: *const SECURITY_ATTRIBUTES, dwFlags: DWORD, + lpScreenBufferData: LPVOID, + ) -> HANDLE; + pub fn CreateDirectoryA( + lpPathName: LPCSTR, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; + pub fn CreateDirectoryExA( + lpTemplateDirectory: LPCSTR, lpNewDirectory: LPCSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; + pub fn CreateDirectoryExW( + lpTemplateDirectory: LPCWSTR, lpNewDirectory: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; + pub fn CreateDirectoryTransactedA( + lpTemplateDirectory: LPCSTR, lpNewDirectory: LPCSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, hTransaction: HANDLE, + ) -> BOOL; + pub fn CreateDirectoryTransactedW( + lpTemplateDirectory: LPCWSTR, lpNewDirectory: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, hTransaction: HANDLE, + ) -> BOOL; + pub fn CreateDirectoryW( + lpPathName: LPCWSTR, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; + pub fn CreateEventA( + lpEventAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, bInitialState: BOOL, + lpName: LPCSTR, + ) -> HANDLE; + pub fn CreateEventW( + lpEventAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, bInitialState: BOOL, + lpName: LPCWSTR, + ) -> HANDLE; + pub fn CreateEventExA( + lpEventAttributes: LPSECURITY_ATTRIBUTES, lpName: LPCSTR, dwFlags: DWORD, + dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateEventExW( + lpEventAttributes: LPSECURITY_ATTRIBUTES, lpName: LPCWSTR, dwFlags: DWORD, + dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateFiber( + dwStackSize: SIZE_T, lpStartAddress: LPFIBER_START_ROUTINE, lpParameter: LPVOID, + ) -> LPVOID; + pub fn CreateFiberEx( + dwStackCommitSize: SIZE_T, dwStackReserveSize: SIZE_T, dwFlags: DWORD, + lpStartAddress: LPFIBER_START_ROUTINE, lpParameter: LPVOID, + ) -> LPVOID; + pub fn CreateFile2( + lpFileName: LPCWSTR, dwDesiredAccess: DWORD, dwShareMode: DWORD, + dwCreationDisposition: DWORD, pCreateExParams: LPCREATEFILE2_EXTENDED_PARAMETERS, + ) -> HANDLE; + pub fn CreateFileA( + lpFileName: LPCSTR, dwDesiredAccess: DWORD, dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, hTemplateFile: HANDLE, + ) -> HANDLE; + pub fn CreateFileMappingA( + hFile: HANDLE, lpAttributes: LPSECURITY_ATTRIBUTES, flProtect: DWORD, + dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, lpName: LPCSTR, + ) -> HANDLE; + pub fn CreateFileMappingFromApp( + hFile: HANDLE, SecurityAttributes: PSECURITY_ATTRIBUTES, PageProtection: ULONG, + MaximumSize: ULONG64, Name: PCWSTR, + ) -> HANDLE; + pub fn CreateFileMappingNumaA( + hFile: HANDLE, lpFileMappingAttributes: LPSECURITY_ATTRIBUTES, flProtect: DWORD, + dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, lpName: LPCSTR, nndPreferred: DWORD, + ) -> HANDLE; + pub fn CreateFileMappingNumaW( + hFile: HANDLE, lpFileMappingAttributes: LPSECURITY_ATTRIBUTES, flProtect: DWORD, + dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, lpName: LPCWSTR, nndPreferred: DWORD, + ) -> HANDLE; + pub fn CreateFileMappingW( + hFile: HANDLE, lpAttributes: LPSECURITY_ATTRIBUTES, flProtect: DWORD, + dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, lpName: LPCWSTR, + ) -> HANDLE; + pub fn CreateFileTransactedA( + lpFileName: LPCSTR, dwDesiredAccess: DWORD, dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, hTemplateFile: HANDLE, hTransaction: HANDLE, + pusMiniVersion: PUSHORT, lpExtendedParameter: PVOID, + ) -> HANDLE; + pub fn CreateFileTransactedW( + lpFileName: LPCWSTR, dwDesiredAccess: DWORD, dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, hTemplateFile: HANDLE, hTransaction: HANDLE, + pusMiniVersion: PUSHORT, lpExtendedParameter: PVOID, + ) -> HANDLE; + pub fn CreateFileW( + lpFileName: LPCWSTR, dwDesiredAccess: DWORD, dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, hTemplateFile: HANDLE, + ) -> HANDLE; + pub fn CreateHardLinkA( + lpFileName: LPCSTR, lpExistingFileName: LPCSTR, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; + pub fn CreateHardLinkTransactedA( + lpFileName: LPCSTR, lpExistingFileName: LPCSTR, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + hTransaction: HANDLE, + ) -> BOOL; + pub fn CreateHardLinkTransactedW( + lpFileName: LPCWSTR, lpExistingFileName: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, hTransaction: HANDLE, + ); + pub fn CreateHardLinkW( + lpFileName: LPCWSTR, lpExistingFileName: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; + pub fn CreateIoCompletionPort( + FileHandle: HANDLE, ExistingCompletionPort: HANDLE, CompletionKey: ULONG_PTR, + NumberOfConcurrentThreads: DWORD, + ) -> HANDLE; + pub fn CreateJobObjectA(lpJobAttributes: LPSECURITY_ATTRIBUTES, lpName: LPCSTR) -> HANDLE; + pub fn CreateJobObjectW(lpJobAttributes: LPSECURITY_ATTRIBUTES, lpName: LPCWSTR) -> HANDLE; + pub fn CreateJobSet(NumJob: ULONG, UserJobSet: PJOB_SET_ARRAY, Flags: ULONG) -> BOOL; + pub fn CreateMailslotA( + lpName: LPCSTR, nMaxMessageSize: DWORD, lReadTimeout: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> HANDLE; + pub fn CreateMailslotW( + lpName: LPCWSTR, nMaxMessageSize: DWORD, lReadTimeout: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> HANDLE; + pub fn CreateMemoryResourceNotification( + NotificationType: MEMORY_RESOURCE_NOTIFICATION_TYPE, + ) -> HANDLE; + pub fn CreateMutexA( + lpMutexAttributes: LPSECURITY_ATTRIBUTES, bInitialOwner: BOOL, lpName: LPCSTR, + ) -> HANDLE; + pub fn CreateMutexExA( + lpMutexAttributes: LPSECURITY_ATTRIBUTES, lpName: LPCSTR, dwFlags: DWORD, + dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateMutexExW( + lpMutexAttributes: LPSECURITY_ATTRIBUTES, lpName: LPCWSTR, dwFlags: DWORD, + dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateMutexW( + lpMutexAttributes: LPSECURITY_ATTRIBUTES, bInitialOwner: BOOL, lpName: LPCWSTR, + ) -> HANDLE; + pub fn CreateNamedPipeA( + lpName: LPCSTR, dwOpenMode: DWORD, dwPipeMode: DWORD, nMaxInstances: DWORD, + nOutBufferSize: DWORD, nInBufferSize: DWORD, nDefaultTimeOut: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> HANDLE; + pub fn CreateNamedPipeW( + lpName: LPCWSTR, dwOpenMode: DWORD, dwPipeMode: DWORD, nMaxInstances: DWORD, + nOutBufferSize: DWORD, nInBufferSize: DWORD, nDefaultTimeOut: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> HANDLE; + pub fn CreatePipe( + hReadPipe: PHANDLE, hWritePipe: PHANDLE, lpPipeAttributes: LPSECURITY_ATTRIBUTES, + nSize: DWORD, + ) -> BOOL; + pub fn CreatePrivateNamespaceA( + lpPrivateNamespaceAttributes: LPSECURITY_ATTRIBUTES, lpBoundaryDescriptor: LPVOID, + lpAliasPrefix: LPCSTR, + ) -> HANDLE; + pub fn CreatePrivateNamespaceW( + lpPrivateNamespaceAttributes: LPSECURITY_ATTRIBUTES, lpBoundaryDescriptor: LPVOID, + lpAliasPrefix: LPCWSTR, + ) -> HANDLE; + pub fn CreateProcessA( + lpApplicationName: LPCSTR, lpCommandLine: LPSTR, lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, bInheritHandles: BOOL, dwCreationFlags: DWORD, + lpEnvironment: LPVOID, lpCurrentDirectory: LPCSTR, lpStartupInfo: LPSTARTUPINFOA, + lpProcessInformation: LPPROCESS_INFORMATION, + ) -> BOOL; + pub fn CreateProcessW( + lpApplicationName: LPCWSTR, lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, dwCreationFlags: DWORD, lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, lpStartupInfo: LPSTARTUPINFOW, + lpProcessInformation: LPPROCESS_INFORMATION, + ) -> BOOL; + pub fn CreateRemoteThread( + hProcess: HANDLE, lpThreadAttributes: LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, + lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: LPVOID, dwCreationFlags: DWORD, + lpThreadId: LPDWORD, + ) -> HANDLE; + pub fn CreateRemoteThreadEx( + hProcess: HANDLE, lpThreadAttributes: LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, + lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: LPVOID, dwCreationFlags: DWORD, + lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST, lpThreadId: LPDWORD, + ) -> HANDLE; + pub fn CreateSemaphoreA( + lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, lInitialCount: LONG, lMaximumCount: LONG, + lpName: LPCSTR, + ) -> HANDLE; + pub fn CreateSemaphoreExA( + lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, lInitialCount: LONG, lMaximumCount: LONG, + lpName: LPCSTR, dwFlags: DWORD, dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateSemaphoreExW( + lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, lInitialCount: LONG, lMaximumCount: LONG, + lpName: LPCWSTR, dwFlags: DWORD, dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateSemaphoreW( + lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, lInitialCount: LONG, lMaximumCount: LONG, + lpName: LPCWSTR, + ) -> HANDLE; + pub fn CreateSymbolicLinkA( + lpSymlinkFileName: LPCSTR, lpTargetFileName: LPCSTR, dwFlags: DWORD, + ) -> BOOLEAN; + pub fn CreateSymbolicLinkTransactedA( + lpSymlinkFileName: LPCSTR, lpTargetFileName: LPCSTR, dwFlags: DWORD, hTransaction: HANDLE, + ) -> BOOLEAN; + pub fn CreateSymbolicLinkTransactedW( + lpSymlinkFileName: LPCWSTR, lpTargetFileName: LPCWSTR, dwFlags: DWORD, hTransaction: HANDLE, + ) -> BOOLEAN; + pub fn CreateSymbolicLinkW( + lpSymlinkFileName: LPCWSTR, lpTargetFileName: LPCWSTR, dwFlags: DWORD, + ) -> BOOLEAN; + pub fn CreateTapePartition( + hDevice: HANDLE, dwPartitionMethod: DWORD, dwCount: DWORD, dwSize: DWORD, + ) -> DWORD; + pub fn CreateThread( + lpThreadAttributes: LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, + lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: LPVOID, dwCreationFlags: DWORD, + lpThreadId: LPDWORD, + ) -> HANDLE; + pub fn CreateThreadpool(reserved: PVOID) -> PTP_POOL; + pub fn CreateThreadpoolCleanupGroup() -> PTP_CLEANUP_GROUP; + pub fn CreateThreadpoolIo( + fl: HANDLE, pfnio: PTP_WIN32_IO_CALLBACK, pv: PVOID, pcbe: PTP_CALLBACK_ENVIRON, + ) -> PTP_IO; + pub fn CreateThreadpoolTimer( + pfnti: PTP_TIMER_CALLBACK, pv: PVOID, pcbe: PTP_CALLBACK_ENVIRON, + ) -> PTP_TIMER; + pub fn CreateThreadpoolWait( + pfnwa: PTP_WAIT_CALLBACK, pv: PVOID, pcbe: PTP_CALLBACK_ENVIRON, + ) -> PTP_WAIT; + pub fn CreateThreadpoolWork( + pfnwk: PTP_WORK_CALLBACK, pv: PVOID, pcbe: PTP_CALLBACK_ENVIRON, + ) -> PTP_WORK; + pub fn CreateTimerQueue() -> HANDLE; + pub fn CreateTimerQueueTimer( + phNewTimer: PHANDLE, TimerQueue: HANDLE, Callback: WAITORTIMERCALLBACK, Parameter: PVOID, + DueTime: DWORD, Period: DWORD, Flags: ULONG, + ) -> BOOL; + pub fn CreateToolhelp32Snapshot(dwFlags: DWORD, th32ProcessID: DWORD) -> HANDLE; + #[cfg(target_arch = "x86_64")] + pub fn CreateUmsCompletionList(UmsCompletionList: *mut PUMS_COMPLETION_LIST) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn CreateUmsThreadContext(lpUmsThread: *mut PUMS_CONTEXT) -> BOOL; + pub fn CreateWaitableTimerA( + lpTimerAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, lpTimerName: LPCSTR, + ) -> HANDLE; + pub fn CreateWaitableTimerExA( + lpTimerAttributes: LPSECURITY_ATTRIBUTES, lpTimerName: LPCSTR, dwFlags: DWORD, + dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateWaitableTimerExW( + lpTimerAttributes: LPSECURITY_ATTRIBUTES, lpTimerName: LPCWSTR, dwFlags: DWORD, + dwDesiredAccess: DWORD, + ) -> HANDLE; + pub fn CreateWaitableTimerW( + lpTimerAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, lpTimerName: LPCWSTR, + ) -> HANDLE; + // pub fn CtrlRoutine(); + pub fn DeactivateActCtx(dwFlags: DWORD, ulCookie: ULONG_PTR) -> BOOL; + pub fn DebugActiveProcess(dwProcessId: DWORD) -> BOOL; + pub fn DebugActiveProcessStop(dwProcessId: DWORD) -> BOOL; + pub fn DebugBreak(); + pub fn DebugBreakProcess(Process: HANDLE) -> BOOL; + pub fn DebugSetProcessKillOnExit(KillOnExit: BOOL) -> BOOL; + pub fn DecodePointer(Ptr: PVOID) -> PVOID; + pub fn DecodeSystemPointer(Ptr: PVOID) -> PVOID; + pub fn DefineDosDeviceA(dwFlags: DWORD, lpDeviceName: LPCSTR, lpTargetPath: LPCSTR) -> BOOL; + pub fn DefineDosDeviceW(dwFlags: DWORD, lpDeviceName: LPCWSTR, lpTargetPath: LPCWSTR) -> BOOL; + pub fn DelayLoadFailureHook(pszDllName: LPCSTR, pszProcName: LPCSTR) -> FARPROC; + pub fn DeleteAtom(nAtom: ATOM) -> ATOM; + pub fn DeleteBoundaryDescriptor(BoundaryDescriptor: HANDLE); + pub fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); + pub fn DeleteFiber(lpFiber: LPVOID); + pub fn DeleteFileA(lpFileName: LPCSTR) -> BOOL; + pub fn DeleteFileTransactedA(lpFileName: LPCSTR, hTransaction: HANDLE) -> BOOL; + pub fn DeleteFileTransactedW(lpFileName: LPCWSTR, hTransaction: HANDLE) -> BOOL; + pub fn DeleteFileW(lpFileName: LPCWSTR) -> BOOL; + pub fn DeleteProcThreadAttributeList(lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST); + pub fn DeleteSynchronizationBarrier(lpBarrier: LPSYNCHRONIZATION_BARRIER) -> BOOL; + pub fn DeleteTimerQueue(TimerQueue: HANDLE) -> BOOL; + pub fn DeleteTimerQueueEx(TimerQueue: HANDLE, CompletionEvent: HANDLE) -> BOOL; + pub fn DeleteTimerQueueTimer( + TimerQueue: HANDLE, Timer: HANDLE, CompletionEvent: HANDLE, + ) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn DeleteUmsCompletionList(UmsCompletionList: PUMS_COMPLETION_LIST) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn DeleteUmsThreadContext(UmsThread: PUMS_CONTEXT) -> BOOL; + pub fn DeleteVolumeMountPointA(lpszVolumeMountPoint: LPCSTR) -> BOOL; + pub fn DeleteVolumeMountPointW(lpszVolumeMountPoint: LPCWSTR) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn DequeueUmsCompletionListItems( + UmsCompletionList: PUMS_COMPLETION_LIST, WaitTimeOut: DWORD, + UmsThreadList: *mut PUMS_CONTEXT, + ) -> BOOL; + pub fn DeviceIoControl( + hDevice: HANDLE, dwIoControlCode: DWORD, lpInBuffer: LPVOID, nInBufferSize: DWORD, + lpOutBuffer: LPVOID, nOutBufferSize: DWORD, lpBytesReturned: LPDWORD, + lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn DisableThreadLibraryCalls(hLibModule: HMODULE) -> BOOL; + pub fn DisableThreadProfiling(PerformanceDataHandle: HANDLE) -> DWORD; + pub fn DisassociateCurrentThreadFromCallback(pci: PTP_CALLBACK_INSTANCE); + pub fn DisconnectNamedPipe(hNamedPipe: HANDLE) -> BOOL; + pub fn DnsHostnameToComputerNameA( + Hostname: LPCSTR, ComputerName: LPCSTR, nSize: LPDWORD, + ) -> BOOL; + pub fn DnsHostnameToComputerNameExW( + Hostname: LPCWSTR, ComputerName: LPWSTR, nSize: LPDWORD, + ) -> BOOL; + pub fn DnsHostnameToComputerNameW( + Hostname: LPCWSTR, ComputerName: LPWSTR, nSize: LPDWORD, + ) -> BOOL; + pub fn DosDateTimeToFileTime(wFatDate: WORD, wFatTime: WORD, lpFileTime: LPFILETIME) -> BOOL; + // pub fn DosPathToSessionPathW(); + pub fn DuplicateHandle( + hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE, hTargetProcessHandle: HANDLE, + lpTargetHandle: LPHANDLE, dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwOptions: DWORD, + ) -> BOOL; + pub fn EnableThreadProfiling( + ThreadHandle: HANDLE, Flags: DWORD, HardwareCounters: DWORD64, + PerformanceDataHandle: *mut HANDLE, + ) -> BOOL; + pub fn EncodePointer(Ptr: PVOID) -> PVOID; + pub fn EncodeSystemPointer(Ptr: PVOID) -> PVOID; + pub fn EndUpdateResourceA(hUpdate: HANDLE, fDiscard: BOOL) -> BOOL; + pub fn EndUpdateResourceW(hUpdate: HANDLE, fDiscard: BOOL) -> BOOL; + pub fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); + pub fn EnterSynchronizationBarrier( + lpBarrier: LPSYNCHRONIZATION_BARRIER, dwFlags: DWORD, + ) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn EnterUmsSchedulingMode(SchedulerStartupInfo: PUMS_SCHEDULER_STARTUP_INFO) -> BOOL; + pub fn EnumCalendarInfoA( + lpCalInfoEnumProc: CALINFO_ENUMPROCA, Locale: LCID, Calendar: CALID, CalType: CALTYPE, + ) -> BOOL; + pub fn EnumCalendarInfoExA( + lpCalInfoEnumProcEx: CALINFO_ENUMPROCEXA, Locale: LCID, Calendar: CALID, CalType: CALTYPE, + ) -> BOOL; + pub fn EnumCalendarInfoExEx( + pCalInfoEnumProcExEx: CALINFO_ENUMPROCEXEX, lpLocaleName: LPCWSTR, Calendar: CALID, + lpReserved: LPCWSTR, CalType: CALTYPE, lParam: LPARAM, + ) -> BOOL; + pub fn EnumCalendarInfoExW( + lpCalInfoEnumProcEx: CALINFO_ENUMPROCEXW, Locale: LCID, Calendar: CALID, CalType: CALTYPE, + ) -> BOOL; + pub fn EnumCalendarInfoW( + lpCalInfoEnumProc: CALINFO_ENUMPROCW, Locale: LCID, Calendar: CALID, CalType: CALTYPE, + ) -> BOOL; + pub fn EnumDateFormatsA( + lpDateFmtEnumProc: DATEFMT_ENUMPROCA, Locale: LCID, dwFlags: DWORD, + ) -> BOOL; + pub fn EnumDateFormatsExA( + lpDateFmtEnumProcEx: DATEFMT_ENUMPROCEXA, Locale: LCID, dwFlags: DWORD, + ) -> BOOL; + pub fn EnumDateFormatsExEx( + lpDateFmtEnumProcExEx: DATEFMT_ENUMPROCEXEX, lpLocaleName: LPCWSTR, dwFlags: DWORD, + lParam: LPARAM, + ) -> BOOL; + pub fn EnumDateFormatsExW( + lpDateFmtEnumProcEx: DATEFMT_ENUMPROCEXW, Locale: LCID, dwFlags: DWORD, + ) -> BOOL; + pub fn EnumDateFormatsW( + lpDateFmtEnumProc: DATEFMT_ENUMPROCW, Locale: LCID, dwFlags: DWORD, + ) -> BOOL; + pub fn EnumLanguageGroupLocalesA( + lpLangGroupLocaleEnumProc: LANGGROUPLOCALE_ENUMPROCA, LanguageGroup: LGRPID, dwFlags: DWORD, + lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumLanguageGroupLocalesW( + lpLangGroupLocaleEnumProc: LANGGROUPLOCALE_ENUMPROCW, LanguageGroup: LGRPID, dwFlags: DWORD, + lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumResourceLanguagesA( + hModule: HMODULE, lpType: LPCSTR, lpName: LPCSTR, lpEnumFunc: ENUMRESLANGPROCA, + lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumResourceLanguagesExA( + hModule: HMODULE, lpType: LPCSTR, lpName: LPCSTR, lpEnumFunc: ENUMRESLANGPROCA, + lParam: LONG_PTR, dwFlags: DWORD, LangId: LANGID, + ) -> BOOL; + pub fn EnumResourceLanguagesExW( + hModule: HMODULE, lpType: LPCWSTR, lpName: LPCWSTR, lpEnumFunc: ENUMRESLANGPROCW, + lParam: LONG_PTR, dwFlags: DWORD, LangId: LANGID, + ) -> BOOL; + pub fn EnumResourceLanguagesW( + hModule: HMODULE, lpType: LPCWSTR, lpName: LPCWSTR, lpEnumFunc: ENUMRESLANGPROCW, + lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumResourceNamesA( + hModule: HMODULE, lpType: LPCSTR, lpEnumFunc: ENUMRESNAMEPROCA, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumResourceNamesExA( + hModule: HMODULE, lpType: LPCSTR, lpEnumFunc: ENUMRESNAMEPROCA, lParam: LONG_PTR, + dwFlags: DWORD, LangId: LANGID, + ) -> BOOL; + pub fn EnumResourceNamesExW( + hModule: HMODULE, lpType: LPCWSTR, lpEnumFunc: ENUMRESNAMEPROCW, lParam: LONG_PTR, + dwFlags: DWORD, LangId: LANGID, + ) -> BOOL; + pub fn EnumResourceNamesW( + hModule: HMODULE, lpType: LPCWSTR, lpEnumFunc: ENUMRESNAMEPROCW, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumResourceTypesA( + hModule: HMODULE, lpEnumFunc: ENUMRESTYPEPROCA, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumResourceTypesExA( + hModule: HMODULE, lpEnumFunc: ENUMRESTYPEPROCA, lParam: LONG_PTR, dwFlags: DWORD, + LangId: LANGID, + ) -> BOOL; + pub fn EnumResourceTypesExW( + hModule: HMODULE, lpEnumFunc: ENUMRESTYPEPROCW, lParam: LONG_PTR, dwFlags: DWORD, + LangId: LANGID, + ) -> BOOL; + pub fn EnumResourceTypesW( + hModule: HMODULE, lpEnumFunc: ENUMRESTYPEPROCW, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumSystemCodePagesA(lpCodePageEnumProc: CODEPAGE_ENUMPROCA, dwFlags: DWORD) -> BOOL; + pub fn EnumSystemCodePagesW(lpCodePageEnumProc: CODEPAGE_ENUMPROCW, dwFlags: DWORD) -> BOOL; + pub fn EnumSystemFirmwareTables( + FirmwareTableProviderSignature: DWORD, pFirmwareTableEnumBuffer: PVOID, BufferSize: DWORD, + ) -> UINT; + pub fn EnumSystemGeoID( + GeoClass: GEOCLASS, ParentGeoId: GEOID, lpGeoEnumProc: GEO_ENUMPROC, + ) -> BOOL; + pub fn EnumSystemLanguageGroupsA( + lpLanguageGroupEnumProc: LANGUAGEGROUP_ENUMPROCA, dwFlags: DWORD, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumSystemLanguageGroupsW( + lpLanguageGroupEnumProc: LANGUAGEGROUP_ENUMPROCW, dwFlags: DWORD, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumSystemLocalesA(lpLocaleEnumProc: LOCALE_ENUMPROCA, dwFlags: DWORD) -> BOOL; + pub fn EnumSystemLocalesEx( + lpLocaleEnumProcEx: LOCALE_ENUMPROCEX, dwFlags: DWORD, lParam: LPARAM, lpReserved: LPVOID, + ) -> BOOL; + pub fn EnumSystemLocalesW(lpLocaleEnumProc: LOCALE_ENUMPROCW, dwFlags: DWORD) -> BOOL; + pub fn EnumTimeFormatsA( + lpTimeFmtEnumProc: TIMEFMT_ENUMPROCA, Locale: LCID, dwFlags: DWORD, + ) -> BOOL; + pub fn EnumTimeFormatsEx( + lpTimeFmtEnumProcEx: TIMEFMT_ENUMPROCEX, lpLocaleName: LPCWSTR, dwFlags: DWORD, + lParam: LPARAM, + ) -> BOOL; + pub fn EnumTimeFormatsW( + lpTimeFmtEnumProc: TIMEFMT_ENUMPROCW, Locale: LCID, dwFlags: DWORD, + ) -> BOOL; + pub fn EnumUILanguagesA( + lpUILanguageEnumProc: UILANGUAGE_ENUMPROCA, dwFlags: DWORD, lParam: LONG_PTR, + ) -> BOOL; + pub fn EnumUILanguagesW( + lpUILanguageEnumProc: UILANGUAGE_ENUMPROCW, dwFlags: DWORD, lParam: LONG_PTR, + ) -> BOOL; + // pub fn EnumerateLocalComputerNamesA(); + // pub fn EnumerateLocalComputerNamesW(); + pub fn EraseTape(hDevice: HANDLE, dwEraseType: DWORD, bImmediate: BOOL) -> DWORD; + pub fn EscapeCommFunction(hFile: HANDLE, dwFunc: DWORD) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn ExecuteUmsThread(UmsThread: PUMS_CONTEXT) -> BOOL; + pub fn ExitProcess(uExitCode: UINT); + pub fn ExitThread(dwExitCode: DWORD); + pub fn ExpandEnvironmentStringsA(lpSrc: LPCSTR, lpDst: LPSTR, nSize: DWORD) -> DWORD; + pub fn ExpandEnvironmentStringsW(lpSrc: LPCWSTR, lpDst: LPWSTR, nSize: DWORD) -> DWORD; + pub fn FatalAppExitA(uAction: UINT, lpMessageText: LPCSTR); + pub fn FatalAppExitW(uAction: UINT, lpMessageText: LPCWSTR); + pub fn FatalExit(ExitCode: c_int); + pub fn FileTimeToDosDateTime( + lpFileTime: *const FILETIME, lpFatDate: LPWORD, lpFatTime: LPWORD, + ) -> BOOL; + pub fn FileTimeToLocalFileTime( + lpFileTime: *const FILETIME, lpLocalFileTime: LPFILETIME, + ) -> BOOL; + pub fn FileTimeToSystemTime( + lpFileTime: *const FILETIME, lpSystemTime: LPSYSTEMTIME, + ) -> BOOL; + pub fn FillConsoleOutputAttribute( + hConsoleOutput: HANDLE, wAttribute: WORD, nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfAttrsWritten: LPDWORD, + ) -> BOOL; + pub fn FillConsoleOutputCharacterA( + hConsoleOutput: HANDLE, cCharacter: CHAR, nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfCharsWritten: LPDWORD, + ) -> BOOL; + pub fn FillConsoleOutputCharacterW( + hConsoleOutput: HANDLE, cCharacter: WCHAR, nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfCharsWritten: LPDWORD, + ) -> BOOL; + pub fn FindActCtxSectionGuid( + dwFlags: DWORD, lpExtensionGuid: *const GUID, ulSectionId: ULONG, lpGuidToFind: *const GUID, + ReturnedData: PACTCTX_SECTION_KEYED_DATA, + ) -> BOOL; + pub fn FindActCtxSectionStringA( + dwFlags: DWORD, lpExtensionGuid: *const GUID, ulSectionId: ULONG, lpStringToFind: LPCSTR, + ReturnedData: PACTCTX_SECTION_KEYED_DATA, + ) -> BOOL; + pub fn FindActCtxSectionStringW( + dwFlags: DWORD, lpExtensionGuid: *const GUID, ulSectionId: ULONG, lpStringToFind: LPCWSTR, + ReturnedData: PACTCTX_SECTION_KEYED_DATA, + ) -> BOOL; + pub fn FindAtomA(lpString: LPCSTR) -> ATOM; + pub fn FindAtomW(lpString: LPCWSTR) -> ATOM; + pub fn FindClose(hFindFile: HANDLE) -> BOOL; + pub fn FindCloseChangeNotification(hChangeHandle: HANDLE) -> BOOL; + pub fn FindFirstChangeNotificationA( + lpPathName: LPCSTR, bWatchSubtree: BOOL, dwNotifyFilter: DWORD, + ) -> HANDLE; + pub fn FindFirstChangeNotificationW( + lpPathName: LPCWSTR, bWatchSubtree: BOOL, dwNotifyFilter: DWORD, + ) -> HANDLE; + pub fn FindFirstFileA(lpFileName: LPCSTR, lpFindFileData: LPWIN32_FIND_DATAA) -> HANDLE; + pub fn FindFirstFileExA( + lpFileName: LPCSTR, fInfoLevelId: FINDEX_INFO_LEVELS, lpFindFileData: LPVOID, + fSearchOp: FINDEX_SEARCH_OPS, lpSearchFilter: LPVOID, dwAdditionalFlags: DWORD, + ) -> HANDLE; + pub fn FindFirstFileExW( + lpFileName: LPCWSTR, fInfoLevelId: FINDEX_INFO_LEVELS, lpFindFileData: LPVOID, + fSearchOp: FINDEX_SEARCH_OPS, lpSearchFilter: LPVOID, dwAdditionalFlags: DWORD, + ) -> HANDLE; + pub fn FindFirstFileNameTransactedW( + lpFileName: LPCWSTR, dwFlags: DWORD, StringLength: LPDWORD, LinkName: PWSTR, + hTransaction: HANDLE, + ) -> HANDLE; + pub fn FindFirstFileNameW( + lpFileName: LPCWSTR, dwFlags: DWORD, StringLength: LPDWORD, LinkName: PWSTR, + ) -> HANDLE; + pub fn FindFirstFileTransactedA( + lpFileName: LPCSTR, fInfoLevelId: FINDEX_INFO_LEVELS, lpFindFileData: LPVOID, + fSearchOp: FINDEX_SEARCH_OPS, lpSearchFilter: LPVOID, dwAdditionalFlags: DWORD, + hTransaction: HANDLE, + ) -> HANDLE; + pub fn FindFirstFileTransactedW( + lpFileName: LPCWSTR, fInfoLevelId: FINDEX_INFO_LEVELS, lpFindFileData: LPVOID, + fSearchOp: FINDEX_SEARCH_OPS, lpSearchFilter: LPVOID, dwAdditionalFlags: DWORD, + hTransaction: HANDLE, + ) -> HANDLE; + pub fn FindFirstFileW(lpFileName: LPCWSTR, lpFindFileData: LPWIN32_FIND_DATAW) -> HANDLE; + pub fn FindFirstStreamTransactedW( + lpFileName: LPCWSTR, InfoLevel: STREAM_INFO_LEVELS, lpFindStreamData: LPVOID, + dwFlags: DWORD, hTransaction: HANDLE, + ) -> HANDLE; + pub fn FindFirstStreamW( + lpFileName: LPCWSTR, InfoLevel: STREAM_INFO_LEVELS, lpFindStreamData: LPVOID, + dwFlags: DWORD, + ) -> HANDLE; + pub fn FindFirstVolumeA(lpszVolumeName: LPSTR, cchBufferLength: DWORD) -> HANDLE; + pub fn FindFirstVolumeMountPointA( + lpszRootPathName: LPCSTR, lpszVolumeMountPoint: LPSTR, cchBufferLength: DWORD, + ) -> HANDLE; + pub fn FindFirstVolumeMountPointW( + lpszRootPathName: LPCWSTR, lpszVolumeMountPoint: LPWSTR, cchBufferLength: DWORD, + ) -> HANDLE; + pub fn FindFirstVolumeW(lpszVolumeName: LPWSTR, cchBufferLength: DWORD) -> HANDLE; + pub fn FindNLSString( + Locale: LCID, dwFindNLSStringFlags: DWORD, lpStringSource: LPCWSTR, cchSource: c_int, + lpStringValue: LPCWSTR, cchValue: c_int, pcchFound: LPINT, + ) -> c_int; + pub fn FindNLSStringEx( + lpLocaleName: LPCWSTR, dwFindNLSStringFlags: DWORD, lpStringSource: LPCWSTR, + cchSource: c_int, lpStringValue: LPCWSTR, cchValue: c_int, pcchFound: LPINT, + lpVersionInformation: LPNLSVERSIONINFO, lpReserved: LPVOID, sortHandle: LPARAM, + ) -> c_int; + pub fn FindNextChangeNotification(hChangeHandle: HANDLE) -> BOOL; + pub fn FindNextFileA(hFindFile: HANDLE, lpFindFileData: LPWIN32_FIND_DATAA) -> BOOL; + pub fn FindNextFileNameW(hFindStream: HANDLE, StringLength: LPDWORD, LinkName: PWSTR) -> BOOL; + pub fn FindNextFileW(hFindFile: HANDLE, lpFindFileData: LPWIN32_FIND_DATAW) -> BOOL; + pub fn FindNextStreamW(hFindStream: HANDLE, lpFindStreamData: LPVOID) -> BOOL; + pub fn FindNextVolumeA( + hFindVolume: HANDLE, lpszVolumeName: LPSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn FindNextVolumeMountPointA( + hFindVolumeMountPoint: HANDLE, lpszVolumeMountPoint: LPSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn FindNextVolumeMountPointW( + hFindVolumeMountPoint: HANDLE, lpszVolumeMountPoint: LPWSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn FindNextVolumeW( + hFindVolume: HANDLE, lpszVolumeName: LPWSTR, cchBufferLength: DWORD, + ) -> BOOL; + // pub fn FindPackagesByPackageFamily(); + pub fn FindResourceA(hModule: HMODULE, lpName: LPCSTR, lpType: LPCSTR) -> HRSRC; + pub fn FindResourceExA( + hModule: HMODULE, lpName: LPCSTR, lpType: LPCSTR, wLanguage: WORD, + ) -> HRSRC; + pub fn FindResourceExW( + hModule: HMODULE, lpName: LPCWSTR, lpType: LPCWSTR, wLanguage: WORD, + ) -> HRSRC; + pub fn FindResourceW(hModule: HMODULE, lpName: LPCWSTR, lpType: LPCWSTR) -> HRSRC; + pub fn FindStringOrdinal( + dwFindStringOrdinalFlags: DWORD, lpStringSource: LPCWSTR, cchSource: c_int, + lpStringValue: LPCWSTR, cchValue: c_int, bIgnoreCase: BOOL, + ) -> c_int; + pub fn FindVolumeClose(hFindVolume: HANDLE) -> BOOL; + pub fn FindVolumeMountPointClose(hFindVolumeMountPoint: HANDLE) -> BOOL; + pub fn FlsAlloc(lpCallback: PFLS_CALLBACK_FUNCTION) -> DWORD; + pub fn FlsFree(dwFlsIndex: DWORD) -> BOOL; + pub fn FlsGetValue(dwFlsIndex: DWORD) -> PVOID; + pub fn FlsSetValue(dwFlsIndex: DWORD, lpFlsData: PVOID) -> BOOL; + pub fn FlushConsoleInputBuffer(hConsoleInput: HANDLE) -> BOOL; + pub fn FlushFileBuffers(hFile: HANDLE) -> BOOL; + pub fn FlushInstructionCache(hProcess: HANDLE, lpBaseAddress: LPCVOID, dwSize: SIZE_T) -> BOOL; + pub fn FlushProcessWriteBuffers(); + pub fn FlushViewOfFile(lpBaseAddress: LPCVOID, dwNumberOfBytesToFlush: SIZE_T) -> BOOL; + pub fn FoldStringA( + dwMapFlags: DWORD, lpSrcStr: LPCSTR, cchSrc: c_int, lpDestStr: LPSTR, cchDest: c_int, + ) -> c_int; + pub fn FoldStringW( + dwMapFlags: DWORD, lpSrcStr: LPCWCH, cchSrc: c_int, lpDestStr: LPWSTR, cchDest: c_int, + ) -> c_int; + // pub fn FormatApplicationUserModelId(); + pub fn FormatMessageA( + dwFlags: DWORD, lpSource: LPCVOID, dwMessageId: DWORD, dwLanguageId: DWORD, + lpBuffer: LPSTR, nSize: DWORD, Arguments: *mut va_list, + ) -> DWORD; + pub fn FormatMessageW( + dwFlags: DWORD, lpSource: LPCVOID, dwMessageId: DWORD, dwLanguageId: DWORD, + lpBuffer: LPWSTR, nSize: DWORD, Arguments: *mut va_list, + ) -> DWORD; + pub fn FreeConsole() -> BOOL; + pub fn FreeEnvironmentStringsA(penv: LPCH) -> BOOL; + pub fn FreeEnvironmentStringsW(penv: LPWCH) -> BOOL; + pub fn FreeLibrary(hLibModule: HMODULE) -> BOOL; + pub fn FreeLibraryAndExitThread(hLibModule: HMODULE, dwExitCode: DWORD); + pub fn FreeLibraryWhenCallbackReturns(pci: PTP_CALLBACK_INSTANCE, module: HMODULE); + pub fn FreeResource(hResData: HGLOBAL) -> BOOL; + pub fn FreeUserPhysicalPages( + hProcess: HANDLE, NumberOfPages: PULONG_PTR, PageArray: PULONG_PTR, + ) -> BOOL; + pub fn GenerateConsoleCtrlEvent(dwCtrlEvent: DWORD, dwProcessGroupId: DWORD) -> BOOL; + pub fn GetACP() -> UINT; + pub fn GetActiveProcessorCount(GroupNumber: WORD) -> DWORD; + pub fn GetActiveProcessorGroupCount() -> WORD; + pub fn GetAppContainerAce( + Acl: PACL, StartingAceIndex: DWORD, AppContainerAce: *mut PVOID, + AppContainerAceIndex: *mut DWORD, + ) -> BOOL; + pub fn GetAppContainerNamedObjectPath( + Token: HANDLE, AppContainerSid: PSID, ObjectPathLength: ULONG, ObjectPath: LPWSTR, + ReturnLength: PULONG, + ) -> BOOL; + pub fn GetApplicationRecoveryCallback( + hProcess: HANDLE, pRecoveryCallback: *mut APPLICATION_RECOVERY_CALLBACK, + ppvParameter: *mut PVOID, pdwPingInterval: PDWORD, pdwFlags: PDWORD, + ) -> HRESULT; + pub fn GetApplicationRestartSettings( + hProcess: HANDLE, pwzCommandline: PWSTR, pcchSize: PDWORD, pdwFlags: PDWORD, + ) -> HRESULT; + // pub fn GetApplicationUserModelId(); + pub fn GetAtomNameA(nAtom: ATOM, lpBuffer: LPSTR, nSize: c_int) -> UINT; + pub fn GetAtomNameW(nAtom: ATOM, lpBuffer: LPWSTR, nSize: c_int) -> UINT; + pub fn GetBinaryTypeA(lpApplicationName: LPCSTR, lpBinaryType: LPDWORD) -> BOOL; + pub fn GetBinaryTypeW(lpApplicationName: LPCWSTR, lpBinaryType: LPDWORD) -> BOOL; + pub fn GetCPInfo(CodePage: UINT, lpCPInfo: LPCPINFO) -> BOOL; + pub fn GetCPInfoExA(CodePage: UINT, dwFlags: DWORD, lpCPInfoEx: LPCPINFOEXA) -> BOOL; + pub fn GetCPInfoExW(CodePage: UINT, dwFlags: DWORD, lpCPInfoEx: LPCPINFOEXW) -> BOOL; + pub fn GetCachedSigningLevel( + File: HANDLE, Flags: PULONG, SigningLevel: PULONG, Thumbprint: PUCHAR, + ThumbprintSize: PULONG, ThumbprintAlgorithm: PULONG, + ) -> BOOL; + pub fn GetCalendarInfoA( + Locale: LCID, Calendar: CALID, CalType: CALTYPE, lpCalData: LPSTR, cchData: c_int, + lpValue: LPDWORD, + ) -> c_int; + pub fn GetCalendarInfoEx( + lpLocaleName: LPCWSTR, Calendar: CALID, lpReserved: LPCWSTR, CalType: CALTYPE, + lpCalData: LPWSTR, cchData: c_int, lpValue: LPDWORD, + ) -> c_int; + pub fn GetCalendarInfoW( + Locale: LCID, Calendar: CALID, CalType: CALTYPE, lpCalData: LPWSTR, cchData: c_int, + lpValue: LPDWORD, + ) -> c_int; + pub fn GetCommConfig(hCommDev: HANDLE, lpCC: LPCOMMCONFIG, lpdwSize: LPDWORD) -> BOOL; + pub fn GetCommMask(hFile: HANDLE, lpEvtMask: LPDWORD) -> BOOL; + pub fn GetCommModemStatus(hFile: HANDLE, lpModemStat: LPDWORD) -> BOOL; + pub fn GetCommProperties(hFile: HANDLE, lpCommProp: LPCOMMPROP) -> BOOL; + pub fn GetCommState(hFile: HANDLE, lpDCB: LPDCB) -> BOOL; + pub fn GetCommTimeouts(hFile: HANDLE, lpCommTimeouts: LPCOMMTIMEOUTS) -> BOOL; + pub fn GetCommandLineA() -> LPSTR; + pub fn GetCommandLineW() -> LPWSTR; + pub fn GetCompressedFileSizeA(lpFileName: LPCSTR, lpFileSizeHigh: LPDWORD) -> DWORD; + pub fn GetCompressedFileSizeTransactedA( + lpFileName: LPCSTR, lpFileSizeHigh: LPDWORD, hTransaction: HANDLE, + ) -> DWORD; + pub fn GetCompressedFileSizeTransactedW( + lpFileName: LPCWSTR, lpFileSizeHigh: LPDWORD, hTransaction: HANDLE, + ); + pub fn GetCompressedFileSizeW(lpFileName: LPCWSTR, lpFileSizeHigh: LPDWORD) -> DWORD; + pub fn GetComputerNameA(lpBuffer: LPSTR, nSize: LPDWORD) -> BOOL; + pub fn GetComputerNameExA( + NameType: COMPUTER_NAME_FORMAT, lpBuffer: LPSTR, nSize: LPDWORD, + ) -> BOOL; + pub fn GetComputerNameExW( + NameType: COMPUTER_NAME_FORMAT, lpBuffer: LPWSTR, nSize: LPDWORD, + ) -> BOOL; + pub fn GetComputerNameW(lpBuffer: LPWSTR, nSize: LPDWORD) -> BOOL; + pub fn GetConsoleAliasA( + Source: LPSTR, TargetBuffer: LPSTR, TargetBufferLength: DWORD, ExeName: LPSTR, + ) -> DWORD; + pub fn GetConsoleAliasExesA(ExeNameBuffer: LPSTR, ExeNameBufferLength: DWORD) -> DWORD; + pub fn GetConsoleAliasExesLengthA() -> DWORD; + pub fn GetConsoleAliasExesLengthW() -> DWORD; + pub fn GetConsoleAliasExesW(ExeNameBuffer: LPWSTR, ExeNameBufferLength: DWORD) -> DWORD; + pub fn GetConsoleAliasW( + Source: LPWSTR, TargetBuffer: LPWSTR, TargetBufferLength: DWORD, ExeName: LPWSTR, + ) -> DWORD; + pub fn GetConsoleAliasesA( + AliasBuffer: LPSTR, AliasBufferLength: DWORD, ExeName: LPSTR, + ) -> DWORD; + pub fn GetConsoleAliasesLengthA(ExeName: LPSTR) -> DWORD; + pub fn GetConsoleAliasesLengthW(ExeName: LPWSTR) -> DWORD; + pub fn GetConsoleAliasesW( + AliasBuffer: LPWSTR, AliasBufferLength: DWORD, ExeName: LPWSTR, + ) -> DWORD; + pub fn GetConsoleCP() -> UINT; + pub fn GetConsoleCursorInfo( + hConsoleOutput: HANDLE, lpConsoleCursorInfo: PCONSOLE_CURSOR_INFO, + ) -> BOOL; + pub fn GetConsoleDisplayMode(lpModeFlags: LPDWORD) -> BOOL; + pub fn GetConsoleFontSize(hConsoleOutput: HANDLE, nFont: DWORD) -> COORD; + pub fn GetConsoleHistoryInfo(lpConsoleHistoryInfo: PCONSOLE_HISTORY_INFO) -> BOOL; + pub fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL; + pub fn GetConsoleOriginalTitleA(lpConsoleTitle: LPSTR, nSize: DWORD) -> DWORD; + pub fn GetConsoleOriginalTitleW(lpConsoleTitle: LPWSTR, nSize: DWORD) -> DWORD; + pub fn GetConsoleOutputCP() -> UINT; + pub fn GetConsoleProcessList(lpdwProcessList: LPDWORD, dwProcessCount: DWORD) -> DWORD; + pub fn GetConsoleScreenBufferInfo( + hConsoleOutput: HANDLE, lpConsoleScreenBufferInfo: PCONSOLE_SCREEN_BUFFER_INFO, + ) -> BOOL; + pub fn GetConsoleScreenBufferInfoEx( + hConsoleOutput: HANDLE, lpConsoleScreenBufferInfoEx: PCONSOLE_SCREEN_BUFFER_INFOEX, + ) -> BOOL; + pub fn GetConsoleSelectionInfo(lpConsoleSelectionInfo: PCONSOLE_SELECTION_INFO) -> BOOL; + pub fn GetConsoleTitleA(lpConsoleTitle: LPSTR, nSize: DWORD) -> DWORD; + pub fn GetConsoleTitleW(lpConsoleTitle: LPWSTR, nSize: DWORD) -> DWORD; + pub fn GetConsoleWindow() -> HWND; + pub fn GetCurrencyFormatA( + Locale: LCID, dwFlags: DWORD, lpValue: LPCSTR, lpFormat: *const CURRENCYFMTA, + lpCurrencyStr: LPSTR, cchCurrency: c_int, + ) -> c_int; + pub fn GetCurrencyFormatEx( + lpLocaleName: LPCWSTR, dwFlags: DWORD, lpValue: LPCWSTR, lpFormat: *const CURRENCYFMTW, + lpCurrencyStr: LPWSTR, cchCurrency: c_int, + ) -> c_int; + pub fn GetCurrencyFormatW( + Locale: LCID, dwFlags: DWORD, lpValue: LPCWSTR, lpFormat: *const CURRENCYFMTW, + lpCurrencyStr: LPWSTR, cchCurrency: c_int, + ) -> c_int; + pub fn GetCurrentActCtx(lphActCtx: *mut HANDLE) -> BOOL; + // pub fn GetCurrentApplicationUserModelId(); + pub fn GetCurrentConsoleFont( + hConsoleOutput: HANDLE, bMaximumWindow: BOOL, lpConsoleCurrentFont: PCONSOLE_FONT_INFO, + ) -> BOOL; + pub fn GetCurrentConsoleFontEx( + hConsoleOutput: HANDLE, bMaximumWindow: BOOL, lpConsoleCurrentFontEx: PCONSOLE_FONT_INFOEX, + ) -> BOOL; + pub fn GetCurrentDirectoryA(nBufferLength: DWORD, lpBuffer: LPSTR) -> DWORD; + pub fn GetCurrentDirectoryW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD; + // pub fn GetCurrentPackageFamilyName(); + // pub fn GetCurrentPackageFullName(); + // pub fn GetCurrentPackageId(); + // pub fn GetCurrentPackageInfo(); + // pub fn GetCurrentPackagePath(); + pub fn GetCurrentProcess() -> HANDLE; + pub fn GetCurrentProcessId() -> DWORD; + pub fn GetCurrentProcessorNumber() -> DWORD; + pub fn GetCurrentProcessorNumberEx(ProcNumber: PPROCESSOR_NUMBER); + pub fn GetCurrentThread() -> HANDLE; + pub fn GetCurrentThreadId() -> DWORD; + pub fn GetCurrentThreadStackLimits(LowLimit: PULONG_PTR, HighLimit: PULONG_PTR); + #[cfg(target_arch = "x86_64")] + pub fn GetCurrentUmsThread() -> PUMS_CONTEXT; + pub fn GetDateFormatA( + Locale: LCID, dwFlags: DWORD, lpDate: *const SYSTEMTIME, lpFormat: LPCSTR, lpDateStr: LPSTR, + cchDate: c_int, + ) -> c_int; + pub fn GetDateFormatEx( + lpLocaleName: LPCWSTR, dwFlags: DWORD, lpDate: *const SYSTEMTIME, lpFormat: LPCWSTR, + lpDateStr: LPWSTR, cchDate: c_int, lpCalendar: LPCWSTR, + ) -> c_int; + pub fn GetDateFormatW( + Locale: LCID, dwFlags: DWORD, lpDate: *const SYSTEMTIME, lpFormat: LPCWSTR, + lpDateStr: LPWSTR, cchDate: c_int, + ) -> c_int; + pub fn GetDefaultCommConfigA(lpszName: LPCSTR, lpCC: LPCOMMCONFIG, lpdwSize: LPDWORD) -> BOOL; + pub fn GetDefaultCommConfigW(lpszName: LPCWSTR, lpCC: LPCOMMCONFIG, lpdwSize: LPDWORD) -> BOOL; + pub fn GetDevicePowerState(hDevice: HANDLE, pfOn: *mut BOOL) -> BOOL; + pub fn GetDiskFreeSpaceA( + lpRootPathName: LPCSTR, lpSectorsPerCluster: LPDWORD, lpBytesPerSector: LPDWORD, + lpNumberOfFreeClusters: LPDWORD, lpTotalNumberOfClusters: LPDWORD, + ) -> BOOL; + pub fn GetDiskFreeSpaceExA( + lpDirectoryName: LPCSTR, lpFreeBytesAvailableToCaller: PULARGE_INTEGER, + lpTotalNumberOfBytes: PULARGE_INTEGER, lpTotalNumberOfFreeBytes: PULARGE_INTEGER, + ) -> BOOL; + pub fn GetDiskFreeSpaceExW( + lpDirectoryName: LPCWSTR, lpFreeBytesAvailableToCaller: PULARGE_INTEGER, + lpTotalNumberOfBytes: PULARGE_INTEGER, lpTotalNumberOfFreeBytes: PULARGE_INTEGER, + ) -> BOOL; + pub fn GetDiskFreeSpaceW( + lpRootPathName: LPCWSTR, lpSectorsPerCluster: LPDWORD, lpBytesPerSector: LPDWORD, + lpNumberOfFreeClusters: LPDWORD, lpTotalNumberOfClusters: LPDWORD, + ) -> BOOL; + pub fn GetDllDirectoryA(nBufferLength: DWORD, lpBuffer: LPSTR) -> DWORD; + pub fn GetDllDirectoryW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD; + pub fn GetDriveTypeA(lpRootPathName: LPCSTR) -> UINT; + pub fn GetDriveTypeW(lpRootPathName: LPCWSTR) -> UINT; + pub fn GetDurationFormat( + Locale: LCID, dwFlags: DWORD, lpDuration: *const SYSTEMTIME, ullDuration: ULONGLONG, + lpFormat: LPCWSTR, lpDurationStr: LPWSTR, cchDuration: c_int, + ) -> c_int; + pub fn GetDurationFormatEx( + lpLocaleName: LPCWSTR, dwFlags: DWORD, lpDuration: *const SYSTEMTIME, + ullDuration: ULONGLONG, lpFormat: LPCWSTR, lpDurationStr: LPWSTR, cchDuration: c_int, + ) -> c_int; + pub fn GetDynamicTimeZoneInformation( + pTimeZoneInformation: PDYNAMIC_TIME_ZONE_INFORMATION, + ) -> DWORD; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + pub fn GetEnabledXStateFeatures() -> DWORD64; + pub fn GetEnvironmentStrings() -> LPCH; + pub fn GetEnvironmentStringsW() -> LPWCH; + pub fn GetEnvironmentVariableA(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD) -> DWORD; + pub fn GetEnvironmentVariableW(lpName: LPCWSTR, lpBuffer: LPWSTR, nSize: DWORD) -> DWORD; + // pub fn GetEraNameCountedString(); + pub fn GetErrorMode() -> UINT; + pub fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: LPDWORD) -> BOOL; + pub fn GetExitCodeThread(hThread: HANDLE, lpExitCode: LPDWORD) -> BOOL; + pub fn GetFileAttributesA(lpFileName: LPCSTR) -> DWORD; + pub fn GetFileAttributesExA( + lpFileName: LPCSTR, fInfoLevelId: GET_FILEEX_INFO_LEVELS, lpFileInformation: LPVOID, + ) -> BOOL; + pub fn GetFileAttributesExW( + lpFileName: LPCWSTR, fInfoLevelId: GET_FILEEX_INFO_LEVELS, lpFileInformation: LPVOID, + ) -> BOOL; + pub fn GetFileAttributesTransactedA( + lpFileName: LPCSTR, fInfoLevelId: GET_FILEEX_INFO_LEVELS, lpFileInformation: LPVOID, + hTransaction: HANDLE, + ) -> BOOL; + pub fn GetFileAttributesTransactedW( + lpFileName: LPCWSTR, fInfoLevelId: GET_FILEEX_INFO_LEVELS, lpFileInformation: LPVOID, + hTransaction: HANDLE, + ) -> BOOL; + pub fn GetFileAttributesW(lpFileName: LPCWSTR) -> DWORD; + pub fn GetFileBandwidthReservation( + hFile: HANDLE, lpPeriodMilliseconds: LPDWORD, lpBytesPerPeriod: LPDWORD, + pDiscardable: LPBOOL, lpTransferSize: LPDWORD, lpNumOutstandingRequests: LPDWORD, + ) -> BOOL; + pub fn GetFileInformationByHandle( + hFile: HANDLE, lpFileInformation: LPBY_HANDLE_FILE_INFORMATION, + ) -> BOOL; + pub fn GetFileInformationByHandleEx( + hFile: HANDLE, FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, lpFileInformation: LPVOID, + dwBufferSize: DWORD, + ) -> BOOL; + pub fn GetFileMUIInfo( + dwFlags: DWORD, pcwszFilePath: PCWSTR, pFileMUIInfo: PFILEMUIINFO, + pcbFileMUIInfo: *mut DWORD, + ) -> BOOL; + pub fn GetFileMUIPath( + dwFlags: DWORD, pcwszFilePath: PCWSTR, pwszLanguage: PWSTR, pcchLanguage: PULONG, + pwszFileMUIPath: PWSTR, pcchFileMUIPath: PULONG, pululEnumerator: PULONGLONG, + ) -> BOOL; + pub fn GetFileSize(hFile: HANDLE, lpFileSizeHigh: LPDWORD) -> DWORD; + pub fn GetFileSizeEx(hFile: HANDLE, lpFileSize: PLARGE_INTEGER) -> BOOL; + pub fn GetFileTime( + hFile: HANDLE, lpCreationTime: LPFILETIME, lpLastAccessTime: LPFILETIME, + lpLastWriteTime: LPFILETIME, + ) -> BOOL; + pub fn GetFileType(hFile: HANDLE) -> DWORD; + pub fn GetFinalPathNameByHandleA( + hFile: HANDLE, lpszFilePath: LPSTR, cchFilePath: DWORD, dwFlags: DWORD, + ) -> DWORD; + pub fn GetFinalPathNameByHandleW( + hFile: HANDLE, lpszFilePath: LPWSTR, cchFilePath: DWORD, dwFlags: DWORD, + ) -> DWORD; + pub fn GetFirmwareEnvironmentVariableA( + lpName: LPCSTR, lpGuid: LPCSTR, pBuffer: PVOID, nSize: DWORD, + ) -> DWORD; + pub fn GetFirmwareEnvironmentVariableExA( + lpName: LPCSTR, lpGuid: LPCSTR, pBuffer: PVOID, nSize: DWORD, pdwAttribubutes: PDWORD, + ) -> DWORD; + pub fn GetFirmwareEnvironmentVariableExW( + lpName: LPCWSTR, lpGuid: LPCWSTR, pBuffer: PVOID, nSize: DWORD, pdwAttribubutes: PDWORD, + ) -> DWORD; + pub fn GetFirmwareEnvironmentVariableW( + lpName: LPCWSTR, lpGuid: LPCWSTR, pBuffer: PVOID, nSize: DWORD, + ) -> DWORD; + pub fn GetFirmwareType(FirmwareType: PFIRMWARE_TYPE) -> BOOL; + pub fn GetFullPathNameA( + lpFileName: LPCSTR, nBufferLength: DWORD, lpBuffer: LPSTR, lpFilePart: *mut LPSTR, + ) -> DWORD; + pub fn GetFullPathNameTransactedA( + lpFileName: LPCSTR, nBufferLength: DWORD, lpBuffer: LPSTR, lpFilePart: *mut LPSTR, + hTransaction: HANDLE, + ) -> DWORD; + pub fn GetFullPathNameTransactedW( + lpFileName: LPCWSTR, nBufferLength: DWORD, lpBuffer: LPWSTR, lpFilePart: *mut LPWSTR, + hTransaction: HANDLE, + ); + pub fn GetFullPathNameW( + lpFileName: LPCWSTR, nBufferLength: DWORD, lpBuffer: LPWSTR, lpFilePart: *mut LPWSTR, + ) -> DWORD; + pub fn GetGeoInfoA( + Location: GEOID, GeoType: GEOTYPE, lpGeoData: LPSTR, cchData: c_int, LangId: LANGID, + ) -> c_int; + pub fn GetGeoInfoW( + Location: GEOID, GeoType: GEOTYPE, lpGeoData: LPWSTR, cchData: c_int, LangId: LANGID, + ) -> c_int; + pub fn GetHandleInformation(hObject: HANDLE, lpdwFlags: LPDWORD) -> BOOL; + pub fn GetLargePageMinimum() -> SIZE_T; + pub fn GetLargestConsoleWindowSize(hConsoleOutput: HANDLE) -> COORD; + pub fn GetLastError() -> DWORD; + pub fn GetLocalTime(lpSystemTime: LPSYSTEMTIME); + pub fn GetLocaleInfoA( + Locale: LCID, LCType: LCTYPE, lpLCData: LPSTR, cchData: c_int, + ) -> c_int; + pub fn GetLocaleInfoEx( + lpLocaleName: LPCWSTR, LCType: LCTYPE, lpLCData: LPWSTR, cchData: c_int, + ) -> c_int; + pub fn GetLocaleInfoW( + Locale: LCID, LCType: LCTYPE, lpLCData: LPWSTR, cchData: c_int, + ) -> c_int; + pub fn GetLogicalDriveStringsA(nBufferLength: DWORD, lpBuffer: LPSTR) -> DWORD; + pub fn GetLogicalDriveStringsW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD; + pub fn GetLogicalDrives() -> DWORD; + pub fn GetLogicalProcessorInformation( + Buffer: PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, ReturnedLength: PDWORD, + ) -> BOOL; + pub fn GetLogicalProcessorInformationEx( + RelationshipType: LOGICAL_PROCESSOR_RELATIONSHIP, + Buffer: PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, + ReturnedLength: PDWORD, + ) -> BOOL; + pub fn GetLongPathNameA(lpszShortPath: LPCSTR, lpszLongPath: LPSTR, cchBuffer: DWORD) -> DWORD; + pub fn GetLongPathNameTransactedA( + lpszShortPath: LPCSTR, lpszLongPath: LPSTR, cchBuffer: DWORD, hTransaction: HANDLE, + ) -> DWORD; + pub fn GetLongPathNameTransactedW( + lpszShortPath: LPCWSTR, lpszLongPath: LPWSTR, cchBuffer: DWORD, hTransaction: HANDLE, + ) -> DWORD; + pub fn GetLongPathNameW( + lpszShortPath: LPCWSTR, lpszLongPath: LPWSTR, cchBuffer: DWORD, + ) -> DWORD; + pub fn GetMailslotInfo( + hMailslot: HANDLE, lpMaxMessageSize: LPDWORD, lpNextSize: LPDWORD, lpMessageCount: LPDWORD, + lpReadTimeout: LPDWORD, + ) -> BOOL; + pub fn GetMaximumProcessorCount(GroupNumber: WORD) -> DWORD; + pub fn GetMaximumProcessorGroupCount() -> WORD; + pub fn GetMemoryErrorHandlingCapabilities(Capabilities: PULONG) -> BOOL; + pub fn GetModuleFileNameA( + hModule: HMODULE, lpFilename: LPSTR, nSize: DWORD, + ) -> DWORD; + pub fn GetModuleFileNameW( + hModule: HMODULE, lpFilename: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn GetModuleHandleA(lpModuleName: LPCSTR) -> HMODULE; + pub fn GetModuleHandleExA( + dwFlags: DWORD, lpModuleName: LPCSTR, phModule: *mut HMODULE, + ) -> BOOL; + pub fn GetModuleHandleExW( + dwFlags: DWORD, lpModuleName: LPCWSTR, phModule: *mut HMODULE, + ) -> BOOL; + pub fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; + pub fn GetNLSVersion( + Function: NLS_FUNCTION, Locale: LCID, lpVersionInformation: LPNLSVERSIONINFO, + ) -> BOOL; + pub fn GetNLSVersionEx( + function: NLS_FUNCTION, lpLocaleName: LPCWSTR, lpVersionInformation: LPNLSVERSIONINFOEX, + ) -> BOOL; + // pub fn GetNamedPipeAttribute(); + pub fn GetNamedPipeClientComputerNameA( + Pipe: HANDLE, ClientComputerName: LPSTR, ClientComputerNameLength: ULONG, + ) -> BOOL; + pub fn GetNamedPipeClientComputerNameW( + Pipe: HANDLE, ClientComputerName: LPWSTR, ClientComputerNameLength: ULONG, + ) -> BOOL; + pub fn GetNamedPipeClientProcessId(Pipe: HANDLE, ClientProcessId: PULONG) -> BOOL; + pub fn GetNamedPipeClientSessionId(Pipe: HANDLE, ClientSessionId: PULONG) -> BOOL; + pub fn GetNamedPipeHandleStateA( + hNamedPipe: HANDLE, lpState: LPDWORD, lpCurInstances: LPDWORD, + lpMaxCollectionCount: LPDWORD, lpCollectDataTimeout: LPDWORD, lpUserName: LPSTR, + nMaxUserNameSize: DWORD, + ) -> BOOL; + pub fn GetNamedPipeHandleStateW( + hNamedPipe: HANDLE, lpState: LPDWORD, lpCurInstances: LPDWORD, + lpMaxCollectionCount: LPDWORD, lpCollectDataTimeout: LPDWORD, lpUserName: LPWSTR, + nMaxUserNameSize: DWORD, + ) -> BOOL; + pub fn GetNamedPipeInfo( + hNamedPipe: HANDLE, lpFlags: LPDWORD, lpOutBufferSize: LPDWORD, lpInBufferSize: LPDWORD, + lpMaxInstances: LPDWORD, + ) -> BOOL; + pub fn GetNamedPipeServerProcessId(Pipe: HANDLE, ServerProcessId: PULONG) -> BOOL; + pub fn GetNamedPipeServerSessionId(Pipe: HANDLE, ServerSessionId: PULONG) -> BOOL; + pub fn GetNativeSystemInfo(lpSystemInfo: LPSYSTEM_INFO); + #[cfg(target_arch = "x86_64")] + pub fn GetNextUmsListItem(UmsContext: PUMS_CONTEXT) -> PUMS_CONTEXT; + pub fn GetNumaAvailableMemoryNode(Node: UCHAR, AvailableBytes: PULONGLONG) -> BOOL; + pub fn GetNumaAvailableMemoryNodeEx(Node: USHORT, AvailableBytes: PULONGLONG) -> BOOL; + pub fn GetNumaHighestNodeNumber(HighestNodeNumber: PULONG) -> BOOL; + pub fn GetNumaNodeNumberFromHandle(hFile: HANDLE, NodeNumber: PUSHORT) -> BOOL; + pub fn GetNumaNodeProcessorMask(Node: UCHAR, ProcessorMask: PULONGLONG) -> BOOL; + pub fn GetNumaNodeProcessorMaskEx(Node: USHORT, ProcessorMask: PGROUP_AFFINITY) -> BOOL; + pub fn GetNumaProcessorNode(Processor: UCHAR, NodeNumber: PUCHAR) -> BOOL; + pub fn GetNumaProcessorNodeEx(Processor: PPROCESSOR_NUMBER, NodeNumber: PUSHORT) -> BOOL; + pub fn GetNumaProximityNode(ProximityId: ULONG, NodeNumber: PUCHAR) -> BOOL; + pub fn GetNumaProximityNodeEx(ProximityId: ULONG, NodeNumber: PUSHORT) -> BOOL; + pub fn GetNumberFormatA( + Locale: LCID, dwFlags: DWORD, lpValue: LPCSTR, lpFormat: *const NUMBERFMTA, + lpNumberStr: LPSTR, cchNumber: c_int, + ) -> c_int; + pub fn GetNumberFormatEx( + lpLocaleName: LPCWSTR, dwFlags: DWORD, lpValue: LPCWSTR, lpFormat: *const NUMBERFMTW, + lpNumberStr: LPWSTR, cchNumber: c_int, + ) -> c_int; + pub fn GetNumberFormatW( + Locale: LCID, dwFlags: DWORD, lpValue: LPCWSTR, lpFormat: *const NUMBERFMTW, + lpNumberStr: LPWSTR, cchNumber: c_int, + ) -> c_int; + pub fn GetNumberOfConsoleInputEvents(hConsoleInput: HANDLE, lpNumberOfEvents: LPDWORD) -> BOOL; + pub fn GetNumberOfConsoleMouseButtons(lpNumberOfMouseButtons: LPDWORD) -> BOOL; + pub fn GetOEMCP() -> UINT; + pub fn GetOverlappedResult( + hFile: HANDLE, lpOverlapped: LPOVERLAPPED, lpNumberOfBytesTransferred: LPDWORD, bWait: BOOL, + ) -> BOOL; + pub fn GetOverlappedResultEx( + hFile: HANDLE, lpOverlapped: LPOVERLAPPED, lpNumberOfBytesTransferred: LPDWORD, + dwMilliseconds: DWORD, bAlertable: BOOL, + ) -> BOOL; + // pub fn GetPackageApplicationIds(); + // pub fn GetPackageFamilyName(); + // pub fn GetPackageFullName(); + // pub fn GetPackageId(); + // pub fn GetPackageInfo(); + // pub fn GetPackagePath(); + // pub fn GetPackagePathByFullName(); + // pub fn GetPackagesByPackageFamily(); + pub fn GetPhysicallyInstalledSystemMemory(TotalMemoryInKilobytes: PULONGLONG) -> BOOL; + pub fn GetPriorityClass(hProcess: HANDLE) -> DWORD; + pub fn GetPrivateProfileIntA( + lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: INT, lpFileName: LPCSTR, + ) -> UINT; + pub fn GetPrivateProfileIntW( + lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: INT, lpFileName: LPCWSTR, + ) -> UINT; + pub fn GetPrivateProfileSectionA( + lpAppName: LPCSTR, lpReturnedString: LPSTR, nSize: DWORD, lpFileName: LPCSTR, + ) -> DWORD; + pub fn GetPrivateProfileSectionNamesA( + lpszReturnBuffer: LPSTR, nSize: DWORD, lpFileName: LPCSTR, + ) -> DWORD; + pub fn GetPrivateProfileSectionNamesW( + lpszReturnBuffer: LPWSTR, nSize: DWORD, lpFileName: LPCWSTR, + ) -> DWORD; + pub fn GetPrivateProfileSectionW( + lpAppName: LPCWSTR, lpReturnedString: LPWSTR, nSize: DWORD, lpFileName: LPCWSTR, + ) -> DWORD; + pub fn GetPrivateProfileStringA( + lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, lpReturnedString: LPSTR, + nSize: DWORD, lpFileName: LPCSTR, + ) -> DWORD; + pub fn GetPrivateProfileStringW( + lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpDefault: LPCWSTR, lpReturnedString: LPWSTR, + nSize: DWORD, lpFileName: LPCWSTR, + ) -> DWORD; + pub fn GetPrivateProfileStructA( + lpszSection: LPCSTR, lpszKey: LPCSTR, lpStruct: LPVOID, uSizeStruct: UINT, szFile: LPCSTR, + ) -> BOOL; + pub fn GetPrivateProfileStructW( + lpszSection: LPCWSTR, lpszKey: LPCWSTR, lpStruct: LPVOID, uSizeStruct: UINT, + szFile: LPCWSTR, + ) -> BOOL; + pub fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> FARPROC; + pub fn GetProcessAffinityMask( + hProcess: HANDLE, lpProcessAffinityMask: PDWORD_PTR, lpSystemAffinityMask: PDWORD_PTR, + ) -> BOOL; + pub fn GetProcessDEPPolicy(hProcess: HANDLE, lpFlags: LPDWORD, lpPermanent: PBOOL) -> BOOL; + pub fn GetProcessGroupAffinity( + hProcess: HANDLE, GroupCount: PUSHORT, GroupArray: PUSHORT, + ) -> BOOL; + pub fn GetProcessHandleCount(hProcess: HANDLE, pdwHandleCount: PDWORD) -> BOOL; + pub fn GetProcessHeap() -> HANDLE; + pub fn GetProcessHeaps(NumberOfHeaps: DWORD, ProcessHeaps: PHANDLE) -> DWORD; + pub fn GetProcessId(Process: HANDLE) -> DWORD; + pub fn GetProcessIdOfThread(Thread: HANDLE) -> DWORD; + pub fn GetProcessInformation( + hProcess: HANDLE, ProcessInformationClass: PROCESS_INFORMATION_CLASS, + ProcessInformation: LPVOID, ProcessInformationSize: DWORD, + ) -> BOOL; + pub fn GetProcessIoCounters(hProcess: HANDLE, lpIoCounters: PIO_COUNTERS) -> BOOL; + pub fn GetProcessMitigationPolicy( + hProcess: HANDLE, MitigationPolicy: PROCESS_MITIGATION_POLICY, lpBuffer: PVOID, + dwLength: SIZE_T, + ) -> BOOL; + pub fn GetProcessPreferredUILanguages( + dwFlags: DWORD, pulNumLanguages: PULONG, pwszLanguagesBuffer: PZZWSTR, + pcchLanguagesBuffer: PULONG, + ) -> BOOL; + pub fn GetProcessPriorityBoost(hProcess: HANDLE, pDisablePriorityBoost: PBOOL) -> BOOL; + pub fn GetProcessShutdownParameters(lpdwLevel: LPDWORD, lpdwFlags: LPDWORD) -> BOOL; + pub fn GetProcessTimes( + hProcess: HANDLE, lpCreationTime: LPFILETIME, lpExitTime: LPFILETIME, + lpKernelTime: LPFILETIME, lpUserTime: LPFILETIME, + ) -> BOOL; + pub fn GetProcessVersion(ProcessId: DWORD) -> DWORD; + pub fn GetProcessWorkingSetSize( + hProcess: HANDLE, lpMinimumWorkingSetSize: PSIZE_T, lpMaximumWorkingSetSize: PSIZE_T, + ) -> BOOL; + pub fn GetProcessWorkingSetSizeEx( + hProcess: HANDLE, lpMinimumWorkingSetSize: PSIZE_T, lpMaximumWorkingSetSize: PSIZE_T, + Flags: PDWORD, + ) -> BOOL; + pub fn GetProcessorSystemCycleTime( + Group: USHORT, Buffer: PSYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION, ReturnedLength: PDWORD, + ) -> BOOL; + pub fn GetProductInfo( + dwOSMajorVersion: DWORD, dwOSMinorVersion: DWORD, dwSpMajorVersion: DWORD, + dwSpMinorVersion: DWORD, pdwReturnedProductType: PDWORD, + ) -> BOOL; + pub fn GetProfileIntA(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: INT) -> UINT; + pub fn GetProfileIntW(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: INT) -> UINT; + pub fn GetProfileSectionA(lpAppName: LPCSTR, lpReturnedString: LPSTR, nSize: DWORD) -> DWORD; + pub fn GetProfileSectionW(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, nSize: DWORD) -> DWORD; + pub fn GetProfileStringA( + lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, lpReturnedString: LPSTR, + nSize: DWORD, + ) -> DWORD; + pub fn GetProfileStringW( + lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpDefault: LPCWSTR, lpReturnedString: LPWSTR, + nSize: DWORD, + ) -> DWORD; + pub fn GetQueuedCompletionStatus( + CompletionPort: HANDLE, lpNumberOfBytesTransferred: LPDWORD, lpCompletionKey: PULONG_PTR, + lpOverlapped: *mut LPOVERLAPPED, dwMilliseconds: DWORD, + ) -> BOOL; + pub fn GetQueuedCompletionStatusEx( + CompletionPort: HANDLE, lpCompletionPortEntries: LPOVERLAPPED_ENTRY, ulCount: ULONG, + ulNumEntriesRemoved: PULONG, dwMilliseconds: DWORD, fAlertable: BOOL, + ) -> BOOL; + pub fn GetShortPathNameA( + lpszLongPath: LPCSTR, lpszShortPath: LPSTR, cchBuffer: DWORD, + ) -> DWORD; + pub fn GetShortPathNameW( + lpszLongPath: LPCWSTR, lpszShortPath: LPWSTR, cchBuffer: DWORD, + ) -> DWORD; + // pub fn GetStagedPackagePathByFullName(); + pub fn GetStartupInfoA(lpStartupInfo: LPSTARTUPINFOA); + pub fn GetStartupInfoW(lpStartupInfo: LPSTARTUPINFOW); + // pub fn GetStateFolder(); + pub fn GetStdHandle(nStdHandle: DWORD) -> HANDLE; + pub fn GetStringScripts( + dwFlags: DWORD, lpString: LPCWSTR, cchString: c_int, lpScripts: LPWSTR, cchScripts: c_int, + ) -> c_int; + pub fn GetStringTypeA( + Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, cchSrc: c_int, lpCharType: LPWORD, + ) -> BOOL; + pub fn GetStringTypeExA( + Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, cchSrc: c_int, lpCharType: LPWORD, + ) -> BOOL; + pub fn GetStringTypeExW( + Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCWCH, cchSrc: c_int, lpCharType: LPWORD, + ) -> BOOL; + pub fn GetStringTypeW( + dwInfoType: DWORD, lpSrcStr: LPCWCH, cchSrc: c_int, lpCharType: LPWORD, + ) -> BOOL; + // pub fn GetSystemAppDataKey(); + pub fn GetSystemDEPPolicy() -> DEP_SYSTEM_POLICY_TYPE; + pub fn GetSystemDefaultLCID() -> LCID; + pub fn GetSystemDefaultLangID() -> LANGID; + pub fn GetSystemDefaultLocaleName(lpLocaleName: LPWSTR, cchLocaleName: c_int) -> c_int; + pub fn GetSystemDefaultUILanguage() -> LANGID; + pub fn GetSystemDirectoryA(lpBuffer: LPSTR, uSize: UINT) -> UINT; + pub fn GetSystemDirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT; + pub fn GetSystemFileCacheSize( + lpMinimumFileCacheSize: PSIZE_T, lpMaximumFileCacheSize: PSIZE_T, lpFlags: PDWORD, + ) -> BOOL; + pub fn GetSystemFirmwareTable( + FirmwareTableProviderSignature: DWORD, FirmwareTableID: DWORD, pFirmwareTableBuffer: PVOID, + BufferSize: DWORD, + ) -> UINT; + pub fn GetSystemInfo(lpSystemInfo: LPSYSTEM_INFO); + pub fn GetSystemPowerStatus(lpSystemPowerStatus: LPSYSTEM_POWER_STATUS) -> BOOL; + pub fn GetSystemPreferredUILanguages( + dwFlags: DWORD, pulNumLanguages: PULONG, pwszLanguagesBuffer: PZZWSTR, + pcchLanguagesBuffer: PULONG, + ) -> BOOL; + pub fn GetSystemRegistryQuota(pdwQuotaAllowed: PDWORD, pdwQuotaUsed: PDWORD) -> BOOL; + pub fn GetSystemTime(lpSystemTime: LPSYSTEMTIME); + pub fn GetSystemTimeAdjustment( + lpTimeAdjustment: PDWORD, lpTimeIncrement: PDWORD, lpTimeAdjustmentDisabled: PBOOL, + ) -> BOOL; + pub fn GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: LPFILETIME); + pub fn GetSystemTimePreciseAsFileTime(lpSystemTimeAsFileTime: LPFILETIME); + pub fn GetSystemTimes( + lpIdleTime: LPFILETIME, lpKernelTime: LPFILETIME, lpUserTime: LPFILETIME, + ) -> BOOL; + pub fn GetSystemWindowsDirectoryA(lpBuffer: LPSTR, uSize: UINT) -> UINT; + pub fn GetSystemWindowsDirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT; + pub fn GetSystemWow64DirectoryA(lpBuffer: LPSTR, uSize: UINT) -> UINT; + pub fn GetSystemWow64DirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT; + pub fn GetTapeParameters( + hDevice: HANDLE, dwOperation: DWORD, lpdwSize: LPDWORD, lpTapeInformation: LPVOID + ) -> DWORD; + pub fn GetTapePosition( + hDevice: HANDLE, dwPositionType: DWORD, lpdwPartition: LPDWORD, + lpdwOffsetLow: LPDWORD, lpdwOffsetHigh: LPDWORD + ) -> DWORD; + pub fn GetTapeStatus(hDevice: HANDLE) -> DWORD; + pub fn GetTempFileNameA( + lpPathName: LPCSTR, lpPrefixString: LPCSTR, uUnique: UINT, lpTempFileName: LPSTR, + ) -> UINT; + pub fn GetTempFileNameW( + lpPathName: LPCWSTR, lpPrefixString: LPCWSTR, uUnique: UINT, lpTempFileName: LPWSTR, + ) -> UINT; + pub fn GetTempPathA(nBufferLength: DWORD, lpBuffer: LPSTR) -> DWORD; + pub fn GetTempPathW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD; + pub fn GetThreadContext(hThread: HANDLE, lpContext: LPCONTEXT) -> BOOL; + pub fn GetThreadErrorMode() -> DWORD; + pub fn GetThreadGroupAffinity(hThread: HANDLE, GroupAffinity: PGROUP_AFFINITY) -> BOOL; + pub fn GetThreadIOPendingFlag(hThread: HANDLE, lpIOIsPending: PBOOL) -> BOOL; + pub fn GetThreadId(Thread: HANDLE) -> DWORD; + pub fn GetThreadIdealProcessorEx(hThread: HANDLE, lpIdealProcessor: PPROCESSOR_NUMBER) -> BOOL; + pub fn GetThreadInformation( + hThread: HANDLE, ThreadInformationClass: THREAD_INFORMATION_CLASS, + ThreadInformation: LPVOID, ThreadInformationSize: DWORD, + ) -> BOOL; + pub fn GetThreadLocale() -> LCID; + pub fn GetThreadPreferredUILanguages( + dwFlags: DWORD, pulNumLanguages: PULONG, pwszLanguagesBuffer: PZZWSTR, + pcchLanguagesBuffer: PULONG, + ) -> BOOL; + pub fn GetThreadPriority(hThread: HANDLE) -> c_int; + pub fn GetThreadPriorityBoost(hThread: HANDLE, pDisablePriorityBoost: PBOOL) -> BOOL; + pub fn GetThreadSelectorEntry( + hThread: HANDLE, dwSelector: DWORD, lpSelectorEntry: LPLDT_ENTRY, + ) -> BOOL; + pub fn GetThreadTimes( + hThread: HANDLE, lpCreationTime: LPFILETIME, lpExitTime: LPFILETIME, + lpKernelTime: LPFILETIME, lpUserTime: LPFILETIME, + ) -> BOOL; + pub fn GetThreadUILanguage() -> LANGID; + pub fn GetTickCount() -> DWORD; + pub fn GetTickCount64() -> ULONGLONG; + pub fn GetTimeFormatA( + Locale: LCID, dwFlags: DWORD, lpTime: *const SYSTEMTIME, lpFormat: LPCSTR, + lpTimeStr: LPSTR, cchTime: c_int, + ) -> c_int; + pub fn GetTimeFormatEx( + lpLocaleName: LPCWSTR, dwFlags: DWORD, lpTime: *const SYSTEMTIME, lpFormat: LPCWSTR, + lpTimeStr: LPWSTR, cchTime: c_int, + ) -> c_int; + pub fn GetTimeFormatW( + Locale: LCID, dwFlags: DWORD, lpTime: *const SYSTEMTIME, lpFormat: LPCWSTR, + lpTimeStr: LPWSTR, cchTime: c_int, + ) -> c_int; + pub fn GetTimeZoneInformation(lpTimeZoneInformation: LPTIME_ZONE_INFORMATION) -> DWORD; + pub fn GetTimeZoneInformationForYear( + wYear: USHORT, pdtzi: PDYNAMIC_TIME_ZONE_INFORMATION, ptzi: LPTIME_ZONE_INFORMATION, + ) -> BOOL; + pub fn GetUILanguageInfo( + dwFlags: DWORD, pwmszLanguage: PCZZWSTR, pwszFallbackLanguages: PZZWSTR, + pcchFallbackLanguages: PDWORD, pAttributes: PDWORD, + ) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn GetUmsCompletionListEvent( + UmsCompletionList: PUMS_COMPLETION_LIST, UmsCompletionEvent: PHANDLE, + ) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn GetUmsSystemThreadInformation( + ThreadHandle: HANDLE, SystemThreadInfo: PUMS_SYSTEM_THREAD_INFORMATION, + ) -> BOOL; + pub fn GetUserDefaultLCID() -> LCID; + pub fn GetUserDefaultLangID() -> LANGID; + pub fn GetUserDefaultLocaleName(lpLocaleName: LPWSTR, cchLocaleName: c_int) -> c_int; + pub fn GetUserDefaultUILanguage() -> LANGID; + pub fn GetUserGeoID(GeoClass: GEOCLASS) -> GEOID; + pub fn GetUserPreferredUILanguages( + dwFlags: DWORD, pulNumLanguages: PULONG, pwszLanguagesBuffer: PZZWSTR, + pcchLanguagesBuffer: PULONG, + ) -> BOOL; + pub fn GetVersion() -> DWORD; + pub fn GetVersionExA(lpVersionInformation: LPOSVERSIONINFOA) -> BOOL; + pub fn GetVersionExW(lpVersionInformation: LPOSVERSIONINFOW) -> BOOL; + pub fn GetVolumeInformationA( + lpRootPathName: LPCSTR, lpVolumeNameBuffer: LPSTR, nVolumeNameSize: DWORD, + lpVolumeSerialNumber: LPDWORD, lpMaximumComponentLength: LPDWORD, + lpFileSystemFlags: LPDWORD, lpFileSystemNameBuffer: LPSTR, nFileSystemNameSize: DWORD, + ) -> BOOL; + pub fn GetVolumeInformationByHandleW( + hFile: HANDLE, lpVolumeNameBuffer: LPWSTR, nVolumeNameSize: DWORD, + lpVolumeSerialNumber: LPDWORD, lpMaximumComponentLength: LPDWORD, + lpFileSystemFlags: LPDWORD, lpFileSystemNameBuffer: LPWSTR, nFileSystemNameSize: DWORD, + ) -> BOOL; + pub fn GetVolumeInformationW( + lpRootPathName: LPCWSTR, lpVolumeNameBuffer: LPWSTR, nVolumeNameSize: DWORD, + lpVolumeSerialNumber: LPDWORD, lpMaximumComponentLength: LPDWORD, + lpFileSystemFlags: LPDWORD, lpFileSystemNameBuffer: LPWSTR, nFileSystemNameSize: DWORD, + ) -> BOOL; + pub fn GetVolumeNameForVolumeMountPointA( + lpszVolumeMountPoint: LPCSTR, lpszVolumeName: LPSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn GetVolumeNameForVolumeMountPointW( + lpszVolumeMountPoint: LPCWSTR, lpszVolumeName: LPWSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn GetVolumePathNameA( + lpszFileName: LPCSTR, lpszVolumePathName: LPSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn GetVolumePathNameW( + lpszFileName: LPCWSTR, lpszVolumePathName: LPWSTR, cchBufferLength: DWORD, + ) -> BOOL; + pub fn GetVolumePathNamesForVolumeNameA( + lpszVolumeName: LPCSTR, lpszVolumePathNames: LPCH, cchBufferLength: DWORD, + lpcchReturnLength: PDWORD, + ) -> BOOL; + pub fn GetVolumePathNamesForVolumeNameW( + lpszVolumeName: LPCWSTR, lpszVolumePathNames: LPWCH, cchBufferLength: DWORD, + lpcchReturnLength: PDWORD, + ) -> BOOL; + pub fn GetWindowsDirectoryA(lpBuffer: LPSTR, uSize: UINT) -> UINT; + pub fn GetWindowsDirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT; + pub fn GetWriteWatch( + dwFlags: DWORD, lpBaseAddress: PVOID, dwRegionSize: SIZE_T, lpAddresses: *mut PVOID, + lpdwCount: *mut ULONG_PTR, lpdwGranularity: LPDWORD, + ) -> UINT; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + pub fn GetXStateFeaturesMask(Context: PCONTEXT, FeatureMask: PDWORD64) -> BOOL; + pub fn GlobalAddAtomA(lpString: LPCSTR) -> ATOM; + pub fn GlobalAddAtomExA(lpString: LPCSTR, Flags: DWORD) -> ATOM; + pub fn GlobalAddAtomExW(lpString: LPCWSTR, Flags: DWORD) -> ATOM; + pub fn GlobalAddAtomW(lpString: LPCWSTR) -> ATOM; + pub fn GlobalAlloc(uFlags: UINT, dwBytes: SIZE_T) -> HGLOBAL; + pub fn GlobalCompact(dwMinFree: DWORD) -> SIZE_T; + pub fn GlobalDeleteAtom(nAtom: ATOM) -> ATOM; + pub fn GlobalFindAtomA(lpString: LPCSTR) -> ATOM; + pub fn GlobalFindAtomW(lpString: LPCWSTR) -> ATOM; + pub fn GlobalFix(hMem: HGLOBAL); + pub fn GlobalFlags(hMem: HGLOBAL) -> UINT; + pub fn GlobalFree(hMem: HGLOBAL) -> HGLOBAL; + pub fn GlobalGetAtomNameA(nAtom: ATOM, lpBuffer: LPSTR, nSize: c_int) -> UINT; + pub fn GlobalGetAtomNameW(nAtom: ATOM, lpBuffer: LPWSTR, nSize: c_int) -> UINT; + pub fn GlobalHandle(pMem: LPCVOID) -> HGLOBAL; + pub fn GlobalLock(hMem: HGLOBAL) -> LPVOID; + pub fn GlobalMemoryStatus(lpBuffer: LPMEMORYSTATUS); + pub fn GlobalMemoryStatusEx(lpBuffer: LPMEMORYSTATUSEX) -> BOOL; + pub fn GlobalReAlloc(hMem: HGLOBAL, dwBytes: SIZE_T, uFlags: UINT) -> HGLOBAL; + pub fn GlobalSize(hMem: HGLOBAL) -> SIZE_T; + pub fn GlobalUnWire(hMem: HGLOBAL) -> BOOL; + pub fn GlobalUnfix(hMem: HGLOBAL); + pub fn GlobalUnlock(hMem: HGLOBAL) -> BOOL; + pub fn GlobalWire(hMem: HGLOBAL) -> LPVOID; + pub fn Heap32First(lphe: LPHEAPENTRY32, th32ProcessID: DWORD, th32HeapID: ULONG_PTR) -> BOOL; + pub fn Heap32ListFirst(hSnapshot: HANDLE, lphl: LPHEAPLIST32) -> BOOL; + pub fn Heap32ListNext(hSnapshot: HANDLE, lphl: LPHEAPLIST32) -> BOOL; + pub fn Heap32Next(lphe: LPHEAPENTRY32) -> BOOL; + pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; + pub fn HeapCompact(hHeap: HANDLE, dwFlags: DWORD) -> SIZE_T; + pub fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) -> HANDLE; + pub fn HeapDestroy(hHeap: HANDLE) -> BOOL; + pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL; + pub fn HeapLock(hHeap: HANDLE) -> BOOL; + pub fn HeapQueryInformation( + HeapHandle: HANDLE, HeapInformationClass: HEAP_INFORMATION_CLASS, HeapInformation: PVOID, + HeapInformationLength: SIZE_T, ReturnLength: PSIZE_T, + ) -> BOOL; + pub fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: SIZE_T) -> LPVOID; + pub fn HeapSetInformation( + HeapHandle: HANDLE, HeapInformationClass: HEAP_INFORMATION_CLASS, HeapInformation: PVOID, + HeapInformationLength: SIZE_T, + ) -> BOOL; + pub fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID) -> SIZE_T; + pub fn HeapSummary(hHeap: HANDLE, dwFlags: DWORD, lpSummary: LPHEAP_SUMMARY) -> BOOL; + pub fn HeapUnlock(hHeap: HANDLE) -> BOOL; + pub fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID) -> BOOL; + pub fn HeapWalk(hHeap: HANDLE, lpEntry: LPPROCESS_HEAP_ENTRY) -> BOOL; + pub fn InitAtomTable(nSize: DWORD) -> BOOL; + pub fn InitOnceBeginInitialize( + lpInitOnce: LPINIT_ONCE, dwFlags: DWORD, fPending: PBOOL, lpContext: *mut LPVOID, + ) -> BOOL; + pub fn InitOnceComplete( + lpInitOnce: LPINIT_ONCE, dwFlags: DWORD, lpContext: LPVOID, + ) -> BOOL; + pub fn InitOnceExecuteOnce( + InitOnce: PINIT_ONCE, InitFn: PINIT_ONCE_FN, Parameter: PVOID, Context: *mut LPVOID, + ) -> BOOL; + pub fn InitOnceInitialize(InitOnce: PINIT_ONCE); + pub fn InitializeConditionVariable(ConditionVariable: PCONDITION_VARIABLE); + pub fn InitializeContext( + Buffer: PVOID, ContextFlags: DWORD, Context: *mut PCONTEXT, ContextLength: PDWORD, + ) -> BOOL; + pub fn InitializeCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); + pub fn InitializeCriticalSectionAndSpinCount( + lpCriticalSection: LPCRITICAL_SECTION, dwSpinCount: DWORD, + ) -> BOOL; + pub fn InitializeCriticalSectionEx( + lpCriticalSection: LPCRITICAL_SECTION, dwSpinCount: DWORD, Flags: DWORD, + ) -> BOOL; + pub fn InitializeProcThreadAttributeList( + lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST, dwAttributeCount: DWORD, dwFlags: DWORD, + lpSize: PSIZE_T, + ) -> BOOL; + pub fn InitializeSListHead(ListHead: PSLIST_HEADER); + pub fn InitializeSRWLock(SRWLock: PSRWLOCK); + pub fn InitializeSynchronizationBarrier( + lpBarrier: LPSYNCHRONIZATION_BARRIER, lTotalThreads: LONG, lSpinCount: LONG, + ) -> BOOL; + pub fn InstallELAMCertificateInfo(ELAMFile: HANDLE) -> BOOL; + #[cfg(target_arch = "x86")] + pub fn InterlockedCompareExchange( + Destination: *mut LONG, ExChange: LONG, Comperand: LONG, + ) -> LONG; + #[cfg(target_arch = "x86")] + pub fn InterlockedCompareExchange64( + Destination: *mut LONG64, ExChange: LONG64, Comperand: LONG64, + ) -> LONG64; + #[cfg(target_arch = "x86")] + pub fn InterlockedDecrement(Addend: *mut LONG) -> LONG; + #[cfg(target_arch = "x86")] + pub fn InterlockedExchange(Target: *mut LONG, Value: LONG) -> LONG; + #[cfg(target_arch = "x86")] + pub fn InterlockedExchangeAdd(Addend: *mut LONG, Value: LONG) -> LONG; + pub fn InterlockedFlushSList(ListHead: PSLIST_HEADER) -> PSLIST_ENTRY; + #[cfg(target_arch = "x86")] + pub fn InterlockedIncrement(Addend: *mut LONG) -> LONG; + pub fn InterlockedPopEntrySList(ListHead: PSLIST_HEADER) -> PSLIST_ENTRY; + pub fn InterlockedPushEntrySList( + ListHead: PSLIST_HEADER, ListEntry: PSLIST_ENTRY, + ) -> PSLIST_ENTRY; + pub fn InterlockedPushListSListEx( + ListHead: PSLIST_HEADER, List: PSLIST_ENTRY, ListEnd: PSLIST_ENTRY, Count: ULONG, + ) -> PSLIST_ENTRY; + pub fn IsBadCodePtr(lpfn: FARPROC) -> BOOL; + pub fn IsBadHugeReadPtr(lp: *const VOID, ucb: UINT_PTR) -> BOOL; + pub fn IsBadHugeWritePtr(lp: LPVOID, ucb: UINT_PTR) -> BOOL; + pub fn IsBadReadPtr(lp: *const VOID, ucb: UINT_PTR) -> BOOL; + pub fn IsBadStringPtrA(lpsz: LPCSTR, ucchMax: UINT_PTR) -> BOOL; + pub fn IsBadStringPtrW(lpsz: LPCWSTR, ucchMax: UINT_PTR) -> BOOL; + pub fn IsBadWritePtr(lp: LPVOID, ucb: UINT_PTR) -> BOOL; + pub fn IsDBCSLeadByte(TestChar: BYTE) -> BOOL; + pub fn IsDBCSLeadByteEx(CodePage: UINT, TestChar: BYTE) -> BOOL; + pub fn IsDebuggerPresent() -> BOOL; + pub fn IsNLSDefinedString( + Function: NLS_FUNCTION, dwFlags: DWORD, lpVersionInformation: LPNLSVERSIONINFO, + lpString: LPCWSTR, cchStr: INT, + ) -> BOOL; + pub fn IsNativeVhdBoot(NativeVhdBoot: PBOOL) -> BOOL; + pub fn IsNormalizedString(NormForm: NORM_FORM, lpString: LPCWSTR, cwLength: c_int) -> BOOL; + pub fn IsProcessCritical(hProcess: HANDLE, Critical: PBOOL) -> BOOL; + pub fn IsProcessInJob(ProcessHandle: HANDLE, JobHandle: HANDLE, Result: PBOOL) -> BOOL; + pub fn IsProcessorFeaturePresent(ProcessorFeature: DWORD) -> BOOL; + pub fn IsSystemResumeAutomatic() -> BOOL; + pub fn IsThreadAFiber() -> BOOL; + pub fn IsThreadpoolTimerSet(pti: PTP_TIMER) -> BOOL; + pub fn IsValidCodePage(CodePage: UINT) -> BOOL; + pub fn IsValidLanguageGroup(LanguageGroup: LGRPID, dwFlags: DWORD) -> BOOL; + pub fn IsValidLocale(Locale: LCID, dwFlags: DWORD) -> BOOL; + pub fn IsValidLocaleName(lpLocaleName: LPCWSTR) -> BOOL; + pub fn IsValidNLSVersion( + function: NLS_FUNCTION, lpLocaleName: LPCWSTR, lpVersionInformation: LPNLSVERSIONINFOEX, + ) -> BOOL; + pub fn IsWow64Process(hProcess: HANDLE, Wow64Process: PBOOL) -> BOOL; + pub fn K32EmptyWorkingSet(hProcess: HANDLE) -> BOOL; + pub fn K32EnumDeviceDrivers(lpImageBase: *mut LPVOID, cb: DWORD, lpcbNeeded: LPDWORD) -> BOOL; + pub fn K32EnumPageFilesA( + pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKA, pContext: LPVOID, + ) -> BOOL; + pub fn K32EnumPageFilesW( + pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKW, pContext: LPVOID, + ) -> BOOL; + pub fn K32EnumProcessModules( + hProcess: HANDLE, lphModule: *mut HMODULE, cb: DWORD, lpcbNeeded: LPDWORD, + ) -> BOOL; + pub fn K32EnumProcessModulesEx( + hProcess: HANDLE, lphModule: *mut HMODULE, cb: DWORD, lpcbNeeded: LPDWORD, + dwFilterFlag: DWORD, + ) -> BOOL; + pub fn K32EnumProcesses( + lpidProcess: *mut DWORD, cb: DWORD, lpcbNeeded: LPDWORD, + ) -> BOOL; + pub fn K32GetDeviceDriverBaseNameA(ImageBase: LPVOID, lpFilename: LPSTR, nSize: DWORD) -> DWORD; + pub fn K32GetDeviceDriverBaseNameW( + ImageBase: LPVOID, lpFilename: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetDeviceDriverFileNameA(ImageBase: LPVOID, lpFilename: LPSTR, nSize: DWORD) -> DWORD; + pub fn K32GetDeviceDriverFileNameW( + ImageBase: LPVOID, lpFilename: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetMappedFileNameA( + hProcess: HANDLE, lpv: LPVOID, lpFilename: LPSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetMappedFileNameW( + hProcess: HANDLE, lpv: LPVOID, lpFilename: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetModuleBaseNameA( + hProcess: HANDLE, hModule: HMODULE, lpBaseName: LPSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetModuleBaseNameW( + hProcess: HANDLE, hModule: HMODULE, lpBaseName: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetModuleFileNameExA( + hProcess: HANDLE, hModule: HMODULE, lpFilename: LPSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetModuleFileNameExW( + hProcess: HANDLE, hModule: HMODULE, lpFilename: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetModuleInformation( + hProcess: HANDLE, hModule: HMODULE, lpmodinfo: LPMODULEINFO, cb: DWORD, + ) -> BOOL; + pub fn K32GetPerformanceInfo( + pPerformanceInformation: PPERFORMANCE_INFORMATION, cb: DWORD, + ) -> BOOL; + pub fn K32GetProcessImageFileNameA( + hProcess: HANDLE, lpImageFileName: LPSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetProcessImageFileNameW( + hProcess: HANDLE, lpImageFileName: LPWSTR, nSize: DWORD, + ) -> DWORD; + pub fn K32GetProcessMemoryInfo( + Process: HANDLE, ppsmemCounters: PPROCESS_MEMORY_COUNTERS, cb: DWORD, + ) -> BOOL; + pub fn K32GetWsChanges( + hProcess: HANDLE, lpWatchInfo: PPSAPI_WS_WATCH_INFORMATION, cb: DWORD, + ) -> BOOL; + pub fn K32GetWsChangesEx( + hProcess: HANDLE, lpWatchInfoEx: PPSAPI_WS_WATCH_INFORMATION_EX, cb: PDWORD, + ) -> BOOL; + pub fn K32InitializeProcessForWsWatch(hProcess: HANDLE) -> BOOL; + pub fn K32QueryWorkingSet(hProcess: HANDLE, pv: PVOID, cb: DWORD) -> BOOL; + pub fn K32QueryWorkingSetEx(hProcess: HANDLE, pv: PVOID, cb: DWORD) -> BOOL; + pub fn LCIDToLocaleName(Locale: LCID, lpName: LPWSTR, cchName: c_int, dwFlags: DWORD) -> c_int; + pub fn LCMapStringA( + Locale: LCID, dwMapFlags: DWORD, lpSrcStr: LPCSTR, cchSrc: c_int, lpDestStr: LPSTR, + cchDest: c_int, + ) -> c_int; + pub fn LCMapStringEx( + lpLocaleName: LPCWSTR, dwMapFlags: DWORD, lpSrcStr: LPCWSTR, cchSrc: c_int, + lpDestStr: LPWSTR, cchDest: c_int, lpVersionInformation: LPNLSVERSIONINFO, + lpReserved: LPVOID, sortHandle: LPARAM, + ) -> c_int; + pub fn LCMapStringW( + Locale: LCID, dwMapFlags: DWORD, lpSrcStr: LPCWSTR, cchSrc: c_int, lpDestStr: LPWSTR, + cchDest: c_int, + ) -> c_int; + pub fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); + pub fn LeaveCriticalSectionWhenCallbackReturns( + pci: PTP_CALLBACK_INSTANCE, pcs: PCRITICAL_SECTION, + ); + // pub fn LoadAppInitDlls(); + pub fn LoadLibraryA(lpFileName: LPCSTR) -> HMODULE; + pub fn LoadLibraryExA(lpLibFileName: LPCSTR, hFile: HANDLE, dwFlags: DWORD) -> HMODULE; + pub fn LoadLibraryExW(lpLibFileName: LPCWSTR, hFile: HANDLE, dwFlags: DWORD) -> HMODULE; + pub fn LoadLibraryW(lpFileName: LPCWSTR) -> HMODULE; + pub fn LoadModule(lpModuleName: LPCSTR, lpParameterBlock: LPVOID) -> DWORD; + pub fn LoadPackagedLibrary(lpwLibFileName: LPCWSTR, Reserved: DWORD) -> HMODULE; + pub fn LoadResource(hModule: HMODULE, hResInfo: HRSRC) -> HGLOBAL; + // pub fn LoadStringBaseExW(); + // pub fn LoadStringBaseW(); + pub fn LocalAlloc(uFlags: UINT, uBytes: SIZE_T) -> HLOCAL; + pub fn LocalCompact(uMinFree: UINT) -> SIZE_T; + pub fn LocalFileTimeToFileTime( + lpLocalFileTime: *const FILETIME, lpFileTime: LPFILETIME, + ) -> BOOL; + pub fn LocalFlags(hMem: HLOCAL) -> UINT; + pub fn LocalFree(hMem: HLOCAL) -> HLOCAL; + pub fn LocalHandle(pMem: LPCVOID) -> HLOCAL; + pub fn LocalLock(hMem: HLOCAL) -> LPVOID; + pub fn LocalReAlloc(hMem: HLOCAL, uBytes: SIZE_T, uFlags: UINT) -> HLOCAL; + pub fn LocalShrink(hMem: HLOCAL, cbNewSize: UINT) -> SIZE_T; + pub fn LocalSize(hMem: HLOCAL) -> SIZE_T; + pub fn LocalUnlock(hMem: HLOCAL) -> BOOL; + pub fn LocaleNameToLCID(lpName: LPCWSTR, dwFlags: DWORD) -> LCID; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + pub fn LocateXStateFeature(Context: PCONTEXT, FeatureId: DWORD, Length: PDWORD) -> PVOID; + pub fn LockFile( + hFile: HANDLE, dwFileOffsetLow: DWORD, dwFileOffsetHigh: DWORD, + nNumberOfBytesToLockLow: DWORD, nNumberOfBytesToLockHigh: DWORD, + ) -> BOOL; + pub fn LockFileEx( + hFile: HANDLE, dwFlags: DWORD, dwReserved: DWORD, nNumberOfBytesToLockLow: DWORD, + nNumberOfBytesToLockHigh: DWORD, lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn LockResource(hResData: HGLOBAL) -> LPVOID; + pub fn MapUserPhysicalPages( + VirtualAddress: PVOID, NumberOfPages: ULONG_PTR, PageArray: PULONG_PTR, + ) -> BOOL; + pub fn MapUserPhysicalPagesScatter( + VirtualAddresses: *mut PVOID, NumberOfPages: ULONG_PTR, PageArray: PULONG_PTR, + ) -> BOOL; + pub fn MapViewOfFile( + hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, dwFileOffsetHigh: DWORD, + dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: SIZE_T, + ) -> LPVOID; + pub fn MapViewOfFileEx( + hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, dwFileOffsetHigh: DWORD, + dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: SIZE_T, lpBaseAddress: LPVOID, + ) -> LPVOID; + pub fn MapViewOfFileExNuma( + hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, dwFileOffsetHigh: DWORD, + dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: SIZE_T, lpBaseAddress: LPVOID, + nndPreferred: DWORD, + ) -> LPVOID; + pub fn MapViewOfFileFromApp( + hFileMappingObject: HANDLE, DesiredAccess: ULONG, FileOffset: ULONG64, + NumberOfBytesToMap: SIZE_T, + ) -> PVOID; + pub fn Module32First(hSnapshot: HANDLE, lpme: LPMODULEENTRY32) -> BOOL; + pub fn Module32FirstW(hSnapshot: HANDLE, lpme: LPMODULEENTRY32W) -> BOOL; + pub fn Module32Next(hSnapshot: HANDLE, lpme: LPMODULEENTRY32) -> BOOL; + pub fn Module32NextW(hSnapshot: HANDLE, lpme: LPMODULEENTRY32W) -> BOOL; + pub fn MoveFileA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR) -> BOOL; + pub fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, dwFlags: DWORD) -> BOOL; + pub fn MoveFileExW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, dwFlags: DWORD) -> BOOL; + pub fn MoveFileTransactedA( + lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, dwFlags: DWORD, hTransaction: HANDLE, + ) -> BOOL; + pub fn MoveFileTransactedW( + lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, dwFlags: DWORD, hTransaction: HANDLE, + ) -> BOOL; + pub fn MoveFileW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR) -> BOOL; + pub fn MoveFileWithProgressA( + lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, dwFlags: DWORD, + ) -> BOOL; + pub fn MoveFileWithProgressW( + lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, dwFlags: DWORD, + ) -> BOOL; + pub fn MulDiv(nNumber: c_int, nNumerator: c_int, nDenominator: c_int) -> c_int; + pub fn MultiByteToWideChar( + CodePage: UINT, dwFlags: DWORD, lpMultiByteStr: LPCSTR, cbMultiByte: c_int, + lpWideCharStr: LPWSTR, cchWideChar: c_int, + ) -> c_int; + pub fn NeedCurrentDirectoryForExePathA(ExeName: LPCSTR) -> BOOL; + pub fn NeedCurrentDirectoryForExePathW(ExeName: LPCWSTR) -> BOOL; + pub fn NormalizeString( + NormForm: NORM_FORM, lpSrcString: LPCWSTR, cwSrcLength: c_int, lpDstString: LPWSTR, + cwDstLength: c_int, + ) -> c_int; + // pub fn NotifyMountMgr(); + pub fn NotifyUILanguageChange( + dwFlags: DWORD, pcwstrNewLanguage: PCWSTR, pcwstrPreviousLanguage: PCWSTR, + dwReserved: DWORD, pdwStatusRtrn: PDWORD, + ) -> BOOL; + // pub fn OOBEComplete(); + pub fn OpenEventA(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE; + pub fn OpenEventW(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE; + pub fn OpenFile(lpFileName: LPCSTR, lpReOpenBuff: LPOFSTRUCT, uStyle: UINT) -> HFILE; + pub fn OpenFileById( + hVolumeHint: HANDLE, lpFileId: LPFILE_ID_DESCRIPTOR, dwDesiredAccess: DWORD, + dwShareMode: DWORD, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + dwFlagsAndAttributes: DWORD, + ) -> HANDLE; + pub fn OpenFileMappingA( + dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCSTR, + ) -> HANDLE; + pub fn OpenFileMappingW( + dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCWSTR, + ) -> HANDLE; + pub fn OpenJobObjectA(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE; + pub fn OpenJobObjectW(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE; + pub fn OpenMutexA(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE; + pub fn OpenMutexW(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE; + // pub fn OpenPackageInfoByFullName(); + pub fn OpenPrivateNamespaceA(lpBoundaryDescriptor: LPVOID, lpAliasPrefix: LPCSTR) -> HANDLE; + pub fn OpenPrivateNamespaceW(lpBoundaryDescriptor: LPVOID, lpAliasPrefix: LPCWSTR) -> HANDLE; + pub fn OpenProcess(dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwProcessId: DWORD) -> HANDLE; + pub fn OpenSemaphoreA(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE; + pub fn OpenSemaphoreW(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE; + // pub fn OpenState(); + // pub fn OpenStateExplicit(); + pub fn OpenThread(dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwThreadId: DWORD) -> HANDLE; + pub fn OpenWaitableTimerA( + dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpTimerName: LPCSTR, + ) -> HANDLE; + pub fn OpenWaitableTimerW( + dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpTimerName: LPCWSTR, + ) -> HANDLE; + pub fn OutputDebugStringA(lpOutputString: LPCSTR); + pub fn OutputDebugStringW(lpOutputString: LPCWSTR); + // pub fn PackageFamilyNameFromFullName(); + // pub fn PackageFamilyNameFromId(); + // pub fn PackageFullNameFromId(); + // pub fn PackageIdFromFullName(); + // pub fn PackageNameAndPublisherIdFromFamilyName(); + // pub fn ParseApplicationUserModelId(); + pub fn PeekConsoleInputA( + hConsoleInput: HANDLE, lpBuffer: PINPUT_RECORD, nLength: DWORD, + lpNumberOfEventsRead: LPDWORD, + ) -> BOOL; + pub fn PeekConsoleInputW( + hConsoleInput: HANDLE, lpBuffer: PINPUT_RECORD, nLength: DWORD, + lpNumberOfEventsRead: LPDWORD, + ) -> BOOL; + pub fn PeekNamedPipe( + hNamedPipe: HANDLE, lpBuffer: LPVOID, nBufferSize: DWORD, lpBytesRead: LPDWORD, + lpTotalBytesAvail: LPDWORD, lpBytesLeftThisMessage: LPDWORD, + ) -> BOOL; + pub fn PostQueuedCompletionStatus( + CompletionPort: HANDLE, dwNumberOfBytesTransferred: DWORD, dwCompletionKey: ULONG_PTR, + lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn PowerClearRequest(PowerRequest: HANDLE, RequestType: POWER_REQUEST_TYPE) -> BOOL; + pub fn PowerCreateRequest(Context: PREASON_CONTEXT) -> HANDLE; + pub fn PowerSetRequest(PowerRequest: HANDLE, RequestType: POWER_REQUEST_TYPE) -> BOOL; + pub fn PrefetchVirtualMemory( + hProcess: HANDLE, NumberOfEntries: ULONG_PTR, VirtualAddresses: PWIN32_MEMORY_RANGE_ENTRY, + Flags: ULONG, + ) -> BOOL; + pub fn PrepareTape(hDevice: HANDLE, dwOperation: DWORD, bImmediate: BOOL) -> DWORD; + pub fn Process32First(hSnapshot: HANDLE, lppe: LPPROCESSENTRY32) -> BOOL; + pub fn Process32FirstW(hSnapshot: HANDLE, lppe: LPPROCESSENTRY32W) -> BOOL; + pub fn Process32Next(hSnapshot: HANDLE, lppe: LPPROCESSENTRY32) -> BOOL; + pub fn Process32NextW(hSnapshot: HANDLE, lppe: LPPROCESSENTRY32W) -> BOOL; + pub fn ProcessIdToSessionId(dwProcessId: DWORD, pSessionId: *mut DWORD) -> BOOL; + pub fn PssCaptureSnapshot( + ProcessHandle: HANDLE, CaptureFlags: PSS_CAPTURE_FLAGS, ThreadContextFlags: DWORD, + SnapshotHandle: *mut HPSS, + ) -> DWORD; + pub fn PssDuplicateSnapshot( + SourceProcessHandle: HANDLE, SnapshotHandle: HPSS, TargetProcessHandle: HANDLE, + TargetSnapshotHandle: *mut HPSS, Flags: PSS_DUPLICATE_FLAGS, + ) -> DWORD; + pub fn PssFreeSnapshot(ProcessHandle: HANDLE, SnapshotHandle: HPSS) -> DWORD; + pub fn PssQuerySnapshot( + SnapshotHandle: HPSS, InformationClass: PSS_QUERY_INFORMATION_CLASS, Buffer: *mut c_void, + BufferLength: DWORD, + ) -> DWORD; + pub fn PssWalkMarkerCreate( + Allocator: *const PSS_ALLOCATOR, WalkMarkerHandle: *mut HPSSWALK, + ) -> DWORD; + pub fn PssWalkMarkerFree(WalkMarkerHandle: HPSSWALK) -> DWORD; + pub fn PssWalkMarkerGetPosition(WalkMarkerHandle: HPSSWALK, Position: *mut ULONG_PTR) -> DWORD; + // pub fn PssWalkMarkerRewind(); + // pub fn PssWalkMarkerSeek(); + pub fn PssWalkMarkerSeekToBeginning(WalkMarkerHandle: HPSS) -> DWORD; + pub fn PssWalkMarkerSetPosition(WalkMarkerHandle: HPSSWALK, Position: ULONG_PTR) -> DWORD; + // pub fn PssWalkMarkerTell(); + pub fn PssWalkSnapshot( + SnapshotHandle: HPSS, InformationClass: PSS_WALK_INFORMATION_CLASS, + WalkMarkerHandle: HPSSWALK, Buffer: *mut c_void, BufferLength: DWORD, + ) -> DWORD; + pub fn PulseEvent(hEvent: HANDLE) -> BOOL; + pub fn PurgeComm(hFile: HANDLE, dwFlags: DWORD) -> BOOL; + pub fn QueryActCtxSettingsW( + dwFlags: DWORD, hActCtx: HANDLE, settingsNameSpace: PCWSTR, settingName: PCWSTR, + pvBuffer: PWSTR, dwBuffer: SIZE_T, pdwWrittenOrRequired: *mut SIZE_T, + ) -> BOOL; + pub fn QueryActCtxW( + dwFlags: DWORD, hActCtx: HANDLE, pvSubInstance: PVOID, ulInfoClass: ULONG, pvBuffer: PVOID, + cbBuffer: SIZE_T, pcbWrittenOrRequired: *mut SIZE_T, + ) -> BOOL; + pub fn QueryDepthSList(ListHead: PSLIST_HEADER) -> USHORT; + pub fn QueryDosDeviceA(lpDeviceName: LPCSTR, lpTargetPath: LPSTR, ucchMax: DWORD) -> DWORD; + pub fn QueryDosDeviceW(lpDeviceName: LPCWSTR, lpTargetPath: LPWSTR, ucchMax: DWORD) -> DWORD; + pub fn QueryFullProcessImageNameA( + hProcess: HANDLE, dwFlags: DWORD, lpExeName: LPSTR, lpdwSize: PDWORD, + ) -> BOOL; + pub fn QueryFullProcessImageNameW( + hProcess: HANDLE, dwFlags: DWORD, lpExeName: LPWSTR, lpdwSize: PDWORD, + ) -> BOOL; + pub fn QueryIdleProcessorCycleTime( + BufferLength: PULONG, ProcessorIdleCycleTime: PULONG64, + ) -> BOOL; + pub fn QueryIdleProcessorCycleTimeEx( + Group: USHORT, BufferLength: PULONG, ProcessorIdleCycleTime: PULONG64, + ) -> BOOL; + pub fn QueryInformationJobObject( + hJob: HANDLE, JobObjectInformationClass: JOBOBJECTINFOCLASS, + lpJobObjectInformation: LPVOID, cbJobObjectInformationLength: DWORD, + lpReturnLength: LPDWORD, + ) -> BOOL; + pub fn QueryMemoryResourceNotification( + ResourceNotificationHandle: HANDLE, ResourceState: PBOOL, + ) -> BOOL; + pub fn QueryPerformanceCounter(lpPerformanceCount: *mut LARGE_INTEGER) -> BOOL; + pub fn QueryPerformanceFrequency(lpFrequency: *mut LARGE_INTEGER) -> BOOL; + pub fn QueryProcessAffinityUpdateMode(hProcess: HANDLE, lpdwFlags: LPDWORD) -> BOOL; + pub fn QueryProcessCycleTime(ProcessHandle: HANDLE, CycleTime: PULONG64) -> BOOL; + pub fn QueryProtectedPolicy(PolicyGuid: LPCGUID, PolicyValue: PULONG_PTR) -> BOOL; + pub fn QueryThreadCycleTime(ThreadHandle: HANDLE, CycleTime: PULONG64) -> BOOL; + pub fn QueryThreadProfiling(ThreadHandle: HANDLE, Enabled: PBOOLEAN) -> DWORD; + pub fn QueryThreadpoolStackInformation( + ptpp: PTP_POOL, ptpsi: PTP_POOL_STACK_INFORMATION, + ) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn QueryUmsThreadInformation( + UmsThread: PUMS_CONTEXT, UmsThreadInfoClass: UMS_THREAD_INFO_CLASS, + UmsThreadInformation: PVOID, UmsThreadInformationLength: ULONG, ReturnLength: PULONG, + ) -> BOOL; + pub fn QueryUnbiasedInterruptTime(UnbiasedTime: PULONGLONG) -> BOOL; + pub fn QueueUserAPC(pfnAPC: PAPCFUNC, hThread: HANDLE, dwData: ULONG_PTR) -> DWORD; + pub fn QueueUserWorkItem( + Function: LPTHREAD_START_ROUTINE, Context: PVOID, Flags: ULONG, + ) -> BOOL; + pub fn RaiseException( + dwExceptionCode: DWORD, dwExceptionFlags: DWORD, nNumberOfArguments: DWORD, + lpArguments: *const ULONG_PTR, + ); + pub fn RaiseFailFastException( + pExceptionRecord: PEXCEPTION_RECORD, pContextRecord: PCONTEXT, dwFlags: DWORD, + ); + pub fn ReOpenFile( + hOriginalFile: HANDLE, dwDesiredAccess: DWORD, dwShareMode: DWORD, dwFlags: DWORD, + ) -> HANDLE; + pub fn ReadConsoleA( + hConsoleInput: HANDLE, lpBuffer: LPVOID, nNumberOfCharsToRead: DWORD, + lpNumberOfCharsRead: LPDWORD, pInputControl: PCONSOLE_READCONSOLE_CONTROL, + ) -> BOOL; + pub fn ReadConsoleInputA( + hConsoleInput: HANDLE, lpBuffer: PINPUT_RECORD, nLength: DWORD, + lpNumberOfEventsRead: LPDWORD, + ) -> BOOL; + pub fn ReadConsoleInputW( + hConsoleInput: HANDLE, lpBuffer: PINPUT_RECORD, nLength: DWORD, + lpNumberOfEventsRead: LPDWORD, + ) -> BOOL; + pub fn ReadConsoleOutputA( + hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, dwBufferSize: COORD, dwBufferCoord: COORD, + lpReadRegion: PSMALL_RECT, + ) -> BOOL; + pub fn ReadConsoleOutputAttribute( + hConsoleOutput: HANDLE, lpAttribute: LPWORD, nLength: DWORD, dwReadCoord: COORD, + lpNumberOfAttrsRead: LPDWORD, + ) -> BOOL; + pub fn ReadConsoleOutputCharacterA( + hConsoleOutput: HANDLE, lpCharacter: LPSTR, nLength: DWORD, dwReadCoord: COORD, + lpNumberOfCharsRead: LPDWORD, + ) -> BOOL; + pub fn ReadConsoleOutputCharacterW( + hConsoleOutput: HANDLE, lpCharacter: LPWSTR, nLength: DWORD, dwReadCoord: COORD, + lpNumberOfCharsRead: LPDWORD, + ) -> BOOL; + pub fn ReadConsoleOutputW( + hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, dwBufferSize: COORD, dwBufferCoord: COORD, + lpReadRegion: PSMALL_RECT, + ) -> BOOL; + pub fn ReadConsoleW( + hConsoleInput: HANDLE, lpBuffer: LPVOID, nNumberOfCharsToRead: DWORD, + lpNumberOfCharsRead: LPDWORD, pInputControl: PCONSOLE_READCONSOLE_CONTROL, + ) -> BOOL; + pub fn ReadDirectoryChangesW( + hDirectory: HANDLE, lpBuffer: LPVOID, nBufferLength: DWORD, bWatchSubtree: BOOL, + dwNotifyFilter: DWORD, lpBytesReturned: LPDWORD, lpOverlapped: LPOVERLAPPED, + lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE, + ) -> BOOL; + pub fn ReadFile( + hFile: HANDLE, lpBuffer: LPVOID, nNumberOfBytesToRead: DWORD, lpNumberOfBytesRead: LPDWORD, + lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn ReadFileEx( + hFile: HANDLE, lpBuffer: LPVOID, nNumberOfBytesToRead: DWORD, lpOverlapped: LPOVERLAPPED, + lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE, + ) -> BOOL; + pub fn ReadFileScatter( + hFile: HANDLE, aSegmentArray: *mut FILE_SEGMENT_ELEMENT, nNumberOfBytesToRead: DWORD, + lpReserved: LPDWORD, lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn ReadProcessMemory( + hProcess: HANDLE, lpBaseAddress: LPCVOID, lpBuffer: LPVOID, nSize: SIZE_T, + lpNumberOfBytesRead: *mut SIZE_T, + ) -> BOOL; + pub fn ReadThreadProfilingData( + PerformanceDataHandle: HANDLE, Flags: DWORD, PerformanceData: PPERFORMANCE_DATA, + ) -> DWORD; + pub fn RegisterApplicationRecoveryCallback( + pRecoveyCallback: APPLICATION_RECOVERY_CALLBACK, pvParameter: PVOID, dwPingInterval: DWORD, + dwFlags: DWORD, + ) -> HRESULT; + pub fn RegisterApplicationRestart(pwzCommandline: PCWSTR, dwFlags: DWORD) -> HRESULT; + pub fn RegisterBadMemoryNotification(Callback: PBAD_MEMORY_CALLBACK_ROUTINE) -> PVOID; + // pub fn RegisterWaitForInputIdle(); + pub fn RegisterWaitForSingleObject( + phNewWaitObject: PHANDLE, hObject: HANDLE, Callback: WAITORTIMERCALLBACK, Context: PVOID, + dwMilliseconds: ULONG, dwFlags: ULONG, + ) -> BOOL; + pub fn RegisterWaitForSingleObjectEx( + hObject: HANDLE, Callback: WAITORTIMERCALLBACK, Context: PVOID, dwMilliseconds: ULONG, + dwFlags: ULONG, + ) -> HANDLE; + // pub fn RegisterWaitUntilOOBECompleted(); + pub fn ReleaseActCtx(hActCtx: HANDLE); + pub fn ReleaseMutex(hMutex: HANDLE) -> BOOL; + pub fn ReleaseMutexWhenCallbackReturns(pci: PTP_CALLBACK_INSTANCE, mutex: HANDLE); + pub fn ReleaseSRWLockExclusive(SRWLock: PSRWLOCK); + pub fn ReleaseSRWLockShared(SRWLock: PSRWLOCK); + pub fn ReleaseSemaphore( + hSemaphore: HANDLE, lReleaseCount: LONG, lpPreviousCount: LPLONG, + ) -> BOOL; + pub fn ReleaseSemaphoreWhenCallbackReturns( + pci: PTP_CALLBACK_INSTANCE, sem: HANDLE, crel: DWORD, + ); + pub fn RemoveDirectoryA(lpPathName: LPCSTR) -> BOOL; + pub fn RemoveDirectoryTransactedA(lpPathName: LPCSTR, hTransaction: HANDLE) -> BOOL; + pub fn RemoveDirectoryTransactedW(lpPathName: LPCWSTR, hTransaction: HANDLE) -> BOOL; + pub fn RemoveDirectoryW(lpPathName: LPCWSTR) -> BOOL; + pub fn RemoveDllDirectory(Cookie: DLL_DIRECTORY_COOKIE) -> BOOL; + // pub fn RemoveLocalAlternateComputerNameA(); + // pub fn RemoveLocalAlternateComputerNameW(); + pub fn RemoveSecureMemoryCacheCallback(pfnCallBack: PSECURE_MEMORY_CACHE_CALLBACK) -> BOOL; + pub fn RemoveVectoredContinueHandler(Handle: PVOID) -> ULONG; + pub fn RemoveVectoredExceptionHandler(Handle: PVOID) -> ULONG; + pub fn ReplaceFileA( + lpReplacedFileName: LPCSTR, lpReplacementFileName: LPCSTR, lpBackupFileName: LPCSTR, + dwReplaceFlags: DWORD, lpExclude: LPVOID, lpReserved: LPVOID, + ); + pub fn ReplaceFileW( + lpReplacedFileName: LPCWSTR, lpReplacementFileName: LPCWSTR, lpBackupFileName: LPCWSTR, + dwReplaceFlags: DWORD, lpExclude: LPVOID, lpReserved: LPVOID, + ); + pub fn ReplacePartitionUnit( + TargetPartition: PWSTR, SparePartition: PWSTR, Flags: ULONG, + ) -> BOOL; + pub fn RequestDeviceWakeup(hDevice: HANDLE) -> BOOL; + pub fn RequestWakeupLatency(latency: LATENCY_TIME) -> BOOL; + pub fn ResetEvent(hEvent: HANDLE) -> BOOL; + pub fn ResetWriteWatch(lpBaseAddress: LPVOID, dwRegionSize: SIZE_T) -> UINT; + // pub fn ResolveDelayLoadedAPI(); + // pub fn ResolveDelayLoadsFromDll(); + pub fn ResolveLocaleName( + lpNameToResolve: LPCWSTR, lpLocaleName: LPWSTR, cchLocaleName: c_int, + ) -> c_int; + pub fn RestoreLastError(dwErrCode: DWORD); + pub fn ResumeThread(hThread: HANDLE) -> DWORD; + #[cfg(target_arch = "arm")] + pub fn RtlAddFunctionTable( + FunctionTable: PRUNTIME_FUNCTION, EntryCount: DWORD, BaseAddress: DWORD, + ) -> BOOLEAN; + #[cfg(target_arch = "x86_64")] + pub fn RtlAddFunctionTable( + FunctionTable: PRUNTIME_FUNCTION, EntryCount: DWORD, BaseAddress: DWORD64, + ) -> BOOLEAN; + pub fn RtlCaptureContext(ContextRecord: PCONTEXT); + pub fn RtlCaptureStackBackTrace( + FramesToSkip: DWORD, FramesToCapture: DWORD, BackTrace: *mut PVOID, BackTraceHash: PDWORD, + ) -> WORD; + // #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn RtlCompareMemory(Source1: *const VOID, Source2: *const VOID, Length: SIZE_T) -> SIZE_T; + // #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn RtlCopyMemory(Destination: PVOID, Source: *const VOID, Length: SIZE_T); + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn RtlDeleteFunctionTable(FunctionTable: PRUNTIME_FUNCTION) -> BOOLEAN; + // pub fn RtlFillMemory(); + #[cfg(target_arch = "arm")] + pub fn RtlInstallFunctionTableCallback( + TableIdentifier: DWORD, BaseAddress: DWORD, Length: DWORD, + Callback: PGET_RUNTIME_FUNCTION_CALLBACK, Context: PVOID, OutOfProcessCallbackDll: PCWSTR, + ) -> BOOLEAN; + #[cfg(target_arch = "x86_64")] + pub fn RtlInstallFunctionTableCallback( + TableIdentifier: DWORD64, BaseAddress: DWORD64, Length: DWORD, + Callback: PGET_RUNTIME_FUNCTION_CALLBACK, Context: PVOID, OutOfProcessCallbackDll: PCWSTR, + ) -> BOOLEAN; + #[cfg(target_arch = "arm")] + pub fn RtlLookupFunctionEntry( + ControlPc: ULONG_PTR, ImageBase: PDWORD, HistoryTable: PUNWIND_HISTORY_TABLE, + ) -> PRUNTIME_FUNCTION; + #[cfg(target_arch = "x86_64")] + pub fn RtlLookupFunctionEntry( + ControlPc: DWORD64, ImageBase: PDWORD64, HistoryTable: PUNWIND_HISTORY_TABLE, + ) -> PRUNTIME_FUNCTION; + // pub fn RtlMoveMemory(); + // #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn RtlPcToFileHeader(PcValue: PVOID, BaseOfImage: *mut PVOID) -> PVOID; + // #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + // pub fn RtlRaiseException(); + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn RtlRestoreContext(ContextRecord: PCONTEXT, ExceptionRecord: *mut EXCEPTION_RECORD); + pub fn RtlUnwind( + TargetFrame: PVOID, TargetIp: PVOID, ExceptionRecord: PEXCEPTION_RECORD, ReturnValue: PVOID, + ); + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn RtlUnwindEx( + TargetFrame: PVOID, TargetIp: PVOID, ExceptionRecord: PEXCEPTION_RECORD, ReturnValue: PVOID, + ContextRecord: PCONTEXT, HistoryTable: PUNWIND_HISTORY_TABLE, + ); + #[cfg(target_arch = "arm")] + pub fn RtlVirtualUnwind( + HandlerType: DWORD, ImageBase: DWORD, ControlPc: DWORD, FunctionEntry: PRUNTIME_FUNCTION, + ContextRecord: PCONTEXT, HandlerData: *mut PVOID, EstablisherFrame: PDWORD, + ContextPointers: PKNONVOLATILE_CONTEXT_POINTERS, + ) -> PEXCEPTION_ROUTINE; + #[cfg(target_arch = "x86_64")] + pub fn RtlVirtualUnwind( + HandlerType: DWORD, ImageBase: DWORD64, ControlPc: DWORD64, + FunctionEntry: PRUNTIME_FUNCTION, ContextRecord: PCONTEXT, HandlerData: *mut PVOID, + EstablisherFrame: PDWORD64, ContextPointers: PKNONVOLATILE_CONTEXT_POINTERS, + ) -> PEXCEPTION_ROUTINE; + // pub fn RtlZeroMemory(); + pub fn ScrollConsoleScreenBufferA( + hConsoleOutput: HANDLE, lpScrollRectangle: *const SMALL_RECT, + lpClipRectangle: *const SMALL_RECT, dwDestinationOrigin: COORD, lpFill: *const CHAR_INFO, + ) -> BOOL; + pub fn ScrollConsoleScreenBufferW( + hConsoleOutput: HANDLE, lpScrollRectangle: *const SMALL_RECT, + lpClipRectangle: *const SMALL_RECT, dwDestinationOrigin: COORD, lpFill: *const CHAR_INFO, + ) -> BOOL; + pub fn SearchPathA( + lpPath: LPCSTR, lpFileName: LPCSTR, lpExtension: LPCSTR, nBufferLength: DWORD, + lpBuffer: LPSTR, lpFilePart: *mut LPSTR, + ) -> DWORD; + pub fn SearchPathW( + lpPath: LPCWSTR, lpFileName: LPCWSTR, lpExtension: LPCWSTR, nBufferLength: DWORD, + lpBuffer: LPWSTR, lpFilePart: *mut LPWSTR, + ) -> DWORD; + pub fn SetCachedSigningLevel( + SourceFiles: PHANDLE, SourceFileCount: ULONG, Flags: ULONG, TargetFile: HANDLE, + ) -> BOOL; + pub fn SetCalendarInfoA( + Locale: LCID, Calendar: CALID, CalType: CALTYPE, lpCalData: LPCSTR, + ) -> BOOL; + pub fn SetCalendarInfoW( + Locale: LCID, Calendar: CALID, CalType: CALTYPE, lpCalData: LPCWSTR, + ) -> BOOL; + pub fn SetCommBreak(hFile: HANDLE) -> BOOL; + pub fn SetCommConfig(hCommDev: HANDLE, lpCC: LPCOMMCONFIG, dwSize: DWORD) -> BOOL; + pub fn SetCommMask(hFile: HANDLE, dwEvtMask: DWORD) -> BOOL; + pub fn SetCommState(hFile: HANDLE, lpDCB: LPDCB) -> BOOL; + pub fn SetCommTimeouts(hFile: HANDLE, lpCommTimeouts: LPCOMMTIMEOUTS) -> BOOL; + pub fn SetComputerNameA(lpComputerName: LPCSTR) -> BOOL; + pub fn SetComputerNameEx2W( + NameType: COMPUTER_NAME_FORMAT, Flags: DWORD, lpBuffer: LPCWSTR, + ) -> BOOL; + pub fn SetComputerNameExA(NameType: COMPUTER_NAME_FORMAT, lpBuffer: LPCSTR) -> BOOL; + pub fn SetComputerNameExW(NameType: COMPUTER_NAME_FORMAT, lpBuffer: LPCWSTR) -> BOOL; + pub fn SetComputerNameW(lpComputerName: LPCWSTR) -> BOOL; + pub fn SetConsoleActiveScreenBuffer(hConsoleOutput: HANDLE) -> BOOL; + pub fn SetConsoleCP(wCodePageID: UINT) -> BOOL; + pub fn SetConsoleCtrlHandler(HandlerRoutine: PHANDLER_ROUTINE, Add: BOOL) -> BOOL; + // pub fn SetConsoleCursor(); + pub fn SetConsoleCursorInfo( + hConsoleOutput: HANDLE, lpConsoleCursorInfo: *const CONSOLE_CURSOR_INFO, + ) -> BOOL; + pub fn SetConsoleCursorPosition(hConsoleOutput: HANDLE, dwCursorPosition: COORD) -> BOOL; + pub fn SetConsoleDisplayMode( + hConsoleOutput: HANDLE, dwFlags: DWORD, lpNewScreenBufferDimensions: PCOORD, + ) -> BOOL; + pub fn SetConsoleHistoryInfo(lpConsoleHistoryInfo: PCONSOLE_HISTORY_INFO) -> BOOL; + pub fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) -> BOOL; + pub fn SetConsoleOutputCP(wCodePageID: UINT) -> BOOL; + pub fn SetConsoleScreenBufferInfoEx( + hConsoleOutput: HANDLE, lpConsoleScreenBufferInfoEx: PCONSOLE_SCREEN_BUFFER_INFOEX, + ) -> BOOL; + pub fn SetConsoleScreenBufferSize(hConsoleOutput: HANDLE, dwSize: COORD) -> BOOL; + pub fn SetConsoleTextAttribute(hConsoleOutput: HANDLE, wAttributes: WORD) -> BOOL; + pub fn SetConsoleTitleA(lpConsoleTitle: LPCSTR) -> BOOL; + pub fn SetConsoleTitleW(lpConsoleTitle: LPCWSTR) -> BOOL; + pub fn SetConsoleWindowInfo( + hConsoleOutput: HANDLE, bAbsolute: BOOL, lpConsoleWindow: *const SMALL_RECT, + ) -> BOOL; + pub fn SetCriticalSectionSpinCount( + lpCriticalSection: LPCRITICAL_SECTION, dwSpinCount: DWORD, + ) -> DWORD; + pub fn SetCurrentConsoleFontEx( + hConsoleOutput: HANDLE, bMaximumWindow: BOOL, lpConsoleCurrentFontEx: PCONSOLE_FONT_INFOEX, + ) -> BOOL; + pub fn SetCurrentDirectoryA(lpPathName: LPCSTR) -> BOOL; + pub fn SetCurrentDirectoryW(lpPathName: LPCWSTR) -> BOOL; + pub fn SetDefaultCommConfigA(lpszName: LPCSTR, lpCC: LPCOMMCONFIG, dwSize: DWORD) -> BOOL; + pub fn SetDefaultCommConfigW(lpszName: LPCWSTR, lpCC: LPCOMMCONFIG, dwSize: DWORD) -> BOOL; + pub fn SetDefaultDllDirectories(DirectoryFlags: DWORD) -> BOOL; + pub fn SetDllDirectoryA(lpPathName: LPCSTR) -> BOOL; + pub fn SetDllDirectoryW(lpPathName: LPCWSTR) -> BOOL; + pub fn SetDynamicTimeZoneInformation( + lpTimeZoneInformation: *const DYNAMIC_TIME_ZONE_INFORMATION, + ) -> BOOL; + pub fn SetEndOfFile(hFile: HANDLE) -> BOOL; + pub fn SetEnvironmentStringsA(NewEnvironment: LPCH) -> BOOL; + pub fn SetEnvironmentStringsW(NewEnvironment: LPWCH) -> BOOL; + pub fn SetEnvironmentVariableA(lpName: LPCSTR, lpValue: LPCSTR) -> BOOL; + pub fn SetEnvironmentVariableW(lpName: LPCWSTR, lpValue: LPCWSTR) -> BOOL; + pub fn SetErrorMode(uMode: UINT) -> UINT; + pub fn SetEvent(hEvent: HANDLE) -> BOOL; + pub fn SetEventWhenCallbackReturns(pci: PTP_CALLBACK_INSTANCE, evt: HANDLE); + pub fn SetFileApisToANSI(); + pub fn SetFileApisToOEM(); + pub fn SetFileAttributesA(lpFileName: LPCSTR, dwFileAttributes: DWORD) -> BOOL; + pub fn SetFileAttributesTransactedA( + lpFileName: LPCSTR, dwFileAttributes: DWORD, hTransaction: HANDLE, + ) -> BOOL; + pub fn SetFileAttributesTransactedW( + lpFileName: LPCWSTR, dwFileAttributes: DWORD, hTransaction: HANDLE, + ) -> BOOL; + pub fn SetFileAttributesW(lpFileName: LPCWSTR, dwFileAttributes: DWORD) -> BOOL; + pub fn SetFileBandwidthReservation( + hFile: HANDLE, nPeriodMilliseconds: DWORD, nBytesPerPeriod: DWORD, bDiscardable: BOOL, + lpTransferSize: LPDWORD, lpNumOutstandingRequests: LPDWORD, + ) -> BOOL; + pub fn SetFileCompletionNotificationModes(FileHandle: HANDLE, Flags: UCHAR) -> BOOL; + pub fn SetFileInformationByHandle( + hFile: HANDLE, FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, lpFileInformation: LPVOID, + dwBufferSize: DWORD, + ) -> BOOL; + pub fn SetFileIoOverlappedRange( + FileHandle: HANDLE, OverlappedRangeStart: PUCHAR, Length: ULONG, + ) -> BOOL; + pub fn SetFilePointer( + hFile: HANDLE, lDistanceToMove: LONG, lpDistanceToMoveHigh: PLONG, dwMoveMethod: DWORD, + ) -> DWORD; + pub fn SetFilePointerEx( + hFile: HANDLE, liDistanceToMove: LARGE_INTEGER, lpNewFilePointer: PLARGE_INTEGER, + dwMoveMethod: DWORD, + ) -> BOOL; + pub fn SetFileShortNameA(hFile: HANDLE, lpShortName: LPCSTR) -> BOOL; + pub fn SetFileShortNameW(hFile: HANDLE, lpShortName: LPCWSTR) -> BOOL; + pub fn SetFileTime( + hFile: HANDLE, lpCreationTime: *const FILETIME, lpLastAccessTime: *const FILETIME, + lpLastWriteTime: *const FILETIME, + ) -> BOOL; + pub fn SetFileValidData(hFile: HANDLE, ValidDataLength: LONGLONG) -> BOOL; + pub fn SetFirmwareEnvironmentVariableA( + lpName: LPCSTR, lpGuid: LPCSTR, pValue: PVOID, nSize: DWORD, + ) -> BOOL; + pub fn SetFirmwareEnvironmentVariableExA( + lpName: LPCSTR, lpGuid: LPCSTR, pValue: PVOID, nSize: DWORD, dwAttributes: DWORD, + ) -> BOOL; + pub fn SetFirmwareEnvironmentVariableExW( + lpName: LPCWSTR, lpGuid: LPCWSTR, pValue: PVOID, nSize: DWORD, dwAttributes: DWORD, + ) -> BOOL; + pub fn SetFirmwareEnvironmentVariableW( + lpName: LPCWSTR, lpGuid: LPCWSTR, pValue: PVOID, nSize: DWORD, + ) -> BOOL; + pub fn SetHandleCount(uNumber: UINT) -> UINT; + pub fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) -> BOOL; + pub fn SetInformationJobObject( + hJob: HANDLE, JobObjectInformationClass: JOBOBJECTINFOCLASS, + lpJobObjectInformation: LPVOID, cbJobObjectInformationLength: DWORD, + ) -> BOOL; + pub fn SetLastError(dwErrCode: DWORD); + // pub fn SetLocalPrimaryComputerNameA(); + // pub fn SetLocalPrimaryComputerNameW(); + pub fn SetLocalTime(lpSystemTime: *const SYSTEMTIME) -> BOOL; + pub fn SetLocaleInfoA(Locale: LCID, LCType: LCTYPE, lpLCData: LPCSTR) -> BOOL; + pub fn SetLocaleInfoW(Locale: LCID, LCType: LCTYPE, lpLCData: LPCWSTR) -> BOOL; + pub fn SetMailslotInfo(hMailslot: HANDLE, lReadTimeout: DWORD) -> BOOL; + pub fn SetMessageWaitingIndicator(hMsgIndicator: HANDLE, ulMsgCount: ULONG) -> BOOL; + pub fn SetNamedPipeAttribute( + Pipe: HANDLE, AttributeType: PIPE_ATTRIBUTE_TYPE, AttributeName: PSTR, + AttributeValue: PVOID, AttributeValueLength: SIZE_T, + ) -> BOOL; + pub fn SetNamedPipeHandleState( + hNamedPipe: HANDLE, lpMode: LPDWORD, lpMaxCollectionCount: LPDWORD, + lpCollectDataTimeout: LPDWORD, + ) -> BOOL; + pub fn SetPriorityClass(hProcess: HANDLE, dwPriorityClass: DWORD) -> BOOL; + pub fn SetProcessAffinityMask(hProcess: HANDLE, dwProcessAffinityMask: DWORD) -> BOOL; + pub fn SetProcessAffinityUpdateMode(hProcess: HANDLE, dwFlags: DWORD) -> BOOL; + pub fn SetProcessDEPPolicy(dwFlags: DWORD) -> BOOL; + pub fn SetProcessInformation( + hProcess: HANDLE, ProcessInformationClass: PROCESS_INFORMATION_CLASS, + ProcessInformation: LPVOID, ProcessInformationSize: DWORD, + ) -> BOOL; + pub fn SetProcessMitigationPolicy( + MitigationPolicy: PROCESS_MITIGATION_POLICY, lpBuffer: PVOID, dwLength: SIZE_T, + ) -> BOOL; + pub fn SetProcessPreferredUILanguages( + dwFlags: DWORD, pwszLanguagesBuffer: PCZZWSTR, pulNumLanguages: PULONG, + ) -> BOOL; + pub fn SetProcessPriorityBoost(hProcess: HANDLE, bDisablePriorityBoost: BOOL) -> BOOL; + pub fn SetProcessShutdownParameters(dwLevel: DWORD, dwFlags: DWORD) -> BOOL; + pub fn SetProcessWorkingSetSize( + hProcess: HANDLE, dwMinimumWorkingSetSize: SIZE_T, dwMaximumWorkingSetSize: SIZE_T, + ) -> BOOL; + pub fn SetProcessWorkingSetSizeEx( + hProcess: HANDLE, dwMinimumWorkingSetSize: SIZE_T, dwMaximumWorkingSetSize: SIZE_T, + Flags: DWORD, + ) -> BOOL; + pub fn SetProtectedPolicy( + PolicyGuid: LPCGUID, PolicyValue: ULONG_PTR, OldPolicyValue: PULONG_PTR, + ) -> BOOL; + pub fn SetSearchPathMode(Flags: DWORD) -> BOOL; + pub fn SetStdHandle(nStdHandle: DWORD, hHandle: HANDLE) -> BOOL; + pub fn SetStdHandleEx(nStdHandle: DWORD, hHandle: HANDLE, phPrevValue: PHANDLE) -> BOOL; + pub fn SetSystemFileCacheSize( + MinimumFileCacheSize: SIZE_T, MaximumFileCacheSize: SIZE_T, Flags: DWORD, + ) -> BOOL; + pub fn SetSystemPowerState(fSuspend: BOOL, fForce: BOOL) -> BOOL; + pub fn SetSystemTime(lpSystemTime: *const SYSTEMTIME) -> BOOL; + pub fn SetSystemTimeAdjustment(dwTimeAdjustment: DWORD, bTimeAdjustmentDisabled: BOOL) -> BOOL; + pub fn SetTapeParameters( + hDevice: HANDLE, dwOperation: DWORD, lpTapeInformation: LPVOID, + ) -> DWORD; + pub fn SetTapePosition( + hDevice: HANDLE, dwPositionMethod: DWORD, dwPartition: DWORD, + dwOffsetLow: DWORD, dwOffsetHigh: DWORD, bImmediate: BOOL + ) -> DWORD; + pub fn SetThreadAffinityMask(hThread: HANDLE, dwThreadAffinityMask: DWORD_PTR) -> DWORD_PTR; + pub fn SetThreadContext(hThread: HANDLE, lpContext: *const CONTEXT) -> BOOL; + pub fn SetThreadErrorMode(dwNewMode: DWORD, lpOldMode: LPDWORD) -> BOOL; + pub fn SetThreadExecutionState(esFlags: EXECUTION_STATE) -> EXECUTION_STATE; + pub fn SetThreadGroupAffinity( + hThread: HANDLE, GroupAffinity: *const GROUP_AFFINITY, + PreviousGroupAffinity: PGROUP_AFFINITY, + ) -> BOOL; + pub fn SetThreadIdealProcessor(hThread: HANDLE, dwIdealProcessor: DWORD) -> DWORD; + pub fn SetThreadIdealProcessorEx( + hThread: HANDLE, lpIdealProcessor: PPROCESSOR_NUMBER, + lpPreviousIdealProcessor: PPROCESSOR_NUMBER, + ) -> BOOL; + pub fn SetThreadInformation( + hThread: HANDLE, ThreadInformationClass: THREAD_INFORMATION_CLASS, + ThreadInformation: LPVOID, ThreadInformationSize: DWORD, + ); + pub fn SetThreadLocale(Locale: LCID) -> BOOL; + pub fn SetThreadPreferredUILanguages( + dwFlags: DWORD, pwszLanguagesBuffer: PCZZWSTR, pulNumLanguages: PULONG, + ) -> BOOL; + pub fn SetThreadPriority(hThread: HANDLE, nPriority: c_int) -> BOOL; + pub fn SetThreadPriorityBoost(hThread: HANDLE, bDisablePriorityBoost: BOOL) -> BOOL; + pub fn SetThreadStackGuarantee(StackSizeInBytes: PULONG) -> BOOL; + pub fn SetThreadUILanguage(LangId: LANGID) -> LANGID; + pub fn SetThreadpoolStackInformation( + ptpp: PTP_POOL, ptpsi: PTP_POOL_STACK_INFORMATION, + ) -> BOOL; + pub fn SetThreadpoolThreadMaximum(ptpp: PTP_POOL, cthrdMost: DWORD); + pub fn SetThreadpoolThreadMinimum(ptpp: PTP_POOL, cthrdMic: DWORD) -> BOOL; + pub fn SetThreadpoolTimer( + pti: PTP_TIMER, pftDueTime: PFILETIME, msPeriod: DWORD, msWindowLength: DWORD, + ); + pub fn SetThreadpoolTimerEx( + pti: PTP_TIMER, pftDueTime: PFILETIME, msPeriod: DWORD, msWindowLength: DWORD, + ) -> BOOL; + pub fn SetThreadpoolWait(pwa: PTP_WAIT, h: HANDLE, pftTimeout: PFILETIME); + pub fn SetThreadpoolWaitEx( + pwa: PTP_WAIT, h: HANDLE, pftTimeout: PFILETIME, Reserved: PVOID, + ) -> BOOL; + pub fn SetTimeZoneInformation(lpTimeZoneInformation: *const TIME_ZONE_INFORMATION) -> BOOL; + pub fn SetTimerQueueTimer( + TimerQueue: HANDLE, Callback: WAITORTIMERCALLBACK, Parameter: PVOID, DueTime: DWORD, + Period: DWORD, PreferIo: BOOL, + ) -> HANDLE; + #[cfg(target_arch = "x86_64")] + pub fn SetUmsThreadInformation( + UmsThread: PUMS_CONTEXT, UmsThreadInfoClass: UMS_THREAD_INFO_CLASS, + UmsThreadInformation: PVOID, UmsThreadInformationLength: ULONG, + ) -> BOOL; + pub fn SetUnhandledExceptionFilter( + lpTopLevelExceptionFilter: LPTOP_LEVEL_EXCEPTION_FILTER, + ) -> LPTOP_LEVEL_EXCEPTION_FILTER; + pub fn SetUserGeoID(GeoId: GEOID) -> BOOL; + pub fn SetVolumeLabelA(lpRootPathName: LPCSTR, lpVolumeName: LPCSTR) -> BOOL; + pub fn SetVolumeLabelW(lpRootPathName: LPCWSTR, lpVolumeName: LPCWSTR) -> BOOL; + pub fn SetVolumeMountPointA(lpszVolumeMountPoint: LPCSTR, lpszVolumeName: LPCSTR) -> BOOL; + pub fn SetVolumeMountPointW(lpszVolumeMountPoint: LPCWSTR, lpszVolumeName: LPCWSTR) -> BOOL; + pub fn SetWaitableTimer( + hTimer: HANDLE, lpDueTime: *const LARGE_INTEGER, lPeriod: LONG, + pfnCompletionRoutine: PTIMERAPCROUTINE, lpArgToCompletionRoutine: LPVOID, fResume: BOOL, + ) -> BOOL; + pub fn SetWaitableTimerEx( + hTimer: HANDLE, lpDueTime: *const LARGE_INTEGER, lPeriod: LONG, + pfnCompletionRoutine: PTIMERAPCROUTINE, lpArgToCompletionRoutine: LPVOID, + WakeContext: PREASON_CONTEXT, TolerableDelay: ULONG, + ) -> BOOL; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + pub fn SetXStateFeaturesMask(Context: PCONTEXT, FeatureMask: DWORD64) -> BOOL; + pub fn SetupComm(hFile: HANDLE, dwInQueue: DWORD, dwOutQueue: DWORD) -> BOOL; + pub fn SignalObjectAndWait( + hObjectToSignal: HANDLE, hObjectToWaitOn: HANDLE, dwMilliseconds: DWORD, bAlertable: BOOL, + ) -> DWORD; + pub fn SizeofResource(hModule: HMODULE, hResInfo: HRSRC) -> DWORD; + pub fn Sleep(dwMilliseconds: DWORD); + pub fn SleepConditionVariableCS( + ConditionVariable: PCONDITION_VARIABLE, CriticalSection: PCRITICAL_SECTION, + dwMilliseconds: DWORD, + ) -> BOOL; + pub fn SleepConditionVariableSRW( + ConditionVariable: PCONDITION_VARIABLE, SRWLock: PSRWLOCK, dwMilliseconds: DWORD, + Flags: ULONG, + ) -> BOOL; + pub fn SleepEx(dwMilliseconds: DWORD, bAlertable: BOOL) -> DWORD; + pub fn StartThreadpoolIo(pio: PTP_IO); + pub fn SubmitThreadpoolWork(pwk: PTP_WORK); + pub fn SuspendThread(hThread: HANDLE) -> DWORD; + pub fn SwitchToFiber(lpFiber: LPVOID); + pub fn SwitchToThread() -> BOOL; + pub fn SystemTimeToFileTime(lpSystemTime: *const SYSTEMTIME, lpFileTime: LPFILETIME) -> BOOL; + pub fn SystemTimeToTzSpecificLocalTime( + lpTimeZoneInformation: *const TIME_ZONE_INFORMATION, lpUniversalTime: *const SYSTEMTIME, + lpLocalTime: LPSYSTEMTIME, + ) -> BOOL; + pub fn SystemTimeToTzSpecificLocalTimeEx( + lpTimeZoneInformation: *const DYNAMIC_TIME_ZONE_INFORMATION, + lpUniversalTime: *const SYSTEMTIME, lpLocalTime: LPSYSTEMTIME, + ) -> BOOL; + pub fn TerminateJobObject(hJob: HANDLE, uExitCode: UINT) -> BOOL; + pub fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) -> BOOL; + pub fn TerminateThread(hThread: HANDLE, dwExitCode: DWORD) -> BOOL; + pub fn Thread32First(hSnapshot: HANDLE, lpte: LPTHREADENTRY32) -> BOOL; + pub fn Thread32Next(hSnapshot: HANDLE, lpte: LPTHREADENTRY32) -> BOOL; + pub fn TlsAlloc() -> DWORD; + pub fn TlsFree(dwTlsIndex: DWORD) -> BOOL; + pub fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID; + pub fn TlsSetValue(dwTlsIndex: DWORD, lpTlsValue: LPVOID) -> BOOL; + pub fn Toolhelp32ReadProcessMemory(th32ProcessID: DWORD, lpBaseAddress: LPCVOID, + lpBuffer: LPVOID, cbRead: SIZE_T, lpNumberOfBytesRead: *mut SIZE_T + ) -> BOOL; + pub fn TransactNamedPipe( + hNamedPipe: HANDLE, lpInBuffer: LPVOID, nInBufferSize: DWORD, lpOutBuffer: LPVOID, + nOutBufferSize: DWORD, lpBytesRead: LPDWORD, lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn TransmitCommChar(hFile: HANDLE, cChar: c_char) -> BOOL; + pub fn TryAcquireSRWLockExclusive(SRWLock: PSRWLOCK) -> BOOLEAN; + pub fn TryAcquireSRWLockShared(SRWLock: PSRWLOCK) -> BOOLEAN; + pub fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL; + pub fn TrySubmitThreadpoolCallback( + pfns: PTP_SIMPLE_CALLBACK, pv: PVOID, pcbe: PTP_CALLBACK_ENVIRON, + ) -> BOOL; + pub fn TzSpecificLocalTimeToSystemTime( + lpTimeZoneInformation: *const TIME_ZONE_INFORMATION, lpLocalTime: *const SYSTEMTIME, + lpUniversalTime: LPSYSTEMTIME, + ) -> BOOL; + pub fn TzSpecificLocalTimeToSystemTimeEx( + lpTimeZoneInformation: *const DYNAMIC_TIME_ZONE_INFORMATION, + lpLocalTime: *const SYSTEMTIME, lpUniversalTime: LPSYSTEMTIME, + ) -> BOOL; + #[cfg(target_arch = "x86_64")] + pub fn UmsThreadYield(SchedulerParam: PVOID) -> BOOL; + pub fn UnhandledExceptionFilter(ExceptionInfo: *mut EXCEPTION_POINTERS) -> LONG; + pub fn UnlockFile( + hFile: HANDLE, dwFileOffsetLow: DWORD, dwFileOffsetHigh: DWORD, + nNumberOfBytesToUnlockLow: DWORD, nNumberOfBytesToUnlockHigh: DWORD, + ) -> BOOL; + pub fn UnlockFileEx( + hFile: HANDLE, dwReserved: DWORD, nNumberOfBytesToUnlockLow: DWORD, + nNumberOfBytesToUnlockHigh: DWORD, lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn UnmapViewOfFile(lpBaseAddress: LPCVOID) -> BOOL; + pub fn UnregisterApplicationRecoveryCallback() -> HRESULT; + pub fn UnregisterApplicationRestart() -> HRESULT; + pub fn UnregisterBadMemoryNotification(RegistrationHandle: PVOID) -> BOOL; + pub fn UnregisterWait(WaitHandle: HANDLE) -> BOOL; + pub fn UnregisterWaitEx(WaitHandle: HANDLE, CompletionEvent: HANDLE) -> BOOL; + // pub fn UnregisterWaitUntilOOBECompleted(); + pub fn UpdateProcThreadAttribute( + lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST, dwFlags: DWORD, Attribute: DWORD_PTR, + lpValue: PVOID, cbSize: SIZE_T, lpPreviousValue: PVOID, lpReturnSize: PSIZE_T, + ) -> BOOL; + pub fn UpdateResourceA( + hUpdate: HANDLE, lpType: LPCSTR, lpName: LPCSTR, wLanguage: WORD, lpData: LPVOID, cb: DWORD, + ) -> BOOL; + pub fn UpdateResourceW( + hUpdate: HANDLE, lpType: LPCWSTR, lpName: LPCWSTR, wLanguage: WORD, lpData: LPVOID, + cb: DWORD, + ) -> BOOL; + pub fn VerLanguageNameA(wLang: DWORD, szLang: LPSTR, cchLang: DWORD) -> DWORD; + pub fn VerLanguageNameW(wLang: DWORD, szLang: LPWSTR, cchLang: DWORD) -> DWORD; + pub fn VerSetConditionMask( + ConditionMask: ULONGLONG, TypeMask: DWORD, Condition: BYTE, + ) -> ULONGLONG; + pub fn VerifyScripts( + dwFlags: DWORD, lpLocaleScripts: LPCWSTR, cchLocaleScripts: c_int, lpTestScripts: LPCWSTR, + cchTestScripts: c_int, + ) -> BOOL; + pub fn VerifyVersionInfoA( + lpVersionInformation: LPOSVERSIONINFOEXA, dwTypeMask: DWORD, dwlConditionMask: DWORDLONG, + ) -> BOOL; + pub fn VerifyVersionInfoW( + lpVersionInformation: LPOSVERSIONINFOEXW, dwTypeMask: DWORD, dwlConditionMask: DWORDLONG, + ) -> BOOL; + pub fn VirtualAlloc( + lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD, + ) -> LPVOID; + pub fn VirtualAllocEx( + hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, + flProtect: DWORD, + ) -> LPVOID; + pub fn VirtualAllocExNuma( + hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, + flProtect: DWORD, nndPreferred: DWORD, + ) -> LPVOID; + pub fn VirtualFree(lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD) -> BOOL; + pub fn VirtualFreeEx( + hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD, + ) -> BOOL; + pub fn VirtualLock(lpAddress: LPVOID, dwSize: SIZE_T) -> BOOL; + pub fn VirtualProtect( + lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, lpflOldProtect: PDWORD, + ) -> BOOL; + pub fn VirtualProtectEx( + hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, + lpflOldProtect: DWORD, + ) -> BOOL; + pub fn VirtualQuery( + lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: SIZE_T, + ) -> SIZE_T; + pub fn VirtualQueryEx( + hProcess: HANDLE, lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: SIZE_T, + ) -> SIZE_T; + pub fn VirtualUnlock(lpAddress: LPVOID, dwSize: SIZE_T) -> BOOL; + pub fn WTSGetActiveConsoleSessionId() -> DWORD; + pub fn WaitCommEvent(hFile: HANDLE, lpEvtMask: LPDWORD, lpOverlapped: LPOVERLAPPED) -> BOOL; + pub fn WaitForDebugEvent(lpDebugEvent: LPDEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL; + pub fn WaitForMultipleObjects( + nCount: DWORD, lpHandles: *const HANDLE, bWaitAll: BOOL, dwMilliseconds: DWORD, + ) -> DWORD; + pub fn WaitForMultipleObjectsEx( + nCount: DWORD, lpHandles: *const HANDLE, bWaitAll: BOOL, dwMilliseconds: DWORD, + bAlertable: BOOL, + ) -> DWORD; + pub fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; + pub fn WaitForSingleObjectEx( + hHandle: HANDLE, dwMilliseconds: DWORD, bAlertable: BOOL, + ) -> DWORD; + pub fn WaitForThreadpoolIoCallbacks(pio: PTP_IO, fCancelPendingCallbacks: BOOL); + pub fn WaitForThreadpoolTimerCallbacks(pti: PTP_TIMER, fCancelPendingCallbacks: BOOL); + pub fn WaitForThreadpoolWaitCallbacks(pwa: PTP_WAIT, fCancelPendingCallbacks: BOOL); + pub fn WaitForThreadpoolWorkCallbacks(pwk: PTP_WORK, fCancelPendingCallbacks: BOOL); + pub fn WaitNamedPipeA(lpNamedPipeName: LPCSTR, nTimeOut: DWORD) -> BOOL; + pub fn WaitNamedPipeW(lpNamedPipeName: LPCWSTR, nTimeOut: DWORD) -> BOOL; + pub fn WakeAllConditionVariable(ConditionVariable: PCONDITION_VARIABLE); + pub fn WakeConditionVariable(ConditionVariable: PCONDITION_VARIABLE); + pub fn WerGetFlags(hProcess: HANDLE, pdwFlags: PDWORD) -> HRESULT; + pub fn WerRegisterFile( + pwzFile: PCWSTR, regFileType: WER_REGISTER_FILE_TYPE, dwFlags: DWORD, + ) -> HRESULT; + pub fn WerRegisterMemoryBlock(pvAddress: PVOID, dwSize: DWORD) -> HRESULT; + pub fn WerRegisterRuntimeExceptionModule( + pwszOutOfProcessCallbackDll: PCWSTR, pContext: PVOID, + ) -> HRESULT; + pub fn WerSetFlags(dwFlags: DWORD) -> HRESULT; + pub fn WerUnregisterFile(pwzFilePath: PCWSTR) -> HRESULT; + pub fn WerUnregisterMemoryBlock(pvAddress: PVOID) -> HRESULT; + pub fn WerUnregisterRuntimeExceptionModule( + pwszOutOfProcessCallbackDll: PCWSTR, pContext: PVOID, + ) -> HRESULT; + // pub fn WerpInitiateRemoteRecovery(); + pub fn WideCharToMultiByte( + CodePage: UINT, dwFlags: DWORD, lpWideCharStr: LPCWSTR, cchWideChar: c_int, + lpMultiByteStr: LPSTR, cbMultiByte: c_int, lpDefaultChar: LPCSTR, lpUsedDefaultChar: LPBOOL, + ) -> c_int; + pub fn WinExec(lpCmdLine: LPCSTR, uCmdShow: UINT) -> UINT; + pub fn Wow64DisableWow64FsRedirection(OldValue: *mut PVOID) -> BOOL; + pub fn Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection: BOOLEAN) -> BOOLEAN; + pub fn Wow64GetThreadContext(hThread: HANDLE, lpContext: PWOW64_CONTEXT) -> BOOL; + pub fn Wow64GetThreadSelectorEntry( + hThread: HANDLE, dwSelector: DWORD, lpSelectorEntry: PWOW64_LDT_ENTRY, + ) -> BOOL; + pub fn Wow64RevertWow64FsRedirection(OlValue: PVOID) -> BOOL; + pub fn Wow64SetThreadContext(hThread: HANDLE, lpContext: *const WOW64_CONTEXT) -> BOOL; + pub fn Wow64SuspendThread(hThread: HANDLE) -> DWORD; + pub fn WriteConsoleA( + hConsoleOutput: HANDLE, lpBuffer: *const VOID, nNumberOfCharsToWrite: DWORD, + lpNumberOfCharsWritten: LPDWORD, lpReserved: LPVOID, + ) -> BOOL; + pub fn WriteConsoleInputA( + hConsoleInput: HANDLE, lpBuffer: *const INPUT_RECORD, nLength: DWORD, + lpNumberOfEventsWritten: LPDWORD, + ) -> BOOL; + pub fn WriteConsoleInputW( + hConsoleInput: HANDLE, lpBuffer: *const INPUT_RECORD, nLength: DWORD, + lpNumberOfEventsWritten: LPDWORD, + ) -> BOOL; + pub fn WriteConsoleOutputA( + hConsoleOutput: HANDLE, lpBuffer: *const CHAR_INFO, dwBufferSize: COORD, + dwBufferCoord: COORD, lpWriteRegion: PSMALL_RECT, + ) -> BOOL; + pub fn WriteConsoleOutputAttribute( + hConsoleOutput: HANDLE, lpAttribute: *const WORD, nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfAttrsWritten: LPDWORD, + ) -> BOOL; + pub fn WriteConsoleOutputCharacterA( + hConsoleOutput: HANDLE, lpCharacter: LPCSTR, nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfCharsWritten: LPDWORD, + ) -> BOOL; + pub fn WriteConsoleOutputCharacterW( + hConsoleOutput: HANDLE, lpCharacter: LPCWSTR, nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfCharsWritten: LPDWORD, + ) -> BOOL; + pub fn WriteConsoleOutputW( + hConsoleOutput: HANDLE, lpBuffer: *const CHAR_INFO, dwBufferSize: COORD, + dwBufferCoord: COORD, lpWriteRegion: PSMALL_RECT, + ) -> BOOL; + pub fn WriteConsoleW( + hConsoleOutput: HANDLE, lpBuffer: *const VOID, nNumberOfCharsToWrite: DWORD, + lpNumberOfCharsWritten: LPDWORD, lpReserved: LPVOID, + ) -> BOOL; + pub fn WriteFile( + hFile: HANDLE, lpBuffer: LPCVOID, nNumberOfBytesToWrite: DWORD, + lpNumberOfBytesWritten: LPDWORD, lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn WriteFileEx( + hFile: HANDLE, lpBuffer: LPCVOID, nNumberOfBytesToWrite: DWORD, lpOverlapped: LPOVERLAPPED, + lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE, + ) -> BOOL; + pub fn WriteFileGather( + hFile: HANDLE, aSegmentArray: *mut FILE_SEGMENT_ELEMENT, nNumberOfBytesToWrite: DWORD, + lpReserved: LPDWORD, lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn WritePrivateProfileSectionA( + lpAppName: LPCSTR, lpString: LPCSTR, lpFileName: LPCSTR, + ) -> BOOL; + pub fn WritePrivateProfileSectionW( + lpAppName: LPCWSTR, lpString: LPCWSTR, lpFileName: LPCWSTR, + ) -> BOOL; + pub fn WritePrivateProfileStringA( + lpAppName: LPCSTR, lpKeyName: LPCSTR, lpString: LPCSTR, lpFileName: LPCSTR, + ) -> BOOL; + pub fn WritePrivateProfileStringW( + lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpString: LPCWSTR, lpFileName: LPCWSTR, + ) -> BOOL; + pub fn WritePrivateProfileStructA( + lpszSection: LPCSTR, lpszKey: LPCSTR, lpStruct: LPVOID, uSizeStruct: UINT, szFile: LPCSTR, + ) -> BOOL; + pub fn WritePrivateProfileStructW( + lpszSection: LPCWSTR, lpszKey: LPCWSTR, lpStruct: LPVOID, uSizeStruct: UINT, + szFile: LPCWSTR, + ) -> BOOL; + pub fn WriteProcessMemory( + hProcess: HANDLE, lpBaseAddress: LPVOID, lpBuffer: LPCVOID, nSize: SIZE_T, + lpNumberOfBytesWritten: *mut SIZE_T, + ) -> BOOL; + pub fn WriteProfileSectionA(lpAppName: LPCSTR, lpString: LPCSTR) -> BOOL; + pub fn WriteProfileSectionW(lpAppName: LPCWSTR, lpString: LPCWSTR) -> BOOL; + pub fn WriteProfileStringA(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpString: LPCSTR) -> BOOL; + pub fn WriteProfileStringW(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpString: LPCWSTR) -> BOOL; + pub fn WriteTapemark( + hDevice: HANDLE, dwTapemarkType: DWORD, dwTapemarkCount: DWORD, bImmediate: BOOL, + ) -> DWORD; + pub fn ZombifyActCtx(hActCtx: HANDLE) -> BOOL; + pub fn _hread(hFile: HFILE, lpBuffer: LPVOID, lBytes: c_long) -> c_long; + pub fn _hwrite(hFile: HFILE, lpBuffer: LPCCH, lBytes: c_long) -> c_long; + pub fn _lclose(hFile: HFILE) -> HFILE; + pub fn _lcreat(lpPathName: LPCSTR, iAttrubute: c_int) -> HFILE; + pub fn _llseek(hFile: HFILE, lOffset: LONG, iOrigin: c_int) -> LONG; + pub fn _lopen(lpPathName: LPCSTR, iReadWrite: c_int) -> HFILE; + pub fn _lread(hFile: HFILE, lpBuffer: LPVOID, uBytes: UINT) -> UINT; + pub fn _lwrite(hFile: HFILE, lpBuffer: LPCCH, uBytes: UINT) -> UINT; + pub fn lstrcat(lpString1: LPSTR, lpString2: LPCSTR) -> LPSTR; + pub fn lstrcatA(lpString1: LPSTR, lpString2: LPCSTR) -> LPSTR; + pub fn lstrcatW(lpString1: LPWSTR, lpString2: LPCWSTR) -> LPSTR; + pub fn lstrcmp(lpString1: LPCSTR, lpString2: LPCSTR) -> c_int; + pub fn lstrcmpA(lpString1: LPCSTR, lpString2: LPCSTR) -> c_int; + pub fn lstrcmpW(lpString1: LPCWSTR, lpString2: LPCWSTR) -> c_int; + pub fn lstrcmpi(lpString1: LPCSTR, lpString2: LPCSTR) -> c_int; + pub fn lstrcmpiA(lpString1: LPCSTR, lpString2: LPCSTR) -> c_int; + pub fn lstrcmpiW(lpString1: LPCWSTR, lpString2: LPCWSTR) -> c_int; + pub fn lstrcpy(lpString1: LPSTR, lpString2: LPCSTR) -> LPSTR; + pub fn lstrcpyA(lpString1: LPSTR, lpString2: LPCSTR) -> LPSTR; + pub fn lstrcpyW(lpString1: LPWSTR, lpString2: LPCWSTR) -> LPSTR; + pub fn lstrcpyn(lpString1: LPSTR, lpString2: LPCSTR, iMaxLength: c_int) -> LPSTR; + pub fn lstrcpynA(lpString1: LPSTR, lpString2: LPCSTR, iMaxLength: c_int) -> LPSTR; + pub fn lstrcpynW(lpString1: LPWSTR, lpString2: LPCWSTR, iMaxLength: c_int) -> LPSTR; + pub fn lstrlen(lpString: LPCSTR) -> c_int; + pub fn lstrlenA(lpString: LPCSTR) -> c_int; + pub fn lstrlenW(lpString: LPCWSTR) -> c_int; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_lstrcmpW(String1: PCUWSTR, String2: PCUWSTR) -> c_int; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_lstrcmpiW(String1: PCUWSTR, String2: PCUWSTR) -> c_int; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_lstrlenW(String: LPCUWSTR) -> c_int; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_wcschr(String: PCUWSTR, Character: WCHAR) -> PUWSTR; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_wcscpy(Destination: PUWSTR, Source: PCUWSTR) -> PUWSTR; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_wcsicmp(String1: PCUWSTR, String2: PCUWSTR) -> c_int; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_wcslen(String: PCUWSTR) -> size_t; + #[cfg(any(target_arch = "arm", target_arch = "x86_64"))] + pub fn uaw_wcsrchr(String: PCUWSTR, Character: WCHAR) -> PUWSTR; +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/.cargo-checksum.json b/bash-5.1/vendor/lazy_static-0.2.11/.cargo-checksum.json new file mode 100644 index 0000000..ab6a46c --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b598bd90e0cda5d1d3cec4042310a9e74afbe398a76af48e0d43ea5d3c51f137","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"c305f498e6d89730d84eaf92e980ba001e259dd40fcb40855947baece2af0895","appveyor.yml":"68c8ff7090ffdfa42b3d65b841d5de67d47a2206e02bf97aaca34b4500ae4bf1","src/core_lazy.rs":"2cea85ad0c2c4f88a5a927815a59270411daa4075510fad0faf671d5f5130fed","src/lazy.rs":"52912a897e8fcc95672e3b3068be82d56548f422edcb60e6ce9570779acb5bc0","src/lib.rs":"facd354cb716ee6941bf9bc8d34c27a2ecd752746c4d5164dbec8cedd80df605","src/nightly_lazy.rs":"34080822b27f3968c872867131448df76acc5aeff259852ff86f6e73b5a913b6","tests/compile-fail/README.md":"296216a459b7bf9947ba540c94b71a48ec90c2632ef5f05248a01dc8611ae149","tests/compile-fail/incorrect_visibility_restriction.rs":"557c94f781d6a2fb6c4be32a2ea252752195ff7b7c889581d95c39f2ce45e7d3","tests/compile-fail/static_is_private.rs":"f778f0759529b2dc8360f9abad1e09ea6662493493d707b3fba6cb1cb3d94af2","tests/compile-fail/static_is_sized.rs":"3b6d632f764ccee5fbd413324d7daeb2ab52dec0c99ea1db11a7eb2bbcad37cb","tests/compile-fail/static_never_used.rs":"5139e2459b4c68b0ed3f5a04452f60895b076acb1b5f344fb6b8ccbd50283a2d","tests/compile_tests.rs":"5710b2c0edc7623b895d67c26180a6c1d4022c154ecd616fab449afc9ba95109","tests/no_std.rs":"2a5236bd3892a253855b4dc192f63138239165fa23b9c3421a9faa5482c780aa","tests/test.rs":"12b100f4790037ca049692d896114d6361373c5321c29e0032c290ee39f1042c"},"package":"76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73"} \ No newline at end of file diff --git a/bash-5.1/vendor/lazy_static-0.2.11/Cargo.toml b/bash-5.1/vendor/lazy_static-0.2.11/Cargo.toml new file mode 100644 index 0000000..c25a8a1 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/Cargo.toml @@ -0,0 +1,43 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "lazy_static" +version = "0.2.11" +authors = ["Marvin Löbel "] +description = "A macro for declaring lazily evaluated statics in Rust." +documentation = "https://docs.rs/lazy_static" +readme = "README.md" +keywords = ["macro", "lazy", "static"] +categories = ["no-std", "rust-patterns", "memory-management"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang-nursery/lazy-static.rs" +[dependencies.compiletest_rs] +version = "0.3" +optional = true + +[dependencies.spin] +version = "0.4.6" +optional = true + +[features] +compiletest = ["compiletest_rs"] +nightly = [] +spin_no_std = ["nightly", "spin"] +[badges.appveyor] +repository = "rust-lang-nursery/lazy-static.rs" + +[badges.maintenance] +status = "passively-maintained" + +[badges.travis-ci] +repository = "rust-lang-nursery/lazy-static.rs" diff --git a/bash-5.1/vendor/lazy_static-0.2.11/LICENSE-APACHE b/bash-5.1/vendor/lazy_static-0.2.11/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/lazy_static-0.2.11/LICENSE-MIT b/bash-5.1/vendor/lazy_static-0.2.11/LICENSE-MIT new file mode 100644 index 0000000..25597d5 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2010 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/lazy_static-0.2.11/README.md b/bash-5.1/vendor/lazy_static-0.2.11/README.md new file mode 100644 index 0000000..ad5380e --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/README.md @@ -0,0 +1,69 @@ +lazy-static.rs +============== + +A macro for declaring lazily evaluated statics in Rust. + +Using this macro, it is possible to have `static`s that require code to be +executed at runtime in order to be initialized. +This includes anything requiring heap allocations, like vectors or hash maps, +as well as anything that requires non-const function calls to be computed. + +[![Travis-CI Status](https://travis-ci.org/rust-lang-nursery/lazy-static.rs.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/lazy-static.rs) + +# Getting Started + +[lazy-static.rs is available on crates.io](https://crates.io/crates/lazy_static). +It is recommended to look there for the newest released version, as well as links to the newest builds of the docs. + +At the point of the last update of this README, the latest published version could be used like this: + +Add the following dependency to your Cargo manifest... + +```toml +[dependencies] +lazy_static = "0.2" +``` + +...and see the [docs](https://docs.rs/lazy_static) for how to use it. + +# Example + +```rust +#[macro_use] +extern crate lazy_static; + +use std::collections::HashMap; + +lazy_static! { + static ref HASHMAP: HashMap = { + let mut m = HashMap::new(); + m.insert(0, "foo"); + m.insert(1, "bar"); + m.insert(2, "baz"); + m + }; +} + +fn main() { + // First access to `HASHMAP` initializes it + println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap()); + + // Any further access to `HASHMAP` just returns the computed value + println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap()); +} +``` + +## License + +Licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/bash-5.1/vendor/lazy_static-0.2.11/appveyor.yml b/bash-5.1/vendor/lazy_static-0.2.11/appveyor.yml new file mode 100644 index 0000000..82a726c --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/appveyor.yml @@ -0,0 +1,59 @@ +environment: + global: + PROJECT_NAME: lazy_static + # When this was added there were revocation check failures when using the + # libcurl backend as libcurl checks by default, but rustup doesn't provide the + # switch to turn this off. Switch to Hyper which looks to not check for + # revocation by default like libcurl does. + RUSTUP_USE_REQWEST: 1 + CARGO_HTTP_CHECK_REVOKE: false + matrix: + # Stable channel + - TARGET: i686-pc-windows-gnu + CHANNEL: stable + - TARGET: i686-pc-windows-msvc + CHANNEL: stable + - TARGET: x86_64-pc-windows-gnu + CHANNEL: stable + - TARGET: x86_64-pc-windows-msvc + CHANNEL: stable + # Beta channel + - TARGET: i686-pc-windows-gnu + CHANNEL: beta + - TARGET: i686-pc-windows-msvc + CHANNEL: beta + - TARGET: x86_64-pc-windows-gnu + CHANNEL: beta + - TARGET: x86_64-pc-windows-msvc + CHANNEL: beta + # Nightly channel + - TARGET: i686-pc-windows-gnu + CHANNEL: nightly + - TARGET: i686-pc-windows-msvc + CHANNEL: nightly + - TARGET: x86_64-pc-windows-gnu + CHANNEL: nightly + - TARGET: x86_64-pc-windows-msvc + CHANNEL: nightly + +# Install Rust and Cargo +# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-toolchain %CHANNEL% --default-host %TARGET% + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - if "%TARGET%" == "i686-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw32\bin + - if "%TARGET%" == "x86_64-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw64\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo build --verbose + - cargo test + - if [%CHANNEL%]==[nightly] ( + cargo clean && + cargo build --verbose --features "compiletest" && + cargo test --features "compiletest" + ) diff --git a/bash-5.1/vendor/lazy_static-0.2.11/src/core_lazy.rs b/bash-5.1/vendor/lazy_static-0.2.11/src/core_lazy.rs new file mode 100644 index 0000000..90c7aaa --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/src/core_lazy.rs @@ -0,0 +1,33 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate spin; + +use self::spin::Once; + +pub struct Lazy(Once); + +impl Lazy { + #[inline(always)] + pub const fn new() -> Self { + Lazy(Once::new()) + } + + #[inline(always)] + pub fn get(&'static self, builder: F) -> &T + where F: FnOnce() -> T + { + self.0.call_once(builder) + } +} + +#[macro_export] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::new(); + } +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/src/lazy.rs b/bash-5.1/vendor/lazy_static-0.2.11/src/lazy.rs new file mode 100644 index 0000000..aab1e05 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/src/lazy.rs @@ -0,0 +1,39 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate std; + +use self::std::prelude::v1::*; +use self::std::sync::Once; +pub use self::std::sync::ONCE_INIT; + +pub struct Lazy(pub *const T, pub Once); + +impl Lazy { + #[inline(always)] + pub fn get(&'static mut self, f: F) -> &T + where F: FnOnce() -> T + { + unsafe { + let r = &mut self.0; + self.1.call_once(|| { + *r = Box::into_raw(Box::new(f())); + }); + + &*self.0 + } + } +} + +unsafe impl Sync for Lazy {} + +#[macro_export] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static mut $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy(0 as *const $T, $crate::lazy::ONCE_INIT); + } +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/src/lib.rs b/bash-5.1/vendor/lazy_static-0.2.11/src/lib.rs new file mode 100644 index 0000000..bb15478 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/src/lib.rs @@ -0,0 +1,212 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +/*! +A macro for declaring lazily evaluated statics. + +Using this macro, it is possible to have `static`s that require code to be +executed at runtime in order to be initialized. +This includes anything requiring heap allocations, like vectors or hash maps, +as well as anything that requires function calls to be computed. + +# Syntax + +```ignore +lazy_static! { + [pub] static ref NAME_1: TYPE_1 = EXPR_1; + [pub] static ref NAME_2: TYPE_2 = EXPR_2; + ... + [pub] static ref NAME_N: TYPE_N = EXPR_N; +} +``` + +Attributes (including doc comments) are supported as well: + +```rust +# #[macro_use] +# extern crate lazy_static; +# fn main() { +lazy_static! { + /// This is an example for using doc comment attributes + static ref EXAMPLE: u8 = 42; +} +# } +``` + +# Semantics + +For a given `static ref NAME: TYPE = EXPR;`, the macro generates a unique type that +implements `Deref` and stores it in a static with name `NAME`. (Attributes end up +attaching to this type.) + +On first deref, `EXPR` gets evaluated and stored internally, such that all further derefs +can return a reference to the same object. Note that this can lead to deadlocks +if you have multiple lazy statics that depend on each other in their initialization. + +Apart from the lazy initialization, the resulting "static ref" variables +have generally the same properties as regular "static" variables: + +- Any type in them needs to fulfill the `Sync` trait. +- If the type has a destructor, then it will not run when the process exits. + +# Example + +Using the macro: + +```rust +#[macro_use] +extern crate lazy_static; + +use std::collections::HashMap; + +lazy_static! { + static ref HASHMAP: HashMap = { + let mut m = HashMap::new(); + m.insert(0, "foo"); + m.insert(1, "bar"); + m.insert(2, "baz"); + m + }; + static ref COUNT: usize = HASHMAP.len(); + static ref NUMBER: u32 = times_two(21); +} + +fn times_two(n: u32) -> u32 { n * 2 } + +fn main() { + println!("The map has {} entries.", *COUNT); + println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap()); + println!("A expensive calculation on a static results in: {}.", *NUMBER); +} +``` + +# Implementation details + +The `Deref` implementation uses a hidden static variable that is guarded by a atomic check on each access. On stable Rust, the macro may need to allocate each static on the heap. + +*/ + +#![cfg_attr(feature="spin_no_std", feature(const_fn))] +#![cfg_attr(feature="nightly", feature(unreachable))] + +#![doc(html_root_url = "https://docs.rs/lazy_static/0.2.11")] +#![no_std] + +#[cfg(not(feature="nightly"))] +#[doc(hidden)] +pub mod lazy; + +#[cfg(all(feature="nightly", not(feature="spin_no_std")))] +#[path="nightly_lazy.rs"] +#[doc(hidden)] +pub mod lazy; + +#[cfg(all(feature="nightly", feature="spin_no_std"))] +#[path="core_lazy.rs"] +#[doc(hidden)] +pub mod lazy; + +#[doc(hidden)] +pub use core::ops::Deref as __Deref; + +#[macro_export] +#[doc(hidden)] +macro_rules! __lazy_static_internal { + // optional visibility restrictions are wrapped in `()` to allow for + // explicitly passing otherwise implicit information about private items + ($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + __lazy_static_internal!(@MAKE TY, $(#[$attr])*, ($($vis)*), $N); + __lazy_static_internal!(@TAIL, $N : $T = $e); + lazy_static!($($t)*); + }; + (@TAIL, $N:ident : $T:ty = $e:expr) => { + impl $crate::__Deref for $N { + type Target = $T; + #[allow(unsafe_code)] + fn deref(&self) -> &$T { + unsafe { + #[inline(always)] + fn __static_ref_initialize() -> $T { $e } + + #[inline(always)] + unsafe fn __stability() -> &'static $T { + __lazy_static_create!(LAZY, $T); + LAZY.get(__static_ref_initialize) + } + __stability() + } + } + } + impl $crate::LazyStatic for $N { + fn initialize(lazy: &Self) { + let _ = &**lazy; + } + } + }; + // `vis` is wrapped in `()` to prevent parsing ambiguity + (@MAKE TY, $(#[$attr:meta])*, ($($vis:tt)*), $N:ident) => { + #[allow(missing_copy_implementations)] + #[allow(non_camel_case_types)] + #[allow(dead_code)] + $(#[$attr])* + $($vis)* struct $N {__private_field: ()} + #[doc(hidden)] + $($vis)* static $N: $N = $N {__private_field: ()}; + }; + () => () +} + +#[macro_export] +macro_rules! lazy_static { + ($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + // use `()` to explicitly forward the information about private items + __lazy_static_internal!($(#[$attr])* () static ref $N : $T = $e; $($t)*); + }; + ($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + __lazy_static_internal!($(#[$attr])* (pub) static ref $N : $T = $e; $($t)*); + }; + ($(#[$attr:meta])* pub ($($vis:tt)+) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + __lazy_static_internal!($(#[$attr])* (pub ($($vis)+)) static ref $N : $T = $e; $($t)*); + }; + () => () +} + +/// Support trait for enabling a few common operation on lazy static values. +/// +/// This is implemented by each defined lazy static, and +/// used by the free functions in this crate. +pub trait LazyStatic { + #[doc(hidden)] + fn initialize(lazy: &Self); +} + +/// Takes a shared reference to a lazy static and initializes +/// it if it has not been already. +/// +/// This can be used to control the initialization point of a lazy static. +/// +/// Example: +/// +/// ```rust +/// #[macro_use] +/// extern crate lazy_static; +/// +/// lazy_static! { +/// static ref BUFFER: Vec = (0..65537).collect(); +/// } +/// +/// fn main() { +/// lazy_static::initialize(&BUFFER); +/// +/// // ... +/// work_with_initialized_data(&BUFFER); +/// } +/// # fn work_with_initialized_data(_: &[u8]) {} +/// ``` +pub fn initialize(lazy: &T) { + LazyStatic::initialize(lazy); +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/src/nightly_lazy.rs b/bash-5.1/vendor/lazy_static-0.2.11/src/nightly_lazy.rs new file mode 100644 index 0000000..0ad0f66 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/src/nightly_lazy.rs @@ -0,0 +1,43 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate std; + +use self::std::prelude::v1::*; +use self::std::sync::Once; +pub use self::std::sync::ONCE_INIT; + +pub struct Lazy(pub Option, pub Once); + +impl Lazy { + #[inline(always)] + pub fn get(&'static mut self, f: F) -> &T + where F: FnOnce() -> T + { + { + let r = &mut self.0; + self.1.call_once(|| { + *r = Some(f()); + }); + } + unsafe { + match self.0 { + Some(ref x) => x, + None => std::mem::unreachable(), + } + } + } +} + +unsafe impl Sync for Lazy {} + +#[macro_export] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static mut $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy(None, $crate::lazy::ONCE_INIT); + } +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/README.md b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/README.md new file mode 100644 index 0000000..7f80d11 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/README.md @@ -0,0 +1,22 @@ +This directory contains snippets of code that should yield a +warning/note/help/error at compilation. Syntax of annotations is described in +[rust documentation](https://github.com/rust-lang/rust/blob/master/src/test/COMPILER_TESTS.md). +For more information check out [`compiletest` crate](https://github.com/laumann/compiletest-rs). + +To run compile tests issue `cargo +nightly --test --features compiletest`. + +## Notes on working with `compiletest` crate + +* Currently code that is inside macro should not be annotated, as `compiletest` + crate cannot deal with the fact that macro invocations effectively changes + line numbering. To prevent this add a `// error-pattern:` + on the top of the file and make sure that you set `deny` lint level + if you want to test compiler message different than error. +* `compiletest` crate by default sets `allow(dead_code)` lint level so make sure + that you change it to something suiting your needs even if the warning is + issued prior to any macro invocation. +* If you get a message `error: 0 unexpected errors found, 1 expected errors not found` + despite the fact that some error was bound to occur don't worry - it's a known + issue in the `compiletest` crate and your error was probably not registered - + make sure that your annotations are correct and that you are setting correct + lint levels. diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs new file mode 100644 index 0000000..e2e5238 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs @@ -0,0 +1,10 @@ +// incorrect visibility restriction +#[macro_use] +extern crate lazy_static; + +lazy_static! { + pub(nonsense) static ref WRONG: () = (); + //~^ ERROR incorrect visibility restriction +} + +fn main() { } diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs new file mode 100644 index 0000000..a88c1c6 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs @@ -0,0 +1,14 @@ +#[macro_use] +extern crate lazy_static; + +mod outer { + pub mod inner { + lazy_static! { + pub(in outer) static ref FOO: () = (); + } + } +} + +fn main() { + assert_eq!(*outer::inner::FOO, ()); //~ ERROR static `FOO` is private +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs new file mode 100644 index 0000000..3681ad7 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs @@ -0,0 +1,11 @@ +// error-pattern:the trait bound `str: std::marker::Sized` is not satisfied +#[macro_use] +extern crate lazy_static; + +lazy_static! { + pub static ref FOO: str = panic!(); +} + + +fn main() { +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs new file mode 100644 index 0000000..a611778 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs @@ -0,0 +1,10 @@ +// error-pattern:static item is never used: `UNUSED` +#![deny(dead_code)] +#[macro_use] +extern crate lazy_static; + +lazy_static! { + static ref UNUSED: () = (); +} + +fn main() { } diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/compile_tests.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile_tests.rs new file mode 100644 index 0000000..3e347d5 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/compile_tests.rs @@ -0,0 +1,18 @@ +#![cfg(feature="compiletest")] +extern crate compiletest_rs as compiletest; + +fn run_mode(mode: &'static str) { + let mut config = compiletest::Config::default(); + config.mode = mode.parse().expect("Invalid mode"); + config.src_base = ["tests", mode].iter().collect(); + config.target_rustcflags = Some("-L target/debug/ -L target/debug/deps/".to_owned()); + + config.verbose = true; + + compiletest::run_tests(&config); +} + +#[test] +fn compile_test() { + run_mode("compile-fail"); +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/no_std.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/no_std.rs new file mode 100644 index 0000000..b460e79 --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/no_std.rs @@ -0,0 +1,21 @@ +#![cfg(feature="spin_no_std")] +#![feature(const_fn)] + +#![no_std] + +#[macro_use] +extern crate lazy_static; + +lazy_static! { + /// Documentation! + pub static ref NUMBER: u32 = times_two(3); +} + +fn times_two(n: u32) -> u32 { + n * 2 +} + +#[test] +fn test_basic() { + assert_eq!(*NUMBER, 6); +} diff --git a/bash-5.1/vendor/lazy_static-0.2.11/tests/test.rs b/bash-5.1/vendor/lazy_static-0.2.11/tests/test.rs new file mode 100644 index 0000000..fbf225d --- /dev/null +++ b/bash-5.1/vendor/lazy_static-0.2.11/tests/test.rs @@ -0,0 +1,164 @@ +#![cfg_attr(feature="nightly", feature(const_fn))] + +#[macro_use] +extern crate lazy_static; +use std::collections::HashMap; + +lazy_static! { + /// Documentation! + pub static ref NUMBER: u32 = times_two(3); + + static ref ARRAY_BOXES: [Box; 3] = [Box::new(1), Box::new(2), Box::new(3)]; + + /// More documentation! + #[allow(unused_variables)] + #[derive(Copy, Clone, Debug)] + pub static ref STRING: String = "hello".to_string(); + + static ref HASHMAP: HashMap = { + let mut m = HashMap::new(); + m.insert(0, "abc"); + m.insert(1, "def"); + m.insert(2, "ghi"); + m + }; + + // This should not compile if the unsafe is removed. + static ref UNSAFE: u32 = unsafe { + std::mem::transmute::(-1) + }; +} + +lazy_static! { + static ref S1: &'static str = "a"; + static ref S2: &'static str = "b"; +} +lazy_static! { + static ref S3: String = [*S1, *S2].join(""); +} + +#[test] +fn s3() { + assert_eq!(&*S3, "ab"); +} + +fn times_two(n: u32) -> u32 { + n * 2 +} + +#[test] +fn test_basic() { + assert_eq!(&**STRING, "hello"); + assert_eq!(*NUMBER, 6); + assert!(HASHMAP.get(&1).is_some()); + assert!(HASHMAP.get(&3).is_none()); + assert_eq!(&*ARRAY_BOXES, &[Box::new(1), Box::new(2), Box::new(3)]); + assert_eq!(*UNSAFE, std::u32::MAX); +} + +#[test] +fn test_repeat() { + assert_eq!(*NUMBER, 6); + assert_eq!(*NUMBER, 6); + assert_eq!(*NUMBER, 6); +} + +#[test] +fn test_meta() { + // this would not compile if STRING were not marked #[derive(Copy, Clone)] + let copy_of_string = STRING; + // just to make sure it was copied + assert!(&STRING as *const _ != ©_of_string as *const _); + + // this would not compile if STRING were not marked #[derive(Debug)] + assert_eq!(format!("{:?}", STRING), "STRING { __private_field: () }".to_string()); +} + +mod visibility { + lazy_static! { + pub static ref FOO: Box = Box::new(0); + static ref BAR: Box = Box::new(98); + } + + pub mod inner { + lazy_static! { + pub(in visibility) static ref BAZ: Box = Box::new(42); + pub(crate) static ref BAG: Box = Box::new(37); + } + } + + #[test] + fn sub_test() { + assert_eq!(**FOO, 0); + assert_eq!(**BAR, 98); + assert_eq!(**inner::BAZ, 42); + assert_eq!(**inner::BAG, 37); + } +} + +#[test] +fn test_visibility() { + assert_eq!(*visibility::FOO, Box::new(0)); + assert_eq!(*visibility::inner::BAG, Box::new(37)); +} + +// This should not cause a warning about a missing Copy implementation +lazy_static! { + pub static ref VAR: i32 = { 0 }; +} + +#[derive(Copy, Clone, Debug, PartialEq)] +struct X; +struct Once(X); +const ONCE_INIT: Once = Once(X); +static DATA: X = X; +static ONCE: X = X; +fn require_sync() -> X { X } +fn transmute() -> X { X } +fn __static_ref_initialize() -> X { X } +fn test(_: Vec) -> X { X } + +// All these names should not be shadowed +lazy_static! { + static ref ITEM_NAME_TEST: X = { + test(vec![X, Once(X).0, ONCE_INIT.0, DATA, ONCE, + require_sync(), transmute(), + // Except this, which will sadly be shadowed by internals: + // __static_ref_initialize() + ]) + }; +} + +#[test] +fn item_name_shadowing() { + assert_eq!(*ITEM_NAME_TEST, X); +} + +use std::sync::atomic::AtomicBool; +use std::sync::atomic::ATOMIC_BOOL_INIT; +use std::sync::atomic::Ordering::SeqCst; + +static PRE_INIT_FLAG: AtomicBool = ATOMIC_BOOL_INIT; + +lazy_static! { + static ref PRE_INIT: () = { + PRE_INIT_FLAG.store(true, SeqCst); + () + }; +} + +#[test] +fn pre_init() { + assert_eq!(PRE_INIT_FLAG.load(SeqCst), false); + lazy_static::initialize(&PRE_INIT); + assert_eq!(PRE_INIT_FLAG.load(SeqCst), true); +} + +lazy_static! { + static ref LIFETIME_NAME: for<'a> fn(&'a u8) = { fn f(_: &u8) {} f }; +} + +#[test] +fn lifetime_name() { + let _ = LIFETIME_NAME; +} diff --git a/bash-5.1/vendor/libc/.cargo-checksum.json b/bash-5.1/vendor/libc/.cargo-checksum.json index 26956a4..631af72 100644 --- a/bash-5.1/vendor/libc/.cargo-checksum.json +++ b/bash-5.1/vendor/libc/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CONTRIBUTING.md":"752eea5a703d11b485c6b5f195f51bd2c79aa5159b619ce09555c779e1fb586b","Cargo.toml":"6a0abcfcbc1d9fb00a356343043a161f5b84b3f780cb0f02df4627d022b14b7f","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"a8d47ff51ca256f56a8932dba07660672dbfe3004257ca8de708aac1415937a1","README.md":"8228847944f1332882fbb00275b6f30e4a8aad08a13569c25d52cac012cc2a47","build.rs":"41f9743021d9e5ed74ede55c94057cf6867a322a13b25a5d524b966656a08e38","rustfmt.toml":"eaa2ea84fc1ba0359b77680804903e07bb38d257ab11986b95b158e460f787b2","src/fixed_width_ints.rs":"7f986e5f5e68d25ef04d386fd2f640e8be8f15427a8d4a458ea01d26b8dca0ca","src/fuchsia/aarch64.rs":"378776a9e40766154a54c94c2a7b4675b5c302a38e6e42da99e67bfbaee60e56","src/fuchsia/align.rs":"ae1cf8f011a99737eabeb14ffff768e60f13b13363d7646744dbb0f443dab3d6","src/fuchsia/mod.rs":"bc8c46531bd1a2429f36aaf2bc137b50e42505b798de83f34eecfa94ad89179b","src/fuchsia/no_align.rs":"303f3f1b255e0088b5715094353cf00476131d8e94e6aebb3f469557771c8b8a","src/fuchsia/x86_64.rs":"93a3632b5cf67d2a6bcb7dc0a558605252d5fe689e0f38d8aa2ec5852255ac87","src/hermit/aarch64.rs":"86048676e335944c37a63d0083d0f368ae10ceccefeed9debb3bbe08777fc682","src/hermit/mod.rs":"d3bfce41e4463d4be8020a2d063c9bfa8b665f45f1cc6cbf3163f5d01e7cb21f","src/hermit/x86_64.rs":"ab832b7524e5fb15c49ff7431165ab1a37dc4667ae0b58e8306f4c539bfa110c","src/lib.rs":"3f13d5f9b29d8969dde507661f1637524e21fe3bd34957fc778868f2f3713c46","src/macros.rs":"d7437c2573c4915768ff96b34710a61ee9f63622b23526cddeaeaf6bfb4751a2","src/psp.rs":"dd31aabd46171d474ec5828372e28588935120e7355c90c105360d8fa9264c1c","src/sgx.rs":"16a95cdefc81c5ee00d8353a60db363c4cc3e0f75abcd5d0144723f2a306ed1b","src/solid/aarch64.rs":"a726e47f324adf73a4a0b67a2c183408d0cad105ae66acf36db37a42ab7f8707","src/solid/arm.rs":"e39a4f74ebbef3b97b8c95758ad741123d84ed3eb48d9cf4f1f4872097fc27fe","src/solid/mod.rs":"5f4151dca5132e4b4e4c23ab9737e12856dddbdc0ca3f7dbc004328ef3c8acde","src/switch.rs":"9da3dd39b3de45a7928789926e8572d00e1e11a39e6f7289a1349aadce90edba","src/unix/align.rs":"2cdc7c826ef7ae61f5171c5ae8c445a743d86f1a7f2d9d7e4ceeec56d6874f65","src/unix/bsd/apple/b32/align.rs":"ec833a747866fe19ca2d9b4d3c9ff0385faba5edf4bd0d15fa68884c40b0e26c","src/unix/bsd/apple/b32/mod.rs":"2546ad3eb6aecb95f916648bc63264117c92b4b4859532b34cb011e4c75a5a72","src/unix/bsd/apple/b64/aarch64/align.rs":"2eaf0f561a32bdcbf4e0477c8895d5e7bcb5cdebd5fef7b4df2ca8e38e144d94","src/unix/bsd/apple/b64/aarch64/mod.rs":"a3f0dfff62d0f7f4f1b5f9a4e2b662acf233a46badbc5419d3cc2d735629a710","src/unix/bsd/apple/b64/align.rs":"ec833a747866fe19ca2d9b4d3c9ff0385faba5edf4bd0d15fa68884c40b0e26c","src/unix/bsd/apple/b64/mod.rs":"f5e278a1af7fb358891d1c9be4eb7e815aaca0c5cb738d0c3604ba2208a856f7","src/unix/bsd/apple/b64/x86_64/align.rs":"ec833a747866fe19ca2d9b4d3c9ff0385faba5edf4bd0d15fa68884c40b0e26c","src/unix/bsd/apple/b64/x86_64/mod.rs":"8c87c5855038aae5d433c8f5eb3b29b0a175879a0245342b3bfd83bdf4cfd936","src/unix/bsd/apple/mod.rs":"d7155927fbd1af6dd984a4c6c1a735a5932af828c96818209487eb6ae72d7d7e","src/unix/bsd/freebsdlike/dragonfly/errno.rs":"8295b8bb0dfd38d2cdb4d9192cdeeb534cc6c3b208170e64615fa3e0edb3e578","src/unix/bsd/freebsdlike/dragonfly/mod.rs":"379302e12d30807a1f973c4e2dd2205179d95343ee6fae05f33c9ed45a342799","src/unix/bsd/freebsdlike/freebsd/aarch64.rs":"2a215bd6136b8617aacedf9be738ccee94da9d29b418e9a78101d6291c182352","src/unix/bsd/freebsdlike/freebsd/arm.rs":"59d6a670eea562fb87686e243e0a84603d29a2028a3d4b3f99ccc01bd04d2f47","src/unix/bsd/freebsdlike/freebsd/freebsd11/b64.rs":"9808d152c1196aa647f1b0f0cf84dac8c930da7d7f897a44975545e3d9d17681","src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs":"a6eee615e6ca5a6e04b526bb6b22d13b9356e87e51825cda33476c37a46cb0ef","src/unix/bsd/freebsdlike/freebsd/freebsd12/b64.rs":"61cbe45f8499bedb168106b686d4f8239472f25c7553b069eec2afe197ff2df6","src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs":"755dafaf3f0945e798c34ea94c48e8552804ce60e2a15a4f0649f9d1aceaf422","src/unix/bsd/freebsdlike/freebsd/freebsd12/x86_64.rs":"2df36a7f122f6d6e5753cfb4d22e915cc80f6bc91c0161b3daae55a481bfd052","src/unix/bsd/freebsdlike/freebsd/freebsd13/b64.rs":"61cbe45f8499bedb168106b686d4f8239472f25c7553b069eec2afe197ff2df6","src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs":"cc65a73b0fa95a77044a4b3ee76d6eceb9773b55aea7d73bdf070e6f66e9ea38","src/unix/bsd/freebsdlike/freebsd/freebsd13/x86_64.rs":"2df36a7f122f6d6e5753cfb4d22e915cc80f6bc91c0161b3daae55a481bfd052","src/unix/bsd/freebsdlike/freebsd/freebsd14/b64.rs":"61cbe45f8499bedb168106b686d4f8239472f25c7553b069eec2afe197ff2df6","src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs":"0ed92eb93e78299cd7de0ae9daebb04a53b3c2d5e6a078e1fcd977f2a86bffc3","src/unix/bsd/freebsdlike/freebsd/freebsd14/x86_64.rs":"2df36a7f122f6d6e5753cfb4d22e915cc80f6bc91c0161b3daae55a481bfd052","src/unix/bsd/freebsdlike/freebsd/mod.rs":"467b66843ab8c1a54b01ae9e90aaf0295b32f54decbdfb64caca84523b488925","src/unix/bsd/freebsdlike/freebsd/powerpc.rs":"9ca3f82f88974e6db5569f2d76a5a3749b248a31747a6c0da5820492bdfeca42","src/unix/bsd/freebsdlike/freebsd/powerpc64.rs":"2dae3ecc87eac3b11657aa98915def55fc4b5c0de11fe26aae23329a54628a9a","src/unix/bsd/freebsdlike/freebsd/riscv64.rs":"8f591bd273464d684c4f64365f8ed56a8138175daa70d96008541393057a0dae","src/unix/bsd/freebsdlike/freebsd/x86.rs":"c5005e3249eb7c93cfbac72a9e9272320d80ce7983da990ceb05a447f59a02c5","src/unix/bsd/freebsdlike/freebsd/x86_64/align.rs":"0e1f69a88fca1c32874b1daf5db3d446fefbe518dca497f096cc9168c39dde70","src/unix/bsd/freebsdlike/freebsd/x86_64/mod.rs":"51e4dd0c8ae247bb652feda5adad9333ea3bb30c750c3a3935e0b0e47d7803eb","src/unix/bsd/freebsdlike/mod.rs":"a7345cc3fb7372572efe06848feb2cc246dfc2c2a0cc9ccf434f4c55041a59fa","src/unix/bsd/mod.rs":"7720ec82c9334f988ec4b271784768a017c3dc2e6dfae4d02418eef753388aa7","src/unix/bsd/netbsdlike/mod.rs":"594a0f9e23c4d7702ba38afdba5a0e866be25d692ec0afd66e04d939aa6b3f04","src/unix/bsd/netbsdlike/netbsd/aarch64.rs":"65dcb58d11e8d8028401a9d07ca3eb4cb4f053e04249cc877353449d84ccc4cb","src/unix/bsd/netbsdlike/netbsd/arm.rs":"58cdbb70b0d6f536551f0f3bb3725d2d75c4690db12c26c034e7d6ec4a924452","src/unix/bsd/netbsdlike/netbsd/mod.rs":"cb1560bf8ffcc7b2726a27b433efac90e726292960626f3064bd2c6b7f861a55","src/unix/bsd/netbsdlike/netbsd/powerpc.rs":"ee7ff5d89d0ed22f531237b5059aa669df93a3b5c489fa641465ace8d405bf41","src/unix/bsd/netbsdlike/netbsd/sparc64.rs":"9489f4b3e4566f43bb12dfb92238960613dac7f6a45cc13068a8d152b902d7d9","src/unix/bsd/netbsdlike/netbsd/x86.rs":"20692320e36bfe028d1a34d16fe12ca77aa909cb02bda167376f98f1a09aefe7","src/unix/bsd/netbsdlike/netbsd/x86_64.rs":"1afe5ef46b14397cdd68664b5b232e4f5b035b6db1d4cf411c899d51ebca9f30","src/unix/bsd/netbsdlike/openbsd/aarch64.rs":"dd91931d373b7ecaf6e2de25adadee10d16fa9b12c2cbacdff3eb291e1ba36af","src/unix/bsd/netbsdlike/openbsd/arm.rs":"01580d261bc6447bb327a0d982181b7bdabfa066cee65a30373d3ced729ad307","src/unix/bsd/netbsdlike/openbsd/mips64.rs":"8532a189ae10c7d668d9d4065da8b05d124e09bd39442c9f74a7f231c43eca48","src/unix/bsd/netbsdlike/openbsd/mod.rs":"816a8ef47df60a752a91967627eeccb9ca776dc718ecc53ae902d8edaee0bce9","src/unix/bsd/netbsdlike/openbsd/powerpc.rs":"01580d261bc6447bb327a0d982181b7bdabfa066cee65a30373d3ced729ad307","src/unix/bsd/netbsdlike/openbsd/powerpc64.rs":"1dd5449dd1fd3d51e30ffdeeaece91d0aaf05c710e0ac699fecc5461cfa2c28e","src/unix/bsd/netbsdlike/openbsd/riscv64.rs":"1dd5449dd1fd3d51e30ffdeeaece91d0aaf05c710e0ac699fecc5461cfa2c28e","src/unix/bsd/netbsdlike/openbsd/sparc64.rs":"d04fd287afbaa2c5df9d48c94e8374a532a3ba491b424ddf018270c7312f4085","src/unix/bsd/netbsdlike/openbsd/x86.rs":"6f7f5c4fde2a2259eb547890cbd86570cea04ef85347d7569e94e679448bec87","src/unix/bsd/netbsdlike/openbsd/x86_64.rs":"d31db31630289c85af3339dbe357998a21ca584cbae31607448fe2cf7675a4e1","src/unix/haiku/b32.rs":"a2efdbf7158a6da341e1db9176b0ab193ba88b449616239ed95dced11f54d87b","src/unix/haiku/b64.rs":"ff8115367d3d7d354f792d6176dfaaa26353f57056197b563bf4681f91ff7985","src/unix/haiku/mod.rs":"d5833ff9b94daa81d2470df544453212af17530d78c5a7fb912eac915d00f329","src/unix/haiku/native.rs":"dbfcbf4954a79d1df2ff58e0590bbcb8c57dfc7a32392aa73ee4726b66bd6cc8","src/unix/haiku/x86_64.rs":"3ec3aeeb7ed208b8916f3e32d42bfd085ff5e16936a1a35d9a52789f043b7237","src/unix/hermit/aarch64.rs":"86048676e335944c37a63d0083d0f368ae10ceccefeed9debb3bbe08777fc682","src/unix/hermit/mod.rs":"859814f5df89e28fd4b345db399d181e11e7ed413841b6ff703a1fcbdbf013ae","src/unix/hermit/x86_64.rs":"ab832b7524e5fb15c49ff7431165ab1a37dc4667ae0b58e8306f4c539bfa110c","src/unix/linux_like/android/b32/arm.rs":"433c1530f602cc5ed26610c58055dde0c4ceea5e00150063b24ddc60768332a4","src/unix/linux_like/android/b32/mod.rs":"7c173e0375119bf06a3081652faede95e5bcd6858e7576b7533d037978737c8f","src/unix/linux_like/android/b32/x86/align.rs":"812914e4241df82e32b12375ca3374615dc3a4bdd4cf31f0423c5815320c0dab","src/unix/linux_like/android/b32/x86/mod.rs":"8388bd3a0fcb5636bf965eee6dc95ae6860b85a2b555b387c868aa4d4e01ec89","src/unix/linux_like/android/b64/aarch64/align.rs":"2179c3b1608fa4bf68840482bfc2b2fa3ee2faf6fcae3770f9e505cddca35c7b","src/unix/linux_like/android/b64/aarch64/int128.rs":"1735f6f5c56770d20dd426442f09724d9b2052b46a7cd82f23f3288a4a7276de","src/unix/linux_like/android/b64/aarch64/mod.rs":"ef230d49fd0d182adf2dae6f8e10babf18d72259d65980bf1c4c2dc8a4f84501","src/unix/linux_like/android/b64/mod.rs":"d7bbbadafdb2cb2ff8e9cde3d89a03b9facaabb6b2d45705225d3ece1c5cce37","src/unix/linux_like/android/b64/x86_64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/android/b64/x86_64/mod.rs":"6454948ea98be86243229f99d67cdc7ca460e16b2a6445663ff4b5b6907c358d","src/unix/linux_like/android/mod.rs":"1247397a7e1b6269e0d2d6df88c6396bc18eb477e3ff293ff57d66a6b1380d94","src/unix/linux_like/emscripten/align.rs":"86c95cbed7a7161b1f23ee06843e7b0e2340ad92b2cb86fe2a8ef3e0e8c36216","src/unix/linux_like/emscripten/mod.rs":"b71d37106750f57bc2dae4e9bcb473ff098ef48235827e41a1687a39825f0aa4","src/unix/linux_like/emscripten/no_align.rs":"0128e4aa721a9902754828b61b5ec7d8a86619983ed1e0544a85d35b1051fad6","src/unix/linux_like/linux/align.rs":"d6c259942c8e843373accd180fc8f4f45f03544dfd21b93a8d02641ead3ef63e","src/unix/linux_like/linux/arch/generic/mod.rs":"e20013ed91edcfb7f84f3f9f5a9ef827fd5c406e24b65989d8438da332236ef6","src/unix/linux_like/linux/arch/mips/mod.rs":"2d166054a586bb4bf6e4a4ba35f7574907b217225eff8f1a43adc4277e142460","src/unix/linux_like/linux/arch/mod.rs":"466a29622e47c6c7f1500682b2eb17f5566dd81b322cd6348f0fdd355cec593a","src/unix/linux_like/linux/arch/powerpc/mod.rs":"3f6da7b0fa7b394c7d4eea2bb3caa7a7729ab0d6c1491fef02206a912c41b815","src/unix/linux_like/linux/arch/sparc/mod.rs":"91593ec0440f1dd8f8e612028f432c44c14089286e2aca50e10511ab942db8c3","src/unix/linux_like/linux/gnu/align.rs":"e4a3c27fe20a57b8d612c34cb05bc70646edb5cec7251957315afa53a7b9f936","src/unix/linux_like/linux/gnu/b32/arm/align.rs":"6ec0eb3ee93f7ae99fd714b4deabfb5e97fbcefd8c26f5a45fb8e7150899cdeb","src/unix/linux_like/linux/gnu/b32/arm/mod.rs":"92ea7edc0e24f79dfbf5e3efc2d7509bed230562036e6aa85ef4f2c8088ecc8f","src/unix/linux_like/linux/gnu/b32/m68k/align.rs":"8faa92f77a9232c035418d45331774e64a9a841d99c91791570a203bf2b45bcb","src/unix/linux_like/linux/gnu/b32/m68k/mod.rs":"a2a0a9400dae44086ebf579e0448e0676d4a3214d1ae7d13a024857251e23b6b","src/unix/linux_like/linux/gnu/b32/mips/align.rs":"429fb5e005cb7143602d430098b6ebfb7d360685b194f333dfd587472ae954ee","src/unix/linux_like/linux/gnu/b32/mips/mod.rs":"0d7849eb2435ec1f49b6774872a0518f0129c50f37c9d38b37b1535722777a22","src/unix/linux_like/linux/gnu/b32/mod.rs":"8da281da578cdee972e952b118b903b370320897a7e335342a15e1359864bef2","src/unix/linux_like/linux/gnu/b32/powerpc.rs":"049d6211ba4a9304bd4497c160bc21ae847c24e0528dd9d76263f16192e6aff5","src/unix/linux_like/linux/gnu/b32/riscv32/align.rs":"d321491612be8d5c61b6ec2dc0111beb3a22e58803f99cd37543efe86621b119","src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs":"a4256148cec0bb672c8dfa605866930d9761af9655721de72ae41eeeb8fdbf6d","src/unix/linux_like/linux/gnu/b32/sparc/align.rs":"21adbed27df73e2d1ed934aaf733a643003d7baf2bde9c48ea440895bcca6d41","src/unix/linux_like/linux/gnu/b32/sparc/mod.rs":"525618615aa0cb80c6c90860bf579dfed8db307fffd56b97dc235fb945419434","src/unix/linux_like/linux/gnu/b32/x86/align.rs":"e4bafdc4a519a7922a81b37a62bbfd1177a2f620890eef8f1fbc47162e9eb413","src/unix/linux_like/linux/gnu/b32/x86/mod.rs":"78b4038852986436888c63be9258037cf642124daee9d5fa5cef2bf8e412bf54","src/unix/linux_like/linux/gnu/b64/aarch64/align.rs":"2179c3b1608fa4bf68840482bfc2b2fa3ee2faf6fcae3770f9e505cddca35c7b","src/unix/linux_like/linux/gnu/b64/aarch64/ilp32.rs":"21a21503ef2e095f4371044915d4bfb07a8578011cb5c713cd9f45947b0b5730","src/unix/linux_like/linux/gnu/b64/aarch64/int128.rs":"1735f6f5c56770d20dd426442f09724d9b2052b46a7cd82f23f3288a4a7276de","src/unix/linux_like/linux/gnu/b64/aarch64/lp64.rs":"e78c3cd197f44832338b414d1a9bc0d194f44c74db77bd7bf830c1fff62b2690","src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs":"c4e20b1c63d7a03a6e22aef2046689ef95cc4651011ade7cb94176fcea1dc252","src/unix/linux_like/linux/gnu/b64/loongarch64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/linux/gnu/b64/loongarch64/mod.rs":"387808d5398b24339e7e2bf7591150735011befc5b421fa713d7017c04a7b1da","src/unix/linux_like/linux/gnu/b64/mips64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/linux/gnu/b64/mips64/mod.rs":"17aad16329431d83e1909e3a08022f6e28f4bcba7dec4a967fe1a321a6a43b99","src/unix/linux_like/linux/gnu/b64/mod.rs":"3c6555f30a7a8852757b31a542ea73fb6a16a6e27e838397e819278ad56e57a4","src/unix/linux_like/linux/gnu/b64/powerpc64/align.rs":"e29c4868bbecfa4a6cd8a2ad06193f3bbc78a468cc1dc9df83f002f1268130d9","src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs":"97e0ecf11ecce793a13fec39654fb513c5479edf7faa7a276fa714b61993d0fc","src/unix/linux_like/linux/gnu/b64/riscv64/align.rs":"d321491612be8d5c61b6ec2dc0111beb3a22e58803f99cd37543efe86621b119","src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs":"b3fe290afe63d2d6e315d0cf1f775464e9c1f2a1906d243c1af74a137a4031cb","src/unix/linux_like/linux/gnu/b64/s390x.rs":"254f00266ecf9644a4b469457cb37c4dd6c055820926c1de0fb9035b6048e75c","src/unix/linux_like/linux/gnu/b64/sparc64/align.rs":"e29c4868bbecfa4a6cd8a2ad06193f3bbc78a468cc1dc9df83f002f1268130d9","src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs":"87dd7f3d5bf3c09f4064ec738e306cc9cc41ad49b4a5df62c5983301c3bbf99a","src/unix/linux_like/linux/gnu/b64/x86_64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs":"1b939aaf3cdf3efc7d3bd53e83e80235530d3ba0c24bb7611d4730d35d457ec1","src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs":"b88ef8a1eaa9ed73bf2acb8192afb73af987a92abb94140c6376fc83f2fa5553","src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs":"79305936a60d342efdc10519ba89507d6b48e65f13f33090d3b04dc9655ceed0","src/unix/linux_like/linux/gnu/mod.rs":"84ad4a663b5fa2498179be8dca96fef5f0446ec1619215ac674424ee394e307d","src/unix/linux_like/linux/gnu/no_align.rs":"9cd223135de75315840ff9c3fd5441ba1cb632b96b5c85a76f8316c86653db25","src/unix/linux_like/linux/mod.rs":"cff23db1e0bac8c30052dfed5e89e65bc207471e4bfb3a6fa0a4df62ed9e413e","src/unix/linux_like/linux/musl/b32/arm/align.rs":"3e8ac052c1043764776b54c93ba4260e061df998631737a897d9d47d54f7b80c","src/unix/linux_like/linux/musl/b32/arm/mod.rs":"e5faee8efda8a225ea0b17d4d6f9e893a678e73773fa62c549a8e19c106b9f04","src/unix/linux_like/linux/musl/b32/hexagon.rs":"226a8b64ce9c75abbbee6d2dceb0b44f7b6c750c4102ebd4d015194afee6666e","src/unix/linux_like/linux/musl/b32/mips/align.rs":"429fb5e005cb7143602d430098b6ebfb7d360685b194f333dfd587472ae954ee","src/unix/linux_like/linux/musl/b32/mips/mod.rs":"df8f8b529a6cc6b8a7326639e83303cf1320c6c50d76517c17d42bcf45f6240a","src/unix/linux_like/linux/musl/b32/mod.rs":"7b3d9dfd8605b00bb9b5fa1439abe5ebf60199c7fa033eee555e8d181e93ffa2","src/unix/linux_like/linux/musl/b32/powerpc.rs":"c957d99a4d4371d2411a5769be8cf344516bf9ddc1011f977501a4eb57cb4e82","src/unix/linux_like/linux/musl/b32/riscv32/align.rs":"efd2accf33b87de7c7547903359a5da896edc33cd6c719552c7474b60d4a5d48","src/unix/linux_like/linux/musl/b32/riscv32/mod.rs":"698f77bfcc838f82126c54f7387881fe3e89490117e5a4f333d1b4433823a672","src/unix/linux_like/linux/musl/b32/x86/align.rs":"08e77fbd7435d7dec2ff56932433bece3f02e47ce810f89004a275a86d39cbe1","src/unix/linux_like/linux/musl/b32/x86/mod.rs":"199a91e90b454f9dc32770d5204cc4f6e5b8f144e0e34a1c91829949d6e804b3","src/unix/linux_like/linux/musl/b64/aarch64/align.rs":"798a9229d70ce235394f2dd625f6c4c1e10519a94382dc5b091952b638ae2928","src/unix/linux_like/linux/musl/b64/aarch64/int128.rs":"1735f6f5c56770d20dd426442f09724d9b2052b46a7cd82f23f3288a4a7276de","src/unix/linux_like/linux/musl/b64/aarch64/mod.rs":"9c4878df0fea0e0affd85346e0bc191abdc5e41e74dc9199b5644ec33d29c300","src/unix/linux_like/linux/musl/b64/mips64.rs":"3686fc8cb2e311cda8e6b96f6dfe90b65a366714bd480312b692b1a6ca1241b6","src/unix/linux_like/linux/musl/b64/mod.rs":"8c10627bd582cb272514e7350ae4743a65d489356eae039d2e7e55cd533fbbc8","src/unix/linux_like/linux/musl/b64/powerpc64.rs":"36694cbdcdc33879e00502d55cb95eaa0096d213538993dd39c3da800cdd06d1","src/unix/linux_like/linux/musl/b64/riscv64/align.rs":"d321491612be8d5c61b6ec2dc0111beb3a22e58803f99cd37543efe86621b119","src/unix/linux_like/linux/musl/b64/riscv64/mod.rs":"36621aca8ecf714f8dd42662dc2997833d95b9f129ef8c220503362e21efd695","src/unix/linux_like/linux/musl/b64/s390x.rs":"9b05b1fae6bcb7cb6d909b9973977fde01684175f3e26c27dcb44223cc3933d9","src/unix/linux_like/linux/musl/b64/x86_64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/linux/musl/b64/x86_64/mod.rs":"238789097a26abc8b7cd578ed1a8e6cb8672083054303902781983902cd66854","src/unix/linux_like/linux/musl/mod.rs":"2efe98b8166270be1624888953fa07da06f08313f15bf4c7dc2eba63f5a790a5","src/unix/linux_like/linux/no_align.rs":"da2a8721becaaaa528781f97f5d9aae6a982ae5d4f5f6d2ffc0150bed72319b3","src/unix/linux_like/linux/non_exhaustive.rs":"181a05bf94fdb911db83ce793b993bd6548a4115b306a7ef3c10f745a8fea3e9","src/unix/linux_like/linux/uclibc/align.rs":"9ed16138d8e439bd90930845a65eafa7ebd67366e6bf633936d44014f6e4c959","src/unix/linux_like/linux/uclibc/arm/align.rs":"e4a3c27fe20a57b8d612c34cb05bc70646edb5cec7251957315afa53a7b9f936","src/unix/linux_like/linux/uclibc/arm/mod.rs":"a056bbf718ddd775519058706bdb4909b56e6256985869e3c3132aa8ec5faca0","src/unix/linux_like/linux/uclibc/arm/no_align.rs":"9cd223135de75315840ff9c3fd5441ba1cb632b96b5c85a76f8316c86653db25","src/unix/linux_like/linux/uclibc/mips/mips32/align.rs":"e4a3c27fe20a57b8d612c34cb05bc70646edb5cec7251957315afa53a7b9f936","src/unix/linux_like/linux/uclibc/mips/mips32/mod.rs":"b84def53a49587e87f884c2bc28b21b290463b00b52e1d0309f2ba233a5b4a99","src/unix/linux_like/linux/uclibc/mips/mips32/no_align.rs":"9cd223135de75315840ff9c3fd5441ba1cb632b96b5c85a76f8316c86653db25","src/unix/linux_like/linux/uclibc/mips/mips64/align.rs":"a7bdcb18a37a2d91e64d5fad83ea3edc78f5412adb28f77ab077dbb26dd08b2d","src/unix/linux_like/linux/uclibc/mips/mips64/mod.rs":"256a428290a560163ef7dc7d18b27bd3c6ce9748a0f28d5dc7f82203ee228220","src/unix/linux_like/linux/uclibc/mips/mips64/no_align.rs":"4a18e3875698c85229599225ac3401a2a40da87e77b2ad4ef47c6fcd5a24ed30","src/unix/linux_like/linux/uclibc/mips/mod.rs":"367ec5483ad317e6ccba1ac0888da6cf088a8d32689214cc8d16129aa692260c","src/unix/linux_like/linux/uclibc/mod.rs":"ddd223d4f574b2b92072bbdab091f12d8d89d5e05f41076ddfa6bc6af379698f","src/unix/linux_like/linux/uclibc/no_align.rs":"3f28637046524618adaa1012e26cb7ffe94b9396e6b518cccdc69d59f274d709","src/unix/linux_like/linux/uclibc/x86_64/l4re.rs":"024eba5753e852dbdd212427351affe7e83f9916c1864bce414d7aa2618f192e","src/unix/linux_like/linux/uclibc/x86_64/mod.rs":"bf6985e901041a61e90ccee1296b35a4c62ef90aa528d31989e1d647f072e79a","src/unix/linux_like/linux/uclibc/x86_64/other.rs":"42c3f71e58cabba373f6a55a623f3c31b85049eb64824c09c2b082b3b2d6a0a8","src/unix/linux_like/mod.rs":"dd4f7a1d66d8501b4a2c4e75e6e9305ed69f1002ae99e410596a6c636878595a","src/unix/mod.rs":"d1b4ba41f9b9c106f6ba8c661b5808824b774a7a7caac7d8938bf50979ba5195","src/unix/newlib/aarch64/mod.rs":"bac93836a9a57b2c710f32f852e92a4d11ad6759ab0fb6ad33e71d60e53278af","src/unix/newlib/align.rs":"28aaf87fafbc6b312622719d472d8cf65f9e5467d15339df5f73e66d8502b28a","src/unix/newlib/arm/mod.rs":"cbba6b3e957eceb496806e60de8725a23ff3fa0015983b4b4fa27b233732b526","src/unix/newlib/espidf/mod.rs":"ff9c13e99d84912f5ebe75b7a7ea9c1e9d8f35a268716081e09899c7ea822bc6","src/unix/newlib/generic.rs":"eab066d9f0a0f3eb53cc1073d01496bba0110989e1f6a59838afd19f870cd599","src/unix/newlib/horizon/mod.rs":"7cc5cc120437421db139bfa6a90b18168cd3070bdd0f5be96d40fe4c996f3ca1","src/unix/newlib/mod.rs":"54633d606e4e0413274af0b5beb5e697e6c061b63feaa0704b026554cc9d9c3e","src/unix/newlib/no_align.rs":"e0743b2179495a9514bc3a4d1781e492878c4ec834ee0085d0891dd1712e82fb","src/unix/newlib/powerpc/mod.rs":"0202ffd57caf75b6afa2c9717750ffb96e375ac33df0ae9609a3f831be393b67","src/unix/no_align.rs":"c06e95373b9088266e0b14bba0954eef95f93fb2b01d951855e382d22de78e53","src/unix/redox/mod.rs":"033768cb273daf2c8090d97252c2de9dba6809e6a5d2457f5727d724807695db","src/unix/solarish/compat.rs":"b07a5bfac925eb012003a459ba6bddbd3bfa9c44b3394da2ac5a602e54beae9c","src/unix/solarish/illumos.rs":"29387916ee7dc58f07478746024003215e631cd30953e8fa2a5c415f81839007","src/unix/solarish/mod.rs":"976b07a13e195840b67c166a62318abfa9ffc8d5ebbb0358f199dd213ec98d1b","src/unix/solarish/solaris.rs":"65b005453aefa9b9d4fc860fe77cfec80d8c97a51342b15daf55fc3e808bb384","src/unix/solarish/x86.rs":"e86e806df0caed72765040eaa2f3c883198d1aa91508540adf9b7008c77f522e","src/unix/solarish/x86_64.rs":"9074e813949f3c613afeac39d4118fb942c0b3c476232fc536489357cff5790f","src/unix/solarish/x86_common.rs":"ac869d9c3c95645c22460468391eb1982023c3a8e02b9e06a72e3aef3d5f1eac","src/vxworks/aarch64.rs":"98f0afdc511cd02557e506c21fed6737585490a1dce7a9d4941d08c437762b99","src/vxworks/arm.rs":"acb7968ce99fe3f4abdf39d98f8133d21a4fba435b8ef7084777cb181d788e88","src/vxworks/mod.rs":"aea3da66f2140f2a82dfc9c58f6e6531d2dd9c15ea696e0f95a0d4a2a187b5b6","src/vxworks/powerpc.rs":"acb7968ce99fe3f4abdf39d98f8133d21a4fba435b8ef7084777cb181d788e88","src/vxworks/powerpc64.rs":"98f0afdc511cd02557e506c21fed6737585490a1dce7a9d4941d08c437762b99","src/vxworks/x86.rs":"552f007f38317620b23889cb7c49d1d115841252439060122f52f434fbc6e5ba","src/vxworks/x86_64.rs":"018d92be3ad628a129eff9f2f5dfbc0883d8b8e5f2fa917b900a7f98ed6b514a","src/wasi.rs":"4fae202af0327d768ed9e1b586b75816cce14fe2dc16947d2f3d381f209a54c1","src/windows/gnu/align.rs":"b2c13ec1b9f3b39a75c452c80c951dff9d0215e31d77e883b4502afb31794647","src/windows/gnu/mod.rs":"3c8c7edb7cdf5d0c44af936db2a94869585c69dfabeef30571b4f4e38375767a","src/windows/mod.rs":"e3ad95ba54f76e74c301611fe868d3d94f6b8939b03be672f568b06b10ae71c7","src/windows/msvc/mod.rs":"c068271e00fca6b62bc4bf44bcf142cfc38caeded9b6c4e01d1ceef3ccf986f4","tests/const_fn.rs":"cb75a1f0864f926aebe79118fc34d51a0d1ade2c20a394e7774c7e545f21f1f4"},"package":"349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"} \ No newline at end of file +{"files":{"CONTRIBUTING.md":"f480d10d2a506eecd23ae2e2dedb7a28b8bf6dae5f46f438dbb61be2003426fb","Cargo.toml":"04fa9ce26b0efcfe3dd51e3f1bbb81bb36f5d61982a11947283c7616d390549e","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"a8d47ff51ca256f56a8932dba07660672dbfe3004257ca8de708aac1415937a1","README.md":"776affa26b66843a2b4f1a1c8f88d92f6461b74568911450fea717e9db6f877b","build.rs":"1d0cbe878e98e970c3318cac0772215a9f44bd286d859d665da27872ba9d8818","rustfmt.toml":"eaa2ea84fc1ba0359b77680804903e07bb38d257ab11986b95b158e460f787b2","src/fixed_width_ints.rs":"7f986e5f5e68d25ef04d386fd2f640e8be8f15427a8d4a458ea01d26b8dca0ca","src/fuchsia/aarch64.rs":"378776a9e40766154a54c94c2a7b4675b5c302a38e6e42da99e67bfbaee60e56","src/fuchsia/align.rs":"ae1cf8f011a99737eabeb14ffff768e60f13b13363d7646744dbb0f443dab3d6","src/fuchsia/mod.rs":"cf7e0df0e655337d1c0852880817b6b514ef9599e2125232fc79cdf8eddd01ba","src/fuchsia/no_align.rs":"303f3f1b255e0088b5715094353cf00476131d8e94e6aebb3f469557771c8b8a","src/fuchsia/x86_64.rs":"93a3632b5cf67d2a6bcb7dc0a558605252d5fe689e0f38d8aa2ec5852255ac87","src/hermit/aarch64.rs":"86048676e335944c37a63d0083d0f368ae10ceccefeed9debb3bbe08777fc682","src/hermit/mod.rs":"d3bfce41e4463d4be8020a2d063c9bfa8b665f45f1cc6cbf3163f5d01e7cb21f","src/hermit/x86_64.rs":"ab832b7524e5fb15c49ff7431165ab1a37dc4667ae0b58e8306f4c539bfa110c","src/lib.rs":"ce753ef318b300bbd441feabdd77d00322dfb6ce9eee8c78a38afe02b57aa4c0","src/macros.rs":"b457eb028b8e8ab3c24bb7292b874ad4e491edbb83594f6a3da024df5348c088","src/psp.rs":"dd31aabd46171d474ec5828372e28588935120e7355c90c105360d8fa9264c1c","src/sgx.rs":"16a95cdefc81c5ee00d8353a60db363c4cc3e0f75abcd5d0144723f2a306ed1b","src/solid/aarch64.rs":"a726e47f324adf73a4a0b67a2c183408d0cad105ae66acf36db37a42ab7f8707","src/solid/arm.rs":"e39a4f74ebbef3b97b8c95758ad741123d84ed3eb48d9cf4f1f4872097fc27fe","src/solid/mod.rs":"5f4151dca5132e4b4e4c23ab9737e12856dddbdc0ca3f7dbc004328ef3c8acde","src/switch.rs":"9da3dd39b3de45a7928789926e8572d00e1e11a39e6f7289a1349aadce90edba","src/unix/align.rs":"2cdc7c826ef7ae61f5171c5ae8c445a743d86f1a7f2d9d7e4ceeec56d6874f65","src/unix/bsd/apple/b32/align.rs":"ec833a747866fe19ca2d9b4d3c9ff0385faba5edf4bd0d15fa68884c40b0e26c","src/unix/bsd/apple/b32/mod.rs":"2546ad3eb6aecb95f916648bc63264117c92b4b4859532b34cb011e4c75a5a72","src/unix/bsd/apple/b64/aarch64/align.rs":"e8eb38d064b5fefec6f37d42873820a0483e7c758ed336cc59a7155455ca89c9","src/unix/bsd/apple/b64/aarch64/mod.rs":"a3f0dfff62d0f7f4f1b5f9a4e2b662acf233a46badbc5419d3cc2d735629a710","src/unix/bsd/apple/b64/align.rs":"ec833a747866fe19ca2d9b4d3c9ff0385faba5edf4bd0d15fa68884c40b0e26c","src/unix/bsd/apple/b64/mod.rs":"f5e278a1af7fb358891d1c9be4eb7e815aaca0c5cb738d0c3604ba2208a856f7","src/unix/bsd/apple/b64/x86_64/align.rs":"ec833a747866fe19ca2d9b4d3c9ff0385faba5edf4bd0d15fa68884c40b0e26c","src/unix/bsd/apple/b64/x86_64/mod.rs":"8c87c5855038aae5d433c8f5eb3b29b0a175879a0245342b3bfd83bdf4cfd936","src/unix/bsd/apple/mod.rs":"bb61eec399428faee753b3df509410c51ed2ac51406d40559fcec290bb50e293","src/unix/bsd/freebsdlike/dragonfly/errno.rs":"8295b8bb0dfd38d2cdb4d9192cdeeb534cc6c3b208170e64615fa3e0edb3e578","src/unix/bsd/freebsdlike/dragonfly/mod.rs":"e4f33050d52d3e5c932da8d10e1f377e1ff609fb178ea986bfc458d31e37dc19","src/unix/bsd/freebsdlike/freebsd/aarch64.rs":"2a215bd6136b8617aacedf9be738ccee94da9d29b418e9a78101d6291c182352","src/unix/bsd/freebsdlike/freebsd/arm.rs":"59d6a670eea562fb87686e243e0a84603d29a2028a3d4b3f99ccc01bd04d2f47","src/unix/bsd/freebsdlike/freebsd/freebsd11/b64.rs":"9808d152c1196aa647f1b0f0cf84dac8c930da7d7f897a44975545e3d9d17681","src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs":"23f189f188651762b38f40b4e9aba785625f6f9a52558a4a490510c3b1d08b53","src/unix/bsd/freebsdlike/freebsd/freebsd12/b64.rs":"61cbe45f8499bedb168106b686d4f8239472f25c7553b069eec2afe197ff2df6","src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs":"57fee9dd251ac615ec7d32d293e0f0b6fa3bf28efbddd6d569765765aafb8b9b","src/unix/bsd/freebsdlike/freebsd/freebsd12/x86_64.rs":"2df36a7f122f6d6e5753cfb4d22e915cc80f6bc91c0161b3daae55a481bfd052","src/unix/bsd/freebsdlike/freebsd/freebsd13/b64.rs":"61cbe45f8499bedb168106b686d4f8239472f25c7553b069eec2afe197ff2df6","src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs":"7df84dd6dee8b73fd4d72dd1638584d788e2a1a85f95746f7c5b330b8dc23655","src/unix/bsd/freebsdlike/freebsd/freebsd13/x86_64.rs":"2df36a7f122f6d6e5753cfb4d22e915cc80f6bc91c0161b3daae55a481bfd052","src/unix/bsd/freebsdlike/freebsd/freebsd14/b64.rs":"61cbe45f8499bedb168106b686d4f8239472f25c7553b069eec2afe197ff2df6","src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs":"236ef119410d566ef94064bf13d734635eaeecb3635a5d21e8e9f91e7e3152ac","src/unix/bsd/freebsdlike/freebsd/freebsd14/x86_64.rs":"2df36a7f122f6d6e5753cfb4d22e915cc80f6bc91c0161b3daae55a481bfd052","src/unix/bsd/freebsdlike/freebsd/mod.rs":"6a8eb9a1e35eec893de9c76a5be3ce29e4c3ca26db45fbcfa925bdd757f6352d","src/unix/bsd/freebsdlike/freebsd/powerpc.rs":"9ca3f82f88974e6db5569f2d76a5a3749b248a31747a6c0da5820492bdfeca42","src/unix/bsd/freebsdlike/freebsd/powerpc64.rs":"2dae3ecc87eac3b11657aa98915def55fc4b5c0de11fe26aae23329a54628a9a","src/unix/bsd/freebsdlike/freebsd/riscv64.rs":"8f591bd273464d684c4f64365f8ed56a8138175daa70d96008541393057a0dae","src/unix/bsd/freebsdlike/freebsd/x86.rs":"c5005e3249eb7c93cfbac72a9e9272320d80ce7983da990ceb05a447f59a02c5","src/unix/bsd/freebsdlike/freebsd/x86_64/align.rs":"0e1f69a88fca1c32874b1daf5db3d446fefbe518dca497f096cc9168c39dde70","src/unix/bsd/freebsdlike/freebsd/x86_64/mod.rs":"51e4dd0c8ae247bb652feda5adad9333ea3bb30c750c3a3935e0b0e47d7803eb","src/unix/bsd/freebsdlike/mod.rs":"a61d41f6fe01c06c6de5db2ed970522601eada133e6bac4ed2d1dfaceb576db2","src/unix/bsd/mod.rs":"817ca5719c36a74c84e52c6a56a5998b60d7f02351a405e034f08ebab079b63a","src/unix/bsd/netbsdlike/mod.rs":"b07a0e81085bd811fce7270f3b90fbfea29faf9593d9e39d9d2ebbb9a78bf25f","src/unix/bsd/netbsdlike/netbsd/aarch64.rs":"65dcb58d11e8d8028401a9d07ca3eb4cb4f053e04249cc877353449d84ccc4cb","src/unix/bsd/netbsdlike/netbsd/arm.rs":"58cdbb70b0d6f536551f0f3bb3725d2d75c4690db12c26c034e7d6ec4a924452","src/unix/bsd/netbsdlike/netbsd/mod.rs":"fa260decf53280d4fdf714af60f42d4774f8d6f2da71b0a55a6c2a85e422eb57","src/unix/bsd/netbsdlike/netbsd/powerpc.rs":"ee7ff5d89d0ed22f531237b5059aa669df93a3b5c489fa641465ace8d405bf41","src/unix/bsd/netbsdlike/netbsd/sparc64.rs":"9489f4b3e4566f43bb12dfb92238960613dac7f6a45cc13068a8d152b902d7d9","src/unix/bsd/netbsdlike/netbsd/x86.rs":"20692320e36bfe028d1a34d16fe12ca77aa909cb02bda167376f98f1a09aefe7","src/unix/bsd/netbsdlike/netbsd/x86_64.rs":"1afe5ef46b14397cdd68664b5b232e4f5b035b6db1d4cf411c899d51ebca9f30","src/unix/bsd/netbsdlike/openbsd/aarch64.rs":"dd91931d373b7ecaf6e2de25adadee10d16fa9b12c2cbacdff3eb291e1ba36af","src/unix/bsd/netbsdlike/openbsd/arm.rs":"01580d261bc6447bb327a0d982181b7bdabfa066cee65a30373d3ced729ad307","src/unix/bsd/netbsdlike/openbsd/mips64.rs":"8532a189ae10c7d668d9d4065da8b05d124e09bd39442c9f74a7f231c43eca48","src/unix/bsd/netbsdlike/openbsd/mod.rs":"079b11c99c6ca3cc5942c0e6d854541f8765c5058c2f024b84656697840e198b","src/unix/bsd/netbsdlike/openbsd/powerpc.rs":"01580d261bc6447bb327a0d982181b7bdabfa066cee65a30373d3ced729ad307","src/unix/bsd/netbsdlike/openbsd/powerpc64.rs":"1dd5449dd1fd3d51e30ffdeeaece91d0aaf05c710e0ac699fecc5461cfa2c28e","src/unix/bsd/netbsdlike/openbsd/riscv64.rs":"1dd5449dd1fd3d51e30ffdeeaece91d0aaf05c710e0ac699fecc5461cfa2c28e","src/unix/bsd/netbsdlike/openbsd/sparc64.rs":"d04fd287afbaa2c5df9d48c94e8374a532a3ba491b424ddf018270c7312f4085","src/unix/bsd/netbsdlike/openbsd/x86.rs":"6f7f5c4fde2a2259eb547890cbd86570cea04ef85347d7569e94e679448bec87","src/unix/bsd/netbsdlike/openbsd/x86_64.rs":"d31db31630289c85af3339dbe357998a21ca584cbae31607448fe2cf7675a4e1","src/unix/haiku/b32.rs":"a2efdbf7158a6da341e1db9176b0ab193ba88b449616239ed95dced11f54d87b","src/unix/haiku/b64.rs":"ff8115367d3d7d354f792d6176dfaaa26353f57056197b563bf4681f91ff7985","src/unix/haiku/mod.rs":"df7b6b7d8dd3441665bfe87f2abc942bddc65b8b10dfa9c83dd0422f68107891","src/unix/haiku/native.rs":"dbfcbf4954a79d1df2ff58e0590bbcb8c57dfc7a32392aa73ee4726b66bd6cc8","src/unix/haiku/x86_64.rs":"3ec3aeeb7ed208b8916f3e32d42bfd085ff5e16936a1a35d9a52789f043b7237","src/unix/hermit/aarch64.rs":"86048676e335944c37a63d0083d0f368ae10ceccefeed9debb3bbe08777fc682","src/unix/hermit/mod.rs":"859814f5df89e28fd4b345db399d181e11e7ed413841b6ff703a1fcbdbf013ae","src/unix/hermit/x86_64.rs":"ab832b7524e5fb15c49ff7431165ab1a37dc4667ae0b58e8306f4c539bfa110c","src/unix/linux_like/android/b32/arm.rs":"433c1530f602cc5ed26610c58055dde0c4ceea5e00150063b24ddc60768332a4","src/unix/linux_like/android/b32/mod.rs":"7c173e0375119bf06a3081652faede95e5bcd6858e7576b7533d037978737c8f","src/unix/linux_like/android/b32/x86/align.rs":"812914e4241df82e32b12375ca3374615dc3a4bdd4cf31f0423c5815320c0dab","src/unix/linux_like/android/b32/x86/mod.rs":"8388bd3a0fcb5636bf965eee6dc95ae6860b85a2b555b387c868aa4d4e01ec89","src/unix/linux_like/android/b64/aarch64/align.rs":"2179c3b1608fa4bf68840482bfc2b2fa3ee2faf6fcae3770f9e505cddca35c7b","src/unix/linux_like/android/b64/aarch64/int128.rs":"1735f6f5c56770d20dd426442f09724d9b2052b46a7cd82f23f3288a4a7276de","src/unix/linux_like/android/b64/aarch64/mod.rs":"ef230d49fd0d182adf2dae6f8e10babf18d72259d65980bf1c4c2dc8a4f84501","src/unix/linux_like/android/b64/mod.rs":"71e4fcbe952bfa4a5f9022f3972e906917b38f729b9d8ef57cd5d179104894ac","src/unix/linux_like/android/b64/riscv64/align.rs":"0bf138f84e5327d8339bcd4adf071a6832b516445e597552c82bbd881095e3a8","src/unix/linux_like/android/b64/riscv64/mod.rs":"80e9f93fed838a48b4e2e8d77b95c72cfd7c0647bcce63851555c5ad16dad143","src/unix/linux_like/android/b64/x86_64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/android/b64/x86_64/mod.rs":"e10d19bea39f719723ab6666a5ddbd378b6958769441c5904629e1df173b1dc2","src/unix/linux_like/android/mod.rs":"41b9d0f405cd474385acce06df0649f4eeaab3fe8fb4655f97806fa40bdf84d8","src/unix/linux_like/emscripten/align.rs":"86c95cbed7a7161b1f23ee06843e7b0e2340ad92b2cb86fe2a8ef3e0e8c36216","src/unix/linux_like/emscripten/mod.rs":"6ef4652dfb94e3c58aed5133ece982ad30569d46b6b1054552cd61905fa61690","src/unix/linux_like/emscripten/no_align.rs":"0128e4aa721a9902754828b61b5ec7d8a86619983ed1e0544a85d35b1051fad6","src/unix/linux_like/linux/align.rs":"d6c259942c8e843373accd180fc8f4f45f03544dfd21b93a8d02641ead3ef63e","src/unix/linux_like/linux/arch/generic/mod.rs":"e2b46404e44f7d63c26af9dbd79b4e166ef7bced2bc9c6746a26ca86e508e0d4","src/unix/linux_like/linux/arch/mips/mod.rs":"2d166054a586bb4bf6e4a4ba35f7574907b217225eff8f1a43adc4277e142460","src/unix/linux_like/linux/arch/mod.rs":"466a29622e47c6c7f1500682b2eb17f5566dd81b322cd6348f0fdd355cec593a","src/unix/linux_like/linux/arch/powerpc/mod.rs":"3f6da7b0fa7b394c7d4eea2bb3caa7a7729ab0d6c1491fef02206a912c41b815","src/unix/linux_like/linux/arch/sparc/mod.rs":"91593ec0440f1dd8f8e612028f432c44c14089286e2aca50e10511ab942db8c3","src/unix/linux_like/linux/gnu/align.rs":"e4a3c27fe20a57b8d612c34cb05bc70646edb5cec7251957315afa53a7b9f936","src/unix/linux_like/linux/gnu/b32/arm/align.rs":"6ec0eb3ee93f7ae99fd714b4deabfb5e97fbcefd8c26f5a45fb8e7150899cdeb","src/unix/linux_like/linux/gnu/b32/arm/mod.rs":"5bd3f6b3484e049ddaac95f411b0d82cbf1cd28e6a5defbc927bd917f5f7d299","src/unix/linux_like/linux/gnu/b32/m68k/align.rs":"8faa92f77a9232c035418d45331774e64a9a841d99c91791570a203bf2b45bcb","src/unix/linux_like/linux/gnu/b32/m68k/mod.rs":"a2a0a9400dae44086ebf579e0448e0676d4a3214d1ae7d13a024857251e23b6b","src/unix/linux_like/linux/gnu/b32/mips/align.rs":"429fb5e005cb7143602d430098b6ebfb7d360685b194f333dfd587472ae954ee","src/unix/linux_like/linux/gnu/b32/mips/mod.rs":"6b9a5dac6f937ddc1453e808e3c43502c87143332df9e43ac64fb8b1eda6c116","src/unix/linux_like/linux/gnu/b32/mod.rs":"8da281da578cdee972e952b118b903b370320897a7e335342a15e1359864bef2","src/unix/linux_like/linux/gnu/b32/powerpc.rs":"5c5d90326b54b57b98eff4745fe7a3fb02f053b2dc782241a73e807b491936a3","src/unix/linux_like/linux/gnu/b32/riscv32/align.rs":"d321491612be8d5c61b6ec2dc0111beb3a22e58803f99cd37543efe86621b119","src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs":"5e7c1e29aeb82fc422f45b73fb0cf3d13d0902300f9150d2755a9074f8d96999","src/unix/linux_like/linux/gnu/b32/sparc/align.rs":"21adbed27df73e2d1ed934aaf733a643003d7baf2bde9c48ea440895bcca6d41","src/unix/linux_like/linux/gnu/b32/sparc/mod.rs":"80894eece66e9348f45d1b07ad37c757ea694bbd10ed49d3f920b34e9f51a9a3","src/unix/linux_like/linux/gnu/b32/x86/align.rs":"e4bafdc4a519a7922a81b37a62bbfd1177a2f620890eef8f1fbc47162e9eb413","src/unix/linux_like/linux/gnu/b32/x86/mod.rs":"c703cc5e9de2dc31d9e5831bfb6f354d6e3518b2ae02263f68a9a70f1c0167e2","src/unix/linux_like/linux/gnu/b64/aarch64/align.rs":"5b32fcc0d60356c92ded4e0ba9bb32f0140a8bd75ba800486bf38294f61dbdbb","src/unix/linux_like/linux/gnu/b64/aarch64/ilp32.rs":"21a21503ef2e095f4371044915d4bfb07a8578011cb5c713cd9f45947b0b5730","src/unix/linux_like/linux/gnu/b64/aarch64/int128.rs":"1735f6f5c56770d20dd426442f09724d9b2052b46a7cd82f23f3288a4a7276de","src/unix/linux_like/linux/gnu/b64/aarch64/lp64.rs":"e78c3cd197f44832338b414d1a9bc0d194f44c74db77bd7bf830c1fff62b2690","src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs":"c91813ee5e1bc817996c46be86d1f46802e73df2952cab576ea015490929afc5","src/unix/linux_like/linux/gnu/b64/loongarch64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/linux/gnu/b64/loongarch64/mod.rs":"387808d5398b24339e7e2bf7591150735011befc5b421fa713d7017c04a7b1da","src/unix/linux_like/linux/gnu/b64/mips64/align.rs":"7169d07a9fd4716f7512719aec9fda5d8bed306dc0720ffc1b21696c9951e3c6","src/unix/linux_like/linux/gnu/b64/mips64/mod.rs":"80b4b97a41564290c510e68a1fb20cfd8424206f010e71a596f12877de886a71","src/unix/linux_like/linux/gnu/b64/mod.rs":"3c6555f30a7a8852757b31a542ea73fb6a16a6e27e838397e819278ad56e57a4","src/unix/linux_like/linux/gnu/b64/powerpc64/align.rs":"e29c4868bbecfa4a6cd8a2ad06193f3bbc78a468cc1dc9df83f002f1268130d9","src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs":"a595e37c2325ceb40ef66c634bd3c255ad184a1d70ff8025e98a075f0ec67704","src/unix/linux_like/linux/gnu/b64/riscv64/align.rs":"d321491612be8d5c61b6ec2dc0111beb3a22e58803f99cd37543efe86621b119","src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs":"ef4b13477ffd8532fb6705ca3fa63a1f13e8d19ee39b083c5355dfce430c1a5b","src/unix/linux_like/linux/gnu/b64/s390x.rs":"788fde4fa1919859cc028b59da31de00449edd2b2c1530ae76134beac418b73c","src/unix/linux_like/linux/gnu/b64/sparc64/align.rs":"e29c4868bbecfa4a6cd8a2ad06193f3bbc78a468cc1dc9df83f002f1268130d9","src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs":"c4fa0ede3f78b21a9982667922cccd0681bee3cb6d42208ea9958f65e93d6308","src/unix/linux_like/linux/gnu/b64/x86_64/align.rs":"62e822478356db4a73b6bbd1b36d825b893939ab4b308ec11b0578bcc4b49769","src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs":"e37e0421290b152fe508883181c41225e09dd5452a6b085e8d807b3b54823028","src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs":"c1b6345ce14f67d1b2e2f7f2c0ff9a074c07acbd348df69cb4558bda8c8fb9ae","src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs":"3f4d2aeadb7d2620cad09564abdbfc5cf02eeb5a27f2bab8a4e9b4bdbdb258a5","src/unix/linux_like/linux/gnu/mod.rs":"06abaca7fc85e805650ec807c4d06c888ff99e146e1ba2685f20840a86e35a2f","src/unix/linux_like/linux/gnu/no_align.rs":"9cd223135de75315840ff9c3fd5441ba1cb632b96b5c85a76f8316c86653db25","src/unix/linux_like/linux/mod.rs":"1d84f37fdfa4dfab1b758345af75e02485e2a18746830413c2afe5069a1e39ce","src/unix/linux_like/linux/musl/b32/arm/align.rs":"3e8ac052c1043764776b54c93ba4260e061df998631737a897d9d47d54f7b80c","src/unix/linux_like/linux/musl/b32/arm/mod.rs":"f5b217a93f99c2852f7fd1459f529798372fa7df84ee0cfd3d8cdd5b2021b8cf","src/unix/linux_like/linux/musl/b32/hexagon.rs":"226a8b64ce9c75abbbee6d2dceb0b44f7b6c750c4102ebd4d015194afee6666e","src/unix/linux_like/linux/musl/b32/mips/align.rs":"429fb5e005cb7143602d430098b6ebfb7d360685b194f333dfd587472ae954ee","src/unix/linux_like/linux/musl/b32/mips/mod.rs":"16a7a03d998a5db11be9ee81525c7faec4623383260e8bc125b1c53a050fde75","src/unix/linux_like/linux/musl/b32/mod.rs":"580e27c5ce3344df686f1ffc08fdfa2c282d1ceb623d778c50d210d4bd65ec7e","src/unix/linux_like/linux/musl/b32/powerpc.rs":"dc52adc264c34bce80753d6bd064e8fc4b8237fa1e5c5315ccb6c72df74c2813","src/unix/linux_like/linux/musl/b32/riscv32/align.rs":"efd2accf33b87de7c7547903359a5da896edc33cd6c719552c7474b60d4a5d48","src/unix/linux_like/linux/musl/b32/riscv32/mod.rs":"e57dc5562553aab6d0765e0ec266254aa52975f8757bfe97e0c6028fa7d5d37c","src/unix/linux_like/linux/musl/b32/x86/align.rs":"08e77fbd7435d7dec2ff56932433bece3f02e47ce810f89004a275a86d39cbe1","src/unix/linux_like/linux/musl/b32/x86/mod.rs":"7a1586f77bb693f0b319ec720c35963da056287fc42f8e2ccf1d5b2bcccf4fd6","src/unix/linux_like/linux/musl/b64/aarch64/align.rs":"6ba32725d24d7d8e6aa111f3b57aafa318f83b606abe96561329151829821133","src/unix/linux_like/linux/musl/b64/aarch64/int128.rs":"1735f6f5c56770d20dd426442f09724d9b2052b46a7cd82f23f3288a4a7276de","src/unix/linux_like/linux/musl/b64/aarch64/mod.rs":"31e75179cbb4e26425b3f5b052e358f593153da662884655e60801d852e55dc2","src/unix/linux_like/linux/musl/b64/mips64.rs":"9a5d29f666332bb056d0e2951e9de989aa1dc016075f009db3f2f628e0cdda8c","src/unix/linux_like/linux/musl/b64/mod.rs":"8c10627bd582cb272514e7350ae4743a65d489356eae039d2e7e55cd533fbbc8","src/unix/linux_like/linux/musl/b64/powerpc64.rs":"455dc0ffa55afc1db6ffaf461f6f2a7b49d31658bfebe0bb4efac5967a6f956c","src/unix/linux_like/linux/musl/b64/riscv64/align.rs":"d321491612be8d5c61b6ec2dc0111beb3a22e58803f99cd37543efe86621b119","src/unix/linux_like/linux/musl/b64/riscv64/mod.rs":"42d4b6d36807f37759094a732a321080cccdf498b174d632cebba147051de294","src/unix/linux_like/linux/musl/b64/s390x.rs":"d8a4fdfea0960ec284cae4facb8b0fb342e8aa41544cffacdcaf08c5a92a43f8","src/unix/linux_like/linux/musl/b64/x86_64/align.rs":"77309276ad7a42cbe59ca381f23590b7a143aded05555b34a5b307b808cbca6e","src/unix/linux_like/linux/musl/b64/x86_64/mod.rs":"7a877cd23b64be66d28e6b8dddae32d59a88d69115637539daf19381f4e39330","src/unix/linux_like/linux/musl/mod.rs":"0514b337aaa6e62be9e01e00702ef996c60319b7050ece155530147c20de9995","src/unix/linux_like/linux/no_align.rs":"da2a8721becaaaa528781f97f5d9aae6a982ae5d4f5f6d2ffc0150bed72319b3","src/unix/linux_like/linux/non_exhaustive.rs":"181a05bf94fdb911db83ce793b993bd6548a4115b306a7ef3c10f745a8fea3e9","src/unix/linux_like/linux/uclibc/align.rs":"9ed16138d8e439bd90930845a65eafa7ebd67366e6bf633936d44014f6e4c959","src/unix/linux_like/linux/uclibc/arm/align.rs":"e4a3c27fe20a57b8d612c34cb05bc70646edb5cec7251957315afa53a7b9f936","src/unix/linux_like/linux/uclibc/arm/mod.rs":"7d8dfbd26ce958d9da17468b3c9d0b119ce7dbd59b3384551cd4423ce25db44a","src/unix/linux_like/linux/uclibc/arm/no_align.rs":"9cd223135de75315840ff9c3fd5441ba1cb632b96b5c85a76f8316c86653db25","src/unix/linux_like/linux/uclibc/mips/mips32/align.rs":"e4a3c27fe20a57b8d612c34cb05bc70646edb5cec7251957315afa53a7b9f936","src/unix/linux_like/linux/uclibc/mips/mips32/mod.rs":"b84def53a49587e87f884c2bc28b21b290463b00b52e1d0309f2ba233a5b4a99","src/unix/linux_like/linux/uclibc/mips/mips32/no_align.rs":"9cd223135de75315840ff9c3fd5441ba1cb632b96b5c85a76f8316c86653db25","src/unix/linux_like/linux/uclibc/mips/mips64/align.rs":"a7bdcb18a37a2d91e64d5fad83ea3edc78f5412adb28f77ab077dbb26dd08b2d","src/unix/linux_like/linux/uclibc/mips/mips64/mod.rs":"256a428290a560163ef7dc7d18b27bd3c6ce9748a0f28d5dc7f82203ee228220","src/unix/linux_like/linux/uclibc/mips/mips64/no_align.rs":"4a18e3875698c85229599225ac3401a2a40da87e77b2ad4ef47c6fcd5a24ed30","src/unix/linux_like/linux/uclibc/mips/mod.rs":"367ec5483ad317e6ccba1ac0888da6cf088a8d32689214cc8d16129aa692260c","src/unix/linux_like/linux/uclibc/mod.rs":"1c3d25cddcfefa2bd17bdc81550826be31a08eef235e13f825f169a5029c8bca","src/unix/linux_like/linux/uclibc/no_align.rs":"3f28637046524618adaa1012e26cb7ffe94b9396e6b518cccdc69d59f274d709","src/unix/linux_like/linux/uclibc/x86_64/l4re.rs":"024eba5753e852dbdd212427351affe7e83f9916c1864bce414d7aa2618f192e","src/unix/linux_like/linux/uclibc/x86_64/mod.rs":"420dbea99e99091f333641e202960fa4bed0733de2a834e610708555be6bab4c","src/unix/linux_like/linux/uclibc/x86_64/other.rs":"42c3f71e58cabba373f6a55a623f3c31b85049eb64824c09c2b082b3b2d6a0a8","src/unix/linux_like/mod.rs":"3d03bd583aaf04f285f95ff8b53c9b5a891d3b64bfcda37a42648ec51c4c51e5","src/unix/mod.rs":"fbd5520d160a32a127608cd408905febe387773bbf05bfe199ef385fb5562e9c","src/unix/newlib/aarch64/mod.rs":"bac93836a9a57b2c710f32f852e92a4d11ad6759ab0fb6ad33e71d60e53278af","src/unix/newlib/align.rs":"28aaf87fafbc6b312622719d472d8cf65f9e5467d15339df5f73e66d8502b28a","src/unix/newlib/arm/mod.rs":"cbba6b3e957eceb496806e60de8725a23ff3fa0015983b4b4fa27b233732b526","src/unix/newlib/espidf/mod.rs":"816f235f4aa4baabba7f2606b31d0fdb03988c52194c966728de8690bf17299d","src/unix/newlib/generic.rs":"eab066d9f0a0f3eb53cc1073d01496bba0110989e1f6a59838afd19f870cd599","src/unix/newlib/horizon/mod.rs":"7cc5cc120437421db139bfa6a90b18168cd3070bdd0f5be96d40fe4c996f3ca1","src/unix/newlib/mod.rs":"494e56628d4408bf66ad30ff71fbd21bc33d9037935c411dff7bf73dd3f1070b","src/unix/newlib/no_align.rs":"e0743b2179495a9514bc3a4d1781e492878c4ec834ee0085d0891dd1712e82fb","src/unix/newlib/powerpc/mod.rs":"0202ffd57caf75b6afa2c9717750ffb96e375ac33df0ae9609a3f831be393b67","src/unix/no_align.rs":"c06e95373b9088266e0b14bba0954eef95f93fb2b01d951855e382d22de78e53","src/unix/redox/mod.rs":"033768cb273daf2c8090d97252c2de9dba6809e6a5d2457f5727d724807695db","src/unix/solarish/compat.rs":"b07a5bfac925eb012003a459ba6bddbd3bfa9c44b3394da2ac5a602e54beae9c","src/unix/solarish/illumos.rs":"1369fb55325914654ba3ad02410b75a40c8c0008feed9704c28520be1ee49641","src/unix/solarish/mod.rs":"52a31038984e68582347f4b28fd64c01e6308ff4293628818bb279605e7b28c6","src/unix/solarish/solaris.rs":"36abcfb46fab6e7151a0c1f555b419e1267b82893f6e84d5d260308ba8eeb0c5","src/unix/solarish/x86.rs":"e86e806df0caed72765040eaa2f3c883198d1aa91508540adf9b7008c77f522e","src/unix/solarish/x86_64.rs":"ec2b01f194eb8a6a27133c57681da195a949e03098f3ea1e847227a9c09ef5fc","src/unix/solarish/x86_common.rs":"ac869d9c3c95645c22460468391eb1982023c3a8e02b9e06a72e3aef3d5f1eac","src/vxworks/aarch64.rs":"98f0afdc511cd02557e506c21fed6737585490a1dce7a9d4941d08c437762b99","src/vxworks/arm.rs":"acb7968ce99fe3f4abdf39d98f8133d21a4fba435b8ef7084777cb181d788e88","src/vxworks/mod.rs":"aea3da66f2140f2a82dfc9c58f6e6531d2dd9c15ea696e0f95a0d4a2a187b5b6","src/vxworks/powerpc.rs":"acb7968ce99fe3f4abdf39d98f8133d21a4fba435b8ef7084777cb181d788e88","src/vxworks/powerpc64.rs":"98f0afdc511cd02557e506c21fed6737585490a1dce7a9d4941d08c437762b99","src/vxworks/x86.rs":"552f007f38317620b23889cb7c49d1d115841252439060122f52f434fbc6e5ba","src/vxworks/x86_64.rs":"018d92be3ad628a129eff9f2f5dfbc0883d8b8e5f2fa917b900a7f98ed6b514a","src/wasi.rs":"4fae202af0327d768ed9e1b586b75816cce14fe2dc16947d2f3d381f209a54c1","src/windows/gnu/align.rs":"b2c13ec1b9f3b39a75c452c80c951dff9d0215e31d77e883b4502afb31794647","src/windows/gnu/mod.rs":"3c8c7edb7cdf5d0c44af936db2a94869585c69dfabeef30571b4f4e38375767a","src/windows/mod.rs":"090dd8fcd951d18f1905bca96188783c2e3f1433484926ecdcda144237ecec0f","src/windows/msvc/mod.rs":"c068271e00fca6b62bc4bf44bcf142cfc38caeded9b6c4e01d1ceef3ccf986f4","tests/const_fn.rs":"cb75a1f0864f926aebe79118fc34d51a0d1ade2c20a394e7774c7e545f21f1f4"},"package":"68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c"} \ No newline at end of file diff --git a/bash-5.1/vendor/libc/CONTRIBUTING.md b/bash-5.1/vendor/libc/CONTRIBUTING.md index 5be6eb9..3315ed3 100644 --- a/bash-5.1/vendor/libc/CONTRIBUTING.md +++ b/bash-5.1/vendor/libc/CONTRIBUTING.md @@ -72,6 +72,10 @@ after a certain period. The steps are: If you're using it, please comment on #XXX"). 2. If we don't see any concerns for a while, do the change actually. +## Supported target policy + +When Rust removes a support for a target, the libc crate also may remove the support anytime. + ## Releasing your change to crates.io Now that you've done the amazing job of landing your new API or your new diff --git a/bash-5.1/vendor/libc/Cargo.toml b/bash-5.1/vendor/libc/Cargo.toml index 7983d02..cb7c004 100644 --- a/bash-5.1/vendor/libc/Cargo.toml +++ b/bash-5.1/vendor/libc/Cargo.toml @@ -11,7 +11,7 @@ [package] name = "libc" -version = "0.2.126" +version = "0.2.135" authors = ["The Rust Project Developers"] build = "build.rs" exclude = [ diff --git a/bash-5.1/vendor/libc/README.md b/bash-5.1/vendor/libc/README.md index a8a3afd..bc5ad18 100644 --- a/bash-5.1/vendor/libc/README.md +++ b/bash-5.1/vendor/libc/README.md @@ -35,13 +35,16 @@ libc = "0.2" This feature derives `Debug`, `Eq`, `Hash`, and `PartialEq`. * `const-extern-fn`: Changes some `extern fn`s into `const extern fn`s. - This feature requires a nightly rustc. + If you use Rust >= 1.62, this feature is implicitly enabled. + Otherwise it requires a nightly rustc. * **deprecated**: `use_std` is deprecated, and is equivalent to `std`. ## Rust version support -The minimum supported Rust toolchain version is **Rust 1.13.0** . APIs requiring +The minimum supported Rust toolchain version is currently **Rust 1.13.0**. +(libc does not currently have any policy regarding changes to the minimum +supported Rust version; such policy is a work in progress.) APIs requiring newer Rust features are only available on newer Rust toolchains: | Feature | Version | @@ -53,6 +56,7 @@ newer Rust features are only available on newer Rust toolchains: | `core::ffi::c_void` | 1.30.0 | | `repr(packed(N))` | 1.33.0 | | `cfg(target_vendor)` | 1.33.0 | +| `const-extern-fn` | 1.62.0 | ## Platform support diff --git a/bash-5.1/vendor/libc/build.rs b/bash-5.1/vendor/libc/build.rs index bc7b77f..0a43b2a 100644 --- a/bash-5.1/vendor/libc/build.rs +++ b/bash-5.1/vendor/libc/build.rs @@ -97,11 +97,18 @@ fn main() { println!("cargo:rustc-cfg=libc_thread_local"); } - if const_extern_fn_cargo_feature { - if !is_nightly || rustc_minor_ver < 40 { - panic!("const-extern-fn requires a nightly compiler >= 1.40") - } + // Rust >= 1.62.0 allows to use `const_extern_fn` for "Rust" and "C". + if rustc_minor_ver >= 62 { println!("cargo:rustc-cfg=libc_const_extern_fn"); + } else { + // Rust < 1.62.0 requires a crate feature and feature gate. + if const_extern_fn_cargo_feature { + if !is_nightly || rustc_minor_ver < 40 { + panic!("const-extern-fn requires a nightly compiler >= 1.40"); + } + println!("cargo:rustc-cfg=libc_const_extern_fn_unstable"); + println!("cargo:rustc-cfg=libc_const_extern_fn"); + } } } diff --git a/bash-5.1/vendor/libc/src/fuchsia/mod.rs b/bash-5.1/vendor/libc/src/fuchsia/mod.rs index 99b7791..eee82d0 100644 --- a/bash-5.1/vendor/libc/src/fuchsia/mod.rs +++ b/bash-5.1/vendor/libc/src/fuchsia/mod.rs @@ -877,6 +877,11 @@ s! { pub c_ispeed: ::speed_t, pub c_ospeed: ::speed_t, } + + pub struct in6_pktinfo { + pub ipi6_addr: ::in6_addr, + pub ipi6_ifindex: ::c_uint, + } } s_no_extra_traits! { @@ -1788,6 +1793,9 @@ pub const IPV6_MULTICAST_LOOP: ::c_int = 19; pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; pub const IPV6_V6ONLY: ::c_int = 26; +pub const IPV6_RECVPKTINFO: ::c_int = 49; +pub const IPV6_RECVTCLASS: ::c_int = 66; +pub const IPV6_TCLASS: ::c_int = 67; pub const TCP_NODELAY: ::c_int = 1; pub const TCP_MAXSEG: ::c_int = 2; @@ -2669,6 +2677,9 @@ pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; pub const PT_GNU_STACK: u32 = 0x6474e551; pub const PT_GNU_RELRO: u32 = 0x6474e552; +// Ethernet protocol IDs. +pub const ETH_P_IP: ::c_int = 0x0800; + pub const SFD_CLOEXEC: ::c_int = 0x080000; pub const NCCS: usize = 32; @@ -3224,17 +3235,6 @@ f! { minor as ::c_uint } - pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { - let major = major as ::dev_t; - let minor = minor as ::dev_t; - let mut dev = 0; - dev |= (major & 0x00000fff) << 8; - dev |= (major & 0xfffff000) << 32; - dev |= (minor & 0x000000ff) << 0; - dev |= (minor & 0xffffff00) << 12; - dev - } - pub fn CMSG_DATA(cmsg: *const cmsghdr) -> *mut c_uchar { cmsg.offset(1) as *mut c_uchar } @@ -3311,6 +3311,17 @@ safe_f! { pub {const} fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { (cmd << 8) | (type_ & 0x00ff) } + + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major & 0x00000fff) << 8; + dev |= (major & 0xfffff000) << 32; + dev |= (minor & 0x000000ff) << 0; + dev |= (minor & 0xffffff00) << 12; + dev + } } fn __CMSG_LEN(cmsg: *const cmsghdr) -> ::ssize_t { @@ -4201,6 +4212,11 @@ extern "C" { child: ::Option, ) -> ::c_int; pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + + pub fn setgrent(); + pub fn endgrent(); + pub fn getgrent() -> *mut ::group; + pub fn getgrouplist( user: *const ::c_char, group: ::gid_t, diff --git a/bash-5.1/vendor/libc/src/lib.rs b/bash-5.1/vendor/libc/src/lib.rs index d87d0d8..acda091 100644 --- a/bash-5.1/vendor/libc/src/lib.rs +++ b/bash-5.1/vendor/libc/src/lib.rs @@ -13,7 +13,9 @@ improper_ctypes, // This lint is renamed but we run CI for old stable rustc so should be here. redundant_semicolon, - redundant_semicolons + redundant_semicolons, + unused_macros, + unused_macro_rules, )] #![cfg_attr(libc_deny_warnings, deny(warnings))] // Attributes needed when building as part of the standard library @@ -24,11 +26,7 @@ #![deny(missing_copy_implementations, safe_packed_borrows)] #![cfg_attr(not(feature = "rustc-dep-of-std"), no_std)] #![cfg_attr(feature = "rustc-dep-of-std", no_core)] -#![cfg_attr( - feature = "rustc-dep-of-std", - feature(native_link_modifiers, native_link_modifiers_bundle) -)] -#![cfg_attr(libc_const_extern_fn, feature(const_extern_fn))] +#![cfg_attr(libc_const_extern_fn_unstable, feature(const_extern_fn))] #[macro_use] mod macros; diff --git a/bash-5.1/vendor/libc/src/macros.rs b/bash-5.1/vendor/libc/src/macros.rs index 603fa58..fd47370 100644 --- a/bash-5.1/vendor/libc/src/macros.rs +++ b/bash-5.1/vendor/libc/src/macros.rs @@ -6,7 +6,6 @@ /// /// This allows you to conveniently provide a long list #[cfg]'d blocks of code /// without having to rewrite each clause multiple times. -#[allow(unused_macros)] macro_rules! cfg_if { // match if/else chains with a final `else` ($( @@ -62,7 +61,6 @@ macro_rules! cfg_if { }; } -#[allow(unused_macros, unused_macro_rules)] macro_rules! s { ($($(#[$attr:meta])* pub $t:ident $i:ident { $($field:tt)* })*) => ($( s!(it: $(#[$attr])* pub $t $i { $($field)* }); @@ -87,7 +85,6 @@ macro_rules! s { ); } -#[allow(unused_macros)] macro_rules! s_no_extra_traits { ($($(#[$attr:meta])* pub $t:ident $i:ident { $($field:tt)* })*) => ($( s_no_extra_traits!(it: $(#[$attr])* pub $t $i { $($field)* }); @@ -123,7 +120,6 @@ macro_rules! s_no_extra_traits { ); } -#[allow(unused_macros)] macro_rules! e { ($($(#[$attr:meta])* pub enum $i:ident { $($field:tt)* })*) => ($( __item! { @@ -138,7 +134,6 @@ macro_rules! e { )*); } -#[allow(unused_macros)] macro_rules! s_paren { ($($(#[$attr:meta])* pub struct $i:ident ( $($field:tt)* ); )* ) => ($( __item! { @@ -182,7 +177,6 @@ macro_rules! s_paren { // 'f!' block cfg_if! { if #[cfg(libc_const_extern_fn)] { - #[allow(unused_macros)] macro_rules! f { ($($(#[$attr:meta])* pub $({$constness:ident})* fn $i:ident( $($arg:ident: $argty:ty),* @@ -198,7 +192,6 @@ cfg_if! { )*) } - #[allow(unused_macros)] macro_rules! safe_f { ($($(#[$attr:meta])* pub $({$constness:ident})* fn $i:ident( $($arg:ident: $argty:ty),* @@ -214,7 +207,6 @@ cfg_if! { )*) } - #[allow(unused_macros)] macro_rules! const_fn { ($($(#[$attr:meta])* $({$constness:ident})* fn $i:ident( $($arg:ident: $argty:ty),* @@ -231,7 +223,6 @@ cfg_if! { } } else { - #[allow(unused_macros)] macro_rules! f { ($($(#[$attr:meta])* pub $({$constness:ident})* fn $i:ident( $($arg:ident: $argty:ty),* @@ -247,7 +238,6 @@ cfg_if! { )*) } - #[allow(unused_macros)] macro_rules! safe_f { ($($(#[$attr:meta])* pub $({$constness:ident})* fn $i:ident( $($arg:ident: $argty:ty),* @@ -263,7 +253,6 @@ cfg_if! { )*) } - #[allow(unused_macros)] macro_rules! const_fn { ($($(#[$attr:meta])* $({$constness:ident})* fn $i:ident( $($arg:ident: $argty:ty),* @@ -281,14 +270,12 @@ cfg_if! { } } -#[allow(unused_macros)] macro_rules! __item { ($i:item) => { $i }; } -#[allow(unused_macros)] macro_rules! align_const { ($($(#[$attr:meta])* pub const $name:ident : $t1:ty @@ -308,7 +295,6 @@ macro_rules! align_const { } // This macro is used to deprecate items that should be accessed via the mach2 crate -#[allow(unused_macros)] macro_rules! deprecated_mach { (pub const $id:ident: $ty:ty = $expr:expr;) => { #[deprecated( @@ -342,7 +328,6 @@ macro_rules! deprecated_mach { } } -#[allow(unused_macros)] #[cfg(not(libc_ptr_addr_of))] macro_rules! ptr_addr_of { ($place:expr) => { @@ -350,7 +335,6 @@ macro_rules! ptr_addr_of { }; } -#[allow(unused_macros)] #[cfg(libc_ptr_addr_of)] macro_rules! ptr_addr_of { ($place:expr) => { diff --git a/bash-5.1/vendor/libc/src/unix/aix/mod.rs b/bash-5.1/vendor/libc/src/unix/aix/mod.rs new file mode 100644 index 0000000..3348ead --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/aix/mod.rs @@ -0,0 +1,2314 @@ +pub type c_char = i8; +pub type caddr_t = *mut ::c_char; +// FIXME: clockid_t must be c_long, but time.rs accepts only i32 +pub type clockid_t = ::c_int; +pub type blkcnt_t = ::c_long; +pub type clock_t = ::c_int; +pub type daddr_t = ::c_long; +pub type dev_t = ::c_ulong; +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type ino_t = ::c_ulong; +pub type key_t = ::c_long; +pub type mode_t = ::c_uint; +pub type nlink_t = ::c_short; +pub type rlim_t = ::c_ulong; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type time_t = ::c_long; +pub type timer_t = ::c_long; +pub type wchar_t = ::c_uint; +pub type nfds_t = ::c_int; +pub type projid_t = ::c_int; +pub type id_t = ::c_uint; +pub type blksize64_t = ::c_ulonglong; +pub type blkcnt64_t = ::c_ulonglong; + +pub type suseconds_t = ::c_int; +pub type useconds_t = ::c_uint; +pub type off_t = ::c_long; +pub type off64_t = ::c_longlong; + +pub type socklen_t = ::c_uint; +pub type sa_family_t = ::c_uchar; +pub type in_port_t = ::c_ushort; +pub type in_addr_t = ::c_uint; + +pub type signal_t = ::c_int; +pub type pthread_t = ::c_uint; +pub type pthread_key_t = ::c_uint; +pub type blksize_t = ::c_long; +pub type nl_item = ::c_int; +pub type mqd_t = ::c_int; +pub type shmatt_t = ::c_ulong; + +pub type sem_t = ::c_int; +pub type pollset_t = ::c_int; + +pub type pthread_rwlockattr_t = *mut ::c_void; +pub type pthread_condattr_t = *mut ::c_void; +pub type pthread_mutexattr_t = *mut ::c_void; +pub type pthread_attr_t = *mut ::c_void; + +e! { + pub enum uio_rw { + UIO_READ = 0, + UIO_WRITE, + UIO_READ_NO_MOVE, + UIO_WRITE_NO_MOVE, + UIO_PWRITE, + } +} + +s! { + pub struct fsid_t { + pub val: [::c_uint; 2], + } + + pub struct fsid64_t { + pub val: [::uint64_t; 2], + } + + pub struct timezone { + pub tz_minuteswest: ::c_int, + pub tz_dsttime: ::c_int, + } + + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + pub struct dirent { + pub d_offset: ::c_ulong, + pub d_ino: ::ino_t, + pub d_reclen: ::c_ushort, + pub d_namlen: ::c_ushort, + pub d_name: [::c_char; 256] + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_cc: [::cc_t; ::NCCS] + } + + pub struct flock64 { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_sysid: ::c_uint, + pub l_pid: ::pid_t, + pub l_vfs: ::c_int, + pub l_start: ::off64_t, + pub l_len: ::off64_t, + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: socklen_t, + pub msg_flags: ::c_int, + } + + pub struct statvfs64 { + pub f_bsize: ::blksize64_t, + pub f_frsize: ::blksize64_t, + pub f_blocks: ::blkcnt64_t, + pub f_bfree: ::blkcnt64_t, + pub f_bavail: ::blkcnt64_t, + pub f_files: ::blkcnt64_t, + pub f_ffree: ::blkcnt64_t, + pub f_favail: ::blkcnt64_t, + pub f_fsid: fsid64_t, + pub f_basetype: [::c_char; 16], + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + pub f_fstr: [::c_char; 32], + pub f_filler: [::c_ulong; 16] + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub left_parenthesis: *mut ::c_char, + pub right_parenthesis: *mut ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: ::c_ulong, + pub ai_canonname: *mut ::c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut addrinfo, + pub ai_eflags: ::c_int, + } + + pub struct in_addr { + pub s_addr: in_addr_t + } + + pub struct ip_mreq_source { + pub imr_multiaddr: in_addr, + pub imr_sourceaddr: in_addr, + pub imr_interface: in_addr, + } + + pub struct sockaddr { + pub sa_len: ::c_uchar, + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::c_uchar, + pub sdl_index: ::c_ushort, + pub sdl_type: ::c_uchar, + pub sdl_nlen: ::c_uchar, + pub sdl_alen: ::c_uchar, + pub sdl_slen: ::c_uchar, + pub sdl_data: [::c_char; 120], + } + + pub struct sockaddr_in { + pub sin_len: ::c_uchar, + pub sin_family: sa_family_t, + pub sin_port: in_port_t, + pub sin_addr: in_addr, + pub sin_zero: [::c_char; 8] + } + + pub struct sockaddr_in6 { + pub sin6_len: ::c_uchar, + pub sin6_family: ::c_uchar, + pub sin6_port: ::uint16_t, + pub sin6_flowinfo: ::uint32_t, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: ::uint32_t + } + + pub struct sockaddr_storage { + pub __ss_len: ::c_uchar, + pub ss_family: sa_family_t, + __ss_pad1: [::c_char; 6], + __ss_align: ::int64_t, + __ss_pad2: [::c_char; 1265], + } + + pub struct sockaddr_un { + pub sun_len: ::c_uchar, + pub sun_family: sa_family_t, + pub sun_path: [::c_char; 1023] + } + + pub struct st_timespec { + pub tv_sec: ::time_t, + pub tv_nsec: ::c_int, + } + + pub struct statfs64 { + pub f_version: ::c_int, + pub f_type: ::c_int, + pub f_bsize: blksize64_t, + pub f_blocks: blkcnt64_t, + pub f_bfree: blkcnt64_t, + pub f_bavail: blkcnt64_t, + pub f_files: ::uint64_t, + pub f_ffree: ::uint64_t, + pub f_fsid: fsid64_t, + pub f_vfstype: ::c_int, + pub f_fsize: blksize64_t, + pub f_vfsnumber: ::c_int, + pub f_vfsoff: ::c_int, + pub f_vfslen: ::c_int, + pub f_vfsvers: ::c_int, + pub f_fname: [::c_char; 32], + pub f_fpack: [::c_char; 32], + pub f_name_max: ::c_int, + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char + } + + pub struct utsname { + pub sysname: [::c_char; 32], + pub nodename: [::c_char; 32], + pub release: [::c_char; 32], + pub version: [::c_char; 32], + pub machine: [::c_char; 32], + } + + pub struct xutsname { + pub nid: ::c_uint, + pub reserved: ::c_int, + pub longnid: ::c_ulonglong, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct sigevent { + pub sigev_value: ::sigval, + pub sigev_signo: ::c_int, + pub sigev_notify: ::c_int, + pub sigev_notify_function: extern fn(val: sigval), + pub sigev_notify_attributes: *mut pthread_attr_t, + } + + // Should be union with another 'sival_int' + pub struct sigval64 { + pub sival_ptr: ::c_ulonglong, + } + + pub struct sigevent64 { + pub sigev_value: sigval64, + pub sigev_signo: ::c_int, + pub sigev_notify: ::c_int, + pub sigev_notify_function: ::c_ulonglong, + pub sigev_notify_attributes: ::c_ulonglong, + } + + pub struct osigevent { + pub sevt_value: *mut ::c_void, + pub sevt_signo: signal_t, + } + + pub struct poll_ctl { + pub cmd: ::c_short, + pub events: ::c_short, + pub fd: ::c_int, + } + + pub struct sf_parms { + pub header_data: *mut ::c_void, + pub header_length: ::c_uint, + pub file_descriptor: ::c_int, + pub file_size: ::uint64_t, + pub file_offset: ::uint64_t, + pub file_bytes: ::int64_t, + pub trailer_data: *mut ::c_void, + pub trailer_length: ::c_uint, + pub bytes_sent: ::uint64_t, + } +} + +s_no_extra_traits! { + #[cfg(libc_union)] + pub union __sigaction_sa_union { + pub __su_handler: extern fn(c: ::c_int), + pub __su_sigaction: extern fn(c: ::c_int, info: *mut siginfo_t, ptr: *mut ::c_void), + } + + pub struct sigaction { + #[cfg(libc_union)] + pub sa_union: __sigaction_sa_union, + pub sa_mask: sigset_t, + pub sa_flags: ::c_int, + } + + #[cfg(libc_union)] + pub union __poll_ctl_ext_u { + pub addr: *mut ::c_void, + pub data32: u32, + pub data: u64, + } + + pub struct poll_ctl_ext { + pub version: u8, + pub command: u8, + pub events: ::c_short, + pub fd: ::c_int, + #[cfg(libc_union)] + pub u: __poll_ctl_ext_u, + pub reversed64: [u64; 6], + } +} + +cfg_if! { + if #[cfg(feature = "extra_traits")] { + #[cfg(libc_union)] + impl PartialEq for __sigaction_sa_union { + fn eq(&self, other: &__sigaction_sa_union) -> bool { + unsafe { + self.__su_handler == other.__su_handler + && self.__su_sigaction == other.__su_sigaction + } + } + } + #[cfg(libc_union)] + impl Eq for __sigaction_sa_union {} + #[cfg(libc_union)] + impl ::fmt::Debug for __sigaction_sa_union { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("__sigaction_sa_union") + .field("__su_handler", unsafe { &self.__su_handler }) + .field("__su_sigaction", unsafe { &self.__su_sigaction }) + .finish() + } + } + #[cfg(libc_union)] + impl ::hash::Hash for __sigaction_sa_union { + fn hash(&self, state: &mut H) { + unsafe { + self.__su_handler.hash(state); + self.__su_sigaction.hash(state); + } + } + } + + impl PartialEq for sigaction { + fn eq(&self, other: &sigaction) -> bool { + #[cfg(libc_union)] + let union_eq = self.sa_union == other.sa_union; + #[cfg(not(libc_union))] + let union_eq = true; + self.sa_mask == other.sa_mask + && self.sa_flags == other.sa_flags + && union_eq + } + } + impl Eq for sigaction {} + impl ::fmt::Debug for sigaction { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("sigaction"); + #[cfg(libc_union)] + struct_formatter.field("sa_union", &self.sa_union); + struct_formatter.field("sa_mask", &self.sa_mask); + struct_formatter.field("sa_flags", &self.sa_flags); + struct_formatter.finish() + } + } + impl ::hash::Hash for sigaction { + fn hash(&self, state: &mut H) { + #[cfg(libc_union)] + self.sa_union.hash(state); + self.sa_mask.hash(state); + self.sa_flags.hash(state); + } + } + + #[cfg(libc_union)] + impl PartialEq for __poll_ctl_ext_u { + fn eq(&self, other: &__poll_ctl_ext_u) -> bool { + unsafe { + self.addr == other.addr + && self.data32 == other.data32 + && self.data == other.data + } + } + } + #[cfg(libc_union)] + impl Eq for __poll_ctl_ext_u {} + #[cfg(libc_union)] + impl ::fmt::Debug for __poll_ctl_ext_u { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("__poll_ctl_ext_u") + .field("addr", unsafe { &self.addr }) + .field("data32", unsafe { &self.data32 }) + .field("data", unsafe { &self.data }) + .finish() + } + } + #[cfg(libc_union)] + impl ::hash::Hash for __poll_ctl_ext_u { + fn hash(&self, state: &mut H) { + unsafe { + self.addr.hash(state); + self.data32.hash(state); + self.data.hash(state); + } + } + } + + impl PartialEq for poll_ctl_ext { + fn eq(&self, other: &poll_ctl_ext) -> bool { + #[cfg(libc_union)] + let union_eq = self.u == other.u; + #[cfg(not(libc_union))] + let union_eq = true; + self.version == other.version + && self.command == other.command + && self.events == other.events + && self.fd == other.fd + && self.reversed64 == other.reversed64 + && union_eq + } + } + impl Eq for poll_ctl_ext {} + impl ::fmt::Debug for poll_ctl_ext { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("poll_ctl_ext"); + struct_formatter.field("version", &self.version); + struct_formatter.field("command", &self.command); + struct_formatter.field("events", &self.events); + struct_formatter.field("fd", &self.fd); + #[cfg(libc_union)] + struct_formatter.field("u", &self.u); + struct_formatter.field("reversed64", &self.reversed64); + struct_formatter.finish() + } + } + impl ::hash::Hash for poll_ctl_ext { + fn hash(&self, state: &mut H) { + self.version.hash(state); + self.command.hash(state); + self.events.hash(state); + self.fd.hash(state); + #[cfg(libc_union)] + self.u.hash(state); + self.reversed64.hash(state); + } + } + } +} + +// dlfcn.h +pub const RTLD_LAZY: ::c_int = 0x4; +pub const RTLD_NOW: ::c_int = 0x2; +pub const RTLD_GLOBAL: ::c_int = 0x10000; +pub const RTLD_LOCAL: ::c_int = 0x80000; +pub const RTLD_DEFAULT: *mut ::c_void = -1isize as *mut ::c_void; + +// fcntl.h +pub const O_RDONLY: ::c_int = 0x0; +pub const O_WRONLY: ::c_int = 0x1; +pub const O_RDWR: ::c_int = 0x2; +pub const O_NDELAY: ::c_int = 0x8000; +pub const O_APPEND: ::c_int = 0x8; +pub const O_DSYNC: ::c_int = 0x400000; +pub const O_CREAT: ::c_int = 0x100; +pub const O_EXCL: ::c_int = 0x400; +pub const O_NOCTTY: ::c_int = 0x800; +pub const O_TRUNC: ::c_int = 0x200; +pub const O_NOFOLLOW: ::c_int = 0x1000000; +pub const O_DIRECTORY: ::c_int = 0x80000; +pub const O_SEARCH: ::c_int = 0x20; +pub const O_EXEC: ::c_int = 0x20; +pub const O_CLOEXEC: ::c_int = 0x800000; +pub const O_ACCMODE: ::c_int = O_RDONLY | O_WRONLY | O_RDWR; +pub const O_DIRECT: ::c_int = 0x8000000; +pub const F_DUPFD_CLOEXEC: ::c_int = 16; +pub const F_GETLK64: ::c_int = 11; +pub const F_SETLK64: ::c_int = 12; +pub const F_SETLKW64: ::c_int = 13; +pub const F_DUP2FD: ::c_int = 14; +pub const F_TSTLK: ::c_int = 15; +pub const F_GETLK: ::c_int = F_GETLK64; +pub const F_SETLK: ::c_int = F_SETLK64; +pub const F_SETLKW: ::c_int = F_SETLKW64; +pub const F_GETOWN: ::c_int = 8; +pub const F_SETOWN: ::c_int = 9; +pub const AT_FDCWD: ::c_int = -2; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 1; +pub const AT_SYMLINK_FOLLOW: ::c_int = 2; +pub const AT_REMOVEDIR: ::c_int = 1; +pub const AT_EACCESS: ::c_int = 1; +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; +pub const O_SYNC: ::c_int = 16; +pub const O_NONBLOCK: ::c_int = 4; +pub const POSIX_FADV_NORMAL: ::c_int = 1; +pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_FADV_RANDOM: ::c_int = 3; +pub const POSIX_FADV_WILLNEED: ::c_int = 4; +pub const POSIX_FADV_DONTNEED: ::c_int = 5; +pub const POSIX_FADV_NOREUSE: ::c_int = 6; + +// glob.h +pub const GLOB_APPEND: ::c_int = 0x1; +pub const GLOB_DOOFFS: ::c_int = 0x2; +pub const GLOB_ERR: ::c_int = 0x4; +pub const GLOB_MARK: ::c_int = 0x8; +pub const GLOB_NOCHECK: ::c_int = 0x10; +pub const GLOB_NOSORT: ::c_int = 0x20; +pub const GLOB_NOESCAPE: ::c_int = 0x80; +pub const GLOB_NOSPACE: ::c_int = 0x2000; +pub const GLOB_ABORTED: ::c_int = 0x1000; +pub const GLOB_NOMATCH: ::c_int = 0x4000; + +// langinfo.h +pub const DAY_1: ::nl_item = 13; +pub const DAY_2: ::nl_item = 14; +pub const DAY_3: ::nl_item = 15; +pub const DAY_4: ::nl_item = 16; +pub const DAY_5: ::nl_item = 17; +pub const DAY_6: ::nl_item = 18; +pub const DAY_7: ::nl_item = 19; +pub const ABDAY_1: ::nl_item = 6; +pub const ABDAY_2: ::nl_item = 7; +pub const ABDAY_3: ::nl_item = 8; +pub const ABDAY_4: ::nl_item = 9; +pub const ABDAY_5: ::nl_item = 10; +pub const ABDAY_6: ::nl_item = 11; +pub const ABDAY_7: ::nl_item = 12; +pub const MON_1: ::nl_item = 32; +pub const MON_2: ::nl_item = 33; +pub const MON_3: ::nl_item = 34; +pub const MON_4: ::nl_item = 35; +pub const MON_5: ::nl_item = 36; +pub const MON_6: ::nl_item = 37; +pub const MON_7: ::nl_item = 38; +pub const MON_8: ::nl_item = 39; +pub const MON_9: ::nl_item = 40; +pub const MON_10: ::nl_item = 41; +pub const MON_11: ::nl_item = 42; +pub const MON_12: ::nl_item = 43; +pub const ABMON_1: ::nl_item = 20; +pub const ABMON_2: ::nl_item = 21; +pub const ABMON_3: ::nl_item = 22; +pub const ABMON_4: ::nl_item = 23; +pub const ABMON_5: ::nl_item = 24; +pub const ABMON_6: ::nl_item = 25; +pub const ABMON_7: ::nl_item = 26; +pub const ABMON_8: ::nl_item = 27; +pub const ABMON_9: ::nl_item = 28; +pub const ABMON_10: ::nl_item = 29; +pub const ABMON_11: ::nl_item = 30; +pub const ABMON_12: ::nl_item = 31; +pub const RADIXCHAR: ::nl_item = 44; +pub const THOUSEP: ::nl_item = 45; +pub const YESSTR: ::nl_item = 46; +pub const NOSTR: ::nl_item = 47; +pub const CRNCYSTR: ::nl_item = 48; +pub const D_T_FMT: ::nl_item = 1; +pub const D_FMT: ::nl_item = 2; +pub const T_FMT: ::nl_item = 3; +pub const AM_STR: ::nl_item = 4; +pub const PM_STR: ::nl_item = 5; +pub const CODESET: ::nl_item = 49; +pub const T_FMT_AMPM: ::nl_item = 55; +pub const ERA: ::nl_item = 56; +pub const ERA_D_FMT: ::nl_item = 57; +pub const ERA_D_T_FMT: ::nl_item = 58; +pub const ERA_T_FMT: ::nl_item = 59; +pub const ALT_DIGITS: ::nl_item = 60; +pub const YESEXPR: ::nl_item = 61; +pub const NOEXPR: ::nl_item = 62; + +// locale.h +pub const LC_CTYPE: ::c_int = 1; +pub const LC_NUMERIC: ::c_int = 3; +pub const LC_TIME: ::c_int = 4; +pub const LC_COLLATE: ::c_int = 0; +pub const LC_MONETARY: ::c_int = 2; +pub const LC_MESSAGES: ::c_int = 4; +pub const LC_ALL: ::c_int = -1; +pub const LC_CTYPE_MASK: ::c_int = 2; +pub const LC_NUMERIC_MASK: ::c_int = 16; +pub const LC_TIME_MASK: ::c_int = 32; +pub const LC_COLLATE_MASK: ::c_int = 1; +pub const LC_MONETARY_MASK: ::c_int = 8; +pub const LC_MESSAGES_MASK: ::c_int = 4; +pub const LC_ALL_MASK: ::c_int = LC_CTYPE_MASK + | LC_NUMERIC_MASK + | LC_TIME_MASK + | LC_COLLATE_MASK + | LC_MONETARY_MASK + | LC_MESSAGES_MASK; + +// netdb.h +pub const NI_MAXHOST: ::socklen_t = 1025; +pub const NI_MAXSERV: ::socklen_t = 32; +pub const NI_NOFQDN: ::socklen_t = 0x1; +pub const NI_NUMERICHOST: ::socklen_t = 0x2; +pub const NI_NAMEREQD: ::socklen_t = 0x4; +pub const NI_NUMERICSERV: ::socklen_t = 0x8; +pub const NI_DGRAM: ::socklen_t = 0x10; +pub const NI_NUMERICSCOPE: ::socklen_t = 0x40; +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 13; +pub const AI_CANONNAME: ::c_int = 0x01; +pub const AI_PASSIVE: ::c_int = 0x02; +pub const AI_NUMERICHOST: ::c_int = 0x04; +pub const AI_ADDRCONFIG: ::c_int = 0x08; +pub const AI_V4MAPPED: ::c_int = 0x10; +pub const AI_ALL: ::c_int = 0x20; +pub const AI_NUMERICSERV: ::c_int = 0x40; +pub const AI_EXTFLAGS: ::c_int = 0x80; +pub const AI_DEFAULT: ::c_int = AI_V4MAPPED | AI_ADDRCONFIG; + +// net/bpf.h +pub const DLT_NULL: ::c_int = 0x18; +pub const DLT_EN10MB: ::c_int = 0x6; +pub const DLT_EN3MB: ::c_int = 0x1a; +pub const DLT_AX25: ::c_int = 0x5; +pub const DLT_PRONET: ::c_int = 0xd; +pub const DLT_IEEE802: ::c_int = 0x7; +pub const DLT_ARCNET: ::c_int = 0x23; +pub const DLT_SLIP: ::c_int = 0x1c; +pub const DLT_PPP: ::c_int = 0x17; +pub const DLT_FDDI: ::c_int = 0xf; +pub const DLT_ATM: ::c_int = 0x25; +pub const DLT_IPOIB: ::c_int = 0xc7; +pub const BIOCSETF: ::c_ulong = 0x80104267; +pub const BIOCGRTIMEOUT: ::c_ulong = 0x4010426e; +pub const BIOCGBLEN: ::c_int = 0x40044266; +pub const BIOCSBLEN: ::c_int = 0xc0044266; +pub const BIOCFLUSH: ::c_int = 0x20004268; +pub const BIOCPROMISC: ::c_int = 0x20004269; +pub const BIOCGDLT: ::c_int = 0x4004426a; +pub const BIOCSRTIMEOUT: ::c_int = 0x8010426d; +pub const BIOCGSTATS: ::c_int = 0x4008426f; +pub const BIOCIMMEDIATE: ::c_int = 0x80044270; +pub const BIOCVERSION: ::c_int = 0x40044271; +pub const BIOCSDEVNO: ::c_int = 0x20004272; + +// net/if.h +pub const IFF_UP: ::c_int = 0x1; +pub const IFF_BROADCAST: ::c_int = 0x2; +pub const IFF_DEBUG: ::c_int = 0x4; +pub const IFF_LOOPBACK: ::c_int = 0x8; +pub const IFF_POINTOPOINT: ::c_int = 0x10; +pub const IFF_NOTRAILERS: ::c_int = 0x20; +pub const IFF_RUNNING: ::c_int = 0x40; +pub const IFF_NOARP: ::c_int = 0x80; +pub const IFF_PROMISC: ::c_int = 0x100; +pub const IFF_ALLMULTI: ::c_int = 0x200; +pub const IFF_MULTICAST: ::c_int = 0x80000; + +// net/route.h +pub const RTM_ADD: ::c_int = 0x1; +pub const RTM_DELETE: ::c_int = 0x2; +pub const RTM_CHANGE: ::c_int = 0x3; +pub const RTM_GET: ::c_int = 0x4; +pub const RTM_LOSING: ::c_int = 0x5; +pub const RTM_REDIRECT: ::c_int = 0x6; +pub const RTM_MISS: ::c_int = 0x7; +pub const RTM_LOCK: ::c_int = 0x8; +pub const RTM_OLDADD: ::c_int = 0x9; +pub const RTM_OLDDEL: ::c_int = 0xa; +pub const RTM_RESOLVE: ::c_int = 0xb; +pub const RTM_NEWADDR: ::c_int = 0xc; +pub const RTM_DELADDR: ::c_int = 0xd; +pub const RTM_IFINFO: ::c_int = 0xe; +pub const RTM_EXPIRE: ::c_int = 0xf; +pub const RTM_RTLOST: ::c_int = 0x10; +pub const RTM_GETNEXT: ::c_int = 0x11; +pub const RTM_SAMEADDR: ::c_int = 0x12; +pub const RTM_SET: ::c_int = 0x13; +pub const RTV_MTU: ::c_int = 0x1; +pub const RTV_HOPCOUNT: ::c_int = 0x2; +pub const RTV_EXPIRE: ::c_int = 0x4; +pub const RTV_RPIPE: ::c_int = 0x8; +pub const RTV_SPIPE: ::c_int = 0x10; +pub const RTV_SSTHRESH: ::c_int = 0x20; +pub const RTV_RTT: ::c_int = 0x40; +pub const RTV_RTTVAR: ::c_int = 0x80; +pub const RTA_DST: ::c_int = 0x1; +pub const RTA_GATEWAY: ::c_int = 0x2; +pub const RTA_NETMASK: ::c_int = 0x4; +pub const RTA_GENMASK: ::c_int = 0x8; +pub const RTA_IFP: ::c_int = 0x10; +pub const RTA_IFA: ::c_int = 0x20; +pub const RTA_AUTHOR: ::c_int = 0x40; +pub const RTA_BRD: ::c_int = 0x80; +pub const RTA_DOWNSTREAM: ::c_int = 0x100; +pub const RTAX_DST: ::c_int = 0; +pub const RTAX_GATEWAY: ::c_int = 1; +pub const RTAX_NETMASK: ::c_int = 2; +pub const RTAX_GENMASK: ::c_int = 3; +pub const RTAX_IFP: ::c_int = 4; +pub const RTAX_IFA: ::c_int = 5; +pub const RTAX_AUTHOR: ::c_int = 6; +pub const RTAX_BRD: ::c_int = 7; +pub const RTAX_MAX: ::c_int = 8; +pub const RTF_UP: ::c_int = 0x1; +pub const RTF_GATEWAY: ::c_int = 0x2; +pub const RTF_HOST: ::c_int = 0x4; +pub const RTF_REJECT: ::c_int = 0x8; +pub const RTF_DYNAMIC: ::c_int = 0x10; +pub const RTF_MODIFIED: ::c_int = 0x20; +pub const RTF_DONE: ::c_int = 0x40; +pub const RTF_MASK: ::c_int = 0x80; +pub const RTF_CLONING: ::c_int = 0x100; +pub const RTF_XRESOLVE: ::c_int = 0x200; +pub const RTF_LLINFO: ::c_int = 0x400; +pub const RTF_STATIC: ::c_int = 0x800; +pub const RTF_BLACKHOLE: ::c_int = 0x1000; +pub const RTF_BUL: ::c_int = 0x2000; +pub const RTF_PROTO2: ::c_int = 0x4000; +pub const RTF_PROTO1: ::c_int = 0x8000; +pub const RTF_CLONE: ::c_int = 0x10000; +pub const RTF_CLONED: ::c_int = 0x20000; +pub const RTF_PROTO3: ::c_int = 0x40000; +pub const RTF_BCE: ::c_int = 0x80000; +pub const RTF_PINNED: ::c_int = 0x100000; +pub const RTF_LOCAL: ::c_int = 0x200000; +pub const RTF_BROADCAST: ::c_int = 0x400000; +pub const RTF_MULTICAST: ::c_int = 0x800000; +pub const RTF_ACTIVE_DGD: ::c_int = 0x1000000; +pub const RTF_STOPSRCH: ::c_int = 0x2000000; +pub const RTF_FREE_IN_PROG: ::c_int = 0x4000000; +pub const RTF_PERMANENT6: ::c_int = 0x8000000; +pub const RTF_UNREACHABLE: ::c_int = 0x10000000; +pub const RTF_CACHED: ::c_int = 0x20000000; +pub const RTF_SMALLMTU: ::c_int = 0x40000; + +// netinet/in.h +pub const IPPROTO_HOPOPTS: ::c_int = 0; +pub const IPPROTO_IGMP: ::c_int = 2; +pub const IPPROTO_GGP: ::c_int = 3; +pub const IPPROTO_IPIP: ::c_int = 4; +pub const IPPROTO_EGP: ::c_int = 8; +pub const IPPROTO_PUP: ::c_int = 12; +pub const IPPROTO_IDP: ::c_int = 22; +pub const IPPROTO_TP: ::c_int = 29; +pub const IPPROTO_ROUTING: ::c_int = 43; +pub const IPPROTO_FRAGMENT: ::c_int = 44; +pub const IPPROTO_QOS: ::c_int = 45; +pub const IPPROTO_RSVP: ::c_int = 46; +pub const IPPROTO_GRE: ::c_int = 47; +pub const IPPROTO_ESP: ::c_int = 50; +pub const IPPROTO_AH: ::c_int = 51; +pub const IPPROTO_NONE: ::c_int = 59; +pub const IPPROTO_DSTOPTS: ::c_int = 60; +pub const IPPROTO_LOCAL: ::c_int = 63; +pub const IPPROTO_EON: ::c_int = 80; +pub const IPPROTO_BIP: ::c_int = 0x53; +pub const IPPROTO_SCTP: ::c_int = 132; +pub const IPPROTO_MH: ::c_int = 135; +pub const IPPROTO_GIF: ::c_int = 140; +pub const IPPROTO_RAW: ::c_int = 255; +pub const IPPROTO_MAX: ::c_int = 256; +pub const IP_OPTIONS: ::c_int = 1; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_TOS: ::c_int = 3; +pub const IP_TTL: ::c_int = 4; +pub const IP_UNICAST_HOPS: ::c_int = 4; +pub const IP_RECVOPTS: ::c_int = 5; +pub const IP_RECVRETOPTS: ::c_int = 6; +pub const IP_RECVDSTADDR: ::c_int = 7; +pub const IP_RETOPTS: ::c_int = 8; +pub const IP_MULTICAST_IF: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_MULTICAST_HOPS: ::c_int = 10; +pub const IP_MULTICAST_LOOP: ::c_int = 11; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; +pub const IP_RECVMACHDR: ::c_int = 14; +pub const IP_RECVIFINFO: ::c_int = 15; +pub const IP_BROADCAST_IF: ::c_int = 16; +pub const IP_DHCPMODE: ::c_int = 17; +pub const IP_RECVIF: ::c_int = 20; +pub const IP_ADDRFORM: ::c_int = 22; +pub const IP_DONTFRAG: ::c_int = 25; +pub const IP_FINDPMTU: ::c_int = 26; +pub const IP_PMTUAGE: ::c_int = 27; +pub const IP_RECVINTERFACE: ::c_int = 32; +pub const IP_RECVTTL: ::c_int = 34; +pub const IP_BLOCK_SOURCE: ::c_int = 58; +pub const IP_UNBLOCK_SOURCE: ::c_int = 59; +pub const IP_ADD_SOURCE_MEMBERSHIP: ::c_int = 60; +pub const IP_DROP_SOURCE_MEMBERSHIP: ::c_int = 61; +pub const IP_DEFAULT_MULTICAST_TTL: ::c_int = 1; +pub const IP_DEFAULT_MULTICAST_LOOP: ::c_int = 1; +pub const IP_INC_MEMBERSHIPS: ::c_int = 20; +pub const IP_INIT_MEMBERSHIP: ::c_int = 20; +pub const IPV6_UNICAST_HOPS: ::c_int = IP_TTL; +pub const IPV6_MULTICAST_IF: ::c_int = IP_MULTICAST_IF; +pub const IPV6_MULTICAST_HOPS: ::c_int = IP_MULTICAST_TTL; +pub const IPV6_MULTICAST_LOOP: ::c_int = IP_MULTICAST_LOOP; +pub const IPV6_RECVPKTINFO: ::c_int = 35; +pub const IPV6_V6ONLY: ::c_int = 37; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = IP_ADD_MEMBERSHIP; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = IP_DROP_MEMBERSHIP; +pub const IPV6_JOIN_GROUP: ::c_int = IP_ADD_MEMBERSHIP; +pub const IPV6_LEAVE_GROUP: ::c_int = IP_DROP_MEMBERSHIP; + +// netinet/tcp.h +pub const TCP_NODELAY: ::c_int = 0x1; +pub const TCP_MAXSEG: ::c_int = 0x2; +pub const TCP_RFC1323: ::c_int = 0x4; +pub const TCP_KEEPALIVE: ::c_int = 0x8; +pub const TCP_KEEPIDLE: ::c_int = 0x11; +pub const TCP_KEEPINTVL: ::c_int = 0x12; +pub const TCP_KEEPCNT: ::c_int = 0x13; +pub const TCP_NODELAYACK: ::c_int = 0x14; + +// pthread.h +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 0; +pub const PTHREAD_PROCESS_PRIVATE: ::c_ushort = 1; +pub const PTHREAD_STACK_MIN: ::size_t = PAGESIZE as ::size_t * 4; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 5; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 3; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 4; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; + +// spawn.h +pub const POSIX_SPAWN_SETPGROUP: ::c_int = 0x1; +pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x2; +pub const POSIX_SPAWN_SETSIGDEF: ::c_int = 0x4; +pub const POSIX_SPAWN_SETSCHEDULER: ::c_int = 0x8; +pub const POSIX_SPAWN_SETSCHEDPARAM: ::c_int = 0x10; +pub const POSIX_SPAWN_RESETIDS: ::c_int = 0x20; +pub const POSIX_SPAWN_FORK_HANDLERS: ::c_int = 0x1000; + +// stdio.h +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0o000; +pub const _IONBF: ::c_int = 0o004; +pub const _IOLBF: ::c_int = 0o100; +pub const BUFSIZ: ::c_uint = 4096; +pub const FOPEN_MAX: ::c_uint = 32767; +pub const FILENAME_MAX: ::c_uint = 255; +pub const L_tmpnam: ::c_uint = 21; +pub const TMP_MAX: ::c_uint = 16384; + +// stdlib.h +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 32767; + +// sys/access.h +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; + +// sys/aio.h +pub const LIO_NOP: ::c_int = 0; +pub const LIO_READ: ::c_int = 1; +pub const LIO_WRITE: ::c_int = 2; + +// sys/errno.h +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const ECHRNG: ::c_int = 37; +pub const EL2NSYNC: ::c_int = 38; +pub const EL3HLT: ::c_int = 39; +pub const EL3RST: ::c_int = 40; +pub const ELNRNG: ::c_int = 41; +pub const EUNATCH: ::c_int = 42; +pub const ENOCSI: ::c_int = 43; +pub const EL2HLT: ::c_int = 44; +pub const EDEADLK: ::c_int = 45; +pub const ENOLCK: ::c_int = 49; +pub const ECANCELED: ::c_int = 117; +pub const ENOTSUP: ::c_int = 124; +pub const EPROCLIM: ::c_int = 83; +pub const EDQUOT: ::c_int = 88; +pub const EOWNERDEAD: ::c_int = 95; +pub const ENOTRECOVERABLE: ::c_int = 94; +pub const ENOSTR: ::c_int = 123; +pub const ENODATA: ::c_int = 122; +pub const ETIME: ::c_int = 119; +pub const ENOSR: ::c_int = 118; +pub const EREMOTE: ::c_int = 93; +pub const ENOLINK: ::c_int = 126; +pub const EPROTO: ::c_int = 121; +pub const EMULTIHOP: ::c_int = 125; +pub const EBADMSG: ::c_int = 120; +pub const ENAMETOOLONG: ::c_int = 86; +pub const EOVERFLOW: ::c_int = 127; +pub const EILSEQ: ::c_int = 116; +pub const ENOSYS: ::c_int = 109; +pub const ELOOP: ::c_int = 85; +pub const ERESTART: ::c_int = 82; +pub const ENOTEMPTY: ::c_int = 87; +pub const EUSERS: ::c_int = 84; +pub const ENOTSOCK: ::c_int = 57; +pub const EDESTADDRREQ: ::c_int = 58; +pub const EMSGSIZE: ::c_int = 59; +pub const EPROTOTYPE: ::c_int = 60; +pub const ENOPROTOOPT: ::c_int = 61; +pub const EPROTONOSUPPORT: ::c_int = 62; +pub const ESOCKTNOSUPPORT: ::c_int = 63; +pub const EOPNOTSUPP: ::c_int = 64; +pub const EPFNOSUPPORT: ::c_int = 65; +pub const EAFNOSUPPORT: ::c_int = 66; +pub const EADDRINUSE: ::c_int = 67; +pub const EADDRNOTAVAIL: ::c_int = 68; +pub const ENETDOWN: ::c_int = 69; +pub const ENETUNREACH: ::c_int = 70; +pub const ENETRESET: ::c_int = 71; +pub const ECONNABORTED: ::c_int = 72; +pub const ECONNRESET: ::c_int = 73; +pub const ENOBUFS: ::c_int = 74; +pub const EISCONN: ::c_int = 75; +pub const ENOTCONN: ::c_int = 76; +pub const ESHUTDOWN: ::c_int = 77; +pub const ETOOMANYREFS: ::c_int = 115; +pub const ETIMEDOUT: ::c_int = 78; +pub const ECONNREFUSED: ::c_int = 79; +pub const EHOSTDOWN: ::c_int = 80; +pub const EHOSTUNREACH: ::c_int = 81; +pub const EWOULDBLOCK: ::c_int = EAGAIN; +pub const EALREADY: ::c_int = 56; +pub const EINPROGRESS: ::c_int = 55; +pub const ESTALE: ::c_int = 52; + +// sys/dr.h +pub const LPAR_INFO_FORMAT1: ::c_int = 1; +pub const LPAR_INFO_FORMAT2: ::c_int = 2; +pub const WPAR_INFO_FORMAT: ::c_int = 3; +pub const PROC_MODULE_INFO: ::c_int = 4; +pub const NUM_PROC_MODULE_TYPES: ::c_int = 5; +pub const LPAR_INFO_VRME_NUM_POOLS: ::c_int = 6; +pub const LPAR_INFO_VRME_POOLS: ::c_int = 7; +pub const LPAR_INFO_VRME_LPAR: ::c_int = 8; +pub const LPAR_INFO_VRME_RESET_HWMARKS: ::c_int = 9; +pub const LPAR_INFO_VRME_ALLOW_DESIRED: ::c_int = 10; +pub const EMTP_INFO_FORMAT: ::c_int = 11; +pub const LPAR_INFO_LPM_CAPABILITY: ::c_int = 12; +pub const ENERGYSCALE_INFO: ::c_int = 13; + +// sys/file.h +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +// sys/flock.h +pub const F_RDLCK: ::c_short = 0o01; +pub const F_WRLCK: ::c_short = 0o02; +pub const F_UNLCK: ::c_short = 0o03; + +// sys/fs/quota_common.h +pub const Q_QUOTAON: ::c_int = 0x100; +pub const Q_QUOTAOFF: ::c_int = 0x200; +pub const Q_SETUSE: ::c_int = 0x500; +pub const Q_SYNC: ::c_int = 0x600; +pub const Q_GETQUOTA: ::c_int = 0x300; +pub const Q_SETQLIM: ::c_int = 0x400; +pub const Q_SETQUOTA: ::c_int = 0x400; + +// sys/ioctl.h +pub const IOCPARM_MASK: ::c_int = 0x7f; +pub const IOC_VOID: ::c_int = 0x20000000; +pub const IOC_OUT: ::c_int = 0x40000000; +pub const IOC_IN: ::c_int = 0x40000000 << 1; +pub const IOC_INOUT: ::c_int = IOC_IN | IOC_OUT; +pub const FIOCLEX: ::c_int = 536897025; +pub const FIONCLEX: ::c_int = 536897026; +pub const FIONREAD: ::c_int = 1074030207; +pub const FIONBIO: ::c_int = -2147195266; +pub const FIOASYNC: ::c_int = -2147195267; +pub const FIOSETOWN: ::c_int = -2147195268; +pub const FIOGETOWN: ::c_int = 1074030203; +pub const TIOCGETD: ::c_int = 0x40047400; +pub const TIOCSETD: ::c_int = 0x80047401; +pub const TIOCHPCL: ::c_int = 0x20007402; +pub const TIOCMODG: ::c_int = 0x40047403; +pub const TIOCMODS: ::c_int = 0x80047404; +pub const TIOCM_LE: ::c_int = 0x1; +pub const TIOCM_DTR: ::c_int = 0x2; +pub const TIOCM_RTS: ::c_int = 0x4; +pub const TIOCM_ST: ::c_int = 0x8; +pub const TIOCM_SR: ::c_int = 0x10; +pub const TIOCM_CTS: ::c_int = 0x20; +pub const TIOCM_CAR: ::c_int = 0x40; +pub const TIOCM_CD: ::c_int = 0x40; +pub const TIOCM_RNG: ::c_int = 0x80; +pub const TIOCM_RI: ::c_int = 0x80; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCGETP: ::c_int = 0x40067408; +pub const TIOCSETP: ::c_int = 0x80067409; +pub const TIOCSETN: ::c_int = 0x8006740a; +pub const TIOCEXCL: ::c_int = 0x2000740d; +pub const TIOCNXCL: ::c_int = 0x2000740e; +pub const TIOCFLUSH: ::c_int = 0x80047410; +pub const TIOCSETC: ::c_int = 0x80067411; +pub const TIOCGETC: ::c_int = 0x40067412; +pub const TANDEM: ::c_int = 0x1; +pub const CBREAK: ::c_int = 0x2; +pub const LCASE: ::c_int = 0x4; + +// sys/ipc.h +pub const IPC_ALLOC: ::c_int = 0o100000; +pub const IPC_CREAT: ::c_int = 0o020000; +pub const IPC_EXCL: ::c_int = 0o002000; +pub const IPC_NOWAIT: ::c_int = 0o004000; +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 101; +pub const IPC_R: ::c_int = 0o0400; +pub const IPC_W: ::c_int = 0o0200; +pub const IPC_O: ::c_int = 0o1000; +pub const IPC_NOERROR: ::c_int = 0o10000; + +// sys/ldr.h +pub const L_GETINFO: ::c_int = 2; +pub const L_GETMESSAGE: ::c_int = 1; +pub const L_GETLIBPATH: ::c_int = 3; +pub const L_GETXINFO: ::c_int = 8; + +// sys/limits.h +pub const PATH_MAX: ::c_int = 1023; +pub const PAGESIZE: ::c_int = 4096; +pub const IOV_MAX: ::c_int = 16; +pub const AIO_LISTIO_MAX: ::c_int = 4096; +pub const PIPE_BUF: usize = 32768; + +// sys/lockf.h +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; + +// sys/mman.h +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; +pub const MAP_FILE: ::c_int = 0; +pub const MAP_SHARED: ::c_int = 1; +pub const MAP_PRIVATE: ::c_int = 2; +pub const MAP_FIXED: ::c_int = 0x100; +pub const MAP_ANON: ::c_int = 0x10; +pub const MAP_ANONYMOUS: ::c_int = 0x10; +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; +pub const MCL_CURRENT: ::c_int = 0x100; +pub const MCL_FUTURE: ::c_int = 0x200; +pub const MS_SYNC: ::c_int = 0x20; +pub const MS_ASYNC: ::c_int = 0x10; +pub const MS_INVALIDATE: ::c_int = 0x40; +pub const POSIX_MADV_NORMAL: ::c_int = 1; +pub const POSIX_MADV_RANDOM: ::c_int = 3; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 4; +pub const POSIX_MADV_DONTNEED: ::c_int = 5; +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; + +// sys/mode.h +pub const S_IFMT: mode_t = 0o170000; +pub const S_IFREG: mode_t = 0o100000; +pub const S_IFDIR: mode_t = 0o40000; +pub const S_IFBLK: mode_t = 0o60000; +pub const S_IFCHR: mode_t = 0o20000; +pub const S_IFIFO: mode_t = 0o10000; +pub const S_IRWXU: mode_t = 0o700; +pub const S_IRUSR: mode_t = 0o400; +pub const S_IWUSR: mode_t = 0o200; +pub const S_IXUSR: mode_t = 0o100; +pub const S_IRWXG: mode_t = 0o70; +pub const S_IRGRP: mode_t = 0o40; +pub const S_IWGRP: mode_t = 0o20; +pub const S_IXGRP: mode_t = 0o10; +pub const S_IRWXO: mode_t = 7; +pub const S_IROTH: mode_t = 4; +pub const S_IWOTH: mode_t = 2; +pub const S_IXOTH: mode_t = 1; +pub const S_IFLNK: mode_t = 0o120000; +pub const S_IFSOCK: mode_t = 0o140000; + +// sys/m_signal.h +pub const SIGSTKSZ: ::size_t = 4096; +pub const MINSIGSTKSZ: ::size_t = 1200; + +// sys/params.h +pub const MAXPATHLEN: ::c_int = PATH_MAX + 1; +pub const MAXSYMLINKS: ::c_int = 20; + +// sys/poll.h +pub const POLLIN: ::c_short = 0x0001; +pub const POLLPRI: ::c_short = 0x0004; +pub const POLLOUT: ::c_short = 0x0002; +pub const POLLERR: ::c_short = 0x4000; +pub const POLLHUP: ::c_short = 0x2000; +pub const POLLMSG: ::c_short = 0x0080; +pub const POLLSYNC: ::c_short = 0x8000; +pub const POLLNVAL: ::c_short = POLLSYNC; +pub const POLLNORM: ::c_short = POLLIN; +pub const POLLRDNORM: ::c_short = 0x0010; +pub const POLLWRNORM: ::c_short = POLLOUT; +pub const POLLRDBAND: ::c_short = 0x0020; +pub const POLLWRBAND: ::c_short = 0x0040; + +// sys/pollset.h +pub const PS_ADD: ::c_uchar = 0; +pub const PS_MOD: ::c_uchar = 1; +pub const PS_DELETE: ::c_uchar = 2; +pub const PS_REPLACE: ::c_uchar = 3; + +// sys/ptrace.h +pub const PT_TRACE_ME: ::c_int = 0; +pub const PT_READ_I: ::c_int = 1; +pub const PT_READ_D: ::c_int = 2; +pub const PT_WRITE_I: ::c_int = 4; +pub const PT_WRITE_D: ::c_int = 5; +pub const PT_CONTINUE: ::c_int = 7; +pub const PT_KILL: ::c_int = 8; +pub const PT_STEP: ::c_int = 9; +pub const PT_READ_GPR: ::c_int = 11; +pub const PT_READ_FPR: ::c_int = 12; +pub const PT_WRITE_GPR: ::c_int = 14; +pub const PT_WRITE_FPR: ::c_int = 15; +pub const PT_READ_BLOCK: ::c_int = 17; +pub const PT_WRITE_BLOCK: ::c_int = 19; +pub const PT_ATTACH: ::c_int = 30; +pub const PT_DETACH: ::c_int = 31; +pub const PT_REGSET: ::c_int = 32; +pub const PT_REATT: ::c_int = 33; +pub const PT_LDINFO: ::c_int = 34; +pub const PT_MULTI: ::c_int = 35; +pub const PT_NEXT: ::c_int = 36; +pub const PT_SET: ::c_int = 37; +pub const PT_CLEAR: ::c_int = 38; +pub const PT_LDXINFO: ::c_int = 39; +pub const PT_QUERY: ::c_int = 40; +pub const PT_WATCH: ::c_int = 41; +pub const PTT_CONTINUE: ::c_int = 50; +pub const PTT_STEP: ::c_int = 51; +pub const PTT_READ_SPRS: ::c_int = 52; +pub const PTT_WRITE_SPRS: ::c_int = 53; +pub const PTT_READ_GPRS: ::c_int = 54; +pub const PTT_WRITE_GPRS: ::c_int = 55; +pub const PTT_READ_FPRS: ::c_int = 56; +pub const PTT_WRITE_FPRS: ::c_int = 57; +pub const PTT_READ_VEC: ::c_int = 58; +pub const PTT_WRITE_VEC: ::c_int = 59; +pub const PTT_WATCH: ::c_int = 60; +pub const PTT_SET_TRAP: ::c_int = 61; +pub const PTT_CLEAR_TRAP: ::c_int = 62; +pub const PTT_READ_UKEYSET: ::c_int = 63; +pub const PT_GET_UKEY: ::c_int = 64; +pub const PTT_READ_FPSCR_HI: ::c_int = 65; +pub const PTT_WRITE_FPSCR_HI: ::c_int = 66; +pub const PTT_READ_VSX: ::c_int = 67; +pub const PTT_WRITE_VSX: ::c_int = 68; +pub const PTT_READ_TM: ::c_int = 69; + +// sys/resource.h +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_AS: ::c_int = 6; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_THREADS: ::c_int = 8; +pub const RLIMIT_NPROC: ::c_int = 9; +pub const RUSAGE_SELF: ::c_int = 0; +pub const RUSAGE_CHILDREN: ::c_int = -1; +pub const PRIO_PROCESS: ::c_int = 0; +pub const PRIO_PGRP: ::c_int = 1; +pub const PRIO_USER: ::c_int = 2; + +// sys/sched.h +pub const SCHED_OTHER: ::c_int = 0; +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_RR: ::c_int = 2; +pub const SCHED_LOCAL: ::c_int = 3; +pub const SCHED_GLOBAL: ::c_int = 4; +pub const SCHED_FIFO2: ::c_int = 5; +pub const SCHED_FIFO3: ::c_int = 6; +pub const SCHED_FIFO4: ::c_int = 7; + +// sys/sem.h +pub const SEM_UNDO: ::c_int = 0o10000; +pub const GETNCNT: ::c_int = 3; +pub const GETPID: ::c_int = 4; +pub const GETVAL: ::c_int = 5; +pub const GETALL: ::c_int = 6; +pub const GETZCNT: ::c_int = 7; +pub const SETVAL: ::c_int = 8; +pub const SETALL: ::c_int = 9; + +// sys/shm.h +pub const SHMLBA: ::c_int = 0x10000000; +pub const SHMLBA_EXTSHM: ::c_int = 0x1000; +pub const SHM_SHMAT: ::c_int = 0x80000000; +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_PIN: ::c_int = 0o4000; +pub const SHM_LGPAGE: ::c_int = 0o20000000000; +pub const SHM_MAP: ::c_int = 0o4000; +pub const SHM_FMAP: ::c_int = 0o2000; +pub const SHM_COPY: ::c_int = 0o40000; +pub const SHM_CLEAR: ::c_int = 0; +pub const SHM_HGSEG: ::c_int = 0o10000000000; +pub const SHM_R: ::c_int = IPC_R; +pub const SHM_W: ::c_int = IPC_W; +pub const SHM_DEST: ::c_int = 0o2000; + +// sys/signal.h +pub const SA_ONSTACK: ::c_int = 0x00000001; +pub const SA_RESETHAND: ::c_int = 0x00000002; +pub const SA_RESTART: ::c_int = 0x00000008; +pub const SA_SIGINFO: ::c_int = 0x00000100; +pub const SA_NODEFER: ::c_int = 0x00000200; +pub const SA_NOCLDWAIT: ::c_int = 0x00000400; +pub const SA_NOCLDSTOP: ::c_int = 0x00000004; +pub const SS_ONSTACK: ::c_int = 0x00000001; +pub const SS_DISABLE: ::c_int = 0x00000002; +pub const SIGCHLD: ::c_int = 20; +pub const SIGBUS: ::c_int = 10; +pub const SIG_BLOCK: ::c_int = 0; +pub const SIG_UNBLOCK: ::c_int = 1; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIGEV_NONE: ::c_int = 1; +pub const SIGEV_SIGNAL: ::c_int = 2; +pub const SIGEV_THREAD: ::c_int = 3; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGEMT: ::c_int = 7; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGSYS: ::c_int = 12; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; +pub const SIGUSR1: ::c_int = 30; +pub const SIGUSR2: ::c_int = 31; +pub const SIGPWR: ::c_int = 29; +pub const SIGWINCH: ::c_int = 28; +pub const SIGURG: ::c_int = 16; +pub const SIGPOLL: ::c_int = SIGIO; +pub const SIGIO: ::c_int = 23; +pub const SIGSTOP: ::c_int = 17; +pub const SIGTSTP: ::c_int = 18; +pub const SIGCONT: ::c_int = 19; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGVTALRM: ::c_int = 34; +pub const SIGPROF: ::c_int = 32; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGTRAP: ::c_int = 5; +pub const SI_USER: ::c_int = 0; +pub const SI_UNDEFINED: ::c_int = 8; +pub const SI_EMPTY: ::c_int = 9; +pub const BUS_ADRALN: ::c_int = 1; +pub const BUS_ADRERR: ::c_int = 2; +pub const BUS_OBJERR: ::c_int = 3; +pub const BUS_UEGARD: ::c_int = 4; +pub const CLD_EXITED: ::c_int = 10; +pub const CLD_KILLED: ::c_int = 11; +pub const CLD_DUMPED: ::c_int = 12; +pub const CLD_TRAPPED: ::c_int = 13; +pub const CLD_STOPPED: ::c_int = 14; +pub const CLD_CONTINUED: ::c_int = 15; +pub const FPE_INTDIV: ::c_int = 20; +pub const FPE_INTOVF: ::c_int = 21; +pub const FPE_FLTDIV: ::c_int = 22; +pub const FPE_FLTOVF: ::c_int = 23; +pub const FPE_FLTUND: ::c_int = 24; +pub const FPE_FLTRES: ::c_int = 25; +pub const FPE_FLTINV: ::c_int = 26; +pub const FPE_FLTSUB: ::c_int = 27; +pub const ILL_ILLOPC: ::c_int = 30; +pub const ILL_ILLOPN: ::c_int = 31; +pub const ILL_ILLADR: ::c_int = 32; +pub const ILL_ILLTRP: ::c_int = 33; +pub const ILL_PRVOPC: ::c_int = 34; +pub const ILL_PRVREG: ::c_int = 35; +pub const ILL_COPROC: ::c_int = 36; +pub const ILL_BADSTK: ::c_int = 37; +pub const ILL_TMBADTHING: ::c_int = 38; +pub const POLL_IN: ::c_int = 40; +pub const POLL_OUT: ::c_int = 41; +pub const POLL_MSG: ::c_int = -3; +pub const POLL_ERR: ::c_int = 43; +pub const POLL_PRI: ::c_int = 44; +pub const POLL_HUP: ::c_int = 45; +pub const SEGV_MAPERR: ::c_int = 50; +pub const SEGV_ACCERR: ::c_int = 51; +pub const SEGV_KEYERR: ::c_int = 52; +pub const TRAP_BRKPT: ::c_int = 60; +pub const TRAP_TRACE: ::c_int = 61; +pub const SI_QUEUE: ::c_int = 71; +pub const SI_TIMER: ::c_int = 72; +pub const SI_ASYNCIO: ::c_int = 73; +pub const SI_MESGQ: ::c_int = 74; + +// sys/socket.h +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_PUP: ::c_int = 4; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_NS: ::c_int = 6; +pub const AF_ECMA: ::c_int = 8; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_CCITT: ::c_int = 10; +pub const AF_SNA: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_LAT: ::c_int = 14; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_ISO: ::c_int = 7; +pub const AF_OSI: ::c_int = AF_ISO; +pub const AF_ROUTE: ::c_int = 17; +pub const AF_LINK: ::c_int = 18; +pub const AF_INET6: ::c_int = 24; +pub const AF_INTF: ::c_int = 20; +pub const AF_RIF: ::c_int = 21; +pub const AF_NDD: ::c_int = 23; +pub const AF_MAX: ::c_int = 30; +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_UNIX: ::c_int = AF_UNIX; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_IMPLINK: ::c_int = AF_IMPLINK; +pub const PF_PUP: ::c_int = AF_PUP; +pub const PF_CHAOS: ::c_int = AF_CHAOS; +pub const PF_NS: ::c_int = AF_NS; +pub const PF_ISO: ::c_int = AF_ISO; +pub const PF_OSI: ::c_int = AF_ISO; +pub const PF_ECMA: ::c_int = AF_ECMA; +pub const PF_DATAKIT: ::c_int = AF_DATAKIT; +pub const PF_CCITT: ::c_int = AF_CCITT; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_DLI: ::c_int = AF_DLI; +pub const PF_LAT: ::c_int = AF_LAT; +pub const PF_HYLINK: ::c_int = AF_HYLINK; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_LINK: ::c_int = AF_LINK; +pub const PF_XTP: ::c_int = 19; +pub const PF_RIF: ::c_int = AF_RIF; +pub const PF_INTF: ::c_int = AF_INTF; +pub const PF_NDD: ::c_int = AF_NDD; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_MAX: ::c_int = AF_MAX; +pub const SF_CLOSE: ::c_int = 1; +pub const SF_REUSE: ::c_int = 2; +pub const SF_DONT_CACHE: ::c_int = 4; +pub const SF_SYNC_CACHE: ::c_int = 8; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOL_SOCKET: ::c_int = 0xffff; +pub const SO_DEBUG: ::c_int = 0x0001; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_USE_IFBUFS: ::c_int = 0x0400; +pub const SO_CKSUMRECV: ::c_int = 0x0800; +pub const SO_NOREUSEADDR: ::c_int = 0x1000; +pub const SO_KERNACCEPT: ::c_int = 0x2000; +pub const SO_NOMULTIPATH: ::c_int = 0x4000; +pub const SO_AUDIT: ::c_int = 0x8000; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SCM_RIGHTS: ::c_int = 0x01; +pub const MSG_OOB: ::c_int = 0x1; +pub const MSG_PEEK: ::c_int = 0x2; +pub const MSG_DONTROUTE: ::c_int = 0x4; +pub const MSG_EOR: ::c_int = 0x8; +pub const MSG_TRUNC: ::c_int = 0x10; +pub const MSG_CTRUNC: ::c_int = 0x20; +pub const MSG_WAITALL: ::c_int = 0x40; +pub const MSG_MPEG2: ::c_int = 0x80; +pub const MSG_NOSIGNAL: ::c_int = 0x100; +pub const MSG_WAITFORONE: ::c_int = 0x200; +pub const MSG_ARGEXT: ::c_int = 0x400; +pub const MSG_NONBLOCK: ::c_int = 0x4000; +pub const MSG_COMPAT: ::c_int = 0x8000; +pub const MSG_MAXIOVLEN: ::c_int = 16; +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +// sys/stat.h +pub const UTIME_NOW: ::c_int = -2; +pub const UTIME_OMIT: ::c_int = -3; + +// sys/statvfs.h +pub const ST_RDONLY: ::c_ulong = 0x0001; +pub const ST_NOSUID: ::c_ulong = 0x0040; +pub const ST_NODEV: ::c_ulong = 0x0080; + +// sys/stropts.h +pub const I_NREAD: ::c_int = 0x20005301; +pub const I_PUSH: ::c_int = 0x20005302; +pub const I_POP: ::c_int = 0x20005303; +pub const I_LOOK: ::c_int = 0x20005304; +pub const I_FLUSH: ::c_int = 0x20005305; +pub const I_SRDOPT: ::c_int = 0x20005306; +pub const I_GRDOPT: ::c_int = 0x20005307; +pub const I_STR: ::c_int = 0x20005308; +pub const I_SETSIG: ::c_int = 0x20005309; +pub const I_GETSIG: ::c_int = 0x2000530a; +pub const I_FIND: ::c_int = 0x2000530b; +pub const I_LINK: ::c_int = 0x2000530c; +pub const I_UNLINK: ::c_int = 0x2000530d; +pub const I_PEEK: ::c_int = 0x2000530f; +pub const I_FDINSERT: ::c_int = 0x20005310; +pub const I_SENDFD: ::c_int = 0x20005311; +pub const I_RECVFD: ::c_int = 0x20005312; +pub const I_SWROPT: ::c_int = 0x20005314; +pub const I_GWROPT: ::c_int = 0x20005315; +pub const I_LIST: ::c_int = 0x20005316; +pub const I_PLINK: ::c_int = 0x2000531d; +pub const I_PUNLINK: ::c_int = 0x2000531e; +pub const I_FLUSHBAND: ::c_int = 0x20005313; +pub const I_CKBAND: ::c_int = 0x20005318; +pub const I_GETBAND: ::c_int = 0x20005319; +pub const I_ATMARK: ::c_int = 0x20005317; +pub const I_SETCLTIME: ::c_int = 0x2000531b; +pub const I_GETCLTIME: ::c_int = 0x2000531c; +pub const I_CANPUT: ::c_int = 0x2000531a; + +// sys/syslog.h +pub const LOG_CRON: ::c_int = 9 << 3; +pub const LOG_AUTHPRIV: ::c_int = 10 << 3; +pub const LOG_NFACILITIES: ::c_int = 24; +pub const LOG_PERROR: ::c_int = 0x20; + +// sys/systemcfg.h +pub const SC_ARCH: ::c_int = 1; +pub const SC_IMPL: ::c_int = 2; +pub const SC_VERS: ::c_int = 3; +pub const SC_WIDTH: ::c_int = 4; +pub const SC_NCPUS: ::c_int = 5; +pub const SC_L1C_ATTR: ::c_int = 6; +pub const SC_L1C_ISZ: ::c_int = 7; +pub const SC_L1C_DSZ: ::c_int = 8; +pub const SC_L1C_ICA: ::c_int = 9; +pub const SC_L1C_DCA: ::c_int = 10; +pub const SC_L1C_IBS: ::c_int = 11; +pub const SC_L1C_DBS: ::c_int = 12; +pub const SC_L1C_ILS: ::c_int = 13; +pub const SC_L1C_DLS: ::c_int = 14; +pub const SC_L2C_SZ: ::c_int = 15; +pub const SC_L2C_AS: ::c_int = 16; +pub const SC_TLB_ATTR: ::c_int = 17; +pub const SC_ITLB_SZ: ::c_int = 18; +pub const SC_DTLB_SZ: ::c_int = 19; +pub const SC_ITLB_ATT: ::c_int = 20; +pub const SC_DTLB_ATT: ::c_int = 21; +pub const SC_RESRV_SZ: ::c_int = 22; +pub const SC_PRI_LC: ::c_int = 23; +pub const SC_PRO_LC: ::c_int = 24; +pub const SC_RTC_TYPE: ::c_int = 25; +pub const SC_VIRT_AL: ::c_int = 26; +pub const SC_CAC_CONG: ::c_int = 27; +pub const SC_MOD_ARCH: ::c_int = 28; +pub const SC_MOD_IMPL: ::c_int = 29; +pub const SC_XINT: ::c_int = 30; +pub const SC_XFRAC: ::c_int = 31; +pub const SC_KRN_ATTR: ::c_int = 32; +pub const SC_PHYSMEM: ::c_int = 33; +pub const SC_SLB_ATTR: ::c_int = 34; +pub const SC_SLB_SZ: ::c_int = 35; +pub const SC_MAX_NCPUS: ::c_int = 37; +pub const SC_MAX_REALADDR: ::c_int = 38; +pub const SC_ORIG_ENT_CAP: ::c_int = 39; +pub const SC_ENT_CAP: ::c_int = 40; +pub const SC_DISP_WHE: ::c_int = 41; +pub const SC_CAPINC: ::c_int = 42; +pub const SC_VCAPW: ::c_int = 43; +pub const SC_SPLP_STAT: ::c_int = 44; +pub const SC_SMT_STAT: ::c_int = 45; +pub const SC_SMT_TC: ::c_int = 46; +pub const SC_VMX_VER: ::c_int = 47; +pub const SC_LMB_SZ: ::c_int = 48; +pub const SC_MAX_XCPU: ::c_int = 49; +pub const SC_EC_LVL: ::c_int = 50; +pub const SC_AME_STAT: ::c_int = 51; +pub const SC_ECO_STAT: ::c_int = 52; +pub const SC_DFP_VER: ::c_int = 53; +pub const SC_VRM_STAT: ::c_int = 54; +pub const SC_PHYS_IMP: ::c_int = 55; +pub const SC_PHYS_VER: ::c_int = 56; +pub const SC_SPCM_STATUS: ::c_int = 57; +pub const SC_SPCM_MAX: ::c_int = 58; +pub const SC_TM_VER: ::c_int = 59; +pub const SC_NX_CAP: ::c_int = 60; +pub const SC_PKS_STATE: ::c_int = 61; +pub const SC_MMA_VER: ::c_int = 62; +pub const POWER_RS: ::c_int = 1; +pub const POWER_PC: ::c_int = 2; +pub const IA64: ::c_int = 3; +pub const POWER_RS1: ::c_int = 0x1; +pub const POWER_RSC: ::c_int = 0x2; +pub const POWER_RS2: ::c_int = 0x4; +pub const POWER_601: ::c_int = 0x8; +pub const POWER_604: ::c_int = 0x10; +pub const POWER_603: ::c_int = 0x20; +pub const POWER_620: ::c_int = 0x40; +pub const POWER_630: ::c_int = 0x80; +pub const POWER_A35: ::c_int = 0x100; +pub const POWER_RS64II: ::c_int = 0x200; +pub const POWER_RS64III: ::c_int = 0x400; +pub const POWER_4: ::c_int = 0x800; +pub const POWER_RS64IV: ::c_int = POWER_4; +pub const POWER_MPC7450: ::c_int = 0x1000; +pub const POWER_5: ::c_int = 0x2000; +pub const POWER_6: ::c_int = 0x4000; +pub const POWER_7: ::c_int = 0x8000; +pub const POWER_8: ::c_int = 0x10000; +pub const POWER_9: ::c_int = 0x20000; + +// sys/time.h +pub const FD_SETSIZE: usize = 65534; +pub const TIMEOFDAY: ::c_int = 9; +pub const CLOCK_REALTIME: ::clockid_t = TIMEOFDAY as clockid_t; +pub const CLOCK_MONOTONIC: ::clockid_t = 10; +pub const TIMER_ABSTIME: ::c_int = 999; +pub const ITIMER_REAL: ::c_int = 0; +pub const ITIMER_VIRTUAL: ::c_int = 1; +pub const ITIMER_PROF: ::c_int = 2; +pub const ITIMER_VIRT: ::c_int = 3; +pub const ITIMER_REAL1: ::c_int = 20; +pub const ITIMER_REAL_TH: ::c_int = ITIMER_REAL1; + +// sys/termio.h +pub const TCGETA: ::c_int = TIOC | 5; +pub const TCSETA: ::c_int = TIOC | 6; +pub const TCSETAW: ::c_int = TIOC | 7; +pub const TCSETAF: ::c_int = TIOC | 8; +pub const TCSBRK: ::c_int = TIOC | 9; +pub const TCXONC: ::c_int = TIOC | 11; +pub const TCFLSH: ::c_int = TIOC | 12; +pub const TCGETS: ::c_int = TIOC | 1; +pub const TCSETS: ::c_int = TIOC | 2; +pub const TCSANOW: ::c_int = 0; +pub const TCSETSW: ::c_int = TIOC | 3; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSETSF: ::c_int = TIOC | 4; +pub const TCSAFLUSH: ::c_int = 2; +pub const TCIFLUSH: ::c_int = 0; +pub const TCOFLUSH: ::c_int = 1; +pub const TCIOFLUSH: ::c_int = 2; +pub const TCOOFF: ::c_int = 0; +pub const TCOON: ::c_int = 1; +pub const TCIOFF: ::c_int = 2; +pub const TCION: ::c_int = 3; +pub const TIOC: ::c_int = 0x5400; +pub const TIOCGWINSZ: ::c_int = 0x40087468; +pub const TIOCSWINSZ: ::c_int = 0x80087467; +pub const TIOCLBIS: ::c_int = 0x8004747f; +pub const TIOCLBIC: ::c_int = 0x8004747e; +pub const TIOCLSET: ::c_int = 0x8004747d; +pub const TIOCLGET: ::c_int = 0x4004747c; +pub const TIOCSBRK: ::c_int = 0x2000747b; +pub const TIOCCBRK: ::c_int = 0x2000747a; +pub const TIOCSDTR: ::c_int = 0x20007479; +pub const TIOCCDTR: ::c_int = 0x20007478; +pub const TIOCSLTC: ::c_int = 0x80067475; +pub const TIOCGLTC: ::c_int = 0x40067474; +pub const TIOCOUTQ: ::c_int = 0x40047473; +pub const TIOCNOTTY: ::c_int = 0x20007471; +pub const TIOCSTOP: ::c_int = 0x2000746f; +pub const TIOCSTART: ::c_int = 0x2000746e; +pub const TIOCGPGRP: ::c_int = 0x40047477; +pub const TIOCSPGRP: ::c_int = 0x80047476; +pub const TIOCGSID: ::c_int = 0x40047448; +pub const TIOCSTI: ::c_int = 0x80017472; +pub const TIOCMSET: ::c_int = 0x8004746d; +pub const TIOCMBIS: ::c_int = 0x8004746c; +pub const TIOCMBIC: ::c_int = 0x8004746b; +pub const TIOCMGET: ::c_int = 0x4004746a; +pub const TIOCREMOTE: ::c_int = 0x80047469; + +// sys/wait.h +pub const P_ALL: ::c_int = 0; +pub const P_PID: ::c_int = 1; +pub const P_PGID: ::c_int = 2; +pub const WNOHANG: ::c_int = 0x1; +pub const WUNTRACED: ::c_int = 0x2; +pub const WEXITED: ::c_int = 0x04; +pub const WCONTINUED: ::c_int = 0x01000000; +pub const WNOWAIT: ::c_int = 0x10; +pub const _W_STOPPED: ::c_int = 0x00000040; +pub const _W_SLWTED: ::c_int = 0x0000007c; +pub const _W_SEWTED: ::c_int = 0x0000007d; +pub const _W_SFWTED: ::c_int = 0x0000007e; +pub const _W_STRC: ::c_int = 0x0000007f; + +// termios.h +pub const NCCS: usize = 16; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS5: ::tcflag_t = 0x00000000; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const ECHO: ::tcflag_t = 0x20000; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOCTL: ::tcflag_t = 0x00020000; +pub const ECHOPRT: ::tcflag_t = 0x00040000; +pub const ECHOKE: ::tcflag_t = 0x00080000; +pub const IGNBRK: ::tcflag_t = 0x00000001; +pub const BRKINT: ::tcflag_t = 0x00000002; +pub const IGNPAR: ::tcflag_t = 0x00000004; +pub const PARMRK: ::tcflag_t = 0x00000008; +pub const INPCK: ::tcflag_t = 0x00000010; +pub const ISTRIP: ::tcflag_t = 0x00000020; +pub const INLCR: ::tcflag_t = 0x00000040; +pub const IGNCR: ::tcflag_t = 0x00000080; +pub const ICRNL: ::tcflag_t = 0x00000100; +pub const IXON: ::tcflag_t = 0x0001; +pub const IXOFF: ::tcflag_t = 0x00000400; +pub const IXANY: ::tcflag_t = 0x00001000; +pub const IMAXBEL: ::tcflag_t = 0x00010000; +pub const OPOST: ::tcflag_t = 0x00000001; +pub const ONLCR: ::tcflag_t = 0x00000004; +pub const OCRNL: ::tcflag_t = 0x00000008; +pub const ONOCR: ::tcflag_t = 0x00000010; +pub const ONLRET: ::tcflag_t = 0x00000020; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const IEXTEN: ::tcflag_t = 0x00200000; +pub const TOSTOP: ::tcflag_t = 0x00010000; +pub const FLUSHO: ::tcflag_t = 0x00100000; +pub const PENDIN: ::tcflag_t = 0x20000000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const VINTR: usize = 0; +pub const VQUIT: usize = 1; +pub const VERASE: usize = 2; +pub const VKILL: usize = 3; +pub const VEOF: usize = 4; +pub const VEOL: usize = 5; +pub const VSTART: usize = 7; +pub const VSTOP: usize = 8; +pub const VSUSP: usize = 9; +pub const VMIN: usize = 4; +pub const VTIME: usize = 5; +pub const VEOL2: usize = 6; +pub const VDSUSP: usize = 10; +pub const VREPRINT: usize = 11; +pub const VDISCRD: usize = 12; +pub const VWERSE: usize = 13; +pub const VLNEXT: usize = 14; +pub const B0: ::speed_t = 0x0; +pub const B50: ::speed_t = 0x1; +pub const B75: ::speed_t = 0x2; +pub const B110: ::speed_t = 0x3; +pub const B134: ::speed_t = 0x4; +pub const B150: ::speed_t = 0x5; +pub const B200: ::speed_t = 0x6; +pub const B300: ::speed_t = 0x7; +pub const B600: ::speed_t = 0x8; +pub const B1200: ::speed_t = 0x9; +pub const B1800: ::speed_t = 0xa; +pub const B2400: ::speed_t = 0xb; +pub const B4800: ::speed_t = 0xc; +pub const B9600: ::speed_t = 0xd; +pub const B19200: ::speed_t = 0xe; +pub const B38400: ::speed_t = 0xf; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const IUCLC: ::tcflag_t = 0x00000800; +pub const OFILL: ::tcflag_t = 0x00000040; +pub const OFDEL: ::tcflag_t = 0x00000080; +pub const CRDLY: ::tcflag_t = 0x00000300; +pub const CR0: ::tcflag_t = 0x00000000; +pub const CR1: ::tcflag_t = 0x00000100; +pub const CR2: ::tcflag_t = 0x00000200; +pub const CR3: ::tcflag_t = 0x00000300; +pub const TABDLY: ::tcflag_t = 0x00000c00; +pub const TAB0: ::tcflag_t = 0x00000000; +pub const TAB1: ::tcflag_t = 0x00000400; +pub const TAB2: ::tcflag_t = 0x00000800; +pub const TAB3: ::tcflag_t = 0x00000c00; +pub const BSDLY: ::tcflag_t = 0x00001000; +pub const BS0: ::tcflag_t = 0x00000000; +pub const BS1: ::tcflag_t = 0x00001000; +pub const FFDLY: ::tcflag_t = 0x00002000; +pub const FF0: ::tcflag_t = 0x00000000; +pub const FF1: ::tcflag_t = 0x00002000; +pub const NLDLY: ::tcflag_t = 0x00004000; +pub const NL0: ::tcflag_t = 0x00000000; +pub const NL1: ::tcflag_t = 0x00004000; +pub const VTDLY: ::tcflag_t = 0x00008000; +pub const VT0: ::tcflag_t = 0x00000000; +pub const VT1: ::tcflag_t = 0x00008000; +pub const OXTABS: ::tcflag_t = 0x00040000; +pub const ONOEOT: ::tcflag_t = 0x00080000; +pub const CBAUD: ::tcflag_t = 0x0000000f; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const CIBAUD: ::tcflag_t = 0x000f0000; +pub const IBSHIFT: ::tcflag_t = 16; +pub const PAREXT: ::tcflag_t = 0x00100000; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const XCASE: ::tcflag_t = 0x00000004; +pub const ALTWERASE: ::tcflag_t = 0x00400000; + +// time.h +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 11; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 12; + +// unistd.h +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const _POSIX_VDISABLE: ::c_int = 0xff; +pub const _PC_LINK_MAX: ::c_int = 11; +pub const _PC_MAX_CANON: ::c_int = 12; +pub const _PC_MAX_INPUT: ::c_int = 13; +pub const _PC_NAME_MAX: ::c_int = 14; +pub const _PC_PATH_MAX: ::c_int = 16; +pub const _PC_PIPE_BUF: ::c_int = 17; +pub const _PC_NO_TRUNC: ::c_int = 15; +pub const _PC_VDISABLE: ::c_int = 18; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 10; +pub const _PC_ASYNC_IO: ::c_int = 19; +pub const _PC_PRIO_IO: ::c_int = 21; +pub const _PC_SYNC_IO: ::c_int = 20; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 26; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 27; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 28; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 29; +pub const _PC_REC_XFER_ALIGN: ::c_int = 30; +pub const _PC_SYMLINK_MAX: ::c_int = 25; +pub const _PC_2_SYMLINKS: ::c_int = 31; +pub const _PC_TIMESTAMP_RESOLUTION: ::c_int = 32; +pub const _PC_FILESIZEBITS: ::c_int = 22; +pub const _SC_ARG_MAX: ::c_int = 0; +pub const _SC_CHILD_MAX: ::c_int = 1; +pub const _SC_CLK_TCK: ::c_int = 2; +pub const _SC_NGROUPS_MAX: ::c_int = 3; +pub const _SC_OPEN_MAX: ::c_int = 4; +pub const _SC_JOB_CONTROL: ::c_int = 7; +pub const _SC_SAVED_IDS: ::c_int = 8; +pub const _SC_VERSION: ::c_int = 9; +pub const _SC_PASS_MAX: ::c_int = 45; +pub const _SC_PAGESIZE: ::c_int = _SC_PAGE_SIZE; +pub const _SC_PAGE_SIZE: ::c_int = 48; +pub const _SC_XOPEN_VERSION: ::c_int = 46; +pub const _SC_NPROCESSORS_CONF: ::c_int = 71; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 72; +pub const _SC_STREAM_MAX: ::c_int = 5; +pub const _SC_TZNAME_MAX: ::c_int = 6; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 75; +pub const _SC_AIO_MAX: ::c_int = 76; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 77; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 78; +pub const _SC_DELAYTIMER_MAX: ::c_int = 79; +pub const _SC_FSYNC: ::c_int = 80; +pub const _SC_MAPPED_FILES: ::c_int = 84; +pub const _SC_MEMLOCK: ::c_int = 85; +pub const _SC_MEMLOCK_RANGE: ::c_int = 86; +pub const _SC_MEMORY_PROTECTION: ::c_int = 87; +pub const _SC_MESSAGE_PASSING: ::c_int = 88; +pub const _SC_MQ_OPEN_MAX: ::c_int = 89; +pub const _SC_MQ_PRIO_MAX: ::c_int = 90; +pub const _SC_PRIORITIZED_IO: ::c_int = 91; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 92; +pub const _SC_REALTIME_SIGNALS: ::c_int = 93; +pub const _SC_RTSIG_MAX: ::c_int = 94; +pub const _SC_SEMAPHORES: ::c_int = 95; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 96; +pub const _SC_SEM_VALUE_MAX: ::c_int = 97; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 98; +pub const _SC_SIGQUEUE_MAX: ::c_int = 99; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 100; +pub const _SC_TIMERS: ::c_int = 102; +pub const _SC_TIMER_MAX: ::c_int = 103; +pub const _SC_2_C_BIND: ::c_int = 51; +pub const _SC_2_C_DEV: ::c_int = 32; +pub const _SC_2_C_VERSION: ::c_int = 52; +pub const _SC_2_FORT_DEV: ::c_int = 33; +pub const _SC_2_FORT_RUN: ::c_int = 34; +pub const _SC_2_LOCALEDEF: ::c_int = 35; +pub const _SC_2_SW_DEV: ::c_int = 36; +pub const _SC_2_UPE: ::c_int = 53; +pub const _SC_2_VERSION: ::c_int = 31; +pub const _SC_BC_BASE_MAX: ::c_int = 23; +pub const _SC_BC_DIM_MAX: ::c_int = 24; +pub const _SC_BC_SCALE_MAX: ::c_int = 25; +pub const _SC_BC_STRING_MAX: ::c_int = 26; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 50; +pub const _SC_EXPR_NEST_MAX: ::c_int = 28; +pub const _SC_LINE_MAX: ::c_int = 29; +pub const _SC_RE_DUP_MAX: ::c_int = 30; +pub const _SC_XOPEN_CRYPT: ::c_int = 56; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 57; +pub const _SC_XOPEN_SHM: ::c_int = 55; +pub const _SC_2_CHAR_TERM: ::c_int = 54; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 109; +pub const _SC_ATEXIT_MAX: ::c_int = 47; +pub const _SC_IOV_MAX: ::c_int = 58; +pub const _SC_XOPEN_UNIX: ::c_int = 73; +pub const _SC_T_IOV_MAX: ::c_int = 0; +pub const _SC_PHYS_PAGES: ::c_int = 113; +pub const _SC_AVPHYS_PAGES: ::c_int = 114; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 101; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 81; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 82; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 83; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 68; +pub const _SC_THREAD_STACK_MIN: ::c_int = 69; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 70; +pub const _SC_TTY_NAME_MAX: ::c_int = 104; +pub const _SC_THREADS: ::c_int = 60; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 61; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 62; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 64; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 65; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 66; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 67; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 59; +pub const _SC_XOPEN_LEGACY: ::c_int = 112; +pub const _SC_XOPEN_REALTIME: ::c_int = 110; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 111; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 105; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 106; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 107; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 108; +pub const _SC_2_PBS: ::c_int = 132; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 133; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 134; +pub const _SC_2_PBS_LOCATE: ::c_int = 135; +pub const _SC_2_PBS_MESSAGE: ::c_int = 136; +pub const _SC_2_PBS_TRACK: ::c_int = 137; +pub const _SC_ADVISORY_INFO: ::c_int = 130; +pub const _SC_BARRIERS: ::c_int = 138; +pub const _SC_CLOCK_SELECTION: ::c_int = 139; +pub const _SC_CPUTIME: ::c_int = 140; +pub const _SC_HOST_NAME_MAX: ::c_int = 126; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 141; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 142; +pub const _SC_REGEXP: ::c_int = 127; +pub const _SC_SHELL: ::c_int = 128; +pub const _SC_SPAWN: ::c_int = 143; +pub const _SC_SPIN_LOCKS: ::c_int = 144; +pub const _SC_SPORADIC_SERVER: ::c_int = 145; +pub const _SC_SS_REPL_MAX: ::c_int = 156; +pub const _SC_SYMLOOP_MAX: ::c_int = 129; +pub const _SC_THREAD_CPUTIME: ::c_int = 146; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 147; +pub const _SC_TIMEOUTS: ::c_int = 148; +pub const _SC_TRACE: ::c_int = 149; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 150; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 157; +pub const _SC_TRACE_INHERIT: ::c_int = 151; +pub const _SC_TRACE_LOG: ::c_int = 152; +pub const _SC_TRACE_NAME_MAX: ::c_int = 158; +pub const _SC_TRACE_SYS_MAX: ::c_int = 159; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 160; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 153; +pub const _SC_V6_ILP32_OFF32: ::c_int = 121; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 122; +pub const _SC_V6_LP64_OFF64: ::c_int = 123; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 124; +pub const _SC_XOPEN_STREAMS: ::c_int = 125; +pub const _SC_IPV6: ::c_int = 154; +pub const _SC_RAW_SOCKETS: ::c_int = 155; + +// utmp.h +pub const EMPTY: ::c_short = -1; +pub const RUN_LVL: ::c_short = 1; +pub const BOOT_TIME: ::c_short = 2; +pub const OLD_TIME: ::c_short = 3; +pub const NEW_TIME: ::c_short = 4; +pub const INIT_PROCESS: ::c_short = 5; +pub const LOGIN_PROCESS: ::c_short = 6; +pub const USER_PROCESS: ::c_short = 7; +pub const DEAD_PROCESS: ::c_short = 8; +pub const ACCOUNTING: ::c_short = 9; + +f! { + pub fn CMSG_FIRSTHDR(mhdr: *const msghdr) -> *mut cmsghdr { + if (*mhdr).msg_controllen as usize >= ::mem::size_of::() { + (*mhdr).msg_control as *mut cmsghdr + } else { + 0 as *mut cmsghdr + } + } + + pub fn CMSG_NXTHDR(mhdr: *const msghdr, cmsg: *const cmsghdr) -> *mut cmsghdr { + if cmsg.is_null() { + CMSG_FIRSTHDR(mhdr) + } else { + if (cmsg as usize + (*cmsg).cmsg_len as usize + ::mem::size_of::<::cmsghdr>()) > + ((*mhdr).msg_control as usize + (*mhdr).msg_controllen as usize) { + 0 as *mut ::cmsghdr + } else { + // AIX does not have any alignment/padding for ancillary data, so we don't need _CMSG_ALIGN here. + (cmsg as usize + (*cmsg).cmsg_len as usize) as *mut cmsghdr + } + } + } + + pub fn CMSG_DATA(cmsg: *const ::cmsghdr) -> *mut ::c_uchar { + (cmsg as *mut ::c_uchar).offset(::mem::size_of::<::cmsghdr>() as isize) + } + + pub fn CMSG_LEN(length: ::c_uint) -> ::c_uint { + ::mem::size_of::<::cmsghdr>() as ::c_uint + length + } + + pub fn CMSG_SPACE(length: ::c_uint) -> ::c_uint { + ::mem::size_of::<::cmsghdr>() as ::c_uint + length + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let bits = ::mem::size_of::<::c_long>() * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] |= 1 << (fd % bits); + return + } + + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let bits = ::mem::size_of::<::c_long>() * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *const fd_set) -> bool { + let bits = ::mem::size_of::<::c_long>() * 8; + let fd = fd as usize; + return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 + } + + pub fn major(dev: ::dev_t) -> ::c_uint { + let x = dev >> 16; + x as ::c_uint + } + + pub fn minor(dev: ::dev_t) -> ::c_uint { + let y = dev & 0xFFFF; + y as ::c_uint + } + + pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= major << 16; + dev |= minor; + dev + } +} + +safe_f! { + pub {const} fn WIFSTOPPED(status: ::c_int) -> bool { + (status & _W_STOPPED) != 0 + } + + pub {const} fn WSTOPSIG(status: ::c_int) -> ::c_int { + if WIFSTOPPED(status) { + (((status as ::c_uint) >> 8) & 0xff) as ::c_int + } else { + -1 + } + } + + pub {const} fn WIFEXITED(status: ::c_int) -> bool { + (status & 0xFF) == 0 + } + + pub {const} fn WEXITSTATUS(status: ::c_int) -> ::c_int { + if WIFEXITED(status) { + (((status as ::c_uint) >> 8) & 0xff) as ::c_int + } else { + -1 + } + } + + pub {const} fn WIFSIGNALED(status: ::c_int) -> bool { + !WIFEXITED(status) && !WIFSTOPPED(status) + } + + pub {const} fn WTERMSIG(status: ::c_int) -> ::c_int { + if WIFSIGNALED(status) { + (((status as ::c_uint) >> 16) & 0xff) as ::c_int + } else { + -1 + } + } + + pub {const} fn WIFCONTINUED(status: ::c_int) -> bool { + (status & WCONTINUED) != 0 + } + + // AIX doesn't have native WCOREDUMP. + pub {const} fn WCOREDUMP(_status: ::c_int) -> bool { + false + } +} + +extern "C" { + pub fn acct(filename: *const ::c_char) -> ::c_int; + pub fn bind(socket: ::c_int, address: *const ::sockaddr, address_len: ::socklen_t) -> ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clock_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + pub fn endgrent(); + pub fn endpwent(); + pub fn faccessat( + dirfd: ::c_int, + pathname: *const ::c_char, + mode: ::c_int, + flags: ::c_int, + ) -> ::c_int; + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn fgetgrent(file: *mut ::FILE) -> *mut ::group; + pub fn fgetpwent(file: *mut ::FILE) -> *mut ::passwd; + pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; + pub fn fstatfs64(fd: ::c_int, buf: *mut statfs64) -> ::c_int; + pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; + pub fn getgrent() -> *mut ::group; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + pub fn getgrgid_r( + gid: ::gid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group, + ) -> ::c_int; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn getgrnam_r( + name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group, + ) -> ::c_int; + pub fn getgrset(user: *mut ::c_char) -> *mut ::c_char; + pub fn getpeereid(socket: ::c_int, euid: *mut ::uid_t, egid: *mut ::gid_t) -> ::c_int; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn getpwent() -> *mut ::passwd; + pub fn getpwnam_r( + name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd, + ) -> ::c_int; + pub fn getpwuid_r( + uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd, + ) -> ::c_int; + pub fn getrlimit(resource: ::c_int, rlim: *mut ::rlimit) -> ::c_int; + pub fn gettimeofday(tp: *mut ::timeval, tz: *mut ::c_void) -> ::c_int; + pub fn initgroups(name: *const ::c_char, basegid: ::gid_t) -> ::c_int; + pub fn ioctl(fildes: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn loadquery(flags: ::c_int, buf: *mut ::c_char, buflen: ::c_uint) -> ::c_int; + pub fn lpar_get_info(command: ::c_int, buf: *mut ::c_void, bufsize: ::size_t) -> ::c_int; + pub fn lpar_set_resources(id: ::c_int, resource: *mut ::c_void) -> ::c_int; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) -> ::c_int; + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, mode: ::mode_t) -> ::c_int; + pub fn mknodat( + dirfd: ::c_int, + pathname: *const ::c_char, + mode: ::mode_t, + dev: dev_t, + ) -> ::c_int; + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) -> ::c_int; + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + pub fn pollset_create(maxfd: ::c_int) -> pollset_t; + pub fn pollset_ctl( + ps: pollset_t, + pollctl_array: *mut poll_ctl, + array_length: ::c_int, + ) -> ::c_int; + pub fn pollset_destroy(ps: pollset_t) -> ::c_int; + pub fn pollset_poll( + ps: pollset_t, + polldata_array: *mut ::pollfd, + array_length: ::c_int, + timeout: ::c_int, + ) -> ::c_int; + pub fn pollset_query(ps: pollset_t, pollfd_query: *mut ::pollfd) -> ::c_int; + pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, advise: ::c_int) -> ::c_int; + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, len: ::off_t) -> ::c_int; + pub fn preadv(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t) -> ::ssize_t; + pub fn pthread_atfork( + prepare: ::Option, + parent: ::Option, + child: ::Option, + ) -> ::c_int; + pub fn pthread_condattr_setclock( + attr: *mut pthread_condattr_t, + clock_id: ::clockid_t, + ) -> ::c_int; + pub fn pthread_create( + native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern "C" fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void, + ) -> ::c_int; + pub fn pthread_kill(thread: ::pthread_t, signal: ::c_int) -> ::c_int; + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, oldset: *mut sigset_t) -> ::c_int; + pub fn pwritev(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t) + -> ::ssize_t; + #[link_name = "__linux_quotactl"] + pub fn quotactl( + cmd: ::c_int, + special: *const ::c_char, + id: ::c_int, + data: *mut ::c_char, + ) -> ::c_int; + pub fn readv(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int) -> ::ssize_t; + pub fn recvfrom( + socket: ::c_int, + buf: *mut ::c_void, + len: ::size_t, + flags: ::c_int, + addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t, + ) -> ::ssize_t; + pub fn recvmsg(sockfd: ::c_int, msg: *mut msghdr, flags: ::c_int) -> ::ssize_t; + pub fn send_file(socket: *mut ::c_int, iobuf: *mut sf_parms, flags: ::c_uint) -> ::ssize_t; + pub fn sendmsg(sockfd: ::c_int, msg: *const msghdr, flags: ::c_int) -> ::ssize_t; + pub fn setgroups(ngroups: ::c_int, ptr: *const ::gid_t) -> ::c_int; + pub fn setgrent(); + pub fn sethostname(name: *const ::c_char, len: ::c_int) -> ::c_int; + pub fn setpriority(which: ::c_int, who: id_t, priority: ::c_int) -> ::c_int; + pub fn setpwent(); + pub fn setrlimit(resource: ::c_int, rlim: *const ::rlimit) -> ::c_int; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; + pub fn sigwait(set: *const sigset_t, sig: *mut ::c_int) -> ::c_int; + pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) -> ::c_int; + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; + pub fn statfs64(path: *const ::c_char, buf: *mut statfs64) -> ::c_int; + pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, buflen: ::size_t) -> ::c_int; + pub fn sync(); + pub fn uname(buf: *mut ::utsname) -> ::c_int; + pub fn utimensat( + dirfd: ::c_int, + path: *const ::c_char, + times: *const ::timespec, + flag: ::c_int, + ) -> ::c_int; + pub fn writev(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int) -> ::ssize_t; + + // Use AIX thread-safe version errno. + pub fn _Errno() -> *mut ::c_int; +} + +cfg_if! { + if #[cfg(target_arch = "powerpc64")] { + mod powerpc64; + pub use self::powerpc64::*; + } +} diff --git a/bash-5.1/vendor/libc/src/unix/aix/powerpc64.rs b/bash-5.1/vendor/libc/src/unix/aix/powerpc64.rs new file mode 100644 index 0000000..1f96ae3 --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/aix/powerpc64.rs @@ -0,0 +1,570 @@ +pub type c_long = i64; +pub type c_ulong = u64; + +s! { + pub struct sigset_t { + pub ss_set: [c_ulong; 4], + } + + pub struct fd_set { + pub fds_bits: [c_long; 1024], + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_sysid: ::c_uint, + pub l_pid: ::pid_t, + pub l_vfs: ::c_int, + pub l_start: ::off_t, + pub l_len: ::off_t, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_basetype: [::c_char; 16], + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + pub f_fstr: [::c_char; 32], + pub f_filler: [::c_ulong; 16] + } + + pub struct pthread_rwlock_t { + __rw_word: [::c_long; 10], + } + + pub struct pthread_cond_t { + __cv_word: [::c_long; 6], + } + + pub struct pthread_mutex_t { + __mt_word: [::c_long; 8], + } + + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_flag: ::c_ushort, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_ssize: ::c_int, + pub st_atime: ::st_timespec, + pub st_mtime: ::st_timespec, + pub st_ctime: ::st_timespec, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_vfstype: ::c_int, + pub st_vfs: ::c_uint, + pub st_type: ::c_uint, + pub st_gen: ::c_uint, + pub st_reserved: [::c_uint; 9], + pub st_padto_ll: ::c_uint, + pub st_size: ::off_t, + } + + pub struct statfs { + pub f_version: ::c_int, + pub f_type: ::c_int, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsblkcnt_t, + pub f_ffree: ::fsblkcnt_t, + pub f_fsid: ::fsid64_t, + pub f_vfstype: ::c_int, + pub f_fsize: ::c_ulong, + pub f_vfsnumber: ::c_int, + pub f_vfsoff: ::c_int, + pub f_vfslen: ::c_int, + pub f_vfsvers: ::c_int, + pub f_fname: [::c_char; 32], + pub f_fpack: [::c_char; 32], + pub f_name_max: ::c_int, + } +} + +s_no_extra_traits! { + #[cfg(libc_union)] + pub union sigval { + pub sival_ptr: *mut ::c_void, + pub sival_int: ::c_int, + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub si_pid: ::pid_t, + pub si_uid: ::uid_t, + pub si_status: ::c_int, + pub si_addr: *mut ::c_void, + pub si_band: ::c_long, + #[cfg(libc_union)] + pub si_value: sigval, + pub __si_flags: ::c_int, + pub __pad: [::c_int; 3], + } + + #[cfg(libc_union)] + pub union _kernel_simple_lock { + pub _slock: ::c_long, + // Should be pointer to 'lock_data_instrumented' + pub _slockp: *mut ::c_void, + } + + pub struct fileops_t { + pub fo_rw: extern fn(file: *mut file, rw: ::uio_rw, io: *mut ::c_void, ext: ::c_long, + secattr: *mut ::c_void) -> ::c_int, + pub fo_ioctl: extern fn(file: *mut file, a: ::c_long, b: ::caddr_t, c: ::c_long, + d: ::c_long) -> ::c_int, + pub fo_select: extern fn(file: *mut file, a: ::c_int, b: *mut ::c_ushort, + c: extern fn()) -> ::c_int, + pub fo_close: extern fn(file: *mut file) -> ::c_int, + pub fo_fstat: extern fn(file: *mut file, sstat: *mut ::stat) -> ::c_int, + } + + pub struct file { + pub f_flag: ::c_long, + pub f_count: ::c_int, + pub f_options: ::c_short, + pub f_type: ::c_short, + // Should be pointer to 'vnode' + pub f_data: *mut ::c_void, + pub f_offset: ::c_longlong, + pub f_dir_off: ::c_long, + // Should be pointer to 'cred' + pub f_cred: *mut ::c_void, + #[cfg(libc_union)] + pub f_lock: _kernel_simple_lock, + #[cfg(libc_union)] + pub f_offset_lock: _kernel_simple_lock, + pub f_vinfo: ::caddr_t, + pub f_ops: *mut fileops_t, + pub f_parentp: ::caddr_t, + pub f_fnamep: ::caddr_t, + pub f_fdata: [::c_char; 160], + } + + #[cfg(libc_union)] + pub union __ld_info_file { + pub _ldinfo_fd: ::c_int, + pub _ldinfo_fp: *mut file, + pub _core_offset: ::c_long, + } + + pub struct ld_info { + pub ldinfo_next: ::c_uint, + pub ldinfo_flags: ::c_uint, + #[cfg(libc_union)] + pub _file: __ld_info_file, + pub ldinfo_textorg: *mut ::c_void, + pub ldinfo_textsize: ::c_ulong, + pub ldinfo_dataorg: *mut ::c_void, + pub ldinfo_datasize: ::c_ulong, + pub ldinfo_filename: [::c_char; 2], + } + + #[cfg(libc_union)] + pub union __pollfd_ext_u { + pub addr: *mut ::c_void, + pub data32: u32, + pub data: u64, + } + + pub struct pollfd_ext { + pub fd: ::c_int, + pub events: ::c_ushort, + pub revents: ::c_ushort, + #[cfg(libc_union)] + pub data: __pollfd_ext_u, + } +} + +cfg_if! { + if #[cfg(feature = "extra_traits")] { + #[cfg(libc_union)] + impl PartialEq for sigval { + fn eq(&self, other: &sigval) -> bool { + unsafe { + self.sival_ptr == other.sival_ptr + && self.sival_int == other.sival_int + } + } + } + #[cfg(libc_union)] + impl Eq for sigval {} + #[cfg(libc_union)] + impl ::fmt::Debug for sigval { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("sigval") + .field("sival_ptr", unsafe { &self.sival_ptr }) + .field("sival_int", unsafe { &self.sival_int }) + .finish() + } + } + #[cfg(libc_union)] + impl ::hash::Hash for sigval { + fn hash(&self, state: &mut H) { + unsafe { + self.sival_ptr.hash(state); + self.sival_int.hash(state); + } + } + } + + impl PartialEq for siginfo_t { + fn eq(&self, other: &siginfo_t) -> bool { + #[cfg(libc_union)] + let value_eq = self.si_value == other.si_value; + #[cfg(not(libc_union))] + let value_eq = true; + self.si_signo == other.si_signo + && self.si_errno == other.si_errno + && self.si_code == other.si_code + && self.si_pid == other.si_pid + && self.si_uid == other.si_uid + && self.si_status == other.si_status + && self.si_addr == other.si_addr + && self.si_band == other.si_band + && self.__si_flags == other.__si_flags + && value_eq + } + } + impl Eq for siginfo_t {} + impl ::fmt::Debug for siginfo_t { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("siginfo_t"); + struct_formatter.field("si_signo", &self.si_signo); + struct_formatter.field("si_errno", &self.si_errno); + struct_formatter.field("si_code", &self.si_code); + struct_formatter.field("si_pid", &self.si_pid); + struct_formatter.field("si_uid", &self.si_uid); + struct_formatter.field("si_status", &self.si_status); + struct_formatter.field("si_addr", &self.si_addr); + struct_formatter.field("si_band", &self.si_band); + #[cfg(libc_union)] + struct_formatter.field("si_value", &self.si_value); + struct_formatter.field("__si_flags", &self.__si_flags); + struct_formatter.finish() + } + } + impl ::hash::Hash for siginfo_t { + fn hash(&self, state: &mut H) { + self.si_signo.hash(state); + self.si_errno.hash(state); + self.si_code.hash(state); + self.si_pid.hash(state); + self.si_uid.hash(state); + self.si_status.hash(state); + self.si_addr.hash(state); + self.si_band.hash(state); + #[cfg(libc_union)] + self.si_value.hash(state); + self.__si_flags.hash(state); + } + } + + #[cfg(libc_union)] + impl PartialEq for _kernel_simple_lock { + fn eq(&self, other: &_kernel_simple_lock) -> bool { + unsafe { + self._slock == other._slock + && self._slockp == other._slockp + } + } + } + #[cfg(libc_union)] + impl Eq for _kernel_simple_lock {} + #[cfg(libc_union)] + impl ::fmt::Debug for _kernel_simple_lock { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("sigval") + .field("_slock", unsafe { &self._slock }) + .field("_slockp", unsafe { &self._slockp }) + .finish() + } + } + #[cfg(libc_union)] + impl ::hash::Hash for _kernel_simple_lock { + fn hash(&self, state: &mut H) { + unsafe { + self._slock.hash(state); + self._slockp.hash(state); + } + } + } + + impl PartialEq for fileops_t { + fn eq(&self, other: &fileops_t) -> bool { + self.fo_rw == other.fo_rw + && self.fo_ioctl == other.fo_ioctl + && self.fo_select == other.fo_select + && self.fo_close == other.fo_close + && self.fo_fstat == other.fo_fstat + } + } + impl Eq for fileops_t {} + impl ::fmt::Debug for fileops_t { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("fileops_t"); + struct_formatter.field("fo_rw", &self.fo_rw); + struct_formatter.field("fo_ioctl", &self.fo_ioctl); + struct_formatter.field("fo_select", &self.fo_select); + struct_formatter.field("fo_close", &self.fo_close); + struct_formatter.field("fo_fstat", &self.fo_fstat); + struct_formatter.finish() + } + } + impl ::hash::Hash for fileops_t { + fn hash(&self, state: &mut H) { + self.fo_rw.hash(state); + self.fo_ioctl.hash(state); + self.fo_select.hash(state); + self.fo_close.hash(state); + self.fo_fstat.hash(state); + } + } + + impl PartialEq for file { + fn eq(&self, other: &file) -> bool { + #[cfg(libc_union)] + let lock_eq = self.f_lock == other.f_lock + && self.f_offset_lock == other.f_offset_lock; + #[cfg(not(libc_union))] + let lock_eq = true; + self.f_flag == other.f_flag + && self.f_count == other.f_count + && self.f_options == other.f_options + && self.f_type == other.f_type + && self.f_data == other.f_data + && self.f_offset == other.f_offset + && self.f_dir_off == other.f_dir_off + && self.f_cred == other.f_cred + && self.f_vinfo == other.f_vinfo + && self.f_ops == other.f_ops + && self.f_parentp == other.f_parentp + && self.f_fnamep == other.f_fnamep + && self.f_fdata == other.f_fdata + && lock_eq + } + } + impl Eq for file {} + impl ::fmt::Debug for file { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("file"); + struct_formatter.field("f_flag", &self.f_flag); + struct_formatter.field("f_count", &self.f_count); + struct_formatter.field("f_options", &self.f_options); + struct_formatter.field("f_type", &self.f_type); + struct_formatter.field("f_data", &self.f_data); + struct_formatter.field("f_offset", &self.f_offset); + struct_formatter.field("f_dir_off", &self.f_dir_off); + struct_formatter.field("f_cred", &self.f_cred); + #[cfg(libc_union)] + struct_formatter.field("f_lock", &self.f_lock); + #[cfg(libc_union)] + struct_formatter.field("f_offset_lock", &self.f_offset_lock); + struct_formatter.field("f_vinfo", &self.f_vinfo); + struct_formatter.field("f_ops", &self.f_ops); + struct_formatter.field("f_parentp", &self.f_parentp); + struct_formatter.field("f_fnamep", &self.f_fnamep); + struct_formatter.field("f_fdata", &self.f_fdata); + struct_formatter.finish() + } + } + impl ::hash::Hash for file { + fn hash(&self, state: &mut H) { + self.f_flag.hash(state); + self.f_count.hash(state); + self.f_options.hash(state); + self.f_type.hash(state); + self.f_data.hash(state); + self.f_offset.hash(state); + self.f_dir_off.hash(state); + self.f_cred.hash(state); + #[cfg(libc_union)] + self.f_lock.hash(state); + #[cfg(libc_union)] + self.f_offset_lock.hash(state); + self.f_vinfo.hash(state); + self.f_ops.hash(state); + self.f_parentp.hash(state); + self.f_fnamep.hash(state); + self.f_fdata.hash(state); + } + } + + #[cfg(libc_union)] + impl PartialEq for __ld_info_file { + fn eq(&self, other: &__ld_info_file) -> bool { + unsafe { + self._ldinfo_fd == other._ldinfo_fd + && self._ldinfo_fp == other._ldinfo_fp + && self._core_offset == other._core_offset + } + } + } + #[cfg(libc_union)] + impl Eq for __ld_info_file {} + #[cfg(libc_union)] + impl ::fmt::Debug for __ld_info_file { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("__ld_info_file") + .field("_ldinfo_fd", unsafe { &self._ldinfo_fd }) + .field("_ldinfo_fp", unsafe { &self._ldinfo_fp }) + .field("_core_offset", unsafe { &self._core_offset }) + .finish() + } + } + #[cfg(libc_union)] + impl ::hash::Hash for __ld_info_file { + fn hash(&self, state: &mut H) { + unsafe { + self._ldinfo_fd.hash(state); + self._ldinfo_fp.hash(state); + self._core_offset.hash(state); + } + } + } + + impl PartialEq for ld_info { + fn eq(&self, other: &ld_info) -> bool { + #[cfg(libc_union)] + let file_eq = self._file == other._file; + #[cfg(not(libc_union))] + let file_eq = true; + self.ldinfo_next == other.ldinfo_next + && self.ldinfo_flags == other.ldinfo_flags + && self.ldinfo_textorg == other.ldinfo_textorg + && self.ldinfo_textsize == other.ldinfo_textsize + && self.ldinfo_dataorg == other.ldinfo_dataorg + && self.ldinfo_datasize == other.ldinfo_datasize + && self.ldinfo_filename == other.ldinfo_filename + && file_eq + } + } + impl Eq for ld_info {} + impl ::fmt::Debug for ld_info { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("ld_info"); + struct_formatter.field("ldinfo_next", &self.ldinfo_next); + struct_formatter.field("ldinfo_flags", &self.ldinfo_flags); + struct_formatter.field("ldinfo_textorg", &self.ldinfo_textorg); + struct_formatter.field("ldinfo_textsize", &self.ldinfo_textsize); + struct_formatter.field("ldinfo_dataorg", &self.ldinfo_dataorg); + struct_formatter.field("ldinfo_datasize", &self.ldinfo_datasize); + struct_formatter.field("ldinfo_filename", &self.ldinfo_filename); + #[cfg(libc_union)] + struct_formatter.field("_file", &self._file); + struct_formatter.finish() + } + } + impl ::hash::Hash for ld_info { + fn hash(&self, state: &mut H) { + self.ldinfo_next.hash(state); + self.ldinfo_flags.hash(state); + self.ldinfo_textorg.hash(state); + self.ldinfo_textsize.hash(state); + self.ldinfo_dataorg.hash(state); + self.ldinfo_datasize.hash(state); + self.ldinfo_filename.hash(state); + #[cfg(libc_union)] + self._file.hash(state); + } + } + + #[cfg(libc_union)] + impl PartialEq for __pollfd_ext_u { + fn eq(&self, other: &__pollfd_ext_u) -> bool { + unsafe { + self.addr == other.addr + && self.data32 == other.data32 + && self.data == other.data + } + } + } + #[cfg(libc_union)] + impl Eq for __pollfd_ext_u {} + #[cfg(libc_union)] + impl ::fmt::Debug for __pollfd_ext_u { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("__pollfd_ext_u") + .field("addr", unsafe { &self.addr }) + .field("data32", unsafe { &self.data32 }) + .field("data", unsafe { &self.data }) + .finish() + } + } + #[cfg(libc_union)] + impl ::hash::Hash for __pollfd_ext_u { + fn hash(&self, state: &mut H) { + unsafe { + self.addr.hash(state); + self.data.hash(state); + self.data32.hash(state); + } + } + } + + impl PartialEq for pollfd_ext { + fn eq(&self, other: &pollfd_ext) -> bool { + #[cfg(libc_union)] + let data_eq = self.data == other.data; + #[cfg(not(libc_union))] + let data_eq = true; + self.fd == other.fd + && self.events == other.events + && self.revents == other.revents + && data_eq + } + } + impl Eq for pollfd_ext {} + impl ::fmt::Debug for pollfd_ext { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + let mut struct_formatter = f.debug_struct("pollfd_ext"); + struct_formatter.field("fd", &self.fd); + struct_formatter.field("events", &self.events); + struct_formatter.field("revents", &self.revents); + #[cfg(libc_union)] + struct_formatter.field("data", &self.data); + struct_formatter.finish() + } + } + impl ::hash::Hash for pollfd_ext { + fn hash(&self, state: &mut H) { + self.fd.hash(state); + self.events.hash(state); + self.revents.hash(state); + #[cfg(libc_union)] + self.data.hash(state); + } + } + } +} + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __mt_word: [0, 2, 0, 0, 0, 0, 0, 0], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __cv_word: [0, 0, 0, 0, 2, 0], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __rw_word: [2, 0, 0, 0, 0, 0, 0, 0, 0, 0], +}; +pub const RLIM_INFINITY: ::c_ulong = 0x7fffffffffffffff; + +extern "C" { + pub fn getsystemcfg(label: ::c_int) -> ::c_ulong; +} diff --git a/bash-5.1/vendor/libc/src/unix/bsd/apple/b64/aarch64/align.rs b/bash-5.1/vendor/libc/src/unix/bsd/apple/b64/aarch64/align.rs index 131e15b..29db97e 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/apple/b64/aarch64/align.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/apple/b64/aarch64/align.rs @@ -15,6 +15,7 @@ s! { pub uc_link: *mut ::ucontext_t, pub uc_mcsize: usize, pub uc_mcontext: mcontext_t, + __mcontext_data: __darwin_mcontext64, } pub struct __darwin_mcontext64 { diff --git a/bash-5.1/vendor/libc/src/unix/bsd/apple/long_array.rs b/bash-5.1/vendor/libc/src/unix/bsd/apple/long_array.rs new file mode 100644 index 0000000..4c56a27 --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/bsd/apple/long_array.rs @@ -0,0 +1,8 @@ +s! { + pub struct ctl_info { + pub ctl_id: u32, + pub ctl_name: [::c_char; MAX_KCTL_NAME], + } +} + +pub const MAX_KCTL_NAME: usize = 96; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/apple/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/apple/mod.rs index bd69d8a..ed30286 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/apple/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/apple/mod.rs @@ -53,6 +53,8 @@ pub type host_info64_t = *mut integer_t; pub type processor_flavor_t = ::c_int; pub type thread_flavor_t = natural_t; pub type thread_inspect_t = ::mach_port_t; +pub type thread_act_t = ::mach_port_t; +pub type thread_act_array_t = *mut ::thread_act_t; pub type policy_t = ::c_int; pub type mach_vm_address_t = u64; pub type mach_vm_offset_t = u64; @@ -64,6 +66,9 @@ pub type memory_object_offset_t = ::c_ulonglong; pub type vm_inherit_t = ::c_uint; pub type vm_prot_t = ::c_int; +pub type ledger_t = ::mach_port_t; +pub type ledger_array_t = *mut ::ledger_t; + pub type iconv_t = *mut ::c_void; pub type processor_cpu_load_info_t = *mut processor_cpu_load_info; @@ -114,6 +119,15 @@ pub type thread_throughput_qos_policy_t = *mut thread_throughput_qos_policy; pub type pthread_introspection_hook_t = extern "C" fn(event: ::c_uint, thread: ::pthread_t, addr: *mut ::c_void, size: ::size_t); +pub type pthread_jit_write_callback_t = ::Option ::c_int>; + +pub type os_unfair_lock = os_unfair_lock_s; +pub type os_unfair_lock_t = *mut os_unfair_lock; + +pub type os_log_t = *mut ::c_void; +pub type os_log_type_t = u8; +pub type os_signpost_id_t = u64; +pub type os_signpost_type_t = u8; pub type vm_statistics_t = *mut vm_statistics; pub type vm_statistics_data_t = vm_statistics; @@ -121,6 +135,7 @@ pub type vm_statistics64_t = *mut vm_statistics64; pub type vm_statistics64_data_t = vm_statistics64; pub type task_t = ::mach_port_t; +pub type task_inspect_t = ::mach_port_t; pub type sysdir_search_path_enumeration_state = ::c_uint; @@ -131,6 +146,9 @@ pub type CCRNGStatus = ::CCCryptorStatus; pub type copyfile_state_t = *mut ::c_void; pub type copyfile_flags_t = u32; +pub type attrgroup_t = u32; +pub type vol_capabilities_set_t = [u32; 4]; + deprecated_mach! { pub type mach_timebase_info_data_t = mach_timebase_info; } @@ -672,6 +690,13 @@ s! { pub s_addr: ::in_addr_t, } + // net/ndrv.h + pub struct sockaddr_ndrv { + pub snd_len: ::c_uchar, + pub snd_family: ::c_uchar, + pub snd_name: [::c_uchar; 16] // IFNAMSIZ from if.h + } + // sys/socket.h pub struct sa_endpoints_t { @@ -968,6 +993,39 @@ s! { pub uuid: ::uuid_t, pub offset: u32, } + + pub struct attrlist { + pub bitmapcount: ::c_ushort, + pub reserved: u16, + pub commonattr: attrgroup_t, + pub volattr: attrgroup_t, + pub dirattr: attrgroup_t, + pub fileattr: attrgroup_t, + pub forkattr: attrgroup_t, + } + + pub struct attrreference_t { + pub attr_dataoffset: i32, + pub attr_length: u32, + } + + pub struct vol_capabilities_attr_t { + pub capabilities: vol_capabilities_set_t, + pub valid: vol_capabilities_set_t, + } + + pub struct attribute_set_t { + pub commonattr: attrgroup_t, + pub volattr: attrgroup_t, + pub dirattr: attrgroup_t, + pub fileattr: attrgroup_t, + pub forkattr: attrgroup_t, + } + + pub struct vol_attributes_attr_t { + pub validattr: attribute_set_t, + pub nativeattr: attribute_set_t, + } } s_no_extra_traits! { @@ -1038,7 +1096,8 @@ s_no_extra_traits! { pub f_fstypename: [::c_char; 16], pub f_mntonname: [::c_char; 1024], pub f_mntfromname: [::c_char; 1024], - pub f_reserved: [u32; 8], + pub f_flags_ext: u32, + pub f_reserved: [u32; 7], } pub struct dirent { @@ -1244,6 +1303,10 @@ s_no_extra_traits! { pub l2p_contigbytes: ::off_t, pub l2p_devoffset: ::off_t, } + + pub struct os_unfair_lock_s { + _os_unfair_lock_opaque: u32, + } } impl siginfo_t { @@ -2525,6 +2588,27 @@ cfg_if! { l2p_devoffset.hash(state); } } + impl PartialEq for os_unfair_lock { + fn eq(&self, other: &os_unfair_lock) -> bool { + self._os_unfair_lock_opaque == other._os_unfair_lock_opaque + } + } + + impl Eq for os_unfair_lock {} + + impl ::fmt::Debug for os_unfair_lock { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("os_unfair_lock") + .field("_os_unfair_lock_opaque", &self._os_unfair_lock_opaque) + .finish() + } + } + + impl ::hash::Hash for os_unfair_lock { + fn hash(&self, state: &mut H) { + self._os_unfair_lock_opaque.hash(state); + } + } } } @@ -2640,6 +2724,8 @@ pub const EOF: ::c_int = -1; pub const SEEK_SET: ::c_int = 0; pub const SEEK_CUR: ::c_int = 1; pub const SEEK_END: ::c_int = 2; +pub const SEEK_HOLE: ::c_int = 3; +pub const SEEK_DATA: ::c_int = 4; pub const _IOFBF: ::c_int = 0; pub const _IONBF: ::c_int = 2; pub const _IOLBF: ::c_int = 1; @@ -2657,11 +2743,13 @@ pub const _PC_PIPE_BUF: ::c_int = 6; pub const _PC_CHOWN_RESTRICTED: ::c_int = 7; pub const _PC_NO_TRUNC: ::c_int = 8; pub const _PC_VDISABLE: ::c_int = 9; -pub const O_DSYNC: ::c_int = 0x400000; -pub const O_NOCTTY: ::c_int = 0x20000; -pub const O_CLOEXEC: ::c_int = 0x1000000; -pub const O_DIRECTORY: ::c_int = 0x100000; -pub const O_SYMLINK: ::c_int = 0x200000; +pub const O_EVTONLY: ::c_int = 0x00008000; +pub const O_NOCTTY: ::c_int = 0x00020000; +pub const O_DIRECTORY: ::c_int = 0x00100000; +pub const O_SYMLINK: ::c_int = 0x00200000; +pub const O_DSYNC: ::c_int = 0x00400000; +pub const O_CLOEXEC: ::c_int = 0x01000000; +pub const O_NOFOLLOW_ANY: ::c_int = 0x20000000; pub const S_IFIFO: mode_t = 4096; pub const S_IFCHR: mode_t = 8192; pub const S_IFBLK: mode_t = 24576; @@ -3466,6 +3554,7 @@ pub const pseudo_AF_RTIP: ::c_int = 22; pub const AF_IPX: ::c_int = 23; pub const AF_SIP: ::c_int = 24; pub const pseudo_AF_PIP: ::c_int = 25; +pub const AF_NDRV: ::c_int = 27; pub const AF_ISDN: ::c_int = 28; pub const AF_E164: ::c_int = AF_ISDN; pub const pseudo_AF_KEY: ::c_int = 29; @@ -3508,6 +3597,7 @@ pub const PF_SIP: ::c_int = AF_SIP; pub const PF_IPX: ::c_int = AF_IPX; pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; pub const PF_PIP: ::c_int = pseudo_AF_PIP; +pub const PF_NDRV: ::c_int = AF_NDRV; pub const PF_ISDN: ::c_int = AF_ISDN; pub const PF_KEY: ::c_int = pseudo_AF_KEY; pub const PF_INET6: ::c_int = AF_INET6; @@ -3552,6 +3642,7 @@ pub const IP_ADD_SOURCE_MEMBERSHIP: ::c_int = 70; pub const IP_DROP_SOURCE_MEMBERSHIP: ::c_int = 71; pub const IP_BLOCK_SOURCE: ::c_int = 72; pub const IP_UNBLOCK_SOURCE: ::c_int = 73; +pub const IPV6_BOUND_IF: ::c_int = 125; pub const TCP_NOPUSH: ::c_int = 4; pub const TCP_NOOPT: ::c_int = 8; @@ -3779,6 +3870,11 @@ pub const _SC_TRACE_NAME_MAX: ::c_int = 128; pub const _SC_TRACE_SYS_MAX: ::c_int = 129; pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 130; pub const _SC_PASS_MAX: ::c_int = 131; +// `confstr` keys (only the values guaranteed by `man confstr`). +pub const _CS_PATH: ::c_int = 1; +pub const _CS_DARWIN_USER_DIR: ::c_int = 65536; +pub const _CS_DARWIN_USER_TEMP_DIR: ::c_int = 65537; +pub const _CS_DARWIN_USER_CACHE_DIR: ::c_int = 65538; pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; @@ -3800,6 +3896,20 @@ pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { __opaque: [0; __PTHREAD_RWLOCK_SIZE__], }; +pub const OS_UNFAIR_LOCK_INIT: os_unfair_lock = os_unfair_lock { + _os_unfair_lock_opaque: 0, +}; + +pub const OS_LOG_TYPE_DEFAULT: ::os_log_type_t = 0x00; +pub const OS_LOG_TYPE_INFO: ::os_log_type_t = 0x01; +pub const OS_LOG_TYPE_DEBUG: ::os_log_type_t = 0x02; +pub const OS_LOG_TYPE_ERROR: ::os_log_type_t = 0x10; +pub const OS_LOG_TYPE_FAULT: ::os_log_type_t = 0x11; + +pub const OS_SIGNPOST_EVENT: ::os_signpost_type_t = 0x00; +pub const OS_SIGNPOST_INTERVAL_BEGIN: ::os_signpost_type_t = 0x01; +pub const OS_SIGNPOST_INTERVAL_END: ::os_signpost_type_t = 0x02; + pub const MINSIGSTKSZ: ::size_t = 32768; pub const SIGSTKSZ: ::size_t = 131072; @@ -4661,6 +4771,145 @@ pub const COPYFILE_CONTINUE: ::c_int = 0; pub const COPYFILE_SKIP: ::c_int = 1; pub const COPYFILE_QUIT: ::c_int = 2; +// +pub const ATTR_BIT_MAP_COUNT: ::c_ushort = 5; +pub const FSOPT_NOFOLLOW: u32 = 0x1; +pub const FSOPT_NOFOLLOW_ANY: u32 = 0x800; +pub const FSOPT_REPORT_FULLSIZE: u32 = 0x4; +pub const FSOPT_PACK_INVAL_ATTRS: u32 = 0x8; +pub const FSOPT_ATTR_CMN_EXTENDED: u32 = 0x20; +pub const FSOPT_RETURN_REALDEV: u32 = 0x200; +pub const ATTR_CMN_NAME: attrgroup_t = 0x00000001; +pub const ATTR_CMN_DEVID: attrgroup_t = 0x00000002; +pub const ATTR_CMN_FSID: attrgroup_t = 0x00000004; +pub const ATTR_CMN_OBJTYPE: attrgroup_t = 0x00000008; +pub const ATTR_CMN_OBJTAG: attrgroup_t = 0x00000010; +pub const ATTR_CMN_OBJID: attrgroup_t = 0x00000020; +pub const ATTR_CMN_OBJPERMANENTID: attrgroup_t = 0x00000040; +pub const ATTR_CMN_PAROBJID: attrgroup_t = 0x00000080; +pub const ATTR_CMN_SCRIPT: attrgroup_t = 0x00000100; +pub const ATTR_CMN_CRTIME: attrgroup_t = 0x00000200; +pub const ATTR_CMN_MODTIME: attrgroup_t = 0x00000400; +pub const ATTR_CMN_CHGTIME: attrgroup_t = 0x00000800; +pub const ATTR_CMN_ACCTIME: attrgroup_t = 0x00001000; +pub const ATTR_CMN_BKUPTIME: attrgroup_t = 0x00002000; +pub const ATTR_CMN_FNDRINFO: attrgroup_t = 0x00004000; +pub const ATTR_CMN_OWNERID: attrgroup_t = 0x00008000; +pub const ATTR_CMN_GRPID: attrgroup_t = 0x00010000; +pub const ATTR_CMN_ACCESSMASK: attrgroup_t = 0x00020000; +pub const ATTR_CMN_FLAGS: attrgroup_t = 0x00040000; +pub const ATTR_CMN_GEN_COUNT: attrgroup_t = 0x00080000; +pub const ATTR_CMN_DOCUMENT_ID: attrgroup_t = 0x00100000; +pub const ATTR_CMN_USERACCESS: attrgroup_t = 0x00200000; +pub const ATTR_CMN_EXTENDED_SECURITY: attrgroup_t = 0x00400000; +pub const ATTR_CMN_UUID: attrgroup_t = 0x00800000; +pub const ATTR_CMN_GRPUUID: attrgroup_t = 0x01000000; +pub const ATTR_CMN_FILEID: attrgroup_t = 0x02000000; +pub const ATTR_CMN_PARENTID: attrgroup_t = 0x04000000; +pub const ATTR_CMN_FULLPATH: attrgroup_t = 0x08000000; +pub const ATTR_CMN_ADDEDTIME: attrgroup_t = 0x10000000; +pub const ATTR_CMN_DATA_PROTECT_FLAGS: attrgroup_t = 0x40000000; +pub const ATTR_CMN_RETURNED_ATTRS: attrgroup_t = 0x80000000; +pub const ATTR_VOL_FSTYPE: attrgroup_t = 0x00000001; +pub const ATTR_VOL_SIGNATURE: attrgroup_t = 0x00000002; +pub const ATTR_VOL_SIZE: attrgroup_t = 0x00000004; +pub const ATTR_VOL_SPACEFREE: attrgroup_t = 0x00000008; +pub const ATTR_VOL_SPACEAVAIL: attrgroup_t = 0x00000010; +pub const ATTR_VOL_MINALLOCATION: attrgroup_t = 0x00000020; +pub const ATTR_VOL_ALLOCATIONCLUMP: attrgroup_t = 0x00000040; +pub const ATTR_VOL_IOBLOCKSIZE: attrgroup_t = 0x00000080; +pub const ATTR_VOL_OBJCOUNT: attrgroup_t = 0x00000100; +pub const ATTR_VOL_FILECOUNT: attrgroup_t = 0x00000200; +pub const ATTR_VOL_DIRCOUNT: attrgroup_t = 0x00000400; +pub const ATTR_VOL_MAXOBJCOUNT: attrgroup_t = 0x00000800; +pub const ATTR_VOL_MOUNTPOINT: attrgroup_t = 0x00001000; +pub const ATTR_VOL_NAME: attrgroup_t = 0x00002000; +pub const ATTR_VOL_MOUNTFLAGS: attrgroup_t = 0x00004000; +pub const ATTR_VOL_MOUNTEDDEVICE: attrgroup_t = 0x00008000; +pub const ATTR_VOL_ENCODINGSUSED: attrgroup_t = 0x00010000; +pub const ATTR_VOL_CAPABILITIES: attrgroup_t = 0x00020000; +pub const ATTR_VOL_UUID: attrgroup_t = 0x00040000; +pub const ATTR_VOL_SPACEUSED: attrgroup_t = 0x00800000; +pub const ATTR_VOL_QUOTA_SIZE: attrgroup_t = 0x10000000; +pub const ATTR_VOL_RESERVED_SIZE: attrgroup_t = 0x20000000; +pub const ATTR_VOL_ATTRIBUTES: attrgroup_t = 0x40000000; +pub const ATTR_VOL_INFO: attrgroup_t = 0x80000000; +pub const ATTR_DIR_LINKCOUNT: attrgroup_t = 0x00000001; +pub const ATTR_DIR_ENTRYCOUNT: attrgroup_t = 0x00000002; +pub const ATTR_DIR_MOUNTSTATUS: attrgroup_t = 0x00000004; +pub const ATTR_DIR_ALLOCSIZE: attrgroup_t = 0x00000008; +pub const ATTR_DIR_IOBLOCKSIZE: attrgroup_t = 0x00000010; +pub const ATTR_DIR_DATALENGTH: attrgroup_t = 0x00000020; +pub const ATTR_FILE_LINKCOUNT: attrgroup_t = 0x00000001; +pub const ATTR_FILE_TOTALSIZE: attrgroup_t = 0x00000002; +pub const ATTR_FILE_ALLOCSIZE: attrgroup_t = 0x00000004; +pub const ATTR_FILE_IOBLOCKSIZE: attrgroup_t = 0x00000008; +pub const ATTR_FILE_DEVTYPE: attrgroup_t = 0x00000020; +pub const ATTR_FILE_FORKCOUNT: attrgroup_t = 0x00000080; +pub const ATTR_FILE_FORKLIST: attrgroup_t = 0x00000100; +pub const ATTR_FILE_DATALENGTH: attrgroup_t = 0x00000200; +pub const ATTR_FILE_DATAALLOCSIZE: attrgroup_t = 0x00000400; +pub const ATTR_FILE_RSRCLENGTH: attrgroup_t = 0x00001000; +pub const ATTR_FILE_RSRCALLOCSIZE: attrgroup_t = 0x00002000; +pub const ATTR_CMNEXT_RELPATH: attrgroup_t = 0x00000004; +pub const ATTR_CMNEXT_PRIVATESIZE: attrgroup_t = 0x00000008; +pub const ATTR_CMNEXT_LINKID: attrgroup_t = 0x00000010; +pub const ATTR_CMNEXT_NOFIRMLINKPATH: attrgroup_t = 0x00000020; +pub const ATTR_CMNEXT_REALDEVID: attrgroup_t = 0x00000040; +pub const ATTR_CMNEXT_REALFSID: attrgroup_t = 0x00000080; +pub const ATTR_CMNEXT_CLONEID: attrgroup_t = 0x00000100; +pub const ATTR_CMNEXT_EXT_FLAGS: attrgroup_t = 0x00000200; +pub const ATTR_CMNEXT_RECURSIVE_GENCOUNT: attrgroup_t = 0x00000400; +pub const DIR_MNTSTATUS_MNTPOINT: u32 = 0x1; +pub const VOL_CAPABILITIES_FORMAT: usize = 0; +pub const VOL_CAPABILITIES_INTERFACES: usize = 1; +pub const VOL_CAP_FMT_PERSISTENTOBJECTIDS: attrgroup_t = 0x00000001; +pub const VOL_CAP_FMT_SYMBOLICLINKS: attrgroup_t = 0x00000002; +pub const VOL_CAP_FMT_HARDLINKS: attrgroup_t = 0x00000004; +pub const VOL_CAP_FMT_JOURNAL: attrgroup_t = 0x00000008; +pub const VOL_CAP_FMT_JOURNAL_ACTIVE: attrgroup_t = 0x00000010; +pub const VOL_CAP_FMT_NO_ROOT_TIMES: attrgroup_t = 0x00000020; +pub const VOL_CAP_FMT_SPARSE_FILES: attrgroup_t = 0x00000040; +pub const VOL_CAP_FMT_ZERO_RUNS: attrgroup_t = 0x00000080; +pub const VOL_CAP_FMT_CASE_SENSITIVE: attrgroup_t = 0x00000100; +pub const VOL_CAP_FMT_CASE_PRESERVING: attrgroup_t = 0x00000200; +pub const VOL_CAP_FMT_FAST_STATFS: attrgroup_t = 0x00000400; +pub const VOL_CAP_FMT_2TB_FILESIZE: attrgroup_t = 0x00000800; +pub const VOL_CAP_FMT_OPENDENYMODES: attrgroup_t = 0x00001000; +pub const VOL_CAP_FMT_HIDDEN_FILES: attrgroup_t = 0x00002000; +pub const VOL_CAP_FMT_PATH_FROM_ID: attrgroup_t = 0x00004000; +pub const VOL_CAP_FMT_NO_VOLUME_SIZES: attrgroup_t = 0x00008000; +pub const VOL_CAP_FMT_DECMPFS_COMPRESSION: attrgroup_t = 0x00010000; +pub const VOL_CAP_FMT_64BIT_OBJECT_IDS: attrgroup_t = 0x00020000; +pub const VOL_CAP_FMT_DIR_HARDLINKS: attrgroup_t = 0x00040000; +pub const VOL_CAP_FMT_DOCUMENT_ID: attrgroup_t = 0x00080000; +pub const VOL_CAP_FMT_WRITE_GENERATION_COUNT: attrgroup_t = 0x00100000; +pub const VOL_CAP_FMT_NO_IMMUTABLE_FILES: attrgroup_t = 0x00200000; +pub const VOL_CAP_FMT_NO_PERMISSIONS: attrgroup_t = 0x00400000; +pub const VOL_CAP_FMT_SHARED_SPACE: attrgroup_t = 0x00800000; +pub const VOL_CAP_FMT_VOL_GROUPS: attrgroup_t = 0x01000000; +pub const VOL_CAP_FMT_SEALED: attrgroup_t = 0x02000000; +pub const VOL_CAP_INT_SEARCHFS: attrgroup_t = 0x00000001; +pub const VOL_CAP_INT_ATTRLIST: attrgroup_t = 0x00000002; +pub const VOL_CAP_INT_NFSEXPORT: attrgroup_t = 0x00000004; +pub const VOL_CAP_INT_READDIRATTR: attrgroup_t = 0x00000008; +pub const VOL_CAP_INT_EXCHANGEDATA: attrgroup_t = 0x00000010; +pub const VOL_CAP_INT_COPYFILE: attrgroup_t = 0x00000020; +pub const VOL_CAP_INT_ALLOCATE: attrgroup_t = 0x00000040; +pub const VOL_CAP_INT_VOL_RENAME: attrgroup_t = 0x00000080; +pub const VOL_CAP_INT_ADVLOCK: attrgroup_t = 0x00000100; +pub const VOL_CAP_INT_FLOCK: attrgroup_t = 0x00000200; +pub const VOL_CAP_INT_EXTENDED_SECURITY: attrgroup_t = 0x00000400; +pub const VOL_CAP_INT_USERACCESS: attrgroup_t = 0x00000800; +pub const VOL_CAP_INT_MANLOCK: attrgroup_t = 0x00001000; +pub const VOL_CAP_INT_NAMEDSTREAMS: attrgroup_t = 0x00002000; +pub const VOL_CAP_INT_EXTENDED_ATTR: attrgroup_t = 0x00004000; +pub const VOL_CAP_INT_CLONE: attrgroup_t = 0x00010000; +pub const VOL_CAP_INT_SNAPSHOT: attrgroup_t = 0x00020000; +pub const VOL_CAP_INT_RENAME_SWAP: attrgroup_t = 0x00040000; +pub const VOL_CAP_INT_RENAME_EXCL: attrgroup_t = 0x00080000; +pub const VOL_CAP_INT_RENAME_OPENFAIL: attrgroup_t = 0x00100000; + cfg_if! { if #[cfg(libc_const_extern_fn)] { const fn __DARWIN_ALIGN32(p: usize) -> usize { @@ -4672,6 +4921,16 @@ cfg_if! { const __DARWIN_ALIGNBYTES32: usize = ::mem::size_of::() - 1; p + __DARWIN_ALIGNBYTES32 & !__DARWIN_ALIGNBYTES32 } + } else { + fn __DARWIN_ALIGN32(p: usize) -> usize { + let __DARWIN_ALIGNBYTES32: usize = ::mem::size_of::() - 1; + p + __DARWIN_ALIGNBYTES32 & !__DARWIN_ALIGNBYTES32 + } + } +} + +cfg_if! { + if #[cfg(libc_const_size_of)] { pub const THREAD_EXTENDED_POLICY_COUNT: mach_msg_type_number_t = (::mem::size_of::() / ::mem::size_of::()) as mach_msg_type_number_t; @@ -4712,10 +4971,6 @@ cfg_if! { (::mem::size_of::() / ::mem::size_of::()) as mach_msg_type_number_t; } else { - fn __DARWIN_ALIGN32(p: usize) -> usize { - let __DARWIN_ALIGNBYTES32: usize = ::mem::size_of::() - 1; - p + __DARWIN_ALIGNBYTES32 & !__DARWIN_ALIGNBYTES32 - } pub const THREAD_EXTENDED_POLICY_COUNT: mach_msg_type_number_t = 1; pub const THREAD_TIME_CONSTRAINT_POLICY_COUNT: mach_msg_type_number_t = 4; pub const THREAD_PRECEDENCE_POLICY_COUNT: mach_msg_type_number_t = 1; @@ -4768,6 +5023,18 @@ f! { pub {const} fn VM_MAKE_TAG(id: u8) -> u32 { (id as u32) << 24u32 } + + pub fn major(dev: dev_t) -> i32 { + (dev >> 24) & 0xff + } + + pub fn minor(dev: dev_t) -> i32 { + dev & 0xffffff + } + + pub fn makedev(major: i32, minor: i32) -> dev_t { + (major << 24) | minor + } } safe_f! { @@ -4823,6 +5090,11 @@ extern "C" { pub fn fchflags(fd: ::c_int, flags: ::c_uint) -> ::c_int; pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + #[cfg_attr( + all(target_os = "macos", target_arch = "x86"), + link_name = "confstr$UNIX2003" + )] + pub fn confstr(name: ::c_int, buf: *mut ::c_char, len: ::size_t) -> ::size_t; pub fn lio_listio( mode: ::c_int, aiocb_list: *const *mut aiocb, @@ -4983,8 +5255,34 @@ extern "C" { ) -> *mut ::c_void; pub fn pthread_jit_write_protect_np(enabled: ::c_int); pub fn pthread_jit_write_protect_supported_np() -> ::c_int; + // An array of pthread_jit_write_with_callback_np must declare + // the list of callbacks e.g. + // #[link_section = "__DATA_CONST,__pth_jit_func"] + // static callbacks: [libc::pthread_jit_write_callback_t; 2] = [native_jit_write_cb, + // std::mem::transmute::(std::ptr::null())]; + // (a handy PTHREAD_JIT_WRITE_CALLBACK_NP macro for other languages). + pub fn pthread_jit_write_with_callback_np( + callback: ::pthread_jit_write_callback_t, + ctx: *mut ::c_void, + ) -> ::c_int; + pub fn pthread_jit_write_freeze_callbacks_np(); pub fn pthread_cpu_number_np(cpu_number_out: *mut ::size_t) -> ::c_int; + pub fn os_unfair_lock_lock(lock: os_unfair_lock_t); + pub fn os_unfair_lock_trylock(lock: os_unfair_lock_t) -> bool; + pub fn os_unfair_lock_unlock(lock: os_unfair_lock_t); + pub fn os_unfair_lock_assert_owner(lock: os_unfair_lock_t); + pub fn os_unfair_lock_assert_not_owner(lock: os_unfair_lock_t); + + pub fn os_log_create(subsystem: *const ::c_char, category: *const ::c_char) -> ::os_log_t; + pub fn os_log_type_enabled(oslog: ::os_log_t, tpe: ::os_log_type_t) -> bool; + pub fn os_signpost_id_make_with_pointer( + log: ::os_log_t, + ptr: *const ::c_void, + ) -> ::os_signpost_id_t; + pub fn os_signpost_id_generate(log: ::os_log_t) -> ::os_signpost_id_t; + pub fn os_signpost_enabled(log: ::os_log_t) -> bool; + pub fn thread_policy_set( thread: thread_t, flavor: thread_policy_flavor_t, @@ -5004,6 +5302,8 @@ extern "C" { thread_info_out: thread_info_t, thread_info_outCnt: *mut mach_msg_type_number_t, ) -> kern_return_t; + #[cfg_attr(doc, doc(alias = "__errno_location"))] + #[cfg_attr(doc, doc(alias = "errno"))] pub fn __error() -> *mut ::c_int; pub fn backtrace(buf: *mut *mut ::c_void, sz: ::c_int) -> ::c_int; pub fn backtrace_symbols(addrs: *const *mut ::c_void, sz: ::c_int) -> *mut *mut ::c_char; @@ -5480,6 +5780,19 @@ extern "C" { task_info_out: task_info_t, task_info_count: *mut mach_msg_type_number_t, ) -> ::kern_return_t; + pub fn task_create( + target_task: ::task_t, + ledgers: ::ledger_array_t, + ledgersCnt: ::mach_msg_type_number_t, + inherit_memory: ::boolean_t, + child_task: *mut ::task_t, + ) -> ::kern_return_t; + pub fn task_terminate(target_task: ::task_t) -> ::kern_return_t; + pub fn task_threads( + target_task: ::task_inspect_t, + act_list: *mut ::thread_act_array_t, + act_listCnt: *mut ::mach_msg_type_number_t, + ) -> ::kern_return_t; pub fn host_statistics( host_priv: host_t, flavor: host_flavor_t, @@ -5498,6 +5811,61 @@ extern "C" { ) -> ::sysdir_search_path_enumeration_state; pub static vm_page_size: vm_size_t; + + pub fn getattrlist( + path: *const ::c_char, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: u32, + ) -> ::c_int; + pub fn fgetattrlist( + fd: ::c_int, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: u32, + ) -> ::c_int; + pub fn getattrlistat( + fd: ::c_int, + path: *const ::c_char, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: ::c_ulong, + ) -> ::c_int; + pub fn setattrlist( + path: *const ::c_char, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: u32, + ) -> ::c_int; + pub fn fsetattrlist( + fd: ::c_int, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: u32, + ) -> ::c_int; + pub fn setattrlistat( + dir_fd: ::c_int, + path: *const ::c_char, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: u32, + ) -> ::c_int; + pub fn getattrlistbulk( + dirfd: ::c_int, + attrList: *mut ::c_void, + attrBuf: *mut ::c_void, + attrBufSize: ::size_t, + options: u64, + ) -> ::c_int; + + pub fn malloc_size(ptr: *const ::c_void) -> ::size_t; + pub fn malloc_good_size(size: ::size_t) -> ::size_t; } pub unsafe fn mach_task_self() -> ::mach_port_t { @@ -5508,17 +5876,31 @@ cfg_if! { if #[cfg(target_os = "macos")] { extern "C" { pub fn clock_settime(clock_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + } + } +} +cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + extern "C" { pub fn memmem( haystack: *const ::c_void, haystacklen: ::size_t, needle: *const ::c_void, needlelen: ::size_t, ) -> *mut ::c_void; + pub fn task_set_info(target_task: ::task_t, + flavor: ::task_flavor_t, + task_info_in: ::task_info_t, + task_info_inCnt: ::mach_msg_type_number_t + ) -> ::kern_return_t; } } } -#[link(name = "iconv")] +// These require a dependency on `libiconv`, and including this when built as +// part of `std` means every Rust program gets it. Ideally we would have a link +// modifier to only include these if they are used, but we do not. +#[cfg_attr(not(feature = "rustc-dep-of-std"), link(name = "iconv"))] extern "C" { pub fn iconv_open(tocode: *const ::c_char, fromcode: *const ::c_char) -> iconv_t; pub fn iconv( diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/dragonfly/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/dragonfly/mod.rs index d563628..418ac3d 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/dragonfly/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/dragonfly/mod.rs @@ -34,6 +34,17 @@ pub type pthread_spinlock_t = ::uintptr_t; pub type segsz_t = usize; +pub type vm_prot_t = u8; +pub type vm_maptype_t = u8; +pub type vm_inherit_t = i8; +pub type vm_subsys_t = ::c_int; +pub type vm_eflags_t = ::c_uint; + +pub type vm_map_t = *mut __c_anonymous_vm_map; +pub type vm_map_entry_t = *mut vm_map_entry; + +pub type pmap = __c_anonymous_pmap; + #[cfg_attr(feature = "extra_traits", derive(Debug))] pub enum sem {} impl ::Copy for sem {} @@ -336,6 +347,50 @@ s! { kp_spare: [::c_int; 2], } + pub struct __c_anonymous_vm_map { + _priv: [::uintptr_t; 36], + } + + pub struct vm_map_entry { + _priv: [::uintptr_t; 15], + pub eflags: ::vm_eflags_t, + pub maptype: ::vm_maptype_t, + pub protection: ::vm_prot_t, + pub max_protection: ::vm_prot_t, + pub inheritance: ::vm_inherit_t, + pub wired_count: ::c_int, + pub id: ::vm_subsys_t, + } + + pub struct __c_anonymous_pmap { + _priv1: [::uintptr_t; 32], + _priv2: [::uintptr_t; 32], + _priv3: [::uintptr_t; 32], + _priv4: [::uintptr_t; 32], + _priv5: [::uintptr_t; 8], + } + + pub struct vmspace { + vm_map: __c_anonymous_vm_map, + vm_pmap: __c_anonymous_pmap, + pub vm_flags: ::c_int, + pub vm_shm: *mut ::c_char, + pub vm_rssize: ::segsz_t, + pub vm_swrss: ::segsz_t, + pub vm_tsize: ::segsz_t, + pub vm_dsize: ::segsz_t, + pub vm_ssize: ::segsz_t, + pub vm_taddr: *mut ::c_char, + pub vm_daddr: *mut ::c_char, + pub vm_maxsaddr: *mut ::c_char, + pub vm_minsaddr: *mut ::c_char, + _unused1: ::c_int, + _unused2: ::c_int, + pub vm_pagesupply: ::c_int, + pub vm_holdcnt: ::c_uint, + pub vm_refcnt: ::c_uint, + } + pub struct cpuctl_msr_args_t { pub msr: ::c_int, pub data: u64, @@ -1011,6 +1066,8 @@ pub const CPUCTL_MSRSBIT: ::c_int = 0xc0106305; pub const CPUCTL_MSRCBIT: ::c_int = 0xc0106306; pub const CPUCTL_CPUID_COUNT: ::c_int = 0xc0106307; +pub const CPU_SETSIZE: ::size_t = ::mem::size_of::<::cpumask_t>() * 8; + pub const EVFILT_READ: i16 = -1; pub const EVFILT_WRITE: i16 = -2; pub const EVFILT_AIO: i16 = -3; @@ -1516,6 +1573,15 @@ safe_f! { pub {const} fn WIFSIGNALED(status: ::c_int) -> bool { (status & 0o177) != 0o177 && (status & 0o177) != 0 } + + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= major << 8; + dev |= minor; + dev + } } extern "C" { @@ -1613,6 +1679,20 @@ extern "C" { pub fn freezero(ptr: *mut ::c_void, size: ::size_t); } +#[link(name = "kvm")] +extern "C" { + pub fn kvm_vm_map_entry_first( + kvm: *mut ::kvm_t, + map: vm_map_t, + entry: vm_map_entry_t, + ) -> vm_map_entry_t; + pub fn kvm_vm_map_entry_next( + kvm: *mut ::kvm_t, + map: vm_map_entry_t, + entry: vm_map_entry_t, + ) -> vm_map_entry_t; +} + cfg_if! { if #[cfg(libc_thread_local)] { mod errno; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs index 1af555f..aaa0435 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs @@ -434,6 +434,14 @@ pub const MINCORE_SUPER: ::c_int = 0x20; /// max length of devicename pub const SPECNAMELEN: ::c_int = 63; +safe_f! { + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + (major << 8) | minor + } +} + extern "C" { // Return type ::c_int was removed in FreeBSD 12 pub fn setgrent() -> ::c_int; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs index 848db33..e7f8ad7 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs @@ -449,6 +449,19 @@ pub const KI_NSPARE_PTR: usize = 6; pub const MINCORE_SUPER: ::c_int = 0x20; +safe_f! { + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= ((major & 0xffffff00) as dev_t) << 32; + dev |= ((major & 0x000000ff) as dev_t) << 8; + dev |= ((minor & 0x0000ff00) as dev_t) << 24; + dev |= ((minor & 0xffff00ff) as dev_t) << 0; + dev + } +} + extern "C" { pub fn setgrent(); pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) -> ::c_int; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs index a929f9d..bcd0900 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs @@ -468,6 +468,19 @@ pub const DOMAINSET_POLICY_INTERLEAVE: ::c_int = 4; pub const MINCORE_SUPER: ::c_int = 0x20; +safe_f! { + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= ((major & 0xffffff00) as dev_t) << 32; + dev |= ((major & 0x000000ff) as dev_t) << 8; + dev |= ((minor & 0x0000ff00) as dev_t) << 24; + dev |= ((minor & 0xffff00ff) as dev_t) << 0; + dev + } +} + extern "C" { pub fn setgrent(); pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) -> ::c_int; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs index c655d55..9da6696 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs @@ -468,6 +468,19 @@ pub const DOMAINSET_POLICY_INTERLEAVE: ::c_int = 4; pub const MINCORE_SUPER: ::c_int = 0x60; +safe_f! { + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= ((major & 0xffffff00) as dev_t) << 32; + dev |= ((major & 0x000000ff) as dev_t) << 8; + dev |= ((minor & 0x0000ff00) as dev_t) << 24; + dev |= ((minor & 0xffff00ff) as dev_t) << 0; + dev + } +} + extern "C" { pub fn setgrent(); pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) -> ::c_int; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/mod.rs index 8d27d88..08fd5a5 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/freebsd/mod.rs @@ -44,9 +44,7 @@ pub type fhandle_t = fhandle; pub type au_id_t = ::uid_t; pub type au_asid_t = ::pid_t; -// It's an alias over "struct __kvm_t". However, its fields aren't supposed to be used directly, -// making the type definition system dependent. Better not bind it exactly. -pub type kvm_t = ::c_void; +pub type cpusetid_t = ::c_int; #[cfg_attr(feature = "extra_traits", derive(Debug, Hash, PartialEq, Eq))] #[repr(u32)] @@ -994,6 +992,12 @@ s! { pub _flags: u32, pub _clockid: u32, } + + pub struct shm_largepage_conf { + pub psind: ::c_int, + pub alloc_policy: ::c_int, + __pad: [::c_int; 10], + } } s_no_extra_traits! { @@ -1894,6 +1898,9 @@ pub const LIO_READV: ::c_int = 6; pub const DEVSTAT_N_TRANS_FLAGS: ::c_int = 4; pub const DEVSTAT_NAME_LEN: ::c_int = 16; +// sys/cpuset.h +pub const CPU_SETSIZE: ::c_int = 256; + pub const SIGEV_THREAD_ID: ::c_int = 4; pub const EXTATTR_NAMESPACE_EMPTY: ::c_int = 0; @@ -2253,6 +2260,7 @@ pub const FIONWRITE: ::c_ulong = 0x40046677; pub const FIONSPACE: ::c_ulong = 0x40046676; pub const FIOSEEKDATA: ::c_ulong = 0xc0086661; pub const FIOSEEKHOLE: ::c_ulong = 0xc0086662; +pub const FIOSSHMLPGCNF: ::c_ulong = 0x80306664; pub const JAIL_API_VERSION: u32 = 2; pub const JAIL_CREATE: ::c_int = 0x01; @@ -2512,6 +2520,8 @@ pub const IFCAP_TOE4: ::c_int = 0x04000; pub const IFCAP_TOE6: ::c_int = 0x08000; /// interface hw can filter vlan tag pub const IFCAP_VLAN_HWFILTER: ::c_int = 0x10000; +/// can do SIOCGIFCAPNV/SIOCSIFCAPNV +pub const IFCAP_NV: ::c_int = 0x20000; /// can do IFCAP_TSO on VLANs pub const IFCAP_VLAN_HWTSO: ::c_int = 0x40000; /// the runtime link state is dynamic @@ -2547,7 +2557,7 @@ pub const IFCAP_TSO: ::c_int = IFCAP_TSO4 | IFCAP_TSO6; pub const IFCAP_WOL: ::c_int = IFCAP_WOL_UCAST | IFCAP_WOL_MCAST | IFCAP_WOL_MAGIC; pub const IFCAP_TOE: ::c_int = IFCAP_TOE4 | IFCAP_TOE6; pub const IFCAP_TXTLS: ::c_int = IFCAP_TXTLS4 | IFCAP_TXTLS6; -pub const IFCAP_CANTCHANGE: ::c_int = IFCAP_NETMAP; +pub const IFCAP_CANTCHANGE: ::c_int = IFCAP_NETMAP | IFCAP_NV; pub const IFQ_MAXLEN: ::c_int = 50; pub const IFNET_SLOWHZ: ::c_int = 1; @@ -3231,30 +3241,67 @@ pub const KKST_STATE_RUNNING: ::c_int = 2; pub const PRI_MIN: ::c_int = 0; pub const PRI_MAX: ::c_int = 255; pub const PRI_MIN_ITHD: ::c_int = PRI_MIN; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PRI_MAX_ITHD: ::c_int = PRI_MIN_REALTIME - 1; pub const PI_REALTIME: ::c_int = PRI_MIN_ITHD + 0; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PI_AV: ::c_int = PRI_MIN_ITHD + 4; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PI_NET: ::c_int = PRI_MIN_ITHD + 8; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PI_DISK: ::c_int = PRI_MIN_ITHD + 12; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PI_TTY: ::c_int = PRI_MIN_ITHD + 16; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PI_DULL: ::c_int = PRI_MIN_ITHD + 20; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PI_SOFT: ::c_int = PRI_MIN_ITHD + 24; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PRI_MIN_REALTIME: ::c_int = 48; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PRI_MAX_REALTIME: ::c_int = PRI_MIN_KERN - 1; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PRI_MIN_KERN: ::c_int = 80; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PRI_MAX_KERN: ::c_int = PRI_MIN_TIMESHARE - 1; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PSWP: ::c_int = PRI_MIN_KERN + 0; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PVM: ::c_int = PRI_MIN_KERN + 4; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PINOD: ::c_int = PRI_MIN_KERN + 8; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PRIBIO: ::c_int = PRI_MIN_KERN + 12; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PVFS: ::c_int = PRI_MIN_KERN + 16; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PZERO: ::c_int = PRI_MIN_KERN + 20; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PSOCK: ::c_int = PRI_MIN_KERN + 24; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PWAIT: ::c_int = PRI_MIN_KERN + 28; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PLOCK: ::c_int = PRI_MIN_KERN + 32; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PPAUSE: ::c_int = PRI_MIN_KERN + 36; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const PRI_MIN_TIMESHARE: ::c_int = 120; pub const PRI_MAX_TIMESHARE: ::c_int = PRI_MIN_IDLE - 1; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] +#[allow(deprecated)] pub const PUSER: ::c_int = PRI_MIN_TIMESHARE; pub const PRI_MIN_IDLE: ::c_int = 224; pub const PRI_MAX_IDLE: ::c_int = PRI_MAX; @@ -3352,24 +3399,32 @@ pub const TDF_CANSWAP: ::c_int = 0x00000040; pub const TDF_KTH_SUSP: ::c_int = 0x00000100; pub const TDF_ALLPROCSUSP: ::c_int = 0x00000200; pub const TDF_BOUNDARY: ::c_int = 0x00000400; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_ASTPENDING: ::c_int = 0x00000800; pub const TDF_SBDRY: ::c_int = 0x00002000; pub const TDF_UPIBLOCKED: ::c_int = 0x00004000; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_NEEDSUSPCHK: ::c_int = 0x00008000; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_NEEDRESCHED: ::c_int = 0x00010000; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_NEEDSIGCHK: ::c_int = 0x00020000; pub const TDF_NOLOAD: ::c_int = 0x00040000; pub const TDF_SERESTART: ::c_int = 0x00080000; pub const TDF_THRWAKEUP: ::c_int = 0x00100000; pub const TDF_SEINTR: ::c_int = 0x00200000; pub const TDF_SWAPINREQ: ::c_int = 0x00400000; +#[deprecated(since = "0.2.133", note = "Removed in FreeBSD 14")] pub const TDF_UNUSED23: ::c_int = 0x00800000; pub const TDF_SCHED0: ::c_int = 0x01000000; pub const TDF_SCHED1: ::c_int = 0x02000000; pub const TDF_SCHED2: ::c_int = 0x04000000; pub const TDF_SCHED3: ::c_int = 0x08000000; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_ALRMPEND: ::c_int = 0x10000000; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_PROFPEND: ::c_int = 0x20000000; +#[deprecated(since = "0.2.133", note = "Not stable across OS versions")] pub const TDF_MACPEND: ::c_int = 0x40000000; pub const TDB_SUSPEND: ::c_int = 0x00000001; @@ -3661,6 +3716,19 @@ pub const CPUCLOCK_WHICH_TID: ::c_int = 1; pub const MFD_CLOEXEC: ::c_uint = 0x00000001; pub const MFD_ALLOW_SEALING: ::c_uint = 0x00000002; pub const MFD_HUGETLB: ::c_uint = 0x00000004; +pub const MFD_HUGE_MASK: ::c_uint = 0xFC000000; +pub const MFD_HUGE_64KB: ::c_uint = 16 << 26; +pub const MFD_HUGE_512KB: ::c_uint = 19 << 26; +pub const MFD_HUGE_1MB: ::c_uint = 20 << 26; +pub const MFD_HUGE_2MB: ::c_uint = 21 << 26; +pub const MFD_HUGE_8MB: ::c_uint = 23 << 26; +pub const MFD_HUGE_16MB: ::c_uint = 24 << 26; +pub const MFD_HUGE_32MB: ::c_uint = 25 << 26; +pub const MFD_HUGE_256MB: ::c_uint = 28 << 26; +pub const MFD_HUGE_512MB: ::c_uint = 29 << 26; +pub const MFD_HUGE_1GB: ::c_uint = 30 << 26; +pub const MFD_HUGE_2GB: ::c_uint = 31 << 26; +pub const MFD_HUGE_16GB: ::c_uint = 34 << 26; pub const SHM_LARGEPAGE_ALLOC_DEFAULT: ::c_int = 0; pub const SHM_LARGEPAGE_ALLOC_NOWAIT: ::c_int = 1; @@ -3695,6 +3763,16 @@ pub const UMTX_OP_ROBUST_LISTS: ::c_int = 26; pub const UMTX_ABSTIME: u32 = 1; +pub const CPU_LEVEL_ROOT: ::c_int = 1; +pub const CPU_LEVEL_CPUSET: ::c_int = 2; +pub const CPU_LEVEL_WHICH: ::c_int = 3; + +pub const CPU_WHICH_TID: ::c_int = 1; +pub const CPU_WHICH_PID: ::c_int = 2; +pub const CPU_WHICH_CPUSET: ::c_int = 3; +pub const CPU_WHICH_IRQ: ::c_int = 4; +pub const CPU_WHICH_JAIL: ::c_int = 5; + const_fn! { {const} fn _ALIGN(p: usize) -> usize { (p + _ALIGNBYTES) & !_ALIGNBYTES @@ -3772,21 +3850,21 @@ f! { } pub fn CPU_SET(cpu: usize, cpuset: &mut cpuset_t) -> () { - let bitset_bits = ::mem::size_of::<::c_long>(); + let bitset_bits = 8 * ::mem::size_of::<::c_long>(); let (idx, offset) = (cpu / bitset_bits, cpu % bitset_bits); cpuset.__bits[idx] |= 1 << offset; () } pub fn CPU_CLR(cpu: usize, cpuset: &mut cpuset_t) -> () { - let bitset_bits = ::mem::size_of::<::c_long>(); + let bitset_bits = 8 * ::mem::size_of::<::c_long>(); let (idx, offset) = (cpu / bitset_bits, cpu % bitset_bits); cpuset.__bits[idx] &= !(1 << offset); () } pub fn CPU_ISSET(cpu: usize, cpuset: &cpuset_t) -> bool { - let bitset_bits = ::mem::size_of::<::c_long>(); + let bitset_bits = 8 * ::mem::size_of::<::c_long>(); let (idx, offset) = (cpu / bitset_bits, cpu % bitset_bits); 0 != cpuset.__bits[idx] & (1 << offset) } @@ -3794,9 +3872,9 @@ f! { pub fn CPU_COUNT(cpuset: &cpuset_t) -> ::c_int { let mut s: u32 = 0; let cpuset_size = ::mem::size_of::(); - let bitset_bits = ::mem::size_of::<::c_long>(); + let bitset_size = ::mem::size_of::<::c_long>(); - for i in cpuset.__bits[..(cpuset_size / bitset_bits)].iter() { + for i in cpuset.__bits[..(cpuset_size / bitset_size)].iter() { s += i.count_ones(); }; s as ::c_int @@ -3839,6 +3917,8 @@ cfg_if! { } extern "C" { + #[cfg_attr(doc, doc(alias = "__errno_location"))] + #[cfg_attr(doc, doc(alias = "errno"))] pub fn __error() -> *mut ::c_int; pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; @@ -3974,6 +4054,7 @@ extern "C" { infop: *mut ::siginfo_t, options: ::c_int, ) -> ::c_int; + pub fn ptsname_r(fd: ::c_int, buf: *mut ::c_char, buflen: ::size_t) -> ::c_int; pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; @@ -4182,6 +4263,14 @@ extern "C" { setsize: ::size_t, mask: *const cpuset_t, ) -> ::c_int; + pub fn cpuset(setid: *mut ::cpusetid_t) -> ::c_int; + pub fn cpuset_getid( + level: cpulevel_t, + which: cpuwhich_t, + id: ::id_t, + setid: *mut ::cpusetid_t, + ) -> ::c_int; + pub fn cpuset_setid(which: cpuwhich_t, id: ::id_t, setid: ::cpusetid_t) -> ::c_int; pub fn cap_enter() -> ::c_int; pub fn cap_getmode(modep: *mut ::c_uint) -> ::c_int; pub fn __cap_rights_init(version: ::c_int, rights: *mut cap_rights_t, ...) @@ -4272,71 +4361,39 @@ extern "C" { #[link(name = "kvm")] extern "C" { - pub fn kvm_open( - execfile: *const ::c_char, - corefile: *const ::c_char, - swapfile: *const ::c_char, - flags: ::c_int, - errstr: *const ::c_char, - ) -> *mut kvm_t; - pub fn kvm_close(kd: *mut kvm_t) -> ::c_int; - pub fn kvm_dpcpu_setcpu(kd: *mut kvm_t, cpu: ::c_uint) -> ::c_int; - pub fn kvm_getargv(kd: *mut kvm_t, p: *const kinfo_proc, nchr: ::c_int) -> *mut *mut ::c_char; - pub fn kvm_getcptime(kd: *mut kvm_t, cp_time: *mut ::c_long) -> ::c_int; - pub fn kvm_getenvv(kd: *mut kvm_t, p: *const kinfo_proc, nchr: ::c_int) -> *mut *mut ::c_char; - pub fn kvm_geterr(kd: *mut kvm_t) -> *mut ::c_char; - pub fn kvm_getloadavg(kd: *mut kvm_t, loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; - pub fn kvm_getmaxcpu(kd: *mut kvm_t) -> ::c_int; - pub fn kvm_getncpus(kd: *mut kvm_t) -> ::c_int; - pub fn kvm_getpcpu(kd: *mut kvm_t, cpu: ::c_int) -> *mut ::c_void; - pub fn kvm_counter_u64_fetch(kd: *mut kvm_t, base: ::c_ulong) -> u64; - pub fn kvm_getprocs( - kd: *mut kvm_t, - op: ::c_int, - arg: ::c_int, - cnt: *mut ::c_int, - ) -> *mut kinfo_proc; + pub fn kvm_dpcpu_setcpu(kd: *mut ::kvm_t, cpu: ::c_uint) -> ::c_int; + pub fn kvm_getargv(kd: *mut ::kvm_t, p: *const kinfo_proc, nchr: ::c_int) + -> *mut *mut ::c_char; + pub fn kvm_getcptime(kd: *mut ::kvm_t, cp_time: *mut ::c_long) -> ::c_int; + pub fn kvm_getenvv(kd: *mut ::kvm_t, p: *const kinfo_proc, nchr: ::c_int) + -> *mut *mut ::c_char; + pub fn kvm_geterr(kd: *mut ::kvm_t) -> *mut ::c_char; + pub fn kvm_getmaxcpu(kd: *mut ::kvm_t) -> ::c_int; + pub fn kvm_getncpus(kd: *mut ::kvm_t) -> ::c_int; + pub fn kvm_getpcpu(kd: *mut ::kvm_t, cpu: ::c_int) -> *mut ::c_void; + pub fn kvm_counter_u64_fetch(kd: *mut ::kvm_t, base: ::c_ulong) -> u64; pub fn kvm_getswapinfo( - kd: *mut kvm_t, + kd: *mut ::kvm_t, info: *mut kvm_swap, maxswap: ::c_int, flags: ::c_int, ) -> ::c_int; - pub fn kvm_native(kd: *mut kvm_t) -> ::c_int; - pub fn kvm_nlist(kd: *mut kvm_t, nl: *mut nlist) -> ::c_int; - pub fn kvm_nlist2(kd: *mut kvm_t, nl: *mut kvm_nlist) -> ::c_int; - pub fn kvm_openfiles( - execfile: *const ::c_char, - corefile: *const ::c_char, - swapfile: *const ::c_char, - flags: ::c_int, - errbuf: *mut ::c_char, - ) -> *mut kvm_t; - pub fn kvm_read( - kd: *mut kvm_t, - addr: ::c_ulong, - buf: *mut ::c_void, - nbytes: ::size_t, - ) -> ::ssize_t; + pub fn kvm_native(kd: *mut ::kvm_t) -> ::c_int; + pub fn kvm_nlist(kd: *mut ::kvm_t, nl: *mut nlist) -> ::c_int; + pub fn kvm_nlist2(kd: *mut ::kvm_t, nl: *mut kvm_nlist) -> ::c_int; pub fn kvm_read_zpcpu( - kd: *mut kvm_t, + kd: *mut ::kvm_t, base: ::c_ulong, buf: *mut ::c_void, size: ::size_t, cpu: ::c_int, ) -> ::ssize_t; pub fn kvm_read2( - kd: *mut kvm_t, + kd: *mut ::kvm_t, addr: kvaddr_t, buf: *mut ::c_void, nbytes: ::size_t, ) -> ::ssize_t; - pub fn kvm_write( - kd: *mut kvm_t, - addr: ::c_ulong, - buf: *const ::c_void, - nbytes: ::size_t, - ) -> ::ssize_t; } #[link(name = "util")] @@ -4486,10 +4543,10 @@ extern "C" { #[link(name = "devstat")] extern "C" { - pub fn devstat_getnumdevs(kd: *mut kvm_t) -> ::c_int; - pub fn devstat_getgeneration(kd: *mut kvm_t) -> ::c_long; - pub fn devstat_getversion(kd: *mut kvm_t) -> ::c_int; - pub fn devstat_checkversion(kd: *mut kvm_t) -> ::c_int; + pub fn devstat_getnumdevs(kd: *mut ::kvm_t) -> ::c_int; + pub fn devstat_getgeneration(kd: *mut ::kvm_t) -> ::c_long; + pub fn devstat_getversion(kd: *mut ::kvm_t) -> ::c_int; + pub fn devstat_checkversion(kd: *mut ::kvm_t) -> ::c_int; pub fn devstat_selectdevs( dev_select: *mut *mut device_selection, num_selected: *mut ::c_int, diff --git a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/mod.rs index b9d29d8..db21597 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/freebsdlike/mod.rs @@ -35,6 +35,10 @@ pub type Elf64_Xword = u64; pub type iconv_t = *mut ::c_void; +// It's an alias over "struct __kvm_t". However, its fields aren't supposed to be used directly, +// making the type definition system dependent. Better not bind it exactly. +pub type kvm_t = ::c_void; + cfg_if! { if #[cfg(target_pointer_width = "64")] { type Elf_Addr = Elf64_Addr; @@ -372,6 +376,10 @@ s! { pub seq: ::c_ushort, pub key: ::key_t, } + + pub struct eui64 { + pub octet: [u8; EUI64_LEN], + } } s_no_extra_traits! { @@ -1325,6 +1333,8 @@ pub const ONLRET: ::tcflag_t = 0x40; pub const CMGROUP_MAX: usize = 16; +pub const EUI64_LEN: usize = 8; + // https://github.com/freebsd/freebsd/blob/master/sys/net/bpf.h pub const BPF_ALIGNMENT: usize = SIZEOF_LONG; @@ -1716,6 +1726,13 @@ extern "C" { pub fn memset_s(s: *mut ::c_void, smax: ::size_t, c: ::c_int, n: ::size_t) -> ::c_int; pub fn gethostid() -> ::c_long; pub fn sethostid(hostid: ::c_long); + + pub fn eui64_aton(a: *const ::c_char, e: *mut eui64) -> ::c_int; + pub fn eui64_ntoa(id: *const eui64, a: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn eui64_ntohost(hostname: *mut ::c_char, len: ::size_t, id: *const eui64) -> ::c_int; + pub fn eui64_hostton(hostname: *const ::c_char, id: *mut eui64) -> ::c_int; + + pub fn eaccess(path: *const ::c_char, mode: ::c_int) -> ::c_int; } #[link(name = "rt")] @@ -1790,6 +1807,44 @@ extern "C" { ) -> ::c_int; } +#[link(name = "kvm")] +extern "C" { + pub fn kvm_open( + execfile: *const ::c_char, + corefile: *const ::c_char, + swapfile: *const ::c_char, + flags: ::c_int, + errstr: *const ::c_char, + ) -> *mut ::kvm_t; + pub fn kvm_close(kd: *mut ::kvm_t) -> ::c_int; + pub fn kvm_getprocs( + kd: *mut ::kvm_t, + op: ::c_int, + arg: ::c_int, + cnt: *mut ::c_int, + ) -> *mut ::kinfo_proc; + pub fn kvm_getloadavg(kd: *mut kvm_t, loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; + pub fn kvm_openfiles( + execfile: *const ::c_char, + corefile: *const ::c_char, + swapfile: *const ::c_char, + flags: ::c_int, + errbuf: *mut ::c_char, + ) -> *mut ::kvm_t; + pub fn kvm_read( + kd: *mut ::kvm_t, + addr: ::c_ulong, + buf: *mut ::c_void, + nbytes: ::size_t, + ) -> ::ssize_t; + pub fn kvm_write( + kd: *mut ::kvm_t, + addr: ::c_ulong, + buf: *const ::c_void, + nbytes: ::size_t, + ) -> ::ssize_t; +} + cfg_if! { if #[cfg(target_os = "freebsd")] { mod freebsd; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/mod.rs index 8ebca09..20e203b 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/mod.rs @@ -449,6 +449,12 @@ pub const TCP_MAXSEG: ::c_int = 2; pub const PIPE_BUF: usize = 512; +// si_code values for SIGBUS signal +pub const BUS_ADRALN: ::c_int = 1; +pub const BUS_ADRERR: ::c_int = 2; +pub const BUS_OBJERR: ::c_int = 3; + +// si_code values for SIGCHLD signal pub const CLD_EXITED: ::c_int = 1; pub const CLD_KILLED: ::c_int = 2; pub const CLD_DUMPED: ::c_int = 3; diff --git a/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/mod.rs index d7d40bd..a7f35ef 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/mod.rs @@ -639,17 +639,6 @@ pub const TIOCM_DSR: ::c_int = 0o0400; pub const TIOCM_CD: ::c_int = TIOCM_CAR; pub const TIOCM_RI: ::c_int = TIOCM_RNG; -// Flags for chflags(2) -pub const UF_SETTABLE: ::c_ulong = 0x0000ffff; -pub const UF_NODUMP: ::c_ulong = 0x00000001; -pub const UF_IMMUTABLE: ::c_ulong = 0x00000002; -pub const UF_APPEND: ::c_ulong = 0x00000004; -pub const UF_OPAQUE: ::c_ulong = 0x00000008; -pub const SF_SETTABLE: ::c_ulong = 0xffff0000; -pub const SF_ARCHIVED: ::c_ulong = 0x00010000; -pub const SF_IMMUTABLE: ::c_ulong = 0x00020000; -pub const SF_APPEND: ::c_ulong = 0x00040000; - pub const TIMER_ABSTIME: ::c_int = 1; #[link(name = "util")] diff --git a/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/netbsd/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/netbsd/mod.rs index 0afff1c..bfe2de0 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/netbsd/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/netbsd/mod.rs @@ -487,6 +487,134 @@ s! { af_arg: [[::c_char; 10]; 24], } + pub struct ki_sigset_t { + pub __bits: [u32; 4], + } + + pub struct kinfo_proc2 { + pub p_forw: u64, + pub p_back: u64, + pub p_paddr: u64, + pub p_addr: u64, + pub p_fd: u64, + pub p_cwdi: u64, + pub p_stats: u64, + pub p_limit: u64, + pub p_vmspace: u64, + pub p_sigacts: u64, + pub p_sess: u64, + pub p_tsess: u64, + pub p_ru: u64, + pub p_eflag: i32, + pub p_exitsig: i32, + pub p_flag: i32, + pub p_pid: i32, + pub p_ppid: i32, + pub p_sid: i32, + pub p__pgid: i32, + pub p_tpgid: i32, + pub p_uid: u32, + pub p_ruid: u32, + pub p_gid: u32, + pub p_rgid: u32, + pub p_groups: [u32; KI_NGROUPS as usize], + pub p_ngroups: i16, + pub p_jobc: i16, + pub p_tdev: u32, + pub p_estcpu: u32, + pub p_rtime_sec: u32, + pub p_rtime_usec: u32, + pub p_cpticks: i32, + pub p_pctcpu: u32, + pub p_swtime: u32, + pub p_slptime: u32, + pub p_schedflags: i32, + pub p_uticks: u64, + pub p_sticks: u64, + pub p_iticks: u64, + pub p_tracep: u64, + pub p_traceflag: i32, + pub p_holdcnt: i32, + pub p_siglist: ki_sigset_t, + pub p_sigmask: ki_sigset_t, + pub p_sigignore: ki_sigset_t, + pub p_sigcatch: ki_sigset_t, + pub p_stat: i8, + pub p_priority: u8, + pub p_usrpri: u8, + pub p_nice: u8, + pub p_xstat: u16, + pub p_acflag: u16, + pub p_comm: [::c_char; KI_MAXCOMLEN as usize], + pub p_wmesg: [::c_char; KI_WMESGLEN as usize], + pub p_wchan: u64, + pub p_login: [::c_char; KI_MAXLOGNAME as usize], + pub p_vm_rssize: i32, + pub p_vm_tsize: i32, + pub p_vm_dsize: i32, + pub p_vm_ssize: i32, + pub p_uvalid: i64, + pub p_ustart_sec: u32, + pub p_ustart_usec: u32, + pub p_uutime_sec: u32, + pub p_uutime_usec: u32, + pub p_ustime_sec: u32, + pub p_ustime_usec: u32, + pub p_uru_maxrss: u64, + pub p_uru_ixrss: u64, + pub p_uru_idrss: u64, + pub p_uru_isrss: u64, + pub p_uru_minflt: u64, + pub p_uru_majflt: u64, + pub p_uru_nswap: u64, + pub p_uru_inblock: u64, + pub p_uru_oublock: u64, + pub p_uru_msgsnd: u64, + pub p_uru_msgrcv: u64, + pub p_uru_nsignals: u64, + pub p_uru_nvcsw: u64, + pub p_uru_nivcsw: u64, + pub p_uctime_sec: u32, + pub p_uctime_usec: u32, + pub p_cpuid: u64, + pub p_realflag: u64, + pub p_nlwps: u64, + pub p_nrlwps: u64, + pub p_realstat: u64, + pub p_svuid: u32, + pub p_svgid: u32, + pub p_ename: [::c_char; KI_MAXEMULLEN as usize], + pub p_vm_vsize: i64, + pub p_vm_msize: i64, + } + + pub struct kinfo_lwp { + pub l_forw: u64, + pub l_back: u64, + pub l_laddr: u64, + pub l_addr: u64, + pub l_lid: i32, + pub l_flag: i32, + pub l_swtime: u32, + pub l_slptime: u32, + pub l_schedflags: i32, + pub l_holdcnt: i32, + pub l_priority: u8, + pub l_usrpri: u8, + pub l_stat: i8, + l_pad1: i8, + l_pad2: i32, + pub l_wmesg: [::c_char; KI_WMESGLEN as usize], + pub l_wchan: u64, + pub l_cpuid: u64, + pub l_rtime_sec: u32, + pub l_rtime_usec: u32, + pub l_cpticks: u32, + pub l_pctcpu: u32, + pub l_pid: u32, + pub l_name: [::c_char; KI_LNAMELEN as usize], + } + pub struct kinfo_vmentry { pub kve_start: u64, pub kve_end: u64, @@ -1440,10 +1568,7 @@ pub const IPPROTO_VRRP: ::c_int = 112; /// Common Address Resolution Protocol pub const IPPROTO_CARP: ::c_int = 112; /// L2TPv3 -// TEMP: Disabled for now; this constant was added to NetBSD on 2017-02-16, -// but isn't yet supported by the NetBSD rumprun kernel image used for -// libc testing. -//pub const IPPROTO_L2TP: ::c_int = 115; +pub const IPPROTO_L2TP: ::c_int = 115; /// SCTP pub const IPPROTO_SCTP: ::c_int = 132; /// PFSYNC @@ -2103,9 +2228,18 @@ pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x20; pub const POSIX_SPAWN_RETURNERROR: ::c_int = 0x40; // Flags for chflags(2) -pub const SF_SNAPSHOT: ::c_ulong = 0x00200000; +pub const SF_APPEND: ::c_ulong = 0x00040000; +pub const SF_ARCHIVED: ::c_ulong = 0x00010000; +pub const SF_IMMUTABLE: ::c_ulong = 0x00020000; pub const SF_LOG: ::c_ulong = 0x00400000; +pub const SF_SETTABLE: ::c_ulong = 0xffff0000; pub const SF_SNAPINVAL: ::c_ulong = 0x00800000; +pub const SF_SNAPSHOT: ::c_ulong = 0x00200000; +pub const UF_APPEND: ::c_ulong = 0x00000004; +pub const UF_IMMUTABLE: ::c_ulong = 0x00000002; +pub const UF_NODUMP: ::c_ulong = 0x00000001; +pub const UF_OPAQUE: ::c_ulong = 0x00000008; +pub const UF_SETTABLE: ::c_ulong = 0x0000ffff; // sys/sysctl.h pub const KVME_PROT_READ: ::c_int = 0x00000001; @@ -2121,6 +2255,49 @@ pub const KVME_FLAG_GROWS_DOWN: ::c_int = 0x000000020; pub const NGROUPS_MAX: ::c_int = 16; +pub const KI_NGROUPS: ::c_int = 16; +pub const KI_MAXCOMLEN: ::c_int = 24; +pub const KI_WMESGLEN: ::c_int = 8; +pub const KI_MAXLOGNAME: ::c_int = 24; +pub const KI_MAXEMULLEN: ::c_int = 16; +pub const KI_LNAMELEN: ::c_int = 20; + +// sys/lwp.h +pub const LSIDL: ::c_int = 1; +pub const LSRUN: ::c_int = 2; +pub const LSSLEEP: ::c_int = 3; +pub const LSSTOP: ::c_int = 4; +pub const LSZOMB: ::c_int = 5; +pub const LSONPROC: ::c_int = 7; +pub const LSSUSPENDED: ::c_int = 8; + +pub const _REG_RDI: ::c_int = 0; +pub const _REG_RSI: ::c_int = 1; +pub const _REG_RDX: ::c_int = 2; +pub const _REG_RCX: ::c_int = 3; +pub const _REG_R8: ::c_int = 4; +pub const _REG_R9: ::c_int = 5; +pub const _REG_R10: ::c_int = 6; +pub const _REG_R11: ::c_int = 7; +pub const _REG_R12: ::c_int = 8; +pub const _REG_R13: ::c_int = 9; +pub const _REG_R14: ::c_int = 10; +pub const _REG_R15: ::c_int = 11; +pub const _REG_RBP: ::c_int = 12; +pub const _REG_RBX: ::c_int = 13; +pub const _REG_RAX: ::c_int = 14; +pub const _REG_GS: ::c_int = 15; +pub const _REG_FS: ::c_int = 16; +pub const _REG_ES: ::c_int = 17; +pub const _REG_DS: ::c_int = 18; +pub const _REG_TRAPNO: ::c_int = 19; +pub const _REG_ERR: ::c_int = 20; +pub const _REG_RIP: ::c_int = 21; +pub const _REG_CS: ::c_int = 22; +pub const _REG_RFLAGS: ::c_int = 23; +pub const _REG_RSP: ::c_int = 24; +pub const _REG_SS: ::c_int = 25; + const_fn! { {const} fn _ALIGN(p: usize) -> usize { (p + _ALIGNBYTES) & !_ALIGNBYTES @@ -2201,6 +2378,16 @@ safe_f! { pub {const} fn WIFCONTINUED(status: ::c_int) -> bool { status == 0xffff } + + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major << 8) & 0x000ff00; + dev |= (minor << 12) & 0xfff00000; + dev |= minor & 0xff; + dev + } } extern "C" { diff --git a/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/openbsd/mod.rs b/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/openbsd/mod.rs index 199473d..506306e 100644 --- a/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/openbsd/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/bsd/netbsdlike/openbsd/mod.rs @@ -1628,6 +1628,21 @@ pub const EPROC_SLEADER: i32 = 0x02; // session leader pub const EPROC_UNVEIL: i32 = 0x04; // has unveil settings pub const EPROC_LKUNVEIL: i32 = 0x08; // unveil is locked +// Flags for chflags(2) +pub const UF_SETTABLE: ::c_uint = 0x0000ffff; +pub const UF_NODUMP: ::c_uint = 0x00000001; +pub const UF_IMMUTABLE: ::c_uint = 0x00000002; +pub const UF_APPEND: ::c_uint = 0x00000004; +pub const UF_OPAQUE: ::c_uint = 0x00000008; +pub const SF_SETTABLE: ::c_uint = 0xffff0000; +pub const SF_ARCHIVED: ::c_uint = 0x00010000; +pub const SF_IMMUTABLE: ::c_uint = 0x00020000; +pub const SF_APPEND: ::c_uint = 0x00040000; + +pub const MNT_WAIT: ::c_int = 1; +pub const MNT_NOWAIT: ::c_int = 2; +pub const MNT_LAZY: ::c_int = 3; + const_fn! { {const} fn _ALIGN(p: usize) -> usize { (p + _ALIGNBYTES) & !_ALIGNBYTES @@ -1684,6 +1699,16 @@ safe_f! { pub {const} fn WIFCONTINUED(status: ::c_int) -> bool { (status & 0o177777) == 0o177777 } + + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major & 0xff) << 8; + dev |= minor & 0xff; + dev |= (minor & 0xffff00) << 8; + dev + } } extern "C" { @@ -1859,6 +1884,8 @@ cfg_if! { // these functions use statfs which uses the union mount_info: pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; + pub fn getmntinfo(mntbufp: *mut *mut ::statfs, flags: ::c_int) -> ::c_int; + pub fn getfsstat(buf: *mut statfs, bufsize: ::size_t, flags: ::c_int) -> ::c_int; } } } diff --git a/bash-5.1/vendor/libc/src/unix/haiku/mod.rs b/bash-5.1/vendor/libc/src/unix/haiku/mod.rs index ab1df72..bb2e035 100644 --- a/bash-5.1/vendor/libc/src/unix/haiku/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/haiku/mod.rs @@ -52,6 +52,9 @@ pub type Elf64_Xword = u64; pub type ENTRY = entry; pub type ACTION = ::c_int; +pub type posix_spawnattr_t = *mut ::c_void; +pub type posix_spawn_file_actions_t = *mut ::c_void; + #[cfg_attr(feature = "extra_traits", derive(Debug))] pub enum timezone {} impl ::Copy for timezone {} @@ -1051,6 +1054,7 @@ pub const LOCK_EX: ::c_int = 0x02; pub const LOCK_NB: ::c_int = 0x04; pub const LOCK_UN: ::c_int = 0x08; +pub const MINSIGSTKSZ: ::size_t = 8192; pub const SIGSTKSZ: ::size_t = 16384; pub const IOV_MAX: ::c_int = 1024; @@ -1067,6 +1071,9 @@ pub const SA_NOMASK: ::c_int = SA_NODEFER; pub const SA_STACK: ::c_int = SA_ONSTACK; pub const SA_ONESHOT: ::c_int = SA_RESETHAND; +pub const SS_ONSTACK: ::c_int = 0x1; +pub const SS_DISABLE: ::c_int = 0x2; + pub const FD_SETSIZE: usize = 1024; pub const RTLD_LOCAL: ::c_int = 0x0; @@ -1225,6 +1232,8 @@ pub const SO_PEERCRED: ::c_int = 0x4000000b; pub const SCM_RIGHTS: ::c_int = 0x01; +pub const SOMAXCONN: ::c_int = 32; + pub const NI_MAXHOST: ::size_t = 1025; pub const WNOHANG: ::c_int = 0x01; @@ -1234,6 +1243,12 @@ pub const WEXITED: ::c_int = 0x08; pub const WSTOPPED: ::c_int = 0x10; pub const WNOWAIT: ::c_int = 0x20; +// si_code values for SIGBUS signal +pub const BUS_ADRALN: ::c_int = 40; +pub const BUS_ADRERR: ::c_int = 41; +pub const BUS_OBJERR: ::c_int = 42; + +// si_code values for SIGCHLD signal pub const CLD_EXITED: ::c_int = 60; pub const CLD_KILLED: ::c_int = 61; pub const CLD_DUMPED: ::c_int = 62; @@ -1432,6 +1447,13 @@ pub const LOG_SERIAL: ::c_int = 16 << 12; pub const LOG_PERROR: ::c_int = 32 << 12; pub const LOG_NOWAIT: ::c_int = 64 << 12; +// spawn.h +pub const POSIX_SPAWN_RESETIDS: ::c_int = 0x01; +pub const POSIX_SPAWN_SETPGROUP: ::c_int = 0x02; +pub const POSIX_SPAWN_SETSIGDEF: ::c_int = 0x10; +pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x20; +pub const POSIX_SPAWN_SETSID: ::c_int = 0x40; + const_fn! { {const} fn CMSG_ALIGN(len: usize) -> usize { len + ::mem::size_of::() - 1 & !(::mem::size_of::() - 1) @@ -1768,8 +1790,6 @@ extern "C" { pub fn endgrent(); pub fn getgrent() -> *mut ::group; pub fn setgrent(); - pub fn setreuid(ruid: ::uid_t, euid: ::uid_t) -> ::c_int; - pub fn setregid(rgid: ::gid_t, egid: ::gid_t) -> ::c_int; pub fn sigwait(set: *const sigset_t, sig: *mut ::c_int) -> ::c_int; pub fn pthread_atfork( prepare: ::Option, @@ -1884,6 +1904,74 @@ extern "C" { pub fn brk(addr: *mut ::c_void) -> ::c_int; pub fn sbrk(increment: ::intptr_t) -> *mut ::c_void; + + pub fn posix_spawn( + pid: *mut ::pid_t, + path: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char, + ) -> ::c_int; + pub fn posix_spawnp( + pid: *mut ::pid_t, + file: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char, + ) -> ::c_int; + + pub fn posix_spawn_file_actions_init(file_actions: *mut posix_spawn_file_actions_t) -> ::c_int; + pub fn posix_spawn_file_actions_destroy( + file_actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addopen( + file_actions: *mut posix_spawn_file_actions_t, + fildes: ::c_int, + path: *const ::c_char, + oflag: ::c_int, + mode: ::mode_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addclose( + file_actions: *mut posix_spawn_file_actions_t, + fildes: ::c_int, + ) -> ::c_int; + pub fn posix_spawn_file_actions_adddup2( + file_actions: *mut posix_spawn_file_actions_t, + fildes: ::c_int, + newfildes: ::c_int, + ) -> ::c_int; + + pub fn posix_spawnattr_init(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_destroy(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_getflags( + attr: *const posix_spawnattr_t, + _flags: *mut ::c_short, + ) -> ::c_int; + pub fn posix_spawnattr_setflags(attr: *mut posix_spawnattr_t, flags: ::c_short) -> ::c_int; + pub fn posix_spawnattr_getpgroup( + attr: *const posix_spawnattr_t, + _pgroup: *mut ::pid_t, + ) -> ::c_int; + pub fn posix_spawnattr_setpgroup(attr: *mut posix_spawnattr_t, pgroup: ::pid_t) -> ::c_int; + pub fn posix_spawnattr_getsigdefault( + attr: *const posix_spawnattr_t, + sigdefault: *mut ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_setsigdefault( + attr: *mut posix_spawnattr_t, + sigdefault: *const ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_getsigmask( + attr: *const posix_spawnattr_t, + _sigmask: *mut ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_setsigmask( + attr: *mut posix_spawnattr_t, + sigmask: *const ::sigset_t, + ) -> ::c_int; + } #[link(name = "bsd")] diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/mod.rs index 0995c54..67d0dac 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/mod.rs @@ -346,6 +346,9 @@ cfg_if! { } else if #[cfg(target_arch = "aarch64")] { mod aarch64; pub use self::aarch64::*; + } else if #[cfg(target_arch = "riscv64")] { + mod riscv64; + pub use self::riscv64::*; } else { // Unknown target_arch } diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/x86_64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/x86_64/mod.rs index df11618..d25b507 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/x86_64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/android/b64/x86_64/mod.rs @@ -350,6 +350,7 @@ cfg_if! { fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { f.debug_struct("user_fpregs_struct") .field("cwd", &self.cwd) + .field("swd", &self.swd) .field("ftw", &self.ftw) .field("fop", &self.fop) .field("rip", &self.rip) @@ -366,6 +367,7 @@ cfg_if! { impl ::hash::Hash for user_fpregs_struct { fn hash(&self, state: &mut H) { self.cwd.hash(state); + self.swd.hash(state); self.ftw.hash(state); self.fop.hash(state); self.rip.hash(state); diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/android/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/android/mod.rs index a57e9b7..67e5eb5 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/android/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/android/mod.rs @@ -2489,6 +2489,8 @@ pub const AF_VSOCK: ::c_int = 40; pub const PF_NFC: ::c_int = AF_NFC; pub const PF_VSOCK: ::c_int = AF_VSOCK; +pub const SOMAXCONN: ::c_int = 128; + // sys/system_properties.h pub const PROP_VALUE_MAX: ::c_int = 92; pub const PROP_NAME_MAX: ::c_int = 32; @@ -2496,6 +2498,227 @@ pub const PROP_NAME_MAX: ::c_int = 32; // sys/prctl.h pub const PR_SET_VMA: ::c_int = 0x53564d41; pub const PR_SET_VMA_ANON_NAME: ::c_int = 0; +pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; +pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; +pub const PR_GET_SECCOMP: ::c_int = 21; +pub const PR_SET_SECCOMP: ::c_int = 22; +pub const PR_GET_TIMING: ::c_int = 13; +pub const PR_SET_TIMING: ::c_int = 14; +pub const PR_TIMING_STATISTICAL: ::c_int = 0; +pub const PR_TIMING_TIMESTAMP: ::c_int = 1; + +// linux/if_addr.h +pub const IFA_UNSPEC: ::c_ushort = 0; +pub const IFA_ADDRESS: ::c_ushort = 1; +pub const IFA_LOCAL: ::c_ushort = 2; +pub const IFA_LABEL: ::c_ushort = 3; +pub const IFA_BROADCAST: ::c_ushort = 4; +pub const IFA_ANYCAST: ::c_ushort = 5; +pub const IFA_CACHEINFO: ::c_ushort = 6; +pub const IFA_MULTICAST: ::c_ushort = 7; + +pub const IFA_F_SECONDARY: u32 = 0x01; +pub const IFA_F_TEMPORARY: u32 = 0x01; +pub const IFA_F_NODAD: u32 = 0x02; +pub const IFA_F_OPTIMISTIC: u32 = 0x04; +pub const IFA_F_DADFAILED: u32 = 0x08; +pub const IFA_F_HOMEADDRESS: u32 = 0x10; +pub const IFA_F_DEPRECATED: u32 = 0x20; +pub const IFA_F_TENTATIVE: u32 = 0x40; +pub const IFA_F_PERMANENT: u32 = 0x80; + +// linux/if_link.h +pub const IFLA_UNSPEC: ::c_ushort = 0; +pub const IFLA_ADDRESS: ::c_ushort = 1; +pub const IFLA_BROADCAST: ::c_ushort = 2; +pub const IFLA_IFNAME: ::c_ushort = 3; +pub const IFLA_MTU: ::c_ushort = 4; +pub const IFLA_LINK: ::c_ushort = 5; +pub const IFLA_QDISC: ::c_ushort = 6; +pub const IFLA_STATS: ::c_ushort = 7; +pub const IFLA_COST: ::c_ushort = 8; +pub const IFLA_PRIORITY: ::c_ushort = 9; +pub const IFLA_MASTER: ::c_ushort = 10; +pub const IFLA_WIRELESS: ::c_ushort = 11; +pub const IFLA_PROTINFO: ::c_ushort = 12; +pub const IFLA_TXQLEN: ::c_ushort = 13; +pub const IFLA_MAP: ::c_ushort = 14; +pub const IFLA_WEIGHT: ::c_ushort = 15; +pub const IFLA_OPERSTATE: ::c_ushort = 16; +pub const IFLA_LINKMODE: ::c_ushort = 17; +pub const IFLA_LINKINFO: ::c_ushort = 18; +pub const IFLA_NET_NS_PID: ::c_ushort = 19; +pub const IFLA_IFALIAS: ::c_ushort = 20; +pub const IFLA_NUM_VF: ::c_ushort = 21; +pub const IFLA_VFINFO_LIST: ::c_ushort = 22; +pub const IFLA_STATS64: ::c_ushort = 23; +pub const IFLA_VF_PORTS: ::c_ushort = 24; +pub const IFLA_PORT_SELF: ::c_ushort = 25; +pub const IFLA_AF_SPEC: ::c_ushort = 26; +pub const IFLA_GROUP: ::c_ushort = 27; +pub const IFLA_NET_NS_FD: ::c_ushort = 28; +pub const IFLA_EXT_MASK: ::c_ushort = 29; +pub const IFLA_PROMISCUITY: ::c_ushort = 30; +pub const IFLA_NUM_TX_QUEUES: ::c_ushort = 31; +pub const IFLA_NUM_RX_QUEUES: ::c_ushort = 32; +pub const IFLA_CARRIER: ::c_ushort = 33; +pub const IFLA_PHYS_PORT_ID: ::c_ushort = 34; +pub const IFLA_CARRIER_CHANGES: ::c_ushort = 35; +pub const IFLA_PHYS_SWITCH_ID: ::c_ushort = 36; +pub const IFLA_LINK_NETNSID: ::c_ushort = 37; +pub const IFLA_PHYS_PORT_NAME: ::c_ushort = 38; +pub const IFLA_PROTO_DOWN: ::c_ushort = 39; +pub const IFLA_GSO_MAX_SEGS: ::c_ushort = 40; +pub const IFLA_GSO_MAX_SIZE: ::c_ushort = 41; +pub const IFLA_PAD: ::c_ushort = 42; +pub const IFLA_XDP: ::c_ushort = 43; +pub const IFLA_EVENT: ::c_ushort = 44; +pub const IFLA_NEW_NETNSID: ::c_ushort = 45; +pub const IFLA_IF_NETNSID: ::c_ushort = 46; +pub const IFLA_TARGET_NETNSID: ::c_ushort = IFLA_IF_NETNSID; +pub const IFLA_CARRIER_UP_COUNT: ::c_ushort = 47; +pub const IFLA_CARRIER_DOWN_COUNT: ::c_ushort = 48; +pub const IFLA_NEW_IFINDEX: ::c_ushort = 49; +pub const IFLA_MIN_MTU: ::c_ushort = 50; +pub const IFLA_MAX_MTU: ::c_ushort = 51; + +pub const IFLA_INFO_UNSPEC: ::c_ushort = 0; +pub const IFLA_INFO_KIND: ::c_ushort = 1; +pub const IFLA_INFO_DATA: ::c_ushort = 2; +pub const IFLA_INFO_XSTATS: ::c_ushort = 3; +pub const IFLA_INFO_SLAVE_KIND: ::c_ushort = 4; +pub const IFLA_INFO_SLAVE_DATA: ::c_ushort = 5; + +// linux/rtnetlink.h +pub const TCA_UNSPEC: ::c_ushort = 0; +pub const TCA_KIND: ::c_ushort = 1; +pub const TCA_OPTIONS: ::c_ushort = 2; +pub const TCA_STATS: ::c_ushort = 3; +pub const TCA_XSTATS: ::c_ushort = 4; +pub const TCA_RATE: ::c_ushort = 5; +pub const TCA_FCNT: ::c_ushort = 6; +pub const TCA_STATS2: ::c_ushort = 7; +pub const TCA_STAB: ::c_ushort = 8; + +pub const RTM_NEWLINK: u16 = 16; +pub const RTM_DELLINK: u16 = 17; +pub const RTM_GETLINK: u16 = 18; +pub const RTM_SETLINK: u16 = 19; +pub const RTM_NEWADDR: u16 = 20; +pub const RTM_DELADDR: u16 = 21; +pub const RTM_GETADDR: u16 = 22; +pub const RTM_NEWROUTE: u16 = 24; +pub const RTM_DELROUTE: u16 = 25; +pub const RTM_GETROUTE: u16 = 26; +pub const RTM_NEWNEIGH: u16 = 28; +pub const RTM_DELNEIGH: u16 = 29; +pub const RTM_GETNEIGH: u16 = 30; +pub const RTM_NEWRULE: u16 = 32; +pub const RTM_DELRULE: u16 = 33; +pub const RTM_GETRULE: u16 = 34; +pub const RTM_NEWQDISC: u16 = 36; +pub const RTM_DELQDISC: u16 = 37; +pub const RTM_GETQDISC: u16 = 38; +pub const RTM_NEWTCLASS: u16 = 40; +pub const RTM_DELTCLASS: u16 = 41; +pub const RTM_GETTCLASS: u16 = 42; +pub const RTM_NEWTFILTER: u16 = 44; +pub const RTM_DELTFILTER: u16 = 45; +pub const RTM_GETTFILTER: u16 = 46; +pub const RTM_NEWACTION: u16 = 48; +pub const RTM_DELACTION: u16 = 49; +pub const RTM_GETACTION: u16 = 50; +pub const RTM_NEWPREFIX: u16 = 52; +pub const RTM_GETMULTICAST: u16 = 58; +pub const RTM_GETANYCAST: u16 = 62; +pub const RTM_NEWNEIGHTBL: u16 = 64; +pub const RTM_GETNEIGHTBL: u16 = 66; +pub const RTM_SETNEIGHTBL: u16 = 67; +pub const RTM_NEWNDUSEROPT: u16 = 68; +pub const RTM_NEWADDRLABEL: u16 = 72; +pub const RTM_DELADDRLABEL: u16 = 73; +pub const RTM_GETADDRLABEL: u16 = 74; +pub const RTM_GETDCB: u16 = 78; +pub const RTM_SETDCB: u16 = 79; +pub const RTM_NEWNETCONF: u16 = 80; +pub const RTM_GETNETCONF: u16 = 82; +pub const RTM_NEWMDB: u16 = 84; +pub const RTM_DELMDB: u16 = 85; +pub const RTM_GETMDB: u16 = 86; +pub const RTM_NEWNSID: u16 = 88; +pub const RTM_DELNSID: u16 = 89; +pub const RTM_GETNSID: u16 = 90; + +pub const RTM_F_NOTIFY: ::c_uint = 0x100; +pub const RTM_F_CLONED: ::c_uint = 0x200; +pub const RTM_F_EQUALIZE: ::c_uint = 0x400; +pub const RTM_F_PREFIX: ::c_uint = 0x800; + +pub const RTA_UNSPEC: ::c_ushort = 0; +pub const RTA_DST: ::c_ushort = 1; +pub const RTA_SRC: ::c_ushort = 2; +pub const RTA_IIF: ::c_ushort = 3; +pub const RTA_OIF: ::c_ushort = 4; +pub const RTA_GATEWAY: ::c_ushort = 5; +pub const RTA_PRIORITY: ::c_ushort = 6; +pub const RTA_PREFSRC: ::c_ushort = 7; +pub const RTA_METRICS: ::c_ushort = 8; +pub const RTA_MULTIPATH: ::c_ushort = 9; +pub const RTA_PROTOINFO: ::c_ushort = 10; // No longer used +pub const RTA_FLOW: ::c_ushort = 11; +pub const RTA_CACHEINFO: ::c_ushort = 12; +pub const RTA_SESSION: ::c_ushort = 13; // No longer used +pub const RTA_MP_ALGO: ::c_ushort = 14; // No longer used +pub const RTA_TABLE: ::c_ushort = 15; +pub const RTA_MARK: ::c_ushort = 16; +pub const RTA_MFC_STATS: ::c_ushort = 17; + +pub const RTN_UNSPEC: ::c_uchar = 0; +pub const RTN_UNICAST: ::c_uchar = 1; +pub const RTN_LOCAL: ::c_uchar = 2; +pub const RTN_BROADCAST: ::c_uchar = 3; +pub const RTN_ANYCAST: ::c_uchar = 4; +pub const RTN_MULTICAST: ::c_uchar = 5; +pub const RTN_BLACKHOLE: ::c_uchar = 6; +pub const RTN_UNREACHABLE: ::c_uchar = 7; +pub const RTN_PROHIBIT: ::c_uchar = 8; +pub const RTN_THROW: ::c_uchar = 9; +pub const RTN_NAT: ::c_uchar = 10; +pub const RTN_XRESOLVE: ::c_uchar = 11; + +pub const RTPROT_UNSPEC: ::c_uchar = 0; +pub const RTPROT_REDIRECT: ::c_uchar = 1; +pub const RTPROT_KERNEL: ::c_uchar = 2; +pub const RTPROT_BOOT: ::c_uchar = 3; +pub const RTPROT_STATIC: ::c_uchar = 4; + +pub const RT_SCOPE_UNIVERSE: ::c_uchar = 0; +pub const RT_SCOPE_SITE: ::c_uchar = 200; +pub const RT_SCOPE_LINK: ::c_uchar = 253; +pub const RT_SCOPE_HOST: ::c_uchar = 254; +pub const RT_SCOPE_NOWHERE: ::c_uchar = 255; + +pub const RT_TABLE_UNSPEC: ::c_uchar = 0; +pub const RT_TABLE_COMPAT: ::c_uchar = 252; +pub const RT_TABLE_DEFAULT: ::c_uchar = 253; +pub const RT_TABLE_MAIN: ::c_uchar = 254; +pub const RT_TABLE_LOCAL: ::c_uchar = 255; + +pub const RTMSG_NEWDEVICE: u32 = 0x11; +pub const RTMSG_DELDEVICE: u32 = 0x12; +pub const RTMSG_NEWROUTE: u32 = 0x21; +pub const RTMSG_DELROUTE: u32 = 0x22; + +// Most `*_SUPER_MAGIC` constants are defined at the `linux_like` level; the +// following are only available on newer Linux versions than the versions +// currently used in CI in some configurations, so we define them here. +cfg_if! { + if #[cfg(not(target_arch = "s390x"))] { + pub const XFS_SUPER_MAGIC: ::c_long = 0x58465342; + } else if #[cfg(target_arch = "s390x")] { + pub const XFS_SUPER_MAGIC: ::c_uint = 0x58465342; + } +} f! { pub fn CMSG_NXTHDR(mhdr: *const msghdr, @@ -2569,12 +2792,6 @@ f! { pub fn minor(dev: ::dev_t) -> ::c_int { ((dev & 0xff) | ((dev >> 12) & 0xfff00)) as ::c_int } - pub fn makedev(ma: ::c_int, mi: ::c_int) -> ::dev_t { - let ma = ma as ::dev_t; - let mi = mi as ::dev_t; - ((ma & 0xfff) << 8) | (mi & 0xff) | ((mi & 0xfff00) << 12) - } - pub fn NLA_ALIGN(len: ::c_int) -> ::c_int { return ((len) + NLA_ALIGNTO - 1) & !(NLA_ALIGNTO - 1) } @@ -2584,6 +2801,15 @@ f! { } } +safe_f! { + pub {const} fn makedev(ma: ::c_uint, mi: ::c_uint) -> ::dev_t { + let ma = ma as ::dev_t; + let mi = mi as ::dev_t; + ((ma & 0xfff) << 8) | (mi & 0xff) | ((mi & 0xfff00) << 12) + } + +} + extern "C" { pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/emscripten/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/emscripten/mod.rs index 5494aad..11fbb31 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/emscripten/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/emscripten/mod.rs @@ -1669,6 +1669,8 @@ pub const PRIO_PROCESS: ::c_int = 0; pub const PRIO_PGRP: ::c_int = 1; pub const PRIO_USER: ::c_int = 2; +pub const SOMAXCONN: ::c_int = 128; + f! { pub fn CMSG_NXTHDR(mhdr: *const msghdr, cmsg: *const cmsghdr) -> *mut cmsghdr { @@ -1738,8 +1740,10 @@ f! { minor |= (dev & 0xffffff00) >> 12; minor as ::c_uint } +} - pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { +safe_f! { + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { let major = major as ::dev_t; let minor = minor as ::dev_t; let mut dev = 0; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/arch/generic/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/arch/generic/mod.rs index 3205799..5265cdd 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/arch/generic/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/arch/generic/mod.rs @@ -104,6 +104,13 @@ cfg_if! { pub const SO_DETACH_REUSEPORT_BPF: ::c_int = 68; } } + +cfg_if! { + if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { + pub const FICLONE: ::c_ulong = 0x40049409; + pub const FICLONERANGE: ::c_ulong = 0x4020940D; + } +} // pub const SO_PREFER_BUSY_POLL: ::c_int = 69; // pub const SO_BUSY_POLL_BUDGET: ::c_int = 70; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/arm/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/arm/mod.rs index 2a06497..e0ac0df 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/arm/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/arm/mod.rs @@ -835,6 +835,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; cfg_if! { if #[cfg(libc_align)] { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/mips/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/mips/mod.rs index eb3886f..6a03f0b 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/mips/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/mips/mod.rs @@ -536,6 +536,14 @@ pub const SYS_faccessat2: ::c_long = 4000 + 439; pub const SYS_process_madvise: ::c_long = 4000 + 440; pub const SYS_epoll_pwait2: ::c_long = 4000 + 441; pub const SYS_mount_setattr: ::c_long = 4000 + 442; +pub const SYS_quotactl_fd: ::c_long = 4000 + 443; +pub const SYS_landlock_create_ruleset: ::c_long = 4000 + 444; +pub const SYS_landlock_add_rule: ::c_long = 4000 + 445; +pub const SYS_landlock_restrict_self: ::c_long = 4000 + 446; +pub const SYS_memfd_secret: ::c_long = 4000 + 447; +pub const SYS_process_mrelease: ::c_long = 4000 + 448; +pub const SYS_futex_waitv: ::c_long = 4000 + 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 4000 + 450; pub const O_DIRECT: ::c_int = 0x8000; pub const O_DIRECTORY: ::c_int = 0x10000; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/powerpc.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/powerpc.rs index ad45c60..e70b216 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/powerpc.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/powerpc.rs @@ -814,3 +814,11 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs index def90d6..827f85e 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs @@ -758,6 +758,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; cfg_if! { if #[cfg(libc_align)] { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/sparc/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/sparc/mod.rs index 5dd2302..57ad9fe 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/sparc/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/sparc/mod.rs @@ -839,6 +839,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; cfg_if! { if #[cfg(libc_align)] { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/x86/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/x86/mod.rs index e42e9eb..9362238 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/x86/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b32/x86/mod.rs @@ -1040,6 +1040,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; // offsets in user_regs_structs, from sys/reg.h pub const EBX: ::c_int = 0; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/align.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/align.rs index 154c2c5..cb2df37 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/align.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/align.rs @@ -26,4 +26,26 @@ s! { // auto-derive traits like Debug __reserved: [[u64; 32]; 16], } + + #[repr(align(16))] + pub struct user_fpsimd_struct { + pub vregs: [[u64; 2]; 32], + pub fpsr: ::c_uint, + pub fpcr: ::c_uint, + } + + #[repr(align(8))] + pub struct clone_args { + pub flags: ::c_ulonglong, + pub pidfd: ::c_ulonglong, + pub child_tid: ::c_ulonglong, + pub parent_tid: ::c_ulonglong, + pub exit_signal: ::c_ulonglong, + pub stack: ::c_ulonglong, + pub stack_size: ::c_ulonglong, + pub tls: ::c_ulonglong, + pub set_tid: ::c_ulonglong, + pub set_tid_size: ::c_ulonglong, + pub cgroup: ::c_ulonglong, + } } diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs index 513f6ac..b620cc0 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs @@ -573,6 +573,22 @@ pub const HWCAP_PACG: ::c_ulong = 1 << 31; //pub const HWCAP2_SVESM4: ::c_ulong = 1 << 6; //pub const HWCAP2_FLAGM2: ::c_ulong = 1 << 7; //pub const HWCAP2_FRINT: ::c_ulong = 1 << 8; +//pub const HWCAP2_MTE: ::c_ulong = 1 << 18; + +// linux/prctl.h +pub const PR_PAC_RESET_KEYS: ::c_int = 54; +pub const PR_SET_TAGGED_ADDR_CTRL: ::c_int = 55; +pub const PR_GET_TAGGED_ADDR_CTRL: ::c_int = 56; +pub const PR_PAC_SET_ENABLED_KEYS: ::c_int = 60; +pub const PR_PAC_GET_ENABLED_KEYS: ::c_int = 61; + +pub const PR_TAGGED_ADDR_ENABLE: ::c_ulong = 1; + +pub const PR_PAC_APIAKEY: ::c_ulong = 1 << 0; +pub const PR_PAC_APIBKEY: ::c_ulong = 1 << 1; +pub const PR_PAC_APDAKEY: ::c_ulong = 1 << 2; +pub const PR_PAC_APDBKEY: ::c_ulong = 1 << 3; +pub const PR_PAC_APGAKEY: ::c_ulong = 1 << 4; // Syscall table pub const SYS_io_setup: ::c_long = 0; @@ -869,6 +885,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { pub fn sysctl( diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/mips64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/mips64/mod.rs index cac215d..0bf5084 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/mips64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/mips64/mod.rs @@ -587,6 +587,14 @@ pub const SYS_faccessat2: ::c_long = 5000 + 439; pub const SYS_process_madvise: ::c_long = 5000 + 440; pub const SYS_epoll_pwait2: ::c_long = 5000 + 441; pub const SYS_mount_setattr: ::c_long = 5000 + 442; +pub const SYS_quotactl_fd: ::c_long = 5000 + 443; +pub const SYS_landlock_create_ruleset: ::c_long = 5000 + 444; +pub const SYS_landlock_add_rule: ::c_long = 5000 + 445; +pub const SYS_landlock_restrict_self: ::c_long = 5000 + 446; +pub const SYS_memfd_secret: ::c_long = 5000 + 447; +pub const SYS_process_mrelease: ::c_long = 5000 + 448; +pub const SYS_futex_waitv: ::c_long = 5000 + 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 5000 + 450; pub const SFD_CLOEXEC: ::c_int = 0x080000; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs index b5c2687..ce8ce97 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs @@ -948,6 +948,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { pub fn sysctl( diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs index f807390..9d022f9 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs @@ -797,6 +797,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; cfg_if! { if #[cfg(libc_align)] { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/s390x.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/s390x.rs index 212dc89..c4bae08 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/s390x.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/s390x.rs @@ -935,6 +935,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs index 8d065e6..9fdacfa 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs @@ -900,6 +900,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { pub fn sysctl( diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/align.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/align.rs index 7ca870f..ba3075e 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/align.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/align.rs @@ -5,3 +5,20 @@ s_no_extra_traits! { priv_: [f64; 4] } } + +s! { + #[repr(align(8))] + pub struct clone_args { + pub flags: ::c_ulonglong, + pub pidfd: ::c_ulonglong, + pub child_tid: ::c_ulonglong, + pub parent_tid: ::c_ulonglong, + pub exit_signal: ::c_ulonglong, + pub stack: ::c_ulonglong, + pub stack_size: ::c_ulonglong, + pub tls: ::c_ulonglong, + pub set_tid: ::c_ulonglong, + pub set_tid_size: ::c_ulonglong, + pub cgroup: ::c_ulonglong, + } +} diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs index 6124226..d515d22 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs @@ -265,6 +265,14 @@ s! { pub seccomp_notif_resp: ::__u16, pub seccomp_data: ::__u16, } + + pub struct ptrace_rseq_configuration { + pub rseq_abi_pointer: ::__u64, + pub rseq_abi_size: ::__u32, + pub signature: ::__u32, + pub flags: ::__u32, + pub pad: ::__u32, + } } s_no_extra_traits! { @@ -535,6 +543,7 @@ pub const O_ASYNC: ::c_int = 0x2000; pub const O_NDELAY: ::c_int = 0x800; pub const PTRACE_DETACH: ::c_uint = 17; +pub const PTRACE_GET_RSEQ_CONFIGURATION: ::c_uint = 0x420f; pub const EFD_NONBLOCK: ::c_int = 0x800; @@ -626,6 +635,19 @@ pub const PTRACE_PEEKSIGINFO_SHARED: ::c_uint = 1; pub const PTRACE_SYSEMU: ::c_uint = 31; pub const PTRACE_SYSEMU_SINGLESTEP: ::c_uint = 32; +pub const PR_GET_SPECULATION_CTRL: ::c_int = 52; +pub const PR_SET_SPECULATION_CTRL: ::c_int = 53; +pub const PR_SPEC_NOT_AFFECTED: ::c_uint = 0; +pub const PR_SPEC_PRCTL: ::c_uint = 1 << 0; +pub const PR_SPEC_ENABLE: ::c_uint = 1 << 1; +pub const PR_SPEC_DISABLE: ::c_uint = 1 << 2; +pub const PR_SPEC_FORCE_DISABLE: ::c_uint = 1 << 3; +pub const PR_SPEC_DISABLE_NOEXEC: ::c_uint = 1 << 4; +pub const PR_SPEC_STORE_BYPASS: ::c_int = 0; +pub const PR_SPEC_INDIRECT_BRANCH: ::c_int = 1; +// FIXME: perharps for later +//pub const PR_SPEC_L1D_FLUSH: ::c_int = 2; + pub const MCL_CURRENT: ::c_int = 0x0001; pub const MCL_FUTURE: ::c_int = 0x0002; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs index f840f9f..35d2714 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs @@ -429,6 +429,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { pub fn sysctl( diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs index de1a8b9..807b948 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs @@ -357,6 +357,14 @@ pub const SYS_faccessat2: ::c_long = __X32_SYSCALL_BIT + 439; pub const SYS_process_madvise: ::c_long = __X32_SYSCALL_BIT + 440; pub const SYS_epoll_pwait2: ::c_long = __X32_SYSCALL_BIT + 441; pub const SYS_mount_setattr: ::c_long = __X32_SYSCALL_BIT + 442; +pub const SYS_quotactl_fd: ::c_long = __X32_SYSCALL_BIT + 443; +pub const SYS_landlock_create_ruleset: ::c_long = __X32_SYSCALL_BIT + 444; +pub const SYS_landlock_add_rule: ::c_long = __X32_SYSCALL_BIT + 445; +pub const SYS_landlock_restrict_self: ::c_long = __X32_SYSCALL_BIT + 446; +pub const SYS_memfd_secret: ::c_long = __X32_SYSCALL_BIT + 447; +pub const SYS_process_mrelease: ::c_long = __X32_SYSCALL_BIT + 448; +pub const SYS_futex_waitv: ::c_long = __X32_SYSCALL_BIT + 449; +pub const SYS_set_mempolicy_home_node: ::c_long = __X32_SYSCALL_BIT + 450; pub const SYS_rt_sigaction: ::c_long = __X32_SYSCALL_BIT + 512; pub const SYS_rt_sigreturn: ::c_long = __X32_SYSCALL_BIT + 513; pub const SYS_ioctl: ::c_long = __X32_SYSCALL_BIT + 514; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/mod.rs index 8a5f9d1..21e7619 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/gnu/mod.rs @@ -954,6 +954,8 @@ pub const NT_LWPSTATUS: ::c_int = 16; pub const NT_LWPSINFO: ::c_int = 17; pub const NT_PRFPXREG: ::c_int = 20; +pub const ELFOSABI_ARM_AEABI: u8 = 64; + // linux/keyctl.h pub const KEYCTL_DH_COMPUTE: u32 = 23; pub const KEYCTL_PKEY_QUERY: u32 = 24; @@ -1024,6 +1026,11 @@ pub const STATX_ATTR_APPEND: ::c_int = 0x0020; pub const STATX_ATTR_NODUMP: ::c_int = 0x0040; pub const STATX_ATTR_ENCRYPTED: ::c_int = 0x0800; pub const STATX_ATTR_AUTOMOUNT: ::c_int = 0x1000; +pub const STATX_ATTR_MOUNT_ROOT: ::c_int = 0x2000; +pub const STATX_ATTR_VERITY: ::c_int = 0x00100000; +pub const STATX_ATTR_DAX: ::c_int = 0x00200000; + +pub const SOMAXCONN: ::c_int = 4096; //sys/timex.h pub const ADJ_OFFSET: ::c_uint = 0x0001; @@ -1289,6 +1296,7 @@ extern "C" { attr: *mut ::pthread_rwlockattr_t, val: ::c_int, ) -> ::c_int; + pub fn pthread_sigqueue(thread: ::pthread_t, sig: ::c_int, value: ::sigval) -> ::c_int; pub fn mallinfo() -> ::mallinfo; pub fn mallinfo2() -> ::mallinfo2; pub fn malloc_info(options: ::c_int, stream: *mut ::FILE) -> ::c_int; @@ -1305,11 +1313,28 @@ extern "C" { buflen: ::size_t, result: *mut *mut ::group, ) -> ::c_int; + pub fn fgetpwent_r( + stream: *mut ::FILE, + pwd: *mut ::passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::passwd, + ) -> ::c_int; + pub fn fgetgrent_r( + stream: *mut ::FILE, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group, + ) -> ::c_int; pub fn sethostid(hostid: ::c_long) -> ::c_int; pub fn memfd_create(name: *const ::c_char, flags: ::c_uint) -> ::c_int; pub fn mlock2(addr: *const ::c_void, len: ::size_t, flags: ::c_uint) -> ::c_int; + + pub fn euidaccess(pathname: *const ::c_char, mode: ::c_int) -> ::c_int; + pub fn eaccess(pathname: *const ::c_char, mode: ::c_int) -> ::c_int; } extern "C" { @@ -1324,6 +1349,11 @@ extern "C" { pub fn malloc_trim(__pad: ::size_t) -> ::c_int; } +extern "C" { + pub fn gnu_get_libc_release() -> *const ::c_char; + pub fn gnu_get_libc_version() -> *const ::c_char; +} + cfg_if! { if #[cfg(any(target_arch = "x86", target_arch = "arm", diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/mod.rs index 2086f70..43f6399 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/mod.rs @@ -596,6 +596,13 @@ s! { pub nla_len: u16, pub nla_type: u16, } + + pub struct file_clone_range { + pub src_fd: ::__s64, + pub src_offset: ::__u64, + pub src_length: ::__u64, + pub dest_offset: ::__u64, + } } s_no_extra_traits! { @@ -1299,6 +1306,181 @@ pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; +// elf.h - Fields in the e_ident array. +pub const EI_NIDENT: usize = 16; + +pub const EI_MAG0: usize = 0; +pub const ELFMAG0: u8 = 0x7f; +pub const EI_MAG1: usize = 1; +pub const ELFMAG1: u8 = b'E'; +pub const EI_MAG2: usize = 2; +pub const ELFMAG2: u8 = b'L'; +pub const EI_MAG3: usize = 3; +pub const ELFMAG3: u8 = b'F'; +pub const SELFMAG: usize = 4; + +pub const EI_CLASS: usize = 4; +pub const ELFCLASSNONE: u8 = 0; +pub const ELFCLASS32: u8 = 1; +pub const ELFCLASS64: u8 = 2; +pub const ELFCLASSNUM: usize = 3; + +pub const EI_DATA: usize = 5; +pub const ELFDATANONE: u8 = 0; +pub const ELFDATA2LSB: u8 = 1; +pub const ELFDATA2MSB: u8 = 2; +pub const ELFDATANUM: usize = 3; + +pub const EI_VERSION: usize = 6; + +pub const EI_OSABI: usize = 7; +pub const ELFOSABI_NONE: u8 = 0; +pub const ELFOSABI_SYSV: u8 = 0; +pub const ELFOSABI_HPUX: u8 = 1; +pub const ELFOSABI_NETBSD: u8 = 2; +pub const ELFOSABI_GNU: u8 = 3; +pub const ELFOSABI_LINUX: u8 = ELFOSABI_GNU; +pub const ELFOSABI_SOLARIS: u8 = 6; +pub const ELFOSABI_AIX: u8 = 7; +pub const ELFOSABI_IRIX: u8 = 8; +pub const ELFOSABI_FREEBSD: u8 = 9; +pub const ELFOSABI_TRU64: u8 = 10; +pub const ELFOSABI_MODESTO: u8 = 11; +pub const ELFOSABI_OPENBSD: u8 = 12; +pub const ELFOSABI_ARM: u8 = 97; +pub const ELFOSABI_STANDALONE: u8 = 255; + +pub const EI_ABIVERSION: usize = 8; + +pub const EI_PAD: usize = 9; + +// elf.h - Legal values for e_type (object file type). +pub const ET_NONE: u16 = 0; +pub const ET_REL: u16 = 1; +pub const ET_EXEC: u16 = 2; +pub const ET_DYN: u16 = 3; +pub const ET_CORE: u16 = 4; +pub const ET_NUM: u16 = 5; +pub const ET_LOOS: u16 = 0xfe00; +pub const ET_HIOS: u16 = 0xfeff; +pub const ET_LOPROC: u16 = 0xff00; +pub const ET_HIPROC: u16 = 0xffff; + +// elf.h - Legal values for e_machine (architecture). +pub const EM_NONE: u16 = 0; +pub const EM_M32: u16 = 1; +pub const EM_SPARC: u16 = 2; +pub const EM_386: u16 = 3; +pub const EM_68K: u16 = 4; +pub const EM_88K: u16 = 5; +pub const EM_860: u16 = 7; +pub const EM_MIPS: u16 = 8; +pub const EM_S370: u16 = 9; +pub const EM_MIPS_RS3_LE: u16 = 10; +pub const EM_PARISC: u16 = 15; +pub const EM_VPP500: u16 = 17; +pub const EM_SPARC32PLUS: u16 = 18; +pub const EM_960: u16 = 19; +pub const EM_PPC: u16 = 20; +pub const EM_PPC64: u16 = 21; +pub const EM_S390: u16 = 22; +pub const EM_V800: u16 = 36; +pub const EM_FR20: u16 = 37; +pub const EM_RH32: u16 = 38; +pub const EM_RCE: u16 = 39; +pub const EM_ARM: u16 = 40; +pub const EM_FAKE_ALPHA: u16 = 41; +pub const EM_SH: u16 = 42; +pub const EM_SPARCV9: u16 = 43; +pub const EM_TRICORE: u16 = 44; +pub const EM_ARC: u16 = 45; +pub const EM_H8_300: u16 = 46; +pub const EM_H8_300H: u16 = 47; +pub const EM_H8S: u16 = 48; +pub const EM_H8_500: u16 = 49; +pub const EM_IA_64: u16 = 50; +pub const EM_MIPS_X: u16 = 51; +pub const EM_COLDFIRE: u16 = 52; +pub const EM_68HC12: u16 = 53; +pub const EM_MMA: u16 = 54; +pub const EM_PCP: u16 = 55; +pub const EM_NCPU: u16 = 56; +pub const EM_NDR1: u16 = 57; +pub const EM_STARCORE: u16 = 58; +pub const EM_ME16: u16 = 59; +pub const EM_ST100: u16 = 60; +pub const EM_TINYJ: u16 = 61; +pub const EM_X86_64: u16 = 62; +pub const EM_PDSP: u16 = 63; +pub const EM_FX66: u16 = 66; +pub const EM_ST9PLUS: u16 = 67; +pub const EM_ST7: u16 = 68; +pub const EM_68HC16: u16 = 69; +pub const EM_68HC11: u16 = 70; +pub const EM_68HC08: u16 = 71; +pub const EM_68HC05: u16 = 72; +pub const EM_SVX: u16 = 73; +pub const EM_ST19: u16 = 74; +pub const EM_VAX: u16 = 75; +pub const EM_CRIS: u16 = 76; +pub const EM_JAVELIN: u16 = 77; +pub const EM_FIREPATH: u16 = 78; +pub const EM_ZSP: u16 = 79; +pub const EM_MMIX: u16 = 80; +pub const EM_HUANY: u16 = 81; +pub const EM_PRISM: u16 = 82; +pub const EM_AVR: u16 = 83; +pub const EM_FR30: u16 = 84; +pub const EM_D10V: u16 = 85; +pub const EM_D30V: u16 = 86; +pub const EM_V850: u16 = 87; +pub const EM_M32R: u16 = 88; +pub const EM_MN10300: u16 = 89; +pub const EM_MN10200: u16 = 90; +pub const EM_PJ: u16 = 91; +pub const EM_OPENRISC: u16 = 92; +pub const EM_ARC_A5: u16 = 93; +pub const EM_XTENSA: u16 = 94; +pub const EM_AARCH64: u16 = 183; +pub const EM_TILEPRO: u16 = 188; +pub const EM_TILEGX: u16 = 191; +pub const EM_ALPHA: u16 = 0x9026; + +// elf.h - Legal values for e_version (version). +pub const EV_NONE: u32 = 0; +pub const EV_CURRENT: u32 = 1; +pub const EV_NUM: u32 = 2; + +// elf.h - Legal values for p_type (segment type). +pub const PT_NULL: u32 = 0; +pub const PT_LOAD: u32 = 1; +pub const PT_DYNAMIC: u32 = 2; +pub const PT_INTERP: u32 = 3; +pub const PT_NOTE: u32 = 4; +pub const PT_SHLIB: u32 = 5; +pub const PT_PHDR: u32 = 6; +pub const PT_TLS: u32 = 7; +pub const PT_NUM: u32 = 8; +pub const PT_LOOS: u32 = 0x60000000; +pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; +pub const PT_GNU_STACK: u32 = 0x6474e551; +pub const PT_GNU_RELRO: u32 = 0x6474e552; +pub const PT_LOSUNW: u32 = 0x6ffffffa; +pub const PT_SUNWBSS: u32 = 0x6ffffffa; +pub const PT_SUNWSTACK: u32 = 0x6ffffffb; +pub const PT_HISUNW: u32 = 0x6fffffff; +pub const PT_HIOS: u32 = 0x6fffffff; +pub const PT_LOPROC: u32 = 0x70000000; +pub const PT_HIPROC: u32 = 0x7fffffff; + +// Legal values for p_flags (segment flags). +pub const PF_X: u32 = 1 << 0; +pub const PF_W: u32 = 1 << 1; +pub const PF_R: u32 = 1 << 2; +pub const PF_MASKOS: u32 = 0x0ff00000; +pub const PF_MASKPROC: u32 = 0xf0000000; + +// elf.h - Legal values for a_type (entry type). pub const AT_NULL: ::c_ulong = 0; pub const AT_IGNORE: ::c_ulong = 1; pub const AT_EXECFD: ::c_ulong = 2; @@ -1565,6 +1747,7 @@ pub const MSG_INFO: ::c_int = 12; pub const MSG_NOERROR: ::c_int = 0o10000; pub const MSG_EXCEPT: ::c_int = 0o20000; +pub const MSG_ZEROCOPY: ::c_int = 0x4000000; pub const SHM_R: ::c_int = 0o400; pub const SHM_W: ::c_int = 0o200; @@ -1810,6 +1993,7 @@ pub const ITIMER_PROF: ::c_int = 2; pub const TFD_CLOEXEC: ::c_int = O_CLOEXEC; pub const TFD_NONBLOCK: ::c_int = O_NONBLOCK; pub const TFD_TIMER_ABSTIME: ::c_int = 1; +pub const TFD_TIMER_CANCEL_ON_SET: ::c_int = 2; pub const _POSIX_VDISABLE: ::cc_t = 0; @@ -1841,6 +2025,17 @@ pub const IPV6_FLOWINFO_PRIORITY: ::c_int = 0x0ff00000; pub const IPV6_RTHDR_LOOSE: ::c_int = 0; pub const IPV6_RTHDR_STRICT: ::c_int = 1; +// SO_MEMINFO offsets +pub const SK_MEMINFO_RMEM_ALLOC: ::c_int = 0; +pub const SK_MEMINFO_RCVBUF: ::c_int = 1; +pub const SK_MEMINFO_WMEM_ALLOC: ::c_int = 2; +pub const SK_MEMINFO_SNDBUF: ::c_int = 3; +pub const SK_MEMINFO_FWD_ALLOC: ::c_int = 4; +pub const SK_MEMINFO_WMEM_QUEUED: ::c_int = 5; +pub const SK_MEMINFO_OPTMEM: ::c_int = 6; +pub const SK_MEMINFO_BACKLOG: ::c_int = 7; +pub const SK_MEMINFO_DROPS: ::c_int = 8; + pub const IUTF8: ::tcflag_t = 0x00004000; #[cfg(not(all(target_env = "uclibc", target_arch = "mips")))] pub const CMSPAR: ::tcflag_t = 0o10000000000; @@ -1938,26 +2133,6 @@ pub const RESOLVE_BENEATH: ::__u64 = 0x08; pub const RESOLVE_IN_ROOT: ::__u64 = 0x10; pub const RESOLVE_CACHED: ::__u64 = 0x20; -// these are used in the p_type field of Elf32_Phdr and Elf64_Phdr, which has -// the type Elf32Word and Elf64Word respectively. Luckily, both of those are u32 -// so we can use that type here to avoid having to cast. -pub const PT_NULL: u32 = 0; -pub const PT_LOAD: u32 = 1; -pub const PT_DYNAMIC: u32 = 2; -pub const PT_INTERP: u32 = 3; -pub const PT_NOTE: u32 = 4; -pub const PT_SHLIB: u32 = 5; -pub const PT_PHDR: u32 = 6; -pub const PT_TLS: u32 = 7; -pub const PT_NUM: u32 = 8; -pub const PT_LOOS: u32 = 0x60000000; -pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; -pub const PT_GNU_STACK: u32 = 0x6474e551; -pub const PT_GNU_RELRO: u32 = 0x6474e552; -pub const PT_HIOS: u32 = 0x6fffffff; -pub const PT_LOPROC: u32 = 0x70000000; -pub const PT_HIPROC: u32 = 0x7fffffff; - // linux/if_ether.h pub const ETH_ALEN: ::c_int = 6; pub const ETH_HLEN: ::c_int = 14; @@ -2073,6 +2248,7 @@ pub const NFNLGRP_CONNTRACK_EXP_UPDATE: ::c_int = 5; pub const NFNLGRP_CONNTRACK_EXP_DESTROY: ::c_int = 6; pub const NFNLGRP_NFTABLES: ::c_int = 7; pub const NFNLGRP_ACCT_QUOTA: ::c_int = 8; +pub const NFNLGRP_NFTRACE: ::c_int = 9; pub const NFNETLINK_V0: ::c_int = 0; @@ -2088,15 +2264,23 @@ pub const NFNL_SUBSYS_CTNETLINK_TIMEOUT: ::c_int = 8; pub const NFNL_SUBSYS_CTHELPER: ::c_int = 9; pub const NFNL_SUBSYS_NFTABLES: ::c_int = 10; pub const NFNL_SUBSYS_NFT_COMPAT: ::c_int = 11; -pub const NFNL_SUBSYS_COUNT: ::c_int = 12; +pub const NFNL_SUBSYS_HOOK: ::c_int = 12; +pub const NFNL_SUBSYS_COUNT: ::c_int = 13; pub const NFNL_MSG_BATCH_BEGIN: ::c_int = NLMSG_MIN_TYPE; pub const NFNL_MSG_BATCH_END: ::c_int = NLMSG_MIN_TYPE + 1; +pub const NFNL_BATCH_UNSPEC: ::c_int = 0; +pub const NFNL_BATCH_GENID: ::c_int = 1; + // linux/netfilter/nfnetlink_log.h pub const NFULNL_MSG_PACKET: ::c_int = 0; pub const NFULNL_MSG_CONFIG: ::c_int = 1; +pub const NFULA_VLAN_UNSPEC: ::c_int = 0; +pub const NFULA_VLAN_PROTO: ::c_int = 1; +pub const NFULA_VLAN_TCI: ::c_int = 2; + pub const NFULA_UNSPEC: ::c_int = 0; pub const NFULA_PACKET_HDR: ::c_int = 1; pub const NFULA_MARK: ::c_int = 2; @@ -2117,6 +2301,8 @@ pub const NFULA_HWHEADER: ::c_int = 16; pub const NFULA_HWLEN: ::c_int = 17; pub const NFULA_CT: ::c_int = 18; pub const NFULA_CT_INFO: ::c_int = 19; +pub const NFULA_VLAN: ::c_int = 20; +pub const NFULA_L2HDR: ::c_int = 21; pub const NFULNL_CFG_CMD_NONE: ::c_int = 0; pub const NFULNL_CFG_CMD_BIND: ::c_int = 1; @@ -2140,7 +2326,7 @@ pub const NFULNL_CFG_F_SEQ: ::c_int = 0x0001; pub const NFULNL_CFG_F_SEQ_GLOBAL: ::c_int = 0x0002; pub const NFULNL_CFG_F_CONNTRACK: ::c_int = 0x0004; -// linux/netfilter/nfnetlink_log.h +// linux/netfilter/nfnetlink_queue.h pub const NFQNL_MSG_PACKET: ::c_int = 0; pub const NFQNL_MSG_VERDICT: ::c_int = 1; pub const NFQNL_MSG_CONFIG: ::c_int = 2; @@ -2165,18 +2351,13 @@ pub const NFQA_EXP: ::c_int = 15; pub const NFQA_UID: ::c_int = 16; pub const NFQA_GID: ::c_int = 17; pub const NFQA_SECCTX: ::c_int = 18; -/* - FIXME: These are not yet available in musl sanitized kernel headers and - make the tests fail. Enable them once musl has them. - - See https://github.com/rust-lang/libc/pull/1628 for more details. pub const NFQA_VLAN: ::c_int = 19; pub const NFQA_L2HDR: ::c_int = 20; +pub const NFQA_PRIORITY: ::c_int = 21; pub const NFQA_VLAN_UNSPEC: ::c_int = 0; pub const NFQA_VLAN_PROTO: ::c_int = 1; pub const NFQA_VLAN_TCI: ::c_int = 2; -*/ pub const NFQNL_CFG_CMD_NONE: ::c_int = 0; pub const NFQNL_CFG_CMD_BIND: ::c_int = 1; @@ -2206,6 +2387,8 @@ pub const NFQA_SKB_CSUMNOTREADY: ::c_int = 0x0001; pub const NFQA_SKB_GSO: ::c_int = 0x0002; pub const NFQA_SKB_CSUM_NOTVERIFIED: ::c_int = 0x0004; +// linux/genetlink.h + pub const GENL_NAMSIZ: ::c_int = 16; pub const GENL_MIN_ID: ::c_int = NLMSG_MIN_TYPE; @@ -2648,6 +2831,62 @@ pub const ARPD_LOOKUP: ::c_ushort = 0x02; pub const ARPD_FLUSH: ::c_ushort = 0x03; pub const ATF_MAGIC: ::c_int = 0x80; +// userspace compat definitions for RTNLGRP_* +pub const RTMGRP_LINK: ::c_int = 0x00001; +pub const RTMGRP_NOTIFY: ::c_int = 0x00002; +pub const RTMGRP_NEIGH: ::c_int = 0x00004; +pub const RTMGRP_TC: ::c_int = 0x00008; +pub const RTMGRP_IPV4_IFADDR: ::c_int = 0x00010; +pub const RTMGRP_IPV4_MROUTE: ::c_int = 0x00020; +pub const RTMGRP_IPV4_ROUTE: ::c_int = 0x00040; +pub const RTMGRP_IPV4_RULE: ::c_int = 0x00080; +pub const RTMGRP_IPV6_IFADDR: ::c_int = 0x00100; +pub const RTMGRP_IPV6_MROUTE: ::c_int = 0x00200; +pub const RTMGRP_IPV6_ROUTE: ::c_int = 0x00400; +pub const RTMGRP_IPV6_IFINFO: ::c_int = 0x00800; +pub const RTMGRP_DECnet_IFADDR: ::c_int = 0x01000; +pub const RTMGRP_DECnet_ROUTE: ::c_int = 0x04000; +pub const RTMGRP_IPV6_PREFIX: ::c_int = 0x20000; + +// enum rtnetlink_groups +pub const RTNLGRP_NONE: ::c_uint = 0x00; +pub const RTNLGRP_LINK: ::c_uint = 0x01; +pub const RTNLGRP_NOTIFY: ::c_uint = 0x02; +pub const RTNLGRP_NEIGH: ::c_uint = 0x03; +pub const RTNLGRP_TC: ::c_uint = 0x04; +pub const RTNLGRP_IPV4_IFADDR: ::c_uint = 0x05; +pub const RTNLGRP_IPV4_MROUTE: ::c_uint = 0x06; +pub const RTNLGRP_IPV4_ROUTE: ::c_uint = 0x07; +pub const RTNLGRP_IPV4_RULE: ::c_uint = 0x08; +pub const RTNLGRP_IPV6_IFADDR: ::c_uint = 0x09; +pub const RTNLGRP_IPV6_MROUTE: ::c_uint = 0x0a; +pub const RTNLGRP_IPV6_ROUTE: ::c_uint = 0x0b; +pub const RTNLGRP_IPV6_IFINFO: ::c_uint = 0x0c; +pub const RTNLGRP_DECnet_IFADDR: ::c_uint = 0x0d; +pub const RTNLGRP_NOP2: ::c_uint = 0x0e; +pub const RTNLGRP_DECnet_ROUTE: ::c_uint = 0x0f; +pub const RTNLGRP_DECnet_RULE: ::c_uint = 0x10; +pub const RTNLGRP_NOP4: ::c_uint = 0x11; +pub const RTNLGRP_IPV6_PREFIX: ::c_uint = 0x12; +pub const RTNLGRP_IPV6_RULE: ::c_uint = 0x13; +pub const RTNLGRP_ND_USEROPT: ::c_uint = 0x14; +pub const RTNLGRP_PHONET_IFADDR: ::c_uint = 0x15; +pub const RTNLGRP_PHONET_ROUTE: ::c_uint = 0x16; +pub const RTNLGRP_DCB: ::c_uint = 0x17; +pub const RTNLGRP_IPV4_NETCONF: ::c_uint = 0x18; +pub const RTNLGRP_IPV6_NETCONF: ::c_uint = 0x19; +pub const RTNLGRP_MDB: ::c_uint = 0x1a; +pub const RTNLGRP_MPLS_ROUTE: ::c_uint = 0x1b; +pub const RTNLGRP_NSID: ::c_uint = 0x1c; +pub const RTNLGRP_MPLS_NETCONF: ::c_uint = 0x1d; +pub const RTNLGRP_IPV4_MROUTE_R: ::c_uint = 0x1e; +pub const RTNLGRP_IPV6_MROUTE_R: ::c_uint = 0x1f; +pub const RTNLGRP_NEXTHOP: ::c_uint = 0x20; +pub const RTNLGRP_BRVLAN: ::c_uint = 0x21; +pub const RTNLGRP_MCTP_IFADDR: ::c_uint = 0x22; +pub const RTNLGRP_TUNNEL: ::c_uint = 0x23; +pub const RTNLGRP_STATS: ::c_uint = 0x24; + // linux/module.h pub const MODULE_INIT_IGNORE_MODVERSIONS: ::c_uint = 0x0001; pub const MODULE_INIT_IGNORE_VERMAGIC: ::c_uint = 0x0002; @@ -2660,6 +2899,14 @@ pub const SOF_TIMESTAMPING_RX_SOFTWARE: ::c_uint = 1 << 3; pub const SOF_TIMESTAMPING_SOFTWARE: ::c_uint = 1 << 4; pub const SOF_TIMESTAMPING_SYS_HARDWARE: ::c_uint = 1 << 5; pub const SOF_TIMESTAMPING_RAW_HARDWARE: ::c_uint = 1 << 6; +pub const SOF_TIMESTAMPING_OPT_ID: ::c_uint = 1 << 7; +pub const SOF_TIMESTAMPING_TX_SCHED: ::c_uint = 1 << 8; +pub const SOF_TIMESTAMPING_TX_ACK: ::c_uint = 1 << 9; +pub const SOF_TIMESTAMPING_OPT_CMSG: ::c_uint = 1 << 10; +pub const SOF_TIMESTAMPING_OPT_TSONLY: ::c_uint = 1 << 11; +pub const SOF_TIMESTAMPING_OPT_STATS: ::c_uint = 1 << 12; +pub const SOF_TIMESTAMPING_OPT_PKTINFO: ::c_uint = 1 << 13; +pub const SOF_TIMESTAMPING_OPT_TX_SWHW: ::c_uint = 1 << 14; pub const SOF_TXTIME_DEADLINE_MODE: u32 = 1 << 0; pub const SOF_TXTIME_REPORT_ERRORS: u32 = 1 << 1; @@ -3061,6 +3308,7 @@ pub const FUTEX_WAIT_BITSET: ::c_int = 9; pub const FUTEX_WAKE_BITSET: ::c_int = 10; pub const FUTEX_WAIT_REQUEUE_PI: ::c_int = 11; pub const FUTEX_CMP_REQUEUE_PI: ::c_int = 12; +pub const FUTEX_LOCK_PI2: ::c_int = 13; pub const FUTEX_PRIVATE_FLAG: ::c_int = 128; pub const FUTEX_CLOCK_REALTIME: ::c_int = 256; @@ -3329,17 +3577,6 @@ f! { minor as ::c_uint } - pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { - let major = major as ::dev_t; - let minor = minor as ::dev_t; - let mut dev = 0; - dev |= (major & 0x00000fff) << 8; - dev |= (major & 0xfffff000) << 32; - dev |= (minor & 0x000000ff) << 0; - dev |= (minor & 0xffffff00) << 12; - dev - } - pub fn IPTOS_TOS(tos: u8) -> u8 { tos & IPTOS_TOS_MASK } @@ -3381,6 +3618,19 @@ f! { } } +safe_f! { + pub {const} fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major & 0x00000fff) << 8; + dev |= (major & 0xfffff000) << 32; + dev |= (minor & 0x000000ff) << 0; + dev |= (minor & 0xffffff00) << 12; + dev + } +} + cfg_if! { if #[cfg(not(target_env = "uclibc"))] { extern "C" { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/arm/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/arm/mod.rs index 7e4868b..c47fa2c 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/arm/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/arm/mod.rs @@ -837,6 +837,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { pub fn getrandom(buf: *mut ::c_void, buflen: ::size_t, flags: ::c_uint) -> ::ssize_t; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mips/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mips/mod.rs index 7443a09..40b507b 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mips/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mips/mod.rs @@ -777,6 +777,14 @@ pub const SYS_faccessat2: ::c_long = 4000 + 439; pub const SYS_process_madvise: ::c_long = 4000 + 440; pub const SYS_epoll_pwait2: ::c_long = 4000 + 441; pub const SYS_mount_setattr: ::c_long = 4000 + 442; +pub const SYS_quotactl_fd: ::c_long = 4000 + 443; +pub const SYS_landlock_create_ruleset: ::c_long = 4000 + 444; +pub const SYS_landlock_add_rule: ::c_long = 4000 + 445; +pub const SYS_landlock_restrict_self: ::c_long = 4000 + 446; +pub const SYS_memfd_secret: ::c_long = 4000 + 447; +pub const SYS_process_mrelease: ::c_long = 4000 + 448; +pub const SYS_futex_waitv: ::c_long = 4000 + 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 4000 + 450; cfg_if! { if #[cfg(libc_align)] { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mod.rs index 6d2ecf2..63824fb 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/mod.rs @@ -3,6 +3,7 @@ pub type c_ulong = u32; pub type nlink_t = u32; pub type blksize_t = ::c_long; pub type __u64 = ::c_ulonglong; +pub type __s64 = ::c_longlong; pub type regoff_t = ::c_int; s! { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/powerpc.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/powerpc.rs index d7ca038..5b1bf17 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/powerpc.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/powerpc.rs @@ -790,6 +790,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; extern "C" { pub fn getrandom(buf: *mut ::c_void, buflen: ::size_t, flags: ::c_uint) -> ::ssize_t; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/riscv32/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/riscv32/mod.rs index 9b68ce2..5736246 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/riscv32/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/riscv32/mod.rs @@ -271,6 +271,7 @@ pub const ENOPROTOOPT: ::c_int = 92; pub const EPROTONOSUPPORT: ::c_int = 93; pub const ESOCKTNOSUPPORT: ::c_int = 94; pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; pub const EPFNOSUPPORT: ::c_int = 96; pub const EAFNOSUPPORT: ::c_int = 97; pub const EADDRINUSE: ::c_int = 98; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/x86/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/x86/mod.rs index a6efea1..c319b91 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/x86/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b32/x86/mod.rs @@ -856,6 +856,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; // offsets in user_regs_structs, from sys/reg.h pub const EBX: ::c_int = 0; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/align.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/align.rs index 81c55c6..a4bf9bf 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/align.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/align.rs @@ -24,4 +24,19 @@ s! { pub pstate: ::c_ulong, __reserved: [[u64; 32]; 16], } + + #[repr(align(8))] + pub struct clone_args { + pub flags: ::c_ulonglong, + pub pidfd: ::c_ulonglong, + pub child_tid: ::c_ulonglong, + pub parent_tid: ::c_ulonglong, + pub exit_signal: ::c_ulonglong, + pub stack: ::c_ulonglong, + pub stack_size: ::c_ulonglong, + pub tls: ::c_ulonglong, + pub set_tid: ::c_ulonglong, + pub set_tid_size: ::c_ulonglong, + pub cgroup: ::c_ulonglong, + } } diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/mod.rs index 845707d..14b4bc6 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/mod.rs @@ -1,5 +1,6 @@ pub type c_char = u8; pub type __u64 = ::c_ulonglong; +pub type __s64 = ::c_longlong; pub type wchar_t = u32; pub type nlink_t = u32; pub type blksize_t = ::c_int; @@ -555,6 +556,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; pub const MCL_CURRENT: ::c_int = 0x0001; pub const MCL_FUTURE: ::c_int = 0x0002; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/mips64.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/mips64.rs index cb9bb93..22ac916 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/mips64.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/mips64.rs @@ -1,6 +1,7 @@ pub type c_char = i8; pub type wchar_t = i32; pub type __u64 = ::c_ulong; +pub type __s64 = ::c_long; pub type nlink_t = u64; pub type blksize_t = i64; @@ -444,6 +445,14 @@ pub const SYS_faccessat2: ::c_long = 5000 + 439; pub const SYS_process_madvise: ::c_long = 5000 + 440; pub const SYS_epoll_pwait2: ::c_long = 5000 + 441; pub const SYS_mount_setattr: ::c_long = 5000 + 442; +pub const SYS_quotactl_fd: ::c_long = 5000 + 443; +pub const SYS_landlock_create_ruleset: ::c_long = 5000 + 444; +pub const SYS_landlock_add_rule: ::c_long = 5000 + 445; +pub const SYS_landlock_restrict_self: ::c_long = 5000 + 446; +pub const SYS_memfd_secret: ::c_long = 5000 + 447; +pub const SYS_process_mrelease: ::c_long = 5000 + 448; +pub const SYS_futex_waitv: ::c_long = 5000 + 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 5000 + 450; pub const O_DIRECT: ::c_int = 0x8000; pub const O_DIRECTORY: ::c_int = 0x10000; @@ -458,7 +467,7 @@ pub const O_SYNC: ::c_int = 0x4010; pub const O_RSYNC: ::c_int = 0x4010; pub const O_DSYNC: ::c_int = 0x10; pub const O_ASYNC: ::c_int = 0x1000; -pub const O_LARGEFILE: ::c_int = 0; +pub const O_LARGEFILE: ::c_int = 0x2000; pub const EDEADLK: ::c_int = 45; pub const ENAMETOOLONG: ::c_int = 78; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/powerpc64.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/powerpc64.rs index f17d72c..0bb4cf8 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/powerpc64.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/powerpc64.rs @@ -1,6 +1,7 @@ pub type c_char = u8; pub type wchar_t = i32; pub type __u64 = ::c_ulong; +pub type __s64 = ::c_long; pub type nlink_t = u64; pub type blksize_t = ::c_long; @@ -600,6 +601,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; pub const EDEADLK: ::c_int = 58; pub const EDEADLOCK: ::c_int = EDEADLK; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/riscv64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/riscv64/mod.rs index fcb28c3..f354293 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/riscv64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/riscv64/mod.rs @@ -8,6 +8,7 @@ pub type blksize_t = ::c_int; pub type fsblkcnt64_t = ::c_ulong; pub type fsfilcnt64_t = ::c_ulong; pub type __u64 = ::c_ulonglong; +pub type __s64 = ::c_longlong; s! { pub struct pthread_attr_t { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/s390x.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/s390x.rs index 5fdd03d..60bfc8d 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/s390x.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/s390x.rs @@ -4,6 +4,7 @@ pub type nlink_t = u64; pub type wchar_t = i32; pub type greg_t = u64; pub type __u64 = u64; +pub type __s64 = i64; s! { pub struct ipc_perm { @@ -221,6 +222,7 @@ pub const ENOPROTOOPT: ::c_int = 92; pub const EPROTONOSUPPORT: ::c_int = 93; pub const ESOCKTNOSUPPORT: ::c_int = 94; pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; pub const EPFNOSUPPORT: ::c_int = 96; pub const EAFNOSUPPORT: ::c_int = 97; pub const ENETDOWN: ::c_int = 100; @@ -709,3 +711,11 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/align.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/align.rs index 7ca870f..94391a0 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/align.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/align.rs @@ -4,4 +4,22 @@ s_no_extra_traits! { pub struct max_align_t { priv_: [f64; 4] } + +} + +s! { + #[repr(align(8))] + pub struct clone_args { + pub flags: ::c_ulonglong, + pub pidfd: ::c_ulonglong, + pub child_tid: ::c_ulonglong, + pub parent_tid: ::c_ulonglong, + pub exit_signal: ::c_ulonglong, + pub stack: ::c_ulonglong, + pub stack_size: ::c_ulonglong, + pub tls: ::c_ulonglong, + pub set_tid: ::c_ulonglong, + pub set_tid_size: ::c_ulonglong, + pub cgroup: ::c_ulonglong, + } } diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/mod.rs index 3429c2c..8198dc2 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/mod.rs @@ -3,6 +3,7 @@ pub type wchar_t = i32; pub type nlink_t = u64; pub type blksize_t = ::c_long; pub type __u64 = ::c_ulonglong; +pub type __s64 = ::c_longlong; pub type greg_t = i64; s! { @@ -599,6 +600,14 @@ pub const SYS_faccessat2: ::c_long = 439; pub const SYS_process_madvise: ::c_long = 440; pub const SYS_epoll_pwait2: ::c_long = 441; pub const SYS_mount_setattr: ::c_long = 442; +pub const SYS_quotactl_fd: ::c_long = 443; +pub const SYS_landlock_create_ruleset: ::c_long = 444; +pub const SYS_landlock_add_rule: ::c_long = 445; +pub const SYS_landlock_restrict_self: ::c_long = 446; +pub const SYS_memfd_secret: ::c_long = 447; +pub const SYS_process_mrelease: ::c_long = 448; +pub const SYS_futex_waitv: ::c_long = 449; +pub const SYS_set_mempolicy_home_node: ::c_long = 450; // offsets in user_regs_structs, from sys/reg.h pub const R15: ::c_int = 0; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/mod.rs index 7071073..894f377 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/musl/mod.rs @@ -529,6 +529,8 @@ pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; pub const SOCK_DCCP: ::c_int = 6; pub const SOCK_PACKET: ::c_int = 10; +pub const SOMAXCONN: ::c_int = 128; + #[deprecated(since = "0.2.55", note = "Use SIGSYS instead")] pub const SIGUNUSED: ::c_int = ::SIGSYS; @@ -752,6 +754,9 @@ extern "C" { pub fn memfd_create(name: *const ::c_char, flags: ::c_uint) -> ::c_int; pub fn mlock2(addr: *const ::c_void, len: ::size_t, flags: ::c_uint) -> ::c_int; pub fn malloc_usable_size(ptr: *mut ::c_void) -> ::size_t; + + pub fn euidaccess(pathname: *const ::c_char, mode: ::c_int) -> ::c_int; + pub fn eaccess(pathname: *const ::c_char, mode: ::c_int) -> ::c_int; } cfg_if! { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/arm/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/arm/mod.rs index e027957..a0035b2 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/arm/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/arm/mod.rs @@ -19,6 +19,7 @@ pub type blkcnt_t = ::c_long; pub type fsblkcnt64_t = u64; pub type fsfilcnt64_t = u64; pub type __u64 = ::c_ulonglong; +pub type __s64 = ::c_longlong; s! { pub struct cmsghdr { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/mod.rs index fc80f0f..4a01e0c 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/mod.rs @@ -235,6 +235,8 @@ pub const PRIO_PROCESS: ::c_int = 0; pub const PRIO_PGRP: ::c_int = 1; pub const PRIO_USER: ::c_int = 2; +pub const SOMAXCONN: ::c_int = 128; + pub const ST_RELATIME: ::c_ulong = 4096; pub const AF_NFC: ::c_int = PF_NFC; diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/mod.rs index 529711f..43ac792 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/mod.rs @@ -20,6 +20,7 @@ pub type wchar_t = ::c_int; pub type fsblkcnt64_t = u64; pub type fsfilcnt64_t = u64; pub type __u64 = ::c_ulong; +pub type __s64 = ::c_long; s! { pub struct ipc_perm { diff --git a/bash-5.1/vendor/libc/src/unix/linux_like/mod.rs b/bash-5.1/vendor/libc/src/unix/linux_like/mod.rs index 125c5d4..46964cc 100644 --- a/bash-5.1/vendor/libc/src/unix/linux_like/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/linux_like/mod.rs @@ -759,8 +759,6 @@ pub const PF_IEEE802154: ::c_int = AF_IEEE802154; pub const PF_CAIF: ::c_int = AF_CAIF; pub const PF_ALG: ::c_int = AF_ALG; -pub const SOMAXCONN: ::c_int = 128; - pub const MSG_OOB: ::c_int = 1; pub const MSG_PEEK: ::c_int = 2; pub const MSG_DONTROUTE: ::c_int = 4; @@ -1213,6 +1211,15 @@ pub const PIPE_BUF: usize = 4096; pub const SI_LOAD_SHIFT: ::c_uint = 16; +// si_code values for SIGBUS signal +pub const BUS_ADRALN: ::c_int = 1; +pub const BUS_ADRERR: ::c_int = 2; +pub const BUS_OBJERR: ::c_int = 3; +// Linux-specific si_code values for SIGBUS signal +pub const BUS_MCEERR_AR: ::c_int = 4; +pub const BUS_MCEERR_AO: ::c_int = 5; + +// si_code values for SIGCHLD signal pub const CLD_EXITED: ::c_int = 1; pub const CLD_KILLED: ::c_int = 2; pub const CLD_DUMPED: ::c_int = 3; @@ -1427,6 +1434,7 @@ cfg_if! { pub const UDF_SUPER_MAGIC: ::c_long = 0x15013346; pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; pub const XENFS_SUPER_MAGIC: ::c_long = 0xabba1974; + pub const NSFS_MAGIC: ::c_long = 0x6e736673; } else if #[cfg(target_arch = "s390x")] { pub const ADFS_SUPER_MAGIC: ::c_uint = 0x0000adf5; pub const AFFS_SUPER_MAGIC: ::c_uint = 0x0000adff; @@ -1480,6 +1488,7 @@ cfg_if! { pub const UDF_SUPER_MAGIC: ::c_uint = 0x15013346; pub const USBDEVICE_SUPER_MAGIC: ::c_uint = 0x00009fa2; pub const XENFS_SUPER_MAGIC: ::c_uint = 0xabba1974; + pub const NSFS_MAGIC: ::c_uint = 0x6e736673; } } @@ -1726,8 +1735,6 @@ extern "C" { pub fn clearenv() -> ::c_int; pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, options: ::c_int) -> ::c_int; - pub fn setreuid(ruid: ::uid_t, euid: ::uid_t) -> ::c_int; - pub fn setregid(rgid: ::gid_t, egid: ::gid_t) -> ::c_int; pub fn getresuid(ruid: *mut ::uid_t, euid: *mut ::uid_t, suid: *mut ::uid_t) -> ::c_int; pub fn getresgid(rgid: *mut ::gid_t, egid: *mut ::gid_t, sgid: *mut ::gid_t) -> ::c_int; pub fn acct(filename: *const ::c_char) -> ::c_int; diff --git a/bash-5.1/vendor/libc/src/unix/mod.rs b/bash-5.1/vendor/libc/src/unix/mod.rs index ecee444..ecc693e 100644 --- a/bash-5.1/vendor/libc/src/unix/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/mod.rs @@ -346,13 +346,13 @@ cfg_if! { } else if #[cfg(target_os = "emscripten")] { #[link(name = "c")] extern {} - } else if #[cfg(all(target_os = "netbsd", - feature = "rustc-dep-of-std", - target_vendor = "rumprun"))] { - // Since we don't use -nodefaultlibs on Rumprun, libc is always pulled - // in automatically by the linker. We avoid passing it explicitly, as it - // causes some versions of binutils to crash with an assertion failure. - #[link(name = "m")] + } else if #[cfg(all(target_os = "android", feature = "rustc-dep-of-std"))] { + #[link(name = "c", kind = "static", modifiers = "-bundle", + cfg(target_feature = "crt-static"))] + #[link(name = "m", kind = "static", modifiers = "-bundle", + cfg(target_feature = "crt-static"))] + #[link(name = "m", cfg(not(target_feature = "crt-static")))] + #[link(name = "c", cfg(not(target_feature = "crt-static")))] extern {} } else if #[cfg(any(target_os = "macos", target_os = "ios", @@ -901,6 +901,8 @@ extern "C" { pub fn setpgid(pid: pid_t, pgid: pid_t) -> ::c_int; pub fn setsid() -> pid_t; pub fn setuid(uid: uid_t) -> ::c_int; + pub fn setreuid(ruid: uid_t, euid: uid_t) -> ::c_int; + pub fn setregid(rgid: gid_t, egid: gid_t) -> ::c_int; #[cfg_attr( all(target_os = "macos", target_arch = "x86"), link_name = "sleep$UNIX2003" diff --git a/bash-5.1/vendor/libc/src/unix/newlib/espidf/mod.rs b/bash-5.1/vendor/libc/src/unix/newlib/espidf/mod.rs index 38c99c6..804cd66 100644 --- a/bash-5.1/vendor/libc/src/unix/newlib/espidf/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/newlib/espidf/mod.rs @@ -83,6 +83,9 @@ pub const MSG_DONTROUTE: ::c_int = 0x4; pub const MSG_WAITALL: ::c_int = 0x02; pub const MSG_MORE: ::c_int = 0x10; pub const MSG_NOSIGNAL: ::c_int = 0x20; +pub const MSG_TRUNC: ::c_int = 0x04; +pub const MSG_CTRUNC: ::c_int = 0x08; +pub const MSG_EOR: ::c_int = 0x08; pub const PTHREAD_STACK_MIN: ::size_t = 768; @@ -100,6 +103,8 @@ extern "C" { pub fn sendmsg(s: ::c_int, msg: *const ::msghdr, flags: ::c_int) -> ::ssize_t; #[link_name = "lwip_recvmsg"] pub fn recvmsg(s: ::c_int, msg: *mut ::msghdr, flags: ::c_int) -> ::ssize_t; + + pub fn eventfd(initval: ::c_uint, flags: ::c_int) -> ::c_int; } pub use crate::unix::newlib::generic::{sigset_t, stat}; diff --git a/bash-5.1/vendor/libc/src/unix/newlib/mod.rs b/bash-5.1/vendor/libc/src/unix/newlib/mod.rs index 34a63a8..1a69469 100644 --- a/bash-5.1/vendor/libc/src/unix/newlib/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/newlib/mod.rs @@ -41,7 +41,7 @@ pub type tcflag_t = ::c_uint; pub type useconds_t = u32; cfg_if! { - if #[cfg(target_os = "horizon")] { + if #[cfg(any(target_os = "horizon", all(target_os = "espidf", espidf_time64)))] { pub type time_t = ::c_longlong; } else { pub type time_t = i32; diff --git a/bash-5.1/vendor/libc/src/unix/nto/aarch64.rs b/bash-5.1/vendor/libc/src/unix/nto/aarch64.rs new file mode 100644 index 0000000..6faf815 --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/nto/aarch64.rs @@ -0,0 +1,36 @@ +pub type c_char = u8; +pub type wchar_t = u32; +pub type c_long = i64; +pub type c_ulong = u64; +pub type time_t = i64; + +s! { + pub struct aarch64_qreg_t { + pub qlo: u64, + pub qhi: u64, + } + + pub struct aarch64_fpu_registers { + pub reg: [::aarch64_qreg_t; 32], + pub fpsr: u32, + pub fpcr: u32, + } + + pub struct aarch64_cpu_registers { + pub gpr: [u64; 32], + pub elr: u64, + pub pstate: u64, + } + + #[repr(align(16))] + pub struct mcontext_t { + pub cpu: ::aarch64_cpu_registers, + pub fpu: ::aarch64_fpu_registers, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } +} diff --git a/bash-5.1/vendor/libc/src/unix/nto/mod.rs b/bash-5.1/vendor/libc/src/unix/nto/mod.rs new file mode 100644 index 0000000..b8fcf9d --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/nto/mod.rs @@ -0,0 +1,3285 @@ +pub type clock_t = u32; + +pub type sa_family_t = u8; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type clockid_t = ::c_int; +pub type timer_t = ::c_int; +pub type key_t = ::c_uint; +pub type id_t = ::c_int; + +pub type useconds_t = u32; +pub type dev_t = u32; +pub type socklen_t = u32; +pub type mode_t = u32; +pub type rlim64_t = u64; +pub type mqd_t = ::c_int; +pub type nfds_t = ::c_uint; +pub type idtype_t = ::c_uint; +pub type errno_t = ::c_int; +pub type rsize_t = c_ulong; + +pub type Elf32_Half = u16; +pub type Elf32_Word = u32; +pub type Elf32_Off = u32; +pub type Elf32_Addr = u32; +pub type Elf32_Lword = u64; +pub type Elf32_Sword = i32; + +pub type Elf64_Half = u16; +pub type Elf64_Word = u32; +pub type Elf64_Off = u64; +pub type Elf64_Addr = u64; +pub type Elf64_Xword = u64; +pub type Elf64_Sxword = i64; +pub type Elf64_Lword = u64; +pub type Elf64_Sword = i32; + +pub type Elf32_Section = u16; +pub type Elf64_Section = u16; + +pub type _Time32t = u32; + +pub type pthread_t = ::c_int; +pub type regoff_t = ::ssize_t; + +pub type nlink_t = u32; +pub type blksize_t = u32; +pub type suseconds_t = i32; + +pub type ino_t = u64; +pub type off_t = i64; +pub type blkcnt_t = u64; +pub type msgqnum_t = u64; +pub type msglen_t = u64; +pub type fsblkcnt_t = u64; +pub type fsfilcnt_t = u64; +pub type rlim_t = u64; +pub type posix_spawn_file_actions_t = *mut ::c_void; +pub type posix_spawnattr_t = ::uintptr_t; + +pub type pthread_mutex_t = ::sync_t; +pub type pthread_mutexattr_t = ::_sync_attr; +pub type pthread_cond_t = ::sync_t; +pub type pthread_condattr_t = ::_sync_attr; +pub type pthread_rwlockattr_t = ::_sync_attr; +pub type pthread_key_t = ::c_int; +pub type pthread_spinlock_t = sync_t; +pub type pthread_barrierattr_t = _sync_attr; +pub type sem_t = sync_t; + +pub type nl_item = ::c_int; + +#[cfg_attr(feature = "extra_traits", derive(Debug))] +pub enum timezone {} +impl ::Copy for timezone {} +impl ::Clone for timezone { + fn clone(&self) -> timezone { + *self + } +} + +s! { + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + #[repr(packed)] + pub struct in_addr { + pub s_addr: ::in_addr_t, + } + + pub struct sockaddr { + pub sa_len: u8, + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_len: u8, + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [i8; 8], + } + + pub struct sockaddr_in6 { + pub sin6_len: u8, + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + // The order of the `ai_addr` field in this struct is crucial + // for converting between the Rust and C types. + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: socklen_t, + pub ai_canonname: *mut c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut addrinfo, + } + + pub struct fd_set { + fds_bits: [::c_uint; 2 * FD_SETSIZE / ULONG_SIZE], + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + pub tm_gmtoff: ::c_long, + pub tm_zone: *const ::c_char, + } + + #[repr(align(8))] + pub struct sched_param { + pub sched_priority: ::c_int, + pub sched_curpriority: ::c_int, + pub reserved: [::c_int; 10], + } + + #[repr(align(8))] + pub struct __sched_param { + pub __sched_priority: ::c_int, + pub __sched_curpriority: ::c_int, + pub reserved: [::c_int; 10], + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct lconv { + pub currency_symbol: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub frac_digits: ::c_char, + pub int_frac_digits: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub n_sign_posn: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + + pub decimal_point: *mut ::c_char, + pub grouping: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + + pub _Frac_grouping: *mut ::c_char, + pub _Frac_sep: *mut ::c_char, + pub _False: *mut ::c_char, + pub _True: *mut ::c_char, + + pub _No: *mut ::c_char, + pub _Yes: *mut ::c_char, + pub _Nostr: *mut ::c_char, + pub _Yesstr: *mut ::c_char, + pub _Reserved: [*mut ::c_char; 8], + } + + pub struct in_pktinfo { + pub ipi_addr: ::in_addr, + pub ipi_ifindex: ::c_uint, + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut c_char, + pub ifa_flags: ::c_uint, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_dstaddr: *mut ::sockaddr, + pub ifa_data: *mut ::c_void + } + + pub struct arpreq { + pub arp_pa: ::sockaddr, + pub arp_ha: ::sockaddr, + pub arp_flags: ::c_int, + } + + #[repr(packed)] + pub struct arphdr { + pub ar_hrd: u16, + pub ar_pro: u16, + pub ar_hln: u8, + pub ar_pln: u8, + pub ar_op: u16, + } + + pub struct mmsghdr { + pub msg_hdr: ::msghdr, + pub msg_len: ::c_uint, + } + + #[repr(align(8))] + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + __data: [u8; 36], // union + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_flags: ::c_int, + pub sa_mask: ::sigset_t, + } + + pub struct _sync { + _union: ::c_uint, + __owner: ::c_uint, + } + pub struct rlimit64 { + pub rlim_cur: rlim64_t, + pub rlim_max: rlim64_t, + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_matchc: ::c_int, + pub gl_pathv: *mut *mut c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + pub gl_errfunc: extern "C" fn(*const ::c_char, ::c_int) -> ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_age: *mut ::c_char, + pub pw_comment: *mut ::c_char, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } + + pub struct sembuf { + pub sem_num: ::c_ushort, + pub sem_op: ::c_short, + pub sem_flg: ::c_short, + } + + pub struct Elf32_Ehdr { + pub e_ident: [::c_uchar; 16], + pub e_type: Elf32_Half, + pub e_machine: Elf32_Half, + pub e_version: Elf32_Word, + pub e_entry: Elf32_Addr, + pub e_phoff: Elf32_Off, + pub e_shoff: Elf32_Off, + pub e_flags: Elf32_Word, + pub e_ehsize: Elf32_Half, + pub e_phentsize: Elf32_Half, + pub e_phnum: Elf32_Half, + pub e_shentsize: Elf32_Half, + pub e_shnum: Elf32_Half, + pub e_shstrndx: Elf32_Half, + } + + pub struct Elf64_Ehdr { + pub e_ident: [::c_uchar; 16], + pub e_type: Elf64_Half, + pub e_machine: Elf64_Half, + pub e_version: Elf64_Word, + pub e_entry: Elf64_Addr, + pub e_phoff: Elf64_Off, + pub e_shoff: Elf64_Off, + pub e_flags: Elf64_Word, + pub e_ehsize: Elf64_Half, + pub e_phentsize: Elf64_Half, + pub e_phnum: Elf64_Half, + pub e_shentsize: Elf64_Half, + pub e_shnum: Elf64_Half, + pub e_shstrndx: Elf64_Half, + } + + pub struct Elf32_Sym { + pub st_name: Elf32_Word, + pub st_value: Elf32_Addr, + pub st_size: Elf32_Word, + pub st_info: ::c_uchar, + pub st_other: ::c_uchar, + pub st_shndx: Elf32_Section, + } + + pub struct Elf64_Sym { + pub st_name: Elf64_Word, + pub st_info: ::c_uchar, + pub st_other: ::c_uchar, + pub st_shndx: Elf64_Section, + pub st_value: Elf64_Addr, + pub st_size: Elf64_Xword, + } + + pub struct Elf32_Phdr { + pub p_type: Elf32_Word, + pub p_offset: Elf32_Off, + pub p_vaddr: Elf32_Addr, + pub p_paddr: Elf32_Addr, + pub p_filesz: Elf32_Word, + pub p_memsz: Elf32_Word, + pub p_flags: Elf32_Word, + pub p_align: Elf32_Word, + } + + pub struct Elf64_Phdr { + pub p_type: Elf64_Word, + pub p_flags: Elf64_Word, + pub p_offset: Elf64_Off, + pub p_vaddr: Elf64_Addr, + pub p_paddr: Elf64_Addr, + pub p_filesz: Elf64_Xword, + pub p_memsz: Elf64_Xword, + pub p_align: Elf64_Xword, + } + + pub struct Elf32_Shdr { + pub sh_name: Elf32_Word, + pub sh_type: Elf32_Word, + pub sh_flags: Elf32_Word, + pub sh_addr: Elf32_Addr, + pub sh_offset: Elf32_Off, + pub sh_size: Elf32_Word, + pub sh_link: Elf32_Word, + pub sh_info: Elf32_Word, + pub sh_addralign: Elf32_Word, + pub sh_entsize: Elf32_Word, + } + + pub struct Elf64_Shdr { + pub sh_name: Elf64_Word, + pub sh_type: Elf64_Word, + pub sh_flags: Elf64_Xword, + pub sh_addr: Elf64_Addr, + pub sh_offset: Elf64_Off, + pub sh_size: Elf64_Xword, + pub sh_link: Elf64_Word, + pub sh_info: Elf64_Word, + pub sh_addralign: Elf64_Xword, + pub sh_entsize: Elf64_Xword, + } + + pub struct in6_pktinfo { + pub ipi6_addr: ::in6_addr, + pub ipi6_ifindex: ::c_uint, + } + + pub struct inotify_event { + pub wd: ::c_int, + pub mask: u32, + pub cookie: u32, + pub len: u32 + } + + pub struct regmatch_t { + pub rm_so: regoff_t, + pub rm_eo: regoff_t, + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_cc: [::cc_t; ::NCCS], + __reserved: [::c_uint; 3], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct mallinfo { + pub arena: ::c_int, + pub ordblks: ::c_int, + pub smblks: ::c_int, + pub hblks: ::c_int, + pub hblkhd: ::c_int, + pub usmblks: ::c_int, + pub fsmblks: ::c_int, + pub uordblks: ::c_int, + pub fordblks: ::c_int, + pub keepcost: ::c_int, + } + + pub struct flock { + pub l_type: i16, + pub l_whence: i16, + pub l_zero1: i32, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + pub l_sysid: u32, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_basetype: [::c_char; 16], + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + f_filler: [::c_uint; 21], + } + + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_offset: off_t, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + pub aio_lio_opcode: ::c_int, + pub _aio_lio_state: *mut ::c_void, + _aio_pad: [::c_int; 3], + pub _aio_next: *mut ::aiocb, + pub _aio_flag: ::c_uint, + pub _aio_iotype: ::c_uint, + pub _aio_result: ::ssize_t, + pub _aio_error: ::c_uint, + pub _aio_suspend: *mut ::c_void, + pub _aio_plist: *mut ::c_void, + pub _aio_policy: ::c_int, + pub _aio_param: ::__sched_param, + } + + pub struct pthread_attr_t { + __data1: ::c_long, + __data2: [u8; 96] + } + + pub struct ipc_perm { + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub seq: ::c_uint, + pub key: ::key_t, + _reserved: [::c_int; 4], + } + + pub struct regex_t { + re_magic: ::c_int, + re_nsub: ::size_t, + re_endp: *const ::c_char, + re_g: *mut ::c_void, + } + + pub struct _thread_attr { + pub __flags: ::c_int, + pub __stacksize: ::size_t, + pub __stackaddr: *mut ::c_void, + pub __exitfunc: ::Option, + pub __policy: ::c_int, + pub __param: ::__sched_param, + pub __guardsize: ::c_uint, + pub __prealloc: ::c_uint, + __spare: [::c_int; 2], + } + + pub struct _sync_attr { + pub __protocol: ::c_int, + pub __flags: ::c_int, + pub __prioceiling: ::c_int, + pub __clockid: ::c_int, + pub __count: ::c_int, + __reserved: [::c_int; 3], + } + + pub struct sockcred { + pub sc_uid: ::uid_t, + pub sc_euid: ::uid_t, + pub sc_gid: ::gid_t, + pub sc_egid: ::gid_t, + pub sc_ngroups: ::c_int, + pub sc_groups: [::gid_t; 1], + } + + pub struct bpf_program { + pub bf_len: ::c_uint, + pub bf_insns: *mut ::bpf_insn, + } + + pub struct bpf_stat { + pub bs_recv: u64, + pub bs_drop: u64, + pub bs_capt: u64, + bs_padding: [u64; 13], + } + + pub struct bpf_version { + pub bv_major: ::c_ushort, + pub bv_minor: ::c_ushort, + } + + pub struct bpf_hdr { + pub bh_tstamp: ::timeval, + pub bh_caplen: u32, + pub bh_datalen: u32, + pub bh_hdrlen: u16, + } + + pub struct bpf_insn { + pub code: u16, + pub jt: ::c_uchar, + pub jf: ::c_uchar, + pub k: u32, + } + + pub struct bpf_dltlist { + pub bfl_len: ::c_uint, + pub bfl_list: *mut ::c_uint, + } + + pub struct unpcbid { + pub unp_pid: ::pid_t, + pub unp_euid: ::uid_t, + pub unp_egid: ::gid_t, + } + + pub struct dl_phdr_info { + pub dlpi_addr: ::Elf64_Addr, + pub dlpi_name: *const ::c_char, + pub dlpi_phdr: *const ::Elf64_Phdr, + pub dlpi_phnum: ::Elf64_Half, + } + + #[repr(align(8))] + pub struct ucontext_t { + pub uc_link: *mut ucontext_t, + pub uc_sigmask: ::sigset_t, + pub uc_stack: stack_t, + pub uc_mcontext: mcontext_t, + } +} + +s_no_extra_traits! { + pub struct sockaddr_un { + pub sun_len: u8, + pub sun_family: sa_family_t, + pub sun_path: [::c_char; 104] + } + + pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: sa_family_t, + __ss_pad1: [::c_char; 6], + __ss_align: i64, + __ss_pad2: [::c_char; 112], + } + + pub struct utsname { + pub sysname: [::c_char; _SYSNAME_SIZE], + pub nodename: [::c_char; _SYSNAME_SIZE], + pub release: [::c_char; _SYSNAME_SIZE], + pub version: [::c_char; _SYSNAME_SIZE], + pub machine: [::c_char; _SYSNAME_SIZE], + } + + pub struct sigevent { + pub sigev_notify: ::c_int, + __sigev_un1: usize, // union + pub sigev_value: ::sigval, + __sigev_un2: usize, // union + + } + pub struct dirent { + pub d_ino: ::ino_t, + pub d_offset: ::off_t, + pub d_reclen: ::c_short, + pub d_namelen: ::c_short, + pub d_name: [::c_char; 1], // flex array + } + + pub struct dirent_extra { + pub d_datalen: u16, + pub d_type: u16, + pub d_reserved: u32, + } + + pub struct stat { + pub st_ino: ::ino_t, + pub st_size: ::off_t, + pub st_dev: ::dev_t, + pub st_rdev: ::dev_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub __old_st_mtime: ::_Time32t, + pub __old_st_atime: ::_Time32t, + pub __old_st_ctime: ::_Time32t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_blocksize: ::blksize_t, + pub st_nblocks: i32, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_mtim: ::timespec, + pub st_atim: ::timespec, + pub st_ctim: ::timespec, + } + + pub struct sigset_t { + __val: [u32; 2], + } + + pub struct mq_attr { + pub mq_maxmsg: ::c_long, + pub mq_msgsize: ::c_long, + pub mq_flags: ::c_long, + pub mq_curmsgs: ::c_long, + pub mq_sendwait: ::c_long, + pub mq_recvwait: ::c_long, + } + + pub struct msg { + pub msg_next: *mut ::msg, + pub msg_type: ::c_long, + pub msg_ts: ::c_ushort, + pub msg_spot: ::c_short, + _pad: [u8; 4], + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_first: *mut ::msg, + pub msg_last: *mut ::msg, + pub msg_cbytes: ::msglen_t, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + pub msg_stime: ::time_t, + msg_pad1: ::c_long, + pub msg_rtime: ::time_t, + msg_pad2: ::c_long, + pub msg_ctime: ::time_t, + msg_pad3: ::c_long, + msg_pad4: [::c_long; 4], + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::sa_family_t, + pub sdl_index: u16, + pub sdl_type: ::c_uchar, + pub sdl_nlen: ::c_uchar, + pub sdl_alen: ::c_uchar, + pub sdl_slen: ::c_uchar, + pub sdl_data: [::c_char; 12], + } + + pub struct sync_t { + __u: ::c_uint, // union + pub __owner: ::c_uint, + } + + #[repr(align(4))] + pub struct pthread_barrier_t { // union + __pad: [u8; 28], // union + } + + pub struct pthread_rwlock_t { + pub __active: ::c_int, + pub __blockedwriters: ::c_int, + pub __blockedreaders: ::c_int, + pub __heavy: ::c_int, + pub __lock: ::pthread_mutex_t, // union + pub __rcond: ::pthread_cond_t, // union + pub __wcond: ::pthread_cond_t, // union + pub __owner: ::c_uint, + pub __spare: ::c_uint, + } +} + +cfg_if! { + if #[cfg(feature = "extra_traits")] { + impl PartialEq for sockaddr_un { + fn eq(&self, other: &sockaddr_un) -> bool { + self.sun_len == other.sun_len + && self.sun_family == other.sun_family + && self + .sun_path + .iter() + .zip(other.sun_path.iter()) + .all(|(a,b)| a == b) + } + } + + impl Eq for sockaddr_un {} + + impl ::fmt::Debug for sockaddr_un { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("sockaddr_un") + .field("sun_len", &self.sun_len) + .field("sun_family", &self.sun_family) + // FIXME: .field("sun_path", &self.sun_path) + .finish() + } + } + + impl ::hash::Hash for sockaddr_un { + fn hash(&self, state: &mut H) { + self.sun_len.hash(state); + self.sun_family.hash(state); + self.sun_path.hash(state); + } + } + + impl PartialEq for utsname { + fn eq(&self, other: &utsname) -> bool { + self.sysname + .iter() + .zip(other.sysname.iter()) + .all(|(a,b)| a == b) + && self + .nodename + .iter() + .zip(other.nodename.iter()) + .all(|(a,b)| a == b) + && self + .release + .iter() + .zip(other.release.iter()) + .all(|(a,b)| a == b) + && self + .version + .iter() + .zip(other.version.iter()) + .all(|(a,b)| a == b) + && self + .machine + .iter() + .zip(other.machine.iter()) + .all(|(a,b)| a == b) + } + } + + impl Eq for utsname {} + + impl ::fmt::Debug for utsname { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("utsname") + // FIXME: .field("sysname", &self.sysname) + // FIXME: .field("nodename", &self.nodename) + // FIXME: .field("release", &self.release) + // FIXME: .field("version", &self.version) + // FIXME: .field("machine", &self.machine) + .finish() + } + } + + impl ::hash::Hash for utsname { + fn hash(&self, state: &mut H) { + self.sysname.hash(state); + self.nodename.hash(state); + self.release.hash(state); + self.version.hash(state); + self.machine.hash(state); + } + } + + impl PartialEq for mq_attr { + fn eq(&self, other: &mq_attr) -> bool { + self.mq_maxmsg == other.mq_maxmsg && + self.mq_msgsize == other.mq_msgsize && + self.mq_flags == other.mq_flags && + self.mq_curmsgs == other.mq_curmsgs && + self.mq_msgsize == other.mq_msgsize && + self.mq_sendwait == other.mq_sendwait && + self.mq_recvwait == other.mq_recvwait + } + } + + impl Eq for mq_attr {} + + impl ::fmt::Debug for mq_attr { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("mq_attr") + .field("mq_maxmsg", &self.mq_maxmsg) + .field("mq_msgsize", &self.mq_msgsize) + .field("mq_flags", &self.mq_flags) + .field("mq_curmsgs", &self.mq_curmsgs) + .field("mq_msgsize", &self.mq_msgsize) + .field("mq_sendwait", &self.mq_sendwait) + .field("mq_recvwait", &self.mq_recvwait) + .finish() + } + } + + impl PartialEq for sockaddr_storage { + fn eq(&self, other: &sockaddr_storage) -> bool { + self.ss_len == other.ss_len + && self.ss_family == other.ss_family + && self.__ss_pad1 == other.__ss_pad1 + && self.__ss_align == other.__ss_align + && self + .__ss_pad2 + .iter() + .zip(other.__ss_pad2.iter()) + .all(|(a, b)| a == b) + } + } + + impl Eq for sockaddr_storage {} + + impl ::fmt::Debug for sockaddr_storage { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("sockaddr_storage") + .field("ss_len", &self.ss_len) + .field("ss_family", &self.ss_family) + .field("__ss_pad1", &self.__ss_pad1) + .field("__ss_align", &self.__ss_align) + // FIXME: .field("__ss_pad2", &self.__ss_pad2) + .finish() + } + } + + impl ::hash::Hash for sockaddr_storage { + fn hash(&self, state: &mut H) { + self.ss_len.hash(state); + self.ss_family.hash(state); + self.__ss_pad1.hash(state); + self.__ss_align.hash(state); + self.__ss_pad2.hash(state); + } + } + + impl PartialEq for dirent { + fn eq(&self, other: &dirent) -> bool { + self.d_ino == other.d_ino + && self.d_offset == other.d_offset + && self.d_reclen == other.d_reclen + && self.d_namelen == other.d_namelen + && self + .d_name[..self.d_namelen as _] + .iter() + .zip(other.d_name.iter()) + .all(|(a,b)| a == b) + } + } + + impl Eq for dirent {} + + impl ::fmt::Debug for dirent { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + f.debug_struct("dirent") + .field("d_ino", &self.d_ino) + .field("d_offset", &self.d_offset) + .field("d_reclen", &self.d_reclen) + .field("d_namelen", &self.d_namelen) + .field("d_name", &&self.d_name[..self.d_namelen as _]) + .finish() + } + } + + impl ::hash::Hash for dirent { + fn hash(&self, state: &mut H) { + self.d_ino.hash(state); + self.d_offset.hash(state); + self.d_reclen.hash(state); + self.d_namelen.hash(state); + self.d_name[..self.d_namelen as _].hash(state); + } + } + } +} + +pub const _SYSNAME_SIZE: usize = 256 + 1; +pub const RLIM_INFINITY: ::rlim_t = 0xfffffffffffffffd; +pub const O_LARGEFILE: ::c_int = 0o0100000; + +// intentionally not public, only used for fd_set +cfg_if! { + if #[cfg(target_pointer_width = "32")] { + const ULONG_SIZE: usize = 32; + } else if #[cfg(target_pointer_width = "64")] { + const ULONG_SIZE: usize = 64; + } else { + // Unknown target_pointer_width + } +} + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 32767; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +pub const F_DUPFD_CLOEXEC: ::c_int = 5; + +pub const SIGTRAP: ::c_int = 5; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_MONOTONIC: ::clockid_t = 2; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 3; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 4; +pub const TIMER_ABSTIME: ::c_uint = 0x80000000; + +pub const RUSAGE_SELF: ::c_int = 0; + +pub const F_OK: ::c_int = 0; +pub const X_OK: ::c_int = 1; +pub const W_OK: ::c_int = 2; +pub const R_OK: ::c_int = 4; + +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; + +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; + +pub const PROT_NONE: ::c_int = 0x00000000; +pub const PROT_READ: ::c_int = 0x00000100; +pub const PROT_WRITE: ::c_int = 0x00000200; +pub const PROT_EXEC: ::c_int = 0x00000400; + +pub const MAP_FILE: ::c_int = 0; +pub const MAP_SHARED: ::c_int = 1; +pub const MAP_PRIVATE: ::c_int = 2; +pub const MAP_FIXED: ::c_int = 0x10; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +pub const MS_ASYNC: ::c_int = 1; +pub const MS_INVALIDATE: ::c_int = 4; +pub const MS_SYNC: ::c_int = 2; + +pub const SCM_RIGHTS: ::c_int = 0x01; +pub const SCM_TIMESTAMP: ::c_int = 0x02; +pub const SCM_CREDS: ::c_int = 0x04; + +pub const MAP_TYPE: ::c_int = 0x3; + +pub const IFF_UP: ::c_int = 0x00000001; +pub const IFF_BROADCAST: ::c_int = 0x00000002; +pub const IFF_DEBUG: ::c_int = 0x00000004; +pub const IFF_LOOPBACK: ::c_int = 0x00000008; +pub const IFF_POINTOPOINT: ::c_int = 0x00000010; +pub const IFF_NOTRAILERS: ::c_int = 0x00000020; +pub const IFF_RUNNING: ::c_int = 0x00000040; +pub const IFF_NOARP: ::c_int = 0x00000080; +pub const IFF_PROMISC: ::c_int = 0x00000100; +pub const IFF_ALLMULTI: ::c_int = 0x00000200; +pub const IFF_MULTICAST: ::c_int = 0x00008000; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = AF_LOCAL; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_IPX: ::c_int = 23; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_INET6: ::c_int = 24; +pub const AF_ROUTE: ::c_int = 17; +pub const AF_SNA: ::c_int = 11; +pub const AF_BLUETOOTH: ::c_int = 31; +pub const AF_ISDN: ::c_int = 26; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_UNIX: ::c_int = PF_LOCAL; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_INET6: ::c_int = AF_INET6; +pub const pseudo_AF_KEY: ::c_int = 29; +pub const PF_KEY: ::c_int = pseudo_AF_KEY; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_SNA: ::c_int = AF_SNA; + +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_ISDN: ::c_int = AF_ISDN; + +pub const SOMAXCONN: ::c_int = 128; + +pub const MSG_OOB: ::c_int = 0x0001; +pub const MSG_PEEK: ::c_int = 0x0002; +pub const MSG_DONTROUTE: ::c_int = 0x0004; +pub const MSG_CTRUNC: ::c_int = 0x0020; +pub const MSG_TRUNC: ::c_int = 0x0010; +pub const MSG_DONTWAIT: ::c_int = 0x0080; +pub const MSG_EOR: ::c_int = 0x0008; +pub const MSG_WAITALL: ::c_int = 0x0040; +pub const MSG_NOSIGNAL: ::c_int = 0x0800; +pub const MSG_WAITFORONE: ::c_int = 0x2000; + +pub const IP_TOS: ::c_int = 3; +pub const IP_TTL: ::c_int = 4; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_OPTIONS: ::c_int = 1; +pub const IP_RECVOPTS: ::c_int = 5; +pub const IP_RETOPTS: ::c_int = 8; +pub const IP_PKTINFO: ::c_int = 25; +pub const IP_IPSEC_POLICY_COMPAT: ::c_int = 22; +pub const IP_MULTICAST_IF: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_MULTICAST_LOOP: ::c_int = 11; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; +pub const IP_DEFAULT_MULTICAST_TTL: ::c_int = 1; +pub const IP_DEFAULT_MULTICAST_LOOP: ::c_int = 1; + +pub const IPPROTO_HOPOPTS: ::c_int = 0; +pub const IPPROTO_IGMP: ::c_int = 2; +pub const IPPROTO_IPIP: ::c_int = 4; +pub const IPPROTO_EGP: ::c_int = 8; +pub const IPPROTO_PUP: ::c_int = 12; +pub const IPPROTO_IDP: ::c_int = 22; +pub const IPPROTO_TP: ::c_int = 29; +pub const IPPROTO_ROUTING: ::c_int = 43; +pub const IPPROTO_FRAGMENT: ::c_int = 44; +pub const IPPROTO_RSVP: ::c_int = 46; +pub const IPPROTO_GRE: ::c_int = 47; +pub const IPPROTO_ESP: ::c_int = 50; +pub const IPPROTO_AH: ::c_int = 51; +pub const IPPROTO_NONE: ::c_int = 59; +pub const IPPROTO_DSTOPTS: ::c_int = 60; +pub const IPPROTO_ENCAP: ::c_int = 98; +pub const IPPROTO_PIM: ::c_int = 103; +pub const IPPROTO_SCTP: ::c_int = 132; +pub const IPPROTO_RAW: ::c_int = 255; +pub const IPPROTO_MAX: ::c_int = 256; +pub const IPPROTO_CARP: ::c_int = 112; +pub const IPPROTO_DIVERT: ::c_int = 259; +pub const IPPROTO_DONE: ::c_int = 257; +pub const IPPROTO_EON: ::c_int = 80; +pub const IPPROTO_ETHERIP: ::c_int = 97; +pub const IPPROTO_GGP: ::c_int = 3; +pub const IPPROTO_IPCOMP: ::c_int = 108; +pub const IPPROTO_MOBILE: ::c_int = 55; + +pub const IPV6_RTHDR_LOOSE: ::c_int = 0; +pub const IPV6_RTHDR_STRICT: ::c_int = 1; +pub const IPV6_UNICAST_HOPS: ::c_int = 4; +pub const IPV6_MULTICAST_IF: ::c_int = 9; +pub const IPV6_MULTICAST_HOPS: ::c_int = 10; +pub const IPV6_MULTICAST_LOOP: ::c_int = 11; +pub const IPV6_JOIN_GROUP: ::c_int = 12; +pub const IPV6_LEAVE_GROUP: ::c_int = 13; +pub const IPV6_CHECKSUM: ::c_int = 26; +pub const IPV6_V6ONLY: ::c_int = 27; +pub const IPV6_IPSEC_POLICY_COMPAT: ::c_int = 28; +pub const IPV6_RTHDRDSTOPTS: ::c_int = 35; +pub const IPV6_RECVPKTINFO: ::c_int = 36; +pub const IPV6_RECVHOPLIMIT: ::c_int = 37; +pub const IPV6_RECVRTHDR: ::c_int = 38; +pub const IPV6_RECVHOPOPTS: ::c_int = 39; +pub const IPV6_RECVDSTOPTS: ::c_int = 40; +pub const IPV6_RECVPATHMTU: ::c_int = 43; +pub const IPV6_PATHMTU: ::c_int = 44; +pub const IPV6_PKTINFO: ::c_int = 46; +pub const IPV6_HOPLIMIT: ::c_int = 47; +pub const IPV6_NEXTHOP: ::c_int = 48; +pub const IPV6_HOPOPTS: ::c_int = 49; +pub const IPV6_DSTOPTS: ::c_int = 50; +pub const IPV6_RECVTCLASS: ::c_int = 57; +pub const IPV6_TCLASS: ::c_int = 61; +pub const IPV6_DONTFRAG: ::c_int = 62; + +pub const TCP_NODELAY: ::c_int = 0x01; +pub const TCP_MAXSEG: ::c_int = 0x02; +pub const TCP_MD5SIG: ::c_int = 0x10; +pub const TCP_KEEPALIVE: ::c_int = 0x04; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 0x1; +pub const LOCK_EX: ::c_int = 0x2; +pub const LOCK_NB: ::c_int = 0x4; +pub const LOCK_UN: ::c_int = 0x8; + +pub const SS_ONSTACK: ::c_int = 1; +pub const SS_DISABLE: ::c_int = 2; + +pub const PATH_MAX: ::c_int = 1024; + +pub const UIO_MAXIOV: ::c_int = 1024; + +pub const FD_SETSIZE: usize = 256; + +pub const TCIOFF: ::c_int = 0x0002; +pub const TCION: ::c_int = 0x0003; +pub const TCOOFF: ::c_int = 0x0000; +pub const TCOON: ::c_int = 0x0001; +pub const TCIFLUSH: ::c_int = 0; +pub const TCOFLUSH: ::c_int = 1; +pub const TCIOFLUSH: ::c_int = 2; +pub const NL0: ::tcflag_t = 0x000; +pub const NL1: ::tcflag_t = 0x100; +pub const TAB0: ::tcflag_t = 0x0000; +pub const CR0: ::tcflag_t = 0x000; +pub const FF0: ::tcflag_t = 0x0000; +pub const BS0: ::tcflag_t = 0x0000; +pub const VT0: ::tcflag_t = 0x0000; +pub const VERASE: usize = 2; +pub const VKILL: usize = 3; +pub const VINTR: usize = 0; +pub const VQUIT: usize = 1; +pub const VLNEXT: usize = 15; +pub const IGNBRK: ::tcflag_t = 0x00000001; +pub const BRKINT: ::tcflag_t = 0x00000002; +pub const IGNPAR: ::tcflag_t = 0x00000004; +pub const PARMRK: ::tcflag_t = 0x00000008; +pub const INPCK: ::tcflag_t = 0x00000010; +pub const ISTRIP: ::tcflag_t = 0x00000020; +pub const INLCR: ::tcflag_t = 0x00000040; +pub const IGNCR: ::tcflag_t = 0x00000080; +pub const ICRNL: ::tcflag_t = 0x00000100; +pub const IXANY: ::tcflag_t = 0x00000800; +pub const IMAXBEL: ::tcflag_t = 0x00002000; +pub const OPOST: ::tcflag_t = 0x00000001; +pub const CS5: ::tcflag_t = 0x00; +pub const ECHO: ::tcflag_t = 0x00000008; +pub const OCRNL: ::tcflag_t = 0x00000008; +pub const ONOCR: ::tcflag_t = 0x00000010; +pub const ONLRET: ::tcflag_t = 0x00000020; +pub const OFILL: ::tcflag_t = 0x00000040; +pub const OFDEL: ::tcflag_t = 0x00000080; + +pub const WNOHANG: ::c_int = 0x0040; +pub const WUNTRACED: ::c_int = 0x0004; +pub const WSTOPPED: ::c_int = WUNTRACED; +pub const WEXITED: ::c_int = 0x0001; +pub const WCONTINUED: ::c_int = 0x0008; +pub const WNOWAIT: ::c_int = 0x0080; +pub const WTRAPPED: ::c_int = 0x0002; + +pub const RTLD_LOCAL: ::c_int = 0x0200; +pub const RTLD_LAZY: ::c_int = 0x0001; + +pub const POSIX_FADV_NORMAL: ::c_int = 0; +pub const POSIX_FADV_RANDOM: ::c_int = 2; +pub const POSIX_FADV_SEQUENTIAL: ::c_int = 1; +pub const POSIX_FADV_WILLNEED: ::c_int = 3; + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_EACCESS: ::c_int = 0x0001; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x0002; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x0004; +pub const AT_REMOVEDIR: ::c_int = 0x0008; + +pub const LOG_CRON: ::c_int = 9 << 3; +pub const LOG_AUTHPRIV: ::c_int = 10 << 3; +pub const LOG_FTP: ::c_int = 11 << 3; +pub const LOG_PERROR: ::c_int = 0x20; + +pub const PIPE_BUF: usize = 5120; + +pub const CLD_EXITED: ::c_int = 1; +pub const CLD_KILLED: ::c_int = 2; +pub const CLD_DUMPED: ::c_int = 3; +pub const CLD_TRAPPED: ::c_int = 4; +pub const CLD_STOPPED: ::c_int = 5; +pub const CLD_CONTINUED: ::c_int = 6; + +pub const UTIME_OMIT: c_long = 0x40000002; +pub const UTIME_NOW: c_long = 0x40000001; + +pub const POLLIN: ::c_short = POLLRDNORM | POLLRDBAND; +pub const POLLPRI: ::c_short = 0x0008; +pub const POLLOUT: ::c_short = 0x0002; +pub const POLLERR: ::c_short = 0x0020; +pub const POLLHUP: ::c_short = 0x0040; +pub const POLLNVAL: ::c_short = 0x1000; +pub const POLLRDNORM: ::c_short = 0x0001; +pub const POLLRDBAND: ::c_short = 0x0004; + +pub const IPTOS_LOWDELAY: u8 = 0x10; +pub const IPTOS_THROUGHPUT: u8 = 0x08; +pub const IPTOS_RELIABILITY: u8 = 0x04; +pub const IPTOS_MINCOST: u8 = 0x02; + +pub const IPTOS_PREC_NETCONTROL: u8 = 0xe0; +pub const IPTOS_PREC_INTERNETCONTROL: u8 = 0xc0; +pub const IPTOS_PREC_CRITIC_ECP: u8 = 0xa0; +pub const IPTOS_PREC_FLASHOVERRIDE: u8 = 0x80; +pub const IPTOS_PREC_FLASH: u8 = 0x60; +pub const IPTOS_PREC_IMMEDIATE: u8 = 0x40; +pub const IPTOS_PREC_PRIORITY: u8 = 0x20; +pub const IPTOS_PREC_ROUTINE: u8 = 0x00; + +pub const IPTOS_ECN_MASK: u8 = 0x03; +pub const IPTOS_ECN_ECT1: u8 = 0x01; +pub const IPTOS_ECN_ECT0: u8 = 0x02; +pub const IPTOS_ECN_CE: u8 = 0x03; + +pub const IPOPT_CONTROL: u8 = 0x00; +pub const IPOPT_RESERVED1: u8 = 0x20; +pub const IPOPT_RESERVED2: u8 = 0x60; +pub const IPOPT_LSRR: u8 = 131; +pub const IPOPT_RR: u8 = 7; +pub const IPOPT_SSRR: u8 = 137; +pub const IPDEFTTL: u8 = 64; +pub const IPOPT_OPTVAL: u8 = 0; +pub const IPOPT_OLEN: u8 = 1; +pub const IPOPT_OFFSET: u8 = 2; +pub const IPOPT_MINOFF: u8 = 4; +pub const IPOPT_NOP: u8 = 1; +pub const IPOPT_EOL: u8 = 0; +pub const IPOPT_TS: u8 = 68; +pub const IPOPT_TS_TSONLY: u8 = 0; +pub const IPOPT_TS_TSANDADDR: u8 = 1; +pub const IPOPT_TS_PRESPEC: u8 = 3; + +pub const MAX_IPOPTLEN: u8 = 40; +pub const IPVERSION: u8 = 4; +pub const MAXTTL: u8 = 255; + +pub const ARPHRD_ETHER: u16 = 1; +pub const ARPHRD_IEEE802: u16 = 6; +pub const ARPHRD_ARCNET: u16 = 7; +pub const ARPHRD_IEEE1394: u16 = 24; + +pub const SOL_SOCKET: ::c_int = 0xffff; + +pub const SO_DEBUG: ::c_int = 0x0001; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_BINDTODEVICE: ::c_int = 0x0800; +pub const SO_TIMESTAMP: ::c_int = 0x0400; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; + +pub const TIOCM_LE: ::c_int = 0x0100; +pub const TIOCM_DTR: ::c_int = 0x0001; +pub const TIOCM_RTS: ::c_int = 0x0002; +pub const TIOCM_ST: ::c_int = 0x0200; +pub const TIOCM_SR: ::c_int = 0x0400; +pub const TIOCM_CTS: ::c_int = 0x1000; +pub const TIOCM_CAR: ::c_int = TIOCM_CD; +pub const TIOCM_CD: ::c_int = 0x8000; +pub const TIOCM_RNG: ::c_int = TIOCM_RI; +pub const TIOCM_RI: ::c_int = 0x4000; +pub const TIOCM_DSR: ::c_int = 0x2000; + +pub const SCHED_OTHER: ::c_int = 3; +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_RR: ::c_int = 2; + +pub const IPC_PRIVATE: ::key_t = 0; + +pub const IPC_CREAT: ::c_int = 0o001000; +pub const IPC_EXCL: ::c_int = 0o002000; +pub const IPC_NOWAIT: ::c_int = 0o004000; + +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; + +pub const MSG_NOERROR: ::c_int = 0o010000; + +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const SEM_FAILED: *mut ::sem_t = 0xFFFFFFFFFFFFFFFF as *mut sem_t; + +pub const AI_PASSIVE: ::c_int = 0x00000001; +pub const AI_CANONNAME: ::c_int = 0x00000002; +pub const AI_NUMERICHOST: ::c_int = 0x00000004; + +pub const AI_NUMERICSERV: ::c_int = 0x00000008; + +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 14; + +pub const NI_NUMERICHOST: ::c_int = 0x00000002; +pub const NI_NUMERICSERV: ::c_int = 0x00000008; +pub const NI_NOFQDN: ::c_int = 0x00000001; +pub const NI_NAMEREQD: ::c_int = 0x00000004; +pub const NI_DGRAM: ::c_int = 0x00000010; + +pub const AIO_CANCELED: ::c_int = 0; +pub const AIO_NOTCANCELED: ::c_int = 2; +pub const AIO_ALLDONE: ::c_int = 1; +pub const LIO_READ: ::c_int = 1; +pub const LIO_WRITE: ::c_int = 2; +pub const LIO_NOP: ::c_int = 0; +pub const LIO_WAIT: ::c_int = 1; +pub const LIO_NOWAIT: ::c_int = 0; + +pub const ITIMER_REAL: ::c_int = 0; +pub const ITIMER_VIRTUAL: ::c_int = 1; +pub const ITIMER_PROF: ::c_int = 2; + +pub const POSIX_SPAWN_RESETIDS: ::c_int = 0x00000010; +pub const POSIX_SPAWN_SETPGROUP: ::c_int = 0x00000001; +pub const POSIX_SPAWN_SETSIGDEF: ::c_int = 0x00000004; +pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x00000002; +pub const POSIX_SPAWN_SETSCHEDPARAM: ::c_int = 0x00000400; +pub const POSIX_SPAWN_SETSCHEDULER: ::c_int = 0x00000040; + +pub const IPTOS_ECN_NOT_ECT: u8 = 0x00; + +pub const RTF_UP: ::c_ushort = 0x0001; +pub const RTF_GATEWAY: ::c_ushort = 0x0002; + +pub const RTF_HOST: ::c_ushort = 0x0004; +pub const RTF_DYNAMIC: ::c_ushort = 0x0010; +pub const RTF_MODIFIED: ::c_ushort = 0x0020; +pub const RTF_REJECT: ::c_ushort = 0x0008; +pub const RTF_STATIC: ::c_ushort = 0x0800; +pub const RTF_XRESOLVE: ::c_ushort = 0x0200; +pub const RTF_BROADCAST: u32 = 0x80000; +pub const RTM_NEWADDR: u16 = 0xc; +pub const RTM_DELADDR: u16 = 0xd; +pub const RTA_DST: ::c_ushort = 0x1; +pub const RTA_GATEWAY: ::c_ushort = 0x2; + +pub const UDP_ENCAP: ::c_int = 100; + +pub const IN_ACCESS: u32 = 0x00000001; +pub const IN_MODIFY: u32 = 0x00000002; +pub const IN_ATTRIB: u32 = 0x00000004; +pub const IN_CLOSE_WRITE: u32 = 0x00000008; +pub const IN_CLOSE_NOWRITE: u32 = 0x00000010; +pub const IN_CLOSE: u32 = IN_CLOSE_WRITE | IN_CLOSE_NOWRITE; +pub const IN_OPEN: u32 = 0x00000020; +pub const IN_MOVED_FROM: u32 = 0x00000040; +pub const IN_MOVED_TO: u32 = 0x00000080; +pub const IN_MOVE: u32 = IN_MOVED_FROM | IN_MOVED_TO; +pub const IN_CREATE: u32 = 0x00000100; +pub const IN_DELETE: u32 = 0x00000200; +pub const IN_DELETE_SELF: u32 = 0x00000400; +pub const IN_MOVE_SELF: u32 = 0x00000800; +pub const IN_UNMOUNT: u32 = 0x00002000; +pub const IN_Q_OVERFLOW: u32 = 0x00004000; +pub const IN_IGNORED: u32 = 0x00008000; +pub const IN_ONLYDIR: u32 = 0x01000000; +pub const IN_DONT_FOLLOW: u32 = 0x02000000; + +pub const IN_ISDIR: u32 = 0x40000000; +pub const IN_ONESHOT: u32 = 0x80000000; + +pub const REG_EXTENDED: ::c_int = 0o0001; +pub const REG_ICASE: ::c_int = 0o0002; +pub const REG_NEWLINE: ::c_int = 0o0010; +pub const REG_NOSUB: ::c_int = 0o0004; + +pub const REG_NOTBOL: ::c_int = 0o00001; +pub const REG_NOTEOL: ::c_int = 0o00002; + +pub const REG_ENOSYS: ::c_int = 17; +pub const REG_NOMATCH: ::c_int = 1; +pub const REG_BADPAT: ::c_int = 2; +pub const REG_ECOLLATE: ::c_int = 3; +pub const REG_ECTYPE: ::c_int = 4; +pub const REG_EESCAPE: ::c_int = 5; +pub const REG_ESUBREG: ::c_int = 6; +pub const REG_EBRACK: ::c_int = 7; +pub const REG_EPAREN: ::c_int = 8; +pub const REG_EBRACE: ::c_int = 9; +pub const REG_BADBR: ::c_int = 10; +pub const REG_ERANGE: ::c_int = 11; +pub const REG_ESPACE: ::c_int = 12; +pub const REG_BADRPT: ::c_int = 13; + +// errno.h +pub const EOK: ::c_int = 0; +pub const EWOULDBLOCK: ::c_int = EAGAIN; +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const ECHRNG: ::c_int = 37; +pub const EL2NSYNC: ::c_int = 38; +pub const EL3HLT: ::c_int = 39; +pub const EL3RST: ::c_int = 40; +pub const ELNRNG: ::c_int = 41; +pub const EUNATCH: ::c_int = 42; +pub const ENOCSI: ::c_int = 43; +pub const EL2HLT: ::c_int = 44; +pub const EDEADLK: ::c_int = 45; +pub const ENOLCK: ::c_int = 46; +pub const ECANCELED: ::c_int = 47; +pub const EDQUOT: ::c_int = 49; +pub const EBADE: ::c_int = 50; +pub const EBADR: ::c_int = 51; +pub const EXFULL: ::c_int = 52; +pub const ENOANO: ::c_int = 53; +pub const EBADRQC: ::c_int = 54; +pub const EBADSLT: ::c_int = 55; +pub const EDEADLOCK: ::c_int = 56; +pub const EBFONT: ::c_int = 57; +pub const EOWNERDEAD: ::c_int = 58; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EMULTIHOP: ::c_int = 74; +pub const EBADMSG: ::c_int = 77; +pub const ENAMETOOLONG: ::c_int = 78; +pub const EOVERFLOW: ::c_int = 79; +pub const ENOTUNIQ: ::c_int = 80; +pub const EBADFD: ::c_int = 81; +pub const EREMCHG: ::c_int = 82; +pub const ELIBACC: ::c_int = 83; +pub const ELIBBAD: ::c_int = 84; +pub const ELIBSCN: ::c_int = 85; +pub const ELIBMAX: ::c_int = 86; +pub const ELIBEXEC: ::c_int = 87; +pub const EILSEQ: ::c_int = 88; +pub const ENOSYS: ::c_int = 89; +pub const ELOOP: ::c_int = 90; +pub const ERESTART: ::c_int = 91; +pub const ESTRPIPE: ::c_int = 92; +pub const ENOTEMPTY: ::c_int = 93; +pub const EUSERS: ::c_int = 94; +pub const ENOTRECOVERABLE: ::c_int = 95; +pub const EOPNOTSUPP: ::c_int = 103; +pub const EFPOS: ::c_int = 110; +pub const ESTALE: ::c_int = 122; +pub const EINPROGRESS: ::c_int = 236; +pub const EALREADY: ::c_int = 237; +pub const ENOTSOCK: ::c_int = 238; +pub const EDESTADDRREQ: ::c_int = 239; +pub const EMSGSIZE: ::c_int = 240; +pub const EPROTOTYPE: ::c_int = 241; +pub const ENOPROTOOPT: ::c_int = 242; +pub const EPROTONOSUPPORT: ::c_int = 243; +pub const ESOCKTNOSUPPORT: ::c_int = 244; +pub const EPFNOSUPPORT: ::c_int = 246; +pub const EAFNOSUPPORT: ::c_int = 247; +pub const EADDRINUSE: ::c_int = 248; +pub const EADDRNOTAVAIL: ::c_int = 249; +pub const ENETDOWN: ::c_int = 250; +pub const ENETUNREACH: ::c_int = 251; +pub const ENETRESET: ::c_int = 252; +pub const ECONNABORTED: ::c_int = 253; +pub const ECONNRESET: ::c_int = 254; +pub const ENOBUFS: ::c_int = 255; +pub const EISCONN: ::c_int = 256; +pub const ENOTCONN: ::c_int = 257; +pub const ESHUTDOWN: ::c_int = 258; +pub const ETOOMANYREFS: ::c_int = 259; +pub const ETIMEDOUT: ::c_int = 260; +pub const ECONNREFUSED: ::c_int = 261; +pub const EHOSTDOWN: ::c_int = 264; +pub const EHOSTUNREACH: ::c_int = 265; +pub const EBADRPC: ::c_int = 272; +pub const ERPCMISMATCH: ::c_int = 273; +pub const EPROGUNAVAIL: ::c_int = 274; +pub const EPROGMISMATCH: ::c_int = 275; +pub const EPROCUNAVAIL: ::c_int = 276; +pub const ENOREMOTE: ::c_int = 300; +pub const ENONDP: ::c_int = 301; +pub const EBADFSYS: ::c_int = 302; +pub const EMORE: ::c_int = 309; +pub const ECTRLTERM: ::c_int = 310; +pub const ENOLIC: ::c_int = 311; +pub const ESRVRFAULT: ::c_int = 312; +pub const EENDIAN: ::c_int = 313; +pub const ESECTYPEINVAL: ::c_int = 314; + +pub const RUSAGE_CHILDREN: ::c_int = -1; +pub const L_tmpnam: ::c_uint = 255; + +pub const _PC_LINK_MAX: ::c_int = 1; +pub const _PC_MAX_CANON: ::c_int = 2; +pub const _PC_MAX_INPUT: ::c_int = 3; +pub const _PC_NAME_MAX: ::c_int = 4; +pub const _PC_PATH_MAX: ::c_int = 5; +pub const _PC_PIPE_BUF: ::c_int = 6; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 9; +pub const _PC_NO_TRUNC: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; +pub const _PC_SYNC_IO: ::c_int = 14; +pub const _PC_ASYNC_IO: ::c_int = 12; +pub const _PC_PRIO_IO: ::c_int = 13; +pub const _PC_SOCK_MAXBUF: ::c_int = 15; +pub const _PC_FILESIZEBITS: ::c_int = 16; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 22; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 23; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 24; +pub const _PC_REC_XFER_ALIGN: ::c_int = 25; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 21; +pub const _PC_SYMLINK_MAX: ::c_int = 17; +pub const _PC_2_SYMLINKS: ::c_int = 20; + +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_ARG_MAX: ::c_int = 1; +pub const _SC_CHILD_MAX: ::c_int = 2; +pub const _SC_CLK_TCK: ::c_int = 3; +pub const _SC_NGROUPS_MAX: ::c_int = 4; +pub const _SC_OPEN_MAX: ::c_int = 5; +pub const _SC_JOB_CONTROL: ::c_int = 6; +pub const _SC_SAVED_IDS: ::c_int = 7; +pub const _SC_VERSION: ::c_int = 8; +pub const _SC_PASS_MAX: ::c_int = 9; +pub const _SC_PAGESIZE: ::c_int = 11; +pub const _SC_XOPEN_VERSION: ::c_int = 12; +pub const _SC_STREAM_MAX: ::c_int = 13; +pub const _SC_TZNAME_MAX: ::c_int = 14; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 15; +pub const _SC_AIO_MAX: ::c_int = 16; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 17; +pub const _SC_DELAYTIMER_MAX: ::c_int = 18; +pub const _SC_MQ_OPEN_MAX: ::c_int = 19; +pub const _SC_MQ_PRIO_MAX: ::c_int = 20; +pub const _SC_RTSIG_MAX: ::c_int = 21; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 22; +pub const _SC_SEM_VALUE_MAX: ::c_int = 23; +pub const _SC_SIGQUEUE_MAX: ::c_int = 24; +pub const _SC_TIMER_MAX: ::c_int = 25; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 26; +pub const _SC_FSYNC: ::c_int = 27; +pub const _SC_MAPPED_FILES: ::c_int = 28; +pub const _SC_MEMLOCK: ::c_int = 29; +pub const _SC_MEMLOCK_RANGE: ::c_int = 30; +pub const _SC_MEMORY_PROTECTION: ::c_int = 31; +pub const _SC_MESSAGE_PASSING: ::c_int = 32; +pub const _SC_PRIORITIZED_IO: ::c_int = 33; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 34; +pub const _SC_REALTIME_SIGNALS: ::c_int = 35; +pub const _SC_SEMAPHORES: ::c_int = 36; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 37; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 38; +pub const _SC_TIMERS: ::c_int = 39; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 40; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 41; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 42; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 43; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 44; +pub const _SC_THREAD_STACK_MIN: ::c_int = 45; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 46; +pub const _SC_TTY_NAME_MAX: ::c_int = 47; +pub const _SC_THREADS: ::c_int = 48; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 49; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 50; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 51; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 52; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 53; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 54; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 55; +pub const _SC_2_CHAR_TERM: ::c_int = 56; +pub const _SC_2_C_BIND: ::c_int = 57; +pub const _SC_2_C_DEV: ::c_int = 58; +pub const _SC_2_C_VERSION: ::c_int = 59; +pub const _SC_2_FORT_DEV: ::c_int = 60; +pub const _SC_2_FORT_RUN: ::c_int = 61; +pub const _SC_2_LOCALEDEF: ::c_int = 62; +pub const _SC_2_SW_DEV: ::c_int = 63; +pub const _SC_2_UPE: ::c_int = 64; +pub const _SC_2_VERSION: ::c_int = 65; +pub const _SC_ATEXIT_MAX: ::c_int = 66; +pub const _SC_AVPHYS_PAGES: ::c_int = 67; +pub const _SC_BC_BASE_MAX: ::c_int = 68; +pub const _SC_BC_DIM_MAX: ::c_int = 69; +pub const _SC_BC_SCALE_MAX: ::c_int = 70; +pub const _SC_BC_STRING_MAX: ::c_int = 71; +pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 72; +pub const _SC_CHAR_BIT: ::c_int = 73; +pub const _SC_CHAR_MAX: ::c_int = 74; +pub const _SC_CHAR_MIN: ::c_int = 75; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 76; +pub const _SC_EQUIV_CLASS_MAX: ::c_int = 77; +pub const _SC_EXPR_NEST_MAX: ::c_int = 78; +pub const _SC_INT_MAX: ::c_int = 79; +pub const _SC_INT_MIN: ::c_int = 80; +pub const _SC_LINE_MAX: ::c_int = 81; +pub const _SC_LONG_BIT: ::c_int = 82; +pub const _SC_MB_LEN_MAX: ::c_int = 83; +pub const _SC_NL_ARGMAX: ::c_int = 84; +pub const _SC_NL_LANGMAX: ::c_int = 85; +pub const _SC_NL_MSGMAX: ::c_int = 86; +pub const _SC_NL_NMAX: ::c_int = 87; +pub const _SC_NL_SETMAX: ::c_int = 88; +pub const _SC_NL_TEXTMAX: ::c_int = 89; +pub const _SC_NPROCESSORS_CONF: ::c_int = 90; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 91; +pub const _SC_NZERO: ::c_int = 92; +pub const _SC_PHYS_PAGES: ::c_int = 93; +pub const _SC_PII: ::c_int = 94; +pub const _SC_PII_INTERNET: ::c_int = 95; +pub const _SC_PII_INTERNET_DGRAM: ::c_int = 96; +pub const _SC_PII_INTERNET_STREAM: ::c_int = 97; +pub const _SC_PII_OSI: ::c_int = 98; +pub const _SC_PII_OSI_CLTS: ::c_int = 99; +pub const _SC_PII_OSI_COTS: ::c_int = 100; +pub const _SC_PII_OSI_M: ::c_int = 101; +pub const _SC_PII_SOCKET: ::c_int = 102; +pub const _SC_PII_XTI: ::c_int = 103; +pub const _SC_POLL: ::c_int = 104; +pub const _SC_RE_DUP_MAX: ::c_int = 105; +pub const _SC_SCHAR_MAX: ::c_int = 106; +pub const _SC_SCHAR_MIN: ::c_int = 107; +pub const _SC_SELECT: ::c_int = 108; +pub const _SC_SHRT_MAX: ::c_int = 109; +pub const _SC_SHRT_MIN: ::c_int = 110; +pub const _SC_SSIZE_MAX: ::c_int = 111; +pub const _SC_T_IOV_MAX: ::c_int = 112; +pub const _SC_UCHAR_MAX: ::c_int = 113; +pub const _SC_UINT_MAX: ::c_int = 114; +pub const _SC_UIO_MAXIOV: ::c_int = 115; +pub const _SC_ULONG_MAX: ::c_int = 116; +pub const _SC_USHRT_MAX: ::c_int = 117; +pub const _SC_WORD_BIT: ::c_int = 118; +pub const _SC_XOPEN_CRYPT: ::c_int = 119; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 120; +pub const _SC_XOPEN_SHM: ::c_int = 121; +pub const _SC_XOPEN_UNIX: ::c_int = 122; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 123; +pub const _SC_XOPEN_XPG2: ::c_int = 124; +pub const _SC_XOPEN_XPG3: ::c_int = 125; +pub const _SC_XOPEN_XPG4: ::c_int = 126; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 127; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 128; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 129; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 130; +pub const _SC_ADVISORY_INFO: ::c_int = 131; +pub const _SC_CPUTIME: ::c_int = 132; +pub const _SC_SPAWN: ::c_int = 133; +pub const _SC_SPORADIC_SERVER: ::c_int = 134; +pub const _SC_THREAD_CPUTIME: ::c_int = 135; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 136; +pub const _SC_TIMEOUTS: ::c_int = 137; +pub const _SC_BARRIERS: ::c_int = 138; +pub const _SC_CLOCK_SELECTION: ::c_int = 139; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 140; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 141; +pub const _SC_SPIN_LOCKS: ::c_int = 142; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 143; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 144; +pub const _SC_TRACE: ::c_int = 145; +pub const _SC_TRACE_INHERIT: ::c_int = 146; +pub const _SC_TRACE_LOG: ::c_int = 147; +pub const _SC_2_PBS: ::c_int = 148; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 149; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 150; +pub const _SC_2_PBS_LOCATE: ::c_int = 151; +pub const _SC_2_PBS_MESSAGE: ::c_int = 152; +pub const _SC_2_PBS_TRACK: ::c_int = 153; +pub const _SC_HOST_NAME_MAX: ::c_int = 154; +pub const _SC_IOV_MAX: ::c_int = 155; +pub const _SC_IPV6: ::c_int = 156; +pub const _SC_RAW_SOCKETS: ::c_int = 157; +pub const _SC_REGEXP: ::c_int = 158; +pub const _SC_SHELL: ::c_int = 159; +pub const _SC_SS_REPL_MAX: ::c_int = 160; +pub const _SC_SYMLOOP_MAX: ::c_int = 161; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 162; +pub const _SC_TRACE_NAME_MAX: ::c_int = 163; +pub const _SC_TRACE_SYS_MAX: ::c_int = 164; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 165; +pub const _SC_V6_ILP32_OFF32: ::c_int = 166; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 167; +pub const _SC_V6_LP64_OFF64: ::c_int = 168; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 169; +pub const _SC_XOPEN_REALTIME: ::c_int = 170; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 171; +pub const _SC_XOPEN_LEGACY: ::c_int = 172; +pub const _SC_XOPEN_STREAMS: ::c_int = 173; +pub const _SC_V7_ILP32_OFF32: ::c_int = 176; +pub const _SC_V7_ILP32_OFFBIG: ::c_int = 177; +pub const _SC_V7_LP64_OFF64: ::c_int = 178; +pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 179; + +pub const GLOB_ERR: ::c_int = 0x0001; +pub const GLOB_MARK: ::c_int = 0x0002; +pub const GLOB_NOSORT: ::c_int = 0x0004; +pub const GLOB_DOOFFS: ::c_int = 0x0008; +pub const GLOB_NOCHECK: ::c_int = 0x0010; +pub const GLOB_APPEND: ::c_int = 0x0020; +pub const GLOB_NOESCAPE: ::c_int = 0x0040; + +pub const GLOB_NOSPACE: ::c_int = 1; +pub const GLOB_ABORTED: ::c_int = 2; +pub const GLOB_NOMATCH: ::c_int = 3; + +pub const S_IEXEC: mode_t = ::S_IXUSR; +pub const S_IWRITE: mode_t = ::S_IWUSR; +pub const S_IREAD: mode_t = ::S_IRUSR; + +pub const S_IFIFO: ::mode_t = 0x1000; +pub const S_IFCHR: ::mode_t = 0x2000; +pub const S_IFDIR: ::mode_t = 0x4000; +pub const S_IFBLK: ::mode_t = 0x6000; +pub const S_IFREG: ::mode_t = 0x8000; +pub const S_IFLNK: ::mode_t = 0xA000; +pub const S_IFSOCK: ::mode_t = 0xC000; +pub const S_IFMT: ::mode_t = 0xF000; + +pub const S_IXOTH: ::mode_t = 0o000001; +pub const S_IWOTH: ::mode_t = 0o000002; +pub const S_IROTH: ::mode_t = 0o000004; +pub const S_IRWXO: ::mode_t = 0o000007; +pub const S_IXGRP: ::mode_t = 0o000010; +pub const S_IWGRP: ::mode_t = 0o000020; +pub const S_IRGRP: ::mode_t = 0o000040; +pub const S_IRWXG: ::mode_t = 0o000070; +pub const S_IXUSR: ::mode_t = 0o000100; +pub const S_IWUSR: ::mode_t = 0o000200; +pub const S_IRUSR: ::mode_t = 0o000400; +pub const S_IRWXU: ::mode_t = 0o000700; + +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; + +pub const ST_RDONLY: ::c_ulong = 0x01; +pub const ST_NOSUID: ::c_ulong = 0x04; +pub const ST_NOEXEC: ::c_ulong = 0x02; +pub const ST_NOATIME: ::c_ulong = 0x20; + +pub const RTLD_NEXT: *mut ::c_void = -3i64 as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = -2i64 as *mut ::c_void; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_NOW: ::c_int = 0x0002; + +pub const EMPTY: ::c_short = 0; +pub const RUN_LVL: ::c_short = 1; +pub const BOOT_TIME: ::c_short = 2; +pub const NEW_TIME: ::c_short = 4; +pub const OLD_TIME: ::c_short = 3; +pub const INIT_PROCESS: ::c_short = 5; +pub const LOGIN_PROCESS: ::c_short = 6; +pub const USER_PROCESS: ::c_short = 7; +pub const DEAD_PROCESS: ::c_short = 8; +pub const ACCOUNTING: ::c_short = 9; + +pub const ENOTSUP: ::c_int = 48; + +pub const BUFSIZ: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 26 * 26 * 26; +pub const FOPEN_MAX: ::c_uint = 16; +pub const FILENAME_MAX: ::c_uint = 255; + +pub const NI_MAXHOST: ::socklen_t = 1025; +pub const M_KEEP: ::c_int = 4; +pub const REG_STARTEND: ::c_int = 0o00004; +pub const VEOF: usize = 4; + +pub const RTLD_GLOBAL: ::c_int = 0x0100; +pub const RTLD_NOLOAD: ::c_int = 0x0004; + +pub const O_RDONLY: ::c_int = 0o000000; +pub const O_WRONLY: ::c_int = 0o000001; +pub const O_RDWR: ::c_int = 0o000002; + +pub const O_EXEC: ::c_int = 0o00003; +pub const O_ASYNC: ::c_int = 0o0200000; +pub const O_NDELAY: ::c_int = O_NONBLOCK; +pub const O_TRUNC: ::c_int = 0o001000; +pub const O_CLOEXEC: ::c_int = 0o020000; +pub const O_DIRECTORY: ::c_int = 0o4000000; +pub const O_ACCMODE: ::c_int = 0o000007; +pub const O_APPEND: ::c_int = 0o000010; +pub const O_CREAT: ::c_int = 0o000400; +pub const O_EXCL: ::c_int = 0o002000; +pub const O_NOCTTY: ::c_int = 0o004000; +pub const O_NONBLOCK: ::c_int = 0o000200; +pub const O_SYNC: ::c_int = 0o000040; +pub const O_RSYNC: ::c_int = 0o000100; +pub const O_DSYNC: ::c_int = 0o000020; +pub const O_NOFOLLOW: ::c_int = 0o010000; + +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; + +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_CLOEXEC: ::c_int = 0x10000000; + +pub const SA_SIGINFO: ::c_int = 0x0002; +pub const SA_NOCLDWAIT: ::c_int = 0x0020; +pub const SA_NODEFER: ::c_int = 0x0010; +pub const SA_RESETHAND: ::c_int = 0x0004; +pub const SA_NOCLDSTOP: ::c_int = 0x0001; + +pub const SIGTTIN: ::c_int = 26; +pub const SIGTTOU: ::c_int = 27; +pub const SIGXCPU: ::c_int = 30; +pub const SIGXFSZ: ::c_int = 31; +pub const SIGVTALRM: ::c_int = 28; +pub const SIGPROF: ::c_int = 29; +pub const SIGWINCH: ::c_int = 20; +pub const SIGCHLD: ::c_int = 18; +pub const SIGBUS: ::c_int = 10; +pub const SIGUSR1: ::c_int = 16; +pub const SIGUSR2: ::c_int = 17; +pub const SIGCONT: ::c_int = 25; +pub const SIGSTOP: ::c_int = 23; +pub const SIGTSTP: ::c_int = 24; +pub const SIGURG: ::c_int = 21; +pub const SIGIO: ::c_int = SIGPOLL; +pub const SIGSYS: ::c_int = 12; +pub const SIGPOLL: ::c_int = 22; +pub const SIGPWR: ::c_int = 19; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0; +pub const SIG_UNBLOCK: ::c_int = 1; + +pub const POLLWRNORM: ::c_short = ::POLLOUT; +pub const POLLWRBAND: ::c_short = 0x0010; + +pub const F_SETLK: ::c_int = 106; +pub const F_SETLKW: ::c_int = 107; +pub const F_ALLOCSP: ::c_int = 110; +pub const F_FREESP: ::c_int = 111; +pub const F_GETLK: ::c_int = 114; + +pub const F_RDLCK: ::c_int = 1; +pub const F_WRLCK: ::c_int = 2; +pub const F_UNLCK: ::c_int = 3; + +pub const NCCS: usize = 40; + +pub const MAP_ANON: ::c_int = MAP_ANONYMOUS; +pub const MAP_ANONYMOUS: ::c_int = 0x00080000; + +pub const MCL_CURRENT: ::c_int = 0x000000001; +pub const MCL_FUTURE: ::c_int = 0x000000002; + +pub const _TIO_CBAUD: ::tcflag_t = 15; +pub const CBAUD: ::tcflag_t = _TIO_CBAUD; +pub const TAB1: ::tcflag_t = 0x0800; +pub const TAB2: ::tcflag_t = 0x1000; +pub const TAB3: ::tcflag_t = 0x1800; +pub const CR1: ::tcflag_t = 0x200; +pub const CR2: ::tcflag_t = 0x400; +pub const CR3: ::tcflag_t = 0x600; +pub const FF1: ::tcflag_t = 0x8000; +pub const BS1: ::tcflag_t = 0x2000; +pub const VT1: ::tcflag_t = 0x4000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 17; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x00000004; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x10; +pub const CS7: ::tcflag_t = 0x20; +pub const CS8: ::tcflag_t = 0x30; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const OLCUC: ::tcflag_t = 0x00000002; +pub const NLDLY: ::tcflag_t = 0x00000100; +pub const CRDLY: ::tcflag_t = 0x00000600; +pub const TABDLY: ::tcflag_t = 0x00001800; +pub const BSDLY: ::tcflag_t = 0x00002000; +pub const FFDLY: ::tcflag_t = 0x00008000; +pub const VTDLY: ::tcflag_t = 0x00004000; +pub const XTABS: ::tcflag_t = 0x1800; + +pub const B0: ::speed_t = 0; +pub const B50: ::speed_t = 1; +pub const B75: ::speed_t = 2; +pub const B110: ::speed_t = 3; +pub const B134: ::speed_t = 4; +pub const B150: ::speed_t = 5; +pub const B200: ::speed_t = 6; +pub const B300: ::speed_t = 7; +pub const B600: ::speed_t = 8; +pub const B1200: ::speed_t = 9; +pub const B1800: ::speed_t = 10; +pub const B2400: ::speed_t = 11; +pub const B4800: ::speed_t = 12; +pub const B9600: ::speed_t = 13; +pub const B19200: ::speed_t = 14; +pub const B38400: ::speed_t = 15; +pub const EXTA: ::speed_t = 14; +pub const EXTB: ::speed_t = 15; +pub const B57600: ::speed_t = 57600; +pub const B115200: ::speed_t = 115200; + +pub const VEOL: usize = 5; +pub const VEOL2: usize = 6; +pub const VMIN: usize = 16; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; + +pub const TCSANOW: ::c_int = 0x0001; +pub const TCSADRAIN: ::c_int = 0x0002; +pub const TCSAFLUSH: ::c_int = 0x0004; + +pub const HW_MACHINE: ::c_int = 1; +pub const HW_MODEL: ::c_int = 2; +pub const HW_NCPU: ::c_int = 3; +pub const HW_BYTEORDER: ::c_int = 4; +pub const HW_PHYSMEM: ::c_int = 5; +pub const HW_USERMEM: ::c_int = 6; +pub const HW_PAGESIZE: ::c_int = 7; +pub const HW_DISKNAMES: ::c_int = 8; +pub const HW_IOSTATS: ::c_int = 9; +pub const HW_MACHINE_ARCH: ::c_int = 10; +pub const HW_ALIGNBYTES: ::c_int = 11; +pub const HW_CNMAGIC: ::c_int = 12; +pub const HW_PHYSMEM64: ::c_int = 13; +pub const HW_USERMEM64: ::c_int = 14; +pub const HW_IOSTATNAMES: ::c_int = 15; +pub const HW_MAXID: ::c_int = 15; + +pub const CTL_UNSPEC: ::c_int = 0; +pub const CTL_KERN: ::c_int = 1; +pub const CTL_VM: ::c_int = 2; +pub const CTL_VFS: ::c_int = 3; +pub const CTL_NET: ::c_int = 4; +pub const CTL_DEBUG: ::c_int = 5; +pub const CTL_HW: ::c_int = 6; +pub const CTL_MACHDEP: ::c_int = 7; +pub const CTL_USER: ::c_int = 8; +pub const CTL_QNX: ::c_int = 9; +pub const CTL_PROC: ::c_int = 10; +pub const CTL_VENDOR: ::c_int = 11; +pub const CTL_EMUL: ::c_int = 12; +pub const CTL_SECURITY: ::c_int = 13; +pub const CTL_MAXID: ::c_int = 14; + +pub const DAY_1: ::nl_item = 8; +pub const DAY_2: ::nl_item = 9; +pub const DAY_3: ::nl_item = 10; +pub const DAY_4: ::nl_item = 11; +pub const DAY_5: ::nl_item = 12; +pub const DAY_6: ::nl_item = 13; +pub const DAY_7: ::nl_item = 14; + +pub const MON_1: ::nl_item = 22; +pub const MON_2: ::nl_item = 23; +pub const MON_3: ::nl_item = 24; +pub const MON_4: ::nl_item = 25; +pub const MON_5: ::nl_item = 26; +pub const MON_6: ::nl_item = 27; +pub const MON_7: ::nl_item = 28; +pub const MON_8: ::nl_item = 29; +pub const MON_9: ::nl_item = 30; +pub const MON_10: ::nl_item = 31; +pub const MON_11: ::nl_item = 32; +pub const MON_12: ::nl_item = 33; + +pub const ABDAY_1: ::nl_item = 15; +pub const ABDAY_2: ::nl_item = 16; +pub const ABDAY_3: ::nl_item = 17; +pub const ABDAY_4: ::nl_item = 18; +pub const ABDAY_5: ::nl_item = 19; +pub const ABDAY_6: ::nl_item = 20; +pub const ABDAY_7: ::nl_item = 21; + +pub const ABMON_1: ::nl_item = 34; +pub const ABMON_2: ::nl_item = 35; +pub const ABMON_3: ::nl_item = 36; +pub const ABMON_4: ::nl_item = 37; +pub const ABMON_5: ::nl_item = 38; +pub const ABMON_6: ::nl_item = 39; +pub const ABMON_7: ::nl_item = 40; +pub const ABMON_8: ::nl_item = 41; +pub const ABMON_9: ::nl_item = 42; +pub const ABMON_10: ::nl_item = 43; +pub const ABMON_11: ::nl_item = 44; +pub const ABMON_12: ::nl_item = 45; + +pub const AF_ARP: ::c_int = 28; +pub const AF_CCITT: ::c_int = 10; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_CNT: ::c_int = 21; +pub const AF_COIP: ::c_int = 20; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_E164: ::c_int = 26; +pub const AF_ECMA: ::c_int = 8; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_IEEE80211: ::c_int = 32; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_ISO: ::c_int = 7; +pub const AF_LAT: ::c_int = 14; +pub const AF_LINK: ::c_int = 18; +pub const AF_NATM: ::c_int = 27; +pub const AF_NS: ::c_int = 6; +pub const AF_OSI: ::c_int = 7; +pub const AF_PUP: ::c_int = 4; +pub const ALT_DIGITS: ::nl_item = 50; +pub const AM_STR: ::nl_item = 6; +pub const B76800: ::speed_t = 76800; + +pub const BIOCFLUSH: ::c_int = 17000; +pub const BIOCGBLEN: ::c_int = 1074020966; +pub const BIOCGDLT: ::c_int = 1074020970; +pub const BIOCGDLTLIST: ::c_int = -1072676233; +pub const BIOCGETIF: ::c_int = 1083196011; +pub const BIOCGHDRCMPLT: ::c_int = 1074020980; +pub const BIOCGRTIMEOUT: ::c_int = 1074807406; +pub const BIOCGSEESENT: ::c_int = 1074020984; +pub const BIOCGSTATS: ::c_int = 1082147439; +pub const BIOCIMMEDIATE: ::c_int = -2147204496; +pub const BIOCPROMISC: ::c_int = 17001; +pub const BIOCSBLEN: ::c_int = -1073462682; +pub const BIOCSDLT: ::c_int = -2147204490; +pub const BIOCSETF: ::c_int = -2146418073; +pub const BIOCSETIF: ::c_int = -2138029460; +pub const BIOCSHDRCMPLT: ::c_int = -2147204491; +pub const BIOCSRTIMEOUT: ::c_int = -2146418067; +pub const BIOCSSEESENT: ::c_int = -2147204487; +pub const BIOCVERSION: ::c_int = 1074020977; + +pub const BPF_ALIGNMENT: usize = ::mem::size_of::<::c_long>(); +pub const CHAR_BIT: usize = 8; +pub const CODESET: ::nl_item = 1; +pub const CRNCYSTR: ::nl_item = 55; + +pub const D_FLAG_FILTER: ::c_int = 0x00000001; +pub const D_FLAG_STAT: ::c_int = 0x00000002; +pub const D_FLAG_STAT_FORM_MASK: ::c_int = 0x000000f0; +pub const D_FLAG_STAT_FORM_T32_2001: ::c_int = 0x00000010; +pub const D_FLAG_STAT_FORM_T32_2008: ::c_int = 0x00000020; +pub const D_FLAG_STAT_FORM_T64_2008: ::c_int = 0x00000030; +pub const D_FLAG_STAT_FORM_UNSET: ::c_int = 0x00000000; + +pub const D_FMT: ::nl_item = 3; +pub const D_GETFLAG: ::c_int = 1; +pub const D_SETFLAG: ::c_int = 2; +pub const D_T_FMT: ::nl_item = 2; +pub const ERA: ::nl_item = 46; +pub const ERA_D_FMT: ::nl_item = 47; +pub const ERA_D_T_FMT: ::nl_item = 48; +pub const ERA_T_FMT: ::nl_item = 49; +pub const RADIXCHAR: ::nl_item = 51; +pub const THOUSEP: ::nl_item = 52; +pub const YESEXPR: ::nl_item = 53; +pub const NOEXPR: ::nl_item = 54; +pub const F_GETOWN: ::c_int = 35; + +pub const FIONBIO: ::c_int = -2147195266; +pub const FIOASYNC: ::c_int = -2147195267; +pub const FIOCLEX: ::c_int = 26113; +pub const FIOGETOWN: ::c_int = 1074030203; +pub const FIONCLEX: ::c_int = 26114; +pub const FIONREAD: ::c_int = 1074030207; +pub const FIONSPACE: ::c_int = 1074030200; +pub const FIONWRITE: ::c_int = 1074030201; +pub const FIOSETOWN: ::c_int = -2147195268; + +pub const F_SETOWN: ::c_int = 36; +pub const IFF_ACCEPTRTADV: ::c_int = 0x40000000; +pub const IFF_IP6FORWARDING: ::c_int = 0x20000000; +pub const IFF_LINK0: ::c_int = 0x00001000; +pub const IFF_LINK1: ::c_int = 0x00002000; +pub const IFF_LINK2: ::c_int = 0x00004000; +pub const IFF_OACTIVE: ::c_int = 0x00000400; +pub const IFF_SHIM: ::c_int = 0x80000000; +pub const IFF_SIMPLEX: ::c_int = 0x00000800; +pub const IHFLOW: tcflag_t = 0x00000001; +pub const IIDLE: tcflag_t = 0x00000008; +pub const IP_RECVDSTADDR: ::c_int = 7; +pub const IP_RECVIF: ::c_int = 20; +pub const IPTOS_ECN_NOTECT: u8 = 0x00; +pub const IUCLC: tcflag_t = 0x00000200; +pub const IUTF8: tcflag_t = 0x0004000; + +pub const KERN_ARGMAX: ::c_int = 8; +pub const KERN_ARND: ::c_int = 81; +pub const KERN_BOOTTIME: ::c_int = 21; +pub const KERN_CLOCKRATE: ::c_int = 12; +pub const KERN_FILE: ::c_int = 15; +pub const KERN_HOSTID: ::c_int = 11; +pub const KERN_HOSTNAME: ::c_int = 10; +pub const KERN_IOV_MAX: ::c_int = 38; +pub const KERN_JOB_CONTROL: ::c_int = 19; +pub const KERN_LOGSIGEXIT: ::c_int = 46; +pub const KERN_MAXFILES: ::c_int = 7; +pub const KERN_MAXID: ::c_int = 83; +pub const KERN_MAXPROC: ::c_int = 6; +pub const KERN_MAXVNODES: ::c_int = 5; +pub const KERN_NGROUPS: ::c_int = 18; +pub const KERN_OSRELEASE: ::c_int = 2; +pub const KERN_OSREV: ::c_int = 3; +pub const KERN_OSTYPE: ::c_int = 1; +pub const KERN_POSIX1: ::c_int = 17; +pub const KERN_PROC: ::c_int = 14; +pub const KERN_PROC_ALL: ::c_int = 0; +pub const KERN_PROC_ARGS: ::c_int = 48; +pub const KERN_PROC_ENV: ::c_int = 3; +pub const KERN_PROC_GID: ::c_int = 7; +pub const KERN_PROC_PGRP: ::c_int = 2; +pub const KERN_PROC_PID: ::c_int = 1; +pub const KERN_PROC_RGID: ::c_int = 8; +pub const KERN_PROC_RUID: ::c_int = 6; +pub const KERN_PROC_SESSION: ::c_int = 3; +pub const KERN_PROC_TTY: ::c_int = 4; +pub const KERN_PROC_UID: ::c_int = 5; +pub const KERN_PROF: ::c_int = 16; +pub const KERN_SAVED_IDS: ::c_int = 20; +pub const KERN_SECURELVL: ::c_int = 9; +pub const KERN_VERSION: ::c_int = 4; +pub const KERN_VNODE: ::c_int = 13; + +pub const LC_ALL: ::c_int = 63; +pub const LC_COLLATE: ::c_int = 1; +pub const LC_CTYPE: ::c_int = 2; +pub const LC_MESSAGES: ::c_int = 32; +pub const LC_MONETARY: ::c_int = 4; +pub const LC_NUMERIC: ::c_int = 8; +pub const LC_TIME: ::c_int = 16; + +pub const LOCAL_CONNWAIT: ::c_int = 0x0002; +pub const LOCAL_CREDS: ::c_int = 0x0001; +pub const LOCAL_PEEREID: ::c_int = 0x0003; + +pub const MAP_STACK: ::c_int = 0x00001000; +pub const MNT_NOEXEC: ::c_int = 0x02; +pub const MNT_NOSUID: ::c_int = 0x04; +pub const MNT_RDONLY: ::c_int = 0x01; + +pub const MSG_NOTIFICATION: ::c_int = 0x0400; + +pub const NET_RT_DUMP: ::c_int = 1; +pub const NET_RT_FLAGS: ::c_int = 2; +pub const NET_RT_IFLIST: ::c_int = 4; +pub const NI_NUMERICSCOPE: ::c_int = 0x00000040; +pub const OHFLOW: tcflag_t = 0x00000002; +pub const P_ALL: idtype_t = 0; +pub const PARSTK: tcflag_t = 0x00000004; +pub const PF_ARP: ::c_int = 28; +pub const PF_CCITT: ::c_int = 10; +pub const PF_CHAOS: ::c_int = 5; +pub const PF_CNT: ::c_int = 21; +pub const PF_COIP: ::c_int = 20; +pub const PF_DATAKIT: ::c_int = 9; +pub const PF_DECnet: ::c_int = 12; +pub const PF_DLI: ::c_int = 13; +pub const PF_ECMA: ::c_int = 8; +pub const PF_HYLINK: ::c_int = 15; +pub const PF_IMPLINK: ::c_int = 3; +pub const PF_ISO: ::c_int = 7; +pub const PF_LAT: ::c_int = 14; +pub const PF_LINK: ::c_int = 18; +pub const PF_NATM: ::c_int = 27; +pub const PF_OSI: ::c_int = 7; +pub const PF_PIP: ::c_int = 25; +pub const PF_PUP: ::c_int = 4; +pub const PF_RTIP: ::c_int = 22; +pub const PF_XTP: ::c_int = 19; +pub const PM_STR: ::nl_item = 7; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 2; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 1; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; +pub const _POSIX_VDISABLE: ::c_int = 0; +pub const P_PGID: idtype_t = 2; +pub const P_PID: idtype_t = 1; +pub const PRIO_PGRP: ::c_int = 1; +pub const PRIO_PROCESS: ::c_int = 0; +pub const PRIO_USER: ::c_int = 2; +pub const pseudo_AF_HDRCMPLT: ::c_int = 30; +pub const pseudo_AF_PIP: ::c_int = 25; +pub const pseudo_AF_RTIP: ::c_int = 22; +pub const pseudo_AF_XTP: ::c_int = 19; +pub const REG_ASSERT: ::c_int = 15; +pub const REG_ATOI: ::c_int = 255; +pub const REG_BACKR: ::c_int = 0x400; +pub const REG_BASIC: ::c_int = 0x00; +pub const REG_DUMP: ::c_int = 0x80; +pub const REG_EMPTY: ::c_int = 14; +pub const REG_INVARG: ::c_int = 16; +pub const REG_ITOA: ::c_int = 0o400; +pub const REG_LARGE: ::c_int = 0x200; +pub const REG_NOSPEC: ::c_int = 0x10; +pub const REG_OK: ::c_int = 0; +pub const REG_PEND: ::c_int = 0x20; +pub const REG_TRACE: ::c_int = 0x100; + +pub const RLIMIT_AS: ::c_int = 6; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_MEMLOCK: ::c_int = 7; +pub const RLIMIT_NOFILE: ::c_int = 5; +pub const RLIMIT_NPROC: ::c_int = 8; +pub const RLIMIT_RSS: ::c_int = 6; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_VMEM: ::c_int = 6; +pub const RLIM_NLIMITS: ::c_int = 14; + +pub const SCHED_ADJTOHEAD: ::c_int = 5; +pub const SCHED_ADJTOTAIL: ::c_int = 6; +pub const SCHED_MAXPOLICY: ::c_int = 7; +pub const SCHED_SETPRIO: ::c_int = 7; +pub const SCHED_SPORADIC: ::c_int = 4; + +pub const SHM_ANON: *mut ::c_char = -1isize as *mut ::c_char; +pub const SIGCLD: ::c_int = SIGCHLD; +pub const SIGDEADLK: ::c_int = 7; +pub const SIGEMT: ::c_int = 7; +pub const SIGEV_NONE: ::c_int = 0; +pub const SIGEV_SIGNAL: ::c_int = 129; +pub const SIGEV_THREAD: ::c_int = 135; +pub const SIOCGIFADDR: ::c_int = -1064277727; +pub const SO_FIB: ::c_int = 0x100a; +pub const SO_OVERFLOWED: ::c_int = 0x1009; +pub const SO_SETFIB: ::c_int = 0x100a; +pub const SO_TXPRIO: ::c_int = 0x100b; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_VLANPRIO: ::c_int = 0x100c; +pub const _SS_ALIGNSIZE: usize = ::mem::size_of::(); +pub const _SS_MAXSIZE: usize = 128; +pub const _SS_PAD1SIZE: usize = _SS_ALIGNSIZE - 2; +pub const _SS_PAD2SIZE: usize = _SS_MAXSIZE - 2 - _SS_PAD1SIZE - _SS_ALIGNSIZE; +pub const TC_CPOSIX: tcflag_t = CLOCAL | CREAD | CSIZE | CSTOPB | HUPCL | PARENB | PARODD; +pub const TCGETS: ::c_int = 0x404c540d; +pub const TC_IPOSIX: tcflag_t = + BRKINT | ICRNL | IGNBRK | IGNPAR | INLCR | INPCK | ISTRIP | IXOFF | IXON | PARMRK; +pub const TC_LPOSIX: tcflag_t = + ECHO | ECHOE | ECHOK | ECHONL | ICANON | IEXTEN | ISIG | NOFLSH | TOSTOP; +pub const TC_OPOSIX: tcflag_t = OPOST; +pub const T_FMT_AMPM: ::nl_item = 5; + +pub const TIOCCBRK: ::c_int = 29818; +pub const TIOCCDTR: ::c_int = 29816; +pub const TIOCDRAIN: ::c_int = 29790; +pub const TIOCEXCL: ::c_int = 29709; +pub const TIOCFLUSH: ::c_int = -2147191792; +pub const TIOCGETA: ::c_int = 1078752275; +pub const TIOCGPGRP: ::c_int = 1074033783; +pub const TIOCGWINSZ: ::c_int = 1074295912; +pub const TIOCMBIC: ::c_int = -2147191701; +pub const TIOCMBIS: ::c_int = -2147191700; +pub const TIOCMGET: ::c_int = 1074033770; +pub const TIOCMSET: ::c_int = -2147191699; +pub const TIOCNOTTY: ::c_int = 29809; +pub const TIOCNXCL: ::c_int = 29710; +pub const TIOCOUTQ: ::c_int = 1074033779; +pub const TIOCPKT: ::c_int = -2147191696; +pub const TIOCPKT_DATA: ::c_int = 0x00; +pub const TIOCPKT_DOSTOP: ::c_int = 0x20; +pub const TIOCPKT_FLUSHREAD: ::c_int = 0x01; +pub const TIOCPKT_FLUSHWRITE: ::c_int = 0x02; +pub const TIOCPKT_IOCTL: ::c_int = 0x40; +pub const TIOCPKT_NOSTOP: ::c_int = 0x10; +pub const TIOCPKT_START: ::c_int = 0x08; +pub const TIOCPKT_STOP: ::c_int = 0x04; +pub const TIOCSBRK: ::c_int = 29819; +pub const TIOCSCTTY: ::c_int = 29793; +pub const TIOCSDTR: ::c_int = 29817; +pub const TIOCSETA: ::c_int = -2142473196; +pub const TIOCSETAF: ::c_int = -2142473194; +pub const TIOCSETAW: ::c_int = -2142473195; +pub const TIOCSPGRP: ::c_int = -2147191690; +pub const TIOCSTART: ::c_int = 29806; +pub const TIOCSTI: ::c_int = -2147388302; +pub const TIOCSTOP: ::c_int = 29807; +pub const TIOCSWINSZ: ::c_int = -2146929561; + +pub const USER_CS_PATH: ::c_int = 1; +pub const USER_BC_BASE_MAX: ::c_int = 2; +pub const USER_BC_DIM_MAX: ::c_int = 3; +pub const USER_BC_SCALE_MAX: ::c_int = 4; +pub const USER_BC_STRING_MAX: ::c_int = 5; +pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; +pub const USER_EXPR_NEST_MAX: ::c_int = 7; +pub const USER_LINE_MAX: ::c_int = 8; +pub const USER_RE_DUP_MAX: ::c_int = 9; +pub const USER_POSIX2_VERSION: ::c_int = 10; +pub const USER_POSIX2_C_BIND: ::c_int = 11; +pub const USER_POSIX2_C_DEV: ::c_int = 12; +pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; +pub const USER_POSIX2_FORT_DEV: ::c_int = 14; +pub const USER_POSIX2_FORT_RUN: ::c_int = 15; +pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; +pub const USER_POSIX2_SW_DEV: ::c_int = 17; +pub const USER_POSIX2_UPE: ::c_int = 18; +pub const USER_STREAM_MAX: ::c_int = 19; +pub const USER_TZNAME_MAX: ::c_int = 20; +pub const USER_ATEXIT_MAX: ::c_int = 21; +pub const USER_MAXID: ::c_int = 22; + +pub const VDOWN: usize = 31; +pub const VINS: usize = 32; +pub const VDEL: usize = 33; +pub const VRUB: usize = 34; +pub const VCAN: usize = 35; +pub const VHOME: usize = 36; +pub const VEND: usize = 37; +pub const VSPARE3: usize = 38; +pub const VSPARE4: usize = 39; +pub const VSWTCH: usize = 7; +pub const VDSUSP: usize = 11; +pub const VFWD: usize = 18; +pub const VLOGIN: usize = 19; +pub const VPREFIX: usize = 20; +pub const VSUFFIX: usize = 24; +pub const VLEFT: usize = 28; +pub const VRIGHT: usize = 29; +pub const VUP: usize = 30; +pub const XCASE: tcflag_t = 0x00000004; + +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0x00; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 0x01; + +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 3; +pub const PTHREAD_STACK_MIN: ::size_t = 256; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = 0; +pub const PTHREAD_MUTEX_STALLED: ::c_int = 0x00; +pub const PTHREAD_MUTEX_ROBUST: ::c_int = 0x10; +pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0x00; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 0x01; + +pub const PTHREAD_KEYS_MAX: usize = 128; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __u: 0x80000000, + __owner: 0xffffffff, +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __u: CLOCK_REALTIME as u32, + __owner: 0xfffffffb, +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __active: 0, + __blockedwriters: 0, + __blockedreaders: 0, + __heavy: 0, + __lock: PTHREAD_MUTEX_INITIALIZER, + __rcond: PTHREAD_COND_INITIALIZER, + __wcond: PTHREAD_COND_INITIALIZER, + __owner: -2i32 as ::c_uint, + __spare: 0, +}; + +const_fn! { + {const} fn _CMSG_ALIGN(len: usize) -> usize { + len + ::mem::size_of::() - 1 & !(::mem::size_of::() - 1) + } + + {const} fn _ALIGN(p: usize, b: usize) -> usize { + (p + b - 1) & !(b-1) + } +} + +f! { + pub fn CMSG_FIRSTHDR(mhdr: *const msghdr) -> *mut cmsghdr { + if (*mhdr).msg_controllen as usize >= ::mem::size_of::() { + (*mhdr).msg_control as *mut cmsghdr + } else { + 0 as *mut cmsghdr + } + } + + pub fn CMSG_NXTHDR(mhdr: *const ::msghdr, cmsg: *const ::cmsghdr) + -> *mut ::cmsghdr + { + let msg = _CMSG_ALIGN((*cmsg).cmsg_len as usize); + let next = cmsg as usize + msg + _CMSG_ALIGN(::mem::size_of::<::cmsghdr>()); + if next > (*mhdr).msg_control as usize + (*mhdr).msg_controllen as usize { + 0 as *mut ::cmsghdr + } else { + (cmsg as usize + msg) as *mut ::cmsghdr + } + } + + pub fn CMSG_DATA(cmsg: *const ::cmsghdr) -> *mut ::c_uchar { + (cmsg as *mut ::c_uchar) + .offset(_CMSG_ALIGN(::mem::size_of::<::cmsghdr>()) as isize) + } + + pub fn CMSG_LEN(length: ::c_uint) -> ::c_uint { + _CMSG_ALIGN(::mem::size_of::<::cmsghdr>()) as ::c_uint + length + } + + pub {const} fn CMSG_SPACE(length: ::c_uint) -> ::c_uint { + (_CMSG_ALIGN(::mem::size_of::()) + _CMSG_ALIGN(length as usize) ) + as ::c_uint + } + + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = ::mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] &= !(1 << (fd % size)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *const fd_set) -> bool { + let fd = fd as usize; + let size = ::mem::size_of_val(&(*set).fds_bits[0]) * 8; + return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = ::mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] |= 1 << (fd % size); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn _DEXTRA_FIRST(_d: *const dirent) -> *mut ::dirent_extra { + let _f = &((*(_d)).d_name) as *const _; + let _s = _d as usize; + + _ALIGN(_s + _f as usize - _s + (*_d).d_namelen as usize + 1, 8) as *mut ::dirent_extra + } + + pub fn _DEXTRA_VALID(_x: *const ::dirent_extra, _d: *const dirent) -> bool { + let sz = _x as usize - _d as usize + ::mem::size_of::<::dirent_extra>(); + let rsz = (*_d).d_reclen as usize; + + if sz > rsz || sz + (*_x).d_datalen as usize > rsz { + false + } else { + true + } + } + + pub fn _DEXTRA_NEXT(_x: *const ::dirent_extra) -> *mut ::dirent_extra { + _ALIGN( + _x as usize + ::mem::size_of::<::dirent_extra>() + (*_x).d_datalen as usize, 8 + ) as *mut ::dirent_extra + } + + pub fn SOCKCREDSIZE(ngrps: usize) -> usize { + let ngrps = if ngrps > 0 { + ngrps - 1 + } else { + 0 + }; + ::mem::size_of::() + ::mem::size_of::<::gid_t>() * ngrps + } +} + +safe_f! { + pub {const} fn WIFSTOPPED(status: ::c_int) -> bool { + (status & 0xff) == 0x7f + } + + pub {const} fn WSTOPSIG(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub {const} fn WIFCONTINUED(status: ::c_int) -> bool { + status == 0xffff + } + + pub {const} fn WIFSIGNALED(status: ::c_int) -> bool { + ((status & 0x7f) + 1) as i8 >= 2 + } + + pub {const} fn WTERMSIG(status: ::c_int) -> ::c_int { + status & 0x7f + } + + pub {const} fn WIFEXITED(status: ::c_int) -> bool { + (status & 0x7f) == 0 + } + + pub {const} fn WEXITSTATUS(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub {const} fn WCOREDUMP(status: ::c_int) -> bool { + (status & 0x80) != 0 + } + + pub {const} fn IPTOS_ECN(x: u8) -> u8 { + x & ::IPTOS_ECN_MASK + } +} + +// Network related functions are provided by libsocket and regex +// functions are provided by libregex. +#[link(name = "socket")] +#[link(name = "regex")] + +extern "C" { + pub fn sem_destroy(sem: *mut sem_t) -> ::c_int; + pub fn sem_init(sem: *mut sem_t, pshared: ::c_int, value: ::c_uint) -> ::c_int; + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, mode: ::mode_t) -> ::c_int; + + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn clock_getcpuclockid(pid: ::pid_t, clk_id: *mut ::clockid_t) -> ::c_int; + + pub fn pthread_attr_getstack( + attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t, + ) -> ::c_int; + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn setgroups(ngroups: ::c_int, ptr: *const ::gid_t) -> ::c_int; + + pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, advise: ::c_int) -> ::c_int; + pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn utimensat( + dirfd: ::c_int, + path: *const ::c_char, + times: *const ::timespec, + flag: ::c_int, + ) -> ::c_int; + + pub fn pthread_condattr_getclock( + attr: *const pthread_condattr_t, + clock_id: *mut clockid_t, + ) -> ::c_int; + pub fn pthread_condattr_setclock( + attr: *mut pthread_condattr_t, + clock_id: ::clockid_t, + ) -> ::c_int; + pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, pshared: ::c_int) -> ::c_int; + pub fn pthread_mutexattr_setpshared( + attr: *mut pthread_mutexattr_t, + pshared: ::c_int, + ) -> ::c_int; + pub fn pthread_rwlockattr_getpshared( + attr: *const pthread_rwlockattr_t, + val: *mut ::c_int, + ) -> ::c_int; + pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, val: ::c_int) -> ::c_int; + pub fn ptsname_r(fd: ::c_int, buf: *mut ::c_char, buflen: ::size_t) -> *mut ::c_char; + pub fn clearenv() -> ::c_int; + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, options: ::c_int) + -> ::c_int; + pub fn wait4( + pid: ::pid_t, + status: *mut ::c_int, + options: ::c_int, + rusage: *mut ::rusage, + ) -> ::pid_t; + pub fn execvpe( + file: *const ::c_char, + argv: *const *const ::c_char, + envp: *const *const ::c_char, + ) -> ::c_int; + + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + pub fn bind(socket: ::c_int, address: *const ::sockaddr, address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, msg: *const ::msghdr, flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) -> ::ssize_t; + pub fn openpty( + amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize, + ) -> ::c_int; + pub fn forkpty( + amaster: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize, + ) -> ::pid_t; + pub fn login_tty(fd: ::c_int) -> ::c_int; + + pub fn uname(buf: *mut ::utsname) -> ::c_int; + + pub fn getpeereid(socket: ::c_int, euid: *mut ::uid_t, egid: *mut ::gid_t) -> ::c_int; + + pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, buflen: ::size_t) -> ::c_int; + + pub fn abs(i: ::c_int) -> ::c_int; + pub fn labs(i: ::c_long) -> ::c_long; + pub fn rand() -> ::c_int; + pub fn srand(seed: ::c_uint); + + pub fn setpwent(); + pub fn endpwent(); + pub fn getpwent() -> *mut passwd; + pub fn setgrent(); + pub fn endgrent(); + pub fn getgrent() -> *mut ::group; + pub fn setspent(); + pub fn endspent(); + + pub fn shm_open(name: *const c_char, oflag: ::c_int, mode: mode_t) -> ::c_int; + + pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) -> ::c_int; + + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, len: ::off_t) -> ::c_int; + pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; + pub fn mkostemps(template: *mut ::c_char, suffixlen: ::c_int, flags: ::c_int) -> ::c_int; + pub fn sigtimedwait( + set: *const sigset_t, + info: *mut siginfo_t, + timeout: *const ::timespec, + ) -> ::c_int; + pub fn sigwaitinfo(set: *const sigset_t, info: *mut siginfo_t) -> ::c_int; + pub fn pthread_setschedprio(native: ::pthread_t, priority: ::c_int) -> ::c_int; + + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + + pub fn glob( + pattern: *const c_char, + flags: ::c_int, + errfunc: ::Option ::c_int>, + pglob: *mut ::glob_t, + ) -> ::c_int; + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) -> ::c_int; + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + pub fn recvfrom( + socket: ::c_int, + buf: *mut ::c_void, + len: ::size_t, + flags: ::c_int, + addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t, + ) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + + pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sync(); + pub fn pthread_getschedparam( + native: ::pthread_t, + policy: *mut ::c_int, + param: *mut ::sched_param, + ) -> ::c_int; + pub fn umount(target: *const ::c_char, flags: ::c_int) -> ::c_int; + pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::c_void) -> ::c_int; + pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, abstime: *const ::timespec) -> ::c_int; + pub fn sem_getvalue(sem: *mut sem_t, sval: *mut ::c_int) -> ::c_int; + pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; + pub fn mount( + special_device: *const ::c_char, + mount_directory: *const ::c_char, + flags: ::c_int, + mount_type: *const ::c_char, + mount_data: *const ::c_void, + mount_datalen: ::c_int, + ) -> ::c_int; + pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; + pub fn pthread_mutex_consistent(mutex: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_timedlock( + lock: *mut pthread_mutex_t, + abstime: *const ::timespec, + ) -> ::c_int; + pub fn pthread_spin_init(lock: *mut ::pthread_spinlock_t, pshared: ::c_int) -> ::c_int; + pub fn pthread_spin_destroy(lock: *mut ::pthread_spinlock_t) -> ::c_int; + pub fn pthread_spin_lock(lock: *mut ::pthread_spinlock_t) -> ::c_int; + pub fn pthread_spin_trylock(lock: *mut ::pthread_spinlock_t) -> ::c_int; + pub fn pthread_spin_unlock(lock: *mut ::pthread_spinlock_t) -> ::c_int; + pub fn pthread_barrierattr_init(__attr: *mut ::pthread_barrierattr_t) -> ::c_int; + pub fn pthread_barrierattr_destroy(__attr: *mut ::pthread_barrierattr_t) -> ::c_int; + pub fn pthread_barrierattr_getpshared( + __attr: *const ::pthread_barrierattr_t, + __pshared: *mut ::c_int, + ) -> ::c_int; + pub fn pthread_barrierattr_setpshared( + __attr: *mut ::pthread_barrierattr_t, + __pshared: ::c_int, + ) -> ::c_int; + pub fn pthread_barrier_init( + __barrier: *mut ::pthread_barrier_t, + __attr: *const ::pthread_barrierattr_t, + __count: ::c_uint, + ) -> ::c_int; + pub fn pthread_barrier_destroy(__barrier: *mut ::pthread_barrier_t) -> ::c_int; + pub fn pthread_barrier_wait(__barrier: *mut ::pthread_barrier_t) -> ::c_int; + + pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; + pub fn clock_nanosleep( + clk_id: ::clockid_t, + flags: ::c_int, + rqtp: *const ::timespec, + rmtp: *mut ::timespec, + ) -> ::c_int; + pub fn pthread_attr_getguardsize( + attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t, + ) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared( + attr: *const pthread_condattr_t, + pshared: *mut ::c_int, + ) -> ::c_int; + pub fn pthread_setschedparam( + native: ::pthread_t, + policy: ::c_int, + param: *const ::sched_param, + ) -> ::c_int; + pub fn sched_setscheduler( + pid: ::pid_t, + policy: ::c_int, + param: *const ::sched_param, + ) -> ::c_int; + pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; + pub fn getgrgid_r( + gid: ::gid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group, + ) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + pub fn getgrnam_r( + name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group, + ) -> ::c_int; + pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + pub fn getpwnam_r( + name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd, + ) -> ::c_int; + pub fn getpwuid_r( + uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd, + ) -> ::c_int; + pub fn sigwait(set: *const sigset_t, sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork( + prepare: ::Option, + parent: ::Option, + child: ::Option, + ) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + pub fn getgrouplist( + user: *const ::c_char, + group: ::gid_t, + groups: *mut ::gid_t, + ngroups: *mut ::c_int, + ) -> ::c_int; + pub fn pthread_mutexattr_getpshared( + attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int, + ) -> ::c_int; + pub fn pthread_mutexattr_getrobust( + attr: *const pthread_mutexattr_t, + robustness: *mut ::c_int, + ) -> ::c_int; + pub fn pthread_mutexattr_setrobust( + attr: *mut pthread_mutexattr_t, + robustness: ::c_int, + ) -> ::c_int; + pub fn pthread_create( + native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern "C" fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void, + ) -> ::c_int; + pub fn getitimer(which: ::c_int, curr_value: *mut ::itimerval) -> ::c_int; + pub fn setitimer( + which: ::c_int, + value: *const ::itimerval, + ovalue: *mut ::itimerval, + ) -> ::c_int; + pub fn posix_spawn( + pid: *mut ::pid_t, + path: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char, + ) -> ::c_int; + pub fn posix_spawnp( + pid: *mut ::pid_t, + file: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char, + ) -> ::c_int; + pub fn posix_spawnattr_init(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_destroy(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_getsigdefault( + attr: *const posix_spawnattr_t, + default: *mut ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_setsigdefault( + attr: *mut posix_spawnattr_t, + default: *const ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_getsigmask( + attr: *const posix_spawnattr_t, + default: *mut ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_setsigmask( + attr: *mut posix_spawnattr_t, + default: *const ::sigset_t, + ) -> ::c_int; + pub fn posix_spawnattr_getflags( + attr: *const posix_spawnattr_t, + flags: *mut ::c_short, + ) -> ::c_int; + pub fn posix_spawnattr_setflags(attr: *mut posix_spawnattr_t, flags: ::c_short) -> ::c_int; + pub fn posix_spawnattr_getpgroup( + attr: *const posix_spawnattr_t, + flags: *mut ::pid_t, + ) -> ::c_int; + pub fn posix_spawnattr_setpgroup(attr: *mut posix_spawnattr_t, flags: ::pid_t) -> ::c_int; + pub fn posix_spawnattr_getschedpolicy( + attr: *const posix_spawnattr_t, + flags: *mut ::c_int, + ) -> ::c_int; + pub fn posix_spawnattr_setschedpolicy(attr: *mut posix_spawnattr_t, flags: ::c_int) -> ::c_int; + pub fn posix_spawnattr_getschedparam( + attr: *const posix_spawnattr_t, + param: *mut ::sched_param, + ) -> ::c_int; + pub fn posix_spawnattr_setschedparam( + attr: *mut posix_spawnattr_t, + param: *const ::sched_param, + ) -> ::c_int; + + pub fn posix_spawn_file_actions_init(actions: *mut posix_spawn_file_actions_t) -> ::c_int; + pub fn posix_spawn_file_actions_destroy(actions: *mut posix_spawn_file_actions_t) -> ::c_int; + pub fn posix_spawn_file_actions_addopen( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + path: *const ::c_char, + oflag: ::c_int, + mode: ::mode_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addclose( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + ) -> ::c_int; + pub fn posix_spawn_file_actions_adddup2( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + newfd: ::c_int, + ) -> ::c_int; + pub fn popen(command: *const c_char, mode: *const c_char) -> *mut ::FILE; + pub fn faccessat( + dirfd: ::c_int, + pathname: *const ::c_char, + mode: ::c_int, + flags: ::c_int, + ) -> ::c_int; + pub fn inotify_rm_watch(fd: ::c_int, wd: ::c_int) -> ::c_int; + pub fn inotify_init() -> ::c_int; + pub fn inotify_add_watch(fd: ::c_int, path: *const ::c_char, mask: u32) -> ::c_int; + + pub fn gettid() -> ::pid_t; + + pub fn pthread_getcpuclockid(thread: ::pthread_t, clk_id: *mut ::clockid_t) -> ::c_int; + + pub fn getnameinfo( + sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int, + ) -> ::c_int; + + pub fn sendmmsg( + sockfd: ::c_int, + msgvec: *mut ::mmsghdr, + vlen: ::c_uint, + flags: ::c_uint, + ) -> ::c_int; + pub fn recvmmsg( + sockfd: ::c_int, + msgvec: *mut ::mmsghdr, + vlen: ::c_uint, + flags: ::c_uint, + timeout: *mut ::timespec, + ) -> ::c_int; + + pub fn mallopt(param: ::c_int, value: i64) -> ::c_int; + pub fn gettimeofday(tp: *mut ::timeval, tz: *mut ::c_void) -> ::c_int; + + pub fn ctermid(s: *mut ::c_char) -> *mut ::c_char; + pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; + + pub fn mallinfo() -> ::mallinfo; + pub fn getpwent_r( + pwd: *mut ::passwd, + buf: *mut ::c_char, + __bufsize: ::c_int, + __result: *mut *mut ::passwd, + ) -> ::c_int; + pub fn pthread_getname_np(thread: ::pthread_t, name: *mut ::c_char, len: ::c_int) -> ::c_int; + pub fn pthread_setname_np(thread: ::pthread_t, name: *const ::c_char) -> ::c_int; + + pub fn sysctl( + _: *const ::c_int, + _: ::c_uint, + _: *mut ::c_void, + _: *mut ::size_t, + _: *const ::c_void, + _: ::size_t, + ) -> ::c_int; + + pub fn getrlimit(resource: ::c_int, rlim: *mut ::rlimit) -> ::c_int; + pub fn setrlimit(resource: ::c_int, rlp: *const ::rlimit) -> ::c_int; + + pub fn lio_listio( + __mode: ::c_int, + __list: *const *mut aiocb, + __nent: ::c_int, + __sig: *mut sigevent, + ) -> ::c_int; + + pub fn dl_iterate_phdr( + callback: ::Option< + unsafe extern "C" fn( + info: *const dl_phdr_info, + size: ::size_t, + data: *mut ::c_void, + ) -> ::c_int, + >, + data: *mut ::c_void, + ) -> ::c_int; + + pub fn memset_s(s: *mut ::c_void, smax: ::size_t, c: ::c_int, n: ::size_t) -> ::c_int; + + pub fn regcomp( + __preg: *mut ::regex_t, + __pattern: *const ::c_char, + __cflags: ::c_int, + ) -> ::c_int; + pub fn regexec( + __preg: *const ::regex_t, + __str: *const ::c_char, + __nmatch: ::size_t, + __pmatch: *mut ::regmatch_t, + __eflags: ::c_int, + ) -> ::c_int; + pub fn regerror( + __errcode: ::c_int, + __preg: *const ::regex_t, + __errbuf: *mut ::c_char, + __errbuf_size: ::size_t, + ) -> ::size_t; + pub fn regfree(__preg: *mut ::regex_t); + pub fn dirfd(__dirp: *mut ::DIR) -> ::c_int; + pub fn dircntl(dir: *mut ::DIR, cmd: ::c_int, ...) -> ::c_int; + + pub fn aio_cancel(__fd: ::c_int, __aiocbp: *mut ::aiocb) -> ::c_int; + pub fn aio_error(__aiocbp: *const ::aiocb) -> ::c_int; + pub fn aio_fsync(__operation: ::c_int, __aiocbp: *mut ::aiocb) -> ::c_int; + pub fn aio_read(__aiocbp: *mut ::aiocb) -> ::c_int; + pub fn aio_return(__aiocpb: *mut ::aiocb) -> ::ssize_t; + pub fn aio_suspend( + __list: *const *const ::aiocb, + __nent: ::c_int, + __timeout: *const ::timespec, + ) -> ::c_int; + pub fn aio_write(__aiocpb: *mut ::aiocb) -> ::c_int; + + pub fn mq_close(__mqdes: ::mqd_t) -> ::c_int; + pub fn mq_getattr(__mqdes: ::mqd_t, __mqstat: *mut ::mq_attr) -> ::c_int; + pub fn mq_notify(__mqdes: ::mqd_t, __notification: *const ::sigevent) -> ::c_int; + pub fn mq_open(__name: *const ::c_char, __oflag: ::c_int, ...) -> ::mqd_t; + pub fn mq_receive( + __mqdes: ::mqd_t, + __msg_ptr: *mut ::c_char, + __msg_len: ::size_t, + __msg_prio: *mut ::c_uint, + ) -> ::ssize_t; + pub fn mq_send( + __mqdes: ::mqd_t, + __msg_ptr: *const ::c_char, + __msg_len: ::size_t, + __msg_prio: ::c_uint, + ) -> ::c_int; + pub fn mq_setattr( + __mqdes: ::mqd_t, + __mqstat: *const mq_attr, + __omqstat: *mut mq_attr, + ) -> ::c_int; + pub fn mq_timedreceive( + __mqdes: ::mqd_t, + __msg_ptr: *mut ::c_char, + __msg_len: ::size_t, + __msg_prio: *mut ::c_uint, + __abs_timeout: *const ::timespec, + ) -> ::ssize_t; + pub fn mq_timedsend( + __mqdes: ::mqd_t, + __msg_ptr: *const ::c_char, + __msg_len: ::size_t, + __msg_prio: ::c_uint, + __abs_timeout: *const ::timespec, + ) -> ::c_int; + pub fn mq_unlink(__name: *const ::c_char) -> ::c_int; + pub fn __get_errno_ptr() -> *mut ::c_int; + + // System page, see https://www.qnx.com/developers/docs/7.1#com.qnx.doc.neutrino.building/topic/syspage/syspage_about.html + pub static mut _syspage_ptr: *mut syspage_entry; + + // Function on the stack after a call to pthread_create(). This is used + // as a sentinel to work around an infitnite loop in the unwinding code. + pub fn __my_thread_exit(value_ptr: *mut *const ::c_void); +} + +// Models the implementation in stdlib.h. Ctest will fail if trying to use the +// default symbol from libc +pub unsafe fn atexit(cb: extern "C" fn()) -> ::c_int { + extern "C" { + static __dso_handle: *mut ::c_void; + pub fn __cxa_atexit( + cb: extern "C" fn(), + __arg: *mut ::c_void, + __dso: *mut ::c_void, + ) -> ::c_int; + } + __cxa_atexit(cb, 0 as *mut ::c_void, __dso_handle) +} + +impl siginfo_t { + pub unsafe fn si_addr(&self) -> *mut ::c_void { + #[repr(C)] + struct siginfo_si_addr { + _pad: [u8; 32], + si_addr: *mut ::c_void, + } + (*(self as *const siginfo_t as *const siginfo_si_addr)).si_addr + } + + pub unsafe fn si_value(&self) -> ::sigval { + #[repr(C)] + struct siginfo_si_value { + _pad: [u8; 32], + si_value: ::sigval, + } + (*(self as *const siginfo_t as *const siginfo_si_value)).si_value + } + + pub unsafe fn si_pid(&self) -> ::pid_t { + #[repr(C)] + struct siginfo_si_pid { + _pad: [u8; 16], + si_pid: ::pid_t, + } + (*(self as *const siginfo_t as *const siginfo_si_pid)).si_pid + } + + pub unsafe fn si_uid(&self) -> ::uid_t { + #[repr(C)] + struct siginfo_si_uid { + _pad: [u8; 24], + si_uid: ::uid_t, + } + (*(self as *const siginfo_t as *const siginfo_si_uid)).si_uid + } + + pub unsafe fn si_status(&self) -> ::c_int { + #[repr(C)] + struct siginfo_si_status { + _pad: [u8; 28], + si_status: ::c_int, + } + (*(self as *const siginfo_t as *const siginfo_si_status)).si_status + } +} + +cfg_if! { + if #[cfg(target_arch = "x86_64")] { + mod x86_64; + pub use self::x86_64::*; + } + else if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } + else { + panic!("Unsupported arch"); + } +} + +mod neutrino; +pub use self::neutrino::*; diff --git a/bash-5.1/vendor/libc/src/unix/nto/neutrino.rs b/bash-5.1/vendor/libc/src/unix/nto/neutrino.rs new file mode 100644 index 0000000..cedd216 --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/nto/neutrino.rs @@ -0,0 +1,1288 @@ +pub type nto_job_t = ::sync_t; + +s! { + pub struct intrspin { + pub value: ::c_uint, // volatile + } + + pub struct iov_t { + pub iov_base: *mut ::c_void, // union + pub iov_len: ::size_t, + } + + pub struct _itimer { + pub nsec: u64, + pub interval_nsec: u64, + } + + pub struct _msg_info64 { + pub nd: u32, + pub srcnd: u32, + pub pid: ::pid_t, + pub tid: i32, + pub chid: i32, + pub scoid: i32, + pub coid: i32, + pub priority: i16, + pub flags: i16, + pub msglen: isize, + pub srcmsglen: isize, + pub dstmsglen: isize, + pub type_id: u32, + reserved: u32, + } + + pub struct _cred_info { + pub ruid: ::uid_t, + pub euid: ::uid_t, + pub suid: ::uid_t, + pub rgid: ::gid_t, + pub egid: ::gid_t, + pub sgid: ::gid_t, + pub ngroups: u32, + pub grouplist: [::gid_t; 8], + } + + pub struct _client_info { + pub nd: u32, + pub pid: ::pid_t, + pub sid: ::pid_t, + pub flags: u32, + pub cred: ::_cred_info, + } + + pub struct _client_able { + pub ability: u32, + pub flags: u32, + pub range_lo: u64, + pub range_hi: u64, + } + + pub struct nto_channel_config { + pub event: ::sigevent, + pub num_pulses: ::c_uint, + pub rearm_threshold: ::c_uint, + pub options: ::c_uint, + reserved: [::c_uint; 3], + } + + // TODO: The following structures are defined in a header file which doesn't + // appear as part of the default headers found in a standard installation + // of Neutrino 7.1 SDP. Commented out for now. + //pub struct _asyncmsg_put_header { + // pub err: ::c_int, + // pub iov: *mut ::iov_t, + // pub parts: ::c_int, + // pub handle: ::c_uint, + // pub cb: ::Option< + // unsafe extern "C" fn( + // err: ::c_int, + // buf: *mut ::c_void, + // handle: ::c_uint, + // ) -> ::c_int>, + // pub put_hdr_flags: ::c_uint, + //} + + //pub struct _asyncmsg_connection_attr { + // pub call_back: ::Option< + // unsafe extern "C" fn( + // err: ::c_int, + // buff: *mut ::c_void, + // handle: ::c_uint, + // ) -> ::c_int>, + // pub buffer_size: ::size_t, + // pub max_num_buffer: ::c_uint, + // pub trigger_num_msg: ::c_uint, + // pub trigger_time: ::_itimer, + // reserve: ::c_uint, + //} + + //pub struct _asyncmsg_connection_descriptor { + // pub flags: ::c_uint, + // pub sendq_size: ::c_uint, + // pub sendq_head: ::c_uint, + // pub sendq_tail: ::c_uint, + // pub sendq_free: ::c_uint, + // pub err: ::c_int, + // pub ev: ::sigevent, + // pub num_curmsg: ::c_uint, + // pub ttimer: ::timer_t, + // pub block_con: ::pthread_cond_t, + // pub mu: ::pthread_mutex_t, + // reserved: ::c_uint, + // pub attr: ::_asyncmsg_connection_attr, + // pub reserves: [::c_uint; 3], + // pub sendq: [::_asyncmsg_put_header; 1], // flexarray + //} + + pub struct __c_anonymous_struct_ev { + pub event: ::sigevent, + pub coid: ::c_int, + } + + pub struct _channel_connect_attr { // union + pub ev: ::__c_anonymous_struct_ev, + } + + pub struct _sighandler_info { + pub siginfo: ::siginfo_t, + pub handler: ::Option, + pub context: *mut ::c_void, + } + + pub struct __c_anonymous_struct_time { + pub length: ::c_uint, + pub scale: ::c_uint, + } + + pub struct _idle_hook { + pub hook_size: ::c_uint, + pub cmd: ::c_uint, + pub mode: ::c_uint, + pub latency: ::c_uint, + pub next_fire: u64, + pub curr_time: u64, + pub tod_adjust: u64, + pub resp: ::c_uint, + pub time: __c_anonymous_struct_time, + pub trigger: ::sigevent, + pub intrs: *mut ::c_uint, + pub block_stack_size: ::c_uint, + } + + pub struct _clockadjust { + pub tick_count: u32, + pub tick_nsec_inc: i32, + } + + pub struct qtime_entry { + pub cycles_per_sec: u64, + pub nsec_tod_adjust: u64, // volatile + pub nsec: u64, // volatile + pub nsec_inc: u32, + pub boot_time: u32, + pub adjust: _clockadjust, + pub timer_rate: u32, + pub timer_scale: i32, + pub timer_load: u32, + pub intr: i32, + pub epoch: u32, + pub flags: u32, + pub rr_interval_mul: u32, + pub timer_load_hi: u32, + pub nsec_stable: u64, // volatile + pub timer_load_max: u64, + pub timer_prog_time: u32, + spare: [u32; 7], + } + + pub struct _sched_info { + pub priority_min: ::c_int, + pub priority_max: ::c_int, + pub interval: u64, + pub priority_priv: ::c_int, + reserved: [::c_int; 11], + } + + pub struct _timer_info { + pub itime: ::_itimer, + pub otime: ::_itimer, + pub flags: u32, + pub tid: i32, + pub notify: i32, + pub clockid: ::clockid_t, + pub overruns: u32, + pub event: ::sigevent, // union + } + + pub struct _clockperiod { + pub nsec: u32, + pub fract: i32, + } +} + +s_no_extra_traits! { + pub struct syspage_entry_info { + pub entry_off: u16, + pub entry_size: u16, + } + + pub struct syspage_array_info { + entry_off: u16, + entry_size: u16, + element_size: u16, + } + + #[repr(align(8))] + pub struct syspage_entry { + pub size: u16, + pub total_size: u16, + pub type_: u16, + pub num_cpu: u16, + pub system_private: syspage_entry_info, + pub old_asinfo: syspage_entry_info, + pub __mangle_name_to_cause_compilation_errs_meminfo: syspage_entry_info, + pub hwinfo: syspage_entry_info, + pub old_cpuinfo: syspage_entry_info, + pub old_cacheattr: syspage_entry_info, + pub qtime: syspage_entry_info, + pub callout: syspage_entry_info, + pub callin: syspage_entry_info, + pub typed_strings: syspage_entry_info, + pub strings: syspage_entry_info, + pub old_intrinfo: syspage_entry_info, + pub smp: syspage_entry_info, + pub pminfo: syspage_entry_info, + pub old_mdriver: syspage_entry_info, + spare0: [u32; 1], + __reserved: [u8; 160], // anonymous union with architecture dependent structs + pub new_asinfo: syspage_array_info, + pub new_cpuinfo: syspage_array_info, + pub new_cacheattr: syspage_array_info, + pub new_intrinfo: syspage_array_info, + pub new_mdriver: syspage_array_info, + } +} + +pub const SYSMGR_PID: u32 = 1; +pub const SYSMGR_CHID: u32 = 1; +pub const SYSMGR_COID: u32 = _NTO_SIDE_CHANNEL; +pub const SYSMGR_HANDLE: u32 = 0; + +pub const STATE_DEAD: ::c_int = 0x00; +pub const STATE_RUNNING: ::c_int = 0x01; +pub const STATE_READY: ::c_int = 0x02; +pub const STATE_STOPPED: ::c_int = 0x03; +pub const STATE_SEND: ::c_int = 0x04; +pub const STATE_RECEIVE: ::c_int = 0x05; +pub const STATE_REPLY: ::c_int = 0x06; +pub const STATE_STACK: ::c_int = 0x07; +pub const STATE_WAITTHREAD: ::c_int = 0x08; +pub const STATE_WAITPAGE: ::c_int = 0x09; +pub const STATE_SIGSUSPEND: ::c_int = 0x0a; +pub const STATE_SIGWAITINFO: ::c_int = 0x0b; +pub const STATE_NANOSLEEP: ::c_int = 0x0c; +pub const STATE_MUTEX: ::c_int = 0x0d; +pub const STATE_CONDVAR: ::c_int = 0x0e; +pub const STATE_JOIN: ::c_int = 0x0f; +pub const STATE_INTR: ::c_int = 0x10; +pub const STATE_SEM: ::c_int = 0x11; +pub const STATE_WAITCTX: ::c_int = 0x12; +pub const STATE_NET_SEND: ::c_int = 0x13; +pub const STATE_NET_REPLY: ::c_int = 0x14; +pub const STATE_MAX: ::c_int = 0x18; + +pub const _NTO_TIMEOUT_RECEIVE: i32 = 1 << STATE_RECEIVE; +pub const _NTO_TIMEOUT_SEND: i32 = 1 << STATE_SEND; +pub const _NTO_TIMEOUT_REPLY: i32 = 1 << STATE_REPLY; +pub const _NTO_TIMEOUT_SIGSUSPEND: i32 = 1 << STATE_SIGSUSPEND; +pub const _NTO_TIMEOUT_SIGWAITINFO: i32 = 1 << STATE_SIGWAITINFO; +pub const _NTO_TIMEOUT_NANOSLEEP: i32 = 1 << STATE_NANOSLEEP; +pub const _NTO_TIMEOUT_MUTEX: i32 = 1 << STATE_MUTEX; +pub const _NTO_TIMEOUT_CONDVAR: i32 = 1 << STATE_CONDVAR; +pub const _NTO_TIMEOUT_JOIN: i32 = 1 << STATE_JOIN; +pub const _NTO_TIMEOUT_INTR: i32 = 1 << STATE_INTR; +pub const _NTO_TIMEOUT_SEM: i32 = 1 << STATE_SEM; + +pub const _NTO_MI_ENDIAN_BIG: u32 = 1; +pub const _NTO_MI_ENDIAN_DIFF: u32 = 2; +pub const _NTO_MI_UNBLOCK_REQ: u32 = 256; +pub const _NTO_MI_NET_CRED_DIRTY: u32 = 512; +pub const _NTO_MI_CONSTRAINED: u32 = 1024; +pub const _NTO_MI_CHROOT: u32 = 2048; +pub const _NTO_MI_BITS_64: u32 = 4096; +pub const _NTO_MI_BITS_DIFF: u32 = 8192; +pub const _NTO_MI_SANDBOX: u32 = 16384; + +pub const _NTO_CI_ENDIAN_BIG: u32 = 1; +pub const _NTO_CI_BKGND_PGRP: u32 = 4; +pub const _NTO_CI_ORPHAN_PGRP: u32 = 8; +pub const _NTO_CI_STOPPED: u32 = 128; +pub const _NTO_CI_UNABLE: u32 = 256; +pub const _NTO_CI_TYPE_ID: u32 = 512; +pub const _NTO_CI_CHROOT: u32 = 2048; +pub const _NTO_CI_BITS_64: u32 = 4096; +pub const _NTO_CI_SANDBOX: u32 = 16384; +pub const _NTO_CI_LOADER: u32 = 32768; +pub const _NTO_CI_FULL_GROUPS: u32 = 2147483648; + +pub const _NTO_TI_ACTIVE: u32 = 1; +pub const _NTO_TI_ABSOLUTE: u32 = 2; +pub const _NTO_TI_EXPIRED: u32 = 4; +pub const _NTO_TI_TOD_BASED: u32 = 8; +pub const _NTO_TI_TARGET_PROCESS: u32 = 16; +pub const _NTO_TI_REPORT_TOLERANCE: u32 = 32; +pub const _NTO_TI_PRECISE: u32 = 64; +pub const _NTO_TI_TOLERANT: u32 = 128; +pub const _NTO_TI_WAKEUP: u32 = 256; +pub const _NTO_TI_PROCESS_TOLERANT: u32 = 512; +pub const _NTO_TI_HIGH_RESOLUTION: u32 = 1024; + +pub const _PULSE_TYPE: u32 = 0; +pub const _PULSE_SUBTYPE: u32 = 0; +pub const _PULSE_CODE_UNBLOCK: i32 = -32; +pub const _PULSE_CODE_DISCONNECT: i32 = -33; +pub const _PULSE_CODE_THREADDEATH: i32 = -34; +pub const _PULSE_CODE_COIDDEATH: i32 = -35; +pub const _PULSE_CODE_NET_ACK: i32 = -36; +pub const _PULSE_CODE_NET_UNBLOCK: i32 = -37; +pub const _PULSE_CODE_NET_DETACH: i32 = -38; +pub const _PULSE_CODE_RESTART: i32 = -39; +pub const _PULSE_CODE_NORESTART: i32 = -40; +pub const _PULSE_CODE_UNBLOCK_RESTART: i32 = -41; +pub const _PULSE_CODE_UNBLOCK_TIMER: i32 = -42; +pub const _PULSE_CODE_MINAVAIL: u32 = 0; +pub const _PULSE_CODE_MAXAVAIL: u32 = 127; + +pub const _NTO_HARD_FLAGS_END: u32 = 1; + +pub const _NTO_PULSE_IF_UNIQUE: u32 = 4096; +pub const _NTO_PULSE_REPLACE: u32 = 8192; + +pub const _NTO_PF_NOCLDSTOP: u32 = 1; +pub const _NTO_PF_LOADING: u32 = 2; +pub const _NTO_PF_TERMING: u32 = 4; +pub const _NTO_PF_ZOMBIE: u32 = 8; +pub const _NTO_PF_NOZOMBIE: u32 = 16; +pub const _NTO_PF_FORKED: u32 = 32; +pub const _NTO_PF_ORPHAN_PGRP: u32 = 64; +pub const _NTO_PF_STOPPED: u32 = 128; +pub const _NTO_PF_DEBUG_STOPPED: u32 = 256; +pub const _NTO_PF_BKGND_PGRP: u32 = 512; +pub const _NTO_PF_NOISYNC: u32 = 1024; +pub const _NTO_PF_CONTINUED: u32 = 2048; +pub const _NTO_PF_CHECK_INTR: u32 = 4096; +pub const _NTO_PF_COREDUMP: u32 = 8192; +pub const _NTO_PF_RING0: u32 = 32768; +pub const _NTO_PF_SLEADER: u32 = 65536; +pub const _NTO_PF_WAITINFO: u32 = 131072; +pub const _NTO_PF_DESTROYALL: u32 = 524288; +pub const _NTO_PF_NOCOREDUMP: u32 = 1048576; +pub const _NTO_PF_WAITDONE: u32 = 4194304; +pub const _NTO_PF_TERM_WAITING: u32 = 8388608; +pub const _NTO_PF_ASLR: u32 = 16777216; +pub const _NTO_PF_EXECED: u32 = 33554432; +pub const _NTO_PF_APP_STOPPED: u32 = 67108864; +pub const _NTO_PF_64BIT: u32 = 134217728; +pub const _NTO_PF_NET: u32 = 268435456; +pub const _NTO_PF_NOLAZYSTACK: u32 = 536870912; +pub const _NTO_PF_NOEXEC_STACK: u32 = 1073741824; +pub const _NTO_PF_LOADER_PERMS: u32 = 2147483648; + +pub const _NTO_TF_INTR_PENDING: u32 = 65536; +pub const _NTO_TF_DETACHED: u32 = 131072; +pub const _NTO_TF_SHR_MUTEX: u32 = 262144; +pub const _NTO_TF_SHR_MUTEX_EUID: u32 = 524288; +pub const _NTO_TF_THREADS_HOLD: u32 = 1048576; +pub const _NTO_TF_UNBLOCK_REQ: u32 = 4194304; +pub const _NTO_TF_ALIGN_FAULT: u32 = 16777216; +pub const _NTO_TF_SSTEP: u32 = 33554432; +pub const _NTO_TF_ALLOCED_STACK: u32 = 67108864; +pub const _NTO_TF_NOMULTISIG: u32 = 134217728; +pub const _NTO_TF_LOW_LATENCY: u32 = 268435456; +pub const _NTO_TF_IOPRIV: u32 = 2147483648; + +pub const _NTO_TCTL_IO_PRIV: u32 = 1; +pub const _NTO_TCTL_THREADS_HOLD: u32 = 2; +pub const _NTO_TCTL_THREADS_CONT: u32 = 3; +pub const _NTO_TCTL_RUNMASK: u32 = 4; +pub const _NTO_TCTL_ALIGN_FAULT: u32 = 5; +pub const _NTO_TCTL_RUNMASK_GET_AND_SET: u32 = 6; +pub const _NTO_TCTL_PERFCOUNT: u32 = 7; +pub const _NTO_TCTL_ONE_THREAD_HOLD: u32 = 8; +pub const _NTO_TCTL_ONE_THREAD_CONT: u32 = 9; +pub const _NTO_TCTL_RUNMASK_GET_AND_SET_INHERIT: u32 = 10; +pub const _NTO_TCTL_NAME: u32 = 11; +pub const _NTO_TCTL_RCM_GET_AND_SET: u32 = 12; +pub const _NTO_TCTL_SHR_MUTEX: u32 = 13; +pub const _NTO_TCTL_IO: u32 = 14; +pub const _NTO_TCTL_NET_KIF_GET_AND_SET: u32 = 15; +pub const _NTO_TCTL_LOW_LATENCY: u32 = 16; +pub const _NTO_TCTL_ADD_EXIT_EVENT: u32 = 17; +pub const _NTO_TCTL_DEL_EXIT_EVENT: u32 = 18; +pub const _NTO_TCTL_IO_LEVEL: u32 = 19; +pub const _NTO_TCTL_RESERVED: u32 = 2147483648; +pub const _NTO_TCTL_IO_LEVEL_INHERIT: u32 = 1073741824; +pub const _NTO_IO_LEVEL_NONE: u32 = 1; +pub const _NTO_IO_LEVEL_1: u32 = 2; +pub const _NTO_IO_LEVEL_2: u32 = 3; + +pub const _NTO_THREAD_NAME_MAX: u32 = 100; + +pub const _NTO_CHF_FIXED_PRIORITY: u32 = 1; +pub const _NTO_CHF_UNBLOCK: u32 = 2; +pub const _NTO_CHF_THREAD_DEATH: u32 = 4; +pub const _NTO_CHF_DISCONNECT: u32 = 8; +pub const _NTO_CHF_NET_MSG: u32 = 16; +pub const _NTO_CHF_SENDER_LEN: u32 = 32; +pub const _NTO_CHF_COID_DISCONNECT: u32 = 64; +pub const _NTO_CHF_REPLY_LEN: u32 = 128; +pub const _NTO_CHF_PULSE_POOL: u32 = 256; +pub const _NTO_CHF_ASYNC_NONBLOCK: u32 = 512; +pub const _NTO_CHF_ASYNC: u32 = 1024; +pub const _NTO_CHF_GLOBAL: u32 = 2048; +pub const _NTO_CHF_PRIVATE: u32 = 4096; +pub const _NTO_CHF_MSG_PAUSING: u32 = 8192; +pub const _NTO_CHF_INHERIT_RUNMASK: u32 = 16384; +pub const _NTO_CHF_UNBLOCK_TIMER: u32 = 32768; + +pub const _NTO_CHO_CUSTOM_EVENT: u32 = 1; + +pub const _NTO_COF_CLOEXEC: u32 = 1; +pub const _NTO_COF_DEAD: u32 = 2; +pub const _NTO_COF_NOSHARE: u32 = 64; +pub const _NTO_COF_NETCON: u32 = 128; +pub const _NTO_COF_NONBLOCK: u32 = 256; +pub const _NTO_COF_ASYNC: u32 = 512; +pub const _NTO_COF_GLOBAL: u32 = 1024; +pub const _NTO_COF_NOEVENT: u32 = 2048; +pub const _NTO_COF_INSECURE: u32 = 4096; +pub const _NTO_COF_REG_EVENTS: u32 = 8192; +pub const _NTO_COF_UNREG_EVENTS: u32 = 16384; +pub const _NTO_COF_MASK: u32 = 65535; + +pub const _NTO_SIDE_CHANNEL: u32 = 1073741824; + +pub const _NTO_CONNECTION_SCOID: u32 = 65536; +pub const _NTO_GLOBAL_CHANNEL: u32 = 1073741824; + +pub const _NTO_TIMEOUT_MASK: u32 = (1 << STATE_MAX) - 1; +pub const _NTO_TIMEOUT_ACTIVE: u32 = 1 << STATE_MAX; +pub const _NTO_TIMEOUT_IMMEDIATE: u32 = 1 << (STATE_MAX + 1); + +pub const _NTO_IC_LATENCY: u32 = 0; + +pub const _NTO_INTR_FLAGS_END: u32 = 1; +pub const _NTO_INTR_FLAGS_NO_UNMASK: u32 = 2; +pub const _NTO_INTR_FLAGS_PROCESS: u32 = 4; +pub const _NTO_INTR_FLAGS_TRK_MSK: u32 = 8; +pub const _NTO_INTR_FLAGS_ARRAY: u32 = 16; +pub const _NTO_INTR_FLAGS_EXCLUSIVE: u32 = 32; +pub const _NTO_INTR_FLAGS_FPU: u32 = 64; + +pub const _NTO_INTR_CLASS_EXTERNAL: u32 = 0; +pub const _NTO_INTR_CLASS_SYNTHETIC: u32 = 2147418112; + +pub const _NTO_INTR_SPARE: u32 = 2147483647; + +pub const _NTO_HOOK_IDLE: u32 = 2147418113; +pub const _NTO_HOOK_OVERDRIVE: u32 = 2147418114; +pub const _NTO_HOOK_LAST: u32 = 2147418114; +pub const _NTO_HOOK_IDLE2_FLAG: u32 = 32768; + +pub const _NTO_IH_CMD_SLEEP_SETUP: u32 = 1; +pub const _NTO_IH_CMD_SLEEP_BLOCK: u32 = 2; +pub const _NTO_IH_CMD_SLEEP_WAKEUP: u32 = 4; +pub const _NTO_IH_CMD_SLEEP_ONLINE: u32 = 8; +pub const _NTO_IH_RESP_NEEDS_BLOCK: u32 = 1; +pub const _NTO_IH_RESP_NEEDS_WAKEUP: u32 = 2; +pub const _NTO_IH_RESP_NEEDS_ONLINE: u32 = 4; +pub const _NTO_IH_RESP_SYNC_TIME: u32 = 16; +pub const _NTO_IH_RESP_SYNC_TLB: u32 = 32; +pub const _NTO_IH_RESP_SUGGEST_OFFLINE: u32 = 256; +pub const _NTO_IH_RESP_SLEEP_MODE_REACHED: u32 = 512; +pub const _NTO_IH_RESP_DELIVER_INTRS: u32 = 1024; + +pub const _NTO_READIOV_SEND: u32 = 0; +pub const _NTO_READIOV_REPLY: u32 = 1; + +pub const _NTO_KEYDATA_VTID: u32 = 2147483648; + +pub const _NTO_KEYDATA_PATHSIGN: u32 = 32768; +pub const _NTO_KEYDATA_OP_MASK: u32 = 255; +pub const _NTO_KEYDATA_VERIFY: u32 = 0; +pub const _NTO_KEYDATA_CALCULATE: u32 = 1; +pub const _NTO_KEYDATA_CALCULATE_REUSE: u32 = 2; +pub const _NTO_KEYDATA_PATHSIGN_VERIFY: u32 = 32768; +pub const _NTO_KEYDATA_PATHSIGN_CALCULATE: u32 = 32769; +pub const _NTO_KEYDATA_PATHSIGN_CALCULATE_REUSE: u32 = 32770; + +pub const _NTO_SCTL_SETPRIOCEILING: u32 = 1; +pub const _NTO_SCTL_GETPRIOCEILING: u32 = 2; +pub const _NTO_SCTL_SETEVENT: u32 = 3; +pub const _NTO_SCTL_MUTEX_WAKEUP: u32 = 4; +pub const _NTO_SCTL_MUTEX_CONSISTENT: u32 = 5; +pub const _NTO_SCTL_SEM_VALUE: u32 = 6; + +pub const _NTO_CLIENTINFO_GETGROUPS: u32 = 1; +pub const _NTO_CLIENTINFO_GETTYPEID: u32 = 2; + +extern "C" { + pub fn ChannelCreate(__flags: ::c_uint) -> ::c_int; + pub fn ChannelCreate_r(__flags: ::c_uint) -> ::c_int; + pub fn ChannelCreatePulsePool( + __flags: ::c_uint, + __config: *const nto_channel_config, + ) -> ::c_int; + pub fn ChannelCreateExt( + __flags: ::c_uint, + __mode: ::mode_t, + __bufsize: usize, + __maxnumbuf: ::c_uint, + __ev: *const ::sigevent, + __cred: *mut _cred_info, + ) -> ::c_int; + pub fn ChannelDestroy(__chid: ::c_int) -> ::c_int; + pub fn ChannelDestroy_r(__chid: ::c_int) -> ::c_int; + pub fn ConnectAttach( + __nd: u32, + __pid: ::pid_t, + __chid: ::c_int, + __index: ::c_uint, + __flags: ::c_int, + ) -> ::c_int; + pub fn ConnectAttach_r( + __nd: u32, + __pid: ::pid_t, + __chid: ::c_int, + __index: ::c_uint, + __flags: ::c_int, + ) -> ::c_int; + + // TODO: The following function uses a structure defined in a header file + // which doesn't appear as part of the default headers found in a + // standard installation of Neutrino 7.1 SDP. Commented out for now. + //pub fn ConnectAttachExt( + // __nd: u32, + // __pid: ::pid_t, + // __chid: ::c_int, + // __index: ::c_uint, + // __flags: ::c_int, + // __cd: *mut _asyncmsg_connection_descriptor, + //) -> ::c_int; + pub fn ConnectDetach(__coid: ::c_int) -> ::c_int; + pub fn ConnectDetach_r(__coid: ::c_int) -> ::c_int; + pub fn ConnectServerInfo(__pid: ::pid_t, __coid: ::c_int, __info: *mut _msg_info64) -> ::c_int; + pub fn ConnectServerInfo_r( + __pid: ::pid_t, + __coid: ::c_int, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn ConnectClientInfoExtraArgs( + __scoid: ::c_int, + __info_pp: *mut _client_info, + __ngroups: ::c_int, + __abilities: *mut _client_able, + __nable: ::c_int, + __type_id: *mut ::c_uint, + ) -> ::c_int; + pub fn ConnectClientInfoExtraArgs_r( + __scoid: ::c_int, + __info_pp: *mut _client_info, + __ngroups: ::c_int, + __abilities: *mut _client_able, + __nable: ::c_int, + __type_id: *mut ::c_uint, + ) -> ::c_int; + pub fn ConnectClientInfo( + __scoid: ::c_int, + __info: *mut _client_info, + __ngroups: ::c_int, + ) -> ::c_int; + pub fn ConnectClientInfo_r( + __scoid: ::c_int, + __info: *mut _client_info, + __ngroups: ::c_int, + ) -> ::c_int; + pub fn ConnectClientInfoExt( + __scoid: ::c_int, + __info_pp: *mut *mut _client_info, + flags: ::c_int, + ) -> ::c_int; + pub fn ClientInfoExtFree(__info_pp: *mut *mut _client_info) -> ::c_int; + pub fn ConnectClientInfoAble( + __scoid: ::c_int, + __info_pp: *mut *mut _client_info, + flags: ::c_int, + abilities: *mut _client_able, + nable: ::c_int, + ) -> ::c_int; + pub fn ConnectFlags( + __pid: ::pid_t, + __coid: ::c_int, + __mask: ::c_uint, + __bits: ::c_uint, + ) -> ::c_int; + pub fn ConnectFlags_r( + __pid: ::pid_t, + __coid: ::c_int, + __mask: ::c_uint, + __bits: ::c_uint, + ) -> ::c_int; + pub fn ChannelConnectAttr( + __id: ::c_uint, + __old_attr: *mut _channel_connect_attr, + __new_attr: *mut _channel_connect_attr, + __flags: ::c_uint, + ) -> ::c_int; + pub fn MsgSend( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSend_r( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendnc( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendnc_r( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendsv( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendsv_r( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendsvnc( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendsvnc_r( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendvs( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendvs_r( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendvsnc( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendvsnc_r( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __rmsg: *mut ::c_void, + __rbytes: usize, + ) -> ::c_long; + pub fn MsgSendv( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendv_r( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendvnc( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgSendvnc_r( + __coid: ::c_int, + __siov: *const ::iovec, + __sparts: usize, + __riov: *const ::iovec, + __rparts: usize, + ) -> ::c_long; + pub fn MsgReceive( + __chid: ::c_int, + __msg: *mut ::c_void, + __bytes: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceive_r( + __chid: ::c_int, + __msg: *mut ::c_void, + __bytes: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceivev( + __chid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceivev_r( + __chid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceivePulse( + __chid: ::c_int, + __pulse: *mut ::c_void, + __bytes: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceivePulse_r( + __chid: ::c_int, + __pulse: *mut ::c_void, + __bytes: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceivePulsev( + __chid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReceivePulsev_r( + __chid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __info: *mut _msg_info64, + ) -> ::c_int; + pub fn MsgReply( + __rcvid: ::c_int, + __status: ::c_long, + __msg: *const ::c_void, + __bytes: usize, + ) -> ::c_int; + pub fn MsgReply_r( + __rcvid: ::c_int, + __status: ::c_long, + __msg: *const ::c_void, + __bytes: usize, + ) -> ::c_int; + pub fn MsgReplyv( + __rcvid: ::c_int, + __status: ::c_long, + __iov: *const ::iovec, + __parts: usize, + ) -> ::c_int; + pub fn MsgReplyv_r( + __rcvid: ::c_int, + __status: ::c_long, + __iov: *const ::iovec, + __parts: usize, + ) -> ::c_int; + pub fn MsgReadiov( + __rcvid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __offset: usize, + __flags: ::c_int, + ) -> isize; + pub fn MsgReadiov_r( + __rcvid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __offset: usize, + __flags: ::c_int, + ) -> isize; + pub fn MsgRead( + __rcvid: ::c_int, + __msg: *mut ::c_void, + __bytes: usize, + __offset: usize, + ) -> isize; + pub fn MsgRead_r( + __rcvid: ::c_int, + __msg: *mut ::c_void, + __bytes: usize, + __offset: usize, + ) -> isize; + pub fn MsgReadv( + __rcvid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __offset: usize, + ) -> isize; + pub fn MsgReadv_r( + __rcvid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __offset: usize, + ) -> isize; + pub fn MsgWrite( + __rcvid: ::c_int, + __msg: *const ::c_void, + __bytes: usize, + __offset: usize, + ) -> isize; + pub fn MsgWrite_r( + __rcvid: ::c_int, + __msg: *const ::c_void, + __bytes: usize, + __offset: usize, + ) -> isize; + pub fn MsgWritev( + __rcvid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __offset: usize, + ) -> isize; + pub fn MsgWritev_r( + __rcvid: ::c_int, + __iov: *const ::iovec, + __parts: usize, + __offset: usize, + ) -> isize; + pub fn MsgSendPulse( + __coid: ::c_int, + __priority: ::c_int, + __code: ::c_int, + __value: ::c_int, + ) -> ::c_int; + pub fn MsgSendPulse_r( + __coid: ::c_int, + __priority: ::c_int, + __code: ::c_int, + __value: ::c_int, + ) -> ::c_int; + pub fn MsgSendPulsePtr( + __coid: ::c_int, + __priority: ::c_int, + __code: ::c_int, + __value: *mut ::c_void, + ) -> ::c_int; + pub fn MsgSendPulsePtr_r( + __coid: ::c_int, + __priority: ::c_int, + __code: ::c_int, + __value: *mut ::c_void, + ) -> ::c_int; + pub fn MsgDeliverEvent(__rcvid: ::c_int, __event: *const ::sigevent) -> ::c_int; + pub fn MsgDeliverEvent_r(__rcvid: ::c_int, __event: *const ::sigevent) -> ::c_int; + pub fn MsgVerifyEvent(__rcvid: ::c_int, __event: *const ::sigevent) -> ::c_int; + pub fn MsgVerifyEvent_r(__rcvid: ::c_int, __event: *const ::sigevent) -> ::c_int; + pub fn MsgRegisterEvent(__event: *mut ::sigevent, __coid: ::c_int) -> ::c_int; + pub fn MsgRegisterEvent_r(__event: *mut ::sigevent, __coid: ::c_int) -> ::c_int; + pub fn MsgUnregisterEvent(__event: *const ::sigevent) -> ::c_int; + pub fn MsgUnregisterEvent_r(__event: *const ::sigevent) -> ::c_int; + pub fn MsgInfo(__rcvid: ::c_int, __info: *mut _msg_info64) -> ::c_int; + pub fn MsgInfo_r(__rcvid: ::c_int, __info: *mut _msg_info64) -> ::c_int; + pub fn MsgKeyData( + __rcvid: ::c_int, + __oper: ::c_int, + __key: u32, + __newkey: *mut u32, + __iov: *const ::iovec, + __parts: ::c_int, + ) -> ::c_int; + pub fn MsgKeyData_r( + __rcvid: ::c_int, + __oper: ::c_int, + __key: u32, + __newkey: *mut u32, + __iov: *const ::iovec, + __parts: ::c_int, + ) -> ::c_int; + pub fn MsgError(__rcvid: ::c_int, __err: ::c_int) -> ::c_int; + pub fn MsgError_r(__rcvid: ::c_int, __err: ::c_int) -> ::c_int; + pub fn MsgCurrent(__rcvid: ::c_int) -> ::c_int; + pub fn MsgCurrent_r(__rcvid: ::c_int) -> ::c_int; + pub fn MsgSendAsyncGbl( + __coid: ::c_int, + __smsg: *const ::c_void, + __sbytes: usize, + __msg_prio: ::c_uint, + ) -> ::c_int; + pub fn MsgSendAsync(__coid: ::c_int) -> ::c_int; + pub fn MsgReceiveAsyncGbl( + __chid: ::c_int, + __rmsg: *mut ::c_void, + __rbytes: usize, + __info: *mut _msg_info64, + __coid: ::c_int, + ) -> ::c_int; + pub fn MsgReceiveAsync(__chid: ::c_int, __iov: *const ::iovec, __parts: ::c_uint) -> ::c_int; + pub fn MsgPause(__rcvid: ::c_int, __cookie: ::c_uint) -> ::c_int; + pub fn MsgPause_r(__rcvid: ::c_int, __cookie: ::c_uint) -> ::c_int; + + pub fn SignalKill( + __nd: u32, + __pid: ::pid_t, + __tid: ::c_int, + __signo: ::c_int, + __code: ::c_int, + __value: ::c_int, + ) -> ::c_int; + pub fn SignalKill_r( + __nd: u32, + __pid: ::pid_t, + __tid: ::c_int, + __signo: ::c_int, + __code: ::c_int, + __value: ::c_int, + ) -> ::c_int; + pub fn SignalKillSigval( + __nd: u32, + __pid: ::pid_t, + __tid: ::c_int, + __signo: ::c_int, + __code: ::c_int, + __value: *const ::sigval, + ) -> ::c_int; + pub fn SignalKillSigval_r( + __nd: u32, + __pid: ::pid_t, + __tid: ::c_int, + __signo: ::c_int, + __code: ::c_int, + __value: *const ::sigval, + ) -> ::c_int; + pub fn SignalReturn(__info: *mut _sighandler_info) -> ::c_int; + pub fn SignalFault(__sigcode: ::c_uint, __regs: *mut ::c_void, __refaddr: usize) -> ::c_int; + pub fn SignalAction( + __pid: ::pid_t, + __sigstub: unsafe extern "C" fn(), + __signo: ::c_int, + __act: *const ::sigaction, + __oact: *mut ::sigaction, + ) -> ::c_int; + pub fn SignalAction_r( + __pid: ::pid_t, + __sigstub: unsafe extern "C" fn(), + __signo: ::c_int, + __act: *const ::sigaction, + __oact: *mut ::sigaction, + ) -> ::c_int; + pub fn SignalProcmask( + __pid: ::pid_t, + __tid: ::c_int, + __how: ::c_int, + __set: *const ::sigset_t, + __oldset: *mut ::sigset_t, + ) -> ::c_int; + pub fn SignalProcmask_r( + __pid: ::pid_t, + __tid: ::c_int, + __how: ::c_int, + __set: *const ::sigset_t, + __oldset: *mut ::sigset_t, + ) -> ::c_int; + pub fn SignalSuspend(__set: *const ::sigset_t) -> ::c_int; + pub fn SignalSuspend_r(__set: *const ::sigset_t) -> ::c_int; + pub fn SignalWaitinfo(__set: *const ::sigset_t, __info: *mut ::siginfo_t) -> ::c_int; + pub fn SignalWaitinfo_r(__set: *const ::sigset_t, __info: *mut ::siginfo_t) -> ::c_int; + pub fn SignalWaitinfoMask( + __set: *const ::sigset_t, + __info: *mut ::siginfo_t, + __mask: *const ::sigset_t, + ) -> ::c_int; + pub fn SignalWaitinfoMask_r( + __set: *const ::sigset_t, + __info: *mut ::siginfo_t, + __mask: *const ::sigset_t, + ) -> ::c_int; + pub fn ThreadCreate( + __pid: ::pid_t, + __func: unsafe extern "C" fn(__arg: *mut ::c_void) -> *mut ::c_void, + __arg: *mut ::c_void, + __attr: *const ::_thread_attr, + ) -> ::c_int; + pub fn ThreadCreate_r( + __pid: ::pid_t, + __func: unsafe extern "C" fn(__arg: *mut ::c_void) -> *mut ::c_void, + __arg: *mut ::c_void, + __attr: *const ::_thread_attr, + ) -> ::c_int; + + pub fn ThreadDestroy(__tid: ::c_int, __priority: ::c_int, __status: *mut ::c_void) -> ::c_int; + pub fn ThreadDestroy_r(__tid: ::c_int, __priority: ::c_int, __status: *mut ::c_void) + -> ::c_int; + pub fn ThreadDetach(__tid: ::c_int) -> ::c_int; + pub fn ThreadDetach_r(__tid: ::c_int) -> ::c_int; + pub fn ThreadJoin(__tid: ::c_int, __status: *mut *mut ::c_void) -> ::c_int; + pub fn ThreadJoin_r(__tid: ::c_int, __status: *mut *mut ::c_void) -> ::c_int; + pub fn ThreadCancel(__tid: ::c_int, __canstub: unsafe extern "C" fn()) -> ::c_int; + pub fn ThreadCancel_r(__tid: ::c_int, __canstub: unsafe extern "C" fn()) -> ::c_int; + pub fn ThreadCtl(__cmd: ::c_int, __data: *mut ::c_void) -> ::c_int; + pub fn ThreadCtl_r(__cmd: ::c_int, __data: *mut ::c_void) -> ::c_int; + pub fn ThreadCtlExt( + __pid: ::pid_t, + __tid: ::c_int, + __cmd: ::c_int, + __data: *mut ::c_void, + ) -> ::c_int; + pub fn ThreadCtlExt_r( + __pid: ::pid_t, + __tid: ::c_int, + __cmd: ::c_int, + __data: *mut ::c_void, + ) -> ::c_int; + + pub fn InterruptHookTrace( + __handler: ::Option *const ::sigevent>, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptHookIdle( + __handler: ::Option, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptHookIdle2( + __handler: ::Option< + unsafe extern "C" fn(arg1: ::c_uint, arg2: *mut syspage_entry, arg3: *mut _idle_hook), + >, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptHookOverdriveEvent(__event: *const ::sigevent, __flags: ::c_uint) -> ::c_int; + pub fn InterruptAttachEvent( + __intr: ::c_int, + __event: *const ::sigevent, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptAttachEvent_r( + __intr: ::c_int, + __event: *const ::sigevent, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptAttach( + __intr: ::c_int, + __handler: ::Option< + unsafe extern "C" fn(__area: *mut ::c_void, __id: ::c_int) -> *const ::sigevent, + >, + __area: *const ::c_void, + __size: ::c_int, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptAttach_r( + __intr: ::c_int, + __handler: ::Option< + unsafe extern "C" fn(__area: *mut ::c_void, __id: ::c_int) -> *const ::sigevent, + >, + __area: *const ::c_void, + __size: ::c_int, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptAttachArray( + __intr: ::c_int, + __handler: ::Option< + unsafe extern "C" fn(__area: *mut ::c_void, __id: ::c_int) -> *const *const ::sigevent, + >, + __area: *const ::c_void, + __size: ::c_int, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptAttachArray_r( + __intr: ::c_int, + __handler: ::Option< + unsafe extern "C" fn(__area: *mut ::c_void, __id: ::c_int) -> *const *const ::sigevent, + >, + __area: *const ::c_void, + __size: ::c_int, + __flags: ::c_uint, + ) -> ::c_int; + pub fn InterruptDetach(__id: ::c_int) -> ::c_int; + pub fn InterruptDetach_r(__id: ::c_int) -> ::c_int; + pub fn InterruptWait(__flags: ::c_int, __timeout: *const u64) -> ::c_int; + pub fn InterruptWait_r(__flags: ::c_int, __timeout: *const u64) -> ::c_int; + pub fn InterruptCharacteristic( + __type: ::c_int, + __id: ::c_int, + __new: *mut ::c_uint, + __old: *mut ::c_uint, + ) -> ::c_int; + pub fn InterruptCharacteristic_r( + __type: ::c_int, + __id: ::c_int, + __new: *mut ::c_uint, + __old: *mut ::c_uint, + ) -> ::c_int; + + pub fn SchedGet(__pid: ::pid_t, __tid: ::c_int, __param: *mut ::sched_param) -> ::c_int; + pub fn SchedGet_r(__pid: ::pid_t, __tid: ::c_int, __param: *mut ::sched_param) -> ::c_int; + pub fn SchedGetCpuNum() -> ::c_uint; + pub fn SchedSet( + __pid: ::pid_t, + __tid: ::c_int, + __algorithm: ::c_int, + __param: *const ::sched_param, + ) -> ::c_int; + pub fn SchedSet_r( + __pid: ::pid_t, + __tid: ::c_int, + __algorithm: ::c_int, + __param: *const ::sched_param, + ) -> ::c_int; + pub fn SchedInfo(__pid: ::pid_t, __algorithm: ::c_int, __info: *mut ::_sched_info) -> ::c_int; + pub fn SchedInfo_r(__pid: ::pid_t, __algorithm: ::c_int, __info: *mut ::_sched_info) + -> ::c_int; + pub fn SchedYield() -> ::c_int; + pub fn SchedYield_r() -> ::c_int; + pub fn SchedCtl(__cmd: ::c_int, __data: *mut ::c_void, __length: usize) -> ::c_int; + pub fn SchedCtl_r(__cmd: ::c_int, __data: *mut ::c_void, __length: usize) -> ::c_int; + pub fn SchedJobCreate(__job: *mut nto_job_t) -> ::c_int; + pub fn SchedJobCreate_r(__job: *mut nto_job_t) -> ::c_int; + pub fn SchedJobDestroy(__job: *mut nto_job_t) -> ::c_int; + pub fn SchedJobDestroy_r(__job: *mut nto_job_t) -> ::c_int; + pub fn SchedWaypoint( + __job: *mut nto_job_t, + __new: *const i64, + __max: *const i64, + __old: *mut i64, + ) -> ::c_int; + pub fn SchedWaypoint_r( + __job: *mut nto_job_t, + __new: *const i64, + __max: *const i64, + __old: *mut i64, + ) -> ::c_int; + + pub fn TimerCreate(__id: ::clockid_t, __notify: *const ::sigevent) -> ::c_int; + pub fn TimerCreate_r(__id: ::clockid_t, __notify: *const ::sigevent) -> ::c_int; + pub fn TimerDestroy(__id: ::timer_t) -> ::c_int; + pub fn TimerDestroy_r(__id: ::timer_t) -> ::c_int; + pub fn TimerSettime( + __id: ::timer_t, + __flags: ::c_int, + __itime: *const ::_itimer, + __oitime: *mut ::_itimer, + ) -> ::c_int; + pub fn TimerSettime_r( + __id: ::timer_t, + __flags: ::c_int, + __itime: *const ::_itimer, + __oitime: *mut ::_itimer, + ) -> ::c_int; + pub fn TimerInfo( + __pid: ::pid_t, + __id: ::timer_t, + __flags: ::c_int, + __info: *mut ::_timer_info, + ) -> ::c_int; + pub fn TimerInfo_r( + __pid: ::pid_t, + __id: ::timer_t, + __flags: ::c_int, + __info: *mut ::_timer_info, + ) -> ::c_int; + pub fn TimerAlarm( + __id: ::clockid_t, + __itime: *const ::_itimer, + __otime: *mut ::_itimer, + ) -> ::c_int; + pub fn TimerAlarm_r( + __id: ::clockid_t, + __itime: *const ::_itimer, + __otime: *mut ::_itimer, + ) -> ::c_int; + pub fn TimerTimeout( + __id: ::clockid_t, + __flags: ::c_int, + __notify: *const ::sigevent, + __ntime: *const u64, + __otime: *mut u64, + ) -> ::c_int; + pub fn TimerTimeout_r( + __id: ::clockid_t, + __flags: ::c_int, + __notify: *const ::sigevent, + __ntime: *const u64, + __otime: *mut u64, + ) -> ::c_int; + + pub fn SyncTypeCreate( + __type: ::c_uint, + __sync: *mut ::sync_t, + __attr: *const ::_sync_attr, + ) -> ::c_int; + pub fn SyncTypeCreate_r( + __type: ::c_uint, + __sync: *mut ::sync_t, + __attr: *const ::_sync_attr, + ) -> ::c_int; + pub fn SyncDestroy(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncDestroy_r(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncCtl(__cmd: ::c_int, __sync: *mut ::sync_t, __data: *mut ::c_void) -> ::c_int; + pub fn SyncCtl_r(__cmd: ::c_int, __sync: *mut ::sync_t, __data: *mut ::c_void) -> ::c_int; + pub fn SyncMutexEvent(__sync: *mut ::sync_t, event: *const ::sigevent) -> ::c_int; + pub fn SyncMutexEvent_r(__sync: *mut ::sync_t, event: *const ::sigevent) -> ::c_int; + pub fn SyncMutexLock(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncMutexLock_r(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncMutexUnlock(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncMutexUnlock_r(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncMutexRevive(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncMutexRevive_r(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncCondvarWait(__sync: *mut ::sync_t, __mutex: *mut ::sync_t) -> ::c_int; + pub fn SyncCondvarWait_r(__sync: *mut ::sync_t, __mutex: *mut ::sync_t) -> ::c_int; + pub fn SyncCondvarSignal(__sync: *mut ::sync_t, __all: ::c_int) -> ::c_int; + pub fn SyncCondvarSignal_r(__sync: *mut ::sync_t, __all: ::c_int) -> ::c_int; + pub fn SyncSemPost(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncSemPost_r(__sync: *mut ::sync_t) -> ::c_int; + pub fn SyncSemWait(__sync: *mut ::sync_t, __tryto: ::c_int) -> ::c_int; + pub fn SyncSemWait_r(__sync: *mut ::sync_t, __tryto: ::c_int) -> ::c_int; + + pub fn ClockTime(__id: ::clockid_t, _new: *const u64, __old: *mut u64) -> ::c_int; + pub fn ClockTime_r(__id: ::clockid_t, _new: *const u64, __old: *mut u64) -> ::c_int; + pub fn ClockAdjust( + __id: ::clockid_t, + _new: *const ::_clockadjust, + __old: *mut ::_clockadjust, + ) -> ::c_int; + pub fn ClockAdjust_r( + __id: ::clockid_t, + _new: *const ::_clockadjust, + __old: *mut ::_clockadjust, + ) -> ::c_int; + pub fn ClockPeriod( + __id: ::clockid_t, + _new: *const ::_clockperiod, + __old: *mut ::_clockperiod, + __reserved: ::c_int, + ) -> ::c_int; + pub fn ClockPeriod_r( + __id: ::clockid_t, + _new: *const ::_clockperiod, + __old: *mut ::_clockperiod, + __reserved: ::c_int, + ) -> ::c_int; + pub fn ClockId(__pid: ::pid_t, __tid: ::c_int) -> ::c_int; + pub fn ClockId_r(__pid: ::pid_t, __tid: ::c_int) -> ::c_int; + + // + //TODO: The following commented out functions are implemented in assembly. + // We can implmement them either via a C stub or rust's inline assembly. + // + //pub fn InterruptEnable(); + //pub fn InterruptDisable(); + pub fn InterruptMask(__intr: ::c_int, __id: ::c_int) -> ::c_int; + pub fn InterruptUnmask(__intr: ::c_int, __id: ::c_int) -> ::c_int; + //pub fn InterruptLock(__spin: *mut ::intrspin); + //pub fn InterruptUnlock(__spin: *mut ::intrspin); + //pub fn InterruptStatus() -> ::c_uint; +} diff --git a/bash-5.1/vendor/libc/src/unix/nto/x86_64.rs b/bash-5.1/vendor/libc/src/unix/nto/x86_64.rs new file mode 100644 index 0000000..3a1d230 --- /dev/null +++ b/bash-5.1/vendor/libc/src/unix/nto/x86_64.rs @@ -0,0 +1,132 @@ +pub type c_char = i8; +pub type wchar_t = u32; +pub type c_long = i64; +pub type c_ulong = u64; +pub type time_t = i64; + +s! { + #[repr(align(8))] + pub struct x86_64_cpu_registers { + pub rdi: u64, + pub rsi: u64, + pub rdx: u64, + pub r10: u64, + pub r8: u64, + pub r9: u64, + pub rax: u64, + pub rbx: u64, + pub rbp: u64, + pub rcx: u64, + pub r11: u64, + pub r12: u64, + pub r13: u64, + pub r14: u64, + pub r15: u64, + pub rip: u64, + pub cs: u32, + rsvd1: u32, + pub rflags: u64, + pub rsp: u64, + pub ss: u32, + rsvd2: u32, + } + + #[repr(align(8))] + pub struct mcontext_t { + pub cpu: x86_64_cpu_registers, + #[cfg(libc_union)] + pub fpu: x86_64_fpu_registers, + #[cfg(not(libc_union))] + __reserved: [u8; 1024], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct fsave_area_64 { + pub fpu_control_word: u32, + pub fpu_status_word: u32, + pub fpu_tag_word: u32, + pub fpu_ip: u32, + pub fpu_cs: u32, + pub fpu_op: u32, + pub fpu_ds: u32, + pub st_regs: [u8; 80], + } + + pub struct fxsave_area_64 { + pub fpu_control_word: u16, + pub fpu_status_word: u16, + pub fpu_tag_word: u16, + pub fpu_operand: u16, + pub fpu_rip: u64, + pub fpu_rdp: u64, + pub mxcsr: u32, + pub mxcsr_mask: u32, + pub st_regs: [u8; 128], + pub xmm_regs: [u8; 128], + reserved2: [u8; 224], + } + + pub struct fpu_extention_savearea_64 { + pub other: [u8; 512], + pub xstate_bv: u64, + pub xstate_undef: [u64; 7], + pub xstate_info: [u8; 224], + } +} + +s_no_extra_traits! { + #[cfg(libc_union)] + pub union x86_64_fpu_registers { + pub fsave_area: fsave_area_64, + pub fxsave_area: fxsave_area_64, + pub xsave_area: fpu_extention_savearea_64, + pub data: [u8; 1024], + } +} + +cfg_if! { + if #[cfg(feature = "extra_traits")] { + #[cfg(libc_union)] + impl Eq for x86_64_fpu_registers {} + + #[cfg(libc_union)] + impl PartialEq for x86_64_fpu_registers { + fn eq(&self, other: &x86_64_fpu_registers) -> bool { + unsafe { + self.fsave_area == other.fsave_area + || self.fxsave_area == other.fxsave_area + || self.xsave_area == other.xsave_area + } + } + } + + #[cfg(libc_union)] + impl ::fmt::Debug for x86_64_fpu_registers { + fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { + unsafe { + f.debug_struct("x86_64_fpu_registers") + .field("fsave_area", &self.fsave_area) + .field("fxsave_area", &self.fxsave_area) + .field("xsave_area", &self.xsave_area) + .finish() + } + } + } + + #[cfg(libc_union)] + impl ::hash::Hash for x86_64_fpu_registers { + fn hash(&self, state: &mut H) { + unsafe { + self.fsave_area.hash(state); + self.fxsave_area.hash(state); + self.xsave_area.hash(state); + } + } + } + } +} diff --git a/bash-5.1/vendor/libc/src/unix/solarish/illumos.rs b/bash-5.1/vendor/libc/src/unix/solarish/illumos.rs index c86c6d6..7d491d3 100644 --- a/bash-5.1/vendor/libc/src/unix/solarish/illumos.rs +++ b/bash-5.1/vendor/libc/src/unix/solarish/illumos.rs @@ -42,6 +42,9 @@ pub const F_OFD_SETLKW: ::c_int = 49; pub const F_FLOCK: ::c_int = 53; pub const F_FLOCKW: ::c_int = 54; +pub const F_DUPFD_CLOEXEC: ::c_int = 37; +pub const F_DUP2FD_CLOEXEC: ::c_int = 36; + pub const FIL_ATTACH: ::c_int = 0x1; pub const FIL_DETACH: ::c_int = 0x2; pub const FIL_LIST: ::c_int = 0x3; @@ -51,6 +54,8 @@ pub const FILF_AUTO: ::c_int = 0x2; pub const FILF_BYPASS: ::c_int = 0x4; pub const SOL_FILTER: ::c_int = 0xfffc; +pub const MADV_PURGE: ::c_int = 9; + pub const MR_HDR_AOUT: ::c_uint = 0x3; pub const B1000000: ::speed_t = 24; diff --git a/bash-5.1/vendor/libc/src/unix/solarish/mod.rs b/bash-5.1/vendor/libc/src/unix/solarish/mod.rs index 3ccdb8c..c5da62b 100644 --- a/bash-5.1/vendor/libc/src/unix/solarish/mod.rs +++ b/bash-5.1/vendor/libc/src/unix/solarish/mod.rs @@ -1327,7 +1327,6 @@ pub const F_LOCK: ::c_int = 1; pub const F_TEST: ::c_int = 3; pub const F_TLOCK: ::c_int = 2; pub const F_ULOCK: ::c_int = 0; -pub const F_DUPFD_CLOEXEC: ::c_int = 37; pub const F_SETLK: ::c_int = 6; pub const F_SETLKW: ::c_int = 7; pub const F_GETLK: ::c_int = 14; @@ -1441,6 +1440,7 @@ pub const MAP_RENAME: ::c_int = 0x20; pub const MAP_ALIGN: ::c_int = 0x200; pub const MAP_TEXT: ::c_int = 0x400; pub const MAP_INITDATA: ::c_int = 0x800; +pub const MAP_32BIT: ::c_int = 0x80; pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; pub const MCL_CURRENT: ::c_int = 0x0001; @@ -1601,7 +1601,6 @@ pub const NI_NUMERICSCOPE: ::c_uint = 0x0040; pub const F_DUPFD: ::c_int = 0; pub const F_DUP2FD: ::c_int = 9; -pub const F_DUP2FD_CLOEXEC: ::c_int = 36; pub const F_GETFD: ::c_int = 1; pub const F_SETFD: ::c_int = 2; pub const F_GETFL: ::c_int = 3; @@ -1685,6 +1684,9 @@ pub const MADV_SEQUENTIAL: ::c_int = 2; pub const MADV_WILLNEED: ::c_int = 3; pub const MADV_DONTNEED: ::c_int = 4; pub const MADV_FREE: ::c_int = 5; +pub const MADV_ACCESS_DEFAULT: ::c_int = 6; +pub const MADV_ACCESS_LWP: ::c_int = 7; +pub const MADV_ACCESS_MANY: ::c_int = 8; pub const AF_UNSPEC: ::c_int = 0; pub const AF_UNIX: ::c_int = 1; @@ -1796,6 +1798,8 @@ pub const TCP_LINGER2: ::c_int = 0x1c; pub const UDP_NAT_T_ENDPOINT: ::c_int = 0x0103; +pub const SOMAXCONN: ::c_int = 128; + pub const SOL_SOCKET: ::c_int = 0xffff; pub const SO_DEBUG: ::c_int = 0x01; pub const SO_ACCEPTCONN: ::c_int = 0x0002; @@ -1892,6 +1896,14 @@ pub const IPC_RMID: ::c_int = 10; pub const IPC_SET: ::c_int = 11; pub const IPC_SEAT: ::c_int = 12; +// sys/shm.h +pub const SHM_R: ::c_int = 0o400; +pub const SHM_W: ::c_int = 0o200; +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_SHARE_MMU: ::c_int = 0o40000; +pub const SHM_PAGEABLE: ::c_int = 0o100000; + pub const SHUT_RD: ::c_int = 0; pub const SHUT_WR: ::c_int = 1; pub const SHUT_RDWR: ::c_int = 2; @@ -3133,6 +3145,8 @@ extern "C" { pub fn setpflags(flags: ::c_uint, value: ::c_uint) -> ::c_int; pub fn sysinfo(command: ::c_int, buf: *mut ::c_char, count: ::c_long) -> ::c_int; + + pub fn faccessat(fd: ::c_int, path: *const ::c_char, amode: ::c_int, flag: ::c_int) -> ::c_int; } #[link(name = "sendfile")] diff --git a/bash-5.1/vendor/libc/src/unix/solarish/solaris.rs b/bash-5.1/vendor/libc/src/unix/solarish/solaris.rs index 8ea070c..3fb1660 100644 --- a/bash-5.1/vendor/libc/src/unix/solarish/solaris.rs +++ b/bash-5.1/vendor/libc/src/unix/solarish/solaris.rs @@ -33,8 +33,13 @@ pub const AF_LOCAL: ::c_int = 0; pub const AF_FILE: ::c_int = 0; pub const TCP_KEEPIDLE: ::c_int = 0x1d; -pub const TCP_KEEPCNT: ::c_int = 0x1e; -pub const TCP_KEEPINTVL: ::c_int = 0x1f; +pub const TCP_KEEPINTVL: ::c_int = 0x1e; +pub const TCP_KEEPCNT: ::c_int = 0x1f; + +pub const F_DUPFD_CLOEXEC: ::c_int = 47; +pub const F_DUPFD_CLOFORK: ::c_int = 49; +pub const F_DUP2FD_CLOEXEC: ::c_int = 48; +pub const F_DUP2FD_CLOFORK: ::c_int = 50; extern "C" { pub fn fexecve( @@ -67,6 +72,8 @@ extern "C" { pub fn fattach(fildes: ::c_int, path: *const ::c_char) -> ::c_int; pub fn pthread_getattr_np(thread: ::pthread_t, attr: *mut ::pthread_attr_t) -> ::c_int; + + pub fn euidaccess(path: *const ::c_char, amode: ::c_int) -> ::c_int; } s_no_extra_traits! { diff --git a/bash-5.1/vendor/libc/src/unix/solarish/x86_64.rs b/bash-5.1/vendor/libc/src/unix/solarish/x86_64.rs index 5f75bdb..bca552f 100644 --- a/bash-5.1/vendor/libc/src/unix/solarish/x86_64.rs +++ b/bash-5.1/vendor/libc/src/unix/solarish/x86_64.rs @@ -157,3 +157,34 @@ cfg_if! { } } + +// sys/regset.h + +pub const REG_GSBASE: ::c_int = 27; +pub const REG_FSBASE: ::c_int = 26; +pub const REG_DS: ::c_int = 25; +pub const REG_ES: ::c_int = 24; +pub const REG_GS: ::c_int = 23; +pub const REG_FS: ::c_int = 22; +pub const REG_SS: ::c_int = 21; +pub const REG_RSP: ::c_int = 20; +pub const REG_RFL: ::c_int = 19; +pub const REG_CS: ::c_int = 18; +pub const REG_RIP: ::c_int = 17; +pub const REG_ERR: ::c_int = 16; +pub const REG_TRAPNO: ::c_int = 15; +pub const REG_RAX: ::c_int = 14; +pub const REG_RCX: ::c_int = 13; +pub const REG_RDX: ::c_int = 12; +pub const REG_RBX: ::c_int = 11; +pub const REG_RBP: ::c_int = 10; +pub const REG_RSI: ::c_int = 9; +pub const REG_RDI: ::c_int = 8; +pub const REG_R8: ::c_int = 7; +pub const REG_R9: ::c_int = 6; +pub const REG_R10: ::c_int = 5; +pub const REG_R11: ::c_int = 4; +pub const REG_R12: ::c_int = 3; +pub const REG_R13: ::c_int = 2; +pub const REG_R14: ::c_int = 1; +pub const REG_R15: ::c_int = 0; diff --git a/bash-5.1/vendor/libc/src/windows/mod.rs b/bash-5.1/vendor/libc/src/windows/mod.rs index 08cba4e..acb0de9 100644 --- a/bash-5.1/vendor/libc/src/windows/mod.rs +++ b/bash-5.1/vendor/libc/src/windows/mod.rs @@ -277,6 +277,16 @@ impl ::Clone for fpos_t { } } +// Special handling for all print and scan type functions because of https://github.com/rust-lang/libc/issues/2860 +#[cfg_attr( + all(windows, target_env = "msvc"), + link(name = "legacy_stdio_definitions") +)] +extern "C" { + pub fn printf(format: *const c_char, ...) -> ::c_int; + pub fn fprintf(stream: *mut FILE, format: *const c_char, ...) -> ::c_int; +} + extern "C" { pub fn isalnum(c: c_int) -> c_int; pub fn isalpha(c: c_int) -> c_int; @@ -319,8 +329,6 @@ extern "C" { pub fn feof(stream: *mut FILE) -> c_int; pub fn ferror(stream: *mut FILE) -> c_int; pub fn perror(s: *const c_char); - pub fn printf(format: *const c_char, ...) -> ::c_int; - pub fn fprintf(stream: *mut FILE, format: *const c_char, ...) -> ::c_int; pub fn atoi(s: *const c_char) -> c_int; pub fn strtod(s: *const c_char, endp: *mut *mut c_char) -> c_double; pub fn strtof(s: *const c_char, endp: *mut *mut c_char) -> c_float; diff --git a/bash-5.1/vendor/libc/src/xous.rs b/bash-5.1/vendor/libc/src/xous.rs new file mode 100644 index 0000000..e6c0c25 --- /dev/null +++ b/bash-5.1/vendor/libc/src/xous.rs @@ -0,0 +1,49 @@ +//! Xous C type definitions + +pub type c_schar = i8; +pub type c_uchar = u8; +pub type c_short = i16; +pub type c_ushort = u16; +pub type c_int = i32; +pub type c_uint = u32; +pub type c_float = f32; +pub type c_double = f64; +pub type c_longlong = i64; +pub type c_ulonglong = u64; +pub type intmax_t = i64; +pub type uintmax_t = u64; + +pub type size_t = usize; +pub type ptrdiff_t = isize; +pub type intptr_t = isize; +pub type uintptr_t = usize; +pub type ssize_t = isize; + +pub type off_t = i64; +pub type c_char = u8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type wchar_t = u32; + +pub const INT_MIN: c_int = -2147483648; +pub const INT_MAX: c_int = 2147483647; + +cfg_if! { + if #[cfg(libc_core_cvoid)] { + pub use ::ffi::c_void; + } else { + // Use repr(u8) as LLVM expects `void*` to be the same as `i8*` to help + // enable more optimization opportunities around it recognizing things + // like malloc/free. + #[repr(u8)] + #[allow(missing_copy_implementations)] + #[allow(missing_debug_implementations)] + pub enum c_void { + // Two dummy variants so the #[repr] attribute can be used. + #[doc(hidden)] + __variant1, + #[doc(hidden)] + __variant2, + } + } +} diff --git a/bash-5.1/vendor/libloading-0.3.4/.cargo-checksum.json b/bash-5.1/vendor/libloading-0.3.4/.cargo-checksum.json new file mode 100644 index 0000000..503348d --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"ff43cba1df2dc69b12847f470e1a4147ce65427a4140724fa384b11161b00dde","LICENSE":"b29f8b01452350c20dd1af16ef83b598fea3053578ccc1c7a0ef40e57be2620f","README.mkd":"34dc610b01f8c3e56d95de1972120ca0d53cee787f636a3ce96526ab343878b5","appveyor.yml":"4c00a8503d3491de985927f703e50fd6893bea106d95e22db68470adf3fb5aee","build.rs":"f4135eaa51256562982eda2f76aceac7a0a08f77c6c24505b2134fa3b55dfb28","src/changelog.rs":"9f2b3a2c870f7e067a6681b8d2ea0895b220564c830ed05ed1cf0695ca7b6112","src/lib.rs":"665c5eeecdf77afc0dbe7de4232b2d5f5da5e19a5fd851ac433c89d600b801ee","src/os/mod.rs":"51d733e5522dacd6069642ad66aa6d7acf6c82950c934eb040e8dfd112e6d610","src/os/unix/mod.rs":"1cd2b6f51a34e492b7c88d054f25d89b825037bd81e62a2950ca13720e760061","src/os/windows/mod.rs":"2ed3564e9b88a601cd93b13affb286af7beee165b710279d55c953c74b783310","src/test_helpers.rs":"3a55052e8cd5231e97d9282b43398c2f144c57ced2d2df64bde7f482f5c778e7","src/util.rs":"0b0155448a26db4b00b2a6ca129e0e1f6f75870c56c9777d262941818c7581b7","tests/functions.rs":"dbed3ad32d6a31c8c0df5943f686ca328f020c5d49a9111281458971caa40e62","tests/markers.rs":"8e9c1b883404d9190e4f23ed39b3d6cbbccb3a07883f733b04aed4357b9c6aca","tests/nagisa32.dll":"5c69b2bd9c8a6ad04165c221075fc9fade1dd66ca697399ace528a5a62328e36","tests/nagisa64.dll":"e20b95e3036f3289421abd100760874d4f455afd33c3b5b64fec56b191f7d477","tests/statics.rs":"8fd0955d38cdf3d56d1ece03ad159192702dbc049aa1af146f28fb10f1cf2fcc","tests/windows.rs":"7711dfe19062d91356cd127546542b1b6e13aeef76ad3098f32c8a6ae319b66a"},"package":"0a020ac941774eb37e9d13d418c37b522e76899bfc4e7b1a600d529a53f83a66"} \ No newline at end of file diff --git a/bash-5.1/vendor/libloading-0.3.4/Cargo.toml b/bash-5.1/vendor/libloading-0.3.4/Cargo.toml new file mode 100644 index 0000000..e4a6af9 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "libloading" +version = "0.3.4" +authors = ["Simonas Kazlauskas "] +build = "build.rs" +description = "A safer binding to platform’s dynamic library loading utilities" +keywords = ["dlopen", "load", "shared", "dylib"] +license = "ISC" +repository = "https://github.com/nagisa/rust_libloading/" +documentation = "https://docs.rs/libloading/" + +[dependencies] +lazy_static = "0.2" + +[target.'cfg(windows)'.dependencies] +winapi = "0.2" +kernel32-sys = "0.2" + +[build-dependencies] +target_build_utils = "0.3" diff --git a/bash-5.1/vendor/libloading-0.3.4/LICENSE b/bash-5.1/vendor/libloading-0.3.4/LICENSE new file mode 100644 index 0000000..9137d56 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/LICENSE @@ -0,0 +1,12 @@ +Copyright © 2015, Simonas Kazlauskas + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without +fee is hereby granted, provided that the above copyright notice and this permission notice appear +in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/bash-5.1/vendor/libloading-0.3.4/README.mkd b/bash-5.1/vendor/libloading-0.3.4/README.mkd new file mode 100644 index 0000000..58f4ad5 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/README.mkd @@ -0,0 +1,27 @@ +# libloading [![Travis CI][tcii]][tci] [![Appveyor CI][acii]][aci] + +[tcii]: https://travis-ci.org/nagisa/rust_libloading.svg?branch=master +[tci]: https://travis-ci.org/nagisa/rust_libloading +[acii]: https://ci.appveyor.com/api/projects/status/cnncnu58qcxb1ikf/branch/master?svg=true +[aci]: https://ci.appveyor.com/project/nagisa/rust-libloading + +A memory-safer wrapper around system dynamic library loading primitives. The most important safety +guarantee by this library is prevention of dangling-`Symbol`s that may occur after a `Library` is +unloaded. + +Using this library allows loading dynamic libraries (also known as shared libraries) as well as use +functions and static variables these libraries contain. + +* [Documentation][docs] +* [Changelog][changelog] + +[docs]: https://docs.rs/libloading/ +[changelog]: https://docs.rs/libloading/*/libloading/changelog/index.html + +libloading is distributed under ISC (MIT-like) license. + +--- + +Note, that this library is not a drop-in replacement for the deprecated `dynamic_lib`. Many +dubious APIs (notably, library search path modification) were prunned and string arguments +take types that match conventions and system APIs better. diff --git a/bash-5.1/vendor/libloading-0.3.4/appveyor.yml b/bash-5.1/vendor/libloading-0.3.4/appveyor.yml new file mode 100644 index 0000000..4390f53 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/appveyor.yml @@ -0,0 +1,19 @@ +environment: + matrix: + - TARGET: nightly-x86_64-pc-windows-msvc + - TARGET: nightly-i686-pc-windows-msvc + - TARGET: nightly-x86_64-pc-windows-gnu + - TARGET: nightly-i686-pc-windows-gnu + - TARGET: 1.12.0-x86_64-pc-windows-msvc + - TARGET: 1.12.0-i686-pc-windows-msvc + - TARGET: 1.12.0-x86_64-pc-windows-gnu + - TARGET: 1.12.0-i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust.exe" + - ps: .\rust.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null + - ps: $env:PATH="$env:PATH;C:\rust\bin" + - rustc -vV + - cargo -vV +build: off +test_script: + - cargo test diff --git a/bash-5.1/vendor/libloading-0.3.4/build.rs b/bash-5.1/vendor/libloading-0.3.4/build.rs new file mode 100644 index 0000000..7657a82 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/build.rs @@ -0,0 +1,47 @@ +extern crate target_build_utils; +use target_build_utils::TargetInfo; +use std::io::Write; +use std::env; + +fn main(){ + let target = TargetInfo::new().expect("could not get target info"); + match target.target_os() { + "linux" | "android" => println!("cargo:rustc-link-lib=dl"), + "freebsd" | "dragonfly" => println!("cargo:rustc-link-lib=c"), + // netbsd claims dl* will be available to any dynamically linked binary, but I haven’t + // found any libraries that have to be linked to on other platforms. + // What happens if the executable is not linked up dynamically? + "openbsd" | "bitrig" | "netbsd" | "macos" | "ios" => {} + // dependencies come with winapi + "windows" => {} + tos => { + writeln!(::std::io::stderr(), + "Building for an unknown target_os=`{}`!\nPlease report an issue ", + tos).expect("could not report the error"); + ::std::process::exit(0xfc); + } + } + maybe_test_helpers(); +} + +fn maybe_test_helpers() { + if env::var("OPT_LEVEL").ok().and_then(|v| v.parse().ok()).unwrap_or(0u64) != 0 { + // certainly not for testing, just skip. + return; + } + let mut outpath = if let Some(od) = env::var_os("OUT_DIR") { od } else { return }; + let target = if let Some(t) = env::var_os("TARGET") { t } else { return }; + let rustc = env::var_os("RUSTC").unwrap_or_else(|| { "rustc".into() }); + outpath.push("/libtest_helpers.dll"); // extension for windows required, POSIX does not care. + let _ = ::std::process::Command::new(rustc) + .arg("src/test_helpers.rs") + .arg("-o") + .arg(outpath) + .arg("-O") + .arg("--target") + .arg(target) + .output(); + // Ignore the failures here. We do not want failures of this thing to inhibit people from + // building and using the library. Might make it hard to debug why tests fail in case this + // library does not get built, though. +} diff --git a/bash-5.1/vendor/libloading-0.3.4/src/changelog.rs b/bash-5.1/vendor/libloading-0.3.4/src/changelog.rs new file mode 100644 index 0000000..7094f7c --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/changelog.rs @@ -0,0 +1,51 @@ +//! Project changelog + +/// Release 0.3.4 (2017-03-25) +/// +/// * Remove rogue println! +pub mod r0_3_4 {} + +/// Release 0.3.3 (2017-03-25) +/// +/// * Panics when `Library::get` is called for incompatibly sized type such as named function +/// types (which are zero-sized). +pub mod r0_3_3 {} + +/// Release 0.3.2 (2017-02-10) +/// +/// * Minimum version required is now rustc 1.12.0; +/// * Updated dependency versions (most notably target_build_utils to 0.3.0) +pub mod r0_3_2 {} + +/// Release 0.3.1 (2016-10-01) +/// +/// * `Symbol` and `os::*::Symbol` now implement `Send` where `T: Send`; +/// * `Symbol` and `os::*::Symbol` now implement `Sync` where `T: Sync`; +/// * `Library` and `os::*::Library` now implement `Sync` (they were `Send` in 0.3.0 already). +pub mod r0_3_1 {} + +/// Release 0.3.0 (2016-07-27) +/// +/// * Greatly improved documentation, especially around platform-specific behaviours; +/// * Improved test suite by building our own library to test against; +/// * All `Library`-ies now implement `Send`. +/// * Added `impl From for Library` and `impl From for +/// os::platform::Library` allowing wrapping and extracting the platform-specific library handle; +/// * Added methods to wrap (`Symbol::from_raw`) and unwrap (`Symbol::into_raw`) the safe `Symbol` +/// wrapper into unsafe `os::platform::Symbol`. +/// +/// The last two additions focus on not restricting potential usecases of this library, allowing +/// users of the library to circumvent safety checks if need be. +/// +/// ## Beaking Changes +/// +/// `Library::new` defaults to `RTLD_NOW` instead of `RTLD_LAZY` on UNIX for more consistent +/// cross-platform behaviour. If a library loaded with `Library::new` had any linking errors, but +/// unresolved references weren’t forced to be resolved, the library would’ve “just worked”, +/// whereas now the call to `Library::new` will return an error signifying presence of such error. +/// +/// ## os::platform +/// * Added `os::unix::Library::open` which allows specifying arbitrary flags (e.g. `RTLD_LAZY`); +/// * Added `os::windows::Library::get_ordinal` which allows finding a function or variable by its +/// ordinal number; +pub mod r0_3_0 {} diff --git a/bash-5.1/vendor/libloading-0.3.4/src/lib.rs b/bash-5.1/vendor/libloading-0.3.4/src/lib.rs new file mode 100644 index 0000000..8195558 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/lib.rs @@ -0,0 +1,281 @@ +//! A memory-safer wrapper around system dynamic library loading primitives. +//! +//! Using this library allows loading [dynamic libraries](struct.Library.html) (also known as +//! shared libraries) as well as use functions and static variables these libraries contain. +//! +//! While the library does expose a cross-platform interface to load a library and find stuff +//! inside it, little is done to paper over the platform differences, especially where library +//! loading is involved. The documentation for each function will attempt to document such +//! differences on the best-effort basis. +//! +//! Less safe, platform specific bindings are also available. See the +//! [`os::platform`](os/index.html) module for details. +//! +//! # Usage +//! +//! Add dependency to this library to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! libloading = "0.3" +//! ``` +//! +//! Then inside your project +//! +//! ```no_run +//! extern crate libloading as lib; +//! +//! fn call_dynamic() -> lib::Result { +//! let lib = try!(lib::Library::new("/path/to/liblibrary.so")); +//! unsafe { +//! let func: lib::Symbol u32> = try!(lib.get(b"my_func")); +//! Ok(func()) +//! } +//! } +//! ``` +//! +//! The compiler will ensure that the loaded `function` will not outlive the `Library` it comes +//! from, preventing a common cause of undefined behaviour and memory safety problems. +use std::ffi::OsStr; +use std::fmt; +use std::ops; +use std::marker; + +#[cfg(unix)] +#[macro_use] +extern crate lazy_static; + +#[cfg(unix)] +use self::os::unix as imp; +#[cfg(windows)] +use self::os::windows as imp; + +pub mod os; +pub mod changelog; +mod util; + +pub type Result = ::std::io::Result; + +/// A loaded dynamic library. +pub struct Library(imp::Library); + +impl Library { + /// Find and load a dynamic library. + /// + /// The `filename` argument may be any of: + /// + /// * A library filename; + /// * Absolute path to the library; + /// * Relative (to the current working directory) path to the library. + /// + /// ## Platform-specific behaviour + /// + /// When a plain library filename is supplied, locations where library is searched for is + /// platform specific and cannot be adjusted in a portable manner. + /// + /// Calling this function from multiple threads is not safe if used in conjunction with + /// path-less filename and library search path is modified (`SetDllDirectory` function on + /// Windows, `{DY,}LD_LIBRARY_PATH` environment variable on UNIX). + /// + /// ### Windows + /// + /// If the `filename` specifies a library filename without path and with extension omitted, + /// `.dll` extension is implicitly added. This behaviour may be suppressed by appending a + /// trailing `.` to the `filename`. + /// + /// If the library contains thread local variables (MSVC’s `_declspec(thread)`, Rust’s + /// `#[thread_local]` attributes), loading the library will fail on versions prior to Windows + /// Vista. + /// + /// ## Tips + /// + /// Distributing your dynamic libraries under a filename common to all platforms (e.g. + /// `awesome.module`) allows to avoid code which has to account for platform’s conventional + /// library filenames. + /// + /// Strive to specify absolute or relative path to your library, unless system-wide libraries + /// are being loaded. Platform-dependent library search locations combined with various quirks + /// related to path-less filenames may cause flaky code. + /// + /// ## Examples + /// + /// ```no_run + /// # use ::libloading::Library; + /// // Any of the following are valid. + /// let _ = Library::new("/path/to/awesome.module").unwrap(); + /// let _ = Library::new("../awesome.module").unwrap(); + /// let _ = Library::new("libsomelib.so.1").unwrap(); + /// ``` + pub fn new>(filename: P) -> Result { + imp::Library::new(filename).map(From::from) + } + + /// Get a pointer to function or static variable by symbol name. + /// + /// The `symbol` may not contain any null bytes, with an exception of last byte. A null + /// terminated `symbol` may avoid a string allocation in some cases. + /// + /// Symbol is interpreted as-is; no mangling is done. This means that symbols like `x::y` are + /// most likely invalid. + /// + /// ## Unsafety + /// + /// Pointer to a value of arbitrary type is returned. Using a value with wrong type is + /// undefined. + /// + /// ## Platform-specific behaviour + /// + /// On Linux and Windows, a TLS variable acts just like any regular static variable. OS X uses + /// some sort of lazy initialization scheme, which makes loading TLS variables this way + /// impossible. Using a TLS variable loaded this way on OS X is undefined behaviour. + /// + /// ## Examples + /// + /// Given a loaded library: + /// + /// ```no_run + /// # use ::libloading::Library; + /// let lib = Library::new("/path/to/awesome.module").unwrap(); + /// ``` + /// + /// Loading and using a function looks like this: + /// + /// ```no_run + /// # use ::libloading::{Library, Symbol}; + /// # let lib = Library::new("/path/to/awesome.module").unwrap(); + /// unsafe { + /// let awesome_function: Symbol f64> = + /// lib.get(b"awesome_function\0").unwrap(); + /// awesome_function(0.42); + /// } + /// ``` + /// + /// A static variable may also be loaded and inspected: + /// + /// ```no_run + /// # use ::libloading::{Library, Symbol}; + /// # let lib = Library::new("/path/to/awesome.module").unwrap(); + /// unsafe { + /// let awesome_variable: Symbol<*mut f64> = lib.get(b"awesome_variable\0").unwrap(); + /// **awesome_variable = 42.0; + /// }; + /// ``` + pub unsafe fn get<'lib, T>(&'lib self, symbol: &[u8]) -> Result> { + self.0.get(symbol).map(|from| Symbol::from_raw(from, self)) + } +} + +impl fmt::Debug for Library { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +impl From for Library { + fn from(lib: imp::Library) -> Library { + Library(lib) + } +} + +impl From for imp::Library { + fn from(lib: Library) -> imp::Library { + lib.0 + } +} + +unsafe impl Send for Library {} +unsafe impl Sync for Library {} + +/// Symbol from a library. +/// +/// This type is a safeguard against using dynamically loaded symbols after a `Library` is +/// unloaded. Primary method to create an instance of a `Symbol` is via `Library::get`. +/// +/// Due to implementation of the `Deref` trait, an instance of `Symbol` may be used as if it was a +/// function or variable directly, without taking care to “extract” function or variable manually +/// most of the time. +/// +/// See [`Library::get`] for details. +/// +/// [`Library::get`]: ./struct.Library.html#method.get +pub struct Symbol<'lib, T: 'lib> { + inner: imp::Symbol, + pd: marker::PhantomData<&'lib T> +} + +impl<'lib, T> Symbol<'lib, T> { + /// Extract the wrapped `os::platform::Symbol`. + /// + /// ## Unsafety + /// Using this function relinquishes all the lifetime guarantees. It is up to programmer to + /// ensure the resulting `Symbol` is not used past the lifetime of the `Library` this symbol + /// was loaded from. + /// + /// ## Examples + /// + /// ```no_run + /// # use ::libloading::{Library, Symbol}; + /// let lib = Library::new("/path/to/awesome.module").unwrap(); + /// unsafe { + /// let symbol: Symbol<*mut u32> = lib.get(b"symbol\0").unwrap(); + /// let symbol = symbol.into_raw(); + /// } + /// ``` + pub unsafe fn into_raw(self) -> imp::Symbol { + self.inner + } + + /// Wrap the `os::platform::Symbol` into this safe wrapper. + /// + /// Note that, in order to create association between the symbol and the library this symbol + /// came from, this function requires reference to the library provided. + /// + /// ## Unsafety + /// + /// It is invalid to provide a reference to any other value other than the library the `sym` + /// was loaded from. Doing so invalidates any lifetime guarantees. + /// + /// ## Examples + /// + /// ```no_run + /// # use ::libloading::{Library, Symbol}; + /// let lib = Library::new("/path/to/awesome.module").unwrap(); + /// unsafe { + /// let symbol: Symbol<*mut u32> = lib.get(b"symbol\0").unwrap(); + /// let symbol = symbol.into_raw(); + /// let symbol = Symbol::from_raw(symbol, &lib); + /// } + /// ``` + pub unsafe fn from_raw(sym: imp::Symbol, _: &'lib L) -> Symbol<'lib, T> { + Symbol { + inner: sym, + pd: marker::PhantomData + } + } +} + +impl<'lib, T> Clone for Symbol<'lib, T> { + fn clone(&self) -> Symbol<'lib, T> { + Symbol { + inner: self.inner.clone(), + pd: marker::PhantomData + } + } +} + +// FIXME: implement FnOnce for callable stuff instead. +impl<'lib, T> ops::Deref for Symbol<'lib, T> { + type Target = T; + fn deref(&self) -> &T { + ops::Deref::deref(&self.inner) + } +} + +impl<'lib, T> fmt::Debug for Symbol<'lib, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +unsafe impl<'lib, T: Send> Send for Symbol<'lib, T> {} +unsafe impl<'lib, T: Sync> Sync for Symbol<'lib, T> {} diff --git a/bash-5.1/vendor/libloading-0.3.4/src/os/mod.rs b/bash-5.1/vendor/libloading-0.3.4/src/os/mod.rs new file mode 100644 index 0000000..ccbc8e9 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/os/mod.rs @@ -0,0 +1,45 @@ +//! Unsafe, platform specific bindings to dynamic library loading facilities. +//! +//! These modules expose more extensive, powerful, less principled bindings to the dynamic +//! library loading facilities. Use of these bindings come at the cost of less (in most cases, +//! none at all) safety guarantees, which are provided by the top-level bindings. +//! +//! # Examples +//! +//! Using these modules will likely involve conditional compilation: +//! +//! ```ignore +//! # extern crate libloading; +//! #[cfg(unix)] +//! use libloading::os::unix::*; +//! #[cfg(windows)] +//! use libloading::os::windows::*; +//! ``` + +macro_rules! unix { + ($item: item) => { + /// UNIX implementation of dynamic library loading. + /// + /// This module should be expanded with more UNIX-specific functionality in the future. + $item + } +} + +macro_rules! windows { + ($item: item) => { + /// Windows implementation of dynamic library loading. + /// + /// This module should be expanded with more Windows-specific functionality in the future. + $item + } +} + +#[cfg(unix)] +unix!(pub mod unix;); +#[cfg(unix)] +windows!(pub mod windows {}); + +#[cfg(windows)] +windows!(pub mod windows;); +#[cfg(windows)] +unix!(pub mod unix {}); diff --git a/bash-5.1/vendor/libloading-0.3.4/src/os/unix/mod.rs b/bash-5.1/vendor/libloading-0.3.4/src/os/unix/mod.rs new file mode 100644 index 0000000..0b6cae1 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/os/unix/mod.rs @@ -0,0 +1,271 @@ +use util::{ensure_compatible_types, cstr_cow_from_bytes}; + +use std::ffi::{CStr, OsStr}; +use std::{fmt, io, marker, mem, ptr}; +use std::os::raw; +use std::os::unix::ffi::OsStrExt; +use std::sync::Mutex; + +lazy_static! { + static ref DLERROR_MUTEX: Mutex<()> = Mutex::new(()); +} + +// libdl is crazy. +// +// First of all, whole error handling scheme in libdl is done via setting and querying some global +// state, therefore it is not safe to use libdl in MT-capable environment at all. Only in POSIX +// 2008+TC1 a thread-local state was allowed, which for our purposes is way too late. +fn with_dlerror(closure: F) -> Result> +where F: FnOnce() -> Option { + // We will guard all uses of libdl library with our own mutex. This makes libdl + // safe to use in MT programs provided the only way a program uses libdl is via this library. + let _lock = DLERROR_MUTEX.lock(); + // While we could could call libdl here to clear the previous error value, only the dlsym + // depends on it being cleared beforehand and only in some cases too. We will instead clear the + // error inside the dlsym binding instead. + // + // In all the other cases, clearing the error here will only be hiding misuse of these bindings + // or the libdl. + closure().ok_or_else(|| unsafe { + // This code will only get executed if the `closure` returns `None`. + let error = dlerror(); + if error.is_null() { + // In non-dlsym case this may happen when there’s bugs in our bindings or there’s + // non-libloading user of libdl; possibly in another thread. + None + } else { + // You can’t even rely on error string being static here; call to subsequent dlerror + // may invalidate or overwrite the error message. Why couldn’t they simply give up the + // ownership over the message? + // TODO: should do locale-aware conversion here. OTOH Rust doesn’t seem to work well in + // any system that uses non-utf8 locale, so I doubt there’s a problem here. + let message = CStr::from_ptr(error).to_string_lossy().into_owned(); + Some(io::Error::new(io::ErrorKind::Other, message)) + // Since we do a copy of the error string above, maybe we should call dlerror again to + // let libdl know it may free its copy of the string now? + } + }) +} + +/// A platform-specific equivalent of the cross-platform `Library`. +pub struct Library { + handle: *mut raw::c_void +} + +unsafe impl Send for Library {} + +// That being said... this section in the volume 2 of POSIX.1-2008 states: +// +// > All functions defined by this volume of POSIX.1-2008 shall be thread-safe, except that the +// > following functions need not be thread-safe. +// +// With notable absence of any dl* function other than dlerror in the list. By “this volume” +// I suppose they refer precisely to the “volume 2”. dl* family of functions are specified +// by this same volume, so the conclusion is indeed that dl* functions are required by POSIX +// to be thread-safe. Great! +// +// See for more details: +// +// * https://github.com/nagisa/rust_libloading/pull/17 +// * http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_09_01 +unsafe impl Sync for Library {} + +impl Library { + /// Find and load a shared library (module). + /// + /// Locations where library is searched for is platform specific and can’t be adjusted + /// portably. + /// + /// Corresponds to `dlopen(filename, RTLD_NOW)`. + #[inline] + pub fn new>(filename: P) -> ::Result { + Library::open(Some(filename), RTLD_NOW) + } + + /// Load the dynamic libraries linked into main program. + /// + /// This allows retrieving symbols from any **dynamic** library linked into the program, + /// without specifying the exact library. + /// + /// Corresponds to `dlopen(NULL, RTLD_NOW)`. + #[inline] + pub fn this() -> Library { + Library::open(None::<&OsStr>, RTLD_NOW).unwrap() + } + + /// Find and load a shared library (module). + /// + /// Locations where library is searched for is platform specific and can’t be adjusted + /// portably. + /// + /// If the `filename` is None, null pointer is passed to `dlopen`. + /// + /// Corresponds to `dlopen(filename, flags)`. + pub fn open

(filename: Option

, flags: raw::c_int) -> ::Result + where P: AsRef { + let filename = match filename { + None => None, + Some(ref f) => Some(try!(cstr_cow_from_bytes(f.as_ref().as_bytes()))), + }; + with_dlerror(move || { + let result = unsafe { + let r = dlopen(match filename { + None => ptr::null(), + Some(ref f) => f.as_ptr() + }, flags); + // ensure filename lives until dlopen completes + drop(filename); + r + }; + if result.is_null() { + None + } else { + Some(Library { + handle: result + }) + } + }).map_err(|e| e.unwrap_or_else(|| + panic!("dlopen failed but dlerror did not report anything") + )) + } + + /// Get a pointer to function or static variable by symbol name. + /// + /// The `symbol` may not contain any null bytes, with an exception of last byte. A null + /// terminated `symbol` may avoid a string allocation in some cases. + /// + /// Symbol is interpreted as-is; no mangling is done. This means that symbols like `x::y` are + /// most likely invalid. + /// + /// ## Unsafety + /// + /// Pointer to a value of arbitrary type is returned. Using a value with wrong type is + /// undefined. + /// + /// ## Platform-specific behaviour + /// + /// OS X uses some sort of lazy initialization scheme, which makes loading TLS variables + /// impossible. Using a TLS variable loaded this way on OS X is undefined behaviour. + pub unsafe fn get(&self, symbol: &[u8]) -> ::Result> { + ensure_compatible_types::(); + let symbol = try!(cstr_cow_from_bytes(symbol)); + // `dlsym` may return nullptr in two cases: when a symbol genuinely points to a null + // pointer or the symbol cannot be found. In order to detect this case a double dlerror + // pattern must be used, which is, sadly, a little bit racy. + // + // We try to leave as little space as possible for this to occur, but we can’t exactly + // fully prevent it. + match with_dlerror(|| { + dlerror(); + let symbol = dlsym(self.handle, symbol.as_ptr()); + if symbol.is_null() { + None + } else { + Some(Symbol { + pointer: symbol, + pd: marker::PhantomData + }) + } + }) { + Err(None) => Ok(Symbol { + pointer: ptr::null_mut(), + pd: marker::PhantomData + }), + Err(Some(e)) => Err(e), + Ok(x) => Ok(x) + } + } +} + +impl Drop for Library { + fn drop(&mut self) { + with_dlerror(|| if unsafe { dlclose(self.handle) } == 0 { + Some(()) + } else { + None + }).unwrap(); + } +} + +impl fmt::Debug for Library { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&format!("Library@{:p}", self.handle)) + } +} + +/// Symbol from a library. +/// +/// A major difference compared to the cross-platform `Symbol` is that this does not ensure the +/// `Symbol` does not outlive `Library` it comes from. +pub struct Symbol { + pointer: *mut raw::c_void, + pd: marker::PhantomData +} + +unsafe impl Send for Symbol {} +unsafe impl Sync for Symbol {} + +impl Clone for Symbol { + fn clone(&self) -> Symbol { + Symbol { ..*self } + } +} + +impl ::std::ops::Deref for Symbol { + type Target = T; + fn deref(&self) -> &T { + unsafe { + // Additional reference level for a dereference on `deref` return value. + mem::transmute(&self.pointer) + } + } +} + +impl fmt::Debug for Symbol { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let mut info: DlInfo = mem::uninitialized(); + if dladdr(self.pointer, &mut info) != 0 { + if info.dli_sname.is_null() { + f.write_str(&format!("Symbol@{:p} from {:?}", + self.pointer, + CStr::from_ptr(info.dli_fname))) + } else { + f.write_str(&format!("Symbol {:?}@{:p} from {:?}", + CStr::from_ptr(info.dli_sname), self.pointer, + CStr::from_ptr(info.dli_fname))) + } + } else { + f.write_str(&format!("Symbol@{:p}", self.pointer)) + } + } + } +} + +// Platform specific things + +extern { + fn dlopen(filename: *const raw::c_char, flags: raw::c_int) -> *mut raw::c_void; + fn dlclose(handle: *mut raw::c_void) -> raw::c_int; + fn dlsym(handle: *mut raw::c_void, symbol: *const raw::c_char) -> *mut raw::c_void; + fn dlerror() -> *mut raw::c_char; + fn dladdr(addr: *mut raw::c_void, info: *mut DlInfo) -> raw::c_int; +} + +#[cfg(not(target_os="android"))] +const RTLD_NOW: raw::c_int = 2; +#[cfg(target_os="android")] +const RTLD_NOW: raw::c_int = 0; + +#[repr(C)] +struct DlInfo { + dli_fname: *const raw::c_char, + dli_fbase: *mut raw::c_void, + dli_sname: *const raw::c_char, + dli_saddr: *mut raw::c_void +} + +#[test] +fn this() { + Library::this(); +} diff --git a/bash-5.1/vendor/libloading-0.3.4/src/os/windows/mod.rs b/bash-5.1/vendor/libloading-0.3.4/src/os/windows/mod.rs new file mode 100644 index 0000000..128e3ff --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/os/windows/mod.rs @@ -0,0 +1,242 @@ +extern crate winapi; +extern crate kernel32; + +use util::{ensure_compatible_types, cstr_cow_from_bytes}; + +use std::ffi::{OsStr, OsString}; +use std::{fmt, io, marker, mem, ptr}; +use std::os::windows::ffi::{OsStrExt, OsStringExt}; +use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; + + +/// A platform-specific equivalent of the cross-platform `Library`. +pub struct Library(winapi::HMODULE); + +unsafe impl Send for Library {} +// Now, this is sort-of-tricky. MSDN documentation does not really make any claims as to safety of +// the Win32 APIs. Sadly, whomever I asked, even current and former Microsoft employees, couldn’t +// say for sure, whether the Win32 APIs used to implement `Library` are thread-safe or not. +// +// My investigation ended up with a question about thread-safety properties of the API involved +// being sent to an internal (to MS) general question mailing-list. The conclusion of the mail is +// as such: +// +// * Nobody inside MS (at least out of all the people who have seen the question) knows for +// sure either; +// * However, the general consensus between MS developers is that one can rely on the API being +// thread-safe. In case it is not thread-safe it should be considered a bug on the Windows +// part. (NB: bugs filled at https://connect.microsoft.com/ against Windows Server) +unsafe impl Sync for Library {} + +impl Library { + /// Find and load a shared library (module). + /// + /// Corresponds to `LoadLibraryW(filename)`. + #[inline] + pub fn new>(filename: P) -> ::Result { + let wide_filename: Vec = filename.as_ref().encode_wide().chain(Some(0)).collect(); + let _guard = ErrorModeGuard::new(); + + let ret = with_get_last_error(|| { + // Make sure no winapi calls as a result of drop happen inside this closure, because + // otherwise that might change the return value of the GetLastError. + let handle = unsafe { kernel32::LoadLibraryW(wide_filename.as_ptr()) }; + if handle.is_null() { + None + } else { + Some(Library(handle)) + } + }).map_err(|e| e.unwrap_or_else(|| + panic!("LoadLibraryW failed but GetLastError did not report the error") + )); + + drop(wide_filename); // Drop wide_filename here to ensure it doesn’t get moved and dropped + // inside the closure by mistake. See comment inside the closure. + ret + } + + /// Get a pointer to function or static variable by symbol name. + /// + /// The `symbol` may not contain any null bytes, with an exception of last byte. A null + /// terminated `symbol` may avoid a string allocation in some cases. + /// + /// Symbol is interpreted as-is; no mangling is done. This means that symbols like `x::y` are + /// most likely invalid. + /// + /// ## Unsafety + /// + /// Pointer to a value of arbitrary type is returned. Using a value with wrong type is + /// undefined. + pub unsafe fn get(&self, symbol: &[u8]) -> ::Result> { + ensure_compatible_types::(); + let symbol = try!(cstr_cow_from_bytes(symbol)); + with_get_last_error(|| { + let symbol = kernel32::GetProcAddress(self.0, symbol.as_ptr()); + if symbol.is_null() { + None + } else { + Some(Symbol { + pointer: symbol, + pd: marker::PhantomData + }) + } + }).map_err(|e| e.unwrap_or_else(|| + panic!("GetProcAddress failed but GetLastError did not report the error") + )) + } + + /// Get a pointer to function or static variable by ordinal number. + /// + /// ## Unsafety + /// + /// Pointer to a value of arbitrary type is returned. Using a value with wrong type is + /// undefined. + pub unsafe fn get_ordinal(&self, ordinal: winapi::WORD) -> ::Result> { + ensure_compatible_types::(); + with_get_last_error(|| { + let ordinal = ordinal as usize as *mut _; + let symbol = kernel32::GetProcAddress(self.0, ordinal); + if symbol.is_null() { + None + } else { + Some(Symbol { + pointer: symbol, + pd: marker::PhantomData + }) + } + }).map_err(|e| e.unwrap_or_else(|| + panic!("GetProcAddress failed but GetLastError did not report the error") + )) + } +} + +impl Drop for Library { + fn drop(&mut self) { + with_get_last_error(|| { + if unsafe { kernel32::FreeLibrary(self.0) == 0 } { + None + } else { + Some(()) + } + }).unwrap() + } +} + +impl fmt::Debug for Library { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let mut buf: [winapi::WCHAR; 1024] = mem::uninitialized(); + let len = kernel32::GetModuleFileNameW(self.0, + (&mut buf[..]).as_mut_ptr(), 1024) as usize; + if len == 0 { + f.write_str(&format!("Library@{:p}", self.0)) + } else { + let string: OsString = OsString::from_wide(&buf[..len]); + f.write_str(&format!("Library@{:p} from {:?}", self.0, string)) + } + } + } +} + +/// Symbol from a library. +/// +/// A major difference compared to the cross-platform `Symbol` is that this does not ensure the +/// `Symbol` does not outlive `Library` it comes from. +pub struct Symbol { + pointer: winapi::FARPROC, + pd: marker::PhantomData +} + +unsafe impl Send for Symbol {} +unsafe impl Sync for Symbol {} + +impl Clone for Symbol { + fn clone(&self) -> Symbol { + Symbol { ..*self } + } +} + +impl ::std::ops::Deref for Symbol { + type Target = T; + fn deref(&self) -> &T { + unsafe { + // Additional reference level for a dereference on `deref` return value. + mem::transmute(&self.pointer) + } + } +} + +impl fmt::Debug for Symbol { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&format!("Symbol@{:p}", self.pointer)) + } +} + + +static USE_ERRORMODE: AtomicBool = ATOMIC_BOOL_INIT; +struct ErrorModeGuard(winapi::DWORD); + +impl ErrorModeGuard { + fn new() -> ErrorModeGuard { + let mut ret = ErrorModeGuard(0); + + if !USE_ERRORMODE.load(Ordering::Acquire) { + if unsafe { kernel32::SetThreadErrorMode(1, &mut ret.0) == 0 + && kernel32::GetLastError() == winapi::ERROR_CALL_NOT_IMPLEMENTED } { + USE_ERRORMODE.store(true, Ordering::Release); + } else { + return ret; + } + } + ret.0 = unsafe { kernel32::SetErrorMode(1) }; + ret + } +} + +impl Drop for ErrorModeGuard { + fn drop(&mut self) { + unsafe { + if !USE_ERRORMODE.load(Ordering::Relaxed) { + kernel32::SetThreadErrorMode(self.0, ptr::null_mut()); + } else { + kernel32::SetErrorMode(self.0); + } + } + } +} + +fn with_get_last_error(closure: F) -> Result> +where F: FnOnce() -> Option { + closure().ok_or_else(|| { + let error = unsafe { kernel32::GetLastError() }; + if error == 0 { + None + } else { + Some(io::Error::from_raw_os_error(error as i32)) + } + }) +} + +#[test] +fn works_getlasterror() { + let lib = Library::new("kernel32.dll").unwrap(); + let gle: Symbol winapi::DWORD> = unsafe { + lib.get(b"GetLastError").unwrap() + }; + unsafe { + kernel32::SetLastError(42); + assert_eq!(kernel32::GetLastError(), gle()) + } +} + +#[test] +fn works_getlasterror0() { + let lib = Library::new("kernel32.dll").unwrap(); + let gle: Symbol winapi::DWORD> = unsafe { + lib.get(b"GetLastError\0").unwrap() + }; + unsafe { + kernel32::SetLastError(42); + assert_eq!(kernel32::GetLastError(), gle()) + } +} diff --git a/bash-5.1/vendor/libloading-0.3.4/src/test_helpers.rs b/bash-5.1/vendor/libloading-0.3.4/src/test_helpers.rs new file mode 100644 index 0000000..32f7023 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/test_helpers.rs @@ -0,0 +1,49 @@ +//! This is a separate file containing helpers for tests of this library. It is built into a +//! dynamic library by the build.rs script. +#![crate_type="dylib"] // FIXME: should become a cdylib in due time +#![cfg_attr(test_nightly, feature(thread_local))] + +#[no_mangle] +pub static mut TEST_STATIC_U32: u32 = 0; + +#[no_mangle] +pub static mut TEST_STATIC_PTR: *mut () = 0 as *mut _; + +#[cfg(test_nightly)] +#[thread_local] +#[no_mangle] +pub static mut TEST_THREAD_LOCAL: u32 = 0; + +#[no_mangle] +pub extern "C" fn test_identity_u32(x: u32) -> u32 { + x +} + +#[repr(C)] +pub struct S { + a: u64, + b: u32, + c: u16, + d: u8 +} + +#[no_mangle] +pub extern "C" fn test_identity_struct(x: S) -> S { + x +} + +#[no_mangle] +pub unsafe extern "C" fn test_get_static_u32() -> u32 { + TEST_STATIC_U32 +} + +#[no_mangle] +pub unsafe extern "C" fn test_check_static_ptr() -> bool { + TEST_STATIC_PTR == (&mut TEST_STATIC_PTR as *mut *mut _ as *mut _) +} + +#[cfg(test_nightly)] +#[no_mangle] +pub unsafe extern "C" fn test_get_thread_local() -> u32 { + TEST_THREAD_LOCAL +} diff --git a/bash-5.1/vendor/libloading-0.3.4/src/util.rs b/bash-5.1/vendor/libloading-0.3.4/src/util.rs new file mode 100644 index 0000000..caa95b6 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/src/util.rs @@ -0,0 +1,61 @@ +use std::ffi::{CStr, CString, NulError, FromBytesWithNulError}; +use std::borrow::Cow; +use std::os::raw; + +#[derive(Debug)] +pub struct NullError; + +impl From for NullError { + fn from(_: NulError) -> NullError { + NullError + } +} + +impl From for NullError { + fn from(_: FromBytesWithNulError) -> NullError { + NullError + } +} + +impl From for ::std::io::Error { + fn from(e: NullError) -> ::std::io::Error { + ::std::io::Error::new(::std::io::ErrorKind::Other, format!("{}", e)) + } +} + +impl ::std::error::Error for NullError { + fn description(&self) -> &str { "non-final null byte found" } +} + +impl ::std::fmt::Display for NullError { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + write!(f, "non-final null byte found") + } +} + +/// Checks for last byte and avoids alocatting if its zero. +/// +/// Non-last null bytes still result in an error. +pub fn cstr_cow_from_bytes<'a>(slice: &'a [u8]) -> Result, NullError> { + static ZERO: raw::c_char = 0; + Ok(match slice.last() { + // Slice out of 0 elements + None => unsafe { Cow::Borrowed(CStr::from_ptr(&ZERO)) }, + // Slice with trailing 0 + Some(&0) => Cow::Borrowed(try!(CStr::from_bytes_with_nul(slice))), + // Slice with no trailing 0 + Some(_) => Cow::Owned(try!(CString::new(slice))), + }) +} + +#[inline] +pub fn ensure_compatible_types() { + #[cold] + #[inline(never)] + fn dopanic() { + panic!("value of requested type cannot be dynamically loaded"); + } + if ::std::mem::size_of::() != ::std::mem::size_of::() { + dopanic() + } +} diff --git a/bash-5.1/vendor/libloading-0.3.4/tests/functions.rs b/bash-5.1/vendor/libloading-0.3.4/tests/functions.rs new file mode 100644 index 0000000..109689b --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/tests/functions.rs @@ -0,0 +1,85 @@ +extern crate libloading; +use libloading::{Symbol, Library}; + +const LIBPATH: &'static str = concat!(env!("OUT_DIR"), "/libtest_helpers.dll"); + +#[test] +fn test_id_u32() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let f: Symbol u32> = lib.get(b"test_identity_u32\0").unwrap(); + assert_eq!(42, f(42)); + } +} + +#[repr(C)] +#[derive(Clone,Copy,PartialEq,Debug)] +struct S { + a: u64, + b: u32, + c: u16, + d: u8 +} + +#[test] +fn test_id_struct() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let f: Symbol S> = lib.get(b"test_identity_struct\0").unwrap(); + assert_eq!(S { a: 1, b: 2, c: 3, d: 4 }, f(S { a: 1, b: 2, c: 3, d: 4 })); + } +} + +#[test] +fn test_0_no_0() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let f: Symbol S> = lib.get(b"test_identity_struct\0").unwrap(); + let f2: Symbol S> = lib.get(b"test_identity_struct").unwrap(); + assert_eq!(*f, *f2); + } +} + +#[test] +fn wrong_name_fails() { + Library::new(concat!(env!("OUT_DIR"), "/libtest_help")).err().unwrap(); +} + +#[test] +fn missing_symbol_fails() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + lib.get::<*mut ()>(b"test_does_not_exist").err().unwrap(); + lib.get::<*mut ()>(b"test_does_not_exist\0").err().unwrap(); + } +} + +#[test] +fn interior_null_fails() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + lib.get::<*mut ()>(b"test_does\0_not_exist").err().unwrap(); + lib.get::<*mut ()>(b"test\0_does_not_exist\0").err().unwrap(); + } +} + +#[test] +#[should_panic] +fn test_incompatible_type() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let _ = lib.get::<()>(b"test_identity_u32\0"); + } +} + +#[test] +#[should_panic] +fn test_incompatible_type_named_fn() { + unsafe fn get<'a, T>(l: &'a Library, _: T) -> libloading::Result> { + l.get::(b"test_identity_u32\0") + } + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let _ = get(&lib, test_incompatible_type_named_fn); + } +} diff --git a/bash-5.1/vendor/libloading-0.3.4/tests/markers.rs b/bash-5.1/vendor/libloading-0.3.4/tests/markers.rs new file mode 100644 index 0000000..01da108 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/tests/markers.rs @@ -0,0 +1,79 @@ +extern crate libloading; + +#[cfg(test)] +fn assert_send() {} +#[cfg(test)] +fn assert_sync() {} + +#[test] +fn check_library_send() { + assert_send::(); +} + +#[cfg(unix)] +#[test] +fn check_unix_library_send() { + assert_send::(); +} + +#[cfg(windows)] +#[test] +fn check_windows_library_send() { + assert_send::(); +} + +#[test] +fn check_library_sync() { + assert_sync::(); +} + +#[cfg(unix)] +#[test] +fn check_unix_library_sync() { + assert_sync::(); +} + +#[cfg(windows)] +#[test] +fn check_windows_library_sync() { + assert_sync::(); +} + +#[test] +fn check_symbol_send() { + assert_send:: ()>>(); + // assert_not_send::>(); +} + +#[cfg(unix)] +#[test] +fn check_unix_symbol_send() { + assert_send:: ()>>(); + // assert_not_send::>(); +} + +#[cfg(windows)] +#[test] +fn check_windows_symbol_send() { + assert_send:: ()>>(); +} + +#[test] +fn check_symbol_sync() { + assert_sync:: ()>>(); + // assert_not_sync::>(); +} + +#[cfg(unix)] +#[test] +fn check_unix_symbol_sync() { + assert_sync:: ()>>(); + // assert_not_sync::>(); +} + +#[cfg(windows)] +#[test] +fn check_windows_symbol_sync() { + assert_sync:: ()>>(); + // assert_not_sync::>(); +} diff --git a/bash-5.1/vendor/libloading-0.3.4/tests/nagisa32.dll b/bash-5.1/vendor/libloading-0.3.4/tests/nagisa32.dll new file mode 100644 index 0000000000000000000000000000000000000000..0a6218ade9c051e3ebc34c5ad4a687c44263fb33 GIT binary patch literal 3072 zcmeHHK}!Nr5S}%SvJ?*;gP!1dkvw@@qM(D3SrG+`uI{1>`ZiX@@-GC{wf|utoun>Z z`~?#91G;qUW;1X1gooe83O zpTP0eTOZPp(4TOX8EE>WxV7`%cF^ApCm=O6hBZrQHHIby5@WevKwiOE+AhX9v^*MV zQIR}wqiQ#e%%*DA>(H^e>2#XJBQS?_OK4cC!3D>JUV+prhB4`@YI(v$y_6^xdY0;T ryJoqHG2U6BSyI1<3NZZy%5Basr#}{)_$w2@f07hGjQ>-B|2Kh8N)2p9 literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/libloading-0.3.4/tests/nagisa64.dll b/bash-5.1/vendor/libloading-0.3.4/tests/nagisa64.dll new file mode 100644 index 0000000000000000000000000000000000000000..bacaa4b969411958776c0aad5a848114b1b7bf51 GIT binary patch literal 2560 zcmeHH&r1SP5FRzd3dLiGz-R1v35>v-2LlgAVnP&%ySkza`Zm^;%2TJnLqD$l9|qDX z@X{gw0_lIKTb*p??LJxvLXU>S&dkpDzW10n?0yHQ_YeYr74+#8V2GJ4BjVqIxUs}j z3vQCreGU!_I80Ve4&H(>b>sR;@F;%bCep_V9?cEu*eRqw9)y^hY@L_GpxE zrBBi)cLS^^>9UtAA{WhClQ^=Y!ajg;9fH*7!?DEPVVi9PV*o)!=t5}mI0f-~6%YUh zTwfK?PZk&U_5?vgs=G<1-?fV{29Wd4nkgZFYbN4sB-N>3I7k)qq?UbmmnSd)O|=c( z(E(lvL_qN55C}ud;G?=UcRo7^(s>bdpJf1^edY3XfhUl=34bL3Mz5ab`&nhPUsB?^ zeqMt~bn%zPGCy ztrnb{+_26&grgycbV_KJ(&hqVt{h2yVpx-&s&!Y0s27cDp0JO0T8z5#EZZ?*sc literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/libloading-0.3.4/tests/statics.rs b/bash-5.1/vendor/libloading-0.3.4/tests/statics.rs new file mode 100644 index 0000000..7a7f4e9 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/tests/statics.rs @@ -0,0 +1,44 @@ +extern crate libloading; +use libloading::{Symbol, Library}; + +const LIBPATH: &'static str = concat!(env!("OUT_DIR"), "/libtest_helpers.dll"); + +#[test] +fn test_static_u32() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let var: Symbol<*mut u32> = lib.get(b"TEST_STATIC_U32\0").unwrap(); + **var = 42; + let help: Symbol u32> = lib.get(b"test_get_static_u32\0").unwrap(); + assert_eq!(42, help()); + } +} + +#[test] +fn test_static_ptr() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let var: Symbol<*mut *mut ()> = lib.get(b"TEST_STATIC_PTR\0").unwrap(); + **var = *var as *mut _; + let works: Symbol bool> = + lib.get(b"test_check_static_ptr\0").unwrap(); + assert!(works()); + } +} + +#[cfg(any(windows, target_os="linux"))] +#[cfg(test_nightly)] +#[test] +fn test_tls_static() { + let lib = Library::new(LIBPATH).unwrap(); + unsafe { + let var: Symbol<*mut u32> = lib.get(b"TEST_THREAD_LOCAL\0").unwrap(); + **var = 84; + let help: Symbol u32> = lib.get(b"test_get_thread_local\0").unwrap(); + assert_eq!(84, help()); + } + ::std::thread::spawn(move || unsafe { + let help: Symbol u32> = lib.get(b"test_get_thread_local\0").unwrap(); + assert_eq!(0, help()); + }).join().unwrap(); +} diff --git a/bash-5.1/vendor/libloading-0.3.4/tests/windows.rs b/bash-5.1/vendor/libloading-0.3.4/tests/windows.rs new file mode 100644 index 0000000..343aaa1 --- /dev/null +++ b/bash-5.1/vendor/libloading-0.3.4/tests/windows.rs @@ -0,0 +1,56 @@ +#![cfg(windows)] +extern crate libloading; +use libloading::os::windows::*; +use std::ffi::CStr; + +// The ordinal DLL contains exactly one function (other than DllMain, that is) with ordinal number +// 1. This function has the sugnature `fn() -> *const c_char` and returns a string "bunny\0" (in +// reference to WindowsBunny). +// +// Both x86_64 and x86 versions of the .dll are functionally the same. Ideally we would compile the +// dlls with well known ordinals from our own testing helpers library, but rustc does not allow +// specifying a custom .def file (https://github.com/rust-lang/rust/issues/35089) +// +// The DLLs were kindly compiled by WindowsBunny (aka. @retep998). + +#[cfg(target_arch="x86")] +fn load_ordinal_lib() -> Library { + Library::new("tests/nagisa32.dll").expect("nagisa32.dll") +} + +#[cfg(target_arch="x86_64")] +fn load_ordinal_lib() -> Library { + Library::new("tests/nagisa64.dll").expect("nagisa64.dll") +} + +#[cfg(any(target_arch="x86", target_arch="x86_64"))] +#[test] +fn test_ordinal() { + let lib = load_ordinal_lib(); + unsafe { + let windows: Symbol *const i8> = lib.get_ordinal(1).expect("function"); + assert_eq!(CStr::from_ptr(windows()).to_bytes(), b"bunny"); + } +} + +#[cfg(any(target_arch="x86", target_arch="x86_64"))] +#[test] +fn test_ordinal_missing_fails() { + let lib = load_ordinal_lib(); + unsafe { + let r: Result *const i8>, _> = lib.get_ordinal(2); + r.err().unwrap(); + let r: Result *const i8>, _> = lib.get_ordinal(!0); + r.err().unwrap(); + } +} + +#[test] +fn test_new_kernel23() { + Library::new("kernel23").err().unwrap(); +} + +#[test] +fn test_new_kernel32_no_ext() { + Library::new("kernel32").unwrap(); +} diff --git a/bash-5.1/vendor/log-0.3.9/.cargo-checksum.json b/bash-5.1/vendor/log-0.3.9/.cargo-checksum.json new file mode 100644 index 0000000..5fc3b71 --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"827b8cdf64e9652b178d6033fdcb4fc04a1382edf67ce4f2c6dce39943349f10","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"7c831cff45cfd33333cc246815dccb25bfa0b981053656e707828fe3f25151da","appveyor.yml":"c61473b8c780ad2626282ce2b2ba0ef278082b6afe151a62ff419f33eaf90221","src/lib.rs":"8238bde9046b1b4a0d21b5ae9029abd672a7d314581b1fd8d0890b2a3052d443","src/macros.rs":"9068d69d32e989ac273ce73659125d31cf4a166076eefdad74dfbdf9506cf9c4"},"package":"e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b"} \ No newline at end of file diff --git a/bash-5.1/vendor/log-0.3.9/Cargo.toml b/bash-5.1/vendor/log-0.3.9/Cargo.toml new file mode 100644 index 0000000..1bea809 --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/Cargo.toml @@ -0,0 +1,45 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "log" +version = "0.3.9" +authors = ["The Rust Project Developers"] +description = "A lightweight logging facade for Rust\n" +homepage = "https://github.com/rust-lang/log" +documentation = "https://doc.rust-lang.org/log" +readme = "README.md" +categories = ["development-tools::debugging"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/log" + +[lib] +doctest = false +[dependencies.log] +version = "0.4" + +[features] +default = ["use_std"] +max_level_debug = ["log/max_level_debug"] +max_level_error = ["log/max_level_error"] +max_level_info = ["log/max_level_info"] +max_level_off = ["log/max_level_off"] +max_level_trace = ["log/max_level_trace"] +max_level_warn = ["log/max_level_warn"] +nightly = [] +release_max_level_debug = ["log/release_max_level_debug"] +release_max_level_error = ["log/release_max_level_error"] +release_max_level_info = ["log/release_max_level_info"] +release_max_level_off = ["log/release_max_level_off"] +release_max_level_trace = ["log/release_max_level_trace"] +release_max_level_warn = ["log/release_max_level_warn"] +use_std = ["log/std"] diff --git a/bash-5.1/vendor/log-0.3.9/LICENSE-APACHE b/bash-5.1/vendor/log-0.3.9/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/log-0.3.9/LICENSE-MIT b/bash-5.1/vendor/log-0.3.9/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/log-0.3.9/README.md b/bash-5.1/vendor/log-0.3.9/README.md new file mode 100644 index 0000000..0e9dc58 --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/README.md @@ -0,0 +1,160 @@ +log +=== + +A Rust library providing a lightweight logging *facade*. + +[![Build Status](https://travis-ci.org/rust-lang-nursery/log.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/log) +[![Build status](https://ci.appveyor.com/api/projects/status/nopdjmmjt45xcrki?svg=true)](https://ci.appveyor.com/project/alexcrichton/log) + +* [`log` documentation](https://doc.rust-lang.org/log) +* [`env_logger` documentation](https://doc.rust-lang.org/log/env_logger) + +A logging facade provides a single logging API that abstracts over the actual +logging implementation. Libraries can use the logging API provided by this +crate, and the consumer of those libraries can choose the logging +implementation that is most suitable for its use case. + +## Usage + +## In libraries + +Libraries should link only to the `log` crate, and use the provided macros to +log whatever information will be useful to downstream consumers: + +```toml +[dependencies] +log = "0.3" +``` + +```rust +#[macro_use] +extern crate log; + +pub fn shave_the_yak(yak: &Yak) { + trace!("Commencing yak shaving"); + + loop { + match find_a_razor() { + Ok(razor) => { + info!("Razor located: {}", razor); + yak.shave(razor); + break; + } + Err(err) => { + warn!("Unable to locate a razor: {}, retrying", err); + } + } + } +} +``` + +## In executables + +Executables should choose a logger implementation and initialize it early in the +runtime of the program. Logger implementations will typically include a +function to do this. Any log messages generated before the logger is +initialized will be ignored. + +The executable itself may use the `log` crate to log as well. + +The `env_logger` crate provides a logger implementation that mirrors the +functionality of the old revision of the `log` crate. + +```toml +[dependencies] +log = "0.3" +env_logger = "0.3" +``` + +```rust +#[macro_use] +extern crate log; +extern crate env_logger; + +fn main() { + env_logger::init().unwrap(); + + info!("starting up"); + + // ... +} +``` + +## In tests + +Tests can use the `env_logger` crate to see log messages generated during that test: + +```toml +[dependencies] +log = "0.3" + +[dev-dependencies] +env_logger = "0.3" +``` + +```rust +#[macro_use] +extern crate log; + +fn add_one(num: i32) -> i32 { + info!("add_one called with {}", num); + num + 1 +} + +#[cfg(test)] +mod tests { + use super::*; + extern crate env_logger; + + #[test] + fn it_adds_one() { + let _ = env_logger::init(); + info!("can log from the test too"); + assert_eq!(3, add_one(2)); + } + + #[test] + fn it_handles_negative_numbers() { + let _ = env_logger::init(); + info!("logging from another test"); + assert_eq!(-7, add_one(-8)); + } +} +``` + +Assuming the module under test is called `my_lib`, running the tests with the +`RUST_LOG` filtering to info messages from this module looks like: + +```bash +$ RUST_LOG=my_lib=info cargo test + Running target/debug/my_lib-... + +running 2 tests +INFO:my_lib::tests: logging from another test +INFO:my_lib: add_one called with -8 +test tests::it_handles_negative_numbers ... ok +INFO:my_lib::tests: can log from the test too +INFO:my_lib: add_one called with 2 +test tests::it_adds_one ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured +``` + +Note that `env_logger::init()` needs to be called in each test in which you +want to enable logging. Additionally, the default behavior of tests to +run in parallel means that logging output may be interleaved with test output. +Either run tests in a single thread by specifying `RUST_TEST_THREADS=1` or by +running one test by specifying its name as an argument to the test binaries as +directed by the `cargo test` help docs: + +```bash +$ RUST_LOG=my_lib=info cargo test it_adds_one + Running target/debug/my_lib-... + +running 1 test +INFO:my_lib::tests: can log from the test too +INFO:my_lib: add_one called with 2 +test tests::it_adds_one ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured +``` diff --git a/bash-5.1/vendor/log-0.3.9/appveyor.yml b/bash-5.1/vendor/log-0.3.9/appveyor.yml new file mode 100644 index 0000000..841011d --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/appveyor.yml @@ -0,0 +1,18 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose + - cargo test --manifest-path env/Cargo.toml diff --git a/bash-5.1/vendor/log-0.3.9/src/lib.rs b/bash-5.1/vendor/log-0.3.9/src/lib.rs new file mode 100644 index 0000000..1abdf31 --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/src/lib.rs @@ -0,0 +1,1091 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A lightweight logging facade. +//! +//! A logging facade provides a single logging API that abstracts over the +//! actual logging implementation. Libraries can use the logging API provided +//! by this crate, and the consumer of those libraries can choose the logging +//! framework that is most suitable for its use case. +//! +//! If no logging implementation is selected, the facade falls back to a "noop" +//! implementation that ignores all log messages. The overhead in this case +//! is very small - just an integer load, comparison and jump. +//! +//! A log request consists of a target, a level, and a body. A target is a +//! string which defaults to the module path of the location of the log +//! request, though that default may be overridden. Logger implementations +//! typically use the target to filter requests based on some user +//! configuration. +//! +//! # Use +//! +//! ## In libraries +//! +//! Libraries should link only to the `log` crate, and use the provided +//! macros to log whatever information will be useful to downstream consumers. +//! +//! ### Examples +//! +//! ```rust +//! # #![allow(unstable)] +//! #[macro_use] +//! extern crate log; +//! +//! # #[derive(Debug)] pub struct Yak(String); +//! # impl Yak { fn shave(&self, _: u32) {} } +//! # fn find_a_razor() -> Result { Ok(1) } +//! pub fn shave_the_yak(yak: &Yak) { +//! info!(target: "yak_events", "Commencing yak shaving for {:?}", yak); +//! +//! loop { +//! match find_a_razor() { +//! Ok(razor) => { +//! info!("Razor located: {}", razor); +//! yak.shave(razor); +//! break; +//! } +//! Err(err) => { +//! warn!("Unable to locate a razor: {}, retrying", err); +//! } +//! } +//! } +//! } +//! # fn main() {} +//! ``` +//! +//! ## In executables +//! +//! Executables should choose a logging framework and initialize it early in the +//! runtime of the program. Logging frameworks will typically include a +//! function to do this. Any log messages generated before the framework is +//! initialized will be ignored. +//! +//! The executable itself may use the `log` crate to log as well. +//! +//! ### Warning +//! +//! The logging system may only be initialized once. +//! +//! ### Examples +//! +//! ```rust,ignore +//! #[macro_use] +//! extern crate log; +//! extern crate my_logger; +//! +//! fn main() { +//! my_logger::init(); +//! +//! info!("starting up"); +//! +//! // ... +//! } +//! ``` +//! +//! # Logger implementations +//! +//! Loggers implement the `Log` trait. Here's a very basic example that simply +//! logs all messages at the `Error`, `Warn` or `Info` levels to stdout: +//! +//! ```rust +//! extern crate log; +//! +//! use log::{LogRecord, LogLevel, LogMetadata}; +//! +//! struct SimpleLogger; +//! +//! impl log::Log for SimpleLogger { +//! fn enabled(&self, metadata: &LogMetadata) -> bool { +//! metadata.level() <= LogLevel::Info +//! } +//! +//! fn log(&self, record: &LogRecord) { +//! if self.enabled(record.metadata()) { +//! println!("{} - {}", record.level(), record.args()); +//! } +//! } +//! } +//! +//! # fn main() {} +//! ``` +//! +//! Loggers are installed by calling the `set_logger` function. It takes a +//! closure which is provided a `MaxLogLevel` token and returns a `Log` trait +//! object. The `MaxLogLevel` token controls the global maximum log level. The +//! logging facade uses this as an optimization to improve performance of log +//! messages at levels that are disabled. In the case of our example logger, +//! we'll want to set the maximum log level to `Info`, since we ignore any +//! `Debug` or `Trace` level log messages. A logging framework should provide a +//! function that wraps a call to `set_logger`, handling initialization of the +//! logger: +//! +//! ```rust +//! # extern crate log; +//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, LogMetadata}; +//! # struct SimpleLogger; +//! # impl log::Log for SimpleLogger { +//! # fn enabled(&self, _: &LogMetadata) -> bool { false } +//! # fn log(&self, _: &log::LogRecord) {} +//! # } +//! # fn main() {} +//! # #[cfg(feature = "use_std")] +//! pub fn init() -> Result<(), SetLoggerError> { +//! log::set_logger(|max_log_level| { +//! max_log_level.set(LogLevelFilter::Info); +//! Box::new(SimpleLogger) +//! }) +//! } +//! ``` +//! +//! # Use with `no_std` +//! +//! To use the `log` crate without depending on `libstd`, you need to specify +//! `default-features = false` when specifying the dependency in `Cargo.toml`. +//! This makes no difference to libraries using `log` since the logging API +//! remains the same. However executables will need to use the `set_logger_raw` +//! function to initialize a logger and the `shutdown_logger_raw` function to +//! shut down the global logger before exiting: +//! +//! ```rust +//! # extern crate log; +//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, ShutdownLoggerError, +//! # LogMetadata}; +//! # struct SimpleLogger; +//! # impl log::Log for SimpleLogger { +//! # fn enabled(&self, _: &LogMetadata) -> bool { false } +//! # fn log(&self, _: &log::LogRecord) {} +//! # } +//! # impl SimpleLogger { +//! # fn flush(&self) {} +//! # } +//! # fn main() {} +//! pub fn init() -> Result<(), SetLoggerError> { +//! unsafe { +//! log::set_logger_raw(|max_log_level| { +//! static LOGGER: SimpleLogger = SimpleLogger; +//! max_log_level.set(LogLevelFilter::Info); +//! &SimpleLogger +//! }) +//! } +//! } +//! pub fn shutdown() -> Result<(), ShutdownLoggerError> { +//! log::shutdown_logger_raw().map(|logger| { +//! let logger = unsafe { &*(logger as *const SimpleLogger) }; +//! logger.flush(); +//! }) +//! } +//! ``` + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/log/")] +#![warn(missing_docs)] +#![cfg_attr(feature = "nightly", feature(panic_handler))] + +#![cfg_attr(not(feature = "use_std"), no_std)] + +// When compiled for the rustc compiler itself we want to make sure that this is +// an unstable crate +#![cfg_attr(rustbuild, feature(staged_api, rustc_private))] +#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] + +#[cfg(not(feature = "use_std"))] +extern crate core as std; +extern crate log; + +use std::cmp; +#[cfg(feature = "use_std")] +use std::error; +use std::fmt; +use std::mem; +use std::ops::Deref; +use std::str::FromStr; +use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; +#[macro_use] +mod macros; + +// The setup here is a bit weird to make shutdown_logger_raw work. +// +// There are four different states that we care about: the logger's +// uninitialized, the logger's initializing (set_logger's been called but +// LOGGER hasn't actually been set yet), the logger's active, or the logger is +// shut down after calling shutdown_logger_raw. +// +// The LOGGER static holds a pointer to the global logger. It is protected by +// the STATE static which determines whether LOGGER has been initialized yet. +// +// The shutdown_logger_raw routine needs to make sure that no threads are +// actively logging before it returns. The number of actively logging threads is +// tracked in the REFCOUNT static. The routine first sets STATE back to +// INITIALIZING. All logging calls past that point will immediately return +// without accessing the logger. At that point, the at_exit routine just waits +// for the refcount to reach 0 before deallocating the logger. Note that the +// refcount does not necessarily monotonically decrease at this point, as new +// log calls still increment and decrement it, but the interval in between is +// small enough that the wait is really just for the active log calls to finish. + +static mut LOGGER: *const Log = &NopLogger; +static STATE: AtomicUsize = ATOMIC_USIZE_INIT; +static REFCOUNT: AtomicUsize = ATOMIC_USIZE_INIT; + +const INITIALIZING: usize = 1; +const INITIALIZED: usize = 2; + +static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", + "DEBUG", "TRACE"]; + +/// An enum representing the available verbosity levels of the logging framework +/// +/// A `LogLevel` may be compared directly to a `LogLevelFilter`. +#[repr(usize)] +#[derive(Copy, Eq, Debug)] +pub enum LogLevel { + /// The "error" level. + /// + /// Designates very serious errors. + Error = 1, // This way these line up with the discriminants for LogLevelFilter below + /// The "warn" level. + /// + /// Designates hazardous situations. + Warn, + /// The "info" level. + /// + /// Designates useful information. + Info, + /// The "debug" level. + /// + /// Designates lower priority information. + Debug, + /// The "trace" level. + /// + /// Designates very low priority, often extremely verbose, information. + Trace, +} + +impl Clone for LogLevel { + #[inline] + fn clone(&self) -> LogLevel { + *self + } +} + +impl PartialEq for LogLevel { + #[inline] + fn eq(&self, other: &LogLevel) -> bool { + *self as usize == *other as usize + } +} + +impl PartialEq for LogLevel { + #[inline] + fn eq(&self, other: &LogLevelFilter) -> bool { + *self as usize == *other as usize + } +} + +impl PartialOrd for LogLevel { + #[inline] + fn partial_cmp(&self, other: &LogLevel) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialOrd for LogLevel { + #[inline] + fn partial_cmp(&self, other: &LogLevelFilter) -> Option { + Some((*self as usize).cmp(&(*other as usize))) + } +} + +impl Ord for LogLevel { + #[inline] + fn cmp(&self, other: &LogLevel) -> cmp::Ordering { + (*self as usize).cmp(&(*other as usize)) + } +} + +fn ok_or(t: Option, e: E) -> Result { + match t { + Some(t) => Ok(t), + None => Err(e), + } +} + +// Reimplemented here because std::ascii is not available in libcore +fn eq_ignore_ascii_case(a: &str, b: &str) -> bool { + fn to_ascii_uppercase(c: u8) -> u8 { + if c >= b'a' && c <= b'z' { + c - b'a' + b'A' + } else { + c + } + } + + if a.len() == b.len() { + a.bytes() + .zip(b.bytes()) + .all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b)) + } else { + false + } +} + +impl FromStr for LogLevel { + type Err = (); + fn from_str(level: &str) -> Result { + ok_or(LOG_LEVEL_NAMES.iter() + .position(|&name| eq_ignore_ascii_case(name, level)) + .into_iter() + .filter(|&idx| idx != 0) + .map(|idx| LogLevel::from_usize(idx).unwrap()) + .next(), ()) + } +} + +impl fmt::Display for LogLevel { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.pad(LOG_LEVEL_NAMES[*self as usize]) + } +} + +impl LogLevel { + fn from_usize(u: usize) -> Option { + match u { + 1 => Some(LogLevel::Error), + 2 => Some(LogLevel::Warn), + 3 => Some(LogLevel::Info), + 4 => Some(LogLevel::Debug), + 5 => Some(LogLevel::Trace), + _ => None + } + } + + fn from_new(level: log::Level) -> LogLevel { + match level { + log::Level::Error => LogLevel::Error, + log::Level::Warn => LogLevel::Warn, + log::Level::Info => LogLevel::Info, + log::Level::Debug => LogLevel::Debug, + log::Level::Trace => LogLevel::Trace, + } + } + + fn to_new(&self) -> log::Level { + match *self { + LogLevel::Error => log::Level::Error, + LogLevel::Warn => log::Level::Warn, + LogLevel::Info => log::Level::Info, + LogLevel::Debug => log::Level::Debug, + LogLevel::Trace => log::Level::Trace, + } + } + + /// Returns the most verbose logging level. + #[inline] + pub fn max() -> LogLevel { + LogLevel::Trace + } + + /// Converts the `LogLevel` to the equivalent `LogLevelFilter`. + #[inline] + pub fn to_log_level_filter(&self) -> LogLevelFilter { + LogLevelFilter::from_usize(*self as usize).unwrap() + } +} + +/// An enum representing the available verbosity level filters of the logging +/// framework. +/// +/// A `LogLevelFilter` may be compared directly to a `LogLevel`. +#[repr(usize)] +#[derive(Copy, Eq, Debug)] +pub enum LogLevelFilter { + /// A level lower than all log levels. + Off, + /// Corresponds to the `Error` log level. + Error, + /// Corresponds to the `Warn` log level. + Warn, + /// Corresponds to the `Info` log level. + Info, + /// Corresponds to the `Debug` log level. + Debug, + /// Corresponds to the `Trace` log level. + Trace, +} + +// Deriving generates terrible impls of these traits + +impl Clone for LogLevelFilter { + #[inline] + fn clone(&self) -> LogLevelFilter { + *self + } +} + +impl PartialEq for LogLevelFilter { + #[inline] + fn eq(&self, other: &LogLevelFilter) -> bool { + *self as usize == *other as usize + } +} + +impl PartialEq for LogLevelFilter { + #[inline] + fn eq(&self, other: &LogLevel) -> bool { + other.eq(self) + } +} + +impl PartialOrd for LogLevelFilter { + #[inline] + fn partial_cmp(&self, other: &LogLevelFilter) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialOrd for LogLevelFilter { + #[inline] + fn partial_cmp(&self, other: &LogLevel) -> Option { + other.partial_cmp(self).map(|x| x.reverse()) + } +} + +impl Ord for LogLevelFilter { + #[inline] + fn cmp(&self, other: &LogLevelFilter) -> cmp::Ordering { + (*self as usize).cmp(&(*other as usize)) + } +} + +impl FromStr for LogLevelFilter { + type Err = (); + fn from_str(level: &str) -> Result { + ok_or(LOG_LEVEL_NAMES.iter() + .position(|&name| eq_ignore_ascii_case(name, level)) + .map(|p| LogLevelFilter::from_usize(p).unwrap()), ()) + } +} + +impl fmt::Display for LogLevelFilter { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}", LOG_LEVEL_NAMES[*self as usize]) + } +} + +impl LogLevelFilter { + fn from_usize(u: usize) -> Option { + match u { + 0 => Some(LogLevelFilter::Off), + 1 => Some(LogLevelFilter::Error), + 2 => Some(LogLevelFilter::Warn), + 3 => Some(LogLevelFilter::Info), + 4 => Some(LogLevelFilter::Debug), + 5 => Some(LogLevelFilter::Trace), + _ => None + } + } + + fn from_new(filter: log::LevelFilter) -> LogLevelFilter { + match filter { + log::LevelFilter::Off => LogLevelFilter::Off, + log::LevelFilter::Error => LogLevelFilter::Error, + log::LevelFilter::Warn => LogLevelFilter::Warn, + log::LevelFilter::Info => LogLevelFilter::Info, + log::LevelFilter::Debug => LogLevelFilter::Debug, + log::LevelFilter::Trace => LogLevelFilter::Trace, + } + } + + fn to_new(&self) -> log::LevelFilter { + match *self { + LogLevelFilter::Off => log::LevelFilter::Off, + LogLevelFilter::Error => log::LevelFilter::Error, + LogLevelFilter::Warn => log::LevelFilter::Warn, + LogLevelFilter::Info => log::LevelFilter::Info, + LogLevelFilter::Debug => log::LevelFilter::Debug, + LogLevelFilter::Trace => log::LevelFilter::Trace, + } + } + + /// Returns the most verbose logging level filter. + #[inline] + pub fn max() -> LogLevelFilter { + LogLevelFilter::Trace + } + + /// Converts `self` to the equivalent `LogLevel`. + /// + /// Returns `None` if `self` is `LogLevelFilter::Off`. + #[inline] + pub fn to_log_level(&self) -> Option { + LogLevel::from_usize(*self as usize) + } +} + +/// The "payload" of a log message. +pub struct LogRecord<'a> { + metadata: LogMetadata<'a>, + location: &'a LogLocation, + args: fmt::Arguments<'a>, +} + +impl<'a> LogRecord<'a> { + /// The message body. + pub fn args(&self) -> &fmt::Arguments<'a> { + &self.args + } + + /// Metadata about the log directive. + pub fn metadata(&self) -> &LogMetadata { + &self.metadata + } + + /// The location of the log directive. + pub fn location(&self) -> &LogLocation { + self.location + } + + /// The verbosity level of the message. + pub fn level(&self) -> LogLevel { + self.metadata.level() + } + + /// The name of the target of the directive. + pub fn target(&self) -> &str { + self.metadata.target() + } +} + +/// Metadata about a log message. +pub struct LogMetadata<'a> { + level: LogLevel, + target: &'a str, +} + +impl<'a> LogMetadata<'a> { + /// The verbosity level of the message. + pub fn level(&self) -> LogLevel { + self.level + } + + /// The name of the target of the directive. + pub fn target(&self) -> &str { + self.target + } +} + +/// A trait encapsulating the operations required of a logger +pub trait Log: Sync+Send { + /// Determines if a log message with the specified metadata would be + /// logged. + /// + /// This is used by the `log_enabled!` macro to allow callers to avoid + /// expensive computation of log message arguments if the message would be + /// discarded anyway. + fn enabled(&self, metadata: &LogMetadata) -> bool; + + /// Logs the `LogRecord`. + /// + /// Note that `enabled` is *not* necessarily called before this method. + /// Implementations of `log` should perform all necessary filtering + /// internally. + fn log(&self, record: &LogRecord); +} + +// Just used as a dummy initial value for LOGGER +struct NopLogger; + +impl Log for NopLogger { + fn enabled(&self, _: &LogMetadata) -> bool { false } + + fn log(&self, _: &LogRecord) {} +} + +/// The location of a log message. +/// +/// # Warning +/// +/// The fields of this struct are public so that they may be initialized by the +/// `log!` macro. They are subject to change at any time and should never be +/// accessed directly. +#[derive(Copy, Clone, Debug)] +pub struct LogLocation { + #[doc(hidden)] + pub __module_path: &'static str, + #[doc(hidden)] + pub __file: &'static str, + #[doc(hidden)] + pub __line: u32, +} + +impl LogLocation { + /// The module path of the message. + pub fn module_path(&self) -> &str { + self.__module_path + } + + /// The source file containing the message. + pub fn file(&self) -> &str { + self.__file + } + + /// The line containing the message. + pub fn line(&self) -> u32 { + self.__line + } +} + +/// A token providing read and write access to the global maximum log level +/// filter. +/// +/// The maximum log level is used as an optimization to avoid evaluating log +/// messages that will be ignored by the logger. Any message with a level +/// higher than the maximum log level filter will be ignored. A logger should +/// make sure to keep the maximum log level filter in sync with its current +/// configuration. +pub struct MaxLogLevelFilter(()); + +impl fmt::Debug for MaxLogLevelFilter { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "MaxLogLevelFilter") + } +} + +impl MaxLogLevelFilter { + /// Gets the current maximum log level filter. + pub fn get(&self) -> LogLevelFilter { + max_log_level() + } + + /// Sets the maximum log level. + pub fn set(&self, level: LogLevelFilter) { + log::set_max_level(level.to_new()) + } +} + +/// Returns the current maximum log level. +/// +/// The `log!`, `error!`, `warn!`, `info!`, `debug!`, and `trace!` macros check +/// this value and discard any message logged at a higher level. The maximum +/// log level is set by the `MaxLogLevel` token passed to loggers. +#[inline(always)] +pub fn max_log_level() -> LogLevelFilter { + LogLevelFilter::from_new(log::max_level()) +} + +/// Sets the global logger. +/// +/// The `make_logger` closure is passed a `MaxLogLevel` object, which the +/// logger should use to keep the global maximum log level in sync with the +/// highest log level that the logger will not ignore. +/// +/// This function may only be called once in the lifetime of a program. Any log +/// events that occur before the call to `set_logger` completes will be +/// ignored. +/// +/// This function does not typically need to be called manually. Logger +/// implementations should provide an initialization method that calls +/// `set_logger` internally. +/// +/// Requires the `use_std` feature (enabled by default). +#[cfg(feature = "use_std")] +pub fn set_logger(make_logger: M) -> Result<(), SetLoggerError> + where M: FnOnce(MaxLogLevelFilter) -> Box { + unsafe { set_logger_raw(|max_level| mem::transmute(make_logger(max_level))) } +} + +/// Sets the global logger from a raw pointer. +/// +/// This function is similar to `set_logger` except that it is usable in +/// `no_std` code. +/// +/// The `make_logger` closure is passed a `MaxLogLevel` object, which the +/// logger should use to keep the global maximum log level in sync with the +/// highest log level that the logger will not ignore. +/// +/// This function may only be called once in the lifetime of a program. Any log +/// events that occur before the call to `set_logger_raw` completes will be +/// ignored. +/// +/// This function does not typically need to be called manually. Logger +/// implementations should provide an initialization method that calls +/// `set_logger_raw` internally. +/// +/// # Safety +/// +/// The pointer returned by `make_logger` must remain valid for the entire +/// duration of the program or until `shutdown_logger_raw` is called. In +/// addition, `shutdown_logger` *must not* be called after this function. +pub unsafe fn set_logger_raw(make_logger: M) -> Result<(), SetLoggerError> + where M: FnOnce(MaxLogLevelFilter) -> *const Log { + static ADAPTOR: LoggerAdaptor = LoggerAdaptor; + match log::set_logger(&ADAPTOR) { + Ok(()) => { + LOGGER = make_logger(MaxLogLevelFilter(())); + STATE.store(INITIALIZED, Ordering::SeqCst); + Ok(()) + } + Err(_) => Err(SetLoggerError(())), + } +} + +/// Shuts down the global logger. +/// +/// This function may only be called once in the lifetime of a program, and may +/// not be called before `set_logger`. Once the global logger has been shut +/// down, it can no longer be re-initialized by `set_logger`. Any log events +/// that occur after the call to `shutdown_logger` completes will be ignored. +/// +/// The logger that was originally created by the call to to `set_logger` is +/// returned on success. At that point it is guaranteed that no other threads +/// are concurrently accessing the logger object. +#[cfg(feature = "use_std")] +pub fn shutdown_logger() -> Result, ShutdownLoggerError> { + shutdown_logger_raw().map(|l| unsafe { mem::transmute(l) }) +} + +/// Shuts down the global logger. +/// +/// This function is similar to `shutdown_logger` except that it is usable in +/// `no_std` code. +/// +/// This function may only be called once in the lifetime of a program, and may +/// not be called before `set_logger_raw`. Once the global logger has been shut +/// down, it can no longer be re-initialized by `set_logger_raw`. Any log +/// events that occur after the call to `shutdown_logger_raw` completes will be +/// ignored. +/// +/// The pointer that was originally passed to `set_logger_raw` is returned on +/// success. At that point it is guaranteed that no other threads are +/// concurrently accessing the logger object. +pub fn shutdown_logger_raw() -> Result<*const Log, ShutdownLoggerError> { + // Set to INITIALIZING to prevent re-initialization after + if STATE.compare_and_swap(INITIALIZED, INITIALIZING, + Ordering::SeqCst) != INITIALIZED { + return Err(ShutdownLoggerError(())); + } + + while REFCOUNT.load(Ordering::SeqCst) != 0 { + // FIXME add a sleep here when it doesn't involve timers + } + + unsafe { + let logger = LOGGER; + LOGGER = &NopLogger; + Ok(logger) + } +} + +/// The type returned by `set_logger` if `set_logger` has already been called. +#[allow(missing_copy_implementations)] +#[derive(Debug)] +pub struct SetLoggerError(()); + +impl fmt::Display for SetLoggerError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "attempted to set a logger after the logging system \ + was already initialized") + } +} + +// The Error trait is not available in libcore +#[cfg(feature = "use_std")] +impl error::Error for SetLoggerError { + fn description(&self) -> &str { "set_logger() called multiple times" } +} + +/// The type returned by `shutdown_logger_raw` if `shutdown_logger_raw` has +/// already been called or if `set_logger_raw` has not been called yet. +#[allow(missing_copy_implementations)] +#[derive(Debug)] +pub struct ShutdownLoggerError(()); + +impl fmt::Display for ShutdownLoggerError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "attempted to shut down the logger without an active logger") + } +} + +// The Error trait is not available in libcore +#[cfg(feature = "use_std")] +impl error::Error for ShutdownLoggerError { + fn description(&self) -> &str { "shutdown_logger() called without an active logger" } +} + +/// Deprecated +/// +/// Use https://crates.io/crates/log-panics instead. +#[cfg(all(feature = "nightly", feature = "use_std"))] +pub fn log_panics() { + std::panic::set_hook(Box::new(panic::log)); +} + +// inner module so that the reporting module is log::panic instead of log +#[cfg(all(feature = "nightly", feature = "use_std"))] +mod panic { + use std::panic::PanicInfo; + use std::thread; + + pub fn log(info: &PanicInfo) { + let thread = thread::current(); + let thread = thread.name().unwrap_or(""); + + let msg = match info.payload().downcast_ref::<&'static str>() { + Some(s) => *s, + None => match info.payload().downcast_ref::() { + Some(s) => &s[..], + None => "Box", + } + }; + + match info.location() { + Some(location) => { + error!("thread '{}' panicked at '{}': {}:{}", + thread, + msg, + location.file(), + location.line()) + } + None => error!("thread '{}' panicked at '{}'", thread, msg), + } + } +} + +struct LoggerGuard(&'static Log); + +impl Drop for LoggerGuard { + fn drop(&mut self) { + REFCOUNT.fetch_sub(1, Ordering::SeqCst); + } +} + +impl Deref for LoggerGuard { + type Target = Log; + + fn deref(&self) -> &(Log + 'static) { + self.0 + } +} + +fn logger() -> Option { + REFCOUNT.fetch_add(1, Ordering::SeqCst); + if STATE.load(Ordering::SeqCst) != INITIALIZED { + REFCOUNT.fetch_sub(1, Ordering::SeqCst); + None + } else { + Some(LoggerGuard(unsafe { &*LOGGER })) + } +} + +struct LoggerAdaptor; + +impl log::Log for LoggerAdaptor { + fn log(&self, record: &log::Record) { + if let Some(logger) = logger() { + let record = LogRecord { + metadata: LogMetadata { + level: LogLevel::from_new(record.level()), + target: record.target(), + }, + // file and module path aren't static in 0.4 so we can't forward them. + location: &LogLocation { + __file: "", + __line: record.line().unwrap_or(0), + __module_path: "", + }, + args: *record.args(), + }; + logger.log(&record); + } + } + + fn enabled(&self, metadata: &log::Metadata) -> bool { + match logger() { + Some(logger) => { + let metadata = LogMetadata { + level: LogLevel::from_new(metadata.level()), + target: metadata.target(), + }; + logger.enabled(&metadata) + } + None => false + } + } + + fn flush(&self) {} +} + +// WARNING +// This is not considered part of the crate's public API. It is subject to +// change at any time. +#[doc(hidden)] +pub fn __enabled(level: LogLevel, target: &str) -> bool { + match logger() { + Some(logger) => { + let metadata = LogMetadata { + level: level, + target: target, + }; + logger.enabled(&metadata) + } + None => { + log::Log::enabled( + log::logger(), + &log::Metadata::builder() + .level(level.to_new()) + .target(target) + .build() + ) + } + } +} + +// WARNING +// This is not considered part of the crate's public API. It is subject to +// change at any time. +#[doc(hidden)] +pub fn __log(level: LogLevel, target: &str, loc: &LogLocation, + args: fmt::Arguments) { + match logger() { + Some(logger) => { + let record = LogRecord { + metadata: LogMetadata { + level: level, + target: target, + }, + location: loc, + args: args, + }; + logger.log(&record); + } + None => { + log::Log::log( + log::logger(), + &log::Record::builder() + .level(level.to_new()) + .target(target) + .file(Some(loc.__file)) + .line(Some(loc.__line)) + .module_path(Some(loc.__module_path)) + .args(args) + .build() + ) + } + } +} + +// WARNING +// This is not considered part of the crate's public API. It is subject to +// change at any time. +#[inline(always)] +#[doc(hidden)] +pub fn __static_max_level() -> LogLevelFilter { + LogLevelFilter::from_new(log::STATIC_MAX_LEVEL) +} + +#[cfg(test)] +mod tests { + extern crate std; + use tests::std::string::ToString; + use super::{LogLevel, LogLevelFilter}; + + #[test] + fn test_loglevelfilter_from_str() { + let tests = [ + ("off", Ok(LogLevelFilter::Off)), + ("error", Ok(LogLevelFilter::Error)), + ("warn", Ok(LogLevelFilter::Warn)), + ("info", Ok(LogLevelFilter::Info)), + ("debug", Ok(LogLevelFilter::Debug)), + ("trace", Ok(LogLevelFilter::Trace)), + ("OFF", Ok(LogLevelFilter::Off)), + ("ERROR", Ok(LogLevelFilter::Error)), + ("WARN", Ok(LogLevelFilter::Warn)), + ("INFO", Ok(LogLevelFilter::Info)), + ("DEBUG", Ok(LogLevelFilter::Debug)), + ("TRACE", Ok(LogLevelFilter::Trace)), + ("asdf", Err(())), + ]; + for &(s, ref expected) in &tests { + assert_eq!(expected, &s.parse()); + } + } + + #[test] + fn test_loglevel_from_str() { + let tests = [ + ("OFF", Err(())), + ("error", Ok(LogLevel::Error)), + ("warn", Ok(LogLevel::Warn)), + ("info", Ok(LogLevel::Info)), + ("debug", Ok(LogLevel::Debug)), + ("trace", Ok(LogLevel::Trace)), + ("ERROR", Ok(LogLevel::Error)), + ("WARN", Ok(LogLevel::Warn)), + ("INFO", Ok(LogLevel::Info)), + ("DEBUG", Ok(LogLevel::Debug)), + ("TRACE", Ok(LogLevel::Trace)), + ("asdf", Err(())), + ]; + for &(s, ref expected) in &tests { + assert_eq!(expected, &s.parse()); + } + } + + #[test] + fn test_loglevel_show() { + assert_eq!("INFO", LogLevel::Info.to_string()); + assert_eq!("ERROR", LogLevel::Error.to_string()); + } + + #[test] + fn test_loglevelfilter_show() { + assert_eq!("OFF", LogLevelFilter::Off.to_string()); + assert_eq!("ERROR", LogLevelFilter::Error.to_string()); + } + + #[test] + fn test_cross_cmp() { + assert!(LogLevel::Debug > LogLevelFilter::Error); + assert!(LogLevelFilter::Warn < LogLevel::Trace); + assert!(LogLevelFilter::Off < LogLevel::Error); + } + + #[test] + fn test_cross_eq() { + assert!(LogLevel::Error == LogLevelFilter::Error); + assert!(LogLevelFilter::Off != LogLevel::Error); + assert!(LogLevel::Trace == LogLevelFilter::Trace); + } + + #[test] + fn test_to_log_level() { + assert_eq!(Some(LogLevel::Error), LogLevelFilter::Error.to_log_level()); + assert_eq!(None, LogLevelFilter::Off.to_log_level()); + assert_eq!(Some(LogLevel::Debug), LogLevelFilter::Debug.to_log_level()); + } + + #[test] + fn test_to_log_level_filter() { + assert_eq!(LogLevelFilter::Error, LogLevel::Error.to_log_level_filter()); + assert_eq!(LogLevelFilter::Trace, LogLevel::Trace.to_log_level_filter()); + } + + #[test] + #[cfg(feature = "use_std")] + fn test_error_trait() { + use std::error::Error; + use super::SetLoggerError; + let e = SetLoggerError(()); + assert_eq!(e.description(), "set_logger() called multiple times"); + } +} diff --git a/bash-5.1/vendor/log-0.3.9/src/macros.rs b/bash-5.1/vendor/log-0.3.9/src/macros.rs new file mode 100644 index 0000000..7037f9a --- /dev/null +++ b/bash-5.1/vendor/log-0.3.9/src/macros.rs @@ -0,0 +1,155 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +/// The standard logging macro. +/// +/// This macro will generically log with the specified `LogLevel` and `format!` +/// based argument list. +/// +/// The `max_level_*` features can be used to statically disable logging at +/// various levels. +#[macro_export] +macro_rules! log { + (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ + static _LOC: $crate::LogLocation = $crate::LogLocation { + __line: line!(), + __file: file!(), + __module_path: module_path!(), + }; + let lvl = $lvl; + if lvl <= $crate::__static_max_level() && lvl <= $crate::max_log_level() { + $crate::__log(lvl, $target, &_LOC, format_args!($($arg)+)) + } + }); + ($lvl:expr, $($arg:tt)+) => (log!(target: module_path!(), $lvl, $($arg)+)) +} + +/// Logs a message at the error level. +/// +/// Logging at this level is disabled if the `max_level_off` feature is present. +#[macro_export] +macro_rules! error { + (target: $target:expr, $($arg:tt)*) => ( + log!(target: $target, $crate::LogLevel::Error, $($arg)*); + ); + ($($arg:tt)*) => ( + log!($crate::LogLevel::Error, $($arg)*); + ) +} + +/// Logs a message at the warn level. +/// +/// Logging at this level is disabled if any of the following features are +/// present: `max_level_off` or `max_level_error`. +/// +/// When building in release mode (i.e., without the `debug_assertions` option), +/// logging at this level is also disabled if any of the following features are +/// present: `release_max_level_off` or `max_level_error`. +#[macro_export] +macro_rules! warn { + (target: $target:expr, $($arg:tt)*) => ( + log!(target: $target, $crate::LogLevel::Warn, $($arg)*); + ); + ($($arg:tt)*) => ( + log!($crate::LogLevel::Warn, $($arg)*); + ) +} + +/// Logs a message at the info level. +/// +/// Logging at this level is disabled if any of the following features are +/// present: `max_level_off`, `max_level_error`, or `max_level_warn`. +/// +/// When building in release mode (i.e., without the `debug_assertions` option), +/// logging at this level is also disabled if any of the following features are +/// present: `release_max_level_off`, `release_max_level_error`, or +/// `release_max_level_warn`. +#[macro_export] +macro_rules! info { + (target: $target:expr, $($arg:tt)*) => ( + log!(target: $target, $crate::LogLevel::Info, $($arg)*); + ); + ($($arg:tt)*) => ( + log!($crate::LogLevel::Info, $($arg)*); + ) +} + +/// Logs a message at the debug level. +/// +/// Logging at this level is disabled if any of the following features are +/// present: `max_level_off`, `max_level_error`, `max_level_warn`, or +/// `max_level_info`. +/// +/// When building in release mode (i.e., without the `debug_assertions` option), +/// logging at this level is also disabled if any of the following features are +/// present: `release_max_level_off`, `release_max_level_error`, +/// `release_max_level_warn`, or `release_max_level_info`. +#[macro_export] +macro_rules! debug { + (target: $target:expr, $($arg:tt)*) => ( + log!(target: $target, $crate::LogLevel::Debug, $($arg)*); + ); + ($($arg:tt)*) => ( + log!($crate::LogLevel::Debug, $($arg)*); + ) +} + +/// Logs a message at the trace level. +/// +/// Logging at this level is disabled if any of the following features are +/// present: `max_level_off`, `max_level_error`, `max_level_warn`, +/// `max_level_info`, or `max_level_debug`. +/// +/// When building in release mode (i.e., without the `debug_assertions` option), +/// logging at this level is also disabled if any of the following features are +/// present: `release_max_level_off`, `release_max_level_error`, +/// `release_max_level_warn`, `release_max_level_info`, or +/// `release_max_level_debug`. +#[macro_export] +macro_rules! trace { + (target: $target:expr, $($arg:tt)*) => ( + log!(target: $target, $crate::LogLevel::Trace, $($arg)*); + ); + ($($arg:tt)*) => ( + log!($crate::LogLevel::Trace, $($arg)*); + ) +} + +/// Determines if a message logged at the specified level in that module will +/// be logged. +/// +/// This can be used to avoid expensive computation of log message arguments if +/// the message would be ignored anyway. +/// +/// # Examples +/// +/// ```rust +/// # #[macro_use] +/// # extern crate log; +/// use log::LogLevel::Debug; +/// +/// # fn foo() { +/// if log_enabled!(Debug) { +/// let data = expensive_call(); +/// debug!("expensive debug data: {} {}", data.x, data.y); +/// } +/// # } +/// # struct Data { x: u32, y: u32 } +/// # fn expensive_call() -> Data { Data { x: 0, y: 0 } } +/// # fn main() {} +/// ``` +#[macro_export] +macro_rules! log_enabled { + (target: $target:expr, $lvl:expr) => ({ + let lvl = $lvl; + lvl <= $crate::__static_max_level() && lvl <= $crate::max_log_level() && + $crate::__enabled(lvl, $target) + }); + ($lvl:expr) => (log_enabled!(target: module_path!(), $lvl)) +} diff --git a/bash-5.1/vendor/log/.cargo-checksum.json b/bash-5.1/vendor/log/.cargo-checksum.json new file mode 100644 index 0000000..96d7c07 --- /dev/null +++ b/bash-5.1/vendor/log/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"d96bb13d82aab1b8f01a077167eb3968fe27c4fbb7aa4933f0e257d42794eb76","Cargo.toml":"e0ff3b07a36ad23348c9cc7113ad787aefbc0c7b75517f5a68247863a4994e1c","LICENSE-APACHE":"7cfd738c53d61c79f07e348f622bf7707c9084237054d37fbe07788a75f5881c","LICENSE-MIT":"705aaaaecefa087c187bd2eacdb01b8ac1c5ee95b1d5d04d8d7efe0363207df8","README.md":"bd6ed9b3c1cf3329d7afca04eb03f5c36e75cf9cb0bbbffddb7f07f3f36f2ea0","benches/value.rs":"55bd5f795a524f0699b2858eb14cc456abebeb43d50c90d2bfc77cd7856e8050","build.rs":"91dd121dd1aa749c8c0c24bda658309d1313baa022afbc5af1fabd1104622376","src/kv/error.rs":"01d37bb1ecbb2ba1145cd6df0b0b9a3ea3f1a2c9586a4908d3256cb865365b7e","src/kv/key.rs":"e74b489cde28960f76d4038b02867b4cb724c206d31abd461abeaa04e73cf7ef","src/kv/mod.rs":"9d916f43fd9c2829991fcff6db32f23bb7864e1113a622d49e59f110e2f290cf","src/kv/source.rs":"3f7aadc5f30c0c821fd20d899d8529eba8088eeda0c8603814de689da25dd4e8","src/kv/value.rs":"3387875f0ffd5f4747f181c3bc5134974358993981e54b1f203d6dd835a50245","src/lib.rs":"69dd3c57d9c6438d2e5bda9dc657827dcd73561faff708358f2e6854f47a2a3d","src/macros.rs":"642640f48a9d61efed0213b3a61a2864e80e8f8ffb9541b7c44d3028d3a7f08c","src/serde.rs":"d8190561ed64398fe45142b261000255ea1bcda8707e6f1b07ef4b805da6829b","triagebot.toml":"2d1d46d069bc4e3739069676707ca2801e0e0ba58a784a264392362ff9ac4a77"},"package":"abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"} \ No newline at end of file diff --git a/bash-5.1/vendor/log/CHANGELOG.md b/bash-5.1/vendor/log/CHANGELOG.md new file mode 100644 index 0000000..7d68f89 --- /dev/null +++ b/bash-5.1/vendor/log/CHANGELOG.md @@ -0,0 +1,241 @@ +# Change Log + +## [Unreleased] + +## [0.4.17] - 2022-04-29 + +* Update `kv_unstable` internal dependencies. + +## [0.4.16] - 2022-03-22 + +* Fix a conflict with unqualified `Option` use in macros. + +## [0.4.15] - 2022-02-23 + +* Silence a warning about the deprecated `spin_loop_hint`. +* Relax ordering in the atomic `set_max_level` call. +* Add thumbv4t-none-eabi to targets that don't support atomics +* Allow levels to be iterated over. +* Implement `Log` on some common wrapper types. +* Improvements to test coverage. +* Improvements to documentation. +* Add key-value support to the `log!` macros. +* Tighten `kv_unstable` internal dependencies so they don't bump past their current alpha. +* Add a simple visit API to `kv_unstable`. +* Support `NonZero*` integers as values in structured logging +* Support static strings as keys in structured logging + +## [0.4.14] - 2021-01-27 + +* Remove the `__private_api_log_lit` special case. +* Fixed incorrect combination of `kv_unstable` and `std` features causing compile failures. +* Remove unstable `Value::to_*` conversions that were incorrectly using `as`. +* Rename unstable `Value::to_error` to `Value::to_borrowed_error`. + +## [0.4.13] - 2021-01-11 + +* This is the same as `0.4.11`, except with a `kv_unstable_std` feature added to aid migrating current dependents to `0.4.14` (which was originally going to be `0.4.13` until it was decided to create a patch from `0.4.11` to minimize disruption). + +## [0.4.12] - 2020-12-24 + +### New + +* Support platforms without atomics by racing instead of failing to compile +* Implement `Log` for `Box` +* Update `cfg-if` to `1.0` +* Internal reworks of the structured logging API. Removed the `Fill` API +and added `source::as_map` and `source::as_list` to easily serialize a `Source` +as either a map of `{key: value, ..}` or as a list of `[(key, value), ..]`. + +### Fixed + +* Fixed deserialization of `LevelFilter` to use their `u64` index variants + +## [0.4.11] - 2020-07-09 + +### New + +* Support coercing structured values into concrete types. +* Reference the `win_dbg_logger` in the readme. + +### Fixed + +* Updates a few deprecated items used internally. +* Fixed issues in docs and expands sections. +* Show the correct build badge in the readme. +* Fix up a possible inference breakage with structured value errors. +* Respect formatting flags in structured value formatting. + +## [0.4.10] - 2019-12-16 (yanked) + +### Fixed + +* Fixed the `log!` macros so they work in expression context (this regressed in `0.4.9`, which has been yanked). + +## [0.4.9] - 2019-12-12 (yanked) + +### Minimum Supported Rust Version + +This release bumps the minimum compiler version to `1.31.0`. This was mainly needed for `cfg-if`, +but between `1.16.0` and `1.31.0` there are a lot of language and library improvements we now +take advantage of. + +### New + +* Unstable support for capturing key-value pairs in a record using the `log!` macros + +### Improved + +* Better documentation for max level filters. +* Internal updates to line up with bumped MSRV + +## [0.4.8] - 2019-07-28 + +### New + +* Support attempting to get `Record` fields as static strings. + +## [0.4.7] - 2019-07-06 + +### New + +* Support for embedded environments with thread-unsafe initialization. +* Initial unstable support for capturing structured data under the `kv_unstable` +feature gate. This new API doesn't affect existing users and may change in future +patches (so those changes may not appear in the changelog until it stabilizes). + +### Improved + +* Docs for using `log` with the 2018 edition. +* Error messages for macros missing arguments. + +## [0.4.6] - 2018-10-27 + +### Improved + +* Support 2018-style macro import for the `log_enabled!` macro. + +## [0.4.5] - 2018-09-03 + +### Improved + +* Make `log`'s internal helper macros less likely to conflict with user-defined + macros. + +## [0.4.4] - 2018-08-17 + +### Improved + +* Support 2018-style imports of the log macros. + +## [0.4.3] - 2018-06-29 + +### Improved + +* More code generation improvements. + +## [0.4.2] - 2018-06-05 + +### Improved + +* Log invocations now generate less code. + +### Fixed + +* Example Logger implementations now properly set the max log level. + +## [0.4.1] - 2017-12-30 + +### Fixed + +* Some doc links were fixed. + +## [0.4.0] - 2017-12-24 + +The changes in this release include cleanup of some obscure functionality and a more robust public +API designed to support bridges to other logging systems, and provide more flexibility to new +features in the future. + +### Compatibility + +Vast portions of the Rust ecosystem use the 0.3.x release series of log, and we don't want to force +the community to go through the pain of upgrading every crate to 0.4.x at the exact same time. Along +with 0.4.0, we've published a new 0.3.9 release which acts as a "shim" over 0.4.0. This will allow +crates using either version to coexist without losing messages from one side or the other. + +There is one caveat - a log message generated by a crate using 0.4.x but consumed by a logging +implementation using 0.3.x will not have a file name or module path. Applications affected by this +can upgrade their logging implementations to one using 0.4.x to avoid losing this information. The +other direction does not lose any information, fortunately! + +**TL;DR** Libraries should feel comfortable upgrading to 0.4.0 without treating that as a breaking +change. Applications may need to update their logging implementation (e.g. env-logger) to a newer +version using log 0.4.x to avoid losing module and file information. + +### New + +* The crate is now `no_std` by default. +* `Level` and `LevelFilter` now implement `Serialize` and `Deserialize` when the `serde` feature is + enabled. +* The `Record` and `Metadata` types can now be constructed by third-party code via a builder API. +* The `logger` free function returns a reference to the logger implementation. This, along with the + ability to construct `Record`s, makes it possible to bridge from another logging framework to + this one without digging into the private internals of the crate. The standard `error!` `warn!`, + etc, macros now exclusively use the public API of the crate rather than "secret" internal APIs. +* `Log::flush` has been added to allow crates to tell the logging implementation to ensure that all + "in flight" log events have been persisted. This can be used, for example, just before an + application exits to ensure that asynchronous log sinks finish their work. + +### Removed + +* The `shutdown` and `shutdown_raw` functions have been removed. Supporting shutdown significantly + complicated the implementation and imposed a performance cost on each logging operation. +* The `log_panics` function and its associated `nightly` Cargo feature have been removed. Use the + [log-panics](https://crates.io/crates/log-panics) instead. + +### Changed + +* The `Log` prefix has been removed from type names. For example, `LogLevelFilter` is now + `LevelFilter`, and `LogRecord` is now `Record`. +* The `MaxLogLevelFilter` object has been removed in favor of a `set_max_level` free function. +* The `set_logger` free functions have been restructured. The logger is now directly passed to the + functions rather than a closure which returns the logger. `set_logger` now takes a `&'static + Log` and is usable in `no_std` contexts in place of the old `set_logger_raw`. `set_boxed_logger` + is a convenience function which takes a `Box` but otherwise acts like `set_logger`. It + requires the `std` feature. +* The `file` and `module_path` values in `Record` no longer have the `'static` lifetime to support + integration with other logging frameworks that don't provide a `'static` lifetime for the + equivalent values. +* The `file`, `line`, and `module_path` values in `Record` are now `Option`s to support integration + with other logging frameworks that don't provide those values. + +### In the Future + +* We're looking to add support for *structured* logging - the inclusion of extra key-value pairs of + information in a log event in addition to the normal string message. This should be able to be + added in a backwards compatible manner to the 0.4.x series when the design is worked out. + +## Older + +Look at the [release tags] for information about older releases. + +[Unreleased]: https://github.com/rust-lang-nursery/log/compare/0.4.17...HEAD +[0.4.17]: https://github.com/rust-lang-nursery/log/compare/0.4.16...0.4.17 +[0.4.16]: https://github.com/rust-lang-nursery/log/compare/0.4.15...0.4.16 +[0.4.15]: https://github.com/rust-lang-nursery/log/compare/0.4.13...0.4.15 +[0.4.14]: https://github.com/rust-lang-nursery/log/compare/0.4.13...0.4.14 +[0.4.13]: https://github.com/rust-lang-nursery/log/compare/0.4.11...0.4.13 +[0.4.12]: https://github.com/rust-lang-nursery/log/compare/0.4.11...0.4.12 +[0.4.11]: https://github.com/rust-lang-nursery/log/compare/0.4.10...0.4.11 +[0.4.10]: https://github.com/rust-lang-nursery/log/compare/0.4.9...0.4.10 +[0.4.9]: https://github.com/rust-lang-nursery/log/compare/0.4.8...0.4.9 +[0.4.8]: https://github.com/rust-lang-nursery/log/compare/0.4.7...0.4.8 +[0.4.7]: https://github.com/rust-lang-nursery/log/compare/0.4.6...0.4.7 +[0.4.6]: https://github.com/rust-lang-nursery/log/compare/0.4.5...0.4.6 +[0.4.5]: https://github.com/rust-lang-nursery/log/compare/0.4.4...0.4.5 +[0.4.4]: https://github.com/rust-lang-nursery/log/compare/0.4.3...0.4.4 +[0.4.3]: https://github.com/rust-lang-nursery/log/compare/0.4.2...0.4.3 +[0.4.2]: https://github.com/rust-lang-nursery/log/compare/0.4.1...0.4.2 +[0.4.1]: https://github.com/rust-lang-nursery/log/compare/0.4.0...0.4.1 +[0.4.0]: https://github.com/rust-lang-nursery/log/compare/0.3.8...0.4.0 +[release tags]: https://github.com/rust-lang-nursery/log/releases diff --git a/bash-5.1/vendor/log/Cargo.toml b/bash-5.1/vendor/log/Cargo.toml new file mode 100644 index 0000000..5fed87f --- /dev/null +++ b/bash-5.1/vendor/log/Cargo.toml @@ -0,0 +1,112 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "log" +version = "0.4.17" +authors = ["The Rust Project Developers"] +build = "build.rs" +exclude = ["rfcs/**/*"] +description = """ +A lightweight logging facade for Rust +""" +documentation = "https://docs.rs/log" +readme = "README.md" +keywords = ["logging"] +categories = ["development-tools::debugging"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang/log" + +[package.metadata.docs.rs] +features = [ + "std", + "serde", + "kv_unstable_std", + "kv_unstable_sval", + "kv_unstable_serde", +] + +[[test]] +name = "filters" +path = "tests/filters.rs" +harness = false + +[[test]] +name = "macros" +path = "tests/macros.rs" +harness = true + +[dependencies.cfg-if] +version = "1.0" + +[dependencies.serde] +version = "1.0" +optional = true +default-features = false + +[dependencies.sval] +version = "=1.0.0-alpha.5" +optional = true +default-features = false + +[dependencies.value-bag] +version = "=1.0.0-alpha.9" +optional = true +default-features = false + +[dev-dependencies.rustversion] +version = "1.0" + +[dev-dependencies.serde] +version = "1.0" +features = ["derive"] + +[dev-dependencies.serde_test] +version = "1.0" + +[dev-dependencies.sval] +version = "=1.0.0-alpha.5" +features = ["derive"] + +[dev-dependencies.value-bag] +version = "=1.0.0-alpha.9" +features = ["test"] + +[features] +kv_unstable = ["value-bag"] +kv_unstable_serde = [ + "kv_unstable_std", + "value-bag/serde", + "serde", +] +kv_unstable_std = [ + "std", + "kv_unstable", + "value-bag/error", +] +kv_unstable_sval = [ + "kv_unstable", + "value-bag/sval", + "sval", +] +max_level_debug = [] +max_level_error = [] +max_level_info = [] +max_level_off = [] +max_level_trace = [] +max_level_warn = [] +release_max_level_debug = [] +release_max_level_error = [] +release_max_level_info = [] +release_max_level_off = [] +release_max_level_trace = [] +release_max_level_warn = [] +std = [] diff --git a/bash-5.1/vendor/log/LICENSE-APACHE b/bash-5.1/vendor/log/LICENSE-APACHE new file mode 100644 index 0000000..f47c941 --- /dev/null +++ b/bash-5.1/vendor/log/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/log/LICENSE-MIT b/bash-5.1/vendor/log/LICENSE-MIT new file mode 100644 index 0000000..c0428e2 --- /dev/null +++ b/bash-5.1/vendor/log/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/log/README.md b/bash-5.1/vendor/log/README.md new file mode 100644 index 0000000..7fa4353 --- /dev/null +++ b/bash-5.1/vendor/log/README.md @@ -0,0 +1,117 @@ +log +=== + +A Rust library providing a lightweight logging *facade*. + +[![Build status](https://img.shields.io/github/workflow/status/rust-lang/log/CI/master)](https://github.com/rust-lang/log/actions) +[![Latest version](https://img.shields.io/crates/v/log.svg)](https://crates.io/crates/log) +[![Documentation](https://docs.rs/log/badge.svg)](https://docs.rs/log) +![License](https://img.shields.io/crates/l/log.svg) + +* [`log` documentation](https://docs.rs/log) + +A logging facade provides a single logging API that abstracts over the actual +logging implementation. Libraries can use the logging API provided by this +crate, and the consumer of those libraries can choose the logging +implementation that is most suitable for its use case. + + +## Minimum supported `rustc` + +`1.31.0+` + +This version is explicitly tested in CI and may be bumped in any release as needed. Maintaining compatibility with older compilers is a priority though, so the bar for bumping the minimum supported version is set very high. Any changes to the supported minimum version will be called out in the release notes. + +## Usage + +### In libraries + +Libraries should link only to the `log` crate, and use the provided macros to +log whatever information will be useful to downstream consumers: + +```toml +[dependencies] +log = "0.4" +``` + +```rust +use log::{info, trace, warn}; + +pub fn shave_the_yak(yak: &mut Yak) { + trace!("Commencing yak shaving"); + + loop { + match find_a_razor() { + Ok(razor) => { + info!("Razor located: {}", razor); + yak.shave(razor); + break; + } + Err(err) => { + warn!("Unable to locate a razor: {}, retrying", err); + } + } + } +} +``` + +### In executables + +In order to produce log output, executables have to use a logger implementation compatible with the facade. +There are many available implementations to choose from, here are some of the most popular ones: + +* Simple minimal loggers: + * [`env_logger`](https://docs.rs/env_logger/*/env_logger/) + * [`simple_logger`](https://docs.rs/simple_logger/*/simple_logger/) + * [`simplelog`](https://docs.rs/simplelog/*/simplelog/) + * [`pretty_env_logger`](https://docs.rs/pretty_env_logger/*/pretty_env_logger/) + * [`stderrlog`](https://docs.rs/stderrlog/*/stderrlog/) + * [`flexi_logger`](https://docs.rs/flexi_logger/*/flexi_logger/) +* Complex configurable frameworks: + * [`log4rs`](https://docs.rs/log4rs/*/log4rs/) + * [`fern`](https://docs.rs/fern/*/fern/) +* Adaptors for other facilities: + * [`syslog`](https://docs.rs/syslog/*/syslog/) + * [`systemd-journal-logger`](https://docs.rs/systemd-journal-logger/*/systemd_journal_logger/) + * [`slog-stdlog`](https://docs.rs/slog-stdlog/*/slog_stdlog/) + * [`android_log`](https://docs.rs/android_log/*/android_log/) + * [`win_dbg_logger`](https://docs.rs/win_dbg_logger/*/win_dbg_logger/) + * [`db_logger`](https://docs.rs/db_logger/*/db_logger/) +* For WebAssembly binaries: + * [`console_log`](https://docs.rs/console_log/*/console_log/) +* For dynamic libraries: + * You may need to construct [an FFI-safe wrapper over `log`](https://github.com/rust-lang/log/issues/421) to initialize in your libraries. +* Utilities: + * [`log_err`](https://docs.rs/log_err/*/log_err/) + +Executables should choose a logger implementation and initialize it early in the +runtime of the program. Logger implementations will typically include a +function to do this. Any log messages generated before the logger is +initialized will be ignored. + +The executable itself may use the `log` crate to log as well. + +## Structured logging + +If you enable the `kv_unstable` feature, you can associate structured data with your log records: + +```rust +use log::{info, trace, warn, as_serde, as_error}; + +pub fn shave_the_yak(yak: &mut Yak) { + trace!(target = "yak_events", yak = as_serde!(yak); "Commencing yak shaving"); + + loop { + match find_a_razor() { + Ok(razor) => { + info!(razor = razor; "Razor located"); + yak.shave(razor); + break; + } + Err(err) => { + warn!(err = as_error!(err); "Unable to locate a razor, retrying"); + } + } + } +} +``` diff --git a/bash-5.1/vendor/log/benches/value.rs b/bash-5.1/vendor/log/benches/value.rs new file mode 100644 index 0000000..3dab3bf --- /dev/null +++ b/bash-5.1/vendor/log/benches/value.rs @@ -0,0 +1,30 @@ +#![cfg(feature = "kv_unstable")] +#![feature(test)] + +extern crate log; +extern crate test; + +use log::kv::Value; + +#[bench] +fn u8_to_value(b: &mut test::Bencher) { + b.iter(|| Value::from(1u8)) +} + +#[bench] +fn u8_to_value_debug(b: &mut test::Bencher) { + b.iter(|| Value::from_debug(&1u8)) +} + +#[bench] +fn str_to_value_debug(b: &mut test::Bencher) { + b.iter(|| Value::from_debug(&"a string")) +} + +#[bench] +fn custom_to_value_debug(b: &mut test::Bencher) { + #[derive(Debug)] + struct A; + + b.iter(|| Value::from_debug(&A)) +} diff --git a/bash-5.1/vendor/log/build.rs b/bash-5.1/vendor/log/build.rs new file mode 100644 index 0000000..30c7edb --- /dev/null +++ b/bash-5.1/vendor/log/build.rs @@ -0,0 +1,46 @@ +//! This build script detects target platforms that lack proper support for +//! atomics and sets `cfg` flags accordingly. + +use std::env; +use std::str; + +fn main() { + let target = match rustc_target() { + Some(target) => target, + None => return, + }; + + if target_has_atomic_cas(&target) { + println!("cargo:rustc-cfg=atomic_cas"); + } + + if target_has_atomics(&target) { + println!("cargo:rustc-cfg=has_atomics"); + } + + println!("cargo:rerun-if-changed=build.rs"); +} + +fn target_has_atomic_cas(target: &str) -> bool { + match &target[..] { + "thumbv6m-none-eabi" + | "msp430-none-elf" + | "riscv32i-unknown-none-elf" + | "riscv32imc-unknown-none-elf" => false, + _ => true, + } +} + +fn target_has_atomics(target: &str) -> bool { + match &target[..] { + "thumbv4t-none-eabi" + | "msp430-none-elf" + | "riscv32i-unknown-none-elf" + | "riscv32imc-unknown-none-elf" => false, + _ => true, + } +} + +fn rustc_target() -> Option { + env::var("TARGET").ok() +} diff --git a/bash-5.1/vendor/log/src/kv/error.rs b/bash-5.1/vendor/log/src/kv/error.rs new file mode 100644 index 0000000..1adad23 --- /dev/null +++ b/bash-5.1/vendor/log/src/kv/error.rs @@ -0,0 +1,90 @@ +use std::fmt; + +/// An error encountered while working with structured data. +#[derive(Debug)] +pub struct Error { + inner: Inner, +} + +#[derive(Debug)] +enum Inner { + #[cfg(feature = "std")] + Boxed(std_support::BoxedError), + Msg(&'static str), + Value(value_bag::Error), + Fmt, +} + +impl Error { + /// Create an error from a message. + pub fn msg(msg: &'static str) -> Self { + Error { + inner: Inner::Msg(msg), + } + } + + // Not public so we don't leak the `value_bag` API + pub(super) fn from_value(err: value_bag::Error) -> Self { + Error { + inner: Inner::Value(err), + } + } + + // Not public so we don't leak the `value_bag` API + pub(super) fn into_value(self) -> value_bag::Error { + match self.inner { + Inner::Value(err) => err, + #[cfg(feature = "kv_unstable_std")] + _ => value_bag::Error::boxed(self), + #[cfg(not(feature = "kv_unstable_std"))] + _ => value_bag::Error::msg("error inspecting a value"), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Inner::*; + match &self.inner { + #[cfg(feature = "std")] + &Boxed(ref err) => err.fmt(f), + &Value(ref err) => err.fmt(f), + &Msg(ref msg) => msg.fmt(f), + &Fmt => fmt::Error.fmt(f), + } + } +} + +impl From for Error { + fn from(_: fmt::Error) -> Self { + Error { inner: Inner::Fmt } + } +} + +#[cfg(feature = "std")] +mod std_support { + use super::*; + use std::{error, io}; + + pub(super) type BoxedError = Box; + + impl Error { + /// Create an error from a standard error type. + pub fn boxed(err: E) -> Self + where + E: Into, + { + Error { + inner: Inner::Boxed(err.into()), + } + } + } + + impl error::Error for Error {} + + impl From for Error { + fn from(err: io::Error) -> Self { + Error::boxed(err) + } + } +} diff --git a/bash-5.1/vendor/log/src/kv/key.rs b/bash-5.1/vendor/log/src/kv/key.rs new file mode 100644 index 0000000..0e688c1 --- /dev/null +++ b/bash-5.1/vendor/log/src/kv/key.rs @@ -0,0 +1,172 @@ +//! Structured keys. + +use std::borrow::Borrow; +use std::cmp; +use std::fmt; +use std::hash; + +/// A type that can be converted into a [`Key`](struct.Key.html). +pub trait ToKey { + /// Perform the conversion. + fn to_key(&self) -> Key; +} + +impl<'a, T> ToKey for &'a T +where + T: ToKey + ?Sized, +{ + fn to_key(&self) -> Key { + (**self).to_key() + } +} + +impl<'k> ToKey for Key<'k> { + fn to_key(&self) -> Key { + Key { key: self.key } + } +} + +impl ToKey for str { + fn to_key(&self) -> Key { + Key::from_str(self) + } +} + +/// A key in a structured key-value pair. +#[derive(Clone)] +pub struct Key<'k> { + key: &'k str, +} + +impl<'k> Key<'k> { + /// Get a key from a borrowed string. + pub fn from_str(key: &'k str) -> Self { + Key { key: key } + } + + /// Get a borrowed string from this key. + pub fn as_str(&self) -> &str { + self.key + } +} + +impl<'k> fmt::Debug for Key<'k> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.key.fmt(f) + } +} + +impl<'k> fmt::Display for Key<'k> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.key.fmt(f) + } +} + +impl<'k> hash::Hash for Key<'k> { + fn hash(&self, state: &mut H) + where + H: hash::Hasher, + { + self.as_str().hash(state) + } +} + +impl<'k, 'ko> PartialEq> for Key<'k> { + fn eq(&self, other: &Key<'ko>) -> bool { + self.as_str().eq(other.as_str()) + } +} + +impl<'k> Eq for Key<'k> {} + +impl<'k, 'ko> PartialOrd> for Key<'k> { + fn partial_cmp(&self, other: &Key<'ko>) -> Option { + self.as_str().partial_cmp(other.as_str()) + } +} + +impl<'k> Ord for Key<'k> { + fn cmp(&self, other: &Self) -> cmp::Ordering { + self.as_str().cmp(other.as_str()) + } +} + +impl<'k> AsRef for Key<'k> { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl<'k> Borrow for Key<'k> { + fn borrow(&self) -> &str { + self.as_str() + } +} + +impl<'k> From<&'k str> for Key<'k> { + fn from(s: &'k str) -> Self { + Key::from_str(s) + } +} + +#[cfg(feature = "std")] +mod std_support { + use super::*; + + use std::borrow::Cow; + + impl ToKey for String { + fn to_key(&self) -> Key { + Key::from_str(self) + } + } + + impl<'a> ToKey for Cow<'a, str> { + fn to_key(&self) -> Key { + Key::from_str(self) + } + } +} + +#[cfg(feature = "kv_unstable_sval")] +mod sval_support { + use super::*; + + extern crate sval; + + use self::sval::value::{self, Value}; + + impl<'a> Value for Key<'a> { + fn stream(&self, stream: &mut value::Stream) -> value::Result { + self.key.stream(stream) + } + } +} + +#[cfg(feature = "kv_unstable_serde")] +mod serde_support { + use super::*; + + extern crate serde; + + use self::serde::{Serialize, Serializer}; + + impl<'a> Serialize for Key<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.key.serialize(serializer) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn key_from_string() { + assert_eq!("a key", Key::from_str("a key").as_str()); + } +} diff --git a/bash-5.1/vendor/log/src/kv/mod.rs b/bash-5.1/vendor/log/src/kv/mod.rs new file mode 100644 index 0000000..f96b821 --- /dev/null +++ b/bash-5.1/vendor/log/src/kv/mod.rs @@ -0,0 +1,26 @@ +//! **UNSTABLE:** Structured key-value pairs. +//! +//! This module is unstable and breaking changes may be made +//! at any time. See [the tracking issue](https://github.com/rust-lang-nursery/log/issues/328) +//! for more details. +//! +//! Add the `kv_unstable` feature to your `Cargo.toml` to enable +//! this module: +//! +//! ```toml +//! [dependencies.log] +//! features = ["kv_unstable"] +//! ``` + +mod error; +mod key; +pub mod source; + +pub mod value; + +pub use self::error::Error; +pub use self::key::{Key, ToKey}; +pub use self::source::{Source, Visitor}; + +#[doc(inline)] +pub use self::value::{ToValue, Value}; diff --git a/bash-5.1/vendor/log/src/kv/source.rs b/bash-5.1/vendor/log/src/kv/source.rs new file mode 100644 index 0000000..e3ecde9 --- /dev/null +++ b/bash-5.1/vendor/log/src/kv/source.rs @@ -0,0 +1,754 @@ +//! Sources for key-value pairs. + +#[cfg(feature = "kv_unstable_sval")] +extern crate sval; + +#[cfg(feature = "kv_unstable_serde")] +extern crate serde; + +use kv::{Error, Key, ToKey, ToValue, Value}; +use std::fmt; + +/// A source of key-value pairs. +/// +/// The source may be a single pair, a set of pairs, or a filter over a set of pairs. +/// Use the [`Visitor`](trait.Visitor.html) trait to inspect the structured data +/// in a source. +pub trait Source { + /// Visit key-value pairs. + /// + /// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs. + /// If the given visitor returns an error then the source may early-return with it, + /// even if there are more key-value pairs. + /// + /// # Implementation notes + /// + /// A source should yield the same key-value pairs to a subsequent visitor unless + /// that visitor itself fails. + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>; + + /// Get the value for a given key. + /// + /// If the key appears multiple times in the source then which key is returned + /// is implementation specific. + /// + /// # Implementation notes + /// + /// A source that can provide a more efficient implementation of this method + /// should override it. + #[cfg(not(test))] + fn get<'v>(&'v self, key: Key) -> Option> { + get_default(self, key) + } + + #[cfg(test)] + fn get<'v>(&'v self, key: Key) -> Option>; + + /// Count the number of key-value pairs that can be visited. + /// + /// # Implementation notes + /// + /// A source that knows the number of key-value pairs upfront may provide a more + /// efficient implementation. + /// + /// A subsequent call to `visit` should yield the same number of key-value pairs + /// to the visitor, unless that visitor fails part way through. + #[cfg(not(test))] + fn count(&self) -> usize { + count_default(self) + } + + #[cfg(test)] + fn count(&self) -> usize; +} + +/// The default implemention of `Source::get` +pub(crate) fn get_default<'v>(source: &'v (impl Source + ?Sized), key: Key) -> Option> { + struct Get<'k, 'v> { + key: Key<'k>, + found: Option>, + } + + impl<'k, 'kvs> Visitor<'kvs> for Get<'k, 'kvs> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + if self.key == key { + self.found = Some(value); + } + + Ok(()) + } + } + + let mut get = Get { key, found: None }; + + let _ = source.visit(&mut get); + get.found +} + +/// The default implementation of `Source::count`. +pub(crate) fn count_default(source: impl Source) -> usize { + struct Count(usize); + + impl<'kvs> Visitor<'kvs> for Count { + fn visit_pair(&mut self, _: Key<'kvs>, _: Value<'kvs>) -> Result<(), Error> { + self.0 += 1; + + Ok(()) + } + } + + let mut count = Count(0); + let _ = source.visit(&mut count); + count.0 +} + +impl<'a, T> Source for &'a T +where + T: Source + ?Sized, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + Source::visit(&**self, visitor) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + Source::get(&**self, key) + } + + fn count(&self) -> usize { + Source::count(&**self) + } +} + +impl Source for (K, V) +where + K: ToKey, + V: ToValue, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + visitor.visit_pair(self.0.to_key(), self.1.to_value()) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + if self.0.to_key() == key { + Some(self.1.to_value()) + } else { + None + } + } + + fn count(&self) -> usize { + 1 + } +} + +impl Source for [S] +where + S: Source, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + for source in self { + source.visit(visitor)?; + } + + Ok(()) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + for source in self { + if let Some(found) = source.get(key.clone()) { + return Some(found); + } + } + + None + } + + fn count(&self) -> usize { + self.len() + } +} + +impl Source for Option +where + S: Source, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + if let Some(ref source) = *self { + source.visit(visitor)?; + } + + Ok(()) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + self.as_ref().and_then(|s| s.get(key)) + } + + fn count(&self) -> usize { + self.as_ref().map(Source::count).unwrap_or(0) + } +} + +/// A visitor for the key-value pairs in a [`Source`](trait.Source.html). +pub trait Visitor<'kvs> { + /// Visit a key-value pair. + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error>; +} + +impl<'a, 'kvs, T> Visitor<'kvs> for &'a mut T +where + T: Visitor<'kvs> + ?Sized, +{ + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + (**self).visit_pair(key, value) + } +} + +impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugMap<'a, 'b> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.entry(&key, &value); + Ok(()) + } +} + +impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugList<'a, 'b> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.entry(&(key, value)); + Ok(()) + } +} + +impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugSet<'a, 'b> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.entry(&(key, value)); + Ok(()) + } +} + +impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugTuple<'a, 'b> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.field(&key); + self.field(&value); + Ok(()) + } +} + +#[cfg(feature = "std")] +mod std_support { + use super::*; + use std::borrow::Borrow; + use std::collections::{BTreeMap, HashMap}; + use std::hash::{BuildHasher, Hash}; + + impl Source for Box + where + S: Source + ?Sized, + { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + Source::visit(&**self, visitor) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + Source::get(&**self, key) + } + + fn count(&self) -> usize { + Source::count(&**self) + } + } + + impl Source for Vec + where + S: Source, + { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + Source::visit(&**self, visitor) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + Source::get(&**self, key) + } + + fn count(&self) -> usize { + Source::count(&**self) + } + } + + impl<'kvs, V> Visitor<'kvs> for Box + where + V: Visitor<'kvs> + ?Sized, + { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + (**self).visit_pair(key, value) + } + } + + impl Source for HashMap + where + K: ToKey + Borrow + Eq + Hash, + V: ToValue, + S: BuildHasher, + { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + for (key, value) in self { + visitor.visit_pair(key.to_key(), value.to_value())?; + } + Ok(()) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + HashMap::get(self, key.as_str()).map(|v| v.to_value()) + } + + fn count(&self) -> usize { + self.len() + } + } + + impl Source for BTreeMap + where + K: ToKey + Borrow + Ord, + V: ToValue, + { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + for (key, value) in self { + visitor.visit_pair(key.to_key(), value.to_value())?; + } + Ok(()) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + BTreeMap::get(self, key.as_str()).map(|v| v.to_value()) + } + + fn count(&self) -> usize { + self.len() + } + } + + #[cfg(test)] + mod tests { + use super::*; + use kv::value::tests::Token; + use std::collections::{BTreeMap, HashMap}; + + #[test] + fn count() { + assert_eq!(1, Source::count(&Box::new(("a", 1)))); + assert_eq!(2, Source::count(&vec![("a", 1), ("b", 2)])); + } + + #[test] + fn get() { + let source = vec![("a", 1), ("b", 2), ("a", 1)]; + assert_eq!( + Token::I64(1), + Source::get(&source, Key::from_str("a")).unwrap().to_token() + ); + + let source = Box::new(Option::None::<(&str, i32)>); + assert!(Source::get(&source, Key::from_str("a")).is_none()); + } + + #[test] + fn hash_map() { + let mut map = HashMap::new(); + map.insert("a", 1); + map.insert("b", 2); + + assert_eq!(2, Source::count(&map)); + assert_eq!( + Token::I64(1), + Source::get(&map, Key::from_str("a")).unwrap().to_token() + ); + } + + #[test] + fn btree_map() { + let mut map = BTreeMap::new(); + map.insert("a", 1); + map.insert("b", 2); + + assert_eq!(2, Source::count(&map)); + assert_eq!( + Token::I64(1), + Source::get(&map, Key::from_str("a")).unwrap().to_token() + ); + } + } +} + +/// The result of calling `Source::as_map`. +pub struct AsMap(S); + +/// Visit this source as a map. +pub fn as_map(source: S) -> AsMap +where + S: Source, +{ + AsMap(source) +} + +impl Source for AsMap +where + S: Source, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + self.0.visit(visitor) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + self.0.get(key) + } + + fn count(&self) -> usize { + self.0.count() + } +} + +impl fmt::Debug for AsMap +where + S: Source, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_map(); + self.0.visit(&mut f).map_err(|_| fmt::Error)?; + f.finish() + } +} + +/// The result of calling `Source::as_list` +pub struct AsList(S); + +/// Visit this source as a list. +pub fn as_list(source: S) -> AsList +where + S: Source, +{ + AsList(source) +} + +impl Source for AsList +where + S: Source, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + self.0.visit(visitor) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + self.0.get(key) + } + + fn count(&self) -> usize { + self.0.count() + } +} + +impl fmt::Debug for AsList +where + S: Source, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_list(); + self.0.visit(&mut f).map_err(|_| fmt::Error)?; + f.finish() + } +} + +#[cfg(feature = "kv_unstable_sval")] +mod sval_support { + use super::*; + + use self::sval::value; + + impl value::Value for AsMap + where + S: Source, + { + fn stream(&self, stream: &mut value::Stream) -> value::Result { + struct StreamVisitor<'a, 'b>(&'a mut value::Stream<'b>); + + impl<'a, 'b, 'kvs> Visitor<'kvs> for StreamVisitor<'a, 'b> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.0 + .map_key(key) + .map_err(|_| Error::msg("failed to stream map key"))?; + self.0 + .map_value(value) + .map_err(|_| Error::msg("failed to stream map value"))?; + Ok(()) + } + } + + stream + .map_begin(Some(self.count())) + .map_err(|_| self::sval::Error::msg("failed to begin map"))?; + + self.visit(&mut StreamVisitor(stream)) + .map_err(|_| self::sval::Error::msg("failed to visit key-values"))?; + + stream + .map_end() + .map_err(|_| self::sval::Error::msg("failed to end map")) + } + } + + impl value::Value for AsList + where + S: Source, + { + fn stream(&self, stream: &mut value::Stream) -> value::Result { + struct StreamVisitor<'a, 'b>(&'a mut value::Stream<'b>); + + impl<'a, 'b, 'kvs> Visitor<'kvs> for StreamVisitor<'a, 'b> { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.0 + .seq_elem((key, value)) + .map_err(|_| Error::msg("failed to stream seq entry"))?; + Ok(()) + } + } + + stream + .seq_begin(Some(self.count())) + .map_err(|_| self::sval::Error::msg("failed to begin seq"))?; + + self.visit(&mut StreamVisitor(stream)) + .map_err(|_| self::sval::Error::msg("failed to visit key-values"))?; + + stream + .seq_end() + .map_err(|_| self::sval::Error::msg("failed to end seq")) + } + } + + #[cfg(test)] + mod tests { + use super::*; + + use self::sval::Value; + + use crate::kv::source; + + #[test] + fn derive_stream() { + #[derive(Value)] + pub struct MyRecordAsMap<'a> { + msg: &'a str, + kvs: source::AsMap<&'a dyn Source>, + } + + #[derive(Value)] + pub struct MyRecordAsList<'a> { + msg: &'a str, + kvs: source::AsList<&'a dyn Source>, + } + } + } +} + +#[cfg(feature = "kv_unstable_serde")] +pub mod as_map { + //! `serde` adapters for serializing a `Source` as a map. + + use super::*; + + use self::serde::{Serialize, Serializer}; + + /// Serialize a `Source` as a map. + pub fn serialize(source: &T, serializer: S) -> Result + where + T: Source, + S: Serializer, + { + as_map(source).serialize(serializer) + } +} + +#[cfg(feature = "kv_unstable_serde")] +pub mod as_list { + //! `serde` adapters for serializing a `Source` as a list. + + use super::*; + + use self::serde::{Serialize, Serializer}; + + /// Serialize a `Source` as a list. + pub fn serialize(source: &T, serializer: S) -> Result + where + T: Source, + S: Serializer, + { + as_list(source).serialize(serializer) + } +} + +#[cfg(feature = "kv_unstable_serde")] +mod serde_support { + use super::*; + + use self::serde::ser::{Error as SerError, Serialize, SerializeMap, SerializeSeq, Serializer}; + + impl Serialize for AsMap + where + T: Source, + { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + struct SerializerVisitor<'a, S>(&'a mut S); + + impl<'a, 'kvs, S> Visitor<'kvs> for SerializerVisitor<'a, S> + where + S: SerializeMap, + { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.0 + .serialize_entry(&key, &value) + .map_err(|_| Error::msg("failed to serialize map entry"))?; + Ok(()) + } + } + + let mut map = serializer.serialize_map(Some(self.count()))?; + + self.visit(&mut SerializerVisitor(&mut map)) + .map_err(|_| S::Error::custom("failed to visit key-values"))?; + + map.end() + } + } + + impl Serialize for AsList + where + T: Source, + { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + struct SerializerVisitor<'a, S>(&'a mut S); + + impl<'a, 'kvs, S> Visitor<'kvs> for SerializerVisitor<'a, S> + where + S: SerializeSeq, + { + fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { + self.0 + .serialize_element(&(key, value)) + .map_err(|_| Error::msg("failed to serialize seq entry"))?; + Ok(()) + } + } + + let mut seq = serializer.serialize_seq(Some(self.count()))?; + + self.visit(&mut SerializerVisitor(&mut seq)) + .map_err(|_| S::Error::custom("failed to visit seq"))?; + + seq.end() + } + } + + #[cfg(test)] + mod tests { + use super::*; + + use self::serde::Serialize; + + use crate::kv::source; + + #[test] + fn derive_serialize() { + #[derive(Serialize)] + pub struct MyRecordAsMap<'a> { + msg: &'a str, + #[serde(flatten)] + #[serde(with = "source::as_map")] + kvs: &'a dyn Source, + } + + #[derive(Serialize)] + pub struct MyRecordAsList<'a> { + msg: &'a str, + #[serde(flatten)] + #[serde(with = "source::as_list")] + kvs: &'a dyn Source, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use kv::value::tests::Token; + + #[test] + fn source_is_object_safe() { + fn _check(_: &dyn Source) {} + } + + #[test] + fn visitor_is_object_safe() { + fn _check(_: &dyn Visitor) {} + } + + #[test] + fn count() { + struct OnePair { + key: &'static str, + value: i32, + } + + impl Source for OnePair { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + visitor.visit_pair(self.key.to_key(), self.value.to_value()) + } + + fn get<'v>(&'v self, key: Key) -> Option> { + get_default(self, key) + } + + fn count(&self) -> usize { + count_default(self) + } + } + + assert_eq!(1, Source::count(&("a", 1))); + assert_eq!(2, Source::count(&[("a", 1), ("b", 2)] as &[_])); + assert_eq!(0, Source::count(&Option::None::<(&str, i32)>)); + assert_eq!(1, Source::count(&OnePair { key: "a", value: 1 })); + } + + #[test] + fn get() { + let source = &[("a", 1), ("b", 2), ("a", 1)] as &[_]; + assert_eq!( + Token::I64(1), + Source::get(source, Key::from_str("a")).unwrap().to_token() + ); + assert_eq!( + Token::I64(2), + Source::get(source, Key::from_str("b")).unwrap().to_token() + ); + assert!(Source::get(&source, Key::from_str("c")).is_none()); + + let source = Option::None::<(&str, i32)>; + assert!(Source::get(&source, Key::from_str("a")).is_none()); + } + + #[test] + fn as_map() { + let _ = crate::kv::source::as_map(("a", 1)); + let _ = crate::kv::source::as_map(&("a", 1) as &dyn Source); + } + + #[test] + fn as_list() { + let _ = crate::kv::source::as_list(("a", 1)); + let _ = crate::kv::source::as_list(&("a", 1) as &dyn Source); + } +} diff --git a/bash-5.1/vendor/log/src/kv/value.rs b/bash-5.1/vendor/log/src/kv/value.rs new file mode 100644 index 0000000..9730f47 --- /dev/null +++ b/bash-5.1/vendor/log/src/kv/value.rs @@ -0,0 +1,1034 @@ +//! Structured values. + +use std::fmt; + +extern crate value_bag; + +#[cfg(feature = "kv_unstable_sval")] +extern crate sval; + +#[cfg(feature = "kv_unstable_serde")] +extern crate serde; + +use self::value_bag::ValueBag; + +pub use kv::Error; + +/// A type that can be converted into a [`Value`](struct.Value.html). +pub trait ToValue { + /// Perform the conversion. + fn to_value(&self) -> Value; +} + +impl<'a, T> ToValue for &'a T +where + T: ToValue + ?Sized, +{ + fn to_value(&self) -> Value { + (**self).to_value() + } +} + +impl<'v> ToValue for Value<'v> { + fn to_value(&self) -> Value { + Value { + inner: self.inner.clone(), + } + } +} + +/// Get a value from a type implementing `std::fmt::Debug`. +#[macro_export] +macro_rules! as_debug { + ($capture:expr) => { + $crate::kv::Value::from_debug(&$capture) + }; +} + +/// Get a value from a type implementing `std::fmt::Display`. +#[macro_export] +macro_rules! as_display { + ($capture:expr) => { + $crate::kv::Value::from_display(&$capture) + }; +} + +/// Get a value from an error. +#[cfg(feature = "kv_unstable_std")] +#[macro_export] +macro_rules! as_error { + ($capture:expr) => { + $crate::kv::Value::from_dyn_error(&$capture) + }; +} + +#[cfg(feature = "kv_unstable_serde")] +/// Get a value from a type implementing `serde::Serialize`. +#[macro_export] +macro_rules! as_serde { + ($capture:expr) => { + $crate::kv::Value::from_serde(&$capture) + }; +} + +/// Get a value from a type implementing `sval::value::Value`. +#[cfg(feature = "kv_unstable_sval")] +#[macro_export] +macro_rules! as_sval { + ($capture:expr) => { + $crate::kv::Value::from_sval(&$capture) + }; +} + +/// A value in a structured key-value pair. +/// +/// # Capturing values +/// +/// There are a few ways to capture a value: +/// +/// - Using the `Value::capture_*` methods. +/// - Using the `Value::from_*` methods. +/// - Using the `ToValue` trait. +/// - Using the standard `From` trait. +/// +/// ## Using the `Value::capture_*` methods +/// +/// `Value` offers a few constructor methods that capture values of different kinds. +/// These methods require a `T: 'static` to support downcasting. +/// +/// ``` +/// use log::kv::Value; +/// +/// let value = Value::capture_debug(&42i32); +/// +/// assert_eq!(Some(42), value.to_i64()); +/// ``` +/// +/// ## Using the `Value::from_*` methods +/// +/// `Value` offers a few constructor methods that capture values of different kinds. +/// These methods don't require `T: 'static`, but can't support downcasting. +/// +/// ``` +/// use log::kv::Value; +/// +/// let value = Value::from_debug(&42i32); +/// +/// assert_eq!(None, value.to_i64()); +/// ``` +/// +/// ## Using the `ToValue` trait +/// +/// The `ToValue` trait can be used to capture values generically. +/// It's the bound used by `Source`. +/// +/// ``` +/// # use log::kv::ToValue; +/// let value = 42i32.to_value(); +/// +/// assert_eq!(Some(42), value.to_i64()); +/// ``` +/// +/// ``` +/// # use std::fmt::Debug; +/// use log::kv::ToValue; +/// +/// let value = (&42i32 as &dyn Debug).to_value(); +/// +/// assert_eq!(None, value.to_i64()); +/// ``` +/// +/// ## Using the standard `From` trait +/// +/// Standard types that implement `ToValue` also implement `From`. +/// +/// ``` +/// use log::kv::Value; +/// +/// let value = Value::from(42i32); +/// +/// assert_eq!(Some(42), value.to_i64()); +/// ``` +pub struct Value<'v> { + inner: ValueBag<'v>, +} + +impl<'v> Value<'v> { + /// Get a value from a type implementing `ToValue`. + pub fn from_any(value: &'v T) -> Self + where + T: ToValue, + { + value.to_value() + } + + /// Get a value from a type implementing `std::fmt::Debug`. + pub fn capture_debug(value: &'v T) -> Self + where + T: fmt::Debug + 'static, + { + Value { + inner: ValueBag::capture_debug(value), + } + } + + /// Get a value from a type implementing `std::fmt::Display`. + pub fn capture_display(value: &'v T) -> Self + where + T: fmt::Display + 'static, + { + Value { + inner: ValueBag::capture_display(value), + } + } + + /// Get a value from an error. + #[cfg(feature = "kv_unstable_std")] + pub fn capture_error(err: &'v T) -> Self + where + T: std::error::Error + 'static, + { + Value { + inner: ValueBag::capture_error(err), + } + } + + #[cfg(feature = "kv_unstable_serde")] + /// Get a value from a type implementing `serde::Serialize`. + pub fn capture_serde(value: &'v T) -> Self + where + T: self::serde::Serialize + 'static, + { + Value { + inner: ValueBag::capture_serde1(value), + } + } + + /// Get a value from a type implementing `sval::value::Value`. + #[cfg(feature = "kv_unstable_sval")] + pub fn capture_sval(value: &'v T) -> Self + where + T: self::sval::value::Value + 'static, + { + Value { + inner: ValueBag::capture_sval1(value), + } + } + + /// Get a value from a type implementing `std::fmt::Debug`. + pub fn from_debug(value: &'v T) -> Self + where + T: fmt::Debug, + { + Value { + inner: ValueBag::from_debug(value), + } + } + + /// Get a value from a type implementing `std::fmt::Display`. + pub fn from_display(value: &'v T) -> Self + where + T: fmt::Display, + { + Value { + inner: ValueBag::from_display(value), + } + } + + /// Get a value from a type implementing `serde::Serialize`. + #[cfg(feature = "kv_unstable_serde")] + pub fn from_serde(value: &'v T) -> Self + where + T: self::serde::Serialize, + { + Value { + inner: ValueBag::from_serde1(value), + } + } + + /// Get a value from a type implementing `sval::value::Value`. + #[cfg(feature = "kv_unstable_sval")] + pub fn from_sval(value: &'v T) -> Self + where + T: self::sval::value::Value, + { + Value { + inner: ValueBag::from_sval1(value), + } + } + + /// Get a value from a dynamic `std::fmt::Debug`. + pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self { + Value { + inner: ValueBag::from_dyn_debug(value), + } + } + + /// Get a value from a dynamic `std::fmt::Display`. + pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self { + Value { + inner: ValueBag::from_dyn_display(value), + } + } + + /// Get a value from a dynamic error. + #[cfg(feature = "kv_unstable_std")] + pub fn from_dyn_error(err: &'v (dyn std::error::Error + 'static)) -> Self { + Value { + inner: ValueBag::from_dyn_error(err), + } + } + + /// Get a value from a type implementing `sval::value::Value`. + #[cfg(feature = "kv_unstable_sval")] + pub fn from_dyn_sval(value: &'v dyn self::sval::value::Value) -> Self { + Value { + inner: ValueBag::from_dyn_sval1(value), + } + } + + /// Get a value from an internal primitive. + fn from_value_bag(value: T) -> Self + where + T: Into>, + { + Value { + inner: value.into(), + } + } + + /// Check whether this value can be downcast to `T`. + pub fn is(&self) -> bool { + self.inner.is::() + } + + /// Try downcast this value to `T`. + pub fn downcast_ref(&self) -> Option<&T> { + self.inner.downcast_ref::() + } + + /// Inspect this value using a simple visitor. + pub fn visit(&self, visitor: impl Visit<'v>) -> Result<(), Error> { + struct Visitor(V); + + impl<'v, V> value_bag::visit::Visit<'v> for Visitor + where + V: Visit<'v>, + { + fn visit_any(&mut self, value: ValueBag) -> Result<(), value_bag::Error> { + self.0 + .visit_any(Value { inner: value }) + .map_err(Error::into_value) + } + + fn visit_u64(&mut self, value: u64) -> Result<(), value_bag::Error> { + self.0.visit_u64(value).map_err(Error::into_value) + } + + fn visit_i64(&mut self, value: i64) -> Result<(), value_bag::Error> { + self.0.visit_i64(value).map_err(Error::into_value) + } + + fn visit_u128(&mut self, value: u128) -> Result<(), value_bag::Error> { + self.0.visit_u128(value).map_err(Error::into_value) + } + + fn visit_i128(&mut self, value: i128) -> Result<(), value_bag::Error> { + self.0.visit_i128(value).map_err(Error::into_value) + } + + fn visit_f64(&mut self, value: f64) -> Result<(), value_bag::Error> { + self.0.visit_f64(value).map_err(Error::into_value) + } + + fn visit_bool(&mut self, value: bool) -> Result<(), value_bag::Error> { + self.0.visit_bool(value).map_err(Error::into_value) + } + + fn visit_str(&mut self, value: &str) -> Result<(), value_bag::Error> { + self.0.visit_str(value).map_err(Error::into_value) + } + + fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), value_bag::Error> { + self.0.visit_borrowed_str(value).map_err(Error::into_value) + } + + fn visit_char(&mut self, value: char) -> Result<(), value_bag::Error> { + self.0.visit_char(value).map_err(Error::into_value) + } + + #[cfg(feature = "kv_unstable_std")] + fn visit_error( + &mut self, + err: &(dyn std::error::Error + 'static), + ) -> Result<(), value_bag::Error> { + self.0.visit_error(err).map_err(Error::into_value) + } + + #[cfg(feature = "kv_unstable_std")] + fn visit_borrowed_error( + &mut self, + err: &'v (dyn std::error::Error + 'static), + ) -> Result<(), value_bag::Error> { + self.0.visit_borrowed_error(err).map_err(Error::into_value) + } + } + + self.inner + .visit(&mut Visitor(visitor)) + .map_err(Error::from_value) + } +} + +impl<'v> fmt::Debug for Value<'v> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.inner, f) + } +} + +impl<'v> fmt::Display for Value<'v> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.inner, f) + } +} + +impl ToValue for dyn fmt::Debug { + fn to_value(&self) -> Value { + Value::from_dyn_debug(self) + } +} + +impl ToValue for dyn fmt::Display { + fn to_value(&self) -> Value { + Value::from_dyn_display(self) + } +} + +#[cfg(feature = "kv_unstable_std")] +impl ToValue for dyn std::error::Error + 'static { + fn to_value(&self) -> Value { + Value::from_dyn_error(self) + } +} + +#[cfg(feature = "kv_unstable_serde")] +impl<'v> self::serde::Serialize for Value<'v> { + fn serialize(&self, s: S) -> Result + where + S: self::serde::Serializer, + { + self.inner.serialize(s) + } +} + +#[cfg(feature = "kv_unstable_sval")] +impl<'v> self::sval::value::Value for Value<'v> { + fn stream(&self, stream: &mut self::sval::value::Stream) -> self::sval::value::Result { + self::sval::value::Value::stream(&self.inner, stream) + } +} + +#[cfg(feature = "kv_unstable_sval")] +impl ToValue for dyn self::sval::value::Value { + fn to_value(&self) -> Value { + Value::from_dyn_sval(self) + } +} + +impl ToValue for str { + fn to_value(&self) -> Value { + Value::from(self) + } +} + +impl ToValue for u128 { + fn to_value(&self) -> Value { + Value::from(self) + } +} + +impl ToValue for i128 { + fn to_value(&self) -> Value { + Value::from(self) + } +} + +impl ToValue for std::num::NonZeroU128 { + fn to_value(&self) -> Value { + Value::from(self) + } +} + +impl ToValue for std::num::NonZeroI128 { + fn to_value(&self) -> Value { + Value::from(self) + } +} + +impl<'v> From<&'v str> for Value<'v> { + fn from(value: &'v str) -> Self { + Value::from_value_bag(value) + } +} + +impl<'v> From<&'v u128> for Value<'v> { + fn from(value: &'v u128) -> Self { + Value::from_value_bag(value) + } +} + +impl<'v> From<&'v i128> for Value<'v> { + fn from(value: &'v i128) -> Self { + Value::from_value_bag(value) + } +} + +impl<'v> From<&'v std::num::NonZeroU128> for Value<'v> { + fn from(v: &'v std::num::NonZeroU128) -> Value<'v> { + // SAFETY: `NonZeroU128` and `u128` have the same ABI + Value::from_value_bag(unsafe { std::mem::transmute::<&std::num::NonZeroU128, &u128>(v) }) + } +} + +impl<'v> From<&'v std::num::NonZeroI128> for Value<'v> { + fn from(v: &'v std::num::NonZeroI128) -> Value<'v> { + // SAFETY: `NonZeroI128` and `i128` have the same ABI + Value::from_value_bag(unsafe { std::mem::transmute::<&std::num::NonZeroI128, &i128>(v) }) + } +} + +impl ToValue for () { + fn to_value(&self) -> Value { + Value::from_value_bag(()) + } +} + +impl ToValue for Option +where + T: ToValue, +{ + fn to_value(&self) -> Value { + match *self { + Some(ref value) => value.to_value(), + None => Value::from_value_bag(()), + } + } +} + +macro_rules! impl_to_value_primitive { + ($($into_ty:ty,)*) => { + $( + impl ToValue for $into_ty { + fn to_value(&self) -> Value { + Value::from(*self) + } + } + + impl<'v> From<$into_ty> for Value<'v> { + fn from(value: $into_ty) -> Self { + Value::from_value_bag(value) + } + } + )* + }; +} + +macro_rules! impl_to_value_nonzero_primitive { + ($($into_ty:ident,)*) => { + $( + impl ToValue for std::num::$into_ty { + fn to_value(&self) -> Value { + Value::from(self.get()) + } + } + + impl<'v> From for Value<'v> { + fn from(value: std::num::$into_ty) -> Self { + Value::from(value.get()) + } + } + )* + }; +} + +macro_rules! impl_value_to_primitive { + ($(#[doc = $doc:tt] $into_name:ident -> $into_ty:ty,)*) => { + impl<'v> Value<'v> { + $( + #[doc = $doc] + pub fn $into_name(&self) -> Option<$into_ty> { + self.inner.$into_name() + } + )* + } + } +} + +impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,]; + +#[rustfmt::skip] +impl_to_value_nonzero_primitive![ + NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, + NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, +]; + +impl_value_to_primitive![ + #[doc = "Try convert this value into a `u64`."] + to_u64 -> u64, + #[doc = "Try convert this value into a `i64`."] + to_i64 -> i64, + #[doc = "Try convert this value into a `u128`."] + to_u128 -> u128, + #[doc = "Try convert this value into a `i128`."] + to_i128 -> i128, + #[doc = "Try convert this value into a `f64`."] + to_f64 -> f64, + #[doc = "Try convert this value into a `char`."] + to_char -> char, + #[doc = "Try convert this value into a `bool`."] + to_bool -> bool, +]; + +impl<'v> Value<'v> { + /// Try convert this value into an error. + #[cfg(feature = "kv_unstable_std")] + pub fn to_borrowed_error(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.inner.to_borrowed_error() + } + + /// Try convert this value into a borrowed string. + pub fn to_borrowed_str(&self) -> Option<&str> { + self.inner.to_borrowed_str() + } +} + +#[cfg(feature = "kv_unstable_std")] +mod std_support { + use super::*; + + use std::borrow::Cow; + + impl ToValue for Box + where + T: ToValue + ?Sized, + { + fn to_value(&self) -> Value { + (**self).to_value() + } + } + + impl ToValue for String { + fn to_value(&self) -> Value { + Value::from(&**self) + } + } + + impl<'v> ToValue for Cow<'v, str> { + fn to_value(&self) -> Value { + Value::from(&**self) + } + } + + impl<'v> Value<'v> { + /// Try convert this value into a string. + pub fn to_str(&self) -> Option> { + self.inner.to_str() + } + } + + impl<'v> From<&'v String> for Value<'v> { + fn from(v: &'v String) -> Self { + Value::from(&**v) + } + } +} + +/// A visitor for a `Value`. +pub trait Visit<'v> { + /// Visit a `Value`. + /// + /// This is the only required method on `Visit` and acts as a fallback for any + /// more specific methods that aren't overridden. + /// The `Value` may be formatted using its `fmt::Debug` or `fmt::Display` implementation, + /// or serialized using its `sval::Value` or `serde::Serialize` implementation. + fn visit_any(&mut self, value: Value) -> Result<(), Error>; + + /// Visit an unsigned integer. + fn visit_u64(&mut self, value: u64) -> Result<(), Error> { + self.visit_any(value.into()) + } + + /// Visit a signed integer. + fn visit_i64(&mut self, value: i64) -> Result<(), Error> { + self.visit_any(value.into()) + } + + /// Visit a big unsigned integer. + fn visit_u128(&mut self, value: u128) -> Result<(), Error> { + self.visit_any((&value).into()) + } + + /// Visit a big signed integer. + fn visit_i128(&mut self, value: i128) -> Result<(), Error> { + self.visit_any((&value).into()) + } + + /// Visit a floating point. + fn visit_f64(&mut self, value: f64) -> Result<(), Error> { + self.visit_any(value.into()) + } + + /// Visit a boolean. + fn visit_bool(&mut self, value: bool) -> Result<(), Error> { + self.visit_any(value.into()) + } + + /// Visit a string. + fn visit_str(&mut self, value: &str) -> Result<(), Error> { + self.visit_any(value.into()) + } + + /// Visit a string. + fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> { + self.visit_str(value) + } + + /// Visit a Unicode character. + fn visit_char(&mut self, value: char) -> Result<(), Error> { + let mut b = [0; 4]; + self.visit_str(&*value.encode_utf8(&mut b)) + } + + /// Visit an error. + #[cfg(feature = "kv_unstable_std")] + fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> { + self.visit_any(Value::from_dyn_error(err)) + } + + /// Visit an error. + #[cfg(feature = "kv_unstable_std")] + fn visit_borrowed_error( + &mut self, + err: &'v (dyn std::error::Error + 'static), + ) -> Result<(), Error> { + self.visit_any(Value::from_dyn_error(err)) + } +} + +impl<'a, 'v, T: ?Sized> Visit<'v> for &'a mut T +where + T: Visit<'v>, +{ + fn visit_any(&mut self, value: Value) -> Result<(), Error> { + (**self).visit_any(value) + } + + fn visit_u64(&mut self, value: u64) -> Result<(), Error> { + (**self).visit_u64(value) + } + + fn visit_i64(&mut self, value: i64) -> Result<(), Error> { + (**self).visit_i64(value) + } + + fn visit_u128(&mut self, value: u128) -> Result<(), Error> { + (**self).visit_u128(value) + } + + fn visit_i128(&mut self, value: i128) -> Result<(), Error> { + (**self).visit_i128(value) + } + + fn visit_f64(&mut self, value: f64) -> Result<(), Error> { + (**self).visit_f64(value) + } + + fn visit_bool(&mut self, value: bool) -> Result<(), Error> { + (**self).visit_bool(value) + } + + fn visit_str(&mut self, value: &str) -> Result<(), Error> { + (**self).visit_str(value) + } + + fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> { + (**self).visit_borrowed_str(value) + } + + fn visit_char(&mut self, value: char) -> Result<(), Error> { + (**self).visit_char(value) + } + + #[cfg(feature = "kv_unstable_std")] + fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> { + (**self).visit_error(err) + } + + #[cfg(feature = "kv_unstable_std")] + fn visit_borrowed_error( + &mut self, + err: &'v (dyn std::error::Error + 'static), + ) -> Result<(), Error> { + (**self).visit_borrowed_error(err) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub(crate) use super::value_bag::test::Token; + + impl<'v> Value<'v> { + pub(crate) fn to_token(&self) -> Token { + self.inner.to_token() + } + } + + fn unsigned() -> impl Iterator> { + vec![ + Value::from(8u8), + Value::from(16u16), + Value::from(32u32), + Value::from(64u64), + Value::from(1usize), + Value::from(std::num::NonZeroU8::new(8).unwrap()), + Value::from(std::num::NonZeroU16::new(16).unwrap()), + Value::from(std::num::NonZeroU32::new(32).unwrap()), + Value::from(std::num::NonZeroU64::new(64).unwrap()), + Value::from(std::num::NonZeroUsize::new(1).unwrap()), + ] + .into_iter() + } + + fn signed() -> impl Iterator> { + vec![ + Value::from(-8i8), + Value::from(-16i16), + Value::from(-32i32), + Value::from(-64i64), + Value::from(-1isize), + Value::from(std::num::NonZeroI8::new(-8).unwrap()), + Value::from(std::num::NonZeroI16::new(-16).unwrap()), + Value::from(std::num::NonZeroI32::new(-32).unwrap()), + Value::from(std::num::NonZeroI64::new(-64).unwrap()), + Value::from(std::num::NonZeroIsize::new(-1).unwrap()), + ] + .into_iter() + } + + fn float() -> impl Iterator> { + vec![Value::from(32.32f32), Value::from(64.64f64)].into_iter() + } + + fn bool() -> impl Iterator> { + vec![Value::from(true), Value::from(false)].into_iter() + } + + fn str() -> impl Iterator> { + vec![Value::from("a string"), Value::from("a loong string")].into_iter() + } + + fn char() -> impl Iterator> { + vec![Value::from('a'), Value::from('⛰')].into_iter() + } + + #[test] + fn test_capture_fmt() { + assert_eq!(Some(42u64), Value::capture_display(&42).to_u64()); + assert_eq!(Some(42u64), Value::capture_debug(&42).to_u64()); + + assert!(Value::from_display(&42).to_u64().is_none()); + assert!(Value::from_debug(&42).to_u64().is_none()); + } + + #[cfg(feature = "kv_unstable_std")] + #[test] + fn test_capture_error() { + let err = std::io::Error::from(std::io::ErrorKind::Other); + + assert!(Value::capture_error(&err).to_borrowed_error().is_some()); + assert!(Value::from_dyn_error(&err).to_borrowed_error().is_some()); + } + + #[cfg(feature = "kv_unstable_serde")] + #[test] + fn test_capture_serde() { + assert_eq!(Some(42u64), Value::capture_serde(&42).to_u64()); + + assert_eq!(Some(42u64), Value::from_serde(&42).to_u64()); + } + + #[cfg(feature = "kv_unstable_sval")] + #[test] + fn test_capture_sval() { + assert_eq!(Some(42u64), Value::capture_sval(&42).to_u64()); + + assert_eq!(Some(42u64), Value::from_sval(&42).to_u64()); + } + + #[test] + fn test_to_value_display() { + assert_eq!(42u64.to_value().to_string(), "42"); + assert_eq!(42i64.to_value().to_string(), "42"); + assert_eq!(42.01f64.to_value().to_string(), "42.01"); + assert_eq!(true.to_value().to_string(), "true"); + assert_eq!('a'.to_value().to_string(), "a"); + assert_eq!("a loong string".to_value().to_string(), "a loong string"); + assert_eq!(Some(true).to_value().to_string(), "true"); + assert_eq!(().to_value().to_string(), "None"); + assert_eq!(Option::None::.to_value().to_string(), "None"); + } + + #[test] + fn test_to_value_structured() { + assert_eq!(42u64.to_value().to_token(), Token::U64(42)); + assert_eq!(42i64.to_value().to_token(), Token::I64(42)); + assert_eq!(42.01f64.to_value().to_token(), Token::F64(42.01)); + assert_eq!(true.to_value().to_token(), Token::Bool(true)); + assert_eq!('a'.to_value().to_token(), Token::Char('a')); + assert_eq!( + "a loong string".to_value().to_token(), + Token::Str("a loong string".into()) + ); + assert_eq!(Some(true).to_value().to_token(), Token::Bool(true)); + assert_eq!(().to_value().to_token(), Token::None); + assert_eq!(Option::None::.to_value().to_token(), Token::None); + } + + #[test] + fn test_to_number() { + for v in unsigned() { + assert!(v.to_u64().is_some()); + assert!(v.to_i64().is_some()); + } + + for v in signed() { + assert!(v.to_i64().is_some()); + } + + for v in unsigned().chain(signed()).chain(float()) { + assert!(v.to_f64().is_some()); + } + + for v in bool().chain(str()).chain(char()) { + assert!(v.to_u64().is_none()); + assert!(v.to_i64().is_none()); + assert!(v.to_f64().is_none()); + } + } + + #[test] + fn test_to_str() { + for v in str() { + assert!(v.to_borrowed_str().is_some()); + + #[cfg(feature = "kv_unstable_std")] + assert!(v.to_str().is_some()); + } + + let short_lived = String::from("short lived"); + let v = Value::from(&*short_lived); + + assert!(v.to_borrowed_str().is_some()); + + #[cfg(feature = "kv_unstable_std")] + assert!(v.to_str().is_some()); + + for v in unsigned().chain(signed()).chain(float()).chain(bool()) { + assert!(v.to_borrowed_str().is_none()); + + #[cfg(feature = "kv_unstable_std")] + assert!(v.to_str().is_none()); + } + } + + #[test] + fn test_to_bool() { + for v in bool() { + assert!(v.to_bool().is_some()); + } + + for v in unsigned() + .chain(signed()) + .chain(float()) + .chain(str()) + .chain(char()) + { + assert!(v.to_bool().is_none()); + } + } + + #[test] + fn test_to_char() { + for v in char() { + assert!(v.to_char().is_some()); + } + + for v in unsigned() + .chain(signed()) + .chain(float()) + .chain(str()) + .chain(bool()) + { + assert!(v.to_char().is_none()); + } + } + + #[test] + fn test_downcast_ref() { + #[derive(Debug)] + struct Foo(u64); + + let v = Value::capture_debug(&Foo(42)); + + assert!(v.is::()); + assert_eq!(42u64, v.downcast_ref::().expect("invalid downcast").0); + } + + #[test] + fn test_visit_integer() { + struct Extract(Option); + + impl<'v> Visit<'v> for Extract { + fn visit_any(&mut self, value: Value) -> Result<(), Error> { + unimplemented!("unexpected value: {:?}", value) + } + + fn visit_u64(&mut self, value: u64) -> Result<(), Error> { + self.0 = Some(value); + + Ok(()) + } + } + + let mut extract = Extract(None); + Value::from(42u64).visit(&mut extract).unwrap(); + + assert_eq!(Some(42), extract.0); + } + + #[test] + fn test_visit_borrowed_str() { + struct Extract<'v>(Option<&'v str>); + + impl<'v> Visit<'v> for Extract<'v> { + fn visit_any(&mut self, value: Value) -> Result<(), Error> { + unimplemented!("unexpected value: {:?}", value) + } + + fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> { + self.0 = Some(value); + + Ok(()) + } + } + + let mut extract = Extract(None); + + let short_lived = String::from("A short-lived string"); + Value::from(&*short_lived).visit(&mut extract).unwrap(); + + assert_eq!(Some("A short-lived string"), extract.0); + } +} diff --git a/bash-5.1/vendor/log/src/lib.rs b/bash-5.1/vendor/log/src/lib.rs new file mode 100644 index 0000000..4ead826 --- /dev/null +++ b/bash-5.1/vendor/log/src/lib.rs @@ -0,0 +1,1971 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A lightweight logging facade. +//! +//! The `log` crate provides a single logging API that abstracts over the +//! actual logging implementation. Libraries can use the logging API provided +//! by this crate, and the consumer of those libraries can choose the logging +//! implementation that is most suitable for its use case. +//! +//! If no logging implementation is selected, the facade falls back to a "noop" +//! implementation that ignores all log messages. The overhead in this case +//! is very small - just an integer load, comparison and jump. +//! +//! A log request consists of a _target_, a _level_, and a _body_. A target is a +//! string which defaults to the module path of the location of the log request, +//! though that default may be overridden. Logger implementations typically use +//! the target to filter requests based on some user configuration. +//! +//! # Usage +//! +//! The basic use of the log crate is through the five logging macros: [`error!`], +//! [`warn!`], [`info!`], [`debug!`] and [`trace!`] +//! where `error!` represents the highest-priority log messages +//! and `trace!` the lowest. The log messages are filtered by configuring +//! the log level to exclude messages with a lower priority. +//! Each of these macros accept format strings similarly to [`println!`]. +//! +//! +//! [`error!`]: ./macro.error.html +//! [`warn!`]: ./macro.warn.html +//! [`info!`]: ./macro.info.html +//! [`debug!`]: ./macro.debug.html +//! [`trace!`]: ./macro.trace.html +//! [`println!`]: https://doc.rust-lang.org/stable/std/macro.println.html +//! +//! ## In libraries +//! +//! Libraries should link only to the `log` crate, and use the provided +//! macros to log whatever information will be useful to downstream consumers. +//! +//! ### Examples +//! +//! ```edition2018 +//! # #[derive(Debug)] pub struct Yak(String); +//! # impl Yak { fn shave(&mut self, _: u32) {} } +//! # fn find_a_razor() -> Result { Ok(1) } +//! use log::{info, warn}; +//! +//! pub fn shave_the_yak(yak: &mut Yak) { +//! info!(target: "yak_events", "Commencing yak shaving for {:?}", yak); +//! +//! loop { +//! match find_a_razor() { +//! Ok(razor) => { +//! info!("Razor located: {}", razor); +//! yak.shave(razor); +//! break; +//! } +//! Err(err) => { +//! warn!("Unable to locate a razor: {}, retrying", err); +//! } +//! } +//! } +//! } +//! # fn main() {} +//! ``` +//! +//! ## In executables +//! +//! Executables should choose a logging implementation and initialize it early in the +//! runtime of the program. Logging implementations will typically include a +//! function to do this. Any log messages generated before +//! the implementation is initialized will be ignored. +//! +//! The executable itself may use the `log` crate to log as well. +//! +//! ### Warning +//! +//! The logging system may only be initialized once. +//! +//! ## Structured logging +//! +//! If you enable the `kv_unstable` feature you can associate structured values +//! with your log records. If we take the example from before, we can include +//! some additional context besides what's in the formatted message: +//! +//! ```edition2018 +//! # #[macro_use] extern crate serde; +//! # #[derive(Debug, Serialize)] pub struct Yak(String); +//! # impl Yak { fn shave(&mut self, _: u32) {} } +//! # fn find_a_razor() -> Result { Ok(1) } +//! # #[cfg(feature = "kv_unstable_serde")] +//! # fn main() { +//! use log::{info, warn, as_serde, as_error}; +//! +//! pub fn shave_the_yak(yak: &mut Yak) { +//! info!(target: "yak_events", yak = as_serde!(yak); "Commencing yak shaving"); +//! +//! loop { +//! match find_a_razor() { +//! Ok(razor) => { +//! info!(razor = razor; "Razor located"); +//! yak.shave(razor); +//! break; +//! } +//! Err(err) => { +//! warn!(err = as_error!(err); "Unable to locate a razor, retrying"); +//! } +//! } +//! } +//! } +//! # } +//! # #[cfg(not(feature = "kv_unstable_serde"))] +//! # fn main() {} +//! ``` +//! +//! # Available logging implementations +//! +//! In order to produce log output executables have to use +//! a logger implementation compatible with the facade. +//! There are many available implementations to choose from, +//! here are some of the most popular ones: +//! +//! * Simple minimal loggers: +//! * [env_logger] +//! * [simple_logger] +//! * [simplelog] +//! * [pretty_env_logger] +//! * [stderrlog] +//! * [flexi_logger] +//! * Complex configurable frameworks: +//! * [log4rs] +//! * [fern] +//! * Adaptors for other facilities: +//! * [syslog] +//! * [slog-stdlog] +//! * [systemd-journal-logger] +//! * [android_log] +//! * [win_dbg_logger] +//! * [db_logger] +//! * For WebAssembly binaries: +//! * [console_log] +//! * For dynamic libraries: +//! * You may need to construct an FFI-safe wrapper over `log` to initialize in your libraries +//! +//! # Implementing a Logger +//! +//! Loggers implement the [`Log`] trait. Here's a very basic example that simply +//! logs all messages at the [`Error`][level_link], [`Warn`][level_link] or +//! [`Info`][level_link] levels to stdout: +//! +//! ```edition2018 +//! use log::{Record, Level, Metadata}; +//! +//! struct SimpleLogger; +//! +//! impl log::Log for SimpleLogger { +//! fn enabled(&self, metadata: &Metadata) -> bool { +//! metadata.level() <= Level::Info +//! } +//! +//! fn log(&self, record: &Record) { +//! if self.enabled(record.metadata()) { +//! println!("{} - {}", record.level(), record.args()); +//! } +//! } +//! +//! fn flush(&self) {} +//! } +//! +//! # fn main() {} +//! ``` +//! +//! Loggers are installed by calling the [`set_logger`] function. The maximum +//! log level also needs to be adjusted via the [`set_max_level`] function. The +//! logging facade uses this as an optimization to improve performance of log +//! messages at levels that are disabled. It's important to set it, as it +//! defaults to [`Off`][filter_link], so no log messages will ever be captured! +//! In the case of our example logger, we'll want to set the maximum log level +//! to [`Info`][filter_link], since we ignore any [`Debug`][level_link] or +//! [`Trace`][level_link] level log messages. A logging implementation should +//! provide a function that wraps a call to [`set_logger`] and +//! [`set_max_level`], handling initialization of the logger: +//! +//! ```edition2018 +//! # use log::{Level, Metadata}; +//! # struct SimpleLogger; +//! # impl log::Log for SimpleLogger { +//! # fn enabled(&self, _: &Metadata) -> bool { false } +//! # fn log(&self, _: &log::Record) {} +//! # fn flush(&self) {} +//! # } +//! # fn main() {} +//! use log::{SetLoggerError, LevelFilter}; +//! +//! static LOGGER: SimpleLogger = SimpleLogger; +//! +//! pub fn init() -> Result<(), SetLoggerError> { +//! log::set_logger(&LOGGER) +//! .map(|()| log::set_max_level(LevelFilter::Info)) +//! } +//! ``` +//! +//! Implementations that adjust their configurations at runtime should take care +//! to adjust the maximum log level as well. +//! +//! # Use with `std` +//! +//! `set_logger` requires you to provide a `&'static Log`, which can be hard to +//! obtain if your logger depends on some runtime configuration. The +//! `set_boxed_logger` function is available with the `std` Cargo feature. It is +//! identical to `set_logger` except that it takes a `Box` rather than a +//! `&'static Log`: +//! +//! ```edition2018 +//! # use log::{Level, LevelFilter, Log, SetLoggerError, Metadata}; +//! # struct SimpleLogger; +//! # impl log::Log for SimpleLogger { +//! # fn enabled(&self, _: &Metadata) -> bool { false } +//! # fn log(&self, _: &log::Record) {} +//! # fn flush(&self) {} +//! # } +//! # fn main() {} +//! # #[cfg(feature = "std")] +//! pub fn init() -> Result<(), SetLoggerError> { +//! log::set_boxed_logger(Box::new(SimpleLogger)) +//! .map(|()| log::set_max_level(LevelFilter::Info)) +//! } +//! ``` +//! +//! # Compile time filters +//! +//! Log levels can be statically disabled at compile time via Cargo features. Log invocations at +//! disabled levels will be skipped and will not even be present in the resulting binary. +//! This level is configured separately for release and debug builds. The features are: +//! +//! * `max_level_off` +//! * `max_level_error` +//! * `max_level_warn` +//! * `max_level_info` +//! * `max_level_debug` +//! * `max_level_trace` +//! * `release_max_level_off` +//! * `release_max_level_error` +//! * `release_max_level_warn` +//! * `release_max_level_info` +//! * `release_max_level_debug` +//! * `release_max_level_trace` +//! +//! These features control the value of the `STATIC_MAX_LEVEL` constant. The logging macros check +//! this value before logging a message. By default, no levels are disabled. +//! +//! Libraries should avoid using the max level features because they're global and can't be changed +//! once they're set. +//! +//! For example, a crate can disable trace level logs in debug builds and trace, debug, and info +//! level logs in release builds with the following configuration: +//! +//! ```toml +//! [dependencies] +//! log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] } +//! ``` +//! # Crate Feature Flags +//! +//! The following crate feature flags are available in addition to the filters. They are +//! configured in your `Cargo.toml`. +//! +//! * `std` allows use of `std` crate instead of the default `core`. Enables using `std::error` and +//! `set_boxed_logger` functionality. +//! * `serde` enables support for serialization and deserialization of `Level` and `LevelFilter`. +//! +//! ```toml +//! [dependencies] +//! log = { version = "0.4", features = ["std", "serde"] } +//! ``` +//! +//! # Version compatibility +//! +//! The 0.3 and 0.4 versions of the `log` crate are almost entirely compatible. Log messages +//! made using `log` 0.3 will forward transparently to a logger implementation using `log` 0.4. Log +//! messages made using `log` 0.4 will forward to a logger implementation using `log` 0.3, but the +//! module path and file name information associated with the message will unfortunately be lost. +//! +//! [`Log`]: trait.Log.html +//! [level_link]: enum.Level.html +//! [filter_link]: enum.LevelFilter.html +//! [`set_logger`]: fn.set_logger.html +//! [`set_max_level`]: fn.set_max_level.html +//! [`try_set_logger_raw`]: fn.try_set_logger_raw.html +//! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html +//! [env_logger]: https://docs.rs/env_logger/*/env_logger/ +//! [simple_logger]: https://github.com/borntyping/rust-simple_logger +//! [simplelog]: https://github.com/drakulix/simplelog.rs +//! [pretty_env_logger]: https://docs.rs/pretty_env_logger/*/pretty_env_logger/ +//! [stderrlog]: https://docs.rs/stderrlog/*/stderrlog/ +//! [flexi_logger]: https://docs.rs/flexi_logger/*/flexi_logger/ +//! [syslog]: https://docs.rs/syslog/*/syslog/ +//! [slog-stdlog]: https://docs.rs/slog-stdlog/*/slog_stdlog/ +//! [log4rs]: https://docs.rs/log4rs/*/log4rs/ +//! [fern]: https://docs.rs/fern/*/fern/ +//! [systemd-journal-logger]: https://docs.rs/systemd-journal-logger/*/systemd_journal_logger/ +//! [android_log]: https://docs.rs/android_log/*/android_log/ +//! [win_dbg_logger]: https://docs.rs/win_dbg_logger/*/win_dbg_logger/ +//! [console_log]: https://docs.rs/console_log/*/console_log/ + +#![doc( + html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://docs.rs/log/0.4.17" +)] +#![warn(missing_docs)] +#![deny(missing_debug_implementations, unconditional_recursion)] +#![cfg_attr(all(not(feature = "std"), not(test)), no_std)] +// When compiled for the rustc compiler itself we want to make sure that this is +// an unstable crate +#![cfg_attr(rustbuild, feature(staged_api, rustc_private))] +#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] + +#[cfg(all(not(feature = "std"), not(test)))] +extern crate core as std; + +#[macro_use] +extern crate cfg_if; + +use std::cmp; +#[cfg(feature = "std")] +use std::error; +use std::fmt; +use std::mem; +use std::str::FromStr; + +#[macro_use] +mod macros; +mod serde; + +#[cfg(feature = "kv_unstable")] +pub mod kv; + +#[cfg(has_atomics)] +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[cfg(not(has_atomics))] +use std::cell::Cell; +#[cfg(not(has_atomics))] +use std::sync::atomic::Ordering; + +#[cfg(not(has_atomics))] +struct AtomicUsize { + v: Cell, +} + +#[cfg(not(has_atomics))] +impl AtomicUsize { + const fn new(v: usize) -> AtomicUsize { + AtomicUsize { v: Cell::new(v) } + } + + fn load(&self, _order: Ordering) -> usize { + self.v.get() + } + + fn store(&self, val: usize, _order: Ordering) { + self.v.set(val) + } + + #[cfg(atomic_cas)] + fn compare_exchange( + &self, + current: usize, + new: usize, + _success: Ordering, + _failure: Ordering, + ) -> Result { + let prev = self.v.get(); + if current == prev { + self.v.set(new); + } + Ok(prev) + } +} + +// Any platform without atomics is unlikely to have multiple cores, so +// writing via Cell will not be a race condition. +#[cfg(not(has_atomics))] +unsafe impl Sync for AtomicUsize {} + +// The LOGGER static holds a pointer to the global logger. It is protected by +// the STATE static which determines whether LOGGER has been initialized yet. +static mut LOGGER: &dyn Log = &NopLogger; + +static STATE: AtomicUsize = AtomicUsize::new(0); + +// There are three different states that we care about: the logger's +// uninitialized, the logger's initializing (set_logger's been called but +// LOGGER hasn't actually been set yet), or the logger's active. +const UNINITIALIZED: usize = 0; +const INITIALIZING: usize = 1; +const INITIALIZED: usize = 2; + +static MAX_LOG_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(0); + +static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"]; + +static SET_LOGGER_ERROR: &str = "attempted to set a logger after the logging system \ + was already initialized"; +static LEVEL_PARSE_ERROR: &str = + "attempted to convert a string that doesn't match an existing log level"; + +/// An enum representing the available verbosity levels of the logger. +/// +/// Typical usage includes: checking if a certain `Level` is enabled with +/// [`log_enabled!`](macro.log_enabled.html), specifying the `Level` of +/// [`log!`](macro.log.html), and comparing a `Level` directly to a +/// [`LevelFilter`](enum.LevelFilter.html). +#[repr(usize)] +#[derive(Copy, Eq, Debug, Hash)] +pub enum Level { + /// The "error" level. + /// + /// Designates very serious errors. + // This way these line up with the discriminants for LevelFilter below + // This works because Rust treats field-less enums the same way as C does: + // https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations + Error = 1, + /// The "warn" level. + /// + /// Designates hazardous situations. + Warn, + /// The "info" level. + /// + /// Designates useful information. + Info, + /// The "debug" level. + /// + /// Designates lower priority information. + Debug, + /// The "trace" level. + /// + /// Designates very low priority, often extremely verbose, information. + Trace, +} + +impl Clone for Level { + #[inline] + fn clone(&self) -> Level { + *self + } +} + +impl PartialEq for Level { + #[inline] + fn eq(&self, other: &Level) -> bool { + *self as usize == *other as usize + } +} + +impl PartialEq for Level { + #[inline] + fn eq(&self, other: &LevelFilter) -> bool { + *self as usize == *other as usize + } +} + +impl PartialOrd for Level { + #[inline] + fn partial_cmp(&self, other: &Level) -> Option { + Some(self.cmp(other)) + } + + #[inline] + fn lt(&self, other: &Level) -> bool { + (*self as usize) < *other as usize + } + + #[inline] + fn le(&self, other: &Level) -> bool { + *self as usize <= *other as usize + } + + #[inline] + fn gt(&self, other: &Level) -> bool { + *self as usize > *other as usize + } + + #[inline] + fn ge(&self, other: &Level) -> bool { + *self as usize >= *other as usize + } +} + +impl PartialOrd for Level { + #[inline] + fn partial_cmp(&self, other: &LevelFilter) -> Option { + Some((*self as usize).cmp(&(*other as usize))) + } + + #[inline] + fn lt(&self, other: &LevelFilter) -> bool { + (*self as usize) < *other as usize + } + + #[inline] + fn le(&self, other: &LevelFilter) -> bool { + *self as usize <= *other as usize + } + + #[inline] + fn gt(&self, other: &LevelFilter) -> bool { + *self as usize > *other as usize + } + + #[inline] + fn ge(&self, other: &LevelFilter) -> bool { + *self as usize >= *other as usize + } +} + +impl Ord for Level { + #[inline] + fn cmp(&self, other: &Level) -> cmp::Ordering { + (*self as usize).cmp(&(*other as usize)) + } +} + +fn ok_or(t: Option, e: E) -> Result { + match t { + Some(t) => Ok(t), + None => Err(e), + } +} + +// Reimplemented here because std::ascii is not available in libcore +fn eq_ignore_ascii_case(a: &str, b: &str) -> bool { + fn to_ascii_uppercase(c: u8) -> u8 { + if c >= b'a' && c <= b'z' { + c - b'a' + b'A' + } else { + c + } + } + + if a.len() == b.len() { + a.bytes() + .zip(b.bytes()) + .all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b)) + } else { + false + } +} + +impl FromStr for Level { + type Err = ParseLevelError; + fn from_str(level: &str) -> Result { + ok_or( + LOG_LEVEL_NAMES + .iter() + .position(|&name| eq_ignore_ascii_case(name, level)) + .into_iter() + .filter(|&idx| idx != 0) + .map(|idx| Level::from_usize(idx).unwrap()) + .next(), + ParseLevelError(()), + ) + } +} + +impl fmt::Display for Level { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.pad(self.as_str()) + } +} + +impl Level { + fn from_usize(u: usize) -> Option { + match u { + 1 => Some(Level::Error), + 2 => Some(Level::Warn), + 3 => Some(Level::Info), + 4 => Some(Level::Debug), + 5 => Some(Level::Trace), + _ => None, + } + } + + /// Returns the most verbose logging level. + #[inline] + pub fn max() -> Level { + Level::Trace + } + + /// Converts the `Level` to the equivalent `LevelFilter`. + #[inline] + pub fn to_level_filter(&self) -> LevelFilter { + LevelFilter::from_usize(*self as usize).unwrap() + } + + /// Returns the string representation of the `Level`. + /// + /// This returns the same string as the `fmt::Display` implementation. + pub fn as_str(&self) -> &'static str { + LOG_LEVEL_NAMES[*self as usize] + } + + /// Iterate through all supported logging levels. + /// + /// The order of iteration is from more severe to less severe log messages. + /// + /// # Examples + /// + /// ``` + /// use log::Level; + /// + /// let mut levels = Level::iter(); + /// + /// assert_eq!(Some(Level::Error), levels.next()); + /// assert_eq!(Some(Level::Trace), levels.last()); + /// ``` + pub fn iter() -> impl Iterator { + (1..6).map(|i| Self::from_usize(i).unwrap()) + } +} + +/// An enum representing the available verbosity level filters of the logger. +/// +/// A `LevelFilter` may be compared directly to a [`Level`]. Use this type +/// to get and set the maximum log level with [`max_level()`] and [`set_max_level`]. +/// +/// [`Level`]: enum.Level.html +/// [`max_level()`]: fn.max_level.html +/// [`set_max_level`]: fn.set_max_level.html +#[repr(usize)] +#[derive(Copy, Eq, Debug, Hash)] +pub enum LevelFilter { + /// A level lower than all log levels. + Off, + /// Corresponds to the `Error` log level. + Error, + /// Corresponds to the `Warn` log level. + Warn, + /// Corresponds to the `Info` log level. + Info, + /// Corresponds to the `Debug` log level. + Debug, + /// Corresponds to the `Trace` log level. + Trace, +} + +// Deriving generates terrible impls of these traits + +impl Clone for LevelFilter { + #[inline] + fn clone(&self) -> LevelFilter { + *self + } +} + +impl PartialEq for LevelFilter { + #[inline] + fn eq(&self, other: &LevelFilter) -> bool { + *self as usize == *other as usize + } +} + +impl PartialEq for LevelFilter { + #[inline] + fn eq(&self, other: &Level) -> bool { + other.eq(self) + } +} + +impl PartialOrd for LevelFilter { + #[inline] + fn partial_cmp(&self, other: &LevelFilter) -> Option { + Some(self.cmp(other)) + } + + #[inline] + fn lt(&self, other: &LevelFilter) -> bool { + (*self as usize) < *other as usize + } + + #[inline] + fn le(&self, other: &LevelFilter) -> bool { + *self as usize <= *other as usize + } + + #[inline] + fn gt(&self, other: &LevelFilter) -> bool { + *self as usize > *other as usize + } + + #[inline] + fn ge(&self, other: &LevelFilter) -> bool { + *self as usize >= *other as usize + } +} + +impl PartialOrd for LevelFilter { + #[inline] + fn partial_cmp(&self, other: &Level) -> Option { + Some((*self as usize).cmp(&(*other as usize))) + } + + #[inline] + fn lt(&self, other: &Level) -> bool { + (*self as usize) < *other as usize + } + + #[inline] + fn le(&self, other: &Level) -> bool { + *self as usize <= *other as usize + } + + #[inline] + fn gt(&self, other: &Level) -> bool { + *self as usize > *other as usize + } + + #[inline] + fn ge(&self, other: &Level) -> bool { + *self as usize >= *other as usize + } +} + +impl Ord for LevelFilter { + #[inline] + fn cmp(&self, other: &LevelFilter) -> cmp::Ordering { + (*self as usize).cmp(&(*other as usize)) + } +} + +impl FromStr for LevelFilter { + type Err = ParseLevelError; + fn from_str(level: &str) -> Result { + ok_or( + LOG_LEVEL_NAMES + .iter() + .position(|&name| eq_ignore_ascii_case(name, level)) + .map(|p| LevelFilter::from_usize(p).unwrap()), + ParseLevelError(()), + ) + } +} + +impl fmt::Display for LevelFilter { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.pad(self.as_str()) + } +} + +impl LevelFilter { + fn from_usize(u: usize) -> Option { + match u { + 0 => Some(LevelFilter::Off), + 1 => Some(LevelFilter::Error), + 2 => Some(LevelFilter::Warn), + 3 => Some(LevelFilter::Info), + 4 => Some(LevelFilter::Debug), + 5 => Some(LevelFilter::Trace), + _ => None, + } + } + + /// Returns the most verbose logging level filter. + #[inline] + pub fn max() -> LevelFilter { + LevelFilter::Trace + } + + /// Converts `self` to the equivalent `Level`. + /// + /// Returns `None` if `self` is `LevelFilter::Off`. + #[inline] + pub fn to_level(&self) -> Option { + Level::from_usize(*self as usize) + } + + /// Returns the string representation of the `LevelFilter`. + /// + /// This returns the same string as the `fmt::Display` implementation. + pub fn as_str(&self) -> &'static str { + LOG_LEVEL_NAMES[*self as usize] + } + + /// Iterate through all supported filtering levels. + /// + /// The order of iteration is from less to more verbose filtering. + /// + /// # Examples + /// + /// ``` + /// use log::LevelFilter; + /// + /// let mut levels = LevelFilter::iter(); + /// + /// assert_eq!(Some(LevelFilter::Off), levels.next()); + /// assert_eq!(Some(LevelFilter::Trace), levels.last()); + /// ``` + pub fn iter() -> impl Iterator { + (0..6).map(|i| Self::from_usize(i).unwrap()) + } +} + +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] +enum MaybeStaticStr<'a> { + Static(&'static str), + Borrowed(&'a str), +} + +impl<'a> MaybeStaticStr<'a> { + #[inline] + fn get(&self) -> &'a str { + match *self { + MaybeStaticStr::Static(s) => s, + MaybeStaticStr::Borrowed(s) => s, + } + } +} + +/// The "payload" of a log message. +/// +/// # Use +/// +/// `Record` structures are passed as parameters to the [`log`][method.log] +/// method of the [`Log`] trait. Logger implementors manipulate these +/// structures in order to display log messages. `Record`s are automatically +/// created by the [`log!`] macro and so are not seen by log users. +/// +/// Note that the [`level()`] and [`target()`] accessors are equivalent to +/// `self.metadata().level()` and `self.metadata().target()` respectively. +/// These methods are provided as a convenience for users of this structure. +/// +/// # Example +/// +/// The following example shows a simple logger that displays the level, +/// module path, and message of any `Record` that is passed to it. +/// +/// ```edition2018 +/// struct SimpleLogger; +/// +/// impl log::Log for SimpleLogger { +/// fn enabled(&self, metadata: &log::Metadata) -> bool { +/// true +/// } +/// +/// fn log(&self, record: &log::Record) { +/// if !self.enabled(record.metadata()) { +/// return; +/// } +/// +/// println!("{}:{} -- {}", +/// record.level(), +/// record.target(), +/// record.args()); +/// } +/// fn flush(&self) {} +/// } +/// ``` +/// +/// [method.log]: trait.Log.html#tymethod.log +/// [`Log`]: trait.Log.html +/// [`log!`]: macro.log.html +/// [`level()`]: struct.Record.html#method.level +/// [`target()`]: struct.Record.html#method.target +#[derive(Clone, Debug)] +pub struct Record<'a> { + metadata: Metadata<'a>, + args: fmt::Arguments<'a>, + module_path: Option>, + file: Option>, + line: Option, + #[cfg(feature = "kv_unstable")] + key_values: KeyValues<'a>, +} + +// This wrapper type is only needed so we can +// `#[derive(Debug)]` on `Record`. It also +// provides a useful `Debug` implementation for +// the underlying `Source`. +#[cfg(feature = "kv_unstable")] +#[derive(Clone)] +struct KeyValues<'a>(&'a dyn kv::Source); + +#[cfg(feature = "kv_unstable")] +impl<'a> fmt::Debug for KeyValues<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut visitor = f.debug_map(); + self.0.visit(&mut visitor).map_err(|_| fmt::Error)?; + visitor.finish() + } +} + +impl<'a> Record<'a> { + /// Returns a new builder. + #[inline] + pub fn builder() -> RecordBuilder<'a> { + RecordBuilder::new() + } + + /// The message body. + #[inline] + pub fn args(&self) -> &fmt::Arguments<'a> { + &self.args + } + + /// Metadata about the log directive. + #[inline] + pub fn metadata(&self) -> &Metadata<'a> { + &self.metadata + } + + /// The verbosity level of the message. + #[inline] + pub fn level(&self) -> Level { + self.metadata.level() + } + + /// The name of the target of the directive. + #[inline] + pub fn target(&self) -> &'a str { + self.metadata.target() + } + + /// The module path of the message. + #[inline] + pub fn module_path(&self) -> Option<&'a str> { + self.module_path.map(|s| s.get()) + } + + /// The module path of the message, if it is a `'static` string. + #[inline] + pub fn module_path_static(&self) -> Option<&'static str> { + match self.module_path { + Some(MaybeStaticStr::Static(s)) => Some(s), + _ => None, + } + } + + /// The source file containing the message. + #[inline] + pub fn file(&self) -> Option<&'a str> { + self.file.map(|s| s.get()) + } + + /// The module path of the message, if it is a `'static` string. + #[inline] + pub fn file_static(&self) -> Option<&'static str> { + match self.file { + Some(MaybeStaticStr::Static(s)) => Some(s), + _ => None, + } + } + + /// The line containing the message. + #[inline] + pub fn line(&self) -> Option { + self.line + } + + /// The structured key-value pairs associated with the message. + #[cfg(feature = "kv_unstable")] + #[inline] + pub fn key_values(&self) -> &dyn kv::Source { + self.key_values.0 + } + + /// Create a new [`RecordBuilder`](struct.RecordBuilder.html) based on this record. + #[cfg(feature = "kv_unstable")] + #[inline] + pub fn to_builder(&self) -> RecordBuilder { + RecordBuilder { + record: Record { + metadata: Metadata { + level: self.metadata.level, + target: self.metadata.target, + }, + args: self.args, + module_path: self.module_path, + file: self.file, + line: self.line, + key_values: self.key_values.clone(), + }, + } + } +} + +/// Builder for [`Record`](struct.Record.html). +/// +/// Typically should only be used by log library creators or for testing and "shim loggers". +/// The `RecordBuilder` can set the different parameters of `Record` object, and returns +/// the created object when `build` is called. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::{Level, Record}; +/// +/// let record = Record::builder() +/// .args(format_args!("Error!")) +/// .level(Level::Error) +/// .target("myApp") +/// .file(Some("server.rs")) +/// .line(Some(144)) +/// .module_path(Some("server")) +/// .build(); +/// ``` +/// +/// Alternatively, use [`MetadataBuilder`](struct.MetadataBuilder.html): +/// +/// ```edition2018 +/// use log::{Record, Level, MetadataBuilder}; +/// +/// let error_metadata = MetadataBuilder::new() +/// .target("myApp") +/// .level(Level::Error) +/// .build(); +/// +/// let record = Record::builder() +/// .metadata(error_metadata) +/// .args(format_args!("Error!")) +/// .line(Some(433)) +/// .file(Some("app.rs")) +/// .module_path(Some("server")) +/// .build(); +/// ``` +#[derive(Debug)] +pub struct RecordBuilder<'a> { + record: Record<'a>, +} + +impl<'a> RecordBuilder<'a> { + /// Construct new `RecordBuilder`. + /// + /// The default options are: + /// + /// - `args`: [`format_args!("")`] + /// - `metadata`: [`Metadata::builder().build()`] + /// - `module_path`: `None` + /// - `file`: `None` + /// - `line`: `None` + /// + /// [`format_args!("")`]: https://doc.rust-lang.org/std/macro.format_args.html + /// [`Metadata::builder().build()`]: struct.MetadataBuilder.html#method.build + #[inline] + pub fn new() -> RecordBuilder<'a> { + RecordBuilder { + record: Record { + args: format_args!(""), + metadata: Metadata::builder().build(), + module_path: None, + file: None, + line: None, + #[cfg(feature = "kv_unstable")] + key_values: KeyValues(&Option::None::<(kv::Key, kv::Value)>), + }, + } + } + + /// Set [`args`](struct.Record.html#method.args). + #[inline] + pub fn args(&mut self, args: fmt::Arguments<'a>) -> &mut RecordBuilder<'a> { + self.record.args = args; + self + } + + /// Set [`metadata`](struct.Record.html#method.metadata). Construct a `Metadata` object with [`MetadataBuilder`](struct.MetadataBuilder.html). + #[inline] + pub fn metadata(&mut self, metadata: Metadata<'a>) -> &mut RecordBuilder<'a> { + self.record.metadata = metadata; + self + } + + /// Set [`Metadata::level`](struct.Metadata.html#method.level). + #[inline] + pub fn level(&mut self, level: Level) -> &mut RecordBuilder<'a> { + self.record.metadata.level = level; + self + } + + /// Set [`Metadata::target`](struct.Metadata.html#method.target) + #[inline] + pub fn target(&mut self, target: &'a str) -> &mut RecordBuilder<'a> { + self.record.metadata.target = target; + self + } + + /// Set [`module_path`](struct.Record.html#method.module_path) + #[inline] + pub fn module_path(&mut self, path: Option<&'a str>) -> &mut RecordBuilder<'a> { + self.record.module_path = path.map(MaybeStaticStr::Borrowed); + self + } + + /// Set [`module_path`](struct.Record.html#method.module_path) to a `'static` string + #[inline] + pub fn module_path_static(&mut self, path: Option<&'static str>) -> &mut RecordBuilder<'a> { + self.record.module_path = path.map(MaybeStaticStr::Static); + self + } + + /// Set [`file`](struct.Record.html#method.file) + #[inline] + pub fn file(&mut self, file: Option<&'a str>) -> &mut RecordBuilder<'a> { + self.record.file = file.map(MaybeStaticStr::Borrowed); + self + } + + /// Set [`file`](struct.Record.html#method.file) to a `'static` string. + #[inline] + pub fn file_static(&mut self, file: Option<&'static str>) -> &mut RecordBuilder<'a> { + self.record.file = file.map(MaybeStaticStr::Static); + self + } + + /// Set [`line`](struct.Record.html#method.line) + #[inline] + pub fn line(&mut self, line: Option) -> &mut RecordBuilder<'a> { + self.record.line = line; + self + } + + /// Set [`key_values`](struct.Record.html#method.key_values) + #[cfg(feature = "kv_unstable")] + #[inline] + pub fn key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a> { + self.record.key_values = KeyValues(kvs); + self + } + + /// Invoke the builder and return a `Record` + #[inline] + pub fn build(&self) -> Record<'a> { + self.record.clone() + } +} + +/// Metadata about a log message. +/// +/// # Use +/// +/// `Metadata` structs are created when users of the library use +/// logging macros. +/// +/// They are consumed by implementations of the `Log` trait in the +/// `enabled` method. +/// +/// `Record`s use `Metadata` to determine the log message's severity +/// and target. +/// +/// Users should use the `log_enabled!` macro in their code to avoid +/// constructing expensive log messages. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::{Record, Level, Metadata}; +/// +/// struct MyLogger; +/// +/// impl log::Log for MyLogger { +/// fn enabled(&self, metadata: &Metadata) -> bool { +/// metadata.level() <= Level::Info +/// } +/// +/// fn log(&self, record: &Record) { +/// if self.enabled(record.metadata()) { +/// println!("{} - {}", record.level(), record.args()); +/// } +/// } +/// fn flush(&self) {} +/// } +/// +/// # fn main(){} +/// ``` +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] +pub struct Metadata<'a> { + level: Level, + target: &'a str, +} + +impl<'a> Metadata<'a> { + /// Returns a new builder. + #[inline] + pub fn builder() -> MetadataBuilder<'a> { + MetadataBuilder::new() + } + + /// The verbosity level of the message. + #[inline] + pub fn level(&self) -> Level { + self.level + } + + /// The name of the target of the directive. + #[inline] + pub fn target(&self) -> &'a str { + self.target + } +} + +/// Builder for [`Metadata`](struct.Metadata.html). +/// +/// Typically should only be used by log library creators or for testing and "shim loggers". +/// The `MetadataBuilder` can set the different parameters of a `Metadata` object, and returns +/// the created object when `build` is called. +/// +/// # Example +/// +/// ```edition2018 +/// let target = "myApp"; +/// use log::{Level, MetadataBuilder}; +/// let metadata = MetadataBuilder::new() +/// .level(Level::Debug) +/// .target(target) +/// .build(); +/// ``` +#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] +pub struct MetadataBuilder<'a> { + metadata: Metadata<'a>, +} + +impl<'a> MetadataBuilder<'a> { + /// Construct a new `MetadataBuilder`. + /// + /// The default options are: + /// + /// - `level`: `Level::Info` + /// - `target`: `""` + #[inline] + pub fn new() -> MetadataBuilder<'a> { + MetadataBuilder { + metadata: Metadata { + level: Level::Info, + target: "", + }, + } + } + + /// Setter for [`level`](struct.Metadata.html#method.level). + #[inline] + pub fn level(&mut self, arg: Level) -> &mut MetadataBuilder<'a> { + self.metadata.level = arg; + self + } + + /// Setter for [`target`](struct.Metadata.html#method.target). + #[inline] + pub fn target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a> { + self.metadata.target = target; + self + } + + /// Returns a `Metadata` object. + #[inline] + pub fn build(&self) -> Metadata<'a> { + self.metadata.clone() + } +} + +/// A trait encapsulating the operations required of a logger. +pub trait Log: Sync + Send { + /// Determines if a log message with the specified metadata would be + /// logged. + /// + /// This is used by the `log_enabled!` macro to allow callers to avoid + /// expensive computation of log message arguments if the message would be + /// discarded anyway. + /// + /// # For implementors + /// + /// This method isn't called automatically by the `log!` macros. + /// It's up to an implementation of the `Log` trait to call `enabled` in its own + /// `log` method implementation to guarantee that filtering is applied. + fn enabled(&self, metadata: &Metadata) -> bool; + + /// Logs the `Record`. + /// + /// # For implementors + /// + /// Note that `enabled` is *not* necessarily called before this method. + /// Implementations of `log` should perform all necessary filtering + /// internally. + fn log(&self, record: &Record); + + /// Flushes any buffered records. + fn flush(&self); +} + +// Just used as a dummy initial value for LOGGER +struct NopLogger; + +impl Log for NopLogger { + fn enabled(&self, _: &Metadata) -> bool { + false + } + + fn log(&self, _: &Record) {} + fn flush(&self) {} +} + +impl Log for &'_ T +where + T: ?Sized + Log, +{ + fn enabled(&self, metadata: &Metadata) -> bool { + (**self).enabled(metadata) + } + + fn log(&self, record: &Record) { + (**self).log(record) + } + fn flush(&self) { + (**self).flush() + } +} + +#[cfg(feature = "std")] +impl Log for std::boxed::Box +where + T: ?Sized + Log, +{ + fn enabled(&self, metadata: &Metadata) -> bool { + self.as_ref().enabled(metadata) + } + + fn log(&self, record: &Record) { + self.as_ref().log(record) + } + fn flush(&self) { + self.as_ref().flush() + } +} + +#[cfg(feature = "std")] +impl Log for std::sync::Arc +where + T: ?Sized + Log, +{ + fn enabled(&self, metadata: &Metadata) -> bool { + self.as_ref().enabled(metadata) + } + + fn log(&self, record: &Record) { + self.as_ref().log(record) + } + fn flush(&self) { + self.as_ref().flush() + } +} + +/// Sets the global maximum log level. +/// +/// Generally, this should only be called by the active logging implementation. +/// +/// Note that `Trace` is the maximum level, because it provides the maximum amount of detail in the emitted logs. +#[inline] +pub fn set_max_level(level: LevelFilter) { + MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::Relaxed) +} + +/// Returns the current maximum log level. +/// +/// The [`log!`], [`error!`], [`warn!`], [`info!`], [`debug!`], and [`trace!`] macros check +/// this value and discard any message logged at a higher level. The maximum +/// log level is set by the [`set_max_level`] function. +/// +/// [`log!`]: macro.log.html +/// [`error!`]: macro.error.html +/// [`warn!`]: macro.warn.html +/// [`info!`]: macro.info.html +/// [`debug!`]: macro.debug.html +/// [`trace!`]: macro.trace.html +/// [`set_max_level`]: fn.set_max_level.html +#[inline(always)] +pub fn max_level() -> LevelFilter { + // Since `LevelFilter` is `repr(usize)`, + // this transmute is sound if and only if `MAX_LOG_LEVEL_FILTER` + // is set to a usize that is a valid discriminant for `LevelFilter`. + // Since `MAX_LOG_LEVEL_FILTER` is private, the only time it's set + // is by `set_max_level` above, i.e. by casting a `LevelFilter` to `usize`. + // So any usize stored in `MAX_LOG_LEVEL_FILTER` is a valid discriminant. + unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) } +} + +/// Sets the global logger to a `Box`. +/// +/// This is a simple convenience wrapper over `set_logger`, which takes a +/// `Box` rather than a `&'static Log`. See the documentation for +/// [`set_logger`] for more details. +/// +/// Requires the `std` feature. +/// +/// # Errors +/// +/// An error is returned if a logger has already been set. +/// +/// [`set_logger`]: fn.set_logger.html +#[cfg(all(feature = "std", atomic_cas))] +pub fn set_boxed_logger(logger: Box) -> Result<(), SetLoggerError> { + set_logger_inner(|| Box::leak(logger)) +} + +/// Sets the global logger to a `&'static Log`. +/// +/// This function may only be called once in the lifetime of a program. Any log +/// events that occur before the call to `set_logger` completes will be ignored. +/// +/// This function does not typically need to be called manually. Logger +/// implementations should provide an initialization method that installs the +/// logger internally. +/// +/// # Availability +/// +/// This method is available even when the `std` feature is disabled. However, +/// it is currently unavailable on `thumbv6` targets, which lack support for +/// some atomic operations which are used by this function. Even on those +/// targets, [`set_logger_racy`] will be available. +/// +/// # Errors +/// +/// An error is returned if a logger has already been set. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::{error, info, warn, Record, Level, Metadata, LevelFilter}; +/// +/// static MY_LOGGER: MyLogger = MyLogger; +/// +/// struct MyLogger; +/// +/// impl log::Log for MyLogger { +/// fn enabled(&self, metadata: &Metadata) -> bool { +/// metadata.level() <= Level::Info +/// } +/// +/// fn log(&self, record: &Record) { +/// if self.enabled(record.metadata()) { +/// println!("{} - {}", record.level(), record.args()); +/// } +/// } +/// fn flush(&self) {} +/// } +/// +/// # fn main(){ +/// log::set_logger(&MY_LOGGER).unwrap(); +/// log::set_max_level(LevelFilter::Info); +/// +/// info!("hello log"); +/// warn!("warning"); +/// error!("oops"); +/// # } +/// ``` +/// +/// [`set_logger_racy`]: fn.set_logger_racy.html +#[cfg(atomic_cas)] +pub fn set_logger(logger: &'static dyn Log) -> Result<(), SetLoggerError> { + set_logger_inner(|| logger) +} + +#[cfg(atomic_cas)] +fn set_logger_inner(make_logger: F) -> Result<(), SetLoggerError> +where + F: FnOnce() -> &'static dyn Log, +{ + let old_state = match STATE.compare_exchange( + UNINITIALIZED, + INITIALIZING, + Ordering::SeqCst, + Ordering::SeqCst, + ) { + Ok(s) | Err(s) => s, + }; + match old_state { + UNINITIALIZED => { + unsafe { + LOGGER = make_logger(); + } + STATE.store(INITIALIZED, Ordering::SeqCst); + Ok(()) + } + INITIALIZING => { + while STATE.load(Ordering::SeqCst) == INITIALIZING { + // TODO: replace with `hint::spin_loop` once MSRV is 1.49.0. + #[allow(deprecated)] + std::sync::atomic::spin_loop_hint(); + } + Err(SetLoggerError(())) + } + _ => Err(SetLoggerError(())), + } +} + +/// A thread-unsafe version of [`set_logger`]. +/// +/// This function is available on all platforms, even those that do not have +/// support for atomics that is needed by [`set_logger`]. +/// +/// In almost all cases, [`set_logger`] should be preferred. +/// +/// # Safety +/// +/// This function is only safe to call when no other logger initialization +/// function is called while this function still executes. +/// +/// This can be upheld by (for example) making sure that **there are no other +/// threads**, and (on embedded) that **interrupts are disabled**. +/// +/// It is safe to use other logging functions while this function runs +/// (including all logging macros). +/// +/// [`set_logger`]: fn.set_logger.html +pub unsafe fn set_logger_racy(logger: &'static dyn Log) -> Result<(), SetLoggerError> { + match STATE.load(Ordering::SeqCst) { + UNINITIALIZED => { + LOGGER = logger; + STATE.store(INITIALIZED, Ordering::SeqCst); + Ok(()) + } + INITIALIZING => { + // This is just plain UB, since we were racing another initialization function + unreachable!("set_logger_racy must not be used with other initialization functions") + } + _ => Err(SetLoggerError(())), + } +} + +/// The type returned by [`set_logger`] if [`set_logger`] has already been called. +/// +/// [`set_logger`]: fn.set_logger.html +#[allow(missing_copy_implementations)] +#[derive(Debug)] +pub struct SetLoggerError(()); + +impl fmt::Display for SetLoggerError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(SET_LOGGER_ERROR) + } +} + +// The Error trait is not available in libcore +#[cfg(feature = "std")] +impl error::Error for SetLoggerError {} + +/// The type returned by [`from_str`] when the string doesn't match any of the log levels. +/// +/// [`from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str +#[allow(missing_copy_implementations)] +#[derive(Debug, PartialEq)] +pub struct ParseLevelError(()); + +impl fmt::Display for ParseLevelError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(LEVEL_PARSE_ERROR) + } +} + +// The Error trait is not available in libcore +#[cfg(feature = "std")] +impl error::Error for ParseLevelError {} + +/// Returns a reference to the logger. +/// +/// If a logger has not been set, a no-op implementation is returned. +pub fn logger() -> &'static dyn Log { + if STATE.load(Ordering::SeqCst) != INITIALIZED { + static NOP: NopLogger = NopLogger; + &NOP + } else { + unsafe { LOGGER } + } +} + +// WARNING: this is not part of the crate's public API and is subject to change at any time +#[doc(hidden)] +#[cfg(not(feature = "kv_unstable"))] +pub fn __private_api_log( + args: fmt::Arguments, + level: Level, + &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), + kvs: Option<&[(&str, &str)]>, +) { + if kvs.is_some() { + panic!( + "key-value support is experimental and must be enabled using the `kv_unstable` feature" + ) + } + + logger().log( + &Record::builder() + .args(args) + .level(level) + .target(target) + .module_path_static(Some(module_path)) + .file_static(Some(file)) + .line(Some(line)) + .build(), + ); +} + +// WARNING: this is not part of the crate's public API and is subject to change at any time +#[doc(hidden)] +#[cfg(feature = "kv_unstable")] +pub fn __private_api_log( + args: fmt::Arguments, + level: Level, + &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), + kvs: Option<&[(&str, &dyn kv::ToValue)]>, +) { + logger().log( + &Record::builder() + .args(args) + .level(level) + .target(target) + .module_path_static(Some(module_path)) + .file_static(Some(file)) + .line(Some(line)) + .key_values(&kvs) + .build(), + ); +} + +// WARNING: this is not part of the crate's public API and is subject to change at any time +#[doc(hidden)] +pub fn __private_api_enabled(level: Level, target: &str) -> bool { + logger().enabled(&Metadata::builder().level(level).target(target).build()) +} + +// WARNING: this is not part of the crate's public API and is subject to change at any time +#[doc(hidden)] +pub mod __private_api { + pub use std::option::Option; +} + +/// The statically resolved maximum log level. +/// +/// See the crate level documentation for information on how to configure this. +/// +/// This value is checked by the log macros, but not by the `Log`ger returned by +/// the [`logger`] function. Code that manually calls functions on that value +/// should compare the level against this value. +/// +/// [`logger`]: fn.logger.html +pub const STATIC_MAX_LEVEL: LevelFilter = MAX_LEVEL_INNER; + +cfg_if! { + if #[cfg(all(not(debug_assertions), feature = "release_max_level_off"))] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Off; + } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_error"))] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Error; + } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_warn"))] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Warn; + } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_info"))] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Info; + } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_debug"))] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Debug; + } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_trace"))] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Trace; + } else if #[cfg(feature = "max_level_off")] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Off; + } else if #[cfg(feature = "max_level_error")] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Error; + } else if #[cfg(feature = "max_level_warn")] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Warn; + } else if #[cfg(feature = "max_level_info")] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Info; + } else if #[cfg(feature = "max_level_debug")] { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Debug; + } else { + const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Trace; + } +} + +#[cfg(test)] +mod tests { + extern crate std; + use super::{Level, LevelFilter, ParseLevelError}; + use tests::std::string::ToString; + + #[test] + fn test_levelfilter_from_str() { + let tests = [ + ("off", Ok(LevelFilter::Off)), + ("error", Ok(LevelFilter::Error)), + ("warn", Ok(LevelFilter::Warn)), + ("info", Ok(LevelFilter::Info)), + ("debug", Ok(LevelFilter::Debug)), + ("trace", Ok(LevelFilter::Trace)), + ("OFF", Ok(LevelFilter::Off)), + ("ERROR", Ok(LevelFilter::Error)), + ("WARN", Ok(LevelFilter::Warn)), + ("INFO", Ok(LevelFilter::Info)), + ("DEBUG", Ok(LevelFilter::Debug)), + ("TRACE", Ok(LevelFilter::Trace)), + ("asdf", Err(ParseLevelError(()))), + ]; + for &(s, ref expected) in &tests { + assert_eq!(expected, &s.parse()); + } + } + + #[test] + fn test_level_from_str() { + let tests = [ + ("OFF", Err(ParseLevelError(()))), + ("error", Ok(Level::Error)), + ("warn", Ok(Level::Warn)), + ("info", Ok(Level::Info)), + ("debug", Ok(Level::Debug)), + ("trace", Ok(Level::Trace)), + ("ERROR", Ok(Level::Error)), + ("WARN", Ok(Level::Warn)), + ("INFO", Ok(Level::Info)), + ("DEBUG", Ok(Level::Debug)), + ("TRACE", Ok(Level::Trace)), + ("asdf", Err(ParseLevelError(()))), + ]; + for &(s, ref expected) in &tests { + assert_eq!(expected, &s.parse()); + } + } + + #[test] + fn test_level_as_str() { + let tests = &[ + (Level::Error, "ERROR"), + (Level::Warn, "WARN"), + (Level::Info, "INFO"), + (Level::Debug, "DEBUG"), + (Level::Trace, "TRACE"), + ]; + for (input, expected) in tests { + assert_eq!(*expected, input.as_str()); + } + } + + #[test] + fn test_level_show() { + assert_eq!("INFO", Level::Info.to_string()); + assert_eq!("ERROR", Level::Error.to_string()); + } + + #[test] + fn test_levelfilter_show() { + assert_eq!("OFF", LevelFilter::Off.to_string()); + assert_eq!("ERROR", LevelFilter::Error.to_string()); + } + + #[test] + fn test_cross_cmp() { + assert!(Level::Debug > LevelFilter::Error); + assert!(LevelFilter::Warn < Level::Trace); + assert!(LevelFilter::Off < Level::Error); + } + + #[test] + fn test_cross_eq() { + assert!(Level::Error == LevelFilter::Error); + assert!(LevelFilter::Off != Level::Error); + assert!(Level::Trace == LevelFilter::Trace); + } + + #[test] + fn test_to_level() { + assert_eq!(Some(Level::Error), LevelFilter::Error.to_level()); + assert_eq!(None, LevelFilter::Off.to_level()); + assert_eq!(Some(Level::Debug), LevelFilter::Debug.to_level()); + } + + #[test] + fn test_to_level_filter() { + assert_eq!(LevelFilter::Error, Level::Error.to_level_filter()); + assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter()); + } + + #[test] + fn test_level_filter_as_str() { + let tests = &[ + (LevelFilter::Off, "OFF"), + (LevelFilter::Error, "ERROR"), + (LevelFilter::Warn, "WARN"), + (LevelFilter::Info, "INFO"), + (LevelFilter::Debug, "DEBUG"), + (LevelFilter::Trace, "TRACE"), + ]; + for (input, expected) in tests { + assert_eq!(*expected, input.as_str()); + } + } + + #[test] + #[cfg(feature = "std")] + fn test_error_trait() { + use super::SetLoggerError; + let e = SetLoggerError(()); + assert_eq!( + &e.to_string(), + "attempted to set a logger after the logging system \ + was already initialized" + ); + } + + #[test] + fn test_metadata_builder() { + use super::MetadataBuilder; + let target = "myApp"; + let metadata_test = MetadataBuilder::new() + .level(Level::Debug) + .target(target) + .build(); + assert_eq!(metadata_test.level(), Level::Debug); + assert_eq!(metadata_test.target(), "myApp"); + } + + #[test] + fn test_metadata_convenience_builder() { + use super::Metadata; + let target = "myApp"; + let metadata_test = Metadata::builder() + .level(Level::Debug) + .target(target) + .build(); + assert_eq!(metadata_test.level(), Level::Debug); + assert_eq!(metadata_test.target(), "myApp"); + } + + #[test] + fn test_record_builder() { + use super::{MetadataBuilder, RecordBuilder}; + let target = "myApp"; + let metadata = MetadataBuilder::new().target(target).build(); + let fmt_args = format_args!("hello"); + let record_test = RecordBuilder::new() + .args(fmt_args) + .metadata(metadata) + .module_path(Some("foo")) + .file(Some("bar")) + .line(Some(30)) + .build(); + assert_eq!(record_test.metadata().target(), "myApp"); + assert_eq!(record_test.module_path(), Some("foo")); + assert_eq!(record_test.file(), Some("bar")); + assert_eq!(record_test.line(), Some(30)); + } + + #[test] + fn test_record_convenience_builder() { + use super::{Metadata, Record}; + let target = "myApp"; + let metadata = Metadata::builder().target(target).build(); + let fmt_args = format_args!("hello"); + let record_test = Record::builder() + .args(fmt_args) + .metadata(metadata) + .module_path(Some("foo")) + .file(Some("bar")) + .line(Some(30)) + .build(); + assert_eq!(record_test.target(), "myApp"); + assert_eq!(record_test.module_path(), Some("foo")); + assert_eq!(record_test.file(), Some("bar")); + assert_eq!(record_test.line(), Some(30)); + } + + #[test] + fn test_record_complete_builder() { + use super::{Level, Record}; + let target = "myApp"; + let record_test = Record::builder() + .module_path(Some("foo")) + .file(Some("bar")) + .line(Some(30)) + .target(target) + .level(Level::Error) + .build(); + assert_eq!(record_test.target(), "myApp"); + assert_eq!(record_test.level(), Level::Error); + assert_eq!(record_test.module_path(), Some("foo")); + assert_eq!(record_test.file(), Some("bar")); + assert_eq!(record_test.line(), Some(30)); + } + + #[test] + #[cfg(feature = "kv_unstable")] + fn test_record_key_values_builder() { + use super::Record; + use kv::{self, Visitor}; + + struct TestVisitor { + seen_pairs: usize, + } + + impl<'kvs> Visitor<'kvs> for TestVisitor { + fn visit_pair( + &mut self, + _: kv::Key<'kvs>, + _: kv::Value<'kvs>, + ) -> Result<(), kv::Error> { + self.seen_pairs += 1; + Ok(()) + } + } + + let kvs: &[(&str, i32)] = &[("a", 1), ("b", 2)]; + let record_test = Record::builder().key_values(&kvs).build(); + + let mut visitor = TestVisitor { seen_pairs: 0 }; + + record_test.key_values().visit(&mut visitor).unwrap(); + + assert_eq!(2, visitor.seen_pairs); + } + + #[test] + #[cfg(feature = "kv_unstable")] + fn test_record_key_values_get_coerce() { + use super::Record; + + let kvs: &[(&str, &str)] = &[("a", "1"), ("b", "2")]; + let record = Record::builder().key_values(&kvs).build(); + + assert_eq!( + "2", + record + .key_values() + .get("b".into()) + .expect("missing key") + .to_borrowed_str() + .expect("invalid value") + ); + } + + // Test that the `impl Log for Foo` blocks work + // This test mostly operates on a type level, so failures will be compile errors + #[test] + fn test_foreign_impl() { + use super::Log; + #[cfg(feature = "std")] + use std::sync::Arc; + + fn assert_is_log() {} + + assert_is_log::<&dyn Log>(); + + #[cfg(feature = "std")] + assert_is_log::>(); + + #[cfg(feature = "std")] + assert_is_log::>(); + + // Assert these statements for all T: Log + ?Sized + #[allow(unused)] + fn forall() { + #[cfg(feature = "std")] + assert_is_log::>(); + + assert_is_log::<&T>(); + + #[cfg(feature = "std")] + assert_is_log::>(); + } + } +} diff --git a/bash-5.1/vendor/log/src/macros.rs b/bash-5.1/vendor/log/src/macros.rs new file mode 100644 index 0000000..f214d0d --- /dev/null +++ b/bash-5.1/vendor/log/src/macros.rs @@ -0,0 +1,280 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// The standard logging macro. +/// +/// This macro will generically log with the specified `Level` and `format!` +/// based argument list. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::{log, Level}; +/// +/// # fn main() { +/// let data = (42, "Forty-two"); +/// let private_data = "private"; +/// +/// log!(Level::Error, "Received errors: {}, {}", data.0, data.1); +/// log!(target: "app_events", Level::Warn, "App warning: {}, {}, {}", +/// data.0, data.1, private_data); +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! log { + // log!(target: "my_target", Level::Info; key1 = 42, key2 = true; "a {} event", "log"); + (target: $target:expr, $lvl:expr, $($key:tt = $value:expr),+; $($arg:tt)+) => ({ + let lvl = $lvl; + if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() { + $crate::__private_api_log( + __log_format_args!($($arg)+), + lvl, + &($target, __log_module_path!(), __log_file!(), __log_line!()), + $crate::__private_api::Option::Some(&[$((__log_key!($key), &$value)),+]) + ); + } + }); + + // log!(target: "my_target", Level::Info; "a {} event", "log"); + (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ + let lvl = $lvl; + if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() { + $crate::__private_api_log( + __log_format_args!($($arg)+), + lvl, + &($target, __log_module_path!(), __log_file!(), __log_line!()), + $crate::__private_api::Option::None, + ); + } + }); + + // log!(Level::Info, "a log event") + ($lvl:expr, $($arg:tt)+) => (log!(target: __log_module_path!(), $lvl, $($arg)+)); +} + +/// Logs a message at the error level. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::error; +/// +/// # fn main() { +/// let (err_info, port) = ("No connection", 22); +/// +/// error!("Error: {} on port {}", err_info, port); +/// error!(target: "app_events", "App Error: {}, Port: {}", err_info, 22); +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! error { + // error!(target: "my_target", key1 = 42, key2 = true; "a {} event", "log") + // error!(target: "my_target", "a {} event", "log") + (target: $target:expr, $($arg:tt)+) => (log!(target: $target, $crate::Level::Error, $($arg)+)); + + // error!("a {} event", "log") + ($($arg:tt)+) => (log!($crate::Level::Error, $($arg)+)) +} + +/// Logs a message at the warn level. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::warn; +/// +/// # fn main() { +/// let warn_description = "Invalid Input"; +/// +/// warn!("Warning! {}!", warn_description); +/// warn!(target: "input_events", "App received warning: {}", warn_description); +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! warn { + // warn!(target: "my_target", key1 = 42, key2 = true; "a {} event", "log") + // warn!(target: "my_target", "a {} event", "log") + (target: $target:expr, $($arg:tt)+) => (log!(target: $target, $crate::Level::Warn, $($arg)+)); + + // warn!("a {} event", "log") + ($($arg:tt)+) => (log!($crate::Level::Warn, $($arg)+)) +} + +/// Logs a message at the info level. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::info; +/// +/// # fn main() { +/// # struct Connection { port: u32, speed: f32 } +/// let conn_info = Connection { port: 40, speed: 3.20 }; +/// +/// info!("Connected to port {} at {} Mb/s", conn_info.port, conn_info.speed); +/// info!(target: "connection_events", "Successfull connection, port: {}, speed: {}", +/// conn_info.port, conn_info.speed); +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! info { + // info!(target: "my_target", key1 = 42, key2 = true; "a {} event", "log") + // info!(target: "my_target", "a {} event", "log") + (target: $target:expr, $($arg:tt)+) => (log!(target: $target, $crate::Level::Info, $($arg)+)); + + // info!("a {} event", "log") + ($($arg:tt)+) => (log!($crate::Level::Info, $($arg)+)) +} + +/// Logs a message at the debug level. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::debug; +/// +/// # fn main() { +/// # struct Position { x: f32, y: f32 } +/// let pos = Position { x: 3.234, y: -1.223 }; +/// +/// debug!("New position: x: {}, y: {}", pos.x, pos.y); +/// debug!(target: "app_events", "New position: x: {}, y: {}", pos.x, pos.y); +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! debug { + // debug!(target: "my_target", key1 = 42, key2 = true; "a {} event", "log") + // debug!(target: "my_target", "a {} event", "log") + (target: $target:expr, $($arg:tt)+) => (log!(target: $target, $crate::Level::Debug, $($arg)+)); + + // debug!("a {} event", "log") + ($($arg:tt)+) => (log!($crate::Level::Debug, $($arg)+)) +} + +/// Logs a message at the trace level. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::trace; +/// +/// # fn main() { +/// # struct Position { x: f32, y: f32 } +/// let pos = Position { x: 3.234, y: -1.223 }; +/// +/// trace!("Position is: x: {}, y: {}", pos.x, pos.y); +/// trace!(target: "app_events", "x is {} and y is {}", +/// if pos.x >= 0.0 { "positive" } else { "negative" }, +/// if pos.y >= 0.0 { "positive" } else { "negative" }); +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! trace { + // trace!(target: "my_target", key1 = 42, key2 = true; "a {} event", "log") + // trace!(target: "my_target", "a {} event", "log") + (target: $target:expr, $($arg:tt)+) => (log!(target: $target, $crate::Level::Trace, $($arg)+)); + + // trace!("a {} event", "log") + ($($arg:tt)+) => (log!($crate::Level::Trace, $($arg)+)) +} + +/// Determines if a message logged at the specified level in that module will +/// be logged. +/// +/// This can be used to avoid expensive computation of log message arguments if +/// the message would be ignored anyway. +/// +/// # Examples +/// +/// ```edition2018 +/// use log::Level::Debug; +/// use log::{debug, log_enabled}; +/// +/// # fn foo() { +/// if log_enabled!(Debug) { +/// let data = expensive_call(); +/// debug!("expensive debug data: {} {}", data.x, data.y); +/// } +/// if log_enabled!(target: "Global", Debug) { +/// let data = expensive_call(); +/// debug!(target: "Global", "expensive debug data: {} {}", data.x, data.y); +/// } +/// # } +/// # struct Data { x: u32, y: u32 } +/// # fn expensive_call() -> Data { Data { x: 0, y: 0 } } +/// # fn main() {} +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! log_enabled { + (target: $target:expr, $lvl:expr) => {{ + let lvl = $lvl; + lvl <= $crate::STATIC_MAX_LEVEL + && lvl <= $crate::max_level() + && $crate::__private_api_enabled(lvl, $target) + }}; + ($lvl:expr) => { + log_enabled!(target: __log_module_path!(), $lvl) + }; +} + +// The log macro above cannot invoke format_args directly because it uses +// local_inner_macros. A format_args invocation there would resolve to +// $crate::format_args which does not exist. Instead invoke format_args here +// outside of local_inner_macros so that it resolves (probably) to +// core::format_args or std::format_args. Same for the several macros that +// follow. +// +// This is a workaround until we drop support for pre-1.30 compilers. At that +// point we can remove use of local_inner_macros, use $crate:: when invoking +// local macros, and invoke format_args directly. +#[doc(hidden)] +#[macro_export] +macro_rules! __log_format_args { + ($($args:tt)*) => { + format_args!($($args)*) + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __log_module_path { + () => { + module_path!() + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __log_file { + () => { + file!() + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __log_line { + () => { + line!() + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __log_key { + // key1 = 42 + ($($args:ident)*) => { + stringify!($($args)*) + }; + // "key1" = 42 + ($($args:expr)*) => { + $($args)* + }; +} diff --git a/bash-5.1/vendor/log/src/serde.rs b/bash-5.1/vendor/log/src/serde.rs new file mode 100644 index 0000000..e691321 --- /dev/null +++ b/bash-5.1/vendor/log/src/serde.rs @@ -0,0 +1,400 @@ +#![cfg(feature = "serde")] + +extern crate serde; +use self::serde::de::{ + Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, Unexpected, VariantAccess, + Visitor, +}; +use self::serde::ser::{Serialize, Serializer}; + +use {Level, LevelFilter, LOG_LEVEL_NAMES}; + +use std::fmt; +use std::str::{self, FromStr}; + +// The Deserialize impls are handwritten to be case insensitive using FromStr. + +impl Serialize for Level { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Level::Error => serializer.serialize_unit_variant("Level", 0, "ERROR"), + Level::Warn => serializer.serialize_unit_variant("Level", 1, "WARN"), + Level::Info => serializer.serialize_unit_variant("Level", 2, "INFO"), + Level::Debug => serializer.serialize_unit_variant("Level", 3, "DEBUG"), + Level::Trace => serializer.serialize_unit_variant("Level", 4, "TRACE"), + } + } +} + +impl<'de> Deserialize<'de> for Level { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct LevelIdentifier; + + impl<'de> Visitor<'de> for LevelIdentifier { + type Value = Level; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("log level") + } + + fn visit_str(self, s: &str) -> Result + where + E: Error, + { + // Case insensitive. + FromStr::from_str(s).map_err(|_| Error::unknown_variant(s, &LOG_LEVEL_NAMES[1..])) + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + let variant = str::from_utf8(value) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(value), &self))?; + + self.visit_str(variant) + } + + fn visit_u64(self, v: u64) -> Result + where + E: Error, + { + let variant = LOG_LEVEL_NAMES[1..] + .get(v as usize) + .ok_or_else(|| Error::invalid_value(Unexpected::Unsigned(v), &self))?; + + self.visit_str(variant) + } + } + + impl<'de> DeserializeSeed<'de> for LevelIdentifier { + type Value = Level; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_identifier(LevelIdentifier) + } + } + + struct LevelEnum; + + impl<'de> Visitor<'de> for LevelEnum { + type Value = Level; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("log level") + } + + fn visit_enum(self, value: A) -> Result + where + A: EnumAccess<'de>, + { + let (level, variant) = value.variant_seed(LevelIdentifier)?; + // Every variant is a unit variant. + variant.unit_variant()?; + Ok(level) + } + } + + deserializer.deserialize_enum("Level", &LOG_LEVEL_NAMES[1..], LevelEnum) + } +} + +impl Serialize for LevelFilter { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + LevelFilter::Off => serializer.serialize_unit_variant("LevelFilter", 0, "OFF"), + LevelFilter::Error => serializer.serialize_unit_variant("LevelFilter", 1, "ERROR"), + LevelFilter::Warn => serializer.serialize_unit_variant("LevelFilter", 2, "WARN"), + LevelFilter::Info => serializer.serialize_unit_variant("LevelFilter", 3, "INFO"), + LevelFilter::Debug => serializer.serialize_unit_variant("LevelFilter", 4, "DEBUG"), + LevelFilter::Trace => serializer.serialize_unit_variant("LevelFilter", 5, "TRACE"), + } + } +} + +impl<'de> Deserialize<'de> for LevelFilter { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct LevelFilterIdentifier; + + impl<'de> Visitor<'de> for LevelFilterIdentifier { + type Value = LevelFilter; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("log level filter") + } + + fn visit_str(self, s: &str) -> Result + where + E: Error, + { + // Case insensitive. + FromStr::from_str(s).map_err(|_| Error::unknown_variant(s, &LOG_LEVEL_NAMES)) + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + let variant = str::from_utf8(value) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(value), &self))?; + + self.visit_str(variant) + } + + fn visit_u64(self, v: u64) -> Result + where + E: Error, + { + let variant = LOG_LEVEL_NAMES + .get(v as usize) + .ok_or_else(|| Error::invalid_value(Unexpected::Unsigned(v), &self))?; + + self.visit_str(variant) + } + } + + impl<'de> DeserializeSeed<'de> for LevelFilterIdentifier { + type Value = LevelFilter; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_identifier(LevelFilterIdentifier) + } + } + + struct LevelFilterEnum; + + impl<'de> Visitor<'de> for LevelFilterEnum { + type Value = LevelFilter; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("log level filter") + } + + fn visit_enum(self, value: A) -> Result + where + A: EnumAccess<'de>, + { + let (level_filter, variant) = value.variant_seed(LevelFilterIdentifier)?; + // Every variant is a unit variant. + variant.unit_variant()?; + Ok(level_filter) + } + } + + deserializer.deserialize_enum("LevelFilter", &LOG_LEVEL_NAMES, LevelFilterEnum) + } +} + +#[cfg(test)] +mod tests { + extern crate serde_test; + use self::serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; + + use {Level, LevelFilter}; + + fn level_token(variant: &'static str) -> Token { + Token::UnitVariant { + name: "Level", + variant: variant, + } + } + + fn level_bytes_tokens(variant: &'static [u8]) -> [Token; 3] { + [ + Token::Enum { name: "Level" }, + Token::Bytes(variant), + Token::Unit, + ] + } + + fn level_variant_tokens(variant: u32) -> [Token; 3] { + [ + Token::Enum { name: "Level" }, + Token::U32(variant), + Token::Unit, + ] + } + + fn level_filter_token(variant: &'static str) -> Token { + Token::UnitVariant { + name: "LevelFilter", + variant: variant, + } + } + + fn level_filter_bytes_tokens(variant: &'static [u8]) -> [Token; 3] { + [ + Token::Enum { + name: "LevelFilter", + }, + Token::Bytes(variant), + Token::Unit, + ] + } + + fn level_filter_variant_tokens(variant: u32) -> [Token; 3] { + [ + Token::Enum { + name: "LevelFilter", + }, + Token::U32(variant), + Token::Unit, + ] + } + + #[test] + fn test_level_ser_de() { + let cases = [ + (Level::Error, [level_token("ERROR")]), + (Level::Warn, [level_token("WARN")]), + (Level::Info, [level_token("INFO")]), + (Level::Debug, [level_token("DEBUG")]), + (Level::Trace, [level_token("TRACE")]), + ]; + + for &(s, expected) in &cases { + assert_tokens(&s, &expected); + } + } + + #[test] + fn test_level_case_insensitive() { + let cases = [ + (Level::Error, [level_token("error")]), + (Level::Warn, [level_token("warn")]), + (Level::Info, [level_token("info")]), + (Level::Debug, [level_token("debug")]), + (Level::Trace, [level_token("trace")]), + ]; + + for &(s, expected) in &cases { + assert_de_tokens(&s, &expected); + } + } + + #[test] + fn test_level_de_bytes() { + let cases = [ + (Level::Error, level_bytes_tokens(b"ERROR")), + (Level::Warn, level_bytes_tokens(b"WARN")), + (Level::Info, level_bytes_tokens(b"INFO")), + (Level::Debug, level_bytes_tokens(b"DEBUG")), + (Level::Trace, level_bytes_tokens(b"TRACE")), + ]; + + for &(value, tokens) in &cases { + assert_de_tokens(&value, &tokens); + } + } + + #[test] + fn test_level_de_variant_index() { + let cases = [ + (Level::Error, level_variant_tokens(0)), + (Level::Warn, level_variant_tokens(1)), + (Level::Info, level_variant_tokens(2)), + (Level::Debug, level_variant_tokens(3)), + (Level::Trace, level_variant_tokens(4)), + ]; + + for &(value, tokens) in &cases { + assert_de_tokens(&value, &tokens); + } + } + + #[test] + fn test_level_de_error() { + let msg = "unknown variant `errorx`, expected one of \ + `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`"; + assert_de_tokens_error::(&[level_token("errorx")], msg); + } + + #[test] + fn test_level_filter_ser_de() { + let cases = [ + (LevelFilter::Off, [level_filter_token("OFF")]), + (LevelFilter::Error, [level_filter_token("ERROR")]), + (LevelFilter::Warn, [level_filter_token("WARN")]), + (LevelFilter::Info, [level_filter_token("INFO")]), + (LevelFilter::Debug, [level_filter_token("DEBUG")]), + (LevelFilter::Trace, [level_filter_token("TRACE")]), + ]; + + for &(s, expected) in &cases { + assert_tokens(&s, &expected); + } + } + + #[test] + fn test_level_filter_case_insensitive() { + let cases = [ + (LevelFilter::Off, [level_filter_token("off")]), + (LevelFilter::Error, [level_filter_token("error")]), + (LevelFilter::Warn, [level_filter_token("warn")]), + (LevelFilter::Info, [level_filter_token("info")]), + (LevelFilter::Debug, [level_filter_token("debug")]), + (LevelFilter::Trace, [level_filter_token("trace")]), + ]; + + for &(s, expected) in &cases { + assert_de_tokens(&s, &expected); + } + } + + #[test] + fn test_level_filter_de_bytes() { + let cases = [ + (LevelFilter::Off, level_filter_bytes_tokens(b"OFF")), + (LevelFilter::Error, level_filter_bytes_tokens(b"ERROR")), + (LevelFilter::Warn, level_filter_bytes_tokens(b"WARN")), + (LevelFilter::Info, level_filter_bytes_tokens(b"INFO")), + (LevelFilter::Debug, level_filter_bytes_tokens(b"DEBUG")), + (LevelFilter::Trace, level_filter_bytes_tokens(b"TRACE")), + ]; + + for &(value, tokens) in &cases { + assert_de_tokens(&value, &tokens); + } + } + + #[test] + fn test_level_filter_de_variant_index() { + let cases = [ + (LevelFilter::Off, level_filter_variant_tokens(0)), + (LevelFilter::Error, level_filter_variant_tokens(1)), + (LevelFilter::Warn, level_filter_variant_tokens(2)), + (LevelFilter::Info, level_filter_variant_tokens(3)), + (LevelFilter::Debug, level_filter_variant_tokens(4)), + (LevelFilter::Trace, level_filter_variant_tokens(5)), + ]; + + for &(value, tokens) in &cases { + assert_de_tokens(&value, &tokens); + } + } + + #[test] + fn test_level_filter_de_error() { + let msg = "unknown variant `errorx`, expected one of \ + `OFF`, `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`"; + assert_de_tokens_error::(&[level_filter_token("errorx")], msg); + } +} diff --git a/bash-5.1/vendor/log/triagebot.toml b/bash-5.1/vendor/log/triagebot.toml new file mode 100644 index 0000000..84659a1 --- /dev/null +++ b/bash-5.1/vendor/log/triagebot.toml @@ -0,0 +1 @@ +[assign] diff --git a/bash-5.1/vendor/memchr-1.0.2/.cargo-checksum.json b/bash-5.1/vendor/memchr-1.0.2/.cargo-checksum.json new file mode 100644 index 0000000..3df40c5 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYING":"01c266bced4a434da0051174d6bee16a4c82cf634e2679b6155d40d75012390f","Cargo.toml":"38694643a2d98dc66c1ea8583b9ee49210e8d92205835e43d9a8cc3216e680fe","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","Makefile":"a45a128685a2ae7d4fa39d310786674417ee113055ef290a11f88002285865fc","README.md":"74e385c51a2402527a61a500d66e509fea97961f15bfffab85040064e576fe31","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","appveyor.yml":"b5c1a28f805854370f24e530df912764a9520f4581b33da090f44cec0eef181c","benches/bench.rs":"87cfb76154c3c322691201c6f5649b37665ed8bf1cf303bca971309a4eef6b61","ctags.rust":"3d128d3cc59f702e68953ba2fe6c3f46bc6991fc575308db060482d5da0c79f3","session.vim":"95cb1d7caf0ff7fbe76ec911988d908ddd883381c925ba64b537695bc9f021c4","src/lib.rs":"98c86c86fd996455d7ec94bdfdcedd3ded3b2a7016480d3474808cfe36d00a63"},"package":"148fab2e51b4f1cfc66da2a7c32981d1d3c083a803978268bb11fe4b86925e7a"} \ No newline at end of file diff --git a/bash-5.1/vendor/memchr-1.0.2/COPYING b/bash-5.1/vendor/memchr-1.0.2/COPYING new file mode 100644 index 0000000..bb9c20a --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/COPYING @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff --git a/bash-5.1/vendor/memchr-1.0.2/Cargo.toml b/bash-5.1/vendor/memchr-1.0.2/Cargo.toml new file mode 100644 index 0000000..2bb28a8 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/Cargo.toml @@ -0,0 +1,44 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "memchr" +version = "1.0.2" +authors = ["Andrew Gallant ", "bluss"] +description = "Safe interface to memchr." +homepage = "https://github.com/BurntSushi/rust-memchr" +documentation = "https://docs.rs/memchr/" +readme = "README.md" +keywords = ["memchr", "char", "scan", "strchr", "string"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/rust-memchr" +[profile.test] +opt-level = 3 + +[lib] +name = "memchr" +bench = false +[dependencies.libc] +version = "0.2.18" +optional = true +default-features = false +[dev-dependencies.quickcheck] +version = "0.4.1" + +[features] +default = ["use_std", "libc"] +use_std = ["libc", "libc/use_std"] +[badges.appveyor] +repository = "BurntSushi/rust-memchr" + +[badges.travis-ci] +repository = "BurntSushi/rust-memchr" diff --git a/bash-5.1/vendor/memchr-1.0.2/LICENSE-MIT b/bash-5.1/vendor/memchr-1.0.2/LICENSE-MIT new file mode 100644 index 0000000..3b0a5dc --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bash-5.1/vendor/memchr-1.0.2/Makefile b/bash-5.1/vendor/memchr-1.0.2/Makefile new file mode 100644 index 0000000..9f956f4 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/Makefile @@ -0,0 +1,14 @@ +all: + echo Nothing to do... + +ctags: + ctags --recurse --options=ctags.rust --languages=Rust + +docs: + cargo doc + in-dir ./target/doc fix-perms + rscp ./target/doc/* gopher:~/www/burntsushi.net/rustdoc/ + +push: + git push origin master + git push github master diff --git a/bash-5.1/vendor/memchr-1.0.2/README.md b/bash-5.1/vendor/memchr-1.0.2/README.md new file mode 100644 index 0000000..1e7548e --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/README.md @@ -0,0 +1,36 @@ +This crate provides a safe interface `libc`'s `memchr` and `memrchr`. +This crate also provides fallback implementations when either function is +unavailable. + +[![Build status](https://api.travis-ci.org/BurntSushi/rust-memchr.png)](https://travis-ci.org/BurntSushi/rust-memchr) +[![Build status](https://ci.appveyor.com/api/projects/status/8i9484t8l4w7uql0/branch/master?svg=true)](https://ci.appveyor.com/project/BurntSushi/rust-memchr/branch/master) +[![](http://meritbadge.herokuapp.com/memchr)](https://crates.io/crates/memchr) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + + +### Documentation + +[https://docs.rs/memchr](https://docs.rs/memchr) + +### no_std + +memchr links to the standard library by default, but you can disable the +`use_std` feature if you want to use it in a `#![no_std]` crate: + +```toml +[dependencies] +memchr = { version = "1.0", default-features = false } +``` + +### Performance + +On my system (Linux/amd64), `memchr` is about an order of magnitude faster than +the more idiomatic `haystack.iter().position(|&b| b == needle)`: + +``` +test iterator ... bench: 5,280 ns/iter (+/- 13) = 1893 MB/s +test iterator_reversed ... bench: 5,271 ns/iter (+/- 7) = 1897 MB/s +test libc_memchr ... bench: 202 ns/iter (+/- 0) = 49504 MB/s +test libc_memrchr ... bench: 197 ns/iter (+/- 1) = 50761 MB/s +``` diff --git a/bash-5.1/vendor/memchr-1.0.2/UNLICENSE b/bash-5.1/vendor/memchr-1.0.2/UNLICENSE new file mode 100644 index 0000000..68a49da --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/bash-5.1/vendor/memchr-1.0.2/appveyor.yml b/bash-5.1/vendor/memchr-1.0.2/appveyor.yml new file mode 100644 index 0000000..e572642 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/appveyor.yml @@ -0,0 +1,19 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo build --verbose + - cargo test --verbose + - cargo bench --verbose diff --git a/bash-5.1/vendor/memchr-1.0.2/benches/bench.rs b/bash-5.1/vendor/memchr-1.0.2/benches/bench.rs new file mode 100644 index 0000000..949b222 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/benches/bench.rs @@ -0,0 +1,117 @@ +#![feature(test)] + +extern crate memchr; +extern crate test; + +use std::iter; + +fn bench_data() -> Vec { iter::repeat(b'z').take(10000).collect() } + +#[bench] +fn iterator_memchr(b: &mut test::Bencher) { + let haystack = bench_data(); + let needle = b'a'; + b.iter(|| { + assert!(haystack.iter().position(|&b| b == needle).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn optimized_memchr(b: &mut test::Bencher) { + let haystack = bench_data(); + let needle = b'a'; + b.iter(|| { + assert!(memchr::memchr(needle, &haystack).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn iterator_memrchr(b: &mut test::Bencher) { + let haystack = bench_data(); + let needle = b'a'; + b.iter(|| { + assert!(haystack.iter().rposition(|&b| b == needle).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn optimized_memrchr(b: &mut test::Bencher) { + let haystack = bench_data(); + let needle = b'a'; + b.iter(|| { + assert!(memchr::memrchr(needle, &haystack).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn iterator_memchr2(b: &mut test::Bencher) { + let haystack = bench_data(); + let (needle1, needle2) = (b'a', b'b'); + b.iter(|| { + assert!(haystack.iter().position(|&b| { + b == needle1 || b == needle2 + }).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn manual_memchr2(b: &mut test::Bencher) { + fn find_singles( + sparse: &[bool], + text: &[u8], + ) -> Option<(usize, usize)> { + for (hi, &b) in text.iter().enumerate() { + if sparse[b as usize] { + return Some((hi, hi+1)); + } + } + None + } + + let haystack = bench_data(); + let mut sparse = vec![false; 256]; + sparse[b'a' as usize] = true; + sparse[b'b' as usize] = true; + b.iter(|| { + assert!(find_singles(&sparse, &haystack).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn optimized_memchr2(b: &mut test::Bencher) { + let haystack = bench_data(); + let (needle1, needle2) = (b'a', b'b'); + b.iter(|| { + assert!(memchr::memchr2(needle1, needle2, &haystack).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn iterator_memchr3(b: &mut test::Bencher) { + let haystack = bench_data(); + let (needle1, needle2, needle3) = (b'a', b'b', b'c'); + b.iter(|| { + assert!(haystack.iter().position(|&b| { + b == needle1 || b == needle2 || b == needle3 + }).is_none()); + }); + b.bytes = haystack.len() as u64; +} + +#[bench] +fn optimized_memchr3(b: &mut test::Bencher) { + let haystack = bench_data(); + let (needle1, needle2, needle3) = (b'a', b'b', b'c'); + b.iter(|| { + assert!(memchr::memchr3( + needle1, needle2, needle3, &haystack).is_none()); + }); + b.bytes = haystack.len() as u64; +} diff --git a/bash-5.1/vendor/memchr-1.0.2/ctags.rust b/bash-5.1/vendor/memchr-1.0.2/ctags.rust new file mode 100644 index 0000000..b42edf7 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/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[ \t]+([a-zA-Z0-9_]+)/\2/c,consts,static constants/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?trait[ \t]+([a-zA-Z0-9_]+)/\2/t,traits,traits/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?impl([ \t\n]+<.*>)?[ \t]+([a-zA-Z0-9_]+)/\3/i,impls,trait implementations/ +--regex-Rust=/^[ \t]*macro_rules![ \t]+([a-zA-Z0-9_]+)/\1/d,macros,macro definitions/ diff --git a/bash-5.1/vendor/memchr-1.0.2/session.vim b/bash-5.1/vendor/memchr-1.0.2/session.vim new file mode 100644 index 0000000..213c956 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/session.vim @@ -0,0 +1 @@ +au BufWritePost *.rs silent!make ctags > /dev/null 2>&1 diff --git a/bash-5.1/vendor/memchr-1.0.2/src/lib.rs b/bash-5.1/vendor/memchr-1.0.2/src/lib.rs new file mode 100644 index 0000000..7faf323 --- /dev/null +++ b/bash-5.1/vendor/memchr-1.0.2/src/lib.rs @@ -0,0 +1,881 @@ +/*! +This crate defines two functions, `memchr` and `memrchr`, which expose a safe interface +to the corresponding functions in `libc`. +*/ + +#![deny(missing_docs)] +#![allow(unused_imports)] + +#![cfg_attr(not(feature = "use_std"), no_std)] + +#[cfg(all(test, not(feature = "use_std")))] +#[macro_use] +extern crate std; + +#[cfg(feature = "libc")] +extern crate libc; + +#[cfg(feature = "libc")] +use libc::c_void; +#[cfg(feature = "libc")] +use libc::{c_int, size_t}; + +#[cfg(feature = "use_std")] +use std::cmp; +#[cfg(not(feature = "use_std"))] +use core::cmp; + +const LO_U64: u64 = 0x0101010101010101; +const HI_U64: u64 = 0x8080808080808080; + +// use truncation +const LO_USIZE: usize = LO_U64 as usize; +const HI_USIZE: usize = HI_U64 as usize; + +#[cfg(target_pointer_width = "32")] +const USIZE_BYTES: usize = 4; +#[cfg(target_pointer_width = "64")] +const USIZE_BYTES: usize = 8; + +/// Return `true` if `x` contains any zero byte. +/// +/// From *Matters Computational*, J. Arndt +/// +/// "The idea is to subtract one from each of the bytes and then look for +/// bytes where the borrow propagated all the way to the most significant +/// bit." +#[inline] +fn contains_zero_byte(x: usize) -> bool { + x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0 +} + +#[cfg(target_pointer_width = "32")] +#[inline] +fn repeat_byte(b: u8) -> usize { + let mut rep = (b as usize) << 8 | b as usize; + rep = rep << 16 | rep; + rep +} + +#[cfg(target_pointer_width = "64")] +#[inline] +fn repeat_byte(b: u8) -> usize { + let mut rep = (b as usize) << 8 | b as usize; + rep = rep << 16 | rep; + rep = rep << 32 | rep; + rep +} + +/// An iterator for memchr +pub struct Memchr<'a> { + needle: u8, + // The haystack to iterate over + haystack: &'a [u8], + // The index + position: usize, +} + +impl<'a> Memchr<'a> { + /// Creates a new iterator that yields all positions of needle in haystack. + pub fn new(needle: u8, haystack: &[u8]) -> Memchr { + Memchr { + needle: needle, + haystack: haystack, + position: 0, + } + } +} + +impl<'a> Iterator for Memchr<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + let search_result = memchr(self.needle, &self.haystack); + match search_result { + Some(index) => { + // Move our internal position + self.haystack = self.haystack.split_at(index + 1).1; + self.position = self.position + index + 1; + Some(self.position) + } + None => None, + } + } +} + +impl<'a> DoubleEndedIterator for Memchr<'a> { + fn next_back(&mut self) -> Option { + let search_result = memrchr(self.needle, &self.haystack); + match search_result { + Some(index) => { + // Move our internal position + self.haystack = self.haystack.split_at(index).0; + Some(self.position + index + 1) + } + None => None, + } + } +} + +/// A safe interface to `memchr`. +/// +/// Returns the index corresponding to the first occurrence of `needle` in +/// `haystack`, or `None` if one is not found. +/// +/// memchr reduces to super-optimized machine code at around an order of +/// magnitude faster than `haystack.iter().position(|&b| b == needle)`. +/// (See benchmarks.) +/// +/// # Example +/// +/// This shows how to find the first position of a byte in a byte string. +/// +/// ```rust +/// use memchr::memchr; +/// +/// let haystack = b"the quick brown fox"; +/// assert_eq!(memchr(b'k', haystack), Some(8)); +/// ``` +#[inline(always)] // reduces constant overhead +pub fn memchr(needle: u8, haystack: &[u8]) -> Option { + // libc memchr + #[cfg(all(feature = "libc", + any(not(target_os = "windows"), + not(any(target_pointer_width = "32", + target_pointer_width = "64")))))] + #[inline(always)] // reduces constant overhead + fn memchr_specific(needle: u8, haystack: &[u8]) -> Option { + use libc::memchr as libc_memchr; + + let p = unsafe { + libc_memchr(haystack.as_ptr() as *const c_void, + needle as c_int, + haystack.len() as size_t) + }; + if p.is_null() { + None + } else { + Some(p as usize - (haystack.as_ptr() as usize)) + } + } + + // use fallback on windows, since it's faster + #[cfg(all(any(not(feature = "libc"), target_os = "windows"), + any(target_pointer_width = "32", + target_pointer_width = "64")))] + fn memchr_specific(needle: u8, haystack: &[u8]) -> Option { + fallback::memchr(needle, haystack) + } + + // For the rare case of neither 32 bit nor 64-bit platform. + #[cfg(all(any(not(feature = "libc"), target_os = "windows"), + not(target_pointer_width = "32"), + not(target_pointer_width = "64")))] + fn memchr_specific(needle: u8, haystack: &[u8]) -> Option { + haystack.iter().position(|&b| b == needle) + } + + memchr_specific(needle, haystack) +} + +/// A safe interface to `memrchr`. +/// +/// Returns the index corresponding to the last occurrence of `needle` in +/// `haystack`, or `None` if one is not found. +/// +/// # Example +/// +/// This shows how to find the last position of a byte in a byte string. +/// +/// ```rust +/// use memchr::memrchr; +/// +/// let haystack = b"the quick brown fox"; +/// assert_eq!(memrchr(b'o', haystack), Some(17)); +/// ``` +#[inline(always)] // reduces constant overhead +pub fn memrchr(needle: u8, haystack: &[u8]) -> Option { + + #[cfg(all(feature = "libc", target_os = "linux"))] + #[inline(always)] // reduces constant overhead + fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { + // GNU's memrchr() will - unlike memchr() - error if haystack is empty. + if haystack.is_empty() { + return None; + } + let p = unsafe { + libc::memrchr(haystack.as_ptr() as *const c_void, + needle as c_int, + haystack.len() as size_t) + }; + if p.is_null() { + None + } else { + Some(p as usize - (haystack.as_ptr() as usize)) + } + } + + #[cfg(all(not(all(feature = "libc", target_os = "linux")), + any(target_pointer_width = "32", target_pointer_width = "64")))] + fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { + fallback::memrchr(needle, haystack) + } + + // For the rare case of neither 32 bit nor 64-bit platform. + #[cfg(all(not(all(feature = "libc", target_os = "linux")), + not(target_pointer_width = "32"), + not(target_pointer_width = "64")))] + fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { + haystack.iter().rposition(|&b| b == needle) + } + + memrchr_specific(needle, haystack) +} + +/// An iterator for Memchr2 +pub struct Memchr2<'a> { + needle1: u8, + needle2: u8, + // The haystack to iterate over + haystack: &'a [u8], + // The index + position: usize, +} + +impl<'a> Memchr2<'a> { + /// Creates a new iterator that yields all positions of needle in haystack. + pub fn new(needle1: u8, needle2: u8, haystack: &[u8]) -> Memchr2 { + Memchr2 { + needle1: needle1, + needle2: needle2, + haystack: haystack, + position: 0, + } + } +} + +impl<'a> Iterator for Memchr2<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + let search_result = memchr2(self.needle1, self.needle2, &self.haystack); + match search_result { + Some(index) => { + // Move our internal position + self.haystack = self.haystack.split_at(index + 1).1; + self.position = self.position + index + 1; + Some(self.position) + } + None => None, + } + } +} + + +/// Like `memchr`, but searches for two bytes instead of one. +pub fn memchr2(needle1: u8, needle2: u8, haystack: &[u8]) -> Option { + fn slow(b1: u8, b2: u8, haystack: &[u8]) -> Option { + haystack.iter().position(|&b| b == b1 || b == b2) + } + + let len = haystack.len(); + let ptr = haystack.as_ptr(); + let align = (ptr as usize) & (USIZE_BYTES - 1); + let mut i = 0; + if align > 0 { + i = cmp::min(USIZE_BYTES - align, len); + if let Some(found) = slow(needle1, needle2, &haystack[..i]) { + return Some(found); + } + } + let repeated_b1 = repeat_byte(needle1); + let repeated_b2 = repeat_byte(needle2); + if len >= USIZE_BYTES { + while i <= len - USIZE_BYTES { + unsafe { + let u = *(ptr.offset(i as isize) as *const usize); + let found_ub1 = contains_zero_byte(u ^ repeated_b1); + let found_ub2 = contains_zero_byte(u ^ repeated_b2); + if found_ub1 || found_ub2 { + break; + } + } + i += USIZE_BYTES; + } + } + slow(needle1, needle2, &haystack[i..]).map(|pos| i + pos) +} + +/// An iterator for Memchr3 +pub struct Memchr3<'a> { + needle1: u8, + needle2: u8, + needle3: u8, + // The haystack to iterate over + haystack: &'a [u8], + // The index + position: usize, +} + +impl<'a> Memchr3<'a> { + /// Create a new Memchr2 that's initalized to zero with a haystack + pub fn new(needle1: u8, needle2: u8, needle3: u8, haystack: &[u8]) -> Memchr3 { + Memchr3 { + needle1: needle1, + needle2: needle2, + needle3: needle3, + haystack: haystack, + position: 0, + } + } +} + +impl<'a> Iterator for Memchr3<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + let search_result = memchr3(self.needle1, self.needle2, self.needle3, &self.haystack); + match search_result { + Some(index) => { + // Move our internal position + self.haystack = self.haystack.split_at(index + 1).1; + self.position = self.position + index + 1; + Some(self.position) + } + None => None, + } + } +} + +/// Like `memchr`, but searches for three bytes instead of one. +pub fn memchr3(needle1: u8, needle2: u8, needle3: u8, haystack: &[u8]) -> Option { + fn slow(b1: u8, b2: u8, b3: u8, haystack: &[u8]) -> Option { + haystack.iter().position(|&b| b == b1 || b == b2 || b == b3) + } + + let len = haystack.len(); + let ptr = haystack.as_ptr(); + let align = (ptr as usize) & (USIZE_BYTES - 1); + let mut i = 0; + if align > 0 { + i = cmp::min(USIZE_BYTES - align, len); + if let Some(found) = slow(needle1, needle2, needle3, &haystack[..i]) { + return Some(found); + } + } + let repeated_b1 = repeat_byte(needle1); + let repeated_b2 = repeat_byte(needle2); + let repeated_b3 = repeat_byte(needle3); + if len >= USIZE_BYTES { + while i <= len - USIZE_BYTES { + unsafe { + let u = *(ptr.offset(i as isize) as *const usize); + let found_ub1 = contains_zero_byte(u ^ repeated_b1); + let found_ub2 = contains_zero_byte(u ^ repeated_b2); + let found_ub3 = contains_zero_byte(u ^ repeated_b3); + if found_ub1 || found_ub2 || found_ub3 { + break; + } + } + i += USIZE_BYTES; + } + } + slow(needle1, needle2, needle3, &haystack[i..]).map(|pos| i + pos) +} + +#[allow(dead_code)] +#[cfg(any(test, not(feature = "libc"), all(not(target_os = "linux"), + any(target_pointer_width = "32", target_pointer_width = "64"))))] +mod fallback { + #[cfg(feature = "use_std")] + use std::cmp; + #[cfg(not(feature = "use_std"))] + use core::cmp; + + use super::{LO_U64, HI_U64, LO_USIZE, HI_USIZE, USIZE_BYTES, contains_zero_byte, repeat_byte}; + + /// Return the first index matching the byte `a` in `text`. + pub fn memchr(x: u8, text: &[u8]) -> Option { + // Scan for a single byte value by reading two `usize` words at a time. + // + // Split `text` in three parts + // - unaligned inital part, before the first word aligned address in text + // - body, scan by 2 words at a time + // - the last remaining part, < 2 word size + let len = text.len(); + let ptr = text.as_ptr(); + + // search up to an aligned boundary + let align = (ptr as usize) & (USIZE_BYTES - 1); + let mut offset; + if align > 0 { + offset = cmp::min(USIZE_BYTES - align, len); + if let Some(index) = text[..offset].iter().position(|elt| *elt == x) { + return Some(index); + } + } else { + offset = 0; + } + + // search the body of the text + let repeated_x = repeat_byte(x); + + if len >= 2 * USIZE_BYTES { + while offset <= len - 2 * USIZE_BYTES { + debug_assert_eq!((ptr as usize + offset) % USIZE_BYTES, 0); + unsafe { + let u = *(ptr.offset(offset as isize) as *const usize); + let v = *(ptr.offset((offset + USIZE_BYTES) as isize) as *const usize); + + // break if there is a matching byte + let zu = contains_zero_byte(u ^ repeated_x); + let zv = contains_zero_byte(v ^ repeated_x); + if zu || zv { + break; + } + } + offset += USIZE_BYTES * 2; + } + } + + // find the byte after the point the body loop stopped + text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i) + } + + /// Return the last index matching the byte `a` in `text`. + pub fn memrchr(x: u8, text: &[u8]) -> Option { + // Scan for a single byte value by reading two `usize` words at a time. + // + // Split `text` in three parts + // - unaligned tail, after the last word aligned address in text + // - body, scan by 2 words at a time + // - the first remaining bytes, < 2 word size + let len = text.len(); + let ptr = text.as_ptr(); + + // search to an aligned boundary + let end_align = (ptr as usize + len) & (USIZE_BYTES - 1); + let mut offset; + if end_align > 0 { + offset = if end_align >= len { 0 } else { len - end_align }; + if let Some(index) = text[offset..].iter().rposition(|elt| *elt == x) { + return Some(offset + index); + } + } else { + offset = len; + } + + // search the body of the text + let repeated_x = repeat_byte(x); + + while offset >= 2 * USIZE_BYTES { + debug_assert_eq!((ptr as usize + offset) % USIZE_BYTES, 0); + unsafe { + let u = *(ptr.offset(offset as isize - 2 * USIZE_BYTES as isize) as *const usize); + let v = *(ptr.offset(offset as isize - USIZE_BYTES as isize) as *const usize); + + // break if there is a matching byte + let zu = contains_zero_byte(u ^ repeated_x); + let zv = contains_zero_byte(v ^ repeated_x); + if zu || zv { + break; + } + } + offset -= 2 * USIZE_BYTES; + } + + // find the byte before the point the body loop stopped + text[..offset].iter().rposition(|elt| *elt == x) + } +} + +#[cfg(test)] +mod tests { + extern crate quickcheck; + use std::prelude::v1::*; + + use super::{memchr, memrchr, memchr2, memchr3, Memchr, Memchr2, Memchr3}; + // Use a macro to test both native and fallback impls on all configurations + macro_rules! memchr_tests { + ($mod_name:ident, $memchr:path, $memrchr:path) => { + mod $mod_name { + use std::prelude::v1::*; + use super::quickcheck; + #[test] + fn matches_one() { + assert_eq!(Some(0), $memchr(b'a', b"a")); + } + + #[test] + fn matches_begin() { + assert_eq!(Some(0), $memchr(b'a', b"aaaa")); + } + + #[test] + fn matches_end() { + assert_eq!(Some(4), $memchr(b'z', b"aaaaz")); + } + + #[test] + fn matches_nul() { + assert_eq!(Some(4), $memchr(b'\x00', b"aaaa\x00")); + } + + #[test] + fn matches_past_nul() { + assert_eq!(Some(5), $memchr(b'z', b"aaaa\x00z")); + } + + #[test] + fn no_match_empty() { + assert_eq!(None, $memchr(b'a', b"")); + } + + #[test] + fn no_match() { + assert_eq!(None, $memchr(b'a', b"xyz")); + } + + #[test] + fn qc_never_fail() { + fn prop(needle: u8, haystack: Vec) -> bool { + $memchr(needle, &haystack); true + } + quickcheck::quickcheck(prop as fn(u8, Vec) -> bool); + } + + #[test] + fn matches_one_reversed() { + assert_eq!(Some(0), $memrchr(b'a', b"a")); + } + + #[test] + fn matches_begin_reversed() { + assert_eq!(Some(3), $memrchr(b'a', b"aaaa")); + } + + #[test] + fn matches_end_reversed() { + assert_eq!(Some(0), $memrchr(b'z', b"zaaaa")); + } + + #[test] + fn matches_nul_reversed() { + assert_eq!(Some(4), $memrchr(b'\x00', b"aaaa\x00")); + } + + #[test] + fn matches_past_nul_reversed() { + assert_eq!(Some(0), $memrchr(b'z', b"z\x00aaaa")); + } + + #[test] + fn no_match_empty_reversed() { + assert_eq!(None, $memrchr(b'a', b"")); + } + + #[test] + fn no_match_reversed() { + assert_eq!(None, $memrchr(b'a', b"xyz")); + } + + #[test] + fn qc_never_fail_reversed() { + fn prop(needle: u8, haystack: Vec) -> bool { + $memrchr(needle, &haystack); true + } + quickcheck::quickcheck(prop as fn(u8, Vec) -> bool); + } + + #[test] + fn qc_correct_memchr() { + fn prop(v: Vec, offset: u8) -> bool { + // test all pointer alignments + let uoffset = (offset & 0xF) as usize; + let data = if uoffset <= v.len() { + &v[uoffset..] + } else { + &v[..] + }; + for byte in 0..256u32 { + let byte = byte as u8; + if $memchr(byte, &data) != data.iter().position(|elt| *elt == byte) { + return false; + } + } + true + } + quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); + } + + #[test] + fn qc_correct_memrchr() { + fn prop(v: Vec, offset: u8) -> bool { + // test all pointer alignments + let uoffset = (offset & 0xF) as usize; + let data = if uoffset <= v.len() { + &v[uoffset..] + } else { + &v[..] + }; + for byte in 0..256u32 { + let byte = byte as u8; + if $memrchr(byte, &data) != data.iter().rposition(|elt| *elt == byte) { + return false; + } + } + true + } + quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); + } + } + } + } + + memchr_tests! { native, ::memchr, ::memrchr } + memchr_tests! { fallback, ::fallback::memchr, ::fallback::memrchr } + + #[test] + fn memchr2_matches_one() { + assert_eq!(Some(0), memchr2(b'a', b'b', b"a")); + assert_eq!(Some(0), memchr2(b'a', b'b', b"b")); + assert_eq!(Some(0), memchr2(b'b', b'a', b"a")); + assert_eq!(Some(0), memchr2(b'b', b'a', b"b")); + } + + #[test] + fn memchr2_matches_begin() { + assert_eq!(Some(0), memchr2(b'a', b'b', b"aaaa")); + assert_eq!(Some(0), memchr2(b'a', b'b', b"bbbb")); + } + + #[test] + fn memchr2_matches_end() { + assert_eq!(Some(4), memchr2(b'z', b'y', b"aaaaz")); + assert_eq!(Some(4), memchr2(b'z', b'y', b"aaaay")); + } + + #[test] + fn memchr2_matches_nul() { + assert_eq!(Some(4), memchr2(b'\x00', b'z', b"aaaa\x00")); + assert_eq!(Some(4), memchr2(b'z', b'\x00', b"aaaa\x00")); + } + + #[test] + fn memchr2_matches_past_nul() { + assert_eq!(Some(5), memchr2(b'z', b'y', b"aaaa\x00z")); + assert_eq!(Some(5), memchr2(b'y', b'z', b"aaaa\x00z")); + } + + #[test] + fn memchr2_no_match_empty() { + assert_eq!(None, memchr2(b'a', b'b', b"")); + assert_eq!(None, memchr2(b'b', b'a', b"")); + } + + #[test] + fn memchr2_no_match() { + assert_eq!(None, memchr2(b'a', b'b', b"xyz")); + } + + #[test] + fn qc_never_fail_memchr2() { + fn prop(needle1: u8, needle2: u8, haystack: Vec) -> bool { + memchr2(needle1, needle2, &haystack); + true + } + quickcheck::quickcheck(prop as fn(u8, u8, Vec) -> bool); + } + + #[test] + fn memchr3_matches_one() { + assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"a")); + assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"b")); + assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"c")); + } + + #[test] + fn memchr3_matches_begin() { + assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"aaaa")); + assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"bbbb")); + assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"cccc")); + } + + #[test] + fn memchr3_matches_end() { + assert_eq!(Some(4), memchr3(b'z', b'y', b'x', b"aaaaz")); + assert_eq!(Some(4), memchr3(b'z', b'y', b'x', b"aaaay")); + assert_eq!(Some(4), memchr3(b'z', b'y', b'x', b"aaaax")); + } + + #[test] + fn memchr3_matches_nul() { + assert_eq!(Some(4), memchr3(b'\x00', b'z', b'y', b"aaaa\x00")); + assert_eq!(Some(4), memchr3(b'z', b'\x00', b'y', b"aaaa\x00")); + assert_eq!(Some(4), memchr3(b'z', b'y', b'\x00', b"aaaa\x00")); + } + + #[test] + fn memchr3_matches_past_nul() { + assert_eq!(Some(5), memchr3(b'z', b'y', b'x', b"aaaa\x00z")); + assert_eq!(Some(5), memchr3(b'y', b'z', b'x', b"aaaa\x00z")); + assert_eq!(Some(5), memchr3(b'y', b'x', b'z', b"aaaa\x00z")); + } + + #[test] + fn memchr3_no_match_empty() { + assert_eq!(None, memchr3(b'a', b'b', b'c', b"")); + assert_eq!(None, memchr3(b'b', b'a', b'c', b"")); + assert_eq!(None, memchr3(b'c', b'b', b'a', b"")); + } + + #[test] + fn memchr3_no_match() { + assert_eq!(None, memchr3(b'a', b'b', b'c', b"xyz")); + } + + #[test] + fn memchr_iter() { + let haystack = b"aaaabaaaab"; + let mut memchr_iter = Memchr::new(b'b', haystack); + let first = memchr_iter.next(); + let second = memchr_iter.next(); + let third = memchr_iter.next(); + assert_eq!(Some(5), first); + assert_eq!(Some(10), second); + assert_eq!(None, third); + } + + #[test] + fn memchr2_iter() { + let haystack = b"ab"; + let mut memchr_iter = Memchr2::new(b'a', b'b', haystack); + let first = memchr_iter.next(); + let second = memchr_iter.next(); + let third = memchr_iter.next(); + assert_eq!(Some(1), first); + assert_eq!(Some(2), second); + assert_eq!(None, third); + } + + #[test] + fn memchr3_iter() { + let haystack = b"abc"; + let mut memchr_iter = Memchr3::new(b'a', b'b', b'c', haystack); + let first = memchr_iter.next(); + let second = memchr_iter.next(); + let third = memchr_iter.next(); + let fourth = memchr_iter.next(); + assert_eq!(Some(1), first); + assert_eq!(Some(2), second); + assert_eq!(Some(3), third); + assert_eq!(None, fourth); + } + + #[test] + fn memchr_reverse_iter() { + let haystack = b"aaaabaaaabaaaab"; + let mut memchr_iter = Memchr::new(b'b', haystack); + let first = memchr_iter.next(); + let second = memchr_iter.next_back(); + let third = memchr_iter.next(); + let fourth = memchr_iter.next_back(); + + assert_eq!(Some(5), first); + assert_eq!(Some(15), second); + assert_eq!(Some(10), third); + assert_eq!(None, fourth); + } + + #[test] + fn memrchr_iter(){ + let haystack = b"aaaabaaaabaaaab"; + let mut memchr_iter = Memchr::new(b'b', haystack); + let first = memchr_iter.next_back(); + let second = memchr_iter.next_back(); + let third = memchr_iter.next_back(); + let fourth = memchr_iter.next_back(); + + assert_eq!(Some(15), first); + assert_eq!(Some(10), second); + assert_eq!(Some(5), third); + assert_eq!(None, fourth); + + } + + #[test] + fn qc_never_fail_memchr3() { + fn prop(needle1: u8, needle2: u8, needle3: u8, haystack: Vec) -> bool { + memchr3(needle1, needle2, needle3, &haystack); + true + } + quickcheck::quickcheck(prop as fn(u8, u8, u8, Vec) -> bool); + } + + #[test] + fn qc_correct_memchr() { + fn prop(v: Vec, offset: u8) -> bool { + // test all pointer alignments + let uoffset = (offset & 0xF) as usize; + let data = if uoffset <= v.len() { + &v[uoffset..] + } else { + &v[..] + }; + for byte in 0..256u32 { + let byte = byte as u8; + if memchr(byte, &data) != data.iter().position(|elt| *elt == byte) { + return false; + } + } + true + } + quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); + } + + #[test] + fn qc_correct_memrchr() { + fn prop(v: Vec, offset: u8) -> bool { + // test all pointer alignments + let uoffset = (offset & 0xF) as usize; + let data = if uoffset <= v.len() { + &v[uoffset..] + } else { + &v[..] + }; + for byte in 0..256u32 { + let byte = byte as u8; + if memrchr(byte, &data) != data.iter().rposition(|elt| *elt == byte) { + return false; + } + } + true + } + quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); + } + + #[test] + fn qc_correct_memchr2() { + fn prop(v: Vec, offset: u8) -> bool { + // test all pointer alignments + let uoffset = (offset & 0xF) as usize; + let data = if uoffset <= v.len() { + &v[uoffset..] + } else { + &v[..] + }; + for b1 in 0..256u32 { + for b2 in 0..256u32 { + let (b1, b2) = (b1 as u8, b2 as u8); + let expected = data.iter().position(|&b| b == b1 || b == b2); + let got = memchr2(b1, b2, &data); + if expected != got { + return false; + } + } + } + true + } + quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); + } +} diff --git a/bash-5.1/vendor/nix/.cargo-checksum.json b/bash-5.1/vendor/nix/.cargo-checksum.json index e6ef259..21c3297 100644 --- a/bash-5.1/vendor/nix/.cargo-checksum.json +++ b/bash-5.1/vendor/nix/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"6ace7a11f8a0bd7883d0b5f0ad40d8c8c018a474677f14d9568d7c1f9d88a64f","Cargo.toml":"75e9539191f0b2664a4d89687cf59877259955fb6af85c5711a257690cf131bc","LICENSE":"66e3ee1fa7f909ad3c612d556f2a0cdabcd809ad6e66f3b0605015ac64841b70","README.md":"00ed4b7d1b538eaea937bcc82e51b21b4b185fac5e2d2124f3163f0c75b09795","src/dir.rs":"37f34eb1db53bc4953c4a0629f2b06a2130228898ae9afe42fe392af08d73842","src/env.rs":"3657fb51d8569ed525787e22cd2adb0ea5eb250d27641cfb8926be6908be4f38","src/errno.rs":"c973e7c0e769208ecdf20da5a7e026375c8eba785e825ff9d5ffe74290fa6a36","src/fcntl.rs":"a80857b4458c16d6ae15eaa71e5cd335ee2557ff598591f6296d898950fce963","src/features.rs":"18ac07e56c3187a650a0ea3b3eee9dacca51686fc3ca3fa0ddde449deb102f56","src/ifaddrs.rs":"e59a7540976c7c60b89929febdf5f6384b42c6d801bd1f339236e0e9c5636b67","src/kmod.rs":"9031edb7b0a8ed1d6635163c9c32490537d5c204e9794cce9dc2db24ead60957","src/lib.rs":"6330ce3b43d21d2ce658f2fab8b7c7e0c43080cf17002718b070d250ca9d70da","src/macros.rs":"257a3e46d315f4bc86f09c66f1dacf722424c96b39c7030a8b1dffc05dfd2bc6","src/mount/bsd.rs":"c14a0e477f08c2949945139fcae9f0ede1f15d17fdd4277f7344b6bd5fafdc48","src/mount/linux.rs":"d938612abe89d2cf0d375b335a570ba4831f2009d3ef6c7e786ccbc398bf2c15","src/mount/mod.rs":"5c9d906d4760ac1a3767949e2cab69d7fa683c454c06045919c58a90689d439f","src/mqueue.rs":"513120f89399fb832f78e8e6f151e23a0b5fcaea40745b465b3fe7080346dc87","src/net/if_.rs":"7e05ba4e41f9921dc5c78ba10c130bc79f31d26863f4db2df3754b6a317839c8","src/net/mod.rs":"577f70170e53d4a6de1abb70bf8f1031ec3e65c0e63ef5fcf05c907125e7ac17","src/poll.rs":"aab8f9e48db4fa43113e5e4eecb095dc1bfa76431d9792e5f79e305af28066ea","src/pty.rs":"e94219e1981cb023d4f3c22edbe26c87f7508fa25b96b9f74b3b36436aebe2fb","src/sched.rs":"83029c0f8f473f2e1323ecaae8e3f15dc0f5326afd7e768d024d91a80aa73e1c","src/sys/aio.rs":"505cd3edec0f8bc77a69c65e26c4f05b12ff565e58d0c029c466369e535eca27","src/sys/epoll.rs":"6d9bcd668010ba26abb9c5ede9f3e238a56ce4949a5c51ee80853fc8e3c37607","src/sys/event.rs":"19061ad0780d01bfd0a17c12d5527b8568aa3d0fa2b1e30692aa594c1dba4fca","src/sys/eventfd.rs":"bc8009f19e8b93b03d0202896e10bd08497f34e2987bb8ce864d6cde11eab892","src/sys/inotify.rs":"215c4217f698b47f73f4418f98f331f06ca93d35e01c6f522e5fa6a156554174","src/sys/ioctl/bsd.rs":"76acf6de6c9e2cd9367835f1b97815120e4baede4c2200661f396be4e4eb800e","src/sys/ioctl/linux.rs":"e91474bee3984a5b80ea41d5edafb4fdb9bf7c8e53969b6450cc56aa4dc7ad65","src/sys/ioctl/mod.rs":"6341f40c37227c77ca4bbb1864e60f99c43898eeaaf05ebb5132be1129550f4b","src/sys/memfd.rs":"72a153df4da17ea0cc4ce90ee3c47c5bec24c6e32fbb4ee7c77c1a89d79efbdd","src/sys/mman.rs":"93f3f4dc0212b0abb172a822e5cc179b15080bf4f5df6b91d950003650db889a","src/sys/mod.rs":"efcaefe12a84e86acd543168006963d062f52d929d1f40c1c79853297830c9d9","src/sys/personality.rs":"bf1daba7141811b39aa293e060a932bb1c2b3a5ac5552658e6509b8fa7b05016","src/sys/pthread.rs":"0407064036af5b1e6247eedd38157201104c51d73575ba2eaba5e89259521462","src/sys/ptrace/bsd.rs":"ca948c863fa55de1f9fc8eabd9fd7803054df08a6ee5044b2a6a7de49a321819","src/sys/ptrace/linux.rs":"7dadde65fa8aac137d9b189d4c571dd64eb44042d0117a0c28ff55dc73de5d66","src/sys/ptrace/mod.rs":"671a6ccac955e75d5998f7e53ffc45ed4c7b6522a0f24a0937d60141f692dd39","src/sys/quota.rs":"1b60c34302e6fad9422fe0bec9fe7e6b93fbe554b8cfe98ecf5834daf93c84de","src/sys/reboot.rs":"dbb1faeeb6525f1952a20cb75adbd76b0681b6214501f747cc154be2bbff7594","src/sys/resource.rs":"a26d30490bcc56eb8b86faf23a3a4ada3c0cd3ce28e2b3040d5f36c668f14f20","src/sys/select.rs":"d30e8dfcfa46f6bd8d8b86676ad09d7aa6f1d7747d2c9601b9bb4f5ccf44b59f","src/sys/sendfile.rs":"637b09a267813c6adf72b6b74235175ed5347e3816777881ba8a9ab192c3e497","src/sys/signal.rs":"625e14dd43d5d7e1d3540543d6438e7a27edbd425838749592418caa18d01d08","src/sys/signalfd.rs":"2677af132b9f01ec277615a5d039f49fbdd06dc4442639df668561b74b9785c4","src/sys/socket/addr.rs":"668460421d0e0915e818ddfa20881f9734231d61311d2da37d4253e9f4476560","src/sys/socket/mod.rs":"2512428d5c1d7de28ff6a680dea880a7ee8e2b30f9f90d39ca91672138347066","src/sys/socket/sockopt.rs":"0935138ab2957814d1acc29a78b8fddc12c283fe2771aae918cf2f09673591a0","src/sys/stat.rs":"aaaf7802733ac6c13c8c1ad22b864d6ba5369c123c06700d5d7d37afe87e8a66","src/sys/statfs.rs":"5827183678ddffad548f131c4e906ef73d8453534b0ac5f838cbc79ee2a12a9c","src/sys/statvfs.rs":"b8e0ea6b22e5bcf906e7367393190a2c60251211c2b4c5fa616e314d50e90d4f","src/sys/sysinfo.rs":"7ff86d7848c2e8ded13b47dc53bf24cb0f4d7f3ded634d6d2f34558a2511ed99","src/sys/termios.rs":"9281d162b68802c8c3a7bdab0a71dc794c81de1493a259f602244d7dfba2d491","src/sys/time.rs":"5ccb77ee0ea0aea934ce92f57d3112dac3a64fcf5648ee01656500dee0136135","src/sys/timer.rs":"1263c84eca7487a0174d507f6c108fdb8ccddbeeafad66ae80e3ba509e7e6ab0","src/sys/timerfd.rs":"c9193f5e1b8d963c7d0d529602859242ec00210238ed30e359001b206c809071","src/sys/uio.rs":"6aa2d19685691a9808c30d89f472cefeed3467cc1335cff36494ba7acd6250d2","src/sys/utsname.rs":"7f1c75dd550c9637a023a4629df571bcd292d53feee7b18f9f80dce425e65bea","src/sys/wait.rs":"5b21039400633d85aa49e153cc927cbf32d05df33c1d6a365921af2432b9495d","src/time.rs":"63ae33f73c79a70c811f87af2edd34e21ce93a3f89b3f176e35065fa1ece3ad7","src/ucontext.rs":"863d783443be1307477daf1970a42594d17d637aba94c8e5b63d5d9a49ea624b","src/unistd.rs":"1560e6be2730531b1f9451475713d907bbfaaac8d33ec15071d2c5b92a8a545e","test/common/mod.rs":"2fb748319611c8ed528b5ea81d7dcfba3a47aabe915917ebbeb5451deaa86e2b","test/sys/mod.rs":"d569cc63defcdcd6d0e23c9799a3f69870a02bd910b50f5aa147f8b5a50e3a25","test/sys/test_aio.rs":"414af194f06b35b83a692e3569801f2c6b7999ba7b55b59f006091902e00146e","test/sys/test_aio_drop.rs":"dbb6808f7813be0de12cef11c4156637eab1d990df6f1192cbc4b26b072b633a","test/sys/test_epoll.rs":"c982bd8fa90c615a6f11de2c816b4553e11171dbbdd8db0944166fb044221a16","test/sys/test_inotify.rs":"dc3e4fe548b0b3b71f94c9bfc157c21b017f5ce8df9dee599849f3bfe7c222bb","test/sys/test_ioctl.rs":"b809085aca01c351380b3ab650153d3800f7271391e090b6f2d6dc9186ee50f4","test/sys/test_lio_listio_resubmit.rs":"436135fce2d2e55cfc9a3a18d43ca15018feb1a51b870eed56dff2f734b9c059","test/sys/test_mman.rs":"09ec20c05f63a909f5ce3b8b3223cbc7240ca9f93a4a3ed50d20a416ab6e7296","test/sys/test_pthread.rs":"4be4a467ead0633429157c1b2191eb28962c5670aeb2ad6fe872acb95c336129","test/sys/test_ptrace.rs":"4a9df38ff14e39967763805e86d7cac86a7411f485815a6aa50b8f0321a84a48","test/sys/test_select.rs":"913ee0569c539fbf8f8d87678cec7ceb9d5529c184e72af845c8076b099b7d29","test/sys/test_signal.rs":"619aeb586309ffd2547b22c37475bb8cf6e88717c4cc114df72f6786b14de1f3","test/sys/test_signalfd.rs":"cccba36d0aba74178d78571dbd728448c8c23aba9063ad5ee24c7d89d01429c6","test/sys/test_socket.rs":"c3e67c6e053ec095170804f7d7e1a0856ccc78add564e0445ba3d49563ce88aa","test/sys/test_sockopt.rs":"c635f46e9c4f479e78e97ce712263bc9dd6a708ca4a3630b0f1fb9cdc0358570","test/sys/test_sysinfo.rs":"1e1bea9130fe38ccb07cd0ad7334c7be1e45efc33f7656a5973f8cad7126f225","test/sys/test_termios.rs":"9a9fb30655f418b59851edc9a9763f0fa1a97faaa5310989d9fa9a5c21add111","test/sys/test_timerfd.rs":"fcada956abd981e4d846da58e5640c5705b16026d47bccd1d603fae765ad10db","test/sys/test_uio.rs":"1e92ae46a1d7d9d0025fbe631123909e97c29264898d59294f0a9cda09d8a298","test/sys/test_wait.rs":"011397c19b2960ec0aa4866405d68a0307b871f52a3d6d627341b836fb4a025c","test/test.rs":"68966e13a75411107ba525891f854613650dc8621dba73fd7158b84c55bb6f55","test/test_clearenv.rs":"45ca548035b3c20ec87314715feaba2be973709a635d85b8cde46fd1d9f1ecd4","test/test_dir.rs":"837d1666d6c48da3ae9f172fa32a497e0d61af94f1e5335c2afd16eafd6b1989","test/test_fcntl.rs":"a61a12011062402900cc709f31c414ba19763107d711f69a17d1e1e71ee3be82","test/test_kmod/hello_mod/Makefile":"0219f7bce0603f97d997fb377ca071966c90333ecc665e78a54dfeb97a9c811b","test/test_kmod/hello_mod/hello.c":"bcac6b19c5bd807e1f3878c15e426acc85785a8ade9840c3bb4d068635c9188c","test/test_kmod/mod.rs":"58ac2bfb788480833d0bab990177324a405bd56d980edc222807acfb12ef23cf","test/test_mount.rs":"6b01b884b97db926ec1d4792f171344c590224554f2930c75609aaf2c0773abf","test/test_mq.rs":"b1609d4d25d6a4aaf0425d7a08700736ec3aa56b971b833fd41c4235b47922a9","test/test_net.rs":"d027680cdb1e2eed9e6912267b42a30cc0d81399826e03abfd7de81296a88282","test/test_nix_path.rs":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","test/test_nmount.rs":"26ecb0c687d9403e2d34d8e67733ddeeba7b4820f886ffa14e75f05ec4de38ea","test/test_poll.rs":"7c7ca94669c7879ee73d793a0261b27904b80c0bb380a5b5acdd4960c9c1aba5","test/test_pty.rs":"4a6dd1afe0056678f1f2c1f27f309827da5806889c4b87dafa8889664889762d","test/test_ptymaster_drop.rs":"48ae888ff4573c68e4da7d1fa737374deb307afb64deff2d788d1e0c81a11112","test/test_resource.rs":"fcbb16942458fa2c11fa4a75831f038b532d87809920dbe30c1af67d4800d94a","test/test_sched.rs":"f8ad92eb554164b0f92428f716db99040186d741cc6e1976f7930f099652f70c","test/test_sendfile.rs":"20739ab4430a23be04a980578c831a0813a94c15e595965aa74bc9882fa79bf8","test/test_stat.rs":"8632715b3f38e5b150108d219959ee8de4d69c2b1ab5321c7ca218bb7a583d0d","test/test_time.rs":"bf668b680db81e443fb402a2580425553329636cd39fad70b828041ea894b43a","test/test_timer.rs":"1c2bab1787c343a2db2963c77f484a038a63e68ed9e98629c8af05a343908372","test/test_unistd.rs":"52966b7c7cff426a9dfb2143699fc4f7e293f8cebfd14b18502df6184f5af58e"},"package":"8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9"} \ No newline at end of file +{"files":{"CHANGELOG.md":"e20b4f5f1db072fdc61fd1ec040fea9f6fc6664b1d6a93cf5dc5cf00f027993f","Cargo.toml":"cede3efdf09707d6fb9fe3c1ad327ea2d0435c70b87cd9e2096be2927f122b1b","LICENSE":"66e3ee1fa7f909ad3c612d556f2a0cdabcd809ad6e66f3b0605015ac64841b70","README.md":"0bbe5a44884e8315d018df67c691cb57d059a30c3f3dd221beb3eee56cb5cf1f","src/dir.rs":"99f348b0c792d307e9c4c36793d8fb981e11e8ffc94a6801a65808a7d8e82065","src/env.rs":"028bc5e20139ebba418a655a2978a53335dc7680bf1de43d2c8333dd72cfa5c4","src/errno.rs":"3b6c568ed8c159603b21011e9b91879a20a0e46e7d94334ab323e14dfd0e2c2a","src/fcntl.rs":"1d40fecd555c94b92d97d99ec6d72a64c6c41b8d443c6db745a41d01f00cdc79","src/features.rs":"1e1e0247662466f6998d3a405c8742ce807fce3a27823575bd235e771c2392ac","src/ifaddrs.rs":"e59a7540976c7c60b89929febdf5f6384b42c6d801bd1f339236e0e9c5636b67","src/kmod.rs":"9031edb7b0a8ed1d6635163c9c32490537d5c204e9794cce9dc2db24ead60957","src/lib.rs":"1384fe677c3a53b48b3d4c41a91ade3611b2751cdd35a0712b3237d20be393fe","src/macros.rs":"e23d7d8be22ef0bf9febaaf2739585453103607c0139bd3995a324e4a16d011e","src/mount/bsd.rs":"114878b4f2ad712236965fc3ed227d37ea56f57156266709b526002c5b65aa6e","src/mount/linux.rs":"d938612abe89d2cf0d375b335a570ba4831f2009d3ef6c7e786ccbc398bf2c15","src/mount/mod.rs":"5c9d906d4760ac1a3767949e2cab69d7fa683c454c06045919c58a90689d439f","src/mqueue.rs":"8e227acb520020b06338bceb8e7e11705564e5f4d96ab51e0815dcadc01a8b4e","src/net/if_.rs":"74dcfa81b1b77303cd8047ca4e2ab60b8fcebaa4a01dc860dd0fec65ab334eb4","src/net/mod.rs":"577f70170e53d4a6de1abb70bf8f1031ec3e65c0e63ef5fcf05c907125e7ac17","src/poll.rs":"cae2182481438f27e14e4c1a88e1835ff371423c0cc8f685ffb0b479dd102e2e","src/pty.rs":"e94219e1981cb023d4f3c22edbe26c87f7508fa25b96b9f74b3b36436aebe2fb","src/sched.rs":"22ba33ee394ef23fbde7d1fca1f2f24fc487dd447b7c28d82c9165a0822b2894","src/sys/aio.rs":"9181e01eeef5ff6f89dec1eca58ba814a80df72736b955cd1b92278d5c79bea6","src/sys/epoll.rs":"6d9bcd668010ba26abb9c5ede9f3e238a56ce4949a5c51ee80853fc8e3c37607","src/sys/event.rs":"d69b7b86bed60d7bf609c636545a5d92f7f9ece7fd69db0e662f6d7e57f3237c","src/sys/eventfd.rs":"bc8009f19e8b93b03d0202896e10bd08497f34e2987bb8ce864d6cde11eab892","src/sys/inotify.rs":"215c4217f698b47f73f4418f98f331f06ca93d35e01c6f522e5fa6a156554174","src/sys/ioctl/bsd.rs":"bbd02e30b0a78c1cb22777d9b00cfcbba9c68505cffc06118ac68474cf6fea39","src/sys/ioctl/linux.rs":"028181834d119b834bf399f2b8a6176cc57e75144693f28f32059d087d8c8018","src/sys/ioctl/mod.rs":"89b20579476b2e0254e0ecb1b41830cccd7027a22cbdb816a9d4ec3924842ac1","src/sys/memfd.rs":"72a153df4da17ea0cc4ce90ee3c47c5bec24c6e32fbb4ee7c77c1a89d79efbdd","src/sys/mman.rs":"cf4970c2ec4eb668926267679bfb7b41e653190f719d7bd1ef768623e53117a3","src/sys/mod.rs":"1be43a6d0d40661851f222b305841555897168b7e75bd9bc9c7f1962bba93369","src/sys/personality.rs":"99677190a5a81e07fc2c5c2e4b9abacf0fd555776dd0eb266fa86b8f9e965dbf","src/sys/pthread.rs":"0407064036af5b1e6247eedd38157201104c51d73575ba2eaba5e89259521462","src/sys/ptrace/bsd.rs":"ca948c863fa55de1f9fc8eabd9fd7803054df08a6ee5044b2a6a7de49a321819","src/sys/ptrace/linux.rs":"ca780ecf61416252e45dd10b5ffa6120c65b22ec4362d4f2fbd554a9bcaf1084","src/sys/ptrace/mod.rs":"671a6ccac955e75d5998f7e53ffc45ed4c7b6522a0f24a0937d60141f692dd39","src/sys/quota.rs":"d3127892f419939d63f75b9326d50e0866f7bdd92c9dcbd1cb3b6890a13b016c","src/sys/reboot.rs":"dbb1faeeb6525f1952a20cb75adbd76b0681b6214501f747cc154be2bbff7594","src/sys/resource.rs":"ee83c0a39e600c496e62592b65f8ca67c761ff9f00f30bb4bfd5cd5897281dad","src/sys/select.rs":"d30e8dfcfa46f6bd8d8b86676ad09d7aa6f1d7747d2c9601b9bb4f5ccf44b59f","src/sys/sendfile.rs":"637b09a267813c6adf72b6b74235175ed5347e3816777881ba8a9ab192c3e497","src/sys/signal.rs":"485c85a0d24a20ecf13c1d35ed740ee40498d9067cb3c0228f63323f89ba4de5","src/sys/signalfd.rs":"309eb1be7d72e8391acb5ba82b07cd6cf6fb26ddb3af914373f8889add6f52dd","src/sys/socket/addr.rs":"d7799cad83df1227d964e824598493871a463f0bf3aa27898f34155653d74453","src/sys/socket/mod.rs":"81bf377feca6fb018c8e293ce91febd95c344edb965a8f1dd7e2442b5cbad233","src/sys/socket/sockopt.rs":"f1f4704307eb76e2d29c256d722b6a8d09dc18e06378487da8fbfcc104546c3b","src/sys/stat.rs":"a7b30aa54033579aea16af4c904b3935c3816a72615537178ad6366b6c8cb381","src/sys/statfs.rs":"39a71fdd995a43210a850aac09ef3c858f0179cc0417c1abe16a1cc6a79fc10b","src/sys/statvfs.rs":"1e17f417675722690354e03184de9b9bfc1ba4367d2dc5446952ed71f67a0270","src/sys/sysinfo.rs":"ee087a4c1cd5f6efb9b29eb3d4e38438157120100fad4608ff863fc7d4d75538","src/sys/termios.rs":"81a3bf2f8995fdfbb560c2cc1bdf94b193b04a4673f085f24ecf0cd5be90b40a","src/sys/time.rs":"8319069283607875a9fe23c71c64ca76bf02681447ee6a45a9f53b8aed5f737b","src/sys/timer.rs":"5bf5068e3fe0050e7b79ed674569682c57f77bd24581ea7c7d58747989343c37","src/sys/timerfd.rs":"ee960c8475d26f01edbbeebcc8e5104a91d028d95aeec1de9d73f3f779130bb8","src/sys/uio.rs":"957e5a6650bd9a7887a332d134c6c1166588dec19530c4e9dbaca6969b99020d","src/sys/utsname.rs":"7f1c75dd550c9637a023a4629df571bcd292d53feee7b18f9f80dce425e65bea","src/sys/wait.rs":"5b21039400633d85aa49e153cc927cbf32d05df33c1d6a365921af2432b9495d","src/time.rs":"63ae33f73c79a70c811f87af2edd34e21ce93a3f89b3f176e35065fa1ece3ad7","src/ucontext.rs":"863d783443be1307477daf1970a42594d17d637aba94c8e5b63d5d9a49ea624b","src/unistd.rs":"38c774652a2adb22086eb4893d0921799addcae36b4632dabc1db79f3bbb224f","test/common/mod.rs":"1d7e28e3635754664cd056f3a1079232ff5c118df619e1d0551a9972eb0b3cd6","test/sys/mod.rs":"87b2891d83067ff21f72b8ff7fde3019dc45b6877282ac278b6da151de45c7a7","test/sys/test_aio.rs":"d2d9e9eb67a1075e43321413666a47195a03b84adf4faf235785e5d0b9158d50","test/sys/test_aio_drop.rs":"614070155fa16a979b7341d001639c5ce24a1d6f632c3abce45a5a6d49c4039b","test/sys/test_epoll.rs":"ffe95e36c79e37426ef8e8ca3b137b7f35ea0333ce666a20a4b7878db17680e9","test/sys/test_inotify.rs":"a141b9a995892547b51ceeb6761a70a6b86d37e8f38d13ea2c497b81b4b0f49f","test/sys/test_ioctl.rs":"ad25e422593408e4b14c7fb8a820e9cf6a73c2a81bd988d2ba70f780315f2403","test/sys/test_mman.rs":"f66da7990aea0b61f6e1c006fcd31389a42fa2f0ce6fdb7b02dfe314a533e32d","test/sys/test_pthread.rs":"ace36a2f5587f1874854281b4fd84e4e4d892a1e3c5cc38ced57975739522ad6","test/sys/test_ptrace.rs":"0385eebc8b1b8c72f655b745769decd9143ad83018198375982da0896310456b","test/sys/test_select.rs":"54cea1c34ad28d5770a613c1c3cbc3b1064b22037ec2b9d3fcd422d3be9e60a7","test/sys/test_signal.rs":"acc9941227bd3e2afad323613c2b8c83902ed0486d3745fd72704f395924f1e4","test/sys/test_signalfd.rs":"0e1060143e2612c490bc3d0168d0bbb042ef55e3f1d91d2578b9e42e4310a14d","test/sys/test_socket.rs":"9e86d4c15f256154f2626e663163ce823645f2934dc97edd6fc99a5f1df9164f","test/sys/test_sockopt.rs":"3013425f4e4936e8b8b1f8ea46446a840dd3c7741cd67c8706db0ae1510a3c33","test/sys/test_stat.rs":"31744a0621dace45ad20b42d16b2774cb153bceb713ca1d42038f2ad115bf6c1","test/sys/test_sysinfo.rs":"ffd49bc96375914a2c4a4a59730cae8072f85771e2c4a80d3403df38d967e272","test/sys/test_termios.rs":"e5bcef10c84bd7583d600d5601835bcb3cfc88781cb283ab0185bbef5faf4327","test/sys/test_timerfd.rs":"f99dda99b6b37ff9f216abe9f17120a3a62a7ac604c2e077279c39b985b7fe74","test/sys/test_uio.rs":"32656bd0a5699e4d019aa928edf104637937179782914a82d50d37226e84c421","test/sys/test_wait.rs":"6fd59fffeeb09ff620c359baefd062ba777598982b6cb001ccc07b6bc7605493","test/test.rs":"9f43d5001eefe1fe85ce20c4dab24474296a76d127dc25b39b4d8bd8798be45c","test/test_clearenv.rs":"45ca548035b3c20ec87314715feaba2be973709a635d85b8cde46fd1d9f1ecd4","test/test_dir.rs":"46aa32e5241cab5f5d74216aeb75427efdcdef054b061b19de36c1e9e0ea6b11","test/test_fcntl.rs":"3277cc195b97cb3950eef7016e380e2450ccc4b942019e5043089a421c31490d","test/test_kmod/hello_mod/Makefile":"0219f7bce0603f97d997fb377ca071966c90333ecc665e78a54dfeb97a9c811b","test/test_kmod/hello_mod/hello.c":"bcac6b19c5bd807e1f3878c15e426acc85785a8ade9840c3bb4d068635c9188c","test/test_kmod/mod.rs":"c214eb631510ef6fd71046c77a8f99ff052cfb1ab7621d658ccd2154eeb1d51a","test/test_mount.rs":"7ffaa8a5b3c8fd66a0f9dfe82a13dbdd268f61aa6668d8e050d7cd986ef02350","test/test_mq.rs":"136071f24131aac0e65d5f29ac18e3806641dfae1164813f5570c0e3a6f70553","test/test_net.rs":"f2912327ebb2a3d37e6cff02a5ac3106cf889cc5c74404db4ef0034059ba26f1","test/test_nix_path.rs":"01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b","test/test_nmount.rs":"d6c112547bb80968170b5497cda4b6cbf69dabec6f51d494bd52298995ceff18","test/test_poll.rs":"3e0b8f0397ba080785c61a3bfc3d637bc87f324bc4e52b5f1bf3ca0d32dbc9fe","test/test_pty.rs":"b26238a0783746cb31880e11eebc1913149be999ce75fbc2d6677bdd1e2731b2","test/test_ptymaster_drop.rs":"ae63c815f5028ddc67d194e86559483018ab1816316bdb917f40cee9364fd8a5","test/test_resource.rs":"40aef790ab745cec31a4b333d2ca406b462aa9bdf4a6d3756371e498b8d51e9a","test/test_sched.rs":"d2c8065cbec77d25230f03683dfde99828c0fa463969a5a8f50ebf913091d6bc","test/test_sendfile.rs":"bb41b4f3621b518e397d3a5b5ad3c5dcef3fe506afe516eab7572fbab92b77e3","test/test_stat.rs":"c407ca47a5258750076d041afad2f6add4c3563be36628bde1c5b314f5d0765d","test/test_time.rs":"f7a21b1e279e60e84909d5dadda97ded66d3326b131fe317badf9af0a1b50335","test/test_timer.rs":"3ae20d364f075d2811f3ff94eda9886682cc21d8807656007d2464fe36d1e361","test/test_unistd.rs":"8663cdb1de1d873e572f9fa08cae9f69c4cdceb0e7e3d6a5de1f24378c17513e"},"package":"e322c04a9e3440c327fca7b6c8a63e6890a32fa2ad689db972425f07e0d22abb"} \ No newline at end of file diff --git a/bash-5.1/vendor/nix/CHANGELOG.md b/bash-5.1/vendor/nix/CHANGELOG.md index b6639a1..f06e412 100644 --- a/bash-5.1/vendor/nix/CHANGELOG.md +++ b/bash-5.1/vendor/nix/CHANGELOG.md @@ -3,16 +3,85 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/). -## [0.24.1] - 2022-04-22 +## [0.25.0] - 2022-08-13 ### Added + +- Added `faccessat` + ([#1780](https://github.com/nix-rust/nix/pull/1780)) +- Added `memfd` on Android. + (#[1773](https://github.com/nix-rust/nix/pull/1773)) +- Added `ETH_P_ALL` to `SockProtocol` enum + (#[1768](https://github.com/nix-rust/nix/pull/1768)) +- Added four non-standard Linux `SysconfVar` variants + (#[1761](https://github.com/nix-rust/nix/pull/1761)) +- Added const constructors for `TimeSpec` and `TimeVal` + (#[1760](https://github.com/nix-rust/nix/pull/1760)) +- Added `chflags`. + (#[1758](https://github.com/nix-rust/nix/pull/1758)) +- Added `aio_writev` and `aio_readv`. + (#[1713](https://github.com/nix-rust/nix/pull/1713)) +- impl `From` for `Uid` and `From` for `Gid` + (#[1727](https://github.com/nix-rust/nix/pull/1727)) +- impl `From` for `std::net::SocketAddrV4` and + impl `From` for `std::net::SocketAddrV6`. + (#[1711](https://github.com/nix-rust/nix/pull/1711)) +- Added support for the `x86_64-unknown-haiku` target. + (#[1703](https://github.com/nix-rust/nix/pull/1703)) +- Added `ptrace::read_user` and `ptrace::write_user` for Linux. + (#[1697](https://github.com/nix-rust/nix/pull/1697)) +- Added `getrusage` and helper types `UsageWho` and `Usage` + (#[1747](https://github.com/nix-rust/nix/pull/1747)) +- Added the `DontRoute` SockOpt + (#[1752](https://github.com/nix-rust/nix/pull/1752)) +- Added `signal::SigSet::from_sigset_t_unchecked()`. + (#[1741](https://github.com/nix-rust/nix/pull/1741)) +- Added the `Ipv4OrigDstAddr` sockopt and control message. + (#[1772](https://github.com/nix-rust/nix/pull/1772)) +- Added the `Ipv6OrigDstAddr` sockopt and control message. + (#[1772](https://github.com/nix-rust/nix/pull/1772)) +- Added the `Ipv4SendSrcAddr` control message. + (#[1776](https://github.com/nix-rust/nix/pull/1776)) + ### Changed + +- Rewrote the aio module. The new module: + * Does more type checking at compile time rather than runtime. + * Gives the caller control over whether and when to `Box` an aio operation. + * Changes the type of the `priority` arguments to `i32`. + * Changes the return type of `aio_return` to `usize`. + (#[1713](https://github.com/nix-rust/nix/pull/1713)) +- `nix::poll::ppoll`: `sigmask` parameter is now optional. + (#[1739](https://github.com/nix-rust/nix/pull/1739)) +- Changed `gethostname` to return an owned `OsString`. + (#[1745](https://github.com/nix-rust/nix/pull/1745)) +- `signal:SigSet` is now marked as `repr(transparent)`. + (#[1741](https://github.com/nix-rust/nix/pull/1741)) + +### Removed + +- Removed support for resubmitting partially complete `lio_listio` operations. + It was too complicated, and didn't fit Nix's theme of zero-cost abstractions. + Instead, it can be reimplemented downstream. + (#[1713](https://github.com/nix-rust/nix/pull/1713)) + +## [0.24.2] - 2022-07-17 +### Fixed + +- Fixed buffer overflow in `nix::sys::socket::recvfrom`. + (#[1763](https://github.com/nix-rust/nix/pull/1763)) +- Enabled `SockaddrStorage::{as_link_addr, as_link_addr_mut}` for Linux-like + operating systems. + (#[1729](https://github.com/nix-rust/nix/pull/1729)) +- Fixed `SockaddrLike::from_raw` implementations for `VsockAddr` and + `SysControlAddr`. + (#[1736](https://github.com/nix-rust/nix/pull/1736)) + +## [0.24.1] - 2022-04-22 ### Fixed - Fixed `UnixAddr::size` on Linux-based OSes. (#[1702](https://github.com/nix-rust/nix/pull/1702)) -### Removed - ## [0.24.0] - 2022-04-21 ### Added @@ -122,7 +191,6 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [0.23.1] - 2021-12-16 -### Added ### Changed - Relaxed the bitflags requirement from 1.3.1 to 1.1. This partially reverts diff --git a/bash-5.1/vendor/nix/Cargo.toml b/bash-5.1/vendor/nix/Cargo.toml index fb4afc8..21b316c 100644 --- a/bash-5.1/vendor/nix/Cargo.toml +++ b/bash-5.1/vendor/nix/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.46" name = "nix" -version = "0.24.1" +version = "0.25.0" authors = ["The nix-rust Project Developers"] include = [ "src/**/*", @@ -59,10 +59,6 @@ path = "test/sys/test_aio_drop.rs" name = "test-clearenv" path = "test/test_clearenv.rs" -[[test]] -name = "test-lio-listio-resubmit" -path = "test/sys/test_lio_listio_resubmit.rs" - [[test]] name = "test-mount" path = "test/test_mount.rs" @@ -79,14 +75,18 @@ version = "1.1" version = "1.0" [dependencies.libc] -version = "0.2.121" +version = "0.2.127" features = ["extra_traits"] +[dependencies.pin-utils] +version = "0.1.0" +optional = true + [dev-dependencies.assert-impl] version = "0.1" [dev-dependencies.lazy_static] -version = "1.2" +version = "1.4" [dev-dependencies.parking_lot] version = "0.11.2" @@ -95,14 +95,17 @@ version = "0.11.2" version = "0.8" [dev-dependencies.semver] -version = "1.0.0" +version = "1.0.7" [dev-dependencies.tempfile] -version = "3.2.0" +version = "3.3.0" + +[build-dependencies.autocfg] +version = "1.1.0" [features] acct = [] -aio = [] +aio = ["pin-utils"] default = [ "acct", "aio", @@ -172,11 +175,11 @@ zerocopy = [ ] [target."cfg(any(target_os = \"android\", target_os = \"linux\"))".dev-dependencies.caps] -version = "0.5.1" +version = "0.5.3" [target."cfg(not(target_os = \"redox\"))".dependencies.memoffset] version = "0.6.3" optional = true [target."cfg(target_os = \"freebsd\")".dev-dependencies.sysctl] -version = "0.1" +version = "0.4" diff --git a/bash-5.1/vendor/nix/README.md b/bash-5.1/vendor/nix/README.md index b0c27b1..7c13cf2 100644 --- a/bash-5.1/vendor/nix/README.md +++ b/bash-5.1/vendor/nix/README.md @@ -24,8 +24,8 @@ call: // libc api (unsafe, requires handling return code/errno) pub unsafe extern fn gethostname(name: *mut c_char, len: size_t) -> c_int; -// nix api (returns a nix::Result) -pub fn gethostname<'a>(buffer: &'a mut [u8]) -> Result<&'a CStr>; +// nix api (returns a nix::Result) +pub fn gethostname() -> Result; ``` ## Supported Platforms @@ -82,6 +82,7 @@ Tier 3: * armv7-unknown-linux-uclibceabihf * x86_64-fuchsia * x86_64-unknown-dragonfly + * x86_64-unknown-haiku * x86_64-unknown-linux-gnux32 * x86_64-unknown-openbsd * x86_64-unknown-redox diff --git a/bash-5.1/vendor/nix/src/dir.rs b/bash-5.1/vendor/nix/src/dir.rs index 396b54f..6d5fc3b 100644 --- a/bash-5.1/vendor/nix/src/dir.rs +++ b/bash-5.1/vendor/nix/src/dir.rs @@ -1,3 +1,5 @@ +//! List directory contents + use crate::{Error, NixPath, Result}; use crate::errno::Errno; use crate::fcntl::{self, OFlag}; @@ -53,6 +55,7 @@ impl Dir { } /// Converts from a file descriptor, closing it on success or failure. + #[cfg_attr(has_doc_alias, doc(alias("fdopendir")))] pub fn from_fd(fd: RawFd) -> Result { let d = ptr::NonNull::new(unsafe { libc::fdopendir(fd) }).ok_or_else(|| { let e = Error::last(); @@ -113,6 +116,7 @@ fn next(dir: &mut Dir) -> Option> { } } +/// Return type of [`Dir::iter`]. #[derive(Debug, Eq, Hash, PartialEq)] pub struct Iter<'d>(&'d mut Dir); @@ -182,14 +186,22 @@ impl IntoIterator for Dir { #[repr(transparent)] pub struct Entry(dirent); +/// Type of file referenced by a directory entry #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum Type { + /// FIFO (Named pipe) Fifo, + /// Character device CharacterDevice, + /// Directory Directory, + /// Block device BlockDevice, + /// Regular file File, + /// Symbolic link Symlink, + /// Unix-domain socket Socket, } @@ -226,7 +238,7 @@ impl Entry { /// notably, some Linux filesystems don't implement this. The caller should use `stat` or /// `fstat` if this returns `None`. pub fn file_type(&self) -> Option { - #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] + #[cfg(not(any(target_os = "illumos", target_os = "solaris", target_os = "haiku")))] match self.0.d_type { libc::DT_FIFO => Some(Type::Fifo), libc::DT_CHR => Some(Type::CharacterDevice), @@ -238,8 +250,8 @@ impl Entry { /* libc::DT_UNKNOWN | */ _ => None, } - // illumos and Solaris systems do not have the d_type member at all: - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + // illumos, Solaris, and Haiku systems do not have the d_type member at all: + #[cfg(any(target_os = "illumos", target_os = "solaris", target_os = "haiku"))] None } } diff --git a/bash-5.1/vendor/nix/src/env.rs b/bash-5.1/vendor/nix/src/env.rs index bcae287..95177a1 100644 --- a/bash-5.1/vendor/nix/src/env.rs +++ b/bash-5.1/vendor/nix/src/env.rs @@ -42,7 +42,6 @@ pub unsafe fn clearenv() -> std::result::Result<(), ClearEnvError> { cfg_if! { if #[cfg(any(target_os = "fuchsia", target_os = "wasi", - target_env = "wasi", target_env = "uclibc", target_os = "linux", target_os = "android", diff --git a/bash-5.1/vendor/nix/src/errno.rs b/bash-5.1/vendor/nix/src/errno.rs index 17744fe..912fb94 100644 --- a/bash-5.1/vendor/nix/src/errno.rs +++ b/bash-5.1/vendor/nix/src/errno.rs @@ -1,8 +1,8 @@ +use crate::{Error, Result}; use cfg_if::cfg_if; use libc::{c_int, c_void}; use std::convert::TryFrom; -use std::{fmt, io, error}; -use crate::{Error, Result}; +use std::{error, fmt, io}; pub use self::consts::*; @@ -30,6 +30,10 @@ cfg_if! { unsafe fn errno_location() -> *mut c_int { libc::___errno() } + } else if #[cfg(any(target_os = "haiku",))] { + unsafe fn errno_location() -> *mut c_int { + libc::_errnop() + } } } @@ -43,9 +47,7 @@ fn clear() { /// Returns the platform-specific value of errno pub fn errno() -> i32 { - unsafe { - (*errno_location()) as i32 - } + unsafe { (*errno_location()) as i32 } } impl Errno { @@ -59,29 +61,20 @@ impl Errno { /// let e = Error::from(Errno::EPERM); /// assert_eq!(Some(Errno::EPERM), e.as_errno()); /// ``` - #[deprecated( - since = "0.22.0", - note = "It's a no-op now; just delete it." - )] + #[deprecated(since = "0.22.0", note = "It's a no-op now; just delete it.")] pub const fn as_errno(self) -> Option { Some(self) } /// Create a nix Error from a given errno - #[deprecated( - since = "0.22.0", - note = "It's a no-op now; just delete it." - )] + #[deprecated(since = "0.22.0", note = "It's a no-op now; just delete it.")] #[allow(clippy::wrong_self_convention)] // False positive pub fn from_errno(errno: Errno) -> Error { errno } /// Create a new invalid argument error (`EINVAL`) - #[deprecated( - since = "0.22.0", - note = "Use Errno::EINVAL instead" - )] + #[deprecated(since = "0.22.0", note = "Use Errno::EINVAL instead")] pub const fn invalid_argument() -> Error { Errno::EINVAL } @@ -118,10 +111,7 @@ impl Errno { /// In older versions of Nix, `Error::Sys` was an enum variant. Now it's a /// function, which is compatible with most of the former use cases of the /// enum variant. But you should use `Error(Errno::...)` instead. - #[deprecated( - since = "0.22.0", - note = "Use Errno::... instead" - )] + #[deprecated(since = "0.22.0", note = "Use Errno::... instead")] #[allow(non_snake_case)] #[inline] pub const fn Sys(errno: Errno) -> Error { @@ -136,23 +126,33 @@ pub trait ErrnoSentinel: Sized { } impl ErrnoSentinel for isize { - fn sentinel() -> Self { -1 } + fn sentinel() -> Self { + -1 + } } impl ErrnoSentinel for i32 { - fn sentinel() -> Self { -1 } + fn sentinel() -> Self { + -1 + } } impl ErrnoSentinel for i64 { - fn sentinel() -> Self { -1 } + fn sentinel() -> Self { + -1 + } } impl ErrnoSentinel for *mut c_void { - fn sentinel() -> Self { -1isize as *mut c_void } + fn sentinel() -> Self { + -1isize as *mut c_void + } } impl ErrnoSentinel for libc::sighandler_t { - fn sentinel() -> Self { libc::SIG_ERR } + fn sentinel() -> Self { + libc::SIG_ERR + } } impl error::Error for Errno {} @@ -173,9 +173,7 @@ impl TryFrom for Errno { type Error = io::Error; fn try_from(ioerror: io::Error) -> std::result::Result { - ioerror.raw_os_error() - .map(Errno::from_i32) - .ok_or(ioerror) + ioerror.raw_os_error().map(Errno::from_i32).ok_or(ioerror) } } @@ -186,728 +184,1117 @@ fn last() -> Errno { fn desc(errno: Errno) -> &'static str { use self::Errno::*; match errno { - UnknownErrno => "Unknown errno", - EPERM => "Operation not permitted", - ENOENT => "No such file or directory", - ESRCH => "No such process", - EINTR => "Interrupted system call", - EIO => "I/O error", - ENXIO => "No such device or address", - E2BIG => "Argument list too long", - ENOEXEC => "Exec format error", - EBADF => "Bad file number", - ECHILD => "No child processes", - EAGAIN => "Try again", - ENOMEM => "Out of memory", - EACCES => "Permission denied", - EFAULT => "Bad address", - ENOTBLK => "Block device required", - EBUSY => "Device or resource busy", - EEXIST => "File exists", - EXDEV => "Cross-device link", - ENODEV => "No such device", - ENOTDIR => "Not a directory", - EISDIR => "Is a directory", - EINVAL => "Invalid argument", - ENFILE => "File table overflow", - EMFILE => "Too many open files", - ENOTTY => "Not a typewriter", - ETXTBSY => "Text file busy", - EFBIG => "File too large", - ENOSPC => "No space left on device", - ESPIPE => "Illegal seek", - EROFS => "Read-only file system", - EMLINK => "Too many links", - EPIPE => "Broken pipe", - EDOM => "Math argument out of domain of func", - ERANGE => "Math result not representable", - EDEADLK => "Resource deadlock would occur", - ENAMETOOLONG => "File name too long", - ENOLCK => "No record locks available", - ENOSYS => "Function not implemented", - ENOTEMPTY => "Directory not empty", - ELOOP => "Too many symbolic links encountered", - ENOMSG => "No message of desired type", - EIDRM => "Identifier removed", - EINPROGRESS => "Operation now in progress", - EALREADY => "Operation already in progress", - ENOTSOCK => "Socket operation on non-socket", - EDESTADDRREQ => "Destination address required", - EMSGSIZE => "Message too long", - EPROTOTYPE => "Protocol wrong type for socket", - ENOPROTOOPT => "Protocol not available", + UnknownErrno => "Unknown errno", + EPERM => "Operation not permitted", + ENOENT => "No such file or directory", + ESRCH => "No such process", + EINTR => "Interrupted system call", + EIO => "I/O error", + ENXIO => "No such device or address", + E2BIG => "Argument list too long", + ENOEXEC => "Exec format error", + EBADF => "Bad file number", + ECHILD => "No child processes", + EAGAIN => "Try again", + ENOMEM => "Out of memory", + EACCES => "Permission denied", + EFAULT => "Bad address", + #[cfg(not(target_os = "haiku"))] + ENOTBLK => "Block device required", + EBUSY => "Device or resource busy", + EEXIST => "File exists", + EXDEV => "Cross-device link", + ENODEV => "No such device", + ENOTDIR => "Not a directory", + EISDIR => "Is a directory", + EINVAL => "Invalid argument", + ENFILE => "File table overflow", + EMFILE => "Too many open files", + ENOTTY => "Not a typewriter", + ETXTBSY => "Text file busy", + EFBIG => "File too large", + ENOSPC => "No space left on device", + ESPIPE => "Illegal seek", + EROFS => "Read-only file system", + EMLINK => "Too many links", + EPIPE => "Broken pipe", + EDOM => "Math argument out of domain of func", + ERANGE => "Math result not representable", + EDEADLK => "Resource deadlock would occur", + ENAMETOOLONG => "File name too long", + ENOLCK => "No record locks available", + ENOSYS => "Function not implemented", + ENOTEMPTY => "Directory not empty", + ELOOP => "Too many symbolic links encountered", + ENOMSG => "No message of desired type", + EIDRM => "Identifier removed", + EINPROGRESS => "Operation now in progress", + EALREADY => "Operation already in progress", + ENOTSOCK => "Socket operation on non-socket", + EDESTADDRREQ => "Destination address required", + EMSGSIZE => "Message too long", + EPROTOTYPE => "Protocol wrong type for socket", + ENOPROTOOPT => "Protocol not available", EPROTONOSUPPORT => "Protocol not supported", + #[cfg(not(target_os = "haiku"))] ESOCKTNOSUPPORT => "Socket type not supported", - EPFNOSUPPORT => "Protocol family not supported", - EAFNOSUPPORT => "Address family not supported by protocol", - EADDRINUSE => "Address already in use", - EADDRNOTAVAIL => "Cannot assign requested address", - ENETDOWN => "Network is down", - ENETUNREACH => "Network is unreachable", - ENETRESET => "Network dropped connection because of reset", - ECONNABORTED => "Software caused connection abort", - ECONNRESET => "Connection reset by peer", - ENOBUFS => "No buffer space available", - EISCONN => "Transport endpoint is already connected", - ENOTCONN => "Transport endpoint is not connected", - ESHUTDOWN => "Cannot send after transport endpoint shutdown", - ETOOMANYREFS => "Too many references: cannot splice", - ETIMEDOUT => "Connection timed out", - ECONNREFUSED => "Connection refused", - EHOSTDOWN => "Host is down", - EHOSTUNREACH => "No route to host", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ECHRNG => "Channel number out of range", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EL2NSYNC => "Level 2 not synchronized", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EL3HLT => "Level 3 halted", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EL3RST => "Level 3 reset", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ELNRNG => "Link number out of range", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EUNATCH => "Protocol driver not attached", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOCSI => "No CSI structure available", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EL2HLT => "Level 2 halted", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EBADE => "Invalid exchange", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EBADR => "Invalid request descriptor", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EXFULL => "Exchange full", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOANO => "No anode", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EBADRQC => "Invalid request code", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EBADSLT => "Invalid slot", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EBFONT => "Bad font file format", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOSTR => "Device not a stream", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENODATA => "No data available", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ETIME => "Timer expired", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOSR => "Out of streams resources", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENONET => "Machine is not on the network", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOPKG => "Package not installed", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EREMOTE => "Object is remote", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOLINK => "Link has been severed", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EADV => "Advertise error", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ESRMNT => "Srmount error", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ECOMM => "Communication error on send", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EPROTO => "Protocol error", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EMULTIHOP => "Multihop attempted", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EDOTDOT => "RFS specific error", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EBADMSG => "Not a data message", + #[cfg(not(target_os = "haiku"))] + EPFNOSUPPORT => "Protocol family not supported", + #[cfg(not(target_os = "haiku"))] + EAFNOSUPPORT => "Address family not supported by protocol", + EADDRINUSE => "Address already in use", + EADDRNOTAVAIL => "Cannot assign requested address", + ENETDOWN => "Network is down", + ENETUNREACH => "Network is unreachable", + ENETRESET => "Network dropped connection because of reset", + ECONNABORTED => "Software caused connection abort", + ECONNRESET => "Connection reset by peer", + ENOBUFS => "No buffer space available", + EISCONN => "Transport endpoint is already connected", + ENOTCONN => "Transport endpoint is not connected", + ESHUTDOWN => "Cannot send after transport endpoint shutdown", + #[cfg(not(target_os = "haiku"))] + ETOOMANYREFS => "Too many references: cannot splice", + ETIMEDOUT => "Connection timed out", + ECONNREFUSED => "Connection refused", + EHOSTDOWN => "Host is down", + EHOSTUNREACH => "No route to host", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ECHRNG => "Channel number out of range", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EL2NSYNC => "Level 2 not synchronized", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EL3HLT => "Level 3 halted", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EL3RST => "Level 3 reset", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ELNRNG => "Link number out of range", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EUNATCH => "Protocol driver not attached", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOCSI => "No CSI structure available", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EL2HLT => "Level 2 halted", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EBADE => "Invalid exchange", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EBADR => "Invalid request descriptor", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EXFULL => "Exchange full", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOANO => "No anode", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EBADRQC => "Invalid request code", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EBADSLT => "Invalid slot", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EBFONT => "Bad font file format", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOSTR => "Device not a stream", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENODATA => "No data available", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ETIME => "Timer expired", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOSR => "Out of streams resources", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENONET => "Machine is not on the network", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOPKG => "Package not installed", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EREMOTE => "Object is remote", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOLINK => "Link has been severed", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EADV => "Advertise error", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ESRMNT => "Srmount error", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ECOMM => "Communication error on send", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EPROTO => "Protocol error", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EMULTIHOP => "Multihop attempted", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EDOTDOT => "RFS specific error", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EBADMSG => "Not a data message", + + #[cfg(any(target_os = "illumos", target_os = "solaris"))] + EBADMSG => "Trying to read unreadable message", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia", + target_os = "haiku" + ))] + EOVERFLOW => "Value too large for defined data type", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ENOTUNIQ => "Name not unique on network", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EBADFD => "File descriptor in bad state", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EREMCHG => "Remote address changed", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ELIBACC => "Can not access a needed shared library", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ELIBBAD => "Accessing a corrupted shared library", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ELIBSCN => ".lib section in a.out corrupted", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ELIBMAX => "Attempting to link in too many shared libraries", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ELIBEXEC => "Cannot exec a shared library directly", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia", + target_os = "openbsd" + ))] + EILSEQ => "Illegal byte sequence", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ERESTART => "Interrupted system call should be restarted", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + ESTRPIPE => "Streams pipe error", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia" + ))] + EUSERS => "Too many users", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia", + target_os = "netbsd", + target_os = "redox" + ))] + EOPNOTSUPP => "Operation not supported on transport endpoint", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + ESTALE => "Stale file handle", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EUCLEAN => "Structure needs cleaning", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + ENOTNAM => "Not a XENIX named type file", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + ENAVAIL => "No XENIX semaphores available", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EISNAM => "Is a named type file", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EREMOTEIO => "Remote I/O error", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EDQUOT => "Quota exceeded", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia", + target_os = "openbsd", + target_os = "dragonfly" + ))] + ENOMEDIUM => "No medium found", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia", + target_os = "openbsd" + ))] + EMEDIUMTYPE => "Wrong medium type", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris", + target_os = "fuchsia", + target_os = "haiku" + ))] + ECANCELED => "Operation canceled", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + ENOKEY => "Required key not available", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EKEYEXPIRED => "Key has expired", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EKEYREVOKED => "Key has been revoked", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EKEYREJECTED => "Key was rejected by service", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] + EOWNERDEAD => "Owner died", #[cfg(any(target_os = "illumos", target_os = "solaris"))] - EBADMSG => "Trying to read unreadable message", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EOVERFLOW => "Value too large for defined data type", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ENOTUNIQ => "Name not unique on network", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EBADFD => "File descriptor in bad state", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EREMCHG => "Remote address changed", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ELIBACC => "Can not access a needed shared library", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ELIBBAD => "Accessing a corrupted shared library", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ELIBSCN => ".lib section in a.out corrupted", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ELIBMAX => "Attempting to link in too many shared libraries", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ELIBEXEC => "Cannot exec a shared library directly", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia", target_os = "openbsd"))] - EILSEQ => "Illegal byte sequence", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ERESTART => "Interrupted system call should be restarted", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ESTRPIPE => "Streams pipe error", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - EUSERS => "Too many users", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia", target_os = "netbsd", - target_os = "redox"))] - EOPNOTSUPP => "Operation not supported on transport endpoint", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - ESTALE => "Stale file handle", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EUCLEAN => "Structure needs cleaning", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - ENOTNAM => "Not a XENIX named type file", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - ENAVAIL => "No XENIX semaphores available", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EISNAM => "Is a named type file", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EREMOTEIO => "Remote I/O error", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EDQUOT => "Quota exceeded", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia", target_os = "openbsd", - target_os = "dragonfly"))] - ENOMEDIUM => "No medium found", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia", target_os = "openbsd"))] - EMEDIUMTYPE => "Wrong medium type", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "illumos", target_os = "solaris", - target_os = "fuchsia"))] - ECANCELED => "Operation canceled", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - ENOKEY => "Required key not available", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EKEYEXPIRED => "Key has expired", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EKEYREVOKED => "Key has been revoked", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EKEYREJECTED => "Key was rejected by service", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] - EOWNERDEAD => "Owner died", - - #[cfg(any( target_os = "illumos", target_os = "solaris"))] - EOWNERDEAD => "Process died with lock", - - #[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] + EOWNERDEAD => "Process died with lock", + + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia" + ))] ENOTRECOVERABLE => "State not recoverable", #[cfg(any(target_os = "illumos", target_os = "solaris"))] ENOTRECOVERABLE => "Lock is not recoverable", - #[cfg(any(all(target_os = "linux", not(target_arch="mips")), - target_os = "fuchsia"))] - ERFKILL => "Operation not possible due to RF-kill", + #[cfg(any( + all(target_os = "linux", not(target_arch = "mips")), + target_os = "fuchsia" + ))] + ERFKILL => "Operation not possible due to RF-kill", - #[cfg(any(all(target_os = "linux", not(target_arch="mips")), - target_os = "fuchsia"))] - EHWPOISON => "Memory page has hardware error", + #[cfg(any( + all(target_os = "linux", not(target_arch = "mips")), + target_os = "fuchsia" + ))] + EHWPOISON => "Memory page has hardware error", #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - EDOOFUS => "Programming error", - - #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "redox"))] - EMULTIHOP => "Multihop attempted", - - #[cfg(any(target_os = "freebsd", target_os = "dragonfly", - target_os = "redox"))] - ENOLINK => "Link has been severed", + EDOOFUS => "Programming error", + + #[cfg(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "redox" + ))] + EMULTIHOP => "Multihop attempted", + + #[cfg(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "redox" + ))] + ENOLINK => "Link has been severed", #[cfg(target_os = "freebsd")] - ENOTCAPABLE => "Capabilities insufficient", + ENOTCAPABLE => "Capabilities insufficient", #[cfg(target_os = "freebsd")] - ECAPMODE => "Not permitted in capability mode", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - ENEEDAUTH => "Need authenticator", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox", target_os = "illumos", - target_os = "solaris"))] - EOVERFLOW => "Value too large to be stored in data type", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "netbsd", target_os = "redox"))] - EILSEQ => "Illegal byte sequence", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - ENOATTR => "Attribute not found", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox"))] - EBADMSG => "Bad message", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox"))] - EPROTO => "Protocol error", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd"))] + ECAPMODE => "Not permitted in capability mode", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + ENEEDAUTH => "Need authenticator", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox", + target_os = "illumos", + target_os = "solaris" + ))] + EOVERFLOW => "Value too large to be stored in data type", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "netbsd", + target_os = "redox", + target_os = "haiku" + ))] + EILSEQ => "Illegal byte sequence", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" + ))] + ENOATTR => "Attribute not found", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox", + target_os = "haiku" + ))] + EBADMSG => "Bad message", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox", + target_os = "haiku" + ))] + EPROTO => "Protocol error", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd" + ))] ENOTRECOVERABLE => "State not recoverable", - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd"))] - EOWNERDEAD => "Previous owner died", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "illumos", target_os = "solaris"))] - ENOTSUP => "Operation not supported", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EPROCLIM => "Too many processes", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox"))] - EUSERS => "Too many users", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox", target_os = "illumos", - target_os = "solaris"))] - EDQUOT => "Disc quota exceeded", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox", target_os = "illumos", - target_os = "solaris"))] - ESTALE => "Stale NFS file handle", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox"))] - EREMOTE => "Too many levels of remote in path", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EBADRPC => "RPC struct is bad", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - ERPCMISMATCH => "RPC version wrong", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EPROGUNAVAIL => "RPC prog. not avail", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EPROGMISMATCH => "Program version wrong", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EPROCUNAVAIL => "Bad procedure for program", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EFTYPE => "Inappropriate file type or format", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd"))] - EAUTH => "Authentication error", - - #[cfg(any(target_os = "macos", target_os = "freebsd", - target_os = "dragonfly", target_os = "ios", - target_os = "openbsd", target_os = "netbsd", - target_os = "redox"))] - ECANCELED => "Operation canceled", + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd" + ))] + EOWNERDEAD => "Previous owner died", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "illumos", + target_os = "solaris", + target_os = "haiku" + ))] + ENOTSUP => "Operation not supported", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EPROCLIM => "Too many processes", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox" + ))] + EUSERS => "Too many users", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox", + target_os = "illumos", + target_os = "solaris", + target_os = "haiku" + ))] + EDQUOT => "Disc quota exceeded", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox", + target_os = "illumos", + target_os = "solaris", + target_os = "haiku" + ))] + ESTALE => "Stale NFS file handle", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox" + ))] + EREMOTE => "Too many levels of remote in path", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EBADRPC => "RPC struct is bad", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + ERPCMISMATCH => "RPC version wrong", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EPROGUNAVAIL => "RPC prog. not avail", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EPROGMISMATCH => "Program version wrong", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EPROCUNAVAIL => "Bad procedure for program", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EFTYPE => "Inappropriate file type or format", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ))] + EAUTH => "Authentication error", + + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd", + target_os = "redox" + ))] + ECANCELED => "Operation canceled", #[cfg(any(target_os = "macos", target_os = "ios"))] - EPWROFF => "Device power is off", + EPWROFF => "Device power is off", #[cfg(any(target_os = "macos", target_os = "ios"))] - EDEVERR => "Device error, e.g. paper out", + EDEVERR => "Device error, e.g. paper out", #[cfg(any(target_os = "macos", target_os = "ios"))] - EBADEXEC => "Bad executable", + EBADEXEC => "Bad executable", #[cfg(any(target_os = "macos", target_os = "ios"))] - EBADARCH => "Bad CPU type in executable", + EBADARCH => "Bad CPU type in executable", #[cfg(any(target_os = "macos", target_os = "ios"))] - ESHLIBVERS => "Shared library version mismatch", + ESHLIBVERS => "Shared library version mismatch", #[cfg(any(target_os = "macos", target_os = "ios"))] - EBADMACHO => "Malformed Macho file", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "netbsd"))] - EMULTIHOP => "Reserved", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "netbsd", target_os = "redox"))] - ENODATA => "No message available on STREAM", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "netbsd"))] - ENOLINK => "Reserved", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "netbsd", target_os = "redox"))] - ENOSR => "No STREAM resources", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "netbsd", target_os = "redox"))] - ENOSTR => "Not a STREAM", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "netbsd", target_os = "redox"))] - ETIME => "STREAM ioctl timeout", - - #[cfg(any(target_os = "macos", target_os = "ios", - target_os = "illumos", target_os = "solaris"))] - EOPNOTSUPP => "Operation not supported on socket", + EBADMACHO => "Malformed Macho file", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "haiku" + ))] + EMULTIHOP => "Reserved", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "redox" + ))] + ENODATA => "No message available on STREAM", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "haiku" + ))] + ENOLINK => "Reserved", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "redox" + ))] + ENOSR => "No STREAM resources", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "redox" + ))] + ENOSTR => "Not a STREAM", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "redox" + ))] + ETIME => "STREAM ioctl timeout", + + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "illumos", + target_os = "solaris" + ))] + EOPNOTSUPP => "Operation not supported on socket", #[cfg(any(target_os = "macos", target_os = "ios"))] - ENOPOLICY => "No such policy registered", + ENOPOLICY => "No such policy registered", #[cfg(any(target_os = "macos", target_os = "ios"))] - EQFULL => "Interface output queue is full", + EQFULL => "Interface output queue is full", #[cfg(target_os = "openbsd")] - EOPNOTSUPP => "Operation not supported", + EOPNOTSUPP => "Operation not supported", #[cfg(target_os = "openbsd")] - EIPSEC => "IPsec processing failure", + EIPSEC => "IPsec processing failure", #[cfg(target_os = "dragonfly")] - EASYNC => "Async", + EASYNC => "Async", #[cfg(any(target_os = "illumos", target_os = "solaris"))] - EDEADLOCK => "Resource deadlock would occur", + EDEADLOCK => "Resource deadlock would occur", #[cfg(any(target_os = "illumos", target_os = "solaris"))] - ELOCKUNMAPPED => "Locked lock was unmapped", + ELOCKUNMAPPED => "Locked lock was unmapped", #[cfg(any(target_os = "illumos", target_os = "solaris"))] - ENOTACTIVE => "Facility is not active", + ENOTACTIVE => "Facility is not active", } } -#[cfg(any(target_os = "linux", target_os = "android", - target_os = "fuchsia"))] +#[cfg(any(target_os = "linux", target_os = "android", target_os = "fuchsia"))] mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] #[non_exhaustive] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EAGAIN = libc::EAGAIN, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EDEADLK = libc::EDEADLK, - ENAMETOOLONG = libc::ENAMETOOLONG, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - ENOTEMPTY = libc::ENOTEMPTY, - ELOOP = libc::ELOOP, - ENOMSG = libc::ENOMSG, - EIDRM = libc::EIDRM, - ECHRNG = libc::ECHRNG, - EL2NSYNC = libc::EL2NSYNC, - EL3HLT = libc::EL3HLT, - EL3RST = libc::EL3RST, - ELNRNG = libc::ELNRNG, - EUNATCH = libc::EUNATCH, - ENOCSI = libc::ENOCSI, - EL2HLT = libc::EL2HLT, - EBADE = libc::EBADE, - EBADR = libc::EBADR, - EXFULL = libc::EXFULL, - ENOANO = libc::ENOANO, - EBADRQC = libc::EBADRQC, - EBADSLT = libc::EBADSLT, - EBFONT = libc::EBFONT, - ENOSTR = libc::ENOSTR, - ENODATA = libc::ENODATA, - ETIME = libc::ETIME, - ENOSR = libc::ENOSR, - ENONET = libc::ENONET, - ENOPKG = libc::ENOPKG, - EREMOTE = libc::EREMOTE, - ENOLINK = libc::ENOLINK, - EADV = libc::EADV, - ESRMNT = libc::ESRMNT, - ECOMM = libc::ECOMM, - EPROTO = libc::EPROTO, - EMULTIHOP = libc::EMULTIHOP, - EDOTDOT = libc::EDOTDOT, - EBADMSG = libc::EBADMSG, - EOVERFLOW = libc::EOVERFLOW, - ENOTUNIQ = libc::ENOTUNIQ, - EBADFD = libc::EBADFD, - EREMCHG = libc::EREMCHG, - ELIBACC = libc::ELIBACC, - ELIBBAD = libc::ELIBBAD, - ELIBSCN = libc::ELIBSCN, - ELIBMAX = libc::ELIBMAX, - ELIBEXEC = libc::ELIBEXEC, - EILSEQ = libc::EILSEQ, - ERESTART = libc::ERESTART, - ESTRPIPE = libc::ESTRPIPE, - EUSERS = libc::EUSERS, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EAGAIN = libc::EAGAIN, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EDEADLK = libc::EDEADLK, + ENAMETOOLONG = libc::ENAMETOOLONG, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + ENOTEMPTY = libc::ENOTEMPTY, + ELOOP = libc::ELOOP, + ENOMSG = libc::ENOMSG, + EIDRM = libc::EIDRM, + ECHRNG = libc::ECHRNG, + EL2NSYNC = libc::EL2NSYNC, + EL3HLT = libc::EL3HLT, + EL3RST = libc::EL3RST, + ELNRNG = libc::ELNRNG, + EUNATCH = libc::EUNATCH, + ENOCSI = libc::ENOCSI, + EL2HLT = libc::EL2HLT, + EBADE = libc::EBADE, + EBADR = libc::EBADR, + EXFULL = libc::EXFULL, + ENOANO = libc::ENOANO, + EBADRQC = libc::EBADRQC, + EBADSLT = libc::EBADSLT, + EBFONT = libc::EBFONT, + ENOSTR = libc::ENOSTR, + ENODATA = libc::ENODATA, + ETIME = libc::ETIME, + ENOSR = libc::ENOSR, + ENONET = libc::ENONET, + ENOPKG = libc::ENOPKG, + EREMOTE = libc::EREMOTE, + ENOLINK = libc::ENOLINK, + EADV = libc::EADV, + ESRMNT = libc::ESRMNT, + ECOMM = libc::ECOMM, + EPROTO = libc::EPROTO, + EMULTIHOP = libc::EMULTIHOP, + EDOTDOT = libc::EDOTDOT, + EBADMSG = libc::EBADMSG, + EOVERFLOW = libc::EOVERFLOW, + ENOTUNIQ = libc::ENOTUNIQ, + EBADFD = libc::EBADFD, + EREMCHG = libc::EREMCHG, + ELIBACC = libc::ELIBACC, + ELIBBAD = libc::ELIBBAD, + ELIBSCN = libc::ELIBSCN, + ELIBMAX = libc::ELIBMAX, + ELIBEXEC = libc::ELIBEXEC, + EILSEQ = libc::EILSEQ, + ERESTART = libc::ERESTART, + ESTRPIPE = libc::ESTRPIPE, + EUSERS = libc::EUSERS, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - EOPNOTSUPP = libc::EOPNOTSUPP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - EALREADY = libc::EALREADY, - EINPROGRESS = libc::EINPROGRESS, - ESTALE = libc::ESTALE, - EUCLEAN = libc::EUCLEAN, - ENOTNAM = libc::ENOTNAM, - ENAVAIL = libc::ENAVAIL, - EISNAM = libc::EISNAM, - EREMOTEIO = libc::EREMOTEIO, - EDQUOT = libc::EDQUOT, - ENOMEDIUM = libc::ENOMEDIUM, - EMEDIUMTYPE = libc::EMEDIUMTYPE, - ECANCELED = libc::ECANCELED, - ENOKEY = libc::ENOKEY, - EKEYEXPIRED = libc::EKEYEXPIRED, - EKEYREVOKED = libc::EKEYREVOKED, - EKEYREJECTED = libc::EKEYREJECTED, - EOWNERDEAD = libc::EOWNERDEAD, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + EALREADY = libc::EALREADY, + EINPROGRESS = libc::EINPROGRESS, + ESTALE = libc::ESTALE, + EUCLEAN = libc::EUCLEAN, + ENOTNAM = libc::ENOTNAM, + ENAVAIL = libc::ENAVAIL, + EISNAM = libc::EISNAM, + EREMOTEIO = libc::EREMOTEIO, + EDQUOT = libc::EDQUOT, + ENOMEDIUM = libc::ENOMEDIUM, + EMEDIUMTYPE = libc::EMEDIUMTYPE, + ECANCELED = libc::ECANCELED, + ENOKEY = libc::ENOKEY, + EKEYEXPIRED = libc::EKEYEXPIRED, + EKEYREVOKED = libc::EKEYREVOKED, + EKEYREJECTED = libc::EKEYREJECTED, + EOWNERDEAD = libc::EOWNERDEAD, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - #[cfg(not(any(target_os = "android", target_arch="mips")))] - ERFKILL = libc::ERFKILL, - #[cfg(not(any(target_os = "android", target_arch="mips")))] - EHWPOISON = libc::EHWPOISON, + #[cfg(not(any(target_os = "android", target_arch = "mips")))] + ERFKILL = libc::ERFKILL, + #[cfg(not(any(target_os = "android", target_arch = "mips")))] + EHWPOISON = libc::EHWPOISON, } #[deprecated( @@ -919,17 +1306,17 @@ mod consts { since = "0.22.1", note = "use nix::errno::Errno::EDEADLOCK instead" )] - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::ENOTSUP instead" )] - pub const ENOTSUP: Errno = Errno::EOPNOTSUPP; + pub const ENOTSUP: Errno = Errno::EOPNOTSUPP; impl Errno { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; - pub const ENOTSUP: Errno = Errno::EOPNOTSUPP; + pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const ENOTSUP: Errno = Errno::EOPNOTSUPP; } pub const fn from_i32(e: i32) -> Errno { @@ -1065,11 +1452,11 @@ mod consts { libc::EKEYREJECTED => EKEYREJECTED, libc::EOWNERDEAD => EOWNERDEAD, libc::ENOTRECOVERABLE => ENOTRECOVERABLE, - #[cfg(not(any(target_os = "android", target_arch="mips")))] + #[cfg(not(any(target_os = "android", target_arch = "mips")))] libc::ERFKILL => ERFKILL, - #[cfg(not(any(target_os = "android", target_arch="mips")))] + #[cfg(not(any(target_os = "android", target_arch = "mips")))] libc::EHWPOISON => EHWPOISON, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -1080,120 +1467,120 @@ mod consts { #[repr(i32)] #[non_exhaustive] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - ENOTSUP = libc::ENOTSUP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EPWROFF = libc::EPWROFF, - EDEVERR = libc::EDEVERR, - EOVERFLOW = libc::EOVERFLOW, - EBADEXEC = libc::EBADEXEC, - EBADARCH = libc::EBADARCH, - ESHLIBVERS = libc::ESHLIBVERS, - EBADMACHO = libc::EBADMACHO, - ECANCELED = libc::ECANCELED, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EILSEQ = libc::EILSEQ, - ENOATTR = libc::ENOATTR, - EBADMSG = libc::EBADMSG, - EMULTIHOP = libc::EMULTIHOP, - ENODATA = libc::ENODATA, - ENOLINK = libc::ENOLINK, - ENOSR = libc::ENOSR, - ENOSTR = libc::ENOSTR, - EPROTO = libc::EPROTO, - ETIME = libc::ETIME, - EOPNOTSUPP = libc::EOPNOTSUPP, - ENOPOLICY = libc::ENOPOLICY, + ENOTSUP = libc::ENOTSUP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EPWROFF = libc::EPWROFF, + EDEVERR = libc::EDEVERR, + EOVERFLOW = libc::EOVERFLOW, + EBADEXEC = libc::EBADEXEC, + EBADARCH = libc::EBADARCH, + ESHLIBVERS = libc::ESHLIBVERS, + EBADMACHO = libc::EBADMACHO, + ECANCELED = libc::ECANCELED, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENODATA = libc::ENODATA, + ENOLINK = libc::ENOLINK, + ENOSR = libc::ENOSR, + ENOSTR = libc::ENOSTR, + EPROTO = libc::EPROTO, + ETIME = libc::ETIME, + EOPNOTSUPP = libc::EOPNOTSUPP, + ENOPOLICY = libc::ENOPOLICY, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - EOWNERDEAD = libc::EOWNERDEAD, - EQFULL = libc::EQFULL, + EOWNERDEAD = libc::EOWNERDEAD, + EQFULL = libc::EQFULL, } #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::ELAST instead" )] - pub const ELAST: Errno = Errno::EQFULL; + pub const ELAST: Errno = Errno::EQFULL; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EWOULDBLOCK instead" @@ -1203,12 +1590,12 @@ mod consts { since = "0.22.1", note = "use nix::errno::Errno::EDEADLOCK instead" )] - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; impl Errno { - pub const ELAST: Errno = Errno::EQFULL; + pub const ELAST: Errno = Errno::EQFULL; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; } pub const fn from_i32(e: i32) -> Errno { @@ -1321,7 +1708,7 @@ mod consts { libc::ENOTRECOVERABLE => ENOTRECOVERABLE, libc::EOWNERDEAD => EOWNERDEAD, libc::EQFULL => EQFULL, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -1332,110 +1719,110 @@ mod consts { #[repr(i32)] #[non_exhaustive] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - ENOTSUP = libc::ENOTSUP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EOVERFLOW = libc::EOVERFLOW, - ECANCELED = libc::ECANCELED, - EILSEQ = libc::EILSEQ, - ENOATTR = libc::ENOATTR, - EDOOFUS = libc::EDOOFUS, - EBADMSG = libc::EBADMSG, - EMULTIHOP = libc::EMULTIHOP, - ENOLINK = libc::ENOLINK, - EPROTO = libc::EPROTO, - ENOTCAPABLE = libc::ENOTCAPABLE, - ECAPMODE = libc::ECAPMODE, + ENOTSUP = libc::ENOTSUP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EDOOFUS = libc::EDOOFUS, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, + ENOTCAPABLE = libc::ENOTCAPABLE, + ECAPMODE = libc::ECAPMODE, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - EOWNERDEAD = libc::EOWNERDEAD, + EOWNERDEAD = libc::EOWNERDEAD, } #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::ELAST instead" )] - pub const ELAST: Errno = Errno::EOWNERDEAD; + pub const ELAST: Errno = Errno::EOWNERDEAD; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EWOULDBLOCK instead" @@ -1445,18 +1832,18 @@ mod consts { since = "0.22.1", note = "use nix::errno::Errno::EDEADLOCK instead" )] - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EOPNOTSUPP instead" )] - pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; + pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; impl Errno { - pub const ELAST: Errno = Errno::EOWNERDEAD; + pub const ELAST: Errno = Errno::EOWNERDEAD; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; - pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; + pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; } pub const fn from_i32(e: i32) -> Errno { @@ -1559,122 +1946,121 @@ mod consts { libc::ECAPMODE => ECAPMODE, libc::ENOTRECOVERABLE => ENOTRECOVERABLE, libc::EOWNERDEAD => EOWNERDEAD, - _ => UnknownErrno, + _ => UnknownErrno, } } } - #[cfg(target_os = "dragonfly")] mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] #[non_exhaustive] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - ENOTSUP = libc::ENOTSUP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EOVERFLOW = libc::EOVERFLOW, - ECANCELED = libc::ECANCELED, - EILSEQ = libc::EILSEQ, - ENOATTR = libc::ENOATTR, - EDOOFUS = libc::EDOOFUS, - EBADMSG = libc::EBADMSG, - EMULTIHOP = libc::EMULTIHOP, - ENOLINK = libc::ENOLINK, - EPROTO = libc::EPROTO, - ENOMEDIUM = libc::ENOMEDIUM, + ENOTSUP = libc::ENOTSUP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EDOOFUS = libc::EDOOFUS, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, + ENOMEDIUM = libc::ENOMEDIUM, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - EOWNERDEAD = libc::EOWNERDEAD, - EASYNC = libc::EASYNC, + EOWNERDEAD = libc::EOWNERDEAD, + EASYNC = libc::EASYNC, } #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::ELAST instead" )] - pub const ELAST: Errno = Errno::EASYNC; + pub const ELAST: Errno = Errno::EASYNC; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EWOULDBLOCK instead" @@ -1684,18 +2070,18 @@ mod consts { since = "0.22.1", note = "use nix::errno::Errno::EDEADLOCK instead" )] - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EOPNOTSUPP instead" )] - pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; + pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; impl Errno { - pub const ELAST: Errno = Errno::EASYNC; + pub const ELAST: Errno = Errno::EASYNC; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; - pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; + pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; } pub const fn from_i32(e: i32) -> Errno { @@ -1722,7 +2108,7 @@ mod consts { libc::EXDEV => EXDEV, libc::ENODEV => ENODEV, libc::ENOTDIR => ENOTDIR, - libc::EISDIR=> EISDIR, + libc::EISDIR => EISDIR, libc::EINVAL => EINVAL, libc::ENFILE => ENFILE, libc::EMFILE => EMFILE, @@ -1796,121 +2182,120 @@ mod consts { libc::EPROTO => EPROTO, libc::ENOMEDIUM => ENOMEDIUM, libc::EASYNC => EASYNC, - _ => UnknownErrno, + _ => UnknownErrno, } } } - #[cfg(target_os = "openbsd")] mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] #[non_exhaustive] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - EOPNOTSUPP = libc::EOPNOTSUPP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIPSEC = libc::EIPSEC, - ENOATTR = libc::ENOATTR, - EILSEQ = libc::EILSEQ, - ENOMEDIUM = libc::ENOMEDIUM, - EMEDIUMTYPE = libc::EMEDIUMTYPE, - EOVERFLOW = libc::EOVERFLOW, - ECANCELED = libc::ECANCELED, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - ENOTSUP = libc::ENOTSUP, - EBADMSG = libc::EBADMSG, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIPSEC = libc::EIPSEC, + ENOATTR = libc::ENOATTR, + EILSEQ = libc::EILSEQ, + ENOMEDIUM = libc::ENOMEDIUM, + EMEDIUMTYPE = libc::EMEDIUMTYPE, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + ENOTSUP = libc::ENOTSUP, + EBADMSG = libc::EBADMSG, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - EOWNERDEAD = libc::EOWNERDEAD, - EPROTO = libc::EPROTO, + EOWNERDEAD = libc::EOWNERDEAD, + EPROTO = libc::EPROTO, } #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::ELAST instead" )] - pub const ELAST: Errno = Errno::ENOTSUP; + pub const ELAST: Errno = Errno::ENOTSUP; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EWOULDBLOCK instead" @@ -1918,7 +2303,7 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; impl Errno { - pub const ELAST: Errno = Errno::ENOTSUP; + pub const ELAST: Errno = Errno::ENOTSUP; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } @@ -2021,7 +2406,7 @@ mod consts { libc::ENOTRECOVERABLE => ENOTRECOVERABLE, libc::EOWNERDEAD => EOWNERDEAD, libc::EPROTO => EPROTO, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -2032,110 +2417,110 @@ mod consts { #[repr(i32)] #[non_exhaustive] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - EOPNOTSUPP = libc::EOPNOTSUPP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EOVERFLOW = libc::EOVERFLOW, - EILSEQ = libc::EILSEQ, - ENOTSUP = libc::ENOTSUP, - ECANCELED = libc::ECANCELED, - EBADMSG = libc::EBADMSG, - ENODATA = libc::ENODATA, - ENOSR = libc::ENOSR, - ENOSTR = libc::ENOSTR, - ETIME = libc::ETIME, - ENOATTR = libc::ENOATTR, - EMULTIHOP = libc::EMULTIHOP, - ENOLINK = libc::ENOLINK, - EPROTO = libc::EPROTO, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + EILSEQ = libc::EILSEQ, + ENOTSUP = libc::ENOTSUP, + ECANCELED = libc::ECANCELED, + EBADMSG = libc::EBADMSG, + ENODATA = libc::ENODATA, + ENOSR = libc::ENOSR, + ENOSTR = libc::ENOSTR, + ETIME = libc::ETIME, + ENOATTR = libc::ENOATTR, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, } #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::ELAST instead" )] - pub const ELAST: Errno = Errno::ENOTSUP; + pub const ELAST: Errno = Errno::ENOTSUP; #[deprecated( since = "0.22.1", note = "use nix::errno::Errno::EWOULDBLOCK instead" @@ -2143,7 +2528,7 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; impl Errno { - pub const ELAST: Errno = Errno::ENOTSUP; + pub const ELAST: Errno = Errno::ENOTSUP; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } @@ -2247,7 +2632,7 @@ mod consts { libc::EMULTIHOP => EMULTIHOP, libc::ENOLINK => ENOLINK, libc::EPROTO => EPROTO, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -2592,7 +2977,7 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; impl Errno { - pub const ELAST: Errno = Errno::ESTALE; + pub const ELAST: Errno = Errno::ESTALE; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } @@ -2725,3 +3110,177 @@ mod consts { } } } + +#[cfg(target_os = "haiku")] +mod consts { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + #[repr(i32)] + #[non_exhaustive] + pub enum Errno { + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, + EPROTONOSUPPORT = libc::EPROTONOSUPPORT, + ENOTSUP = libc::ENOTSUP, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, + } + + impl Errno { + pub const EWOULDBLOCK: Errno = Errno::EAGAIN; + pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; + } + + pub const fn from_i32(e: i32) -> Errno { + use self::Errno::*; + + match e { + libc::EPERM => EPERM, + libc::ENOENT => ENOENT, + libc::ESRCH => ESRCH, + libc::EINTR => EINTR, + libc::EIO => EIO, + libc::ENXIO => ENXIO, + libc::E2BIG => E2BIG, + libc::ENOEXEC => ENOEXEC, + libc::EBADF => EBADF, + libc::ECHILD => ECHILD, + libc::EDEADLK => EDEADLK, + libc::ENOMEM => ENOMEM, + libc::EACCES => EACCES, + libc::EFAULT => EFAULT, + libc::EBUSY => EBUSY, + libc::EEXIST => EEXIST, + libc::EXDEV => EXDEV, + libc::ENODEV => ENODEV, + libc::ENOTDIR => ENOTDIR, + libc::EISDIR => EISDIR, + libc::EINVAL => EINVAL, + libc::ENFILE => ENFILE, + libc::EMFILE => EMFILE, + libc::ENOTTY => ENOTTY, + libc::ETXTBSY => ETXTBSY, + libc::EFBIG => EFBIG, + libc::ENOSPC => ENOSPC, + libc::ESPIPE => ESPIPE, + libc::EROFS => EROFS, + libc::EMLINK => EMLINK, + libc::EPIPE => EPIPE, + libc::EDOM => EDOM, + libc::ERANGE => ERANGE, + libc::EAGAIN => EAGAIN, + libc::EINPROGRESS => EINPROGRESS, + libc::EALREADY => EALREADY, + libc::ENOTSOCK => ENOTSOCK, + libc::EDESTADDRREQ => EDESTADDRREQ, + libc::EMSGSIZE => EMSGSIZE, + libc::EPROTOTYPE => EPROTOTYPE, + libc::ENOPROTOOPT => ENOPROTOOPT, + libc::EPROTONOSUPPORT => EPROTONOSUPPORT, + libc::ENOTSUP => ENOTSUP, + libc::EADDRINUSE => EADDRINUSE, + libc::EADDRNOTAVAIL => EADDRNOTAVAIL, + libc::ENETDOWN => ENETDOWN, + libc::ENETUNREACH => ENETUNREACH, + libc::ENETRESET => ENETRESET, + libc::ECONNABORTED => ECONNABORTED, + libc::ECONNRESET => ECONNRESET, + libc::ENOBUFS => ENOBUFS, + libc::EISCONN => EISCONN, + libc::ENOTCONN => ENOTCONN, + libc::ESHUTDOWN => ESHUTDOWN, + libc::ETIMEDOUT => ETIMEDOUT, + libc::ECONNREFUSED => ECONNREFUSED, + libc::ELOOP => ELOOP, + libc::ENAMETOOLONG => ENAMETOOLONG, + libc::EHOSTDOWN => EHOSTDOWN, + libc::EHOSTUNREACH => EHOSTUNREACH, + libc::ENOTEMPTY => ENOTEMPTY, + libc::EDQUOT => EDQUOT, + libc::ESTALE => ESTALE, + libc::ENOLCK => ENOLCK, + libc::ENOSYS => ENOSYS, + libc::EIDRM => EIDRM, + libc::ENOMSG => ENOMSG, + libc::EOVERFLOW => EOVERFLOW, + libc::ECANCELED => ECANCELED, + libc::EILSEQ => EILSEQ, + libc::ENOATTR => ENOATTR, + libc::EBADMSG => EBADMSG, + libc::EMULTIHOP => EMULTIHOP, + libc::ENOLINK => ENOLINK, + libc::EPROTO => EPROTO, + _ => UnknownErrno, + } + } +} diff --git a/bash-5.1/vendor/nix/src/fcntl.rs b/bash-5.1/vendor/nix/src/fcntl.rs index fa64c8e..160b022 100644 --- a/bash-5.1/vendor/nix/src/fcntl.rs +++ b/bash-5.1/vendor/nix/src/fcntl.rs @@ -6,26 +6,22 @@ use std::os::raw; use std::os::unix::ffi::OsStringExt; use std::os::unix::io::RawFd; +#[cfg(feature = "fs")] +use crate::{sys::stat::Mode, NixPath, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] use std::ptr; // For splice and copy_file_range -#[cfg(feature = "fs")] -use crate::{ - NixPath, - Result, - sys::stat::Mode -}; #[cfg(any( target_os = "linux", target_os = "android", target_os = "emscripten", target_os = "fuchsia", - any(target_os = "wasi", target_env = "wasi"), + target_os = "wasi", target_env = "uclibc", target_os = "freebsd" ))] #[cfg(feature = "fs")] -pub use self::posix_fadvise::{PosixFadviseAdvice, posix_fadvise}; +pub use self::posix_fadvise::{posix_fadvise, PosixFadviseAdvice}; #[cfg(not(target_os = "redox"))] #[cfg(any(feature = "fs", feature = "process"))] @@ -58,7 +54,7 @@ libc_bitflags!( /// Open the file in append-only mode. O_APPEND; /// Generate a signal when input or output becomes possible. - #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] + #[cfg(not(any(target_os = "illumos", target_os = "solaris", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] O_ASYNC; /// Closes the file descriptor once an `execve` call is made. @@ -128,7 +124,7 @@ libc_bitflags!( #[cfg_attr(docsrs, doc(cfg(all())))] O_NOCTTY; /// Same as `O_NONBLOCK`. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] O_NDELAY; /// `open()` will fail if the given path is a symbolic link. @@ -241,10 +237,7 @@ pub fn renameat( } } -#[cfg(all( - target_os = "linux", - target_env = "gnu", -))] +#[cfg(all(target_os = "linux", target_env = "gnu",))] #[cfg(feature = "fs")] libc_bitflags! { #[cfg_attr(docsrs, doc(cfg(feature = "fs")))] @@ -385,7 +378,7 @@ pub(crate) fn at_rawfd(fd: Option) -> raw::c_int { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] #[cfg(feature = "fs")] libc_bitflags!( /// Additional flags for file sealing, which allows for limiting operations on a file. @@ -434,9 +427,9 @@ pub enum FcntlArg<'a> { F_OFD_SETLKW(&'a libc::flock), #[cfg(any(target_os = "linux", target_os = "android"))] F_OFD_GETLK(&'a mut libc::flock), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] F_ADD_SEALS(SealFlag), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] F_GET_SEALS, #[cfg(any(target_os = "macos", target_os = "ios"))] F_FULLFSYNC, @@ -482,9 +475,9 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { F_OFD_SETLKW(flock) => libc::fcntl(fd, libc::F_OFD_SETLKW, flock), #[cfg(any(target_os = "android", target_os = "linux"))] F_OFD_GETLK(flock) => libc::fcntl(fd, libc::F_OFD_GETLK, flock), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] F_ADD_SEALS(flag) => libc::fcntl(fd, libc::F_ADD_SEALS, flag.bits()), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] F_GET_SEALS => libc::fcntl(fd, libc::F_GET_SEALS), #[cfg(any(target_os = "macos", target_os = "ios"))] F_FULLFSYNC => libc::fcntl(fd, libc::F_FULLFSYNC), @@ -742,8 +735,8 @@ impl SpacectlRange { /// /// # Example /// -// no_run because it fails to link until FreeBSD 14.0 -/// ```no_run +#[cfg_attr(fbsd14, doc = " ```")] +#[cfg_attr(not(fbsd14), doc = " ```no_run")] /// # use std::io::Write; /// # use std::os::unix::fs::FileExt; /// # use std::os::unix::io::AsRawFd; @@ -788,8 +781,8 @@ pub fn fspacectl(fd: RawFd, range: SpacectlRange) -> Result { /// /// # Example /// -// no_run because it fails to link until FreeBSD 14.0 -/// ```no_run +#[cfg_attr(fbsd14, doc = " ```")] +#[cfg_attr(not(fbsd14), doc = " ```no_run")] /// # use std::io::Write; /// # use std::os::unix::fs::FileExt; /// # use std::os::unix::io::AsRawFd; @@ -828,7 +821,7 @@ pub fn fspacectl_all(fd: RawFd, offset: libc::off_t, len: libc::off_t) target_os = "android", target_os = "emscripten", target_os = "fuchsia", - any(target_os = "wasi", target_env = "wasi"), + target_os = "wasi", target_env = "uclibc", target_os = "freebsd" ))] @@ -877,7 +870,7 @@ mod posix_fadvise { target_os = "dragonfly", target_os = "emscripten", target_os = "fuchsia", - any(target_os = "wasi", target_env = "wasi"), + target_os = "wasi", target_os = "freebsd" ))] pub fn posix_fallocate(fd: RawFd, offset: libc::off_t, len: libc::off_t) -> Result<()> { diff --git a/bash-5.1/vendor/nix/src/features.rs b/bash-5.1/vendor/nix/src/features.rs index 6108098..d2adc16 100644 --- a/bash-5.1/vendor/nix/src/features.rs +++ b/bash-5.1/vendor/nix/src/features.rs @@ -114,6 +114,7 @@ mod os { #[cfg(any(target_os = "macos", target_os = "ios", target_os = "fuchsia", + target_os = "haiku", target_os = "solaris"))] mod os { /// Check if the OS supports atomic close-on-exec for sockets diff --git a/bash-5.1/vendor/nix/src/lib.rs b/bash-5.1/vendor/nix/src/lib.rs index d4dcbc4..770258d 100644 --- a/bash-5.1/vendor/nix/src/lib.rs +++ b/bash-5.1/vendor/nix/src/lib.rs @@ -52,20 +52,20 @@ #![deny(missing_copy_implementations)] #![deny(missing_debug_implementations)] #![warn(missing_docs)] - #![cfg_attr(docsrs, feature(doc_cfg))] +#![deny(clippy::cast_ptr_alignment)] // Re-exported external crates pub use libc; // Private internal modules -#[macro_use] mod macros; +#[macro_use] +mod macros; // Public crates #[cfg(not(target_os = "redox"))] feature! { #![feature = "dir"] - #[allow(missing_docs)] pub mod dir; } feature! { @@ -100,28 +100,25 @@ feature! { #[deny(missing_docs)] pub mod net; } -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] feature! { #![feature = "kmod"] #[allow(missing_docs)] pub mod kmod; } -#[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] feature! { #![feature = "mount"] pub mod mount; } -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "fushsia", - target_os = "linux", - target_os = "netbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd" +))] feature! { #![feature = "mqueue"] - #[allow(missing_docs)] pub mod mqueue; } feature! { @@ -146,9 +143,10 @@ feature! { } // This can be implemented for other platforms as soon as libc // provides bindings for them. -#[cfg(all(target_os = "linux", - any(target_arch = "s390x", target_arch = "x86", - target_arch = "x86_64")))] +#[cfg(all( + target_os = "linux", + any(target_arch = "s390x", target_arch = "x86", target_arch = "x86_64") +))] feature! { #![feature = "ucontext"] #[allow(missing_docs)] @@ -192,7 +190,8 @@ pub trait NixPath { /// /// Mostly used internally by Nix. fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T; + where + F: FnOnce(&CStr) -> T; } impl NixPath for str { @@ -205,9 +204,11 @@ impl NixPath for str { } fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T { - OsStr::new(self).with_nix_path(f) - } + where + F: FnOnce(&CStr) -> T, + { + OsStr::new(self).with_nix_path(f) + } } impl NixPath for OsStr { @@ -220,9 +221,11 @@ impl NixPath for OsStr { } fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T { - self.as_bytes().with_nix_path(f) - } + where + F: FnOnce(&CStr) -> T, + { + self.as_bytes().with_nix_path(f) + } } impl NixPath for CStr { @@ -275,7 +278,9 @@ impl NixPath for [u8] { buf_ptr.add(self.len()).write(0); } - match CStr::from_bytes_with_nul(unsafe { slice::from_raw_parts(buf_ptr, self.len() + 1) }) { + match CStr::from_bytes_with_nul(unsafe { + slice::from_raw_parts(buf_ptr, self.len() + 1) + }) { Ok(s) => Ok(f(s)), Err(_) => Err(Errno::EINVAL), } @@ -303,7 +308,10 @@ impl NixPath for Path { NixPath::len(self.as_os_str()) } - fn with_nix_path(&self, f: F) -> Result where F: FnOnce(&CStr) -> T { + fn with_nix_path(&self, f: F) -> Result + where + F: FnOnce(&CStr) -> T, + { self.as_os_str().with_nix_path(f) } } @@ -317,7 +325,10 @@ impl NixPath for PathBuf { NixPath::len(self.as_os_str()) } - fn with_nix_path(&self, f: F) -> Result where F: FnOnce(&CStr) -> T { + fn with_nix_path(&self, f: F) -> Result + where + F: FnOnce(&CStr) -> T, + { self.as_os_str().with_nix_path(f) } } diff --git a/bash-5.1/vendor/nix/src/macros.rs b/bash-5.1/vendor/nix/src/macros.rs index c357a06..99e0de8 100644 --- a/bash-5.1/vendor/nix/src/macros.rs +++ b/bash-5.1/vendor/nix/src/macros.rs @@ -19,7 +19,7 @@ macro_rules! feature { /// The `libc` crate must be in scope with the name `libc`. /// /// # Example -/// ``` +/// ```ignore /// libc_bitflags!{ /// pub struct ProtFlags: libc::c_int { /// PROT_NONE; @@ -39,7 +39,7 @@ macro_rules! feature { /// various flags have different types, so we cast the broken ones to the right /// type. /// -/// ``` +/// ```ignore /// libc_bitflags!{ /// pub struct SaFlags: libc::c_ulong { /// SA_NOCLDSTOP as libc::c_ulong; @@ -80,7 +80,7 @@ macro_rules! libc_bitflags { /// The `libc` crate must be in scope with the name `libc`. /// /// # Example -/// ``` +/// ```ignore /// libc_enum!{ /// pub enum ProtFlags { /// PROT_NONE, @@ -94,6 +94,9 @@ macro_rules! libc_bitflags { /// } /// } /// ``` +// Some targets don't use all rules. +#[allow(unknown_lints)] +#[allow(unused_macro_rules)] macro_rules! libc_enum { // Exit rule. (@make_enum diff --git a/bash-5.1/vendor/nix/src/mount/bsd.rs b/bash-5.1/vendor/nix/src/mount/bsd.rs index b4d611e..109522f 100644 --- a/bash-5.1/vendor/nix/src/mount/bsd.rs +++ b/bash-5.1/vendor/nix/src/mount/bsd.rs @@ -168,8 +168,9 @@ pub type NmountResult = std::result::Result<(), NmountError>; /// To mount `target` onto `mountpoint` with `nullfs`: /// ``` /// # use nix::unistd::Uid; -/// # use ::sysctl::CtlValue; -/// # if !Uid::current().is_root() && CtlValue::Int(0) == ::sysctl::value("vfs.usermount").unwrap() { +/// # use ::sysctl::{CtlValue, Sysctl}; +/// # let ctl = ::sysctl::Ctl::new("vfs.usermount").unwrap(); +/// # if !Uid::current().is_root() && CtlValue::Int(0) == ctl.value().unwrap() { /// # return; /// # }; /// use nix::mount::{MntFlags, Nmount, unmount}; diff --git a/bash-5.1/vendor/nix/src/mqueue.rs b/bash-5.1/vendor/nix/src/mqueue.rs index 792a5d2..e3c0c43 100644 --- a/bash-5.1/vendor/nix/src/mqueue.rs +++ b/bash-5.1/vendor/nix/src/mqueue.rs @@ -39,23 +39,29 @@ use crate::sys::stat::Mode; use std::mem; libc_bitflags!{ + /// Used with [`mq_open`]. pub struct MQ_OFlag: libc::c_int { + /// Open the message queue for receiving messages. O_RDONLY; + /// Open the queue for sending messages. O_WRONLY; + /// Open the queue for both receiving and sending messages O_RDWR; + /// Create a message queue. O_CREAT; + /// If set along with `O_CREAT`, `mq_open` will fail if the message + /// queue name exists. O_EXCL; + /// `mq_send` and `mq_receive` should fail with `EAGAIN` rather than + /// wait for resources that are not currently available. O_NONBLOCK; + /// Set the close-on-exec flag for the message queue descriptor. O_CLOEXEC; } } -libc_bitflags!{ - pub struct FdFlag: libc::c_int { - FD_CLOEXEC; - } -} - +/// A message-queue attribute, optionally used with [`mq_setattr`] and +/// [`mq_getattr`] and optionally [`mq_open`], #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct MqAttr { @@ -72,14 +78,24 @@ pub struct MqdT(mqd_t); // x32 compatibility // See https://sourceware.org/bugzilla/show_bug.cgi?id=21279 +/// Size of a message queue attribute member #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub type mq_attr_member_t = i64; +/// Size of a message queue attribute member #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] #[cfg_attr(docsrs, doc(cfg(all())))] pub type mq_attr_member_t = libc::c_long; impl MqAttr { + /// Create a new message queue attribute + /// + /// # Arguments + /// + /// - `mq_flags`: Either `0` or `O_NONBLOCK`. + /// - `mq_maxmsg`: Maximum number of messages on the queue. + /// - `mq_msgsize`: Maximum message size in bytes. + /// - `mq_curmsgs`: Number of messages currently in the queue. pub fn new(mq_flags: mq_attr_member_t, mq_maxmsg: mq_attr_member_t, mq_msgsize: mq_attr_member_t, @@ -97,6 +113,7 @@ impl MqAttr { } } + /// The current flags, either `0` or `O_NONBLOCK`. pub const fn flags(&self) -> mq_attr_member_t { self.mq_attr.mq_flags } diff --git a/bash-5.1/vendor/nix/src/net/if_.rs b/bash-5.1/vendor/nix/src/net/if_.rs index ebe8bcc..045efad 100644 --- a/bash-5.1/vendor/nix/src/net/if_.rs +++ b/bash-5.1/vendor/nix/src/net/if_.rs @@ -28,6 +28,7 @@ libc_bitflags!( IFF_BROADCAST; /// Internal debugging flag. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) + #[cfg(not(target_os = "haiku"))] IFF_DEBUG; /// Interface is a loopback interface. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) @@ -102,8 +103,7 @@ libc_bitflags!( target_os = "freebsd", target_os = "macos", target_os = "netbsd", - target_os = "openbsd", - target_os = "osx"))] + target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] IFF_SIMPLEX; /// Supports multicast. (see diff --git a/bash-5.1/vendor/nix/src/poll.rs b/bash-5.1/vendor/nix/src/poll.rs index 6d332b0..3004d24 100644 --- a/bash-5.1/vendor/nix/src/poll.rs +++ b/bash-5.1/vendor/nix/src/poll.rs @@ -151,20 +151,24 @@ feature! { /// `ppoll` behaves like `poll`, but let you specify what signals may interrupt it /// with the `sigmask` argument. If you want `ppoll` to block indefinitely, /// specify `None` as `timeout` (it is like `timeout = -1` for `poll`). +/// If `sigmask` is `None`, then no signal mask manipulation is performed, +/// so in that case `ppoll` differs from `poll` only in the precision of the +/// timeout argument. /// #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] pub fn ppoll( fds: &mut [PollFd], timeout: Option, - sigmask: crate::sys::signal::SigSet + sigmask: Option ) -> Result { let timeout = timeout.as_ref().map_or(core::ptr::null(), |r| r.as_ref()); + let sigmask = sigmask.as_ref().map_or(core::ptr::null(), |r| r.as_ref()); let res = unsafe { libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd, fds.len() as libc::nfds_t, timeout, - sigmask.as_ref()) + sigmask) }; Errno::result(res) } diff --git a/bash-5.1/vendor/nix/src/sched.rs b/bash-5.1/vendor/nix/src/sched.rs index e736f8d..e9a326e 100644 --- a/bash-5.1/vendor/nix/src/sched.rs +++ b/bash-5.1/vendor/nix/src/sched.rs @@ -233,8 +233,8 @@ mod sched_affinity { /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); - /// cpu_set.set(0); - /// sched_setaffinity(Pid::from_raw(0), &cpu_set); + /// cpu_set.set(0).unwrap(); + /// sched_setaffinity(Pid::from_raw(0), &cpu_set).unwrap(); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { diff --git a/bash-5.1/vendor/nix/src/sys/aio.rs b/bash-5.1/vendor/nix/src/sys/aio.rs index 4780cde..6ff8846 100644 --- a/bash-5.1/vendor/nix/src/sys/aio.rs +++ b/bash-5.1/vendor/nix/src/sys/aio.rs @@ -2,9 +2,12 @@ //! POSIX Asynchronous I/O //! //! The POSIX AIO interface is used for asynchronous I/O on files and disk-like -//! devices. It supports [`read`](struct.AioCb.html#method.read), -//! [`write`](struct.AioCb.html#method.write), and -//! [`fsync`](struct.AioCb.html#method.fsync) operations. Completion +//! devices. It supports [`read`](struct.AioRead.html#method.new), +//! [`write`](struct.AioWrite.html#method.new), +//! [`fsync`](struct.AioFsync.html#method.new), +//! [`readv`](struct.AioReadv.html#method.new), and +//! [`writev`](struct.AioWritev.html#method.new), operations, subject to +//! platform support. Completion //! notifications can optionally be delivered via //! [signals](../signal/enum.SigevNotify.html#variant.SigevSignal), via the //! [`aio_suspend`](fn.aio_suspend.html) function, or via polling. Some @@ -17,23 +20,30 @@ //! that they will be executed atomically. //! //! Outstanding operations may be cancelled with -//! [`cancel`](struct.AioCb.html#method.cancel) or +//! [`cancel`](trait.Aio.html#method.cancel) or //! [`aio_cancel_all`](fn.aio_cancel_all.html), though the operating system may //! not support this for all filesystems and devices. +#[cfg(target_os = "freebsd")] +use std::io::{IoSlice, IoSliceMut}; +use std::{ + convert::TryFrom, + fmt::{self, Debug}, + marker::{PhantomData, PhantomPinned}, + mem, + os::unix::io::RawFd, + pin::Pin, + ptr, + thread, +}; -use crate::Result; -use crate::errno::Errno; -use std::os::unix::io::RawFd; -use libc::{c_void, off_t, size_t}; -use std::fmt; -use std::fmt::Debug; -use std::marker::PhantomData; -use std::mem; -use std::pin::Pin; -use std::ptr::{null, null_mut}; -use crate::sys::signal::*; -use std::thread; -use crate::sys::time::TimeSpec; +use libc::{c_void, off_t}; +use pin_utils::unsafe_pinned; + +use crate::{ + errno::Errno, + sys::{signal::*, time::TimeSpec}, + Result, +}; libc_enum! { /// Mode for `AioCb::fsync`. Controls whether only data or both data and @@ -52,22 +62,7 @@ libc_enum! { #[cfg_attr(docsrs, doc(cfg(all())))] O_DSYNC } -} - -libc_enum! { - /// When used with [`lio_listio`](fn.lio_listio.html), determines whether a - /// given `aiocb` should be used for a read operation, a write operation, or - /// ignored. Has no effect for any other aio functions. - #[repr(i32)] - #[non_exhaustive] - pub enum LioOpcode { - /// No operation - LIO_NOP, - /// Write data as if by a call to [`AioCb::write`] - LIO_WRITE, - /// Write data as if by a call to [`AioCb::read`] - LIO_READ, - } + impl TryFrom } libc_enum! { @@ -103,354 +98,133 @@ struct LibcAiocb(libc::aiocb); unsafe impl Send for LibcAiocb {} unsafe impl Sync for LibcAiocb {} -/// AIO Control Block. -/// -/// The basic structure used by all aio functions. Each `AioCb` represents one -/// I/O request. -pub struct AioCb<'a> { - aiocb: LibcAiocb, - /// Tracks whether the buffer pointed to by `libc::aiocb.aio_buf` is mutable - mutable: bool, +/// Base class for all AIO operations. Should only be used directly when +/// checking for completion. +// We could create some kind of AsPinnedMut trait, and implement it for all aio +// ops, allowing the crate's users to get pinned references to `AioCb`. That +// could save some code for things like polling methods. But IMHO it would +// provide polymorphism at the wrong level. Instead, the best place for +// polymorphism is at the level of `Futures`. +#[repr(C)] +struct AioCb { + aiocb: LibcAiocb, /// Could this `AioCb` potentially have any in-kernel state? + // It would be really nice to perform the in-progress check entirely at + // compile time. But I can't figure out how, because: + // * Future::poll takes a `Pin<&mut self>` rather than `self`, and + // * Rust's lack of an equivalent of C++'s Guaranteed Copy Elision means + // that there's no way to write an AioCb constructor that neither boxes + // the object itself, nor moves it during return. in_progress: bool, - _buffer: std::marker::PhantomData<&'a [u8]>, - _pin: std::marker::PhantomPinned } -impl<'a> AioCb<'a> { - /// Returns the underlying file descriptor associated with the `AioCb` - pub fn fd(&self) -> RawFd { - self.aiocb.0.aio_fildes - } +impl AioCb { + pin_utils::unsafe_unpinned!(aiocb: LibcAiocb); - /// Constructs a new `AioCb` with no associated buffer. - /// - /// The resulting `AioCb` structure is suitable for use with `AioCb::fsync`. - /// - /// # Parameters - /// - /// * `fd`: File descriptor. Required for all aio functions. - /// * `prio`: If POSIX Prioritized IO is supported, then the - /// operation will be prioritized at the process's - /// priority level minus `prio`. - /// * `sigev_notify`: Determines how you will be notified of event - /// completion. - /// - /// # Examples - /// - /// Create an `AioCb` from a raw file descriptor and use it for an - /// [`fsync`](#method.fsync) operation. - /// - /// ``` - /// # use nix::errno::Errno; - /// # use nix::Error; - /// # use nix::sys::aio::*; - /// # use nix::sys::signal::SigevNotify::SigevNone; - /// # use std::{thread, time}; - /// # use std::os::unix::io::AsRawFd; - /// # use tempfile::tempfile; - /// let f = tempfile().unwrap(); - /// let mut aiocb = AioCb::from_fd( f.as_raw_fd(), 0, SigevNone); - /// aiocb.fsync(AioFsyncMode::O_SYNC).expect("aio_fsync failed early"); - /// while (aiocb.error() == Err(Errno::EINPROGRESS)) { - /// thread::sleep(time::Duration::from_millis(10)); - /// } - /// aiocb.aio_return().expect("aio_fsync failed late"); - /// ``` - pub fn from_fd(fd: RawFd, prio: libc::c_int, - sigev_notify: SigevNotify) -> Pin>> { - let mut a = AioCb::common_init(fd, prio, sigev_notify); - a.0.aio_offset = 0; - a.0.aio_nbytes = 0; - a.0.aio_buf = null_mut(); - - Box::pin(AioCb { - aiocb: a, - mutable: false, - in_progress: false, - _buffer: PhantomData, - _pin: std::marker::PhantomPinned - }) + fn aio_return(mut self: Pin<&mut Self>) -> Result { + self.in_progress = false; + unsafe { + let p: *mut libc::aiocb = &mut self.aiocb.0; + Errno::result(libc::aio_return(p)) + } + .map(|r| r as usize) } - // Private helper - #[cfg(not(any(target_os = "ios", target_os = "macos")))] - fn from_mut_slice_unpinned(fd: RawFd, offs: off_t, buf: &'a mut [u8], - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb<'a> - { - let mut a = AioCb::common_init(fd, prio, sigev_notify); - a.0.aio_offset = offs; - a.0.aio_nbytes = buf.len() as size_t; - a.0.aio_buf = buf.as_ptr() as *mut c_void; - a.0.aio_lio_opcode = opcode as libc::c_int; + fn cancel(mut self: Pin<&mut Self>) -> Result { + let r = unsafe { + libc::aio_cancel(self.aiocb.0.aio_fildes, &mut self.aiocb.0) + }; + match r { + libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled), + libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled), + libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone), + -1 => Err(Errno::last()), + _ => panic!("unknown aio_cancel return value"), + } + } + fn common_init(fd: RawFd, prio: i32, sigev_notify: SigevNotify) -> Self { + // Use mem::zeroed instead of explicitly zeroing each field, because the + // number and name of reserved fields is OS-dependent. On some OSes, + // some reserved fields are used the kernel for state, and must be + // explicitly zeroed when allocated. + let mut a = unsafe { mem::zeroed::() }; + a.aio_fildes = fd; + a.aio_reqprio = prio; + a.aio_sigevent = SigEvent::new(sigev_notify).sigevent(); AioCb { - aiocb: a, - mutable: true, + aiocb: LibcAiocb(a), in_progress: false, - _buffer: PhantomData, - _pin: std::marker::PhantomPinned } } - /// Constructs a new `AioCb` from a mutable slice. - /// - /// The resulting `AioCb` will be suitable for both read and write - /// operations, but only if the borrow checker can guarantee that the slice - /// will outlive the `AioCb`. That will usually be the case if the `AioCb` - /// is stack-allocated. - /// - /// # Parameters - /// - /// * `fd`: File descriptor. Required for all aio functions. - /// * `offs`: File offset - /// * `buf`: A memory buffer - /// * `prio`: If POSIX Prioritized IO is supported, then the - /// operation will be prioritized at the process's - /// priority level minus `prio` - /// * `sigev_notify`: Determines how you will be notified of event - /// completion. - /// * `opcode`: This field is only used for `lio_listio`. It - /// determines which operation to use for this individual - /// aiocb - /// - /// # Examples - /// - /// Create an `AioCb` from a mutable slice and read into it. - /// - /// ``` - /// # use nix::errno::Errno; - /// # use nix::Error; - /// # use nix::sys::aio::*; - /// # use nix::sys::signal::SigevNotify; - /// # use std::{thread, time}; - /// # use std::io::Write; - /// # use std::os::unix::io::AsRawFd; - /// # use tempfile::tempfile; - /// const INITIAL: &[u8] = b"abcdef123456"; - /// const LEN: usize = 4; - /// let mut rbuf = vec![0; LEN]; - /// let mut f = tempfile().unwrap(); - /// f.write_all(INITIAL).unwrap(); - /// { - /// let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - /// 2, //offset - /// &mut rbuf, - /// 0, //priority - /// SigevNotify::SigevNone, - /// LioOpcode::LIO_NOP); - /// aiocb.read().unwrap(); - /// while (aiocb.error() == Err(Errno::EINPROGRESS)) { - /// thread::sleep(time::Duration::from_millis(10)); - /// } - /// assert_eq!(aiocb.aio_return().unwrap() as usize, LEN); - /// } - /// assert_eq!(rbuf, b"cdef"); - /// ``` - pub fn from_mut_slice(fd: RawFd, offs: off_t, buf: &'a mut [u8], - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> Pin>> { - let mut a = AioCb::common_init(fd, prio, sigev_notify); - a.0.aio_offset = offs; - a.0.aio_nbytes = buf.len() as size_t; - a.0.aio_buf = buf.as_ptr() as *mut c_void; - a.0.aio_lio_opcode = opcode as libc::c_int; - - Box::pin(AioCb { - aiocb: a, - mutable: true, - in_progress: false, - _buffer: PhantomData, - _pin: std::marker::PhantomPinned - }) + fn error(self: Pin<&mut Self>) -> Result<()> { + let r = unsafe { libc::aio_error(&self.aiocb().0) }; + match r { + 0 => Ok(()), + num if num > 0 => Err(Errno::from_i32(num)), + -1 => Err(Errno::last()), + num => panic!("unknown aio_error return value {:?}", num), + } } - /// Constructs a new `AioCb` from a mutable raw pointer - /// - /// Unlike `from_mut_slice`, this method returns a structure suitable for - /// placement on the heap. It may be used for both reads and writes. Due - /// to its unsafety, this method is not recommended. It is most useful when - /// heap allocation is required. - /// - /// # Parameters - /// - /// * `fd`: File descriptor. Required for all aio functions. - /// * `offs`: File offset - /// * `buf`: Pointer to the memory buffer - /// * `len`: Length of the buffer pointed to by `buf` - /// * `prio`: If POSIX Prioritized IO is supported, then the - /// operation will be prioritized at the process's - /// priority level minus `prio` - /// * `sigev_notify`: Determines how you will be notified of event - /// completion. - /// * `opcode`: This field is only used for `lio_listio`. It - /// determines which operation to use for this individual - /// aiocb - /// - /// # Safety - /// - /// The caller must ensure that the storage pointed to by `buf` outlives the - /// `AioCb`. The lifetime checker can't help here. - pub unsafe fn from_mut_ptr(fd: RawFd, offs: off_t, - buf: *mut c_void, len: usize, - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> Pin>> { - let mut a = AioCb::common_init(fd, prio, sigev_notify); - a.0.aio_offset = offs; - a.0.aio_nbytes = len; - a.0.aio_buf = buf; - a.0.aio_lio_opcode = opcode as libc::c_int; - - Box::pin(AioCb { - aiocb: a, - mutable: true, - in_progress: false, - _buffer: PhantomData, - _pin: std::marker::PhantomPinned, - }) + fn in_progress(&self) -> bool { + self.in_progress } - /// Constructs a new `AioCb` from a raw pointer. - /// - /// Unlike `from_slice`, this method returns a structure suitable for - /// placement on the heap. Due to its unsafety, this method is not - /// recommended. It is most useful when heap allocation is required. - /// - /// # Parameters - /// - /// * `fd`: File descriptor. Required for all aio functions. - /// * `offs`: File offset - /// * `buf`: Pointer to the memory buffer - /// * `len`: Length of the buffer pointed to by `buf` - /// * `prio`: If POSIX Prioritized IO is supported, then the - /// operation will be prioritized at the process's - /// priority level minus `prio` - /// * `sigev_notify`: Determines how you will be notified of event - /// completion. - /// * `opcode`: This field is only used for `lio_listio`. It - /// determines which operation to use for this individual - /// aiocb - /// - /// # Safety - /// - /// The caller must ensure that the storage pointed to by `buf` outlives the - /// `AioCb`. The lifetime checker can't help here. - pub unsafe fn from_ptr(fd: RawFd, offs: off_t, - buf: *const c_void, len: usize, - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> Pin>> { - let mut a = AioCb::common_init(fd, prio, sigev_notify); - a.0.aio_offset = offs; - a.0.aio_nbytes = len; - // casting a const ptr to a mutable ptr here is ok, because we set the - // AioCb's mutable field to false - a.0.aio_buf = buf as *mut c_void; - a.0.aio_lio_opcode = opcode as libc::c_int; - - Box::pin(AioCb { - aiocb: a, - mutable: false, - in_progress: false, - _buffer: PhantomData, - _pin: std::marker::PhantomPinned - }) + fn set_in_progress(mut self: Pin<&mut Self>) { + self.as_mut().in_progress = true; } - // Private helper - fn from_slice_unpinned(fd: RawFd, offs: off_t, buf: &'a [u8], - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb - { - let mut a = AioCb::common_init(fd, prio, sigev_notify); - a.0.aio_offset = offs; - a.0.aio_nbytes = buf.len() as size_t; - // casting an immutable buffer to a mutable pointer looks unsafe, - // but technically its only unsafe to dereference it, not to create - // it. - a.0.aio_buf = buf.as_ptr() as *mut c_void; - assert!(opcode != LioOpcode::LIO_READ, "Can't read into an immutable buffer"); - a.0.aio_lio_opcode = opcode as libc::c_int; - - AioCb { - aiocb: a, - mutable: false, - in_progress: false, - _buffer: PhantomData, - _pin: std::marker::PhantomPinned - } + /// Update the notification settings for an existing AIO operation that has + /// not yet been submitted. + // Takes a normal reference rather than a pinned one because this method is + // normally called before the object needs to be pinned, that is, before + // it's been submitted to the kernel. + fn set_sigev_notify(&mut self, sigev_notify: SigevNotify) { + assert!( + !self.in_progress, + "Can't change notification settings for an in-progress operation" + ); + self.aiocb.0.aio_sigevent = SigEvent::new(sigev_notify).sigevent(); } +} - /// Like [`AioCb::from_mut_slice`], but works on constant slices rather than - /// mutable slices. - /// - /// An `AioCb` created this way cannot be used with `read`, and its - /// `LioOpcode` cannot be set to `LIO_READ`. This method is useful when - /// writing a const buffer with `AioCb::write`, since `from_mut_slice` can't - /// work with const buffers. - /// - /// # Examples - /// - /// Construct an `AioCb` from a slice and use it for writing. - /// - /// ``` - /// # use nix::errno::Errno; - /// # use nix::Error; - /// # use nix::sys::aio::*; - /// # use nix::sys::signal::SigevNotify; - /// # use std::{thread, time}; - /// # use std::os::unix::io::AsRawFd; - /// # use tempfile::tempfile; - /// const WBUF: &[u8] = b"abcdef123456"; - /// let mut f = tempfile().unwrap(); - /// let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - /// 2, //offset - /// WBUF, - /// 0, //priority - /// SigevNotify::SigevNone, - /// LioOpcode::LIO_NOP); - /// aiocb.write().unwrap(); - /// while (aiocb.error() == Err(Errno::EINPROGRESS)) { - /// thread::sleep(time::Duration::from_millis(10)); - /// } - /// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len()); - /// ``` - // Note: another solution to the problem of writing const buffers would be - // to genericize AioCb for both &mut [u8] and &[u8] buffers. AioCb::read - // could take the former and AioCb::write could take the latter. However, - // then lio_listio wouldn't work, because that function needs a slice of - // AioCb, and they must all be of the same type. - pub fn from_slice(fd: RawFd, offs: off_t, buf: &'a [u8], - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> Pin> - { - Box::pin(AioCb::from_slice_unpinned(fd, offs, buf, prio, sigev_notify, - opcode)) +impl Debug for AioCb { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("AioCb") + .field("aiocb", &self.aiocb.0) + .field("in_progress", &self.in_progress) + .finish() } +} - fn common_init(fd: RawFd, prio: libc::c_int, - sigev_notify: SigevNotify) -> LibcAiocb { - // Use mem::zeroed instead of explicitly zeroing each field, because the - // number and name of reserved fields is OS-dependent. On some OSes, - // some reserved fields are used the kernel for state, and must be - // explicitly zeroed when allocated. - let mut a = unsafe { mem::zeroed::()}; - a.aio_fildes = fd; - a.aio_reqprio = prio; - a.aio_sigevent = SigEvent::new(sigev_notify).sigevent(); - LibcAiocb(a) +impl Drop for AioCb { + /// If the `AioCb` has no remaining state in the kernel, just drop it. + /// Otherwise, dropping constitutes a resource leak, which is an error + fn drop(&mut self) { + assert!( + thread::panicking() || !self.in_progress, + "Dropped an in-progress AioCb" + ); } +} - /// Update the notification settings for an existing `aiocb` - pub fn set_sigev_notify(self: &mut Pin>, - sigev_notify: SigevNotify) - { - // Safe because we don't move any of the data - let selfp = unsafe { - self.as_mut().get_unchecked_mut() - }; - selfp.aiocb.0.aio_sigevent = SigEvent::new(sigev_notify).sigevent(); - } +/// Methods common to all AIO operations +pub trait Aio { + /// The return type of [`Aio::aio_return`]. + type Output; + + /// Retrieve return status of an asynchronous operation. + /// + /// Should only be called once for each operation, after [`Aio::error`] + /// indicates that it has completed. The result is the same as for the + /// synchronous `read(2)`, `write(2)`, of `fsync(2)` functions. + /// + /// # References + /// + /// [aio_return](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_return.html) + fn aio_return(self: Pin<&mut Self>) -> Result; /// Cancels an outstanding AIO request. /// @@ -477,51 +251,26 @@ impl<'a> AioCb<'a> { /// # use tempfile::tempfile; /// let wbuf = b"CDEF"; /// let mut f = tempfile().unwrap(); - /// let mut aiocb = AioCb::from_slice( f.as_raw_fd(), + /// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(), /// 2, //offset /// &wbuf[..], /// 0, //priority - /// SigevNotify::SigevNone, - /// LioOpcode::LIO_NOP); - /// aiocb.write().unwrap(); - /// let cs = aiocb.cancel().unwrap(); + /// SigevNotify::SigevNone)); + /// aiocb.as_mut().submit().unwrap(); + /// let cs = aiocb.as_mut().cancel().unwrap(); /// if cs == AioCancelStat::AioNotCanceled { - /// while (aiocb.error() == Err(Errno::EINPROGRESS)) { + /// while (aiocb.as_mut().error() == Err(Errno::EINPROGRESS)) { /// thread::sleep(time::Duration::from_millis(10)); /// } /// } /// // Must call `aio_return`, but ignore the result - /// let _ = aiocb.aio_return(); + /// let _ = aiocb.as_mut().aio_return(); /// ``` /// /// # References /// /// [aio_cancel](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html) - pub fn cancel(self: &mut Pin>) -> Result { - let r = unsafe { - let selfp = self.as_mut().get_unchecked_mut(); - libc::aio_cancel(selfp.aiocb.0.aio_fildes, &mut selfp.aiocb.0) - }; - match r { - libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled), - libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled), - libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone), - -1 => Err(Errno::last()), - _ => panic!("unknown aio_cancel return value") - } - } - - fn error_unpinned(&mut self) -> Result<()> { - let r = unsafe { - libc::aio_error(&mut self.aiocb.0 as *mut libc::aiocb) - }; - match r { - 0 => Ok(()), - num if num > 0 => Err(Errno::from_i32(num)), - -1 => Err(Errno::last()), - num => panic!("unknown aio_error return value {:?}", num) - } - } + fn cancel(self: Pin<&mut Self>) -> Result; /// Retrieve error status of an asynchronous operation. /// @@ -543,155 +292,222 @@ impl<'a> AioCb<'a> { /// # use tempfile::tempfile; /// const WBUF: &[u8] = b"abcdef123456"; /// let mut f = tempfile().unwrap(); - /// let mut aiocb = AioCb::from_slice( f.as_raw_fd(), + /// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(), /// 2, //offset /// WBUF, /// 0, //priority - /// SigevNotify::SigevNone, - /// LioOpcode::LIO_NOP); - /// aiocb.write().unwrap(); - /// while (aiocb.error() == Err(Errno::EINPROGRESS)) { + /// SigevNotify::SigevNone)); + /// aiocb.as_mut().submit().unwrap(); + /// while (aiocb.as_mut().error() == Err(Errno::EINPROGRESS)) { /// thread::sleep(time::Duration::from_millis(10)); /// } - /// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len()); + /// assert_eq!(aiocb.as_mut().aio_return().unwrap(), WBUF.len()); /// ``` /// /// # References /// /// [aio_error](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_error.html) - pub fn error(self: &mut Pin>) -> Result<()> { - // Safe because error_unpinned doesn't move the data - let selfp = unsafe { - self.as_mut().get_unchecked_mut() - }; - selfp.error_unpinned() - } + fn error(self: Pin<&mut Self>) -> Result<()>; - /// An asynchronous version of `fsync(2)`. + /// Returns the underlying file descriptor associated with the operation. + fn fd(&self) -> RawFd; + + /// Does this operation currently have any in-kernel state? /// - /// # References + /// Dropping an operation that does have in-kernel state constitutes a + /// resource leak. /// - /// [aio_fsync](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_fsync.html) - pub fn fsync(self: &mut Pin>, mode: AioFsyncMode) -> Result<()> { - // Safe because we don't move the libc::aiocb - unsafe { - let selfp = self.as_mut().get_unchecked_mut(); - Errno::result({ - let p: *mut libc::aiocb = &mut selfp.aiocb.0; - libc::aio_fsync(mode as libc::c_int, p) - }).map(|_| { - selfp.in_progress = true; - }) - } - } - - /// Returns the `aiocb`'s `LioOpcode` field + /// # Examples /// - /// If the value cannot be represented as an `LioOpcode`, returns `None` - /// instead. - pub fn lio_opcode(&self) -> Option { - match self.aiocb.0.aio_lio_opcode { - libc::LIO_READ => Some(LioOpcode::LIO_READ), - libc::LIO_WRITE => Some(LioOpcode::LIO_WRITE), - libc::LIO_NOP => Some(LioOpcode::LIO_NOP), - _ => None - } - } + /// ``` + /// # use nix::errno::Errno; + /// # use nix::Error; + /// # use nix::sys::aio::*; + /// # use nix::sys::signal::SigevNotify::SigevNone; + /// # use std::{thread, time}; + /// # use std::os::unix::io::AsRawFd; + /// # use tempfile::tempfile; + /// let f = tempfile().unwrap(); + /// let mut aiof = Box::pin(AioFsync::new(f.as_raw_fd(), AioFsyncMode::O_SYNC, + /// 0, SigevNone)); + /// assert!(!aiof.as_mut().in_progress()); + /// aiof.as_mut().submit().expect("aio_fsync failed early"); + /// assert!(aiof.as_mut().in_progress()); + /// while (aiof.as_mut().error() == Err(Errno::EINPROGRESS)) { + /// thread::sleep(time::Duration::from_millis(10)); + /// } + /// aiof.as_mut().aio_return().expect("aio_fsync failed late"); + /// assert!(!aiof.as_mut().in_progress()); + /// ``` + fn in_progress(&self) -> bool; - /// Returns the requested length of the aio operation in bytes - /// - /// This method returns the *requested* length of the operation. To get the - /// number of bytes actually read or written by a completed operation, use - /// `aio_return` instead. - pub fn nbytes(&self) -> usize { - self.aiocb.0.aio_nbytes - } + /// Returns the priority of the `AioCb` + fn priority(&self) -> i32; - /// Returns the file offset stored in the `AioCb` - pub fn offset(&self) -> off_t { - self.aiocb.0.aio_offset - } + /// Update the notification settings for an existing AIO operation that has + /// not yet been submitted. + fn set_sigev_notify(&mut self, sev: SigevNotify); - /// Returns the priority of the `AioCb` - pub fn priority(&self) -> libc::c_int { - self.aiocb.0.aio_reqprio - } + /// Returns the `SigEvent` that will be used for notification. + fn sigevent(&self) -> SigEvent; - /// Asynchronously reads from a file descriptor into a buffer + /// Actually start the I/O operation. /// - /// # References - /// - /// [aio_read](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_read.html) - pub fn read(self: &mut Pin>) -> Result<()> { - assert!(self.mutable, "Can't read into an immutable buffer"); - // Safe because we don't move anything - let selfp = unsafe { - self.as_mut().get_unchecked_mut() - }; - Errno::result({ - let p: *mut libc::aiocb = &mut selfp.aiocb.0; - unsafe { libc::aio_read(p) } - }).map(|_| { - selfp.in_progress = true; - }) - } + /// After calling this method and until [`Aio::aio_return`] returns `Ok`, + /// the structure may not be moved in memory. + fn submit(self: Pin<&mut Self>) -> Result<()>; +} - /// Returns the `SigEvent` stored in the `AioCb` - pub fn sigevent(&self) -> SigEvent { - SigEvent::from(&self.aiocb.0.aio_sigevent) - } +macro_rules! aio_methods { + () => { + fn cancel(self: Pin<&mut Self>) -> Result { + self.aiocb().cancel() + } - fn aio_return_unpinned(&mut self) -> Result { - unsafe { - let p: *mut libc::aiocb = &mut self.aiocb.0; - self.in_progress = false; - Errno::result(libc::aio_return(p)) + fn error(self: Pin<&mut Self>) -> Result<()> { + self.aiocb().error() } - } - /// Retrieve return status of an asynchronous operation. - /// - /// Should only be called once for each `AioCb`, after `AioCb::error` - /// indicates that it has completed. The result is the same as for the - /// synchronous `read(2)`, `write(2)`, of `fsync(2)` functions. - /// - /// # References - /// - /// [aio_return](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_return.html) - // Note: this should be just `return`, but that's a reserved word - pub fn aio_return(self: &mut Pin>) -> Result { - // Safe because aio_return_unpinned does not move the data - let selfp = unsafe { - self.as_mut().get_unchecked_mut() - }; - selfp.aio_return_unpinned() - } + fn fd(&self) -> RawFd { + self.aiocb.aiocb.0.aio_fildes + } - /// Asynchronously writes from a buffer to a file descriptor - /// - /// # References - /// - /// [aio_write](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_write.html) - pub fn write(self: &mut Pin>) -> Result<()> { - // Safe because we don't move anything - let selfp = unsafe { - self.as_mut().get_unchecked_mut() - }; - Errno::result({ - let p: *mut libc::aiocb = &mut selfp.aiocb.0; - unsafe{ libc::aio_write(p) } - }).map(|_| { - selfp.in_progress = true; - }) - } -} + fn in_progress(&self) -> bool { + self.aiocb.in_progress() + } -/// Cancels outstanding AIO requests for a given file descriptor. + fn priority(&self) -> i32 { + self.aiocb.aiocb.0.aio_reqprio + } + + fn set_sigev_notify(&mut self, sev: SigevNotify) { + self.aiocb.set_sigev_notify(sev) + } + + fn sigevent(&self) -> SigEvent { + SigEvent::from(&self.aiocb.aiocb.0.aio_sigevent) + } + }; + ($func:ident) => { + aio_methods!(); + + fn aio_return(self: Pin<&mut Self>) -> Result<::Output> { + self.aiocb().aio_return() + } + + fn submit(mut self: Pin<&mut Self>) -> Result<()> { + let p: *mut libc::aiocb = &mut self.as_mut().aiocb().aiocb.0; + Errno::result({ unsafe { libc::$func(p) } }).map(|_| { + self.aiocb().set_in_progress(); + }) + } + }; +} + +/// An asynchronous version of `fsync(2)`. +/// +/// # References +/// +/// [aio_fsync](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_fsync.html) +/// # Examples +/// +/// ``` +/// # use nix::errno::Errno; +/// # use nix::Error; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify::SigevNone; +/// # use std::{thread, time}; +/// # use std::os::unix::io::AsRawFd; +/// # use tempfile::tempfile; +/// let f = tempfile().unwrap(); +/// let mut aiof = Box::pin(AioFsync::new(f.as_raw_fd(), AioFsyncMode::O_SYNC, +/// 0, SigevNone)); +/// aiof.as_mut().submit().expect("aio_fsync failed early"); +/// while (aiof.as_mut().error() == Err(Errno::EINPROGRESS)) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// aiof.as_mut().aio_return().expect("aio_fsync failed late"); +/// ``` +#[derive(Debug)] +#[repr(transparent)] +pub struct AioFsync { + aiocb: AioCb, + _pin: PhantomPinned, +} + +impl AioFsync { + unsafe_pinned!(aiocb: AioCb); + + /// Returns the operation's fsync mode: data and metadata or data only? + pub fn mode(&self) -> AioFsyncMode { + AioFsyncMode::try_from(self.aiocb.aiocb.0.aio_lio_opcode).unwrap() + } + + /// Create a new `AioFsync`. + /// + /// # Arguments + /// + /// * `fd`: File descriptor to sync. + /// * `mode`: Whether to sync file metadata too, or just data. + /// * `prio`: If POSIX Prioritized IO is supported, then the + /// operation will be prioritized at the process's + /// priority level minus `prio`. + /// * `sigev_notify`: Determines how you will be notified of event + /// completion. + pub fn new( + fd: RawFd, + mode: AioFsyncMode, + prio: i32, + sigev_notify: SigevNotify, + ) -> Self { + let mut aiocb = AioCb::common_init(fd, prio, sigev_notify); + // To save some memory, store mode in an unused field of the AioCb. + // True it isn't very much memory, but downstream creates will likely + // create an enum containing this and other AioCb variants and pack + // those enums into data structures like Vec, so it adds up. + aiocb.aiocb.0.aio_lio_opcode = mode as libc::c_int; + AioFsync { + aiocb, + _pin: PhantomPinned, + } + } +} + +impl Aio for AioFsync { + type Output = (); + + aio_methods!(); + + fn aio_return(self: Pin<&mut Self>) -> Result<()> { + self.aiocb().aio_return().map(drop) + } + + fn submit(mut self: Pin<&mut Self>) -> Result<()> { + let aiocb = &mut self.as_mut().aiocb().aiocb.0; + let mode = mem::replace(&mut aiocb.aio_lio_opcode, 0); + let p: *mut libc::aiocb = aiocb; + Errno::result(unsafe { libc::aio_fsync(mode, p) }).map(|_| { + self.aiocb().set_in_progress(); + }) + } +} + +// AioFsync does not need AsMut, since it can't be used with lio_listio + +impl AsRef for AioFsync { + fn as_ref(&self) -> &libc::aiocb { + &self.aiocb.aiocb.0 + } +} + +/// Asynchronously reads from a file descriptor into a buffer +/// +/// # References +/// +/// [aio_read](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_read.html) /// /// # Examples /// -/// Issue an aio operation, then cancel all outstanding operations on that file -/// descriptor. /// /// ``` /// # use nix::errno::Errno; @@ -702,428 +518,727 @@ impl<'a> AioCb<'a> { /// # use std::io::Write; /// # use std::os::unix::io::AsRawFd; /// # use tempfile::tempfile; -/// let wbuf = b"CDEF"; +/// const INITIAL: &[u8] = b"abcdef123456"; +/// const LEN: usize = 4; +/// let mut rbuf = vec![0; LEN]; /// let mut f = tempfile().unwrap(); -/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(), -/// 2, //offset -/// &wbuf[..], -/// 0, //priority -/// SigevNotify::SigevNone, -/// LioOpcode::LIO_NOP); -/// aiocb.write().unwrap(); -/// let cs = aio_cancel_all(f.as_raw_fd()).unwrap(); -/// if cs == AioCancelStat::AioNotCanceled { -/// while (aiocb.error() == Err(Errno::EINPROGRESS)) { +/// f.write_all(INITIAL).unwrap(); +/// { +/// let mut aior = Box::pin( +/// AioRead::new( +/// f.as_raw_fd(), +/// 2, //offset +/// &mut rbuf, +/// 0, //priority +/// SigevNotify::SigevNone +/// ) +/// ); +/// aior.as_mut().submit().unwrap(); +/// while (aior.as_mut().error() == Err(Errno::EINPROGRESS)) { /// thread::sleep(time::Duration::from_millis(10)); /// } +/// assert_eq!(aior.as_mut().aio_return().unwrap(), LEN); /// } -/// // Must call `aio_return`, but ignore the result -/// let _ = aiocb.aio_return(); +/// assert_eq!(rbuf, b"cdef"); /// ``` -/// -/// # References -/// -/// [`aio_cancel`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html) -pub fn aio_cancel_all(fd: RawFd) -> Result { - match unsafe { libc::aio_cancel(fd, null_mut()) } { - libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled), - libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled), - libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone), - -1 => Err(Errno::last()), - _ => panic!("unknown aio_cancel return value") +#[derive(Debug)] +#[repr(transparent)] +pub struct AioRead<'a> { + aiocb: AioCb, + _data: PhantomData<&'a [u8]>, + _pin: PhantomPinned, +} + +impl<'a> AioRead<'a> { + unsafe_pinned!(aiocb: AioCb); + + /// Returns the requested length of the aio operation in bytes + /// + /// This method returns the *requested* length of the operation. To get the + /// number of bytes actually read or written by a completed operation, use + /// `aio_return` instead. + pub fn nbytes(&self) -> usize { + self.aiocb.aiocb.0.aio_nbytes + } + + /// Create a new `AioRead`, placing the data in a mutable slice. + /// + /// # Arguments + /// + /// * `fd`: File descriptor to read from + /// * `offs`: File offset + /// * `buf`: A memory buffer. It must outlive the `AioRead`. + /// * `prio`: If POSIX Prioritized IO is supported, then the + /// operation will be prioritized at the process's + /// priority level minus `prio` + /// * `sigev_notify`: Determines how you will be notified of event + /// completion. + pub fn new( + fd: RawFd, + offs: off_t, + buf: &'a mut [u8], + prio: i32, + sigev_notify: SigevNotify, + ) -> Self { + let mut aiocb = AioCb::common_init(fd, prio, sigev_notify); + aiocb.aiocb.0.aio_nbytes = buf.len(); + aiocb.aiocb.0.aio_buf = buf.as_mut_ptr() as *mut c_void; + aiocb.aiocb.0.aio_lio_opcode = libc::LIO_READ; + aiocb.aiocb.0.aio_offset = offs; + AioRead { + aiocb, + _data: PhantomData, + _pin: PhantomPinned, + } + } + + /// Returns the file offset of the operation. + pub fn offset(&self) -> off_t { + self.aiocb.aiocb.0.aio_offset } } -/// Suspends the calling process until at least one of the specified `AioCb`s -/// has completed, a signal is delivered, or the timeout has passed. +impl<'a> Aio for AioRead<'a> { + type Output = usize; + + aio_methods!(aio_read); +} + +impl<'a> AsMut for AioRead<'a> { + fn as_mut(&mut self) -> &mut libc::aiocb { + &mut self.aiocb.aiocb.0 + } +} + +impl<'a> AsRef for AioRead<'a> { + fn as_ref(&self) -> &libc::aiocb { + &self.aiocb.aiocb.0 + } +} + +/// Asynchronously reads from a file descriptor into a scatter/gather list of buffers. /// -/// If `timeout` is `None`, `aio_suspend` will block indefinitely. +/// # References +/// +/// [aio_readv](https://www.freebsd.org/cgi/man.cgi?query=aio_readv) /// /// # Examples /// -/// Use `aio_suspend` to block until an aio operation completes. /// -/// ``` +#[cfg_attr(fbsd14, doc = " ```")] +#[cfg_attr(not(fbsd14), doc = " ```no_run")] +/// # use nix::errno::Errno; +/// # use nix::Error; /// # use nix::sys::aio::*; /// # use nix::sys::signal::SigevNotify; +/// # use std::{thread, time}; +/// # use std::io::{IoSliceMut, Write}; /// # use std::os::unix::io::AsRawFd; /// # use tempfile::tempfile; -/// const WBUF: &[u8] = b"abcdef123456"; +/// const INITIAL: &[u8] = b"abcdef123456"; +/// let mut rbuf0 = vec![0; 4]; +/// let mut rbuf1 = vec![0; 2]; +/// let expected_len = rbuf0.len() + rbuf1.len(); +/// let mut rbufs = [IoSliceMut::new(&mut rbuf0), IoSliceMut::new(&mut rbuf1)]; /// let mut f = tempfile().unwrap(); -/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(), -/// 2, //offset -/// WBUF, -/// 0, //priority -/// SigevNotify::SigevNone, -/// LioOpcode::LIO_NOP); -/// aiocb.write().unwrap(); -/// aio_suspend(&[aiocb.as_ref()], None).expect("aio_suspend failed"); -/// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len()); +/// f.write_all(INITIAL).unwrap(); +/// { +/// let mut aior = Box::pin( +/// AioReadv::new( +/// f.as_raw_fd(), +/// 2, //offset +/// &mut rbufs, +/// 0, //priority +/// SigevNotify::SigevNone +/// ) +/// ); +/// aior.as_mut().submit().unwrap(); +/// while (aior.as_mut().error() == Err(Errno::EINPROGRESS)) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// assert_eq!(aior.as_mut().aio_return().unwrap(), expected_len); +/// } +/// assert_eq!(rbuf0, b"cdef"); +/// assert_eq!(rbuf1, b"12"); /// ``` -/// # References -/// -/// [`aio_suspend`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_suspend.html) -pub fn aio_suspend(list: &[Pin<&AioCb>], timeout: Option) -> Result<()> { - let plist = list as *const [Pin<&AioCb>] as *const [*const libc::aiocb]; - let p = plist as *const *const libc::aiocb; - let timep = match timeout { - None => null::(), - Some(x) => x.as_ref() as *const libc::timespec - }; - Errno::result(unsafe { - libc::aio_suspend(p, list.len() as i32, timep) - }).map(drop) +#[cfg(target_os = "freebsd")] +#[derive(Debug)] +#[repr(transparent)] +pub struct AioReadv<'a> { + aiocb: AioCb, + _data: PhantomData<&'a [&'a [u8]]>, + _pin: PhantomPinned, } -impl<'a> Debug for AioCb<'a> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("AioCb") - .field("aiocb", &self.aiocb.0) - .field("mutable", &self.mutable) - .field("in_progress", &self.in_progress) - .finish() +#[cfg(target_os = "freebsd")] +impl<'a> AioReadv<'a> { + unsafe_pinned!(aiocb: AioCb); + + /// Returns the number of buffers the operation will read into. + pub fn iovlen(&self) -> usize { + self.aiocb.aiocb.0.aio_nbytes } -} -impl<'a> Drop for AioCb<'a> { - /// If the `AioCb` has no remaining state in the kernel, just drop it. - /// Otherwise, dropping constitutes a resource leak, which is an error - fn drop(&mut self) { - assert!(thread::panicking() || !self.in_progress, - "Dropped an in-progress AioCb"); + /// Create a new `AioReadv`, placing the data in a list of mutable slices. + /// + /// # Arguments + /// + /// * `fd`: File descriptor to read from + /// * `offs`: File offset + /// * `bufs`: A scatter/gather list of memory buffers. They must + /// outlive the `AioReadv`. + /// * `prio`: If POSIX Prioritized IO is supported, then the + /// operation will be prioritized at the process's + /// priority level minus `prio` + /// * `sigev_notify`: Determines how you will be notified of event + /// completion. + pub fn new( + fd: RawFd, + offs: off_t, + bufs: &mut [IoSliceMut<'a>], + prio: i32, + sigev_notify: SigevNotify, + ) -> Self { + let mut aiocb = AioCb::common_init(fd, prio, sigev_notify); + // In vectored mode, aio_nbytes stores the length of the iovec array, + // not the byte count. + aiocb.aiocb.0.aio_nbytes = bufs.len(); + aiocb.aiocb.0.aio_buf = bufs.as_mut_ptr() as *mut c_void; + aiocb.aiocb.0.aio_lio_opcode = libc::LIO_READV; + aiocb.aiocb.0.aio_offset = offs; + AioReadv { + aiocb, + _data: PhantomData, + _pin: PhantomPinned, + } + } + + /// Returns the file offset of the operation. + pub fn offset(&self) -> off_t { + self.aiocb.aiocb.0.aio_offset } } -/// LIO Control Block. -/// -/// The basic structure used to issue multiple AIO operations simultaneously. -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(docsrs, doc(cfg(all())))] -pub struct LioCb<'a> { - /// A collection of [`AioCb`]s. All of these will be issued simultaneously - /// by the [`listio`] method. - /// - /// [`AioCb`]: struct.AioCb.html - /// [`listio`]: #method.listio - // Their locations in memory must be fixed once they are passed to the - // kernel. So this field must be non-public so the user can't swap. - aiocbs: Box<[AioCb<'a>]>, +#[cfg(target_os = "freebsd")] +impl<'a> Aio for AioReadv<'a> { + type Output = usize; - /// The actual list passed to `libc::lio_listio`. - /// - /// It must live for as long as any of the operations are still being - /// processesed, because the aio subsystem uses its address as a unique - /// identifier. - list: Vec<*mut libc::aiocb>, - - /// A partial set of results. This field will get populated by - /// `listio_resubmit` when an `LioCb` is resubmitted after an error - results: Vec>> + aio_methods!(aio_readv); } -/// LioCb can't automatically impl Send and Sync just because of the raw -/// pointers in list. But that's stupid. There's no reason that raw pointers -/// should automatically be non-Send -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -unsafe impl<'a> Send for LioCb<'a> {} -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -unsafe impl<'a> Sync for LioCb<'a> {} - -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(docsrs, doc(cfg(all())))] -impl<'a> LioCb<'a> { - /// Are no [`AioCb`]s contained? - pub fn is_empty(&self) -> bool { - self.aiocbs.is_empty() +#[cfg(target_os = "freebsd")] +impl<'a> AsMut for AioReadv<'a> { + fn as_mut(&mut self) -> &mut libc::aiocb { + &mut self.aiocb.aiocb.0 } +} - /// Return the number of individual [`AioCb`]s contained. - pub fn len(&self) -> usize { - self.aiocbs.len() +#[cfg(target_os = "freebsd")] +impl<'a> AsRef for AioReadv<'a> { + fn as_ref(&self) -> &libc::aiocb { + &self.aiocb.aiocb.0 } +} - /// Submits multiple asynchronous I/O requests with a single system call. - /// - /// They are not guaranteed to complete atomically, and the order in which - /// the requests are carried out is not specified. Reads, writes, and - /// fsyncs may be freely mixed. - /// - /// This function is useful for reducing the context-switch overhead of - /// submitting many AIO operations. It can also be used with - /// `LioMode::LIO_WAIT` to block on the result of several independent - /// operations. Used that way, it is often useful in programs that - /// otherwise make little use of AIO. - /// - /// # Examples - /// - /// Use `listio` to submit an aio operation and wait for its completion. In - /// this case, there is no need to use [`aio_suspend`] to wait or - /// [`AioCb::error`] to poll. - /// - /// ``` - /// # use nix::sys::aio::*; - /// # use nix::sys::signal::SigevNotify; - /// # use std::os::unix::io::AsRawFd; - /// # use tempfile::tempfile; - /// const WBUF: &[u8] = b"abcdef123456"; - /// let mut f = tempfile().unwrap(); - /// let mut liocb = LioCbBuilder::with_capacity(1) - /// .emplace_slice( - /// f.as_raw_fd(), - /// 2, //offset - /// WBUF, - /// 0, //priority - /// SigevNotify::SigevNone, - /// LioOpcode::LIO_WRITE - /// ).finish(); - /// liocb.listio(LioMode::LIO_WAIT, - /// SigevNotify::SigevNone).unwrap(); - /// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len()); - /// ``` - /// - /// # References - /// - /// [`lio_listio`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html) +/// Asynchronously writes from a buffer to a file descriptor +/// +/// # References +/// +/// [aio_write](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_write.html) +/// +/// # Examples +/// +/// ``` +/// # use nix::errno::Errno; +/// # use nix::Error; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify; +/// # use std::{thread, time}; +/// # use std::os::unix::io::AsRawFd; +/// # use tempfile::tempfile; +/// const WBUF: &[u8] = b"abcdef123456"; +/// let mut f = tempfile().unwrap(); +/// let mut aiow = Box::pin( +/// AioWrite::new( +/// f.as_raw_fd(), +/// 2, //offset +/// WBUF, +/// 0, //priority +/// SigevNotify::SigevNone +/// ) +/// ); +/// aiow.as_mut().submit().unwrap(); +/// while (aiow.as_mut().error() == Err(Errno::EINPROGRESS)) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// assert_eq!(aiow.as_mut().aio_return().unwrap(), WBUF.len()); +/// ``` +#[derive(Debug)] +#[repr(transparent)] +pub struct AioWrite<'a> { + aiocb: AioCb, + _data: PhantomData<&'a [u8]>, + _pin: PhantomPinned, +} + +impl<'a> AioWrite<'a> { + unsafe_pinned!(aiocb: AioCb); + + /// Returns the requested length of the aio operation in bytes /// - /// [`aio_suspend`]: fn.aio_suspend.html - /// [`AioCb::error`]: struct.AioCb.html#method.error - pub fn listio(&mut self, mode: LioMode, - sigev_notify: SigevNotify) -> Result<()> { - let sigev = SigEvent::new(sigev_notify); - let sigevp = &mut sigev.sigevent() as *mut libc::sigevent; - self.list.clear(); - for a in &mut self.aiocbs.iter_mut() { - a.in_progress = true; - self.list.push(a as *mut AioCb<'a> - as *mut libc::aiocb); - } - let p = self.list.as_ptr(); - Errno::result(unsafe { - libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp) - }).map(drop) + /// This method returns the *requested* length of the operation. To get the + /// number of bytes actually read or written by a completed operation, use + /// `aio_return` instead. + pub fn nbytes(&self) -> usize { + self.aiocb.aiocb.0.aio_nbytes } - /// Resubmits any incomplete operations with [`lio_listio`]. - /// - /// Sometimes, due to system resource limitations, an `lio_listio` call will - /// return `EIO`, or `EAGAIN`. Or, if a signal is received, it may return - /// `EINTR`. In any of these cases, only a subset of its constituent - /// operations will actually have been initiated. `listio_resubmit` will - /// resubmit any operations that are still uninitiated. - /// - /// After calling `listio_resubmit`, results should be collected by - /// [`LioCb::aio_return`]. - /// - /// # Examples - /// ```no_run - /// # use nix::Error; - /// # use nix::errno::Errno; - /// # use nix::sys::aio::*; - /// # use nix::sys::signal::SigevNotify; - /// # use std::os::unix::io::AsRawFd; - /// # use std::{thread, time}; - /// # use tempfile::tempfile; - /// const WBUF: &[u8] = b"abcdef123456"; - /// let mut f = tempfile().unwrap(); - /// let mut liocb = LioCbBuilder::with_capacity(1) - /// .emplace_slice( - /// f.as_raw_fd(), - /// 2, //offset - /// WBUF, - /// 0, //priority - /// SigevNotify::SigevNone, - /// LioOpcode::LIO_WRITE - /// ).finish(); - /// let mut err = liocb.listio(LioMode::LIO_WAIT, SigevNotify::SigevNone); - /// while err == Err(Errno::EIO) || - /// err == Err(Errno::EAGAIN) { - /// thread::sleep(time::Duration::from_millis(10)); - /// err = liocb.listio_resubmit(LioMode::LIO_WAIT, SigevNotify::SigevNone); - /// } - /// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len()); - /// ``` - /// - /// # References + /// Construct a new `AioWrite`. /// - /// [`lio_listio`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html) + /// # Arguments /// - /// [`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html - /// [`LioCb::aio_return`]: struct.LioCb.html#method.aio_return - // Note: the addresses of any EINPROGRESS or EOK aiocbs _must_ not be - // changed by this method, because the kernel relies on their addresses - // being stable. - // Note: aiocbs that are Ok(()) must be finalized by aio_return, or else the - // sigev_notify will immediately refire. - pub fn listio_resubmit(&mut self, mode:LioMode, - sigev_notify: SigevNotify) -> Result<()> { - let sigev = SigEvent::new(sigev_notify); - let sigevp = &mut sigev.sigevent() as *mut libc::sigevent; - self.list.clear(); - - while self.results.len() < self.aiocbs.len() { - self.results.push(None); - } - - for (i, a) in self.aiocbs.iter_mut().enumerate() { - if self.results[i].is_some() { - // Already collected final status for this operation - continue; - } - match a.error_unpinned() { - Ok(()) => { - // aiocb is complete; collect its status and don't resubmit - self.results[i] = Some(a.aio_return_unpinned()); - }, - Err(Errno::EAGAIN) => { - self.list.push(a as *mut AioCb<'a> as *mut libc::aiocb); - }, - Err(Errno::EINPROGRESS) => { - // aiocb is was successfully queued; no need to do anything - }, - Err(Errno::EINVAL) => panic!( - "AioCb was never submitted, or already finalized"), - _ => unreachable!() - } + /// * `fd`: File descriptor to write to + /// * `offs`: File offset + /// * `buf`: A memory buffer. It must outlive the `AioWrite`. + /// * `prio`: If POSIX Prioritized IO is supported, then the + /// operation will be prioritized at the process's + /// priority level minus `prio` + /// * `sigev_notify`: Determines how you will be notified of event + /// completion. + pub fn new( + fd: RawFd, + offs: off_t, + buf: &'a [u8], + prio: i32, + sigev_notify: SigevNotify, + ) -> Self { + let mut aiocb = AioCb::common_init(fd, prio, sigev_notify); + aiocb.aiocb.0.aio_nbytes = buf.len(); + // casting an immutable buffer to a mutable pointer looks unsafe, + // but technically its only unsafe to dereference it, not to create + // it. Type Safety guarantees that we'll never pass aiocb to + // aio_read or aio_readv. + aiocb.aiocb.0.aio_buf = buf.as_ptr() as *mut c_void; + aiocb.aiocb.0.aio_lio_opcode = libc::LIO_WRITE; + aiocb.aiocb.0.aio_offset = offs; + AioWrite { + aiocb, + _data: PhantomData, + _pin: PhantomPinned, } - let p = self.list.as_ptr(); - Errno::result(unsafe { - libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp) - }).map(drop) } - /// Collect final status for an individual `AioCb` submitted as part of an - /// `LioCb`. - /// - /// This is just like [`AioCb::aio_return`], except it takes into account - /// operations that were restarted by [`LioCb::listio_resubmit`] - /// - /// [`AioCb::aio_return`]: struct.AioCb.html#method.aio_return - /// [`LioCb::listio_resubmit`]: #method.listio_resubmit - pub fn aio_return(&mut self, i: usize) -> Result { - if i >= self.results.len() || self.results[i].is_none() { - self.aiocbs[i].aio_return_unpinned() - } else { - self.results[i].unwrap() - } + /// Returns the file offset of the operation. + pub fn offset(&self) -> off_t { + self.aiocb.aiocb.0.aio_offset } +} - /// Retrieve error status of an individual `AioCb` submitted as part of an - /// `LioCb`. - /// - /// This is just like [`AioCb::error`], except it takes into account - /// operations that were restarted by [`LioCb::listio_resubmit`] - /// - /// [`AioCb::error`]: struct.AioCb.html#method.error - /// [`LioCb::listio_resubmit`]: #method.listio_resubmit - pub fn error(&mut self, i: usize) -> Result<()> { - if i >= self.results.len() || self.results[i].is_none() { - self.aiocbs[i].error_unpinned() - } else { - Ok(()) - } +impl<'a> Aio for AioWrite<'a> { + type Output = usize; + + aio_methods!(aio_write); +} + +impl<'a> AsMut for AioWrite<'a> { + fn as_mut(&mut self) -> &mut libc::aiocb { + &mut self.aiocb.aiocb.0 } } -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -impl<'a> Debug for LioCb<'a> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("LioCb") - .field("aiocbs", &self.aiocbs) - .finish() +impl<'a> AsRef for AioWrite<'a> { + fn as_ref(&self) -> &libc::aiocb { + &self.aiocb.aiocb.0 } } -/// Used to construct `LioCb` -// This must be a separate class from LioCb due to pinning constraints. LioCb -// must use a boxed slice of AioCbs so they will have stable storage, but -// LioCbBuilder must use a Vec to make construction possible when the final size -// is unknown. -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(docsrs, doc(cfg(all())))] +/// Asynchronously writes from a scatter/gather list of buffers to a file descriptor. +/// +/// # References +/// +/// [aio_writev](https://www.freebsd.org/cgi/man.cgi?query=aio_writev) +/// +/// # Examples +/// +#[cfg_attr(fbsd14, doc = " ```")] +#[cfg_attr(not(fbsd14), doc = " ```no_run")] +/// # use nix::errno::Errno; +/// # use nix::Error; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify; +/// # use std::{thread, time}; +/// # use std::io::IoSlice; +/// # use std::os::unix::io::AsRawFd; +/// # use tempfile::tempfile; +/// const wbuf0: &[u8] = b"abcdef"; +/// const wbuf1: &[u8] = b"123456"; +/// let len = wbuf0.len() + wbuf1.len(); +/// let wbufs = [IoSlice::new(wbuf0), IoSlice::new(wbuf1)]; +/// let mut f = tempfile().unwrap(); +/// let mut aiow = Box::pin( +/// AioWritev::new( +/// f.as_raw_fd(), +/// 2, //offset +/// &wbufs, +/// 0, //priority +/// SigevNotify::SigevNone +/// ) +/// ); +/// aiow.as_mut().submit().unwrap(); +/// while (aiow.as_mut().error() == Err(Errno::EINPROGRESS)) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// assert_eq!(aiow.as_mut().aio_return().unwrap(), len); +/// ``` +#[cfg(target_os = "freebsd")] #[derive(Debug)] -pub struct LioCbBuilder<'a> { - /// A collection of [`AioCb`]s. - /// - /// [`AioCb`]: struct.AioCb.html - pub aiocbs: Vec>, +#[repr(transparent)] +pub struct AioWritev<'a> { + aiocb: AioCb, + _data: PhantomData<&'a [&'a [u8]]>, + _pin: PhantomPinned, } -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(docsrs, doc(cfg(all())))] -impl<'a> LioCbBuilder<'a> { - /// Initialize an empty `LioCb` - pub fn with_capacity(capacity: usize) -> LioCbBuilder<'a> { - LioCbBuilder { - aiocbs: Vec::with_capacity(capacity), - } +#[cfg(target_os = "freebsd")] +impl<'a> AioWritev<'a> { + unsafe_pinned!(aiocb: AioCb); + + /// Returns the number of buffers the operation will read into. + pub fn iovlen(&self) -> usize { + self.aiocb.aiocb.0.aio_nbytes } - /// Add a new operation on an immutable slice to the [`LioCb`] under - /// construction. + /// Construct a new `AioWritev`. /// - /// Arguments are the same as for [`AioCb::from_slice`] + /// # Arguments /// - /// [`LioCb`]: struct.LioCb.html - /// [`AioCb::from_slice`]: struct.AioCb.html#method.from_slice - #[must_use] - pub fn emplace_slice(mut self, fd: RawFd, offs: off_t, buf: &'a [u8], - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> Self - { - self.aiocbs.push(AioCb::from_slice_unpinned(fd, offs, buf, prio, - sigev_notify, opcode)); - self + /// * `fd`: File descriptor to write to + /// * `offs`: File offset + /// * `bufs`: A scatter/gather list of memory buffers. They must + /// outlive the `AioWritev`. + /// * `prio`: If POSIX Prioritized IO is supported, then the + /// operation will be prioritized at the process's + /// priority level minus `prio` + /// * `sigev_notify`: Determines how you will be notified of event + /// completion. + pub fn new( + fd: RawFd, + offs: off_t, + bufs: &[IoSlice<'a>], + prio: i32, + sigev_notify: SigevNotify, + ) -> Self { + let mut aiocb = AioCb::common_init(fd, prio, sigev_notify); + // In vectored mode, aio_nbytes stores the length of the iovec array, + // not the byte count. + aiocb.aiocb.0.aio_nbytes = bufs.len(); + // casting an immutable buffer to a mutable pointer looks unsafe, + // but technically its only unsafe to dereference it, not to create + // it. Type Safety guarantees that we'll never pass aiocb to + // aio_read or aio_readv. + aiocb.aiocb.0.aio_buf = bufs.as_ptr() as *mut c_void; + aiocb.aiocb.0.aio_lio_opcode = libc::LIO_WRITEV; + aiocb.aiocb.0.aio_offset = offs; + AioWritev { + aiocb, + _data: PhantomData, + _pin: PhantomPinned, + } } - /// Add a new operation on a mutable slice to the [`LioCb`] under - /// construction. - /// - /// Arguments are the same as for [`AioCb::from_mut_slice`] - /// - /// [`LioCb`]: struct.LioCb.html - /// [`AioCb::from_mut_slice`]: struct.AioCb.html#method.from_mut_slice - #[must_use] - pub fn emplace_mut_slice(mut self, fd: RawFd, offs: off_t, - buf: &'a mut [u8], prio: libc::c_int, - sigev_notify: SigevNotify, opcode: LioOpcode) - -> Self - { - self.aiocbs.push(AioCb::from_mut_slice_unpinned(fd, offs, buf, prio, - sigev_notify, opcode)); - self + /// Returns the file offset of the operation. + pub fn offset(&self) -> off_t { + self.aiocb.aiocb.0.aio_offset } +} - /// Finalize this [`LioCb`]. - /// - /// Afterwards it will be possible to issue the operations with - /// [`LioCb::listio`]. Conversely, it will no longer be possible to add new - /// operations with [`LioCbBuilder::emplace_slice`] or - /// [`LioCbBuilder::emplace_mut_slice`]. - /// - /// [`LioCb::listio`]: struct.LioCb.html#method.listio - /// [`LioCb::from_mut_slice`]: struct.LioCb.html#method.from_mut_slice - /// [`LioCb::from_slice`]: struct.LioCb.html#method.from_slice - pub fn finish(self) -> LioCb<'a> { - let len = self.aiocbs.len(); - LioCb { - aiocbs: self.aiocbs.into(), - list: Vec::with_capacity(len), - results: Vec::with_capacity(len) - } +#[cfg(target_os = "freebsd")] +impl<'a> Aio for AioWritev<'a> { + type Output = usize; + + aio_methods!(aio_writev); +} + +#[cfg(target_os = "freebsd")] +impl<'a> AsMut for AioWritev<'a> { + fn as_mut(&mut self) -> &mut libc::aiocb { + &mut self.aiocb.aiocb.0 + } +} + +#[cfg(target_os = "freebsd")] +impl<'a> AsRef for AioWritev<'a> { + fn as_ref(&self) -> &libc::aiocb { + &self.aiocb.aiocb.0 } } -#[cfg(not(any(target_os = "ios", target_os = "macos")))] +/// Cancels outstanding AIO requests for a given file descriptor. +/// +/// # Examples +/// +/// Issue an aio operation, then cancel all outstanding operations on that file +/// descriptor. +/// +/// ``` +/// # use nix::errno::Errno; +/// # use nix::Error; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify; +/// # use std::{thread, time}; +/// # use std::io::Write; +/// # use std::os::unix::io::AsRawFd; +/// # use tempfile::tempfile; +/// let wbuf = b"CDEF"; +/// let mut f = tempfile().unwrap(); +/// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(), +/// 2, //offset +/// &wbuf[..], +/// 0, //priority +/// SigevNotify::SigevNone)); +/// aiocb.as_mut().submit().unwrap(); +/// let cs = aio_cancel_all(f.as_raw_fd()).unwrap(); +/// if cs == AioCancelStat::AioNotCanceled { +/// while (aiocb.as_mut().error() == Err(Errno::EINPROGRESS)) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// } +/// // Must call `aio_return`, but ignore the result +/// let _ = aiocb.as_mut().aio_return(); +/// ``` +/// +/// # References +/// +/// [`aio_cancel`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html) +pub fn aio_cancel_all(fd: RawFd) -> Result { + match unsafe { libc::aio_cancel(fd, ptr::null_mut()) } { + libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled), + libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled), + libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone), + -1 => Err(Errno::last()), + _ => panic!("unknown aio_cancel return value"), + } +} + +/// Suspends the calling process until at least one of the specified operations +/// have completed, a signal is delivered, or the timeout has passed. +/// +/// If `timeout` is `None`, `aio_suspend` will block indefinitely. +/// +/// # Examples +/// +/// Use `aio_suspend` to block until an aio operation completes. +/// +/// ``` +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify; +/// # use std::os::unix::io::AsRawFd; +/// # use tempfile::tempfile; +/// const WBUF: &[u8] = b"abcdef123456"; +/// let mut f = tempfile().unwrap(); +/// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(), +/// 2, //offset +/// WBUF, +/// 0, //priority +/// SigevNotify::SigevNone)); +/// aiocb.as_mut().submit().unwrap(); +/// aio_suspend(&[&*aiocb], None).expect("aio_suspend failed"); +/// assert_eq!(aiocb.as_mut().aio_return().unwrap() as usize, WBUF.len()); +/// ``` +/// # References +/// +/// [`aio_suspend`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_suspend.html) +pub fn aio_suspend( + list: &[&dyn AsRef], + timeout: Option, +) -> Result<()> { + let p = list as *const [&dyn AsRef] + as *const [*const libc::aiocb] + as *const *const libc::aiocb; + let timep = match timeout { + None => ptr::null::(), + Some(x) => x.as_ref() as *const libc::timespec, + }; + Errno::result(unsafe { libc::aio_suspend(p, list.len() as i32, timep) }) + .map(drop) +} + +/// Submits multiple asynchronous I/O requests with a single system call. +/// +/// They are not guaranteed to complete atomically, and the order in which the +/// requests are carried out is not specified. Reads, and writes may be freely +/// mixed. +/// +/// # Examples +/// +/// Use `lio_listio` to submit an aio operation and wait for its completion. In +/// this case, there is no need to use aio_suspend to wait or `error` to poll. +/// This mode is useful for otherwise-synchronous programs that want to execute +/// a handful of I/O operations in parallel. +/// ``` +/// # use std::os::unix::io::AsRawFd; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify; +/// # use tempfile::tempfile; +/// const WBUF: &[u8] = b"abcdef123456"; +/// let mut f = tempfile().unwrap(); +/// let mut aiow = Box::pin(AioWrite::new( +/// f.as_raw_fd(), +/// 2, // offset +/// WBUF, +/// 0, // priority +/// SigevNotify::SigevNone +/// )); +/// lio_listio(LioMode::LIO_WAIT, &mut[aiow.as_mut()], SigevNotify::SigevNone) +/// .unwrap(); +/// // At this point, we are guaranteed that aiow is complete. +/// assert_eq!(aiow.as_mut().aio_return().unwrap(), WBUF.len()); +/// ``` +/// +/// Use `lio_listio` to submit multiple asynchronous operations with a single +/// syscall, but receive notification individually. This is an efficient +/// technique for reducing overall context-switch overhead, especially when +/// combined with kqueue. +/// ``` +/// # use std::os::unix::io::AsRawFd; +/// # use std::thread; +/// # use std::time; +/// # use nix::errno::Errno; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::SigevNotify; +/// # use tempfile::tempfile; +/// const WBUF: &[u8] = b"abcdef123456"; +/// let mut f = tempfile().unwrap(); +/// let mut aiow = Box::pin(AioWrite::new( +/// f.as_raw_fd(), +/// 2, // offset +/// WBUF, +/// 0, // priority +/// SigevNotify::SigevNone +/// )); +/// lio_listio(LioMode::LIO_NOWAIT, &mut[aiow.as_mut()], SigevNotify::SigevNone) +/// .unwrap(); +/// // We must wait for the completion of each individual operation +/// while (aiow.as_mut().error() == Err(Errno::EINPROGRESS)) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// assert_eq!(aiow.as_mut().aio_return().unwrap(), WBUF.len()); +/// ``` +/// +/// Use `lio_listio` to submit multiple operations, and receive notification +/// only when all of them are complete. This can be useful when there is some +/// logical relationship between the operations. But beware! Errors or system +/// resource limitations may cause `lio_listio` to return `EIO`, `EAGAIN`, or +/// `EINTR`, in which case some but not all operations may have been submitted. +/// In that case, you must check the status of each individual operation, and +/// possibly resubmit some. +/// ``` +/// # use libc::c_int; +/// # use std::os::unix::io::AsRawFd; +/// # use std::sync::atomic::{AtomicBool, Ordering}; +/// # use std::thread; +/// # use std::time; +/// # use lazy_static::lazy_static; +/// # use nix::errno::Errno; +/// # use nix::sys::aio::*; +/// # use nix::sys::signal::*; +/// # use tempfile::tempfile; +/// lazy_static! { +/// pub static ref SIGNALED: AtomicBool = AtomicBool::new(false); +/// } +/// +/// extern fn sigfunc(_: c_int) { +/// SIGNALED.store(true, Ordering::Relaxed); +/// } +/// let sa = SigAction::new(SigHandler::Handler(sigfunc), +/// SaFlags::SA_RESETHAND, +/// SigSet::empty()); +/// SIGNALED.store(false, Ordering::Relaxed); +/// unsafe { sigaction(Signal::SIGUSR2, &sa) }.unwrap(); +/// +/// const WBUF: &[u8] = b"abcdef123456"; +/// let mut f = tempfile().unwrap(); +/// let mut aiow = Box::pin(AioWrite::new( +/// f.as_raw_fd(), +/// 2, // offset +/// WBUF, +/// 0, // priority +/// SigevNotify::SigevNone +/// )); +/// let sev = SigevNotify::SigevSignal { signal: Signal::SIGUSR2, si_value: 0 }; +/// lio_listio(LioMode::LIO_NOWAIT, &mut[aiow.as_mut()], sev).unwrap(); +/// while !SIGNALED.load(Ordering::Relaxed) { +/// thread::sleep(time::Duration::from_millis(10)); +/// } +/// // At this point, since `lio_listio` returned success and delivered its +/// // notification, we know that all operations are complete. +/// assert_eq!(aiow.as_mut().aio_return().unwrap(), WBUF.len()); +/// ``` +pub fn lio_listio( + mode: LioMode, + list: &mut [Pin<&mut dyn AsMut>], + sigev_notify: SigevNotify, +) -> Result<()> { + let p = list as *mut [Pin<&mut dyn AsMut>] + as *mut [*mut libc::aiocb] + as *mut *mut libc::aiocb; + let sigev = SigEvent::new(sigev_notify); + let sigevp = &mut sigev.sigevent() as *mut libc::sigevent; + Errno::result(unsafe { + libc::lio_listio(mode as i32, p, list.len() as i32, sigevp) + }) + .map(drop) +} + #[cfg(test)] mod t { use super::*; - // It's important that `LioCb` be `UnPin`. The tokio-file crate relies on - // it. + /// aio_suspend relies on casting Rust Aio* struct pointers to libc::aiocb + /// pointers. This test ensures that such casts are valid. #[test] - fn liocb_is_unpin() { - use assert_impl::assert_impl; + fn casting() { + let sev = SigevNotify::SigevNone; + let aiof = AioFsync::new(666, AioFsyncMode::O_SYNC, 0, sev); + assert_eq!( + aiof.as_ref() as *const libc::aiocb, + &aiof as *const AioFsync as *const libc::aiocb + ); + + let mut rbuf = []; + let aior = AioRead::new(666, 0, &mut rbuf, 0, sev); + assert_eq!( + aior.as_ref() as *const libc::aiocb, + &aior as *const AioRead as *const libc::aiocb + ); + + let wbuf = []; + let aiow = AioWrite::new(666, 0, &wbuf, 0, sev); + assert_eq!( + aiow.as_ref() as *const libc::aiocb, + &aiow as *const AioWrite as *const libc::aiocb + ); + } + + #[cfg(target_os = "freebsd")] + #[test] + fn casting_vectored() { + let sev = SigevNotify::SigevNone; + + let mut rbuf = []; + let mut rbufs = [IoSliceMut::new(&mut rbuf)]; + let aiorv = AioReadv::new(666, 0, &mut rbufs[..], 0, sev); + assert_eq!( + aiorv.as_ref() as *const libc::aiocb, + &aiorv as *const AioReadv as *const libc::aiocb + ); - assert_impl!(Unpin: LioCb); + let wbuf = []; + let wbufs = [IoSlice::new(&wbuf)]; + let aiowv = AioWritev::new(666, 0, &wbufs, 0, sev); + assert_eq!( + aiowv.as_ref() as *const libc::aiocb, + &aiowv as *const AioWritev as *const libc::aiocb + ); } } diff --git a/bash-5.1/vendor/nix/src/sys/event.rs b/bash-5.1/vendor/nix/src/sys/event.rs index 9262acc..0d0d23a 100644 --- a/bash-5.1/vendor/nix/src/sys/event.rs +++ b/bash-5.1/vendor/nix/src/sys/event.rs @@ -7,6 +7,7 @@ use libc::{timespec, time_t, c_int, c_long, intptr_t, uintptr_t}; #[cfg(target_os = "netbsd")] use libc::{timespec, time_t, c_long, intptr_t, uintptr_t, size_t}; use std::convert::TryInto; +use std::mem; use std::os::unix::io::RawFd; use std::ptr; @@ -21,13 +22,8 @@ pub struct KEvent { target_os = "ios", target_os = "macos", target_os = "openbsd"))] type type_of_udata = *mut libc::c_void; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos"))] -type type_of_data = intptr_t; #[cfg(any(target_os = "netbsd"))] type type_of_udata = intptr_t; -#[cfg(any(target_os = "netbsd", target_os = "openbsd"))] -type type_of_data = i64; #[cfg(target_os = "netbsd")] type type_of_event_filter = u32; @@ -217,6 +213,7 @@ unsafe impl Send for KEvent { } impl KEvent { + #[allow(clippy::needless_update)] // Not needless on all platforms. pub fn new(ident: uintptr_t, filter: EventFilter, flags: EventFlag, fflags:FilterFlag, data: intptr_t, udata: intptr_t) -> KEvent { KEvent { kevent: libc::kevent { @@ -224,8 +221,10 @@ impl KEvent { filter: filter as type_of_event_filter, flags: flags.bits(), fflags: fflags.bits(), - data: data as type_of_data, - udata: udata as type_of_udata + // data can be either i64 or intptr_t, depending on platform + data: data as _, + udata: udata as type_of_udata, + .. unsafe { mem::zeroed() } } } } @@ -328,7 +327,7 @@ fn test_struct_kevent() { assert_eq!(libc::EVFILT_READ, filter); assert_eq!(libc::EV_ONESHOT | libc::EV_ADD, actual.flags().bits()); assert_eq!(libc::NOTE_CHILD | libc::NOTE_EXIT, actual.fflags().bits()); - assert_eq!(0x1337, actual.data() as type_of_data); + assert_eq!(0x1337, actual.data()); assert_eq!(udata as type_of_udata, actual.udata() as type_of_udata); assert_eq!(mem::size_of::(), mem::size_of::()); } diff --git a/bash-5.1/vendor/nix/src/sys/ioctl/bsd.rs b/bash-5.1/vendor/nix/src/sys/ioctl/bsd.rs index 4ce4d33..307994c 100644 --- a/bash-5.1/vendor/nix/src/sys/ioctl/bsd.rs +++ b/bash-5.1/vendor/nix/src/sys/ioctl/bsd.rs @@ -21,7 +21,7 @@ mod consts { #[allow(overflowing_literals)] pub const IN: ioctl_num_type = 0x8000_0000; #[doc(hidden)] - pub const INOUT: ioctl_num_type = IN|OUT; + pub const INOUT: ioctl_num_type = IN | OUT; #[doc(hidden)] pub const IOCPARM_MASK: ioctl_num_type = 0x1fff; } @@ -31,9 +31,14 @@ pub use self::consts::*; #[macro_export] #[doc(hidden)] macro_rules! ioc { - ($inout:expr, $group:expr, $num:expr, $len:expr) => ( - $inout | (($len as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::IOCPARM_MASK) << 16) | (($group as $crate::sys::ioctl::ioctl_num_type) << 8) | ($num as $crate::sys::ioctl::ioctl_num_type) - ) + ($inout:expr, $group:expr, $num:expr, $len:expr) => { + $inout + | (($len as $crate::sys::ioctl::ioctl_num_type + & $crate::sys::ioctl::IOCPARM_MASK) + << 16) + | (($group as $crate::sys::ioctl::ioctl_num_type) << 8) + | ($num as $crate::sys::ioctl::ioctl_num_type) + }; } /// Generate an ioctl request code for a command that passes no data. @@ -53,7 +58,9 @@ macro_rules! ioc { /// ``` #[macro_export(local_inner_macros)] macro_rules! request_code_none { - ($g:expr, $n:expr) => (ioc!($crate::sys::ioctl::VOID, $g, $n, 0)) + ($g:expr, $n:expr) => { + ioc!($crate::sys::ioctl::VOID, $g, $n, 0) + }; } /// Generate an ioctl request code for a command that passes an integer @@ -64,7 +71,14 @@ macro_rules! request_code_none { /// with is "bad" and you cannot use `ioctl_write_int!()` directly. #[macro_export(local_inner_macros)] macro_rules! request_code_write_int { - ($g:expr, $n:expr) => (ioc!($crate::sys::ioctl::VOID, $g, $n, ::std::mem::size_of::<$crate::libc::c_int>())) + ($g:expr, $n:expr) => { + ioc!( + $crate::sys::ioctl::VOID, + $g, + $n, + ::std::mem::size_of::<$crate::libc::c_int>() + ) + }; } /// Generate an ioctl request code for a command that reads. @@ -79,7 +93,9 @@ macro_rules! request_code_write_int { /// writing. #[macro_export(local_inner_macros)] macro_rules! request_code_read { - ($g:expr, $n:expr, $len:expr) => (ioc!($crate::sys::ioctl::OUT, $g, $n, $len)) + ($g:expr, $n:expr, $len:expr) => { + ioc!($crate::sys::ioctl::OUT, $g, $n, $len) + }; } /// Generate an ioctl request code for a command that writes. @@ -94,7 +110,9 @@ macro_rules! request_code_read { /// reading. #[macro_export(local_inner_macros)] macro_rules! request_code_write { - ($g:expr, $n:expr, $len:expr) => (ioc!($crate::sys::ioctl::IN, $g, $n, $len)) + ($g:expr, $n:expr, $len:expr) => { + ioc!($crate::sys::ioctl::IN, $g, $n, $len) + }; } /// Generate an ioctl request code for a command that reads and writes. @@ -105,5 +123,7 @@ macro_rules! request_code_write { /// with is "bad" and you cannot use `ioctl_readwrite!()` directly. #[macro_export(local_inner_macros)] macro_rules! request_code_readwrite { - ($g:expr, $n:expr, $len:expr) => (ioc!($crate::sys::ioctl::INOUT, $g, $n, $len)) + ($g:expr, $n:expr, $len:expr) => { + ioc!($crate::sys::ioctl::INOUT, $g, $n, $len) + }; } diff --git a/bash-5.1/vendor/nix/src/sys/ioctl/linux.rs b/bash-5.1/vendor/nix/src/sys/ioctl/linux.rs index 08cd0c3..0c0a209 100644 --- a/bash-5.1/vendor/nix/src/sys/ioctl/linux.rs +++ b/bash-5.1/vendor/nix/src/sys/ioctl/linux.rs @@ -14,7 +14,13 @@ pub const NRBITS: ioctl_num_type = 8; #[doc(hidden)] pub const TYPEBITS: ioctl_num_type = 8; -#[cfg(any(target_arch = "mips", target_arch = "mips64", target_arch = "powerpc", target_arch = "powerpc64", target_arch = "sparc64"))] +#[cfg(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "sparc64" +))] mod consts { #[doc(hidden)] pub const NONE: u8 = 1; @@ -29,13 +35,15 @@ mod consts { } // "Generic" ioctl protocol -#[cfg(any(target_arch = "x86", - target_arch = "arm", - target_arch = "s390x", - target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "riscv32", - target_arch = "riscv64"))] +#[cfg(any( + target_arch = "x86", + target_arch = "arm", + target_arch = "s390x", + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "riscv32", + target_arch = "riscv64" +))] mod consts { #[doc(hidden)] pub const NONE: u8 = 0; @@ -73,11 +81,20 @@ pub const DIRMASK: ioctl_num_type = (1 << DIRBITS) - 1; #[macro_export] #[doc(hidden)] macro_rules! ioc { - ($dir:expr, $ty:expr, $nr:expr, $sz:expr) => ( - (($dir as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::DIRMASK) << $crate::sys::ioctl::DIRSHIFT) | - (($ty as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::TYPEMASK) << $crate::sys::ioctl::TYPESHIFT) | - (($nr as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::NRMASK) << $crate::sys::ioctl::NRSHIFT) | - (($sz as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::SIZEMASK) << $crate::sys::ioctl::SIZESHIFT)) + ($dir:expr, $ty:expr, $nr:expr, $sz:expr) => { + (($dir as $crate::sys::ioctl::ioctl_num_type + & $crate::sys::ioctl::DIRMASK) + << $crate::sys::ioctl::DIRSHIFT) + | (($ty as $crate::sys::ioctl::ioctl_num_type + & $crate::sys::ioctl::TYPEMASK) + << $crate::sys::ioctl::TYPESHIFT) + | (($nr as $crate::sys::ioctl::ioctl_num_type + & $crate::sys::ioctl::NRMASK) + << $crate::sys::ioctl::NRSHIFT) + | (($sz as $crate::sys::ioctl::ioctl_num_type + & $crate::sys::ioctl::SIZEMASK) + << $crate::sys::ioctl::SIZESHIFT) + }; } /// Generate an ioctl request code for a command that passes no data. @@ -97,7 +114,9 @@ macro_rules! ioc { /// ``` #[macro_export(local_inner_macros)] macro_rules! request_code_none { - ($ty:expr, $nr:expr) => (ioc!($crate::sys::ioctl::NONE, $ty, $nr, 0)) + ($ty:expr, $nr:expr) => { + ioc!($crate::sys::ioctl::NONE, $ty, $nr, 0) + }; } /// Generate an ioctl request code for a command that reads. @@ -112,7 +131,9 @@ macro_rules! request_code_none { /// writing. #[macro_export(local_inner_macros)] macro_rules! request_code_read { - ($ty:expr, $nr:expr, $sz:expr) => (ioc!($crate::sys::ioctl::READ, $ty, $nr, $sz)) + ($ty:expr, $nr:expr, $sz:expr) => { + ioc!($crate::sys::ioctl::READ, $ty, $nr, $sz) + }; } /// Generate an ioctl request code for a command that writes. @@ -127,7 +148,9 @@ macro_rules! request_code_read { /// reading. #[macro_export(local_inner_macros)] macro_rules! request_code_write { - ($ty:expr, $nr:expr, $sz:expr) => (ioc!($crate::sys::ioctl::WRITE, $ty, $nr, $sz)) + ($ty:expr, $nr:expr, $sz:expr) => { + ioc!($crate::sys::ioctl::WRITE, $ty, $nr, $sz) + }; } /// Generate an ioctl request code for a command that reads and writes. @@ -138,5 +161,12 @@ macro_rules! request_code_write { /// with is "bad" and you cannot use `ioctl_readwrite!()` directly. #[macro_export(local_inner_macros)] macro_rules! request_code_readwrite { - ($ty:expr, $nr:expr, $sz:expr) => (ioc!($crate::sys::ioctl::READ | $crate::sys::ioctl::WRITE, $ty, $nr, $sz)) + ($ty:expr, $nr:expr, $sz:expr) => { + ioc!( + $crate::sys::ioctl::READ | $crate::sys::ioctl::WRITE, + $ty, + $nr, + $sz + ) + }; } diff --git a/bash-5.1/vendor/nix/src/sys/ioctl/mod.rs b/bash-5.1/vendor/nix/src/sys/ioctl/mod.rs index 203b7d0..98d6b5c 100644 --- a/bash-5.1/vendor/nix/src/sys/ioctl/mod.rs +++ b/bash-5.1/vendor/nix/src/sys/ioctl/mod.rs @@ -227,37 +227,45 @@ use cfg_if::cfg_if; #[macro_use] mod linux; -#[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] +#[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "redox" +))] pub use self::linux::*; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "illumos", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "haiku", + target_os = "openbsd" +))] #[macro_use] mod bsd; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "illumos", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "haiku", + target_os = "openbsd" +))] pub use self::bsd::*; /// Convert raw ioctl return value to a Nix result #[macro_export] #[doc(hidden)] macro_rules! convert_ioctl_res { - ($w:expr) => ( - { - $crate::errno::Errno::result($w) - } - ); + ($w:expr) => {{ + $crate::errno::Errno::result($w) + }}; } /// Generates a wrapper function for an ioctl that passes no data to the kernel. @@ -489,7 +497,7 @@ macro_rules! ioctl_write_ptr_bad { ) } -cfg_if!{ +cfg_if! { if #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] { /// Generates a wrapper function for a ioctl that writes an integer to the kernel. /// diff --git a/bash-5.1/vendor/nix/src/sys/mman.rs b/bash-5.1/vendor/nix/src/sys/mman.rs index a7469a1..700e231 100644 --- a/bash-5.1/vendor/nix/src/sys/mman.rs +++ b/bash-5.1/vendor/nix/src/sys/mman.rs @@ -351,6 +351,7 @@ libc_bitflags!{ } } +#[cfg(not(target_os = "haiku"))] libc_bitflags!{ /// Flags for [`mlockall`]. pub struct MlockAllFlags: c_int { @@ -393,6 +394,7 @@ pub unsafe fn munlock(addr: *const c_void, length: size_t) -> Result<()> { /// Locked pages never move to the swap area. For more information, see [`mlockall(2)`]. /// /// [`mlockall(2)`]: https://man7.org/linux/man-pages/man2/mlockall.2.html +#[cfg(not(target_os = "haiku"))] pub fn mlockall(flags: MlockAllFlags) -> Result<()> { unsafe { Errno::result(libc::mlockall(flags.bits())) }.map(drop) } @@ -402,6 +404,7 @@ pub fn mlockall(flags: MlockAllFlags) -> Result<()> { /// For more information, see [`munlockall(2)`]. /// /// [`munlockall(2)`]: https://man7.org/linux/man-pages/man2/munlockall.2.html +#[cfg(not(target_os = "haiku"))] pub fn munlockall() -> Result<()> { unsafe { Errno::result(libc::munlockall()) }.map(drop) } diff --git a/bash-5.1/vendor/nix/src/sys/mod.rs b/bash-5.1/vendor/nix/src/sys/mod.rs index e5639f2..979d623 100644 --- a/bash-5.1/vendor/nix/src/sys/mod.rs +++ b/bash-5.1/vendor/nix/src/sys/mod.rs @@ -1,10 +1,12 @@ //! Mostly platform-specific functionality -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - all(target_os = "linux", not(target_env = "uclibc")), - target_os = "macos", - target_os = "netbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + target_os = "netbsd" +))] feature! { #![feature = "aio"] pub mod aio; @@ -31,22 +33,24 @@ feature! { pub mod eventfd; } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "redox", - target_os = "macos", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "redox", + target_os = "macos", + target_os = "netbsd", + target_os = "illumos", + target_os = "openbsd" +))] #[cfg(feature = "ioctl")] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] #[macro_use] pub mod ioctl; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "android", target_os = "linux"))] feature! { #![feature = "fs"] pub mod memfd; @@ -69,13 +73,15 @@ feature! { pub mod pthread; } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] feature! { #![feature = "ptrace"] #[allow(missing_docs)] @@ -94,7 +100,12 @@ feature! { pub mod reboot; } -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "illumos")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "illumos", + target_os = "haiku" +)))] feature! { #![feature = "resource"] pub mod resource; @@ -106,12 +117,14 @@ feature! { pub mod select; } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos" +))] feature! { #![feature = "zerocopy"] pub mod sendfile; @@ -139,13 +152,14 @@ feature! { pub mod stat; } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "openbsd" +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" ))] feature! { #![feature = "fs"] diff --git a/bash-5.1/vendor/nix/src/sys/personality.rs b/bash-5.1/vendor/nix/src/sys/personality.rs index 2af6687..9e285ae 100644 --- a/bash-5.1/vendor/nix/src/sys/personality.rs +++ b/bash-5.1/vendor/nix/src/sys/personality.rs @@ -86,7 +86,7 @@ pub fn get() -> Result { /// # use nix::sys::personality::{self, Persona}; /// let mut pers = personality::get().unwrap(); /// assert!(!pers.contains(Persona::ADDR_NO_RANDOMIZE)); -/// personality::set(pers | Persona::ADDR_NO_RANDOMIZE); +/// personality::set(pers | Persona::ADDR_NO_RANDOMIZE).unwrap(); /// ``` pub fn set(persona: Persona) -> Result { let res = unsafe { diff --git a/bash-5.1/vendor/nix/src/sys/ptrace/linux.rs b/bash-5.1/vendor/nix/src/sys/ptrace/linux.rs index 24152d7..1d9b241 100644 --- a/bash-5.1/vendor/nix/src/sys/ptrace/linux.rs +++ b/bash-5.1/vendor/nix/src/sys/ptrace/linux.rs @@ -481,3 +481,24 @@ pub unsafe fn write( { ptrace_other(Request::PTRACE_POKEDATA, pid, addr, data).map(drop) } + +/// Reads a word from a user area at `offset`. +/// The user struct definition can be found in `/usr/include/sys/user.h`. +pub fn read_user(pid: Pid, offset: AddressType) -> Result { + ptrace_peek(Request::PTRACE_PEEKUSER, pid, offset, ptr::null_mut()) +} + +/// Writes a word to a user area at `offset`. +/// The user struct definition can be found in `/usr/include/sys/user.h`. +/// +/// # Safety +/// +/// The `data` argument is passed directly to `ptrace(2)`. Read that man page +/// for guidance. +pub unsafe fn write_user( + pid: Pid, + offset: AddressType, + data: *mut c_void) -> Result<()> +{ + ptrace_other(Request::PTRACE_POKEUSER, pid, offset, data).map(drop) +} diff --git a/bash-5.1/vendor/nix/src/sys/quota.rs b/bash-5.1/vendor/nix/src/sys/quota.rs index 6e34e38..f3b4c02 100644 --- a/bash-5.1/vendor/nix/src/sys/quota.rs +++ b/bash-5.1/vendor/nix/src/sys/quota.rs @@ -6,11 +6,11 @@ //! //! ```rust,no_run //! # use nix::sys::quota::{Dqblk, quotactl_on, quotactl_set, QuotaFmt, QuotaType, QuotaValidFlags}; -//! quotactl_on(QuotaType::USRQUOTA, "/dev/sda1", QuotaFmt::QFMT_VFS_V1, "aquota.user"); +//! quotactl_on(QuotaType::USRQUOTA, "/dev/sda1", QuotaFmt::QFMT_VFS_V1, "aquota.user").unwrap(); //! let mut dqblk: Dqblk = Default::default(); //! dqblk.set_blocks_hard_limit(10000); //! dqblk.set_blocks_soft_limit(8000); -//! quotactl_set(QuotaType::USRQUOTA, "/dev/sda1", 50, &dqblk, QuotaValidFlags::QIF_BLIMITS); +//! quotactl_set(QuotaType::USRQUOTA, "/dev/sda1", 50, &dqblk, QuotaValidFlags::QIF_BLIMITS).unwrap(); //! ``` use std::default::Default; use std::{mem, ptr}; diff --git a/bash-5.1/vendor/nix/src/sys/resource.rs b/bash-5.1/vendor/nix/src/sys/resource.rs index 76ceaf5..e9a11d9 100644 --- a/bash-5.1/vendor/nix/src/sys/resource.rs +++ b/bash-5.1/vendor/nix/src/sys/resource.rs @@ -1,7 +1,9 @@ //! Configure the process resource limits. use cfg_if::cfg_if; +use libc::{c_int, c_long, rusage}; use crate::errno::Errno; +use crate::sys::time::TimeVal; use crate::Result; pub use libc::rlim_t; use std::mem; @@ -19,7 +21,7 @@ cfg_if! { target_os = "dragonfly", all(target_os = "linux", not(target_env = "gnu")) ))]{ - use libc::{c_int, rlimit}; + use libc::rlimit; } } @@ -242,11 +244,7 @@ pub fn getrlimit(resource: Resource) -> Result<(rlim_t, rlim_t)> { /// [`Resource`]: enum.Resource.html /// /// Note: `setrlimit` provides a safe wrapper to libc's `setrlimit`. -pub fn setrlimit( - resource: Resource, - soft_limit: rlim_t, - hard_limit: rlim_t, -) -> Result<()> { +pub fn setrlimit(resource: Resource, soft_limit: rlim_t, hard_limit: rlim_t) -> Result<()> { let new_rlim = rlimit { rlim_cur: soft_limit, rlim_max: hard_limit, @@ -261,3 +259,179 @@ pub fn setrlimit( Errno::result(res).map(drop) } + +libc_enum! { + /// Whose resource usage should be returned by [`getrusage`]. + #[repr(i32)] + #[non_exhaustive] + pub enum UsageWho { + /// Resource usage for the current process. + RUSAGE_SELF, + + /// Resource usage for all the children that have terminated and been waited for. + RUSAGE_CHILDREN, + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[cfg_attr(docsrs, doc(cfg(all())))] + /// Resource usage for the calling thread. + RUSAGE_THREAD, + } +} + +/// Output of `getrusage` with information about resource usage. Some of the fields +/// may be unused in some platforms, and will be always zeroed out. See their manuals +/// for details. +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub struct Usage(rusage); + +impl AsRef for Usage { + fn as_ref(&self) -> &rusage { + &self.0 + } +} + +impl AsMut for Usage { + fn as_mut(&mut self) -> &mut rusage { + &mut self.0 + } +} + +impl Usage { + /// Total amount of time spent executing in user mode. + pub fn user_time(&self) -> TimeVal { + TimeVal::from(self.0.ru_utime) + } + + /// Total amount of time spent executing in kernel mode. + pub fn system_time(&self) -> TimeVal { + TimeVal::from(self.0.ru_stime) + } + + /// The resident set size at its peak, in kilobytes. + pub fn max_rss(&self) -> c_long { + self.0.ru_maxrss + } + + /// Integral value expressed in kilobytes times ticks of execution indicating + /// the amount of text memory shared with other processes. + pub fn shared_integral(&self) -> c_long { + self.0.ru_ixrss + } + + /// Integral value expressed in kilobytes times ticks of execution indicating + /// the amount of unshared memory used by data. + pub fn unshared_data_integral(&self) -> c_long { + self.0.ru_idrss + } + + /// Integral value expressed in kilobytes times ticks of execution indicating + /// the amount of unshared memory used for stack space. + pub fn unshared_stack_integral(&self) -> c_long { + self.0.ru_isrss + } + + /// Number of page faults that were served without resorting to I/O, with pages + /// that have been allocated previously by the kernel. + pub fn minor_page_faults(&self) -> c_long { + self.0.ru_minflt + } + + /// Number of page faults that were served through I/O (i.e. swap). + pub fn major_page_faults(&self) -> c_long { + self.0.ru_majflt + } + + /// Number of times all of the memory was fully swapped out. + pub fn full_swaps(&self) -> c_long { + self.0.ru_nswap + } + + /// Number of times a read was done from a block device. + pub fn block_reads(&self) -> c_long { + self.0.ru_inblock + } + + /// Number of times a write was done to a block device. + pub fn block_writes(&self) -> c_long { + self.0.ru_oublock + } + + /// Number of IPC messages sent. + pub fn ipc_sends(&self) -> c_long { + self.0.ru_msgsnd + } + + /// Number of IPC messages received. + pub fn ipc_receives(&self) -> c_long { + self.0.ru_msgrcv + } + + /// Number of signals received. + pub fn signals(&self) -> c_long { + self.0.ru_nsignals + } + + /// Number of times a context switch was voluntarily invoked. + pub fn voluntary_context_switches(&self) -> c_long { + self.0.ru_nvcsw + } + + /// Number of times a context switch was imposed by the kernel (usually due to + /// time slice expiring or preemption by a higher priority process). + pub fn involuntary_context_switches(&self) -> c_long { + self.0.ru_nivcsw + } +} + +/// Get usage information for a process, its children or the current thread +/// +/// Real time information can be obtained for either the current process or (in some +/// systems) thread, but information about children processes is only provided for +/// those that have terminated and been waited for (see [`super::wait::wait`]). +/// +/// Some information may be missing depending on the platform, and the way information +/// is provided for children may also vary. Check the manuals for details. +/// +/// # References +/// +/// * [getrusage(2)](https://pubs.opengroup.org/onlinepubs/009696699/functions/getrusage.html) +/// * [Linux](https://man7.org/linux/man-pages/man2/getrusage.2.html) +/// * [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=getrusage) +/// * [NetBSD](https://man.netbsd.org/getrusage.2) +/// * [MacOS](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getrusage.2.html) +/// +/// [`UsageWho`]: enum.UsageWho.html +/// +/// Note: `getrusage` provides a safe wrapper to libc's [`libc::getrusage`]. +pub fn getrusage(who: UsageWho) -> Result { + unsafe { + let mut rusage = mem::MaybeUninit::::uninit(); + let res = libc::getrusage(who as c_int, rusage.as_mut_ptr()); + Errno::result(res).map(|_| Usage(rusage.assume_init())) + } +} + +#[cfg(test)] +mod test { + use super::{getrusage, UsageWho}; + + #[test] + pub fn test_self_cpu_time() { + // Make sure some CPU time is used. + let mut numbers: Vec = (1..1_000_000).collect(); + numbers.iter_mut().for_each(|item| *item *= 2); + + // FIXME: this is here to help ensure the compiler does not optimize the whole + // thing away. Replace the assert with test::black_box once stabilized. + assert_eq!(numbers[100..200].iter().sum::(), 30_100); + + let usage = getrusage(UsageWho::RUSAGE_SELF).expect("Failed to call getrusage for SELF"); + let rusage = usage.as_ref(); + + let user = usage.user_time(); + assert!(user.tv_sec() > 0 || user.tv_usec() > 0); + assert_eq!(user.tv_sec(), rusage.ru_utime.tv_sec); + assert_eq!(user.tv_usec(), rusage.ru_utime.tv_usec); + } +} diff --git a/bash-5.1/vendor/nix/src/sys/signal.rs b/bash-5.1/vendor/nix/src/sys/signal.rs index f982b4e..0da9c74 100644 --- a/bash-5.1/vendor/nix/src/sys/signal.rs +++ b/bash-5.1/vendor/nix/src/sys/signal.rs @@ -3,22 +3,22 @@ //! Operating system signals. -use crate::{Error, Result}; use crate::errno::Errno; -use std::mem; +use crate::{Error, Result}; +use cfg_if::cfg_if; use std::fmt; -use std::str::FromStr; +use std::mem; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] use std::os::unix::io::RawFd; use std::ptr; -use cfg_if::cfg_if; +use std::str::FromStr; #[cfg(not(any(target_os = "openbsd", target_os = "redox")))] #[cfg(any(feature = "aio", feature = "signal"))] pub use self::sigevent::*; #[cfg(any(feature = "aio", feature = "process", feature = "signal"))] -libc_enum!{ +libc_enum! { /// Types of operating system signals // Currently there is only one definition of c_int in libc, as well as only one // type for signal constants. @@ -89,6 +89,8 @@ libc_enum!{ /// Window size changes SIGWINCH, /// Input/output possible signal + #[cfg(not(target_os = "haiku"))] + #[cfg_attr(docsrs, doc(cfg(all())))] SIGIO, #[cfg(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux"))] @@ -99,13 +101,13 @@ libc_enum!{ SIGSYS, #[cfg(not(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux", - target_os = "redox")))] + target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] /// Emulator trap SIGEMT, #[cfg(not(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux", - target_os = "redox")))] + target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] /// Information request SIGINFO, @@ -133,10 +135,19 @@ impl FromStr for Signal { "SIGPIPE" => Signal::SIGPIPE, "SIGALRM" => Signal::SIGALRM, "SIGTERM" => Signal::SIGTERM, - #[cfg(all(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux"), - not(any(target_arch = "mips", target_arch = "mips64", - target_arch = "sparc64"))))] + #[cfg(all( + any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux" + ), + not(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "sparc64" + )) + ))] "SIGSTKFLT" => Signal::SIGSTKFLT, "SIGCHLD" => Signal::SIGCHLD, "SIGCONT" => Signal::SIGCONT, @@ -150,18 +161,33 @@ impl FromStr for Signal { "SIGVTALRM" => Signal::SIGVTALRM, "SIGPROF" => Signal::SIGPROF, "SIGWINCH" => Signal::SIGWINCH, + #[cfg(not(target_os = "haiku"))] "SIGIO" => Signal::SIGIO, - #[cfg(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux"))] + #[cfg(any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux" + ))] "SIGPWR" => Signal::SIGPWR, "SIGSYS" => Signal::SIGSYS, - #[cfg(not(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", - target_os = "redox")))] + #[cfg(not(any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux", + target_os = "redox", + target_os = "haiku" + )))] "SIGEMT" => Signal::SIGEMT, - #[cfg(not(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", - target_os = "redox")))] + #[cfg(not(any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux", + target_os = "redox", + target_os = "haiku" + )))] "SIGINFO" => Signal::SIGINFO, _ => return Err(Errno::EINVAL), }) @@ -192,9 +218,19 @@ impl Signal { Signal::SIGPIPE => "SIGPIPE", Signal::SIGALRM => "SIGALRM", Signal::SIGTERM => "SIGTERM", - #[cfg(all(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux"), - not(any(target_arch = "mips", target_arch = "mips64", target_arch = "sparc64"))))] + #[cfg(all( + any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux" + ), + not(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "sparc64" + )) + ))] Signal::SIGSTKFLT => "SIGSTKFLT", Signal::SIGCHLD => "SIGCHLD", Signal::SIGCONT => "SIGCONT", @@ -208,18 +244,33 @@ impl Signal { Signal::SIGVTALRM => "SIGVTALRM", Signal::SIGPROF => "SIGPROF", Signal::SIGWINCH => "SIGWINCH", + #[cfg(not(target_os = "haiku"))] Signal::SIGIO => "SIGIO", - #[cfg(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux"))] + #[cfg(any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux" + ))] Signal::SIGPWR => "SIGPWR", Signal::SIGSYS => "SIGSYS", - #[cfg(not(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", - target_os = "redox")))] + #[cfg(not(any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux", + target_os = "redox", + target_os = "haiku" + )))] Signal::SIGEMT => "SIGEMT", - #[cfg(not(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", - target_os = "redox")))] + #[cfg(not(any( + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "linux", + target_os = "redox", + target_os = "haiku" + )))] Signal::SIGINFO => "SIGINFO", } } @@ -245,144 +296,70 @@ pub use self::Signal::*; #[cfg(target_os = "redox")] #[cfg(feature = "signal")] const SIGNALS: [Signal; 29] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGSYS]; -#[cfg(all(any(target_os = "linux", target_os = "android", - target_os = "emscripten", target_os = "fuchsia"), - not(any(target_arch = "mips", target_arch = "mips64", - target_arch = "sparc64"))))] + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, + SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, + SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, + SIGPROF, SIGWINCH, SIGIO, SIGSYS, +]; +#[cfg(target_os = "haiku")] +#[cfg(feature = "signal")] +const SIGNALS: [Signal; 28] = [ + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, + SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, + SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, + SIGPROF, SIGWINCH, SIGSYS, +]; +#[cfg(all( + any( + target_os = "linux", + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia" + ), + not(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "sparc64" + )) +))] #[cfg(feature = "signal")] const SIGNALS: [Signal; 31] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGSTKFLT, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGPWR, - SIGSYS]; -#[cfg(all(any(target_os = "linux", target_os = "android", - target_os = "emscripten", target_os = "fuchsia"), - any(target_arch = "mips", target_arch = "mips64", - target_arch = "sparc64")))] + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, + SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGSTKFLT, SIGCHLD, + SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, + SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS, +]; +#[cfg(all( + any( + target_os = "linux", + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia" + ), + any(target_arch = "mips", target_arch = "mips64", target_arch = "sparc64") +))] #[cfg(feature = "signal")] const SIGNALS: [Signal; 30] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGPWR, - SIGSYS]; -#[cfg(not(any(target_os = "linux", target_os = "android", - target_os = "fuchsia", target_os = "emscripten", - target_os = "redox")))] + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, + SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, + SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, + SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS, +]; +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "fuchsia", + target_os = "emscripten", + target_os = "redox", + target_os = "haiku" +)))] #[cfg(feature = "signal")] const SIGNALS: [Signal; 31] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGSYS, - SIGEMT, - SIGINFO]; + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, + SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, + SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, + SIGPROF, SIGWINCH, SIGIO, SIGSYS, SIGEMT, SIGINFO, +]; feature! { #![feature = "signal"] @@ -417,6 +394,7 @@ impl Signal { /// Alias for [`SIGABRT`] pub const SIGIOT : Signal = SIGABRT; /// Alias for [`SIGIO`] +#[cfg(not(target_os = "haiku"))] pub const SIGPOLL : Signal = SIGIO; /// Alias for [`SIGSYS`] pub const SIGUNUSED : Signal = SIGSYS; @@ -433,7 +411,7 @@ cfg_if! { } #[cfg(feature = "signal")] -libc_bitflags!{ +libc_bitflags! { /// Controls the behavior of a [`SigAction`] #[cfg_attr(docsrs, doc(cfg(feature = "signal")))] pub struct SaFlags: SaFlags_t { @@ -487,6 +465,9 @@ use std::iter::FromIterator; use std::iter::IntoIterator; /// Specifies a set of [`Signal`]s that may be blocked, waited for, etc. +// We are using `transparent` here to be super sure that `SigSet` +// is represented exactly like the `sigset_t` struct from C. +#[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct SigSet { sigset: libc::sigset_t @@ -494,6 +475,7 @@ pub struct SigSet { impl SigSet { /// Initialize to include all signals. + #[cfg_attr(has_doc_alias, doc(alias("sigfillset")))] pub fn all() -> SigSet { let mut sigset = mem::MaybeUninit::uninit(); let _ = unsafe { libc::sigfillset(sigset.as_mut_ptr()) }; @@ -502,6 +484,7 @@ impl SigSet { } /// Initialize to include nothing. + #[cfg_attr(has_doc_alias, doc(alias("sigemptyset")))] pub fn empty() -> SigSet { let mut sigset = mem::MaybeUninit::uninit(); let _ = unsafe { libc::sigemptyset(sigset.as_mut_ptr()) }; @@ -510,21 +493,25 @@ impl SigSet { } /// Add the specified signal to the set. + #[cfg_attr(has_doc_alias, doc(alias("sigaddset")))] pub fn add(&mut self, signal: Signal) { unsafe { libc::sigaddset(&mut self.sigset as *mut libc::sigset_t, signal as libc::c_int) }; } /// Remove all signals from this set. + #[cfg_attr(has_doc_alias, doc(alias("sigemptyset")))] pub fn clear(&mut self) { unsafe { libc::sigemptyset(&mut self.sigset as *mut libc::sigset_t) }; } /// Remove the specified signal from this set. + #[cfg_attr(has_doc_alias, doc(alias("sigdelset")))] pub fn remove(&mut self, signal: Signal) { unsafe { libc::sigdelset(&mut self.sigset as *mut libc::sigset_t, signal as libc::c_int) }; } /// Return whether this set includes the specified signal. + #[cfg_attr(has_doc_alias, doc(alias("sigismember")))] pub fn contains(&self, signal: Signal) -> bool { let res = unsafe { libc::sigismember(&self.sigset as *const libc::sigset_t, signal as libc::c_int) }; @@ -583,6 +570,19 @@ impl SigSet { Signal::try_from(signum.assume_init()).unwrap() }) } + + /// Converts a `libc::sigset_t` object to a [`SigSet`] without checking whether the + /// `libc::sigset_t` is already initialized. + /// + /// # Safety + /// + /// The `sigset` passed in must be a valid an initialized `libc::sigset_t` by calling either + /// [`sigemptyset(3)`](https://man7.org/linux/man-pages/man3/sigemptyset.3p.html) or + /// [`sigfillset(3)`](https://man7.org/linux/man-pages/man3/sigfillset.3p.html). + /// Otherwise, the results are undefined. + pub unsafe fn from_sigset_t_unchecked(sigset: libc::sigset_t) -> SigSet { + SigSet { sigset } + } } impl AsRef for SigSet { @@ -965,7 +965,6 @@ pub fn raise(signal: Signal) -> Result<()> { } } - feature! { #![any(feature = "aio", feature = "signal")] @@ -1125,9 +1124,9 @@ mod sigevent { #[cfg(test)] mod tests { + use super::*; #[cfg(not(target_os = "redox"))] use std::thread; - use super::*; #[test] fn test_contains() { @@ -1190,15 +1189,19 @@ mod tests { let mut test_mask = prev_mask; test_mask.add(SIGUSR1); - assert!(test_mask.thread_set_mask().is_ok()); - let new_mask = SigSet::thread_get_mask() - .expect("Failed to get new mask!"); + test_mask.thread_set_mask().expect("assertion failed"); + let new_mask = + SigSet::thread_get_mask().expect("Failed to get new mask!"); assert!(new_mask.contains(SIGUSR1)); assert!(!new_mask.contains(SIGUSR2)); - prev_mask.thread_set_mask().expect("Failed to revert signal mask!"); - }).join().unwrap(); + prev_mask + .thread_set_mask() + .expect("Failed to revert signal mask!"); + }) + .join() + .unwrap(); } #[test] @@ -1208,10 +1211,12 @@ mod tests { let mut mask = SigSet::empty(); mask.add(SIGUSR1); - assert!(mask.thread_block().is_ok()); + mask.thread_block().expect("assertion failed"); assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); - }).join().unwrap(); + }) + .join() + .unwrap(); } #[test] @@ -1221,10 +1226,12 @@ mod tests { let mut mask = SigSet::empty(); mask.add(SIGUSR1); - assert!(mask.thread_unblock().is_ok()); + mask.thread_unblock().expect("assertion failed"); assert!(!SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); - }).join().unwrap(); + }) + .join() + .unwrap(); } #[test] @@ -1240,14 +1247,16 @@ mod tests { let mut mask2 = SigSet::empty(); mask2.add(SIGUSR2); - let oldmask = mask2.thread_swap_mask(SigmaskHow::SIG_SETMASK) - .unwrap(); + let oldmask = + mask2.thread_swap_mask(SigmaskHow::SIG_SETMASK).unwrap(); assert!(oldmask.contains(SIGUSR1)); assert!(!oldmask.contains(SIGUSR2)); assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR2)); - }).join().unwrap(); + }) + .join() + .unwrap(); } #[test] @@ -1261,22 +1270,28 @@ mod tests { #[cfg(not(target_os = "redox"))] fn test_sigaction() { thread::spawn(|| { - extern fn test_sigaction_handler(_: libc::c_int) {} - extern fn test_sigaction_action(_: libc::c_int, - _: *mut libc::siginfo_t, _: *mut libc::c_void) {} + extern "C" fn test_sigaction_handler(_: libc::c_int) {} + extern "C" fn test_sigaction_action( + _: libc::c_int, + _: *mut libc::siginfo_t, + _: *mut libc::c_void, + ) { + } let handler_sig = SigHandler::Handler(test_sigaction_handler); - let flags = SaFlags::SA_ONSTACK | SaFlags::SA_RESTART | - SaFlags::SA_SIGINFO; + let flags = + SaFlags::SA_ONSTACK | SaFlags::SA_RESTART | SaFlags::SA_SIGINFO; let mut mask = SigSet::empty(); mask.add(SIGUSR1); let action_sig = SigAction::new(handler_sig, flags, mask); - assert_eq!(action_sig.flags(), - SaFlags::SA_ONSTACK | SaFlags::SA_RESTART); + assert_eq!( + action_sig.flags(), + SaFlags::SA_ONSTACK | SaFlags::SA_RESTART + ); assert_eq!(action_sig.handler(), handler_sig); mask = action_sig.mask(); @@ -1292,7 +1307,9 @@ mod tests { let action_ign = SigAction::new(SigHandler::SigIgn, flags, mask); assert_eq!(action_ign.handler(), SigHandler::SigIgn); - }).join().unwrap(); + }) + .join() + .unwrap(); } #[test] @@ -1306,6 +1323,25 @@ mod tests { raise(SIGUSR1).unwrap(); assert_eq!(mask.wait().unwrap(), SIGUSR1); - }).join().unwrap(); + }) + .join() + .unwrap(); + } + + #[test] + fn test_from_sigset_t_unchecked() { + let src_set = SigSet::empty(); + let set = unsafe { SigSet::from_sigset_t_unchecked(src_set.sigset) }; + + for signal in Signal::iterator() { + assert!(!set.contains(signal)); + } + + let src_set = SigSet::all(); + let set = unsafe { SigSet::from_sigset_t_unchecked(src_set.sigset) }; + + for signal in Signal::iterator() { + assert!(set.contains(signal)); + } } } diff --git a/bash-5.1/vendor/nix/src/sys/signalfd.rs b/bash-5.1/vendor/nix/src/sys/signalfd.rs index bc4a452..166bb9d 100644 --- a/bash-5.1/vendor/nix/src/sys/signalfd.rs +++ b/bash-5.1/vendor/nix/src/sys/signalfd.rs @@ -147,15 +147,17 @@ mod tests { #[test] fn create_signalfd() { let mask = SigSet::empty(); - let fd = SignalFd::new(&mask); - assert!(fd.is_ok()); + SignalFd::new(&mask).unwrap(); } #[test] fn create_signalfd_with_opts() { let mask = SigSet::empty(); - let fd = SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK); - assert!(fd.is_ok()); + SignalFd::with_flags( + &mask, + SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK, + ) + .unwrap(); } #[test] diff --git a/bash-5.1/vendor/nix/src/sys/socket/addr.rs b/bash-5.1/vendor/nix/src/sys/socket/addr.rs index 52d60ac..ad917cd 100644 --- a/bash-5.1/vendor/nix/src/sys/socket/addr.rs +++ b/bash-5.1/vendor/nix/src/sys/socket/addr.rs @@ -26,6 +26,7 @@ use crate::sys::socket::addr::sys_control::SysControlAddr; target_os = "illumos", target_os = "netbsd", target_os = "openbsd", + target_os = "haiku", target_os = "fuchsia"))] #[cfg(feature = "net")] pub use self::datalink::LinkAddr; @@ -120,6 +121,7 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] Rose = libc::AF_ROSE, /// DECet protocol sockets. + #[cfg(not(target_os = "haiku"))] Decnet = libc::AF_DECnet, /// Reserved for "802.2LLC project"; never used. #[cfg(any(target_os = "android", target_os = "linux"))] @@ -151,6 +153,7 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] Rds = libc::AF_RDS, /// IBM SNA + #[cfg(not(target_os = "haiku"))] Sna = libc::AF_SNA, /// Socket interface over IrDA #[cfg(any(target_os = "android", target_os = "linux"))] @@ -202,7 +205,7 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] RxRpc = libc::AF_RXRPC, /// New "modular ISDN" driver interface protocol - #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] + #[cfg(not(any(target_os = "illumos", target_os = "solaris", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] Isdn = libc::AF_ISDN, /// Nokia cellular modem IPC/RPC interface @@ -1158,6 +1161,7 @@ impl SockaddrIn { target_os = "ios", target_os = "macos", target_os = "netbsd", + target_os = "haiku", target_os = "openbsd"))] sin_len: Self::size() as u8, sin_family: AddressFamily::Inet as sa_family_t, @@ -1191,7 +1195,7 @@ impl SockaddrLike for SockaddrIn { if (*addr).sa_family as i32 != libc::AF_INET as i32 { return None; } - Some(SockaddrIn(*(addr as *const libc::sockaddr_in))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -1233,6 +1237,16 @@ impl From for SockaddrIn { } } +#[cfg(feature = "net")] +impl From for net::SocketAddrV4 { + fn from(addr: SockaddrIn) -> Self { + net::SocketAddrV4::new( + net::Ipv4Addr::from(addr.0.sin_addr.s_addr.to_ne_bytes()), + u16::from_be(addr.0.sin_port) + ) + } +} + #[cfg(feature = "net")] impl std::str::FromStr for SockaddrIn { type Err = net::AddrParseError; @@ -1287,7 +1301,7 @@ impl SockaddrLike for SockaddrIn6 { if (*addr).sa_family as i32 != libc::AF_INET6 as i32 { return None; } - Some(SockaddrIn6(*(addr as *const libc::sockaddr_in6))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -1329,6 +1343,18 @@ impl From for SockaddrIn6 { } } +#[cfg(feature = "net")] +impl From for net::SocketAddrV6 { + fn from(addr: SockaddrIn6) -> Self { + net::SocketAddrV6::new( + net::Ipv6Addr::from(addr.0.sin6_addr.s6_addr), + u16::from_be(addr.0.sin6_port), + u32::from_be(addr.0.sin6_flowinfo), + u32::from_be(addr.0.sin6_scope_id) + ) + } +} + #[cfg(feature = "net")] impl std::str::FromStr for SockaddrIn6 { type Err = net::AddrParseError; @@ -1420,6 +1446,7 @@ impl SockaddrLike for SockaddrStorage { target_os = "macos", target_os = "illumos", target_os = "netbsd", + target_os = "haiku", target_os = "openbsd"))] #[cfg(feature = "net")] libc::AF_LINK => LinkAddr::from_raw(addr, l) @@ -1487,6 +1514,14 @@ impl SockaddrStorage { accessors!{as_alg_addr, as_alg_addr_mut, AlgAddr, AddressFamily::Alg, libc::sockaddr_alg, alg} + #[cfg(any(target_os = "android", + target_os = "fuchsia", + target_os = "linux"))] + #[cfg(feature = "net")] + accessors!{ + as_link_addr, as_link_addr_mut, LinkAddr, + AddressFamily::Packet, libc::sockaddr_ll, dl} + #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", @@ -1835,21 +1870,21 @@ impl SockAddr { Some(AddressFamily::Unix) => None, #[cfg(feature = "net")] Some(AddressFamily::Inet) => Some(SockAddr::Inet( - InetAddr::V4(*(addr as *const libc::sockaddr_in)))), + InetAddr::V4(ptr::read_unaligned(addr as *const _)))), #[cfg(feature = "net")] Some(AddressFamily::Inet6) => Some(SockAddr::Inet( - InetAddr::V6(*(addr as *const libc::sockaddr_in6)))), + InetAddr::V6(ptr::read_unaligned(addr as *const _)))), #[cfg(any(target_os = "android", target_os = "linux"))] Some(AddressFamily::Netlink) => Some(SockAddr::Netlink( - NetlinkAddr(*(addr as *const libc::sockaddr_nl)))), + NetlinkAddr(ptr::read_unaligned(addr as *const _)))), #[cfg(all(feature = "ioctl", any(target_os = "ios", target_os = "macos")))] Some(AddressFamily::System) => Some(SockAddr::SysControl( - SysControlAddr(*(addr as *const libc::sockaddr_ctl)))), + SysControlAddr(ptr::read_unaligned(addr as *const _)))), #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] Some(AddressFamily::Packet) => Some(SockAddr::Link( - LinkAddr(*(addr as *const libc::sockaddr_ll)))), + LinkAddr(ptr::read_unaligned(addr as *const _)))), #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", @@ -1859,7 +1894,7 @@ impl SockAddr { target_os = "openbsd"))] #[cfg(feature = "net")] Some(AddressFamily::Link) => { - let ether_addr = LinkAddr(*(addr as *const libc::sockaddr_dl)); + let ether_addr = LinkAddr(ptr::read_unaligned(addr as *const _)); if ether_addr.is_empty() { None } else { @@ -1868,7 +1903,7 @@ impl SockAddr { }, #[cfg(any(target_os = "android", target_os = "linux"))] Some(AddressFamily::Vsock) => Some(SockAddr::Vsock( - VsockAddr(*(addr as *const libc::sockaddr_vm)))), + VsockAddr(ptr::read_unaligned(addr as *const _)))), // Other address families are currently not supported and simply yield a None // entry instead of a proper conversion to a `SockAddr`. Some(_) | None => None, @@ -2069,7 +2104,7 @@ pub mod netlink { if (*addr).sa_family as i32 != libc::AF_NETLINK as i32 { return None; } - Some(NetlinkAddr(*(addr as *const libc::sockaddr_nl))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -2113,7 +2148,7 @@ pub mod alg { if (*addr).sa_family as i32 != libc::AF_ALG as i32 { return None; } - Some(AlgAddr(*(addr as *const libc::sockaddr_alg))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -2185,7 +2220,7 @@ feature! { pub mod sys_control { use crate::sys::socket::addr::AddressFamily; use libc::{self, c_uchar}; - use std::{fmt, mem}; + use std::{fmt, mem, ptr}; use std::os::unix::io::RawFd; use crate::{Errno, Result}; use super::{private, SockaddrLike}; @@ -2224,10 +2259,10 @@ pub mod sys_control { return None; } } - if (*addr).sa_family as i32 != libc::AF_INET6 as i32 { + if (*addr).sa_family as i32 != libc::AF_SYSTEM as i32 { return None; } - Some(SysControlAddr(*(addr as *const libc::sockaddr_ctl))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -2294,7 +2329,7 @@ pub mod sys_control { mod datalink { feature! { #![feature = "net"] - use super::{fmt, mem, private, SockaddrLike}; + use super::{fmt, mem, private, ptr, SockaddrLike}; /// Hardware Address #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] @@ -2370,7 +2405,7 @@ mod datalink { if (*addr).sa_family as i32 != libc::AF_PACKET as i32 { return None; } - Some(LinkAddr(*(addr as *const libc::sockaddr_ll))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -2389,12 +2424,13 @@ mod datalink { target_os = "macos", target_os = "illumos", target_os = "netbsd", + target_os = "haiku", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] mod datalink { feature! { #![feature = "net"] - use super::{fmt, mem, private, SockaddrLike}; + use super::{fmt, mem, private, ptr, SockaddrLike}; /// Hardware Address #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] @@ -2403,11 +2439,13 @@ mod datalink { impl LinkAddr { /// interface index, if != 0, system given index for interface + #[cfg(not(target_os = "haiku"))] pub fn ifindex(&self) -> usize { self.0.sdl_index as usize } /// Datalink type + #[cfg(not(target_os = "haiku"))] pub fn datalink_type(&self) -> u8 { self.0.sdl_type } @@ -2423,6 +2461,7 @@ mod datalink { } /// link layer selector length + #[cfg(not(target_os = "haiku"))] pub fn slen(&self) -> usize { self.0.sdl_slen as usize } @@ -2486,7 +2525,7 @@ mod datalink { if (*addr).sa_family as i32 != libc::AF_LINK as i32 { return None; } - Some(LinkAddr(*(addr as *const libc::sockaddr_dl))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -2527,10 +2566,10 @@ pub mod vsock { return None; } } - if (*addr).sa_family as i32 != libc::AF_INET6 as i32 { + if (*addr).sa_family as i32 != libc::AF_VSOCK as i32 { return None; } - Some(VsockAddr(*(addr as *const libc::sockaddr_vm))) + Some(Self(ptr::read_unaligned(addr as *const _))) } } @@ -2619,6 +2658,8 @@ mod tests { } mod link { + #![allow(clippy::cast_ptr_alignment)] + use super::*; #[cfg(any(target_os = "ios", target_os = "macos", @@ -2651,6 +2692,28 @@ mod tests { format!("{}", la); } + #[cfg(all( + any(target_os = "android", + target_os = "fuchsia", + target_os = "linux"), + target_endian = "little" + ))] + #[test] + fn linux_loopback() { + #[repr(align(2))] + struct Raw([u8; 20]); + + let bytes = Raw([17u8, 0, 0, 0, 1, 0, 0, 0, 4, 3, 0, 6, 1, 2, 3, 4, 5, 6, 0, 0]); + let sa = bytes.0.as_ptr() as *const libc::sockaddr; + let len = None; + let sock_addr = unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); + assert_eq!(sock_addr.family(), Some(AddressFamily::Packet)); + match sock_addr.as_link_addr() { + Some(dl) => assert_eq!(dl.addr(), Some([1, 2, 3, 4, 5, 6])), + None => panic!("Can't unwrap sockaddr storage") + } + } + #[cfg(any(target_os = "ios", target_os = "macos" ))] @@ -2715,7 +2778,8 @@ mod tests { target_os = "macos", target_os = "netbsd", target_os = "illumos", - target_os = "openbsd"))] + target_os = "openbsd", + target_os = "haiku"))] let l = mem::size_of::(); #[cfg(any( target_os = "android", diff --git a/bash-5.1/vendor/nix/src/sys/socket/mod.rs b/bash-5.1/vendor/nix/src/sys/socket/mod.rs index c661389..ecbf30a 100644 --- a/bash-5.1/vendor/nix/src/sys/socket/mod.rs +++ b/bash-5.1/vendor/nix/src/sys/socket/mod.rs @@ -38,7 +38,7 @@ pub use self::addr::{ UnixAddr, }; #[allow(deprecated)] -#[cfg(not(any(target_os = "illumos", target_os = "solaris")))] +#[cfg(not(any(target_os = "illumos", target_os = "solaris", target_os = "haiku")))] #[cfg(feature = "net")] pub use self::addr::{ InetAddr, @@ -57,7 +57,7 @@ pub use self::addr::{ UnixAddr, }; #[allow(deprecated)] -#[cfg(any(target_os = "illumos", target_os = "solaris"))] +#[cfg(any(target_os = "illumos", target_os = "solaris", target_os = "haiku"))] #[cfg(feature = "net")] pub use self::addr::{ InetAddr, @@ -118,6 +118,7 @@ pub enum SockType { Raw = libc::SOCK_RAW, /// Provides a reliable datagram layer that does not /// guarantee ordering. + #[cfg(not(any(target_os = "haiku")))] Rdm = libc::SOCK_RDM, } @@ -213,6 +214,13 @@ pub enum SockProtocol { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkCrypto = libc::NETLINK_CRYPTO, + /// Non-DIX type protocol number defined for the Ethernet IEEE 802.3 interface that allows packets of all protocols + /// defined in the interface to be received. + /// ([ref](https://man7.org/linux/man-pages/man7/packet.7.html)) + // The protocol number is fed into the socket syscall in network byte order. + #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg_attr(docsrs, doc(cfg(all())))] + EthAll = libc::ETH_P_ALL.to_be(), } #[cfg(any(target_os = "linux"))] @@ -669,7 +677,7 @@ pub enum ControlMessageOwned { /// None).unwrap(); /// setsockopt(in_socket, sockopt::ReceiveTimestamp, &true).unwrap(); /// let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); - /// bind(in_socket, &localhost); + /// bind(in_socket, &localhost).unwrap(); /// let address: SockaddrIn = getsockname(in_socket).unwrap(); /// // Get initial time /// let time0 = SystemTime::now(); @@ -756,6 +764,14 @@ pub enum ControlMessageOwned { #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvDstAddr(libc::in_addr), + #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(feature = "net")] + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + Ipv4OrigDstAddr(libc::sockaddr_in), + #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(feature = "net")] + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + Ipv6OrigDstAddr(libc::sockaddr_in6), /// UDP Generic Receive Offload (GRO) allows receiving multiple UDP /// packets from a single sender. @@ -845,6 +861,7 @@ impl ControlMessageOwned { let cred: libc::cmsgcred = ptr::read_unaligned(p as *const _); ControlMessageOwned::ScmCreds(cred.into()) } + #[cfg(not(target_os = "haiku"))] (libc::SOL_SOCKET, libc::SCM_TIMESTAMP) => { let tv: libc::timeval = ptr::read_unaligned(p as *const _); ControlMessageOwned::ScmTimestamp(TimeVal::from(tv)) @@ -914,6 +931,12 @@ impl ControlMessageOwned { let dl = ptr::read_unaligned(p as *const libc::in_addr); ControlMessageOwned::Ipv4RecvDstAddr(dl) }, + #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(feature = "net")] + (libc::IPPROTO_IP, libc::IP_ORIGDSTADDR) => { + let dl = ptr::read_unaligned(p as *const libc::sockaddr_in); + ControlMessageOwned::Ipv4OrigDstAddr(dl) + }, #[cfg(target_os = "linux")] #[cfg(feature = "net")] (libc::SOL_UDP, libc::UDP_GRO) => { @@ -937,6 +960,12 @@ impl ControlMessageOwned { let (err, addr) = Self::recv_err_helper::(p, len); ControlMessageOwned::Ipv6RecvErr(err, addr) }, + #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(feature = "net")] + (libc::IPPROTO_IPV6, libc::IPV6_ORIGDSTADDR) => { + let dl = ptr::read_unaligned(p as *const libc::sockaddr_in6); + ControlMessageOwned::Ipv6OrigDstAddr(dl) + }, (_, _) => { let sl = slice::from_raw_parts(p, len); let ucmsg = UnknownCmsg(*header, Vec::::from(sl)); @@ -947,6 +976,7 @@ impl ControlMessageOwned { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] + #[allow(clippy::cast_ptr_alignment)] // False positive unsafe fn recv_err_helper(p: *mut libc::c_uchar, len: usize) -> (libc::sock_extended_err, Option) { let ee = p as *const libc::sock_extended_err; let err = ptr::read_unaligned(ee); @@ -1087,6 +1117,17 @@ pub enum ControlMessage<'a> { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6PacketInfo(&'a libc::in6_pktinfo), + /// Configure the IPv4 source address with `IP_SENDSRCADDR`. + #[cfg(any( + target_os = "netbsd", + target_os = "freebsd", + target_os = "openbsd", + target_os = "dragonfly", + ))] + #[cfg(feature = "net")] + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + Ipv4SendSrcAddr(&'a libc::in_addr), + /// SO_RXQ_OVFL indicates that an unsigned 32 bit value /// ancilliary msg (cmsg) should be attached to recieved /// skbs indicating the number of packets dropped by the @@ -1196,6 +1237,10 @@ impl<'a> ControlMessage<'a> { target_os = "android", target_os = "ios",))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => info as *const _ as *const u8, + #[cfg(any(target_os = "netbsd", target_os = "freebsd", + target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(feature = "net")] + ControlMessage::Ipv4SendSrcAddr(addr) => addr as *const _ as *const u8, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(drop_count) => { drop_count as *const _ as *const u8 @@ -1255,6 +1300,10 @@ impl<'a> ControlMessage<'a> { target_os = "android", target_os = "ios",))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => mem::size_of_val(info), + #[cfg(any(target_os = "netbsd", target_os = "freebsd", + target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(feature = "net")] + ControlMessage::Ipv4SendSrcAddr(addr) => mem::size_of_val(addr), #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(drop_count) => { mem::size_of_val(drop_count) @@ -1290,6 +1339,10 @@ impl<'a> ControlMessage<'a> { target_os = "android", target_os = "ios",))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPPROTO_IPV6, + #[cfg(any(target_os = "netbsd", target_os = "freebsd", + target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(feature = "net")] + ControlMessage::Ipv4SendSrcAddr(_) => libc::IPPROTO_IP, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(_) => libc::SOL_SOCKET, #[cfg(target_os = "linux")] @@ -1332,6 +1385,10 @@ impl<'a> ControlMessage<'a> { target_os = "android", target_os = "ios",))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPV6_PKTINFO, + #[cfg(any(target_os = "netbsd", target_os = "freebsd", + target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(feature = "net")] + ControlMessage::Ipv4SendSrcAddr(_) => libc::IP_SENDSRCADDR, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(_) => { libc::SO_RXQ_OVFL @@ -1910,8 +1967,8 @@ pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, Option)> { unsafe { - let mut addr = mem::MaybeUninit::uninit(); - let mut len = mem::size_of::() as socklen_t; + let mut addr = mem::MaybeUninit::::uninit(); + let mut len = mem::size_of_val(&addr) as socklen_t; let ret = Errno::result(libc::recvfrom( sockfd, @@ -1921,7 +1978,10 @@ pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) addr.as_mut_ptr() as *mut libc::sockaddr, &mut len as *mut socklen_t))? as usize; - Ok((ret, T::from_raw(&addr.assume_init(), Some(len)))) + Ok((ret, T::from_raw( + addr.assume_init().as_ptr() as *const libc::sockaddr, + Some(len)) + )) } } diff --git a/bash-5.1/vendor/nix/src/sys/socket/sockopt.rs b/bash-5.1/vendor/nix/src/sys/socket/sockopt.rs index e80b09e..1cbb223 100644 --- a/bash-5.1/vendor/nix/src/sys/socket/sockopt.rs +++ b/bash-5.1/vendor/nix/src/sys/socket/sockopt.rs @@ -129,6 +129,9 @@ macro_rules! getsockopt_impl { /// * `$ty:ty`: type of the value that will be get/set. /// * `$getter:ty`: `Get` implementation; optional; only for `GetOnly` and `Both`. /// * `$setter:ty`: `Set` implementation; optional; only for `SetOnly` and `Both`. +// Some targets don't use all rules. +#[allow(unknown_lints)] +#[allow(unused_macro_rules)] macro_rules! sockopt_impl { ($(#[$attr:meta])* $name:ident, GetOnly, $level:expr, $flag:path, bool) => { sockopt_impl!($(#[$attr])* @@ -349,6 +352,9 @@ sockopt_impl!( sockopt_impl!( /// Get and clear the pending socket error. SocketError, GetOnly, libc::SOL_SOCKET, libc::SO_ERROR, i32); +sockopt_impl!( + /// Set or get the don't route flag. + DontRoute, Both, libc::SOL_SOCKET, libc::SO_DONTROUTE, bool); sockopt_impl!( /// Enable sending of keep-alive messages on connection-oriented sockets. KeepAlive, Both, libc::SOL_SOCKET, libc::SO_KEEPALIVE, bool); @@ -377,8 +383,7 @@ sockopt_impl!( #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", - target_os = "nacl"))] + target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -396,7 +401,7 @@ cfg_if! { TcpMaxSeg, GetOnly, libc::IPPROTO_TCP, libc::TCP_MAXSEG, u32); } } -#[cfg(not(target_os = "openbsd"))] +#[cfg(not(any(target_os = "openbsd", target_os = "haiku")))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -410,7 +415,7 @@ sockopt_impl!( #[allow(missing_docs)] // Not documented by Linux! TcpRepair, Both, libc::IPPROTO_TCP, libc::TCP_REPAIR, u32); -#[cfg(not(target_os = "openbsd"))] +#[cfg(not(any(target_os = "openbsd", target_os = "haiku")))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -470,6 +475,7 @@ sockopt_impl!( /// Specifies exact type of timestamping information collected by the kernel /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) Timestamping, Both, libc::SOL_SOCKET, libc::SO_TIMESTAMPING, super::TimestampingFlag); +#[cfg(not(target_os = "haiku"))] sockopt_impl!( /// Enable or disable the receiving of the `SO_TIMESTAMP` control message. ReceiveTimestamp, Both, libc::SOL_SOCKET, libc::SO_TIMESTAMP, bool); @@ -568,6 +574,13 @@ sockopt_impl!( /// The `recvmsg(2)` call will return the destination IP address for a UDP /// datagram. Ipv4RecvDstAddr, Both, libc::IPPROTO_IP, libc::IP_RECVDSTADDR, bool); +#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(feature = "net")] +sockopt_impl!( + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + /// The `recvmsg(2)` call will return the destination IP address for a UDP + /// datagram. + Ipv4OrigDstAddr, Both, libc::IPPROTO_IP, libc::IP_ORIGDSTADDR, bool); #[cfg(target_os = "linux")] #[cfg(feature = "net")] sockopt_impl!( @@ -615,6 +628,13 @@ sockopt_impl!( sockopt_impl!( /// Set the unicast hop limit for the socket. Ipv6Ttl, Both, libc::IPPROTO_IPV6, libc::IPV6_UNICAST_HOPS, libc::c_int); +#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(feature = "net")] +sockopt_impl!( + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + /// The `recvmsg(2)` call will return the destination IP address for a UDP + /// datagram. + Ipv6OrigDstAddr, Both, libc::IPPROTO_IPV6, libc::IPV6_ORIGDSTADDR, bool); #[cfg(any(target_os = "ios", target_os = "macos"))] sockopt_impl!( /// Set "don't fragment packet" flag on the IP packet. @@ -962,7 +982,7 @@ mod test { let a_cred = getsockopt(a, super::PeerCredentials).unwrap(); let b_cred = getsockopt(b, super::PeerCredentials).unwrap(); assert_eq!(a_cred, b_cred); - assert!(a_cred.pid() != 0); + assert_ne!(a_cred.pid(), 0); } #[test] @@ -989,8 +1009,7 @@ mod test { } #[cfg(any(target_os = "freebsd", - target_os = "linux", - target_os = "nacl"))] + target_os = "linux"))] #[test] fn can_get_listen_on_tcp_socket() { use super::super::*; diff --git a/bash-5.1/vendor/nix/src/sys/stat.rs b/bash-5.1/vendor/nix/src/sys/stat.rs index 67a1b7f..8b7627d 100644 --- a/bash-5.1/vendor/nix/src/sys/stat.rs +++ b/bash-5.1/vendor/nix/src/sys/stat.rs @@ -1,4 +1,12 @@ pub use libc::{dev_t, mode_t}; +#[cfg(any(target_os = "macos", target_os = "ios", target_os = "openbsd"))] +pub use libc::c_uint; +#[cfg(any( + target_os = "netbsd", + target_os = "freebsd", + target_os = "dragonfly" +))] +pub use libc::c_ulong; pub use libc::stat as FileStat; use crate::{Result, NixPath, errno::Errno}; @@ -43,6 +51,110 @@ libc_bitflags! { } } +#[cfg(any(target_os = "macos", target_os = "ios", target_os="openbsd"))] +pub type type_of_file_flag = c_uint; +#[cfg(any( + target_os = "netbsd", + target_os = "freebsd", + target_os = "dragonfly" +))] +pub type type_of_file_flag = c_ulong; + +#[cfg(any( + target_os = "openbsd", + target_os = "netbsd", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "macos", + target_os = "ios" +))] +libc_bitflags! { + /// File flags. + #[cfg_attr(docsrs, doc(cfg(all())))] + pub struct FileFlag: type_of_file_flag { + /// The file may only be appended to. + SF_APPEND; + /// The file has been archived. + SF_ARCHIVED; + #[cfg(any(target_os = "dragonfly"))] + SF_CACHE; + /// The file may not be changed. + SF_IMMUTABLE; + /// Indicates a WAPBL journal file. + #[cfg(any(target_os = "netbsd"))] + SF_LOG; + /// Do not retain history for file + #[cfg(any(target_os = "dragonfly"))] + SF_NOHISTORY; + /// The file may not be renamed or deleted. + #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + SF_NOUNLINK; + /// Mask of superuser changeable flags + SF_SETTABLE; + /// Snapshot is invalid. + #[cfg(any(target_os = "netbsd"))] + SF_SNAPINVAL; + /// The file is a snapshot file. + #[cfg(any(target_os = "netbsd", target_os = "freebsd"))] + SF_SNAPSHOT; + #[cfg(any(target_os = "dragonfly"))] + SF_XLINK; + /// The file may only be appended to. + UF_APPEND; + /// The file needs to be archived. + #[cfg(any(target_os = "freebsd"))] + UF_ARCHIVE; + #[cfg(any(target_os = "dragonfly"))] + UF_CACHE; + /// File is compressed at the file system level. + #[cfg(any(target_os = "macos", target_os = "ios"))] + UF_COMPRESSED; + /// The file may be hidden from directory listings at the application's + /// discretion. + #[cfg(any( + target_os = "freebsd", + target_os = "macos", + target_os = "ios", + ))] + UF_HIDDEN; + /// The file may not be changed. + UF_IMMUTABLE; + /// Do not dump the file. + UF_NODUMP; + #[cfg(any(target_os = "dragonfly"))] + UF_NOHISTORY; + /// The file may not be renamed or deleted. + #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + UF_NOUNLINK; + /// The file is offline, or has the Windows and CIFS + /// `FILE_ATTRIBUTE_OFFLINE` attribute. + #[cfg(any(target_os = "freebsd"))] + UF_OFFLINE; + /// The directory is opaque when viewed through a union stack. + UF_OPAQUE; + /// The file is read only, and may not be written or appended. + #[cfg(any(target_os = "freebsd"))] + UF_READONLY; + /// The file contains a Windows reparse point. + #[cfg(any(target_os = "freebsd"))] + UF_REPARSE; + /// Mask of owner changeable flags. + UF_SETTABLE; + /// The file has the Windows `FILE_ATTRIBUTE_SPARSE_FILE` attribute. + #[cfg(any(target_os = "freebsd"))] + UF_SPARSE; + /// The file has the DOS, Windows and CIFS `FILE_ATTRIBUTE_SYSTEM` + /// attribute. + #[cfg(any(target_os = "freebsd"))] + UF_SYSTEM; + /// File renames and deletes are tracked. + #[cfg(any(target_os = "macos", target_os = "ios"))] + UF_TRACKED; + #[cfg(any(target_os = "dragonfly"))] + UF_XLINK; + } +} + /// Create a special or ordinary file, by pathname. pub fn mknod(path: &P, kind: SFlag, perm: Mode, dev: dev_t) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { @@ -53,7 +165,7 @@ pub fn mknod(path: &P, kind: SFlag, perm: Mode, dev: dev_t) } /// Create a special or ordinary file, relative to a given directory. -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))] +#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn mknodat( dirfd: RawFd, diff --git a/bash-5.1/vendor/nix/src/sys/statfs.rs b/bash-5.1/vendor/nix/src/sys/statfs.rs index 5a7ac11..e8c06e4 100644 --- a/bash-5.1/vendor/nix/src/sys/statfs.rs +++ b/bash-5.1/vendor/nix/src/sys/statfs.rs @@ -49,160 +49,160 @@ pub struct FsType(pub fs_type_t); // These constants are defined without documentation in the Linux headers, so we // can't very well document them here. -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const ADFS_SUPER_MAGIC: FsType = FsType(libc::ADFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const AFFS_SUPER_MAGIC: FsType = FsType(libc::AFFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const AFS_SUPER_MAGIC: FsType = FsType(libc::AFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const AUTOFS_SUPER_MAGIC: FsType = FsType(libc::AUTOFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const BPF_FS_MAGIC: FsType = FsType(libc::BPF_FS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const BTRFS_SUPER_MAGIC: FsType = FsType(libc::BTRFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const CGROUP2_SUPER_MAGIC: FsType = FsType(libc::CGROUP2_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const CGROUP_SUPER_MAGIC: FsType = FsType(libc::CGROUP_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const CODA_SUPER_MAGIC: FsType = FsType(libc::CODA_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const CRAMFS_MAGIC: FsType = FsType(libc::CRAMFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const DEBUGFS_MAGIC: FsType = FsType(libc::DEBUGFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const DEVPTS_SUPER_MAGIC: FsType = FsType(libc::DEVPTS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const ECRYPTFS_SUPER_MAGIC: FsType = FsType(libc::ECRYPTFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const EFS_SUPER_MAGIC: FsType = FsType(libc::EFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const EXT2_SUPER_MAGIC: FsType = FsType(libc::EXT2_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const EXT3_SUPER_MAGIC: FsType = FsType(libc::EXT3_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const EXT4_SUPER_MAGIC: FsType = FsType(libc::EXT4_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const F2FS_SUPER_MAGIC: FsType = FsType(libc::F2FS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const FUSE_SUPER_MAGIC: FsType = FsType(libc::FUSE_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const FUTEXFS_SUPER_MAGIC: FsType = FsType(libc::FUTEXFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const HOSTFS_SUPER_MAGIC: FsType = FsType(libc::HOSTFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const HPFS_SUPER_MAGIC: FsType = FsType(libc::HPFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const HUGETLBFS_MAGIC: FsType = FsType(libc::HUGETLBFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const ISOFS_SUPER_MAGIC: FsType = FsType(libc::ISOFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const JFFS2_SUPER_MAGIC: FsType = FsType(libc::JFFS2_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const MINIX2_SUPER_MAGIC2: FsType = FsType(libc::MINIX2_SUPER_MAGIC2 as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const MINIX2_SUPER_MAGIC: FsType = FsType(libc::MINIX2_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const MINIX3_SUPER_MAGIC: FsType = FsType(libc::MINIX3_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const MINIX_SUPER_MAGIC2: FsType = FsType(libc::MINIX_SUPER_MAGIC2 as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const MINIX_SUPER_MAGIC: FsType = FsType(libc::MINIX_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const MSDOS_SUPER_MAGIC: FsType = FsType(libc::MSDOS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const NCP_SUPER_MAGIC: FsType = FsType(libc::NCP_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const NFS_SUPER_MAGIC: FsType = FsType(libc::NFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const NILFS_SUPER_MAGIC: FsType = FsType(libc::NILFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const OCFS2_SUPER_MAGIC: FsType = FsType(libc::OCFS2_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const OPENPROM_SUPER_MAGIC: FsType = FsType(libc::OPENPROM_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const OVERLAYFS_SUPER_MAGIC: FsType = FsType(libc::OVERLAYFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const PROC_SUPER_MAGIC: FsType = FsType(libc::PROC_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const QNX4_SUPER_MAGIC: FsType = FsType(libc::QNX4_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const QNX6_SUPER_MAGIC: FsType = FsType(libc::QNX6_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const RDTGROUP_SUPER_MAGIC: FsType = FsType(libc::RDTGROUP_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const REISERFS_SUPER_MAGIC: FsType = FsType(libc::REISERFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const SECURITYFS_MAGIC: FsType = FsType(libc::SECURITYFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const SELINUX_MAGIC: FsType = FsType(libc::SELINUX_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const SMACK_MAGIC: FsType = FsType(libc::SMACK_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const SMB_SUPER_MAGIC: FsType = FsType(libc::SMB_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const SYSFS_MAGIC: FsType = FsType(libc::SYSFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const TMPFS_MAGIC: FsType = FsType(libc::TMPFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const TRACEFS_MAGIC: FsType = FsType(libc::TRACEFS_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const UDF_SUPER_MAGIC: FsType = FsType(libc::UDF_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const USBDEVICE_SUPER_MAGIC: FsType = FsType(libc::USBDEVICE_SUPER_MAGIC as fs_type_t); -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const XENFS_SUPER_MAGIC: FsType = FsType(libc::XENFS_SUPER_MAGIC as fs_type_t); diff --git a/bash-5.1/vendor/nix/src/sys/statvfs.rs b/bash-5.1/vendor/nix/src/sys/statvfs.rs index ab54b4b..38b1fdc 100644 --- a/bash-5.1/vendor/nix/src/sys/statvfs.rs +++ b/bash-5.1/vendor/nix/src/sys/statvfs.rs @@ -16,8 +16,10 @@ libc_bitflags!( #[derive(Default)] pub struct FsFlags: c_ulong { /// Read Only + #[cfg(not(target_os = "haiku"))] ST_RDONLY; /// Do not allow the set-uid bits to have an effect + #[cfg(not(target_os = "haiku"))] ST_NOSUID; /// Do not interpret character or block-special devices #[cfg(any(target_os = "android", target_os = "linux"))] diff --git a/bash-5.1/vendor/nix/src/sys/sysinfo.rs b/bash-5.1/vendor/nix/src/sys/sysinfo.rs index dc943c1..96f0433 100644 --- a/bash-5.1/vendor/nix/src/sys/sysinfo.rs +++ b/bash-5.1/vendor/nix/src/sys/sysinfo.rs @@ -1,9 +1,9 @@ use libc::{self, SI_LOAD_SHIFT}; -use std::{cmp, mem}; use std::time::Duration; +use std::{cmp, mem}; -use crate::Result; use crate::errno::Errno; +use crate::Result; /// System info structure returned by `sysinfo`. #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] @@ -75,5 +75,5 @@ impl SysInfo { pub fn sysinfo() -> Result { let mut info = mem::MaybeUninit::uninit(); let res = unsafe { libc::sysinfo(info.as_mut_ptr()) }; - Errno::result(res).map(|_| unsafe{ SysInfo(info.assume_init()) }) + Errno::result(res).map(|_| unsafe { SysInfo(info.assume_init()) }) } diff --git a/bash-5.1/vendor/nix/src/sys/termios.rs b/bash-5.1/vendor/nix/src/sys/termios.rs index 8870f6b..c5b27d2 100644 --- a/bash-5.1/vendor/nix/src/sys/termios.rs +++ b/bash-5.1/vendor/nix/src/sys/termios.rs @@ -64,9 +64,9 @@ //! # use nix::sys::termios::{BaudRate, cfsetispeed, cfsetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; -//! cfsetispeed(&mut t, BaudRate::B9600); -//! cfsetospeed(&mut t, BaudRate::B9600); -//! cfsetspeed(&mut t, BaudRate::B9600); +//! cfsetispeed(&mut t, BaudRate::B9600).unwrap(); +//! cfsetospeed(&mut t, BaudRate::B9600).unwrap(); +//! cfsetspeed(&mut t, BaudRate::B9600).unwrap(); //! # } //! ``` //! @@ -76,10 +76,10 @@ //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfgetospeed, cfsetispeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; -//! # cfsetspeed(&mut t, BaudRate::B9600); +//! # cfsetspeed(&mut t, BaudRate::B9600).unwrap(); //! let speed = cfgetispeed(&t); //! assert_eq!(speed, cfgetospeed(&t)); -//! cfsetispeed(&mut t, speed); +//! cfsetispeed(&mut t, speed).unwrap(); //! # } //! ``` //! @@ -255,8 +255,9 @@ libc_enum!{ /// enum. /// /// B0 is special and will disable the port. + #[cfg_attr(all(any(target_os = "haiku"), target_pointer_width = "64"), repr(u8))] #[cfg_attr(all(any(target_os = "ios", target_os = "macos"), target_pointer_width = "64"), repr(u64))] - #[cfg_attr(not(all(any(target_os = "ios", target_os = "macos"), target_pointer_width = "64")), repr(u32))] + #[cfg_attr(not(all(any(target_os = "ios", target_os = "macos", target_os = "haiku"), target_pointer_width = "64")), repr(u32))] #[non_exhaustive] pub enum BaudRate { B0, @@ -374,6 +375,14 @@ impl From for u32 { } } +#[cfg(target_os = "haiku")] +impl From for u8 { + fn from(b: BaudRate) -> u8 { + b as u8 + } +} + + // TODO: Add TCSASOFT, which will require treating this as a bitfield. libc_enum! { /// Specify when a port configuration change should occur. @@ -426,6 +435,7 @@ libc_enum! { } // TODO: Make this usable directly as a slice index. +#[cfg(not(target_os = "haiku"))] libc_enum! { /// Indices into the `termios.c_cc` array for special characters. #[repr(usize)] @@ -524,7 +534,7 @@ libc_bitflags! { #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] IXANY; - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] IMAXBEL; #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] @@ -851,7 +861,7 @@ libc_bitflags! { #[cfg_attr(docsrs, doc(cfg(all())))] ALTWERASE; IEXTEN; - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] EXTPROC; TOSTOP; @@ -979,6 +989,7 @@ cfg_if!{ /// /// `cfsetspeed()` sets the input and output baud rate in the given `Termios` structure. Note that /// this is part of the 4.4BSD standard and not part of POSIX. + #[cfg(not(target_os = "haiku"))] pub fn cfsetspeed(termios: &mut Termios, baud: BaudRate) -> Result<()> { let inner_termios = unsafe { termios.get_libc_termios_mut() }; let res = unsafe { libc::cfsetspeed(inner_termios, baud as libc::speed_t) }; @@ -1095,6 +1106,9 @@ mod test { #[test] fn try_from() { assert_eq!(Ok(BaudRate::B0), BaudRate::try_from(libc::B0)); - assert!(BaudRate::try_from(999999999).is_err()); + #[cfg(not(target_os = "haiku"))] + BaudRate::try_from(999999999).expect_err("assertion failed"); + #[cfg(target_os = "haiku")] + BaudRate::try_from(99).expect_err("assertion failed"); } } diff --git a/bash-5.1/vendor/nix/src/sys/time.rs b/bash-5.1/vendor/nix/src/sys/time.rs index 1e62b76..0cac7e8 100644 --- a/bash-5.1/vendor/nix/src/sys/time.rs +++ b/bash-5.1/vendor/nix/src/sys/time.rs @@ -1,9 +1,10 @@ -use std::{cmp, fmt, ops}; -use std::time::Duration; -use std::convert::From; +#[cfg_attr(target_env = "musl", allow(deprecated))] +// https://github.com/rust-lang/libc/issues/1848 +pub use libc::{suseconds_t, time_t}; use libc::{timespec, timeval}; -#[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 -pub use libc::{time_t, suseconds_t}; +use std::convert::From; +use std::time::Duration; +use std::{cmp, fmt, ops}; #[cfg(any( all(feature = "time", any(target_os = "android", target_os = "linux")), @@ -62,10 +63,12 @@ pub(crate) mod timer { }, it_value: *t.as_ref(), }), - Expiration::IntervalDelayed(start, interval) => TimerSpec(libc::itimerspec { - it_interval: *interval.as_ref(), - it_value: *start.as_ref(), - }), + Expiration::IntervalDelayed(start, interval) => { + TimerSpec(libc::itimerspec { + it_interval: *interval.as_ref(), + it_value: *start.as_ref(), + }) + } Expiration::Interval(t) => TimerSpec(libc::itimerspec { it_interval: *t.as_ref(), it_value: *t.as_ref(), @@ -76,7 +79,7 @@ pub(crate) mod timer { /// An enumeration allowing the definition of the expiration time of an alarm, /// recurring or not. - #[derive(Debug, Clone, Copy, PartialEq)] + #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Expiration { /// Alarm will trigger once after the time given in `TimeSpec` OneShot(TimeSpec), @@ -94,7 +97,12 @@ pub(crate) mod timer { const TFD_TIMER_ABSTIME = libc::TFD_TIMER_ABSTIME; } } - #[cfg(any(target_os = "freebsd", target_os = "netbsd", target_os = "dragonfly", target_os = "illumos"))] + #[cfg(any( + target_os = "freebsd", + target_os = "netbsd", + target_os = "dragonfly", + target_os = "illumos" + ))] bitflags! { /// Flags that are used for arming the timer. pub struct TimerSetTimeFlags: libc::c_int { @@ -117,10 +125,15 @@ pub(crate) mod timer { it_interval: int_ts, it_value: val_ts, }) => { - if (int_ts.tv_sec == val_ts.tv_sec) && (int_ts.tv_nsec == val_ts.tv_nsec) { + if (int_ts.tv_sec == val_ts.tv_sec) + && (int_ts.tv_nsec == val_ts.tv_nsec) + { Expiration::Interval(int_ts.into()) } else { - Expiration::IntervalDelayed(val_ts.into(), int_ts.into()) + Expiration::IntervalDelayed( + val_ts.into(), + int_ts.into(), + ) } } } @@ -136,14 +149,16 @@ pub trait TimeValLike: Sized { #[inline] fn hours(hours: i64) -> Self { - let secs = hours.checked_mul(SECS_PER_HOUR) + let secs = hours + .checked_mul(SECS_PER_HOUR) .expect("TimeValLike::hours ouf of bounds"); Self::seconds(secs) } #[inline] fn minutes(minutes: i64) -> Self { - let secs = minutes.checked_mul(SECS_PER_MINUTE) + let secs = minutes + .checked_mul(SECS_PER_MINUTE) .expect("TimeValLike::minutes out of bounds"); Self::seconds(secs) } @@ -178,10 +193,10 @@ const SECS_PER_MINUTE: i64 = 60; const SECS_PER_HOUR: i64 = 3600; #[cfg(target_pointer_width = "64")] -const TS_MAX_SECONDS: i64 = (::std::i64::MAX / NANOS_PER_SEC) - 1; +const TS_MAX_SECONDS: i64 = (i64::MAX / NANOS_PER_SEC) - 1; #[cfg(target_pointer_width = "32")] -const TS_MAX_SECONDS: i64 = ::std::isize::MAX as i64; +const TS_MAX_SECONDS: i64 = isize::MAX as i64; const TS_MIN_SECONDS: i64 = -TS_MAX_SECONDS; @@ -243,15 +258,23 @@ impl PartialOrd for TimeSpec { impl TimeValLike for TimeSpec { #[inline] fn seconds(seconds: i64) -> TimeSpec { - assert!(seconds >= TS_MIN_SECONDS && seconds <= TS_MAX_SECONDS, - "TimeSpec out of bounds; seconds={}", seconds); - #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 - TimeSpec(timespec {tv_sec: seconds as time_t, tv_nsec: 0 }) + assert!( + (TS_MIN_SECONDS..=TS_MAX_SECONDS).contains(&seconds), + "TimeSpec out of bounds; seconds={}", + seconds + ); + #[cfg_attr(target_env = "musl", allow(deprecated))] + // https://github.com/rust-lang/libc/issues/1848 + TimeSpec(timespec { + tv_sec: seconds as time_t, + tv_nsec: 0, + }) } #[inline] fn milliseconds(milliseconds: i64) -> TimeSpec { - let nanoseconds = milliseconds.checked_mul(1_000_000) + let nanoseconds = milliseconds + .checked_mul(1_000_000) .expect("TimeSpec::milliseconds out of bounds"); TimeSpec::nanoseconds(nanoseconds) @@ -260,7 +283,8 @@ impl TimeValLike for TimeSpec { /// Makes a new `TimeSpec` with given number of microseconds. #[inline] fn microseconds(microseconds: i64) -> TimeSpec { - let nanoseconds = microseconds.checked_mul(1_000) + let nanoseconds = microseconds + .checked_mul(1_000) .expect("TimeSpec::milliseconds out of bounds"); TimeSpec::nanoseconds(nanoseconds) @@ -270,11 +294,16 @@ impl TimeValLike for TimeSpec { #[inline] fn nanoseconds(nanoseconds: i64) -> TimeSpec { let (secs, nanos) = div_mod_floor_64(nanoseconds, NANOS_PER_SEC); - assert!(secs >= TS_MIN_SECONDS && secs <= TS_MAX_SECONDS, - "TimeSpec out of bounds"); - #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 - TimeSpec(timespec {tv_sec: secs as time_t, - tv_nsec: nanos as timespec_tv_nsec_t }) + assert!( + (TS_MIN_SECONDS..=TS_MAX_SECONDS).contains(&secs), + "TimeSpec out of bounds" + ); + #[cfg_attr(target_env = "musl", allow(deprecated))] + // https://github.com/rust-lang/libc/issues/1848 + TimeSpec(timespec { + tv_sec: secs as time_t, + tv_nsec: nanos as timespec_tv_nsec_t, + }) } fn num_seconds(&self) -> i64 { @@ -301,6 +330,15 @@ impl TimeValLike for TimeSpec { } impl TimeSpec { + /// Construct a new `TimeSpec` from its components + #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 + pub const fn new(seconds: time_t, nanoseconds: timespec_tv_nsec_t) -> Self { + Self(timespec { + tv_sec: seconds, + tv_nsec: nanoseconds, + }) + } + fn nanos_mod_sec(&self) -> timespec_tv_nsec_t { if self.tv_sec() < 0 && self.tv_nsec() > 0 { self.tv_nsec() - NANOS_PER_SEC as timespec_tv_nsec_t @@ -319,10 +357,11 @@ impl TimeSpec { } pub const fn from_duration(duration: Duration) -> Self { - #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 + #[cfg_attr(target_env = "musl", allow(deprecated))] + // https://github.com/rust-lang/libc/issues/1848 TimeSpec(timespec { tv_sec: duration.as_secs() as time_t, - tv_nsec: duration.subsec_nanos() as timespec_tv_nsec_t + tv_nsec: duration.subsec_nanos() as timespec_tv_nsec_t, }) } @@ -343,8 +382,7 @@ impl ops::Add for TimeSpec { type Output = TimeSpec; fn add(self, rhs: TimeSpec) -> TimeSpec { - TimeSpec::nanoseconds( - self.num_nanoseconds() + rhs.num_nanoseconds()) + TimeSpec::nanoseconds(self.num_nanoseconds() + rhs.num_nanoseconds()) } } @@ -352,8 +390,7 @@ impl ops::Sub for TimeSpec { type Output = TimeSpec; fn sub(self, rhs: TimeSpec) -> TimeSpec { - TimeSpec::nanoseconds( - self.num_nanoseconds() - rhs.num_nanoseconds()) + TimeSpec::nanoseconds(self.num_nanoseconds() - rhs.num_nanoseconds()) } } @@ -361,7 +398,9 @@ impl ops::Mul for TimeSpec { type Output = TimeSpec; fn mul(self, rhs: i32) -> TimeSpec { - let usec = self.num_nanoseconds().checked_mul(i64::from(rhs)) + let usec = self + .num_nanoseconds() + .checked_mul(i64::from(rhs)) .expect("TimeSpec multiply out of bounds"); TimeSpec::nanoseconds(usec) @@ -407,8 +446,6 @@ impl fmt::Display for TimeSpec { } } - - #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct TimeVal(timeval); @@ -416,10 +453,10 @@ pub struct TimeVal(timeval); const MICROS_PER_SEC: i64 = 1_000_000; #[cfg(target_pointer_width = "64")] -const TV_MAX_SECONDS: i64 = (::std::i64::MAX / MICROS_PER_SEC) - 1; +const TV_MAX_SECONDS: i64 = (i64::MAX / MICROS_PER_SEC) - 1; #[cfg(target_pointer_width = "32")] -const TV_MAX_SECONDS: i64 = ::std::isize::MAX as i64; +const TV_MAX_SECONDS: i64 = isize::MAX as i64; const TV_MIN_SECONDS: i64 = -TV_MAX_SECONDS; @@ -456,15 +493,23 @@ impl PartialOrd for TimeVal { impl TimeValLike for TimeVal { #[inline] fn seconds(seconds: i64) -> TimeVal { - assert!(seconds >= TV_MIN_SECONDS && seconds <= TV_MAX_SECONDS, - "TimeVal out of bounds; seconds={}", seconds); - #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 - TimeVal(timeval {tv_sec: seconds as time_t, tv_usec: 0 }) + assert!( + (TV_MIN_SECONDS..=TV_MAX_SECONDS).contains(&seconds), + "TimeVal out of bounds; seconds={}", + seconds + ); + #[cfg_attr(target_env = "musl", allow(deprecated))] + // https://github.com/rust-lang/libc/issues/1848 + TimeVal(timeval { + tv_sec: seconds as time_t, + tv_usec: 0, + }) } #[inline] fn milliseconds(milliseconds: i64) -> TimeVal { - let microseconds = milliseconds.checked_mul(1_000) + let microseconds = milliseconds + .checked_mul(1_000) .expect("TimeVal::milliseconds out of bounds"); TimeVal::microseconds(microseconds) @@ -474,11 +519,16 @@ impl TimeValLike for TimeVal { #[inline] fn microseconds(microseconds: i64) -> TimeVal { let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC); - assert!(secs >= TV_MIN_SECONDS && secs <= TV_MAX_SECONDS, - "TimeVal out of bounds"); - #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 - TimeVal(timeval {tv_sec: secs as time_t, - tv_usec: micros as suseconds_t }) + assert!( + (TV_MIN_SECONDS..=TV_MAX_SECONDS).contains(&secs), + "TimeVal out of bounds" + ); + #[cfg_attr(target_env = "musl", allow(deprecated))] + // https://github.com/rust-lang/libc/issues/1848 + TimeVal(timeval { + tv_sec: secs as time_t, + tv_usec: micros as suseconds_t, + }) } /// Makes a new `TimeVal` with given number of nanoseconds. Some precision @@ -487,11 +537,16 @@ impl TimeValLike for TimeVal { fn nanoseconds(nanoseconds: i64) -> TimeVal { let microseconds = nanoseconds / 1000; let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC); - assert!(secs >= TV_MIN_SECONDS && secs <= TV_MAX_SECONDS, - "TimeVal out of bounds"); - #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 - TimeVal(timeval {tv_sec: secs as time_t, - tv_usec: micros as suseconds_t }) + assert!( + (TV_MIN_SECONDS..=TV_MAX_SECONDS).contains(&secs), + "TimeVal out of bounds" + ); + #[cfg_attr(target_env = "musl", allow(deprecated))] + // https://github.com/rust-lang/libc/issues/1848 + TimeVal(timeval { + tv_sec: secs as time_t, + tv_usec: micros as suseconds_t, + }) } fn num_seconds(&self) -> i64 { @@ -518,6 +573,15 @@ impl TimeValLike for TimeVal { } impl TimeVal { + /// Construct a new `TimeVal` from its components + #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 + pub const fn new(seconds: time_t, microseconds: suseconds_t) -> Self { + Self(timeval { + tv_sec: seconds, + tv_usec: microseconds, + }) + } + fn micros_mod_sec(&self) -> suseconds_t { if self.tv_sec() < 0 && self.tv_usec() > 0 { self.tv_usec() - MICROS_PER_SEC as suseconds_t @@ -548,8 +612,7 @@ impl ops::Add for TimeVal { type Output = TimeVal; fn add(self, rhs: TimeVal) -> TimeVal { - TimeVal::microseconds( - self.num_microseconds() + rhs.num_microseconds()) + TimeVal::microseconds(self.num_microseconds() + rhs.num_microseconds()) } } @@ -557,8 +620,7 @@ impl ops::Sub for TimeVal { type Output = TimeVal; fn sub(self, rhs: TimeVal) -> TimeVal { - TimeVal::microseconds( - self.num_microseconds() - rhs.num_microseconds()) + TimeVal::microseconds(self.num_microseconds() - rhs.num_microseconds()) } } @@ -566,7 +628,9 @@ impl ops::Mul for TimeVal { type Output = TimeVal; fn mul(self, rhs: i32) -> TimeVal { - let usec = self.num_microseconds().checked_mul(i64::from(rhs)) + let usec = self + .num_microseconds() + .checked_mul(i64::from(rhs)) .expect("TimeVal multiply out of bounds"); TimeVal::microseconds(usec) @@ -624,18 +688,16 @@ fn div_mod_floor_64(this: i64, other: i64) -> (i64, i64) { #[inline] fn div_floor_64(this: i64, other: i64) -> i64 { match div_rem_64(this, other) { - (d, r) if (r > 0 && other < 0) - || (r < 0 && other > 0) => d - 1, - (d, _) => d, + (d, r) if (r > 0 && other < 0) || (r < 0 && other > 0) => d - 1, + (d, _) => d, } } #[inline] fn mod_floor_64(this: i64, other: i64) -> i64 { match this % other { - r if (r > 0 && other < 0) - || (r < 0 && other > 0) => r + other, - r => r, + r if (r > 0 && other < 0) || (r < 0 && other > 0) => r + other, + r => r, } } @@ -651,11 +713,15 @@ mod test { #[test] pub fn test_timespec() { - assert!(TimeSpec::seconds(1) != TimeSpec::zero()); - assert_eq!(TimeSpec::seconds(1) + TimeSpec::seconds(2), - TimeSpec::seconds(3)); - assert_eq!(TimeSpec::minutes(3) + TimeSpec::seconds(2), - TimeSpec::seconds(182)); + assert_ne!(TimeSpec::seconds(1), TimeSpec::zero()); + assert_eq!( + TimeSpec::seconds(1) + TimeSpec::seconds(2), + TimeSpec::seconds(3) + ); + assert_eq!( + TimeSpec::minutes(3) + TimeSpec::seconds(2), + TimeSpec::seconds(182) + ); } #[test] @@ -677,7 +743,7 @@ mod test { #[test] pub fn test_timespec_ord() { - assert!(TimeSpec::seconds(1) == TimeSpec::nanoseconds(1_000_000_000)); + assert_eq!(TimeSpec::seconds(1), TimeSpec::nanoseconds(1_000_000_000)); assert!(TimeSpec::seconds(1) < TimeSpec::nanoseconds(1_000_000_001)); assert!(TimeSpec::seconds(1) > TimeSpec::nanoseconds(999_999_999)); assert!(TimeSpec::seconds(-1) < TimeSpec::nanoseconds(-999_999_999)); @@ -690,22 +756,29 @@ mod test { assert_eq!(TimeSpec::seconds(42).to_string(), "42 seconds"); assert_eq!(TimeSpec::milliseconds(42).to_string(), "0.042 seconds"); assert_eq!(TimeSpec::microseconds(42).to_string(), "0.000042 seconds"); - assert_eq!(TimeSpec::nanoseconds(42).to_string(), "0.000000042 seconds"); + assert_eq!( + TimeSpec::nanoseconds(42).to_string(), + "0.000000042 seconds" + ); assert_eq!(TimeSpec::seconds(-86401).to_string(), "-86401 seconds"); } #[test] pub fn test_timeval() { - assert!(TimeVal::seconds(1) != TimeVal::zero()); - assert_eq!(TimeVal::seconds(1) + TimeVal::seconds(2), - TimeVal::seconds(3)); - assert_eq!(TimeVal::minutes(3) + TimeVal::seconds(2), - TimeVal::seconds(182)); + assert_ne!(TimeVal::seconds(1), TimeVal::zero()); + assert_eq!( + TimeVal::seconds(1) + TimeVal::seconds(2), + TimeVal::seconds(3) + ); + assert_eq!( + TimeVal::minutes(3) + TimeVal::seconds(2), + TimeVal::seconds(182) + ); } #[test] pub fn test_timeval_ord() { - assert!(TimeVal::seconds(1) == TimeVal::microseconds(1_000_000)); + assert_eq!(TimeVal::seconds(1), TimeVal::microseconds(1_000_000)); assert!(TimeVal::seconds(1) < TimeVal::microseconds(1_000_001)); assert!(TimeVal::seconds(1) > TimeVal::microseconds(999_999)); assert!(TimeVal::seconds(-1) < TimeVal::microseconds(-999_999)); diff --git a/bash-5.1/vendor/nix/src/sys/timer.rs b/bash-5.1/vendor/nix/src/sys/timer.rs index 349346b..45ce0e5 100644 --- a/bash-5.1/vendor/nix/src/sys/timer.rs +++ b/bash-5.1/vendor/nix/src/sys/timer.rs @@ -70,6 +70,7 @@ pub struct Timer(libc::timer_t); impl Timer { /// Creates a new timer based on the clock defined by `clockid`. The details /// of the signal and its handler are defined by the passed `sigevent`. + #[cfg_attr(has_doc_alias, doc(alias("timer_create")))] pub fn new(clockid: ClockId, mut sigevent: SigEvent) -> Result { let mut timer_id: mem::MaybeUninit = mem::MaybeUninit::uninit(); Errno::result(unsafe { @@ -122,6 +123,7 @@ impl Timer { /// /// Note: Setting a one shot alarm with a 0s TimeSpec disable the alarm /// altogether. + #[cfg_attr(has_doc_alias, doc(alias("timer_settime")))] pub fn set(&mut self, expiration: Expiration, flags: TimerSetTimeFlags) -> Result<()> { let timerspec: TimerSpec = expiration.into(); Errno::result(unsafe { @@ -136,6 +138,7 @@ impl Timer { } /// Get the parameters for the alarm currently set, if any. + #[cfg_attr(has_doc_alias, doc(alias("timer_gettime")))] pub fn get(&self) -> Result> { let mut timerspec = TimerSpec::none(); Errno::result(unsafe { libc::timer_gettime(self.0, timerspec.as_mut()) }).map(|_| { @@ -158,6 +161,7 @@ impl Timer { /// 'overrun'. This function returns how many times that has happened to /// this timer, up to `libc::DELAYTIMER_MAX`. If more than the maximum /// number of overruns have happened the return is capped to the maximum. + #[cfg_attr(has_doc_alias, doc(alias("timer_getoverrun")))] pub fn overruns(&self) -> i32 { unsafe { libc::timer_getoverrun(self.0) } } diff --git a/bash-5.1/vendor/nix/src/sys/timerfd.rs b/bash-5.1/vendor/nix/src/sys/timerfd.rs index 18acbae..4286065 100644 --- a/bash-5.1/vendor/nix/src/sys/timerfd.rs +++ b/bash-5.1/vendor/nix/src/sys/timerfd.rs @@ -92,6 +92,7 @@ impl TimerFd { /// Creates a new timer based on the clock defined by `clockid`. The /// underlying fd can be assigned specific flags with `flags` (CLOEXEC, /// NONBLOCK). The underlying fd will be closed on drop. + #[cfg_attr(has_doc_alias, doc(alias("timerfd_create")))] pub fn new(clockid: ClockId, flags: TimerFlags) -> Result { Errno::result(unsafe { libc::timerfd_create(clockid as i32, flags.bits()) }) .map(|fd| Self { fd }) @@ -133,6 +134,7 @@ impl TimerFd { /// /// Note: Setting a one shot alarm with a 0s TimeSpec disables the alarm /// altogether. + #[cfg_attr(has_doc_alias, doc(alias("timerfd_settime")))] pub fn set(&self, expiration: Expiration, flags: TimerSetTimeFlags) -> Result<()> { let timerspec: TimerSpec = expiration.into(); Errno::result(unsafe { @@ -147,6 +149,7 @@ impl TimerFd { } /// Get the parameters for the alarm currently set, if any. + #[cfg_attr(has_doc_alias, doc(alias("timerfd_gettime")))] pub fn get(&self) -> Result> { let mut timerspec = TimerSpec::none(); Errno::result(unsafe { libc::timerfd_gettime(self.fd, timerspec.as_mut()) }).map(|_| { @@ -163,6 +166,7 @@ impl TimerFd { } /// Remove the alarm if any is set. + #[cfg_attr(has_doc_alias, doc(alias("timerfd_settime")))] pub fn unset(&self) -> Result<()> { Errno::result(unsafe { libc::timerfd_settime( diff --git a/bash-5.1/vendor/nix/src/sys/uio.rs b/bash-5.1/vendor/nix/src/sys/uio.rs index ba6c64e..1908973 100644 --- a/bash-5.1/vendor/nix/src/sys/uio.rs +++ b/bash-5.1/vendor/nix/src/sys/uio.rs @@ -39,7 +39,7 @@ pub fn readv(fd: RawFd, iov: &mut [IoSliceMut<'_>]) -> Result { /// or an error occurs. The file offset is not changed. /// /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn pwritev(fd: RawFd, iov: &[IoSlice<'_>], offset: off_t) -> Result { @@ -62,7 +62,7 @@ pub fn pwritev(fd: RawFd, iov: &[IoSlice<'_>], /// changed. /// /// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html) -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn preadv(fd: RawFd, iov: &mut [IoSliceMut<'_>], offset: off_t) -> Result { @@ -132,6 +132,10 @@ pub struct RemoteIoVec { note = "`IoVec` is no longer used in the public interface, use `IoSlice` or `IoSliceMut` instead" )] #[repr(transparent)] +#[allow(renamed_and_removed_lints)] +#[allow(clippy::unknown_clippy_lints)] +// Clippy false positive: https://github.com/rust-lang/rust-clippy/issues/8867 +#[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct IoVec(pub(crate) libc::iovec, PhantomData); diff --git a/bash-5.1/vendor/nix/src/unistd.rs b/bash-5.1/vendor/nix/src/unistd.rs index 764b3de..42e1456 100644 --- a/bash-5.1/vendor/nix/src/unistd.rs +++ b/bash-5.1/vendor/nix/src/unistd.rs @@ -1,28 +1,42 @@ //! Safe wrappers around functions found in libc "unistd.h" header -#[cfg(not(target_os = "redox"))] -use cfg_if::cfg_if; use crate::errno::{self, Errno}; -use crate::{Error, Result, NixPath}; #[cfg(not(target_os = "redox"))] #[cfg(feature = "fs")] -use crate::fcntl::{AtFlags, at_rawfd}; -use libc::{self, c_char, c_void, c_int, c_long, c_uint, size_t, pid_t, off_t, - uid_t, gid_t, mode_t, PATH_MAX}; +use crate::fcntl::{at_rawfd, AtFlags}; #[cfg(feature = "fs")] -use crate::fcntl::{FdFlag, OFlag, fcntl, FcntlArg::F_SETFD}; -use std::{fmt, mem, ptr}; +use crate::fcntl::{fcntl, FcntlArg::F_SETFD, FdFlag, OFlag}; +#[cfg(all( + feature = "fs", + any( + target_os = "openbsd", + target_os = "netbsd", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "macos", + target_os = "ios" + ) +))] +use crate::sys::stat::FileFlag; +#[cfg(feature = "fs")] +use crate::sys::stat::Mode; +use crate::{Error, NixPath, Result}; +#[cfg(not(target_os = "redox"))] +use cfg_if::cfg_if; +use libc::{ + self, c_char, c_int, c_long, c_uint, c_void, gid_t, mode_t, off_t, pid_t, + size_t, uid_t, PATH_MAX, +}; use std::convert::Infallible; use std::ffi::{CStr, OsString}; #[cfg(not(target_os = "redox"))] use std::ffi::{CString, OsStr}; -use std::os::unix::ffi::OsStringExt; #[cfg(not(target_os = "redox"))] use std::os::unix::ffi::OsStrExt; +use std::os::unix::ffi::OsStringExt; use std::os::unix::io::RawFd; use std::path::PathBuf; -#[cfg(feature = "fs")] -use crate::sys::stat::Mode; +use std::{fmt, mem, ptr}; feature! { #![feature = "fs"] @@ -30,18 +44,22 @@ feature! { pub use self::pivot_root::*; } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] pub use self::setres::*; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] pub use self::getres::*; feature! { @@ -61,11 +79,13 @@ impl Uid { } /// Returns Uid of calling process. This is practically a more Rusty alias for `getuid`. + #[cfg_attr(has_doc_alias, doc(alias("getuid")))] pub fn current() -> Self { getuid() } /// Returns effective Uid of calling process. This is practically a more Rusty alias for `geteuid`. + #[cfg_attr(has_doc_alias, doc(alias("geteuid")))] pub fn effective() -> Self { geteuid() } @@ -87,6 +107,12 @@ impl From for uid_t { } } +impl From for Uid { + fn from(uid: uid_t) -> Self { + Uid(uid) + } +} + impl fmt::Display for Uid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) @@ -110,11 +136,13 @@ impl Gid { } /// Returns Gid of calling process. This is practically a more Rusty alias for `getgid`. + #[cfg_attr(has_doc_alias, doc(alias("getgid")))] pub fn current() -> Self { getgid() } /// Returns effective Gid of calling process. This is practically a more Rusty alias for `getegid`. + #[cfg_attr(has_doc_alias, doc(alias("getegid")))] pub fn effective() -> Self { getegid() } @@ -131,6 +159,12 @@ impl From for gid_t { } } +impl From for Gid { + fn from(gid: gid_t) -> Self { + Gid(gid) + } +} + impl fmt::Display for Gid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) @@ -154,11 +188,13 @@ impl Pid { } /// Returns PID of calling process + #[cfg_attr(has_doc_alias, doc(alias("getpid")))] pub fn this() -> Self { getpid() } /// Returns PID of parent of calling process + #[cfg_attr(has_doc_alias, doc(alias("getppid")))] pub fn parent() -> Self { getppid() } @@ -549,7 +585,7 @@ pub fn mkfifo(path: &P, mode: Mode) -> Result<()> { // mkfifoat is not implemented in OSX or android #[inline] #[cfg(not(any( - target_os = "macos", target_os = "ios", + target_os = "macos", target_os = "ios", target_os = "haiku", target_os = "android", target_os = "redox")))] pub fn mkfifoat(dirfd: Option, path: &P, mode: Mode) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { @@ -596,7 +632,7 @@ fn reserve_double_buffer_size(buf: &mut Vec, limit: usize) -> Result<()> { use std::cmp::min; if buf.capacity() >= limit { - return Err(Errno::ERANGE) + return Err(Errno::ERANGE); } let capacity = min(buf.capacity() * 2, limit); @@ -722,8 +758,8 @@ pub enum FchownatFlags { /// If `flag` is `FchownatFlags::NoFollowSymlink` and `path` names a symbolic link, /// then the mode of the symbolic link is changed. /// -/// `fchownat(None, path, mode, FchownatFlags::NoFollowSymlink)` is identical to -/// a call `libc::lchown(path, mode)`. That's why `lchmod` is unimplemented in +/// `fchownat(None, path, owner, group, FchownatFlags::NoFollowSymlink)` is identical to +/// a call `libc::lchown(path, owner, group)`. That's why `lchown` is unimplemented in /// the `nix` crate. /// /// # References @@ -967,34 +1003,34 @@ pub fn sethostname>(name: S) -> Result<()> { Errno::result(res).map(drop) } -/// Get the host name and store it in the provided buffer, returning a pointer -/// the `CStr` in that buffer on success (see +/// Get the host name and store it in an internally allocated buffer, returning an +/// `OsString` on success (see /// [gethostname(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/gethostname.html)). /// /// This function call attempts to get the host name for the running system and -/// store it in a provided buffer. The buffer will be populated with bytes up -/// to the length of the provided slice including a NUL terminating byte. If -/// the hostname is longer than the length provided, no error will be provided. -/// The posix specification does not specify whether implementations will -/// null-terminate in this case, but the nix implementation will ensure that the -/// buffer is null terminated in this case. +/// store it in an internal buffer, returning it as an `OsString` if successful. /// /// ```no_run /// use nix::unistd; /// -/// let mut buf = [0u8; 64]; -/// let hostname_cstr = unistd::gethostname(&mut buf).expect("Failed getting hostname"); -/// let hostname = hostname_cstr.to_str().expect("Hostname wasn't valid UTF-8"); +/// let hostname = unistd::gethostname().expect("Failed getting hostname"); +/// let hostname = hostname.into_string().expect("Hostname wasn't valid UTF-8"); /// println!("Hostname: {}", hostname); /// ``` -pub fn gethostname(buffer: &mut [u8]) -> Result<&CStr> { +pub fn gethostname() -> Result { + // The capacity is the max length of a hostname plus the NUL terminator. + let mut buffer: Vec = Vec::with_capacity(256); let ptr = buffer.as_mut_ptr() as *mut c_char; - let len = buffer.len() as size_t; + let len = buffer.capacity() as size_t; let res = unsafe { libc::gethostname(ptr, len) }; Errno::result(res).map(|_| { - buffer[len - 1] = 0; // ensure always null-terminated - unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) } + unsafe { + buffer.as_mut_ptr().wrapping_add(len - 1).write(0); // ensure always null-terminated + let len = CStr::from_ptr(buffer.as_ptr() as *const c_char).len(); + buffer.set_len(len); + } + OsString::from_vec(buffer) }) } } @@ -1033,7 +1069,9 @@ pub fn close(fd: RawFd) -> Result<()> { /// /// See also [read(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html) pub fn read(fd: RawFd, buf: &mut [u8]) -> Result { - let res = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t) }; + let res = unsafe { + libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t) + }; Errno::result(res).map(|r| r as usize) } @@ -1042,7 +1080,9 @@ pub fn read(fd: RawFd, buf: &mut [u8]) -> Result { /// /// See also [write(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html) pub fn write(fd: RawFd, buf: &[u8]) -> Result { - let res = unsafe { libc::write(fd, buf.as_ptr() as *const c_void, buf.len() as size_t) }; + let res = unsafe { + libc::write(fd, buf.as_ptr() as *const c_void, buf.len() as size_t) + }; Errno::result(res).map(|r| r as usize) } @@ -1106,15 +1146,13 @@ pub fn lseek64(fd: RawFd, offset: libc::off64_t, whence: Whence) -> Result std::result::Result<(RawFd, RawFd), Error> { - unsafe { - let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit(); + let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit(); - let res = libc::pipe(fds.as_mut_ptr() as *mut c_int); + let res = unsafe { libc::pipe(fds.as_mut_ptr() as *mut c_int) }; - Error::result(res)?; + Error::result(res)?; - Ok((fds.assume_init()[0], fds.assume_init()[1])) - } + unsafe { Ok((fds.assume_init()[0], fds.assume_init()[1])) } } feature! { @@ -1534,7 +1572,7 @@ pub fn getgroups() -> Result> { /// # use std::error::Error; /// # use nix::unistd::*; /// # -/// # fn try_main() -> Result<(), Box> { +/// # fn try_main() -> Result<(), Box> { /// let uid = Uid::from_raw(33); /// let gid = Gid::from_raw(34); /// setgroups(&[gid])?; @@ -1546,7 +1584,7 @@ pub fn getgroups() -> Result> { /// # /// # try_main().unwrap(); /// ``` -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))] +#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox", target_os = "haiku")))] pub fn setgroups(groups: &[Gid]) -> Result<()> { cfg_if! { if #[cfg(any(target_os = "dragonfly", @@ -1660,7 +1698,7 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { /// # use std::ffi::CString; /// # use nix::unistd::*; /// # -/// # fn try_main() -> Result<(), Box> { +/// # fn try_main() -> Result<(), Box> { /// let user = CString::new("www-data").unwrap(); /// let uid = Uid::from_raw(33); /// let gid = Gid::from_raw(33); @@ -1673,7 +1711,7 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { /// # /// # try_main().unwrap(); /// ``` -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))] +#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox", target_os = "haiku")))] pub fn initgroups(user: &CStr, group: Gid) -> Result<()> { cfg_if! { if #[cfg(any(target_os = "ios", target_os = "macos"))] { @@ -1802,7 +1840,7 @@ pub fn sleep(seconds: c_uint) -> c_uint { feature! { #![feature = "acct"] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] pub mod acct { use crate::{Result, NixPath}; use crate::errno::Errno; @@ -2088,12 +2126,12 @@ feature! { pub enum SysconfVar { /// Maximum number of I/O operations in a single list I/O call supported by /// the implementation. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] AIO_LISTIO_MAX = libc::_SC_AIO_LISTIO_MAX, /// Maximum number of outstanding asynchronous I/O operations supported by /// the implementation. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] AIO_MAX = libc::_SC_AIO_MAX, #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", @@ -2110,19 +2148,19 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] ATEXIT_MAX = libc::_SC_ATEXIT_MAX, /// Maximum obase values allowed by the bc utility. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] BC_BASE_MAX = libc::_SC_BC_BASE_MAX, /// Maximum number of elements permitted in an array by the bc utility. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] BC_DIM_MAX = libc::_SC_BC_DIM_MAX, /// Maximum scale value allowed by the bc utility. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] BC_SCALE_MAX = libc::_SC_BC_SCALE_MAX, /// Maximum length of a string constant accepted by the bc utility. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] BC_STRING_MAX = libc::_SC_BC_STRING_MAX, /// Maximum number of simultaneous processes per real user ID. @@ -2131,16 +2169,16 @@ pub enum SysconfVar { CLK_TCK = libc::_SC_CLK_TCK, /// Maximum number of weights that can be assigned to an entry of the /// LC_COLLATE order keyword in the locale definition file - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] COLL_WEIGHTS_MAX = libc::_SC_COLL_WEIGHTS_MAX, /// Maximum number of timer expiration overruns. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] DELAYTIMER_MAX = libc::_SC_DELAYTIMER_MAX, /// Maximum number of expressions that can be nested within parentheses by /// the expr utility. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] EXPR_NEST_MAX = libc::_SC_EXPR_NEST_MAX, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos", @@ -2159,10 +2197,11 @@ pub enum SysconfVar { /// input line (either standard input or another file), when the utility is /// described as processing text files. The length includes room for the /// trailing . - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] LINE_MAX = libc::_SC_LINE_MAX, /// Maximum length of a login name. + #[cfg(not(target_os = "haiku"))] LOGIN_NAME_MAX = libc::_SC_LOGIN_NAME_MAX, /// Maximum number of simultaneous supplementary group IDs per process. NGROUPS_MAX = libc::_SC_NGROUPS_MAX, @@ -2175,11 +2214,11 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] GETPW_R_SIZE_MAX = libc::_SC_GETPW_R_SIZE_MAX, /// The maximum number of open message queue descriptors a process may hold. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] MQ_OPEN_MAX = libc::_SC_MQ_OPEN_MAX, /// The maximum number of message priorities supported by the implementation. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] MQ_PRIO_MAX = libc::_SC_MQ_PRIO_MAX, /// A value one greater than the maximum value that the system may assign to @@ -2197,7 +2236,7 @@ pub enum SysconfVar { /// The implementation supports barriers. _POSIX_BARRIERS = libc::_SC_BARRIERS, /// The implementation supports asynchronous input and output. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_ASYNCHRONOUS_IO = libc::_SC_ASYNCHRONOUS_IO, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos", @@ -2213,7 +2252,7 @@ pub enum SysconfVar { /// The implementation supports the Process CPU-Time Clocks option. _POSIX_CPUTIME = libc::_SC_CPUTIME, /// The implementation supports the File Synchronization option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_FSYNC = libc::_SC_FSYNC, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos", @@ -2227,15 +2266,15 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_JOB_CONTROL = libc::_SC_JOB_CONTROL, /// The implementation supports memory mapped Files. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MAPPED_FILES = libc::_SC_MAPPED_FILES, /// The implementation supports the Process Memory Locking option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MEMLOCK = libc::_SC_MEMLOCK, /// The implementation supports the Range Memory Locking option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MEMLOCK_RANGE = libc::_SC_MEMLOCK_RANGE, /// The implementation supports memory protection. @@ -2243,7 +2282,7 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MEMORY_PROTECTION = libc::_SC_MEMORY_PROTECTION, /// The implementation supports the Message Passing option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MESSAGE_PASSING = libc::_SC_MESSAGE_PASSING, /// The implementation supports the Monotonic Clock option. @@ -2257,7 +2296,7 @@ pub enum SysconfVar { /// The implementation supports the Prioritized Input and Output option. _POSIX_PRIORITIZED_IO = libc::_SC_PRIORITIZED_IO, /// The implementation supports the Process Scheduling option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_PRIORITY_SCHEDULING = libc::_SC_PRIORITY_SCHEDULING, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos", @@ -2293,7 +2332,7 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SEMAPHORES = libc::_SC_SEMAPHORES, /// The implementation supports the Shared Memory Objects option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SHARED_MEMORY_OBJECTS = libc::_SC_SHARED_MEMORY_OBJECTS, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", @@ -2324,7 +2363,7 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SS_REPL_MAX = libc::_SC_SS_REPL_MAX, /// The implementation supports the Synchronized Input and Output option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SYNCHRONIZED_IO = libc::_SC_SYNCHRONIZED_IO, /// The implementation supports the Thread Stack Address Attribute option. @@ -2342,11 +2381,11 @@ pub enum SysconfVar { _POSIX_THREAD_CPUTIME = libc::_SC_THREAD_CPUTIME, /// The implementation supports the Non-Robust Mutex Priority Inheritance /// option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_PRIO_INHERIT = libc::_SC_THREAD_PRIO_INHERIT, /// The implementation supports the Non-Robust Mutex Priority Protection option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_PRIO_PROTECT = libc::_SC_THREAD_PRIO_PROTECT, /// The implementation supports the Thread Execution Scheduling option. @@ -2369,7 +2408,7 @@ pub enum SysconfVar { /// The implementation supports the Robust Mutex Priority Protection option. _POSIX_THREAD_ROBUST_PRIO_PROTECT = libc::_SC_THREAD_ROBUST_PRIO_PROTECT, /// The implementation supports thread-safe functions. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_SAFE_FUNCTIONS = libc::_SC_THREAD_SAFE_FUNCTIONS, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", @@ -2466,28 +2505,28 @@ pub enum SysconfVar { /// using at least 64 bits. _POSIX_V6_LPBIG_OFFBIG = libc::_SC_V6_LPBIG_OFFBIG, /// The implementation supports the C-Language Binding option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_C_BIND = libc::_SC_2_C_BIND, /// The implementation supports the C-Language Development Utilities option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_C_DEV = libc::_SC_2_C_DEV, /// The implementation supports the Terminal Characteristics option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_CHAR_TERM = libc::_SC_2_CHAR_TERM, /// The implementation supports the FORTRAN Development Utilities option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_FORT_DEV = libc::_SC_2_FORT_DEV, /// The implementation supports the FORTRAN Runtime Utilities option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_FORT_RUN = libc::_SC_2_FORT_RUN, /// The implementation supports the creation of locales by the localedef /// utility. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_LOCALEDEF = libc::_SC_2_LOCALEDEF, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", @@ -2528,16 +2567,16 @@ pub enum SysconfVar { /// The implementation supports the Track Batch Job Request option. _POSIX2_PBS_TRACK = libc::_SC_2_PBS_TRACK, /// The implementation supports the Software Development Utilities option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_SW_DEV = libc::_SC_2_SW_DEV, /// The implementation supports the User Portability Utilities option. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_UPE = libc::_SC_2_UPE, /// Integer value indicating version of the Shell and Utilities volume of /// POSIX.1 to which the implementation conforms. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_VERSION = libc::_SC_2_VERSION, /// The size of a system page in bytes. @@ -2545,18 +2584,19 @@ pub enum SysconfVar { /// POSIX also defines an alias named `PAGESIZE`, but Rust does not allow two /// enum constants to have the same value, so nix omits `PAGESIZE`. PAGE_SIZE = libc::_SC_PAGE_SIZE, - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_DESTRUCTOR_ITERATIONS = libc::_SC_THREAD_DESTRUCTOR_ITERATIONS, - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_KEYS_MAX = libc::_SC_THREAD_KEYS_MAX, #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_STACK_MIN = libc::_SC_THREAD_STACK_MIN, - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_THREADS_MAX = libc::_SC_THREAD_THREADS_MAX, + #[cfg(not(target_os = "haiku"))] RE_DUP_MAX = libc::_SC_RE_DUP_MAX, #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", target_os = "ios", target_os="linux", target_os = "macos", @@ -2619,7 +2659,7 @@ pub enum SysconfVar { _XOPEN_REALTIME_THREADS = libc::_SC_XOPEN_REALTIME_THREADS, /// The implementation supports the Issue 4, Version 2 Shared Memory Option /// Group. - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] _XOPEN_SHM = libc::_SC_XOPEN_SHM, #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", @@ -2640,6 +2680,19 @@ pub enum SysconfVar { /// Integer value indicating version of the X/Open Portability Guide to /// which the implementation conforms. _XOPEN_VERSION = libc::_SC_XOPEN_VERSION, + /// The number of pages of physical memory. Note that it is possible for + /// the product of this value to overflow. + #[cfg(any(target_os="android", target_os="linux"))] + _PHYS_PAGES = libc::_SC_PHYS_PAGES, + /// The number of currently available pages of physical memory. + #[cfg(any(target_os="android", target_os="linux"))] + _AVPHYS_PAGES = libc::_SC_AVPHYS_PAGES, + /// The number of processors configured. + #[cfg(any(target_os="android", target_os="linux"))] + _NPROCESSORS_CONF = libc::_SC_NPROCESSORS_CONF, + /// The number of processors currently online (available). + #[cfg(any(target_os="android", target_os="linux"))] + _NPROCESSORS_ONLN = libc::_SC_NPROCESSORS_ONLN, } /// Get configurable system variables (see @@ -2698,11 +2751,13 @@ mod pivot_root { } } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] mod setres { feature! { #![feature = "user"] @@ -2745,11 +2800,13 @@ mod setres { } } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] mod getres { feature! { #![feature = "user"] @@ -2815,7 +2872,7 @@ mod getres { } #[cfg(feature = "fs")] -libc_bitflags!{ +libc_bitflags! { /// Options for access() #[cfg_attr(docsrs, doc(cfg(feature = "fs")))] pub struct AccessFlags : c_int { @@ -2843,6 +2900,27 @@ pub fn access(path: &P, amode: AccessFlags) -> Result<()> { })?; Errno::result(res).map(drop) } + +/// Checks the file named by `path` for accessibility according to the flags given by `mode` +/// +/// If `dirfd` has a value, then `path` is relative to directory associated with the file descriptor. +/// +/// If `dirfd` is `None`, then `path` is relative to the current working directory. +/// +/// # References +/// +/// [faccessat(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/faccessat.html) +// illumos: faccessat(2) appears to be supported, but the libc crate does not provide a binding. +// redox: does not appear to support the *at family of syscalls. +#[cfg(not(any(target_os = "illumos", target_os = "redox")))] +pub fn faccessat(dirfd: Option, path: &P, mode: AccessFlags, flags: AtFlags) -> Result<()> { + let res = path.with_nix_path(|cstr| { + unsafe { + libc::faccessat(at_rawfd(dirfd), cstr.as_ptr(), mode.bits(), flags.bits()) + } + })?; + Errno::result(res).map(drop) +} } feature! { @@ -2855,11 +2933,11 @@ feature! { /// guaranteed to conform to [`NAME_REGEX`](https://serverfault.com/a/73101/407341), which only /// contains ASCII. #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq)] pub struct User { /// Username pub name: String, - /// User password (probably encrypted) + /// User password (probably hashed) pub passwd: CString, /// User ID pub uid: Uid, @@ -2875,6 +2953,7 @@ pub struct User { /// Login class #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] @@ -2883,6 +2962,7 @@ pub struct User { /// Last password change #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] @@ -2891,6 +2971,7 @@ pub struct User { /// Expiration time of account #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] @@ -2898,37 +2979,40 @@ pub struct User { pub expire: libc::time_t } -#[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd +#[cfg(not(target_os = "redox"))] //RedoxFS does not support passwd impl From<&libc::passwd> for User { fn from(pw: &libc::passwd) -> User { unsafe { User { - name: CStr::from_ptr((*pw).pw_name).to_string_lossy().into_owned(), - passwd: CString::new(CStr::from_ptr((*pw).pw_passwd).to_bytes()).unwrap(), + name: CStr::from_ptr(pw.pw_name).to_string_lossy().into_owned(), + passwd: CString::new(CStr::from_ptr(pw.pw_passwd).to_bytes()).unwrap(), #[cfg(not(all(target_os = "android", target_pointer_width = "32")))] - gecos: CString::new(CStr::from_ptr((*pw).pw_gecos).to_bytes()).unwrap(), - dir: PathBuf::from(OsStr::from_bytes(CStr::from_ptr((*pw).pw_dir).to_bytes())), - shell: PathBuf::from(OsStr::from_bytes(CStr::from_ptr((*pw).pw_shell).to_bytes())), - uid: Uid::from_raw((*pw).pw_uid), - gid: Gid::from_raw((*pw).pw_gid), + gecos: CString::new(CStr::from_ptr(pw.pw_gecos).to_bytes()).unwrap(), + dir: PathBuf::from(OsStr::from_bytes(CStr::from_ptr(pw.pw_dir).to_bytes())), + shell: PathBuf::from(OsStr::from_bytes(CStr::from_ptr(pw.pw_shell).to_bytes())), + uid: Uid::from_raw(pw.pw_uid), + gid: Gid::from_raw(pw.pw_gid), #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] - class: CString::new(CStr::from_ptr((*pw).pw_class).to_bytes()).unwrap(), + class: CString::new(CStr::from_ptr(pw.pw_class).to_bytes()).unwrap(), #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] - change: (*pw).pw_change, + change: pw.pw_change, #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] - expire: (*pw).pw_expire + expire: pw.pw_expire } } } @@ -2960,18 +3044,21 @@ impl From for libc::passwd { pw_gid: u.gid.0, #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] pw_class: u.class.into_raw(), #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] pw_change: u.change, #[cfg(not(any(target_os = "android", target_os = "fuchsia", + target_os = "haiku", target_os = "illumos", target_os = "linux", target_os = "solaris")))] @@ -3034,7 +3121,7 @@ impl User { /// use nix::unistd::{Uid, User}; /// // Returns an Result>, thus the double unwrap. /// let res = User::from_uid(Uid::from_raw(0)).unwrap().unwrap(); - /// assert!(res.name == "root"); + /// assert_eq!(res.name, "root"); /// ``` pub fn from_uid(uid: Uid) -> Result> { User::from_anything(|pwd, cbuf, cap, res| { @@ -3053,7 +3140,7 @@ impl User { /// use nix::unistd::User; /// // Returns an Result>, thus the double unwrap. /// let res = User::from_name("root").unwrap().unwrap(); - /// assert!(res.name == "root"); + /// assert_eq!(res.name, "root"); /// ``` pub fn from_name(name: &str) -> Result> { let name = CString::new(name).unwrap(); @@ -3065,7 +3152,7 @@ impl User { /// Representation of a Group, based on `libc::group` #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq)] pub struct Group { /// Group name pub name: String, @@ -3082,10 +3169,10 @@ impl From<&libc::group> for Group { fn from(gr: &libc::group) -> Group { unsafe { Group { - name: CStr::from_ptr((*gr).gr_name).to_string_lossy().into_owned(), - passwd: CString::new(CStr::from_ptr((*gr).gr_passwd).to_bytes()).unwrap(), - gid: Gid::from_raw((*gr).gr_gid), - mem: Group::members((*gr).gr_mem) + name: CStr::from_ptr(gr.gr_name).to_string_lossy().into_owned(), + passwd: CString::new(CStr::from_ptr(gr.gr_passwd).to_bytes()).unwrap(), + gid: Gid::from_raw(gr.gr_gid), + mem: Group::members(gr.gr_mem) } } } @@ -3234,3 +3321,26 @@ pub fn getpeereid(fd: RawFd) -> Result<(Uid, Gid)> { Errno::result(ret).map(|_| (Uid(uid), Gid(gid))) } } + +feature! { +#![all(feature = "fs")] + +/// Set the file flags. +/// +/// See also [chflags(2)](https://www.freebsd.org/cgi/man.cgi?query=chflags&sektion=2) +#[cfg(any( + target_os = "openbsd", + target_os = "netbsd", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "macos", + target_os = "ios" +))] +pub fn chflags(path: &P, flags: FileFlag) -> Result<()> { + let res = path.with_nix_path(|cstr| unsafe { + libc::chflags(cstr.as_ptr(), flags.bits()) + })?; + + Errno::result(res).map(drop) +} +} diff --git a/bash-5.1/vendor/nix/test/common/mod.rs b/bash-5.1/vendor/nix/test/common/mod.rs index 544a1ae..bb056aa 100644 --- a/bash-5.1/vendor/nix/test/common/mod.rs +++ b/bash-5.1/vendor/nix/test/common/mod.rs @@ -1,6 +1,7 @@ use cfg_if::cfg_if; -#[macro_export] macro_rules! skip { +#[macro_export] +macro_rules! skip { ($($reason: expr),+) => { use ::std::io::{self, Write}; @@ -33,42 +34,49 @@ cfg_if! { /// Skip the test if we don't have the ability to mount file systems. #[cfg(target_os = "freebsd")] -#[macro_export] macro_rules! require_mount { +#[macro_export] +macro_rules! require_mount { ($name:expr) => { - use ::sysctl::CtlValue; + use ::sysctl::{CtlValue, Sysctl}; use nix::unistd::Uid; - if !Uid::current().is_root() && CtlValue::Int(0) == ::sysctl::value("vfs.usermount").unwrap() + let ctl = ::sysctl::Ctl::new("vfs.usermount").unwrap(); + if !Uid::current().is_root() && CtlValue::Int(0) == ctl.value().unwrap() { - skip!("{} requires the ability to mount file systems. Skipping test.", $name); + skip!( + "{} requires the ability to mount file systems. Skipping test.", + $name + ); } - } + }; } -#[cfg(any(target_os = "linux", target_os= "android"))] -#[macro_export] macro_rules! skip_if_cirrus { +#[cfg(any(target_os = "linux", target_os = "android"))] +#[macro_export] +macro_rules! skip_if_cirrus { ($reason:expr) => { if std::env::var_os("CIRRUS_CI").is_some() { skip!("{}", $reason); } - } + }; } #[cfg(target_os = "freebsd")] -#[macro_export] macro_rules! skip_if_jailed { +#[macro_export] +macro_rules! skip_if_jailed { ($name:expr) => { - use ::sysctl::CtlValue; + use ::sysctl::{CtlValue, Sysctl}; - if let CtlValue::Int(1) = ::sysctl::value("security.jail.jailed") - .unwrap() - { + let ctl = ::sysctl::Ctl::new("security.jail.jailed").unwrap(); + if let CtlValue::Int(1) = ctl.value().unwrap() { skip!("{} cannot run in a jail. Skipping test.", $name); } - } + }; } #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] -#[macro_export] macro_rules! skip_if_not_root { +#[macro_export] +macro_rules! skip_if_not_root { ($name:expr) => { use nix::unistd::Uid; diff --git a/bash-5.1/vendor/nix/test/sys/mod.rs b/bash-5.1/vendor/nix/test/sys/mod.rs index 91c0aae..2031212 100644 --- a/bash-5.1/vendor/nix/test/sys/mod.rs +++ b/bash-5.1/vendor/nix/test/sys/mod.rs @@ -5,43 +5,56 @@ mod test_signal; // works or not heavily depends on which pthread implementation is chosen // by the user at link time. For this reason we do not want to run aio test // cases on DragonFly. -#[cfg(any(target_os = "freebsd", - target_os = "ios", - all(target_os = "linux", not(target_env = "uclibc")), - target_os = "macos", - target_os = "netbsd"))] +#[cfg(any( + target_os = "freebsd", + target_os = "ios", + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + target_os = "netbsd" +))] mod test_aio; +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] +mod test_ioctl; #[cfg(not(target_os = "redox"))] mod test_mman; +#[cfg(not(target_os = "redox"))] +mod test_select; #[cfg(target_os = "linux")] mod test_signalfd; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] mod test_socket; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox")))] mod test_sockopt; -#[cfg(not(target_os = "redox"))] -mod test_select; +mod test_stat; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_sysinfo; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] mod test_termios; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] -mod test_ioctl; -mod test_wait; mod test_uio; +mod test_wait; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_epoll; #[cfg(target_os = "linux")] mod test_inotify; mod test_pthread; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] mod test_ptrace; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_timerfd; diff --git a/bash-5.1/vendor/nix/test/sys/test_aio.rs b/bash-5.1/vendor/nix/test/sys/test_aio.rs index 80cd053..6a36f3e 100644 --- a/bash-5.1/vendor/nix/test/sys/test_aio.rs +++ b/bash-5.1/vendor/nix/test/sys/test_aio.rs @@ -1,415 +1,516 @@ -use libc::{c_int, c_void}; -use nix::Result; -use nix::errno::*; -use nix::sys::aio::*; -use nix::sys::signal::{SaFlags, SigAction, sigaction, SigevNotify, SigHandler, Signal, SigSet}; -use nix::sys::time::{TimeSpec, TimeValLike}; -use std::io::{Write, Read, Seek, SeekFrom}; -use std::ops::Deref; -use std::os::unix::io::AsRawFd; -use std::pin::Pin; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::{thread, time}; +use std::{ + io::{Read, Seek, SeekFrom, Write}, + ops::Deref, + os::unix::io::AsRawFd, + pin::Pin, + sync::atomic::{AtomicBool, Ordering}, + thread, time, +}; + +use libc::c_int; +use nix::{ + errno::*, + sys::{ + aio::*, + signal::{ + sigaction, SaFlags, SigAction, SigHandler, SigSet, SigevNotify, + Signal, + }, + time::{TimeSpec, TimeValLike}, + }, +}; use tempfile::tempfile; -// Helper that polls an AioCb for completion or error -fn poll_aio(aiocb: &mut Pin>) -> Result<()> { - loop { - let err = aiocb.error(); - if err != Err(Errno::EINPROGRESS) { return err; }; - thread::sleep(time::Duration::from_millis(10)); - } +lazy_static! { + pub static ref SIGNALED: AtomicBool = AtomicBool::new(false); } -// Helper that polls a component of an LioCb for completion or error -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -fn poll_lio(liocb: &mut LioCb, i: usize) -> Result<()> { - loop { - let err = liocb.error(i); - if err != Err(Errno::EINPROGRESS) { return err; }; - thread::sleep(time::Duration::from_millis(10)); - } +extern "C" fn sigfunc(_: c_int) { + SIGNALED.store(true, Ordering::Relaxed); } -#[test] -fn test_accessors() { - let mut rbuf = vec![0; 4]; - let aiocb = AioCb::from_mut_slice( 1001, - 2, //offset - &mut rbuf, - 42, //priority - SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, - si_value: 99 - }, - LioOpcode::LIO_NOP); - assert_eq!(1001, aiocb.fd()); - assert_eq!(Some(LioOpcode::LIO_NOP), aiocb.lio_opcode()); - assert_eq!(4, aiocb.nbytes()); - assert_eq!(2, aiocb.offset()); - assert_eq!(42, aiocb.priority()); - let sev = aiocb.sigevent().sigevent(); - assert_eq!(Signal::SIGUSR2 as i32, sev.sigev_signo); - assert_eq!(99, sev.sigev_value.sival_ptr as i64); +// Helper that polls an AioCb for completion or error +macro_rules! poll_aio { + ($aiocb: expr) => { + loop { + let err = $aiocb.as_mut().error(); + if err != Err(Errno::EINPROGRESS) { + break err; + }; + thread::sleep(time::Duration::from_millis(10)); + } + }; } -// Tests AioCb.cancel. We aren't trying to test the OS's implementation, only -// our bindings. So it's sufficient to check that AioCb.cancel returned any -// AioCancelStat value. -#[test] -#[cfg_attr(target_env = "musl", ignore)] -fn test_cancel() { - let wbuf: &[u8] = b"CDEF"; - - let f = tempfile().unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 0, //offset - wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.write().unwrap(); - let err = aiocb.error(); - assert!(err == Ok(()) || err == Err(Errno::EINPROGRESS)); +mod aio_fsync { + use super::*; + + #[test] + fn test_accessors() { + let aiocb = AioFsync::new( + 1001, + AioFsyncMode::O_SYNC, + 42, + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 99, + }, + ); + assert_eq!(1001, aiocb.fd()); + assert_eq!(AioFsyncMode::O_SYNC, aiocb.mode()); + assert_eq!(42, aiocb.priority()); + let sev = aiocb.sigevent().sigevent(); + assert_eq!(Signal::SIGUSR2 as i32, sev.sigev_signo); + assert_eq!(99, sev.sigev_value.sival_ptr as i64); + } - let cancelstat = aiocb.cancel(); - assert!(cancelstat.is_ok()); + /// `AioFsync::submit` should not modify the `AioCb` object if + /// `libc::aio_fsync` returns an error + // Skip on Linux, because Linux's AIO implementation can't detect errors + // synchronously + #[test] + #[cfg(any(target_os = "freebsd", target_os = "macos"))] + fn error() { + use std::mem; + + const INITIAL: &[u8] = b"abcdef123456"; + // Create an invalid AioFsyncMode + let mode = unsafe { mem::transmute(666) }; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let mut aiof = Box::pin(AioFsync::new( + f.as_raw_fd(), + mode, + 0, + SigevNotify::SigevNone, + )); + let err = aiof.as_mut().submit(); + err.expect_err("assertion failed"); + } - // Wait for aiocb to complete, but don't care whether it succeeded - let _ = poll_aio(&mut aiocb); - let _ = aiocb.aio_return(); + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn ok() { + const INITIAL: &[u8] = b"abcdef123456"; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let fd = f.as_raw_fd(); + let mut aiof = Box::pin(AioFsync::new( + fd, + AioFsyncMode::O_SYNC, + 0, + SigevNotify::SigevNone, + )); + aiof.as_mut().submit().unwrap(); + poll_aio!(&mut aiof).unwrap(); + aiof.as_mut().aio_return().unwrap(); + } } -// Tests using aio_cancel_all for all outstanding IOs. -#[test] -#[cfg_attr(target_env = "musl", ignore)] -fn test_aio_cancel_all() { - let wbuf: &[u8] = b"CDEF"; - - let f = tempfile().unwrap(); - let mut aiocb = AioCb::from_slice(f.as_raw_fd(), - 0, //offset - wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.write().unwrap(); - let err = aiocb.error(); - assert!(err == Ok(()) || err == Err(Errno::EINPROGRESS)); +mod aio_read { + use super::*; + + #[test] + fn test_accessors() { + let mut rbuf = vec![0; 4]; + let aiocb = AioRead::new( + 1001, + 2, //offset + &mut rbuf, + 42, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 99, + }, + ); + assert_eq!(1001, aiocb.fd()); + assert_eq!(4, aiocb.nbytes()); + assert_eq!(2, aiocb.offset()); + assert_eq!(42, aiocb.priority()); + let sev = aiocb.sigevent().sigevent(); + assert_eq!(Signal::SIGUSR2 as i32, sev.sigev_signo); + assert_eq!(99, sev.sigev_value.sival_ptr as i64); + } - let cancelstat = aio_cancel_all(f.as_raw_fd()); - assert!(cancelstat.is_ok()); + // Tests AioWrite.cancel. We aren't trying to test the OS's implementation, + // only our bindings. So it's sufficient to check that cancel + // returned any AioCancelStat value. + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn cancel() { + const INITIAL: &[u8] = b"abcdef123456"; + let mut rbuf = vec![0; 4]; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let fd = f.as_raw_fd(); + let mut aior = + Box::pin(AioRead::new(fd, 2, &mut rbuf, 0, SigevNotify::SigevNone)); + aior.as_mut().submit().unwrap(); + + aior.as_mut().cancel().unwrap(); + + // Wait for aiow to complete, but don't care whether it succeeded + let _ = poll_aio!(&mut aior); + let _ = aior.as_mut().aio_return(); + } - // Wait for aiocb to complete, but don't care whether it succeeded - let _ = poll_aio(&mut aiocb); - let _ = aiocb.aio_return(); -} + /// `AioRead::submit` should not modify the `AioCb` object if + /// `libc::aio_read` returns an error + // Skip on Linux, because Linux's AIO implementation can't detect errors + // synchronously + #[test] + #[cfg(any(target_os = "freebsd", target_os = "macos"))] + fn error() { + const INITIAL: &[u8] = b"abcdef123456"; + let mut rbuf = vec![0; 4]; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let mut aior = Box::pin(AioRead::new( + f.as_raw_fd(), + -1, //an invalid offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + )); + aior.as_mut().submit().expect_err("assertion failed"); + } -#[test] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_fsync() { - const INITIAL: &[u8] = b"abcdef123456"; - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_fd( f.as_raw_fd(), - 0, //priority - SigevNotify::SigevNone); - let err = aiocb.fsync(AioFsyncMode::O_SYNC); - assert!(err.is_ok()); - poll_aio(&mut aiocb).unwrap(); - aiocb.aio_return().unwrap(); -} + // Test a simple aio operation with no completion notification. We must + // poll for completion + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn ok() { + const INITIAL: &[u8] = b"abcdef123456"; + let mut rbuf = vec![0; 4]; + const EXPECT: &[u8] = b"cdef"; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + { + let fd = f.as_raw_fd(); + let mut aior = Box::pin(AioRead::new( + fd, + 2, + &mut rbuf, + 0, + SigevNotify::SigevNone, + )); + aior.as_mut().submit().unwrap(); -/// `AioCb::fsync` should not modify the `AioCb` object if `libc::aio_fsync` returns -/// an error -// Skip on Linux, because Linux's AIO implementation can't detect errors -// synchronously -#[test] -#[cfg(any(target_os = "freebsd", target_os = "macos"))] -fn test_fsync_error() { - use std::mem; + let err = poll_aio!(&mut aior); + assert_eq!(err, Ok(())); + assert_eq!(aior.as_mut().aio_return().unwrap(), EXPECT.len()); + } + assert_eq!(EXPECT, rbuf.deref().deref()); + } - const INITIAL: &[u8] = b"abcdef123456"; - // Create an invalid AioFsyncMode - let mode = unsafe { mem::transmute(666) }; - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_fd( f.as_raw_fd(), - 0, //priority - SigevNotify::SigevNone); - let err = aiocb.fsync(mode); - assert!(err.is_err()); + // Like ok, but allocates the structure on the stack. + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn on_stack() { + const INITIAL: &[u8] = b"abcdef123456"; + let mut rbuf = vec![0; 4]; + const EXPECT: &[u8] = b"cdef"; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + { + let fd = f.as_raw_fd(); + let mut aior = + AioRead::new(fd, 2, &mut rbuf, 0, SigevNotify::SigevNone); + let mut aior = unsafe { Pin::new_unchecked(&mut aior) }; + aior.as_mut().submit().unwrap(); + + let err = poll_aio!(&mut aior); + assert_eq!(err, Ok(())); + assert_eq!(aior.as_mut().aio_return().unwrap(), EXPECT.len()); + } + assert_eq!(EXPECT, rbuf.deref().deref()); + } } -#[test] -// On Cirrus on Linux, this test fails due to a glibc bug. -// https://github.com/nix-rust/nix/issues/1099 -#[cfg_attr(target_os = "linux", ignore)] -// On Cirrus, aio_suspend is failing with EINVAL -// https://github.com/nix-rust/nix/issues/1361 -#[cfg_attr(target_os = "macos", ignore)] -fn test_aio_suspend() { - const INITIAL: &[u8] = b"abcdef123456"; - const WBUF: &[u8] = b"CDEFG"; - let timeout = TimeSpec::seconds(10); - let mut rbuf = vec![0; 4]; - let rlen = rbuf.len(); - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); +#[cfg(target_os = "freebsd")] +#[cfg(fbsd14)] +mod aio_readv { + use std::io::IoSliceMut; + + use super::*; + + #[test] + fn test_accessors() { + let mut rbuf0 = vec![0; 4]; + let mut rbuf1 = vec![0; 8]; + let mut rbufs = + [IoSliceMut::new(&mut rbuf0), IoSliceMut::new(&mut rbuf1)]; + let aiocb = AioReadv::new( + 1001, + 2, //offset + &mut rbufs, + 42, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 99, + }, + ); + assert_eq!(1001, aiocb.fd()); + assert_eq!(2, aiocb.iovlen()); + assert_eq!(2, aiocb.offset()); + assert_eq!(42, aiocb.priority()); + let sev = aiocb.sigevent().sigevent(); + assert_eq!(Signal::SIGUSR2 as i32, sev.sigev_signo); + assert_eq!(99, sev.sigev_value.sival_ptr as i64); + } - let mut wcb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE); - - let mut rcb = AioCb::from_mut_slice( f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ); - wcb.write().unwrap(); - rcb.read().unwrap(); - loop { + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn ok() { + const INITIAL: &[u8] = b"abcdef123456"; + let mut rbuf0 = vec![0; 4]; + let mut rbuf1 = vec![0; 2]; + let mut rbufs = + [IoSliceMut::new(&mut rbuf0), IoSliceMut::new(&mut rbuf1)]; + const EXPECT0: &[u8] = b"cdef"; + const EXPECT1: &[u8] = b"12"; + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); { - let cbbuf = [wcb.as_ref(), rcb.as_ref()]; - let r = aio_suspend(&cbbuf[..], Some(timeout)); - match r { - Err(Errno::EINTR) => continue, - Err(e) => panic!("aio_suspend returned {:?}", e), - Ok(_) => () - }; - } - if rcb.error() != Err(Errno::EINPROGRESS) && - wcb.error() != Err(Errno::EINPROGRESS) { - break + let fd = f.as_raw_fd(); + let mut aior = Box::pin(AioReadv::new( + fd, + 2, + &mut rbufs, + 0, + SigevNotify::SigevNone, + )); + aior.as_mut().submit().unwrap(); + + let err = poll_aio!(&mut aior); + assert_eq!(err, Ok(())); + assert_eq!( + aior.as_mut().aio_return().unwrap(), + EXPECT0.len() + EXPECT1.len() + ); } + assert_eq!(&EXPECT0, &rbuf0); + assert_eq!(&EXPECT1, &rbuf1); } - - assert_eq!(wcb.aio_return().unwrap() as usize, WBUF.len()); - assert_eq!(rcb.aio_return().unwrap() as usize, rlen); } -// Test a simple aio operation with no completion notification. We must poll -// for completion -#[test] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_read() { - const INITIAL: &[u8] = b"abcdef123456"; - let mut rbuf = vec![0; 4]; - const EXPECT: &[u8] = b"cdef"; - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - { - let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - 2, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.read().unwrap(); - - let err = poll_aio(&mut aiocb); - assert_eq!(err, Ok(())); - assert_eq!(aiocb.aio_return().unwrap() as usize, EXPECT.len()); +mod aio_write { + use super::*; + + #[test] + fn test_accessors() { + let wbuf = vec![0; 4]; + let aiocb = AioWrite::new( + 1001, + 2, //offset + &wbuf, + 42, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 99, + }, + ); + assert_eq!(1001, aiocb.fd()); + assert_eq!(4, aiocb.nbytes()); + assert_eq!(2, aiocb.offset()); + assert_eq!(42, aiocb.priority()); + let sev = aiocb.sigevent().sigevent(); + assert_eq!(Signal::SIGUSR2 as i32, sev.sigev_signo); + assert_eq!(99, sev.sigev_value.sival_ptr as i64); } - assert_eq!(EXPECT, rbuf.deref().deref()); -} + // Tests AioWrite.cancel. We aren't trying to test the OS's implementation, + // only our bindings. So it's sufficient to check that cancel + // returned any AioCancelStat value. + #[test] + #[cfg_attr(target_env = "musl", ignore)] + fn cancel() { + let wbuf: &[u8] = b"CDEF"; -/// `AioCb::read` should not modify the `AioCb` object if `libc::aio_read` -/// returns an error -// Skip on Linux, because Linux's AIO implementation can't detect errors -// synchronously -#[test] -#[cfg(any(target_os = "freebsd", target_os = "macos"))] -fn test_read_error() { - const INITIAL: &[u8] = b"abcdef123456"; - let mut rbuf = vec![0; 4]; - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - -1, //an invalid offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - assert!(aiocb.read().is_err()); -} + let f = tempfile().unwrap(); + let mut aiow = Box::pin(AioWrite::new( + f.as_raw_fd(), + 0, + wbuf, + 0, + SigevNotify::SigevNone, + )); + aiow.as_mut().submit().unwrap(); + let err = aiow.as_mut().error(); + assert!(err == Ok(()) || err == Err(Errno::EINPROGRESS)); -// Tests from_mut_slice -#[test] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_read_into_mut_slice() { - const INITIAL: &[u8] = b"abcdef123456"; - let mut rbuf = vec![0; 4]; - const EXPECT: &[u8] = b"cdef"; - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - { - let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - 2, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.read().unwrap(); - - let err = poll_aio(&mut aiocb); - assert_eq!(err, Ok(())); - assert_eq!(aiocb.aio_return().unwrap() as usize, EXPECT.len()); + aiow.as_mut().cancel().unwrap(); + + // Wait for aiow to complete, but don't care whether it succeeded + let _ = poll_aio!(&mut aiow); + let _ = aiow.as_mut().aio_return(); } - assert_eq!(rbuf, EXPECT); -} + // Test a simple aio operation with no completion notification. We must + // poll for completion. + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn ok() { + const INITIAL: &[u8] = b"abcdef123456"; + let wbuf = "CDEF".to_string().into_bytes(); + let mut rbuf = Vec::new(); + const EXPECT: &[u8] = b"abCDEF123456"; + + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let mut aiow = Box::pin(AioWrite::new( + f.as_raw_fd(), + 2, + &wbuf, + 0, + SigevNotify::SigevNone, + )); + aiow.as_mut().submit().unwrap(); -// Tests from_ptr -#[test] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_read_into_pointer() { - const INITIAL: &[u8] = b"abcdef123456"; - let mut rbuf = vec![0; 4]; - const EXPECT: &[u8] = b"cdef"; - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - { - // Safety: ok because rbuf lives until after poll_aio - let mut aiocb = unsafe { - AioCb::from_mut_ptr( f.as_raw_fd(), - 2, //offset - rbuf.as_mut_ptr() as *mut c_void, - rbuf.len(), - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP) - }; - aiocb.read().unwrap(); - - let err = poll_aio(&mut aiocb); + let err = poll_aio!(&mut aiow); assert_eq!(err, Ok(())); - assert_eq!(aiocb.aio_return().unwrap() as usize, EXPECT.len()); - } + assert_eq!(aiow.as_mut().aio_return().unwrap(), wbuf.len()); - assert_eq!(rbuf, EXPECT); -} - -// Test reading into an immutable buffer. It should fail -// FIXME: This test fails to panic on Linux/musl -#[test] -#[should_panic(expected = "Can't read into an immutable buffer")] -#[cfg_attr(target_env = "musl", ignore)] -fn test_read_immutable_buffer() { - let rbuf: &[u8] = b"CDEF"; - let f = tempfile().unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.read().unwrap(); -} + f.seek(SeekFrom::Start(0)).unwrap(); + let len = f.read_to_end(&mut rbuf).unwrap(); + assert_eq!(len, EXPECT.len()); + assert_eq!(rbuf, EXPECT); + } + // Like ok, but allocates the structure on the stack. + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn on_stack() { + const INITIAL: &[u8] = b"abcdef123456"; + let wbuf = "CDEF".to_string().into_bytes(); + let mut rbuf = Vec::new(); + const EXPECT: &[u8] = b"abCDEF123456"; + + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let mut aiow = AioWrite::new( + f.as_raw_fd(), + 2, //offset + &wbuf, + 0, //priority + SigevNotify::SigevNone, + ); + let mut aiow = unsafe { Pin::new_unchecked(&mut aiow) }; + aiow.as_mut().submit().unwrap(); -// Test a simple aio operation with no completion notification. We must poll -// for completion. Unlike test_aio_read, this test uses AioCb::from_slice -#[test] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_write() { - const INITIAL: &[u8] = b"abcdef123456"; - let wbuf = "CDEF".to_string().into_bytes(); - let mut rbuf = Vec::new(); - const EXPECT: &[u8] = b"abCDEF123456"; + let err = poll_aio!(&mut aiow); + assert_eq!(err, Ok(())); + assert_eq!(aiow.as_mut().aio_return().unwrap(), wbuf.len()); - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - &wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.write().unwrap(); - - let err = poll_aio(&mut aiocb); - assert_eq!(err, Ok(())); - assert_eq!(aiocb.aio_return().unwrap() as usize, wbuf.len()); + f.seek(SeekFrom::Start(0)).unwrap(); + let len = f.read_to_end(&mut rbuf).unwrap(); + assert_eq!(len, EXPECT.len()); + assert_eq!(rbuf, EXPECT); + } - f.seek(SeekFrom::Start(0)).unwrap(); - let len = f.read_to_end(&mut rbuf).unwrap(); - assert_eq!(len, EXPECT.len()); - assert_eq!(rbuf, EXPECT); + /// `AioWrite::write` should not modify the `AioCb` object if + /// `libc::aio_write` returns an error. + // Skip on Linux, because Linux's AIO implementation can't detect errors + // synchronously + #[test] + #[cfg(any(target_os = "freebsd", target_os = "macos"))] + fn error() { + let wbuf = "CDEF".to_string().into_bytes(); + let mut aiow = Box::pin(AioWrite::new( + 666, // An invalid file descriptor + 0, //offset + &wbuf, + 0, //priority + SigevNotify::SigevNone, + )); + aiow.as_mut().submit().expect_err("assertion failed"); + // Dropping the AioWrite at this point should not panic + } } -// Tests `AioCb::from_ptr` -#[test] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_write_from_pointer() { - const INITIAL: &[u8] = b"abcdef123456"; - let wbuf = "CDEF".to_string().into_bytes(); - let mut rbuf = Vec::new(); - const EXPECT: &[u8] = b"abCDEF123456"; - - let mut f = tempfile().unwrap(); - f.write_all(INITIAL).unwrap(); - // Safety: ok because aiocb outlives poll_aio - let mut aiocb = unsafe { - AioCb::from_ptr( f.as_raw_fd(), - 2, //offset - wbuf.as_ptr() as *const c_void, - wbuf.len(), - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP) - }; - aiocb.write().unwrap(); - - let err = poll_aio(&mut aiocb); - assert_eq!(err, Ok(())); - assert_eq!(aiocb.aio_return().unwrap() as usize, wbuf.len()); - - f.seek(SeekFrom::Start(0)).unwrap(); - let len = f.read_to_end(&mut rbuf).unwrap(); - assert_eq!(len, EXPECT.len()); - assert_eq!(rbuf, EXPECT); -} +#[cfg(target_os = "freebsd")] +#[cfg(fbsd14)] +mod aio_writev { + use std::io::IoSlice; + + use super::*; + + #[test] + fn test_accessors() { + let wbuf0 = vec![0; 4]; + let wbuf1 = vec![0; 8]; + let wbufs = [IoSlice::new(&wbuf0), IoSlice::new(&wbuf1)]; + let aiocb = AioWritev::new( + 1001, + 2, //offset + &wbufs, + 42, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 99, + }, + ); + assert_eq!(1001, aiocb.fd()); + assert_eq!(2, aiocb.iovlen()); + assert_eq!(2, aiocb.offset()); + assert_eq!(42, aiocb.priority()); + let sev = aiocb.sigevent().sigevent(); + assert_eq!(Signal::SIGUSR2 as i32, sev.sigev_signo); + assert_eq!(99, sev.sigev_value.sival_ptr as i64); + } -/// `AioCb::write` should not modify the `AioCb` object if `libc::aio_write` -/// returns an error -// Skip on Linux, because Linux's AIO implementation can't detect errors -// synchronously -#[test] -#[cfg(any(target_os = "freebsd", target_os = "macos"))] -fn test_write_error() { - let wbuf = "CDEF".to_string().into_bytes(); - let mut aiocb = AioCb::from_slice( 666, // An invalid file descriptor - 0, //offset - &wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - assert!(aiocb.write().is_err()); -} + // Test a simple aio operation with no completion notification. We must + // poll for completion. + #[test] + #[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] + fn ok() { + const INITIAL: &[u8] = b"abcdef123456"; + let wbuf0 = b"BC"; + let wbuf1 = b"DEF"; + let wbufs = [IoSlice::new(wbuf0), IoSlice::new(wbuf1)]; + let wlen = wbuf0.len() + wbuf1.len(); + let mut rbuf = Vec::new(); + const EXPECT: &[u8] = b"aBCDEF123456"; + + let mut f = tempfile().unwrap(); + f.write_all(INITIAL).unwrap(); + let mut aiow = Box::pin(AioWritev::new( + f.as_raw_fd(), + 1, + &wbufs, + 0, + SigevNotify::SigevNone, + )); + aiow.as_mut().submit().unwrap(); -lazy_static! { - pub static ref SIGNALED: AtomicBool = AtomicBool::new(false); -} + let err = poll_aio!(&mut aiow); + assert_eq!(err, Ok(())); + assert_eq!(aiow.as_mut().aio_return().unwrap(), wlen); -extern fn sigfunc(_: c_int) { - SIGNALED.store(true, Ordering::Relaxed); + f.seek(SeekFrom::Start(0)).unwrap(); + let len = f.read_to_end(&mut rbuf).unwrap(); + assert_eq!(len, EXPECT.len()); + assert_eq!(rbuf, EXPECT); + } } // Test an aio operation with completion delivered by a signal -// FIXME: This test is ignored on mips because of failures in qemu in CI #[test] -#[cfg_attr(any(all(target_env = "musl", target_arch = "x86_64"), target_arch = "mips", target_arch = "mips64"), ignore)] -fn test_write_sigev_signal() { +#[cfg_attr( + any( + all(target_env = "musl", target_arch = "x86_64"), + target_arch = "mips", + target_arch = "mips64" + ), + ignore +)] +fn sigev_signal() { let _m = crate::SIGNAL_MTX.lock(); - let sa = SigAction::new(SigHandler::Handler(sigfunc), - SaFlags::SA_RESETHAND, - SigSet::empty()); + let sa = SigAction::new( + SigHandler::Handler(sigfunc), + SaFlags::SA_RESETHAND, + SigSet::empty(), + ); SIGNALED.store(false, Ordering::Relaxed); unsafe { sigaction(Signal::SIGUSR2, &sa) }.unwrap(); @@ -420,201 +521,106 @@ fn test_write_sigev_signal() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, - si_value: 0 //TODO: validate in sigfunc - }, - LioOpcode::LIO_NOP); - aiocb.write().unwrap(); + let mut aiow = Box::pin(AioWrite::new( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 0, //TODO: validate in sigfunc + }, + )); + aiow.as_mut().submit().unwrap(); while !SIGNALED.load(Ordering::Relaxed) { thread::sleep(time::Duration::from_millis(10)); } - assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len()); + assert_eq!(aiow.as_mut().aio_return().unwrap(), WBUF.len()); f.seek(SeekFrom::Start(0)).unwrap(); let len = f.read_to_end(&mut rbuf).unwrap(); assert_eq!(len, EXPECT.len()); assert_eq!(rbuf, EXPECT); } -// Test LioCb::listio with LIO_WAIT, so all AIO ops should be complete by the -// time listio returns. -#[test] -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_liocb_listio_wait() { - const INITIAL: &[u8] = b"abcdef123456"; - const WBUF: &[u8] = b"CDEF"; - let mut rbuf = vec![0; 4]; - let rlen = rbuf.len(); - let mut rbuf2 = Vec::new(); - const EXPECT: &[u8] = b"abCDEF123456"; - let mut f = tempfile().unwrap(); - - f.write_all(INITIAL).unwrap(); - - { - let mut liocb = LioCbBuilder::with_capacity(2) - .emplace_slice( - f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE - ).emplace_mut_slice( - f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ - ).finish(); - let err = liocb.listio(LioMode::LIO_WAIT, SigevNotify::SigevNone); - err.expect("lio_listio"); - - assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len()); - assert_eq!(liocb.aio_return(1).unwrap() as usize, rlen); - } - assert_eq!(rbuf.deref().deref(), b"3456"); - - f.seek(SeekFrom::Start(0)).unwrap(); - let len = f.read_to_end(&mut rbuf2).unwrap(); - assert_eq!(len, EXPECT.len()); - assert_eq!(rbuf2, EXPECT); -} - -// Test LioCb::listio with LIO_NOWAIT and no SigEvent, so we must use some other -// mechanism to check for the individual AioCb's completion. +// Tests using aio_cancel_all for all outstanding IOs. #[test] -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(all(target_env = "musl", target_arch = "x86_64"), ignore)] -fn test_liocb_listio_nowait() { - const INITIAL: &[u8] = b"abcdef123456"; - const WBUF: &[u8] = b"CDEF"; - let mut rbuf = vec![0; 4]; - let rlen = rbuf.len(); - let mut rbuf2 = Vec::new(); - const EXPECT: &[u8] = b"abCDEF123456"; - let mut f = tempfile().unwrap(); +#[cfg_attr(target_env = "musl", ignore)] +fn test_aio_cancel_all() { + let wbuf: &[u8] = b"CDEF"; - f.write_all(INITIAL).unwrap(); + let f = tempfile().unwrap(); + let mut aiocb = Box::pin(AioWrite::new( + f.as_raw_fd(), + 0, //offset + wbuf, + 0, //priority + SigevNotify::SigevNone, + )); + aiocb.as_mut().submit().unwrap(); + let err = aiocb.as_mut().error(); + assert!(err == Ok(()) || err == Err(Errno::EINPROGRESS)); - { - let mut liocb = LioCbBuilder::with_capacity(2) - .emplace_slice( - f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE - ).emplace_mut_slice( - f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ - ).finish(); - let err = liocb.listio(LioMode::LIO_NOWAIT, SigevNotify::SigevNone); - err.expect("lio_listio"); - - poll_lio(&mut liocb, 0).unwrap(); - poll_lio(&mut liocb, 1).unwrap(); - assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len()); - assert_eq!(liocb.aio_return(1).unwrap() as usize, rlen); - } - assert_eq!(rbuf.deref().deref(), b"3456"); + aio_cancel_all(f.as_raw_fd()).unwrap(); - f.seek(SeekFrom::Start(0)).unwrap(); - let len = f.read_to_end(&mut rbuf2).unwrap(); - assert_eq!(len, EXPECT.len()); - assert_eq!(rbuf2, EXPECT); + // Wait for aiocb to complete, but don't care whether it succeeded + let _ = poll_aio!(&mut aiocb); + let _ = aiocb.as_mut().aio_return(); } -// Test LioCb::listio with LIO_NOWAIT and a SigEvent to indicate when all -// AioCb's are complete. -// FIXME: This test is ignored on mips/mips64 because of failures in qemu in CI. #[test] -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[cfg_attr(any(target_arch = "mips", target_arch = "mips64", target_env = "musl"), ignore)] -fn test_liocb_listio_signal() { - let _m = crate::SIGNAL_MTX.lock(); +// On Cirrus on Linux, this test fails due to a glibc bug. +// https://github.com/nix-rust/nix/issues/1099 +#[cfg_attr(target_os = "linux", ignore)] +// On Cirrus, aio_suspend is failing with EINVAL +// https://github.com/nix-rust/nix/issues/1361 +#[cfg_attr(target_os = "macos", ignore)] +fn test_aio_suspend() { const INITIAL: &[u8] = b"abcdef123456"; - const WBUF: &[u8] = b"CDEF"; + const WBUF: &[u8] = b"CDEFG"; + let timeout = TimeSpec::seconds(10); let mut rbuf = vec![0; 4]; let rlen = rbuf.len(); - let mut rbuf2 = Vec::new(); - const EXPECT: &[u8] = b"abCDEF123456"; let mut f = tempfile().unwrap(); - let sa = SigAction::new(SigHandler::Handler(sigfunc), - SaFlags::SA_RESETHAND, - SigSet::empty()); - let sigev_notify = SigevNotify::SigevSignal { signal: Signal::SIGUSR2, - si_value: 0 }; - f.write_all(INITIAL).unwrap(); - { - let mut liocb = LioCbBuilder::with_capacity(2) - .emplace_slice( - f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE - ).emplace_mut_slice( - f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ - ).finish(); - SIGNALED.store(false, Ordering::Relaxed); - unsafe { sigaction(Signal::SIGUSR2, &sa) }.unwrap(); - let err = liocb.listio(LioMode::LIO_NOWAIT, sigev_notify); - err.expect("lio_listio"); - while !SIGNALED.load(Ordering::Relaxed) { - thread::sleep(time::Duration::from_millis(10)); + let mut wcb = Box::pin(AioWrite::new( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + )); + + let mut rcb = Box::pin(AioRead::new( + f.as_raw_fd(), + 8, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + )); + wcb.as_mut().submit().unwrap(); + rcb.as_mut().submit().unwrap(); + loop { + { + let cbbuf = [ + &*wcb as &dyn AsRef, + &*rcb as &dyn AsRef, + ]; + let r = aio_suspend(&cbbuf[..], Some(timeout)); + match r { + Err(Errno::EINTR) => continue, + Err(e) => panic!("aio_suspend returned {:?}", e), + Ok(_) => (), + }; + } + if rcb.as_mut().error() != Err(Errno::EINPROGRESS) + && wcb.as_mut().error() != Err(Errno::EINPROGRESS) + { + break; } - - assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len()); - assert_eq!(liocb.aio_return(1).unwrap() as usize, rlen); } - assert_eq!(rbuf.deref().deref(), b"3456"); - - f.seek(SeekFrom::Start(0)).unwrap(); - let len = f.read_to_end(&mut rbuf2).unwrap(); - assert_eq!(len, EXPECT.len()); - assert_eq!(rbuf2, EXPECT); -} -// Try to use LioCb::listio to read into an immutable buffer. It should fail -// FIXME: This test fails to panic on Linux/musl -#[test] -#[cfg(not(any(target_os = "ios", target_os = "macos")))] -#[should_panic(expected = "Can't read into an immutable buffer")] -#[cfg_attr(target_env = "musl", ignore)] -fn test_liocb_listio_read_immutable() { - let rbuf: &[u8] = b"abcd"; - let f = tempfile().unwrap(); - - - let mut liocb = LioCbBuilder::with_capacity(1) - .emplace_slice( - f.as_raw_fd(), - 2, //offset - rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ - ).finish(); - let _ = liocb.listio(LioMode::LIO_NOWAIT, SigevNotify::SigevNone); + assert_eq!(wcb.as_mut().aio_return().unwrap(), WBUF.len()); + assert_eq!(rcb.as_mut().aio_return().unwrap(), rlen); } diff --git a/bash-5.1/vendor/nix/test/sys/test_aio_drop.rs b/bash-5.1/vendor/nix/test/sys/test_aio_drop.rs index f9ff97a..bbe6623 100644 --- a/bash-5.1/vendor/nix/test/sys/test_aio_drop.rs +++ b/bash-5.1/vendor/nix/test/sys/test_aio_drop.rs @@ -3,13 +3,17 @@ // the AIO subsystem and causes subsequent tests to fail #[test] #[should_panic(expected = "Dropped an in-progress AioCb")] -#[cfg(all(not(target_env = "musl"), - not(target_env = "uclibc"), - any(target_os = "linux", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd")))] +#[cfg(all( + not(target_env = "musl"), + not(target_env = "uclibc"), + any( + target_os = "linux", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" + ) +))] fn test_drop() { use nix::sys::aio::*; use nix::sys::signal::*; @@ -20,11 +24,12 @@ fn test_drop() { let f = tempfile().unwrap(); f.set_len(6).unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); - aiocb.write().unwrap(); + let mut aiocb = Box::pin(AioWrite::new( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + )); + aiocb.as_mut().submit().unwrap(); } diff --git a/bash-5.1/vendor/nix/test/sys/test_epoll.rs b/bash-5.1/vendor/nix/test/sys/test_epoll.rs index 8d44cd0..9156915 100644 --- a/bash-5.1/vendor/nix/test/sys/test_epoll.rs +++ b/bash-5.1/vendor/nix/test/sys/test_epoll.rs @@ -1,23 +1,24 @@ -use nix::sys::epoll::{EpollCreateFlags, EpollFlags, EpollOp, EpollEvent}; -use nix::sys::epoll::{epoll_create1, epoll_ctl}; use nix::errno::Errno; +use nix::sys::epoll::{epoll_create1, epoll_ctl}; +use nix::sys::epoll::{EpollCreateFlags, EpollEvent, EpollFlags, EpollOp}; #[test] pub fn test_epoll_errno() { let efd = epoll_create1(EpollCreateFlags::empty()).unwrap(); let result = epoll_ctl(efd, EpollOp::EpollCtlDel, 1, None); - assert!(result.is_err()); + result.expect_err("assertion failed"); assert_eq!(result.unwrap_err(), Errno::ENOENT); let result = epoll_ctl(efd, EpollOp::EpollCtlAdd, 1, None); - assert!(result.is_err()); + result.expect_err("assertion failed"); assert_eq!(result.unwrap_err(), Errno::EINVAL); } #[test] pub fn test_epoll_ctl() { let efd = epoll_create1(EpollCreateFlags::empty()).unwrap(); - let mut event = EpollEvent::new(EpollFlags::EPOLLIN | EpollFlags::EPOLLERR, 1); + let mut event = + EpollEvent::new(EpollFlags::EPOLLIN | EpollFlags::EPOLLERR, 1); epoll_ctl(efd, EpollOp::EpollCtlAdd, 1, &mut event).unwrap(); epoll_ctl(efd, EpollOp::EpollCtlDel, 1, None).unwrap(); } diff --git a/bash-5.1/vendor/nix/test/sys/test_inotify.rs b/bash-5.1/vendor/nix/test/sys/test_inotify.rs index 137816a..bb5851a 100644 --- a/bash-5.1/vendor/nix/test/sys/test_inotify.rs +++ b/bash-5.1/vendor/nix/test/sys/test_inotify.rs @@ -1,15 +1,16 @@ -use nix::sys::inotify::{AddWatchFlags,InitFlags,Inotify}; use nix::errno::Errno; +use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; use std::ffi::OsString; use std::fs::{rename, File}; #[test] pub fn test_inotify() { - let instance = Inotify::init(InitFlags::IN_NONBLOCK) - .unwrap(); + let instance = Inotify::init(InitFlags::IN_NONBLOCK).unwrap(); let tempdir = tempfile::tempdir().unwrap(); - instance.add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS).unwrap(); + instance + .add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS) + .unwrap(); let events = instance.read_events(); assert_eq!(events.unwrap_err(), Errno::EAGAIN); @@ -22,11 +23,12 @@ pub fn test_inotify() { #[test] pub fn test_inotify_multi_events() { - let instance = Inotify::init(InitFlags::IN_NONBLOCK) - .unwrap(); + let instance = Inotify::init(InitFlags::IN_NONBLOCK).unwrap(); let tempdir = tempfile::tempdir().unwrap(); - instance.add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS).unwrap(); + instance + .add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS) + .unwrap(); let events = instance.read_events(); assert_eq!(events.unwrap_err(), Errno::EAGAIN); diff --git a/bash-5.1/vendor/nix/test/sys/test_ioctl.rs b/bash-5.1/vendor/nix/test/sys/test_ioctl.rs index 236d242..7a603c5 100644 --- a/bash-5.1/vendor/nix/test/sys/test_ioctl.rs +++ b/bash-5.1/vendor/nix/test/sys/test_ioctl.rs @@ -32,7 +32,12 @@ ioctl_readwrite_buf!(readwritebuf_test, 0, 0, u32); mod linux { #[test] fn test_op_none() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_none!(b'q', 10) as u32, 0x2000_710A); assert_eq!(request_code_none!(b'a', 255) as u32, 0x2000_61FF); } else { @@ -43,7 +48,12 @@ mod linux { #[test] fn test_op_write() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_write!(b'z', 10, 1) as u32, 0x8001_7A0A); assert_eq!(request_code_write!(b'z', 10, 512) as u32, 0x8200_7A0A); } else { @@ -55,19 +65,27 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_write_64() { - if cfg!(any(target_arch = "mips64", target_arch="powerpc64")){ - assert_eq!(request_code_write!(b'z', 10, 1u64 << 32) as u32, - 0x8000_7A0A); + if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { + assert_eq!( + request_code_write!(b'z', 10, 1u64 << 32) as u32, + 0x8000_7A0A + ); } else { - assert_eq!(request_code_write!(b'z', 10, 1u64 << 32) as u32, - 0x4000_7A0A); + assert_eq!( + request_code_write!(b'z', 10, 1u64 << 32) as u32, + 0x4000_7A0A + ); } - } #[test] fn test_op_read() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_read!(b'z', 10, 1) as u32, 0x4001_7A0A); assert_eq!(request_code_read!(b'z', 10, 512) as u32, 0x4200_7A0A); } else { @@ -79,12 +97,16 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_64() { - if cfg!(any(target_arch = "mips64", target_arch="powerpc64")){ - assert_eq!(request_code_read!(b'z', 10, 1u64 << 32) as u32, - 0x4000_7A0A); + if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { + assert_eq!( + request_code_read!(b'z', 10, 1u64 << 32) as u32, + 0x4000_7A0A + ); } else { - assert_eq!(request_code_read!(b'z', 10, 1u64 << 32) as u32, - 0x8000_7A0A); + assert_eq!( + request_code_read!(b'z', 10, 1u64 << 32) as u32, + 0x8000_7A0A + ); } } @@ -97,17 +119,21 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_write_64() { - assert_eq!(request_code_readwrite!(b'z', 10, 1u64 << 32) as u32, - 0xC000_7A0A); + assert_eq!( + request_code_readwrite!(b'z', 10, 1u64 << 32) as u32, + 0xC000_7A0A + ); } } -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] mod bsd { #[test] fn test_op_none() { @@ -164,8 +190,8 @@ mod linux_ioctls { use std::mem; use std::os::unix::io::AsRawFd; + use libc::{termios, TCGETS, TCSBRK, TCSETS, TIOCNXCL}; use tempfile::tempfile; - use libc::{TCGETS, TCSBRK, TCSETS, TIOCNXCL, termios}; use nix::errno::Errno; @@ -255,7 +281,7 @@ mod linux_ioctls { } // From linux/videodev2.h - ioctl_readwrite!(enum_audio, b'V', 65, v4l2_audio); + ioctl_readwrite!(enum_audio, b'V', 65, v4l2_audio); #[test] fn test_ioctl_readwrite() { let file = tempfile().unwrap(); @@ -281,7 +307,12 @@ mod linux_ioctls { } // From linux/spi/spidev.h - ioctl_write_buf!(spi_ioc_message, super::SPI_IOC_MAGIC, super::SPI_IOC_MESSAGE, spi_ioc_transfer); + ioctl_write_buf!( + spi_ioc_message, + super::SPI_IOC_MAGIC, + super::SPI_IOC_MESSAGE, + spi_ioc_transfer + ); #[test] fn test_ioctl_write_buf() { let file = tempfile().unwrap(); @@ -298,8 +329,8 @@ mod freebsd_ioctls { use std::mem; use std::os::unix::io::AsRawFd; - use tempfile::tempfile; use libc::termios; + use tempfile::tempfile; use nix::errno::Errno; diff --git a/bash-5.1/vendor/nix/test/sys/test_mman.rs b/bash-5.1/vendor/nix/test/sys/test_mman.rs index 8858375..75cbf6c 100644 --- a/bash-5.1/vendor/nix/test/sys/test_mman.rs +++ b/bash-5.1/vendor/nix/test/sys/test_mman.rs @@ -3,53 +3,73 @@ use nix::sys::mman::{mmap, MapFlags, ProtFlags}; #[test] fn test_mmap_anonymous() { unsafe { - let ptr = mmap(std::ptr::null_mut(), 1, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS, -1, 0) - .unwrap() as *mut u8; - assert_eq !(*ptr, 0x00u8); + let ptr = mmap( + std::ptr::null_mut(), + 1, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS, + -1, + 0, + ) + .unwrap() as *mut u8; + assert_eq!(*ptr, 0x00u8); *ptr = 0xffu8; - assert_eq !(*ptr, 0xffu8); + assert_eq!(*ptr, 0xffu8); } } #[test] #[cfg(any(target_os = "linux", target_os = "netbsd"))] fn test_mremap_grow() { - use nix::sys::mman::{mremap, MRemapFlags}; use nix::libc::{c_void, size_t}; + use nix::sys::mman::{mremap, MRemapFlags}; - const ONE_K : size_t = 1024; - let slice : &mut[u8] = unsafe { - let mem = mmap(std::ptr::null_mut(), ONE_K, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, -1, 0) - .unwrap(); - std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) + const ONE_K: size_t = 1024; + let slice: &mut [u8] = unsafe { + let mem = mmap( + std::ptr::null_mut(), + ONE_K, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, + -1, + 0, + ) + .unwrap(); + std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; - assert_eq !(slice[ONE_K - 1], 0x00); + assert_eq!(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); - let slice : &mut[u8] = unsafe { + let slice: &mut [u8] = unsafe { #[cfg(target_os = "linux")] - let mem = mremap(slice.as_mut_ptr() as * mut c_void, ONE_K, 10 * ONE_K, - MRemapFlags::MREMAP_MAYMOVE, None) - .unwrap(); + let mem = mremap( + slice.as_mut_ptr() as *mut c_void, + ONE_K, + 10 * ONE_K, + MRemapFlags::MREMAP_MAYMOVE, + None, + ) + .unwrap(); #[cfg(target_os = "netbsd")] - let mem = mremap(slice.as_mut_ptr() as * mut c_void, ONE_K, 10 * ONE_K, - MRemapFlags::MAP_REMAPDUP, None) - .unwrap(); - std::slice::from_raw_parts_mut(mem as * mut u8, 10 * ONE_K) + let mem = mremap( + slice.as_mut_ptr() as *mut c_void, + ONE_K, + 10 * ONE_K, + MRemapFlags::MAP_REMAPDUP, + None, + ) + .unwrap(); + std::slice::from_raw_parts_mut(mem as *mut u8, 10 * ONE_K) }; // The first KB should still have the old data in it. - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); // The additional range should be zero-init'd and accessible. - assert_eq !(slice[10 * ONE_K - 1], 0x00); + assert_eq!(slice[10 * ONE_K - 1], 0x00); slice[10 * ONE_K - 1] = 0xFF; - assert_eq !(slice[10 * ONE_K - 1], 0xFF); + assert_eq!(slice[10 * ONE_K - 1], 0xFF); } #[test] @@ -57,31 +77,41 @@ fn test_mremap_grow() { // Segfaults for unknown reasons under QEMU for 32-bit targets #[cfg_attr(all(target_pointer_width = "32", qemu), ignore)] fn test_mremap_shrink() { - use nix::sys::mman::{mremap, MRemapFlags}; use nix::libc::{c_void, size_t}; + use nix::sys::mman::{mremap, MRemapFlags}; - const ONE_K : size_t = 1024; - let slice : &mut[u8] = unsafe { - let mem = mmap(std::ptr::null_mut(), 10 * ONE_K, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, -1, 0) - .unwrap(); - std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) + const ONE_K: size_t = 1024; + let slice: &mut [u8] = unsafe { + let mem = mmap( + std::ptr::null_mut(), + 10 * ONE_K, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, + -1, + 0, + ) + .unwrap(); + std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; - assert_eq !(slice[ONE_K - 1], 0x00); + assert_eq!(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); - let slice : &mut[u8] = unsafe { - let mem = mremap(slice.as_mut_ptr() as * mut c_void, 10 * ONE_K, ONE_K, - MRemapFlags::empty(), None) - .unwrap(); + let slice: &mut [u8] = unsafe { + let mem = mremap( + slice.as_mut_ptr() as *mut c_void, + 10 * ONE_K, + ONE_K, + MRemapFlags::empty(), + None, + ) + .unwrap(); // Since we didn't supply MREMAP_MAYMOVE, the address should be the // same. - assert_eq !(mem, slice.as_mut_ptr() as * mut c_void); - std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) + assert_eq!(mem, slice.as_mut_ptr() as *mut c_void); + std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; // The first KB should still be accessible and have the old data in it. - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); } diff --git a/bash-5.1/vendor/nix/test/sys/test_pthread.rs b/bash-5.1/vendor/nix/test/sys/test_pthread.rs index fa9b510..ce048ba 100644 --- a/bash-5.1/vendor/nix/test/sys/test_pthread.rs +++ b/bash-5.1/vendor/nix/test/sys/test_pthread.rs @@ -4,14 +4,14 @@ use nix::sys::pthread::*; #[test] fn test_pthread_self() { let tid = pthread_self(); - assert!(tid != ::std::ptr::null_mut()); + assert!(!tid.is_null()); } #[cfg(not(any(target_env = "musl", target_os = "redox")))] #[test] fn test_pthread_self() { let tid = pthread_self(); - assert!(tid != 0); + assert_ne!(tid, 0); } #[test] diff --git a/bash-5.1/vendor/nix/test/sys/test_ptrace.rs b/bash-5.1/vendor/nix/test/sys/test_ptrace.rs index 89c4e2d..530560f 100644 --- a/bash-5.1/vendor/nix/test/sys/test_ptrace.rs +++ b/bash-5.1/vendor/nix/test/sys/test_ptrace.rs @@ -1,8 +1,14 @@ +#[cfg(all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "x86"), + target_env = "gnu" +))] +use memoffset::offset_of; use nix::errno::Errno; -use nix::unistd::getpid; use nix::sys::ptrace; #[cfg(any(target_os = "android", target_os = "linux"))] use nix::sys::ptrace::Options; +use nix::unistd::getpid; #[cfg(any(target_os = "android", target_os = "linux"))] use std::mem; @@ -15,8 +21,9 @@ fn test_ptrace() { // FIXME: qemu-user doesn't implement ptrace on all arches, so permit ENOSYS require_capability!("test_ptrace", CAP_SYS_PTRACE); let err = ptrace::attach(getpid()).unwrap_err(); - assert!(err == Errno::EPERM || err == Errno::EINVAL || - err == Errno::ENOSYS); + assert!( + err == Errno::EPERM || err == Errno::EINVAL || err == Errno::ENOSYS + ); } // Just make sure ptrace_setoptions can be called at all, for now. @@ -24,8 +31,9 @@ fn test_ptrace() { #[cfg(any(target_os = "android", target_os = "linux"))] fn test_ptrace_setoptions() { require_capability!("test_ptrace_setoptions", CAP_SYS_PTRACE); - let err = ptrace::setoptions(getpid(), Options::PTRACE_O_TRACESYSGOOD).unwrap_err(); - assert!(err != Errno::EOPNOTSUPP); + let err = ptrace::setoptions(getpid(), Options::PTRACE_O_TRACESYSGOOD) + .unwrap_err(); + assert_ne!(err, Errno::EOPNOTSUPP); } // Just make sure ptrace_getevent can be called at all, for now. @@ -34,7 +42,7 @@ fn test_ptrace_setoptions() { fn test_ptrace_getevent() { require_capability!("test_ptrace_getevent", CAP_SYS_PTRACE); let err = ptrace::getevent(getpid()).unwrap_err(); - assert!(err != Errno::EOPNOTSUPP); + assert_ne!(err, Errno::EOPNOTSUPP); } // Just make sure ptrace_getsiginfo can be called at all, for now. @@ -58,7 +66,6 @@ fn test_ptrace_setsiginfo() { } } - #[test] fn test_ptrace_cont() { use nix::sys::ptrace; @@ -82,7 +89,7 @@ fn test_ptrace_cont() { return; } - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => { ptrace::traceme().unwrap(); // As recommended by ptrace(2), raise SIGTRAP to pause the child @@ -90,15 +97,22 @@ fn test_ptrace_cont() { loop { raise(Signal::SIGTRAP).unwrap(); } - - }, + } Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTRAP)) + ); ptrace::cont(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTRAP)) + ); ptrace::cont(child, Some(Signal::SIGKILL)).unwrap(); match waitpid(child, None) { - Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) if pid == child => { + Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) + if pid == child => + { // FIXME It's been observed on some systems (apple) the // tracee may not be killed but remain as a zombie process // affecting other wait based tests. Add an extra kill just @@ -110,7 +124,7 @@ fn test_ptrace_cont() { } _ => panic!("The process should have been killed"), } - }, + } } } @@ -129,22 +143,28 @@ fn test_ptrace_interrupt() { let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => { - loop { - sleep(Duration::from_millis(1000)); - } - + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => loop { + sleep(Duration::from_millis(1000)); }, Parent { child } => { - ptrace::seize(child, ptrace::Options::PTRACE_O_TRACESYSGOOD).unwrap(); + ptrace::seize(child, ptrace::Options::PTRACE_O_TRACESYSGOOD) + .unwrap(); ptrace::interrupt(child).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceEvent(child, Signal::SIGTRAP, 128))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceEvent(child, Signal::SIGTRAP, 128)) + ); ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceSyscall(child)) + ); ptrace::detach(child, Some(Signal::SIGKILL)).unwrap(); match waitpid(child, None) { - Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) if pid == child => { + Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) + if pid == child => + { let _ = waitpid(child, Some(WaitPidFlag::WNOHANG)); while ptrace::cont(child, Some(Signal::SIGKILL)).is_ok() { let _ = waitpid(child, Some(WaitPidFlag::WNOHANG)); @@ -152,19 +172,20 @@ fn test_ptrace_interrupt() { } _ => panic!("The process should have been killed"), } - }, + } } } // ptrace::{setoptions, getregs} are only available in these platforms -#[cfg(all(target_os = "linux", - any(target_arch = "x86_64", - target_arch = "x86"), - target_env = "gnu"))] +#[cfg(all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "x86"), + target_env = "gnu" +))] #[test] fn test_ptrace_syscall() { - use nix::sys::signal::kill; use nix::sys::ptrace; + use nix::sys::signal::kill; use nix::sys::signal::Signal; use nix::sys::wait::{waitpid, WaitStatus}; use nix::unistd::fork; @@ -175,45 +196,80 @@ fn test_ptrace_syscall() { let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => { ptrace::traceme().unwrap(); // first sigstop until parent is ready to continue let pid = getpid(); kill(pid, Signal::SIGSTOP).unwrap(); kill(pid, Signal::SIGTERM).unwrap(); - unsafe { ::libc::_exit(0); } - }, + unsafe { + ::libc::_exit(0); + } + } Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGSTOP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGSTOP)) + ); // set this option to recognize syscall-stops - ptrace::setoptions(child, ptrace::Options::PTRACE_O_TRACESYSGOOD).unwrap(); + ptrace::setoptions(child, ptrace::Options::PTRACE_O_TRACESYSGOOD) + .unwrap(); #[cfg(target_arch = "x86_64")] - let get_syscall_id = || ptrace::getregs(child).unwrap().orig_rax as libc::c_long; + let get_syscall_id = + || ptrace::getregs(child).unwrap().orig_rax as libc::c_long; #[cfg(target_arch = "x86")] - let get_syscall_id = || ptrace::getregs(child).unwrap().orig_eax as libc::c_long; + let get_syscall_id = + || ptrace::getregs(child).unwrap().orig_eax as libc::c_long; + + // this duplicates `get_syscall_id` for the purpose of testing `ptrace::read_user`. + #[cfg(target_arch = "x86_64")] + let rax_offset = offset_of!(libc::user_regs_struct, orig_rax); + #[cfg(target_arch = "x86")] + let rax_offset = offset_of!(libc::user_regs_struct, orig_eax); + + let get_syscall_from_user_area = || { + // Find the offset of `user.regs.rax` (or `user.regs.eax` for x86) + let rax_offset = offset_of!(libc::user, regs) + rax_offset; + ptrace::read_user(child, rax_offset as _).unwrap() + as libc::c_long + }; // kill entry ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceSyscall(child)) + ); assert_eq!(get_syscall_id(), ::libc::SYS_kill); + assert_eq!(get_syscall_from_user_area(), ::libc::SYS_kill); // kill exit ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceSyscall(child)) + ); assert_eq!(get_syscall_id(), ::libc::SYS_kill); + assert_eq!(get_syscall_from_user_area(), ::libc::SYS_kill); // receive signal ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTERM))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTERM)) + ); // inject signal ptrace::syscall(child, Signal::SIGTERM).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, Signal::SIGTERM, false))); - }, + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Signaled(child, Signal::SIGTERM, false)) + ); + } } } diff --git a/bash-5.1/vendor/nix/test/sys/test_select.rs b/bash-5.1/vendor/nix/test/sys/test_select.rs index 2f7396b..40bda4d 100644 --- a/bash-5.1/vendor/nix/test/sys/test_select.rs +++ b/bash-5.1/vendor/nix/test/sys/test_select.rs @@ -1,7 +1,7 @@ use nix::sys::select::*; -use nix::unistd::{pipe, write}; use nix::sys::signal::SigSet; use nix::sys::time::{TimeSpec, TimeValLike}; +use nix::unistd::{pipe, write}; #[test] pub fn test_pselect() { @@ -45,7 +45,8 @@ pub fn test_pselect_nfds2() { None, &timeout, None - ).unwrap() + ) + .unwrap() ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); diff --git a/bash-5.1/vendor/nix/test/sys/test_signal.rs b/bash-5.1/vendor/nix/test/sys/test_signal.rs index fdd2568..3ad14f4 100644 --- a/bash-5.1/vendor/nix/test/sys/test_signal.rs +++ b/bash-5.1/vendor/nix/test/sys/test_signal.rs @@ -52,9 +52,12 @@ fn test_sigprocmask() { // Make sure the old set doesn't contain the signal, otherwise the following // test don't make sense. - assert!(!old_signal_set.contains(SIGNAL), - "the {:?} signal is already blocked, please change to a \ - different one", SIGNAL); + assert!( + !old_signal_set.contains(SIGNAL), + "the {:?} signal is already blocked, please change to a \ + different one", + SIGNAL + ); // Now block the signal. let mut signal_set = SigSet::empty(); @@ -66,8 +69,11 @@ fn test_sigprocmask() { old_signal_set.clear(); sigprocmask(SigmaskHow::SIG_BLOCK, None, Some(&mut old_signal_set)) .expect("expect to be able to retrieve old signals"); - assert!(old_signal_set.contains(SIGNAL), - "expected the {:?} to be blocked", SIGNAL); + assert!( + old_signal_set.contains(SIGNAL), + "expected the {:?} to be blocked", + SIGNAL + ); // Reset the signal. sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&signal_set), None) @@ -78,13 +84,18 @@ lazy_static! { static ref SIGNALED: AtomicBool = AtomicBool::new(false); } -extern fn test_sigaction_handler(signal: libc::c_int) { +extern "C" fn test_sigaction_handler(signal: libc::c_int) { let signal = Signal::try_from(signal).unwrap(); SIGNALED.store(signal == Signal::SIGINT, Ordering::Relaxed); } #[cfg(not(target_os = "redox"))] -extern fn test_sigaction_action(_: libc::c_int, _: *mut libc::siginfo_t, _: *mut libc::c_void) {} +extern "C" fn test_sigaction_action( + _: libc::c_int, + _: *mut libc::siginfo_t, + _: *mut libc::c_void, +) { +} #[test] #[cfg(not(target_os = "redox"))] @@ -92,7 +103,10 @@ fn test_signal_sigaction() { let _m = crate::SIGNAL_MTX.lock(); let action_handler = SigHandler::SigAction(test_sigaction_action); - assert_eq!(unsafe { signal(Signal::SIGINT, action_handler) }.unwrap_err(), Errno::ENOTSUP); + assert_eq!( + unsafe { signal(Signal::SIGINT, action_handler) }.unwrap_err(), + Errno::ENOTSUP + ); } #[test] @@ -101,20 +115,32 @@ fn test_signal() { unsafe { signal(Signal::SIGINT, SigHandler::SigIgn) }.unwrap(); raise(Signal::SIGINT).unwrap(); - assert_eq!(unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), SigHandler::SigIgn); + assert_eq!( + unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), + SigHandler::SigIgn + ); let handler = SigHandler::Handler(test_sigaction_handler); - assert_eq!(unsafe { signal(Signal::SIGINT, handler) }.unwrap(), SigHandler::SigDfl); + assert_eq!( + unsafe { signal(Signal::SIGINT, handler) }.unwrap(), + SigHandler::SigDfl + ); raise(Signal::SIGINT).unwrap(); assert!(SIGNALED.load(Ordering::Relaxed)); #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] - assert_eq!(unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), handler); + assert_eq!( + unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), + handler + ); // System V based OSes (e.g. illumos and Solaris) always resets the // disposition to SIG_DFL prior to calling the signal handler #[cfg(any(target_os = "illumos", target_os = "solaris"))] - assert_eq!(unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), SigHandler::SigDfl); + assert_eq!( + unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), + SigHandler::SigDfl + ); // Restore default signal handler unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(); diff --git a/bash-5.1/vendor/nix/test/sys/test_signalfd.rs b/bash-5.1/vendor/nix/test/sys/test_signalfd.rs index b6f748b..87153c9 100644 --- a/bash-5.1/vendor/nix/test/sys/test_signalfd.rs +++ b/bash-5.1/vendor/nix/test/sys/test_signalfd.rs @@ -2,8 +2,8 @@ use std::convert::TryFrom; #[test] fn test_signalfd() { + use nix::sys::signal::{self, raise, SigSet, Signal}; use nix::sys::signalfd::SignalFd; - use nix::sys::signal::{self, raise, Signal, SigSet}; // Grab the mutex for altering signals so we don't interfere with other tests. let _m = crate::SIGNAL_MTX.lock(); diff --git a/bash-5.1/vendor/nix/test/sys/test_socket.rs b/bash-5.1/vendor/nix/test/sys/test_socket.rs index 2aac795..b4ca279 100644 --- a/bash-5.1/vendor/nix/test/sys/test_socket.rs +++ b/bash-5.1/vendor/nix/test/sys/test_socket.rs @@ -1,7 +1,11 @@ +#[cfg(any(target_os = "linux", target_os = "android"))] +use crate::*; +use libc::{c_char, sockaddr_storage}; #[allow(deprecated)] use nix::sys::socket::InetAddr; -use nix::sys::socket::{AddressFamily, - UnixAddr, getsockname, sockaddr, sockaddr_in6}; +use nix::sys::socket::{ + getsockname, sockaddr, sockaddr_in6, AddressFamily, UnixAddr, +}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::mem::{self, MaybeUninit}; @@ -10,9 +14,6 @@ use std::os::unix::io::RawFd; use std::path::Path; use std::slice; use std::str::FromStr; -use libc::{c_char, sockaddr_storage}; -#[cfg(any(target_os = "linux", target_os= "android"))] -use crate::*; #[allow(deprecated)] #[test] @@ -41,7 +42,7 @@ pub fn test_inetv4_addr_to_sock_addr() { #[allow(deprecated)] #[test] pub fn test_inetv4_addr_roundtrip_sockaddr_storage_to_addr() { - use nix::sys::socket::{SockAddr, sockaddr_storage_to_addr}; + use nix::sys::socket::{sockaddr_storage_to_addr, SockAddr}; let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); @@ -58,9 +59,12 @@ pub fn test_inetv4_addr_roundtrip_sockaddr_storage_to_addr() { } }; - let from_storage = sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); assert_eq!(from_storage, sockaddr); - let from_storage = sockaddr_storage_to_addr(&storage, mem::size_of::()).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, mem::size_of::()) + .unwrap(); assert_eq!(from_storage, sockaddr); } @@ -69,8 +73,9 @@ pub fn test_inetv4_addr_roundtrip_sockaddr_storage_to_addr() { #[test] pub fn test_timestamping() { use nix::sys::socket::{ - recvmsg, sendmsg, setsockopt, socket, sockopt::Timestamping, ControlMessageOwned, MsgFlags, - SockaddrIn, SockFlag, SockType, TimestampingFlag, + recvmsg, sendmsg, setsockopt, socket, sockopt::Timestamping, + ControlMessageOwned, MsgFlags, SockFlag, SockType, SockaddrIn, + TimestampingFlag, }; use std::io::{IoSlice, IoSliceMut}; @@ -112,7 +117,9 @@ pub fn test_timestamping() { } } let ts = ts.expect("ScmTimestampns is present"); - let sys_time = ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME).unwrap(); + let sys_time = + ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME) + .unwrap(); let diff = if ts > sys_time { ts - sys_time } else { @@ -124,14 +131,15 @@ pub fn test_timestamping() { #[allow(deprecated)] #[test] pub fn test_inetv6_addr_roundtrip_sockaddr_storage_to_addr() { - use nix::sys::socket::{SockAddr, sockaddr_storage_to_addr}; + use nix::sys::socket::{sockaddr_storage_to_addr, SockAddr}; let port: u16 = 3000; let flowinfo: u32 = 1; let scope_id: u32 = 2; let ip: Ipv6Addr = "fe80::1".parse().unwrap(); - let actual = SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); + let actual = + SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); let addr = InetAddr::from_std(&actual); let sockaddr = SockAddr::new_inet(addr); @@ -141,14 +149,20 @@ pub fn test_inetv6_addr_roundtrip_sockaddr_storage_to_addr() { let (ffi_ptr, ffi_size) = sockaddr.as_ffi_pair(); assert_eq!(mem::size_of::(), ffi_size as usize); unsafe { - storage_ptr.copy_from_nonoverlapping((ffi_ptr as *const sockaddr).cast::(), 1); + storage_ptr.copy_from_nonoverlapping( + (ffi_ptr as *const sockaddr).cast::(), + 1, + ); (storage.assume_init(), ffi_size) } }; - let from_storage = sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); assert_eq!(from_storage, sockaddr); - let from_storage = sockaddr_storage_to_addr(&storage, mem::size_of::()).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, mem::size_of::()) + .unwrap(); assert_eq!(from_storage, sockaddr); } @@ -190,7 +204,7 @@ pub fn test_addr_equality_path() { pub fn test_abstract_sun_path_too_long() { let name = String::from("nix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0testttttnix\0abstract\0test\0make\0sure\0this\0is\0long\0enough"); let addr = UnixAddr::new_abstract(name.as_bytes()); - assert!(addr.is_err()); + addr.expect_err("assertion failed"); } #[cfg(any(target_os = "android", target_os = "linux"))] @@ -220,7 +234,8 @@ pub fn test_abstract_uds_addr() { let name = String::from("nix\0abstract\0test"); let addr = UnixAddr::new_abstract(name.as_bytes()).unwrap(); let sun_path = [ - 110u8, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, 116, 101, 115, 116 + 110u8, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, 116, 101, + 115, 116, ]; assert_eq!(addr.as_abstract(), Some(&sun_path[..])); assert_eq!(addr.path(), None); @@ -231,13 +246,18 @@ pub fn test_abstract_uds_addr() { #[test] pub fn test_getsockname() { - use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::bind; + use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType}; let tempdir = tempfile::tempdir().unwrap(); let sockname = tempdir.path().join("sock"); - let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); assert_eq!(sockaddr, getsockname(sock).expect("getsockname failed")); @@ -245,30 +265,53 @@ pub fn test_getsockname() { #[test] pub fn test_socketpair() { + use nix::sys::socket::{socketpair, AddressFamily, SockFlag, SockType}; use nix::unistd::{read, write}; - use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); write(fd1, b"hello").unwrap(); - let mut buf = [0;5]; + let mut buf = [0; 5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); } +#[test] +pub fn test_std_conversions() { + use nix::sys::socket::*; + + let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap(); + let sock_addr = SockaddrIn::from(std_sa); + assert_eq!(std_sa, sock_addr.into()); + + let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap(); + let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa); + assert_eq!(std_sa, sock_addr.into()); +} + mod recvfrom { - use nix::Result; + use super::*; use nix::sys::socket::*; + use nix::{errno::Errno, Result}; use std::thread; - use super::*; const MSG: &[u8] = b"Hello, World!"; - fn sendrecv(rsock: RawFd, ssock: RawFd, f_send: Fs, mut f_recv: Fr) -> Option - where - Fs: Fn(RawFd, &[u8], MsgFlags) -> Result + Send + 'static, - Fr: FnMut(usize, Option), + fn sendrecv( + rsock: RawFd, + ssock: RawFd, + f_send: Fs, + mut f_recv: Fr, + ) -> Option + where + Fs: Fn(RawFd, &[u8], MsgFlags) -> Result + Send + 'static, + Fr: FnMut(usize, Option), { let mut buf: [u8; 13] = [0u8; 13]; let mut l = 0; @@ -294,33 +337,42 @@ mod recvfrom { #[test] pub fn stream() { - let (fd2, fd1) = socketpair(AddressFamily::Unix, SockType::Stream, - None, SockFlag::empty()).unwrap(); + let (fd2, fd1) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); // Ignore from for stream sockets - let _ = sendrecv(fd1, fd2, |s, m, flags| { - send(s, m, flags) - }, |_, _| {}); + let _ = sendrecv(fd1, fd2, send, |_, _| {}); } #[test] pub fn udp() { let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap(); let sock_addr = SockaddrIn::from(std_sa); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - let from = sendrecv(rsock, ssock, move |s, m, flags| { - sendto(s, m, &sock_addr, flags) - },|_, _| {}); + ) + .expect("send socket failed"); + let from = sendrecv( + rsock, + ssock, + move |s, m, flags| sendto(s, m, &sock_addr, flags), + |_, _| {}, + ); // UDP sockets should set the from address assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap()); } @@ -344,11 +396,13 @@ mod recvfrom { let segment_size: u16 = 2; let sock_addr = SockaddrIn::new(127, 0, 0, 1, 6791); - let rsock = socket(AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None - ).unwrap(); + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(rsock, UdpGsoSegment, &(segment_size as _)) .expect("setsockopt UDP_SEGMENT failed"); @@ -359,24 +413,30 @@ mod recvfrom { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); let mut num_packets_received: i32 = 0; - sendrecv(rsock, ssock, move |s, m, flags| { - let iov = [IoSlice::new(m)]; - let cmsg = ControlMessage::UdpGsoSegments(&segment_size); - sendmsg(s, &iov, &[cmsg], flags, Some(&sock_addr)) - }, { - let num_packets_received_ref = &mut num_packets_received; - - move |len, _| { - // check that we receive UDP packets with payload size - // less or equal to segment size - assert!(len <= segment_size as usize); - *num_packets_received_ref += 1; - } - }); + sendrecv( + rsock, + ssock, + move |s, m, flags| { + let iov = [IoSlice::new(m)]; + let cmsg = ControlMessage::UdpGsoSegments(&segment_size); + sendmsg(s, &iov, &[cmsg], flags, Some(&sock_addr)) + }, + { + let num_packets_received_ref = &mut num_packets_received; + + move |len, _| { + // check that we receive UDP packets with payload size + // less or equal to segment size + assert!(len <= segment_size as usize); + *num_packets_received_ref += 1; + } + }, + ); // Buffer size is 13, we will receive six packets of size 2, // and one packet of size 1. @@ -393,11 +453,13 @@ mod recvfrom { // It's hard to guarantee receiving GRO packets. Just checking // that `setsockopt` doesn't fail with error - let rsock = socket(AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None - ).unwrap(); + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(rsock, UdpGroSegment, &true) .expect("setsockopt UDP_GRO failed"); @@ -419,51 +481,54 @@ mod recvfrom { let sock_addr = SockaddrIn::from(std_sa); let sock_addr2 = SockaddrIn::from(std_sa2); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); - let from = sendrecv(rsock, ssock, move |s, m, flags| { - let iov = [IoSlice::new(m)]; - let mut msgs = vec![ - SendMmsgData { + let from = sendrecv( + rsock, + ssock, + move |s, m, flags| { + let iov = [IoSlice::new(m)]; + let mut msgs = vec![SendMmsgData { iov: &iov, cmsgs: &[], addr: Some(sock_addr), _lt: Default::default(), - } - ]; + }]; - let batch_size = 15; + let batch_size = 15; - for _ in 0..batch_size { - msgs.push( - SendMmsgData { + for _ in 0..batch_size { + msgs.push(SendMmsgData { iov: &iov, cmsgs: &[], addr: Some(sock_addr2), _lt: Default::default(), - } - ); - } - sendmmsg(s, msgs.iter(), flags) - .map(move |sent_bytes| { + }); + } + sendmmsg(s, msgs.iter(), flags).map(move |sent_bytes| { assert!(!sent_bytes.is_empty()); for sent in &sent_bytes { assert_eq!(*sent, m.len()); } sent_bytes.len() }) - }, |_, _ | {}); + }, + |_, _| {}, + ); // UDP sockets should set the from address assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap()); } @@ -476,31 +541,35 @@ mod recvfrom { ))] #[test] pub fn udp_recvmmsg() { + use nix::sys::socket::{recvmmsg, MsgFlags}; use std::io::IoSliceMut; - use nix::sys::socket::{MsgFlags, recvmmsg}; const NUM_MESSAGES_SENT: usize = 2; - const DATA: [u8; 2] = [1,2]; + const DATA: [u8; 2] = [1, 2]; let inet_addr = SocketAddrV4::from_str("127.0.0.1:6798").unwrap(); let sock_addr = SockaddrIn::from(inet_addr); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); let send_thread = thread::spawn(move || { for _ in 0..NUM_MESSAGES_SENT { - sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()).unwrap(); + sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()) + .unwrap(); } }); @@ -508,18 +577,21 @@ mod recvfrom { // Buffers to receive exactly `NUM_MESSAGES_SENT` messages let mut receive_buffers = [[0u8; 32]; NUM_MESSAGES_SENT]; - let iovs: Vec<_> = receive_buffers.iter_mut().map(|buf| { - [IoSliceMut::new(&mut buf[..])] - }).collect(); + let iovs: Vec<_> = receive_buffers + .iter_mut() + .map(|buf| [IoSliceMut::new(&mut buf[..])]) + .collect(); for iov in &iovs { msgs.push_back(RecvMmsgData { iov, cmsg_buffer: None, }) - }; + } - let res: Vec> = recvmmsg(rsock, &mut msgs, MsgFlags::empty(), None).expect("recvmmsg"); + let res: Vec> = + recvmmsg(rsock, &mut msgs, MsgFlags::empty(), None) + .expect("recvmmsg"); assert_eq!(res.len(), DATA.len()); for RecvMsg { address, bytes, .. } in res.into_iter() { @@ -542,31 +614,35 @@ mod recvfrom { ))] #[test] pub fn udp_recvmmsg_dontwait_short_read() { - use nix::sys::socket::{MsgFlags, recvmmsg}; + use nix::sys::socket::{recvmmsg, MsgFlags}; use std::io::IoSliceMut; const NUM_MESSAGES_SENT: usize = 2; - const DATA: [u8; 4] = [1,2,3,4]; + const DATA: [u8; 4] = [1, 2, 3, 4]; let inet_addr = SocketAddrV4::from_str("127.0.0.1:6799").unwrap(); let sock_addr = SockaddrIn::from(inet_addr); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); let send_thread = thread::spawn(move || { for _ in 0..NUM_MESSAGES_SENT { - sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()).unwrap(); + sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()) + .unwrap(); } }); // Ensure we've sent all the messages before continuing so `recvmmsg` @@ -579,18 +655,21 @@ mod recvfrom { // will return when there are fewer than requested messages in the // kernel buffers when using `MSG_DONTWAIT`. let mut receive_buffers = [[0u8; 32]; NUM_MESSAGES_SENT + 2]; - let iovs: Vec<_> = receive_buffers.iter_mut().map(|buf| { - [IoSliceMut::new(&mut buf[..])] - }).collect(); + let iovs: Vec<_> = receive_buffers + .iter_mut() + .map(|buf| [IoSliceMut::new(&mut buf[..])]) + .collect(); for iov in &iovs { msgs.push_back(RecvMmsgData { iov, cmsg_buffer: None, }) - }; + } - let res: Vec> = recvmmsg(rsock, &mut msgs, MsgFlags::MSG_DONTWAIT, None).expect("recvmmsg"); + let res: Vec> = + recvmmsg(rsock, &mut msgs, MsgFlags::MSG_DONTWAIT, None) + .expect("recvmmsg"); assert_eq!(res.len(), NUM_MESSAGES_SENT); for RecvMsg { address, bytes, .. } in res.into_iter() { @@ -602,19 +681,64 @@ mod recvfrom { assert_eq!(&buf[..DATA.len()], DATA); } } + + #[test] + pub fn udp_inet6() { + let addr = std::net::Ipv6Addr::from_str("::1").unwrap(); + let rport = 6789; + let rstd_sa = SocketAddrV6::new(addr, rport, 0, 0); + let raddr = SockaddrIn6::from(rstd_sa); + let sport = 6790; + let sstd_sa = SocketAddrV6::new(addr, sport, 0, 0); + let saddr = SockaddrIn6::from(sstd_sa); + let rsock = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("receive socket failed"); + match bind(rsock, &raddr) { + Err(Errno::EADDRNOTAVAIL) => { + println!("IPv6 not available, skipping test."); + return; + } + Err(e) => panic!("bind: {}", e), + Ok(()) => (), + } + let ssock = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("send socket failed"); + bind(ssock, &saddr).unwrap(); + let from = sendrecv( + rsock, + ssock, + move |s, m, flags| sendto(s, m, &raddr, flags), + |_, _| {}, + ); + assert_eq!(AddressFamily::Inet6, from.unwrap().family().unwrap()); + let osent_addr = from.unwrap(); + let sent_addr = osent_addr.as_sockaddr_in6().unwrap(); + assert_eq!(sent_addr.ip(), addr); + assert_eq!(sent_addr.port(), sport); + } } // Test error handling of our recvmsg wrapper #[test] pub fn test_recvmsg_ebadf() { use nix::errno::Errno; - use nix::sys::socket::{MsgFlags, recvmsg}; + use nix::sys::socket::{recvmsg, MsgFlags}; use std::io::IoSliceMut; let mut buf = [0u8; 5]; let mut iov = [IoSliceMut::new(&mut buf[..])]; - let fd = -1; // Bad file descriptor + let fd = -1; // Bad file descriptor let r = recvmsg::<()>(fd, &mut iov, None, MsgFlags::empty()); assert_eq!(r.err().unwrap(), Errno::EBADF); @@ -625,14 +749,20 @@ pub fn test_recvmsg_ebadf() { #[cfg_attr(qemu, ignore)] #[test] pub fn test_scm_rights() { - use nix::unistd::{pipe, read, write, close}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, - ControlMessage, ControlMessageOwned, MsgFlags}; + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage, + ControlMessageOwned, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::{close, pipe, read, write}; use std::io::{IoSlice, IoSliceMut}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option = None; @@ -640,7 +770,10 @@ pub fn test_scm_rights() { let iov = [IoSlice::new(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); - assert_eq!(sendmsg::<()>(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), + 5 + ); close(r).unwrap(); close(fd1).unwrap(); } @@ -650,7 +783,13 @@ pub fn test_scm_rights() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!([RawFd; 1]); - let msg = recvmsg::<()>(fd2, &mut iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); + let msg = recvmsg::<()>( + fd2, + &mut iov, + Some(&mut cmsgspace), + MsgFlags::empty(), + ) + .unwrap(); for cmsg in msg.cmsgs() { if let ControlMessageOwned::ScmRights(fd) = cmsg { @@ -662,7 +801,9 @@ pub fn test_scm_rights() { } } assert_eq!(msg.bytes, 5); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); close(fd2).unwrap(); } @@ -677,15 +818,16 @@ pub fn test_scm_rights() { } // Disable the test on emulated platforms due to not enabled support of AF_ALG in QEMU from rust cross -#[cfg(any(target_os = "linux", target_os= "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg_attr(qemu, ignore)] #[test] pub fn test_af_alg_cipher() { - use nix::unistd::read; - use nix::sys::socket::{socket, sendmsg, bind, accept, setsockopt, - AddressFamily, SockType, SockFlag, AlgAddr, - ControlMessage, MsgFlags}; use nix::sys::socket::sockopt::AlgSetKey; + use nix::sys::socket::{ + accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr, + ControlMessage, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::read; use std::io::IoSlice; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1352"); @@ -704,8 +846,13 @@ pub fn test_af_alg_cipher() { let payload_len = 256; let payload = vec![2u8; payload_len]; - let sock = socket(AddressFamily::Alg, SockType::SeqPacket, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Alg, + SockType::SeqPacket, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = AlgAddr::new(alg_type, alg_name); bind(sock, &sockaddr).expect("bind failed"); @@ -716,9 +863,13 @@ pub fn test_af_alg_cipher() { setsockopt(sock, AlgSetKey::default(), &key).expect("setsockopt"); let session_socket = accept(sock).expect("accept failed"); - let msgs = [ControlMessage::AlgSetOp(&libc::ALG_OP_ENCRYPT), ControlMessage::AlgSetIv(iv.as_slice())]; + let msgs = [ + ControlMessage::AlgSetOp(&libc::ALG_OP_ENCRYPT), + ControlMessage::AlgSetIv(iv.as_slice()), + ]; let iov = IoSlice::new(&payload); - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg encrypt"); + sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg encrypt"); // allocate buffer for encrypted data let mut encrypted = vec![0u8; payload_len]; @@ -729,8 +880,12 @@ pub fn test_af_alg_cipher() { let iv = vec![1u8; iv_len]; - let msgs = [ControlMessage::AlgSetOp(&libc::ALG_OP_DECRYPT), ControlMessage::AlgSetIv(iv.as_slice())]; - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg decrypt"); + let msgs = [ + ControlMessage::AlgSetOp(&libc::ALG_OP_DECRYPT), + ControlMessage::AlgSetIv(iv.as_slice()), + ]; + sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg decrypt"); // allocate buffer for decrypted data let mut decrypted = vec![0u8; payload_len]; @@ -742,17 +897,18 @@ pub fn test_af_alg_cipher() { // Disable the test on emulated platforms due to not enabled support of AF_ALG // in QEMU from rust cross -#[cfg(any(target_os = "linux", target_os= "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg_attr(qemu, ignore)] #[test] pub fn test_af_alg_aead() { use libc::{ALG_OP_DECRYPT, ALG_OP_ENCRYPT}; use nix::fcntl::{fcntl, FcntlArg, OFlag}; - use nix::unistd::{read, close}; - use nix::sys::socket::{socket, sendmsg, bind, accept, setsockopt, - AddressFamily, SockType, SockFlag, AlgAddr, - ControlMessage, MsgFlags}; - use nix::sys::socket::sockopt::{AlgSetKey, AlgSetAeadAuthSize}; + use nix::sys::socket::sockopt::{AlgSetAeadAuthSize, AlgSetKey}; + use nix::sys::socket::{ + accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr, + ControlMessage, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::{close, read}; use std::io::IoSlice; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1352"); @@ -772,7 +928,8 @@ pub fn test_af_alg_aead() { let iv = vec![1u8; iv_len]; // 256-bytes plain payload let payload_len = 256; - let mut payload = vec![2u8; payload_len + (assoc_size as usize) + auth_size]; + let mut payload = + vec![2u8; payload_len + (assoc_size as usize) + auth_size]; for i in 0..assoc_size { payload[i as usize] = 10; @@ -784,26 +941,35 @@ pub fn test_af_alg_aead() { payload[len - 1 - i] = 0; } - let sock = socket(AddressFamily::Alg, SockType::SeqPacket, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Alg, + SockType::SeqPacket, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = AlgAddr::new(alg_type, alg_name); bind(sock, &sockaddr).expect("bind failed"); - setsockopt(sock, AlgSetAeadAuthSize, &auth_size).expect("setsockopt AlgSetAeadAuthSize"); + setsockopt(sock, AlgSetAeadAuthSize, &auth_size) + .expect("setsockopt AlgSetAeadAuthSize"); setsockopt(sock, AlgSetKey::default(), &key).expect("setsockopt AlgSetKey"); let session_socket = accept(sock).expect("accept failed"); let msgs = [ ControlMessage::AlgSetOp(&ALG_OP_ENCRYPT), ControlMessage::AlgSetIv(iv.as_slice()), - ControlMessage::AlgSetAeadAssoclen(&assoc_size)]; + ControlMessage::AlgSetAeadAssoclen(&assoc_size), + ]; let iov = IoSlice::new(&payload); - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg encrypt"); + sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg encrypt"); // allocate buffer for encrypted data - let mut encrypted = vec![0u8; (assoc_size as usize) + payload_len + auth_size]; + let mut encrypted = + vec![0u8; (assoc_size as usize) + payload_len + auth_size]; let num_bytes = read(session_socket, &mut encrypted).expect("read encrypt"); assert_eq!(num_bytes, payload_len + auth_size + (assoc_size as usize)); close(session_socket).expect("close"); @@ -823,19 +989,25 @@ pub fn test_af_alg_aead() { ControlMessage::AlgSetIv(iv.as_slice()), ControlMessage::AlgSetAeadAssoclen(&assoc_size), ]; - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg decrypt"); + sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg decrypt"); // allocate buffer for decrypted data - let mut decrypted = vec![0u8; payload_len + (assoc_size as usize) + auth_size]; + let mut decrypted = + vec![0u8; payload_len + (assoc_size as usize) + auth_size]; // Starting with kernel 4.9, the interface changed slightly such that the // authentication tag memory is only needed in the output buffer for encryption // and in the input buffer for decryption. // Do not block on read, as we may have fewer bytes than buffer size - fcntl(session_socket,FcntlArg::F_SETFL(OFlag::O_NONBLOCK)).expect("fcntl non_blocking"); + fcntl(session_socket, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)) + .expect("fcntl non_blocking"); let num_bytes = read(session_socket, &mut decrypted).expect("read decrypt"); assert!(num_bytes >= payload_len + (assoc_size as usize)); - assert_eq!(decrypted[(assoc_size as usize)..(payload_len + (assoc_size as usize))], payload[(assoc_size as usize)..payload_len + (assoc_size as usize)]); + assert_eq!( + decrypted[(assoc_size as usize)..(payload_len + (assoc_size as usize))], + payload[(assoc_size as usize)..payload_len + (assoc_size as usize)] + ); } // Verify `ControlMessage::Ipv4PacketInfo` for `sendmsg`. @@ -845,24 +1017,25 @@ pub fn test_af_alg_aead() { // This would be a more interesting test if we could assume that the test host // has more than one IP address (since we could select a different address to // test from). -#[cfg(any(target_os = "linux", - target_os = "macos", - target_os = "netbsd"))] +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd"))] #[test] pub fn test_sendmsg_ipv4packetinfo() { use cfg_if::cfg_if; - use nix::sys::socket::{socket, sendmsg, bind, - AddressFamily, SockType, SockFlag, SockaddrIn, - ControlMessage, MsgFlags}; + use nix::sys::socket::{ + bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags, + SockFlag, SockType, SockaddrIn, + }; use std::io::IoSlice; - let sock = socket(AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("socket failed"); - let sock_addr = SockaddrIn::new(127,0,0,1, 4000); + let sock_addr = SockaddrIn::new(127, 0, 0, 1, 4000); bind(sock, &sock_addr).expect("bind failed"); @@ -898,23 +1071,28 @@ pub fn test_sendmsg_ipv4packetinfo() { // This would be a more interesting test if we could assume that the test host // has more than one IP address (since we could select a different address to // test from). -#[cfg(any(target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "freebsd" +))] #[test] pub fn test_sendmsg_ipv6packetinfo() { use nix::errno::Errno; - use nix::sys::socket::{socket, sendmsg, bind, - AddressFamily, SockType, SockFlag, SockaddrIn6, - ControlMessage, MsgFlags}; + use nix::sys::socket::{ + bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags, + SockFlag, SockType, SockaddrIn6, + }; use std::io::IoSlice; - let sock = socket(AddressFamily::Inet6, - SockType::Datagram, - SockFlag::empty(), - None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap(); let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa); @@ -934,8 +1112,66 @@ pub fn test_sendmsg_ipv6packetinfo() { let cmsg = [ControlMessage::Ipv6PacketInfo(&pi)]; - sendmsg::(sock, &iov, &cmsg, MsgFlags::empty(), Some(&sock_addr)) - .expect("sendmsg"); + sendmsg::( + sock, + &iov, + &cmsg, + MsgFlags::empty(), + Some(&sock_addr), + ) + .expect("sendmsg"); +} + +// Verify that ControlMessage::Ipv4SendSrcAddr works for sendmsg. This +// creates a UDP socket bound to all local interfaces (0.0.0.0). It then +// sends message to itself at 127.0.0.1 while explicitly specifying +// 127.0.0.1 as the source address through an Ipv4SendSrcAddr +// (IP_SENDSRCADDR) control message. +// +// Note that binding to 0.0.0.0 is *required* on FreeBSD; sendmsg +// returns EINVAL otherwise. (See FreeBSD's ip(4) man page.) +#[cfg(any( + target_os = "netbsd", + target_os = "freebsd", + target_os = "openbsd", + target_os = "dragonfly", +))] +#[test] +pub fn test_sendmsg_ipv4sendsrcaddr() { + use nix::sys::socket::{ + bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags, + SockFlag, SockType, SockaddrIn, + }; + use std::io::IoSlice; + + let sock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("socket failed"); + + let unspec_sock_addr = SockaddrIn::new(0, 0, 0, 0, 0); + bind(sock, &unspec_sock_addr).expect("bind failed"); + let bound_sock_addr: SockaddrIn = getsockname(sock).unwrap(); + let localhost_sock_addr: SockaddrIn = + SockaddrIn::new(127, 0, 0, 1, bound_sock_addr.port()); + + let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let iov = [IoSlice::new(&slice)]; + let cmsg = [ControlMessage::Ipv4SendSrcAddr( + &localhost_sock_addr.as_ref().sin_addr, + )]; + + sendmsg( + sock, + &iov, + &cmsg, + MsgFlags::empty(), + Some(&localhost_sock_addr), + ) + .expect("sendmsg"); } /// Tests that passing multiple fds using a single `ControlMessage` works. @@ -944,12 +1180,13 @@ pub fn test_sendmsg_ipv6packetinfo() { #[cfg_attr(qemu, ignore)] #[test] fn test_scm_rights_single_cmsg_multiple_fds() { + use nix::sys::socket::{ + recvmsg, sendmsg, ControlMessage, ControlMessageOwned, MsgFlags, + }; + use std::io::{IoSlice, IoSliceMut}; + use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixDatagram; - use std::os::unix::io::{RawFd, AsRawFd}; use std::thread; - use nix::sys::socket::{ControlMessage, ControlMessageOwned, MsgFlags, - sendmsg, recvmsg}; - use std::io::{IoSlice, IoSliceMut}; let (send, receive) = UnixDatagram::pair().unwrap(); let thread = thread::spawn(move || { @@ -961,17 +1198,23 @@ fn test_scm_rights_single_cmsg_multiple_fds() { receive.as_raw_fd(), &mut iovec, Some(&mut space), - MsgFlags::empty() - ).unwrap(); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + MsgFlags::empty(), + ) + .unwrap(); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); let mut cmsgs = msg.cmsgs(); match cmsgs.next() { Some(ControlMessageOwned::ScmRights(fds)) => { - assert_eq!(fds.len(), 2, - "unexpected fd count (expected 2 fds, got {})", - fds.len()); - }, + assert_eq!( + fds.len(), + 2, + "unexpected fd count (expected 2 fds, got {})", + fds.len() + ); + } _ => panic!(), } assert!(cmsgs.next().is_none(), "unexpected control msg"); @@ -982,9 +1225,10 @@ fn test_scm_rights_single_cmsg_multiple_fds() { let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; let iov = [IoSlice::new(&slice)]; - let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout + let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout let cmsg = [ControlMessage::ScmRights(&fds)]; - sendmsg::<()>(send.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), None).unwrap(); + sendmsg::<()>(send.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), None) + .unwrap(); thread.join().unwrap(); } @@ -994,17 +1238,27 @@ fn test_scm_rights_single_cmsg_multiple_fds() { // raw `sendmsg`. #[test] pub fn test_sendmsg_empty_cmsgs() { + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, MsgFlags, SockFlag, + SockType, + }; use nix::unistd::close; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, MsgFlags}; use std::io::{IoSlice, IoSliceMut}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); { let iov = [IoSlice::new(b"hello")]; - assert_eq!(sendmsg::<()>(fd1, &iov, &[], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(fd1, &iov, &[], MsgFlags::empty(), None).unwrap(), + 5 + ); close(fd1).unwrap(); } @@ -1013,12 +1267,20 @@ pub fn test_sendmsg_empty_cmsgs() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!([RawFd; 1]); - let msg = recvmsg::<()>(fd2, &mut iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); + let msg = recvmsg::<()>( + fd2, + &mut iov, + Some(&mut cmsgspace), + MsgFlags::empty(), + ) + .unwrap(); for _ in msg.cmsgs() { panic!("unexpected cmsg"); } - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); assert_eq!(msg.bytes, 5); close(fd2).unwrap(); } @@ -1032,17 +1294,22 @@ pub fn test_sendmsg_empty_cmsgs() { ))] #[test] fn test_scm_credentials() { - use nix::unistd::{close, getpid, getuid, getgid}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, - ControlMessage, ControlMessageOwned, MsgFlags, - UnixCredentials}; + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage, + ControlMessageOwned, MsgFlags, SockFlag, SockType, UnixCredentials, + }; #[cfg(any(target_os = "android", target_os = "linux"))] use nix::sys::socket::{setsockopt, sockopt::PassCred}; + use nix::unistd::{close, getgid, getpid, getuid}; use std::io::{IoSlice, IoSliceMut}; - let (send, recv) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (send, recv) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); #[cfg(any(target_os = "android", target_os = "linux"))] setsockopt(recv, PassCred, &true).unwrap(); @@ -1054,7 +1321,11 @@ fn test_scm_credentials() { let cmsg = ControlMessage::ScmCredentials(&cred); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] let cmsg = ControlMessage::ScmCreds; - assert_eq!(sendmsg::<()>(send, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(send, &iov, &[cmsg], MsgFlags::empty(), None) + .unwrap(), + 5 + ); close(send).unwrap(); } @@ -1063,7 +1334,13 @@ fn test_scm_credentials() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!(UnixCredentials); - let msg = recvmsg::<()>(recv, &mut iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); + let msg = recvmsg::<()>( + recv, + &mut iov, + Some(&mut cmsgspace), + MsgFlags::empty(), + ) + .unwrap(); let mut received_cred = None; for cmsg in msg.cmsgs() { @@ -1082,7 +1359,9 @@ fn test_scm_credentials() { } received_cred.expect("no creds received"); assert_eq!(msg.bytes, 5); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); close(recv).unwrap(); } } @@ -1114,15 +1393,21 @@ fn test_too_large_cmsgspace() { #[cfg(any(target_os = "android", target_os = "linux"))] fn test_impl_scm_credentials_and_rights(mut space: Vec) { use libc::ucred; - use nix::unistd::{pipe, write, close, getpid, getuid, getgid}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, setsockopt, - SockType, SockFlag, - ControlMessage, ControlMessageOwned, MsgFlags}; use nix::sys::socket::sockopt::PassCred; + use nix::sys::socket::{ + recvmsg, sendmsg, setsockopt, socketpair, ControlMessage, + ControlMessageOwned, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::{close, getgid, getpid, getuid, pipe, write}; use std::io::{IoSlice, IoSliceMut}; - let (send, recv) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (send, recv) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); setsockopt(recv, PassCred, &true).unwrap(); let (r, w) = pipe().unwrap(); @@ -1134,13 +1419,17 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { pid: getpid().as_raw(), uid: getuid().as_raw(), gid: getgid().as_raw(), - }.into(); + } + .into(); let fds = [r]; let cmsgs = [ ControlMessage::ScmCredentials(&cred), ControlMessage::ScmRights(&fds), ]; - assert_eq!(sendmsg::<()>(send, &iov, &cmsgs, MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(send, &iov, &cmsgs, MsgFlags::empty(), None).unwrap(), + 5 + ); close(r).unwrap(); close(send).unwrap(); } @@ -1148,7 +1437,9 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { { let mut buf = [0u8; 5]; let mut iov = [IoSliceMut::new(&mut buf[..])]; - let msg = recvmsg::<()>(recv, &mut iov, Some(&mut space), MsgFlags::empty()).unwrap(); + let msg = + recvmsg::<()>(recv, &mut iov, Some(&mut space), MsgFlags::empty()) + .unwrap(); let mut received_cred = None; assert_eq!(msg.cmsgs().count(), 2, "expected 2 cmsgs"); @@ -1172,7 +1463,9 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { } received_cred.expect("no creds received"); assert_eq!(msg.bytes, 5); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); close(recv).unwrap(); } @@ -1189,22 +1482,32 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { // Test creating and using named unix domain sockets #[test] pub fn test_unixdomain() { - use nix::sys::socket::{SockType, SockFlag}; - use nix::sys::socket::{bind, socket, connect, listen, accept, UnixAddr}; - use nix::unistd::{read, write, close}; + use nix::sys::socket::{accept, bind, connect, listen, socket, UnixAddr}; + use nix::sys::socket::{SockFlag, SockType}; + use nix::unistd::{close, read, write}; use std::thread; let tempdir = tempfile::tempdir().unwrap(); let sockname = tempdir.path().join("sock"); - let s1 = socket(AddressFamily::Unix, SockType::Stream, - SockFlag::empty(), None).expect("socket failed"); + let s1 = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { - let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None) - .expect("socket failed"); + let s2 = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); @@ -1212,7 +1515,7 @@ pub fn test_unixdomain() { let s3 = accept(s1).expect("accept failed"); - let mut buf = [0;5]; + let mut buf = [0; 5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); @@ -1226,14 +1529,23 @@ pub fn test_unixdomain() { #[test] pub fn test_syscontrol() { use nix::errno::Errno; - use nix::sys::socket::{socket, SysControlAddr, SockType, SockFlag, SockProtocol}; + use nix::sys::socket::{ + socket, SockFlag, SockProtocol, SockType, SysControlAddr, + }; - let fd = socket(AddressFamily::System, SockType::Datagram, - SockFlag::empty(), SockProtocol::KextControl) - .expect("socket failed"); + let fd = socket( + AddressFamily::System, + SockType::Datagram, + SockFlag::empty(), + SockProtocol::KextControl, + ) + .expect("socket failed"); SysControlAddr::from_name(fd, "com.apple.net.utun_control", 0) .expect("resolving sys_control name failed"); - assert_eq!(SysControlAddr::from_name(fd, "foo.bar.lol", 0).err(), Some(Errno::ENOENT)); + assert_eq!( + SysControlAddr::from_name(fd, "foo.bar.lol", 0).err(), + Some(Errno::ENOENT) + ); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); @@ -1248,31 +1560,30 @@ pub fn test_syscontrol() { target_os = "netbsd", target_os = "openbsd", ))] -fn loopback_address(family: AddressFamily) -> Option { - use std::io; - use std::io::Write; +fn loopback_address( + family: AddressFamily, +) -> Option { use nix::ifaddrs::getifaddrs; use nix::net::if_::*; use nix::sys::socket::SockaddrLike; + use std::io; + use std::io::Write; - let addrs = match getifaddrs() { + let mut addrs = match getifaddrs() { Ok(iter) => iter, Err(e) => { let stdioerr = io::stderr(); let mut handle = stdioerr.lock(); writeln!(handle, "getifaddrs: {:?}", e).unwrap(); return None; - }, + } }; // return first address matching family - for ifaddr in addrs { - if ifaddr.flags.contains(InterfaceFlags::IFF_LOOPBACK) && - ifaddr.address.as_ref().and_then(SockaddrLike::family) == Some(family) - { - return Some(ifaddr) - } - } - None + addrs.find(|ifaddr| { + ifaddr.flags.contains(InterfaceFlags::IFF_LOOPBACK) + && ifaddr.address.as_ref().and_then(SockaddrLike::family) + == Some(family) + }) } #[cfg(any( @@ -1283,35 +1594,41 @@ fn loopback_address(family: AddressFamily) -> Option (ifaddr.interface_name, - ifaddr.address.expect("Expect IPv4 address on interface")), + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv4 address on interface"), + ), None => return, }; let receive = socket( - AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None, - ).expect("receive socket failed"); + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("receive socket failed"); bind(receive, &lo).expect("bind failed"); let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); setsockopt(receive, Ipv4PacketInfo, &true).expect("setsockopt failed"); @@ -1325,8 +1642,10 @@ pub fn test_recv_ipv4pktinfo() { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)).expect("sendmsg failed"); + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); } { @@ -1339,29 +1658,25 @@ pub fn test_recv_ipv4pktinfo() { &mut iovec, Some(&mut space), MsgFlags::empty(), - ).expect("recvmsg failed"); - assert!( - !msg.flags - .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) - ); + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); let mut cmsgs = msg.cmsgs(); - if let Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) = cmsgs.next() { + if let Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) = cmsgs.next() + { let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex"); assert_eq!( - pktinfo.ipi_ifindex as libc::c_uint, - i, + pktinfo.ipi_ifindex as libc::c_uint, i, "unexpected ifindex (expected {}, got {})", - i, - pktinfo.ipi_ifindex + i, pktinfo.ipi_ifindex ); } assert!(cmsgs.next().is_none(), "unexpected additional control msg"); assert_eq!(msg.bytes, 8); - assert_eq!( - *iovec[0], - [1u8, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); } } @@ -1373,27 +1688,32 @@ pub fn test_recv_ipv4pktinfo() { target_os = "openbsd", ))] // qemu doesn't seem to be emulating this correctly in these architectures -#[cfg_attr(all( - qemu, - any( - target_arch = "mips", - target_arch = "mips64", - target_arch = "powerpc64", - ) -), ignore)] +#[cfg_attr( + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc64", + ) + ), + ignore +)] #[test] pub fn test_recvif() { use nix::net::if_::*; - use nix::sys::socket::sockopt::{Ipv4RecvIf, Ipv4RecvDstAddr}; - use nix::sys::socket::{bind, SockaddrIn, SockFlag, SockType}; + use nix::sys::socket::sockopt::{Ipv4RecvDstAddr, Ipv4RecvIf}; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn}; use nix::sys::socket::{getsockname, setsockopt, socket}; use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; use std::io::{IoSlice, IoSliceMut}; let lo_ifaddr = loopback_address(AddressFamily::Inet); let (lo_name, lo) = match lo_ifaddr { - Some(ifaddr) => (ifaddr.interface_name, - ifaddr.address.expect("Expect IPv4 address on interface")), + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv4 address on interface"), + ), None => return, }; let receive = socket( @@ -1401,11 +1721,14 @@ pub fn test_recvif() { SockType::Datagram, SockFlag::empty(), None, - ).expect("receive socket failed"); + ) + .expect("receive socket failed"); bind(receive, &lo).expect("bind failed"); let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv4RecvIf, &true).expect("setsockopt IP_RECVIF failed"); - setsockopt(receive, Ipv4RecvDstAddr, &true).expect("setsockopt IP_RECVDSTADDR failed"); + setsockopt(receive, Ipv4RecvIf, &true) + .expect("setsockopt IP_RECVIF failed"); + setsockopt(receive, Ipv4RecvDstAddr, &true) + .expect("setsockopt IP_RECVDSTADDR failed"); { let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; @@ -1416,8 +1739,10 @@ pub fn test_recvif() { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)).expect("sendmsg failed"); + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); } { @@ -1429,11 +1754,11 @@ pub fn test_recvif() { &mut iovec, Some(&mut space), MsgFlags::empty(), - ).expect("recvmsg failed"); - assert!( - !msg.flags - .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) - ); + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); assert_eq!(msg.cmsgs().count(), 2, "expected 2 cmsgs"); let mut rx_recvif = false; @@ -1442,15 +1767,14 @@ pub fn test_recvif() { match cmsg { ControlMessageOwned::Ipv4RecvIf(dl) => { rx_recvif = true; - let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex"); + let i = if_nametoindex(lo_name.as_bytes()) + .expect("if_nametoindex"); assert_eq!( - dl.sdl_index as libc::c_uint, - i, + dl.sdl_index as libc::c_uint, i, "unexpected ifindex (expected {}, got {})", - i, - dl.sdl_index + i, dl.sdl_index ); - }, + } ControlMessageOwned::Ipv4RecvDstAddr(addr) => { rx_recvdstaddr = true; if let Some(sin) = lo.as_sockaddr_in() { @@ -1462,17 +1786,184 @@ pub fn test_recvif() { } else { panic!("unexpected Sockaddr"); } - }, + } _ => panic!("unexpected additional control msg"), } } assert!(rx_recvif); assert!(rx_recvdstaddr); assert_eq!(msg.bytes, 8); - assert_eq!( - *iovec[0], - [1u8, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); + } +} + +#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg_attr(qemu, ignore)] +#[test] +pub fn test_recvif_ipv4() { + use nix::sys::socket::sockopt::Ipv4OrigDstAddr; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn}; + use nix::sys::socket::{getsockname, setsockopt, socket}; + use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; + use std::io::{IoSlice, IoSliceMut}; + + let lo_ifaddr = loopback_address(AddressFamily::Inet); + let (_lo_name, lo) = match lo_ifaddr { + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv4 address on interface"), + ), + None => return, + }; + let receive = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("receive socket failed"); + bind(receive, &lo).expect("bind failed"); + let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); + setsockopt(receive, Ipv4OrigDstAddr, &true) + .expect("setsockopt IP_ORIGDSTADDR failed"); + + { + let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let iov = [IoSlice::new(&slice)]; + + let send = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); + } + + { + let mut buf = [0u8; 8]; + let mut iovec = [IoSliceMut::new(&mut buf)]; + let mut space = cmsg_space!(libc::sockaddr_in); + let msg = recvmsg::<()>( + receive, + &mut iovec, + Some(&mut space), + MsgFlags::empty(), + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert_eq!(msg.cmsgs().count(), 1, "expected 1 cmsgs"); + + let mut rx_recvorigdstaddr = false; + for cmsg in msg.cmsgs() { + match cmsg { + ControlMessageOwned::Ipv4OrigDstAddr(addr) => { + rx_recvorigdstaddr = true; + if let Some(sin) = lo.as_sockaddr_in() { + assert_eq!(sin.as_ref().sin_addr.s_addr, + addr.sin_addr.s_addr, + "unexpected destination address (expected {}, got {})", + sin.as_ref().sin_addr.s_addr, + addr.sin_addr.s_addr); + } else { + panic!("unexpected Sockaddr"); + } + } + _ => panic!("unexpected additional control msg"), + } + } + assert!(rx_recvorigdstaddr); + assert_eq!(msg.bytes, 8); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); + } +} + +#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg_attr(qemu, ignore)] +#[test] +pub fn test_recvif_ipv6() { + use nix::sys::socket::sockopt::Ipv6OrigDstAddr; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn6}; + use nix::sys::socket::{getsockname, setsockopt, socket}; + use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; + use std::io::{IoSlice, IoSliceMut}; + + let lo_ifaddr = loopback_address(AddressFamily::Inet6); + let (_lo_name, lo) = match lo_ifaddr { + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv6 address on interface"), + ), + None => return, + }; + let receive = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("receive socket failed"); + bind(receive, &lo).expect("bind failed"); + let sa: SockaddrIn6 = getsockname(receive).expect("getsockname failed"); + setsockopt(receive, Ipv6OrigDstAddr, &true) + .expect("setsockopt IP_ORIGDSTADDR failed"); + + { + let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let iov = [IoSlice::new(&slice)]; + + let send = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); + } + + { + let mut buf = [0u8; 8]; + let mut iovec = [IoSliceMut::new(&mut buf)]; + let mut space = cmsg_space!(libc::sockaddr_in6); + let msg = recvmsg::<()>( + receive, + &mut iovec, + Some(&mut space), + MsgFlags::empty(), + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert_eq!(msg.cmsgs().count(), 1, "expected 1 cmsgs"); + + let mut rx_recvorigdstaddr = false; + for cmsg in msg.cmsgs() { + match cmsg { + ControlMessageOwned::Ipv6OrigDstAddr(addr) => { + rx_recvorigdstaddr = true; + if let Some(sin) = lo.as_sockaddr_in6() { + assert_eq!(sin.as_ref().sin6_addr.s6_addr, + addr.sin6_addr.s6_addr, + "unexpected destination address (expected {:?}, got {:?})", + sin.as_ref().sin6_addr.s6_addr, + addr.sin6_addr.s6_addr); + } else { + panic!("unexpected Sockaddr"); + } + } + _ => panic!("unexpected additional control msg"), + } + } + assert!(rx_recvorigdstaddr); + assert_eq!(msg.bytes, 8); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); } } @@ -1486,27 +1977,32 @@ pub fn test_recvif() { target_os = "openbsd", ))] // qemu doesn't seem to be emulating this correctly in these architectures -#[cfg_attr(all( - qemu, - any( - target_arch = "mips", - target_arch = "mips64", - target_arch = "powerpc64", - ) -), ignore)] +#[cfg_attr( + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc64", + ) + ), + ignore +)] #[test] pub fn test_recv_ipv6pktinfo() { use nix::net::if_::*; use nix::sys::socket::sockopt::Ipv6RecvPacketInfo; - use nix::sys::socket::{bind, SockaddrIn6, SockFlag, SockType}; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn6}; use nix::sys::socket::{getsockname, setsockopt, socket}; use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; use std::io::{IoSlice, IoSliceMut}; let lo_ifaddr = loopback_address(AddressFamily::Inet6); let (lo_name, lo) = match lo_ifaddr { - Some(ifaddr) => (ifaddr.interface_name, - ifaddr.address.expect("Expect IPv4 address on interface")), + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv6 address on interface"), + ), None => return, }; let receive = socket( @@ -1514,7 +2010,8 @@ pub fn test_recv_ipv6pktinfo() { SockType::Datagram, SockFlag::empty(), None, - ).expect("receive socket failed"); + ) + .expect("receive socket failed"); bind(receive, &lo).expect("bind failed"); let sa: SockaddrIn6 = getsockname(receive).expect("getsockname failed"); setsockopt(receive, Ipv6RecvPacketInfo, &true).expect("setsockopt failed"); @@ -1528,8 +2025,10 @@ pub fn test_recv_ipv6pktinfo() { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)).expect("sendmsg failed"); + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); } { @@ -1542,30 +2041,25 @@ pub fn test_recv_ipv6pktinfo() { &mut iovec, Some(&mut space), MsgFlags::empty(), - ).expect("recvmsg failed"); - assert!( - !msg.flags - .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) - ); + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); let mut cmsgs = msg.cmsgs(); if let Some(ControlMessageOwned::Ipv6PacketInfo(pktinfo)) = cmsgs.next() { let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex"); assert_eq!( - pktinfo.ipi6_ifindex as libc::c_uint, - i, + pktinfo.ipi6_ifindex as libc::c_uint, i, "unexpected ifindex (expected {}, got {})", - i, - pktinfo.ipi6_ifindex + i, pktinfo.ipi6_ifindex ); } assert!(cmsgs.next().is_none(), "unexpected additional control msg"); assert_eq!(msg.bytes, 8); - assert_eq!( - *iovec[0], - [1u8, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); } } @@ -1574,21 +2068,26 @@ pub fn test_recv_ipv6pktinfo() { #[test] pub fn test_vsock() { use nix::errno::Errno; - use nix::sys::socket::{AddressFamily, socket, bind, connect, listen, - SockType, SockFlag, VsockAddr}; - use nix::unistd::{close}; + use nix::sys::socket::{ + bind, connect, listen, socket, AddressFamily, SockFlag, SockType, + VsockAddr, + }; + use nix::unistd::close; use std::thread; let port: u32 = 3000; - let s1 = socket(AddressFamily::Vsock, SockType::Stream, - SockFlag::empty(), None) - .expect("socket failed"); + let s1 = socket( + AddressFamily::Vsock, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); // VMADDR_CID_HYPERVISOR is reserved, so we expect an EADDRNOTAVAIL error. let sockaddr_hv = VsockAddr::new(libc::VMADDR_CID_HYPERVISOR, port); - assert_eq!(bind(s1, &sockaddr_hv).err(), - Some(Errno::EADDRNOTAVAIL)); + assert_eq!(bind(s1, &sockaddr_hv).err(), Some(Errno::EADDRNOTAVAIL)); let sockaddr_any = VsockAddr::new(libc::VMADDR_CID_ANY, port); assert_eq!(bind(s1, &sockaddr_any), Ok(())); @@ -1597,9 +2096,13 @@ pub fn test_vsock() { let thr = thread::spawn(move || { let cid: u32 = libc::VMADDR_CID_HOST; - let s2 = socket(AddressFamily::Vsock, SockType::Stream, - SockFlag::empty(), None) - .expect("socket failed"); + let s2 = socket( + AddressFamily::Vsock, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr_host = VsockAddr::new(cid, port); @@ -1621,8 +2124,8 @@ pub fn test_vsock() { #[test] fn test_recvmsg_timestampns() { use nix::sys::socket::*; - use std::io::{IoSlice, IoSliceMut}; use nix::sys::time::*; + use std::io::{IoSlice, IoSliceMut}; use std::time::*; // Set up @@ -1631,7 +2134,9 @@ fn test_recvmsg_timestampns() { AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); setsockopt(in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); let localhost = SockaddrIn::new(127, 0, 0, 1, 0); bind(in_socket, &localhost).unwrap(); @@ -1648,18 +2153,19 @@ fn test_recvmsg_timestampns() { let mut cmsgspace = nix::cmsg_space!(TimeSpec); let mut iov = [IoSliceMut::new(&mut buffer)]; - let r = recvmsg::<()>(in_socket, &mut iov, Some(&mut cmsgspace), flags).unwrap(); + let r = recvmsg::<()>(in_socket, &mut iov, Some(&mut cmsgspace), flags) + .unwrap(); let rtime = match r.cmsgs().next() { Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime, Some(_) => panic!("Unexpected control message"), - None => panic!("No control message") + None => panic!("No control message"), }; // Check the final time let time1 = SystemTime::now(); // the packet's received timestamp should lie in-between the two system // times, unless the system clock was adjusted in the meantime. - let rduration = Duration::new(rtime.tv_sec() as u64, - rtime.tv_nsec() as u32); + let rduration = + Duration::new(rtime.tv_sec() as u64, rtime.tv_nsec() as u32); assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration); assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap()); // Close socket @@ -1673,8 +2179,8 @@ fn test_recvmsg_timestampns() { #[test] fn test_recvmmsg_timestampns() { use nix::sys::socket::*; - use std::io::{IoSlice, IoSliceMut}; use nix::sys::time::*; + use std::io::{IoSlice, IoSliceMut}; use std::time::*; // Set up @@ -1683,7 +2189,9 @@ fn test_recvmmsg_timestampns() { AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); setsockopt(in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); bind(in_socket, &localhost).unwrap(); @@ -1699,24 +2207,23 @@ fn test_recvmmsg_timestampns() { let mut buffer = vec![0u8; message.len()]; let mut cmsgspace = nix::cmsg_space!(TimeSpec); let iov = [IoSliceMut::new(&mut buffer)]; - let mut data = vec![ - RecvMmsgData { - iov, - cmsg_buffer: Some(&mut cmsgspace), - }, - ]; - let r: Vec> = recvmmsg(in_socket, &mut data, flags, None).unwrap(); + let mut data = vec![RecvMmsgData { + iov, + cmsg_buffer: Some(&mut cmsgspace), + }]; + let r: Vec> = + recvmmsg(in_socket, &mut data, flags, None).unwrap(); let rtime = match r[0].cmsgs().next() { Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime, Some(_) => panic!("Unexpected control message"), - None => panic!("No control message") + None => panic!("No control message"), }; // Check the final time let time1 = SystemTime::now(); // the packet's received timestamp should lie in-between the two system // times, unless the system clock was adjusted in the meantime. - let rduration = Duration::new(rtime.tv_sec() as u64, - rtime.tv_nsec() as u32); + let rduration = + Duration::new(rtime.tv_sec() as u64, rtime.tv_nsec() as u32); assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration); assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap()); // Close socket @@ -1729,10 +2236,10 @@ fn test_recvmmsg_timestampns() { #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] #[test] fn test_recvmsg_rxq_ovfl() { - use nix::Error; + use nix::sys::socket::sockopt::{RcvBuf, RxqOvfl}; use nix::sys::socket::*; + use nix::Error; use std::io::{IoSlice, IoSliceMut}; - use nix::sys::socket::sockopt::{RxqOvfl, RcvBuf}; let message = [0u8; 2048]; let bufsize = message.len() * 2; @@ -1741,12 +2248,16 @@ fn test_recvmsg_rxq_ovfl() { AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); let out_socket = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); bind(in_socket, &localhost).unwrap(); @@ -1769,7 +2280,8 @@ fn test_recvmsg_rxq_ovfl() { // Send the 3 messages (the receiver buffer can only hold 2 messages) // to create an overflow. for _ in 0..3 { - let l = sendmsg(out_socket, &iov, &[], flags, Some(&address)).unwrap(); + let l = + sendmsg(out_socket, &iov, &[], flags, Some(&address)).unwrap(); assert_eq!(message.len(), l); } @@ -1784,16 +2296,23 @@ fn test_recvmsg_rxq_ovfl() { in_socket, &mut iov, Some(&mut cmsgspace), - MsgFlags::MSG_DONTWAIT) { + MsgFlags::MSG_DONTWAIT, + ) { Ok(r) => { drop_counter = match r.cmsgs().next() { - Some(ControlMessageOwned::RxqOvfl(drop_counter)) => drop_counter, + Some(ControlMessageOwned::RxqOvfl(drop_counter)) => { + drop_counter + } Some(_) => panic!("Unexpected control message"), None => 0, }; - }, - Err(Error::EAGAIN) => { break; }, - _ => { panic!("unknown recvmsg() error"); }, + } + Err(Error::EAGAIN) => { + break; + } + _ => { + panic!("unknown recvmsg() error"); + } } } } @@ -1806,13 +2325,10 @@ fn test_recvmsg_rxq_ovfl() { nix::unistd::close(out_socket).unwrap(); } -#[cfg(any( - target_os = "linux", - target_os = "android", -))] +#[cfg(any(target_os = "linux", target_os = "android",))] mod linux_errqueue { - use nix::sys::socket::*; use super::FromStr; + use nix::sys::socket::*; // Send a UDP datagram to a bogus destination address and observe an ICMP error (v4). // @@ -1840,11 +2356,16 @@ mod linux_errqueue { // Closure handles protocol-specific testing and returns generic sock_extended_err for // protocol-independent test impl. |cmsg| { - if let ControlMessageOwned::Ipv4RecvErr(ext_err, err_addr) = cmsg { + if let ControlMessageOwned::Ipv4RecvErr(ext_err, err_addr) = + cmsg + { if let Some(origin) = err_addr { // Validate that our network error originated from 127.0.0.1:0. assert_eq!(origin.sin_family, AddressFamily::Inet as _); - assert_eq!(origin.sin_addr.s_addr, u32::from_be(0x7f000001)); + assert_eq!( + origin.sin_addr.s_addr, + u32::from_be(0x7f000001) + ); assert_eq!(origin.sin_port, 0); } else { panic!("Expected some error origin"); @@ -1883,10 +2404,15 @@ mod linux_errqueue { // Closure handles protocol-specific testing and returns generic sock_extended_err for // protocol-independent test impl. |cmsg| { - if let ControlMessageOwned::Ipv6RecvErr(ext_err, err_addr) = cmsg { + if let ControlMessageOwned::Ipv6RecvErr(ext_err, err_addr) = + cmsg + { if let Some(origin) = err_addr { // Validate that our network error originated from localhost:0. - assert_eq!(origin.sin6_family, AddressFamily::Inet6 as _); + assert_eq!( + origin.sin6_family, + AddressFamily::Inet6 as _ + ); assert_eq!( origin.sin6_addr.s6_addr, std::net::Ipv6Addr::LOCALHOST.octets() @@ -1903,16 +2429,17 @@ mod linux_errqueue { ) } - fn test_recverr_impl(sa: &str, - af: AddressFamily, - opt: OPT, - ee_origin: u8, - ee_type: u8, - ee_code: u8, - testf: TESTF) - where - OPT: SetSockOpt, - TESTF: FnOnce(&ControlMessageOwned) -> libc::sock_extended_err, + fn test_recverr_impl( + sa: &str, + af: AddressFamily, + opt: OPT, + ee_origin: u8, + ee_type: u8, + ee_code: u8, + testf: TESTF, + ) where + OPT: SetSockOpt, + TESTF: FnOnce(&ControlMessageOwned) -> libc::sock_extended_err, { use nix::errno::Errno; use std::io::IoSliceMut; @@ -1920,9 +2447,15 @@ mod linux_errqueue { const MESSAGE_CONTENTS: &str = "ABCDEF"; let std_sa = std::net::SocketAddr::from_str(sa).unwrap(); let sock_addr = SockaddrStorage::from(std_sa); - let sock = socket(af, SockType::Datagram, SockFlag::SOCK_CLOEXEC, None).unwrap(); + let sock = socket(af, SockType::Datagram, SockFlag::SOCK_CLOEXEC, None) + .unwrap(); setsockopt(sock, opt, &true).unwrap(); - if let Err(e) = sendto(sock, MESSAGE_CONTENTS.as_bytes(), &sock_addr, MsgFlags::empty()) { + if let Err(e) = sendto( + sock, + MESSAGE_CONTENTS.as_bytes(), + &sock_addr, + MsgFlags::empty(), + ) { assert_eq!(e, Errno::EADDRNOTAVAIL); println!("{:?} not available, skipping test.", af); return; @@ -1932,7 +2465,13 @@ mod linux_errqueue { let mut iovec = [IoSliceMut::new(&mut buf)]; let mut cspace = cmsg_space!(libc::sock_extended_err, SA); - let msg = recvmsg(sock, &mut iovec, Some(&mut cspace), MsgFlags::MSG_ERRQUEUE).unwrap(); + let msg = recvmsg( + sock, + &mut iovec, + Some(&mut cspace), + MsgFlags::MSG_ERRQUEUE, + ) + .unwrap(); // The sent message / destination associated with the error is returned: assert_eq!(msg.bytes, MESSAGE_CONTENTS.as_bytes().len()); // recvmsg(2): "The original destination address of the datagram that caused the error is @@ -1969,10 +2508,10 @@ mod linux_errqueue { pub fn test_txtime() { use nix::sys::socket::{ bind, recvmsg, sendmsg, setsockopt, socket, sockopt, ControlMessage, - MsgFlags, SockaddrIn, SockFlag, SockType, + MsgFlags, SockFlag, SockType, SockaddrIn, }; use nix::sys::time::TimeValLike; - use nix::time::{ClockId, clock_gettime}; + use nix::time::{clock_gettime, ClockId}; require_kernel_version!(test_txtime, ">= 5.8"); @@ -2009,7 +2548,8 @@ pub fn test_txtime() { let txtime = (now + delay).num_nanoseconds() as u64; let cmsg = ControlMessage::TxTime(&txtime); - sendmsg(ssock, &iov1, &[cmsg], MsgFlags::empty(), Some(&sock_addr)).unwrap(); + sendmsg(ssock, &iov1, &[cmsg], MsgFlags::empty(), Some(&sock_addr)) + .unwrap(); let mut rbuf = [0u8; 2048]; let mut iov2 = [std::io::IoSliceMut::new(&mut rbuf)]; diff --git a/bash-5.1/vendor/nix/test/sys/test_sockopt.rs b/bash-5.1/vendor/nix/test/sys/test_sockopt.rs index 4f75e17..2ddbf77 100644 --- a/bash-5.1/vendor/nix/test/sys/test_sockopt.rs +++ b/bash-5.1/vendor/nix/test/sys/test_sockopt.rs @@ -1,22 +1,27 @@ -use rand::{thread_rng, Rng}; -use nix::sys::socket::{socket, sockopt, getsockopt, setsockopt, AddressFamily, SockType, SockFlag, SockProtocol}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::*; +use nix::sys::socket::{ + getsockopt, setsockopt, socket, sockopt, AddressFamily, SockFlag, + SockProtocol, SockType, +}; +use rand::{thread_rng, Rng}; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", -))] +#[cfg(any(target_os = "dragonfly", target_os = "freebsd",))] #[test] pub fn test_local_peercred_seqpacket() { use nix::{ + sys::socket::socketpair, unistd::{Gid, Uid}, - sys::socket::socketpair }; - let (fd1, _fd2) = socketpair(AddressFamily::Unix, SockType::SeqPacket, None, - SockFlag::empty()).unwrap(); + let (fd1, _fd2) = socketpair( + AddressFamily::Unix, + SockType::SeqPacket, + None, + SockFlag::empty(), + ) + .unwrap(); let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.version(), 0); assert_eq!(Uid::from_raw(xucred.uid()), Uid::current()); @@ -24,20 +29,25 @@ pub fn test_local_peercred_seqpacket() { } #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "ios" + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "ios" ))] #[test] pub fn test_local_peercred_stream() { use nix::{ + sys::socket::socketpair, unistd::{Gid, Uid}, - sys::socket::socketpair }; - let (fd1, _fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, - SockFlag::empty()).unwrap(); + let (fd1, _fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.version(), 0); assert_eq!(Uid::from_raw(xucred.uid()), Uid::current()); @@ -51,7 +61,13 @@ fn is_so_mark_functional() { require_capability!("is_so_mark_functional", CAP_NET_ADMIN); - let s = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let s = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(s, sockopt::Mark, &1337).unwrap(); let mark = getsockopt(s, sockopt::Mark).unwrap(); assert_eq!(mark, 1337); @@ -59,8 +75,13 @@ fn is_so_mark_functional() { #[test] fn test_so_buf() { - let fd = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), SockProtocol::Udp) - .unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + SockProtocol::Udp, + ) + .unwrap(); let bufsize: usize = thread_rng().gen_range(4096..131_072); setsockopt(fd, sockopt::SndBuf, &bufsize).unwrap(); let actual = getsockopt(fd, sockopt::SndBuf).unwrap(); @@ -72,16 +93,21 @@ fn test_so_buf() { #[test] fn test_so_tcp_maxseg() { - use std::net::SocketAddrV4; - use std::str::FromStr; use nix::sys::socket::{accept, bind, connect, listen, SockaddrIn}; use nix::unistd::{close, write}; + use std::net::SocketAddrV4; + use std::str::FromStr; let std_sa = SocketAddrV4::from_str("127.0.0.1:4001").unwrap(); let sock_addr = SockaddrIn::from(std_sa); - let rsock = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp) - .unwrap(); + let rsock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); listen(rsock, 10).unwrap(); let initial = getsockopt(rsock, sockopt::TcpMaxSeg).unwrap(); @@ -99,8 +125,13 @@ fn test_so_tcp_maxseg() { } // Connect and check the MSS that was advertised - let ssock = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp) - .unwrap(); + let ssock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); connect(ssock, &sock_addr).unwrap(); let rsess = accept(rsock).unwrap(); write(rsess, b"hello").unwrap(); @@ -132,17 +163,25 @@ fn test_so_tcp_maxseg() { fn test_tcp_congestion() { use std::ffi::OsString; - let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .unwrap(); let val = getsockopt(fd, sockopt::TcpCongestion).unwrap(); setsockopt(fd, sockopt::TcpCongestion, &val).unwrap(); - setsockopt(fd, sockopt::TcpCongestion, &OsString::from("tcp_congestion_does_not_exist")).unwrap_err(); + setsockopt( + fd, + sockopt::TcpCongestion, + &OsString::from("tcp_congestion_does_not_exist"), + ) + .unwrap_err(); - assert_eq!( - getsockopt(fd, sockopt::TcpCongestion).unwrap(), - val - ); + assert_eq!(getsockopt(fd, sockopt::TcpCongestion).unwrap(), val); } #[test] @@ -150,28 +189,39 @@ fn test_tcp_congestion() { fn test_bindtodevice() { skip_if_not_root!("test_bindtodevice"); - let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .unwrap(); let val = getsockopt(fd, sockopt::BindToDevice).unwrap(); setsockopt(fd, sockopt::BindToDevice, &val).unwrap(); - assert_eq!( - getsockopt(fd, sockopt::BindToDevice).unwrap(), - val - ); + assert_eq!(getsockopt(fd, sockopt::BindToDevice).unwrap(), val); } #[test] fn test_so_tcp_keepalive() { - let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); setsockopt(fd, sockopt::KeepAlive, &true).unwrap(); assert!(getsockopt(fd, sockopt::KeepAlive).unwrap()); - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "nacl"))] { + #[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux" + ))] + { let x = getsockopt(fd, sockopt::TcpKeepIdle).unwrap(); setsockopt(fd, sockopt::TcpKeepIdle, &(x + 1)).unwrap(); assert_eq!(getsockopt(fd, sockopt::TcpKeepIdle).unwrap(), x + 1); @@ -189,10 +239,22 @@ fn test_so_tcp_keepalive() { #[test] #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] fn test_ttl_opts() { - let fd4 = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); + let fd4 = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(fd4, sockopt::Ipv4Ttl, &1) .expect("setting ipv4ttl on an inet socket should succeed"); - let fd6 = socket(AddressFamily::Inet6, SockType::Datagram, SockFlag::empty(), None).unwrap(); + let fd6 = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(fd6, sockopt::Ipv6Ttl, &1) .expect("setting ipv6ttl on an inet6 socket should succeed"); } @@ -200,38 +262,68 @@ fn test_ttl_opts() { #[test] #[cfg(any(target_os = "ios", target_os = "macos"))] fn test_dontfrag_opts() { - let fd4 = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); + let fd4 = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); setsockopt(fd4, sockopt::IpDontFrag, &true) .expect("setting IP_DONTFRAG on an inet stream socket should succeed"); - setsockopt(fd4, sockopt::IpDontFrag, &false) - .expect("unsetting IP_DONTFRAG on an inet stream socket should succeed"); - let fd4d = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); - setsockopt(fd4d, sockopt::IpDontFrag, &true) - .expect("setting IP_DONTFRAG on an inet datagram socket should succeed"); - setsockopt(fd4d, sockopt::IpDontFrag, &false) - .expect("unsetting IP_DONTFRAG on an inet datagram socket should succeed"); + setsockopt(fd4, sockopt::IpDontFrag, &false).expect( + "unsetting IP_DONTFRAG on an inet stream socket should succeed", + ); + let fd4d = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(fd4d, sockopt::IpDontFrag, &true).expect( + "setting IP_DONTFRAG on an inet datagram socket should succeed", + ); + setsockopt(fd4d, sockopt::IpDontFrag, &false).expect( + "unsetting IP_DONTFRAG on an inet datagram socket should succeed", + ); } #[test] #[cfg(any( - target_os = "android", - target_os = "ios", - target_os = "linux", - target_os = "macos", - ) -)] + target_os = "android", + target_os = "ios", + target_os = "linux", + target_os = "macos", +))] // Disable the test under emulation because it fails in Cirrus-CI. Lack // of QEMU support is suspected. #[cfg_attr(qemu, ignore)] fn test_v6dontfrag_opts() { - let fd6 = socket(AddressFamily::Inet6, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); - setsockopt(fd6, sockopt::Ipv6DontFrag, &true) - .expect("setting IPV6_DONTFRAG on an inet6 stream socket should succeed"); - setsockopt(fd6, sockopt::Ipv6DontFrag, &false) - .expect("unsetting IPV6_DONTFRAG on an inet6 stream socket should succeed"); - let fd6d = socket(AddressFamily::Inet6, SockType::Datagram, SockFlag::empty(), None).unwrap(); - setsockopt(fd6d, sockopt::Ipv6DontFrag, &true) - .expect("setting IPV6_DONTFRAG on an inet6 datagram socket should succeed"); - setsockopt(fd6d, sockopt::Ipv6DontFrag, &false) - .expect("unsetting IPV6_DONTFRAG on an inet6 datagram socket should succeed"); + let fd6 = socket( + AddressFamily::Inet6, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + setsockopt(fd6, sockopt::Ipv6DontFrag, &true).expect( + "setting IPV6_DONTFRAG on an inet6 stream socket should succeed", + ); + setsockopt(fd6, sockopt::Ipv6DontFrag, &false).expect( + "unsetting IPV6_DONTFRAG on an inet6 stream socket should succeed", + ); + let fd6d = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(fd6d, sockopt::Ipv6DontFrag, &true).expect( + "setting IPV6_DONTFRAG on an inet6 datagram socket should succeed", + ); + setsockopt(fd6d, sockopt::Ipv6DontFrag, &false).expect( + "unsetting IPV6_DONTFRAG on an inet6 datagram socket should succeed", + ); } diff --git a/bash-5.1/vendor/nix/test/sys/test_sysinfo.rs b/bash-5.1/vendor/nix/test/sys/test_sysinfo.rs index 73e6586..2897366 100644 --- a/bash-5.1/vendor/nix/test/sys/test_sysinfo.rs +++ b/bash-5.1/vendor/nix/test/sys/test_sysinfo.rs @@ -9,10 +9,12 @@ fn sysinfo_works() { assert!(l5 >= 0.0); assert!(l15 >= 0.0); - info.uptime(); // just test Duration construction + info.uptime(); // just test Duration construction - assert!(info.swap_free() <= info.swap_total(), - "more swap available than installed (free: {}, total: {})", - info.swap_free(), - info.swap_total()); + assert!( + info.swap_free() <= info.swap_total(), + "more swap available than installed (free: {}, total: {})", + info.swap_free(), + info.swap_total() + ); } diff --git a/bash-5.1/vendor/nix/test/sys/test_termios.rs b/bash-5.1/vendor/nix/test/sys/test_termios.rs index 4a86154..aaf0008 100644 --- a/bash-5.1/vendor/nix/test/sys/test_termios.rs +++ b/bash-5.1/vendor/nix/test/sys/test_termios.rs @@ -1,11 +1,11 @@ use std::os::unix::prelude::*; use tempfile::tempfile; -use nix::fcntl; use nix::errno::Errno; +use nix::fcntl; use nix::pty::openpty; -use nix::sys::termios::{self, LocalFlags, OutputFlags, tcgetattr}; -use nix::unistd::{read, write, close}; +use nix::sys::termios::{self, tcgetattr, LocalFlags, OutputFlags}; +use nix::unistd::{close, read, write}; /// Helper function analogous to `std::io::Write::write_all`, but for `RawFd`s fn write_all(f: RawFd, buf: &[u8]) { @@ -22,7 +22,7 @@ fn test_tcgetattr_pty() { let _m = crate::PTSNAME_MTX.lock(); let pty = openpty(None, None).expect("openpty failed"); - assert!(termios::tcgetattr(pty.slave).is_ok()); + termios::tcgetattr(pty.slave).unwrap(); close(pty.master).expect("closing the master failed"); close(pty.slave).expect("closing the slave failed"); } @@ -31,15 +31,16 @@ fn test_tcgetattr_pty() { #[test] fn test_tcgetattr_enotty() { let file = tempfile().unwrap(); - assert_eq!(termios::tcgetattr(file.as_raw_fd()).err(), - Some(Errno::ENOTTY)); + assert_eq!( + termios::tcgetattr(file.as_raw_fd()).err(), + Some(Errno::ENOTTY) + ); } // Test tcgetattr on an invalid file descriptor #[test] fn test_tcgetattr_ebadf() { - assert_eq!(termios::tcgetattr(-1).err(), - Some(Errno::EBADF)); + assert_eq!(termios::tcgetattr(-1).err(), Some(Errno::EBADF)); } // Test modifying output flags @@ -60,11 +61,15 @@ fn test_output_flags() { }; // Make sure postprocessing '\r' isn't specified by default or this test is useless. - assert!(!termios.output_flags.contains(OutputFlags::OPOST | OutputFlags::OCRNL)); + assert!(!termios + .output_flags + .contains(OutputFlags::OPOST | OutputFlags::OCRNL)); // Specify that '\r' characters should be transformed to '\n' // OPOST is specified to enable post-processing - termios.output_flags.insert(OutputFlags::OPOST | OutputFlags::OCRNL); + termios + .output_flags + .insert(OutputFlags::OPOST | OutputFlags::OCRNL); // Open a pty let pty = openpty(None, &termios).unwrap(); @@ -114,7 +119,8 @@ fn test_local_flags() { // Set the master is in nonblocking mode or reading will never return. let flags = fcntl::fcntl(pty.master, fcntl::F_GETFL).unwrap(); - let new_flags = fcntl::OFlag::from_bits_truncate(flags) | fcntl::OFlag::O_NONBLOCK; + let new_flags = + fcntl::OFlag::from_bits_truncate(flags) | fcntl::OFlag::O_NONBLOCK; fcntl::fcntl(pty.master, fcntl::F_SETFL(new_flags)).unwrap(); // Write into the master diff --git a/bash-5.1/vendor/nix/test/sys/test_timerfd.rs b/bash-5.1/vendor/nix/test/sys/test_timerfd.rs index 24fb2ac..927cc70 100644 --- a/bash-5.1/vendor/nix/test/sys/test_timerfd.rs +++ b/bash-5.1/vendor/nix/test/sys/test_timerfd.rs @@ -1,10 +1,13 @@ use nix::sys::time::{TimeSpec, TimeValLike}; -use nix::sys::timerfd::{ClockId, Expiration, TimerFd, TimerFlags, TimerSetTimeFlags}; +use nix::sys::timerfd::{ + ClockId, Expiration, TimerFd, TimerFlags, TimerSetTimeFlags, +}; use std::time::Instant; #[test] pub fn test_timerfd_oneshot() { - let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); + let timer = + TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); let before = Instant::now(); @@ -23,12 +26,16 @@ pub fn test_timerfd_oneshot() { #[test] pub fn test_timerfd_interval() { - let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); + let timer = + TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); let before = Instant::now(); timer .set( - Expiration::IntervalDelayed(TimeSpec::seconds(1), TimeSpec::seconds(2)), + Expiration::IntervalDelayed( + TimeSpec::seconds(1), + TimeSpec::seconds(2), + ), TimerSetTimeFlags::empty(), ) .unwrap(); @@ -46,7 +53,8 @@ pub fn test_timerfd_interval() { #[test] pub fn test_timerfd_unset() { - let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); + let timer = + TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); timer .set( diff --git a/bash-5.1/vendor/nix/test/sys/test_uio.rs b/bash-5.1/vendor/nix/test/sys/test_uio.rs index 7dd12a2..0f4b8a6 100644 --- a/bash-5.1/vendor/nix/test/sys/test_uio.rs +++ b/bash-5.1/vendor/nix/test/sys/test_uio.rs @@ -1,18 +1,18 @@ use nix::sys::uio::*; use nix::unistd::*; -use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; -use std::{cmp, iter}; -use std::fs::{OpenOptions}; +use rand::{thread_rng, Rng}; +use std::fs::OpenOptions; use std::io::IoSlice; use std::os::unix::io::AsRawFd; +use std::{cmp, iter}; #[cfg(not(target_os = "redox"))] use std::io::IoSliceMut; +use tempfile::tempdir; #[cfg(not(target_os = "redox"))] use tempfile::tempfile; -use tempfile::tempdir; #[test] fn test_writev() { @@ -31,41 +31,38 @@ fn test_writev() { let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; - let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64..cmp::min(256, left)) }; - let b = &to_write[consumed..consumed+slice_len]; + let slice_len = if left <= 64 { + left + } else { + thread_rng().gen_range(64..cmp::min(256, left)) + }; + let b = &to_write[consumed..consumed + slice_len]; iovecs.push(IoSlice::new(b)); consumed += slice_len; } let pipe_res = pipe(); - assert!(pipe_res.is_ok()); - let (reader, writer) = pipe_res.ok().unwrap(); + let (reader, writer) = pipe_res.expect("Couldn't create pipe"); // FileDesc will close its filedesc (reader). let mut read_buf: Vec = iter::repeat(0u8).take(128 * 16).collect(); // Blocking io, should write all data. let write_res = writev(writer, &iovecs); - // Successful write - assert!(write_res.is_ok()); - let written = write_res.ok().unwrap(); + let written = write_res.expect("couldn't write"); // Check whether we written all data assert_eq!(to_write.len(), written); let read_res = read(reader, &mut read_buf[..]); - // Successful read - assert!(read_res.is_ok()); - let read = read_res.ok().unwrap() as usize; + let read = read_res.expect("couldn't read"); // Check we have read as much as we written assert_eq!(read, written); // Check equality of written and read data assert_eq!(&to_write, &read_buf); - let close_res = close(writer); - assert!(close_res.is_ok()); - let close_res = close(reader); - assert!(close_res.is_ok()); + close(writer).expect("closed writer"); + close(reader).expect("closed reader"); } #[test] #[cfg(not(target_os = "redox"))] fn test_readv() { - let s:String = thread_rng() + let s: String = thread_rng() .sample_iter(&Alphanumeric) .map(char::from) .take(128) @@ -75,7 +72,11 @@ fn test_readv() { let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; - let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64..cmp::min(256, left)) }; + let vec_len = if left <= 64 { + left + } else { + thread_rng().gen_range(64..cmp::min(256, left)) + }; let v: Vec = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; @@ -84,16 +85,10 @@ fn test_readv() { for v in &mut storage { iovecs.push(IoSliceMut::new(&mut v[..])); } - let pipe_res = pipe(); - assert!(pipe_res.is_ok()); - let (reader, writer) = pipe_res.ok().unwrap(); + let (reader, writer) = pipe().expect("couldn't create pipe"); // Blocking io, should write all data. - let write_res = write(writer, &to_write); - // Successful write - assert!(write_res.is_ok()); - let read_res = readv(reader, &mut iovecs[..]); - assert!(read_res.is_ok()); - let read = read_res.ok().unwrap(); + write(writer, &to_write).expect("write failed"); + let read = readv(reader, &mut iovecs[..]).expect("read failed"); // Check whether we've read all data assert_eq!(to_write.len(), read); // Cccumulate data from iovecs @@ -105,10 +100,8 @@ fn test_readv() { assert_eq!(read_buf.len(), to_write.len()); // Check equality of written and read data assert_eq!(&read_buf, &to_write); - let close_res = close(reader); - assert!(close_res.is_ok()); - let close_res = close(writer); - assert!(close_res.is_ok()); + close(reader).expect("couldn't close reader"); + close(writer).expect("couldn't close writer"); } #[test] @@ -117,12 +110,12 @@ fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); - let buf = [1u8;8]; + let buf = [1u8; 8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); - let mut expected = vec![0u8;8]; - expected.extend(vec![1;8]); + let mut expected = vec![0u8; 8]; + expected.extend(vec![1; 8]); assert_eq!(file_content, expected); } @@ -133,24 +126,29 @@ fn test_pread() { let tempdir = tempdir().unwrap(); let path = tempdir.path().join("pread_test_file"); - let mut file = OpenOptions::new().write(true).read(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); let file_content: Vec = (0..64).collect(); file.write_all(&file_content).unwrap(); - let mut buf = [0u8;16]; + let mut buf = [0u8; 16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_pwritev() { use std::io::Read; let to_write: Vec = (0..128).collect(); - let expected: Vec = [vec![0;100], to_write.clone()].concat(); + let expected: Vec = [vec![0; 100], to_write.clone()].concat(); let iovecs = [ IoSlice::new(&to_write[0..17]), @@ -162,8 +160,13 @@ fn test_pwritev() { // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); - let mut file = OpenOptions::new().write(true).read(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); @@ -175,7 +178,7 @@ fn test_pwritev() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_preadv() { use std::io::Write; @@ -186,20 +189,23 @@ fn test_preadv() { let path = tempdir.path().join("preadv_test_file"); - let mut file = OpenOptions::new().read(true).write(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); file.write_all(&to_write).unwrap(); - let mut buffers: Vec> = vec![ - vec![0; 24], - vec![0; 1], - vec![0; 75], - ]; + let mut buffers: Vec> = vec![vec![0; 24], vec![0; 1], vec![0; 75]]; { // Borrow the buffers into IoVecs and preadv into them - let mut iovecs: Vec<_> = buffers.iter_mut().map( - |buf| IoSliceMut::new(&mut buf[..])).collect(); + let mut iovecs: Vec<_> = buffers + .iter_mut() + .map(|buf| IoSliceMut::new(&mut buf[..])) + .collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &mut iovecs, 100)); } @@ -208,14 +214,15 @@ fn test_preadv() { } #[test] -#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] // uclibc doesn't implement process_vm_readv +#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] +// uclibc doesn't implement process_vm_readv // qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(qemu, ignore)] fn test_process_vm_readv() { - use nix::unistd::ForkResult::*; + use crate::*; use nix::sys::signal::*; use nix::sys::wait::*; - use crate::*; + use nix::unistd::ForkResult::*; require_capability!("test_process_vm_readv", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); @@ -225,7 +232,7 @@ fn test_process_vm_readv() { let mut vector = vec![1u8, 2, 3, 4, 5]; let (r, w) = pipe().unwrap(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Parent { child } => { close(w).unwrap(); // wait for child @@ -236,16 +243,18 @@ fn test_process_vm_readv() { let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; - let ret = process_vm_readv(child, - &mut [IoSliceMut::new(&mut buf)], - &[remote_iov]); + let ret = process_vm_readv( + child, + &mut [IoSliceMut::new(&mut buf)], + &[remote_iov], + ); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); - }, + } Child => { let _ = close(r); for i in &mut vector { @@ -253,7 +262,9 @@ fn test_process_vm_readv() { } let _ = write(w, b"\0"); let _ = close(w); - loop { let _ = pause(); } - }, + loop { + pause(); + } + } } } diff --git a/bash-5.1/vendor/nix/test/sys/test_wait.rs b/bash-5.1/vendor/nix/test/sys/test_wait.rs index 90d9fcf..d472f1e 100644 --- a/bash-5.1/vendor/nix/test/sys/test_wait.rs +++ b/bash-5.1/vendor/nix/test/sys/test_wait.rs @@ -1,25 +1,28 @@ +use libc::_exit; use nix::errno::Errno; -use nix::unistd::*; -use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; -use libc::_exit; +use nix::unistd::ForkResult::*; +use nix::unistd::*; #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_wait_signal() { let _m = crate::FORK_MTX.lock(); // Safe: The child only calls `pause` and/or `_exit`, which are async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => { - pause(); - unsafe { _exit(123) } - }, - Parent { child } => { - kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false))); - }, + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => { + pause(); + unsafe { _exit(123) } + } + Parent { child } => { + kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Signaled(child, SIGKILL, false)) + ); + } } } @@ -27,7 +30,7 @@ fn test_wait_signal() { #[cfg(any( target_os = "android", target_os = "freebsd", - target_os = "haiku", + //target_os = "haiku", all(target_os = "linux", not(target_env = "uclibc")), ))] #[cfg(not(any(target_arch = "mips", target_arch = "mips64")))] @@ -35,18 +38,18 @@ fn test_waitid_signal() { let _m = crate::FORK_MTX.lock(); // Safe: The child only calls `pause` and/or `_exit`, which are async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => { - pause(); - unsafe { _exit(123) } - }, - Parent { child } => { - kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); - assert_eq!( - waitid(Id::Pid(child), WaitPidFlag::WEXITED), - Ok(WaitStatus::Signaled(child, SIGKILL, false)), - ); - }, + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => { + pause(); + unsafe { _exit(123) } + } + Parent { child } => { + kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); + assert_eq!( + waitid(Id::Pid(child), WaitPidFlag::WEXITED), + Ok(WaitStatus::Signaled(child, SIGKILL, false)), + ); + } } } @@ -55,14 +58,17 @@ fn test_wait_exit() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => unsafe { _exit(12); }, - Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); - }, + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => unsafe { + _exit(12); + }, + Parent { child } => { + assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); + } } } +#[cfg(not(target_os = "haiku"))] #[test] #[cfg(any( target_os = "android", @@ -75,22 +81,30 @@ fn test_waitid_exit() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => unsafe { _exit(12); }, - Parent { child } => { - assert_eq!( - waitid(Id::Pid(child), WaitPidFlag::WEXITED), - Ok(WaitStatus::Exited(child, 12)), - ); - } + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => unsafe { + _exit(12); + }, + Parent { child } => { + assert_eq!( + waitid(Id::Pid(child), WaitPidFlag::WEXITED), + Ok(WaitStatus::Exited(child, 12)), + ); + } } } #[test] fn test_waitstatus_from_raw() { let pid = Pid::from_raw(1); - assert_eq!(WaitStatus::from_raw(pid, 0x0002), Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false))); - assert_eq!(WaitStatus::from_raw(pid, 0x0200), Ok(WaitStatus::Exited(pid, 2))); + assert_eq!( + WaitStatus::from_raw(pid, 0x0002), + Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false)) + ); + assert_eq!( + WaitStatus::from_raw(pid, 0x0200), + Ok(WaitStatus::Exited(pid, 2)) + ); assert_eq!(WaitStatus::from_raw(pid, 0x7f7f), Err(Errno::EINVAL)); } @@ -98,7 +112,7 @@ fn test_waitstatus_from_raw() { fn test_waitstatus_pid() { let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.unwrap() { + match unsafe { fork() }.unwrap() { Child => unsafe { _exit(0) }, Parent { child } => { let status = waitpid(child, None).unwrap(); @@ -130,13 +144,13 @@ fn test_waitid_pid() { // FIXME: qemu-user doesn't implement ptrace on most arches #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod ptrace { - use nix::sys::ptrace::{self, Options, Event}; + use crate::*; + use libc::_exit; + use nix::sys::ptrace::{self, Event, Options}; use nix::sys::signal::*; use nix::sys::wait::*; - use nix::unistd::*; use nix::unistd::ForkResult::*; - use libc::_exit; - use crate::*; + use nix::unistd::*; fn ptrace_child() -> ! { ptrace::traceme().unwrap(); @@ -148,18 +162,32 @@ mod ptrace { fn ptrace_wait_parent(child: Pid) { // Wait for the raised SIGTRAP - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, SIGTRAP)) + ); // We want to test a syscall stop and a PTRACE_EVENT stop - assert!(ptrace::setoptions(child, Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT).is_ok()); + ptrace::setoptions( + child, + Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT, + ) + .expect("setoptions failed"); // First, stop on the next system call, which will be exit() - assert!(ptrace::syscall(child, None).is_ok()); + ptrace::syscall(child, None).expect("syscall failed"); assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); // Then get the ptrace event for the process exiting - assert!(ptrace::cont(child, None).is_ok()); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceEvent(child, SIGTRAP, Event::PTRACE_EVENT_EXIT as i32))); + ptrace::cont(child, None).expect("cont failed"); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceEvent( + child, + SIGTRAP, + Event::PTRACE_EVENT_EXIT as i32 + )) + ); // Finally get the normal wait() result, now that the process has exited - assert!(ptrace::cont(child, None).is_ok()); + ptrace::cont(child, None).expect("cont failed"); assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 0))); } @@ -174,22 +202,30 @@ mod ptrace { Ok(WaitStatus::PtraceEvent(child, SIGTRAP, 0)), ); // We want to test a syscall stop and a PTRACE_EVENT stop - assert!(ptrace::setoptions(child, Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT).is_ok()); + ptrace::setoptions( + child, + Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT, + ) + .expect("setopts failed"); // First, stop on the next system call, which will be exit() - assert!(ptrace::syscall(child, None).is_ok()); + ptrace::syscall(child, None).expect("syscall failed"); assert_eq!( waitid(Id::Pid(child), WaitPidFlag::WEXITED), Ok(WaitStatus::PtraceSyscall(child)), ); // Then get the ptrace event for the process exiting - assert!(ptrace::cont(child, None).is_ok()); + ptrace::cont(child, None).expect("cont failed"); assert_eq!( waitid(Id::Pid(child), WaitPidFlag::WEXITED), - Ok(WaitStatus::PtraceEvent(child, SIGTRAP, Event::PTRACE_EVENT_EXIT as i32)), + Ok(WaitStatus::PtraceEvent( + child, + SIGTRAP, + Event::PTRACE_EVENT_EXIT as i32 + )), ); // Finally get the normal wait() result, now that the process has exited - assert!(ptrace::cont(child, None).is_ok()); + ptrace::cont(child, None).expect("cont failed"); assert_eq!( waitid(Id::Pid(child), WaitPidFlag::WEXITED), Ok(WaitStatus::Exited(child, 0)), @@ -201,7 +237,7 @@ mod ptrace { require_capability!("test_wait_ptrace", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => ptrace_child(), Parent { child } => ptrace_wait_parent(child), } @@ -213,7 +249,7 @@ mod ptrace { require_capability!("test_waitid_ptrace", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => ptrace_child(), Parent { child } => ptrace_waitid_parent(child), } diff --git a/bash-5.1/vendor/nix/test/test.rs b/bash-5.1/vendor/nix/test/test.rs index 3cac48f..f725ef9 100644 --- a/bash-5.1/vendor/nix/test/test.rs +++ b/bash-5.1/vendor/nix/test/test.rs @@ -1,6 +1,6 @@ #[macro_use] extern crate cfg_if; -#[cfg_attr(not(target_os = "redox"), macro_use)] +#[cfg_attr(not(any(target_os = "redox", target_os = "haiku")), macro_use)] extern crate nix; #[macro_use] extern crate lazy_static; @@ -10,38 +10,46 @@ mod sys; #[cfg(not(target_os = "redox"))] mod test_dir; mod test_fcntl; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] mod test_kmod; -#[cfg(target_os = "freebsd")] -mod test_nmount; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "fushsia", - target_os = "linux", - target_os = "netbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "fushsia", + target_os = "linux", + target_os = "netbsd" +))] mod test_mq; #[cfg(not(target_os = "redox"))] mod test_net; mod test_nix_path; -mod test_resource; +#[cfg(target_os = "freebsd")] +mod test_nmount; mod test_poll; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] mod test_pty; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "linux"))] +mod test_resource; +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "linux" +))] mod test_sched; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos" +))] mod test_sendfile; mod test_stat; mod test_time; -mod test_unistd; #[cfg(all( any( target_os = "freebsd", @@ -53,15 +61,15 @@ mod test_unistd; feature = "signal" ))] mod test_timer; +mod test_unistd; +use nix::unistd::{chdir, getcwd, read}; +use parking_lot::{Mutex, RwLock, RwLockWriteGuard}; use std::os::unix::io::RawFd; use std::path::PathBuf; -use parking_lot::{Mutex, RwLock, RwLockWriteGuard}; -use nix::unistd::{chdir, getcwd, read}; - /// Helper function analogous to `std::io::Read::read_exact`, but for `RawFD`s -fn read_exact(f: RawFd, buf: &mut [u8]) { +fn read_exact(f: RawFd, buf: &mut [u8]) { let mut len = 0; while len < buf.len() { // get_mut would be better than split_at_mut, but it requires nightly @@ -92,13 +100,13 @@ lazy_static! { /// RAII object that restores a test's original directory on drop struct DirRestore<'a> { d: PathBuf, - _g: RwLockWriteGuard<'a, ()> + _g: RwLockWriteGuard<'a, ()>, } impl<'a> DirRestore<'a> { fn new() -> Self { let guard = crate::CWD_LOCK.write(); - DirRestore{ + DirRestore { _g: guard, d: getcwd().unwrap(), } diff --git a/bash-5.1/vendor/nix/test/test_dir.rs b/bash-5.1/vendor/nix/test/test_dir.rs index 2940b6e..f662992 100644 --- a/bash-5.1/vendor/nix/test/test_dir.rs +++ b/bash-5.1/vendor/nix/test/test_dir.rs @@ -4,7 +4,6 @@ use nix::sys::stat::Mode; use std::fs::File; use tempfile::tempdir; - #[cfg(test)] fn flags() -> OFlag { #[cfg(target_os = "illumos")] @@ -17,11 +16,11 @@ fn flags() -> OFlag { } #[test] -#[allow(clippy::unnecessary_sort_by)] // False positive +#[allow(clippy::unnecessary_sort_by)] // False positive fn read() { let tmp = tempdir().unwrap(); File::create(&tmp.path().join("foo")).unwrap(); - ::std::os::unix::fs::symlink("foo", tmp.path().join("bar")).unwrap(); + std::os::unix::fs::symlink("foo", tmp.path().join("bar")).unwrap(); let mut dir = Dir::open(tmp.path(), flags(), Mode::empty()).unwrap(); let mut entries: Vec<_> = dir.iter().map(|e| e.unwrap()).collect(); entries.sort_by(|a, b| a.file_name().cmp(b.file_name())); @@ -43,13 +42,23 @@ fn read() { fn rewind() { let tmp = tempdir().unwrap(); let mut dir = Dir::open(tmp.path(), flags(), Mode::empty()).unwrap(); - let entries1: Vec<_> = dir.iter().map(|e| e.unwrap().file_name().to_owned()).collect(); - let entries2: Vec<_> = dir.iter().map(|e| e.unwrap().file_name().to_owned()).collect(); - let entries3: Vec<_> = dir.into_iter().map(|e| e.unwrap().file_name().to_owned()).collect(); + let entries1: Vec<_> = dir + .iter() + .map(|e| e.unwrap().file_name().to_owned()) + .collect(); + let entries2: Vec<_> = dir + .iter() + .map(|e| e.unwrap().file_name().to_owned()) + .collect(); + let entries3: Vec<_> = dir + .into_iter() + .map(|e| e.unwrap().file_name().to_owned()) + .collect(); assert_eq!(entries1, entries2); assert_eq!(entries2, entries3); } +#[cfg(not(target_os = "haiku"))] #[test] fn ebadf() { assert_eq!(Dir::from_fd(-1).unwrap_err(), nix::Error::EBADF); diff --git a/bash-5.1/vendor/nix/test/test_fcntl.rs b/bash-5.1/vendor/nix/test/test_fcntl.rs index ebfc43e..f4adee2 100644 --- a/bash-5.1/vendor/nix/test/test_fcntl.rs +++ b/bash-5.1/vendor/nix/test/test_fcntl.rs @@ -1,7 +1,7 @@ #[cfg(not(target_os = "redox"))] use nix::errno::*; #[cfg(not(target_os = "redox"))] -use nix::fcntl::{open, OFlag, readlink}; +use nix::fcntl::{open, readlink, OFlag}; #[cfg(not(target_os = "redox"))] use nix::fcntl::{openat, readlinkat, renameat}; #[cfg(all( @@ -14,19 +14,19 @@ use nix::fcntl::{openat, readlinkat, renameat}; target_arch = "s390x" ) ))] -use nix::fcntl::{RenameFlags, renameat2}; +use nix::fcntl::{renameat2, RenameFlags}; #[cfg(not(target_os = "redox"))] use nix::sys::stat::Mode; #[cfg(not(target_os = "redox"))] use nix::unistd::{close, read}; #[cfg(not(target_os = "redox"))] -use tempfile::{self, NamedTempFile}; -#[cfg(not(target_os = "redox"))] use std::fs::File; #[cfg(not(target_os = "redox"))] use std::io::prelude::*; #[cfg(not(target_os = "redox"))] use std::os::unix::fs; +#[cfg(not(target_os = "redox"))] +use tempfile::{self, NamedTempFile}; #[test] #[cfg(not(target_os = "redox"))] @@ -38,13 +38,16 @@ fn test_openat() { let mut tmp = NamedTempFile::new().unwrap(); tmp.write_all(CONTENTS).unwrap(); - let dirfd = open(tmp.path().parent().unwrap(), - OFlag::empty(), - Mode::empty()).unwrap(); - let fd = openat(dirfd, - tmp.path().file_name().unwrap(), - OFlag::O_RDONLY, - Mode::empty()).unwrap(); + let dirfd = + open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty()) + .unwrap(); + let fd = openat( + dirfd, + tmp.path().file_name().unwrap(), + OFlag::O_RDONLY, + Mode::empty(), + ) + .unwrap(); let mut buf = [0u8; 1024]; assert_eq!(4, read(fd, &mut buf).unwrap()); @@ -58,14 +61,18 @@ fn test_openat() { #[cfg(not(target_os = "redox"))] fn test_renameat() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); File::create(&old_path).unwrap(); let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); renameat(Some(old_dirfd), "old", Some(new_dirfd), "new").unwrap(); - assert_eq!(renameat(Some(old_dirfd), "old", Some(new_dirfd), "new").unwrap_err(), - Errno::ENOENT); + assert_eq!( + renameat(Some(old_dirfd), "old", Some(new_dirfd), "new").unwrap_err(), + Errno::ENOENT + ); close(old_dirfd).unwrap(); close(new_dirfd).unwrap(); assert!(new_dir.path().join("new").exists()); @@ -84,11 +91,13 @@ fn test_renameat() { ))] fn test_renameat2_behaves_like_renameat_with_no_flags() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); File::create(&old_path).unwrap(); let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); renameat2( Some(old_dirfd), "old", @@ -126,14 +135,16 @@ fn test_renameat2_behaves_like_renameat_with_no_flags() { ))] fn test_renameat2_exchange() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); { let mut old_f = File::create(&old_path).unwrap(); old_f.write_all(b"old").unwrap(); } let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let new_path = new_dir.path().join("new"); { let mut new_f = File::create(&new_path).unwrap(); @@ -172,11 +183,13 @@ fn test_renameat2_exchange() { ))] fn test_renameat2_noreplace() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); File::create(&old_path).unwrap(); let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let new_path = new_dir.path().join("new"); File::create(&new_path).unwrap(); assert_eq!( @@ -196,7 +209,6 @@ fn test_renameat2_noreplace() { assert!(old_dir.path().join("old").exists()); } - #[test] #[cfg(not(target_os = "redox"))] fn test_readlink() { @@ -205,22 +217,22 @@ fn test_readlink() { let dst = tempdir.path().join("b"); println!("a: {:?}, b: {:?}", &src, &dst); fs::symlink(&src.as_path(), &dst.as_path()).unwrap(); - let dirfd = open(tempdir.path(), - OFlag::empty(), - Mode::empty()).unwrap(); + let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); let expected_dir = src.to_str().unwrap(); assert_eq!(readlink(&dst).unwrap().to_str().unwrap(), expected_dir); - assert_eq!(readlinkat(dirfd, "b").unwrap().to_str().unwrap(), expected_dir); - + assert_eq!( + readlinkat(dirfd, "b").unwrap().to_str().unwrap(), + expected_dir + ); } #[cfg(any(target_os = "linux", target_os = "android"))] mod linux_android { + use libc::loff_t; use std::io::prelude::*; use std::io::{IoSlice, SeekFrom}; use std::os::unix::prelude::*; - use libc::loff_t; use nix::fcntl::*; use nix::unistd::{close, pipe, read, write}; @@ -275,8 +287,15 @@ mod linux_android { let (rd, wr) = pipe().unwrap(); let mut offset: loff_t = 5; - let res = splice(tmp.as_raw_fd(), Some(&mut offset), - wr, None, 2, SpliceFFlags::empty()).unwrap(); + let res = splice( + tmp.as_raw_fd(), + Some(&mut offset), + wr, + None, + 2, + SpliceFFlags::empty(), + ) + .unwrap(); assert_eq!(2, res); @@ -321,10 +340,7 @@ mod linux_android { let buf1 = b"abcdef"; let buf2 = b"defghi"; - let iovecs = vec![ - IoSlice::new(&buf1[0..3]), - IoSlice::new(&buf2[0..3]) - ]; + let iovecs = vec![IoSlice::new(&buf1[0..3]), IoSlice::new(&buf2[0..3])]; let res = vmsplice(wr, &iovecs[..], SpliceFFlags::empty()).unwrap(); @@ -359,7 +375,7 @@ mod linux_android { #[test] #[cfg(all(target_os = "linux", not(target_env = "musl")))] - #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile + #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile fn test_ofd_write_lock() { use nix::sys::stat::fstat; use std::mem; @@ -377,7 +393,7 @@ mod linux_android { let inode = fstat(fd).expect("fstat failed").st_ino as usize; let mut flock: libc::flock = unsafe { - mem::zeroed() // required for Linux/mips + mem::zeroed() // required for Linux/mips }; flock.l_type = libc::F_WRLCK as libc::c_short; flock.l_whence = libc::SEEK_SET as libc::c_short; @@ -397,7 +413,7 @@ mod linux_android { #[test] #[cfg(all(target_os = "linux", not(target_env = "musl")))] - #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile + #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile fn test_ofd_read_lock() { use nix::sys::stat::fstat; use std::mem; @@ -415,7 +431,7 @@ mod linux_android { let inode = fstat(fd).expect("fstat failed").st_ino as usize; let mut flock: libc::flock = unsafe { - mem::zeroed() // required for Linux/mips + mem::zeroed() // required for Linux/mips }; flock.l_type = libc::F_RDLCK as libc::c_short; flock.l_whence = libc::SEEK_SET as libc::c_short; @@ -435,10 +451,7 @@ mod linux_android { #[cfg(all(target_os = "linux", not(target_env = "musl")))] fn lock_info(inode: usize) -> Option<(String, String)> { - use std::{ - fs::File, - io::BufReader - }; + use std::{fs::File, io::BufReader}; let file = File::open("/proc/locks").expect("open /proc/locks failed"); let buf = BufReader::new(file); @@ -458,52 +471,63 @@ mod linux_android { } } -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - any(target_os = "wasi", target_env = "wasi"), - target_env = "uclibc", - target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "wasi", + target_env = "uclibc", + target_os = "freebsd" +))] mod test_posix_fadvise { - use tempfile::NamedTempFile; - use std::os::unix::io::{RawFd, AsRawFd}; use nix::errno::Errno; use nix::fcntl::*; use nix::unistd::pipe; + use std::os::unix::io::{AsRawFd, RawFd}; + use tempfile::NamedTempFile; #[test] fn test_success() { let tmp = NamedTempFile::new().unwrap(); let fd = tmp.as_raw_fd(); - let res = posix_fadvise(fd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED); - - assert!(res.is_ok()); + posix_fadvise(fd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED) + .expect("posix_fadvise failed"); } #[test] fn test_errno() { let (rd, _wr) = pipe().unwrap(); - let res = posix_fadvise(rd as RawFd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED); + let res = posix_fadvise( + rd as RawFd, + 0, + 100, + PosixFadviseAdvice::POSIX_FADV_WILLNEED, + ); assert_eq!(res, Err(Errno::ESPIPE)); } } -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "fuchsia", - any(target_os = "wasi", target_env = "wasi"), - target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "wasi", + target_os = "freebsd" +))] mod test_posix_fallocate { - use tempfile::NamedTempFile; - use std::{io::Read, os::unix::io::{RawFd, AsRawFd}}; use nix::errno::Errno; use nix::fcntl::*; use nix::unistd::pipe; + use std::{ + io::Read, + os::unix::io::{AsRawFd, RawFd}, + }; + use tempfile::NamedTempFile; #[test] fn success() { @@ -535,11 +559,7 @@ mod test_posix_fallocate { let err = posix_fallocate(rd as RawFd, 0, 100).unwrap_err(); match err { Errno::EINVAL | Errno::ENODEV | Errno::ESPIPE | Errno::EBADF => (), - errno => - panic!( - "unexpected errno {}", - errno, - ), + errno => panic!("unexpected errno {}", errno,), } } } diff --git a/bash-5.1/vendor/nix/test/test_kmod/mod.rs b/bash-5.1/vendor/nix/test/test_kmod/mod.rs index 8eef538..5ebc242 100644 --- a/bash-5.1/vendor/nix/test/test_kmod/mod.rs +++ b/bash-5.1/vendor/nix/test/test_kmod/mod.rs @@ -1,22 +1,25 @@ +use crate::*; use std::fs::copy; use std::path::PathBuf; use std::process::Command; use tempfile::{tempdir, TempDir}; -use crate::*; fn compile_kernel_module() -> (PathBuf, String, TempDir) { let _m = crate::FORK_MTX.lock(); - let tmp_dir = tempdir().expect("unable to create temporary build directory"); + let tmp_dir = + tempdir().expect("unable to create temporary build directory"); copy( "test/test_kmod/hello_mod/hello.c", &tmp_dir.path().join("hello.c"), - ).expect("unable to copy hello.c to temporary build directory"); + ) + .expect("unable to copy hello.c to temporary build directory"); copy( "test/test_kmod/hello_mod/Makefile", &tmp_dir.path().join("Makefile"), - ).expect("unable to copy Makefile to temporary build directory"); + ) + .expect("unable to copy Makefile to temporary build directory"); let status = Command::new("make") .current_dir(tmp_dir.path()) @@ -51,12 +54,16 @@ fn test_finit_and_delete_module() { delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] fn test_finit_and_delete_module_with_params() { - require_capability!("test_finit_and_delete_module_with_params", CAP_SYS_MODULE); + require_capability!( + "test_finit_and_delete_module_with_params", + CAP_SYS_MODULE + ); let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); @@ -67,12 +74,14 @@ fn test_finit_and_delete_module_with_params() { &f, &CString::new("who=Rust number=2018").unwrap(), ModuleInitFlags::empty(), - ).expect("unable to load kernel module"); + ) + .expect("unable to load kernel module"); delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] @@ -87,17 +96,22 @@ fn test_init_and_delete_module() { let mut contents: Vec = Vec::new(); f.read_to_end(&mut contents) .expect("unable to read kernel module content to buffer"); - init_module(&contents, &CString::new("").unwrap()).expect("unable to load kernel module"); + init_module(&contents, &CString::new("").unwrap()) + .expect("unable to load kernel module"); delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] fn test_init_and_delete_module_with_params() { - require_capability!("test_init_and_delete_module_with_params", CAP_SYS_MODULE); + require_capability!( + "test_init_and_delete_module_with_params", + CAP_SYS_MODULE + ); let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); @@ -113,7 +127,8 @@ fn test_init_and_delete_module_with_params() { delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] @@ -125,14 +140,18 @@ fn test_finit_module_invalid() { let kmod_path = "/dev/zero"; let f = File::open(kmod_path).expect("unable to open kernel module"); - let result = finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); + let result = + finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); assert_eq!(result.unwrap_err(), Errno::EINVAL); } #[test] fn test_finit_module_twice_and_delete_module() { - require_capability!("test_finit_module_twice_and_delete_module", CAP_SYS_MODULE); + require_capability!( + "test_finit_module_twice_and_delete_module", + CAP_SYS_MODULE + ); let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); @@ -142,14 +161,16 @@ fn test_finit_module_twice_and_delete_module() { finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()) .expect("unable to load kernel module"); - let result = finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); + let result = + finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); assert_eq!(result.unwrap_err(), Errno::EEXIST); delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] @@ -158,7 +179,10 @@ fn test_delete_module_not_loaded() { let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); - let result = delete_module(&CString::new("hello").unwrap(), DeleteModuleFlags::empty()); + let result = delete_module( + &CString::new("hello").unwrap(), + DeleteModuleFlags::empty(), + ); assert_eq!(result.unwrap_err(), Errno::ENOENT); } diff --git a/bash-5.1/vendor/nix/test/test_mount.rs b/bash-5.1/vendor/nix/test/test_mount.rs index 1ddfcfe..febcadf 100644 --- a/bash-5.1/vendor/nix/test/test_mount.rs +++ b/bash-5.1/vendor/nix/test/test_mount.rs @@ -27,16 +27,18 @@ exit 23"; const EXPECTED_STATUS: i32 = 23; const NONE: Option<&'static [u8]> = None; - #[allow(clippy::bind_instead_of_map)] // False positive + #[allow(clippy::bind_instead_of_map)] // False positive pub fn test_mount_tmpfs_without_flags_allows_rwx() { let tempdir = tempfile::tempdir().unwrap(); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::empty(), - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::empty(), + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); let test_path = tempdir.path().join("test"); @@ -46,8 +48,10 @@ exit 23"; .write(true) .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) .open(&test_path) - .or_else(|e| - if Errno::from_i32(e.raw_os_error().unwrap()) == Errno::EOVERFLOW { + .or_else(|e| { + if Errno::from_i32(e.raw_os_error().unwrap()) + == Errno::EOVERFLOW + { // Skip tests on certain Linux kernels which have a bug // regarding tmpfs in namespaces. // Ubuntu 14.04 and 16.04 are known to be affected; 16.10 is @@ -56,13 +60,16 @@ exit 23"; // https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1659087 let stderr = io::stderr(); let mut handle = stderr.lock(); - writeln!(handle, "Buggy Linux kernel detected. Skipping test.") + writeln!( + handle, + "Buggy Linux kernel detected. Skipping test." + ) .unwrap(); process::exit(0); - } else { - panic!("open failed: {}", e); - } - ) + } else { + panic!("open failed: {}", e); + } + }) .and_then(|mut f| f.write(SCRIPT_CONTENTS)) .unwrap_or_else(|e| panic!("write failed: {}", e)); @@ -74,42 +81,55 @@ exit 23"; assert_eq!(buf, SCRIPT_CONTENTS); // Verify execute. - assert_eq!(EXPECTED_STATUS, - Command::new(&test_path) - .status() - .unwrap_or_else(|e| panic!("exec failed: {}", e)) - .code() - .unwrap_or_else(|| panic!("child killed by signal"))); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + assert_eq!( + EXPECTED_STATUS, + Command::new(&test_path) + .status() + .unwrap_or_else(|e| panic!("exec failed: {}", e)) + .code() + .unwrap_or_else(|| panic!("child killed by signal")) + ); + + umount(tempdir.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_rdonly_disallows_write() { let tempdir = tempfile::tempdir().unwrap(); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_RDONLY, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_RDONLY, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); // EROFS: Read-only file system - assert_eq!(EROFS as i32, - File::create(tempdir.path().join("test")).unwrap_err().raw_os_error().unwrap()); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + assert_eq!( + EROFS as i32, + File::create(tempdir.path().join("test")) + .unwrap_err() + .raw_os_error() + .unwrap() + ); + + umount(tempdir.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_noexec_disallows_exec() { let tempdir = tempfile::tempdir().unwrap(); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_NOEXEC, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_NOEXEC, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); let test_path = tempdir.path().join("test"); @@ -122,21 +142,30 @@ exit 23"; .unwrap_or_else(|e| panic!("write failed: {}", e)); // Verify that we cannot execute despite a+x permissions being set. - let mode = stat::Mode::from_bits_truncate(fs::metadata(&test_path) - .map(|md| md.permissions().mode()) - .unwrap_or_else(|e| { - panic!("metadata failed: {}", e) - })); - - assert!(mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), - "{:?} did not have execute permissions", - &test_path); + let mode = stat::Mode::from_bits_truncate( + fs::metadata(&test_path) + .map(|md| md.permissions().mode()) + .unwrap_or_else(|e| panic!("metadata failed: {}", e)), + ); + + assert!( + mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), + "{:?} did not have execute permissions", + &test_path + ); // EACCES: Permission denied - assert_eq!(EACCES as i32, - Command::new(&test_path).status().unwrap_err().raw_os_error().unwrap()); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + assert_eq!( + EACCES as i32, + Command::new(&test_path) + .status() + .unwrap_err() + .raw_os_error() + .unwrap() + ); + + umount(tempdir.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_bind() { @@ -146,12 +175,14 @@ exit 23"; { let mount_point = tempfile::tempdir().unwrap(); - mount(Some(tempdir.path()), - mount_point.path(), - NONE, - MsFlags::MS_BIND, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + Some(tempdir.path()), + mount_point.path(), + NONE, + MsFlags::MS_BIND, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); fs::OpenOptions::new() .create(true) @@ -161,7 +192,8 @@ exit 23"; .and_then(|mut f| f.write(SCRIPT_CONTENTS)) .unwrap_or_else(|e| panic!("write failed: {}", e)); - umount(mount_point.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + umount(mount_point.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } // Verify the file written in the mount shows up in source directory, even @@ -199,7 +231,6 @@ exit 23"; } } - // Test runner /// Mimic normal test output (hackishly). @@ -220,16 +251,20 @@ macro_rules! run_tests { #[cfg(target_os = "linux")] fn main() { - use test_mount::{setup_namespaces, test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, test_mount_noexec_disallows_exec, - test_mount_bind}; + use test_mount::{ + setup_namespaces, test_mount_bind, test_mount_noexec_disallows_exec, + test_mount_rdonly_disallows_write, + test_mount_tmpfs_without_flags_allows_rwx, + }; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1351"); setup_namespaces(); - run_tests!(test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, - test_mount_noexec_disallows_exec, - test_mount_bind); + run_tests!( + test_mount_tmpfs_without_flags_allows_rwx, + test_mount_rdonly_disallows_write, + test_mount_noexec_disallows_exec, + test_mount_bind + ); } #[cfg(not(target_os = "linux"))] diff --git a/bash-5.1/vendor/nix/test/test_mq.rs b/bash-5.1/vendor/nix/test/test_mq.rs index 8aff840..7b48e7a 100644 --- a/bash-5.1/vendor/nix/test/test_mq.rs +++ b/bash-5.1/vendor/nix/test/test_mq.rs @@ -3,8 +3,8 @@ use std::ffi::CString; use std::str; use nix::errno::Errno; -use nix::mqueue::{mq_open, mq_close, mq_send, mq_receive, mq_attr_member_t}; -use nix::mqueue::{MqAttr, MQ_OFlag}; +use nix::mqueue::{mq_attr_member_t, mq_close, mq_open, mq_receive, mq_send}; +use nix::mqueue::{MQ_OFlag, MqAttr}; use nix::sys::stat::Mode; // Defined as a macro such that the error source is reported as the caller's location. @@ -29,8 +29,8 @@ macro_rules! assert_attr_eq { #[test] fn test_mq_send_and_receive() { const MSG_SIZE: mq_attr_member_t = 32; - let attr = MqAttr::new(0, 10, MSG_SIZE, 0); - let mq_name= &CString::new(b"/a_nix_test_queue".as_ref()).unwrap(); + let attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let mq_name = &CString::new(b"/a_nix_test_queue".as_ref()).unwrap(); let oflag0 = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -55,12 +55,11 @@ fn test_mq_send_and_receive() { assert_eq!(msg_to_send, str::from_utf8(&buf[0..len]).unwrap()); } - #[test] fn test_mq_getattr() { use nix::mqueue::mq_getattr; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -78,15 +77,14 @@ fn test_mq_getattr() { // FIXME: Fix failures for mips in QEMU #[test] -#[cfg_attr(all( - qemu, - any(target_arch = "mips", target_arch = "mips64") - ), ignore +#[cfg_attr( + all(qemu, any(target_arch = "mips", target_arch = "mips64")), + ignore )] fn test_mq_setattr() { use nix::mqueue::{mq_getattr, mq_setattr}; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -109,7 +107,12 @@ fn test_mq_setattr() { assert_ne!(new_attr_get, new_attr); } - let new_attr_non_blocking = MqAttr::new(MQ_OFlag::O_NONBLOCK.bits() as mq_attr_member_t, 10, MSG_SIZE, 0); + let new_attr_non_blocking = MqAttr::new( + MQ_OFlag::O_NONBLOCK.bits() as mq_attr_member_t, + 10, + MSG_SIZE, + 0, + ); mq_setattr(&mqd, &new_attr_non_blocking).unwrap(); let new_attr_get = mq_getattr(&mqd).unwrap(); @@ -124,15 +127,14 @@ fn test_mq_setattr() { // FIXME: Fix failures for mips in QEMU #[test] -#[cfg_attr(all( - qemu, - any(target_arch = "mips", target_arch = "mips64") - ), ignore +#[cfg_attr( + all(qemu, any(target_arch = "mips", target_arch = "mips64")), + ignore )] fn test_mq_set_nonblocking() { - use nix::mqueue::{mq_getattr, mq_set_nonblock, mq_remove_nonblock}; + use nix::mqueue::{mq_getattr, mq_remove_nonblock, mq_set_nonblock}; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -156,10 +158,11 @@ fn test_mq_set_nonblocking() { fn test_mq_unlink() { use nix::mqueue::mq_unlink; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name_opened = &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); #[cfg(not(any(target_os = "dragonfly", target_os = "netbsd")))] - let mq_name_not_opened = &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); + let mq_name_not_opened = + &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; let r = mq_open(mq_name_opened, oflag, mode, Some(&initial_attr)); @@ -170,7 +173,7 @@ fn test_mq_unlink() { let mqd = r.unwrap(); let res_unlink = mq_unlink(mq_name_opened); - assert_eq!(res_unlink, Ok(()) ); + assert_eq!(res_unlink, Ok(())); // NetBSD (and others which inherit its implementation) defer removing the message // queue name until all references are closed, whereas Linux and others remove the @@ -178,10 +181,10 @@ fn test_mq_unlink() { #[cfg(not(any(target_os = "dragonfly", target_os = "netbsd")))] { let res_unlink_not_opened = mq_unlink(mq_name_not_opened); - assert_eq!(res_unlink_not_opened, Err(Errno::ENOENT) ); + assert_eq!(res_unlink_not_opened, Err(Errno::ENOENT)); } mq_close(mqd).unwrap(); let res_unlink_after_close = mq_unlink(mq_name_opened); - assert_eq!(res_unlink_after_close, Err(Errno::ENOENT) ); + assert_eq!(res_unlink_after_close, Err(Errno::ENOENT)); } diff --git a/bash-5.1/vendor/nix/test/test_net.rs b/bash-5.1/vendor/nix/test/test_net.rs index 40ecd6b..c44655a 100644 --- a/bash-5.1/vendor/nix/test/test_net.rs +++ b/bash-5.1/vendor/nix/test/test_net.rs @@ -3,10 +3,17 @@ use nix::net::if_::*; #[cfg(any(target_os = "android", target_os = "linux"))] const LOOPBACK: &[u8] = b"lo"; -#[cfg(not(any(target_os = "android", target_os = "linux")))] +#[cfg(not(any( + target_os = "android", + target_os = "linux", + target_os = "haiku" +)))] const LOOPBACK: &[u8] = b"lo0"; +#[cfg(target_os = "haiku")] +const LOOPBACK: &[u8] = b"loop"; + #[test] fn test_if_nametoindex() { - assert!(if_nametoindex(LOOPBACK).is_ok()); + if_nametoindex(LOOPBACK).expect("assertion failed"); } diff --git a/bash-5.1/vendor/nix/test/test_nix_path.rs b/bash-5.1/vendor/nix/test/test_nix_path.rs index e69de29..8b13789 100644 --- a/bash-5.1/vendor/nix/test/test_nix_path.rs +++ b/bash-5.1/vendor/nix/test/test_nix_path.rs @@ -0,0 +1 @@ + diff --git a/bash-5.1/vendor/nix/test/test_nmount.rs b/bash-5.1/vendor/nix/test/test_nmount.rs index 4c74ecf..dec806a 100644 --- a/bash-5.1/vendor/nix/test/test_nmount.rs +++ b/bash-5.1/vendor/nix/test/test_nmount.rs @@ -1,13 +1,9 @@ use crate::*; use nix::{ errno::Errno, - mount::{MntFlags, Nmount, unmount} -}; -use std::{ - ffi::CString, - fs::File, - path::Path + mount::{unmount, MntFlags, Nmount}, }; +use std::{ffi::CString, fs::File, path::Path}; use tempfile::tempdir; #[test] @@ -24,14 +20,15 @@ fn ok() { .str_opt(&fstype, &nullfs) .str_opt_owned("fspath", mountpoint.path().to_str().unwrap()) .str_opt_owned("target", target.path().to_str().unwrap()) - .nmount(MntFlags::empty()).unwrap(); - + .nmount(MntFlags::empty()) + .unwrap(); + // Now check that the sentry is visible through the mountpoint let exists = Path::exists(&mountpoint.path().join("sentry")); // Cleanup the mountpoint before asserting unmount(mountpoint.path(), MntFlags::empty()).unwrap(); - + assert!(exists); } @@ -44,8 +41,9 @@ fn bad_fstype() { let e = Nmount::new() .str_opt_owned("fspath", mountpoint.path().to_str().unwrap()) .str_opt_owned("target", target.path().to_str().unwrap()) - .nmount(MntFlags::empty()).unwrap_err(); - + .nmount(MntFlags::empty()) + .unwrap_err(); + assert_eq!(e.error(), Errno::EINVAL); assert_eq!(e.errmsg(), Some("Invalid fstype")); } diff --git a/bash-5.1/vendor/nix/test/test_poll.rs b/bash-5.1/vendor/nix/test/test_poll.rs index e4b369f..53964e2 100644 --- a/bash-5.1/vendor/nix/test/test_poll.rs +++ b/bash-5.1/vendor/nix/test/test_poll.rs @@ -1,7 +1,7 @@ use nix::{ errno::Errno, - poll::{PollFlags, poll, PollFd}, - unistd::{write, pipe} + poll::{poll, PollFd, PollFlags}, + unistd::{pipe, write}, }; macro_rules! loop_while_eintr { @@ -10,10 +10,10 @@ macro_rules! loop_while_eintr { match $poll_expr { Ok(nfds) => break nfds, Err(Errno::EINTR) => (), - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), } } - } + }; } #[test] @@ -37,10 +37,12 @@ fn test_poll() { // ppoll(2) is the same as poll except for how it handles timeouts and signals. // Repeating the test for poll(2) should be sufficient to check that our // bindings are correct. -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux" +))] #[test] fn test_ppoll() { use nix::poll::ppoll; @@ -53,14 +55,14 @@ fn test_ppoll() { // Poll an idle pipe. Should timeout let sigset = SigSet::empty(); - let nfds = loop_while_eintr!(ppoll(&mut fds, Some(timeout), sigset)); + let nfds = loop_while_eintr!(ppoll(&mut fds, Some(timeout), Some(sigset))); assert_eq!(nfds, 0); assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN)); write(w, b".").unwrap(); // Poll a readable pipe. Should return an event. - let nfds = ppoll(&mut fds, Some(timeout), SigSet::empty()).unwrap(); + let nfds = ppoll(&mut fds, Some(timeout), None).unwrap(); assert_eq!(nfds, 1); assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN)); } diff --git a/bash-5.1/vendor/nix/test/test_pty.rs b/bash-5.1/vendor/nix/test/test_pty.rs index 1a7cab8..5c27e2d 100644 --- a/bash-5.1/vendor/nix/test/test_pty.rs +++ b/bash-5.1/vendor/nix/test/test_pty.rs @@ -1,15 +1,15 @@ use std::fs::File; use std::io::{Read, Write}; -use std::path::Path; use std::os::unix::prelude::*; +use std::path::Path; use tempfile::tempfile; use libc::{_exit, STDOUT_FILENO}; -use nix::fcntl::{OFlag, open}; +use nix::fcntl::{open, OFlag}; use nix::pty::*; use nix::sys::stat; use nix::sys::termios::*; -use nix::unistd::{write, close, pause}; +use nix::unistd::{close, pause, write}; /// Regression test for Issue #659 /// This is the correct way to explicitly close a `PtyMaster` @@ -36,7 +36,7 @@ fn test_ptsname_equivalence() { assert!(master_fd.as_raw_fd() > 0); // Get the name of the slave - let slave_name = unsafe { ptsname(&master_fd) }.unwrap() ; + let slave_name = unsafe { ptsname(&master_fd) }.unwrap(); let slave_name_r = ptsname_r(&master_fd).unwrap(); assert_eq!(slave_name, slave_name_r); } @@ -58,7 +58,7 @@ fn test_ptsname_copy() { assert_eq!(slave_name1, slave_name2); // Also make sure that the string was actually copied and they point to different parts of // memory. - assert!(slave_name1.as_ptr() != slave_name2.as_ptr()); + assert_ne!(slave_name1.as_ptr(), slave_name2.as_ptr()); } /// Test data copying of `ptsname_r` @@ -73,7 +73,7 @@ fn test_ptsname_r_copy() { let slave_name1 = ptsname_r(&master_fd).unwrap(); let slave_name2 = ptsname_r(&master_fd).unwrap(); assert_eq!(slave_name1, slave_name2); - assert!(slave_name1.as_ptr() != slave_name2.as_ptr()); + assert_ne!(slave_name1.as_ptr(), slave_name2.as_ptr()); } /// Test that `ptsname` returns different names for different devices @@ -93,7 +93,7 @@ fn test_ptsname_unique() { // Get the name of the slave let slave_name1 = unsafe { ptsname(&master1_fd) }.unwrap(); let slave_name2 = unsafe { ptsname(&master2_fd) }.unwrap(); - assert!(slave_name1 != slave_name2); + assert_ne!(slave_name1, slave_name2); } /// Common setup for testing PTTY pairs @@ -111,7 +111,9 @@ fn open_ptty_pair() -> (PtyMaster, File) { let slave_name = unsafe { ptsname(&master) }.expect("ptsname failed"); // Open the slave device - let slave_fd = open(Path::new(&slave_name), OFlag::O_RDWR, stat::Mode::empty()).unwrap(); + let slave_fd = + open(Path::new(&slave_name), OFlag::O_RDWR, stat::Mode::empty()) + .unwrap(); #[cfg(target_os = "illumos")] // TODO: rewrite using ioctl! @@ -279,9 +281,9 @@ fn test_openpty_with_termios() { #[test] fn test_forkpty() { - use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::wait; + use nix::unistd::ForkResult::*; // forkpty calls openpty which uses ptname(3) internally. let _m0 = crate::PTSNAME_MTX.lock(); // forkpty spawns a child process @@ -289,15 +291,15 @@ fn test_forkpty() { let string = "naninani\n"; let echoed_string = "naninani\r\n"; - let pty = unsafe { - forkpty(None, None).unwrap() - }; + let pty = unsafe { forkpty(None, None).unwrap() }; match pty.fork_result { Child => { write(STDOUT_FILENO, string.as_bytes()).unwrap(); - pause(); // we need the child to stay alive until the parent calls read - unsafe { _exit(0); } - }, + pause(); // we need the child to stay alive until the parent calls read + unsafe { + _exit(0); + } + } Parent { child } => { let mut buf = [0u8; 10]; assert!(child.as_raw() > 0); @@ -306,6 +308,6 @@ fn test_forkpty() { wait().unwrap(); // keep other tests using generic wait from getting our child assert_eq!(&buf, echoed_string.as_bytes()); close(pty.master).unwrap(); - }, + } } } diff --git a/bash-5.1/vendor/nix/test/test_ptymaster_drop.rs b/bash-5.1/vendor/nix/test/test_ptymaster_drop.rs index a68f81e..ffbaa56 100644 --- a/bash-5.1/vendor/nix/test/test_ptymaster_drop.rs +++ b/bash-5.1/vendor/nix/test/test_ptymaster_drop.rs @@ -15,6 +15,6 @@ mod t { fn test_double_close() { let m = posix_openpt(OFlag::O_RDWR).unwrap(); close(m.as_raw_fd()).unwrap(); - drop(m); // should panic here + drop(m); // should panic here } } diff --git a/bash-5.1/vendor/nix/test/test_resource.rs b/bash-5.1/vendor/nix/test/test_resource.rs index c89d601..2ab581b 100644 --- a/bash-5.1/vendor/nix/test/test_resource.rs +++ b/bash-5.1/vendor/nix/test/test_resource.rs @@ -1,4 +1,9 @@ -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "illumos")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "illumos", + target_os = "haiku" +)))] use nix::sys::resource::{getrlimit, setrlimit, Resource}; /// Tests the RLIMIT_NOFILE functionality of getrlimit(), where the resource RLIMIT_NOFILE refers @@ -10,9 +15,15 @@ use nix::sys::resource::{getrlimit, setrlimit, Resource}; /// to put the new soft limit in effect, and then getrlimit() once more to ensure the limits have /// been updated. #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "illumos")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "illumos", + target_os = "haiku" +)))] pub fn test_resource_limits_nofile() { - let (mut soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap(); + let (mut soft_limit, hard_limit) = + getrlimit(Resource::RLIMIT_NOFILE).unwrap(); soft_limit -= 1; assert_ne!(soft_limit, hard_limit); diff --git a/bash-5.1/vendor/nix/test/test_sched.rs b/bash-5.1/vendor/nix/test/test_sched.rs index 922196a..ebf346d 100644 --- a/bash-5.1/vendor/nix/test/test_sched.rs +++ b/bash-5.1/vendor/nix/test/test_sched.rs @@ -24,7 +24,10 @@ fn test_sched_affinity() { let updated_affinity = sched_getaffinity(Pid::from_raw(0)).unwrap(); for field in 0..CpuSet::count() { // Should be set only for the CPU we set previously - assert_eq!(updated_affinity.is_set(field).unwrap(), field==last_valid_cpu) + assert_eq!( + updated_affinity.is_set(field).unwrap(), + field == last_valid_cpu + ) } // Finally, reset the initial CPU set diff --git a/bash-5.1/vendor/nix/test/test_sendfile.rs b/bash-5.1/vendor/nix/test/test_sendfile.rs index e56ff12..f73a3b5 100644 --- a/bash-5.1/vendor/nix/test/test_sendfile.rs +++ b/bash-5.1/vendor/nix/test/test_sendfile.rs @@ -62,7 +62,8 @@ fn test_sendfile64_linux() { #[test] fn test_sendfile_freebsd() { // Declare the content - let header_strings = vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let header_strings = + vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; let body = "Xabcdef123456"; let body_offset = 1; let trailer_strings = vec!["\n", "Served by Make Believe\n"]; @@ -72,8 +73,10 @@ fn test_sendfile_freebsd() { tmp.write_all(body.as_bytes()).unwrap(); // Prepare headers and trailers for sendfile - let headers: Vec<&[u8]> = header_strings.iter().map(|s| s.as_bytes()).collect(); - let trailers: Vec<&[u8]> = trailer_strings.iter().map(|s| s.as_bytes()).collect(); + let headers: Vec<&[u8]> = + header_strings.iter().map(|s| s.as_bytes()).collect(); + let trailers: Vec<&[u8]> = + trailer_strings.iter().map(|s| s.as_bytes()).collect(); // Prepare socket pair let (mut rd, wr) = UnixStream::pair().unwrap(); @@ -93,8 +96,9 @@ fn test_sendfile_freebsd() { wr.shutdown(Shutdown::Both).unwrap(); // Prepare the expected result - let expected_string = - header_strings.concat() + &body[body_offset..] + &trailer_strings.concat(); + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); // Verify the message that was sent assert_eq!(bytes_written as usize, expected_string.as_bytes().len()); @@ -109,7 +113,8 @@ fn test_sendfile_freebsd() { #[test] fn test_sendfile_dragonfly() { // Declare the content - let header_strings = vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let header_strings = + vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; let body = "Xabcdef123456"; let body_offset = 1; let trailer_strings = vec!["\n", "Served by Make Believe\n"]; @@ -119,8 +124,10 @@ fn test_sendfile_dragonfly() { tmp.write_all(body.as_bytes()).unwrap(); // Prepare headers and trailers for sendfile - let headers: Vec<&[u8]> = header_strings.iter().map(|s| s.as_bytes()).collect(); - let trailers: Vec<&[u8]> = trailer_strings.iter().map(|s| s.as_bytes()).collect(); + let headers: Vec<&[u8]> = + header_strings.iter().map(|s| s.as_bytes()).collect(); + let trailers: Vec<&[u8]> = + trailer_strings.iter().map(|s| s.as_bytes()).collect(); // Prepare socket pair let (mut rd, wr) = UnixStream::pair().unwrap(); @@ -138,8 +145,9 @@ fn test_sendfile_dragonfly() { wr.shutdown(Shutdown::Both).unwrap(); // Prepare the expected result - let expected_string = - header_strings.concat() + &body[body_offset..] + &trailer_strings.concat(); + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); // Verify the message that was sent assert_eq!(bytes_written as usize, expected_string.as_bytes().len()); @@ -154,7 +162,8 @@ fn test_sendfile_dragonfly() { #[test] fn test_sendfile_darwin() { // Declare the content - let header_strings = vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let header_strings = + vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; let body = "Xabcdef123456"; let body_offset = 1; let trailer_strings = vec!["\n", "Served by Make Believe\n"]; @@ -164,8 +173,10 @@ fn test_sendfile_darwin() { tmp.write_all(body.as_bytes()).unwrap(); // Prepare headers and trailers for sendfile - let headers: Vec<&[u8]> = header_strings.iter().map(|s| s.as_bytes()).collect(); - let trailers: Vec<&[u8]> = trailer_strings.iter().map(|s| s.as_bytes()).collect(); + let headers: Vec<&[u8]> = + header_strings.iter().map(|s| s.as_bytes()).collect(); + let trailers: Vec<&[u8]> = + trailer_strings.iter().map(|s| s.as_bytes()).collect(); // Prepare socket pair let (mut rd, wr) = UnixStream::pair().unwrap(); @@ -183,8 +194,9 @@ fn test_sendfile_darwin() { wr.shutdown(Shutdown::Both).unwrap(); // Prepare the expected result - let expected_string = - header_strings.concat() + &body[body_offset..] + &trailer_strings.concat(); + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); // Verify the message that was sent assert_eq!(bytes_written as usize, expected_string.as_bytes().len()); diff --git a/bash-5.1/vendor/nix/test/test_stat.rs b/bash-5.1/vendor/nix/test/test_stat.rs index 8baa655..55f15c0 100644 --- a/bash-5.1/vendor/nix/test/test_stat.rs +++ b/bash-5.1/vendor/nix/test/test_stat.rs @@ -1,42 +1,51 @@ -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] use std::fs; use std::fs::File; #[cfg(not(target_os = "redox"))] -use std::os::unix::fs::{symlink, PermissionsExt}; +use std::os::unix::fs::symlink; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use std::os::unix::fs::PermissionsExt; use std::os::unix::prelude::AsRawFd; #[cfg(not(target_os = "redox"))] -use std::time::{Duration, UNIX_EPOCH}; -#[cfg(not(target_os = "redox"))] use std::path::Path; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use std::time::{Duration, UNIX_EPOCH}; -#[cfg(not(any(target_os = "netbsd", target_os = "redox")))] -use libc::{S_IFMT, S_IFLNK}; use libc::mode_t; +#[cfg(not(any(target_os = "netbsd", target_os = "redox")))] +use libc::{S_IFLNK, S_IFMT}; -#[cfg(not(target_os = "redox"))] -use nix::fcntl; #[cfg(not(target_os = "redox"))] use nix::errno::Errno; #[cfg(not(target_os = "redox"))] -use nix::sys::stat::{self, futimens, utimes}; -use nix::sys::stat::{fchmod, stat}; -#[cfg(not(target_os = "redox"))] -use nix::sys::stat::{fchmodat, utimensat, mkdirat}; -#[cfg(any(target_os = "linux", - target_os = "haiku", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd"))] +use nix::fcntl; +#[cfg(any( + target_os = "linux", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +))] use nix::sys::stat::lutimes; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use nix::sys::stat::utimensat; #[cfg(not(target_os = "redox"))] -use nix::sys::stat::{FchmodatFlags, UtimensatFlags}; +use nix::sys::stat::FchmodatFlags; use nix::sys::stat::Mode; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use nix::sys::stat::UtimensatFlags; +#[cfg(not(target_os = "redox"))] +use nix::sys::stat::{self}; +use nix::sys::stat::{fchmod, stat}; +#[cfg(not(target_os = "redox"))] +use nix::sys::stat::{fchmodat, mkdirat}; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use nix::sys::stat::{futimens, utimes}; #[cfg(not(any(target_os = "netbsd", target_os = "redox")))] use nix::sys::stat::FileStat; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] use nix::sys::time::{TimeSpec, TimeVal, TimeValLike}; #[cfg(not(target_os = "redox"))] use nix::unistd::chdir; @@ -47,32 +56,35 @@ use nix::Result; #[cfg(not(any(target_os = "netbsd", target_os = "redox")))] fn assert_stat_results(stat_result: Result) { let stats = stat_result.expect("stat call failed"); - assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent - assert!(stats.st_mode > 0); // must be positive integer - assert_eq!(stats.st_nlink, 1); // there links created, must be 1 - assert_eq!(stats.st_size, 0); // size is 0 because we did not write anything to the file - assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_blocks <= 16); // Up to 16 blocks can be allocated for a blank file + assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent + assert!(stats.st_mode > 0); // must be positive integer + assert_eq!(stats.st_nlink, 1); // there links created, must be 1 + assert_eq!(stats.st_size, 0); // size is 0 because we did not write anything to the file + assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_blocks <= 16); // Up to 16 blocks can be allocated for a blank file } #[cfg(not(any(target_os = "netbsd", target_os = "redox")))] // (Android's st_blocks is ulonglong which is always non-negative.) #[cfg_attr(target_os = "android", allow(unused_comparisons))] -#[allow(clippy::absurd_extreme_comparisons)] // Not absurd on all OSes +#[allow(clippy::absurd_extreme_comparisons)] // Not absurd on all OSes fn assert_lstat_results(stat_result: Result) { let stats = stat_result.expect("stat call failed"); - assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent - assert!(stats.st_mode > 0); // must be positive integer + assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent + assert!(stats.st_mode > 0); // must be positive integer // st_mode is c_uint (u32 on Android) while S_IFMT is mode_t // (u16 on Android), and that will be a compile error. // On other platforms they are the same (either both are u16 or u32). - assert_eq!((stats.st_mode as usize) & (S_IFMT as usize), S_IFLNK as usize); // should be a link - assert_eq!(stats.st_nlink, 1); // there links created, must be 1 - assert!(stats.st_size > 0); // size is > 0 because it points to another file - assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent + assert_eq!( + (stats.st_mode as usize) & (S_IFMT as usize), + S_IFLNK as usize + ); // should be a link + assert_eq!(stats.st_nlink, 1); // there links created, must be 1 + assert!(stats.st_size > 0); // size is > 0 because it points to another file + assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent // st_blocks depends on whether the machine's file system uses fast // or slow symlinks, so just make sure it's not negative @@ -101,13 +113,11 @@ fn test_fstatat() { let tempdir = tempfile::tempdir().unwrap(); let filename = tempdir.path().join("foo.txt"); File::create(&filename).unwrap(); - let dirfd = fcntl::open(tempdir.path(), - fcntl::OFlag::empty(), - stat::Mode::empty()); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()); - let result = stat::fstatat(dirfd.unwrap(), - &filename, - fcntl::AtFlags::empty()); + let result = + stat::fstatat(dirfd.unwrap(), &filename, fcntl::AtFlags::empty()); assert_stat_results(result); } @@ -167,12 +177,15 @@ fn test_fchmodat() { let fullpath = tempdir.path().join(filename); File::create(&fullpath).unwrap(); - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); let mut mode1 = Mode::empty(); mode1.insert(Mode::S_IRUSR); mode1.insert(Mode::S_IWUSR); - fchmodat(Some(dirfd), filename, mode1, FchmodatFlags::FollowSymlink).unwrap(); + fchmodat(Some(dirfd), filename, mode1, FchmodatFlags::FollowSymlink) + .unwrap(); let file_stat1 = stat(&fullpath).unwrap(); assert_eq!(file_stat1.st_mode as mode_t & 0o7777, mode1.bits()); @@ -191,34 +204,42 @@ fn test_fchmodat() { /// /// The atime and mtime are expressed with a resolution of seconds because some file systems /// (like macOS's HFS+) do not have higher granularity. -#[cfg(not(target_os = "redox"))] -fn assert_times_eq(exp_atime_sec: u64, exp_mtime_sec: u64, attr: &fs::Metadata) { +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +fn assert_times_eq( + exp_atime_sec: u64, + exp_mtime_sec: u64, + attr: &fs::Metadata, +) { assert_eq!( Duration::new(exp_atime_sec, 0), - attr.accessed().unwrap().duration_since(UNIX_EPOCH).unwrap()); + attr.accessed().unwrap().duration_since(UNIX_EPOCH).unwrap() + ); assert_eq!( Duration::new(exp_mtime_sec, 0), - attr.modified().unwrap().duration_since(UNIX_EPOCH).unwrap()); + attr.modified().unwrap().duration_since(UNIX_EPOCH).unwrap() + ); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_utimes() { let tempdir = tempfile::tempdir().unwrap(); let fullpath = tempdir.path().join("file"); drop(File::create(&fullpath).unwrap()); - utimes(&fullpath, &TimeVal::seconds(9990), &TimeVal::seconds(5550)).unwrap(); + utimes(&fullpath, &TimeVal::seconds(9990), &TimeVal::seconds(5550)) + .unwrap(); assert_times_eq(9990, 5550, &fs::metadata(&fullpath).unwrap()); } #[test] -#[cfg(any(target_os = "linux", - target_os = "haiku", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd"))] +#[cfg(any( + target_os = "linux", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +))] fn test_lutimes() { let tempdir = tempfile::tempdir().unwrap(); let target = tempdir.path().join("target"); @@ -227,31 +248,39 @@ fn test_lutimes() { symlink(&target, &fullpath).unwrap(); let exp_target_metadata = fs::symlink_metadata(&target).unwrap(); - lutimes(&fullpath, &TimeVal::seconds(4560), &TimeVal::seconds(1230)).unwrap(); + lutimes(&fullpath, &TimeVal::seconds(4560), &TimeVal::seconds(1230)) + .unwrap(); assert_times_eq(4560, 1230, &fs::symlink_metadata(&fullpath).unwrap()); let target_metadata = fs::symlink_metadata(&target).unwrap(); - assert_eq!(exp_target_metadata.accessed().unwrap(), target_metadata.accessed().unwrap(), - "atime of symlink target was unexpectedly modified"); - assert_eq!(exp_target_metadata.modified().unwrap(), target_metadata.modified().unwrap(), - "mtime of symlink target was unexpectedly modified"); + assert_eq!( + exp_target_metadata.accessed().unwrap(), + target_metadata.accessed().unwrap(), + "atime of symlink target was unexpectedly modified" + ); + assert_eq!( + exp_target_metadata.modified().unwrap(), + target_metadata.modified().unwrap(), + "mtime of symlink target was unexpectedly modified" + ); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_futimens() { let tempdir = tempfile::tempdir().unwrap(); let fullpath = tempdir.path().join("file"); drop(File::create(&fullpath).unwrap()); - let fd = fcntl::open(&fullpath, fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let fd = fcntl::open(&fullpath, fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); futimens(fd, &TimeSpec::seconds(10), &TimeSpec::seconds(20)).unwrap(); assert_times_eq(10, 20, &fs::metadata(&fullpath).unwrap()); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_utimensat() { let _dr = crate::DirRestore::new(); let tempdir = tempfile::tempdir().unwrap(); @@ -259,16 +288,30 @@ fn test_utimensat() { let fullpath = tempdir.path().join(filename); drop(File::create(&fullpath).unwrap()); - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); - utimensat(Some(dirfd), filename, &TimeSpec::seconds(12345), &TimeSpec::seconds(678), - UtimensatFlags::FollowSymlink).unwrap(); + utimensat( + Some(dirfd), + filename, + &TimeSpec::seconds(12345), + &TimeSpec::seconds(678), + UtimensatFlags::FollowSymlink, + ) + .unwrap(); assert_times_eq(12345, 678, &fs::metadata(&fullpath).unwrap()); chdir(tempdir.path()).unwrap(); - utimensat(None, filename, &TimeSpec::seconds(500), &TimeSpec::seconds(800), - UtimensatFlags::FollowSymlink).unwrap(); + utimensat( + None, + filename, + &TimeSpec::seconds(500), + &TimeSpec::seconds(800), + UtimensatFlags::FollowSymlink, + ) + .unwrap(); assert_times_eq(500, 800, &fs::metadata(&fullpath).unwrap()); } @@ -277,20 +320,27 @@ fn test_utimensat() { fn test_mkdirat_success_path() { let tempdir = tempfile::tempdir().unwrap(); let filename = "example_subdir"; - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); - assert!((mkdirat(dirfd, filename, Mode::S_IRWXU)).is_ok()); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); + mkdirat(dirfd, filename, Mode::S_IRWXU).expect("mkdirat failed"); assert!(Path::exists(&tempdir.path().join(filename))); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_mkdirat_success_mode() { - let expected_bits = stat::SFlag::S_IFDIR.bits() | stat::Mode::S_IRWXU.bits(); + let expected_bits = + stat::SFlag::S_IFDIR.bits() | stat::Mode::S_IRWXU.bits(); let tempdir = tempfile::tempdir().unwrap(); let filename = "example_subdir"; - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); - assert!((mkdirat(dirfd, filename, Mode::S_IRWXU)).is_ok()); - let permissions = fs::metadata(tempdir.path().join(filename)).unwrap().permissions(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); + mkdirat(dirfd, filename, Mode::S_IRWXU).expect("mkdirat failed"); + let permissions = fs::metadata(tempdir.path().join(filename)) + .unwrap() + .permissions(); let mode = permissions.mode(); assert_eq!(mode as mode_t, expected_bits) } @@ -299,20 +349,27 @@ fn test_mkdirat_success_mode() { #[cfg(not(target_os = "redox"))] fn test_mkdirat_fail() { let tempdir = tempfile::tempdir().unwrap(); - let not_dir_filename= "example_not_dir"; + let not_dir_filename = "example_not_dir"; let filename = "example_subdir_dir"; - let dirfd = fcntl::open(&tempdir.path().join(not_dir_filename), fcntl::OFlag::O_CREAT, - stat::Mode::empty()).unwrap(); + let dirfd = fcntl::open( + &tempdir.path().join(not_dir_filename), + fcntl::OFlag::O_CREAT, + stat::Mode::empty(), + ) + .unwrap(); let result = mkdirat(dirfd, filename, Mode::S_IRWXU).unwrap_err(); assert_eq!(result, Errno::ENOTDIR); } #[test] -#[cfg(not(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "redox")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "haiku", + target_os = "redox" +)))] fn test_mknod() { use stat::{lstat, mknod, SFlag}; @@ -321,17 +378,20 @@ fn test_mknod() { let target = tempdir.path().join(file_name); mknod(&target, SFlag::S_IFREG, Mode::S_IRWXU, 0).unwrap(); let mode = lstat(&target).unwrap().st_mode as mode_t; - assert!(mode & libc::S_IFREG == libc::S_IFREG); - assert!(mode & libc::S_IRWXU == libc::S_IRWXU); + assert_eq!(mode & libc::S_IFREG, libc::S_IFREG); + assert_eq!(mode & libc::S_IRWXU, libc::S_IRWXU); } #[test] -#[cfg(not(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "ios", - target_os = "macos", - target_os = "redox")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "illumos", + target_os = "ios", + target_os = "macos", + target_os = "haiku", + target_os = "redox" +)))] fn test_mknodat() { use fcntl::{AtFlags, OFlag}; use nix::dir::Dir; @@ -339,7 +399,8 @@ fn test_mknodat() { let file_name = "test_file"; let tempdir = tempfile::tempdir().unwrap(); - let target_dir = Dir::open(tempdir.path(), OFlag::O_DIRECTORY, Mode::S_IRWXU).unwrap(); + let target_dir = + Dir::open(tempdir.path(), OFlag::O_DIRECTORY, Mode::S_IRWXU).unwrap(); mknodat( target_dir.as_raw_fd(), file_name, @@ -355,6 +416,6 @@ fn test_mknodat() { ) .unwrap() .st_mode as mode_t; - assert!(mode & libc::S_IFREG == libc::S_IFREG); - assert!(mode & libc::S_IRWXU == libc::S_IRWXU); + assert_eq!(mode & libc::S_IFREG, libc::S_IFREG); + assert_eq!(mode & libc::S_IRWXU, libc::S_IRWXU); } diff --git a/bash-5.1/vendor/nix/test/test_time.rs b/bash-5.1/vendor/nix/test/test_time.rs index dc307e5..5f76e61 100644 --- a/bash-5.1/vendor/nix/test/test_time.rs +++ b/bash-5.1/vendor/nix/test/test_time.rs @@ -11,12 +11,12 @@ use nix::time::{clock_gettime, ClockId}; #[cfg(not(target_os = "redox"))] #[test] pub fn test_clock_getres() { - assert!(nix::time::clock_getres(ClockId::CLOCK_REALTIME).is_ok()); + nix::time::clock_getres(ClockId::CLOCK_REALTIME).expect("assertion failed"); } #[test] pub fn test_clock_gettime() { - assert!(clock_gettime(ClockId::CLOCK_REALTIME).is_ok()); + clock_gettime(ClockId::CLOCK_REALTIME).expect("assertion failed"); } #[cfg(any( @@ -29,18 +29,18 @@ pub fn test_clock_gettime() { #[test] pub fn test_clock_getcpuclockid() { let clock_id = clock_getcpuclockid(nix::unistd::Pid::this()).unwrap(); - assert!(clock_gettime(clock_id).is_ok()); + clock_gettime(clock_id).unwrap(); } #[cfg(not(target_os = "redox"))] #[test] pub fn test_clock_id_res() { - assert!(ClockId::CLOCK_REALTIME.res().is_ok()); + ClockId::CLOCK_REALTIME.res().unwrap(); } #[test] pub fn test_clock_id_now() { - assert!(ClockId::CLOCK_REALTIME.now().is_ok()); + ClockId::CLOCK_REALTIME.now().unwrap(); } #[cfg(any( @@ -52,7 +52,8 @@ pub fn test_clock_id_now() { ))] #[test] pub fn test_clock_id_pid_cpu_clock_id() { - assert!(ClockId::pid_cpu_clock_id(nix::unistd::Pid::this()) + ClockId::pid_cpu_clock_id(nix::unistd::Pid::this()) .map(ClockId::now) - .is_ok()); + .unwrap() + .unwrap(); } diff --git a/bash-5.1/vendor/nix/test/test_timer.rs b/bash-5.1/vendor/nix/test/test_timer.rs index d07d963..ffd1468 100644 --- a/bash-5.1/vendor/nix/test/test_timer.rs +++ b/bash-5.1/vendor/nix/test/test_timer.rs @@ -1,5 +1,6 @@ use nix::sys::signal::{ - sigaction, SaFlags, SigAction, SigEvent, SigHandler, SigSet, SigevNotify, Signal, + sigaction, SaFlags, SigAction, SigEvent, SigHandler, SigSet, SigevNotify, + Signal, }; use nix::sys::timer::{Expiration, Timer, TimerSetTimeFlags}; use nix::time::ClockId; @@ -32,9 +33,12 @@ fn alarm_fires() { // Create a handler for the test signal, `SIG`. The handler is responsible // for flipping `ALARM_CALLED`. let handler = SigHandler::Handler(handle_sigalarm); - let signal_action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); - let old_handler = - unsafe { sigaction(SIG, &signal_action).expect("unable to set signal handler for alarm") }; + let signal_action = + SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); + let old_handler = unsafe { + sigaction(SIG, &signal_action) + .expect("unable to set signal handler for alarm") + }; // Create the timer. We use the monotonic clock here, though any would do // really. The timer is set to fire every 250 milliseconds with no delay for @@ -44,7 +48,8 @@ fn alarm_fires() { signal: SIG, si_value: 0, }); - let mut timer = Timer::new(clockid, sigevent).expect("failed to create timer"); + let mut timer = + Timer::new(clockid, sigevent).expect("failed to create timer"); let expiration = Expiration::Interval(TIMER_PERIOD.into()); let flags = TimerSetTimeFlags::empty(); timer.set(expiration, flags).expect("could not set timer"); @@ -60,12 +65,10 @@ fn alarm_fires() { // represents a delay to the next expiration. We're only interested in the // timer still being extant. match timer.get() { - Ok(Some(exp)) => { - assert!(matches!( - exp, - Expiration::Interval(..) | Expiration::IntervalDelayed(..) - )) - } + Ok(Some(exp)) => assert!(matches!( + exp, + Expiration::Interval(..) | Expiration::IntervalDelayed(..) + )), _ => panic!("timer lost its expiration"), } diff --git a/bash-5.1/vendor/nix/test/test_unistd.rs b/bash-5.1/vendor/nix/test/test_unistd.rs index 0f56b92..eee1010 100644 --- a/bash-5.1/vendor/nix/test/test_unistd.rs +++ b/bash-5.1/vendor/nix/test/test_unistd.rs @@ -1,15 +1,24 @@ -#[cfg(not(target_os = "redox"))] -use nix::fcntl::{self, open, readlink}; +use libc::{_exit, mode_t, off_t}; +use nix::errno::Errno; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use nix::fcntl::readlink; use nix::fcntl::OFlag; -use nix::unistd::*; -use nix::unistd::ForkResult::*; #[cfg(not(target_os = "redox"))] -use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction}; -use nix::sys::wait::*; +use nix::fcntl::{self, open}; +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] +use nix::pty::{grantpt, posix_openpt, ptsname, unlockpt}; +#[cfg(not(target_os = "redox"))] +use nix::sys::signal::{ + sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal, +}; use nix::sys::stat::{self, Mode, SFlag}; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] -use nix::pty::{posix_openpt, grantpt, unlockpt, ptsname}; -use nix::errno::Errno; +use nix::sys::wait::*; +use nix::unistd::ForkResult::*; +use nix::unistd::*; use std::env; #[cfg(not(any(target_os = "fuchsia", target_os = "redox")))] use std::ffi::CString; @@ -18,10 +27,13 @@ use std::fs::DirBuilder; use std::fs::{self, File}; use std::io::Write; use std::os::unix::prelude::*; -#[cfg(not(any(target_os = "fuchsia", target_os = "redox")))] +#[cfg(not(any( + target_os = "fuchsia", + target_os = "redox", + target_os = "haiku" +)))] use std::path::Path; use tempfile::{tempdir, tempfile}; -use libc::{_exit, mode_t, off_t}; use crate::*; @@ -31,7 +43,7 @@ fn test_fork_and_waitpid() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is signal-safe - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => unsafe { _exit(0) }, Parent { child } => { // assert that child was created and pid > 0 @@ -40,16 +52,17 @@ fn test_fork_and_waitpid() { let wait_status = waitpid(child, None); match wait_status { // assert that waitpid returned correct status and the pid is the one of the child - Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child), + Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child), // panic, must never happen - s @ Ok(_) => panic!("Child exited {:?}, should never happen", s), + s @ Ok(_) => { + panic!("Child exited {:?}, should never happen", s) + } // panic, waitpid should never fail - Err(s) => panic!("Error: waitpid returned Err({:?}", s) + Err(s) => panic!("Error: waitpid returned Err({:?}", s), } - - }, + } } } @@ -59,14 +72,14 @@ fn test_wait() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is signal-safe - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => unsafe { _exit(0) }, Parent { child } => { let wait_status = wait(); // just assert that (any) one child returns with WaitStatus::Exited assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0))); - }, + } } } @@ -80,15 +93,15 @@ fn test_mkstemp() { Ok((fd, path)) => { close(fd).unwrap(); unlink(path.as_path()).unwrap(); - }, - Err(e) => panic!("mkstemp failed: {}", e) + } + Err(e) => panic!("mkstemp failed: {}", e), } } #[test] fn test_mkstemp_directory() { // mkstemp should fail if a directory is given - assert!(mkstemp(&env::temp_dir()).is_err()); + mkstemp(&env::temp_dir()).expect_err("assertion failed"); } #[test] @@ -101,20 +114,24 @@ fn test_mkfifo() { let stats = stat::stat(&mkfifo_fifo).unwrap(); let typ = stat::SFlag::from_bits_truncate(stats.st_mode as mode_t); - assert!(typ == SFlag::S_IFIFO); + assert_eq!(typ, SFlag::S_IFIFO); } #[test] #[cfg(not(target_os = "redox"))] fn test_mkfifo_directory() { // mkfifo should fail if a directory is given - assert!(mkfifo(&env::temp_dir(), Mode::S_IRUSR).is_err()); + mkfifo(&env::temp_dir(), Mode::S_IRUSR).expect_err("assertion failed"); } #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat_none() { let _m = crate::CWD_LOCK.read(); @@ -130,8 +147,12 @@ fn test_mkfifoat_none() { #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat() { use nix::fcntl; @@ -141,26 +162,36 @@ fn test_mkfifoat() { mkfifoat(Some(dirfd), mkfifoat_name, Mode::S_IRUSR).unwrap(); - let stats = stat::fstatat(dirfd, mkfifoat_name, fcntl::AtFlags::empty()).unwrap(); + let stats = + stat::fstatat(dirfd, mkfifoat_name, fcntl::AtFlags::empty()).unwrap(); let typ = stat::SFlag::from_bits_truncate(stats.st_mode); assert_eq!(typ, SFlag::S_IFIFO); } #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat_directory_none() { let _m = crate::CWD_LOCK.read(); // mkfifoat should fail if a directory is given - assert!(mkfifoat(None, &env::temp_dir(), Mode::S_IRUSR).is_err()); + mkfifoat(None, &env::temp_dir(), Mode::S_IRUSR) + .expect_err("assertion failed"); } #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat_directory() { // mkfifoat should fail if a directory is given let tempdir = tempdir().unwrap(); @@ -168,7 +199,8 @@ fn test_mkfifoat_directory() { let mkfifoat_dir = "mkfifoat_dir"; stat::mkdirat(dirfd, mkfifoat_dir, Mode::S_IRUSR).unwrap(); - assert!(mkfifoat(Some(dirfd), mkfifoat_dir, Mode::S_IRUSR).is_err()); + mkfifoat(Some(dirfd), mkfifoat_dir, Mode::S_IRUSR) + .expect_err("assertion failed"); } #[test] @@ -201,7 +233,13 @@ mod linux_android { #[test] // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox", target_os = "fuchsia")))] +#[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_setgroups() { // Skip this test when not run as root as `setgroups()` requires root. skip_if_not_root!("test_setgroups"); @@ -224,11 +262,14 @@ fn test_setgroups() { #[test] // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms -#[cfg(not(any(target_os = "ios", - target_os = "macos", - target_os = "redox", - target_os = "fuchsia", - target_os = "illumos")))] +#[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku", + target_os = "illumos" +)))] fn test_initgroups() { // Skip this test when not run as root as `initgroups()` and `setgroups()` // require root. @@ -259,7 +300,7 @@ fn test_initgroups() { } #[cfg(not(any(target_os = "fuchsia", target_os = "redox")))] -macro_rules! execve_test_factory( +macro_rules! execve_test_factory ( ($test_name:ident, $syscall:ident, $exe: expr $(, $pathname:expr, $flags:expr)*) => ( #[cfg(test)] @@ -359,7 +400,7 @@ macro_rules! execve_test_factory( ) ); -cfg_if!{ +cfg_if! { if #[cfg(target_os = "android")] { execve_test_factory!(test_execve, execve, CString::new("/system/bin/sh").unwrap().as_c_str()); execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd()); @@ -384,7 +425,7 @@ cfg_if!{ #[cfg(any(target_os = "haiku", target_os = "linux", target_os = "openbsd"))] execve_test_factory!(test_execvpe, execvpe, &CString::new("sh").unwrap()); -cfg_if!{ +cfg_if! { if #[cfg(target_os = "android")] { use nix::fcntl::AtFlags; execve_test_factory!(test_execveat_empty, execveat, @@ -417,10 +458,10 @@ fn test_fchdir() { let tmpdir_path = tmpdir.path().canonicalize().unwrap(); let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd(); - assert!(fchdir(tmpdir_fd).is_ok()); + fchdir(tmpdir_fd).expect("assertion failed"); assert_eq!(getcwd().unwrap(), tmpdir_path); - assert!(close(tmpdir_fd).is_ok()); + close(tmpdir_fd).expect("assertion failed"); } #[test] @@ -430,7 +471,7 @@ fn test_getcwd() { let tmpdir = tempdir().unwrap(); let tmpdir_path = tmpdir.path().canonicalize().unwrap(); - assert!(chdir(&tmpdir_path).is_ok()); + chdir(&tmpdir_path).expect("assertion failed"); assert_eq!(getcwd().unwrap(), tmpdir_path); // make path 500 chars longer so that buffer doubling in getcwd @@ -441,9 +482,10 @@ fn test_getcwd() { for _ in 0..5 { let newdir = "a".repeat(100); inner_tmp_dir.push(newdir); - assert!(mkdir(inner_tmp_dir.as_path(), Mode::S_IRWXU).is_ok()); + mkdir(inner_tmp_dir.as_path(), Mode::S_IRWXU) + .expect("assertion failed"); } - assert!(chdir(inner_tmp_dir.as_path()).is_ok()); + chdir(inner_tmp_dir.as_path()).expect("assertion failed"); assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path()); } @@ -498,7 +540,8 @@ fn test_fchownat() { let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); - fchownat(Some(dirfd), "file", uid, gid, FchownatFlags::FollowSymlink).unwrap(); + fchownat(Some(dirfd), "file", uid, gid, FchownatFlags::FollowSymlink) + .unwrap(); chdir(tempdir.path()).unwrap(); fchownat(None, "file", uid, gid, FchownatFlags::FollowSymlink).unwrap(); @@ -541,7 +584,7 @@ fn test_lseek64() { close(tmpfd).unwrap(); } -cfg_if!{ +cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { macro_rules! require_acct{ () => { @@ -555,7 +598,7 @@ cfg_if!{ skip_if_jailed!("test_acct"); } } - } else if #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] { + } else if #[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] { macro_rules! require_acct{ () => { skip_if_not_root!("test_acct"); @@ -565,11 +608,15 @@ cfg_if!{ } #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_acct() { - use tempfile::NamedTempFile; use std::process::Command; use std::{thread, time}; + use tempfile::NamedTempFile; let _m = crate::FORK_MTX.lock(); require_acct!(); @@ -580,9 +627,11 @@ fn test_acct() { acct::enable(path).unwrap(); loop { - Command::new("echo").arg("Hello world"); + Command::new("echo").arg("Hello world").output().unwrap(); let len = fs::metadata(path).unwrap().len(); - if len > 0 { break; } + if len > 0 { + break; + } thread::sleep(time::Duration::from_millis(10)); } acct::disable().unwrap(); @@ -593,21 +642,36 @@ fn test_fpathconf_limited() { let f = tempfile().unwrap(); // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX); - assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0); + assert!( + path_max + .expect("fpathconf failed") + .expect("PATH_MAX is unlimited") + > 0 + ); } #[test] fn test_pathconf_limited() { // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test let path_max = pathconf("/", PathconfVar::PATH_MAX); - assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0); + assert!( + path_max + .expect("pathconf failed") + .expect("PATH_MAX is unlimited") + > 0 + ); } #[test] fn test_sysconf_limited() { // AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test let open_max = sysconf(SysconfVar::OPEN_MAX); - assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0); + assert!( + open_max + .expect("sysconf failed") + .expect("OPEN_MAX is unlimited") + > 0 + ); } #[cfg(target_os = "freebsd")] @@ -620,31 +684,34 @@ fn test_sysconf_unsupported() { assert!(open_max.expect("sysconf failed").is_none()) } - -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] #[test] fn test_getresuid() { let resuids = getresuid().unwrap(); - assert!(resuids.real.as_raw() != libc::uid_t::max_value()); - assert!(resuids.effective.as_raw() != libc::uid_t::max_value()); - assert!(resuids.saved.as_raw() != libc::uid_t::max_value()); + assert_ne!(resuids.real.as_raw(), libc::uid_t::MAX); + assert_ne!(resuids.effective.as_raw(), libc::uid_t::MAX); + assert_ne!(resuids.saved.as_raw(), libc::uid_t::MAX); } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] #[test] fn test_getresgid() { let resgids = getresgid().unwrap(); - assert!(resgids.real.as_raw() != libc::gid_t::max_value()); - assert!(resgids.effective.as_raw() != libc::gid_t::max_value()); - assert!(resgids.saved.as_raw() != libc::gid_t::max_value()); + assert_ne!(resgids.real.as_raw(), libc::gid_t::MAX); + assert_ne!(resgids.effective.as_raw(), libc::gid_t::MAX); + assert_ne!(resgids.saved.as_raw(), libc::gid_t::MAX); } // Test that we can create a pair of pipes. No need to verify that they pass @@ -652,25 +719,31 @@ fn test_getresgid() { #[test] fn test_pipe() { let (fd0, fd1) = pipe().unwrap(); - let m0 = stat::SFlag::from_bits_truncate(stat::fstat(fd0).unwrap().st_mode as mode_t); + let m0 = stat::SFlag::from_bits_truncate( + stat::fstat(fd0).unwrap().st_mode as mode_t, + ); // S_IFIFO means it's a pipe assert_eq!(m0, SFlag::S_IFIFO); - let m1 = stat::SFlag::from_bits_truncate(stat::fstat(fd1).unwrap().st_mode as mode_t); + let m1 = stat::SFlag::from_bits_truncate( + stat::fstat(fd1).unwrap().st_mode as mode_t, + ); assert_eq!(m1, SFlag::S_IFIFO); } // pipe2(2) is the same as pipe(2), except it allows setting some flags. Check // that we can set a flag. -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", - target_os = "redox", - target_os = "solaris"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "emscripten", + target_os = "freebsd", + target_os = "illumos", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd", + target_os = "redox", + target_os = "solaris" +))] #[test] fn test_pipe2() { use nix::fcntl::{fcntl, FcntlArg, FdFlag}; @@ -725,8 +798,13 @@ static mut ALARM_CALLED: bool = false; // Used in `test_alarm`. #[cfg(not(target_os = "redox"))] -pub extern fn alarm_signal_handler(raw_signal: libc::c_int) { - assert_eq!(raw_signal, libc::SIGALRM, "unexpected signal: {}", raw_signal); +pub extern "C" fn alarm_signal_handler(raw_signal: libc::c_int) { + assert_eq!( + raw_signal, + libc::SIGALRM, + "unexpected signal: {}", + raw_signal + ); unsafe { ALARM_CALLED = true }; } @@ -734,15 +812,16 @@ pub extern fn alarm_signal_handler(raw_signal: libc::c_int) { #[cfg(not(target_os = "redox"))] fn test_alarm() { use std::{ - time::{Duration, Instant,}, - thread + thread, + time::{Duration, Instant}, }; // Maybe other tests that fork interfere with this one? let _m = crate::SIGNAL_MTX.lock(); let handler = SigHandler::Handler(alarm_signal_handler); - let signal_action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); + let signal_action = + SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); let old_handler = unsafe { sigaction(Signal::SIGALRM, &signal_action) .expect("unable to set signal handler for alarm") @@ -759,7 +838,7 @@ fn test_alarm() { let starttime = Instant::now(); loop { thread::sleep(Duration::from_millis(100)); - if unsafe { ALARM_CALLED} { + if unsafe { ALARM_CALLED } { break; } if starttime.elapsed() > Duration::from_secs(3) { @@ -786,7 +865,7 @@ fn test_canceling_alarm() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_symlinkat() { let _m = crate::CWD_LOCK.read(); @@ -814,7 +893,7 @@ fn test_symlinkat() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_file() { let tempdir = tempdir().unwrap(); let oldfilename = "foo.txt"; @@ -827,15 +906,24 @@ fn test_linkat_file() { File::create(&oldfilepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt hard link file at relative path - linkat(Some(dirfd), oldfilename, Some(dirfd), newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + Some(dirfd), + oldfilename, + Some(dirfd), + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); assert!(newfilepath.exists()); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_olddirfd_none() { let _dr = crate::DirRestore::new(); @@ -851,16 +939,28 @@ fn test_linkat_olddirfd_none() { File::create(&oldfilepath).unwrap(); // Get file descriptor for base directory of new file - let dirfd = fcntl::open(tempdir_newfile.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = fcntl::open( + tempdir_newfile.path(), + fcntl::OFlag::empty(), + stat::Mode::empty(), + ) + .unwrap(); // Attempt hard link file using curent working directory as relative path for old file path chdir(tempdir_oldfile.path()).unwrap(); - linkat(None, oldfilename, Some(dirfd), newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + None, + oldfilename, + Some(dirfd), + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); assert!(newfilepath.exists()); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_newdirfd_none() { let _dr = crate::DirRestore::new(); @@ -876,16 +976,33 @@ fn test_linkat_newdirfd_none() { File::create(&oldfilepath).unwrap(); // Get file descriptor for base directory of old file - let dirfd = fcntl::open(tempdir_oldfile.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = fcntl::open( + tempdir_oldfile.path(), + fcntl::OFlag::empty(), + stat::Mode::empty(), + ) + .unwrap(); // Attempt hard link file using current working directory as relative path for new file path chdir(tempdir_newfile.path()).unwrap(); - linkat(Some(dirfd), oldfilename, None, newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + Some(dirfd), + oldfilename, + None, + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); assert!(newfilepath.exists()); } #[test] -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))] +#[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "haiku" +)))] fn test_linkat_no_follow_symlink() { let _m = crate::CWD_LOCK.read(); @@ -906,23 +1023,29 @@ fn test_linkat_no_follow_symlink() { symlinkat(&oldfilepath, None, &symoldfilepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt link symlink of file at relative path - linkat(Some(dirfd), symoldfilename, Some(dirfd), newfilename, LinkatFlags::NoSymlinkFollow).unwrap(); + linkat( + Some(dirfd), + symoldfilename, + Some(dirfd), + newfilename, + LinkatFlags::NoSymlinkFollow, + ) + .unwrap(); // Assert newfile is actually a symlink to oldfile. assert_eq!( - readlink(&newfilepath) - .unwrap() - .to_str() - .unwrap(), + readlink(&newfilepath).unwrap().to_str().unwrap(), oldfilepath.to_str().unwrap() ); } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_follow_symlink() { let _m = crate::CWD_LOCK.read(); @@ -943,15 +1066,26 @@ fn test_linkat_follow_symlink() { symlinkat(&oldfilepath, None, &symoldfilepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt link target of symlink of file at relative path - linkat(Some(dirfd), symoldfilename, Some(dirfd), newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + Some(dirfd), + symoldfilename, + Some(dirfd), + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); let newfilestat = stat::stat(&newfilepath).unwrap(); // Check the file type of the new link - assert_eq!((stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t) & SFlag::S_IFMT), + assert_eq!( + (stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t) + & SFlag::S_IFMT), SFlag::S_IFREG ); @@ -970,12 +1104,15 @@ fn test_unlinkat_dir_noremovedir() { DirBuilder::new().recursive(true).create(&dirpath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt unlink dir at relative path without proper flag - let err_result = unlinkat(Some(dirfd), dirname, UnlinkatFlags::NoRemoveDir).unwrap_err(); + let err_result = + unlinkat(Some(dirfd), dirname, UnlinkatFlags::NoRemoveDir).unwrap_err(); assert!(err_result == Errno::EISDIR || err_result == Errno::EPERM); - } +} #[test] #[cfg(not(target_os = "redox"))] @@ -988,12 +1125,14 @@ fn test_unlinkat_dir_removedir() { DirBuilder::new().recursive(true).create(&dirpath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt unlink dir at relative path with proper flag unlinkat(Some(dirfd), dirname, UnlinkatFlags::RemoveDir).unwrap(); assert!(!dirpath.exists()); - } +} #[test] #[cfg(not(target_os = "redox"))] @@ -1006,34 +1145,47 @@ fn test_unlinkat_file() { File::create(&filepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt unlink file at relative path unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir).unwrap(); assert!(!filepath.exists()); - } +} #[test] fn test_access_not_existing() { let tempdir = tempdir().unwrap(); let dir = tempdir.path().join("does_not_exist.txt"); - assert_eq!(access(&dir, AccessFlags::F_OK).err().unwrap(), - Errno::ENOENT); + assert_eq!( + access(&dir, AccessFlags::F_OK).err().unwrap(), + Errno::ENOENT + ); } #[test] fn test_access_file_exists() { let tempdir = tempdir().unwrap(); - let path = tempdir.path().join("does_exist.txt"); + let path = tempdir.path().join("does_exist.txt"); let _file = File::create(path.clone()).unwrap(); - assert!(access(&path, AccessFlags::R_OK | AccessFlags::W_OK).is_ok()); + access(&path, AccessFlags::R_OK | AccessFlags::W_OK) + .expect("assertion failed"); } +//Clippy false positive https://github.com/rust-lang/rust-clippy/issues/9111 +#[allow(clippy::needless_borrow)] #[cfg(not(target_os = "redox"))] #[test] fn test_user_into_passwd() { // get the UID of the "nobody" user - let nobody = User::from_name("nobody").unwrap().unwrap(); + #[cfg(not(target_os = "haiku"))] + let test_username = "nobody"; + // "nobody" unavailable on haiku + #[cfg(target_os = "haiku")] + let test_username = "user"; + + let nobody = User::from_name(test_username).unwrap().unwrap(); let pwd: libc::passwd = nobody.into(); let _: User = (&pwd).into(); } @@ -1052,8 +1204,7 @@ fn test_setfsuid() { // create a temporary file with permissions '-rw-r-----' let file = tempfile::NamedTempFile::new_in("/var/tmp").unwrap(); let temp_path = file.into_temp_path(); - dbg!(&temp_path); - let temp_path_2 = (&temp_path).to_path_buf(); + let temp_path_2 = temp_path.to_path_buf(); let mut permissions = fs::metadata(&temp_path).unwrap().permissions(); permissions.set_mode(0o640); @@ -1063,8 +1214,8 @@ fn test_setfsuid() { let fuid = setfsuid(nobody.uid); // trying to open the temporary file should fail with EACCES let res = fs::File::open(&temp_path); - assert!(res.is_err()); - assert_eq!(res.err().unwrap().kind(), io::ErrorKind::PermissionDenied); + let err = res.expect_err("assertion failed"); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); // assert fuid actually changes let prev_fuid = setfsuid(Uid::from_raw(-1i32 as u32)); @@ -1078,7 +1229,11 @@ fn test_setfsuid() { } #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_ttyname() { let fd = posix_openpt(OFlag::O_RDWR).expect("posix_openpt failed"); assert!(fd.as_raw_fd() > 0); @@ -1089,11 +1244,8 @@ fn test_ttyname() { grantpt(&fd).expect("grantpt failed"); unlockpt(&fd).expect("unlockpt failed"); let sname = unsafe { ptsname(&fd) }.expect("ptsname failed"); - let fds = open( - Path::new(&sname), - OFlag::O_RDWR, - stat::Mode::empty(), - ).expect("open failed"); + let fds = open(Path::new(&sname), OFlag::O_RDWR, stat::Mode::empty()) + .expect("open failed"); assert!(fds > 0); let name = ttyname(fds).expect("ttyname failed"); @@ -1109,7 +1261,11 @@ fn test_ttyname_not_pty() { } #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_ttyname_invalid_fd() { assert_eq!(ttyname(-1), Err(Errno::EBADF)); } @@ -1150,5 +1306,73 @@ fn test_getpeereid() { ))] fn test_getpeereid_invalid_fd() { // getpeereid is not POSIX, so error codes are inconsistent between different Unices. - assert!(getpeereid(-1).is_err()); + getpeereid(-1).expect_err("assertion failed"); +} + +#[test] +#[cfg(not(any(target_os = "illumos", target_os = "redox")))] +fn test_faccessat_none_not_existing() { + use nix::fcntl::AtFlags; + let tempdir = tempfile::tempdir().unwrap(); + let dir = tempdir.path().join("does_not_exist.txt"); + assert_eq!( + faccessat(None, &dir, AccessFlags::F_OK, AtFlags::empty()) + .err() + .unwrap(), + Errno::ENOENT + ); +} + +#[test] +#[cfg(not(any(target_os = "illumos", target_os = "redox")))] +fn test_faccessat_not_existing() { + use nix::fcntl::AtFlags; + let tempdir = tempfile::tempdir().unwrap(); + let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let not_exist_file = "does_not_exist.txt"; + assert_eq!( + faccessat( + Some(dirfd), + not_exist_file, + AccessFlags::F_OK, + AtFlags::empty(), + ) + .err() + .unwrap(), + Errno::ENOENT + ); +} + +#[test] +#[cfg(not(any(target_os = "illumos", target_os = "redox")))] +fn test_faccessat_none_file_exists() { + use nix::fcntl::AtFlags; + let tempdir = tempfile::tempdir().unwrap(); + let path = tempdir.path().join("does_exist.txt"); + let _file = File::create(path.clone()).unwrap(); + assert!(faccessat( + None, + &path, + AccessFlags::R_OK | AccessFlags::W_OK, + AtFlags::empty(), + ) + .is_ok()); +} + +#[test] +#[cfg(not(any(target_os = "illumos", target_os = "redox")))] +fn test_faccessat_file_exists() { + use nix::fcntl::AtFlags; + let tempdir = tempfile::tempdir().unwrap(); + let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let exist_file = "does_exist.txt"; + let path = tempdir.path().join(exist_file); + let _file = File::create(path.clone()).unwrap(); + assert!(faccessat( + Some(dirfd), + &path, + AccessFlags::R_OK | AccessFlags::W_OK, + AtFlags::empty(), + ) + .is_ok()); } diff --git a/bash-5.1/vendor/nom/.cargo-checksum.json b/bash-5.1/vendor/nom/.cargo-checksum.json new file mode 100644 index 0000000..5baf086 --- /dev/null +++ b/bash-5.1/vendor/nom/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"0ca452f3de1955e58ac7e6814077b430c0ee1dbf7e64c5348b6d7b0b997ffb27","Cargo.toml":"69edf4fdee4c17415625f77366f55cf6b3fd7410222c392a2b4bc262bf2e2bc9","LICENSE":"568d0ae12e18bf9dda98fcd838732321852abdb557c24900d474e71f8fd29f4e","src/bits.rs":"8cd8786191145b5365d381ffdf3aedf69002b6a8d40520c7b752c3e6adb83cc9","src/branch.rs":"e298f1d370a25e0a85f34186d38427f5805e745808f98586c2e8c51581e40480","src/bytes.rs":"bf0fe97e34f47d1f5d4ef93d3a00bd7553ae87ea248162cbce8872ea64c44b36","src/character.rs":"3891258d893c09833f6577dee5b9c7af3e12dc2e60458df542a8fcfb8516e068","src/internal.rs":"7be274fd578166404e0b8236417efeaa8a6cda4a8b10ab637083b1d6cba70f1c","src/lib.rs":"14300d7984ea66e052923e0db31b6c99840e5e234cc76042ce94645d2779c7ea","src/macros.rs":"58cde368c072e219ac19a83b7cb6eb9942d57030b2f74426110e8d91e7968145","src/methods.rs":"e6438ac91baec05fb898765879722d55bb54d9e96e29ab823ed34fe571802063","src/multi.rs":"318b4a345b185252515e1373e3fb1302d74ba3a0c65d44c55b4da39bf74a4c29","src/nom.rs":"48acec4a5dd92222823272e38b63e0decf33a31bdd3e97d22ed5d02ae4c6696c","src/regexp.rs":"8a780a8d328b31012a083ca763b8326e7126320a9071ea011629ddb9d82d178a","src/sequence.rs":"20055b97349f135fae182ba3755261439784b3b83572938ed2d9e4eda3c04758","src/simple_errors.rs":"0a37b042eba1c41da6d18b9249f3b7360f1732a5ed43150c39f36877b40594df","src/str.rs":"4cc81376b1d8c48709d73af357141554bbabb4e0546c1bb4606cfdd2ad8082cb","src/stream.rs":"f80895c621aae949a655576fc1082b65235d3e3af5d6a1cafcc9c0d2398264c9","src/traits.rs":"15db8ac6d5f698d9f55d23fbd025dd10f0e461533b34166e6234bf00e443f42e","src/util.rs":"5c8af3f73dff0efe3bcff59ff0c9cdbfeeecc4bafed14763c229a37bf26f7c99","src/verbose_errors.rs":"f640709d9bd8ffffb8baebab8252bc3d55e247a4c4ee814007b7fbda29856233","src/whitespace.rs":"0117cc62c288acd3ba53903fc14fd650934039919039ba5f83195e0435e12535","tests/arithmetic.rs":"aac143de5c80179f9cb71bf3c79268aa892876622b6f08d5e360ab9308f21341","tests/arithmetic_ast.rs":"bb8995cf726ac382e87dd9665f168cba0d25c8cc040372321027d23499ddea99","tests/blockbuf-arithmetic.rs":"485605360f68fc301390eff084657c27cb30347b8eaaed6d92a5830767d50ce6","tests/cross_function_backtracking.rs":"ea847fa762954e1ff8d8e4fbd130e453d57f41132735e4745286a2fbaf10dd6e","tests/float.rs":"7e380464cd8c2c315eaa2bcd3bb7407a4ba558ee5d6adde3ec72492c7987f784","tests/ini.rs":"c3b2b3ccd6b854c36dc89afc8d68877ff7f5cb8b2cb9d8f138e143deb8ee6ddc","tests/ini_str.rs":"7c5db358330be22e1c64900a8182f26881f7e5d38f1c78d827c60de0af68612f","tests/issues.rs":"d9af6f28be33a70732bec51213a4811910c656a1c38c4ffb5b3202efc188b4b6","tests/json.rs":"5d2c2f3f6ebb9f9c188f5b0cfad723a421ce161caceb3d8517d02fc6546fece6","tests/mp4.rs":"0e5f248dc9e27182ff82b3153481df529600bc4418b84f1f0554e1ada6cc3e08","tests/multiline.rs":"5165e95ba471f77dc0e614a716828d71bbcebcd42fe0fb882b7da1d9633222af","tests/named_args.rs":"3954a031e17e55e12e2bbb107c36a29e2204969ee2e4afb9cbd604decfe3f81a","tests/omnom.rs":"ff749d621b51df8aa3db289b1b626c706190fa15e29061dd5653de83635976d4","tests/overflow.rs":"aec98fc65bf102ae934625aa70e2b48cfcce70f4af38d6520716d79df3e95335","tests/reborrow_fold.rs":"8f140330dd0bfb3bbdab8286b4be6d6f698cadb7b064fac586dcca97e3d397fe","tests/test1.rs":"3e0c187bad91d822ebc113eb5cf30fc6585e53a961728304ac24e05ab2123d10"},"package":"05aec50c70fd288702bcd93284a8444607f3292dbdf2a30de5ea5dcdbe72287b"} \ No newline at end of file diff --git a/bash-5.1/vendor/nom/CHANGELOG.md b/bash-5.1/vendor/nom/CHANGELOG.md new file mode 100644 index 0000000..35e5236 --- /dev/null +++ b/bash-5.1/vendor/nom/CHANGELOG.md @@ -0,0 +1,825 @@ +# Change Log + +## [Unreleased][unreleased] + +### Changed + +## 3.2.1 - 2017-10-27 + +### Thanks + +- @ordian for `alt_complete` fixes +- @friedm for documentation fixes +- @kali for improving error management + +### Fixed + +- there were cases where `alt_complete` could return `Incomplete` + +### Added + +- an `into_error_kind` method can be used to transform any error to a common value. This helps when the library is included multiple times as dependency with different feature sets + + +## 3.2.0 - 2017-07-24 + +### Thanks + +- @jedireza for documentation fixes +- @gmorenz for the `bytes` combinator +- @meh for character combinator fixes for UTF-8 +- @jethrogb for avoiding move issues in `separated_list` + +### Changed + +- new layout for the main page of documentation +- `anychar` can now work on any input type +- `length_bytes` is now an alias for `length_data` + +### Fixed + +- `one_of`, `none_of` and `char` will now index correctly UTF-8 characters +- the `compiler_error` macro is now correctly exported + + +### Added + +- the `bytes` combinator transforms a bit stream back to a byte slice for child parsers + +## 3.1.0 - 2017-06-16 + +### Thanks + +- @sdroege: implementing be_i24 and le_i24 +- @Hywan: integrating faster substring search using memchr +- @nizox: fixing type issues in bit stream parsing +- @grissiom: documentation fixes +- @doomrobo: implementing separated_list_complete and separated_nonempty_list_complete +- @CWood1: fixing memchr integration in no_std +- @lu_zero: integrating the compiler_error crate +- @dtolnay: helping debug a type inference issue in map + +### Changed + +- memchr is used for substring search if possible +- if building on nightly, some common syntax errors will display a specific error message. If building no stable, display the documentation to activate those messages +- `count` no longer preallocates its vector + +### Fixed + +- better type inference in alt_complete +- `alt` should now work with whitespace parsing +- `map` should not make type inference errors anymore + +### Added + +- be_i24 and le_i24, parsing big endian and little endian signed 24 bit integers +- `separated_list_complete` and `separated_nonempty_list_complete` will treat incomplete from sub parsers as error + +## 3.0.0 - 2017-05-12 + +### Thanks + +- Chris Pick for some `Incomplete` related refactors +- @drbgn for documentation fixes +- @valarauca for adding `be_u24` +- @ithinuel for usability fixes +- @evuez for README readability fixes and improvements to `IResult` +- @s3bk for allowing non-`Copy` types as input +- @keruspe for documentation fixes +- @0xd34d10cc for trait fixes on `InputIter` +- @sdleffler for lifetime shenanigans on `named_args` +- @chengsun for type inference fixes in `alt` +- @iBelieve for adding str to no_std +- @Hywan for simplifying code in input traits +- @azerupi for extensive documentation of `alt` and `alt_complete` + +### Breaking Changes + +- `escaped`, `separated_list` and `separated_nonempty_list` can now return `Incomplete` when necessary +- `InputIter` does not require `AsChar` on its `Item` type anymore +- the `core` feature that was putting nom in `no_std` mode has been removed. There is now a `std` feature, activated by default. If it is not activated, nom is in `no_std` +- in `verbose-errors` mode, the error list is now stored in a `Vec` instead of a box based linked list +- `chain!` has finally been removed + +### Changed + +- `Endianness` now implements `Debug`, `PartialEq`, `Eq`, `Clone` and `Copy` +- custom input types can now be cloned if they're not `Copy` +- the infamous 'Cannot infer type for E' error should happen less often now +- `str` is now available in `no_std` mode + +### Fixed + +- `FileProducer` will be marked as `Eof` on full buffer +- `named_args!` now has lifetimes that cannot conflict with the lifetimes from other arguments + +### Added + +- `be_u24`: big endian 24 bit unsigned integer parsing +- `IResult` now has a `unwrap_or` method + + +## 2.2.1 - 2017-04-03 + +### Thanks + +- @Victor-Savu for formatting fixes in the README +- @chifflier for detecting and fixing integer overflows +- @utkarshkukreti for some performance improvements in benchmarks + +### Changed + +- when calculating how much data is needed in `IResult::Incomplete`, the addition could overflow (it is stored as a usize). This would apparently not result in any security vulnerability on release code + +## 2.2.0 - 2017-03-20 + +### Thanks + +- @seppo0010 for fixing `named_args` +- @keruspe for implementing or() on `IResult`, adding the option of default cases in `switch!`, adding support for `cargo-travis` +- @timlyo for documentation fixes +- @JayKickliter for extending `hex_u32` +- @1011X for fixing regex integration +- @Kerollmops for actually marking `chain!` as deprecated +- @joliss for documentation fixes +- @utkarshkukreti for tests refactoring and performance improvement +- @tmccombs for documentation fixes + +### Added + +- `IResult` gets an `or()` method +- `take_until1`, `take_until_and_consume1`, `take_till1!` and `take_till1_s!` require at least 1 character + +### Changed + +- `hex_u32` accepts uppercase digits as well +- the character based combinators leverage the input traits +- the whitespace parsers now work on &str and other types +- `take_while1` returns `Incomplete` on empty input +- `switch!` can now take a default case + +### Fixed + +- `named_args!` now imports `IResult` directly +- the upgrade to regex 0.2 broke the regex combinators, they work now + +## 2.1.0 - 2017-01-27 + +### Thanks + +- @nickbabcock for documentation fixes +- @derekdreery for documentation fixes +- @DirkyJerky for documentation fixes +- @saschagrunert for documentation fixes +- @lucab for documentation fixes +- @hyone for documentation fixes +- @tstorch for factoring `Slice` +- @shepmaster for adding crate categories +- @antoyo for adding `named_args!` + +### Added + +- `verify!` uses a first parser, then applies a function to check that its result satisfies some conditions +- `named_args!` creates a parser function that can accept other arguments along with the input +- `parse_to!` will use the `parse` method from `FromStr` to parse a value. It will automatically translate the input to a string if necessary +- `float`, `float_s`, `double`, `double_s` can recognize floating point numbers in text + +### Changed + +- `escaped!` will now return `Incomplete` if needed +- `permutation!` supports up to 20 child parsers + +## 2.0.1 - 2016-12-10 + +Bugfix release + +*Warning*: there is a small breaking change, `add_error!` is renamed to `add_return_error!`. This was planned for the 2.0 release but was forgotten. This is a small change in a feature that not many people use, for a release that is not yet widely in use, so there will be no 3.0 release for that change. + +### Thanks + +- @nickbabcock for catching and fixing the `add_error!` mixup +- @lucab for documentation fixes +- @jtdowney for noticing that `tag_no_case!` was not working at all for byte slices + +### Fixed + +- `add_error!` has been renamed to `add_return_error!` +- the `not!` combinator now accepts functions +- `tag_no_case!` is now working as accepted (before, it accepted everything) + + +## 2.0 - 2016-11-25 + +The 2.0 release is one of the biggest yet. It was a good opportunity to clean up some badly named combinators and fix invalid behaviours. + +Since this version introduces a few breaking changes, an [upgrade documentation](https://github.com/Geal/nom/blob/master/doc/upgrading_to_nom_2.md) is available, detailing the steps to fix the most common migration issues. After testing on a set of 30 crates, most of them will build directly, a large part will just need to activate the "verbose-errors" compilation feature. The remaining fixes are documented. + +This version also adds a lot of interesting features, like the permutation combinator or whitespace separated formats support. + +### Thanks + +- @lu-zero for license help +- @adamgreig for type inference fixes +- @keruspe for documentation and example fixes, for the `IResult => Result` conversion work, making `AsChar`'s method more consistent, and adding `many_till!` +- @jdeeny for implementing `Offset` on `&str` +- @vickenty for documentation fixes and his refactoring of `length_value!` and `length_bytes!` +- @overdrivenpotato for refactoring some combinators +- @taralx for documentation fixes +- @keeperofdakeys for fixing eol behaviour, writing documentation and adding `named_attr!` +- @jturner314 for writing documentation +- @bozaro for fixing compilation errors +- @uniphil for adding a `crates.io` badge +- @badboy for documentation fixes +- @jugglerchris for fixing `take_s!` +- @AndyShiue for implementing `Error` and `Display` on `ErrorKind` and detecting incorrect UTF-8 string indexing + +### Added + +- the "simple" error management system does not accumulates errors when backtracking. This is a big perf gain, and is activated by default in nom 2.0 +- nom can now work on any type that implement the traits defined in `src/traits.rs`: `InputLength`, `InputIter`, `InputTake`, `Compare`, `FindToken`, `FindSubstring`, `Slice` +- the documentation from Github's wiki has been moved to the `doc/` directory. They are markdown files that you can build with [cargo-external-doc](https://crates.io/crates/cargo-external-doc) +- whitespace separated format support: with the `ws!` combinator, you can automatically introduce whitespace parsers between all parsers and combinators +- the `permutation!` combinator applies its child parsers in any order, as long as they all succeed once, and return a tuple of the results +- `do_parse!` is a simpler alternative to `chain!`, which is now deprecated +- you can now transform an `IResult` in a `std::result::Result` +- `length_data!` parses a length, and returns a subslice of that length +- `tag_no_case!` provides case independent comparison. It works nicely, without any allocation, for ASCII strings, but for UTF-8 strings, it defaults to an unsatisfying (and incorrect) comparison by lowercasing both strings +- `named_attr!` creates functions like `named!` but can add attributes like documentation +- `many_till!` applies repeatedly its first child parser until the second succeeds + +### Changed + +- the "verbose" error management that was available in previous versions is now activated by the "verbose-errors" compilation feature +- code reorganization: most of the parsers were moved in separate files to make the source easier to navigate +- most of the combinators are now independent from the input type +- the `eof` function was replaced with the `eof!` macro +- `error!` and `add_error!` were replaced with `return_error!` and `add_return_error!` to fix the name conflict with the log crate +- the `offset()` method is now in the `Offset` trait +- `length_value!` has been renamed to `length_count!`. The new `length_value!` selects a slice and applies the second parser once on that slice +- `AsChar::is_0_to_9` is now `AsChar::is_dec_digit` +- the combinators with configurable endianness now take an enum instead of a boolean as parameter + +### Fixed +- the `count!`, `count_fixed!` and `length_*!` combinator calculate incomplete data needs correctly +- `eol`, `line_ending` and `not_line_ending` now have a consistent behaviour that works correctly with incomplete data +- `take_s!` didn't correctly handle the case when the slice is exactly the right length + +## 1.2.4 - 2016-07-20 + +### Thanks +- @Phlosioneer for documentation fixes +- @sourrust for fixing offsets in `take_bits!` +- @ChrisMacNaughton for the XFS crate +- @pwoolcoc for `rest_s` +- @fitzgen for more `IResult` methods +- @gtors for the negative lookahead feature +- @frk1 and @jeandudey for little endian float parsing +- @jethrogb for fixing input usage in `many1` +- @acatton for beating me at nom golf :D + +### Added +- the `rest_s` method on `IResult` returns the remaining `&str` input +- `unwrap_err` and `unwrap_inc` methods on `IResult` +- `not!` will peek at the input and return `Done` if the underlying parser returned `Error` or `Incomplete`, without consuming the input +- `le_f32` and `le_f64` parse little endian floating point numbers (IEEE 754) +- + +### Fixed +- documentation fixes +- `take_bits!` is now more precise +- `many1` inccorectly used the `len` function instead of `input_len` +- the INI parser is simpler +- `recognize!` had an early `return` that is removed now + +## 1.2.3 - 2016-05-10 + +### Thanks +- @lu-zero for the contribution guidelines +- @GuillaumeGomez for fixes on `length_bytes` and some documentation +- @Hywan for documentation and test fixes +- @Xirdus for correct trait import issues +- @mspiegel for the new AST example +- @cholcombe973 for adding the `cond_with_error!` combinator +- @tstorch for refactoring `many0!` +- @panicbit for the folding combinators +- @evestera for `separated_list!` fixes +- @DanielKeep for correcting some enum imports + +### Added +- Regular expression combinators starting with `re_bytes_` work on byte slices +- example parsing arithmetic expressions to an AST +- `cond_with_error!` works like `cond!` but will return `None` if the condition is false, and `Some(value)` if the underlying parser succeeded +- `fold_many0!`, `fold_many1!` and `fold_many_m_n!` will take a parser, an initial value and a combining function, and fold over the successful applications of the parser + +### Fixed +- `length_bytes!` converts the result of its child parser to usize +- `take_till!` now imports `InputLength` instead of assuming it's in scope +- `separated_list!` and `separated_nonempty_list!` will not consume the separator if there's no following successfully parsed value +- no more warnings on build + +### Changed +- simpler implementation of `many0!` + +## 1.2.2 - 2016-03-09 + +### Thanks +- @conradev for fixing `take_until_s!` +- @GuillaumeGomez for some documentation fixes +- @frewsxcv for some documentation fixes +- @tstorch for some test refactorings + +### Added +- `nom::Err` now implements `std::error::Error` + +### Fixed +- `hex_u32` does not parses more than 8 chars now +- `take_while!` and `take_while1!` will not perturb the behaviour of `recognize!` anymore + +## 1.2.1 - 2016-02-23 + +### Thanks +- @sourrust for adding methods to `IResult` +- @tstorch for the test refactoring, and for adding methods to `IResult` and `Needed` +- @joelself for fixing the method system + +### Added + +- mapping methods over `IResult` and `Needed` + +### Changed + +- `apply_rf` is renamed to `apply_m`. This will not warrant a major version, since it is part missing from the methods feture added in the 1.2.0 release +- the `regexp_macros` feature that used `regex!` to precompile regular expressions has been replaced by the normal regex engine combined with `lazy_static` + +### Fixed + +- when a parser or combinator was returning an empty buffer as remaining part, it was generating one from a static empty string. This was messing with buffer offset calculation. Now, that empty slice is taken like this: `&input[input.len()..]`. +- The `regexp_macros` and `no_std` feature build again and are now tested with Travis CI + +## 1.2.0 - 2016-02-08 + +### Thanks +- @zentner-kyle for type inference fixes +- @joelself for his work on `&str` parsing and method parsers +- @GuillaumeGomez for implementing methods on `IResult` +- @dirk for the `alt_complete!` combinator +- @tstorch for a lot of refactoring work and unit tests additions +- @jansegre for the hex digit parsers +- @belgum for some documentation fixes +- @lwandrebeck for some documentation fixes and code fixes in `hex_digit` + +### Added +- `take_until_and_consume_s!` for consumption of string data until a tag +- more function patterns in `named!`. The error type can now be specified +- `alt_complete!` works like the `alt!` combinator, but tries the next branch if the current one returned `Incomplete`, instead of returning directly +- more unit tests for a lot of combinators +- hexadecimal digit parsers +- the `tuple!` combinator takes a list of parsers as argument, and applies them serially on the input. If all of them are successful, it willr eturn a tuple accumulating all the values. This combinator will (hopefully) replace most uses of `chain!` +- parsers can now be implemented as a method for a struct thanks to the `method!`, `call_m!` and `apply_rf!` combinators + +### Fixed +- there were type inference issues in a few combinators. They will now be easier to compile +- `peek!` compilation with bare functions +- `&str` parsers were splitting data at the byte level, not at the char level, which can result in inconsistencies in parsing UTF-8 characters. They now use character indexes +- some method implementations were missing on `IResult` (with specified error type instead of implicit) + +## 1.1.0 - 2016-01-01 + +This release adds a lot of features related to `&str` parsing. The previous versions +were focused on `&[u8]` and bit streams parsing, but there's a need for more text +parsing with nom. The parsing functions like `alpha`, `digit` and others will now +accept either a `&[u8]` or a `&str`, so there is no breaking change on that part. + +There are also a few performance improvements and documentation fixes. + +### Thanks +- @Binero for pushing the work on `&str` parsing +- @meh for fixing `Option` and `Vec` imports +- @hoodie for a documentation fix +- @joelself for some documentation fixes +- @vberger for his traits magic making nom functions more generic + +### Added + +- string related parsers: `tag_s!`, `take_s!`, `is_a_s!`, `is_not_s!`, `take_while_s!`, `take_while1_s!`, `take_till_s!` +- `value!` is a combinator that always returns the same value. If a child parser is passed as second argument, that value is returned when the child parser succeeds + +### Changed + +- `tag!` will now compare even on partial input. If it expects "abcd" but receives "ef", it will now return an `Error` instead of `Incomplete` +- `many0!` and others will preallocate a larger vector to avoid some copies and reallocations +- `alpha`, `digit`, `alphanumeric`, `space` and `multispace` now accept as input a `&[u8]` or a `&str`. Additionally, they return an error if they receive an empty input +- `take_while!`, `take_while1!`, `take_while_s!`, `take_while1_s!` wilreturn an error on empty input + +### Fixed + +- if the child parser of `many0!` or `many1!` returns `Incomplete`, it will return `Incomplete` too, possibly updating the needed size +- `Option,` `Some`, `None` and `Vec` are now used with full path imports + +## 1.0.1 - 2015-11-22 + +This releases makes the 1.0 version compatible with Rust 1.2 and 1.3 + +### Thanks +- @steveklabnik for fixing lifetime issues in Producers and Consumers + +## 1.0.0 - 2015-11-16 + +Stable release for nom. A lot of new features, a few breaking changes + +### Thanks +- @ahenry for macro fixes +- @bluss for fixing documentation +- @sourrust for cleaning code and debugging the new streaming utilities +- @meh for inline optimizations +- @ccmtaylor for fixing function imports +- @soro for improvements to the streaming utilities +- @breard-r for catching my typos +- @nelsonjchen for catching my typos too +- @divarvel for hex string parsers +- @mrordinaire for the `length_bytes!` combinator + +### Breaking changes +- `IResult::Error` can now use custom error types, and is generic over the input type +- Producers and consumers have been replaced. The new implementation uses less memory and integrates more with parsers +- `nom::ErrorCode` is now `nom::ErrorKind` +- `filter!` has been renamed to `take_while!` +- `chain!` will count how much data is consumed and use that number to calculate how much data is needed if a parser returned `Incomplete` +- `alt!` returns `Incomplete` if a child parser returned `Incomplete`, instead of skipping to the next parser +- `IResult` does not require a lifetime tag anymore, yay! + +### Added + +- `complete!` will return an error if the child parser returned `Incomplete` +- `add_error!` will wrap an error, but allow backtracking +- `hex_u32` parser + +### Fixed +- the behaviour around `Incomplete` is better for most parsers now + +## 0.5.0 - 2015-10-16 + +This release fixes a few issues and stabilizes the code. + +### Thanks +- @nox for documentation fixes +- @daboross for linting fixes +- @ahenry for fixing `tap!` and extending `dbg!` and `dbg_dmp!` +- @bluss for tracking down and fixing issues with unsafe code +- @meh for inlining parser functions +- @ccmtaylor for fixing import of `str::from_utf8` + +### Fixed +- `tap!`, `dbg!` and `dbg_dmp!` now accept function parameters + +### Changed +- the type used in `count_fixed!` must be `Copy` +- `chain!` calculates how much data is needed if one of the parsers returns `Incomplete +- optional parsers in `chain!` can return `Incomplete` + +## 0.4.0 - 2015-09-08 + +Considering the number of changes since the last release, this version can contain breaking changes, so the version number becomes 0.4.0. A lot of new features and performance improvements! + +### Thanks +- @frewsxcv for documentation fixes +- @ngrewe for his work on producers and consumers +- @meh for fixes on `chain!` and for the `rest` parser +- @daboross for refactoring `many0!` and `many1!` +- @aleksander for the `switch!` combinator idea +- @TechnoMancer for his help with bit level parsing +- @sxeraverx for pointing out a bug in `is_a!` + +### Fixed +- `count_fixed!` must take an explicit type as argument to generate the fixed-size array +- optional parsing behaviour in `chain!` +- `count!` can take 0 elements +- `is_a!` and `is_not!` can now consume the whole input + +### Added +- it is now possible to seek to the end of a `MemProducer` +- `opt!` returns `Done(input, None)` if `the child parser returned `Incomplete` +- `rest` will return the remaining input +- consumers can now seek to and from the end of input +- `switch!` applies a first parser then matches on its result to choose the next parser +- bit-level parsers +- character-level parsers +- regular expression parsers +- implementation of `take_till!`, `take_while!` and `take_while1!` + +### Changed +- `alt!` can return `Incomplete` +- the error analysis functions will now take references to functions instead of moving them +- performance improvements on producers +- performance improvement for `filter!` +- performance improvement for `count!`: a `Vec` of the right size is directly allocated + +## 0.3.11 - 2015-08-04 + +### Thanks +- @bluss for remarking that the crate included random junk lying non commited in my local repository + +### Fixed +- cleanup of my local repository will ship less files in the crates, resulting in a smaller download + +## 0.3.10 - 2015-08-03 + +### Added + +- `bits!` for bit level parsing. It indicates that all child parsers will take a `(&[u8], usize)`as input, with the second parameter indicating the bit offset in the first byte. This allows viewing a byte slice as a bit stream. Most combinators can be used directly under `bits!` +- `take_bits!` takes an integer type and a number of bits, consumes that number of bits and updates the offset, possibly by crossing byte boundaries +- bit level parsers are all written in `src/bits.rs` + +### Changed + +- Parsers that specifically handle bytes have been moved to src/bytes.rs`. This applies to `tag!`, `is_not!`, `is_a!`, `filter!`, `take!`, `take_str!`, `take_until_and_consume!`, `take_until!`, `take_until_either_and_consume!`, `take_until_either!` + +## 0.3.9 - 2015-07-20 + +### Thanks +- @badboy for fixing `filter!` +- @idmit for some documentation fixes + +### Added +- `opt_res!` applies a parser and transform its result in a Result. This parser never fails +- `cond_reduce!` takes an expression as parameter, applies the parser if the expression is true, and returns an error if the expression is false +- `tap!` pass the result of a parser to a block to manipulate it, but do not affect the parser's result +- `AccReader` is a Read+BufRead that supports data accumulation and partial consumption. The `consume` method must be called afterwardsto indicate how much was consumed +- Arithmetic expression evaluation and parsing example +- `u16!`, `u32!`, `u64!`, `i16!`, `i32!`, `i64!` take an expression as parameter, if the expression is true, apply the big endian integer parser, if false, the little endian version +- type information for combinators. This will make the documentation a bit easier to navigate + +### Fixed +- `map_opt!` and `map_res!` had issues with argument order due to bad macros +- `delimited!` did not compile for certain combinations of arguments +- `filter!` did not return a byte slice but a fixed array + +## 0.3.8 - 2015-07-03 + +### Added +- code coverage is now calculated automatically on Travis CI +- `Stepper`: wrap a `Producer`, and call the method `step` with a parser. This method will buffer data if there is not enough, apply the parser if there is, and keep the rest of the input in memory for the next call +- `ReadProducer`: takes something implementing `Read`, and makes a `Producer` out of it + +### Fixed +- the combinators `separated_pair!` and `delimited!` did not work because an implementation macro was not exported +- if a `MemProducer` reached its end, it should always return `Eof` +- `map!` had issues with argument matching + +## 0.3.7 - 2015-06-24 + +### Added +- `expr_res!` and `expr_opt!` evaluate an expression returning a Result or Opt and convert it to IResult +- `AsBytes` is implemented for fixed size arrays. This allows `tag!([41u8, 42u8])` + +### Fixed +- `count_fixed!` argument parsing works again + +## 0.3.6 - 2015-06-15 + +### Added +- documentation for a few functions +- the consumer trait now requires the `failed(&self, error_code)` method in case of parsing error +- `named!` now handles thge alternative `named!(pub fun_name, ...)` + +### Fixed +- `filter!` now returns the whole input if the filter function never returned false +- `take!` casts its argument as usize, so it can accepts any integer type now + +## 0.3.5 - 2015-06-10 + +### Thanks +- @cmr for some documentation fixes + +### Added +- `count_fixed!` returns a fixed array + +### Fixed +- `count!` is back to the previous behaviour, returning a `Vec` for sizes known at runtime + +### Changed +- functions and traits exported from `nom::util` are now directly in `nom::` + +## 0.3.4 - 2015-06-09 + +### Thanks +- @andrew-d for fixes on `cond!` +- @keruspe for features in `chain!` + +### Added +- `chain!` can now have mutable fields + +### Fixed +- `cond!` had an infinite macro recursion + +### Changed +- `chain!` generates less code now. No apprent compilation time improvement + +## 0.3.3 - 2015-06-09 + +### Thanks +- @andrew-d for the little endian signed integer parsers +- @keruspe for fixes on `count!` + +### Added +- `le_i8`, `le_i16`, `le_i32`, `le_i64`: little endian signed integer parsers + +### Changed +- the `alt!` parser compiles much faster, even with more than 8 branches +- `count!` can now return a fixed size array instead of a growable vector + +## 0.3.2 - 2015-05-31 + +### Thanks +- @keruspe for the `take_str` parser and the function application combinator + +### Added +- `take_str!`: takes the specified number of bytes and return a UTF-8 string +- `apply!`: do partial application on the parameters of a function + +### Changed +- `Needed::Size` now contains a `usize` instead of a `u32` + +## 0.3.1 - 2015-05-21 + +### Thanks +- @divarvel for the big endian signed integer parsers + +### Added +- `be_i8`, `be_i16`, `be_i32`, `be_i64`: big endian signed integer parsers +- the `core` feature can be passed to cargo to build with `no_std` +- colored hexdump can be generated from error chains + +## 0.3.0 - 2015-05-07 + +### Thanks +- @filipegoncalves for some documentation and the new eof parser +- @CrimsonVoid for putting fully qualified types in the macros +- @lu_zero for some documentation fixes + +### Added +- new error types that can contain an error code, an input slice, and a list of following errors +- `error!` will cut backtracking and return directly from the parser, with a specified error code +- `eof` parser, successful if there is no more input +- specific error codes for the parsers provided by nom + +### Changed +- fully qualified types in macros. A lot of imports are not needed anymore + +### Removed +- `FlatMap`, `FlatpMapOpt` and `Functor` traits (replaced by `map!`, `map_opt!` and `map_res!`) + +## 0.2.2 - 2015-04-12 + +### Thanks +- @filipegoncalves and @thehydroimpulse for debugging an infinite loop in many0 and many1 +- @thehydroimpulse for suggesting public named parsers +- @skade for removing the dependency on the collections gate + +### Added +- `named!` can now declare public functions like this: `named!(pub tst, tag!("abcd"));` +- `pair!(X,Y)` returns a tuple `(x, y)` +- `separated_pair!(X, sep, Y)` returns a tuple `(x, y)` +- `preceded!(opening, X)` returns `x` +- `terminated!(X, closing)` returns `x` +- `delimited(opening, X, closing)` returns `x` +- `separated_list(sep, X)` returns a `Vec` +- `separated_nonempty_list(sep, X)` returns a `Vec` of at list one element + +### Changed +- `many0!` and `many1!` forbid parsers that do not consume input +- `is_a!`, `is_not!`, `alpha`, `digit`, `space`, `multispace` will now return an error if they do not consume at least one byte + +## 0.2.1 - 2015-04-04 + +### Thanks +- @mtsr for catching the remaining debug println! +- @jag426 who killed a lot of warnings +- @skade for removing the dependency on the core feature gate + + +### Added +- little endian unsigned int parsers le_u8, le_u16, le_u32, le_u64 +- `count!` to apply a parser a specified number of times +- `cond!` applies a parser if the condition is met +- more parser development tools in `util::*` + +### Fixed +- in one case, `opt!` would not compile + +### Removed +- most of the feature gates are now removed. The only one still needed is `collections` + +## 0.2.0 - 2015-03-24 +*works with `rustc 1.0.0-dev (81e2396c7 2015-03-19) (built 2015-03-19)`* + +### Thanks +- Ryman for the AsBytes implementation +- jag426 and jaredly for documentation fixes +- eternaleye on #rust IRC for his help on the new macro syntax + +### Changed +- the AsBytes trait improves readability, no more b"...", but "..." instead +- Incomplete will now hold either Needed;;Unknown, or Needed::Size(u32). Matching on Incomplete without caring for the value is done with `Incomplete(_)`, but if more granularity is mandatory, `Needed` can be matched too +- `alt!` can pass the result of the parser to a closure +- the `take_*` macros changed behaviour, the default case is now not to consume the separator. The macros have been renamed as follows: `take_until!` -> `take_until_and_consume!`, `take_until_and_leave!` -> `take_until!`, `take_until_either_and_leave!` -> `take_until_either!`, `take_until_either!` -> `take_until_either_and_consume!` + +### Added +- `peek!` macro: matches the future input but does not consume it +- `length_value!` macro: the first argument is a parser returning a `n` that can cast to usize, then applies the second parser `n` times. The macro has a variant with a third argument indicating the expected input size for the second parser +- benchmarks are available at https://github.com/Geal/nom_benchmarks +- more documentation +- **Unnamed parser syntax**: warning, this is a breaking change. With this new syntax, the macro combinators do not generate functions anymore, they create blocks. That way, they can be nested, for better readability. The `named!` macro is provided to create functions from parsers. Please be aware that nesting parsers comes with a small cost of compilation time, negligible in most cases, but can quickly get to the minutes scale if not careful. If this happens, separate your parsers in multiple subfunctions. +- `named!`, `closure!` and `call!` macros used to support the unnamed syntax +- `map!`, `map_opt!` and `map_res!` to combine a parser with a normal function, transforming the input directly, or returning an `Option` or `Result` + +### Fixed +- `is_a!` is now working properly + +### Removed +- the `o!` macro does less than `chain!`, so it has been removed +- the `fold0!` and `fold1!` macros were too complex and awkward to use, the `many*` combinators will be useful for most uses for now + +## 0.1.6 - 2015-02-24 +### Changed +- consumers must have an end method that will be called after parsing + +### Added +- big endian unsigned int and float parsers: be_u8, be_u16, be_u32, be_u64, be_f32, be_f64 +- producers can seek +- function and macros documentation +- README documentation +### Fixed +- lifetime declarations +- tag! can return Incomplete + +## 0.1.5 - 2015-02-17 +### Changed +- traits were renamed: FlatMapper -> FlatMap, Mapper -> FlatMapOpt, Mapper2 -> Functor + +### Fixed +- woeks with rustc f1bb6c2f4 + +## 0.1.4 - 2015-02-17 +### Changed +- the chaining macro can take optional arguments with '?' + +## 0.1.3 - 2015-02-16 +### Changed +- the chaining macro now takes the closure at the end of the argument list + +## 0.1.2 - 2015-02-16 +### Added +- flat_map implementation for <&[u8], &[u8]> +- chaining macro +- partial MP4 parser example + + +## 0.1.1 - 2015-02-06 +### Fixed +- closure syntax change + +## Compare code + +* [unreleased]: https://github.com/Geal/nom/compare/3.2.1...HEAD +* [3.2.1]: https://github.com/Geal/nom/compare/3.2.0...3.2.1 +* [3.2.0]: https://github.com/Geal/nom/compare/3.1.0...3.2.0 +* [3.1.0]: https://github.com/Geal/nom/compare/3.0.0...3.1.0 +* [3.0.0]: https://github.com/Geal/nom/compare/2.2.1...3.0.0 +* [2.2.1]: https://github.com/Geal/nom/compare/2.2.0...2.2.1 +* [2.2.0]: https://github.com/Geal/nom/compare/2.1.0...2.2.0 +* [2.1.0]: https://github.com/Geal/nom/compare/2.0.1...2.1.0 +* [2.0.1]: https://github.com/Geal/nom/compare/2.0.0...2.0.1 +* [2.0.0]: https://github.com/Geal/nom/compare/1.2.4...2.0.0 +* [1.2.4]: https://github.com/Geal/nom/compare/1.2.3...1.2.4 +* [1.2.3]: https://github.com/Geal/nom/compare/1.2.2...1.2.3 +* [1.2.2]: https://github.com/Geal/nom/compare/1.2.1...1.2.2 +* [1.2.1]: https://github.com/Geal/nom/compare/1.2.0...1.2.1 +* [1.2.0]: https://github.com/Geal/nom/compare/1.1.0...1.2.0 +* [1.1.0]: https://github.com/Geal/nom/compare/1.0.1...1.1.0 +* [1.0.1]: https://github.com/Geal/nom/compare/1.0.0...1.0.1 +* [1.0.0]: https://github.com/Geal/nom/compare/0.5.0...1.0.0 +* [0.5.0]: https://github.com/geal/nom/compare/0.4.0...0.5.0 +* [0.4.0]: https://github.com/geal/nom/compare/0.3.11...0.4.0 +* [0.3.11]: https://github.com/geal/nom/compare/0.3.10...0.3.11 +* [0.3.10]: https://github.com/geal/nom/compare/0.3.9...0.3.10 +* [0.3.9]: https://github.com/geal/nom/compare/0.3.8...0.3.9 +* [0.3.8]: https://github.com/Geal/nom/compare/0.3.7...0.3.8 +* [0.3.7]: https://github.com/Geal/nom/compare/0.3.6...0.3.7 +* [0.3.6]: https://github.com/Geal/nom/compare/0.3.5...0.3.6 +* [0.3.5]: https://github.com/Geal/nom/compare/0.3.4...0.3.5 +* [0.3.4]: https://github.com/Geal/nom/compare/0.3.3...0.3.4 +* [0.3.3]: https://github.com/Geal/nom/compare/0.3.2...0.3.3 +* [0.3.2]: https://github.com/Geal/nom/compare/0.3.1...0.3.2 +* [0.3.1]: https://github.com/Geal/nom/compare/0.3.0...0.3.1 +* [0.3.0]: https://github.com/Geal/nom/compare/0.2.2...0.3.0 +* [0.2.2]: https://github.com/Geal/nom/compare/0.2.1...0.2.2 +* [0.2.1]: https://github.com/Geal/nom/compare/0.2.0...0.2.1 +* [0.2.0]: https://github.com/Geal/nom/compare/0.1.6...0.2.0 +* [0.1.6]: https://github.com/Geal/nom/compare/0.1.5...0.1.6 +* [0.1.5]: https://github.com/Geal/nom/compare/0.1.4...0.1.5 +* [0.1.4]: https://github.com/Geal/nom/compare/0.1.3...0.1.4 +* [0.1.3]: https://github.com/Geal/nom/compare/0.1.2...0.1.3 +* [0.1.2]: https://github.com/Geal/nom/compare/0.1.1...0.1.2 +* [0.1.1]: https://github.com/Geal/nom/compare/0.1.0...0.1.1 diff --git a/bash-5.1/vendor/nom/Cargo.toml b/bash-5.1/vendor/nom/Cargo.toml new file mode 100644 index 0000000..1ee10cf --- /dev/null +++ b/bash-5.1/vendor/nom/Cargo.toml @@ -0,0 +1,50 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "nom" +version = "3.2.1" +authors = ["contact@geoffroycouprie.com"] +include = ["CHANGELOG.md", "LICENSE", ".gitignore", ".travis.yml", "Cargo.toml", "src/*.rs", "tests/*.rs"] +description = "A byte-oriented, zero-copy, parser combinators library" +documentation = "http://rust.unhandledexpression.com/nom/" +readme = "README.md" +keywords = ["parser", "parser-combinators", "parsing", "streaming", "bit"] +categories = ["parsing"] +license = "MIT" +repository = "https://github.com/Geal/nom" +[dependencies.memchr] +version = "^1.0.1" +default-features = false + +[dependencies.compiler_error] +version = "0.1.1" +optional = true + +[dependencies.regex] +version = "^0.2" +optional = true + +[dependencies.lazy_static] +version = "^0.2.2" +optional = true + +[features] +default = ["std", "stream"] +regexp = ["regex"] +verbose-errors = [] +stream = [] +nightly = ["compiler_error"] +regexp_macros = ["regexp", "lazy_static"] +std = ["memchr/use_std"] +[badges.travis-ci] +repository = "Geal/nom" diff --git a/bash-5.1/vendor/nom/LICENSE b/bash-5.1/vendor/nom/LICENSE new file mode 100644 index 0000000..a885458 --- /dev/null +++ b/bash-5.1/vendor/nom/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2015-2016 Geoffroy Couprie + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/nom/src/bits.rs b/bash-5.1/vendor/nom/src/bits.rs new file mode 100644 index 0000000..d475cd3 --- /dev/null +++ b/bash-5.1/vendor/nom/src/bits.rs @@ -0,0 +1,394 @@ +//! Bit level parsers and combinators +//! +//! Bit parsing is handled by tweaking the input in most macros. +//! In byte level parsing, the input is generally a `&[u8]` passed from combinator +//! to combinator until the slices are manipulated. +//! +//! Bit parsers take a `(&[u8], usize)` as input. The first part of the tuple is an byte slice, +//! the second part is a bit offset in the first byte of the slice. +//! +//! By passing a pair like this, we can leverage most of the combinators, and avoid +//! transforming the whole slice to a vector of booleans. This should make it easy +//! to see a byte slice as a bit stream, and parse code points of arbitrary bit length. + + +/// `bits!( parser ) => ( &[u8], (&[u8], usize) -> IResult<(&[u8], usize), T> ) -> IResult<&[u8], T>` +/// transforms its byte slice input into a bit stream for the underlying parsers +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!( take_3_bits, bits!( take_bits!( u8, 3 ) ) ); +/// +/// let input = vec![0b10101010, 0b11110000, 0b00110011]; +/// let sl = &input[..]; +/// +/// assert_eq!(take_3_bits( sl ), Done(&sl[1..], 5) ); +/// # } +#[macro_export] +macro_rules! bits ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + bits_impl!($i, $submac!($($args)*)); + ); + ($i:expr, $f:expr) => ( + bits_impl!($i, call!($f)); + ); +); + +#[cfg(feature = "verbose-errors")] +/// Internal parser, do not use directly +#[doc(hidden)] +#[macro_export] +macro_rules! bits_impl ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let input = ($i, 0usize); + match $submac!(input, $($args)*) { + $crate::IResult::Error(e) => { + let err = match e { + $crate::Err::Code(k) | $crate::Err::Node(k, _) => $crate::Err::Code(k), + $crate::Err::Position(k, (i,b)) | $crate::Err::NodePosition(k, (i,b), _) => { + $crate::Err::Position(k, &i[b/8..]) + } + }; + $crate::IResult::Error(err) + } + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + //println!("bits parser returned Needed::Size({})", i); + $crate::IResult::Incomplete($crate::Needed::Size(i / 8 + 1)) + }, + $crate::IResult::Done((i, bit_index), o) => { + let byte_index = bit_index / 8 + if bit_index % 8 == 0 { 0 } else { 1 } ; + //println!("bit index=={} => byte index=={}", bit_index, byte_index); + $crate::IResult::Done(&i[byte_index..], o) + } + } + } + ); +); + +#[cfg(not(feature = "verbose-errors"))] +/// Internal parser, do not use directly +#[doc(hidden)] +#[macro_export] +macro_rules! bits_impl ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let input = ($i, 0usize); + match $submac!(input, $($args)*) { + $crate::IResult::Error(e) => { + $crate::IResult::Error(e) + } + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + //println!("bits parser returned Needed::Size({})", i); + $crate::IResult::Incomplete($crate::Needed::Size(i / 8 + 1)) + }, + $crate::IResult::Done((i, bit_index), o) => { + let byte_index = bit_index / 8 + if bit_index % 8 == 0 { 0 } else { 1 } ; + //println!("bit index=={} => byte index=={}", bit_index, byte_index); + $crate::IResult::Done(&i[byte_index..], o) + } + } + } + ); +); + +/// Counterpart to bits, +/// `bytes!( parser ) => ( (&[u8], usize), &[u8] -> IResult<&[u8], T> ) -> IResult<(&[u8], usize), T>`, +/// transforms its bits stream input into a byte slice for the underlying parsers. If we start in the +/// middle of a byte throws away the bits until the end of the byte. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::rest; +/// # fn main() { +/// named!( parse<(u8, u8, &[u8])>, bits!( tuple!( +/// take_bits!(u8, 4), +/// take_bits!(u8, 8), +/// bytes!(rest) +/// ))); +/// +/// let input = &[0xde, 0xad, 0xbe, 0xaf]; +/// +/// assert_eq!(parse( input ), Done(&[][..], (0xd, 0xea, &[0xbe, 0xaf][..]))); +/// # } +#[macro_export] +macro_rules! bytes ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + bytes_impl!($i, $submac!($($args)*)); + ); + ($i:expr, $f:expr) => ( + bytes_impl!($i, call!($f)); + ); +); + +#[cfg(feature = "verbose-errors")] +/// Internal parser, do not use directly +#[doc(hidden)] +#[macro_export] +macro_rules! bytes_impl ( + ($macro_i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let inp; + if $macro_i.1 % 8 != 0 { + inp = & $macro_i.0[1 + $macro_i.1 / 8 ..]; + } + else { + inp = & $macro_i.0[$macro_i.1 / 8 ..]; + } + + match $submac!(inp, $($args)*) { + $crate::IResult::Error(e) => { + let err = match e { + $crate::Err::Code(k) | $crate::Err::Node(k, _) => $crate::Err::Code(k), + $crate::Err::Position(k, i) | $crate::Err::NodePosition(k, i, _) => { + $crate::Err::Position(k, (i, 0)) + } + }; + $crate::IResult::Error(err) + } + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + $crate::IResult::Incomplete($crate::Needed::Size(i * 8)) + }, + $crate::IResult::Done(i, o) => { + $crate::IResult::Done((i, 0), o) + } + } + } + ); +); + +#[cfg(not(feature = "verbose-errors"))] +/// Internal parser, do not use directly +#[doc(hidden)] +#[macro_export] +macro_rules! bytes_impl ( + ($macro_i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let inp; + if $macro_i.1 % 8 != 0 { + inp = & $macro_i.0[1 + $macro_i.1 / 8 ..]; + } + else { + inp = & $macro_i.0[$macro_i.1 / 8 ..]; + } + + match $submac!(inp, $($args)*) { + $crate::IResult::Error(e) => { + $crate::IResult::Error(e) + } + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + $crate::IResult::Incomplete($crate::Needed::Size(i * 8)) + }, + $crate::IResult::Done(i, o) => { + $crate::IResult::Done((i, 0), o) + } + } + } + ); +); + +/// `take_bits!(type, nb) => ( (&[T], usize), U, usize) -> IResult<(&[T], usize), U>` +/// generates a parser consuming the specified number of bits. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!( take_pair<(u8, u8)>, bits!( pair!( take_bits!( u8, 3 ), take_bits!(u8, 5) ) ) ); +/// +/// let input = vec![0b10101010, 0b11110000, 0b00110011]; +/// let sl = &input[..]; +/// +/// assert_eq!(take_pair( sl ), Done(&sl[1..], (5, 10)) ); +/// assert_eq!(take_pair( &sl[1..] ), Done(&sl[2..], (7, 16)) ); +/// # } +/// ``` +#[macro_export] +macro_rules! take_bits ( + ($i:expr, $t:ty, $count:expr) => ( + { + use std::ops::Div; + use std::convert::Into; + //println!("taking {} bits from {:?}", $count, $i); + let (input, bit_offset) = $i; + let res : $crate::IResult<(&[u8],usize), $t> = if $count == 0 { + $crate::IResult::Done( (input, bit_offset), (0 as u8).into()) + } else { + let cnt = ($count as usize + bit_offset).div(8); + if input.len() * 8 < $count as usize + bit_offset { + //println!("returning incomplete: {}", $count as usize + bit_offset); + $crate::IResult::Incomplete($crate::Needed::Size($count as usize)) + } else { + let mut acc:$t = (0 as u8).into(); + let mut offset: usize = bit_offset; + let mut remaining: usize = $count; + let mut end_offset: usize = 0; + + for byte in input.iter().take(cnt + 1) { + if remaining == 0 { + break; + } + let val: $t = if offset == 0 { + (*byte as u8).into() + } else { + (((*byte as u8) << offset) as u8 >> offset).into() + }; + + if remaining < 8 - offset { + acc += val >> (8 - offset - remaining); + end_offset = remaining + offset; + break; + } else { + acc += val << (remaining - (8 - offset)); + remaining -= 8 - offset; + offset = 0; + } + } + $crate::IResult::Done( (&input[cnt..], end_offset) , acc) + } + }; + res + } + ); +); + +/// matches an integer pattern to a bitstream. The number of bits of the input to compare must be specified +#[macro_export] +macro_rules! tag_bits ( + ($i:expr, $t:ty, $count:expr, $p: pat) => ( + { + match take_bits!($i, $t, $count) { + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i, o) => { + if let $p = o { + let res: $crate::IResult<(&[u8],usize),$t> = $crate::IResult::Done(i, o); + res + } else { + $crate::IResult::Error(error_position!($crate::ErrorKind::TagBits, $i)) + } + }, + _ => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TagBits, $i)) + } + } + } + ) +); + +#[cfg(test)] +mod tests { + use std::ops::{Shr,Shl,AddAssign}; + use internal::{IResult,Needed}; + use ErrorKind; + + #[test] + fn take_bits() { + let input = [0b10101010, 0b11110000, 0b00110011]; + let sl = &input[..]; + + assert_eq!(take_bits!( (sl, 0), u8, 0 ), IResult::Done((sl, 0), 0)); + assert_eq!(take_bits!( (sl, 0), u8, 8 ), IResult::Done((&sl[1..], 0), 170)); + assert_eq!(take_bits!( (sl, 0), u8, 3 ), IResult::Done((&sl[0..], 3), 5)); + assert_eq!(take_bits!( (sl, 0), u8, 6 ), IResult::Done((&sl[0..], 6), 42)); + assert_eq!(take_bits!( (sl, 1), u8, 1 ), IResult::Done((&sl[0..], 2), 0)); + assert_eq!(take_bits!( (sl, 1), u8, 2 ), IResult::Done((&sl[0..], 3), 1)); + assert_eq!(take_bits!( (sl, 1), u8, 3 ), IResult::Done((&sl[0..], 4), 2)); + assert_eq!(take_bits!( (sl, 6), u8, 3 ), IResult::Done((&sl[1..], 1), 5)); + assert_eq!(take_bits!( (sl, 0), u16, 10 ), IResult::Done((&sl[1..], 2), 683)); + assert_eq!(take_bits!( (sl, 0), u16, 8 ), IResult::Done((&sl[1..], 0), 170)); + assert_eq!(take_bits!( (sl, 6), u16, 10 ), IResult::Done((&sl[2..], 0), 752)); + assert_eq!(take_bits!( (sl, 6), u16, 11 ), IResult::Done((&sl[2..], 1), 1504)); + assert_eq!(take_bits!( (sl, 0), u32, 20 ), IResult::Done((&sl[2..], 4), 700163)); + assert_eq!(take_bits!( (sl, 4), u32, 20 ), IResult::Done((&sl[3..], 0), 716851)); + assert_eq!(take_bits!( (sl, 4), u32, 22 ), IResult::Incomplete(Needed::Size(22))); + } + + #[test] + fn tag_bits() { + let input = [0b10101010, 0b11110000, 0b00110011]; + let sl = &input[..]; + + assert_eq!(tag_bits!( (sl, 0), u8, 3, 0b101), IResult::Done((&sl[0..], 3), 5)); + assert_eq!(tag_bits!( (sl, 0), u8, 4, 0b1010), IResult::Done((&sl[0..], 4), 10)); + } + + named!(ch<(&[u8],usize),(u8,u8)>, + do_parse!( + tag_bits!(u8, 3, 0b101) >> + x: take_bits!(u8, 4) >> + y: take_bits!(u8, 5) >> + (x,y) + ) + ); + + #[test] + fn chain_bits() { + let input = [0b10101010, 0b11110000, 0b00110011]; + let sl = &input[..]; + assert_eq!(ch((&input[..],0)), IResult::Done((&sl[1..], 4), (5,15))); + assert_eq!(ch((&input[..],4)), IResult::Done((&sl[2..], 0), (7,16))); + assert_eq!(ch((&input[..1],0)), IResult::Incomplete(Needed::Size(12))); + } + + named!(ch_bytes<(u8,u8)>, bits!(ch)); + #[test] + fn bits_to_bytes() { + let input = [0b10101010, 0b11110000, 0b00110011]; + assert_eq!(ch_bytes(&input[..]), IResult::Done(&input[2..], (5,15))); + assert_eq!(ch_bytes(&input[..1]), IResult::Incomplete(Needed::Size(2))); + assert_eq!(ch_bytes(&input[1..]), IResult::Error(error_position!(ErrorKind::TagBits, &input[1..]))); + } + + #[derive(PartialEq,Debug)] + struct FakeUint(u32); + + impl AddAssign for FakeUint { + + fn add_assign(&mut self, other: FakeUint) { + *self = FakeUint(&self.0 + other.0); + } + + } + + impl Shr for FakeUint { + type Output = FakeUint; + + fn shr(self, shift: usize) -> FakeUint { + FakeUint(&self.0 >> shift) + } + + } + + impl Shl for FakeUint { + type Output = FakeUint; + + fn shl(self, shift: usize) -> FakeUint { + FakeUint(&self.0 << shift) + } + + } + + impl From for FakeUint { + + fn from(i: u8) -> FakeUint { + FakeUint(u32::from(i)) + } + } + + #[test] + fn non_privitive_type() { + let input = [0b10101010, 0b11110000, 0b00110011]; + let sl = &input[..]; + + assert_eq!(take_bits!( (sl, 0), FakeUint, 20 ), IResult::Done((&sl[2..], 4), FakeUint(700163))); + assert_eq!(take_bits!( (sl, 4), FakeUint, 20 ), IResult::Done((&sl[3..], 0), FakeUint(716851))); + assert_eq!(take_bits!( (sl, 4), FakeUint, 22 ), IResult::Incomplete(Needed::Size(22))); + } +} diff --git a/bash-5.1/vendor/nom/src/branch.rs b/bash-5.1/vendor/nom/src/branch.rs new file mode 100644 index 0000000..a925437 --- /dev/null +++ b/bash-5.1/vendor/nom/src/branch.rs @@ -0,0 +1,871 @@ +/// Try a list of parsers and return the result of the first successful one +/// +/// ```rust,ignore +/// alt!(I -> IResult | I -> IResult | ... | I -> IResult ) => I -> IResult +/// ``` +/// All the parsers must have the same return type. +/// +/// If one of the parsers returns `Incomplete`, `alt!` will return `Incomplete`, to retry +/// once you get more input. Note that it is better for performance to know the +/// minimum size of data you need before you get into `alt!`. +/// +/// The `alt!` combinator is used in the following way: +/// +/// ```rust,ignore +/// alt!(parser_1 | parser_2 | ... | parser_n) +/// ``` +/// +/// # Basic example +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # fn main() { +/// // Create a parser that will match either "dragon" or "beast" +/// named!( dragon_or_beast, alt!( tag!( "dragon" ) | tag!( "beast" ) ) ); +/// +/// // Given the input "dragon slayer", the parser will match "dragon" +/// // and the rest will be " slayer" +/// let (rest, result) = dragon_or_beast(b"dragon slayer").unwrap(); +/// assert_eq!(result, b"dragon"); +/// assert_eq!(rest, b" slayer"); +/// +/// // Given the input "beast of Gevaudan", the parser will match "beast" +/// // and the rest will be " of Gevaudan" +/// let (rest, result) = dragon_or_beast(&b"beast of Gevaudan"[..]).unwrap(); +/// assert_eq!(result, b"beast"); +/// assert_eq!(rest, b" of Gevaudan"); +/// # } +/// ``` +/// +/// # Manipulate results +/// +/// There exists another syntax for `alt!` that gives you the ability to +/// manipulate the result from each parser: +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// # +/// // We create an enum to represent our creatures +/// #[derive(Debug,PartialEq,Eq)] +/// enum Creature { +/// Dragon, +/// Beast, +/// Unknown(usize) +/// } +/// +/// // Let's make a helper function that returns true when not a space +/// // we are required to do this because the `take_while!` macro is limited +/// // to idents, so we can't negate `ìs_space` at the call site +/// fn is_not_space(c: u8) -> bool { ! nom::is_space(c) } +/// +/// // Our parser will return the `Dragon` variant when matching "dragon", +/// // the `Beast` variant when matching "beast" and otherwise it will consume +/// // the input until a space is found and return an `Unknown` creature with +/// // the size of it's name. +/// named!(creature, alt!( +/// tag!("dragon") => { |_| Creature::Dragon } | +/// tag!("beast") => { |_| Creature::Beast } | +/// take_while!(is_not_space) => { |r: &[u8]| Creature::Unknown(r.len()) } +/// // the closure takes the result as argument if the parser is successful +/// )); +/// +/// // Given the input "dragon slayer" the parser will return `Creature::Dragon` +/// // and the rest will be " slayer" +/// let (rest, result) = creature(b"dragon slayer").unwrap(); +/// assert_eq!(result, Creature::Dragon); +/// assert_eq!(rest, b" slayer"); +/// +/// // Given the input "beast of Gevaudan" the parser will return `Creature::Beast` +/// // and the rest will be " of Gevaudan" +/// let (rest, result) = creature(b"beast of Gevaudan").unwrap(); +/// assert_eq!(result, Creature::Beast); +/// assert_eq!(rest, b" of Gevaudan"); +/// +/// // Given the input "demon hunter" the parser will return `Creature::Unkown(5)` +/// // and the rest will be " hunter" +/// let (rest, result) = creature(b"demon hunter").unwrap(); +/// assert_eq!(result, Creature::Unknown(5)); +/// assert_eq!(rest, b" hunter"); +/// # } +/// ``` +/// +/// # Behaviour of `alt!` +/// +/// **BE CAREFUL** there is a case where the behaviour of `alt!` can be confusing: +/// +/// when the alternatives have different lengths, like this case: +/// +/// ```ignore +/// named!( test, alt!( tag!( "abcd" ) | tag!( "ef" ) | tag!( "ghi" ) | tag!( "kl" ) ) ); +/// ``` +/// +/// With this parser, if you pass `"abcd"` as input, the first alternative parses it correctly, +/// but if you pass `"efg"`, the first alternative will return `Incomplete`, since it needs an input +/// of 4 bytes. This behaviour of `alt!` is expected: if you get a partial input that isn't matched +/// by the first alternative, but would match if the input was complete, you want `alt!` to indicate +/// that it cannot decide with limited information. +/// +/// There are two ways to fix this behaviour. The first one consists in ordering the alternatives +/// by size, like this: +/// +/// ```ignore +/// named!( test, alt!( tag!( "ef" ) | tag!( "kl") | tag!( "ghi" ) | tag!( "abcd" ) ) ); +/// ``` +/// +/// With this solution, the largest alternative will be tested last. +/// +/// The other solution uses the `complete!` combinator, which transforms an `Incomplete` in an +/// `Error`. If one of the alternatives returns `Incomplete` but is wrapped by `complete!`, +/// `alt!` will try the next alternative. This is useful when you know that +/// you will not get partial input: +/// +/// ```ignore +/// named!( test, +/// alt!( +/// complete!( tag!( "abcd" ) ) | +/// complete!( tag!( "ef" ) ) | +/// complete!( tag!( "ghi" ) ) | +/// complete!( tag!( "kl" ) ) +/// ) +/// ); +/// ``` +/// +/// If you want the `complete!` combinator to be applied to all rules then use the convenience +/// `alt_complete!` macro (see below). +/// +/// This behaviour of `alt!` can get especially confusing if multiple alternatives have different +/// sizes but a common prefix, like this: +/// +/// ```ignore +/// named!( test, alt!( tag!( "abcd" ) | tag!( "ab" ) | tag!( "ef" ) ) ); +/// ``` +/// +/// in that case, if you order by size, passing `"abcd"` as input will always be matched by the +/// smallest parser, so the solution using `complete!` is better suited. +/// +/// You can also nest multiple `alt!`, like this: +/// +/// ```ignore +/// named!( test, +/// alt!( +/// preceded!( +/// tag!("ab"), +/// alt!( +/// tag!( "cd" ) | +/// eof!() +/// ) +/// ) +/// | tag!( "ef" ) +/// ) +/// ); +/// ``` +/// +/// `preceded!` will first parse `"ab"` then, if successful, try the alternatives "cd", +/// or empty input (End Of File). If none of them work, `preceded!` will fail and +/// "ef" will be tested. +/// +#[macro_export] +macro_rules! alt ( + (__impl $i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)* ) => ( + compiler_error!("alt uses '|' as separator, not ',': + + alt!( + tag!(\"abcd\") | + tag!(\"efgh\") | + tag!(\"ijkl\") + ) + "); + ); + (__impl $i:expr, $e:ident, $($rest:tt)* ) => ( + alt!(__impl $i, call!($e) , $($rest)*); + ); + (__impl $i:expr, $e:ident | $($rest:tt)*) => ( + alt!(__impl $i, call!($e) | $($rest)*); + ); + + (__impl $i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => ( + { + let i_ = $i.clone(); + let res = $subrule!(i_, $($args)*); + match res { + $crate::IResult::Done(_,_) => res, + $crate::IResult::Incomplete(_) => res, + $crate::IResult::Error(e) => { + let out = alt!(__impl $i, $($rest)*); + + // Compile-time hack to ensure that res's E type is not under-specified. + // This all has no effect at runtime. + fn unify_types(_: &T, _: &T) {} + if let $crate::IResult::Error(ref e2) = out { + unify_types(&e, e2); + } + + out + } + } + } + ); + + (__impl $i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)*) => ( + { + let i_ = $i.clone(); + match $subrule!(i_, $($args)* ) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)), + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Error(e) => { + let out = alt!(__impl $i, $($rest)*); + + // Compile-time hack to ensure that res's E type is not under-specified. + // This all has no effect at runtime. + fn unify_types(_: &T, _: &T) {} + if let $crate::IResult::Error(ref e2) = out { + unify_types(&e, e2); + } + + out + } + } + } + ); + + (__impl $i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => ( + alt!(__impl $i, call!($e) => { $gen } | $($rest)*); + ); + + (__impl $i:expr, __end) => ( + $crate::IResult::Error(error_position!($crate::ErrorKind::Alt,$i)) + ); + + ($i:expr, $($rest:tt)*) => ( + { + alt!(__impl $i, $($rest)* | __end) + } + ); +); + +/// Is equivalent to the `alt!` combinator, except that it will not return `Incomplete` +/// when one of the constituting parsers returns `Incomplete`. Instead, it will try the +/// next alternative in the chain. +/// +/// You should use this combinator only if you know you +/// will not receive partial input for the rules you're trying to match (this +/// is almost always the case for parsing programming languages). +/// +/// ```rust,ignore +/// alt_complete!(I -> IResult | I -> IResult | ... | I -> IResult ) => I -> IResult +/// ``` +/// All the parsers must have the same return type. +/// +/// If one of the parsers return `Incomplete`, `alt_complete!` will try the next alternative. +/// If there is no other parser left to try, an `Error` will be returned. +/// +/// ```rust,ignore +/// alt_complete!(parser_1 | parser_2 | ... | parser_n) +/// ``` +/// **For more in depth examples, refer to the documentation of `alt!`** +#[macro_export] +macro_rules! alt_complete ( + // Recursive rules (must include `complete!` around the head) + + ($i:expr, $e:ident | $($rest:tt)*) => ( + alt_complete!($i, complete!(call!($e)) | $($rest)*); + ); + + ($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => ( + { + let i_ = $i.clone(); + let res = complete!(i_, $subrule!($($args)*)); + match res { + $crate::IResult::Done(_,_) => res, + e => { + let out = alt_complete!($i, $($rest)*); + + if let (&$crate::IResult::Error(ref e1), &$crate::IResult::Error(ref e2)) = (&e, &out) { + // Compile-time hack to ensure that res's E type is not under-specified. + // This all has no effect at runtime. + fn unify_types(_: &T, _: &T) {} + unify_types(e1, e2); + } + + out + }, + } + } + ); + + ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => ( + { + let i_ = $i.clone(); + match complete!(i_, $subrule!($($args)*)) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)), + e => { + let out = alt_complete!($i, $($rest)*); + + if let (&$crate::IResult::Error(ref e1), &$crate::IResult::Error(ref e2)) = (&e, &out) { + // Compile-time hack to ensure that res's E type is not under-specified. + // This all has no effect at runtime. + fn unify_types(_: &T, _: &T) {} + unify_types(e1, e2); + } + + out + }, + } + } + ); + + ($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => ( + alt_complete!($i, complete!(call!($e)) => { $gen } | $($rest)*); + ); + + // Tail (non-recursive) rules + + ($i:expr, $e:ident => { $gen:expr }) => ( + alt_complete!($i, call!($e) => { $gen }); + ); + + ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => ( + alt!(__impl $i, complete!($subrule!($($args)*)) => { $gen } | __end) + ); + + ($i:expr, $e:ident) => ( + alt_complete!($i, call!($e)); + ); + + ($i:expr, $subrule:ident!( $($args:tt)*)) => ( + alt!(__impl $i, complete!($subrule!($($args)*)) | __end) + ); +); + +/// `switch!(I -> IResult, P => I -> IResult | ... | P => I -> IResult ) => I -> IResult` +/// choose the next parser depending on the result of the first one, if successful, +/// and returns the result of the second parser +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done,Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::{Position, NodePosition}; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(sw, +/// switch!(take!(4), +/// b"abcd" => tag!("XYZ") | +/// b"efgh" => tag!("123") +/// ) +/// ); +/// +/// let a = b"abcdXYZ123"; +/// let b = b"abcdef"; +/// let c = b"efgh123"; +/// let d = b"blah"; +/// +/// assert_eq!(sw(&a[..]), Done(&b"123"[..], &b"XYZ"[..])); +/// assert_eq!(sw(&b[..]), Error(error_node_position!(ErrorKind::Switch, &b"abcdef"[..], +/// error_position!(ErrorKind::Tag, &b"ef"[..])))); +/// assert_eq!(sw(&c[..]), Done(&b""[..], &b"123"[..])); +/// assert_eq!(sw(&d[..]), Error(error_position!(ErrorKind::Switch, &b"blah"[..]))); +/// # } +/// ``` +/// +/// You can specify a default case like with a normal match, using `_` +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(sw, +/// switch!(take!(4), +/// b"abcd" => tag!("XYZ") | +/// _ => value!(&b"default"[..]) +/// ) +/// ); +/// +/// let a = b"abcdXYZ123"; +/// let b = b"blah"; +/// +/// assert_eq!(sw(&a[..]), Done(&b"123"[..], &b"XYZ"[..])); +/// assert_eq!(sw(&b[..]), Done(&b""[..], &b"default"[..])); +/// # } +/// ``` +/// +/// Due to limitations in Rust macros, it is not possible to have simple functions on the right hand +/// side of pattern, like this: +/// +/// ```ignore +/// named!(sw, +/// switch!(take!(4), +/// b"abcd" => tag!("XYZ") | +/// b"efgh" => tag!("123") +/// ) +/// ); +/// ``` +/// +/// If you want to pass your own functions instead, you can use the `call!` combinator as follows: +/// +/// ```ignore +/// named!(xyz, tag!("XYZ")); +/// named!(num, tag!("123")); +/// named!(sw, +/// switch!(take!(4), +/// b"abcd" => call!(xyz) | +/// b"efgh" => call!(num) +/// ) +/// ); +/// ``` +/// +#[macro_export] +macro_rules! switch ( + (__impl $i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => ( + { + let i_ = $i.clone(); + match map!(i_, $submac!($($args)*), |o| Some(o)) { + $crate::IResult::Error(e) => $crate::IResult::Error(error_node_position!( + $crate::ErrorKind::Switch, $i, e + )), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i, o) => { + match o { + $(Some($p) => match $subrule!(i, $($args2)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(error_node_position!( + $crate::ErrorKind::Switch, $i, e + )), + a => a, + }),*, + _ => $crate::IResult::Error(error_position!($crate::ErrorKind::Switch,$i)) + } + } + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)*), $($rest:tt)*) => ( + { + switch!(__impl $i, $submac!($($args)*), $($rest)*) + } + ); + ($i:expr, $e:ident, $($rest:tt)*) => ( + { + switch!(__impl $i, call!($e), $($rest)*) + } + ); +); + +/// +/// +/// `permutation!(I -> IResult, I -> IResult, ... I -> IResult ) => I -> IResult` +/// applies its sub parsers in a sequence, but independent from their order +/// this parser will only succeed if all of its sub parsers succeed +/// +/// the tuple of results is in the same order as the parsers are declared +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done,Error,Incomplete}; +/// # use nom::{ErrorKind,Needed}; +/// # fn main() { +/// named!(perm<(&[u8], &[u8], &[u8])>, +/// permutation!(tag!("abcd"), tag!("efg"), tag!("hi")) +/// ); +/// +/// // whatever the order, if the parser succeeds, each +/// // tag should have matched correctly +/// let expected = (&b"abcd"[..], &b"efg"[..], &b"hi"[..]); +/// +/// let a = &b"abcdefghijk"[..]; +/// assert_eq!(perm(a), Done(&b"jk"[..], expected)); +/// let b = &b"efgabcdhijkl"[..]; +/// assert_eq!(perm(b), Done(&b"jkl"[..], expected)); +/// let c = &b"hiefgabcdjklm"[..]; +/// assert_eq!(perm(c), Done(&b"jklm"[..], expected)); +/// +/// let d = &b"efgxyzabcdefghi"[..]; +/// assert_eq!(perm(d), Error(error_position!(ErrorKind::Permutation, &b"xyzabcdefghi"[..]))); +/// +/// let e = &b"efgabc"[..]; +/// assert_eq!(perm(e), Incomplete(Needed::Size(7))); +/// # } +/// ``` +#[macro_export] +macro_rules! permutation ( + ($i:expr, $($rest:tt)*) => ( + { + let mut res = permutation_init!((), $($rest)*); + let mut input = $i; + let mut error = ::std::option::Option::None; + let mut needed = ::std::option::Option::None; + + loop { + let mut all_done = true; + permutation_iterator!(0, input, all_done, needed, res, $($rest)*); + + //if we reach that part, it means none of the parsers were able to read anything + if !all_done { + //FIXME: should wrap the error returned by the child parser + error = ::std::option::Option::Some(error_position!($crate::ErrorKind::Permutation, input)); + } + break; + } + + if let ::std::option::Option::Some(need) = needed { + if let $crate::Needed::Size(sz) = need { + $crate::IResult::Incomplete( + $crate::Needed::Size( + $crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&input) + + sz + ) + ) + } else { + $crate::IResult::Incomplete($crate::Needed::Unknown) + } + } else if let ::std::option::Option::Some(e) = error { + $crate::IResult::Error(e) + } else { + let unwrapped_res = permutation_unwrap!(0, (), res, $($rest)*); + $crate::IResult::Done(input, unwrapped_res) + } + } + ); +); + + +#[doc(hidden)] +#[macro_export] +macro_rules! permutation_init ( + ((), $e:ident, $($rest:tt)*) => ( + permutation_init!((::std::option::Option::None), $($rest)*) + ); + ((), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + permutation_init!((::std::option::Option::None), $($rest)*) + ); + (($($parsed:expr),*), $e:ident, $($rest:tt)*) => ( + permutation_init!(($($parsed),* , ::std::option::Option::None), $($rest)*); + ); + (($($parsed:expr),*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + permutation_init!(($($parsed),* , ::std::option::Option::None), $($rest)*); + ); + (($($parsed:expr),*), $e:ident) => ( + ($($parsed),* , ::std::option::Option::None) + ); + (($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => ( + ($($parsed),* , ::std::option::Option::None) + ); + (($($parsed:expr),*),) => ( + ($($parsed),*) + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! succ ( + (0, $submac:ident ! ($($rest:tt)*)) => ($submac!(1, $($rest)*)); + (1, $submac:ident ! ($($rest:tt)*)) => ($submac!(2, $($rest)*)); + (2, $submac:ident ! ($($rest:tt)*)) => ($submac!(3, $($rest)*)); + (3, $submac:ident ! ($($rest:tt)*)) => ($submac!(4, $($rest)*)); + (4, $submac:ident ! ($($rest:tt)*)) => ($submac!(5, $($rest)*)); + (5, $submac:ident ! ($($rest:tt)*)) => ($submac!(6, $($rest)*)); + (6, $submac:ident ! ($($rest:tt)*)) => ($submac!(7, $($rest)*)); + (7, $submac:ident ! ($($rest:tt)*)) => ($submac!(8, $($rest)*)); + (8, $submac:ident ! ($($rest:tt)*)) => ($submac!(9, $($rest)*)); + (9, $submac:ident ! ($($rest:tt)*)) => ($submac!(10, $($rest)*)); + (10, $submac:ident ! ($($rest:tt)*)) => ($submac!(11, $($rest)*)); + (11, $submac:ident ! ($($rest:tt)*)) => ($submac!(12, $($rest)*)); + (12, $submac:ident ! ($($rest:tt)*)) => ($submac!(13, $($rest)*)); + (13, $submac:ident ! ($($rest:tt)*)) => ($submac!(14, $($rest)*)); + (14, $submac:ident ! ($($rest:tt)*)) => ($submac!(15, $($rest)*)); + (15, $submac:ident ! ($($rest:tt)*)) => ($submac!(16, $($rest)*)); + (16, $submac:ident ! ($($rest:tt)*)) => ($submac!(17, $($rest)*)); + (17, $submac:ident ! ($($rest:tt)*)) => ($submac!(18, $($rest)*)); + (18, $submac:ident ! ($($rest:tt)*)) => ($submac!(19, $($rest)*)); + (19, $submac:ident ! ($($rest:tt)*)) => ($submac!(20, $($rest)*)); +); + +// HACK: for some reason, Rust 1.11 does not accept $res.$it in +// permutation_unwrap. This is a bit ugly, but it will have no +// impact on the generated code +#[doc(hidden)] +#[macro_export] +macro_rules! acc ( + (0, $tup:expr) => ($tup.0); + (1, $tup:expr) => ($tup.1); + (2, $tup:expr) => ($tup.2); + (3, $tup:expr) => ($tup.3); + (4, $tup:expr) => ($tup.4); + (5, $tup:expr) => ($tup.5); + (6, $tup:expr) => ($tup.6); + (7, $tup:expr) => ($tup.7); + (8, $tup:expr) => ($tup.8); + (9, $tup:expr) => ($tup.9); + (10, $tup:expr) => ($tup.10); + (11, $tup:expr) => ($tup.11); + (12, $tup:expr) => ($tup.12); + (13, $tup:expr) => ($tup.13); + (14, $tup:expr) => ($tup.14); + (15, $tup:expr) => ($tup.15); + (16, $tup:expr) => ($tup.16); + (17, $tup:expr) => ($tup.17); + (18, $tup:expr) => ($tup.18); + (19, $tup:expr) => ($tup.19); + (20, $tup:expr) => ($tup.20); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! permutation_unwrap ( + ($it:tt, (), $res:ident, $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + succ!($it, permutation_unwrap!((acc!($it, $res).unwrap()), $res, $($rest)*)); + ); + ($it:tt, ($($parsed:expr),*), $res:ident, $e:ident, $($rest:tt)*) => ( + succ!($it, permutation_unwrap!(($($parsed),* , acc!($it, $res).unwrap()), $res, $($rest)*)); + ); + ($it:tt, ($($parsed:expr),*), $res:ident, $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + succ!($it, permutation_unwrap!(($($parsed),* , acc!($it, $res).unwrap()), $res, $($rest)*)); + ); + ($it:tt, ($($parsed:expr),*), $res:ident, $e:ident) => ( + ($($parsed),* , { acc!($it, $res).unwrap() }) + ); + ($it:tt, ($($parsed:expr),*), $res:ident, $submac:ident!( $($args:tt)* )) => ( + ($($parsed),* , acc!($it, $res).unwrap() ) + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! permutation_iterator ( + ($it:tt,$i:expr, $all_done:expr, $needed:expr, $res:expr, $e:ident, $($rest:tt)*) => ( + permutation_iterator!($it, $i, $all_done, $needed, $res, call!($e), $($rest)*); + ); + ($it:tt, $i:expr, $all_done:expr, $needed:expr, $res:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)*) => { + if acc!($it, $res) == ::std::option::Option::None { + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,o) => { + $i = i; + acc!($it, $res) = ::std::option::Option::Some(o); + continue; + }, + $crate::IResult::Error(_) => { + $all_done = false; + }, + $crate::IResult::Incomplete(i) => { + $needed = ::std::option::Option::Some(i); + break; + } + }; + } + succ!($it, permutation_iterator!($i, $all_done, $needed, $res, $($rest)*)); + }; + ($it:tt,$i:expr, $all_done:expr, $needed:expr, $res:expr, $e:ident) => ( + permutation_iterator!($it, $i, $all_done, $res, call!($e)); + ); + ($it:tt, $i:expr, $all_done:expr, $needed:expr, $res:expr, $submac:ident!( $($args:tt)* )) => { + if acc!($it, $res) == ::std::option::Option::None { + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,o) => { + $i = i; + acc!($it, $res) = ::std::option::Option::Some(o); + continue; + }, + $crate::IResult::Error(_) => { + $all_done = false; + }, + $crate::IResult::Incomplete(i) => { + $needed = ::std::option::Option::Some(i); + break; + } + }; + } + }; +); + +#[cfg(test)] +mod tests { + use internal::{Needed,IResult}; + use internal::IResult::*; + use util::ErrorKind; + + // reproduce the tag and take macros, because of module import order + macro_rules! tag ( + ($i:expr, $inp: expr) => ( + { + #[inline(always)] + fn as_bytes(b: &T) -> &[u8] { + b.as_bytes() + } + + let expected = $inp; + let bytes = as_bytes(&expected); + + tag_bytes!($i,bytes) + } + ); + ); + + macro_rules! tag_bytes ( + ($i:expr, $bytes: expr) => ( + { + use std::cmp::min; + let len = $i.len(); + let blen = $bytes.len(); + let m = min(len, blen); + let reduced = &$i[..m]; + let b = &$bytes[..m]; + + let res: $crate::IResult<_,_> = if reduced != b { + $crate::IResult::Error(error_position!($crate::ErrorKind::Tag, $i)) + } else if m < blen { + $crate::IResult::Incomplete($crate::Needed::Size(blen)) + } else { + $crate::IResult::Done(&$i[blen..], reduced) + }; + res + } + ); + ); + + macro_rules! take( + ($i:expr, $count:expr) => ( + { + let cnt = $count as usize; + let res:$crate::IResult<&[u8],&[u8]> = if $i.len() < cnt { + $crate::IResult::Incomplete($crate::Needed::Size(cnt)) + } else { + $crate::IResult::Done(&$i[cnt..],&$i[0..cnt]) + }; + res + } + ); + ); + +#[test] + fn alt() { + fn work(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> { + Done(&b""[..], input) + } + + #[allow(unused_variables)] + fn dont_work(input: &[u8]) -> IResult<&[u8],&[u8],&'static str> { + Error(error_code!(ErrorKind::Custom("abcd"))) + } + + fn work2(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> { + Done(input, &b""[..]) + } + + fn alt1(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> { + alt!(i, dont_work | dont_work) + } + fn alt2(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> { + alt!(i, dont_work | work) + } + fn alt3(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> { + alt!(i, dont_work | dont_work | work2 | dont_work) + } + //named!(alt1, alt!(dont_work | dont_work)); + //named!(alt2, alt!(dont_work | work)); + //named!(alt3, alt!(dont_work | dont_work | work2 | dont_work)); + + let a = &b"abcd"[..]; + assert_eq!(alt1(a), Error(error_position!(ErrorKind::Alt, a))); + assert_eq!(alt2(a), Done(&b""[..], a)); + assert_eq!(alt3(a), Done(a, &b""[..])); + + named!(alt4, alt!(tag!("abcd") | tag!("efgh"))); + let b = &b"efgh"[..]; + assert_eq!(alt4(a), Done(&b""[..], a)); + assert_eq!(alt4(b), Done(&b""[..], b)); + + // test the alternative syntax + named!(alt5, alt!(tag!("abcd") => { |_| false } | tag!("efgh") => { |_| true })); + assert_eq!(alt5(a), Done(&b""[..], false)); + assert_eq!(alt5(b), Done(&b""[..], true)); + + // compile-time test guarding against an underspecified E generic type (#474) + named!(alt_eof1, alt!(eof!() | eof!())); + named!(alt_eof2, alt!(eof!() => {|x| x} | eof!() => {|x| x})); + let _ = (alt_eof1, alt_eof2); + + } + + #[test] + fn alt_incomplete() { + named!(alt1, alt!(tag!("a") | tag!("bc") | tag!("def"))); + + let a = &b""[..]; + assert_eq!(alt1(a), Incomplete(Needed::Size(1))); + let a = &b"b"[..]; + assert_eq!(alt1(a), Incomplete(Needed::Size(2))); + let a = &b"bcd"[..]; + assert_eq!(alt1(a), Done(&b"d"[..], &b"bc"[..])); + let a = &b"cde"[..]; + assert_eq!(alt1(a), Error(error_position!(ErrorKind::Alt, a))); + let a = &b"de"[..]; + assert_eq!(alt1(a), Incomplete(Needed::Size(3))); + let a = &b"defg"[..]; + assert_eq!(alt1(a), Done(&b"g"[..], &b"def"[..])); + } + + #[test] + fn alt_complete() { + named!(ac<&[u8], &[u8]>, + alt_complete!(tag!("abcd") | tag!("ef") | tag!("ghi") | tag!("kl")) + ); + + let a = &b""[..]; + assert_eq!(ac(a), Error(error_position!(ErrorKind::Alt, a))); + let a = &b"ef"[..]; + assert_eq!(ac(a), Done(&b""[..], &b"ef"[..])); + let a = &b"cde"[..]; + assert_eq!(ac(a), Error(error_position!(ErrorKind::Alt, a))); + } + + #[allow(unused_variables)] + #[test] + fn switch() { + named!(sw, + switch!(take!(4), + b"abcd" => take!(2) | + b"efgh" => take!(4) + ) + ); + + let a = &b"abcdefgh"[..]; + assert_eq!(sw(a), Done(&b"gh"[..], &b"ef"[..])); + + let b = &b"efghijkl"[..]; + assert_eq!(sw(b), Done(&b""[..], &b"ijkl"[..])); + let c = &b"afghijkl"[..]; + assert_eq!(sw(c), Error(error_position!(ErrorKind::Switch, &b"afghijkl"[..]))); + } + + #[test] + fn permutation() { + //trace_macros!(true); + named!(perm<(&[u8], &[u8], &[u8])>, + permutation!(tag!("abcd"), tag!("efg"), tag!("hi")) + ); + //trace_macros!(false); + + let expected = (&b"abcd"[..], &b"efg"[..], &b"hi"[..]); + + let a = &b"abcdefghijk"[..]; + assert_eq!(perm(a), Done(&b"jk"[..], expected)); + let b = &b"efgabcdhijk"[..]; + assert_eq!(perm(b), Done(&b"jk"[..], expected)); + let c = &b"hiefgabcdjk"[..]; + assert_eq!(perm(c), Done(&b"jk"[..], expected)); + + let d = &b"efgxyzabcdefghi"[..]; + assert_eq!(perm(d), Error(error_position!(ErrorKind::Permutation, &b"xyzabcdefghi"[..]))); + + let e = &b"efgabc"[..]; + assert_eq!(perm(e), Incomplete(Needed::Size(7))); + } + + /* + named!(does_not_compile, + alt!(tag!("abcd"), tag!("efgh")) + ); + */ +} diff --git a/bash-5.1/vendor/nom/src/bytes.rs b/bash-5.1/vendor/nom/src/bytes.rs new file mode 100644 index 0000000..462ed02 --- /dev/null +++ b/bash-5.1/vendor/nom/src/bytes.rs @@ -0,0 +1,1119 @@ +//! Byte level parsers and combinators +//! +#[allow(unused_variables)] + +/// `tag!(&[T]: nom::AsBytes) => &[T] -> IResult<&[T], &[T]>` +/// declares a byte array as a suite to recognize +/// +/// consumes the recognized characters +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(x, tag!("abcd")); +/// let r = x(&b"abcdefgh"[..]); +/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! tag ( + ($i:expr, $tag: expr) => ( + { + use $crate::{Compare,CompareResult,InputLength,Slice}; + let res: $crate::IResult<_,_> = match ($i).compare($tag) { + CompareResult::Ok => { + let blen = $tag.input_len(); + $crate::IResult::Done($i.slice(blen..), $i.slice(..blen)) + }, + CompareResult::Incomplete => { + $crate::IResult::Incomplete($crate::Needed::Size($tag.input_len())) + }, + CompareResult::Error => { + $crate::IResult::Error(error_position!($crate::ErrorKind::Tag, $i)) + } + }; + res + } + ); +); + +/// `tag_no_case!(&[T]) => &[T] -> IResult<&[T], &[T]>` +/// declares a case insensitive ascii string as a suite to recognize +/// +/// consumes the recognized characters +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self,Done}; +/// # fn main() { +/// named!(test, tag_no_case!("ABcd")); +/// +/// let r = test(&b"aBCdefgh"[..]); +/// assert_eq!(r, Done(&b"efgh"[..], &b"aBCd"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! tag_no_case ( + ($i:expr, $tag: expr) => ( + { + use $crate::{Compare,CompareResult,InputLength,Slice}; + let res: $crate::IResult<_,_> = match ($i).compare_no_case($tag) { + CompareResult::Ok => { + let blen = $tag.input_len(); + $crate::IResult::Done($i.slice(blen..), $i.slice(..blen)) + }, + CompareResult::Incomplete => { + $crate::IResult::Incomplete($crate::Needed::Size($tag.input_len())) + }, + CompareResult::Error => { + $crate::IResult::Error(error_position!($crate::ErrorKind::Tag, $i)) + } + }; + res + } + ); +); + + +/// `is_not!(&[T:AsBytes]) => &[T] -> IResult<&[T], &[T]>` +/// returns the longest list of bytes that do not appear in the provided array +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!( not_space, is_not!( " \t\r\n" ) ); +/// +/// let r = not_space(&b"abcdefgh\nijkl"[..]); +/// assert_eq!(r, Done(&b"\nijkl"[..], &b"abcdefgh"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! is_not( + ($input:expr, $arr:expr) => ( + { + use $crate::InputLength; + use $crate::InputIter; + use $crate::FindToken; + use $crate::Slice; + + let res: $crate::IResult<_,_> = match $input.position(|c| { + c.find_token($arr) + }) { + Some(0) => $crate::IResult::Error(error_position!($crate::ErrorKind::IsNot,$input)), + Some(n) => { + let res = $crate::IResult::Done($input.slice(n..), $input.slice(..n)); + res + }, + None => { + $crate::IResult::Done($input.slice($input.input_len()..), $input) + } + }; + res + } + ); +); + +/// `is_a!(&[T]) => &[T] -> IResult<&[T], &[T]>` +/// returns the longest list of bytes that appear in the provided array +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(abcd, is_a!( "abcd" )); +/// +/// let r1 = abcd(&b"aaaaefgh"[..]); +/// assert_eq!(r1, Done(&b"efgh"[..], &b"aaaa"[..])); +/// +/// let r2 = abcd(&b"dcbaefgh"[..]); +/// assert_eq!(r2, Done(&b"efgh"[..], &b"dcba"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! is_a ( + ($input:expr, $arr:expr) => ( + { + use $crate::InputLength; + use $crate::InputIter; + use $crate::FindToken; + use $crate::Slice; + + let res: $crate::IResult<_,_> = match $input.position(|c| { + !c.find_token($arr) + }) { + Some(0) => $crate::IResult::Error(error_position!($crate::ErrorKind::IsA,$input)), + Some(n) => { + let res: $crate::IResult<_,_> = $crate::IResult::Done($input.slice(n..), $input.slice(..n)); + res + }, + None => { + $crate::IResult::Done($input.slice(($input).input_len()..), $input) + } + }; + res + } + ); +); + +/// `escaped!(&[T] -> IResult<&[T], &[T]>, T, &[T] -> IResult<&[T], &[T]>) => &[T] -> IResult<&[T], &[T]>` +/// matches a byte string with escaped characters. +/// +/// The first argument matches the normal characters (it must not accept the control character), the second argument is the control character (like `\` in most languages), +/// the third argument matches the escaped characters +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::alpha; +/// # fn main() { +/// named!(esc, escaped!(call!(alpha), '\\', one_of!("\"n\\"))); +/// assert_eq!(esc(&b"abcd"[..]), Done(&b""[..], &b"abcd"[..])); +/// assert_eq!(esc(&b"ab\\\"cd"[..]), Done(&b""[..], &b"ab\\\"cd"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! escaped ( + // Internal parser, do not use directly + (__impl $i: expr, $normal:ident!( $($args:tt)* ), $control_char: expr, $escapable:ident!( $($args2:tt)* )) => ( + { + use $crate::InputLength; + use $crate::Slice; + let cl = || -> $crate::IResult<_,_,_> { + use $crate::Offset; + let mut index = 0; + + while index < $i.input_len() { + match $normal!($i.slice(index..), $($args)*) { + $crate::IResult::Done(i, _) => { + if i.is_empty() { + return $crate::IResult::Done($i.slice($i.input_len()..), $i) + } else { + index = $i.offset(i); + } + }, + $crate::IResult::Incomplete(i) => { + return $crate::IResult::Incomplete(i) + }, + $crate::IResult::Error(e) => { + if $i[index] == $control_char as u8 { + if index + 1 >= $i.input_len() { + return $crate::IResult::Incomplete($crate::Needed::Unknown) + } else { + match $escapable!($i.slice(index+1..), $($args2)*) { + $crate::IResult::Done(i,_) => { + if i.is_empty() { + return $crate::IResult::Done($i.slice($i.input_len()..), $i) + } else { + index = $i.offset(i); + } + }, + $crate::IResult::Incomplete(i) => return $crate::IResult::Incomplete(i), + $crate::IResult::Error(e2) => return $crate::IResult::Error(e2) + } + } + } else { + return $crate::IResult::Done($i.slice(index..), $i.slice(..index)); + } + } + } + } + $crate::IResult::Done(&$i[index..], &$i[..index]) + }; + match cl() { + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => { + return $crate::IResult::Error(error_node_position!($crate::ErrorKind::Escaped, $i, e)) + } + } + } + ); + // Internal parser, do not use directly + (__impl_1 $i:expr, $submac1:ident!( $($args:tt)* ), $control_char: expr, $submac2:ident!( $($args2:tt)*) ) => ( + { + escaped!(__impl $i, $submac1!($($args)*), $control_char, $submac2!($($args2)*)) + } + ); + // Internal parser, do not use directly + (__impl_1 $i:expr, $submac1:ident!( $($args:tt)* ), $control_char: expr, $g:expr) => ( + escaped!(__impl $i, $submac1!($($args)*), $control_char, call!($g)) + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $control_char: expr, $($rest:tt)+) => ( + { + let input: &[u8] = $i; + + escaped!(__impl_1 input, $submac!($($args)*), $control_char, $($rest)*) + } + ); + + ($i:expr, $f:expr, $control_char: expr, $($rest:tt)+) => ( + escaped!(__impl_1 $i, call!($f), $control_char, $($rest)*) + ); +); + +/// `escaped_transform!(&[T] -> IResult<&[T], &[T]>, T, &[T] -> IResult<&[T], &[T]>) => &[T] -> IResult<&[T], Vec>` +/// matches a byte string with escaped characters. +/// +/// The first argument matches the normal characters (it must not match the control character), the second argument is the control character (like `\` in most languages), +/// the third argument matches the escaped characters and transforms them. +/// +/// As an example, the chain `abc\tdef` could be `abc def` (it also consumes the control character) +/// +/// WARNING: if you do not use the `verbose-errors` feature, this combinator will currently fail to build +/// because of a type inference error +/// +/// ```ignore +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::alpha; +/// # use std::str::from_utf8; +/// # fn main() { +/// fn to_s(i:Vec) -> String { +/// String::from_utf8_lossy(&i).into_owned() +/// } + +/// named!(transform < String >, +/// map!( +/// escaped_transform!(call!(alpha), '\\', +/// alt!( +/// tag!("\\") => { |_| &b"\\"[..] } +/// | tag!("\"") => { |_| &b"\""[..] } +/// | tag!("n") => { |_| &b"\n"[..] } +/// ) +/// ), to_s +/// ) +/// ); +/// assert_eq!(transform(&b"ab\\\"cd"[..]), Done(&b""[..], String::from("ab\"cd"))); +/// # } +/// ``` +#[macro_export] +macro_rules! escaped_transform ( + // Internal parser, do not use directly + (__impl $i: expr, $normal:ident!( $($args:tt)* ), $control_char: expr, $transform:ident!( $($args2:tt)* )) => ( + { + use $crate::{InputLength,Slice}; + let cl = || { + use $crate::Offset; + let mut index = 0; + let mut res = Vec::new(); + + while index < $i.input_len() { + if let $crate::IResult::Done(i,o) = $normal!($i.slice(index..), $($args)*) { + res.extend(o.iter().cloned()); + if i.is_empty() { + return $crate::IResult::Done($i.slice($i.input_len()..), res); + } else { + index = $i.offset(i); + } + } else if $i[index] == $control_char as u8 { + if index + 1 >= $i.input_len() { + return $crate::IResult::Error(error_position!($crate::ErrorKind::EscapedTransform,$i.slice(index..))); + } else { + match $transform!($i.slice(index+1..), $($args2)*) { + $crate::IResult::Done(i,o) => { + res.extend(o.iter().cloned()); + if i.is_empty() { + return $crate::IResult::Done($i.slice($i.input_len()..), res) + } else { + index = $i.offset(i); + } + }, + $crate::IResult::Incomplete(i) => return $crate::IResult::Incomplete(i), + $crate::IResult::Error(e) => return $crate::IResult::Error(e) + } + } + } else { + if index == 0 { + return $crate::IResult::Error(error_position!($crate::ErrorKind::EscapedTransform,$i.slice(index..))) + } else { + return $crate::IResult::Done($i.slice(index..), res) + } + } + } + $crate::IResult::Done($i.slice(index..), res) + }; + match cl() { + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => { + return $crate::IResult::Error(error_node_position!($crate::ErrorKind::EscapedTransform, $i, e)) + } + } + } + ); + // Internal parser, do not use directly + (__impl_1 $i:expr, $submac1:ident!( $($args:tt)* ), $control_char: expr, $submac2:ident!( $($args2:tt)*) ) => ( + { + escaped_transform!(__impl $i, $submac1!($($args)*), $control_char, $submac2!($($args2)*)) + } + ); + // Internal parser, do not use directly + (__impl_1 $i:expr, $submac1:ident!( $($args:tt)* ), $control_char: expr, $g:expr) => ( + escaped_transform_impl!($i, $submac1!($($args)*), $control_char, call!($g)) + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $control_char: expr, $($rest:tt)+) => ( + { + let input: &[u8] = $i; + + escaped_transform!(__impl_1 input, $submac!($($args)*), $control_char, $($rest)*) + } + ); + + ($i:expr, $f:expr, $control_char: expr, $($rest:tt)+) => ( + escaped_transform!(__impl_1 $i, call!($f), $control_char, $($rest)*) + ); +); + +/// `take_while!(T -> bool) => &[T] -> IResult<&[T], &[T]>` +/// returns the longest list of bytes until the provided function fails. +/// +/// The argument is either a function `T -> bool` or a macro returning a `bool`. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::is_alphanumeric; +/// # fn main() { +/// named!( alpha, take_while!( is_alphanumeric ) ); +/// +/// let r = alpha(&b"abcd\nefgh"[..]); +/// assert_eq!(r, Done(&b"\nefgh"[..], &b"abcd"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! take_while ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::{InputLength,InputIter,Slice}; + let input = $input; + + match input.position(|c| !$submac!(c, $($args)*)) { + Some(n) => { + let res:$crate::IResult<_,_> = $crate::IResult::Done(input.slice(n..), input.slice(..n)); + res + }, + None => { + $crate::IResult::Done(input.slice(input.input_len()..), input) + } + } + } + ); + ($input:expr, $f:expr) => ( + take_while!($input, call!($f)); + ); +); + +/// `take_while1!(T -> bool) => &[T] -> IResult<&[T], &[T]>` +/// returns the longest (non empty) list of bytes until the provided function fails. +/// +/// The argument is either a function `&[T] -> bool` or a macro returning a `bool +#[macro_export] +macro_rules! take_while1 ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + let input = $input; + + use $crate::InputLength; + use $crate::InputIter; + use $crate::Slice; + if input.input_len() == 0 { + $crate::IResult::Incomplete($crate::Needed::Size(1)) + } else { + match input.position(|c| !$submac!(c, $($args)*)) { + Some(0) => $crate::IResult::Error(error_position!($crate::ErrorKind::TakeWhile1,input)), + Some(n) => { + $crate::IResult::Done(input.slice(n..), input.slice(..n)) + }, + None => { + $crate::IResult::Done(input.slice(input.input_len()..), input) + } + } + } + } + ); + ($input:expr, $f:expr) => ( + take_while1!($input, call!($f)); + ); +); + +/// `take_till!(T -> bool) => &[T] -> IResult<&[T], &[T]>` +/// returns the longest list of bytes until the provided function succeeds +/// +/// The argument is either a function `&[T] -> bool` or a macro returning a `bool +#[macro_export] +macro_rules! take_till ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + let input = $input; + + use $crate::InputLength; + use $crate::InputIter; + use $crate::Slice; + match input.position(|c| $submac!(c, $($args)*)) { + Some(n) => $crate::IResult::Done(input.slice(n..), input.slice(..n)), + None => $crate::IResult::Done(input.slice(input.input_len()..), input) + } + } + ); + ($input:expr, $f:expr) => ( + take_till!($input, call!($f)); + ); +); + +/// `take_till1!(T -> bool) => &[T] -> IResult<&[T], &[T]>` +/// returns the longest non empty list of bytes until the provided function succeeds +/// +/// The argument is either a function `&[T] -> bool` or a macro returning a `bool +#[macro_export] +macro_rules! take_till1 ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + let input = $input; + + use $crate::InputLength; + use $crate::InputIter; + use $crate::Slice; + if input.input_len() == 0 { + $crate::IResult::Incomplete($crate::Needed::Size(1)) + } else { + match input.position(|c| $submac!(c, $($args)*)) { + Some(0) => $crate::IResult::Error(error_position!($crate::ErrorKind::TakeTill1,input)), + Some(n) => $crate::IResult::Done(input.slice(n..), input.slice(..n)), + None => $crate::IResult::Done(input.slice(input.input_len()..), input) + } + } + } + ); + ($input:expr, $f:expr) => ( + take_till1!($input, call!($f)); + ); +); + +/// `take!(nb) => &[T] -> IResult<&[T], &[T]>` +/// generates a parser consuming the specified number of bytes +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// // Desmond parser +/// named!(take5, take!( 5 ) ); +/// +/// let a = b"abcdefgh"; +/// +/// assert_eq!(take5(&a[..]), Done(&b"fgh"[..], &b"abcde"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! take ( + ($i:expr, $count:expr) => ( + { + use $crate::InputIter; + use $crate::Slice; + let input = $i; + + let cnt = $count as usize; + + let res: $crate::IResult<_,_> = match input.slice_index(cnt) { + None => $crate::IResult::Incomplete($crate::Needed::Size(cnt)), + //FIXME: use the InputTake trait + Some(index) => $crate::IResult::Done(input.slice(index..), input.slice(..index)) + }; + res + } + ); +); + +/// `take_str!(nb) => &[T] -> IResult<&[T], &str>` +/// same as take! but returning a &str +#[macro_export] +macro_rules! take_str ( + ( $i:expr, $size:expr ) => ( + { + let input: &[u8] = $i; + + map_res!(input, take!($size), ::std::str::from_utf8) + } + ); +); + +/// `take_until_and_consume!(tag) => &[T] -> IResult<&[T], &[T]>` +/// generates a parser consuming bytes until the specified byte sequence is found, and consumes it +#[macro_export] +macro_rules! take_until_and_consume ( + ($i:expr, $substr:expr) => ( + { + use $crate::InputLength; + use $crate::FindSubstring; + use $crate::Slice; + + let res: $crate::IResult<_,_> = if $substr.input_len() > $i.input_len() { + $crate::IResult::Incomplete($crate::Needed::Size($substr.input_len())) + } else { + match ($i).find_substring($substr) { + None => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntilAndConsume,$i)) + }, + Some(index) => { + $crate::IResult::Done($i.slice(index+$substr.input_len()..), $i.slice(0..index)) + }, + } + }; + res + } + ); +); + +/// `take_until_and_consume1!(tag) => &[T] -> IResult<&[T], &[T]>` +/// generates a parser consuming bytes (at least 1) until the specified byte sequence is found, and consumes it +#[macro_export] +macro_rules! take_until_and_consume1 ( + ($i:expr, $substr:expr) => ( + { + use $crate::InputLength; + + let res: $crate::IResult<_,_> = if 1 + $substr.input_len() > $i.input_len() { + $crate::IResult::Incomplete($crate::Needed::Size($substr.input_len())) + } else { + match ($i).find_substring($substr) { + None => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntilAndConsume,$i)) + }, + Some(index) => { + $crate::IResult::Done($i.slice(index+$substr.input_len()..), $i.slice(0..index)) + }, + } + }; + res + } + ); +); + +/// `take_until!(tag) => &[T] -> IResult<&[T], &[T]>` +/// consumes data until it finds the specified tag +#[macro_export] +macro_rules! take_until ( + ($i:expr, $substr:expr) => ( + { + use $crate::InputLength; + use $crate::FindSubstring; + use $crate::Slice; + + let res: $crate::IResult<_,_> = if $substr.input_len() > $i.input_len() { + $crate::IResult::Incomplete($crate::Needed::Size($substr.input_len())) + } else { + match ($i).find_substring($substr) { + None => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntil,$i)) + }, + Some(index) => { + $crate::IResult::Done($i.slice(index..), $i.slice(0..index)) + }, + } + }; + res + } + ); +); + +/// `take_until1!(tag) => &[T] -> IResult<&[T], &[T]>` +/// consumes data until it finds the specified tag +#[macro_export] +macro_rules! take_until1 ( + ($i:expr, $substr:expr) => ( + { + use $crate::InputLength; + use $crate::FindSubstring; + use $crate::Slice; + + let res: $crate::IResult<_,_> = if 1+$substr.input_len() > $i.input_len() { + $crate::IResult::Incomplete($crate::Needed::Size($substr.input_len())) + } else { + match ($i).find_substring($substr) { + None => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntil,$i)) + }, + Some(index) => { + $crate::IResult::Done($i.slice(index..), $i.slice(0..index)) + }, + } + }; + res + } + ); +); + +/// `take_until_either_and_consume!(tag) => &[T] -> IResult<&[T], &[T]>` +/// consumes data until it finds any of the specified characters, and consume it +#[macro_export] +macro_rules! take_until_either_and_consume ( + ($input:expr, $arr:expr) => ( + { + use $crate::InputLength; + use $crate::InputIter; + use $crate::FindToken; + use $crate::Slice; + + if $input.input_len() == 0 { + $crate::IResult::Incomplete($crate::Needed::Size(1)) + } else { + let res: $crate::IResult<_,_> = match $input.position(|c| { + c.find_token($arr) + }) { + Some(0) => $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntilEitherAndConsume,$input)), + Some(n) => { + let res = $crate::IResult::Done($input.slice(n+1..), $input.slice(..n)); + res + }, + None => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntilEitherAndConsume,$input)) + } + }; + res + } + } + ); +); + +/// `take_until_either!(tag) => &[T] -> IResult<&[T], &[T]>` +#[macro_export] +macro_rules! take_until_either ( + ($input:expr, $arr:expr) => ( + { + use $crate::InputLength; + use $crate::InputIter; + use $crate::FindToken; + use $crate::Slice; + + if $input.input_len() == 0 { + $crate::IResult::Incomplete($crate::Needed::Size(1)) + } else { + let res: $crate::IResult<_,_> = match $input.position(|c| { + c.find_token($arr) + }) { + Some(0) => $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntilEither,$input)), + Some(n) => { + let res = $crate::IResult::Done($input.slice(n..), $input.slice(..n)); + res + }, + None => { + $crate::IResult::Error(error_position!($crate::ErrorKind::TakeUntilEither,$input)) + } + }; + res + } + } + ); +); + +/// `length_bytes!(&[T] -> IResult<&[T], nb>) => &[T] -> IResult<&[T], &[T]>` +/// Gets a number from the first parser, then extracts that many bytes from the +/// remaining stream +#[macro_export] +macro_rules! length_bytes( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + length_data!($i, $submac!($($args)*)) + } + ); + ($i:expr, $f:expr) => ( + length_data!($i, call!($f)) + ) +); + +#[cfg(test)] +mod tests { + use internal::Needed; + use internal::IResult::*; + use util::ErrorKind; + use nom::{alpha, digit, hex_digit, oct_digit, alphanumeric, space, multispace}; + + macro_rules! one_of ( + ($i:expr, $inp: expr) => ( + { + if $i.is_empty() { + $crate::IResult::Incomplete::<_, _>($crate::Needed::Size(1)) + } else { + #[inline(always)] + fn as_bytes(b: &T) -> &[u8] { + b.as_bytes() + } + + let expected = $inp; + let bytes = as_bytes(&expected); + one_of_bytes!($i, bytes) + } + } + ); + ); + + macro_rules! one_of_bytes ( + ($i:expr, $bytes: expr) => ( + { + if $i.is_empty() { + $crate::IResult::Incomplete::<_, _>($crate::Needed::Size(1)) + } else { + let mut found = false; + + for &i in $bytes { + if i == $i[0] { + found = true; + break; + } + } + + if found { + $crate::IResult::Done(&$i[1..], $i[0] as char) + } else { + $crate::IResult::Error(error_position!($crate::ErrorKind::OneOf, $i)) + } + } + } + ); + ); + + #[test] + fn is_a() { + named!(a_or_b, is_a!(&b"ab"[..])); + + let a = &b"abcd"[..]; + assert_eq!(a_or_b(a), Done(&b"cd"[..], &b"ab"[..])); + + let b = &b"bcde"[..]; + assert_eq!(a_or_b(b), Done(&b"cde"[..], &b"b"[..])); + + let c = &b"cdef"[..]; + assert_eq!(a_or_b(c), Error(error_position!(ErrorKind::IsA,c))); + + let d = &b"bacdef"[..]; + assert_eq!(a_or_b(d), Done(&b"cdef"[..], &b"ba"[..])); + } + + #[test] + fn is_not() { + named!(a_or_b, is_not!(&b"ab"[..])); + + let a = &b"cdab"[..]; + assert_eq!(a_or_b(a), Done(&b"ab"[..], &b"cd"[..])); + + let b = &b"cbde"[..]; + assert_eq!(a_or_b(b), Done(&b"bde"[..], &b"c"[..])); + + let c = &b"abab"[..]; + assert_eq!(a_or_b(c), Error(error_position!(ErrorKind::IsNot,c))); + + let d = &b"cdefba"[..]; + assert_eq!(a_or_b(d), Done(&b"ba"[..], &b"cdef"[..])); + + let e = &b"e"[..]; + assert_eq!(a_or_b(e), Done(&b""[..], &b"e"[..])); + + let f = &b"fghi"[..]; + assert_eq!(a_or_b(f), Done(&b""[..], &b"fghi"[..])); + } + + #[allow(unused_variables)] + #[test] + fn escaping() { + named!(esc, escaped!(call!(alpha), '\\', one_of!("\"n\\"))); + assert_eq!(esc(&b"abcd"[..]), Done(&b""[..], &b"abcd"[..])); + assert_eq!(esc(&b"ab\\\"cd"[..]), Done(&b""[..], &b"ab\\\"cd"[..])); + assert_eq!(esc(&b"\\\"abcd"[..]), Done(&b""[..], &b"\\\"abcd"[..])); + assert_eq!(esc(&b"\\n"[..]), Done(&b""[..], &b"\\n"[..])); + assert_eq!(esc(&b"ab\\\"12"[..]), Done(&b"12"[..], &b"ab\\\""[..])); + assert_eq!(esc(&b"AB\\"[..]), Incomplete(Needed::Unknown)); + assert_eq!(esc(&b"AB\\A"[..]), Error(error_node_position!(ErrorKind::Escaped, &b"AB\\A"[..], + error_position!(ErrorKind::OneOf, &b"A"[..])))); + + named!(esc2, escaped!(call!(digit), '\\', one_of!("\"n\\"))); + assert_eq!(esc2(&b"12\\nnn34"[..]), Done(&b"nn34"[..], &b"12\\n"[..])); + } + + #[cfg(feature = "verbose-errors")] + fn to_s(i:Vec) -> String { + String::from_utf8_lossy(&i).into_owned() + } + + #[cfg(feature = "verbose-errors")] + #[test] + fn escape_transform() { + use std::str; + + named!(esc, map!(escaped_transform!(alpha, '\\', + alt!( + tag!("\\") => { |_| &b"\\"[..] } + | tag!("\"") => { |_| &b"\""[..] } + | tag!("n") => { |_| &b"\n"[..] } + )), to_s) + ); + + assert_eq!(esc(&b"abcd"[..]), Done(&b""[..], String::from("abcd"))); + assert_eq!(esc(&b"ab\\\"cd"[..]), Done(&b""[..], String::from("ab\"cd"))); + assert_eq!(esc(&b"\\\"abcd"[..]), Done(&b""[..], String::from("\"abcd"))); + assert_eq!(esc(&b"\\n"[..]), Done(&b""[..], String::from("\n"))); + assert_eq!(esc(&b"ab\\\"12"[..]), Done(&b"12"[..], String::from("ab\""))); + assert_eq!(esc(&b"AB\\"[..]), Error(error_node_position!(ErrorKind::EscapedTransform, &b"AB\\"[..], error_position!(ErrorKind::EscapedTransform, &b"\\"[..])))); + assert_eq!(esc(&b"AB\\A"[..]), Error(error_node_position!(ErrorKind::EscapedTransform, &b"AB\\A"[..], + error_position!(ErrorKind::Alt, &b"A"[..])))); + + let e = "è"; + let a = "à"; + println!("è: {:?} | à: {:?}", str::as_bytes(e), str::as_bytes(a)); + named!(esc2< String >, map!(escaped_transform!(call!(alpha), '&', + alt!( + tag!("egrave;") => { |_| str::as_bytes("è") } + | tag!("agrave;") => { |_| str::as_bytes("à") } + )), to_s) + ); + assert_eq!(esc2(&b"abèDEF"[..]), Done(&b""[..], String::from("abèDEF"))); + assert_eq!(esc2(&b"abèDàEF"[..]), Done(&b""[..], String::from("abèDàEF"))); + } + + #[test] + fn issue_84() { + let r0 = is_a!(&b"aaaaefgh"[..], "abcd"); + assert_eq!(r0, Done(&b"efgh"[..], &b"aaaa"[..])); + let r1 = is_a!(&b"aaaa"[..], "abcd"); + assert_eq!(r1, Done(&b""[..], &b"aaaa"[..])); + let r2 = is_a!(&b"1"[..], "123456789"); + assert_eq!(r2, Done(&b""[..], &b"1"[..])); + } + + #[test] + fn take_str_test() { + let a = b"omnomnom"; + + assert_eq!(take_str!(&a[..], 5), Done(&b"nom"[..], "omnom")); + assert_eq!(take_str!(&a[..], 9), Incomplete(Needed::Size(9))); + } + + #[test] + #[cfg(feature = "std")] + fn take_until_test() { + named!(x, take_until_and_consume!("efgh")); + let r = x(&b"abcdabcdefghijkl"[..]); + assert_eq!(r, Done(&b"ijkl"[..], &b"abcdabcd"[..])); + + println!("Done 1\n"); + + let r2 = x(&b"abcdabcdefgh"[..]); + assert_eq!(r2, Done(&b""[..], &b"abcdabcd"[..])); + + println!("Done 2\n"); + let r3 = x(&b"abcefg"[..]); + assert_eq!(r3, Error(error_position!(ErrorKind::TakeUntilAndConsume, &b"abcefg"[..]))); + + assert_eq!( + x(&b"ab"[..]), + Incomplete(Needed::Size(4)) + ); + } + + #[test] + fn take_until_either() { + named!(x, take_until_either!("!.")); + assert_eq!( + x(&b"123!abc"[..]), + Done(&b"!abc"[..], &b"123"[..]) + ); + } + + #[test] + fn take_until_either_incomplete() { + named!(x, take_until_either!("!.")); + assert_eq!( + x(&b"123"[..]), + Error(error_position!(ErrorKind::TakeUntilEither, &b"123"[..])) + ); + } + + #[test] + fn take_until_either_and_consume() { + named!(x, take_until_either_and_consume!("!.")); + assert_eq!( + x(&b"123.abc"[..]), + Done(&b"abc"[..], &b"123"[..]) + ); + } + + + #[test] + fn take_until_incomplete() { + named!(y, take_until!("end")); + assert_eq!( + y(&b"nd"[..]), + Incomplete(Needed::Size(3)) + ); + assert_eq!( + y(&b"123"[..]), + Error(error_position!(ErrorKind::TakeUntil, &b"123"[..])) + ); + } + + #[test] + fn recognize() { + named!(x, recognize!(delimited!(tag!("")))); + let r = x(&b" aaa"[..]); + assert_eq!(r, Done(&b" aaa"[..], &b""[..])); + + let empty = &b""[..]; + + named!(ya, recognize!(alpha)); + let ra = ya(&b"abc"[..]); + assert_eq!(ra, Done(empty, &b"abc"[..])); + + named!(yd, recognize!(digit)); + let rd = yd(&b"123"[..]); + assert_eq!(rd, Done(empty, &b"123"[..])); + + named!(yhd, recognize!(hex_digit)); + let rhd = yhd(&b"123abcDEF"[..]); + assert_eq!(rhd, Done(empty, &b"123abcDEF"[..])); + + named!(yod, recognize!(oct_digit)); + let rod = yod(&b"1234567"[..]); + assert_eq!(rod, Done(empty, &b"1234567"[..])); + + named!(yan, recognize!(alphanumeric)); + let ran = yan(&b"123abc"[..]); + assert_eq!(ran, Done(empty, &b"123abc"[..])); + + named!(ys, recognize!(space)); + let rs = ys(&b" \t"[..]); + assert_eq!(rs, Done(empty, &b" \t"[..])); + + named!(yms, recognize!(multispace)); + let rms = yms(&b" \t\r\n"[..]); + assert_eq!(rms, Done(empty, &b" \t\r\n"[..])); + } + + #[test] + fn take_while() { + use nom::is_alphabetic; + named!(f, take_while!(is_alphabetic)); + let a = b""; + let b = b"abcd"; + let c = b"abcd123"; + let d = b"123"; + + assert_eq!(f(&a[..]), Done(&a[..], &a[..])); + assert_eq!(f(&b[..]), Done(&a[..], &b[..])); + assert_eq!(f(&c[..]), Done(&d[..], &b[..])); + assert_eq!(f(&d[..]), Done(&d[..], &a[..])); + } + + #[test] + fn take_while1() { + use nom::is_alphabetic; + named!(f, take_while1!(is_alphabetic)); + let a = b""; + let b = b"abcd"; + let c = b"abcd123"; + let d = b"123"; + + assert_eq!(f(&a[..]), Incomplete(Needed::Size(1))); + assert_eq!(f(&b[..]), Done(&a[..], &b[..])); + assert_eq!(f(&c[..]), Done(&b"123"[..], &b[..])); + assert_eq!(f(&d[..]), Error(error_position!(ErrorKind::TakeWhile1, &d[..]))); + } + + #[test] + fn take_till() { + use nom::is_alphabetic; + named!(f, take_till!(is_alphabetic)); + let a = b""; + let b = b"abcd"; + let c = b"123abcd"; + let d = b"123"; + + assert_eq!(f(&a[..]), Done(&b""[..], &b""[..])); + assert_eq!(f(&b[..]), Done(&b"abcd"[..], &b""[..])); + assert_eq!(f(&c[..]), Done(&b"abcd"[..], &b"123"[..])); + assert_eq!(f(&d[..]), Done(&b""[..], &b"123"[..])); + } + + #[test] + fn take_till1() { + use nom::is_alphabetic; + named!(f, take_till1!(is_alphabetic)); + let a = b""; + let b = b"abcd"; + let c = b"123abcd"; + let d = b"123"; + + assert_eq!(f(&a[..]), Incomplete(Needed::Size(1))); + assert_eq!(f(&b[..]), Error(error_position!(ErrorKind::TakeTill1, &b[..]))); + assert_eq!(f(&c[..]), Done(&b"abcd"[..], &b"123"[..])); + assert_eq!(f(&d[..]), Done(&b""[..], &b"123"[..])); + } + + #[cfg(feature = "nightly")] + use test::Bencher; + + #[cfg(feature = "nightly")] + #[bench] + fn take_while_bench(b: &mut Bencher) { + use nom::is_alphabetic; + named!(f, take_while!(is_alphabetic)); + b.iter(|| { + f(&b"abcdefghijklABCDEejfrfrjgro12aa"[..]) + }); + } + + #[test] + #[cfg(feature = "std")] + fn recognize_take_while() { + use nom::is_alphanumeric; + named!(x, take_while!(is_alphanumeric)); + named!(y, recognize!(x)); + assert_eq!(x(&b"ab"[..]), Done(&[][..], &b"ab"[..])); + println!("X: {:?}", x(&b"ab"[..])); + assert_eq!(y(&b"ab"[..]), Done(&[][..], &b"ab"[..])); + } + + #[test] + fn length_bytes() { + use nom::le_u8; + named!(x, length_bytes!(le_u8)); + assert_eq!(x(b"\x02..>>"), Done(&b">>"[..], &b".."[..])); + assert_eq!(x(b"\x02.."), Done(&[][..], &b".."[..])); + assert_eq!(x(b"\x02."), Incomplete(Needed::Size(3))); + assert_eq!(x(b"\x02"), Incomplete(Needed::Size(3))); + + named!(y, do_parse!(tag!("magic") >> b: length_bytes!(le_u8) >> (b))); + assert_eq!(y(b"magic\x02..>>"), Done(&b">>"[..], &b".."[..])); + assert_eq!(y(b"magic\x02.."), Done(&[][..], &b".."[..])); + assert_eq!(y(b"magic\x02."), Incomplete(Needed::Size(8))); + assert_eq!(y(b"magic\x02"), Incomplete(Needed::Size(8))); + } + + #[test] + fn case_insensitive() { + named!(test, tag_no_case!("ABcd")); + assert_eq!(test(&b"aBCdefgh"[..]), Done(&b"efgh"[..], &b"aBCd"[..])); + assert_eq!(test(&b"abcdefgh"[..]), Done(&b"efgh"[..], &b"abcd"[..])); + assert_eq!(test(&b"ABCDefgh"[..]), Done(&b"efgh"[..], &b"ABCD"[..])); + assert_eq!(test(&b"ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(test(&b"Hello"[..]), Error(error_position!(ErrorKind::Tag, &b"Hello"[..]))); + assert_eq!(test(&b"Hel"[..]), Error(error_position!(ErrorKind::Tag, &b"Hel"[..]))); + + named!(test2<&str, &str>, tag_no_case!("ABcd")); + assert_eq!(test2("aBCdefgh"), Done("efgh", "aBCd")); + assert_eq!(test2("abcdefgh"), Done("efgh", "abcd")); + assert_eq!(test2("ABCDefgh"), Done("efgh", "ABCD")); + assert_eq!(test2("ab"), Incomplete(Needed::Size(4))); + assert_eq!(test2("Hello"), Error(error_position!(ErrorKind::Tag, &"Hello"[..]))); + assert_eq!(test2("Hel"), Error(error_position!(ErrorKind::Tag, &"Hel"[..]))); + } + + #[test] + fn tag_fixed_size_array() { + named!(test, tag!([0x42])); + named!(test2, tag!(&[0x42])); + let input = [0x42, 0x00]; + assert_eq!(test(&input), Done(&b"\x00"[..], &b"\x42"[..])); + assert_eq!(test2(&input), Done(&b"\x00"[..], &b"\x42"[..])); + } +} diff --git a/bash-5.1/vendor/nom/src/character.rs b/bash-5.1/vendor/nom/src/character.rs new file mode 100644 index 0000000..6748e07 --- /dev/null +++ b/bash-5.1/vendor/nom/src/character.rs @@ -0,0 +1,143 @@ +/// Character level parsers + +use internal::{IResult,Needed}; +use traits::{AsChar,InputIter,InputLength,Slice}; +use std::ops::RangeFrom; + +/// matches one of the provided characters +/// +/// # Example +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult; +/// # fn main() { +/// named!(simple, one_of!(&b"abc"[..])); +/// assert_eq!(simple(b"a123"), IResult::Done(&b"123"[..], 'a')); +/// +/// named!(a_or_b<&str, char>, one_of!("ab汉")); +/// assert_eq!(a_or_b("汉jiosfe"), IResult::Done("jiosfe", '汉')); +/// # } +/// ``` +#[macro_export] +macro_rules! one_of ( + ($i:expr, $inp: expr) => ( + { + use $crate::Slice; + use $crate::AsChar; + use $crate::FindToken; + use $crate::InputIter; + + match ($i).iter_elements().next().map(|c| { + (c, c.find_token($inp)) + }) { + None => $crate::IResult::Incomplete::<_, _>($crate::Needed::Size(1)), + Some((_, false)) => $crate::IResult::Error(error_position!($crate::ErrorKind::OneOf, $i)), + //the unwrap should be safe here + Some((c, true)) => $crate::IResult::Done($i.slice(c.len()..), $i.iter_elements().next().unwrap().as_char()) + } + } + ); +); + +/// matches anything but the provided characters +#[macro_export] +macro_rules! none_of ( + ($i:expr, $inp: expr) => ( + { + use $crate::Slice; + use $crate::AsChar; + use $crate::FindToken; + use $crate::InputIter; + + match ($i).iter_elements().next().map(|c| { + (c, !c.find_token($inp)) + }) { + None => $crate::IResult::Incomplete::<_, _>($crate::Needed::Size(1)), + Some((_, false)) => $crate::IResult::Error(error_position!($crate::ErrorKind::NoneOf, $i)), + //the unwrap should be safe here + Some((c, true)) => $crate::IResult::Done($i.slice(c.len()..), $i.iter_elements().next().unwrap().as_char()) + } + } + ); +); + +/// matches one character: `char!(char) => &[u8] -> IResult<&[u8], char> +#[macro_export] +macro_rules! char ( + ($i:expr, $c: expr) => ( + { + use $crate::Slice; + use $crate::AsChar; + use $crate::InputIter; + + match ($i).iter_elements().next().map(|c| { + (c, c.as_char() == $c) + }) { + None => $crate::IResult::Incomplete::<_, _>($crate::Needed::Size(1)), + Some((_, false)) => $crate::IResult::Error(error_position!($crate::ErrorKind::Char, $i)), + //the unwrap should be safe here + Some((c, true)) => $crate::IResult::Done($i.slice(c.len()..), $i.iter_elements().next().unwrap().as_char()) + } + } + ); +); + +named!(#[doc="Matches a newline character '\\n'"], pub newline, char!('\n')); + +named!(#[doc="Matches a tab character '\\t'"], pub tab, char!('\t')); + +pub fn anychar(input: T) -> IResult where + T: InputIter+InputLength+Slice>, + ::Item: AsChar { + if input.input_len() == 0 { + IResult::Incomplete(Needed::Size(1)) + } else { + IResult::Done(input.slice(1..), input.iter_elements().next().expect("slice should contain at least one element").as_char()) + } +} + +#[cfg(test)] +mod tests { + use internal::IResult::*; + use util::ErrorKind; + + #[test] + fn one_of() { + named!(f, one_of!("ab")); + + let a = &b"abcd"[..]; + assert_eq!(f(a), Done(&b"bcd"[..], 'a')); + + let b = &b"cde"[..]; + assert_eq!(f(b), Error(error_position!(ErrorKind::OneOf, b))); + + named!(utf8(&str) -> char, + one_of!("+\u{FF0B}")); + + assert!(utf8("+").is_done()); + assert!(utf8("\u{FF0B}").is_done()); + } + + #[test] + fn none_of() { + named!(f, none_of!("ab")); + + let a = &b"abcd"[..]; + assert_eq!(f(a), Error(error_position!(ErrorKind::NoneOf, a))); + + let b = &b"cde"[..]; + assert_eq!(f(b), Done(&b"de"[..], 'c')); + } + + #[test] + fn char() { + named!(f, char!('c')); + + let a = &b"abcd"[..]; + assert_eq!(f(a), Error(error_position!(ErrorKind::Char, a))); + + let b = &b"cde"[..]; + assert_eq!(f(b), Done(&b"de"[..], 'c')); + } + +} diff --git a/bash-5.1/vendor/nom/src/internal.rs b/bash-5.1/vendor/nom/src/internal.rs new file mode 100644 index 0000000..c5a51ee --- /dev/null +++ b/bash-5.1/vendor/nom/src/internal.rs @@ -0,0 +1,515 @@ +//! Basic types to build the parsers + +use self::IResult::*; +use self::Needed::*; + +#[cfg(not(feature = "std"))] +use std::prelude::v1::*; + +#[cfg(feature = "verbose-errors")] +use verbose_errors::Err; + +#[cfg(not(feature = "verbose-errors"))] +use simple_errors::Err; + +/// Contains information on needed data if a parser returned `Incomplete` +#[derive(Debug,PartialEq,Eq,Clone,Copy)] +pub enum Needed { + /// needs more data, but we do not know how much + Unknown, + /// contains the required data size + Size(usize) +} + +impl Needed { + pub fn is_known(&self) -> bool { + *self != Unknown + } + + /// Maps a `Needed` to `Needed` by appling a function to a contained `Size` value. + #[inline] + pub fn map usize>(self, f: F) -> Needed { + match self { + Unknown => Unknown, + Size(n) => Size(f(n)), + } + } +} + +#[cfg(feature = "verbose-errors")] +/// Holds the result of parsing functions +/// +/// It depends on I, the input type, O, the output type, and E, the error type (by default u32) +/// +/// Depending on a compilation flag, the content of the `Error` variant +/// can change. By default, it will be a `ErrorKind` (with `E` configurable). +/// +/// If you activate the `verbose-errors` compilation flags, it will be an +/// enum that contains an error code, optionally, an input position, +/// and an error sent by child parsers. +/// +/// The verbose errors feature allows very flexible error management: +/// you can know precisely which parser got to which part of the input. +/// The main drawback is that it is a lot slower than default error +/// management. +/// +#[derive(Debug,PartialEq,Eq,Clone)] +pub enum IResult { + /// indicates a correct parsing, the first field containing the rest of the unparsed data, the second field contains the parsed data + Done(I,O), + /// contains a Err, an enum that can indicate an error code, a position in the input, and a pointer to another error, making a list of errors in the parsing tree + Error(Err), + /// Incomplete contains a Needed, an enum than can represent a known quantity of input data, or unknown + Incomplete(Needed) +} + +#[cfg(not(feature = "verbose-errors"))] +/// Holds the result of parsing functions +/// +/// It depends on I, the input type, O, the output type, and E, the error type (by default u32) +/// +#[derive(Debug,PartialEq,Eq,Clone)] +pub enum IResult { + /// indicates a correct parsing, the first field containing the rest of the unparsed data, the second field contains the parsed data + Done(I,O), + /// contains a Err, an enum that can indicate an error code, a position in the input, and a pointer to another error, making a list of errors in the parsing tree + Error(Err), + /// Incomplete contains a Needed, an enum than can represent a known quantity of input data, or unknown + Incomplete(Needed) +} + +#[cfg(feature = "verbose-errors")] +/// This is the same as IResult, but without Done +/// +/// This is used as the Error type when converting to std::result::Result +#[derive(Debug,PartialEq,Eq,Clone)] +pub enum IError { + Error(Err), + Incomplete(Needed) +} + +#[cfg(not(feature = "verbose-errors"))] +/// This is the same as IResult, but without Done +/// +/// This is used as the Error type when converting to std::result::Result +#[derive(Debug,PartialEq,Eq,Clone)] +pub enum IError { + Error(Err), + Incomplete(Needed) +} + +impl IResult { + pub fn is_done(&self) -> bool { + match *self { + Done(_,_) => true, + _ => false + } + } + + pub fn is_err(&self) -> bool { + match *self { + Error(_) => true, + _ => false + } + } + + pub fn is_incomplete(&self) -> bool { + match *self { + Incomplete(_) => true, + _ => false + } + } + + pub fn or(self, other: IResult) -> IResult { + if self.is_done() { + self + } else { + other + } + } + + /// Maps a `IResult` to `IResult` by appling a function + /// to a contained `Done` value, leaving `Error` and `Incomplete` value + /// untouched. + #[inline] + pub fn map N>(self, f: F) -> IResult { + match self { + Done(i, o) => Done(i, f(o)), + Error(e) => Error(e), + Incomplete(n) => Incomplete(n), + } + } + + /// Maps a `IResult` to `IResult` by appling a function + /// to a contained `Incomplete` value, leaving `Done` and `Error` value + /// untouched. + #[inline] + pub fn map_inc(self, f: F) -> IResult + where F: FnOnce(Needed) -> Needed { + match self { + Error(e) => Error(e), + Incomplete(n) => Incomplete(f(n)), + Done(i, o) => Done(i, o), + } + } + + /// Unwrap the contained `Done(I, O)` value, or panic if the `IResult` is not + /// `Done`. + pub fn unwrap(self) -> (I, O) { + match self { + Done(i, o) => (i, o), + Incomplete(_) => panic!("unwrap() called on an IResult that is Incomplete"), + Error(_) => panic!("unwrap() called on an IResult that is Error") + } + } + + /// Unwrap the contained `Done(I, O)` value or a default if the `IResult` is not + /// `Done`. + pub fn unwrap_or(self, default: (I, O)) -> (I, O) { + match self { + Done(i, o) => (i, o), + Incomplete(_) => default, + Error(_) => default + } + } + + /// Unwrap the contained `Incomplete(n)` value, or panic if the `IResult` is not + /// `Incomplete`. + pub fn unwrap_inc(self) -> Needed { + match self { + Incomplete(n) => n, + Done(_, _) => panic!("unwrap_inc() called on an IResult that is Done"), + Error(_) => panic!("unwrap_inc() called on an IResult that is Error") + } + } +} + +pub trait GetInput { + fn remaining_input(&self) -> Option; +} + +pub trait GetOutput { + fn output(&self) -> Option; +} + +impl<'a,I,O,E> GetInput<&'a[I]> for IResult<&'a[I],O,E> { + fn remaining_input(&self) -> Option<&'a[I]> { + match *self { + Done(ref i,_) => Some(*i), + _ => None + } + } +} + +impl GetInput<()> for IResult<(),O,E> { + fn remaining_input(&self) -> Option<()> { + match *self { + Done((),_) => Some(()), + _ => None + } + } +} + +impl<'a,O,E> GetInput<&'a str> for IResult<&'a str,O,E> { + fn remaining_input(&self) -> Option<&'a str> { + match *self { + Done(ref i,_) => Some(*i), + _ => None + } + } +} + +impl<'a,I,O,E> GetOutput<&'a[O]> for IResult { + fn output(&self) -> Option<&'a[O]> { + match *self { + Done(_, ref o) => Some(*o), + _ => None + } + } +} + +impl GetOutput<()> for IResult { + fn output(&self) -> Option<()> { + match *self { + Done(_,()) => Some(()), + _ => None + } + } +} + +impl<'a,I,E> GetOutput<&'a str> for IResult { + fn output(&self) -> Option<&'a str> { + match *self { + Done(_,ref o) => Some(*o), + _ => None + } + } +} + +#[cfg(feature = "verbose-errors")] +/// creates a parse error from a `nom::ErrorKind` +#[macro_export] +macro_rules! error_code( + ($code:expr) => ($crate::Err::Code($code)); +); + +#[cfg(not(feature = "verbose-errors"))] +/// creates a parse error from a `nom::ErrorKind` +#[macro_export] +macro_rules! error_code( + ($code:expr) => ($code); +); + +#[cfg(feature = "verbose-errors")] +/// creates a parse error from a `nom::ErrorKind` +/// and the next error in the parsing tree. +/// if "verbose-errors" is not activated, +/// it default to only the error code +#[macro_export] +macro_rules! error_node( + ($code:expr, $next:expr) => { + let next_errors = match $next { + $crate::Err::Code(e) => { + let mut v = ::std::vec::Vec::new(); + v.push($crate::Err::Code(e)); + v + }, + $crate::Err::Position(e, p) => { + let mut v = ::std::vec::Vec::new(); + v.push($crate::Err::Position(e,p)); + v + }, + $crate::Err::Node(e, mut next) => { + next.push($crate::Err::Code(e)); + next + }, + $crate::Err::NodePosition(e, p, mut next) => { + next.push($crate::Err::Position(e,p)); + next + }, + }; + $crate::Err::Node($code, next_errors) + }; +); + +#[cfg(not(feature = "verbose-errors"))] +/// creates a parse error from a `nom::ErrorKind` +/// and the next error in the parsing tree. +/// if "verbose-errors" is not activated, +/// it default to only the error code +#[allow(unused_variables)] +#[macro_export] +macro_rules! error_node( + ($code:expr, $next:expr) => ($code); +); + +#[cfg(feature = "verbose-errors")] +/// creates a parse error from a `nom::ErrorKind` +/// and the position in the input +/// if "verbose-errors" is not activated, +/// it default to only the error code +#[macro_export] +macro_rules! error_position( + ($code:expr, $input:expr) => ($crate::Err::Position($code, $input)); +); + +#[cfg(not(feature = "verbose-errors"))] +/// creates a parse error from a `nom::ErrorKind` +/// and the position in the input +/// if "verbose-errors" is not activated, +/// it default to only the error code +#[allow(unused_variables)] +#[macro_export] +macro_rules! error_position( + ($code:expr, $input:expr) => ($code); +); + +#[cfg(feature = "verbose-errors")] +/// creates a parse error from a `nom::ErrorKind`, +/// the position in the input and the next error in +/// the parsing tree. +/// if "verbose-errors" is not activated, +/// it default to only the error code +#[macro_export] +macro_rules! error_node_position( + ($code:expr, $input:expr, $next:expr) => { + { + let next_errors = match $next { + $crate::Err::Code(e) => { + let mut v = ::std::vec::Vec::new(); + v.push($crate::Err::Code(e)); + v + }, + $crate::Err::Position(e, p) => { + let mut v = ::std::vec::Vec::new(); + v.push($crate::Err::Position(e,p)); + v + }, + $crate::Err::Node(e, mut next) => { + next.push($crate::Err::Code(e)); + next + }, + $crate::Err::NodePosition(e, p, mut next) => { + next.push($crate::Err::Position(e,p)); + next + } + }; + $crate::Err::NodePosition($code, $input, next_errors) + } + } +); + +#[cfg(not(feature = "verbose-errors"))] +/// creates a parse error from a `nom::ErrorKind`, +/// the position in the input and the next error in +/// the parsing tree. +/// if "verbose-errors" is not activated, +/// it default to only the error code +#[allow(unused_variables)] +#[macro_export] +macro_rules! error_node_position( + ($code:expr, $input: expr, $next:expr) => ($code); +); + +#[cfg(test)] +mod tests { + use super::*; + use util::ErrorKind; + + const REST: [u8; 0] = []; + const DONE: IResult<&'static [u8], u32> = IResult::Done(&REST, 5); + const ERROR: IResult<&'static [u8], u32> = IResult::Error(error_code!(ErrorKind::Tag)); + const INCOMPLETE: IResult<&'static [u8], u32> = IResult::Incomplete(Needed::Unknown); + + #[test] + fn iresult_or() { + assert_eq!(DONE.or(ERROR), DONE); + assert_eq!(ERROR.or(DONE), DONE); + assert_eq!(INCOMPLETE.or(ERROR), ERROR); + } + + #[test] + fn needed_map() { + let unknown = Needed::Unknown; + let size = Needed::Size(5); + + assert_eq!(size.map(|x| x * 2), Needed::Size(10)); + assert_eq!(unknown.map(|x| x * 2), Needed::Unknown); + } + + #[test] + fn iresult_map() { + assert_eq!(DONE.map(|x| x * 2), IResult::Done(&b""[..], 10)); + assert_eq!(ERROR.map(|x| x * 2), IResult::Error(error_code!(ErrorKind::Tag))); + assert_eq!(INCOMPLETE.map(|x| x * 2), IResult::Incomplete(Needed::Unknown)); + } + + #[test] + fn iresult_map_inc() { + let inc_unknown: IResult<&[u8], u32> = IResult::Incomplete(Needed::Unknown); + let inc_size: IResult<&[u8], u32> = IResult::Incomplete(Needed::Size(5)); + + assert_eq!(DONE.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Done(&b""[..], 5)); + assert_eq!(ERROR.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Error(error_code!(ErrorKind::Tag))); + assert_eq!(inc_unknown.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Incomplete(Needed::Unknown)); + assert_eq!(inc_size.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Incomplete(Needed::Size(6))); + } + + #[test] + #[cfg(feature = "std")] + fn iresult_map_err() { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + struct Error(u32); + + let error_kind = error_code!(ErrorKind::Custom(Error(5))); + + assert_eq!(DONE.map_err(|_| error_kind.clone()), IResult::Done(&b""[..], 5)); + assert_eq!(ERROR.map_err(|x| {println!("err: {:?}", x); error_kind.clone()}), IResult::Error(error_kind.clone())); + assert_eq!(INCOMPLETE.map_err(|x| {println!("err: {:?}", x); error_kind.clone()}), IResult::Incomplete(Needed::Unknown)); + } + + #[test] + fn iresult_unwrap_on_done() { + assert_eq!(DONE.unwrap(), (&b""[..], 5)); + } + + #[test] + #[should_panic] + fn iresult_unwrap_on_err() { + ERROR.unwrap(); + } + + #[test] + #[should_panic] + fn iresult_unwrap_on_inc() { + INCOMPLETE.unwrap(); + } + + #[test] + fn iresult_unwrap_or_on_done() { + assert_eq!(DONE.unwrap_or((&b""[..], 2)), (&b""[..], 5)); + } + + #[test] + fn iresult_unwrap_or_on_err() { + assert_eq!(ERROR.unwrap_or((&b""[..], 2)), (&b""[..], 2)); + } + + #[test] + fn iresult_unwrap_or_on_inc() { + assert_eq!(INCOMPLETE.unwrap_or((&b""[..], 2)), (&b""[..], 2)); + } + + #[test] + #[should_panic] + fn iresult_unwrap_err_on_done() { + DONE.unwrap_err(); + } + + #[test] + fn iresult_unwrap_err_on_err() { + assert_eq!(ERROR.unwrap_err(), error_code!(ErrorKind::Tag)); + } + + #[test] + #[should_panic] + fn iresult_unwrap_err_on_inc() { + INCOMPLETE.unwrap_err(); + } + + #[test] + #[should_panic] + fn iresult_unwrap_inc_on_done() { + DONE.unwrap_inc(); + } + + #[test] + #[should_panic] + fn iresult_unwrap_inc_on_err() { + ERROR.unwrap_inc(); + } + + #[test] + fn iresult_unwrap_inc_on_inc() { + assert_eq!(INCOMPLETE.unwrap_inc(), Needed::Unknown); + } + + #[test] + fn iresult_to_result() { + assert_eq!(DONE.to_result(), Ok(5)); + assert_eq!(ERROR.to_result(), Err(error_code!(ErrorKind::Tag))); + } + + #[test] + #[should_panic] + fn iresult_to_result_on_incomplete() { + INCOMPLETE.to_result().unwrap(); + } + + #[test] + fn iresult_to_full_result() { + assert_eq!(DONE.to_full_result(), Ok(5)); + assert_eq!(INCOMPLETE.to_full_result(), Err(IError::Incomplete(Needed::Unknown))); + assert_eq!(ERROR.to_full_result(), Err(IError::Error(error_code!(ErrorKind::Tag)))); + } +} diff --git a/bash-5.1/vendor/nom/src/lib.rs b/bash-5.1/vendor/nom/src/lib.rs new file mode 100644 index 0000000..150ef85 --- /dev/null +++ b/bash-5.1/vendor/nom/src/lib.rs @@ -0,0 +1,491 @@ +//! nom, eating data byte by byte +//! +//! nom is a parser combinator library with a focus on safe parsing, +//! streaming patterns, and as much as possible zero copy. +//! +//! The code is available on [Github](https://github.com/Geal/nom) +//! +//! There are a few [guides](http://rust.unhandledexpression.com/nom/home.html) with more details +//! about [the design of nom](http://rust.unhandledexpression.com/nom/how_nom_macros_work.html), +//! [how to write parsers](http://rust.unhandledexpression.com/nom/making_a_new_parser_from_scratch.html), +//! or the [error management system](http://rust.unhandledexpression.com/nom/error_management.html). +//! +//! If you are upgrading to nom 2.0, please read the +//! [migration document](http://rust.unhandledexpression.com/nom/upgrading_to_nom_2.html). +//! +//! See also the [FAQ](http://rust.unhandledexpression.com/nom/FAQ.html). +//! +//! # What are parser combinators? +//! +//! Parser combinators are a way to build parsers out of small functions. instead of +//! writing a huge grammar file then generaing code, like you would do with lex and yacc, +//! you write small functions, to parse small things like a character, or a number, +//! and then you assemble them in larger and larger functions, that can parse larger +//! parts of your formats. +//! +//! You end up with a list of small functions that you can reuse everywhere you need. Each +//! of them can be unit tested anf fuzzed separately. +//! +//! # nom parser design +//! +//! All nom parsers follow the same convention. They are all functions with the following signature: +//! +//! ```ignore +//! fn parser(input: I) -> IResult { ... } +//! ``` +//! +//! Here is the definition of that `IResult` type: +//! +//! ``` +//! # #[macro_use] extern crate nom; +//! # use nom::{Err,Needed}; +//! # fn main() {} +//! pub enum IResult { +//! Done(I,O), +//! Error(Err), // indicates the parser encountered an error. E is a custom error type you can redefine +//! /// Incomplete contains a Needed, an enum than can represent a known quantity of input data, or unknown +//! Incomplete(Needed) // if the parser did not have enough data to decide +//! } +//! ``` +//! +//! What it means: +//! +//! * `Done(i,o)` means the parser was successful. `i` is the remaining part of the input, `o` is the correctly parsed value +//! The remaining part can then be used as input for other parsers called in a sequence +//! * `Error(e)` indicates the parser encountered an error. The `Err` type is an enum of possible parser errors, +//! that can also contain a custom error that you'd specify, by redefining the `E` error type +//! * `Incomplete(i)` means the parser did not have enough information to decide, and tells you, if possible, +//! how much data it needs +//! +//! That way, you could write your own parser that recognizes the letter 'a' like this: +//! +//! ``` +//! #[macro_use] extern crate nom; +//! use nom::{IResult,Needed,Err,ErrorKind}; +//! # fn main() {} +//! +//! fn a(input: &[u8]) -> IResult<&[u8], char> { +//! // if there is not enough data, we return Ìncomplete +//! if input.len() == 0 { +//! IResult::Incomplete(Needed::Size(1)) +//! } else { +//! if input[0] == 'a' as u8 { +//! // the first part of the returned value is the remaining slice +//! IResult::Done(&input[1..], 'a') +//! } else { +//! IResult::Error(error_code!(ErrorKind::Custom(42))) +//! } +//! } +//! } +//! ``` +//! +//! Writing all the parsers manually, like this, is dangerous, despite Rust's safety features. There +//! are still a lot of mistakes one can make. That's why nom provides a list of macros to help in +//! developing parsers. As an example, here is a parser that would recognize the phrase +//! "Hello " and return the name of the person we hail: +//! +//! ``` +//! #[macro_use] extern crate nom; +//! use nom::alpha; +//! +//! named!(hello, preceded!(tag!("Hello "), alpha)); +//! # use nom::IResult; +//! # fn main() { +//! # assert_eq!(hello(b"Hello nom."), IResult::Done(&b"."[..], &b"nom"[..])); +//! # } +//! ``` +//! +//! Let's deconstruct it: +//! +//! * `named!` generates a function with the correct type. Without `named` here, we could write the parser +//! as follows: +//! +//! ``` +//! #[macro_use] extern crate nom; +//! use nom::{alpha,IResult}; +//! +//! fn hello(input: &[u8]) -> IResult<&[u8], &[u8]> { +//! preceded!(input, +//! tag!("Hello "), alpha) +//! } +//! # fn main() { +//! # assert_eq!(hello(b"Hello nom."), IResult::Done(&b"."[..], &b"nom"[..])); +//! # } +//! ``` +//! +//! By default, `named` makes a function that takes `&[u8]` as input type, and returns `&[u8]` as output type. +//! You can override it like this: +//! +//! * `named!(hello<&str>, ...):` would take `&[u8]` as input type, and return `&str` as output type. +//! * `named!(hello<&str, &str>, ...):` would take `&str` as input type, and return `&str` as output type. +//! +//! *Note* : when we don't use `named!`, we must pass the input as first argument of the top +//! level combinator (see the line `preceded!(input,` in the preceding code example). This is a macro trick +//! in nom to pass input from one combinator to the next by rewriting the call. +//! +//! Next part of the parser: `preceded!(tag!("Hello "), alpha))`. Here, `tag!` is a combinator that recognizes +//! a specific serie of bytes or characters. `alpha` is a function that recognizes alphabetical characters. +//! The `preceded!` combinator assembles them in a more complex parser: if both parsers are successful, +//! it returns the result of the second one (`alpha` is preceded by `tag!`). +//! +//! *Note* : combinators can assemble other combinators (macros), or parser functions, as long as they follow +//! the same interface. Here, `alpha` is a parser function already implemented in nom. +//! +//! # List of parsers and combinators +//! +//! ## Basic elements +//! +//! Those are used to recognize the lowest level elements of your grammar, like, "here is a dot", or +//! "here is an big endian integer". +//! +//! * **char!**: matches one character: `char!('a')` will make a parser that recognizes the letter 'a' (works with non ASCII chars too) +//! * **eof!**: `eof!()` returns its input if it is at the end of input data +//! * **is_a!, is_a_s!**: matches a sequence of any of the characters passed as arguments. `is_a!("ab1")` could recognize `ababa` or `1bb`. `is_a_s!` is a legacy combinator, it does exactly the same thing as `is_a` +//! * **is_not!, is_not_s!**: matches a sequence of none of the characters passed as arguments +//! * **one_of!**: matches one of the provided characters. `one_of!("abc")` could recognize 'a', 'b', or 'c'. It also works with non ASCII characters +//! * **none_of!**: matches anything but the provided characters +//! * **tag!, tag_s!**: recognizes a specific suite of characters or bytes. `tag!("hello")` matches "hello" +//! * **tag_no_case!**: recognizes a suite of ASCII characters, case insensitive. `tag_no_case!("hello")` could match "hello", "Hello" or even "HeLlO" +//! * **tag_no_case_s!** works like `tag_no_case` but on UTF-8 characters too (uses `&str` as input). Note that case insensitive comparison is not well defined for unicode, and that you might have bad surprises. Also, this combinator allocates a new string for the comparison. Ponder for a bit before using this combinator +//! * **take!, take_s!**: takes a specific number of bytes or characters. `take!(5)` would return "hello" from the string "hello world" +//! * **take_str!**: same as `take!` but returning a `&str` +//! * **take_till!, take_till_s!**: returns the longest list of bytes until the provided function succeeds. `take_till!(is_alphabetic)` with input "123abc" would return "123" +//! * **take_till1!, take_till1_s!**: same as `take_till!`, but the result must not be empty: `take_till1!(is_alphabetic)` would fail on "abc" +//! * **take_until!, take_until_s!**: returns the longest list of bytes until the provided tag is found. `take_until!("world")` with input "Hello world!" would return "Hello " and leave "world!" as remaining input +//! * **take_until1!**: same as `take_until!`, but cannot return an empty result +//! * **take_until_and_consume!, take_until_and_consume_s!**: same as `take_until!` but consumes the tag. `take_until_and_consume!("world")` with input "Hello world!" would return "Hello " and leave "!" as remaining input +//! * **take_until_and_consume1!**: same as `take_until_and_consume!`, but cannot return an empty result +//! * **take_until_either!**: returns the longest list of bytes until any of the provided characters are found +//! * **take_until_either_and_consume!**: same as `take_until_either!`, but consumes the terminating character +//! * **take_while!, take_while_s!**: returns the longest list of bytes for which the function is true. `take_while!(is_alphabetic)` with input "abc123" would return "abc" +//! * **take_while1!, take_while1_s!**: same as `take_while!`, but cannot return an empty result +//! * **value!**: you can use `value!` to always return the same result value without consuming input, like this: `value!(42)`. Or you can replace the result of a child parser with a predefined value, like this: `value!(42, tag!("abcd"))` which would replace, if successful, the return value from "abcd", to 42 +//! +//! Parsing integers from binary formats can be done in two ways: with parser functions, or combinators with configurable endianness: +//! +//! * configurable endianness: **i16!, i32!, i64!, u16!, u32!, u64!** are combinators that take as argument a `nom::Endianness`, +//! like this: `i16!(endianness)`. If the parameter is nom::Endianness::Big, parse a big endian i16 integer, otherwise a little endian i16 integer +//! * fixed endianness: the functions are prefixed by "be_" for big endian numbers, and by "le_" for little endian numbers, and the suffix is the type they parse to. As an example, "be_u32" parses a big endian unsigned integer stored in 32 bits. +//! * **be_f32, be_f64, le_f32, le_f64**: recognize floating point numbers +//! * **be_i8, be_i16, be_i32, be_i24, be_i32, be_i64**: big endian signed integers +//! * **be_u8, be_u16, be_u32, be_u24, be_u32, be_u64**: big endian unsigned integers +//! * **le_i8, le_i16, le_i32, le_i24, le_i32, le_i64**: little endian signed integers +//! * **le_u8, le_u16, le_u32, le_u24, le_u32, le_u64**: little endian unsigned integers +//! +//! ## Modifiers +//! +//! * **complete!**: replaces a Incomplete returned by the child parser with an Error +//! * **cond!**: conditional combinator +//! * **cond_reduce!**: Conditional combinator with error +//! * **cond_with_error!**: Conditional combinator +//! * **expr_opt!**: evaluates an expression that returns a Option and returns a IResult::Done(I,T) if Some +//! * **expr_res!**: evaluates an expression that returns a Result and returns a IResult::Done(I,T) if Ok +//! * **flat_map!**: +//! * **map!**: maps a function on the result of a parser +//! * **map_opt!**: maps a function returning an Option on the output of a parser +//! * **map_res!**: maps a function returning a Result on the output of a parser +//! * **not!**: returns a result only if the embedded parser returns Error or Incomplete does not consume the input +//! * **opt!**: make the underlying parser optional +//! * **opt_res!**: make the underlying parser optional +//! * **parse_to!**: uses the parse method from std::str::FromStr to convert the current input to the specified type +//! * **peek!**: returns a result without consuming the input +//! * **recognize!**: if the child parser was successful, return the consumed input as produced value +//! * **return_error!**: prevents backtracking if the child parser fails +//! * **tap!**: allows access to the parser's result without affecting it +//! * **verify!**: returns the result of the child parser if it satisfies a verification function +//! +//! ## Error management and debugging +//! +//! * **add_return_error!**: Add an error if the child parser fails +//! * **dbg!**: Prints a message if the parser fails +//! * **dbg_dmp!**: Prints a message and the input if the parser fails +//! * **error_code!**: creates a parse error from a nom::ErrorKind +//! * **error_node!**: creates a parse error from a nom::ErrorKind and the next error in the parsing tree. if "verbose-errors" is not activated, it default to only the error code +//! * **error_node_position!**: creates a parse error from a nom::ErrorKind, the position in the input and the next error in the parsing tree. if "verbose-errors" is not activated, it default to only the error code +//! * **error_position!**: creates a parse error from a nom::ErrorKind and the position in the input if "verbose-errors" is not activated, it default to only the error code +//! * **fix_error!**: translate parser result from IResult to IResult with a custom type +//! +//! ## Choice combinators +//! +//! * **alt!**: try a list of parsers and return the result of the first successful one +//! * **alt_complete!**: is equivalent to the alt! combinator, except that it will not return Incomplete when one of the constituting parsers returns Incomplete. Instead, it will try the next alternative in the chain. +//! * **switch!**: choose the next parser depending on the result of the first one, if successful, and returns the result of the second parser +//! +//! # Sequence combinators +//! +//! * **delimited!**: delimited(opening, X, closing) returns X +//! * **do_parse!**: do_parse applies sub parsers in a sequence. it can store intermediary results and make them available for later parsers +//! * **pair!**: pair(X,Y), returns (x,y) +//! * **permutation!**: applies its sub parsers in a sequence, but independent from their order this parser will only succeed if all of its sub parsers succeed +//! * **preceded!**: preceded(opening, X) returns X +//! * **separated_pair!**: separated_pair(X,sep,Y) returns (x,y) +//! * **terminated!**: terminated(X, closing) returns X +//! * **tuple!**: chains parsers and assemble the sub results in a tuple. +//! +//! ## Applying a parser multiple times +//! +//! * **count!**: Applies the child parser a specified number of times +//! * **count_fixed!**: Applies the child parser a fixed number of times and returns a fixed size array The type must be specified and it must be Copy +//! * **fold_many0!**: Applies the parser 0 or more times and folds the list of return values +//! * **fold_many1!**: Applies the parser 1 or more times and folds the list of return values +//! * **fold_many_m_n!**: Applies the parser between m and n times (n included) and folds the list of return value +//! * **length_count!**: gets a number from the first parser, then applies the second parser that many times +//! * **many0!**: Applies the parser 0 or more times and returns the list of results in a Vec +//! * **many1!**: Applies the parser 1 or more times and returns the list of results in a Vec +//! * **many_m_n!**: Applies the parser between m and n times (n included) and returns the list of results in a Vec +//! * **many_till!**: Applies the first parser until the second applies. Returns a tuple containing the list of results from the first in a Vec and the result of the second. +//! * **separated_list!**: separated_list(sep, X) returns Vec will return Incomplete if there may be more elements +//! * **separated_list_complete!**: This is equivalent to the separated_list! combinator, except that it will return Error when either the separator or element subparser returns Incomplete. +//! * **separated_nonempty_list!**: separated_nonempty_list(sep, X) returns Vec will return Incomplete if there may be more elements +//! * **separated_nonempty_list_complete!**: This is equivalent to the separated_nonempty_list! combinator, except that it will return Error when either the separator or element subparser returns Incomplete. +//! +//! ## Text parsing +//! +//! * **escaped!**: matches a byte string with escaped characters. +//! * **escaped_transform!**: matches a byte string with escaped characters, and returns a new string with the escaped characters replaced +//! +//! ## Binary format parsing +//! +//! * **length_data!**: gets a number from the first parser, than takes a subslice of the input of that size, and returns that subslice +//! * **length_bytes!**: alias for `length_data` +//! * **length_value!**: gets a number from the first parser, takes a subslice of the input of that size, then applies the second parser on that subslice. If the second parser returns Incomplete, length_value will return an error +//! +//! ## Bit stream parsing +//! +//! * **bits!**: transforms the current input type (byte slice `&[u8]`) to a bit stream on which bit specific parsers and more general combinators can be applied +//! * **bytes!**: transforms its bits stream input back into a byte slice for the underlying parsers. +//! * **tag_bits!**: matches an integer pattern to a bitstream. The number of bits of the input to compare must be specified +//! * **take_bits!**: generates a parser consuming the specified number of bits +//! +//! ## Whitespace delimited formats parsing +//! +//! * **eat_separator!**: helper macros to build a separator parser +//! * **sep!**: sep is the parser rewriting macro for whitespace separated formats +//! * **wrap_sep!**: +//! * **ws!**: +//! +//! ## Remaining combinators +//! +//! * **apply!**: emulate function currying: apply!(my_function, arg1, arg2, ...) becomes my_function(input, arg1, arg2, ...) +//! * **apply_m!**: emulate function currying for method calls on structs apply_m!(self.my_function, arg1, arg2, ...) becomes self.my_function(input, arg1, arg2, ...) +//! * **call!**: Used to wrap common expressions and function as macros +//! * **call_m!**: Used to called methods then move self back into self +//! * **closure!**: Wraps a parser in a closure +//! * **method!**: Makes a method from a parser combination +//! * **named!**: Makes a function from a parser combination +//! * **named_args!**: Makes a function from a parser combination with arguments. +//! * **named_attr!**: Makes a function from a parser combination, with attributes +//! * **try_parse!**: A bit like std::try!, this macro will return the remaining input and parsed value if the child parser returned Done, and will do an early return for Error and Incomplete this can provide more flexibility than do_parse! if needed +//! +//! ## Character test functions +//! +//! use those functions with a combinator like `take_while!`: +//! +//! * **is_alphabetic**: Tests if byte is ASCII alphabetic: A-Z, a-z +//! * **is_alphanumeric**: Tests if byte is ASCII alphanumeric: A-Z, a-z, 0-9 +//! * **is_digit**: Tests if byte is ASCII digit: 0-9 +//! * **is_hex_digit**: Tests if byte is ASCII hex digit: 0-9, A-F, a-f +//! * **is_oct_digit**: Tests if byte is ASCII octal digit: 0-7 +//! * **is_space**: Tests if byte is ASCII space or tab +//! +//! ## Remaining functions (sort those out in the other categories) +//! +//! * **alpha**: Recognizes one or more lowercase and uppercase alphabetic characters: a-zA-Z +//! * **alphanumeric**: Recognizes one or more numerical and alphabetic characters: 0-9a-zA-Z +//! * **anychar**: +//! * **begin**: +//! * **crlf**: +//! * **digit**: Recognizes one or more numerical characters: 0-9 +//! * **double**: Recognizes floating point number in a byte string and returns a f64 +//! * **double_s**: Recognizes floating point number in a string and returns a f64 +//! * **eol**: +//! * **float**: Recognizes floating point number in a byte string and returns a f32 +//! * **float_s**: Recognizes floating point number in a string and returns a f32 +//! * **hex_digit**: Recognizes one or more hexadecimal numerical characters: 0-9, A-F, a-f +//! * **hex_u32**: Recognizes a hex-encoded integer +//! * **line_ending**: Recognizes an end of line (both '\n' and "\r\n") +//! * **multispace**: Recognizes one or more spaces, tabs, carriage returns and line feeds +//! * **newline**: Matches a newline character '\n' +//! * **non_empty**: Recognizes non empty buffers +//! * **not_line_ending**: +//! * **oct_digit**: Recognizes one or more octal characters: 0-7 +//! * **rest**: Return the remaining input. +//! * **rest_s**: Return the remaining input, for strings. +//! * **shift**: +//! * **sized_buffer**: +//! * **space**: Recognizes one or more spaces and tabs +//! * **tab**: Matches a tab character '\t' +//! * **tag_cl**: +//! +//! # Example +//! +//! ``` +//! #[macro_use] +//! extern crate nom; +//! +//! use nom::{IResult,digit}; +//! +//! // Parser definition +//! +//! use std::str; +//! use std::str::FromStr; +//! +//! // We parse any expr surrounded by parens, ignoring all whitespaces around those +//! named!(parens, ws!(delimited!( tag!("("), expr, tag!(")") )) ); +//! +//! // We transform an integer string into a i64, ignoring surrounding whitespaces +//! // We look for a digit suite, and try to convert it. +//! // If either str::from_utf8 or FromStr::from_str fail, +//! // we fallback to the parens parser defined above +//! named!(factor, alt!( +//! map_res!( +//! map_res!( +//! ws!(digit), +//! str::from_utf8 +//! ), +//! FromStr::from_str +//! ) +//! | parens +//! ) +//! ); +//! +//! // We read an initial factor and for each time we find +//! // a * or / operator followed by another factor, we do +//! // the math by folding everything +//! named!(term , do_parse!( +//! init: factor >> +//! res: fold_many0!( +//! pair!(alt!(tag!("*") | tag!("/")), factor), +//! init, +//! |acc, (op, val): (&[u8], i64)| { +//! if (op[0] as char) == '*' { acc * val } else { acc / val } +//! } +//! ) >> +//! (res) +//! ) +//! ); +//! +//! named!(expr , do_parse!( +//! init: term >> +//! res: fold_many0!( +//! pair!(alt!(tag!("+") | tag!("-")), term), +//! init, +//! |acc, (op, val): (&[u8], i64)| { +//! if (op[0] as char) == '+' { acc + val } else { acc - val } +//! } +//! ) >> +//! (res) +//! ) +//! ); +//! +//! fn main() { +//! assert_eq!(expr(b"1+2"), IResult::Done(&b""[..], 3)); +//! assert_eq!(expr(b"12+6-4+3"), IResult::Done(&b""[..], 17)); +//! assert_eq!(expr(b"1+2*3+4"), IResult::Done(&b""[..], 11)); +//! +//! assert_eq!(expr(b"(2)"), IResult::Done(&b""[..], 2)); +//! assert_eq!(expr(b"2*(3+4)"), IResult::Done(&b""[..], 14)); +//! assert_eq!(expr(b"2*2/(5-1)+3"), IResult::Done(&b""[..], 4)); +//! } +//! ``` +#![cfg_attr(not(feature = "std"), feature(no_std))] +#![cfg_attr(not(feature = "std"), feature(collections))] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(feature = "nightly", feature(test))] +#![cfg_attr(feature = "nightly", feature(const_fn))] +#![cfg_attr(feature = "nightly", feature(plugin))] +#![cfg_attr(feature = "nightly", plugin(compiler_error))] +//#![warn(missing_docs)] + +#[cfg(not(feature = "std"))] +extern crate collections; +#[cfg(feature = "regexp")] +extern crate regex; +#[cfg(feature = "regexp_macros")] +#[macro_use] extern crate lazy_static; +extern crate memchr; +#[cfg(feature = "nightly")] +extern crate test; + +#[cfg(not(feature = "nightly"))] +#[allow(unused_macros)] +#[macro_export] +macro_rules! compiler_error { + ($e:expr) => { + INVALID_NOM_SYNTAX_PLEASE_SEE_FAQ //https://github.com/Geal/nom/blob/master/doc/FAQ.md#using-nightly-to-get-better-error-messages + } +} + +#[cfg(not(feature = "std"))] +mod std { +#[macro_use] + pub use core::{fmt, cmp, iter, option, result, ops, slice, str, mem, convert}; + pub use collections::{boxed, vec, string}; + pub mod prelude { + pub use core::prelude as v1; + } +} + +pub use self::util::*; +pub use self::traits::*; + +#[cfg(feature = "verbose-errors")] +pub use self::verbose_errors::*; + +#[cfg(not(feature = "verbose-errors"))] +pub use self::simple_errors::*; + +pub use self::internal::*; +pub use self::macros::*; +pub use self::branch::*; +pub use self::sequence::*; +pub use self::multi::*; +pub use self::methods::*; +pub use self::bytes::*; +pub use self::bits::*; + +pub use self::nom::*; +pub use self::character::*; + +pub use self::whitespace::*; + +#[cfg(feature = "regexp")] +pub use self::regexp::*; + +#[cfg(feature = "std")] +#[cfg(feature = "stream")] +pub use self::stream::*; + +pub use self::str::*; + +#[macro_use] mod util; +mod traits; + +#[cfg(feature = "verbose-errors")] #[macro_use] pub mod verbose_errors; + +#[cfg(not(feature = "verbose-errors"))] #[macro_use] pub mod simple_errors; + +#[macro_use] mod internal; +#[macro_use] mod macros; +#[macro_use] mod branch; +#[macro_use] mod sequence; +#[macro_use] mod multi; +#[macro_use] pub mod methods; +#[macro_use] mod bytes; +#[macro_use] pub mod bits; + +#[macro_use] mod nom; +#[macro_use] mod character; + +#[macro_use] +pub mod whitespace; + +#[cfg(feature = "regexp")] +#[macro_use] mod regexp; + +#[macro_use] +#[cfg(feature = "std")] +#[cfg(feature = "stream")] +mod stream; + +mod str; diff --git a/bash-5.1/vendor/nom/src/macros.rs b/bash-5.1/vendor/nom/src/macros.rs new file mode 100644 index 0000000..2bbe4bc --- /dev/null +++ b/bash-5.1/vendor/nom/src/macros.rs @@ -0,0 +1,1342 @@ +//! Macro combinators +//! +//! Macros are used to make combination easier, +//! since they often do not depend on the type +//! of the data they manipulate or return. +//! +//! There is a trick to make them easier to assemble, +//! combinators are defined like this: +//! +//! ```ignore +//! macro_rules! tag ( +//! ($i:expr, $inp: expr) => ( +//! { +//! ... +//! } +//! ); +//! ); +//! ``` +//! +//! But when used in other combinators, are Used +//! like this: +//! +//! ```ignore +//! named!(my_function, tag!("abcd")); +//! ``` +//! +//! Internally, other combinators will rewrite +//! that call to pass the input as first argument: +//! +//! ```ignore +//! macro_rules! named ( +//! ($name:ident, $submac:ident!( $($args:tt)* )) => ( +//! fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> { +//! $submac!(i, $($args)*) +//! } +//! ); +//! ); +//! ``` +//! +//! If you want to call a combinator directly, you can +//! do it like this: +//! +//! ```ignore +//! let res = { tag!(input, "abcd"); } +//! ``` +//! +//! Combinators must have a specific variant for +//! non-macro arguments. Example: passing a function +//! to take_while! instead of another combinator. +//! +//! ```ignore +//! macro_rules! take_while( +//! ($input:expr, $submac:ident!( $($args:tt)* )) => ( +//! { +//! ... +//! } +//! ); +//! +//! // wrap the function in a macro to pass it to the main implementation +//! ($input:expr, $f:expr) => ( +//! take_while!($input, call!($f)); +//! ); +//! ); +//! ``` +#[allow(unused_variables)] + +/// Wraps a parser in a closure +#[macro_export] +macro_rules! closure ( + ($ty:ty, $submac:ident!( $($args:tt)* )) => ( + |i: $ty| { $submac!(i, $($args)*) } + ); + ($submac:ident!( $($args:tt)* )) => ( + |i| { $submac!(i, $($args)*) } + ); +); + +/// Makes a function from a parser combination +/// +/// The type can be set up if the compiler needs +/// more information +/// +/// ```ignore +/// named!(my_function( &[u8] ) -> &[u8], tag!("abcd")); +/// // first type parameter is input, second is output +/// named!(my_function<&[u8], &[u8]>, tag!("abcd")); +/// // will have &[u8] as input type, &[u8] as output type +/// named!(my_function, tag!("abcd")); +/// // will use &[u8] as input type (use this if the compiler +/// // complains about lifetime issues +/// named!(my_function<&[u8]>, tag!("abcd")); +/// //prefix them with 'pub' to make the functions public +/// named!(pub my_function, tag!("abcd")); +/// ``` +#[macro_export] +macro_rules! named ( + (#$($args:tt)*) => ( + named_attr!(#$($args)*); + ); + ($name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( i: $i ) -> $crate::IResult<$i,$o,u32> { + $submac!(i, $($args)*) + } + ); + ($name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> { + $submac!(i, $($args)*) + } + ); + ($name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> { + $submac!(i, $($args)*) + } + ); + ($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<&'a [u8], $o, u32> { + $submac!(i, $($args)*) + } + ); + ($name:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( i: &[u8] ) -> $crate::IResult<&[u8], &[u8], u32> { + $submac!(i, $($args)*) + } + ); + (pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( i: $i ) -> $crate::IResult<$i,$o, u32> { + $submac!(i, $($args)*) + } + ); + (pub $name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> { + $submac!(i, $($args)*) + } + ); + (pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> { + $submac!(i, $($args)*) + } + ); + (pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( i: &[u8] ) -> $crate::IResult<&[u8], $o, u32> { + $submac!(i, $($args)*) + } + ); + (pub $name:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<&[u8], &[u8], u32> { + $submac!(i, $($args)*) + } + ); +); + +/// Makes a function from a parser combination with arguments. +#[macro_export] +macro_rules! named_args { + (pub $func_name:ident ( $( $arg:ident : $typ:ty ),* ) < $return_type:ty > , $submac:ident!( $($args:tt)* ) ) => { + pub fn $func_name(input: &[u8], $( $arg : $typ ),*) -> $crate::IResult<&[u8], $return_type> { + $submac!(input, $($args)*) + } + }; + (pub $func_name:ident < 'a > ( $( $arg:ident : $typ:ty ),* ) < $return_type:ty > , $submac:ident!( $($args:tt)* ) ) => { + pub fn $func_name<'this_is_probably_unique_i_hope_please, 'a>(input: &'this_is_probably_unique_i_hope_please [u8], $( $arg : $typ ),*) -> $crate::IResult<&'this_is_probably_unique_i_hope_please [u8], $return_type> { + $submac!(input, $($args)*) + } + }; + ($func_name:ident ( $( $arg:ident : $typ:ty ),* ) < $return_type:ty > , $submac:ident!( $($args:tt)* ) ) => { + fn $func_name(input: &[u8], $( $arg : $typ ),*) -> $crate::IResult<&[u8], $return_type> { + $submac!(input, $($args)*) + } + }; + ($func_name:ident < 'a > ( $( $arg:ident : $typ:ty ),* ) < $return_type:ty > , $submac:ident!( $($args:tt)* ) ) => { + fn $func_name<'this_is_probably_unique_i_hope_please, 'a>(input: &'this_is_probably_unique_i_hope_please [u8], $( $arg : $typ ),*) -> $crate::IResult<&'this_is_probably_unique_i_hope_please [u8], $return_type> { + $submac!(input, $($args)*) + } + }; +} + +/// Makes a function from a parser combination, with attributes +/// +/// The usage of this macro is almost identical to `named!`, except that +/// you also pass attributes to be attached to the generated function. +/// This is ideal for adding documentation to your parser. +/// +/// ```ignore +/// // Create my_function as if you wrote it with the doc comment /// My Func +/// named_attr!(#[doc = "My Func"], my_function( &[u8] ) -> &[u8], tag!("abcd")); +/// // Also works for pub functions, and multiple lines +/// named!(#[doc = "My Func\nRecognise abcd"], pub my_function, tag!("abcd")); +/// // Multiple attributes can be passed if required +/// named!(#[doc = "My Func"] #[inline(always)], pub my_function, tag!("abcd")); +/// ``` +#[macro_export] +macro_rules! named_attr ( + ($(#[$attr:meta])*, $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + fn $name( i: $i ) -> $crate::IResult<$i,$o,u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, $name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<&'a [u8], $o, u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, $name:ident, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + fn $name( i: &[u8] ) -> $crate::IResult<&[u8], &[u8], u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + pub fn $name( i: $i ) -> $crate::IResult<$i,$o, u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, pub $name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + pub fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + pub fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + pub fn $name( i: &[u8] ) -> $crate::IResult<&[u8], $o, u32> { + $submac!(i, $($args)*) + } + ); + ($(#[$attr:meta])*, pub $name:ident, $submac:ident!( $($args:tt)* )) => ( + $(#[$attr])* + pub fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<&[u8], &[u8], u32> { + $submac!(i, $($args)*) + } + ); +); + +/// Used to wrap common expressions and function as macros +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult; +/// # fn main() { +/// fn take_wrapper(input: &[u8], i: u8) -> IResult<&[u8],&[u8]> { take!(input, i * 10) } +/// +/// // will make a parser taking 20 bytes +/// named!(parser, call!(take_wrapper, 2)); +/// # } +/// ``` +#[macro_export] +macro_rules! call ( + ($i:expr, $fun:expr) => ( $fun( $i ) ); + ($i:expr, $fun:expr, $($args:expr),* ) => ( $fun( $i, $($args),* ) ); +); + +/// emulate function currying: `apply!(my_function, arg1, arg2, ...)` becomes `my_function(input, arg1, arg2, ...)` +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult; +/// # fn main() { +/// fn take_wrapper(input: &[u8], i: u8) -> IResult<&[u8],&[u8]> { take!(input, i * 10) } +/// +/// // will make a parser taking 20 bytes +/// named!(parser, apply!(take_wrapper, 2)); +/// # } +/// ``` +#[macro_export] +macro_rules! apply ( + ($i:expr, $fun:expr, $($args:expr),* ) => ( $fun( $i, $($args),* ) ); +); + +/// Prevents backtracking if the child parser fails +/// +/// This parser will do an early return instead of sending +/// its result to the parent parser. +/// +/// If another `return_error!` combinator is present in the parent +/// chain, the error will be wrapped and another early +/// return will be made. +/// +/// This makes it easy to build report on which parser failed, +/// where it failed in the input, and the chain of parsers +/// that led it there. +/// +/// Additionally, the error chain contains number identifiers +/// that can be matched to provide useful error messages. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use std::collections; +/// # use nom::IResult::Error; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::{Position,NodePosition}; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(err_test, alt!( +/// tag!("abcd") | +/// preceded!(tag!("efgh"), return_error!(ErrorKind::Custom(42), +/// do_parse!( +/// tag!("ijkl") >> +/// res: return_error!(ErrorKind::Custom(128), tag!("mnop")) >> +/// (res) +/// ) +/// ) +/// ) +/// )); +/// let a = &b"efghblah"[..]; +/// let b = &b"efghijklblah"[..]; +/// let c = &b"efghijklmnop"[..]; +/// +/// let blah = &b"blah"[..]; +/// +/// let res_a = err_test(a); +/// let res_b = err_test(b); +/// let res_c = err_test(c); +/// assert_eq!(res_a, Error(error_node_position!(ErrorKind::Custom(42), blah, error_position!(ErrorKind::Tag, blah)))); +/// assert_eq!(res_b, Error(error_node_position!(ErrorKind::Custom(42), &b"ijklblah"[..], +/// error_node_position!(ErrorKind::Custom(128), blah, error_position!(ErrorKind::Tag, blah)))) +/// ); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! return_error ( + ($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => ( + { + let i_ = $i.clone(); + let cl = || { + $submac!(i_, $($args)*) + }; + + match cl() { + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => { + return $crate::IResult::Error(error_node_position!($code, $i, e)) + } + } + } + ); + ($i:expr, $code:expr, $f:expr) => ( + return_error!($i, $code, call!($f)); + ); +); + +/// Add an error if the child parser fails +/// +/// While error! does an early return and avoids backtracking, +/// add_return_error! backtracks normally. It just provides more context +/// for an error +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use std::collections; +/// # use nom::IResult::Error; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::{Position,NodePosition}; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(err_test, add_return_error!(ErrorKind::Custom(42), tag!("abcd"))); +/// +/// let a = &b"efghblah"[..]; +/// let res_a = err_test(a); +/// assert_eq!(res_a, Error(error_node_position!(ErrorKind::Custom(42), a, error_position!(ErrorKind::Tag, a)))); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! add_return_error ( + ($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => { + $crate::IResult::Error(error_node_position!($code, $i, e)) + } + } + } + ); + ($i:expr, $code:expr, $f:expr) => ( + add_return_error!($i, $code, call!($f)); + ); +); + +/// replaces a `Incomplete` returned by the child parser +/// with an `Error` +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use std::collections; +/// # use nom::IResult::Error; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::{Position,NodePosition}; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(take_5, complete!(take!(5))); +/// +/// let a = &b"abcd"[..]; +/// let res_a = take_5(a); +/// assert_eq!(res_a, Error(error_position!(ErrorKind::Complete, a))); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! complete ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(_) => { + $crate::IResult::Error(error_position!($crate::ErrorKind::Complete, $i)) + }, + } + } + ); + ($i:expr, $f:expr) => ( + complete!($i, call!($f)); + ); +); + +/// A bit like `std::try!`, this macro will return the remaining input and parsed value if the child parser returned `Done`, +/// and will do an early return for `Error` and `Incomplete` +/// this can provide more flexibility than `do_parse!` if needed +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self, Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::{be_u8,ErrorKind}; +/// +/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> { +/// let (i1, sz) = try_parse!(input, be_u8); +/// let (i2, length) = try_parse!(i1, expr_opt!(size.checked_add(sz))); +/// let (i3, data) = try_parse!(i2, take!(length)); +/// return Done(i3, data); +/// } +/// # fn main() { +/// let arr1 = [1, 2, 3, 4, 5]; +/// let r1 = take_add(&arr1[..], 1); +/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..])); +/// +/// let arr2 = [0xFE, 2, 3, 4, 5]; +/// // size is overflowing +/// let r1 = take_add(&arr2[..], 42); +/// assert_eq!(r1, Error(error_position!(ErrorKind::ExprOpt,&[2,3,4,5][..]))); +/// # } +/// ``` +#[macro_export] +macro_rules! try_parse ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,o) => (i,o), + $crate::IResult::Error(e) => return $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => return $crate::IResult::Incomplete(i) + } + ); + ($i:expr, $f:expr) => ( + try_parse!($i, call!($f)) + ); +); + +/// `map!(I -> IResult, O -> P) => I -> IResult` +/// maps a function on the result of a parser +#[macro_export] +macro_rules! map( + // Internal parser, do not use directly + (__impl $i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + { + pub fn _unify R>(f: F, t: T) -> R { + f(t) + } + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, _unify($g, o)) + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + map!(__impl $i, $submac!($($args)*), $g); + ); + ($i:expr, $f:expr, $g:expr) => ( + map!(__impl $i, call!($f), $g); + ); +); + +/// `map_res!(I -> IResult, O -> Result

) => I -> IResult` +/// maps a function returning a Result on the output of a parser +#[macro_export] +macro_rules! map_res ( + // Internal parser, do not use directly + (__impl $i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)), + $crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) { + Ok(output) => $crate::IResult::Done(i, output), + Err(_) => $crate::IResult::Error(error_position!($crate::ErrorKind::MapRes, $i)) + } + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + map_res!(__impl $i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + map_res!(__impl $i, $submac!($($args)*), $submac2!($($args2)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + map_res!(__impl $i, call!($f), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + map_res!(__impl $i, call!($f), $submac!($($args)*)); + ); +); + +/// `map_opt!(I -> IResult, O -> Option

) => I -> IResult` +/// maps a function returning an Option on the output of a parser +#[macro_export] +macro_rules! map_opt ( + // Internal parser, do not use directly + (__impl $i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)), + $crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) { + ::std::option::Option::Some(output) => $crate::IResult::Done(i, output), + ::std::option::Option::None => $crate::IResult::Error(error_position!($crate::ErrorKind::MapOpt, $i)) + } + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + map_opt!(__impl $i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + map_opt!(__impl $i, $submac!($($args)*), $submac2!($($args2)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + map_opt!(__impl $i, call!($f), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + map_opt!(__impl $i, call!($f), $submac!($($args)*)); + ); +); + +/// `parse_to!(O) => I -> IResult` +/// uses the `parse` method from `std::str::FromStr` to convert the current +/// input to the specified type +/// +/// this will completely consume the input +#[macro_export] +macro_rules! parse_to ( + ($i:expr, $t:ty ) => ( + { + use $crate::ParseTo; + use $crate::Slice; + use $crate::InputLength; + match ($i).parse_to() { + ::std::option::Option::Some(output) => $crate::IResult::Done($i.slice(..$i.input_len()), output), + ::std::option::Option::None => $crate::IResult::Error(error_position!($crate::ErrorKind::MapOpt, $i)) + } + } + ); +); + +/// `verify!(I -> IResult, O -> bool) => I -> IResult` +/// returns the result of the child parser if it satisfies a verification function +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::be_u32; +/// # fn main() { +/// named!(check, verify!(be_u32, |val:u32| val >= 0 && val < 3)); +/// # } +/// ``` +#[macro_export] +macro_rules! verify ( + // Internal parser, do not use directly + (__impl $i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)), + $crate::IResult::Done(i, o) => if $submac2!(o, $($args2)*) { + $crate::IResult::Done(i, o) + } else { + $crate::IResult::Error(error_position!($crate::ErrorKind::Verify, $i)) + } + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + verify!(__impl $i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + verify!(__impl $i, $submac!($($args)*), $submac2!($($args2)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + verify!(__impl $i, call!($f), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + verify!(__impl $i, call!($f), $submac!($($args)*)); + ); +); + +/// `value!(T, R -> IResult ) => R -> IResult` +/// +/// or `value!(T) => R -> IResult` +/// +/// If the child parser was successful, return the value. +/// If no child parser is provided, always return the value +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(x, value!(42, delimited!(tag!("")))); +/// named!(y, delimited!(tag!(""))); +/// let r = x(&b" aaa"[..]); +/// assert_eq!(r, Done(&b" aaa"[..], 42)); +/// +/// let r2 = y(&b" aaa"[..]); +/// assert_eq!(r2, Done(&b" aaa"[..], 42)); +/// # } +/// ``` +#[macro_export] +macro_rules! value ( + ($i:expr, $res:expr, $submac:ident!( $($args:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,_) => { + let res: $crate::IResult<_,_> = $crate::IResult::Done(i, $res); + res + }, + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } + ); + ($i:expr, $res:expr, $f:expr) => ( + value!($i, $res, call!($f)) + ); + ($i:expr, $res:expr) => ( + { + let res: $crate::IResult<_,_> = $crate::IResult::Done($i, $res); + res + } + ); +); + +/// `expr_res!(Result) => I -> IResult` +/// evaluate an expression that returns a Result and returns a IResult::Done(I,T) if Ok +/// +/// See expr_opt for an example +#[macro_export] +macro_rules! expr_res ( + ($i:expr, $e:expr) => ( + { + match $e { + Ok(output) => $crate::IResult::Done($i, output), + Err(_) => $crate::IResult::Error(error_position!($crate::ErrorKind::ExprRes, $i)) + } + } + ); +); + +/// `expr_opt!(Option) => I -> IResult` +/// evaluate an expression that returns a Option and returns a IResult::Done(I,T) if Some +/// +/// Useful when doing computations in a chain +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self, Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::{be_u8,ErrorKind}; +/// +/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> { +/// do_parse!(input, +/// sz: be_u8 >> +/// length: expr_opt!(size.checked_add(sz)) >> // checking for integer overflow (returns an Option) +/// data: take!(length) >> +/// (data) +/// ) +/// } +/// # fn main() { +/// let arr1 = [1, 2, 3, 4, 5]; +/// let r1 = take_add(&arr1[..], 1); +/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..])); +/// +/// let arr2 = [0xFE, 2, 3, 4, 5]; +/// // size is overflowing +/// let r1 = take_add(&arr2[..], 42); +/// assert_eq!(r1, Error(error_position!(ErrorKind::ExprOpt,&[2,3,4,5][..]))); +/// # } +/// ``` +#[macro_export] +macro_rules! expr_opt ( + ($i:expr, $e:expr) => ( + { + match $e { + ::std::option::Option::Some(output) => $crate::IResult::Done($i, output), + ::std::option::Option::None => $crate::IResult::Error(error_position!($crate::ErrorKind::ExprOpt, $i)) + } + } + ); +); + +/// `opt!(I -> IResult) => I -> IResult>` +/// make the underlying parser optional +/// +/// returns an Option of the returned type. This parser returns `Some(result)` if the child parser +/// succeeds,`None` if it fails, and `Incomplete` if it did not have enough data to decide +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!( o<&[u8], Option<&[u8]> >, opt!( tag!( "abcd" ) ) ); +/// +/// let a = b"abcdef"; +/// let b = b"bcdefg"; +/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..]))); +/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], None)); +/// # } +/// ``` +#[macro_export] +macro_rules! opt( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + _ => { + let res: $crate::IResult<_,_> = $crate::IResult::Done($i, ::std::option::Option::None); + res + }, + } + } + ); + ($i:expr, $f:expr) => ( + opt!($i, call!($f)); + ); +); + +/// `opt_res!(I -> IResult) => I -> IResult>` +/// make the underlying parser optional +/// +/// returns a Result, with Err containing the parsing error +/// +/// ```ignore +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!( o<&[u8], Result<&[u8], nom::Err<&[u8]> > >, opt_res!( tag!( "abcd" ) ) ); +/// +/// let a = b"abcdef"; +/// let b = b"bcdefg"; +/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Ok(&b"abcd"[..]))); +/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], Err(error_position!(ErrorKind::Tag, &b[..])))); +/// # } +/// ``` +#[macro_export] +macro_rules! opt_res ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::result::Result::Ok(o)), + $crate::IResult::Error(e) => $crate::IResult::Done($i, ::std::result::Result::Err(e)), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } + ); + ($i:expr, $f:expr) => ( + opt_res!($i, call!($f)); + ); +); + +/// `cond_with_error!(bool, I -> IResult) => I -> IResult>` +/// Conditional combinator +/// +/// Wraps another parser and calls it if the +/// condition is met. This combinator returns +/// an Option of the return type of the child +/// parser. +/// +/// This is especially useful if a parser depends +/// on the value returned by a preceding parser in +/// a `do_parse!`. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::IResult; +/// # fn main() { +/// let b = true; +/// let f: Box IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8], +/// cond!( b, tag!("abcd") )) +/// ); +/// +/// let a = b"abcdef"; +/// assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..]))); +/// +/// let b2 = false; +/// let f2:Box IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8], +/// cond!( b2, tag!("abcd") )) +/// ); +/// assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None)); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! cond_with_error( + ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => ( + { + if $cond { + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)), + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Done($i, ::std::option::Option::None); + res + } + } + ); + ($i:expr, $cond:expr, $f:expr) => ( + cond_with_error!($i, $cond, call!($f)); + ); +); + +/// `cond!(bool, I -> IResult) => I -> IResult>` +/// Conditional combinator +/// +/// Wraps another parser and calls it if the +/// condition is met. This combinator returns +/// an Option of the return type of the child +/// parser. +/// +/// This is especially useful if a parser depends +/// on the value returned by a preceding parser in +/// a `do_parse!`. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::IResult; +/// # fn main() { +/// let b = true; +/// let f: Box IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8], +/// cond!( b, tag!("abcd") )) +/// ); +/// +/// let a = b"abcdef"; +/// assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..]))); +/// +/// let b2 = false; +/// let f2:Box IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8], +/// cond!( b2, tag!("abcd") )) +/// ); +/// assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None)); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! cond( + ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => ( + { + if $cond { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Error(_) => { + let res: $crate::IResult<_,_> = $crate::IResult::Done($i, ::std::option::Option::None); + res + }, + } + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Done($i, ::std::option::Option::None); + res + } + } + ); + ($i:expr, $cond:expr, $f:expr) => ( + cond!($i, $cond, call!($f)); + ); +); + +/// `cond_reduce!(bool, I -> IResult) => I -> IResult` +/// Conditional combinator with error +/// +/// Wraps another parser and calls it if the +/// condition is met. This combinator returns +/// an error if the condition is false +/// +/// This is especially useful if a parser depends +/// on the value returned by a preceding parser in +/// a `do_parse!`. +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done,Error}; +/// # use nom::{Err,ErrorKind}; +/// # fn main() { +/// let b = true; +/// let f = closure!(&'static[u8], +/// cond_reduce!( b, tag!("abcd") ) +/// ); +/// +/// let a = b"abcdef"; +/// assert_eq!(f(&a[..]), Done(&b"ef"[..], &b"abcd"[..])); +/// +/// let b2 = false; +/// let f2 = closure!(&'static[u8], +/// cond_reduce!( b2, tag!("abcd") ) +/// ); +/// assert_eq!(f2(&a[..]), Error(error_position!(ErrorKind::CondReduce, &a[..]))); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! cond_reduce( + ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => ( + { + if $cond { + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } else { + $crate::IResult::Error(error_position!($crate::ErrorKind::CondReduce, $i)) + } + } + ); + ($i:expr, $cond:expr, $f:expr) => ( + cond_reduce!($i, $cond, call!($f)); + ); +); + +/// `peek!(I -> IResult) => I -> IResult` +/// returns a result without consuming the input +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(ptag, peek!( tag!( "abcd" ) ) ); +/// +/// let r = ptag(&b"abcdefgh"[..]); +/// assert_eq!(r, Done(&b"abcdefgh"[..], &b"abcd"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! peek( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(_,o) => $crate::IResult::Done($i, o), + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } + ); + ($i:expr, $f:expr) => ( + peek!($i, call!($f)); + ); +); + +/// `not!(I -> IResult) => I -> IResult` +/// returns a result only if the embedded parser returns Error or Incomplete +/// does not consume the input +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(not_e, do_parse!( +/// res: tag!("abc") >> +/// not!(char!('e')) >> +/// (res) +/// )); +/// +/// let r = not_e(&b"abcd"[..]); +/// assert_eq!(r, Done(&b"d"[..], &b"abc"[..])); +/// +/// let r2 = not_e(&b"abce"[..]); +/// assert_eq!(r2, Error(error_position!(ErrorKind::Not, &b"e"[..]))); +/// # } +/// ``` +#[macro_export] +macro_rules! not( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::Slice; + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(_, _) => $crate::IResult::Error(error_position!($crate::ErrorKind::Not, $i)), + $crate::IResult::Error(_) => $crate::IResult::Done($i, ($i).slice(..0)), + $crate::IResult::Incomplete(_) => $crate::IResult::Done($i, ($i).slice(..0)) + } + } + ); + ($i:expr, $f:expr) => ( + not!($i, call!($f)); + ); +); + +/// `tap!(name: I -> IResult => { block }) => I -> IResult` +/// allows access to the parser's result without affecting it +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use std::str; +/// # fn main() { +/// named!(ptag, tap!(res: tag!( "abcd" ) => { println!("recognized {}", str::from_utf8(res).unwrap()) } ) ); +/// +/// let r = ptag(&b"abcdefgh"[..]); +/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! tap ( + ($i:expr, $name:ident : $submac:ident!( $($args:tt)* ) => $e:expr) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Done(i,o) => { + let $name = o; + $e; + $crate::IResult::Done(i, $name) + }, + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } + ); + ($i:expr, $name: ident: $f:expr => $e:expr) => ( + tap!($i, $name: call!($f) => $e); + ); +); + +/// `eof!()` returns its input if it is at the end of input data +/// +/// please note that for now, eof only means there's no more +/// data available, it does not work yet with smarter input +/// types +#[macro_export] +macro_rules! eof ( + ($i:expr,) => ( + { + use $crate::InputLength; + if ($i).input_len() == 0 { + $crate::IResult::Done($i, $i) + } else { + $crate::IResult::Error(error_position!($crate::ErrorKind::Eof, $i)) + } + } + ); +); + +/// `recognize!(I -> IResult ) => I -> IResult` +/// if the child parser was successful, return the consumed input as produced value +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(x, recognize!(delimited!(tag!("")))); +/// let r = x(&b" aaa"[..]); +/// assert_eq!(r, Done(&b" aaa"[..], &b""[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! recognize ( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::Offset; + use $crate::Slice; + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(i,_) => { + let index = (&$i).offset(&i); + $crate::IResult::Done(i, ($i).slice(..index)) + }, + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) + } + } + ); + ($i:expr, $f:expr) => ( + recognize!($i, call!($f)) + ); +); + + +#[cfg(test)] +mod tests { + use internal::{Needed,IResult}; + #[cfg(feature = "verbose-errors")] + use verbose_errors::Err; + + #[cfg(not(feature = "verbose-errors"))] + use simple_errors::Err; + + use internal::IResult::*; + use util::ErrorKind; + + // reproduce the tag and take macros, because of module import order + macro_rules! tag ( + ($i:expr, $inp: expr) => ( + { + #[inline(always)] + fn as_bytes(b: &T) -> &[u8] { + b.as_bytes() + } + + let expected = $inp; + let bytes = as_bytes(&expected); + + tag_bytes!($i,bytes) + } + ); + ); + + macro_rules! tag_bytes ( + ($i:expr, $bytes: expr) => ( + { + use std::cmp::min; + let len = $i.len(); + let blen = $bytes.len(); + let m = min(len, blen); + let reduced = &$i[..m]; + let b = &$bytes[..m]; + + let res: $crate::IResult<_,_> = if reduced != b { + $crate::IResult::Error(error_position!($crate::ErrorKind::Tag, $i)) + } else if m < blen { + $crate::IResult::Incomplete($crate::Needed::Size(blen)) + } else { + $crate::IResult::Done(&$i[blen..], reduced) + }; + res + } + ); + ); + + macro_rules! take( + ($i:expr, $count:expr) => ( + { + let cnt = $count as usize; + let res:$crate::IResult<&[u8],&[u8]> = if $i.len() < cnt { + $crate::IResult::Incomplete($crate::Needed::Size(cnt)) + } else { + $crate::IResult::Done(&$i[cnt..],&$i[0..cnt]) + }; + res + } + ); + ); + + + mod pub_named_mod { + named!(pub tst, tag!("abcd")); + } + + #[test] + fn pub_named_test() { + let a = &b"abcd"[..]; + let res = pub_named_mod::tst(a); + assert_eq!(res, Done(&b""[..], a)); + } + + #[test] + fn apply_test() { + fn sum2(a:u8, b:u8) -> u8 { a + b } + fn sum3(a:u8, b:u8, c:u8) -> u8 { a + b + c } + let a = apply!(1, sum2, 2); + let b = apply!(1, sum3, 2, 3); + + assert_eq!(a, 3); + assert_eq!(b, 6); + } + + #[test] + fn opt() { + named!(opt_abcd<&[u8],Option<&[u8]> >, opt!(tag!("abcd"))); + + let a = &b"abcdef"[..]; + let b = &b"bcdefg"[..]; + let c = &b"ab"[..]; + assert_eq!(opt_abcd(a), Done(&b"ef"[..], Some(&b"abcd"[..]))); + assert_eq!(opt_abcd(b), Done(&b"bcdefg"[..], None)); + assert_eq!(opt_abcd(c), Incomplete(Needed::Size(4))); + } + + #[cfg(feature = "verbose-errors")] + #[test] + fn opt_res() { + named!(opt_res_abcd<&[u8], Result<&[u8], Err<&[u8]> > >, opt_res!(tag!("abcd"))); + + let a = &b"abcdef"[..]; + let b = &b"bcdefg"[..]; + let c = &b"ab"[..]; + assert_eq!(opt_res_abcd(a), Done(&b"ef"[..], Ok(&b"abcd"[..]))); + assert_eq!(opt_res_abcd(b), Done(&b"bcdefg"[..], Err(error_position!(ErrorKind::Tag, b)))); + assert_eq!(opt_res_abcd(c), Incomplete(Needed::Size(4))); + } + + #[cfg(not(feature = "verbose-errors"))] + #[test] + fn opt_res() { + named!(opt_res_abcd<&[u8], Result<&[u8], Err> >, opt_res!(tag!("abcd"))); + + let a = &b"abcdef"[..]; + let b = &b"bcdefg"[..]; + let c = &b"ab"[..]; + assert_eq!(opt_res_abcd(a), Done(&b"ef"[..], Ok(&b"abcd"[..]))); + assert_eq!(opt_res_abcd(b), Done(&b"bcdefg"[..], Err(error_position!(ErrorKind::Tag, b)))); + assert_eq!(opt_res_abcd(c), Incomplete(Needed::Size(4))); + } + + #[test] + #[cfg(feature = "std")] + fn cond() { + let f_true: Box IResult<&[u8],Option<&[u8]>, &str>> = + Box::new(closure!(&'static [u8], fix_error!(&str, cond!( true, tag!("abcd") ) ))); + let f_false: Box IResult<&[u8],Option<&[u8]>, &str>> = + Box::new(closure!(&'static [u8], fix_error!(&str, cond!( false, tag!("abcd") ) ))); + //let f_false = closure!(&'static [u8], cond!( false, tag!("abcd") ) ); + + assert_eq!(f_true(&b"abcdef"[..]), Done(&b"ef"[..], Some(&b"abcd"[..]))); + assert_eq!(f_true(&b"ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(f_true(&b"xxx"[..]), Done(&b"xxx"[..], None)); + + assert_eq!(f_false(&b"abcdef"[..]), Done(&b"abcdef"[..], None)); + assert_eq!(f_false(&b"ab"[..]), Done(&b"ab"[..], None)); + assert_eq!(f_false(&b"xxx"[..]), Done(&b"xxx"[..], None)); + } + + #[test] + #[cfg(feature = "std")] + fn cond_wrapping() { + // Test that cond!() will wrap a given identifier in the call!() macro. + named!( tag_abcd, tag!("abcd") ); + let f_true: Box IResult<&[u8],Option<&[u8]>, &str>> = + Box::new(closure!(&'static [u8], fix_error!(&str, cond!( true, tag_abcd ) ))); + let f_false: Box IResult<&[u8],Option<&[u8]>, &str>> = + Box::new(closure!(&'static [u8], fix_error!(&str, cond!( false, tag_abcd ) ))); + //let f_false = closure!(&'static [u8], cond!( b2, tag!("abcd") ) ); + + assert_eq!(f_true(&b"abcdef"[..]), Done(&b"ef"[..], Some(&b"abcd"[..]))); + assert_eq!(f_true(&b"ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(f_true(&b"xxx"[..]), Done(&b"xxx"[..], None)); + + assert_eq!(f_false(&b"abcdef"[..]), Done(&b"abcdef"[..], None)); + assert_eq!(f_false(&b"ab"[..]), Done(&b"ab"[..], None)); + assert_eq!(f_false(&b"xxx"[..]), Done(&b"xxx"[..], None)); + } + + #[test] + fn peek() { + named!(peek_tag<&[u8],&[u8]>, peek!(tag!("abcd"))); + + assert_eq!(peek_tag(&b"abcdef"[..]), Done(&b"abcdef"[..], &b"abcd"[..])); + assert_eq!(peek_tag(&b"ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(peek_tag(&b"xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + } + + #[test] + fn not() { + named!(not_aaa, not!(tag!("aaa"))); + assert_eq!(not_aaa(&b"aaa"[..]), Error(error_position!(ErrorKind::Not, &b"aaa"[..]))); + assert_eq!(not_aaa(&b"aa"[..]), Done(&b"aa"[..], &b""[..])); + assert_eq!(not_aaa(&b"abcd"[..]), Done(&b"abcd"[..], &b""[..])); + } + + #[test] + fn verify() { + named!(test, verify!(take!(5), |slice: &[u8]| slice[0] == 'a' as u8)); + assert_eq!(test(&b"bcd"[..]), Incomplete(Needed::Size(5))); + assert_eq!(test(&b"bcdefg"[..]), Error(error_position!(ErrorKind::Verify, &b"bcdefg"[..]))); + assert_eq!(test(&b"abcdefg"[..]), Done(&b"fg"[..], &b"abcde"[..])); + } +} diff --git a/bash-5.1/vendor/nom/src/methods.rs b/bash-5.1/vendor/nom/src/methods.rs new file mode 100644 index 0000000..7bdabfd --- /dev/null +++ b/bash-5.1/vendor/nom/src/methods.rs @@ -0,0 +1,500 @@ +//! Method macro combinators +//! +//! These macros make parsers as methods of structs +//! and that can take methods of structs to call +//! as parsers. +//! +//! There is a trick to make them easier to assemble, +//! combinators are defined like this: +//! +//! ```ignore +//! macro_rules! tag ( +//! ($i:expr, $inp: expr) => ( +//! { +//! ... +//! } +//! ); +//! ); +//! ``` +//! +//! But when used as methods in other combinators, are used +//! like this: +//! +//! ```ignore +//! method!(my_function >, self, tag!("abcd")); +//! ``` +//! +//! Internally, other combinators will rewrite +//! that call to pass the input as second argument: +//! +//! ```ignore +//! macro_rules! method ( +//! ($name:ident<$a:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( +//! fn $name( $self_: $a, i: &[u8] ) -> $crate::IResult<&[u8], &[u8]> { +//! $submac!(i, $($args)*) +//! } +//! ); +//! ); +//! ``` +//! +//! The `method!` macro is similar to the `named!` macro in the macros module. +//! While `named!` will create a parser function, `method!` will create a parser +//! method on the struct it is defined in. +//! +//! Compared to the `named!` macro there are a few differences in how they are +//! invoked. A `method!` invocation always has to have the type of `self` +//! declared and it can't be a reference due to Rust's borrow lifetime +//! restrictions: +//! ```ignore +//! // -`self`'s type- +//! method!(method_name< Parser<'a> >, ...); +//! ``` +//! `self`'s type always comes first. +//! The next difference is you have to input the self struct. Due to Rust's +//! macro hygiene the macro can't declare it on it's own. +//! ```ignore +//! // -self- +//! method!(method_name, &'a str, &'a str>, self, ...); +//! ``` +//! When making a parsing struct with parsing methods, due to the static borrow +//! checker,calling any parsing methods on self (or any other parsing struct) +//! will cause self to be moved for the rest of the method.To get around this +//! restriction all self is moved into the called method and then the called +//! method will return self to the caller. +//! +//! To call a method on self you need to use the `call_m!` macro. For example: +//! ```ignore +//! struct<'a> Parser<'a> { +//! parsed: &'a str, +//! } +//! impl<'a> Parser<'a> { +//! // Constructor omitted for brevity +//! method!(take4, &'a str, &'a str>, self, take!(4)); +//! method!(caller, &'a str, &'a str>, self, call_m!(self.take4)); +//! } +//! ``` +//! More complicated combinations still mostly look the same as their `named!` +//! counterparts: +//! ```ignore +//! method!(pub simple_chain<&mut Parser<'a>, &'a str, &'a str>, self, +//! do_parse!( +//! call_m!(self.tag_abc) >> +//! call_m!(self.tag_def) >> +//! call_m!(self.tag_ghi) >> +//! last: map!(call_m!(self.simple_peek), |parsed| sb.parsed = parsed) >> +//! (last) +//! ) +//! ); +//! ``` +//! The three additions to method definitions to remember are: +//! 1. Specify `self`'s type +//! 2. Pass `self` to the macro +//! 4. Call parser methods using the `call_m!` macro. + +/// Makes a method from a parser combination +/// +/// The must be set up because the compiler needs +/// the information +/// +/// ```ignore +/// method!(my_function >( &[u8] ) -> &[u8], tag!("abcd")); +/// // first type parameter is `self`'s type, second is input, third is output +/// method!(my_function, &[u8], &[u8]>, tag!("abcd")); +/// //prefix them with 'pub' to make the methods public +/// method!(pub my_function,&[u8], &[u8]>, tag!("abcd")); +/// ``` +#[macro_export] +macro_rules! method ( + // Non-public immutable self + ($name:ident<$a:ty>( $i:ty ) -> $o:ty, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( $self_: $a, i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty,$i:ty,$o:ty,$e:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( $self_: $a, i: $i ) -> ($a, $crate::IResult<$i, $o, $e>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty,$i:ty,$o:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( $self_: $a, i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty,$o:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], $o, u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], &[u8], u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + // Public immutable self + (pub $name:ident<$a:ty>( $i:ty ) -> $o:ty, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( $self_: $a, i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty,$i:ty,$o:ty,$e:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( $self_: $a, i: $i ) -> ($a, $crate::IResult<$i, $o, $e>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty,$i:ty,$o:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( $self_: $a,i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty,$o:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], $o, u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty>, $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], &[u8], u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + // Non-public mutable self + ($name:ident<$a:ty>( $i:ty ) -> $o:ty, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( mut $self_: $a, i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty,$i:ty,$o:ty,$e:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( mut $self_: $a, i: $i ) -> ($a, $crate::IResult<$i, $o, $e>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty,$i:ty,$o:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( mut $self_: $a, i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty,$o:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( mut $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], $o, u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + ($name:ident<$a:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( mut $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], &[u8], u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + // Public mutable self + (pub $name:ident<$a:ty>( $i:ty ) -> $o:ty, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( mut $self_: $a, i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty,$i:ty,$o:ty,$e:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + fn $name( mut $self_: $a, i: $i ) -> ($a, $crate::IResult<$i, $o, $e>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty,$i:ty,$o:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( mut $self_: $a,i: $i ) -> ($a, $crate::IResult<$i,$o,u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty,$o:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( mut $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], $o, u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); + (pub $name:ident<$a:ty>, mut $self_:ident, $submac:ident!( $($args:tt)* )) => ( + #[allow(unused_variables)] + pub fn $name( mut $self_: $a, i: &[u8] ) -> ($a, $crate::IResult<&[u8], &[u8], u32>) { + let result = $submac!(i, $($args)*); + ($self_, result) + } + ); +); + +/// Used to called methods then move self back into self +#[macro_export] +macro_rules! call_m ( + ($i:expr, $self_:ident.$method:ident) => ( + { + let (tmp, res) = $self_.$method($i); + $self_ = tmp; + res + } + ); + ($i:expr, $self_:ident.$method:ident, $($args:expr),* ) => ( + { + let (tmp, res) = $self_.$method($i, $($args),*); + $self_ = tmp; + res + } + ); +); + + +/// emulate function currying for method calls on structs +/// `apply_m!(self.my_function, arg1, arg2, ...)` becomes `self.my_function(input, arg1, arg2, ...)` +/// +/// Supports up to 6 arguments +#[macro_export] +macro_rules! apply_m ( + ($i:expr, $self_:ident.$method:ident, $($args:expr),* ) => ( { let (tmp, res) = $self_.$method( $i, $($args),* ); $self_ = tmp; res } ); +); + +#[cfg(test)] +mod tests { + use internal::IResult::*; + + // reproduce the tag_s and take_s macros, because of module import order + macro_rules! tag_s ( + ($i:expr, $tag: expr) => ( + { + let res: $crate::IResult<_,_> = if $tag.len() > $i.len() { + $crate::IResult::Incomplete($crate::Needed::Size($tag.len())) + //} else if &$i[0..$tag.len()] == $tag { + } else if ($i).starts_with($tag) { + $crate::IResult::Done(&$i[$tag.len()..], &$i[0..$tag.len()]) + } else { + $crate::IResult::Error(error_position!($crate::ErrorKind::TagStr, $i)) + }; + res + } + ); + ); + + macro_rules! take_s ( + ($i:expr, $count:expr) => ( + { + let cnt = $count as usize; + let res: $crate::IResult<_,_> = if $i.chars().count() < cnt { + $crate::IResult::Incomplete($crate::Needed::Size(cnt)) + } else { + let mut offset = $i.len(); + let mut count = 0; + for (o, _) in $i.char_indices() { + if count == cnt { + offset = o; + break; + } + count += 1; + } + $crate::IResult::Done(&$i[offset..], &$i[..offset]) + }; + res + } + ); + ); + + struct Parser<'a> { + bcd: &'a str, + } + + impl<'a> Parser<'a> { + pub fn new() -> Parser<'a> { + Parser{bcd: ""} + } + + method!(tag_abc, &'a str, &'a str>, self, tag_s!("áβç")); + method!(tag_bcd >(&'a str) -> &'a str, self, tag_s!("βçδ")); + method!(pub tag_hij >(&'a str) -> &'a str, self, tag_s!("λïJ")); + method!(pub tag_ijk, &'a str, &'a str>, self, tag_s!("ïJƙ")); + method!(take3, &'a str, &'a str>, self, take_s!(3)); + method!(pub simple_call, &'a str, &'a str>, mut self, + call_m!(self.tag_abc) + ); + method!(pub simple_peek, &'a str, &'a str>, mut self, + peek!(call_m!(self.take3)) + ); + method!(pub simple_chain, &'a str, &'a str>, mut self, + do_parse!( + map!(call_m!(self.tag_bcd), |bcd| self.bcd = bcd) >> + last: call_m!(self.simple_peek) >> + (last) + ) + ); + fn tag_stuff(mut self: Parser<'a>, input: &'a str, something: &'a str) -> (Parser<'a>, ::IResult<&'a str, &'a str>) { + self.bcd = something; + let(tmp, res) = self.tag_abc(input); + self = tmp; + (self, res) + } + method!(use_apply, &'a str, &'a str>, mut self, apply_m!(self.tag_stuff, "βçδ")); + } + + #[test] + fn test_method_call_abc() { + let p = Parser::new(); + let input: &str = "áβçδèƒϱλïJƙ"; + let consumed: &str = "áβç"; + let leftover: &str = "δèƒϱλïJƙ"; + let(_, res) = p.tag_abc(input); + match res { + Done(extra, output) => { assert!(extra == leftover, "`Parser.tag_abc` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.tag_abc` doesnt return the string it consumed \ + on success. Expected `{}`, got `{}`.", consumed, output); + }, + other => panic!("`Parser.tag_abc` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + + #[test] + fn test_method_call_bcd() { + let p = Parser::new(); + let input: &str = "βçδèƒϱλïJƙ"; + let consumed: &str = "βçδ"; + let leftover: &str = "èƒϱλïJƙ"; + let(_, res) = p.tag_bcd(input); + match res { + Done(extra, output) => { assert!(extra == leftover, "`Parser.tag_bcd` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.tag_bcd` doesn't return the string it consumed \ + on success. Expected `{}`, got `{}`.", consumed, output); + }, + other => panic!("`Parser.tag_bcd` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + + #[test] + fn test_method_call_hij() { + let p = Parser::new(); + let input: &str = "λïJƙℓ₥ñôƥ9řƨ"; + let consumed: &str = "λïJ"; + let leftover: &str = "ƙℓ₥ñôƥ9řƨ"; + let(_, res) = p.tag_hij(input); + match res { + Done(extra, output) => { assert!(extra == leftover, "`Parser.tag_hij` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.tag_hij` doesn't return the string it consumed \ + on success. Expected `{}`, got `{}`.", consumed, output); + }, + other => panic!("`Parser.tag_hij` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + + #[test] + fn test_method_call_ijk() { + let p = Parser::new(); + let input: &str = "ïJƙℓ₥ñôƥ9řƨ"; + let consumed: &str = "ïJƙ"; + let leftover: &str = "ℓ₥ñôƥ9řƨ"; + let(_, res) = p.tag_ijk(input); + match res { + Done(extra, output) => { assert!(extra == leftover, "`Parser.tag_ijk` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.tag_ijk` doesn't return the string it consumed \ + on success. Expected `{}`, got `{}`.", consumed, output); + }, + other => panic!("`Parser.tag_ijk` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + #[test] + fn test_method_simple_call() { + let p = Parser::new(); + let input: &str = "áβçδèƒϱλïJƙ"; + let consumed: &str = "áβç"; + let leftover: &str = "δèƒϱλïJƙ"; + let(_, res) = p.simple_call(input); + match res { + Done(extra, output) => { assert!(extra == leftover, "`Parser.simple_call` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.simple_call` doesn't return the string it consumed \ + on success. Expected `{}`, got `{}`.", consumed, output); + }, + other => panic!("`Parser.simple_call` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + + #[test] + fn test_apply_m() { + let mut p = Parser::new(); + let input: &str = "áβçδèƒϱλïJƙ"; + let consumed: &str = "áβç"; + let leftover: &str = "δèƒϱλïJƙ"; + let(tmp, res) = p.use_apply(input); + p = tmp; + match res { + Done(extra, output) => { assert!(extra == leftover, "`Parser.use_apply` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.use_apply` doesn't return the string it was supposed to \ + on success. Expected `{}`, got `{}`.", leftover, output); + assert!(p.bcd == "βçδ", "Parser.use_apply didn't modify the parser field correctly: {}", p.bcd); + }, + other => panic!("`Parser.use_apply` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + + #[test] + fn test_method_call_peek() { + let p = Parser::new(); + let input: &str = "ж¥ƺáβçδèƒϱλïJƙ"; + let consumed: &str = "ж¥ƺ"; + let(_, res) = p.simple_peek(input); + match res { + Done(extra, output) => { assert!(extra == input, "`Parser.simple_peek` consumed leftover input. leftover: {}", extra); + assert!(output == consumed, "`Parser.simple_peek` doesn't return the string it consumed \ + on success. Expected `{}`, got `{}`.", consumed, output); + }, + other => panic!("`Parser.simple_peek` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } + + #[test] + fn test_method_call_chain() { + let mut p = Parser::new(); + let input : &str = "βçδδèƒϱλïJƙℓ"; + let leftover : &str = "δèƒϱλïJƙℓ"; + let output : &str = "δèƒ"; + let(tmp, res) = p.simple_chain(input); + p = tmp; + match res { + Done(extra, out) => { assert!(extra == leftover, "`Parser.simple_chain` consumed leftover input. leftover: {}", extra); + assert!(out == output, "`Parser.simple_chain` doesn't return the string it was supposed to \ + on success. Expected `{}`, got `{}`.", output, out); + assert!(p.bcd == "βçδ", "Parser.simple_chain didn't modify the parser field correctly: {}", p.bcd); + }, + other => panic!("`Parser.simple_chain` didn't succeed when it should have. \ + Got `{:?}`.", other), + } + } +} diff --git a/bash-5.1/vendor/nom/src/multi.rs b/bash-5.1/vendor/nom/src/multi.rs new file mode 100644 index 0000000..f42164d --- /dev/null +++ b/bash-5.1/vendor/nom/src/multi.rs @@ -0,0 +1,1614 @@ +//! Parsers for applying parsers multiple times + +/// `separated_list!(I -> IResult, I -> IResult) => I -> IResult>` +/// separated_list(sep, X) returns Vec will return Incomplete if there may be more elements +#[macro_export] +macro_rules! separated_list( + ($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => ( + { + use $crate::InputLength; + + //FIXME: use crate vec + let mut res = ::std::vec::Vec::new(); + let mut input = $i.clone(); + + // get the first element + let input_ = input.clone(); + match $submac!(input_, $($args2)*) { + $crate::IResult::Error(_) => $crate::IResult::Done(input, ::std::vec::Vec::new()), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i,o) => { + if i.input_len() == input.input_len() { + $crate::IResult::Error(error_position!($crate::ErrorKind::SeparatedList,input)) + } else { + res.push(o); + input = i; + + let ret; + + loop { + // get the separator first + let input_ = input.clone(); + match $sep!(input_, $($args)*) { + $crate::IResult::Error(_) => { + ret = $crate::IResult::Done(input, res); + break; + } + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(needed)) => { + let (size,overflowed) = needed.overflowing_add(($i).input_len() - input.input_len()); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i2,_) => { + let i2_len = i2.input_len(); + if i2_len == input.input_len() { + ret = $crate::IResult::Done(input, res); + break; + } + + // get the element next + match $submac!(i2, $($args2)*) { + $crate::IResult::Error(_) => { + ret = $crate::IResult::Done(input, res); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(needed)) => { + let (size,overflowed) = needed.overflowing_add(($i).input_len() - i2_len); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i3,o3) => { + if i3.input_len() == i2_len { + ret = $crate::IResult::Done(input, res); + break; + } + res.push(o3); + input = i3; + } + } + } + } + } + + ret + } + }, + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + separated_list!($i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + separated_list!($i, call!($f), $submac!($($args)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + separated_list!($i, call!($f), call!($g)); + ); +); + +/// `separated_nonempty_list!(I -> IResult, I -> IResult) => I -> IResult>` +/// separated_nonempty_list(sep, X) returns Vec will return Incomplete if there may be more elements +#[macro_export] +macro_rules! separated_nonempty_list( + ($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => ( + { + use $crate::InputLength; + + let mut res = ::std::vec::Vec::new(); + let mut input = $i.clone(); + + // get the first element + let input_ = input.clone(); + match $submac!(input_, $($args2)*) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i,o) => { + if i.input_len() == input.len() { + $crate::IResult::Error(error_position!($crate::ErrorKind::SeparatedNonEmptyList,input)) + } else { + res.push(o); + input = i; + + let ret; + + loop { + // get the separator first + let input_ = input.clone(); + match $sep!(input_, $($args)*) { + $crate::IResult::Error(_) => { + ret = $crate::IResult::Done(input, res); + break; + } + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(needed)) => { + let (size,overflowed) = needed.overflowing_add(($i).input_len() - input.input_len()); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i2,_) => { + let i2_len = i2.input_len(); + if i2_len == input.input_len() { + ret = $crate::IResult::Done(input, res); + break; + } + + // get the element next + match $submac!(i2, $($args2)*) { + $crate::IResult::Error(_) => { + ret = $crate::IResult::Done(input, res); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(needed)) => { + let (size,overflowed) = needed.overflowing_add(($i).input_len() - i2_len); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i3,o3) => { + if i3.input_len() == i2_len { + ret = $crate::IResult::Done(input, res); + break; + } + res.push(o3); + input = i3; + } + } + } + } + } + + ret + } + }, + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + separated_nonempty_list!($i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + separated_nonempty_list!($i, call!($f), $submac!($($args)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + separated_nonempty_list!($i, call!($f), call!($g)); + ); +); + +/// `separated_list_complete!(I -> IResult, I -> IResult) => I -> IResult>` +/// This is equivalent to the `separated_list!` combinator, except that it will return `Error` +/// when either the separator or element subparser returns `Incomplete`. +#[macro_export] +macro_rules! separated_list_complete { + ($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => ({ + separated_list!($i, complete!($sep!($($args)*)), complete!($submac!($($args2)*))) + }); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + separated_list_complete!($i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + separated_list_complete!($i, call!($f), $submac!($($args)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + separated_list_complete!($i, call!($f), call!($g)); + ); +} + +/// `separated_nonempty_list_complete!(I -> IResult, I -> IResult) => I -> IResult>` +/// This is equivalent to the `separated_nonempty_list!` combinator, except that it will return +/// `Error` when either the separator or element subparser returns `Incomplete`. +#[macro_export] +macro_rules! separated_nonempty_list_complete { + ($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => ({ + separated_nonempty_list!($i, complete!($sep!($($args)*)), complete!($submac!($($args2)*))) + }); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + separated_nonempty_list_complete!($i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + separated_nonempty_list_complete!($i, call!($f), $submac!($($args)*)); + ); + ($i:expr, $f:expr, $g:expr) => ( + separated_nonempty_list_complete!($i, call!($f), call!($g)); + ); +} + +/// `many0!(I -> IResult) => I -> IResult>` +/// Applies the parser 0 or more times and returns the list of results in a Vec +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(multi<&[u8], Vec<&[u8]> >, many0!( tag!( "abcd" ) ) ); +/// +/// let a = b"abcdabcdefgh"; +/// let b = b"azerty"; +/// +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res)); +/// assert_eq!(multi(&b[..]), Done(&b"azerty"[..], Vec::new())); +/// # } +/// ``` +/// 0 or more +#[macro_export] +macro_rules! many0( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::InputLength; + + let ret; + let mut res = ::std::vec::Vec::new(); + let mut input = $i.clone(); + + loop { + if input.input_len() == 0 { + ret = $crate::IResult::Done(input, res); + break; + } + + let input_ = input.clone(); + match $submac!(input_, $($args)*) { + $crate::IResult::Error(_) => { + ret = $crate::IResult::Done(input, res); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add(($i).input_len() - input.input_len()); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i, o) => { + // loop trip must always consume (otherwise infinite loops) + if i == input { + ret = $crate::IResult::Error(error_position!($crate::ErrorKind::Many0,input)); + break; + } + + res.push(o); + input = i; + } + } + } + + ret + } + ); + ($i:expr, $f:expr) => ( + many0!($i, call!($f)); + ); +); + +/// `many1!(I -> IResult) => I -> IResult>` +/// Applies the parser 1 or more times and returns the list of results in a Vec +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(multi<&[u8], Vec<&[u8]> >, many1!( tag!( "abcd" ) ) ); +/// +/// let a = b"abcdabcdefgh"; +/// let b = b"azerty"; +/// +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res)); +/// assert_eq!(multi(&b[..]), Error(error_position!(ErrorKind::Many1,&b[..]))); +/// # } +/// ``` +#[macro_export] +macro_rules! many1( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::InputLength; + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(_) => $crate::IResult::Error( + error_position!($crate::ErrorKind::Many1,$i) + ), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i1,o1) => { + if i1.input_len() == 0 { + let mut res = ::std::vec::Vec::new(); + res.push(o1); + $crate::IResult::Done(i1,res) + } else { + + let mut res = ::std::vec::Vec::with_capacity(4); + res.push(o1); + let mut input = i1; + let mut incomplete: ::std::option::Option<$crate::Needed> = + ::std::option::Option::None; + loop { + if input.input_len() == 0 { + break; + } + let input_ = input.clone(); + match $submac!(input_, $($args)*) { + $crate::IResult::Error(_) => { + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + incomplete = ::std::option::Option::Some($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add(($i).input_len() - input.input_len()); + incomplete = ::std::option::Option::Some( + match overflowed { + true => $crate::Needed::Unknown, + false => $crate::Needed::Size(size), + } + ); + break; + }, + $crate::IResult::Done(i, o) => { + if i.input_len() == input.input_len() { + break; + } + res.push(o); + input = i; + } + } + } + + match incomplete { + ::std::option::Option::Some(i) => $crate::IResult::Incomplete(i), + ::std::option::Option::None => $crate::IResult::Done(input, res) + } + } + } + } + } + ); + ($i:expr, $f:expr) => ( + many1!($i, call!($f)); + ); +); + +/// `many_till!(I -> IResult, I -> IResult) => I -> IResult, P)>` +/// Applies the first parser until the second applies. Returns a tuple containing the list +/// of results from the first in a Vec and the result of the second. +/// +/// The first embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(multi<&[u8], (Vec<&[u8]>, &[u8]) >, many_till!( tag!( "abcd" ), tag!( "efgh" ) ) ); +/// +/// let a = b"abcdabcdefghabcd"; +/// let b = b"efghabcd"; +/// let c = b"azerty"; +/// +/// let res_a = (vec![&b"abcd"[..], &b"abcd"[..]], &b"efgh"[..]); +/// let res_b: (Vec<&[u8]>, &[u8]) = (Vec::new(), &b"efgh"[..]); +/// assert_eq!(multi(&a[..]), Done(&b"abcd"[..], res_a)); +/// assert_eq!(multi(&b[..]), Done(&b"abcd"[..], res_b)); +/// assert_eq!(multi(&c[..]), Error(error_node_position!(ErrorKind::ManyTill,&c[..],error_position!(ErrorKind::Tag,&c[..])))); +/// # } +/// ``` +#[macro_export] +macro_rules! many_till( + ($i:expr, $submac1:ident!( $($args1:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + use $crate::InputLength; + + let ret; + let mut res = ::std::vec::Vec::new(); + let mut input = $i.clone(); + + loop { + match $submac2!(input, $($args2)*) { + $crate::IResult::Done(i, o) => { + ret = $crate::IResult::Done(i, (res, o)); + break; + }, + _ => { + match $submac1!(input, $($args1)*) { + $crate::IResult::Error(err) => { + ret = $crate::IResult::Error(error_node_position!($crate::ErrorKind::ManyTill,input, err)); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add(($i).input_len() - input.input_len()); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i, o) => { + // loop trip must always consume (otherwise infinite loops) + if i == input { + ret = $crate::IResult::Error(error_position!($crate::ErrorKind::ManyTill,input)); + break; + } + + res.push(o); + input = i; + }, + } + }, + } + } + + ret + } + ); + ($i:expr, $f:expr, $g: expr) => ( + many_till!($i, call!($f), call!($g)); + ); +); + +/// `many_m_n!(usize, usize, I -> IResult) => I -> IResult>` +/// Applies the parser between m and n times (n included) and returns the list of +/// results in a Vec +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(multi<&[u8], Vec<&[u8]> >, many_m_n!(2, 4, tag!( "abcd" ) ) ); +/// +/// let a = b"abcdefgh"; +/// let b = b"abcdabcdefgh"; +/// let c = b"abcdabcdabcdabcdabcdefgh"; +/// +/// assert_eq!(multi(&a[..]),Error(error_position!(ErrorKind::ManyMN,&a[..]))); +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&b[..]), Done(&b"efgh"[..], res)); +/// let res2 = vec![&b"abcd"[..], &b"abcd"[..], &b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&c[..]), Done(&b"abcdefgh"[..], res2)); +/// # } +/// ``` +#[macro_export] +macro_rules! many_m_n( + ($i:expr, $m:expr, $n: expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::InputLength; + let mut res = ::std::vec::Vec::with_capacity($m); + let mut input = $i.clone(); + let mut count: usize = 0; + let mut err = false; + let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None; + loop { + if count == $n { break } + let i_ = input.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Done(i, o) => { + // do not allow parsers that do not consume input (causes infinite loops) + if i.input_len() == input.input_len() { + break; + } + res.push(o); + input = i; + count += 1; + } + $crate::IResult::Error(_) => { + err = true; + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + incomplete = ::std::option::Option::Some($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add($i.input_len() - input.input_len()); + incomplete = ::std::option::Option::Some( + match overflowed { + true => $crate::Needed::Unknown, + false => $crate::Needed::Size(size), + } + ); + break; + }, + } + if input.input_len() == 0 { + break; + } + } + + if count < $m { + if err { + $crate::IResult::Error(error_position!($crate::ErrorKind::ManyMN,$i)) + } else { + match incomplete { + ::std::option::Option::Some(i) => $crate::IResult::Incomplete(i), + ::std::option::Option::None => $crate::IResult::Incomplete( + $crate::Needed::Unknown + ) + } + } + } else { + match incomplete { + ::std::option::Option::Some(i) => $crate::IResult::Incomplete(i), + ::std::option::Option::None => $crate::IResult::Done(input, res) + } + } + } + ); + ($i:expr, $m:expr, $n: expr, $f:expr) => ( + many_m_n!($i, $m, $n, call!($f)); + ); +); + +/// `count!(I -> IResult, nb) => I -> IResult>` +/// Applies the child parser a specified number of times +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done,Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(counter< Vec<&[u8]> >, count!( tag!( "abcd" ), 2 ) ); +/// +/// let a = b"abcdabcdabcdef"; +/// let b = b"abcdefgh"; +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// +/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res)); +/// assert_eq!(counter(&b[..]), Error(error_position!(ErrorKind::Count, &b[..]))); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! count( + ($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => ( + { + let ret: $crate::IResult<_,_>; + let mut input = $i.clone(); + let mut res = ::std::vec::Vec::new(); + + loop { + if res.len() == $count { + ret = $crate::IResult::Done(input, res); + break; + } + + let input_ = input.clone(); + match $submac!(input_, $($args)*) { + $crate::IResult::Done(i,o) => { + res.push(o); + input = i; + }, + $crate::IResult::Error(_) => { + ret = $crate::IResult::Error(error_position!($crate::ErrorKind::Count,$i)); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + } + $crate::IResult::Incomplete($crate::Needed::Size(sz)) => { + let (size,overflowed) = sz.overflowing_add( + $crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&input) + ); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + } + } + } + + ret + } + ); + ($i:expr, $f:expr, $count: expr) => ( + count!($i, call!($f), $count); + ); +); + +/// `count_fixed!(O, I -> IResult, nb) => I -> IResult` +/// Applies the child parser a fixed number of times and returns a fixed size array +/// The type must be specified and it must be `Copy` +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done,Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) ); +/// // can omit the type specifier if returning slices +/// // named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) ); +/// +/// let a = b"abcdabcdabcdef"; +/// let b = b"abcdefgh"; +/// let res = [&b"abcd"[..], &b"abcd"[..]]; +/// +/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res)); +/// assert_eq!(counter(&b[..]), Error(error_position!(ErrorKind::Count, &b[..]))); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! count_fixed ( + ($i:expr, $typ:ty, $submac:ident!( $($args:tt)* ), $count: expr) => ( + { + let ret; + let mut input = $i.clone(); + // `$typ` must be Copy, and thus having no destructor, this is panic safe + let mut res: [$typ; $count] = unsafe{[::std::mem::uninitialized(); $count as usize]}; + let mut cnt: usize = 0; + + loop { + if cnt == $count { + ret = $crate::IResult::Done(input, res); break; + } + + match $submac!(input, $($args)*) { + $crate::IResult::Done(i,o) => { + res[cnt] = o; + cnt += 1; + input = i; + }, + $crate::IResult::Error(_) => { + ret = $crate::IResult::Error(error_position!($crate::ErrorKind::Count,$i)); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + } + $crate::IResult::Incomplete($crate::Needed::Size(sz)) => { + let (size,overflowed) = sz.overflowing_add( + $crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&input) + ); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + } + } + } + + ret + } +); + ($i:expr, $typ: ty, $f:ident, $count: expr) => ( + count_fixed!($i, $typ, call!($f), $count); + ); +); + +/// `length_count!(I -> IResult, I -> IResult) => I -> IResult>` +/// gets a number from the first parser, then applies the second parser that many times +#[macro_export] +macro_rules! length_count( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i, o) => { + match count!(i, $submac2!($($args2)*), o as usize) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(n)) => { + let (size,overflowed) = n.overflowing_add( + $crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i) + ); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + } + }, + $crate::IResult::Done(i2, o2) => $crate::IResult::Done(i2, o2) + } + } + } + } + ); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + length_count!($i, $submac!($($args)*), call!($g)); + ); + + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + length_count!($i, call!($f), $submac!($($args)*)); + ); + + ($i:expr, $f:expr, $g:expr) => ( + length_count!($i, call!($f), call!($g)); + ); +); + +/// `length_data!(I -> IResult) => O` +/// +/// `length_data` gets a number from the first parser, than takes a subslice of the input +/// of that size, and returns that subslice +#[macro_export] +macro_rules! length_data( + ($i:expr, $submac:ident!( $($args:tt)* )) => ( + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i, o) => { + match take!(i, o as usize) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(n)) => { + let (size,overflowed) = n.overflowing_add( + $crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i) + ); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + } + }, + $crate::IResult::Done(i2, o2) => $crate::IResult::Done(i2, o2) + } + } + } + ); + + ($i:expr, $f:expr) => ( + length_data!($i, call!($f)); + ); +); + +/// `length_value!(I -> IResult, I -> IResult) => I -> IResult>` +/// gets a number from the first parser, takes a subslice of the input of that size, +/// then applies the second parser on that subslice. If the second parser returns +/// `Incomplete`, `length_value` will return an error +#[macro_export] +macro_rules! length_value( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i, o) => { + match take!(i, o as usize) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(n)) => { + let (size,overflowed) = n.overflowing_add( + $crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i) + ); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + } + }, + $crate::IResult::Done(i2, o2) => { + match complete!(o2, $submac2!($($args2)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(_, o3) => $crate::IResult::Done(i2, o3) + } + } + } + } + } + } + ); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + length_value!($i, $submac!($($args)*), call!($g)); + ); + + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + length_value!($i, call!($f), $submac!($($args)*)); + ); + + ($i:expr, $f:expr, $g:expr) => ( + length_value!($i, call!($f), call!($g)); + ); +); + +/// `fold_many0!(I -> IResult, R, Fn(R, O) -> R) => I -> IResult` +/// Applies the parser 0 or more times and folds the list of return values +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(multi<&[u8], Vec<&[u8]> >, +/// fold_many0!( tag!( "abcd" ), Vec::new(), |mut acc: Vec<_>, item| { +/// acc.push(item); +/// acc +/// })); +/// +/// let a = b"abcdabcdefgh"; +/// let b = b"azerty"; +/// +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res)); +/// assert_eq!(multi(&b[..]), Done(&b"azerty"[..], Vec::new())); +/// # } +/// ``` +/// 0 or more +#[macro_export] +macro_rules! fold_many0( + ($i:expr, $submac:ident!( $($args:tt)* ), $init:expr, $f:expr) => ( + { + use $crate::InputLength; + let ret; + let f = $f; + let mut res = $init; + let mut input = $i.clone(); + + loop { + if input.input_len() == 0 { + ret = $crate::IResult::Done(input, res); + break; + } + + match $submac!(input, $($args)*) { + $crate::IResult::Error(_) => { + ret = $crate::IResult::Done(input, res); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + ret = $crate::IResult::Incomplete($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add( ($i).input_len() - input.input_len() ); + ret = match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(size)), + }; + break; + }, + $crate::IResult::Done(i, o) => { + // loop trip must always consume (otherwise infinite loops) + if i == input { + ret = $crate::IResult::Error( + error_position!($crate::ErrorKind::Many0,input) + ); + break; + } + + res = f(res, o); + input = i; + } + } + } + + ret + } + ); + ($i:expr, $f:expr, $init:expr, $fold_f:expr) => ( + fold_many0!($i, call!($f), $init, $fold_f); + ); +); + +/// `fold_many1!(I -> IResult, R, Fn(R, O) -> R) => I -> IResult` +/// Applies the parser 1 or more times and folds the list of return values +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(multi<&[u8], Vec<&[u8]> >, +/// fold_many1!( tag!( "abcd" ), Vec::new(), |mut acc: Vec<_>, item| { +/// acc.push(item); +/// acc +/// })); +/// +/// let a = b"abcdabcdefgh"; +/// let b = b"azerty"; +/// +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res)); +/// assert_eq!(multi(&b[..]), Error(error_position!(ErrorKind::Many1,&b[..]))); +/// # } +/// ``` +#[macro_export] +macro_rules! fold_many1( + ($i:expr, $submac:ident!( $($args:tt)* ), $init:expr, $f:expr) => ( + { + use $crate::InputLength; + match $submac!($i, $($args)*) { + $crate::IResult::Error(_) => $crate::IResult::Error( + error_position!($crate::ErrorKind::Many1,$i) + ), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i1,o1) => { + let acc = $init; + let f = $f; + if i1.input_len() == 0 { + let acc = f(acc, o1); + $crate::IResult::Done(i1,acc) + } else { + let mut acc = f(acc, o1); + let mut input = i1; + let mut incomplete: ::std::option::Option<$crate::Needed> = + ::std::option::Option::None; + loop { + if input.input_len() == 0 { + break; + } + match $submac!(input, $($args)*) { + $crate::IResult::Error(_) => { + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + incomplete = ::std::option::Option::Some($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add( ($i).input_len() - input.input_len() ); + incomplete = ::std::option::Option::Some( + match overflowed { + true => $crate::Needed::Unknown, + false => $crate::Needed::Size(size), + } + ); + break; + }, + $crate::IResult::Done(i, o) => { + if i.input_len() == input.input_len() { + break; + } + acc = f(acc, o); + input = i; + } + } + } + + match incomplete { + ::std::option::Option::Some(i) => $crate::IResult::Incomplete(i), + ::std::option::Option::None => $crate::IResult::Done(input, acc) + } + } + } + } + } + ); + ($i:expr, $f:expr, $init:expr, $fold_f:expr) => ( + fold_many1!($i, call!($f), $init, $fold_f); + ); +); + +/// `fold_many_m_n!(usize, usize, I -> IResult, R, Fn(R, O) -> R) => I -> IResult` +/// Applies the parser between m and n times (n included) and folds the list of return value +/// +/// the embedded parser may return Incomplete +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # fn main() { +/// named!(multi<&[u8], Vec<&[u8]> >, +/// fold_many_m_n!(2, 4, tag!( "abcd" ), Vec::new(), |mut acc: Vec<_>, item| { +/// acc.push(item); +/// acc +/// })); +/// +/// let a = b"abcdefgh"; +/// let b = b"abcdabcdefgh"; +/// let c = b"abcdabcdabcdabcdabcdefgh"; +/// +/// assert_eq!(multi(&a[..]),Error(error_position!(ErrorKind::ManyMN,&a[..]))); +/// let res = vec![&b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&b[..]), Done(&b"efgh"[..], res)); +/// let res2 = vec![&b"abcd"[..], &b"abcd"[..], &b"abcd"[..], &b"abcd"[..]]; +/// assert_eq!(multi(&c[..]), Done(&b"abcdefgh"[..], res2)); +/// # } +/// ``` +#[macro_export] +macro_rules! fold_many_m_n( + ($i:expr, $m:expr, $n: expr, $submac:ident!( $($args:tt)* ), $init:expr, $f:expr) => ( + { + use $crate::InputLength; + let mut acc = $init; + let f = $f; + let mut input = $i.clone(); + let mut count: usize = 0; + let mut err = false; + let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None; + loop { + if count == $n { break } + match $submac!(input, $($args)*) { + $crate::IResult::Done(i, o) => { + // do not allow parsers that do not consume input (causes infinite loops) + if i.input_len() == input.input_len() { + break; + } + acc = f(acc, o); + input = i; + count += 1; + } + $crate::IResult::Error(_) => { + err = true; + break; + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => { + incomplete = ::std::option::Option::Some($crate::Needed::Unknown); + break; + }, + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (size,overflowed) = i.overflowing_add( ($i).input_len() - input.input_len() ); + incomplete = ::std::option::Option::Some( + match overflowed { + true => $crate::Needed::Unknown, + false => $crate::Needed::Size(size), + } + ); + break; + }, + } + if input.input_len() == 0 { + break; + } + } + + if count < $m { + if err { + $crate::IResult::Error(error_position!($crate::ErrorKind::ManyMN,$i)) + } else { + match incomplete { + ::std::option::Option::Some(i) => $crate::IResult::Incomplete(i), + ::std::option::Option::None => $crate::IResult::Incomplete($crate::Needed::Unknown) + } + } + } else { + match incomplete { + ::std::option::Option::Some(i) => $crate::IResult::Incomplete(i), + ::std::option::Option::None => $crate::IResult::Done(input, acc) + } + } + } + ); + ($i:expr, $m:expr, $n: expr, $f:expr, $init:expr, $fold_f:expr) => ( + fold_many_m_n!($i, $m, $n, call!($f), $init, $fold_f); + ); +); + +#[cfg(test)] +mod tests { + use internal::{Needed,IResult}; + + use internal::IResult::*; + use util::ErrorKind; + use nom::{alpha,be_u8,be_u16,le_u16,digit}; + use std::str::{self,FromStr}; + + // reproduce the tag and take macros, because of module import order + macro_rules! tag ( + ($i:expr, $inp: expr) => ( + { + #[inline(always)] + fn as_bytes(b: &T) -> &[u8] { + b.as_bytes() + } + + let expected = $inp; + let bytes = as_bytes(&expected); + + tag_bytes!($i,bytes) + } + ); + ); + + macro_rules! tag_bytes ( + ($i:expr, $bytes: expr) => ( + { + use std::cmp::min; + let len = $i.len(); + let blen = $bytes.len(); + let m = min(len, blen); + let reduced = &$i[..m]; + let b = &$bytes[..m]; + + let res: $crate::IResult<_,_> = if reduced != b { + $crate::IResult::Error(error_position!($crate::ErrorKind::Tag, $i)) + } else if m < blen { + $crate::IResult::Incomplete($crate::Needed::Size(blen)) + } else { + $crate::IResult::Done(&$i[blen..], reduced) + }; + res + } + ); + ); + + macro_rules! take( + ($i:expr, $count:expr) => ( + { + let cnt = $count as usize; + let res:$crate::IResult<&[u8],&[u8]> = if $i.len() < cnt { + $crate::IResult::Incomplete($crate::Needed::Size(cnt)) + } else { + $crate::IResult::Done(&$i[cnt..],&$i[0..cnt]) + }; + res + } + ) + ); + + #[test] + #[cfg(feature = "std")] + fn separated_list() { + named!(multi<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("abcd"))); + named!(multi_empty<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!(""))); + named!(multi_longsep<&[u8],Vec<&[u8]> >, separated_list!(tag!(".."), tag!("abcd"))); + + let a = &b"abcdef"[..]; + let b = &b"abcd,abcdef"[..]; + let c = &b"azerty"[..]; + let d = &b",,abc"[..]; + let e = &b"abcd,abcd,ef"[..]; + let f = &b"abc"[..]; + let g = &b"abcd."[..]; + let h = &b"abcd,abc"[..]; + + let res1 = vec![&b"abcd"[..]]; + assert_eq!(multi(a), Done(&b"ef"[..], res1)); + let res2 = vec![&b"abcd"[..], &b"abcd"[..]]; + assert_eq!(multi(b), Done(&b"ef"[..], res2)); + assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new())); + assert_eq!(multi_empty(d), Error(error_position!(ErrorKind::SeparatedList, d))); + //let res3 = vec![&b""[..], &b""[..], &b""[..]]; + //assert_eq!(multi_empty(d), Done(&b"abc"[..], res3)); + let res4 = vec![&b"abcd"[..], &b"abcd"[..]]; + assert_eq!(multi(e), Done(&b",ef"[..], res4)); + + assert_eq!(multi(f), Incomplete(Needed::Size(4))); + assert_eq!(multi_longsep(g), Incomplete(Needed::Size(6))); + assert_eq!(multi(h), Incomplete(Needed::Size(9))); + } + + #[test] + #[cfg(feature = "std")] + fn separated_list_complete() { + named!(multi<&[u8],Vec<&[u8]> >, separated_list_complete!(tag!(","), alpha)); + let a = &b"abcdef"[..]; + let b = &b"abcd,abcdef"[..]; + let c = &b"abcd,abcd,ef"[..]; + let d = &b"abc."[..]; + let e = &b"abcd,ef."[..]; + let f = &b"123"[..]; + + assert_eq!(multi(a), Done(&b""[..], vec!(a))); + assert_eq!(multi(b), Done(&b""[..], vec!(&b"abcd"[..], &b"abcdef"[..]))); + assert_eq!(multi(c), Done(&b""[..], vec!(&b"abcd"[..], &b"abcd"[..], &b"ef"[..]))); + assert_eq!(multi(d), Done(&b"."[..], vec!(&b"abc"[..]))); + assert_eq!(multi(e), Done(&b"."[..], vec!(&b"abcd"[..], &b"ef"[..]))); + assert_eq!(multi(f), Done(&b"123"[..], Vec::new())); + } + + + #[test] + #[cfg(feature = "std")] + fn separated_nonempty_list() { + named!(multi<&[u8],Vec<&[u8]> >, separated_nonempty_list!(tag!(","), tag!("abcd"))); + named!(multi_longsep<&[u8],Vec<&[u8]> >, separated_nonempty_list!(tag!(".."), tag!("abcd"))); + + let a = &b"abcdef"[..]; + let b = &b"abcd,abcdef"[..]; + let c = &b"azerty"[..]; + let d = &b"abcd,abcd,ef"[..]; + + let f = &b"abc"[..]; + let g = &b"abcd."[..]; + let h = &b"abcd,abc"[..]; + + let res1 = vec![&b"abcd"[..]]; + assert_eq!(multi(a), Done(&b"ef"[..], res1)); + let res2 = vec![&b"abcd"[..], &b"abcd"[..]]; + assert_eq!(multi(b), Done(&b"ef"[..], res2)); + assert_eq!(multi(c), Error(error_position!(ErrorKind::Tag,c))); + let res3 = vec![&b"abcd"[..], &b"abcd"[..]]; + assert_eq!(multi(d), Done(&b",ef"[..], res3)); + + assert_eq!(multi(f), Incomplete(Needed::Size(4))); + assert_eq!(multi_longsep(g), Incomplete(Needed::Size(6))); + assert_eq!(multi(h), Incomplete(Needed::Size(9))); + } + + #[test] + #[cfg(feature = "std")] + fn separated_nonempty_list_complete() { + named!(multi<&[u8],Vec<&[u8]> >, separated_nonempty_list_complete!(tag!(","), alpha)); + let a = &b"abcdef"[..]; + let b = &b"abcd,abcdef"[..]; + let c = &b"abcd,abcd,ef"[..]; + let d = &b"abc."[..]; + let e = &b"abcd,ef."[..]; + let f = &b"123"[..]; + + assert_eq!(multi(a), Done(&b""[..], vec!(a))); + assert_eq!(multi(b), Done(&b""[..], vec!(&b"abcd"[..], &b"abcdef"[..]))); + assert_eq!(multi(c), Done(&b""[..], vec!(&b"abcd"[..], &b"abcd"[..], &b"ef"[..]))); + assert_eq!(multi(d), Done(&b"."[..], vec!(&b"abc"[..]))); + assert_eq!(multi(e), Done(&b"."[..], vec!(&b"abcd"[..], &b"ef"[..]))); + assert_eq!(multi(f), Error(error_position!(ErrorKind::Alpha, &b"123"[..]))); + } + + + #[test] + #[cfg(feature = "std")] + fn many0() { + named!( tag_abcd, tag!("abcd") ); + named!( tag_empty, tag!("") ); + named!( multi<&[u8],Vec<&[u8]> >, many0!(tag_abcd) ); + named!( multi_empty<&[u8],Vec<&[u8]> >, many0!(tag_empty) ); + + assert_eq!(multi(&b"abcdef"[..]), Done(&b"ef"[..], vec![&b"abcd"[..]])); + assert_eq!(multi(&b"abcdabcdefgh"[..]), Done(&b"efgh"[..], vec![&b"abcd"[..], &b"abcd"[..]])); + assert_eq!(multi(&b"azerty"[..]), Done(&b"azerty"[..], Vec::new())); + assert_eq!(multi(&b"abcdab"[..]), Incomplete(Needed::Size(8))); + assert_eq!(multi(&b"abcd"[..]), Done(&b""[..], vec![&b"abcd"[..]])); + assert_eq!(multi(&b""[..]), Done(&b""[..], Vec::new())); + assert_eq!(multi_empty(&b"abcdef"[..]), Error(error_position!(ErrorKind::Many0, &b"abcdef"[..]))); + } + + #[cfg(feature = "nightly")] + use test::Bencher; + + #[cfg(feature = "nightly")] + #[bench] + fn many0_bench(b: &mut Bencher) { + named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd"))); + b.iter(|| { + multi(&b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"[..]) + }); + } + + #[test] + #[cfg(feature = "std")] + fn many1() { + named!(multi<&[u8],Vec<&[u8]> >, many1!(tag!("abcd"))); + + let a = &b"abcdef"[..]; + let b = &b"abcdabcdefgh"[..]; + let c = &b"azerty"[..]; + let d = &b"abcdab"[..]; + + let res1 = vec![&b"abcd"[..]]; + assert_eq!(multi(a), Done(&b"ef"[..], res1)); + let res2 = vec![&b"abcd"[..], &b"abcd"[..]]; + assert_eq!(multi(b), Done(&b"efgh"[..], res2)); + assert_eq!(multi(c), Error(error_position!(ErrorKind::Many1,c))); + assert_eq!(multi(d), Incomplete(Needed::Size(8))); + } + + #[test] + #[cfg(feature = "std")] + fn many_till() { + named!(multi<&[u8], (Vec<&[u8]>, &[u8]) >, many_till!( tag!( "abcd" ), tag!( "efgh" ) ) ); + + let a = b"abcdabcdefghabcd"; + let b = b"efghabcd"; + let c = b"azerty"; + + let res_a = (vec![&b"abcd"[..], &b"abcd"[..]], &b"efgh"[..]); + let res_b: (Vec<&[u8]>, &[u8]) = (Vec::new(), &b"efgh"[..]); + assert_eq!(multi(&a[..]), Done(&b"abcd"[..], res_a)); + assert_eq!(multi(&b[..]), Done(&b"abcd"[..], res_b)); + assert_eq!(multi(&c[..]), Error(error_node_position!(ErrorKind::ManyTill,&c[..], error_position!(ErrorKind::Tag,&c[..])))); + } + + #[test] + #[cfg(feature = "std")] + fn infinite_many() { + fn tst(input: &[u8]) -> IResult<&[u8], &[u8]> { + println!("input: {:?}", input); + Error(error_position!(ErrorKind::Custom(0),input)) + } + + // should not go into an infinite loop + named!(multi0<&[u8],Vec<&[u8]> >, many0!(tst)); + let a = &b"abcdef"[..]; + assert_eq!(multi0(a), Done(a, Vec::new())); + + named!(multi1<&[u8],Vec<&[u8]> >, many1!(tst)); + let a = &b"abcdef"[..]; + assert_eq!(multi1(a), Error(error_position!(ErrorKind::Many1,a))); + } + + #[test] + #[cfg(feature = "std")] + fn many_m_n() { + named!(multi<&[u8],Vec<&[u8]> >, many_m_n!(2, 4, tag!("Abcd"))); + + let a = &b"Abcdef"[..]; + let b = &b"AbcdAbcdefgh"[..]; + let c = &b"AbcdAbcdAbcdAbcdefgh"[..]; + let d = &b"AbcdAbcdAbcdAbcdAbcdefgh"[..]; + let e = &b"AbcdAb"[..]; + + assert_eq!(multi(a), Error(error_position!(ErrorKind::ManyMN,a))); + let res1 = vec![&b"Abcd"[..], &b"Abcd"[..]]; + assert_eq!(multi(b), Done(&b"efgh"[..], res1)); + let res2 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]]; + assert_eq!(multi(c), Done(&b"efgh"[..], res2)); + let res3 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]]; + assert_eq!(multi(d), Done(&b"Abcdefgh"[..], res3)); + assert_eq!(multi(e), Incomplete(Needed::Size(8))); + } + + #[test] + #[cfg(feature = "std")] + fn count() { + const TIMES: usize = 2; + named!( tag_abc, tag!("abc") ); + named!( cnt_2<&[u8], Vec<&[u8]> >, count!(tag_abc, TIMES ) ); + + assert_eq!(cnt_2(&b"abcabcabcdef"[..]), Done(&b"abcdef"[..], vec![&b"abc"[..], &b"abc"[..]])); + assert_eq!(cnt_2(&b"ab"[..]), Incomplete(Needed::Size(3))); + assert_eq!(cnt_2(&b"abcab"[..]), Incomplete(Needed::Size(6))); + assert_eq!(cnt_2(&b"xxx"[..]), Error(error_position!(ErrorKind::Count, &b"xxx"[..]))); + assert_eq!(cnt_2(&b"xxxabcabcdef"[..]), Error(error_position!(ErrorKind::Count, &b"xxxabcabcdef"[..]))); + assert_eq!(cnt_2(&b"abcxxxabcdef"[..]), Error(error_position!(ErrorKind::Count, &b"abcxxxabcdef"[..]))); + } + + #[test] + #[cfg(feature = "std")] + fn count_zero() { + const TIMES: usize = 0; + named!( tag_abc, tag!("abc") ); + named!( counter_2<&[u8], Vec<&[u8]> >, count!(tag_abc, TIMES ) ); + + let done = &b"abcabcabcdef"[..]; + let parsed_done = Vec::new(); + let rest = done; + let incomplete_1 = &b"ab"[..]; + let parsed_incompl_1 = Vec::new(); + let incomplete_2 = &b"abcab"[..]; + let parsed_incompl_2 = Vec::new(); + let error = &b"xxx"[..]; + let error_remain = &b"xxx"[..]; + let parsed_err = Vec::new(); + let error_1 = &b"xxxabcabcdef"[..]; + let parsed_err_1 = Vec::new(); + let error_1_remain = &b"xxxabcabcdef"[..]; + let error_2 = &b"abcxxxabcdef"[..]; + let parsed_err_2 = Vec::new(); + let error_2_remain = &b"abcxxxabcdef"[..]; + + assert_eq!(counter_2(done), Done(rest, parsed_done)); + assert_eq!(counter_2(incomplete_1), Done(incomplete_1, parsed_incompl_1)); + assert_eq!(counter_2(incomplete_2), Done(incomplete_2, parsed_incompl_2)); + assert_eq!(counter_2(error), Done(error_remain, parsed_err)); + assert_eq!(counter_2(error_1), Done(error_1_remain, parsed_err_1)); + assert_eq!(counter_2(error_2), Done(error_2_remain, parsed_err_2)); + } + + #[test] + fn count_fixed() { + const TIMES: usize = 2; + named!( tag_abc, tag!("abc") ); + named!( cnt_2<&[u8], [&[u8]; TIMES] >, count_fixed!(&[u8], tag_abc, TIMES ) ); + + assert_eq!(cnt_2(&b"abcabcabcdef"[..]), Done(&b"abcdef"[..], [&b"abc"[..], &b"abc"[..]])); + assert_eq!(cnt_2(&b"ab"[..]), Incomplete(Needed::Size(3))); + assert_eq!(cnt_2(&b"abcab"[..]), Incomplete(Needed::Size(6))); + assert_eq!(cnt_2(&b"xxx"[..]), Error(error_position!(ErrorKind::Count, &b"xxx"[..]))); + assert_eq!(cnt_2(&b"xxxabcabcdef"[..]), Error(error_position!(ErrorKind::Count, &b"xxxabcabcdef"[..]))); + assert_eq!(cnt_2(&b"abcxxxabcdef"[..]), Error(error_position!(ErrorKind::Count, &b"abcxxxabcdef"[..]))); + } + + #[allow(dead_code)] + pub fn compile_count_fixed(input: &[u8]) -> IResult<&[u8], ()> { + do_parse!(input, + tag!("abcd") >> + count_fixed!( u16, le_u16, 4 ) >> + eof!() >> + () + ) + } + + #[allow(unused_variables)] + #[test] + fn count_fixed_no_type() { + const TIMES: usize = 2; + named!( tag_abc, tag!("abc") ); + named!( counter_2<&[u8], [&[u8]; TIMES], () >, count_fixed!(&[u8], tag_abc, TIMES ) ); + + let done = &b"abcabcabcdef"[..]; + let parsed_main = [&b"abc"[..], &b"abc"[..]]; + let rest = &b"abcdef"[..]; + let incomplete_1 = &b"ab"[..]; + let incomplete_2 = &b"abcab"[..]; + let error = &b"xxx"[..]; + let error_1 = &b"xxxabcabcdef"[..]; + let error_1_remain = &b"xxxabcabcdef"[..]; + let error_2 = &b"abcxxxabcdef"[..]; + let error_2_remain = &b"abcxxxabcdef"[..]; + + assert_eq!(counter_2(done), Done(rest, parsed_main)); + assert_eq!(counter_2(incomplete_1), Incomplete(Needed::Size(3))); + assert_eq!(counter_2(incomplete_2), Incomplete(Needed::Size(6))); + assert_eq!(counter_2(error), Error(error_position!(ErrorKind::Count, error))); + assert_eq!(counter_2(error_1), Error(error_position!(ErrorKind::Count, error_1_remain))); + assert_eq!(counter_2(error_2), Error(error_position!(ErrorKind::Count, error_2_remain))); + } + + named!(pub number, map_res!( + map_res!( + digit, + str::from_utf8 + ), + FromStr::from_str + )); + + #[test] + #[cfg(feature = "std")] + fn length_count() { + named!(tag_abc, tag!(&b"abc"[..]) ); + named!( cnt<&[u8], Vec<&[u8]> >, length_count!(number, tag_abc) ); + + assert_eq!(cnt(&b"2abcabcabcdef"[..]), Done(&b"abcdef"[..], vec![&b"abc"[..], &b"abc"[..]])); + assert_eq!(cnt(&b"2ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(cnt(&b"3abcab"[..]), Incomplete(Needed::Size(7))); + assert_eq!(cnt(&b"xxx"[..]), Error(error_position!(ErrorKind::Digit, &b"xxx"[..]))); + assert_eq!(cnt(&b"2abcxxx"[..]), Error(error_position!(ErrorKind::Count, &b"abcxxx"[..]))); + } + + #[test] + fn length_data() { + named!( take<&[u8], &[u8]>, length_data!(number) ); + + assert_eq!(take(&b"6abcabcabcdef"[..]), Done(&b"abcdef"[..], &b"abcabc"[..])); + assert_eq!(take(&b"3ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(take(&b"xxx"[..]), Error(error_position!(ErrorKind::Digit, &b"xxx"[..]))); + assert_eq!(take(&b"2abcxxx"[..]), Done(&b"cxxx"[..], &b"ab"[..])); + } + + #[test] + fn length_value_test() { + named!(length_value_1<&[u8], u16 >, length_value!(be_u8, be_u16)); + named!(length_value_2<&[u8], (u8, u8) >, length_value!(be_u8, tuple!(be_u8, be_u8))); + + let i1 = [0, 5, 6]; + assert_eq!(length_value_1(&i1), IResult::Error(error_position!(ErrorKind::Complete, &b""[..]))); + assert_eq!(length_value_2(&i1), IResult::Error(error_position!(ErrorKind::Complete, &b""[..]))); + + let i2 = [1, 5, 6, 3]; + assert_eq!(length_value_1(&i2), IResult::Error(error_position!(ErrorKind::Complete, &i2[1..2]))); + assert_eq!(length_value_2(&i2), IResult::Error(error_position!(ErrorKind::Complete, &i2[1..2]))); + + let i3 = [2, 5, 6, 3, 4, 5, 7]; + assert_eq!(length_value_1(&i3), IResult::Done(&i3[3..], 1286)); + assert_eq!(length_value_2(&i3), IResult::Done(&i3[3..], (5, 6))); + + let i4 = [3, 5, 6, 3, 4, 5]; + assert_eq!(length_value_1(&i4), IResult::Done(&i4[4..], 1286)); + assert_eq!(length_value_2(&i4), IResult::Done(&i4[4..], (5, 6))); + } + + #[test] + #[cfg(feature = "std")] + fn fold_many0() { + fn fold_into_vec(mut acc: Vec, item: T) -> Vec { + acc.push(item); + acc + }; + named!( tag_abcd, tag!("abcd") ); + named!( tag_empty, tag!("") ); + named!( multi<&[u8],Vec<&[u8]> >, fold_many0!(tag_abcd, Vec::new(), fold_into_vec) ); + named!( multi_empty<&[u8],Vec<&[u8]> >, fold_many0!(tag_empty, Vec::new(), fold_into_vec) ); + + assert_eq!(multi(&b"abcdef"[..]), Done(&b"ef"[..], vec![&b"abcd"[..]])); + assert_eq!(multi(&b"abcdabcdefgh"[..]), Done(&b"efgh"[..], vec![&b"abcd"[..], &b"abcd"[..]])); + assert_eq!(multi(&b"azerty"[..]), Done(&b"azerty"[..], Vec::new())); + assert_eq!(multi(&b"abcdab"[..]), Incomplete(Needed::Size(8))); + assert_eq!(multi(&b"abcd"[..]), Done(&b""[..], vec![&b"abcd"[..]])); + assert_eq!(multi(&b""[..]), Done(&b""[..], Vec::new())); + assert_eq!(multi_empty(&b"abcdef"[..]), Error(error_position!(ErrorKind::Many0, &b"abcdef"[..]))); + } + + #[test] + #[cfg(feature = "std")] + fn fold_many1() { + fn fold_into_vec(mut acc: Vec, item: T) -> Vec { + acc.push(item); + acc + }; + named!(multi<&[u8],Vec<&[u8]> >, fold_many1!(tag!("abcd"), Vec::new(), fold_into_vec)); + + let a = &b"abcdef"[..]; + let b = &b"abcdabcdefgh"[..]; + let c = &b"azerty"[..]; + let d = &b"abcdab"[..]; + + let res1 = vec![&b"abcd"[..]]; + assert_eq!(multi(a), Done(&b"ef"[..], res1)); + let res2 = vec![&b"abcd"[..], &b"abcd"[..]]; + assert_eq!(multi(b), Done(&b"efgh"[..], res2)); + assert_eq!(multi(c), Error(error_position!(ErrorKind::Many1,c))); + assert_eq!(multi(d), Incomplete(Needed::Size(8))); + } + + #[test] + #[cfg(feature = "std")] + fn fold_many_m_n() { + fn fold_into_vec(mut acc: Vec, item: T) -> Vec { + acc.push(item); + acc + }; + named!(multi<&[u8],Vec<&[u8]> >, fold_many_m_n!(2, 4, tag!("Abcd"), Vec::new(), fold_into_vec)); + + let a = &b"Abcdef"[..]; + let b = &b"AbcdAbcdefgh"[..]; + let c = &b"AbcdAbcdAbcdAbcdefgh"[..]; + let d = &b"AbcdAbcdAbcdAbcdAbcdefgh"[..]; + let e = &b"AbcdAb"[..]; + + assert_eq!(multi(a), Error(error_position!(ErrorKind::ManyMN,a))); + let res1 = vec![&b"Abcd"[..], &b"Abcd"[..]]; + assert_eq!(multi(b), Done(&b"efgh"[..], res1)); + let res2 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]]; + assert_eq!(multi(c), Done(&b"efgh"[..], res2)); + let res3 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]]; + assert_eq!(multi(d), Done(&b"Abcdefgh"[..], res3)); + assert_eq!(multi(e), Incomplete(Needed::Size(8))); + } + +} diff --git a/bash-5.1/vendor/nom/src/nom.rs b/bash-5.1/vendor/nom/src/nom.rs new file mode 100644 index 0000000..7f48afc --- /dev/null +++ b/bash-5.1/vendor/nom/src/nom.rs @@ -0,0 +1,1225 @@ +//! Useful parser combinators +//! +//! A number of useful parser combinators have already been implemented. +//! Some of them use macros, other are implemented through functions. +//! Hopefully, the syntax will converge to onely one way in the future, +//! but the macros system makes no promises. +//! + +#[cfg(not(feature = "std"))] +use std::prelude::v1::*; +use std::boxed::Box; + +use std::fmt::Debug; +use internal::*; +use internal::IResult::*; +use util::ErrorKind; +use traits::{AsChar,InputLength,InputIter}; +use std::mem::transmute; +use std::ops::{Range,RangeFrom,RangeTo}; +use traits::{Compare,CompareResult,Slice}; + +#[inline] +pub fn tag_cl<'a,'b>(rec:&'a[u8]) -> Box IResult<&'b[u8], &'b[u8]> + 'a> { + Box::new(move |i: &'b[u8]| -> IResult<&'b[u8], &'b[u8]> { + if i.len() >= rec.len() && &i[0..rec.len()] == rec { + Done(&i[rec.len()..], &i[0..rec.len()]) + } else { + Error(error_position!(ErrorKind::TagClosure, i)) + } + }) +} + +#[cfg(feature = "std")] +#[inline] +pub fn print(input: T) -> IResult { + println!("{:?}", input); + Done(input, ()) +} + +#[inline] +pub fn begin(input: &[u8]) -> IResult<(), &[u8]> { + Done((), input) +} + +pub fn crlf(input:T) -> IResult where + T:Slice>+Slice>+Slice>, + T: InputIter, + T: Compare<&'static str> { + match input.compare("\r\n") { + //FIXME: is this the right index? + CompareResult::Ok => { + IResult::Done(input.slice(2..), input.slice(0..2)) + }, + CompareResult::Incomplete => IResult::Incomplete(Needed::Size(2)), + CompareResult::Error => IResult::Error(error_position!(ErrorKind::CrLf, input)) + } +} + +// FIXME: when rust-lang/rust#17436 is fixed, macros will be able to export +// public methods +pub fn not_line_ending(input:T) -> IResult where + T:Slice>+Slice>+Slice>, + T: InputIter+InputLength, + T: Compare<&'static str>, + ::Item: AsChar { + match input.iter_elements().position(|item| { + let c = item.as_char(); + c == '\r' || c == '\n' + }) { + None => Done(input.slice(input.input_len()..), input), + Some(index) => { + let mut it = input.iter_elements(); + let nth = it.nth(index).unwrap().as_char(); + if nth == '\r' { + let sliced = input.slice(index..); + let comp = sliced.compare("\r\n"); + match comp { + //FIXME: calculate the right index + CompareResult::Incomplete => Incomplete(Needed::Unknown), + CompareResult::Error => Error(error_position!(ErrorKind::Tag, input)), + CompareResult::Ok => Done(input.slice(index..), input.slice(..index)) + } + } else { + Done(input.slice(index..), input.slice(..index)) + } + } + } +} + +/// Recognizes an end of line (both '\n' and '\r\n') +pub fn line_ending(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + T: Compare<&'static str> { + + match input.compare("\n") { + CompareResult::Ok => Done(input.slice(1..), input.slice(0..1)), + CompareResult::Incomplete => Incomplete(Needed::Size(1)), + CompareResult::Error => match input.compare("\r\n") { + //FIXME: is this the right index? + CompareResult::Ok => Done(input.slice(2..), input.slice(0..2)), + CompareResult::Incomplete => Incomplete(Needed::Size(2)), + CompareResult::Error => Error(error_position!(ErrorKind::CrLf, input)) + } + } +} + +pub fn eol(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + T: Compare<&'static str> { + line_ending(input) +} + +/// Tests if byte is ASCII alphabetic: A-Z, a-z +#[inline] +pub fn is_alphabetic(chr:u8) -> bool { + (chr >= 0x41 && chr <= 0x5A) || (chr >= 0x61 && chr <= 0x7A) +} + +/// Tests if byte is ASCII digit: 0-9 +#[inline] +pub fn is_digit(chr: u8) -> bool { + chr >= 0x30 && chr <= 0x39 +} + +/// Tests if byte is ASCII hex digit: 0-9, A-F, a-f +#[inline] +pub fn is_hex_digit(chr: u8) -> bool { + (chr >= 0x30 && chr <= 0x39) || + (chr >= 0x41 && chr <= 0x46) || + (chr >= 0x61 && chr <= 0x66) +} + +/// Tests if byte is ASCII octal digit: 0-7 +#[inline] +pub fn is_oct_digit(chr: u8) -> bool { + chr >= 0x30 && chr <= 0x37 +} + +/// Tests if byte is ASCII alphanumeric: A-Z, a-z, 0-9 +#[inline] +pub fn is_alphanumeric(chr: u8) -> bool { + is_alphabetic(chr) || is_digit(chr) +} + +/// Tests if byte is ASCII space or tab +#[inline] +pub fn is_space(chr:u8) -> bool { + chr == ' ' as u8 || chr == '\t' as u8 +} + +// FIXME: when rust-lang/rust#17436 is fixed, macros will be able to export +//pub filter!(alpha is_alphabetic) +//pub filter!(digit is_digit) +//pub filter!(hex_digit is_hex_digit) +//pub filter!(oct_digit is_oct_digit) +//pub filter!(alphanumeric is_alphanumeric) + +/// Recognizes one or more lowercase and uppercase alphabetic characters: a-zA-Z +pub fn alpha(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + if ! item.is_alpha() { + if idx == 0 { + return Error(error_position!(ErrorKind::Alpha, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +/// Recognizes one or more numerical characters: 0-9 +pub fn digit(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + if ! item.is_dec_digit() { + if idx == 0 { + return Error(error_position!(ErrorKind::Digit, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +/// Recognizes one or more hexadecimal numerical characters: 0-9, A-F, a-f +pub fn hex_digit(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + if ! item.is_hex_digit() { + if idx == 0 { + return Error(error_position!(ErrorKind::HexDigit, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +/// Recognizes one or more octal characters: 0-7 +pub fn oct_digit(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + if ! item.is_oct_digit() { + if idx == 0 { + return Error(error_position!(ErrorKind::OctDigit, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +/// Recognizes one or more numerical and alphabetic characters: 0-9a-zA-Z +pub fn alphanumeric(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + if ! item.is_alphanum() { + if idx == 0 { + return Error(error_position!(ErrorKind::AlphaNumeric, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +/// Recognizes one or more spaces and tabs +pub fn space(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + let chr = item.as_char(); + if ! (chr == ' ' || chr == '\t') { + if idx == 0 { + return Error(error_position!(ErrorKind::Space, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +/// Recognizes one or more spaces, tabs, carriage returns and line feeds +pub fn multispace(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputIter+InputLength, + ::Item: AsChar { + let input_length = input.input_len(); + if input_length == 0 { + return Incomplete(Needed::Unknown); + } + + for (idx, item) in input.iter_indices() { + let chr = item.as_char(); + if ! (chr == ' ' || chr == '\t' || chr == '\r' || chr == '\n') { + if idx == 0 { + return Error(error_position!(ErrorKind::MultiSpace, input)) + } else { + return Done(input.slice(idx..), input.slice(0..idx)) + } + } + } + Done(input.slice(input_length..), input) +} + +pub fn sized_buffer(input:&[u8]) -> IResult<&[u8], &[u8]> { + if input.is_empty() { + return Incomplete(Needed::Unknown) + } + + let len = input[0] as usize; + + if input.len() >= len + 1 { + Done(&input[len+1..], &input[1..len+1]) + } else { + Incomplete(Needed::Size(1 + len)) + } +} + +/// Recognizes an unsigned 1 byte integer (equivalent to take!(1) +#[inline] +pub fn be_u8(i: &[u8]) -> IResult<&[u8], u8> { + if i.len() < 1 { + Incomplete(Needed::Size(1)) + } else { + Done(&i[1..], i[0]) + } +} + +/// Recognizes big endian unsigned 2 bytes integer +#[inline] +pub fn be_u16(i: &[u8]) -> IResult<&[u8], u16> { + if i.len() < 2 { + Incomplete(Needed::Size(2)) + } else { + let res = ((i[0] as u16) << 8) + i[1] as u16; + Done(&i[2..], res) + } +} + +/// Recognizes big endian unsigned 3 byte integer +#[inline] +pub fn be_u24(i: &[u8]) -> IResult<&[u8], u32> { + if i.len() < 3 { + Incomplete(Needed::Size(3)) + } else { + let res = ((i[0] as u32) << 16) + ((i[1] as u32) << 8) + (i[2] as u32); + Done(&i[3..], res) + } +} + +/// Recognizes big endian unsigned 4 bytes integer +#[inline] +pub fn be_u32(i: &[u8]) -> IResult<&[u8], u32> { + if i.len() < 4 { + Incomplete(Needed::Size(4)) + } else { + let res = ((i[0] as u32) << 24) + ((i[1] as u32) << 16) + ((i[2] as u32) << 8) + i[3] as u32; + Done(&i[4..], res) + } +} + +/// Recognizes big endian unsigned 8 bytes integer +#[inline] +pub fn be_u64(i: &[u8]) -> IResult<&[u8], u64> { + if i.len() < 8 { + Incomplete(Needed::Size(8)) + } else { + let res = ((i[0] as u64) << 56) + ((i[1] as u64) << 48) + ((i[2] as u64) << 40) + ((i[3] as u64) << 32) + + ((i[4] as u64) << 24) + ((i[5] as u64) << 16) + ((i[6] as u64) << 8) + i[7] as u64; + Done(&i[8..], res) + } +} + +/// Recognizes a signed 1 byte integer (equivalent to take!(1) +#[inline] +pub fn be_i8(i:&[u8]) -> IResult<&[u8], i8> { + map!(i, be_u8, | x | { x as i8 }) +} + +/// Recognizes big endian signed 2 bytes integer +#[inline] +pub fn be_i16(i:&[u8]) -> IResult<&[u8], i16> { + map!(i, be_u16, | x | { x as i16 }) +} + +/// Recognizes big endian signed 3 bytes integer +#[inline] +pub fn be_i24(i: &[u8]) -> IResult<&[u8], i32> { + // Same as the unsigned version but we need to sign-extend manually here + map!(i, be_u24, | x | if x & 0x80_00_00 != 0 { (x | 0xff_00_00_00) as i32 } else { x as i32 }) +} + +/// Recognizes big endian signed 4 bytes integer +#[inline] +pub fn be_i32(i:&[u8]) -> IResult<&[u8], i32> { + map!(i, be_u32, | x | { x as i32 }) +} + +/// Recognizes big endian signed 8 bytes integer +#[inline] +pub fn be_i64(i:&[u8]) -> IResult<&[u8], i64> { + map!(i, be_u64, | x | { x as i64 }) +} + +/// Recognizes an unsigned 1 byte integer (equivalent to take!(1) +#[inline] +pub fn le_u8(i: &[u8]) -> IResult<&[u8], u8> { + if i.len() < 1 { + Incomplete(Needed::Size(1)) + } else { + Done(&i[1..], i[0]) + } +} + +/// Recognizes little endian unsigned 2 bytes integer +#[inline] +pub fn le_u16(i: &[u8]) -> IResult<&[u8], u16> { + if i.len() < 2 { + Incomplete(Needed::Size(2)) + } else { + let res = ((i[1] as u16) << 8) + i[0] as u16; + Done(&i[2..], res) + } +} + +/// Recognizes little endian unsigned 3 byte integer +#[inline] +pub fn le_u24(i: &[u8]) -> IResult<&[u8], u32> { + if i.len() < 3 { + Incomplete(Needed::Size(3)) + } else { + let res = (i[0] as u32) + ((i[1] as u32) << 8) + ((i[2] as u32) << 16); + Done(&i[3..], res) + } +} + +/// Recognizes little endian unsigned 4 bytes integer +#[inline] +pub fn le_u32(i: &[u8]) -> IResult<&[u8], u32> { + if i.len() < 4 { + Incomplete(Needed::Size(4)) + } else { + let res = ((i[3] as u32) << 24) + ((i[2] as u32) << 16) + ((i[1] as u32) << 8) + i[0] as u32; + Done(&i[4..], res) + } +} + +/// Recognizes little endian unsigned 8 bytes integer +#[inline] +pub fn le_u64(i: &[u8]) -> IResult<&[u8], u64> { + if i.len() < 8 { + Incomplete(Needed::Size(8)) + } else { + let res = ((i[7] as u64) << 56) + ((i[6] as u64) << 48) + ((i[5] as u64) << 40) + ((i[4] as u64) << 32) + + ((i[3] as u64) << 24) + ((i[2] as u64) << 16) + ((i[1] as u64) << 8) + i[0] as u64; + Done(&i[8..], res) + } +} + +/// Recognizes a signed 1 byte integer (equivalent to take!(1) +#[inline] +pub fn le_i8(i:&[u8]) -> IResult<&[u8], i8> { + map!(i, le_u8, | x | { x as i8 }) +} + +/// Recognizes little endian signed 2 bytes integer +#[inline] +pub fn le_i16(i:&[u8]) -> IResult<&[u8], i16> { + map!(i, le_u16, | x | { x as i16 }) +} + +/// Recognizes little endian signed 3 bytes integer +#[inline] +pub fn le_i24(i: &[u8]) -> IResult<&[u8], i32> { + // Same as the unsigned version but we need to sign-extend manually here + map!(i, le_u24, | x | if x & 0x80_00_00 != 0 { (x | 0xff_00_00_00) as i32 } else { x as i32 }) +} + +/// Recognizes little endian signed 4 bytes integer +#[inline] +pub fn le_i32(i:&[u8]) -> IResult<&[u8], i32> { + map!(i, le_u32, | x | { x as i32 }) +} + +/// Recognizes little endian signed 8 bytes integer +#[inline] +pub fn le_i64(i:&[u8]) -> IResult<&[u8], i64> { + map!(i, le_u64, | x | { x as i64 }) +} + +/// Configurable endianness +#[derive(Debug,PartialEq,Eq,Clone,Copy)] +pub enum Endianness { + Big, + Little, +} + +/// if the parameter is nom::Endianness::Big, parse a big endian u16 integer, +/// otherwise a little endian u16 integer +#[macro_export] +macro_rules! u16 ( ($i:expr, $e:expr) => ( {if $crate::Endianness::Big == $e { $crate::be_u16($i) } else { $crate::le_u16($i) } } );); +/// if the parameter is nom::Endianness::Big, parse a big endian u32 integer, +/// otherwise a little endian u32 integer +#[macro_export] +macro_rules! u32 ( ($i:expr, $e:expr) => ( {if $crate::Endianness::Big == $e { $crate::be_u32($i) } else { $crate::le_u32($i) } } );); +/// if the parameter is nom::Endianness::Big, parse a big endian u64 integer, +/// otherwise a little endian u64 integer +#[macro_export] +macro_rules! u64 ( ($i:expr, $e:expr) => ( {if $crate::Endianness::Big == $e { $crate::be_u64($i) } else { $crate::le_u64($i) } } );); + +/// if the parameter is nom::Endianness::Big, parse a big endian i16 integer, +/// otherwise a little endian i16 integer +#[macro_export] +macro_rules! i16 ( ($i:expr, $e:expr) => ( {if $crate::Endianness::Big == $e { $crate::be_i16($i) } else { $crate::le_i16($i) } } );); +/// if the parameter is nom::Endianness::Big, parse a big endian i32 integer, +/// otherwise a little endian i32 integer +#[macro_export] +macro_rules! i32 ( ($i:expr, $e:expr) => ( {if $crate::Endianness::Big == $e { $crate::be_i32($i) } else { $crate::le_i32($i) } } );); +/// if the parameter is nom::Endianness::Big, parse a big endian i64 integer, +/// otherwise a little endian i64 integer +#[macro_export] +macro_rules! i64 ( ($i:expr, $e:expr) => ( {if $crate::Endianness::Big == $e { $crate::be_i64($i) } else { $crate::le_i64($i) } } );); + +/// Recognizes big endian 4 bytes floating point number +#[inline] +pub fn be_f32(input: &[u8]) -> IResult<&[u8], f32> { + match be_u32(input) { + Error(e) => Error(e), + Incomplete(e) => Incomplete(e), + Done(i,o) => { + unsafe { + Done(i, transmute::(o)) + } + } + } +} + +/// Recognizes big endian 8 bytes floating point number +#[inline] +pub fn be_f64(input: &[u8]) -> IResult<&[u8], f64> { + match be_u64(input) { + Error(e) => Error(e), + Incomplete(e) => Incomplete(e), + Done(i,o) => { + unsafe { + Done(i, transmute::(o)) + } + } + } +} + +/// Recognizes little endian 4 bytes floating point number +#[inline] +pub fn le_f32(input: &[u8]) -> IResult<&[u8], f32> { + match le_u32(input) { + Error(e) => Error(e), + Incomplete(e) => Incomplete(e), + Done(i,o) => { + unsafe { + Done(i, transmute::(o)) + } + } + } +} + +/// Recognizes little endian 8 bytes floating point number +#[inline] +pub fn le_f64(input: &[u8]) -> IResult<&[u8], f64> { + match le_u64(input) { + Error(e) => Error(e), + Incomplete(e) => Incomplete(e), + Done(i,o) => { + unsafe { + Done(i, transmute::(o)) + } + } + } +} + +/// Recognizes a hex-encoded integer +#[inline] +pub fn hex_u32(input: &[u8]) -> IResult<&[u8], u32> { + match is_a!(input, &b"0123456789abcdefABCDEF"[..]) { + Error(e) => Error(e), + Incomplete(e) => Incomplete(e), + Done(i,o) => { + let mut res = 0u32; + + // Do not parse more than 8 characters for a u32 + let mut remaining = i; + let mut parsed = o; + if o.len() > 8 { + remaining = &input[8..]; + parsed = &input[..8]; + } + + for &e in parsed { + let digit = e as char; + let value = digit.to_digit(16).unwrap_or(0); + res = value + (res << 4); + } + Done(remaining, res) + } + } +} + +/// Recognizes non empty buffers +#[inline] +pub fn non_empty(input:T) -> IResult where + T: Slice>+Slice>+Slice>, + T: InputLength { + if input.input_len() == 0 { + Error(error_position!(ErrorKind::NonEmpty, input)) + } else { + Done(input.slice(input.input_len()..), input) + } +} + +/// Return the remaining input. +#[inline] +pub fn rest(input: &[u8]) -> IResult<&[u8], &[u8]> { + IResult::Done(&input[input.len()..], input) +} + +/// Return the remaining input, for strings. +#[inline] +pub fn rest_s(input: &str) -> IResult<&str, &str> { + IResult::Done(&input[input.len()..], input) +} + +/// Recognizes floating point number in a byte string and returns a f32 +#[cfg(feature = "std")] +pub fn float(input: &[u8]) -> IResult<&[u8],f32> { + flat_map!(input, + recognize!( + tuple!( + opt!(alt!(tag!("+") | tag!("-"))), + alt!( + delimited!(digit, tag!("."), opt!(digit)) + | delimited!(opt!(digit), tag!("."), digit) + ), + opt!(complete!(tuple!( + alt!(tag!("e") | tag!("E")), + opt!(alt!(tag!("+") | tag!("-"))), + digit + ) + )) + ) + ), + parse_to!(f32) + ) +} + +/// Recognizes floating point number in a string and returns a f32 +#[cfg(feature = "std")] +pub fn float_s(input: &str) -> IResult<&str,f32> { + flat_map!(input, + recognize!( + tuple!( + opt!(alt!(tag!("+") | tag!("-"))), + alt!( + delimited!(digit, tag!("."), opt!(digit)) + | delimited!(opt!(digit), tag!("."), digit) + ), + opt!(complete!(tuple!( + alt!(tag!("e") | tag!("E")), + opt!(alt!(tag!("+") | tag!("-"))), + digit + ) + )) + ) + ), + parse_to!(f32) + ) +} + +/// Recognizes floating point number in a byte string and returns a f64 +#[cfg(feature = "std")] +pub fn double(input: &[u8]) -> IResult<&[u8],f64> { + flat_map!(input, + recognize!( + tuple!( + opt!(alt!(tag!("+") | tag!("-"))), + alt!( + delimited!(digit, tag!("."), opt!(digit)) + | delimited!(opt!(digit), tag!("."), digit) + ), + opt!(complete!(tuple!( + alt!(tag!("e") | tag!("E")), + opt!(alt!(tag!("+") | tag!("-"))), + digit + ) + )) + ) + ), + parse_to!(f64) + ) +} + +/// Recognizes floating point number in a string and returns a f64 +#[cfg(feature = "std")] +pub fn double_s(input: &str) -> IResult<&str,f64> { + flat_map!(input, + recognize!( + tuple!( + opt!(alt!(tag!("+") | tag!("-"))), + alt!( + delimited!(digit, tag!("."), opt!(digit)) + | delimited!(opt!(digit), tag!("."), digit) + ), + opt!(complete!(tuple!( + alt!(tag!("e") | tag!("E")), + opt!(alt!(tag!("+") | tag!("-"))), + digit + ) + )) + ) + ), + parse_to!(f64) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use internal::{Needed,IResult}; + use util::ErrorKind; + + #[test] + fn tag_closure() { + let x = tag_cl(&b"abcd"[..]); + let r = x(&b"abcdabcdefgh"[..]); + assert_eq!(r, Done(&b"abcdefgh"[..], &b"abcd"[..])); + + let r2 = x(&b"abcefgh"[..]); + assert_eq!(r2, Error(error_position!(ErrorKind::TagClosure, &b"abcefgh"[..]))); + } + + #[test] + fn character() { + let empty: &[u8] = b""; + let a: &[u8] = b"abcd"; + let b: &[u8] = b"1234"; + let c: &[u8] = b"a123"; + let d: &[u8] = "azé12".as_bytes(); + let e: &[u8] = b" "; + assert_eq!(alpha(a), Done(empty, a)); + assert_eq!(alpha(b), Error(error_position!(ErrorKind::Alpha,b))); + assert_eq!(alpha(c), Done(&c[1..], &b"a"[..])); + assert_eq!(alpha(d), Done("é12".as_bytes(), &b"az"[..])); + assert_eq!(digit(a), Error(error_position!(ErrorKind::Digit,a))); + assert_eq!(digit(b), Done(empty, b)); + assert_eq!(digit(c), Error(error_position!(ErrorKind::Digit,c))); + assert_eq!(digit(d), Error(error_position!(ErrorKind::Digit,d))); + assert_eq!(hex_digit(a), Done(empty, a)); + assert_eq!(hex_digit(b), Done(empty, b)); + assert_eq!(hex_digit(c), Done(empty, c)); + assert_eq!(hex_digit(d), Done("zé12".as_bytes(), &b"a"[..])); + assert_eq!(hex_digit(e), Error(error_position!(ErrorKind::HexDigit,e))); + assert_eq!(oct_digit(a), Error(error_position!(ErrorKind::OctDigit,a))); + assert_eq!(oct_digit(b), Done(empty, b)); + assert_eq!(oct_digit(c), Error(error_position!(ErrorKind::OctDigit,c))); + assert_eq!(oct_digit(d), Error(error_position!(ErrorKind::OctDigit,d))); + assert_eq!(alphanumeric(a), Done(empty, a)); + assert_eq!(fix_error!(b,(), alphanumeric), Done(empty, b)); + assert_eq!(alphanumeric(c), Done(empty, c)); + assert_eq!(alphanumeric(d), Done("é12".as_bytes(), &b"az"[..])); + assert_eq!(space(e), Done(&b""[..], &b" "[..])); + } + + #[test] + fn character_s() { + let empty = ""; + let a = "abcd"; + let b = "1234"; + let c = "a123"; + let d = "azé12"; + let e = " "; + assert_eq!(alpha(a), Done(empty, a)); + assert_eq!(alpha(b), Error(error_position!(ErrorKind::Alpha,b))); + assert_eq!(alpha(c), Done(&c[1..], &"a"[..])); + assert_eq!(alpha(d), Done("12", &"azé"[..])); + assert_eq!(digit(a), Error(error_position!(ErrorKind::Digit,a))); + assert_eq!(digit(b), Done(empty, b)); + assert_eq!(digit(c), Error(error_position!(ErrorKind::Digit,c))); + assert_eq!(digit(d), Error(error_position!(ErrorKind::Digit,d))); + assert_eq!(hex_digit(a), Done(empty, a)); + assert_eq!(hex_digit(b), Done(empty, b)); + assert_eq!(hex_digit(c), Done(empty, c)); + assert_eq!(hex_digit(d), Done("zé12", &"a"[..])); + assert_eq!(hex_digit(e), Error(error_position!(ErrorKind::HexDigit,e))); + assert_eq!(oct_digit(a), Error(error_position!(ErrorKind::OctDigit,a))); + assert_eq!(oct_digit(b), Done(empty, b)); + assert_eq!(oct_digit(c), Error(error_position!(ErrorKind::OctDigit,c))); + assert_eq!(oct_digit(d), Error(error_position!(ErrorKind::OctDigit,d))); + assert_eq!(alphanumeric(a), Done(empty, a)); + assert_eq!(fix_error!(b,(), alphanumeric), Done(empty, b)); + assert_eq!(alphanumeric(c), Done(empty, c)); + assert_eq!(alphanumeric(d), Done("", &"azé12"[..])); + assert_eq!(space(e), Done(&""[..], &" "[..])); + } + + use util::Offset; + #[test] + fn offset() { + let a = &b"abcd"[..]; + let b = &b"1234"[..]; + let c = &b"a123"[..]; + let d = &b" \t"[..]; + let e = &b" \t\r\n"[..]; + let f = &b"123abcDEF"[..]; + + match alpha(a) { + Done(i, _) => { assert_eq!(a.offset(i) + i.len(), a.len()); } + _ => { panic!("wrong return type in offset test for alpha") } + } + match digit(b) { + Done(i, _) => { assert_eq!(b.offset(i) + i.len(), b.len()); } + _ => { panic!("wrong return type in offset test for digit") } + } + match alphanumeric(c) { + Done(i, _) => { assert_eq!(c.offset(i) + i.len(), c.len()); } + _ => { panic!("wrong return type in offset test for alphanumeric") } + } + match space(d) { + Done(i, _) => { assert_eq!(d.offset(i) + i.len(), d.len()); } + _ => { panic!("wrong return type in offset test for space") } + } + match multispace(e) { + Done(i, _) => { assert_eq!(e.offset(i) + i.len(), e.len()); } + _ => { panic!("wrong return type in offset test for multispace") } + } + match hex_digit(f) { + Done(i, _) => { assert_eq!(f.offset(i) + i.len(), f.len()); } + _ => { panic!("wrong return type in offset test for hex_digit") } + } + match oct_digit(f) { + Done(i, _) => { assert_eq!(f.offset(i) + i.len(), f.len()); } + _ => { panic!("wrong return type in offset test for oct_digit") } + } + } + + #[test] + fn is_not_line_ending_bytes() { + let a: &[u8] = b"ab12cd\nefgh"; + assert_eq!(not_line_ending(a), Done(&b"\nefgh"[..], &b"ab12cd"[..])); + + let b: &[u8] = b"ab12cd\nefgh\nijkl"; + assert_eq!(not_line_ending(b), Done(&b"\nefgh\nijkl"[..], &b"ab12cd"[..])); + + let c: &[u8] = b"ab12cd\r\nefgh\nijkl"; + assert_eq!(not_line_ending(c), Done(&b"\r\nefgh\nijkl"[..], &b"ab12cd"[..])); + + let d: &[u8] = b"ab12cd"; + assert_eq!(not_line_ending(d), Done(&b""[..], d)); + } + + #[test] + fn is_not_line_ending_str() { + /* + let a: &str = "ab12cd\nefgh"; + assert_eq!(not_line_ending(a), Done(&"\nefgh"[..], &"ab12cd"[..])); + + let b: &str = "ab12cd\nefgh\nijkl"; + assert_eq!(not_line_ending(b), Done(&"\nefgh\nijkl"[..], &"ab12cd"[..])); + + let c: &str = "ab12cd\r\nefgh\nijkl"; + assert_eq!(not_line_ending(c), Done(&"\r\nefgh\nijkl"[..], &"ab12cd"[..])); + + let d = "βèƒôřè\nÂßÇáƒƭèř"; + assert_eq!(not_line_ending(d), Done(&"\nÂßÇáƒƭèř"[..], &"βèƒôřè"[..])); + + let e = "βèƒôřè\r\nÂßÇáƒƭèř"; + assert_eq!(not_line_ending(e), Done(&"\r\nÂßÇáƒƭèř"[..], &"βèƒôřè"[..])); + */ + + let f = "βèƒôřè\rÂßÇáƒƭèř"; + assert_eq!(not_line_ending(f), Error(error_position!(ErrorKind::Tag,f))); + + let g: &str = "ab12cd"; + assert_eq!(not_line_ending(g), Done("", g)); + } + + #[test] + #[cfg(feature = "std")] + fn buffer_with_size() { + let i:Vec = vec![7,8]; + let o:Vec = vec![4,5,6]; + //let arr:[u8; 6usize] = [3, 4, 5, 6, 7, 8]; + let arr:[u8; 6usize] = [3, 4, 5, 6, 7, 8]; + let res = sized_buffer(&arr[..]); + assert_eq!(res, Done(&i[..], &o[..])) + } + + /*#[test] + fn t1() { + let v1:Vec = vec![1,2,3]; + let v2:Vec = vec![4,5,6]; + let d = Done(&v1[..], &v2[..]); + let res = d.flat_map(print); + assert_eq!(res, Done(&v2[..], ())); + }*/ + + #[test] + fn i8_tests() { + assert_eq!(be_i8(&[0x00]), Done(&b""[..], 0)); + assert_eq!(be_i8(&[0x7f]), Done(&b""[..], 127)); + assert_eq!(be_i8(&[0xff]), Done(&b""[..], -1)); + assert_eq!(be_i8(&[0x80]), Done(&b""[..], -128)); + } + + #[test] + fn i16_tests() { + assert_eq!(be_i16(&[0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(be_i16(&[0x7f, 0xff]), Done(&b""[..], 32767_i16)); + assert_eq!(be_i16(&[0xff, 0xff]), Done(&b""[..], -1)); + assert_eq!(be_i16(&[0x80, 0x00]), Done(&b""[..], -32768_i16)); + } + + #[test] + fn u24_tests() { + assert_eq!(be_u24(&[0x00, 0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(be_u24(&[0x00, 0xFF, 0xFF]), Done(&b""[..], 65535_u32)); + assert_eq!(be_u24(&[0x12, 0x34, 0x56]), Done(&b""[..], 1193046_u32)); + } + + #[test] + fn i24_tests() { + assert_eq!(be_i24(&[0xFF, 0xFF, 0xFF]), Done(&b""[..], -1_i32)); + assert_eq!(be_i24(&[0xFF, 0x00, 0x00]), Done(&b""[..], -65536_i32)); + assert_eq!(be_i24(&[0xED, 0xCB, 0xAA]), Done(&b""[..], -1193046_i32)); + } + + #[test] + fn i32_tests() { + assert_eq!(be_i32(&[0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(be_i32(&[0x7f, 0xff, 0xff, 0xff]), Done(&b""[..], 2147483647_i32)); + assert_eq!(be_i32(&[0xff, 0xff, 0xff, 0xff]), Done(&b""[..], -1)); + assert_eq!(be_i32(&[0x80, 0x00, 0x00, 0x00]), Done(&b""[..], -2147483648_i32)); + } + + #[test] + fn i64_tests() { + assert_eq!(be_i64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(be_i64(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Done(&b""[..], 9223372036854775807_i64)); + assert_eq!(be_i64(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Done(&b""[..], -1)); + assert_eq!(be_i64(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Done(&b""[..], -9223372036854775808_i64)); + } + + #[test] + fn le_i8_tests() { + assert_eq!(le_i8(&[0x00]), Done(&b""[..], 0)); + assert_eq!(le_i8(&[0x7f]), Done(&b""[..], 127)); + assert_eq!(le_i8(&[0xff]), Done(&b""[..], -1)); + assert_eq!(le_i8(&[0x80]), Done(&b""[..], -128)); + } + + #[test] + fn le_i16_tests() { + assert_eq!(le_i16(&[0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(le_i16(&[0xff, 0x7f]), Done(&b""[..], 32767_i16)); + assert_eq!(le_i16(&[0xff, 0xff]), Done(&b""[..], -1)); + assert_eq!(le_i16(&[0x00, 0x80]), Done(&b""[..], -32768_i16)); + } + + #[test] + fn le_u24_tests() { + assert_eq!(le_u24(&[0x00, 0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(le_u24(&[0xFF, 0xFF, 0x00]), Done(&b""[..], 65535_u32)); + assert_eq!(le_u24(&[0x56, 0x34, 0x12]), Done(&b""[..], 1193046_u32)); + } + + #[test] + fn le_i24_tests() { + assert_eq!(le_i24(&[0xFF, 0xFF, 0xFF]), Done(&b""[..], -1_i32)); + assert_eq!(le_i24(&[0x00, 0x00, 0xFF]), Done(&b""[..], -65536_i32)); + assert_eq!(le_i24(&[0xAA, 0xCB, 0xED]), Done(&b""[..], -1193046_i32)); + } + + #[test] + fn le_i32_tests() { + assert_eq!(le_i32(&[0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(le_i32(&[0xff, 0xff, 0xff, 0x7f]), Done(&b""[..], 2147483647_i32)); + assert_eq!(le_i32(&[0xff, 0xff, 0xff, 0xff]), Done(&b""[..], -1)); + assert_eq!(le_i32(&[0x00, 0x00, 0x00, 0x80]), Done(&b""[..], -2147483648_i32)); + } + + #[test] + fn le_i64_tests() { + assert_eq!(le_i64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0)); + assert_eq!(le_i64(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]), Done(&b""[..], 9223372036854775807_i64)); + assert_eq!(le_i64(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Done(&b""[..], -1)); + assert_eq!(le_i64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), Done(&b""[..], -9223372036854775808_i64)); + } + + #[test] + fn be_f32_tests() { + assert_eq!(be_f32(&[0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0_f32)); + assert_eq!(be_f32(&[0x4d, 0x31, 0x1f, 0xd8]), Done(&b""[..], 185728392_f32)); + } + + #[test] + fn be_f64_tests() { + assert_eq!(be_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0_f64)); + assert_eq!(be_f64(&[0x41, 0xa6, 0x23, 0xfb, 0x10, 0x00, 0x00, 0x00]), Done(&b""[..], 185728392_f64)); + } + + #[test] + fn le_f32_tests() { + assert_eq!(le_f32(&[0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0_f32)); + assert_eq!(le_f32(&[0xd8, 0x1f, 0x31, 0x4d]), Done(&b""[..], 185728392_f32)); + } + + #[test] + fn le_f64_tests() { + assert_eq!(le_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Done(&b""[..], 0_f64)); + assert_eq!(le_f64(&[0x00, 0x00, 0x00, 0x10, 0xfb, 0x23, 0xa6, 0x41]), Done(&b""[..], 185728392_f64)); + } + + #[test] + fn hex_u32_tests() { + assert_eq!(hex_u32(&b""[..]), Done(&b""[..], 0)); + assert_eq!(hex_u32(&b"ff"[..]), Done(&b""[..], 255)); + assert_eq!(hex_u32(&b"1be2"[..]), Done(&b""[..], 7138)); + assert_eq!(hex_u32(&b"c5a31be2"[..]), Done(&b""[..], 3315801058)); + assert_eq!(hex_u32(&b"C5A31be2"[..]), Done(&b""[..], 3315801058)); + assert_eq!(hex_u32(&b"00c5a31be2"[..]), Done(&b"e2"[..], 12952347)); + assert_eq!(hex_u32(&b"c5a31be201"[..]), Done(&b"01"[..], 3315801058)); + assert_eq!(hex_u32(&b"ffffffff"[..]), Done(&b""[..], 4294967295)); + assert_eq!(hex_u32(&b"0x1be2"[..]), Done(&b"x1be2"[..], 0)); + } + + #[test] + fn end_of_input() { + let not_over = &b"Hello, world!"[..]; + let is_over = &b""[..]; + named!(eof_test, eof!()); + + let res_not_over = eof_test(not_over); + assert_eq!(res_not_over, Error(error_position!(ErrorKind::Eof, not_over))); + + let res_over = eof_test(is_over); + assert_eq!(res_over, Done(is_over, is_over)); + } + + #[test] + fn configurable_endianness() { + named!(be_tst16, u16!(Endianness::Big)); + named!(le_tst16, u16!(Endianness::Little)); + assert_eq!(be_tst16(&[0x80, 0x00]), Done(&b""[..], 32768_u16)); + assert_eq!(le_tst16(&[0x80, 0x00]), Done(&b""[..], 128_u16)); + + named!(be_tst32, u32!(Endianness::Big)); + named!(le_tst32, u32!(Endianness::Little)); + assert_eq!(be_tst32(&[0x12, 0x00, 0x60, 0x00]), Done(&b""[..], 302014464_u32)); + assert_eq!(le_tst32(&[0x12, 0x00, 0x60, 0x00]), Done(&b""[..], 6291474_u32)); + + named!(be_tst64, u64!(Endianness::Big)); + named!(le_tst64, u64!(Endianness::Little)); + assert_eq!(be_tst64(&[0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]), Done(&b""[..], 1297142246100992000_u64)); + assert_eq!(le_tst64(&[0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]), Done(&b""[..], 36028874334666770_u64)); + + named!(be_tsti16, i16!(Endianness::Big)); + named!(le_tsti16, i16!(Endianness::Little)); + assert_eq!(be_tsti16(&[0x00, 0x80]), Done(&b""[..], 128_i16)); + assert_eq!(le_tsti16(&[0x00, 0x80]), Done(&b""[..], -32768_i16)); + + named!(be_tsti32, i32!(Endianness::Big)); + named!(le_tsti32, i32!(Endianness::Little)); + assert_eq!(be_tsti32(&[0x00, 0x12, 0x60, 0x00]), Done(&b""[..], 1204224_i32)); + assert_eq!(le_tsti32(&[0x00, 0x12, 0x60, 0x00]), Done(&b""[..], 6296064_i32)); + + named!(be_tsti64, i64!(Endianness::Big)); + named!(le_tsti64, i64!(Endianness::Little)); + assert_eq!(be_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]), Done(&b""[..], 71881672479506432_i64)); + assert_eq!(le_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]), Done(&b""[..], 36028874334732032_i64)); + + } + + #[test] + #[cfg(feature = "std")] + fn manual_configurable_endianness_test() { + let x = 1; + let int_parse: Box IResult<&[u8], u16> > = if x == 2 { + Box::new(be_u16) + } else { + Box::new(le_u16) + }; + println!("{:?}", int_parse(&b"3"[..])); + assert_eq!(int_parse(&[0x80, 0x00]), Done(&b""[..], 128_u16)); + } + + #[allow(dead_code)] + fn custom_error(input: &[u8]) -> IResult<&[u8], &[u8], ()> { + fix_error!(input, (), alphanumeric) + } + + #[test] + fn hex_digit_test() { + let empty = &b""[..]; + + let i = &b"0123456789abcdefABCDEF"[..]; + assert_eq!(hex_digit(i), Done(empty, i)); + + let i = &b"g"[..]; + assert_eq!(hex_digit(i), Error(error_position!(ErrorKind::HexDigit,i))); + + let i = &b"G"[..]; + assert_eq!(hex_digit(i), Error(error_position!(ErrorKind::HexDigit,i))); + + assert!(is_hex_digit(b'0')); + assert!(is_hex_digit(b'9')); + assert!(is_hex_digit(b'a')); + assert!(is_hex_digit(b'f')); + assert!(is_hex_digit(b'A')); + assert!(is_hex_digit(b'F')); + assert!(!is_hex_digit(b'g')); + assert!(!is_hex_digit(b'G')); + assert!(!is_hex_digit(b'/')); + assert!(!is_hex_digit(b':')); + assert!(!is_hex_digit(b'@')); + assert!(!is_hex_digit(b'\x60')); + } + + #[test] + fn oct_digit_test() { + let empty = &b""[..]; + + let i = &b"01234567"[..]; + assert_eq!(oct_digit(i), Done(empty, i)); + + let i = &b"8"[..]; + assert_eq!(oct_digit(i), Error(error_position!(ErrorKind::OctDigit,i))); + + assert!(is_oct_digit(b'0')); + assert!(is_oct_digit(b'7')); + assert!(!is_oct_digit(b'8')); + assert!(!is_oct_digit(b'9')); + assert!(!is_oct_digit(b'a')); + assert!(!is_oct_digit(b'A')); + assert!(!is_oct_digit(b'/')); + assert!(!is_oct_digit(b':')); + assert!(!is_oct_digit(b'@')); + assert!(!is_oct_digit(b'\x60')); + } + + #[test] + fn full_line_windows() { + named!(take_full_line<(&[u8], &[u8])>, tuple!(not_line_ending, line_ending)); + let input = b"abc\r\n"; + let output = take_full_line(input); + assert_eq!(output, Done(&b""[..], (&b"abc"[..], &b"\r\n"[..]))); + } + + #[test] + fn full_line_unix() { + named!(take_full_line<(&[u8], &[u8])>, tuple!(not_line_ending, line_ending)); + let input = b"abc\n"; + let output = take_full_line(input); + assert_eq!(output, Done(&b""[..], (&b"abc"[..], &b"\n"[..]))); + } + + #[test] + fn check_windows_lineending() { + let input = b"\r\n"; + let output = line_ending(&input[..]); + assert_eq!(output, Done(&b""[..], &b"\r\n"[..])); + } + + #[test] + fn check_unix_lineending() { + let input = b"\n"; + let output = line_ending(&input[..]); + assert_eq!(output, Done(&b""[..], &b"\n"[..])); + } + + #[test] + fn cr_lf() { + assert_eq!(crlf(&b"\r\na"[..]), Done(&b"a"[..], &b"\r\n"[..])); + assert_eq!(crlf(&b"\r"[..]), Incomplete(Needed::Size(2))); + assert_eq!(crlf(&b"\ra"[..]), Error(error_position!(ErrorKind::CrLf, &b"\ra"[..]))); + + assert_eq!(crlf("\r\na"), Done("a", "\r\n")); + assert_eq!(crlf("\r"), Incomplete(Needed::Size(2))); + assert_eq!(crlf("\ra"), Error(error_position!(ErrorKind::CrLf, "\ra"))); + } + + #[test] + fn end_of_line() { + assert_eq!(eol(&b"\na"[..]), Done(&b"a"[..], &b"\n"[..])); + assert_eq!(eol(&b"\r\na"[..]), Done(&b"a"[..], &b"\r\n"[..])); + assert_eq!(eol(&b"\r"[..]), Incomplete(Needed::Size(2))); + assert_eq!(eol(&b"\ra"[..]), Error(error_position!(ErrorKind::CrLf, &b"\ra"[..]))); + + assert_eq!(eol("\na"), Done("a", "\n")); + assert_eq!(eol("\r\na"), Done("a", "\r\n")); + assert_eq!(eol("\r"), Incomplete(Needed::Size(2))); + assert_eq!(eol("\ra"), Error(error_position!(ErrorKind::CrLf, "\ra"))); + } + + #[test] + #[cfg(feature = "std")] + fn float_test() { + assert_eq!(float(&b"+3.14"[..]), Done(&b""[..], 3.14)); + assert_eq!(float_s(&"3.14"[..]), Done(&""[..], 3.14)); + assert_eq!(double(&b"3.14"[..]), Done(&b""[..], 3.14)); + assert_eq!(double_s(&"3.14"[..]), Done(&""[..], 3.14)); + + assert_eq!(float(&b"-1.234E-12"[..]), Done(&b""[..], -1.234E-12)); + assert_eq!(float_s(&"-1.234E-12"[..]), Done(&""[..], -1.234E-12)); + assert_eq!(double(&b"-1.234E-12"[..]), Done(&b""[..], -1.234E-12)); + assert_eq!(double_s(&"-1.234E-12"[..]), Done(&""[..], -1.234E-12)); + } +} diff --git a/bash-5.1/vendor/nom/src/regexp.rs b/bash-5.1/vendor/nom/src/regexp.rs new file mode 100644 index 0000000..b4a90f4 --- /dev/null +++ b/bash-5.1/vendor/nom/src/regexp.rs @@ -0,0 +1,683 @@ +#[doc(hidden)] +#[macro_export] +macro_rules! regex ( + ($re: ident, $s:expr) => ( + lazy_static! { + static ref $re: ::regex::Regex = ::regex::Regex::new($s).unwrap(); + } + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! regex_bytes ( + ($re: ident, $s:expr) => ( + lazy_static! { + static ref $re: ::regex::bytes::Regex = ::regex::bytes::Regex::new($s).unwrap(); + } + ); +); + + +/// `re_match!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the whole input if a match is found +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_match ( + ($i:expr, $re:expr) => ( + { + use $crate::InputLength; + use $crate::Slice; + let re = ::regex::Regex::new($re).unwrap(); + if re.is_match($i) { + $crate::IResult::Done($i.slice($i.input_len()..), $i) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatch)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_match_static!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the whole input if a match is found. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_match_static ( + ($i:expr, $re:expr) => ( + { + use $crate::InputLength; + use $crate::Slice; + regex!(RE, $re); + if RE.is_match($i) { + $crate::IResult::Done($i.slice($i.input_len()..), $i) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatch)); + res + } + } + ) +); + +/// `re_bytes_match!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the whole input if a match is found +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_bytes_match ( + ($i:expr, $re:expr) => ( + { + use $crate::InputLength; + use $crate::Slice; + let re = ::regex::bytes::Regex::new($re).unwrap(); + if re.is_match($i) { + $crate::IResult::Done($i.slice($i.input_len()..), $i) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatch)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_bytes_match_static!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the whole input if a match is found. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_bytes_match_static ( + ($i:expr, $re:expr) => ( + { + use $crate::InputLength; + use $crate::Slice; + regex_bytes!(RE, $re); + if RE.is_match($i) { + $crate::IResult::Done($i.slice($i.input_len()..), $i) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatch)); + res + } + } + ) +); + +/// `re_find!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the first match +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_find ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::Regex::new($re).unwrap(); + if let Some(m) = re.find($i) { + $crate::IResult::Done($i.slice(m.end()..), $i.slice(m.start()..m.end())) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpFind)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_find_static!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the first match. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_find_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex!(RE, $re); + if let Some(m) = RE.find($i) { + $crate::IResult::Done($i.slice(m.end()..), $i.slice(m.start()..m.end())) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpFind)); + res + } + } + + ) +); + +/// `re_bytes_find!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the first match +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_bytes_find ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::bytes::Regex::new($re).unwrap(); + if let Some(m) = re.find($i) { + $crate::IResult::Done($i.slice(m.end()..), $i.slice(m.start()..m.end())) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpFind)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_bytes_find!(regexp) => &[T] -> IResult<&[T], &[T]>` +/// Returns the first match. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_bytes_find_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex_bytes!(RE, $re); + if let Some(m) = RE.find($i) { + $crate::IResult::Done($i.slice(m.end()..), $i.slice(m.start()..m.end())) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpFind)); + res + } + } + + ) +); + +/// `re_matches!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns all the matched parts +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_matches ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::Regex::new($re).unwrap(); + let v: Vec<&str> = re.find_iter($i).map(|m| $i.slice(m.start()..m.end())).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatches)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_matches_static!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns all the matched parts. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_matches_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex!(RE, $re); + let v: Vec<&str> = RE.find_iter($i).map(|m| $i.slice(m.start()..m.end())).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatches)); + res + } + } + ) +); + +/// `re_bytes_matches!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns all the matched parts +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_bytes_matches ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::bytes::Regex::new($re).unwrap(); + let v: Vec<&[u8]> = re.find_iter($i).map(|m| $i.slice(m.start()..m.end())).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatches)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_bytes_matches_static!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns all the matched parts. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_bytes_matches_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex_bytes!(RE, $re); + let v: Vec<&[u8]> = RE.find_iter($i).map(|m| $i.slice(m.start()..m.end())).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpMatches)); + res + } + } + ) +); + +/// `re_capture!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns the first capture group +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_capture ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::Regex::new($re).unwrap(); + if let Some(c) = re.captures($i) { + let v:Vec<&str> = c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect(); + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_capture_static!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns the first capture group. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_capture_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex!(RE, $re); + if let Some(c) = RE.captures($i) { + let v:Vec<&str> = c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect(); + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +/// `re_bytes_capture!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns the first capture group +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_bytes_capture ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::bytes::Regex::new($re).unwrap(); + if let Some(c) = re.captures($i) { + let v:Vec<&[u8]> = c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect(); + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_bytes_capture_static!(regexp) => &[T] -> IResult<&[T], Vec<&[T]>>` +/// Returns the first capture group. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_bytes_capture_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex_bytes!(RE, $re); + if let Some(c) = RE.captures($i) { + let v:Vec<&[u8]> = c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect(); + let offset = { + let end = v.last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +/// `re_captures!(regexp) => &[T] -> IResult<&[T], Vec>>` +/// Returns all the capture groups +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_captures ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::Regex::new($re).unwrap(); + let v:Vec> = re.captures_iter($i).map(|c| c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect()).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap().last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_captures_static!(regexp) => &[T] -> IResult<&[T], Vec>>` +/// Returns all the capture groups. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_captures_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex!(RE, $re); + let v:Vec> = RE.captures_iter($i).map(|c| c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect()).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap().last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +/// `re_bytes_captures!(regexp) => &[T] -> IResult<&[T], Vec>>` +/// Returns all the capture groups +/// +/// requires the `regexp` feature +#[macro_export] +macro_rules! re_bytes_captures ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + let re = ::regex::bytes::Regex::new($re).unwrap(); + let v:Vec> = re.captures_iter($i).map(|c| c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect()).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap().last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); + +#[cfg(feature = "regexp_macros")] +/// `re_bytes_captures_static!(regexp) => &[T] -> IResult<&[T], Vec>>` +/// Returns all the capture groups. Regular expression calculated at compile time +/// +/// requires the `regexp_macros` feature +#[macro_export] +macro_rules! re_bytes_captures_static ( + ($i:expr, $re:expr) => ( + { + use $crate::Slice; + regex_bytes!(RE, $re); + let v:Vec> = RE.captures_iter($i).map(|c| c.iter().filter(|el| el.is_some()).map(|el| el.unwrap()).map(|m| $i.slice(m.start()..m.end())).collect()).collect(); + if v.len() != 0 { + let offset = { + let end = v.last().unwrap().last().unwrap(); + end.as_ptr() as usize + end.len() - $i.as_ptr() as usize + }; + $crate::IResult::Done($i.slice(offset..), v) + } else { + let res: $crate::IResult<_,_> = $crate::IResult::Error(error_code!($crate::ErrorKind::RegexpCapture)); + res + } + } + ) +); +#[cfg(test)] +mod tests { + use internal::IResult::*; + use util::ErrorKind; + + #[test] + fn re_match() { + named!(rm<&str,&str>, re_match!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm("2015-09-07"), Done("", "2015-09-07")); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpMatch))); + assert_eq!(rm("2015-09-07blah"), Done("", "2015-09-07blah")); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_match_static() { + named!(rm<&str,&str>, re_match_static!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm("2015-09-07"), Done("", "2015-09-07")); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpMatch))); + assert_eq!(rm("2015-09-07blah"), Done("", "2015-09-07blah")); + } + + #[test] + fn re_find() { + named!(rm<&str,&str>, re_find!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm("2015-09-07"), Done("", "2015-09-07")); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpFind))); + assert_eq!(rm("2015-09-07blah"), Done("blah", "2015-09-07")); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_find_static() { + named!(rm<&str,&str>, re_find_static!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm("2015-09-07"), Done("", "2015-09-07")); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpFind))); + assert_eq!(rm("2015-09-07blah"), Done("blah", "2015-09-07")); + } + + #[test] + fn re_matches() { + named!(rm< &str,Vec<&str> >, re_matches!(r"\d{4}-\d{2}-\d{2}")); + assert_eq!(rm("2015-09-07"), Done("", vec!["2015-09-07"])); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpMatches))); + assert_eq!(rm("aaa2015-09-07blah2015-09-09pouet"), Done("pouet", vec!["2015-09-07", "2015-09-09"])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_matches_static() { + named!(rm< &str,Vec<&str> >, re_matches_static!(r"\d{4}-\d{2}-\d{2}")); + assert_eq!(rm("2015-09-07"), Done("", vec!["2015-09-07"])); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpMatches))); + assert_eq!(rm("aaa2015-09-07blah2015-09-09pouet"), Done("pouet", vec!["2015-09-07", "2015-09-09"])); + } + + #[test] + fn re_capture() { + named!(rm< &str,Vec<&str> >, re_capture!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm("blah nom 0.3.11pouet"), Done("pouet", vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"])); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm("hello nom 0.3.11 world regex 0.1.41"), Done(" world regex 0.1.41", vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_capture_static() { + named!(rm< &str,Vec<&str> >, re_capture_static!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm("blah nom 0.3.11pouet"), Done("pouet", vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"])); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm("hello nom 0.3.11 world regex 0.1.41"), Done(" world regex 0.1.41", vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"])); + } + + #[test] + fn re_captures() { + named!(rm< &str,Vec> >, re_captures!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm("blah nom 0.3.11pouet"), Done("pouet", vec![vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"]])); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm("hello nom 0.3.11 world regex 0.1.41 aaa"), Done(" aaa", vec![ + vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"], + vec!["regex 0.1.41", "regex", "0.1.41", "0", "1", "41"], + ])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_captures_static() { + named!(rm< &str,Vec> >, re_captures_static!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm("blah nom 0.3.11pouet"), Done("pouet", vec![vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"]])); + assert_eq!(rm("blah"), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm("hello nom 0.3.11 world regex 0.1.41 aaa"), Done(" aaa", vec![ + vec!["nom 0.3.11", "nom", "0.3.11", "0", "3", "11"], + vec!["regex 0.1.41", "regex", "0.1.41", "0", "1", "41"], + ])); + } + + #[test] + fn re_bytes_match() { + named!(rm, re_bytes_match!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm(&b"2015-09-07"[..]), Done(&b""[..], &b"2015-09-07"[..])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpMatch))); + assert_eq!(rm(&b"2015-09-07blah"[..]), Done(&b""[..], &b"2015-09-07blah"[..])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_bytes_match_static() { + named!(rm, re_bytes_match_static!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm(&b"2015-09-07"[..]), Done(&b""[..], &b"2015-09-07"[..])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpMatch))); + assert_eq!(rm(&b"2015-09-07blah"[..]), Done(&b""[..], &b"2015-09-07blah"[..])); + } + + #[test] + fn re_bytes_find() { + named!(rm, re_bytes_find!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm(&b"2015-09-07"[..]), Done(&b""[..], &b"2015-09-07"[..])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpFind))); + assert_eq!(rm(&b"2015-09-07blah"[..]), Done(&b"blah"[..], &b"2015-09-07"[..])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_bytes_find_static() { + named!(rm, re_bytes_find_static!(r"^\d{4}-\d{2}-\d{2}")); + assert_eq!(rm(&b"2015-09-07"[..]), Done(&b""[..], &b"2015-09-07"[..])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpFind))); + assert_eq!(rm(&b"2015-09-07blah"[..]), Done(&b"blah"[..], &b"2015-09-07"[..])); + } + + #[test] + fn re_bytes_matches() { + named!(rm >, re_bytes_matches!(r"\d{4}-\d{2}-\d{2}")); + assert_eq!(rm(&b"2015-09-07"[..]), Done(&b""[..], vec![&b"2015-09-07"[..]])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpMatches))); + assert_eq!(rm(&b"aaa2015-09-07blah2015-09-09pouet"[..]), Done(&b"pouet"[..], vec![&b"2015-09-07"[..], &b"2015-09-09"[..]])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_bytes_matches_static() { + named!(rm >, re_bytes_matches_static!(r"\d{4}-\d{2}-\d{2}")); + assert_eq!(rm(&b"2015-09-07"[..]), Done(&b""[..], vec![&b"2015-09-07"[..]])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpMatches))); + assert_eq!(rm(&b"aaa2015-09-07blah2015-09-09pouet"[..]), Done(&b"pouet"[..], vec![&b"2015-09-07"[..], &b"2015-09-09"[..]])); + } + + #[test] + fn re_bytes_capture() { + named!(rm >, re_bytes_capture!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm(&b"blah nom 0.3.11pouet"[..]), Done(&b"pouet"[..], vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm(&b"hello nom 0.3.11 world regex 0.1.41"[..]), Done(&b" world regex 0.1.41"[..], vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_bytes_capture_static() { + named!(rm< Vec<&[u8]> >, re_bytes_capture_static!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm(&b"blah nom 0.3.11pouet"[..]), Done(&b"pouet"[..], vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm(&b"hello nom 0.3.11 world regex 0.1.41"[..]), Done(&b" world regex 0.1.41"[..], vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]])); + } + + #[test] + fn re_bytes_captures() { + named!(rm< Vec> >, re_bytes_captures!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm(&b"blah nom 0.3.11pouet"[..]), Done(&b"pouet"[..], vec![vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]]])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm(&b"hello nom 0.3.11 world regex 0.1.41 aaa"[..]), Done(&b" aaa"[..], vec![ + vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]], + vec![&b"regex 0.1.41"[..], &b"regex"[..], &b"0.1.41"[..], &b"0"[..], &b"1"[..], &b"41"[..]], + ])); + } + + #[cfg(feature = "regexp_macros")] + #[test] + fn re_bytes_captures_static() { + named!(rm< Vec> >, re_bytes_captures_static!(r"([[:alpha:]]+)\s+((\d+).(\d+).(\d+))")); + assert_eq!(rm(&b"blah nom 0.3.11pouet"[..]), Done(&b"pouet"[..], vec![vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]]])); + assert_eq!(rm(&b"blah"[..]), Error(error_code!(ErrorKind::RegexpCapture))); + assert_eq!(rm(&b"hello nom 0.3.11 world regex 0.1.41 aaa"[..]), Done(&b" aaa"[..], vec![ + vec![&b"nom 0.3.11"[..], &b"nom"[..], &b"0.3.11"[..], &b"0"[..], &b"3"[..], &b"11"[..]], + vec![&b"regex 0.1.41"[..], &b"regex"[..], &b"0.1.41"[..], &b"0"[..], &b"1"[..], &b"41"[..]], + ])); + } +} diff --git a/bash-5.1/vendor/nom/src/sequence.rs b/bash-5.1/vendor/nom/src/sequence.rs new file mode 100644 index 0000000..0bbefe0 --- /dev/null +++ b/bash-5.1/vendor/nom/src/sequence.rs @@ -0,0 +1,889 @@ +/// `tuple!(I->IResult, I->IResult, ... I->IResult) => I -> IResult` +/// chains parsers and assemble the sub results in a tuple. +/// +/// The input type `I` must implement `nom::InputLength`. +/// +/// This combinator will count how much data is consumed by every child parser +/// and take it into account if there is not enough data +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self, Done, Error}; +/// # #[cfg(feature = "verbose-errors")] +/// # use nom::Err::Position; +/// # use nom::ErrorKind; +/// # use nom::be_u16; +/// // the return type depends of the children parsers +/// named!(parser<&[u8], (u16, &[u8], &[u8]) >, +/// tuple!( +/// be_u16 , +/// take!(3), +/// tag!("fg") +/// ) +/// ); +/// +/// # fn main() { +/// assert_eq!( +/// parser(&b"abcdefgh"[..]), +/// Done( +/// &b"h"[..], +/// (0x6162u16, &b"cde"[..], &b"fg"[..]) +/// ) +/// ); +/// # } +/// ``` +#[macro_export] +macro_rules! tuple ( + ($i:expr, $($rest:tt)*) => ( + { + tuple_parser!($i, 0usize, (), $($rest)*) + } + ); +); + +/// Internal parser, do not use directly +#[doc(hidden)] +#[macro_export] +macro_rules! tuple_parser ( + ($i:expr, $consumed:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => ( + tuple_parser!($i, $consumed, ($($parsed),*), call!($e), $($rest)*); + ); + ($i:expr, $consumed:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => + $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,o) => { + let i_ = i.clone(); + tuple_parser!(i_, + $consumed + ($crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&i)), (o), $($rest)*) + } + } + } + ); + ($i:expr, $consumed:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => + $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,o) => { + let i_ = i.clone(); + tuple_parser!(i_, + $consumed + ($crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&i)), ($($parsed)* , o), $($rest)*) + } + } + } + ); + ($i:expr, $consumed:expr, ($($parsed:tt),*), $e:ident) => ( + tuple_parser!($i, $consumed, ($($parsed),*), call!($e)); + ); + ($i:expr, $consumed:expr, (), $submac:ident!( $($args:tt)* )) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => + $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,o) => { + $crate::IResult::Done(i, (o)) + } + } + } + ); + ($i:expr, $consumed:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => + $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,o) => { + $crate::IResult::Done(i, ($($parsed),* , o)) + } + } + } + ); + ($i:expr, $consumed:expr, ($($parsed:expr),*)) => ( + { + $crate::IResult::Done($i, ($($parsed),*)) + } + ); +); + +/// `pair!(I -> IResult, I -> IResult) => I -> IResult` +/// pair(X,Y), returns (x,y) +/// +#[macro_export] +macro_rules! pair( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) + } + ); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + pair!($i, $submac!($($args)*), call!($g)); + ); + + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + pair!($i, call!($f), $submac!($($args)*)); + ); + + ($i:expr, $f:expr, $g:expr) => ( + pair!($i, call!($f), call!($g)); + ); +); + +/// `separated_pair!(I -> IResult, I -> IResult, I -> IResult) => I -> IResult` +/// separated_pair(X,sep,Y) returns (x,y) +#[macro_export] +macro_rules! separated_pair( + ($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => ( + { + match tuple_parser!($i, 0usize, (), $submac!($($args)*), $($rest)*) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i1, (o1, _, o2)) => { + $crate::IResult::Done(i1, (o1, o2)) + } + } + } + ); + + ($i:expr, $f:expr, $($rest:tt)+) => ( + separated_pair!($i, call!($f), $($rest)*); + ); +); + +/// `preceded!(I -> IResult, I -> IResult) => I -> IResult` +/// preceded(opening, X) returns X +#[macro_export] +macro_rules! preceded( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + match tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(remaining, (_,o)) => { + $crate::IResult::Done(remaining, o) + } + } + } + ); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + preceded!($i, $submac!($($args)*), call!($g)); + ); + + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + preceded!($i, call!($f), $submac!($($args)*)); + ); + + ($i:expr, $f:expr, $g:expr) => ( + preceded!($i, call!($f), call!($g)); + ); +); + +/// `terminated!(I -> IResult, I -> IResult) => I -> IResult` +/// terminated(X, closing) returns X +#[macro_export] +macro_rules! terminated( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + match tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(remaining, (o,_)) => { + $crate::IResult::Done(remaining, o) + } + } + } + ); + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + terminated!($i, $submac!($($args)*), call!($g)); + ); + + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + terminated!($i, call!($f), $submac!($($args)*)); + ); + + ($i:expr, $f:expr, $g:expr) => ( + terminated!($i, call!($f), call!($g)); + ); +); + +/// `delimited!(I -> IResult, I -> IResult, I -> IResult) => I -> IResult` +/// delimited(opening, X, closing) returns X +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self, Done}; +/// named!(bracketed, +/// delimited!( +/// tag!("("), +/// take_until!(")"), +/// tag!(")") +/// ) +/// ); +/// +/// # fn main() { +/// let input = &b"(test)"[..]; +/// assert_eq!(bracketed(input), Done(&b""[..], &b"test"[..])); +/// # } +/// ``` +#[macro_export] +macro_rules! delimited( + ($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => ( + { + match tuple_parser!($i, 0usize, (), $submac!($($args)*), $($rest)*) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i1, (_, o, _)) => { + $crate::IResult::Done(i1, o) + } + } + } + ); + + ($i:expr, $f:expr, $($rest:tt)+) => ( + delimited!($i, call!($f), $($rest)*); + ); +); + +/// `do_parse!(I->IResult >> I->IResult >> ... I->IResult , ( O ) ) => I -> IResult` +/// do_parse applies sub parsers in a sequence. +/// it can store intermediary results and make them available +/// for later parsers +/// +/// The input type `I` must implement `nom::InputLength`. +/// +/// This combinator will count how much data is consumed by every child parser +/// and take it into account if there is not enough data +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self, Done, Incomplete}; +/// # use nom::Needed; +/// use nom::be_u8; +/// +/// // this parser implements a common pattern in binary formats, +/// // the TAG-LENGTH-VALUE, where you first recognize a specific +/// // byte slice, then the next bytes indicate the length of +/// // the data, then you take that slice and return it +/// // +/// // here, we match the tag 42, take the length in the next byte +/// // and store it in `length`, then use `take!` with `length` +/// // to obtain the subslice that we store in `bytes`, then return +/// // `bytes` +/// named!(tag_length_value, +/// do_parse!( +/// tag!( &[ 42u8 ][..] ) >> +/// length: be_u8 >> +/// bytes: take!(length) >> +/// (bytes) +/// ) +/// ); +/// +/// # fn main() { +/// let a: Vec = vec!(42, 2, 3, 4, 5); +/// let result_a: Vec = vec!(3, 4); +/// let rest_a: Vec = vec!(5); +/// assert_eq!(tag_length_value(&a[..]), Done(&rest_a[..], &result_a[..])); +/// +/// // here, the length is 5, but there are only 3 bytes afterwards (3, 4 and 5), +/// // so the parser will tell you that you need 7 bytes: one for the tag, +/// // one for the length, then 5 bytes +/// let b: Vec = vec!(42, 5, 3, 4, 5); +/// assert_eq!(tag_length_value(&b[..]), Incomplete(Needed::Size(7))); +/// # } +/// ``` +/// +/// the result is a tuple, so you can return multiple sub results, like +/// this: +/// `do_parse!(I->IResult >> I->IResult >> ... I->IResult , ( O, P ) ) => I -> IResult` +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self, Done, Incomplete}; +/// # use nom::Needed; +/// use nom::be_u8; +/// named!(tag_length_value<(u8, &[u8])>, +/// do_parse!( +/// tag!( &[ 42u8 ][..] ) >> +/// length: be_u8 >> +/// bytes: take!(length) >> +/// (length, bytes) +/// ) +/// ); +/// +/// # fn main() { +/// # } +/// ``` +/// +#[macro_export] +macro_rules! do_parse ( + (__impl $i:expr, $consumed:expr, ( $($rest:expr),* )) => ( + $crate::IResult::Done($i, ( $($rest),* )) + ); + + (__impl $i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ) => ( + do_parse!(__impl $i, $consumed, $submac!( $($args)* )) + ); + + (__impl $i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ) => ( + compiler_error!("do_parse is missing the return value. A do_parse call must end + with a return value between parenthesis, as follows: + + do_parse!( + a: tag!(\"abcd\") >> + b: tag!(\"efgh\") >> + + ( Value { a: a, b: b } ) + "); + ); + + (__impl $i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)* ) => ( + compiler_error!("do_parse uses >> as separator, not ~"); + ); + (__impl $i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ~ $($rest:tt)* ) => ( + compiler_error!("do_parse uses >> as separator, not ~"); + ); + (__impl $i:expr, $consumed:expr, $field:ident : $e:ident ~ $($rest:tt)*) => ( + do_parse!(__impl $i, $consumed, $field: call!($e) ~ $($rest)*); + ); + (__impl $i:expr, $consumed:expr, $e:ident ~ $($rest:tt)*) => ( + do_parse!(__impl $i, $consumed, call!($e) ~ $($rest)*); + ); + + (__impl $i:expr, $consumed:expr, $e:ident >> $($rest:tt)*) => ( + do_parse!(__impl $i, $consumed, call!($e) >> $($rest)*); + ); + (__impl $i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,_) => { + let i_ = i.clone(); + do_parse!(__impl i_, + $consumed + ($crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&i)), $($rest)*) + }, + } + } + ); + + (__impl $i:expr, $consumed:expr, $field:ident : $e:ident >> $($rest:tt)*) => ( + do_parse!(__impl $i, $consumed, $field: call!($e) >> $($rest)*); + ); + + (__impl $i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => ( + { + let i_ = $i.clone(); + match $submac!(i_, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,o) => { + let $field = o; + let i_ = i.clone(); + do_parse!(__impl i_, + $consumed + ($crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&i)), $($rest)*) + }, + } + } + ); + + // ending the chain + (__impl $i:expr, $consumed:expr, $e:ident >> ( $($rest:tt)* )) => ( + do_parse!(__impl $i, $consumed, call!($e) >> ( $($rest)* )); + ); + + (__impl $i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) >> ( $($rest:tt)* )) => ( + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,_) => { + $crate::IResult::Done(i, ( $($rest)* )) + }, + } + ); + + (__impl $i:expr, $consumed:expr, $field:ident : $e:ident >> ( $($rest:tt)* )) => ( + do_parse!(__impl $i, $consumed, $field: call!($e) >> ( $($rest)* ) ); + ); + + (__impl $i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> ( $($rest:tt)* )) => ( + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => { + let (needed,overflowed) = $consumed.overflowing_add(i); + match overflowed { + true => $crate::IResult::Incomplete($crate::Needed::Unknown), + false => $crate::IResult::Incomplete($crate::Needed::Size(needed)), + } + }, + $crate::IResult::Done(i,o) => { + let $field = o; + $crate::IResult::Done(i, ( $($rest)* )) + }, + } + ); + + ($i:expr, $($rest:tt)*) => ( + { + do_parse!(__impl $i, 0usize, $($rest)*) + } + ); + ($submac:ident!( $($args:tt)* ) >> $($rest:tt)* ) => ( + compiler_error!("if you are using do_parse outside of a named! macro, you must + pass the input data as first argument, like this: + + let res = do_parse!(input, + a: tag!(\"abcd\") >> + b: tag!(\"efgh\") >> + ( Value { a: a, b: b } ) + );"); + ); + ($e:ident! >> $($rest:tt)* ) => ( + do_parse!( call!($e) >> $($rest)*); + ); +); + +#[cfg(test)] +mod tests { + use internal::{Needed,IResult}; + use internal::IResult::*; + use util::ErrorKind; + use nom::be_u16; + + #[cfg(feature = "verbose-errors")] + use verbose_errors::Err; + + // reproduce the tag and take macros, because of module import order + macro_rules! tag ( + ($i:expr, $inp: expr) => ( + { + #[inline(always)] + fn as_bytes(b: &T) -> &[u8] { + b.as_bytes() + } + + let expected = $inp; + let bytes = as_bytes(&expected); + + tag_bytes!($i,bytes) + } + ); + ); + + macro_rules! tag_bytes ( + ($i:expr, $bytes: expr) => ( + { + use std::cmp::min; + let len = $i.len(); + let blen = $bytes.len(); + let m = min(len, blen); + let reduced = &$i[..m]; + let b = &$bytes[..m]; + + let res: $crate::IResult<_,_> = if reduced != b { + $crate::IResult::Error(error_position!($crate::ErrorKind::Tag, $i)) + } else if m < blen { + $crate::IResult::Incomplete($crate::Needed::Size(blen)) + } else { + $crate::IResult::Done(&$i[blen..], reduced) + }; + res + } + ); + ); + + macro_rules! take ( + ($i:expr, $count:expr) => ( + { + let cnt = $count as usize; + let res:$crate::IResult<&[u8],&[u8]> = if $i.len() < cnt { + $crate::IResult::Incomplete($crate::Needed::Size(cnt)) + } else { + $crate::IResult::Done(&$i[cnt..],&$i[0..cnt]) + }; + res + } + ); + ); + + #[derive(PartialEq,Eq,Debug)] + struct B { + a: u8, + b: u8 + } + + #[derive(PartialEq,Eq,Debug)] + struct C { + a: u8, + b: Option + } + + #[cfg(feature = "verbose-errors")] + use util::{error_to_list, add_error_pattern, print_error}; + + #[cfg(feature = "verbose-errors")] + fn error_to_string

(e: &Err

) -> &'static str { + let v:Vec = error_to_list(e); + // do it this way if you can use slice patterns + /* + match &v[..] { + [ErrorKind::Custom(42), ErrorKind::Tag] => "missing `ijkl` tag", + [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag] => "missing `mnop` tag after `ijkl`", + _ => "unrecognized error" + } + */ + if &v[..] == [ErrorKind::Custom(42),ErrorKind::Tag] { + "missing `ijkl` tag" + } else if &v[..] == [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag] { + "missing `mnop` tag after `ijkl`" + } else { + "unrecognized error" + } + } + + // do it this way if you can use box patterns + /*use std::str; + fn error_to_string(e:Err) -> String + match e { + NodePosition(ErrorKind::Custom(42), i1, box Position(ErrorKind::Tag, i2)) => { + format!("missing `ijkl` tag, found '{}' instead", str::from_utf8(i2).unwrap()) + }, + NodePosition(ErrorKind::Custom(42), i1, box NodePosition(ErrorKind::Custom(128), i2, box Position(ErrorKind::Tag, i3))) => { + format!("missing `mnop` tag after `ijkl`, found '{}' instead", str::from_utf8(i3).unwrap()) + }, + _ => "unrecognized error".to_string() + } + }*/ + + #[cfg(feature = "verbose-errors")] + use std::collections; + + #[cfg(feature = "verbose-errors")] + #[test] + fn err() { + named!(err_test, alt!( + tag!("abcd") | + preceded!(tag!("efgh"), return_error!(ErrorKind::Custom(42), + do_parse!( + tag!("ijkl") >> + res: return_error!(ErrorKind::Custom(128), tag!("mnop")) >> + (res) + ) + ) + ) + )); + let a = &b"efghblah"[..]; + let b = &b"efghijklblah"[..]; + let c = &b"efghijklmnop"[..]; + + let blah = &b"blah"[..]; + + let res_a = err_test(a); + let res_b = err_test(b); + let res_c = err_test(c); + assert_eq!(res_a, Error(error_node_position!(ErrorKind::Custom(42), blah, error_position!(ErrorKind::Tag, blah)))); + assert_eq!(res_b, Error(error_node_position!(ErrorKind::Custom(42), &b"ijklblah"[..], error_node_position!(ErrorKind::Custom(128), blah, error_position!(ErrorKind::Tag, blah))))); + assert_eq!(res_c, Done(&b""[..], &b"mnop"[..])); + + // Merr-like error matching + let mut err_map = collections::HashMap::new(); + assert!(add_error_pattern(&mut err_map, err_test(&b"efghpouet"[..]), "missing `ijkl` tag")); + assert!(add_error_pattern(&mut err_map, err_test(&b"efghijklpouet"[..]), "missing `mnop` tag after `ijkl`")); + + let res_a2 = res_a.clone(); + match res_a { + Error(e) => { + assert_eq!(error_to_list(&e), [ErrorKind::Custom(42), ErrorKind::Tag]); + assert_eq!(error_to_string(&e), "missing `ijkl` tag"); + assert_eq!(err_map.get(&error_to_list(&e)), Some(&"missing `ijkl` tag")); + }, + _ => panic!() + }; + + let res_b2 = res_b.clone(); + match res_b { + Error(e) => { + assert_eq!(error_to_list(&e), [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag]); + assert_eq!(error_to_string(&e), "missing `mnop` tag after `ijkl`"); + assert_eq!(err_map.get(&error_to_list(&e)), Some(&"missing `mnop` tag after `ijkl`")); + }, + _ => panic!() + }; + + print_error(a, res_a2); + print_error(b, res_b2); + } + + #[allow(unused_variables)] + #[test] + fn add_err() { + named!(err_test, + preceded!(tag!("efgh"), add_return_error!(ErrorKind::Custom(42), + do_parse!( + tag!("ijkl") >> + res: add_return_error!(ErrorKind::Custom(128), tag!("mnop")) >> + (res) + ) + ) + )); + let a = &b"efghblah"[..]; + let b = &b"efghijklblah"[..]; + let c = &b"efghijklmnop"[..]; + + let blah = &b"blah"[..]; + + let res_a = err_test(a); + let res_b = err_test(b); + let res_c = err_test(c); + assert_eq!(res_a, Error(error_node_position!(ErrorKind::Custom(42), blah, error_position!(ErrorKind::Tag, blah)))); + assert_eq!(res_b, Error(error_node_position!(ErrorKind::Custom(42), &b"ijklblah"[..], error_node_position!(ErrorKind::Custom(128), blah, error_position!(ErrorKind::Tag, blah))))); + assert_eq!(res_c, Done(&b""[..], &b"mnop"[..])); + } + + #[test] + fn complete() { + named!(err_test, + do_parse!( + tag!("ijkl") >> + res: complete!(tag!("mnop")) >> + (res) + ) + ); + let a = &b"ijklmn"[..]; + + let res_a = err_test(a); + assert_eq!(res_a, Error(error_position!(ErrorKind::Complete, &b"mn"[..]))); + } + + #[test] + fn pair() { + named!( tag_abc, tag!("abc") ); + named!( tag_def, tag!("def") ); + named!( pair_abc_def<&[u8],(&[u8], &[u8])>, pair!(tag_abc, tag_def) ); + + assert_eq!(pair_abc_def(&b"abcdefghijkl"[..]), Done(&b"ghijkl"[..], (&b"abc"[..], &b"def"[..]))); + assert_eq!(pair_abc_def(&b"ab"[..]), Incomplete(Needed::Size(3))); + assert_eq!(pair_abc_def(&b"abcd"[..]), Incomplete(Needed::Size(6))); + assert_eq!(pair_abc_def(&b"xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + assert_eq!(pair_abc_def(&b"xxxdef"[..]), Error(error_position!(ErrorKind::Tag, &b"xxxdef"[..]))); + assert_eq!(pair_abc_def(&b"abcxxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + } + + #[test] + fn separated_pair() { + named!( tag_abc, tag!("abc") ); + named!( tag_def, tag!("def") ); + named!( tag_separator, tag!(",") ); + named!( sep_pair_abc_def<&[u8],(&[u8], &[u8])>, separated_pair!(tag_abc, tag_separator, tag_def) ); + + assert_eq!(sep_pair_abc_def(&b"abc,defghijkl"[..]), Done(&b"ghijkl"[..], (&b"abc"[..], &b"def"[..]))); + assert_eq!(sep_pair_abc_def(&b"ab"[..]), Incomplete(Needed::Size(3))); + assert_eq!(sep_pair_abc_def(&b"abc,d"[..]), Incomplete(Needed::Size(7))); + assert_eq!(sep_pair_abc_def(&b"xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + assert_eq!(sep_pair_abc_def(&b"xxx,def"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx,def"[..]))); + assert_eq!(sep_pair_abc_def(&b"abc,xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + } + + #[test] + fn preceded() { + named!( tag_abcd, tag!("abcd") ); + named!( tag_efgh, tag!("efgh") ); + named!( preceded_abcd_efgh<&[u8], &[u8]>, preceded!(tag_abcd, tag_efgh) ); + + assert_eq!(preceded_abcd_efgh(&b"abcdefghijkl"[..]), Done(&b"ijkl"[..], &b"efgh"[..])); + assert_eq!(preceded_abcd_efgh(&b"ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(preceded_abcd_efgh(&b"abcde"[..]), Incomplete(Needed::Size(8))); + assert_eq!(preceded_abcd_efgh(&b"xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + assert_eq!(preceded_abcd_efgh(&b"xxxxdef"[..]), Error(error_position!(ErrorKind::Tag, &b"xxxxdef"[..]))); + assert_eq!(preceded_abcd_efgh(&b"abcdxxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + } + + #[test] + fn terminated() { + named!( tag_abcd, tag!("abcd") ); + named!( tag_efgh, tag!("efgh") ); + named!( terminated_abcd_efgh<&[u8], &[u8]>, terminated!(tag_abcd, tag_efgh) ); + + assert_eq!(terminated_abcd_efgh(&b"abcdefghijkl"[..]), Done(&b"ijkl"[..], &b"abcd"[..])); + assert_eq!(terminated_abcd_efgh(&b"ab"[..]), Incomplete(Needed::Size(4))); + assert_eq!(terminated_abcd_efgh(&b"abcde"[..]), Incomplete(Needed::Size(8))); + assert_eq!(terminated_abcd_efgh(&b"xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + assert_eq!(terminated_abcd_efgh(&b"xxxxdef"[..]), Error(error_position!(ErrorKind::Tag, &b"xxxxdef"[..]))); + assert_eq!(terminated_abcd_efgh(&b"abcdxxxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxxx"[..]))); + } + + #[test] + fn delimited() { + named!( tag_abc, tag!("abc") ); + named!( tag_def, tag!("def") ); + named!( tag_ghi, tag!("ghi") ); + named!( delimited_abc_def_ghi<&[u8], &[u8]>, delimited!(tag_abc, tag_def, tag_ghi) ); + + assert_eq!(delimited_abc_def_ghi(&b"abcdefghijkl"[..]), Done(&b"jkl"[..], &b"def"[..])); + assert_eq!(delimited_abc_def_ghi(&b"ab"[..]), Incomplete(Needed::Size(3))); + assert_eq!(delimited_abc_def_ghi(&b"abcde"[..]), Incomplete(Needed::Size(6))); + assert_eq!(delimited_abc_def_ghi(&b"abcdefgh"[..]), Incomplete(Needed::Size(9))); + assert_eq!(delimited_abc_def_ghi(&b"xxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + assert_eq!(delimited_abc_def_ghi(&b"xxxdefghi"[..]), Error(error_position!(ErrorKind::Tag, &b"xxxdefghi"[..]))); + assert_eq!(delimited_abc_def_ghi(&b"abcxxxghi"[..]), Error(error_position!(ErrorKind::Tag, &b"xxxghi"[..]))); + assert_eq!(delimited_abc_def_ghi(&b"abcdefxxx"[..]), Error(error_position!(ErrorKind::Tag, &b"xxx"[..]))); + } + + #[test] + fn tuple_test() { + named!(tuple_3<&[u8], (u16, &[u8], &[u8]) >, + tuple!( be_u16 , take!(3), tag!("fg") ) ); + + assert_eq!(tuple_3(&b"abcdefgh"[..]), Done(&b"h"[..], (0x6162u16, &b"cde"[..], &b"fg"[..]))); + assert_eq!(tuple_3(&b"abcd"[..]), Incomplete(Needed::Size(5))); + assert_eq!(tuple_3(&b"abcde"[..]), Incomplete(Needed::Size(7))); + assert_eq!(tuple_3(&b"abcdejk"[..]), Error(error_position!(ErrorKind::Tag, &b"jk"[..]))); + } + + #[test] + fn do_parse() { + fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) }; + fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) }; + + //trace_macros!(true); + named!(do_parser<&[u8], (u8, u8)>, + do_parse!( + tag!("abcd") >> + opt!(tag!("abcd")) >> + aa: ret_int1 >> + tag!("efgh") >> + bb: ret_int2 >> + tag!("efgh") >> + (aa, bb) + ) + ); + //named!(do_parser<&[u8], (u8, u8)>, + // do_parse!( + // tag!("abcd") >> aa: ret_int1 >> tag!("efgh") >> bb: ret_int2 >> tag!("efgh") >> (aa, bb) + // ) + //); + + //trace_macros!(false); + + assert_eq!(do_parser(&b"abcdabcdefghefghX"[..]), Done(&b"X"[..], (1, 2))); + assert_eq!(do_parser(&b"abcdefghefghX"[..]), Done(&b"X"[..], (1, 2))); + assert_eq!(do_parser(&b"abcdab"[..]), Incomplete(Needed::Size(8))); + assert_eq!(do_parser(&b"abcdefghef"[..]), Incomplete(Needed::Size(12))); + } + + #[test] + fn do_parse_dependency() { + use nom::be_u8; + + named!(length_value, + do_parse!( + length: be_u8 >> + bytes: take!(length) >> + (bytes) + ) + ); + + let a = [2u8, 3, 4, 5]; + let res_a = [3u8, 4]; + assert_eq!(length_value(&a[..]), Done(&a[3..], &res_a[..])); + let b = [5u8, 3, 4, 5]; + assert_eq!(length_value(&b[..]), Incomplete(Needed::Size(6))); + } + + /* + named!(does_not_compile, + do_parse!( + length: be_u8 >> + bytes: take!(length) + ) + ); + named!(does_not_compile_either, + do_parse!( + length: be_u8 ~ + bytes: take!(length) ~ + ( () ) + ) + ); + fn still_does_not_compile() { + let data = b"abcd"; + + let res = do_parse!( + tag!("abcd") >> + tag!("efgh") >> + ( () ) + ); + } + */ +} diff --git a/bash-5.1/vendor/nom/src/simple_errors.rs b/bash-5.1/vendor/nom/src/simple_errors.rs new file mode 100644 index 0000000..04bddd4 --- /dev/null +++ b/bash-5.1/vendor/nom/src/simple_errors.rs @@ -0,0 +1,153 @@ +//! Error management +//! +//! there are two ways to handle errors in nom. The first one, +//! activated by default, uses the `nom::ErrorKind` enum +//! in the error branch of `IResult`. This enum can hold either +//! a parser specific error code, or a custom error type you +//! specify. +//! +//! If you need more advanced error management, you can activate +//! the "verbose-errors" compilation feature, which will give you +//! the error system available in nom 1.0. The verbose errors +//! accumulate error codes and positions as you backtrack through +//! the parser tree. From there, you can precisely identify which +//! parts of the input triggered the error case. +//! +//! Please note that the verbose error management is a bit slower +//! than the simple one. +use util::ErrorKind; +use internal::{IResult, IError}; +use internal::IResult::*; + +pub type Err = ErrorKind; + +impl IResult { + /// Maps a `IResult` to `IResult` by appling a function + /// to a contained `Error` value, leaving `Done` and `Incomplete` value + /// untouched. + #[inline] + pub fn map_err(self, f: F) -> IResult + where F: FnOnce(Err) -> Err { + match self { + Error(e) => Error(f(e)), + Incomplete(n) => Incomplete(n), + Done(i, o) => Done(i, o), + } + } + + /// Unwrap the contained `Error(E)` value, or panic if the `IResult` is not + /// `Error`. + pub fn unwrap_err(self) -> Err { + match self { + Error(e) => e, + Done(_, _) => panic!("unwrap_err() called on an IResult that is Done"), + Incomplete(_) => panic!("unwrap_err() called on an IResult that is Incomplete"), + } + } + + /// Convert the IResult to a std::result::Result + pub fn to_full_result(self) -> Result> { + match self { + Done(_, o) => Ok(o), + Incomplete(n) => Err(IError::Incomplete(n)), + Error(e) => Err(IError::Error(e)) + } + } + + /// Convert the IResult to a std::result::Result, or panic if the `IResult` is `Incomplete` + pub fn to_result(self) -> Result> { + match self { + Done(_, o) => Ok(o), + Error(e) => Err(e), + Incomplete(_) => panic!("to_result() called on an IResult that is Incomplete") + } + } +} + +#[cfg(feature = "std")] +use std::any::Any; +#[cfg(feature = "std")] +use std::{error,fmt}; +#[cfg(feature = "std")] +impl error::Error for Err { + fn description(&self) -> &str { + self.description() + } +} + +#[cfg(feature = "std")] +impl fmt::Display for Err { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.description()) + } +} + +/// translate parser result from IResult to IResult with a custom type +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use std::collections; +/// # use nom::IResult::Error; +/// # use nom::ErrorKind; +/// # fn main() { +/// // will add a Custom(42) error to the error chain +/// named!(err_test, add_return_error!(ErrorKind::Custom(42), tag!("abcd"))); +/// // Convert to IREsult<&[u8], &[u8], &str> +/// named!(parser<&[u8], &[u8], &str>, add_return_error!(ErrorKind::Custom("custom error message"), fix_error!(&str, err_test))); +/// +/// let a = &b"efghblah"[..]; +/// let res_a = parser(a); +/// assert_eq!(res_a, Error(error_node_position!( ErrorKind::Custom("custom error message"), a, Position(ErrorKind::Fix, a)))); +/// # } +/// ``` +#[macro_export] +macro_rules! fix_error ( + ($i:expr, $t:ty, $submac:ident!( $($args:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(_) => { + let e: $crate::ErrorKind<$t> = $crate::ErrorKind::Fix; + $crate::IResult::Error(e) + } + } + } + ); + ($i:expr, $t:ty, $f:expr) => ( + fix_error!($i, $t, call!($f)); + ); +); + +/// `flat_map!(R -> IResult, S -> IResult) => R -> IResult` +/// +/// combines a parser R -> IResult and +/// a parser S -> IResult to return another +/// parser R -> IResult +#[macro_export] +macro_rules! flat_map( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)), + $crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(ref i2)) => $crate::IResult::Incomplete($crate::Needed::Size(*i2)), + $crate::IResult::Done(_, o2) => $crate::IResult::Done(i, o2) + } + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + flat_map!($i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $f:expr, $g:expr) => ( + flat_map!($i, call!($f), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + flat_map!($i, call!($f), $submac!($($args)*)); + ); +); diff --git a/bash-5.1/vendor/nom/src/str.rs b/bash-5.1/vendor/nom/src/str.rs new file mode 100644 index 0000000..4f8643b --- /dev/null +++ b/bash-5.1/vendor/nom/src/str.rs @@ -0,0 +1,658 @@ +//! Parsers and helper functions operating on strings, especially useful when writing parsers for +//! text-based formats. + +/// `tag_s!(&str) => &str -> IResult<&str, &str>` +/// declares a string as a suite to recognize +/// +/// consumes the recognized characters +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self,Done}; +/// # fn main() { +/// fn test(input: &str) -> IResult<&str, &str> { +/// tag_s!(input, "abcd") +/// } +/// let r = test("abcdefgh"); +/// assert_eq!(r, Done("efgh", "abcd")); +/// # } +/// ``` +#[macro_export] +macro_rules! tag_s ( + ($i:expr, $tag: expr) => ( + { + tag!($i, $tag) + } + ); +); + +/// `tag_no_case_s!(&str) => &str -> IResult<&str, &str>` +/// declares a case-insensitive string as a suite to recognize +/// +/// consumes the recognized characters +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::{self,Done}; +/// # fn main() { +/// fn test(input: &str) -> IResult<&str, &str> { +/// tag_no_case_s!(input, "ABcd") +/// } +/// let r = test("aBCdefgh"); +/// assert_eq!(r, Done("efgh", "aBCd")); +/// # } +/// ``` +#[macro_export] +macro_rules! tag_no_case_s ( + ($i:expr, $tag: expr) => ( + { + tag_no_case!($i, $tag) + } + ); +); + +/// `take_s!(nb) => &str -> IResult<&str, &str>` +/// generates a parser consuming the specified number of characters +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// // Desmond parser +/// named!(take5<&str,&str>, take_s!( 5 ) ); +/// +/// let a = "abcdefgh"; +/// +/// assert_eq!(take5(a), Done("fgh", "abcde")); +/// +/// let b = "12345"; +/// +/// assert_eq!(take5(b), Done("", "12345")); +/// # } +/// ``` +#[macro_export] +macro_rules! take_s ( + ($i:expr, $count:expr) => ( + { + let input = $i; + let cnt = $count as usize; + take!(input, cnt) + } + ); +); + + +/// `is_not_s!(&str) => &str -> IResult<&str, &str>` +/// returns the longest list of characters that do not appear in the provided array +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!( not_space<&str,&str>, is_not_s!( " \t\r\n" ) ); +/// +/// let r = not_space("abcdefgh\nijkl"); +/// assert_eq!(r, Done("\nijkl", "abcdefgh")); +/// # } +/// ``` +#[macro_export] +macro_rules! is_not_s ( + ($input:expr, $arr:expr) => ( + { + is_not!($input, $arr) + } + ); +); + +/// `is_a_s!(&str) => &str -> IResult<&str, &str>` +/// returns the longest list of characters that appear in the provided array +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(abcd<&str, &str>, is_a_s!( "abcd" )); +/// +/// let r1 = abcd("aaaaefgh"); +/// assert_eq!(r1, Done("efgh", "aaaa")); +/// +/// let r2 = abcd("dcbaefgh"); +/// assert_eq!(r2, Done("efgh", "dcba")); +/// # } +/// ``` +#[macro_export] +macro_rules! is_a_s ( + ($input:expr, $arr:expr) => ( + { + is_a!($input, $arr) + } + ); +); + + +/// `take_while_s!(char -> bool) => &str -> IResult<&str, &str>` +/// returns the longest list of characters until the provided function fails. +/// +/// The argument is either a function `char -> bool` or a macro returning a `bool +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::is_alphanumeric; +/// # fn main() { +/// fn alphabetic(chr: char) -> bool { (chr >= 0x41 as char && chr <= 0x5A as char) || (chr >= 0x61 as char && chr <= 0x7A as char) } +/// named!( alpha<&str,&str>, take_while_s!( alphabetic ) ); +/// +/// let r = alpha("abcd\nefgh"); +/// assert_eq!(r, Done("\nefgh", "abcd")); +/// # } +/// ``` +#[macro_export] +macro_rules! take_while_s ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + take_while!($input, $submac!($($args)*)) + } + ); + ($input:expr, $f:expr) => ( + take_while_s!($input, call!($f)); + ); +); + +/// `take_while1_s!(char -> bool) => &str -> IResult<&str, &str>` +/// returns the longest (non empty) list of characters until the provided function fails. +/// +/// The argument is either a function `char -> bool` or a macro returning a `bool` +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # use nom::is_alphanumeric; +/// # fn main() { +/// fn alphabetic(chr: char) -> bool { (chr >= 0x41 as char && chr <= 0x5A as char) || (chr >= 0x61 as char && chr <= 0x7A as char) } +/// named!( alpha<&str,&str>, take_while1_s!( alphabetic ) ); +/// +/// let r = alpha("abcd\nefgh"); +/// assert_eq!(r, Done("\nefgh", "abcd")); +/// # } +/// ``` +#[macro_export] +macro_rules! take_while1_s ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + take_while1!($input, $submac!($($args)*)) + ); + ($input:expr, $f:expr) => ( + take_while1_s!($input, call!($f)); + ); +); + + +/// `take_till_s!(char -> bool) => &str -> IResult<&str, &str>` +/// returns the longest list of characters until the provided function succeeds +/// +/// The argument is either a function `char -> bool` or a macro returning a `bool +#[macro_export] +macro_rules! take_till_s ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + take_till!($input, $submac!($($args)*)) + } + ); + ($input:expr, $f:expr) => ( + take_till_s!($input, call!($f)); + ); +); + +/// `take_till1_s!(char -> bool) => &str -> IResult<&str, &str>` +/// returns the longest non empty list of characters until the provided function succeeds +/// +/// The argument is either a function `char -> bool` or a macro returning a `bool +#[macro_export] +macro_rules! take_till1_s ( + ($input:expr, $submac:ident!( $($args:tt)* )) => ( + { + take_till1!($input, $submac!($($args)*)) + } + ); + ($input:expr, $f:expr) => ( + take_till1_s!($input, call!($f)); + ); +); + +/// `take_until_and_consume_s!(&str) => &str -> IResult<&str, &str>` +/// generates a parser consuming all chars until the specified string is found and consumes it +#[macro_export] +macro_rules! take_until_and_consume_s ( + ($input:expr, $substr:expr) => ( + { + take_until_and_consume!($input, $substr) + } + ); +); + +/// `take_until_s!(&str) => &str -> IResult<&str, &str>` +/// generates a parser consuming all chars until the specified string is found and leaves it in the remaining input +#[macro_export] +macro_rules! take_until_s ( + ($input:expr, $substr:expr) => ( + { + take_until!($input, $substr) + } + ); +); + +#[cfg(test)] +mod test { + use ::IResult; + + #[test] + fn tag_str_succeed() { + const INPUT: &'static str = "Hello World!"; + const TAG: &'static str = "Hello"; + fn test(input: &str) -> IResult<&str, &str> { + tag_s!(input, TAG) + } + + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == " World!", "Parser `tag_s` consumed leftover input."); + assert!(output == TAG, + "Parser `tag_s` doesn't return the tag it matched on success. \ + Expected `{}`, got `{}`.", TAG, output); + }, + other => panic!("Parser `tag_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn tag_str_incomplete() { + const INPUT: &'static str = "Hello"; + const TAG: &'static str = "Hello World!"; + + match tag_s!(INPUT, TAG) { + IResult::Incomplete(_) => (), + other => { + panic!("Parser `tag_s` didn't require more input when it should have. \ + Got `{:?}`.", other); + } + }; + } + + #[test] + fn tag_str_error() { + const INPUT: &'static str = "Hello World!"; + const TAG: &'static str = "Random"; // TAG must be closer than INPUT. + + match tag_s!(INPUT, TAG) { + IResult::Error(_) => (), + other => { + panic!("Parser `tag_s` didn't fail when it should have. Got `{:?}`.`", other); + }, + }; + } + + #[test] + fn take_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const CONSUMED: &'static str = "βèƒôřèÂßÇ"; + const LEFTOVER: &'static str = "áƒƭèř"; + + match take_s!(INPUT, 9) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_s` consumed leftover input. Leftover `{}`.", extra); + assert!(output == CONSUMED, + "Parser `take_s` doens't return the string it consumed on success. Expected `{}`, got `{}`.", + CONSUMED, output); + }, + other => panic!("Parser `take_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_until_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇ∂áƒƭèř"; + const FIND: &'static str = "ÂßÇ∂"; + const CONSUMED: &'static str = "βèƒôřè"; + const LEFTOVER: &'static str = "ÂßÇ∂áƒƭèř"; + + match take_until_s!(INPUT, FIND) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_until_s`\ + consumed leftover input. Leftover `{}`.", extra); + assert!(output == CONSUMED, "Parser `take_until_s`\ + doens't return the string it consumed on success. Expected `{}`, got `{}`.", + CONSUMED, output); + } + other => panic!("Parser `take_until_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_s_incomplete() { + const INPUT: &'static str = "βèƒôřèÂßÇá"; + + match take_s!(INPUT, 13) { + IResult::Incomplete(_) => (), + other => panic!("Parser `take_s` didn't require more input when it should have. \ + Got `{:?}`.", other), + } + } + + use internal::IResult::{Done, Error, Incomplete}; + use internal::Needed; + use util::ErrorKind; + + pub fn is_alphabetic(c:char) -> bool { + (c as u8 >= 0x41 && c as u8 <= 0x5A) || (c as u8 >= 0x61 && c as u8 <= 0x7A) + } + #[test] + fn take_while_s() { + named!(f<&str,&str>, take_while_s!(is_alphabetic)); + let a = ""; + let b = "abcd"; + let c = "abcd123"; + let d = "123"; + + assert_eq!(f(&a[..]), Done(&a[..], &a[..])); + assert_eq!(f(&b[..]), Done(&a[..], &b[..])); + assert_eq!(f(&c[..]), Done(&d[..], &b[..])); + assert_eq!(f(&d[..]), Done(&d[..], &a[..])); + } + + #[test] + fn take_while1_s() { + named!(f<&str,&str>, take_while1_s!(is_alphabetic)); + let a = ""; + let b = "abcd"; + let c = "abcd123"; + let d = "123"; + + assert_eq!(f(&a[..]), Incomplete(Needed::Size(1))); + assert_eq!(f(&b[..]), Done(&a[..], &b[..])); + assert_eq!(f(&c[..]), Done(&"123"[..], &b[..])); + assert_eq!(f(&d[..]), Error(error_position!(ErrorKind::TakeWhile1, &d[..]))); + } + + #[test] + fn take_till_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const CONSUMED: &'static str = "βèƒôřèÂßÇ"; + const LEFTOVER: &'static str = "áƒƭèř"; + fn till_s(c: char) -> bool { + c == 'á' + } + fn test(input: &str) -> IResult<&str, &str> { + take_till_s!(input, till_s) + } + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_till_s` consumed leftover input."); + assert!(output == CONSUMED, + "Parser `take_till_s` doesn't return the string it consumed on success. \ + Expected `{}`, got `{}`.", CONSUMED, output); + }, + other => panic!("Parser `take_till_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_while_s_succeed_none() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const CONSUMED: &'static str = ""; + const LEFTOVER: &'static str = "βèƒôřèÂßÇáƒƭèř"; + fn while_s(c: char) -> bool { + c == '9' + } + fn test(input: &str) -> IResult<&str, &str> { + take_while_s!(input, while_s) + } + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_while_s` consumed leftover input."); + assert!(output == CONSUMED, + "Parser `take_while_s` doesn't return the string it consumed on success. \ + Expected `{}`, got `{}`.", CONSUMED, output); + }, + other => panic!("Parser `take_while_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn is_not_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const AVOID: &'static str = "£úçƙ¥á"; + const CONSUMED: &'static str = "βèƒôřèÂßÇ"; + const LEFTOVER: &'static str = "áƒƭèř"; + fn test(input: &str) -> IResult<&str, &str> { + is_not_s!(input, AVOID) + } + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `is_not_s` consumed leftover input. Leftover `{}`.", extra); + assert!(output == CONSUMED, + "Parser `is_not_s` doens't return the string it consumed on success. Expected `{}`, got `{}`.", + CONSUMED, output); + }, + other => panic!("Parser `is_not_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_until_and_consume_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const FIND: &'static str = "ÂßÇ"; + const OUTPUT: &'static str = "βèƒôřè"; + const LEFTOVER: &'static str = "áƒƭèř"; + + match take_until_and_consume_s!(INPUT, FIND) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_until_and_consume_s`\ + consumed leftover input. Leftover `{}`.", extra); + assert!(output == OUTPUT, "Parser `take_until_and_consume_s`\ + doens't return the string it selected on success. Expected `{}`, got `{}`.", + OUTPUT, output); + } + other => panic!("Parser `take_until_and_consume_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_while_s_succeed_some() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const CONSUMED: &'static str = "βèƒôřèÂßÇ"; + const LEFTOVER: &'static str = "áƒƭèř"; + fn while_s(c: char) -> bool { + c == 'β' || c == 'è' || c == 'ƒ' || c == 'ô' || c == 'ř' || + c == 'è' || c == 'Â' || c == 'ß' || c == 'Ç' + } + fn test(input: &str) -> IResult<&str, &str> { + take_while_s!(input, while_s) + } + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_while_s` consumed leftover input."); + assert!(output == CONSUMED, + "Parser `take_while_s` doesn't return the string it consumed on success. \ + Expected `{}`, got `{}`.", CONSUMED, output); + }, + other => panic!("Parser `take_while_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn is_not_s_fail() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const AVOID: &'static str = "βúçƙ¥"; + fn test(input: &str) -> IResult<&str, &str> { + is_not_s!(input, AVOID) + } + match test(INPUT) { + IResult::Error(_) => (), + other => panic!("Parser `is_not_s` didn't fail when it should have. Got `{:?}`.", other), + }; + } + + #[test] + fn take_while1_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const CONSUMED: &'static str = "βèƒôřèÂßÇ"; + const LEFTOVER: &'static str = "áƒƭèř"; + fn while1_s(c: char) -> bool { + c == 'β' || c == 'è' || c == 'ƒ' || c == 'ô' || c == 'ř' || + c == 'è' || c == 'Â' || c == 'ß' || c == 'Ç' + } + fn test(input: &str) -> IResult<&str, &str> { + take_while1_s!(input, while1_s) + } + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `take_while1_s` consumed leftover input."); + assert!(output == CONSUMED, + "Parser `take_while1_s` doesn't return the string it consumed on success. \ + Expected `{}`, got `{}`.", CONSUMED, output); + }, + other => panic!("Parser `take_while1_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_until_and_consume_s_incomplete() { + const INPUT: &'static str = "βèƒôřè"; + const FIND: &'static str = "βèƒôřèÂßÇ"; + + match take_until_and_consume_s!(INPUT, FIND) { + IResult::Incomplete(_) => (), + other => panic!("Parser `take_until_and_consume_s` didn't require more input when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_until_s_incomplete() { + const INPUT: &'static str = "βèƒôřè"; + const FIND: &'static str = "βèƒôřèÂßÇ"; + + match take_until_s!(INPUT, FIND) { + IResult::Incomplete(_) => (), + other => panic!("Parser `take_until_s` didn't require more input when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn is_a_s_succeed() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const MATCH: &'static str = "βèƒôřèÂßÇ"; + const CONSUMED: &'static str = "βèƒôřèÂßÇ"; + const LEFTOVER: &'static str = "áƒƭèř"; + fn test(input: &str) -> IResult<&str, &str> { + is_a_s!(input, MATCH) + } + match test(INPUT) { + IResult::Done(extra, output) => { + assert!(extra == LEFTOVER, "Parser `is_a_s` consumed leftover input. Leftover `{}`.", extra); + assert!(output == CONSUMED, + "Parser `is_a_s` doens't return the string it consumed on success. Expected `{}`, got `{}`.", + CONSUMED, output); + }, + other => panic!("Parser `is_a_s` didn't succeed when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_while1_s_fail() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + fn while1_s(c: char) -> bool { + c == '9' + } + fn test(input: &str) -> IResult<&str, &str> { + take_while1_s!(input, while1_s) + } + match test(INPUT) { + IResult::Error(_) => (), + other => panic!("Parser `take_while1_s` didn't fail when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn is_a_s_fail() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const MATCH: &'static str = "Ûñℓúçƙ¥"; + fn test(input: &str) -> IResult<&str, &str> { + is_a_s!(input, MATCH) + } + match test(INPUT) { + IResult::Error(_) => (), + other => panic!("Parser `is_a_s` didn't fail when it should have. Got `{:?}`.", other), + }; + } + + #[test] + fn take_until_and_consume_s_error() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const FIND: &'static str = "Ráñδô₥"; + + match take_until_and_consume_s!(INPUT, FIND) { + IResult::Error(_) => (), + other => panic!("Parser `take_until_and_consume_s` didn't fail when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + fn take_until_s_error() { + const INPUT: &'static str = "βèƒôřèÂßÇáƒƭèř"; + const FIND: &'static str = "Ráñδô₥"; + + match take_until_s!(INPUT, FIND) { + IResult::Error(_) => (), + other => panic!("Parser `take_until_and_consume_s` didn't fail when it should have. \ + Got `{:?}`.", other), + }; + } + + #[test] + #[cfg(feature = "std")] + fn recognize_is_a_s() { + let a = "aabbab"; + let b = "ababcd"; + + named!(f <&str,&str>, recognize!(many1!(alt!( tag_s!("a") | tag_s!("b") )))); + + assert_eq!(f(&a[..]), Done(&a[6..], &a[..])); + assert_eq!(f(&b[..]), Done(&b[4..], &b[..4])); + + } + + #[test] + fn utf8_indexing() { + named!(dot(&str) -> &str, + tag_s!(".") + ); + + dot("點"); + } + + #[test] + fn case_insensitive() { + named!(test<&str,&str>, tag_no_case!("ABcd")); + assert_eq!(test("aBCdefgh"), Done("efgh", "aBCd")); + assert_eq!(test("abcdefgh"), Done("efgh", "abcd")); + assert_eq!(test("ABCDefgh"), Done("efgh", "ABCD")); + + named!(test2<&str,&str>, tag_no_case!("ABcd")); + assert_eq!(test2("aBCdefgh"), Done("efgh", "aBCd")); + assert_eq!(test2("abcdefgh"), Done("efgh", "abcd")); + assert_eq!(test2("ABCDefgh"), Done("efgh", "ABCD")); + } +} diff --git a/bash-5.1/vendor/nom/src/stream.rs b/bash-5.1/vendor/nom/src/stream.rs new file mode 100644 index 0000000..4d92bed --- /dev/null +++ b/bash-5.1/vendor/nom/src/stream.rs @@ -0,0 +1,1062 @@ +/// Context: +/// * Rust does not have tail call optimization, so we cannot recurse wildly +/// * data lifetimes makes sure that the result of a function applied to a producer cannot live longer than the producer's data (unless there is cloning) +/// * previous implementation of Producer and Consumer spent its time copying buffers +/// * the old Consumer was handling everything and buffering data. The new design has the producer handle data, but the consumer makes seeking decision +use std::io::{self,Read,Write,Seek,SeekFrom}; +use std::fs::File; +use std::path::Path; +use std::ptr; +use std::iter::repeat; +use internal::Needed; + +//pub type Computation = Box) -> (I,Consumer)>; + +#[derive(Debug,Clone)] +pub enum Input { + Element(I), + Empty, + Eof(Option) +} + +/// Stores a consumer's current computation state +#[derive(Debug,Clone)] +pub enum ConsumerState { + /// A value of type O has been produced + Done(M,O), + /// An error of type E has been encountered + Error(E), + /// Continue applying, and pass a message of type M to the data source + Continue(M) +} + +impl ConsumerState { + pub fn map(&self, f: F) -> ConsumerState where F: FnOnce(O) -> P { + match *self { + ConsumerState::Error(e) => ConsumerState::Error(e), + ConsumerState::Continue(m) => ConsumerState::Continue(m), + ConsumerState::Done(m, ref o) => ConsumerState::Done(m, f(o.clone())) + } + } + pub fn flat_map(&self, f: F) -> ConsumerState where F: FnOnce(M, O) -> ConsumerState { + match *self { + ConsumerState::Error(e) => ConsumerState::Error(e), + ConsumerState::Continue(m) => ConsumerState::Continue(m), + ConsumerState::Done(m, ref o) => f(m, o.clone()) + } + } +} +/// The Consumer trait wraps a computation and its state +/// +/// it depends on the input type I, the produced value's type O, the error type E, and the message type M +pub trait Consumer { + + /// implement handle for the current computation, returning the new state of the consumer + fn handle(&mut self, input: Input) -> &ConsumerState; + /// returns the current state + fn state(&self) -> &ConsumerState; + +} + +/// The producer wraps a data source, like file or network, and applies a consumer on it +/// +/// it handles buffer copying and reallocation, to provide streaming patterns. +/// it depends on the input type I, and the message type M. +/// the consumer can change the way data is produced (for example, to seek in the source) by sending a message of type M. +pub trait Producer<'b,I,M: 'b> { + /// Applies a consumer once on the produced data, and return the consumer's state + /// + /// a new producer has to implement this method. + /// + /// WARNING: if the `ConsumerState` generated by your consumer has a reference + /// to the input, it will generate borrow checking errors such as + /// `error: cannot borrow `producer` as mutable more than once at a time [E0499]`. + /// + /// It is caused by the producer's ability to refill the input at will, so it can modify + /// the input slice the `ConsumerState` is referring to. + /// + /// To avoid that kind of issue, try to do all the computations on input slices inside the + /// `Consumer` chain + fn apply<'a, O,E>(&'b mut self, consumer: &'a mut Consumer) -> &'a ConsumerState; + + /// Applies a consumer once on the produced data, and returns the generated value if there is one + fn run<'a: 'b,O,E: 'b>(&'b mut self, consumer: &'a mut Consumer) -> Option<&O> { + if let &ConsumerState::Done(_,ref o) = self.apply(consumer) { + Some(o) + } else { + None + } + } + // fn fromFile, FromSocket, fromRead +} + +/// ProducerRepeat takes a single value, and generates it at each step +pub struct ProducerRepeat { + value: I +} + +impl<'b,I:Copy,M: 'b> Producer<'b,I,M> for ProducerRepeat { + fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer) -> &'a ConsumerState { + if { + if let &ConsumerState::Continue(_) = consumer.state() { + true + } else { + false + } + } + { + consumer.handle(Input::Element(self.value)) + } else { + consumer.state() + } + } +} + +/// A MemProducer generates values from an in memory byte buffer +/// +/// it generates data by chunks, and keeps track of how much was consumed. +/// It can receive messages of type `Move` to handle consumption and seeking +pub struct MemProducer<'x> { + buffer: &'x [u8], + chunk_size: usize, + length: usize, + index: usize +} + +impl<'x> MemProducer<'x> { + pub fn new(buffer: &'x[u8], chunk_size: usize) -> MemProducer { + MemProducer { + buffer: buffer, + chunk_size: chunk_size, + length: buffer.len(), + index: 0 + } + } +} + +#[derive(Debug,Clone,Copy,PartialEq,Eq)] +pub enum Move { + /// indcates how much data was consumed + Consume(usize), + /// indicates where in the input the consumer must seek + Seek(SeekFrom), + /// indicates more data is needed + Await(Needed) +} + +impl<'x,'b> Producer<'b,&'x[u8],Move> for MemProducer<'x> { + fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState { + if { + if let &ConsumerState::Continue(ref m) = consumer.state() { + match *m { + Move::Consume(s) => { + if self.length - self.index >= s { + self.index += s + } else { + panic!("cannot consume past the end of the buffer"); + } + }, + Move::Await(a) => { + panic!("not handled for now: await({:?}", a); + } + Move::Seek(SeekFrom::Start(position)) => { + if position as usize > self.length { + self.index = self.length + } else { + self.index = position as usize + } + }, + Move::Seek(SeekFrom::Current(offset)) => { + let next = if offset >= 0 { + (self.index as u64).checked_add(offset as u64) + } else { + (self.index as u64).checked_sub(-offset as u64) + }; + match next { + None => None, + Some(u) => { + if u as usize > self.length { + self.index = self.length + } else { + self.index = u as usize + } + Some(self.index as u64) + } + }; + }, + Move::Seek(SeekFrom::End(i)) => { + let next = if i < 0 { + (self.length as u64).checked_sub(-i as u64) + } else { + // std::io::SeekFrom documentation explicitly allows + // seeking beyond the end of the stream, so we seek + // to the end of the content if the offset is 0 or + // greater. + Some(self.length as u64) + }; + match next { + // std::io:SeekFrom documentation states that it `is an + // error to seek before byte 0.' So it's the sensible + // thing to refuse to seek on underflow. + None => None, + Some(u) => { + self.index = u as usize; + Some(u) + } + }; + } + } + true + } else { + false + } + } + { + if self.index + self.chunk_size > self.length { + consumer.handle(Input::Eof(Some(&self.buffer[self.index..self.length]))) + } else { + consumer.handle(Input::Element(&self.buffer[self.index..self.index + self.chunk_size])) + } + } else { + consumer.state() + } + } +} + +#[derive(Debug,Copy,Clone,PartialEq,Eq)] +pub enum FileProducerState { + Normal, + Error, + Eof +} + +#[derive(Debug)] +pub struct FileProducer { + size: usize, + file: File, + position: usize, + v: Vec, + start: usize, + end: usize, + state: FileProducerState, +} + +impl FileProducer { + pub fn new(filename: &str, buffer_size: usize) -> io::Result { + File::open(&Path::new(filename)).and_then(|mut f| { + f.seek(SeekFrom::Start(0)).map(|_| { + let mut v = Vec::with_capacity(buffer_size); + v.extend(repeat(0).take(buffer_size)); + FileProducer {size: buffer_size, file: f, position: 0, v: v, start: 0, end: 0, state: FileProducerState::Normal } + }) + }) + } + + pub fn state(&self) -> FileProducerState { + self.state + } + + // FIXME: should handle refill until a certain size is obtained + pub fn refill(&mut self) -> Option { + shift(&mut self.v, self.start, self.end); + self.end = self.end - self.start; + self.start = 0; + + let remaining = &mut self.v[self.end..]; + + // already full, prevents erroneous Eof below + if remaining.is_empty() { + return Some(0); + } + + match self.file.read(remaining) { + Err(_) => { + self.state = FileProducerState::Error; + None + }, + Ok(n) => { + //println!("read: {} bytes\ndata:\n{:?}", n, &self.v); + if n == 0 { + self.state = FileProducerState::Eof; + } + self.end += n; + Some(0) + } + } + } + + /// Resize the internal buffer, copy the data to the new one and returned how much data was copied + /// + /// If the new buffer is smaller, the prefix will be copied, and the rest of the data will be dropped + pub fn resize(&mut self, s: usize) -> usize { + let mut v = vec![0; s]; + let length = self.end - self.start; + + let size = if length <= s { length } else { s }; + + // Use `Write` for `&mut [u8]` + (&mut v[..]).write(&self.v[self.start..self.start + size]).unwrap(); + + self.v = v; + self.start = 0; + self.end = size; + + size + } +} + +pub fn shift(s: &mut[u8], start: usize, end: usize) { + if start > 0 { + unsafe { + let length = end - start; + ptr::copy( (&s[start..end]).as_ptr(), (&mut s[..length]).as_mut_ptr(), length); + } + } +} + + +impl<'x> Producer<'x,&'x [u8],Move> for FileProducer { + + fn apply<'a,O,E>(&'x mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState { + //consumer.handle(Input::Element(&self.v[self.start..self.end])) + //self.my_apply(consumer) + if { + if let &ConsumerState::Continue(ref m) = consumer.state() { + match *m { + Move::Consume(s) => { + //println!("start: {}, end: {}, consumed: {}", self.start, self.end, s); + if self.end - self.start >= s { + self.start = self.start + s; + self.position = self.position + s; + } else { + panic!("cannot consume past the end of the buffer"); + } + if self.start == self.end { + self.refill(); + } + }, + Move::Await(_) => { + self.refill(); + }, + + // FIXME: naive seeking for now + Move::Seek(position) => { + let pos = match position { + // take into account data in the buffer + SeekFrom::Current(c) => SeekFrom::Current(c - (self.end - self.start) as i64), + default => default + }; + match self.file.seek(pos) { + Ok(pos) => { + //println!("file got seek to position {:?}. New position is {:?}", position, next); + self.position = pos as usize; + self.start = 0; + self.end = 0; + self.refill(); + }, + Err(_) => { + self.state = FileProducerState::Error; + } + } + } + } + true + } else { + false + } + } + { + //println!("producer state: {:?}", self.state); + match self.state { + FileProducerState::Normal => consumer.handle(Input::Element(&self.v[self.start..self.end])), + FileProducerState::Eof => { + let slice = &self.v[self.start..self.end]; + + if slice.is_empty() { + consumer.handle(Input::Eof(None)) + } else { + consumer.handle(Input::Eof(Some(slice))) + } + } + // is it right? + FileProducerState::Error => consumer.state() + } + } else { + consumer.state() + } + } +} + + +use std::marker::PhantomData; + +/// MapConsumer takes a function S -> T and applies it on a consumer producing values of type S +pub struct MapConsumer<'a, C:'a,R,S,T,E,M,F> { + state: ConsumerState, + consumer: &'a mut C, + f: F, + consumer_input_type: PhantomData, + f_input_type: PhantomData, + f_output_type: PhantomData +} + +impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer> MapConsumer<'a,C,R,S,T,E,M,F> { + pub fn new(c: &'a mut C, f: F) -> MapConsumer<'a,C,R,S,T,E,M,F> { + //let state = c.state(); + let initial = match *c.state() { + ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), f(o.clone())), + ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()), + ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()) + }; + + MapConsumer { + state: initial, + consumer: c, + f: f, + consumer_input_type: PhantomData, + f_input_type: PhantomData, + f_output_type: PhantomData + } + } +} + +impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer> Consumer for MapConsumer<'a,C,R,S,T,E,M,F> { + fn handle(&mut self, input: Input) -> &ConsumerState { + let res:&ConsumerState = self.consumer.handle(input); + self.state = match res { + &ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), (self.f)(o.clone())), + &ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()), + &ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()) + }; + &self.state + } + + fn state(&self) -> &ConsumerState { + &self.state + } +} + +/// ChainConsumer takes a consumer C1 R -> S, and a consumer C2 S -> T, and makes a consumer R -> T by applying C2 on C1's result +pub struct ChainConsumer<'a,'b, C1:'a,C2:'b,R,S,T,E,M> { + state: ConsumerState, + consumer1: &'a mut C1, + consumer2: &'b mut C2, + input_type: PhantomData, + temp_type: PhantomData +} + +impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer, C2:Consumer> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> { + pub fn new(c1: &'a mut C1, c2: &'b mut C2) -> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> { + let initial = match *c1.state() { + ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()), + ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()), + ConsumerState::Done(ref m, ref o) => match *c2.handle(Input::Element(o.clone())) { + ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()), + ConsumerState::Continue(ref m2) => ConsumerState::Continue(m2.clone()), + ConsumerState::Done(_,ref o2) => ConsumerState::Done(m.clone(), o2.clone()) + } + }; + + ChainConsumer { + state: initial, + consumer1: c1, + consumer2: c2, + input_type: PhantomData, + temp_type: PhantomData + } + } +} + +impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer, C2:Consumer> Consumer for ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> { + fn handle(&mut self, input: Input) -> &ConsumerState { + let res:&ConsumerState = self.consumer1.handle(input); + self.state = match *res { + ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()), + ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()), + ConsumerState::Done(ref m, ref o) => match *self.consumer2.handle(Input::Element(o.clone())) { + ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()), + ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()), + ConsumerState::Done(_, ref o2) => ConsumerState::Done(m.clone(), o2.clone()) + } + }; + &self.state + } + + fn state(&self) -> &ConsumerState { + &self.state + } +} + +#[macro_export] +macro_rules! consumer_from_parser ( + //FIXME: should specify the error and move type + ($name:ident<$input:ty, $output:ty>, $submac:ident!( $($args:tt)* )) => ( + #[derive(Debug)] + struct $name { + state: $crate::ConsumerState<$output, (), $crate::Move> + } + + impl $name { + fn new() -> $name { + $name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) } + } + } + + impl $crate::Consumer<$input, $output, (), $crate::Move> for $name { + fn handle(&mut self, input: $crate::Input<$input>) -> & $crate::ConsumerState<$output, (), $crate::Move> { + use $crate::Offset; + match input { + $crate::Input::Empty | $crate::Input::Eof(None) => &self.state, + $crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => { + self.state = match $submac!(sl, $($args)*) { + $crate::IResult::Incomplete(n) => { + $crate::ConsumerState::Continue($crate::Move::Await(n)) + }, + $crate::IResult::Error(_) => { + $crate::ConsumerState::Error(()) + }, + $crate::IResult::Done(i,o) => { + $crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o) + } + }; + + &self.state + } + } + + } + + fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> { + &self.state + } + } + ); + ($name:ident<$output:ty>, $submac:ident!( $($args:tt)* )) => ( + #[derive(Debug)] + struct $name { + state: $crate::ConsumerState<$output, (), $crate::Move> + } + + impl $name { + // Allow this to go unused, because code in the defining scope can create the struct directly. + #[allow(dead_code)] + fn new() -> $name { + $name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) } + } + } + + impl<'a> $crate::Consumer<&'a[u8], $output, (), $crate::Move> for $name { + fn handle(&mut self, input: $crate::Input<&'a[u8]>) -> & $crate::ConsumerState<$output, (), $crate::Move> { + use $crate::Offset; + match input { + $crate::Input::Empty | $crate::Input::Eof(None) => &self.state, + $crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => { + self.state = match $submac!(sl, $($args)*) { + $crate::IResult::Incomplete(n) => { + $crate::ConsumerState::Continue($crate::Move::Await(n)) + }, + $crate::IResult::Error(_) => { + $crate::ConsumerState::Error(()) + }, + $crate::IResult::Done(i,o) => { + $crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o) + } + }; + + &self.state + } + } + + } + + fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> { + &self.state + } + } + ); + ($name:ident<$input:ty, $output:ty>, $f:expr) => ( + consumer_from_parser!($name<$input, $output>, call!($f)); + ); + ($name:ident<$output:ty>, $f:expr) => ( + consumer_from_parser!($name<$output>, call!($f)); + ); + +); + +#[cfg(test)] +mod tests { + use super::*; + use internal::IResult; + use util::Offset; + use std::str::from_utf8; + use std::io::SeekFrom; + + #[derive(Debug)] + struct AbcdConsumer<'a> { + state: ConsumerState<&'a [u8], (), Move> + } + + named!(abcd, tag!("abcd")); + impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for AbcdConsumer<'a> { + fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8],(),Move> { + match input { + Input::Empty | Input::Eof(None) => &self.state, + Input::Element(sl) => { + match abcd(sl) { + IResult::Error(_) => { + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.state = ConsumerState::Continue(Move::Consume(0)) + }, + IResult::Done(i,o) => { + self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o) + } + }; + &self.state + } + Input::Eof(Some(sl)) => { + match abcd(sl) { + IResult::Error(_) => { + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + // we cannot return incomplete on Eof + self.state = ConsumerState::Error(()) + }, + IResult::Done(i,o) => { + self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o) + } + }; + &self.state + } + } + + } + + fn state(&self) -> &ConsumerState<&'a [u8], (), Move> { + &self.state + } + } + + #[test] + fn mem() { + let mut m = MemProducer::new(&b"abcdabcdabcdabcdabcd"[..], 8); + + let mut a = AbcdConsumer { state: ConsumerState::Continue(Move::Consume(0)) }; + + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + //assert!(false); + } + + named!(efgh, tag!("efgh")); + named!(ijkl, tag!("ijkl")); + #[derive(Debug)] + enum State { + Initial, + A, + B, + End, + Error + } + #[derive(Debug)] + struct StateConsumer<'a> { + state: ConsumerState<&'a [u8], (), Move>, + parsing_state: State + } + + impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for StateConsumer<'a> { + fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8], (), Move> { + match input { + Input::Empty | Input::Eof(None) => &self.state, + Input::Element(sl) => { + match self.parsing_state { + State::Initial => match abcd(sl) { + IResult::Error(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.state = ConsumerState::Continue(Move::Consume(0)) + }, + IResult::Done(i,_) => { + self.parsing_state = State::A; + self.state = ConsumerState::Continue(Move::Consume(sl.offset(i))) + } + }, + State::A => match efgh(sl) { + IResult::Error(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.state = ConsumerState::Continue(Move::Consume(0)) + }, + IResult::Done(i,_) => { + self.parsing_state = State::B; + self.state = ConsumerState::Continue(Move::Consume(sl.offset(i))) + } + }, + State::B => match ijkl(sl) { + IResult::Error(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.state = ConsumerState::Continue(Move::Consume(0)) + }, + IResult::Done(i,o) => { + self.parsing_state = State::End; + self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o) + } + }, + _ => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + } + } + &self.state + } + Input::Eof(Some(sl)) => { + match self.parsing_state { + State::Initial => match abcd(sl) { + IResult::Error(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Done(_,_) => { + self.parsing_state = State::A; + self.state = ConsumerState::Error(()) + } + }, + State::A => match efgh(sl) { + IResult::Error(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Done(_,_) => { + self.parsing_state = State::B; + self.state = ConsumerState::Error(()) + } + }, + State::B => match ijkl(sl) { + IResult::Error(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Incomplete(_) => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + }, + IResult::Done(i,o) => { + self.parsing_state = State::End; + self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o) + } + }, + _ => { + self.parsing_state = State::Error; + self.state = ConsumerState::Error(()) + } + } + &self.state + } + } + + } + + fn state(&self) -> &ConsumerState<&'a [u8], (), Move> { + &self.state + } + } + impl<'a> StateConsumer<'a> { + fn parsing(&self) -> &State { + &self.parsing_state + } + } + + #[test] + fn mem2() { + let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8); + + let mut a = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial }; + + println!("apply {:?}", m.apply(&mut a)); + println!("state {:?}", a.parsing()); + println!("apply {:?}", m.apply(&mut a)); + println!("state {:?}", a.parsing()); + println!("apply {:?}", m.apply(&mut a)); + println!("state {:?}", a.parsing()); + println!("apply {:?}", m.apply(&mut a)); + println!("state {:?}", a.parsing()); + //assert!(false); + } + + + #[test] + fn map() { + let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8); + + let mut s = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial }; + let mut a = MapConsumer::new(&mut s, from_utf8); + + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + //assert!(false); + } + + #[derive(Debug)] + struct StrConsumer<'a> { + state: ConsumerState<&'a str, (), Move> + } + + impl<'a> Consumer<&'a [u8], &'a str, (), Move> for StrConsumer<'a> { + fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a str, (), Move> { + match input { + Input::Empty | Input::Eof(None) => &self.state, + Input::Element(sl) | Input::Eof(Some(sl)) => { + self.state = ConsumerState::Done(Move::Consume(sl.len()), from_utf8(sl).unwrap()); + &self.state + } + } + + } + + fn state(&self) -> &ConsumerState<&'a str, (), Move> { + &self.state + } + } + + + #[test] + fn chain() { + let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8); + + let mut s1 = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial }; + let mut s2 = StrConsumer { state: ConsumerState::Continue(Move::Consume(0)) }; + let mut a = ChainConsumer::new(&mut s1, &mut s2); + + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + println!("apply {:?}", m.apply(&mut a)); + //assert!(false); + // + //let x = [0, 1, 2, 3, 4]; + //let b = [1, 2, 3]; + //assert_eq!(&x[1..3], &b[..]); + } + + #[test] + fn shift_test() { + let mut v = vec![0,1,2,3,4,5]; + shift(&mut v, 1, 3); + assert_eq!(&v[..2], &[1,2][..]); + let mut v2 = vec![0,1,2,3,4,5]; + shift(&mut v2, 2, 6); + assert_eq!(&v2[..4], &[2,3,4,5][..]); + } + + /*#[derive(Debug)] + struct LineConsumer { + state: ConsumerState + } + impl<'a> Consumer<&'a [u8], String, (), Move> for LineConsumer { + fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState { + match input { + Input::Empty | Input::Eof(None) => &self.state, + Input::Element(sl) | Input::Eof(Some(sl)) => { + //println!("got slice: {:?}", sl); + self.state = match line(sl) { + IResult::Incomplete(n) => { + println!("line not complete, continue (line was \"{}\")", from_utf8(sl).unwrap()); + ConsumerState::Continue(Move::Await(n)) + }, + IResult::Error(e) => { + println!("LineConsumer parsing error: {:?}", e); + ConsumerState::Error(()) + }, + IResult::Done(i,o) => { + let res = String::from(from_utf8(o).unwrap()); + println!("found: {}", res); + //println!("sl: {:?}\ni:{:?}\noffset:{}", sl, i, sl.offset(i)); + ConsumerState::Done(Move::Consume(sl.offset(i)), res) + } + }; + + &self.state + } + } + + } + + fn state(&self) -> &ConsumerState { + &self.state + } + }*/ + + fn lf(i:u8) -> bool { + i == '\n' as u8 + } + fn to_utf8_string(input:&[u8]) -> String { + String::from(from_utf8(input).unwrap()) + } + + //named!(line<&[u8]>, terminated!(take_till!(lf), tag!("\n"))); + + consumer_from_parser!(LineConsumer, map!(terminated!(take_till!(lf), tag!("\n")), to_utf8_string)); + + fn get_line(producer: &mut FileProducer, mv: Move) -> Option<(Move,String)> { + let mut a = LineConsumer { state: ConsumerState::Continue(mv) }; + while let &ConsumerState::Continue(_) = producer.apply(&mut a) { + println!("continue"); + } + + if let &ConsumerState::Done(ref m, ref s) = a.state() { + Some((m.clone(), s.clone())) + } else { + None + } + } + + #[test] + fn file() { + let mut f = FileProducer::new("LICENSE", 200).unwrap(); + f.refill(); + + let mut mv = Move::Consume(0); + for i in 1..10 { + if let Some((m,s)) = get_line(&mut f, mv.clone()) { + println!("got line[{}]: {}", i, s); + mv = m; + } else { + assert!(false, "LineConsumer should not have failed"); + } + } + //assert!(false); + } + + #[test] + fn small_buffer() { + let mut f = FileProducer::new("LICENSE", 10 /* smaller than a line */).unwrap(); + let mut a = LineConsumer::new(); + + for i in 0..2 { + match f.apply(&mut a) { + &ConsumerState::Continue(Move::Await(_)) => {} + _ => assert!(false, "LineConsumer should be awaiting more input: {}", i), + } + assert_eq!(FileProducerState::Normal, f.state()); + } + + f.resize(200 /* large enough for a line */); + match f.apply(&mut a) { + &ConsumerState::Done(..) => {} + _ => assert!(false, "LineConsumer should have succeeded"), + } + assert_eq!(FileProducerState::Normal, f.state()); + } + + #[derive(Debug,Clone,Copy,PartialEq,Eq)] + enum SeekState { + Begin, + SeekedToEnd, + ShouldEof, + IsEof + } + + #[derive(Debug)] + struct SeekingConsumer { + state: ConsumerState<(), u8, Move>, + position: SeekState + } + + impl SeekingConsumer { + fn position(&self) -> SeekState { + self.position + } + } + + impl<'a> Consumer<&'a [u8], (), u8, Move> for SeekingConsumer { + fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<(), u8, Move> { + println!("input: {:?}", input); + match self.position { + SeekState::Begin => { + self.state = ConsumerState::Continue(Move::Seek(SeekFrom::End(-4))); + self.position = SeekState::SeekedToEnd; + }, + SeekState::SeekedToEnd => match input { + Input::Element(sl) => { + if sl.len() == 4 { + self.state = ConsumerState::Continue(Move::Consume(4)); + self.position = SeekState::ShouldEof; + } else { + self.state = ConsumerState::Error(0); + } + }, + Input::Eof(Some(sl)) => { + if sl.len() == 4 { + self.state = ConsumerState::Done(Move::Consume(4), ()); + self.position = SeekState::IsEof; + } else { + self.state = ConsumerState::Error(1); + } + }, + _ => self.state = ConsumerState::Error(2) + }, + SeekState::ShouldEof => match input { + Input::Eof(Some(sl)) => { + if sl.len() == 0 { + self.state = ConsumerState::Done(Move::Consume(0), ()); + self.position = SeekState::IsEof; + } else { + self.state = ConsumerState::Error(3); + } + }, + Input::Eof(None) => { + self.state = ConsumerState::Done(Move::Consume(0), ()); + self.position = SeekState::IsEof; + }, + _ => self.state = ConsumerState::Error(4) + }, + _ => self.state = ConsumerState::Error(5) + }; + &self.state + } + + fn state(&self) -> &ConsumerState<(), u8, Move> { + &self.state + } + } + + #[test] + fn seeking_consumer() { + let mut f = FileProducer::new("assets/testfile.txt", 200).unwrap(); + f.refill(); + + let mut a = SeekingConsumer { state: ConsumerState::Continue(Move::Consume(0)), position: SeekState::Begin }; + for _ in 1..4 { + println!("file apply {:?}", f.apply(&mut a)); + } + println!("consumer is now: {:?}", a); + if let &ConsumerState::Done(Move::Consume(0), ()) = a.state() { + println!("end"); + } else { + println!("invalid state is {:?}", a.state()); + assert!(false, "consumer is not at EOF"); + } + assert_eq!(a.position(), SeekState::IsEof); + } +} diff --git a/bash-5.1/vendor/nom/src/traits.rs b/bash-5.1/vendor/nom/src/traits.rs new file mode 100644 index 0000000..e810333 --- /dev/null +++ b/bash-5.1/vendor/nom/src/traits.rs @@ -0,0 +1,623 @@ +//! Traits input types have to implement to work with nom combinators +//! +use std::ops::{Range,RangeTo,RangeFrom,RangeFull}; +use std::iter::Enumerate; +use std::slice::Iter; + +use std::str::Chars; +use std::str::CharIndices; +use std::str::FromStr; +use std::str::from_utf8; + +use memchr; + + +/// abstract method to calculate the input length +pub trait InputLength { + /// calculates the input length, as indicated by its name, + /// and the name of the trait itself + #[inline] + fn input_len(&self) -> usize; +} + +impl<'a, T> InputLength for &'a[T] { + #[inline] + fn input_len(&self) -> usize { + self.len() + } +} + +impl<'a> InputLength for &'a str { + #[inline] + fn input_len(&self) -> usize { + self.len() + } +} + +impl<'a> InputLength for (&'a [u8], usize) { + #[inline] + fn input_len(&self) -> usize { + //println!("bit input length for ({:?}, {}):", self.0, self.1); + let res = self.0.len() * 8 - self.1; + //println!("-> {}", res); + res + } +} + +/// transforms common types to a char for basic token parsing +pub trait AsChar { + /// makes a char from self + #[inline] + fn as_char(self) -> char; + + /// tests that self is an alphabetic character + /// + /// warning: for `&str` it recognizes alphabetic + /// characters outside of the 52 ASCII letters + #[inline] + fn is_alpha(self) -> bool; + + /// tests that self is an alphabetic character + /// or a decimal digit + #[inline] + fn is_alphanum(self) -> bool; + /// tests that self is a decimal digit + #[inline] + fn is_dec_digit(self) -> bool; + /// tests that self is an hex digit + #[inline] + fn is_hex_digit(self) -> bool; + /// tests that self is an octal digit + #[inline] + fn is_oct_digit(self) -> bool; + /// gets the len in bytes for self + #[inline] + fn len(self) -> usize; +} + +impl AsChar for u8 { + #[inline] + fn as_char(self) -> char { self as char } + #[inline] + fn is_alpha(self) -> bool { + (self >= 0x41 && self <= 0x5A) || (self >= 0x61 && self <= 0x7A) + } + #[inline] + fn is_alphanum(self) -> bool { self.is_alpha() || self.is_dec_digit() } + #[inline] + fn is_dec_digit(self) -> bool { + self >= 0x30 && self <= 0x39 + } + #[inline] + fn is_hex_digit(self) -> bool { + (self >= 0x30 && self <= 0x39) || + (self >= 0x41 && self <= 0x46) || + (self >= 0x61 && self <= 0x66) + } + #[inline] + fn is_oct_digit(self) -> bool { + self >= 0x30 && self <= 0x37 + } + #[inline] + fn len(self) -> usize { + 1 + } +} +impl<'a> AsChar for &'a u8 { + #[inline] + fn as_char(self) -> char { *self as char } + #[inline] + fn is_alpha(self) -> bool { + (*self >= 0x41 && *self <= 0x5A) || (*self >= 0x61 && *self <= 0x7A) + } + #[inline] + fn is_alphanum(self) -> bool { self.is_alpha() || self.is_dec_digit() } + #[inline] + fn is_dec_digit(self) -> bool { + *self >= 0x30 && *self <= 0x39 + } + #[inline] + fn is_hex_digit(self) -> bool { + (*self >= 0x30 && *self <= 0x39) || + (*self >= 0x41 && *self <= 0x46) || + (*self >= 0x61 && *self <= 0x66) + } + #[inline] + fn is_oct_digit(self) -> bool { + *self >= 0x30 && *self <= 0x37 + } + #[inline] + fn len(self) -> usize { + 1 + } +} + +impl AsChar for char { + #[inline] + fn as_char(self) -> char { self } + #[inline] + fn is_alpha(self) -> bool { self.is_alphabetic() } + #[inline] + fn is_alphanum(self) -> bool { self.is_alpha() || self.is_dec_digit() } + #[inline] + fn is_dec_digit(self) -> bool { self.is_digit(10) } + #[inline] + fn is_hex_digit(self) -> bool { self.is_digit(16) } + #[inline] + fn is_oct_digit(self) -> bool { self.is_digit(8) } + #[inline] + fn len(self) -> usize { self.len_utf8() } +} + +impl<'a> AsChar for &'a char { + #[inline] + fn as_char(self) -> char { self.clone() } + #[inline] + fn is_alpha(self) -> bool { self.is_alphabetic() } + #[inline] + fn is_alphanum(self) -> bool { self.is_alpha() || self.is_dec_digit() } + #[inline] + fn is_dec_digit(self) -> bool { self.is_digit(10) } + #[inline] + fn is_hex_digit(self) -> bool { self.is_digit(16) } + #[inline] + fn is_oct_digit(self) -> bool { self.is_digit(8) } + #[inline] + fn len(self) -> usize { self.len_utf8() } +} + +/// abstracts common iteration operations on the input type +/// +/// it needs a distinction between `Item` and `RawItem` because +/// `&[T]` iterates on references +pub trait InputIter { + type Item; + type RawItem; + type Iter : Iterator; + type IterElem : Iterator; + + /// returns an iterator over the elements and their byte offsets + fn iter_indices(&self) -> Self::Iter; + /// returns an iterator over the elements + fn iter_elements(&self) -> Self::IterElem; + /// finds the byte position of the element + fn position

(&self, predicate: P) -> Option where P: Fn(Self::RawItem) -> bool; + /// get the byte offset from the element's position in the stream + fn slice_index(&self, count:usize) -> Option; +} + +/// abstracts slicing operations +pub trait InputTake { + /// returns a slice of `count` bytes + fn take

(&self, count: usize) -> Option<&Self>; + /// split the stream at the `count` byte offset + fn take_split

(&self, count: usize) -> Option<(&Self,&Self)>; +} + +impl<'a> InputIter for &'a [u8] { + type Item = &'a u8; + type RawItem = u8; + type Iter = Enumerate>; + type IterElem = Iter<'a, Self::RawItem>; + + #[inline] + fn iter_indices(&self) -> Self::Iter { + self.iter().enumerate() + } + #[inline] + fn iter_elements(&self) -> Self::IterElem { + self.iter() + } + #[inline] + fn position

(&self, predicate: P) -> Option where P: Fn(Self::RawItem) -> bool { + self.iter().position(|b| predicate(*b)) + } + #[inline] + fn slice_index(&self, count:usize) -> Option { + if self.len() >= count { + Some(count) + } else { + None + } + } +} + +impl InputTake for [u8] { + #[inline] + fn take

(&self, count: usize) -> Option<&Self> { + if self.len() >= count { + Some(&self[0..count]) + } else { + None + } + } + #[inline] + fn take_split

(&self, count: usize) -> Option<(&Self,&Self)> { + if self.len() >= count { + Some((&self[count..],&self[..count])) + } else { + None + } + } +} + +impl<'a> InputIter for &'a str { + type Item = char; + type RawItem = char; + type Iter = CharIndices<'a>; + type IterElem = Chars<'a>; + #[inline] + fn iter_indices(&self) -> Self::Iter { + self.char_indices() + } + #[inline] + fn iter_elements(&self) -> Self::IterElem { + self.chars() + } + fn position

(&self, predicate: P) -> Option where P: Fn(Self::RawItem) -> bool { + for (o,c) in self.char_indices() { + if predicate(c) { + return Some(o) + } + } + None + } + #[inline] + fn slice_index(&self, count:usize) -> Option { + let mut cnt = 0; + for (index, _) in self.char_indices() { + if cnt == count { + return Some(index) + } + cnt += 1; + } + if cnt == count { + return Some(self.len()) + } + None + } +} + +impl InputTake for str { + #[inline] + fn take

(&self, count: usize) -> Option<&Self> { + let mut cnt = 0; + for (index, _) in self.char_indices() { + if cnt == count { + return Some(&self[..index]) + } + cnt += 1; + } + None + } + + // return byte index + #[inline] + fn take_split

(&self, count: usize) -> Option<(&Self,&Self)> { + let mut cnt = 0; + for (index, _) in self.char_indices() { + if cnt == count { + return Some((&self[index..],&self[..index])) + } + cnt += 1; + } + None + } +} + +/// indicates wether a comparison was successful, an error, or +/// if more data was needed +#[derive(Debug,PartialEq)] +pub enum CompareResult { + Ok, + Incomplete, + Error +} + +/// abstracts comparison operations +pub trait Compare { + /// compares self to another value for equality + fn compare(&self, t:T) -> CompareResult; + /// compares self to another value for equality + /// independently of the case. + /// + /// warning: for `&str`, the comparison is done + /// by lowercasing both strings and comparing + /// the result. This is a temporary solution until + /// a better one appears + fn compare_no_case(&self, t:T) -> CompareResult; +} + +impl<'a,'b> Compare<&'b[u8]> for &'a [u8] { + #[inline(always)] + fn compare(&self, t: &'b[u8]) -> CompareResult { + let len = self.len(); + let blen = t.len(); + let m = if len < blen { len } else { blen }; + let reduced = &self[..m]; + let b = &t[..m]; + + if reduced != b { + CompareResult::Error + } else if m < blen { + CompareResult::Incomplete + } else { + CompareResult::Ok + } + } + + #[inline(always)] + fn compare_no_case(&self, t: &'b[u8]) -> CompareResult { + let len = self.len(); + let blen = t.len(); + let m = if len < blen { len } else { blen }; + let reduced = &self[..m]; + let other = &t[..m]; + + if !reduced.iter().zip(other).all(|(a, b)| { + match (*a,*b) { + (0...64, 0...64) | (91...96, 91...96) | (123...255, 123...255) => a == b, + (65...90, 65...90) | (97...122, 97...122) | (65...90, 97...122 ) |(97...122, 65...90) => { + *a | 0b00100000 == *b | 0b00100000 + } + _ => false + } + }) { + CompareResult::Error + } else if m < blen { + CompareResult::Incomplete + } else { + CompareResult::Ok + } + } +} + +impl<'a,'b> Compare<&'b str> for &'a [u8] { + #[inline(always)] + fn compare(&self, t: &'b str) -> CompareResult { + self.compare(str::as_bytes(t)) + } + #[inline(always)] + fn compare_no_case(&self, t: &'b str) -> CompareResult { + self.compare_no_case(str::as_bytes(t)) + } +} + +impl<'a,'b> Compare<&'b str> for &'a str { + #[inline(always)] + fn compare(&self, t: &'b str) -> CompareResult { + let pos = self.chars().zip(t.chars()).position(|(a,b)| a != b); + + match pos { + Some(_) => CompareResult::Error, + None => if self.len() >= t.len() { + CompareResult::Ok + } else { + CompareResult::Incomplete + } + } + } + + //FIXME: this version is too simple and does not use the current locale + #[inline(always)] + fn compare_no_case(&self, t: &'b str) -> CompareResult { + let pos = self.to_lowercase().chars().zip(t.to_lowercase().chars()).position(|(a,b)| a != b); + + match pos { + Some(_) => CompareResult::Error, + None => if self.len() >= t.len() { + CompareResult::Ok + } else { + CompareResult::Incomplete + } + } + } +} + +/// look for self in the given input stream +pub trait FindToken { + fn find_token(&self, input: T) -> bool; +} + +impl<'a> FindToken<&'a[u8]> for u8 { + fn find_token(&self, input: &[u8]) -> bool { + memchr::memchr(*self, input).is_some() + } +} + +impl<'a> FindToken<&'a str> for u8 { + fn find_token(&self, input: &str) -> bool { + self.find_token(str::as_bytes(input)) + } +} + +impl<'a,'b> FindToken<&'a[u8]> for &'b u8 { + fn find_token(&self, input: &[u8]) -> bool { + memchr::memchr(**self, input).is_some() + } +} + +impl<'a,'b> FindToken<&'a str> for &'b u8 { + fn find_token(&self, input: &str) -> bool { + self.find_token(str::as_bytes(input)) + } +} + +impl<'a> FindToken<&'a str> for char { + fn find_token(&self, input: &str) -> bool { + for i in input.chars() { + if *self == i { return true } + } + false + } +} + +/// look for a substring in self +pub trait FindSubstring { + fn find_substring(&self, substr: T) -> Option; +} + +impl<'a,'b> FindSubstring<&'b [u8]> for &'a[u8] { + fn find_substring(&self, substr: &'b[u8]) -> Option { + let substr_len = substr.len(); + + if substr_len == 0 { + None + } else if substr_len == 1 { + memchr::memchr(substr[0], self) + } else { + let max = self.len() - substr_len; + let mut offset = 0; + let mut haystack = &self[..]; + + while let Some(position) = memchr::memchr(substr[0], haystack) { + offset += position; + + if offset > max { + return None + } + + if &haystack[position..position + substr_len] == substr { + return Some(offset) + } + + haystack = &haystack[position + 1..]; + offset += 1; + } + + None + } + } +} + +impl<'a,'b> FindSubstring<&'b str> for &'a[u8] { + fn find_substring(&self, substr: &'b str) -> Option { + self.find_substring(str::as_bytes(substr)) + } +} + +impl<'a,'b> FindSubstring<&'b str> for &'a str { + //returns byte index + fn find_substring(&self, substr: &'b str) -> Option { + self.find(substr) + } +} + +/// used to integrate str's parse() method +pub trait ParseTo { + fn parse_to(&self) -> Option; +} + +impl<'a,R: FromStr> ParseTo for &'a[u8] { + fn parse_to(&self) -> Option { + from_utf8(self).ok().and_then(|s| s.parse().ok()) + } +} + +impl<'a,R:FromStr> ParseTo for &'a str { + fn parse_to(&self) -> Option { + self.parse().ok() + } +} + +/// slicing operations using ranges +/// +/// this trait is loosely based on +/// `Index`, but can actually return +/// something else than a `&[T]` or `&str` +pub trait Slice { + #[inline(always)] + fn slice(&self, range: R) -> Self; +} + +macro_rules! impl_fn_slice { + ( $ty:ty ) => { + fn slice(&self, range:$ty) -> Self { + &self[range] + } + } +} + +macro_rules! slice_range_impl { + ( [ $for_type:ident ], $ty:ty ) => { + impl<'a, $for_type> Slice<$ty> for &'a [$for_type] { + impl_fn_slice!( $ty ); + } + }; + ( $for_type:ty, $ty:ty ) => { + impl<'a> Slice<$ty> for &'a $for_type { + impl_fn_slice!( $ty ); + } + } +} + +macro_rules! slice_ranges_impl { + ( [ $for_type:ident ] ) => { + slice_range_impl! {[$for_type], Range} + slice_range_impl! {[$for_type], RangeTo} + slice_range_impl! {[$for_type], RangeFrom} + slice_range_impl! {[$for_type], RangeFull} + }; + ( $for_type:ty ) => { + slice_range_impl! {$for_type, Range} + slice_range_impl! {$for_type, RangeTo} + slice_range_impl! {$for_type, RangeFrom} + slice_range_impl! {$for_type, RangeFull} + } +} + +slice_ranges_impl! {str} +slice_ranges_impl! {[T]} + + +macro_rules! array_impls { + ($($N:expr)+) => { + $( + impl InputLength for [u8; $N] { + #[inline] + fn input_len(&self) -> usize { + self.len() + } + } + + impl<'a> InputLength for &'a [u8; $N] { + #[inline] + fn input_len(&self) -> usize { + self.len() + } + } + + impl<'a> Compare<[u8; $N]> for &'a [u8] { + #[inline(always)] + fn compare(&self, t: [u8; $N]) -> CompareResult { + self.compare(&t[..]) + } + + #[inline(always)] + fn compare_no_case(&self, t: [u8;$N]) -> CompareResult { + self.compare_no_case(&t[..]) + } + } + + impl<'a,'b> Compare<&'b [u8; $N]> for &'a [u8] { + #[inline(always)] + fn compare(&self, t: &'b [u8; $N]) -> CompareResult { + self.compare(&t[..]) + } + + #[inline(always)] + fn compare_no_case(&self, t: &'b [u8;$N]) -> CompareResult { + self.compare_no_case(&t[..]) + } + } + )+ + }; +} + + +array_impls! { + 0 1 2 3 4 5 6 7 8 9 + 10 11 12 13 14 15 16 17 18 19 + 20 21 22 23 24 25 26 27 28 29 + 30 31 32 +} diff --git a/bash-5.1/vendor/nom/src/util.rs b/bash-5.1/vendor/nom/src/util.rs new file mode 100644 index 0000000..75663b9 --- /dev/null +++ b/bash-5.1/vendor/nom/src/util.rs @@ -0,0 +1,738 @@ + +#[cfg(feature = "verbose-errors")] +use internal::IResult; + +#[cfg(feature = "verbose-errors")] +use verbose_errors::Err; + +#[cfg(feature = "std")] +use std::collections::HashMap; + +#[cfg(not(feature = "std"))] +use std::prelude::v1::*; + +use std::vec::Vec; +use std::string::ToString; + +/// useful functions to calculate the offset between slices and show a hexdump of a slice +pub trait Offset { + /// offset between the first byte of self and the first byte of the argument + fn offset(&self, second:&Self) -> usize; +} + +#[cfg(feature = "std")] +pub trait HexDisplay { + /// Converts the value of `self` to a hex dump, returning the owned + /// string. + fn to_hex(&self, chunk_size: usize) -> String; + + /// Converts the value of `self` to a hex dump beginning at `from` address, returning the owned + /// string. + fn to_hex_from(&self, chunk_size: usize, from: usize) -> String; +} + +static CHARS: &'static[u8] = b"0123456789abcdef"; + +impl Offset for [u8] { + fn offset(&self, second:&[u8]) -> usize { + let fst = self.as_ptr(); + let snd = second.as_ptr(); + + snd as usize - fst as usize + } +} + +impl Offset for str { + fn offset(&self, second: &Self) -> usize { + let fst = self.as_ptr(); + let snd = second.as_ptr(); + + snd as usize - fst as usize + } +} + +#[cfg(feature = "std")] +impl HexDisplay for [u8] { + #[allow(unused_variables)] + fn to_hex(&self, chunk_size: usize) -> String { + self.to_hex_from(chunk_size, 0) + } + + #[allow(unused_variables)] + fn to_hex_from(&self, chunk_size: usize, from: usize) -> String { + let mut v = Vec::with_capacity(self.len() * 3); + let mut i = from; + for chunk in self.chunks(chunk_size) { + let s = format!("{:08x}", i); + for &ch in s.as_bytes().iter() { + v.push(ch); + } + v.push('\t' as u8); + + i = i + chunk_size; + + for &byte in chunk { + v.push(CHARS[(byte >> 4) as usize]); + v.push(CHARS[(byte & 0xf) as usize]); + v.push(' ' as u8); + } + if chunk_size > chunk.len() { + for j in 0..(chunk_size - chunk.len()) { + v.push(' ' as u8); + v.push(' ' as u8); + v.push(' ' as u8); + } + } + v.push('\t' as u8); + + for &byte in chunk { + if (byte >=32 && byte <= 126) || byte >= 128 { + v.push(byte); + } else { + v.push('.' as u8); + } + } + v.push('\n' as u8); + } + + String::from_utf8_lossy(&v[..]).into_owned() + } +} + +/// Prints a message if the parser fails +/// +/// The message prints the `Error` or `Incomplete` +/// and the parser's calling code +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # fn main() { +/// named!(f, dbg!( tag!( "abcd" ) ) ); +/// +/// let a = &b"efgh"[..]; +/// +/// // Will print the following message: +/// // Error(Position(0, [101, 102, 103, 104])) at l.5 by ' tag ! ( "abcd" ) ' +/// f(a); +/// # } +/// ``` +#[macro_export] +macro_rules! dbg ( + ($i: expr, $submac:ident!( $($args:tt)* )) => ( + { + let l = line!(); + match $submac!($i, $($args)*) { + $crate::IResult::Error(a) => { + println!("Error({:?}) at l.{} by ' {} '", a, l, stringify!($submac!($($args)*))); + $crate::IResult::Error(a) + }, + $crate::IResult::Incomplete(a) => { + println!("Incomplete({:?}) at {} by ' {} '", a, l, stringify!($submac!($($args)*))); + $crate::IResult::Incomplete(a) + }, + a => a + } + } + ); + + ($i:expr, $f:ident) => ( + dbg!($i, call!($f)); + ); +); + +/// Prints a message and the input if the parser fails +/// +/// The message prints the `Error` or `Incomplete` +/// and the parser's calling code. +/// +/// It also displays the input in hexdump format +/// +/// ```ignore +/// # #[macro_use] extern crate nom; +/// # fn main() { +/// named!(f, dbg_dmp!( tag!( "abcd" ) ) ); +/// +/// let a = &b"efghijkl"[..]; +/// +/// // Will print the following message: +/// // Error(Position(0, [101, 102, 103, 104, 105, 106, 107, 108])) at l.5 by ' tag ! ( "abcd" ) ' +/// // 00000000 65 66 67 68 69 6a 6b 6c efghijkl +/// f(a); +/// # } +#[macro_export] +macro_rules! dbg_dmp ( + ($i: expr, $submac:ident!( $($args:tt)* )) => ( + { + use $crate::HexDisplay; + let l = line!(); + match $submac!($i, $($args)*) { + $crate::IResult::Error(a) => { + println!("Error({:?}) at l.{} by ' {} '\n{}", a, l, stringify!($submac!($($args)*)), $i.to_hex(8)); + $crate::IResult::Error(a) + }, + $crate::IResult::Incomplete(a) => { + println!("Incomplete({:?}) at {} by ' {} '\n{}", a, l, stringify!($submac!($($args)*)), $i.to_hex(8)); + $crate::IResult::Incomplete(a) + }, + a => a + } + } + ); + + ($i:expr, $f:ident) => ( + dbg_dmp!($i, call!($f)); + ); +); + +#[cfg(feature = "verbose-errors")] +pub fn error_to_list(e:&Err) -> Vec> { + let mut v:Vec> = Vec::new(); + match e { + &Err::Code(ref i) | &Err::Position(ref i,_) => { + v.push(i.clone()); + return v; + }, + &Err::Node(ref i, ref next) | &Err::NodePosition(ref i, _, ref next) => { + //v.push(i.clone()); + for error in next.iter() { + if let &Err::Code(ref i2) = error { + v.push(i2.clone()); + } + if let &Err::Position(ref i2,_) = error { + v.push(i2.clone()); + } + } + v.push(i.clone()); + v.reverse() + } + } + + v +} + +#[cfg(feature = "verbose-errors")] +pub fn compare_error_paths(e1:&Err, e2:&Err) -> bool { + error_to_list(e1) == error_to_list(e2) +} + + +#[cfg(feature = "std")] +#[cfg(feature = "verbose-errors")] +use std::hash::Hash; + +#[cfg(feature = "std")] +#[cfg(feature = "verbose-errors")] +pub fn add_error_pattern<'a,I,O,E: Clone+Hash+Eq>(h: &mut HashMap>, &'a str>, res: IResult, message: &'a str) -> bool { + if let IResult::Error(e) = res { + h.insert(error_to_list(&e), message); + true + } else { + false + } +} + +pub fn slice_to_offsets(input: &[u8], s: &[u8]) -> (usize, usize) { + let start = input.as_ptr(); + let off1 = s.as_ptr() as usize - start as usize; + let off2 = off1 + s.len(); + (off1, off2) +} + +#[cfg(feature = "std")] +#[cfg(feature = "verbose-errors")] +pub fn prepare_errors(input: &[u8], res: IResult<&[u8],O,E>) -> Option, usize, usize)> > { + if let IResult::Error(e) = res { + let mut v:Vec<(ErrorKind, usize, usize)> = Vec::new(); + + match e { + Err::Code(_) => {}, + Err::Position(i, p) => { + let (o1, o2) = slice_to_offsets(input, p); + v.push((i, o1, o2)); + }, + Err::Node(_, _) => {}, + Err::NodePosition(i, p, next) => { + //v.push(i.clone()); + for error in next.iter() { + if let &Err::Position(ref i2, ref p2) = error { + let (o1, o2) = slice_to_offsets(input, p2); + v.push((i2.clone(), o1, o2)); + } + } + let (o1, o2) = slice_to_offsets(input, p); + v.push((i, o1, o2)); + v.reverse() + } + } + + v.sort_by(|a, b| a.1.cmp(&b.1)); + Some(v) + } else { + None + } +} + +#[cfg(feature = "std")] +#[cfg(feature = "verbose-errors")] +pub fn print_error(input: &[u8], res: IResult<&[u8],O,E>) { + if let Some(v) = prepare_errors(input, res) { + let colors = generate_colors(&v); + println!("parser codes: {}", print_codes(colors, HashMap::new())); + println!("{}", print_offsets(input, 0, &v)); + + } else { + println!("not an error"); + } +} + +#[cfg(feature = "std")] +#[cfg(feature = "verbose-errors")] +pub fn generate_colors(v: &[(ErrorKind, usize, usize)]) -> HashMap { + let mut h: HashMap = HashMap::new(); + let mut color = 0; + + for &(ref c,_,_) in v.iter() { + h.insert(error_to_u32(c), color + 31); + color = color + 1 % 7; + } + + h +} + +pub fn code_from_offset(v: &[(ErrorKind, usize, usize)], offset: usize) -> Option { + let mut acc: Option<(u32, usize, usize)> = None; + for &(ref ek, s, e) in v.iter() { + let c = error_to_u32(ek); + if s <= offset && offset <=e { + if let Some((_, start, end)) = acc { + if start <= s && e <= end { + acc = Some((c, s, e)); + } + } else { + acc = Some((c, s, e)); + } + } + } + if let Some((code, _, _)) = acc { + return Some(code); + } else { + return None; + } +} + +pub fn reset_color(v: &mut Vec) { + v.push(0x1B); + v.push('[' as u8); + v.push(0); + v.push('m' as u8); +} + +pub fn write_color(v: &mut Vec, color: u8) { + v.push(0x1B); + v.push('[' as u8); + v.push(1); + v.push(';' as u8); + let s = color.to_string(); + let bytes = s.as_bytes(); + v.extend(bytes.iter().cloned()); + v.push('m' as u8); +} + +#[cfg(feature = "std")] +pub fn print_codes(colors: HashMap, names: HashMap) -> String { + let mut v = Vec::new(); + for (code, &color) in &colors { + if let Some(&s) = names.get(&code) { + let bytes = s.as_bytes(); + write_color(&mut v, color); + v.extend(bytes.iter().cloned()); + } else { + let s = code.to_string(); + let bytes = s.as_bytes(); + write_color(&mut v, color); + v.extend(bytes.iter().cloned()); + } + reset_color(&mut v); + v.push(' ' as u8); + } + reset_color(&mut v); + + String::from_utf8_lossy(&v[..]).into_owned() +} + +#[cfg(feature = "std")] +#[cfg(feature = "verbose-errors")] +pub fn print_offsets(input: &[u8], from: usize, offsets: &[(ErrorKind, usize, usize)]) -> String { + let mut v = Vec::with_capacity(input.len() * 3); + let mut i = from; + let chunk_size = 8; + let mut current_code: Option = None; + let mut current_code2: Option = None; + + let colors = generate_colors(&offsets); + + for chunk in input.chunks(chunk_size) { + let s = format!("{:08x}", i); + for &ch in s.as_bytes().iter() { + v.push(ch); + } + v.push('\t' as u8); + + let mut k = i; + let mut l = i; + for &byte in chunk { + if let Some(code) = code_from_offset(&offsets, k) { + if let Some(current) = current_code { + if current != code { + reset_color(&mut v); + current_code = Some(code); + if let Some(&color) = colors.get(&code) { + write_color(&mut v, color); + } + } + } else { + current_code = Some(code); + if let Some(&color) = colors.get(&code) { + write_color(&mut v, color); + } + } + } + v.push(CHARS[(byte >> 4) as usize]); + v.push(CHARS[(byte & 0xf) as usize]); + v.push(' ' as u8); + k = k + 1; + } + + reset_color(&mut v); + + if chunk_size > chunk.len() { + for _ in 0..(chunk_size - chunk.len()) { + v.push(' ' as u8); + v.push(' ' as u8); + v.push(' ' as u8); + } + } + v.push('\t' as u8); + + for &byte in chunk { + if let Some(code) = code_from_offset(&offsets, l) { + if let Some(current) = current_code2 { + if current != code { + reset_color(&mut v); + current_code2 = Some(code); + if let Some(&color) = colors.get(&code) { + write_color(&mut v, color); + } + } + } else { + current_code2 = Some(code); + if let Some(&color) = colors.get(&code) { + write_color(&mut v, color); + } + } + } + if (byte >=32 && byte <= 126) || byte >= 128 { + v.push(byte); + } else { + v.push('.' as u8); + } + l = l + 1; + } + reset_color(&mut v); + + v.push('\n' as u8); + i = i + chunk_size; + } + + String::from_utf8_lossy(&v[..]).into_owned() +} + +pub trait AsBytes { + fn as_bytes(&self) -> &[u8]; +} + +impl<'a> AsBytes for &'a str { + #[inline(always)] + fn as_bytes(&self) -> &[u8] { + str::as_bytes(self) + } +} + +impl AsBytes for str { + #[inline(always)] + fn as_bytes(&self) -> &[u8] { + str::as_bytes(self) + } +} + +impl<'a> AsBytes for &'a [u8] { + #[inline(always)] + fn as_bytes(&self) -> &[u8] { + *self + } +} + +impl AsBytes for [u8] { + #[inline(always)] + fn as_bytes(&self) -> &[u8] { + self + } +} + +macro_rules! array_impls { + ($($N:expr)+) => { + $( + impl<'a> AsBytes for &'a [u8; $N] { + #[inline(always)] + fn as_bytes(&self) -> &[u8] { + *self + } + } + + impl AsBytes for [u8; $N] { + #[inline(always)] + fn as_bytes(&self) -> &[u8] { + self + } + } + )+ + }; +} + + +array_impls! { + 0 1 2 3 4 5 6 7 8 9 + 10 11 12 13 14 15 16 17 18 19 + 20 21 22 23 24 25 26 27 28 29 + 30 31 32 +} + +/// indicates which parser returned an error +#[derive(Debug,PartialEq,Eq,Hash,Clone)] +pub enum ErrorKind { + Custom(E), + Tag, + MapRes, + MapOpt, + Alt, + IsNot, + IsA, + SeparatedList, + SeparatedNonEmptyList, + Many0, + Many1, + ManyTill, + Count, + TakeUntilAndConsume, + TakeUntil, + TakeUntilEitherAndConsume, + TakeUntilEither, + LengthValue, + TagClosure, + Alpha, + Digit, + HexDigit, + OctDigit, + AlphaNumeric, + Space, + MultiSpace, + LengthValueFn, + Eof, + ExprOpt, + ExprRes, + CondReduce, + Switch, + TagBits, + OneOf, + NoneOf, + Char, + CrLf, + RegexpMatch, + RegexpMatches, + RegexpFind, + RegexpCapture, + RegexpCaptures, + TakeWhile1, + Complete, + Fix, + Escaped, + EscapedTransform, + TagStr, + IsNotStr, + IsAStr, + TakeWhile1Str, + NonEmpty, + ManyMN, + TakeUntilAndConsumeStr, + TakeUntilStr, + Not, + Permutation, + Verify, + TakeTill1, +} + +pub fn error_to_u32(e: &ErrorKind) -> u32 { + match *e { + ErrorKind::Custom(_) => 0, + ErrorKind::Tag => 1, + ErrorKind::MapRes => 2, + ErrorKind::MapOpt => 3, + ErrorKind::Alt => 4, + ErrorKind::IsNot => 5, + ErrorKind::IsA => 6, + ErrorKind::SeparatedList => 7, + ErrorKind::SeparatedNonEmptyList => 8, + ErrorKind::Many1 => 9, + ErrorKind::Count => 10, + ErrorKind::TakeUntilAndConsume => 11, + ErrorKind::TakeUntil => 12, + ErrorKind::TakeUntilEitherAndConsume => 13, + ErrorKind::TakeUntilEither => 14, + ErrorKind::LengthValue => 15, + ErrorKind::TagClosure => 16, + ErrorKind::Alpha => 17, + ErrorKind::Digit => 18, + ErrorKind::AlphaNumeric => 19, + ErrorKind::Space => 20, + ErrorKind::MultiSpace => 21, + ErrorKind::LengthValueFn => 22, + ErrorKind::Eof => 23, + ErrorKind::ExprOpt => 24, + ErrorKind::ExprRes => 25, + ErrorKind::CondReduce => 26, + ErrorKind::Switch => 27, + ErrorKind::TagBits => 28, + ErrorKind::OneOf => 29, + ErrorKind::NoneOf => 30, + ErrorKind::Char => 40, + ErrorKind::CrLf => 41, + ErrorKind::RegexpMatch => 42, + ErrorKind::RegexpMatches => 43, + ErrorKind::RegexpFind => 44, + ErrorKind::RegexpCapture => 45, + ErrorKind::RegexpCaptures => 46, + ErrorKind::TakeWhile1 => 47, + ErrorKind::Complete => 48, + ErrorKind::Fix => 49, + ErrorKind::Escaped => 50, + ErrorKind::EscapedTransform => 51, + ErrorKind::TagStr => 52, + ErrorKind::IsNotStr => 53, + ErrorKind::IsAStr => 54, + ErrorKind::TakeWhile1Str => 55, + ErrorKind::NonEmpty => 56, + ErrorKind::ManyMN => 57, + ErrorKind::TakeUntilAndConsumeStr => 58, + ErrorKind::HexDigit => 59, + ErrorKind::TakeUntilStr => 60, + ErrorKind::OctDigit => 61, + ErrorKind::Many0 => 62, + ErrorKind::Not => 63, + ErrorKind::Permutation => 64, + ErrorKind::ManyTill => 65, + ErrorKind::Verify => 66, + ErrorKind::TakeTill1 => 67, + } +} + + impl ErrorKind { + pub fn description(&self) -> &str { + match *self { + ErrorKind::Custom(_) => "Custom error", + ErrorKind::Tag => "Tag", + ErrorKind::MapRes => "Map on Result", + ErrorKind::MapOpt => "Map on Option", + ErrorKind::Alt => "Alternative", + ErrorKind::IsNot => "IsNot", + ErrorKind::IsA => "IsA", + ErrorKind::SeparatedList => "Separated list", + ErrorKind::SeparatedNonEmptyList => "Separated non empty list", + ErrorKind::Many0 => "Many0", + ErrorKind::Many1 => "Many1", + ErrorKind::Count => "Count", + ErrorKind::TakeUntilAndConsume => "Take until and consume", + ErrorKind::TakeUntil => "Take until", + ErrorKind::TakeUntilEitherAndConsume => "Take until either and consume", + ErrorKind::TakeUntilEither => "Take until either", + ErrorKind::LengthValue => "Length followed by value", + ErrorKind::TagClosure => "Tag closure", + ErrorKind::Alpha => "Alphabetic", + ErrorKind::Digit => "Digit", + ErrorKind::AlphaNumeric => "AlphaNumeric", + ErrorKind::Space => "Space", + ErrorKind::MultiSpace => "Multiple spaces", + ErrorKind::LengthValueFn => "LengthValueFn", + ErrorKind::Eof => "End of file", + ErrorKind::ExprOpt => "Evaluate Option", + ErrorKind::ExprRes => "Evaluate Result", + ErrorKind::CondReduce => "Condition reduce", + ErrorKind::Switch => "Switch", + ErrorKind::TagBits => "Tag on bitstream", + ErrorKind::OneOf => "OneOf", + ErrorKind::NoneOf => "NoneOf", + ErrorKind::Char => "Char", + ErrorKind::CrLf => "CrLf", + ErrorKind::RegexpMatch => "RegexpMatch", + ErrorKind::RegexpMatches => "RegexpMatches", + ErrorKind::RegexpFind => "RegexpFind", + ErrorKind::RegexpCapture => "RegexpCapture", + ErrorKind::RegexpCaptures => "RegexpCaptures", + ErrorKind::TakeWhile1 => "TakeWhile1", + ErrorKind::Complete => "Complete", + ErrorKind::Fix => "Fix", + ErrorKind::Escaped => "Escaped", + ErrorKind::EscapedTransform => "EscapedTransform", + ErrorKind::TagStr => "Tag on strings", + ErrorKind::IsNotStr => "IsNot on strings", + ErrorKind::IsAStr => "IsA on strings", + ErrorKind::TakeWhile1Str => "TakeWhile1 on strings", + ErrorKind::NonEmpty => "NonEmpty", + ErrorKind::ManyMN => "Many(m, n)", + ErrorKind::TakeUntilAndConsumeStr => "Take until and consume on strings", + ErrorKind::HexDigit => "Hexadecimal Digit", + ErrorKind::TakeUntilStr => "Take until on strings", + ErrorKind::OctDigit => "Octal digit", + ErrorKind::Not => "Negation", + ErrorKind::Permutation => "Permutation", + ErrorKind::ManyTill => "ManyTill", + ErrorKind::Verify => "predicate verification", + ErrorKind::TakeTill1 => "TakeTill1", + } + + } + /// Convert Err into an ErrorKind. + /// + /// This allows application code to use ErrorKind and stay independent from the `verbose-errors` features activation. + pub fn into_error_kind(self) -> ErrorKind { + self + } + } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_offset_u8() { + let s = b"abcd123"; + let a = &s[..]; + let b = &a[2..]; + let c = &a[..4]; + let d = &a[3..5]; + assert_eq!(a.offset(b), 2); + assert_eq!(a.offset(c), 0); + assert_eq!(a.offset(d), 3); + } + + #[test] + fn test_offset_str() { + let s = "abcřèÂßÇd123"; + let a = &s[..]; + let b = &a[7..]; + let c = &a[..5]; + let d = &a[5..9]; + assert_eq!(a.offset(b), 7); + assert_eq!(a.offset(c), 0); + assert_eq!(a.offset(d), 5); + } +} diff --git a/bash-5.1/vendor/nom/src/verbose_errors.rs b/bash-5.1/vendor/nom/src/verbose_errors.rs new file mode 100644 index 0000000..fe236b6 --- /dev/null +++ b/bash-5.1/vendor/nom/src/verbose_errors.rs @@ -0,0 +1,227 @@ +//! Error management +//! +//! there are two ways to handle errors in nom. The first one, +//! activated by default, uses the `nom::ErrorKind` enum +//! in the error branch of `IResult`. This enum can hold either +//! a parser specific error code, or a custom error type you +//! specify. +//! +//! If you need more advanced error management, you can activate +//! the "verbose-errors" compilation feature, which will give you +//! the error system available in nom 1.0. The verbose errors +//! accumulate error codes and positions as you backtrack through +//! the parser tree. From there, you can precisely identify which +//! parts of the input triggered the error case. +//! +//! Please note that the verbose error management is a bit slower +//! than the simple one. +use util::ErrorKind; +use internal::{IResult, IError}; +use internal::IResult::*; + +/// Contains the error that a parser can return +/// +/// If you use the `verbose-errors` compilation feature, +/// `nom::Err` will be the enum defined here, +/// otherwise, it will amount to a `ErrorKind`. +/// +/// It can represent a linked list of errors, indicating the path taken in the parsing tree, with corresponding position in the input data. +/// It depends on P, the input position (for a &[u8] parser, it would be a &[u8]), and E, the custom error type (by default, u32) +#[derive(Debug,PartialEq,Eq,Clone)] +pub enum Err{ + /// An error code, represented by an ErrorKind, which can contain a custom error code represented by E + Code(ErrorKind), + /// An error code, and the next error + Node(ErrorKind, Vec>), + /// An error code, and the input position + Position(ErrorKind, P), + /// An error code, the input position and the next error + NodePosition(ErrorKind, P, Vec>) +} + +impl Err { + /// Convert Err into ErrorKind. + /// + /// This allows application code to use ErrorKind and stay independent from the verbose-errors features activation. + pub fn into_error_kind(self) -> ErrorKind { + match self { + Err::Code(kind) => kind, + Err::Node(kind, _) => kind, + Err::Position(kind, _) => kind, + Err::NodePosition(kind, _, _) => kind, + } + } +} + +impl IResult { + /// Maps a `IResult` to `IResult` by appling a function + /// to a contained `Error` value, leaving `Done` and `Incomplete` value + /// untouched. + #[inline] + pub fn map_err(self, f: F) -> IResult + where F: FnOnce(Err) -> Err { + match self { + Error(e) => Error(f(e)), + Incomplete(n) => Incomplete(n), + Done(i, o) => Done(i, o), + } + } + + /// Unwrap the contained `Error(I, E)` value, or panic if the `IResult` is not + /// `Error`. + pub fn unwrap_err(self) -> Err { + match self { + Error(e) => e, + Done(_, _) => panic!("unwrap_err() called on an IResult that is Done"), + Incomplete(_) => panic!("unwrap_err() called on an IResult that is Incomplete"), + } + } + + /// Convert the IResult to a std::result::Result + pub fn to_full_result(self) -> Result> { + match self { + Done(_, o) => Ok(o), + Incomplete(n) => Err(IError::Incomplete(n)), + Error(e) => Err(IError::Error(e)) + } + } + + /// Convert the IResult to a std::result::Result + pub fn to_result(self) -> Result> { + match self { + Done(_, o) => Ok(o), + Error(e) => Err(e), + Incomplete(_) => panic!("to_result() called on an IResult that is Incomplete") + } + } +} + +#[cfg(feature = "std")] +use std::any::Any; +#[cfg(feature = "std")] +use std::{error,fmt}; +#[cfg(feature = "std")] +use std::fmt::Debug; +#[cfg(feature = "std")] +impl error::Error for Err { + fn description(&self) -> &str { + let kind = match *self { + Err::Code(ref e) | Err::Node(ref e, _) | Err::Position(ref e, _) | Err::NodePosition(ref e, _, _) => e + }; + kind.description() + } +} + +#[cfg(feature = "std")] +impl fmt::Display for Err { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Err::Code(ref e) | Err::Node(ref e, _) => { + write!(f, "{:?}", e) + }, + Err::Position(ref e, ref p) | Err::NodePosition(ref e, ref p, _) => { + write!(f, "{:?}:{:?}", p, e) + } + } + } +} + + +/// translate parser result from IResult to IResult with a custom type +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use std::collections; +/// # use nom::IResult::Error; +/// # use nom::Err::{Position,NodePosition}; +/// # use nom::ErrorKind; +/// # fn main() { +/// // will add a Custom(42) error to the error chain +/// named!(err_test, add_return_error!(ErrorKind::Custom(42), tag!("abcd"))); +/// // Convert to IREsult<&[u8], &[u8], &str> +/// named!(parser<&[u8], &[u8], &str>, add_return_error!(ErrorKind::Custom("custom error message"), fix_error!(&str, err_test))); +/// +/// let a = &b"efghblah"[..]; +/// let res_a = parser(a); +/// assert_eq!(res_a, Error(NodePosition( ErrorKind::Custom("custom error message"), a, vec!(Position(ErrorKind::Fix, a))))); +/// # } +/// ``` +#[macro_export] +macro_rules! fix_error ( + ($i:expr, $t:ty, $submac:ident!( $($args:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Done(i, o) => $crate::IResult::Done(i, o), + $crate::IResult::Error(e) => { + let err = match e { + $crate::Err::Code($crate::ErrorKind::Custom(_)) | + $crate::Err::Node($crate::ErrorKind::Custom(_), _) => { + let e: $crate::ErrorKind<$t> = $crate::ErrorKind::Fix; + $crate::Err::Code(e) + }, + $crate::Err::Position($crate::ErrorKind::Custom(_), p) | + $crate::Err::NodePosition($crate::ErrorKind::Custom(_), p, _) => { + let e: $crate::ErrorKind<$t> = $crate::ErrorKind::Fix; + $crate::Err::Position(e, p) + }, + $crate::Err::Code(_) | + $crate::Err::Node(_, _) => { + let e: $crate::ErrorKind<$t> = $crate::ErrorKind::Fix; + $crate::Err::Code(e) + }, + $crate::Err::Position(_, p) | + $crate::Err::NodePosition(_, p, _) => { + let e: $crate::ErrorKind<$t> = $crate::ErrorKind::Fix; + $crate::Err::Position(e, p) + }, + }; + $crate::IResult::Error(err) + } + } + } + ); + ($i:expr, $t:ty, $f:expr) => ( + fix_error!($i, $t, call!($f)); + ); +); + +/// `flat_map!(R -> IResult, S -> IResult) => R -> IResult` +/// +/// combines a parser R -> IResult and +/// a parser S -> IResult to return another +/// parser R -> IResult +#[macro_export] +macro_rules! flat_map( + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + { + match $submac!($i, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)), + $crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) { + $crate::IResult::Error(e) => { + let err = match e { + $crate::Err::Code(k) | $crate::Err::Node(k, _) | $crate::Err::Position(k, _) | $crate::Err::NodePosition(k, _, _) => { + $crate::Err::Position(k, $i) + } + }; + $crate::IResult::Error(err) + }, + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(ref i2)) => $crate::IResult::Incomplete($crate::Needed::Size(*i2)), + $crate::IResult::Done(_, o2) => $crate::IResult::Done(i, o2) + } + } + } + ); + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( + flat_map!($i, $submac!($($args)*), call!($g)); + ); + ($i:expr, $f:expr, $g:expr) => ( + flat_map!($i, call!($f), call!($g)); + ); + ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( + flat_map!($i, call!($f), $submac!($($args)*)); + ); +); diff --git a/bash-5.1/vendor/nom/src/whitespace.rs b/bash-5.1/vendor/nom/src/whitespace.rs new file mode 100644 index 0000000..3b8f7bd --- /dev/null +++ b/bash-5.1/vendor/nom/src/whitespace.rs @@ -0,0 +1,1056 @@ +//! Support for whitespace delimited formats +//! +//! a lot of textual formats allows spaces and other +//! types of separators between tokens. Handling it +//! manually with nom means wrapping all parsers +//! like this: +//! +//! ```ignore +//! named!(token, delimited!(space, tk, space)); +//! ``` +//! +//! To ease the development of such parsers, you +//! can use the whitespace parsing facility, which works +//! as follows: +//! +//! ``` +//! # #[macro_use] extern crate nom; +//! # use nom::IResult::Done; +//! # fn main() { +//! named!(tuple<&[u8], (&[u8], &[u8]) >, +//! ws!(tuple!( take!(3), tag!("de") )) +//! ); +//! +//! assert_eq!( +//! tuple(&b" \t abc de fg"[..]), +//! Done(&b"fg"[..], (&b"abc"[..], &b"de"[..])) +//! ); +//! # } +//! ``` +//! +//! The `ws!` combinator will modify the parser to +//! intersperse space parsers everywhere. By default, +//! it will consume the following characters: " \t\r\n". +//! +//! If you want to modify that behaviour, you can make +//! your own whitespace wrapper. As an example, if +//! you don't want to consume ends of lines, only +//! spaces and tabs, you can do it like this: +//! +//! ``` +//! # #[macro_use] extern crate nom; +//! # use nom::IResult::Done; +//! named!(pub space, eat_separator!(&b" \t"[..])); +//! +//! #[macro_export] +//! macro_rules! sp ( +//! ($i:expr, $($args:tt)*) => ( +//! { +//! sep!($i, space, $($args)*) +//! } +//! ) +//! ); +//! +//! # fn main() { +//! named!(tuple<&[u8], (&[u8], &[u8]) >, +//! sp!(tuple!( take!(3), tag!("de") )) +//! ); +//! +//! assert_eq!( +//! tuple(&b" \t abc de fg"[..]), +//! Done(&b"fg"[..], (&b"abc"[..], &b"de"[..])) +//! ); +//! # } +//! ``` +//! +//! This combinator works by replacing each combinator with +//! a version that supports wrapping with separator parsers. +//! It will not support the combinators you wrote in your +//! own code. You can still manually wrap them with the separator +//! you want, or you can copy the macros defined in src/whitespace.rs +//! and modify them to support a new combinator: +//! * copy the combinator's code here, add the _sep suffix +//! * add the `$separator:expr` as second argument +//! * wrap any sub parsers with sep!($separator, $submac!($($args)*)) +//! * reference it in the definition of `sep!` as follows: +//! +//! ```ignore +//! ($i:expr, $separator:ident, my_combinator ! ($($rest:tt)*) ) => { +//! wrap_sep!($i, +//! $separator, +//! my_combinator_sep!($separator, $($rest)*) +//! ) +//! }; +//! ``` +//! + +#[macro_export] +macro_rules! wrap_sep ( + ($i:expr, $separator:expr, $submac:ident!( $($args:tt)* )) => ( + match ($separator)($i) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i1,_) => { + match $submac!(i1, $($args)*) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i + ($crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i1)))), + $crate::IResult::Done(i2,o) => { + match ($separator)(i2) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i + ($crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i2)))), + $crate::IResult::Done(i3,_) => $crate::IResult::Done(i3, o) + } + } + } + } + } + ); + ($i:expr, $separator:expr, $f:expr) => ( + wrap_sep!($i, $separator, call!($f)) + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! pair_sep ( + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + tuple!( + $i, + sep!($separator, $submac!($($args)*)), + sep!($separator, $submac2!($($args2)*)) + ) + ); + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $g:expr) => ( + pair_sep!($i, $separator, $submac!($($args)*), call!($g)); + ); + ($i:expr, $separator:ident, $f:expr, $submac:ident!( $($args:tt)* )) => ( + pair_sep!($i, $separator, call!($f), $submac!($($args)*)); + ); + ($i:expr, $separator:ident, $f:expr, $g:expr) => ( + pair_sep!($i, $separator, call!($f), call!($g)); + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! delimited_sep ( + ($i:expr, $separator:ident, $submac1:ident!( $($args1:tt)* ), $($rest:tt)+) => ( + match tuple_sep!($i, $separator, 0usize, (), $submac1!($($args1)*), $($rest)*) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(remaining, (_,o,_)) => { + $crate::IResult::Done(remaining, o) + } + } + ); + ($i:expr, $separator:ident, $f:expr, $($rest:tt)+) => ( + delimited_sep!($i, $separator, call!($f), $($rest)*); + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! separated_pair_sep ( + ($i:expr, $separator:ident, $submac1:ident!( $($args1:tt)* ), $($rest:tt)+) => ( + match tuple_sep!($i, $separator, 0usize, (), $submac1!($($args1)*), $($rest)*) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(remaining, (o1,_,o2)) => { + $crate::IResult::Done(remaining, (o1,o2)) + } + } + ); + ($i:expr, $separator:ident, $f:expr, $($rest:tt)+) => ( + separated_pair_sep!($i, $separator, call!($f), $($rest)*); + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! preceded_sep ( + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + match pair_sep!($i, $separator, $submac!($($args)*), $submac2!($($args2)*)) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(remaining, (_,o)) => { + $crate::IResult::Done(remaining, o) + } + } + ); + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $g:expr) => ( + preceded_sep!($i, $separator, $submac!($($args)*), call!($g)); + ); + ($i:expr, $separator:ident, $f:expr, $submac:ident!( $($args:tt)* )) => ( + preceded_sep!($i, $separator, call!($f), $submac!($($args)*)); + ); + ($i:expr, $separator:ident, $f:expr, $g:expr) => ( + preceded_sep!($i, $separator, call!($f), call!($g)); + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! terminated_sep ( + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + match pair_sep!($i, $separator, $submac!($($args)*), $submac2!($($args2)*)) { + $crate::IResult::Error(a) => $crate::IResult::Error(a), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(remaining, (o,_)) => { + $crate::IResult::Done(remaining, o) + } + } + ); + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $g:expr) => ( + terminated_sep!($i, $separator, $submac!($($args)*), call!($g)); + ); + ($i:expr, $separator:ident, $f:expr, $submac:ident!( $($args:tt)* )) => ( + terminated_sep!($i, $separator, call!($f), $submac!($($args)*)); + ); + ($i:expr, $separator:ident, $f:expr, $g:expr) => ( + terminated_sep!($i, $separator, call!($f), call!($g)); + ); +); + +/// Internal parser, do not use directly +#[doc(hidden)] +#[macro_export] +macro_rules! tuple_sep ( + ($i:expr, $separator:ident, $consumed:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => ( + tuple_sep!($i, $separator, $consumed, ($($parsed),*), call!($e), $($rest)*); + ); + ($i:expr, $separator:ident, $consumed:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,o) => { + tuple_sep!(i, $separator, $consumed + ($crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i)), (o), $($rest)*) + } + } + } + ); + ($i:expr, $separator:ident, $consumed:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,o) => { + tuple_sep!(i, $separator, $consumed + ($crate::InputLength::input_len(&($i)) - $crate::InputLength::input_len(&i)), ($($parsed)* , o), $($rest)*) + } + } + } + ); + ($i:expr, $separator:ident, $consumed:expr, ($($parsed:tt),*), $e:ident) => ( + tuple_sep!($i, $separator, $consumed, ($($parsed),*), call!($e)); + ); + ($i:expr, $separator:ident, $consumed:expr, (), $submac:ident!( $($args:tt)* )) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,o) => { + $crate::IResult::Done(i, (o)) + } + } + } + ); + ($i:expr, $separator:ident, $consumed:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,o) => { + $crate::IResult::Done(i, ($($parsed),* , o)) + } + } + } + ); + ($i:expr, $separator:ident, $consumed:expr, ($($parsed:expr),*)) => ( + { + $crate::IResult::Done($i, ($($parsed),*)) + } + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! do_parse_sep ( + (__impl $i:expr, $separator:ident, $consumed:expr, ( $($rest:expr),* )) => ( + $crate::IResult::Done($i, ( $($rest),* )) + ); + + (__impl $i:expr, $separator:ident, $consumed:expr, $e:ident >> $($rest:tt)*) => ( + do_parse_sep!(__impl $i, $separator, $consumed, call!($e) >> $($rest)*); + ); + (__impl $i:expr, $separator:ident, $consumed:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => + $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,_) => { + do_parse_sep!(__impl i, $separator, + $consumed + ($crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&i)), $($rest)*) + }, + } + } + ); + + (__impl $i:expr, $separator:ident, $consumed:expr, $field:ident : $e:ident >> $($rest:tt)*) => ( + do_parse_sep!(__impl $i, $separator, $consumed, $field: call!($e) >> $($rest)*); + ); + + (__impl $i:expr, $separator:ident, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => + $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,o) => { + let $field = o; + do_parse_sep!(__impl i, $separator, + $consumed + ($crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&i)), $($rest)*) + }, + } + } + ); + + // ending the chain + (__impl $i:expr, $separator:ident, $consumed:expr, $e:ident >> ( $($rest:tt)* )) => ( + do_parse_sep!(__impl $i, $separator, $consumed, call!($e) >> ( $($rest)* )); + ); + + (__impl $i:expr, $separator:ident, $consumed:expr, $submac:ident!( $($args:tt)* ) >> ( $($rest:tt)* )) => ( + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => + $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,_) => { + $crate::IResult::Done(i, ( $($rest)* )) + }, + } + ); + + (__impl $i:expr, $separator:ident, $consumed:expr, $field:ident : $e:ident >> ( $($rest:tt)* )) => ( + do_parse_sep!(__impl $i, $separator, $consumed, $field: call!($e) >> ( $($rest)* ) ); + ); + + (__impl $i:expr, $separator:ident, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> ( $($rest:tt)* )) => ( + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(e), + $crate::IResult::Incomplete($crate::Needed::Unknown) => + $crate::IResult::Incomplete($crate::Needed::Unknown), + $crate::IResult::Incomplete($crate::Needed::Size(i)) => + $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)), + $crate::IResult::Done(i,o) => { + let $field = o; + $crate::IResult::Done(i, ( $($rest)* )) + }, + } + ); + + ($i:expr, $separator:ident, $($rest:tt)*) => ( + { + do_parse_sep!(__impl $i, $separator, 0usize, $($rest)*) + } + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! permutation_sep ( + ($i:expr, $separator:ident, $($rest:tt)*) => ( + { + let mut res = permutation_init!((), $($rest)*); + let mut input = $i; + let mut error = ::std::option::Option::None; + let mut needed = ::std::option::Option::None; + + loop { + let mut all_done = true; + permutation_iterator_sep!(0, input, $separator, all_done, needed, res, $($rest)*); + + //if we reach that part, it means none of the parsers were able to read anything + if !all_done { + //FIXME: should wrap the error returned by the child parser + error = ::std::option::Option::Some(error_position!($crate::ErrorKind::Permutation, input)); + } + break; + } + + if let ::std::option::Option::Some(need) = needed { + if let $crate::Needed::Size(sz) = need { + $crate::IResult::Incomplete( + $crate::Needed::Size( + $crate::InputLength::input_len(&($i)) - + $crate::InputLength::input_len(&input) + + sz + ) + ) + } else { + $crate::IResult::Incomplete($crate::Needed::Unknown) + } + } else if let ::std::option::Option::Some(e) = error { + $crate::IResult::Error(e) + } else { + let unwrapped_res = permutation_unwrap!(0, (), res, $($rest)*); + $crate::IResult::Done(input, unwrapped_res) + } + } + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! permutation_iterator_sep ( + ($it:tt,$i:expr, $separator:ident, $all_done:expr, $needed:expr, $res:expr, $e:ident, $($rest:tt)*) => ( + permutation_iterator_sep!($it, $i, $separator, $all_done, $needed, $res, call!($e), $($rest)*); + ); + ($it:tt, $i:expr, $separator:ident, $all_done:expr, $needed:expr, $res:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)*) => { + if acc!($it, $res) == ::std::option::Option::None { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Done(i,o) => { + $i = i; + acc!($it, $res) = ::std::option::Option::Some(o); + continue; + }, + $crate::IResult::Error(_) => { + $all_done = false; + }, + $crate::IResult::Incomplete(i) => { + $needed = ::std::option::Option::Some(i); + break; + } + }; + } + succ!($it, permutation_iterator_sep!($i, $separator, $all_done, $needed, $res, $($rest)*)); + }; + ($it:tt,$i:expr, $separator:ident, $all_done:expr, $needed:expr, $res:expr, $e:ident) => ( + permutation_iterator_sep!($it, $i, $separator, $all_done, $res, call!($e)); + ); + ($it:tt, $i:expr, $separator:ident, $all_done:expr, $needed:expr, $res:expr, $submac:ident!( $($args:tt)* )) => { + if acc!($it, $res) == ::std::option::Option::None { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Done(i,o) => { + $i = i; + acc!($it, $res) = ::std::option::Option::Some(o); + continue; + }, + $crate::IResult::Error(_) => { + $all_done = false; + }, + $crate::IResult::Incomplete(i) => { + $needed = ::std::option::Option::Some(i); + break; + } + }; + } + }; +); + +#[doc(hidden)] +#[macro_export] +macro_rules! alt_sep ( + (__impl $i:expr, $separator:ident, $e:ident | $($rest:tt)*) => ( + alt_sep!(__impl $i, $separator, call!($e) | $($rest)*); + ); + + (__impl $i:expr, $separator:ident, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => ( + { + let res = sep!($i, $separator, $subrule!($($args)*)); + match res { + $crate::IResult::Done(_,_) => res, + $crate::IResult::Incomplete(_) => res, + _ => alt_sep!(__impl $i, $separator, $($rest)*) + } + } + ); + + (__impl $i:expr, $separator:ident, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => ( + { + match sep!($i, $separator, $subrule!( $($args)* )) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)), + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Error(_) => { + alt_sep!(__impl $i, $separator, $($rest)*) + } + } + } + ); + + (__impl $i:expr, $separator:ident, $e:ident => { $gen:expr } | $($rest:tt)*) => ( + alt_sep!(__impl $i, $separator, call!($e) => { $gen } | $($rest)*); + ); + + (__impl $i:expr, $separator:ident, $e:ident => { $gen:expr }) => ( + alt_sep!(__impl $i, $separator, call!($e) => { $gen }); + ); + + (__impl $i:expr, $separator:ident, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => ( + { + match sep!($i, $separator, $subrule!( $($args)* )) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)), + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Error(_) => { + $crate::IResult::Error(error_position!($crate::ErrorKind::Alt,$i)) + } + } + } + ); + + (__impl $i:expr, $separator:ident, $e:ident) => ( + alt_sep!(__impl $i, $separator, call!($e)); + ); + + (__impl $i:expr, $separator:ident, $subrule:ident!( $($args:tt)*)) => ( + { + match sep!($i, $separator, $subrule!( $($args)* )) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i,o), + $crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x), + $crate::IResult::Error(_) => { + $crate::IResult::Error(error_position!($crate::ErrorKind::Alt,$i)) + } + } + } + ); + + (__impl $i:expr) => ( + $crate::IResult::Error(error_position!($crate::ErrorKind::Alt,$i)) + ); + + (__impl $i:expr, $separator:ident) => ( + $crate::IResult::Error(error_position!($crate::ErrorKind::Alt,$i)) + ); + + ($i:expr, $separator:ident, $($rest:tt)*) => ( + { + alt_sep!(__impl $i, $separator, $($rest)*) + } + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! alt_complete_sep ( + ($i:expr, $separator:ident, $e:ident | $($rest:tt)*) => ( + alt_complete_sep!($i, $separator, complete!(call!($e)) | $($rest)*); + ); + + ($i:expr, $separator:ident, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => ( + { + let res = complete!($i, sep!($separator, $subrule!($($args)*))); + match res { + $crate::IResult::Done(_,_) => res, + _ => alt_complete_sep!($i, $separator, $($rest)*), + } + } + ); + + ($i:expr, $separator:ident, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => ( + { + match complete!($i, sep!($separator, $subrule!($($args)*))) { + $crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)), + _ => alt_complete_sep!($i, $separator, $($rest)*), + } + } + ); + + ($i:expr, $separator:ident, $e:ident => { $gen:expr } | $($rest:tt)*) => ( + alt_complete_sep!($i, $separator, complete!(call!($e)) => { $gen } | $($rest)*); + ); + + // Tail (non-recursive) rules + + ($i:expr, $separator:ident, $e:ident => { $gen:expr }) => ( + alt_complete_sep!($i, $separator, call!($e) => { $gen }); + ); + + ($i:expr, $separator:ident, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => ( + alt_sep!(__impl $i, $separator, $subrule!($($args)*) => { $gen }) + ); + + ($i:expr, $separator:ident, $e:ident) => ( + alt_complete_sep!($i, $separator, call!($e)); + ); + + ($i:expr, $separator:ident, $subrule:ident!( $($args:tt)*)) => ( + alt_sep!(__impl $i, $separator, $subrule!($($args)*)) + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! switch_sep ( + (__impl $i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => ( + { + match sep!($i, $separator, $submac!($($args)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(error_node_position!( + $crate::ErrorKind::Switch, $i, e + )), + $crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i), + $crate::IResult::Done(i, o) => { + match o { + $($p => match sep!(i, $separator, $subrule!($($args2)*)) { + $crate::IResult::Error(e) => $crate::IResult::Error(error_node_position!( + $crate::ErrorKind::Switch, $i, e + )), + a => a, + }),*, + _ => $crate::IResult::Error(error_position!($crate::ErrorKind::Switch,$i)) + } + } + } + } + ); + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)*), $($rest:tt)*) => ( + { + switch_sep!(__impl $i, $separator, $submac!($($args)*), $($rest)*) + } + ); + ($i:expr, $separator:ident, $e:ident, $($rest:tt)*) => ( + { + switch_sep!(__impl $i, $separator, call!($e), $($rest)*) + } + ); +); + +#[doc(hidden)] +#[macro_export] +macro_rules! separated_list_sep ( + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => ( + separated_list!( + $i, + sep!($separator, $submac!($($args)*)), + sep!($separator, $submac2!($($args2)*)) + ) + ); + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* ), $g:expr) => ( + separated_list_sep!($i, $separator, $submac!($($args)*), call!($g)); + ); + ($i:expr, $separator:ident, $f:expr, $submac:ident!( $($args:tt)* )) => ( + separated_list_sep!($i, $separator, call!($f), $submac!($($args)*)); + ); + ($i:expr, $separator:ident, $f:expr, $g:expr) => ( + separated_list_sep!($i, $separator, call!($f), call!($g)); + ); +); + +/// helper macros to build a separator parser +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// named!(pub space, eat_separator!(&b" \t"[..])); +/// # fn main() {} +/// ``` +#[macro_export] +macro_rules! eat_separator ( + ($i:expr, $arr:expr) => ( + { + use $crate::{AsChar,InputLength,InputIter,Slice}; + if ($i).input_len() == 0 { + $crate::IResult::Done(($i).slice(0..), ($i).slice(0..0)) + } else { + match ($i).iter_indices().position(|(_, item)| { + let i = item.as_char(); + for (_,c) in ($arr).iter_indices() { + if c.as_char() == i { return false; } + } + true + }) { + ::std::option::Option::Some(index) => { + $crate::IResult::Done(($i).slice(index..), ($i).slice(..index)) + }, + ::std::option::Option::None => { + $crate::IResult::Done(($i).slice(($i).input_len()..), ($i)) + } + } + } + } + ); +); + +/// sep is the parser rewriting macro for whitespace separated formats +/// +/// it takes as argument a space eating function and a parser tree, +/// and will intersperse the space parser everywhere +/// +/// ```ignore +/// #[macro_export] +/// macro_rules! ws ( +/// ($i:expr, $($args:tt)*) => ( +/// { +/// use $crate::sp; +/// sep!($i, sp, $($args)*) +/// } +/// ) +/// ); +/// ``` +#[macro_export] +macro_rules! sep ( + ($i:expr, $separator:ident, tuple ! ($($rest:tt)*) ) => { + tuple_sep!($i, $separator, 0usize, (), $($rest)*) + }; + ($i:expr, $separator:ident, pair ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + pair_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, delimited ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + delimited_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, separated_pair ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + separated_pair_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, preceded ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + preceded_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, terminated ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + terminated_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, do_parse ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + do_parse_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, permutation ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + permutation_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, alt ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + alt_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, alt_complete ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + alt_complete_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, switch ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + switch_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, separated_list ! ($($rest:tt)*) ) => { + wrap_sep!($i, + $separator, + separated_list_sep!($separator, $($rest)*) + ) + }; + ($i:expr, $separator:ident, many0 ! ($($rest:tt)*) ) => { + many0!($i, wrap_sep!($separator, $($rest)*)) + }; + ($i:expr, $separator:ident, many1 ! ($($rest:tt)*) ) => { + many1!($i, wrap_sep!($separator, $($rest)*)) + }; +//FIXME: missing separated_nonempty_list, +// many_till, many_m_n, count, count_fixed, fold_many0, fold_many1, +// fold_many_m_n + ($i:expr, $separator:ident, $submac:ident!( $($args:tt)* )) => { + wrap_sep!($i, $separator, $submac!($($args)*)) + }; + ($i:expr, $separator:ident, $f:expr) => { + wrap_sep!($i, $separator, call!($f)) + }; +); + +use std::ops::{Range,RangeFrom,RangeTo}; +use internal::IResult; +#[allow(unused_imports)] +pub fn sp<'a,T>(input:T) -> IResult where + T: ::traits::Slice>+::traits::Slice>+::traits::Slice>, + T: ::traits::InputIter+::traits::InputLength, + ::Item: ::traits::AsChar { + eat_separator!(input, &b" \t\r\n"[..]) +} + +/// `ws!(I -> IResult) => I -> IResult` +/// +/// transforms a parser to automatically consume +/// whitespace between each token. By default, +/// it takes the following characters: " \t\r\n". +/// +/// If you need a whitespace parser consuming a +/// different set of characters, you can make +/// your own by reusing the `sep!` combinator. +/// +/// To use `ws!`, pass your parser as argument: +/// +/// ``` +/// # #[macro_use] extern crate nom; +/// # use nom::IResult::Done; +/// # fn main() { +/// named!(tuple<&[u8], (&[u8], &[u8]) >, +/// ws!(tuple!( take!(3), tag!("de") )) +/// ); +/// +/// assert_eq!( +/// tuple(&b" \t abc de fg"[..]), +/// Done(&b"fg"[..], (&b"abc"[..], &b"de"[..])) +/// ); +/// # } +/// ``` +/// +#[macro_export] +macro_rules! ws ( + ($i:expr, $($args:tt)*) => ( + { + use $crate::sp; + sep!($i, sp, $($args)*) + } + ) +); + +#[cfg(test)] +#[allow(dead_code)] +mod tests { + use internal::IResult::*; + use internal::{IResult,Needed}; + use super::sp; + use util::ErrorKind; + + #[test] + fn spaaaaace() { + assert_eq!(sp(&b" \t abc "[..]), Done(&b"abc "[..], &b" \t "[..])); + } + + #[test] + fn tag() { + named!(abc, ws!(tag!("abc"))); + + assert_eq!(abc(&b" \t abc def"[..]), Done(&b"def"[..], &b"abc"[..])); + } + + #[test] + fn pair() { + named!(pair_2<&[u8], (&[u8], &[u8]) >, + ws!(pair!( take!(3), tag!("de") )) + ); + + assert_eq!(pair_2(&b" \t abc de fg"[..]), Done(&b"fg"[..], (&b"abc"[..], &b"de"[..]))); + } + + #[test] + fn preceded() { + named!(prec<&[u8], &[u8] >, + ws!(preceded!( take!(3), tag!("de") )) + ); + + assert_eq!(prec(&b" \t abc de fg"[..]), Done(&b"fg"[..], &b"de"[..])); + } + + #[test] + fn terminated() { + named!(term<&[u8], &[u8] >, + ws!(terminated!( take!(3), tag!("de") )) + ); + + assert_eq!(term(&b" \t abc de fg"[..]), Done(&b"fg"[..], &b"abc"[..])); + } + + #[test] + fn tuple() { + //trace_macros!(true); + named!(tuple_2<&[u8], (&[u8], &[u8]) >, + ws!(tuple!( take!(3), tag!("de") )) + ); + //trace_macros!(false); + + assert_eq!(tuple_2(&b" \t abc de fg"[..]), Done(&b"fg"[..], (&b"abc"[..], &b"de"[..]))); + } + + #[test] + fn levels() { + //trace_macros!(true); + named!(level_2<&[u8], (&[u8], (&[u8], &[u8])) >, + ws!(pair!(take!(3), tuple!( tag!("de"), tag!("fg ") ))) + ); + //trace_macros!(false); + + assert_eq!(level_2(&b" \t abc de fg \t hi "[..]), Done(&b"hi "[..], (&b"abc"[..], (&b"de"[..], &b"fg "[..])))); + } + + #[test] + fn do_parse() { + fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) }; + fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) }; + + //trace_macros!(true); + named!(do_parser<&[u8], (u8, u8)>, + ws!(do_parse!( + tag!("abcd") >> + opt!(tag!("abcd")) >> + aa: ret_int1 >> + tag!("efgh") >> + bb: ret_int2 >> + tag!("efgh") >> + (aa, bb) + )) + ); + + //trace_macros!(false); + + assert_eq!(do_parser(&b"abcd abcd\tefghefghX"[..]), Done(&b"X"[..], (1, 2))); + assert_eq!(do_parser(&b"abcd\tefgh efgh X"[..]), Done(&b"X"[..], (1, 2))); + assert_eq!(do_parser(&b"abcd ab"[..]), Incomplete(Needed::Size(10))); + assert_eq!(do_parser(&b" abcd\tefgh\tef"[..]), Incomplete(Needed::Size(15))); + } + + #[test] + fn permutation() { + //trace_macros!(true); + named!(perm<(&[u8], &[u8], &[u8])>, + ws!(permutation!(tag!("abcd"), tag!("efg"), tag!("hi"))) + ); + //trace_macros!(false); + + let expected = (&b"abcd"[..], &b"efg"[..], &b"hi"[..]); + + let a = &b"abcd\tefg \thijk"[..]; + assert_eq!(perm(a), Done(&b"jk"[..], expected)); + let b = &b" efg \tabcdhi jk"[..]; + assert_eq!(perm(b), Done(&b"jk"[..], expected)); + let c = &b" hi efg\tabcdjk"[..]; + assert_eq!(perm(c), Done(&b"jk"[..], expected)); + + let d = &b"efg xyzabcdefghi"[..]; + assert_eq!(perm(d), Error(error_position!(ErrorKind::Permutation, &b"xyzabcdefghi"[..]))); + + let e = &b" efg \tabc"[..]; + assert_eq!(perm(e), Incomplete(Needed::Size(10))); + } + + #[test] + fn alt() { + fn work(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> { + Done(&b""[..], input) + } + + #[allow(unused_variables)] + fn dont_work(input: &[u8]) -> IResult<&[u8],&[u8],&'static str> { + Error(error_code!(ErrorKind::Custom("abcd"))) + } + + fn work2(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> { + Done(input, &b""[..]) + } + + fn alt1(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> { + alt!(i, dont_work | dont_work) + } + fn alt2(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> { + alt!(i, dont_work | work) + } + fn alt3(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> { + alt!(i, dont_work | dont_work | work2 | dont_work) + } + + let a = &b"\tabcd"[..]; + assert_eq!(alt1(a), Error(error_position!(ErrorKind::Alt, a))); + assert_eq!(alt2(a), Done(&b""[..], a)); + assert_eq!(alt3(a), Done(a, &b""[..])); + + named!(alt4, ws!(alt!(tag!("abcd") | tag!("efgh")))); + let b = &b" efgh "[..]; + assert_eq!(alt4(a), Done(&b""[..], &b"abcd"[..])); + assert_eq!(alt4(b), Done(&b""[..], &b"efgh"[..])); + + // test the alternative syntax + named!(alt5, ws!(alt!(tag!("abcd") => { |_| false } | tag!("efgh") => { |_| true }))); + assert_eq!(alt5(a), Done(&b""[..], false)); + assert_eq!(alt5(b), Done(&b""[..], true)); + } + + #[test] + fn alt_complete() { + named!(ac<&[u8], &[u8]>, + ws!(alt_complete!(tag!("abcd") | tag!("ef") | tag!("ghi") | tag!("kl"))) + ); + + let a = &b""[..]; + assert_eq!(ac(a), Incomplete(Needed::Size(2))); + let a = &b" \tef "[..]; + assert_eq!(ac(a), Done(&b""[..], &b"ef"[..])); + let a = &b" cde"[..]; + assert_eq!(ac(a), Error(error_position!(ErrorKind::Alt, &a[1..]))); + } + + #[allow(unused_variables)] + #[test] + fn switch() { + named!(sw, + ws!(switch!(take!(4), + b"abcd" => take!(2) | + b"efgh" => take!(4) + )) + ); + + let a = &b" abcd ef gh"[..]; + assert_eq!(sw(a), Done(&b"gh"[..], &b"ef"[..])); + + let b = &b"\tefgh ijkl "[..]; + assert_eq!(sw(b), Done(&b""[..], &b"ijkl"[..])); + let c = &b"afghijkl"[..]; + assert_eq!(sw(c), Error(error_position!(ErrorKind::Switch, &b"afghijkl"[..]))); + } + + named!(str_parse(&str) -> &str, ws!(tag!("test"))); + #[allow(unused_variables)] + #[test] + fn str_test() { + assert_eq!(str_parse(" \n test\t a\nb"), Done("a\nb", "test")); + } + + // test whitespace parser generation for alt + named!(space, tag!(" ")); + named!(pipeline_statement<&[u8], ()>, + ws!( + do_parse!( + tag!("pipeline") >> + attributes: delimited!(char!('{'), + separated_list!(char!(','), alt!( + space | + space + )), + char!('}')) >> + + ( () ) + ) + ) + ); + +} diff --git a/bash-5.1/vendor/nom/tests/arithmetic.rs b/bash-5.1/vendor/nom/tests/arithmetic.rs new file mode 100644 index 0000000..40ffc8c --- /dev/null +++ b/bash-5.1/vendor/nom/tests/arithmetic.rs @@ -0,0 +1,87 @@ +#[macro_use] +extern crate nom; + +use nom::{IResult,digit}; + +// Parser definition + +use std::str; +use std::str::FromStr; + +// We parse any expr surrounded by parens, ignoring all whitespaces around those +named!(parens, ws!(delimited!( tag!("("), expr, tag!(")") )) ); + +// We transform an integer string into a i64, ignoring surrounding whitespaces +// We look for a digit suite, and try to convert it. +// If either str::from_utf8 or FromStr::from_str fail, +// we fallback to the parens parser defined above +named!(factor, alt!( + map_res!( + map_res!( + ws!(digit), + str::from_utf8 + ), + FromStr::from_str + ) + | parens + ) +); + +// We read an initial factor and for each time we find +// a * or / operator followed by another factor, we do +// the math by folding everything +named!(term , do_parse!( + init: factor >> + res: fold_many0!( + pair!(alt!(tag!("*") | tag!("/")), factor), + init, + |acc, (op, val): (&[u8], i64)| { + if (op[0] as char) == '*' { acc * val } else { acc / val } + } + ) >> + (res) + ) +); + +named!(expr , do_parse!( + init: term >> + res: fold_many0!( + pair!(alt!(tag!("+") | tag!("-")), term), + init, + |acc, (op, val): (&[u8], i64)| { + if (op[0] as char) == '+' { acc + val } else { acc - val } + } + ) >> + (res) + ) +); + +#[test] +fn factor_test() { + assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3)); + assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12)); + assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537)); + assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24)); +} + + +#[test] +fn term_test() { + assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8)); + assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8)); + assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8)); +} + +#[test] +fn expr_test() { + assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3)); + assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17)); + assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11)); +} + +#[test] +fn parens_test() { + assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2)); + assert_eq!(expr(&b" 2* ( 3 + 4 ) "[..]), IResult::Done(&b""[..], 14)); + assert_eq!(expr(&b" 2*2 / ( 5 - 1) + 3"[..]), IResult::Done(&b""[..], 4)); +} diff --git a/bash-5.1/vendor/nom/tests/arithmetic_ast.rs b/bash-5.1/vendor/nom/tests/arithmetic_ast.rs new file mode 100644 index 0000000..d48b902 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/arithmetic_ast.rs @@ -0,0 +1,137 @@ +#[macro_use] +extern crate nom; + +use std::fmt; +use std::fmt::{Display, Debug, Formatter}; + +use std::str; +use std::str::FromStr; + +use nom::{IResult, digit, multispace}; + +pub enum Expr { + Value(i64), + Add(Box, Box), + Sub(Box, Box), + Mul(Box, Box), + Div(Box, Box), + Paren(Box), +} + +pub enum Oper { + Add, + Sub, + Mul, + Div, +} + +impl Display for Expr { + fn fmt(&self, format: &mut Formatter) -> fmt::Result { + use self::Expr::*; + match *self { + Value(val) => write!(format, "{}", val), + Add(ref left, ref right) => write!(format, "{} + {}", left, right), + Sub(ref left, ref right) => write!(format, "{} - {}", left, right), + Mul(ref left, ref right) => write!(format, "{} * {}", left, right), + Div(ref left, ref right) => write!(format, "{} / {}", left, right), + Paren(ref expr) => write!(format, "({})", expr), + } + } +} + +impl Debug for Expr { + fn fmt(&self, format: &mut Formatter) -> fmt::Result { + use self::Expr::*; + match *self { + Value(val) => write!(format, "{}", val), + Add(ref left, ref right) => write!(format, "({:?} + {:?})", left, right), + Sub(ref left, ref right) => write!(format, "({:?} - {:?})", left, right), + Mul(ref left, ref right) => write!(format, "({:?} * {:?})", left, right), + Div(ref left, ref right) => write!(format, "({:?} / {:?})", left, right), + Paren(ref expr) => write!(format, "[{:?}]", expr), + } + } +} + +named!(parens< Expr >, delimited!( + delimited!(opt!(multispace), tag!("("), opt!(multispace)), + map!(map!(expr, Box::new), Expr::Paren), + delimited!(opt!(multispace), tag!(")"), opt!(multispace)) + ) +); + +named!(factor< Expr >, alt_complete!( + map!( + map_res!( + map_res!( + delimited!(opt!(multispace), digit, opt!(multispace)), + str::from_utf8 + ), + FromStr::from_str + ), + Expr::Value) + | parens + ) +); + +fn fold_exprs(initial: Expr, remainder: Vec<(Oper, Expr)>) -> Expr { + remainder.into_iter().fold(initial, |acc, pair| { + let (oper, expr) = pair; + match oper { + Oper::Add => Expr::Add(Box::new(acc), Box::new(expr)), + Oper::Sub => Expr::Sub(Box::new(acc), Box::new(expr)), + Oper::Mul => Expr::Mul(Box::new(acc), Box::new(expr)), + Oper::Div => Expr::Div(Box::new(acc), Box::new(expr)), + } + }) +} + +named!(term< Expr >, do_parse!( + initial: factor >> + remainder: many0!( + alt!( + do_parse!(tag!("*") >> mul: factor >> (Oper::Mul, mul)) | + do_parse!(tag!("/") >> div: factor >> (Oper::Div, div)) + ) + ) >> + (fold_exprs(initial, remainder)) +)); + +named!(expr< Expr >, do_parse!( + initial: term >> + remainder: many0!( + alt!( + do_parse!(tag!("+") >> add: term >> (Oper::Add, add)) | + do_parse!(tag!("-") >> sub: term >> (Oper::Sub, sub)) + ) + ) >> + (fold_exprs(initial, remainder)) +)); + +#[test] +fn factor_test() { + assert_eq!(factor(&b" 3 "[..]).map(|x| format!("{:?}", x)), + IResult::Done(&b""[..], String::from("3"))); +} + +#[test] +fn term_test() { + assert_eq!(term(&b" 3 * 5 "[..]).map(|x| format!("{:?}", x)), + IResult::Done(&b""[..], String::from("(3 * 5)"))); +} + +#[test] +fn expr_test() { + assert_eq!(expr(&b" 1 + 2 * 3 "[..]).map(|x| format!("{:?}", x)), + IResult::Done(&b""[..], String::from("(1 + (2 * 3))"))); + assert_eq!(expr(&b" 1 + 2 * 3 / 4 - 5 "[..]).map(|x| format!("{:?}", x)), + IResult::Done(&b""[..], String::from("((1 + ((2 * 3) / 4)) - 5)"))); + assert_eq!(expr(&b" 72 / 2 / 3 "[..]).map(|x| format!("{:?}", x)), + IResult::Done(&b""[..], String::from("((72 / 2) / 3)"))); +} + +#[test] +fn parens_test() { + assert_eq!(expr(&b" ( 1 + 2 ) * 3 "[..]).map(|x| format!("{:?}", x)), + IResult::Done(&b""[..], String::from("([(1 + 2)] * 3)"))); +} diff --git a/bash-5.1/vendor/nom/tests/blockbuf-arithmetic.rs b/bash-5.1/vendor/nom/tests/blockbuf-arithmetic.rs new file mode 100644 index 0000000..fe65518 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/blockbuf-arithmetic.rs @@ -0,0 +1,321 @@ +/* +#[macro_use] +extern crate nom; +extern crate bytes; + +use nom::{Compare,CompareResult,InputLength,InputIter,Slice,HexDisplay}; + +use std::str; +use std::str::FromStr; +use bytes::{Buf,MutBuf}; +use bytes::buf::{BlockBuf,BlockBufCursor}; +use std::ops::{Range,RangeTo,RangeFrom,RangeFull}; +use std::iter::{Enumerate,Iterator}; +use std::fmt; +use std::cmp::{min,PartialEq}; + +#[derive(Clone,Copy)] +#[repr(C)] +pub struct BlockSlice<'a> { + buf: &'a BlockBuf, + start: usize, + end: usize, +} + +impl<'a> BlockSlice<'a> { + fn cursor(&self) -> WrapCursor<'a> { + let mut cur = self.buf.buf(); + cur.advance(self.start); + WrapCursor { + cursor: cur, + length: self.end - self.start, + } + } +} + +impl<'a> fmt::Debug for BlockSlice<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "BlockSlice {{ start: {}, end: {}, data:\n{}\n}}", self.start, self.end, self.buf.bytes().unwrap_or(&b""[..]).to_hex(16)) + } +} + +impl<'a> PartialEq for BlockSlice<'a> { + fn eq(&self, other: &BlockSlice<'a>) -> bool { + let bufs = (self.buf as *const BlockBuf) == (other.buf as *const BlockBuf); + self.start == other.start && self.end == other.end && bufs + } +} + +impl<'a> Slice> for BlockSlice<'a> { + fn slice(&self, range:Range) -> Self { + BlockSlice { + buf: self.buf, + start: self.start + range.start, + //FIXME: check for valid end here + end: self.start + range.end, + } + } +} + +impl<'a> Slice> for BlockSlice<'a> { + fn slice(&self, range:RangeTo) -> Self { + self.slice(0..range.end) + } +} + +impl<'a> Slice> for BlockSlice<'a> { + fn slice(&self, range:RangeFrom) -> Self { + self.slice(range.start..self.end - self.start) + } +} + +impl<'a> Slice for BlockSlice<'a> { + fn slice(&self, _:RangeFull) -> Self { + BlockSlice { + buf: self.buf, + start: self.start, + end: self.end, + } + } +} + + +impl<'a> InputIter for BlockSlice<'a> { + type Item = u8; + type RawItem = u8; + type Iter = Enumerate>; + type IterElem = WrapCursor<'a>; + + fn iter_indices(&self) -> Self::Iter { + self.cursor().enumerate() + } + fn iter_elements(&self) -> Self::IterElem { + self.cursor() + } + fn position

(&self, predicate: P) -> Option where P: Fn(Self::RawItem) -> bool { + self.cursor().position(|b| predicate(b)) + } + fn slice_index(&self, count:usize) -> Option { + if self.end - self.start >= count { + Some(count) + } else { + None + } + } +} + + +impl<'a> InputLength for BlockSlice<'a> { + fn input_len(&self) -> usize { + self.end - self.start + } +} + +impl<'a,'b> Compare<&'b[u8]> for BlockSlice<'a> { + fn compare(&self, t: &'b[u8]) -> CompareResult { + let len = self.end - self.start; + let blen = t.len(); + let m = if len < blen { len } else { blen }; + let reduced = self.slice(..m); + let b = &t[..m]; + + for (a,b) in reduced.cursor().zip(b.iter()) { + if a != *b { + return CompareResult::Error; + } + } + if m < blen { + CompareResult::Incomplete + } else { + CompareResult::Ok + } + } + + + #[inline(always)] + fn compare_no_case(&self, t: &'b[u8]) -> CompareResult { + let len = self.end - self.start; + let blen = t.len(); + let m = if len < blen { len } else { blen }; + let reduced = self.slice(..m); + let other = &t[..m]; + + if !reduced.cursor().zip(other).all(|(a, b)| { + match (a,*b) { + (0...64, 0...64) | (91...96, 91...96) | (123...255, 123...255) => a == *b, + (65...90, 65...90) | (97...122, 97...122) | (65...90, 97...122 ) |(97...122, 65...90) => { + a & 0b01000000 == *b & 0b01000000 + } + _ => false + } + }) { + CompareResult::Error + } else if m < blen { + CompareResult::Incomplete + } else { + CompareResult::Ok + } + } +} + +impl<'a,'b> Compare<&'b str> for BlockSlice<'a> { + fn compare(&self, t: &'b str) -> CompareResult { + self.compare(str::as_bytes(t)) + } + fn compare_no_case(&self, t: &'b str) -> CompareResult { + self.compare_no_case(str::as_bytes(t)) + } +} + +//Wrapper to implement Iterator on BlockBufCursor +pub struct WrapCursor<'a> { + pub cursor: BlockBufCursor<'a>, + pub length: usize, +} + +impl<'a> Iterator for WrapCursor<'a> { + type Item = u8; + fn next(&mut self) -> Option { + //println!("NEXT: length={}, remaining={}", self.length, self.cursor.remaining()); + if min(self.length, self.cursor.remaining()) > 0 { + self.length -=1; + Some(self.cursor.read_u8()) + } else { + None + } + } +} + +//Reimplement eat_separator instead of fixing iterators +#[macro_export] +macro_rules! block_eat_separator ( + ($i:expr, $arr:expr) => ( + { + use nom::{InputLength,InputIter,Slice}; + if ($i).input_len() == 0 { + nom::IResult::Done($i, ($i).slice(0..0)) + } else { + match ($i).iter_indices().position(|(_, item)| { + for (_,c) in ($arr).iter_indices() { + if *c == item { return false; } + } + true + }) { + Some(index) => { + nom::IResult::Done(($i).slice(index..), ($i).slice(..index)) + }, + None => { + nom::IResult::Done(($i).slice(($i).input_len()..), $i) + } + } + } + } + ) +); + +#[macro_export] +macro_rules! block_named ( + ($name:ident, $submac:ident!( $($args:tt)* )) => ( + fn $name<'a>( i: BlockSlice<'a> ) -> nom::IResult, BlockSlice<'a>, u32> { + $submac!(i, $($args)*) + } + ); + ($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + fn $name<'a>( i: BlockSlice<'a> ) -> nom::IResult, $o, u32> { + $submac!(i, $($args)*) + } + ); +); + +block_named!(sp, block_eat_separator!(&b" \t\r\n"[..])); + +macro_rules! block_ws ( + ($i:expr, $($args:tt)*) => ( + { + sep!($i, sp, $($args)*) + } + ) +); + +block_named!(digit, is_a!("0123456789")); + +block_named!(parens, block_ws!(delimited!( tag!("("), expr, tag!(")") )) ); + + +block_named!(factor, alt!( + map_res!( + block_ws!(digit), + to_i64 + ) + | parens + ) +); + +block_named!(term , do_parse!( + init: factor >> + res: fold_many0!( + pair!(alt!(tag!("*") | tag!("/")), factor), + init, + |acc, (op, val): (BlockSlice, i64)| { + if (op.cursor().next().unwrap() as char) == '*' { acc * val } else { acc / val } + } + ) >> + (res) + ) +); + +block_named!(expr , do_parse!( + init: term >> + res: fold_many0!( + pair!(alt!(tag!("+") | tag!("-")), term), + init, + |acc, (op, val): (BlockSlice, i64)| { + if (op.cursor().next().unwrap() as char) == '+' { acc + val } else { acc - val } + } + ) >> + (res) + ) +); + + +fn blockbuf_from(input: &[u8]) -> BlockBuf { + let mut b = BlockBuf::new(2, 100); + b.copy_from(input); + b +} + + +fn sl<'a>(input: &'a BlockBuf) -> BlockSlice<'a> { + BlockSlice { + buf: input, + start: 0, + end: input.len(), + } +} + +fn to_i64<'a>(input: BlockSlice<'a>) -> Result { + let v: Vec = input.cursor().collect(); + + match str::from_utf8(&v) { + Err(_) => Err(()), + Ok(s) => match FromStr::from_str(s) { + Err(_) => Err(()), + Ok(i) => Ok(i) + } + } +} + +#[test] +fn factor_test() { + let a = blockbuf_from(&b"3"[..]); + println!("calculated: {:?}", factor(sl(&a))); +} + +#[test] +fn parens_test() { + let input1 = blockbuf_from(&b" 2* ( 3 + 4 ) "[..]); + println!("calculated 1: {:?}", expr(sl(&input1))); + let input2 = blockbuf_from(&b" 2*2 / ( 5 - 1) + 3"[..]); + println!("calculated 2: {:?}", expr(sl(&input2))); +} +*/ diff --git a/bash-5.1/vendor/nom/tests/cross_function_backtracking.rs b/bash-5.1/vendor/nom/tests/cross_function_backtracking.rs new file mode 100644 index 0000000..3163037 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/cross_function_backtracking.rs @@ -0,0 +1,147 @@ +/// this file tests a different backtracking behaviour. With the current +/// `error!` macro, an early return is done in the current function, but +/// backtracking continues normally outside of that function. +/// +/// The solution here wraps `IResult` in a `Result`: a `Ok` indicates usual +/// backtracking, `Err` indicates that we must "cut". + +#[allow(unused_imports)] +#[macro_use] extern crate nom; + +#[cfg(feature = "verbose_errors")] +macro_rules! n ( + ($name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => ( + fn $name( i: $i ) -> std::result::Result, nom::Err<$i, u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + ($name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => ( + fn $name( i: $i ) -> std::result::Result, nom::Err<$i, $e>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + ($name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => ( + fn $name( i: $i ) -> std::result::Result, nom::Err<$i, u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + ($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + fn $name<'a>( i: &'a[u8] ) -> std::result::Result, nom::Err<&'a [u8], u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + ($name:ident, $submac:ident!( $($args:tt)* )) => ( + fn $name( i: &[u8] ) -> std::result::Result, nom::Err<&[u8], u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + (pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => ( + pub fn $name( i: $i ) -> std::result::Result, nom::Err<$i, u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + (pub $name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => ( + pub fn $name( i: $i ) -> std::result::Result, nom::Err<$i, $e>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + (pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => ( + pub fn $name( i: $i ) -> std::result::Result, nom::Err<$i, u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + (pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => ( + pub fn $name( i: &[u8] ) -> std::result::Result, nom::Err<&[u8], u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); + (pub $name:ident, $submac:ident!( $($args:tt)* )) => ( + pub fn $name<'a>( i: &'a [u8] ) -> std::result::Result, nom::Err<&[u8], u32>> { + std::result::Result::Ok($submac!(i, $($args)*)) + } + ); +); + +#[cfg(feature = "verbose_errors")] +macro_rules! cut ( + ($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => ( + { + let cl = || { + Ok($submac!($i, $($args)*)) + }; + + match cl() { + std::result::Result::Ok(nom::IResult::Incomplete(x)) => nom::IResult::Incomplete(x), + std::result::Result::Ok(nom::IResult::Done(i, o)) => nom::IResult::Done(i, o), + std::result::Result::Ok(nom::IResult::Error(e)) | std::result::Result::Err(e) => { + return std::result::Result::Err(nom::Err::NodePosition($code, $i, Box::new(e))) + } + } + } + ); + ($i:expr, $code:expr, $f:expr) => ( + cut!($i, $code, call!($f)); + ); +); + +#[cfg(feature = "verbose_errors")] +macro_rules! c ( + ($i:expr, $f:expr) => ( + { + match $f($i) { + std::result::Result::Ok(nom::IResult::Incomplete(x)) => nom::IResult::Incomplete(x), + std::result::Result::Ok(nom::IResult::Done(i, o)) => nom::IResult::Done(i, o), + std::result::Result::Ok(nom::IResult::Error(e)) => nom::IResult::Error(e), + std::result::Result::Err(e) => { + return std::result::Result::Err(e) + } + } + } + ); +); + +#[cfg(feature = "verbose_errors")] +n!(pub foo< bool >, + do_parse!( + tag!("a") >> + cut!(nom::ErrorKind::Custom(42),dbg_dmp!(tag!("b"))) >> + (true) + ) +); + +#[cfg(feature = "verbose_errors")] +n!(pub foos< Vec >, + delimited!( + tag!("("), + many0!(c!(foo)), + tag!(")") + ) +); + +#[cfg(feature = "verbose_errors")] +#[test] +fn test_ok() { + let r = foos(b"(abab)"); + println!("result: {:?}", r); + match r { + Ok(nom::IResult::Done(_,result)) => assert_eq!(result,vec![true,true]), + res => panic!("Oops {:?}.",res) + } +} + +#[cfg(feature = "verbose_errors")] +#[test] +fn test_err() { + let input = b"(ac)"; + let r = foos(&input[..]); + println!("result: {:?}", r); + match r { + //Ok(nom::IResult::Error(nom::Err::Position(kind,_))) => assert_eq!(kind,nom::ErrorKind::Custom(42)), + Err(nom::Err::NodePosition(kind, position, _)) => { + assert_eq!(kind, nom::ErrorKind::Custom(42)); + assert_eq!(position, &input[2..]); + } + res => panic!("Oops, {:?}",res) + } +} + diff --git a/bash-5.1/vendor/nom/tests/float.rs b/bash-5.1/vendor/nom/tests/float.rs new file mode 100644 index 0000000..5710e26 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/float.rs @@ -0,0 +1,46 @@ +#[macro_use] +extern crate nom; + +use nom::{IResult,digit}; + +use std::str; +use std::str::FromStr; + +named!(unsigned_float , map_res!( + map_res!( + recognize!( + alt!( + delimited!(digit, tag!("."), opt!(complete!(digit))) | + delimited!(opt!(digit), tag!("."), digit) + ) + ), + str::from_utf8 + ), + FromStr::from_str +)); + +named!(float , map!( + pair!( + opt!(alt!(tag!("+") | tag!("-"))), + unsigned_float + ), + |(sign, value): (Option<&[u8]>, f32)| { + sign.and_then(|s| if s[0] == ('-' as u8) { Some(-1f32) } else { None }).unwrap_or(1f32) * value + } +)); + +#[test] +fn unsigned_float_test() { + assert_eq!(unsigned_float(&b"123.456"[..]), IResult::Done(&b""[..], 123.456)); + assert_eq!(unsigned_float(&b"0.123"[..]), IResult::Done(&b""[..], 0.123)); + assert_eq!(unsigned_float(&b"123.0"[..]), IResult::Done(&b""[..], 123.0)); + assert_eq!(unsigned_float(&b"123."[..]), IResult::Done(&b""[..], 123.0)); + assert_eq!(unsigned_float(&b".123"[..]), IResult::Done(&b""[..], 0.123)); +} + +#[test] +fn float_test() { + assert_eq!(float(&b"123.456"[..]), IResult::Done(&b""[..], 123.456)); + assert_eq!(float(&b"+123.456"[..]), IResult::Done(&b""[..], 123.456)); + assert_eq!(float(&b"-123.456"[..]), IResult::Done(&b""[..], -123.456)); +} diff --git a/bash-5.1/vendor/nom/tests/ini.rs b/bash-5.1/vendor/nom/tests/ini.rs new file mode 100644 index 0000000..c721770 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/ini.rs @@ -0,0 +1,219 @@ +#[macro_use] +extern crate nom; + +use nom::{IResult, space, alphanumeric, multispace}; + +use std::str; +use std::collections::HashMap; + +named!(category<&str>, map_res!( + delimited!( + char!('['), + take_while!(call!(|c| c != ']' as u8)), + char!(']') + ), + str::from_utf8 +)); + +named!(key_value <&[u8],(&str,&str)>, + do_parse!( + key: map_res!(alphanumeric, str::from_utf8) + >> opt!(space) + >> char!('=') + >> opt!(space) + >> val: map_res!( + take_while!(call!(|c| c != '\n' as u8 && c != ';' as u8)), + str::from_utf8 + ) + >> opt!(pair!(char!(';'), take_while!(call!(|c| c != '\n' as u8)))) + >> (key, val) + ) +); + + +named!(keys_and_values<&[u8], HashMap<&str, &str> >, + map!( + many0!(terminated!(key_value, opt!(multispace))), + |vec: Vec<_>| vec.into_iter().collect() + ) +); + + +named!(category_and_keys<&[u8],(&str,HashMap<&str,&str>)>, + do_parse!( + category: category >> + opt!(multispace) >> + keys: keys_and_values >> + (category, keys) + ) +); + +named!(categories<&[u8], HashMap<&str, HashMap<&str,&str> > >, + map!( + many0!( + separated_pair!( + category, + opt!(multispace), + map!( + many0!(terminated!(key_value, opt!(multispace))), + |vec: Vec<_>| vec.into_iter().collect() + ) + ) + ), + |vec: Vec<_>| vec.into_iter().collect() + ) +); + +#[test] +fn parse_category_test() { + let ini_file = &b"[category] + +parameter=value +key = value2"[..]; + + let ini_without_category = &b"\n\nparameter=value +key = value2"[..]; + + let res = category(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, o) => println!("i: {:?} | o: {:?}", str::from_utf8(i), o), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_category, "category")); +} + +#[test] +fn parse_key_value_test() { + let ini_file = &b"parameter=value +key = value2"[..]; + + let ini_without_key_value = &b"\nkey = value2"[..]; + + let res = key_value(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, (o1, o2)) => println!("i: {:?} | o: ({:?},{:?})", str::from_utf8(i), o1, o2), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_key_value, ("parameter", "value"))); +} + + +#[test] +fn parse_key_value_with_space_test() { + let ini_file = &b"parameter = value +key = value2"[..]; + + let ini_without_key_value = &b"\nkey = value2"[..]; + + let res = key_value(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, (o1, o2)) => println!("i: {:?} | o: ({:?},{:?})", str::from_utf8(i), o1, o2), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_key_value, ("parameter", "value"))); +} + +#[test] +fn parse_key_value_with_comment_test() { + let ini_file = &b"parameter=value;abc +key = value2"[..]; + + let ini_without_key_value = &b"\nkey = value2"[..]; + + let res = key_value(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, (o1, o2)) => println!("i: {:?} | o: ({:?},{:?})", str::from_utf8(i), o1, o2), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_key_value, ("parameter", "value"))); +} + +#[test] +fn parse_multiple_keys_and_values_test() { + let ini_file = &b"parameter=value;abc + +key = value2 + +[category]"[..]; + + let ini_without_key_value = &b"[category]"[..]; + + let res = keys_and_values(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, ref o) => println!("i: {:?} | o: {:?}", str::from_utf8(i), o), + _ => println!("error") + } + + let mut expected: HashMap<&str, &str> = HashMap::new(); + expected.insert("parameter", "value"); + expected.insert("key", "value2"); + assert_eq!(res, IResult::Done(ini_without_key_value, expected)); +} + +#[test] +fn parse_category_then_multiple_keys_and_values_test() { + //FIXME: there can be an empty line or a comment line after a category + let ini_file = &b"[abcd] +parameter=value;abc + +key = value2 + +[category]"[..]; + + let ini_after_parser = &b"[category]"[..]; + + let res = category_and_keys(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, ref o) => println!("i: {:?} | o: {:?}", str::from_utf8(i), o), + _ => println!("error") + } + + let mut expected_h: HashMap<&str, &str> = HashMap::new(); + expected_h.insert("parameter", "value"); + expected_h.insert("key", "value2"); + assert_eq!(res, IResult::Done(ini_after_parser, ("abcd", expected_h))); +} + +#[test] +fn parse_multiple_categories_test() { + let ini_file = &b"[abcd] + +parameter=value;abc + +key = value2 + +[category] +parameter3=value3 +key4 = value4 +"[..]; + + let ini_after_parser = &b""[..]; + + let res = categories(ini_file); + //println!("{:?}", res); + match res { + IResult::Done(i, ref o) => println!("i: {:?} | o: {:?}", str::from_utf8(i), o), + _ => println!("error") + } + + let mut expected_1: HashMap<&str, &str> = HashMap::new(); + expected_1.insert("parameter", "value"); + expected_1.insert("key", "value2"); + let mut expected_2: HashMap<&str, &str> = HashMap::new(); + expected_2.insert("parameter3", "value3"); + expected_2.insert("key4", "value4"); + let mut expected_h: HashMap<&str, HashMap<&str, &str>> = HashMap::new(); + expected_h.insert("abcd", expected_1); + expected_h.insert("category", expected_2); + assert_eq!(res, IResult::Done(ini_after_parser, expected_h)); +} diff --git a/bash-5.1/vendor/nom/tests/ini_str.rs b/bash-5.1/vendor/nom/tests/ini_str.rs new file mode 100644 index 0000000..330e490 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/ini_str.rs @@ -0,0 +1,240 @@ +#[macro_use] +extern crate nom; + +use nom::IResult; + +use std::collections::HashMap; + +fn is_alphabetic(chr:char) -> bool { + (chr as u8 >= 0x41 && chr as u8 <= 0x5A) || (chr as u8 >= 0x61 && chr as u8 <= 0x7A) +} + +fn is_digit(chr: char) -> bool { + chr as u8 >= 0x30 && chr as u8 <= 0x39 +} + +fn is_alphanumeric(chr: char) -> bool { + is_alphabetic(chr) || is_digit(chr) +} + +fn is_space(chr:char) -> bool { + chr == ' ' || chr == '\t' +} + +fn is_line_ending_or_comment(chr:char) -> bool { + chr == ';' || chr == '\n' +} + +named!(alphanumeric<&str,&str>, take_while_s!(is_alphanumeric)); +named!(not_line_ending<&str,&str>, is_not_s!("\r\n")); +named!(space<&str,&str>, take_while_s!(is_space)); +named!(space_or_line_ending<&str,&str>, is_a_s!(" \r\n")); + +fn right_bracket(c:char) -> bool { + c == ']' +} + +named!(category <&str, &str>, + do_parse!( + tag_s!("[") >> + name: take_till_s!(right_bracket) >> + tag_s!("]") >> + opt!(space_or_line_ending) >> + (name) + ) +); + +named!(key_value <&str,(&str,&str)>, + do_parse!( + key: alphanumeric >> + opt!(space) >> + tag_s!("=") >> + opt!(space) >> + val: take_till_s!(is_line_ending_or_comment) >> + opt!(space) >> + opt!(pair!(tag_s!(";"), not_line_ending)) >> + opt!(space_or_line_ending) >> + (key, val) + ) +); + +named!(keys_and_values_aggregator<&str, Vec<(&str,&str)> >, many0!(key_value)); + +fn keys_and_values(input:&str) -> IResult<&str, HashMap<&str, &str> > { + match keys_and_values_aggregator(input) { + IResult::Done(i,tuple_vec) => { + IResult::Done(i, tuple_vec.into_iter().collect()) + }, + IResult::Incomplete(a) => IResult::Incomplete(a), + IResult::Error(a) => IResult::Error(a) + } +} + + +named!(category_and_keys<&str,(&str,HashMap<&str,&str>)>, + pair!(category, keys_and_values) +); + +named!(categories_aggregator<&str, Vec<(&str, HashMap<&str,&str>)> >, many0!(category_and_keys)); + +fn categories(input: &str) -> IResult<&str, HashMap<&str, HashMap<&str, &str> > > { + match categories_aggregator(input) { + IResult::Done(i,tuple_vec) => { + IResult::Done(i, tuple_vec.into_iter().collect()) + }, + IResult::Incomplete(a) => IResult::Incomplete(a), + IResult::Error(a) => IResult::Error(a) + } +} + + +#[test] +fn parse_category_test() { + let ini_file = "[category] + +parameter=value +key = value2"; + + let ini_without_category = "parameter=value +key = value2"; + + let res = category(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, o) => println!("i: {} | o: {:?}", i, o), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_category, "category")); +} + +#[test] +fn parse_key_value_test() { + let ini_file = "parameter=value +key = value2"; + + let ini_without_key_value = "key = value2"; + + let res = key_value(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, (o1, o2)) => println!("i: {} | o: ({:?},{:?})", i, o1, o2), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_key_value, ("parameter", "value"))); +} + +#[test] +fn parse_key_value_with_space_test() { + let ini_file = "parameter = value +key = value2"; + + let ini_without_key_value = "key = value2"; + + let res = key_value(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, (o1, o2)) => println!("i: {} | o: ({:?},{:?})", i, o1, o2), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_key_value, ("parameter", "value"))); +} + +#[test] +fn parse_key_value_with_comment_test() { + let ini_file = "parameter=value;abc +key = value2"; + + let ini_without_key_value = "key = value2"; + + let res = key_value(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, (o1, o2)) => println!("i: {} | o: ({:?},{:?})", i, o1, o2), + _ => println!("error") + } + + assert_eq!(res, IResult::Done(ini_without_key_value, ("parameter", "value"))); +} + +#[test] +fn parse_multiple_keys_and_values_test() { + let ini_file = "parameter=value;abc + +key = value2 + +[category]"; + + let ini_without_key_value = "[category]"; + + let res = keys_and_values(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, ref o) => println!("i: {} | o: {:?}", i, o), + _ => println!("error") + } + + let mut expected: HashMap<&str, &str> = HashMap::new(); + expected.insert("parameter", "value"); + expected.insert("key", "value2"); + assert_eq!(res, IResult::Done(ini_without_key_value, expected)); +} + +#[test] +fn parse_category_then_multiple_keys_and_values_test() { + //FIXME: there can be an empty line or a comment line after a category + let ini_file = "[abcd] +parameter=value;abc + +key = value2 + +[category]"; + + let ini_after_parser = "[category]"; + + let res = category_and_keys(ini_file); + println!("{:?}", res); + match res { + IResult::Done(i, ref o) => println!("i: {} | o: {:?}", i, o), + _ => println!("error") + } + + let mut expected_h: HashMap<&str, &str> = HashMap::new(); + expected_h.insert("parameter", "value"); + expected_h.insert("key", "value2"); + assert_eq!(res, IResult::Done(ini_after_parser, ("abcd", expected_h))); +} + +#[test] +fn parse_multiple_categories_test() { + let ini_file = "[abcd] + +parameter=value;abc + +key = value2 + +[category] +parameter3=value3 +key4 = value4 +"; + + let res = categories(ini_file); + //println!("{:?}", res); + match res { + IResult::Done(i, ref o) => println!("i: {} | o: {:?}", i, o), + _ => println!("error") + } + + let mut expected_1: HashMap<&str, &str> = HashMap::new(); + expected_1.insert("parameter", "value"); + expected_1.insert("key", "value2"); + let mut expected_2: HashMap<&str, &str> = HashMap::new(); + expected_2.insert("parameter3", "value3"); + expected_2.insert("key4", "value4"); + let mut expected_h: HashMap<&str, HashMap<&str, &str>> = HashMap::new(); + expected_h.insert("abcd", expected_1); + expected_h.insert("category", expected_2); + assert_eq!(res, IResult::Done("", expected_h)); +} diff --git a/bash-5.1/vendor/nom/tests/issues.rs b/bash-5.1/vendor/nom/tests/issues.rs new file mode 100644 index 0000000..7a726dc --- /dev/null +++ b/bash-5.1/vendor/nom/tests/issues.rs @@ -0,0 +1,157 @@ +//#![feature(trace_macros)] +#![allow(dead_code)] + +#[macro_use] +extern crate nom; + +use nom::{IResult,Needed,space,be_u16,le_u64}; + +#[allow(dead_code)] +struct Range { + start: char, + end: char +} + +pub fn take_char(input: &[u8]) -> IResult<&[u8], char> { + if input.len() > 0 { + IResult::Done(&input[1..], input[0] as char) + } else { + IResult::Incomplete(Needed::Size(1)) + } +} + +//trace_macros!(true); + +#[allow(dead_code)] +named!(range<&[u8], Range>, + alt!( + do_parse!( + start: take_char >> + tag!("-") >> + end: take_char >> + (Range { + start: start, + end: end, + }) + ) | + map!( + take_char, + |c| { + Range { + start: c, + end: c, + } + } + ) + ) +); + + +#[allow(dead_code)] +named!(literal<&[u8], Vec >, + map!( + many1!(take_char), + |cs| { + cs + } + ) +); + +#[test] +fn issue_58() { + range(&b"abcd"[..]); + literal(&b"abcd"[..]); +} + +//trace_macros!(false); + +#[cfg(feature = "std")] +mod parse_int { + use nom::HexDisplay; + use nom::{IResult,space,digit}; + use std::str; + + named!(parse_ints< Vec >, many0!(spaces_or_int)); + + fn spaces_or_int(input: &[u8]) -> IResult<&[u8], i32>{ + println!("{}", input.to_hex(8)); + do_parse!(input, + opt!(complete!(space)) >> + res: map!(complete!(digit), + |x| { + println!("x: {:?}", x); + let result = str::from_utf8(x).unwrap(); + println!("Result: {}", result); + println!("int is empty?: {}", x.is_empty()); + match result.parse(){ + Ok(i) => i, + Err(_) => panic!("UH OH! NOT A DIGIT!") + } + }) >> + (res) + ) + } + + #[test] + fn issue_142(){ + let subject = parse_ints(&b"12 34 5689"[..]); + let expected = IResult::Done(&b""[..], vec![12, 34, 5689]); + assert_eq!(subject, expected); + + let subject = parse_ints(&b"12 34 5689 "[..]); + let expected = IResult::Done(&b" "[..], vec![12, 34, 5689]); + assert_eq!(subject, expected) + } +} + +#[test] +fn usize_length_bytes_issue(){ + length_bytes!(b"012346", be_u16); +} + +/* + DOES NOT COMPILE +#[test] +fn issue_152() { + named!(take4, take!(4)); + named!(xyz, tag!("XYZ")); + named!(abc, tag!("abc")); + + + named!(sw, + switch!(take4, + b"abcd" => xyz | + b"efgh" => abc + ) + ); +} +*/ + +#[test] +fn take_till_issue() { + named!(nothing, + take_till!(call!(|_| true)) + ); + + assert_eq!(nothing(b""), IResult::Done(&b""[..], &b""[..])); + assert_eq!(nothing(b"abc"), IResult::Done(&b"abc"[..], &b""[..])); +} + +named!(issue_498< Vec<&[u8]> >, separated_nonempty_list!( opt!(space), tag!("abcd") )); + +named!(issue_308(&str) -> bool, + do_parse! ( + tag_s! ("foo") >> + b: alt_complete! ( + map! (tag_s! ("1"), |_: &str|->bool {true}) | + value! (false) + ) >> + (b) )); + + +fn issue_302(input: &[u8]) -> IResult<&[u8], Option> > { + do_parse!(input, + entries: cond!(true, count!(le_u64, 3)) >> + ( entries ) + ) +} diff --git a/bash-5.1/vendor/nom/tests/json.rs b/bash-5.1/vendor/nom/tests/json.rs new file mode 100644 index 0000000..b036916 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/json.rs @@ -0,0 +1,130 @@ +//#![feature(trace_macros)] + +#[macro_use] +extern crate nom; + +use nom::{digit, alphanumeric}; + +use std::str::{self,FromStr}; +use std::collections::HashMap; + +#[derive(Debug,PartialEq)] +pub enum JsonValue { + Str(String), + Num(f32), + Array(Vec), + Object(HashMap) +} + +// FIXME: since we already parsed a serie of digits and dots, +// we know it is correct UTF-8. no need to use from_utf8 to +// verify it is correct +// FIXME: use alt_complete (implement ws for alt_complete) +named!(unsigned_float , map_res!( + map_res!( + recognize!( + alt_complete!( + delimited!(digit, tag!("."), opt!(complete!(digit))) | + delimited!(opt!(digit), tag!("."), digit) | + digit + ) + ), + str::from_utf8 + ), + FromStr::from_str +)); +named!(float, map!( + pair!( + opt!(alt!(tag!("+") | tag!("-"))), + unsigned_float + ), + |(sign, value): (Option<&[u8]>, f32)| { + sign.and_then(|s| if s[0] == ('-' as u8) { Some(-1f32) } else { None }).unwrap_or(1f32) * value + } +)); + +//FIXME: verify how json strings are formatted +named!(string<&str>, + delimited!( + tag!("\""), + map_res!(escaped!(call!(alphanumeric), '\\', is_a!("\"n\\")), str::from_utf8), + tag!("\"") + ) +); + +named!(array < Vec >, + ws!( + delimited!( + tag!("["), + separated_list!(tag!(","), value), + tag!("]") + ) + ) +); + +named!(key_value<(&str,JsonValue)>, + ws!( + separated_pair!( + string, + tag!(":"), + value + ) + ) +); + +named!(hash< HashMap >, + ws!( + map!( + delimited!( + tag!("{"), + separated_list!(tag!(","), key_value), + tag!("}") + ), + |tuple_vec| { + let mut h: HashMap = HashMap::new(); + for (k, v) in tuple_vec { + h.insert(String::from(k), v); + } + h + } + ) + ) +); + +named!(value, + ws!( + alt!( + hash => { |h| JsonValue::Object(h) } | + array => { |v| JsonValue::Array(v) } | + string => { |s| JsonValue::Str(String::from(s)) } | + float => { |num| JsonValue::Num(num) } + ) + ) +); + + + +#[test] +fn hash_test() { + let test = &b" { \"a\"\t: 42, + \"b\": \"x\" + }"; + +//FIXME: top level value must be an object? + println!("{:?}", value(&test[..])); + //assert!(false); +} + +#[test] +fn parse_example_test() { + let test = &b" { \"a\"\t: 42, + \"b\": [ \"x\", \"y\", 12 ] , + \"c\": { \"hello\" : \"world\" + } + }"; + +//FIXME: top level value must be an object? + println!("{:?}", value(&test[..])); + //assert!(false); +} + diff --git a/bash-5.1/vendor/nom/tests/mp4.rs b/bash-5.1/vendor/nom/tests/mp4.rs new file mode 100644 index 0000000..e6d5c9f --- /dev/null +++ b/bash-5.1/vendor/nom/tests/mp4.rs @@ -0,0 +1,528 @@ +#![cfg(feature = "stream")] +#![allow(dead_code)] + +#[macro_use] +extern crate nom; + +use nom::{HexDisplay,Offset,Needed,IResult,be_u16,be_u32,be_u64,be_f32,ErrorKind}; +use nom::{Consumer,ConsumerState,Move,Input,Producer,FileProducer,FileProducerState}; +use nom::IResult::*; + +use std::str; +use std::io::SeekFrom; + +fn mp4_box(input:&[u8]) -> IResult<&[u8], &[u8]> { + match be_u32(input) { + Done(i, offset) => { + let sz: usize = offset as usize; + if i.len() >= sz - 4 { + Done(&i[(sz-4)..], &i[0..(sz-4)]) + } else { + Incomplete(Needed::Size(offset as usize + 4)) + } + } + Error(e) => Error(e), + Incomplete(e) => Incomplete(e) + } +} + +#[derive(PartialEq,Eq,Debug)] +struct FileType<'a> { + major_brand: &'a str, + major_brand_version: &'a [u8], + compatible_brands: Vec<&'a str> +} + +#[allow(non_snake_case)] +#[derive(Debug,Clone)] +pub struct Mvhd32 { + version_flags: u32, // actually: + // version: u8, + // flags: u24 // 3 bytes + created_date: u32, + modified_date: u32, + scale: u32, + duration: u32, + speed: f32, + volume: u16, // actually a 2 bytes decimal + /* 10 bytes reserved */ + scaleA: f32, + rotateB: f32, + angleU: f32, + rotateC: f32, + scaleD: f32, + angleV: f32, + positionX: f32, + positionY: f32, + scaleW: f32, + preview: u64, + poster: u32, + selection: u64, + current_time: u32, + track_id: u32 +} + +#[allow(non_snake_case)] +#[derive(Debug,Clone)] +pub struct Mvhd64 { + version_flags: u32, // actually: + // version: u8, + // flags: u24 // 3 bytes + created_date: u64, + modified_date: u64, + scale: u32, + duration: u64, + speed: f32, + volume: u16, // actually a 2 bytes decimal + /* 10 bytes reserved */ + scaleA: f32, + rotateB: f32, + angleU: f32, + rotateC: f32, + scaleD: f32, + angleV: f32, + positionX: f32, + positionY: f32, + scaleW: f32, + preview: u64, + poster: u32, + selection: u64, + current_time: u32, + track_id: u32 +} + +#[allow(non_snake_case)] +named!(mvhd32 <&[u8], MvhdBox>, + do_parse!( + version_flags: be_u32 >> + created_date: be_u32 >> + modified_date: be_u32 >> + scale: be_u32 >> + duration: be_u32 >> + speed: be_f32 >> + volume: be_u16 >> // actually a 2 bytes decimal + take!(10) >> + scale_a: be_f32 >> + rotate_b: be_f32 >> + angle_u: be_f32 >> + rotate_c: be_f32 >> + scale_d: be_f32 >> + angle_v: be_f32 >> + position_x: be_f32 >> + position_y: be_f32 >> + scale_w: be_f32 >> + preview: be_u64 >> + poster: be_u32 >> + selection: be_u64 >> + current_time: be_u32 >> + track_id: be_u32 >> + ( + MvhdBox::M32(Mvhd32 { + version_flags: version_flags, + created_date: created_date, + modified_date: modified_date, + scale: scale, + duration: duration, + speed: speed, + volume: volume, + scaleA: scale_a, + rotateB: rotate_b, + angleU: angle_u, + rotateC: rotate_c, + scaleD: scale_d, + angleV: angle_v, + positionX: position_x, + positionY: position_y, + scaleW: scale_w, + preview: preview, + poster: poster, + selection: selection, + current_time: current_time, + track_id: track_id + }) + )) +); + +#[allow(non_snake_case)] +named!(mvhd64 <&[u8], MvhdBox>, + do_parse!( + version_flags: be_u32 >> + created_date: be_u64 >> + modified_date: be_u64 >> + scale: be_u32 >> + duration: be_u64 >> + speed: be_f32 >> + volume: be_u16 >> // actually a 2 bytes decimal + take!(10) >> + scale_a: be_f32 >> + rotate_b: be_f32 >> + angle_u: be_f32 >> + rotate_c: be_f32 >> + scale_d: be_f32 >> + angle_v: be_f32 >> + position_x: be_f32 >> + position_y: be_f32 >> + scale_w: be_f32 >> + preview: be_u64 >> + poster: be_u32 >> + selection: be_u64 >> + current_time: be_u32 >> + track_id: be_u32 >> + ( + MvhdBox::M64(Mvhd64 { + version_flags: version_flags, + created_date: created_date, + modified_date: modified_date, + scale: scale, + duration: duration, + speed: speed, + volume: volume, + scaleA: scale_a, + rotateB: rotate_b, + angleU: angle_u, + rotateC: rotate_c, + scaleD: scale_d, + angleV: angle_v, + positionX: position_x, + positionY: position_y, + scaleW: scale_w, + preview: preview, + poster: poster, + selection: selection, + current_time: current_time, + track_id: track_id + }) + )) +); + +#[derive(Debug,Clone)] +pub enum MvhdBox { + M32(Mvhd32), + M64(Mvhd64) +} + +#[derive(Debug,Clone)] +pub enum MoovBox { + Mdra, + Dref, + Cmov, + Rmra, + Iods, + Mvhd(MvhdBox), + Clip, + Trak, + Udta +} + +#[derive(Debug)] +enum MP4BoxType { + Ftyp, + Moov, + Mdat, + Free, + Skip, + Wide, + Mdra, + Dref, + Cmov, + Rmra, + Iods, + Mvhd, + Clip, + Trak, + Udta, + Unknown +} + +#[derive(Debug)] +struct MP4BoxHeader { + length: u32, + tag: MP4BoxType +} + +named!(brand_name<&[u8],&str>, map_res!(take!(4), str::from_utf8)); + +named!(filetype_parser<&[u8], FileType>, + do_parse!( + m: brand_name >> + v: take!(4) >> + c: many0!(brand_name) >> + (FileType{ major_brand: m, major_brand_version:v, compatible_brands: c }) + ) +); + +fn mvhd_box(input:&[u8]) -> IResult<&[u8],MvhdBox> { + let res = if input.len() < 100 { + Incomplete(Needed::Size(100)) + } else if input.len() == 100 { + mvhd32(input) + } else if input.len() == 112 { + mvhd64(input) + } else { + Error(error_position!(ErrorKind::Custom(32),input)) + }; + println!("res: {:?}", res); + res +} + +fn unknown_box_type(input:&[u8]) -> IResult<&[u8], MP4BoxType> { + Done(input, MP4BoxType::Unknown) +} + +//named!(box_type<&[u8], MP4BoxType>, +fn box_type(input: &[u8]) -> IResult<&[u8], MP4BoxType, u32> { + alt!(input, + tag!("ftyp") => { |_| MP4BoxType::Ftyp } | + tag!("moov") => { |_| MP4BoxType::Moov } | + tag!("mdat") => { |_| MP4BoxType::Mdat } | + tag!("free") => { |_| MP4BoxType::Free } | + tag!("skip") => { |_| MP4BoxType::Skip } | + tag!("wide") => { |_| MP4BoxType::Wide } | + unknown_box_type + ) +} + +// warning, an alt combinator with 9 branches containing a tag combinator +// can make the compilation very slow. Use functions as sub parsers, +// or split into multiple alt! parsers if it gets slow +named!(moov_type<&[u8], MP4BoxType>, + alt!( + tag!("mdra") => { |_| MP4BoxType::Mdra } | + tag!("dref") => { |_| MP4BoxType::Dref } | + tag!("cmov") => { |_| MP4BoxType::Cmov } | + tag!("rmra") => { |_| MP4BoxType::Rmra } | + tag!("iods") => { |_| MP4BoxType::Iods } | + tag!("mvhd") => { |_| MP4BoxType::Mvhd } | + tag!("clip") => { |_| MP4BoxType::Clip } | + tag!("trak") => { |_| MP4BoxType::Trak } | + tag!("udta") => { |_| MP4BoxType::Udta } + ) +); + +named!(box_header<&[u8],MP4BoxHeader>, + do_parse!( + length: be_u32 >> + tag: box_type >> + (MP4BoxHeader{ length: length, tag: tag}) + ) +); + +named!(moov_header<&[u8],MP4BoxHeader>, + do_parse!( + length: be_u32 >> + tag: moov_type >> + (MP4BoxHeader{ length: length, tag: tag}) + ) +); + +#[derive(Debug,PartialEq,Eq)] +enum MP4State { + Main, + Moov, + Mvhd(usize) +} + +pub struct MP4Consumer { + state: MP4State, + moov_bytes: usize, + c_state: ConsumerState<(), (), Move> +} + +impl MP4Consumer { + fn new() -> MP4Consumer { + MP4Consumer { state: MP4State::Main, moov_bytes: 0, c_state: ConsumerState::Continue(Move::Consume(0)) } + } + + fn consume_main(&mut self, input: Input<&[u8]>) -> ConsumerState<(), (), Move> { + //println!("\nparsing box header:\n{}", input.to_hex(8)); + match input { + Input::Eof(None) => ConsumerState::Done(Move::Consume(0), ()), + Input::Empty => ConsumerState::Continue(Move::Consume(0)), + Input::Element(sl) | Input::Eof(Some(sl)) => { + match box_header(sl) { + Done(i, header) => { + match header.tag { + MP4BoxType::Ftyp => { + println!("-> FTYP"); + match filetype_parser(&i[0..(header.length as usize - 8)]) { + Done(rest, filetype_header) => { + println!("filetype header: {:?}", filetype_header); + //return ConsumerState::Await(header.length as usize, header.length as usize - 8); + return ConsumerState::Continue(Move::Consume(sl.offset(rest))); + } + Error(a) => { + println!("ftyp parsing error: {:?}", a); + assert!(false); + return ConsumerState::Error(()); + }, + Incomplete(n) => { + println!("ftyp incomplete -> await: {}", sl.len()); + return ConsumerState::Continue(Move::Await(n)); + //return ConsumerState::Await(0, input.len() + 100); + } + } + }, + MP4BoxType::Moov => { + println!("-> MOOV"); + self.state = MP4State::Moov; + self.moov_bytes = header.length as usize - 8; + return ConsumerState::Continue(Move::Consume(sl.offset(i))); + }, + MP4BoxType::Mdat => println!("-> MDAT"), + MP4BoxType::Free => println!("-> FREE"), + MP4BoxType::Skip => println!("-> SKIP"), + MP4BoxType::Wide => println!("-> WIDE"), + MP4BoxType::Unknown => { + println!("-> UNKNOWN"); + println!("bytes:\n{}", (sl).to_hex(8)); + //return ConsumerState::Continue(Move::Consume(sl.offset(i))); + }, + _ => { println!("invalid"); return ConsumerState::Error(())} + } + return ConsumerState::Continue(Move::Seek(SeekFrom::Current((header.length) as i64))) + }, + Error(a) => { + println!("mp4 parsing error: {:?}", a); + assert!(false); + return ConsumerState::Error(()); + }, + Incomplete(i) => { + // FIXME: incomplete should send the required size + println!("mp4 incomplete -> await: {}", sl.len()); + return ConsumerState::Continue(Move::Await(i)); + } + } + } + } + } + + fn consume_moov(&mut self, input: Input<&[u8]>) -> ConsumerState<(), (), Move> { + //println!("\nparsing moov box(remaining {} bytes):\n{}", self.moov_bytes, input.to_hex(8)); + match input { + Input::Eof(None) => return ConsumerState::Error(()), + Input::Empty => return ConsumerState::Continue(Move::Consume(0)), + Input::Element(sl) | Input::Eof(Some(sl)) => { + if self.moov_bytes == 0 { + //println!("finished parsing moov atom, continuing with main parser"); + self.state = MP4State::Main; + return ConsumerState::Continue(Move::Consume(0)); + } + match moov_header(sl) { + Done(i, header) => { + match header.tag { + MP4BoxType::Mvhd => { + println!("-> MVHD"); + self.state = MP4State::Mvhd(header.length as usize - 8); + // TODO: check for overflow here + self.moov_bytes = self.moov_bytes - (sl.len() - i.len()); + println!("remaining moov_bytes: {}", self.moov_bytes); + return ConsumerState::Continue(Move::Consume(sl.offset(i))); + }, + MP4BoxType::Wide => println!("-> WIDE"), + MP4BoxType::Mdra => println!("-> MDRA"), + MP4BoxType::Dref => println!("-> DREF"), + MP4BoxType::Cmov => println!("-> CMOV"), + MP4BoxType::Rmra => println!("-> RMRA"), + MP4BoxType::Iods => println!("-> IODS"), + MP4BoxType::Clip => println!("-> CLIP"), + MP4BoxType::Trak => println!("-> TRAK"), + MP4BoxType::Udta => println!("-> UDTA"), + MP4BoxType::Unknown => println!("-> MOOV UNKNOWN"), + _ => { println!("invalid header here: {:?}", header.tag); return ConsumerState::Error(());} + }; + // TODO: check for overflow here + self.moov_bytes = self.moov_bytes - header.length as usize; + println!("remaining moov_bytes: {}", self.moov_bytes); + return ConsumerState::Continue(Move::Seek(SeekFrom::Current((header.length) as i64))) + }, + Error(a) => { + println!("moov parsing error: {:?}", a); + println!("data:\n{}", sl.to_hex(8)); + assert!(false); + return ConsumerState::Error(()); + }, + Incomplete(i) => { + println!("moov incomplete -> await: {}", sl.len()); + return ConsumerState::Continue(Move::Await(i)); + } + } + } + }; + } + +} + +consumer_from_parser!(MvhdConsumer, mvhd_box); + +impl<'a> Consumer<&'a[u8], (), (), Move> for MP4Consumer { + fn handle(&mut self, input: Input<&[u8]>) -> &ConsumerState<(), (), Move> { + match self.state { + MP4State::Main => { + self.c_state = self.consume_main(input); + }, + MP4State::Moov => { + self.c_state = self.consume_moov(input); + }, + MP4State::Mvhd(sz) => { + match input { + Input::Eof(None) => self.c_state = ConsumerState::Error(()), + Input::Empty => self.c_state = ConsumerState::Continue(Move::Consume(0)), + Input::Element(sl) | Input::Eof(Some(sl)) => { + let mut c = MvhdConsumer{ state:ConsumerState::Continue(Move::Consume(0)) }; + self.c_state = c.handle(Input::Element(&sl[..sz])).flat_map(|m, _| { + self.state = MP4State::Moov; + ConsumerState::Continue(m) + }); + println!("found mvhd?: {:?}", c.state()); + match self.c_state { + ConsumerState::Continue(Move::Consume(sz)) => self.moov_bytes = self.moov_bytes - sz, + ConsumerState::Continue(Move::Seek(SeekFrom::Current(sz))) => self.moov_bytes = self.moov_bytes - (sz as usize), + _ => () + }; + println!("remaining moov_bytes: {}", self.moov_bytes); + } + } + } + }; + &self.c_state + } + + fn state(&self) -> &ConsumerState<(), (), Move> { + &self.c_state + } +} + +#[allow(unused_must_use)] +fn explore_mp4_file(filename: &str) { + let mut p = FileProducer::new(filename, 400).unwrap(); + let mut c = MP4Consumer{state: MP4State::Main, moov_bytes: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; + //c.run(&mut p); + while let &ConsumerState::Continue(mv) = p.apply(&mut c) { + println!("move: {:?}", mv); + } + println!("last consumer state: {:?} | last state: {:?}", c.c_state, c.state); + + if let ConsumerState::Done(Move::Consume(0), ()) = c.c_state { + println!("consumer state ok"); + } else { + assert!(false, "consumer should have reached Done state"); + } + assert_eq!(c.state, MP4State::Main); + assert_eq!(p.state(), FileProducerState::Eof); + //assert!(false); +} + + +#[test] +fn small_test() { + explore_mp4_file("assets/small.mp4"); +} + + +#[test] +fn big_bunny_test() { + explore_mp4_file("assets/bigbuckbunny.mp4"); +} + + + diff --git a/bash-5.1/vendor/nom/tests/multiline.rs b/bash-5.1/vendor/nom/tests/multiline.rs new file mode 100644 index 0000000..9016472 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/multiline.rs @@ -0,0 +1,21 @@ +#[macro_use] +extern crate nom; + +use nom::{IResult,alphanumeric,eol}; + +use std::str; + +named!(end_of_line, alt!(eof!() | eol)); +named!(read_line <&str>, map_res!( + terminated!(alphanumeric, end_of_line), + str::from_utf8 +)); +named!(read_lines >, many0!(read_line)); + +#[test] +fn read_lines_test() { + let res = IResult::Done(&b""[..], vec!["Duck", "Dog", "Cow"]); + + assert_eq!(read_lines(&b"Duck\nDog\nCow\n"[..]), res); + assert_eq!(read_lines(&b"Duck\nDog\nCow"[..]), res); +} diff --git a/bash-5.1/vendor/nom/tests/named_args.rs b/bash-5.1/vendor/nom/tests/named_args.rs new file mode 100644 index 0000000..e998a08 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/named_args.rs @@ -0,0 +1,108 @@ +#[macro_use] +extern crate nom; + +use nom::{IResult,digit}; + +// Parser definition + +use std::str; +use std::str::FromStr; + +use self::Operator::*; + +enum Operator { + Slash, + Star, +} + +impl Operator { + fn to_str(&self) -> &'static str { + match *self { + Slash => "/", + Star => "*", + } + } +} + +// Parse the specified `Operator`. +named_args!(operator(op: Operator) <&[u8]>, + tag!(op.to_str()) +); + +// We parse any expr surrounded by the tags `open_tag` and `close_tag`, ignoring all whitespaces around those +named_args!(brackets<'a>(open_tag: &str, close_tag: &str) , ws!(delimited!( tag!(open_tag), expr, tag!(close_tag) )) ); + +// We transform an integer string into a i64, ignoring surrounding whitespaces +// We look for a digit suite, and try to convert it. +// If either str::from_utf8 or FromStr::from_str fail, +// we fallback to the brackets parser defined above +named!(factor, alt!( + map_res!( + map_res!( + ws!(digit), + str::from_utf8 + ), + FromStr::from_str + ) + | call!(brackets, "(", ")") + ) +); + +// We read an initial factor and for each time we find +// a * or / operator followed by another factor, we do +// the math by folding everything +named!(term , do_parse!( + init: factor >> + res: fold_many0!( + pair!(alt!(call!(operator, Star) | call!(operator, Slash)), factor), + init, + |acc, (op, val): (&[u8], i64)| { + if (op[0] as char) == '*' { acc * val } else { acc / val } + } + ) >> + (res) + ) +); + +named!(expr , do_parse!( + init: term >> + res: fold_many0!( + pair!(alt!(tag!("+") | tag!("-")), term), + init, + |acc, (op, val): (&[u8], i64)| { + if (op[0] as char) == '+' { acc + val } else { acc - val } + } + ) >> + (res) + ) +); + +#[test] +fn factor_test() { + assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3)); + assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12)); + assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537)); + assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24)); +} + + +#[test] +fn term_test() { + assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8)); + assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8)); + assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8)); +} + +#[test] +fn expr_test() { + assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3)); + assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17)); + assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11)); +} + +#[test] +fn parens_test() { + assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2)); + assert_eq!(expr(&b" 2* ( 3 + 4 ) "[..]), IResult::Done(&b""[..], 14)); + assert_eq!(expr(&b" 2*2 / ( 5 - 1) + 3"[..]), IResult::Done(&b""[..], 4)); +} diff --git a/bash-5.1/vendor/nom/tests/omnom.rs b/bash-5.1/vendor/nom/tests/omnom.rs new file mode 100644 index 0000000..f90b379 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/omnom.rs @@ -0,0 +1,160 @@ +#![cfg(feature = "stream")] + +#[macro_use] +extern crate nom; + +use nom::{Producer,Consumer,ConsumerState,Input,Move,MemProducer,IResult,Offset}; + +#[derive(PartialEq,Eq,Debug)] +enum State { + Beginning, + Middle, + End, + Done, + Error +} + +struct TestConsumer { + state: State, + c_state: ConsumerState, + counter: usize, +} + +named!(om_parser, tag!("om")); +named!(nomnom_parser<&[u8],Vec<&[u8]> >, many1!(tag!("nom"))); +named!(end_parser, tag!("kthxbye")); + +impl<'a> Consumer<&'a[u8], usize, (), Move> for TestConsumer { + fn state(&self) -> &ConsumerState { + &self.c_state + } + + fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState { + match self.state { + State::Beginning => { + match input { + Input::Empty | Input::Eof(None) => { + self.state = State::Error; + self.c_state = ConsumerState::Error(()); + }, + Input::Element(sl) | Input::Eof(Some(sl)) => { + match om_parser(sl) { + IResult::Error(_) => { + self.state = State::Error; + self.c_state = ConsumerState::Error(()); + }, + IResult::Incomplete(n) => { + self.c_state = ConsumerState::Continue(Move::Await(n)); + }, + IResult::Done(i,_) => { + self.state = State::Middle; + self.c_state = ConsumerState::Continue(Move::Consume(sl.offset(i))); + } + } + } + } + }, + State::Middle => { + match input { + Input::Empty | Input::Eof(None) => { + self.state = State::Error; + self.c_state = ConsumerState::Error(()); + }, + Input::Element(sl) | Input::Eof(Some(sl)) => { + match nomnom_parser(sl) { + IResult::Error(_) => { + self.state = State::End; + self.c_state = ConsumerState::Continue(Move::Consume(0)); + }, + IResult::Incomplete(n) => { + println!("Middle got Incomplete({:?})", n); + self.c_state = ConsumerState::Continue(Move::Await(n)); + }, + IResult::Done(i,noms_vec) => { + self.counter = self.counter + noms_vec.len(); + self.state = State::Middle; + self.c_state = ConsumerState::Continue(Move::Consume(sl.offset(i))); + } + } + } + } + }, + State::End => { + match input { + Input::Empty | Input::Eof(None) => { + self.state = State::Error; + self.c_state = ConsumerState::Error(()); + }, + Input::Element(sl) | Input::Eof(Some(sl)) => { + match end_parser(sl) { + IResult::Error(_) => { + self.state = State::Error; + self.c_state = ConsumerState::Error(()); + }, + IResult::Incomplete(n) => { + self.c_state = ConsumerState::Continue(Move::Await(n)); + }, + IResult::Done(i,_) => { + self.state = State::Done; + self.c_state = ConsumerState::Done(Move::Consume(sl.offset(i)), self.counter); + } + } + } + } + }, + State::Done | State::Error => { + // this should not be called + self.state = State::Error; + self.c_state = ConsumerState::Error(()) + } + }; + &self.c_state + } +} + +#[test] +fn nom1() { + let mut p = MemProducer::new(&b"omnomkthxbye"[..], 8); + let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; + while let &ConsumerState::Continue(Move::Consume(_)) = p.apply(&mut c) { + } + + assert_eq!(c.counter, 1); + assert_eq!(c.state, State::Done); +} + +#[test] +fn nomnomnom() { + let mut p = MemProducer::new(&b"omnomnomnomkthxbye"[..], 9); + let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; + while let &ConsumerState::Continue(_) = p.apply(&mut c) { + } + + assert_eq!(c.counter, 3); + assert_eq!(c.state, State::Done); +} + +#[test] +fn no_nomnom() { + let mut p = MemProducer::new(&b"omkthxbye"[..], 8); + let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; + while let &ConsumerState::Continue(_) = p.apply(&mut c) { + } + + assert_eq!(c.counter, 0); + assert_eq!(c.state, State::Done); +} + +/* +#[test] +fn impolite() { + let mut p = MemProducer::new(&b"omnomnomnom"[..], 11); + let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; + while let &ConsumerState::Continue(cont) = p.apply(&mut c) { + println!("continue {:?}", cont); + } + + assert_eq!(c.counter, 3); + assert_eq!(c.state, State::End); +} +*/ diff --git a/bash-5.1/vendor/nom/tests/overflow.rs b/bash-5.1/vendor/nom/tests/overflow.rs new file mode 100644 index 0000000..d20099f --- /dev/null +++ b/bash-5.1/vendor/nom/tests/overflow.rs @@ -0,0 +1,99 @@ +#[macro_use] +extern crate nom; + +use nom::{IResult,Needed,be_u8,be_u64}; + +// Parser definition + +// We request a length that would trigger an overflow if computing consumed + requested +named!(parser01<&[u8],()>, + do_parse!( + hdr: take!(1) >> + data: take!(18446744073709551615) >> + ( () ) + ) +); + +// We request a length that would trigger an overflow if computing consumed + requested +named!(parser02<&[u8],(&[u8],&[u8])>, + tuple!(take!(1),take!(18446744073709551615)) +); + +#[test] +fn overflow_incomplete_do_parse() { + assert_eq!(parser01(&b"3"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_tuple() { + assert_eq!(parser02(&b"3"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_length_bytes() { + named!(multi<&[u8], Vec<&[u8]> >, many0!( length_bytes!(be_u64) ) ); + + // Trigger an overflow in length_bytes + assert_eq!(multi(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xff\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_many0() { + named!(multi<&[u8], Vec<&[u8]> >, many0!( length_bytes!(be_u64) ) ); + + // Trigger an overflow in many0 + assert_eq!(multi(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xef\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +#[cfg(feature = "std")] +fn overflow_incomplete_many1() { + named!(multi<&[u8], Vec<&[u8]> >, many1!( length_bytes!(be_u64) ) ); + + // Trigger an overflow in many1 + assert_eq!(multi(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xef\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_many_till() { + named!(multi<&[u8], (Vec<&[u8]>, &[u8]) >, many_till!( length_bytes!(be_u64), tag!("abc") ) ); + + // Trigger an overflow in many_till + assert_eq!(multi(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xef\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_many_m_n() { + named!(multi<&[u8], Vec<&[u8]> >, many_m_n!(2, 4, length_bytes!(be_u64) ) ); + + // Trigger an overflow in many_m_n + assert_eq!(multi(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xef\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_count() { + named!(counter<&[u8], Vec<&[u8]> >, count!( length_bytes!(be_u64), 2 ) ); + + assert_eq!(counter(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xef\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_count_fixed() { + named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], length_bytes!(be_u64), 2 ) ); + + assert_eq!(counter(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xef\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_length_count() { + named!(multi<&[u8], Vec<&[u8]> >, length_count!( be_u8, length_bytes!(be_u64) ) ); + + assert_eq!(multi(&b"\x04\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xee\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} + +#[test] +fn overflow_incomplete_length_data() { + named!(multi<&[u8], Vec<&[u8]> >, many0!( length_data!(be_u64) ) ); + + assert_eq!(multi(&b"\x00\x00\x00\x00\x00\x00\x00\x01\xaa\xff\xff\xff\xff\xff\xff\xff\xff\xaa"[..]), IResult::Incomplete(Needed::Unknown)); +} diff --git a/bash-5.1/vendor/nom/tests/reborrow_fold.rs b/bash-5.1/vendor/nom/tests/reborrow_fold.rs new file mode 100644 index 0000000..0527cb2 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/reborrow_fold.rs @@ -0,0 +1,16 @@ +#![allow(dead_code)] +#![allow(unused_variables)] + + +#[macro_use] +extern crate nom; + +use std::str; + + +named_args!(atom<'a>(tomb: &'a mut ()), + map!(map_res!(is_not_s!(" \t\r\n()"), str::from_utf8), ToString::to_string)); + + +named_args!(list<'a>(tomb: &'a mut ()), + delimited!(char!('('), fold_many0!(call!(atom, tomb), "".to_string(), |acc: String, next: String| acc + next.as_str()), char!(')'))); diff --git a/bash-5.1/vendor/nom/tests/test1.rs b/bash-5.1/vendor/nom/tests/test1.rs new file mode 100644 index 0000000..95f8fd4 --- /dev/null +++ b/bash-5.1/vendor/nom/tests/test1.rs @@ -0,0 +1,44 @@ +#![cfg(feature = "stream")] + +#[macro_use] +extern crate nom; + +use nom::{IResult,Producer,FileProducer,not_line_ending}; + +use std::str; +use std::fmt::Debug; + +#[test] +#[allow(unused_must_use)] +fn tag() { + FileProducer::new("assets/links.txt", 20).map(|producer: FileProducer| { + let mut p = producer; + p.refill(); + + consumer_from_parser!(PrintConsumer<()>, flat_map!(map_res!(tag!("https!"), str::from_utf8), print)); + let mut cs = PrintConsumer::new(); + for _ in 1..4 { + p.apply(&mut cs); + } + }); +} + +pub fn print(input: T) -> IResult { + println!("{:?}", input); + IResult::Done(input, ()) +} + + +#[test] +fn is_not() { + //is_not!(foo b"\r\n"); + named!(foo<&[u8],&[u8]>, is_not!(&b"\r\n"[..])); + let a = &b"ab12cd\nefgh"[..]; + assert_eq!(foo(a), IResult::Done(&b"\nefgh"[..], &b"ab12cd"[..])); +} + +#[test] +fn exported_public_method_defined_by_macro() { + let a = &b"ab12cd\nefgh"[..]; + assert_eq!(not_line_ending(a), IResult::Done(&b"\nefgh"[..], &b"ab12cd"[..])); +} diff --git a/bash-5.1/vendor/num-traits-0.1.43/.cargo-checksum.json b/bash-5.1/vendor/num-traits-0.1.43/.cargo-checksum.json new file mode 100644 index 0000000..762feb3 --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b3ca516be2bbfdf5b76fd95da36d75b40161074f5f75f81391737b7c7cdee4c6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"b49a361bd2026fbbe3c778ab9ce1c100bbf459a5c47f6d35f55086c0c4da1285","RELEASES.md":"86c3e6703e6948bfc23c165a8b121930b8da4ffc7c38ab49d7a9e27b1655090e","bors.toml":"1c81ede536a37edd30fe4e622ff0531b25372403ac9475a5d6c50f14156565a2","ci/rustup.sh":"723d546a1ffefcdd5d4db9fb26dbf4128954e3991aff32932284cdc67fa5c85e","ci/test_full.sh":"c66b8c60fa2a643f521cd645aa9338d74dd29ee064c670557ae95b73f919b5cb","src/lib.rs":"3beb14151cfb7fe47f1c4f42869df5c4a347efac34b93b34ec776c158be78fcc"},"package":"92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31"} \ No newline at end of file diff --git a/bash-5.1/vendor/num-traits-0.1.43/Cargo.toml b/bash-5.1/vendor/num-traits-0.1.43/Cargo.toml new file mode 100644 index 0000000..fd68dfc --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/Cargo.toml @@ -0,0 +1,29 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "num-traits" +version = "0.1.43" +authors = ["The Rust Project Developers"] +description = "Numeric traits for generic mathematics" +homepage = "https://github.com/rust-num/num-traits" +documentation = "https://docs.rs/num-traits" +readme = "README.md" +keywords = ["mathematics", "numerics"] +categories = ["algorithms", "science"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num-traits" + +[lib] +doctest = false +[dependencies.num-traits] +version = "0.2.0" diff --git a/bash-5.1/vendor/num-traits-0.1.43/LICENSE-APACHE b/bash-5.1/vendor/num-traits-0.1.43/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/num-traits-0.1.43/LICENSE-MIT b/bash-5.1/vendor/num-traits-0.1.43/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/num-traits-0.1.43/README.md b/bash-5.1/vendor/num-traits-0.1.43/README.md new file mode 100644 index 0000000..83021f9 --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/README.md @@ -0,0 +1,33 @@ +# num-traits + +[![crate](https://img.shields.io/crates/v/num-traits.svg)](https://crates.io/crates/num-traits) +[![documentation](https://docs.rs/num-traits/badge.svg)](https://docs.rs/num-traits) +[![Travis status](https://travis-ci.org/rust-num/num-traits.svg?branch=master)](https://travis-ci.org/rust-num/num-traits) + +Numeric traits for generic mathematics in Rust. + +This version of the crate only exists to re-export compatible +items from `num-traits` 0.2. Please consider updating! + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +num-traits = "0.1" +``` + +and this to your crate root: + +```rust +extern crate num_traits; +``` + +## Releases + +Release notes are available in [RELEASES.md](RELEASES.md). + +## Compatibility + +The `num-traits` crate is tested for rustc 1.8 and greater. diff --git a/bash-5.1/vendor/num-traits-0.1.43/RELEASES.md b/bash-5.1/vendor/num-traits-0.1.43/RELEASES.md new file mode 100644 index 0000000..d2bc774 --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/RELEASES.md @@ -0,0 +1,41 @@ +# Release 0.2.0 + +- **breaking change**: There is now a `std` feature, enabled by default, along + with the implication that building *without* this feature makes this a + `#[no_std]` crate. + - The `Float` and `Real` traits are only available when `std` is enabled. + - Otherwise, the API is unchanged, and num-traits 0.1.43 now re-exports its + items from num-traits 0.2 for compatibility (the [semver-trick]). + +**Contributors**: @cuviper, @termoshtt, @vks + +[semver-trick]: https://github.com/dtolnay/semver-trick + +# Release 0.1.43 + +- All items are now re-exported from num-traits 0.2 for compatibility. + +# Release 0.1.42 + +- [num-traits now has its own source repository][num-356] at [rust-num/num-traits][home]. +- [`ParseFloatError` now implements `Display`][22]. +- [The new `AsPrimitive` trait][17] implements generic casting with the `as` operator. +- [The new `CheckedShl` and `CheckedShr` traits][21] implement generic + support for the `checked_shl` and `checked_shr` methods on primitive integers. +- [The new `Real` trait][23] offers a subset of `Float` functionality that may be applicable to more + types, with a blanket implementation for all existing `T: Float` types. + +Thanks to @cuviper, @Enet4, @fabianschuiki, @svartalf, and @yoanlcq for their contributions! + +[home]: https://github.com/rust-num/num-traits +[num-356]: https://github.com/rust-num/num/pull/356 +[17]: https://github.com/rust-num/num-traits/pull/17 +[21]: https://github.com/rust-num/num-traits/pull/21 +[22]: https://github.com/rust-num/num-traits/pull/22 +[23]: https://github.com/rust-num/num-traits/pull/23 + + +# Prior releases + +No prior release notes were kept. Thanks all the same to the many +contributors that have made this crate what it is! diff --git a/bash-5.1/vendor/num-traits-0.1.43/bors.toml b/bash-5.1/vendor/num-traits-0.1.43/bors.toml new file mode 100644 index 0000000..ca08e81 --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/bors.toml @@ -0,0 +1,3 @@ +status = [ + "continuous-integration/travis-ci/push", +] diff --git a/bash-5.1/vendor/num-traits-0.1.43/ci/rustup.sh b/bash-5.1/vendor/num-traits-0.1.43/ci/rustup.sh new file mode 100755 index 0000000..16483d4 --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/ci/rustup.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Use rustup to locally run the same suite of tests as .travis.yml. +# (You should first install/update 1.8.0, stable, beta, and nightly.) + +set -ex + +export TRAVIS_RUST_VERSION +for TRAVIS_RUST_VERSION in 1.8.0 stable beta nightly; do + run="rustup run $TRAVIS_RUST_VERSION" + $run cargo build --verbose + $run $PWD/ci/test_full.sh +done diff --git a/bash-5.1/vendor/num-traits-0.1.43/ci/test_full.sh b/bash-5.1/vendor/num-traits-0.1.43/ci/test_full.sh new file mode 100755 index 0000000..c64610f --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/ci/test_full.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +set -ex + +echo Testing num-traits on rustc ${TRAVIS_RUST_VERSION} + +# num-integer should build and test everywhere. +cargo build --verbose +cargo test --verbose + +# We have no features to test... diff --git a/bash-5.1/vendor/num-traits-0.1.43/src/lib.rs b/bash-5.1/vendor/num-traits-0.1.43/src/lib.rs new file mode 100644 index 0000000..80075d7 --- /dev/null +++ b/bash-5.1/vendor/num-traits-0.1.43/src/lib.rs @@ -0,0 +1,88 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Numeric traits for generic mathematics +//! +//! This version of the crate only exists to re-export compatible +//! items from num-traits 0.2. Please consider updating! + +#![doc(html_root_url = "https://docs.rs/num-traits/0.1")] + +extern crate num_traits; + +pub use bounds::Bounded; +pub use float::{Float, FloatConst}; +// pub use real::Real; // NOTE: Don't do this, it breaks `use num_traits::*;`. +pub use identities::{Zero, One, zero, one}; +pub use ops::checked::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, CheckedShl, CheckedShr}; +pub use ops::wrapping::{WrappingAdd, WrappingMul, WrappingSub}; +pub use ops::saturating::Saturating; +pub use sign::{Signed, Unsigned, abs, abs_sub, signum}; +pub use cast::{AsPrimitive, FromPrimitive, ToPrimitive, NumCast, cast}; +pub use int::PrimInt; +pub use pow::{pow, checked_pow}; + + +// Re-exports from num-traits 0.2! + +pub use num_traits::{Num, NumOps, NumRef, RefNum}; +pub use num_traits::{NumAssignOps, NumAssign, NumAssignRef}; +pub use num_traits::{FloatErrorKind, ParseFloatError}; +pub use num_traits::clamp; + +// Note: the module structure is explicitly re-created, rather than re-exporting en masse, +// so we won't expose any items that may be added later in the new version. + +pub mod identities { + pub use num_traits::identities::{Zero, One, zero, one}; +} + +pub mod sign { + pub use num_traits::sign::{Signed, Unsigned, abs, abs_sub, signum}; +} + +pub mod ops { + pub mod saturating { + pub use num_traits::ops::saturating::Saturating; + } + + pub mod checked { + pub use num_traits::ops::checked::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, + CheckedShl, CheckedShr}; + } + + pub mod wrapping { + pub use num_traits::ops::wrapping::{WrappingAdd, WrappingMul, WrappingSub}; + } +} + +pub mod bounds { + pub use num_traits::bounds::Bounded; +} + +pub mod float { + pub use num_traits::float::{Float, FloatConst}; +} + +pub mod real { + pub use num_traits::real::Real; +} + +pub mod cast { + pub use num_traits::cast::{AsPrimitive, FromPrimitive, ToPrimitive, NumCast, cast}; +} + +pub mod int { + pub use num_traits::int::PrimInt; +} + +pub mod pow { + pub use num_traits::pow::{pow, checked_pow}; +} diff --git a/bash-5.1/vendor/num-traits/.cargo-checksum.json b/bash-5.1/vendor/num-traits/.cargo-checksum.json new file mode 100644 index 0000000..82a6d1c --- /dev/null +++ b/bash-5.1/vendor/num-traits/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"5b2749641deeabb2dfcc8e4d7e26ccfbc306800021e0d24e8367f313e57f9def","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"81e7df6fa6bea6f8c2809f9af68e3d32e7a4504b93394f775d37ed3d9f7f9166","RELEASES.md":"e1f774cba66e5e15e1086ab8afebece771140dd4168f59dca8dd4fd5e50b72dc","build.rs":"cf682b2322303196e241048cb56d873597b78a3b4e3f275f6f761dadb33a65f5","src/bounds.rs":"c90190de4dfba13c49119dbdf889726f8ece1cbd7dfd4bbfa364ea995f627e49","src/cast.rs":"8c8384dcdfaf926b9331399d528278fc73851f8b5e1105dee343f4f19557e932","src/float.rs":"6a84820f4828515639565848a63359b3e69329aa36b990178adbfc7d141ef0c5","src/identities.rs":"5b6238ebd52e1fadd5b405bc40ad81e45346bcb1c4b46cf1f0496a30be7c9bc4","src/int.rs":"bb4c0f4ce8d71e262bd9119ab820dd5a79e2bd476a8ad7e84b2167733b11d9d8","src/lib.rs":"cc0c8352b3f29a22b17f76e9cfe12acb279ec2aac5e22a9395569d58445c137c","src/macros.rs":"ee96613a2c73a3bef10ec7ae4d359dbf5f0b41f83e8a87c3d62ccc18dd27e498","src/ops/checked.rs":"b6dfae21fe1a5ce41e92074c57d204284975ec56d45e63cac5f0136b8c3643b4","src/ops/euclid.rs":"71e0e181bd365c196a7dea980c2ec8bd47fd1d1d9b47bd3f401edcadb861eb0b","src/ops/inv.rs":"dd80b9bd48d815f17855a25842287942317fa49d1fdcdd655b61bd20ef927cda","src/ops/mod.rs":"3bea8b98fa7537c0a5b4562d1b9d4d49481f1e2e88941cfd4cc8f0f3f0870fb3","src/ops/mul_add.rs":"368bdebb40b16f3b4b85cf50235954268ff601ec7a458a3a83fe433f47f86f6d","src/ops/overflowing.rs":"1b92882a5a738ea4cafdb0971101dc438be9043f540e1246f58f7c9ecf6348dc","src/ops/saturating.rs":"6fb4b2a2c78d9202152a84586d7b068444b78d3caed4b293980832672a234d4b","src/ops/wrapping.rs":"0acf88c0e5fc81a3c6790b31986ab9be5b16c720c9e27461fe5d69b710ffcaba","src/pow.rs":"9f78cb9c4d5987b59e16f4141723a33ff689781cc352f357b0cc0111d22cde3a","src/real.rs":"b5115bb2cfb752a59426bb3fcbabf9cff15521a00a3f8b5ef4dfc0b0b31bb1f4","src/sign.rs":"83562caa3501c6873558eb64c9e3bfe25b4b20d38562a7aa7cc9adafcb3ff037","tests/cast.rs":"0a41785611b3909ecb4a88d6d5264a85564f6de8fbfc761436d3c8baafc8e3d0"},"package":"578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"} \ No newline at end of file diff --git a/bash-5.1/vendor/num-traits/Cargo.toml b/bash-5.1/vendor/num-traits/Cargo.toml new file mode 100644 index 0000000..b30fca3 --- /dev/null +++ b/bash-5.1/vendor/num-traits/Cargo.toml @@ -0,0 +1,51 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "num-traits" +version = "0.2.15" +authors = ["The Rust Project Developers"] +build = "build.rs" +exclude = [ + "/bors.toml", + "/ci/*", + "/.github/*", +] +description = "Numeric traits for generic mathematics" +homepage = "https://github.com/rust-num/num-traits" +documentation = "https://docs.rs/num-traits" +readme = "README.md" +keywords = [ + "mathematics", + "numerics", +] +categories = [ + "algorithms", + "science", + "no-std", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-num/num-traits" + +[package.metadata.docs.rs] +features = ["std"] + +[dependencies.libm] +version = "0.2.0" +optional = true + +[build-dependencies.autocfg] +version = "1" + +[features] +default = ["std"] +i128 = [] +std = [] diff --git a/bash-5.1/vendor/num-traits/LICENSE-APACHE b/bash-5.1/vendor/num-traits/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/num-traits/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/num-traits/LICENSE-MIT b/bash-5.1/vendor/num-traits/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/num-traits/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/num-traits/README.md b/bash-5.1/vendor/num-traits/README.md new file mode 100644 index 0000000..3633962 --- /dev/null +++ b/bash-5.1/vendor/num-traits/README.md @@ -0,0 +1,63 @@ +# num-traits + +[![crate](https://img.shields.io/crates/v/num-traits.svg)](https://crates.io/crates/num-traits) +[![documentation](https://docs.rs/num-traits/badge.svg)](https://docs.rs/num-traits) +[![minimum rustc 1.8](https://img.shields.io/badge/rustc-1.8+-red.svg)](https://rust-lang.github.io/rfcs/2495-min-rust-version.html) +[![build status](https://github.com/rust-num/num-traits/workflows/master/badge.svg)](https://github.com/rust-num/num-traits/actions) + +Numeric traits for generic mathematics in Rust. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +num-traits = "0.2" +``` + +## Features + +This crate can be used without the standard library (`#![no_std]`) by disabling +the default `std` feature. Use this in `Cargo.toml`: + +```toml +[dependencies.num-traits] +version = "0.2" +default-features = false +# features = ["libm"] # <--- Uncomment if you wish to use `Float` and `Real` without `std` +``` + +The `Float` and `Real` traits are only available when either `std` or `libm` is enabled. +The `libm` feature is only available with Rust 1.31 and later ([see PR #99](https://github.com/rust-num/num-traits/pull/99)). + +The `FloatCore` trait is always available. `MulAdd` and `MulAddAssign` for `f32` +and `f64` also require `std` or `libm`, as do implementations of signed and floating- +point exponents in `Pow`. + +Implementations for `i128` and `u128` are only available with Rust 1.26 and +later. The build script automatically detects this, but you can make it +mandatory by enabling the `i128` crate feature. + +## Releases + +Release notes are available in [RELEASES.md](RELEASES.md). + +## Compatibility + +The `num-traits` crate is tested for rustc 1.8 and greater. + +## License + +Licensed under either of + + * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) + * [MIT license](http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bash-5.1/vendor/num-traits/RELEASES.md b/bash-5.1/vendor/num-traits/RELEASES.md new file mode 100644 index 0000000..cd33c04 --- /dev/null +++ b/bash-5.1/vendor/num-traits/RELEASES.md @@ -0,0 +1,259 @@ +# Release 0.2.15 (2022-05-02) + +- [The new `Euclid` trait calculates Euclidean division][195], where the + remainder is always positive or zero. +- [The new `LowerBounded` and `UpperBounded` traits][210] separately describe + types with lower and upper bounds. These traits are automatically implemented + for all fully-`Bounded` types. +- [The new `Float::copysign` method copies the sign of the argument][207] to + to the magnitude of `self`. +- [The new `PrimInt::leading_ones` and `trailing_ones` methods][205] are the + complement of the existing methods that count zero bits. +- [The new `PrimInt::reverse_bits` method reverses the order of all bits][202] + of a primitive integer. +- [Improved `Num::from_str_radix` for floats][201], also [ignoring case][214]. +- [`Float` and `FloatCore` use more from `libm`][196] when that is enabled. + +**Contributors**: @alion02, @clarfonthey, @cuviper, @ElectronicRU, +@ibraheemdev, @SparrowLii, @sshilovsky, @tspiteri, @XAMPPRocky, @Xiretza + +[195]: https://github.com/rust-num/num-traits/pull/195 +[196]: https://github.com/rust-num/num-traits/pull/196 +[201]: https://github.com/rust-num/num-traits/pull/201 +[202]: https://github.com/rust-num/num-traits/pull/202 +[205]: https://github.com/rust-num/num-traits/pull/205 +[207]: https://github.com/rust-num/num-traits/pull/207 +[210]: https://github.com/rust-num/num-traits/pull/210 +[214]: https://github.com/rust-num/num-traits/pull/214 + +# Release 0.2.14 (2020-10-29) + +- Clarify the license specification as "MIT OR Apache-2.0". + +**Contributors**: @cuviper + +# Release 0.2.13 (2020-10-29) + +- [The new `OverflowingAdd`, `OverflowingSub`, and `OverflowingMul` traits][180] + return a tuple with the operation result and a `bool` indicating overflow. +- [The "i128" feature now overrides compiler probes for that support][185]. + This may fix scenarios where `autocfg` probing doesn't work properly. +- [Casts from large `f64` values to `f32` now saturate to infinity][186]. They + previously returned `None` because that was once thought to be undefined + behavior, but [rust#15536] resolved that such casts are fine. +- [`Num::from_str_radix` documents requirements for radix support][192], which + are now more relaxed than previously implied. It is suggested to accept at + least `2..=36` without panicking, but `Err` may be returned otherwise. + +**Contributors**: @cuviper, @Enet4, @KaczuH, @martin-t, @newpavlov + +[180]: https://github.com/rust-num/num-traits/pull/180 +[185]: https://github.com/rust-num/num-traits/pull/185 +[186]: https://github.com/rust-num/num-traits/pull/186 +[192]: https://github.com/rust-num/num-traits/issues/192 +[rust#15536]: https://github.com/rust-lang/rust/issues/15536 + +# Release 0.2.12 (2020-06-11) + +- [The new `WrappingNeg` trait][153] will wrap the result if it exceeds the + boundary of the type, e.g. `i32::MIN.wrapping_neg() == i32::MIN`. +- [The new `SaturatingAdd`, `SaturatingSub`, and `SaturatingMul` traits][165] + will saturate at the numeric bounds if the operation would overflow. These + soft-deprecate the existing `Saturating` trait that only has addition and + subtraction methods. +- [Added new constants for logarithms, `FloatConst::{LOG10_2, LOG2_10}`][171]. + +**Contributors**: @cuviper, @ocstl, @trepetti, @vallentin + +[153]: https://github.com/rust-num/num-traits/pull/153 +[165]: https://github.com/rust-num/num-traits/pull/165 +[171]: https://github.com/rust-num/num-traits/pull/171 + +# Release 0.2.11 (2020-01-09) + +- [Added the full circle constant τ as `FloatConst::TAU`][145]. +- [Updated the `autocfg` build dependency to 1.0][148]. + +**Contributors**: @cuviper, @m-ou-se + +[145]: https://github.com/rust-num/num-traits/pull/145 +[148]: https://github.com/rust-num/num-traits/pull/148 + +# Release 0.2.10 (2019-11-22) + +- [Updated the `libm` dependency to 0.2][144]. + +**Contributors**: @CryZe + +[144]: https://github.com/rust-num/num-traits/pull/144 + +# Release 0.2.9 (2019-11-12) + +- [A new optional `libm` dependency][99] enables the `Float` and `Real` traits + in `no_std` builds. +- [The new `clamp_min` and `clamp_max`][122] limit minimum and maximum values + while preserving input `NAN`s. +- [Fixed a panic in floating point `from_str_radix` on invalid signs][126]. +- Miscellaneous documentation updates. + +**Contributors**: @cuviper, @dingelish, @HeroicKatora, @jturner314, @ocstl, +@Shnatsel, @termoshtt, @waywardmonkeys, @yoanlcq + +[99]: https://github.com/rust-num/num-traits/pull/99 +[122]: https://github.com/rust-num/num-traits/pull/122 +[126]: https://github.com/rust-num/num-traits/pull/126 + +# Release 0.2.8 (2019-05-21) + +- [Fixed feature detection on `no_std` targets][116]. + +**Contributors**: @cuviper + +[116]: https://github.com/rust-num/num-traits/pull/116 + +# Release 0.2.7 (2019-05-20) + +- [Documented when `CheckedShl` and `CheckedShr` return `None`][90]. +- [The new `Zero::set_zero` and `One::set_one`][104] will set values to their + identities in place, possibly optimized better than direct assignment. +- [Documented general features and intentions of `PrimInt`][108]. + +**Contributors**: @cuviper, @dvdhrm, @ignatenkobrain, @lcnr, @samueltardieu + +[90]: https://github.com/rust-num/num-traits/pull/90 +[104]: https://github.com/rust-num/num-traits/pull/104 +[108]: https://github.com/rust-num/num-traits/pull/108 + +# Release 0.2.6 (2018-09-13) + +- [Documented that `pow(0, 0)` returns `1`][79]. Mathematically, this is not + strictly defined, but the current behavior is a pragmatic choice that has + precedent in Rust `core` for the primitives and in many other languages. +- [The new `WrappingShl` and `WrappingShr` traits][81] will wrap the shift count + if it exceeds the bit size of the type. + +**Contributors**: @cuviper, @edmccard, @meltinglava + +[79]: https://github.com/rust-num/num-traits/pull/79 +[81]: https://github.com/rust-num/num-traits/pull/81 + +# Release 0.2.5 (2018-06-20) + +- [Documentation for `mul_add` now clarifies that it's not always faster.][70] +- [The default methods in `FromPrimitive` and `ToPrimitive` are more robust.][73] + +**Contributors**: @cuviper, @frewsxcv + +[70]: https://github.com/rust-num/num-traits/pull/70 +[73]: https://github.com/rust-num/num-traits/pull/73 + +# Release 0.2.4 (2018-05-11) + +- [Support for 128-bit integers is now automatically detected and enabled.][69] + Setting the `i128` crate feature now causes the build script to panic if such + support is not detected. + +**Contributors**: @cuviper + +[69]: https://github.com/rust-num/num-traits/pull/69 + +# Release 0.2.3 (2018-05-10) + +- [The new `CheckedNeg` and `CheckedRem` traits][63] perform checked `Neg` and + `Rem`, returning `Some(output)` or `None` on overflow. +- [The `no_std` implementation of `FloatCore::to_degrees` for `f32`][61] now + uses a constant for greater accuracy, mirroring [rust#47919]. (With `std` it + just calls the inherent `f32::to_degrees` in the standard library.) +- [The new `MulAdd` and `MulAddAssign` traits][59] perform a fused multiply- + add. For integer types this is just a convenience, but for floating point + types this produces a more accurate result than the separate operations. +- [All applicable traits are now implemented for 128-bit integers][60] starting + with Rust 1.26, enabled by the new `i128` crate feature. The `FromPrimitive` + and `ToPrimitive` traits now also have corresponding 128-bit methods, which + default to converting via 64-bit integers for compatibility. + +**Contributors**: @cuviper, @LEXUGE, @regexident, @vks + +[59]: https://github.com/rust-num/num-traits/pull/59 +[60]: https://github.com/rust-num/num-traits/pull/60 +[61]: https://github.com/rust-num/num-traits/pull/61 +[63]: https://github.com/rust-num/num-traits/pull/63 +[rust#47919]: https://github.com/rust-lang/rust/pull/47919 + +# Release 0.2.2 (2018-03-18) + +- [Casting from floating point to integers now returns `None` on overflow][52], + avoiding [rustc's undefined behavior][rust-10184]. This applies to the `cast` + function and the traits `NumCast`, `FromPrimitive`, and `ToPrimitive`. + +**Contributors**: @apopiak, @cuviper, @dbarella + +[52]: https://github.com/rust-num/num-traits/pull/52 +[rust-10184]: https://github.com/rust-lang/rust/issues/10184 + + +# Release 0.2.1 (2018-03-01) + +- [The new `FloatCore` trait][32] offers a subset of `Float` for `#![no_std]` use. + [This includes everything][41] except the transcendental functions and FMA. +- [The new `Inv` trait][37] returns the multiplicative inverse, or reciprocal. +- [The new `Pow` trait][37] performs exponentiation, much like the existing `pow` + function, but with generic exponent types. +- [The new `One::is_one` method][39] tests if a value equals 1. Implementers + should override this method if there's a more efficient way to check for 1, + rather than comparing with a temporary `one()`. + +**Contributors**: @clarcharr, @cuviper, @vks + +[32]: https://github.com/rust-num/num-traits/pull/32 +[37]: https://github.com/rust-num/num-traits/pull/37 +[39]: https://github.com/rust-num/num-traits/pull/39 +[41]: https://github.com/rust-num/num-traits/pull/41 + + +# Release 0.2.0 (2018-02-06) + +- **breaking change**: [There is now a `std` feature][30], enabled by default, along + with the implication that building *without* this feature makes this a + `#![no_std]` crate. + - The `Float` and `Real` traits are only available when `std` is enabled. + - Otherwise, the API is unchanged, and num-traits 0.1.43 now re-exports its + items from num-traits 0.2 for compatibility (the [semver-trick]). + +**Contributors**: @cuviper, @termoshtt, @vks + +[semver-trick]: https://github.com/dtolnay/semver-trick +[30]: https://github.com/rust-num/num-traits/pull/30 + + +# Release 0.1.43 (2018-02-06) + +- All items are now [re-exported from num-traits 0.2][31] for compatibility. + +[31]: https://github.com/rust-num/num-traits/pull/31 + + +# Release 0.1.42 (2018-01-22) + +- [num-traits now has its own source repository][num-356] at [rust-num/num-traits][home]. +- [`ParseFloatError` now implements `Display`][22]. +- [The new `AsPrimitive` trait][17] implements generic casting with the `as` operator. +- [The new `CheckedShl` and `CheckedShr` traits][21] implement generic + support for the `checked_shl` and `checked_shr` methods on primitive integers. +- [The new `Real` trait][23] offers a subset of `Float` functionality that may be applicable to more + types, with a blanket implementation for all existing `T: Float` types. + +Thanks to @cuviper, @Enet4, @fabianschuiki, @svartalf, and @yoanlcq for their contributions! + +[home]: https://github.com/rust-num/num-traits +[num-356]: https://github.com/rust-num/num/pull/356 +[17]: https://github.com/rust-num/num-traits/pull/17 +[21]: https://github.com/rust-num/num-traits/pull/21 +[22]: https://github.com/rust-num/num-traits/pull/22 +[23]: https://github.com/rust-num/num-traits/pull/23 + + +# Prior releases + +No prior release notes were kept. Thanks all the same to the many +contributors that have made this crate what it is! diff --git a/bash-5.1/vendor/num-traits/build.rs b/bash-5.1/vendor/num-traits/build.rs new file mode 100644 index 0000000..c7bf364 --- /dev/null +++ b/bash-5.1/vendor/num-traits/build.rs @@ -0,0 +1,29 @@ +extern crate autocfg; + +use std::env; + +fn main() { + let ac = autocfg::new(); + + // If the "i128" feature is explicity requested, don't bother probing for it. + // It will still cause a build error if that was set improperly. + if env::var_os("CARGO_FEATURE_I128").is_some() || ac.probe_type("i128") { + autocfg::emit("has_i128"); + } + + ac.emit_expression_cfg( + "unsafe { 1f64.to_int_unchecked::() }", + "has_to_int_unchecked", + ); + + ac.emit_expression_cfg("1u32.reverse_bits()", "has_reverse_bits"); + ac.emit_expression_cfg("1u32.trailing_ones()", "has_leading_trailing_ones"); + ac.emit_expression_cfg("{ let mut x = 1; x += &2; }", "has_int_assignop_ref"); + ac.emit_expression_cfg("1u32.div_euclid(1u32)", "has_div_euclid"); + + if env::var_os("CARGO_FEATURE_STD").is_some() { + ac.emit_expression_cfg("1f64.copysign(-1f64)", "has_copysign"); + } + + autocfg::rerun_path("build.rs"); +} diff --git a/bash-5.1/vendor/num-traits/src/bounds.rs b/bash-5.1/vendor/num-traits/src/bounds.rs new file mode 100644 index 0000000..36e1bbd --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/bounds.rs @@ -0,0 +1,153 @@ +use core::num::Wrapping; +use core::{f32, f64}; +#[cfg(has_i128)] +use core::{i128, u128}; +use core::{i16, i32, i64, i8, isize}; +use core::{u16, u32, u64, u8, usize}; + +/// Numbers which have upper and lower bounds +pub trait Bounded { + // FIXME (#5527): These should be associated constants + /// Returns the smallest finite number this type can represent + fn min_value() -> Self; + /// Returns the largest finite number this type can represent + fn max_value() -> Self; +} + +/// Numbers which have lower bounds +pub trait LowerBounded { + /// Returns the smallest finite number this type can represent + fn min_value() -> Self; +} + +// FIXME: With a major version bump, this should be a supertrait instead +impl LowerBounded for T { + fn min_value() -> T { + Bounded::min_value() + } +} + +/// Numbers which have upper bounds +pub trait UpperBounded { + /// Returns the largest finite number this type can represent + fn max_value() -> Self; +} + +// FIXME: With a major version bump, this should be a supertrait instead +impl UpperBounded for T { + fn max_value() -> T { + Bounded::max_value() + } +} + +macro_rules! bounded_impl { + ($t:ty, $min:expr, $max:expr) => { + impl Bounded for $t { + #[inline] + fn min_value() -> $t { + $min + } + + #[inline] + fn max_value() -> $t { + $max + } + } + }; +} + +bounded_impl!(usize, usize::MIN, usize::MAX); +bounded_impl!(u8, u8::MIN, u8::MAX); +bounded_impl!(u16, u16::MIN, u16::MAX); +bounded_impl!(u32, u32::MIN, u32::MAX); +bounded_impl!(u64, u64::MIN, u64::MAX); +#[cfg(has_i128)] +bounded_impl!(u128, u128::MIN, u128::MAX); + +bounded_impl!(isize, isize::MIN, isize::MAX); +bounded_impl!(i8, i8::MIN, i8::MAX); +bounded_impl!(i16, i16::MIN, i16::MAX); +bounded_impl!(i32, i32::MIN, i32::MAX); +bounded_impl!(i64, i64::MIN, i64::MAX); +#[cfg(has_i128)] +bounded_impl!(i128, i128::MIN, i128::MAX); + +impl Bounded for Wrapping { + fn min_value() -> Self { + Wrapping(T::min_value()) + } + fn max_value() -> Self { + Wrapping(T::max_value()) + } +} + +bounded_impl!(f32, f32::MIN, f32::MAX); + +macro_rules! for_each_tuple_ { + ( $m:ident !! ) => ( + $m! { } + ); + ( $m:ident !! $h:ident, $($t:ident,)* ) => ( + $m! { $h $($t)* } + for_each_tuple_! { $m !! $($t,)* } + ); +} +macro_rules! for_each_tuple { + ($m:ident) => { + for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, } + }; +} + +macro_rules! bounded_tuple { + ( $($name:ident)* ) => ( + impl<$($name: Bounded,)*> Bounded for ($($name,)*) { + #[inline] + fn min_value() -> Self { + ($($name::min_value(),)*) + } + #[inline] + fn max_value() -> Self { + ($($name::max_value(),)*) + } + } + ); +} + +for_each_tuple!(bounded_tuple); +bounded_impl!(f64, f64::MIN, f64::MAX); + +#[test] +fn wrapping_bounded() { + macro_rules! test_wrapping_bounded { + ($($t:ty)+) => { + $( + assert_eq!( as Bounded>::min_value().0, <$t>::min_value()); + assert_eq!( as Bounded>::max_value().0, <$t>::max_value()); + )+ + }; + } + + test_wrapping_bounded!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); +} + +#[cfg(has_i128)] +#[test] +fn wrapping_bounded_i128() { + macro_rules! test_wrapping_bounded { + ($($t:ty)+) => { + $( + assert_eq!( as Bounded>::min_value().0, <$t>::min_value()); + assert_eq!( as Bounded>::max_value().0, <$t>::max_value()); + )+ + }; + } + + test_wrapping_bounded!(u128 i128); +} + +#[test] +fn wrapping_is_bounded() { + fn require_bounded(_: &T) {} + require_bounded(&Wrapping(42_u32)); + require_bounded(&Wrapping(-42)); +} diff --git a/bash-5.1/vendor/num-traits/src/cast.rs b/bash-5.1/vendor/num-traits/src/cast.rs new file mode 100644 index 0000000..d38c338 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/cast.rs @@ -0,0 +1,814 @@ +use core::mem::size_of; +use core::num::Wrapping; +use core::{f32, f64}; +#[cfg(has_i128)] +use core::{i128, u128}; +use core::{i16, i32, i64, i8, isize}; +use core::{u16, u32, u64, u8, usize}; + +/// A generic trait for converting a value to a number. +/// +/// A value can be represented by the target type when it lies within +/// the range of scalars supported by the target type. +/// For example, a negative integer cannot be represented by an unsigned +/// integer type, and an `i64` with a very high magnitude might not be +/// convertible to an `i32`. +/// On the other hand, conversions with possible precision loss or truncation +/// are admitted, like an `f32` with a decimal part to an integer type, or +/// even a large `f64` saturating to `f32` infinity. +pub trait ToPrimitive { + /// Converts the value of `self` to an `isize`. If the value cannot be + /// represented by an `isize`, then `None` is returned. + #[inline] + fn to_isize(&self) -> Option { + self.to_i64().as_ref().and_then(ToPrimitive::to_isize) + } + + /// Converts the value of `self` to an `i8`. If the value cannot be + /// represented by an `i8`, then `None` is returned. + #[inline] + fn to_i8(&self) -> Option { + self.to_i64().as_ref().and_then(ToPrimitive::to_i8) + } + + /// Converts the value of `self` to an `i16`. If the value cannot be + /// represented by an `i16`, then `None` is returned. + #[inline] + fn to_i16(&self) -> Option { + self.to_i64().as_ref().and_then(ToPrimitive::to_i16) + } + + /// Converts the value of `self` to an `i32`. If the value cannot be + /// represented by an `i32`, then `None` is returned. + #[inline] + fn to_i32(&self) -> Option { + self.to_i64().as_ref().and_then(ToPrimitive::to_i32) + } + + /// Converts the value of `self` to an `i64`. If the value cannot be + /// represented by an `i64`, then `None` is returned. + fn to_i64(&self) -> Option; + + /// Converts the value of `self` to an `i128`. If the value cannot be + /// represented by an `i128` (`i64` under the default implementation), then + /// `None` is returned. + /// + /// This method is only available with feature `i128` enabled on Rust >= 1.26. + /// + /// The default implementation converts through `to_i64()`. Types implementing + /// this trait should override this method if they can represent a greater range. + #[inline] + #[cfg(has_i128)] + fn to_i128(&self) -> Option { + self.to_i64().map(From::from) + } + + /// Converts the value of `self` to a `usize`. If the value cannot be + /// represented by a `usize`, then `None` is returned. + #[inline] + fn to_usize(&self) -> Option { + self.to_u64().as_ref().and_then(ToPrimitive::to_usize) + } + + /// Converts the value of `self` to a `u8`. If the value cannot be + /// represented by a `u8`, then `None` is returned. + #[inline] + fn to_u8(&self) -> Option { + self.to_u64().as_ref().and_then(ToPrimitive::to_u8) + } + + /// Converts the value of `self` to a `u16`. If the value cannot be + /// represented by a `u16`, then `None` is returned. + #[inline] + fn to_u16(&self) -> Option { + self.to_u64().as_ref().and_then(ToPrimitive::to_u16) + } + + /// Converts the value of `self` to a `u32`. If the value cannot be + /// represented by a `u32`, then `None` is returned. + #[inline] + fn to_u32(&self) -> Option { + self.to_u64().as_ref().and_then(ToPrimitive::to_u32) + } + + /// Converts the value of `self` to a `u64`. If the value cannot be + /// represented by a `u64`, then `None` is returned. + fn to_u64(&self) -> Option; + + /// Converts the value of `self` to a `u128`. If the value cannot be + /// represented by a `u128` (`u64` under the default implementation), then + /// `None` is returned. + /// + /// This method is only available with feature `i128` enabled on Rust >= 1.26. + /// + /// The default implementation converts through `to_u64()`. Types implementing + /// this trait should override this method if they can represent a greater range. + #[inline] + #[cfg(has_i128)] + fn to_u128(&self) -> Option { + self.to_u64().map(From::from) + } + + /// Converts the value of `self` to an `f32`. Overflows may map to positive + /// or negative inifinity, otherwise `None` is returned if the value cannot + /// be represented by an `f32`. + #[inline] + fn to_f32(&self) -> Option { + self.to_f64().as_ref().and_then(ToPrimitive::to_f32) + } + + /// Converts the value of `self` to an `f64`. Overflows may map to positive + /// or negative inifinity, otherwise `None` is returned if the value cannot + /// be represented by an `f64`. + /// + /// The default implementation tries to convert through `to_i64()`, and + /// failing that through `to_u64()`. Types implementing this trait should + /// override this method if they can represent a greater range. + #[inline] + fn to_f64(&self) -> Option { + match self.to_i64() { + Some(i) => i.to_f64(), + None => self.to_u64().as_ref().and_then(ToPrimitive::to_f64), + } + } +} + +macro_rules! impl_to_primitive_int_to_int { + ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$DstT> { + let min = $DstT::MIN as $SrcT; + let max = $DstT::MAX as $SrcT; + if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_int_to_uint { + ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$DstT> { + let max = $DstT::MAX as $SrcT; + if 0 <= *self && (size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max) { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_int { + ($T:ident) => { + impl ToPrimitive for $T { + impl_to_primitive_int_to_int! { $T: + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + #[cfg(has_i128)] + fn to_i128 -> i128; + } + + impl_to_primitive_int_to_uint! { $T: + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + #[cfg(has_i128)] + fn to_u128 -> u128; + } + + #[inline] + fn to_f32(&self) -> Option { + Some(*self as f32) + } + #[inline] + fn to_f64(&self) -> Option { + Some(*self as f64) + } + } + }; +} + +impl_to_primitive_int!(isize); +impl_to_primitive_int!(i8); +impl_to_primitive_int!(i16); +impl_to_primitive_int!(i32); +impl_to_primitive_int!(i64); +#[cfg(has_i128)] +impl_to_primitive_int!(i128); + +macro_rules! impl_to_primitive_uint_to_int { + ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$DstT> { + let max = $DstT::MAX as $SrcT; + if size_of::<$SrcT>() < size_of::<$DstT>() || *self <= max { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_uint_to_uint { + ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$DstT> { + let max = $DstT::MAX as $SrcT; + if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_uint { + ($T:ident) => { + impl ToPrimitive for $T { + impl_to_primitive_uint_to_int! { $T: + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + #[cfg(has_i128)] + fn to_i128 -> i128; + } + + impl_to_primitive_uint_to_uint! { $T: + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + #[cfg(has_i128)] + fn to_u128 -> u128; + } + + #[inline] + fn to_f32(&self) -> Option { + Some(*self as f32) + } + #[inline] + fn to_f64(&self) -> Option { + Some(*self as f64) + } + } + }; +} + +impl_to_primitive_uint!(usize); +impl_to_primitive_uint!(u8); +impl_to_primitive_uint!(u16); +impl_to_primitive_uint!(u32); +impl_to_primitive_uint!(u64); +#[cfg(has_i128)] +impl_to_primitive_uint!(u128); + +macro_rules! impl_to_primitive_float_to_float { + ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$DstT> { + // We can safely cast all values, whether NaN, +-inf, or finite. + // Finite values that are reducing size may saturate to +-inf. + Some(*self as $DstT) + } + )*} +} + +#[cfg(has_to_int_unchecked)] +macro_rules! float_to_int_unchecked { + // SAFETY: Must not be NaN or infinite; must be representable as the integer after truncating. + // We already checked that the float is in the exclusive range `(MIN-1, MAX+1)`. + ($float:expr => $int:ty) => { + unsafe { $float.to_int_unchecked::<$int>() } + }; +} + +#[cfg(not(has_to_int_unchecked))] +macro_rules! float_to_int_unchecked { + ($float:expr => $int:ty) => { + $float as $int + }; +} + +macro_rules! impl_to_primitive_float_to_signed_int { + ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$i> { + // Float as int truncates toward zero, so we want to allow values + // in the exclusive range `(MIN-1, MAX+1)`. + if size_of::<$f>() > size_of::<$i>() { + // With a larger size, we can represent the range exactly. + const MIN_M1: $f = $i::MIN as $f - 1.0; + const MAX_P1: $f = $i::MAX as $f + 1.0; + if *self > MIN_M1 && *self < MAX_P1 { + return Some(float_to_int_unchecked!(*self => $i)); + } + } else { + // We can't represent `MIN-1` exactly, but there's no fractional part + // at this magnitude, so we can just use a `MIN` inclusive boundary. + const MIN: $f = $i::MIN as $f; + // We can't represent `MAX` exactly, but it will round up to exactly + // `MAX+1` (a power of two) when we cast it. + const MAX_P1: $f = $i::MAX as $f; + if *self >= MIN && *self < MAX_P1 { + return Some(float_to_int_unchecked!(*self => $i)); + } + } + None + } + )*} +} + +macro_rules! impl_to_primitive_float_to_unsigned_int { + ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $u:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$u> { + // Float as int truncates toward zero, so we want to allow values + // in the exclusive range `(-1, MAX+1)`. + if size_of::<$f>() > size_of::<$u>() { + // With a larger size, we can represent the range exactly. + const MAX_P1: $f = $u::MAX as $f + 1.0; + if *self > -1.0 && *self < MAX_P1 { + return Some(float_to_int_unchecked!(*self => $u)); + } + } else { + // We can't represent `MAX` exactly, but it will round up to exactly + // `MAX+1` (a power of two) when we cast it. + // (`u128::MAX as f32` is infinity, but this is still ok.) + const MAX_P1: $f = $u::MAX as $f; + if *self > -1.0 && *self < MAX_P1 { + return Some(float_to_int_unchecked!(*self => $u)); + } + } + None + } + )*} +} + +macro_rules! impl_to_primitive_float { + ($T:ident) => { + impl ToPrimitive for $T { + impl_to_primitive_float_to_signed_int! { $T: + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + #[cfg(has_i128)] + fn to_i128 -> i128; + } + + impl_to_primitive_float_to_unsigned_int! { $T: + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + #[cfg(has_i128)] + fn to_u128 -> u128; + } + + impl_to_primitive_float_to_float! { $T: + fn to_f32 -> f32; + fn to_f64 -> f64; + } + } + }; +} + +impl_to_primitive_float!(f32); +impl_to_primitive_float!(f64); + +/// A generic trait for converting a number to a value. +/// +/// A value can be represented by the target type when it lies within +/// the range of scalars supported by the target type. +/// For example, a negative integer cannot be represented by an unsigned +/// integer type, and an `i64` with a very high magnitude might not be +/// convertible to an `i32`. +/// On the other hand, conversions with possible precision loss or truncation +/// are admitted, like an `f32` with a decimal part to an integer type, or +/// even a large `f64` saturating to `f32` infinity. +pub trait FromPrimitive: Sized { + /// Converts an `isize` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_isize(n: isize) -> Option { + n.to_i64().and_then(FromPrimitive::from_i64) + } + + /// Converts an `i8` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_i8(n: i8) -> Option { + FromPrimitive::from_i64(From::from(n)) + } + + /// Converts an `i16` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_i16(n: i16) -> Option { + FromPrimitive::from_i64(From::from(n)) + } + + /// Converts an `i32` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_i32(n: i32) -> Option { + FromPrimitive::from_i64(From::from(n)) + } + + /// Converts an `i64` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + fn from_i64(n: i64) -> Option; + + /// Converts an `i128` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + /// + /// This method is only available with feature `i128` enabled on Rust >= 1.26. + /// + /// The default implementation converts through `from_i64()`. Types implementing + /// this trait should override this method if they can represent a greater range. + #[inline] + #[cfg(has_i128)] + fn from_i128(n: i128) -> Option { + n.to_i64().and_then(FromPrimitive::from_i64) + } + + /// Converts a `usize` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_usize(n: usize) -> Option { + n.to_u64().and_then(FromPrimitive::from_u64) + } + + /// Converts an `u8` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_u8(n: u8) -> Option { + FromPrimitive::from_u64(From::from(n)) + } + + /// Converts an `u16` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_u16(n: u16) -> Option { + FromPrimitive::from_u64(From::from(n)) + } + + /// Converts an `u32` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_u32(n: u32) -> Option { + FromPrimitive::from_u64(From::from(n)) + } + + /// Converts an `u64` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + fn from_u64(n: u64) -> Option; + + /// Converts an `u128` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + /// + /// This method is only available with feature `i128` enabled on Rust >= 1.26. + /// + /// The default implementation converts through `from_u64()`. Types implementing + /// this trait should override this method if they can represent a greater range. + #[inline] + #[cfg(has_i128)] + fn from_u128(n: u128) -> Option { + n.to_u64().and_then(FromPrimitive::from_u64) + } + + /// Converts a `f32` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + #[inline] + fn from_f32(n: f32) -> Option { + FromPrimitive::from_f64(From::from(n)) + } + + /// Converts a `f64` to return an optional value of this type. If the + /// value cannot be represented by this type, then `None` is returned. + /// + /// The default implementation tries to convert through `from_i64()`, and + /// failing that through `from_u64()`. Types implementing this trait should + /// override this method if they can represent a greater range. + #[inline] + fn from_f64(n: f64) -> Option { + match n.to_i64() { + Some(i) => FromPrimitive::from_i64(i), + None => n.to_u64().and_then(FromPrimitive::from_u64), + } + } +} + +macro_rules! impl_from_primitive { + ($T:ty, $to_ty:ident) => { + #[allow(deprecated)] + impl FromPrimitive for $T { + #[inline] + fn from_isize(n: isize) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_i8(n: i8) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_i16(n: i16) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_i32(n: i32) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_i64(n: i64) -> Option<$T> { + n.$to_ty() + } + #[cfg(has_i128)] + #[inline] + fn from_i128(n: i128) -> Option<$T> { + n.$to_ty() + } + + #[inline] + fn from_usize(n: usize) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_u8(n: u8) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_u16(n: u16) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_u32(n: u32) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_u64(n: u64) -> Option<$T> { + n.$to_ty() + } + #[cfg(has_i128)] + #[inline] + fn from_u128(n: u128) -> Option<$T> { + n.$to_ty() + } + + #[inline] + fn from_f32(n: f32) -> Option<$T> { + n.$to_ty() + } + #[inline] + fn from_f64(n: f64) -> Option<$T> { + n.$to_ty() + } + } + }; +} + +impl_from_primitive!(isize, to_isize); +impl_from_primitive!(i8, to_i8); +impl_from_primitive!(i16, to_i16); +impl_from_primitive!(i32, to_i32); +impl_from_primitive!(i64, to_i64); +#[cfg(has_i128)] +impl_from_primitive!(i128, to_i128); +impl_from_primitive!(usize, to_usize); +impl_from_primitive!(u8, to_u8); +impl_from_primitive!(u16, to_u16); +impl_from_primitive!(u32, to_u32); +impl_from_primitive!(u64, to_u64); +#[cfg(has_i128)] +impl_from_primitive!(u128, to_u128); +impl_from_primitive!(f32, to_f32); +impl_from_primitive!(f64, to_f64); + +macro_rules! impl_to_primitive_wrapping { + ($( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(&self) -> Option<$i> { + (self.0).$method() + } + )*} +} + +impl ToPrimitive for Wrapping { + impl_to_primitive_wrapping! { + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + #[cfg(has_i128)] + fn to_i128 -> i128; + + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + #[cfg(has_i128)] + fn to_u128 -> u128; + + fn to_f32 -> f32; + fn to_f64 -> f64; + } +} + +macro_rules! impl_from_primitive_wrapping { + ($( $(#[$cfg:meta])* fn $method:ident ( $i:ident ); )*) => {$( + #[inline] + $(#[$cfg])* + fn $method(n: $i) -> Option { + T::$method(n).map(Wrapping) + } + )*} +} + +impl FromPrimitive for Wrapping { + impl_from_primitive_wrapping! { + fn from_isize(isize); + fn from_i8(i8); + fn from_i16(i16); + fn from_i32(i32); + fn from_i64(i64); + #[cfg(has_i128)] + fn from_i128(i128); + + fn from_usize(usize); + fn from_u8(u8); + fn from_u16(u16); + fn from_u32(u32); + fn from_u64(u64); + #[cfg(has_i128)] + fn from_u128(u128); + + fn from_f32(f32); + fn from_f64(f64); + } +} + +/// Cast from one machine scalar to another. +/// +/// # Examples +/// +/// ``` +/// # use num_traits as num; +/// let twenty: f32 = num::cast(0x14).unwrap(); +/// assert_eq!(twenty, 20f32); +/// ``` +/// +#[inline] +pub fn cast(n: T) -> Option { + NumCast::from(n) +} + +/// An interface for casting between machine scalars. +pub trait NumCast: Sized + ToPrimitive { + /// Creates a number from another value that can be converted into + /// a primitive via the `ToPrimitive` trait. If the source value cannot be + /// represented by the target type, then `None` is returned. + /// + /// A value can be represented by the target type when it lies within + /// the range of scalars supported by the target type. + /// For example, a negative integer cannot be represented by an unsigned + /// integer type, and an `i64` with a very high magnitude might not be + /// convertible to an `i32`. + /// On the other hand, conversions with possible precision loss or truncation + /// are admitted, like an `f32` with a decimal part to an integer type, or + /// even a large `f64` saturating to `f32` infinity. + fn from(n: T) -> Option; +} + +macro_rules! impl_num_cast { + ($T:ty, $conv:ident) => { + impl NumCast for $T { + #[inline] + #[allow(deprecated)] + fn from(n: N) -> Option<$T> { + // `$conv` could be generated using `concat_idents!`, but that + // macro seems to be broken at the moment + n.$conv() + } + } + }; +} + +impl_num_cast!(u8, to_u8); +impl_num_cast!(u16, to_u16); +impl_num_cast!(u32, to_u32); +impl_num_cast!(u64, to_u64); +#[cfg(has_i128)] +impl_num_cast!(u128, to_u128); +impl_num_cast!(usize, to_usize); +impl_num_cast!(i8, to_i8); +impl_num_cast!(i16, to_i16); +impl_num_cast!(i32, to_i32); +impl_num_cast!(i64, to_i64); +#[cfg(has_i128)] +impl_num_cast!(i128, to_i128); +impl_num_cast!(isize, to_isize); +impl_num_cast!(f32, to_f32); +impl_num_cast!(f64, to_f64); + +impl NumCast for Wrapping { + fn from(n: U) -> Option { + T::from(n).map(Wrapping) + } +} + +/// A generic interface for casting between machine scalars with the +/// `as` operator, which admits narrowing and precision loss. +/// Implementers of this trait `AsPrimitive` should behave like a primitive +/// numeric type (e.g. a newtype around another primitive), and the +/// intended conversion must never fail. +/// +/// # Examples +/// +/// ``` +/// # use num_traits::AsPrimitive; +/// let three: i32 = (3.14159265f32).as_(); +/// assert_eq!(three, 3); +/// ``` +/// +/// # Safety +/// +/// **In Rust versions before 1.45.0**, some uses of the `as` operator were not entirely safe. +/// In particular, it was undefined behavior if +/// a truncated floating point value could not fit in the target integer +/// type ([#10184](https://github.com/rust-lang/rust/issues/10184)). +/// +/// ```ignore +/// # use num_traits::AsPrimitive; +/// let x: u8 = (1.04E+17).as_(); // UB +/// ``` +/// +pub trait AsPrimitive: 'static + Copy +where + T: 'static + Copy, +{ + /// Convert a value to another, using the `as` operator. + fn as_(self) -> T; +} + +macro_rules! impl_as_primitive { + (@ $T: ty => $(#[$cfg:meta])* impl $U: ty ) => { + $(#[$cfg])* + impl AsPrimitive<$U> for $T { + #[inline] fn as_(self) -> $U { self as $U } + } + }; + (@ $T: ty => { $( $U: ty ),* } ) => {$( + impl_as_primitive!(@ $T => impl $U); + )*}; + ($T: ty => { $( $U: ty ),* } ) => { + impl_as_primitive!(@ $T => { $( $U ),* }); + impl_as_primitive!(@ $T => { u8, u16, u32, u64, usize }); + impl_as_primitive!(@ $T => #[cfg(has_i128)] impl u128); + impl_as_primitive!(@ $T => { i8, i16, i32, i64, isize }); + impl_as_primitive!(@ $T => #[cfg(has_i128)] impl i128); + }; +} + +impl_as_primitive!(u8 => { char, f32, f64 }); +impl_as_primitive!(i8 => { f32, f64 }); +impl_as_primitive!(u16 => { f32, f64 }); +impl_as_primitive!(i16 => { f32, f64 }); +impl_as_primitive!(u32 => { f32, f64 }); +impl_as_primitive!(i32 => { f32, f64 }); +impl_as_primitive!(u64 => { f32, f64 }); +impl_as_primitive!(i64 => { f32, f64 }); +#[cfg(has_i128)] +impl_as_primitive!(u128 => { f32, f64 }); +#[cfg(has_i128)] +impl_as_primitive!(i128 => { f32, f64 }); +impl_as_primitive!(usize => { f32, f64 }); +impl_as_primitive!(isize => { f32, f64 }); +impl_as_primitive!(f32 => { f32, f64 }); +impl_as_primitive!(f64 => { f32, f64 }); +impl_as_primitive!(char => { char }); +impl_as_primitive!(bool => {}); diff --git a/bash-5.1/vendor/num-traits/src/float.rs b/bash-5.1/vendor/num-traits/src/float.rs new file mode 100644 index 0000000..47bd654 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/float.rs @@ -0,0 +1,2351 @@ +use core::mem; +use core::num::FpCategory; +use core::ops::{Add, Div, Neg}; + +use core::f32; +use core::f64; + +use {Num, NumCast, ToPrimitive}; + +#[cfg(all(not(feature = "std"), feature = "libm"))] +use libm; + +/// Generic trait for floating point numbers that works with `no_std`. +/// +/// This trait implements a subset of the `Float` trait. +pub trait FloatCore: Num + NumCast + Neg + PartialOrd + Copy { + /// Returns positive infinity. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::infinity() == x); + /// } + /// + /// check(f32::INFINITY); + /// check(f64::INFINITY); + /// ``` + fn infinity() -> Self; + + /// Returns negative infinity. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::neg_infinity() == x); + /// } + /// + /// check(f32::NEG_INFINITY); + /// check(f64::NEG_INFINITY); + /// ``` + fn neg_infinity() -> Self; + + /// Returns NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// + /// fn check() { + /// let n = T::nan(); + /// assert!(n != n); + /// } + /// + /// check::(); + /// check::(); + /// ``` + fn nan() -> Self; + + /// Returns `-0.0`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(n: T) { + /// let z = T::neg_zero(); + /// assert!(z.is_zero()); + /// assert!(T::one() / z == n); + /// } + /// + /// check(f32::NEG_INFINITY); + /// check(f64::NEG_INFINITY); + /// ``` + fn neg_zero() -> Self; + + /// Returns the smallest finite value that this type can represent. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::min_value() == x); + /// } + /// + /// check(f32::MIN); + /// check(f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::min_positive_value() == x); + /// } + /// + /// check(f32::MIN_POSITIVE); + /// check(f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns epsilon, a small positive value. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::epsilon() == x); + /// } + /// + /// check(f32::EPSILON); + /// check(f64::EPSILON); + /// ``` + fn epsilon() -> Self; + + /// Returns the largest finite value that this type can represent. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::max_value() == x); + /// } + /// + /// check(f32::MAX); + /// check(f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns `true` if the number is NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_nan() == p); + /// } + /// + /// check(f32::NAN, true); + /// check(f32::INFINITY, false); + /// check(f64::NAN, true); + /// check(0.0f64, false); + /// ``` + #[inline] + fn is_nan(self) -> bool { + self != self + } + + /// Returns `true` if the number is infinite. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_infinite() == p); + /// } + /// + /// check(f32::INFINITY, true); + /// check(f32::NEG_INFINITY, true); + /// check(f32::NAN, false); + /// check(f64::INFINITY, true); + /// check(f64::NEG_INFINITY, true); + /// check(0.0f64, false); + /// ``` + #[inline] + fn is_infinite(self) -> bool { + self == Self::infinity() || self == Self::neg_infinity() + } + + /// Returns `true` if the number is neither infinite or NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_finite() == p); + /// } + /// + /// check(f32::INFINITY, false); + /// check(f32::MAX, true); + /// check(f64::NEG_INFINITY, false); + /// check(f64::MIN_POSITIVE, true); + /// check(f64::NAN, false); + /// ``` + #[inline] + fn is_finite(self) -> bool { + !(self.is_nan() || self.is_infinite()) + } + + /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_normal() == p); + /// } + /// + /// check(f32::INFINITY, false); + /// check(f32::MAX, true); + /// check(f64::NEG_INFINITY, false); + /// check(f64::MIN_POSITIVE, true); + /// check(0.0f64, false); + /// ``` + #[inline] + fn is_normal(self) -> bool { + self.classify() == FpCategory::Normal + } + + /// Returns the floating point category of the number. If only one property + /// is going to be tested, it is generally faster to use the specific + /// predicate instead. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// use std::num::FpCategory; + /// + /// fn check(x: T, c: FpCategory) { + /// assert!(x.classify() == c); + /// } + /// + /// check(f32::INFINITY, FpCategory::Infinite); + /// check(f32::MAX, FpCategory::Normal); + /// check(f64::NAN, FpCategory::Nan); + /// check(f64::MIN_POSITIVE, FpCategory::Normal); + /// check(f64::MIN_POSITIVE / 2.0, FpCategory::Subnormal); + /// check(0.0f64, FpCategory::Zero); + /// ``` + fn classify(self) -> FpCategory; + + /// Returns the largest integer less than or equal to a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.floor() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.9f32, 0.0); + /// check(1.0f32, 1.0); + /// check(1.1f32, 1.0); + /// check(-0.0f64, 0.0); + /// check(-0.9f64, -1.0); + /// check(-1.0f64, -1.0); + /// check(-1.1f64, -2.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn floor(self) -> Self { + let f = self.fract(); + if f.is_nan() || f.is_zero() { + self + } else if self < Self::zero() { + self - f - Self::one() + } else { + self - f + } + } + + /// Returns the smallest integer greater than or equal to a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.ceil() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.9f32, 1.0); + /// check(1.0f32, 1.0); + /// check(1.1f32, 2.0); + /// check(-0.0f64, 0.0); + /// check(-0.9f64, -0.0); + /// check(-1.0f64, -1.0); + /// check(-1.1f64, -1.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn ceil(self) -> Self { + let f = self.fract(); + if f.is_nan() || f.is_zero() { + self + } else if self > Self::zero() { + self - f + Self::one() + } else { + self - f + } + } + + /// Returns the nearest integer to a number. Round half-way cases away from `0.0`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.round() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.4f32, 0.0); + /// check(0.5f32, 1.0); + /// check(0.6f32, 1.0); + /// check(-0.4f64, 0.0); + /// check(-0.5f64, -1.0); + /// check(-0.6f64, -1.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn round(self) -> Self { + let one = Self::one(); + let h = Self::from(0.5).expect("Unable to cast from 0.5"); + let f = self.fract(); + if f.is_nan() || f.is_zero() { + self + } else if self > Self::zero() { + if f < h { + self - f + } else { + self - f + one + } + } else { + if -f < h { + self - f + } else { + self - f - one + } + } + } + + /// Return the integer part of a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.trunc() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.9f32, 0.0); + /// check(1.0f32, 1.0); + /// check(1.1f32, 1.0); + /// check(-0.0f64, 0.0); + /// check(-0.9f64, -0.0); + /// check(-1.0f64, -1.0); + /// check(-1.1f64, -1.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn trunc(self) -> Self { + let f = self.fract(); + if f.is_nan() { + self + } else { + self - f + } + } + + /// Returns the fractional part of a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.fract() == y); + /// } + /// + /// check(f32::MAX, 0.0); + /// check(0.75f32, 0.75); + /// check(1.0f32, 0.0); + /// check(1.25f32, 0.25); + /// check(-0.0f64, 0.0); + /// check(-0.75f64, -0.75); + /// check(-1.0f64, 0.0); + /// check(-1.25f64, -0.25); + /// check(f64::MIN, 0.0); + /// ``` + #[inline] + fn fract(self) -> Self { + if self.is_zero() { + Self::zero() + } else { + self % Self::one() + } + } + + /// Computes the absolute value of `self`. Returns `FloatCore::nan()` if the + /// number is `FloatCore::nan()`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.abs() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(1.0f32, 1.0); + /// check(0.0f64, 0.0); + /// check(-0.0f64, 0.0); + /// check(-1.0f64, 1.0); + /// check(f64::MIN, f64::MAX); + /// ``` + #[inline] + fn abs(self) -> Self { + if self.is_sign_positive() { + return self; + } + if self.is_sign_negative() { + return -self; + } + Self::nan() + } + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `FloatCore::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `FloatCore::neg_infinity()` + /// - `FloatCore::nan()` if the number is `FloatCore::nan()` + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.signum() == y); + /// } + /// + /// check(f32::INFINITY, 1.0); + /// check(3.0f32, 1.0); + /// check(0.0f32, 1.0); + /// check(-0.0f64, -1.0); + /// check(-3.0f64, -1.0); + /// check(f64::MIN, -1.0); + /// ``` + #[inline] + fn signum(self) -> Self { + if self.is_nan() { + Self::nan() + } else if self.is_sign_negative() { + -Self::one() + } else { + Self::one() + } + } + + /// Returns `true` if `self` is positive, including `+0.0` and + /// `FloatCore::infinity()`, and since Rust 1.20 also + /// `FloatCore::nan()`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_sign_positive() == p); + /// } + /// + /// check(f32::INFINITY, true); + /// check(f32::MAX, true); + /// check(0.0f32, true); + /// check(-0.0f64, false); + /// check(f64::NEG_INFINITY, false); + /// check(f64::MIN_POSITIVE, true); + /// check(-f64::NAN, false); + /// ``` + #[inline] + fn is_sign_positive(self) -> bool { + !self.is_sign_negative() + } + + /// Returns `true` if `self` is negative, including `-0.0` and + /// `FloatCore::neg_infinity()`, and since Rust 1.20 also + /// `-FloatCore::nan()`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_sign_negative() == p); + /// } + /// + /// check(f32::INFINITY, false); + /// check(f32::MAX, false); + /// check(0.0f32, false); + /// check(-0.0f64, true); + /// check(f64::NEG_INFINITY, true); + /// check(f64::MIN_POSITIVE, false); + /// check(f64::NAN, false); + /// ``` + #[inline] + fn is_sign_negative(self) -> bool { + let (_, _, sign) = self.integer_decode(); + sign < 0 + } + + /// Returns the minimum of the two numbers. + /// + /// If one of the arguments is NaN, then the other argument is returned. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T, min: T) { + /// assert!(x.min(y) == min); + /// } + /// + /// check(1.0f32, 2.0, 1.0); + /// check(f32::NAN, 2.0, 2.0); + /// check(1.0f64, -2.0, -2.0); + /// check(1.0f64, f64::NAN, 1.0); + /// ``` + #[inline] + fn min(self, other: Self) -> Self { + if self.is_nan() { + return other; + } + if other.is_nan() { + return self; + } + if self < other { + self + } else { + other + } + } + + /// Returns the maximum of the two numbers. + /// + /// If one of the arguments is NaN, then the other argument is returned. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T, max: T) { + /// assert!(x.max(y) == max); + /// } + /// + /// check(1.0f32, 2.0, 2.0); + /// check(1.0f32, f32::NAN, 1.0); + /// check(-1.0f64, 2.0, 2.0); + /// check(-1.0f64, f64::NAN, -1.0); + /// ``` + #[inline] + fn max(self, other: Self) -> Self { + if self.is_nan() { + return other; + } + if other.is_nan() { + return self; + } + if self > other { + self + } else { + other + } + } + + /// Returns the reciprocal (multiplicative inverse) of the number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.recip() == y); + /// assert!(y.recip() == x); + /// } + /// + /// check(f32::INFINITY, 0.0); + /// check(2.0f32, 0.5); + /// check(-0.25f64, -4.0); + /// check(-0.0f64, f64::NEG_INFINITY); + /// ``` + #[inline] + fn recip(self) -> Self { + Self::one() / self + } + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// + /// fn check(x: T, exp: i32, powi: T) { + /// assert!(x.powi(exp) == powi); + /// } + /// + /// check(9.0f32, 2, 81.0); + /// check(1.0f32, -2, 1.0); + /// check(10.0f64, 20, 1e20); + /// check(4.0f64, -2, 0.0625); + /// check(-1.0f64, std::i32::MIN, 1.0); + /// ``` + #[inline] + fn powi(mut self, mut exp: i32) -> Self { + if exp < 0 { + exp = exp.wrapping_neg(); + self = self.recip(); + } + // It should always be possible to convert a positive `i32` to a `usize`. + // Note, `i32::MIN` will wrap and still be negative, so we need to convert + // to `u32` without sign-extension before growing to `usize`. + super::pow(self, (exp as u32).to_usize().unwrap()) + } + + /// Converts to degrees, assuming the number is in radians. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(rad: T, deg: T) { + /// assert!(rad.to_degrees() == deg); + /// } + /// + /// check(0.0f32, 0.0); + /// check(f32::consts::PI, 180.0); + /// check(f64::consts::FRAC_PI_4, 45.0); + /// check(f64::INFINITY, f64::INFINITY); + /// ``` + fn to_degrees(self) -> Self; + + /// Converts to radians, assuming the number is in degrees. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(deg: T, rad: T) { + /// assert!(deg.to_radians() == rad); + /// } + /// + /// check(0.0f32, 0.0); + /// check(180.0, f32::consts::PI); + /// check(45.0, f64::consts::FRAC_PI_4); + /// check(f64::INFINITY, f64::INFINITY); + /// ``` + fn to_radians(self) -> Self; + + /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. + /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, m: u64, e: i16, s:i8) { + /// let (mantissa, exponent, sign) = x.integer_decode(); + /// assert_eq!(mantissa, m); + /// assert_eq!(exponent, e); + /// assert_eq!(sign, s); + /// } + /// + /// check(2.0f32, 1 << 23, -22, 1); + /// check(-2.0f32, 1 << 23, -22, -1); + /// check(f32::INFINITY, 1 << 23, 105, 1); + /// check(f64::NEG_INFINITY, 1 << 52, 972, -1); + /// ``` + fn integer_decode(self) -> (u64, i16, i8); +} + +impl FloatCore for f32 { + constant! { + infinity() -> f32::INFINITY; + neg_infinity() -> f32::NEG_INFINITY; + nan() -> f32::NAN; + neg_zero() -> -0.0; + min_value() -> f32::MIN; + min_positive_value() -> f32::MIN_POSITIVE; + epsilon() -> f32::EPSILON; + max_value() -> f32::MAX; + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + integer_decode_f32(self) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn classify(self) -> FpCategory { + const EXP_MASK: u32 = 0x7f800000; + const MAN_MASK: u32 = 0x007fffff; + + // Safety: this identical to the implementation of f32::to_bits(), + // which is only available starting at Rust 1.20 + let bits: u32 = unsafe { mem::transmute(self) }; + match (bits & MAN_MASK, bits & EXP_MASK) { + (0, 0) => FpCategory::Zero, + (_, 0) => FpCategory::Subnormal, + (0, EXP_MASK) => FpCategory::Infinite, + (_, EXP_MASK) => FpCategory::Nan, + _ => FpCategory::Normal, + } + } + + #[inline] + #[cfg(not(feature = "std"))] + fn is_sign_negative(self) -> bool { + const SIGN_MASK: u32 = 0x80000000; + + // Safety: this identical to the implementation of f32::to_bits(), + // which is only available starting at Rust 1.20 + let bits: u32 = unsafe { mem::transmute(self) }; + bits & SIGN_MASK != 0 + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_degrees(self) -> Self { + // Use a constant for better precision. + const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32; + self * PIS_IN_180 + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_radians(self) -> Self { + self * (f32::consts::PI / 180.0) + } + + #[cfg(feature = "std")] + forward! { + Self::is_nan(self) -> bool; + Self::is_infinite(self) -> bool; + Self::is_finite(self) -> bool; + Self::is_normal(self) -> bool; + Self::classify(self) -> FpCategory; + Self::floor(self) -> Self; + Self::ceil(self) -> Self; + Self::round(self) -> Self; + Self::trunc(self) -> Self; + Self::fract(self) -> Self; + Self::abs(self) -> Self; + Self::signum(self) -> Self; + Self::is_sign_positive(self) -> bool; + Self::is_sign_negative(self) -> bool; + Self::min(self, other: Self) -> Self; + Self::max(self, other: Self) -> Self; + Self::recip(self) -> Self; + Self::powi(self, n: i32) -> Self; + Self::to_degrees(self) -> Self; + Self::to_radians(self) -> Self; + } + + #[cfg(all(not(feature = "std"), feature = "libm"))] + forward! { + libm::floorf as floor(self) -> Self; + libm::ceilf as ceil(self) -> Self; + libm::roundf as round(self) -> Self; + libm::truncf as trunc(self) -> Self; + libm::fabsf as abs(self) -> Self; + libm::fminf as min(self, other: Self) -> Self; + libm::fmaxf as max(self, other: Self) -> Self; + } + + #[cfg(all(not(feature = "std"), feature = "libm"))] + #[inline] + fn fract(self) -> Self { + self - libm::truncf(self) + } +} + +impl FloatCore for f64 { + constant! { + infinity() -> f64::INFINITY; + neg_infinity() -> f64::NEG_INFINITY; + nan() -> f64::NAN; + neg_zero() -> -0.0; + min_value() -> f64::MIN; + min_positive_value() -> f64::MIN_POSITIVE; + epsilon() -> f64::EPSILON; + max_value() -> f64::MAX; + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + integer_decode_f64(self) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn classify(self) -> FpCategory { + const EXP_MASK: u64 = 0x7ff0000000000000; + const MAN_MASK: u64 = 0x000fffffffffffff; + + // Safety: this identical to the implementation of f64::to_bits(), + // which is only available starting at Rust 1.20 + let bits: u64 = unsafe { mem::transmute(self) }; + match (bits & MAN_MASK, bits & EXP_MASK) { + (0, 0) => FpCategory::Zero, + (_, 0) => FpCategory::Subnormal, + (0, EXP_MASK) => FpCategory::Infinite, + (_, EXP_MASK) => FpCategory::Nan, + _ => FpCategory::Normal, + } + } + + #[inline] + #[cfg(not(feature = "std"))] + fn is_sign_negative(self) -> bool { + const SIGN_MASK: u64 = 0x8000000000000000; + + // Safety: this identical to the implementation of f64::to_bits(), + // which is only available starting at Rust 1.20 + let bits: u64 = unsafe { mem::transmute(self) }; + bits & SIGN_MASK != 0 + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_degrees(self) -> Self { + // The division here is correctly rounded with respect to the true + // value of 180/π. (This differs from f32, where a constant must be + // used to ensure a correctly rounded result.) + self * (180.0 / f64::consts::PI) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_radians(self) -> Self { + self * (f64::consts::PI / 180.0) + } + + #[cfg(feature = "std")] + forward! { + Self::is_nan(self) -> bool; + Self::is_infinite(self) -> bool; + Self::is_finite(self) -> bool; + Self::is_normal(self) -> bool; + Self::classify(self) -> FpCategory; + Self::floor(self) -> Self; + Self::ceil(self) -> Self; + Self::round(self) -> Self; + Self::trunc(self) -> Self; + Self::fract(self) -> Self; + Self::abs(self) -> Self; + Self::signum(self) -> Self; + Self::is_sign_positive(self) -> bool; + Self::is_sign_negative(self) -> bool; + Self::min(self, other: Self) -> Self; + Self::max(self, other: Self) -> Self; + Self::recip(self) -> Self; + Self::powi(self, n: i32) -> Self; + Self::to_degrees(self) -> Self; + Self::to_radians(self) -> Self; + } + + #[cfg(all(not(feature = "std"), feature = "libm"))] + forward! { + libm::floor as floor(self) -> Self; + libm::ceil as ceil(self) -> Self; + libm::round as round(self) -> Self; + libm::trunc as trunc(self) -> Self; + libm::fabs as abs(self) -> Self; + libm::fmin as min(self, other: Self) -> Self; + libm::fmax as max(self, other: Self) -> Self; + } + + #[cfg(all(not(feature = "std"), feature = "libm"))] + #[inline] + fn fract(self) -> Self { + self - libm::trunc(self) + } +} + +// FIXME: these doctests aren't actually helpful, because they're using and +// testing the inherent methods directly, not going through `Float`. + +/// Generic trait for floating point numbers +/// +/// This trait is only available with the `std` feature, or with the `libm` feature otherwise. +#[cfg(any(feature = "std", feature = "libm"))] +pub trait Float: Num + Copy + NumCast + PartialOrd + Neg { + /// Returns the `NaN` value. + /// + /// ``` + /// use num_traits::Float; + /// + /// let nan: f32 = Float::nan(); + /// + /// assert!(nan.is_nan()); + /// ``` + fn nan() -> Self; + /// Returns the infinite value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let infinity: f32 = Float::infinity(); + /// + /// assert!(infinity.is_infinite()); + /// assert!(!infinity.is_finite()); + /// assert!(infinity > f32::MAX); + /// ``` + fn infinity() -> Self; + /// Returns the negative infinite value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let neg_infinity: f32 = Float::neg_infinity(); + /// + /// assert!(neg_infinity.is_infinite()); + /// assert!(!neg_infinity.is_finite()); + /// assert!(neg_infinity < f32::MIN); + /// ``` + fn neg_infinity() -> Self; + /// Returns `-0.0`. + /// + /// ``` + /// use num_traits::{Zero, Float}; + /// + /// let inf: f32 = Float::infinity(); + /// let zero: f32 = Zero::zero(); + /// let neg_zero: f32 = Float::neg_zero(); + /// + /// assert_eq!(zero, neg_zero); + /// assert_eq!(7.0f32/inf, zero); + /// assert_eq!(zero * 10.0, zero); + /// ``` + fn neg_zero() -> Self; + + /// Returns the smallest finite value that this type can represent. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::min_value(); + /// + /// assert_eq!(x, f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::min_positive_value(); + /// + /// assert_eq!(x, f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns epsilon, a small positive value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::epsilon(); + /// + /// assert_eq!(x, f64::EPSILON); + /// ``` + /// + /// # Panics + /// + /// The default implementation will panic if `f32::EPSILON` cannot + /// be cast to `Self`. + fn epsilon() -> Self { + Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON") + } + + /// Returns the largest finite value that this type can represent. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::max_value(); + /// assert_eq!(x, f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns `true` if this value is `NaN` and false otherwise. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let nan = f64::NAN; + /// let f = 7.0; + /// + /// assert!(nan.is_nan()); + /// assert!(!f.is_nan()); + /// ``` + fn is_nan(self) -> bool; + + /// Returns `true` if this value is positive infinity or negative infinity and + /// false otherwise. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let f = 7.0f32; + /// let inf: f32 = Float::infinity(); + /// let neg_inf: f32 = Float::neg_infinity(); + /// let nan: f32 = f32::NAN; + /// + /// assert!(!f.is_infinite()); + /// assert!(!nan.is_infinite()); + /// + /// assert!(inf.is_infinite()); + /// assert!(neg_inf.is_infinite()); + /// ``` + fn is_infinite(self) -> bool; + + /// Returns `true` if this number is neither infinite nor `NaN`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let f = 7.0f32; + /// let inf: f32 = Float::infinity(); + /// let neg_inf: f32 = Float::neg_infinity(); + /// let nan: f32 = f32::NAN; + /// + /// assert!(f.is_finite()); + /// + /// assert!(!nan.is_finite()); + /// assert!(!inf.is_finite()); + /// assert!(!neg_inf.is_finite()); + /// ``` + fn is_finite(self) -> bool; + + /// Returns `true` if the number is neither zero, infinite, + /// [subnormal][subnormal], or `NaN`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 + /// let max = f32::MAX; + /// let lower_than_min = 1.0e-40_f32; + /// let zero = 0.0f32; + /// + /// assert!(min.is_normal()); + /// assert!(max.is_normal()); + /// + /// assert!(!zero.is_normal()); + /// assert!(!f32::NAN.is_normal()); + /// assert!(!f32::INFINITY.is_normal()); + /// // Values between `0` and `min` are Subnormal. + /// assert!(!lower_than_min.is_normal()); + /// ``` + /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number + fn is_normal(self) -> bool; + + /// Returns the floating point category of the number. If only one property + /// is going to be tested, it is generally faster to use the specific + /// predicate instead. + /// + /// ``` + /// use num_traits::Float; + /// use std::num::FpCategory; + /// use std::f32; + /// + /// let num = 12.4f32; + /// let inf = f32::INFINITY; + /// + /// assert_eq!(num.classify(), FpCategory::Normal); + /// assert_eq!(inf.classify(), FpCategory::Infinite); + /// ``` + fn classify(self) -> FpCategory; + + /// Returns the largest integer less than or equal to a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.99; + /// let g = 3.0; + /// + /// assert_eq!(f.floor(), 3.0); + /// assert_eq!(g.floor(), 3.0); + /// ``` + fn floor(self) -> Self; + + /// Returns the smallest integer greater than or equal to a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.01; + /// let g = 4.0; + /// + /// assert_eq!(f.ceil(), 4.0); + /// assert_eq!(g.ceil(), 4.0); + /// ``` + fn ceil(self) -> Self; + + /// Returns the nearest integer to a number. Round half-way cases away from + /// `0.0`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.3; + /// let g = -3.3; + /// + /// assert_eq!(f.round(), 3.0); + /// assert_eq!(g.round(), -3.0); + /// ``` + fn round(self) -> Self; + + /// Return the integer part of a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.3; + /// let g = -3.7; + /// + /// assert_eq!(f.trunc(), 3.0); + /// assert_eq!(g.trunc(), -3.0); + /// ``` + fn trunc(self) -> Self; + + /// Returns the fractional part of a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 3.5; + /// let y = -3.5; + /// let abs_difference_x = (x.fract() - 0.5).abs(); + /// let abs_difference_y = (y.fract() - (-0.5)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn fract(self) -> Self; + + /// Computes the absolute value of `self`. Returns `Float::nan()` if the + /// number is `Float::nan()`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = 3.5; + /// let y = -3.5; + /// + /// let abs_difference_x = (x.abs() - x).abs(); + /// let abs_difference_y = (y.abs() - (-y)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// + /// assert!(f64::NAN.abs().is_nan()); + /// ``` + fn abs(self) -> Self; + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` + /// - `Float::nan()` if the number is `Float::nan()` + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let f = 3.5; + /// + /// assert_eq!(f.signum(), 1.0); + /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); + /// + /// assert!(f64::NAN.signum().is_nan()); + /// ``` + fn signum(self) -> Self; + + /// Returns `true` if `self` is positive, including `+0.0`, + /// `Float::infinity()`, and since Rust 1.20 also `Float::nan()`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let neg_nan: f64 = -f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(f.is_sign_positive()); + /// assert!(!g.is_sign_positive()); + /// assert!(!neg_nan.is_sign_positive()); + /// ``` + fn is_sign_positive(self) -> bool; + + /// Returns `true` if `self` is negative, including `-0.0`, + /// `Float::neg_infinity()`, and since Rust 1.20 also `-Float::nan()`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let nan: f64 = f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(!f.is_sign_negative()); + /// assert!(g.is_sign_negative()); + /// assert!(!nan.is_sign_negative()); + /// ``` + fn is_sign_negative(self) -> bool; + + /// Fused multiply-add. Computes `(self * a) + b` with only one rounding + /// error, yielding a more accurate result than an unfused multiply-add. + /// + /// Using `mul_add` can be more performant than an unfused multiply-add if + /// the target architecture has a dedicated `fma` CPU instruction. + /// + /// ``` + /// use num_traits::Float; + /// + /// let m = 10.0; + /// let x = 4.0; + /// let b = 60.0; + /// + /// // 100.0 + /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn mul_add(self, a: Self, b: Self) -> Self; + /// Take the reciprocal (inverse) of a number, `1/x`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.recip() - (1.0/x)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn recip(self) -> Self; + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.powi(2) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powi(self, n: i32) -> Self; + + /// Raise a number to a floating point power. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.powf(2.0) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powf(self, n: Self) -> Self; + + /// Take the square root of a number. + /// + /// Returns NaN if `self` is a negative number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let positive = 4.0; + /// let negative = -4.0; + /// + /// let abs_difference = (positive.sqrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// assert!(negative.sqrt().is_nan()); + /// ``` + fn sqrt(self) -> Self; + + /// Returns `e^(self)`, (the exponential function). + /// + /// ``` + /// use num_traits::Float; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp(self) -> Self; + + /// Returns `2^(self)`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 2.0; + /// + /// // 2^2 - 4 == 0 + /// let abs_difference = (f.exp2() - 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp2(self) -> Self; + + /// Returns the natural logarithm of the number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln(self) -> Self; + + /// Returns the logarithm of the number with respect to an arbitrary base. + /// + /// ``` + /// use num_traits::Float; + /// + /// let ten = 10.0; + /// let two = 2.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); + /// + /// // log2(2) - 1 == 0 + /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); + /// + /// assert!(abs_difference_10 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn log(self, base: Self) -> Self; + + /// Returns the base 2 logarithm of the number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let two = 2.0; + /// + /// // log2(2) - 1 == 0 + /// let abs_difference = (two.log2() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log2(self) -> Self; + + /// Returns the base 10 logarithm of the number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let ten = 10.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference = (ten.log10() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log10(self) -> Self; + + /// Converts radians to degrees. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = consts::PI; + /// + /// let abs_difference = (angle.to_degrees() - 180.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + #[inline] + fn to_degrees(self) -> Self { + let halfpi = Self::zero().acos(); + let ninety = Self::from(90u8).unwrap(); + self * ninety / halfpi + } + + /// Converts degrees to radians. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = 180.0_f64; + /// + /// let abs_difference = (angle.to_radians() - consts::PI).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + #[inline] + fn to_radians(self) -> Self { + let halfpi = Self::zero().acos(); + let ninety = Self::from(90u8).unwrap(); + self * halfpi / ninety + } + + /// Returns the maximum of the two numbers. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.max(y), y); + /// ``` + fn max(self, other: Self) -> Self; + + /// Returns the minimum of the two numbers. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.min(y), x); + /// ``` + fn min(self, other: Self) -> Self; + + /// The positive difference of two numbers. + /// + /// * If `self <= other`: `0:0` + /// * Else: `self - other` + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 3.0; + /// let y = -3.0; + /// + /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); + /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn abs_sub(self, other: Self) -> Self; + + /// Take the cubic root of a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 8.0; + /// + /// // x^(1/3) - 2 == 0 + /// let abs_difference = (x.cbrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cbrt(self) -> Self; + + /// Calculate the length of the hypotenuse of a right-angle triangle given + /// legs of length `x` and `y`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let y = 3.0; + /// + /// // sqrt(x^2 + y^2) + /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn hypot(self, other: Self) -> Self; + + /// Computes the sine of a number (in radians). + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/2.0; + /// + /// let abs_difference = (x.sin() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sin(self) -> Self; + + /// Computes the cosine of a number (in radians). + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = 2.0*f64::consts::PI; + /// + /// let abs_difference = (x.cos() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cos(self) -> Self; + + /// Computes the tangent of a number (in radians). + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let abs_difference = (x.tan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-14); + /// ``` + fn tan(self) -> Self; + + /// Computes the arcsine of a number. Return value is in radians in + /// the range [-pi/2, pi/2] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let f = f64::consts::PI / 2.0; + /// + /// // asin(sin(pi/2)) + /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn asin(self) -> Self; + + /// Computes the arccosine of a number. Return value is in radians in + /// the range [0, pi] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let f = f64::consts::PI / 4.0; + /// + /// // acos(cos(pi/4)) + /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn acos(self) -> Self; + + /// Computes the arctangent of a number. Return value is in radians in the + /// range [-pi/2, pi/2]; + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 1.0; + /// + /// // atan(tan(1)) + /// let abs_difference = (f.tan().atan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn atan(self) -> Self; + + /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). + /// + /// * `x = 0`, `y = 0`: `0` + /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` + /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` + /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let pi = f64::consts::PI; + /// // All angles from horizontal right (+x) + /// // 45 deg counter-clockwise + /// let x1 = 3.0; + /// let y1 = -3.0; + /// + /// // 135 deg clockwise + /// let x2 = -3.0; + /// let y2 = 3.0; + /// + /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); + /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); + /// + /// assert!(abs_difference_1 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn atan2(self, other: Self) -> Self; + + /// Simultaneously computes the sine and cosine of the number, `x`. Returns + /// `(sin(x), cos(x))`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let f = x.sin_cos(); + /// + /// let abs_difference_0 = (f.0 - x.sin()).abs(); + /// let abs_difference_1 = (f.1 - x.cos()).abs(); + /// + /// assert!(abs_difference_0 < 1e-10); + /// assert!(abs_difference_0 < 1e-10); + /// ``` + fn sin_cos(self) -> (Self, Self); + + /// Returns `e^(self) - 1` in a way that is accurate even if the + /// number is close to zero. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 7.0; + /// + /// // e^(ln(7)) - 1 + /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp_m1(self) -> Self; + + /// Returns `ln(1+n)` (natural logarithm) more accurately than if + /// the operations were performed separately. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::E - 1.0; + /// + /// // ln(1 + (e - 1)) == ln(e) == 1 + /// let abs_difference = (x.ln_1p() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln_1p(self) -> Self; + + /// Hyperbolic sine function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.sinh(); + /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` + /// let g = (e*e - 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sinh(self) -> Self; + + /// Hyperbolic cosine function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// let f = x.cosh(); + /// // Solving cosh() at 1 gives this result + /// let g = (e*e + 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// // Same result + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn cosh(self) -> Self; + + /// Hyperbolic tangent function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.tanh(); + /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` + /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn tanh(self) -> Self; + + /// Inverse hyperbolic sine function. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let f = x.sinh().asinh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn asinh(self) -> Self; + + /// Inverse hyperbolic cosine function. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let f = x.cosh().acosh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn acosh(self) -> Self; + + /// Inverse hyperbolic tangent function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let f = e.tanh().atanh(); + /// + /// let abs_difference = (f - e).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn atanh(self) -> Self; + + /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. + /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let num = 2.0f32; + /// + /// // (8388608, -22, 1) + /// let (mantissa, exponent, sign) = Float::integer_decode(num); + /// let sign_f = sign as f32; + /// let mantissa_f = mantissa as f32; + /// let exponent_f = num.powf(exponent as f32); + /// + /// // 1 * 8388608 * 2^(-22) == 2 + /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn integer_decode(self) -> (u64, i16, i8); + + /// Returns a number composed of the magnitude of `self` and the sign of + /// `sign`. + /// + /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise + /// equal to `-self`. If `self` is a `NAN`, then a `NAN` with the sign of + /// `sign` is returned. + /// + /// # Examples + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.5_f32; + /// + /// assert_eq!(f.copysign(0.42), 3.5_f32); + /// assert_eq!(f.copysign(-0.42), -3.5_f32); + /// assert_eq!((-f).copysign(0.42), 3.5_f32); + /// assert_eq!((-f).copysign(-0.42), -3.5_f32); + /// + /// assert!(f32::nan().copysign(1.0).is_nan()); + /// ``` + fn copysign(self, sign: Self) -> Self { + if self.is_sign_negative() == sign.is_sign_negative() { + self + } else { + self.neg() + } + } +} + +#[cfg(feature = "std")] +macro_rules! float_impl_std { + ($T:ident $decode:ident) => { + impl Float for $T { + constant! { + nan() -> $T::NAN; + infinity() -> $T::INFINITY; + neg_infinity() -> $T::NEG_INFINITY; + neg_zero() -> -0.0; + min_value() -> $T::MIN; + min_positive_value() -> $T::MIN_POSITIVE; + epsilon() -> $T::EPSILON; + max_value() -> $T::MAX; + } + + #[inline] + #[allow(deprecated)] + fn abs_sub(self, other: Self) -> Self { + <$T>::abs_sub(self, other) + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + $decode(self) + } + + forward! { + Self::is_nan(self) -> bool; + Self::is_infinite(self) -> bool; + Self::is_finite(self) -> bool; + Self::is_normal(self) -> bool; + Self::classify(self) -> FpCategory; + Self::floor(self) -> Self; + Self::ceil(self) -> Self; + Self::round(self) -> Self; + Self::trunc(self) -> Self; + Self::fract(self) -> Self; + Self::abs(self) -> Self; + Self::signum(self) -> Self; + Self::is_sign_positive(self) -> bool; + Self::is_sign_negative(self) -> bool; + Self::mul_add(self, a: Self, b: Self) -> Self; + Self::recip(self) -> Self; + Self::powi(self, n: i32) -> Self; + Self::powf(self, n: Self) -> Self; + Self::sqrt(self) -> Self; + Self::exp(self) -> Self; + Self::exp2(self) -> Self; + Self::ln(self) -> Self; + Self::log(self, base: Self) -> Self; + Self::log2(self) -> Self; + Self::log10(self) -> Self; + Self::to_degrees(self) -> Self; + Self::to_radians(self) -> Self; + Self::max(self, other: Self) -> Self; + Self::min(self, other: Self) -> Self; + Self::cbrt(self) -> Self; + Self::hypot(self, other: Self) -> Self; + Self::sin(self) -> Self; + Self::cos(self) -> Self; + Self::tan(self) -> Self; + Self::asin(self) -> Self; + Self::acos(self) -> Self; + Self::atan(self) -> Self; + Self::atan2(self, other: Self) -> Self; + Self::sin_cos(self) -> (Self, Self); + Self::exp_m1(self) -> Self; + Self::ln_1p(self) -> Self; + Self::sinh(self) -> Self; + Self::cosh(self) -> Self; + Self::tanh(self) -> Self; + Self::asinh(self) -> Self; + Self::acosh(self) -> Self; + Self::atanh(self) -> Self; + } + + #[cfg(has_copysign)] + #[inline] + fn copysign(self, sign: Self) -> Self { + Self::copysign(self, sign) + } + } + }; +} + +#[cfg(all(not(feature = "std"), feature = "libm"))] +macro_rules! float_impl_libm { + ($T:ident $decode:ident) => { + constant! { + nan() -> $T::NAN; + infinity() -> $T::INFINITY; + neg_infinity() -> $T::NEG_INFINITY; + neg_zero() -> -0.0; + min_value() -> $T::MIN; + min_positive_value() -> $T::MIN_POSITIVE; + epsilon() -> $T::EPSILON; + max_value() -> $T::MAX; + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + $decode(self) + } + + #[inline] + fn fract(self) -> Self { + self - Float::trunc(self) + } + + #[inline] + fn log(self, base: Self) -> Self { + self.ln() / base.ln() + } + + forward! { + FloatCore::is_nan(self) -> bool; + FloatCore::is_infinite(self) -> bool; + FloatCore::is_finite(self) -> bool; + FloatCore::is_normal(self) -> bool; + FloatCore::classify(self) -> FpCategory; + FloatCore::signum(self) -> Self; + FloatCore::is_sign_positive(self) -> bool; + FloatCore::is_sign_negative(self) -> bool; + FloatCore::recip(self) -> Self; + FloatCore::powi(self, n: i32) -> Self; + FloatCore::to_degrees(self) -> Self; + FloatCore::to_radians(self) -> Self; + } + }; +} + +fn integer_decode_f32(f: f32) -> (u64, i16, i8) { + // Safety: this identical to the implementation of f32::to_bits(), + // which is only available starting at Rust 1.20 + let bits: u32 = unsafe { mem::transmute(f) }; + let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 }; + let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; + let mantissa = if exponent == 0 { + (bits & 0x7fffff) << 1 + } else { + (bits & 0x7fffff) | 0x800000 + }; + // Exponent bias + mantissa shift + exponent -= 127 + 23; + (mantissa as u64, exponent, sign) +} + +fn integer_decode_f64(f: f64) -> (u64, i16, i8) { + // Safety: this identical to the implementation of f64::to_bits(), + // which is only available starting at Rust 1.20 + let bits: u64 = unsafe { mem::transmute(f) }; + let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; + let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; + let mantissa = if exponent == 0 { + (bits & 0xfffffffffffff) << 1 + } else { + (bits & 0xfffffffffffff) | 0x10000000000000 + }; + // Exponent bias + mantissa shift + exponent -= 1023 + 52; + (mantissa, exponent, sign) +} + +#[cfg(feature = "std")] +float_impl_std!(f32 integer_decode_f32); +#[cfg(feature = "std")] +float_impl_std!(f64 integer_decode_f64); + +#[cfg(all(not(feature = "std"), feature = "libm"))] +impl Float for f32 { + float_impl_libm!(f32 integer_decode_f32); + + #[inline] + #[allow(deprecated)] + fn abs_sub(self, other: Self) -> Self { + libm::fdimf(self, other) + } + + forward! { + libm::floorf as floor(self) -> Self; + libm::ceilf as ceil(self) -> Self; + libm::roundf as round(self) -> Self; + libm::truncf as trunc(self) -> Self; + libm::fabsf as abs(self) -> Self; + libm::fmaf as mul_add(self, a: Self, b: Self) -> Self; + libm::powf as powf(self, n: Self) -> Self; + libm::sqrtf as sqrt(self) -> Self; + libm::expf as exp(self) -> Self; + libm::exp2f as exp2(self) -> Self; + libm::logf as ln(self) -> Self; + libm::log2f as log2(self) -> Self; + libm::log10f as log10(self) -> Self; + libm::cbrtf as cbrt(self) -> Self; + libm::hypotf as hypot(self, other: Self) -> Self; + libm::sinf as sin(self) -> Self; + libm::cosf as cos(self) -> Self; + libm::tanf as tan(self) -> Self; + libm::asinf as asin(self) -> Self; + libm::acosf as acos(self) -> Self; + libm::atanf as atan(self) -> Self; + libm::atan2f as atan2(self, other: Self) -> Self; + libm::sincosf as sin_cos(self) -> (Self, Self); + libm::expm1f as exp_m1(self) -> Self; + libm::log1pf as ln_1p(self) -> Self; + libm::sinhf as sinh(self) -> Self; + libm::coshf as cosh(self) -> Self; + libm::tanhf as tanh(self) -> Self; + libm::asinhf as asinh(self) -> Self; + libm::acoshf as acosh(self) -> Self; + libm::atanhf as atanh(self) -> Self; + libm::fmaxf as max(self, other: Self) -> Self; + libm::fminf as min(self, other: Self) -> Self; + libm::copysignf as copysign(self, other: Self) -> Self; + } +} + +#[cfg(all(not(feature = "std"), feature = "libm"))] +impl Float for f64 { + float_impl_libm!(f64 integer_decode_f64); + + #[inline] + #[allow(deprecated)] + fn abs_sub(self, other: Self) -> Self { + libm::fdim(self, other) + } + + forward! { + libm::floor as floor(self) -> Self; + libm::ceil as ceil(self) -> Self; + libm::round as round(self) -> Self; + libm::trunc as trunc(self) -> Self; + libm::fabs as abs(self) -> Self; + libm::fma as mul_add(self, a: Self, b: Self) -> Self; + libm::pow as powf(self, n: Self) -> Self; + libm::sqrt as sqrt(self) -> Self; + libm::exp as exp(self) -> Self; + libm::exp2 as exp2(self) -> Self; + libm::log as ln(self) -> Self; + libm::log2 as log2(self) -> Self; + libm::log10 as log10(self) -> Self; + libm::cbrt as cbrt(self) -> Self; + libm::hypot as hypot(self, other: Self) -> Self; + libm::sin as sin(self) -> Self; + libm::cos as cos(self) -> Self; + libm::tan as tan(self) -> Self; + libm::asin as asin(self) -> Self; + libm::acos as acos(self) -> Self; + libm::atan as atan(self) -> Self; + libm::atan2 as atan2(self, other: Self) -> Self; + libm::sincos as sin_cos(self) -> (Self, Self); + libm::expm1 as exp_m1(self) -> Self; + libm::log1p as ln_1p(self) -> Self; + libm::sinh as sinh(self) -> Self; + libm::cosh as cosh(self) -> Self; + libm::tanh as tanh(self) -> Self; + libm::asinh as asinh(self) -> Self; + libm::acosh as acosh(self) -> Self; + libm::atanh as atanh(self) -> Self; + libm::fmax as max(self, other: Self) -> Self; + libm::fmin as min(self, other: Self) -> Self; + libm::copysign as copysign(self, sign: Self) -> Self; + } +} + +macro_rules! float_const_impl { + ($(#[$doc:meta] $constant:ident,)+) => ( + #[allow(non_snake_case)] + pub trait FloatConst { + $(#[$doc] fn $constant() -> Self;)+ + #[doc = "Return the full circle constant `τ`."] + #[inline] + fn TAU() -> Self where Self: Sized + Add { + Self::PI() + Self::PI() + } + #[doc = "Return `log10(2.0)`."] + #[inline] + fn LOG10_2() -> Self where Self: Sized + Div { + Self::LN_2() / Self::LN_10() + } + #[doc = "Return `log2(10.0)`."] + #[inline] + fn LOG2_10() -> Self where Self: Sized + Div { + Self::LN_10() / Self::LN_2() + } + } + float_const_impl! { @float f32, $($constant,)+ } + float_const_impl! { @float f64, $($constant,)+ } + ); + (@float $T:ident, $($constant:ident,)+) => ( + impl FloatConst for $T { + constant! { + $( $constant() -> $T::consts::$constant; )+ + TAU() -> 6.28318530717958647692528676655900577; + LOG10_2() -> 0.301029995663981195213738894724493027; + LOG2_10() -> 3.32192809488736234787031942948939018; + } + } + ); +} + +float_const_impl! { + #[doc = "Return Euler’s number."] + E, + #[doc = "Return `1.0 / π`."] + FRAC_1_PI, + #[doc = "Return `1.0 / sqrt(2.0)`."] + FRAC_1_SQRT_2, + #[doc = "Return `2.0 / π`."] + FRAC_2_PI, + #[doc = "Return `2.0 / sqrt(π)`."] + FRAC_2_SQRT_PI, + #[doc = "Return `π / 2.0`."] + FRAC_PI_2, + #[doc = "Return `π / 3.0`."] + FRAC_PI_3, + #[doc = "Return `π / 4.0`."] + FRAC_PI_4, + #[doc = "Return `π / 6.0`."] + FRAC_PI_6, + #[doc = "Return `π / 8.0`."] + FRAC_PI_8, + #[doc = "Return `ln(10.0)`."] + LN_10, + #[doc = "Return `ln(2.0)`."] + LN_2, + #[doc = "Return `log10(e)`."] + LOG10_E, + #[doc = "Return `log2(e)`."] + LOG2_E, + #[doc = "Return Archimedes’ constant `π`."] + PI, + #[doc = "Return `sqrt(2.0)`."] + SQRT_2, +} + +#[cfg(test)] +mod tests { + use core::f64::consts; + + const DEG_RAD_PAIRS: [(f64, f64); 7] = [ + (0.0, 0.), + (22.5, consts::FRAC_PI_8), + (30.0, consts::FRAC_PI_6), + (45.0, consts::FRAC_PI_4), + (60.0, consts::FRAC_PI_3), + (90.0, consts::FRAC_PI_2), + (180.0, consts::PI), + ]; + + #[test] + fn convert_deg_rad() { + use float::FloatCore; + + for &(deg, rad) in &DEG_RAD_PAIRS { + assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-6); + assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-6); + + let (deg, rad) = (deg as f32, rad as f32); + assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-5); + assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-5); + } + } + + #[cfg(any(feature = "std", feature = "libm"))] + #[test] + fn convert_deg_rad_std() { + for &(deg, rad) in &DEG_RAD_PAIRS { + use Float; + + assert!((Float::to_degrees(rad) - deg).abs() < 1e-6); + assert!((Float::to_radians(deg) - rad).abs() < 1e-6); + + let (deg, rad) = (deg as f32, rad as f32); + assert!((Float::to_degrees(rad) - deg).abs() < 1e-5); + assert!((Float::to_radians(deg) - rad).abs() < 1e-5); + } + } + + #[test] + // This fails with the forwarded `std` implementation in Rust 1.8. + // To avoid the failure, the test is limited to `no_std` builds. + #[cfg(not(feature = "std"))] + fn to_degrees_rounding() { + use float::FloatCore; + + assert_eq!( + FloatCore::to_degrees(1_f32), + 57.2957795130823208767981548141051703 + ); + } + + #[test] + #[cfg(any(feature = "std", feature = "libm"))] + fn extra_logs() { + use float::{Float, FloatConst}; + + fn check(diff: F) { + let _2 = F::from(2.0).unwrap(); + assert!((F::LOG10_2() - F::log10(_2)).abs() < diff); + assert!((F::LOG10_2() - F::LN_2() / F::LN_10()).abs() < diff); + + let _10 = F::from(10.0).unwrap(); + assert!((F::LOG2_10() - F::log2(_10)).abs() < diff); + assert!((F::LOG2_10() - F::LN_10() / F::LN_2()).abs() < diff); + } + + check::(1e-6); + check::(1e-12); + } + + #[test] + #[cfg(any(feature = "std", feature = "libm"))] + fn copysign() { + use float::Float; + test_copysign_generic(2.0_f32, -2.0_f32, f32::nan()); + test_copysign_generic(2.0_f64, -2.0_f64, f64::nan()); + test_copysignf(2.0_f32, -2.0_f32, f32::nan()); + } + + #[cfg(any(feature = "std", feature = "libm"))] + fn test_copysignf(p: f32, n: f32, nan: f32) { + use core::ops::Neg; + use float::Float; + + assert!(p.is_sign_positive()); + assert!(n.is_sign_negative()); + assert!(nan.is_nan()); + + assert_eq!(p, Float::copysign(p, p)); + assert_eq!(p.neg(), Float::copysign(p, n)); + + assert_eq!(n, Float::copysign(n, n)); + assert_eq!(n.neg(), Float::copysign(n, p)); + + // FIXME: is_sign... only works on NaN starting in Rust 1.20 + // assert!(Float::copysign(nan, p).is_sign_positive()); + // assert!(Float::copysign(nan, n).is_sign_negative()); + } + + #[cfg(any(feature = "std", feature = "libm"))] + fn test_copysign_generic(p: F, n: F, nan: F) { + assert!(p.is_sign_positive()); + assert!(n.is_sign_negative()); + assert!(nan.is_nan()); + + assert_eq!(p, p.copysign(p)); + assert_eq!(p.neg(), p.copysign(n)); + + assert_eq!(n, n.copysign(n)); + assert_eq!(n.neg(), n.copysign(p)); + + // FIXME: is_sign... only works on NaN starting in Rust 1.20 + // assert!(nan.copysign(p).is_sign_positive()); + // assert!(nan.copysign(n).is_sign_negative()); + } +} diff --git a/bash-5.1/vendor/num-traits/src/identities.rs b/bash-5.1/vendor/num-traits/src/identities.rs new file mode 100644 index 0000000..7a99566 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/identities.rs @@ -0,0 +1,206 @@ +use core::num::Wrapping; +use core::ops::{Add, Mul}; + +/// Defines an additive identity element for `Self`. +/// +/// # Laws +/// +/// ```{.text} +/// a + 0 = a ∀ a ∈ Self +/// 0 + a = a ∀ a ∈ Self +/// ``` +pub trait Zero: Sized + Add { + /// Returns the additive identity element of `Self`, `0`. + /// # Purity + /// + /// This function should return the same result at all times regardless of + /// external mutable state, for example values stored in TLS or in + /// `static mut`s. + // This cannot be an associated constant, because of bignums. + fn zero() -> Self; + + /// Sets `self` to the additive identity element of `Self`, `0`. + fn set_zero(&mut self) { + *self = Zero::zero(); + } + + /// Returns `true` if `self` is equal to the additive identity. + fn is_zero(&self) -> bool; +} + +macro_rules! zero_impl { + ($t:ty, $v:expr) => { + impl Zero for $t { + #[inline] + fn zero() -> $t { + $v + } + #[inline] + fn is_zero(&self) -> bool { + *self == $v + } + } + }; +} + +zero_impl!(usize, 0); +zero_impl!(u8, 0); +zero_impl!(u16, 0); +zero_impl!(u32, 0); +zero_impl!(u64, 0); +#[cfg(has_i128)] +zero_impl!(u128, 0); + +zero_impl!(isize, 0); +zero_impl!(i8, 0); +zero_impl!(i16, 0); +zero_impl!(i32, 0); +zero_impl!(i64, 0); +#[cfg(has_i128)] +zero_impl!(i128, 0); + +zero_impl!(f32, 0.0); +zero_impl!(f64, 0.0); + +impl Zero for Wrapping +where + Wrapping: Add>, +{ + fn is_zero(&self) -> bool { + self.0.is_zero() + } + + fn set_zero(&mut self) { + self.0.set_zero(); + } + + fn zero() -> Self { + Wrapping(T::zero()) + } +} + +/// Defines a multiplicative identity element for `Self`. +/// +/// # Laws +/// +/// ```{.text} +/// a * 1 = a ∀ a ∈ Self +/// 1 * a = a ∀ a ∈ Self +/// ``` +pub trait One: Sized + Mul { + /// Returns the multiplicative identity element of `Self`, `1`. + /// + /// # Purity + /// + /// This function should return the same result at all times regardless of + /// external mutable state, for example values stored in TLS or in + /// `static mut`s. + // This cannot be an associated constant, because of bignums. + fn one() -> Self; + + /// Sets `self` to the multiplicative identity element of `Self`, `1`. + fn set_one(&mut self) { + *self = One::one(); + } + + /// Returns `true` if `self` is equal to the multiplicative identity. + /// + /// For performance reasons, it's best to implement this manually. + /// After a semver bump, this method will be required, and the + /// `where Self: PartialEq` bound will be removed. + #[inline] + fn is_one(&self) -> bool + where + Self: PartialEq, + { + *self == Self::one() + } +} + +macro_rules! one_impl { + ($t:ty, $v:expr) => { + impl One for $t { + #[inline] + fn one() -> $t { + $v + } + #[inline] + fn is_one(&self) -> bool { + *self == $v + } + } + }; +} + +one_impl!(usize, 1); +one_impl!(u8, 1); +one_impl!(u16, 1); +one_impl!(u32, 1); +one_impl!(u64, 1); +#[cfg(has_i128)] +one_impl!(u128, 1); + +one_impl!(isize, 1); +one_impl!(i8, 1); +one_impl!(i16, 1); +one_impl!(i32, 1); +one_impl!(i64, 1); +#[cfg(has_i128)] +one_impl!(i128, 1); + +one_impl!(f32, 1.0); +one_impl!(f64, 1.0); + +impl One for Wrapping +where + Wrapping: Mul>, +{ + fn set_one(&mut self) { + self.0.set_one(); + } + + fn one() -> Self { + Wrapping(T::one()) + } +} + +// Some helper functions provided for backwards compatibility. + +/// Returns the additive identity, `0`. +#[inline(always)] +pub fn zero() -> T { + Zero::zero() +} + +/// Returns the multiplicative identity, `1`. +#[inline(always)] +pub fn one() -> T { + One::one() +} + +#[test] +fn wrapping_identities() { + macro_rules! test_wrapping_identities { + ($($t:ty)+) => { + $( + assert_eq!(zero::<$t>(), zero::>().0); + assert_eq!(one::<$t>(), one::>().0); + assert_eq!((0 as $t).is_zero(), Wrapping(0 as $t).is_zero()); + assert_eq!((1 as $t).is_zero(), Wrapping(1 as $t).is_zero()); + )+ + }; + } + + test_wrapping_identities!(isize i8 i16 i32 i64 usize u8 u16 u32 u64); +} + +#[test] +fn wrapping_is_zero() { + fn require_zero(_: &T) {} + require_zero(&Wrapping(42)); +} +#[test] +fn wrapping_is_one() { + fn require_one(_: &T) {} + require_one(&Wrapping(42)); +} diff --git a/bash-5.1/vendor/num-traits/src/int.rs b/bash-5.1/vendor/num-traits/src/int.rs new file mode 100644 index 0000000..c7dbf12 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/int.rs @@ -0,0 +1,568 @@ +use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr}; + +use bounds::Bounded; +use ops::checked::*; +use ops::saturating::Saturating; +use {Num, NumCast}; + +/// Generic trait for primitive integers. +/// +/// The `PrimInt` trait is an abstraction over the builtin primitive integer types (e.g., `u8`, +/// `u32`, `isize`, `i128`, ...). It inherits the basic numeric traits and extends them with +/// bitwise operators and non-wrapping arithmetic. +/// +/// The trait explicitly inherits `Copy`, `Eq`, `Ord`, and `Sized`. The intention is that all +/// types implementing this trait behave like primitive types that are passed by value by default +/// and behave like builtin integers. Furthermore, the types are expected to expose the integer +/// value in binary representation and support bitwise operators. The standard bitwise operations +/// (e.g., bitwise-and, bitwise-or, right-shift, left-shift) are inherited and the trait extends +/// these with introspective queries (e.g., `PrimInt::count_ones()`, `PrimInt::leading_zeros()`), +/// bitwise combinators (e.g., `PrimInt::rotate_left()`), and endianness converters (e.g., +/// `PrimInt::to_be()`). +/// +/// All `PrimInt` types are expected to be fixed-width binary integers. The width can be queried +/// via `T::zero().count_zeros()`. The trait currently lacks a way to query the width at +/// compile-time. +/// +/// While a default implementation for all builtin primitive integers is provided, the trait is in +/// no way restricted to these. Other integer types that fulfil the requirements are free to +/// implement the trait was well. +/// +/// This trait and many of the method names originate in the unstable `core::num::Int` trait from +/// the rust standard library. The original trait was never stabilized and thus removed from the +/// standard library. +pub trait PrimInt: + Sized + + Copy + + Num + + NumCast + + Bounded + + PartialOrd + + Ord + + Eq + + Not + + BitAnd + + BitOr + + BitXor + + Shl + + Shr + + CheckedAdd + + CheckedSub + + CheckedMul + + CheckedDiv + + Saturating +{ + /// Returns the number of ones in the binary representation of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b01001100u8; + /// + /// assert_eq!(n.count_ones(), 3); + /// ``` + fn count_ones(self) -> u32; + + /// Returns the number of zeros in the binary representation of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b01001100u8; + /// + /// assert_eq!(n.count_zeros(), 5); + /// ``` + fn count_zeros(self) -> u32; + + /// Returns the number of leading ones in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xF00Du16; + /// + /// assert_eq!(n.leading_ones(), 4); + /// ``` + fn leading_ones(self) -> u32 { + (!self).leading_zeros() + } + + /// Returns the number of leading zeros in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b0101000u16; + /// + /// assert_eq!(n.leading_zeros(), 10); + /// ``` + fn leading_zeros(self) -> u32; + + /// Returns the number of trailing ones in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xBEEFu16; + /// + /// assert_eq!(n.trailing_ones(), 4); + /// ``` + fn trailing_ones(self) -> u32 { + (!self).trailing_zeros() + } + + /// Returns the number of trailing zeros in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b0101000u16; + /// + /// assert_eq!(n.trailing_zeros(), 3); + /// ``` + fn trailing_zeros(self) -> u32; + + /// Shifts the bits to the left by a specified amount, `n`, wrapping + /// the truncated bits to the end of the resulting integer. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0x3456789ABCDEF012u64; + /// + /// assert_eq!(n.rotate_left(12), m); + /// ``` + fn rotate_left(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount, `n`, wrapping + /// the truncated bits to the beginning of the resulting integer. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0xDEF0123456789ABCu64; + /// + /// assert_eq!(n.rotate_right(12), m); + /// ``` + fn rotate_right(self, n: u32) -> Self; + + /// Shifts the bits to the left by a specified amount, `n`, filling + /// zeros in the least significant bits. + /// + /// This is bitwise equivalent to signed `Shl`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0x3456789ABCDEF000u64; + /// + /// assert_eq!(n.signed_shl(12), m); + /// ``` + fn signed_shl(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount, `n`, copying + /// the "sign bit" in the most significant bits even for unsigned types. + /// + /// This is bitwise equivalent to signed `Shr`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xFEDCBA9876543210u64; + /// let m = 0xFFFFEDCBA9876543u64; + /// + /// assert_eq!(n.signed_shr(12), m); + /// ``` + fn signed_shr(self, n: u32) -> Self; + + /// Shifts the bits to the left by a specified amount, `n`, filling + /// zeros in the least significant bits. + /// + /// This is bitwise equivalent to unsigned `Shl`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFi64; + /// let m = 0x3456789ABCDEF000i64; + /// + /// assert_eq!(n.unsigned_shl(12), m); + /// ``` + fn unsigned_shl(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount, `n`, filling + /// zeros in the most significant bits. + /// + /// This is bitwise equivalent to unsigned `Shr`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = -8i8; // 0b11111000 + /// let m = 62i8; // 0b00111110 + /// + /// assert_eq!(n.unsigned_shr(2), m); + /// ``` + fn unsigned_shr(self, n: u32) -> Self; + + /// Reverses the byte order of the integer. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0xEFCDAB8967452301u64; + /// + /// assert_eq!(n.swap_bytes(), m); + /// ``` + fn swap_bytes(self) -> Self; + + /// Reverses the order of bits in the integer. + /// + /// The least significant bit becomes the most significant bit, second least-significant bit + /// becomes second most-significant bit, etc. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x12345678u32; + /// let m = 0x1e6a2c48u32; + /// + /// assert_eq!(n.reverse_bits(), m); + /// assert_eq!(0u32.reverse_bits(), 0); + /// ``` + fn reverse_bits(self) -> Self { + reverse_bits_fallback(self) + } + + /// Convert an integer from big endian to the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(u64::from_be(n), n) + /// } else { + /// assert_eq!(u64::from_be(n), n.swap_bytes()) + /// } + /// ``` + fn from_be(x: Self) -> Self; + + /// Convert an integer from little endian to the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(u64::from_le(n), n) + /// } else { + /// assert_eq!(u64::from_le(n), n.swap_bytes()) + /// } + /// ``` + fn from_le(x: Self) -> Self; + + /// Convert `self` to big endian from the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(n.to_be(), n) + /// } else { + /// assert_eq!(n.to_be(), n.swap_bytes()) + /// } + /// ``` + fn to_be(self) -> Self; + + /// Convert `self` to little endian from the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(n.to_le(), n) + /// } else { + /// assert_eq!(n.to_le(), n.swap_bytes()) + /// } + /// ``` + fn to_le(self) -> Self; + + /// Raises self to the power of `exp`, using exponentiation by squaring. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// assert_eq!(2i32.pow(4), 16); + /// ``` + fn pow(self, exp: u32) -> Self; +} + +fn one_per_byte() -> P { + // i8, u8: return 0x01 + // i16, u16: return 0x0101 = (0x01 << 8) | 0x01 + // i32, u32: return 0x01010101 = (0x0101 << 16) | 0x0101 + // ... + let mut ret = P::one(); + let mut shift = 8; + let mut b = ret.count_zeros() >> 3; + while b != 0 { + ret = (ret << shift) | ret; + shift <<= 1; + b >>= 1; + } + ret +} + +fn reverse_bits_fallback(i: P) -> P { + let rep_01: P = one_per_byte(); + let rep_03 = (rep_01 << 1) | rep_01; + let rep_05 = (rep_01 << 2) | rep_01; + let rep_0f = (rep_03 << 2) | rep_03; + let rep_33 = (rep_03 << 4) | rep_03; + let rep_55 = (rep_05 << 4) | rep_05; + + // code above only used to determine rep_0f, rep_33, rep_55; + // optimizer should be able to do it in compile time + let mut ret = i.swap_bytes(); + ret = ((ret & rep_0f) << 4) | ((ret >> 4) & rep_0f); + ret = ((ret & rep_33) << 2) | ((ret >> 2) & rep_33); + ret = ((ret & rep_55) << 1) | ((ret >> 1) & rep_55); + ret +} + +macro_rules! prim_int_impl { + ($T:ty, $S:ty, $U:ty) => { + impl PrimInt for $T { + #[inline] + fn count_ones(self) -> u32 { + <$T>::count_ones(self) + } + + #[inline] + fn count_zeros(self) -> u32 { + <$T>::count_zeros(self) + } + + #[cfg(has_leading_trailing_ones)] + #[inline] + fn leading_ones(self) -> u32 { + <$T>::leading_ones(self) + } + + #[inline] + fn leading_zeros(self) -> u32 { + <$T>::leading_zeros(self) + } + + #[cfg(has_leading_trailing_ones)] + #[inline] + fn trailing_ones(self) -> u32 { + <$T>::trailing_ones(self) + } + + #[inline] + fn trailing_zeros(self) -> u32 { + <$T>::trailing_zeros(self) + } + + #[inline] + fn rotate_left(self, n: u32) -> Self { + <$T>::rotate_left(self, n) + } + + #[inline] + fn rotate_right(self, n: u32) -> Self { + <$T>::rotate_right(self, n) + } + + #[inline] + fn signed_shl(self, n: u32) -> Self { + ((self as $S) << n) as $T + } + + #[inline] + fn signed_shr(self, n: u32) -> Self { + ((self as $S) >> n) as $T + } + + #[inline] + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + #[inline] + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + + #[inline] + fn swap_bytes(self) -> Self { + <$T>::swap_bytes(self) + } + + #[cfg(has_reverse_bits)] + #[inline] + fn reverse_bits(self) -> Self { + <$T>::reverse_bits(self) + } + + #[inline] + fn from_be(x: Self) -> Self { + <$T>::from_be(x) + } + + #[inline] + fn from_le(x: Self) -> Self { + <$T>::from_le(x) + } + + #[inline] + fn to_be(self) -> Self { + <$T>::to_be(self) + } + + #[inline] + fn to_le(self) -> Self { + <$T>::to_le(self) + } + + #[inline] + fn pow(self, exp: u32) -> Self { + <$T>::pow(self, exp) + } + } + }; +} + +// prim_int_impl!(type, signed, unsigned); +prim_int_impl!(u8, i8, u8); +prim_int_impl!(u16, i16, u16); +prim_int_impl!(u32, i32, u32); +prim_int_impl!(u64, i64, u64); +#[cfg(has_i128)] +prim_int_impl!(u128, i128, u128); +prim_int_impl!(usize, isize, usize); +prim_int_impl!(i8, i8, u8); +prim_int_impl!(i16, i16, u16); +prim_int_impl!(i32, i32, u32); +prim_int_impl!(i64, i64, u64); +#[cfg(has_i128)] +prim_int_impl!(i128, i128, u128); +prim_int_impl!(isize, isize, usize); + +#[cfg(test)] +mod tests { + use int::PrimInt; + + #[test] + pub fn reverse_bits() { + use core::{i16, i32, i64, i8}; + + assert_eq!( + PrimInt::reverse_bits(0x0123_4567_89ab_cdefu64), + 0xf7b3_d591_e6a2_c480 + ); + + assert_eq!(PrimInt::reverse_bits(0i8), 0); + assert_eq!(PrimInt::reverse_bits(-1i8), -1); + assert_eq!(PrimInt::reverse_bits(1i8), i8::MIN); + assert_eq!(PrimInt::reverse_bits(i8::MIN), 1); + assert_eq!(PrimInt::reverse_bits(-2i8), i8::MAX); + assert_eq!(PrimInt::reverse_bits(i8::MAX), -2); + + assert_eq!(PrimInt::reverse_bits(0i16), 0); + assert_eq!(PrimInt::reverse_bits(-1i16), -1); + assert_eq!(PrimInt::reverse_bits(1i16), i16::MIN); + assert_eq!(PrimInt::reverse_bits(i16::MIN), 1); + assert_eq!(PrimInt::reverse_bits(-2i16), i16::MAX); + assert_eq!(PrimInt::reverse_bits(i16::MAX), -2); + + assert_eq!(PrimInt::reverse_bits(0i32), 0); + assert_eq!(PrimInt::reverse_bits(-1i32), -1); + assert_eq!(PrimInt::reverse_bits(1i32), i32::MIN); + assert_eq!(PrimInt::reverse_bits(i32::MIN), 1); + assert_eq!(PrimInt::reverse_bits(-2i32), i32::MAX); + assert_eq!(PrimInt::reverse_bits(i32::MAX), -2); + + assert_eq!(PrimInt::reverse_bits(0i64), 0); + assert_eq!(PrimInt::reverse_bits(-1i64), -1); + assert_eq!(PrimInt::reverse_bits(1i64), i64::MIN); + assert_eq!(PrimInt::reverse_bits(i64::MIN), 1); + assert_eq!(PrimInt::reverse_bits(-2i64), i64::MAX); + assert_eq!(PrimInt::reverse_bits(i64::MAX), -2); + } + + #[test] + #[cfg(has_i128)] + pub fn reverse_bits_i128() { + use core::i128; + + assert_eq!(PrimInt::reverse_bits(0i128), 0); + assert_eq!(PrimInt::reverse_bits(-1i128), -1); + assert_eq!(PrimInt::reverse_bits(1i128), i128::MIN); + assert_eq!(PrimInt::reverse_bits(i128::MIN), 1); + assert_eq!(PrimInt::reverse_bits(-2i128), i128::MAX); + assert_eq!(PrimInt::reverse_bits(i128::MAX), -2); + } +} diff --git a/bash-5.1/vendor/num-traits/src/lib.rs b/bash-5.1/vendor/num-traits/src/lib.rs new file mode 100644 index 0000000..bed87f3 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/lib.rs @@ -0,0 +1,640 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Numeric traits for generic mathematics +//! +//! ## Compatibility +//! +//! The `num-traits` crate is tested for rustc 1.8 and greater. + +#![doc(html_root_url = "https://docs.rs/num-traits/0.2")] +#![deny(unconditional_recursion)] +#![no_std] +#[cfg(feature = "std")] +extern crate std; + +// Only `no_std` builds actually use `libm`. +#[cfg(all(not(feature = "std"), feature = "libm"))] +extern crate libm; + +use core::fmt; +use core::num::Wrapping; +use core::ops::{Add, Div, Mul, Rem, Sub}; +use core::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign}; + +pub use bounds::Bounded; +#[cfg(any(feature = "std", feature = "libm"))] +pub use float::Float; +pub use float::FloatConst; +// pub use real::{FloatCore, Real}; // NOTE: Don't do this, it breaks `use num_traits::*;`. +pub use cast::{cast, AsPrimitive, FromPrimitive, NumCast, ToPrimitive}; +pub use identities::{one, zero, One, Zero}; +pub use int::PrimInt; +pub use ops::checked::{ + CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl, CheckedShr, CheckedSub, +}; +pub use ops::euclid::{CheckedEuclid, Euclid}; +pub use ops::inv::Inv; +pub use ops::mul_add::{MulAdd, MulAddAssign}; +pub use ops::saturating::{Saturating, SaturatingAdd, SaturatingMul, SaturatingSub}; +pub use ops::wrapping::{ + WrappingAdd, WrappingMul, WrappingNeg, WrappingShl, WrappingShr, WrappingSub, +}; +pub use pow::{checked_pow, pow, Pow}; +pub use sign::{abs, abs_sub, signum, Signed, Unsigned}; + +#[macro_use] +mod macros; + +pub mod bounds; +pub mod cast; +pub mod float; +pub mod identities; +pub mod int; +pub mod ops; +pub mod pow; +pub mod real; +pub mod sign; + +/// The base trait for numeric types, covering `0` and `1` values, +/// comparisons, basic numeric operations, and string conversion. +pub trait Num: PartialEq + Zero + One + NumOps { + type FromStrRadixErr; + + /// Convert from a string and radix (typically `2..=36`). + /// + /// # Examples + /// + /// ```rust + /// use num_traits::Num; + /// + /// let result = ::from_str_radix("27", 10); + /// assert_eq!(result, Ok(27)); + /// + /// let result = ::from_str_radix("foo", 10); + /// assert!(result.is_err()); + /// ``` + /// + /// # Supported radices + /// + /// The exact range of supported radices is at the discretion of each type implementation. For + /// primitive integers, this is implemented by the inherent `from_str_radix` methods in the + /// standard library, which **panic** if the radix is not in the range from 2 to 36. The + /// implementation in this crate for primitive floats is similar. + /// + /// For third-party types, it is suggested that implementations should follow suit and at least + /// accept `2..=36` without panicking, but an `Err` may be returned for any unsupported radix. + /// It's possible that a type might not even support the common radix 10, nor any, if string + /// parsing doesn't make sense for that type. + fn from_str_radix(str: &str, radix: u32) -> Result; +} + +/// Generic trait for types implementing basic numeric operations +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumOps: + Add + + Sub + + Mul + + Div + + Rem +{ +} + +impl NumOps for T where + T: Add + + Sub + + Mul + + Div + + Rem +{ +} + +/// The trait for `Num` types which also implement numeric operations taking +/// the second operand by reference. +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumRef: Num + for<'r> NumOps<&'r Self> {} +impl NumRef for T where T: Num + for<'r> NumOps<&'r T> {} + +/// The trait for `Num` references which implement numeric operations, taking the +/// second operand either by value or by reference. +/// +/// This is automatically implemented for all types which implement the operators. It covers +/// every type implementing the operations though, regardless of it being a reference or +/// related to `Num`. +pub trait RefNum: NumOps + for<'r> NumOps<&'r Base, Base> {} +impl RefNum for T where T: NumOps + for<'r> NumOps<&'r Base, Base> {} + +/// Generic trait for types implementing numeric assignment operators (like `+=`). +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumAssignOps: + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign +{ +} + +impl NumAssignOps for T where + T: AddAssign + SubAssign + MulAssign + DivAssign + RemAssign +{ +} + +/// The trait for `Num` types which also implement assignment operators. +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumAssign: Num + NumAssignOps {} +impl NumAssign for T where T: Num + NumAssignOps {} + +/// The trait for `NumAssign` types which also implement assignment operations +/// taking the second operand by reference. +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumAssignRef: NumAssign + for<'r> NumAssignOps<&'r Self> {} +impl NumAssignRef for T where T: NumAssign + for<'r> NumAssignOps<&'r T> {} + +macro_rules! int_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t { + type FromStrRadixErr = ::core::num::ParseIntError; + #[inline] + fn from_str_radix(s: &str, radix: u32) + -> Result + { + <$t>::from_str_radix(s, radix) + } + } + )*) +} +int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64); +#[cfg(has_i128)] +int_trait_impl!(Num for u128 i128); + +impl Num for Wrapping +where + Wrapping: NumOps, +{ + type FromStrRadixErr = T::FromStrRadixErr; + fn from_str_radix(str: &str, radix: u32) -> Result { + T::from_str_radix(str, radix).map(Wrapping) + } +} + +#[derive(Debug)] +pub enum FloatErrorKind { + Empty, + Invalid, +} +// FIXME: core::num::ParseFloatError is stable in 1.0, but opaque to us, +// so there's not really any way for us to reuse it. +#[derive(Debug)] +pub struct ParseFloatError { + pub kind: FloatErrorKind, +} + +impl fmt::Display for ParseFloatError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match self.kind { + FloatErrorKind::Empty => "cannot parse float from empty string", + FloatErrorKind::Invalid => "invalid float literal", + }; + + description.fmt(f) + } +} + +fn str_to_ascii_lower_eq_str(a: &str, b: &str) -> bool { + a.len() == b.len() + && a.bytes().zip(b.bytes()).all(|(a, b)| { + let a_to_ascii_lower = a | (((b'A' <= a && a <= b'Z') as u8) << 5); + a_to_ascii_lower == b + }) +} + +// FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck +// with this implementation ourselves until we want to make a breaking change. +// (would have to drop it from `Num` though) +macro_rules! float_trait_impl { + ($name:ident for $($t:ident)*) => ($( + impl $name for $t { + type FromStrRadixErr = ParseFloatError; + + fn from_str_radix(src: &str, radix: u32) + -> Result + { + use self::FloatErrorKind::*; + use self::ParseFloatError as PFE; + + // Special case radix 10 to use more accurate standard library implementation + if radix == 10 { + return src.parse().map_err(|_| PFE { + kind: if src.is_empty() { Empty } else { Invalid }, + }); + } + + // Special values + if str_to_ascii_lower_eq_str(src, "inf") + || str_to_ascii_lower_eq_str(src, "infinity") + { + return Ok(core::$t::INFINITY); + } else if str_to_ascii_lower_eq_str(src, "-inf") + || str_to_ascii_lower_eq_str(src, "-infinity") + { + return Ok(core::$t::NEG_INFINITY); + } else if str_to_ascii_lower_eq_str(src, "nan") { + return Ok(core::$t::NAN); + } else if str_to_ascii_lower_eq_str(src, "-nan") { + return Ok(-core::$t::NAN); + } + + fn slice_shift_char(src: &str) -> Option<(char, &str)> { + let mut chars = src.chars(); + if let Some(ch) = chars.next() { + Some((ch, chars.as_str())) + } else { + None + } + } + + let (is_positive, src) = match slice_shift_char(src) { + None => return Err(PFE { kind: Empty }), + Some(('-', "")) => return Err(PFE { kind: Empty }), + Some(('-', src)) => (false, src), + Some((_, _)) => (true, src), + }; + + // The significand to accumulate + let mut sig = if is_positive { 0.0 } else { -0.0 }; + // Necessary to detect overflow + let mut prev_sig = sig; + let mut cs = src.chars().enumerate(); + // Exponent prefix and exponent index offset + let mut exp_info = None::<(char, usize)>; + + // Parse the integer part of the significand + for (i, c) in cs.by_ref() { + match c.to_digit(radix) { + Some(digit) => { + // shift significand one digit left + sig = sig * (radix as $t); + + // add/subtract current digit depending on sign + if is_positive { + sig = sig + ((digit as isize) as $t); + } else { + sig = sig - ((digit as isize) as $t); + } + + // Detect overflow by comparing to last value, except + // if we've not seen any non-zero digits. + if prev_sig != 0.0 { + if is_positive && sig <= prev_sig + { return Ok(core::$t::INFINITY); } + if !is_positive && sig >= prev_sig + { return Ok(core::$t::NEG_INFINITY); } + + // Detect overflow by reversing the shift-and-add process + if is_positive && (prev_sig != (sig - digit as $t) / radix as $t) + { return Ok(core::$t::INFINITY); } + if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t) + { return Ok(core::$t::NEG_INFINITY); } + } + prev_sig = sig; + }, + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_info = Some((c, i + 1)); + break; // start of exponent + }, + '.' => { + break; // start of fractional part + }, + _ => { + return Err(PFE { kind: Invalid }); + }, + }, + } + } + + // If we are not yet at the exponent parse the fractional + // part of the significand + if exp_info.is_none() { + let mut power = 1.0; + for (i, c) in cs.by_ref() { + match c.to_digit(radix) { + Some(digit) => { + // Decrease power one order of magnitude + power = power / (radix as $t); + // add/subtract current digit depending on sign + sig = if is_positive { + sig + (digit as $t) * power + } else { + sig - (digit as $t) * power + }; + // Detect overflow by comparing to last value + if is_positive && sig < prev_sig + { return Ok(core::$t::INFINITY); } + if !is_positive && sig > prev_sig + { return Ok(core::$t::NEG_INFINITY); } + prev_sig = sig; + }, + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_info = Some((c, i + 1)); + break; // start of exponent + }, + _ => { + return Err(PFE { kind: Invalid }); + }, + }, + } + } + } + + // Parse and calculate the exponent + let exp = match exp_info { + Some((c, offset)) => { + let base = match c { + 'E' | 'e' if radix == 10 => 10.0, + 'P' | 'p' if radix == 16 => 2.0, + _ => return Err(PFE { kind: Invalid }), + }; + + // Parse the exponent as decimal integer + let src = &src[offset..]; + let (is_positive, exp) = match slice_shift_char(src) { + Some(('-', src)) => (false, src.parse::()), + Some(('+', src)) => (true, src.parse::()), + Some((_, _)) => (true, src.parse::()), + None => return Err(PFE { kind: Invalid }), + }; + + #[cfg(feature = "std")] + fn pow(base: $t, exp: usize) -> $t { + Float::powi(base, exp as i32) + } + // otherwise uses the generic `pow` from the root + + match (is_positive, exp) { + (true, Ok(exp)) => pow(base, exp), + (false, Ok(exp)) => 1.0 / pow(base, exp), + (_, Err(_)) => return Err(PFE { kind: Invalid }), + } + }, + None => 1.0, // no exponent + }; + + Ok(sig * exp) + } + } + )*) +} +float_trait_impl!(Num for f32 f64); + +/// A value bounded by a minimum and a maximum +/// +/// If input is less than min then this returns min. +/// If input is greater than max then this returns max. +/// Otherwise this returns input. +/// +/// **Panics** in debug mode if `!(min <= max)`. +#[inline] +pub fn clamp(input: T, min: T, max: T) -> T { + debug_assert!(min <= max, "min must be less than or equal to max"); + if input < min { + min + } else if input > max { + max + } else { + input + } +} + +/// A value bounded by a minimum value +/// +/// If input is less than min then this returns min. +/// Otherwise this returns input. +/// `clamp_min(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::min(std::f32::NAN, 1.0)`. +/// +/// **Panics** in debug mode if `!(min == min)`. (This occurs if `min` is `NAN`.) +#[inline] +pub fn clamp_min(input: T, min: T) -> T { + debug_assert!(min == min, "min must not be NAN"); + if input < min { + min + } else { + input + } +} + +/// A value bounded by a maximum value +/// +/// If input is greater than max then this returns max. +/// Otherwise this returns input. +/// `clamp_max(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::max(std::f32::NAN, 1.0)`. +/// +/// **Panics** in debug mode if `!(max == max)`. (This occurs if `max` is `NAN`.) +#[inline] +pub fn clamp_max(input: T, max: T) -> T { + debug_assert!(max == max, "max must not be NAN"); + if input > max { + max + } else { + input + } +} + +#[test] +fn clamp_test() { + // Int test + assert_eq!(1, clamp(1, -1, 2)); + assert_eq!(-1, clamp(-2, -1, 2)); + assert_eq!(2, clamp(3, -1, 2)); + assert_eq!(1, clamp_min(1, -1)); + assert_eq!(-1, clamp_min(-2, -1)); + assert_eq!(-1, clamp_max(1, -1)); + assert_eq!(-2, clamp_max(-2, -1)); + + // Float test + assert_eq!(1.0, clamp(1.0, -1.0, 2.0)); + assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0)); + assert_eq!(2.0, clamp(3.0, -1.0, 2.0)); + assert_eq!(1.0, clamp_min(1.0, -1.0)); + assert_eq!(-1.0, clamp_min(-2.0, -1.0)); + assert_eq!(-1.0, clamp_max(1.0, -1.0)); + assert_eq!(-2.0, clamp_max(-2.0, -1.0)); + assert!(clamp(::core::f32::NAN, -1.0, 1.0).is_nan()); + assert!(clamp_min(::core::f32::NAN, 1.0).is_nan()); + assert!(clamp_max(::core::f32::NAN, 1.0).is_nan()); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_nan_min() { + clamp(0., ::core::f32::NAN, 1.); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_nan_max() { + clamp(0., -1., ::core::f32::NAN); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_nan_min_max() { + clamp(0., ::core::f32::NAN, ::core::f32::NAN); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_min_nan_min() { + clamp_min(0., ::core::f32::NAN); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_max_nan_max() { + clamp_max(0., ::core::f32::NAN); +} + +#[test] +fn from_str_radix_unwrap() { + // The Result error must impl Debug to allow unwrap() + + let i: i32 = Num::from_str_radix("0", 10).unwrap(); + assert_eq!(i, 0); + + let f: f32 = Num::from_str_radix("0.0", 10).unwrap(); + assert_eq!(f, 0.0); +} + +#[test] +fn from_str_radix_multi_byte_fail() { + // Ensure parsing doesn't panic, even on invalid sign characters + assert!(f32::from_str_radix("™0.2", 10).is_err()); + + // Even when parsing the exponent sign + assert!(f32::from_str_radix("0.2E™1", 10).is_err()); +} + +#[test] +fn from_str_radix_ignore_case() { + assert_eq!( + f32::from_str_radix("InF", 16).unwrap(), + ::core::f32::INFINITY + ); + assert_eq!( + f32::from_str_radix("InfinitY", 16).unwrap(), + ::core::f32::INFINITY + ); + assert_eq!( + f32::from_str_radix("-InF", 8).unwrap(), + ::core::f32::NEG_INFINITY + ); + assert_eq!( + f32::from_str_radix("-InfinitY", 8).unwrap(), + ::core::f32::NEG_INFINITY + ); + assert!(f32::from_str_radix("nAn", 4).unwrap().is_nan()); + assert!(f32::from_str_radix("-nAn", 4).unwrap().is_nan()); +} + +#[test] +fn wrapping_is_num() { + fn require_num(_: &T) {} + require_num(&Wrapping(42_u32)); + require_num(&Wrapping(-42)); +} + +#[test] +fn wrapping_from_str_radix() { + macro_rules! test_wrapping_from_str_radix { + ($($t:ty)+) => { + $( + for &(s, r) in &[("42", 10), ("42", 2), ("-13.0", 10), ("foo", 10)] { + let w = Wrapping::<$t>::from_str_radix(s, r).map(|w| w.0); + assert_eq!(w, <$t as Num>::from_str_radix(s, r)); + } + )+ + }; + } + + test_wrapping_from_str_radix!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); +} + +#[test] +fn check_num_ops() { + fn compute(x: T, y: T) -> T { + x * y / y % y + y - y + } + assert_eq!(compute(1, 2), 1) +} + +#[test] +fn check_numref_ops() { + fn compute(x: T, y: &T) -> T { + x * y / y % y + y - y + } + assert_eq!(compute(1, &2), 1) +} + +#[test] +fn check_refnum_ops() { + fn compute(x: &T, y: T) -> T + where + for<'a> &'a T: RefNum, + { + &(&(&(&(x * y) / y) % y) + y) - y + } + assert_eq!(compute(&1, 2), 1) +} + +#[test] +fn check_refref_ops() { + fn compute(x: &T, y: &T) -> T + where + for<'a> &'a T: RefNum, + { + &(&(&(&(x * y) / y) % y) + y) - y + } + assert_eq!(compute(&1, &2), 1) +} + +#[test] +fn check_numassign_ops() { + fn compute(mut x: T, y: T) -> T { + x *= y; + x /= y; + x %= y; + x += y; + x -= y; + x + } + assert_eq!(compute(1, 2), 1) +} + +#[cfg(has_int_assignop_ref)] +#[test] +fn check_numassignref_ops() { + fn compute(mut x: T, y: &T) -> T { + x *= y; + x /= y; + x %= y; + x += y; + x -= y; + x + } + assert_eq!(compute(1, &2), 1) +} diff --git a/bash-5.1/vendor/num-traits/src/macros.rs b/bash-5.1/vendor/num-traits/src/macros.rs new file mode 100644 index 0000000..b97758e --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/macros.rs @@ -0,0 +1,44 @@ +// not all are used in all features configurations +#![allow(unused)] + +/// Forward a method to an inherent method or a base trait method. +macro_rules! forward { + ($( Self :: $method:ident ( self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method(self $( , $arg : $ty )* ) -> $ret { + Self::$method(self $( , $arg )* ) + } + )*}; + ($( $base:ident :: $method:ident ( self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method(self $( , $arg : $ty )* ) -> $ret { + ::$method(self $( , $arg )* ) + } + )*}; + ($( $base:ident :: $method:ident ( $( $arg:ident : $ty:ty ),* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method( $( $arg : $ty ),* ) -> $ret { + ::$method( $( $arg ),* ) + } + )*}; + ($( $imp:path as $method:ident ( self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method(self $( , $arg : $ty )* ) -> $ret { + $imp(self $( , $arg )* ) + } + )*}; +} + +macro_rules! constant { + ($( $method:ident () -> $ret:expr ; )*) + => {$( + #[inline] + fn $method() -> Self { + $ret + } + )*}; +} diff --git a/bash-5.1/vendor/num-traits/src/ops/checked.rs b/bash-5.1/vendor/num-traits/src/ops/checked.rs new file mode 100644 index 0000000..3865570 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/checked.rs @@ -0,0 +1,277 @@ +use core::ops::{Add, Div, Mul, Rem, Shl, Shr, Sub}; + +/// Performs addition that returns `None` instead of wrapping around on +/// overflow. +pub trait CheckedAdd: Sized + Add { + /// Adds two numbers, checking for overflow. If overflow happens, `None` is + /// returned. + fn checked_add(&self, v: &Self) -> Option; +} + +macro_rules! checked_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &$t) -> Option<$t> { + <$t>::$method(*self, *v) + } + } + }; +} + +checked_impl!(CheckedAdd, checked_add, u8); +checked_impl!(CheckedAdd, checked_add, u16); +checked_impl!(CheckedAdd, checked_add, u32); +checked_impl!(CheckedAdd, checked_add, u64); +checked_impl!(CheckedAdd, checked_add, usize); +#[cfg(has_i128)] +checked_impl!(CheckedAdd, checked_add, u128); + +checked_impl!(CheckedAdd, checked_add, i8); +checked_impl!(CheckedAdd, checked_add, i16); +checked_impl!(CheckedAdd, checked_add, i32); +checked_impl!(CheckedAdd, checked_add, i64); +checked_impl!(CheckedAdd, checked_add, isize); +#[cfg(has_i128)] +checked_impl!(CheckedAdd, checked_add, i128); + +/// Performs subtraction that returns `None` instead of wrapping around on underflow. +pub trait CheckedSub: Sized + Sub { + /// Subtracts two numbers, checking for underflow. If underflow happens, + /// `None` is returned. + fn checked_sub(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedSub, checked_sub, u8); +checked_impl!(CheckedSub, checked_sub, u16); +checked_impl!(CheckedSub, checked_sub, u32); +checked_impl!(CheckedSub, checked_sub, u64); +checked_impl!(CheckedSub, checked_sub, usize); +#[cfg(has_i128)] +checked_impl!(CheckedSub, checked_sub, u128); + +checked_impl!(CheckedSub, checked_sub, i8); +checked_impl!(CheckedSub, checked_sub, i16); +checked_impl!(CheckedSub, checked_sub, i32); +checked_impl!(CheckedSub, checked_sub, i64); +checked_impl!(CheckedSub, checked_sub, isize); +#[cfg(has_i128)] +checked_impl!(CheckedSub, checked_sub, i128); + +/// Performs multiplication that returns `None` instead of wrapping around on underflow or +/// overflow. +pub trait CheckedMul: Sized + Mul { + /// Multiplies two numbers, checking for underflow or overflow. If underflow + /// or overflow happens, `None` is returned. + fn checked_mul(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedMul, checked_mul, u8); +checked_impl!(CheckedMul, checked_mul, u16); +checked_impl!(CheckedMul, checked_mul, u32); +checked_impl!(CheckedMul, checked_mul, u64); +checked_impl!(CheckedMul, checked_mul, usize); +#[cfg(has_i128)] +checked_impl!(CheckedMul, checked_mul, u128); + +checked_impl!(CheckedMul, checked_mul, i8); +checked_impl!(CheckedMul, checked_mul, i16); +checked_impl!(CheckedMul, checked_mul, i32); +checked_impl!(CheckedMul, checked_mul, i64); +checked_impl!(CheckedMul, checked_mul, isize); +#[cfg(has_i128)] +checked_impl!(CheckedMul, checked_mul, i128); + +/// Performs division that returns `None` instead of panicking on division by zero and instead of +/// wrapping around on underflow and overflow. +pub trait CheckedDiv: Sized + Div { + /// Divides two numbers, checking for underflow, overflow and division by + /// zero. If any of that happens, `None` is returned. + fn checked_div(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedDiv, checked_div, u8); +checked_impl!(CheckedDiv, checked_div, u16); +checked_impl!(CheckedDiv, checked_div, u32); +checked_impl!(CheckedDiv, checked_div, u64); +checked_impl!(CheckedDiv, checked_div, usize); +#[cfg(has_i128)] +checked_impl!(CheckedDiv, checked_div, u128); + +checked_impl!(CheckedDiv, checked_div, i8); +checked_impl!(CheckedDiv, checked_div, i16); +checked_impl!(CheckedDiv, checked_div, i32); +checked_impl!(CheckedDiv, checked_div, i64); +checked_impl!(CheckedDiv, checked_div, isize); +#[cfg(has_i128)] +checked_impl!(CheckedDiv, checked_div, i128); + +/// Performs an integral remainder that returns `None` instead of panicking on division by zero and +/// instead of wrapping around on underflow and overflow. +pub trait CheckedRem: Sized + Rem { + /// Finds the remainder of dividing two numbers, checking for underflow, overflow and division + /// by zero. If any of that happens, `None` is returned. + /// + /// # Examples + /// + /// ``` + /// use num_traits::CheckedRem; + /// use std::i32::MIN; + /// + /// assert_eq!(CheckedRem::checked_rem(&10, &7), Some(3)); + /// assert_eq!(CheckedRem::checked_rem(&10, &-7), Some(3)); + /// assert_eq!(CheckedRem::checked_rem(&-10, &7), Some(-3)); + /// assert_eq!(CheckedRem::checked_rem(&-10, &-7), Some(-3)); + /// + /// assert_eq!(CheckedRem::checked_rem(&10, &0), None); + /// + /// assert_eq!(CheckedRem::checked_rem(&MIN, &1), Some(0)); + /// assert_eq!(CheckedRem::checked_rem(&MIN, &-1), None); + /// ``` + fn checked_rem(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedRem, checked_rem, u8); +checked_impl!(CheckedRem, checked_rem, u16); +checked_impl!(CheckedRem, checked_rem, u32); +checked_impl!(CheckedRem, checked_rem, u64); +checked_impl!(CheckedRem, checked_rem, usize); +#[cfg(has_i128)] +checked_impl!(CheckedRem, checked_rem, u128); + +checked_impl!(CheckedRem, checked_rem, i8); +checked_impl!(CheckedRem, checked_rem, i16); +checked_impl!(CheckedRem, checked_rem, i32); +checked_impl!(CheckedRem, checked_rem, i64); +checked_impl!(CheckedRem, checked_rem, isize); +#[cfg(has_i128)] +checked_impl!(CheckedRem, checked_rem, i128); + +macro_rules! checked_impl_unary { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self) -> Option<$t> { + <$t>::$method(*self) + } + } + }; +} + +/// Performs negation that returns `None` if the result can't be represented. +pub trait CheckedNeg: Sized { + /// Negates a number, returning `None` for results that can't be represented, like signed `MIN` + /// values that can't be positive, or non-zero unsigned values that can't be negative. + /// + /// # Examples + /// + /// ``` + /// use num_traits::CheckedNeg; + /// use std::i32::MIN; + /// + /// assert_eq!(CheckedNeg::checked_neg(&1_i32), Some(-1)); + /// assert_eq!(CheckedNeg::checked_neg(&-1_i32), Some(1)); + /// assert_eq!(CheckedNeg::checked_neg(&MIN), None); + /// + /// assert_eq!(CheckedNeg::checked_neg(&0_u32), Some(0)); + /// assert_eq!(CheckedNeg::checked_neg(&1_u32), None); + /// ``` + fn checked_neg(&self) -> Option; +} + +checked_impl_unary!(CheckedNeg, checked_neg, u8); +checked_impl_unary!(CheckedNeg, checked_neg, u16); +checked_impl_unary!(CheckedNeg, checked_neg, u32); +checked_impl_unary!(CheckedNeg, checked_neg, u64); +checked_impl_unary!(CheckedNeg, checked_neg, usize); +#[cfg(has_i128)] +checked_impl_unary!(CheckedNeg, checked_neg, u128); + +checked_impl_unary!(CheckedNeg, checked_neg, i8); +checked_impl_unary!(CheckedNeg, checked_neg, i16); +checked_impl_unary!(CheckedNeg, checked_neg, i32); +checked_impl_unary!(CheckedNeg, checked_neg, i64); +checked_impl_unary!(CheckedNeg, checked_neg, isize); +#[cfg(has_i128)] +checked_impl_unary!(CheckedNeg, checked_neg, i128); + +/// Performs a left shift that returns `None` on shifts larger than +/// the type width. +pub trait CheckedShl: Sized + Shl { + /// Checked shift left. Computes `self << rhs`, returning `None` + /// if `rhs` is larger than or equal to the number of bits in `self`. + /// + /// ``` + /// use num_traits::CheckedShl; + /// + /// let x: u16 = 0x0001; + /// + /// assert_eq!(CheckedShl::checked_shl(&x, 0), Some(0x0001)); + /// assert_eq!(CheckedShl::checked_shl(&x, 1), Some(0x0002)); + /// assert_eq!(CheckedShl::checked_shl(&x, 15), Some(0x8000)); + /// assert_eq!(CheckedShl::checked_shl(&x, 16), None); + /// ``` + fn checked_shl(&self, rhs: u32) -> Option; +} + +macro_rules! checked_shift_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, rhs: u32) -> Option<$t> { + <$t>::$method(*self, rhs) + } + } + }; +} + +checked_shift_impl!(CheckedShl, checked_shl, u8); +checked_shift_impl!(CheckedShl, checked_shl, u16); +checked_shift_impl!(CheckedShl, checked_shl, u32); +checked_shift_impl!(CheckedShl, checked_shl, u64); +checked_shift_impl!(CheckedShl, checked_shl, usize); +#[cfg(has_i128)] +checked_shift_impl!(CheckedShl, checked_shl, u128); + +checked_shift_impl!(CheckedShl, checked_shl, i8); +checked_shift_impl!(CheckedShl, checked_shl, i16); +checked_shift_impl!(CheckedShl, checked_shl, i32); +checked_shift_impl!(CheckedShl, checked_shl, i64); +checked_shift_impl!(CheckedShl, checked_shl, isize); +#[cfg(has_i128)] +checked_shift_impl!(CheckedShl, checked_shl, i128); + +/// Performs a right shift that returns `None` on shifts larger than +/// the type width. +pub trait CheckedShr: Sized + Shr { + /// Checked shift right. Computes `self >> rhs`, returning `None` + /// if `rhs` is larger than or equal to the number of bits in `self`. + /// + /// ``` + /// use num_traits::CheckedShr; + /// + /// let x: u16 = 0x8000; + /// + /// assert_eq!(CheckedShr::checked_shr(&x, 0), Some(0x8000)); + /// assert_eq!(CheckedShr::checked_shr(&x, 1), Some(0x4000)); + /// assert_eq!(CheckedShr::checked_shr(&x, 15), Some(0x0001)); + /// assert_eq!(CheckedShr::checked_shr(&x, 16), None); + /// ``` + fn checked_shr(&self, rhs: u32) -> Option; +} + +checked_shift_impl!(CheckedShr, checked_shr, u8); +checked_shift_impl!(CheckedShr, checked_shr, u16); +checked_shift_impl!(CheckedShr, checked_shr, u32); +checked_shift_impl!(CheckedShr, checked_shr, u64); +checked_shift_impl!(CheckedShr, checked_shr, usize); +#[cfg(has_i128)] +checked_shift_impl!(CheckedShr, checked_shr, u128); + +checked_shift_impl!(CheckedShr, checked_shr, i8); +checked_shift_impl!(CheckedShr, checked_shr, i16); +checked_shift_impl!(CheckedShr, checked_shr, i32); +checked_shift_impl!(CheckedShr, checked_shr, i64); +checked_shift_impl!(CheckedShr, checked_shr, isize); +#[cfg(has_i128)] +checked_shift_impl!(CheckedShr, checked_shr, i128); diff --git a/bash-5.1/vendor/num-traits/src/ops/euclid.rs b/bash-5.1/vendor/num-traits/src/ops/euclid.rs new file mode 100644 index 0000000..99b5127 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/euclid.rs @@ -0,0 +1,347 @@ +use core::ops::{Div, Rem}; + +pub trait Euclid: Sized + Div + Rem { + /// Calculates Euclidean division, the matching method for `rem_euclid`. + /// + /// This computes the integer `n` such that + /// `self = n * v + self.rem_euclid(v)`. + /// In other words, the result is `self / v` rounded to the integer `n` + /// such that `self >= n * v`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::Euclid; + /// + /// let a: i32 = 7; + /// let b: i32 = 4; + /// assert_eq!(Euclid::div_euclid(&a, &b), 1); // 7 > 4 * 1 + /// assert_eq!(Euclid::div_euclid(&-a, &b), -2); // -7 >= 4 * -2 + /// assert_eq!(Euclid::div_euclid(&a, &-b), -1); // 7 >= -4 * -1 + /// assert_eq!(Euclid::div_euclid(&-a, &-b), 2); // -7 >= -4 * 2 + /// ``` + fn div_euclid(&self, v: &Self) -> Self; + + /// Calculates the least nonnegative remainder of `self (mod v)`. + /// + /// In particular, the return value `r` satisfies `0.0 <= r < v.abs()` in + /// most cases. However, due to a floating point round-off error it can + /// result in `r == v.abs()`, violating the mathematical definition, if + /// `self` is much smaller than `v.abs()` in magnitude and `self < 0.0`. + /// This result is not an element of the function's codomain, but it is the + /// closest floating point number in the real numbers and thus fulfills the + /// property `self == self.div_euclid(v) * v + self.rem_euclid(v)` + /// approximatively. + /// + /// # Examples + /// + /// ``` + /// use num_traits::Euclid; + /// + /// let a: i32 = 7; + /// let b: i32 = 4; + /// assert_eq!(Euclid::rem_euclid(&a, &b), 3); + /// assert_eq!(Euclid::rem_euclid(&-a, &b), 1); + /// assert_eq!(Euclid::rem_euclid(&a, &-b), 3); + /// assert_eq!(Euclid::rem_euclid(&-a, &-b), 1); + /// ``` + fn rem_euclid(&self, v: &Self) -> Self; +} + +macro_rules! euclid_forward_impl { + ($($t:ty)*) => {$( + #[cfg(has_div_euclid)] + impl Euclid for $t { + #[inline] + fn div_euclid(&self, v: &$t) -> Self { + <$t>::div_euclid(*self, *v) + } + + #[inline] + fn rem_euclid(&self, v: &$t) -> Self { + <$t>::rem_euclid(*self, *v) + } + } + )*} +} + +macro_rules! euclid_int_impl { + ($($t:ty)*) => {$( + euclid_forward_impl!($t); + + #[cfg(not(has_div_euclid))] + impl Euclid for $t { + #[inline] + fn div_euclid(&self, v: &$t) -> Self { + let q = self / v; + if self % v < 0 { + return if *v > 0 { q - 1 } else { q + 1 } + } + q + } + + #[inline] + fn rem_euclid(&self, v: &$t) -> Self { + let r = self % v; + if r < 0 { + if *v < 0 { + r - v + } else { + r + v + } + } else { + r + } + } + } + )*} +} + +macro_rules! euclid_uint_impl { + ($($t:ty)*) => {$( + euclid_forward_impl!($t); + + #[cfg(not(has_div_euclid))] + impl Euclid for $t { + #[inline] + fn div_euclid(&self, v: &$t) -> Self { + self / v + } + + #[inline] + fn rem_euclid(&self, v: &$t) -> Self { + self % v + } + } + )*} +} + +euclid_int_impl!(isize i8 i16 i32 i64); +euclid_uint_impl!(usize u8 u16 u32 u64); +#[cfg(has_i128)] +euclid_int_impl!(i128); +#[cfg(has_i128)] +euclid_uint_impl!(u128); + +#[cfg(all(has_div_euclid, feature = "std"))] +euclid_forward_impl!(f32 f64); + +#[cfg(not(all(has_div_euclid, feature = "std")))] +impl Euclid for f32 { + #[inline] + fn div_euclid(&self, v: &f32) -> f32 { + let q = ::trunc(self / v); + if self % v < 0.0 { + return if *v > 0.0 { q - 1.0 } else { q + 1.0 }; + } + q + } + + #[inline] + fn rem_euclid(&self, v: &f32) -> f32 { + let r = self % v; + if r < 0.0 { + r + ::abs(*v) + } else { + r + } + } +} + +#[cfg(not(all(has_div_euclid, feature = "std")))] +impl Euclid for f64 { + #[inline] + fn div_euclid(&self, v: &f64) -> f64 { + let q = ::trunc(self / v); + if self % v < 0.0 { + return if *v > 0.0 { q - 1.0 } else { q + 1.0 }; + } + q + } + + #[inline] + fn rem_euclid(&self, v: &f64) -> f64 { + let r = self % v; + if r < 0.0 { + r + ::abs(*v) + } else { + r + } + } +} + +pub trait CheckedEuclid: Euclid { + /// Performs euclid division that returns `None` instead of panicking on division by zero + /// and instead of wrapping around on underflow and overflow. + fn checked_div_euclid(&self, v: &Self) -> Option; + + /// Finds the euclid remainder of dividing two numbers, checking for underflow, overflow and + /// division by zero. If any of that happens, `None` is returned. + fn checked_rem_euclid(&self, v: &Self) -> Option; +} + +macro_rules! checked_euclid_forward_impl { + ($($t:ty)*) => {$( + #[cfg(has_div_euclid)] + impl CheckedEuclid for $t { + #[inline] + fn checked_div_euclid(&self, v: &$t) -> Option { + <$t>::checked_div_euclid(*self, *v) + } + + #[inline] + fn checked_rem_euclid(&self, v: &$t) -> Option { + <$t>::checked_rem_euclid(*self, *v) + } + } + )*} +} + +macro_rules! checked_euclid_int_impl { + ($($t:ty)*) => {$( + checked_euclid_forward_impl!($t); + + #[cfg(not(has_div_euclid))] + impl CheckedEuclid for $t { + #[inline] + fn checked_div_euclid(&self, v: &$t) -> Option<$t> { + if *v == 0 || (*self == Self::min_value() && *v == -1) { + None + } else { + Some(Euclid::div_euclid(self, v)) + } + } + + #[inline] + fn checked_rem_euclid(&self, v: &$t) -> Option<$t> { + if *v == 0 || (*self == Self::min_value() && *v == -1) { + None + } else { + Some(Euclid::rem_euclid(self, v)) + } + } + } + )*} +} + +macro_rules! checked_euclid_uint_impl { + ($($t:ty)*) => {$( + checked_euclid_forward_impl!($t); + + #[cfg(not(has_div_euclid))] + impl CheckedEuclid for $t { + #[inline] + fn checked_div_euclid(&self, v: &$t) -> Option<$t> { + if *v == 0 { + None + } else { + Some(Euclid::div_euclid(self, v)) + } + } + + #[inline] + fn checked_rem_euclid(&self, v: &$t) -> Option<$t> { + if *v == 0 { + None + } else { + Some(Euclid::rem_euclid(self, v)) + } + } + } + )*} +} + +checked_euclid_int_impl!(isize i8 i16 i32 i64); +checked_euclid_uint_impl!(usize u8 u16 u32 u64); +#[cfg(has_i128)] +checked_euclid_int_impl!(i128); +#[cfg(has_i128)] +checked_euclid_uint_impl!(u128); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn euclid_unsigned() { + macro_rules! test_euclid { + ($($t:ident)+) => { + $( + { + let x: $t = 10; + let y: $t = 3; + assert_eq!(Euclid::div_euclid(&x, &y), 3); + assert_eq!(Euclid::rem_euclid(&x, &y), 1); + } + )+ + }; + } + + test_euclid!(usize u8 u16 u32 u64); + } + + #[test] + fn euclid_signed() { + macro_rules! test_euclid { + ($($t:ident)+) => { + $( + { + let x: $t = 10; + let y: $t = -3; + assert_eq!(Euclid::div_euclid(&x, &y), -3); + assert_eq!(Euclid::div_euclid(&-x, &y), 4); + assert_eq!(Euclid::rem_euclid(&x, &y), 1); + assert_eq!(Euclid::rem_euclid(&-x, &y), 2); + let x: $t = $t::min_value() + 1; + let y: $t = -1; + assert_eq!(Euclid::div_euclid(&x, &y), $t::max_value()); + } + )+ + }; + } + + test_euclid!(isize i8 i16 i32 i64); + } + + #[test] + fn euclid_float() { + macro_rules! test_euclid { + ($($t:ident)+) => { + $( + { + let x: $t = 12.1; + let y: $t = 3.2; + assert!(Euclid::div_euclid(&x, &y) * y + Euclid::rem_euclid(&x, &y) - x + <= 46.4 * <$t as ::float::FloatCore>::epsilon()); + assert!(Euclid::div_euclid(&x, &-y) * -y + Euclid::rem_euclid(&x, &-y) - x + <= 46.4 * <$t as ::float::FloatCore>::epsilon()); + assert!(Euclid::div_euclid(&-x, &y) * y + Euclid::rem_euclid(&-x, &y) + x + <= 46.4 * <$t as ::float::FloatCore>::epsilon()); + assert!(Euclid::div_euclid(&-x, &-y) * -y + Euclid::rem_euclid(&-x, &-y) + x + <= 46.4 * <$t as ::float::FloatCore>::epsilon()); + } + )+ + }; + } + + test_euclid!(f32 f64); + } + + #[test] + fn euclid_checked() { + macro_rules! test_euclid_checked { + ($($t:ident)+) => { + $( + { + assert_eq!(CheckedEuclid::checked_div_euclid(&$t::min_value(), &-1), None); + assert_eq!(CheckedEuclid::checked_rem_euclid(&$t::min_value(), &-1), None); + assert_eq!(CheckedEuclid::checked_div_euclid(&1, &0), None); + assert_eq!(CheckedEuclid::checked_rem_euclid(&1, &0), None); + } + )+ + }; + } + + test_euclid_checked!(isize i8 i16 i32 i64); + } +} diff --git a/bash-5.1/vendor/num-traits/src/ops/inv.rs b/bash-5.1/vendor/num-traits/src/ops/inv.rs new file mode 100644 index 0000000..7087d09 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/inv.rs @@ -0,0 +1,47 @@ +/// Unary operator for retrieving the multiplicative inverse, or reciprocal, of a value. +pub trait Inv { + /// The result after applying the operator. + type Output; + + /// Returns the multiplicative inverse of `self`. + /// + /// # Examples + /// + /// ``` + /// use std::f64::INFINITY; + /// use num_traits::Inv; + /// + /// assert_eq!(7.0.inv() * 7.0, 1.0); + /// assert_eq!((-0.0).inv(), -INFINITY); + /// ``` + fn inv(self) -> Self::Output; +} + +impl Inv for f32 { + type Output = f32; + #[inline] + fn inv(self) -> f32 { + 1.0 / self + } +} +impl Inv for f64 { + type Output = f64; + #[inline] + fn inv(self) -> f64 { + 1.0 / self + } +} +impl<'a> Inv for &'a f32 { + type Output = f32; + #[inline] + fn inv(self) -> f32 { + 1.0 / *self + } +} +impl<'a> Inv for &'a f64 { + type Output = f64; + #[inline] + fn inv(self) -> f64 { + 1.0 / *self + } +} diff --git a/bash-5.1/vendor/num-traits/src/ops/mod.rs b/bash-5.1/vendor/num-traits/src/ops/mod.rs new file mode 100644 index 0000000..585879f --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/mod.rs @@ -0,0 +1,7 @@ +pub mod checked; +pub mod euclid; +pub mod inv; +pub mod mul_add; +pub mod overflowing; +pub mod saturating; +pub mod wrapping; diff --git a/bash-5.1/vendor/num-traits/src/ops/mul_add.rs b/bash-5.1/vendor/num-traits/src/ops/mul_add.rs new file mode 100644 index 0000000..c5835d3 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/mul_add.rs @@ -0,0 +1,151 @@ +/// Fused multiply-add. Computes `(self * a) + b` with only one rounding +/// error, yielding a more accurate result than an unfused multiply-add. +/// +/// Using `mul_add` can be more performant than an unfused multiply-add if +/// the target architecture has a dedicated `fma` CPU instruction. +/// +/// Note that `A` and `B` are `Self` by default, but this is not mandatory. +/// +/// # Example +/// +/// ``` +/// use std::f32; +/// +/// let m = 10.0_f32; +/// let x = 4.0_f32; +/// let b = 60.0_f32; +/// +/// // 100.0 +/// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); +/// +/// assert!(abs_difference <= 100.0 * f32::EPSILON); +/// ``` +pub trait MulAdd { + /// The resulting type after applying the fused multiply-add. + type Output; + + /// Performs the fused multiply-add operation. + fn mul_add(self, a: A, b: B) -> Self::Output; +} + +/// The fused multiply-add assignment operation. +pub trait MulAddAssign { + /// Performs the fused multiply-add operation. + fn mul_add_assign(&mut self, a: A, b: B); +} + +#[cfg(any(feature = "std", feature = "libm"))] +impl MulAdd for f32 { + type Output = Self; + + #[inline] + fn mul_add(self, a: Self, b: Self) -> Self::Output { + ::mul_add(self, a, b) + } +} + +#[cfg(any(feature = "std", feature = "libm"))] +impl MulAdd for f64 { + type Output = Self; + + #[inline] + fn mul_add(self, a: Self, b: Self) -> Self::Output { + ::mul_add(self, a, b) + } +} + +macro_rules! mul_add_impl { + ($trait_name:ident for $($t:ty)*) => {$( + impl $trait_name for $t { + type Output = Self; + + #[inline] + fn mul_add(self, a: Self, b: Self) -> Self::Output { + (self * a) + b + } + } + )*} +} + +mul_add_impl!(MulAdd for isize usize i8 u8 i16 u16 i32 u32 i64 u64); +#[cfg(has_i128)] +mul_add_impl!(MulAdd for i128 u128); + +#[cfg(any(feature = "std", feature = "libm"))] +impl MulAddAssign for f32 { + #[inline] + fn mul_add_assign(&mut self, a: Self, b: Self) { + *self = ::mul_add(*self, a, b) + } +} + +#[cfg(any(feature = "std", feature = "libm"))] +impl MulAddAssign for f64 { + #[inline] + fn mul_add_assign(&mut self, a: Self, b: Self) { + *self = ::mul_add(*self, a, b) + } +} + +macro_rules! mul_add_assign_impl { + ($trait_name:ident for $($t:ty)*) => {$( + impl $trait_name for $t { + #[inline] + fn mul_add_assign(&mut self, a: Self, b: Self) { + *self = (*self * a) + b + } + } + )*} +} + +mul_add_assign_impl!(MulAddAssign for isize usize i8 u8 i16 u16 i32 u32 i64 u64); +#[cfg(has_i128)] +mul_add_assign_impl!(MulAddAssign for i128 u128); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mul_add_integer() { + macro_rules! test_mul_add { + ($($t:ident)+) => { + $( + { + let m: $t = 2; + let x: $t = 3; + let b: $t = 4; + + assert_eq!(MulAdd::mul_add(m, x, b), (m*x + b)); + } + )+ + }; + } + + test_mul_add!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); + } + + #[test] + #[cfg(feature = "std")] + fn mul_add_float() { + macro_rules! test_mul_add { + ($($t:ident)+) => { + $( + { + use core::$t; + + let m: $t = 12.0; + let x: $t = 3.4; + let b: $t = 5.6; + + let abs_difference = (MulAdd::mul_add(m, x, b) - (m*x + b)).abs(); + + assert!(abs_difference <= 46.4 * $t::EPSILON); + } + )+ + }; + } + + test_mul_add!(f32 f64); + } +} diff --git a/bash-5.1/vendor/num-traits/src/ops/overflowing.rs b/bash-5.1/vendor/num-traits/src/ops/overflowing.rs new file mode 100644 index 0000000..56118a0 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/overflowing.rs @@ -0,0 +1,104 @@ +use core::ops::{Add, Mul, Sub}; +#[cfg(has_i128)] +use core::{i128, u128}; +use core::{i16, i32, i64, i8, isize}; +use core::{u16, u32, u64, u8, usize}; + +macro_rules! overflowing_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &Self) -> (Self, bool) { + <$t>::$method(*self, *v) + } + } + }; +} + +/// Performs addition with a flag for overflow. +pub trait OverflowingAdd: Sized + Add { + /// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow would occur. + /// If an overflow would have occurred then the wrapped value is returned. + fn overflowing_add(&self, v: &Self) -> (Self, bool); +} + +overflowing_impl!(OverflowingAdd, overflowing_add, u8); +overflowing_impl!(OverflowingAdd, overflowing_add, u16); +overflowing_impl!(OverflowingAdd, overflowing_add, u32); +overflowing_impl!(OverflowingAdd, overflowing_add, u64); +overflowing_impl!(OverflowingAdd, overflowing_add, usize); +#[cfg(has_i128)] +overflowing_impl!(OverflowingAdd, overflowing_add, u128); + +overflowing_impl!(OverflowingAdd, overflowing_add, i8); +overflowing_impl!(OverflowingAdd, overflowing_add, i16); +overflowing_impl!(OverflowingAdd, overflowing_add, i32); +overflowing_impl!(OverflowingAdd, overflowing_add, i64); +overflowing_impl!(OverflowingAdd, overflowing_add, isize); +#[cfg(has_i128)] +overflowing_impl!(OverflowingAdd, overflowing_add, i128); + +/// Performs substraction with a flag for overflow. +pub trait OverflowingSub: Sized + Sub { + /// Returns a tuple of the difference along with a boolean indicating whether an arithmetic overflow would occur. + /// If an overflow would have occurred then the wrapped value is returned. + fn overflowing_sub(&self, v: &Self) -> (Self, bool); +} + +overflowing_impl!(OverflowingSub, overflowing_sub, u8); +overflowing_impl!(OverflowingSub, overflowing_sub, u16); +overflowing_impl!(OverflowingSub, overflowing_sub, u32); +overflowing_impl!(OverflowingSub, overflowing_sub, u64); +overflowing_impl!(OverflowingSub, overflowing_sub, usize); +#[cfg(has_i128)] +overflowing_impl!(OverflowingSub, overflowing_sub, u128); + +overflowing_impl!(OverflowingSub, overflowing_sub, i8); +overflowing_impl!(OverflowingSub, overflowing_sub, i16); +overflowing_impl!(OverflowingSub, overflowing_sub, i32); +overflowing_impl!(OverflowingSub, overflowing_sub, i64); +overflowing_impl!(OverflowingSub, overflowing_sub, isize); +#[cfg(has_i128)] +overflowing_impl!(OverflowingSub, overflowing_sub, i128); + +/// Performs multiplication with a flag for overflow. +pub trait OverflowingMul: Sized + Mul { + /// Returns a tuple of the product along with a boolean indicating whether an arithmetic overflow would occur. + /// If an overflow would have occurred then the wrapped value is returned. + fn overflowing_mul(&self, v: &Self) -> (Self, bool); +} + +overflowing_impl!(OverflowingMul, overflowing_mul, u8); +overflowing_impl!(OverflowingMul, overflowing_mul, u16); +overflowing_impl!(OverflowingMul, overflowing_mul, u32); +overflowing_impl!(OverflowingMul, overflowing_mul, u64); +overflowing_impl!(OverflowingMul, overflowing_mul, usize); +#[cfg(has_i128)] +overflowing_impl!(OverflowingMul, overflowing_mul, u128); + +overflowing_impl!(OverflowingMul, overflowing_mul, i8); +overflowing_impl!(OverflowingMul, overflowing_mul, i16); +overflowing_impl!(OverflowingMul, overflowing_mul, i32); +overflowing_impl!(OverflowingMul, overflowing_mul, i64); +overflowing_impl!(OverflowingMul, overflowing_mul, isize); +#[cfg(has_i128)] +overflowing_impl!(OverflowingMul, overflowing_mul, i128); + +#[test] +fn test_overflowing_traits() { + fn overflowing_add(a: T, b: T) -> (T, bool) { + a.overflowing_add(&b) + } + fn overflowing_sub(a: T, b: T) -> (T, bool) { + a.overflowing_sub(&b) + } + fn overflowing_mul(a: T, b: T) -> (T, bool) { + a.overflowing_mul(&b) + } + assert_eq!(overflowing_add(5i16, 2), (7, false)); + assert_eq!(overflowing_add(i16::MAX, 1), (i16::MIN, true)); + assert_eq!(overflowing_sub(5i16, 2), (3, false)); + assert_eq!(overflowing_sub(i16::MIN, 1), (i16::MAX, true)); + assert_eq!(overflowing_mul(5i16, 2), (10, false)); + assert_eq!(overflowing_mul(1_000_000_000i32, 10), (1410065408, true)); +} diff --git a/bash-5.1/vendor/num-traits/src/ops/saturating.rs b/bash-5.1/vendor/num-traits/src/ops/saturating.rs new file mode 100644 index 0000000..e39cfd7 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/saturating.rs @@ -0,0 +1,137 @@ +use core::ops::{Add, Mul, Sub}; + +/// Saturating math operations. Deprecated, use `SaturatingAdd`, `SaturatingSub` and +/// `SaturatingMul` instead. +pub trait Saturating { + /// Saturating addition operator. + /// Returns a+b, saturating at the numeric bounds instead of overflowing. + fn saturating_add(self, v: Self) -> Self; + + /// Saturating subtraction operator. + /// Returns a-b, saturating at the numeric bounds instead of overflowing. + fn saturating_sub(self, v: Self) -> Self; +} + +macro_rules! deprecated_saturating_impl { + ($trait_name:ident for $($t:ty)*) => {$( + impl $trait_name for $t { + #[inline] + fn saturating_add(self, v: Self) -> Self { + Self::saturating_add(self, v) + } + + #[inline] + fn saturating_sub(self, v: Self) -> Self { + Self::saturating_sub(self, v) + } + } + )*} +} + +deprecated_saturating_impl!(Saturating for isize usize i8 u8 i16 u16 i32 u32 i64 u64); +#[cfg(has_i128)] +deprecated_saturating_impl!(Saturating for i128 u128); + +macro_rules! saturating_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &Self) -> Self { + <$t>::$method(*self, *v) + } + } + }; +} + +/// Performs addition that saturates at the numeric bounds instead of overflowing. +pub trait SaturatingAdd: Sized + Add { + /// Saturating addition. Computes `self + other`, saturating at the relevant high or low boundary of + /// the type. + fn saturating_add(&self, v: &Self) -> Self; +} + +saturating_impl!(SaturatingAdd, saturating_add, u8); +saturating_impl!(SaturatingAdd, saturating_add, u16); +saturating_impl!(SaturatingAdd, saturating_add, u32); +saturating_impl!(SaturatingAdd, saturating_add, u64); +saturating_impl!(SaturatingAdd, saturating_add, usize); +#[cfg(has_i128)] +saturating_impl!(SaturatingAdd, saturating_add, u128); + +saturating_impl!(SaturatingAdd, saturating_add, i8); +saturating_impl!(SaturatingAdd, saturating_add, i16); +saturating_impl!(SaturatingAdd, saturating_add, i32); +saturating_impl!(SaturatingAdd, saturating_add, i64); +saturating_impl!(SaturatingAdd, saturating_add, isize); +#[cfg(has_i128)] +saturating_impl!(SaturatingAdd, saturating_add, i128); + +/// Performs subtraction that saturates at the numeric bounds instead of overflowing. +pub trait SaturatingSub: Sized + Sub { + /// Saturating subtraction. Computes `self - other`, saturating at the relevant high or low boundary of + /// the type. + fn saturating_sub(&self, v: &Self) -> Self; +} + +saturating_impl!(SaturatingSub, saturating_sub, u8); +saturating_impl!(SaturatingSub, saturating_sub, u16); +saturating_impl!(SaturatingSub, saturating_sub, u32); +saturating_impl!(SaturatingSub, saturating_sub, u64); +saturating_impl!(SaturatingSub, saturating_sub, usize); +#[cfg(has_i128)] +saturating_impl!(SaturatingSub, saturating_sub, u128); + +saturating_impl!(SaturatingSub, saturating_sub, i8); +saturating_impl!(SaturatingSub, saturating_sub, i16); +saturating_impl!(SaturatingSub, saturating_sub, i32); +saturating_impl!(SaturatingSub, saturating_sub, i64); +saturating_impl!(SaturatingSub, saturating_sub, isize); +#[cfg(has_i128)] +saturating_impl!(SaturatingSub, saturating_sub, i128); + +/// Performs multiplication that saturates at the numeric bounds instead of overflowing. +pub trait SaturatingMul: Sized + Mul { + /// Saturating multiplication. Computes `self * other`, saturating at the relevant high or low boundary of + /// the type. + fn saturating_mul(&self, v: &Self) -> Self; +} + +saturating_impl!(SaturatingMul, saturating_mul, u8); +saturating_impl!(SaturatingMul, saturating_mul, u16); +saturating_impl!(SaturatingMul, saturating_mul, u32); +saturating_impl!(SaturatingMul, saturating_mul, u64); +saturating_impl!(SaturatingMul, saturating_mul, usize); +#[cfg(has_i128)] +saturating_impl!(SaturatingMul, saturating_mul, u128); + +saturating_impl!(SaturatingMul, saturating_mul, i8); +saturating_impl!(SaturatingMul, saturating_mul, i16); +saturating_impl!(SaturatingMul, saturating_mul, i32); +saturating_impl!(SaturatingMul, saturating_mul, i64); +saturating_impl!(SaturatingMul, saturating_mul, isize); +#[cfg(has_i128)] +saturating_impl!(SaturatingMul, saturating_mul, i128); + +// TODO: add SaturatingNeg for signed integer primitives once the saturating_neg() API is stable. + +#[test] +fn test_saturating_traits() { + fn saturating_add(a: T, b: T) -> T { + a.saturating_add(&b) + } + fn saturating_sub(a: T, b: T) -> T { + a.saturating_sub(&b) + } + fn saturating_mul(a: T, b: T) -> T { + a.saturating_mul(&b) + } + assert_eq!(saturating_add(255, 1), 255u8); + assert_eq!(saturating_add(127, 1), 127i8); + assert_eq!(saturating_add(-128, -1), -128i8); + assert_eq!(saturating_sub(0, 1), 0u8); + assert_eq!(saturating_sub(-128, 1), -128i8); + assert_eq!(saturating_sub(127, -1), 127i8); + assert_eq!(saturating_mul(255, 2), 255u8); + assert_eq!(saturating_mul(127, 2), 127i8); + assert_eq!(saturating_mul(-128, 2), -128i8); +} diff --git a/bash-5.1/vendor/num-traits/src/ops/wrapping.rs b/bash-5.1/vendor/num-traits/src/ops/wrapping.rs new file mode 100644 index 0000000..265b8f3 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/ops/wrapping.rs @@ -0,0 +1,337 @@ +use core::num::Wrapping; +use core::ops::{Add, Mul, Neg, Shl, Shr, Sub}; + +macro_rules! wrapping_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &Self) -> Self { + <$t>::$method(*self, *v) + } + } + }; + ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => { + impl $trait_name<$rhs> for $t { + #[inline] + fn $method(&self, v: &$rhs) -> Self { + <$t>::$method(*self, *v) + } + } + }; +} + +/// Performs addition that wraps around on overflow. +pub trait WrappingAdd: Sized + Add { + /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of + /// the type. + fn wrapping_add(&self, v: &Self) -> Self; +} + +wrapping_impl!(WrappingAdd, wrapping_add, u8); +wrapping_impl!(WrappingAdd, wrapping_add, u16); +wrapping_impl!(WrappingAdd, wrapping_add, u32); +wrapping_impl!(WrappingAdd, wrapping_add, u64); +wrapping_impl!(WrappingAdd, wrapping_add, usize); +#[cfg(has_i128)] +wrapping_impl!(WrappingAdd, wrapping_add, u128); + +wrapping_impl!(WrappingAdd, wrapping_add, i8); +wrapping_impl!(WrappingAdd, wrapping_add, i16); +wrapping_impl!(WrappingAdd, wrapping_add, i32); +wrapping_impl!(WrappingAdd, wrapping_add, i64); +wrapping_impl!(WrappingAdd, wrapping_add, isize); +#[cfg(has_i128)] +wrapping_impl!(WrappingAdd, wrapping_add, i128); + +/// Performs subtraction that wraps around on overflow. +pub trait WrappingSub: Sized + Sub { + /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary + /// of the type. + fn wrapping_sub(&self, v: &Self) -> Self; +} + +wrapping_impl!(WrappingSub, wrapping_sub, u8); +wrapping_impl!(WrappingSub, wrapping_sub, u16); +wrapping_impl!(WrappingSub, wrapping_sub, u32); +wrapping_impl!(WrappingSub, wrapping_sub, u64); +wrapping_impl!(WrappingSub, wrapping_sub, usize); +#[cfg(has_i128)] +wrapping_impl!(WrappingSub, wrapping_sub, u128); + +wrapping_impl!(WrappingSub, wrapping_sub, i8); +wrapping_impl!(WrappingSub, wrapping_sub, i16); +wrapping_impl!(WrappingSub, wrapping_sub, i32); +wrapping_impl!(WrappingSub, wrapping_sub, i64); +wrapping_impl!(WrappingSub, wrapping_sub, isize); +#[cfg(has_i128)] +wrapping_impl!(WrappingSub, wrapping_sub, i128); + +/// Performs multiplication that wraps around on overflow. +pub trait WrappingMul: Sized + Mul { + /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary + /// of the type. + fn wrapping_mul(&self, v: &Self) -> Self; +} + +wrapping_impl!(WrappingMul, wrapping_mul, u8); +wrapping_impl!(WrappingMul, wrapping_mul, u16); +wrapping_impl!(WrappingMul, wrapping_mul, u32); +wrapping_impl!(WrappingMul, wrapping_mul, u64); +wrapping_impl!(WrappingMul, wrapping_mul, usize); +#[cfg(has_i128)] +wrapping_impl!(WrappingMul, wrapping_mul, u128); + +wrapping_impl!(WrappingMul, wrapping_mul, i8); +wrapping_impl!(WrappingMul, wrapping_mul, i16); +wrapping_impl!(WrappingMul, wrapping_mul, i32); +wrapping_impl!(WrappingMul, wrapping_mul, i64); +wrapping_impl!(WrappingMul, wrapping_mul, isize); +#[cfg(has_i128)] +wrapping_impl!(WrappingMul, wrapping_mul, i128); + +macro_rules! wrapping_unary_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self) -> $t { + <$t>::$method(*self) + } + } + }; +} + +/// Performs a negation that does not panic. +pub trait WrappingNeg: Sized { + /// Wrapping (modular) negation. Computes `-self`, + /// wrapping around at the boundary of the type. + /// + /// Since unsigned types do not have negative equivalents + /// all applications of this function will wrap (except for `-0`). + /// For values smaller than the corresponding signed type's maximum + /// the result is the same as casting the corresponding signed value. + /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where + /// `MAX` is the corresponding signed type's maximum. + /// + /// ``` + /// use num_traits::WrappingNeg; + /// + /// assert_eq!(100i8.wrapping_neg(), -100); + /// assert_eq!((-100i8).wrapping_neg(), 100); + /// assert_eq!((-128i8).wrapping_neg(), -128); // wrapped! + /// ``` + fn wrapping_neg(&self) -> Self; +} + +wrapping_unary_impl!(WrappingNeg, wrapping_neg, u8); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, u16); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, u32); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, u64); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, usize); +#[cfg(has_i128)] +wrapping_unary_impl!(WrappingNeg, wrapping_neg, u128); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, i8); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, i16); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, i32); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, i64); +wrapping_unary_impl!(WrappingNeg, wrapping_neg, isize); +#[cfg(has_i128)] +wrapping_unary_impl!(WrappingNeg, wrapping_neg, i128); + +macro_rules! wrapping_shift_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, rhs: u32) -> $t { + <$t>::$method(*self, rhs) + } + } + }; +} + +/// Performs a left shift that does not panic. +pub trait WrappingShl: Sized + Shl { + /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, + /// where `mask` removes any high order bits of `rhs` that would + /// cause the shift to exceed the bitwidth of the type. + /// + /// ``` + /// use num_traits::WrappingShl; + /// + /// let x: u16 = 0x0001; + /// + /// assert_eq!(WrappingShl::wrapping_shl(&x, 0), 0x0001); + /// assert_eq!(WrappingShl::wrapping_shl(&x, 1), 0x0002); + /// assert_eq!(WrappingShl::wrapping_shl(&x, 15), 0x8000); + /// assert_eq!(WrappingShl::wrapping_shl(&x, 16), 0x0001); + /// ``` + fn wrapping_shl(&self, rhs: u32) -> Self; +} + +wrapping_shift_impl!(WrappingShl, wrapping_shl, u8); +wrapping_shift_impl!(WrappingShl, wrapping_shl, u16); +wrapping_shift_impl!(WrappingShl, wrapping_shl, u32); +wrapping_shift_impl!(WrappingShl, wrapping_shl, u64); +wrapping_shift_impl!(WrappingShl, wrapping_shl, usize); +#[cfg(has_i128)] +wrapping_shift_impl!(WrappingShl, wrapping_shl, u128); + +wrapping_shift_impl!(WrappingShl, wrapping_shl, i8); +wrapping_shift_impl!(WrappingShl, wrapping_shl, i16); +wrapping_shift_impl!(WrappingShl, wrapping_shl, i32); +wrapping_shift_impl!(WrappingShl, wrapping_shl, i64); +wrapping_shift_impl!(WrappingShl, wrapping_shl, isize); +#[cfg(has_i128)] +wrapping_shift_impl!(WrappingShl, wrapping_shl, i128); + +/// Performs a right shift that does not panic. +pub trait WrappingShr: Sized + Shr { + /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, + /// where `mask` removes any high order bits of `rhs` that would + /// cause the shift to exceed the bitwidth of the type. + /// + /// ``` + /// use num_traits::WrappingShr; + /// + /// let x: u16 = 0x8000; + /// + /// assert_eq!(WrappingShr::wrapping_shr(&x, 0), 0x8000); + /// assert_eq!(WrappingShr::wrapping_shr(&x, 1), 0x4000); + /// assert_eq!(WrappingShr::wrapping_shr(&x, 15), 0x0001); + /// assert_eq!(WrappingShr::wrapping_shr(&x, 16), 0x8000); + /// ``` + fn wrapping_shr(&self, rhs: u32) -> Self; +} + +wrapping_shift_impl!(WrappingShr, wrapping_shr, u8); +wrapping_shift_impl!(WrappingShr, wrapping_shr, u16); +wrapping_shift_impl!(WrappingShr, wrapping_shr, u32); +wrapping_shift_impl!(WrappingShr, wrapping_shr, u64); +wrapping_shift_impl!(WrappingShr, wrapping_shr, usize); +#[cfg(has_i128)] +wrapping_shift_impl!(WrappingShr, wrapping_shr, u128); + +wrapping_shift_impl!(WrappingShr, wrapping_shr, i8); +wrapping_shift_impl!(WrappingShr, wrapping_shr, i16); +wrapping_shift_impl!(WrappingShr, wrapping_shr, i32); +wrapping_shift_impl!(WrappingShr, wrapping_shr, i64); +wrapping_shift_impl!(WrappingShr, wrapping_shr, isize); +#[cfg(has_i128)] +wrapping_shift_impl!(WrappingShr, wrapping_shr, i128); + +// Well this is a bit funny, but all the more appropriate. +impl WrappingAdd for Wrapping +where + Wrapping: Add>, +{ + fn wrapping_add(&self, v: &Self) -> Self { + Wrapping(self.0.wrapping_add(&v.0)) + } +} +impl WrappingSub for Wrapping +where + Wrapping: Sub>, +{ + fn wrapping_sub(&self, v: &Self) -> Self { + Wrapping(self.0.wrapping_sub(&v.0)) + } +} +impl WrappingMul for Wrapping +where + Wrapping: Mul>, +{ + fn wrapping_mul(&self, v: &Self) -> Self { + Wrapping(self.0.wrapping_mul(&v.0)) + } +} +impl WrappingNeg for Wrapping +where + Wrapping: Neg>, +{ + fn wrapping_neg(&self) -> Self { + Wrapping(self.0.wrapping_neg()) + } +} +impl WrappingShl for Wrapping +where + Wrapping: Shl>, +{ + fn wrapping_shl(&self, rhs: u32) -> Self { + Wrapping(self.0.wrapping_shl(rhs)) + } +} +impl WrappingShr for Wrapping +where + Wrapping: Shr>, +{ + fn wrapping_shr(&self, rhs: u32) -> Self { + Wrapping(self.0.wrapping_shr(rhs)) + } +} + +#[test] +fn test_wrapping_traits() { + fn wrapping_add(a: T, b: T) -> T { + a.wrapping_add(&b) + } + fn wrapping_sub(a: T, b: T) -> T { + a.wrapping_sub(&b) + } + fn wrapping_mul(a: T, b: T) -> T { + a.wrapping_mul(&b) + } + fn wrapping_neg(a: T) -> T { + a.wrapping_neg() + } + fn wrapping_shl(a: T, b: u32) -> T { + a.wrapping_shl(b) + } + fn wrapping_shr(a: T, b: u32) -> T { + a.wrapping_shr(b) + } + assert_eq!(wrapping_add(255, 1), 0u8); + assert_eq!(wrapping_sub(0, 1), 255u8); + assert_eq!(wrapping_mul(255, 2), 254u8); + assert_eq!(wrapping_neg(255), 1u8); + assert_eq!(wrapping_shl(255, 8), 255u8); + assert_eq!(wrapping_shr(255, 8), 255u8); + assert_eq!(wrapping_add(255, 1), (Wrapping(255u8) + Wrapping(1u8)).0); + assert_eq!(wrapping_sub(0, 1), (Wrapping(0u8) - Wrapping(1u8)).0); + assert_eq!(wrapping_mul(255, 2), (Wrapping(255u8) * Wrapping(2u8)).0); + // TODO: Test for Wrapping::Neg. Not possible yet since core::ops::Neg was + // only added to core::num::Wrapping<_> in Rust 1.10. + assert_eq!(wrapping_shl(255, 8), (Wrapping(255u8) << 8).0); + assert_eq!(wrapping_shr(255, 8), (Wrapping(255u8) >> 8).0); +} + +#[test] +fn wrapping_is_wrappingadd() { + fn require_wrappingadd(_: &T) {} + require_wrappingadd(&Wrapping(42)); +} + +#[test] +fn wrapping_is_wrappingsub() { + fn require_wrappingsub(_: &T) {} + require_wrappingsub(&Wrapping(42)); +} + +#[test] +fn wrapping_is_wrappingmul() { + fn require_wrappingmul(_: &T) {} + require_wrappingmul(&Wrapping(42)); +} + +// TODO: Test for Wrapping::Neg. Not possible yet since core::ops::Neg was +// only added to core::num::Wrapping<_> in Rust 1.10. + +#[test] +fn wrapping_is_wrappingshl() { + fn require_wrappingshl(_: &T) {} + require_wrappingshl(&Wrapping(42)); +} + +#[test] +fn wrapping_is_wrappingshr() { + fn require_wrappingshr(_: &T) {} + require_wrappingshr(&Wrapping(42)); +} diff --git a/bash-5.1/vendor/num-traits/src/pow.rs b/bash-5.1/vendor/num-traits/src/pow.rs new file mode 100644 index 0000000..8addc21 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/pow.rs @@ -0,0 +1,262 @@ +use core::num::Wrapping; +use core::ops::Mul; +use {CheckedMul, One}; + +/// Binary operator for raising a value to a power. +pub trait Pow { + /// The result after applying the operator. + type Output; + + /// Returns `self` to the power `rhs`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::Pow; + /// assert_eq!(Pow::pow(10u32, 2u32), 100); + /// ``` + fn pow(self, rhs: RHS) -> Self::Output; +} + +macro_rules! pow_impl { + ($t:ty) => { + pow_impl!($t, u8); + pow_impl!($t, usize); + + // FIXME: these should be possible + // pow_impl!($t, u16); + // pow_impl!($t, u32); + // pow_impl!($t, u64); + }; + ($t:ty, $rhs:ty) => { + pow_impl!($t, $rhs, usize, pow); + }; + ($t:ty, $rhs:ty, $desired_rhs:ty, $method:expr) => { + impl Pow<$rhs> for $t { + type Output = $t; + #[inline] + fn pow(self, rhs: $rhs) -> $t { + ($method)(self, <$desired_rhs>::from(rhs)) + } + } + + impl<'a> Pow<&'a $rhs> for $t { + type Output = $t; + #[inline] + fn pow(self, rhs: &'a $rhs) -> $t { + ($method)(self, <$desired_rhs>::from(*rhs)) + } + } + + impl<'a> Pow<$rhs> for &'a $t { + type Output = $t; + #[inline] + fn pow(self, rhs: $rhs) -> $t { + ($method)(*self, <$desired_rhs>::from(rhs)) + } + } + + impl<'a, 'b> Pow<&'a $rhs> for &'b $t { + type Output = $t; + #[inline] + fn pow(self, rhs: &'a $rhs) -> $t { + ($method)(*self, <$desired_rhs>::from(*rhs)) + } + } + }; +} + +pow_impl!(u8, u8, u32, u8::pow); +pow_impl!(u8, u16, u32, u8::pow); +pow_impl!(u8, u32, u32, u8::pow); +pow_impl!(u8, usize); +pow_impl!(i8, u8, u32, i8::pow); +pow_impl!(i8, u16, u32, i8::pow); +pow_impl!(i8, u32, u32, i8::pow); +pow_impl!(i8, usize); +pow_impl!(u16, u8, u32, u16::pow); +pow_impl!(u16, u16, u32, u16::pow); +pow_impl!(u16, u32, u32, u16::pow); +pow_impl!(u16, usize); +pow_impl!(i16, u8, u32, i16::pow); +pow_impl!(i16, u16, u32, i16::pow); +pow_impl!(i16, u32, u32, i16::pow); +pow_impl!(i16, usize); +pow_impl!(u32, u8, u32, u32::pow); +pow_impl!(u32, u16, u32, u32::pow); +pow_impl!(u32, u32, u32, u32::pow); +pow_impl!(u32, usize); +pow_impl!(i32, u8, u32, i32::pow); +pow_impl!(i32, u16, u32, i32::pow); +pow_impl!(i32, u32, u32, i32::pow); +pow_impl!(i32, usize); +pow_impl!(u64, u8, u32, u64::pow); +pow_impl!(u64, u16, u32, u64::pow); +pow_impl!(u64, u32, u32, u64::pow); +pow_impl!(u64, usize); +pow_impl!(i64, u8, u32, i64::pow); +pow_impl!(i64, u16, u32, i64::pow); +pow_impl!(i64, u32, u32, i64::pow); +pow_impl!(i64, usize); + +#[cfg(has_i128)] +pow_impl!(u128, u8, u32, u128::pow); +#[cfg(has_i128)] +pow_impl!(u128, u16, u32, u128::pow); +#[cfg(has_i128)] +pow_impl!(u128, u32, u32, u128::pow); +#[cfg(has_i128)] +pow_impl!(u128, usize); + +#[cfg(has_i128)] +pow_impl!(i128, u8, u32, i128::pow); +#[cfg(has_i128)] +pow_impl!(i128, u16, u32, i128::pow); +#[cfg(has_i128)] +pow_impl!(i128, u32, u32, i128::pow); +#[cfg(has_i128)] +pow_impl!(i128, usize); + +pow_impl!(usize, u8, u32, usize::pow); +pow_impl!(usize, u16, u32, usize::pow); +pow_impl!(usize, u32, u32, usize::pow); +pow_impl!(usize, usize); +pow_impl!(isize, u8, u32, isize::pow); +pow_impl!(isize, u16, u32, isize::pow); +pow_impl!(isize, u32, u32, isize::pow); +pow_impl!(isize, usize); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +#[cfg(has_i128)] +pow_impl!(Wrapping); +#[cfg(has_i128)] +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); + +// FIXME: these should be possible +// pow_impl!(u8, u64); +// pow_impl!(i16, u64); +// pow_impl!(i8, u64); +// pow_impl!(u16, u64); +// pow_impl!(u32, u64); +// pow_impl!(i32, u64); +// pow_impl!(u64, u64); +// pow_impl!(i64, u64); +// pow_impl!(usize, u64); +// pow_impl!(isize, u64); + +#[cfg(any(feature = "std", feature = "libm"))] +mod float_impls { + use super::Pow; + use Float; + + pow_impl!(f32, i8, i32, ::powi); + pow_impl!(f32, u8, i32, ::powi); + pow_impl!(f32, i16, i32, ::powi); + pow_impl!(f32, u16, i32, ::powi); + pow_impl!(f32, i32, i32, ::powi); + pow_impl!(f64, i8, i32, ::powi); + pow_impl!(f64, u8, i32, ::powi); + pow_impl!(f64, i16, i32, ::powi); + pow_impl!(f64, u16, i32, ::powi); + pow_impl!(f64, i32, i32, ::powi); + pow_impl!(f32, f32, f32, ::powf); + pow_impl!(f64, f32, f64, ::powf); + pow_impl!(f64, f64, f64, ::powf); +} + +/// Raises a value to the power of exp, using exponentiation by squaring. +/// +/// Note that `0⁰` (`pow(0, 0)`) returns `1`. Mathematically this is undefined. +/// +/// # Example +/// +/// ```rust +/// use num_traits::pow; +/// +/// assert_eq!(pow(2i8, 4), 16); +/// assert_eq!(pow(6u8, 3), 216); +/// assert_eq!(pow(0u8, 0), 1); // Be aware if this case affects you +/// ``` +#[inline] +pub fn pow>(mut base: T, mut exp: usize) -> T { + if exp == 0 { + return T::one(); + } + + while exp & 1 == 0 { + base = base.clone() * base; + exp >>= 1; + } + if exp == 1 { + return base; + } + + let mut acc = base.clone(); + while exp > 1 { + exp >>= 1; + base = base.clone() * base; + if exp & 1 == 1 { + acc = acc * base.clone(); + } + } + acc +} + +/// Raises a value to the power of exp, returning `None` if an overflow occurred. +/// +/// Note that `0⁰` (`checked_pow(0, 0)`) returns `Some(1)`. Mathematically this is undefined. +/// +/// Otherwise same as the `pow` function. +/// +/// # Example +/// +/// ```rust +/// use num_traits::checked_pow; +/// +/// assert_eq!(checked_pow(2i8, 4), Some(16)); +/// assert_eq!(checked_pow(7i8, 8), None); +/// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); +/// assert_eq!(checked_pow(0u32, 0), Some(1)); // Be aware if this case affect you +/// ``` +#[inline] +pub fn checked_pow(mut base: T, mut exp: usize) -> Option { + if exp == 0 { + return Some(T::one()); + } + + macro_rules! optry { + ($expr:expr) => { + if let Some(val) = $expr { + val + } else { + return None; + } + }; + } + + while exp & 1 == 0 { + base = optry!(base.checked_mul(&base)); + exp >>= 1; + } + if exp == 1 { + return Some(base); + } + + let mut acc = base.clone(); + while exp > 1 { + exp >>= 1; + base = optry!(base.checked_mul(&base)); + if exp & 1 == 1 { + acc = optry!(acc.checked_mul(&base)); + } + } + Some(acc) +} diff --git a/bash-5.1/vendor/num-traits/src/real.rs b/bash-5.1/vendor/num-traits/src/real.rs new file mode 100644 index 0000000..8b31cce --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/real.rs @@ -0,0 +1,834 @@ +#![cfg(any(feature = "std", feature = "libm"))] + +use core::ops::Neg; + +use {Float, Num, NumCast}; + +// NOTE: These doctests have the same issue as those in src/float.rs. +// They're testing the inherent methods directly, and not those of `Real`. + +/// A trait for real number types that do not necessarily have +/// floating-point-specific characteristics such as NaN and infinity. +/// +/// See [this Wikipedia article](https://en.wikipedia.org/wiki/Real_data_type) +/// for a list of data types that could meaningfully implement this trait. +/// +/// This trait is only available with the `std` feature, or with the `libm` feature otherwise. +pub trait Real: Num + Copy + NumCast + PartialOrd + Neg { + /// Returns the smallest finite value that this type can represent. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::min_value(); + /// + /// assert_eq!(x, f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::min_positive_value(); + /// + /// assert_eq!(x, f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns epsilon, a small positive value. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::epsilon(); + /// + /// assert_eq!(x, f64::EPSILON); + /// ``` + /// + /// # Panics + /// + /// The default implementation will panic if `f32::EPSILON` cannot + /// be cast to `Self`. + fn epsilon() -> Self; + + /// Returns the largest finite value that this type can represent. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::max_value(); + /// assert_eq!(x, f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns the largest integer less than or equal to a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.99; + /// let g = 3.0; + /// + /// assert_eq!(f.floor(), 3.0); + /// assert_eq!(g.floor(), 3.0); + /// ``` + fn floor(self) -> Self; + + /// Returns the smallest integer greater than or equal to a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.01; + /// let g = 4.0; + /// + /// assert_eq!(f.ceil(), 4.0); + /// assert_eq!(g.ceil(), 4.0); + /// ``` + fn ceil(self) -> Self; + + /// Returns the nearest integer to a number. Round half-way cases away from + /// `0.0`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.3; + /// let g = -3.3; + /// + /// assert_eq!(f.round(), 3.0); + /// assert_eq!(g.round(), -3.0); + /// ``` + fn round(self) -> Self; + + /// Return the integer part of a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.3; + /// let g = -3.7; + /// + /// assert_eq!(f.trunc(), 3.0); + /// assert_eq!(g.trunc(), -3.0); + /// ``` + fn trunc(self) -> Self; + + /// Returns the fractional part of a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 3.5; + /// let y = -3.5; + /// let abs_difference_x = (x.fract() - 0.5).abs(); + /// let abs_difference_y = (y.fract() - (-0.5)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn fract(self) -> Self; + + /// Computes the absolute value of `self`. Returns `Float::nan()` if the + /// number is `Float::nan()`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = 3.5; + /// let y = -3.5; + /// + /// let abs_difference_x = (x.abs() - x).abs(); + /// let abs_difference_y = (y.abs() - (-y)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// + /// assert!(::num_traits::Float::is_nan(f64::NAN.abs())); + /// ``` + fn abs(self) -> Self; + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` + /// - `Float::nan()` if the number is `Float::nan()` + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let f = 3.5; + /// + /// assert_eq!(f.signum(), 1.0); + /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); + /// + /// assert!(f64::NAN.signum().is_nan()); + /// ``` + fn signum(self) -> Self; + + /// Returns `true` if `self` is positive, including `+0.0`, + /// `Float::infinity()`, and with newer versions of Rust `f64::NAN`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let neg_nan: f64 = -f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(f.is_sign_positive()); + /// assert!(!g.is_sign_positive()); + /// assert!(!neg_nan.is_sign_positive()); + /// ``` + fn is_sign_positive(self) -> bool; + + /// Returns `true` if `self` is negative, including `-0.0`, + /// `Float::neg_infinity()`, and with newer versions of Rust `-f64::NAN`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let nan: f64 = f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(!f.is_sign_negative()); + /// assert!(g.is_sign_negative()); + /// assert!(!nan.is_sign_negative()); + /// ``` + fn is_sign_negative(self) -> bool; + + /// Fused multiply-add. Computes `(self * a) + b` with only one rounding + /// error, yielding a more accurate result than an unfused multiply-add. + /// + /// Using `mul_add` can be more performant than an unfused multiply-add if + /// the target architecture has a dedicated `fma` CPU instruction. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let m = 10.0; + /// let x = 4.0; + /// let b = 60.0; + /// + /// // 100.0 + /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn mul_add(self, a: Self, b: Self) -> Self; + + /// Take the reciprocal (inverse) of a number, `1/x`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let abs_difference = (x.recip() - (1.0/x)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn recip(self) -> Self; + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let abs_difference = (x.powi(2) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powi(self, n: i32) -> Self; + + /// Raise a number to a real number power. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let abs_difference = (x.powf(2.0) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powf(self, n: Self) -> Self; + + /// Take the square root of a number. + /// + /// Returns NaN if `self` is a negative floating-point number. + /// + /// # Panics + /// + /// If the implementing type doesn't support NaN, this method should panic if `self < 0`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let positive = 4.0; + /// let negative = -4.0; + /// + /// let abs_difference = (positive.sqrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// assert!(::num_traits::Float::is_nan(negative.sqrt())); + /// ``` + fn sqrt(self) -> Self; + + /// Returns `e^(self)`, (the exponential function). + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp(self) -> Self; + + /// Returns `2^(self)`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 2.0; + /// + /// // 2^2 - 4 == 0 + /// let abs_difference = (f.exp2() - 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp2(self) -> Self; + + /// Returns the natural logarithm of the number. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln(self) -> Self; + + /// Returns the logarithm of the number with respect to an arbitrary base. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let ten = 10.0; + /// let two = 2.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); + /// + /// // log2(2) - 1 == 0 + /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); + /// + /// assert!(abs_difference_10 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn log(self, base: Self) -> Self; + + /// Returns the base 2 logarithm of the number. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let two = 2.0; + /// + /// // log2(2) - 1 == 0 + /// let abs_difference = (two.log2() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log2(self) -> Self; + + /// Returns the base 10 logarithm of the number. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let ten = 10.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference = (ten.log10() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log10(self) -> Self; + + /// Converts radians to degrees. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = consts::PI; + /// + /// let abs_difference = (angle.to_degrees() - 180.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn to_degrees(self) -> Self; + + /// Converts degrees to radians. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = 180.0_f64; + /// + /// let abs_difference = (angle.to_radians() - consts::PI).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn to_radians(self) -> Self; + + /// Returns the maximum of the two numbers. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.max(y), y); + /// ``` + fn max(self, other: Self) -> Self; + + /// Returns the minimum of the two numbers. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.min(y), x); + /// ``` + fn min(self, other: Self) -> Self; + + /// The positive difference of two numbers. + /// + /// * If `self <= other`: `0:0` + /// * Else: `self - other` + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 3.0; + /// let y = -3.0; + /// + /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); + /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn abs_sub(self, other: Self) -> Self; + + /// Take the cubic root of a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 8.0; + /// + /// // x^(1/3) - 2 == 0 + /// let abs_difference = (x.cbrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cbrt(self) -> Self; + + /// Calculate the length of the hypotenuse of a right-angle triangle given + /// legs of length `x` and `y`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let y = 3.0; + /// + /// // sqrt(x^2 + y^2) + /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn hypot(self, other: Self) -> Self; + + /// Computes the sine of a number (in radians). + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::PI/2.0; + /// + /// let abs_difference = (x.sin() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sin(self) -> Self; + + /// Computes the cosine of a number (in radians). + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = 2.0*f64::consts::PI; + /// + /// let abs_difference = (x.cos() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cos(self) -> Self; + + /// Computes the tangent of a number (in radians). + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let abs_difference = (x.tan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-14); + /// ``` + fn tan(self) -> Self; + + /// Computes the arcsine of a number. Return value is in radians in + /// the range [-pi/2, pi/2] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// # Panics + /// + /// If this type does not support a NaN representation, this function should panic + /// if the number is outside the range [-1, 1]. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let f = f64::consts::PI / 2.0; + /// + /// // asin(sin(pi/2)) + /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn asin(self) -> Self; + + /// Computes the arccosine of a number. Return value is in radians in + /// the range [0, pi] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// # Panics + /// + /// If this type does not support a NaN representation, this function should panic + /// if the number is outside the range [-1, 1]. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let f = f64::consts::PI / 4.0; + /// + /// // acos(cos(pi/4)) + /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn acos(self) -> Self; + + /// Computes the arctangent of a number. Return value is in radians in the + /// range [-pi/2, pi/2]; + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 1.0; + /// + /// // atan(tan(1)) + /// let abs_difference = (f.tan().atan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn atan(self) -> Self; + + /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). + /// + /// * `x = 0`, `y = 0`: `0` + /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` + /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` + /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let pi = f64::consts::PI; + /// // All angles from horizontal right (+x) + /// // 45 deg counter-clockwise + /// let x1 = 3.0; + /// let y1 = -3.0; + /// + /// // 135 deg clockwise + /// let x2 = -3.0; + /// let y2 = 3.0; + /// + /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); + /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); + /// + /// assert!(abs_difference_1 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn atan2(self, other: Self) -> Self; + + /// Simultaneously computes the sine and cosine of the number, `x`. Returns + /// `(sin(x), cos(x))`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let f = x.sin_cos(); + /// + /// let abs_difference_0 = (f.0 - x.sin()).abs(); + /// let abs_difference_1 = (f.1 - x.cos()).abs(); + /// + /// assert!(abs_difference_0 < 1e-10); + /// assert!(abs_difference_0 < 1e-10); + /// ``` + fn sin_cos(self) -> (Self, Self); + + /// Returns `e^(self) - 1` in a way that is accurate even if the + /// number is close to zero. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 7.0; + /// + /// // e^(ln(7)) - 1 + /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp_m1(self) -> Self; + + /// Returns `ln(1+n)` (natural logarithm) more accurately than if + /// the operations were performed separately. + /// + /// # Panics + /// + /// If this type does not support a NaN representation, this function should panic + /// if `self-1 <= 0`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::E - 1.0; + /// + /// // ln(1 + (e - 1)) == ln(e) == 1 + /// let abs_difference = (x.ln_1p() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln_1p(self) -> Self; + + /// Hyperbolic sine function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.sinh(); + /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` + /// let g = (e*e - 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sinh(self) -> Self; + + /// Hyperbolic cosine function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// let f = x.cosh(); + /// // Solving cosh() at 1 gives this result + /// let g = (e*e + 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// // Same result + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn cosh(self) -> Self; + + /// Hyperbolic tangent function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.tanh(); + /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` + /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn tanh(self) -> Self; + + /// Inverse hyperbolic sine function. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let f = x.sinh().asinh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn asinh(self) -> Self; + + /// Inverse hyperbolic cosine function. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let f = x.cosh().acosh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn acosh(self) -> Self; + + /// Inverse hyperbolic tangent function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let f = e.tanh().atanh(); + /// + /// let abs_difference = (f - e).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn atanh(self) -> Self; +} + +impl Real for T { + forward! { + Float::min_value() -> Self; + Float::min_positive_value() -> Self; + Float::epsilon() -> Self; + Float::max_value() -> Self; + } + forward! { + Float::floor(self) -> Self; + Float::ceil(self) -> Self; + Float::round(self) -> Self; + Float::trunc(self) -> Self; + Float::fract(self) -> Self; + Float::abs(self) -> Self; + Float::signum(self) -> Self; + Float::is_sign_positive(self) -> bool; + Float::is_sign_negative(self) -> bool; + Float::mul_add(self, a: Self, b: Self) -> Self; + Float::recip(self) -> Self; + Float::powi(self, n: i32) -> Self; + Float::powf(self, n: Self) -> Self; + Float::sqrt(self) -> Self; + Float::exp(self) -> Self; + Float::exp2(self) -> Self; + Float::ln(self) -> Self; + Float::log(self, base: Self) -> Self; + Float::log2(self) -> Self; + Float::log10(self) -> Self; + Float::to_degrees(self) -> Self; + Float::to_radians(self) -> Self; + Float::max(self, other: Self) -> Self; + Float::min(self, other: Self) -> Self; + Float::abs_sub(self, other: Self) -> Self; + Float::cbrt(self) -> Self; + Float::hypot(self, other: Self) -> Self; + Float::sin(self) -> Self; + Float::cos(self) -> Self; + Float::tan(self) -> Self; + Float::asin(self) -> Self; + Float::acos(self) -> Self; + Float::atan(self) -> Self; + Float::atan2(self, other: Self) -> Self; + Float::sin_cos(self) -> (Self, Self); + Float::exp_m1(self) -> Self; + Float::ln_1p(self) -> Self; + Float::sinh(self) -> Self; + Float::cosh(self) -> Self; + Float::tanh(self) -> Self; + Float::asinh(self) -> Self; + Float::acosh(self) -> Self; + Float::atanh(self) -> Self; + } +} diff --git a/bash-5.1/vendor/num-traits/src/sign.rs b/bash-5.1/vendor/num-traits/src/sign.rs new file mode 100644 index 0000000..5c32071 --- /dev/null +++ b/bash-5.1/vendor/num-traits/src/sign.rs @@ -0,0 +1,224 @@ +use core::num::Wrapping; +use core::ops::Neg; + +use float::FloatCore; +use Num; + +/// Useful functions for signed numbers (i.e. numbers that can be negative). +pub trait Signed: Sized + Num + Neg { + /// Computes the absolute value. + /// + /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`. + /// + /// For signed integers, `::MIN` will be returned if the number is `::MIN`. + fn abs(&self) -> Self; + + /// The positive difference of two numbers. + /// + /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference + /// between `self` and `other` is returned. + fn abs_sub(&self, other: &Self) -> Self; + + /// Returns the sign of the number. + /// + /// For `f32` and `f64`: + /// + /// * `1.0` if the number is positive, `+0.0` or `INFINITY` + /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` + /// * `NaN` if the number is `NaN` + /// + /// For signed integers: + /// + /// * `0` if the number is zero + /// * `1` if the number is positive + /// * `-1` if the number is negative + fn signum(&self) -> Self; + + /// Returns true if the number is positive and false if the number is zero or negative. + fn is_positive(&self) -> bool; + + /// Returns true if the number is negative and false if the number is zero or positive. + fn is_negative(&self) -> bool; +} + +macro_rules! signed_impl { + ($($t:ty)*) => ($( + impl Signed for $t { + #[inline] + fn abs(&self) -> $t { + if self.is_negative() { -*self } else { *self } + } + + #[inline] + fn abs_sub(&self, other: &$t) -> $t { + if *self <= *other { 0 } else { *self - *other } + } + + #[inline] + fn signum(&self) -> $t { + match *self { + n if n > 0 => 1, + 0 => 0, + _ => -1, + } + } + + #[inline] + fn is_positive(&self) -> bool { *self > 0 } + + #[inline] + fn is_negative(&self) -> bool { *self < 0 } + } + )*) +} + +signed_impl!(isize i8 i16 i32 i64); + +#[cfg(has_i128)] +signed_impl!(i128); + +impl Signed for Wrapping +where + Wrapping: Num + Neg>, +{ + #[inline] + fn abs(&self) -> Self { + Wrapping(self.0.abs()) + } + + #[inline] + fn abs_sub(&self, other: &Self) -> Self { + Wrapping(self.0.abs_sub(&other.0)) + } + + #[inline] + fn signum(&self) -> Self { + Wrapping(self.0.signum()) + } + + #[inline] + fn is_positive(&self) -> bool { + self.0.is_positive() + } + + #[inline] + fn is_negative(&self) -> bool { + self.0.is_negative() + } +} + +macro_rules! signed_float_impl { + ($t:ty) => { + impl Signed for $t { + /// Computes the absolute value. Returns `NAN` if the number is `NAN`. + #[inline] + fn abs(&self) -> $t { + FloatCore::abs(*self) + } + + /// The positive difference of two numbers. Returns `0.0` if the number is + /// less than or equal to `other`, otherwise the difference between`self` + /// and `other` is returned. + #[inline] + fn abs_sub(&self, other: &$t) -> $t { + if *self <= *other { + 0. + } else { + *self - *other + } + } + + /// # Returns + /// + /// - `1.0` if the number is positive, `+0.0` or `INFINITY` + /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` + /// - `NAN` if the number is NaN + #[inline] + fn signum(&self) -> $t { + FloatCore::signum(*self) + } + + /// Returns `true` if the number is positive, including `+0.0` and `INFINITY` + #[inline] + fn is_positive(&self) -> bool { + FloatCore::is_sign_positive(*self) + } + + /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY` + #[inline] + fn is_negative(&self) -> bool { + FloatCore::is_sign_negative(*self) + } + } + }; +} + +signed_float_impl!(f32); +signed_float_impl!(f64); + +/// Computes the absolute value. +/// +/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN` +/// +/// For signed integers, `::MIN` will be returned if the number is `::MIN`. +#[inline(always)] +pub fn abs(value: T) -> T { + value.abs() +} + +/// The positive difference of two numbers. +/// +/// Returns zero if `x` is less than or equal to `y`, otherwise the difference +/// between `x` and `y` is returned. +#[inline(always)] +pub fn abs_sub(x: T, y: T) -> T { + x.abs_sub(&y) +} + +/// Returns the sign of the number. +/// +/// For `f32` and `f64`: +/// +/// * `1.0` if the number is positive, `+0.0` or `INFINITY` +/// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` +/// * `NaN` if the number is `NaN` +/// +/// For signed integers: +/// +/// * `0` if the number is zero +/// * `1` if the number is positive +/// * `-1` if the number is negative +#[inline(always)] +pub fn signum(value: T) -> T { + value.signum() +} + +/// A trait for values which cannot be negative +pub trait Unsigned: Num {} + +macro_rules! empty_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t {} + )*) +} + +empty_trait_impl!(Unsigned for usize u8 u16 u32 u64); +#[cfg(has_i128)] +empty_trait_impl!(Unsigned for u128); + +impl Unsigned for Wrapping where Wrapping: Num {} + +#[test] +fn unsigned_wrapping_is_unsigned() { + fn require_unsigned(_: &T) {} + require_unsigned(&Wrapping(42_u32)); +} + +// Commenting this out since it doesn't compile on Rust 1.8, +// because on this version Wrapping doesn't implement Neg and therefore can't +// implement Signed. +// #[test] +// fn signed_wrapping_is_signed() { +// fn require_signed(_: &T) {} +// require_signed(&Wrapping(-42)); +// } diff --git a/bash-5.1/vendor/num-traits/tests/cast.rs b/bash-5.1/vendor/num-traits/tests/cast.rs new file mode 100644 index 0000000..69310d0 --- /dev/null +++ b/bash-5.1/vendor/num-traits/tests/cast.rs @@ -0,0 +1,397 @@ +//! Tests of `num_traits::cast`. + +#![no_std] + +#[cfg(feature = "std")] +#[macro_use] +extern crate std; + +extern crate num_traits; + +use num_traits::cast::*; +use num_traits::Bounded; + +use core::{f32, f64}; +#[cfg(has_i128)] +use core::{i128, u128}; +use core::{i16, i32, i64, i8, isize}; +use core::{u16, u32, u64, u8, usize}; + +use core::fmt::Debug; +use core::mem; +use core::num::Wrapping; + +#[test] +fn to_primitive_float() { + let f32_toolarge = 1e39f64; + assert_eq!(f32_toolarge.to_f32(), Some(f32::INFINITY)); + assert_eq!((-f32_toolarge).to_f32(), Some(f32::NEG_INFINITY)); + assert_eq!((f32::MAX as f64).to_f32(), Some(f32::MAX)); + assert_eq!((-f32::MAX as f64).to_f32(), Some(-f32::MAX)); + assert_eq!(f64::INFINITY.to_f32(), Some(f32::INFINITY)); + assert_eq!((f64::NEG_INFINITY).to_f32(), Some(f32::NEG_INFINITY)); + assert!((f64::NAN).to_f32().map_or(false, |f| f.is_nan())); +} + +#[test] +fn wrapping_to_primitive() { + macro_rules! test_wrapping_to_primitive { + ($($t:ty)+) => { + $({ + let i: $t = 0; + let w = Wrapping(i); + assert_eq!(i.to_u8(), w.to_u8()); + assert_eq!(i.to_u16(), w.to_u16()); + assert_eq!(i.to_u32(), w.to_u32()); + assert_eq!(i.to_u64(), w.to_u64()); + assert_eq!(i.to_usize(), w.to_usize()); + assert_eq!(i.to_i8(), w.to_i8()); + assert_eq!(i.to_i16(), w.to_i16()); + assert_eq!(i.to_i32(), w.to_i32()); + assert_eq!(i.to_i64(), w.to_i64()); + assert_eq!(i.to_isize(), w.to_isize()); + assert_eq!(i.to_f32(), w.to_f32()); + assert_eq!(i.to_f64(), w.to_f64()); + })+ + }; + } + + test_wrapping_to_primitive!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); +} + +#[test] +fn wrapping_is_toprimitive() { + fn require_toprimitive(_: &T) {} + require_toprimitive(&Wrapping(42)); +} + +#[test] +fn wrapping_is_fromprimitive() { + fn require_fromprimitive(_: &T) {} + require_fromprimitive(&Wrapping(42)); +} + +#[test] +fn wrapping_is_numcast() { + fn require_numcast(_: &T) {} + require_numcast(&Wrapping(42)); +} + +#[test] +fn as_primitive() { + let x: f32 = (1.625f64).as_(); + assert_eq!(x, 1.625f32); + + let x: f32 = (3.14159265358979323846f64).as_(); + assert_eq!(x, 3.1415927f32); + + let x: u8 = (768i16).as_(); + assert_eq!(x, 0); +} + +#[test] +fn float_to_integer_checks_overflow() { + // This will overflow an i32 + let source: f64 = 1.0e+123f64; + + // Expect the overflow to be caught + assert_eq!(cast::(source), None); +} + +#[test] +fn cast_to_int_checks_overflow() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as isize), cast::(normal_f)); + assert_eq!(Some(normal_f as i8), cast::(normal_f)); + assert_eq!(Some(normal_f as i16), cast::(normal_f)); + assert_eq!(Some(normal_f as i32), cast::(normal_f)); + assert_eq!(Some(normal_f as i64), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +} + +#[test] +fn cast_to_unsigned_int_checks_overflow() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as usize), cast::(normal_f)); + assert_eq!(Some(normal_f as u8), cast::(normal_f)); + assert_eq!(Some(normal_f as u16), cast::(normal_f)); + assert_eq!(Some(normal_f as u32), cast::(normal_f)); + assert_eq!(Some(normal_f as u64), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +} + +#[test] +#[cfg(has_i128)] +fn cast_to_i128_checks_overflow() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as i128), cast::(normal_f)); + assert_eq!(Some(normal_f as u128), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +} + +#[cfg(feature = "std")] +fn dbg(args: ::core::fmt::Arguments) { + println!("{}", args); +} + +#[cfg(not(feature = "std"))] +fn dbg(_: ::core::fmt::Arguments) {} + +// Rust 1.8 doesn't handle cfg on macros correctly +macro_rules! dbg { ($($tok:tt)*) => { dbg(format_args!($($tok)*)) } } + +macro_rules! float_test_edge { + ($f:ident -> $($t:ident)+) => { $({ + dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t)); + + let small = if $t::MIN == 0 || mem::size_of::<$t>() < mem::size_of::<$f>() { + $t::MIN as $f - 1.0 + } else { + ($t::MIN as $f).raw_offset(1).floor() + }; + let fmin = small.raw_offset(-1); + dbg!(" testing min {}\n\tvs. {:.0}\n\tand {:.0}", $t::MIN, fmin, small); + assert_eq!(Some($t::MIN), cast::<$f, $t>($t::MIN as $f)); + assert_eq!(Some($t::MIN), cast::<$f, $t>(fmin)); + assert_eq!(None, cast::<$f, $t>(small)); + + let (max, large) = if mem::size_of::<$t>() < mem::size_of::<$f>() { + ($t::MAX, $t::MAX as $f + 1.0) + } else { + let large = $t::MAX as $f; // rounds up! + let max = large.raw_offset(-1) as $t; // the next smallest possible + assert_eq!(max.count_ones(), $f::MANTISSA_DIGITS); + (max, large) + }; + let fmax = large.raw_offset(-1); + dbg!(" testing max {}\n\tvs. {:.0}\n\tand {:.0}", max, fmax, large); + assert_eq!(Some(max), cast::<$f, $t>(max as $f)); + assert_eq!(Some(max), cast::<$f, $t>(fmax)); + assert_eq!(None, cast::<$f, $t>(large)); + + dbg!(" testing non-finite values"); + assert_eq!(None, cast::<$f, $t>($f::NAN)); + assert_eq!(None, cast::<$f, $t>($f::INFINITY)); + assert_eq!(None, cast::<$f, $t>($f::NEG_INFINITY)); + })+} +} + +trait RawOffset: Sized { + type Raw; + fn raw_offset(self, offset: Self::Raw) -> Self; +} + +impl RawOffset for f32 { + type Raw = i32; + fn raw_offset(self, offset: Self::Raw) -> Self { + unsafe { + let raw: Self::Raw = mem::transmute(self); + mem::transmute(raw + offset) + } + } +} + +impl RawOffset for f64 { + type Raw = i64; + fn raw_offset(self, offset: Self::Raw) -> Self { + unsafe { + let raw: Self::Raw = mem::transmute(self); + mem::transmute(raw + offset) + } + } +} + +#[test] +fn cast_float_to_int_edge_cases() { + float_test_edge!(f32 -> isize i8 i16 i32 i64); + float_test_edge!(f32 -> usize u8 u16 u32 u64); + float_test_edge!(f64 -> isize i8 i16 i32 i64); + float_test_edge!(f64 -> usize u8 u16 u32 u64); +} + +#[test] +#[cfg(has_i128)] +fn cast_float_to_i128_edge_cases() { + float_test_edge!(f32 -> i128 u128); + float_test_edge!(f64 -> i128 u128); +} + +macro_rules! int_test_edge { + ($f:ident -> { $($t:ident)+ } with $BigS:ident $BigU:ident ) => { $({ + fn test_edge() { + dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t)); + + match ($f::MIN as $BigS).cmp(&($t::MIN as $BigS)) { + Greater => { + assert_eq!(Some($f::MIN as $t), cast::<$f, $t>($f::MIN)); + } + Equal => { + assert_eq!(Some($t::MIN), cast::<$f, $t>($f::MIN)); + } + Less => { + let min = $t::MIN as $f; + assert_eq!(Some($t::MIN), cast::<$f, $t>(min)); + assert_eq!(None, cast::<$f, $t>(min - 1)); + } + } + + match ($f::MAX as $BigU).cmp(&($t::MAX as $BigU)) { + Greater => { + let max = $t::MAX as $f; + assert_eq!(Some($t::MAX), cast::<$f, $t>(max)); + assert_eq!(None, cast::<$f, $t>(max + 1)); + } + Equal => { + assert_eq!(Some($t::MAX), cast::<$f, $t>($f::MAX)); + } + Less => { + assert_eq!(Some($f::MAX as $t), cast::<$f, $t>($f::MAX)); + } + } + } + test_edge(); + })+} +} + +#[test] +fn cast_int_to_int_edge_cases() { + use core::cmp::Ordering::*; + + macro_rules! test_edge { + ($( $from:ident )+) => { $({ + int_test_edge!($from -> { isize i8 i16 i32 i64 } with i64 u64); + int_test_edge!($from -> { usize u8 u16 u32 u64 } with i64 u64); + })+} + } + + test_edge!(isize i8 i16 i32 i64); + test_edge!(usize u8 u16 u32 u64); +} + +#[test] +#[cfg(has_i128)] +fn cast_int_to_128_edge_cases() { + use core::cmp::Ordering::*; + + macro_rules! test_edge { + ($( $t:ident )+) => { + $( + int_test_edge!($t -> { i128 u128 } with i128 u128); + )+ + int_test_edge!(i128 -> { $( $t )+ } with i128 u128); + int_test_edge!(u128 -> { $( $t )+ } with i128 u128); + } + } + + test_edge!(isize i8 i16 i32 i64 i128); + test_edge!(usize u8 u16 u32 u64 u128); +} + +#[test] +fn newtype_from_primitive() { + #[derive(PartialEq, Debug)] + struct New(T); + + // minimal impl + impl FromPrimitive for New { + fn from_i64(n: i64) -> Option { + T::from_i64(n).map(New) + } + + fn from_u64(n: u64) -> Option { + T::from_u64(n).map(New) + } + } + + macro_rules! assert_eq_from { + ($( $from:ident )+) => {$( + assert_eq!(T::$from(Bounded::min_value()).map(New), + New::::$from(Bounded::min_value())); + assert_eq!(T::$from(Bounded::max_value()).map(New), + New::::$from(Bounded::max_value())); + )+} + } + + fn check() { + assert_eq_from!(from_i8 from_i16 from_i32 from_i64 from_isize); + assert_eq_from!(from_u8 from_u16 from_u32 from_u64 from_usize); + assert_eq_from!(from_f32 from_f64); + } + + macro_rules! check { + ($( $ty:ty )+) => {$( check::<$ty>(); )+} + } + check!(i8 i16 i32 i64 isize); + check!(u8 u16 u32 u64 usize); +} + +#[test] +fn newtype_to_primitive() { + #[derive(PartialEq, Debug)] + struct New(T); + + // minimal impl + impl ToPrimitive for New { + fn to_i64(&self) -> Option { + self.0.to_i64() + } + + fn to_u64(&self) -> Option { + self.0.to_u64() + } + } + + macro_rules! assert_eq_to { + ($( $to:ident )+) => {$( + assert_eq!(T::$to(&Bounded::min_value()), + New::::$to(&New(Bounded::min_value()))); + assert_eq!(T::$to(&Bounded::max_value()), + New::::$to(&New(Bounded::max_value()))); + )+} + } + + fn check() { + assert_eq_to!(to_i8 to_i16 to_i32 to_i64 to_isize); + assert_eq_to!(to_u8 to_u16 to_u32 to_u64 to_usize); + assert_eq_to!(to_f32 to_f64); + } + + macro_rules! check { + ($( $ty:ty )+) => {$( check::<$ty>(); )+} + } + check!(i8 i16 i32 i64 isize); + check!(u8 u16 u32 u64 usize); +} diff --git a/bash-5.1/vendor/once_cell/.cargo-checksum.json b/bash-5.1/vendor/once_cell/.cargo-checksum.json index 9dffae3..6f8adad 100644 --- a/bash-5.1/vendor/once_cell/.cargo-checksum.json +++ b/bash-5.1/vendor/once_cell/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"1638f5757551c399130656e1daab76b0322538923a791bf39e9ec247257daf79","Cargo.lock":"417a830ee5d5359f413fdf973391bf137de7ea8b075d83dcf798f1d3de36cfda","Cargo.toml":"d083a23d498e2dbf1cb3f249bdade38715b3cb237a38b733df79f20824eec4f7","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"813d262a320611ba874c4b2488256bdb2b4073649616a1471b389d464a704301","bors.toml":"ebd69f714a49dceb8fd10ebadfea6e2767be4732fdef49eddf6239151b4bc78c","examples/bench.rs":"1597a52529f75d6c5ad0b86759a775b1d723dfa810e2016317283b13594219da","examples/bench_acquire.rs":"9f4912ca262194cb55e893c33739c85c2f4868d07905b9dd3238552b6ce8a6e4","examples/bench_vs_lazy_static.rs":"d527294a2e73b53ac5faed8b316dfd1ae2a06adb31384134af21f10ce76333a5","examples/lazy_static.rs":"90541b093ed1d1cbb73f4097ff02cf80657e28264d281d6a31d96a708fdfea90","examples/reentrant_init_deadlocks.rs":"ff84929de27a848e5b155549caa96db5db5f030afca975f8ba3f3da640083001","examples/regex.rs":"4a2e0fb093c7f5bbe0fff8689fc0c670c5334344a1bfda376f5faa98a05d459f","examples/test_synchronization.rs":"88abd5c16275bb2f2d77eaecf369d97681404a77b8edd0021f24bfd377c46be3","src/imp_pl.rs":"1959494004fb0ee7443e97c4abd8be69d7173fe2b66f8fff0bca7b5c8e512525","src/imp_std.rs":"33be3a0df87e092abd68280dc72d50534d273d17eb86940e7ba2b8a45da78a70","src/lib.rs":"5320847175dc279e7abd2d98e17ab8d05b2eb7e383a4f249623b71a5209f2346","src/race.rs":"5a19afca4b5510d09ca7317b96f5642725c58b0969b2bdeb7275ed674d061e5d","tests/it.rs":"501c4ab3f4e718fa555707e9d32f3688c05e4ef8ea967e72e1c99da6bb06a0ad"},"package":"074864da206b4973b84eb91683020dbefd6a8c3f0f38e054d93954e891935e4e"} \ No newline at end of file +{"files":{"CHANGELOG.md":"f6198c1a83a8245a7b2ab062a316f3f97dfba190ac1d6bb47949e9c0cf4dac80","Cargo.lock":"e69c2663fe7efb3a4e463af446fa1367bd8e008100500137052ef15b84b02ebc","Cargo.toml":"d08e0411e5eda265a3359939f1fb646dff29ca38896222ffe0900b0af8e3ae70","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"813d262a320611ba874c4b2488256bdb2b4073649616a1471b389d464a704301","bors.toml":"ebd69f714a49dceb8fd10ebadfea6e2767be4732fdef49eddf6239151b4bc78c","examples/bench.rs":"1597a52529f75d6c5ad0b86759a775b1d723dfa810e2016317283b13594219da","examples/bench_acquire.rs":"9f4912ca262194cb55e893c33739c85c2f4868d07905b9dd3238552b6ce8a6e4","examples/bench_vs_lazy_static.rs":"d527294a2e73b53ac5faed8b316dfd1ae2a06adb31384134af21f10ce76333a5","examples/lazy_static.rs":"8bca1b264da21eceb1ccaf30477fc941bc71bedd030f1c6982ed3a7804abfb4f","examples/reentrant_init_deadlocks.rs":"ff84929de27a848e5b155549caa96db5db5f030afca975f8ba3f3da640083001","examples/regex.rs":"4a2e0fb093c7f5bbe0fff8689fc0c670c5334344a1bfda376f5faa98a05d459f","examples/test_synchronization.rs":"88abd5c16275bb2f2d77eaecf369d97681404a77b8edd0021f24bfd377c46be3","src/imp_pl.rs":"1959494004fb0ee7443e97c4abd8be69d7173fe2b66f8fff0bca7b5c8e512525","src/imp_std.rs":"33be3a0df87e092abd68280dc72d50534d273d17eb86940e7ba2b8a45da78a70","src/lib.rs":"88d2f7a63bd63f630733c86ea035b53e53f2f8d3c44f1025bc9bbe5ceaa7375f","src/race.rs":"5a19afca4b5510d09ca7317b96f5642725c58b0969b2bdeb7275ed674d061e5d","tests/it.rs":"4448a74a9898babfb943bae42ebfe3b07ec2b002ea39712127159955015d33b4"},"package":"e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1"} \ No newline at end of file diff --git a/bash-5.1/vendor/once_cell/CHANGELOG.md b/bash-5.1/vendor/once_cell/CHANGELOG.md index ffb5b1d..005ce69 100644 --- a/bash-5.1/vendor/once_cell/CHANGELOG.md +++ b/bash-5.1/vendor/once_cell/CHANGELOG.md @@ -4,6 +4,18 @@ - +## 1.15.0 + +- Increase minimal supported Rust version to 1.56.0. +- Implement `UnwindSafe` even if the `std` feature is disabled. + +## 1.14.0 + +- Add extension to `unsync` and `sync` `Lazy` mut API: + - `force_mut` + - `get_mut` + + ## 1.13.1 - Make implementation compliant with [strict provenance](https://github.com/rust-lang/rust/issues/95228). diff --git a/bash-5.1/vendor/once_cell/Cargo.toml b/bash-5.1/vendor/once_cell/Cargo.toml index e8222f1..bde77ee 100644 --- a/bash-5.1/vendor/once_cell/Cargo.toml +++ b/bash-5.1/vendor/once_cell/Cargo.toml @@ -10,9 +10,10 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2018" +edition = "2021" +rust-version = "1.56" name = "once_cell" -version = "1.13.1" +version = "1.15.0" authors = ["Aleksey Kladov "] exclude = [ "*.png", @@ -33,6 +34,7 @@ categories = [ ] license = "MIT OR Apache-2.0" repository = "https://github.com/matklad/once_cell" +resolver = "2" [package.metadata.docs.rs] all-features = true diff --git a/bash-5.1/vendor/once_cell/examples/lazy_static.rs b/bash-5.1/vendor/once_cell/examples/lazy_static.rs index f050560..3cdb19f 100644 --- a/bash-5.1/vendor/once_cell/examples/lazy_static.rs +++ b/bash-5.1/vendor/once_cell/examples/lazy_static.rs @@ -32,5 +32,5 @@ fn main() { // The same works for function-style: assert_eq!(hashmap().get(&0), Some(&"foo")); - assert_eq!(hashmap().get(&0), Some(&"bar")); + assert_eq!(hashmap().get(&1), Some(&"bar")); } diff --git a/bash-5.1/vendor/once_cell/src/imp_cs.rs b/bash-5.1/vendor/once_cell/src/imp_cs.rs new file mode 100644 index 0000000..668f18e --- /dev/null +++ b/bash-5.1/vendor/once_cell/src/imp_cs.rs @@ -0,0 +1,78 @@ +use core::panic::{RefUnwindSafe, UnwindSafe}; + +use atomic_polyfill::{AtomicBool, Ordering}; +use critical_section::{CriticalSection, Mutex}; + +use crate::unsync; + +pub(crate) struct OnceCell { + initialized: AtomicBool, + // Use `unsync::OnceCell` internally since `Mutex` does not provide + // interior mutability and to be able to re-use `get_or_try_init`. + value: Mutex>, +} + +// Why do we need `T: Send`? +// Thread A creates a `OnceCell` and shares it with +// scoped thread B, which fills the cell, which is +// then destroyed by A. That is, destructor observes +// a sent value. +unsafe impl Sync for OnceCell {} +unsafe impl Send for OnceCell {} + +impl RefUnwindSafe for OnceCell {} +impl UnwindSafe for OnceCell {} + +impl OnceCell { + pub(crate) const fn new() -> OnceCell { + OnceCell { initialized: AtomicBool::new(false), value: Mutex::new(unsync::OnceCell::new()) } + } + + pub(crate) const fn with_value(value: T) -> OnceCell { + OnceCell { + initialized: AtomicBool::new(true), + value: Mutex::new(unsync::OnceCell::with_value(value)), + } + } + + #[inline] + pub(crate) fn is_initialized(&self) -> bool { + self.initialized.load(Ordering::Acquire) + } + + #[cold] + pub(crate) fn initialize(&self, f: F) -> Result<(), E> + where + F: FnOnce() -> Result, + { + critical_section::with(|cs| { + let cell = self.value.borrow(cs); + cell.get_or_try_init(f).map(|_| { + self.initialized.store(true, Ordering::Release); + }) + }) + } + + /// Get the reference to the underlying value, without checking if the cell + /// is initialized. + /// + /// # Safety + /// + /// Caller must ensure that the cell is in initialized state, and that + /// the contents are acquired by (synchronized to) this thread. + pub(crate) unsafe fn get_unchecked(&self) -> &T { + debug_assert!(self.is_initialized()); + // SAFETY: The caller ensures that the value is initialized and access synchronized. + crate::unwrap_unchecked(self.value.borrow(CriticalSection::new()).get()) + } + + #[inline] + pub(crate) fn get_mut(&mut self) -> Option<&mut T> { + self.value.get_mut().get_mut() + } + + #[inline] + pub(crate) fn into_inner(self) -> Option { + self.value.into_inner().into_inner() + } +} diff --git a/bash-5.1/vendor/once_cell/src/lib.rs b/bash-5.1/vendor/once_cell/src/lib.rs index 70f08de..6de1e3e 100644 --- a/bash-5.1/vendor/once_cell/src/lib.rs +++ b/bash-5.1/vendor/once_cell/src/lib.rs @@ -267,7 +267,7 @@ //! //! # Minimum Supported `rustc` Version //! -//! This crate's minimum supported `rustc` version is `1.36.0`. +//! This crate's minimum supported `rustc` version is `1.56.0`. //! //! If only the `std` feature is enabled, MSRV will be updated conservatively. //! When using other features, like `parking_lot`, MSRV might be updated more frequently, up to the latest stable. @@ -348,11 +348,9 @@ pub mod unsync { cell::{Cell, UnsafeCell}, fmt, hint, mem, ops::{Deref, DerefMut}, + panic::{RefUnwindSafe, UnwindSafe}, }; - #[cfg(feature = "std")] - use std::panic::{RefUnwindSafe, UnwindSafe}; - /// A cell which can be written to only once. It is not thread safe. /// /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&` @@ -382,9 +380,7 @@ pub mod unsync { // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`, // by initializing the cell in closure and extracting the value in the // `Drop`. - #[cfg(feature = "std")] impl RefUnwindSafe for OnceCell {} - #[cfg(feature = "std")] impl UnwindSafe for OnceCell {} impl Default for OnceCell { @@ -680,7 +676,6 @@ pub mod unsync { init: Cell>, } - #[cfg(feature = "std")] impl RefUnwindSafe for Lazy where OnceCell: RefUnwindSafe {} impl fmt::Debug for Lazy { @@ -742,6 +737,25 @@ pub mod unsync { }) } + /// Forces the evaluation of this lazy value and returns a mutable reference to + /// the result. + /// + /// This is equivalent to the `DerefMut` impl, but is explicit. + /// + /// # Example + /// ``` + /// use once_cell::unsync::Lazy; + /// + /// let mut lazy = Lazy::new(|| 92); + /// + /// assert_eq!(Lazy::force_mut(&mut lazy), &92); + /// assert_eq!(*lazy, 92); + /// ``` + pub fn force_mut(this: &mut Lazy) -> &mut T { + Self::force(this); + Self::get_mut(this).unwrap_or_else(|| unreachable!()) + } + /// Gets the reference to the result of this lazy value if /// it was initialized, otherwise returns `None`. /// @@ -758,6 +772,23 @@ pub mod unsync { pub fn get(this: &Lazy) -> Option<&T> { this.cell.get() } + + /// Gets the mutable reference to the result of this lazy value if + /// it was initialized, otherwise returns `None`. + /// + /// # Example + /// ``` + /// use once_cell::unsync::Lazy; + /// + /// let mut lazy = Lazy::new(|| 92); + /// + /// assert_eq!(Lazy::get_mut(&mut lazy), None); + /// assert_eq!(*lazy, 92); + /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92)); + /// ``` + pub fn get_mut(this: &mut Lazy) -> Option<&mut T> { + this.cell.get_mut() + } } impl T> Deref for Lazy { @@ -1189,7 +1220,6 @@ pub mod sync { unsafe impl Sync for Lazy where OnceCell: Sync {} // auto-derived `Send` impl is OK. - #[cfg(feature = "std")] impl RefUnwindSafe for Lazy where OnceCell: RefUnwindSafe {} impl Lazy { @@ -1232,6 +1262,23 @@ pub mod sync { }) } + /// Forces the evaluation of this lazy value and + /// returns a mutable reference to the result. This is equivalent + /// to the `Deref` impl, but is explicit. + /// + /// # Example + /// ``` + /// use once_cell::sync::Lazy; + /// + /// let mut lazy = Lazy::new(|| 92); + /// + /// assert_eq!(Lazy::force_mut(&mut lazy), &mut 92); + /// ``` + pub fn force_mut(this: &mut Lazy) -> &mut T { + Self::force(this); + Self::get_mut(this).unwrap_or_else(|| unreachable!()) + } + /// Gets the reference to the result of this lazy value if /// it was initialized, otherwise returns `None`. /// @@ -1248,6 +1295,23 @@ pub mod sync { pub fn get(this: &Lazy) -> Option<&T> { this.cell.get() } + + /// Gets the reference to the result of this lazy value if + /// it was initialized, otherwise returns `None`. + /// + /// # Example + /// ``` + /// use once_cell::sync::Lazy; + /// + /// let mut lazy = Lazy::new(|| 92); + /// + /// assert_eq!(Lazy::get_mut(&mut lazy), None); + /// assert_eq!(&*lazy, &92); + /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92)); + /// ``` + pub fn get_mut(this: &mut Lazy) -> Option<&mut T> { + this.cell.get_mut() + } } impl T> Deref for Lazy { diff --git a/bash-5.1/vendor/once_cell/tests/it.rs b/bash-5.1/vendor/once_cell/tests/it.rs index 476f14b..410b93b 100644 --- a/bash-5.1/vendor/once_cell/tests/it.rs +++ b/bash-5.1/vendor/once_cell/tests/it.rs @@ -137,6 +137,41 @@ mod unsync { assert_eq!(called.get(), 1); } + #[test] + fn lazy_force_mut() { + let called = Cell::new(0); + let mut x = Lazy::new(|| { + called.set(called.get() + 1); + 92 + }); + assert_eq!(called.get(), 0); + let v = Lazy::force_mut(&mut x); + assert_eq!(called.get(), 1); + + *v /= 2; + assert_eq!(*x, 46); + assert_eq!(called.get(), 1); + } + + #[test] + fn lazy_get_mut() { + let called = Cell::new(0); + let mut x: Lazy = Lazy::new(|| { + called.set(called.get() + 1); + 92 + }); + + assert_eq!(called.get(), 0); + assert_eq!(*x, 92); + + let mut_ref: &mut u32 = Lazy::get_mut(&mut x).unwrap(); + assert_eq!(called.get(), 1); + + *mut_ref /= 2; + assert_eq!(*x, 46); + assert_eq!(called.get(), 1); + } + #[test] fn lazy_default() { static CALLED: AtomicUsize = AtomicUsize::new(0); diff --git a/bash-5.1/vendor/phf/.cargo-checksum.json b/bash-5.1/vendor/phf/.cargo-checksum.json new file mode 100644 index 0000000..0dce5fe --- /dev/null +++ b/bash-5.1/vendor/phf/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"6f7dab76577b5ad2e5c66d0d9599ba70cc4149cd1eba3e7f7bf7759648d428ee","src/lib.rs":"1ac7e756459c6e2833d50940a6e139705e48751335a34a98157b1a0f3692a7d7","src/map.rs":"40e21ea0ee8f7f07fe92e50d6ef58aad7e02aa829173b531e73ecb21f9baa8a7","src/ordered_map.rs":"929354c6c12dbccacf0a32fc4959b17fb0e5a0b171e981c8d20700b99c7c8aa3","src/ordered_set.rs":"0e6616b7f7be80db58c9888704a59e39b3d03c8cadafd8c64bdc6a53679f77a6","src/set.rs":"55f8378aa480ffacb088126fa3897dd307405faf6f3df90709b41388d4f6781d"},"package":"b3da44b85f8e8dfaec21adae67f95d93244b2ecf6ad2a692320598dcc8e6dd18"} \ No newline at end of file diff --git a/bash-5.1/vendor/phf/Cargo.toml b/bash-5.1/vendor/phf/Cargo.toml new file mode 100644 index 0000000..356b6a2 --- /dev/null +++ b/bash-5.1/vendor/phf/Cargo.toml @@ -0,0 +1,35 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "phf" +version = "0.7.24" +authors = ["Steven Fackler "] +description = "Runtime support for perfect hash function data structures" +license = "MIT" +repository = "https://github.com/sfackler/rust-phf" + +[lib] +name = "phf" +path = "src/lib.rs" +test = false +[dependencies.phf_macros] +version = "0.7.24" +optional = true + +[dependencies.phf_shared] +version = "0.7.24" + +[features] +core = ["phf_shared/core"] +macros = ["phf_macros"] +unicase = ["phf_shared/unicase"] diff --git a/bash-5.1/vendor/phf/src/lib.rs b/bash-5.1/vendor/phf/src/lib.rs new file mode 100644 index 0000000..28e6b86 --- /dev/null +++ b/bash-5.1/vendor/phf/src/lib.rs @@ -0,0 +1,92 @@ +//! Compile-time generated maps and sets. +//! +//! The `phf::Map` and `phf::Set` types have roughly comparable performance to +//! a standard hash table, but can be generated as compile-time static values. +//! +//! # Usage +//! +//! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`, +//! `phf_ordered_map`, and `phf_ordered_set` macros can be used to construct +//! the PHF type. This currently requires a nightly compiler. +//! +//! ```toml +//! [dependencies] +//! phf = { version = "0.7.24", features = ["macros"] } +//! ``` +//! +//! ``` +//! #![feature(proc_macro_hygiene)] +//! +//! use phf::{phf_map, phf_set}; +//! +//! static MY_MAP: phf::Map<&'static str, u32> = phf_map! { +//! "hello" => 1, +//! "world" => 2, +//! }; +//! +//! static MY_SET: phf::Set<&'static str> = phf_set! { +//! "hello world", +//! "hola mundo", +//! }; +//! +//! fn main() { +//! assert_eq!(MY_MAP["hello"], 1); +//! assert!(MY_SET.contains("hello world")); +//! } +//! ``` +//! +//! Alternatively, you can use the phf_codegen crate to generate PHF datatypes +//! in a build script. This method can be used with a stable compiler. +#![doc(html_root_url="https://docs.rs/phf/0.7")] +#![warn(missing_docs)] +#![cfg_attr(feature = "core", no_std)] + +#[cfg(not(feature = "core"))] +extern crate std as core; + +extern crate phf_shared; +#[cfg(feature = "macros")] +extern crate phf_macros; + +#[cfg(feature = "macros")] +pub use phf_macros::*; + +use core::ops::Deref; + +pub use phf_shared::PhfHash; +#[doc(inline)] +pub use map::Map; +#[doc(inline)] +pub use set::Set; +#[doc(inline)] +pub use ordered_map::OrderedMap; +#[doc(inline)] +pub use ordered_set::OrderedSet; + +pub mod map; +pub mod set; +pub mod ordered_map; +pub mod ordered_set; + +// WARNING: this is not considered part of phf's public API and is subject to +// change at any time. +// +// Basically Cow, but with the Owned version conditionally compiled +#[doc(hidden)] +pub enum Slice { + Static(&'static [T]), + #[cfg(not(feature = "core"))] + Dynamic(Vec), +} + +impl Deref for Slice { + type Target = [T]; + + fn deref(&self) -> &[T] { + match *self { + Slice::Static(t) => t, + #[cfg(not(feature = "core"))] + Slice::Dynamic(ref t) => t, + } + } +} diff --git a/bash-5.1/vendor/phf/src/map.rs b/bash-5.1/vendor/phf/src/map.rs new file mode 100644 index 0000000..f8046af --- /dev/null +++ b/bash-5.1/vendor/phf/src/map.rs @@ -0,0 +1,198 @@ +//! An immutable map constructed at compile time. +use core::borrow::Borrow; +use core::ops::Index; +use core::slice; +use core::fmt; +use core::iter::IntoIterator; +use phf_shared::{self, PhfHash}; +use Slice; + +/// An immutable map constructed at compile time. +/// +/// ## Note +/// +/// The fields of this struct are public so that they may be initialized by the +/// `phf_map!` macro and code generation. They are subject to change at any +/// time and should never be accessed directly. +pub struct Map { + #[doc(hidden)] + pub key: u64, + #[doc(hidden)] + pub disps: Slice<(u32, u32)>, + #[doc(hidden)] + pub entries: Slice<(K, V)>, +} + +impl fmt::Debug for Map where K: fmt::Debug, V: fmt::Debug { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_map().entries(self.entries()).finish() + } +} + +impl<'a, K, V, T: ?Sized> Index<&'a T> for Map where T: Eq + PhfHash, K: Borrow { + type Output = V; + + fn index(&self, k: &'a T) -> &V { + self.get(k).expect("invalid key") + } +} + +impl Map { + /// Returns true if the `Map` is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the number of entries in the `Map`. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Determines if `key` is in the `Map`. + pub fn contains_key(&self, key: &T) -> bool + where T: Eq + PhfHash, + K: Borrow + { + self.get(key).is_some() + } + + /// Returns a reference to the value that `key` maps to. + pub fn get(&self, key: &T) -> Option<&V> + where T: Eq + PhfHash, + K: Borrow + { + self.get_entry(key).map(|e| e.1) + } + + /// Returns a reference to the map's internal static instance of the given + /// key. + /// + /// This can be useful for interning schemes. + pub fn get_key(&self, key: &T) -> Option<&K> + where T: Eq + PhfHash, + K: Borrow + { + self.get_entry(key).map(|e| e.0) + } + + /// Like `get`, but returns both the key and the value. + pub fn get_entry(&self, key: &T) -> Option<(&K, &V)> + where T: Eq + PhfHash, + K: Borrow + { + let hash = phf_shared::hash(key, self.key); + let index = phf_shared::get_index(hash, &*self.disps, self.entries.len()); + let entry = &self.entries[index as usize]; + let b: &T = entry.0.borrow(); + if b == key { + Some((&entry.0, &entry.1)) + } else { + None + } + } + + /// Returns an iterator over the key/value pairs in the map. + /// + /// Entries are returned in an arbitrary but fixed order. + pub fn entries<'a>(&'a self) -> Entries<'a, K, V> { + Entries { iter: self.entries.iter() } + } + + /// Returns an iterator over the keys in the map. + /// + /// Keys are returned in an arbitrary but fixed order. + pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { + Keys { iter: self.entries() } + } + + /// Returns an iterator over the values in the map. + /// + /// Values are returned in an arbitrary but fixed order. + pub fn values<'a>(&'a self) -> Values<'a, K, V> { + Values { iter: self.entries() } + } +} + +impl<'a, K, V> IntoIterator for &'a Map { + type Item = (&'a K, &'a V); + type IntoIter = Entries<'a, K, V>; + + fn into_iter(self) -> Entries<'a, K, V> { + self.entries() + } +} + +/// An iterator over the key/value pairs in a `Map`. +pub struct Entries<'a, K: 'a, V: 'a> { + iter: slice::Iter<'a, (K, V)>, +} + +impl<'a, K, V> Iterator for Entries<'a, K, V> { + type Item = (&'a K, &'a V); + + fn next(&mut self) -> Option<(&'a K, &'a V)> { + self.iter.next().map(|&(ref k, ref v)| (k, v)) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, K, V> DoubleEndedIterator for Entries<'a, K, V> { + fn next_back(&mut self) -> Option<(&'a K, &'a V)> { + self.iter.next_back().map(|e| (&e.0, &e.1)) + } +} + +impl<'a, K, V> ExactSizeIterator for Entries<'a, K, V> {} + +/// An iterator over the keys in a `Map`. +pub struct Keys<'a, K: 'a, V: 'a> { + iter: Entries<'a, K, V>, +} + +impl<'a, K, V> Iterator for Keys<'a, K, V> { + type Item = &'a K; + + fn next(&mut self) -> Option<&'a K> { + self.iter.next().map(|e| e.0) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { + fn next_back(&mut self) -> Option<&'a K> { + self.iter.next_back().map(|e| e.0) + } +} + +impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {} + +/// An iterator over the values in a `Map`. +pub struct Values<'a, K: 'a, V: 'a> { + iter: Entries<'a, K, V>, +} + +impl<'a, K, V> Iterator for Values<'a, K, V> { + type Item = &'a V; + + fn next(&mut self) -> Option<&'a V> { + self.iter.next().map(|e| e.1) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { + fn next_back(&mut self) -> Option<&'a V> { + self.iter.next_back().map(|e| e.1) + } +} + +impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {} diff --git a/bash-5.1/vendor/phf/src/ordered_map.rs b/bash-5.1/vendor/phf/src/ordered_map.rs new file mode 100644 index 0000000..cd1d552 --- /dev/null +++ b/bash-5.1/vendor/phf/src/ordered_map.rs @@ -0,0 +1,228 @@ +//! An order-preserving immutable map constructed at compile time. +use core::borrow::Borrow; +use core::iter::IntoIterator; +use core::ops::Index; +use core::fmt; +use core::slice; +use phf_shared::{self, PhfHash}; + +use Slice; + +/// An order-preserving immutable map constructed at compile time. +/// +/// Unlike a `Map`, iteration order is guaranteed to match the definition +/// order. +/// +/// ## Note +/// +/// The fields of this struct are public so that they may be initialized by the +/// `phf_ordered_map!` macro and code generation. They are subject to change at +/// any time and should never be accessed directly. +pub struct OrderedMap { + #[doc(hidden)] + pub key: u64, + #[doc(hidden)] + pub disps: Slice<(u32, u32)>, + #[doc(hidden)] + pub idxs: Slice, + #[doc(hidden)] + pub entries: Slice<(K, V)>, +} + +impl fmt::Debug for OrderedMap where K: fmt::Debug, V: fmt::Debug { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_map().entries(self.entries()).finish() + } +} + +impl<'a, K, V, T: ?Sized> Index<&'a T> for OrderedMap where T: Eq + PhfHash, K: Borrow { + type Output = V; + + fn index(&self, k: &'a T) -> &V { + self.get(k).expect("invalid key") + } +} + +impl OrderedMap { + /// Returns the number of entries in the `Map`. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Returns true if the `Map` is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns a reference to the value that `key` maps to. + pub fn get(&self, key: &T) -> Option<&V> + where T: Eq + PhfHash, + K: Borrow + { + self.get_entry(key).map(|e| e.1) + } + + /// Returns a reference to the map's internal static instance of the given + /// key. + /// + /// This can be useful for interning schemes. + pub fn get_key(&self, key: &T) -> Option<&K> + where T: Eq + PhfHash, + K: Borrow + { + self.get_entry(key).map(|e| e.0) + } + + /// Determines if `key` is in the `Map`. + pub fn contains_key(&self, key: &T) -> bool + where T: Eq + PhfHash, + K: Borrow + { + self.get(key).is_some() + } + + /// Returns the index of the key within the list used to initialize + /// the ordered map. + pub fn get_index(&self, key: &T) -> Option + where T: Eq + PhfHash, + K: Borrow + { + self.get_internal(key).map(|(i, _)| i) + } + + /// Returns references to both the key and values at an index + /// within the list used to initialize the ordered map. See `.get_index(key)`. + pub fn index(&self, index: usize) -> Option<(&K, &V)> { + self.entries.get(index).map(|&(ref k, ref v)| (k, v)) + } + + /// Like `get`, but returns both the key and the value. + pub fn get_entry(&self, key: &T) -> Option<(&K, &V)> + where T: Eq + PhfHash, + K: Borrow + { + self.get_internal(key).map(|(_, e)| e) + } + + fn get_internal(&self, key: &T) -> Option<(usize, (&K, &V))> + where T: Eq + PhfHash, + K: Borrow + { + let hash = phf_shared::hash(key, self.key); + let idx_index = phf_shared::get_index(hash, &*self.disps, self.idxs.len()); + let idx = self.idxs[idx_index as usize]; + let entry = &self.entries[idx]; + + let b: &T = entry.0.borrow(); + if b == key { + Some((idx, (&entry.0, &entry.1))) + } else { + None + } + } + + /// Returns an iterator over the key/value pairs in the map. + /// + /// Entries are returned in the same order in which they were defined. + pub fn entries<'a>(&'a self) -> Entries<'a, K, V> { + Entries { iter: self.entries.iter() } + } + + /// Returns an iterator over the keys in the map. + /// + /// Keys are returned in the same order in which they were defined. + pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { + Keys { iter: self.entries() } + } + + /// Returns an iterator over the values in the map. + /// + /// Values are returned in the same order in which they were defined. + pub fn values<'a>(&'a self) -> Values<'a, K, V> { + Values { iter: self.entries() } + } +} + +impl<'a, K, V> IntoIterator for &'a OrderedMap { + type Item = (&'a K, &'a V); + type IntoIter = Entries<'a, K, V>; + + fn into_iter(self) -> Entries<'a, K, V> { + self.entries() + } +} + +/// An iterator over the entries in a `OrderedMap`. +pub struct Entries<'a, K: 'a, V: 'a> { + iter: slice::Iter<'a, (K, V)>, +} + +impl<'a, K, V> Iterator for Entries<'a, K, V> { + type Item = (&'a K, &'a V); + + fn next(&mut self) -> Option<(&'a K, &'a V)> { + self.iter.next().map(|e| (&e.0, &e.1)) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, K, V> DoubleEndedIterator for Entries<'a, K, V> { + fn next_back(&mut self) -> Option<(&'a K, &'a V)> { + self.iter.next_back().map(|e| (&e.0, &e.1)) + } +} + +impl<'a, K, V> ExactSizeIterator for Entries<'a, K, V> {} + +/// An iterator over the keys in a `OrderedMap`. +pub struct Keys<'a, K: 'a, V: 'a> { + iter: Entries<'a, K, V>, +} + +impl<'a, K, V> Iterator for Keys<'a, K, V> { + type Item = &'a K; + + fn next(&mut self) -> Option<&'a K> { + self.iter.next().map(|e| e.0) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { + fn next_back(&mut self) -> Option<&'a K> { + self.iter.next_back().map(|e| e.0) + } +} + +impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {} + +/// An iterator over the values in a `OrderedMap`. +pub struct Values<'a, K: 'a, V: 'a> { + iter: Entries<'a, K, V>, +} + +impl<'a, K, V> Iterator for Values<'a, K, V> { + type Item = &'a V; + + fn next(&mut self) -> Option<&'a V> { + self.iter.next().map(|e| e.1) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { + fn next_back(&mut self) -> Option<&'a V> { + self.iter.next_back().map(|e| e.1) + } +} + +impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {} diff --git a/bash-5.1/vendor/phf/src/ordered_set.rs b/bash-5.1/vendor/phf/src/ordered_set.rs new file mode 100644 index 0000000..622fad9 --- /dev/null +++ b/bash-5.1/vendor/phf/src/ordered_set.rs @@ -0,0 +1,137 @@ +//! An order-preserving immutable set constructed at compile time. +use core::borrow::Borrow; +use core::iter::IntoIterator; +use core::fmt; +use ordered_map; +use {PhfHash, OrderedMap}; + +/// An order-preserving immutable set constructed at compile time. +/// +/// Unlike a `Set`, iteration order is guaranteed to match the definition +/// order. +/// +/// ## Note +/// +/// The fields of this struct are public so that they may be initialized by the +/// `phf_ordered_set!` macro and code generation. They are subject to change at +/// any time and should never be accessed directly. +pub struct OrderedSet { + #[doc(hidden)] + pub map: OrderedMap, +} + +impl fmt::Debug for OrderedSet where T: fmt::Debug { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_set().entries(self).finish() + } +} + +impl OrderedSet { + /// Returns the number of elements in the `OrderedSet`. + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns true if the `OrderedSet` contains no elements. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns a reference to the set's internal static instance of the given + /// key. + /// + /// This can be useful for interning schemes. + pub fn get_key(&self, key: &U) -> Option<&T> + where U: Eq + PhfHash, + T: Borrow + { + self.map.get_key(key) + } + + /// Returns the index of the key within the list used to initialize + /// the ordered set. + pub fn get_index(&self, key: &U) -> Option + where U: Eq + PhfHash, + T: Borrow + { + self.map.get_index(key) + } + + /// Returns a reference to the key at an index + /// within the list used to initialize the ordered set. See `.get_index(key)`. + pub fn index(&self, index: usize) -> Option<&T> { + self.map.index(index).map(|(k, &())| k) + } + + /// Returns true if `value` is in the `Set`. + pub fn contains(&self, value: &U) -> bool + where U: Eq + PhfHash, + T: Borrow + { + self.map.contains_key(value) + } + + /// Returns an iterator over the values in the set. + /// + /// Values are returned in the same order in which they were defined. + pub fn iter<'a>(&'a self) -> Iter<'a, T> { + Iter { iter: self.map.keys() } + } +} + +impl OrderedSet where T: Eq + PhfHash { + /// Returns true if `other` shares no elements with `self`. + #[inline] + pub fn is_disjoint(&self, other: &OrderedSet) -> bool { + !self.iter().any(|value| other.contains(value)) + } + + /// Returns true if `other` contains all values in `self`. + #[inline] + pub fn is_subset(&self, other: &OrderedSet) -> bool { + self.iter().all(|value| other.contains(value)) + } + + /// Returns true if `self` contains all values in `other`. + #[inline] + pub fn is_superset(&self, other: &OrderedSet) -> bool { + other.is_subset(self) + } +} + +impl<'a, T> IntoIterator for &'a OrderedSet { + type Item = &'a T; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +/// An iterator over the values in a `OrderedSet`. +pub struct Iter<'a, T: 'a> { + iter: ordered_map::Keys<'a, T, ()>, +} + +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + + #[inline] + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, T> DoubleEndedIterator for Iter<'a, T> { + #[inline] + fn next_back(&mut self) -> Option<&'a T> { + self.iter.next_back() + } +} + +impl<'a, T> ExactSizeIterator for Iter<'a, T> {} diff --git a/bash-5.1/vendor/phf/src/set.rs b/bash-5.1/vendor/phf/src/set.rs new file mode 100644 index 0000000..04ed9a0 --- /dev/null +++ b/bash-5.1/vendor/phf/src/set.rs @@ -0,0 +1,115 @@ +//! An immutable set constructed at compile time. +use core::borrow::Borrow; +use core::iter::IntoIterator; +use core::fmt; + +use PhfHash; +use map; +use Map; + +/// An immutable set constructed at compile time. +/// +/// ## Note +/// +/// The fields of this struct are public so that they may be initialized by the +/// `phf_set!` macro and code generation. They are subject to change at any +/// time and should never be accessed directly. +pub struct Set { + #[doc(hidden)] + pub map: Map, +} + +impl fmt::Debug for Set where T: fmt::Debug { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_set().entries(self).finish() + } +} + +impl Set { + /// Returns the number of elements in the `Set`. + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns true if the `Set` contains no elements. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns a reference to the set's internal static instance of the given + /// key. + /// + /// This can be useful for interning schemes. + pub fn get_key(&self, key: &U) -> Option<&T> + where U: Eq + PhfHash, + T: Borrow + { + self.map.get_key(key) + } + + /// Returns true if `value` is in the `Set`. + pub fn contains(&self, value: &U) -> bool + where U: Eq + PhfHash, + T: Borrow + { + self.map.contains_key(value) + } + + /// Returns an iterator over the values in the set. + /// + /// Values are returned in an arbitrary but fixed order. + pub fn iter<'a>(&'a self) -> Iter<'a, T> { + Iter { iter: self.map.keys() } + } +} + +impl Set where T: Eq + PhfHash { + /// Returns true if `other` shares no elements with `self`. + pub fn is_disjoint(&self, other: &Set) -> bool { + !self.iter().any(|value| other.contains(value)) + } + + /// Returns true if `other` contains all values in `self`. + pub fn is_subset(&self, other: &Set) -> bool { + self.iter().all(|value| other.contains(value)) + } + + /// Returns true if `self` contains all values in `other`. + pub fn is_superset(&self, other: &Set) -> bool { + other.is_subset(self) + } +} + +impl<'a, T> IntoIterator for &'a Set { + type Item = &'a T; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +/// An iterator over the values in a `Set`. +pub struct Iter<'a, T: 'static> { + iter: map::Keys<'a, T, ()>, +} + +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a, T> DoubleEndedIterator for Iter<'a, T> { + fn next_back(&mut self) -> Option<&'a T> { + self.iter.next_back() + } +} + +impl<'a, T> ExactSizeIterator for Iter<'a, T> {} diff --git a/bash-5.1/vendor/phf_codegen/.cargo-checksum.json b/bash-5.1/vendor/phf_codegen/.cargo-checksum.json new file mode 100644 index 0000000..3e7ecae --- /dev/null +++ b/bash-5.1/vendor/phf_codegen/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"02ef1b1c1e389f156446953e9944c83dfd8ca424824dde3e0f987dfe0f4d16c1","src/lib.rs":"7babf32aa5ea3b8587e9c3fb4130e5db9be4c2456bf3ff4dd7fd11971a0afecf"},"package":"b03e85129e324ad4166b06b2c7491ae27fe3ec353af72e72cd1654c7225d517e"} \ No newline at end of file diff --git a/bash-5.1/vendor/phf_codegen/Cargo.toml b/bash-5.1/vendor/phf_codegen/Cargo.toml new file mode 100644 index 0000000..0ac3c19 --- /dev/null +++ b/bash-5.1/vendor/phf_codegen/Cargo.toml @@ -0,0 +1,24 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "phf_codegen" +version = "0.7.24" +authors = ["Steven Fackler "] +description = "Codegen library for PHF types" +license = "MIT" +repository = "https://github.com/sfackler/rust-phf" +[dependencies.phf_generator] +version = "0.7.24" + +[dependencies.phf_shared] +version = "0.7.24" diff --git a/bash-5.1/vendor/phf_codegen/src/lib.rs b/bash-5.1/vendor/phf_codegen/src/lib.rs new file mode 100644 index 0000000..00c04e3 --- /dev/null +++ b/bash-5.1/vendor/phf_codegen/src/lib.rs @@ -0,0 +1,341 @@ +//! A set of builders to generate Rust source for PHF data structures at +//! compile time. +//! +//! The provided builders are intended to be used in a Cargo build script to +//! generate a Rust source file that will be included in a library at build +//! time. +//! +//! # Examples +//! +//! build.rs +//! +//! ```rust,no_run +//! extern crate phf_codegen; +//! +//! use std::env; +//! use std::fs::File; +//! use std::io::{BufWriter, Write}; +//! use std::path::Path; +//! +//! fn main() { +//! let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs"); +//! let mut file = BufWriter::new(File::create(&path).unwrap()); +//! +//! write!(&mut file, "static KEYWORDS: phf::Map<&'static str, Keyword> = +//! ").unwrap(); +//! phf_codegen::Map::new() +//! .entry("loop", "Keyword::Loop") +//! .entry("continue", "Keyword::Continue") +//! .entry("break", "Keyword::Break") +//! .entry("fn", "Keyword::Fn") +//! .entry("extern", "Keyword::Extern") +//! .build(&mut file) +//! .unwrap(); +//! write!(&mut file, ";\n").unwrap(); +//! } +//! ``` +//! +//! lib.rs +//! +//! ```ignore +//! extern crate phf; +//! +//! #[derive(Clone)] +//! enum Keyword { +//! Loop, +//! Continue, +//! Break, +//! Fn, +//! Extern, +//! } +//! +//! include!(concat!(env!("OUT_DIR"), "/codegen.rs")); +//! +//! pub fn parse_keyword(keyword: &str) -> Option { +//! KEYWORDS.get(keyword).cloned() +//! } +//! ``` +//! +//! # Note +//! +//! The compiler's stack will overflow when processing extremely long method +//! chains (500+ calls). When generating large PHF data structures, consider +//! looping over the entries or making each call a separate statement: +//! +//! ```rust +//! let entries = [("hello", "1"), ("world", "2")]; +//! +//! let mut builder = phf_codegen::Map::new(); +//! for &(key, value) in &entries { +//! builder.entry(key, value); +//! } +//! // ... +//! ``` +//! +//! ```rust +//! let mut builder = phf_codegen::Map::new(); +//! builder.entry("hello", "1"); +//! builder.entry("world", "2"); +//! // ... +//! ``` +#![doc(html_root_url="https://docs.rs/phf_codegen/0.7")] +extern crate phf_shared; +extern crate phf_generator; + +use phf_shared::PhfHash; +use std::collections::HashSet; +use std::fmt; +use std::hash::Hash; +use std::io; +use std::io::prelude::*; + +/// A builder for the `phf::Map` type. +pub struct Map { + keys: Vec, + values: Vec, + path: String, +} + +impl Map { + /// Creates a new `phf::Map` builder. + pub fn new() -> Map { + // FIXME rust#27438 + // + // On Windows/MSVC there are major problems with the handling of dllimport. + // Here, because downstream build scripts only invoke generics from phf_codegen, + // the linker ends up throwing a way a bunch of static symbols we actually need. + // This works around the problem, assuming that all clients call `Map::new` by + // calling a non-generic function. + fn noop_fix_for_27438() { + } + noop_fix_for_27438(); + + Map { + keys: vec![], + values: vec![], + path: String::from("::phf"), + } + } + + /// Set the path to the `phf` crate from the global namespace + pub fn phf_path(&mut self, path: &str) -> &mut Map { + self.path = path.to_owned(); + self + } + + /// Adds an entry to the builder. + /// + /// `value` will be written exactly as provided in the constructed source. + pub fn entry(&mut self, key: K, value: &str) -> &mut Map { + self.keys.push(key); + self.values.push(value.to_owned()); + self + } + + /// Constructs a `phf::Map`, outputting Rust source to the provided writer. + /// + /// # Panics + /// + /// Panics if there are any duplicate keys. + pub fn build(&self, w: &mut W) -> io::Result<()> { + let mut set = HashSet::new(); + for key in &self.keys { + if !set.insert(key) { + panic!("duplicate key `{:?}`", key); + } + } + + let state = phf_generator::generate_hash(&self.keys); + + try!(write!(w, + "{}::Map {{ + key: {}, + disps: {}::Slice::Static(&[", + self.path, state.key, self.path)); + for &(d1, d2) in &state.disps { + try!(write!(w, + " + ({}, {}),", + d1, + d2)); + } + try!(write!(w, + " + ]), + entries: {}::Slice::Static(&[", self.path)); + for &idx in &state.map { + try!(write!(w, + " + ({:?}, {}),", + &self.keys[idx], + &self.values[idx])); + } + write!(w, + " + ]), +}}") + } +} + +/// A builder for the `phf::Set` type. +pub struct Set { + map: Map, +} + +impl Set { + /// Constructs a new `phf::Set` builder. + pub fn new() -> Set { + Set { + map: Map::new(), + } + } + + /// Set the path to the `phf` crate from the global namespace + pub fn phf_path(&mut self, path: &str) -> &mut Set { + self.map.phf_path(path); + self + } + + /// Adds an entry to the builder. + pub fn entry(&mut self, entry: T) -> &mut Set { + self.map.entry(entry, "()"); + self + } + + /// Constructs a `phf::Set`, outputting Rust source to the provided writer. + /// + /// # Panics + /// + /// Panics if there are any duplicate entries. + pub fn build(&self, w: &mut W) -> io::Result<()> { + try!(write!(w, "{}::Set {{ map: ", self.map.path)); + try!(self.map.build(w)); + write!(w, " }}") + } +} + +/// A builder for the `phf::OrderedMap` type. +pub struct OrderedMap { + keys: Vec, + values: Vec, + path: String, +} + +impl OrderedMap { + /// Constructs a enw `phf::OrderedMap` builder. + pub fn new() -> OrderedMap { + OrderedMap { + keys: vec![], + values: vec![], + path: String::from("::phf"), + } + } + + /// Set the path to the `phf` crate from the global namespace + pub fn phf_path(&mut self, path: &str) -> &mut OrderedMap { + self.path = path.to_owned(); + self + } + + /// Adds an entry to the builder. + /// + /// `value` will be written exactly as provided in the constructed source. + pub fn entry(&mut self, key: K, value: &str) -> &mut OrderedMap { + self.keys.push(key); + self.values.push(value.to_owned()); + self + } + + /// Constructs a `phf::OrderedMap`, outputting Rust source to the provided + /// writer. + /// + /// # Panics + /// + /// Panics if there are any duplicate keys. + pub fn build(&self, w: &mut W) -> io::Result<()> { + let mut set = HashSet::new(); + for key in &self.keys { + if !set.insert(key) { + panic!("duplicate key `{:?}`", key); + } + } + + let state = phf_generator::generate_hash(&self.keys); + + try!(write!(w, + "{}::OrderedMap {{ + key: {}, + disps: {}::Slice::Static(&[", + self.path, state.key, self.path)); + for &(d1, d2) in &state.disps { + try!(write!(w, + " + ({}, {}),", + d1, + d2)); + } + try!(write!(w, + " + ]), + idxs: {}::Slice::Static(&[", self.path)); + for &idx in &state.map { + try!(write!(w, + " + {},", + idx)); + } + try!(write!(w, + " + ]), + entries: {}::Slice::Static(&[", self.path)); + for (key, value) in self.keys.iter().zip(self.values.iter()) { + try!(write!(w, + " + ({:?}, {}),", + key, + value)); + } + write!(w, + " + ]), +}}") + } +} + +/// A builder for the `phf::OrderedSet` type. +pub struct OrderedSet { + map: OrderedMap, +} + +impl OrderedSet { + /// Constructs a new `phf::OrderedSet` builder. + pub fn new() -> OrderedSet { + OrderedSet { + map: OrderedMap::new(), + } + } + + /// Set the path to the `phf` crate from the global namespace + pub fn phf_path(&mut self, path: &str) -> &mut OrderedSet { + self.map.phf_path(path); + self + } + + /// Adds an entry to the builder. + pub fn entry(&mut self, entry: T) -> &mut OrderedSet { + self.map.entry(entry, "()"); + self + } + + /// Constructs a `phf::OrderedSet`, outputting Rust source to the provided + /// writer. + /// + /// # Panics + /// + /// Panics if there are any duplicate entries. + pub fn build(&self, w: &mut W) -> io::Result<()> { + try!(write!(w, "{}::OrderedSet {{ map: ", self.map.path)); + try!(self.map.build(w)); + write!(w, " }}") + } +} diff --git a/bash-5.1/vendor/phf_generator/.cargo-checksum.json b/bash-5.1/vendor/phf_generator/.cargo-checksum.json new file mode 100644 index 0000000..2230c6b --- /dev/null +++ b/bash-5.1/vendor/phf_generator/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"04fafe59f69e671fac9405597492de5acae5fc8b8517cc549738999163a92813","src/lib.rs":"f1f52ad596fe634f21b64caaf3d4c88ceb952b4ae40858f4280526c177af3a9e"},"package":"09364cc93c159b8b06b1f4dd8a4398984503483891b0c26b867cf431fb132662"} \ No newline at end of file diff --git a/bash-5.1/vendor/phf_generator/Cargo.toml b/bash-5.1/vendor/phf_generator/Cargo.toml new file mode 100644 index 0000000..e265f3a --- /dev/null +++ b/bash-5.1/vendor/phf_generator/Cargo.toml @@ -0,0 +1,24 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "phf_generator" +version = "0.7.24" +authors = ["Steven Fackler "] +description = "PHF generation logic" +license = "MIT" +repository = "https://github.com/sfackler/rust-phf" +[dependencies.phf_shared] +version = "0.7.24" + +[dependencies.rand] +version = "0.6" diff --git a/bash-5.1/vendor/phf_generator/src/lib.rs b/bash-5.1/vendor/phf_generator/src/lib.rs new file mode 100644 index 0000000..6a83340 --- /dev/null +++ b/bash-5.1/vendor/phf_generator/src/lib.rs @@ -0,0 +1,124 @@ +#![doc(html_root_url="https://docs.rs/phf_generator/0.7")] +extern crate phf_shared; +extern crate rand; + +use phf_shared::PhfHash; +use rand::{SeedableRng, Rng}; +use rand::rngs::SmallRng; + +const DEFAULT_LAMBDA: usize = 5; + +const FIXED_SEED: u64 = 1234567890; + +pub struct HashState { + pub key: u64, + pub disps: Vec<(u32, u32)>, + pub map: Vec, +} + +pub fn generate_hash(entries: &[H]) -> HashState { + let mut rng = SmallRng::seed_from_u64(FIXED_SEED); + loop { + if let Some(s) = try_generate_hash(entries, &mut rng) { + return s; + } + } +} + +fn try_generate_hash(entries: &[H], rng: &mut SmallRng) -> Option { + struct Bucket { + idx: usize, + keys: Vec, + } + + struct Hashes { + g: u32, + f1: u32, + f2: u32, + } + + let key = rng.gen(); + + let hashes: Vec<_> = entries.iter() + .map(|entry| { + let hash = phf_shared::hash(entry, key); + let (g, f1, f2) = phf_shared::split(hash); + Hashes { + g: g, + f1: f1, + f2: f2, + } + }) + .collect(); + + let buckets_len = (entries.len() + DEFAULT_LAMBDA - 1) / DEFAULT_LAMBDA; + let mut buckets = (0..buckets_len) + .map(|i| { + Bucket { + idx: i, + keys: vec![], + } + }) + .collect::>(); + + for (i, hash) in hashes.iter().enumerate() { + buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i); + } + + // Sort descending + buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse()); + + let table_len = entries.len(); + let mut map = vec![None; table_len]; + let mut disps = vec![(0u32, 0u32); buckets_len]; + + // store whether an element from the bucket being placed is + // located at a certain position, to allow for efficient overlap + // checks. It works by storing the generation in each cell and + // each new placement-attempt is a new generation, so you can tell + // if this is legitimately full by checking that the generations + // are equal. (A u64 is far too large to overflow in a reasonable + // time for current hardware.) + let mut try_map = vec![0u64; table_len]; + let mut generation = 0u64; + + // the actual values corresponding to the markers above, as + // (index, key) pairs, for adding to the main map once we've + // chosen the right disps. + let mut values_to_add = vec![]; + + 'buckets: for bucket in &buckets { + for d1 in 0..(table_len as u32) { + 'disps: for d2 in 0..(table_len as u32) { + values_to_add.clear(); + generation += 1; + + for &key in &bucket.keys { + let idx = (phf_shared::displace(hashes[key].f1, hashes[key].f2, d1, d2) % + (table_len as u32)) as usize; + if map[idx].is_some() || try_map[idx] == generation { + continue 'disps; + } + try_map[idx] = generation; + values_to_add.push((idx, key)); + } + + // We've picked a good set of disps + disps[bucket.idx] = (d1, d2); + for &(idx, key) in &values_to_add { + map[idx] = Some(key); + } + continue 'buckets; + } + } + + // Unable to find displacements for a bucket + return None; + } + + Some(HashState { + key: key, + disps: disps, + map: map.into_iter().map(|i| i.unwrap()).collect(), + }) +} diff --git a/bash-5.1/vendor/phf_shared/.cargo-checksum.json b/bash-5.1/vendor/phf_shared/.cargo-checksum.json new file mode 100644 index 0000000..4e47725 --- /dev/null +++ b/bash-5.1/vendor/phf_shared/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"1609c50abd23fa8064635f2f80301e319287b6d2c47c3688eebed04824ccb72d","src/lib.rs":"496a0f55d09c297bb44a674cccac9205243f6e3b602f884da557d6d56acbc682"},"package":"234f71a15de2288bcb7e3b6515828d22af7ec8598ee6d24c3b526fa0a80b67a0"} \ No newline at end of file diff --git a/bash-5.1/vendor/phf_shared/Cargo.toml b/bash-5.1/vendor/phf_shared/Cargo.toml new file mode 100644 index 0000000..2e3ae38 --- /dev/null +++ b/bash-5.1/vendor/phf_shared/Cargo.toml @@ -0,0 +1,33 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "phf_shared" +version = "0.7.24" +authors = ["Steven Fackler "] +description = "Support code shared by PHF libraries" +license = "MIT" +repository = "https://github.com/sfackler/rust-phf" + +[lib] +name = "phf_shared" +path = "src/lib.rs" +test = false +[dependencies.siphasher] +version = "0.2" + +[dependencies.unicase] +version = "1.4" +optional = true + +[features] +core = [] diff --git a/bash-5.1/vendor/phf_shared/src/lib.rs b/bash-5.1/vendor/phf_shared/src/lib.rs new file mode 100644 index 0000000..e840e6e --- /dev/null +++ b/bash-5.1/vendor/phf_shared/src/lib.rs @@ -0,0 +1,200 @@ +#![doc(html_root_url="https://docs.rs/phf_shared/0.7")] +#![cfg_attr(feature = "core", no_std)] + +#[cfg(not(feature = "core"))] +extern crate std as core; + +extern crate siphasher; + +#[cfg(feature = "unicase")] +extern crate unicase; + +use core::hash::{Hasher, Hash}; +use siphasher::sip::SipHasher13; + +#[inline] +pub fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { + d2 + f1 * d1 + f2 +} + +#[inline] +pub fn split(hash: u64) -> (u32, u32, u32) { + const BITS: u32 = 21; + const MASK: u64 = (1 << BITS) - 1; + + ((hash & MASK) as u32, + ((hash >> BITS) & MASK) as u32, + ((hash >> (2 * BITS)) & MASK) as u32) +} + +/// `key` is from `phf_generator::HashState::key`. +#[inline] +pub fn hash(x: &T, key: u64) -> u64 { + let mut hasher = SipHasher13::new_with_keys(0, key); + x.phf_hash(&mut hasher); + hasher.finish() +} + +/// Return an index into `phf_generator::HashState::map`. +/// +/// * `hash` is from `hash()` in this crate. +/// * `disps` is from `phf_generator::HashState::disps`. +/// * `len` is the length of `phf_generator::HashState::map`. +#[inline] +pub fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 { + let (g, f1, f2) = split(hash); + let (d1, d2) = disps[(g % (disps.len() as u32)) as usize]; + displace(f1, f2, d1, d2) % (len as u32) +} + +/// A trait implemented by types which can be used in PHF data structures. +/// +/// This differs from the standard library's `Hash` trait in that `PhfHash`'s +/// results must be architecture independent so that hashes will be consistent +/// between the host and target when cross compiling. +pub trait PhfHash { + /// Feeds the value into the state given, updating the hasher as necessary. + fn phf_hash(&self, state: &mut H); + + /// Feeds a slice of this type into the state provided. + fn phf_hash_slice(data: &[Self], state: &mut H) + where Self: Sized + { + for piece in data { + piece.phf_hash(state); + } + } +} + +#[cfg(not(feature = "core"))] +impl PhfHash for String { + #[inline] + fn phf_hash(&self, state: &mut H) { + (**self).phf_hash(state) + } +} + +#[cfg(not(feature = "core"))] +impl PhfHash for Vec { + #[inline] + fn phf_hash(&self, state: &mut H) { + (**self).phf_hash(state) + } +} + +impl<'a> PhfHash for &'a str { + #[inline] + fn phf_hash(&self, state: &mut H) { + (*self).phf_hash(state) + } +} + +impl<'a> PhfHash for &'a [u8] { + #[inline] + fn phf_hash(&self, state: &mut H) { + (*self).phf_hash(state) + } +} + +impl PhfHash for str { + #[inline] + fn phf_hash(&self, state: &mut H) { + self.as_bytes().phf_hash(state) + } +} + +impl PhfHash for [u8] { + #[inline] + fn phf_hash(&self, state: &mut H) { + state.write(self); + } +} + +#[cfg(feature = "unicase")] +impl PhfHash for unicase::UniCase +where unicase::UniCase: Hash { + #[inline] + fn phf_hash(&self, state: &mut H) { + self.hash(state) + } +} + +macro_rules! sip_impl( + (le $t:ty) => ( + impl PhfHash for $t { + #[inline] + fn phf_hash(&self, state: &mut H) { + self.to_le().hash(state); + } + } + ); + ($t:ty) => ( + impl PhfHash for $t { + #[inline] + fn phf_hash(&self, state: &mut H) { + self.hash(state); + } + } + ) +); + +sip_impl!(u8); +sip_impl!(i8); +sip_impl!(le u16); +sip_impl!(le i16); +sip_impl!(le u32); +sip_impl!(le i32); +sip_impl!(le u64); +sip_impl!(le i64); +sip_impl!(bool); + +impl PhfHash for char { + #[inline] + fn phf_hash(&self, state: &mut H) { + (*self as u32).phf_hash(state) + } +} + +macro_rules! array_impl( + ($t:ty, $n:expr) => ( + impl PhfHash for [$t; $n] { + #[inline] + fn phf_hash(&self, state: &mut H) { + state.write(self); + } + } + ) +); + +array_impl!(u8, 1); +array_impl!(u8, 2); +array_impl!(u8, 3); +array_impl!(u8, 4); +array_impl!(u8, 5); +array_impl!(u8, 6); +array_impl!(u8, 7); +array_impl!(u8, 8); +array_impl!(u8, 9); +array_impl!(u8, 10); +array_impl!(u8, 11); +array_impl!(u8, 12); +array_impl!(u8, 13); +array_impl!(u8, 14); +array_impl!(u8, 15); +array_impl!(u8, 16); +array_impl!(u8, 17); +array_impl!(u8, 18); +array_impl!(u8, 19); +array_impl!(u8, 20); +array_impl!(u8, 21); +array_impl!(u8, 22); +array_impl!(u8, 23); +array_impl!(u8, 24); +array_impl!(u8, 25); +array_impl!(u8, 26); +array_impl!(u8, 27); +array_impl!(u8, 28); +array_impl!(u8, 29); +array_impl!(u8, 30); +array_impl!(u8, 31); +array_impl!(u8, 32); diff --git a/bash-5.1/vendor/proc-macro2/.cargo-checksum.json b/bash-5.1/vendor/proc-macro2/.cargo-checksum.json index 59f2a84..8d2317f 100644 --- a/bash-5.1/vendor/proc-macro2/.cargo-checksum.json +++ b/bash-5.1/vendor/proc-macro2/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"774906eb037620dba1ef4cf6adc14ec35e7f9f81d1e2d967dfedfab8e7b603d9","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"0c17148c1957c3f721d99fc99aedaefee5f2f1ba7e2336a289b02f91609099fb","build.rs":"2c6ddbeeb1700b8dba3689185a535c672dc43e9d61b54f835cf4f3cc163b4afc","src/detection.rs":"ed9a5f9a979ab01247d7a68eeb1afa3c13209334c5bfff0f9289cb07e5bb4e8b","src/fallback.rs":"5aab7b73e381dc192256a0c67c99706ae0850159fd9f805fb0c9418fc14b1e00","src/lib.rs":"8bd3da5c9f048acda3799d53eefb7fb2f8b4046612d48f34ec30102b10f4ab08","src/marker.rs":"344a8394f06a1d43355b514920e7e3c0c6dce507be767e3a590bbe3552edd110","src/parse.rs":"34fa3c2e03fa9ab3e63ea57595d1dea4edf0fcfa313a04057e4dd7dc7d7269e0","src/rcvec.rs":"49b6784c6ca5f32573cd8a83758b485d8acbfa126e5fb516ae439e429ef4c144","src/wrapper.rs":"a88d0dff9bb8317071ec205b0c2a79717cd8313041e03ef58e0645be65ab05e8","tests/comments.rs":"31115b3a56c83d93eef2fb4c9566bf4543e302560732986161b98aef504785ed","tests/features.rs":"a86deb8644992a4eb64d9fd493eff16f9cf9c5cb6ade3a634ce0c990cf87d559","tests/marker.rs":"cb6d776eba6a238d726b0f531883adf41957e06f2717ee8a069821c81e7081d6","tests/test.rs":"2fe87d2eab135fb2417cac2876998e9314616fb68981918d7d76333c22b199a0","tests/test_fmt.rs":"9357769945784354909259084ec8b34d2aa52081dd3967cac6dae3a5e3df3bc0"},"package":"0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab"} \ No newline at end of file +{"files":{"Cargo.toml":"9505cf076f910ef2f0b0ceb4a90c02bb42bcb9447996c4938a02f5fc3c4afe7a","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"0c17148c1957c3f721d99fc99aedaefee5f2f1ba7e2336a289b02f91609099fb","build.rs":"275f7a9ee0b9eff972124951de544ae17ee3e698a4e89b0f0393b334344f5e30","src/detection.rs":"ed9a5f9a979ab01247d7a68eeb1afa3c13209334c5bfff0f9289cb07e5bb4e8b","src/fallback.rs":"a9e6fa159d6a111a231fa9367d54859103e9d49f6662397baea951b5f3e7e983","src/lib.rs":"a2fa0948c2475b762b293be6d1fbbe2ea6b1801f13cd1628e8ac71044c331641","src/marker.rs":"344a8394f06a1d43355b514920e7e3c0c6dce507be767e3a590bbe3552edd110","src/parse.rs":"ac37962914e575cd8f4537f9edf484d8a7ebbc3fd8c80bb7107ff8200d17be60","src/rcvec.rs":"49b6784c6ca5f32573cd8a83758b485d8acbfa126e5fb516ae439e429ef4c144","src/wrapper.rs":"8ea825cdac628570719a258419fcffd1c9d2ca1ca5e2fbbbf283dd9cc6695910","tests/comments.rs":"31115b3a56c83d93eef2fb4c9566bf4543e302560732986161b98aef504785ed","tests/features.rs":"a86deb8644992a4eb64d9fd493eff16f9cf9c5cb6ade3a634ce0c990cf87d559","tests/marker.rs":"cb6d776eba6a238d726b0f531883adf41957e06f2717ee8a069821c81e7081d6","tests/test.rs":"d7f21088314d1df25447fdc0a32feffae26d4d637e3ce68e23c0190060cb5652","tests/test_fmt.rs":"9357769945784354909259084ec8b34d2aa52081dd3967cac6dae3a5e3df3bc0"},"package":"94e2ef8dbfc347b10c094890f778ee2e36ca9bb4262e86dc99cd217e35f3470b"} \ No newline at end of file diff --git a/bash-5.1/vendor/proc-macro2/Cargo.toml b/bash-5.1/vendor/proc-macro2/Cargo.toml index b8b4643..531faf2 100644 --- a/bash-5.1/vendor/proc-macro2/Cargo.toml +++ b/bash-5.1/vendor/proc-macro2/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.31" name = "proc-macro2" -version = "1.0.43" +version = "1.0.46" authors = [ "David Tolnay ", "Alex Crichton ", diff --git a/bash-5.1/vendor/proc-macro2/build.rs b/bash-5.1/vendor/proc-macro2/build.rs index 3840496..b69d813 100644 --- a/bash-5.1/vendor/proc-macro2/build.rs +++ b/bash-5.1/vendor/proc-macro2/build.rs @@ -111,7 +111,10 @@ fn main() { println!("cargo:rustc-cfg=wrap_proc_macro"); } - if version.nightly && feature_allowed("proc_macro_span") { + if version.nightly + && feature_allowed("proc_macro_span") + && feature_allowed("proc_macro_span_shrink") + { println!("cargo:rustc-cfg=proc_macro_span"); } diff --git a/bash-5.1/vendor/proc-macro2/src/fallback.rs b/bash-5.1/vendor/proc-macro2/src/fallback.rs index 378ef7e..fe4f248 100644 --- a/bash-5.1/vendor/proc-macro2/src/fallback.rs +++ b/bash-5.1/vendor/proc-macro2/src/fallback.rs @@ -182,7 +182,13 @@ impl FromStr for TokenStream { fn from_str(src: &str) -> Result { // Create a dummy file & add it to the source map - let cursor = get_cursor(src); + let mut cursor = get_cursor(src); + + // Strip a byte order mark if present + const BYTE_ORDER_MARK: &str = "\u{feff}"; + if cursor.starts_with(BYTE_ORDER_MARK) { + cursor = cursor.advance(BYTE_ORDER_MARK.len()); + } parse::token_stream(cursor) } @@ -512,6 +518,26 @@ impl Span { }) } + #[cfg(procmacro2_semver_exempt)] + pub fn before(&self) -> Span { + Span { + #[cfg(span_locations)] + lo: self.lo, + #[cfg(span_locations)] + hi: self.lo, + } + } + + #[cfg(procmacro2_semver_exempt)] + pub fn after(&self) -> Span { + Span { + #[cfg(span_locations)] + lo: self.hi, + #[cfg(span_locations)] + hi: self.hi, + } + } + #[cfg(not(span_locations))] pub fn join(&self, _other: Span) -> Option { Some(Span {}) diff --git a/bash-5.1/vendor/proc-macro2/src/lib.rs b/bash-5.1/vendor/proc-macro2/src/lib.rs index be5aa51..47b48df 100644 --- a/bash-5.1/vendor/proc-macro2/src/lib.rs +++ b/bash-5.1/vendor/proc-macro2/src/lib.rs @@ -86,8 +86,11 @@ //! a different thread. // Proc-macro2 types in rustdoc of other crates get linked to here. -#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.43")] -#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))] +#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.46")] +#![cfg_attr( + any(proc_macro_span, super_unstable), + feature(proc_macro_span, proc_macro_span_shrink) +)] #![cfg_attr(super_unstable, feature(proc_macro_def_site))] #![cfg_attr(doc_cfg, feature(doc_cfg))] #![allow( @@ -509,6 +512,24 @@ impl Span { LineColumn { line, column } } + /// Creates an empty span pointing to directly before this span. + /// + /// This method is semver exempt and not exposed by default. + #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] + #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] + pub fn before(&self) -> Span { + Span::_new(self.inner.before()) + } + + /// Creates an empty span pointing to directly after this span. + /// + /// This method is semver exempt and not exposed by default. + #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] + #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] + pub fn after(&self) -> Span { + Span::_new(self.inner.after()) + } + /// Create a new span encompassing `self` and `other`. /// /// Returns `None` if `self` and `other` are from different files. diff --git a/bash-5.1/vendor/proc-macro2/src/location.rs b/bash-5.1/vendor/proc-macro2/src/location.rs new file mode 100644 index 0000000..463026c --- /dev/null +++ b/bash-5.1/vendor/proc-macro2/src/location.rs @@ -0,0 +1,29 @@ +use core::cmp::Ordering; + +/// A line-column pair representing the start or end of a `Span`. +/// +/// This type is semver exempt and not exposed by default. +#[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct LineColumn { + /// The 1-indexed line in the source file on which the span starts or ends + /// (inclusive). + pub line: usize, + /// The 0-indexed column (in UTF-8 characters) in the source file on which + /// the span starts or ends (inclusive). + pub column: usize, +} + +impl Ord for LineColumn { + fn cmp(&self, other: &Self) -> Ordering { + self.line + .cmp(&other.line) + .then(self.column.cmp(&other.column)) + } +} + +impl PartialOrd for LineColumn { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} diff --git a/bash-5.1/vendor/proc-macro2/src/parse.rs b/bash-5.1/vendor/proc-macro2/src/parse.rs index 1c9974c..04c4833 100644 --- a/bash-5.1/vendor/proc-macro2/src/parse.rs +++ b/bash-5.1/vendor/proc-macro2/src/parse.rs @@ -14,7 +14,7 @@ pub(crate) struct Cursor<'a> { } impl<'a> Cursor<'a> { - fn advance(&self, bytes: usize) -> Cursor<'a> { + pub fn advance(&self, bytes: usize) -> Cursor<'a> { let (_front, rest) = self.rest.split_at(bytes); Cursor { rest, @@ -23,7 +23,7 @@ impl<'a> Cursor<'a> { } } - fn starts_with(&self, s: &str) -> bool { + pub fn starts_with(&self, s: &str) -> bool { self.rest.starts_with(s) } @@ -283,8 +283,9 @@ fn ident_any(input: Cursor) -> PResult { return Ok((rest, ident)); } - if sym == "_" { - return Err(Reject); + match sym { + "_" | "super" | "self" | "Self" | "crate" => return Err(Reject), + _ => {} } let ident = crate::Ident::_new_raw(sym, crate::Span::call_site()); diff --git a/bash-5.1/vendor/proc-macro2/src/wrapper.rs b/bash-5.1/vendor/proc-macro2/src/wrapper.rs index 9344401..47d1494 100644 --- a/bash-5.1/vendor/proc-macro2/src/wrapper.rs +++ b/bash-5.1/vendor/proc-macro2/src/wrapper.rs @@ -505,6 +505,22 @@ impl Span { } } + #[cfg(super_unstable)] + pub fn before(&self) -> Span { + match self { + Span::Compiler(s) => Span::Compiler(s.before()), + Span::Fallback(s) => Span::Fallback(s.before()), + } + } + + #[cfg(super_unstable)] + pub fn after(&self) -> Span { + match self { + Span::Compiler(s) => Span::Compiler(s.after()), + Span::Fallback(s) => Span::Fallback(s.after()), + } + } + pub fn join(&self, other: Span) -> Option { let ret = match (self, other) { #[cfg(proc_macro_span)] diff --git a/bash-5.1/vendor/proc-macro2/tests/test.rs b/bash-5.1/vendor/proc-macro2/tests/test.rs index 16f775e..8f5624d 100644 --- a/bash-5.1/vendor/proc-macro2/tests/test.rs +++ b/bash-5.1/vendor/proc-macro2/tests/test.rs @@ -630,3 +630,16 @@ fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usi } } } + +#[test] +fn byte_order_mark() { + let string = "\u{feff}foo"; + let tokens = string.parse::().unwrap(); + match tokens.into_iter().next().unwrap() { + TokenTree::Ident(ident) => assert_eq!(ident, "foo"), + _ => unreachable!(), + } + + let string = "foo\u{feff}"; + string.parse::().unwrap_err(); +} diff --git a/bash-5.1/vendor/quasi/.cargo-checksum.json b/bash-5.1/vendor/quasi/.cargo-checksum.json new file mode 100644 index 0000000..adf60f1 --- /dev/null +++ b/bash-5.1/vendor/quasi/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"c7784ad13b709e309a65b60a42fa5728373e5dade1f5fc70eb66be9bd6519cdd","src/lib.rs":"f05bfe4525aecd520f568f548aa972c00faba9559973e318d06b62de5cb7d4ad"},"package":"dcbf815446dc6a0afbc72d88f9a8aa71b608d10b168e09437c80c0fd6fd410c9"} \ No newline at end of file diff --git a/bash-5.1/vendor/quasi/Cargo.toml b/bash-5.1/vendor/quasi/Cargo.toml new file mode 100644 index 0000000..1e3c71c --- /dev/null +++ b/bash-5.1/vendor/quasi/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "quasi" +version = "0.29.0" +authors = ["Erick Tryzelaar "] +license = "MIT/Apache-2.0" +description = "A quasi-quoting macro system" +repository = "https://github.com/serde-rs/quasi" +include = ["Cargo.toml", "src/**/*.rs"] + +[features] +with-syntex = ["syntex_syntax", "syntex_errors"] +unstable-testing = ["clippy"] + +[dependencies] +clippy = { version = "^0.*", optional = true } +syntex_errors = { version = "^0.54.0", optional = true } +syntex_syntax = { version = "^0.54.0", optional = true } diff --git a/bash-5.1/vendor/quasi/src/lib.rs b/bash-5.1/vendor/quasi/src/lib.rs new file mode 100644 index 0000000..15ae694 --- /dev/null +++ b/bash-5.1/vendor/quasi/src/lib.rs @@ -0,0 +1,592 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, i128_type))] +#![cfg_attr(feature = "unstable-testing", feature(plugin))] +#![cfg_attr(feature = "unstable-testing", plugin(clippy))] + +#[macro_use] +#[cfg(feature = "with-syntex")] +extern crate syntex_syntax as syntax; +#[cfg(feature = "with-syntex")] +extern crate syntex_errors as errors; + +#[macro_use] +#[cfg(not(feature = "with-syntex"))] +extern crate syntax; +#[cfg(not(feature = "with-syntex"))] +extern crate rustc_errors as errors; + +use std::iter; +use std::marker; +use std::rc::Rc; +use std::usize; + +use syntax::ast; +use syntax::codemap::{DUMMY_SP, Spanned, dummy_spanned}; +use syntax::ext::base::ExtCtxt; +use syntax::parse::parser::Parser; +use syntax::parse::{self, classify, parse_tts_from_source_str, token}; +use syntax::print::pprust; +use syntax::ptr::P; +use syntax::symbol::Symbol; +use syntax::tokenstream::{self, TokenTree}; +use syntax::util::ThinVec; + +pub trait ToTokens { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec; +} + +impl ToTokens for TokenTree { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec!(self.clone()) + } +} + +impl<'a, T: ToTokens> ToTokens for &'a T { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + (**self).to_tokens(cx) + } +} + +impl<'a, T: ToTokens> ToTokens for &'a [T] { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + self.iter() + .flat_map(|t| t.to_tokens(cx).into_iter()) + .collect() + } +} + +impl ToTokens for Vec { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + self.iter().flat_map(|t| t.to_tokens(cx).into_iter()).collect() + } +} + +impl ToTokens for Spanned { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + // FIXME: use the span? + self.node.to_tokens(cx) + } +} + +impl ToTokens for Option { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + match *self { + Some(ref t) => t.to_tokens(cx), + None => Vec::new(), + } + } +} + +impl ToTokens for ast::Ident { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(DUMMY_SP, token::Ident(*self))] + } +} + +impl ToTokens for ast::Path { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(token::NtPath(self.clone()))))] + } +} + +impl ToTokens for ast::Ty { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtTy(P(self.clone())))))] + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtTy(self.clone()))))] + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtBlock(self.clone()))))] + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtItem(self.clone()))))] + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtImplItem((**self).clone()))))] + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtTraitItem((**self).clone()))))] + } +} + +impl ToTokens for ast::Generics { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + /* + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(token::NtGenerics(self.clone())))] + */ + + let s = pprust::generics_to_string(self); + + panictry!(parse_tts_from_source_str( + "".to_string(), + s, + cx.parse_sess())) + } +} + +impl ToTokens for ast::WhereClause { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + /* + vec![TokenTree::Token(DUMMY_SP, + token::Interpolated(token::NtWhereClause(self.clone())))] + */ + + let s = pprust::to_string(|s| { + s.print_where_clause(self) + }); + + panictry!(parse_tts_from_source_str( + "".to_string(), + s, + cx.parse_sess())) + } +} + +impl ToTokens for ast::Stmt { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + let mut tts = vec![ + TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtStmt(self.clone())))) + ]; + + // Some statements require a trailing semicolon. + if classify::stmt_ends_with_semi(&self.node) { + tts.push(TokenTree::Token(self.span, token::Semi)); + } + + tts + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtExpr(self.clone()))))] + } +} + +impl ToTokens for P { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(token::NtPat(self.clone()))))] + } +} + +impl ToTokens for ast::Arm { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(token::NtArm(self.clone()))))] + } +} + +macro_rules! impl_to_tokens_slice { + ($t: ty, $sep: expr) => { + impl ToTokens for [$t] { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let mut v = vec![]; + for (i, x) in self.iter().enumerate() { + if i > 0 { + v.extend($sep.iter().cloned()); + } + v.extend(x.to_tokens(cx)); + } + v + } + } + }; +} + +impl_to_tokens_slice! { ast::Ty, [TokenTree::Token(DUMMY_SP, token::Comma)] } +impl_to_tokens_slice! { P, [] } + +impl ToTokens for ast::MetaItem { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(token::NtMeta(self.clone()))))] + } +} + +impl ToTokens for ast::Arg { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let mut v = self.pat.to_tokens(cx); + v.push(TokenTree::Token(DUMMY_SP, token::Colon)); + v.extend(self.ty.to_tokens(cx)); + v.push(TokenTree::Token(DUMMY_SP, token::Comma)); + v + } +} + +impl ToTokens for ast::Attribute { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let mut r = vec![]; + // FIXME: The spans could be better + r.push(TokenTree::Token(self.span, token::Pound)); + if self.style == ast::AttrStyle::Inner { + r.push(TokenTree::Token(self.span, token::Not)); + } + r.push(TokenTree::Delimited(self.span, Rc::new(tokenstream::Delimited { + delim: token::Bracket, + open_span: self.span, + tts: self.value.to_tokens(cx), + close_span: self.span, + }))); + r + } +} + +impl ToTokens for str { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let lit + = ast::LitKind::Str( + Symbol::intern(self), ast::StrStyle::Cooked); + dummy_spanned(lit).to_tokens(cx) + } +} + +impl ToTokens for String { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let lit + = ast::LitKind::Str( + Symbol::intern(self), ast::StrStyle::Cooked); + dummy_spanned(lit).to_tokens(cx) + } +} + +impl ToTokens for () { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { + vec![TokenTree::Delimited(DUMMY_SP, Rc::new(tokenstream::Delimited { + delim: token::Paren, + open_span: DUMMY_SP, + tts: vec![], + close_span: DUMMY_SP, + }))] + } +} + +impl ToTokens for ast::Lit { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + // FIXME: This is wrong + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Lit(P(self.clone())), + span: DUMMY_SP, + attrs: ThinVec::new(), + }).to_tokens(cx) + } +} + +impl ToTokens for bool { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + dummy_spanned(ast::LitKind::Bool(*self)).to_tokens(cx) + } +} + +impl ToTokens for char { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + dummy_spanned(ast::LitKind::Char(*self)).to_tokens(cx) + } +} + +macro_rules! impl_wrap_repeat { + ($t:ty) => ( + impl IntoWrappedRepeat for $t { + type Item = $t; + type IntoIter = iter::Repeat<$t>; + fn into_wrappable_iter(self) -> iter::Repeat<$t> { + iter::repeat(self) + } + } + ) +} + +#[cfg(feature = "with-syntex")] +#[allow(non_camel_case_types)] +type umax = u64; +#[cfg(not(feature = "with-syntex"))] +#[allow(non_camel_case_types)] +type umax = u128; + +macro_rules! impl_to_tokens_int { + (signed, $t:ty, $tag:expr) => ( + impl_wrap_repeat! { $t } + impl ToTokens for $t { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let val = if *self < 0 { + -self + } else { + *self + }; + let lit = ast::LitKind::Int(val as umax, ast::LitIntType::Signed($tag)); + dummy_spanned(lit).to_tokens(cx) + } + } + ); + (unsigned, $t:ty, $tag:expr) => ( + impl_wrap_repeat! { $t } + impl ToTokens for $t { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec { + let lit = ast::LitKind::Int(*self as umax, ast::LitIntType::Unsigned($tag)); + dummy_spanned(lit).to_tokens(cx) + } + } + ); +} + +impl_to_tokens_int! { signed, isize, ast::IntTy::Is } +impl_to_tokens_int! { signed, i8, ast::IntTy::I8 } +impl_to_tokens_int! { signed, i16, ast::IntTy::I16 } +impl_to_tokens_int! { signed, i32, ast::IntTy::I32 } +impl_to_tokens_int! { signed, i64, ast::IntTy::I64 } + +impl_to_tokens_int! { unsigned, usize, ast::UintTy::Us } +impl_to_tokens_int! { unsigned, u8, ast::UintTy::U8 } +impl_to_tokens_int! { unsigned, u16, ast::UintTy::U16 } +impl_to_tokens_int! { unsigned, u32, ast::UintTy::U32 } +impl_to_tokens_int! { unsigned, u64, ast::UintTy::U64 } + +pub trait ExtParseUtils { + fn parse_item(&self, s: String) -> P; + fn parse_expr(&self, s: String) -> P; + fn parse_stmt(&self, s: String) -> ast::Stmt; + fn parse_tts(&self, s: String) -> Vec; +} + +impl<'a> ExtParseUtils for ExtCtxt<'a> { + + fn parse_item(&self, s: String) -> P { + panictry!(parse::parse_item_from_source_str( + "".to_string(), + s, + self.parse_sess())).expect("parse error") + } + + fn parse_stmt(&self, s: String) -> ast::Stmt { + panictry!(parse::parse_stmt_from_source_str( + "".to_string(), + s, + self.parse_sess())).expect("parse error") + } + + fn parse_expr(&self, s: String) -> P { + panictry!(parse::parse_expr_from_source_str( + "".to_string(), + s, + self.parse_sess())) + } + + fn parse_tts(&self, s: String) -> Vec { + panictry!(parse::parse_tts_from_source_str( + "".to_string(), + s, + self.parse_sess())) + } +} + +pub fn parse_expr_panic(parser: &mut Parser) -> P { + panictry!(parser.parse_expr()) +} + +pub fn parse_item_panic(parser: &mut Parser) -> Option> { + panictry!(parser.parse_item()) +} + +pub fn parse_pat_panic(parser: &mut Parser) -> P { + panictry!(parser.parse_pat()) +} + +pub fn parse_arm_panic(parser: &mut Parser) -> ast::Arm { + panictry!(parser.parse_arm()) +} + +pub fn parse_ty_panic(parser: &mut Parser) -> P { + panictry!(parser.parse_ty()) +} + +pub fn parse_stmt_panic(parser: &mut Parser) -> Option { + panictry!(parser.parse_stmt()) +} + +pub fn parse_attribute_panic(parser: &mut Parser, permit_inner: bool) -> ast::Attribute { + panictry!(parser.parse_attribute(permit_inner)) +} + +pub struct IterWrapper { + inner: I, + require_nonempty: bool, + is_repeat: bool, +} + +impl IterWrapper where I: Iterator { + pub fn zip_wrap(self, other: IterWrapper) -> IterWrapper> { + IterWrapper { + inner: ZipLockstep { + a: self.inner, + b: other.inner, + contains_repeat: self.is_repeat || other.is_repeat, + }, + require_nonempty: false, + is_repeat: self.is_repeat && other.is_repeat, + } + } + + pub fn check(mut self, one_or_more: bool) -> Self { + // This check prevents running out of memory. + assert!(self.size_hint() != (usize::MAX, None), + "unbounded repetition in quasiquotation"); + self.require_nonempty = one_or_more; + self + } +} + +impl> Iterator for IterWrapper { + type Item = T; + fn next(&mut self) -> Option { + match self.inner.next() { + Some(elem) => { + self.require_nonempty = false; + Some(elem) + } + None => { + assert!(!self.require_nonempty, + "a fragment must repeat at least once in quasiquotation"); + None + } + } + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +pub struct ZipLockstep { + a: A, + b: B, + contains_repeat: bool, +} + +impl Iterator for ZipLockstep + where A: Iterator, + B: Iterator, +{ + type Item = (A::Item, B::Item); + fn next(&mut self) -> Option { + match (self.a.next(), self.b.next()) { + (Some(left), Some(right)) => Some((left, right)), + (None, None) => None, + _ => { + if self.contains_repeat { + None + } else { + panic!("incorrect lockstep iteration in quasiquotation"); + } + } + } + } + + fn size_hint(&self) -> (usize, Option) { + struct SizeHint((usize, Option), marker::PhantomData); + impl Iterator for SizeHint { + type Item = A; + fn next(&mut self) -> Option { None } + fn size_hint(&self) -> (usize, Option) { + ((self.0).0, (self.0).1) + } + } + let a_size_hint = SizeHint(self.a.size_hint(), marker::PhantomData::<()>); + let b_size_hint = SizeHint(self.b.size_hint(), marker::PhantomData::<()>); + a_size_hint.zip(b_size_hint).size_hint() + } +} + +// This is a workaround for trait coherence. +// Both traits have almost identical methods. We can generate code that calls +// `into_wrapper_iter` on a value that should implement one of these traits, +// without knowing which. + +pub trait IntoWrappedIterator: Sized { + type Item; + type IntoIter: Iterator; + fn into_wrappable_iter(self) -> Self::IntoIter; + fn into_wrapped_iter(self) -> IterWrapper { + IterWrapper { + inner: self.into_wrappable_iter(), + require_nonempty: false, + is_repeat: false, + } + } +} + +pub trait IntoWrappedRepeat: Sized { + type Item; + type IntoIter: Iterator; + fn into_wrappable_iter(self) -> Self::IntoIter; + fn into_wrapped_iter(self) -> IterWrapper { + IterWrapper { + inner: self.into_wrappable_iter(), + require_nonempty: false, + // The iterator repeats an element. + is_repeat: true, + } + } +} + +// Can't write a blanket impl for IntoIterator, because P impls +// IntoIterator, and P may already impl IntoWrappedRepeat. +impl IntoWrappedIterator for I { + type Item = I::Item; + type IntoIter = I; + fn into_wrappable_iter(self) -> I { + self + } +} + +impl IntoWrappedRepeat for Spanned { + type Item = Spanned; + type IntoIter = iter::Repeat>; + fn into_wrappable_iter(self) -> iter::Repeat> { + iter::repeat(self) + } +} + +impl_wrap_repeat! { TokenTree } +impl_wrap_repeat! { ast::Ident } +impl_wrap_repeat! { ast::Path } +impl_wrap_repeat! { ast::Ty } +impl_wrap_repeat! { P } +impl_wrap_repeat! { P } +impl_wrap_repeat! { P } +impl_wrap_repeat! { P } +impl_wrap_repeat! { P } +impl_wrap_repeat! { ast::Generics } +impl_wrap_repeat! { ast::WhereClause } +impl_wrap_repeat! { ast::StmtKind } +impl_wrap_repeat! { P } +impl_wrap_repeat! { P } +impl_wrap_repeat! { ast::Arm } +impl_wrap_repeat! { P } +impl_wrap_repeat! { ast::Attribute } +impl_wrap_repeat! { () } +impl_wrap_repeat! { ast::LitKind } +impl_wrap_repeat! { bool } +impl_wrap_repeat! { char } diff --git a/bash-5.1/vendor/quasi_codegen/.cargo-checksum.json b/bash-5.1/vendor/quasi_codegen/.cargo-checksum.json new file mode 100644 index 0000000..df3a3a1 --- /dev/null +++ b/bash-5.1/vendor/quasi_codegen/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"47c15a377d35bccd1c9bf93caa7105c5ed9b36483959b67d9ccb17a9763a9eb8","src/lib.rs":"b978275b356139de30584044e4e8b1b39959fb2a2ed3d04eb60dd8260b83df85"},"package":"b06172e92ab0099427609854ffb1512c377be5fc4beaf572ae5d5a01b8359596"} \ No newline at end of file diff --git a/bash-5.1/vendor/quasi_codegen/Cargo.toml b/bash-5.1/vendor/quasi_codegen/Cargo.toml new file mode 100644 index 0000000..cf25e49 --- /dev/null +++ b/bash-5.1/vendor/quasi_codegen/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "quasi_codegen" +version = "0.29.0" +authors = ["Erick Tryzelaar "] +license = "MIT/Apache-2.0" +description = "A quasi-quoting macro system" +repository = "https://github.com/serde-rs/quasi" +include = ["Cargo.toml", "src/**/*.rs"] + +[features] +default = ["with-syntex"] +with-syntex = ["syntex", "syntex_errors", "syntex_syntax", "aster/with-syntex"] +unstable-testing = ["clippy"] + +[dependencies] +aster = { version = "^0.38.0", default-features = false } +clippy = { version = "^0.*", optional = true } +syntex = { version = "^0.54.0", optional = true } +syntex_errors = { version = "^0.54.0", optional = true } +syntex_syntax = { version = "^0.54.0", optional = true } diff --git a/bash-5.1/vendor/quasi_codegen/src/lib.rs b/bash-5.1/vendor/quasi_codegen/src/lib.rs new file mode 100644 index 0000000..10d2d42 --- /dev/null +++ b/bash-5.1/vendor/quasi_codegen/src/lib.rs @@ -0,0 +1,858 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private))] +#![cfg_attr(feature = "unstable-testing", feature(plugin))] +#![cfg_attr(feature = "unstable-testing", plugin(clippy))] + +extern crate aster; + +#[cfg(feature = "with-syntex")] +extern crate syntex; +#[macro_use] +#[cfg(feature = "with-syntex")] +extern crate syntex_syntax as syntax; +#[cfg(feature = "with-syntex")] +extern crate syntex_errors as errors; + +#[macro_use] +#[cfg(not(feature = "with-syntex"))] +extern crate syntax; +#[cfg(not(feature = "with-syntex"))] +extern crate rustc_errors as errors; +#[cfg(not(feature = "with-syntex"))] +extern crate rustc_plugin; + +#[cfg(feature = "with-syntex")] +use std::path::Path; + +use syntax::ast; +use syntax::codemap::{Span, respan}; +use syntax::ext::base::ExtCtxt; +use syntax::ext::base; +use syntax::parse::token::*; +use syntax::parse::token; +use syntax::ptr::P; +use syntax::symbol::Symbol; +use syntax::tokenstream::{self, TokenTree}; + +/// Quasiquoting works via token trees. +/// +/// This is registered as a set of expression syntax extension called quote! +/// that lifts its argument token-tree to an AST representing the +/// construction of the same token tree, with `token::SubstNt` interpreted +/// as antiquotes (splices). + +fn expand_quote_tokens<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree], +) -> Box { + let (cx_expr, expr) = expand_tts(cx, sp, tts); + let expanded = expand_wrapper(sp, cx_expr, expr); + base::MacEager::expr(expanded) +} + +fn expand_quote_ty<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_ty_panic"], + vec!(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_expr<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_expr_panic"], + Vec::new(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_stmt<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_stmt_panic"], + vec!(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_attr<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let builder = aster::AstBuilder::new().span(sp); + + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_attribute_panic"], + vec![builder.expr().bool(true)], + tts); + + base::MacEager::expr(expanded) +} + +fn expand_quote_matcher<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let builder = aster::AstBuilder::new().span(sp); + + let (cx_expr, tts) = parse_arguments_to_quote(cx, tts); + let mut vector = mk_stmts_let(&builder); + match statements_mk_tts(&tts[..], true) { + Ok(stmts) => vector.extend(stmts.stmts.into_iter()), + Err(_) => cx.span_fatal(sp, "attempted to repeat an expression containing \ + no syntax variables matched as repeating at this depth"), + } + + let block = builder.expr().block() + .with_stmts(vector) + .expr().id("tt"); + + let expanded = expand_wrapper(sp, cx_expr, block); + base::MacEager::expr(expanded) +} + +fn expand_quote_pat<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_pat_panic"], + vec!(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_arm<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_arm_panic"], + vec!(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_block<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["syntax", "parse", "parser", "Parser", "parse_block"], + Vec::new(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_item<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["quasi", "parse_item_panic"], + vec!(), + tts); + base::MacEager::expr(expanded) +} + +fn expand_quote_impl_item<'cx>( + cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree] +) -> Box { + let expanded = expand_parse_call( + cx, + sp, + &["syntax", "parse", "parser", "Parser", "parse_impl_item"], + vec!(), + tts); + base::MacEager::expr(expanded) +} + +/* +fn expand_quote_where_clause<'cx>(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box { + let expanded = expand_parse_call(cx, sp, "parse_where_clause", + vec!(), tts); + base::MacEager::expr(expanded) +} +*/ + +// Lift an ident to the expr that evaluates to that ident. +fn mk_ident(builder: &aster::AstBuilder, ident: ast::Ident) -> P { + builder.expr().method_call("ident_of").id("ext_cx") + .arg().str(ident) + .build() +} + +// Lift a name to the expr that evaluates to that name +fn mk_name(builder: &aster::AstBuilder, name: T) -> P + where T: aster::symbol::ToSymbol +{ + builder.expr().method_call("name_of").id("ext_cx") + .arg().str(name) + .build() +} + +fn mk_tt_path(builder: &aster::AstBuilder, name: &str) -> P { + builder.expr().path() + .global() + .ids(&["syntax", "tokenstream", "TokenTree", name]) + .build() +} + +fn mk_token_path(builder: &aster::AstBuilder, name: &str) -> P { + builder.expr().path() + .global() + .ids(&["syntax", "parse", "token", name]) + .build() +} + +fn mk_binop(builder: &aster::AstBuilder, bop: token::BinOpToken) -> P { + let name = match bop { + token::Plus => "Plus", + token::Minus => "Minus", + token::Star => "Star", + token::Slash => "Slash", + token::Percent => "Percent", + token::Caret => "Caret", + token::And => "And", + token::Or => "Or", + token::Shl => "Shl", + token::Shr => "Shr" + }; + mk_token_path(builder, name) +} + +fn mk_delim(builder: &aster::AstBuilder, delim: token::DelimToken) -> P { + let name = match delim { + token::Paren => "Paren", + token::Bracket => "Bracket", + token::Brace => "Brace", + token::NoDelim => "NoDelim", + }; + mk_token_path(builder, name) +} + +#[allow(non_upper_case_globals)] +fn expr_mk_token(builder: &aster::AstBuilder, tok: &token::Token) -> P { + macro_rules! mk_lit { + ($name: expr, $suffix: expr, $($args: expr),+) => {{ + let inner = builder.expr().call() + .build(mk_token_path(builder, $name)) + $(.with_arg($args))+ + .build(); + + let suffix = match $suffix { + Some(name) => builder.expr().some().build(mk_name(builder, name)), + None => builder.expr().none(), + }; + + builder.expr().call() + .build(mk_token_path(builder, "Literal")) + .with_arg(inner) + .with_arg(suffix) + .build() + }} + } + + match *tok { + token::BinOp(binop) => { + builder.expr().call() + .build(mk_token_path(builder, "BinOp")) + .with_arg(mk_binop(builder, binop)) + .build() + } + token::BinOpEq(binop) => { + builder.expr().call() + .build(mk_token_path(builder, "BinOpEq")) + .with_arg(mk_binop(builder, binop)) + .build() + } + + token::OpenDelim(delim) => { + builder.expr().call() + .build(mk_token_path(builder, "OpenDelim")) + .with_arg(mk_delim(builder, delim)) + .build() + } + token::CloseDelim(delim) => { + builder.expr().call() + .build(mk_token_path(builder, "CloseDelim")) + .with_arg(mk_delim(builder, delim)) + .build() + } + + token::Literal(token::Byte(i), suf) => { + let e_byte = mk_name(builder, i.as_str()); + mk_lit!("Byte", suf, e_byte) + } + + token::Literal(token::Char(i), suf) => { + let e_char = mk_name(builder, i.as_str()); + mk_lit!("Char", suf, e_char) + } + + token::Literal(token::Integer(i), suf) => { + let e_int = mk_name(builder, i.as_str()); + mk_lit!("Integer", suf, e_int) + } + + token::Literal(token::Float(fident), suf) => { + let e_fident = mk_name(builder, fident.as_str()); + mk_lit!("Float", suf, e_fident) + } + + token::Literal(token::ByteStr(ident), suf) => { + mk_lit!("ByteStr", suf, mk_name(builder, ident.as_str())) + } + + token::Literal(token::ByteStrRaw(ident, n), suf) => { + mk_lit!( + "ByteStrRaw", + suf, + mk_name(builder, ident.as_str()), + builder.expr().usize(n)) + } + + token::Literal(token::Str_(ident), suf) => { + mk_lit!("Str_", suf, mk_name(builder, ident.as_str())) + } + + token::Literal(token::StrRaw(ident, n), suf) => { + mk_lit!( + "StrRaw", + suf, + mk_name(builder, ident.as_str()), + builder.expr().usize(n)) + } + + token::Ident(ident) => { + builder.expr().call() + .build(mk_token_path(builder, "Ident")) + .with_arg(mk_ident(builder, ident)) + .build() + } + + token::Lifetime(ident) => { + builder.expr().call() + .build(mk_token_path(builder, "Lifetime")) + .with_arg(mk_ident(builder, ident)) + .build() + } + + token::DocComment(ident) => { + builder.expr().call() + .build(mk_token_path(builder, "DocComment")) + .with_arg(mk_name(builder, ident)) + .build() + } + + token::Eq => mk_token_path(builder, "Eq"), + token::Lt => mk_token_path(builder, "Lt"), + token::Le => mk_token_path(builder, "Le"), + token::EqEq => mk_token_path(builder, "EqEq"), + token::Ne => mk_token_path(builder, "Ne"), + token::Ge => mk_token_path(builder, "Ge"), + token::Gt => mk_token_path(builder, "Gt"), + token::AndAnd => mk_token_path(builder, "AndAnd"), + token::OrOr => mk_token_path(builder, "OrOr"), + token::Not => mk_token_path(builder, "Not"), + token::Tilde => mk_token_path(builder, "Tilde"), + token::At => mk_token_path(builder, "At"), + token::Dot => mk_token_path(builder, "Dot"), + token::DotDot => mk_token_path(builder, "DotDot"), + token::Comma => mk_token_path(builder, "Comma"), + token::Semi => mk_token_path(builder, "Semi"), + token::Colon => mk_token_path(builder, "Colon"), + token::ModSep => mk_token_path(builder, "ModSep"), + token::RArrow => mk_token_path(builder, "RArrow"), + token::LArrow => mk_token_path(builder, "LArrow"), + token::FatArrow => mk_token_path(builder, "FatArrow"), + token::Pound => mk_token_path(builder, "Pound"), + token::Dollar => mk_token_path(builder, "Dollar"), + token::Underscore => mk_token_path(builder, "Underscore"), + token::Eof => mk_token_path(builder, "Eof"), + token::DotDotDot => mk_token_path(builder, "DotDotDot"), + token::Question => mk_token_path(builder, "Question"), + token::Whitespace => mk_token_path(builder, "Whitespace"), + token::Comment => mk_token_path(builder, "Comment"), + + token::Shebang(s) => { + builder.expr().call() + .build(mk_token_path(builder, "Shebang")) + .arg().str(s) + .build() + } + + token::MatchNt(name, kind) => { + builder.expr().call() + .build(mk_token_path(builder, "MatchNt")) + .arg().build(mk_ident(builder, name)) + .arg().build(mk_ident(builder, kind)) + .build() + } + + token::Interpolated(..) + | token::SubstNt(..) => { + panic!("quote! with {:?} token", tok) + } + } +} + +struct QuoteStmts { + stmts: Vec, + idents: Vec, +} + +fn statements_mk_tt(tt: &TokenTree, matcher: bool) -> Result { + let builder = aster::AstBuilder::new(); + + match *tt { + TokenTree::Token(sp, SubstNt(ident)) => { + // tt.extend($ident.to_tokens(ext_cx).into_iter()) + + let builder = builder.span(sp); + + let to_tokens = builder.path() + .global() + .ids(&["quasi", "ToTokens", "to_tokens"]) + .build(); + + let e_to_toks = builder.expr().call() + .build_path(to_tokens) + .arg().ref_().id(ident) + .arg().id("ext_cx") + .build(); + + let e_to_toks = builder.expr().method_call("into_iter") + .build(e_to_toks) + .build(); + + let e_push = builder.expr().method_call("extend") + .id("tt") + .with_arg(e_to_toks) + .build(); + + Ok(QuoteStmts { + stmts: vec![builder.stmt().build_expr(e_push)], + idents: vec![respan(sp, ident)], + }) + } + ref tt @ TokenTree::Token(_, MatchNt(..)) if !matcher => { + let mut seq = vec![]; + for i in 0..tt.len() { + seq.push(tt.get_tt(i)); + } + statements_mk_tts(&seq[..], matcher) + } + TokenTree::Token(sp, ref tok) => { + let builder = builder.span(sp); + + let e_tok = builder.expr().call() + .build(mk_tt_path(&builder, "Token")) + .arg().id("_sp") + .with_arg(expr_mk_token(&builder, tok)) + .build(); + + let e_push = builder.expr().method_call("push") + .id("tt") + .with_arg(e_tok) + .build(); + + Ok(QuoteStmts { + stmts: vec![builder.stmt().build_expr(e_push)], + idents: vec![], + }) + }, + TokenTree::Delimited(_, ref delimed) => { + let delimited = try!(statements_mk_tts(&delimed.tts[..], matcher)); + let open = try!(statements_mk_tt(&delimed.open_tt(), matcher)).stmts.into_iter(); + let close = try!(statements_mk_tt(&delimed.close_tt(), matcher)).stmts.into_iter(); + Ok(QuoteStmts { + stmts: open.chain(delimited.stmts.into_iter()).chain(close).collect(), + idents: delimited.idents, + }) + }, + TokenTree::Sequence(sp, ref seq) if matcher => { + let builder = builder.span(sp); + + let e_sp = builder.expr().id("_sp"); + + let stmt_let_tt = builder.stmt().let_() + .mut_id("tt") + .expr().vec().build(); + + let mut tts_stmts = vec![stmt_let_tt]; + tts_stmts.extend(try!(statements_mk_tts(&seq.tts[..], matcher)).stmts.into_iter()); + + let e_tts = builder.expr().block() + .with_stmts(tts_stmts) + .expr().id("tt"); + + let e_separator = match seq.separator { + Some(ref sep) => builder.expr().some().build(expr_mk_token(&builder, sep)), + None => builder.expr().none(), + }; + + let e_op = match seq.op { + tokenstream::KleeneOp::ZeroOrMore => "ZeroOrMore", + tokenstream::KleeneOp::OneOrMore => "OneOrMore", + }; + let e_op = builder.expr().path() + .global() + .ids(&["syntax", "tokenstream", "KleeneOp", e_op]) + .build(); + + let e_seq_struct = builder.expr().struct_() + .global().ids(&["syntax", "tokenstream", "SequenceRepetition"]).build() + .field("tts").build(e_tts) + .field("separator").build(e_separator) + .field("op").build(e_op) + .field("num_captures").usize(seq.num_captures) + .build(); + + let e_rc_new = builder.expr().rc() + .build(e_seq_struct); + + let e_tok = builder.expr().call() + .build(mk_tt_path(&builder, "Sequence")) + .arg().build(e_sp) + .arg().build(e_rc_new) + .build(); + + let e_push = builder.expr().method_call("push").id("tt") + .arg().build(e_tok) + .build(); + + Ok(QuoteStmts { + stmts: vec![builder.stmt().expr().build(e_push)], + idents: vec![], + }) + } + TokenTree::Sequence(sp, ref seq) => { + // Repeating fragments in a loop: + // for (...(a, b), ...) in a.into_wrapped_iter() + // .zip_wrap(b.into_wrapped_iter())... + // .check(true/false) { + // // (quasiquotation with $a, $b, ...) + //} + let QuoteStmts { mut stmts, idents } = try!(statements_mk_tts(&seq.tts[..], matcher)); + if idents.is_empty() { + return Err(()); + } + let builder = builder.span(sp); + let one_or_more = builder.expr().bool(seq.op == tokenstream::KleeneOp::OneOrMore); + let mut iter = idents.iter().cloned(); + let first = iter.next().unwrap(); + let mut zipped = builder.span(first.span).expr() + .method_call("into_wrapped_iter") + .id(first.node) + .build(); + let mut pat = builder.span(first.span).pat().id(first.node); + for ident in iter { + // Repeating calls to zip_wrap: + // $zipped.zip_wrap($ident.into_wrapped_iter()) + zipped = builder.expr() + .method_call("zip_wrap") + .build(zipped) + .arg().span(ident.span).method_call("into_wrapped_iter") + .id(ident.node) + .build() + .build(); + let span = ident.span; + pat = builder.pat().tuple().with_pat(pat).pat().span(span).id(ident.node).build(); + } + // Assertion: zipped iterators must have at least one element + // if one_or_more == `true`. + zipped = builder.expr() + .method_call("check") + .build(zipped) + .with_arg(one_or_more) + .build(); + // Repetition can have a separator. + if let Some(ref tok) = seq.separator { + // Add the separator after each iteration. + let sep_token = TokenTree::Token(sp, tok.clone()); + let mk_sep = try!(statements_mk_tt(&sep_token, false)); + stmts.extend(mk_sep.stmts.into_iter()); + } + + let stmt_for = builder.stmt().expr().build_expr_kind( + ast::ExprKind::ForLoop(pat, zipped, builder.block().with_stmts(stmts).build(), None) + ); + + let stmts_for = if seq.separator.is_some() { + // Pop the last occurence of the separator after the last iteration + // only if there was at least one iteration (which changes the number of tokens). + let tt_len = builder.expr().method_call("len").id("tt").build(); + let tt_len_id = Symbol::intern("tt_len"); + let cond = builder.expr().ne().build(tt_len.clone()).id(tt_len_id); + let then = builder.block() + .stmt().semi().method_call("pop").id("tt").build() + .build(); + let if_len_eq = builder.expr().build_expr_kind( + ast::ExprKind::If(cond, then, None) + ); + vec![ + builder.stmt().let_id(tt_len_id).build_expr(tt_len), + stmt_for, + builder.stmt().build_expr(if_len_eq)] + } else { + vec![stmt_for] + }; + + Ok(QuoteStmts { + stmts: stmts_for, + idents: idents.clone(), + }) + } + } +} + +fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[TokenTree]) + -> (P, Vec) { + // NB: It appears that the main parser loses its mind if we consider + // $foo as a SubstNt during the main parse, so we have to re-parse + // under quote_depth > 0. This is silly and should go away; the _guess_ is + // it has to do with transition away from supporting old-style macros, so + // try removing it when enough of them are gone. + + let mut p = cx.new_parser_from_tts(tts); + p.quote_depth += 1; + + let cx_expr = panictry!(p.parse_expr()); + + if !p.eat(&token::Comma) { + let _ = p.diagnostic().fatal("expected token `,`"); + } + + let tts = panictry!(p.parse_all_token_trees()); + p.abort_if_errors(); + + (cx_expr, tts) +} + +fn mk_stmts_let(builder: &aster::AstBuilder) -> Vec { + // We also bind a single value, sp, to ext_cx.call_site() + // + // This causes every span in a token-tree quote to be attributed to the + // call site of the extension using the quote. We can't really do much + // better since the source of the quote may well be in a library that + // was not even parsed by this compilation run, that the user has no + // source code for (eg. in libsyntax, which they're just _using_). + // + // The old quasiquoter had an elaborate mechanism for denoting input + // file locations from which quotes originated; unfortunately this + // relied on feeding the source string of the quote back into the + // compiler (which we don't really want to do) and, in any case, only + // pushed the problem a very small step further back: an error + // resulting from a parse of the resulting quote is still attributed to + // the site the string literal occurred, which was in a source file + // _other_ than the one the user has control over. For example, an + // error in a quote from the protocol compiler, invoked in user code + // using macro_rules! for example, will be attributed to the macro_rules.rs + // file in libsyntax, which the user might not even have source to (unless + // they happen to have a compiler on hand). Over all, the phase distinction + // just makes quotes "hard to attribute". Possibly this could be fixed + // by recreating some of the original qq machinery in the tt regime + // (pushing fake FileMaps onto the parser to account for original sites + // of quotes, for example) but at this point it seems not likely to be + // worth the hassle. + + let e_sp = builder.expr().method_call("call_site") + .id("ext_cx") + .build(); + + let stmt_let_sp = builder.stmt() + .let_id("_sp").build_expr(e_sp); + + let stmt_let_tt = builder.stmt().let_().mut_id("tt") + .expr().call() + .path().global().ids(&["std", "vec", "Vec", "new"]).build() + .build(); + + vec!(stmt_let_sp, stmt_let_tt) +} + +fn statements_mk_tts(tts: &[TokenTree], matcher: bool) -> Result { + let mut ret = QuoteStmts { stmts: vec![], idents: vec![] }; + for tt in tts { + let QuoteStmts { stmts, idents } = try!(statements_mk_tt(tt, matcher)); + ret.stmts.extend(stmts.into_iter()); + ret.idents.extend(idents.into_iter()); + } + Ok(ret) +} + +fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[TokenTree]) + -> (P, P) { + let builder = aster::AstBuilder::new().span(sp); + + let (cx_expr, tts) = parse_arguments_to_quote(cx, tts); + + let mut vector = mk_stmts_let(&builder); + + match statements_mk_tts(&tts[..], false) { + Ok(stmts) => vector.extend(stmts.stmts.into_iter()), + Err(_) => cx.span_fatal(sp, "attempted to repeat an expression containing \ + no syntax variables matched as repeating at this depth"), + } + + let block = builder.expr().block() + .stmt().item().attr().allow(&["unused_imports"]) + .use_().ids(&["quasi", "IntoWrappedIterator"]).build().build() + .stmt().item().attr().allow(&["unused_imports"]) + .use_().ids(&["quasi", "IntoWrappedRepeat"]).build().build() + .with_stmts(vector) + .expr().id("tt"); + + (cx_expr, block) +} + +fn expand_wrapper(sp: Span, + cx_expr: P, + expr: P) -> P { + let builder = aster::AstBuilder::new().span(sp); + + // Explicitly borrow to avoid moving from the invoker (#16992) + let cx_expr_borrow = builder.expr() + .ref_().build_deref(cx_expr); + + let stmt_let_ext_cx = builder.stmt().let_id("ext_cx") + .build_expr(cx_expr_borrow); + + builder.expr().block() + .with_stmt(stmt_let_ext_cx) + .build_expr(expr) +} + +fn expand_parse_call(cx: &ExtCtxt, + sp: Span, + parse_method: &[&str], + arg_exprs: Vec> , + tts: &[TokenTree]) -> P { + let builder = aster::AstBuilder::new().span(sp); + + let (cx_expr, tts_expr) = expand_tts(cx, sp, tts); + + let parse_sess_call = builder.expr().method_call("parse_sess") + .id("ext_cx") + .build(); + + let new_parser_from_tts_path = builder.path() + .global() + .ids(&["syntax", "parse", "new_parser_from_tts"]) + .build(); + + let new_parser_call = builder.expr().call() + .build_path(new_parser_from_tts_path) + .with_arg(parse_sess_call) + .with_arg(tts_expr) + .build(); + + let parse_method_path = builder.path() + .global() + .ids(parse_method) + .build(); + + let expr = builder.expr().call() + .build_path(parse_method_path) + .arg().mut_ref().build(new_parser_call) + .with_args(arg_exprs) + .build(); + + expand_wrapper(sp, cx_expr, expr) +} + +#[cfg(feature = "with-syntex")] +pub fn expand(src: S, dst: D) -> Result<(), syntex::Error> + where S: AsRef, + D: AsRef, +{ + let src = src.as_ref().to_owned(); + let dst = dst.as_ref().to_owned(); + + syntex::with_extra_stack(move || { + let mut registry = syntex::Registry::new(); + register(&mut registry); + registry.expand("", src, dst) + }) +} + +#[cfg(feature = "with-syntex")] +fn register(reg: &mut syntex::Registry) { + reg.add_macro("quote_tokens", expand_quote_tokens); + reg.add_macro("quote_ty", expand_quote_ty); + reg.add_macro("quote_expr", expand_quote_expr); + reg.add_macro("quote_matcher", expand_quote_matcher); + reg.add_macro("quote_stmt", expand_quote_stmt); + reg.add_macro("quote_attr", expand_quote_attr); + reg.add_macro("quote_pat", expand_quote_pat); + reg.add_macro("quote_arm", expand_quote_arm); + reg.add_macro("quote_block", expand_quote_block); + reg.add_macro("quote_item", expand_quote_item); + reg.add_macro("quote_impl_item", expand_quote_impl_item); + //reg.add_macro("quote_where_clause", expand_quote_where_clause); +} + +#[cfg(not(feature = "syntex"))] +pub fn register(reg: &mut rustc_plugin::Registry) { + reg.register_macro("quote_tokens", expand_quote_tokens); + reg.register_macro("quote_ty", expand_quote_ty); + reg.register_macro("quote_expr", expand_quote_expr); + reg.register_macro("quote_matcher", expand_quote_matcher); + reg.register_macro("quote_stmt", expand_quote_stmt); + reg.register_macro("quote_attr", expand_quote_attr); + reg.register_macro("quote_pat", expand_quote_pat); + reg.register_macro("quote_arm", expand_quote_arm); + reg.register_macro("quote_block", expand_quote_block); + reg.register_macro("quote_item", expand_quote_item); + reg.register_macro("quote_impl_item", expand_quote_impl_item); + //reg.register_macro("quote_where_clause", expand_quote_where_clause); +} diff --git a/bash-5.1/vendor/rand/.cargo-checksum.json b/bash-5.1/vendor/rand/.cargo-checksum.json new file mode 100644 index 0000000..875021e --- /dev/null +++ b/bash-5.1/vendor/rand/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"ddc101ef9368ef83c21ea9e43064307b1c59b0698b78f59ea01cba32c0ef55bf","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"54c97aa3fc80f7482358b32df3fb96dbd63a4b52fb7f2eb06f1707cda7d15f09","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"d442009fc242a0670f6e7a418862c67514e2c544a43c88b24cb7f37695b8ae38","benches/distributions.rs":"fea4337cd3eb6eaa7bb3250bb04b084290a2b081d3f4679510f3e1dab9c9506b","benches/generators.rs":"19286f1022041bca7e9f83ff615534397565246d5cd26c53abcaeaebebad6773","benches/misc.rs":"c0302e0d9ab973ba4463506d90f89f903104b2a42fc11247be2056a2e1cb561f","benches/seq.rs":"188043fe02640c3936da7634517d0bc0bbdbf685739c52d2ec51a95f238aa347","build.rs":"00d4e7d3521f631913001cfaeb5c97f9dab8b550346046deb2683b962a99e9b3","examples/monte-carlo.rs":"2161c9c1ed90af6b72a5b05b6650d5fce6a983873c29c99798957099cd7a5153","examples/monty-hall.rs":"6a1921868c41d4c130a6b098632f2c127d2446ac6a73aeea10b79b845df1cbbc","src/deprecated.rs":"da2a39dfc440a09bdcdf5af93842dce0fbbc179e5e7146dc94ea861c244bf4c5","src/distributions/bernoulli.rs":"02526bdc24fe17f390505779fb38a441c6a1792c1f7e6093d8b86e143bf9e07e","src/distributions/binomial.rs":"5e2cd6ebc0a5411a4af26ff07d05dd30ae91fc47852cd29757b370ce496074b6","src/distributions/cauchy.rs":"b49d4abd1d861e9f9e9a27444680ea0e24779a6a263dce07c400cf43bab9363c","src/distributions/dirichlet.rs":"b6c0273216a05d32ab21320c11f46f80bc6a6173c93f7aa63fd397927fa365fb","src/distributions/exponential.rs":"7e8a98b63a271714c1f982dd15bc21626593691eaa92c7a76bd59af7b37a56a2","src/distributions/float.rs":"6e1e15b47f9efd282a0e7d140c141d35ece4ebbb748ce7ead620782dc492e88f","src/distributions/gamma.rs":"c922a1b7b2f20ee5a7f5241a252b8b947ab998a88a747df488380211b865f9a6","src/distributions/integer.rs":"b615123a814b118f8bc0563cd7615eec7ee171223bf8100416fb7d22e350c8d7","src/distributions/mod.rs":"6824a6a461d84aef22646d6c3ac8af5d2b5dfc90f09d537be2112fde98a9a8ea","src/distributions/normal.rs":"fe5df9d00ff4038ef6e1f6ca22971547aaec57887c700a511806da01bb4a2f17","src/distributions/other.rs":"44abe480bdc2000ca91a9d41c04e3d5fff2b08e81dfc9168d82c90ddc5cbf616","src/distributions/pareto.rs":"8a9d0f6a7b7221c5716f92b4b65dc19954c146eaeeddcc0b9533d01e2b7414ff","src/distributions/poisson.rs":"918f36d9f7b6c9c4a249b49138cf4df5e1498dd894e3856c21d2f82b83d33e53","src/distributions/triangular.rs":"5a3927b4f1306686591c6d6f3df01d774a5dbf9ec2450ee2f3ce6a71b54f744d","src/distributions/uniform.rs":"9536012592e978cda4e72cd936f21b9986704468de531fbe873f25f763afa4da","src/distributions/unit_circle.rs":"007815186a3696a3d835e9004f51e52402557a7cda09219a0ade13122578e1bd","src/distributions/unit_sphere.rs":"24b8dea60bee580378713477235ddac5e8da07e4f9ceb610fe655ec82390abaf","src/distributions/utils.rs":"68a8257290fdbbd1e72c77e55f21aab4420c6ff168ffb82f7cabc3ad815f4803","src/distributions/weibull.rs":"7678c47145bbb8455fb34326e59d05c2564d427b9c13d5d32435119fd37b5eeb","src/distributions/weighted.rs":"2c98d09ed15d204687efce857129742f905e50e96ba0518122a742f3b47753df","src/distributions/ziggurat_tables.rs":"6368acec20801c703ae76dd1e08983793732c5ac221c491f85d719ef75448b6d","src/lib.rs":"5a7c48d633e75c6d9f2598651ac7b754b3b34fec4212bdc50358a0abbc4ffc62","src/prelude.rs":"36f87f720c1ce0c9d0041872b0498e016b5578b96ba4f6152765ac5084d3b5da","src/prng/mod.rs":"e38182ca652acd0f9348e70e6896e2143b11e9cdcdb34fc78ad13b150dbd7da9","src/rngs/adapter/mod.rs":"e8f37aed72eaebc7dff20787f194e3a74da3e824e2b92a6839b7e6f01fcd911c","src/rngs/adapter/read.rs":"f9502c774607b5c3e62b87ea58698db258486b7c0dbb9b01559e3c18b468bb34","src/rngs/adapter/reseeding.rs":"0ce93bd0f00da429459bca7081346bddea85735bf2d617bcde92708907016a0d","src/rngs/entropy.rs":"cd89359f7891e955245279e4848c37733c508a8cf126eee34f2361a228014f4e","src/rngs/mock.rs":"ef812949b98e4f2eea3e62f8b3ee56edaeffc99d17625337efc882b7b2b19f4b","src/rngs/mod.rs":"440870d8066f1fbeb5d3b178bbf62d899f565d3cbc99c9b179ae4bca81b45a4f","src/rngs/small.rs":"eb942851fe2c2ce11eb0fe179efdfe2889dfc9bc72398bddbdfa327882935dd9","src/rngs/std.rs":"8420c2c32f312b2400ed23afdd9019632c2dd61bb5bd935d6d73bacbcbb9a5b2","src/rngs/thread.rs":"82ef4cf043d16d1d3e6f0037b269f817b133833240f866cd8a7b6e82d3c279ff","src/seq/index.rs":"384500a66361d21531db1380474066fa0bafb672ff7c9db00208b30a94664511","src/seq/mod.rs":"5a9938dc2ac75f393b54267abced2c5f7fbba4ffbdeb6ecdc80afe618c28fea6","tests/uniformity.rs":"0b774361f7db445bd910ad2cbac71207d01ace6881b8d501f4ff01bffd16cd68"},"package":"6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand/CHANGELOG.md b/bash-5.1/vendor/rand/CHANGELOG.md new file mode 100644 index 0000000..955e872 --- /dev/null +++ b/bash-5.1/vendor/rand/CHANGELOG.md @@ -0,0 +1,522 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +A [separate changelog is kept for rand_core](rand_core/CHANGELOG.md). + +You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.html) useful. + + +## [0.6.5] - 2019-01-28 +### Crates +- Update `rand_core` to 0.4 (#703) +- Move `JitterRng` to its own crate (#685) +- Add a warm-bindgen test crate (#696) + +### Platforms +- Fuchsia: Replaced fuchsia-zircon with fuchsia-cprng + +### Doc +- Use RFC 1946 for doc links (#691) +- Fix some doc links and notes (#711) + +## [0.6.4] - 2019-01-08 +### Fixes +- Move wasm-bindgen shims to correct crate (#686) +- Make `wasm32-unknown-unknown` compile but fail at run-time if missing bindingsg (#686) + +## [0.6.3] - 2019-01-04 +### Fixes +- Make the `std` feature require the optional `rand_os` dependency (#675) +- Re-export the optional WASM dependencies of `rand_os` from `rand` to avoid breakage (#674) + +## [0.6.2] - 2019-01-04 +### Additions +- Add `Default` for `ThreadRng` (#657) +- Move `rngs::OsRng` to `rand_os` sub-crate; clean up code; use as dependency (#643) ##BLOCKER## +- Add `rand_xoshiro` sub-crate, plus benchmarks (#642, #668) + +### Fixes +- Fix bias in `UniformInt::sample_single` (#662) +- Use `autocfg` instead of `rustc_version` for rustc version detection (#664) +- Disable `i128` and `u128` if the `target_os` is `emscripten` (#671: work-around Emscripten limitation) +- CI fixes (#660, #671) + +### Optimisations +- Optimise memory usage of `UnitCircle` and `UnitSphereSurface` distributions (no PR) + +## [0.6.1] - 2018-11-22 +- Support sampling `Duration` also for `no_std` (only since Rust 1.25) (#649) +- Disable default features of `libc` (#647) + +## [0.6.0] - 2018-11-14 + +### Project organisation +- Rand has moved from [rust-lang-nursery](https://github.com/rust-lang-nursery/rand) + to [rust-random](https://github.com/rust-random/rand)! (#578) +- Created [The Rust Random Book](https://rust-random.github.io/book/) + ([source](https://github.com/rust-random/book)) +- Update copyright and licence notices (#591, #611) +- Migrate policy documentation from the wiki (#544) + +### Platforms +- Add fork protection on Unix (#466) +- Added support for wasm-bindgen. (#541, #559, #562, #600) +- Enable `OsRng` for powerpc64, sparc and sparc64 (#609) +- Use `syscall` from `libc` on Linux instead of redefining it (#629) + +### RNGs +- Switch `SmallRng` to use PCG (#623) +- Implement `Pcg32` and `Pcg64Mcg` generators (#632) +- Move ISAAC RNGs to a dedicated crate (#551) +- Move Xorshift RNG to its own crate (#557) +- Move ChaCha and HC128 RNGs to dedicated crates (#607, #636) +- Remove usage of `Rc` from `ThreadRng` (#615) + +### Sampling and distributions +- Implement `Rng.gen_ratio()` and `Bernoulli::new_ratio()` (#491) +- Make `Uniform` strictly respect `f32` / `f64` high/low bounds (#477) +- Allow `gen_range` and `Uniform` to work on non-`Copy` types (#506) +- `Uniform` supports inclusive ranges: `Uniform::from(a..=b)`. This is + automatically enabled for Rust >= 1.27. (#566) +- Implement `TrustedLen` and `FusedIterator` for `DistIter` (#620) + +#### New distributions +- Add the `Dirichlet` distribution (#485) +- Added sampling from the unit sphere and circle. (#567) +- Implement the triangular distribution (#575) +- Implement the Weibull distribution (#576) +- Implement the Beta distribution (#574) + +#### Optimisations + +- Optimise `Bernoulli::new` (#500) +- Optimise `char` sampling (#519) +- Optimise sampling of `std::time::Duration` (#583) + +### Sequences +- Redesign the `seq` module (#483, #515) +- Add `WeightedIndex` and `choose_weighted` (#518, #547) +- Optimised and changed return type of the `sample_indices` function. (#479) +- Use `Iterator::size_hint()` to speed up `IteratorRandom::choose` (#593) + +### SIMD +- Support for generating SIMD types (#523, #542, #561, #630) + +### Other +- Revise CI scripts (#632, #635) +- Remove functionality already deprecated in 0.5 (#499) +- Support for `i128` and `u128` is automatically enabled for Rust >= 1.26. This + renders the `i128_support` feature obsolete. It still exists for backwards + compatibility but does not have any effect. This breaks programs using Rand + with `i128_support` on nightlies older than Rust 1.26. (#571) + + +## [0.5.5] - 2018-08-07 +### Documentation +- Fix links in documentation (#582) + + +## [0.5.4] - 2018-07-11 +### Platform support +- Make `OsRng` work via WASM/stdweb for WebWorkers + + +## [0.5.3] - 2018-06-26 +### Platform support +- OpenBSD, Bitrig: fix compilation (broken in 0.5.1) (#530) + + +## [0.5.2] - 2018-06-18 +### Platform support +- Hide `OsRng` and `JitterRng` on unsupported platforms (#512; fixes #503). + + +## [0.5.1] - 2018-06-08 + +### New distributions +- Added Cauchy distribution. (#474, #486) +- Added Pareto distribution. (#495) + +### Platform support and `OsRng` +- Remove blanket Unix implementation. (#484) +- Remove Wasm unimplemented stub. (#484) +- Dragonfly BSD: read from `/dev/random`. (#484) +- Bitrig: use `getentropy` like OpenBSD. (#484) +- Solaris: (untested) use `getrandom` if available, otherwise `/dev/random`. (#484) +- Emscripten, `stdweb`: split the read up in chunks. (#484) +- Emscripten, Haiku: don't do an extra blocking read from `/dev/random`. (#484) +- Linux, NetBSD, Solaris: read in blocking mode on first use in `fill_bytes`. (#484) +- Fuchsia, CloudABI: fix compilation (broken in Rand 0.5). (#484) + + +## [0.5.0] - 2018-05-21 + +### Crate features and organisation +- Minimum Rust version update: 1.22.0. (#239) +- Create a separate `rand_core` crate. (#288) +- Deprecate `rand_derive`. (#256) +- Add `prelude` (and module reorganisation). (#435) +- Add `log` feature. Logging is now available in `JitterRng`, `OsRng`, `EntropyRng` and `ReseedingRng`. (#246) +- Add `serde1` feature for some PRNGs. (#189) +- `stdweb` feature for `OsRng` support on WASM via stdweb. (#272, #336) + +### `Rng` trait +- Split `Rng` in `RngCore` and `Rng` extension trait. + `next_u32`, `next_u64` and `fill_bytes` are now part of `RngCore`. (#265) +- Add `Rng::sample`. (#256) +- Deprecate `Rng::gen_weighted_bool`. (#308) +- Add `Rng::gen_bool`. (#308) +- Remove `Rng::next_f32` and `Rng::next_f64`. (#273) +- Add optimized `Rng::fill` and `Rng::try_fill` methods. (#247) +- Deprecate `Rng::gen_iter`. (#286) +- Deprecate `Rng::gen_ascii_chars`. (#279) + +### `rand_core` crate +- `rand` now depends on new `rand_core` crate (#288) +- `RngCore` and `SeedableRng` are now part of `rand_core`. (#288) +- Add modules to help implementing RNGs `impl` and `le`. (#209, #228) +- Add `Error` and `ErrorKind`. (#225) +- Add `CryptoRng` marker trait. (#273) +- Add `BlockRngCore` trait. (#281) +- Add `BlockRng` and `BlockRng64` wrappers to help implementations. (#281, #325) +- Revise the `SeedableRng` trait. (#233) +- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. (#288) +- Add `RngCore::try_fill_bytes`. (#225) + +### Other traits and types +- Add `FromEntropy` trait. (#233, #375) +- Add `SmallRng` wrapper. (#296) +- Rewrite `ReseedingRng` to only work with `BlockRngCore` (substantial performance improvement). (#281) +- Deprecate `weak_rng`. Use `SmallRng` instead. (#296) +- Deprecate `AsciiGenerator`. (#279) + +### Random number generators +- Switch `StdRng` and `thread_rng` to HC-128. (#277) +- `StdRng` must now be created with `from_entropy` instead of `new` +- Change `thread_rng` reseeding threshold to 32 MiB. (#277) +- PRNGs no longer implement `Copy`. (#209) +- `Debug` implementations no longer show internals. (#209) +- Implement `Clone` for `ReseedingRng`, `JitterRng`, OsRng`. (#383, #384) +- Implement serialization for `XorShiftRng`, `IsaacRng` and `Isaac64Rng` under the `serde1` feature. (#189) +- Implement `BlockRngCore` for `ChaChaCore` and `Hc128Core`. (#281) +- All PRNGs are now portable across big- and little-endian architectures. (#209) +- `Isaac64Rng::next_u32` no longer throws away half the results. (#209) +- Add `IsaacRng::new_from_u64` and `Isaac64Rng::new_from_u64`. (#209) +- Add the HC-128 CSPRNG `Hc128Rng`. (#210) +- Change ChaCha20 to have 64-bit counter and 64-bit stream. (#349) +- Changes to `JitterRng` to get its size down from 2112 to 24 bytes. (#251) +- Various performance improvements to all PRNGs. + +### Platform support and `OsRng` +- Add support for CloudABI. (#224) +- Remove support for NaCl. (#225) +- WASM support for `OsRng` via stdweb, behind the `stdweb` feature. (#272, #336) +- Use `getrandom` on more platforms for Linux, and on Android. (#338) +- Use the `SecRandomCopyBytes` interface on macOS. (#322) +- On systems that do not have a syscall interface, only keep a single file descriptor open for `OsRng`. (#239) +- On Unix, first try a single read from `/dev/random`, then `/dev/urandom`. (#338) +- Better error handling and reporting in `OsRng` (using new error type). (#225) +- `OsRng` now uses non-blocking when available. (#225) +- Add `EntropyRng`, which provides `OsRng`, but has `JitterRng` as a fallback. (#235) + +### Distributions +- New `Distribution` trait. (#256) +- Add `Distribution::sample_iter` and `Rng::::sample_iter`. (#361) +- Deprecate `Rand`, `Sample` and `IndependentSample` traits. (#256) +- Add a `Standard` distribution (replaces most `Rand` implementations). (#256) +- Add `Binomial` and `Poisson` distributions. (#96) +- Add `Bernoulli` dsitribution. (#411) +- Add `Alphanumeric` distribution. (#279) +- Remove `Closed01` distribution, add `OpenClosed01`. (#274, #420) +- Rework `Range` type, making it possible to implement it for user types. (#274) +- Rename `Range` to `Uniform`. (#395) +- Add `Uniform::new_inclusive` for inclusive ranges. (#274) +- Use widening multiply method for much faster integer range reduction. (#274) +- `Standard` distribution for `char` uses `Uniform` internally. (#274) +- `Standard` distribution for `bool` uses sign test. (#274) +- Implement `Standard` distribution for `Wrapping`. (#436) +- Implement `Uniform` distribution for `Duration`. (#427) + + +## [0.4.3] - 2018-08-16 +### Fixed +- Use correct syscall number for PowerPC (#589) + + +## [0.4.2] - 2018-01-06 +### Changed +- Use `winapi` on Windows +- Update for Fuchsia OS +- Remove dev-dependency on `log` + + +## [0.4.1] - 2017-12-17 +### Added +- `no_std` support + + +## [0.4.0-pre.0] - 2017-12-11 +### Added +- `JitterRng` added as a high-quality alternative entropy source using the + system timer +- new `seq` module with `sample_iter`, `sample_slice`, etc. +- WASM support via dummy implementations (fail at run-time) +- Additional benchmarks, covering generators and new seq code + +### Changed +- `thread_rng` uses `JitterRng` if seeding from system time fails + (slower but more secure than previous method) + +### Deprecated + - `sample` function deprecated (replaced by `sample_iter`) + + +## [0.3.20] - 2018-01-06 +### Changed +- Remove dev-dependency on `log` +- Update `fuchsia-zircon` dependency to 0.3.2 + + +## [0.3.19] - 2017-12-27 +### Changed +- Require `log <= 0.3.8` for dev builds +- Update `fuchsia-zircon` dependency to 0.3 +- Fix broken links in docs (to unblock compiler docs testing CI) + + +## [0.3.18] - 2017-11-06 +### Changed +- `thread_rng` is seeded from the system time if `OsRng` fails +- `weak_rng` now uses `thread_rng` internally + + +## [0.3.17] - 2017-10-07 +### Changed + - Fuchsia: Magenta was renamed Zircon + +## [0.3.16] - 2017-07-27 +### Added +- Implement Debug for mote non-public types +- implement `Rand` for (i|u)i128 +- Support for Fuchsia + +### Changed +- Add inline attribute to SampleRange::construct_range. + This improves the benchmark for sample in 11% and for shuffle in 16%. +- Use `RtlGenRandom` instead of `CryptGenRandom` + + +## [0.3.15] - 2016-11-26 +### Added +- Add `Rng` trait method `choose_mut` +- Redox support + +### Changed +- Use `arc4rand` for `OsRng` on FreeBSD. +- Use `arc4random(3)` for `OsRng` on OpenBSD. + +### Fixed +- Fix filling buffers 4 GiB or larger with `OsRng::fill_bytes` on Windows + + +## [0.3.14] - 2016-02-13 +### Fixed +- Inline definitions from winapi/advapi32, wich decreases build times + + +## [0.3.13] - 2016-01-09 +### Fixed +- Compatible with Rust 1.7.0-nightly (needed some extra type annotations) + + +## [0.3.12] - 2015-11-09 +### Changed +- Replaced the methods in `next_f32` and `next_f64` with the technique described + Saito & Matsumoto at MCQMC'08. The new method should exhibit a slightly more + uniform distribution. +- Depend on libc 0.2 + +### Fixed +- Fix iterator protocol issue in `rand::sample` + + +## [0.3.11] - 2015-08-31 +### Added +- Implement `Rand` for arrays with n <= 32 + + +## [0.3.10] - 2015-08-17 +### Added +- Support for NaCl platforms + +### Changed +- Allow `Rng` to be `?Sized`, impl for `&mut R` and `Box` where `R: ?Sized + Rng` + + +## [0.3.9] - 2015-06-18 +### Changed +- Use `winapi` for Windows API things + +### Fixed +- Fixed test on stable/nightly +- Fix `getrandom` syscall number for aarch64-unknown-linux-gnu + + +## [0.3.8] - 2015-04-23 +### Changed +- `log` is a dev dependency + +### Fixed +- Fix race condition of atomics in `is_getrandom_available` + + +## [0.3.7] - 2015-04-03 +### Fixed +- Derive Copy/Clone changes + + +## [0.3.6] - 2015-04-02 +### Changed +- Move to stable Rust! + + +## [0.3.5] - 2015-04-01 +### Fixed +- Compatible with Rust master + + +## [0.3.4] - 2015-03-31 +### Added +- Implement Clone for `Weighted` + +### Fixed +- Compatible with Rust master + + +## [0.3.3] - 2015-03-26 +### Fixed +- Fix compile on Windows + + +## [0.3.2] - 2015-03-26 + + +## [0.3.1] - 2015-03-26 +### Fixed +- Fix compile on Windows + + +## [0.3.0] - 2015-03-25 +### Changed +- Update to use log version 0.3.x + + +## [0.2.1] - 2015-03-22 +### Fixed +- Compatible with Rust master +- Fixed iOS compilation + + +## [0.2.0] - 2015-03-06 +### Fixed +- Compatible with Rust master (move from `old_io` to `std::io`) + + +## [0.1.4] - 2015-03-04 +### Fixed +- Compatible with Rust master (use wrapping ops) + + +## [0.1.3] - 2015-02-20 +### Fixed +- Compatible with Rust master + +### Removed +- Removed Copy implementations from RNGs + + +## [0.1.2] - 2015-02-03 +### Added +- Imported functionality from `std::rand`, including: + - `StdRng`, `SeedableRng`, `TreadRng`, `weak_rng()` + - `ReaderRng`: A wrapper around any Reader to treat it as an RNG. +- Imported documentation from `std::rand` +- Imported tests from `std::rand` + + +## [0.1.1] - 2015-02-03 +### Added +- Migrate to a cargo-compatible directory structure. + +### Fixed +- Do not use entropy during `gen_weighted_bool(1)` + + +## [Rust 0.12.0] - 2014-10-09 +### Added +- Impl Rand for tuples of arity 11 and 12 +- Include ChaCha pseudorandom generator +- Add `next_f64` and `next_f32` to Rng +- Implement Clone for PRNGs + +### Changed +- Rename `TaskRng` to `ThreadRng` and `task_rng` to `thread_rng` (since a + runtime is removed from Rust). + +### Fixed +- Improved performance of ISAAC and ISAAC64 by 30% and 12 % respectively, by + informing the optimiser that indexing is never out-of-bounds. + +### Removed +- Removed the Deprecated `choose_option` + + +## [Rust 0.11.0] - 2014-07-02 +### Added +- document when to use `OSRng` in cryptographic context, and explain why we use `/dev/urandom` instead of `/dev/random` +- `Rng::gen_iter()` which will return an infinite stream of random values +- `Rng::gen_ascii_chars()` which will return an infinite stream of random ascii characters + +### Changed +- Now only depends on libcore! +- Remove `Rng.choose()`, rename `Rng.choose_option()` to `.choose()` +- Rename OSRng to OsRng +- The WeightedChoice structure is no longer built with a `Vec>`, + but rather a `&mut [Weighted]`. This means that the WeightedChoice + structure now has a lifetime associated with it. +- The `sample` method on `Rng` has been moved to a top-level function in the + `rand` module due to its dependence on `Vec`. + +### Removed +- `Rng::gen_vec()` was removed. Previous behavior can be regained with + `rng.gen_iter().take(n).collect()` +- `Rng::gen_ascii_str()` was removed. Previous behavior can be regained with + `rng.gen_ascii_chars().take(n).collect()` +- {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all + relied on being able to use an OSRng for seeding, but this is no longer + available in librand (where these types are defined). To retain the same + functionality, these types now implement the `Rand` trait so they can be + generated with a random seed from another random number generator. This allows + the stdlib to use an OSRng to create seeded instances of these RNGs. +- Rand implementations for `Box` and `@T` were removed. These seemed to be + pretty rare in the codebase, and it allows for librand to not depend on + liballoc. Additionally, other pointer types like Rc and Arc were not + supported. +- Remove a slew of old deprecated functions + + +## [Rust 0.10] - 2014-04-03 +### Changed +- replace `Rng.shuffle's` functionality with `.shuffle_mut` +- bubble up IO errors when creating an OSRng + +### Fixed +- Use `fill()` instead of `read()` +- Rewrite OsRng in Rust for windows + +## [0.10-pre] - 2014-03-02 +### Added +- Seperate `rand` out of the standard library diff --git a/bash-5.1/vendor/rand/COPYRIGHT b/bash-5.1/vendor/rand/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand/Cargo.toml b/bash-5.1/vendor/rand/Cargo.toml new file mode 100644 index 0000000..fc0313a --- /dev/null +++ b/bash-5.1/vendor/rand/Cargo.toml @@ -0,0 +1,90 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand" +version = "0.6.5" +authors = ["The Rand Project Developers", "The Rust Project Developers"] +build = "build.rs" +exclude = ["/utils/*", "/.travis.yml", "/appveyor.yml", ".gitignore"] +description = "Random number generators and other randomness functionality.\n" +homepage = "https://crates.io/crates/rand" +documentation = "https://rust-random.github.io/rand" +readme = "README.md" +keywords = ["random", "rng"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[package.metadata.docs.rs] +all-features = true +[dependencies.log] +version = "0.4" +optional = true + +[dependencies.packed_simd] +version = "0.3" +features = ["into_bits"] +optional = true + +[dependencies.rand_chacha] +version = "0.1" + +[dependencies.rand_core] +version = "0.4" + +[dependencies.rand_hc] +version = "0.1" + +[dependencies.rand_isaac] +version = "0.1" + +[dependencies.rand_jitter] +version = "0.1" + +[dependencies.rand_os] +version = "0.1" +optional = true + +[dependencies.rand_pcg] +version = "0.1" + +[dependencies.rand_xorshift] +version = "0.1" +[dev-dependencies.average] +version = "0.9.2" + +[dev-dependencies.rand_xoshiro] +version = "0.1" +[build-dependencies.autocfg] +version = "0.1" + +[features] +alloc = ["rand_core/alloc"] +default = ["std"] +i128_support = [] +nightly = ["simd_support"] +serde1 = ["rand_core/serde1", "rand_isaac/serde1", "rand_xorshift/serde1"] +simd_support = ["packed_simd"] +std = ["rand_core/std", "alloc", "rand_os", "rand_jitter/std"] +stdweb = ["rand_os/stdweb"] +wasm-bindgen = ["rand_os/wasm-bindgen"] +[target."cfg(unix)".dependencies.libc] +version = "0.2" +default-features = false +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["minwindef", "ntsecapi", "profileapi", "winnt"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand/LICENSE-APACHE b/bash-5.1/vendor/rand/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand/LICENSE-MIT b/bash-5.1/vendor/rand/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand/README.md b/bash-5.1/vendor/rand/README.md new file mode 100644 index 0000000..314a57f --- /dev/null +++ b/bash-5.1/vendor/rand/README.md @@ -0,0 +1,122 @@ +# Rand + +[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Crate](https://img.shields.io/crates/v/rand.svg)](https://crates.io/crates/rand) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand) +[![API](https://docs.rs/rand/badge.svg)](https://docs.rs/rand) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +A Rust library for random number generation. + +Rand provides utilities to generate random numbers, to convert them to useful +types and distributions, and some randomness-related algorithms. + +The core random number generation traits of Rand live in the [rand_core]( +https://crates.io/crates/rand_core) crate but are also exposed here; RNG +implementations should prefer to use `rand_core` while most other users should +depend on `rand`. + +Documentation: +- [The Rust Rand Book](https://rust-random.github.io/book) +- [API reference (master)](https://rust-random.github.io/rand) +- [API reference (docs.rs)](https://docs.rs/rand) + + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +rand = "0.6" +``` + +To get started using Rand, see [The Book](https://rust-random.github.io/book). + + +## Versions + +The Rand lib is not yet stable, however we are careful to limit breaking changes +and warn via deprecation wherever possible. Patch versions never introduce +breaking changes. The following minor versions are supported: + +- Version 0.6 was released in November 2018, redesigning the `seq` module, + moving most PRNGs to external crates, and many small changes. +- Version 0.5 was released in May 2018, as a major reorganisation + (introducing `RngCore` and `rand_core`, and deprecating `Rand` and the + previous distribution traits). +- Version 0.4 was released in December 2017, but contained almost no breaking + changes from the 0.3 series. + +A detailed [changelog](CHANGELOG.md) is available. + +When upgrading to the next minor series (especially 0.4 → 0.5), we recommend +reading the [Upgrade Guide](https://rust-random.github.io/book/update.html). + +### Rust version requirements + +Since version 0.5, Rand requires **Rustc version 1.22 or greater**. +Rand 0.4 and 0.3 (since approx. June 2017) require Rustc version 1.15 or +greater. Subsets of the Rand code may work with older Rust versions, but this +is not supported. + +Travis CI always has a build with a pinned version of Rustc matching the oldest +supported Rust release. The current policy is that this can be updated in any +Rand release if required, but the change must be noted in the changelog. + +To avoid bumping the required version unnecessarily, we use a `build.rs` script +to auto-detect the compiler version and enable certain features or change code +paths automatically. Since this makes it easy to unintentionally make use of +features requiring a more recent Rust version, we recommend testing with a +pinned version of Rustc if you require compatibility with a specific version. + +## Crate Features + +Rand is built with the `std` and `rand_os` features enabled by default: + +- `std` enables functionality dependent on the `std` lib and implies `alloc` + and `rand_os` +- `rand_os` enables the `rand_os` crate, `rngs::OsRng` and enables its usage; + the continued existance of this feature is not guaranteed so users are + encouraged to specify `std` instead + +The following optional features are available: + +- `alloc` can be used instead of `std` to provide `Vec` and `Box`. +- `log` enables some logging via the `log` crate. +- `nightly` enables all unstable features (`simd_support`). +- `serde1` enables serialization for some types, via Serde version 1. +- `simd_support` enables uniform sampling of SIMD types (integers and floats). +- `stdweb` enables support for `OsRng` on `wasm32-unknown-unknown` via `stdweb` + combined with `cargo-web`. +- `wasm-bindgen` enables support for `OsRng` on `wasm32-unknown-unknown` via + [`wasm-bindgen`] + +[`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen + +`no_std` mode is activated by setting `default-features = false`; this removes +functionality depending on `std`: + +- `thread_rng()`, and `random()` are not available, as they require thread-local + storage and an entropy source. +- `OsRng` and `EntropyRng` are unavailable. +- `JitterRng` code is still present, but a nanosecond timer must be provided via + `JitterRng::new_with_timer` +- Since no external entropy is available, it is not possible to create + generators with fresh seeds using the `FromEntropy` trait (user must provide + a seed). +- Several non-linear distributions distributions are unavailable since `exp` + and `log` functions are not provided in `core`. +- Large parts of the `seq`-uence module are unavailable, unless the `alloc` + feature is used (several APIs and many implementations require `Vec`). + + +# License + +Rand is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand/benches/distributions.rs b/bash-5.1/vendor/rand/benches/distributions.rs new file mode 100644 index 0000000..069a828 --- /dev/null +++ b/bash-5.1/vendor/rand/benches/distributions.rs @@ -0,0 +1,259 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(test)] + +extern crate test; +extern crate rand; + +const RAND_BENCH_N: u64 = 1000; + +use std::mem::size_of; +use test::Bencher; +use std::time::Duration; + +use rand::{Rng, FromEntropy}; +use rand::rngs::SmallRng; +use rand::distributions::*; + +macro_rules! distr_int { + ($fnn:ident, $ty:ty, $distr:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + let distr = $distr; + + b.iter(|| { + let mut accum = 0 as $ty; + for _ in 0..::RAND_BENCH_N { + let x: $ty = distr.sample(&mut rng); + accum = accum.wrapping_add(x); + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; + } + } +} + +macro_rules! distr_float { + ($fnn:ident, $ty:ty, $distr:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + let distr = $distr; + + b.iter(|| { + let mut accum = 0.0; + for _ in 0..::RAND_BENCH_N { + let x: $ty = distr.sample(&mut rng); + accum += x; + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; + } + } +} + +macro_rules! distr_duration { + ($fnn:ident, $distr:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + let distr = $distr; + + b.iter(|| { + let mut accum = Duration::new(0, 0); + for _ in 0..::RAND_BENCH_N { + let x: Duration = distr.sample(&mut rng); + accum = accum.checked_add(x).unwrap_or(Duration::new(u64::max_value(), 999_999_999)); + } + accum + }); + b.bytes = size_of::() as u64 * ::RAND_BENCH_N; + } + } +} + +macro_rules! distr { + ($fnn:ident, $ty:ty, $distr:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + let distr = $distr; + + b.iter(|| { + let mut accum = 0u32; + for _ in 0..::RAND_BENCH_N { + let x: $ty = distr.sample(&mut rng); + accum = accum.wrapping_add(x as u32); + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; + } + } +} + +macro_rules! distr_arr { + ($fnn:ident, $ty:ty, $distr:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + let distr = $distr; + + b.iter(|| { + let mut accum = 0u32; + for _ in 0..::RAND_BENCH_N { + let x: $ty = distr.sample(&mut rng); + accum = accum.wrapping_add(x[0] as u32); + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; + } + } +} + +// uniform +distr_int!(distr_uniform_i8, i8, Uniform::new(20i8, 100)); +distr_int!(distr_uniform_i16, i16, Uniform::new(-500i16, 2000)); +distr_int!(distr_uniform_i32, i32, Uniform::new(-200_000_000i32, 800_000_000)); +distr_int!(distr_uniform_i64, i64, Uniform::new(3i64, 123_456_789_123)); +distr_int!(distr_uniform_i128, i128, Uniform::new(-123_456_789_123i128, 123_456_789_123_456_789)); + +distr_float!(distr_uniform_f32, f32, Uniform::new(2.26f32, 2.319)); +distr_float!(distr_uniform_f64, f64, Uniform::new(2.26f64, 2.319)); + +const LARGE_SEC: u64 = u64::max_value() / 1000; + +distr_duration!(distr_uniform_duration_largest, + Uniform::new_inclusive(Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999)) +); +distr_duration!(distr_uniform_duration_large, + Uniform::new(Duration::new(0, 0), Duration::new(LARGE_SEC, 1_000_000_000 / 2)) +); +distr_duration!(distr_uniform_duration_one, + Uniform::new(Duration::new(0, 0), Duration::new(1, 0)) +); +distr_duration!(distr_uniform_duration_variety, + Uniform::new(Duration::new(10000, 423423), Duration::new(200000, 6969954)) +); +distr_duration!(distr_uniform_duration_edge, + Uniform::new_inclusive(Duration::new(LARGE_SEC, 999_999_999), Duration::new(LARGE_SEC + 1, 1)) +); + + +// standard +distr_int!(distr_standard_i8, i8, Standard); +distr_int!(distr_standard_i16, i16, Standard); +distr_int!(distr_standard_i32, i32, Standard); +distr_int!(distr_standard_i64, i64, Standard); +distr_int!(distr_standard_i128, i128, Standard); + +distr!(distr_standard_bool, bool, Standard); +distr!(distr_standard_alphanumeric, char, Alphanumeric); +distr!(distr_standard_codepoint, char, Standard); + +distr_float!(distr_standard_f32, f32, Standard); +distr_float!(distr_standard_f64, f64, Standard); +distr_float!(distr_open01_f32, f32, Open01); +distr_float!(distr_open01_f64, f64, Open01); +distr_float!(distr_openclosed01_f32, f32, OpenClosed01); +distr_float!(distr_openclosed01_f64, f64, OpenClosed01); + +// distributions +distr_float!(distr_exp, f64, Exp::new(1.23 * 4.56)); +distr_float!(distr_normal, f64, Normal::new(-1.23, 4.56)); +distr_float!(distr_log_normal, f64, LogNormal::new(-1.23, 4.56)); +distr_float!(distr_gamma_large_shape, f64, Gamma::new(10., 1.0)); +distr_float!(distr_gamma_small_shape, f64, Gamma::new(0.1, 1.0)); +distr_float!(distr_cauchy, f64, Cauchy::new(4.2, 6.9)); +distr_int!(distr_binomial, u64, Binomial::new(20, 0.7)); +distr_int!(distr_poisson, u64, Poisson::new(4.0)); +distr!(distr_bernoulli, bool, Bernoulli::new(0.18)); +distr_arr!(distr_circle, [f64; 2], UnitCircle::new()); +distr_arr!(distr_sphere_surface, [f64; 3], UnitSphereSurface::new()); + +// Weighted +distr_int!(distr_weighted_i8, usize, WeightedIndex::new(&[1i8, 2, 3, 4, 12, 0, 2, 1]).unwrap()); +distr_int!(distr_weighted_u32, usize, WeightedIndex::new(&[1u32, 2, 3, 4, 12, 0, 2, 1]).unwrap()); +distr_int!(distr_weighted_f64, usize, WeightedIndex::new(&[1.0f64, 0.001, 1.0/3.0, 4.01, 0.0, 3.3, 22.0, 0.001]).unwrap()); +distr_int!(distr_weighted_large_set, usize, WeightedIndex::new((0..10000).rev().chain(1..10001)).unwrap()); + +// construct and sample from a range +macro_rules! gen_range_int { + ($fnn:ident, $ty:ident, $low:expr, $high:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + + b.iter(|| { + let mut high = $high; + let mut accum: $ty = 0; + for _ in 0..::RAND_BENCH_N { + accum = accum.wrapping_add(rng.gen_range($low, high)); + // force recalculation of range each time + high = high.wrapping_add(1) & std::$ty::MAX; + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; + } + } +} + +gen_range_int!(gen_range_i8, i8, -20i8, 100); +gen_range_int!(gen_range_i16, i16, -500i16, 2000); +gen_range_int!(gen_range_i32, i32, -200_000_000i32, 800_000_000); +gen_range_int!(gen_range_i64, i64, 3i64, 123_456_789_123); +gen_range_int!(gen_range_i128, i128, -12345678901234i128, 123_456_789_123_456_789); + +// construct and sample from a floating-point range +macro_rules! gen_range_float { + ($fnn:ident, $ty:ident, $low:expr, $high:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + + b.iter(|| { + let mut high = $high; + let mut low = $low; + let mut accum: $ty = 0.0; + for _ in 0..::RAND_BENCH_N { + accum += rng.gen_range(low, high); + // force recalculation of range each time + low += 0.9; + high += 1.1; + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; + } + } +} + +gen_range_float!(gen_range_f32, f32, -20000.0f32, 100000.0); +gen_range_float!(gen_range_f64, f64, 123.456f64, 7890.12); + +#[bench] +fn dist_iter(b: &mut Bencher) { + let mut rng = SmallRng::from_entropy(); + let distr = Normal::new(-2.71828, 3.14159); + let mut iter = distr.sample_iter(&mut rng); + + b.iter(|| { + let mut accum = 0.0; + for _ in 0..::RAND_BENCH_N { + accum += iter.next().unwrap(); + } + accum + }); + b.bytes = size_of::() as u64 * ::RAND_BENCH_N; +} diff --git a/bash-5.1/vendor/rand/benches/generators.rs b/bash-5.1/vendor/rand/benches/generators.rs new file mode 100644 index 0000000..a6e3a42 --- /dev/null +++ b/bash-5.1/vendor/rand/benches/generators.rs @@ -0,0 +1,240 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(test)] + +extern crate test; +extern crate rand; +extern crate rand_isaac; +extern crate rand_chacha; +extern crate rand_hc; +extern crate rand_pcg; +extern crate rand_xorshift; +extern crate rand_xoshiro; + +const RAND_BENCH_N: u64 = 1000; +const BYTES_LEN: usize = 1024; + +use std::mem::size_of; +use test::{black_box, Bencher}; + +use rand::prelude::*; +use rand::rngs::adapter::ReseedingRng; +use rand::rngs::{OsRng, JitterRng, EntropyRng}; +use rand_isaac::{IsaacRng, Isaac64Rng}; +use rand_chacha::ChaChaRng; +use rand_hc::{Hc128Rng, Hc128Core}; +use rand_pcg::{Lcg64Xsh32, Mcg128Xsl64}; +use rand_xorshift::XorShiftRng; +use rand_xoshiro::{Xoshiro256StarStar, Xoshiro256Plus, Xoshiro128StarStar, + Xoshiro128Plus, Xoroshiro128StarStar, Xoroshiro128Plus, SplitMix64, + Xoroshiro64StarStar, Xoroshiro64Star}; + +macro_rules! gen_bytes { + ($fnn:ident, $gen:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = $gen; + let mut buf = [0u8; BYTES_LEN]; + b.iter(|| { + for _ in 0..RAND_BENCH_N { + rng.fill_bytes(&mut buf); + black_box(buf); + } + }); + b.bytes = BYTES_LEN as u64 * RAND_BENCH_N; + } + } +} + +gen_bytes!(gen_bytes_xorshift, XorShiftRng::from_entropy()); +gen_bytes!(gen_bytes_xoshiro256starstar, Xoshiro256StarStar::from_entropy()); +gen_bytes!(gen_bytes_xoshiro256plus, Xoshiro256Plus::from_entropy()); +gen_bytes!(gen_bytes_xoshiro128starstar, Xoshiro128StarStar::from_entropy()); +gen_bytes!(gen_bytes_xoshiro128plus, Xoshiro128Plus::from_entropy()); +gen_bytes!(gen_bytes_xoroshiro128starstar, Xoroshiro128StarStar::from_entropy()); +gen_bytes!(gen_bytes_xoroshiro128plus, Xoroshiro128Plus::from_entropy()); +gen_bytes!(gen_bytes_xoroshiro64starstar, Xoroshiro64StarStar::from_entropy()); +gen_bytes!(gen_bytes_xoroshiro64star, Xoroshiro64Star::from_entropy()); +gen_bytes!(gen_bytes_splitmix64, SplitMix64::from_entropy()); +gen_bytes!(gen_bytes_lcg64_xsh32, Lcg64Xsh32::from_entropy()); +gen_bytes!(gen_bytes_mcg128_xsh64, Mcg128Xsl64::from_entropy()); +gen_bytes!(gen_bytes_chacha20, ChaChaRng::from_entropy()); +gen_bytes!(gen_bytes_hc128, Hc128Rng::from_entropy()); +gen_bytes!(gen_bytes_isaac, IsaacRng::from_entropy()); +gen_bytes!(gen_bytes_isaac64, Isaac64Rng::from_entropy()); +gen_bytes!(gen_bytes_std, StdRng::from_entropy()); +gen_bytes!(gen_bytes_small, SmallRng::from_entropy()); +gen_bytes!(gen_bytes_os, OsRng::new().unwrap()); + +macro_rules! gen_uint { + ($fnn:ident, $ty:ty, $gen:expr) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = $gen; + b.iter(|| { + let mut accum: $ty = 0; + for _ in 0..RAND_BENCH_N { + accum = accum.wrapping_add(rng.gen::<$ty>()); + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; + } + } +} + +gen_uint!(gen_u32_xorshift, u32, XorShiftRng::from_entropy()); +gen_uint!(gen_u32_xoshiro256starstar, u32, Xoshiro256StarStar::from_entropy()); +gen_uint!(gen_u32_xoshiro256plus, u32, Xoshiro256Plus::from_entropy()); +gen_uint!(gen_u32_xoshiro128starstar, u32, Xoshiro128StarStar::from_entropy()); +gen_uint!(gen_u32_xoshiro128plus, u32, Xoshiro128Plus::from_entropy()); +gen_uint!(gen_u32_xoroshiro128starstar, u32, Xoroshiro128StarStar::from_entropy()); +gen_uint!(gen_u32_xoroshiro128plus, u32, Xoroshiro128Plus::from_entropy()); +gen_uint!(gen_u32_xoroshiro64starstar, u32, Xoroshiro64StarStar::from_entropy()); +gen_uint!(gen_u32_xoroshiro64star, u32, Xoroshiro64Star::from_entropy()); +gen_uint!(gen_u32_splitmix64, u32, SplitMix64::from_entropy()); +gen_uint!(gen_u32_lcg64_xsh32, u32, Lcg64Xsh32::from_entropy()); +gen_uint!(gen_u32_mcg128_xsh64, u32, Mcg128Xsl64::from_entropy()); +gen_uint!(gen_u32_chacha20, u32, ChaChaRng::from_entropy()); +gen_uint!(gen_u32_hc128, u32, Hc128Rng::from_entropy()); +gen_uint!(gen_u32_isaac, u32, IsaacRng::from_entropy()); +gen_uint!(gen_u32_isaac64, u32, Isaac64Rng::from_entropy()); +gen_uint!(gen_u32_std, u32, StdRng::from_entropy()); +gen_uint!(gen_u32_small, u32, SmallRng::from_entropy()); +gen_uint!(gen_u32_os, u32, OsRng::new().unwrap()); + +gen_uint!(gen_u64_xorshift, u64, XorShiftRng::from_entropy()); +gen_uint!(gen_u64_xoshiro256starstar, u64, Xoshiro256StarStar::from_entropy()); +gen_uint!(gen_u64_xoshiro256plus, u64, Xoshiro256Plus::from_entropy()); +gen_uint!(gen_u64_xoshiro128starstar, u64, Xoshiro128StarStar::from_entropy()); +gen_uint!(gen_u64_xoshiro128plus, u64, Xoshiro128Plus::from_entropy()); +gen_uint!(gen_u64_xoroshiro128starstar, u64, Xoroshiro128StarStar::from_entropy()); +gen_uint!(gen_u64_xoroshiro128plus, u64, Xoroshiro128Plus::from_entropy()); +gen_uint!(gen_u64_xoroshiro64starstar, u64, Xoroshiro64StarStar::from_entropy()); +gen_uint!(gen_u64_xoroshiro64star, u64, Xoroshiro64Star::from_entropy()); +gen_uint!(gen_u64_splitmix64, u64, SplitMix64::from_entropy()); +gen_uint!(gen_u64_lcg64_xsh32, u64, Lcg64Xsh32::from_entropy()); +gen_uint!(gen_u64_mcg128_xsh64, u64, Mcg128Xsl64::from_entropy()); +gen_uint!(gen_u64_chacha20, u64, ChaChaRng::from_entropy()); +gen_uint!(gen_u64_hc128, u64, Hc128Rng::from_entropy()); +gen_uint!(gen_u64_isaac, u64, IsaacRng::from_entropy()); +gen_uint!(gen_u64_isaac64, u64, Isaac64Rng::from_entropy()); +gen_uint!(gen_u64_std, u64, StdRng::from_entropy()); +gen_uint!(gen_u64_small, u64, SmallRng::from_entropy()); +gen_uint!(gen_u64_os, u64, OsRng::new().unwrap()); + +// Do not test JitterRng like the others by running it RAND_BENCH_N times per, +// measurement, because it is way too slow. Only run it once. +#[bench] +fn gen_u64_jitter(b: &mut Bencher) { + let mut rng = JitterRng::new().unwrap(); + b.iter(|| { + rng.gen::() + }); + b.bytes = size_of::() as u64; +} + +macro_rules! init_gen { + ($fnn:ident, $gen:ident) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = XorShiftRng::from_entropy(); + b.iter(|| { + let r2 = $gen::from_rng(&mut rng).unwrap(); + r2 + }); + } + } +} + +init_gen!(init_xorshift, XorShiftRng); +init_gen!(init_xoshiro256starstar, Xoshiro256StarStar); +init_gen!(init_xoshiro256plus, Xoshiro256Plus); +init_gen!(init_xoshiro128starstar, Xoshiro128StarStar); +init_gen!(init_xoshiro128plus, Xoshiro128Plus); +init_gen!(init_xoroshiro128starstar, Xoroshiro128StarStar); +init_gen!(init_xoroshiro128plus, Xoroshiro128Plus); +init_gen!(init_xoroshiro64starstar, Xoroshiro64StarStar); +init_gen!(init_xoroshiro64star, Xoroshiro64Star); +init_gen!(init_splitmix64, SplitMix64); +init_gen!(init_lcg64_xsh32, Lcg64Xsh32); +init_gen!(init_mcg128_xsh64, Mcg128Xsl64); +init_gen!(init_hc128, Hc128Rng); +init_gen!(init_isaac, IsaacRng); +init_gen!(init_isaac64, Isaac64Rng); +init_gen!(init_chacha, ChaChaRng); + +#[bench] +fn init_jitter(b: &mut Bencher) { + b.iter(|| { + JitterRng::new().unwrap() + }); +} + + +const RESEEDING_THRESHOLD: u64 = 1024*1024*1024; // something high enough to get + // deterministic measurements + +#[bench] +fn reseeding_hc128_bytes(b: &mut Bencher) { + let mut rng = ReseedingRng::new(Hc128Core::from_entropy(), + RESEEDING_THRESHOLD, + EntropyRng::new()); + let mut buf = [0u8; BYTES_LEN]; + b.iter(|| { + for _ in 0..RAND_BENCH_N { + rng.fill_bytes(&mut buf); + black_box(buf); + } + }); + b.bytes = BYTES_LEN as u64 * RAND_BENCH_N; +} + +macro_rules! reseeding_uint { + ($fnn:ident, $ty:ty) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = ReseedingRng::new(Hc128Core::from_entropy(), + RESEEDING_THRESHOLD, + EntropyRng::new()); + b.iter(|| { + let mut accum: $ty = 0; + for _ in 0..RAND_BENCH_N { + accum = accum.wrapping_add(rng.gen::<$ty>()); + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; + } + } +} + +reseeding_uint!(reseeding_hc128_u32, u32); +reseeding_uint!(reseeding_hc128_u64, u64); + + +macro_rules! threadrng_uint { + ($fnn:ident, $ty:ty) => { + #[bench] + fn $fnn(b: &mut Bencher) { + let mut rng = thread_rng(); + b.iter(|| { + let mut accum: $ty = 0; + for _ in 0..RAND_BENCH_N { + accum = accum.wrapping_add(rng.gen::<$ty>()); + } + accum + }); + b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; + } + } +} + +threadrng_uint!(thread_rng_u32, u32); +threadrng_uint!(thread_rng_u64, u64); diff --git a/bash-5.1/vendor/rand/benches/misc.rs b/bash-5.1/vendor/rand/benches/misc.rs new file mode 100644 index 0000000..8fb3a83 --- /dev/null +++ b/bash-5.1/vendor/rand/benches/misc.rs @@ -0,0 +1,160 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(test)] + +extern crate test; +extern crate rand; + +const RAND_BENCH_N: u64 = 1000; + +use test::Bencher; + +use rand::prelude::*; + +#[bench] +fn misc_gen_bool_const(b: &mut Bencher) { + let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let mut accum = true; + for _ in 0..::RAND_BENCH_N { + accum ^= rng.gen_bool(0.18); + } + accum + }) +} + +#[bench] +fn misc_gen_bool_var(b: &mut Bencher) { + let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let mut accum = true; + let mut p = 0.18; + for _ in 0..::RAND_BENCH_N { + accum ^= rng.gen_bool(p); + p += 0.0001; + } + accum + }) +} + +#[bench] +fn misc_gen_ratio_const(b: &mut Bencher) { + let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let mut accum = true; + for _ in 0..::RAND_BENCH_N { + accum ^= rng.gen_ratio(2, 3); + } + accum + }) +} + +#[bench] +fn misc_gen_ratio_var(b: &mut Bencher) { + let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let mut accum = true; + for i in 2..(::RAND_BENCH_N as u32 + 2) { + accum ^= rng.gen_ratio(i, i + 1); + } + accum + }) +} + +#[bench] +fn misc_bernoulli_const(b: &mut Bencher) { + let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let d = rand::distributions::Bernoulli::new(0.18); + let mut accum = true; + for _ in 0..::RAND_BENCH_N { + accum ^= rng.sample(d); + } + accum + }) +} + +#[bench] +fn misc_bernoulli_var(b: &mut Bencher) { + let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let mut accum = true; + let mut p = 0.18; + for _ in 0..::RAND_BENCH_N { + let d = rand::distributions::Bernoulli::new(p); + accum ^= rng.sample(d); + p += 0.0001; + } + accum + }) +} + +macro_rules! sample_binomial { + ($name:ident, $n:expr, $p:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); + let (n, p) = ($n, $p); + b.iter(|| { + let d = rand::distributions::Binomial::new(n, p); + rng.sample(d) + }) + } + } +} + +sample_binomial!(misc_binomial_1, 1, 0.9); +sample_binomial!(misc_binomial_10, 10, 0.9); +sample_binomial!(misc_binomial_100, 100, 0.99); +sample_binomial!(misc_binomial_1000, 1000, 0.01); +sample_binomial!(misc_binomial_1e12, 1000_000_000_000, 0.2); + +#[bench] +fn gen_1k_iter_repeat(b: &mut Bencher) { + use std::iter; + let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let v: Vec = iter::repeat(()).map(|()| rng.gen()).take(128).collect(); + v + }); + b.bytes = 1024; +} + +#[bench] +fn gen_1k_sample_iter(b: &mut Bencher) { + use rand::distributions::{Distribution, Standard}; + let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + let v: Vec = Standard.sample_iter(&mut rng).take(128).collect(); + v + }); + b.bytes = 1024; +} + +#[bench] +fn gen_1k_gen_array(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); + b.iter(|| { + // max supported array length is 32! + let v: [[u64; 32]; 4] = rng.gen(); + v + }); + b.bytes = 1024; +} + +#[bench] +fn gen_1k_fill(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); + let mut buf = [0u64; 128]; + b.iter(|| { + rng.fill(&mut buf[..]); + buf + }); + b.bytes = 1024; +} diff --git a/bash-5.1/vendor/rand/benches/seq.rs b/bash-5.1/vendor/rand/benches/seq.rs new file mode 100644 index 0000000..0ca3398 --- /dev/null +++ b/bash-5.1/vendor/rand/benches/seq.rs @@ -0,0 +1,174 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(test)] +#![allow(non_snake_case)] + +extern crate test; +extern crate rand; + +use test::Bencher; + +use rand::prelude::*; +use rand::seq::*; +use std::mem::size_of; + +const RAND_BENCH_N: u64 = 1000; + +#[bench] +fn seq_shuffle_100(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &mut [usize] = &mut [1; 100]; + b.iter(|| { + x.shuffle(&mut rng); + x[0] + }) +} + +#[bench] +fn seq_slice_choose_1_of_1000(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &mut [usize] = &mut [1; 1000]; + for i in 0..1000 { + x[i] = i; + } + b.iter(|| { + let mut s = 0; + for _ in 0..RAND_BENCH_N { + s += x.choose(&mut rng).unwrap(); + } + s + }); + b.bytes = size_of::() as u64 * ::RAND_BENCH_N; +} + +macro_rules! seq_slice_choose_multiple { + ($name:ident, $amount:expr, $length:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &[i32] = &[$amount; $length]; + let mut result = [0i32; $amount]; + b.iter(|| { + // Collect full result to prevent unwanted shortcuts getting + // first element (in case sample_indices returns an iterator). + for (slot, sample) in result.iter_mut().zip( + x.choose_multiple(&mut rng, $amount)) { + *slot = *sample; + } + result[$amount-1] + }) + } + } +} + +seq_slice_choose_multiple!(seq_slice_choose_multiple_1_of_1000, 1, 1000); +seq_slice_choose_multiple!(seq_slice_choose_multiple_950_of_1000, 950, 1000); +seq_slice_choose_multiple!(seq_slice_choose_multiple_10_of_100, 10, 100); +seq_slice_choose_multiple!(seq_slice_choose_multiple_90_of_100, 90, 100); + +#[bench] +fn seq_iter_choose_from_1000(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &mut [usize] = &mut [1; 1000]; + for i in 0..1000 { + x[i] = i; + } + b.iter(|| { + let mut s = 0; + for _ in 0..RAND_BENCH_N { + s += x.iter().choose(&mut rng).unwrap(); + } + s + }); + b.bytes = size_of::() as u64 * ::RAND_BENCH_N; +} + +#[derive(Clone)] +struct UnhintedIterator { + iter: I, +} +impl Iterator for UnhintedIterator { + type Item = I::Item; + fn next(&mut self) -> Option { + self.iter.next() + } +} + +#[derive(Clone)] +struct WindowHintedIterator { + iter: I, + window_size: usize, +} +impl Iterator for WindowHintedIterator { + type Item = I::Item; + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (std::cmp::min(self.iter.len(), self.window_size), None) + } +} + +#[bench] +fn seq_iter_unhinted_choose_from_1000(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &[usize] = &[1; 1000]; + b.iter(|| { + UnhintedIterator { iter: x.iter() }.choose(&mut rng).unwrap() + }) +} + +#[bench] +fn seq_iter_window_hinted_choose_from_1000(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &[usize] = &[1; 1000]; + b.iter(|| { + WindowHintedIterator { iter: x.iter(), window_size: 7 }.choose(&mut rng) + }) +} + +#[bench] +fn seq_iter_choose_multiple_10_of_100(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &[usize] = &[1; 100]; + b.iter(|| { + x.iter().cloned().choose_multiple(&mut rng, 10) + }) +} + +#[bench] +fn seq_iter_choose_multiple_fill_10_of_100(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + let x : &[usize] = &[1; 100]; + let mut buf = [0; 10]; + b.iter(|| { + x.iter().cloned().choose_multiple_fill(&mut rng, &mut buf) + }) +} + +macro_rules! sample_indices { + ($name:ident, $fn:ident, $amount:expr, $length:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); + b.iter(|| { + index::$fn(&mut rng, $length, $amount) + }) + } + } +} + +sample_indices!(misc_sample_indices_1_of_1k, sample, 1, 1000); +sample_indices!(misc_sample_indices_10_of_1k, sample, 10, 1000); +sample_indices!(misc_sample_indices_100_of_1k, sample, 100, 1000); +sample_indices!(misc_sample_indices_100_of_1M, sample, 100, 1000_000); +sample_indices!(misc_sample_indices_100_of_1G, sample, 100, 1000_000_000); +sample_indices!(misc_sample_indices_200_of_1G, sample, 200, 1000_000_000); +sample_indices!(misc_sample_indices_400_of_1G, sample, 400, 1000_000_000); +sample_indices!(misc_sample_indices_600_of_1G, sample, 600, 1000_000_000); diff --git a/bash-5.1/vendor/rand/build.rs b/bash-5.1/vendor/rand/build.rs new file mode 100644 index 0000000..a554ad9 --- /dev/null +++ b/bash-5.1/vendor/rand/build.rs @@ -0,0 +1,10 @@ +extern crate autocfg; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + + let ac = autocfg::new(); + ac.emit_rustc_version(1, 25); + ac.emit_rustc_version(1, 26); + ac.emit_rustc_version(1, 27); +} diff --git a/bash-5.1/vendor/rand/examples/monte-carlo.rs b/bash-5.1/vendor/rand/examples/monte-carlo.rs new file mode 100644 index 0000000..9162996 --- /dev/null +++ b/bash-5.1/vendor/rand/examples/monte-carlo.rs @@ -0,0 +1,51 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! # Monte Carlo estimation of π +//! +//! Imagine that we have a square with sides of length 2 and a unit circle +//! (radius = 1), both centered at the origin. The areas are: +//! +//! ```text +//! area of circle = πr² = π * r * r = π +//! area of square = 2² = 4 +//! ``` +//! +//! The circle is entirely within the square, so if we sample many points +//! randomly from the square, roughly π / 4 of them should be inside the circle. +//! +//! We can use the above fact to estimate the value of π: pick many points in +//! the square at random, calculate the fraction that fall within the circle, +//! and multiply this fraction by 4. + +#![cfg(feature="std")] + + +extern crate rand; + +use rand::distributions::{Distribution, Uniform}; + +fn main() { + let range = Uniform::new(-1.0f64, 1.0); + let mut rng = rand::thread_rng(); + + let total = 1_000_000; + let mut in_circle = 0; + + for _ in 0..total { + let a = range.sample(&mut rng); + let b = range.sample(&mut rng); + if a*a + b*b <= 1.0 { + in_circle += 1; + } + } + + // prints something close to 3.14159... + println!("π is approximately {}", 4. * (in_circle as f64) / (total as f64)); +} diff --git a/bash-5.1/vendor/rand/examples/monty-hall.rs b/bash-5.1/vendor/rand/examples/monty-hall.rs new file mode 100644 index 0000000..0932c5e --- /dev/null +++ b/bash-5.1/vendor/rand/examples/monty-hall.rs @@ -0,0 +1,116 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! ## Monty Hall Problem +//! +//! This is a simulation of the [Monty Hall Problem][]: +//! +//! > Suppose you're on a game show, and you're given the choice of three doors: +//! > Behind one door is a car; behind the others, goats. You pick a door, say +//! > No. 1, and the host, who knows what's behind the doors, opens another +//! > door, say No. 3, which has a goat. He then says to you, "Do you want to +//! > pick door No. 2?" Is it to your advantage to switch your choice? +//! +//! The rather unintuitive answer is that you will have a 2/3 chance of winning +//! if you switch and a 1/3 chance of winning if you don't, so it's better to +//! switch. +//! +//! This program will simulate the game show and with large enough simulation +//! steps it will indeed confirm that it is better to switch. +//! +//! [Monty Hall Problem]: https://en.wikipedia.org/wiki/Monty_Hall_problem + +#![cfg(feature="std")] + + +extern crate rand; + +use rand::Rng; +use rand::distributions::{Distribution, Uniform}; + +struct SimulationResult { + win: bool, + switch: bool, +} + +// Run a single simulation of the Monty Hall problem. +fn simulate(random_door: &Uniform, rng: &mut R) + -> SimulationResult { + let car = random_door.sample(rng); + + // This is our initial choice + let mut choice = random_door.sample(rng); + + // The game host opens a door + let open = game_host_open(car, choice, rng); + + // Shall we switch? + let switch = rng.gen(); + if switch { + choice = switch_door(choice, open); + } + + SimulationResult { win: choice == car, switch } +} + +// Returns the door the game host opens given our choice and knowledge of +// where the car is. The game host will never open the door with the car. +fn game_host_open(car: u32, choice: u32, rng: &mut R) -> u32 { + use rand::seq::SliceRandom; + *free_doors(&[car, choice]).choose(rng).unwrap() +} + +// Returns the door we switch to, given our current choice and +// the open door. There will only be one valid door. +fn switch_door(choice: u32, open: u32) -> u32 { + free_doors(&[choice, open])[0] +} + +fn free_doors(blocked: &[u32]) -> Vec { + (0..3).filter(|x| !blocked.contains(x)).collect() +} + +fn main() { + // The estimation will be more accurate with more simulations + let num_simulations = 10000; + + let mut rng = rand::thread_rng(); + let random_door = Uniform::new(0u32, 3); + + let (mut switch_wins, mut switch_losses) = (0, 0); + let (mut keep_wins, mut keep_losses) = (0, 0); + + println!("Running {} simulations...", num_simulations); + for _ in 0..num_simulations { + let result = simulate(&random_door, &mut rng); + + match (result.win, result.switch) { + (true, true) => switch_wins += 1, + (true, false) => keep_wins += 1, + (false, true) => switch_losses += 1, + (false, false) => keep_losses += 1, + } + } + + let total_switches = switch_wins + switch_losses; + let total_keeps = keep_wins + keep_losses; + + println!("Switched door {} times with {} wins and {} losses", + total_switches, switch_wins, switch_losses); + + println!("Kept our choice {} times with {} wins and {} losses", + total_keeps, keep_wins, keep_losses); + + // With a large number of simulations, the values should converge to + // 0.667 and 0.333 respectively. + println!("Estimated chance to win if we switch: {}", + switch_wins as f32 / total_switches as f32); + println!("Estimated chance to win if we don't: {}", + keep_wins as f32 / total_keeps as f32); +} diff --git a/bash-5.1/vendor/rand/src/deprecated.rs b/bash-5.1/vendor/rand/src/deprecated.rs new file mode 100644 index 0000000..88eb09f --- /dev/null +++ b/bash-5.1/vendor/rand/src/deprecated.rs @@ -0,0 +1,544 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Deprecated re-exports (we can't add deprecation warnings otherwise) + +#![allow(deprecated)] + +use rngs; +use {RngCore, CryptoRng, SeedableRng, Error}; +use rand_core::block::BlockRngCore; +use rand_isaac; +use rand_chacha; +use rand_hc; + +#[cfg(feature="std")] +use std::io::Read; + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", + note="import from rand_isaac crate instead, or use the newer Hc128Rng")] +pub struct IsaacRng(rand_isaac::IsaacRng); + +impl RngCore for IsaacRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for IsaacRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + IsaacRng(rand_isaac::IsaacRng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + rand_isaac::IsaacRng::from_rng(rng).map(IsaacRng) + } +} + +impl IsaacRng { + pub fn new_from_u64(seed: u64) -> Self { + IsaacRng(rand_isaac::IsaacRng::new_from_u64(seed)) + } +} + + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", + note="import from rand_isaac crate instead, or use newer Hc128Rng")] +pub struct Isaac64Rng(rand_isaac::Isaac64Rng); + +impl RngCore for Isaac64Rng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for Isaac64Rng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + Isaac64Rng(rand_isaac::Isaac64Rng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + rand_isaac::Isaac64Rng::from_rng(rng).map(Isaac64Rng) + } +} + +impl Isaac64Rng { + pub fn new_from_u64(seed: u64) -> Self { + Isaac64Rng(rand_isaac::Isaac64Rng::new_from_u64(seed)) + } +} + + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", note="import from rand_chacha crate instead")] +pub struct ChaChaRng(rand_chacha::ChaChaRng); + +impl RngCore for ChaChaRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for ChaChaRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + ChaChaRng(rand_chacha::ChaChaRng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + rand_chacha::ChaChaRng::from_rng(rng).map(ChaChaRng) + } +} + +impl ChaChaRng { + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + pub fn get_word_pos(&self) -> u128 { + self.0.get_word_pos() + } + + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + pub fn set_word_pos(&mut self, word_offset: u128) { + self.0.set_word_pos(word_offset) + } + + pub fn set_stream(&mut self, stream: u64) { + self.0.set_stream(stream) + } +} + +impl CryptoRng for ChaChaRng {} + + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", note="import from rand_hc crate instead")] +pub struct Hc128Rng(rand_hc::Hc128Rng); + +impl RngCore for Hc128Rng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for Hc128Rng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + Hc128Rng(rand_hc::Hc128Rng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + rand_hc::Hc128Rng::from_rng(rng).map(Hc128Rng) + } +} + +impl CryptoRng for Hc128Rng {} + + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", note="import from rand_xorshift crate instead")] +pub struct XorShiftRng(::rand_xorshift::XorShiftRng); + +impl RngCore for XorShiftRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for XorShiftRng { + type Seed = <::rand_xorshift::XorShiftRng as SeedableRng>::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + XorShiftRng(::rand_xorshift::XorShiftRng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + ::rand_xorshift::XorShiftRng::from_rng(rng).map(XorShiftRng) + } +} + + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", + note="import with rand::prelude::* or rand::rngs::StdRng instead")] +pub struct StdRng(rngs::StdRng); + +impl RngCore for StdRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for StdRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + StdRng(rngs::StdRng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + rngs::StdRng::from_rng(rng).map(StdRng) + } +} + +impl CryptoRng for StdRng {} + + +#[cfg(feature="rand_os")] +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", note="import with rand::rngs::OsRng instead")] +pub struct OsRng(rngs::OsRng); + +#[cfg(feature="rand_os")] +impl RngCore for OsRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +#[cfg(feature="rand_os")] +impl OsRng { + pub fn new() -> Result { + rngs::OsRng::new().map(OsRng) + } +} + +#[cfg(feature="rand_os")] +impl CryptoRng for OsRng {} + + +#[cfg(feature="std")] +#[derive(Debug)] +#[deprecated(since="0.6.0", note="import with rand::rngs::EntropyRng instead")] +pub struct EntropyRng(rngs::EntropyRng); + +#[cfg(feature="std")] +impl RngCore for EntropyRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +#[cfg(feature="std")] +impl EntropyRng { + pub fn new() -> Self { + EntropyRng(rngs::EntropyRng::new()) + } +} + +#[cfg(feature="std")] +impl Default for EntropyRng { + fn default() -> Self { + EntropyRng::new() + } +} + +#[cfg(feature="std")] +impl CryptoRng for EntropyRng {} + + +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", note="import with rand::rngs::JitterRng instead")] +pub struct JitterRng(rngs::JitterRng); + +impl RngCore for JitterRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl JitterRng { + #[cfg(all(feature="std", not(target_arch = "wasm32")))] + pub fn new() -> Result { + rngs::JitterRng::new().map(JitterRng) + } + + pub fn new_with_timer(timer: fn() -> u64) -> JitterRng { + JitterRng(rngs::JitterRng::new_with_timer(timer)) + } + + pub fn set_rounds(&mut self, rounds: u8) { + self.0.set_rounds(rounds) + } + + pub fn test_timer(&mut self) -> Result { + self.0.test_timer() + } + + #[cfg(feature="std")] + pub fn timer_stats(&mut self, var_rounds: bool) -> i64 { + self.0.timer_stats(var_rounds) + } +} + +impl CryptoRng for JitterRng {} + + +#[cfg(feature="std")] +#[derive(Clone, Debug)] +#[deprecated(since="0.6.0", + note="import with rand::prelude::* or rand::rngs::ThreadRng instead")] +pub struct ThreadRng(rngs::ThreadRng); + +#[cfg(feature="std")] +impl RngCore for ThreadRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +#[cfg(feature="std")] +impl CryptoRng for ThreadRng {} + + +#[cfg(feature="std")] +#[derive(Debug)] +#[deprecated(since="0.6.0", note="import with rand::rngs::adapter::ReadRng instead")] +pub struct ReadRng(rngs::adapter::ReadRng); + +#[cfg(feature="std")] +impl RngCore for ReadRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +#[cfg(feature="std")] +impl ReadRng { + pub fn new(r: R) -> ReadRng { + ReadRng(rngs::adapter::ReadRng::new(r)) + } +} + + +#[derive(Clone, Debug)] +pub struct ReseedingRng(rngs::adapter::ReseedingRng) +where R: BlockRngCore + SeedableRng, + Rsdr: RngCore; + +impl RngCore for ReseedingRng +where R: BlockRngCore + SeedableRng, + ::Results: AsRef<[u32]> + AsMut<[u32]> +{ + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl ReseedingRng +where R: BlockRngCore + SeedableRng, + Rsdr: RngCore +{ + pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { + ReseedingRng(rngs::adapter::ReseedingRng::new(rng, threshold, reseeder)) + } + + pub fn reseed(&mut self) -> Result<(), Error> { + self.0.reseed() + } +} + +impl CryptoRng for ReseedingRng +where R: BlockRngCore + SeedableRng + CryptoRng, + Rsdr: RngCore + CryptoRng {} diff --git a/bash-5.1/vendor/rand/src/distributions/bernoulli.rs b/bash-5.1/vendor/rand/src/distributions/bernoulli.rs new file mode 100644 index 0000000..f49618c --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/bernoulli.rs @@ -0,0 +1,165 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Bernoulli distribution. + +use Rng; +use distributions::Distribution; + +/// The Bernoulli distribution. +/// +/// This is a special case of the Binomial distribution where `n = 1`. +/// +/// # Example +/// +/// ```rust +/// use rand::distributions::{Bernoulli, Distribution}; +/// +/// let d = Bernoulli::new(0.3); +/// let v = d.sample(&mut rand::thread_rng()); +/// println!("{} is from a Bernoulli distribution", v); +/// ``` +/// +/// # Precision +/// +/// This `Bernoulli` distribution uses 64 bits from the RNG (a `u64`), +/// so only probabilities that are multiples of 2-64 can be +/// represented. +#[derive(Clone, Copy, Debug)] +pub struct Bernoulli { + /// Probability of success, relative to the maximal integer. + p_int: u64, +} + +// To sample from the Bernoulli distribution we use a method that compares a +// random `u64` value `v < (p * 2^64)`. +// +// If `p == 1.0`, the integer `v` to compare against can not represented as a +// `u64`. We manually set it to `u64::MAX` instead (2^64 - 1 instead of 2^64). +// Note that value of `p < 1.0` can never result in `u64::MAX`, because an +// `f64` only has 53 bits of precision, and the next largest value of `p` will +// result in `2^64 - 2048`. +// +// Also there is a 100% theoretical concern: if someone consistenly wants to +// generate `true` using the Bernoulli distribution (i.e. by using a probability +// of `1.0`), just using `u64::MAX` is not enough. On average it would return +// false once every 2^64 iterations. Some people apparently care about this +// case. +// +// That is why we special-case `u64::MAX` to always return `true`, without using +// the RNG, and pay the performance price for all uses that *are* reasonable. +// Luckily, if `new()` and `sample` are close, the compiler can optimize out the +// extra check. +const ALWAYS_TRUE: u64 = ::core::u64::MAX; + +// This is just `2.0.powi(64)`, but written this way because it is not available +// in `no_std` mode. +const SCALE: f64 = 2.0 * (1u64 << 63) as f64; + +impl Bernoulli { + /// Construct a new `Bernoulli` with the given probability of success `p`. + /// + /// # Panics + /// + /// If `p < 0` or `p > 1`. + /// + /// # Precision + /// + /// For `p = 1.0`, the resulting distribution will always generate true. + /// For `p = 0.0`, the resulting distribution will always generate false. + /// + /// This method is accurate for any input `p` in the range `[0, 1]` which is + /// a multiple of 2-64. (Note that not all multiples of + /// 2-64 in `[0, 1]` can be represented as a `f64`.) + #[inline] + pub fn new(p: f64) -> Bernoulli { + if p < 0.0 || p >= 1.0 { + if p == 1.0 { return Bernoulli { p_int: ALWAYS_TRUE } } + panic!("Bernoulli::new not called with 0.0 <= p <= 1.0"); + } + Bernoulli { p_int: (p * SCALE) as u64 } + } + + /// Construct a new `Bernoulli` with the probability of success of + /// `numerator`-in-`denominator`. I.e. `new_ratio(2, 3)` will return + /// a `Bernoulli` with a 2-in-3 chance, or about 67%, of returning `true`. + /// + /// If `numerator == denominator` then the returned `Bernoulli` will always + /// return `true`. If `numerator == 0` it will always return `false`. + /// + /// # Panics + /// + /// If `denominator == 0` or `numerator > denominator`. + /// + #[inline] + pub fn from_ratio(numerator: u32, denominator: u32) -> Bernoulli { + assert!(numerator <= denominator); + if numerator == denominator { + return Bernoulli { p_int: ::core::u64::MAX } + } + let p_int = ((numerator as f64 / denominator as f64) * SCALE) as u64; + Bernoulli { p_int } + } +} + +impl Distribution for Bernoulli { + #[inline] + fn sample(&self, rng: &mut R) -> bool { + // Make sure to always return true for p = 1.0. + if self.p_int == ALWAYS_TRUE { return true; } + let v: u64 = rng.gen(); + v < self.p_int + } +} + +#[cfg(test)] +mod test { + use Rng; + use distributions::Distribution; + use super::Bernoulli; + + #[test] + fn test_trivial() { + let mut r = ::test::rng(1); + let always_false = Bernoulli::new(0.0); + let always_true = Bernoulli::new(1.0); + for _ in 0..5 { + assert_eq!(r.sample::(&always_false), false); + assert_eq!(r.sample::(&always_true), true); + assert_eq!(Distribution::::sample(&always_false, &mut r), false); + assert_eq!(Distribution::::sample(&always_true, &mut r), true); + } + } + + #[test] + fn test_average() { + const P: f64 = 0.3; + const NUM: u32 = 3; + const DENOM: u32 = 10; + let d1 = Bernoulli::new(P); + let d2 = Bernoulli::from_ratio(NUM, DENOM); + const N: u32 = 100_000; + + let mut sum1: u32 = 0; + let mut sum2: u32 = 0; + let mut rng = ::test::rng(2); + for _ in 0..N { + if d1.sample(&mut rng) { + sum1 += 1; + } + if d2.sample(&mut rng) { + sum2 += 1; + } + } + let avg1 = (sum1 as f64) / (N as f64); + assert!((avg1 - P).abs() < 5e-3); + + let avg2 = (sum2 as f64) / (N as f64); + assert!((avg2 - (NUM as f64)/(DENOM as f64)).abs() < 5e-3); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/binomial.rs b/bash-5.1/vendor/rand/src/distributions/binomial.rs new file mode 100644 index 0000000..2df393e --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/binomial.rs @@ -0,0 +1,177 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2016-2017 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The binomial distribution. + +use Rng; +use distributions::{Distribution, Bernoulli, Cauchy}; +use distributions::utils::log_gamma; + +/// The binomial distribution `Binomial(n, p)`. +/// +/// This distribution has density function: +/// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Binomial, Distribution}; +/// +/// let bin = Binomial::new(20, 0.3); +/// let v = bin.sample(&mut rand::thread_rng()); +/// println!("{} is from a binomial distribution", v); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Binomial { + /// Number of trials. + n: u64, + /// Probability of success. + p: f64, +} + +impl Binomial { + /// Construct a new `Binomial` with the given shape parameters `n` (number + /// of trials) and `p` (probability of success). + /// + /// Panics if `p < 0` or `p > 1`. + pub fn new(n: u64, p: f64) -> Binomial { + assert!(p >= 0.0, "Binomial::new called with p < 0"); + assert!(p <= 1.0, "Binomial::new called with p > 1"); + Binomial { n, p } + } +} + +impl Distribution for Binomial { + fn sample(&self, rng: &mut R) -> u64 { + // Handle these values directly. + if self.p == 0.0 { + return 0; + } else if self.p == 1.0 { + return self.n; + } + + // For low n, it is faster to sample directly. For both methods, + // performance is independent of p. On Intel Haswell CPU this method + // appears to be faster for approx n < 300. + if self.n < 300 { + let mut result = 0; + let d = Bernoulli::new(self.p); + for _ in 0 .. self.n { + result += rng.sample(d) as u32; + } + return result as u64; + } + + // binomial distribution is symmetrical with respect to p -> 1-p, k -> n-k + // switch p so that it is less than 0.5 - this allows for lower expected values + // we will just invert the result at the end + let p = if self.p <= 0.5 { + self.p + } else { + 1.0 - self.p + }; + + // prepare some cached values + let float_n = self.n as f64; + let ln_fact_n = log_gamma(float_n + 1.0); + let pc = 1.0 - p; + let log_p = p.ln(); + let log_pc = pc.ln(); + let expected = self.n as f64 * p; + let sq = (expected * (2.0 * pc)).sqrt(); + + let mut lresult; + + // we use the Cauchy distribution as the comparison distribution + // f(x) ~ 1/(1+x^2) + let cauchy = Cauchy::new(0.0, 1.0); + loop { + let mut comp_dev: f64; + loop { + // draw from the Cauchy distribution + comp_dev = rng.sample(cauchy); + // shift the peak of the comparison ditribution + lresult = expected + sq * comp_dev; + // repeat the drawing until we are in the range of possible values + if lresult >= 0.0 && lresult < float_n + 1.0 { + break; + } + } + + // the result should be discrete + lresult = lresult.floor(); + + let log_binomial_dist = ln_fact_n - log_gamma(lresult+1.0) - + log_gamma(float_n - lresult + 1.0) + lresult*log_p + (float_n - lresult)*log_pc; + // this is the binomial probability divided by the comparison probability + // we will generate a uniform random value and if it is larger than this, + // we interpret it as a value falling out of the distribution and repeat + let comparison_coeff = (log_binomial_dist.exp() * sq) * (1.2 * (1.0 + comp_dev*comp_dev)); + + if comparison_coeff >= rng.gen() { + break; + } + } + + // invert the result for p < 0.5 + if p != self.p { + self.n - lresult as u64 + } else { + lresult as u64 + } + } +} + +#[cfg(test)] +mod test { + use Rng; + use distributions::Distribution; + use super::Binomial; + + fn test_binomial_mean_and_variance(n: u64, p: f64, rng: &mut R) { + let binomial = Binomial::new(n, p); + + let expected_mean = n as f64 * p; + let expected_variance = n as f64 * p * (1.0 - p); + + let mut results = [0.0; 1000]; + for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } + + let mean = results.iter().sum::() / results.len() as f64; + assert!((mean as f64 - expected_mean).abs() < expected_mean / 50.0); + + let variance = + results.iter().map(|x| (x - mean) * (x - mean)).sum::() + / results.len() as f64; + assert!((variance - expected_variance).abs() < expected_variance / 10.0); + } + + #[test] + fn test_binomial() { + let mut rng = ::test::rng(351); + test_binomial_mean_and_variance(150, 0.1, &mut rng); + test_binomial_mean_and_variance(70, 0.6, &mut rng); + test_binomial_mean_and_variance(40, 0.5, &mut rng); + test_binomial_mean_and_variance(20, 0.7, &mut rng); + test_binomial_mean_and_variance(20, 0.5, &mut rng); + } + + #[test] + fn test_binomial_end_points() { + let mut rng = ::test::rng(352); + assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); + assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); + } + + #[test] + #[should_panic] + fn test_binomial_invalid_lambda_neg() { + Binomial::new(20, -10.0); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/cauchy.rs b/bash-5.1/vendor/rand/src/distributions/cauchy.rs new file mode 100644 index 0000000..feef015 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/cauchy.rs @@ -0,0 +1,115 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2016-2017 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Cauchy distribution. + +use Rng; +use distributions::Distribution; +use std::f64::consts::PI; + +/// The Cauchy distribution `Cauchy(median, scale)`. +/// +/// This distribution has a density function: +/// `f(x) = 1 / (pi * scale * (1 + ((x - median) / scale)^2))` +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Cauchy, Distribution}; +/// +/// let cau = Cauchy::new(2.0, 5.0); +/// let v = cau.sample(&mut rand::thread_rng()); +/// println!("{} is from a Cauchy(2, 5) distribution", v); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Cauchy { + median: f64, + scale: f64 +} + +impl Cauchy { + /// Construct a new `Cauchy` with the given shape parameters + /// `median` the peak location and `scale` the scale factor. + /// Panics if `scale <= 0`. + pub fn new(median: f64, scale: f64) -> Cauchy { + assert!(scale > 0.0, "Cauchy::new called with scale factor <= 0"); + Cauchy { + median, + scale + } + } +} + +impl Distribution for Cauchy { + fn sample(&self, rng: &mut R) -> f64 { + // sample from [0, 1) + let x = rng.gen::(); + // get standard cauchy random number + // note that π/2 is not exactly representable, even if x=0.5 the result is finite + let comp_dev = (PI * x).tan(); + // shift and scale according to parameters + let result = self.median + self.scale * comp_dev; + result + } +} + +#[cfg(test)] +mod test { + use distributions::Distribution; + use super::Cauchy; + + fn median(mut numbers: &mut [f64]) -> f64 { + sort(&mut numbers); + let mid = numbers.len() / 2; + numbers[mid] + } + + fn sort(numbers: &mut [f64]) { + numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); + } + + #[test] + fn test_cauchy_median() { + let cauchy = Cauchy::new(10.0, 5.0); + let mut rng = ::test::rng(123); + let mut numbers: [f64; 1000] = [0.0; 1000]; + for i in 0..1000 { + numbers[i] = cauchy.sample(&mut rng); + } + let median = median(&mut numbers); + println!("Cauchy median: {}", median); + assert!((median - 10.0).abs() < 0.5); // not 100% certain, but probable enough + } + + #[test] + fn test_cauchy_mean() { + let cauchy = Cauchy::new(10.0, 5.0); + let mut rng = ::test::rng(123); + let mut sum = 0.0; + for _ in 0..1000 { + sum += cauchy.sample(&mut rng); + } + let mean = sum / 1000.0; + println!("Cauchy mean: {}", mean); + // for a Cauchy distribution the mean should not converge + assert!((mean - 10.0).abs() > 0.5); // not 100% certain, but probable enough + } + + #[test] + #[should_panic] + fn test_cauchy_invalid_scale_zero() { + Cauchy::new(0.0, 0.0); + } + + #[test] + #[should_panic] + fn test_cauchy_invalid_scale_neg() { + Cauchy::new(0.0, -10.0); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/dirichlet.rs b/bash-5.1/vendor/rand/src/distributions/dirichlet.rs new file mode 100644 index 0000000..19384b8 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/dirichlet.rs @@ -0,0 +1,137 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The dirichlet distribution. + +use Rng; +use distributions::Distribution; +use distributions::gamma::Gamma; + +/// The dirichelet distribution `Dirichlet(alpha)`. +/// +/// The Dirichlet distribution is a family of continuous multivariate +/// probability distributions parameterized by a vector alpha of positive reals. +/// It is a multivariate generalization of the beta distribution. +/// +/// # Example +/// +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::Dirichlet; +/// +/// let dirichlet = Dirichlet::new(vec![1.0, 2.0, 3.0]); +/// let samples = dirichlet.sample(&mut rand::thread_rng()); +/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples); +/// ``` + +#[derive(Clone, Debug)] +pub struct Dirichlet { + /// Concentration parameters (alpha) + alpha: Vec, +} + +impl Dirichlet { + /// Construct a new `Dirichlet` with the given alpha parameter `alpha`. + /// + /// # Panics + /// - if `alpha.len() < 2` + /// + #[inline] + pub fn new>>(alpha: V) -> Dirichlet { + let a = alpha.into(); + assert!(a.len() > 1); + for i in 0..a.len() { + assert!(a[i] > 0.0); + } + + Dirichlet { alpha: a } + } + + /// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`. + /// + /// # Panics + /// - if `alpha <= 0.0` + /// - if `size < 2` + /// + #[inline] + pub fn new_with_param(alpha: f64, size: usize) -> Dirichlet { + assert!(alpha > 0.0); + assert!(size > 1); + Dirichlet { + alpha: vec![alpha; size], + } + } +} + +impl Distribution> for Dirichlet { + fn sample(&self, rng: &mut R) -> Vec { + let n = self.alpha.len(); + let mut samples = vec![0.0f64; n]; + let mut sum = 0.0f64; + + for i in 0..n { + let g = Gamma::new(self.alpha[i], 1.0); + samples[i] = g.sample(rng); + sum += samples[i]; + } + let invacc = 1.0 / sum; + for i in 0..n { + samples[i] *= invacc; + } + samples + } +} + +#[cfg(test)] +mod test { + use super::Dirichlet; + use distributions::Distribution; + + #[test] + fn test_dirichlet() { + let d = Dirichlet::new(vec![1.0, 2.0, 3.0]); + let mut rng = ::test::rng(221); + let samples = d.sample(&mut rng); + let _: Vec = samples + .into_iter() + .map(|x| { + assert!(x > 0.0); + x + }) + .collect(); + } + + #[test] + fn test_dirichlet_with_param() { + let alpha = 0.5f64; + let size = 2; + let d = Dirichlet::new_with_param(alpha, size); + let mut rng = ::test::rng(221); + let samples = d.sample(&mut rng); + let _: Vec = samples + .into_iter() + .map(|x| { + assert!(x > 0.0); + x + }) + .collect(); + } + + #[test] + #[should_panic] + fn test_dirichlet_invalid_length() { + Dirichlet::new_with_param(0.5f64, 1); + } + + #[test] + #[should_panic] + fn test_dirichlet_invalid_alpha() { + Dirichlet::new_with_param(0.0f64, 2); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/exponential.rs b/bash-5.1/vendor/rand/src/distributions/exponential.rs new file mode 100644 index 0000000..76752a6 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/exponential.rs @@ -0,0 +1,124 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The exponential distribution. + +use {Rng}; +use distributions::{ziggurat_tables, Distribution}; +use distributions::utils::ziggurat; + +/// Samples floating-point numbers according to the exponential distribution, +/// with rate parameter `λ = 1`. This is equivalent to `Exp::new(1.0)` or +/// sampling with `-rng.gen::().ln()`, but faster. +/// +/// See `Exp` for the general exponential distribution. +/// +/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact +/// description in the paper was adjusted to use tables for the exponential +/// distribution rather than normal. +/// +/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to +/// Generate Normal Random Samples*]( +/// https://www.doornik.com/research/ziggurat.pdf). +/// Nuffield College, Oxford +/// +/// # Example +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::Exp1; +/// +/// let val: f64 = SmallRng::from_entropy().sample(Exp1); +/// println!("{}", val); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Exp1; + +// This could be done via `-rng.gen::().ln()` but that is slower. +impl Distribution for Exp1 { + #[inline] + fn sample(&self, rng: &mut R) -> f64 { + #[inline] + fn pdf(x: f64) -> f64 { + (-x).exp() + } + #[inline] + fn zero_case(rng: &mut R, _u: f64) -> f64 { + ziggurat_tables::ZIG_EXP_R - rng.gen::().ln() + } + + ziggurat(rng, false, + &ziggurat_tables::ZIG_EXP_X, + &ziggurat_tables::ZIG_EXP_F, + pdf, zero_case) + } +} + +/// The exponential distribution `Exp(lambda)`. +/// +/// This distribution has density function: `f(x) = lambda * exp(-lambda * x)` +/// for `x > 0`. +/// +/// Note that [`Exp1`][crate::distributions::Exp1] is an optimised implementation for `lambda = 1`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Exp, Distribution}; +/// +/// let exp = Exp::new(2.0); +/// let v = exp.sample(&mut rand::thread_rng()); +/// println!("{} is from a Exp(2) distribution", v); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Exp { + /// `lambda` stored as `1/lambda`, since this is what we scale by. + lambda_inverse: f64 +} + +impl Exp { + /// Construct a new `Exp` with the given shape parameter + /// `lambda`. Panics if `lambda <= 0`. + #[inline] + pub fn new(lambda: f64) -> Exp { + assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0"); + Exp { lambda_inverse: 1.0 / lambda } + } +} + +impl Distribution for Exp { + fn sample(&self, rng: &mut R) -> f64 { + let n: f64 = rng.sample(Exp1); + n * self.lambda_inverse + } +} + +#[cfg(test)] +mod test { + use distributions::Distribution; + use super::Exp; + + #[test] + fn test_exp() { + let exp = Exp::new(10.0); + let mut rng = ::test::rng(221); + for _ in 0..1000 { + assert!(exp.sample(&mut rng) >= 0.0); + } + } + #[test] + #[should_panic] + fn test_exp_invalid_lambda_zero() { + Exp::new(0.0); + } + #[test] + #[should_panic] + fn test_exp_invalid_lambda_neg() { + Exp::new(-10.0); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/float.rs b/bash-5.1/vendor/rand/src/distributions/float.rs new file mode 100644 index 0000000..0dd5caa --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/float.rs @@ -0,0 +1,259 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Basic floating-point number distributions + +use core::mem; +use Rng; +use distributions::{Distribution, Standard}; +use distributions::utils::FloatSIMDUtils; +#[cfg(feature="simd_support")] +use packed_simd::*; + +/// A distribution to sample floating point numbers uniformly in the half-open +/// interval `(0, 1]`, i.e. including 1 but not 0. +/// +/// All values that can be generated are of the form `n * ε/2`. For `f32` +/// the 23 most significant random bits of a `u32` are used and for `f64` the +/// 53 most significant bits of a `u64` are used. The conversion uses the +/// multiplicative method. +/// +/// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`] +/// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary +/// ranges. +/// +/// # Example +/// ``` +/// use rand::{thread_rng, Rng}; +/// use rand::distributions::OpenClosed01; +/// +/// let val: f32 = thread_rng().sample(OpenClosed01); +/// println!("f32 from (0, 1): {}", val); +/// ``` +/// +/// [`Standard`]: crate::distributions::Standard +/// [`Open01`]: crate::distributions::Open01 +/// [`Uniform`]: crate::distributions::uniform::Uniform +#[derive(Clone, Copy, Debug)] +pub struct OpenClosed01; + +/// A distribution to sample floating point numbers uniformly in the open +/// interval `(0, 1)`, i.e. not including either endpoint. +/// +/// All values that can be generated are of the form `n * ε + ε/2`. For `f32` +/// the 22 most significant random bits of an `u32` are used, for `f64` 52 from +/// an `u64`. The conversion uses a transmute-based method. +/// +/// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`] +/// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary +/// ranges. +/// +/// # Example +/// ``` +/// use rand::{thread_rng, Rng}; +/// use rand::distributions::Open01; +/// +/// let val: f32 = thread_rng().sample(Open01); +/// println!("f32 from (0, 1): {}", val); +/// ``` +/// +/// [`Standard`]: crate::distributions::Standard +/// [`OpenClosed01`]: crate::distributions::OpenClosed01 +/// [`Uniform`]: crate::distributions::uniform::Uniform +#[derive(Clone, Copy, Debug)] +pub struct Open01; + + +pub(crate) trait IntoFloat { + type F; + + /// Helper method to combine the fraction and a contant exponent into a + /// float. + /// + /// Only the least significant bits of `self` may be set, 23 for `f32` and + /// 52 for `f64`. + /// The resulting value will fall in a range that depends on the exponent. + /// As an example the range with exponent 0 will be + /// [20..21), which is [1..2). + fn into_float_with_exponent(self, exponent: i32) -> Self::F; +} + +macro_rules! float_impls { + ($ty:ident, $uty:ident, $f_scalar:ident, $u_scalar:ty, + $fraction_bits:expr, $exponent_bias:expr) => { + impl IntoFloat for $uty { + type F = $ty; + #[inline(always)] + fn into_float_with_exponent(self, exponent: i32) -> $ty { + // The exponent is encoded using an offset-binary representation + let exponent_bits: $u_scalar = + (($exponent_bias + exponent) as $u_scalar) << $fraction_bits; + // TODO: use from_bits when min compiler > 1.25 (see #545) + // $ty::from_bits(self | exponent_bits) + unsafe{ mem::transmute(self | exponent_bits) } + } + } + + impl Distribution<$ty> for Standard { + fn sample(&self, rng: &mut R) -> $ty { + // Multiply-based method; 24/53 random bits; [0, 1) interval. + // We use the most significant bits because for simple RNGs + // those are usually more random. + let float_size = mem::size_of::<$f_scalar>() as u32 * 8; + let precision = $fraction_bits + 1; + let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar); + + let value: $uty = rng.gen(); + let value = value >> (float_size - precision); + scale * $ty::cast_from_int(value) + } + } + + impl Distribution<$ty> for OpenClosed01 { + fn sample(&self, rng: &mut R) -> $ty { + // Multiply-based method; 24/53 random bits; (0, 1] interval. + // We use the most significant bits because for simple RNGs + // those are usually more random. + let float_size = mem::size_of::<$f_scalar>() as u32 * 8; + let precision = $fraction_bits + 1; + let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar); + + let value: $uty = rng.gen(); + let value = value >> (float_size - precision); + // Add 1 to shift up; will not overflow because of right-shift: + scale * $ty::cast_from_int(value + 1) + } + } + + impl Distribution<$ty> for Open01 { + fn sample(&self, rng: &mut R) -> $ty { + // Transmute-based method; 23/52 random bits; (0, 1) interval. + // We use the most significant bits because for simple RNGs + // those are usually more random. + use core::$f_scalar::EPSILON; + let float_size = mem::size_of::<$f_scalar>() as u32 * 8; + + let value: $uty = rng.gen(); + let fraction = value >> (float_size - $fraction_bits); + fraction.into_float_with_exponent(0) - (1.0 - EPSILON / 2.0) + } + } + } +} + +float_impls! { f32, u32, f32, u32, 23, 127 } +float_impls! { f64, u64, f64, u64, 52, 1023 } + +#[cfg(feature="simd_support")] +float_impls! { f32x2, u32x2, f32, u32, 23, 127 } +#[cfg(feature="simd_support")] +float_impls! { f32x4, u32x4, f32, u32, 23, 127 } +#[cfg(feature="simd_support")] +float_impls! { f32x8, u32x8, f32, u32, 23, 127 } +#[cfg(feature="simd_support")] +float_impls! { f32x16, u32x16, f32, u32, 23, 127 } + +#[cfg(feature="simd_support")] +float_impls! { f64x2, u64x2, f64, u64, 52, 1023 } +#[cfg(feature="simd_support")] +float_impls! { f64x4, u64x4, f64, u64, 52, 1023 } +#[cfg(feature="simd_support")] +float_impls! { f64x8, u64x8, f64, u64, 52, 1023 } + + +#[cfg(test)] +mod tests { + use Rng; + use distributions::{Open01, OpenClosed01}; + use rngs::mock::StepRng; + #[cfg(feature="simd_support")] + use packed_simd::*; + + const EPSILON32: f32 = ::core::f32::EPSILON; + const EPSILON64: f64 = ::core::f64::EPSILON; + + macro_rules! test_f32 { + ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => { + #[test] + fn $fnn() { + // Standard + let mut zeros = StepRng::new(0, 0); + assert_eq!(zeros.gen::<$ty>(), $ZERO); + let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); + assert_eq!(one.gen::<$ty>(), $EPSILON / 2.0); + let mut max = StepRng::new(!0, 0); + assert_eq!(max.gen::<$ty>(), 1.0 - $EPSILON / 2.0); + + // OpenClosed01 + let mut zeros = StepRng::new(0, 0); + assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), + 0.0 + $EPSILON / 2.0); + let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); + assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON); + let mut max = StepRng::new(!0, 0); + assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + 1.0); + + // Open01 + let mut zeros = StepRng::new(0, 0); + assert_eq!(zeros.sample::<$ty, _>(Open01), 0.0 + $EPSILON / 2.0); + let mut one = StepRng::new(1 << 9 | 1 << (9 + 32), 0); + assert_eq!(one.sample::<$ty, _>(Open01), $EPSILON / 2.0 * 3.0); + let mut max = StepRng::new(!0, 0); + assert_eq!(max.sample::<$ty, _>(Open01), 1.0 - $EPSILON / 2.0); + } + } + } + test_f32! { f32_edge_cases, f32, 0.0, EPSILON32 } + #[cfg(feature="simd_support")] + test_f32! { f32x2_edge_cases, f32x2, f32x2::splat(0.0), f32x2::splat(EPSILON32) } + #[cfg(feature="simd_support")] + test_f32! { f32x4_edge_cases, f32x4, f32x4::splat(0.0), f32x4::splat(EPSILON32) } + #[cfg(feature="simd_support")] + test_f32! { f32x8_edge_cases, f32x8, f32x8::splat(0.0), f32x8::splat(EPSILON32) } + #[cfg(feature="simd_support")] + test_f32! { f32x16_edge_cases, f32x16, f32x16::splat(0.0), f32x16::splat(EPSILON32) } + + macro_rules! test_f64 { + ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => { + #[test] + fn $fnn() { + // Standard + let mut zeros = StepRng::new(0, 0); + assert_eq!(zeros.gen::<$ty>(), $ZERO); + let mut one = StepRng::new(1 << 11, 0); + assert_eq!(one.gen::<$ty>(), $EPSILON / 2.0); + let mut max = StepRng::new(!0, 0); + assert_eq!(max.gen::<$ty>(), 1.0 - $EPSILON / 2.0); + + // OpenClosed01 + let mut zeros = StepRng::new(0, 0); + assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), + 0.0 + $EPSILON / 2.0); + let mut one = StepRng::new(1 << 11, 0); + assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON); + let mut max = StepRng::new(!0, 0); + assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + 1.0); + + // Open01 + let mut zeros = StepRng::new(0, 0); + assert_eq!(zeros.sample::<$ty, _>(Open01), 0.0 + $EPSILON / 2.0); + let mut one = StepRng::new(1 << 12, 0); + assert_eq!(one.sample::<$ty, _>(Open01), $EPSILON / 2.0 * 3.0); + let mut max = StepRng::new(!0, 0); + assert_eq!(max.sample::<$ty, _>(Open01), 1.0 - $EPSILON / 2.0); + } + } + } + test_f64! { f64_edge_cases, f64, 0.0, EPSILON64 } + #[cfg(feature="simd_support")] + test_f64! { f64x2_edge_cases, f64x2, f64x2::splat(0.0), f64x2::splat(EPSILON64) } + #[cfg(feature="simd_support")] + test_f64! { f64x4_edge_cases, f64x4, f64x4::splat(0.0), f64x4::splat(EPSILON64) } + #[cfg(feature="simd_support")] + test_f64! { f64x8_edge_cases, f64x8, f64x8::splat(0.0), f64x8::splat(EPSILON64) } +} diff --git a/bash-5.1/vendor/rand/src/distributions/gamma.rs b/bash-5.1/vendor/rand/src/distributions/gamma.rs new file mode 100644 index 0000000..43ac2bc --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/gamma.rs @@ -0,0 +1,413 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Gamma and derived distributions. + +use self::GammaRepr::*; +use self::ChiSquaredRepr::*; + +use Rng; +use distributions::normal::StandardNormal; +use distributions::{Distribution, Exp, Open01}; + +/// The Gamma distribution `Gamma(shape, scale)` distribution. +/// +/// The density function of this distribution is +/// +/// ```text +/// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) +/// ``` +/// +/// where `Γ` is the Gamma function, `k` is the shape and `θ` is the +/// scale and both `k` and `θ` are strictly positive. +/// +/// The algorithm used is that described by Marsaglia & Tsang 2000[^1], +/// falling back to directly sampling from an Exponential for `shape +/// == 1`, and using the boosting technique described in that paper for +/// `shape < 1`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Distribution, Gamma}; +/// +/// let gamma = Gamma::new(2.0, 5.0); +/// let v = gamma.sample(&mut rand::thread_rng()); +/// println!("{} is from a Gamma(2, 5) distribution", v); +/// ``` +/// +/// [^1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method for +/// Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 +/// (September 2000), 363-372. +/// DOI:[10.1145/358407.358414](https://doi.acm.org/10.1145/358407.358414) +#[derive(Clone, Copy, Debug)] +pub struct Gamma { + repr: GammaRepr, +} + +#[derive(Clone, Copy, Debug)] +enum GammaRepr { + Large(GammaLargeShape), + One(Exp), + Small(GammaSmallShape) +} + +// These two helpers could be made public, but saving the +// match-on-Gamma-enum branch from using them directly (e.g. if one +// knows that the shape is always > 1) doesn't appear to be much +// faster. + +/// Gamma distribution where the shape parameter is less than 1. +/// +/// Note, samples from this require a compulsory floating-point `pow` +/// call, which makes it significantly slower than sampling from a +/// gamma distribution where the shape parameter is greater than or +/// equal to 1. +/// +/// See `Gamma` for sampling from a Gamma distribution with general +/// shape parameters. +#[derive(Clone, Copy, Debug)] +struct GammaSmallShape { + inv_shape: f64, + large_shape: GammaLargeShape +} + +/// Gamma distribution where the shape parameter is larger than 1. +/// +/// See `Gamma` for sampling from a Gamma distribution with general +/// shape parameters. +#[derive(Clone, Copy, Debug)] +struct GammaLargeShape { + scale: f64, + c: f64, + d: f64 +} + +impl Gamma { + /// Construct an object representing the `Gamma(shape, scale)` + /// distribution. + /// + /// Panics if `shape <= 0` or `scale <= 0`. + #[inline] + pub fn new(shape: f64, scale: f64) -> Gamma { + assert!(shape > 0.0, "Gamma::new called with shape <= 0"); + assert!(scale > 0.0, "Gamma::new called with scale <= 0"); + + let repr = if shape == 1.0 { + One(Exp::new(1.0 / scale)) + } else if shape < 1.0 { + Small(GammaSmallShape::new_raw(shape, scale)) + } else { + Large(GammaLargeShape::new_raw(shape, scale)) + }; + Gamma { repr } + } +} + +impl GammaSmallShape { + fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { + GammaSmallShape { + inv_shape: 1. / shape, + large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) + } + } +} + +impl GammaLargeShape { + fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { + let d = shape - 1. / 3.; + GammaLargeShape { + scale, + c: 1. / (9. * d).sqrt(), + d + } + } +} + +impl Distribution for Gamma { + fn sample(&self, rng: &mut R) -> f64 { + match self.repr { + Small(ref g) => g.sample(rng), + One(ref g) => g.sample(rng), + Large(ref g) => g.sample(rng), + } + } +} +impl Distribution for GammaSmallShape { + fn sample(&self, rng: &mut R) -> f64 { + let u: f64 = rng.sample(Open01); + + self.large_shape.sample(rng) * u.powf(self.inv_shape) + } +} +impl Distribution for GammaLargeShape { + fn sample(&self, rng: &mut R) -> f64 { + loop { + let x = rng.sample(StandardNormal); + let v_cbrt = 1.0 + self.c * x; + if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 + continue + } + + let v = v_cbrt * v_cbrt * v_cbrt; + let u: f64 = rng.sample(Open01); + + let x_sqr = x * x; + if u < 1.0 - 0.0331 * x_sqr * x_sqr || + u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { + return self.d * v * self.scale + } + } + } +} + +/// The chi-squared distribution `χ²(k)`, where `k` is the degrees of +/// freedom. +/// +/// For `k > 0` integral, this distribution is the sum of the squares +/// of `k` independent standard normal random variables. For other +/// `k`, this uses the equivalent characterisation +/// `χ²(k) = Gamma(k/2, 2)`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{ChiSquared, Distribution}; +/// +/// let chi = ChiSquared::new(11.0); +/// let v = chi.sample(&mut rand::thread_rng()); +/// println!("{} is from a χ²(11) distribution", v) +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct ChiSquared { + repr: ChiSquaredRepr, +} + +#[derive(Clone, Copy, Debug)] +enum ChiSquaredRepr { + // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, + // e.g. when alpha = 1/2 as it would be for this case, so special- + // casing and using the definition of N(0,1)^2 is faster. + DoFExactlyOne, + DoFAnythingElse(Gamma), +} + +impl ChiSquared { + /// Create a new chi-squared distribution with degrees-of-freedom + /// `k`. Panics if `k < 0`. + pub fn new(k: f64) -> ChiSquared { + let repr = if k == 1.0 { + DoFExactlyOne + } else { + assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); + DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) + }; + ChiSquared { repr } + } +} +impl Distribution for ChiSquared { + fn sample(&self, rng: &mut R) -> f64 { + match self.repr { + DoFExactlyOne => { + // k == 1 => N(0,1)^2 + let norm = rng.sample(StandardNormal); + norm * norm + } + DoFAnythingElse(ref g) => g.sample(rng) + } + } +} + +/// The Fisher F distribution `F(m, n)`. +/// +/// This distribution is equivalent to the ratio of two normalised +/// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / +/// (χ²(n)/n)`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{FisherF, Distribution}; +/// +/// let f = FisherF::new(2.0, 32.0); +/// let v = f.sample(&mut rand::thread_rng()); +/// println!("{} is from an F(2, 32) distribution", v) +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct FisherF { + numer: ChiSquared, + denom: ChiSquared, + // denom_dof / numer_dof so that this can just be a straight + // multiplication, rather than a division. + dof_ratio: f64, +} + +impl FisherF { + /// Create a new `FisherF` distribution, with the given + /// parameter. Panics if either `m` or `n` are not positive. + pub fn new(m: f64, n: f64) -> FisherF { + assert!(m > 0.0, "FisherF::new called with `m < 0`"); + assert!(n > 0.0, "FisherF::new called with `n < 0`"); + + FisherF { + numer: ChiSquared::new(m), + denom: ChiSquared::new(n), + dof_ratio: n / m + } + } +} +impl Distribution for FisherF { + fn sample(&self, rng: &mut R) -> f64 { + self.numer.sample(rng) / self.denom.sample(rng) * self.dof_ratio + } +} + +/// The Student t distribution, `t(nu)`, where `nu` is the degrees of +/// freedom. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{StudentT, Distribution}; +/// +/// let t = StudentT::new(11.0); +/// let v = t.sample(&mut rand::thread_rng()); +/// println!("{} is from a t(11) distribution", v) +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct StudentT { + chi: ChiSquared, + dof: f64 +} + +impl StudentT { + /// Create a new Student t distribution with `n` degrees of + /// freedom. Panics if `n <= 0`. + pub fn new(n: f64) -> StudentT { + assert!(n > 0.0, "StudentT::new called with `n <= 0`"); + StudentT { + chi: ChiSquared::new(n), + dof: n + } + } +} +impl Distribution for StudentT { + fn sample(&self, rng: &mut R) -> f64 { + let norm = rng.sample(StandardNormal); + norm * (self.dof / self.chi.sample(rng)).sqrt() + } +} + +/// The Beta distribution with shape parameters `alpha` and `beta`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Distribution, Beta}; +/// +/// let beta = Beta::new(2.0, 5.0); +/// let v = beta.sample(&mut rand::thread_rng()); +/// println!("{} is from a Beta(2, 5) distribution", v); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Beta { + gamma_a: Gamma, + gamma_b: Gamma, +} + +impl Beta { + /// Construct an object representing the `Beta(alpha, beta)` + /// distribution. + /// + /// Panics if `shape <= 0` or `scale <= 0`. + pub fn new(alpha: f64, beta: f64) -> Beta { + assert!((alpha > 0.) & (beta > 0.)); + Beta { + gamma_a: Gamma::new(alpha, 1.), + gamma_b: Gamma::new(beta, 1.), + } + } +} + +impl Distribution for Beta { + fn sample(&self, rng: &mut R) -> f64 { + let x = self.gamma_a.sample(rng); + let y = self.gamma_b.sample(rng); + x / (x + y) + } +} + +#[cfg(test)] +mod test { + use distributions::Distribution; + use super::{Beta, ChiSquared, StudentT, FisherF}; + + #[test] + fn test_chi_squared_one() { + let chi = ChiSquared::new(1.0); + let mut rng = ::test::rng(201); + for _ in 0..1000 { + chi.sample(&mut rng); + } + } + #[test] + fn test_chi_squared_small() { + let chi = ChiSquared::new(0.5); + let mut rng = ::test::rng(202); + for _ in 0..1000 { + chi.sample(&mut rng); + } + } + #[test] + fn test_chi_squared_large() { + let chi = ChiSquared::new(30.0); + let mut rng = ::test::rng(203); + for _ in 0..1000 { + chi.sample(&mut rng); + } + } + #[test] + #[should_panic] + fn test_chi_squared_invalid_dof() { + ChiSquared::new(-1.0); + } + + #[test] + fn test_f() { + let f = FisherF::new(2.0, 32.0); + let mut rng = ::test::rng(204); + for _ in 0..1000 { + f.sample(&mut rng); + } + } + + #[test] + fn test_t() { + let t = StudentT::new(11.0); + let mut rng = ::test::rng(205); + for _ in 0..1000 { + t.sample(&mut rng); + } + } + + #[test] + fn test_beta() { + let beta = Beta::new(1.0, 2.0); + let mut rng = ::test::rng(201); + for _ in 0..1000 { + beta.sample(&mut rng); + } + } + + #[test] + #[should_panic] + fn test_beta_invalid_dof() { + Beta::new(0., 0.); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/integer.rs b/bash-5.1/vendor/rand/src/distributions/integer.rs new file mode 100644 index 0000000..7e408db --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/integer.rs @@ -0,0 +1,161 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The implementations of the `Standard` distribution for integer types. + +use {Rng}; +use distributions::{Distribution, Standard}; +#[cfg(feature="simd_support")] +use packed_simd::*; +#[cfg(all(target_arch = "x86", feature="nightly"))] +use core::arch::x86::*; +#[cfg(all(target_arch = "x86_64", feature="nightly"))] +use core::arch::x86_64::*; + +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> u8 { + rng.next_u32() as u8 + } +} + +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> u16 { + rng.next_u32() as u16 + } +} + +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> u32 { + rng.next_u32() + } +} + +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> u64 { + rng.next_u64() + } +} + +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> u128 { + // Use LE; we explicitly generate one value before the next. + let x = rng.next_u64() as u128; + let y = rng.next_u64() as u128; + (y << 64) | x + } +} + +impl Distribution for Standard { + #[inline] + #[cfg(any(target_pointer_width = "32", target_pointer_width = "16"))] + fn sample(&self, rng: &mut R) -> usize { + rng.next_u32() as usize + } + + #[inline] + #[cfg(target_pointer_width = "64")] + fn sample(&self, rng: &mut R) -> usize { + rng.next_u64() as usize + } +} + +macro_rules! impl_int_from_uint { + ($ty:ty, $uty:ty) => { + impl Distribution<$ty> for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> $ty { + rng.gen::<$uty>() as $ty + } + } + } +} + +impl_int_from_uint! { i8, u8 } +impl_int_from_uint! { i16, u16 } +impl_int_from_uint! { i32, u32 } +impl_int_from_uint! { i64, u64 } +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] impl_int_from_uint! { i128, u128 } +impl_int_from_uint! { isize, usize } + +#[cfg(feature="simd_support")] +macro_rules! simd_impl { + ($(($intrinsic:ident, $vec:ty),)+) => {$( + impl Distribution<$intrinsic> for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> $intrinsic { + $intrinsic::from_bits(rng.gen::<$vec>()) + } + } + )+}; + + ($bits:expr,) => {}; + ($bits:expr, $ty:ty, $($ty_more:ty,)*) => { + simd_impl!($bits, $($ty_more,)*); + + impl Distribution<$ty> for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> $ty { + let mut vec: $ty = Default::default(); + unsafe { + let ptr = &mut vec; + let b_ptr = &mut *(ptr as *mut $ty as *mut [u8; $bits/8]); + rng.fill_bytes(b_ptr); + } + vec.to_le() + } + } + }; +} + +#[cfg(feature="simd_support")] +simd_impl!(16, u8x2, i8x2,); +#[cfg(feature="simd_support")] +simd_impl!(32, u8x4, i8x4, u16x2, i16x2,); +#[cfg(feature="simd_support")] +simd_impl!(64, u8x8, i8x8, u16x4, i16x4, u32x2, i32x2,); +#[cfg(feature="simd_support")] +simd_impl!(128, u8x16, i8x16, u16x8, i16x8, u32x4, i32x4, u64x2, i64x2,); +#[cfg(feature="simd_support")] +simd_impl!(256, u8x32, i8x32, u16x16, i16x16, u32x8, i32x8, u64x4, i64x4,); +#[cfg(feature="simd_support")] +simd_impl!(512, u8x64, i8x64, u16x32, i16x32, u32x16, i32x16, u64x8, i64x8,); +#[cfg(all(feature="simd_support", feature="nightly", any(target_arch="x86", target_arch="x86_64")))] +simd_impl!((__m64, u8x8), (__m128i, u8x16), (__m256i, u8x32),); + +#[cfg(test)] +mod tests { + use Rng; + use distributions::{Standard}; + + #[test] + fn test_integers() { + let mut rng = ::test::rng(806); + + rng.sample::(Standard); + rng.sample::(Standard); + rng.sample::(Standard); + rng.sample::(Standard); + rng.sample::(Standard); + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + rng.sample::(Standard); + + rng.sample::(Standard); + rng.sample::(Standard); + rng.sample::(Standard); + rng.sample::(Standard); + rng.sample::(Standard); + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + rng.sample::(Standard); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/mod.rs b/bash-5.1/vendor/rand/src/distributions/mod.rs new file mode 100644 index 0000000..6e2d6c7 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/mod.rs @@ -0,0 +1,608 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2017 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Generating random samples from probability distributions. +//! +//! This module is the home of the [`Distribution`] trait and several of its +//! implementations. It is the workhorse behind some of the convenient +//! functionality of the [`Rng`] trait, including [`gen`], [`gen_range`] and +//! of course [`sample`]. +//! +//! Abstractly, a [probability distribution] describes the probability of +//! occurance of each value in its sample space. +//! +//! More concretely, an implementation of `Distribution` for type `X` is an +//! algorithm for choosing values from the sample space (a subset of `T`) +//! according to the distribution `X` represents, using an external source of +//! randomness (an RNG supplied to the `sample` function). +//! +//! A type `X` may implement `Distribution` for multiple types `T`. +//! Any type implementing [`Distribution`] is stateless (i.e. immutable), +//! but it may have internal parameters set at construction time (for example, +//! [`Uniform`] allows specification of its sample space as a range within `T`). +//! +//! +//! # The `Standard` distribution +//! +//! The [`Standard`] distribution is important to mention. This is the +//! distribution used by [`Rng::gen()`] and represents the "default" way to +//! produce a random value for many different types, including most primitive +//! types, tuples, arrays, and a few derived types. See the documentation of +//! [`Standard`] for more details. +//! +//! Implementing `Distribution` for [`Standard`] for user types `T` makes it +//! possible to generate type `T` with [`Rng::gen()`], and by extension also +//! with the [`random()`] function. +//! +//! +//! # Distribution to sample from a `Uniform` range +//! +//! The [`Uniform`] distribution is more flexible than [`Standard`], but also +//! more specialised: it supports fewer target types, but allows the sample +//! space to be specified as an arbitrary range within its target type `T`. +//! Both [`Standard`] and [`Uniform`] are in some sense uniform distributions. +//! +//! Values may be sampled from this distribution using [`Rng::gen_range`] or +//! by creating a distribution object with [`Uniform::new`], +//! [`Uniform::new_inclusive`] or `From`. When the range limits are not +//! known at compile time it is typically faster to reuse an existing +//! distribution object than to call [`Rng::gen_range`]. +//! +//! User types `T` may also implement `Distribution` for [`Uniform`], +//! although this is less straightforward than for [`Standard`] (see the +//! documentation in the [`uniform`] module. Doing so enables generation of +//! values of type `T` with [`Rng::gen_range`]. +//! +//! +//! # Other distributions +//! +//! There are surprisingly many ways to uniformly generate random floats. A +//! range between 0 and 1 is standard, but the exact bounds (open vs closed) +//! and accuracy differ. In addition to the [`Standard`] distribution Rand offers +//! [`Open01`] and [`OpenClosed01`]. See "Floating point implementation" section of +//! [`Standard`] documentation for more details. +//! +//! [`Alphanumeric`] is a simple distribution to sample random letters and +//! numbers of the `char` type; in contrast [`Standard`] may sample any valid +//! `char`. +//! +//! [`WeightedIndex`] can be used to do weighted sampling from a set of items, +//! such as from an array. +//! +//! # Non-uniform probability distributions +//! +//! Rand currently provides the following probability distributions: +//! +//! - Related to real-valued quantities that grow linearly +//! (e.g. errors, offsets): +//! - [`Normal`] distribution, and [`StandardNormal`] as a primitive +//! - [`Cauchy`] distribution +//! - Related to Bernoulli trials (yes/no events, with a given probability): +//! - [`Binomial`] distribution +//! - [`Bernoulli`] distribution, similar to [`Rng::gen_bool`]. +//! - Related to positive real-valued quantities that grow exponentially +//! (e.g. prices, incomes, populations): +//! - [`LogNormal`] distribution +//! - Related to the occurrence of independent events at a given rate: +//! - [`Pareto`] distribution +//! - [`Poisson`] distribution +//! - [`Exp`]onential distribution, and [`Exp1`] as a primitive +//! - [`Weibull`] distribution +//! - Gamma and derived distributions: +//! - [`Gamma`] distribution +//! - [`ChiSquared`] distribution +//! - [`StudentT`] distribution +//! - [`FisherF`] distribution +//! - Triangular distribution: +//! - [`Beta`] distribution +//! - [`Triangular`] distribution +//! - Multivariate probability distributions +//! - [`Dirichlet`] distribution +//! - [`UnitSphereSurface`] distribution +//! - [`UnitCircle`] distribution +//! +//! # Examples +//! +//! Sampling from a distribution: +//! +//! ``` +//! use rand::{thread_rng, Rng}; +//! use rand::distributions::Exp; +//! +//! let exp = Exp::new(2.0); +//! let v = thread_rng().sample(exp); +//! println!("{} is from an Exp(2) distribution", v); +//! ``` +//! +//! Implementing the [`Standard`] distribution for a user type: +//! +//! ``` +//! # #![allow(dead_code)] +//! use rand::Rng; +//! use rand::distributions::{Distribution, Standard}; +//! +//! struct MyF32 { +//! x: f32, +//! } +//! +//! impl Distribution for Standard { +//! fn sample(&self, rng: &mut R) -> MyF32 { +//! MyF32 { x: rng.gen() } +//! } +//! } +//! ``` +//! +//! +//! [probability distribution]: https://en.wikipedia.org/wiki/Probability_distribution +//! [`gen_range`]: Rng::gen_range +//! [`gen`]: Rng::gen +//! [`sample`]: Rng::sample +//! [`new_inclusive`]: Uniform::new_inclusive +//! [`Alphanumeric`]: distributions::Alphanumeric +//! [`Bernoulli`]: distributions::Bernoulli +//! [`Beta`]: distributions::Beta +//! [`Binomial`]: distributions::Binomial +//! [`Cauchy`]: distributions::Cauchy +//! [`ChiSquared`]: distributions::ChiSquared +//! [`Dirichlet`]: distributions::Dirichlet +//! [`Exp`]: distributions::Exp +//! [`Exp1`]: distributions::Exp1 +//! [`FisherF`]: distributions::FisherF +//! [`Gamma`]: distributions::Gamma +//! [`LogNormal`]: distributions::LogNormal +//! [`Normal`]: distributions::Normal +//! [`Open01`]: distributions::Open01 +//! [`OpenClosed01`]: distributions::OpenClosed01 +//! [`Pareto`]: distributions::Pareto +//! [`Poisson`]: distributions::Poisson +//! [`Standard`]: distributions::Standard +//! [`StandardNormal`]: distributions::StandardNormal +//! [`StudentT`]: distributions::StudentT +//! [`Triangular`]: distributions::Triangular +//! [`Uniform`]: distributions::Uniform +//! [`Uniform::new`]: distributions::Uniform::new +//! [`Uniform::new_inclusive`]: distributions::Uniform::new_inclusive +//! [`UnitSphereSurface`]: distributions::UnitSphereSurface +//! [`UnitCircle`]: distributions::UnitCircle +//! [`Weibull`]: distributions::Weibull +//! [`WeightedIndex`]: distributions::WeightedIndex + +#[cfg(any(rustc_1_26, features="nightly"))] +use core::iter; +use Rng; + +pub use self::other::Alphanumeric; +#[doc(inline)] pub use self::uniform::Uniform; +pub use self::float::{OpenClosed01, Open01}; +pub use self::bernoulli::Bernoulli; +#[cfg(feature="alloc")] pub use self::weighted::{WeightedIndex, WeightedError}; +#[cfg(feature="std")] pub use self::unit_sphere::UnitSphereSurface; +#[cfg(feature="std")] pub use self::unit_circle::UnitCircle; +#[cfg(feature="std")] pub use self::gamma::{Gamma, ChiSquared, FisherF, + StudentT, Beta}; +#[cfg(feature="std")] pub use self::normal::{Normal, LogNormal, StandardNormal}; +#[cfg(feature="std")] pub use self::exponential::{Exp, Exp1}; +#[cfg(feature="std")] pub use self::pareto::Pareto; +#[cfg(feature="std")] pub use self::poisson::Poisson; +#[cfg(feature="std")] pub use self::binomial::Binomial; +#[cfg(feature="std")] pub use self::cauchy::Cauchy; +#[cfg(feature="std")] pub use self::dirichlet::Dirichlet; +#[cfg(feature="std")] pub use self::triangular::Triangular; +#[cfg(feature="std")] pub use self::weibull::Weibull; + +pub mod uniform; +mod bernoulli; +#[cfg(feature="alloc")] mod weighted; +#[cfg(feature="std")] mod unit_sphere; +#[cfg(feature="std")] mod unit_circle; +#[cfg(feature="std")] mod gamma; +#[cfg(feature="std")] mod normal; +#[cfg(feature="std")] mod exponential; +#[cfg(feature="std")] mod pareto; +#[cfg(feature="std")] mod poisson; +#[cfg(feature="std")] mod binomial; +#[cfg(feature="std")] mod cauchy; +#[cfg(feature="std")] mod dirichlet; +#[cfg(feature="std")] mod triangular; +#[cfg(feature="std")] mod weibull; + +mod float; +mod integer; +mod other; +mod utils; +#[cfg(feature="std")] mod ziggurat_tables; + +/// Types (distributions) that can be used to create a random instance of `T`. +/// +/// It is possible to sample from a distribution through both the +/// `Distribution` and [`Rng`] traits, via `distr.sample(&mut rng)` and +/// `rng.sample(distr)`. They also both offer the [`sample_iter`] method, which +/// produces an iterator that samples from the distribution. +/// +/// All implementations are expected to be immutable; this has the significant +/// advantage of not needing to consider thread safety, and for most +/// distributions efficient state-less sampling algorithms are available. +/// +/// [`sample_iter`]: Distribution::method.sample_iter +pub trait Distribution { + /// Generate a random value of `T`, using `rng` as the source of randomness. + fn sample(&self, rng: &mut R) -> T; + + /// Create an iterator that generates random values of `T`, using `rng` as + /// the source of randomness. + /// + /// # Example + /// + /// ``` + /// use rand::thread_rng; + /// use rand::distributions::{Distribution, Alphanumeric, Uniform, Standard}; + /// + /// let mut rng = thread_rng(); + /// + /// // Vec of 16 x f32: + /// let v: Vec = Standard.sample_iter(&mut rng).take(16).collect(); + /// + /// // String: + /// let s: String = Alphanumeric.sample_iter(&mut rng).take(7).collect(); + /// + /// // Dice-rolling: + /// let die_range = Uniform::new_inclusive(1, 6); + /// let mut roll_die = die_range.sample_iter(&mut rng); + /// while roll_die.next().unwrap() != 6 { + /// println!("Not a 6; rolling again!"); + /// } + /// ``` + fn sample_iter<'a, R>(&'a self, rng: &'a mut R) -> DistIter<'a, Self, R, T> + where Self: Sized, R: Rng + { + DistIter { + distr: self, + rng: rng, + phantom: ::core::marker::PhantomData, + } + } +} + +impl<'a, T, D: Distribution> Distribution for &'a D { + fn sample(&self, rng: &mut R) -> T { + (*self).sample(rng) + } +} + + +/// An iterator that generates random values of `T` with distribution `D`, +/// using `R` as the source of randomness. +/// +/// This `struct` is created by the [`sample_iter`] method on [`Distribution`]. +/// See its documentation for more. +/// +/// [`sample_iter`]: Distribution::sample_iter +#[derive(Debug)] +pub struct DistIter<'a, D: 'a, R: 'a, T> { + distr: &'a D, + rng: &'a mut R, + phantom: ::core::marker::PhantomData, +} + +impl<'a, D, R, T> Iterator for DistIter<'a, D, R, T> + where D: Distribution, R: Rng + 'a +{ + type Item = T; + + #[inline(always)] + fn next(&mut self) -> Option { + Some(self.distr.sample(self.rng)) + } + + fn size_hint(&self) -> (usize, Option) { + (usize::max_value(), None) + } +} + +#[cfg(rustc_1_26)] +impl<'a, D, R, T> iter::FusedIterator for DistIter<'a, D, R, T> + where D: Distribution, R: Rng + 'a {} + +#[cfg(features = "nightly")] +impl<'a, D, R, T> iter::TrustedLen for DistIter<'a, D, R, T> + where D: Distribution, R: Rng + 'a {} + + +/// A generic random value distribution, implemented for many primitive types. +/// Usually generates values with a numerically uniform distribution, and with a +/// range appropriate to the type. +/// +/// ## Built-in Implementations +/// +/// Assuming the provided `Rng` is well-behaved, these implementations +/// generate values with the following ranges and distributions: +/// +/// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed +/// over all values of the type. +/// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all +/// code points in the range `0...0x10_FFFF`, except for the range +/// `0xD800...0xDFFF` (the surrogate code points). This includes +/// unassigned/reserved code points. +/// * `bool`: Generates `false` or `true`, each with probability 0.5. +/// * Floating point types (`f32` and `f64`): Uniformly distributed in the +/// half-open range `[0, 1)`. See notes below. +/// * Wrapping integers (`Wrapping`), besides the type identical to their +/// normal integer variants. +/// +/// The following aggregate types also implement the distribution `Standard` as +/// long as their component types implement it: +/// +/// * Tuples and arrays: Each element of the tuple or array is generated +/// independently, using the `Standard` distribution recursively. +/// * `Option` where `Standard` is implemented for `T`: Returns `None` with +/// probability 0.5; otherwise generates a random `x: T` and returns `Some(x)`. +/// +/// # Example +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::Standard; +/// +/// let val: f32 = SmallRng::from_entropy().sample(Standard); +/// println!("f32 from [0, 1): {}", val); +/// ``` +/// +/// # Floating point implementation +/// The floating point implementations for `Standard` generate a random value in +/// the half-open interval `[0, 1)`, i.e. including 0 but not 1. +/// +/// All values that can be generated are of the form `n * ε/2`. For `f32` +/// the 23 most significant random bits of a `u32` are used and for `f64` the +/// 53 most significant bits of a `u64` are used. The conversion uses the +/// multiplicative method: `(rng.gen::<$uty>() >> N) as $ty * (ε/2)`. +/// +/// See also: [`Open01`] which samples from `(0, 1)`, [`OpenClosed01`] which +/// samples from `(0, 1]` and `Rng::gen_range(0, 1)` which also samples from +/// `[0, 1)`. Note that `Open01` and `gen_range` (which uses [`Uniform`]) use +/// transmute-based methods which yield 1 bit less precision but may perform +/// faster on some architectures (on modern Intel CPUs all methods have +/// approximately equal performance). +/// +/// [`Uniform`]: uniform::Uniform +#[derive(Clone, Copy, Debug)] +pub struct Standard; + + +/// A value with a particular weight for use with `WeightedChoice`. +#[deprecated(since="0.6.0", note="use WeightedIndex instead")] +#[allow(deprecated)] +#[derive(Copy, Clone, Debug)] +pub struct Weighted { + /// The numerical weight of this item + pub weight: u32, + /// The actual item which is being weighted + pub item: T, +} + +/// A distribution that selects from a finite collection of weighted items. +/// +/// Deprecated: use [`WeightedIndex`] instead. +/// +/// [`WeightedIndex`]: WeightedIndex +#[deprecated(since="0.6.0", note="use WeightedIndex instead")] +#[allow(deprecated)] +#[derive(Debug)] +pub struct WeightedChoice<'a, T:'a> { + items: &'a mut [Weighted], + weight_range: Uniform, +} + +#[deprecated(since="0.6.0", note="use WeightedIndex instead")] +#[allow(deprecated)] +impl<'a, T: Clone> WeightedChoice<'a, T> { + /// Create a new `WeightedChoice`. + /// + /// Panics if: + /// + /// - `items` is empty + /// - the total weight is 0 + /// - the total weight is larger than a `u32` can contain. + pub fn new(items: &'a mut [Weighted]) -> WeightedChoice<'a, T> { + // strictly speaking, this is subsumed by the total weight == 0 case + assert!(!items.is_empty(), "WeightedChoice::new called with no items"); + + let mut running_total: u32 = 0; + + // we convert the list from individual weights to cumulative + // weights so we can binary search. This *could* drop elements + // with weight == 0 as an optimisation. + for item in items.iter_mut() { + running_total = match running_total.checked_add(item.weight) { + Some(n) => n, + None => panic!("WeightedChoice::new called with a total weight \ + larger than a u32 can contain") + }; + + item.weight = running_total; + } + assert!(running_total != 0, "WeightedChoice::new called with a total weight of 0"); + + WeightedChoice { + items, + // we're likely to be generating numbers in this range + // relatively often, so might as well cache it + weight_range: Uniform::new(0, running_total) + } + } +} + +#[deprecated(since="0.6.0", note="use WeightedIndex instead")] +#[allow(deprecated)] +impl<'a, T: Clone> Distribution for WeightedChoice<'a, T> { + fn sample(&self, rng: &mut R) -> T { + // we want to find the first element that has cumulative + // weight > sample_weight, which we do by binary since the + // cumulative weights of self.items are sorted. + + // choose a weight in [0, total_weight) + let sample_weight = self.weight_range.sample(rng); + + // short circuit when it's the first item + if sample_weight < self.items[0].weight { + return self.items[0].item.clone(); + } + + let mut idx = 0; + let mut modifier = self.items.len(); + + // now we know that every possibility has an element to the + // left, so we can just search for the last element that has + // cumulative weight <= sample_weight, then the next one will + // be "it". (Note that this greatest element will never be the + // last element of the vector, since sample_weight is chosen + // in [0, total_weight) and the cumulative weight of the last + // one is exactly the total weight.) + while modifier > 1 { + let i = idx + modifier / 2; + if self.items[i].weight <= sample_weight { + // we're small, so look to the right, but allow this + // exact element still. + idx = i; + // we need the `/ 2` to round up otherwise we'll drop + // the trailing elements when `modifier` is odd. + modifier += 1; + } else { + // otherwise we're too big, so go left. (i.e. do + // nothing) + } + modifier /= 2; + } + self.items[idx + 1].item.clone() + } +} + +#[cfg(test)] +mod tests { + use rngs::mock::StepRng; + #[allow(deprecated)] + use super::{WeightedChoice, Weighted, Distribution}; + + #[test] + #[allow(deprecated)] + fn test_weighted_choice() { + // this makes assumptions about the internal implementation of + // WeightedChoice. It may fail when the implementation in + // `distributions::uniform::UniformInt` changes. + + macro_rules! t { + ($items:expr, $expected:expr) => {{ + let mut items = $items; + let mut total_weight = 0; + for item in &items { total_weight += item.weight; } + + let wc = WeightedChoice::new(&mut items); + let expected = $expected; + + // Use extremely large steps between the random numbers, because + // we test with small ranges and `UniformInt` is designed to prefer + // the most significant bits. + let mut rng = StepRng::new(0, !0 / (total_weight as u64)); + + for &val in expected.iter() { + assert_eq!(wc.sample(&mut rng), val) + } + }} + } + + t!([Weighted { weight: 1, item: 10}], [10]); + + // skip some + t!([Weighted { weight: 0, item: 20}, + Weighted { weight: 2, item: 21}, + Weighted { weight: 0, item: 22}, + Weighted { weight: 1, item: 23}], + [21, 21, 23]); + + // different weights + t!([Weighted { weight: 4, item: 30}, + Weighted { weight: 3, item: 31}], + [30, 31, 30, 31, 30, 31, 30]); + + // check that we're binary searching + // correctly with some vectors of odd + // length. + t!([Weighted { weight: 1, item: 40}, + Weighted { weight: 1, item: 41}, + Weighted { weight: 1, item: 42}, + Weighted { weight: 1, item: 43}, + Weighted { weight: 1, item: 44}], + [40, 41, 42, 43, 44]); + t!([Weighted { weight: 1, item: 50}, + Weighted { weight: 1, item: 51}, + Weighted { weight: 1, item: 52}, + Weighted { weight: 1, item: 53}, + Weighted { weight: 1, item: 54}, + Weighted { weight: 1, item: 55}, + Weighted { weight: 1, item: 56}], + [50, 54, 51, 55, 52, 56, 53]); + } + + #[test] + #[allow(deprecated)] + fn test_weighted_clone_initialization() { + let initial : Weighted = Weighted {weight: 1, item: 1}; + let clone = initial.clone(); + assert_eq!(initial.weight, clone.weight); + assert_eq!(initial.item, clone.item); + } + + #[test] #[should_panic] + #[allow(deprecated)] + fn test_weighted_clone_change_weight() { + let initial : Weighted = Weighted {weight: 1, item: 1}; + let mut clone = initial.clone(); + clone.weight = 5; + assert_eq!(initial.weight, clone.weight); + } + + #[test] #[should_panic] + #[allow(deprecated)] + fn test_weighted_clone_change_item() { + let initial : Weighted = Weighted {weight: 1, item: 1}; + let mut clone = initial.clone(); + clone.item = 5; + assert_eq!(initial.item, clone.item); + + } + + #[test] #[should_panic] + #[allow(deprecated)] + fn test_weighted_choice_no_items() { + WeightedChoice::::new(&mut []); + } + #[test] #[should_panic] + #[allow(deprecated)] + fn test_weighted_choice_zero_weight() { + WeightedChoice::new(&mut [Weighted { weight: 0, item: 0}, + Weighted { weight: 0, item: 1}]); + } + #[test] #[should_panic] + #[allow(deprecated)] + fn test_weighted_choice_weight_overflows() { + let x = ::core::u32::MAX / 2; // x + x + 2 is the overflow + WeightedChoice::new(&mut [Weighted { weight: x, item: 0 }, + Weighted { weight: 1, item: 1 }, + Weighted { weight: x, item: 2 }, + Weighted { weight: 1, item: 3 }]); + } + + #[cfg(feature="std")] + #[test] + fn test_distributions_iter() { + use distributions::Normal; + let mut rng = ::test::rng(210); + let distr = Normal::new(10.0, 10.0); + let results: Vec<_> = distr.sample_iter(&mut rng).take(100).collect(); + println!("{:?}", results); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/normal.rs b/bash-5.1/vendor/rand/src/distributions/normal.rs new file mode 100644 index 0000000..089865e --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/normal.rs @@ -0,0 +1,197 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The normal and derived distributions. + +use Rng; +use distributions::{ziggurat_tables, Distribution, Open01}; +use distributions::utils::ziggurat; + +/// Samples floating-point numbers according to the normal distribution +/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to +/// `Normal::new(0.0, 1.0)` but faster. +/// +/// See `Normal` for the general normal distribution. +/// +/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. +/// +/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to +/// Generate Normal Random Samples*]( +/// https://www.doornik.com/research/ziggurat.pdf). +/// Nuffield College, Oxford +/// +/// # Example +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::StandardNormal; +/// +/// let val: f64 = SmallRng::from_entropy().sample(StandardNormal); +/// println!("{}", val); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct StandardNormal; + +impl Distribution for StandardNormal { + fn sample(&self, rng: &mut R) -> f64 { + #[inline] + fn pdf(x: f64) -> f64 { + (-x*x/2.0).exp() + } + #[inline] + fn zero_case(rng: &mut R, u: f64) -> f64 { + // compute a random number in the tail by hand + + // strange initial conditions, because the loop is not + // do-while, so the condition should be true on the first + // run, they get overwritten anyway (0 < 1, so these are + // good). + let mut x = 1.0f64; + let mut y = 0.0f64; + + while -2.0 * y < x * x { + let x_: f64 = rng.sample(Open01); + let y_: f64 = rng.sample(Open01); + + x = x_.ln() / ziggurat_tables::ZIG_NORM_R; + y = y_.ln(); + } + + if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } + } + + ziggurat(rng, true, // this is symmetric + &ziggurat_tables::ZIG_NORM_X, + &ziggurat_tables::ZIG_NORM_F, + pdf, zero_case) + } +} + +/// The normal distribution `N(mean, std_dev**2)`. +/// +/// This uses the ZIGNOR variant of the Ziggurat method, see [`StandardNormal`] +/// for more details. +/// +/// Note that [`StandardNormal`] is an optimised implementation for mean 0, and +/// standard deviation 1. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Normal, Distribution}; +/// +/// // mean 2, standard deviation 3 +/// let normal = Normal::new(2.0, 3.0); +/// let v = normal.sample(&mut rand::thread_rng()); +/// println!("{} is from a N(2, 9) distribution", v) +/// ``` +/// +/// [`StandardNormal`]: crate::distributions::StandardNormal +#[derive(Clone, Copy, Debug)] +pub struct Normal { + mean: f64, + std_dev: f64, +} + +impl Normal { + /// Construct a new `Normal` distribution with the given mean and + /// standard deviation. + /// + /// # Panics + /// + /// Panics if `std_dev < 0`. + #[inline] + pub fn new(mean: f64, std_dev: f64) -> Normal { + assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); + Normal { + mean, + std_dev + } + } +} +impl Distribution for Normal { + fn sample(&self, rng: &mut R) -> f64 { + let n = rng.sample(StandardNormal); + self.mean + self.std_dev * n + } +} + + +/// The log-normal distribution `ln N(mean, std_dev**2)`. +/// +/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)` +/// distributed. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{LogNormal, Distribution}; +/// +/// // mean 2, standard deviation 3 +/// let log_normal = LogNormal::new(2.0, 3.0); +/// let v = log_normal.sample(&mut rand::thread_rng()); +/// println!("{} is from an ln N(2, 9) distribution", v) +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct LogNormal { + norm: Normal +} + +impl LogNormal { + /// Construct a new `LogNormal` distribution with the given mean + /// and standard deviation. + /// + /// # Panics + /// + /// Panics if `std_dev < 0`. + #[inline] + pub fn new(mean: f64, std_dev: f64) -> LogNormal { + assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); + LogNormal { norm: Normal::new(mean, std_dev) } + } +} +impl Distribution for LogNormal { + fn sample(&self, rng: &mut R) -> f64 { + self.norm.sample(rng).exp() + } +} + +#[cfg(test)] +mod tests { + use distributions::Distribution; + use super::{Normal, LogNormal}; + + #[test] + fn test_normal() { + let norm = Normal::new(10.0, 10.0); + let mut rng = ::test::rng(210); + for _ in 0..1000 { + norm.sample(&mut rng); + } + } + #[test] + #[should_panic] + fn test_normal_invalid_sd() { + Normal::new(10.0, -1.0); + } + + + #[test] + fn test_log_normal() { + let lnorm = LogNormal::new(10.0, 10.0); + let mut rng = ::test::rng(211); + for _ in 0..1000 { + lnorm.sample(&mut rng); + } + } + #[test] + #[should_panic] + fn test_log_normal_invalid_sd() { + LogNormal::new(10.0, -1.0); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/other.rs b/bash-5.1/vendor/rand/src/distributions/other.rs new file mode 100644 index 0000000..2295f79 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/other.rs @@ -0,0 +1,219 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The implementations of the `Standard` distribution for other built-in types. + +use core::char; +use core::num::Wrapping; + +use {Rng}; +use distributions::{Distribution, Standard, Uniform}; + +// ----- Sampling distributions ----- + +/// Sample a `char`, uniformly distributed over ASCII letters and numbers: +/// a-z, A-Z and 0-9. +/// +/// # Example +/// +/// ``` +/// use std::iter; +/// use rand::{Rng, thread_rng}; +/// use rand::distributions::Alphanumeric; +/// +/// let mut rng = thread_rng(); +/// let chars: String = iter::repeat(()) +/// .map(|()| rng.sample(Alphanumeric)) +/// .take(7) +/// .collect(); +/// println!("Random chars: {}", chars); +/// ``` +#[derive(Debug)] +pub struct Alphanumeric; + + +// ----- Implementations of distributions ----- + +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> char { + // A valid `char` is either in the interval `[0, 0xD800)` or + // `(0xDFFF, 0x11_0000)`. All `char`s must therefore be in + // `[0, 0x11_0000)` but not in the "gap" `[0xD800, 0xDFFF]` which is + // reserved for surrogates. This is the size of that gap. + const GAP_SIZE: u32 = 0xDFFF - 0xD800 + 1; + + // Uniform::new(0, 0x11_0000 - GAP_SIZE) can also be used but it + // seemed slower. + let range = Uniform::new(GAP_SIZE, 0x11_0000); + + let mut n = range.sample(rng); + if n <= 0xDFFF { + n -= GAP_SIZE; + } + unsafe { char::from_u32_unchecked(n) } + } +} + +impl Distribution for Alphanumeric { + fn sample(&self, rng: &mut R) -> char { + const RANGE: u32 = 26 + 26 + 10; + const GEN_ASCII_STR_CHARSET: &[u8] = + b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ + abcdefghijklmnopqrstuvwxyz\ + 0123456789"; + // We can pick from 62 characters. This is so close to a power of 2, 64, + // that we can do better than `Uniform`. Use a simple bitshift and + // rejection sampling. We do not use a bitmask, because for small RNGs + // the most significant bits are usually of higher quality. + loop { + let var = rng.next_u32() >> (32 - 6); + if var < RANGE { + return GEN_ASCII_STR_CHARSET[var as usize] as char + } + } + } +} + +impl Distribution for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> bool { + // We can compare against an arbitrary bit of an u32 to get a bool. + // Because the least significant bits of a lower quality RNG can have + // simple patterns, we compare against the most significant bit. This is + // easiest done using a sign test. + (rng.next_u32() as i32) < 0 + } +} + +macro_rules! tuple_impl { + // use variables to indicate the arity of the tuple + ($($tyvar:ident),* ) => { + // the trailing commas are for the 1 tuple + impl< $( $tyvar ),* > + Distribution<( $( $tyvar ),* , )> + for Standard + where $( Standard: Distribution<$tyvar> ),* + { + #[inline] + fn sample(&self, _rng: &mut R) -> ( $( $tyvar ),* , ) { + ( + // use the $tyvar's to get the appropriate number of + // repeats (they're not actually needed) + $( + _rng.gen::<$tyvar>() + ),* + , + ) + } + } + } +} + +impl Distribution<()> for Standard { + #[inline] + fn sample(&self, _: &mut R) -> () { () } +} +tuple_impl!{A} +tuple_impl!{A, B} +tuple_impl!{A, B, C} +tuple_impl!{A, B, C, D} +tuple_impl!{A, B, C, D, E} +tuple_impl!{A, B, C, D, E, F} +tuple_impl!{A, B, C, D, E, F, G} +tuple_impl!{A, B, C, D, E, F, G, H} +tuple_impl!{A, B, C, D, E, F, G, H, I} +tuple_impl!{A, B, C, D, E, F, G, H, I, J} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} + +macro_rules! array_impl { + // recursive, given at least one type parameter: + {$n:expr, $t:ident, $($ts:ident,)*} => { + array_impl!{($n - 1), $($ts,)*} + + impl Distribution<[T; $n]> for Standard where Standard: Distribution { + #[inline] + fn sample(&self, _rng: &mut R) -> [T; $n] { + [_rng.gen::<$t>(), $(_rng.gen::<$ts>()),*] + } + } + }; + // empty case: + {$n:expr,} => { + impl Distribution<[T; $n]> for Standard { + fn sample(&self, _rng: &mut R) -> [T; $n] { [] } + } + }; +} + +array_impl!{32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,} + +impl Distribution> for Standard where Standard: Distribution { + #[inline] + fn sample(&self, rng: &mut R) -> Option { + // UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 + if rng.gen::() { + Some(rng.gen()) + } else { + None + } + } +} + +impl Distribution> for Standard where Standard: Distribution { + #[inline] + fn sample(&self, rng: &mut R) -> Wrapping { + Wrapping(rng.gen()) + } +} + + +#[cfg(test)] +mod tests { + use {Rng, RngCore, Standard}; + use distributions::Alphanumeric; + #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::string::String; + + #[test] + fn test_misc() { + let rng: &mut RngCore = &mut ::test::rng(820); + + rng.sample::(Standard); + rng.sample::(Standard); + } + + #[cfg(feature="alloc")] + #[test] + fn test_chars() { + use core::iter; + let mut rng = ::test::rng(805); + + // Test by generating a relatively large number of chars, so we also + // take the rejection sampling path. + let word: String = iter::repeat(()) + .map(|()| rng.gen::()).take(1000).collect(); + assert!(word.len() != 0); + } + + #[test] + fn test_alphanumeric() { + let mut rng = ::test::rng(806); + + // Test by generating a relatively large number of chars, so we also + // take the rejection sampling path. + let mut incorrect = false; + for _ in 0..100 { + let c = rng.sample(Alphanumeric); + incorrect |= !((c >= '0' && c <= '9') || + (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') ); + } + assert!(incorrect == false); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/pareto.rs b/bash-5.1/vendor/rand/src/distributions/pareto.rs new file mode 100644 index 0000000..744a157 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/pareto.rs @@ -0,0 +1,74 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Pareto distribution. + +use Rng; +use distributions::{Distribution, OpenClosed01}; + +/// Samples floating-point numbers according to the Pareto distribution +/// +/// # Example +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::Pareto; +/// +/// let val: f64 = SmallRng::from_entropy().sample(Pareto::new(1., 2.)); +/// println!("{}", val); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Pareto { + scale: f64, + inv_neg_shape: f64, +} + +impl Pareto { + /// Construct a new Pareto distribution with given `scale` and `shape`. + /// + /// In the literature, `scale` is commonly written as xm or k and + /// `shape` is often written as α. + /// + /// # Panics + /// + /// `scale` and `shape` have to be non-zero and positive. + pub fn new(scale: f64, shape: f64) -> Pareto { + assert!((scale > 0.) & (shape > 0.)); + Pareto { scale, inv_neg_shape: -1.0 / shape } + } +} + +impl Distribution for Pareto { + fn sample(&self, rng: &mut R) -> f64 { + let u: f64 = rng.sample(OpenClosed01); + self.scale * u.powf(self.inv_neg_shape) + } +} + +#[cfg(test)] +mod tests { + use distributions::Distribution; + use super::Pareto; + + #[test] + #[should_panic] + fn invalid() { + Pareto::new(0., 0.); + } + + #[test] + fn sample() { + let scale = 1.0; + let shape = 2.0; + let d = Pareto::new(scale, shape); + let mut rng = ::test::rng(1); + for _ in 0..1000 { + let r = d.sample(&mut rng); + assert!(r >= scale); + } + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/poisson.rs b/bash-5.1/vendor/rand/src/distributions/poisson.rs new file mode 100644 index 0000000..1244caa --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/poisson.rs @@ -0,0 +1,157 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2016-2017 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Poisson distribution. + +use Rng; +use distributions::{Distribution, Cauchy}; +use distributions::utils::log_gamma; + +/// The Poisson distribution `Poisson(lambda)`. +/// +/// This distribution has a density function: +/// `f(k) = lambda^k * exp(-lambda) / k!` for `k >= 0`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Poisson, Distribution}; +/// +/// let poi = Poisson::new(2.0); +/// let v = poi.sample(&mut rand::thread_rng()); +/// println!("{} is from a Poisson(2) distribution", v); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Poisson { + lambda: f64, + // precalculated values + exp_lambda: f64, + log_lambda: f64, + sqrt_2lambda: f64, + magic_val: f64, +} + +impl Poisson { + /// Construct a new `Poisson` with the given shape parameter + /// `lambda`. Panics if `lambda <= 0`. + pub fn new(lambda: f64) -> Poisson { + assert!(lambda > 0.0, "Poisson::new called with lambda <= 0"); + let log_lambda = lambda.ln(); + Poisson { + lambda, + exp_lambda: (-lambda).exp(), + log_lambda, + sqrt_2lambda: (2.0 * lambda).sqrt(), + magic_val: lambda * log_lambda - log_gamma(1.0 + lambda), + } + } +} + +impl Distribution for Poisson { + fn sample(&self, rng: &mut R) -> u64 { + // using the algorithm from Numerical Recipes in C + + // for low expected values use the Knuth method + if self.lambda < 12.0 { + let mut result = 0; + let mut p = 1.0; + while p > self.exp_lambda { + p *= rng.gen::(); + result += 1; + } + result - 1 + } + // high expected values - rejection method + else { + let mut int_result: u64; + + // we use the Cauchy distribution as the comparison distribution + // f(x) ~ 1/(1+x^2) + let cauchy = Cauchy::new(0.0, 1.0); + + loop { + let mut result; + let mut comp_dev; + + loop { + // draw from the Cauchy distribution + comp_dev = rng.sample(cauchy); + // shift the peak of the comparison ditribution + result = self.sqrt_2lambda * comp_dev + self.lambda; + // repeat the drawing until we are in the range of possible values + if result >= 0.0 { + break; + } + } + // now the result is a random variable greater than 0 with Cauchy distribution + // the result should be an integer value + result = result.floor(); + int_result = result as u64; + + // this is the ratio of the Poisson distribution to the comparison distribution + // the magic value scales the distribution function to a range of approximately 0-1 + // since it is not exact, we multiply the ratio by 0.9 to avoid ratios greater than 1 + // this doesn't change the resulting distribution, only increases the rate of failed drawings + let check = 0.9 * (1.0 + comp_dev * comp_dev) + * (result * self.log_lambda - log_gamma(1.0 + result) - self.magic_val).exp(); + + // check with uniform random value - if below the threshold, we are within the target distribution + if rng.gen::() <= check { + break; + } + } + int_result + } + } +} + +#[cfg(test)] +mod test { + use distributions::Distribution; + use super::Poisson; + + #[test] + fn test_poisson_10() { + let poisson = Poisson::new(10.0); + let mut rng = ::test::rng(123); + let mut sum = 0; + for _ in 0..1000 { + sum += poisson.sample(&mut rng); + } + let avg = (sum as f64) / 1000.0; + println!("Poisson average: {}", avg); + assert!((avg - 10.0).abs() < 0.5); // not 100% certain, but probable enough + } + + #[test] + fn test_poisson_15() { + // Take the 'high expected values' path + let poisson = Poisson::new(15.0); + let mut rng = ::test::rng(123); + let mut sum = 0; + for _ in 0..1000 { + sum += poisson.sample(&mut rng); + } + let avg = (sum as f64) / 1000.0; + println!("Poisson average: {}", avg); + assert!((avg - 15.0).abs() < 0.5); // not 100% certain, but probable enough + } + + #[test] + #[should_panic] + fn test_poisson_invalid_lambda_zero() { + Poisson::new(0.0); + } + + #[test] + #[should_panic] + fn test_poisson_invalid_lambda_neg() { + Poisson::new(-10.0); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/triangular.rs b/bash-5.1/vendor/rand/src/distributions/triangular.rs new file mode 100644 index 0000000..a6eef5c --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/triangular.rs @@ -0,0 +1,86 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! The triangular distribution. + +use Rng; +use distributions::{Distribution, Standard}; + +/// The triangular distribution. +/// +/// # Example +/// +/// ```rust +/// use rand::distributions::{Triangular, Distribution}; +/// +/// let d = Triangular::new(0., 5., 2.5); +/// let v = d.sample(&mut rand::thread_rng()); +/// println!("{} is from a triangular distribution", v); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Triangular { + min: f64, + max: f64, + mode: f64, +} + +impl Triangular { + /// Construct a new `Triangular` with minimum `min`, maximum `max` and mode + /// `mode`. + /// + /// # Panics + /// + /// If `max < mode`, `mode < max` or `max == min`. + /// + #[inline] + pub fn new(min: f64, max: f64, mode: f64) -> Triangular { + assert!(max >= mode); + assert!(mode >= min); + assert!(max != min); + Triangular { min, max, mode } + } +} + +impl Distribution for Triangular { + #[inline] + fn sample(&self, rng: &mut R) -> f64 { + let f: f64 = rng.sample(Standard); + let diff_mode_min = self.mode - self.min; + let diff_max_min = self.max - self.min; + if f * diff_max_min < diff_mode_min { + self.min + (f * diff_max_min * diff_mode_min).sqrt() + } else { + self.max - ((1. - f) * diff_max_min * (self.max - self.mode)).sqrt() + } + } +} + +#[cfg(test)] +mod test { + use distributions::Distribution; + use super::Triangular; + + #[test] + fn test_new() { + for &(min, max, mode) in &[ + (-1., 1., 0.), (1., 2., 1.), (5., 25., 25.), (1e-5, 1e5, 1e-3), + (0., 1., 0.9), (-4., -0.5, -2.), (-13.039, 8.41, 1.17), + ] { + println!("{} {} {}", min, max, mode); + let _ = Triangular::new(min, max, mode); + } + } + + #[test] + fn test_sample() { + let norm = Triangular::new(0., 1., 0.5); + let mut rng = ::test::rng(1); + for _ in 0..1000 { + norm.sample(&mut rng); + } + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/uniform.rs b/bash-5.1/vendor/rand/src/distributions/uniform.rs new file mode 100644 index 0000000..19b4934 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/uniform.rs @@ -0,0 +1,1283 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A distribution uniformly sampling numbers within a given range. +//! +//! [`Uniform`] is the standard distribution to sample uniformly from a range; +//! e.g. `Uniform::new_inclusive(1, 6)` can sample integers from 1 to 6, like a +//! standard die. [`Rng::gen_range`] supports any type supported by +//! [`Uniform`]. +//! +//! This distribution is provided with support for several primitive types +//! (all integer and floating-point types) as well as [`std::time::Duration`], +//! and supports extension to user-defined types via a type-specific *back-end* +//! implementation. +//! +//! The types [`UniformInt`], [`UniformFloat`] and [`UniformDuration`] are the +//! back-ends supporting sampling from primitive integer and floating-point +//! ranges as well as from [`std::time::Duration`]; these types do not normally +//! need to be used directly (unless implementing a derived back-end). +//! +//! # Example usage +//! +//! ``` +//! use rand::{Rng, thread_rng}; +//! use rand::distributions::Uniform; +//! +//! let mut rng = thread_rng(); +//! let side = Uniform::new(-10.0, 10.0); +//! +//! // sample between 1 and 10 points +//! for _ in 0..rng.gen_range(1, 11) { +//! // sample a point from the square with sides -10 - 10 in two dimensions +//! let (x, y) = (rng.sample(side), rng.sample(side)); +//! println!("Point: {}, {}", x, y); +//! } +//! ``` +//! +//! # Extending `Uniform` to support a custom type +//! +//! To extend [`Uniform`] to support your own types, write a back-end which +//! implements the [`UniformSampler`] trait, then implement the [`SampleUniform`] +//! helper trait to "register" your back-end. See the `MyF32` example below. +//! +//! At a minimum, the back-end needs to store any parameters needed for sampling +//! (e.g. the target range) and implement `new`, `new_inclusive` and `sample`. +//! Those methods should include an assert to check the range is valid (i.e. +//! `low < high`). The example below merely wraps another back-end. +//! +//! The `new`, `new_inclusive` and `sample_single` functions use arguments of +//! type SampleBorrow in order to support passing in values by reference or +//! by value. In the implementation of these functions, you can choose to +//! simply use the reference returned by [`SampleBorrow::borrow`], or you can choose +//! to copy or clone the value, whatever is appropriate for your type. +//! +//! ``` +//! use rand::prelude::*; +//! use rand::distributions::uniform::{Uniform, SampleUniform, +//! UniformSampler, UniformFloat, SampleBorrow}; +//! +//! struct MyF32(f32); +//! +//! #[derive(Clone, Copy, Debug)] +//! struct UniformMyF32 { +//! inner: UniformFloat, +//! } +//! +//! impl UniformSampler for UniformMyF32 { +//! type X = MyF32; +//! fn new(low: B1, high: B2) -> Self +//! where B1: SampleBorrow + Sized, +//! B2: SampleBorrow + Sized +//! { +//! UniformMyF32 { +//! inner: UniformFloat::::new(low.borrow().0, high.borrow().0), +//! } +//! } +//! fn new_inclusive(low: B1, high: B2) -> Self +//! where B1: SampleBorrow + Sized, +//! B2: SampleBorrow + Sized +//! { +//! UniformSampler::new(low, high) +//! } +//! fn sample(&self, rng: &mut R) -> Self::X { +//! MyF32(self.inner.sample(rng)) +//! } +//! } +//! +//! impl SampleUniform for MyF32 { +//! type Sampler = UniformMyF32; +//! } +//! +//! let (low, high) = (MyF32(17.0f32), MyF32(22.0f32)); +//! let uniform = Uniform::new(low, high); +//! let x = uniform.sample(&mut thread_rng()); +//! ``` +//! +//! [`SampleUniform`]: crate::distributions::uniform::SampleUniform +//! [`UniformSampler`]: crate::distributions::uniform::UniformSampler +//! [`UniformInt`]: crate::distributions::uniform::UniformInt +//! [`UniformFloat`]: crate::distributions::uniform::UniformFloat +//! [`UniformDuration`]: crate::distributions::uniform::UniformDuration +//! [`SampleBorrow::borrow`]: crate::distributions::uniform::SampleBorrow::borrow + +#[cfg(feature = "std")] +use std::time::Duration; +#[cfg(all(not(feature = "std"), rustc_1_25))] +use core::time::Duration; + +use Rng; +use distributions::Distribution; +use distributions::float::IntoFloat; +use distributions::utils::{WideningMultiply, FloatSIMDUtils, FloatAsSIMD, BoolAsSIMD}; + +#[cfg(not(feature = "std"))] +#[allow(unused_imports)] // rustc doesn't detect that this is actually used +use distributions::utils::Float; + + +#[cfg(feature="simd_support")] +use packed_simd::*; + +/// Sample values uniformly between two bounds. +/// +/// [`Uniform::new`] and [`Uniform::new_inclusive`] construct a uniform +/// distribution sampling from the given range; these functions may do extra +/// work up front to make sampling of multiple values faster. +/// +/// When sampling from a constant range, many calculations can happen at +/// compile-time and all methods should be fast; for floating-point ranges and +/// the full range of integer types this should have comparable performance to +/// the `Standard` distribution. +/// +/// Steps are taken to avoid bias which might be present in naive +/// implementations; for example `rng.gen::() % 170` samples from the range +/// `[0, 169]` but is twice as likely to select numbers less than 85 than other +/// values. Further, the implementations here give more weight to the high-bits +/// generated by the RNG than the low bits, since with some RNGs the low-bits +/// are of lower quality than the high bits. +/// +/// Implementations must sample in `[low, high)` range for +/// `Uniform::new(low, high)`, i.e., excluding `high`. In particular care must +/// be taken to ensure that rounding never results values `< low` or `>= high`. +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{Distribution, Uniform}; +/// +/// fn main() { +/// let between = Uniform::from(10..10000); +/// let mut rng = rand::thread_rng(); +/// let mut sum = 0; +/// for _ in 0..1000 { +/// sum += between.sample(&mut rng); +/// } +/// println!("{}", sum); +/// } +/// ``` +/// +/// [`new`]: Uniform::new +/// [`new_inclusive`]: Uniform::new_inclusive +#[derive(Clone, Copy, Debug)] +pub struct Uniform { + inner: X::Sampler, +} + +impl Uniform { + /// Create a new `Uniform` instance which samples uniformly from the half + /// open range `[low, high)` (excluding `high`). Panics if `low >= high`. + pub fn new(low: B1, high: B2) -> Uniform + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + Uniform { inner: X::Sampler::new(low, high) } + } + + /// Create a new `Uniform` instance which samples uniformly from the closed + /// range `[low, high]` (inclusive). Panics if `low > high`. + pub fn new_inclusive(low: B1, high: B2) -> Uniform + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + Uniform { inner: X::Sampler::new_inclusive(low, high) } + } +} + +impl Distribution for Uniform { + fn sample(&self, rng: &mut R) -> X { + self.inner.sample(rng) + } +} + +/// Helper trait for creating objects using the correct implementation of +/// [`UniformSampler`] for the sampling type. +/// +/// See the [module documentation] on how to implement [`Uniform`] range +/// sampling for a custom type. +/// +/// [module documentation]: crate::distributions::uniform +pub trait SampleUniform: Sized { + /// The `UniformSampler` implementation supporting type `X`. + type Sampler: UniformSampler; +} + +/// Helper trait handling actual uniform sampling. +/// +/// See the [module documentation] on how to implement [`Uniform`] range +/// sampling for a custom type. +/// +/// Implementation of [`sample_single`] is optional, and is only useful when +/// the implementation can be faster than `Self::new(low, high).sample(rng)`. +/// +/// [module documentation]: crate::distributions::uniform +/// [`sample_single`]: UniformSampler::sample_single +pub trait UniformSampler: Sized { + /// The type sampled by this implementation. + type X; + + /// Construct self, with inclusive lower bound and exclusive upper bound + /// `[low, high)`. + /// + /// Usually users should not call this directly but instead use + /// `Uniform::new`, which asserts that `low < high` before calling this. + fn new(low: B1, high: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized; + + /// Construct self, with inclusive bounds `[low, high]`. + /// + /// Usually users should not call this directly but instead use + /// `Uniform::new_inclusive`, which asserts that `low <= high` before + /// calling this. + fn new_inclusive(low: B1, high: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized; + + /// Sample a value. + fn sample(&self, rng: &mut R) -> Self::X; + + /// Sample a single value uniformly from a range with inclusive lower bound + /// and exclusive upper bound `[low, high)`. + /// + /// Usually users should not call this directly but instead use + /// `Uniform::sample_single`, which asserts that `low < high` before calling + /// this. + /// + /// Via this method, implementations can provide a method optimized for + /// sampling only a single value from the specified range. The default + /// implementation simply calls `UniformSampler::new` then `sample` on the + /// result. + fn sample_single(low: B1, high: B2, rng: &mut R) + -> Self::X + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let uniform: Self = UniformSampler::new(low, high); + uniform.sample(rng) + } +} + +impl From<::core::ops::Range> for Uniform { + fn from(r: ::core::ops::Range) -> Uniform { + Uniform::new(r.start, r.end) + } +} + +#[cfg(rustc_1_27)] +impl From<::core::ops::RangeInclusive> for Uniform { + fn from(r: ::core::ops::RangeInclusive) -> Uniform { + Uniform::new_inclusive(r.start(), r.end()) + } +} + +/// Helper trait similar to [`Borrow`] but implemented +/// only for SampleUniform and references to SampleUniform in +/// order to resolve ambiguity issues. +/// +/// [`Borrow`]: std::borrow::Borrow +pub trait SampleBorrow { + /// Immutably borrows from an owned value. See [`Borrow::borrow`] + /// + /// [`Borrow::borrow`]: std::borrow::Borrow::borrow + fn borrow(&self) -> &Borrowed; +} +impl SampleBorrow for Borrowed where Borrowed: SampleUniform { + #[inline(always)] + fn borrow(&self) -> &Borrowed { self } +} +impl<'a, Borrowed> SampleBorrow for &'a Borrowed where Borrowed: SampleUniform { + #[inline(always)] + fn borrow(&self) -> &Borrowed { *self } +} + +//////////////////////////////////////////////////////////////////////////////// + +// What follows are all back-ends. + + +/// The back-end implementing [`UniformSampler`] for integer types. +/// +/// Unless you are implementing [`UniformSampler`] for your own type, this type +/// should not be used directly, use [`Uniform`] instead. +/// +/// # Implementation notes +/// +/// For a closed range, the number of possible numbers we should generate is +/// `range = (high - low + 1)`. It is not possible to end up with a uniform +/// distribution if we map *all* the random integers that can be generated to +/// this range. We have to map integers from a `zone` that is a multiple of the +/// range. The rest of the integers, that cause a bias, are rejected. +/// +/// The problem with `range` is that to cover the full range of the type, it has +/// to store `unsigned_max + 1`, which can't be represented. But if the range +/// covers the full range of the type, no modulus is needed. A range of size 0 +/// can't exist, so we use that to represent this special case. Wrapping +/// arithmetic even makes representing `unsigned_max + 1` as 0 simple. +/// +/// We don't calculate `zone` directly, but first calculate the number of +/// integers to reject. To handle `unsigned_max + 1` not fitting in the type, +/// we use: +/// `ints_to_reject = (unsigned_max + 1) % range;` +/// `ints_to_reject = (unsigned_max - range + 1) % range;` +/// +/// The smallest integer PRNGs generate is `u32`. That is why for small integer +/// sizes (`i8`/`u8` and `i16`/`u16`) there is an optimization: don't pick the +/// largest zone that can fit in the small type, but pick the largest zone that +/// can fit in an `u32`. `ints_to_reject` is always less than half the size of +/// the small integer. This means the first bit of `zone` is always 1, and so +/// are all the other preceding bits of a larger integer. The easiest way to +/// grow the `zone` for the larger type is to simply sign extend it. +/// +/// An alternative to using a modulus is widening multiply: After a widening +/// multiply by `range`, the result is in the high word. Then comparing the low +/// word against `zone` makes sure our distribution is uniform. +#[derive(Clone, Copy, Debug)] +pub struct UniformInt { + low: X, + range: X, + zone: X, +} + +macro_rules! uniform_int_impl { + ($ty:ty, $signed:ty, $unsigned:ident, + $i_large:ident, $u_large:ident) => { + impl SampleUniform for $ty { + type Sampler = UniformInt<$ty>; + } + + impl UniformSampler for UniformInt<$ty> { + // We play free and fast with unsigned vs signed here + // (when $ty is signed), but that's fine, since the + // contract of this macro is for $ty and $unsigned to be + // "bit-equal", so casting between them is a no-op. + + type X = $ty; + + #[inline] // if the range is constant, this helps LLVM to do the + // calculations at compile-time. + fn new(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low < high, "Uniform::new called with `low >= high`"); + UniformSampler::new_inclusive(low, high - 1) + } + + #[inline] // if the range is constant, this helps LLVM to do the + // calculations at compile-time. + fn new_inclusive(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low <= high, + "Uniform::new_inclusive called with `low > high`"); + let unsigned_max = ::core::$unsigned::MAX; + + let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned; + let ints_to_reject = + if range > 0 { + (unsigned_max - range + 1) % range + } else { + 0 + }; + let zone = unsigned_max - ints_to_reject; + + UniformInt { + low: low, + // These are really $unsigned values, but store as $ty: + range: range as $ty, + zone: zone as $ty + } + } + + fn sample(&self, rng: &mut R) -> Self::X { + let range = self.range as $unsigned as $u_large; + if range > 0 { + // Grow `zone` to fit a type of at least 32 bits, by + // sign-extending it (the first bit is always 1, so are all + // the preceding bits of the larger type). + // For types that already have the right size, all the + // casting is a no-op. + let zone = self.zone as $signed as $i_large as $u_large; + loop { + let v: $u_large = rng.gen(); + let (hi, lo) = v.wmul(range); + if lo <= zone { + return self.low.wrapping_add(hi as $ty); + } + } + } else { + // Sample from the entire integer range. + rng.gen() + } + } + + fn sample_single(low_b: B1, high_b: B2, rng: &mut R) + -> Self::X + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low < high, + "Uniform::sample_single called with low >= high"); + let range = high.wrapping_sub(low) as $unsigned as $u_large; + let zone = + if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned { + // Using a modulus is faster than the approximation for + // i8 and i16. I suppose we trade the cost of one + // modulus for near-perfect branch prediction. + let unsigned_max: $u_large = ::core::$u_large::MAX; + let ints_to_reject = (unsigned_max - range + 1) % range; + unsigned_max - ints_to_reject + } else { + // conservative but fast approximation. `- 1` is necessary to allow the + // same comparison without bias. + (range << range.leading_zeros()).wrapping_sub(1) + }; + + loop { + let v: $u_large = rng.gen(); + let (hi, lo) = v.wmul(range); + if lo <= zone { + return low.wrapping_add(hi as $ty); + } + } + } + } + } +} + +uniform_int_impl! { i8, i8, u8, i32, u32 } +uniform_int_impl! { i16, i16, u16, i32, u32 } +uniform_int_impl! { i32, i32, u32, i32, u32 } +uniform_int_impl! { i64, i64, u64, i64, u64 } +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] +uniform_int_impl! { i128, i128, u128, u128, u128 } +uniform_int_impl! { isize, isize, usize, isize, usize } +uniform_int_impl! { u8, i8, u8, i32, u32 } +uniform_int_impl! { u16, i16, u16, i32, u32 } +uniform_int_impl! { u32, i32, u32, i32, u32 } +uniform_int_impl! { u64, i64, u64, i64, u64 } +uniform_int_impl! { usize, isize, usize, isize, usize } +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] +uniform_int_impl! { u128, u128, u128, i128, u128 } + +#[cfg(all(feature = "simd_support", feature = "nightly"))] +macro_rules! uniform_simd_int_impl { + ($ty:ident, $unsigned:ident, $u_scalar:ident) => { + // The "pick the largest zone that can fit in an `u32`" optimization + // is less useful here. Multiple lanes complicate things, we don't + // know the PRNG's minimal output size, and casting to a larger vector + // is generally a bad idea for SIMD performance. The user can still + // implement it manually. + + // TODO: look into `Uniform::::new(0u32, 100)` functionality + // perhaps `impl SampleUniform for $u_scalar`? + impl SampleUniform for $ty { + type Sampler = UniformInt<$ty>; + } + + impl UniformSampler for UniformInt<$ty> { + type X = $ty; + + #[inline] // if the range is constant, this helps LLVM to do the + // calculations at compile-time. + fn new(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low.lt(high).all(), "Uniform::new called with `low >= high`"); + UniformSampler::new_inclusive(low, high - 1) + } + + #[inline] // if the range is constant, this helps LLVM to do the + // calculations at compile-time. + fn new_inclusive(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low.le(high).all(), + "Uniform::new_inclusive called with `low > high`"); + let unsigned_max = ::core::$u_scalar::MAX; + + // NOTE: these may need to be replaced with explicitly + // wrapping operations if `packed_simd` changes + let range: $unsigned = ((high - low) + 1).cast(); + // `% 0` will panic at runtime. + let not_full_range = range.gt($unsigned::splat(0)); + // replacing 0 with `unsigned_max` allows a faster `select` + // with bitwise OR + let modulo = not_full_range.select(range, $unsigned::splat(unsigned_max)); + // wrapping addition + let ints_to_reject = (unsigned_max - range + 1) % modulo; + // When `range` is 0, `lo` of `v.wmul(range)` will always be + // zero which means only one sample is needed. + let zone = unsigned_max - ints_to_reject; + + UniformInt { + low: low, + // These are really $unsigned values, but store as $ty: + range: range.cast(), + zone: zone.cast(), + } + } + + fn sample(&self, rng: &mut R) -> Self::X { + let range: $unsigned = self.range.cast(); + let zone: $unsigned = self.zone.cast(); + + // This might seem very slow, generating a whole new + // SIMD vector for every sample rejection. For most uses + // though, the chance of rejection is small and provides good + // general performance. With multiple lanes, that chance is + // multiplied. To mitigate this, we replace only the lanes of + // the vector which fail, iteratively reducing the chance of + // rejection. The replacement method does however add a little + // overhead. Benchmarking or calculating probabilities might + // reveal contexts where this replacement method is slower. + let mut v: $unsigned = rng.gen(); + loop { + let (hi, lo) = v.wmul(range); + let mask = lo.le(zone); + if mask.all() { + let hi: $ty = hi.cast(); + // wrapping addition + let result = self.low + hi; + // `select` here compiles to a blend operation + // When `range.eq(0).none()` the compare and blend + // operations are avoided. + let v: $ty = v.cast(); + return range.gt($unsigned::splat(0)).select(result, v); + } + // Replace only the failing lanes + v = mask.select(v, rng.gen()); + } + } + } + }; + + // bulk implementation + ($(($unsigned:ident, $signed:ident),)+ $u_scalar:ident) => { + $( + uniform_simd_int_impl!($unsigned, $unsigned, $u_scalar); + uniform_simd_int_impl!($signed, $unsigned, $u_scalar); + )+ + }; +} + +#[cfg(all(feature = "simd_support", feature = "nightly"))] +uniform_simd_int_impl! { + (u64x2, i64x2), + (u64x4, i64x4), + (u64x8, i64x8), + u64 +} + +#[cfg(all(feature = "simd_support", feature = "nightly"))] +uniform_simd_int_impl! { + (u32x2, i32x2), + (u32x4, i32x4), + (u32x8, i32x8), + (u32x16, i32x16), + u32 +} + +#[cfg(all(feature = "simd_support", feature = "nightly"))] +uniform_simd_int_impl! { + (u16x2, i16x2), + (u16x4, i16x4), + (u16x8, i16x8), + (u16x16, i16x16), + (u16x32, i16x32), + u16 +} + +#[cfg(all(feature = "simd_support", feature = "nightly"))] +uniform_simd_int_impl! { + (u8x2, i8x2), + (u8x4, i8x4), + (u8x8, i8x8), + (u8x16, i8x16), + (u8x32, i8x32), + (u8x64, i8x64), + u8 +} + + +/// The back-end implementing [`UniformSampler`] for floating-point types. +/// +/// Unless you are implementing [`UniformSampler`] for your own type, this type +/// should not be used directly, use [`Uniform`] instead. +/// +/// # Implementation notes +/// +/// Instead of generating a float in the `[0, 1)` range using [`Standard`], the +/// `UniformFloat` implementation converts the output of an PRNG itself. This +/// way one or two steps can be optimized out. +/// +/// The floats are first converted to a value in the `[1, 2)` interval using a +/// transmute-based method, and then mapped to the expected range with a +/// multiply and addition. Values produced this way have what equals 22 bits of +/// random digits for an `f32`, and 52 for an `f64`. +/// +/// [`new`]: UniformSampler::new +/// [`new_inclusive`]: UniformSampler::new_inclusive +/// [`Standard`]: crate::distributions::Standard +#[derive(Clone, Copy, Debug)] +pub struct UniformFloat { + low: X, + scale: X, +} + +macro_rules! uniform_float_impl { + ($ty:ty, $uty:ident, $f_scalar:ident, $u_scalar:ident, $bits_to_discard:expr) => { + impl SampleUniform for $ty { + type Sampler = UniformFloat<$ty>; + } + + impl UniformSampler for UniformFloat<$ty> { + type X = $ty; + + fn new(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low.all_lt(high), + "Uniform::new called with `low >= high`"); + assert!(low.all_finite() && high.all_finite(), + "Uniform::new called with non-finite boundaries"); + let max_rand = <$ty>::splat((::core::$u_scalar::MAX >> $bits_to_discard) + .into_float_with_exponent(0) - 1.0); + + let mut scale = high - low; + + loop { + let mask = (scale * max_rand + low).ge_mask(high); + if mask.none() { + break; + } + scale = scale.decrease_masked(mask); + } + + debug_assert!(<$ty>::splat(0.0).all_le(scale)); + + UniformFloat { low, scale } + } + + fn new_inclusive(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low.all_le(high), + "Uniform::new_inclusive called with `low > high`"); + assert!(low.all_finite() && high.all_finite(), + "Uniform::new_inclusive called with non-finite boundaries"); + let max_rand = <$ty>::splat((::core::$u_scalar::MAX >> $bits_to_discard) + .into_float_with_exponent(0) - 1.0); + + let mut scale = (high - low) / max_rand; + + loop { + let mask = (scale * max_rand + low).gt_mask(high); + if mask.none() { + break; + } + scale = scale.decrease_masked(mask); + } + + debug_assert!(<$ty>::splat(0.0).all_le(scale)); + + UniformFloat { low, scale } + } + + fn sample(&self, rng: &mut R) -> Self::X { + // Generate a value in the range [1, 2) + let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard) + .into_float_with_exponent(0); + + // Get a value in the range [0, 1) in order to avoid + // overflowing into infinity when multiplying with scale + let value0_1 = value1_2 - 1.0; + + // We don't use `f64::mul_add`, because it is not available with + // `no_std`. Furthermore, it is slower for some targets (but + // faster for others). However, the order of multiplication and + // addition is important, because on some platforms (e.g. ARM) + // it will be optimized to a single (non-FMA) instruction. + value0_1 * self.scale + self.low + } + + #[inline] + fn sample_single(low_b: B1, high_b: B2, rng: &mut R) + -> Self::X + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low.all_lt(high), + "Uniform::sample_single called with low >= high"); + let mut scale = high - low; + + loop { + // Generate a value in the range [1, 2) + let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard) + .into_float_with_exponent(0); + + // Get a value in the range [0, 1) in order to avoid + // overflowing into infinity when multiplying with scale + let value0_1 = value1_2 - 1.0; + + // Doing multiply before addition allows some architectures + // to use a single instruction. + let res = value0_1 * scale + low; + + debug_assert!(low.all_le(res) || !scale.all_finite()); + if res.all_lt(high) { + return res; + } + + // This handles a number of edge cases. + // * `low` or `high` is NaN. In this case `scale` and + // `res` are going to end up as NaN. + // * `low` is negative infinity and `high` is finite. + // `scale` is going to be infinite and `res` will be + // NaN. + // * `high` is positive infinity and `low` is finite. + // `scale` is going to be infinite and `res` will + // be infinite or NaN (if value0_1 is 0). + // * `low` is negative infinity and `high` is positive + // infinity. `scale` will be infinite and `res` will + // be NaN. + // * `low` and `high` are finite, but `high - low` + // overflows to infinite. `scale` will be infinite + // and `res` will be infinite or NaN (if value0_1 is 0). + // So if `high` or `low` are non-finite, we are guaranteed + // to fail the `res < high` check above and end up here. + // + // While we technically should check for non-finite `low` + // and `high` before entering the loop, by doing the checks + // here instead, we allow the common case to avoid these + // checks. But we are still guaranteed that if `low` or + // `high` are non-finite we'll end up here and can do the + // appropriate checks. + // + // Likewise `high - low` overflowing to infinity is also + // rare, so handle it here after the common case. + let mask = !scale.finite_mask(); + if mask.any() { + assert!(low.all_finite() && high.all_finite(), + "Uniform::sample_single called with non-finite boundaries"); + scale = scale.decrease_masked(mask); + } + } + } + } + } +} + +uniform_float_impl! { f32, u32, f32, u32, 32 - 23 } +uniform_float_impl! { f64, u64, f64, u64, 64 - 52 } + +#[cfg(feature="simd_support")] +uniform_float_impl! { f32x2, u32x2, f32, u32, 32 - 23 } +#[cfg(feature="simd_support")] +uniform_float_impl! { f32x4, u32x4, f32, u32, 32 - 23 } +#[cfg(feature="simd_support")] +uniform_float_impl! { f32x8, u32x8, f32, u32, 32 - 23 } +#[cfg(feature="simd_support")] +uniform_float_impl! { f32x16, u32x16, f32, u32, 32 - 23 } + +#[cfg(feature="simd_support")] +uniform_float_impl! { f64x2, u64x2, f64, u64, 64 - 52 } +#[cfg(feature="simd_support")] +uniform_float_impl! { f64x4, u64x4, f64, u64, 64 - 52 } +#[cfg(feature="simd_support")] +uniform_float_impl! { f64x8, u64x8, f64, u64, 64 - 52 } + + + +/// The back-end implementing [`UniformSampler`] for `Duration`. +/// +/// Unless you are implementing [`UniformSampler`] for your own types, this type +/// should not be used directly, use [`Uniform`] instead. +#[cfg(any(feature = "std", rustc_1_25))] +#[derive(Clone, Copy, Debug)] +pub struct UniformDuration { + mode: UniformDurationMode, + offset: u32, +} + +#[cfg(any(feature = "std", rustc_1_25))] +#[derive(Debug, Copy, Clone)] +enum UniformDurationMode { + Small { + secs: u64, + nanos: Uniform, + }, + Medium { + nanos: Uniform, + }, + Large { + max_secs: u64, + max_nanos: u32, + secs: Uniform, + } +} + +#[cfg(any(feature = "std", rustc_1_25))] +impl SampleUniform for Duration { + type Sampler = UniformDuration; +} + +#[cfg(any(feature = "std", rustc_1_25))] +impl UniformSampler for UniformDuration { + type X = Duration; + + #[inline] + fn new(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low < high, "Uniform::new called with `low >= high`"); + UniformDuration::new_inclusive(low, high - Duration::new(0, 1)) + } + + #[inline] + fn new_inclusive(low_b: B1, high_b: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + let low = *low_b.borrow(); + let high = *high_b.borrow(); + assert!(low <= high, "Uniform::new_inclusive called with `low > high`"); + + let low_s = low.as_secs(); + let low_n = low.subsec_nanos(); + let mut high_s = high.as_secs(); + let mut high_n = high.subsec_nanos(); + + if high_n < low_n { + high_s = high_s - 1; + high_n = high_n + 1_000_000_000; + } + + let mode = if low_s == high_s { + UniformDurationMode::Small { + secs: low_s, + nanos: Uniform::new_inclusive(low_n, high_n), + } + } else { + let max = high_s + .checked_mul(1_000_000_000) + .and_then(|n| n.checked_add(high_n as u64)); + + if let Some(higher_bound) = max { + let lower_bound = low_s * 1_000_000_000 + low_n as u64; + UniformDurationMode::Medium { + nanos: Uniform::new_inclusive(lower_bound, higher_bound), + } + } else { + // An offset is applied to simplify generation of nanoseconds + let max_nanos = high_n - low_n; + UniformDurationMode::Large { + max_secs: high_s, + max_nanos, + secs: Uniform::new_inclusive(low_s, high_s), + } + } + }; + UniformDuration { + mode, + offset: low_n, + } + } + + #[inline] + fn sample(&self, rng: &mut R) -> Duration { + match self.mode { + UniformDurationMode::Small { secs, nanos } => { + let n = nanos.sample(rng); + Duration::new(secs, n) + } + UniformDurationMode::Medium { nanos } => { + let nanos = nanos.sample(rng); + Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32) + } + UniformDurationMode::Large { max_secs, max_nanos, secs } => { + // constant folding means this is at least as fast as `gen_range` + let nano_range = Uniform::new(0, 1_000_000_000); + loop { + let s = secs.sample(rng); + let n = nano_range.sample(rng); + if !(s == max_secs && n > max_nanos) { + let sum = n + self.offset; + break Duration::new(s, sum); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use Rng; + use rngs::mock::StepRng; + use distributions::uniform::Uniform; + use distributions::utils::FloatAsSIMD; + #[cfg(feature="simd_support")] use packed_simd::*; + + #[should_panic] + #[test] + fn test_uniform_bad_limits_equal_int() { + Uniform::new(10, 10); + } + + #[test] + fn test_uniform_good_limits_equal_int() { + let mut rng = ::test::rng(804); + let dist = Uniform::new_inclusive(10, 10); + for _ in 0..20 { + assert_eq!(rng.sample(dist), 10); + } + } + + #[should_panic] + #[test] + fn test_uniform_bad_limits_flipped_int() { + Uniform::new(10, 5); + } + + #[test] + fn test_integers() { + use core::{i8, i16, i32, i64, isize}; + use core::{u8, u16, u32, u64, usize}; + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + use core::{i128, u128}; + + let mut rng = ::test::rng(251); + macro_rules! t { + ($ty:ident, $v:expr, $le:expr, $lt:expr) => {{ + for &(low, high) in $v.iter() { + let my_uniform = Uniform::new(low, high); + for _ in 0..1000 { + let v: $ty = rng.sample(my_uniform); + assert!($le(low, v) && $lt(v, high)); + } + + let my_uniform = Uniform::new_inclusive(low, high); + for _ in 0..1000 { + let v: $ty = rng.sample(my_uniform); + assert!($le(low, v) && $le(v, high)); + } + + let my_uniform = Uniform::new(&low, high); + for _ in 0..1000 { + let v: $ty = rng.sample(my_uniform); + assert!($le(low, v) && $lt(v, high)); + } + + let my_uniform = Uniform::new_inclusive(&low, &high); + for _ in 0..1000 { + let v: $ty = rng.sample(my_uniform); + assert!($le(low, v) && $le(v, high)); + } + + for _ in 0..1000 { + let v: $ty = rng.gen_range(low, high); + assert!($le(low, v) && $lt(v, high)); + } + } + }}; + + // scalar bulk + ($($ty:ident),*) => {{ + $(t!( + $ty, + [(0, 10), (10, 127), ($ty::MIN, $ty::MAX)], + |x, y| x <= y, + |x, y| x < y + );)* + }}; + + // simd bulk + ($($ty:ident),* => $scalar:ident) => {{ + $(t!( + $ty, + [ + ($ty::splat(0), $ty::splat(10)), + ($ty::splat(10), $ty::splat(127)), + ($ty::splat($scalar::MIN), $ty::splat($scalar::MAX)), + ], + |x: $ty, y| x.le(y).all(), + |x: $ty, y| x.lt(y).all() + );)* + }}; + } + t!(i8, i16, i32, i64, isize, + u8, u16, u32, u64, usize); + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + t!(i128, u128); + + #[cfg(all(feature = "simd_support", feature = "nightly"))] + { + t!(u8x2, u8x4, u8x8, u8x16, u8x32, u8x64 => u8); + t!(i8x2, i8x4, i8x8, i8x16, i8x32, i8x64 => i8); + t!(u16x2, u16x4, u16x8, u16x16, u16x32 => u16); + t!(i16x2, i16x4, i16x8, i16x16, i16x32 => i16); + t!(u32x2, u32x4, u32x8, u32x16 => u32); + t!(i32x2, i32x4, i32x8, i32x16 => i32); + t!(u64x2, u64x4, u64x8 => u64); + t!(i64x2, i64x4, i64x8 => i64); + } + } + + #[test] + fn test_floats() { + let mut rng = ::test::rng(252); + let mut zero_rng = StepRng::new(0, 0); + let mut max_rng = StepRng::new(0xffff_ffff_ffff_ffff, 0); + macro_rules! t { + ($ty:ty, $f_scalar:ident, $bits_shifted:expr) => {{ + let v: &[($f_scalar, $f_scalar)]= + &[(0.0, 100.0), + (-1e35, -1e25), + (1e-35, 1e-25), + (-1e35, 1e35), + (<$f_scalar>::from_bits(0), <$f_scalar>::from_bits(3)), + (-<$f_scalar>::from_bits(10), -<$f_scalar>::from_bits(1)), + (-<$f_scalar>::from_bits(5), 0.0), + (-<$f_scalar>::from_bits(7), -0.0), + (10.0, ::core::$f_scalar::MAX), + (-100.0, ::core::$f_scalar::MAX), + (-::core::$f_scalar::MAX / 5.0, ::core::$f_scalar::MAX), + (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX / 5.0), + (-::core::$f_scalar::MAX * 0.8, ::core::$f_scalar::MAX * 0.7), + (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX), + ]; + for &(low_scalar, high_scalar) in v.iter() { + for lane in 0..<$ty>::lanes() { + let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar); + let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar); + let my_uniform = Uniform::new(low, high); + let my_incl_uniform = Uniform::new_inclusive(low, high); + for _ in 0..100 { + let v = rng.sample(my_uniform).extract(lane); + assert!(low_scalar <= v && v < high_scalar); + let v = rng.sample(my_incl_uniform).extract(lane); + assert!(low_scalar <= v && v <= high_scalar); + let v = rng.gen_range(low, high).extract(lane); + assert!(low_scalar <= v && v < high_scalar); + } + + assert_eq!(rng.sample(Uniform::new_inclusive(low, low)).extract(lane), low_scalar); + + assert_eq!(zero_rng.sample(my_uniform).extract(lane), low_scalar); + assert_eq!(zero_rng.sample(my_incl_uniform).extract(lane), low_scalar); + assert_eq!(zero_rng.gen_range(low, high).extract(lane), low_scalar); + assert!(max_rng.sample(my_uniform).extract(lane) < high_scalar); + assert!(max_rng.sample(my_incl_uniform).extract(lane) <= high_scalar); + + // Don't run this test for really tiny differences between high and low + // since for those rounding might result in selecting high for a very + // long time. + if (high_scalar - low_scalar) > 0.0001 { + let mut lowering_max_rng = + StepRng::new(0xffff_ffff_ffff_ffff, + (-1i64 << $bits_shifted) as u64); + assert!(lowering_max_rng.gen_range(low, high).extract(lane) < high_scalar); + } + } + } + + assert_eq!(rng.sample(Uniform::new_inclusive(::core::$f_scalar::MAX, + ::core::$f_scalar::MAX)), + ::core::$f_scalar::MAX); + assert_eq!(rng.sample(Uniform::new_inclusive(-::core::$f_scalar::MAX, + -::core::$f_scalar::MAX)), + -::core::$f_scalar::MAX); + }} + } + + t!(f32, f32, 32 - 23); + t!(f64, f64, 64 - 52); + #[cfg(feature="simd_support")] + { + t!(f32x2, f32, 32 - 23); + t!(f32x4, f32, 32 - 23); + t!(f32x8, f32, 32 - 23); + t!(f32x16, f32, 32 - 23); + t!(f64x2, f64, 64 - 52); + t!(f64x4, f64, 64 - 52); + t!(f64x8, f64, 64 - 52); + } + } + + #[test] + #[cfg(all(feature="std", + not(target_arch = "wasm32"), + not(target_arch = "asmjs")))] + fn test_float_assertions() { + use std::panic::catch_unwind; + use super::SampleUniform; + fn range(low: T, high: T) { + let mut rng = ::test::rng(253); + rng.gen_range(low, high); + } + + macro_rules! t { + ($ty:ident, $f_scalar:ident) => {{ + let v: &[($f_scalar, $f_scalar)] = + &[(::std::$f_scalar::NAN, 0.0), + (1.0, ::std::$f_scalar::NAN), + (::std::$f_scalar::NAN, ::std::$f_scalar::NAN), + (1.0, 0.5), + (::std::$f_scalar::MAX, -::std::$f_scalar::MAX), + (::std::$f_scalar::INFINITY, ::std::$f_scalar::INFINITY), + (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NEG_INFINITY), + (::std::$f_scalar::NEG_INFINITY, 5.0), + (5.0, ::std::$f_scalar::INFINITY), + (::std::$f_scalar::NAN, ::std::$f_scalar::INFINITY), + (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NAN), + (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::INFINITY), + ]; + for &(low_scalar, high_scalar) in v.iter() { + for lane in 0..<$ty>::lanes() { + let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar); + let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar); + assert!(catch_unwind(|| range(low, high)).is_err()); + assert!(catch_unwind(|| Uniform::new(low, high)).is_err()); + assert!(catch_unwind(|| Uniform::new_inclusive(low, high)).is_err()); + assert!(catch_unwind(|| range(low, low)).is_err()); + assert!(catch_unwind(|| Uniform::new(low, low)).is_err()); + } + } + }} + } + + t!(f32, f32); + t!(f64, f64); + #[cfg(feature="simd_support")] + { + t!(f32x2, f32); + t!(f32x4, f32); + t!(f32x8, f32); + t!(f32x16, f32); + t!(f64x2, f64); + t!(f64x4, f64); + t!(f64x8, f64); + } + } + + + #[test] + #[cfg(any(feature = "std", rustc_1_25))] + fn test_durations() { + #[cfg(feature = "std")] + use std::time::Duration; + #[cfg(all(not(feature = "std"), rustc_1_25))] + use core::time::Duration; + + let mut rng = ::test::rng(253); + + let v = &[(Duration::new(10, 50000), Duration::new(100, 1234)), + (Duration::new(0, 100), Duration::new(1, 50)), + (Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999))]; + for &(low, high) in v.iter() { + let my_uniform = Uniform::new(low, high); + for _ in 0..1000 { + let v = rng.sample(my_uniform); + assert!(low <= v && v < high); + } + } + } + + #[test] + fn test_custom_uniform() { + use distributions::uniform::{UniformSampler, UniformFloat, SampleUniform, SampleBorrow}; + #[derive(Clone, Copy, PartialEq, PartialOrd)] + struct MyF32 { + x: f32, + } + #[derive(Clone, Copy, Debug)] + struct UniformMyF32 { + inner: UniformFloat, + } + impl UniformSampler for UniformMyF32 { + type X = MyF32; + fn new(low: B1, high: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + UniformMyF32 { + inner: UniformFloat::::new(low.borrow().x, high.borrow().x), + } + } + fn new_inclusive(low: B1, high: B2) -> Self + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized + { + UniformSampler::new(low, high) + } + fn sample(&self, rng: &mut R) -> Self::X { + MyF32 { x: self.inner.sample(rng) } + } + } + impl SampleUniform for MyF32 { + type Sampler = UniformMyF32; + } + + let (low, high) = (MyF32{ x: 17.0f32 }, MyF32{ x: 22.0f32 }); + let uniform = Uniform::new(low, high); + let mut rng = ::test::rng(804); + for _ in 0..100 { + let x: MyF32 = rng.sample(uniform); + assert!(low <= x && x < high); + } + } + + #[test] + fn test_uniform_from_std_range() { + let r = Uniform::from(2u32..7); + assert_eq!(r.inner.low, 2); + assert_eq!(r.inner.range, 5); + let r = Uniform::from(2.0f64..7.0); + assert_eq!(r.inner.low, 2.0); + assert_eq!(r.inner.scale, 5.0); + } + + #[cfg(rustc_1_27)] + #[test] + fn test_uniform_from_std_range_inclusive() { + let r = Uniform::from(2u32..=6); + assert_eq!(r.inner.low, 2); + assert_eq!(r.inner.range, 5); + let r = Uniform::from(2.0f64..=7.0); + assert_eq!(r.inner.low, 2.0); + assert!(r.inner.scale > 5.0); + assert!(r.inner.scale < 5.0 + 1e-14); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/unit_circle.rs b/bash-5.1/vendor/rand/src/distributions/unit_circle.rs new file mode 100644 index 0000000..01ab76a --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/unit_circle.rs @@ -0,0 +1,101 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use Rng; +use distributions::{Distribution, Uniform}; + +/// Samples uniformly from the edge of the unit circle in two dimensions. +/// +/// Implemented via a method by von Neumann[^1]. +/// +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{UnitCircle, Distribution}; +/// +/// let circle = UnitCircle::new(); +/// let v = circle.sample(&mut rand::thread_rng()); +/// println!("{:?} is from the unit circle.", v) +/// ``` +/// +/// [^1]: von Neumann, J. (1951) [*Various Techniques Used in Connection with +/// Random Digits.*](https://mcnp.lanl.gov/pdf_files/nbs_vonneumann.pdf) +/// NBS Appl. Math. Ser., No. 12. Washington, DC: U.S. Government Printing +/// Office, pp. 36-38. +#[derive(Clone, Copy, Debug)] +pub struct UnitCircle; + +impl UnitCircle { + /// Construct a new `UnitCircle` distribution. + #[inline] + pub fn new() -> UnitCircle { + UnitCircle + } +} + +impl Distribution<[f64; 2]> for UnitCircle { + #[inline] + fn sample(&self, rng: &mut R) -> [f64; 2] { + let uniform = Uniform::new(-1., 1.); + let mut x1; + let mut x2; + let mut sum; + loop { + x1 = uniform.sample(rng); + x2 = uniform.sample(rng); + sum = x1*x1 + x2*x2; + if sum < 1. { + break; + } + } + let diff = x1*x1 - x2*x2; + [diff / sum, 2.*x1*x2 / sum] + } +} + +#[cfg(test)] +mod tests { + use distributions::Distribution; + use super::UnitCircle; + + /// Assert that two numbers are almost equal to each other. + /// + /// On panic, this macro will print the values of the expressions with their + /// debug representations. + macro_rules! assert_almost_eq { + ($a:expr, $b:expr, $prec:expr) => ( + let diff = ($a - $b).abs(); + if diff > $prec { + panic!(format!( + "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ + (left: `{}`, right: `{}`)", + diff, $prec, $a, $b)); + } + ); + } + + #[test] + fn norm() { + let mut rng = ::test::rng(1); + let dist = UnitCircle::new(); + for _ in 0..1000 { + let x = dist.sample(&mut rng); + assert_almost_eq!(x[0]*x[0] + x[1]*x[1], 1., 1e-15); + } + } + + #[test] + fn value_stability() { + let mut rng = ::test::rng(2); + let dist = UnitCircle::new(); + assert_eq!(dist.sample(&mut rng), [-0.8032118336637037, 0.5956935036263119]); + assert_eq!(dist.sample(&mut rng), [-0.4742919588505423, -0.880367615130018]); + assert_eq!(dist.sample(&mut rng), [0.9297328981467168, 0.368234623716601]); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/unit_sphere.rs b/bash-5.1/vendor/rand/src/distributions/unit_sphere.rs new file mode 100644 index 0000000..37de88b --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/unit_sphere.rs @@ -0,0 +1,99 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use Rng; +use distributions::{Distribution, Uniform}; + +/// Samples uniformly from the surface of the unit sphere in three dimensions. +/// +/// Implemented via a method by Marsaglia[^1]. +/// +/// +/// # Example +/// +/// ``` +/// use rand::distributions::{UnitSphereSurface, Distribution}; +/// +/// let sphere = UnitSphereSurface::new(); +/// let v = sphere.sample(&mut rand::thread_rng()); +/// println!("{:?} is from the unit sphere surface.", v) +/// ``` +/// +/// [^1]: Marsaglia, George (1972). [*Choosing a Point from the Surface of a +/// Sphere.*](https://doi.org/10.1214/aoms/1177692644) +/// Ann. Math. Statist. 43, no. 2, 645--646. +#[derive(Clone, Copy, Debug)] +pub struct UnitSphereSurface; + +impl UnitSphereSurface { + /// Construct a new `UnitSphereSurface` distribution. + #[inline] + pub fn new() -> UnitSphereSurface { + UnitSphereSurface + } +} + +impl Distribution<[f64; 3]> for UnitSphereSurface { + #[inline] + fn sample(&self, rng: &mut R) -> [f64; 3] { + let uniform = Uniform::new(-1., 1.); + loop { + let (x1, x2) = (uniform.sample(rng), uniform.sample(rng)); + let sum = x1*x1 + x2*x2; + if sum >= 1. { + continue; + } + let factor = 2. * (1.0_f64 - sum).sqrt(); + return [x1 * factor, x2 * factor, 1. - 2.*sum]; + } + } +} + +#[cfg(test)] +mod tests { + use distributions::Distribution; + use super::UnitSphereSurface; + + /// Assert that two numbers are almost equal to each other. + /// + /// On panic, this macro will print the values of the expressions with their + /// debug representations. + macro_rules! assert_almost_eq { + ($a:expr, $b:expr, $prec:expr) => ( + let diff = ($a - $b).abs(); + if diff > $prec { + panic!(format!( + "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ + (left: `{}`, right: `{}`)", + diff, $prec, $a, $b)); + } + ); + } + + #[test] + fn norm() { + let mut rng = ::test::rng(1); + let dist = UnitSphereSurface::new(); + for _ in 0..1000 { + let x = dist.sample(&mut rng); + assert_almost_eq!(x[0]*x[0] + x[1]*x[1] + x[2]*x[2], 1., 1e-15); + } + } + + #[test] + fn value_stability() { + let mut rng = ::test::rng(2); + let dist = UnitSphereSurface::new(); + assert_eq!(dist.sample(&mut rng), + [-0.24950027180862533, -0.7552572587896719, 0.6060825747478084]); + assert_eq!(dist.sample(&mut rng), + [0.47604534507233487, -0.797200864987207, -0.3712837328763685]); + assert_eq!(dist.sample(&mut rng), + [0.9795722330927367, 0.18692349236651176, 0.07414747571708524]); + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/utils.rs b/bash-5.1/vendor/rand/src/distributions/utils.rs new file mode 100644 index 0000000..d4d3642 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/utils.rs @@ -0,0 +1,504 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Math helper functions + +#[cfg(feature="simd_support")] +use packed_simd::*; +#[cfg(feature="std")] +use distributions::ziggurat_tables; +#[cfg(feature="std")] +use Rng; + + +pub trait WideningMultiply { + type Output; + + fn wmul(self, x: RHS) -> Self::Output; +} + +macro_rules! wmul_impl { + ($ty:ty, $wide:ty, $shift:expr) => { + impl WideningMultiply for $ty { + type Output = ($ty, $ty); + + #[inline(always)] + fn wmul(self, x: $ty) -> Self::Output { + let tmp = (self as $wide) * (x as $wide); + ((tmp >> $shift) as $ty, tmp as $ty) + } + } + }; + + // simd bulk implementation + ($(($ty:ident, $wide:ident),)+, $shift:expr) => { + $( + impl WideningMultiply for $ty { + type Output = ($ty, $ty); + + #[inline(always)] + fn wmul(self, x: $ty) -> Self::Output { + // For supported vectors, this should compile to a couple + // supported multiply & swizzle instructions (no actual + // casting). + // TODO: optimize + let y: $wide = self.cast(); + let x: $wide = x.cast(); + let tmp = y * x; + let hi: $ty = (tmp >> $shift).cast(); + let lo: $ty = tmp.cast(); + (hi, lo) + } + } + )+ + }; +} +wmul_impl! { u8, u16, 8 } +wmul_impl! { u16, u32, 16 } +wmul_impl! { u32, u64, 32 } +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] +wmul_impl! { u64, u128, 64 } + +// This code is a translation of the __mulddi3 function in LLVM's +// compiler-rt. It is an optimised variant of the common method +// `(a + b) * (c + d) = ac + ad + bc + bd`. +// +// For some reason LLVM can optimise the C version very well, but +// keeps shuffling registers in this Rust translation. +macro_rules! wmul_impl_large { + ($ty:ty, $half:expr) => { + impl WideningMultiply for $ty { + type Output = ($ty, $ty); + + #[inline(always)] + fn wmul(self, b: $ty) -> Self::Output { + const LOWER_MASK: $ty = !0 >> $half; + let mut low = (self & LOWER_MASK).wrapping_mul(b & LOWER_MASK); + let mut t = low >> $half; + low &= LOWER_MASK; + t += (self >> $half).wrapping_mul(b & LOWER_MASK); + low += (t & LOWER_MASK) << $half; + let mut high = t >> $half; + t = low >> $half; + low &= LOWER_MASK; + t += (b >> $half).wrapping_mul(self & LOWER_MASK); + low += (t & LOWER_MASK) << $half; + high += t >> $half; + high += (self >> $half).wrapping_mul(b >> $half); + + (high, low) + } + } + }; + + // simd bulk implementation + (($($ty:ty,)+) $scalar:ty, $half:expr) => { + $( + impl WideningMultiply for $ty { + type Output = ($ty, $ty); + + #[inline(always)] + fn wmul(self, b: $ty) -> Self::Output { + // needs wrapping multiplication + const LOWER_MASK: $scalar = !0 >> $half; + let mut low = (self & LOWER_MASK) * (b & LOWER_MASK); + let mut t = low >> $half; + low &= LOWER_MASK; + t += (self >> $half) * (b & LOWER_MASK); + low += (t & LOWER_MASK) << $half; + let mut high = t >> $half; + t = low >> $half; + low &= LOWER_MASK; + t += (b >> $half) * (self & LOWER_MASK); + low += (t & LOWER_MASK) << $half; + high += t >> $half; + high += (self >> $half) * (b >> $half); + + (high, low) + } + } + )+ + }; +} +#[cfg(not(all(rustc_1_26, not(target_os = "emscripten"))))] +wmul_impl_large! { u64, 32 } +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] +wmul_impl_large! { u128, 64 } + +macro_rules! wmul_impl_usize { + ($ty:ty) => { + impl WideningMultiply for usize { + type Output = (usize, usize); + + #[inline(always)] + fn wmul(self, x: usize) -> Self::Output { + let (high, low) = (self as $ty).wmul(x as $ty); + (high as usize, low as usize) + } + } + } +} +#[cfg(target_pointer_width = "32")] +wmul_impl_usize! { u32 } +#[cfg(target_pointer_width = "64")] +wmul_impl_usize! { u64 } + +#[cfg(all(feature = "simd_support", feature = "nightly"))] +mod simd_wmul { + #[cfg(target_arch = "x86")] + use core::arch::x86::*; + #[cfg(target_arch = "x86_64")] + use core::arch::x86_64::*; + use super::*; + + wmul_impl! { + (u8x2, u16x2), + (u8x4, u16x4), + (u8x8, u16x8), + (u8x16, u16x16), + (u8x32, u16x32),, + 8 + } + + wmul_impl! { (u16x2, u32x2),, 16 } + #[cfg(not(target_feature = "sse2"))] + wmul_impl! { (u16x4, u32x4),, 16 } + #[cfg(not(target_feature = "sse4.2"))] + wmul_impl! { (u16x8, u32x8),, 16 } + #[cfg(not(target_feature = "avx2"))] + wmul_impl! { (u16x16, u32x16),, 16 } + + // 16-bit lane widths allow use of the x86 `mulhi` instructions, which + // means `wmul` can be implemented with only two instructions. + #[allow(unused_macros)] + macro_rules! wmul_impl_16 { + ($ty:ident, $intrinsic:ident, $mulhi:ident, $mullo:ident) => { + impl WideningMultiply for $ty { + type Output = ($ty, $ty); + + #[inline(always)] + fn wmul(self, x: $ty) -> Self::Output { + let b = $intrinsic::from_bits(x); + let a = $intrinsic::from_bits(self); + let hi = $ty::from_bits(unsafe { $mulhi(a, b) }); + let lo = $ty::from_bits(unsafe { $mullo(a, b) }); + (hi, lo) + } + } + }; + } + + #[cfg(target_feature = "sse2")] + wmul_impl_16! { u16x4, __m64, _mm_mulhi_pu16, _mm_mullo_pi16 } + #[cfg(target_feature = "sse4.2")] + wmul_impl_16! { u16x8, __m128i, _mm_mulhi_epu16, _mm_mullo_epi16 } + #[cfg(target_feature = "avx2")] + wmul_impl_16! { u16x16, __m256i, _mm256_mulhi_epu16, _mm256_mullo_epi16 } + // FIXME: there are no `__m512i` types in stdsimd yet, so `wmul::` + // cannot use the same implementation. + + wmul_impl! { + (u32x2, u64x2), + (u32x4, u64x4), + (u32x8, u64x8),, + 32 + } + + // TODO: optimize, this seems to seriously slow things down + wmul_impl_large! { (u8x64,) u8, 4 } + wmul_impl_large! { (u16x32,) u16, 8 } + wmul_impl_large! { (u32x16,) u32, 16 } + wmul_impl_large! { (u64x2, u64x4, u64x8,) u64, 32 } +} +#[cfg(all(feature = "simd_support", feature = "nightly"))] +pub use self::simd_wmul::*; + + +/// Helper trait when dealing with scalar and SIMD floating point types. +pub(crate) trait FloatSIMDUtils { + // `PartialOrd` for vectors compares lexicographically. We want to compare all + // the individual SIMD lanes instead, and get the combined result over all + // lanes. This is possible using something like `a.lt(b).all()`, but we + // implement it as a trait so we can write the same code for `f32` and `f64`. + // Only the comparison functions we need are implemented. + fn all_lt(self, other: Self) -> bool; + fn all_le(self, other: Self) -> bool; + fn all_finite(self) -> bool; + + type Mask; + fn finite_mask(self) -> Self::Mask; + fn gt_mask(self, other: Self) -> Self::Mask; + fn ge_mask(self, other: Self) -> Self::Mask; + + // Decrease all lanes where the mask is `true` to the next lower value + // representable by the floating-point type. At least one of the lanes + // must be set. + fn decrease_masked(self, mask: Self::Mask) -> Self; + + // Convert from int value. Conversion is done while retaining the numerical + // value, not by retaining the binary representation. + type UInt; + fn cast_from_int(i: Self::UInt) -> Self; +} + +/// Implement functions available in std builds but missing from core primitives +#[cfg(not(std))] +pub(crate) trait Float : Sized { + type Bits; + + fn is_nan(self) -> bool; + fn is_infinite(self) -> bool; + fn is_finite(self) -> bool; + fn to_bits(self) -> Self::Bits; + fn from_bits(v: Self::Bits) -> Self; +} + +/// Implement functions on f32/f64 to give them APIs similar to SIMD types +pub(crate) trait FloatAsSIMD : Sized { + #[inline(always)] + fn lanes() -> usize { 1 } + #[inline(always)] + fn splat(scalar: Self) -> Self { scalar } + #[inline(always)] + fn extract(self, index: usize) -> Self { debug_assert_eq!(index, 0); self } + #[inline(always)] + fn replace(self, index: usize, new_value: Self) -> Self { debug_assert_eq!(index, 0); new_value } +} + +pub(crate) trait BoolAsSIMD : Sized { + fn any(self) -> bool; + fn all(self) -> bool; + fn none(self) -> bool; +} + +impl BoolAsSIMD for bool { + #[inline(always)] + fn any(self) -> bool { self } + #[inline(always)] + fn all(self) -> bool { self } + #[inline(always)] + fn none(self) -> bool { !self } +} + +macro_rules! scalar_float_impl { + ($ty:ident, $uty:ident) => { + #[cfg(not(std))] + impl Float for $ty { + type Bits = $uty; + + #[inline] + fn is_nan(self) -> bool { + self != self + } + + #[inline] + fn is_infinite(self) -> bool { + self == ::core::$ty::INFINITY || self == ::core::$ty::NEG_INFINITY + } + + #[inline] + fn is_finite(self) -> bool { + !(self.is_nan() || self.is_infinite()) + } + + #[inline] + fn to_bits(self) -> Self::Bits { + unsafe { ::core::mem::transmute(self) } + } + + #[inline] + fn from_bits(v: Self::Bits) -> Self { + // It turns out the safety issues with sNaN were overblown! Hooray! + unsafe { ::core::mem::transmute(v) } + } + } + + impl FloatSIMDUtils for $ty { + type Mask = bool; + #[inline(always)] + fn all_lt(self, other: Self) -> bool { self < other } + #[inline(always)] + fn all_le(self, other: Self) -> bool { self <= other } + #[inline(always)] + fn all_finite(self) -> bool { self.is_finite() } + #[inline(always)] + fn finite_mask(self) -> Self::Mask { self.is_finite() } + #[inline(always)] + fn gt_mask(self, other: Self) -> Self::Mask { self > other } + #[inline(always)] + fn ge_mask(self, other: Self) -> Self::Mask { self >= other } + #[inline(always)] + fn decrease_masked(self, mask: Self::Mask) -> Self { + debug_assert!(mask, "At least one lane must be set"); + <$ty>::from_bits(self.to_bits() - 1) + } + type UInt = $uty; + fn cast_from_int(i: Self::UInt) -> Self { i as $ty } + } + + impl FloatAsSIMD for $ty {} + } +} + +scalar_float_impl!(f32, u32); +scalar_float_impl!(f64, u64); + + +#[cfg(feature="simd_support")] +macro_rules! simd_impl { + ($ty:ident, $f_scalar:ident, $mty:ident, $uty:ident) => { + impl FloatSIMDUtils for $ty { + type Mask = $mty; + #[inline(always)] + fn all_lt(self, other: Self) -> bool { self.lt(other).all() } + #[inline(always)] + fn all_le(self, other: Self) -> bool { self.le(other).all() } + #[inline(always)] + fn all_finite(self) -> bool { self.finite_mask().all() } + #[inline(always)] + fn finite_mask(self) -> Self::Mask { + // This can possibly be done faster by checking bit patterns + let neg_inf = $ty::splat(::core::$f_scalar::NEG_INFINITY); + let pos_inf = $ty::splat(::core::$f_scalar::INFINITY); + self.gt(neg_inf) & self.lt(pos_inf) + } + #[inline(always)] + fn gt_mask(self, other: Self) -> Self::Mask { self.gt(other) } + #[inline(always)] + fn ge_mask(self, other: Self) -> Self::Mask { self.ge(other) } + #[inline(always)] + fn decrease_masked(self, mask: Self::Mask) -> Self { + // Casting a mask into ints will produce all bits set for + // true, and 0 for false. Adding that to the binary + // representation of a float means subtracting one from + // the binary representation, resulting in the next lower + // value representable by $ty. This works even when the + // current value is infinity. + debug_assert!(mask.any(), "At least one lane must be set"); + <$ty>::from_bits(<$uty>::from_bits(self) + <$uty>::from_bits(mask)) + } + type UInt = $uty; + fn cast_from_int(i: Self::UInt) -> Self { i.cast() } + } + } +} + +#[cfg(feature="simd_support")] simd_impl! { f32x2, f32, m32x2, u32x2 } +#[cfg(feature="simd_support")] simd_impl! { f32x4, f32, m32x4, u32x4 } +#[cfg(feature="simd_support")] simd_impl! { f32x8, f32, m32x8, u32x8 } +#[cfg(feature="simd_support")] simd_impl! { f32x16, f32, m32x16, u32x16 } +#[cfg(feature="simd_support")] simd_impl! { f64x2, f64, m64x2, u64x2 } +#[cfg(feature="simd_support")] simd_impl! { f64x4, f64, m64x4, u64x4 } +#[cfg(feature="simd_support")] simd_impl! { f64x8, f64, m64x8, u64x8 } + +/// Calculates ln(gamma(x)) (natural logarithm of the gamma +/// function) using the Lanczos approximation. +/// +/// The approximation expresses the gamma function as: +/// `gamma(z+1) = sqrt(2*pi)*(z+g+0.5)^(z+0.5)*exp(-z-g-0.5)*Ag(z)` +/// `g` is an arbitrary constant; we use the approximation with `g=5`. +/// +/// Noting that `gamma(z+1) = z*gamma(z)` and applying `ln` to both sides: +/// `ln(gamma(z)) = (z+0.5)*ln(z+g+0.5)-(z+g+0.5) + ln(sqrt(2*pi)*Ag(z)/z)` +/// +/// `Ag(z)` is an infinite series with coefficients that can be calculated +/// ahead of time - we use just the first 6 terms, which is good enough +/// for most purposes. +#[cfg(feature="std")] +pub fn log_gamma(x: f64) -> f64 { + // precalculated 6 coefficients for the first 6 terms of the series + let coefficients: [f64; 6] = [ + 76.18009172947146, + -86.50532032941677, + 24.01409824083091, + -1.231739572450155, + 0.1208650973866179e-2, + -0.5395239384953e-5, + ]; + + // (x+0.5)*ln(x+g+0.5)-(x+g+0.5) + let tmp = x + 5.5; + let log = (x + 0.5) * tmp.ln() - tmp; + + // the first few terms of the series for Ag(x) + let mut a = 1.000000000190015; + let mut denom = x; + for coeff in &coefficients { + denom += 1.0; + a += coeff / denom; + } + + // get everything together + // a is Ag(x) + // 2.5066... is sqrt(2pi) + log + (2.5066282746310005 * a / x).ln() +} + +/// Sample a random number using the Ziggurat method (specifically the +/// ZIGNOR variant from Doornik 2005). Most of the arguments are +/// directly from the paper: +/// +/// * `rng`: source of randomness +/// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0. +/// * `X`: the $x_i$ abscissae. +/// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$) +/// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$ +/// * `pdf`: the probability density function +/// * `zero_case`: manual sampling from the tail when we chose the +/// bottom box (i.e. i == 0) + +// the perf improvement (25-50%) is definitely worth the extra code +// size from force-inlining. +#[cfg(feature="std")] +#[inline(always)] +pub fn ziggurat( + rng: &mut R, + symmetric: bool, + x_tab: ziggurat_tables::ZigTable, + f_tab: ziggurat_tables::ZigTable, + mut pdf: P, + mut zero_case: Z) + -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 { + use distributions::float::IntoFloat; + loop { + // As an optimisation we re-implement the conversion to a f64. + // From the remaining 12 most significant bits we use 8 to construct `i`. + // This saves us generating a whole extra random number, while the added + // precision of using 64 bits for f64 does not buy us much. + let bits = rng.next_u64(); + let i = bits as usize & 0xff; + + let u = if symmetric { + // Convert to a value in the range [2,4) and substract to get [-1,1) + // We can't convert to an open range directly, that would require + // substracting `3.0 - EPSILON`, which is not representable. + // It is possible with an extra step, but an open range does not + // seem neccesary for the ziggurat algorithm anyway. + (bits >> 12).into_float_with_exponent(1) - 3.0 + } else { + // Convert to a value in the range [1,2) and substract to get (0,1) + (bits >> 12).into_float_with_exponent(0) + - (1.0 - ::core::f64::EPSILON / 2.0) + }; + let x = u * x_tab[i]; + + let test_x = if symmetric { x.abs() } else {x}; + + // algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u < x_tab[i+1]/x_tab[i]) + if test_x < x_tab[i + 1] { + return x; + } + if i == 0 { + return zero_case(rng, u); + } + // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1 + if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen::() < pdf(x) { + return x; + } + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/weibull.rs b/bash-5.1/vendor/rand/src/distributions/weibull.rs new file mode 100644 index 0000000..5fbe10a --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/weibull.rs @@ -0,0 +1,71 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Weibull distribution. + +use Rng; +use distributions::{Distribution, OpenClosed01}; + +/// Samples floating-point numbers according to the Weibull distribution +/// +/// # Example +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::Weibull; +/// +/// let val: f64 = SmallRng::from_entropy().sample(Weibull::new(1., 10.)); +/// println!("{}", val); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Weibull { + inv_shape: f64, + scale: f64, +} + +impl Weibull { + /// Construct a new `Weibull` distribution with given `scale` and `shape`. + /// + /// # Panics + /// + /// `scale` and `shape` have to be non-zero and positive. + pub fn new(scale: f64, shape: f64) -> Weibull { + assert!((scale > 0.) & (shape > 0.)); + Weibull { inv_shape: 1./shape, scale } + } +} + +impl Distribution for Weibull { + fn sample(&self, rng: &mut R) -> f64 { + let x: f64 = rng.sample(OpenClosed01); + self.scale * (-x.ln()).powf(self.inv_shape) + } +} + +#[cfg(test)] +mod tests { + use distributions::Distribution; + use super::Weibull; + + #[test] + #[should_panic] + fn invalid() { + Weibull::new(0., 0.); + } + + #[test] + fn sample() { + let scale = 1.0; + let shape = 2.0; + let d = Weibull::new(scale, shape); + let mut rng = ::test::rng(1); + for _ in 0..1000 { + let r = d.sample(&mut rng); + assert!(r >= 0.); + } + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/weighted.rs b/bash-5.1/vendor/rand/src/distributions/weighted.rs new file mode 100644 index 0000000..d749959 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/weighted.rs @@ -0,0 +1,230 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use Rng; +use distributions::Distribution; +use distributions::uniform::{UniformSampler, SampleUniform, SampleBorrow}; +use ::core::cmp::PartialOrd; +use core::fmt; + +// Note that this whole module is only imported if feature="alloc" is enabled. +#[cfg(not(feature="std"))] use alloc::vec::Vec; + +/// A distribution using weighted sampling to pick a discretely selected +/// item. +/// +/// Sampling a `WeightedIndex` distribution returns the index of a randomly +/// selected element from the iterator used when the `WeightedIndex` was +/// created. The chance of a given element being picked is proportional to the +/// value of the element. The weights can use any type `X` for which an +/// implementation of [`Uniform`] exists. +/// +/// # Performance +/// +/// A `WeightedIndex` contains a `Vec` and a [`Uniform`] and so its +/// size is the sum of the size of those objects, possibly plus some alignment. +/// +/// Creating a `WeightedIndex` will allocate enough space to hold `N - 1` +/// weights of type `X`, where `N` is the number of weights. However, since +/// `Vec` doesn't guarantee a particular growth strategy, additional memory +/// might be allocated but not used. Since the `WeightedIndex` object also +/// contains, this might cause additional allocations, though for primitive +/// types, ['Uniform`] doesn't allocate any memory. +/// +/// Time complexity of sampling from `WeightedIndex` is `O(log N)` where +/// `N` is the number of weights. +/// +/// Sampling from `WeightedIndex` will result in a single call to +/// `Uniform::sample` (method of the [`Distribution`] trait), which typically +/// will request a single value from the underlying [`RngCore`], though the +/// exact number depends on the implementaiton of `Uniform::sample`. +/// +/// # Example +/// +/// ``` +/// use rand::prelude::*; +/// use rand::distributions::WeightedIndex; +/// +/// let choices = ['a', 'b', 'c']; +/// let weights = [2, 1, 1]; +/// let dist = WeightedIndex::new(&weights).unwrap(); +/// let mut rng = thread_rng(); +/// for _ in 0..100 { +/// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' +/// println!("{}", choices[dist.sample(&mut rng)]); +/// } +/// +/// let items = [('a', 0), ('b', 3), ('c', 7)]; +/// let dist2 = WeightedIndex::new(items.iter().map(|item| item.1)).unwrap(); +/// for _ in 0..100 { +/// // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c' +/// println!("{}", items[dist2.sample(&mut rng)].0); +/// } +/// ``` +/// +/// [`Uniform`]: crate::distributions::uniform::Uniform +/// [`RngCore`]: rand_core::RngCore +#[derive(Debug, Clone)] +pub struct WeightedIndex { + cumulative_weights: Vec, + weight_distribution: X::Sampler, +} + +impl WeightedIndex { + /// Creates a new a `WeightedIndex` [`Distribution`] using the values + /// in `weights`. The weights can use any type `X` for which an + /// implementation of [`Uniform`] exists. + /// + /// Returns an error if the iterator is empty, if any weight is `< 0`, or + /// if its total value is 0. + /// + /// [`Uniform`]: crate::distributions::uniform::Uniform + pub fn new(weights: I) -> Result, WeightedError> + where I: IntoIterator, + I::Item: SampleBorrow, + X: for<'a> ::core::ops::AddAssign<&'a X> + + Clone + + Default { + let mut iter = weights.into_iter(); + let mut total_weight: X = iter.next() + .ok_or(WeightedError::NoItem)? + .borrow() + .clone(); + + let zero = ::default(); + if total_weight < zero { + return Err(WeightedError::NegativeWeight); + } + + let mut weights = Vec::::with_capacity(iter.size_hint().0); + for w in iter { + if *w.borrow() < zero { + return Err(WeightedError::NegativeWeight); + } + weights.push(total_weight.clone()); + total_weight += w.borrow(); + } + + if total_weight == zero { + return Err(WeightedError::AllWeightsZero); + } + let distr = X::Sampler::new(zero, total_weight); + + Ok(WeightedIndex { cumulative_weights: weights, weight_distribution: distr }) + } +} + +impl Distribution for WeightedIndex where + X: SampleUniform + PartialOrd { + fn sample(&self, rng: &mut R) -> usize { + use ::core::cmp::Ordering; + let chosen_weight = self.weight_distribution.sample(rng); + // Find the first item which has a weight *higher* than the chosen weight. + self.cumulative_weights.binary_search_by( + |w| if *w <= chosen_weight { Ordering::Less } else { Ordering::Greater }).unwrap_err() + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_weightedindex() { + let mut r = ::test::rng(700); + const N_REPS: u32 = 5000; + let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; + let total_weight = weights.iter().sum::() as f32; + + let verify = |result: [i32; 14]| { + for (i, count) in result.iter().enumerate() { + let exp = (weights[i] * N_REPS) as f32 / total_weight; + let mut err = (*count as f32 - exp).abs(); + if err != 0.0 { + err /= exp; + } + assert!(err <= 0.25); + } + }; + + // WeightedIndex from vec + let mut chosen = [0i32; 14]; + let distr = WeightedIndex::new(weights.to_vec()).unwrap(); + for _ in 0..N_REPS { + chosen[distr.sample(&mut r)] += 1; + } + verify(chosen); + + // WeightedIndex from slice + chosen = [0i32; 14]; + let distr = WeightedIndex::new(&weights[..]).unwrap(); + for _ in 0..N_REPS { + chosen[distr.sample(&mut r)] += 1; + } + verify(chosen); + + // WeightedIndex from iterator + chosen = [0i32; 14]; + let distr = WeightedIndex::new(weights.iter()).unwrap(); + for _ in 0..N_REPS { + chosen[distr.sample(&mut r)] += 1; + } + verify(chosen); + + for _ in 0..5 { + assert_eq!(WeightedIndex::new(&[0, 1]).unwrap().sample(&mut r), 1); + assert_eq!(WeightedIndex::new(&[1, 0]).unwrap().sample(&mut r), 0); + assert_eq!(WeightedIndex::new(&[0, 0, 0, 0, 10, 0]).unwrap().sample(&mut r), 4); + } + + assert_eq!(WeightedIndex::new(&[10][0..0]).unwrap_err(), WeightedError::NoItem); + assert_eq!(WeightedIndex::new(&[0]).unwrap_err(), WeightedError::AllWeightsZero); + assert_eq!(WeightedIndex::new(&[10, 20, -1, 30]).unwrap_err(), WeightedError::NegativeWeight); + assert_eq!(WeightedIndex::new(&[-10, 20, 1, 30]).unwrap_err(), WeightedError::NegativeWeight); + assert_eq!(WeightedIndex::new(&[-10]).unwrap_err(), WeightedError::NegativeWeight); + } +} + +/// Error type returned from `WeightedIndex::new`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WeightedError { + /// The provided iterator contained no items. + NoItem, + + /// A weight lower than zero was used. + NegativeWeight, + + /// All items in the provided iterator had a weight of zero. + AllWeightsZero, +} + +impl WeightedError { + fn msg(&self) -> &str { + match *self { + WeightedError::NoItem => "No items found", + WeightedError::NegativeWeight => "Item has negative weight", + WeightedError::AllWeightsZero => "All items had weight zero", + } + } +} + +#[cfg(feature="std")] +impl ::std::error::Error for WeightedError { + fn description(&self) -> &str { + self.msg() + } + fn cause(&self) -> Option<&::std::error::Error> { + None + } +} + +impl fmt::Display for WeightedError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.msg()) + } +} diff --git a/bash-5.1/vendor/rand/src/distributions/ziggurat_tables.rs b/bash-5.1/vendor/rand/src/distributions/ziggurat_tables.rs new file mode 100644 index 0000000..ca1ce30 --- /dev/null +++ b/bash-5.1/vendor/rand/src/distributions/ziggurat_tables.rs @@ -0,0 +1,279 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Tables for distributions which are sampled using the ziggurat +// algorithm. Autogenerated by `ziggurat_tables.py`. + +pub type ZigTable = &'static [f64; 257]; +pub const ZIG_NORM_R: f64 = 3.654152885361008796; +pub static ZIG_NORM_X: [f64; 257] = + [3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074, + 3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434, + 2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548, + 2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056, + 2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570, + 2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761, + 2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318, + 2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520, + 2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952, + 2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565, + 2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760, + 2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995, + 2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268, + 2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957, + 2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778, + 2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715, + 2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244, + 1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896, + 1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257, + 1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081, + 1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281, + 1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566, + 1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199, + 1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933, + 1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012, + 1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086, + 1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338, + 1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526, + 1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427, + 1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339, + 1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456, + 1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553, + 1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404, + 1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369, + 1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830, + 1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425, + 1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534, + 1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964, + 1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606, + 1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679, + 1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728, + 1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732, + 1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903, + 1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552, + 1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650, + 1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240, + 1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975, + 1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151, + 1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714, + 1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538, + 1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441, + 1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750, + 0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130, + 0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997, + 0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550, + 0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752, + 0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785, + 0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653, + 0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448, + 0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928, + 0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262, + 0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393, + 0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746, + 0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806, + 0.000000000000000000]; +pub static ZIG_NORM_F: [f64; 257] = + [0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872, + 0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100, + 0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839, + 0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237, + 0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690, + 0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918, + 0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664, + 0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916, + 0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854, + 0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965, + 0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509, + 0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229, + 0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627, + 0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880, + 0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014, + 0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349, + 0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352, + 0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926, + 0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563, + 0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071, + 0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654, + 0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926, + 0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112, + 0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651, + 0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589, + 0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525, + 0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988, + 0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150, + 0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837, + 0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316, + 0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984, + 0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274, + 0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396, + 0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099, + 0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340, + 0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515, + 0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344, + 0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958, + 0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668, + 0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784, + 0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519, + 0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750, + 0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481, + 0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788, + 0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658, + 0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142, + 0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700, + 0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941, + 0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916, + 0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473, + 0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719, + 0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205, + 0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991, + 0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357, + 0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376, + 0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409, + 0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437, + 0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500, + 0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902, + 0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935, + 0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077, + 0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839, + 0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247, + 0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328, + 1.000000000000000000]; +pub const ZIG_EXP_R: f64 = 7.697117470131050077; +pub static ZIG_EXP_X: [f64; 257] = + [8.697117470131052741, 7.697117470131050077, 6.941033629377212577, 6.478378493832569696, + 6.144164665772472667, 5.882144315795399869, 5.666410167454033697, 5.482890627526062488, + 5.323090505754398016, 5.181487281301500047, 5.054288489981304089, 4.938777085901250530, + 4.832939741025112035, 4.735242996601741083, 4.644491885420085175, 4.559737061707351380, + 4.480211746528421912, 4.405287693473573185, 4.334443680317273007, 4.267242480277365857, + 4.203313713735184365, 4.142340865664051464, 4.084051310408297830, 4.028208544647936762, + 3.974606066673788796, 3.923062500135489739, 3.873417670399509127, 3.825529418522336744, + 3.779270992411667862, 3.734528894039797375, 3.691201090237418825, 3.649195515760853770, + 3.608428813128909507, 3.568825265648337020, 3.530315889129343354, 3.492837654774059608, + 3.456332821132760191, 3.420748357251119920, 3.386035442460300970, 3.352149030900109405, + 3.319047470970748037, 3.286692171599068679, 3.255047308570449882, 3.224079565286264160, + 3.193757903212240290, 3.164053358025972873, 3.134938858084440394, 3.106389062339824481, + 3.078380215254090224, 3.050890016615455114, 3.023897504455676621, 2.997382949516130601, + 2.971327759921089662, 2.945714394895045718, 2.920526286512740821, 2.895747768600141825, + 2.871364012015536371, 2.847360965635188812, 2.823725302450035279, 2.800444370250737780, + 2.777506146439756574, 2.754899196562344610, 2.732612636194700073, 2.710636095867928752, + 2.688959688741803689, 2.667573980773266573, 2.646469963151809157, 2.625639026797788489, + 2.605072938740835564, 2.584763820214140750, 2.564704126316905253, 2.544886627111869970, + 2.525304390037828028, 2.505950763528594027, 2.486819361740209455, 2.467904050297364815, + 2.449198932978249754, 2.430698339264419694, 2.412396812688870629, 2.394289099921457886, + 2.376370140536140596, 2.358635057409337321, 2.341079147703034380, 2.323697874390196372, + 2.306486858283579799, 2.289441870532269441, 2.272558825553154804, 2.255833774367219213, + 2.239262898312909034, 2.222842503111036816, 2.206569013257663858, 2.190438966723220027, + 2.174449009937774679, 2.158595893043885994, 2.142876465399842001, 2.127287671317368289, + 2.111826546019042183, 2.096490211801715020, 2.081275874393225145, 2.066180819490575526, + 2.051202409468584786, 2.036338080248769611, 2.021585338318926173, 2.006941757894518563, + 1.992404978213576650, 1.977972700957360441, 1.963642687789548313, 1.949412758007184943, + 1.935280786297051359, 1.921244700591528076, 1.907302480018387536, 1.893452152939308242, + 1.879691795072211180, 1.866019527692827973, 1.852433515911175554, 1.838931967018879954, + 1.825513128903519799, 1.812175288526390649, 1.798916770460290859, 1.785735935484126014, + 1.772631179231305643, 1.759600930889074766, 1.746643651946074405, 1.733757834985571566, + 1.720942002521935299, 1.708194705878057773, 1.695514524101537912, 1.682900062917553896, + 1.670349953716452118, 1.657862852574172763, 1.645437439303723659, 1.633072416535991334, + 1.620766508828257901, 1.608518461798858379, 1.596327041286483395, 1.584191032532688892, + 1.572109239386229707, 1.560080483527888084, 1.548103603714513499, 1.536177455041032092, + 1.524300908219226258, 1.512472848872117082, 1.500692176842816750, 1.488957805516746058, + 1.477268661156133867, 1.465623682245745352, 1.454021818848793446, 1.442462031972012504, + 1.430943292938879674, 1.419464582769983219, 1.408024891569535697, 1.396623217917042137, + 1.385258568263121992, 1.373929956328490576, 1.362636402505086775, 1.351376933258335189, + 1.340150580529504643, 1.328956381137116560, 1.317793376176324749, 1.306660610415174117, + 1.295557131686601027, 1.284481990275012642, 1.273434238296241139, 1.262412929069615330, + 1.251417116480852521, 1.240445854334406572, 1.229498195693849105, 1.218573192208790124, + 1.207669893426761121, 1.196787346088403092, 1.185924593404202199, 1.175080674310911677, + 1.164254622705678921, 1.153445466655774743, 1.142652227581672841, 1.131873919411078511, + 1.121109547701330200, 1.110358108727411031, 1.099618588532597308, 1.088889961938546813, + 1.078171191511372307, 1.067461226479967662, 1.056759001602551429, 1.046063435977044209, + 1.035373431790528542, 1.024687873002617211, 1.014005623957096480, 1.003325527915696735, + 0.992646405507275897, 0.981967053085062602, 0.971286240983903260, 0.960602711668666509, + 0.949915177764075969, 0.939222319955262286, 0.928522784747210395, 0.917815182070044311, + 0.907098082715690257, 0.896370015589889935, 0.885629464761751528, 0.874874866291025066, + 0.864104604811004484, 0.853317009842373353, 0.842510351810368485, 0.831682837734273206, + 0.820832606554411814, 0.809957724057418282, 0.799056177355487174, 0.788125868869492430, + 0.777164609759129710, 0.766170112735434672, 0.755139984181982249, 0.744071715500508102, + 0.732962673584365398, 0.721810090308756203, 0.710611050909655040, 0.699362481103231959, + 0.688061132773747808, 0.676703568029522584, 0.665286141392677943, 0.653804979847664947, + 0.642255960424536365, 0.630634684933490286, 0.618936451394876075, 0.607156221620300030, + 0.595288584291502887, 0.583327712748769489, 0.571267316532588332, 0.559100585511540626, + 0.546820125163310577, 0.534417881237165604, 0.521885051592135052, 0.509211982443654398, + 0.496388045518671162, 0.483401491653461857, 0.470239275082169006, 0.456886840931420235, + 0.443327866073552401, 0.429543940225410703, 0.415514169600356364, 0.401214678896277765, + 0.386617977941119573, 0.371692145329917234, 0.356399760258393816, 0.340696481064849122, + 0.324529117016909452, 0.307832954674932158, 0.290527955491230394, 0.272513185478464703, + 0.253658363385912022, 0.233790483059674731, 0.212671510630966620, 0.189958689622431842, + 0.165127622564187282, 0.137304980940012589, 0.104838507565818778, 0.063852163815001570, + 0.000000000000000000]; +pub static ZIG_EXP_F: [f64; 257] = + [0.000167066692307963, 0.000454134353841497, 0.000967269282327174, 0.001536299780301573, + 0.002145967743718907, 0.002788798793574076, 0.003460264777836904, 0.004157295120833797, + 0.004877655983542396, 0.005619642207205489, 0.006381905937319183, 0.007163353183634991, + 0.007963077438017043, 0.008780314985808977, 0.009614413642502212, 0.010464810181029981, + 0.011331013597834600, 0.012212592426255378, 0.013109164931254991, 0.014020391403181943, + 0.014945968011691148, 0.015885621839973156, 0.016839106826039941, 0.017806200410911355, + 0.018786700744696024, 0.019780424338009740, 0.020787204072578114, 0.021806887504283581, + 0.022839335406385240, 0.023884420511558174, 0.024942026419731787, 0.026012046645134221, + 0.027094383780955803, 0.028188948763978646, 0.029295660224637411, 0.030414443910466622, + 0.031545232172893622, 0.032687963508959555, 0.033842582150874358, 0.035009037697397431, + 0.036187284781931443, 0.037377282772959382, 0.038578995503074871, 0.039792391023374139, + 0.041017441380414840, 0.042254122413316254, 0.043502413568888197, 0.044762297732943289, + 0.046033761076175184, 0.047316792913181561, 0.048611385573379504, 0.049917534282706379, + 0.051235237055126281, 0.052564494593071685, 0.053905310196046080, 0.055257689676697030, + 0.056621641283742870, 0.057997175631200659, 0.059384305633420280, 0.060783046445479660, + 0.062193415408541036, 0.063615431999807376, 0.065049117786753805, 0.066494496385339816, + 0.067951593421936643, 0.069420436498728783, 0.070901055162371843, 0.072393480875708752, + 0.073897746992364746, 0.075413888734058410, 0.076941943170480517, 0.078481949201606435, + 0.080033947542319905, 0.081597980709237419, 0.083174093009632397, 0.084762330532368146, + 0.086362741140756927, 0.087975374467270231, 0.089600281910032886, 0.091237516631040197, + 0.092887133556043569, 0.094549189376055873, 0.096223742550432825, 0.097910853311492213, + 0.099610583670637132, 0.101322997425953631, 0.103048160171257702, 0.104786139306570145, + 0.106537004050001632, 0.108300825451033755, 0.110077676405185357, 0.111867631670056283, + 0.113670767882744286, 0.115487163578633506, 0.117316899211555525, 0.119160057175327641, + 0.121016721826674792, 0.122886979509545108, 0.124770918580830933, 0.126668629437510671, + 0.128580204545228199, 0.130505738468330773, 0.132445327901387494, 0.134399071702213602, + 0.136367070926428829, 0.138349428863580176, 0.140346251074862399, 0.142357645432472146, + 0.144383722160634720, 0.146424593878344889, 0.148480375643866735, 0.150551185001039839, + 0.152637142027442801, 0.154738369384468027, 0.156854992369365148, 0.158987138969314129, + 0.161134939917591952, 0.163298528751901734, 0.165478041874935922, 0.167673618617250081, + 0.169885401302527550, 0.172113535315319977, 0.174358169171353411, 0.176619454590494829, + 0.178897546572478278, 0.181192603475496261, 0.183504787097767436, 0.185834262762197083, + 0.188181199404254262, 0.190545769663195363, 0.192928149976771296, 0.195328520679563189, + 0.197747066105098818, 0.200183974691911210, 0.202639439093708962, 0.205113656293837654, + 0.207606827724221982, 0.210119159388988230, 0.212650861992978224, 0.215202151075378628, + 0.217773247148700472, 0.220364375843359439, 0.222975768058120111, 0.225607660116683956, + 0.228260293930716618, 0.230933917169627356, 0.233628783437433291, 0.236345152457059560, + 0.239083290262449094, 0.241843469398877131, 0.244625969131892024, 0.247431075665327543, + 0.250259082368862240, 0.253110290015629402, 0.255985007030415324, 0.258883549749016173, + 0.261806242689362922, 0.264753418835062149, 0.267725419932044739, 0.270722596799059967, + 0.273745309652802915, 0.276793928448517301, 0.279868833236972869, 0.282970414538780746, + 0.286099073737076826, 0.289255223489677693, 0.292439288161892630, 0.295651704281261252, + 0.298892921015581847, 0.302163400675693528, 0.305463619244590256, 0.308794066934560185, + 0.312155248774179606, 0.315547685227128949, 0.318971912844957239, 0.322428484956089223, + 0.325917972393556354, 0.329440964264136438, 0.332998068761809096, 0.336589914028677717, + 0.340217149066780189, 0.343880444704502575, 0.347580494621637148, 0.351318016437483449, + 0.355093752866787626, 0.358908472948750001, 0.362762973354817997, 0.366658079781514379, + 0.370594648435146223, 0.374573567615902381, 0.378595759409581067, 0.382662181496010056, + 0.386773829084137932, 0.390931736984797384, 0.395136981833290435, 0.399390684475231350, + 0.403694012530530555, 0.408048183152032673, 0.412454465997161457, 0.416914186433003209, + 0.421428728997616908, 0.425999541143034677, 0.430628137288459167, 0.435316103215636907, + 0.440065100842354173, 0.444876873414548846, 0.449753251162755330, 0.454696157474615836, + 0.459707615642138023, 0.464789756250426511, 0.469944825283960310, 0.475175193037377708, + 0.480483363930454543, 0.485871987341885248, 0.491343869594032867, 0.496901987241549881, + 0.502549501841348056, 0.508289776410643213, 0.514126393814748894, 0.520063177368233931, + 0.526104213983620062, 0.532253880263043655, 0.538516872002862246, 0.544898237672440056, + 0.551403416540641733, 0.558038282262587892, 0.564809192912400615, 0.571723048664826150, + 0.578787358602845359, 0.586010318477268366, 0.593400901691733762, 0.600968966365232560, + 0.608725382079622346, 0.616682180915207878, 0.624852738703666200, 0.633251994214366398, + 0.641896716427266423, 0.650805833414571433, 0.660000841079000145, 0.669506316731925177, + 0.679350572264765806, 0.689566496117078431, 0.700192655082788606, 0.711274760805076456, + 0.722867659593572465, 0.735038092431424039, 0.747868621985195658, 0.761463388849896838, + 0.775956852040116218, 0.791527636972496285, 0.808421651523009044, 0.826993296643051101, + 0.847785500623990496, 0.871704332381204705, 0.900469929925747703, 0.938143680862176477, + 1.000000000000000000]; diff --git a/bash-5.1/vendor/rand/src/lib.rs b/bash-5.1/vendor/rand/src/lib.rs new file mode 100644 index 0000000..9c0482f --- /dev/null +++ b/bash-5.1/vendor/rand/src/lib.rs @@ -0,0 +1,830 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2017 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Utilities for random number generation +//! +//! Rand provides utilities to generate random numbers, to convert them to +//! useful types and distributions, and some randomness-related algorithms. +//! +//! # Quick Start +//! +//! To get you started quickly, the easiest and highest-level way to get +//! a random value is to use [`random()`]; alternatively you can use +//! [`thread_rng()`]. The [`Rng`] trait provides a useful API on all RNGs, while +//! the [`distributions`] and [`seq`] modules provide further +//! functionality on top of RNGs. +//! +//! ``` +//! use rand::prelude::*; +//! +//! if rand::random() { // generates a boolean +//! // Try printing a random unicode code point (probably a bad idea)! +//! println!("char: {}", rand::random::()); +//! } +//! +//! let mut rng = rand::thread_rng(); +//! let y: f64 = rng.gen(); // generates a float between 0 and 1 +//! +//! let mut nums: Vec = (1..100).collect(); +//! nums.shuffle(&mut rng); +//! ``` +//! +//! # The Book +//! +//! For the user guide and futher documentation, please read +//! [The Rust Rand Book](https://rust-random.github.io/book). + + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![cfg_attr(not(feature="std"), no_std)] +#![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))] +#![cfg_attr(all(feature="simd_support", feature="nightly"), feature(stdsimd))] + +#[cfg(feature = "std")] extern crate core; +#[cfg(all(feature = "alloc", not(feature="std")))] #[macro_use] extern crate alloc; + +#[cfg(feature="simd_support")] extern crate packed_simd; + +extern crate rand_jitter; +#[cfg(feature = "rand_os")] +extern crate rand_os; + +extern crate rand_core; +extern crate rand_isaac; // only for deprecations +extern crate rand_chacha; // only for deprecations +extern crate rand_hc; +extern crate rand_pcg; +extern crate rand_xorshift; + +#[cfg(feature = "log")] #[macro_use] extern crate log; +#[allow(unused)] +#[cfg(not(feature = "log"))] macro_rules! trace { ($($x:tt)*) => () } +#[allow(unused)] +#[cfg(not(feature = "log"))] macro_rules! debug { ($($x:tt)*) => () } +#[allow(unused)] +#[cfg(not(feature = "log"))] macro_rules! info { ($($x:tt)*) => () } +#[allow(unused)] +#[cfg(not(feature = "log"))] macro_rules! warn { ($($x:tt)*) => () } +#[allow(unused)] +#[cfg(not(feature = "log"))] macro_rules! error { ($($x:tt)*) => () } + + +// Re-exports from rand_core +pub use rand_core::{RngCore, CryptoRng, SeedableRng}; +pub use rand_core::{ErrorKind, Error}; + +// Public exports +#[cfg(feature="std")] pub use rngs::thread::thread_rng; + +// Public modules +pub mod distributions; +pub mod prelude; +#[deprecated(since="0.6.0")] +pub mod prng; +pub mod rngs; +pub mod seq; + +//////////////////////////////////////////////////////////////////////////////// +// Compatibility re-exports. Documentation is hidden; will be removed eventually. + +#[doc(hidden)] mod deprecated; + +#[allow(deprecated)] +#[doc(hidden)] pub use deprecated::ReseedingRng; + +#[allow(deprecated)] +#[cfg(feature="std")] #[doc(hidden)] pub use deprecated::EntropyRng; + +#[allow(deprecated)] +#[cfg(feature="rand_os")] +#[doc(hidden)] +pub use deprecated::OsRng; + +#[allow(deprecated)] +#[doc(hidden)] pub use deprecated::{ChaChaRng, IsaacRng, Isaac64Rng, XorShiftRng}; +#[allow(deprecated)] +#[doc(hidden)] pub use deprecated::StdRng; + + +#[allow(deprecated)] +#[doc(hidden)] +pub mod jitter { + pub use deprecated::JitterRng; + pub use rngs::TimerError; +} +#[allow(deprecated)] +#[cfg(feature="rand_os")] +#[doc(hidden)] +pub mod os { + pub use deprecated::OsRng; +} +#[allow(deprecated)] +#[doc(hidden)] +pub mod chacha { + pub use deprecated::ChaChaRng; +} +#[allow(deprecated)] +#[doc(hidden)] +pub mod isaac { + pub use deprecated::{IsaacRng, Isaac64Rng}; +} +#[allow(deprecated)] +#[cfg(feature="std")] +#[doc(hidden)] +pub mod read { + pub use deprecated::ReadRng; +} + +#[allow(deprecated)] +#[cfg(feature="std")] #[doc(hidden)] pub use deprecated::ThreadRng; + +//////////////////////////////////////////////////////////////////////////////// + + +use core::{mem, slice}; +use distributions::{Distribution, Standard}; +use distributions::uniform::{SampleUniform, UniformSampler, SampleBorrow}; + +/// An automatically-implemented extension trait on [`RngCore`] providing high-level +/// generic methods for sampling values and other convenience methods. +/// +/// This is the primary trait to use when generating random values. +/// +/// # Generic usage +/// +/// The basic pattern is `fn foo(rng: &mut R)`. Some +/// things are worth noting here: +/// +/// - Since `Rng: RngCore` and every `RngCore` implements `Rng`, it makes no +/// difference whether we use `R: Rng` or `R: RngCore`. +/// - The `+ ?Sized` un-bounding allows functions to be called directly on +/// type-erased references; i.e. `foo(r)` where `r: &mut RngCore`. Without +/// this it would be necessary to write `foo(&mut r)`. +/// +/// An alternative pattern is possible: `fn foo(rng: R)`. This has some +/// trade-offs. It allows the argument to be consumed directly without a `&mut` +/// (which is how `from_rng(thread_rng())` works); also it still works directly +/// on references (including type-erased references). Unfortunately within the +/// function `foo` it is not known whether `rng` is a reference type or not, +/// hence many uses of `rng` require an extra reference, either explicitly +/// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the +/// optimiser can remove redundant references later. +/// +/// Example: +/// +/// ``` +/// # use rand::thread_rng; +/// use rand::Rng; +/// +/// fn foo(rng: &mut R) -> f32 { +/// rng.gen() +/// } +/// +/// # let v = foo(&mut thread_rng()); +/// ``` +pub trait Rng: RngCore { + /// Return a random value supporting the [`Standard`] distribution. + /// + /// [`Standard`]: distributions::Standard + /// + /// # Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// + /// let mut rng = thread_rng(); + /// let x: u32 = rng.gen(); + /// println!("{}", x); + /// println!("{:?}", rng.gen::<(f64, bool)>()); + /// ``` + #[inline] + fn gen(&mut self) -> T where Standard: Distribution { + Standard.sample(self) + } + + /// Generate a random value in the range [`low`, `high`), i.e. inclusive of + /// `low` and exclusive of `high`. + /// + /// This function is optimised for the case that only a single sample is + /// made from the given range. See also the [`Uniform`] distribution + /// type which may be faster if sampling from the same range repeatedly. + /// + /// # Panics + /// + /// Panics if `low >= high`. + /// + /// # Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// + /// let mut rng = thread_rng(); + /// let n: u32 = rng.gen_range(0, 10); + /// println!("{}", n); + /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64); + /// println!("{}", m); + /// ``` + /// + /// [`Uniform`]: distributions::uniform::Uniform + fn gen_range(&mut self, low: B1, high: B2) -> T + where B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized { + T::Sampler::sample_single(low, high, self) + } + + /// Sample a new value, using the given distribution. + /// + /// ### Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// use rand::distributions::Uniform; + /// + /// let mut rng = thread_rng(); + /// let x = rng.sample(Uniform::new(10u32, 15)); + /// // Type annotation requires two types, the type and distribution; the + /// // distribution can be inferred. + /// let y = rng.sample::(Uniform::new(10, 15)); + /// ``` + fn sample>(&mut self, distr: D) -> T { + distr.sample(self) + } + + /// Create an iterator that generates values using the given distribution. + /// + /// # Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// use rand::distributions::{Alphanumeric, Uniform, Standard}; + /// + /// let mut rng = thread_rng(); + /// + /// // Vec of 16 x f32: + /// let v: Vec = thread_rng().sample_iter(&Standard).take(16).collect(); + /// + /// // String: + /// let s: String = rng.sample_iter(&Alphanumeric).take(7).collect(); + /// + /// // Combined values + /// println!("{:?}", thread_rng().sample_iter(&Standard).take(5) + /// .collect::>()); + /// + /// // Dice-rolling: + /// let die_range = Uniform::new_inclusive(1, 6); + /// let mut roll_die = rng.sample_iter(&die_range); + /// while roll_die.next().unwrap() != 6 { + /// println!("Not a 6; rolling again!"); + /// } + /// ``` + fn sample_iter<'a, T, D: Distribution>(&'a mut self, distr: &'a D) + -> distributions::DistIter<'a, D, Self, T> where Self: Sized + { + distr.sample_iter(self) + } + + /// Fill `dest` entirely with random bytes (uniform value distribution), + /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices + /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). + /// + /// On big-endian platforms this performs byte-swapping to ensure + /// portability of results from reproducible generators. + /// + /// This uses [`fill_bytes`] internally which may handle some RNG errors + /// implicitly (e.g. waiting if the OS generator is not ready), but panics + /// on other errors. See also [`try_fill`] which returns errors. + /// + /// # Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// + /// let mut arr = [0i8; 20]; + /// thread_rng().fill(&mut arr[..]); + /// ``` + /// + /// [`fill_bytes`]: RngCore::fill_bytes + /// [`try_fill`]: Rng::try_fill + fn fill(&mut self, dest: &mut T) { + self.fill_bytes(dest.as_byte_slice_mut()); + dest.to_le(); + } + + /// Fill `dest` entirely with random bytes (uniform value distribution), + /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices + /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). + /// + /// On big-endian platforms this performs byte-swapping to ensure + /// portability of results from reproducible generators. + /// + /// This uses [`try_fill_bytes`] internally and forwards all RNG errors. In + /// some cases errors may be resolvable; see [`ErrorKind`] and + /// documentation for the RNG in use. If you do not plan to handle these + /// errors you may prefer to use [`fill`]. + /// + /// # Example + /// + /// ``` + /// # use rand::Error; + /// use rand::{thread_rng, Rng}; + /// + /// # fn try_inner() -> Result<(), Error> { + /// let mut arr = [0u64; 4]; + /// thread_rng().try_fill(&mut arr[..])?; + /// # Ok(()) + /// # } + /// + /// # try_inner().unwrap() + /// ``` + /// + /// [`try_fill_bytes`]: RngCore::try_fill_bytes + /// [`fill`]: Rng::fill + fn try_fill(&mut self, dest: &mut T) -> Result<(), Error> { + self.try_fill_bytes(dest.as_byte_slice_mut())?; + dest.to_le(); + Ok(()) + } + + /// Return a bool with a probability `p` of being true. + /// + /// See also the [`Bernoulli`] distribution, which may be faster if + /// sampling from the same probability repeatedly. + /// + /// # Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// + /// let mut rng = thread_rng(); + /// println!("{}", rng.gen_bool(1.0 / 3.0)); + /// ``` + /// + /// # Panics + /// + /// If `p < 0` or `p > 1`. + /// + /// [`Bernoulli`]: distributions::bernoulli::Bernoulli + #[inline] + fn gen_bool(&mut self, p: f64) -> bool { + let d = distributions::Bernoulli::new(p); + self.sample(d) + } + + /// Return a bool with a probability of `numerator/denominator` of being + /// true. I.e. `gen_ratio(2, 3)` has chance of 2 in 3, or about 67%, of + /// returning true. If `numerator == denominator`, then the returned value + /// is guaranteed to be `true`. If `numerator == 0`, then the returned + /// value is guaranteed to be `false`. + /// + /// See also the [`Bernoulli`] distribution, which may be faster if + /// sampling from the same `numerator` and `denominator` repeatedly. + /// + /// # Panics + /// + /// If `denominator == 0` or `numerator > denominator`. + /// + /// # Example + /// + /// ``` + /// use rand::{thread_rng, Rng}; + /// + /// let mut rng = thread_rng(); + /// println!("{}", rng.gen_ratio(2, 3)); + /// ``` + /// + /// [`Bernoulli`]: distributions::bernoulli::Bernoulli + #[inline] + fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool { + let d = distributions::Bernoulli::from_ratio(numerator, denominator); + self.sample(d) + } + + /// Return a random element from `values`. + /// + /// Deprecated: use [`seq::SliceRandom::choose`] instead. + #[deprecated(since="0.6.0", note="use SliceRandom::choose instead")] + fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { + use seq::SliceRandom; + values.choose(self) + } + + /// Return a mutable pointer to a random element from `values`. + /// + /// Deprecated: use [`seq::SliceRandom::choose_mut`] instead. + #[deprecated(since="0.6.0", note="use SliceRandom::choose_mut instead")] + fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T> { + use seq::SliceRandom; + values.choose_mut(self) + } + + /// Shuffle a mutable slice in place. + /// + /// Deprecated: use [`seq::SliceRandom::shuffle`] instead. + #[deprecated(since="0.6.0", note="use SliceRandom::shuffle instead")] + fn shuffle(&mut self, values: &mut [T]) { + use seq::SliceRandom; + values.shuffle(self) + } +} + +impl Rng for R {} + +/// Trait for casting types to byte slices +/// +/// This is used by the [`Rng::fill`] and [`Rng::try_fill`] methods. +pub trait AsByteSliceMut { + /// Return a mutable reference to self as a byte slice + fn as_byte_slice_mut(&mut self) -> &mut [u8]; + + /// Call `to_le` on each element (i.e. byte-swap on Big Endian platforms). + fn to_le(&mut self); +} + +impl AsByteSliceMut for [u8] { + fn as_byte_slice_mut(&mut self) -> &mut [u8] { + self + } + + fn to_le(&mut self) {} +} + +macro_rules! impl_as_byte_slice { + ($t:ty) => { + impl AsByteSliceMut for [$t] { + fn as_byte_slice_mut(&mut self) -> &mut [u8] { + if self.len() == 0 { + unsafe { + // must not use null pointer + slice::from_raw_parts_mut(0x1 as *mut u8, 0) + } + } else { + unsafe { + slice::from_raw_parts_mut(&mut self[0] + as *mut $t + as *mut u8, + self.len() * mem::size_of::<$t>() + ) + } + } + } + + fn to_le(&mut self) { + for x in self { + *x = x.to_le(); + } + } + } + } +} + +impl_as_byte_slice!(u16); +impl_as_byte_slice!(u32); +impl_as_byte_slice!(u64); +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] impl_as_byte_slice!(u128); +impl_as_byte_slice!(usize); +impl_as_byte_slice!(i8); +impl_as_byte_slice!(i16); +impl_as_byte_slice!(i32); +impl_as_byte_slice!(i64); +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] impl_as_byte_slice!(i128); +impl_as_byte_slice!(isize); + +macro_rules! impl_as_byte_slice_arrays { + ($n:expr,) => {}; + ($n:expr, $N:ident, $($NN:ident,)*) => { + impl_as_byte_slice_arrays!($n - 1, $($NN,)*); + + impl AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { + fn as_byte_slice_mut(&mut self) -> &mut [u8] { + self[..].as_byte_slice_mut() + } + + fn to_le(&mut self) { + self[..].to_le() + } + } + }; + (!div $n:expr,) => {}; + (!div $n:expr, $N:ident, $($NN:ident,)*) => { + impl_as_byte_slice_arrays!(!div $n / 2, $($NN,)*); + + impl AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { + fn as_byte_slice_mut(&mut self) -> &mut [u8] { + self[..].as_byte_slice_mut() + } + + fn to_le(&mut self) { + self[..].to_le() + } + } + }; +} +impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,); +impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,); + + +/// A convenience extension to [`SeedableRng`] allowing construction from fresh +/// entropy. This trait is automatically implemented for any PRNG implementing +/// [`SeedableRng`] and is not intended to be implemented by users. +/// +/// This is equivalent to using `SeedableRng::from_rng(EntropyRng::new())` then +/// unwrapping the result. +/// +/// Since this is convenient and secure, it is the recommended way to create +/// PRNGs, though two alternatives may be considered: +/// +/// * Deterministic creation using [`SeedableRng::from_seed`] with a fixed seed +/// * Seeding from `thread_rng`: `SeedableRng::from_rng(thread_rng())?`; +/// this will usually be faster and should also be secure, but requires +/// trusting one extra component. +/// +/// ## Example +/// +/// ``` +/// use rand::{Rng, FromEntropy}; +/// use rand::rngs::StdRng; +/// +/// let mut rng = StdRng::from_entropy(); +/// println!("Random die roll: {}", rng.gen_range(1, 7)); +/// ``` +/// +/// [`EntropyRng`]: rngs::EntropyRng +#[cfg(feature="std")] +pub trait FromEntropy: SeedableRng { + /// Creates a new instance, automatically seeded with fresh entropy. + /// + /// Normally this will use `OsRng`, but if that fails `JitterRng` will be + /// used instead. Both should be suitable for cryptography. It is possible + /// that both entropy sources will fail though unlikely; failures would + /// almost certainly be platform limitations or build issues, i.e. most + /// applications targetting PC/mobile platforms should not need to worry + /// about this failing. + /// + /// # Panics + /// + /// If all entropy sources fail this will panic. If you need to handle + /// errors, use the following code, equivalent aside from error handling: + /// + /// ``` + /// # use rand::Error; + /// use rand::prelude::*; + /// use rand::rngs::EntropyRng; + /// + /// # fn try_inner() -> Result<(), Error> { + /// // This uses StdRng, but is valid for any R: SeedableRng + /// let mut rng = StdRng::from_rng(EntropyRng::new())?; + /// + /// println!("random number: {}", rng.gen_range(1, 10)); + /// # Ok(()) + /// # } + /// + /// # try_inner().unwrap() + /// ``` + fn from_entropy() -> Self; +} + +#[cfg(feature="std")] +impl FromEntropy for R { + fn from_entropy() -> R { + R::from_rng(rngs::EntropyRng::new()).unwrap_or_else(|err| + panic!("FromEntropy::from_entropy() failed: {}", err)) + } +} + + +/// Generates a random value using the thread-local random number generator. +/// +/// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for +/// documentation of the entropy source and [`Standard`] for documentation of +/// distributions and type-specific generation. +/// +/// # Examples +/// +/// ``` +/// let x = rand::random::(); +/// println!("{}", x); +/// +/// let y = rand::random::(); +/// println!("{}", y); +/// +/// if rand::random() { // generates a boolean +/// println!("Better lucky than good!"); +/// } +/// ``` +/// +/// If you're calling `random()` in a loop, caching the generator as in the +/// following example can increase performance. +/// +/// ``` +/// use rand::Rng; +/// +/// let mut v = vec![1, 2, 3]; +/// +/// for x in v.iter_mut() { +/// *x = rand::random() +/// } +/// +/// // can be made faster by caching thread_rng +/// +/// let mut rng = rand::thread_rng(); +/// +/// for x in v.iter_mut() { +/// *x = rng.gen(); +/// } +/// ``` +/// +/// [`Standard`]: distributions::Standard +#[cfg(feature="std")] +#[inline] +pub fn random() -> T where Standard: Distribution { + thread_rng().gen() +} + +#[cfg(test)] +mod test { + use rngs::mock::StepRng; + use rngs::StdRng; + use super::*; + #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::boxed::Box; + + pub struct TestRng { inner: R } + + impl RngCore for TestRng { + fn next_u32(&mut self) -> u32 { + self.inner.next_u32() + } + fn next_u64(&mut self) -> u64 { + self.inner.next_u64() + } + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.inner.fill_bytes(dest) + } + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.inner.try_fill_bytes(dest) + } + } + + pub fn rng(seed: u64) -> TestRng { + TestRng { inner: StdRng::seed_from_u64(seed) } + } + + #[test] + fn test_fill_bytes_default() { + let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0); + + // check every remainder mod 8, both in small and big vectors. + let lengths = [0, 1, 2, 3, 4, 5, 6, 7, + 80, 81, 82, 83, 84, 85, 86, 87]; + for &n in lengths.iter() { + let mut buffer = [0u8; 87]; + let v = &mut buffer[0..n]; + r.fill_bytes(v); + + // use this to get nicer error messages. + for (i, &byte) in v.iter().enumerate() { + if byte == 0 { + panic!("byte {} of {} is zero", i, n) + } + } + } + } + + #[test] + fn test_fill() { + let x = 9041086907909331047; // a random u64 + let mut rng = StepRng::new(x, 0); + + // Convert to byte sequence and back to u64; byte-swap twice if BE. + let mut array = [0u64; 2]; + rng.fill(&mut array[..]); + assert_eq!(array, [x, x]); + assert_eq!(rng.next_u64(), x); + + // Convert to bytes then u32 in LE order + let mut array = [0u32; 2]; + rng.fill(&mut array[..]); + assert_eq!(array, [x as u32, (x >> 32) as u32]); + assert_eq!(rng.next_u32(), x as u32); + } + + #[test] + fn test_fill_empty() { + let mut array = [0u32; 0]; + let mut rng = StepRng::new(0, 1); + rng.fill(&mut array); + rng.fill(&mut array[..]); + } + + #[test] + fn test_gen_range() { + let mut r = rng(101); + for _ in 0..1000 { + let a = r.gen_range(-4711, 17); + assert!(a >= -4711 && a < 17); + let a = r.gen_range(-3i8, 42); + assert!(a >= -3i8 && a < 42i8); + let a = r.gen_range(&10u16, 99); + assert!(a >= 10u16 && a < 99u16); + let a = r.gen_range(-100i32, &2000); + assert!(a >= -100i32 && a < 2000i32); + let a = r.gen_range(&12u32, &24u32); + assert!(a >= 12u32 && a < 24u32); + + assert_eq!(r.gen_range(0u32, 1), 0u32); + assert_eq!(r.gen_range(-12i64, -11), -12i64); + assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000); + } + } + + #[test] + #[should_panic] + fn test_gen_range_panic_int() { + let mut r = rng(102); + r.gen_range(5, -2); + } + + #[test] + #[should_panic] + fn test_gen_range_panic_usize() { + let mut r = rng(103); + r.gen_range(5, 2); + } + + #[test] + fn test_gen_bool() { + let mut r = rng(105); + for _ in 0..5 { + assert_eq!(r.gen_bool(0.0), false); + assert_eq!(r.gen_bool(1.0), true); + } + } + + #[test] + fn test_rng_trait_object() { + use distributions::{Distribution, Standard}; + let mut rng = rng(109); + let mut r = &mut rng as &mut RngCore; + r.next_u32(); + r.gen::(); + assert_eq!(r.gen_range(0, 1), 0); + let _c: u8 = Standard.sample(&mut r); + } + + #[test] + #[cfg(feature="alloc")] + fn test_rng_boxed_trait() { + use distributions::{Distribution, Standard}; + let rng = rng(110); + let mut r = Box::new(rng) as Box; + r.next_u32(); + r.gen::(); + assert_eq!(r.gen_range(0, 1), 0); + let _c: u8 = Standard.sample(&mut r); + } + + #[test] + #[cfg(feature="std")] + fn test_random() { + // not sure how to test this aside from just getting some values + let _n : usize = random(); + let _f : f32 = random(); + let _o : Option> = random(); + let _many : ((), + (usize, + isize, + Option<(u32, (bool,))>), + (u8, i8, u16, i16, u32, i32, u64, i64), + (f32, (f64, (f64,)))) = random(); + } + + #[test] + fn test_gen_ratio_average() { + const NUM: u32 = 3; + const DENOM: u32 = 10; + const N: u32 = 100_000; + + let mut sum: u32 = 0; + let mut rng = rng(111); + for _ in 0..N { + if rng.gen_ratio(NUM, DENOM) { + sum += 1; + } + } + // Have Binomial(N, NUM/DENOM) distribution + let expected = (NUM * N) / DENOM; // exact integer + assert!(((sum - expected) as i32).abs() < 500); + } +} diff --git a/bash-5.1/vendor/rand/src/prelude.rs b/bash-5.1/vendor/rand/src/prelude.rs new file mode 100644 index 0000000..5d8a0e9 --- /dev/null +++ b/bash-5.1/vendor/rand/src/prelude.rs @@ -0,0 +1,27 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Convenience re-export of common members +//! +//! Like the standard library's prelude, this module simplifies importing of +//! common items. Unlike the standard prelude, the contents of this module must +//! be imported manually: +//! +//! ``` +//! use rand::prelude::*; +//! # let _ = StdRng::from_entropy(); +//! # let mut r = SmallRng::from_rng(thread_rng()).unwrap(); +//! # let _: f32 = r.gen(); +//! ``` + +#[doc(no_inline)] pub use distributions::Distribution; +#[doc(no_inline)] pub use rngs::{SmallRng, StdRng}; +#[doc(no_inline)] #[cfg(feature="std")] pub use rngs::ThreadRng; +#[doc(no_inline)] pub use {Rng, RngCore, CryptoRng, SeedableRng}; +#[doc(no_inline)] #[cfg(feature="std")] pub use {FromEntropy, random, thread_rng}; +#[doc(no_inline)] pub use seq::{SliceRandom, IteratorRandom}; diff --git a/bash-5.1/vendor/rand/src/prng/mod.rs b/bash-5.1/vendor/rand/src/prng/mod.rs new file mode 100644 index 0000000..3c0d27b --- /dev/null +++ b/bash-5.1/vendor/rand/src/prng/mod.rs @@ -0,0 +1,37 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Pseudo-random number generators. +//! +//! This module is deprecated: +//! +//! - documentation has moved to +//! [The Book](https://rust-random.github.io/book/guide-rngs.html), +//! - PRNGs have moved to other `rand_*` crates. + +// Deprecations (to be removed in 0.7) +#[doc(hidden)] #[allow(deprecated)] +pub use deprecated::XorShiftRng; +#[doc(hidden)] pub mod isaac { + // Note: we miss `IsaacCore` here but probably unimportant. + #[allow(deprecated)] pub use deprecated::IsaacRng; +} +#[doc(hidden)] pub mod isaac64 { + #[allow(deprecated)] pub use deprecated::Isaac64Rng; +} +#[doc(hidden)] #[allow(deprecated)] pub use deprecated::{IsaacRng, Isaac64Rng}; +#[doc(hidden)] pub mod chacha { + // Note: we miss `ChaChaCore` here but probably unimportant. + #[allow(deprecated)] pub use deprecated::ChaChaRng; +} +#[doc(hidden)] #[allow(deprecated)] pub use deprecated::ChaChaRng; +#[doc(hidden)] pub mod hc128 { + // Note: we miss `Hc128Core` here but probably unimportant. + #[allow(deprecated)] pub use deprecated::Hc128Rng; +} +#[doc(hidden)] #[allow(deprecated)] pub use deprecated::Hc128Rng; diff --git a/bash-5.1/vendor/rand/src/rngs/adapter/mod.rs b/bash-5.1/vendor/rand/src/rngs/adapter/mod.rs new file mode 100644 index 0000000..60b832e --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/adapter/mod.rs @@ -0,0 +1,15 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Wrappers / adapters forming RNGs + +#[cfg(feature="std")] #[doc(hidden)] pub mod read; +mod reseeding; + +#[cfg(feature="std")] pub use self::read::ReadRng; +pub use self::reseeding::ReseedingRng; diff --git a/bash-5.1/vendor/rand/src/rngs/adapter/read.rs b/bash-5.1/vendor/rand/src/rngs/adapter/read.rs new file mode 100644 index 0000000..9b9c18b --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/adapter/read.rs @@ -0,0 +1,136 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A wrapper around any Read to treat it as an RNG. + +use std::io::Read; + +use rand_core::{RngCore, Error, ErrorKind, impls}; + + +/// An RNG that reads random bytes straight from any type supporting +/// [`std::io::Read`], for example files. +/// +/// This will work best with an infinite reader, but that is not required. +/// +/// This can be used with `/dev/urandom` on Unix but it is recommended to use +/// [`OsRng`] instead. +/// +/// # Panics +/// +/// `ReadRng` uses [`std::io::Read::read_exact`], which retries on interrupts. +/// All other errors from the underlying reader, including when it does not +/// have enough data, will only be reported through [`try_fill_bytes`]. +/// The other [`RngCore`] methods will panic in case of an error. +/// +/// # Example +/// +/// ``` +/// use rand::Rng; +/// use rand::rngs::adapter::ReadRng; +/// +/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8]; +/// let mut rng = ReadRng::new(&data[..]); +/// println!("{:x}", rng.gen::()); +/// ``` +/// +/// [`OsRng`]: rand_os::OsRng +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Debug)] +pub struct ReadRng { + reader: R +} + +impl ReadRng { + /// Create a new `ReadRng` from a `Read`. + pub fn new(r: R) -> ReadRng { + ReadRng { + reader: r + } + } +} + +impl RngCore for ReadRng { + fn next_u32(&mut self) -> u32 { + impls::next_u32_via_fill(self) + } + + fn next_u64(&mut self) -> u64 { + impls::next_u64_via_fill(self) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.try_fill_bytes(dest).unwrap_or_else(|err| + panic!("reading random bytes from Read implementation failed; error: {}", err)); + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + if dest.len() == 0 { return Ok(()); } + // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. + self.reader.read_exact(dest).map_err(|err| { + match err.kind() { + ::std::io::ErrorKind::UnexpectedEof => Error::with_cause( + ErrorKind::Unavailable, + "not enough bytes available, reached end of source", err), + _ => Error::with_cause(ErrorKind::Unavailable, + "error reading from Read source", err) + } + }) + } +} + +#[cfg(test)] +mod test { + use super::ReadRng; + use {RngCore, ErrorKind}; + + #[test] + fn test_reader_rng_u64() { + // transmute from the target to avoid endianness concerns. + let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1, + 0 , 0, 0, 0, 0, 0, 0, 2, + 0, 0, 0, 0, 0, 0, 0, 3]; + let mut rng = ReadRng::new(&v[..]); + + assert_eq!(rng.next_u64(), 1_u64.to_be()); + assert_eq!(rng.next_u64(), 2_u64.to_be()); + assert_eq!(rng.next_u64(), 3_u64.to_be()); + } + + #[test] + fn test_reader_rng_u32() { + let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]; + let mut rng = ReadRng::new(&v[..]); + + assert_eq!(rng.next_u32(), 1_u32.to_be()); + assert_eq!(rng.next_u32(), 2_u32.to_be()); + assert_eq!(rng.next_u32(), 3_u32.to_be()); + } + + #[test] + fn test_reader_rng_fill_bytes() { + let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let mut w = [0u8; 8]; + + let mut rng = ReadRng::new(&v[..]); + rng.fill_bytes(&mut w); + + assert!(v == w); + } + + #[test] + fn test_reader_rng_insufficient_bytes() { + let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let mut w = [0u8; 9]; + + let mut rng = ReadRng::new(&v[..]); + + assert!(rng.try_fill_bytes(&mut w).err().unwrap().kind == ErrorKind::Unavailable); + } +} diff --git a/bash-5.1/vendor/rand/src/rngs/adapter/reseeding.rs b/bash-5.1/vendor/rand/src/rngs/adapter/reseeding.rs new file mode 100644 index 0000000..ed2aab4 --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/adapter/reseeding.rs @@ -0,0 +1,370 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A wrapper around another PRNG that reseeds it after it +//! generates a certain number of random bytes. + +use core::mem::size_of; + +use rand_core::{RngCore, CryptoRng, SeedableRng, Error, ErrorKind}; +use rand_core::block::{BlockRngCore, BlockRng}; + +/// A wrapper around any PRNG that implements [`BlockRngCore`], that adds the +/// ability to reseed it. +/// +/// `ReseedingRng` reseeds the underlying PRNG in the following cases: +/// +/// - On a manual call to [`reseed()`]. +/// - After `clone()`, the clone will be reseeded on first use. +/// - After a process is forked, the RNG in the child process is reseeded within +/// the next few generated values, depending on the block size of the +/// underlying PRNG. For [`ChaChaCore`] and [`Hc128Core`] this is a maximum of +/// 15 `u32` values before reseeding. +/// - After the PRNG has generated a configurable number of random bytes. +/// +/// # When should reseeding after a fixed number of generated bytes be used? +/// +/// Reseeding after a fixed number of generated bytes is never strictly +/// *necessary*. Cryptographic PRNGs don't have a limited number of bytes they +/// can output, or at least not a limit reachable in any practical way. There is +/// no such thing as 'running out of entropy'. +/// +/// Occasionally reseeding can be seen as some form of 'security in depth'. Even +/// if in the future a cryptographic weakness is found in the CSPRNG being used, +/// or a flaw in the implementation, occasionally reseeding should make +/// exploiting it much more difficult or even impossible. +/// +/// Use [`ReseedingRng::new`] with a `threshold` of `0` to disable reseeding +/// after a fixed number of generated bytes. +/// +/// # Error handling +/// +/// Although unlikely, reseeding the wrapped PRNG can fail. `ReseedingRng` will +/// never panic but try to handle the error intelligently through some +/// combination of retrying and delaying reseeding until later. +/// If handling the source error fails `ReseedingRng` will continue generating +/// data from the wrapped PRNG without reseeding. +/// +/// Manually calling [`reseed()`] will not have this retry or delay logic, but +/// reports the error. +/// +/// # Example +/// +/// ``` +/// # extern crate rand; +/// # extern crate rand_chacha; +/// # fn main() { +/// use rand::prelude::*; +/// use rand_chacha::ChaChaCore; // Internal part of ChaChaRng that +/// // implements BlockRngCore +/// use rand::rngs::OsRng; +/// use rand::rngs::adapter::ReseedingRng; +/// +/// let prng = ChaChaCore::from_entropy(); +// FIXME: it is better to use EntropyRng as reseeder, but that doesn't implement +// clone yet. +/// let reseeder = OsRng::new().unwrap(); +/// let mut reseeding_rng = ReseedingRng::new(prng, 0, reseeder); +/// +/// println!("{}", reseeding_rng.gen::()); +/// +/// let mut cloned_rng = reseeding_rng.clone(); +/// assert!(reseeding_rng.gen::() != cloned_rng.gen::()); +/// # } +/// ``` +/// +/// [`ChaChaCore`]: rand_chacha::ChaChaCore +/// [`Hc128Core`]: rand_hc::Hc128Core +/// [`BlockRngCore`]: rand_core::block::BlockRngCore +/// [`ReseedingRng::new`]: ReseedingRng::new +/// [`reseed()`]: ReseedingRng::reseed +#[derive(Debug)] +pub struct ReseedingRng(BlockRng>) +where R: BlockRngCore + SeedableRng, + Rsdr: RngCore; + +impl ReseedingRng +where R: BlockRngCore + SeedableRng, + Rsdr: RngCore +{ + /// Create a new `ReseedingRng` from an existing PRNG, combined with a RNG + /// to use as reseeder. + /// + /// `threshold` sets the number of generated bytes after which to reseed the + /// PRNG. Set it to zero to never reseed based on the number of generated + /// values. + pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { + ReseedingRng(BlockRng::new(ReseedingCore::new(rng, threshold, reseeder))) + } + + /// Reseed the internal PRNG. + pub fn reseed(&mut self) -> Result<(), Error> { + self.0.core.reseed() + } +} + +// TODO: this should be implemented for any type where the inner type +// implements RngCore, but we can't specify that because ReseedingCore is private +impl RngCore for ReseedingRng +where R: BlockRngCore + SeedableRng, + ::Results: AsRef<[u32]> + AsMut<[u32]> +{ + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl Clone for ReseedingRng +where R: BlockRngCore + SeedableRng + Clone, + Rsdr: RngCore + Clone +{ + fn clone(&self) -> ReseedingRng { + // Recreating `BlockRng` seems easier than cloning it and resetting + // the index. + ReseedingRng(BlockRng::new(self.0.core.clone())) + } +} + +impl CryptoRng for ReseedingRng +where R: BlockRngCore + SeedableRng + CryptoRng, + Rsdr: RngCore + CryptoRng {} + +#[derive(Debug)] +struct ReseedingCore { + inner: R, + reseeder: Rsdr, + threshold: i64, + bytes_until_reseed: i64, + fork_counter: usize, +} + +impl BlockRngCore for ReseedingCore +where R: BlockRngCore + SeedableRng, + Rsdr: RngCore +{ + type Item = ::Item; + type Results = ::Results; + + fn generate(&mut self, results: &mut Self::Results) { + let global_fork_counter = fork::get_fork_counter(); + if self.bytes_until_reseed <= 0 || + self.is_forked(global_fork_counter) { + // We get better performance by not calling only `reseed` here + // and continuing with the rest of the function, but by directly + // returning from a non-inlined function. + return self.reseed_and_generate(results, global_fork_counter); + } + let num_bytes = results.as_ref().len() * size_of::(); + self.bytes_until_reseed -= num_bytes as i64; + self.inner.generate(results); + } +} + +impl ReseedingCore +where R: BlockRngCore + SeedableRng, + Rsdr: RngCore +{ + /// Create a new `ReseedingCore`. + fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { + use ::core::i64::MAX; + fork::register_fork_handler(); + + // Because generating more values than `i64::MAX` takes centuries on + // current hardware, we just clamp to that value. + // Also we set a threshold of 0, which indicates no limit, to that + // value. + let threshold = + if threshold == 0 { MAX } + else if threshold <= MAX as u64 { threshold as i64 } + else { MAX }; + + ReseedingCore { + inner: rng, + reseeder, + threshold: threshold as i64, + bytes_until_reseed: threshold as i64, + fork_counter: 0, + } + } + + /// Reseed the internal PRNG. + fn reseed(&mut self) -> Result<(), Error> { + R::from_rng(&mut self.reseeder).map(|result| { + self.bytes_until_reseed = self.threshold; + self.inner = result + }) + } + + fn is_forked(&self, global_fork_counter: usize) -> bool { + // In theory, on 32-bit platforms, it is possible for + // `global_fork_counter` to wrap around after ~4e9 forks. + // + // This check will detect a fork in the normal case where + // `fork_counter < global_fork_counter`, and also when the difference + // between both is greater than `isize::MAX` (wrapped around). + // + // It will still fail to detect a fork if there have been more than + // `isize::MAX` forks, without any reseed in between. Seems unlikely + // enough. + (self.fork_counter.wrapping_sub(global_fork_counter) as isize) < 0 + } + + #[inline(never)] + fn reseed_and_generate(&mut self, + results: &mut ::Results, + global_fork_counter: usize) + { + if self.is_forked(global_fork_counter) { + info!("Fork detected, reseeding RNG"); + } else { + trace!("Reseeding RNG (periodic reseed)"); + } + + let num_bytes = + results.as_ref().len() * size_of::<::Item>(); + + let threshold = if let Err(e) = self.reseed() { + let delay = match e.kind { + ErrorKind::Transient => num_bytes as i64, + kind @ _ if kind.should_retry() => self.threshold >> 8, + _ => self.threshold, + }; + warn!("Reseeding RNG delayed reseeding by {} bytes due to \ + error from source: {}", delay, e); + delay + } else { + self.fork_counter = global_fork_counter; + self.threshold + }; + + self.bytes_until_reseed = threshold - num_bytes as i64; + self.inner.generate(results); + } +} + +impl Clone for ReseedingCore +where R: BlockRngCore + SeedableRng + Clone, + Rsdr: RngCore + Clone +{ + fn clone(&self) -> ReseedingCore { + ReseedingCore { + inner: self.inner.clone(), + reseeder: self.reseeder.clone(), + threshold: self.threshold, + bytes_until_reseed: 0, // reseed clone on first use + fork_counter: self.fork_counter, + } + } +} + +impl CryptoRng for ReseedingCore +where R: BlockRngCore + SeedableRng + CryptoRng, + Rsdr: RngCore + CryptoRng {} + + +#[cfg(all(feature="std", unix, not(target_os="emscripten")))] +mod fork { + extern crate libc; + + use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; + use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT}; + + // Fork protection + // + // We implement fork protection on Unix using `pthread_atfork`. + // When the process is forked, we increment `RESEEDING_RNG_FORK_COUNTER`. + // Every `ReseedingRng` stores the last known value of the static in + // `fork_counter`. If the cached `fork_counter` is less than + // `RESEEDING_RNG_FORK_COUNTER`, it is time to reseed this RNG. + // + // If reseeding fails, we don't deal with this by setting a delay, but just + // don't update `fork_counter`, so a reseed is attempted as soon as + // possible. + + static RESEEDING_RNG_FORK_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; + + pub fn get_fork_counter() -> usize { + RESEEDING_RNG_FORK_COUNTER.load(Ordering::Relaxed) + } + + static FORK_HANDLER_REGISTERED: AtomicBool = ATOMIC_BOOL_INIT; + + extern fn fork_handler() { + // Note: fetch_add is defined to wrap on overflow + // (which is what we want). + RESEEDING_RNG_FORK_COUNTER.fetch_add(1, Ordering::Relaxed); + } + + pub fn register_fork_handler() { + if FORK_HANDLER_REGISTERED.load(Ordering::Relaxed) == false { + unsafe { libc::pthread_atfork(None, None, Some(fork_handler)) }; + FORK_HANDLER_REGISTERED.store(true, Ordering::Relaxed); + } + } +} + +#[cfg(not(all(feature="std", unix, not(target_os="emscripten"))))] +mod fork { + pub fn get_fork_counter() -> usize { 0 } + pub fn register_fork_handler() {} +} + + +#[cfg(test)] +mod test { + use {Rng, SeedableRng}; + use rand_chacha::ChaChaCore; + use rngs::mock::StepRng; + use super::ReseedingRng; + + #[test] + fn test_reseeding() { + let mut zero = StepRng::new(0, 0); + let rng = ChaChaCore::from_rng(&mut zero).unwrap(); + let mut reseeding = ReseedingRng::new(rng, 32*4, zero); + + // Currently we only support for arrays up to length 32. + // TODO: cannot generate seq via Rng::gen because it uses different alg + let mut buf = [0u32; 32]; // Needs to be a multiple of the RNGs result + // size to test exactly. + reseeding.fill(&mut buf); + let seq = buf; + for _ in 0..10 { + reseeding.fill(&mut buf); + assert_eq!(buf, seq); + } + } + + #[test] + fn test_clone_reseeding() { + let mut zero = StepRng::new(0, 0); + let rng = ChaChaCore::from_rng(&mut zero).unwrap(); + let mut rng1 = ReseedingRng::new(rng, 32*4, zero); + + let first: u32 = rng1.gen(); + for _ in 0..10 { let _ = rng1.gen::(); } + + let mut rng2 = rng1.clone(); + assert_eq!(first, rng2.gen::()); + } +} diff --git a/bash-5.1/vendor/rand/src/rngs/entropy.rs b/bash-5.1/vendor/rand/src/rngs/entropy.rs new file mode 100644 index 0000000..9a2affd --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/entropy.rs @@ -0,0 +1,248 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Entropy generator, or wrapper around external generators + +use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; +#[allow(unused)] +use rngs; + +/// An interface returning random data from external source(s), provided +/// specifically for securely seeding algorithmic generators (PRNGs). +/// +/// Where possible, `EntropyRng` retrieves random data from the operating +/// system's interface for random numbers ([`OsRng`]); if that fails it will +/// fall back to the [`JitterRng`] entropy collector. In the latter case it will +/// still try to use [`OsRng`] on the next usage. +/// +/// If no secure source of entropy is available `EntropyRng` will panic on use; +/// i.e. it should never output predictable data. +/// +/// This is either a little slow ([`OsRng`] requires a system call) or extremely +/// slow ([`JitterRng`] must use significant CPU time to generate sufficient +/// jitter); for better performance it is common to seed a local PRNG from +/// external entropy then primarily use the local PRNG ([`thread_rng`] is +/// provided as a convenient, local, automatically-seeded CSPRNG). +/// +/// # Panics +/// +/// On most systems, like Windows, Linux, macOS and *BSD on common hardware, it +/// is highly unlikely for both [`OsRng`] and [`JitterRng`] to fail. But on +/// combinations like webassembly without Emscripten or stdweb both sources are +/// unavailable. If both sources fail, only [`try_fill_bytes`] is able to +/// report the error, and only the one from `OsRng`. The other [`RngCore`] +/// methods will panic in case of an error. +/// +/// [`OsRng`]: rand_os::OsRng +/// [`thread_rng`]: crate::thread_rng +/// [`JitterRng`]: crate::rngs::JitterRng +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Debug)] +pub struct EntropyRng { + source: Source, +} + +#[derive(Debug)] +enum Source { + Os(Os), + Custom(Custom), + Jitter(Jitter), + None, +} + +impl EntropyRng { + /// Create a new `EntropyRng`. + /// + /// This method will do no system calls or other initialization routines, + /// those are done on first use. This is done to make `new` infallible, + /// and `try_fill_bytes` the only place to report errors. + pub fn new() -> Self { + EntropyRng { source: Source::None } + } +} + +impl Default for EntropyRng { + fn default() -> Self { + EntropyRng::new() + } +} + +impl RngCore for EntropyRng { + fn next_u32(&mut self) -> u32 { + impls::next_u32_via_fill(self) + } + + fn next_u64(&mut self) -> u64 { + impls::next_u64_via_fill(self) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.try_fill_bytes(dest).unwrap_or_else(|err| + panic!("all entropy sources failed; first error: {}", err)) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + let mut reported_error = None; + + if let Source::Os(ref mut os_rng) = self.source { + match os_rng.fill(dest) { + Ok(()) => return Ok(()), + Err(err) => { + warn!("EntropyRng: OsRng failed \ + [trying other entropy sources]: {}", err); + reported_error = Some(err); + }, + } + } else if Os::is_supported() { + match Os::new_and_fill(dest) { + Ok(os_rng) => { + debug!("EntropyRng: using OsRng"); + self.source = Source::Os(os_rng); + return Ok(()); + }, + Err(err) => { reported_error = reported_error.or(Some(err)) }, + } + } + + if let Source::Custom(ref mut rng) = self.source { + match rng.fill(dest) { + Ok(()) => return Ok(()), + Err(err) => { + warn!("EntropyRng: custom entropy source failed \ + [trying other entropy sources]: {}", err); + reported_error = Some(err); + }, + } + } else if Custom::is_supported() { + match Custom::new_and_fill(dest) { + Ok(custom) => { + debug!("EntropyRng: using custom entropy source"); + self.source = Source::Custom(custom); + return Ok(()); + }, + Err(err) => { reported_error = reported_error.or(Some(err)) }, + } + } + + if let Source::Jitter(ref mut jitter_rng) = self.source { + match jitter_rng.fill(dest) { + Ok(()) => return Ok(()), + Err(err) => { + warn!("EntropyRng: JitterRng failed: {}", err); + reported_error = Some(err); + }, + } + } else if Jitter::is_supported() { + match Jitter::new_and_fill(dest) { + Ok(jitter_rng) => { + debug!("EntropyRng: using JitterRng"); + self.source = Source::Jitter(jitter_rng); + return Ok(()); + }, + Err(err) => { reported_error = reported_error.or(Some(err)) }, + } + } + + if let Some(err) = reported_error { + Err(Error::with_cause(ErrorKind::Unavailable, + "All entropy sources failed", + err)) + } else { + Err(Error::new(ErrorKind::Unavailable, + "No entropy sources available")) + } + } +} + +impl CryptoRng for EntropyRng {} + + + +trait EntropySource { + fn new_and_fill(dest: &mut [u8]) -> Result + where Self: Sized; + + fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error>; + + fn is_supported() -> bool { true } +} + +#[allow(unused)] +#[derive(Clone, Debug)] +struct NoSource; + +#[allow(unused)] +impl EntropySource for NoSource { + fn new_and_fill(dest: &mut [u8]) -> Result { + Err(Error::new(ErrorKind::Unavailable, "Source not supported")) + } + + fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { + unreachable!() + } + + fn is_supported() -> bool { false } +} + + +#[cfg(feature="rand_os")] +#[derive(Clone, Debug)] +pub struct Os(rngs::OsRng); + +#[cfg(feature="rand_os")] +impl EntropySource for Os { + fn new_and_fill(dest: &mut [u8]) -> Result { + let mut rng = rngs::OsRng::new()?; + rng.try_fill_bytes(dest)?; + Ok(Os(rng)) + } + + fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +#[cfg(not(feature="std"))] +type Os = NoSource; + + +type Custom = NoSource; + + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug)] +pub struct Jitter(rngs::JitterRng); + +#[cfg(not(target_arch = "wasm32"))] +impl EntropySource for Jitter { + fn new_and_fill(dest: &mut [u8]) -> Result { + let mut rng = rngs::JitterRng::new()?; + rng.try_fill_bytes(dest)?; + Ok(Jitter(rng)) + } + + fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +#[cfg(target_arch = "wasm32")] +type Jitter = NoSource; + + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_entropy() { + let mut rng = EntropyRng::new(); + let n = (rng.next_u32() ^ rng.next_u32()).count_ones(); + assert!(n >= 2); // p(failure) approx 1e-7 + } +} diff --git a/bash-5.1/vendor/rand/src/rngs/mock.rs b/bash-5.1/vendor/rand/src/rngs/mock.rs new file mode 100644 index 0000000..3c9a994 --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/mock.rs @@ -0,0 +1,59 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Mock random number generator + +use rand_core::{RngCore, Error, impls}; + +/// A simple implementation of `RngCore` for testing purposes. +/// +/// This generates an arithmetic sequence (i.e. adds a constant each step) +/// over a `u64` number, using wrapping arithmetic. If the increment is 0 +/// the generator yields a constant. +/// +/// ``` +/// use rand::Rng; +/// use rand::rngs::mock::StepRng; +/// +/// let mut my_rng = StepRng::new(2, 1); +/// let sample: [u64; 3] = my_rng.gen(); +/// assert_eq!(sample, [2, 3, 4]); +/// ``` +#[derive(Debug, Clone)] +pub struct StepRng { + v: u64, + a: u64, +} + +impl StepRng { + /// Create a `StepRng`, yielding an arithmetic sequence starting with + /// `initial` and incremented by `increment` each time. + pub fn new(initial: u64, increment: u64) -> Self { + StepRng { v: initial, a: increment } + } +} + +impl RngCore for StepRng { + fn next_u32(&mut self) -> u32 { + self.next_u64() as u32 + } + + fn next_u64(&mut self) -> u64 { + let result = self.v; + self.v = self.v.wrapping_add(self.a); + result + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + impls::fill_bytes_via_next(self, dest); + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} diff --git a/bash-5.1/vendor/rand/src/rngs/mod.rs b/bash-5.1/vendor/rand/src/rngs/mod.rs new file mode 100644 index 0000000..b3f05a0 --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/mod.rs @@ -0,0 +1,167 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Random number generators and adapters for common usage: +//! +//! - [`ThreadRng`], a fast, secure, auto-seeded thread-local generator +//! - [`StdRng`] and [`SmallRng`], algorithms to cover typical usage +//! - [`EntropyRng`], [`OsRng`] and [`JitterRng`] as entropy sources +//! - [`mock::StepRng`] as a simple counter for tests +//! - [`adapter::ReadRng`] to read from a file/stream +//! - [`adapter::ReseedingRng`] to reseed a PRNG on clone / process fork etc. +//! +//! # Background — Random number generators (RNGs) +//! +//! Computers are inherently deterministic, so to get *random* numbers one +//! either has to use a hardware generator or collect bits of *entropy* from +//! various sources (e.g. event timestamps, or jitter). This is a relatively +//! slow and complicated operation. +//! +//! Generally the operating system will collect some entropy, remove bias, and +//! use that to seed its own PRNG; [`OsRng`] provides an interface to this. +//! [`JitterRng`] is an entropy collector included with Rand that measures +//! jitter in the CPU execution time, and jitter in memory access time. +//! [`EntropyRng`] is a wrapper that uses the best entropy source that is +//! available. +//! +//! ## Pseudo-random number generators +//! +//! What is commonly used instead of "true" random number renerators, are +//! *pseudo-random number generators* (PRNGs), deterministic algorithms that +//! produce an infinite stream of pseudo-random numbers from a small random +//! seed. PRNGs are faster, and have better provable properties. The numbers +//! produced can be statistically of very high quality and can be impossible to +//! predict. (They can also have obvious correlations and be trivial to predict; +//! quality varies.) +//! +//! There are two different types of PRNGs: those developed for simulations +//! and statistics, and those developed for use in cryptography; the latter are +//! called Cryptographically Secure PRNGs (CSPRNG or CPRNG). Both types can +//! have good statistical quality but the latter also have to be impossible to +//! predict, even after seeing many previous output values. Rand provides a good +//! default algorithm from each class: +//! +//! - [`SmallRng`] is a PRNG chosen for low memory usage, high performance and +//! good statistical quality. +//! - [`StdRng`] is a CSPRNG chosen for good performance and trust of security +//! (based on reviews, maturity and usage). The current algorithm is HC-128, +//! which is one of the recommendations by ECRYPT's eSTREAM project. +//! +//! The above PRNGs do not cover all use-cases; more algorithms can be found in +//! the [`prng`][crate::prng] module, as well as in several other crates. For example, you +//! may wish a CSPRNG with significantly lower memory usage than [`StdRng`] +//! while being less concerned about performance, in which case [`ChaChaRng`] +//! is a good choice. +//! +//! One complexity is that the internal state of a PRNG must change with every +//! generated number. For APIs this generally means a mutable reference to the +//! state of the PRNG has to be passed around. +//! +//! A solution is [`ThreadRng`]. This is a thread-local implementation of +//! [`StdRng`] with automatic seeding on first use. It is the best choice if you +//! "just" want a convenient, secure, fast random number source. Use via the +//! [`thread_rng`] function, which gets a reference to the current thread's +//! local instance. +//! +//! ## Seeding +//! +//! As mentioned above, PRNGs require a random seed in order to produce random +//! output. This is especially important for CSPRNGs, which are still +//! deterministic algorithms, thus can only be secure if their seed value is +//! also secure. To seed a PRNG, use one of: +//! +//! - [`FromEntropy::from_entropy`]; this is the most convenient way to seed +//! with fresh, secure random data. +//! - [`SeedableRng::from_rng`]; this allows seeding from another PRNG or +//! from an entropy source such as [`EntropyRng`]. +//! - [`SeedableRng::from_seed`]; this is mostly useful if you wish to be able +//! to reproduce the output sequence by using a fixed seed. (Don't use +//! [`StdRng`] or [`SmallRng`] in this case since different algorithms may be +//! used by future versions of Rand; use an algorithm from the +//! [`prng`] module.) +//! +//! ## Conclusion +//! +//! - [`thread_rng`] is what you often want to use. +//! - If you want more control, flexibility, or better performance, use +//! [`StdRng`], [`SmallRng`] or an algorithm from the [`prng`] module. +//! - Use [`FromEntropy::from_entropy`] to seed new PRNGs. +//! - If you need reproducibility, use [`SeedableRng::from_seed`] combined with +//! a named PRNG. +//! +//! More information and notes on cryptographic security can be found +//! in the [`prng`] module. +//! +//! ## Examples +//! +//! Examples of seeding PRNGs: +//! +//! ``` +//! use rand::prelude::*; +//! # use rand::Error; +//! +//! // StdRng seeded securely by the OS or local entropy collector: +//! let mut rng = StdRng::from_entropy(); +//! # let v: u32 = rng.gen(); +//! +//! // SmallRng seeded from thread_rng: +//! # fn try_inner() -> Result<(), Error> { +//! let mut rng = SmallRng::from_rng(thread_rng())?; +//! # let v: u32 = rng.gen(); +//! # Ok(()) +//! # } +//! # try_inner().unwrap(); +//! +//! // SmallRng seeded by a constant, for deterministic results: +//! let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; // byte array +//! let mut rng = SmallRng::from_seed(seed); +//! # let v: u32 = rng.gen(); +//! ``` +//! +//! +//! # Implementing custom RNGs +//! +//! If you want to implement custom RNG, see the [`rand_core`] crate. The RNG +//! will have to implement the [`RngCore`] trait, where the [`Rng`] trait is +//! build on top of. +//! +//! If the RNG needs seeding, also implement the [`SeedableRng`] trait. +//! +//! [`CryptoRng`] is a marker trait cryptographically secure PRNGs can +//! implement. +//! +//! [`OsRng`]: rand_os::OsRng +//! [`SmallRng`]: rngs::SmallRng +//! [`StdRng`]: rngs::StdRng +//! [`ThreadRng`]: rngs::ThreadRng +//! [`EntropyRng`]: rngs::EntropyRng +//! [`JitterRng`]: rngs::JitterRng +//! [`mock::StepRng`]: rngs::mock::StepRng +//! [`adapter::ReadRng`]: rngs::adapter::ReadRng +//! [`adapter::ReseedingRng`]: rngs::adapter::ReseedingRng +//! [`ChaChaRng`]: rand_chacha::ChaChaRng + +pub mod adapter; + +#[cfg(feature="std")] mod entropy; +pub mod mock; // Public so we don't export `StepRng` directly, making it a bit + // more clear it is intended for testing. +mod small; +mod std; +#[cfg(feature="std")] pub(crate) mod thread; + + +pub use rand_jitter::{JitterRng, TimerError}; +#[cfg(feature="std")] pub use self::entropy::EntropyRng; + +pub use self::small::SmallRng; +pub use self::std::StdRng; +#[cfg(feature="std")] pub use self::thread::ThreadRng; + +#[cfg(feature="rand_os")] +pub use rand_os::OsRng; diff --git a/bash-5.1/vendor/rand/src/rngs/small.rs b/bash-5.1/vendor/rand/src/rngs/small.rs new file mode 100644 index 0000000..9874d24 --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/small.rs @@ -0,0 +1,106 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A small fast RNG + +use {RngCore, SeedableRng, Error}; + +#[cfg(all(all(rustc_1_26, not(target_os = "emscripten")), target_pointer_width = "64"))] +type Rng = ::rand_pcg::Pcg64Mcg; +#[cfg(not(all(all(rustc_1_26, not(target_os = "emscripten")), target_pointer_width = "64")))] +type Rng = ::rand_pcg::Pcg32; + +/// An RNG recommended when small state, cheap initialization and good +/// performance are required. The PRNG algorithm in `SmallRng` is chosen to be +/// efficient on the current platform, **without consideration for cryptography +/// or security**. The size of its state is much smaller than for [`StdRng`]. +/// +/// Reproducibility of output from this generator is however not required, thus +/// future library versions may use a different internal generator with +/// different output. Further, this generator may not be portable and can +/// produce different output depending on the architecture. If you require +/// reproducible output, use a named RNG. +/// Refer to [The Book](https://rust-random.github.io/book/guide-rngs.html). +/// +/// +/// The current algorithm is [`Pcg64Mcg`][rand_pcg::Pcg64Mcg] on 64-bit platforms with Rust version +/// 1.26 and later, or [`Pcg32`][rand_pcg::Pcg32] otherwise. Both are found in +/// the [rand_pcg] crate. +/// +/// # Examples +/// +/// Initializing `SmallRng` with a random seed can be done using [`FromEntropy`]: +/// +/// ``` +/// # use rand::Rng; +/// use rand::FromEntropy; +/// use rand::rngs::SmallRng; +/// +/// // Create small, cheap to initialize and fast RNG with a random seed. +/// // The randomness is supplied by the operating system. +/// let mut small_rng = SmallRng::from_entropy(); +/// # let v: u32 = small_rng.gen(); +/// ``` +/// +/// When initializing a lot of `SmallRng`'s, using [`thread_rng`] can be more +/// efficient: +/// +/// ``` +/// use std::iter; +/// use rand::{SeedableRng, thread_rng}; +/// use rand::rngs::SmallRng; +/// +/// // Create a big, expensive to initialize and slower, but unpredictable RNG. +/// // This is cached and done only once per thread. +/// let mut thread_rng = thread_rng(); +/// // Create small, cheap to initialize and fast RNGs with random seeds. +/// // One can generally assume this won't fail. +/// let rngs: Vec = iter::repeat(()) +/// .map(|()| SmallRng::from_rng(&mut thread_rng).unwrap()) +/// .take(10) +/// .collect(); +/// ``` +/// +/// [`FromEntropy`]: crate::FromEntropy +/// [`StdRng`]: crate::rngs::StdRng +/// [`thread_rng`]: crate::thread_rng +/// [rand_pcg]: https://crates.io/crates/rand_pcg +#[derive(Clone, Debug)] +pub struct SmallRng(Rng); + +impl RngCore for SmallRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for SmallRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + SmallRng(Rng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + Rng::from_rng(rng).map(SmallRng) + } +} diff --git a/bash-5.1/vendor/rand/src/rngs/std.rs b/bash-5.1/vendor/rand/src/rngs/std.rs new file mode 100644 index 0000000..e67a76d --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/std.rs @@ -0,0 +1,85 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The standard RNG + +use {RngCore, CryptoRng, Error, SeedableRng}; +use rand_hc::Hc128Rng; + +/// The standard RNG. The PRNG algorithm in `StdRng` is chosen to be efficient +/// on the current platform, to be statistically strong and unpredictable +/// (meaning a cryptographically secure PRNG). +/// +/// The current algorithm used on all platforms is [HC-128], found in the +/// [rand_hc] crate. +/// +/// Reproducibility of output from this generator is however not required, thus +/// future library versions may use a different internal generator with +/// different output. Further, this generator may not be portable and can +/// produce different output depending on the architecture. If you require +/// reproducible output, use a named RNG, for example [`ChaChaRng`] from the +/// [rand_chacha] crate. +/// +/// [HC-128]: rand_hc::Hc128Rng +/// [`ChaChaRng`]: rand_chacha::ChaChaRng +/// [rand_hc]: https://crates.io/crates/rand_hc +/// [rand_chacha]: https://crates.io/crates/rand_chacha +#[derive(Clone, Debug)] +pub struct StdRng(Hc128Rng); + +impl RngCore for StdRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest); + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for StdRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + StdRng(Hc128Rng::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + Hc128Rng::from_rng(rng).map(StdRng) + } +} + +impl CryptoRng for StdRng {} + + +#[cfg(test)] +mod test { + use {RngCore, SeedableRng}; + use rngs::StdRng; + + #[test] + fn test_stdrng_construction() { + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng1 = StdRng::from_seed(seed); + assert_eq!(rng1.next_u64(), 15759097995037006553); + + let mut rng2 = StdRng::from_rng(rng1).unwrap(); + assert_eq!(rng2.next_u64(), 6766915756997287454); + } +} diff --git a/bash-5.1/vendor/rand/src/rngs/thread.rs b/bash-5.1/vendor/rand/src/rngs/thread.rs new file mode 100644 index 0000000..f1aa787 --- /dev/null +++ b/bash-5.1/vendor/rand/src/rngs/thread.rs @@ -0,0 +1,137 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Thread-local random number generator + +use std::cell::UnsafeCell; + +use {RngCore, CryptoRng, SeedableRng, Error}; +use rngs::adapter::ReseedingRng; +use rngs::EntropyRng; +use rand_hc::Hc128Core; + +// Rationale for using `UnsafeCell` in `ThreadRng`: +// +// Previously we used a `RefCell`, with an overhead of ~15%. There will only +// ever be one mutable reference to the interior of the `UnsafeCell`, because +// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a +// single thread (which is the definition of `ThreadRng`), there will only ever +// be one of these methods active at a time. +// +// A possible scenario where there could be multiple mutable references is if +// `ThreadRng` is used inside `next_u32` and co. But the implementation is +// completely under our control. We just have to ensure none of them use +// `ThreadRng` internally, which is nonsensical anyway. We should also never run +// `ThreadRng` in destructors of its implementation, which is also nonsensical. +// +// The additional `Rc` is not strictly neccesary, and could be removed. For now +// it ensures `ThreadRng` stays `!Send` and `!Sync`, and implements `Clone`. + + +// Number of generated bytes after which to reseed `TreadRng`. +// +// The time it takes to reseed HC-128 is roughly equivalent to generating 7 KiB. +// We pick a treshold here that is large enough to not reduce the average +// performance too much, but also small enough to not make reseeding something +// that basically never happens. +const THREAD_RNG_RESEED_THRESHOLD: u64 = 32*1024*1024; // 32 MiB + +/// The type returned by [`thread_rng`], essentially just a reference to the +/// PRNG in thread-local memory. +/// +/// `ThreadRng` uses [`ReseedingRng`] wrapping the same PRNG as [`StdRng`], +/// which is reseeded after generating 32 MiB of random data. A single instance +/// is cached per thread and the returned `ThreadRng` is a reference to this +/// instance — hence `ThreadRng` is neither `Send` nor `Sync` but is safe to use +/// within a single thread. This RNG is seeded and reseeded via [`EntropyRng`] +/// as required. +/// +/// Note that the reseeding is done as an extra precaution against entropy +/// leaks and is in theory unnecessary — to predict `ThreadRng`'s output, an +/// attacker would have to either determine most of the RNG's seed or internal +/// state, or crack the algorithm used. +/// +/// Like [`StdRng`], `ThreadRng` is a cryptographically secure PRNG. The current +/// algorithm used is [HC-128], which is an array-based PRNG that trades memory +/// usage for better performance. This makes it similar to ISAAC, the algorithm +/// used in `ThreadRng` before rand 0.5. +/// +/// Cloning this handle just produces a new reference to the same thread-local +/// generator. +/// +/// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng +/// [`StdRng`]: crate::rngs::StdRng +/// [HC-128]: rand_hc::Hc128Rng +#[derive(Clone, Debug)] +pub struct ThreadRng { + // use of raw pointer implies type is neither Send nor Sync + rng: *mut ReseedingRng, +} + +thread_local!( + static THREAD_RNG_KEY: UnsafeCell> = { + let mut entropy_source = EntropyRng::new(); + let r = Hc128Core::from_rng(&mut entropy_source).unwrap_or_else(|err| + panic!("could not initialize thread_rng: {}", err)); + let rng = ReseedingRng::new(r, + THREAD_RNG_RESEED_THRESHOLD, + entropy_source); + UnsafeCell::new(rng) + } +); + +/// Retrieve the lazily-initialized thread-local random number generator, +/// seeded by the system. Intended to be used in method chaining style, +/// e.g. `thread_rng().gen::()`, or cached locally, e.g. +/// `let mut rng = thread_rng();`. Invoked by the `Default` trait, making +/// `ThreadRng::default()` equivelent. +/// +/// For more information see [`ThreadRng`]. +pub fn thread_rng() -> ThreadRng { + ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.get()) } +} + +impl Default for ThreadRng { + fn default() -> ThreadRng { + ::prelude::thread_rng() + } +} + +impl RngCore for ThreadRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + unsafe { (*self.rng).next_u32() } + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + unsafe { (*self.rng).next_u64() } + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + unsafe { (*self.rng).fill_bytes(dest) } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + unsafe { (*self.rng).try_fill_bytes(dest) } + } +} + +impl CryptoRng for ThreadRng {} + + +#[cfg(test)] +mod test { + #[test] + fn test_thread_rng() { + use Rng; + let mut r = ::thread_rng(); + r.gen::(); + assert_eq!(r.gen_range(0, 1), 0); + } +} diff --git a/bash-5.1/vendor/rand/src/seq/index.rs b/bash-5.1/vendor/rand/src/seq/index.rs new file mode 100644 index 0000000..a70c736 --- /dev/null +++ b/bash-5.1/vendor/rand/src/seq/index.rs @@ -0,0 +1,378 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Index sampling + +#[cfg(feature="alloc")] use core::slice; + +#[cfg(feature="std")] use std::vec; +#[cfg(all(feature="alloc", not(feature="std")))] use alloc::vec::{self, Vec}; +// BTreeMap is not as fast in tests, but better than nothing. +#[cfg(feature="std")] use std::collections::{HashSet}; +#[cfg(all(feature="alloc", not(feature="std")))] use alloc::collections::BTreeSet; + +#[cfg(feature="alloc")] use distributions::{Distribution, Uniform}; +use Rng; + +/// A vector of indices. +/// +/// Multiple internal representations are possible. +#[derive(Clone, Debug)] +pub enum IndexVec { + #[doc(hidden)] U32(Vec), + #[doc(hidden)] USize(Vec), +} + +impl IndexVec { + /// Returns the number of indices + pub fn len(&self) -> usize { + match self { + &IndexVec::U32(ref v) => v.len(), + &IndexVec::USize(ref v) => v.len(), + } + } + + /// Return the value at the given `index`. + /// + /// (Note: we cannot implement [`std::ops::Index`] because of lifetime + /// restrictions.) + pub fn index(&self, index: usize) -> usize { + match self { + &IndexVec::U32(ref v) => v[index] as usize, + &IndexVec::USize(ref v) => v[index], + } + } + + /// Return result as a `Vec`. Conversion may or may not be trivial. + pub fn into_vec(self) -> Vec { + match self { + IndexVec::U32(v) => v.into_iter().map(|i| i as usize).collect(), + IndexVec::USize(v) => v, + } + } + + /// Iterate over the indices as a sequence of `usize` values + pub fn iter<'a>(&'a self) -> IndexVecIter<'a> { + match self { + &IndexVec::U32(ref v) => IndexVecIter::U32(v.iter()), + &IndexVec::USize(ref v) => IndexVecIter::USize(v.iter()), + } + } + + /// Convert into an iterator over the indices as a sequence of `usize` values + pub fn into_iter(self) -> IndexVecIntoIter { + match self { + IndexVec::U32(v) => IndexVecIntoIter::U32(v.into_iter()), + IndexVec::USize(v) => IndexVecIntoIter::USize(v.into_iter()), + } + } +} + +impl PartialEq for IndexVec { + fn eq(&self, other: &IndexVec) -> bool { + use self::IndexVec::*; + match (self, other) { + (&U32(ref v1), &U32(ref v2)) => v1 == v2, + (&USize(ref v1), &USize(ref v2)) => v1 == v2, + (&U32(ref v1), &USize(ref v2)) => (v1.len() == v2.len()) + && (v1.iter().zip(v2.iter()).all(|(x, y)| *x as usize == *y)), + (&USize(ref v1), &U32(ref v2)) => (v1.len() == v2.len()) + && (v1.iter().zip(v2.iter()).all(|(x, y)| *x == *y as usize)), + } + } +} + +impl From> for IndexVec { + fn from(v: Vec) -> Self { + IndexVec::U32(v) + } +} + +impl From> for IndexVec { + fn from(v: Vec) -> Self { + IndexVec::USize(v) + } +} + +/// Return type of `IndexVec::iter`. +#[derive(Debug)] +pub enum IndexVecIter<'a> { + #[doc(hidden)] U32(slice::Iter<'a, u32>), + #[doc(hidden)] USize(slice::Iter<'a, usize>), +} + +impl<'a> Iterator for IndexVecIter<'a> { + type Item = usize; + fn next(&mut self) -> Option { + use self::IndexVecIter::*; + match self { + &mut U32(ref mut iter) => iter.next().map(|i| *i as usize), + &mut USize(ref mut iter) => iter.next().cloned(), + } + } + + fn size_hint(&self) -> (usize, Option) { + match self { + &IndexVecIter::U32(ref v) => v.size_hint(), + &IndexVecIter::USize(ref v) => v.size_hint(), + } + } +} + +impl<'a> ExactSizeIterator for IndexVecIter<'a> {} + +/// Return type of `IndexVec::into_iter`. +#[derive(Clone, Debug)] +pub enum IndexVecIntoIter { + #[doc(hidden)] U32(vec::IntoIter), + #[doc(hidden)] USize(vec::IntoIter), +} + +impl Iterator for IndexVecIntoIter { + type Item = usize; + + fn next(&mut self) -> Option { + use self::IndexVecIntoIter::*; + match self { + &mut U32(ref mut v) => v.next().map(|i| i as usize), + &mut USize(ref mut v) => v.next(), + } + } + + fn size_hint(&self) -> (usize, Option) { + use self::IndexVecIntoIter::*; + match self { + &U32(ref v) => v.size_hint(), + &USize(ref v) => v.size_hint(), + } + } +} + +impl ExactSizeIterator for IndexVecIntoIter {} + + +/// Randomly sample exactly `amount` distinct indices from `0..length`, and +/// return them in random order (fully shuffled). +/// +/// This method is used internally by the slice sampling methods, but it can +/// sometimes be useful to have the indices themselves so this is provided as +/// an alternative. +/// +/// The implementation used is not specified; we automatically select the +/// fastest available algorithm for the `length` and `amount` parameters +/// (based on detailed profiling on an Intel Haswell CPU). Roughly speaking, +/// complexity is `O(amount)`, except that when `amount` is small, performance +/// is closer to `O(amount^2)`, and when `length` is close to `amount` then +/// `O(length)`. +/// +/// Note that performance is significantly better over `u32` indices than over +/// `u64` indices. Because of this we hide the underlying type behind an +/// abstraction, `IndexVec`. +/// +/// If an allocation-free `no_std` function is required, it is suggested +/// to adapt the internal `sample_floyd` implementation. +/// +/// Panics if `amount > length`. +pub fn sample(rng: &mut R, length: usize, amount: usize) -> IndexVec + where R: Rng + ?Sized, +{ + if amount > length { + panic!("`amount` of samples must be less than or equal to `length`"); + } + if length > (::core::u32::MAX as usize) { + // We never want to use inplace here, but could use floyd's alg + // Lazy version: always use the cache alg. + return sample_rejection(rng, length, amount); + } + let amount = amount as u32; + let length = length as u32; + + // Choice of algorithm here depends on both length and amount. See: + // https://github.com/rust-random/rand/pull/479 + // We do some calculations with f32. Accuracy is not very important. + + if amount < 163 { + const C: [[f32; 2]; 2] = [[1.6, 8.0/45.0], [10.0, 70.0/9.0]]; + let j = if length < 500_000 { 0 } else { 1 }; + let amount_fp = amount as f32; + let m4 = C[0][j] * amount_fp; + // Short-cut: when amount < 12, floyd's is always faster + if amount > 11 && (length as f32) < (C[1][j] + m4) * amount_fp { + sample_inplace(rng, length, amount) + } else { + sample_floyd(rng, length, amount) + } + } else { + const C: [f32; 2] = [270.0, 330.0/9.0]; + let j = if length < 500_000 { 0 } else { 1 }; + if (length as f32) < C[j] * (amount as f32) { + sample_inplace(rng, length, amount) + } else { + // note: could have a specific u32 impl, but I'm lazy and + // generics don't have usable conversions + sample_rejection(rng, length as usize, amount as usize) + } + } +} + +/// Randomly sample exactly `amount` indices from `0..length`, using Floyd's +/// combination algorithm. +/// +/// The output values are fully shuffled. (Overhead is under 50%.) +/// +/// This implementation uses `O(amount)` memory and `O(amount^2)` time. +fn sample_floyd(rng: &mut R, length: u32, amount: u32) -> IndexVec + where R: Rng + ?Sized, +{ + // For small amount we use Floyd's fully-shuffled variant. For larger + // amounts this is slow due to Vec::insert performance, so we shuffle + // afterwards. Benchmarks show little overhead from extra logic. + let floyd_shuffle = amount < 50; + + debug_assert!(amount <= length); + let mut indices = Vec::with_capacity(amount as usize); + for j in length - amount .. length { + let t = rng.gen_range(0, j + 1); + if floyd_shuffle { + if let Some(pos) = indices.iter().position(|&x| x == t) { + indices.insert(pos, j); + continue; + } + } else { + if indices.contains(&t) { + indices.push(j); + continue; + } + } + indices.push(t); + } + if !floyd_shuffle { + // Reimplement SliceRandom::shuffle with smaller indices + for i in (1..amount).rev() { + // invariant: elements with index > i have been locked in place. + indices.swap(i as usize, rng.gen_range(0, i + 1) as usize); + } + } + IndexVec::from(indices) +} + +/// Randomly sample exactly `amount` indices from `0..length`, using an inplace +/// partial Fisher-Yates method. +/// Sample an amount of indices using an inplace partial fisher yates method. +/// +/// This allocates the entire `length` of indices and randomizes only the first `amount`. +/// It then truncates to `amount` and returns. +/// +/// This method is not appropriate for large `length` and potentially uses a lot +/// of memory; because of this we only implement for `u32` index (which improves +/// performance in all cases). +/// +/// Set-up is `O(length)` time and memory and shuffling is `O(amount)` time. +fn sample_inplace(rng: &mut R, length: u32, amount: u32) -> IndexVec + where R: Rng + ?Sized, +{ + debug_assert!(amount <= length); + let mut indices: Vec = Vec::with_capacity(length as usize); + indices.extend(0..length); + for i in 0..amount { + let j: u32 = rng.gen_range(i, length); + indices.swap(i as usize, j as usize); + } + indices.truncate(amount as usize); + debug_assert_eq!(indices.len(), amount as usize); + IndexVec::from(indices) +} + +/// Randomly sample exactly `amount` indices from `0..length`, using rejection +/// sampling. +/// +/// Since `amount <<< length` there is a low chance of a random sample in +/// `0..length` being a duplicate. We test for duplicates and resample where +/// necessary. The algorithm is `O(amount)` time and memory. +fn sample_rejection(rng: &mut R, length: usize, amount: usize) -> IndexVec + where R: Rng + ?Sized, +{ + debug_assert!(amount < length); + #[cfg(feature="std")] let mut cache = HashSet::with_capacity(amount); + #[cfg(not(feature="std"))] let mut cache = BTreeSet::new(); + let distr = Uniform::new(0, length); + let mut indices = Vec::with_capacity(amount); + for _ in 0..amount { + let mut pos = distr.sample(rng); + while !cache.insert(pos) { + pos = distr.sample(rng); + } + indices.push(pos); + } + + debug_assert_eq!(indices.len(), amount); + IndexVec::from(indices) +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_sample_boundaries() { + let mut r = ::test::rng(404); + + assert_eq!(sample_inplace(&mut r, 0, 0).len(), 0); + assert_eq!(sample_inplace(&mut r, 1, 0).len(), 0); + assert_eq!(sample_inplace(&mut r, 1, 1).into_vec(), vec![0]); + + assert_eq!(sample_rejection(&mut r, 1, 0).len(), 0); + + assert_eq!(sample_floyd(&mut r, 0, 0).len(), 0); + assert_eq!(sample_floyd(&mut r, 1, 0).len(), 0); + assert_eq!(sample_floyd(&mut r, 1, 1).into_vec(), vec![0]); + + // These algorithms should be fast with big numbers. Test average. + let sum: usize = sample_rejection(&mut r, 1 << 25, 10) + .into_iter().sum(); + assert!(1 << 25 < sum && sum < (1 << 25) * 25); + + let sum: usize = sample_floyd(&mut r, 1 << 25, 10) + .into_iter().sum(); + assert!(1 << 25 < sum && sum < (1 << 25) * 25); + } + + #[test] + fn test_sample_alg() { + let seed_rng = ::test::rng; + + // We can't test which algorithm is used directly, but Floyd's alg + // should produce different results from the others. (Also, `inplace` + // and `cached` currently use different sizes thus produce different results.) + + // A small length and relatively large amount should use inplace + let (length, amount): (usize, usize) = (100, 50); + let v1 = sample(&mut seed_rng(420), length, amount); + let v2 = sample_inplace(&mut seed_rng(420), length as u32, amount as u32); + assert!(v1.iter().all(|e| e < length)); + assert_eq!(v1, v2); + + // Test Floyd's alg does produce different results + let v3 = sample_floyd(&mut seed_rng(420), length as u32, amount as u32); + assert!(v1 != v3); + + // A large length and small amount should use Floyd + let (length, amount): (usize, usize) = (1<<20, 50); + let v1 = sample(&mut seed_rng(421), length, amount); + let v2 = sample_floyd(&mut seed_rng(421), length as u32, amount as u32); + assert!(v1.iter().all(|e| e < length)); + assert_eq!(v1, v2); + + // A large length and larger amount should use cache + let (length, amount): (usize, usize) = (1<<20, 600); + let v1 = sample(&mut seed_rng(422), length, amount); + let v2 = sample_rejection(&mut seed_rng(422), length, amount); + assert!(v1.iter().all(|e| e < length)); + assert_eq!(v1, v2); + } +} diff --git a/bash-5.1/vendor/rand/src/seq/mod.rs b/bash-5.1/vendor/rand/src/seq/mod.rs new file mode 100644 index 0000000..d0f8308 --- /dev/null +++ b/bash-5.1/vendor/rand/src/seq/mod.rs @@ -0,0 +1,829 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Functions for randomly accessing and sampling sequences. +//! +//! TODO: module doc + + +#[cfg(feature="alloc")] pub mod index; + +#[cfg(feature="alloc")] use core::ops::Index; + +#[cfg(all(feature="alloc", not(feature="std")))] use alloc::vec::Vec; + +use Rng; +#[cfg(feature="alloc")] use distributions::WeightedError; +#[cfg(feature="alloc")] use distributions::uniform::{SampleUniform, SampleBorrow}; + +/// Extension trait on slices, providing random mutation and sampling methods. +/// +/// An implementation is provided for slices. This may also be implementable for +/// other types. +pub trait SliceRandom { + /// The element type. + type Item; + + /// Returns a reference to one random element of the slice, or `None` if the + /// slice is empty. + /// + /// Depending on the implementation, complexity is expected to be `O(1)`. + /// + /// # Example + /// + /// ``` + /// use rand::thread_rng; + /// use rand::seq::SliceRandom; + /// + /// let choices = [1, 2, 4, 8, 16, 32]; + /// let mut rng = thread_rng(); + /// println!("{:?}", choices.choose(&mut rng)); + /// assert_eq!(choices[..0].choose(&mut rng), None); + /// ``` + fn choose(&self, rng: &mut R) -> Option<&Self::Item> + where R: Rng + ?Sized; + + /// Returns a mutable reference to one random element of the slice, or + /// `None` if the slice is empty. + /// + /// Depending on the implementation, complexity is expected to be `O(1)`. + fn choose_mut(&mut self, rng: &mut R) -> Option<&mut Self::Item> + where R: Rng + ?Sized; + + /// Produces an iterator that chooses `amount` elements from the slice at + /// random without repeating any, and returns them in random order. + /// + /// In case this API is not sufficiently flexible, use `index::sample` then + /// apply the indices to the slice. + /// + /// Complexity is expected to be the same as `index::sample`. + /// + /// # Example + /// ``` + /// use rand::seq::SliceRandom; + /// + /// let mut rng = &mut rand::thread_rng(); + /// let sample = "Hello, audience!".as_bytes(); + /// + /// // collect the results into a vector: + /// let v: Vec = sample.choose_multiple(&mut rng, 3).cloned().collect(); + /// + /// // store in a buffer: + /// let mut buf = [0u8; 5]; + /// for (b, slot) in sample.choose_multiple(&mut rng, buf.len()).zip(buf.iter_mut()) { + /// *slot = *b; + /// } + /// ``` + #[cfg(feature = "alloc")] + fn choose_multiple(&self, rng: &mut R, amount: usize) -> SliceChooseIter + where R: Rng + ?Sized; + + /// Similar to [`choose`], where the likelihood of each outcome may be + /// specified. The specified function `weight` maps items `x` to a relative + /// likelihood `weight(x)`. The probability of each item being selected is + /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. + /// + /// # Example + /// + /// ``` + /// use rand::prelude::*; + /// + /// let choices = [('a', 2), ('b', 1), ('c', 1)]; + /// let mut rng = thread_rng(); + /// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' + /// println!("{:?}", choices.choose_weighted(&mut rng, |item| item.1).unwrap().0); + /// ``` + /// [`choose`]: SliceRandom::choose + #[cfg(feature = "alloc")] + fn choose_weighted(&self, rng: &mut R, weight: F) -> Result<&Self::Item, WeightedError> + where R: Rng + ?Sized, + F: Fn(&Self::Item) -> B, + B: SampleBorrow, + X: SampleUniform + + for<'a> ::core::ops::AddAssign<&'a X> + + ::core::cmp::PartialOrd + + Clone + + Default; + + /// Similar to [`choose_mut`], where the likelihood of each outcome may be + /// specified. The specified function `weight` maps items `x` to a relative + /// likelihood `weight(x)`. The probability of each item being selected is + /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. + /// + /// See also [`choose_weighted`]. + /// + /// [`choose_mut`]: SliceRandom::choose_mut + /// [`choose_weighted`]: SliceRandom::choose_weighted + #[cfg(feature = "alloc")] + fn choose_weighted_mut(&mut self, rng: &mut R, weight: F) -> Result<&mut Self::Item, WeightedError> + where R: Rng + ?Sized, + F: Fn(&Self::Item) -> B, + B: SampleBorrow, + X: SampleUniform + + for<'a> ::core::ops::AddAssign<&'a X> + + ::core::cmp::PartialOrd + + Clone + + Default; + + /// Shuffle a mutable slice in place. + /// + /// Depending on the implementation, complexity is expected to be `O(1)`. + /// + /// # Example + /// + /// ``` + /// use rand::thread_rng; + /// use rand::seq::SliceRandom; + /// + /// let mut rng = thread_rng(); + /// let mut y = [1, 2, 3, 4, 5]; + /// println!("Unshuffled: {:?}", y); + /// y.shuffle(&mut rng); + /// println!("Shuffled: {:?}", y); + /// ``` + fn shuffle(&mut self, rng: &mut R) where R: Rng + ?Sized; + + /// Shuffle a slice in place, but exit early. + /// + /// Returns two mutable slices from the source slice. The first contains + /// `amount` elements randomly permuted. The second has the remaining + /// elements that are not fully shuffled. + /// + /// This is an efficient method to select `amount` elements at random from + /// the slice, provided the slice may be mutated. + /// + /// If you only need to choose elements randomly and `amount > self.len()/2` + /// then you may improve performance by taking + /// `amount = values.len() - amount` and using only the second slice. + /// + /// If `amount` is greater than the number of elements in the slice, this + /// will perform a full shuffle. + /// + /// Complexity is expected to be `O(m)` where `m = amount`. + fn partial_shuffle(&mut self, rng: &mut R, amount: usize) + -> (&mut [Self::Item], &mut [Self::Item]) where R: Rng + ?Sized; +} + +/// Extension trait on iterators, providing random sampling methods. +pub trait IteratorRandom: Iterator + Sized { + /// Choose one element at random from the iterator. If you have a slice, + /// it's significantly faster to call the [`choose`] or [`choose_mut`] + /// functions using the slice instead. + /// + /// Returns `None` if and only if the iterator is empty. + /// + /// Complexity is `O(n)`, where `n` is the length of the iterator. + /// This likely consumes multiple random numbers, but the exact number + /// is unspecified. + /// + /// [`choose`]: SliceRandom::method.choose + /// [`choose_mut`]: SliceRandom::choose_mut + fn choose(mut self, rng: &mut R) -> Option + where R: Rng + ?Sized + { + let (mut lower, mut upper) = self.size_hint(); + let mut consumed = 0; + let mut result = None; + + if upper == Some(lower) { + return if lower == 0 { None } else { self.nth(rng.gen_range(0, lower)) }; + } + + // Continue until the iterator is exhausted + loop { + if lower > 1 { + let ix = rng.gen_range(0, lower + consumed); + let skip; + if ix < lower { + result = self.nth(ix); + skip = lower - (ix + 1); + } else { + skip = lower; + } + if upper == Some(lower) { + return result; + } + consumed += lower; + if skip > 0 { + self.nth(skip - 1); + } + } else { + let elem = self.next(); + if elem.is_none() { + return result; + } + consumed += 1; + let denom = consumed as f64; // accurate to 2^53 elements + if rng.gen_bool(1.0 / denom) { + result = elem; + } + } + + let hint = self.size_hint(); + lower = hint.0; + upper = hint.1; + } + } + + /// Collects `amount` values at random from the iterator into a supplied + /// buffer. + /// + /// Although the elements are selected randomly, the order of elements in + /// the buffer is neither stable nor fully random. If random ordering is + /// desired, shuffle the result. + /// + /// Returns the number of elements added to the buffer. This equals `amount` + /// unless the iterator contains insufficient elements, in which case this + /// equals the number of elements available. + /// + /// Complexity is `O(n)` where `n` is the length of the iterator. + fn choose_multiple_fill(mut self, rng: &mut R, buf: &mut [Self::Item]) + -> usize where R: Rng + ?Sized + { + let amount = buf.len(); + let mut len = 0; + while len < amount { + if let Some(elem) = self.next() { + buf[len] = elem; + len += 1; + } else { + // Iterator exhausted; stop early + return len; + } + } + + // Continue, since the iterator was not exhausted + for (i, elem) in self.enumerate() { + let k = rng.gen_range(0, i + 1 + amount); + if let Some(slot) = buf.get_mut(k) { + *slot = elem; + } + } + len + } + + /// Collects `amount` values at random from the iterator into a vector. + /// + /// This is equivalent to `choose_multiple_fill` except for the result type. + /// + /// Although the elements are selected randomly, the order of elements in + /// the buffer is neither stable nor fully random. If random ordering is + /// desired, shuffle the result. + /// + /// The length of the returned vector equals `amount` unless the iterator + /// contains insufficient elements, in which case it equals the number of + /// elements available. + /// + /// Complexity is `O(n)` where `n` is the length of the iterator. + #[cfg(feature = "alloc")] + fn choose_multiple(mut self, rng: &mut R, amount: usize) -> Vec + where R: Rng + ?Sized + { + let mut reservoir = Vec::with_capacity(amount); + reservoir.extend(self.by_ref().take(amount)); + + // Continue unless the iterator was exhausted + // + // note: this prevents iterators that "restart" from causing problems. + // If the iterator stops once, then so do we. + if reservoir.len() == amount { + for (i, elem) in self.enumerate() { + let k = rng.gen_range(0, i + 1 + amount); + if let Some(slot) = reservoir.get_mut(k) { + *slot = elem; + } + } + } else { + // Don't hang onto extra memory. There is a corner case where + // `amount` was much less than `self.len()`. + reservoir.shrink_to_fit(); + } + reservoir + } +} + + +impl SliceRandom for [T] { + type Item = T; + + fn choose(&self, rng: &mut R) -> Option<&Self::Item> + where R: Rng + ?Sized + { + if self.is_empty() { + None + } else { + Some(&self[rng.gen_range(0, self.len())]) + } + } + + fn choose_mut(&mut self, rng: &mut R) -> Option<&mut Self::Item> + where R: Rng + ?Sized + { + if self.is_empty() { + None + } else { + let len = self.len(); + Some(&mut self[rng.gen_range(0, len)]) + } + } + + #[cfg(feature = "alloc")] + fn choose_multiple(&self, rng: &mut R, amount: usize) + -> SliceChooseIter + where R: Rng + ?Sized + { + let amount = ::core::cmp::min(amount, self.len()); + SliceChooseIter { + slice: self, + _phantom: Default::default(), + indices: index::sample(rng, self.len(), amount).into_iter(), + } + } + + #[cfg(feature = "alloc")] + fn choose_weighted(&self, rng: &mut R, weight: F) -> Result<&Self::Item, WeightedError> + where R: Rng + ?Sized, + F: Fn(&Self::Item) -> B, + B: SampleBorrow, + X: SampleUniform + + for<'a> ::core::ops::AddAssign<&'a X> + + ::core::cmp::PartialOrd + + Clone + + Default { + use distributions::{Distribution, WeightedIndex}; + let distr = WeightedIndex::new(self.iter().map(weight))?; + Ok(&self[distr.sample(rng)]) + } + + #[cfg(feature = "alloc")] + fn choose_weighted_mut(&mut self, rng: &mut R, weight: F) -> Result<&mut Self::Item, WeightedError> + where R: Rng + ?Sized, + F: Fn(&Self::Item) -> B, + B: SampleBorrow, + X: SampleUniform + + for<'a> ::core::ops::AddAssign<&'a X> + + ::core::cmp::PartialOrd + + Clone + + Default { + use distributions::{Distribution, WeightedIndex}; + let distr = WeightedIndex::new(self.iter().map(weight))?; + Ok(&mut self[distr.sample(rng)]) + } + + fn shuffle(&mut self, rng: &mut R) where R: Rng + ?Sized + { + for i in (1..self.len()).rev() { + // invariant: elements with index > i have been locked in place. + self.swap(i, rng.gen_range(0, i + 1)); + } + } + + fn partial_shuffle(&mut self, rng: &mut R, amount: usize) + -> (&mut [Self::Item], &mut [Self::Item]) where R: Rng + ?Sized + { + // This applies Durstenfeld's algorithm for the + // [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) + // for an unbiased permutation, but exits early after choosing `amount` + // elements. + + let len = self.len(); + let end = if amount >= len { 0 } else { len - amount }; + + for i in (end..len).rev() { + // invariant: elements with index > i have been locked in place. + self.swap(i, rng.gen_range(0, i + 1)); + } + let r = self.split_at_mut(end); + (r.1, r.0) + } +} + +impl IteratorRandom for I where I: Iterator + Sized {} + + +/// Iterator over multiple choices, as returned by [`SliceRandom::choose_multiple] +#[cfg(feature = "alloc")] +#[derive(Debug)] +pub struct SliceChooseIter<'a, S: ?Sized + 'a, T: 'a> { + slice: &'a S, + _phantom: ::core::marker::PhantomData, + indices: index::IndexVecIntoIter, +} + +#[cfg(feature = "alloc")] +impl<'a, S: Index + ?Sized + 'a, T: 'a> Iterator for SliceChooseIter<'a, S, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + // TODO: investigate using SliceIndex::get_unchecked when stable + self.indices.next().map(|i| &self.slice[i as usize]) + } + + fn size_hint(&self) -> (usize, Option) { + (self.indices.len(), Some(self.indices.len())) + } +} + +#[cfg(feature = "alloc")] +impl<'a, S: Index + ?Sized + 'a, T: 'a> ExactSizeIterator + for SliceChooseIter<'a, S, T> +{ + fn len(&self) -> usize { + self.indices.len() + } +} + + +/// Randomly sample `amount` elements from a finite iterator. +/// +/// Deprecated: use [`IteratorRandom::choose_multiple`] instead. +#[cfg(feature = "alloc")] +#[deprecated(since="0.6.0", note="use IteratorRandom::choose_multiple instead")] +pub fn sample_iter(rng: &mut R, iterable: I, amount: usize) -> Result, Vec> + where I: IntoIterator, + R: Rng + ?Sized, +{ + use seq::IteratorRandom; + let iter = iterable.into_iter(); + let result = iter.choose_multiple(rng, amount); + if result.len() == amount { + Ok(result) + } else { + Err(result) + } +} + +/// Randomly sample exactly `amount` values from `slice`. +/// +/// The values are non-repeating and in random order. +/// +/// This implementation uses `O(amount)` time and memory. +/// +/// Panics if `amount > slice.len()` +/// +/// Deprecated: use [`SliceRandom::choose_multiple`] instead. +#[cfg(feature = "alloc")] +#[deprecated(since="0.6.0", note="use SliceRandom::choose_multiple instead")] +pub fn sample_slice(rng: &mut R, slice: &[T], amount: usize) -> Vec + where R: Rng + ?Sized, + T: Clone +{ + let indices = index::sample(rng, slice.len(), amount).into_iter(); + + let mut out = Vec::with_capacity(amount); + out.extend(indices.map(|i| slice[i].clone())); + out +} + +/// Randomly sample exactly `amount` references from `slice`. +/// +/// The references are non-repeating and in random order. +/// +/// This implementation uses `O(amount)` time and memory. +/// +/// Panics if `amount > slice.len()` +/// +/// Deprecated: use [`SliceRandom::choose_multiple`] instead. +#[cfg(feature = "alloc")] +#[deprecated(since="0.6.0", note="use SliceRandom::choose_multiple instead")] +pub fn sample_slice_ref<'a, R, T>(rng: &mut R, slice: &'a [T], amount: usize) -> Vec<&'a T> + where R: Rng + ?Sized +{ + let indices = index::sample(rng, slice.len(), amount).into_iter(); + + let mut out = Vec::with_capacity(amount); + out.extend(indices.map(|i| &slice[i])); + out +} + +#[cfg(test)] +mod test { + use super::*; + #[cfg(feature = "alloc")] use {Rng, SeedableRng}; + #[cfg(feature = "alloc")] use rngs::SmallRng; + #[cfg(all(feature="alloc", not(feature="std")))] + use alloc::vec::Vec; + + #[test] + fn test_slice_choose() { + let mut r = ::test::rng(107); + let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']; + let mut chosen = [0i32; 14]; + for _ in 0..1000 { + let picked = *chars.choose(&mut r).unwrap(); + chosen[(picked as usize) - ('a' as usize)] += 1; + } + for count in chosen.iter() { + let err = *count - (1000 / (chars.len() as i32)); + assert!(-20 <= err && err <= 20); + } + + chosen.iter_mut().for_each(|x| *x = 0); + for _ in 0..1000 { + *chosen.choose_mut(&mut r).unwrap() += 1; + } + for count in chosen.iter() { + let err = *count - (1000 / (chosen.len() as i32)); + assert!(-20 <= err && err <= 20); + } + + let mut v: [isize; 0] = []; + assert_eq!(v.choose(&mut r), None); + assert_eq!(v.choose_mut(&mut r), None); + } + + #[derive(Clone)] + struct UnhintedIterator { + iter: I, + } + impl Iterator for UnhintedIterator { + type Item = I::Item; + fn next(&mut self) -> Option { + self.iter.next() + } + } + + #[derive(Clone)] + struct ChunkHintedIterator { + iter: I, + chunk_remaining: usize, + chunk_size: usize, + hint_total_size: bool, + } + impl Iterator for ChunkHintedIterator { + type Item = I::Item; + fn next(&mut self) -> Option { + if self.chunk_remaining == 0 { + self.chunk_remaining = ::core::cmp::min(self.chunk_size, + self.iter.len()); + } + self.chunk_remaining = self.chunk_remaining.saturating_sub(1); + + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.chunk_remaining, + if self.hint_total_size { Some(self.iter.len()) } else { None }) + } + } + + #[derive(Clone)] + struct WindowHintedIterator { + iter: I, + window_size: usize, + hint_total_size: bool, + } + impl Iterator for WindowHintedIterator { + type Item = I::Item; + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (::core::cmp::min(self.iter.len(), self.window_size), + if self.hint_total_size { Some(self.iter.len()) } else { None }) + } + } + + #[test] + fn test_iterator_choose() { + let r = &mut ::test::rng(109); + fn test_iter + Clone>(r: &mut R, iter: Iter) { + let mut chosen = [0i32; 9]; + for _ in 0..1000 { + let picked = iter.clone().choose(r).unwrap(); + chosen[picked] += 1; + } + for count in chosen.iter() { + // Samples should follow Binomial(1000, 1/9) + // Octave: binopdf(x, 1000, 1/9) gives the prob of *count == x + // Note: have seen 153, which is unlikely but not impossible. + assert!(72 < *count && *count < 154, "count not close to 1000/9: {}", count); + } + } + + test_iter(r, 0..9); + test_iter(r, [0, 1, 2, 3, 4, 5, 6, 7, 8].iter().cloned()); + #[cfg(feature = "alloc")] + test_iter(r, (0..9).collect::>().into_iter()); + test_iter(r, UnhintedIterator { iter: 0..9 }); + test_iter(r, ChunkHintedIterator { iter: 0..9, chunk_size: 4, chunk_remaining: 4, hint_total_size: false }); + test_iter(r, ChunkHintedIterator { iter: 0..9, chunk_size: 4, chunk_remaining: 4, hint_total_size: true }); + test_iter(r, WindowHintedIterator { iter: 0..9, window_size: 2, hint_total_size: false }); + test_iter(r, WindowHintedIterator { iter: 0..9, window_size: 2, hint_total_size: true }); + + assert_eq!((0..0).choose(r), None); + assert_eq!(UnhintedIterator{ iter: 0..0 }.choose(r), None); + } + + #[test] + fn test_shuffle() { + let mut r = ::test::rng(108); + let empty: &mut [isize] = &mut []; + empty.shuffle(&mut r); + let mut one = [1]; + one.shuffle(&mut r); + let b: &[_] = &[1]; + assert_eq!(one, b); + + let mut two = [1, 2]; + two.shuffle(&mut r); + assert!(two == [1, 2] || two == [2, 1]); + + fn move_last(slice: &mut [usize], pos: usize) { + // use slice[pos..].rotate_left(1); once we can use that + let last_val = slice[pos]; + for i in pos..slice.len() - 1 { + slice[i] = slice[i + 1]; + } + *slice.last_mut().unwrap() = last_val; + } + let mut counts = [0i32; 24]; + for _ in 0..10000 { + let mut arr: [usize; 4] = [0, 1, 2, 3]; + arr.shuffle(&mut r); + let mut permutation = 0usize; + let mut pos_value = counts.len(); + for i in 0..4 { + pos_value /= 4 - i; + let pos = arr.iter().position(|&x| x == i).unwrap(); + assert!(pos < (4 - i)); + permutation += pos * pos_value; + move_last(&mut arr, pos); + assert_eq!(arr[3], i); + } + for i in 0..4 { + assert_eq!(arr[i], i); + } + counts[permutation] += 1; + } + for count in counts.iter() { + let err = *count - 10000i32 / 24; + assert!(-50 <= err && err <= 50); + } + } + + #[test] + fn test_partial_shuffle() { + let mut r = ::test::rng(118); + + let mut empty: [u32; 0] = []; + let res = empty.partial_shuffle(&mut r, 10); + assert_eq!((res.0.len(), res.1.len()), (0, 0)); + + let mut v = [1, 2, 3, 4, 5]; + let res = v.partial_shuffle(&mut r, 2); + assert_eq!((res.0.len(), res.1.len()), (2, 3)); + assert!(res.0[0] != res.0[1]); + // First elements are only modified if selected, so at least one isn't modified: + assert!(res.1[0] == 1 || res.1[1] == 2 || res.1[2] == 3); + } + + #[test] + #[cfg(feature = "alloc")] + fn test_sample_iter() { + let min_val = 1; + let max_val = 100; + + let mut r = ::test::rng(401); + let vals = (min_val..max_val).collect::>(); + let small_sample = vals.iter().choose_multiple(&mut r, 5); + let large_sample = vals.iter().choose_multiple(&mut r, vals.len() + 5); + + assert_eq!(small_sample.len(), 5); + assert_eq!(large_sample.len(), vals.len()); + // no randomization happens when amount >= len + assert_eq!(large_sample, vals.iter().collect::>()); + + assert!(small_sample.iter().all(|e| { + **e >= min_val && **e <= max_val + })); + } + + #[test] + #[cfg(feature = "alloc")] + #[allow(deprecated)] + fn test_sample_slice_boundaries() { + let empty: &[u8] = &[]; + + let mut r = ::test::rng(402); + + // sample 0 items + assert_eq!(&sample_slice(&mut r, empty, 0)[..], [0u8; 0]); + assert_eq!(&sample_slice(&mut r, &[42, 2, 42], 0)[..], [0u8; 0]); + + // sample 1 item + assert_eq!(&sample_slice(&mut r, &[42], 1)[..], [42]); + let v = sample_slice(&mut r, &[1, 42], 1)[0]; + assert!(v == 1 || v == 42); + + // sample "all" the items + let v = sample_slice(&mut r, &[42, 133], 2); + assert!(&v[..] == [42, 133] || v[..] == [133, 42]); + + // Make sure lucky 777's aren't lucky + let slice = &[42, 777]; + let mut num_42 = 0; + let total = 1000; + for _ in 0..total { + let v = sample_slice(&mut r, slice, 1); + assert_eq!(v.len(), 1); + let v = v[0]; + assert!(v == 42 || v == 777); + if v == 42 { + num_42 += 1; + } + } + let ratio_42 = num_42 as f64 / 1000 as f64; + assert!(0.4 <= ratio_42 || ratio_42 <= 0.6, "{}", ratio_42); + } + + #[test] + #[cfg(feature = "alloc")] + #[allow(deprecated)] + fn test_sample_slice() { + let seeded_rng = SmallRng::from_seed; + + let mut r = ::test::rng(403); + + for n in 1..20 { + let length = 5*n - 4; // 1, 6, ... + let amount = r.gen_range(0, length); + let mut seed = [0u8; 16]; + r.fill(&mut seed); + + // assert the basics work + let regular = index::sample(&mut seeded_rng(seed), length, amount); + assert_eq!(regular.len(), amount); + assert!(regular.iter().all(|e| e < length)); + + // also test that sampling the slice works + let vec: Vec = (0..(length as u32)).collect(); + let result = sample_slice(&mut seeded_rng(seed), &vec, amount); + assert_eq!(result, regular.iter().map(|i| i as u32).collect::>()); + + let result = sample_slice_ref(&mut seeded_rng(seed), &vec, amount); + assert!(result.iter().zip(regular.iter()).all(|(i,j)| **i == j as u32)); + } + } + + #[test] + #[cfg(feature = "alloc")] + fn test_weighted() { + let mut r = ::test::rng(406); + const N_REPS: u32 = 3000; + let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; + let total_weight = weights.iter().sum::() as f32; + + let verify = |result: [i32; 14]| { + for (i, count) in result.iter().enumerate() { + let exp = (weights[i] * N_REPS) as f32 / total_weight; + let mut err = (*count as f32 - exp).abs(); + if err != 0.0 { + err /= exp; + } + assert!(err <= 0.25); + } + }; + + // choose_weighted + fn get_weight(item: &(u32, T)) -> u32 { + item.0 + } + let mut chosen = [0i32; 14]; + let mut items = [(0u32, 0usize); 14]; // (weight, index) + for (i, item) in items.iter_mut().enumerate() { + *item = (weights[i], i); + } + for _ in 0..N_REPS { + let item = items.choose_weighted(&mut r, get_weight).unwrap(); + chosen[item.1] += 1; + } + verify(chosen); + + // choose_weighted_mut + let mut items = [(0u32, 0i32); 14]; // (weight, count) + for (i, item) in items.iter_mut().enumerate() { + *item = (weights[i], 0); + } + for _ in 0..N_REPS { + items.choose_weighted_mut(&mut r, get_weight).unwrap().1 += 1; + } + for (ch, item) in chosen.iter_mut().zip(items.iter()) { + *ch = item.1; + } + verify(chosen); + + // Check error cases + let empty_slice = &mut [10][0..0]; + assert_eq!(empty_slice.choose_weighted(&mut r, |_| 1), Err(WeightedError::NoItem)); + assert_eq!(empty_slice.choose_weighted_mut(&mut r, |_| 1), Err(WeightedError::NoItem)); + assert_eq!(['x'].choose_weighted_mut(&mut r, |_| 0), Err(WeightedError::AllWeightsZero)); + assert_eq!([0, -1].choose_weighted_mut(&mut r, |x| *x), Err(WeightedError::NegativeWeight)); + assert_eq!([-1, 0].choose_weighted_mut(&mut r, |x| *x), Err(WeightedError::NegativeWeight)); + } +} diff --git a/bash-5.1/vendor/rand/tests/uniformity.rs b/bash-5.1/vendor/rand/tests/uniformity.rs new file mode 100644 index 0000000..b8f74a6 --- /dev/null +++ b/bash-5.1/vendor/rand/tests/uniformity.rs @@ -0,0 +1,67 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg(feature = "std")] + +#[macro_use] +extern crate average; +extern crate rand; + +use std as core; +use rand::FromEntropy; +use rand::distributions::Distribution; +use average::Histogram; + +const N_BINS: usize = 100; +const N_SAMPLES: u32 = 1_000_000; +const TOL: f64 = 1e-3; +define_histogram!(hist, 100); +use hist::Histogram as Histogram100; + +#[test] +fn unit_sphere() { + const N_DIM: usize = 3; + let h = Histogram100::with_const_width(-1., 1.); + let mut histograms = [h.clone(), h.clone(), h]; + let dist = rand::distributions::UnitSphereSurface::new(); + let mut rng = rand::rngs::SmallRng::from_entropy(); + for _ in 0..N_SAMPLES { + let v = dist.sample(&mut rng); + for i in 0..N_DIM { + histograms[i].add(v[i]).map_err( + |e| { println!("v: {}", v[i]); e } + ).unwrap(); + } + } + for h in &histograms { + let sum: u64 = h.bins().iter().sum(); + println!("{:?}", h); + for &b in h.bins() { + let p = (b as f64) / (sum as f64); + assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p); + } + } +} + +#[test] +fn unit_circle() { + use ::std::f64::consts::PI; + let mut h = Histogram100::with_const_width(-PI, PI); + let dist = rand::distributions::UnitCircle::new(); + let mut rng = rand::rngs::SmallRng::from_entropy(); + for _ in 0..N_SAMPLES { + let v = dist.sample(&mut rng); + h.add(v[0].atan2(v[1])).unwrap(); + } + let sum: u64 = h.bins().iter().sum(); + println!("{:?}", h); + for &b in h.bins() { + let p = (b as f64) / (sum as f64); + assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p); + } +} diff --git a/bash-5.1/vendor/rand_chacha/.cargo-checksum.json b/bash-5.1/vendor/rand_chacha/.cargo-checksum.json new file mode 100644 index 0000000..42ac082 --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"66b938cf98ad5c5305ef4cc07886b0f64d9985189f6b32630bf32712a0395e5d","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"020a747006ee14a2faae021077d5f2d1b41c90a79f97a79bd33a6fc2b256206f","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"2c4782326824e620912d671f1903722c60ada94c440817ff5e6f83e784f472bf","build.rs":"003108281c4f4bd7a40a93529012acc9d2555c7a4f4b3bfc3ab81d0ed92b8864","src/chacha.rs":"ea9bc97d0fec99d627fcd5ee57f3e187571efdea752ef4b514d1ae0c00476801","src/lib.rs":"ff1162b8836ccc23763cf7f64fa92c2d91b09d1b9ac80960a1486dca6d8a23ca"},"package":"556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_chacha/CHANGELOG.md b/bash-5.1/vendor/rand_chacha/CHANGELOG.md new file mode 100644 index 0000000..a1979f6 --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.1] - 2019-01-04 +- Disable `i128` and `u128` if the `target_os` is `emscripten` (#671: work-around Emscripten limitation) +- Update readme and doc links + +## [0.1.0] - 2018-10-17 +- Pulled out of the Rand crate diff --git a/bash-5.1/vendor/rand_chacha/COPYRIGHT b/bash-5.1/vendor/rand_chacha/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_chacha/Cargo.toml b/bash-5.1/vendor/rand_chacha/Cargo.toml new file mode 100644 index 0000000..e6d5523 --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/Cargo.toml @@ -0,0 +1,35 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_chacha" +version = "0.1.1" +authors = ["The Rand Project Developers", "The Rust Project Developers"] +build = "build.rs" +description = "ChaCha random number generator\n" +homepage = "https://crates.io/crates/rand_chacha" +documentation = "https://rust-random.github.io/rand/rand_chacha" +readme = "README.md" +keywords = ["random", "rng", "chacha"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.rand_core] +version = ">=0.2, <0.4" +default-features = false +[build-dependencies.autocfg] +version = "0.1" +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_chacha/LICENSE-APACHE b/bash-5.1/vendor/rand_chacha/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_chacha/LICENSE-MIT b/bash-5.1/vendor/rand_chacha/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_chacha/README.md b/bash-5.1/vendor/rand_chacha/README.md new file mode 100644 index 0000000..5a1dbac --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/README.md @@ -0,0 +1,45 @@ +# rand_chacha + +[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_chacha.svg)](https://crates.io/crates/rand_chacha) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_chacha) +[![API](https://docs.rs/rand_chacha/badge.svg)](https://docs.rs/rand_chacha) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +A cryptographically secure random number generator that uses the ChaCha +algorithm. + +ChaCha is a stream cipher designed by Daniel J. Bernstein[^1], that we use +as an RNG. It is an improved variant of the Salsa20 cipher family, which was +selected as one of the "stream ciphers suitable for widespread adoption" by +eSTREAM[^2]. + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_chacha) +- [API documentation (docs.rs)](https://docs.rs/rand_chacha) +- [Changelog](CHANGELOG.md) + +[rand]: https://crates.io/crates/rand +[^1]: D. J. Bernstein, [*ChaCha, a variant of Salsa20*]( + https://cr.yp.to/chacha.html) + +[^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( + http://www.ecrypt.eu.org/stream/) + + +## Crate Features + +`rand_chacha` is `no_std` compatible. It does not require any functionality +outside of the `core` lib, thus there are no features to configure. + + +# License + +`rand_chacha` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_chacha/build.rs b/bash-5.1/vendor/rand_chacha/build.rs new file mode 100644 index 0000000..06e12a4 --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/build.rs @@ -0,0 +1,7 @@ +extern crate autocfg; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + let ac = autocfg::new(); + ac.emit_rustc_version(1, 26); +} diff --git a/bash-5.1/vendor/rand_chacha/src/chacha.rs b/bash-5.1/vendor/rand_chacha/src/chacha.rs new file mode 100644 index 0000000..86f191e --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/src/chacha.rs @@ -0,0 +1,449 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2014 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The ChaCha random number generator. + +use core::fmt; +use rand_core::{CryptoRng, RngCore, SeedableRng, Error, le}; +use rand_core::block::{BlockRngCore, BlockRng}; + +const SEED_WORDS: usize = 8; // 8 words for the 256-bit key +const STATE_WORDS: usize = 16; + +/// A cryptographically secure random number generator that uses the ChaCha +/// algorithm. +/// +/// ChaCha is a stream cipher designed by Daniel J. Bernstein[^1], that we use +/// as an RNG. It is an improved variant of the Salsa20 cipher family, which was +/// selected as one of the "stream ciphers suitable for widespread adoption" by +/// eSTREAM[^2]. +/// +/// ChaCha uses add-rotate-xor (ARX) operations as its basis. These are safe +/// against timing attacks, although that is mostly a concern for ciphers and +/// not for RNGs. Also it is very suitable for SIMD implementation. +/// Here we do not provide a SIMD implementation yet, except for what is +/// provided by auto-vectorisation. +/// +/// With the ChaCha algorithm it is possible to choose the number of rounds the +/// core algorithm should run. The number of rounds is a tradeoff between +/// performance and security, where 8 rounds is the minimum potentially +/// secure configuration, and 20 rounds is widely used as a conservative choice. +/// We use 20 rounds in this implementation, but hope to allow type-level +/// configuration in the future. +/// +/// We use a 64-bit counter and 64-bit stream identifier as in Bernstein's +/// implementation[^1] except that we use a stream identifier in place of a +/// nonce. A 64-bit counter over 64-byte (16 word) blocks allows 1 ZiB of output +/// before cycling, and the stream identifier allows 264 unique +/// streams of output per seed. Both counter and stream are initialized to zero +/// but may be set via [`set_word_pos`] and [`set_stream`]. +/// +/// The word layout is: +/// +/// ```text +/// constant constant constant constant +/// seed seed seed seed +/// seed seed seed seed +/// counter counter stream_id stream_id +/// ``` +/// +/// This implementation uses an output buffer of sixteen `u32` words, and uses +/// [`BlockRng`] to implement the [`RngCore`] methods. +/// +/// [^1]: D. J. Bernstein, [*ChaCha, a variant of Salsa20*]( +/// https://cr.yp.to/chacha.html) +/// +/// [^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( +/// http://www.ecrypt.eu.org/stream/) +/// +/// [`set_word_pos`]: #method.set_word_pos +/// [`set_stream`]: #method.set_stream +/// [`BlockRng`]: ../rand_core/block/struct.BlockRng.html +/// [`RngCore`]: ../rand_core/trait.RngCore.html +#[derive(Clone, Debug)] +pub struct ChaChaRng(BlockRng); + +impl RngCore for ChaChaRng { + #[inline] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + #[inline] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for ChaChaRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + ChaChaRng(BlockRng::::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + BlockRng::::from_rng(rng).map(ChaChaRng) + } +} + +impl CryptoRng for ChaChaRng {} + +impl ChaChaRng { + /// Get the offset from the start of the stream, in 32-bit words. + /// + /// Since the generated blocks are 16 words (24) long and the + /// counter is 64-bits, the offset is a 68-bit number. Sub-word offsets are + /// not supported, hence the result can simply be multiplied by 4 to get a + /// byte-offset. + /// + /// Note: this function is currently only available with Rust 1.26 or later. + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + pub fn get_word_pos(&self) -> u128 { + let mut c = (self.0.core.state[13] as u64) << 32 + | (self.0.core.state[12] as u64); + let mut index = self.0.index(); + // c is the end of the last block generated, unless index is at end + if index >= STATE_WORDS { + index = 0; + } else { + c = c.wrapping_sub(1); + } + ((c as u128) << 4) | (index as u128) + } + + /// Set the offset from the start of the stream, in 32-bit words. + /// + /// As with `get_word_pos`, we use a 68-bit number. Since the generator + /// simply cycles at the end of its period (1 ZiB), we ignore the upper + /// 60 bits. + /// + /// Note: this function is currently only available with Rust 1.26 or later. + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + pub fn set_word_pos(&mut self, word_offset: u128) { + let index = (word_offset as usize) & 0xF; + let counter = (word_offset >> 4) as u64; + self.0.core.state[12] = counter as u32; + self.0.core.state[13] = (counter >> 32) as u32; + if index != 0 { + self.0.generate_and_set(index); // also increments counter + } else { + self.0.reset(); + } + } + + /// Set the stream number. + /// + /// This is initialized to zero; 264 unique streams of output + /// are available per seed/key. + /// + /// Note that in order to reproduce ChaCha output with a specific 64-bit + /// nonce, one can convert that nonce to a `u64` in little-endian fashion + /// and pass to this function. In theory a 96-bit nonce can be used by + /// passing the last 64-bits to this function and using the first 32-bits as + /// the most significant half of the 64-bit counter (which may be set + /// indirectly via `set_word_pos`), but this is not directly supported. + pub fn set_stream(&mut self, stream: u64) { + let index = self.0.index(); + self.0.core.state[14] = stream as u32; + self.0.core.state[15] = (stream >> 32) as u32; + if index < STATE_WORDS { + // we need to regenerate a partial result buffer + { + // reverse of counter adjustment in generate() + if self.0.core.state[12] == 0 { + self.0.core.state[13] = self.0.core.state[13].wrapping_sub(1); + } + self.0.core.state[12] = self.0.core.state[12].wrapping_sub(1); + } + self.0.generate_and_set(index); + } + } +} + +/// The core of `ChaChaRng`, used with `BlockRng`. +#[derive(Clone)] +pub struct ChaChaCore { + state: [u32; STATE_WORDS], +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for ChaChaCore { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ChaChaCore {{}}") + } +} + +macro_rules! quarter_round{ + ($a: expr, $b: expr, $c: expr, $d: expr) => {{ + $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16); + $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12); + $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8); + $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7); + }} +} + +macro_rules! double_round{ + ($x: expr) => {{ + // Column round + quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); + quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); + quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); + quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); + // Diagonal round + quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); + quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); + quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); + quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); + }} +} + +impl BlockRngCore for ChaChaCore { + type Item = u32; + type Results = [u32; STATE_WORDS]; + + fn generate(&mut self, results: &mut Self::Results) { + // For some reason extracting this part into a separate function + // improves performance by 50%. + fn core(results: &mut [u32; STATE_WORDS], + state: &[u32; STATE_WORDS]) + { + let mut tmp = *state; + let rounds = 20; + for _ in 0..rounds / 2 { + double_round!(tmp); + } + for i in 0..STATE_WORDS { + results[i] = tmp[i].wrapping_add(state[i]); + } + } + + core(results, &self.state); + + // update 64-bit counter + self.state[12] = self.state[12].wrapping_add(1); + if self.state[12] != 0 { return; }; + self.state[13] = self.state[13].wrapping_add(1); + } +} + +impl SeedableRng for ChaChaCore { + type Seed = [u8; SEED_WORDS*4]; + + fn from_seed(seed: Self::Seed) -> Self { + let mut seed_le = [0u32; SEED_WORDS]; + le::read_u32_into(&seed, &mut seed_le); + Self { + state: [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574, // constants + seed_le[0], seed_le[1], seed_le[2], seed_le[3], // seed + seed_le[4], seed_le[5], seed_le[6], seed_le[7], // seed + 0, 0, 0, 0], // counter + } + } +} + +impl CryptoRng for ChaChaCore {} + +impl From for ChaChaRng { + fn from(core: ChaChaCore) -> Self { + ChaChaRng(BlockRng::new(core)) + } +} + +#[cfg(test)] +mod test { + use ::rand_core::{RngCore, SeedableRng}; + use super::ChaChaRng; + + #[test] + fn test_chacha_construction() { + let seed = [0,0,0,0,0,0,0,0, + 1,0,0,0,0,0,0,0, + 2,0,0,0,0,0,0,0, + 3,0,0,0,0,0,0,0]; + let mut rng1 = ChaChaRng::from_seed(seed); + assert_eq!(rng1.next_u32(), 137206642); + + let mut rng2 = ChaChaRng::from_rng(rng1).unwrap(); + assert_eq!(rng2.next_u32(), 1325750369); + } + + #[test] + fn test_chacha_true_values_a() { + // Test vectors 1 and 2 from + // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 + let seed = [0u8; 32]; + let mut rng = ChaChaRng::from_seed(seed); + + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, + 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, + 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, + 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2]; + assert_eq!(results, expected); + + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, + 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, + 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, + 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b]; + assert_eq!(results, expected); + } + + #[test] + fn test_chacha_true_values_b() { + // Test vector 3 from + // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 + let seed = [0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1]; + let mut rng = ChaChaRng::from_seed(seed); + + // Skip block 0 + for _ in 0..16 { rng.next_u32(); } + + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, + 0xe8252083, 0x60818b01, 0xf38422b8, 0x5aaa49c9, + 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, + 0x4436274e, 0x2561b3c8, 0xebdd4aa6, 0xa0136c00]; + assert_eq!(results, expected); + } + + #[test] + #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] + fn test_chacha_true_values_c() { + // Test vector 4 from + // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 + let seed = [0, 0xff, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0]; + let expected = [0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, + 0xa78dea8f, 0x5e269039, 0xa1bebbc1, 0xcaf09aae, + 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, + 0x546ca624, 0x1bec45d5, 0x87f47473, 0x96f0992e]; + let expected_end = 3 * 16; + let mut results = [0u32; 16]; + + // Test block 2 by skipping block 0 and 1 + let mut rng1 = ChaChaRng::from_seed(seed); + for _ in 0..32 { rng1.next_u32(); } + for i in results.iter_mut() { *i = rng1.next_u32(); } + assert_eq!(results, expected); + assert_eq!(rng1.get_word_pos(), expected_end); + + // Test block 2 by using `set_word_pos` + let mut rng2 = ChaChaRng::from_seed(seed); + rng2.set_word_pos(2 * 16); + for i in results.iter_mut() { *i = rng2.next_u32(); } + assert_eq!(results, expected); + assert_eq!(rng2.get_word_pos(), expected_end); + + // Test skipping behaviour with other types + let mut buf = [0u8; 32]; + rng2.fill_bytes(&mut buf[..]); + assert_eq!(rng2.get_word_pos(), expected_end + 8); + rng2.fill_bytes(&mut buf[0..25]); + assert_eq!(rng2.get_word_pos(), expected_end + 15); + rng2.next_u64(); + assert_eq!(rng2.get_word_pos(), expected_end + 17); + rng2.next_u32(); + rng2.next_u64(); + assert_eq!(rng2.get_word_pos(), expected_end + 20); + rng2.fill_bytes(&mut buf[0..1]); + assert_eq!(rng2.get_word_pos(), expected_end + 21); + } + + #[test] + fn test_chacha_multiple_blocks() { + let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; + let mut rng = ChaChaRng::from_seed(seed); + + // Store the 17*i-th 32-bit word, + // i.e., the i-th word of the i-th 16-word block + let mut results = [0u32; 16]; + for i in results.iter_mut() { + *i = rng.next_u32(); + for _ in 0..16 { + rng.next_u32(); + } + } + let expected = [0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, + 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, + 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, + 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4]; + assert_eq!(results, expected); + } + + #[test] + fn test_chacha_true_bytes() { + let seed = [0u8; 32]; + let mut rng = ChaChaRng::from_seed(seed); + let mut results = [0u8; 32]; + rng.fill_bytes(&mut results); + let expected = [118, 184, 224, 173, 160, 241, 61, 144, + 64, 93, 106, 229, 83, 134, 189, 40, + 189, 210, 25, 184, 160, 141, 237, 26, + 168, 54, 239, 204, 139, 119, 13, 199]; + assert_eq!(results, expected); + } + + #[test] + fn test_chacha_nonce() { + // Test vector 5 from + // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 + // Although we do not support setting a nonce, we try it here anyway so + // we can use this test vector. + let seed = [0u8; 32]; + let mut rng = ChaChaRng::from_seed(seed); + // 96-bit nonce in LE order is: 0,0,0,0, 0,0,0,0, 0,0,0,2 + rng.set_stream(2u64 << (24 + 32)); + + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, + 0x88228b1a, 0x96a4dfb3, 0x5b76ab72, 0xc727ee54, + 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, + 0x99c28f5f, 0x628314e8, 0x398a19fa, 0x6ded1b53]; + assert_eq!(results, expected); + } + + #[test] + fn test_chacha_clone_streams() { + let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; + let mut rng = ChaChaRng::from_seed(seed); + let mut clone = rng.clone(); + for _ in 0..16 { + assert_eq!(rng.next_u64(), clone.next_u64()); + } + + rng.set_stream(51); + for _ in 0..7 { + assert!(rng.next_u32() != clone.next_u32()); + } + clone.set_stream(51); // switch part way through block + for _ in 7..16 { + assert_eq!(rng.next_u32(), clone.next_u32()); + } + } +} diff --git a/bash-5.1/vendor/rand_chacha/src/lib.rs b/bash-5.1/vendor/rand_chacha/src/lib.rs new file mode 100644 index 0000000..8cff03a --- /dev/null +++ b/bash-5.1/vendor/rand_chacha/src/lib.rs @@ -0,0 +1,25 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The ChaCha random number generator. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![no_std] + +extern crate rand_core; + +mod chacha; + +pub use chacha::{ChaChaRng, ChaChaCore}; diff --git a/bash-5.1/vendor/rand_core-0.3.1/.cargo-checksum.json b/bash-5.1/vendor/rand_core-0.3.1/.cargo-checksum.json new file mode 100644 index 0000000..1fd20d4 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"35b32c8dc19610e66f7c6967e93f5a0f49e5a021c633da72e7219571cfb7b457","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"38f22c1be27541f74b322a721c95aaacd622cddfa02cfa22f7976d613453dc78","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"2781af9ae12e434bb3f43c5a3b16b330eea7a8c80065e28e967333a82be7a507","src/block.rs":"43778ab70f0b650c3203a6da70b40bc33afa845a5e14ef88dd26c18a07b70f88","src/error.rs":"8403a968d7c9bd95cc9f23d9dc5cc4771ede8e81dda5a8fdd59d347590345d14","src/impls.rs":"c248ddd04a65c974768baaec028fa0d2a6117525fa27bce8a98f2ba2f352700a","src/le.rs":"cb187f58f7514877918f7f47633397e08e20392dcf072bc245d62c9e5238198c","src/lib.rs":"4452ea591ce26f69e6a3dd1341795faeec5c14af35eb4a17aaf2b5d342753cf0"},"package":"7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_core-0.3.1/CHANGELOG.md b/bash-5.1/vendor/rand_core-0.3.1/CHANGELOG.md new file mode 100644 index 0000000..e375536 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.3.1] - 2019-01-25 +- Compatibility shim around version 0.4 + +## [0.3.0] - 2018-09-24 +- Add `SeedableRng::seed_from_u64` for convenient seeding. (#537) + +## [0.2.1] - 2018-06-08 +- References to a `CryptoRng` now also implement `CryptoRng`. (#470) + +## [0.2.0] - 2018-05-21 +- Enable the `std` feature by default. (#409) +- Remove `BlockRng{64}::inner` and `BlockRng::inner_mut`; instead making `core` public +- Add `BlockRng{64}::index` and `BlockRng{64}::generate_and_set`. (#374, #419) +- Change `BlockRngCore::Results` bound to also require `AsMut<[Self::Item]>`. (#419) +- Implement `std::io::Read` for RngCore. (#434) + +## [0.1.0] - 2018-04-17 +(Split out of the Rand crate, changes here are relative to rand 0.4.2) +- `RngCore` and `SeedableRng` are now part of `rand_core`. (#288) +- Add modules to help implementing RNGs `impl` and `le`. (#209, #228) +- Add `Error` and `ErrorKind`. (#225) +- Add `CryptoRng` marker trait. (#273) +- Add `BlockRngCore` trait. (#281) +- Add `BlockRng` and `BlockRng64` wrappers to help implementations. (#281, #325) +- Revise the `SeedableRng` trait. (#233) +- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. (#288) +- Add `RngCore::try_fill_bytes`. (#225) + +## [0.0.1] - 2017-09-14 (yanked) +Experimental version as part of the rand crate refactor. diff --git a/bash-5.1/vendor/rand_core-0.3.1/COPYRIGHT b/bash-5.1/vendor/rand_core-0.3.1/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_core-0.3.1/Cargo.toml b/bash-5.1/vendor/rand_core-0.3.1/Cargo.toml new file mode 100644 index 0000000..439b7d1 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/Cargo.toml @@ -0,0 +1,37 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_core" +version = "0.3.1" +authors = ["The Rand Project Developers", "The Rust Project Developers"] +description = "Core random number generator traits and tools for implementation.\n" +homepage = "https://crates.io/crates/rand_core" +documentation = "https://rust-random.github.io/rand/rand_core" +readme = "README.md" +keywords = ["random", "rng"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.rand_core] +version = "0.4" + +[features] +alloc = ["rand_core/alloc"] +default = ["std"] +serde1 = ["rand_core/serde1"] +std = ["rand_core/std"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_core-0.3.1/LICENSE-APACHE b/bash-5.1/vendor/rand_core-0.3.1/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_core-0.3.1/LICENSE-MIT b/bash-5.1/vendor/rand_core-0.3.1/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_core-0.3.1/README.md b/bash-5.1/vendor/rand_core-0.3.1/README.md new file mode 100644 index 0000000..dee6504 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/README.md @@ -0,0 +1,65 @@ +# rand_core + +[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_core.svg)](https://crates.io/crates/rand_core) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_core) +[![API](https://docs.rs/rand_core/badge.svg)](https://docs.rs/rand_core) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Core traits and error types of the [rand] library, plus tools for implementing +RNGs. + +This crate is intended for use when implementing the core trait, `RngCore`; it +defines the core traits to be implemented as well as several small functions to +aid in their implementation and types required for error handling. + +The main [rand] crate re-exports most items defined in this crate, along with +tools to convert the integer samples generated by `RngCore` to many different +applications (including sampling from restricted ranges, conversion to floating +point, list permutations and secure initialisation of RNGs). Most users should +prefer to use the main [rand] crate. + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_core) +- [API documentation (docs.rs)](https://docs.rs/rand_core) +- [Changelog](CHANGELOG.md) + +[rand]: https://crates.io/crates/rand + + +## Functionality + +The `rand_core` crate provides: + +- base random number generator traits +- error-reporting types +- functionality to aid implementation of RNGs + +The traits and error types are also available via `rand`. + +## Crate Features + +`rand_core` supports `no_std` and `alloc`-only configurations, as well as full +`std` functionality. The differences between `no_std` and full `std` are small, +comprising `RngCore` support for `Box` types where `R: RngCore`, as well as +extensions to the `Error` type's functionality. + +Due to [rust-lang/cargo#1596](https://github.com/rust-lang/cargo/issues/1596), +`rand_core` is built without `std` support by default. Since features are +unioned across the whole dependency tree, any crate using `rand` with its +default features will also enable `std` support in `rand_core`. + +The `serde1` feature can be used to derive `Serialize` and `Deserialize` for RNG +implementations that use the `BlockRng` or `BlockRng64` wrappers. + + +# License + +`rand_core` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_core-0.3.1/src/block.rs b/bash-5.1/vendor/rand_core-0.3.1/src/block.rs new file mode 100644 index 0000000..3045b94 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/src/block.rs @@ -0,0 +1,499 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The `BlockRngCore` trait and implementation helpers +//! +//! The [`BlockRngCore`] trait exists to assist in the implementation of RNGs +//! which generate a block of data in a cache instead of returning generated +//! values directly. +//! +//! Usage of this trait is optional, but provides two advantages: +//! implementations only need to concern themselves with generation of the +//! block, not the various [`RngCore`] methods (especially [`fill_bytes`], where +//! the optimal implementations are not trivial), and this allows +//! `ReseedingRng` (see [`rand`](https://docs.rs/rand) crate) perform periodic +//! reseeding with very low overhead. +//! +//! # Example +//! +//! ```norun +//! use rand_core::block::{BlockRngCore, BlockRng}; +//! +//! struct MyRngCore; +//! +//! impl BlockRngCore for MyRngCore { +//! type Results = [u32; 16]; +//! +//! fn generate(&mut self, results: &mut Self::Results) { +//! unimplemented!() +//! } +//! } +//! +//! impl SeedableRng for MyRngCore { +//! type Seed = unimplemented!(); +//! fn from_seed(seed: Self::Seed) -> Self { +//! unimplemented!() +//! } +//! } +//! +//! // optionally, also implement CryptoRng for MyRngCore +//! +//! // Final RNG. +//! type MyRng = BlockRng; +//! ``` +//! +//! [`BlockRngCore`]: crate::block::BlockRngCore +//! [`fill_bytes`]: RngCore::fill_bytes + +use core::convert::AsRef; +use core::fmt; +use {RngCore, CryptoRng, SeedableRng, Error}; +use impls::{fill_via_u32_chunks, fill_via_u64_chunks}; + +/// A trait for RNGs which do not generate random numbers individually, but in +/// blocks (typically `[u32; N]`). This technique is commonly used by +/// cryptographic RNGs to improve performance. +/// +/// See the [module][crate::block] documentation for details. +pub trait BlockRngCore { + /// Results element type, e.g. `u32`. + type Item; + + /// Results type. This is the 'block' an RNG implementing `BlockRngCore` + /// generates, which will usually be an array like `[u32; 16]`. + type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default; + + /// Generate a new block of results. + fn generate(&mut self, results: &mut Self::Results); +} + + +/// A wrapper type implementing [`RngCore`] for some type implementing +/// [`BlockRngCore`] with `u32` array buffer; i.e. this can be used to implement +/// a full RNG from just a `generate` function. +/// +/// The `core` field may be accessed directly but the results buffer may not. +/// PRNG implementations can simply use a type alias +/// (`pub type MyRng = BlockRng;`) but might prefer to use a +/// wrapper type (`pub struct MyRng(BlockRng);`); the latter must +/// re-implement `RngCore` but hides the implementation details and allows +/// extra functionality to be defined on the RNG +/// (e.g. `impl MyRng { fn set_stream(...){...} }`). +/// +/// `BlockRng` has heavily optimized implementations of the [`RngCore`] methods +/// reading values from the results buffer, as well as +/// calling [`BlockRngCore::generate`] directly on the output array when +/// [`fill_bytes`] / [`try_fill_bytes`] is called on a large array. These methods +/// also handle the bookkeeping of when to generate a new batch of values. +/// +/// No whole generated `u32` values are thown away and all values are consumed +/// in-order. [`next_u32`] simply takes the next available `u32` value. +/// [`next_u64`] is implemented by combining two `u32` values, least +/// significant first. [`fill_bytes`] and [`try_fill_bytes`] consume a whole +/// number of `u32` values, converting each `u32` to a byte slice in +/// little-endian order. If the requested byte length is not a multiple of 4, +/// some bytes will be discarded. +/// +/// See also [`BlockRng64`] which uses `u64` array buffers. Currently there is +/// no direct support for other buffer types. +/// +/// For easy initialization `BlockRng` also implements [`SeedableRng`]. +/// +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct BlockRng { + results: R::Results, + index: usize, + /// The *core* part of the RNG, implementing the `generate` function. + pub core: R, +} + +// Custom Debug implementation that does not expose the contents of `results`. +impl fmt::Debug for BlockRng { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("BlockRng") + .field("core", &self.core) + .field("result_len", &self.results.as_ref().len()) + .field("index", &self.index) + .finish() + } +} + +impl BlockRng { + /// Create a new `BlockRng` from an existing RNG implementing + /// `BlockRngCore`. Results will be generated on first use. + pub fn new(core: R) -> BlockRng{ + let results_empty = R::Results::default(); + BlockRng { + core, + index: results_empty.as_ref().len(), + results: results_empty, + } + } + + /// Get the index into the result buffer. + /// + /// If this is equal to or larger than the size of the result buffer then + /// the buffer is "empty" and `generate()` must be called to produce new + /// results. + pub fn index(&self) -> usize { + self.index + } + + /// Reset the number of available results. + /// This will force a new set of results to be generated on next use. + pub fn reset(&mut self) { + self.index = self.results.as_ref().len(); + } + + /// Generate a new set of results immediately, setting the index to the + /// given value. + pub fn generate_and_set(&mut self, index: usize) { + assert!(index < self.results.as_ref().len()); + self.core.generate(&mut self.results); + self.index = index; + } +} + +impl> RngCore for BlockRng +where ::Results: AsRef<[u32]> + AsMut<[u32]> +{ + #[inline(always)] + fn next_u32(&mut self) -> u32 { + if self.index >= self.results.as_ref().len() { + self.generate_and_set(0); + } + + let value = self.results.as_ref()[self.index]; + self.index += 1; + value + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + let read_u64 = |results: &[u32], index| { + if cfg!(any(target_arch = "x86", target_arch = "x86_64")) { + // requires little-endian CPU supporting unaligned reads: + unsafe { *(&results[index] as *const u32 as *const u64) } + } else { + let x = u64::from(results[index]); + let y = u64::from(results[index + 1]); + (y << 32) | x + } + }; + + let len = self.results.as_ref().len(); + + let index = self.index; + if index < len-1 { + self.index += 2; + // Read an u64 from the current index + read_u64(self.results.as_ref(), index) + } else if index >= len { + self.generate_and_set(2); + read_u64(self.results.as_ref(), 0) + } else { + let x = u64::from(self.results.as_ref()[len-1]); + self.generate_and_set(1); + let y = u64::from(self.results.as_ref()[0]); + (y << 32) | x + } + } + + // As an optimization we try to write directly into the output buffer. + // This is only enabled for little-endian platforms where unaligned writes + // are known to be safe and fast. + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut filled = 0; + + // Continue filling from the current set of results + if self.index < self.results.as_ref().len() { + let (consumed_u32, filled_u8) = + fill_via_u32_chunks(&self.results.as_ref()[self.index..], + dest); + + self.index += consumed_u32; + filled += filled_u8; + } + + let len_remainder = + (dest.len() - filled) % (self.results.as_ref().len() * 4); + let end_direct = dest.len() - len_remainder; + + while filled < end_direct { + let dest_u32: &mut R::Results = unsafe { + &mut *(dest[filled..].as_mut_ptr() as + *mut ::Results) + }; + self.core.generate(dest_u32); + filled += self.results.as_ref().len() * 4; + self.index = self.results.as_ref().len(); + } + + if len_remainder > 0 { + self.core.generate(&mut self.results); + let (consumed_u32, _) = + fill_via_u32_chunks(self.results.as_ref(), + &mut dest[filled..]); + + self.index = consumed_u32; + } + } + + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut read_len = 0; + while read_len < dest.len() { + if self.index >= self.results.as_ref().len() { + self.generate_and_set(0); + } + let (consumed_u32, filled_u8) = + fill_via_u32_chunks(&self.results.as_ref()[self.index..], + &mut dest[read_len..]); + + self.index += consumed_u32; + read_len += filled_u8; + } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.fill_bytes(dest); + Ok(()) + } +} + +impl SeedableRng for BlockRng { + type Seed = R::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + Self::new(R::from_seed(seed)) + } + + fn seed_from_u64(seed: u64) -> Self { + Self::new(R::seed_from_u64(seed)) + } + + fn from_rng(rng: S) -> Result { + Ok(Self::new(R::from_rng(rng)?)) + } +} + + + +/// A wrapper type implementing [`RngCore`] for some type implementing +/// [`BlockRngCore`] with `u64` array buffer; i.e. this can be used to implement +/// a full RNG from just a `generate` function. +/// +/// This is similar to [`BlockRng`], but specialized for algorithms that operate +/// on `u64` values. +/// +/// No whole generated `u64` values are thrown away and all values are consumed +/// in-order. [`next_u64`] simply takes the next available `u64` value. +/// [`next_u32`] is however a bit special: half of a `u64` is consumed, leaving +/// the other half in the buffer. If the next function called is [`next_u32`] +/// then the other half is then consumed, however both [`next_u64`] and +/// [`fill_bytes`] discard the rest of any half-consumed `u64`s when called. +/// +/// [`fill_bytes`] and [`try_fill_bytes`] consume a whole number of `u64` +/// values. If the requested length is not a multiple of 8, some bytes will be +/// discarded. +/// +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct BlockRng64 { + results: R::Results, + index: usize, + half_used: bool, // true if only half of the previous result is used + /// The *core* part of the RNG, implementing the `generate` function. + pub core: R, +} + +// Custom Debug implementation that does not expose the contents of `results`. +impl fmt::Debug for BlockRng64 { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("BlockRng64") + .field("core", &self.core) + .field("result_len", &self.results.as_ref().len()) + .field("index", &self.index) + .field("half_used", &self.half_used) + .finish() + } +} + +impl BlockRng64 { + /// Create a new `BlockRng` from an existing RNG implementing + /// `BlockRngCore`. Results will be generated on first use. + pub fn new(core: R) -> BlockRng64{ + let results_empty = R::Results::default(); + BlockRng64 { + core, + index: results_empty.as_ref().len(), + half_used: false, + results: results_empty, + } + } + + /// Get the index into the result buffer. + /// + /// If this is equal to or larger than the size of the result buffer then + /// the buffer is "empty" and `generate()` must be called to produce new + /// results. + pub fn index(&self) -> usize { + self.index + } + + /// Reset the number of available results. + /// This will force a new set of results to be generated on next use. + pub fn reset(&mut self) { + self.index = self.results.as_ref().len(); + self.half_used = false; + } + + /// Generate a new set of results immediately, setting the index to the + /// given value. + pub fn generate_and_set(&mut self, index: usize) { + assert!(index < self.results.as_ref().len()); + self.core.generate(&mut self.results); + self.index = index; + self.half_used = false; + } +} + +impl> RngCore for BlockRng64 +where ::Results: AsRef<[u64]> + AsMut<[u64]> +{ + #[inline(always)] + fn next_u32(&mut self) -> u32 { + let mut index = self.index * 2 - self.half_used as usize; + if index >= self.results.as_ref().len() * 2 { + self.core.generate(&mut self.results); + self.index = 0; + // `self.half_used` is by definition `false` + self.half_used = false; + index = 0; + } + + self.half_used = !self.half_used; + self.index += self.half_used as usize; + + // Index as if this is a u32 slice. + unsafe { + let results = + &*(self.results.as_ref() as *const [u64] as *const [u32]); + if cfg!(target_endian = "little") { + *results.get_unchecked(index) + } else { + *results.get_unchecked(index ^ 1) + } + } + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + if self.index >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + } + + let value = self.results.as_ref()[self.index]; + self.index += 1; + self.half_used = false; + value + } + + // As an optimization we try to write directly into the output buffer. + // This is only enabled for little-endian platforms where unaligned writes + // are known to be safe and fast. + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut filled = 0; + self.half_used = false; + + // Continue filling from the current set of results + if self.index < self.results.as_ref().len() { + let (consumed_u64, filled_u8) = + fill_via_u64_chunks(&self.results.as_ref()[self.index..], + dest); + + self.index += consumed_u64; + filled += filled_u8; + } + + let len_remainder = + (dest.len() - filled) % (self.results.as_ref().len() * 8); + let end_direct = dest.len() - len_remainder; + + while filled < end_direct { + let dest_u64: &mut R::Results = unsafe { + ::core::mem::transmute(dest[filled..].as_mut_ptr()) + }; + self.core.generate(dest_u64); + filled += self.results.as_ref().len() * 8; + self.index = self.results.as_ref().len(); + } + + if len_remainder > 0 { + self.core.generate(&mut self.results); + let (consumed_u64, _) = + fill_via_u64_chunks(&mut self.results.as_ref(), + &mut dest[filled..]); + + self.index = consumed_u64; + } + } + + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut read_len = 0; + self.half_used = false; + while read_len < dest.len() { + if self.index as usize >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + } + + let (consumed_u64, filled_u8) = + fill_via_u64_chunks(&self.results.as_ref()[self.index as usize..], + &mut dest[read_len..]); + + self.index += consumed_u64; + read_len += filled_u8; + } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl SeedableRng for BlockRng64 { + type Seed = R::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + Self::new(R::from_seed(seed)) + } + + fn seed_from_u64(seed: u64) -> Self { + Self::new(R::seed_from_u64(seed)) + } + + fn from_rng(rng: S) -> Result { + Ok(Self::new(R::from_rng(rng)?)) + } +} + +impl CryptoRng for BlockRng {} diff --git a/bash-5.1/vendor/rand_core-0.3.1/src/error.rs b/bash-5.1/vendor/rand_core-0.3.1/src/error.rs new file mode 100644 index 0000000..5a8459e --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/src/error.rs @@ -0,0 +1,177 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Error types + +use core::fmt; + +#[cfg(feature="std")] +use std::error::Error as stdError; +#[cfg(feature="std")] +use std::io; + +/// Error kind which can be matched over. +#[derive(PartialEq, Eq, Debug, Copy, Clone)] +pub enum ErrorKind { + /// Feature is not available; not recoverable. + /// + /// This is the most permanent failure type and implies the error cannot be + /// resolved simply by retrying (e.g. the feature may not exist in this + /// build of the application or on the current platform). + Unavailable, + /// General failure; there may be a chance of recovery on retry. + /// + /// This is the catch-all kind for errors from known and unknown sources + /// which do not have a more specific kind / handling method. + /// + /// It is suggested to retry a couple of times or retry later when + /// handling; some error sources may be able to resolve themselves, + /// although this is not likely. + Unexpected, + /// A transient failure which likely can be resolved or worked around. + /// + /// This error kind exists for a few specific cases where it is known that + /// the error likely can be resolved internally, but is reported anyway. + Transient, + /// Not ready yet: recommended to try again a little later. + /// + /// This error kind implies the generator needs more time or needs some + /// other part of the application to do something else first before it is + /// ready for use; for example this may be used by external generators + /// which require time for initialization. + NotReady, + #[doc(hidden)] + __Nonexhaustive, +} + +impl ErrorKind { + /// True if this kind of error may resolve itself on retry. + /// + /// See also `should_wait()`. + pub fn should_retry(self) -> bool { + self != ErrorKind::Unavailable + } + + /// True if we should retry but wait before retrying + /// + /// This implies `should_retry()` is true. + pub fn should_wait(self) -> bool { + self == ErrorKind::NotReady + } + + /// A description of this error kind + pub fn description(self) -> &'static str { + match self { + ErrorKind::Unavailable => "permanently unavailable", + ErrorKind::Unexpected => "unexpected failure", + ErrorKind::Transient => "transient failure", + ErrorKind::NotReady => "not ready yet", + ErrorKind::__Nonexhaustive => unreachable!(), + } + } +} + + +/// Error type of random number generators +/// +/// This is a relatively simple error type, designed for compatibility with and +/// without the Rust `std` library. It embeds a "kind" code, a message (static +/// string only), and an optional chained cause (`std` only). The `kind` and +/// `msg` fields can be accessed directly; cause can be accessed via +/// `std::error::Error::cause` or `Error::take_cause`. Construction can only be +/// done via `Error::new` or `Error::with_cause`. +#[derive(Debug)] +pub struct Error { + /// The error kind + pub kind: ErrorKind, + /// The error message + pub msg: &'static str, + #[cfg(feature="std")] + cause: Option>, +} + +impl Error { + /// Create a new instance, with specified kind and a message. + pub fn new(kind: ErrorKind, msg: &'static str) -> Self { + #[cfg(feature="std")] { + Error { kind, msg, cause: None } + } + #[cfg(not(feature="std"))] { + Error { kind, msg } + } + } + + /// Create a new instance, with specified kind, message, and a + /// chained cause. + /// + /// Note: `stdError` is an alias for `std::error::Error`. + /// + /// If not targetting `std` (i.e. `no_std`), this function is replaced by + /// another with the same prototype, except that there are no bounds on the + /// type `E` (because both `Box` and `stdError` are unavailable), and the + /// `cause` is ignored. + #[cfg(feature="std")] + pub fn with_cause(kind: ErrorKind, msg: &'static str, cause: E) -> Self + where E: Into> + { + Error { kind, msg, cause: Some(cause.into()) } + } + + /// Create a new instance, with specified kind, message, and a + /// chained cause. + /// + /// In `no_std` mode the *cause* is ignored. + #[cfg(not(feature="std"))] + pub fn with_cause(kind: ErrorKind, msg: &'static str, _cause: E) -> Self { + Error { kind, msg } + } + + /// Take the cause, if any. This allows the embedded cause to be extracted. + /// This uses `Option::take`, leaving `self` with no cause. + #[cfg(feature="std")] + pub fn take_cause(&mut self) -> Option> { + self.cause.take() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + #[cfg(feature="std")] { + if let Some(ref cause) = self.cause { + return write!(f, "{} ({}); cause: {}", + self.msg, self.kind.description(), cause); + } + } + write!(f, "{} ({})", self.msg, self.kind.description()) + } +} + +#[cfg(feature="std")] +impl stdError for Error { + fn description(&self) -> &str { + self.msg + } + + fn cause(&self) -> Option<&stdError> { + self.cause.as_ref().map(|e| e.as_ref() as &stdError) + } +} + +#[cfg(feature="std")] +impl From for io::Error { + fn from(error: Error) -> Self { + use std::io::ErrorKind::*; + match error.kind { + ErrorKind::Unavailable => io::Error::new(NotFound, error), + ErrorKind::Unexpected | + ErrorKind::Transient => io::Error::new(Other, error), + ErrorKind::NotReady => io::Error::new(WouldBlock, error), + ErrorKind::__Nonexhaustive => unreachable!(), + } + } +} diff --git a/bash-5.1/vendor/rand_core-0.3.1/src/impls.rs b/bash-5.1/vendor/rand_core-0.3.1/src/impls.rs new file mode 100644 index 0000000..57bdd07 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/src/impls.rs @@ -0,0 +1,165 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Helper functions for implementing `RngCore` functions. +//! +//! For cross-platform reproducibility, these functions all use Little Endian: +//! least-significant part first. For example, `next_u64_via_u32` takes `u32` +//! values `x, y`, then outputs `(y << 32) | x`. To implement `next_u32` +//! from `next_u64` in little-endian order, one should use `next_u64() as u32`. +//! +//! Byte-swapping (like the std `to_le` functions) is only needed to convert +//! to/from byte sequences, and since its purpose is reproducibility, +//! non-reproducible sources (e.g. `OsRng`) need not bother with it. + +use core::intrinsics::transmute; +use core::ptr::copy_nonoverlapping; +use core::slice; +use core::cmp::min; +use core::mem::size_of; +use RngCore; + + +/// Implement `next_u64` via `next_u32`, little-endian order. +pub fn next_u64_via_u32(rng: &mut R) -> u64 { + // Use LE; we explicitly generate one value before the next. + let x = u64::from(rng.next_u32()); + let y = u64::from(rng.next_u32()); + (y << 32) | x +} + +/// Implement `fill_bytes` via `next_u64` and `next_u32`, little-endian order. +/// +/// The fastest way to fill a slice is usually to work as long as possible with +/// integers. That is why this method mostly uses `next_u64`, and only when +/// there are 4 or less bytes remaining at the end of the slice it uses +/// `next_u32` once. +pub fn fill_bytes_via_next(rng: &mut R, dest: &mut [u8]) { + let mut left = dest; + while left.len() >= 8 { + let (l, r) = {left}.split_at_mut(8); + left = r; + let chunk: [u8; 8] = unsafe { + transmute(rng.next_u64().to_le()) + }; + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 4 { + let chunk: [u8; 8] = unsafe { + transmute(rng.next_u64().to_le()) + }; + left.copy_from_slice(&chunk[..n]); + } else if n > 0 { + let chunk: [u8; 4] = unsafe { + transmute(rng.next_u32().to_le()) + }; + left.copy_from_slice(&chunk[..n]); + } +} + +macro_rules! impl_uint_from_fill { + ($rng:expr, $ty:ty, $N:expr) => ({ + debug_assert!($N == size_of::<$ty>()); + + let mut int: $ty = 0; + unsafe { + let ptr = &mut int as *mut $ty as *mut u8; + let slice = slice::from_raw_parts_mut(ptr, $N); + $rng.fill_bytes(slice); + } + int + }); +} + +macro_rules! fill_via_chunks { + ($src:expr, $dst:expr, $ty:ty, $size:expr) => ({ + let chunk_size_u8 = min($src.len() * $size, $dst.len()); + let chunk_size = (chunk_size_u8 + $size - 1) / $size; + if cfg!(target_endian="little") { + unsafe { + copy_nonoverlapping( + $src.as_ptr() as *const u8, + $dst.as_mut_ptr(), + chunk_size_u8); + } + } else { + for (&n, chunk) in $src.iter().zip($dst.chunks_mut($size)) { + let tmp = n.to_le(); + let src_ptr = &tmp as *const $ty as *const u8; + unsafe { + copy_nonoverlapping(src_ptr, + chunk.as_mut_ptr(), + chunk.len()); + } + } + } + + (chunk_size, chunk_size_u8) + }); +} + +/// Implement `fill_bytes` by reading chunks from the output buffer of a block +/// based RNG. +/// +/// The return values are `(consumed_u32, filled_u8)`. +/// +/// `filled_u8` is the number of filled bytes in `dest`, which may be less than +/// the length of `dest`. +/// `consumed_u32` is the number of words consumed from `src`, which is the same +/// as `filled_u8 / 4` rounded up. +/// +/// # Example +/// (from `IsaacRng`) +/// +/// ```ignore +/// fn fill_bytes(&mut self, dest: &mut [u8]) { +/// let mut read_len = 0; +/// while read_len < dest.len() { +/// if self.index >= self.rsl.len() { +/// self.isaac(); +/// } +/// +/// let (consumed_u32, filled_u8) = +/// impls::fill_via_u32_chunks(&mut self.rsl[self.index..], +/// &mut dest[read_len..]); +/// +/// self.index += consumed_u32; +/// read_len += filled_u8; +/// } +/// } +/// ``` +pub fn fill_via_u32_chunks(src: &[u32], dest: &mut [u8]) -> (usize, usize) { + fill_via_chunks!(src, dest, u32, 4) +} + +/// Implement `fill_bytes` by reading chunks from the output buffer of a block +/// based RNG. +/// +/// The return values are `(consumed_u64, filled_u8)`. +/// `filled_u8` is the number of filled bytes in `dest`, which may be less than +/// the length of `dest`. +/// `consumed_u64` is the number of words consumed from `src`, which is the same +/// as `filled_u8 / 8` rounded up. +/// +/// See `fill_via_u32_chunks` for an example. +pub fn fill_via_u64_chunks(src: &[u64], dest: &mut [u8]) -> (usize, usize) { + fill_via_chunks!(src, dest, u64, 8) +} + +/// Implement `next_u32` via `fill_bytes`, little-endian order. +pub fn next_u32_via_fill(rng: &mut R) -> u32 { + impl_uint_from_fill!(rng, u32, 4) +} + +/// Implement `next_u64` via `fill_bytes`, little-endian order. +pub fn next_u64_via_fill(rng: &mut R) -> u64 { + impl_uint_from_fill!(rng, u64, 8) +} + +// TODO: implement tests for the above diff --git a/bash-5.1/vendor/rand_core-0.3.1/src/le.rs b/bash-5.1/vendor/rand_core-0.3.1/src/le.rs new file mode 100644 index 0000000..266651f --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/src/le.rs @@ -0,0 +1,68 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Little-Endian utilities +//! +//! Little-Endian order has been chosen for internal usage; this makes some +//! useful functions available. + +use core::ptr; + +macro_rules! read_slice { + ($src:expr, $dst:expr, $size:expr, $which:ident) => {{ + assert_eq!($src.len(), $size * $dst.len()); + + unsafe { + ptr::copy_nonoverlapping( + $src.as_ptr(), + $dst.as_mut_ptr() as *mut u8, + $src.len()); + } + for v in $dst.iter_mut() { + *v = v.$which(); + } + }}; +} + +/// Reads unsigned 32 bit integers from `src` into `dst`. +/// Borrowed from the `byteorder` crate. +#[inline] +pub fn read_u32_into(src: &[u8], dst: &mut [u32]) { + read_slice!(src, dst, 4, to_le); +} + +/// Reads unsigned 64 bit integers from `src` into `dst`. +/// Borrowed from the `byteorder` crate. +#[inline] +pub fn read_u64_into(src: &[u8], dst: &mut [u64]) { + read_slice!(src, dst, 8, to_le); +} + +#[test] +fn test_read() { + let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + + let mut buf = [0u32; 4]; + read_u32_into(&bytes, &mut buf); + assert_eq!(buf[0], 0x04030201); + assert_eq!(buf[3], 0x100F0E0D); + + let mut buf = [0u32; 3]; + read_u32_into(&bytes[1..13], &mut buf); // unaligned + assert_eq!(buf[0], 0x05040302); + assert_eq!(buf[2], 0x0D0C0B0A); + + let mut buf = [0u64; 2]; + read_u64_into(&bytes, &mut buf); + assert_eq!(buf[0], 0x0807060504030201); + assert_eq!(buf[1], 0x100F0E0D0C0B0A09); + + let mut buf = [0u64; 1]; + read_u64_into(&bytes[7..15], &mut buf); // unaligned + assert_eq!(buf[0], 0x0F0E0D0C0B0A0908); +} diff --git a/bash-5.1/vendor/rand_core-0.3.1/src/lib.rs b/bash-5.1/vendor/rand_core-0.3.1/src/lib.rs new file mode 100644 index 0000000..8923142 --- /dev/null +++ b/bash-5.1/vendor/rand_core-0.3.1/src/lib.rs @@ -0,0 +1,46 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Random number generation traits +//! +//! This version of `rand_core` is a compatibility shim around version 0.3. +//! +//! This crate is mainly of interest to crates publishing implementations of +//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead +//! which re-exports the main traits and error types. +//! +//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number +//! generators and external random-number sources. +//! +//! [`SeedableRng`] is an extension trait for construction from fixed seeds and +//! other random number generators. +//! +//! [`Error`] is provided for error-handling. It is safe to use in `no_std` +//! environments. +//! +//! The [`impls`] and [`le`] sub-modules include a few small functions to assist +//! implementation of [`RngCore`]. +//! +//! [`rand`]: https://docs.rs/rand + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![no_std] + +extern crate rand_core as core4; + +pub use core4::{ErrorKind, Error}; +pub use core4::{block, impls, le}; +pub use core4::{RngCore, CryptoRng, SeedableRng}; diff --git a/bash-5.1/vendor/rand_core/.cargo-checksum.json b/bash-5.1/vendor/rand_core/.cargo-checksum.json new file mode 100644 index 0000000..958d0a4 --- /dev/null +++ b/bash-5.1/vendor/rand_core/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"41e587d62ec904ec1bf97a8137a74fd5f502beb30dc0d03c0db380d136d92b3a","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"9b2e5c9dd0041a4ab2f887a7054c7fe0e03715899cc55a8250a9fd296aa4fb5b","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"ec960eb9636ab8278e80815603187f7c8f0d8f6bc0683ebf86ad9963b9a6da97","src/block.rs":"1cd85e129bf8bf0653244dcf129b916aa5b2fa510fd0199f838c754e113c7ce3","src/error.rs":"8403a968d7c9bd95cc9f23d9dc5cc4771ede8e81dda5a8fdd59d347590345d14","src/impls.rs":"c248ddd04a65c974768baaec028fa0d2a6117525fa27bce8a98f2ba2f352700a","src/le.rs":"cb187f58f7514877918f7f47633397e08e20392dcf072bc245d62c9e5238198c","src/lib.rs":"65ef1545f6054eb19b6fb5ef8aced95acff51cc252fb0d032af49161493f3c8c"},"package":"9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_core/CHANGELOG.md b/bash-5.1/vendor/rand_core/CHANGELOG.md new file mode 100644 index 0000000..356f4d1 --- /dev/null +++ b/bash-5.1/vendor/rand_core/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.4.2] - 2019-08-01 +Back-port non-API changes from version 0.5.0: +- Enable testing with Miri and fix incorrect pointer usages (#779, #780, #781, #783, #784) +- Adjust usage of `#[inline]` for `BlockRng` and `BlockRng64` + +## [0.4.0] - 2019-01-24 +- Disable the `std` feature by default (#702) + +## [0.3.0] - 2018-09-24 +- Add `SeedableRng::seed_from_u64` for convenient seeding. (#537) + +## [0.2.1] - 2018-06-08 +- References to a `CryptoRng` now also implement `CryptoRng`. (#470) + +## [0.2.0] - 2018-05-21 +- Enable the `std` feature by default. (#409) +- Remove `BlockRng{64}::inner` and `BlockRng::inner_mut`; instead making `core` public +- Add `BlockRng{64}::index` and `BlockRng{64}::generate_and_set`. (#374, #419) +- Change `BlockRngCore::Results` bound to also require `AsMut<[Self::Item]>`. (#419) +- Implement `std::io::Read` for RngCore. (#434) + +## [0.1.0] - 2018-04-17 +(Split out of the Rand crate, changes here are relative to rand 0.4.2) +- `RngCore` and `SeedableRng` are now part of `rand_core`. (#288) +- Add modules to help implementing RNGs `impl` and `le`. (#209, #228) +- Add `Error` and `ErrorKind`. (#225) +- Add `CryptoRng` marker trait. (#273) +- Add `BlockRngCore` trait. (#281) +- Add `BlockRng` and `BlockRng64` wrappers to help implementations. (#281, #325) +- Revise the `SeedableRng` trait. (#233) +- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. (#288) +- Add `RngCore::try_fill_bytes`. (#225) + +## [0.0.1] - 2017-09-14 (yanked) +Experimental version as part of the rand crate refactor. diff --git a/bash-5.1/vendor/rand_core/COPYRIGHT b/bash-5.1/vendor/rand_core/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_core/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_core/Cargo.toml b/bash-5.1/vendor/rand_core/Cargo.toml new file mode 100644 index 0000000..01d8ced --- /dev/null +++ b/bash-5.1/vendor/rand_core/Cargo.toml @@ -0,0 +1,41 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_core" +version = "0.4.2" +authors = ["The Rand Project Developers", "The Rust Project Developers"] +description = "Core random number generator traits and tools for implementation.\n" +homepage = "https://crates.io/crates/rand_core" +documentation = "https://rust-random.github.io/rand/rand_core/" +readme = "README.md" +keywords = ["random", "rng"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.serde] +version = "1" +optional = true + +[dependencies.serde_derive] +version = "^1.0.38" +optional = true + +[features] +alloc = [] +serde1 = ["serde", "serde_derive"] +std = ["alloc"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_core/LICENSE-APACHE b/bash-5.1/vendor/rand_core/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_core/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_core/LICENSE-MIT b/bash-5.1/vendor/rand_core/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_core/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_core/README.md b/bash-5.1/vendor/rand_core/README.md new file mode 100644 index 0000000..0ac8b91 --- /dev/null +++ b/bash-5.1/vendor/rand_core/README.md @@ -0,0 +1,77 @@ +# rand_core + +[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_core.svg)](https://crates.io/crates/rand_core) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_core) +[![API](https://docs.rs/rand_core/badge.svg)](https://docs.rs/rand_core) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Core traits and error types of the [rand] library, plus tools for implementing +RNGs. + +This crate is intended for use when implementing the core trait, `RngCore`; it +defines the core traits to be implemented as well as several small functions to +aid in their implementation and types required for error handling. + +The main [rand] crate re-exports most items defined in this crate, along with +tools to convert the integer samples generated by `RngCore` to many different +applications (including sampling from restricted ranges, conversion to floating +point, list permutations and secure initialisation of RNGs). Most users should +prefer to use the main [rand] crate. + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_core) +- [API documentation (docs.rs)](https://docs.rs/rand_core) +- [Changelog](CHANGELOG.md) + +[rand]: https://crates.io/crates/rand + + +## Functionality + +The `rand_core` crate provides: + +- base random number generator traits +- error-reporting types +- functionality to aid implementation of RNGs + +The traits and error types are also available via `rand`. + +## Versions + +Rand libs have inter-dependencies and make use of the +[semver trick](https://github.com/dtolnay/semver-trick/) in order to make traits +compatible across crate versions. (This is especially important for `RngCore` +and `SeedableRng`.) A few crate releases are thus compatibility shims, +depending on the *next* lib version (e.g. `rand_core` versions `0.2.2` and +`0.3.1`). This means, for example, that `rand_core_0_4_0::SeedableRng` and +`rand_core_0_3_0::SeedableRng` are distinct, incompatible traits, which can +cause build errors. Usually, running `cargo update` is enough to fix any issues. + +## Crate Features + +`rand_core` supports `no_std` and `alloc`-only configurations, as well as full +`std` functionality. The differences between `no_std` and full `std` are small, +comprising `RngCore` support for `Box` types where `R: RngCore`, +`std::io::Read` support for types supporting `RngCore`, and +extensions to the `Error` type's functionality. + +The `std` feature is *not enabled by default*. This is primarily to avoid build +problems where one crate implicitly requires `rand_core` with `std` support and +another crate requires `rand` *without* `std` support. However, the `rand` crate +continues to enable `std` support by default, both for itself and `rand_core`. + +The `serde1` feature can be used to derive `Serialize` and `Deserialize` for RNG +implementations that use the `BlockRng` or `BlockRng64` wrappers. + + +# License + +`rand_core` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_core/src/block.rs b/bash-5.1/vendor/rand_core/src/block.rs new file mode 100644 index 0000000..7d91263 --- /dev/null +++ b/bash-5.1/vendor/rand_core/src/block.rs @@ -0,0 +1,433 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The `BlockRngCore` trait and implementation helpers +//! +//! The [`BlockRngCore`] trait exists to assist in the implementation of RNGs +//! which generate a block of data in a cache instead of returning generated +//! values directly. +//! +//! Usage of this trait is optional, but provides two advantages: +//! implementations only need to concern themselves with generation of the +//! block, not the various [`RngCore`] methods (especially [`fill_bytes`], where +//! the optimal implementations are not trivial), and this allows +//! `ReseedingRng` (see [`rand`](https://docs.rs/rand) crate) perform periodic +//! reseeding with very low overhead. +//! +//! # Example +//! +//! ```norun +//! use rand_core::block::{BlockRngCore, BlockRng}; +//! +//! struct MyRngCore; +//! +//! impl BlockRngCore for MyRngCore { +//! type Results = [u32; 16]; +//! +//! fn generate(&mut self, results: &mut Self::Results) { +//! unimplemented!() +//! } +//! } +//! +//! impl SeedableRng for MyRngCore { +//! type Seed = unimplemented!(); +//! fn from_seed(seed: Self::Seed) -> Self { +//! unimplemented!() +//! } +//! } +//! +//! // optionally, also implement CryptoRng for MyRngCore +//! +//! // Final RNG. +//! type MyRng = BlockRng; +//! ``` +//! +//! [`BlockRngCore`]: crate::block::BlockRngCore +//! [`fill_bytes`]: RngCore::fill_bytes + +use core::convert::AsRef; +use core::{fmt, ptr}; +use {RngCore, CryptoRng, SeedableRng, Error}; +use impls::{fill_via_u32_chunks, fill_via_u64_chunks}; + +/// A trait for RNGs which do not generate random numbers individually, but in +/// blocks (typically `[u32; N]`). This technique is commonly used by +/// cryptographic RNGs to improve performance. +/// +/// See the [module][crate::block] documentation for details. +pub trait BlockRngCore { + /// Results element type, e.g. `u32`. + type Item; + + /// Results type. This is the 'block' an RNG implementing `BlockRngCore` + /// generates, which will usually be an array like `[u32; 16]`. + type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default; + + /// Generate a new block of results. + fn generate(&mut self, results: &mut Self::Results); +} + + +/// A wrapper type implementing [`RngCore`] for some type implementing +/// [`BlockRngCore`] with `u32` array buffer; i.e. this can be used to implement +/// a full RNG from just a `generate` function. +/// +/// The `core` field may be accessed directly but the results buffer may not. +/// PRNG implementations can simply use a type alias +/// (`pub type MyRng = BlockRng;`) but might prefer to use a +/// wrapper type (`pub struct MyRng(BlockRng);`); the latter must +/// re-implement `RngCore` but hides the implementation details and allows +/// extra functionality to be defined on the RNG +/// (e.g. `impl MyRng { fn set_stream(...){...} }`). +/// +/// `BlockRng` has heavily optimized implementations of the [`RngCore`] methods +/// reading values from the results buffer, as well as +/// calling [`BlockRngCore::generate`] directly on the output array when +/// [`fill_bytes`] / [`try_fill_bytes`] is called on a large array. These methods +/// also handle the bookkeeping of when to generate a new batch of values. +/// +/// No whole generated `u32` values are thown away and all values are consumed +/// in-order. [`next_u32`] simply takes the next available `u32` value. +/// [`next_u64`] is implemented by combining two `u32` values, least +/// significant first. [`fill_bytes`] and [`try_fill_bytes`] consume a whole +/// number of `u32` values, converting each `u32` to a byte slice in +/// little-endian order. If the requested byte length is not a multiple of 4, +/// some bytes will be discarded. +/// +/// See also [`BlockRng64`] which uses `u64` array buffers. Currently there is +/// no direct support for other buffer types. +/// +/// For easy initialization `BlockRng` also implements [`SeedableRng`]. +/// +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct BlockRng { + results: R::Results, + index: usize, + /// The *core* part of the RNG, implementing the `generate` function. + pub core: R, +} + +// Custom Debug implementation that does not expose the contents of `results`. +impl fmt::Debug for BlockRng { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("BlockRng") + .field("core", &self.core) + .field("result_len", &self.results.as_ref().len()) + .field("index", &self.index) + .finish() + } +} + +impl BlockRng { + /// Create a new `BlockRng` from an existing RNG implementing + /// `BlockRngCore`. Results will be generated on first use. + #[inline] + pub fn new(core: R) -> BlockRng{ + let results_empty = R::Results::default(); + BlockRng { + core, + index: results_empty.as_ref().len(), + results: results_empty, + } + } + + /// Get the index into the result buffer. + /// + /// If this is equal to or larger than the size of the result buffer then + /// the buffer is "empty" and `generate()` must be called to produce new + /// results. + #[inline(always)] + pub fn index(&self) -> usize { + self.index + } + + /// Reset the number of available results. + /// This will force a new set of results to be generated on next use. + #[inline] + pub fn reset(&mut self) { + self.index = self.results.as_ref().len(); + } + + /// Generate a new set of results immediately, setting the index to the + /// given value. + #[inline] + pub fn generate_and_set(&mut self, index: usize) { + assert!(index < self.results.as_ref().len()); + self.core.generate(&mut self.results); + self.index = index; + } +} + +impl> RngCore for BlockRng +where ::Results: AsRef<[u32]> + AsMut<[u32]> +{ + #[inline] + fn next_u32(&mut self) -> u32 { + if self.index >= self.results.as_ref().len() { + self.generate_and_set(0); + } + + let value = self.results.as_ref()[self.index]; + self.index += 1; + value + } + + #[inline] + fn next_u64(&mut self) -> u64 { + let read_u64 = |results: &[u32], index| { + if cfg!(any(target_endian = "little")) { + // requires little-endian CPU + let ptr: *const u64 = results[index..index+2].as_ptr() as *const u64; + unsafe { ptr::read_unaligned(ptr) } + } else { + let x = u64::from(results[index]); + let y = u64::from(results[index + 1]); + (y << 32) | x + } + }; + + let len = self.results.as_ref().len(); + + let index = self.index; + if index < len-1 { + self.index += 2; + // Read an u64 from the current index + read_u64(self.results.as_ref(), index) + } else if index >= len { + self.generate_and_set(2); + read_u64(self.results.as_ref(), 0) + } else { + let x = u64::from(self.results.as_ref()[len-1]); + self.generate_and_set(1); + let y = u64::from(self.results.as_ref()[0]); + (y << 32) | x + } + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut read_len = 0; + while read_len < dest.len() { + if self.index >= self.results.as_ref().len() { + self.generate_and_set(0); + } + let (consumed_u32, filled_u8) = + fill_via_u32_chunks(&self.results.as_ref()[self.index..], + &mut dest[read_len..]); + + self.index += consumed_u32; + read_len += filled_u8; + } + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl SeedableRng for BlockRng { + type Seed = R::Seed; + + #[inline(always)] + fn from_seed(seed: Self::Seed) -> Self { + Self::new(R::from_seed(seed)) + } + + #[inline(always)] + fn seed_from_u64(seed: u64) -> Self { + Self::new(R::seed_from_u64(seed)) + } + + #[inline(always)] + fn from_rng(rng: S) -> Result { + Ok(Self::new(R::from_rng(rng)?)) + } +} + + + +/// A wrapper type implementing [`RngCore`] for some type implementing +/// [`BlockRngCore`] with `u64` array buffer; i.e. this can be used to implement +/// a full RNG from just a `generate` function. +/// +/// This is similar to [`BlockRng`], but specialized for algorithms that operate +/// on `u64` values. +/// +/// No whole generated `u64` values are thrown away and all values are consumed +/// in-order. [`next_u64`] simply takes the next available `u64` value. +/// [`next_u32`] is however a bit special: half of a `u64` is consumed, leaving +/// the other half in the buffer. If the next function called is [`next_u32`] +/// then the other half is then consumed, however both [`next_u64`] and +/// [`fill_bytes`] discard the rest of any half-consumed `u64`s when called. +/// +/// [`fill_bytes`] and [`try_fill_bytes`] consume a whole number of `u64` +/// values. If the requested length is not a multiple of 8, some bytes will be +/// discarded. +/// +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct BlockRng64 { + results: R::Results, + index: usize, + half_used: bool, // true if only half of the previous result is used + /// The *core* part of the RNG, implementing the `generate` function. + pub core: R, +} + +// Custom Debug implementation that does not expose the contents of `results`. +impl fmt::Debug for BlockRng64 { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("BlockRng64") + .field("core", &self.core) + .field("result_len", &self.results.as_ref().len()) + .field("index", &self.index) + .field("half_used", &self.half_used) + .finish() + } +} + +impl BlockRng64 { + /// Create a new `BlockRng` from an existing RNG implementing + /// `BlockRngCore`. Results will be generated on first use. + #[inline] + pub fn new(core: R) -> BlockRng64{ + let results_empty = R::Results::default(); + BlockRng64 { + core, + index: results_empty.as_ref().len(), + half_used: false, + results: results_empty, + } + } + + /// Get the index into the result buffer. + /// + /// If this is equal to or larger than the size of the result buffer then + /// the buffer is "empty" and `generate()` must be called to produce new + /// results. + #[inline(always)] + pub fn index(&self) -> usize { + self.index + } + + /// Reset the number of available results. + /// This will force a new set of results to be generated on next use. + #[inline] + pub fn reset(&mut self) { + self.index = self.results.as_ref().len(); + self.half_used = false; + } + + /// Generate a new set of results immediately, setting the index to the + /// given value. + #[inline] + pub fn generate_and_set(&mut self, index: usize) { + assert!(index < self.results.as_ref().len()); + self.core.generate(&mut self.results); + self.index = index; + self.half_used = false; + } +} + +impl> RngCore for BlockRng64 +where ::Results: AsRef<[u64]> + AsMut<[u64]> +{ + #[inline] + fn next_u32(&mut self) -> u32 { + let mut index = self.index * 2 - self.half_used as usize; + if index >= self.results.as_ref().len() * 2 { + self.core.generate(&mut self.results); + self.index = 0; + // `self.half_used` is by definition `false` + self.half_used = false; + index = 0; + } + + self.half_used = !self.half_used; + self.index += self.half_used as usize; + + // Index as if this is a u32 slice. + unsafe { + let results = + &*(self.results.as_ref() as *const [u64] as *const [u32]); + if cfg!(target_endian = "little") { + *results.get_unchecked(index) + } else { + *results.get_unchecked(index ^ 1) + } + } + } + + #[inline] + fn next_u64(&mut self) -> u64 { + if self.index >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + } + + let value = self.results.as_ref()[self.index]; + self.index += 1; + self.half_used = false; + value + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut read_len = 0; + self.half_used = false; + while read_len < dest.len() { + if self.index as usize >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + } + + let (consumed_u64, filled_u8) = + fill_via_u64_chunks(&self.results.as_ref()[self.index as usize..], + &mut dest[read_len..]); + + self.index += consumed_u64; + read_len += filled_u8; + } + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl SeedableRng for BlockRng64 { + type Seed = R::Seed; + + #[inline(always)] + fn from_seed(seed: Self::Seed) -> Self { + Self::new(R::from_seed(seed)) + } + + #[inline(always)] + fn seed_from_u64(seed: u64) -> Self { + Self::new(R::seed_from_u64(seed)) + } + + #[inline(always)] + fn from_rng(rng: S) -> Result { + Ok(Self::new(R::from_rng(rng)?)) + } +} + +impl CryptoRng for BlockRng {} diff --git a/bash-5.1/vendor/rand_core/src/error.rs b/bash-5.1/vendor/rand_core/src/error.rs new file mode 100644 index 0000000..5a8459e --- /dev/null +++ b/bash-5.1/vendor/rand_core/src/error.rs @@ -0,0 +1,177 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Error types + +use core::fmt; + +#[cfg(feature="std")] +use std::error::Error as stdError; +#[cfg(feature="std")] +use std::io; + +/// Error kind which can be matched over. +#[derive(PartialEq, Eq, Debug, Copy, Clone)] +pub enum ErrorKind { + /// Feature is not available; not recoverable. + /// + /// This is the most permanent failure type and implies the error cannot be + /// resolved simply by retrying (e.g. the feature may not exist in this + /// build of the application or on the current platform). + Unavailable, + /// General failure; there may be a chance of recovery on retry. + /// + /// This is the catch-all kind for errors from known and unknown sources + /// which do not have a more specific kind / handling method. + /// + /// It is suggested to retry a couple of times or retry later when + /// handling; some error sources may be able to resolve themselves, + /// although this is not likely. + Unexpected, + /// A transient failure which likely can be resolved or worked around. + /// + /// This error kind exists for a few specific cases where it is known that + /// the error likely can be resolved internally, but is reported anyway. + Transient, + /// Not ready yet: recommended to try again a little later. + /// + /// This error kind implies the generator needs more time or needs some + /// other part of the application to do something else first before it is + /// ready for use; for example this may be used by external generators + /// which require time for initialization. + NotReady, + #[doc(hidden)] + __Nonexhaustive, +} + +impl ErrorKind { + /// True if this kind of error may resolve itself on retry. + /// + /// See also `should_wait()`. + pub fn should_retry(self) -> bool { + self != ErrorKind::Unavailable + } + + /// True if we should retry but wait before retrying + /// + /// This implies `should_retry()` is true. + pub fn should_wait(self) -> bool { + self == ErrorKind::NotReady + } + + /// A description of this error kind + pub fn description(self) -> &'static str { + match self { + ErrorKind::Unavailable => "permanently unavailable", + ErrorKind::Unexpected => "unexpected failure", + ErrorKind::Transient => "transient failure", + ErrorKind::NotReady => "not ready yet", + ErrorKind::__Nonexhaustive => unreachable!(), + } + } +} + + +/// Error type of random number generators +/// +/// This is a relatively simple error type, designed for compatibility with and +/// without the Rust `std` library. It embeds a "kind" code, a message (static +/// string only), and an optional chained cause (`std` only). The `kind` and +/// `msg` fields can be accessed directly; cause can be accessed via +/// `std::error::Error::cause` or `Error::take_cause`. Construction can only be +/// done via `Error::new` or `Error::with_cause`. +#[derive(Debug)] +pub struct Error { + /// The error kind + pub kind: ErrorKind, + /// The error message + pub msg: &'static str, + #[cfg(feature="std")] + cause: Option>, +} + +impl Error { + /// Create a new instance, with specified kind and a message. + pub fn new(kind: ErrorKind, msg: &'static str) -> Self { + #[cfg(feature="std")] { + Error { kind, msg, cause: None } + } + #[cfg(not(feature="std"))] { + Error { kind, msg } + } + } + + /// Create a new instance, with specified kind, message, and a + /// chained cause. + /// + /// Note: `stdError` is an alias for `std::error::Error`. + /// + /// If not targetting `std` (i.e. `no_std`), this function is replaced by + /// another with the same prototype, except that there are no bounds on the + /// type `E` (because both `Box` and `stdError` are unavailable), and the + /// `cause` is ignored. + #[cfg(feature="std")] + pub fn with_cause(kind: ErrorKind, msg: &'static str, cause: E) -> Self + where E: Into> + { + Error { kind, msg, cause: Some(cause.into()) } + } + + /// Create a new instance, with specified kind, message, and a + /// chained cause. + /// + /// In `no_std` mode the *cause* is ignored. + #[cfg(not(feature="std"))] + pub fn with_cause(kind: ErrorKind, msg: &'static str, _cause: E) -> Self { + Error { kind, msg } + } + + /// Take the cause, if any. This allows the embedded cause to be extracted. + /// This uses `Option::take`, leaving `self` with no cause. + #[cfg(feature="std")] + pub fn take_cause(&mut self) -> Option> { + self.cause.take() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + #[cfg(feature="std")] { + if let Some(ref cause) = self.cause { + return write!(f, "{} ({}); cause: {}", + self.msg, self.kind.description(), cause); + } + } + write!(f, "{} ({})", self.msg, self.kind.description()) + } +} + +#[cfg(feature="std")] +impl stdError for Error { + fn description(&self) -> &str { + self.msg + } + + fn cause(&self) -> Option<&stdError> { + self.cause.as_ref().map(|e| e.as_ref() as &stdError) + } +} + +#[cfg(feature="std")] +impl From for io::Error { + fn from(error: Error) -> Self { + use std::io::ErrorKind::*; + match error.kind { + ErrorKind::Unavailable => io::Error::new(NotFound, error), + ErrorKind::Unexpected | + ErrorKind::Transient => io::Error::new(Other, error), + ErrorKind::NotReady => io::Error::new(WouldBlock, error), + ErrorKind::__Nonexhaustive => unreachable!(), + } + } +} diff --git a/bash-5.1/vendor/rand_core/src/impls.rs b/bash-5.1/vendor/rand_core/src/impls.rs new file mode 100644 index 0000000..57bdd07 --- /dev/null +++ b/bash-5.1/vendor/rand_core/src/impls.rs @@ -0,0 +1,165 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Helper functions for implementing `RngCore` functions. +//! +//! For cross-platform reproducibility, these functions all use Little Endian: +//! least-significant part first. For example, `next_u64_via_u32` takes `u32` +//! values `x, y`, then outputs `(y << 32) | x`. To implement `next_u32` +//! from `next_u64` in little-endian order, one should use `next_u64() as u32`. +//! +//! Byte-swapping (like the std `to_le` functions) is only needed to convert +//! to/from byte sequences, and since its purpose is reproducibility, +//! non-reproducible sources (e.g. `OsRng`) need not bother with it. + +use core::intrinsics::transmute; +use core::ptr::copy_nonoverlapping; +use core::slice; +use core::cmp::min; +use core::mem::size_of; +use RngCore; + + +/// Implement `next_u64` via `next_u32`, little-endian order. +pub fn next_u64_via_u32(rng: &mut R) -> u64 { + // Use LE; we explicitly generate one value before the next. + let x = u64::from(rng.next_u32()); + let y = u64::from(rng.next_u32()); + (y << 32) | x +} + +/// Implement `fill_bytes` via `next_u64` and `next_u32`, little-endian order. +/// +/// The fastest way to fill a slice is usually to work as long as possible with +/// integers. That is why this method mostly uses `next_u64`, and only when +/// there are 4 or less bytes remaining at the end of the slice it uses +/// `next_u32` once. +pub fn fill_bytes_via_next(rng: &mut R, dest: &mut [u8]) { + let mut left = dest; + while left.len() >= 8 { + let (l, r) = {left}.split_at_mut(8); + left = r; + let chunk: [u8; 8] = unsafe { + transmute(rng.next_u64().to_le()) + }; + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 4 { + let chunk: [u8; 8] = unsafe { + transmute(rng.next_u64().to_le()) + }; + left.copy_from_slice(&chunk[..n]); + } else if n > 0 { + let chunk: [u8; 4] = unsafe { + transmute(rng.next_u32().to_le()) + }; + left.copy_from_slice(&chunk[..n]); + } +} + +macro_rules! impl_uint_from_fill { + ($rng:expr, $ty:ty, $N:expr) => ({ + debug_assert!($N == size_of::<$ty>()); + + let mut int: $ty = 0; + unsafe { + let ptr = &mut int as *mut $ty as *mut u8; + let slice = slice::from_raw_parts_mut(ptr, $N); + $rng.fill_bytes(slice); + } + int + }); +} + +macro_rules! fill_via_chunks { + ($src:expr, $dst:expr, $ty:ty, $size:expr) => ({ + let chunk_size_u8 = min($src.len() * $size, $dst.len()); + let chunk_size = (chunk_size_u8 + $size - 1) / $size; + if cfg!(target_endian="little") { + unsafe { + copy_nonoverlapping( + $src.as_ptr() as *const u8, + $dst.as_mut_ptr(), + chunk_size_u8); + } + } else { + for (&n, chunk) in $src.iter().zip($dst.chunks_mut($size)) { + let tmp = n.to_le(); + let src_ptr = &tmp as *const $ty as *const u8; + unsafe { + copy_nonoverlapping(src_ptr, + chunk.as_mut_ptr(), + chunk.len()); + } + } + } + + (chunk_size, chunk_size_u8) + }); +} + +/// Implement `fill_bytes` by reading chunks from the output buffer of a block +/// based RNG. +/// +/// The return values are `(consumed_u32, filled_u8)`. +/// +/// `filled_u8` is the number of filled bytes in `dest`, which may be less than +/// the length of `dest`. +/// `consumed_u32` is the number of words consumed from `src`, which is the same +/// as `filled_u8 / 4` rounded up. +/// +/// # Example +/// (from `IsaacRng`) +/// +/// ```ignore +/// fn fill_bytes(&mut self, dest: &mut [u8]) { +/// let mut read_len = 0; +/// while read_len < dest.len() { +/// if self.index >= self.rsl.len() { +/// self.isaac(); +/// } +/// +/// let (consumed_u32, filled_u8) = +/// impls::fill_via_u32_chunks(&mut self.rsl[self.index..], +/// &mut dest[read_len..]); +/// +/// self.index += consumed_u32; +/// read_len += filled_u8; +/// } +/// } +/// ``` +pub fn fill_via_u32_chunks(src: &[u32], dest: &mut [u8]) -> (usize, usize) { + fill_via_chunks!(src, dest, u32, 4) +} + +/// Implement `fill_bytes` by reading chunks from the output buffer of a block +/// based RNG. +/// +/// The return values are `(consumed_u64, filled_u8)`. +/// `filled_u8` is the number of filled bytes in `dest`, which may be less than +/// the length of `dest`. +/// `consumed_u64` is the number of words consumed from `src`, which is the same +/// as `filled_u8 / 8` rounded up. +/// +/// See `fill_via_u32_chunks` for an example. +pub fn fill_via_u64_chunks(src: &[u64], dest: &mut [u8]) -> (usize, usize) { + fill_via_chunks!(src, dest, u64, 8) +} + +/// Implement `next_u32` via `fill_bytes`, little-endian order. +pub fn next_u32_via_fill(rng: &mut R) -> u32 { + impl_uint_from_fill!(rng, u32, 4) +} + +/// Implement `next_u64` via `fill_bytes`, little-endian order. +pub fn next_u64_via_fill(rng: &mut R) -> u64 { + impl_uint_from_fill!(rng, u64, 8) +} + +// TODO: implement tests for the above diff --git a/bash-5.1/vendor/rand_core/src/le.rs b/bash-5.1/vendor/rand_core/src/le.rs new file mode 100644 index 0000000..266651f --- /dev/null +++ b/bash-5.1/vendor/rand_core/src/le.rs @@ -0,0 +1,68 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Little-Endian utilities +//! +//! Little-Endian order has been chosen for internal usage; this makes some +//! useful functions available. + +use core::ptr; + +macro_rules! read_slice { + ($src:expr, $dst:expr, $size:expr, $which:ident) => {{ + assert_eq!($src.len(), $size * $dst.len()); + + unsafe { + ptr::copy_nonoverlapping( + $src.as_ptr(), + $dst.as_mut_ptr() as *mut u8, + $src.len()); + } + for v in $dst.iter_mut() { + *v = v.$which(); + } + }}; +} + +/// Reads unsigned 32 bit integers from `src` into `dst`. +/// Borrowed from the `byteorder` crate. +#[inline] +pub fn read_u32_into(src: &[u8], dst: &mut [u32]) { + read_slice!(src, dst, 4, to_le); +} + +/// Reads unsigned 64 bit integers from `src` into `dst`. +/// Borrowed from the `byteorder` crate. +#[inline] +pub fn read_u64_into(src: &[u8], dst: &mut [u64]) { + read_slice!(src, dst, 8, to_le); +} + +#[test] +fn test_read() { + let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + + let mut buf = [0u32; 4]; + read_u32_into(&bytes, &mut buf); + assert_eq!(buf[0], 0x04030201); + assert_eq!(buf[3], 0x100F0E0D); + + let mut buf = [0u32; 3]; + read_u32_into(&bytes[1..13], &mut buf); // unaligned + assert_eq!(buf[0], 0x05040302); + assert_eq!(buf[2], 0x0D0C0B0A); + + let mut buf = [0u64; 2]; + read_u64_into(&bytes, &mut buf); + assert_eq!(buf[0], 0x0807060504030201); + assert_eq!(buf[1], 0x100F0E0D0C0B0A09); + + let mut buf = [0u64; 1]; + read_u64_into(&bytes[7..15], &mut buf); // unaligned + assert_eq!(buf[0], 0x0F0E0D0C0B0A0908); +} diff --git a/bash-5.1/vendor/rand_core/src/lib.rs b/bash-5.1/vendor/rand_core/src/lib.rs new file mode 100644 index 0000000..28e7ac1 --- /dev/null +++ b/bash-5.1/vendor/rand_core/src/lib.rs @@ -0,0 +1,477 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Random number generation traits +//! +//! This crate is mainly of interest to crates publishing implementations of +//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead +//! which re-exports the main traits and error types. +//! +//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number +//! generators and external random-number sources. +//! +//! [`SeedableRng`] is an extension trait for construction from fixed seeds and +//! other random number generators. +//! +//! [`Error`] is provided for error-handling. It is safe to use in `no_std` +//! environments. +//! +//! The [`impls`] and [`le`] sub-modules include a few small functions to assist +//! implementation of [`RngCore`]. +//! +//! [`rand`]: https://docs.rs/rand + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![cfg_attr(not(feature="std"), no_std)] +#![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))] + +#[cfg(feature="std")] extern crate core; +#[cfg(all(feature = "alloc", not(feature="std")))] extern crate alloc; +#[cfg(feature="serde1")] extern crate serde; +#[cfg(feature="serde1")] #[macro_use] extern crate serde_derive; + + +use core::default::Default; +use core::convert::AsMut; +use core::ptr::copy_nonoverlapping; + +#[cfg(all(feature="alloc", not(feature="std")))] use alloc::boxed::Box; + +pub use error::{ErrorKind, Error}; + + +mod error; +pub mod block; +pub mod impls; +pub mod le; + + +/// The core of a random number generator. +/// +/// This trait encapsulates the low-level functionality common to all +/// generators, and is the "back end", to be implemented by generators. +/// End users should normally use the `Rng` trait from the [`rand`] crate, +/// which is automatically implemented for every type implementing `RngCore`. +/// +/// Three different methods for generating random data are provided since the +/// optimal implementation of each is dependent on the type of generator. There +/// is no required relationship between the output of each; e.g. many +/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64` +/// values and drop any remaining unused bytes. +/// +/// The [`try_fill_bytes`] method is a variant of [`fill_bytes`] allowing error +/// handling; it is not deemed sufficiently useful to add equivalents for +/// [`next_u32`] or [`next_u64`] since the latter methods are almost always used +/// with algorithmic generators (PRNGs), which are normally infallible. +/// +/// Algorithmic generators implementing [`SeedableRng`] should normally have +/// *portable, reproducible* output, i.e. fix Endianness when converting values +/// to avoid platform differences, and avoid making any changes which affect +/// output (except by communicating that the release has breaking changes). +/// +/// Typically implementators will implement only one of the methods available +/// in this trait directly, then use the helper functions from the +/// [`impls`] module to implement the other methods. +/// +/// It is recommended that implementations also implement: +/// +/// - `Debug` with a custom implementation which *does not* print any internal +/// state (at least, [`CryptoRng`]s should not risk leaking state through +/// `Debug`). +/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde +/// support optional at the crate level in PRNG libs. +/// - `Clone`, if possible. +/// - *never* implement `Copy` (accidental copies may cause repeated values). +/// - *do not* implement `Default` for pseudorandom generators, but instead +/// implement [`SeedableRng`], to guide users towards proper seeding. +/// External / hardware RNGs can choose to implement `Default`. +/// - `Eq` and `PartialEq` could be implemented, but are probably not useful. +/// +/// # Example +/// +/// A simple example, obviously not generating very *random* output: +/// +/// ``` +/// #![allow(dead_code)] +/// use rand_core::{RngCore, Error, impls}; +/// +/// struct CountingRng(u64); +/// +/// impl RngCore for CountingRng { +/// fn next_u32(&mut self) -> u32 { +/// self.next_u64() as u32 +/// } +/// +/// fn next_u64(&mut self) -> u64 { +/// self.0 += 1; +/// self.0 +/// } +/// +/// fn fill_bytes(&mut self, dest: &mut [u8]) { +/// impls::fill_bytes_via_next(self, dest) +/// } +/// +/// fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { +/// Ok(self.fill_bytes(dest)) +/// } +/// } +/// ``` +/// +/// [`rand`]: https://docs.rs/rand +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +pub trait RngCore { + /// Return the next random `u32`. + /// + /// RNGs must implement at least one method from this trait directly. In + /// the case this method is not implemented directly, it can be implemented + /// using `self.next_u64() as u32` or via + /// [`fill_bytes`](impls::next_u32_via_fill). + fn next_u32(&mut self) -> u32; + + /// Return the next random `u64`. + /// + /// RNGs must implement at least one method from this trait directly. In + /// the case this method is not implemented directly, it can be implemented + /// via [`next_u32`](impls::next_u64_via_u32) or via + /// [`fill_bytes`](impls::next_u64_via_fill). + fn next_u64(&mut self) -> u64; + + /// Fill `dest` with random data. + /// + /// RNGs must implement at least one method from this trait directly. In + /// the case this method is not implemented directly, it can be implemented + /// via [`next_u*`](impls::fill_bytes_via_next) or + /// via [`try_fill_bytes`](RngCore::try_fill_bytes); if this generator can + /// fail the implementation must choose how best to handle errors here + /// (e.g. panic with a descriptive message or log a warning and retry a few + /// times). + /// + /// This method should guarantee that `dest` is entirely filled + /// with new data, and may panic if this is impossible + /// (e.g. reading past the end of a file that is being used as the + /// source of randomness). + fn fill_bytes(&mut self, dest: &mut [u8]); + + /// Fill `dest` entirely with random data. + /// + /// This is the only method which allows an RNG to report errors while + /// generating random data thus making this the primary method implemented + /// by external (true) RNGs (e.g. `OsRng`) which can fail. It may be used + /// directly to generate keys and to seed (infallible) PRNGs. + /// + /// Other than error handling, this method is identical to [`fill_bytes`]; + /// thus this may be implemented using `Ok(self.fill_bytes(dest))` or + /// `fill_bytes` may be implemented with + /// `self.try_fill_bytes(dest).unwrap()` or more specific error handling. + /// + /// [`fill_bytes`]: RngCore::fill_bytes + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>; +} + +/// A marker trait used to indicate that an [`RngCore`] or [`BlockRngCore`] +/// implementation is supposed to be cryptographically secure. +/// +/// *Cryptographically secure generators*, also known as *CSPRNGs*, should +/// satisfy an additional properties over other generators: given the first +/// *k* bits of an algorithm's output +/// sequence, it should not be possible using polynomial-time algorithms to +/// predict the next bit with probability significantly greater than 50%. +/// +/// Some generators may satisfy an additional property, however this is not +/// required by this trait: if the CSPRNG's state is revealed, it should not be +/// computationally-feasible to reconstruct output prior to this. Some other +/// generators allow backwards-computation and are consided *reversible*. +/// +/// Note that this trait is provided for guidance only and cannot guarantee +/// suitability for cryptographic applications. In general it should only be +/// implemented for well-reviewed code implementing well-regarded algorithms. +/// +/// Note also that use of a `CryptoRng` does not protect against other +/// weaknesses such as seeding from a weak entropy source or leaking state. +/// +/// [`BlockRngCore`]: block::BlockRngCore +pub trait CryptoRng {} + +/// A random number generator that can be explicitly seeded. +/// +/// This trait encapsulates the low-level functionality common to all +/// pseudo-random number generators (PRNGs, or algorithmic generators). +/// +/// The `FromEntropy` trait from the [`rand`] crate is automatically +/// implemented for every type implementing `SeedableRng`, providing +/// a convenient `from_entropy()` constructor. +/// +/// [`rand`]: https://docs.rs/rand +pub trait SeedableRng: Sized { + /// Seed type, which is restricted to types mutably-dereferencable as `u8` + /// arrays (we recommend `[u8; N]` for some `N`). + /// + /// It is recommended to seed PRNGs with a seed of at least circa 100 bits, + /// which means an array of `[u8; 12]` or greater to avoid picking RNGs with + /// partially overlapping periods. + /// + /// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`. + /// + /// + /// # Implementing `SeedableRng` for RNGs with large seeds + /// + /// Note that the required traits `core::default::Default` and + /// `core::convert::AsMut` are not implemented for large arrays + /// `[u8; N]` with `N` > 32. To be able to implement the traits required by + /// `SeedableRng` for RNGs with such large seeds, the newtype pattern can be + /// used: + /// + /// ``` + /// use rand_core::SeedableRng; + /// + /// const N: usize = 64; + /// pub struct MyRngSeed(pub [u8; N]); + /// pub struct MyRng(MyRngSeed); + /// + /// impl Default for MyRngSeed { + /// fn default() -> MyRngSeed { + /// MyRngSeed([0; N]) + /// } + /// } + /// + /// impl AsMut<[u8]> for MyRngSeed { + /// fn as_mut(&mut self) -> &mut [u8] { + /// &mut self.0 + /// } + /// } + /// + /// impl SeedableRng for MyRng { + /// type Seed = MyRngSeed; + /// + /// fn from_seed(seed: MyRngSeed) -> MyRng { + /// MyRng(seed) + /// } + /// } + /// ``` + type Seed: Sized + Default + AsMut<[u8]>; + + /// Create a new PRNG using the given seed. + /// + /// PRNG implementations are allowed to assume that bits in the seed are + /// well distributed. That means usually that the number of one and zero + /// bits are about equal, and values like 0, 1 and (size - 1) are unlikely. + /// + /// PRNG implementations are recommended to be reproducible. A PRNG seeded + /// using this function with a fixed seed should produce the same sequence + /// of output in the future and on different architectures (with for example + /// different endianness). + /// + /// It is however not required that this function yield the same state as a + /// reference implementation of the PRNG given equivalent seed; if necessary + /// another constructor replicating behaviour from a reference + /// implementation can be added. + /// + /// PRNG implementations should make sure `from_seed` never panics. In the + /// case that some special values (like an all zero seed) are not viable + /// seeds it is preferable to map these to alternative constant value(s), + /// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad + /// seed"). This is assuming only a small number of values must be rejected. + fn from_seed(seed: Self::Seed) -> Self; + + /// Create a new PRNG using a `u64` seed. + /// + /// This is a convenience-wrapper around `from_seed` to allow construction + /// of any `SeedableRng` from a simple `u64` value. It is designed such that + /// low Hamming Weight numbers like 0 and 1 can be used and should still + /// result in good, independent seeds to the PRNG which is returned. + /// + /// This **is not suitable for cryptography**, as should be clear given that + /// the input size is only 64 bits. + /// + /// Implementations for PRNGs *may* provide their own implementations of + /// this function, but the default implementation should be good enough for + /// all purposes. *Changing* the implementation of this function should be + /// considered a value-breaking change. + fn seed_from_u64(mut state: u64) -> Self { + // We use PCG32 to generate a u32 sequence, and copy to the seed + const MUL: u64 = 6364136223846793005; + const INC: u64 = 11634580027462260723; + + let mut seed = Self::Seed::default(); + for chunk in seed.as_mut().chunks_mut(4) { + // We advance the state first (to get away from the input value, + // in case it has low Hamming Weight). + state = state.wrapping_mul(MUL).wrapping_add(INC); + + // Use PCG output function with to_le to generate x: + let xorshifted = (((state >> 18) ^ state) >> 27) as u32; + let rot = (state >> 59) as u32; + let x = xorshifted.rotate_right(rot).to_le(); + + unsafe { + let p = &x as *const u32 as *const u8; + copy_nonoverlapping(p, chunk.as_mut_ptr(), chunk.len()); + } + } + + Self::from_seed(seed) + } + + /// Create a new PRNG seeded from another `Rng`. + /// + /// This is the recommended way to initialize PRNGs with fresh entropy. The + /// `FromEntropy` trait from the [`rand`] crate provides a convenient + /// `from_entropy` method based on `from_rng`. + /// + /// Usage of this method is not recommended when reproducibility is required + /// since implementing PRNGs are not required to fix Endianness and are + /// allowed to modify implementations in new releases. + /// + /// It is important to use a good source of randomness to initialize the + /// PRNG. Cryptographic PRNG may be rendered insecure when seeded from a + /// non-cryptographic PRNG or with insufficient entropy. + /// Many non-cryptographic PRNGs will show statistical bias in their first + /// results if their seed numbers are small or if there is a simple pattern + /// between them. + /// + /// Prefer to seed from a strong external entropy source like `OsRng` from + /// the [`rand_os`] crate or from a cryptographic PRNG; if creating a new + /// generator for cryptographic uses you *must* seed from a strong source. + /// + /// Seeding a small PRNG from another small PRNG is possible, but + /// something to be careful with. An extreme example of how this can go + /// wrong is seeding an Xorshift RNG from another Xorshift RNG, which + /// will effectively clone the generator. In general seeding from a + /// generator which is hard to predict is probably okay. + /// + /// PRNG implementations are allowed to assume that a good RNG is provided + /// for seeding, and that it is cryptographically secure when appropriate. + /// + /// [`rand`]: https://docs.rs/rand + /// [`rand_os`]: https://docs.rs/rand_os + fn from_rng(mut rng: R) -> Result { + let mut seed = Self::Seed::default(); + rng.try_fill_bytes(seed.as_mut())?; + Ok(Self::from_seed(seed)) + } +} + +// Implement `RngCore` for references to an `RngCore`. +// Force inlining all functions, so that it is up to the `RngCore` +// implementation and the optimizer to decide on inlining. +impl<'a, R: RngCore + ?Sized> RngCore for &'a mut R { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + (**self).next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + (**self).next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + (**self).fill_bytes(dest) + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + (**self).try_fill_bytes(dest) + } +} + +// Implement `RngCore` for boxed references to an `RngCore`. +// Force inlining all functions, so that it is up to the `RngCore` +// implementation and the optimizer to decide on inlining. +#[cfg(feature="alloc")] +impl RngCore for Box { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + (**self).next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + (**self).next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + (**self).fill_bytes(dest) + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + (**self).try_fill_bytes(dest) + } +} + +#[cfg(feature="std")] +impl std::io::Read for RngCore { + fn read(&mut self, buf: &mut [u8]) -> Result { + self.try_fill_bytes(buf)?; + Ok(buf.len()) + } +} + +// Implement `CryptoRng` for references to an `CryptoRng`. +impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R {} + +// Implement `CryptoRng` for boxed references to an `CryptoRng`. +#[cfg(feature="alloc")] +impl CryptoRng for Box {} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_seed_from_u64() { + struct SeedableNum(u64); + impl SeedableRng for SeedableNum { + type Seed = [u8; 8]; + fn from_seed(seed: Self::Seed) -> Self { + let mut x = [0u64; 1]; + le::read_u64_into(&seed, &mut x); + SeedableNum(x[0]) + } + } + + const N: usize = 8; + const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64]; + let mut results = [0u64; N]; + for (i, seed) in SEEDS.iter().enumerate() { + let SeedableNum(x) = SeedableNum::seed_from_u64(*seed); + results[i] = x; + } + + for (i1, r1) in results.iter().enumerate() { + let weight = r1.count_ones(); + // This is the binomial distribution B(64, 0.5), so chance of + // weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for + // weight > 44. + assert!(weight >= 20 && weight <= 44); + + for (i2, r2) in results.iter().enumerate() { + if i1 == i2 { continue; } + let diff_weight = (r1 ^ r2).count_ones(); + assert!(diff_weight >= 20); + } + } + + // value-breakage test: + assert_eq!(results[0], 5029875928683246316); + } +} diff --git a/bash-5.1/vendor/rand_hc/.cargo-checksum.json b/bash-5.1/vendor/rand_hc/.cargo-checksum.json new file mode 100644 index 0000000..562cce3 --- /dev/null +++ b/bash-5.1/vendor/rand_hc/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"f6dd960de06e087466066cd3e05bfd51288d144f917a62c591238697d7db1f49","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"467a2ecd73f7b32471fe00fe8042ef4dff756c05e6e4e6dd3a2e48d25867ef07","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"a771e4354f6b3ad4c92da1a5c9a239b6c291527db869632ecea4f20e24ca1135","README.md":"98a46c583c11b36bf3cc30ba646c9598a7d051b22c10e6d408aa0b1aefc6062d","src/hc128.rs":"ec8a1122eff5d1b79efa721d97d8aabaadd3f9af504336ecd928c082a9a40b45","src/lib.rs":"959f8d7280fac5683e4d2bf1713b3742a0a3685bb0b7e19d06875d254751cffb"},"package":"7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_hc/CHANGELOG.md b/bash-5.1/vendor/rand_hc/CHANGELOG.md new file mode 100644 index 0000000..d0c4a2f --- /dev/null +++ b/bash-5.1/vendor/rand_hc/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.0] - 2018-10-17 +- Pulled out of the Rand crate diff --git a/bash-5.1/vendor/rand_hc/COPYRIGHT b/bash-5.1/vendor/rand_hc/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_hc/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_hc/Cargo.toml b/bash-5.1/vendor/rand_hc/Cargo.toml new file mode 100644 index 0000000..e080274 --- /dev/null +++ b/bash-5.1/vendor/rand_hc/Cargo.toml @@ -0,0 +1,32 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_hc" +version = "0.1.0" +authors = ["The Rand Project Developers"] +description = "HC128 random number generator\n" +homepage = "https://crates.io/crates/rand_hc" +documentation = "https://docs.rs/rand_hc" +readme = "README.md" +keywords = ["random", "rng", "hc128"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.rand_core] +version = ">=0.2, <0.4" +default-features = false +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_hc/LICENSE-APACHE b/bash-5.1/vendor/rand_hc/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_hc/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_hc/LICENSE-MIT b/bash-5.1/vendor/rand_hc/LICENSE-MIT new file mode 100644 index 0000000..cf65607 --- /dev/null +++ b/bash-5.1/vendor/rand_hc/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright 2018 Developers of the Rand project + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_hc/README.md b/bash-5.1/vendor/rand_hc/README.md new file mode 100644 index 0000000..9c1f5e1 --- /dev/null +++ b/bash-5.1/vendor/rand_hc/README.md @@ -0,0 +1,44 @@ +# rand_hc + +[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_hc.svg)](https://crates.io/crates/rand_hc) +[![Documentation](https://docs.rs/rand_hc/badge.svg)](https://docs.rs/rand_hc) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-yellow.svg)](https://github.com/rust-random/rand#rust-version-requirements) +[![License](https://img.shields.io/crates/l/rand_hc.svg)](https://github.com/rust-random/rand/tree/master/rand_hc#license) + +A cryptographically secure random number generator that uses the HC-128 +algorithm. + +HC-128 is a stream cipher designed by Hongjun Wu[^1], that we use as an +RNG. It is selected as one of the "stream ciphers suitable for widespread +adoption" by eSTREAM[^2]. + +Documentation: +[master branch](https://rust-random.github.io/rand/rand_hc/index.html), +[by release](https://docs.rs/rand_hc) + +[Changelog](CHANGELOG.md) + +[rand]: https://crates.io/crates/rand +[^1]: Hongjun Wu (2008). ["The Stream Cipher HC-128"]( + http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf). + *The eSTREAM Finalists*, LNCS 4986, pp. 39–47, Springer-Verlag. + +[^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( + http://www.ecrypt.eu.org/stream/) + + +## Crate Features + +`rand_hc` is `no_std` compatible. It does not require any functionality +outside of the `core` lib, thus there are no features to configure. + + +# License + +`rand_hc` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_hc/src/hc128.rs b/bash-5.1/vendor/rand_hc/src/hc128.rs new file mode 100644 index 0000000..d1dadcc --- /dev/null +++ b/bash-5.1/vendor/rand_hc/src/hc128.rs @@ -0,0 +1,462 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The HC-128 random number generator. + +use core::fmt; +use rand_core::{CryptoRng, RngCore, SeedableRng, Error, le}; +use rand_core::block::{BlockRngCore, BlockRng}; + +const SEED_WORDS: usize = 8; // 128 bit key followed by 128 bit iv + +/// A cryptographically secure random number generator that uses the HC-128 +/// algorithm. +/// +/// HC-128 is a stream cipher designed by Hongjun Wu[^1], that we use as an +/// RNG. It is selected as one of the "stream ciphers suitable for widespread +/// adoption" by eSTREAM[^2]. +/// +/// HC-128 is an array based RNG. In this it is similar to RC-4 and ISAAC before +/// it, but those have never been proven cryptographically secure (or have even +/// been significantly compromised, as in the case of RC-4[^5]). +/// +/// Because HC-128 works with simple indexing into a large array and with a few +/// operations that parallelize well, it has very good performance. The size of +/// the array it needs, 4kb, can however be a disadvantage. +/// +/// This implementation is not based on the version of HC-128 submitted to the +/// eSTREAM contest, but on a later version by the author with a few small +/// improvements from December 15, 2009[^3]. +/// +/// HC-128 has no known weaknesses that are easier to exploit than doing a +/// brute-force search of 2128. A very comprehensive analysis of the +/// current state of known attacks / weaknesses of HC-128 is given in *Some +/// Results On Analysis And Implementation Of HC-128 Stream Cipher*[^4]. +/// +/// The average cycle length is expected to be +/// 21024*32+10-1 = 232777. +/// We support seeding with a 256-bit array, which matches the 128-bit key +/// concatenated with a 128-bit IV from the stream cipher. +/// +/// This implementation uses an output buffer of sixteen `u32` words, and uses +/// [`BlockRng`] to implement the [`RngCore`] methods. +/// +/// ## References +/// [^1]: Hongjun Wu (2008). ["The Stream Cipher HC-128"]( +/// http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf). +/// *The eSTREAM Finalists*, LNCS 4986, pp. 39–47, Springer-Verlag. +/// +/// [^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( +/// http://www.ecrypt.eu.org/stream/) +/// +/// [^3]: Hongjun Wu, [Stream Ciphers HC-128 and HC-256]( +/// https://www.ntu.edu.sg/home/wuhj/research/hc/index.html) +/// +/// [^4]: Shashwat Raizada (January 2015),["Some Results On Analysis And +/// Implementation Of HC-128 Stream Cipher"]( +/// http://library.isical.ac.in:8080/jspui/bitstream/123456789/6636/1/TH431.pdf). +/// +/// [^5]: Internet Engineering Task Force (February 2015), +/// ["Prohibiting RC4 Cipher Suites"](https://tools.ietf.org/html/rfc7465). +/// +/// [`BlockRng`]: ../rand_core/block/struct.BlockRng.html +/// [`RngCore`]: ../rand_core/trait.RngCore.html +#[derive(Clone, Debug)] +pub struct Hc128Rng(BlockRng); + +impl RngCore for Hc128Rng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for Hc128Rng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + Hc128Rng(BlockRng::::from_seed(seed)) + } + + fn from_rng(rng: R) -> Result { + BlockRng::::from_rng(rng).map(Hc128Rng) + } +} + +impl CryptoRng for Hc128Rng {} + +/// The core of `Hc128Rng`, used with `BlockRng`. +#[derive(Clone)] +pub struct Hc128Core { + t: [u32; 1024], + counter1024: usize, +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for Hc128Core { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Hc128Core {{}}") + } +} + +impl BlockRngCore for Hc128Core { + type Item = u32; + type Results = [u32; 16]; + + fn generate(&mut self, results: &mut Self::Results) { + assert!(self.counter1024 % 16 == 0); + + let cc = self.counter1024 % 512; + let dd = (cc + 16) % 512; + let ee = cc.wrapping_sub(16) % 512; + + if self.counter1024 & 512 == 0 { + // P block + results[0] = self.step_p(cc+0, cc+1, ee+13, ee+6, ee+4); + results[1] = self.step_p(cc+1, cc+2, ee+14, ee+7, ee+5); + results[2] = self.step_p(cc+2, cc+3, ee+15, ee+8, ee+6); + results[3] = self.step_p(cc+3, cc+4, cc+0, ee+9, ee+7); + results[4] = self.step_p(cc+4, cc+5, cc+1, ee+10, ee+8); + results[5] = self.step_p(cc+5, cc+6, cc+2, ee+11, ee+9); + results[6] = self.step_p(cc+6, cc+7, cc+3, ee+12, ee+10); + results[7] = self.step_p(cc+7, cc+8, cc+4, ee+13, ee+11); + results[8] = self.step_p(cc+8, cc+9, cc+5, ee+14, ee+12); + results[9] = self.step_p(cc+9, cc+10, cc+6, ee+15, ee+13); + results[10] = self.step_p(cc+10, cc+11, cc+7, cc+0, ee+14); + results[11] = self.step_p(cc+11, cc+12, cc+8, cc+1, ee+15); + results[12] = self.step_p(cc+12, cc+13, cc+9, cc+2, cc+0); + results[13] = self.step_p(cc+13, cc+14, cc+10, cc+3, cc+1); + results[14] = self.step_p(cc+14, cc+15, cc+11, cc+4, cc+2); + results[15] = self.step_p(cc+15, dd+0, cc+12, cc+5, cc+3); + } else { + // Q block + results[0] = self.step_q(cc+0, cc+1, ee+13, ee+6, ee+4); + results[1] = self.step_q(cc+1, cc+2, ee+14, ee+7, ee+5); + results[2] = self.step_q(cc+2, cc+3, ee+15, ee+8, ee+6); + results[3] = self.step_q(cc+3, cc+4, cc+0, ee+9, ee+7); + results[4] = self.step_q(cc+4, cc+5, cc+1, ee+10, ee+8); + results[5] = self.step_q(cc+5, cc+6, cc+2, ee+11, ee+9); + results[6] = self.step_q(cc+6, cc+7, cc+3, ee+12, ee+10); + results[7] = self.step_q(cc+7, cc+8, cc+4, ee+13, ee+11); + results[8] = self.step_q(cc+8, cc+9, cc+5, ee+14, ee+12); + results[9] = self.step_q(cc+9, cc+10, cc+6, ee+15, ee+13); + results[10] = self.step_q(cc+10, cc+11, cc+7, cc+0, ee+14); + results[11] = self.step_q(cc+11, cc+12, cc+8, cc+1, ee+15); + results[12] = self.step_q(cc+12, cc+13, cc+9, cc+2, cc+0); + results[13] = self.step_q(cc+13, cc+14, cc+10, cc+3, cc+1); + results[14] = self.step_q(cc+14, cc+15, cc+11, cc+4, cc+2); + results[15] = self.step_q(cc+15, dd+0, cc+12, cc+5, cc+3); + } + self.counter1024 = self.counter1024.wrapping_add(16); + } +} + +impl Hc128Core { + // One step of HC-128, update P and generate 32 bits keystream + #[inline(always)] + fn step_p(&mut self, i: usize, i511: usize, i3: usize, i10: usize, i12: usize) + -> u32 + { + let (p, q) = self.t.split_at_mut(512); + // FIXME: it would be great if we the bounds checks here could be + // optimized out, and we would not need unsafe. + // This improves performance by about 7%. + unsafe { + let temp0 = p.get_unchecked(i511).rotate_right(23); + let temp1 = p.get_unchecked(i3).rotate_right(10); + let temp2 = p.get_unchecked(i10).rotate_right(8); + *p.get_unchecked_mut(i) = p.get_unchecked(i) + .wrapping_add(temp2) + .wrapping_add(temp0 ^ temp1); + let temp3 = { + // The h1 function in HC-128 + let a = *p.get_unchecked(i12) as u8; + let c = (p.get_unchecked(i12) >> 16) as u8; + q[a as usize].wrapping_add(q[256 + c as usize]) + }; + temp3 ^ p.get_unchecked(i) + } + } + + // One step of HC-128, update Q and generate 32 bits keystream + // Similar to `step_p`, but `p` and `q` are swapped, and the rotates are to + // the left instead of to the right. + #[inline(always)] + fn step_q(&mut self, i: usize, i511: usize, i3: usize, i10: usize, i12: usize) + -> u32 + { + let (p, q) = self.t.split_at_mut(512); + unsafe { + let temp0 = q.get_unchecked(i511).rotate_left(23); + let temp1 = q.get_unchecked(i3).rotate_left(10); + let temp2 = q.get_unchecked(i10).rotate_left(8); + *q.get_unchecked_mut(i) = q.get_unchecked(i) + .wrapping_add(temp2) + .wrapping_add(temp0 ^ temp1); + let temp3 = { + // The h2 function in HC-128 + let a = *q.get_unchecked(i12) as u8; + let c = (q.get_unchecked(i12) >> 16) as u8; + p[a as usize].wrapping_add(p[256 + c as usize]) + }; + temp3 ^ q.get_unchecked(i) + } + } + + fn sixteen_steps(&mut self) { + assert!(self.counter1024 % 16 == 0); + + let cc = self.counter1024 % 512; + let dd = (cc + 16) % 512; + let ee = cc.wrapping_sub(16) % 512; + + if self.counter1024 < 512 { + // P block + self.t[cc+0] = self.step_p(cc+0, cc+1, ee+13, ee+6, ee+4); + self.t[cc+1] = self.step_p(cc+1, cc+2, ee+14, ee+7, ee+5); + self.t[cc+2] = self.step_p(cc+2, cc+3, ee+15, ee+8, ee+6); + self.t[cc+3] = self.step_p(cc+3, cc+4, cc+0, ee+9, ee+7); + self.t[cc+4] = self.step_p(cc+4, cc+5, cc+1, ee+10, ee+8); + self.t[cc+5] = self.step_p(cc+5, cc+6, cc+2, ee+11, ee+9); + self.t[cc+6] = self.step_p(cc+6, cc+7, cc+3, ee+12, ee+10); + self.t[cc+7] = self.step_p(cc+7, cc+8, cc+4, ee+13, ee+11); + self.t[cc+8] = self.step_p(cc+8, cc+9, cc+5, ee+14, ee+12); + self.t[cc+9] = self.step_p(cc+9, cc+10, cc+6, ee+15, ee+13); + self.t[cc+10] = self.step_p(cc+10, cc+11, cc+7, cc+0, ee+14); + self.t[cc+11] = self.step_p(cc+11, cc+12, cc+8, cc+1, ee+15); + self.t[cc+12] = self.step_p(cc+12, cc+13, cc+9, cc+2, cc+0); + self.t[cc+13] = self.step_p(cc+13, cc+14, cc+10, cc+3, cc+1); + self.t[cc+14] = self.step_p(cc+14, cc+15, cc+11, cc+4, cc+2); + self.t[cc+15] = self.step_p(cc+15, dd+0, cc+12, cc+5, cc+3); + } else { + // Q block + self.t[cc+512+0] = self.step_q(cc+0, cc+1, ee+13, ee+6, ee+4); + self.t[cc+512+1] = self.step_q(cc+1, cc+2, ee+14, ee+7, ee+5); + self.t[cc+512+2] = self.step_q(cc+2, cc+3, ee+15, ee+8, ee+6); + self.t[cc+512+3] = self.step_q(cc+3, cc+4, cc+0, ee+9, ee+7); + self.t[cc+512+4] = self.step_q(cc+4, cc+5, cc+1, ee+10, ee+8); + self.t[cc+512+5] = self.step_q(cc+5, cc+6, cc+2, ee+11, ee+9); + self.t[cc+512+6] = self.step_q(cc+6, cc+7, cc+3, ee+12, ee+10); + self.t[cc+512+7] = self.step_q(cc+7, cc+8, cc+4, ee+13, ee+11); + self.t[cc+512+8] = self.step_q(cc+8, cc+9, cc+5, ee+14, ee+12); + self.t[cc+512+9] = self.step_q(cc+9, cc+10, cc+6, ee+15, ee+13); + self.t[cc+512+10] = self.step_q(cc+10, cc+11, cc+7, cc+0, ee+14); + self.t[cc+512+11] = self.step_q(cc+11, cc+12, cc+8, cc+1, ee+15); + self.t[cc+512+12] = self.step_q(cc+12, cc+13, cc+9, cc+2, cc+0); + self.t[cc+512+13] = self.step_q(cc+13, cc+14, cc+10, cc+3, cc+1); + self.t[cc+512+14] = self.step_q(cc+14, cc+15, cc+11, cc+4, cc+2); + self.t[cc+512+15] = self.step_q(cc+15, dd+0, cc+12, cc+5, cc+3); + } + self.counter1024 += 16; + } + + // Initialize an HC-128 random number generator. The seed has to be + // 256 bits in length (`[u32; 8]`), matching the 128 bit `key` followed by + // 128 bit `iv` when HC-128 where to be used as a stream cipher. + fn init(seed: [u32; SEED_WORDS]) -> Self { + #[inline] + fn f1(x: u32) -> u32 { + x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3) + } + + #[inline] + fn f2(x: u32) -> u32 { + x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) + } + + let mut t = [0u32; 1024]; + + // Expand the key and iv into P and Q + let (key, iv) = seed.split_at(4); + t[..4].copy_from_slice(key); + t[4..8].copy_from_slice(key); + t[8..12].copy_from_slice(iv); + t[12..16].copy_from_slice(iv); + + // Generate the 256 intermediate values W[16] ... W[256+16-1], and + // copy the last 16 generated values to the start op P. + for i in 16..256+16 { + t[i] = f2(t[i-2]).wrapping_add(t[i-7]).wrapping_add(f1(t[i-15])) + .wrapping_add(t[i-16]).wrapping_add(i as u32); + } + { + let (p1, p2) = t.split_at_mut(256); + p1[0..16].copy_from_slice(&p2[0..16]); + } + + // Generate both the P and Q tables + for i in 16..1024 { + t[i] = f2(t[i-2]).wrapping_add(t[i-7]).wrapping_add(f1(t[i-15])) + .wrapping_add(t[i-16]).wrapping_add(256 + i as u32); + } + + let mut core = Self { t, counter1024: 0 }; + + // run the cipher 1024 steps + for _ in 0..64 { core.sixteen_steps() }; + core.counter1024 = 0; + core + } +} + +impl SeedableRng for Hc128Core { + type Seed = [u8; SEED_WORDS*4]; + + /// Create an HC-128 random number generator with a seed. The seed has to be + /// 256 bits in length, matching the 128 bit `key` followed by 128 bit `iv` + /// when HC-128 where to be used as a stream cipher. + fn from_seed(seed: Self::Seed) -> Self { + let mut seed_u32 = [0u32; SEED_WORDS]; + le::read_u32_into(&seed, &mut seed_u32); + Self::init(seed_u32) + } +} + +impl CryptoRng for Hc128Core {} + +#[cfg(test)] +mod test { + use ::rand_core::{RngCore, SeedableRng}; + use super::Hc128Rng; + + #[test] + // Test vector 1 from the paper "The Stream Cipher HC-128" + fn test_hc128_true_values_a() { + let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv + let mut rng = Hc128Rng::from_seed(seed); + + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0x73150082, 0x3bfd03a0, 0xfb2fd77f, 0xaa63af0e, + 0xde122fc6, 0xa7dc29b6, 0x62a68527, 0x8b75ec68, + 0x9036db1e, 0x81896005, 0x00ade078, 0x491fbf9a, + 0x1cdc3013, 0x6c3d6e24, 0x90f664b2, 0x9cd57102]; + assert_eq!(results, expected); + } + + #[test] + // Test vector 2 from the paper "The Stream Cipher HC-128" + fn test_hc128_true_values_b() { + let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key + 1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv + let mut rng = Hc128Rng::from_seed(seed); + + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0xc01893d5, 0xb7dbe958, 0x8f65ec98, 0x64176604, + 0x36fc6724, 0xc82c6eec, 0x1b1c38a7, 0xc9b42a95, + 0x323ef123, 0x0a6a908b, 0xce757b68, 0x9f14f7bb, + 0xe4cde011, 0xaeb5173f, 0x89608c94, 0xb5cf46ca]; + assert_eq!(results, expected); + } + + #[test] + // Test vector 3 from the paper "The Stream Cipher HC-128" + fn test_hc128_true_values_c() { + let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv + let mut rng = Hc128Rng::from_seed(seed); + + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected = [0x518251a4, 0x04b4930a, 0xb02af931, 0x0639f032, + 0xbcb4a47a, 0x5722480b, 0x2bf99f72, 0xcdc0e566, + 0x310f0c56, 0xd3cc83e8, 0x663db8ef, 0x62dfe07f, + 0x593e1790, 0xc5ceaa9c, 0xab03806f, 0xc9a6e5a0]; + assert_eq!(results, expected); + } + + #[test] + fn test_hc128_true_values_u64() { + let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv + let mut rng = Hc128Rng::from_seed(seed); + + let mut results = [0u64; 8]; + for i in results.iter_mut() { *i = rng.next_u64(); } + let expected = [0x3bfd03a073150082, 0xaa63af0efb2fd77f, + 0xa7dc29b6de122fc6, 0x8b75ec6862a68527, + 0x818960059036db1e, 0x491fbf9a00ade078, + 0x6c3d6e241cdc3013, 0x9cd5710290f664b2]; + assert_eq!(results, expected); + + // The RNG operates in a P block of 512 results and next a Q block. + // After skipping 2*800 u32 results we end up somewhere in the Q block + // of the second round + for _ in 0..800 { rng.next_u64(); } + + for i in results.iter_mut() { *i = rng.next_u64(); } + let expected = [0xd8c4d6ca84d0fc10, 0xf16a5d91dc66e8e7, + 0xd800de5bc37a8653, 0x7bae1f88c0dfbb4c, + 0x3bfe1f374e6d4d14, 0x424b55676be3fa06, + 0xe3a1e8758cbff579, 0x417f7198c5652bcd]; + assert_eq!(results, expected); + } + + #[test] + fn test_hc128_true_values_bytes() { + let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv + let mut rng = Hc128Rng::from_seed(seed); + let expected = [0x31, 0xf9, 0x2a, 0xb0, 0x32, 0xf0, 0x39, 0x06, + 0x7a, 0xa4, 0xb4, 0xbc, 0x0b, 0x48, 0x22, 0x57, + 0x72, 0x9f, 0xf9, 0x2b, 0x66, 0xe5, 0xc0, 0xcd, + 0x56, 0x0c, 0x0f, 0x31, 0xe8, 0x83, 0xcc, 0xd3, + 0xef, 0xb8, 0x3d, 0x66, 0x7f, 0xe0, 0xdf, 0x62, + 0x90, 0x17, 0x3e, 0x59, 0x9c, 0xaa, 0xce, 0xc5, + 0x6f, 0x80, 0x03, 0xab, 0xa0, 0xe5, 0xa6, 0xc9, + 0x60, 0x95, 0x84, 0x7a, 0xa5, 0x68, 0x5a, 0x84, + 0xea, 0xd5, 0xf3, 0xea, 0x73, 0xa9, 0xad, 0x01, + 0x79, 0x7d, 0xbe, 0x9f, 0xea, 0xe3, 0xf9, 0x74, + 0x0e, 0xda, 0x2f, 0xa0, 0xe4, 0x7b, 0x4b, 0x1b, + 0xdd, 0x17, 0x69, 0x4a, 0xfe, 0x9f, 0x56, 0x95, + 0xad, 0x83, 0x6b, 0x9d, 0x60, 0xa1, 0x99, 0x96, + 0x90, 0x00, 0x66, 0x7f, 0xfa, 0x7e, 0x65, 0xe9, + 0xac, 0x8b, 0x92, 0x34, 0x77, 0xb4, 0x23, 0xd0, + 0xb9, 0xab, 0xb1, 0x47, 0x7d, 0x4a, 0x13, 0x0a]; + + // Pick a somewhat large buffer so we can test filling with the + // remainder from `state.results`, directly filling the buffer, and + // filling the remainder of the buffer. + let mut buffer = [0u8; 16*4*2]; + // Consume a value so that we have a remainder. + assert!(rng.next_u64() == 0x04b4930a518251a4); + rng.fill_bytes(&mut buffer); + + // [u8; 128] doesn't implement PartialEq + assert_eq!(buffer.len(), expected.len()); + for (b, e) in buffer.iter().zip(expected.iter()) { + assert_eq!(b, e); + } + } + + #[test] + fn test_hc128_clone() { + let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv + let mut rng1 = Hc128Rng::from_seed(seed); + let mut rng2 = rng1.clone(); + for _ in 0..16 { + assert_eq!(rng1.next_u32(), rng2.next_u32()); + } + } +} diff --git a/bash-5.1/vendor/rand_hc/src/lib.rs b/bash-5.1/vendor/rand_hc/src/lib.rs new file mode 100644 index 0000000..15ca34e --- /dev/null +++ b/bash-5.1/vendor/rand_hc/src/lib.rs @@ -0,0 +1,25 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The HC128 random number generator. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://docs.rs/rand_hc/0.1.0")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![no_std] + +extern crate rand_core; + +mod hc128; + +pub use hc128::{Hc128Rng, Hc128Core}; diff --git a/bash-5.1/vendor/rand_isaac/.cargo-checksum.json b/bash-5.1/vendor/rand_isaac/.cargo-checksum.json new file mode 100644 index 0000000..c552718 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"1f98689d52278352079e5235ffe00537bd3b64c1807a87d5707e3e74c7fce1d8","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"c3fb66104a60aa0dd91b83645be897023e7eb001aa6be108a1948999e86d2512","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"9a1c416b5930337e94fe559673a32a136d3ddd513f19dbd1b37039f8fc3501a1","src/isaac.rs":"40b00c02dc1ce29786c2e5e4c4d642588709397d6bf276a1610743b9b76ab9c6","src/isaac64.rs":"61a11f4a34dc2f009771d41c8d200c1c4815cdc23dfbe96aec03219cfeee4daa","src/isaac_array.rs":"89d20f07eb4dacd42f4cdc25b59796d51bca708f218e6e6dd4a445113b5123d6","src/lib.rs":"840a9c5a5ef2150cc4fb4a3edf34bda7e48bfaa49a3ee7ef8b182743aeaf73dd"},"package":"ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_isaac/CHANGELOG.md b/bash-5.1/vendor/rand_isaac/CHANGELOG.md new file mode 100644 index 0000000..fb1ab3f --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.1] - 2018-11-26 +- Fix `rand_core` version requirement +- Fix doc links + +## [0.1.0] - 2018-10-17 +- Pulled out of the Rand crate diff --git a/bash-5.1/vendor/rand_isaac/COPYRIGHT b/bash-5.1/vendor/rand_isaac/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_isaac/Cargo.toml b/bash-5.1/vendor/rand_isaac/Cargo.toml new file mode 100644 index 0000000..79a541d --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/Cargo.toml @@ -0,0 +1,45 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_isaac" +version = "0.1.1" +authors = ["The Rand Project Developers", "The Rust Project Developers"] +description = "ISAAC random number generator\n" +homepage = "https://crates.io/crates/rand_isaac" +documentation = "https://rust-random.github.io/rand/rand_isaac" +readme = "README.md" +keywords = ["random", "rng", "isaac"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.rand_core] +version = "0.3" +default-features = false + +[dependencies.serde] +version = "1" +optional = true + +[dependencies.serde_derive] +version = "^1.0.38" +optional = true +[dev-dependencies.bincode] +version = "1" + +[features] +serde1 = ["serde", "serde_derive", "rand_core/serde1"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_isaac/LICENSE-APACHE b/bash-5.1/vendor/rand_isaac/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_isaac/LICENSE-MIT b/bash-5.1/vendor/rand_isaac/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_isaac/README.md b/bash-5.1/vendor/rand_isaac/README.md new file mode 100644 index 0000000..02d1230 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/README.md @@ -0,0 +1,47 @@ +# rand_isaac + +[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_isaac.svg)](https://crates.io/crates/rand_isaac) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_isaac) +[![API](https://docs.rs/rand_isaac/badge.svg)](https://docs.rs/rand_isaac) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Implements the ISAAC and ISAAC-64 random number generators. + +ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are +the principal bitwise operations employed. It is the most advanced of a +series of array based random number generator designed by Robert Jenkins +in 1996[^1][^2]. + +ISAAC is notably fast and produces excellent quality random numbers for +non-cryptographic applications. + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_isaac) +- [API documentation (docs.rs)](https://docs.rs/rand_isaac) +- [Changelog](CHANGELOG.md) + +[rand]: https://crates.io/crates/rand +[^1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number generator*](http://burtleburtle.net/bob/rand/isaacafa.html) +[^2]: Bob Jenkins, [*ISAAC and RC4*](http://burtleburtle.net/bob/rand/isaac.html) + + +## Crate Features + +`rand_isaac` is `no_std` compatible. It does not require any functionality +outside of the `core` lib, thus there are no features to configure. + +The `serde1` feature includes implementations of `Serialize` and `Deserialize` +for the included RNGs. + + +# License + +`rand_isaac` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_isaac/src/isaac.rs b/bash-5.1/vendor/rand_isaac/src/isaac.rs new file mode 100644 index 0000000..2bfdd94 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/src/isaac.rs @@ -0,0 +1,484 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The ISAAC random number generator. + +use core::{fmt, slice}; +use core::num::Wrapping as w; +use rand_core::{RngCore, SeedableRng, Error, le}; +use rand_core::block::{BlockRngCore, BlockRng}; +use isaac_array::IsaacArray; + +#[allow(non_camel_case_types)] +type w32 = w; + +const RAND_SIZE_LEN: usize = 8; +const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; + +/// A random number generator that uses the ISAAC algorithm. +/// +/// ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are +/// the principal bitwise operations employed. It is the most advanced of a +/// series of array based random number generator designed by Robert Jenkins +/// in 1996[^1][^2]. +/// +/// ISAAC is notably fast and produces excellent quality random numbers for +/// non-cryptographic applications. +/// +/// In spite of being designed with cryptographic security in mind, ISAAC hasn't +/// been stringently cryptanalyzed and thus cryptographers do not not +/// consensually trust it to be secure. When looking for a secure RNG, prefer +/// [`Hc128Rng`] instead, which, like ISAAC, is an array-based RNG and one of +/// the stream-ciphers selected the by eSTREAM contest. +/// +/// In 2006 an improvement to ISAAC was suggested by Jean-Philippe Aumasson, +/// named ISAAC+[^3]. But because the specification is not complete, because +/// there is no good implementation, and because the suggested bias may not +/// exist, it is not implemented here. +/// +/// ## Overview of the ISAAC algorithm: +/// (in pseudo-code) +/// +/// ```text +/// Input: a, b, c, s[256] // state +/// Output: r[256] // results +/// +/// mix(a,i) = a ^ a << 13 if i = 0 mod 4 +/// a ^ a >> 6 if i = 1 mod 4 +/// a ^ a << 2 if i = 2 mod 4 +/// a ^ a >> 16 if i = 3 mod 4 +/// +/// c = c + 1 +/// b = b + c +/// +/// for i in 0..256 { +/// x = s_[i] +/// a = f(a,i) + s[i+128 mod 256] +/// y = a + b + s[x>>2 mod 256] +/// s[i] = y +/// b = x + s[y>>10 mod 256] +/// r[i] = b +/// } +/// ``` +/// +/// Numbers are generated in blocks of 256. This means the function above only +/// runs once every 256 times you ask for a next random number. In all other +/// circumstances the last element of the results array is returned. +/// +/// ISAAC therefore needs a lot of memory, relative to other non-crypto RNGs. +/// 2 * 256 * 4 = 2 kb to hold the state and results. +/// +/// This implementation uses [`BlockRng`] to implement the [`RngCore`] methods. +/// +/// ## References +/// [^1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number generator*]( +/// http://burtleburtle.net/bob/rand/isaacafa.html) +/// +/// [^2]: Bob Jenkins, [*ISAAC and RC4*]( +/// http://burtleburtle.net/bob/rand/isaac.html) +/// +/// [^3]: Jean-Philippe Aumasson, [*On the pseudo-random generator ISAAC*]( +/// https://eprint.iacr.org/2006/438) +/// +/// [`Hc128Rng`]: ../../rand_hc/struct.Hc128Rng.html +/// [`BlockRng`]: ../../rand_core/block/struct.BlockRng.html +/// [`RngCore`]: ../../rand_core/trait.RngCore.html +#[derive(Clone, Debug)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct IsaacRng(BlockRng); + +impl RngCore for IsaacRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for IsaacRng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + IsaacRng(BlockRng::::from_seed(seed)) + } + + /// Create an ISAAC random number generator using an `u64` as seed. + /// If `seed == 0` this will produce the same stream of random numbers as + /// the reference implementation when used unseeded. + fn seed_from_u64(seed: u64) -> Self { + IsaacRng(BlockRng::::seed_from_u64(seed)) + } + + fn from_rng(rng: S) -> Result { + BlockRng::::from_rng(rng).map(|rng| IsaacRng(rng)) + } +} + +impl IsaacRng { + /// Create an ISAAC random number generator using an `u64` as seed. + /// If `seed == 0` this will produce the same stream of random numbers as + /// the reference implementation when used unseeded. + #[deprecated(since="0.6.0", note="use SeedableRng::seed_from_u64 instead")] + pub fn new_from_u64(seed: u64) -> Self { + Self::seed_from_u64(seed) + } +} + +/// The core of `IsaacRng`, used with `BlockRng`. +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct IsaacCore { + #[cfg_attr(feature="serde1",serde(with="super::isaac_array::isaac_array_serde"))] + mem: [w32; RAND_SIZE], + a: w32, + b: w32, + c: w32, +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for IsaacCore { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "IsaacCore {{}}") + } +} + +impl BlockRngCore for IsaacCore { + type Item = u32; + type Results = IsaacArray; + + /// Refills the output buffer, `results`. See also the pseudocode desciption + /// of the algorithm in the [`IsaacRng`] documentation. + /// + /// Optimisations used (similar to the reference implementation): + /// + /// - The loop is unrolled 4 times, once for every constant of mix(). + /// - The contents of the main loop are moved to a function `rngstep`, to + /// reduce code duplication. + /// - We use local variables for a and b, which helps with optimisations. + /// - We split the main loop in two, one that operates over 0..128 and one + /// over 128..256. This way we can optimise out the addition and modulus + /// from `s[i+128 mod 256]`. + /// - We maintain one index `i` and add `m` or `m2` as base (m2 for the + /// `s[i+128 mod 256]`), relying on the optimizer to turn it into pointer + /// arithmetic. + /// - We fill `results` backwards. The reference implementation reads values + /// from `results` in reverse. We read them in the normal direction, to + /// make `fill_bytes` a memcopy. To maintain compatibility we fill in + /// reverse. + /// + /// [`IsaacRng`]: struct.IsaacRng.html + fn generate(&mut self, results: &mut IsaacArray) { + self.c += w(1); + // abbreviations + let mut a = self.a; + let mut b = self.b + self.c; + const MIDPOINT: usize = RAND_SIZE / 2; + + #[inline] + fn ind(mem:&[w32; RAND_SIZE], v: w32, amount: usize) -> w32 { + let index = (v >> amount).0 as usize % RAND_SIZE; + mem[index] + } + + #[inline] + fn rngstep(mem: &mut [w32; RAND_SIZE], + results: &mut [u32; RAND_SIZE], + mix: w32, + a: &mut w32, + b: &mut w32, + base: usize, + m: usize, + m2: usize) { + let x = mem[base + m]; + *a = mix + mem[base + m2]; + let y = *a + *b + ind(&mem, x, 2); + mem[base + m] = y; + *b = x + ind(&mem, y, 2 + RAND_SIZE_LEN); + results[RAND_SIZE - 1 - base - m] = (*b).0; + } + + let mut m = 0; + let mut m2 = MIDPOINT; + for i in (0..MIDPOINT/4).map(|i| i * 4) { + rngstep(&mut self.mem, results, a ^ (a << 13), &mut a, &mut b, i + 0, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 6 ), &mut a, &mut b, i + 1, m, m2); + rngstep(&mut self.mem, results, a ^ (a << 2 ), &mut a, &mut b, i + 2, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 16), &mut a, &mut b, i + 3, m, m2); + } + + m = MIDPOINT; + m2 = 0; + for i in (0..MIDPOINT/4).map(|i| i * 4) { + rngstep(&mut self.mem, results, a ^ (a << 13), &mut a, &mut b, i + 0, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 6 ), &mut a, &mut b, i + 1, m, m2); + rngstep(&mut self.mem, results, a ^ (a << 2 ), &mut a, &mut b, i + 2, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 16), &mut a, &mut b, i + 3, m, m2); + } + + self.a = a; + self.b = b; + } +} + +impl IsaacCore { + /// Create a new ISAAC random number generator. + /// + /// The author Bob Jenkins describes how to best initialize ISAAC here: + /// + /// The answer is included here just in case: + /// + /// "No, you don't need a full 8192 bits of seed data. Normal key sizes will + /// do fine, and they should have their expected strength (eg a 40-bit key + /// will take as much time to brute force as 40-bit keys usually will). You + /// could fill the remainder with 0, but set the last array element to the + /// length of the key provided (to distinguish keys that differ only by + /// different amounts of 0 padding). You do still need to call `randinit()` + /// to make sure the initial state isn't uniform-looking." + /// "After publishing ISAAC, I wanted to limit the key to half the size of + /// `r[]`, and repeat it twice. That would have made it hard to provide a + /// key that sets the whole internal state to anything convenient. But I'd + /// already published it." + /// + /// And his answer to the question "For my code, would repeating the key + /// over and over to fill 256 integers be a better solution than + /// zero-filling, or would they essentially be the same?": + /// "If the seed is under 32 bytes, they're essentially the same, otherwise + /// repeating the seed would be stronger. randinit() takes a chunk of 32 + /// bytes, mixes it, and combines that with the next 32 bytes, et cetera. + /// Then loops over all the elements the same way a second time." + #[inline] + fn init(mut mem: [w32; RAND_SIZE], rounds: u32) -> Self { + fn mix(a: &mut w32, b: &mut w32, c: &mut w32, d: &mut w32, + e: &mut w32, f: &mut w32, g: &mut w32, h: &mut w32) { + *a ^= *b << 11; *d += *a; *b += *c; + *b ^= *c >> 2; *e += *b; *c += *d; + *c ^= *d << 8; *f += *c; *d += *e; + *d ^= *e >> 16; *g += *d; *e += *f; + *e ^= *f << 10; *h += *e; *f += *g; + *f ^= *g >> 4; *a += *f; *g += *h; + *g ^= *h << 8; *b += *g; *h += *a; + *h ^= *a >> 9; *c += *h; *a += *b; + } + + // These numbers are the result of initializing a...h with the + // fractional part of the golden ratio in binary (0x9e3779b9) + // and applying mix() 4 times. + let mut a = w(0x1367df5a); + let mut b = w(0x95d90059); + let mut c = w(0xc3163e4b); + let mut d = w(0x0f421ad8); + let mut e = w(0xd92a4a78); + let mut f = w(0xa51a3c49); + let mut g = w(0xc4efea1b); + let mut h = w(0x30609119); + + // Normally this should do two passes, to make all of the seed effect + // all of `mem` + for _ in 0..rounds { + for i in (0..RAND_SIZE/8).map(|i| i * 8) { + a += mem[i ]; b += mem[i+1]; + c += mem[i+2]; d += mem[i+3]; + e += mem[i+4]; f += mem[i+5]; + g += mem[i+6]; h += mem[i+7]; + mix(&mut a, &mut b, &mut c, &mut d, + &mut e, &mut f, &mut g, &mut h); + mem[i ] = a; mem[i+1] = b; + mem[i+2] = c; mem[i+3] = d; + mem[i+4] = e; mem[i+5] = f; + mem[i+6] = g; mem[i+7] = h; + } + } + + Self { mem, a: w(0), b: w(0), c: w(0) } + } +} + +impl SeedableRng for IsaacCore { + type Seed = [u8; 32]; + + fn from_seed(seed: Self::Seed) -> Self { + let mut seed_u32 = [0u32; 8]; + le::read_u32_into(&seed, &mut seed_u32); + // Convert the seed to `Wrapping` and zero-extend to `RAND_SIZE`. + let mut seed_extended = [w(0); RAND_SIZE]; + for (x, y) in seed_extended.iter_mut().zip(seed_u32.iter()) { + *x = w(*y); + } + Self::init(seed_extended, 2) + } + + /// Create an ISAAC random number generator using an `u64` as seed. + /// If `seed == 0` this will produce the same stream of random numbers as + /// the reference implementation when used unseeded. + fn seed_from_u64(seed: u64) -> Self { + let mut key = [w(0); RAND_SIZE]; + key[0] = w(seed as u32); + key[1] = w((seed >> 32) as u32); + // Initialize with only one pass. + // A second pass does not improve the quality here, because all of the + // seed was already available in the first round. + // Not doing the second pass has the small advantage that if + // `seed == 0` this method produces exactly the same state as the + // reference implementation when used unseeded. + Self::init(key, 1) + } + + fn from_rng(mut rng: R) -> Result { + // Custom `from_rng` implementation that fills a seed with the same size + // as the entire state. + let mut seed = [w(0u32); RAND_SIZE]; + unsafe { + let ptr = seed.as_mut_ptr() as *mut u8; + + let slice = slice::from_raw_parts_mut(ptr, RAND_SIZE * 4); + rng.try_fill_bytes(slice)?; + } + for i in seed.iter_mut() { + *i = w(i.0.to_le()); + } + + Ok(Self::init(seed, 2)) + } +} + +#[cfg(test)] +mod test { + use rand_core::{RngCore, SeedableRng}; + use super::IsaacRng; + + #[test] + fn test_isaac_construction() { + // Test that various construction techniques produce a working RNG. + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng1 = IsaacRng::from_seed(seed); + assert_eq!(rng1.next_u32(), 2869442790); + + let mut rng2 = IsaacRng::from_rng(rng1).unwrap(); + assert_eq!(rng2.next_u32(), 3094074039); + } + + #[test] + fn test_isaac_true_values_32() { + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng1 = IsaacRng::from_seed(seed); + let mut results = [0u32; 10]; + for i in results.iter_mut() { *i = rng1.next_u32(); } + let expected = [ + 2558573138, 873787463, 263499565, 2103644246, 3595684709, + 4203127393, 264982119, 2765226902, 2737944514, 3900253796]; + assert_eq!(results, expected); + + let seed = [57,48,0,0, 50,9,1,0, 49,212,0,0, 148,38,0,0, + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng2 = IsaacRng::from_seed(seed); + // skip forward to the 10000th number + for _ in 0..10000 { rng2.next_u32(); } + + for i in results.iter_mut() { *i = rng2.next_u32(); } + let expected = [ + 3676831399, 3183332890, 2834741178, 3854698763, 2717568474, + 1576568959, 3507990155, 179069555, 141456972, 2478885421]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac_true_values_64() { + // As above, using little-endian versions of above values + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng = IsaacRng::from_seed(seed); + let mut results = [0u64; 5]; + for i in results.iter_mut() { *i = rng.next_u64(); } + let expected = [ + 3752888579798383186, 9035083239252078381,18052294697452424037, + 11876559110374379111, 16751462502657800130]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac_true_bytes() { + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng = IsaacRng::from_seed(seed); + let mut results = [0u8; 32]; + rng.fill_bytes(&mut results); + // Same as first values in test_isaac_true_values as bytes in LE order + let expected = [82, 186, 128, 152, 71, 240, 20, 52, + 45, 175, 180, 15, 86, 16, 99, 125, + 101, 203, 81, 214, 97, 162, 134, 250, + 103, 78, 203, 15, 150, 3, 210, 164]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac_new_uninitialized() { + // Compare the results from initializing `IsaacRng` with + // `seed_from_u64(0)`, to make sure it is the same as the reference + // implementation when used uninitialized. + // Note: We only test the first 16 integers, not the full 256 of the + // first block. + let mut rng = IsaacRng::seed_from_u64(0); + let mut results = [0u32; 16]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected: [u32; 16] = [ + 0x71D71FD2, 0xB54ADAE7, 0xD4788559, 0xC36129FA, + 0x21DC1EA9, 0x3CB879CA, 0xD83B237F, 0xFA3CE5BD, + 0x8D048509, 0xD82E9489, 0xDB452848, 0xCA20E846, + 0x500F972E, 0x0EEFF940, 0x00D6B993, 0xBC12C17F]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac_clone() { + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng1 = IsaacRng::from_seed(seed); + let mut rng2 = rng1.clone(); + for _ in 0..16 { + assert_eq!(rng1.next_u32(), rng2.next_u32()); + } + } + + #[test] + #[cfg(feature="serde1")] + fn test_isaac_serde() { + use bincode; + use std::io::{BufWriter, BufReader}; + + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng = IsaacRng::from_seed(seed); + + let buf: Vec = Vec::new(); + let mut buf = BufWriter::new(buf); + bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); + + let buf = buf.into_inner().unwrap(); + let mut read = BufReader::new(&buf[..]); + let mut deserialized: IsaacRng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); + + for _ in 0..300 { // more than the 256 buffered results + assert_eq!(rng.next_u32(), deserialized.next_u32()); + } + } +} diff --git a/bash-5.1/vendor/rand_isaac/src/isaac64.rs b/bash-5.1/vendor/rand_isaac/src/isaac64.rs new file mode 100644 index 0000000..2712762 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/src/isaac64.rs @@ -0,0 +1,481 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The ISAAC-64 random number generator. + +use core::{fmt, slice}; +use core::num::Wrapping as w; +use rand_core::{RngCore, SeedableRng, Error, le}; +use rand_core::block::{BlockRngCore, BlockRng64}; +use isaac_array::IsaacArray; + +#[allow(non_camel_case_types)] +type w64 = w; + +const RAND_SIZE_LEN: usize = 8; +const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; + +/// A random number generator that uses ISAAC-64, the 64-bit variant of the +/// ISAAC algorithm. +/// +/// ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are +/// the principal bitwise operations employed. It is the most advanced of a +/// series of array based random number generator designed by Robert Jenkins +/// in 1996[^1]. +/// +/// ISAAC-64 is mostly similar to ISAAC. Because it operates on 64-bit integers +/// instead of 32-bit, it uses twice as much memory to hold its state and +/// results. Also it uses different constants for shifts and indirect indexing, +/// optimized to give good results for 64bit arithmetic. +/// +/// ISAAC-64 is notably fast and produces excellent quality random numbers for +/// non-cryptographic applications. +/// +/// In spite of being designed with cryptographic security in mind, ISAAC hasn't +/// been stringently cryptanalyzed and thus cryptographers do not not +/// consensually trust it to be secure. When looking for a secure RNG, prefer +/// [`Hc128Rng`] instead, which, like ISAAC, is an array-based RNG and one of +/// the stream-ciphers selected the by eSTREAM contest. +/// +/// ## Overview of the ISAAC-64 algorithm: +/// (in pseudo-code) +/// +/// ```text +/// Input: a, b, c, s[256] // state +/// Output: r[256] // results +/// +/// mix(a,i) = !(a ^ a << 21) if i = 0 mod 4 +/// a ^ a >> 5 if i = 1 mod 4 +/// a ^ a << 12 if i = 2 mod 4 +/// a ^ a >> 33 if i = 3 mod 4 +/// +/// c = c + 1 +/// b = b + c +/// +/// for i in 0..256 { +/// x = s_[i] +/// a = mix(a,i) + s[i+128 mod 256] +/// y = a + b + s[x>>3 mod 256] +/// s[i] = y +/// b = x + s[y>>11 mod 256] +/// r[i] = b +/// } +/// ``` +/// +/// This implementation uses [`BlockRng64`] to implement the [`RngCore`] methods. +/// +/// See for more information the documentation of [`IsaacRng`]. +/// +/// [^1]: Bob Jenkins, [*ISAAC and RC4*]( +/// http://burtleburtle.net/bob/rand/isaac.html) +/// +/// [`IsaacRng`]: ../isaac/struct.IsaacRng.html +/// [`Hc128Rng`]: ../../rand_hc/struct.Hc128Rng.html +/// [`BlockRng64`]: ../../rand_core/block/struct.BlockRng64.html +/// [`RngCore`]: ../../rand_core/trait.RngCore.html +#[derive(Clone, Debug)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct Isaac64Rng(BlockRng64); + +impl RngCore for Isaac64Rng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.0.try_fill_bytes(dest) + } +} + +impl SeedableRng for Isaac64Rng { + type Seed = ::Seed; + + fn from_seed(seed: Self::Seed) -> Self { + Isaac64Rng(BlockRng64::::from_seed(seed)) + } + + /// Create an ISAAC random number generator using an `u64` as seed. + /// If `seed == 0` this will produce the same stream of random numbers as + /// the reference implementation when used unseeded. + fn seed_from_u64(seed: u64) -> Self { + Isaac64Rng(BlockRng64::::seed_from_u64(seed)) + } + + fn from_rng(rng: S) -> Result { + BlockRng64::::from_rng(rng).map(|rng| Isaac64Rng(rng)) + } +} + +impl Isaac64Rng { + /// Create an ISAAC-64 random number generator using an `u64` as seed. + /// If `seed == 0` this will produce the same stream of random numbers as + /// the reference implementation when used unseeded. + #[deprecated(since="0.6.0", note="use SeedableRng::seed_from_u64 instead")] + pub fn new_from_u64(seed: u64) -> Self { + Self::seed_from_u64(seed) + } +} + +/// The core of `Isaac64Rng`, used with `BlockRng`. +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct Isaac64Core { + #[cfg_attr(feature="serde1",serde(with="super::isaac_array::isaac_array_serde"))] + mem: [w64; RAND_SIZE], + a: w64, + b: w64, + c: w64, +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for Isaac64Core { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Isaac64Core {{}}") + } +} + +impl BlockRngCore for Isaac64Core { + type Item = u64; + type Results = IsaacArray; + + /// Refills the output buffer, `results`. See also the pseudocode desciption + /// of the algorithm in the [`Isaac64Rng`] documentation. + /// + /// Optimisations used (similar to the reference implementation): + /// + /// - The loop is unrolled 4 times, once for every constant of mix(). + /// - The contents of the main loop are moved to a function `rngstep`, to + /// reduce code duplication. + /// - We use local variables for a and b, which helps with optimisations. + /// - We split the main loop in two, one that operates over 0..128 and one + /// over 128..256. This way we can optimise out the addition and modulus + /// from `s[i+128 mod 256]`. + /// - We maintain one index `i` and add `m` or `m2` as base (m2 for the + /// `s[i+128 mod 256]`), relying on the optimizer to turn it into pointer + /// arithmetic. + /// - We fill `results` backwards. The reference implementation reads values + /// from `results` in reverse. We read them in the normal direction, to + /// make `fill_bytes` a memcopy. To maintain compatibility we fill in + /// reverse. + /// + /// [`Isaac64Rng`]: struct.Isaac64Rng.html + fn generate(&mut self, results: &mut IsaacArray) { + self.c += w(1); + // abbreviations + let mut a = self.a; + let mut b = self.b + self.c; + const MIDPOINT: usize = RAND_SIZE / 2; + + #[inline] + fn ind(mem:&[w64; RAND_SIZE], v: w64, amount: usize) -> w64 { + let index = (v >> amount).0 as usize % RAND_SIZE; + mem[index] + } + + #[inline] + fn rngstep(mem: &mut [w64; RAND_SIZE], + results: &mut [u64; RAND_SIZE], + mix: w64, + a: &mut w64, + b: &mut w64, + base: usize, + m: usize, + m2: usize) { + let x = mem[base + m]; + *a = mix + mem[base + m2]; + let y = *a + *b + ind(&mem, x, 3); + mem[base + m] = y; + *b = x + ind(&mem, y, 3 + RAND_SIZE_LEN); + results[RAND_SIZE - 1 - base - m] = (*b).0; + } + + let mut m = 0; + let mut m2 = MIDPOINT; + for i in (0..MIDPOINT/4).map(|i| i * 4) { + rngstep(&mut self.mem, results, !(a ^ (a << 21)), &mut a, &mut b, i + 0, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 5 ), &mut a, &mut b, i + 1, m, m2); + rngstep(&mut self.mem, results, a ^ (a << 12), &mut a, &mut b, i + 2, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 33), &mut a, &mut b, i + 3, m, m2); + } + + m = MIDPOINT; + m2 = 0; + for i in (0..MIDPOINT/4).map(|i| i * 4) { + rngstep(&mut self.mem, results, !(a ^ (a << 21)), &mut a, &mut b, i + 0, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 5 ), &mut a, &mut b, i + 1, m, m2); + rngstep(&mut self.mem, results, a ^ (a << 12), &mut a, &mut b, i + 2, m, m2); + rngstep(&mut self.mem, results, a ^ (a >> 33), &mut a, &mut b, i + 3, m, m2); + } + + self.a = a; + self.b = b; + } +} + +impl Isaac64Core { + /// Create a new ISAAC-64 random number generator. + fn init(mut mem: [w64; RAND_SIZE], rounds: u32) -> Self { + fn mix(a: &mut w64, b: &mut w64, c: &mut w64, d: &mut w64, + e: &mut w64, f: &mut w64, g: &mut w64, h: &mut w64) { + *a -= *e; *f ^= *h >> 9; *h += *a; + *b -= *f; *g ^= *a << 9; *a += *b; + *c -= *g; *h ^= *b >> 23; *b += *c; + *d -= *h; *a ^= *c << 15; *c += *d; + *e -= *a; *b ^= *d >> 14; *d += *e; + *f -= *b; *c ^= *e << 20; *e += *f; + *g -= *c; *d ^= *f >> 17; *f += *g; + *h -= *d; *e ^= *g << 14; *g += *h; + } + + // These numbers are the result of initializing a...h with the + // fractional part of the golden ratio in binary (0x9e3779b97f4a7c13) + // and applying mix() 4 times. + let mut a = w(0x647c4677a2884b7c); + let mut b = w(0xb9f8b322c73ac862); + let mut c = w(0x8c0ea5053d4712a0); + let mut d = w(0xb29b2e824a595524); + let mut e = w(0x82f053db8355e0ce); + let mut f = w(0x48fe4a0fa5a09315); + let mut g = w(0xae985bf2cbfc89ed); + let mut h = w(0x98f5704f6c44c0ab); + + // Normally this should do two passes, to make all of the seed effect + // all of `mem` + for _ in 0..rounds { + for i in (0..RAND_SIZE/8).map(|i| i * 8) { + a += mem[i ]; b += mem[i+1]; + c += mem[i+2]; d += mem[i+3]; + e += mem[i+4]; f += mem[i+5]; + g += mem[i+6]; h += mem[i+7]; + mix(&mut a, &mut b, &mut c, &mut d, + &mut e, &mut f, &mut g, &mut h); + mem[i ] = a; mem[i+1] = b; + mem[i+2] = c; mem[i+3] = d; + mem[i+4] = e; mem[i+5] = f; + mem[i+6] = g; mem[i+7] = h; + } + } + + Self { mem, a: w(0), b: w(0), c: w(0) } + } + + /// Create an ISAAC-64 random number generator using an `u64` as seed. + /// If `seed == 0` this will produce the same stream of random numbers as + /// the reference implementation when used unseeded. + #[deprecated(since="0.6.0", note="use SeedableRng::seed_from_u64 instead")] + pub fn new_from_u64(seed: u64) -> Self { + Self::seed_from_u64(seed) + } +} + +impl SeedableRng for Isaac64Core { + type Seed = [u8; 32]; + + fn from_seed(seed: Self::Seed) -> Self { + let mut seed_u64 = [0u64; 4]; + le::read_u64_into(&seed, &mut seed_u64); + // Convert the seed to `Wrapping` and zero-extend to `RAND_SIZE`. + let mut seed_extended = [w(0); RAND_SIZE]; + for (x, y) in seed_extended.iter_mut().zip(seed_u64.iter()) { + *x = w(*y); + } + Self::init(seed_extended, 2) + } + + fn seed_from_u64(seed: u64) -> Self { + let mut key = [w(0); RAND_SIZE]; + key[0] = w(seed); + // Initialize with only one pass. + // A second pass does not improve the quality here, because all of the + // seed was already available in the first round. + // Not doing the second pass has the small advantage that if + // `seed == 0` this method produces exactly the same state as the + // reference implementation when used unseeded. + Self::init(key, 1) + } + + fn from_rng(mut rng: R) -> Result { + // Custom `from_rng` implementation that fills a seed with the same size + // as the entire state. + let mut seed = [w(0u64); RAND_SIZE]; + unsafe { + let ptr = seed.as_mut_ptr() as *mut u8; + let slice = slice::from_raw_parts_mut(ptr, RAND_SIZE * 8); + rng.try_fill_bytes(slice)?; + } + for i in seed.iter_mut() { + *i = w(i.0.to_le()); + } + + Ok(Self::init(seed, 2)) + } +} + +#[cfg(test)] +mod test { + use rand_core::{RngCore, SeedableRng}; + use super::Isaac64Rng; + + #[test] + fn test_isaac64_construction() { + // Test that various construction techniques produce a working RNG. + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng1 = Isaac64Rng::from_seed(seed); + assert_eq!(rng1.next_u64(), 14964555543728284049); + + let mut rng2 = Isaac64Rng::from_rng(rng1).unwrap(); + assert_eq!(rng2.next_u64(), 919595328260451758); + } + + #[test] + fn test_isaac64_true_values_64() { + let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, + 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; + let mut rng1 = Isaac64Rng::from_seed(seed); + let mut results = [0u64; 10]; + for i in results.iter_mut() { *i = rng1.next_u64(); } + let expected = [ + 15071495833797886820, 7720185633435529318, + 10836773366498097981, 5414053799617603544, + 12890513357046278984, 17001051845652595546, + 9240803642279356310, 12558996012687158051, + 14673053937227185542, 1677046725350116783]; + assert_eq!(results, expected); + + let seed = [57,48,0,0, 0,0,0,0, 50,9,1,0, 0,0,0,0, + 49,212,0,0, 0,0,0,0, 148,38,0,0, 0,0,0,0]; + let mut rng2 = Isaac64Rng::from_seed(seed); + // skip forward to the 10000th number + for _ in 0..10000 { rng2.next_u64(); } + + for i in results.iter_mut() { *i = rng2.next_u64(); } + let expected = [ + 18143823860592706164, 8491801882678285927, 2699425367717515619, + 17196852593171130876, 2606123525235546165, 15790932315217671084, + 596345674630742204, 9947027391921273664, 11788097613744130851, + 10391409374914919106]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac64_true_values_32() { + let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, + 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; + let mut rng = Isaac64Rng::from_seed(seed); + let mut results = [0u32; 12]; + for i in results.iter_mut() { *i = rng.next_u32(); } + // Subset of above values, as an LE u32 sequence + let expected = [ + 3477963620, 3509106075, + 687845478, 1797495790, + 227048253, 2523132918, + 4044335064, 1260557630, + 4079741768, 3001306521, + 69157722, 3958365844]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac64_true_values_mixed() { + let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, + 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; + let mut rng = Isaac64Rng::from_seed(seed); + // Test alternating between `next_u64` and `next_u32` works as expected. + // Values are the same as `test_isaac64_true_values` and + // `test_isaac64_true_values_32`. + assert_eq!(rng.next_u64(), 15071495833797886820); + assert_eq!(rng.next_u32(), 687845478); + assert_eq!(rng.next_u32(), 1797495790); + assert_eq!(rng.next_u64(), 10836773366498097981); + assert_eq!(rng.next_u32(), 4044335064); + // Skip one u32 + assert_eq!(rng.next_u64(), 12890513357046278984); + assert_eq!(rng.next_u32(), 69157722); + } + + #[test] + fn test_isaac64_true_bytes() { + let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, + 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; + let mut rng = Isaac64Rng::from_seed(seed); + let mut results = [0u8; 32]; + rng.fill_bytes(&mut results); + // Same as first values in test_isaac64_true_values as bytes in LE order + let expected = [100, 131, 77, 207, 155, 181, 40, 209, + 102, 176, 255, 40, 238, 155, 35, 107, + 61, 123, 136, 13, 246, 243, 99, 150, + 216, 167, 15, 241, 62, 149, 34, 75]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac64_new_uninitialized() { + // Compare the results from initializing `IsaacRng` with + // `seed_from_u64(0)`, to make sure it is the same as the reference + // implementation when used uninitialized. + // Note: We only test the first 16 integers, not the full 256 of the + // first block. + let mut rng = Isaac64Rng::seed_from_u64(0); + let mut results = [0u64; 16]; + for i in results.iter_mut() { *i = rng.next_u64(); } + let expected: [u64; 16] = [ + 0xF67DFBA498E4937C, 0x84A5066A9204F380, 0xFEE34BD5F5514DBB, + 0x4D1664739B8F80D6, 0x8607459AB52A14AA, 0x0E78BC5A98529E49, + 0xFE5332822AD13777, 0x556C27525E33D01A, 0x08643CA615F3149F, + 0xD0771FAF3CB04714, 0x30E86F68A37B008D, 0x3074EBC0488A3ADF, + 0x270645EA7A2790BC, 0x5601A0A8D3763C6A, 0x2F83071F53F325DD, + 0xB9090F3D42D2D2EA]; + assert_eq!(results, expected); + } + + #[test] + fn test_isaac64_clone() { + let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, + 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; + let mut rng1 = Isaac64Rng::from_seed(seed); + let mut rng2 = rng1.clone(); + for _ in 0..16 { + assert_eq!(rng1.next_u64(), rng2.next_u64()); + } + } + + #[test] + #[cfg(feature="serde1")] + fn test_isaac64_serde() { + use bincode; + use std::io::{BufWriter, BufReader}; + + let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, + 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng = Isaac64Rng::from_seed(seed); + + let buf: Vec = Vec::new(); + let mut buf = BufWriter::new(buf); + bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); + + let buf = buf.into_inner().unwrap(); + let mut read = BufReader::new(&buf[..]); + let mut deserialized: Isaac64Rng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); + + for _ in 0..300 { // more than the 256 buffered results + assert_eq!(rng.next_u64(), deserialized.next_u64()); + } + } +} diff --git a/bash-5.1/vendor/rand_isaac/src/isaac_array.rs b/bash-5.1/vendor/rand_isaac/src/isaac_array.rs new file mode 100644 index 0000000..0fa6147 --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/src/isaac_array.rs @@ -0,0 +1,136 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! ISAAC helper functions for 256-element arrays. + +// Terrible workaround because arrays with more than 32 elements do not +// implement `AsRef`, `Default`, `Serialize`, `Deserialize`, or any other +// traits for that matter. + +#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; + +const RAND_SIZE_LEN: usize = 8; +const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; + + +#[derive(Copy, Clone)] +#[allow(missing_debug_implementations)] +#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] +pub struct IsaacArray { + #[cfg_attr(feature="serde1",serde(with="isaac_array_serde"))] + #[cfg_attr(feature="serde1", serde(bound( + serialize = "T: Serialize", + deserialize = "T: Deserialize<'de> + Copy + Default")))] + inner: [T; RAND_SIZE] +} + +impl ::core::convert::AsRef<[T]> for IsaacArray { + #[inline(always)] + fn as_ref(&self) -> &[T] { + &self.inner[..] + } +} + +impl ::core::convert::AsMut<[T]> for IsaacArray { + #[inline(always)] + fn as_mut(&mut self) -> &mut [T] { + &mut self.inner[..] + } +} + +impl ::core::ops::Deref for IsaacArray { + type Target = [T; RAND_SIZE]; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl ::core::ops::DerefMut for IsaacArray { + #[inline(always)] + fn deref_mut(&mut self) -> &mut [T; RAND_SIZE] { + &mut self.inner + } +} + +impl ::core::default::Default for IsaacArray where T: Copy + Default { + fn default() -> IsaacArray { + IsaacArray { inner: [T::default(); RAND_SIZE] } + } +} + + +#[cfg(feature="serde1")] +pub(super) mod isaac_array_serde { + const RAND_SIZE_LEN: usize = 8; + const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; + + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use serde::de::{Visitor,SeqAccess}; + use serde::de; + + use core::fmt; + + pub fn serialize(arr: &[T;RAND_SIZE], ser: S) -> Result + where + T: Serialize, + S: Serializer + { + use serde::ser::SerializeTuple; + + let mut seq = ser.serialize_tuple(RAND_SIZE)?; + + for e in arr.iter() { + seq.serialize_element(&e)?; + } + + seq.end() + } + + #[inline] + pub fn deserialize<'de, T, D>(de: D) -> Result<[T;RAND_SIZE], D::Error> + where + T: Deserialize<'de>+Default+Copy, + D: Deserializer<'de>, + { + use core::marker::PhantomData; + struct ArrayVisitor { + _pd: PhantomData, + }; + impl<'de,T> Visitor<'de> for ArrayVisitor + where + T: Deserialize<'de>+Default+Copy + { + type Value = [T; RAND_SIZE]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Isaac state array") + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result<[T; RAND_SIZE], A::Error> + where + A: SeqAccess<'de>, + { + let mut out = [Default::default();RAND_SIZE]; + + for i in 0..RAND_SIZE { + match seq.next_element()? { + Some(val) => out[i] = val, + None => return Err(de::Error::invalid_length(i, &self)), + }; + } + + Ok(out) + } + } + + de.deserialize_tuple(RAND_SIZE, ArrayVisitor{_pd: PhantomData}) + } +} diff --git a/bash-5.1/vendor/rand_isaac/src/lib.rs b/bash-5.1/vendor/rand_isaac/src/lib.rs new file mode 100644 index 0000000..ec82d8e --- /dev/null +++ b/bash-5.1/vendor/rand_isaac/src/lib.rs @@ -0,0 +1,36 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The ISAAC and ISAAC-64 random number generators. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![cfg_attr(not(all(feature="serde1", test)), no_std)] + +extern crate rand_core; + +#[cfg(feature="serde1")] extern crate serde; +#[cfg(feature="serde1")] #[macro_use] extern crate serde_derive; + +// To test serialization we need bincode and the standard library +#[cfg(all(feature="serde1", test))] extern crate bincode; +#[cfg(all(feature="serde1", test))] extern crate std as core; + +pub mod isaac; +pub mod isaac64; + +mod isaac_array; + +pub use self::isaac::IsaacRng; +pub use self::isaac64::Isaac64Rng; diff --git a/bash-5.1/vendor/rand_jitter/.cargo-checksum.json b/bash-5.1/vendor/rand_jitter/.cargo-checksum.json new file mode 100644 index 0000000..bf96336 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"dd1714225c7cca47c349ddbca2b5ab8a546e0c7b1c52cf05cafca1e05c48f2b0","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"d524ddfe62a9ca58ff86d9ad37532081bae35bfcca2a1e68ca0ffaf0e981d477","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7b685b3204fc1bb9a09b40eb586bf55358f076b276866c1c2afb20f57e8357b2","benches/mod.rs":"caea9aa8c327d4af18eeabe798cf7919d5f64225c3e5f4685814592a1595b9bf","src/dummy_log.rs":"4e26589c18de568b7da7f0ccc9b77bb430961739a6510c2b043a43dee300c6fa","src/error.rs":"e632a67e30528bed8c2a74b04b04e4e67f6c184d21234d74cc28f5f292e47666","src/lib.rs":"6655eb8d1fba653dda788c885ae380b017e6482baa6e2885019d33dbd829b0e6","src/platform.rs":"8c7b75567a28391176de17a3df2a8c6b3517f2c1f044b792db50de19844e9660","tests/mod.rs":"f3f99c64b250b2ddea43e724c47497de3d68cbaf05a0a8a255d360861cd979ec"},"package":"1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_jitter/CHANGELOG.md b/bash-5.1/vendor/rand_jitter/CHANGELOG.md new file mode 100644 index 0000000..bbb21dc --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.4] - 2019-05-02 +- Change error conversion code to partially fix #738 + +## [0.1.3] - 2019-02-05 +- Use libc in `no_std` mode to fix #723 + +## [0.1.2] - 2019-01-31 +- Fix for older rustc compilers on Windows (#722) + +## [0.1.1] - 2019-01-29 +- Fix for older rustc compilers on Mac OSX / iOS (#720) +- Misc. doc fixes + +## [0.1.0] - 2019-01-24 +Initial release. diff --git a/bash-5.1/vendor/rand_jitter/COPYRIGHT b/bash-5.1/vendor/rand_jitter/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_jitter/Cargo.toml b/bash-5.1/vendor/rand_jitter/Cargo.toml new file mode 100644 index 0000000..387b807 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/Cargo.toml @@ -0,0 +1,42 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_jitter" +version = "0.1.4" +authors = ["The Rand Project Developers"] +description = "Random number generator based on timing jitter" +documentation = "https://docs.rs/rand_jitter" +readme = "README.md" +keywords = ["random", "rng", "os"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.log] +version = "0.4" +optional = true + +[dependencies.rand_core] +version = "0.4" + +[features] +std = ["rand_core/std"] +[target."cfg(any(target_os = \"macos\", target_os = \"ios\"))".dependencies.libc] +version = "0.2" +default_features = false +[target."cfg(target_os = \"windows\")".dependencies.winapi] +version = "0.3" +features = ["profileapi"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_jitter/LICENSE-APACHE b/bash-5.1/vendor/rand_jitter/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_jitter/LICENSE-MIT b/bash-5.1/vendor/rand_jitter/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_jitter/README.md b/bash-5.1/vendor/rand_jitter/README.md new file mode 100644 index 0000000..8e0805f --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/README.md @@ -0,0 +1,104 @@ +# rand_jitter +[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_jitter.svg)](https://crates.io/crates/rand_jitter) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_jitter) +[![API](https://docs.rs/rand_jitter/badge.svg)](https://docs.rs/rand_jitter) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Non-physical true random number generator based on timing jitter. + +This crate depends on [rand_core](https://crates.io/crates/rand_core) and is +part of the [Rand project](https://github.com/rust-random/rand). + +This crate aims to support all of Rust's `std` platforms with a system-provided +entropy source. Unlike other Rand crates, this crate does not support `no_std` +(handling this gracefully is a current discussion topic). + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_jitter) +- [API documentation (docs.rs)](https://docs.rs/rand_jitter) +- [Changelog](CHANGELOG.md) + +## Features + +This crate has optional `std` support which is *disabled by default*; +this feature is required to provide the `JitterRng::new` function; +without `std` support a timer must be supplied via `JitterRng::new_with_timer`. + +## Quality testing + +`JitterRng::new()` has build-in, but limited, quality testing, however +before using `JitterRng` on untested hardware, or after changes that could +effect how the code is optimized (such as a new LLVM version), it is +recommend to run the much more stringent +[NIST SP 800-90B Entropy Estimation Suite](https://github.com/usnistgov/SP800-90B_EntropyAssessment). + +Use the following code using `timer_stats` to collect the data: + +```rust +use rand_jitter::JitterRng; + +use std::error::Error; +use std::fs::File; +use std::io::Write; + +fn main() -> Result<(), Box> { + let mut rng = JitterRng::new()?; + + // 1_000_000 results are required for the + // NIST SP 800-90B Entropy Estimation Suite + const ROUNDS: usize = 1_000_000; + let mut deltas_variable: Vec = Vec::with_capacity(ROUNDS); + let mut deltas_minimal: Vec = Vec::with_capacity(ROUNDS); + + for _ in 0..ROUNDS { + deltas_variable.push(rng.timer_stats(true) as u8); + deltas_minimal.push(rng.timer_stats(false) as u8); + } + + // Write out after the statistics collection loop, to not disturb the + // test results. + File::create("jitter_rng_var.bin")?.write(&deltas_variable)?; + File::create("jitter_rng_min.bin")?.write(&deltas_minimal)?; + Ok(()) +} +``` + +This will produce two files: `jitter_rng_var.bin` and `jitter_rng_min.bin`. +Run the Entropy Estimation Suite in three configurations, as outlined below. +Every run has two steps. One step to produce an estimation, another to +validate the estimation. + +1. Estimate the expected amount of entropy that is at least available with + each round of the entropy collector. This number should be greater than + the amount estimated with `64 / test_timer()`. + ```sh + python noniid_main.py -v jitter_rng_var.bin 8 + restart.py -v jitter_rng_var.bin 8 + ``` +2. Estimate the expected amount of entropy that is available in the last 4 + bits of the timer delta after running noice sources. Note that a value of + `3.70` is the minimum estimated entropy for true randomness. + ```sh + python noniid_main.py -v -u 4 jitter_rng_var.bin 4 + restart.py -v -u 4 jitter_rng_var.bin 4 + ``` +3. Estimate the expected amount of entropy that is available to the entropy + collector if both noise sources only run their minimal number of times. + This measures the absolute worst-case, and gives a lower bound for the + available entropy. + ```sh + python noniid_main.py -v -u 4 jitter_rng_min.bin 4 + restart.py -v -u 4 jitter_rng_min.bin 4 + ``` + +## License + +`rand_jitter` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_jitter/benches/mod.rs b/bash-5.1/vendor/rand_jitter/benches/mod.rs new file mode 100644 index 0000000..23b3447 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/benches/mod.rs @@ -0,0 +1,18 @@ +#![feature(test)] +extern crate test; +extern crate rand_jitter; + +use test::Bencher; +use rand_jitter::rand_core::RngCore; + +#[bench] +fn bench_add_two(b: &mut Bencher) { + let mut rng = rand_jitter::JitterRng::new().unwrap(); + let mut buf = [0u8; 1024]; + b.iter(|| { + rng.fill_bytes(&mut buf[..]); + test::black_box(&buf); + }); + b.bytes = buf.len() as u64; +} + diff --git a/bash-5.1/vendor/rand_jitter/src/dummy_log.rs b/bash-5.1/vendor/rand_jitter/src/dummy_log.rs new file mode 100644 index 0000000..ccfe4ba --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/src/dummy_log.rs @@ -0,0 +1,10 @@ +#[allow(unused)] +macro_rules! trace { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! debug { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! info { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! warn { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! error { ($($x:tt)*) => () } diff --git a/bash-5.1/vendor/rand_jitter/src/error.rs b/bash-5.1/vendor/rand_jitter/src/error.rs new file mode 100644 index 0000000..a3483e8 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/src/error.rs @@ -0,0 +1,70 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2015 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use rand_core::{Error, ErrorKind}; +use core::fmt; + +/// An error that can occur when [`JitterRng::test_timer`] fails. +/// +/// [`JitterRng::test_timer`]: crate::JitterRng::test_timer +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TimerError { + /// No timer available. + NoTimer, + /// Timer too coarse to use as an entropy source. + CoarseTimer, + /// Timer is not monotonically increasing. + NotMonotonic, + /// Variations of deltas of time too small. + TinyVariantions, + /// Too many stuck results (indicating no added entropy). + TooManyStuck, + #[doc(hidden)] + __Nonexhaustive, +} + +impl TimerError { + fn description(&self) -> &'static str { + match *self { + TimerError::NoTimer => "no timer available", + TimerError::CoarseTimer => "coarse timer", + TimerError::NotMonotonic => "timer not monotonic", + TimerError::TinyVariantions => "time delta variations too small", + TimerError::TooManyStuck => "too many stuck results", + TimerError::__Nonexhaustive => unreachable!(), + } + } +} + +impl fmt::Display for TimerError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.description()) + } +} + +#[cfg(feature = "std")] +impl ::std::error::Error for TimerError { + fn description(&self) -> &str { + self.description() + } +} + +impl From for Error { + fn from(err: TimerError) -> Error { + // Timer check is already quite permissive of failures so we don't + // expect false-positive failures, i.e. any error is irrecoverable. + #[cfg(feature = "std")] { + Error::with_cause(ErrorKind::Unavailable, "timer jitter failed basic quality tests", err) + } + #[cfg(not(feature = "std"))] { + Error::new(ErrorKind::Unavailable, "timer jitter failed basic quality tests") + } + } +} + diff --git a/bash-5.1/vendor/rand_jitter/src/lib.rs b/bash-5.1/vendor/rand_jitter/src/lib.rs new file mode 100644 index 0000000..338a6b9 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/src/lib.rs @@ -0,0 +1,718 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +// +// Based on jitterentropy-library, http://www.chronox.de/jent.html. +// Copyright Stephan Mueller , 2014 - 2017. +// +// With permission from Stephan Mueller to relicense the Rust translation under +// the MIT license. + +//! Non-physical true random number generator based on timing jitter. +//! +//! This is a true random number generator, as opposed to pseudo-random +//! generators. Random numbers generated by `JitterRng` can be seen as fresh +//! entropy. A consequence is that it is orders of magnitude slower than `OsRng` +//! and PRNGs (about 103..106 slower). +//! +//! There are very few situations where using this RNG is appropriate. Only very +//! few applications require true entropy. A normal PRNG can be statistically +//! indistinguishable, and a cryptographic PRNG should also be as impossible to +//! predict. +//! +//! Use of `JitterRng` is recommended for initializing cryptographic PRNGs when +//! `OsRng` is not available. +//! +//! `JitterRng` can be used without the standard library, but not conveniently, +//! you must provide a high-precision timer and carefully have to follow the +//! instructions of [`JitterRng::new_with_timer`]. +//! +//! This implementation is based on [Jitterentropy] version 2.1.0. +//! +//! Note: There is no accurate timer available on WASM platforms, to help +//! prevent fingerprinting or timing side-channel attacks. Therefore +//! [`JitterRng::new()`] is not available on WASM. It is also unavailable +//! with disabled `std` feature. +//! +//! [Jitterentropy]: http://www.chronox.de/jent.html + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +// Note: the C implementation of `Jitterentropy` relies on being compiled +// without optimizations. This implementation goes through lengths to make the +// compiler not optimize out code which does influence timing jitter, but is +// technically dead code. +#![no_std] +pub extern crate rand_core; +#[cfg(feature = "std")] +extern crate std; +#[cfg(feature = "log")] +#[macro_use] extern crate log; +#[cfg(any(target_os = "macos", target_os = "ios"))] +extern crate libc; +#[cfg(target_os = "windows")] +extern crate winapi; + + +#[cfg(not(feature = "log"))] +#[macro_use] mod dummy_log; +#[cfg(feature = "std")] +mod platform; +mod error; + +use rand_core::{RngCore, CryptoRng, Error, impls}; +pub use error::TimerError; + +use core::{fmt, mem, ptr}; +#[cfg(feature = "std")] +use std::sync::atomic::{AtomicUsize, Ordering}; +#[cfg(feature = "std")] +#[allow(deprecated)] // Required for compatibility with Rust < 1.24. +use std::sync::atomic::ATOMIC_USIZE_INIT; + +const MEMORY_BLOCKS: usize = 64; +const MEMORY_BLOCKSIZE: usize = 32; +const MEMORY_SIZE: usize = MEMORY_BLOCKS * MEMORY_BLOCKSIZE; + +/// A true random number generator based on jitter in the CPU execution time, +/// and jitter in memory access time. +pub struct JitterRng { + data: u64, // Actual random number + // Number of rounds to run the entropy collector per 64 bits + rounds: u8, + // Timer used by `measure_jitter` + timer: fn() -> u64, + // Memory for the Memory Access noise source + mem_prev_index: u16, + // Make `next_u32` not waste 32 bits + data_half_used: bool, +} + +// Note: `JitterRng` maintains a small 64-bit entropy pool. With every +// `generate` 64 new bits should be integrated in the pool. If a round of +// `generate` were to collect less than the expected 64 bit, then the returned +// value, and the new state of the entropy pool, would be in some way related to +// the initial state. It is therefore better if the initial state of the entropy +// pool is different on each call to `generate`. This has a few implications: +// - `generate` should be called once before using `JitterRng` to produce the +// first usable value (this is done by default in `new`); +// - We do not zero the entropy pool after generating a result. The reference +// implementation also does not support zeroing, but recommends generating a +// new value without using it if you want to protect a previously generated +// 'secret' value from someone inspecting the memory; +// - Implementing `Clone` seems acceptable, as it would not cause the systematic +// bias a constant might cause. Only instead of one value that could be +// potentially related to the same initial state, there are now two. + +// Entropy collector state. +// These values are not necessary to preserve across runs. +struct EcState { + // Previous time stamp to determine the timer delta + prev_time: u64, + // Deltas used for the stuck test + last_delta: i32, + last_delta2: i32, + // Memory for the Memory Access noise source + mem: [u8; MEMORY_SIZE], +} + +impl EcState { + // Stuck test by checking the: + // - 1st derivation of the jitter measurement (time delta) + // - 2nd derivation of the jitter measurement (delta of time deltas) + // - 3rd derivation of the jitter measurement (delta of delta of time + // deltas) + // + // All values must always be non-zero. + // This test is a heuristic to see whether the last measurement holds + // entropy. + fn stuck(&mut self, current_delta: i32) -> bool { + let delta2 = self.last_delta - current_delta; + let delta3 = delta2 - self.last_delta2; + + self.last_delta = current_delta; + self.last_delta2 = delta2; + + current_delta == 0 || delta2 == 0 || delta3 == 0 + } +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for JitterRng { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "JitterRng {{}}") + } +} + +impl Clone for JitterRng { + fn clone(&self) -> JitterRng { + JitterRng { + data: self.data, + rounds: self.rounds, + timer: self.timer, + mem_prev_index: self.mem_prev_index, + // The 32 bits that may still be unused from the previous round are + // for the original to use, not for the clone. + data_half_used: false, + } + } +} + +// Initialise to zero; must be positive +#[cfg(all(feature = "std", not(target_arch = "wasm32")))] +#[allow(deprecated)] +static JITTER_ROUNDS: AtomicUsize = ATOMIC_USIZE_INIT; + +impl JitterRng { + /// Create a new `JitterRng`. Makes use of `std::time` for a timer, or a + /// platform-specific function with higher accuracy if necessary and + /// available. + /// + /// During initialization CPU execution timing jitter is measured a few + /// hundred times. If this does not pass basic quality tests, an error is + /// returned. The test result is cached to make subsequent calls faster. + #[cfg(all(feature = "std", not(target_arch = "wasm32")))] + pub fn new() -> Result { + if cfg!(target_arch = "wasm32") { + return Err(TimerError::NoTimer); + } + let mut state = JitterRng::new_with_timer(platform::get_nstime); + let mut rounds = JITTER_ROUNDS.load(Ordering::Relaxed) as u8; + if rounds == 0 { + // No result yet: run test. + // This allows the timer test to run multiple times; we don't care. + rounds = state.test_timer()?; + JITTER_ROUNDS.store(rounds as usize, Ordering::Relaxed); + info!("JitterRng: using {} rounds per u64 output", rounds); + } + state.set_rounds(rounds); + + // Fill `data` with a non-zero value. + state.gen_entropy(); + Ok(state) + } + + /// Create a new `JitterRng`. + /// A custom timer can be supplied, making it possible to use `JitterRng` in + /// `no_std` environments. + /// + /// The timer must have nanosecond precision. + /// + /// This method is more low-level than `new()`. It is the responsibility of + /// the caller to run [`test_timer`] before using any numbers generated with + /// `JitterRng`, and optionally call [`set_rounds`]. Also it is important to + /// consume at least one `u64` before using the first result to initialize + /// the entropy collection pool. + /// + /// # Example + /// + /// ``` + /// # use rand_jitter::rand_core::{RngCore, Error}; + /// use rand_jitter::JitterRng; + /// + /// # fn try_inner() -> Result<(), Error> { + /// fn get_nstime() -> u64 { + /// use std::time::{SystemTime, UNIX_EPOCH}; + /// + /// let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + /// // The correct way to calculate the current time is + /// // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` + /// // But this is faster, and the difference in terms of entropy is + /// // negligible (log2(10^9) == 29.9). + /// dur.as_secs() << 30 | dur.subsec_nanos() as u64 + /// } + /// + /// let mut rng = JitterRng::new_with_timer(get_nstime); + /// let rounds = rng.test_timer()?; + /// rng.set_rounds(rounds); // optional + /// let _ = rng.next_u64(); + /// + /// // Ready for use + /// let v: u64 = rng.next_u64(); + /// # Ok(()) + /// # } + /// + /// # let _ = try_inner(); + /// ``` + /// + /// [`test_timer`]: JitterRng::test_timer + /// [`set_rounds`]: JitterRng::set_rounds + pub fn new_with_timer(timer: fn() -> u64) -> JitterRng { + JitterRng { + data: 0, + rounds: 64, + timer, + mem_prev_index: 0, + data_half_used: false, + } + } + + /// Configures how many rounds are used to generate each 64-bit value. + /// This must be greater than zero, and has a big impact on performance + /// and output quality. + /// + /// [`new_with_timer`] conservatively uses 64 rounds, but often less rounds + /// can be used. The `test_timer()` function returns the minimum number of + /// rounds required for full strength (platform dependent), so one may use + /// `rng.set_rounds(rng.test_timer()?);` or cache the value. + /// + /// [`new_with_timer`]: JitterRng::new_with_timer + pub fn set_rounds(&mut self, rounds: u8) { + assert!(rounds > 0); + self.rounds = rounds; + } + + // Calculate a random loop count used for the next round of an entropy + // collection, based on bits from a fresh value from the timer. + // + // The timer is folded to produce a number that contains at most `n_bits` + // bits. + // + // Note: A constant should be added to the resulting random loop count to + // prevent loops that run 0 times. + #[inline(never)] + fn random_loop_cnt(&mut self, n_bits: u32) -> u32 { + let mut rounds = 0; + + let mut time = (self.timer)(); + // Mix with the current state of the random number balance the random + // loop counter a bit more. + time ^= self.data; + + // We fold the time value as much as possible to ensure that as many + // bits of the time stamp are included as possible. + let folds = (64 + n_bits - 1) / n_bits; + let mask = (1 << n_bits) - 1; + for _ in 0..folds { + rounds ^= time & mask; + time >>= n_bits; + } + + rounds as u32 + } + + // CPU jitter noise source + // Noise source based on the CPU execution time jitter + // + // This function injects the individual bits of the time value into the + // entropy pool using an LFSR. + // + // The code is deliberately inefficient with respect to the bit shifting. + // This function not only acts as folding operation, but this function's + // execution is used to measure the CPU execution time jitter. Any change to + // the loop in this function implies that careful retesting must be done. + #[inline(never)] + fn lfsr_time(&mut self, time: u64, var_rounds: bool) { + fn lfsr(mut data: u64, time: u64) -> u64{ + for i in 1..65 { + let mut tmp = time << (64 - i); + tmp >>= 64 - 1; + + // Fibonacci LSFR with polynomial of + // x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is + // primitive according to + // http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf + // (the shift values are the polynomial values minus one + // due to counting bits from 0 to 63). As the current + // position is always the LSB, the polynomial only needs + // to shift data in from the left without wrap. + data ^= tmp; + data ^= (data >> 63) & 1; + data ^= (data >> 60) & 1; + data ^= (data >> 55) & 1; + data ^= (data >> 30) & 1; + data ^= (data >> 27) & 1; + data ^= (data >> 22) & 1; + data = data.rotate_left(1); + } + data + } + + // Note: in the reference implementation only the last round effects + // `self.data`, all the other results are ignored. To make sure the + // other rounds are not optimised out, we first run all but the last + // round on a throw-away value instead of the real `self.data`. + let mut lfsr_loop_cnt = 0; + if var_rounds { lfsr_loop_cnt = self.random_loop_cnt(4) }; + + let mut throw_away: u64 = 0; + for _ in 0..lfsr_loop_cnt { + throw_away = lfsr(throw_away, time); + } + black_box(throw_away); + + self.data = lfsr(self.data, time); + } + + // Memory Access noise source + // This is a noise source based on variations in memory access times + // + // This function performs memory accesses which will add to the timing + // variations due to an unknown amount of CPU wait states that need to be + // added when accessing memory. The memory size should be larger than the L1 + // caches as outlined in the documentation and the associated testing. + // + // The L1 cache has a very high bandwidth, albeit its access rate is usually + // slower than accessing CPU registers. Therefore, L1 accesses only add + // minimal variations as the CPU has hardly to wait. Starting with L2, + // significant variations are added because L2 typically does not belong to + // the CPU any more and therefore a wider range of CPU wait states is + // necessary for accesses. L3 and real memory accesses have even a wider + // range of wait states. However, to reliably access either L3 or memory, + // the `self.mem` memory must be quite large which is usually not desirable. + #[inline(never)] + fn memaccess(&mut self, mem: &mut [u8; MEMORY_SIZE], var_rounds: bool) { + let mut acc_loop_cnt = 128; + if var_rounds { acc_loop_cnt += self.random_loop_cnt(4) }; + + let mut index = self.mem_prev_index as usize; + for _ in 0..acc_loop_cnt { + // Addition of memblocksize - 1 to index with wrap around logic to + // ensure that every memory location is hit evenly. + // The modulus also allows the compiler to remove the indexing + // bounds check. + index = (index + MEMORY_BLOCKSIZE - 1) % MEMORY_SIZE; + + // memory access: just add 1 to one byte + // memory access implies read from and write to memory location + mem[index] = mem[index].wrapping_add(1); + } + self.mem_prev_index = index as u16; + } + + // This is the heart of the entropy generation: calculate time deltas and + // use the CPU jitter in the time deltas. The jitter is injected into the + // entropy pool. + // + // Ensure that `ec.prev_time` is primed before using the output of this + // function. This can be done by calling this function and not using its + // result. + fn measure_jitter(&mut self, ec: &mut EcState) -> Option<()> { + // Invoke one noise source before time measurement to add variations + self.memaccess(&mut ec.mem, true); + + // Get time stamp and calculate time delta to previous + // invocation to measure the timing variations + let time = (self.timer)(); + // Note: wrapping_sub combined with a cast to `i64` generates a correct + // delta, even in the unlikely case this is a timer that is not strictly + // monotonic. + let current_delta = time.wrapping_sub(ec.prev_time) as i64 as i32; + ec.prev_time = time; + + // Call the next noise source which also injects the data + self.lfsr_time(current_delta as u64, true); + + // Check whether we have a stuck measurement (i.e. does the last + // measurement holds entropy?). + if ec.stuck(current_delta) { return None }; + + // Rotate the data buffer by a prime number (any odd number would + // do) to ensure that every bit position of the input time stamp + // has an even chance of being merged with a bit position in the + // entropy pool. We do not use one here as the adjacent bits in + // successive time deltas may have some form of dependency. The + // chosen value of 7 implies that the low 7 bits of the next + // time delta value is concatenated with the current time delta. + self.data = self.data.rotate_left(7); + + Some(()) + } + + // Shuffle the pool a bit by mixing some value with a bijective function + // (XOR) into the pool. + // + // The function generates a mixer value that depends on the bits set and + // the location of the set bits in the random number generated by the + // entropy source. Therefore, based on the generated random number, this + // mixer value can have 2^64 different values. That mixer value is + // initialized with the first two SHA-1 constants. After obtaining the + // mixer value, it is XORed into the random number. + // + // The mixer value is not assumed to contain any entropy. But due to the + // XOR operation, it can also not destroy any entropy present in the + // entropy pool. + #[inline(never)] + fn stir_pool(&mut self) { + // This constant is derived from the first two 32 bit initialization + // vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 + // The order does not really matter as we do not rely on the specific + // numbers. We just pick the SHA-1 constants as they have a good mix of + // bit set and unset. + const CONSTANT: u64 = 0x67452301efcdab89; + + // The start value of the mixer variable is derived from the third + // and fourth 32 bit initialization vector of SHA-1 as defined in + // FIPS 180-4 section 5.3.1 + let mut mixer = 0x98badcfe10325476; + + // This is a constant time function to prevent leaking timing + // information about the random number. + // The normal code is: + // ``` + // for i in 0..64 { + // if ((self.data >> i) & 1) == 1 { mixer ^= CONSTANT; } + // } + // ``` + // This is a bit fragile, as LLVM really wants to use branches here, and + // we rely on it to not recognise the opportunity. + for i in 0..64 { + let apply = (self.data >> i) & 1; + let mask = !apply.wrapping_sub(1); + mixer ^= CONSTANT & mask; + mixer = mixer.rotate_left(1); + } + + self.data ^= mixer; + } + + fn gen_entropy(&mut self) -> u64 { + trace!("JitterRng: collecting entropy"); + + // Prime `ec.prev_time`, and run the noice sources to make sure the + // first loop round collects the expected entropy. + let mut ec = EcState { + prev_time: (self.timer)(), + last_delta: 0, + last_delta2: 0, + mem: [0; MEMORY_SIZE], + }; + let _ = self.measure_jitter(&mut ec); + + for _ in 0..self.rounds { + // If a stuck measurement is received, repeat measurement + // Note: we do not guard against an infinite loop, that would mean + // the timer suddenly became broken. + while self.measure_jitter(&mut ec).is_none() {} + } + + // Do a single read from `self.mem` to make sure the Memory Access noise + // source is not optimised out. + black_box(ec.mem[0]); + + self.stir_pool(); + self.data + } + + /// Basic quality tests on the timer, by measuring CPU timing jitter a few + /// hundred times. + /// + /// If successful, this will return the estimated number of rounds necessary + /// to collect 64 bits of entropy. Otherwise a [`TimerError`] with the cause + /// of the failure will be returned. + pub fn test_timer(&mut self) -> Result { + debug!("JitterRng: testing timer ..."); + // We could add a check for system capabilities such as `clock_getres` + // or check for `CONFIG_X86_TSC`, but it does not make much sense as the + // following sanity checks verify that we have a high-resolution timer. + + let mut delta_sum = 0; + let mut old_delta = 0; + + let mut time_backwards = 0; + let mut count_mod = 0; + let mut count_stuck = 0; + + let mut ec = EcState { + prev_time: (self.timer)(), + last_delta: 0, + last_delta2: 0, + mem: [0; MEMORY_SIZE], + }; + + // TESTLOOPCOUNT needs some loops to identify edge systems. + // 100 is definitely too little. + const TESTLOOPCOUNT: u64 = 300; + const CLEARCACHE: u64 = 100; + + for i in 0..(CLEARCACHE + TESTLOOPCOUNT) { + // Measure time delta of core entropy collection logic + let time = (self.timer)(); + self.memaccess(&mut ec.mem, true); + self.lfsr_time(time, true); + let time2 = (self.timer)(); + + // Test whether timer works + if time == 0 || time2 == 0 { + return Err(TimerError::NoTimer); + } + let delta = time2.wrapping_sub(time) as i64 as i32; + + // Test whether timer is fine grained enough to provide delta even + // when called shortly after each other -- this implies that we also + // have a high resolution timer + if delta == 0 { + return Err(TimerError::CoarseTimer); + } + + // Up to here we did not modify any variable that will be + // evaluated later, but we already performed some work. Thus we + // already have had an impact on the caches, branch prediction, + // etc. with the goal to clear it to get the worst case + // measurements. + if i < CLEARCACHE { continue; } + + if ec.stuck(delta) { count_stuck += 1; } + + // Test whether we have an increasing timer. + if !(time2 > time) { time_backwards += 1; } + + // Count the number of times the counter increases in steps of 100ns + // or greater. + if (delta % 100) == 0 { count_mod += 1; } + + // Ensure that we have a varying delta timer which is necessary for + // the calculation of entropy -- perform this check only after the + // first loop is executed as we need to prime the old_delta value + delta_sum += (delta - old_delta).abs() as u64; + old_delta = delta; + } + + // Do a single read from `self.mem` to make sure the Memory Access noise + // source is not optimised out. + black_box(ec.mem[0]); + + // We allow the time to run backwards for up to three times. + // This can happen if the clock is being adjusted by NTP operations. + // If such an operation just happens to interfere with our test, it + // should not fail. The value of 3 should cover the NTP case being + // performed during our test run. + if time_backwards > 3 { + return Err(TimerError::NotMonotonic); + } + + // Test that the available amount of entropy per round does not get to + // low. We expect 1 bit of entropy per round as a reasonable minimum + // (although less is possible, it means the collector loop has to run + // much more often). + // `assert!(delta_average >= log2(1))` + // `assert!(delta_sum / TESTLOOPCOUNT >= 1)` + // `assert!(delta_sum >= TESTLOOPCOUNT)` + if delta_sum < TESTLOOPCOUNT { + return Err(TimerError::TinyVariantions); + } + + // Ensure that we have variations in the time stamp below 100 for at + // least 10% of all checks -- on some platforms, the counter increments + // in multiples of 100, but not always + if count_mod > (TESTLOOPCOUNT * 9 / 10) { + return Err(TimerError::CoarseTimer); + } + + // If we have more than 90% stuck results, then this Jitter RNG is + // likely to not work well. + if count_stuck > (TESTLOOPCOUNT * 9 / 10) { + return Err(TimerError::TooManyStuck); + } + + // Estimate the number of `measure_jitter` rounds necessary for 64 bits + // of entropy. + // + // We don't try very hard to come up with a good estimate of the + // available bits of entropy per round here for two reasons: + // 1. Simple estimates of the available bits (like Shannon entropy) are + // too optimistic. + // 2. Unless we want to waste a lot of time during intialization, there + // only a small number of samples are available. + // + // Therefore we use a very simple and conservative estimate: + // `let bits_of_entropy = log2(delta_average) / 2`. + // + // The number of rounds `measure_jitter` should run to collect 64 bits + // of entropy is `64 / bits_of_entropy`. + let delta_average = delta_sum / TESTLOOPCOUNT; + + if delta_average >= 16 { + let log2 = 64 - delta_average.leading_zeros(); + // Do something similar to roundup(64/(log2/2)): + Ok( ((64u32 * 2 + log2 - 1) / log2) as u8) + } else { + // For values < 16 the rounding error becomes too large, use a + // lookup table. + // Values 0 and 1 are invalid, and filtered out by the + // `delta_sum < TESTLOOPCOUNT` test above. + let log2_lookup = [0, 0, 128, 81, 64, 56, 50, 46, + 43, 41, 39, 38, 36, 35, 34, 33]; + Ok(log2_lookup[delta_average as usize]) + } + } + + /// Statistical test: return the timer delta of one normal run of the + /// `JitterRng` entropy collector. + /// + /// Setting `var_rounds` to `true` will execute the memory access and the + /// CPU jitter noice sources a variable amount of times (just like a real + /// `JitterRng` round). + /// + /// Setting `var_rounds` to `false` will execute the noice sources the + /// minimal number of times. This can be used to measure the minimum amount + /// of entropy one round of the entropy collector can collect in the worst + /// case. + /// + /// See this crate's README on how to use `timer_stats` to test the quality + /// of `JitterRng`. + pub fn timer_stats(&mut self, var_rounds: bool) -> i64 { + let mut mem = [0; MEMORY_SIZE]; + + let time = (self.timer)(); + self.memaccess(&mut mem, var_rounds); + self.lfsr_time(time, var_rounds); + let time2 = (self.timer)(); + time2.wrapping_sub(time) as i64 + } +} + +// A function that is opaque to the optimizer to assist in avoiding dead-code +// elimination. Taken from `bencher`. +fn black_box(dummy: T) -> T { + unsafe { + let ret = ptr::read_volatile(&dummy); + mem::forget(dummy); + ret + } +} + +impl RngCore for JitterRng { + fn next_u32(&mut self) -> u32 { + // We want to use both parts of the generated entropy + if self.data_half_used { + self.data_half_used = false; + (self.data >> 32) as u32 + } else { + self.data = self.next_u64(); + self.data_half_used = true; + self.data as u32 + } + } + + fn next_u64(&mut self) -> u64 { + self.data_half_used = false; + self.gen_entropy() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + // Fill using `next_u32`. This is faster for filling small slices (four + // bytes or less), while the overhead is negligible. + // + // This is done especially for wrappers that implement `next_u32` + // themselves via `fill_bytes`. + impls::fill_bytes_via_next(self, dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl CryptoRng for JitterRng {} + diff --git a/bash-5.1/vendor/rand_jitter/src/platform.rs b/bash-5.1/vendor/rand_jitter/src/platform.rs new file mode 100644 index 0000000..8e3d0fb --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/src/platform.rs @@ -0,0 +1,44 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2015 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))] +pub fn get_nstime() -> u64 { + use std::time::{SystemTime, UNIX_EPOCH}; + + let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + // The correct way to calculate the current time is + // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` + // But this is faster, and the difference in terms of entropy is + // negligible (log2(10^9) == 29.9). + dur.as_secs() << 30 | dur.subsec_nanos() as u64 +} + +#[cfg(any(target_os = "macos", target_os = "ios"))] +pub fn get_nstime() -> u64 { + use libc; + + // On Mac OS and iOS std::time::SystemTime only has 1000ns resolution. + // We use `mach_absolute_time` instead. This provides a CPU dependent + // unit, to get real nanoseconds the result should by multiplied by + // numer/denom from `mach_timebase_info`. + // But we are not interested in the exact nanoseconds, just entropy. So + // we use the raw result. + unsafe { libc::mach_absolute_time() } +} + +#[cfg(target_os = "windows")] +pub fn get_nstime() -> u64 { + use winapi; + + unsafe { + let mut t = super::mem::zeroed(); + winapi::um::profileapi::QueryPerformanceCounter(&mut t); + *t.QuadPart() as u64 + } +} diff --git a/bash-5.1/vendor/rand_jitter/tests/mod.rs b/bash-5.1/vendor/rand_jitter/tests/mod.rs new file mode 100644 index 0000000..6820c20 --- /dev/null +++ b/bash-5.1/vendor/rand_jitter/tests/mod.rs @@ -0,0 +1,31 @@ +extern crate rand_jitter; +extern crate rand_core; + +use rand_jitter::JitterRng; +#[cfg(feature = "std")] +use rand_core::RngCore; + +#[cfg(feature = "std")] +#[test] +fn test_jitter_init() { + // Because this is a debug build, measurements here are not representive + // of the final release build. + // Don't fail this test if initializing `JitterRng` fails because of a + // bad timer (the timer from the standard library may not have enough + // accuracy on all platforms). + match JitterRng::new() { + Ok(ref mut rng) => { + // false positives are possible, but extremely unlikely + assert!(rng.next_u32() | rng.next_u32() != 0); + }, + Err(_) => {}, + } +} + +#[test] +fn test_jitter_bad_timer() { + fn bad_timer() -> u64 { 0 } + let mut rng = JitterRng::new_with_timer(bad_timer); + assert!(rng.test_timer().is_err()); +} + diff --git a/bash-5.1/vendor/rand_os/.cargo-checksum.json b/bash-5.1/vendor/rand_os/.cargo-checksum.json new file mode 100644 index 0000000..6adb38d --- /dev/null +++ b/bash-5.1/vendor/rand_os/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"b109ac9f2501be2151402585c5278ba9db30d1b880139f0f67aadcd7a9f85506","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"cb81ac6d2ae3ccec84cb897d1c2c4fe53986065424b46fea3ca4e15bca47db05","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"91ccce04b8ea75d26b78f155b578b92be283b2e740d94192ade9eaa3d59c8c27","src/cloudabi.rs":"4f9f9991a1ef7dc330e81ee5208fcc23ad6acc2c73c257b019a3aa488f3a1291","src/dragonfly_haiku_emscripten.rs":"8e693952f38b2576ce7c454cc51d0209917ec40f2a3224ff0f138f798d2c82b3","src/dummy_log.rs":"4e26589c18de568b7da7f0ccc9b77bb430961739a6510c2b043a43dee300c6fa","src/freebsd.rs":"6b1e0a3735d798d8297a9426721e01672424cc289707dae86e336a207cd43436","src/fuchsia.rs":"61159ae3fa469a40214b7ad2f9b0445ed952944c0d5738cd3b7c045eb3e5034a","src/lib.rs":"7d5bd0b5565f7dff4dc352608ab2fb95737dba9b5576fe70b57dcd90e1f11411","src/linux_android.rs":"24b113ef388a2b734ac7a47e045527edac4fe5f29e5ca7948c9a6edf3f69a111","src/macos.rs":"17ccfd5a69068db0580480f680398e20d9ed5219abd726c90e5d9db509539608","src/netbsd.rs":"1b00923bd48673e709cc3f4efd47111093d5bfb86643c8647dd30aeaf5aa6fce","src/openbsd_bitrig.rs":"b9601aa0c6cc0129913341adba838aa0fadd698563eca7f0b046e31c97f0ac92","src/random_device.rs":"bc9cf2470619a90bb8444a632a873e431f801cc3230977851e20d54d86093321","src/redox.rs":"c3fd6f418f085d3b5ffaa6ff4540380cf437cbd65c8b87f89c1dbe16222539e4","src/sgx.rs":"140cf6529ebbf28a19c112e6f325ecd9d84427cc962895795e427cb5b1fa8500","src/solarish.rs":"2c39d2b28a4b9568a378b78b2021bf633fef505d9c5fed2e0a50e90ed9711359","src/wasm32_bindgen.rs":"befe5b8a90ed23c2b3adf40281651966a5ee15ae520101704b68890ec4fb4529","src/wasm32_stdweb.rs":"8684b8ce392941c9d7864d45f82e5a4577fc63b0f0bb709fa627f8b9c9e154a6","src/windows.rs":"d72d555013440aeffe764d961a0a095f8a11417d28a13c2a8882abce2dc000f0","tests/mod.rs":"b8a6caeb5aafd13de775488168b0b46592336568ded37be713e422f724f6f086"},"package":"7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_os/CHANGELOG.md b/bash-5.1/vendor/rand_os/CHANGELOG.md new file mode 100644 index 0000000..1ce36fc --- /dev/null +++ b/bash-5.1/vendor/rand_os/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [0.1.3] - 2019-03-05 +### Changes +- Fix support for Illumos (#730) +- Fix deprecation warnings from atomic init (#739) + +## [0.1.2] - 2019-01-28 +### Changes +- Fuchsia: Replaced fuchsia-zircon with fuchsia-cprng + +## [0.1.1] - 2019-01-08 +### Additions +- Add support for x86_64-fortanix-unknown-sgx target (#670) + +## [0.1.0] - 2019-01-04 +Initial release. diff --git a/bash-5.1/vendor/rand_os/COPYRIGHT b/bash-5.1/vendor/rand_os/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_os/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_os/Cargo.toml b/bash-5.1/vendor/rand_os/Cargo.toml new file mode 100644 index 0000000..d0f1dfe --- /dev/null +++ b/bash-5.1/vendor/rand_os/Cargo.toml @@ -0,0 +1,53 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_os" +version = "0.1.3" +authors = ["The Rand Project Developers"] +description = "OS backed Random Number Generator" +homepage = "https://crates.io/crates/rand_os" +documentation = "https://docs.rs/rand_os" +readme = "README.md" +keywords = ["random", "rng", "os"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.log] +version = "0.4" +optional = true + +[dependencies.rand_core] +version = "0.4" +features = ["std"] +[target."cfg(target_env = \"sgx\")".dependencies.rdrand] +version = "0.4.0" +[target."cfg(target_os = \"cloudabi\")".dependencies.cloudabi] +version = "0.0.3" +[target."cfg(target_os = \"fuchsia\")".dependencies.fuchsia-cprng] +version = "0.1.0" +[target."cfg(unix)".dependencies.libc] +version = "0.2" +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["minwindef", "ntsecapi", "winnt"] +[target.wasm32-unknown-unknown.dependencies.stdweb] +version = "0.4" +optional = true + +[target.wasm32-unknown-unknown.dependencies.wasm-bindgen] +version = "0.2.12" +optional = true +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_os/LICENSE-APACHE b/bash-5.1/vendor/rand_os/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_os/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_os/LICENSE-MIT b/bash-5.1/vendor/rand_os/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_os/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_os/README.md b/bash-5.1/vendor/rand_os/README.md new file mode 100644 index 0000000..4f48b63 --- /dev/null +++ b/bash-5.1/vendor/rand_os/README.md @@ -0,0 +1,33 @@ +# rand_os + +[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_os.svg)](https://crates.io/crates/rand_os) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_os) +[![API](https://docs.rs/rand_os/badge.svg)](https://docs.rs/rand_os) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +A random number generator that retrieves randomness straight from the +operating system. + +This crate depends on [rand_core](https://crates.io/crates/rand_core) and is +part of the [Rand project](https://github.com/rust-random/rand). + +This crate aims to support all of Rust's `std` platforms with a system-provided +entropy source. Unlike other Rand crates, this crate does not support `no_std` +(handling this gracefully is a current discussion topic). + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_os) +- [API documentation (docs.rs)](https://docs.rs/rand_os) +- [Changelog](CHANGELOG.md) + +## License + +`rand_os` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_os/src/cloudabi.rs b/bash-5.1/vendor/rand_os/src/cloudabi.rs new file mode 100644 index 0000000..8b96a2b --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/cloudabi.rs @@ -0,0 +1,39 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for CloudABI + +extern crate cloudabi; + +use std::io; +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; + +#[derive(Clone, Debug)] +pub struct OsRng; + +impl OsRngImpl for OsRng { + fn new() -> Result { Ok(OsRng) } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + let errno = unsafe { cloudabi::random_get(dest) }; + if errno == cloudabi::errno::SUCCESS { + Ok(()) + } else { + // Cloudlibc provides its own `strerror` implementation so we + // can use `from_raw_os_error` here. + Err(Error::with_cause( + ErrorKind::Unavailable, + "random_get() system call failed", + io::Error::from_raw_os_error(errno as i32), + )) + } + } + + fn method_str(&self) -> &'static str { "cloudabi::random_get" } +} diff --git a/bash-5.1/vendor/rand_os/src/dragonfly_haiku_emscripten.rs b/bash-5.1/vendor/rand_os/src/dragonfly_haiku_emscripten.rs new file mode 100644 index 0000000..6132d7a --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/dragonfly_haiku_emscripten.rs @@ -0,0 +1,39 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for DragonFly / Haiku / Emscripten + +use rand_core::Error; +use super::random_device; +use super::OsRngImpl; +use std::fs::File; + +#[derive(Clone, Debug)] +pub struct OsRng(); + +impl OsRngImpl for OsRng { + fn new() -> Result { + random_device::open("/dev/random", &|p| File::open(p))?; + Ok(OsRng()) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + random_device::read(dest) + } + + #[cfg(target_os = "emscripten")] + fn max_chunk_size(&self) -> usize { + // `Crypto.getRandomValues` documents `dest` should be at most 65536 + // bytes. `crypto.randomBytes` documents: "To minimize threadpool + // task length variation, partition large randomBytes requests when + // doing so as part of fulfilling a client request. + 65536 + } + + fn method_str(&self) -> &'static str { "/dev/random" } +} diff --git a/bash-5.1/vendor/rand_os/src/dummy_log.rs b/bash-5.1/vendor/rand_os/src/dummy_log.rs new file mode 100644 index 0000000..ccfe4ba --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/dummy_log.rs @@ -0,0 +1,10 @@ +#[allow(unused)] +macro_rules! trace { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! debug { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! info { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! warn { ($($x:tt)*) => () } +#[allow(unused)] +macro_rules! error { ($($x:tt)*) => () } diff --git a/bash-5.1/vendor/rand_os/src/freebsd.rs b/bash-5.1/vendor/rand_os/src/freebsd.rs new file mode 100644 index 0000000..6b8e672 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/freebsd.rs @@ -0,0 +1,45 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for FreeBSD + +extern crate libc; + +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; + +use std::ptr; +use std::io; + +#[derive(Clone, Debug)] +pub struct OsRng; + +impl OsRngImpl for OsRng { + fn new() -> Result { Ok(OsRng) } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + let mib = [libc::CTL_KERN, libc::KERN_ARND]; + let mut len = dest.len(); + let ret = unsafe { + libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint, + dest.as_mut_ptr() as *mut _, &mut len, + ptr::null(), 0) + }; + if ret == -1 || len != dest.len() { + return Err(Error::with_cause( + ErrorKind::Unavailable, + "kern.arandom sysctl failed", + io::Error::last_os_error())); + } + Ok(()) + } + + fn max_chunk_size(&self) -> usize { 256 } + + fn method_str(&self) -> &'static str { "kern.arandom" } +} diff --git a/bash-5.1/vendor/rand_os/src/fuchsia.rs b/bash-5.1/vendor/rand_os/src/fuchsia.rs new file mode 100644 index 0000000..ada3677 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/fuchsia.rs @@ -0,0 +1,28 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for Fuchsia Zircon + +extern crate fuchsia_cprng; + +use rand_core::Error; +use super::OsRngImpl; + +#[derive(Clone, Debug)] +pub struct OsRng; + +impl OsRngImpl for OsRng { + fn new() -> Result { Ok(OsRng) } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + fuchsia_cprng::cprng_draw(dest); + Ok(()) + } + + fn method_str(&self) -> &'static str { "cprng_draw" } +} diff --git a/bash-5.1/vendor/rand_os/src/lib.rs b/bash-5.1/vendor/rand_os/src/lib.rs new file mode 100644 index 0000000..1b9cb25 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/lib.rs @@ -0,0 +1,440 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2013-2015 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Interface to the random number generator of the operating system. +//! +//! [`OsRng`] is the preferred external source of entropy for most applications. +//! Commonly it is used to initialize a user-space RNG, which can then be used +//! to generate random values with much less overhead than `OsRng`. +//! +//! You may prefer to use [`EntropyRng`] instead of `OsRng`. It is unlikely, but +//! not entirely theoretical, for `OsRng` to fail. In such cases [`EntropyRng`] +//! falls back on a good alternative entropy source. +//! +//! [`OsRng::new()`] is guaranteed to be very cheap (after the first successful +//! call), and will never consume more than one file handle per process. +//! +//! # Usage example +//! ``` +//! use rand_os::OsRng; +//! use rand_os::rand_core::RngCore; +//! +//! let mut os_rng = OsRng::new().unwrap(); +//! let mut key = [0u8; 16]; +//! os_rng.fill_bytes(&mut key); +//! let random_u64 = os_rng.next_u64(); +//! ``` +//! +//! # Platform sources +//! +//! | OS | interface +//! |------------------|--------------------------------------------------------- +//! | Linux, Android | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after reading from `/dev/random` once +//! | Windows | [`RtlGenRandom`][3] +//! | macOS, iOS | [`SecRandomCopyBytes`][4] +//! | FreeBSD | [`kern.arandom`][5] +//! | OpenBSD, Bitrig | [`getentropy`][6] +//! | NetBSD | [`/dev/urandom`][7] after reading from `/dev/random` once +//! | Dragonfly BSD | [`/dev/random`][8] +//! | Solaris, illumos | [`getrandom`][9] system call if available, otherwise [`/dev/random`][10] +//! | Fuchsia OS | [`cprng_draw`][11] +//! | Redox | [`rand:`][12] +//! | CloudABI | [`random_get`][13] +//! | Haiku | `/dev/random` (identical to `/dev/urandom`) +//! | Web browsers | [`Crypto.getRandomValues`][14] (see [Support for WebAssembly and ams.js][14]) +//! | Node.js | [`crypto.randomBytes`][15] (see [Support for WebAssembly and ams.js][16]) +//! +//! Rand doesn't have a blanket implementation for all Unix-like operating +//! systems that reads from `/dev/urandom`. This ensures all supported operating +//! systems are using the recommended interface and respect maximum buffer +//! sizes. +//! +//! ## Support for WebAssembly and ams.js +//! +//! The three Emscripten targets `asmjs-unknown-emscripten`, +//! `wasm32-unknown-emscripten` and `wasm32-experimental-emscripten` use +//! Emscripten's emulation of `/dev/random` on web browsers and Node.js. +//! +//! The bare WASM target `wasm32-unknown-unknown` tries to call the javascript +//! methods directly, using either `stdweb` or `wasm-bindgen` depending on what +//! features are activated for this crate. Note that if both features are +//! enabled `wasm-bindgen` will be used. +//! +//! ## Early boot +//! +//! It is possible that early in the boot process the OS hasn't had enough time +//! yet to collect entropy to securely seed its RNG, especially on virtual +//! machines. +//! +//! Some operating systems always block the thread until the RNG is securely +//! seeded. This can take anywhere from a few seconds to more than a minute. +//! Others make a best effort to use a seed from before the shutdown and don't +//! document much. +//! +//! A few, Linux, NetBSD and Solaris, offer a choice between blocking, and +//! getting an error. With `try_fill_bytes` we choose to get the error +//! ([`ErrorKind::NotReady`]), while the other methods use a blocking interface. +//! +//! On Linux (when the `genrandom` system call is not available) and on NetBSD +//! reading from `/dev/urandom` never blocks, even when the OS hasn't collected +//! enough entropy yet. As a countermeasure we try to do a single read from +//! `/dev/random` until we know the OS RNG is initialized (and store this in a +//! global static). +//! +//! # Panics and error handling +//! +//! We cannot guarantee that `OsRng` will fail, but if it does, it will likely +//! be either when `OsRng::new()` is first called or when data is first read. +//! If you wish to catch errors early, then test reading of at least one byte +//! from `OsRng` via [`try_fill_bytes`]. If this succeeds, it is extremely +//! unlikely that any further errors will occur. +//! +//! Only [`try_fill_bytes`] is able to report the cause of an error; the other +//! [`RngCore`] methods may (depending on the error kind) retry several times, +//! but must eventually panic if the error persists. +//! +//! [`EntropyRng`]: ../rand/rngs/struct.EntropyRng.html +//! [`try_fill_bytes`]: RngCore::try_fill_bytes +//! [`ErrorKind::NotReady`]: rand_core::ErrorKind +//! +//! [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html +//! [2]: http://man7.org/linux/man-pages/man4/urandom.4.html +//! [3]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx +//! [4]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc +//! [5]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4 +//! [6]: https://man.openbsd.org/getentropy.2 +//! [7]: http://netbsd.gw.com/cgi-bin/man-cgi?random+4+NetBSD-current +//! [8]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4 +//! [9]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html +//! [10]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html +//! [11]: https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/cprng_draw.md +//! [12]: https://github.com/redox-os/randd/blob/master/src/main.rs +//! [13]: https://github.com/NuxiNL/cloudabi/blob/v0.20/cloudabi.txt#L1826 +//! [14]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues +//! [15]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback +//! [16]: #support-for-webassembly-and-amsjs +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +#![cfg_attr(feature = "stdweb", recursion_limit="128")] + +pub extern crate rand_core; +#[cfg(feature = "log")] +#[macro_use] extern crate log; + +// We have to do it here because we load macros +#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), + feature = "wasm-bindgen"))] +extern crate wasm_bindgen; +#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), + not(feature = "wasm-bindgen"), + feature = "stdweb"))] +#[macro_use] extern crate stdweb; + +#[cfg(target_env = "sgx")] +extern crate rdrand; + +#[cfg(not(feature = "log"))] +#[macro_use] +mod dummy_log; + +use std::fmt; +use rand_core::{CryptoRng, RngCore, Error, impls}; + +/// A random number generator that retrieves randomness straight from the +/// operating system. +#[derive(Clone)] +pub struct OsRng(imp::OsRng); + +impl fmt::Debug for OsRng { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +impl OsRng { + /// Create a new `OsRng`. + pub fn new() -> Result { + imp::OsRng::new().map(OsRng) + } +} + +impl CryptoRng for OsRng {} + +impl RngCore for OsRng { + fn next_u32(&mut self) -> u32 { + impls::next_u32_via_fill(self) + } + + fn next_u64(&mut self) -> u64 { + impls::next_u64_via_fill(self) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + use std::{time, thread}; + + // We cannot return Err(..), so we try to handle before panicking. + const MAX_RETRY_PERIOD: u32 = 10; // max 10s + const WAIT_DUR_MS: u32 = 100; // retry every 100ms + let wait_dur = time::Duration::from_millis(WAIT_DUR_MS as u64); + const RETRY_LIMIT: u32 = (MAX_RETRY_PERIOD * 1000) / WAIT_DUR_MS; + const TRANSIENT_RETRIES: u32 = 8; + let mut err_count = 0; + let mut error_logged = false; + + // Maybe block until the OS RNG is initialized + let mut read = 0; + if let Ok(n) = self.0.test_initialized(dest, true) { read = n }; + let dest = &mut dest[read..]; + + loop { + if let Err(e) = self.try_fill_bytes(dest) { + if err_count >= RETRY_LIMIT { + error!("OsRng failed too many times; last error: {}", e); + panic!("OsRng failed too many times; last error: {}", e); + } + + if e.kind.should_wait() { + if !error_logged { + warn!("OsRng failed; waiting up to {}s and retrying. Error: {}", + MAX_RETRY_PERIOD, e); + error_logged = true; + } + err_count += 1; + thread::sleep(wait_dur); + continue; + } else if e.kind.should_retry() { + if !error_logged { + warn!("OsRng failed; retrying up to {} times. Error: {}", + TRANSIENT_RETRIES, e); + error_logged = true; + } + err_count += (RETRY_LIMIT + TRANSIENT_RETRIES - 1) + / TRANSIENT_RETRIES; // round up + continue; + } else { + error!("OsRng failed: {}", e); + panic!("OsRng fatal error: {}", e); + } + } + + break; + } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + // Some systems do not support reading 0 random bytes. + // (And why waste a system call?) + if dest.len() == 0 { return Ok(()); } + + let read = self.0.test_initialized(dest, false)?; + let dest = &mut dest[read..]; + + let max = self.0.max_chunk_size(); + if dest.len() <= max { + trace!("OsRng: reading {} bytes via {}", + dest.len(), self.0.method_str()); + } else { + trace!("OsRng: reading {} bytes via {} in {} chunks of {} bytes", + dest.len(), self.0.method_str(), (dest.len() + max) / max, max); + } + for slice in dest.chunks_mut(max) { + self.0.fill_chunk(slice)?; + } + Ok(()) + } +} + +trait OsRngImpl where Self: Sized { + // Create a new `OsRng` platform interface. + fn new() -> Result; + + // Fill a chunk with random bytes. + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error>; + + // Test whether the OS RNG is initialized. This method may not be possible + // to support cheaply (or at all) on all operating systems. + // + // If `blocking` is set, this will cause the OS the block execution until + // its RNG is initialized. + // + // Random values that are read while this are stored in `dest`, the amount + // of read bytes is returned. + fn test_initialized(&mut self, _dest: &mut [u8], _blocking: bool) + -> Result { Ok(0) } + + // Maximum chunk size supported. + fn max_chunk_size(&self) -> usize { ::std::usize::MAX } + + // Name of the OS interface (used for logging). + fn method_str(&self) -> &'static str; +} + +#[cfg(any(target_os = "linux", target_os = "android", + target_os = "netbsd", target_os = "dragonfly", + target_os = "solaris", target_os = "redox", + target_os = "haiku", target_os = "emscripten", + target_os = "illumos"))] +mod random_device; + +macro_rules! mod_use { + ($cond:meta, $module:ident) => { + #[$cond] + mod $module; + #[$cond] + use $module as imp; + } +} + +mod_use!(cfg(target_os = "android"), linux_android); +mod_use!(cfg(target_os = "bitrig"), openbsd_bitrig); +mod_use!(cfg(target_os = "cloudabi"), cloudabi); +mod_use!(cfg(target_os = "dragonfly"), dragonfly_haiku_emscripten); +mod_use!(cfg(target_os = "emscripten"), dragonfly_haiku_emscripten); +mod_use!(cfg(target_os = "freebsd"), freebsd); +mod_use!(cfg(target_os = "fuchsia"), fuchsia); +mod_use!(cfg(target_os = "haiku"), dragonfly_haiku_emscripten); +mod_use!(cfg(target_os = "ios"), macos); +mod_use!(cfg(target_os = "linux"), linux_android); +mod_use!(cfg(target_os = "macos"), macos); +mod_use!(cfg(target_os = "netbsd"), netbsd); +mod_use!(cfg(target_os = "openbsd"), openbsd_bitrig); +mod_use!(cfg(target_os = "redox"), redox); +mod_use!(cfg(any(target_os = "solaris", target_os = "illumos")), solarish); +mod_use!(cfg(windows), windows); +mod_use!(cfg(target_env = "sgx"), sgx); + +mod_use!( + cfg(all( + target_arch = "wasm32", + not(target_os = "emscripten"), + feature = "wasm-bindgen" + )), + wasm32_bindgen +); + +mod_use!( + cfg(all( + target_arch = "wasm32", + not(target_os = "emscripten"), + not(feature = "wasm-bindgen"), + feature = "stdweb", + )), + wasm32_stdweb +); + +/// Per #678 we use run-time failure where WASM bindings are missing +#[cfg(all( + target_arch = "wasm32", + not(target_os = "emscripten"), + not(feature = "wasm-bindgen"), + not(feature = "stdweb"), +))] +mod imp { + use rand_core::{Error, ErrorKind}; + use super::OsRngImpl; + + #[derive(Clone, Debug)] + pub struct OsRng; + + impl OsRngImpl for OsRng { + fn new() -> Result { + Err(Error::new(ErrorKind::Unavailable, + "OsRng: support for wasm32 requires emscripten, stdweb or wasm-bindgen")) + } + + fn fill_chunk(&mut self, _dest: &mut [u8]) -> Result<(), Error> { + unimplemented!() + } + + fn method_str(&self) -> &'static str { unimplemented!() } + } +} + +#[cfg(not(any( + target_os = "android", + target_os = "bitrig", + target_os = "cloudabi", + target_os = "dragonfly", + target_os = "emscripten", + target_os = "freebsd", + target_os = "fuchsia", + target_os = "haiku", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd", + target_os = "redox", + target_os = "solaris", + target_os = "illumos", + windows, + target_arch = "wasm32", + target_env = "sgx" +)))] +compile_error!("OS RNG support is not available for this platform"); + +// Due to rustwasm/wasm-bindgen#201 this can't be defined in the inner os +// modules, so hack around it for now and place it at the root. +#[cfg(all(feature = "wasm-bindgen", target_arch = "wasm32"))] +#[doc(hidden)] +#[allow(missing_debug_implementations)] +pub mod __wbg_shims { + + // `extern { type Foo; }` isn't supported on 1.22 syntactically, so use a + // macro to work around that. + macro_rules! rust_122_compat { + ($($t:tt)*) => ($($t)*) + } + + rust_122_compat! { + extern crate wasm_bindgen; + + pub use wasm_bindgen::prelude::*; + + #[wasm_bindgen] + extern "C" { + pub type Function; + #[wasm_bindgen(constructor)] + pub fn new(s: &str) -> Function; + #[wasm_bindgen(method)] + pub fn call(this: &Function, self_: &JsValue) -> JsValue; + + pub type This; + #[wasm_bindgen(method, getter, structural, js_name = self)] + pub fn self_(me: &This) -> JsValue; + #[wasm_bindgen(method, getter, structural)] + pub fn crypto(me: &This) -> JsValue; + + #[derive(Clone, Debug)] + pub type BrowserCrypto; + + // TODO: these `structural` annotations here ideally wouldn't be here to + // avoid a JS shim, but for now with feature detection they're + // unavoidable. + #[wasm_bindgen(method, js_name = getRandomValues, structural, getter)] + pub fn get_random_values_fn(me: &BrowserCrypto) -> JsValue; + #[wasm_bindgen(method, js_name = getRandomValues, structural)] + pub fn get_random_values(me: &BrowserCrypto, buf: &mut [u8]); + + #[wasm_bindgen(js_name = require)] + pub fn node_require(s: &str) -> NodeCrypto; + + #[derive(Clone, Debug)] + pub type NodeCrypto; + + #[wasm_bindgen(method, js_name = randomFillSync, structural)] + pub fn random_fill_sync(me: &NodeCrypto, buf: &mut [u8]); + } + } +} diff --git a/bash-5.1/vendor/rand_os/src/linux_android.rs b/bash-5.1/vendor/rand_os/src/linux_android.rs new file mode 100644 index 0000000..255c220 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/linux_android.rs @@ -0,0 +1,186 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for Linux / Android + +extern crate libc; + +use rand_core::{Error, ErrorKind}; +use super::random_device; +use super::OsRngImpl; + +use std::io; +use std::io::Read; +use std::fs::{File, OpenOptions}; +use std::os::unix::fs::OpenOptionsExt; +use std::sync::atomic::{AtomicBool, Ordering}; +#[allow(deprecated)] // Required for compatibility with Rust < 1.24. +use std::sync::atomic::ATOMIC_BOOL_INIT; +use std::sync::{Once, ONCE_INIT}; + +#[derive(Clone, Debug)] +pub struct OsRng { + method: OsRngMethod, + initialized: bool, +} + +#[derive(Clone, Debug)] +enum OsRngMethod { + GetRandom, + RandomDevice, +} + +impl OsRngImpl for OsRng { + fn new() -> Result { + if is_getrandom_available() { + return Ok(OsRng { method: OsRngMethod::GetRandom, + initialized: false }); + } + random_device::open("/dev/urandom", &|p| File::open(p))?; + Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false }) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + match self.method { + OsRngMethod::GetRandom => getrandom_try_fill(dest, false), + OsRngMethod::RandomDevice => random_device::read(dest), + } + } + + fn test_initialized(&mut self, dest: &mut [u8], blocking: bool) + -> Result + { + #[allow(deprecated)] + static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; + if !self.initialized { + self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); + } + if self.initialized { return Ok(0); } + + let result = match self.method { + OsRngMethod::GetRandom => { + getrandom_try_fill(dest, blocking)?; + Ok(dest.len()) + } + OsRngMethod::RandomDevice => { + info!("OsRng: testing random device /dev/random"); + let mut file = OpenOptions::new() + .read(true) + .custom_flags(if blocking { 0 } else { libc::O_NONBLOCK }) + .open("/dev/random") + .map_err(random_device::map_err)?; + file.read(&mut dest[..1]).map_err(random_device::map_err)?; + Ok(1) + } + }; + OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); + self.initialized = true; + result + } + + fn method_str(&self) -> &'static str { + match self.method { + OsRngMethod::GetRandom => "getrandom", + OsRngMethod::RandomDevice => "/dev/urandom", + } + } +} + +#[cfg(target_arch = "x86_64")] +const NR_GETRANDOM: libc::c_long = 318; +#[cfg(target_arch = "x86")] +const NR_GETRANDOM: libc::c_long = 355; +#[cfg(target_arch = "arm")] +const NR_GETRANDOM: libc::c_long = 384; +#[cfg(target_arch = "aarch64")] +const NR_GETRANDOM: libc::c_long = 278; + #[cfg(target_arch = "s390x")] +const NR_GETRANDOM: libc::c_long = 349; +#[cfg(target_arch = "powerpc")] +const NR_GETRANDOM: libc::c_long = 359; +#[cfg(target_arch = "powerpc64")] +const NR_GETRANDOM: libc::c_long = 359; +#[cfg(target_arch = "mips")] // old ABI +const NR_GETRANDOM: libc::c_long = 4353; +#[cfg(target_arch = "mips64")] +const NR_GETRANDOM: libc::c_long = 5313; +#[cfg(target_arch = "sparc")] +const NR_GETRANDOM: libc::c_long = 347; +#[cfg(target_arch = "sparc64")] +const NR_GETRANDOM: libc::c_long = 347; +#[cfg(not(any(target_arch = "x86_64", target_arch = "x86", + target_arch = "arm", target_arch = "aarch64", + target_arch = "s390x", target_arch = "powerpc", + target_arch = "powerpc64", target_arch = "mips", + target_arch = "mips64", target_arch = "sparc", + target_arch = "sparc64")))] +const NR_GETRANDOM: libc::c_long = 0; + +fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long { + const GRND_NONBLOCK: libc::c_uint = 0x0001; + + if NR_GETRANDOM == 0 { return -1 }; + + unsafe { + libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), + if blocking { 0 } else { GRND_NONBLOCK }) + } +} + +fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> { + let mut read = 0; + while read < dest.len() { + let result = getrandom(&mut dest[read..], blocking); + if result == -1 { + let err = io::Error::last_os_error(); + let kind = err.kind(); + if kind == io::ErrorKind::Interrupted { + continue; + } else if kind == io::ErrorKind::WouldBlock { + return Err(Error::with_cause( + ErrorKind::NotReady, + "getrandom not ready", + err, + )); + } else { + return Err(Error::with_cause( + ErrorKind::Unavailable, + "unexpected getrandom error", + err, + )); + } + } else { + read += result as usize; + } + } + Ok(()) +} + +fn is_getrandom_available() -> bool { + static CHECKER: Once = ONCE_INIT; + #[allow(deprecated)] + static AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT; + + if NR_GETRANDOM == 0 { return false }; + + CHECKER.call_once(|| { + debug!("OsRng: testing getrandom"); + let mut buf: [u8; 0] = []; + let result = getrandom(&mut buf, false); + let available = if result == -1 { + let err = io::Error::last_os_error().raw_os_error(); + err != Some(libc::ENOSYS) + } else { + true + }; + AVAILABLE.store(available, Ordering::Relaxed); + info!("OsRng: using {}", if available { "getrandom" } else { "/dev/urandom" }); + }); + + AVAILABLE.load(Ordering::Relaxed) +} diff --git a/bash-5.1/vendor/rand_os/src/macos.rs b/bash-5.1/vendor/rand_os/src/macos.rs new file mode 100644 index 0000000..6c67251 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/macos.rs @@ -0,0 +1,53 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for MacOS / iOS + +extern crate libc; + +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; + +use std::io; +use self::libc::{c_int, size_t}; + +#[derive(Clone, Debug)] +pub struct OsRng; + +enum SecRandom {} + +#[allow(non_upper_case_globals)] +const kSecRandomDefault: *const SecRandom = 0 as *const SecRandom; + +#[link(name = "Security", kind = "framework")] +extern { + fn SecRandomCopyBytes(rnd: *const SecRandom, + count: size_t, bytes: *mut u8) -> c_int; +} + +impl OsRngImpl for OsRng { + fn new() -> Result { Ok(OsRng) } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + let ret = unsafe { + SecRandomCopyBytes(kSecRandomDefault, + dest.len() as size_t, + dest.as_mut_ptr()) + }; + if ret == -1 { + Err(Error::with_cause( + ErrorKind::Unavailable, + "couldn't generate random bytes", + io::Error::last_os_error())) + } else { + Ok(()) + } + } + + fn method_str(&self) -> &'static str { "SecRandomCopyBytes" } +} diff --git a/bash-5.1/vendor/rand_os/src/netbsd.rs b/bash-5.1/vendor/rand_os/src/netbsd.rs new file mode 100644 index 0000000..34517bf --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/netbsd.rs @@ -0,0 +1,57 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for NetBSD + +use rand_core::Error; +use super::random_device; +use super::OsRngImpl; + +use std::fs::File; +use std::io::Read; +use std::sync::atomic::{AtomicBool, Ordering}; +#[allow(deprecated)] // Required for compatibility with Rust < 1.24. +use std::sync::atomic::ATOMIC_BOOL_INIT; + +#[derive(Clone, Debug)] +pub struct OsRng { initialized: bool } + +impl OsRngImpl for OsRng { + fn new() -> Result { + random_device::open("/dev/urandom", &|p| File::open(p))?; + Ok(OsRng { initialized: false }) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + random_device::read(dest) + } + + // Read a single byte from `/dev/random` to determine if the OS RNG is + // already seeded. NetBSD always blocks if not yet ready. + fn test_initialized(&mut self, dest: &mut [u8], _blocking: bool) + -> Result + { + #[allow(deprecated)] + static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; + if !self.initialized { + self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); + } + if self.initialized { return Ok(0); } + + info!("OsRng: testing random device /dev/random"); + let mut file = + File::open("/dev/random").map_err(random_device::map_err)?; + file.read(&mut dest[..1]).map_err(random_device::map_err)?; + + OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); + self.initialized = true; + Ok(1) + } + + fn method_str(&self) -> &'static str { "/dev/urandom" } +} diff --git a/bash-5.1/vendor/rand_os/src/openbsd_bitrig.rs b/bash-5.1/vendor/rand_os/src/openbsd_bitrig.rs new file mode 100644 index 0000000..c9b35a6 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/openbsd_bitrig.rs @@ -0,0 +1,40 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for OpenBSD / Bitrig + +extern crate libc; + +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; + +use std::io; + +#[derive(Clone, Debug)] +pub struct OsRng; + +impl OsRngImpl for OsRng { + fn new() -> Result { Ok(OsRng) } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + let ret = unsafe { + libc::getentropy(dest.as_mut_ptr() as *mut libc::c_void, dest.len()) + }; + if ret == -1 { + return Err(Error::with_cause( + ErrorKind::Unavailable, + "getentropy failed", + io::Error::last_os_error())); + } + Ok(()) + } + + fn max_chunk_size(&self) -> usize { 256 } + + fn method_str(&self) -> &'static str { "getentropy" } +} diff --git a/bash-5.1/vendor/rand_os/src/random_device.rs b/bash-5.1/vendor/rand_os/src/random_device.rs new file mode 100644 index 0000000..5da9194 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/random_device.rs @@ -0,0 +1,70 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Helper functions to read from a random device such as `/dev/urandom`. +//! +//! All instances use a single internal file handle, to prevent possible +//! exhaustion of file descriptors. +use rand_core::{Error, ErrorKind}; +use std::fs::File; +use std::io; +use std::io::Read; +use std::sync::{Once, Mutex, ONCE_INIT}; + +// TODO: remove outer Option when `Mutex::new(None)` is a constant expression +static mut READ_RNG_FILE: Option>> = None; +static READ_RNG_ONCE: Once = ONCE_INIT; + +#[allow(unused)] +pub fn open(path: &'static str, open_fn: F) -> Result<(), Error> + where F: Fn(&'static str) -> Result +{ + READ_RNG_ONCE.call_once(|| { + unsafe { READ_RNG_FILE = Some(Mutex::new(None)) } + }); + + // We try opening the file outside the `call_once` fn because we cannot + // clone the error, thus we must retry on failure. + + let mutex = unsafe { READ_RNG_FILE.as_ref().unwrap() }; + let mut guard = mutex.lock().unwrap(); + if (*guard).is_none() { + info!("OsRng: opening random device {}", path); + let file = open_fn(path).map_err(map_err)?; + *guard = Some(file); + }; + Ok(()) +} + +pub fn read(dest: &mut [u8]) -> Result<(), Error> { + // We expect this function only to be used after `random_device::open` + // was succesful. Therefore we can assume that our memory was set with a + // valid object. + let mutex = unsafe { READ_RNG_FILE.as_ref().unwrap() }; + let mut guard = mutex.lock().unwrap(); + let file = (*guard).as_mut().unwrap(); + + // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. + file.read_exact(dest).map_err(|err| { + Error::with_cause(ErrorKind::Unavailable, + "error reading random device", err) + }) + +} + +pub fn map_err(err: io::Error) -> Error { + match err.kind() { + io::ErrorKind::Interrupted => + Error::new(ErrorKind::Transient, "interrupted"), + io::ErrorKind::WouldBlock => + Error::with_cause(ErrorKind::NotReady, + "OS RNG not yet seeded", err), + _ => Error::with_cause(ErrorKind::Unavailable, + "error while opening random device", err) + } +} diff --git a/bash-5.1/vendor/rand_os/src/redox.rs b/bash-5.1/vendor/rand_os/src/redox.rs new file mode 100644 index 0000000..36fae26 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/redox.rs @@ -0,0 +1,30 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for Redox + +use rand_core::Error; +use super::random_device; +use super::OsRngImpl; +use std::fs::File; + +#[derive(Clone, Debug)] +pub struct OsRng(); + +impl OsRngImpl for OsRng { + fn new() -> Result { + random_device::open("rand:", &|p| File::open(p))?; + Ok(OsRng()) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + random_device::read(dest) + } + + fn method_str(&self) -> &'static str { "'rand:'" } +} diff --git a/bash-5.1/vendor/rand_os/src/sgx.rs b/bash-5.1/vendor/rand_os/src/sgx.rs new file mode 100644 index 0000000..43ae0ef --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/sgx.rs @@ -0,0 +1,38 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::OsRngImpl; +use Error; +use rdrand::RdRand; +use rand_core::RngCore; +use std::fmt::{Debug, Formatter, Result as FmtResult}; + +#[derive(Clone)] +pub struct OsRng{ + gen: RdRand +} + +impl OsRngImpl for OsRng { + fn new() -> Result { + let rng = RdRand::new()?; + Ok(OsRng{ gen: rng }) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.gen.try_fill_bytes(dest) + } + + fn method_str(&self) -> &'static str { "RDRAND" } +} + +impl Debug for OsRng { + fn fmt(&self, f: &mut Formatter) -> FmtResult { + f.debug_struct("OsRng") + .finish() + } +} diff --git a/bash-5.1/vendor/rand_os/src/solarish.rs b/bash-5.1/vendor/rand_os/src/solarish.rs new file mode 100644 index 0000000..471768a --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/solarish.rs @@ -0,0 +1,195 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for the Solaris family +//! +//! Read from `/dev/random`, with chunks of limited size (1040 bytes). +//! `/dev/random` uses the Hash_DRBG with SHA512 algorithm from NIST SP 800-90A. +//! `/dev/urandom` uses the FIPS 186-2 algorithm, which is considered less +//! secure. We choose to read from `/dev/random`. +//! +//! Since Solaris 11.3 the `getrandom` syscall is available. To make sure we can +//! compile on both Solaris and on OpenSolaris derivatives, that do not have the +//! function, we do a direct syscall instead of calling a library function. +//! +//! We have no way to differentiate between Solaris, illumos, SmartOS, etc. +extern crate libc; + +use rand_core::{Error, ErrorKind}; +use super::random_device; +use super::OsRngImpl; + +use std::io; +use std::io::Read; +use std::fs::{File, OpenOptions}; +use std::os::unix::fs::OpenOptionsExt; +use std::sync::atomic::{AtomicBool, Ordering, AtomicUsize}; +#[allow(deprecated)] // Required for compatibility with Rust < 1.24. +use std::sync::atomic::ATOMIC_BOOL_INIT; +use std::cmp; +use std::mem; + +#[derive(Clone, Debug)] +pub struct OsRng { + method: OsRngMethod, + initialized: bool, +} + +#[derive(Clone, Debug)] +enum OsRngMethod { + GetRandom, + RandomDevice, +} + +impl OsRngImpl for OsRng { + fn new() -> Result { + if is_getrandom_available() { + return Ok(OsRng { method: OsRngMethod::GetRandom, + initialized: false }); + } + let open = |p| OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(p); + random_device::open("/dev/random", &open)?; + Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false }) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + match self.method { + OsRngMethod::GetRandom => getrandom_try_fill(dest, false), + OsRngMethod::RandomDevice => random_device::read(dest), + } + } + + fn test_initialized(&mut self, dest: &mut [u8], blocking: bool) + -> Result + { + #[allow(deprecated)] + static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; + if !self.initialized { + self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); + } + if self.initialized { return Ok(0); } + + let chunk_len = cmp::min(1024, dest.len()); + let dest = &mut dest[..chunk_len]; + + match self.method { + OsRngMethod::GetRandom => getrandom_try_fill(dest, blocking)?, + OsRngMethod::RandomDevice => { + if blocking { + info!("OsRng: testing random device /dev/random"); + // We already have a non-blocking handle, but now need a + // blocking one. Not much choice except opening it twice + let mut file = File::open("/dev/random") + .map_err(random_device::map_err)?; + file.read(dest).map_err(random_device::map_err)?; + } else { + self.fill_chunk(dest)?; + } + } + }; + OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); + self.initialized = true; + Ok(chunk_len) + } + + fn max_chunk_size(&self) -> usize { + // This is the largest size that's guaranteed to not block across + // all the Solarish platforms, though some may allow for larger + // sizes. + 256 + } + + fn method_str(&self) -> &'static str { + match self.method { + OsRngMethod::GetRandom => "getrandom", + OsRngMethod::RandomDevice => "/dev/random", + } + } +} + +#[cfg(target_os = "illumos")] +type GetRandomFn = unsafe extern fn(*mut u8, libc::size_t, libc::c_uint) + -> libc::ssize_t; +#[cfg(target_os = "solaris")] +type GetRandomFn = unsafe extern fn(*mut u8, libc::size_t, libc::c_uint) + -> libc::c_int; + +// Use dlsym to determine if getrandom(2) is present in libc. On Solarish +// systems, the syscall interface is not stable and can change between +// updates. Even worse, issuing unsupported syscalls will cause the system +// to generate a SIGSYS signal (usually terminating the program). +// Instead the stable APIs are exposed via libc. Cache the result of the +// lookup for future calls. This is loosely modeled after the +// libstd::sys::unix::weak macro which unfortunately is not exported. +fn fetch() -> Option { + static FPTR: AtomicUsize = AtomicUsize::new(1); + + if FPTR.load(Ordering::SeqCst) == 1 { + let name = "getrandom\0"; + let addr = unsafe { + libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize + }; + FPTR.store(addr, Ordering::SeqCst); + } + + let ptr = FPTR.load(Ordering::SeqCst); + unsafe { + mem::transmute::>(ptr) + } +} + +fn getrandom(buf: &mut [u8], blocking: bool) -> libc::ssize_t { + const GRND_NONBLOCK: libc::c_uint = 0x0001; + const GRND_RANDOM: libc::c_uint = 0x0002; + + if let Some(rand) = fetch() { + let flag = if blocking { 0 } else { GRND_NONBLOCK } | GRND_RANDOM; + unsafe { + rand(buf.as_mut_ptr(), buf.len(), flag) as libc::ssize_t + } + } else { + -1 + } +} + +fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> { + let result = getrandom(dest, blocking); + if result == -1 || result == 0 { + let err = io::Error::last_os_error(); + let kind = err.kind(); + if kind == io::ErrorKind::WouldBlock { + return Err(Error::with_cause( + ErrorKind::NotReady, + "getrandom not ready", + err, + )); + } else { + return Err(Error::with_cause( + ErrorKind::Unavailable, + "unexpected getrandom error", + err, + )); + } + } else if result != dest.len() as libc::ssize_t { + return Err(Error::new(ErrorKind::Unavailable, + "unexpected getrandom error")); + } + Ok(()) +} + +fn is_getrandom_available() -> bool { + let available = match fetch() { + Some(_) => true, + None => false, + }; + info!("OsRng: using {}", if available { "getrandom" } else { "/dev/random" }); + available +} diff --git a/bash-5.1/vendor/rand_os/src/wasm32_bindgen.rs b/bash-5.1/vendor/rand_os/src/wasm32_bindgen.rs new file mode 100644 index 0000000..5ab2d84 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/wasm32_bindgen.rs @@ -0,0 +1,92 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for WASM via wasm-bindgen + +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; +use super::__wbg_shims::*; + +use wasm_bindgen::prelude::*; + + +#[derive(Clone, Debug)] +pub enum OsRng { + Node(NodeCrypto), + Browser(BrowserCrypto), +} + +impl OsRngImpl for OsRng { + fn new() -> Result { + // First up we need to detect if we're running in node.js or a + // browser. To do this we get ahold of the `this` object (in a bit + // of a roundabout fashion). + // + // Once we have `this` we look at its `self` property, which is + // only defined on the web (either a main window or web worker). + let this = Function::new("return this").call(&JsValue::undefined()); + assert!(this != JsValue::undefined()); + let this = This::from(this); + let is_browser = this.self_() != JsValue::undefined(); + + if !is_browser { + return Ok(OsRng::Node(node_require("crypto"))) + } + + // If `self` is defined then we're in a browser somehow (main window + // or web worker). Here we want to try to use + // `crypto.getRandomValues`, but if `crypto` isn't defined we assume + // we're in an older web browser and the OS RNG isn't available. + let crypto = this.crypto(); + if crypto.is_undefined() { + let msg = "self.crypto is undefined"; + return Err(Error::new(ErrorKind::Unavailable, msg)) + } + + // Test if `crypto.getRandomValues` is undefined as well + let crypto: BrowserCrypto = crypto.into(); + if crypto.get_random_values_fn().is_undefined() { + let msg = "crypto.getRandomValues is undefined"; + return Err(Error::new(ErrorKind::Unavailable, msg)) + } + + // Ok! `self.crypto.getRandomValues` is a defined value, so let's + // assume we can do browser crypto. + Ok(OsRng::Browser(crypto)) + } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + match *self { + OsRng::Node(ref n) => n.random_fill_sync(dest), + OsRng::Browser(ref n) => n.get_random_values(dest), + } + Ok(()) + } + + fn max_chunk_size(&self) -> usize { + match *self { + OsRng::Node(_) => usize::max_value(), + OsRng::Browser(_) => { + // see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues + // + // where it says: + // + // > A QuotaExceededError DOMException is thrown if the + // > requested length is greater than 65536 bytes. + 65536 + } + } + } + + fn method_str(&self) -> &'static str { + match *self { + OsRng::Node(_) => "crypto.randomFillSync", + OsRng::Browser(_) => "crypto.getRandomValues", + } + } +} diff --git a/bash-5.1/vendor/rand_os/src/wasm32_stdweb.rs b/bash-5.1/vendor/rand_os/src/wasm32_stdweb.rs new file mode 100644 index 0000000..3be0ce6 --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/wasm32_stdweb.rs @@ -0,0 +1,107 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for WASM via stdweb + +use std::mem; +use stdweb::unstable::TryInto; +use stdweb::web::error::Error as WebError; +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; + +#[derive(Clone, Debug)] +enum OsRngMethod { + Browser, + Node +} + +#[derive(Clone, Debug)] +pub struct OsRng(OsRngMethod); + +impl OsRngImpl for OsRng { + fn new() -> Result { + let result = js! { + try { + if ( + typeof self === "object" && + typeof self.crypto === "object" && + typeof self.crypto.getRandomValues === "function" + ) { + return { success: true, ty: 1 }; + } + + if (typeof require("crypto").randomBytes === "function") { + return { success: true, ty: 2 }; + } + + return { success: false, error: new Error("not supported") }; + } catch(err) { + return { success: false, error: err }; + } + }; + + if js!{ return @{ result.as_ref() }.success } == true { + let ty = js!{ return @{ result }.ty }; + + if ty == 1 { Ok(OsRng(OsRngMethod::Browser)) } + else if ty == 2 { Ok(OsRng(OsRngMethod::Node)) } + else { unreachable!() } + } else { + let err: WebError = js!{ return @{ result }.error }.try_into().unwrap(); + Err(Error::with_cause(ErrorKind::Unavailable, "WASM Error", err)) + } + } + + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + assert_eq!(mem::size_of::(), 4); + + let len = dest.len() as u32; + let ptr = dest.as_mut_ptr() as i32; + + let result = match self.0 { + OsRngMethod::Browser => js! { + try { + let array = new Uint8Array(@{ len }); + self.crypto.getRandomValues(array); + HEAPU8.set(array, @{ ptr }); + + return { success: true }; + } catch(err) { + return { success: false, error: err }; + } + }, + OsRngMethod::Node => js! { + try { + let bytes = require("crypto").randomBytes(@{ len }); + HEAPU8.set(new Uint8Array(bytes), @{ ptr }); + + return { success: true }; + } catch(err) { + return { success: false, error: err }; + } + } + }; + + if js!{ return @{ result.as_ref() }.success } == true { + Ok(()) + } else { + let err: WebError = js!{ return @{ result }.error }.try_into().unwrap(); + Err(Error::with_cause(ErrorKind::Unexpected, "WASM Error", err)) + } + } + + fn max_chunk_size(&self) -> usize { 65536 } + + fn method_str(&self) -> &'static str { + match self.0 { + OsRngMethod::Browser => "Crypto.getRandomValues", + OsRngMethod::Node => "crypto.randomBytes", + } + } +} diff --git a/bash-5.1/vendor/rand_os/src/windows.rs b/bash-5.1/vendor/rand_os/src/windows.rs new file mode 100644 index 0000000..6b06c7a --- /dev/null +++ b/bash-5.1/vendor/rand_os/src/windows.rs @@ -0,0 +1,44 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementation for Windows + +extern crate winapi; + +use rand_core::{Error, ErrorKind}; +use super::OsRngImpl; + +use std::io; + +use self::winapi::shared::minwindef::ULONG; +use self::winapi::um::ntsecapi::RtlGenRandom; +use self::winapi::um::winnt::PVOID; + +#[derive(Clone, Debug)] +pub struct OsRng; + +impl OsRngImpl for OsRng { + fn new() -> Result { Ok(OsRng) } + + fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { + let ret = unsafe { + RtlGenRandom(dest.as_mut_ptr() as PVOID, dest.len() as ULONG) + }; + if ret == 0 { + return Err(Error::with_cause( + ErrorKind::Unavailable, + "couldn't generate random bytes", + io::Error::last_os_error())); + } + Ok(()) + } + + fn max_chunk_size(&self) -> usize { ::max_value() as usize } + + fn method_str(&self) -> &'static str { "RtlGenRandom" } +} diff --git a/bash-5.1/vendor/rand_os/tests/mod.rs b/bash-5.1/vendor/rand_os/tests/mod.rs new file mode 100644 index 0000000..2130e16 --- /dev/null +++ b/bash-5.1/vendor/rand_os/tests/mod.rs @@ -0,0 +1,80 @@ +extern crate rand_os; + +use rand_os::rand_core::RngCore; +use rand_os::OsRng; + +#[test] +fn test_os_rng() { + let mut r = OsRng::new().unwrap(); + + r.next_u32(); + r.next_u64(); + + let mut v1 = [0u8; 1000]; + r.fill_bytes(&mut v1); + + let mut v2 = [0u8; 1000]; + r.fill_bytes(&mut v2); + + let mut n_diff_bits = 0; + for i in 0..v1.len() { + n_diff_bits += (v1[i] ^ v2[i]).count_ones(); + } + + // Check at least 1 bit per byte differs. p(failure) < 1e-1000 with random input. + assert!(n_diff_bits >= v1.len() as u32); +} + +#[test] +fn test_os_rng_empty() { + let mut r = OsRng::new().unwrap(); + + let mut empty = [0u8; 0]; + r.fill_bytes(&mut empty); +} + +#[test] +fn test_os_rng_huge() { + let mut r = OsRng::new().unwrap(); + + let mut huge = [0u8; 100_000]; + r.fill_bytes(&mut huge); +} + +#[cfg(not(any(target_arch = "wasm32", target_arch = "asmjs")))] +#[test] +fn test_os_rng_tasks() { + use std::sync::mpsc::channel; + use std::thread; + + let mut txs = vec!(); + for _ in 0..20 { + let (tx, rx) = channel(); + txs.push(tx); + + thread::spawn(move|| { + // wait until all the tasks are ready to go. + rx.recv().unwrap(); + + // deschedule to attempt to interleave things as much + // as possible (XXX: is this a good test?) + let mut r = OsRng::new().unwrap(); + thread::yield_now(); + let mut v = [0u8; 1000]; + + for _ in 0..100 { + r.next_u32(); + thread::yield_now(); + r.next_u64(); + thread::yield_now(); + r.fill_bytes(&mut v); + thread::yield_now(); + } + }); + } + + // start all the tasks + for tx in txs.iter() { + tx.send(()).unwrap(); + } +} diff --git a/bash-5.1/vendor/rand_pcg/.cargo-checksum.json b/bash-5.1/vendor/rand_pcg/.cargo-checksum.json new file mode 100644 index 0000000..a21533e --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"f95c32b93b4ba4aac59fcf1d28b1818a8551a450198c075cf5720e71a5db17ef","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"82101af38b08afd05d0b09aae70b578f3d08d7fdc98ed643498e52175d85c09c","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"2234e3cefee876aeb686ad89e978bdb07bf118a1186ab1cf161bcdf69d4b4f57","README.md":"8da8a3dce4abed17df07963b65637cc150093d04d1d7354450afdcee26b0af4f","build.rs":"003108281c4f4bd7a40a93529012acc9d2555c7a4f4b3bfc3ab81d0ed92b8864","src/lib.rs":"443c6e23da72f86d4c0b24698c0d188ee984fce69e4f52d633191399b0051c6c","src/pcg128.rs":"71bc1063e56b0b906aab333438178bb3e636dd1fcdbae2c2452af9143aea5855","src/pcg64.rs":"0b36d28ec2e1cdd630473530785b3143966a4657e52f032e020bb5524be2e044","tests/lcg64xsh32.rs":"5770fb1dd2cce4843de89dccb05f79ffce9c0b8dc68487d09b30b376e8e982e3","tests/mcg128xsl64.rs":"8276f9ce83df0f76b0a242ec35fbbd6a6fcd5aacd9cd9a3b0812b538dc5a70f0"},"package":"abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_pcg/CHANGELOG.md b/bash-5.1/vendor/rand_pcg/CHANGELOG.md new file mode 100644 index 0000000..6957224 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/CHANGELOG.md @@ -0,0 +1,19 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.2] - 2019-02-23 +- require `bincode` 1.1.2 for i128 auto-detection +- make `bincode` a dev-dependency again #663 +- clean up tests and Serde support + +## [0.1.1] - 2018-10-04 +- make `bincode` an explicit dependency when using Serde + +## [0.1.0] - 2018-10-04 +Initial release, including: + +- `Lcg64Xsh32` aka `Pcg32` +- `Mcg128Xsl64` aka `Pcg64Mcg` diff --git a/bash-5.1/vendor/rand_pcg/COPYRIGHT b/bash-5.1/vendor/rand_pcg/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_pcg/Cargo.toml b/bash-5.1/vendor/rand_pcg/Cargo.toml new file mode 100644 index 0000000..346f2f7 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/Cargo.toml @@ -0,0 +1,47 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_pcg" +version = "0.1.2" +authors = ["The Rand Project Developers"] +build = "build.rs" +description = "Selected PCG random number generators\n" +homepage = "https://crates.io/crates/rand_pcg" +documentation = "https://rust-random.github.io/rand/rand_pcg" +readme = "README.md" +keywords = ["random", "rng", "pcg"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.rand_core] +version = "0.4" + +[dependencies.serde] +version = "1" +optional = true + +[dependencies.serde_derive] +version = "^1.0.38" +optional = true +[dev-dependencies.bincode] +version = "1.1.2" +[build-dependencies.autocfg] +version = "0.1" + +[features] +serde1 = ["serde", "serde_derive"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_pcg/LICENSE-APACHE b/bash-5.1/vendor/rand_pcg/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_pcg/LICENSE-MIT b/bash-5.1/vendor/rand_pcg/LICENSE-MIT new file mode 100644 index 0000000..d46f058 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors +Copyright 2018 Developers of the Rand project + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_pcg/README.md b/bash-5.1/vendor/rand_pcg/README.md new file mode 100644 index 0000000..ae583a1 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/README.md @@ -0,0 +1,43 @@ +# rand_pcg + +[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_pcg.svg)](https://crates.io/crates/rand_pcg) +[[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_pcg) +[![API](https://docs.rs/rand_pcg/badge.svg)](https://docs.rs/rand_pcg) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Implements a selection of PCG random number generators. + +> PCG is a family of simple fast space-efficient statistically good algorithms +> for random number generation. [Melissa O'Neill, Harvey Mudd College, 2014]. + +The PCG algorithms are not suitable for cryptographic uses, but perform well +in statistical tests, use little memory and are fairly fast. +See the [pcg-random website](http://www.pcg-random.org/). + +This crate depends on [rand_core](https://crates.io/crates/rand_core) and is +part of the [Rand project](https://github.com/rust-random/rand). + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_pcg) +- [API documentation (docs.rs)](https://docs.rs/rand_pcg) +- [Changelog](CHANGELOG.md) + + +## Crate Features + +`rand_pcg` is `no_std` compatible by default. + +The `serde1` feature includes implementations of `Serialize` and `Deserialize` +for the included RNGs. + +## License + +`rand_pcg` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_pcg/build.rs b/bash-5.1/vendor/rand_pcg/build.rs new file mode 100644 index 0000000..06e12a4 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/build.rs @@ -0,0 +1,7 @@ +extern crate autocfg; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + let ac = autocfg::new(); + ac.emit_rustc_version(1, 26); +} diff --git a/bash-5.1/vendor/rand_pcg/src/lib.rs b/bash-5.1/vendor/rand_pcg/src/lib.rs new file mode 100644 index 0000000..9648e85 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/src/lib.rs @@ -0,0 +1,48 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The PCG random number generators. +//! +//! This is a native Rust implementation of a small selection of PCG generators. +//! The primary goal of this crate is simple, minimal, well-tested code; in +//! other words it is explicitly not a goal to re-implement all of PCG. +//! +//! This crate provides: +//! +//! - `Pcg32` aka `Lcg64Xsh32`, officially known as `pcg32`, a general +//! purpose RNG. This is a good choice on both 32-bit and 64-bit CPUs +//! (for 32-bit output). +//! - `Pcg64Mcg` aka `Mcg128Xsl64`, officially known as `mcg_xsl_rr_128_64`, +//! a general purpose RNG using 128-bit multiplications. This has poor +//! performance on 32-bit CPUs but is a good choice on 64-bit CPUs for +//! both 32-bit and 64-bit output. (Note: this RNG is only available using +//! Rust 1.26 or later.) +//! +//! Both of these use 16 bytes of state and 128-bit seeds, and are considered +//! value-stable (i.e. any change affecting the output given a fixed seed would +//! be considered a breaking change to the crate). + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] + +#![no_std] + +pub extern crate rand_core; + +#[cfg(feature="serde1")] extern crate serde; +#[cfg(feature="serde1")] #[macro_use] extern crate serde_derive; + +mod pcg64; +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] mod pcg128; + +pub use self::pcg64::{Pcg32, Lcg64Xsh32}; +#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] pub use self::pcg128::{Pcg64Mcg, Mcg128Xsl64}; diff --git a/bash-5.1/vendor/rand_pcg/src/pcg128.rs b/bash-5.1/vendor/rand_pcg/src/pcg128.rs new file mode 100644 index 0000000..9aff506 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/src/pcg128.rs @@ -0,0 +1,122 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017 Paul Dicker. +// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! PCG random number generators + +// This is the default multiplier used by PCG for 64-bit state. +const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645; + +use core::fmt; +use core::mem::transmute; +use rand_core::{RngCore, SeedableRng, Error, le}; + +/// A PCG random number generator (XSL 128/64 (MCG) variant). +/// +/// Permuted Congruential Generator with 128-bit state, internal Multiplicative +/// Congruential Generator, and 64-bit output via "xorshift low (bits), +/// random rotation" output function. +/// +/// This is a 128-bit MCG with the PCG-XSL-RR output function. +/// Note that compared to the standard `pcg64` (128-bit LCG with PCG-XSL-RR +/// output function), this RNG is faster, also has a long cycle, and still has +/// good performance on statistical tests. +/// +/// Note: this RNG is only available using Rust 1.26 or later. +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] +pub struct Mcg128Xsl64 { + state: u128, +} + +/// A friendly name for `Mcg128Xsl64`. +pub type Pcg64Mcg = Mcg128Xsl64; + +impl Mcg128Xsl64 { + /// Construct an instance compatible with PCG seed. + /// + /// Note that PCG specifies a default value for the parameter: + /// + /// - `state = 0xcafef00dd15ea5e5` + pub fn new(state: u128) -> Self { + // Force low bit to 1, as in C version (C++ uses `state | 3` instead). + Mcg128Xsl64 { state: state | 1 } + } +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for Mcg128Xsl64 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Mcg128Xsl64 {{}}") + } +} + +/// We use a single 126-bit seed to initialise the state and select a stream. +/// Two `seed` bits (lowest order of last byte) are ignored. +impl SeedableRng for Mcg128Xsl64 { + type Seed = [u8; 16]; + + fn from_seed(seed: Self::Seed) -> Self { + // Read as if a little-endian u128 value: + let mut seed_u64 = [0u64; 2]; + le::read_u64_into(&seed, &mut seed_u64); + let state = (seed_u64[0] as u128) | + (seed_u64[1] as u128) << 64; + Mcg128Xsl64::new(state) + } +} + +impl RngCore for Mcg128Xsl64 { + #[inline] + fn next_u32(&mut self) -> u32 { + self.next_u64() as u32 + } + + #[inline] + fn next_u64(&mut self) -> u64 { + // prepare the LCG for the next round + let state = self.state.wrapping_mul(MULTIPLIER); + self.state = state; + + // Output function XSL RR ("xorshift low (bits), random rotation") + // Constants are for 128-bit state, 64-bit output + const XSHIFT: u32 = 64; // (128 - 64 + 64) / 2 + const ROTATE: u32 = 122; // 128 - 6 + + let rot = (state >> ROTATE) as u32; + let xsl = ((state >> XSHIFT) as u64) ^ (state as u64); + xsl.rotate_right(rot) + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + // specialisation of impls::fill_bytes_via_next; approx 3x faster + let mut left = dest; + while left.len() >= 8 { + let (l, r) = {left}.split_at_mut(8); + left = r; + let chunk: [u8; 8] = unsafe { + transmute(self.next_u64().to_le()) + }; + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 0 { + let chunk: [u8; 8] = unsafe { + transmute(self.next_u64().to_le()) + }; + left.copy_from_slice(&chunk[..n]); + } + } + + #[inline] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} diff --git a/bash-5.1/vendor/rand_pcg/src/pcg64.rs b/bash-5.1/vendor/rand_pcg/src/pcg64.rs new file mode 100644 index 0000000..9177ec2 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/src/pcg64.rs @@ -0,0 +1,141 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017 Paul Dicker. +// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! PCG random number generators + +use core::fmt; +use core::mem::transmute; +use rand_core::{RngCore, SeedableRng, Error, le, impls}; + +// This is the default multiplier used by PCG for 64-bit state. +const MULTIPLIER: u64 = 6364136223846793005; + +/// A PCG random number generator (XSH RR 64/32 (LCG) variant). +/// +/// Permuted Congruential Generator with 64-bit state, internal Linear +/// Congruential Generator, and 32-bit output via "xorshift high (bits), +/// random rotation" output function. +/// +/// This is a 64-bit LCG with explicitly chosen stream with the PCG-XSH-RR +/// output function. This combination is the standard `pcg32`. +/// +/// Despite the name, this implementation uses 16 bytes (128 bit) space +/// comprising 64 bits of state and 64 bits stream selector. These are both set +/// by `SeedableRng`, using a 128-bit seed. +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] +pub struct Lcg64Xsh32 { + state: u64, + increment: u64, +} + +/// `Lcg64Xsh32` is also officially known as `pcg32`. +pub type Pcg32 = Lcg64Xsh32; + +impl Lcg64Xsh32 { + /// Construct an instance compatible with PCG seed and stream. + /// + /// Note that PCG specifies default values for both parameters: + /// + /// - `state = 0xcafef00dd15ea5e5` + /// - `stream = 721347520444481703` + pub fn new(state: u64, stream: u64) -> Self { + // The increment must be odd, hence we discard one bit: + let increment = (stream << 1) | 1; + Lcg64Xsh32::from_state_incr(state, increment) + } + + #[inline] + fn from_state_incr(state: u64, increment: u64) -> Self { + let mut pcg = Lcg64Xsh32 { state, increment }; + // Move away from inital value: + pcg.state = pcg.state.wrapping_add(pcg.increment); + pcg.step(); + pcg + } + + #[inline] + fn step(&mut self) { + // prepare the LCG for the next round + self.state = self.state + .wrapping_mul(MULTIPLIER) + .wrapping_add(self.increment); + } +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for Lcg64Xsh32 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Lcg64Xsh32 {{}}") + } +} + +/// We use a single 127-bit seed to initialise the state and select a stream. +/// One `seed` bit (lowest bit of `seed[8]`) is ignored. +impl SeedableRng for Lcg64Xsh32 { + type Seed = [u8; 16]; + + fn from_seed(seed: Self::Seed) -> Self { + let mut seed_u64 = [0u64; 2]; + le::read_u64_into(&seed, &mut seed_u64); + + // The increment must be odd, hence we discard one bit: + Lcg64Xsh32::from_state_incr(seed_u64[0], seed_u64[1] | 1) + } +} + +impl RngCore for Lcg64Xsh32 { + #[inline] + fn next_u32(&mut self) -> u32 { + let state = self.state; + self.step(); + + // Output function XSH RR: xorshift high (bits), followed by a random rotate + // Constants are for 64-bit state, 32-bit output + const ROTATE: u32 = 59; // 64 - 5 + const XSHIFT: u32 = 18; // (5 + 32) / 2 + const SPARE: u32 = 27; // 64 - 32 - 5 + + let rot = (state >> ROTATE) as u32; + let xsh = (((state >> XSHIFT) ^ state) >> SPARE) as u32; + xsh.rotate_right(rot) + } + + #[inline] + fn next_u64(&mut self) -> u64 { + impls::next_u64_via_u32(self) + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + // specialisation of impls::fill_bytes_via_next; approx 40% faster + let mut left = dest; + while left.len() >= 4 { + let (l, r) = {left}.split_at_mut(4); + left = r; + let chunk: [u8; 4] = unsafe { + transmute(self.next_u32().to_le()) + }; + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 0 { + let chunk: [u8; 4] = unsafe { + transmute(self.next_u32().to_le()) + }; + left.copy_from_slice(&chunk[..n]); + } + } + + #[inline] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} diff --git a/bash-5.1/vendor/rand_pcg/tests/lcg64xsh32.rs b/bash-5.1/vendor/rand_pcg/tests/lcg64xsh32.rs new file mode 100644 index 0000000..775b12c --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/tests/lcg64xsh32.rs @@ -0,0 +1,58 @@ +extern crate rand_pcg; +extern crate rand_core; +#[cfg(all(feature="serde1", test))] extern crate bincode; + +use rand_core::{RngCore, SeedableRng}; +use rand_pcg::{Lcg64Xsh32, Pcg32}; + +#[test] +fn test_lcg64xsh32_construction() { + // Test that various construction techniques produce a working RNG. + let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; + let mut rng1 = Lcg64Xsh32::from_seed(seed); + assert_eq!(rng1.next_u64(), 1204678643940597513); + + let mut rng2 = Lcg64Xsh32::from_rng(&mut rng1).unwrap(); + assert_eq!(rng2.next_u64(), 12384929573776311845); + + let mut rng3 = Lcg64Xsh32::seed_from_u64(0); + assert_eq!(rng3.next_u64(), 18195738587432868099); + + // This is the same as Lcg64Xsh32, so we only have a single test: + let mut rng4 = Pcg32::seed_from_u64(0); + assert_eq!(rng4.next_u64(), 18195738587432868099); +} + +#[test] +fn test_lcg64xsh32_true_values() { + // Numbers copied from official test suite. + let mut rng = Lcg64Xsh32::new(42, 54); + + let mut results = [0u32; 6]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected: [u32; 6] = [0xa15c02b7, 0x7b47f409, 0xba1d3330, + 0x83d2f293, 0xbfa4784b, 0xcbed606e]; + assert_eq!(results, expected); +} + +#[cfg(feature="serde1")] +#[test] +fn test_lcg64xsh32_serde() { + use bincode; + use std::io::{BufWriter, BufReader}; + + let mut rng = Lcg64Xsh32::seed_from_u64(0); + + let buf: Vec = Vec::new(); + let mut buf = BufWriter::new(buf); + bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); + + let buf = buf.into_inner().unwrap(); + let mut read = BufReader::new(&buf[..]); + let mut deserialized: Lcg64Xsh32 = bincode::deserialize_from(&mut read) + .expect("Could not deserialize"); + + for _ in 0..16 { + assert_eq!(rng.next_u64(), deserialized.next_u64()); + } +} diff --git a/bash-5.1/vendor/rand_pcg/tests/mcg128xsl64.rs b/bash-5.1/vendor/rand_pcg/tests/mcg128xsl64.rs new file mode 100644 index 0000000..3279536 --- /dev/null +++ b/bash-5.1/vendor/rand_pcg/tests/mcg128xsl64.rs @@ -0,0 +1,59 @@ +#![cfg(rustc_1_26)] +extern crate rand_pcg; +extern crate rand_core; +#[cfg(all(feature="serde1", test))] extern crate bincode; + +use rand_core::{RngCore, SeedableRng}; +use rand_pcg::{Mcg128Xsl64, Pcg64Mcg}; + +#[test] +fn test_mcg128xsl64_construction() { + // Test that various construction techniques produce a working RNG. + let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; + let mut rng1 = Mcg128Xsl64::from_seed(seed); + assert_eq!(rng1.next_u64(), 7071994460355047496); + + let mut rng2 = Mcg128Xsl64::from_rng(&mut rng1).unwrap(); + assert_eq!(rng2.next_u64(), 12300796107712034932); + + let mut rng3 = Mcg128Xsl64::seed_from_u64(0); + assert_eq!(rng3.next_u64(), 6198063878555692194); + + // This is the same as Mcg128Xsl64, so we only have a single test: + let mut rng4 = Pcg64Mcg::seed_from_u64(0); + assert_eq!(rng4.next_u64(), 6198063878555692194); +} + +#[test] +fn test_mcg128xsl64_true_values() { + // Numbers copied from official test suite (C version). + let mut rng = Mcg128Xsl64::new(42); + + let mut results = [0u64; 6]; + for i in results.iter_mut() { *i = rng.next_u64(); } + let expected: [u64; 6] = [0x63b4a3a813ce700a, 0x382954200617ab24, + 0xa7fd85ae3fe950ce, 0xd715286aa2887737, 0x60c92fee2e59f32c, 0x84c4e96beff30017]; + assert_eq!(results, expected); +} + +#[cfg(feature="serde1")] +#[test] +fn test_mcg128xsl64_serde() { + use bincode; + use std::io::{BufWriter, BufReader}; + + let mut rng = Mcg128Xsl64::seed_from_u64(0); + + let buf: Vec = Vec::new(); + let mut buf = BufWriter::new(buf); + bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); + + let buf = buf.into_inner().unwrap(); + let mut read = BufReader::new(&buf[..]); + let mut deserialized: Mcg128Xsl64 = bincode::deserialize_from(&mut read) + .expect("Could not deserialize"); + + for _ in 0..16 { + assert_eq!(rng.next_u64(), deserialized.next_u64()); + } +} diff --git a/bash-5.1/vendor/rand_xorshift/.cargo-checksum.json b/bash-5.1/vendor/rand_xorshift/.cargo-checksum.json new file mode 100644 index 0000000..ce75b59 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"8b36d20dea31334f1dabb3c4ef2c5d4f373432e5fc4f16ea247f0c8550f21e1a","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"3fdcb1949fd24244fb3e608a0bb950f3466799207f6f93759addc26fa89cea68","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"d15ff53ca6f8a7d4791343836e29fe86ce7528029a05f9f327064aaaa01a5368","src/lib.rs":"642ec47c3419708550926cc03f26ca4915e6471dd796d1f1e83b675fb5633649","tests/mod.rs":"533eb0d703ff6154c21d9655c863223e79f81da026dc4abf79c24d2705ae3813"},"package":"cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c"} \ No newline at end of file diff --git a/bash-5.1/vendor/rand_xorshift/CHANGELOG.md b/bash-5.1/vendor/rand_xorshift/CHANGELOG.md new file mode 100644 index 0000000..539af41 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.1] - 2019-01-04 +- Reorganise code and tests; tweak doc + +## [0.1.0] - 2018-07-16 +- Pulled out of the Rand crate diff --git a/bash-5.1/vendor/rand_xorshift/COPYRIGHT b/bash-5.1/vendor/rand_xorshift/COPYRIGHT new file mode 100644 index 0000000..468d907 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/COPYRIGHT @@ -0,0 +1,12 @@ +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/bash-5.1/vendor/rand_xorshift/Cargo.toml b/bash-5.1/vendor/rand_xorshift/Cargo.toml new file mode 100644 index 0000000..26aa481 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/Cargo.toml @@ -0,0 +1,45 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rand_xorshift" +version = "0.1.1" +authors = ["The Rand Project Developers", "The Rust Project Developers"] +description = "Xorshift random number generator\n" +homepage = "https://crates.io/crates/rand_xorshift" +documentation = "https://rust-random.github.io/rand/rand_xorshift" +readme = "README.md" +keywords = ["random", "rng", "xorshift"] +categories = ["algorithms", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-random/rand" +[dependencies.rand_core] +version = ">=0.2, <0.4" +default-features = false + +[dependencies.serde] +version = "1" +optional = true + +[dependencies.serde_derive] +version = "^1.0.38" +optional = true +[dev-dependencies.bincode] +version = "1" + +[features] +serde1 = ["serde", "serde_derive"] +[badges.appveyor] +repository = "rust-random/rand" + +[badges.travis-ci] +repository = "rust-random/rand" diff --git a/bash-5.1/vendor/rand_xorshift/LICENSE-APACHE b/bash-5.1/vendor/rand_xorshift/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rand_xorshift/LICENSE-MIT b/bash-5.1/vendor/rand_xorshift/LICENSE-MIT new file mode 100644 index 0000000..d93b5ba --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rand_xorshift/README.md b/bash-5.1/vendor/rand_xorshift/README.md new file mode 100644 index 0000000..573ee12 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/README.md @@ -0,0 +1,45 @@ +# rand_xorshift + +[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) +[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) +[![Latest version](https://img.shields.io/crates/v/rand_xorshift.svg)](https://crates.io/crates/rand_xorshift) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_xorshift) +[![API](https://docs.rs/rand_xorshift/badge.svg)](https://docs.rs/rand_xorshift) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Implements the Xorshift random number generator. + +The Xorshift[^1] algorithm is not suitable for cryptographic purposes +but is very fast. If you do not know for sure that it fits your +requirements, use a more secure one such as `StdRng` or `OsRng`. + +[^1]: Marsaglia, George (July 2003). + ["Xorshift RNGs"](https://www.jstatsoft.org/v08/i14/paper). + *Journal of Statistical Software*. Vol. 8 (Issue 14). + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_xorshift) +- [API documentation (docs.rs)](https://docs.rs/rand_xorshift) +- [Changelog](CHANGELOG.md) + +[rand]: https://crates.io/crates/rand + + +## Crate Features + +`rand_xorshift` is `no_std` compatible. It does not require any functionality +outside of the `core` lib, thus there are no features to configure. + +The `serde1` feature includes implementations of `Serialize` and `Deserialize` +for the included RNGs. + + +## License + +`rand_xorshift` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/bash-5.1/vendor/rand_xorshift/src/lib.rs b/bash-5.1/vendor/rand_xorshift/src/lib.rs new file mode 100644 index 0000000..aad74e4 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/src/lib.rs @@ -0,0 +1,123 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The xorshift random number generator. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://rust-random.github.io/rand/")] + +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] + +#![no_std] + +extern crate rand_core; + +#[cfg(feature="serde1")] extern crate serde; +#[cfg(feature="serde1")] #[macro_use] extern crate serde_derive; + +use core::num::Wrapping as w; +use core::{fmt, slice}; +use rand_core::{RngCore, SeedableRng, Error, impls, le}; + +/// An Xorshift random number generator. +/// +/// The Xorshift[^1] algorithm is not suitable for cryptographic purposes +/// but is very fast. If you do not know for sure that it fits your +/// requirements, use a more secure one such as `StdRng` or `OsRng`. +/// +/// [^1]: Marsaglia, George (July 2003). +/// ["Xorshift RNGs"](https://www.jstatsoft.org/v08/i14/paper). +/// *Journal of Statistical Software*. Vol. 8 (Issue 14). +#[derive(Clone)] +#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] +pub struct XorShiftRng { + x: w, + y: w, + z: w, + w: w, +} + +// Custom Debug implementation that does not expose the internal state +impl fmt::Debug for XorShiftRng { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "XorShiftRng {{}}") + } +} + +impl RngCore for XorShiftRng { + #[inline] + fn next_u32(&mut self) -> u32 { + let x = self.x; + let t = x ^ (x << 11); + self.x = self.y; + self.y = self.z; + self.z = self.w; + let w_ = self.w; + self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8)); + self.w.0 + } + + #[inline] + fn next_u64(&mut self) -> u64 { + impls::next_u64_via_u32(self) + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + impls::fill_bytes_via_next(self, dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl SeedableRng for XorShiftRng { + type Seed = [u8; 16]; + + fn from_seed(seed: Self::Seed) -> Self { + let mut seed_u32 = [0u32; 4]; + le::read_u32_into(&seed, &mut seed_u32); + + // Xorshift cannot be seeded with 0 and we cannot return an Error, but + // also do not wish to panic (because a random seed can legitimately be + // 0); our only option is therefore to use a preset value. + if seed_u32.iter().all(|&x| x == 0) { + seed_u32 = [0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED]; + } + + XorShiftRng { + x: w(seed_u32[0]), + y: w(seed_u32[1]), + z: w(seed_u32[2]), + w: w(seed_u32[3]), + } + } + + fn from_rng(mut rng: R) -> Result { + let mut seed_u32 = [0u32; 4]; + loop { + unsafe { + let ptr = seed_u32.as_mut_ptr() as *mut u8; + + let slice = slice::from_raw_parts_mut(ptr, 4 * 4); + rng.try_fill_bytes(slice)?; + } + if !seed_u32.iter().all(|&x| x == 0) { break; } + } + + Ok(XorShiftRng { + x: w(seed_u32[0]), + y: w(seed_u32[1]), + z: w(seed_u32[2]), + w: w(seed_u32[3]), + }) + } +} diff --git a/bash-5.1/vendor/rand_xorshift/tests/mod.rs b/bash-5.1/vendor/rand_xorshift/tests/mod.rs new file mode 100644 index 0000000..8374b64 --- /dev/null +++ b/bash-5.1/vendor/rand_xorshift/tests/mod.rs @@ -0,0 +1,92 @@ +extern crate rand_core; +extern crate rand_xorshift; +#[cfg(all(feature="serde1", test))] extern crate bincode; + +use rand_core::{RngCore, SeedableRng}; +use rand_xorshift::XorShiftRng; + +#[test] +fn test_xorshift_construction() { + // Test that various construction techniques produce a working RNG. + let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; + let mut rng1 = XorShiftRng::from_seed(seed); + assert_eq!(rng1.next_u64(), 4325440999699518727); + + let _rng2 = XorShiftRng::from_rng(rng1).unwrap(); + // Note: we cannot test the state of _rng2 because from_rng does not + // fix Endianness. This is allowed in the trait specification. +} + +#[test] +fn test_xorshift_true_values() { + let seed = [16,15,14,13, 12,11,10,9, 8,7,6,5, 4,3,2,1]; + let mut rng = XorShiftRng::from_seed(seed); + + let mut results = [0u32; 9]; + for i in results.iter_mut() { *i = rng.next_u32(); } + let expected: [u32; 9] = [ + 2081028795, 620940381, 269070770, 16943764, 854422573, 29242889, + 1550291885, 1227154591, 271695242]; + assert_eq!(results, expected); + + let mut results = [0u64; 9]; + for i in results.iter_mut() { *i = rng.next_u64(); } + let expected: [u64; 9] = [ + 9247529084182843387, 8321512596129439293, 14104136531997710878, + 6848554330849612046, 343577296533772213, 17828467390962600268, + 9847333257685787782, 7717352744383350108, 1133407547287910111]; + assert_eq!(results, expected); + + let mut results = [0u8; 32]; + rng.fill_bytes(&mut results); + let expected = [102, 57, 212, 16, 233, 130, 49, 183, + 158, 187, 44, 203, 63, 149, 45, 17, + 117, 129, 131, 160, 70, 121, 158, 155, + 224, 209, 192, 53, 10, 62, 57, 72]; + assert_eq!(results, expected); +} + +#[test] +fn test_xorshift_zero_seed() { + // Xorshift does not work with an all zero seed. + // Assert it does not panic. + let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + let mut rng = XorShiftRng::from_seed(seed); + let a = rng.next_u64(); + let b = rng.next_u64(); + assert!(a != 0); + assert!(b != a); +} + +#[test] +fn test_xorshift_clone() { + let seed = [1,2,3,4, 5,5,7,8, 8,7,6,5, 4,3,2,1]; + let mut rng1 = XorShiftRng::from_seed(seed); + let mut rng2 = rng1.clone(); + for _ in 0..16 { + assert_eq!(rng1.next_u64(), rng2.next_u64()); + } +} + +#[cfg(feature="serde1")] +#[test] +fn test_xorshift_serde() { + use bincode; + use std::io::{BufWriter, BufReader}; + + let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; + let mut rng = XorShiftRng::from_seed(seed); + + let buf: Vec = Vec::new(); + let mut buf = BufWriter::new(buf); + bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); + + let buf = buf.into_inner().unwrap(); + let mut read = BufReader::new(&buf[..]); + let mut deserialized: XorShiftRng = bincode::deserialize_from(&mut read) + .expect("Could not deserialize"); + + for _ in 0..16 { + assert_eq!(rng.next_u64(), deserialized.next_u64()); + } +} diff --git a/bash-5.1/vendor/rdrand/.cargo-checksum.json b/bash-5.1/vendor/rdrand/.cargo-checksum.json new file mode 100644 index 0000000..c7b5a11 --- /dev/null +++ b/bash-5.1/vendor/rdrand/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"f11ed31fc1b481c7d0e24251d7d60d34442f1d25747c887c49dc9fbad7e13e59","LICENSE":"00d7b0c8bf95ea93162fccc84da96b906b15add708eade04f7ee6141f7b53141","README.mkd":"93853e9e773543ed0d0cf696b5fb151b15bddc1ad9c39996c9eb11b20a3c7ff6","appveyor.yml":"f502d8a0755b98e904a40b07e8ba270bccd729045b03c24a7db0dfbb4047b515","benches/rdrand.rs":"f3684c360d43bc8a780868c0a3af43b20d56975e03575122cee87277787cc8d0","benches/rdseed.rs":"520097b15a3f11c0c6a357e6cd23add598be22f37839bbc71040b827b05d1064","benches/std.rs":"6a5b52b070b2a594e735aa617f16fc6a861e64534634cdb61801c3297444f6fe","src/changelog.rs":"644e08c06836ecdf94f9a43aec109e9f05f9d85f00541683c72d0d3893ff8d6a","src/lib.rs":"8fc306db8a304d24c28fcefaec1849c0d8bbca97417420af7b81449c352b2e92"},"package":"678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"} \ No newline at end of file diff --git a/bash-5.1/vendor/rdrand/Cargo.toml b/bash-5.1/vendor/rdrand/Cargo.toml new file mode 100644 index 0000000..6b3c80a --- /dev/null +++ b/bash-5.1/vendor/rdrand/Cargo.toml @@ -0,0 +1,28 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rdrand" +version = "0.4.0" +authors = ["Simonas Kazlauskas "] +description = "An implementation of random number generator based on rdrand and rdseed instructions" +documentation = "https://docs.rs/rdrand/0.4.0/" +keywords = ["rand", "rdrand", "rdseed", "random"] +license = "ISC" +repository = "https://github.com/nagisa/rust_rdrand/" +[dependencies.rand_core] +version = "0.3" +default-features = false + +[features] +default = ["std"] +std = [] diff --git a/bash-5.1/vendor/rdrand/LICENSE b/bash-5.1/vendor/rdrand/LICENSE new file mode 100644 index 0000000..4d6f40d --- /dev/null +++ b/bash-5.1/vendor/rdrand/LICENSE @@ -0,0 +1,12 @@ +Copyright © 2014, Simonas Kazlauskas + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without +fee is hereby granted, provided that the above copyright notice and this permission notice appear +in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/bash-5.1/vendor/rdrand/README.mkd b/bash-5.1/vendor/rdrand/README.mkd new file mode 100644 index 0000000..55ab48b --- /dev/null +++ b/bash-5.1/vendor/rdrand/README.mkd @@ -0,0 +1,8 @@ +An implementation of random number generators based on `rdrand` and `rdseed` instructions. + +The random number generators provided by this crate are fairly slow (the latency for these +instructions is pretty high), but provide high quality random bits. Caveat is: neither AMD’s +nor Intel’s designs are public and therefore are not verifiable for lack of backdoors. + +Unless you know what you are doing, use the random number generators provided by the `rand` +crate (such as `EntropyRng`) instead. diff --git a/bash-5.1/vendor/rdrand/appveyor.yml b/bash-5.1/vendor/rdrand/appveyor.yml new file mode 100644 index 0000000..2e915cf --- /dev/null +++ b/bash-5.1/vendor/rdrand/appveyor.yml @@ -0,0 +1,27 @@ +environment: + matrix: + - TARGET: 1.30.0-x86_64-pc-windows-msvc + - TARGET: 1.30.0-i686-pc-windows-msvc + - TARGET: 1.30.0-x86_64-pc-windows-gnu + - TARGET: 1.30.0-i686-pc-windows-gnu + - TARGET: nightly-x86_64-pc-windows-msvc + - TARGET: nightly-i686-pc-windows-msvc +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust.exe" + - ps: .\rust.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null + - ps: $env:PATH="$env:PATH;C:\rust\bin" + - rustc -vV + - cargo -vV +build: off + +test_script: +- cargo test +- cargo test --no-default-features + +for: +- matrix: + only: + - TARGET: nightly-x86_64-pc-windows-msvc + - TARGET: nightly-i686-pc-windows-msvc + test_script: + - cargo bench diff --git a/bash-5.1/vendor/rdrand/benches/rdrand.rs b/bash-5.1/vendor/rdrand/benches/rdrand.rs new file mode 100644 index 0000000..7e70c23 --- /dev/null +++ b/bash-5.1/vendor/rdrand/benches/rdrand.rs @@ -0,0 +1,49 @@ +#![feature(test)] +extern crate rand_core; +extern crate rdrand; +extern crate test; + +use rand_core::RngCore; +use test::Bencher; + +#[bench] +fn bench_u16(b : &mut Bencher) { + if let Ok(gen) = rdrand::RdRand::new() { + b.bytes = 2; + b.iter(|| { + gen.try_next_u16().unwrap() + }); + } +} + +#[bench] +fn bench_u32(b : &mut Bencher) { + if let Ok(mut gen) = rdrand::RdRand::new() { + b.bytes = 4; + b.iter(|| { + gen.next_u32() + }); + } +} + +#[bench] +fn bench_u64(b : &mut Bencher) { + if let Ok(mut gen) = rdrand::RdRand::new() { + b.bytes = 8; + b.iter(|| { + gen.next_u64() + }); + } +} + +#[bench] +fn bench_fill(b : &mut Bencher) { + if let Ok(mut gen) = rdrand::RdRand::new() { + let mut buffer = [0; 128]; + b.bytes = 128; + b.iter(|| { + gen.fill_bytes(&mut buffer); + buffer + }); + } +} diff --git a/bash-5.1/vendor/rdrand/benches/rdseed.rs b/bash-5.1/vendor/rdrand/benches/rdseed.rs new file mode 100644 index 0000000..6bf8ceb --- /dev/null +++ b/bash-5.1/vendor/rdrand/benches/rdseed.rs @@ -0,0 +1,49 @@ +#![feature(test)] +extern crate rand_core; +extern crate rdrand; +extern crate test; + +use rand_core::RngCore; +use test::Bencher; + +#[bench] +fn bench_rdseed_u16(b : &mut Bencher) { + if let Ok(gen) = rdrand::RdSeed::new() { + b.bytes = 2; + b.iter(|| { + gen.try_next_u16().unwrap() + }); + } +} + +#[bench] +fn bench_rdseed_u32(b : &mut Bencher) { + if let Ok(mut gen) = rdrand::RdSeed::new() { + b.bytes = 4; + b.iter(|| { + gen.next_u32() + }); + } +} + +#[bench] +fn bench_rdseed_u64(b : &mut Bencher) { + if let Ok(mut gen) = rdrand::RdSeed::new() { + b.bytes = 8; + b.iter(|| { + gen.next_u64() + }); + } +} + +#[bench] +fn bench_fill(b : &mut Bencher) { + if let Ok(mut gen) = rdrand::RdSeed::new() { + let mut buffer = [0; 128]; + b.bytes = 128; + b.iter(|| { + gen.fill_bytes(&mut buffer); + buffer + }); + } +} diff --git a/bash-5.1/vendor/rdrand/benches/std.rs b/bash-5.1/vendor/rdrand/benches/std.rs new file mode 100644 index 0000000..3fa8fad --- /dev/null +++ b/bash-5.1/vendor/rdrand/benches/std.rs @@ -0,0 +1,31 @@ +// #![feature(test)] +// extern crate rand; +// extern crate test; +// +// use test::Bencher; +// use test::black_box; +// use rand::Rng; +// use rand::StdRng; +// use rand::OsRng; +// +// // OsRng is supposed to be the default for crypto uses. +// #[bench] +// fn bench_osrng_u64(b : &mut Bencher) { +// if let Ok(mut gen) = OsRng::new() { +// b.bytes = 8; +// b.iter(|| { +// black_box(gen.next_u64()); +// }); +// } +// } +// +// // StdRng is the default for everything else. +// #[bench] +// fn bench_stdrng_u64(b : &mut Bencher) { +// if let Ok(mut gen) = StdRng::new() { +// b.bytes = 8; +// b.iter(|| { +// gen.next_u64(); +// }); +// } +// } diff --git a/bash-5.1/vendor/rdrand/src/changelog.rs b/bash-5.1/vendor/rdrand/src/changelog.rs new file mode 100644 index 0000000..503f738 --- /dev/null +++ b/bash-5.1/vendor/rdrand/src/changelog.rs @@ -0,0 +1,25 @@ +//! Project changelog + +/// ## Breaking changes +/// +/// Crate gained an enabled-by-default `std` feature. If you relied on rdrand being `core`-able +/// change your dependency to appear as such: +/// +/// ```toml +/// rdrand = { version = "0.4", default-features = false } +/// ``` +/// +/// This is done so that an advantage of the common feature detection functionality could be +/// employed by users that are not constrained by `core`. This functionality is faster, caches the +/// results and is shared between all users of the functionality. +/// +/// For `core` usage the feature detection has also been improved and will not be done if e.g. +/// crate is built with `rdrand` instructions enabled globally. +pub mod r0_4_0 {} + +/// Crate now works on stable! +/// +/// ## Breaking changes +/// +/// * Updated to `rand_core = ^0.3`. +pub mod r0_3_0 {} diff --git a/bash-5.1/vendor/rdrand/src/lib.rs b/bash-5.1/vendor/rdrand/src/lib.rs new file mode 100644 index 0000000..423ae21 --- /dev/null +++ b/bash-5.1/vendor/rdrand/src/lib.rs @@ -0,0 +1,472 @@ +// Copyright © 2014, Simonas Kazlauskas +// +// Permission to use, copy, modify, and/or distribute this software for any purpose with or without +// fee is hereby granted, provided that the above copyright notice and this permission notice +// appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +// SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +// OF THIS SOFTWARE. +//! An implementation of random number generators based on `rdrand` and `rdseed` instructions. +//! +//! The random number generators provided by this crate are fairly slow (the latency for these +//! instructions is pretty high), but provide high quality random bits. Caveat is: neither AMD’s +//! nor Intel’s designs are public and therefore are not verifiable for lack of backdoors. +//! +//! Unless you know what you are doing, use the random number generators provided by the `rand` +//! crate (such as `OsRng`) instead. +//! +//! Here are a measurements for select processor architectures. Check [Agner’s instruction tables] +//! for up-to-date listings. +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//! +//!
ArchitectureLatency (cycles)Maximum throughput (per core)
u16u32u64
AMD Ryzen~1200~1200~2500~12MB/s @ 3.7GHz
Intel Skylake460460460~72MB/s @ 4.2GHz
Intel Haswell320320320~110MB/s @ 4.4GHz
+//! +//! [Agner’s instruction tables]: http://agner.org/optimize/ +#![cfg_attr(not(feature = "std"), no_std)] + +extern crate rand_core; + +#[cfg(feature = "std")] +extern crate core; + +pub mod changelog; + +use rand_core::{RngCore, CryptoRng, Error, ErrorKind}; +use core::slice; + +const RETRY_LIMIT: u8 = 127; + +#[cold] +#[inline(never)] +pub(crate) fn busy_loop_fail() -> ! { + panic!("hardware generator failure"); +} + +/// A cryptographically secure statistically uniform, non-periodic and non-deterministic random bit +/// generator. +/// +/// Note that this generator may be implemented using a deterministic algorithm that is reseeded +/// routinely from a non-deterministic entropy source to achieve the desirable properties. +/// +/// This generator is a viable replacement to any generator, however, since nobody has audited +/// Intel or AMD hardware yet, the usual disclaimers as to their suitability apply. +/// +/// It is potentially faster than `OsRng`, but is only supported on more recent Intel (Ivy Bridge +/// and later) and AMD (Ryzen and later) processors. +#[derive(Clone, Copy)] +pub struct RdRand(()); + +/// A cryptographically secure non-deterministic random bit generator. +/// +/// This generator produces high-entropy output and is suited to seed other pseudo-random +/// generators. +/// +/// This instruction currently is only available in Intel Broadwell (and later) and AMD Ryzen +/// processors. +/// +/// This generator is not intended for general random number generation purposes and should be used +/// to seed other generators implementing [rand_core::SeedableRng]. +#[derive(Clone, Copy)] +pub struct RdSeed(()); + +impl CryptoRng for RdRand {} +impl CryptoRng for RdSeed {} + +mod arch { + #[cfg(target_arch = "x86_64")] + pub use core::arch::x86_64::*; + #[cfg(target_arch = "x86")] + pub use core::arch::x86::*; + + #[cfg(target_arch = "x86")] + pub(crate) unsafe fn _rdrand64_step(dest: &mut u64) -> i32 { + let mut ret1: u32 = ::core::mem::uninitialized(); + let mut ret2: u32 = ::core::mem::uninitialized(); + if _rdrand32_step(&mut ret1) != 0 && _rdrand32_step(&mut ret2) != 0 { + *dest = (ret1 as u64) << 32 | (ret2 as u64); + 1 + } else { + 0 + } + } + + #[cfg(target_arch = "x86")] + pub(crate) unsafe fn _rdseed64_step(dest: &mut u64) -> i32 { + let mut ret1: u32 = ::core::mem::uninitialized(); + let mut ret2: u32 = ::core::mem::uninitialized(); + if _rdseed32_step(&mut ret1) != 0 && _rdseed32_step(&mut ret2) != 0 { + *dest = (ret1 as u64) << 32 | (ret2 as u64); + 1 + } else { + 0 + } + } +} + +#[cfg(not(feature = "std"))] +macro_rules! is_x86_feature_detected { + ("rdrand") => {{ + if cfg!(target_feature="rdrand") { + true + } else if cfg!(target_env = "sgx") { + false + } else { + const FLAG : u32 = 1 << 30; + unsafe { ::arch::__cpuid(1).ecx & FLAG == FLAG } + } + }}; + ("rdseed") => {{ + if cfg!(target_feature = "rdseed") { + true + } else if cfg!(target_env = "sgx") { + false + } else { + const FLAG : u32 = 1 << 18; + unsafe { ::arch::__cpuid(7).ebx & FLAG == FLAG } + } + }}; +} + +macro_rules! loop_rand { + ($el: ty, $step: path) => { { + let mut idx = 0; + loop { + let mut el: $el = ::core::mem::uninitialized(); + if $step(&mut el) != 0 { + break Some(el); + } else if idx == RETRY_LIMIT { + break None; + } + idx += 1; + } + } } +} + +macro_rules! impl_rand { + ($gen:ident, $feat:tt, $step16: path, $step32:path, $step64:path, + maxstep = $maxstep:path, maxty = $maxty: ty) => { + impl $gen { + /// Create a new instance of the random number generator. + /// + /// This constructor checks whether the CPU the program is running on supports the + /// instruction necessary for this generator to operate. If the instruction is not + /// supported, an error is returned. + pub fn new() -> Result { + if is_x86_feature_detected!($feat) { + Ok($gen(())) + } else { + Err(Error::new(rand_core::ErrorKind::Unavailable, + "the instruction is not supported")) + } + } + + /// Generate a single random `u16` value. + /// + /// The underlying instruction may fail for variety reasons (such as actual hardware + /// failure or exhausted entropy), however the exact reason for the failure is not + /// usually exposed. + /// + /// This method will retry calling the instruction a few times, however if all the + /// attempts fail, it will return `None`. + /// + /// In case `None` is returned, the caller should assume that an non-recoverable + /// hardware failure has occured and use another random number genrator instead. + #[inline(always)] + pub fn try_next_u16(&self) -> Option { + #[target_feature(enable = $feat)] + unsafe fn imp() + -> Option { + loop_rand!(u16, $step16) + } + unsafe { imp() } + } + + /// Generate a single random `u32` value. + /// + /// The underlying instruction may fail for variety reasons (such as actual hardware + /// failure or exhausted entropy), however the exact reason for the failure is not + /// usually exposed. + /// + /// This method will retry calling the instruction a few times, however if all the + /// attempts fail, it will return `None`. + /// + /// In case `None` is returned, the caller should assume that an non-recoverable + /// hardware failure has occured and use another random number genrator instead. + #[inline(always)] + pub fn try_next_u32(&self) -> Option { + #[target_feature(enable = $feat)] + unsafe fn imp() + -> Option { + loop_rand!(u32, $step32) + } + unsafe { imp() } + } + + /// Generate a single random `u64` value. + /// + /// The underlying instruction may fail for variety reasons (such as actual hardware + /// failure or exhausted entropy), however the exact reason for the failure is not + /// usually exposed. + /// + /// This method will retry calling the instruction a few times, however if all the + /// attempts fail, it will return `None`. + /// + /// In case `None` is returned, the caller should assume that an non-recoverable + /// hardware failure has occured and use another random number genrator instead. + /// + /// Note, that on 32-bit targets, there’s no underlying instruction to generate a + /// 64-bit number, so it is emulated with the 32-bit version of the instruction. + #[inline(always)] + pub fn try_next_u64(&self) -> Option { + #[target_feature(enable = $feat)] + unsafe fn imp() + -> Option { + loop_rand!(u64, $step64) + } + unsafe { imp() } + } + } + + impl RngCore for $gen { + /// Generate a single random `u32` value. + /// + /// The underlying instruction may fail for variety reasons (such as actual hardware + /// failure or exhausted entropy), however the exact reason for the failure is not + /// usually exposed. + /// + /// # Panic + /// + /// This method will retry calling the instruction a few times, however if all the + /// attempts fail, it will `panic`. + /// + /// In case `panic` occurs, the caller should assume that an non-recoverable + /// hardware failure has occured and use another random number genrator instead. + #[inline(always)] + fn next_u32(&mut self) -> u32 { + if let Some(result) = self.try_next_u32() { + result + } else { + busy_loop_fail() + } + } + + /// Generate a single random `u64` value. + /// + /// The underlying instruction may fail for variety reasons (such as actual hardware + /// failure or exhausted entropy), however the exact reason for the failure is not + /// usually exposed. + /// + /// Note, that on 32-bit targets, there’s no underlying instruction to generate a + /// 64-bit number, so it is emulated with the 32-bit version of the instruction. + /// + /// # Panic + /// + /// This method will retry calling the instruction a few times, however if all the + /// attempts fail, it will `panic`. + /// + /// In case `panic` occurs, the caller should assume that an non-recoverable + /// hardware failure has occured and use another random number genrator instead. + #[inline(always)] + fn next_u64(&mut self) -> u64 { + if let Some(result) = self.try_next_u64() { + result + } else { + busy_loop_fail() + } + } + + /// Fill a buffer `dest` with random data. + /// + /// See `try_fill_bytes` for a more extensive documentation. + /// + /// # Panic + /// + /// This method will panic any time `try_fill_bytes` would return an error. + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + if let Err(_) = self.try_fill_bytes(dest) { + busy_loop_fail() + } + } + + /// Fill a buffer `dest` with random data. + /// + /// This method will use the most appropriate variant of the instruction available on + /// the machine to achieve the greatest single-core throughput, however it has a + /// slightly higher setup cost than the plain `next_u32` or `next_u64` methods. + /// + /// The underlying instruction may fail for variety reasons (such as actual hardware + /// failure or exhausted entropy), however the exact reason for the failure is not + /// usually exposed. + /// + /// This method will retry calling the instruction a few times, however if all the + /// attempts fail, it will return an error. + /// + /// If an error is returned, the caller should assume that an non-recoverable hardware + /// failure has occured and use another random number genrator instead. + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) + -> Result<(), Error> { + #[target_feature(enable = $feat)] + unsafe fn imp(dest: &mut [u8]) + -> Result<(), Error> + { + unsafe fn imp_less_fast(mut dest: &mut [u8], word: &mut $maxty, + buffer: &mut &[u8]) + -> Result<(), Error> + { + while !dest.is_empty() { + if buffer.is_empty() { + if let Some(w) = loop_rand!($maxty, $maxstep) { + *word = w; + *buffer = slice::from_raw_parts( + word as *const _ as *const u8, + ::core::mem::size_of::<$maxty>() + ); + } else { + return Err(Error::new(ErrorKind::Unexpected, + "hardware generator failure")); + } + } + + let len = dest.len().min(buffer.len()); + let (copy_src, leftover) = buffer.split_at(len); + let (copy_dest, dest_leftover) = { dest }.split_at_mut(len); + *buffer = leftover; + dest = dest_leftover; + ::core::ptr::copy_nonoverlapping( + copy_src.as_ptr(), copy_dest.as_mut_ptr(), len + ); + } + Ok(()) + } + + let destlen = dest.len(); + if destlen > ::core::mem::size_of::<$maxty>() { + let (left, mid, right) = dest.align_to_mut(); + let mut word = 0; + let mut buffer: &[u8] = &[]; + + for el in mid { + if let Some(val) = loop_rand!($maxty, $maxstep) { + *el = val; + } else { + return Err(Error::new(ErrorKind::Unexpected, + "hardware generator failure")); + } + } + + imp_less_fast(left, &mut word, &mut buffer)?; + imp_less_fast(right, &mut word, &mut buffer) + } else { + let mut word = 0; + let mut buffer: &[u8] = &[]; + imp_less_fast(dest, &mut word, &mut buffer) + } + } + unsafe { imp(dest) } + } + } + } +} + +#[cfg(target_arch = "x86_64")] +impl_rand!(RdRand, "rdrand", + ::arch::_rdrand16_step, ::arch::_rdrand32_step, ::arch::_rdrand64_step, + maxstep = ::arch::_rdrand64_step, maxty = u64); +#[cfg(target_arch = "x86_64")] +impl_rand!(RdSeed, "rdseed", + ::arch::_rdseed16_step, ::arch::_rdseed32_step, ::arch::_rdseed64_step, + maxstep = ::arch::_rdseed64_step, maxty = u64); +#[cfg(target_arch = "x86")] +impl_rand!(RdRand, "rdrand", + ::arch::_rdrand16_step, ::arch::_rdrand32_step, ::arch::_rdrand64_step, + maxstep = ::arch::_rdrand32_step, maxty = u32); +#[cfg(target_arch = "x86")] +impl_rand!(RdSeed, "rdseed", + ::arch::_rdseed16_step, ::arch::_rdseed32_step, ::arch::_rdseed64_step, + maxstep = ::arch::_rdseed32_step, maxty = u32); + +#[test] +fn rdrand_works() { + let _ = RdRand::new().map(|mut r| { + r.next_u32(); + r.next_u64(); + }); +} + +#[test] +fn fill_fills_all_bytes() { + let _ = RdRand::new().map(|mut r| { + let mut peach; + let mut banana; + let mut start = 0; + let mut end = 128; + 'outer: while start < end { + banana = [0; 128]; + for _ in 0..512 { + peach = [0; 128]; + r.fill_bytes(&mut peach[start..end]); + for (b, p) in banana.iter_mut().zip(peach.iter()) { + *b = *b | *p; + } + if (&banana[start..end]).iter().all(|x| *x != 0) { + assert!(banana[..start].iter().all(|x| *x == 0), "all other values must be 0"); + assert!(banana[end..].iter().all(|x| *x == 0), "all other values must be 0"); + if start < 17 { + start += 1; + } else { + end -= 3; + } + continue 'outer; + } + } + panic!("wow, we broke it? {} {} {:?}", start, end, &banana[..]) + } + }); +} + +#[test] +fn rdseed_works() { + let _ = RdSeed::new().map(|mut r| { + r.next_u32(); + r.next_u64(); + }); +} diff --git a/bash-5.1/vendor/regex-syntax/.cargo-checksum.json b/bash-5.1/vendor/regex-syntax/.cargo-checksum.json new file mode 100644 index 0000000..c59e211 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"315907546da5d3fca2b21dce17b556b895b436b720230b4317d017492d41bdb2","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","benches/bench.rs":"4d09c75f457459f850877ee334a924f331c701a22fa19b1f7942c3504c8981f4","src/ast/mod.rs":"31825eaa0fdc0ae9939cf118f07c9a3ce7c0485065e0646df353a2d310ae5cd8","src/ast/parse.rs":"6debdde5c4725a74190d12d2a461893010a1d8c902f37a1d67eaf501d63ce340","src/ast/print.rs":"1b3f82fd5a7fccdfd3fd4ee77ba0430b78549089d8028a0ba83e40403ec795d1","src/ast/visitor.rs":"61223b70e39d92505a93bbd5824f0ce85ac4d4ca683dd56ea27592adf2580982","src/either.rs":"1758e3edd056884eccadd995708d1e374ba9aa65846bd0e13b1aae852607c560","src/error.rs":"3084e5d4a33f92204012c83489745a6f4450c465ac8a79d19a19196ca86abd04","src/hir/interval.rs":"3c2599c9c07149afb0770eca720ab66ed9599402ee58b34bf6709eac4c895239","src/hir/literal/mod.rs":"c2d3f38587ead57fa846ae343686fed40d42b8e0acb7e894f288e41ba8b29ddc","src/hir/mod.rs":"07bdd0dc1c7c60194ab8a3242cb2fe58d5b51ba36d303d495dcd394726ea469e","src/hir/print.rs":"1e6a41bd54a6e2945691d1143c30e867cb1a17a749385e76de1057247345e04d","src/hir/translate.rs":"0a7fc73840f16c6966df2284d420f94f0fd0d260fc1fb2ff240e1af3481682cd","src/hir/visitor.rs":"6a88bf5561c276187eef6f322404a6c50874df33aff165dbd5a107f77df89467","src/lib.rs":"826ed23bb4f518d0fe80b8b66f516438123f5bcabed87b704275c21ae3a77f88","src/parser.rs":"c388ef87e93b8e6e4cb29da8423031e7387bc6197763ddff8cdf4769ec3e0101","src/unicode.rs":"8c9d6e11a8a262f4f3af85769975b3d2466fc6eeae39abc48d5e833e6c14a190","src/unicode_tables/age.rs":"29519a86a3fc9dc600e3b4d102e8708b45917e89c8f8418706c8f451781f795a","src/unicode_tables/case_folding_simple.rs":"426a08a04bcd250ef2825bd718245ef5e7d5ba0500b436ab86bff84507293955","src/unicode_tables/general_category.rs":"bc9781e1cbaafdaa14ad54942a19d75d6e7cb9d4cc39dce076f898f1da865fcd","src/unicode_tables/mod.rs":"c395afbe606c4a9ef8656cd315b1ce2d5c1729fd60c99da8c6d661c49c47adf4","src/unicode_tables/perl_word.rs":"e2accaa8ed515374c1b32e8b854a57b3e20b9fc8b9e293d972913de3cc4d4234","src/unicode_tables/property_bool.rs":"7babe7f5737f6418709072f68aa7cc5c5e807cee14c05b30bf735efb6b9fb36a","src/unicode_tables/property_names.rs":"1427ee7831f2ccd6504714474408907a5ae1c20d7f85c4e0733b72ef56b4e867","src/unicode_tables/property_values.rs":"596f6f6c4fba90552357dfa133d16a0055eef45da9b50121d91035dd0a6404c6","src/unicode_tables/script.rs":"013b630faa01389e096bd3428186206c616dd9a9591cb94e78cc16c19354e2c6","src/unicode_tables/script_extension.rs":"d43169d6351a884a0dbe67255a26007dcb01966994444e33ab24083dcf31f30c"},"package":"7d707a4fa2637f2dca2ef9fd02225ec7661fe01a53623c1e6515b6916511f7a7"} \ No newline at end of file diff --git a/bash-5.1/vendor/regex-syntax/Cargo.toml b/bash-5.1/vendor/regex-syntax/Cargo.toml new file mode 100644 index 0000000..10c2ca6 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/Cargo.toml @@ -0,0 +1,23 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "regex-syntax" +version = "0.5.6" +authors = ["The Rust Project Developers"] +description = "A regular expression parser." +homepage = "https://github.com/rust-lang/regex" +documentation = "https://docs.rs/regex-syntax" +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/regex" +[dependencies.ucd-util] +version = "0.1.0" diff --git a/bash-5.1/vendor/regex-syntax/LICENSE-APACHE b/bash-5.1/vendor/regex-syntax/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/regex-syntax/LICENSE-MIT b/bash-5.1/vendor/regex-syntax/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/regex-syntax/benches/bench.rs b/bash-5.1/vendor/regex-syntax/benches/bench.rs new file mode 100644 index 0000000..60aea9e --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/benches/bench.rs @@ -0,0 +1,73 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(test)] + +extern crate regex_syntax; +extern crate test; + +use regex_syntax::Parser; +use test::Bencher; + +#[bench] +fn parse_simple1(b: &mut Bencher) { + b.iter(|| { + let re = r"^bc(d|e)*$"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_simple2(b: &mut Bencher) { + b.iter(|| { + let re = r"'[a-zA-Z_][a-zA-Z0-9_]*(')\b"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_small1(b: &mut Bencher) { + b.iter(|| { + let re = r"\p{L}|\p{N}|\s|.|\d"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_medium1(b: &mut Bencher) { + b.iter(|| { + let re = r"\pL\p{Greek}\p{Hiragana}\p{Alphabetic}\p{Hebrew}\p{Arabic}"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_medium2(b: &mut Bencher) { + b.iter(|| { + let re = r"\s\S\w\W\d\D"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_medium3(b: &mut Bencher) { + b.iter(|| { + let re = r"\p{age:3.2}\p{hira}\p{scx:hira}\p{alphabetic}\p{sc:Greek}\pL"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_huge(b: &mut Bencher) { + b.iter(|| { + let re = r"\p{L}{100}"; + Parser::new().parse(re).unwrap() + }); +} diff --git a/bash-5.1/vendor/regex-syntax/src/ast/mod.rs b/bash-5.1/vendor/regex-syntax/src/ast/mod.rs new file mode 100644 index 0000000..884fcfa --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/ast/mod.rs @@ -0,0 +1,1515 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Defines an abstract syntax for regular expressions. +*/ + +use std::cmp::Ordering; +use std::error; +use std::fmt; + +pub use ast::visitor::{Visitor, visit}; + +pub mod parse; +pub mod print; +mod visitor; + +/// An error that occurred while parsing a regular expression into an abstract +/// syntax tree. +/// +/// Note that note all ASTs represents a valid regular expression. For example, +/// an AST is constructed without error for `\p{Quux}`, but `Quux` is not a +/// valid Unicode property name. That particular error is reported when +/// translating an AST to the high-level intermediate representation (`HIR`). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Error { + /// The kind of error. + kind: ErrorKind, + /// The original pattern that the parser generated the error from. Every + /// span in an error is a valid range into this string. + pattern: String, + /// The span of this error. + span: Span, +} + +impl Error { + /// Return the type of this error. + pub fn kind(&self) -> &ErrorKind { + &self.kind + } + + /// The original pattern string in which this error occurred. + /// + /// Every span reported by this error is reported in terms of this string. + pub fn pattern(&self) -> &str { + &self.pattern + } + + /// Return the span at which this error occurred. + pub fn span(&self) -> &Span { + &self.span + } + + /// Return an auxiliary span. This span exists only for some errors that + /// benefit from being able to point to two locations in the original + /// regular expression. For example, "duplicate" errors will have the + /// main error position set to the duplicate occurrence while its + /// auxiliary span will be set to the initial occurrence. + pub fn auxiliary_span(&self) -> Option<&Span> { + use self::ErrorKind::*; + match self.kind { + FlagDuplicate { ref original } => Some(original), + FlagRepeatedNegation { ref original, .. } => Some(original), + GroupNameDuplicate { ref original, .. } => Some(original), + _ => None, + } + } +} + +/// The type of an error that occurred while building an AST. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ErrorKind { + /// The capturing group limit was exceeded. + /// + /// Note that this represents a limit on the total number of capturing + /// groups in a regex and not necessarily the number of nested capturing + /// groups. That is, the nest limit can be low and it is still possible for + /// this error to occur. + CaptureLimitExceeded, + /// An invalid escape sequence was found in a character class set. + ClassEscapeInvalid, + /// An invalid character class range was found. An invalid range is any + /// range where the start is greater than the end. + ClassRangeInvalid, + /// An invalid range boundary was found in a character class. Range + /// boundaries must be a single literal codepoint, but this error indicates + /// that something else was found, such as a nested class. + ClassRangeLiteral, + /// An opening `[` was found with no corresponding closing `]`. + ClassUnclosed, + /// An empty decimal number was given where one was expected. + DecimalEmpty, + /// An invalid decimal number was given where one was expected. + DecimalInvalid, + /// A bracketed hex literal was empty. + EscapeHexEmpty, + /// A bracketed hex literal did not correspond to a Unicode scalar value. + EscapeHexInvalid, + /// An invalid hexadecimal digit was found. + EscapeHexInvalidDigit, + /// EOF was found before an escape sequence was completed. + EscapeUnexpectedEof, + /// An unrecognized escape sequence. + EscapeUnrecognized, + /// A dangling negation was used when setting flags, e.g., `i-`. + FlagDanglingNegation, + /// A flag was used twice, e.g., `i-i`. + FlagDuplicate { + /// The position of the original flag. The error position + /// points to the duplicate flag. + original: Span, + }, + /// The negation operator was used twice, e.g., `-i-s`. + FlagRepeatedNegation { + /// The position of the original negation operator. The error position + /// points to the duplicate negation operator. + original: Span, + }, + /// Expected a flag but got EOF, e.g., `(?`. + FlagUnexpectedEof, + /// Unrecognized flag, e.g., `a`. + FlagUnrecognized, + /// A duplicate capture name was found. + GroupNameDuplicate { + /// The position of the initial occurrence of the capture name. The + /// error position itself points to the duplicate occurrence. + original: Span, + }, + /// A capture group name is empty, e.g., `(?P<>abc)`. + GroupNameEmpty, + /// An invalid character was seen for a capture group name. This includes + /// errors where the first character is a digit (even though subsequent + /// characters are allowed to be digits). + GroupNameInvalid, + /// A closing `>` could not be found for a capture group name. + GroupNameUnexpectedEof, + /// An unclosed group, e.g., `(ab`. + /// + /// The span of this error corresponds to the unclosed parenthesis. + GroupUnclosed, + /// An unopened group, e.g., `ab)`. + GroupUnopened, + /// The nest limit was exceeded. The limit stored here is the limit + /// configured in the parser. + NestLimitExceeded(u32), + /// The range provided in a counted repetition operator is invalid. The + /// range is invalid if the start is greater than the end. + RepetitionCountInvalid, + /// An opening `{` was found with no corresponding closing `}`. + RepetitionCountUnclosed, + /// A repetition operator was applied to a missing sub-expression. This + /// occurs, for example, in the regex consisting of just a `*` or even + /// `(?i)*`. It is, however, possible to create a repetition operating on + /// an empty sub-expression. For example, `()*` is still considered valid. + RepetitionMissing, + /// When octal support is disabled, this error is produced when an octal + /// escape is used. The octal escape is assumed to be an invocation of + /// a backreference, which is the common case. + UnsupportedBackreference, + /// When syntax similar to PCRE's look-around is used, this error is + /// returned. Some example syntaxes that are rejected include, but are + /// not necessarily limited to, `(?=re)`, `(?!re)`, `(?<=re)` and + /// `(? &str { + use self::ErrorKind::*; + match self.kind { + CaptureLimitExceeded => "capture group limit exceeded", + ClassEscapeInvalid => "invalid escape sequence in character class", + ClassRangeInvalid => "invalid character class range", + ClassRangeLiteral => "invalid range boundary, must be a literal", + ClassUnclosed => "unclosed character class", + DecimalEmpty => "empty decimal literal", + DecimalInvalid => "invalid decimal literal", + EscapeHexEmpty => "empty hexadecimal literal", + EscapeHexInvalid => "invalid hexadecimal literal", + EscapeHexInvalidDigit => "invalid hexadecimal digit", + EscapeUnexpectedEof => "unexpected eof (escape sequence)", + EscapeUnrecognized => "unrecognized escape sequence", + FlagDanglingNegation => "dangling flag negation operator", + FlagDuplicate{..} => "duplicate flag", + FlagRepeatedNegation{..} => "repeated negation", + FlagUnexpectedEof => "unexpected eof (flag)", + FlagUnrecognized => "unrecognized flag", + GroupNameDuplicate{..} => "duplicate capture group name", + GroupNameEmpty => "empty capture group name", + GroupNameInvalid => "invalid capture group name", + GroupNameUnexpectedEof => "unclosed capture group name", + GroupUnclosed => "unclosed group", + GroupUnopened => "unopened group", + NestLimitExceeded(_) => "nest limit exceeded", + RepetitionCountInvalid => "invalid repetition count range", + RepetitionCountUnclosed => "unclosed counted repetition", + RepetitionMissing => "repetition operator missing expression", + UnsupportedBackreference => "backreferences are not supported", + UnsupportedLookAround => "look-around is not supported", + _ => unreachable!(), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::error::Formatter::from(self).fmt(f) + } +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::ErrorKind::*; + match *self { + CaptureLimitExceeded => { + write!(f, "exceeded the maximum number of \ + capturing groups ({})", ::std::u32::MAX) + } + ClassEscapeInvalid => { + write!(f, "invalid escape sequence found in character class") + } + ClassRangeInvalid => { + write!(f, "invalid character class range, \ + the start must be <= the end") + } + ClassRangeLiteral => { + write!(f, "invalid range boundary, must be a literal") + } + ClassUnclosed => { + write!(f, "unclosed character class") + } + DecimalEmpty => { + write!(f, "decimal literal empty") + } + DecimalInvalid => { + write!(f, "decimal literal invalid") + } + EscapeHexEmpty => { + write!(f, "hexadecimal literal empty") + } + EscapeHexInvalid => { + write!(f, "hexadecimal literal is not a Unicode scalar value") + } + EscapeHexInvalidDigit => { + write!(f, "invalid hexadecimal digit") + } + EscapeUnexpectedEof => { + write!(f, "incomplete escape sequence, \ + reached end of pattern prematurely") + } + EscapeUnrecognized => { + write!(f, "unrecognized escape sequence") + } + FlagDanglingNegation => { + write!(f, "dangling flag negation operator") + } + FlagDuplicate{..} => { + write!(f, "duplicate flag") + } + FlagRepeatedNegation{..} => { + write!(f, "flag negation operator repeated") + } + FlagUnexpectedEof => { + write!(f, "expected flag but got end of regex") + } + FlagUnrecognized => { + write!(f, "unrecognized flag") + } + GroupNameDuplicate{..} => { + write!(f, "duplicate capture group name") + } + GroupNameEmpty => { + write!(f, "empty capture group name") + } + GroupNameInvalid => { + write!(f, "invalid capture group character") + } + GroupNameUnexpectedEof => { + write!(f, "unclosed capture group name") + } + GroupUnclosed => { + write!(f, "unclosed group") + } + GroupUnopened => { + write!(f, "unopened group") + } + NestLimitExceeded(limit) => { + write!(f, "exceed the maximum number of \ + nested parentheses/brackets ({})", limit) + } + RepetitionCountInvalid => { + write!(f, "invalid repetition count range, \ + the start must be <= the end") + } + RepetitionCountUnclosed => { + write!(f, "unclosed counted repetition") + } + RepetitionMissing => { + write!(f, "repetition operator missing expression") + } + UnsupportedBackreference => { + write!(f, "backreferences are not supported") + } + UnsupportedLookAround => { + write!(f, "look-around, including look-ahead and look-behind, \ + is not supported") + } + _ => unreachable!(), + } + } +} + +/// Span represents the position information of a single AST item. +/// +/// All span positions are absolute byte offsets that can be used on the +/// original regular expression that was parsed. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Span { + /// The start byte offset. + pub start: Position, + /// The end byte offset. + pub end: Position, +} + +impl fmt::Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Span({:?}, {:?})", self.start, self.end) + } +} + +impl Ord for Span { + fn cmp(&self, other: &Span) -> Ordering { + (&self.start, &self.end).cmp(&(&other.start, &other.end)) + } +} + +impl PartialOrd for Span { + fn partial_cmp(&self, other: &Span) -> Option { + Some(self.cmp(other)) + } +} + +/// A single position in a regular expression. +/// +/// A position encodes one half of a span, and include the byte offset, line +/// number and column number. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Position { + /// The absolute offset of this position, starting at `0` from the + /// beginning of the regular expression pattern string. + pub offset: usize, + /// The line number, starting at `1`. + pub line: usize, + /// The approximate column number, starting at `1`. + pub column: usize, +} + +impl fmt::Debug for Position { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "Position(o: {:?}, l: {:?}, c: {:?})", + self.offset, self.line, self.column) + } +} + +impl Ord for Position { + fn cmp(&self, other: &Position) -> Ordering { + self.offset.cmp(&other.offset) + } +} + +impl PartialOrd for Position { + fn partial_cmp(&self, other: &Position) -> Option { + Some(self.cmp(other)) + } +} + +impl Span { + /// Create a new span with the given positions. + pub fn new(start: Position, end: Position) -> Span { + Span { start: start, end: end } + } + + /// Create a new span using the given position as the start and end. + pub fn splat(pos: Position) -> Span { + Span::new(pos, pos) + } + + /// Create a new span by replacing the starting the position with the one + /// given. + pub fn with_start(self, pos: Position) -> Span { + Span { start: pos, ..self } + } + + /// Create a new span by replacing the ending the position with the one + /// given. + pub fn with_end(self, pos: Position) -> Span { + Span { end: pos, ..self } + } + + /// Returns true if and only if this span occurs on a single line. + pub fn is_one_line(&self) -> bool { + self.start.line == self.end.line + } + + /// Returns true if and only if this span is empty. That is, it points to + /// a single position in the concrete syntax of a regular expression. + pub fn is_empty(&self) -> bool { + self.start.offset == self.end.offset + } +} + +impl Position { + /// Create a new position with the given information. + /// + /// `offset` is the absolute offset of the position, starting at `0` from + /// the beginning of the regular expression pattern string. + /// + /// `line` is the line number, starting at `1`. + /// + /// `column` is the approximate column number, starting at `1`. + pub fn new(offset: usize, line: usize, column: usize) -> Position { + Position { offset: offset, line: line, column: column } + } +} + +/// An abstract syntax tree for a singular expression along with comments +/// found. +/// +/// Comments are not stored in the tree itself to avoid complexity. Each +/// comment contains a span of precisely where it occurred in the original +/// regular expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct WithComments { + /// The actual ast. + pub ast: Ast, + /// All comments found in the original regular expression. + pub comments: Vec, +} + +/// A comment from a regular expression with an associated span. +/// +/// A regular expression can only contain comments when the `x` flag is +/// enabled. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Comment { + /// The span of this comment, including the beginning `#` and ending `\n`. + pub span: Span, + /// The comment text, starting with the first character following the `#` + /// and ending with the last character preceding the `\n`. + pub comment: String, +} + +/// An abstract syntax tree for a single regular expression. +/// +/// An `Ast`'s `fmt::Display` implementation uses constant stack space and heap +/// space proportional to the size of the `Ast`. +/// +/// This type defines its own destructor that uses constant stack space and +/// heap space proportional to the size of the `Ast`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Ast { + /// An empty regex that matches everything. + Empty(Span), + /// A set of flags, e.g., `(?is)`. + Flags(SetFlags), + /// A single character literal, which includes escape sequences. + Literal(Literal), + /// The "any character" class. + Dot(Span), + /// A single zero-width assertion. + Assertion(Assertion), + /// A single character class. This includes all forms of character classes + /// except for `.`. e.g., `\d`, `\pN`, `[a-z]` and `[[:alpha:]]`. + Class(Class), + /// A repetition operator applied to an arbitrary regular expression. + Repetition(Repetition), + /// A grouped regular expression. + Group(Group), + /// An alternation of regular expressions. + Alternation(Alternation), + /// A concatenation of regular expressions. + Concat(Concat), +} + +impl Ast { + /// Return the span of this abstract syntax tree. + pub fn span(&self) -> &Span { + match *self { + Ast::Empty(ref span) => span, + Ast::Flags(ref x) => &x.span, + Ast::Literal(ref x) => &x.span, + Ast::Dot(ref span) => span, + Ast::Assertion(ref x) => &x.span, + Ast::Class(ref x) => x.span(), + Ast::Repetition(ref x) => &x.span, + Ast::Group(ref x) => &x.span, + Ast::Alternation(ref x) => &x.span, + Ast::Concat(ref x) => &x.span, + } + } + + /// Return true if and only if this Ast is empty. + pub fn is_empty(&self) -> bool { + match *self { + Ast::Empty(_) => true, + _ => false, + } + } + + /// Returns true if and only if this AST has any (including possibly empty) + /// subexpressions. + fn has_subexprs(&self) -> bool { + match *self { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) => false, + Ast::Class(_) + | Ast::Repetition(_) + | Ast::Group(_) + | Ast::Alternation(_) + | Ast::Concat(_) => true, + } + } +} + +/// Print a display representation of this Ast. +/// +/// This does not preserve any of the original whitespace formatting that may +/// have originally been present in the concrete syntax from which this Ast +/// was generated. +/// +/// This implementation uses constant stack space and heap space proportional +/// to the size of the `Ast`. +impl fmt::Display for Ast { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use ast::print::Printer; + Printer::new().print(self, f) + } +} + +/// An alternation of regular expressions. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Alternation { + /// The span of this alternation. + pub span: Span, + /// The alternate regular expressions. + pub asts: Vec, +} + +impl Alternation { + /// Return this alternation as an AST. + /// + /// If this alternation contains zero ASTs, then Ast::Empty is + /// returned. If this alternation contains exactly 1 AST, then the + /// corresponding AST is returned. Otherwise, Ast::Alternation is returned. + pub fn into_ast(mut self) -> Ast { + match self.asts.len() { + 0 => Ast::Empty(self.span), + 1 => self.asts.pop().unwrap(), + _ => Ast::Alternation(self), + } + } +} + +/// A concatenation of regular expressions. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Concat { + /// The span of this concatenation. + pub span: Span, + /// The concatenation regular expressions. + pub asts: Vec, +} + +impl Concat { + /// Return this concatenation as an AST. + /// + /// If this concatenation contains zero ASTs, then Ast::Empty is + /// returned. If this concatenation contains exactly 1 AST, then the + /// corresponding AST is returned. Otherwise, Ast::Concat is returned. + pub fn into_ast(mut self) -> Ast { + match self.asts.len() { + 0 => Ast::Empty(self.span), + 1 => self.asts.pop().unwrap(), + _ => Ast::Concat(self), + } + } +} + +/// A single literal expression. +/// +/// A literal corresponds to a single Unicode scalar value. Literals may be +/// represented in their literal form, e.g., `a` or in their escaped form, +/// e.g., `\x61`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Literal { + /// The span of this literal. + pub span: Span, + /// The kind of this literal. + pub kind: LiteralKind, + /// The Unicode scalar value corresponding to this literal. + pub c: char, +} + +impl Literal { + /// If this literal was written as a `\x` hex escape, then this returns + /// the corresponding byte value. Otherwise, this returns `None`. + pub fn byte(&self) -> Option { + let short_hex = LiteralKind::HexFixed(HexLiteralKind::X); + if self.c as u32 <= 255 && self.kind == short_hex { + Some(self.c as u8) + } else { + None + } + } +} + +/// The kind of a single literal expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum LiteralKind { + /// The literal is written verbatim, e.g., `a` or `☃`. + Verbatim, + /// The literal is written as an escape because it is punctuation, e.g., + /// `\*` or `\[`. + Punctuation, + /// The literal is written as an octal escape, e.g., `\141`. + Octal, + /// The literal is written as a hex code with a fixed number of digits + /// depending on the type of the escape, e.g., `\x61` or or `\u0061` or + /// `\U00000061`. + HexFixed(HexLiteralKind), + /// The literal is written as a hex code with a bracketed number of + /// digits. The only restriction is that the bracketed hex code must refer + /// to a valid Unicode scalar value. + HexBrace(HexLiteralKind), + /// The literal is written as a specially recognized escape, e.g., `\f` + /// or `\n`. + Special(SpecialLiteralKind), +} + +/// The type of a special literal. +/// +/// A special literal is a special escape sequence recognized by the regex +/// parser, e.g., `\f` or `\n`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SpecialLiteralKind { + /// Bell, spelled `\a` (`\x07`). + Bell, + /// Form feed, spelled `\f` (`\x0C`). + FormFeed, + /// Tab, spelled `\t` (`\x09`). + Tab, + /// Line feed, spelled `\n` (`\x0A`). + LineFeed, + /// Carriage return, spelled `\r` (`\x0D`). + CarriageReturn, + /// Vertical tab, spelled `\v` (`\x0B`). + VerticalTab, + /// Space, spelled `\ ` (`\x20`). Note that this can only appear when + /// parsing in verbose mode. + Space, +} + +/// The type of a Unicode hex literal. +/// +/// Note that all variants behave the same when used with brackets. They only +/// differ when used without brackets in the number of hex digits that must +/// follow. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum HexLiteralKind { + /// A `\x` prefix. When used without brackets, this form is limited to + /// two digits. + X, + /// A `\u` prefix. When used without brackets, this form is limited to + /// four digits. + UnicodeShort, + /// A `\U` prefix. When used without brackets, this form is limited to + /// eight digits. + UnicodeLong, +} + +impl HexLiteralKind { + /// The number of digits that must be used with this literal form when + /// used without brackets. When used with brackets, there is no + /// restriction on the number of digits. + pub fn digits(&self) -> u32 { + match *self { + HexLiteralKind::X => 2, + HexLiteralKind::UnicodeShort => 4, + HexLiteralKind::UnicodeLong => 8, + } + } +} + +/// A single character class expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Class { + /// A Unicode character class, e.g., `\pL` or `\p{Greek}`. + Unicode(ClassUnicode), + /// A perl character class, e.g., `\d` or `\W`. + Perl(ClassPerl), + /// A bracketed character class set, which may contain zero or more + /// character ranges and/or zero or more nested classes. e.g., + /// `[a-zA-Z\pL]`. + Bracketed(ClassBracketed), +} + +impl Class { + /// Return the span of this character class. + pub fn span(&self) -> &Span { + match *self { + Class::Perl(ref x) => &x.span, + Class::Unicode(ref x) => &x.span, + Class::Bracketed(ref x) => &x.span, + } + } +} + +/// A Perl character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassPerl { + /// The span of this class. + pub span: Span, + /// The kind of Perl class. + pub kind: ClassPerlKind, + /// Whether the class is negated or not. e.g., `\d` is not negated but + /// `\D` is. + pub negated: bool, +} + +/// The available Perl character classes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassPerlKind { + /// Decimal numbers. + Digit, + /// Whitespace. + Space, + /// Word characters. + Word, +} + +/// An ASCII character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassAscii { + /// The span of this class. + pub span: Span, + /// The kind of ASCII class. + pub kind: ClassAsciiKind, + /// Whether the class is negated or not. e.g., `[[:alpha:]]` is not negated + /// but `[[:^alpha:]]` is. + pub negated: bool, +} + +/// The available ASCII character classes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassAsciiKind { + /// `[0-9A-Za-z]` + Alnum, + /// `[A-Za-z]` + Alpha, + /// `[\x00-\x7F]` + Ascii, + /// `[ \t]` + Blank, + /// `[\x00-\x1F\x7F]` + Cntrl, + /// `[0-9]` + Digit, + /// `[!-~]` + Graph, + /// `[a-z]` + Lower, + /// `[ -~]` + Print, + /// `[!-/:-@\[-`{-~]` + Punct, + /// `[\t\n\v\f\r ]` + Space, + /// `[A-Z]` + Upper, + /// `[0-9A-Za-z_]` + Word, + /// `[0-9A-Fa-f]` + Xdigit, +} + +impl ClassAsciiKind { + /// Return the corresponding ClassAsciiKind variant for the given name. + /// + /// The name given should correspond to the lowercase version of the + /// variant name. e.g., `cntrl` is the name for `ClassAsciiKind::Cntrl`. + /// + /// If no variant with the corresponding name exists, then `None` is + /// returned. + pub fn from_name(name: &str) -> Option { + use self::ClassAsciiKind::*; + match name { + "alnum" => Some(Alnum), + "alpha" => Some(Alpha), + "ascii" => Some(Ascii), + "blank" => Some(Blank), + "cntrl" => Some(Cntrl), + "digit" => Some(Digit), + "graph" => Some(Graph), + "lower" => Some(Lower), + "print" => Some(Print), + "punct" => Some(Punct), + "space" => Some(Space), + "upper" => Some(Upper), + "word" => Some(Word), + "xdigit" => Some(Xdigit), + _ => None, + } + } +} + +/// A Unicode character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassUnicode { + /// The span of this class. + pub span: Span, + /// Whether this class is negated or not. + /// + /// Note: be careful when using this attribute. This specifically refers + /// to whether the class is written as `\p` or `\P`, where the latter + /// is `negated = true`. However, it also possible to write something like + /// `\P{scx!=Katakana}` which is actually equivalent to + /// `\p{scx=Katakana}` and is therefore not actually negated even though + /// `negated = true` here. To test whether this class is truly negated + /// or not, use the `is_negated` method. + pub negated: bool, + /// The kind of Unicode class. + pub kind: ClassUnicodeKind, +} + +impl ClassUnicode { + /// Returns true if this class has been negated. + /// + /// Note that this takes the Unicode op into account, if it's present. + /// e.g., `is_negated` for `\P{scx!=Katakana}` will return `false`. + pub fn is_negated(&self) -> bool { + match self.kind { + ClassUnicodeKind::NamedValue { + op: ClassUnicodeOpKind::NotEqual, .. + } => !self.negated, + _ => self.negated, + } + } +} + +/// The available forms of Unicode character classes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassUnicodeKind { + /// A one letter abbreviated class, e.g., `\pN`. + OneLetter(char), + /// A binary property, general category or script. The string may be + /// empty. + Named(String), + /// A property name and an associated value. + NamedValue { + /// The type of Unicode op used to associate `name` with `value`. + op: ClassUnicodeOpKind, + /// The property name (which may be empty). + name: String, + /// The property value (which may be empty). + value: String, + }, +} + +/// The type of op used in a Unicode character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassUnicodeOpKind { + /// A property set to a specific value, e.g., `\p{scx=Katakana}`. + Equal, + /// A property set to a specific value using a colon, e.g., + /// `\p{scx:Katakana}`. + Colon, + /// A property that isn't a particular value, e.g., `\p{scx!=Katakana}`. + NotEqual, +} + +impl ClassUnicodeOpKind { + /// Whether the op is an equality op or not. + pub fn is_equal(&self) -> bool { + match *self { + ClassUnicodeOpKind::Equal|ClassUnicodeOpKind::Colon => true, + _ => false, + } + } +} + +/// A bracketed character class, e.g., `[a-z0-9]`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassBracketed { + /// The span of this class. + pub span: Span, + /// Whether this class is negated or not. e.g., `[a]` is not negated but + /// `[^a]` is. + pub negated: bool, + /// The type of this set. A set is either a normal union of things, e.g., + /// `[abc]` or a result of applying set operations, e.g., `[\pL--c]`. + pub kind: ClassSet, +} + +/// A character class set. +/// +/// This type corresponds to the internal structure of a bracketed character +/// class. That is, every bracketed character is one of two types: a union of +/// items (literals, ranges, other bracketed classes) or a tree of binary set +/// operations. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassSet { + /// An item, which can be a single literal, range, nested character class + /// or a union of items. + Item(ClassSetItem), + /// A single binary operation (i.e., &&, -- or ~~). + BinaryOp(ClassSetBinaryOp), +} + +impl ClassSet { + /// Build a set from a union. + pub fn union(ast: ClassSetUnion) -> ClassSet { + ClassSet::Item(ClassSetItem::Union(ast)) + } + + /// Return the span of this character class set. + pub fn span(&self) -> &Span { + match *self { + ClassSet::Item(ref x) => x.span(), + ClassSet::BinaryOp(ref x) => &x.span, + } + } + + /// Return true if and only if this class set is empty. + fn is_empty(&self) -> bool { + match *self { + ClassSet::Item(ClassSetItem::Empty(_)) => true, + _ => false, + } + } +} + +/// A single component of a character class set. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassSetItem { + /// An empty item. + /// + /// Note that a bracketed character class cannot contain a single empty + /// item. Empty items can appear when using one of the binary operators. + /// For example, `[&&]` is the intersection of two empty classes. + Empty(Span), + /// A single literal. + Literal(Literal), + /// A range between two literals. + Range(ClassSetRange), + /// An ASCII character class, e.g., `[:alnum:]` or `[:punct:]`. + Ascii(ClassAscii), + /// A Unicode character class, e.g., `\pL` or `\p{Greek}`. + Unicode(ClassUnicode), + /// A perl character class, e.g., `\d` or `\W`. + Perl(ClassPerl), + /// A bracketed character class set, which may contain zero or more + /// character ranges and/or zero or more nested classes. e.g., + /// `[a-zA-Z\pL]`. + Bracketed(Box), + /// A union of items. + Union(ClassSetUnion), +} + +impl ClassSetItem { + /// Return the span of this character class set item. + pub fn span(&self) -> &Span { + match *self { + ClassSetItem::Empty(ref span) => span, + ClassSetItem::Literal(ref x) => &x.span, + ClassSetItem::Range(ref x) => &x.span, + ClassSetItem::Ascii(ref x) => &x.span, + ClassSetItem::Perl(ref x) => &x.span, + ClassSetItem::Unicode(ref x) => &x.span, + ClassSetItem::Bracketed(ref x) => &x.span, + ClassSetItem::Union(ref x) => &x.span, + } + } +} + +/// A single character class range in a set. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassSetRange { + /// The span of this range. + pub span: Span, + /// The start of this range. + pub start: Literal, + /// The end of this range. + pub end: Literal, +} + +impl ClassSetRange { + /// Returns true if and only if this character class range is valid. + /// + /// The only case where a range is invalid is if its start is greater than + /// its end. + pub fn is_valid(&self) -> bool { + self.start.c <= self.end.c + } +} + +/// A union of items inside a character class set. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassSetUnion { + /// The span of the items in this operation. e.g., the `a-z0-9` in + /// `[^a-z0-9]` + pub span: Span, + /// The sequence of items that make up this union. + pub items: Vec, +} + +impl ClassSetUnion { + /// Push a new item in this union. + /// + /// The ending position of this union's span is updated to the ending + /// position of the span of the item given. If the union is empty, then + /// the starting position of this union is set to the starting position + /// of this item. + /// + /// In other words, if you only use this method to add items to a union + /// and you set the spans on each item correctly, then you should never + /// need to adjust the span of the union directly. + pub fn push(&mut self, item: ClassSetItem) { + if self.items.is_empty() { + self.span.start = item.span().start; + } + self.span.end = item.span().end; + self.items.push(item); + } + + /// Return this union as a character class set item. + /// + /// If this union contains zero items, then an empty union is + /// returned. If this concatenation contains exactly 1 item, then the + /// corresponding item is returned. Otherwise, ClassSetItem::Union is + /// returned. + pub fn into_item(mut self) -> ClassSetItem { + match self.items.len() { + 0 => ClassSetItem::Empty(self.span), + 1 => self.items.pop().unwrap(), + _ => ClassSetItem::Union(self), + } + } +} + +/// A Unicode character class set operation. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassSetBinaryOp { + /// The span of this operation. e.g., the `a-z--[h-p]` in `[a-z--h-p]`. + pub span: Span, + /// The type of this set operation. + pub kind: ClassSetBinaryOpKind, + /// The left hand side of the operation. + pub lhs: Box, + /// The right hand side of the operation. + pub rhs: Box, +} + +/// The type of a Unicode character class set operation. +/// +/// Note that this doesn't explicitly represent union since there is no +/// explicit union operator. Concatenation inside a character class corresponds +/// to the union operation. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ClassSetBinaryOpKind { + /// The intersection of two sets, e.g., `\pN&&[a-z]`. + Intersection, + /// The difference of two sets, e.g., `\pN--[0-9]`. + Difference, + /// The symmetric difference of two sets. The symmetric difference is the + /// set of elements belonging to one but not both sets. + /// e.g., `[\pL~~[:ascii:]]`. + SymmetricDifference, +} + +/// A single zero-width assertion. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Assertion { + /// The span of this assertion. + pub span: Span, + /// The assertion kind, e.g., `\b` or `^`. + pub kind: AssertionKind, +} + +/// An assertion kind. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum AssertionKind { + /// `^` + StartLine, + /// `$` + EndLine, + /// `\A` + StartText, + /// `\z` + EndText, + /// `\b` + WordBoundary, + /// `\B` + NotWordBoundary, +} + +/// A repetition operation applied to a regular expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Repetition { + /// The span of this operation. + pub span: Span, + /// The actual operation. + pub op: RepetitionOp, + /// Whether this operation was applied greedily or not. + pub greedy: bool, + /// The regular expression under repetition. + pub ast: Box, +} + +/// The repetition operator itself. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RepetitionOp { + /// The span of this operator. This includes things like `+`, `*?` and + /// `{m,n}`. + pub span: Span, + /// The type of operation. + pub kind: RepetitionKind, +} + +/// The kind of a repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionKind { + /// `?` + ZeroOrOne, + /// `*` + ZeroOrMore, + /// `+` + OneOrMore, + /// `{m,n}` + Range(RepetitionRange), +} + +/// A range repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionRange { + /// `{m}` + Exactly(u32), + /// `{m,}` + AtLeast(u32), + /// `{m,n}` + Bounded(u32, u32), +} + +impl RepetitionRange { + /// Returns true if and only if this repetition range is valid. + /// + /// The only case where a repetition range is invalid is if it is bounded + /// and its start is greater than its end. + pub fn is_valid(&self) -> bool { + match *self { + RepetitionRange::Bounded(s, e) if s > e => false, + _ => true, + } + } +} + +/// A grouped regular expression. +/// +/// This includes both capturing and non-capturing groups. This does **not** +/// include flag-only groups like `(?is)`, but does contain any group that +/// contains a sub-expression, e.g., `(a)`, `(?Pa)`, `(?:a)` and +/// `(?is:a)`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Group { + /// The span of this group. + pub span: Span, + /// The kind of this group. + pub kind: GroupKind, + /// The regular expression in this group. + pub ast: Box, +} + +impl Group { + /// If this group is non-capturing, then this returns the (possibly empty) + /// set of flags. Otherwise, `None` is returned. + pub fn flags(&self) -> Option<&Flags> { + match self.kind { + GroupKind::NonCapturing(ref flags) => Some(flags), + _ => None, + } + } + + /// Returns true if and only if this group is capturing. + pub fn is_capturing(&self) -> bool { + match self.kind { + GroupKind::CaptureIndex(_) | GroupKind::CaptureName(_) => true, + GroupKind::NonCapturing(_) => false, + } + } + + /// Returns the capture index of this group, if this is a capturing group. + /// + /// This returns a capture index precisely when `is_capturing` is `true`. + pub fn capture_index(&self) -> Option { + match self.kind { + GroupKind::CaptureIndex(i) => Some(i), + GroupKind::CaptureName(ref x) => Some(x.index), + GroupKind::NonCapturing(_) => None, + } + } +} + +/// The kind of a group. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GroupKind { + /// `(a)` + CaptureIndex(u32), + /// `(?Pa)` + CaptureName(CaptureName), + /// `(?:a)` and `(?i:a)` + NonCapturing(Flags), +} + +/// A capture name. +/// +/// This corresponds to the name itself between the angle brackets in, e.g., +/// `(?Pexpr)`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CaptureName { + /// The span of this capture name. + pub span: Span, + /// The capture name. + pub name: String, + /// The capture index. + pub index: u32, +} + +/// A group of flags that is not applied to a particular regular expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SetFlags { + /// The span of these flags, including the grouping parentheses. + pub span: Span, + /// The actual sequence of flags. + pub flags: Flags, +} + +/// A group of flags. +/// +/// This corresponds only to the sequence of flags themselves, e.g., `is-u`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Flags { + /// The span of this group of flags. + pub span: Span, + /// A sequence of flag items. Each item is either a flag or a negation + /// operator. + pub items: Vec, +} + +impl Flags { + /// Add the given item to this sequence of flags. + /// + /// If the item was added successfully, then `None` is returned. If the + /// given item is a duplicate, then `Some(i)` is returned, where + /// `items[i].kind == item.kind`. + pub fn add_item(&mut self, item: FlagsItem) -> Option { + for (i, x) in self.items.iter().enumerate() { + if x.kind == item.kind { + return Some(i); + } + } + self.items.push(item); + None + } + + /// Returns the state of the given flag in this set. + /// + /// If the given flag is in the set but is negated, then `Some(false)` is + /// returned. + /// + /// If the given flag is in the set and is not negated, then `Some(true)` + /// is returned. + /// + /// Otherwise, `None` is returned. + pub fn flag_state(&self, flag: Flag) -> Option { + let mut negated = false; + for x in &self.items { + match x.kind { + FlagsItemKind::Negation => { + negated = true; + } + FlagsItemKind::Flag(ref xflag) if xflag == &flag => { + return Some(!negated); + } + _ => {} + } + } + None + } +} + +/// A single item in a group of flags. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FlagsItem { + /// The span of this item. + pub span: Span, + /// The kind of this item. + pub kind: FlagsItemKind, +} + +/// The kind of an item in a group of flags. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum FlagsItemKind { + /// A negation operator applied to all subsequent flags in the enclosing + /// group. + Negation, + /// A single flag in a group. + Flag(Flag), +} + +impl FlagsItemKind { + /// Returns true if and only if this item is a negation operator. + pub fn is_negation(&self) -> bool { + match *self { + FlagsItemKind::Negation => true, + _ => false, + } + } +} + +/// A single flag. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Flag { + /// `i` + CaseInsensitive, + /// `m` + MultiLine, + /// `s` + DotMatchesNewLine, + /// `U` + SwapGreed, + /// `u` + Unicode, + /// `x` + IgnoreWhitespace, +} + +/// A custom `Drop` impl is used for `Ast` such that it uses constant stack +/// space but heap space proportional to the depth of the `Ast`. +impl Drop for Ast { + fn drop(&mut self) { + use std::mem; + + match *self { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + // Classes are recursive, so they get their own Drop impl. + | Ast::Class(_) => return, + Ast::Repetition(ref x) if !x.ast.has_subexprs() => return, + Ast::Group(ref x) if !x.ast.has_subexprs() => return, + Ast::Alternation(ref x) if x.asts.is_empty() => return, + Ast::Concat(ref x) if x.asts.is_empty() => return, + _ => {} + } + + let empty_span = || Span::splat(Position::new(0, 0, 0)); + let empty_ast = || Ast::Empty(empty_span()); + let mut stack = vec![mem::replace(self, empty_ast())]; + while let Some(mut ast) = stack.pop() { + match ast { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + // Classes are recursive, so they get their own Drop impl. + | Ast::Class(_) => {} + Ast::Repetition(ref mut x) => { + stack.push(mem::replace(&mut x.ast, empty_ast())); + } + Ast::Group(ref mut x) => { + stack.push(mem::replace(&mut x.ast, empty_ast())); + } + Ast::Alternation(ref mut x) => { + stack.extend(x.asts.drain(..)); + } + Ast::Concat(ref mut x) => { + stack.extend(x.asts.drain(..)); + } + } + } + } +} + +/// A custom `Drop` impl is used for `ClassSet` such that it uses constant +/// stack space but heap space proportional to the depth of the `ClassSet`. +impl Drop for ClassSet { + fn drop(&mut self) { + use std::mem; + + match *self { + ClassSet::Item(ref item) => { + match *item { + ClassSetItem::Empty(_) + | ClassSetItem::Literal(_) + | ClassSetItem::Range(_) + | ClassSetItem::Ascii(_) + | ClassSetItem::Unicode(_) + | ClassSetItem::Perl(_) => return, + ClassSetItem::Bracketed(ref x) => { + if x.kind.is_empty() { + return; + } + } + ClassSetItem::Union(ref x) => { + if x.items.is_empty() { + return; + } + } + } + } + ClassSet::BinaryOp(ref op) => { + if op.lhs.is_empty() && op.rhs.is_empty() { + return; + } + } + } + + let empty_span = || Span::splat(Position::new(0, 0, 0)); + let empty_set = || ClassSet::Item(ClassSetItem::Empty(empty_span())); + let mut stack = vec![mem::replace(self, empty_set())]; + while let Some(mut set) = stack.pop() { + match set { + ClassSet::Item(ref mut item) => { + match *item { + ClassSetItem::Empty(_) + | ClassSetItem::Literal(_) + | ClassSetItem::Range(_) + | ClassSetItem::Ascii(_) + | ClassSetItem::Unicode(_) + | ClassSetItem::Perl(_) => {} + ClassSetItem::Bracketed(ref mut x) => { + stack.push(mem::replace(&mut x.kind, empty_set())); + } + ClassSetItem::Union(ref mut x) => { + stack.extend( + x.items.drain(..).map(ClassSet::Item)); + } + } + } + ClassSet::BinaryOp(ref mut op) => { + stack.push(mem::replace(&mut op.lhs, empty_set())); + stack.push(mem::replace(&mut op.rhs, empty_set())); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // We use a thread with an explicit stack size to test that our destructor + // for Ast can handle arbitrarily sized expressions in constant stack + // space. In case we run on a platform without threads (WASM?), we limit + // this test to Windows/Unix. + #[test] + #[cfg(any(unix, windows))] + fn no_stack_overflow_on_drop() { + use std::thread; + + let run = || { + let span = || Span::splat(Position::new(0, 0, 0)); + let mut ast = Ast::Empty(span()); + for i in 0..200 { + ast = Ast::Group(Group { + span: span(), + kind: GroupKind::CaptureIndex(i), + ast: Box::new(ast), + }); + } + assert!(!ast.is_empty()); + }; + + // We run our test on a thread with a small stack size so we can + // force the issue more easily. + thread::Builder::new() + .stack_size(1<<10) + .spawn(run) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/ast/parse.rs b/bash-5.1/vendor/regex-syntax/src/ast/parse.rs new file mode 100644 index 0000000..171dd66 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/ast/parse.rs @@ -0,0 +1,5365 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This module provides a regular expression parser. +*/ + +use std::borrow::Borrow; +use std::cell::{Cell, RefCell}; +use std::mem; +use std::result; + +use ast::{self, Ast, Position, Span}; +use either::Either; + +use is_meta_character; + +type Result = result::Result; + +/// A primitive is an expression with no sub-expressions. This includes +/// literals, assertions and non-set character classes. This representation +/// is used as intermediate state in the parser. +/// +/// This does not include ASCII character classes, since they can only appear +/// within a set character class. +#[derive(Clone, Debug, Eq, PartialEq)] +enum Primitive { + Literal(ast::Literal), + Assertion(ast::Assertion), + Dot(Span), + Perl(ast::ClassPerl), + Unicode(ast::ClassUnicode), +} + +impl Primitive { + /// Return the span of this primitive. + fn span(&self) -> &Span { + match *self { + Primitive::Literal(ref x) => &x.span, + Primitive::Assertion(ref x) => &x.span, + Primitive::Dot(ref span) => span, + Primitive::Perl(ref x) => &x.span, + Primitive::Unicode(ref x) => &x.span, + } + } + + /// Convert this primitive into a proper AST. + fn into_ast(self) -> Ast { + match self { + Primitive::Literal(lit) => Ast::Literal(lit), + Primitive::Assertion(assert) => Ast::Assertion(assert), + Primitive::Dot(span) => Ast::Dot(span), + Primitive::Perl(cls) => Ast::Class(ast::Class::Perl(cls)), + Primitive::Unicode(cls) => Ast::Class(ast::Class::Unicode(cls)), + } + } + + /// Convert this primitive into an item in a character class. + /// + /// If this primitive is not a legal item (i.e., an assertion or a dot), + /// then return an error. + fn into_class_set_item>( + self, + p: &ParserI

, + ) -> Result { + use ast::ClassSetItem; + use self::Primitive::*; + + match self { + Literal(lit) => Ok(ClassSetItem::Literal(lit)), + Perl(cls) => Ok(ClassSetItem::Perl(cls)), + Unicode(cls) => Ok(ClassSetItem::Unicode(cls)), + x => Err(p.error(*x.span(), ast::ErrorKind::ClassEscapeInvalid)), + } + } + + /// Convert this primitive into a literal in a character class. In + /// particular, literals are the only valid items that can appear in + /// ranges. + /// + /// If this primitive is not a legal item (i.e., a class, assertion or a + /// dot), then return an error. + fn into_class_literal>( + self, + p: &ParserI

, + ) -> Result { + use self::Primitive::*; + + match self { + Literal(lit) => Ok(lit), + x => Err(p.error(*x.span(), ast::ErrorKind::ClassRangeLiteral)), + } + } +} + +/// Returns true if the given character is a hexadecimal digit. +fn is_hex(c: char) -> bool { + ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') +} + +/// Returns true if the given character is a valid in a capture group name. +/// +/// If `first` is true, then `c` is treated as the first character in the +/// group name (which is not allowed to be a digit). +fn is_capture_char(c: char, first: bool) -> bool { + c == '_' || (!first && c >= '0' && c <= '9') + || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +/// A builder for a regular expression parser. +/// +/// This builder permits modifying configuration options for the parser. +#[derive(Clone, Debug)] +pub struct ParserBuilder { + ignore_whitespace: bool, + nest_limit: u32, + octal: bool, +} + +impl Default for ParserBuilder { + fn default() -> ParserBuilder { + ParserBuilder::new() + } +} + +impl ParserBuilder { + /// Create a new parser builder with a default configuration. + pub fn new() -> ParserBuilder { + ParserBuilder { + ignore_whitespace: false, + nest_limit: 250, + octal: false, + } + } + + /// Build a parser from this configuration with the given pattern. + pub fn build(&self) -> Parser { + Parser { + pos: Cell::new(Position { offset: 0, line: 1, column: 1 }), + capture_index: Cell::new(0), + nest_limit: self.nest_limit, + octal: self.octal, + initial_ignore_whitespace: self.ignore_whitespace, + ignore_whitespace: Cell::new(self.ignore_whitespace), + comments: RefCell::new(vec![]), + stack_group: RefCell::new(vec![]), + stack_class: RefCell::new(vec![]), + capture_names: RefCell::new(vec![]), + scratch: RefCell::new(String::new()), + } + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut ParserBuilder { + self.nest_limit = limit; + self + } + + /// Whether to support octal syntax or not. + /// + /// Octal syntax is a little-known way of uttering Unicode codepoints in + /// a regular expression. For example, `a`, `\x61`, `\u0061` and + /// `\141` are all equivalent regular expressions, where the last example + /// shows octal syntax. + /// + /// While supporting octal syntax isn't in and of itself a problem, it does + /// make good error messages harder. That is, in PCRE based regex engines, + /// syntax like `\0` invokes a backreference, which is explicitly + /// unsupported in Rust's regex engine. However, many users expect it to + /// be supported. Therefore, when octal support is disabled, the error + /// message will explicitly mention that backreferences aren't supported. + /// + /// Octal syntax is disabled by default. + pub fn octal(&mut self, yes: bool) -> &mut ParserBuilder { + self.octal = yes; + self + } + + /// Enable verbose mode in the regular expression. + /// + /// When enabled, verbose mode permits insigificant whitespace in many + /// places in the regular expression, as well as comments. Comments are + /// started using `#` and continue until the end of the line. + /// + /// By default, this is disabled. It may be selectively enabled in the + /// regular expression by using the `x` flag regardless of this setting. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut ParserBuilder { + self.ignore_whitespace = yes; + self + } +} + +/// A regular expression parser. +/// +/// This parses a string representation of a regular expression into an +/// abstract syntax tree. The size of the tree is proportional to the length +/// of the regular expression pattern. +/// +/// A `Parser` can be configured in more detail via a +/// [`ParserBuilder`](struct.ParserBuilder.html). +#[derive(Clone, Debug)] +pub struct Parser { + /// The current position of the parser. + pos: Cell, + /// The current capture index. + capture_index: Cell, + /// The maximum number of open parens/brackets allowed. If the parser + /// exceeds this number, then an error is returned. + nest_limit: u32, + /// Whether to support octal syntax or not. When `false`, the parser will + /// return an error helpfully pointing out that backreferences are not + /// supported. + octal: bool, + /// The initial setting for `ignore_whitespace` as provided by + /// Th`ParserBuilder`. is is used when reseting the parser's state. + initial_ignore_whitespace: bool, + /// Whether whitespace should be ignored. When enabled, comments are + /// also permitted. + ignore_whitespace: Cell, + /// A list of comments, in order of appearance. + comments: RefCell>, + /// A stack of grouped sub-expressions, including alternations. + stack_group: RefCell>, + /// A stack of nested character classes. This is only non-empty when + /// parsing a class. + stack_class: RefCell>, + /// A sorted sequence of capture names. This is used to detect duplicate + /// capture names and report an error if one is detected. + capture_names: RefCell>, + /// A scratch buffer used in various places. Mostly this is used to + /// accumulate relevant characters from parts of a pattern. + scratch: RefCell, +} + +/// ParserI is the internal parser implementation. +/// +/// We use this separate type so that we can carry the provided pattern string +/// along with us. In particular, a `Parser` internal state is not tied to any +/// one pattern, but `ParserI` is. +/// +/// This type also lets us use `ParserI<&Parser>` in production code while +/// retaining the convenience of `ParserI` for tests, which sometimes +/// work against the internal interface of the parser. +#[derive(Clone, Debug)] +struct ParserI<'s, P> { + /// The parser state/configuration. + parser: P, + /// The full regular expression provided by the user. + pattern: &'s str, +} + +/// GroupState represents a single stack frame while parsing nested groups +/// and alternations. Each frame records the state up to an opening parenthesis +/// or a alternating bracket `|`. +#[derive(Clone, Debug)] +enum GroupState { + /// This state is pushed whenever an opening group is found. + Group { + /// The concatenation immediately preceding the opening group. + concat: ast::Concat, + /// The group that has been opened. Its sub-AST is always empty. + group: ast::Group, + /// Whether this group has the `x` flag enabled or not. + ignore_whitespace: bool, + }, + /// This state is pushed whenever a new alternation branch is found. If + /// an alternation branch is found and this state is at the top of the + /// stack, then this state should be modified to include the new + /// alternation. + Alternation(ast::Alternation), +} + +/// ClassState represents a single stack frame while parsing character classes. +/// Each frame records the state up to an intersection, difference, symmetric +/// difference or nested class. +/// +/// Note that a parser's character class stack is only non-empty when parsing +/// a character class. In all other cases, it is empty. +#[derive(Clone, Debug)] +enum ClassState { + /// This state is pushed whenever an opening bracket is found. + Open { + /// The union of class items immediately preceding this class. + union: ast::ClassSetUnion, + /// The class that has been opened. Typically this just corresponds + /// to the `[`, but it can also include `[^` since `^` indicates + /// negation of the class. + set: ast::ClassBracketed, + }, + /// This state is pushed when a operator is seen. When popped, the stored + /// set becomes the left hand side of the operator. + Op { + /// The type of the operation, i.e., &&, -- or ~~. + kind: ast::ClassSetBinaryOpKind, + /// The left-hand side of the operator. + lhs: ast::ClassSet, + }, +} + +impl Parser { + /// Create a new parser with a default configuration. + /// + /// The parser can be run with either the `parse` or `parse_with_comments` + /// methods. The parse methods return an abstract syntax tree. + /// + /// To set configuration options on the parser, use + /// [`ParserBuilder`](struct.ParserBuilder.html). + pub fn new() -> Parser { + ParserBuilder::new().build() + } + + /// Parse the regular expression into an abstract syntax tree. + pub fn parse(&mut self, pattern: &str) -> Result { + ParserI::new(self, pattern).parse() + } + + /// Parse the regular expression and return an abstract syntax tree with + /// all of the comments found in the pattern. + pub fn parse_with_comments( + &mut self, + pattern: &str, + ) -> Result { + ParserI::new(self, pattern).parse_with_comments() + } + + /// Reset the internal state of a parser. + /// + /// This is called at the beginning of every parse. This prevents the + /// parser from running with inconsistent state (say, if a previous + /// invocation returned an error and the parser is reused). + fn reset(&self) { + // These settings should be in line with the construction + // in `ParserBuilder::build`. + self.pos.set(Position { offset: 0, line: 1, column: 1}); + self.ignore_whitespace.set(self.initial_ignore_whitespace); + self.comments.borrow_mut().clear(); + self.stack_group.borrow_mut().clear(); + self.stack_class.borrow_mut().clear(); + } +} + +impl<'s, P: Borrow> ParserI<'s, P> { + /// Build an internal parser from a parser configuration and a pattern. + fn new(parser: P, pattern: &'s str) -> ParserI<'s, P> { + ParserI { parser: parser, pattern: pattern } + } + + /// Return a reference to the parser state. + fn parser(&self) -> &Parser { + self.parser.borrow() + } + + /// Return a reference to the pattern being parsed. + fn pattern(&self) -> &str { + self.pattern.borrow() + } + + /// Create a new error with the given span and error type. + fn error(&self, span: Span, kind: ast::ErrorKind) -> ast::Error { + ast::Error { + kind: kind, + pattern: self.pattern().to_string(), + span: span, + } + } + + /// Return the current offset of the parser. + /// + /// The offset starts at `0` from the beginning of the regular expression + /// pattern string. + fn offset(&self) -> usize { + self.parser().pos.get().offset + } + + /// Return the current line number of the parser. + /// + /// The line number starts at `1`. + fn line(&self) -> usize { + self.parser().pos.get().line + } + + /// Return the current column of the parser. + /// + /// The column number starts at `1` and is reset whenever a `\n` is seen. + fn column(&self) -> usize { + self.parser().pos.get().column + } + + /// Return the next capturing index. Each subsequent call increments the + /// internal index. + /// + /// The span given should correspond to the location of the opening + /// parenthesis. + /// + /// If the capture limit is exceeded, then an error is returned. + fn next_capture_index(&self, span: Span) -> Result { + let current = self.parser().capture_index.get(); + let i = try!(current.checked_add(1).ok_or_else(|| { + self.error(span, ast::ErrorKind::CaptureLimitExceeded) + })); + self.parser().capture_index.set(i); + Ok(i) + } + + /// Adds the given capture name to this parser. If this capture name has + /// already been used, then an error is returned. + fn add_capture_name(&self, cap: &ast::CaptureName) -> Result<()> { + let mut names = self.parser().capture_names.borrow_mut(); + match names.binary_search_by_key( + &cap.name.as_str(), + |c| c.name.as_str(), + ) { + Err(i) => { + names.insert(i, cap.clone()); + Ok(()) + } + Ok(i) => { + Err(self.error(cap.span, ast::ErrorKind::GroupNameDuplicate { + original: names[i].span, + })) + } + } + } + + /// Return whether the parser should ignore whitespace or not. + fn ignore_whitespace(&self) -> bool { + self.parser().ignore_whitespace.get() + } + + /// Return the character at the current position of the parser. + /// + /// This panics if the current position does not point to a valid char. + fn char(&self) -> char { + self.char_at(self.offset()) + } + + /// Return the character at the given position. + /// + /// This panics if the given position does not point to a valid char. + fn char_at(&self, i: usize) -> char { + self.pattern()[i..].chars().next() + .unwrap_or_else(|| { + panic!("expected char at offset {}", i) + }) + } + + /// Bump the parser to the next Unicode scalar value. + /// + /// If the end of the input has been reached, then `false` is returned. + fn bump(&self) -> bool { + if self.is_eof() { + return false; + } + let Position { mut offset, mut line, mut column } = self.pos(); + if self.char() == '\n' { + line = line.checked_add(1).unwrap(); + column = 1; + } else { + column = column.checked_add(1).unwrap(); + } + offset += self.char().len_utf8(); + self.parser().pos.set(Position { + offset: offset, + line: line, + column: column, + }); + self.pattern()[self.offset()..].chars().next().is_some() + } + + /// If the substring starting at the current position of the parser has + /// the given prefix, then bump the parser to the character immediately + /// following the prefix and return true. Otherwise, don't bump the parser + /// and return false. + fn bump_if(&self, prefix: &str) -> bool { + if self.pattern()[self.offset()..].starts_with(prefix) { + for _ in 0..prefix.chars().count() { + self.bump(); + } + true + } else { + false + } + } + + /// Returns true if and only if the parser is positioned at a look-around + /// prefix. The conditions under which this returns true must always + /// correspond to a regular expression that would otherwise be consider + /// invalid. + /// + /// This should only be called immediately after parsing the opening of + /// a group or a set of flags. + fn is_lookaround_prefix(&self) -> bool { + self.bump_if("?=") + || self.bump_if("?!") + || self.bump_if("?<=") + || self.bump_if("? bool { + if !self.bump() { + return false; + } + self.bump_space(); + !self.is_eof() + } + + /// If the `x` flag is enabled (i.e., whitespace insensitivity with + /// comments), then this will advance the parser through all whitespace + /// and comments to the next non-whitespace non-comment byte. + /// + /// If the `x` flag is disabled, then this is a no-op. + /// + /// This should be used selectively throughout the parser where + /// arbitrary whitespace is permitted when the `x` flag is enabled. For + /// example, `{ 5 , 6}` is equivalent to `{5,6}`. + fn bump_space(&self) { + if !self.ignore_whitespace() { + return; + } + while !self.is_eof() { + if self.char().is_whitespace() { + self.bump(); + } else if self.char() == '#' { + let start = self.pos(); + let mut comment_text = String::new(); + self.bump(); + while !self.is_eof() { + let c = self.char(); + self.bump(); + if c == '\n' { + break; + } + comment_text.push(c); + } + let comment = ast::Comment { + span: Span::new(start, self.pos()), + comment: comment_text, + }; + self.parser().comments.borrow_mut().push(comment); + } else { + break; + } + } + } + + /// Peek at the next character in the input without advancing the parser. + /// + /// If the input has been exhausted, then this returns `None`. + fn peek(&self) -> Option { + if self.is_eof() { + return None; + } + self.pattern()[self.offset() + self.char().len_utf8()..].chars().next() + } + + /// Like peek, but will ignore spaces when the parser is in whitespace + /// insensitive mode. + fn peek_space(&self) -> Option { + if !self.ignore_whitespace() { + return self.peek(); + } + if self.is_eof() { + return None; + } + let mut start = self.offset() + self.char().len_utf8(); + let mut in_comment = false; + for (i, c) in self.pattern()[start..].char_indices() { + if c.is_whitespace() { + continue; + } else if !in_comment && c == '#' { + in_comment = true; + } else if in_comment && c == '\n' { + in_comment = false; + } else { + start += i; + break; + } + } + self.pattern()[start..].chars().next() + } + + /// Returns true if the next call to `bump` would return false. + fn is_eof(&self) -> bool { + self.offset() == self.pattern().len() + } + + /// Return the current position of the parser, which includes the offset, + /// line and column. + fn pos(&self) -> Position { + self.parser().pos.get() + } + + /// Create a span at the current position of the parser. Both the start + /// and end of the span are set. + fn span(&self) -> Span { + Span::splat(self.pos()) + } + + /// Create a span that covers the current character. + fn span_char(&self) -> Span { + let mut next = Position { + offset: self.offset().checked_add(self.char().len_utf8()).unwrap(), + line: self.line(), + column: self.column().checked_add(1).unwrap(), + }; + if self.char() == '\n' { + next.line += 1; + next.column = 1; + } + Span::new(self.pos(), next) + } + + /// Parse and push a single alternation on to the parser's internal stack. + /// If the top of the stack already has an alternation, then add to that + /// instead of pushing a new one. + /// + /// The concatenation given corresponds to a single alternation branch. + /// The concatenation returned starts the next branch and is empty. + /// + /// This assumes the parser is currently positioned at `|` and will advance + /// the parser to the character following `|`. + fn push_alternate(&self, mut concat: ast::Concat) -> Result { + assert_eq!(self.char(), '|'); + concat.span.end = self.pos(); + self.push_or_add_alternation(concat); + self.bump(); + Ok(ast::Concat { + span: self.span(), + asts: vec![], + }) + } + + /// Pushes or adds the given branch of an alternation to the parser's + /// internal stack of state. + fn push_or_add_alternation(&self, concat: ast::Concat) { + use self::GroupState::*; + + let mut stack = self.parser().stack_group.borrow_mut(); + if let Some(&mut Alternation(ref mut alts)) = stack.last_mut() { + alts.asts.push(concat.into_ast()); + return; + } + stack.push(Alternation(ast::Alternation { + span: Span::new(concat.span.start, self.pos()), + asts: vec![concat.into_ast()], + })); + } + + /// Parse and push a group AST (and its parent concatenation) on to the + /// parser's internal stack. Return a fresh concatenation corresponding + /// to the group's sub-AST. + /// + /// If a set of flags was found (with no group), then the concatenation + /// is returned with that set of flags added. + /// + /// This assumes that the parser is currently positioned on the opening + /// parenthesis. It advances the parser to the character at the start + /// of the sub-expression (or adjoining expression). + /// + /// If there was a problem parsing the start of the group, then an error + /// is returned. + fn push_group(&self, mut concat: ast::Concat) -> Result { + assert_eq!(self.char(), '('); + match try!(self.parse_group()) { + Either::Left(set) => { + let ignore = set.flags.flag_state(ast::Flag::IgnoreWhitespace); + if let Some(v) = ignore { + self.parser().ignore_whitespace.set(v); + } + + concat.asts.push(Ast::Flags(set)); + Ok(concat) + } + Either::Right(group) => { + let old_ignore_whitespace = self.ignore_whitespace(); + let new_ignore_whitespace = group + .flags() + .and_then(|f| f.flag_state(ast::Flag::IgnoreWhitespace)) + .unwrap_or(old_ignore_whitespace); + self.parser().stack_group.borrow_mut().push(GroupState::Group { + concat: concat, + group: group, + ignore_whitespace: old_ignore_whitespace, + }); + self.parser().ignore_whitespace.set(new_ignore_whitespace); + Ok(ast::Concat { + span: self.span(), + asts: vec![], + }) + } + } + } + + /// Pop a group AST from the parser's internal stack and set the group's + /// AST to the given concatenation. Return the concatenation containing + /// the group. + /// + /// This assumes that the parser is currently positioned on the closing + /// parenthesis and advances the parser to the character following the `)`. + /// + /// If no such group could be popped, then an unopened group error is + /// returned. + fn pop_group(&self, mut group_concat: ast::Concat) -> Result { + use self::GroupState::*; + + assert_eq!(self.char(), ')'); + let mut stack = self.parser().stack_group.borrow_mut(); + let (mut prior_concat, mut group, ignore_whitespace, alt) = + match stack.pop() { + Some(Group { concat, group, ignore_whitespace }) => { + (concat, group, ignore_whitespace, None) + } + Some(Alternation(alt)) => { + match stack.pop() { + Some(Group { concat, group, ignore_whitespace }) => { + (concat, group, ignore_whitespace, Some(alt)) + } + None | Some(Alternation(_)) => { + return Err(self.error( + self.span_char(), + ast::ErrorKind::GroupUnopened, + )); + } + } + } + None => { + return Err(self.error( + self.span_char(), + ast::ErrorKind::GroupUnopened, + )); + } + }; + self.parser().ignore_whitespace.set(ignore_whitespace); + group_concat.span.end = self.pos(); + self.bump(); + group.span.end = self.pos(); + match alt { + Some(mut alt) => { + alt.span.end = group_concat.span.end; + alt.asts.push(group_concat.into_ast()); + group.ast = Box::new(alt.into_ast()); + } + None => { + group.ast = Box::new(group_concat.into_ast()); + } + } + prior_concat.asts.push(Ast::Group(group)); + Ok(prior_concat) + } + + /// Pop the last state from the parser's internal stack, if it exists, and + /// add the given concatenation to it. There either must be no state or a + /// single alternation item on the stack. Any other scenario produces an + /// error. + /// + /// This assumes that the parser has advanced to the end. + fn pop_group_end(&self, mut concat: ast::Concat) -> Result { + concat.span.end = self.pos(); + let mut stack = self.parser().stack_group.borrow_mut(); + let ast = match stack.pop() { + None => Ok(concat.into_ast()), + Some(GroupState::Alternation(mut alt)) => { + alt.span.end = self.pos(); + alt.asts.push(concat.into_ast()); + Ok(Ast::Alternation(alt)) + } + Some(GroupState::Group { group, .. }) => { + return Err(self.error( + group.span, + ast::ErrorKind::GroupUnclosed, + )); + } + }; + // If we try to pop again, there should be nothing. + match stack.pop() { + None => ast, + Some(GroupState::Alternation(_)) => { + // This unreachable is unfortunate. This case can't happen + // because the only way we can be here is if there were two + // `GroupState::Alternation`s adjacent in the parser's stack, + // which we guarantee to never happen because we never push a + // `GroupState::Alternation` if one is already at the top of + // the stack. + unreachable!() + } + Some(GroupState::Group { group, .. }) => { + Err(self.error(group.span, ast::ErrorKind::GroupUnclosed)) + } + } + } + + /// Parse the opening of a character class and push the current class + /// parsing context onto the parser's stack. This assumes that the parser + /// is positioned at an opening `[`. The given union should correspond to + /// the union of set items built up before seeing the `[`. + /// + /// If there was a problem parsing the opening of the class, then an error + /// is returned. Otherwise, a new union of set items for the class is + /// returned (which may be populated with either a `]` or a `-`). + fn push_class_open( + &self, + parent_union: ast::ClassSetUnion, + ) -> Result { + assert_eq!(self.char(), '['); + + let (nested_set, nested_union) = try!(self.parse_set_class_open()); + self.parser().stack_class.borrow_mut().push(ClassState::Open { + union: parent_union, + set: nested_set, + }); + Ok(nested_union) + } + + /// Parse the end of a character class set and pop the character class + /// parser stack. The union given corresponds to the last union built + /// before seeing the closing `]`. The union returned corresponds to the + /// parent character class set with the nested class added to it. + /// + /// This assumes that the parser is positioned at a `]` and will advance + /// the parser to the byte immediately following the `]`. + /// + /// If the stack is empty after popping, then this returns the final + /// "top-level" character class AST (where a "top-level" character class + /// is one that is not nested inside any other character class). + /// + /// If there is no corresponding opening bracket on the parser's stack, + /// then an error is returned. + fn pop_class( + &self, + nested_union: ast::ClassSetUnion, + ) -> Result> { + assert_eq!(self.char(), ']'); + + let item = ast::ClassSet::Item(nested_union.into_item()); + let prevset = self.pop_class_op(item); + let mut stack = self.parser().stack_class.borrow_mut(); + match stack.pop() { + None => { + // We can never observe an empty stack: + // + // 1) We are guaranteed to start with a non-empty stack since + // the character class parser is only initiated when it sees + // a `[`. + // 2) If we ever observe an empty stack while popping after + // seeing a `]`, then we signal the character class parser + // to terminate. + panic!("unexpected empty character class stack") + }, + Some(ClassState::Op { .. }) => { + // This panic is unfortunate, but this case is impossible + // since we already popped the Op state if one exists above. + // Namely, every push to the class parser stack is guarded by + // whether an existing Op is already on the top of the stack. + // If it is, the existing Op is modified. That is, the stack + // can never have consecutive Op states. + panic!("unexpected ClassState::Op") + } + Some(ClassState::Open { mut union, mut set }) => { + self.bump(); + set.span.end = self.pos(); + set.kind = prevset; + if stack.is_empty() { + Ok(Either::Right(ast::Class::Bracketed(set))) + } else { + union.push(ast::ClassSetItem::Bracketed(Box::new(set))); + Ok(Either::Left(union)) + } + } + } + } + + /// Return an "unclosed class" error whose span points to the most + /// recently opened class. + /// + /// This should only be called while parsing a character class. + fn unclosed_class_error(&self) -> ast::Error { + for state in self.parser().stack_class.borrow().iter().rev() { + match *state { + ClassState::Open { ref set, .. } => { + return self.error(set.span, ast::ErrorKind::ClassUnclosed); + } + _ => {} + } + } + // We are guaranteed to have a non-empty stack with at least + // one open bracket, so we should never get here. + panic!("no open character class found") + } + + /// Push the current set of class items on to the class parser's stack as + /// the left hand side of the given operator. + /// + /// A fresh set union is returned, which should be used to build the right + /// hand side of this operator. + fn push_class_op( + &self, + next_kind: ast::ClassSetBinaryOpKind, + next_union: ast::ClassSetUnion, + ) -> ast::ClassSetUnion { + + let item = ast::ClassSet::Item(next_union.into_item()); + let new_lhs = self.pop_class_op(item); + self.parser().stack_class.borrow_mut().push(ClassState::Op { + kind: next_kind, + lhs: new_lhs, + }); + ast::ClassSetUnion { span: self.span(), items: vec![] } + } + + /// Pop a character class set from the character class parser stack. If the + /// top of the stack is just an item (not an operation), then return the + /// given set unchanged. If the top of the stack is an operation, then the + /// given set will be used as the rhs of the operation on the top of the + /// stack. In that case, the binary operation is returned as a set. + fn pop_class_op(&self, rhs: ast::ClassSet) -> ast::ClassSet { + let mut stack = self.parser().stack_class.borrow_mut(); + let (kind, lhs) = match stack.pop() { + Some(ClassState::Op { kind, lhs }) => (kind, lhs), + Some(state @ ClassState::Open { .. }) => { + stack.push(state); + return rhs; + } + None => unreachable!(), + }; + let span = Span::new(lhs.span().start, rhs.span().end); + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: kind, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } +} + +impl<'s, P: Borrow> ParserI<'s, P> { + /// Parse the regular expression into an abstract syntax tree. + fn parse(&self) -> Result { + self.parse_with_comments().map(|astc| astc.ast) + } + + /// Parse the regular expression and return an abstract syntax tree with + /// all of the comments found in the pattern. + fn parse_with_comments(&self) -> Result { + assert_eq!(self.offset(), 0, "parser can only be used once"); + self.parser().reset(); + let mut concat = ast::Concat { + span: self.span(), + asts: vec![], + }; + loop { + self.bump_space(); + if self.is_eof() { + break; + } + match self.char() { + '(' => concat = try!(self.push_group(concat)), + ')' => concat = try!(self.pop_group(concat)), + '|' => concat = try!(self.push_alternate(concat)), + '[' => { + let class = try!(self.parse_set_class()); + concat.asts.push(Ast::Class(class)); + } + '?' => { + concat = try!(self.parse_uncounted_repetition( + concat, ast::RepetitionKind::ZeroOrOne)); + } + '*' => { + concat = try!(self.parse_uncounted_repetition( + concat, ast::RepetitionKind::ZeroOrMore)); + } + '+' => { + concat = try!(self.parse_uncounted_repetition( + concat, ast::RepetitionKind::OneOrMore)); + } + '{' => { + concat = try!(self.parse_counted_repetition(concat)); + } + _ => concat.asts.push(try!(self.parse_primitive()).into_ast()), + } + } + let ast = try!(self.pop_group_end(concat)); + try!(NestLimiter::new(self).check(&ast)); + Ok(ast::WithComments { + ast: ast, + comments: mem::replace( + &mut *self.parser().comments.borrow_mut(), + vec![], + ), + }) + } + + /// Parses an uncounted repetition operation. An uncounted repetition + /// operator includes ?, * and +, but does not include the {m,n} syntax. + /// The given `kind` should correspond to the operator observed by the + /// caller. + /// + /// This assumes that the paser is currently positioned at the repetition + /// operator and advances the parser to the first character after the + /// operator. (Note that the operator may include a single additional `?`, + /// which makes the operator ungreedy.) + /// + /// The caller should include the concatenation that is being built. The + /// concatenation returned includes the repetition operator applied to the + /// last expression in the given concatenation. + fn parse_uncounted_repetition( + &self, + mut concat: ast::Concat, + kind: ast::RepetitionKind, + ) -> Result { + assert!( + self.char() == '?' || self.char() == '*' || self.char() == '+'); + let op_start = self.pos(); + let ast = match concat.asts.pop() { + Some(ast) => ast, + None => return Err(self.error( + self.span(), + ast::ErrorKind::RepetitionMissing, + )), + }; + match ast { + Ast::Empty(_) | Ast::Flags(_) => return Err(self.error( + self.span(), + ast::ErrorKind::RepetitionMissing, + )), + _ => {} + } + let mut greedy = true; + if self.bump() && self.char() == '?' { + greedy = false; + self.bump(); + } + concat.asts.push(Ast::Repetition(ast::Repetition { + span: ast.span().with_end(self.pos()), + op: ast::RepetitionOp { + span: Span::new(op_start, self.pos()), + kind: kind, + }, + greedy: greedy, + ast: Box::new(ast), + })); + Ok(concat) + } + + /// Parses a counted repetition operation. A counted repetition operator + /// corresponds to the {m,n} syntax, and does not include the ?, * or + + /// operators. + /// + /// This assumes that the paser is currently positioned at the opening `{` + /// and advances the parser to the first character after the operator. + /// (Note that the operator may include a single additional `?`, which + /// makes the operator ungreedy.) + /// + /// The caller should include the concatenation that is being built. The + /// concatenation returned includes the repetition operator applied to the + /// last expression in the given concatenation. + fn parse_counted_repetition( + &self, + mut concat: ast::Concat, + ) -> Result { + assert!(self.char() == '{'); + let start = self.pos(); + let ast = match concat.asts.pop() { + Some(ast) => ast, + None => return Err(self.error( + self.span(), + ast::ErrorKind::RepetitionMissing, + )), + }; + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + let count_start = try!(self.parse_decimal()); + let mut range = ast::RepetitionRange::Exactly(count_start); + if self.is_eof() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + if self.char() == ',' { + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + if self.char() != '}' { + let count_end = try!(self.parse_decimal()); + range = ast::RepetitionRange::Bounded(count_start, count_end); + } else { + range = ast::RepetitionRange::AtLeast(count_start); + } + } + if self.is_eof() || self.char() != '}' { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + + let mut greedy = true; + if self.bump_and_bump_space() && self.char() == '?' { + greedy = false; + self.bump(); + } + + let op_span = Span::new(start, self.pos()); + if !range.is_valid() { + return Err(self.error( + op_span, + ast::ErrorKind::RepetitionCountInvalid, + )); + } + concat.asts.push(Ast::Repetition(ast::Repetition { + span: ast.span().with_end(self.pos()), + op: ast::RepetitionOp { + span: op_span, + kind: ast::RepetitionKind::Range(range), + }, + greedy: greedy, + ast: Box::new(ast), + })); + Ok(concat) + } + + /// Parse a group (which contains a sub-expression) or a set of flags. + /// + /// If a group was found, then it is returned with an empty AST. If a set + /// of flags is found, then that set is returned. + /// + /// The parser should be positioned at the opening parenthesis. + /// + /// This advances the parser to the character before the start of the + /// sub-expression (in the case of a group) or to the closing parenthesis + /// immediately following the set of flags. + /// + /// # Errors + /// + /// If flags are given and incorrectly specified, then a corresponding + /// error is returned. + /// + /// If a capture name is given and it is incorrectly specified, then a + /// corresponding error is returned. + fn parse_group(&self) -> Result> { + assert_eq!(self.char(), '('); + let open_span = self.span_char(); + self.bump(); + self.bump_space(); + if self.is_lookaround_prefix() { + return Err(self.error( + Span::new(open_span.start, self.span().end), + ast::ErrorKind::UnsupportedLookAround, + )); + } + let inner_span = self.span(); + if self.bump_if("?P<") { + let capture_index = try!(self.next_capture_index(open_span)); + let cap = try!(self.parse_capture_name(capture_index)); + Ok(Either::Right(ast::Group { + span: open_span, + kind: ast::GroupKind::CaptureName(cap), + ast: Box::new(Ast::Empty(self.span())), + })) + } else if self.bump_if("?") { + if self.is_eof() { + return Err(self.error( + open_span, + ast::ErrorKind::GroupUnclosed, + )); + } + let flags = try!(self.parse_flags()); + let char_end = self.char(); + self.bump(); + if char_end == ')' { + // We don't allow empty flags, e.g., `(?)`. We instead + // interpret it as a repetition operator missing its argument. + if flags.items.is_empty() { + return Err(self.error( + inner_span, + ast::ErrorKind::RepetitionMissing, + )); + } + Ok(Either::Left(ast::SetFlags { + span: Span { end: self.pos(), ..open_span }, + flags: flags, + })) + } else { + assert_eq!(char_end, ':'); + Ok(Either::Right(ast::Group { + span: open_span, + kind: ast::GroupKind::NonCapturing(flags), + ast: Box::new(Ast::Empty(self.span())), + })) + } + } else { + let capture_index = try!(self.next_capture_index(open_span)); + Ok(Either::Right(ast::Group { + span: open_span, + kind: ast::GroupKind::CaptureIndex(capture_index), + ast: Box::new(Ast::Empty(self.span())), + })) + } + } + + /// Parses a capture group name. Assumes that the parser is positioned at + /// the first character in the name following the opening `<` (and may + /// possibly be EOF). This advances the parser to the first character + /// following the closing `>`. + /// + /// The caller must provide the capture index of the group for this name. + fn parse_capture_name( + &self, + capture_index: u32, + ) -> Result { + if self.is_eof() { + return Err(self.error( + self.span(), + ast::ErrorKind::GroupNameUnexpectedEof, + )); + } + let start = self.pos(); + loop { + if self.char() == '>' { + break; + } + if !is_capture_char(self.char(), self.pos() == start) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::GroupNameInvalid, + )); + } + if !self.bump() { + break; + } + } + let end = self.pos(); + if self.is_eof() { + return Err(self.error( + self.span(), + ast::ErrorKind::GroupNameUnexpectedEof, + )); + } + assert_eq!(self.char(), '>'); + self.bump(); + let name = &self.pattern()[start.offset..end.offset]; + if name.is_empty() { + return Err(self.error( + Span::new(start, start), + ast::ErrorKind::GroupNameEmpty, + )); + } + let capname = ast::CaptureName { + span: Span::new(start, end), + name: name.to_string(), + index: capture_index, + }; + try!(self.add_capture_name(&capname)); + Ok(capname) + } + + /// Parse a sequence of flags starting at the current character. + /// + /// This advances the parser to the character immediately following the + /// flags, which is guaranteed to be either `:` or `)`. + /// + /// # Errors + /// + /// If any flags are duplicated, then an error is returned. + /// + /// If the negation operator is used more than once, then an error is + /// returned. + /// + /// If no flags could be found or if the negation operation is not followed + /// by any flags, then an error is returned. + fn parse_flags(&self) -> Result { + let mut flags = ast::Flags { + span: self.span(), + items: vec![], + }; + let mut last_was_negation = None; + while self.char() != ':' && self.char() != ')' { + if self.char() == '-' { + last_was_negation = Some(self.span_char()); + let item = ast::FlagsItem { + span: self.span_char(), + kind: ast::FlagsItemKind::Negation, + }; + if let Some(i) = flags.add_item(item) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::FlagRepeatedNegation { + original: flags.items[i].span, + }, + )); + } + } else { + last_was_negation = None; + let item = ast::FlagsItem { + span: self.span_char(), + kind: ast::FlagsItemKind::Flag(try!(self.parse_flag())), + }; + if let Some(i) = flags.add_item(item) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::FlagDuplicate { + original: flags.items[i].span, + }, + )); + } + } + if !self.bump() { + return Err(self.error( + self.span(), + ast::ErrorKind::FlagUnexpectedEof, + )); + } + } + if let Some(span) = last_was_negation { + return Err(self.error(span, ast::ErrorKind::FlagDanglingNegation)); + } + flags.span.end = self.pos(); + Ok(flags) + } + + /// Parse the current character as a flag. Do not advance the parser. + /// + /// # Errors + /// + /// If the flag is not recognized, then an error is returned. + fn parse_flag(&self) -> Result { + match self.char() { + 'i' => Ok(ast::Flag::CaseInsensitive), + 'm' => Ok(ast::Flag::MultiLine), + 's' => Ok(ast::Flag::DotMatchesNewLine), + 'U' => Ok(ast::Flag::SwapGreed), + 'u' => Ok(ast::Flag::Unicode), + 'x' => Ok(ast::Flag::IgnoreWhitespace), + _ => Err(self.error( + self.span_char(), + ast::ErrorKind::FlagUnrecognized, + )), + } + } + + /// Parse a primitive AST. e.g., A literal, non-set character class or + /// assertion. + /// + /// This assumes that the parser expects a primitive at the current + /// location. i.e., All other non-primitive cases have been handled. + /// For example, if the parser's position is at `|`, then `|` will be + /// treated as a literal (e.g., inside a character class). + /// + /// This advances the parser to the first character immediately following + /// the primitive. + fn parse_primitive(&self) -> Result { + match self.char() { + '\\' => self.parse_escape(), + '.' => { + let ast = Primitive::Dot(self.span_char()); + self.bump(); + Ok(ast) + } + '^' => { + let ast = Primitive::Assertion(ast::Assertion { + span: self.span_char(), + kind: ast::AssertionKind::StartLine, + }); + self.bump(); + Ok(ast) + } + '$' => { + let ast = Primitive::Assertion(ast::Assertion { + span: self.span_char(), + kind: ast::AssertionKind::EndLine, + }); + self.bump(); + Ok(ast) + } + c => { + let ast = Primitive::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: c, + }); + self.bump(); + Ok(ast) + } + } + } + + /// Parse an escape sequence as a primitive AST. + /// + /// This assumes the parser is positioned at the start of the escape + /// sequence, i.e., `\`. It advances the parser to the first position + /// immediately following the escape sequence. + fn parse_escape(&self) -> Result { + assert_eq!(self.char(), '\\'); + let start = self.pos(); + if !self.bump() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + let c = self.char(); + // Put some of the more complicated routines into helpers. + match c { + '0'...'7' => { + if !self.parser().octal { + return Err(self.error( + Span::new(start, self.span_char().end), + ast::ErrorKind::UnsupportedBackreference, + )); + } + let mut lit = self.parse_octal(); + lit.span.start = start; + return Ok(Primitive::Literal(lit)); + } + '8'...'9' if !self.parser().octal => { + return Err(self.error( + Span::new(start, self.span_char().end), + ast::ErrorKind::UnsupportedBackreference, + )); + } + 'x' | 'u' | 'U' => { + let mut lit = try!(self.parse_hex()); + lit.span.start = start; + return Ok(Primitive::Literal(lit)); + } + 'p' | 'P' => { + let mut cls = try!(self.parse_unicode_class()); + cls.span.start = start; + return Ok(Primitive::Unicode(cls)); + } + 'd' | 's' | 'w' | 'D' | 'S' | 'W' => { + let mut cls = self.parse_perl_class(); + cls.span.start = start; + return Ok(Primitive::Perl(cls)); + } + _ => {} + } + + // Handle all of the one letter sequences inline. + self.bump(); + let span = Span::new(start, self.pos()); + if is_meta_character(c) { + return Ok(Primitive::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Punctuation, + c: c, + })); + } + let special = |kind, c| Ok(Primitive::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Special(kind), + c: c, + })); + match c { + 'a' => special(ast::SpecialLiteralKind::Bell, '\x07'), + 'f' => special(ast::SpecialLiteralKind::FormFeed, '\x0C'), + 't' => special(ast::SpecialLiteralKind::Tab, '\t'), + 'n' => special(ast::SpecialLiteralKind::LineFeed, '\n'), + 'r' => special(ast::SpecialLiteralKind::CarriageReturn, '\r'), + 'v' => special(ast::SpecialLiteralKind::VerticalTab, '\x0B'), + ' ' if self.ignore_whitespace() => { + special(ast::SpecialLiteralKind::Space, ' ') + } + 'A' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::StartText, + })), + 'z' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::EndText, + })), + 'b' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::WordBoundary, + })), + 'B' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::NotWordBoundary, + })), + _ => Err(self.error(span, ast::ErrorKind::EscapeUnrecognized)), + } + } + + /// Parse an octal representation of a Unicode codepoint up to 3 digits + /// long. This expects the parser to be positioned at the first octal + /// digit and advances the parser to the first character immediately + /// following the octal number. This also assumes that parsing octal + /// escapes is enabled. + /// + /// Assuming the preconditions are met, this routine can never fail. + fn parse_octal(&self) -> ast::Literal { + use std::char; + use std::u32; + + assert!(self.parser().octal); + assert!('0' <= self.char() && self.char() <= '7'); + let start = self.pos(); + // Parse up to two more digits. + while + self.bump() && + '0' <= self.char() && self.char() <= '7' && + self.pos().offset - start.offset <= 2 + {} + let end = self.pos(); + let octal = &self.pattern()[start.offset..end.offset]; + // Parsing the octal should never fail since the above guarantees a + // valid number. + let codepoint = + u32::from_str_radix(octal, 8).expect("valid octal number"); + // The max value for 3 digit octal is 0777 = 511 and [0, 511] has no + // invalid Unicode scalar values. + let c = char::from_u32(codepoint).expect("Unicode scalar value"); + ast::Literal { + span: Span::new(start, end), + kind: ast::LiteralKind::Octal, + c: c, + } + } + + /// Parse a hex representation of a Unicode codepoint. This handles both + /// hex notations, i.e., `\xFF` and `\x{FFFF}`. This expects the parser to + /// be positioned at the `x`, `u` or `U` prefix. The parser is advanced to + /// the first character immediately following the hexadecimal literal. + fn parse_hex(&self) -> Result { + assert!(self.char() == 'x' + || self.char() == 'u' + || self.char() == 'U'); + + let hex_kind = match self.char() { + 'x' => ast::HexLiteralKind::X, + 'u' => ast::HexLiteralKind::UnicodeShort, + _ => ast::HexLiteralKind::UnicodeLong, + }; + if !self.bump_and_bump_space() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + if self.char() == '{' { + self.parse_hex_brace(hex_kind) + } else { + self.parse_hex_digits(hex_kind) + } + } + + /// Parse an N-digit hex representation of a Unicode codepoint. This + /// expects the parser to be positioned at the first digit and will advance + /// the parser to the first character immediately following the escape + /// sequence. + /// + /// The number of digits given must be 2 (for `\xNN`), 4 (for `\uNNNN`) + /// or 8 (for `\UNNNNNNNN`). + fn parse_hex_digits( + &self, + kind: ast::HexLiteralKind, + ) -> Result { + use std::char; + use std::u32; + + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + let start = self.pos(); + for i in 0..kind.digits() { + if i > 0 && !self.bump_and_bump_space() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + if !is_hex(self.char()) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::EscapeHexInvalidDigit, + )); + } + scratch.push(self.char()); + } + // The final bump just moves the parser past the literal, which may + // be EOF. + self.bump_and_bump_space(); + let end = self.pos(); + let hex = scratch.as_str(); + match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) { + None => Err(self.error( + Span::new(start, end), + ast::ErrorKind::EscapeHexInvalid, + )), + Some(c) => Ok(ast::Literal { + span: Span::new(start, end), + kind: ast::LiteralKind::HexFixed(kind), + c: c, + }), + } + } + + /// Parse a hex representation of any Unicode scalar value. This expects + /// the parser to be positioned at the opening brace `{` and will advance + /// the parser to the first character following the closing brace `}`. + fn parse_hex_brace( + &self, + kind: ast::HexLiteralKind, + ) -> Result { + use std::char; + use std::u32; + + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + let brace_pos = self.pos(); + let start = self.span_char().end; + while self.bump_and_bump_space() && self.char() != '}' { + if !is_hex(self.char()) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::EscapeHexInvalidDigit, + )); + } + scratch.push(self.char()); + } + if self.is_eof() { + return Err(self.error( + Span::new(brace_pos, self.pos()), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + let end = self.pos(); + let hex = scratch.as_str(); + assert_eq!(self.char(), '}'); + self.bump_and_bump_space(); + + if hex.is_empty() { + return Err(self.error( + Span::new(brace_pos, self.pos()), + ast::ErrorKind::EscapeHexEmpty, + )); + } + match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) { + None => Err(self.error( + Span::new(start, end), + ast::ErrorKind::EscapeHexInvalid, + )), + Some(c) => Ok(ast::Literal { + span: Span::new(start, self.pos()), + kind: ast::LiteralKind::HexBrace(kind), + c: c, + }), + } + } + + /// Parse a decimal number into a u32 while trimming leading and trailing + /// whitespace. + /// + /// This expects the parser to be positioned at the first position where + /// a decimal digit could occur. This will advance the parser to the byte + /// immediately following the last contiguous decimal digit. + /// + /// If no decimal digit could be found or if there was a problem parsing + /// the complete set of digits into a u32, then an error is returned. + fn parse_decimal(&self) -> Result { + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + while !self.is_eof() && self.char().is_whitespace() { + self.bump(); + } + let start = self.pos(); + while !self.is_eof() && '0' <= self.char() && self.char() <= '9' { + scratch.push(self.char()); + self.bump_and_bump_space(); + } + let span = Span::new(start, self.pos()); + while !self.is_eof() && self.char().is_whitespace() { + self.bump_and_bump_space(); + } + let digits = scratch.as_str(); + if digits.is_empty() { + return Err(self.error(span, ast::ErrorKind::DecimalEmpty)); + } + match u32::from_str_radix(digits, 10).ok() { + Some(n) => Ok(n), + None => Err(self.error(span, ast::ErrorKind::DecimalInvalid)), + } + } + + /// Parse a standard character class consisting primarily of characters or + /// character ranges, but can also contain nested character classes of + /// any type (sans `.`). + /// + /// This assumes the parser is positioned at the opening `[`. If parsing + /// is successful, then the parser is advanced to the position immediately + /// following the closing `]`. + fn parse_set_class(&self) -> Result { + assert_eq!(self.char(), '['); + + let mut union = ast::ClassSetUnion { + span: self.span(), + items: vec![], + }; + loop { + self.bump_space(); + if self.is_eof() { + return Err(self.unclosed_class_error()); + } + match self.char() { + '[' => { + // If we've already parsed the opening bracket, then + // attempt to treat this as the beginning of an ASCII + // class. If ASCII class parsing fails, then the parser + // backs up to `[`. + if !self.parser().stack_class.borrow().is_empty() { + if let Some(cls) = self.maybe_parse_ascii_class() { + union.push(ast::ClassSetItem::Ascii(cls)); + continue; + } + } + union = try!(self.push_class_open(union)); + } + ']' => { + match try!(self.pop_class(union)) { + Either::Left(nested_union) => { union = nested_union; } + Either::Right(class) => return Ok(class), + } + } + '&' if self.peek() == Some('&') => { + assert!(self.bump_if("&&")); + union = self.push_class_op( + ast::ClassSetBinaryOpKind::Intersection, union); + } + '-' if self.peek() == Some('-') => { + assert!(self.bump_if("--")); + union = self.push_class_op( + ast::ClassSetBinaryOpKind::Difference, union); + } + '~' if self.peek() == Some('~') => { + assert!(self.bump_if("~~")); + union = self.push_class_op( + ast::ClassSetBinaryOpKind::SymmetricDifference, union); + } + _ => { + union.push(try!(self.parse_set_class_range())); + } + } + } + } + + /// Parse a single primitive item in a character class set. The item to + /// be parsed can either be one of a simple literal character, a range + /// between two simple literal characters or a "primitive" character + /// class like \w or \p{Greek}. + /// + /// If an invalid escape is found, or if a character class is found where + /// a simple literal is expected (e.g., in a range), then an error is + /// returned. + fn parse_set_class_range(&self) -> Result { + let prim1 = try!(self.parse_set_class_item()); + self.bump_space(); + if self.is_eof() { + return Err(self.unclosed_class_error()); + } + // If the next char isn't a `-`, then we don't have a range. + // There are two exceptions. If the char after a `-` is a `]`, then + // `-` is interpreted as a literal `-`. Alternatively, if the char + // after a `-` is a `-`, then `--` corresponds to a "difference" + // operation. + if self.char() != '-' + || self.peek_space() == Some(']') + || self.peek_space() == Some('-') + { + return prim1.into_class_set_item(self); + } + // OK, now we're parsing a range, so bump past the `-` and parse the + // second half of the range. + if !self.bump_and_bump_space() { + return Err(self.unclosed_class_error()); + } + let prim2 = try!(self.parse_set_class_item()); + let range = ast::ClassSetRange { + span: Span::new(prim1.span().start, prim2.span().end), + start: try!(prim1.into_class_literal(self)), + end: try!(prim2.into_class_literal(self)), + }; + if !range.is_valid() { + return Err(self.error( + range.span, + ast::ErrorKind::ClassRangeInvalid, + )); + } + Ok(ast::ClassSetItem::Range(range)) + } + + /// Parse a single item in a character class as a primitive, where the + /// primitive either consists of a verbatim literal or a single escape + /// sequence. + /// + /// This assumes the parser is positioned at the beginning of a primitive, + /// and advances the parser to the first position after the primitive if + /// successful. + /// + /// Note that it is the caller's responsibility to report an error if an + /// illegal primitive was parsed. + fn parse_set_class_item(&self) -> Result { + if self.char() == '\\' { + self.parse_escape() + } else { + let x = Primitive::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: self.char(), + }); + self.bump(); + Ok(x) + } + } + + /// Parses the opening of a character class set. This includes the opening + /// bracket along with `^` if present to indicate negation. This also + /// starts parsing the opening set of unioned items if applicable, since + /// there are special rules applied to certain characters in the opening + /// of a character class. For example, `[^]]` is the class of all + /// characters not equal to `]`. (`]` would need to be escaped in any other + /// position.) Similarly for `-`. + /// + /// In all cases, the op inside the returned `ast::ClassBracketed` is an + /// empty union. This empty union should be replaced with the actual item + /// when it is popped from the parser's stack. + /// + /// This assumes the parser is positioned at the opening `[` and advances + /// the parser to the first non-special byte of the character class. + /// + /// An error is returned if EOF is found. + fn parse_set_class_open( + &self, + ) -> Result<(ast::ClassBracketed, ast::ClassSetUnion)> { + assert_eq!(self.char(), '['); + let start = self.pos(); + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + + let negated = + if self.char() != '^' { + false + } else { + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + true + }; + // Accept any number of `-` as literal `-`. + let mut union = ast::ClassSetUnion { + span: self.span(), + items: vec![], + }; + while self.char() == '-' { + union.push(ast::ClassSetItem::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: '-', + })); + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + } + // If `]` is the *first* char in a set, then interpret it as a literal + // `]`. That is, an empty class is impossible to write. + if union.items.is_empty() && self.char() == ']' { + union.push(ast::ClassSetItem::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: ']', + })); + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + } + let set = ast::ClassBracketed { + span: Span::new(start, self.pos()), + negated: negated, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: Span::new(union.span.start, union.span.start), + items: vec![], + }), + }; + Ok((set, union)) + } + + /// Attempt to parse an ASCII character class, e.g., `[:alnum:]`. + /// + /// This assumes the parser is positioned at the opening `[`. + /// + /// If no valid ASCII character class could be found, then this does not + /// advance the parser and `None` is returned. Otherwise, the parser is + /// advanced to the first byte following the closing `]` and the + /// corresponding ASCII class is returned. + fn maybe_parse_ascii_class(&self) -> Option { + // ASCII character classes are interesting from a parsing perspective + // because parsing cannot fail with any interesting error. For example, + // in order to use an ASCII character class, it must be enclosed in + // double brackets, e.g., `[[:alnum:]]`. Alternatively, you might think + // of it as "ASCII character characters have the syntax `[:NAME:]` + // which can only appear within character brackets." This means that + // things like `[[:lower:]A]` are legal constructs. + // + // However, if one types an incorrect ASCII character class, e.g., + // `[[:loower:]]`, then we treat that as a normal nested character + // class containing the characters `:elorw`. One might argue that we + // should return an error instead since the repeated colons give away + // the intent to write an ASCII class. But what if the user typed + // `[[:lower]]` instead? How can we tell that was intended to be an + // ASCII class and not just a normal nested class? + // + // Reasonable people can probably disagree over this, but for better + // or worse, we implement semantics that never fails at the expense + // of better failure modes. + assert_eq!(self.char(), '['); + // If parsing fails, then we back up the parser to this starting point. + let start = self.pos(); + let mut negated = false; + if !self.bump() || self.char() != ':' { + self.parser().pos.set(start); + return None; + } + if !self.bump() { + self.parser().pos.set(start); + return None; + } + if self.char() == '^' { + negated = true; + if !self.bump() { + self.parser().pos.set(start); + return None; + } + } + let name_start = self.offset(); + while self.char() != ':' && self.bump() {} + if self.is_eof() { + self.parser().pos.set(start); + return None; + } + let name = &self.pattern()[name_start..self.offset()]; + if !self.bump_if(":]") { + self.parser().pos.set(start); + return None; + } + let kind = match ast::ClassAsciiKind::from_name(name) { + Some(kind) => kind, + None => { + self.parser().pos.set(start); + return None; + } + }; + Some(ast::ClassAscii { + span: Span::new(start, self.pos()), + kind: kind, + negated: negated, + }) + } + + /// Parse a Unicode class in either the single character notation, `\pN` + /// or the multi-character bracketed notation, `\p{Greek}`. This assumes + /// the parser is positioned at the `p` (or `P` for negation) and will + /// advance the parser to the character immediately following the class. + /// + /// Note that this does not check whether the class name is valid or not. + fn parse_unicode_class(&self) -> Result { + assert!(self.char() == 'p' || self.char() == 'P'); + + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + let negated = self.char() == 'P'; + if !self.bump_and_bump_space() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + let (start, kind) = + if self.char() == '{' { + let start = self.span_char().end; + while self.bump_and_bump_space() && self.char() != '}' { + scratch.push(self.char()); + } + if self.is_eof() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + assert_eq!(self.char(), '}'); + self.bump(); + + let name = scratch.as_str(); + if let Some(i) = name.find("!=") { + (start, ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::NotEqual, + name: name[..i].to_string(), + value: name[i+2..].to_string(), + }) + } else if let Some(i) = name.find(':') { + (start, ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Colon, + name: name[..i].to_string(), + value: name[i+1..].to_string(), + }) + } else if let Some(i) = name.find('=') { + (start, ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Equal, + name: name[..i].to_string(), + value: name[i+1..].to_string(), + }) + } else { + (start, ast::ClassUnicodeKind::Named(name.to_string())) + } + } else { + let start = self.pos(); + let c = self.char(); + self.bump_and_bump_space(); + let kind = ast::ClassUnicodeKind::OneLetter(c); + (start, kind) + }; + Ok(ast::ClassUnicode { + span: Span::new(start, self.pos()), + negated: negated, + kind: kind, + }) + } + + /// Parse a Perl character class, e.g., `\d` or `\W`. This assumes the + /// parser is currently at a valid character class name and will be + /// advanced to the character immediately following the class. + fn parse_perl_class(&self) -> ast::ClassPerl { + let c = self.char(); + let span = self.span_char(); + self.bump(); + let (negated, kind) = match c { + 'd' => (false, ast::ClassPerlKind::Digit), + 'D' => (true, ast::ClassPerlKind::Digit), + 's' => (false, ast::ClassPerlKind::Space), + 'S' => (true, ast::ClassPerlKind::Space), + 'w' => (false, ast::ClassPerlKind::Word), + 'W' => (true, ast::ClassPerlKind::Word), + c => panic!("expected valid Perl class but got '{}'", c), + }; + ast::ClassPerl { span: span, kind: kind, negated: negated } + } +} + +/// A type that traverses a fully parsed Ast and checks whether its depth +/// exceeds the specified nesting limit. If it does, then an error is returned. +#[derive(Debug)] +struct NestLimiter<'p, 's: 'p, P: 'p + 's> { + /// The parser that is checking the nest limit. + p: &'p ParserI<'s, P>, + /// The current depth while walking an Ast. + depth: u32, +} + +impl<'p, 's, P: Borrow> NestLimiter<'p, 's, P> { + fn new(p: &'p ParserI<'s, P>) -> NestLimiter<'p, 's, P> { + NestLimiter { p: p, depth: 0 } + } + + fn check(self, ast: &Ast) -> Result<()> { + ast::visit(ast, self) + } + + fn increment_depth(&mut self, span: &Span) -> Result<()> { + let new = try!(self.depth.checked_add(1).ok_or_else(|| self.p.error( + span.clone(), + ast::ErrorKind::NestLimitExceeded(::std::u32::MAX), + ))); + let limit = self.p.parser().nest_limit; + if new > limit { + return Err(self.p.error( + span.clone(), + ast::ErrorKind::NestLimitExceeded(limit), + )); + } + self.depth = new; + Ok(()) + } + + fn decrement_depth(&mut self) { + // Assuming the correctness of the visitor, this should never drop + // below 0. + self.depth = self.depth.checked_sub(1).unwrap(); + } +} + +impl<'p, 's, P: Borrow> ast::Visitor for NestLimiter<'p, 's, P> { + type Output = (); + type Err = ast::Error; + + fn finish(self) -> Result<()> { + Ok(()) + } + + fn visit_pre(&mut self, ast: &Ast) -> Result<()> { + let span = match *ast { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + | Ast::Class(ast::Class::Unicode(_)) + | Ast::Class(ast::Class::Perl(_)) => { + // These are all base cases, so we don't increment depth. + return Ok(()); + } + Ast::Class(ast::Class::Bracketed(ref x)) => &x.span, + Ast::Repetition(ref x) => &x.span, + Ast::Group(ref x) => &x.span, + Ast::Alternation(ref x) => &x.span, + Ast::Concat(ref x) => &x.span, + }; + self.increment_depth(span) + } + + fn visit_post(&mut self, ast: &Ast) -> Result<()> { + match *ast { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + | Ast::Class(ast::Class::Unicode(_)) + | Ast::Class(ast::Class::Perl(_)) => { + // These are all base cases, so we don't decrement depth. + Ok(()) + } + Ast::Class(ast::Class::Bracketed(_)) + | Ast::Repetition(_) + | Ast::Group(_) + | Ast::Alternation(_) + | Ast::Concat(_) => { + self.decrement_depth(); + Ok(()) + } + } + } + + fn visit_class_set_item_pre( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + let span = match *ast { + ast::ClassSetItem::Empty(_) + | ast::ClassSetItem::Literal(_) + | ast::ClassSetItem::Range(_) + | ast::ClassSetItem::Ascii(_) + | ast::ClassSetItem::Unicode(_) + | ast::ClassSetItem::Perl(_) => { + // These are all base cases, so we don't increment depth. + return Ok(()); + } + ast::ClassSetItem::Bracketed(ref x) => &x.span, + ast::ClassSetItem::Union(ref x) => &x.span, + }; + self.increment_depth(span) + } + + fn visit_class_set_item_post( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + match *ast { + ast::ClassSetItem::Empty(_) + | ast::ClassSetItem::Literal(_) + | ast::ClassSetItem::Range(_) + | ast::ClassSetItem::Ascii(_) + | ast::ClassSetItem::Unicode(_) + | ast::ClassSetItem::Perl(_) => { + // These are all base cases, so we don't decrement depth. + Ok(()) + } + ast::ClassSetItem::Bracketed(_) + | ast::ClassSetItem::Union(_) => { + self.decrement_depth(); + Ok(()) + } + } + } + + fn visit_class_set_binary_op_pre( + &mut self, + ast: &ast::ClassSetBinaryOp, + ) -> Result<()> { + self.increment_depth(&ast.span) + } + + fn visit_class_set_binary_op_post( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<()> { + self.decrement_depth(); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use ast::{self, Ast, Position, Span}; + use super::{Parser, ParserI, ParserBuilder, Primitive}; + + // Our own assert_eq, which has slightly better formatting (but honestly + // still kind of crappy). + macro_rules! assert_eq { + ($left:expr, $right:expr) => ({ + match (&$left, &$right) { + (left_val, right_val) => { + if !(*left_val == *right_val) { + panic!("assertion failed: `(left == right)`\n\n\ + left: `{:?}`\nright: `{:?}`\n\n", + left_val, right_val) + } + } + } + }); + } + + // We create these errors to compare with real ast::Errors in the tests. + // We define equality between TestError and ast::Error to disregard the + // pattern string in ast::Error, which is annoying to provide in tests. + #[derive(Clone, Debug)] + struct TestError { + span: Span, + kind: ast::ErrorKind, + } + + impl PartialEq for TestError { + fn eq(&self, other: &ast::Error) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + impl PartialEq for ast::Error { + fn eq(&self, other: &TestError) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + fn s(str: &str) -> String { + str.to_string() + } + + fn parser(pattern: &str) -> ParserI { + ParserI::new(Parser::new(), pattern) + } + + fn parser_octal(pattern: &str) -> ParserI { + let parser = ParserBuilder::new().octal(true).build(); + ParserI::new(parser, pattern) + } + + fn parser_nest_limit(pattern: &str, nest_limit: u32) -> ParserI { + let p = ParserBuilder::new().nest_limit(nest_limit).build(); + ParserI::new(p, pattern) + } + + fn parser_ignore_whitespace(pattern: &str) -> ParserI { + let p = ParserBuilder::new().ignore_whitespace(true).build(); + ParserI::new(p, pattern) + } + + /// Short alias for creating a new span. + fn nspan(start: Position, end: Position) -> Span { + Span::new(start, end) + } + + /// Short alias for creating a new position. + fn npos(offset: usize, line: usize, column: usize) -> Position { + Position::new(offset, line, column) + } + + /// Create a new span from the given offset range. This assumes a single + /// line and sets the columns based on the offsets. i.e., This only works + /// out of the box for ASCII, which is fine for most tests. + fn span(range: Range) -> Span { + let start = Position::new(range.start, 1, range.start + 1); + let end = Position::new(range.end, 1, range.end + 1); + Span::new(start, end) + } + + /// Create a new span for the corresponding byte range in the given string. + fn span_range(subject: &str, range: Range) -> Span { + let start = Position { + offset: range.start, + line: 1 + subject[..range.start].matches('\n').count(), + column: 1 + subject[..range.start] + .chars() + .rev() + .position(|c| c == '\n') + .unwrap_or(subject[..range.start].chars().count()), + }; + let end = Position { + offset: range.end, + line: 1 + subject[..range.end].matches('\n').count(), + column: 1 + subject[..range.end] + .chars() + .rev() + .position(|c| c == '\n') + .unwrap_or(subject[..range.end].chars().count()), + }; + Span::new(start, end) + } + + /// Create a verbatim literal starting at the given position. + fn lit(c: char, start: usize) -> Ast { + lit_with(c, span(start..start + c.len_utf8())) + } + + /// Create a punctuation literal starting at the given position. + fn punct_lit(c: char, span: Span) -> Ast { + Ast::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Punctuation, + c: c, + }) + } + + /// Create a verbatim literal with the given span. + fn lit_with(c: char, span: Span) -> Ast { + Ast::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Verbatim, + c: c, + }) + } + + /// Create a concatenation with the given range. + fn concat(range: Range, asts: Vec) -> Ast { + concat_with(span(range), asts) + } + + /// Create a concatenation with the given span. + fn concat_with(span: Span, asts: Vec) -> Ast { + Ast::Concat(ast::Concat { span: span, asts: asts }) + } + + /// Create an alternation with the given span. + fn alt(range: Range, asts: Vec) -> Ast { + Ast::Alternation(ast::Alternation { span: span(range), asts: asts }) + } + + /// Create a capturing group with the given span. + fn group(range: Range, index: u32, ast: Ast) -> Ast { + Ast::Group(ast::Group { + span: span(range), + kind: ast::GroupKind::CaptureIndex(index), + ast: Box::new(ast), + }) + } + + /// Create an ast::SetFlags. + /// + /// The given pattern should be the full pattern string. The range given + /// should correspond to the byte offsets where the flag set occurs. + /// + /// If negated is true, then the set is interpreted as beginning with a + /// negation. + fn flag_set( + pat: &str, + range: Range, + flag: ast::Flag, + negated: bool, + ) -> Ast { + let mut items = vec![ + ast::FlagsItem { + span: span_range(pat, (range.end - 2)..(range.end - 1)), + kind: ast::FlagsItemKind::Flag(flag), + }, + ]; + if negated { + items.insert(0, ast::FlagsItem { + span: span_range(pat, (range.start + 2)..(range.end - 2)), + kind: ast::FlagsItemKind::Negation, + }); + } + Ast::Flags(ast::SetFlags { + span: span_range(pat, range.clone()), + flags: ast::Flags { + span: span_range(pat, (range.start + 2)..(range.end - 1)), + items: items, + }, + }) + } + + #[test] + fn parse_nest_limit() { + // A nest limit of 0 still allows some types of regexes. + assert_eq!( + parser_nest_limit("", 0).parse(), + Ok(Ast::Empty(span(0..0)))); + assert_eq!( + parser_nest_limit("a", 0).parse(), + Ok(lit('a', 0))); + + // Test repetition operations, which require one level of nesting. + assert_eq!( + parser_nest_limit("a+", 0).parse().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("a+", 1).parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::OneOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser_nest_limit("(a)+", 1).parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("a+*", 1).parse().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("a+*", 2).parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..3), + op: ast::RepetitionOp { + span: span(2..3), + kind: ast::RepetitionKind::ZeroOrMore, + }, + greedy: true, + ast: Box::new(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::OneOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + })), + }))); + + // Test concatenations. A concatenation requires one level of nesting. + assert_eq!( + parser_nest_limit("ab", 0).parse().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("ab", 1).parse(), + Ok(concat(0..2, vec![lit('a', 0), lit('b', 1)]))); + assert_eq!( + parser_nest_limit("abc", 1).parse(), + Ok(concat(0..3, vec![lit('a', 0), lit('b', 1), lit('c', 2)]))); + + // Test alternations. An alternation requires one level of nesting. + assert_eq!( + parser_nest_limit("a|b", 0).parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("a|b", 1).parse(), + Ok(alt(0..3, vec![lit('a', 0), lit('b', 2)]))); + assert_eq!( + parser_nest_limit("a|b|c", 1).parse(), + Ok(alt(0..5, vec![lit('a', 0), lit('b', 2), lit('c', 4)]))); + + // Test character classes. Classes form their own mini-recursive + // syntax! + assert_eq!( + parser_nest_limit("[a]", 0).parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("[a]", 1).parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: ast::ClassSet::Item( + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: 'a', + }) + ), + })))); + assert_eq!( + parser_nest_limit("[ab]", 1).parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("[ab[cd]]", 2).parse().unwrap_err(), + TestError { + span: span(3..7), + kind: ast::ErrorKind::NestLimitExceeded(2), + }); + assert_eq!( + parser_nest_limit("[ab[cd]]", 3).parse().unwrap_err(), + TestError { + span: span(4..6), + kind: ast::ErrorKind::NestLimitExceeded(3), + }); + assert_eq!( + parser_nest_limit("[a--b]", 1).parse().unwrap_err(), + TestError { + span: span(1..5), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("[a--bc]", 2).parse().unwrap_err(), + TestError { + span: span(4..6), + kind: ast::ErrorKind::NestLimitExceeded(2), + }); + } + + #[test] + fn parse_comments() { + let pat = "(?x) +# This is comment 1. +foo # This is comment 2. + # This is comment 3. +bar +# This is comment 4."; + let astc = parser(pat).parse_with_comments().unwrap(); + assert_eq!( + astc.ast, + concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + lit_with('f', span_range(pat, 26..27)), + lit_with('o', span_range(pat, 27..28)), + lit_with('o', span_range(pat, 28..29)), + lit_with('b', span_range(pat, 74..75)), + lit_with('a', span_range(pat, 75..76)), + lit_with('r', span_range(pat, 76..77)), + ])); + assert_eq!(astc.comments, vec![ + ast::Comment { + span: span_range(pat, 5..26), + comment: s(" This is comment 1."), + }, + ast::Comment { + span: span_range(pat, 30..51), + comment: s(" This is comment 2."), + }, + ast::Comment { + span: span_range(pat, 53..74), + comment: s(" This is comment 3."), + }, + ast::Comment { + span: span_range(pat, 78..98), + comment: s(" This is comment 4."), + }, + ]); + } + + #[test] + fn parse_holistic() { + assert_eq!( + parser("]").parse(), + Ok(lit(']', 0))); + assert_eq!( + parser(r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#\&\-\~").parse(), + Ok(concat(0..36, vec![ + punct_lit('\\', span(0..2)), + punct_lit('.', span(2..4)), + punct_lit('+', span(4..6)), + punct_lit('*', span(6..8)), + punct_lit('?', span(8..10)), + punct_lit('(', span(10..12)), + punct_lit(')', span(12..14)), + punct_lit('|', span(14..16)), + punct_lit('[', span(16..18)), + punct_lit(']', span(18..20)), + punct_lit('{', span(20..22)), + punct_lit('}', span(22..24)), + punct_lit('^', span(24..26)), + punct_lit('$', span(26..28)), + punct_lit('#', span(28..30)), + punct_lit('&', span(30..32)), + punct_lit('-', span(32..34)), + punct_lit('~', span(34..36)), + ]))); + } + + #[test] + fn parse_ignore_whitespace() { + // Test that basic whitespace insensitivity works. + let pat = "(?x)a b"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(nspan(npos(0, 1, 1), npos(7, 1, 8)), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))), + lit_with('b', nspan(npos(6, 1, 7), npos(7, 1, 8))), + ]))); + + // Test that we can toggle whitespace insensitivity. + let pat = "(?x)a b(?-x)a b"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(nspan(npos(0, 1, 1), npos(15, 1, 16)), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))), + lit_with('b', nspan(npos(6, 1, 7), npos(7, 1, 8))), + flag_set(pat, 7..12, ast::Flag::IgnoreWhitespace, true), + lit_with('a', nspan(npos(12, 1, 13), npos(13, 1, 14))), + lit_with(' ', nspan(npos(13, 1, 14), npos(14, 1, 15))), + lit_with('b', nspan(npos(14, 1, 15), npos(15, 1, 16))), + ]))); + + // Test that nesting whitespace insensitive flags works. + let pat = "a (?x:a )a "; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..11), vec![ + lit_with('a', span_range(pat, 0..1)), + lit_with(' ', span_range(pat, 1..2)), + Ast::Group(ast::Group { + span: span_range(pat, 2..9), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span_range(pat, 4..5), + items: vec![ + ast::FlagsItem { + span: span_range(pat, 4..5), + kind: ast::FlagsItemKind::Flag( + ast::Flag::IgnoreWhitespace), + }, + ], + }), + ast: Box::new(lit_with('a', span_range(pat, 6..7))), + }), + lit_with('a', span_range(pat, 9..10)), + lit_with(' ', span_range(pat, 10..11)), + ]))); + + // Test that whitespace after an opening paren is insignificant. + let pat = "(?x)( ?P a )"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Group(ast::Group { + span: span_range(pat, 4..pat.len()), + kind: ast::GroupKind::CaptureName(ast::CaptureName { + span: span_range(pat, 9..12), + name: s("foo"), + index: 1, + }), + ast: Box::new(lit_with('a', span_range(pat, 14..15))), + }), + ]))); + let pat = "(?x)( a )"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Group(ast::Group { + span: span_range(pat, 4..pat.len()), + kind: ast::GroupKind::CaptureIndex(1), + ast: Box::new(lit_with('a', span_range(pat, 7..8))), + }), + ]))); + let pat = "(?x)( ?: a )"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Group(ast::Group { + span: span_range(pat, 4..pat.len()), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span_range(pat, 8..8), + items: vec![], + }), + ast: Box::new(lit_with('a', span_range(pat, 11..12))), + }), + ]))); + let pat = r"(?x)\x { 53 }"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Literal(ast::Literal { + span: span(4..13), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: 'S', + }), + ]))); + + // Test that whitespace after an escape is OK. + let pat = r"(?x)\ "; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Literal(ast::Literal { + span: span_range(pat, 4..6), + kind: ast::LiteralKind::Special( + ast::SpecialLiteralKind::Space), + c: ' ', + }), + ]))); + // ... but only when `x` mode is enabled. + let pat = r"\ "; + assert_eq!( + parser(pat).parse().unwrap_err(), + TestError { + span: span_range(pat, 0..2), + kind: ast::ErrorKind::EscapeUnrecognized, + }); + } + + #[test] + fn parse_newlines() { + let pat = ".\n."; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..3), vec![ + Ast::Dot(span_range(pat, 0..1)), + lit_with('\n', span_range(pat, 1..2)), + Ast::Dot(span_range(pat, 2..3)), + ]))); + + let pat = "foobar\nbaz\nquux\n"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + lit_with('f', nspan(npos(0, 1, 1), npos(1, 1, 2))), + lit_with('o', nspan(npos(1, 1, 2), npos(2, 1, 3))), + lit_with('o', nspan(npos(2, 1, 3), npos(3, 1, 4))), + lit_with('b', nspan(npos(3, 1, 4), npos(4, 1, 5))), + lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))), + lit_with('r', nspan(npos(5, 1, 6), npos(6, 1, 7))), + lit_with('\n', nspan(npos(6, 1, 7), npos(7, 2, 1))), + lit_with('b', nspan(npos(7, 2, 1), npos(8, 2, 2))), + lit_with('a', nspan(npos(8, 2, 2), npos(9, 2, 3))), + lit_with('z', nspan(npos(9, 2, 3), npos(10, 2, 4))), + lit_with('\n', nspan(npos(10, 2, 4), npos(11, 3, 1))), + lit_with('q', nspan(npos(11, 3, 1), npos(12, 3, 2))), + lit_with('u', nspan(npos(12, 3, 2), npos(13, 3, 3))), + lit_with('u', nspan(npos(13, 3, 3), npos(14, 3, 4))), + lit_with('x', nspan(npos(14, 3, 4), npos(15, 3, 5))), + lit_with('\n', nspan(npos(15, 3, 5), npos(16, 4, 1))), + ]))); + } + + #[test] + fn parse_uncounted_repetition() { + assert_eq!( + parser(r"a*").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a+").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::OneOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + + assert_eq!( + parser(r"a?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a??").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..3), + op: ast::RepetitionOp { + span: span(1..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a?b").parse(), + Ok(concat(0..3, vec![ + Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }), + lit('b', 2), + ]))); + assert_eq!( + parser(r"a??b").parse(), + Ok(concat(0..4, vec![ + Ast::Repetition(ast::Repetition { + span: span(0..3), + op: ast::RepetitionOp { + span: span(1..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }), + lit('b', 3), + ]))); + assert_eq!( + parser(r"ab?").parse(), + Ok(concat(0..3, vec![ + lit('a', 0), + Ast::Repetition(ast::Repetition { + span: span(1..3), + op: ast::RepetitionOp { + span: span(2..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('b', 1)), + }), + ]))); + assert_eq!( + parser(r"(ab)?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..5), + op: ast::RepetitionOp { + span: span(4..5), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(group(0..4, 1, concat(1..3, vec![ + lit('a', 1), + lit('b', 2), + ]))), + }))); + assert_eq!( + parser(r"|a?").parse(), + Ok(alt(0..3, vec![ + Ast::Empty(span(0..0)), + Ast::Repetition(ast::Repetition { + span: span(1..3), + op: ast::RepetitionOp { + span: span(2..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 1)), + }), + ]))); + + assert_eq!( + parser(r"*").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(?i)*").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(*)").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(?:?)").parse().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"+").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"?").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(?)").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|*").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|+").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|?").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + } + + #[test] + fn parse_counted_repetition() { + assert_eq!( + parser(r"a{5}").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..4), + op: ast::RepetitionOp { + span: span(1..4), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{5,}").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..5), + op: ast::RepetitionOp { + span: span(1..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::AtLeast(5)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{5,9}").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..6), + op: ast::RepetitionOp { + span: span(1..6), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Bounded(5, 9)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{5}?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..5), + op: ast::RepetitionOp { + span: span(1..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"ab{5}").parse(), + Ok(concat(0..5, vec![ + lit('a', 0), + Ast::Repetition(ast::Repetition { + span: span(1..5), + op: ast::RepetitionOp { + span: span(2..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('b', 1)), + }), + ]))); + assert_eq!( + parser(r"ab{5}c").parse(), + Ok(concat(0..6, vec![ + lit('a', 0), + Ast::Repetition(ast::Repetition { + span: span(1..5), + op: ast::RepetitionOp { + span: span(2..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('b', 1)), + }), + lit('c', 5), + ]))); + + assert_eq!( + parser(r"a{ 5 }").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..6), + op: ast::RepetitionOp { + span: span(1..6), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{ 5 , 9 }").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..10), + op: ast::RepetitionOp { + span: span(1..10), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Bounded(5, 9)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser_ignore_whitespace(r"a{5,9} ?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..8), + op: ast::RepetitionOp { + span: span(1..8), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Bounded(5, 9)), + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }))); + + assert_eq!( + parser(r"a{").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{}").parse().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser(r"a{a").parse().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser(r"a{9999999999}").parse().unwrap_err(), + TestError { + span: span(2..12), + kind: ast::ErrorKind::DecimalInvalid, + }); + assert_eq!( + parser(r"a{9").parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{9,a").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser(r"a{9,9999999999}").parse().unwrap_err(), + TestError { + span: span(4..14), + kind: ast::ErrorKind::DecimalInvalid, + }); + assert_eq!( + parser(r"a{9,").parse().unwrap_err(), + TestError { + span: span(1..4), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{9,11").parse().unwrap_err(), + TestError { + span: span(1..6), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{2,1}").parse().unwrap_err(), + TestError { + span: span(1..6), + kind: ast::ErrorKind::RepetitionCountInvalid, + }); + assert_eq!( + parser(r"{5}").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|{5}").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + } + + #[test] + fn parse_alternate() { + assert_eq!( + parser(r"a|b").parse(), + Ok(Ast::Alternation(ast::Alternation { + span: span(0..3), + asts: vec![lit('a', 0), lit('b', 2)], + }))); + assert_eq!( + parser(r"(a|b)").parse(), + Ok(group(0..5, 1, Ast::Alternation(ast::Alternation { + span: span(1..4), + asts: vec![lit('a', 1), lit('b', 3)], + })))); + + assert_eq!( + parser(r"a|b|c").parse(), + Ok(Ast::Alternation(ast::Alternation { + span: span(0..5), + asts: vec![lit('a', 0), lit('b', 2), lit('c', 4)], + }))); + assert_eq!( + parser(r"ax|by|cz").parse(), + Ok(Ast::Alternation(ast::Alternation { + span: span(0..8), + asts: vec![ + concat(0..2, vec![lit('a', 0), lit('x', 1)]), + concat(3..5, vec![lit('b', 3), lit('y', 4)]), + concat(6..8, vec![lit('c', 6), lit('z', 7)]), + ], + }))); + assert_eq!( + parser(r"(ax|by|cz)").parse(), + Ok(group(0..10, 1, Ast::Alternation(ast::Alternation { + span: span(1..9), + asts: vec![ + concat(1..3, vec![lit('a', 1), lit('x', 2)]), + concat(4..6, vec![lit('b', 4), lit('y', 5)]), + concat(7..9, vec![lit('c', 7), lit('z', 8)]), + ], + })))); + assert_eq!( + parser(r"(ax|(by|(cz)))").parse(), + Ok(group(0..14, 1, alt(1..13, vec![ + concat(1..3, vec![lit('a', 1), lit('x', 2)]), + group(4..13, 2, alt(5..12, vec![ + concat(5..7, vec![lit('b', 5), lit('y', 6)]), + group(8..12, 3, concat(9..11, vec![ + lit('c', 9), + lit('z', 10), + ])), + ])), + ])))); + + assert_eq!( + parser(r"|").parse(), Ok(alt(0..1, vec![ + Ast::Empty(span(0..0)), Ast::Empty(span(1..1)), + ]))); + assert_eq!( + parser(r"||").parse(), Ok(alt(0..2, vec![ + Ast::Empty(span(0..0)), + Ast::Empty(span(1..1)), + Ast::Empty(span(2..2)), + ]))); + assert_eq!( + parser(r"a|").parse(), Ok(alt(0..2, vec![ + lit('a', 0), Ast::Empty(span(2..2)), + ]))); + assert_eq!( + parser(r"|a").parse(), Ok(alt(0..2, vec![ + Ast::Empty(span(0..0)), lit('a', 1), + ]))); + + assert_eq!( + parser(r"(|)").parse(), Ok(group(0..3, 1, alt(1..2, vec![ + Ast::Empty(span(1..1)), Ast::Empty(span(2..2)), + ])))); + assert_eq!( + parser(r"(a|)").parse(), Ok(group(0..4, 1, alt(1..3, vec![ + lit('a', 1), Ast::Empty(span(3..3)), + ])))); + assert_eq!( + parser(r"(|a)").parse(), Ok(group(0..4, 1, alt(1..3, vec![ + Ast::Empty(span(1..1)), lit('a', 2), + ])))); + + assert_eq!( + parser(r"a|b)").parse().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::GroupUnopened, + }); + assert_eq!( + parser(r"(a|b").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnclosed, + }); + } + + #[test] + fn parse_unsupported_lookaround() { + assert_eq!( + parser(r"(?=a)").parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + assert_eq!( + parser(r"(?!a)").parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + assert_eq!( + parser(r"(?<=a)").parse().unwrap_err(), + TestError { + span: span(0..4), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + assert_eq!( + parser(r"(?z)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..8), + kind: ast::GroupKind::CaptureName(ast::CaptureName { + span: span(4..5), + name: s("a"), + index: 1, + }), + ast: Box::new(lit('z', 6)), + }))); + assert_eq!(parser("(?Pz)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..10), + kind: ast::GroupKind::CaptureName(ast::CaptureName { + span: span(4..7), + name: s("abc"), + index: 1, + }), + ast: Box::new(lit('z', 8)), + }))); + + assert_eq!( + parser("(?P<").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::GroupNameUnexpectedEof, + }); + assert_eq!( + parser("(?P<>z)").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::GroupNameEmpty, + }); + assert_eq!( + parser("(?Py)(?Pz)").parse().unwrap_err(), + TestError { + span: span(12..13), + kind: ast::ErrorKind::GroupNameDuplicate { + original: span(4..5), + }, + }); + } + + #[test] + fn parse_flags() { + assert_eq!(parser("i:").parse_flags(), Ok(ast::Flags { + span: span(0..1), + items: vec![ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }], + })); + assert_eq!(parser("i)").parse_flags(), Ok(ast::Flags { + span: span(0..1), + items: vec![ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }], + })); + + assert_eq!(parser("isU:").parse_flags(), Ok(ast::Flags { + span: span(0..3), + items: vec![ + ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(1..2), + kind: ast::FlagsItemKind::Flag( + ast::Flag::DotMatchesNewLine), + }, + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + })); + + assert_eq!(parser("-isU:").parse_flags(), Ok(ast::Flags { + span: span(0..4), + items: vec![ + ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Negation, + }, + ast::FlagsItem { + span: span(1..2), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::DotMatchesNewLine), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + })); + assert_eq!(parser("i-sU:").parse_flags(), Ok(ast::Flags { + span: span(0..4), + items: vec![ + ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(1..2), + kind: ast::FlagsItemKind::Negation, + }, + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::DotMatchesNewLine), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + })); + + assert_eq!( + parser("isU").parse_flags().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::FlagUnexpectedEof, + }); + assert_eq!( + parser("isUa:").parse_flags().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::FlagUnrecognized, + }); + assert_eq!( + parser("isUi:").parse_flags().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::FlagDuplicate { + original: span(0..1), + }, + }); + assert_eq!( + parser("i-sU-i:").parse_flags().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::FlagRepeatedNegation { + original: span(1..2), + }, + }); + assert_eq!( + parser("-)").parse_flags().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::FlagDanglingNegation, + }); + assert_eq!( + parser("i-)").parse_flags().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::FlagDanglingNegation, + }); + assert_eq!( + parser("iU-)").parse_flags().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::FlagDanglingNegation, + }); + } + + #[test] + fn parse_flag() { + assert_eq!(parser("i").parse_flag(), Ok(ast::Flag::CaseInsensitive)); + assert_eq!(parser("m").parse_flag(), Ok(ast::Flag::MultiLine)); + assert_eq!(parser("s").parse_flag(), Ok(ast::Flag::DotMatchesNewLine)); + assert_eq!(parser("U").parse_flag(), Ok(ast::Flag::SwapGreed)); + assert_eq!(parser("u").parse_flag(), Ok(ast::Flag::Unicode)); + assert_eq!(parser("x").parse_flag(), Ok(ast::Flag::IgnoreWhitespace)); + + assert_eq!( + parser("a").parse_flag().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::FlagUnrecognized, + }); + assert_eq!( + parser("☃").parse_flag().unwrap_err(), + TestError { + span: span_range("☃", 0..3), + kind: ast::ErrorKind::FlagUnrecognized, + }); + } + + #[test] + fn parse_primitive_non_escape() { + assert_eq!( + parser(r".").parse_primitive(), + Ok(Primitive::Dot(span(0..1)))); + assert_eq!( + parser(r"^").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..1), + kind: ast::AssertionKind::StartLine, + }))); + assert_eq!( + parser(r"$").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..1), + kind: ast::AssertionKind::EndLine, + }))); + + assert_eq!( + parser(r"a").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..1), + kind: ast::LiteralKind::Verbatim, + c: 'a', + }))); + assert_eq!( + parser(r"|").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..1), + kind: ast::LiteralKind::Verbatim, + c: '|', + }))); + assert_eq!( + parser(r"☃").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span_range("☃", 0..3), + kind: ast::LiteralKind::Verbatim, + c: '☃', + }))); + } + + #[test] + fn parse_escape() { + assert_eq!( + parser(r"\|").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..2), + kind: ast::LiteralKind::Punctuation, + c: '|', + }))); + let specials = &[ + (r"\a", '\x07', ast::SpecialLiteralKind::Bell), + (r"\f", '\x0C', ast::SpecialLiteralKind::FormFeed), + (r"\t", '\t', ast::SpecialLiteralKind::Tab), + (r"\n", '\n', ast::SpecialLiteralKind::LineFeed), + (r"\r", '\r', ast::SpecialLiteralKind::CarriageReturn), + (r"\v", '\x0B', ast::SpecialLiteralKind::VerticalTab), + ]; + for &(pat, c, ref kind) in specials { + assert_eq!( + parser(pat).parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..2), + kind: ast::LiteralKind::Special(kind.clone()), + c: c, + }))); + } + assert_eq!( + parser(r"\A").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::StartText, + }))); + assert_eq!( + parser(r"\z").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::EndText, + }))); + assert_eq!( + parser(r"\b").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::WordBoundary, + }))); + assert_eq!( + parser(r"\B").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::NotWordBoundary, + }))); + + assert_eq!( + parser(r"\").parse_escape().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\y").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::EscapeUnrecognized, + }); + } + + #[test] + fn parse_unsupported_backreference() { + assert_eq!( + parser(r"\0").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::UnsupportedBackreference, + }); + assert_eq!( + parser(r"\9").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::UnsupportedBackreference, + }); + } + + #[test] + fn parse_octal() { + for i in 0..511 { + let pat = format!(r"\{:o}", i); + assert_eq!( + parser_octal(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::Octal, + c: ::std::char::from_u32(i).unwrap(), + }))); + } + assert_eq!( + parser_octal(r"\778").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..3), + kind: ast::LiteralKind::Octal, + c: '?', + }))); + assert_eq!( + parser_octal(r"\7777").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..4), + kind: ast::LiteralKind::Octal, + c: '\u{01FF}', + }))); + assert_eq!( + parser_octal(r"\778").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..4), + asts: vec![ + Ast::Literal(ast::Literal { + span: span(0..3), + kind: ast::LiteralKind::Octal, + c: '?', + }), + Ast::Literal(ast::Literal { + span: span(3..4), + kind: ast::LiteralKind::Verbatim, + c: '8', + }), + ], + }))); + assert_eq!( + parser_octal(r"\7777").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..5), + asts: vec![ + Ast::Literal(ast::Literal { + span: span(0..4), + kind: ast::LiteralKind::Octal, + c: '\u{01FF}', + }), + Ast::Literal(ast::Literal { + span: span(4..5), + kind: ast::LiteralKind::Verbatim, + c: '7', + }), + ], + }))); + + assert_eq!( + parser_octal(r"\8").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::EscapeUnrecognized, + }); + } + + #[test] + fn parse_hex_two() { + for i in 0..256 { + let pat = format!(r"\x{:02x}", i); + assert_eq!( + parser(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::HexFixed(ast::HexLiteralKind::X), + c: ::std::char::from_u32(i).unwrap(), + }))); + } + + assert_eq!( + parser(r"\xF").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\xG").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\xFG").parse_escape().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + } + + #[test] + fn parse_hex_four() { + for i in 0..65536 { + let c = match ::std::char::from_u32(i) { + None => continue, + Some(c) => c, + }; + let pat = format!(r"\u{:04x}", i); + assert_eq!( + parser(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::HexFixed( + ast::HexLiteralKind::UnicodeShort), + c: c, + }))); + } + + assert_eq!( + parser(r"\uF").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\uG").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uFG").parse_escape().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uFFG").parse_escape().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uFFFG").parse_escape().unwrap_err(), + TestError { + span: span(5..6), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uD800").parse_escape().unwrap_err(), + TestError { + span: span(2..6), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + } + + #[test] + fn parse_hex_eight() { + for i in 0..65536 { + let c = match ::std::char::from_u32(i) { + None => continue, + Some(c) => c, + }; + let pat = format!(r"\U{:08x}", i); + assert_eq!( + parser(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::HexFixed( + ast::HexLiteralKind::UnicodeLong), + c: c, + }))); + } + + assert_eq!( + parser(r"\UF").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\UG").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFG").parse_escape().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFG").parse_escape().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFG").parse_escape().unwrap_err(), + TestError { + span: span(5..6), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(6..7), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(7..8), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(8..9), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(9..10), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + } + + #[test] + fn parse_hex_brace() { + assert_eq!( + parser(r"\u{26c4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace( + ast::HexLiteralKind::UnicodeShort), + c: '⛄', + }))); + assert_eq!( + parser(r"\U{26c4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace( + ast::HexLiteralKind::UnicodeLong), + c: '⛄', + }))); + assert_eq!( + parser(r"\x{26c4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: '⛄', + }))); + assert_eq!( + parser(r"\x{26C4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: '⛄', + }))); + assert_eq!( + parser(r"\x{10fFfF}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..10), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: '\u{10FFFF}', + }))); + + assert_eq!( + parser(r"\x").parse_escape().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\x{").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\x{FF").parse_escape().unwrap_err(), + TestError { + span: span(2..5), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\x{}").parse_escape().unwrap_err(), + TestError { + span: span(2..4), + kind: ast::ErrorKind::EscapeHexEmpty, + }); + assert_eq!( + parser(r"\x{FGF}").parse_escape().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\x{FFFFFF}").parse_escape().unwrap_err(), + TestError { + span: span(3..9), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + assert_eq!( + parser(r"\x{D800}").parse_escape().unwrap_err(), + TestError { + span: span(3..7), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + assert_eq!( + parser(r"\x{FFFFFFFFF}").parse_escape().unwrap_err(), + TestError { + span: span(3..12), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + } + + #[test] + fn parse_decimal() { + assert_eq!(parser("123").parse_decimal(), Ok(123)); + assert_eq!(parser("0").parse_decimal(), Ok(0)); + assert_eq!(parser("01").parse_decimal(), Ok(1)); + + assert_eq!( + parser("-1").parse_decimal().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser("").parse_decimal().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser("9999999999").parse_decimal().unwrap_err(), + TestError { + span: span(0..10), + kind: ast::ErrorKind::DecimalInvalid, + }); + } + + #[test] + fn parse_set_class() { + fn union(span: Span, items: Vec) -> ast::ClassSet { + ast::ClassSet::union(ast::ClassSetUnion { + span: span, + items: items, + }) + } + + fn intersection( + span: Span, + lhs: ast::ClassSet, + rhs: ast::ClassSet, + ) -> ast::ClassSet { + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: ast::ClassSetBinaryOpKind::Intersection, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } + + fn difference( + span: Span, + lhs: ast::ClassSet, + rhs: ast::ClassSet, + ) -> ast::ClassSet { + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: ast::ClassSetBinaryOpKind::Difference, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } + + fn symdifference( + span: Span, + lhs: ast::ClassSet, + rhs: ast::ClassSet, + ) -> ast::ClassSet { + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: ast::ClassSetBinaryOpKind::SymmetricDifference, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } + + fn itemset(item: ast::ClassSetItem) -> ast::ClassSet { + ast::ClassSet::Item(item) + } + + fn item_ascii(cls: ast::ClassAscii) -> ast::ClassSetItem { + ast::ClassSetItem::Ascii(cls) + } + + fn item_unicode(cls: ast::ClassUnicode) -> ast::ClassSetItem { + ast::ClassSetItem::Unicode(cls) + } + + fn item_perl(cls: ast::ClassPerl) -> ast::ClassSetItem { + ast::ClassSetItem::Perl(cls) + } + + fn item_bracket(cls: ast::ClassBracketed) -> ast::ClassSetItem { + ast::ClassSetItem::Bracketed(Box::new(cls)) + } + + fn lit(span: Span, c: char) -> ast::ClassSetItem { + ast::ClassSetItem::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Verbatim, + c: c, + }) + } + + fn empty(span: Span) -> ast::ClassSetItem { + ast::ClassSetItem::Empty(span) + } + + fn range(span: Span, start: char, end: char) -> ast::ClassSetItem { + let pos1 = Position { + offset: span.start.offset + start.len_utf8(), + column: span.start.column + 1, + ..span.start + }; + let pos2 = Position { + offset: span.end.offset - end.len_utf8(), + column: span.end.column - 1, + ..span.end + }; + ast::ClassSetItem::Range(ast::ClassSetRange { + span: span, + start: ast::Literal { + span: Span { end: pos1, ..span }, + kind: ast::LiteralKind::Verbatim, + c: start, + }, + end: ast::Literal { + span: Span { start: pos2, ..span }, + kind: ast::LiteralKind::Verbatim, + c: end, + }, + }) + } + + fn alnum(span: Span, negated: bool) -> ast::ClassAscii { + ast::ClassAscii { + span: span, + kind: ast::ClassAsciiKind::Alnum, + negated: negated, + } + } + + fn lower(span: Span, negated: bool) -> ast::ClassAscii { + ast::ClassAscii { + span: span, + kind: ast::ClassAsciiKind::Lower, + negated: negated, + } + } + + assert_eq!( + parser("[[:alnum:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..11), + negated: false, + kind: itemset(item_ascii(alnum(span(1..10), false))), + })))); + assert_eq!( + parser("[[[:alnum:]]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..13), + negated: false, + kind: itemset(item_bracket(ast::ClassBracketed { + span: span(1..12), + negated: false, + kind: itemset(item_ascii(alnum(span(2..11), false))), + })), + })))); + assert_eq!( + parser("[[:alnum:]&&[:lower:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..22), + negated: false, + kind: intersection( + span(1..21), + itemset(item_ascii(alnum(span(1..10), false))), + itemset(item_ascii(lower(span(12..21), false))), + ), + })))); + assert_eq!( + parser("[[:alnum:]--[:lower:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..22), + negated: false, + kind: difference( + span(1..21), + itemset(item_ascii(alnum(span(1..10), false))), + itemset(item_ascii(lower(span(12..21), false))), + ), + })))); + assert_eq!( + parser("[[:alnum:]~~[:lower:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..22), + negated: false, + kind: symdifference( + span(1..21), + itemset(item_ascii(alnum(span(1..10), false))), + itemset(item_ascii(lower(span(12..21), false))), + ), + })))); + + assert_eq!( + parser("[a]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: itemset(lit(span(1..2), 'a')), + })))); + assert_eq!( + parser(r"[a\]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: union(span(1..4), vec![ + lit(span(1..2), 'a'), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..4), + kind: ast::LiteralKind::Punctuation, + c: ']', + }), + ]), + })))); + assert_eq!( + parser(r"[a\-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..6), + negated: false, + kind: union(span(1..5), vec![ + lit(span(1..2), 'a'), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..4), + kind: ast::LiteralKind::Punctuation, + c: '-', + }), + lit(span(4..5), 'z'), + ]), + })))); + assert_eq!( + parser("[ab]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: union(span(1..3), vec![ + lit(span(1..2), 'a'), + lit(span(2..3), 'b'), + ]), + })))); + assert_eq!( + parser("[a-]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: union(span(1..3), vec![ + lit(span(1..2), 'a'), + lit(span(2..3), '-'), + ]), + })))); + assert_eq!( + parser("[-a]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: union(span(1..3), vec![ + lit(span(1..2), '-'), + lit(span(2..3), 'a'), + ]), + })))); + assert_eq!( + parser(r"[\pL]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: itemset(item_unicode(ast::ClassUnicode { + span: span(1..4), + negated: false, + kind: ast::ClassUnicodeKind::OneLetter('L'), + })), + })))); + assert_eq!( + parser(r"[\w]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: itemset(item_perl(ast::ClassPerl { + span: span(1..3), + kind: ast::ClassPerlKind::Word, + negated: false, + })), + })))); + assert_eq!( + parser(r"[a\wz]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..6), + negated: false, + kind: union(span(1..5), vec![ + lit(span(1..2), 'a'), + item_perl(ast::ClassPerl { + span: span(2..4), + kind: ast::ClassPerlKind::Word, + negated: false, + }), + lit(span(4..5), 'z'), + ]), + })))); + + assert_eq!( + parser("[a-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: itemset(range(span(1..4), 'a', 'z')), + })))); + assert_eq!( + parser("[a-cx-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..8), + negated: false, + kind: union(span(1..7), vec![ + range(span(1..4), 'a', 'c'), + range(span(4..7), 'x', 'z'), + ]), + })))); + assert_eq!( + parser(r"[\w&&a-cx-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..12), + negated: false, + kind: intersection( + span(1..11), + itemset(item_perl(ast::ClassPerl { + span: span(1..3), + kind: ast::ClassPerlKind::Word, + negated: false, + })), + union(span(5..11), vec![ + range(span(5..8), 'a', 'c'), + range(span(8..11), 'x', 'z'), + ]), + ), + })))); + assert_eq!( + parser(r"[a-cx-z&&\w]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..12), + negated: false, + kind: intersection( + span(1..11), + union(span(1..7), vec![ + range(span(1..4), 'a', 'c'), + range(span(4..7), 'x', 'z'), + ]), + itemset(item_perl(ast::ClassPerl { + span: span(9..11), + kind: ast::ClassPerlKind::Word, + negated: false, + })), + ), + })))); + assert_eq!( + parser(r"[a--b--c]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..9), + negated: false, + kind: difference( + span(1..8), + difference( + span(1..5), + itemset(lit(span(1..2), 'a')), + itemset(lit(span(4..5), 'b')), + ), + itemset(lit(span(7..8), 'c')), + ), + })))); + assert_eq!( + parser(r"[a~~b~~c]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..9), + negated: false, + kind: symdifference( + span(1..8), + symdifference( + span(1..5), + itemset(lit(span(1..2), 'a')), + itemset(lit(span(4..5), 'b')), + ), + itemset(lit(span(7..8), 'c')), + ), + })))); + assert_eq!( + parser(r"[\^&&^]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..7), + negated: false, + kind: intersection( + span(1..6), + itemset(ast::ClassSetItem::Literal(ast::Literal { + span: span(1..3), + kind: ast::LiteralKind::Punctuation, + c: '^', + })), + itemset(lit(span(5..6), '^')), + ), + })))); + assert_eq!( + parser(r"[\&&&&]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..7), + negated: false, + kind: intersection( + span(1..6), + itemset(ast::ClassSetItem::Literal(ast::Literal { + span: span(1..3), + kind: ast::LiteralKind::Punctuation, + c: '&', + })), + itemset(lit(span(5..6), '&')), + ), + })))); + assert_eq!( + parser(r"[&&&&]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..6), + negated: false, + kind: intersection( + span(1..5), + intersection( + span(1..3), + itemset(empty(span(1..1))), + itemset(empty(span(3..3))), + ), + itemset(empty(span(5..5))), + ), + })))); + + let pat = "[☃-⛄]"; + assert_eq!( + parser(pat).parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span_range(pat, 0..9), + negated: false, + kind: itemset(ast::ClassSetItem::Range(ast::ClassSetRange { + span: span_range(pat, 1..8), + start: ast::Literal { + span: span_range(pat, 1..4), + kind: ast::LiteralKind::Verbatim, + c: '☃', + }, + end: ast::Literal { + span: span_range(pat, 5..8), + kind: ast::LiteralKind::Verbatim, + c: '⛄', + }, + })), + })))); + + assert_eq!( + parser(r"[]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: itemset(lit(span(1..2), ']')), + })))); + assert_eq!( + parser(r"[]\[]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: union(span(1..4), vec![ + lit(span(1..2), ']'), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..4), + kind: ast::LiteralKind::Punctuation, + c: '[', + }), + ]), + })))); + assert_eq!( + parser(r"[\[]]").parse(), + Ok(concat(0..5, vec![ + Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: itemset(ast::ClassSetItem::Literal(ast::Literal { + span: span(1..3), + kind: ast::LiteralKind::Punctuation, + c: '[', + })), + })), + Ast::Literal(ast::Literal { + span: span(4..5), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ]))); + + assert_eq!( + parser("[").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[[").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[[-]").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[[[:alnum:]").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser(r"[\b]").parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::ClassEscapeInvalid, + }); + assert_eq!( + parser(r"[\w-a]").parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::ClassRangeLiteral, + }); + assert_eq!( + parser(r"[a-\w]").parse().unwrap_err(), + TestError { + span: span(3..5), + kind: ast::ErrorKind::ClassRangeLiteral, + }); + assert_eq!( + parser(r"[z-a]").parse().unwrap_err(), + TestError { + span: span(1..4), + kind: ast::ErrorKind::ClassRangeInvalid, + }); + + assert_eq!( + parser_ignore_whitespace("[a ").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser_ignore_whitespace("[a- ").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + } + + #[test] + fn parse_set_class_open() { + assert_eq!( + parser("[a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..1), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[^a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ ^ a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[-a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..2), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ - a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[^-a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..3), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[--a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[]a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..2), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ ] a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[^]a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..3), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[-]a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..2), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + + assert_eq!( + parser("[").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser_ignore_whitespace("[ ") + .parse_set_class_open() + .unwrap_err(), + TestError { + span: span(0..5), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[^").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[]").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[-").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[--").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::ClassUnclosed, + }); + } + + #[test] + fn maybe_parse_ascii_class() { + assert_eq!( + parser(r"[:alnum:]").maybe_parse_ascii_class(), + Some(ast::ClassAscii { + span: span(0..9), + kind: ast::ClassAsciiKind::Alnum, + negated: false, + })); + assert_eq!( + parser(r"[:alnum:]A").maybe_parse_ascii_class(), + Some(ast::ClassAscii { + span: span(0..9), + kind: ast::ClassAsciiKind::Alnum, + negated: false, + })); + assert_eq!( + parser(r"[:^alnum:]").maybe_parse_ascii_class(), + Some(ast::ClassAscii { + span: span(0..10), + kind: ast::ClassAsciiKind::Alnum, + negated: true, + })); + + let p = parser(r"[:"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:^"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[^:alnum:]"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:alnnum:]"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:alnum]"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:alnum:"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + } + + #[test] + fn parse_unicode_class() { + assert_eq!( + parser(r"\pN").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..3), + negated: false, + kind: ast::ClassUnicodeKind::OneLetter('N'), + }))); + assert_eq!( + parser(r"\PN").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..3), + negated: true, + kind: ast::ClassUnicodeKind::OneLetter('N'), + }))); + assert_eq!( + parser(r"\p{N}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: false, + kind: ast::ClassUnicodeKind::Named(s("N")), + }))); + assert_eq!( + parser(r"\P{N}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: true, + kind: ast::ClassUnicodeKind::Named(s("N")), + }))); + assert_eq!( + parser(r"\p{Greek}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..9), + negated: false, + kind: ast::ClassUnicodeKind::Named(s("Greek")), + }))); + + assert_eq!( + parser(r"\p{scx:Katakana}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..16), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Colon, + name: s("scx"), + value: s("Katakana"), + }, + }))); + assert_eq!( + parser(r"\p{scx=Katakana}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..16), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Equal, + name: s("scx"), + value: s("Katakana"), + }, + }))); + assert_eq!( + parser(r"\p{scx!=Katakana}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..17), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::NotEqual, + name: s("scx"), + value: s("Katakana"), + }, + }))); + + assert_eq!( + parser(r"\p{:}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Colon, + name: s(""), + value: s(""), + }, + }))); + assert_eq!( + parser(r"\p{=}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Equal, + name: s(""), + value: s(""), + }, + }))); + assert_eq!( + parser(r"\p{!=}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..6), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::NotEqual, + name: s(""), + value: s(""), + }, + }))); + + assert_eq!( + parser(r"\p").parse_escape().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\p{").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\p{N").parse_escape().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\p{Greek").parse_escape().unwrap_err(), + TestError { + span: span(8..8), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + + assert_eq!( + parser(r"\pNz").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..4), + asts: vec![ + Ast::Class(ast::Class::Unicode(ast::ClassUnicode { + span: span(0..3), + negated: false, + kind: ast::ClassUnicodeKind::OneLetter('N'), + })), + Ast::Literal(ast::Literal { + span: span(3..4), + kind: ast::LiteralKind::Verbatim, + c: 'z', + }), + ], + }))); + assert_eq!( + parser(r"\p{Greek}z").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..10), + asts: vec![ + Ast::Class(ast::Class::Unicode(ast::ClassUnicode { + span: span(0..9), + negated: false, + kind: ast::ClassUnicodeKind::Named(s("Greek")), + })), + Ast::Literal(ast::Literal { + span: span(9..10), + kind: ast::LiteralKind::Verbatim, + c: 'z', + }), + ], + }))); + } + + #[test] + fn parse_perl_class() { + assert_eq!( + parser(r"\d").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: false, + }))); + assert_eq!( + parser(r"\D").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: true, + }))); + assert_eq!( + parser(r"\s").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Space, + negated: false, + }))); + assert_eq!( + parser(r"\S").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Space, + negated: true, + }))); + assert_eq!( + parser(r"\w").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Word, + negated: false, + }))); + assert_eq!( + parser(r"\W").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Word, + negated: true, + }))); + + assert_eq!( + parser(r"\d").parse(), + Ok(Ast::Class(ast::Class::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: false, + })))); + assert_eq!( + parser(r"\dz").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..3), + asts: vec![ + Ast::Class(ast::Class::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: false, + })), + Ast::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: 'z', + }), + ], + }))); + } + + // This tests a bug fix where the nest limit checker wasn't decrementing + // its depth during post-traversal, which causes long regexes to trip + // the default limit too aggressively. + #[test] + fn regression_454_nest_too_big() { + let pattern = r#" + 2(?: + [45]\d{3}| + 7(?: + 1[0-267]| + 2[0-289]| + 3[0-29]| + 4[01]| + 5[1-3]| + 6[013]| + 7[0178]| + 91 + )| + 8(?: + 0[125]| + [139][1-6]| + 2[0157-9]| + 41| + 6[1-35]| + 7[1-5]| + 8[1-8]| + 90 + )| + 9(?: + 0[0-2]| + 1[0-4]| + 2[568]| + 3[3-6]| + 5[5-7]| + 6[0167]| + 7[15]| + 8[0146-9] + ) + )\d{4} + "#; + assert!(parser_nest_limit(pattern, 50).parse().is_ok()); + } + + // This tests that we treat a trailing `-` in a character class as a + // literal `-` even when whitespace mode is enabled and there is whitespace + // after the trailing `-`. + #[test] + fn regression_455_trailing_dash_ignore_whitespace() { + assert!(parser("(?x)[ / - ]").parse().is_ok()); + assert!(parser("(?x)[ a - ]").parse().is_ok()); + assert!(parser("(?x)[ + a + - ] + ").parse().is_ok()); + assert!(parser("(?x)[ + a # wat + - ] + ").parse().is_ok()); + + assert!(parser("(?x)[ / -").parse().is_err()); + assert!(parser("(?x)[ / - ").parse().is_err()); + assert!(parser("(?x)[ + / - + ").parse().is_err()); + assert!(parser("(?x)[ + / - # wat + ").parse().is_err()); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/ast/print.rs b/bash-5.1/vendor/regex-syntax/src/ast/print.rs new file mode 100644 index 0000000..ddec734 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/ast/print.rs @@ -0,0 +1,586 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This module provides a regular expression printer for `Ast`. +*/ + +use std::fmt; + +use ast::{self, Ast}; +use ast::visitor::{self, Visitor}; + +/// A builder for constructing a printer. +/// +/// Note that since a printer doesn't have any configuration knobs, this type +/// remains unexported. +#[derive(Clone, Debug)] +struct PrinterBuilder { + _priv: (), +} + +impl Default for PrinterBuilder { + fn default() -> PrinterBuilder { + PrinterBuilder::new() + } +} + +impl PrinterBuilder { + fn new() -> PrinterBuilder { + PrinterBuilder { + _priv: (), + } + } + + fn build(&self) -> Printer { + Printer { + _priv: (), + } + } +} + +/// A printer for a regular expression abstract syntax tree. +/// +/// A printer converts an abstract syntax tree (AST) to a regular expression +/// pattern string. This particular printer uses constant stack space and heap +/// space proportional to the size of the AST. +/// +/// This printer will not necessarily preserve the original formatting of the +/// regular expression pattern string. For example, all whitespace and comments +/// are ignored. +#[derive(Debug)] +pub struct Printer { + _priv: (), +} + +impl Printer { + /// Create a new printer. + pub fn new() -> Printer { + PrinterBuilder::new().build() + } + + /// Print the given `Ast` to the given writer. The writer must implement + /// `fmt::Write`. Typical implementations of `fmt::Write` that can be used + /// here are a `fmt::Formatter` (which is available in `fmt::Display` + /// implementations) or a `&mut String`. + pub fn print(&mut self, ast: &Ast, wtr: W) -> fmt::Result { + visitor::visit(ast, Writer { printer: self, wtr: wtr }) + } +} + +#[derive(Debug)] +struct Writer<'p, W> { + printer: &'p mut Printer, + wtr: W, +} + +impl<'p, W: fmt::Write> Visitor for Writer<'p, W> { + type Output = (); + type Err = fmt::Error; + + fn finish(self) -> fmt::Result { + Ok(()) + } + + fn visit_pre(&mut self, ast: &Ast) -> fmt::Result { + match *ast { + Ast::Group(ref x) => self.fmt_group_pre(x), + Ast::Class(ast::Class::Bracketed(ref x)) => { + self.fmt_class_bracketed_pre(x) + } + _ => Ok(()) + } + } + + fn visit_post(&mut self, ast: &Ast) -> fmt::Result { + use ast::Class; + + match *ast { + Ast::Empty(_) => Ok(()), + Ast::Flags(ref x) => self.fmt_set_flags(x), + Ast::Literal(ref x) => self.fmt_literal(x), + Ast::Dot(_) => self.wtr.write_str("."), + Ast::Assertion(ref x) => self.fmt_assertion(x), + Ast::Class(Class::Perl(ref x)) => self.fmt_class_perl(x), + Ast::Class(Class::Unicode(ref x)) => self.fmt_class_unicode(x), + Ast::Class(Class::Bracketed(ref x)) => { + self.fmt_class_bracketed_post(x) + } + Ast::Repetition(ref x) => self.fmt_repetition(x), + Ast::Group(ref x) => self.fmt_group_post(x), + Ast::Alternation(_) => Ok(()), + Ast::Concat(_) => Ok(()), + } + } + + fn visit_alternation_in(&mut self) -> fmt::Result { + self.wtr.write_str("|") + } + + fn visit_class_set_item_pre( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + match *ast { + ast::ClassSetItem::Bracketed(ref x) => { + self.fmt_class_bracketed_pre(x) + } + _ => Ok(()), + } + } + + fn visit_class_set_item_post( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + use ast::ClassSetItem::*; + + match *ast { + Empty(_) => Ok(()), + Literal(ref x) => self.fmt_literal(x), + Range(ref x) => { + try!(self.fmt_literal(&x.start)); + try!(self.wtr.write_str("-")); + try!(self.fmt_literal(&x.end)); + Ok(()) + } + Ascii(ref x) => self.fmt_class_ascii(x), + Unicode(ref x) => self.fmt_class_unicode(x), + Perl(ref x) => self.fmt_class_perl(x), + Bracketed(ref x) => self.fmt_class_bracketed_post(x), + Union(_) => Ok(()), + } + } + + fn visit_class_set_binary_op_in( + &mut self, + ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + self.fmt_class_set_binary_op_kind(&ast.kind) + } +} + +impl<'p, W: fmt::Write> Writer<'p, W> { + fn fmt_group_pre(&mut self, ast: &ast::Group) -> fmt::Result { + use ast::GroupKind::*; + match ast.kind { + CaptureIndex(_) => self.wtr.write_str("("), + CaptureName(ref x) => { + try!(self.wtr.write_str("(?P<")); + try!(self.wtr.write_str(&x.name)); + try!(self.wtr.write_str(">")); + Ok(()) + } + NonCapturing(ref flags) => { + try!(self.wtr.write_str("(?")); + try!(self.fmt_flags(flags)); + try!(self.wtr.write_str(":")); + Ok(()) + } + } + } + + fn fmt_group_post(&mut self, _ast: &ast::Group) -> fmt::Result { + self.wtr.write_str(")") + } + + fn fmt_repetition(&mut self, ast: &ast::Repetition) -> fmt::Result { + use ast::RepetitionKind::*; + match ast.op.kind { + ZeroOrOne if ast.greedy => self.wtr.write_str("?"), + ZeroOrOne => self.wtr.write_str("??"), + ZeroOrMore if ast.greedy => self.wtr.write_str("*"), + ZeroOrMore => self.wtr.write_str("*?"), + OneOrMore if ast.greedy => self.wtr.write_str("+"), + OneOrMore => self.wtr.write_str("+?"), + Range(ref x) => { + try!(self.fmt_repetition_range(x)); + if !ast.greedy { + try!(self.wtr.write_str("?")); + } + Ok(()) + } + } + } + + fn fmt_repetition_range( + &mut self, + ast: &ast::RepetitionRange, + ) -> fmt::Result { + use ast::RepetitionRange::*; + match *ast { + Exactly(x) => write!(self.wtr, "{{{}}}", x), + AtLeast(x) => write!(self.wtr, "{{{},}}", x), + Bounded(x, y) => write!(self.wtr, "{{{},{}}}", x, y), + } + } + + fn fmt_literal(&mut self, ast: &ast::Literal) -> fmt::Result { + use ast::LiteralKind::*; + + match ast.kind { + Verbatim => self.wtr.write_char(ast.c), + Punctuation => write!(self.wtr, r"\{}", ast.c), + Octal => write!(self.wtr, r"\{:o}", ast.c as u32), + HexFixed(ast::HexLiteralKind::X) => { + write!(self.wtr, r"\x{:02X}", ast.c as u32) + } + HexFixed(ast::HexLiteralKind::UnicodeShort) => { + write!(self.wtr, r"\u{:04X}", ast.c as u32) + } + HexFixed(ast::HexLiteralKind::UnicodeLong) => { + write!(self.wtr, r"\U{:08X}", ast.c as u32) + } + HexBrace(ast::HexLiteralKind::X) => { + write!(self.wtr, r"\x{{{:X}}}", ast.c as u32) + } + HexBrace(ast::HexLiteralKind::UnicodeShort) => { + write!(self.wtr, r"\u{{{:X}}}", ast.c as u32) + } + HexBrace(ast::HexLiteralKind::UnicodeLong) => { + write!(self.wtr, r"\U{{{:X}}}", ast.c as u32) + } + Special(ast::SpecialLiteralKind::Bell) => { + self.wtr.write_str(r"\a") + } + Special(ast::SpecialLiteralKind::FormFeed) => { + self.wtr.write_str(r"\f") + } + Special(ast::SpecialLiteralKind::Tab) => { + self.wtr.write_str(r"\t") + } + Special(ast::SpecialLiteralKind::LineFeed) => { + self.wtr.write_str(r"\n") + } + Special(ast::SpecialLiteralKind::CarriageReturn) => { + self.wtr.write_str(r"\r") + } + Special(ast::SpecialLiteralKind::VerticalTab) => { + self.wtr.write_str(r"\v") + } + Special(ast::SpecialLiteralKind::Space) => { + self.wtr.write_str(r"\ ") + } + } + } + + fn fmt_assertion(&mut self, ast: &ast::Assertion) -> fmt::Result { + use ast::AssertionKind::*; + match ast.kind { + StartLine => self.wtr.write_str("^"), + EndLine => self.wtr.write_str("$"), + StartText => self.wtr.write_str(r"\A"), + EndText => self.wtr.write_str(r"\z"), + WordBoundary => self.wtr.write_str(r"\b"), + NotWordBoundary => self.wtr.write_str(r"\B"), + } + } + + fn fmt_set_flags(&mut self, ast: &ast::SetFlags) -> fmt::Result { + try!(self.wtr.write_str("(?")); + try!(self.fmt_flags(&ast.flags)); + try!(self.wtr.write_str(")")); + Ok(()) + } + + fn fmt_flags(&mut self, ast: &ast::Flags) -> fmt::Result { + use ast::{Flag, FlagsItemKind}; + + for item in &ast.items { + try!(match item.kind { + FlagsItemKind::Negation => self.wtr.write_str("-"), + FlagsItemKind::Flag(ref flag) => { + match *flag { + Flag::CaseInsensitive => self.wtr.write_str("i"), + Flag::MultiLine => self.wtr.write_str("m"), + Flag::DotMatchesNewLine => self.wtr.write_str("s"), + Flag::SwapGreed => self.wtr.write_str("U"), + Flag::Unicode => self.wtr.write_str("u"), + Flag::IgnoreWhitespace => self.wtr.write_str("x"), + } + } + }); + } + Ok(()) + } + + fn fmt_class_bracketed_pre( + &mut self, + ast: &ast::ClassBracketed, + ) -> fmt::Result { + if ast.negated { + self.wtr.write_str("[^") + } else { + self.wtr.write_str("[") + } + } + + fn fmt_class_bracketed_post( + &mut self, + _ast: &ast::ClassBracketed, + ) -> fmt::Result { + self.wtr.write_str("]") + } + + fn fmt_class_set_binary_op_kind( + &mut self, + ast: &ast::ClassSetBinaryOpKind, + ) -> fmt::Result { + use ast::ClassSetBinaryOpKind::*; + match *ast { + Intersection => self.wtr.write_str("&&"), + Difference => self.wtr.write_str("--"), + SymmetricDifference => self.wtr.write_str("~~"), + } + } + + fn fmt_class_perl(&mut self, ast: &ast::ClassPerl) -> fmt::Result { + use ast::ClassPerlKind::*; + match ast.kind { + Digit if ast.negated => self.wtr.write_str(r"\D"), + Digit => self.wtr.write_str(r"\d"), + Space if ast.negated => self.wtr.write_str(r"\S"), + Space => self.wtr.write_str(r"\s"), + Word if ast.negated => self.wtr.write_str(r"\W"), + Word => self.wtr.write_str(r"\w"), + } + } + + fn fmt_class_ascii(&mut self, ast: &ast::ClassAscii) -> fmt::Result { + use ast::ClassAsciiKind::*; + match ast.kind { + Alnum if ast.negated => self.wtr.write_str("[:^alnum:]"), + Alnum => self.wtr.write_str("[:alnum:]"), + Alpha if ast.negated => self.wtr.write_str("[:^alpha:]"), + Alpha => self.wtr.write_str("[:alpha:]"), + Ascii if ast.negated => self.wtr.write_str("[:^ascii:]"), + Ascii => self.wtr.write_str("[:ascii:]"), + Blank if ast.negated => self.wtr.write_str("[:^blank:]"), + Blank => self.wtr.write_str("[:blank:]"), + Cntrl if ast.negated => self.wtr.write_str("[:^cntrl:]"), + Cntrl => self.wtr.write_str("[:cntrl:]"), + Digit if ast.negated => self.wtr.write_str("[:^digit:]"), + Digit => self.wtr.write_str("[:digit:]"), + Graph if ast.negated => self.wtr.write_str("[:^graph:]"), + Graph => self.wtr.write_str("[:graph:]"), + Lower if ast.negated => self.wtr.write_str("[:^lower:]"), + Lower => self.wtr.write_str("[:lower:]"), + Print if ast.negated => self.wtr.write_str("[:^print:]"), + Print => self.wtr.write_str("[:print:]"), + Punct if ast.negated => self.wtr.write_str("[:^punct:]"), + Punct => self.wtr.write_str("[:punct:]"), + Space if ast.negated => self.wtr.write_str("[:^space:]"), + Space => self.wtr.write_str("[:space:]"), + Upper if ast.negated => self.wtr.write_str("[:^upper:]"), + Upper => self.wtr.write_str("[:upper:]"), + Word if ast.negated => self.wtr.write_str("[:^word:]"), + Word => self.wtr.write_str("[:word:]"), + Xdigit if ast.negated => self.wtr.write_str("[:^xdigit:]"), + Xdigit => self.wtr.write_str("[:xdigit:]"), + } + } + + fn fmt_class_unicode(&mut self, ast: &ast::ClassUnicode) -> fmt::Result { + use ast::ClassUnicodeKind::*; + use ast::ClassUnicodeOpKind::*; + + if ast.negated { + try!(self.wtr.write_str(r"\P")); + } else { + try!(self.wtr.write_str(r"\p")); + } + match ast.kind { + OneLetter(c) => self.wtr.write_char(c), + Named(ref x) => write!(self.wtr, "{{{}}}", x), + NamedValue { op: Equal, ref name, ref value } => { + write!(self.wtr, "{{{}={}}}", name, value) + } + NamedValue { op: Colon, ref name, ref value } => { + write!(self.wtr, "{{{}:{}}}", name, value) + } + NamedValue { op: NotEqual, ref name, ref value } => { + write!(self.wtr, "{{{}!={}}}", name, value) + } + } + } +} + +#[cfg(test)] +mod tests { + use ast::parse::ParserBuilder; + use super::Printer; + + fn roundtrip(given: &str) { + roundtrip_with(|b| b, given); + } + + fn roundtrip_with(mut f: F, given: &str) + where F: FnMut(&mut ParserBuilder) -> &mut ParserBuilder + { + let mut builder = ParserBuilder::new(); + f(&mut builder); + let ast = builder.build().parse(given).unwrap(); + + let mut printer = Printer::new(); + let mut dst = String::new(); + printer.print(&ast, &mut dst).unwrap(); + assert_eq!(given, dst); + } + + #[test] + fn print_literal() { + roundtrip("a"); + roundtrip(r"\["); + roundtrip_with(|b| b.octal(true), r"\141"); + roundtrip(r"\x61"); + roundtrip(r"\x7F"); + roundtrip(r"\u0061"); + roundtrip(r"\U00000061"); + roundtrip(r"\x{61}"); + roundtrip(r"\x{7F}"); + roundtrip(r"\u{61}"); + roundtrip(r"\U{61}"); + + roundtrip(r"\a"); + roundtrip(r"\f"); + roundtrip(r"\t"); + roundtrip(r"\n"); + roundtrip(r"\r"); + roundtrip(r"\v"); + roundtrip(r"(?x)\ "); + } + + #[test] + fn print_dot() { + roundtrip("."); + } + + #[test] + fn print_concat() { + roundtrip("ab"); + roundtrip("abcde"); + roundtrip("a(bcd)ef"); + } + + #[test] + fn print_alternation() { + roundtrip("a|b"); + roundtrip("a|b|c|d|e"); + roundtrip("|a|b|c|d|e"); + roundtrip("|a|b|c|d|e|"); + roundtrip("a(b|c|d)|e|f"); + } + + #[test] + fn print_assertion() { + roundtrip(r"^"); + roundtrip(r"$"); + roundtrip(r"\A"); + roundtrip(r"\z"); + roundtrip(r"\b"); + roundtrip(r"\B"); + } + + #[test] + fn print_repetition() { + roundtrip("a?"); + roundtrip("a??"); + roundtrip("a*"); + roundtrip("a*?"); + roundtrip("a+"); + roundtrip("a+?"); + roundtrip("a{5}"); + roundtrip("a{5}?"); + roundtrip("a{5,}"); + roundtrip("a{5,}?"); + roundtrip("a{5,10}"); + roundtrip("a{5,10}?"); + } + + #[test] + fn print_flags() { + roundtrip("(?i)"); + roundtrip("(?-i)"); + roundtrip("(?s-i)"); + roundtrip("(?-si)"); + roundtrip("(?siUmux)"); + } + + #[test] + fn print_group() { + roundtrip("(?i:a)"); + roundtrip("(?Pa)"); + roundtrip("(a)"); + } + + #[test] + fn print_class() { + roundtrip(r"[abc]"); + roundtrip(r"[a-z]"); + roundtrip(r"[^a-z]"); + roundtrip(r"[a-z0-9]"); + roundtrip(r"[-a-z0-9]"); + roundtrip(r"[-a-z0-9]"); + roundtrip(r"[a-z0-9---]"); + roundtrip(r"[a-z&&m-n]"); + roundtrip(r"[[a-z&&m-n]]"); + roundtrip(r"[a-z--m-n]"); + roundtrip(r"[a-z~~m-n]"); + roundtrip(r"[a-z[0-9]]"); + roundtrip(r"[a-z[^0-9]]"); + + roundtrip(r"\d"); + roundtrip(r"\D"); + roundtrip(r"\s"); + roundtrip(r"\S"); + roundtrip(r"\w"); + roundtrip(r"\W"); + + roundtrip(r"[[:alnum:]]"); + roundtrip(r"[[:^alnum:]]"); + roundtrip(r"[[:alpha:]]"); + roundtrip(r"[[:^alpha:]]"); + roundtrip(r"[[:ascii:]]"); + roundtrip(r"[[:^ascii:]]"); + roundtrip(r"[[:blank:]]"); + roundtrip(r"[[:^blank:]]"); + roundtrip(r"[[:cntrl:]]"); + roundtrip(r"[[:^cntrl:]]"); + roundtrip(r"[[:digit:]]"); + roundtrip(r"[[:^digit:]]"); + roundtrip(r"[[:graph:]]"); + roundtrip(r"[[:^graph:]]"); + roundtrip(r"[[:lower:]]"); + roundtrip(r"[[:^lower:]]"); + roundtrip(r"[[:print:]]"); + roundtrip(r"[[:^print:]]"); + roundtrip(r"[[:punct:]]"); + roundtrip(r"[[:^punct:]]"); + roundtrip(r"[[:space:]]"); + roundtrip(r"[[:^space:]]"); + roundtrip(r"[[:upper:]]"); + roundtrip(r"[[:^upper:]]"); + roundtrip(r"[[:word:]]"); + roundtrip(r"[[:^word:]]"); + roundtrip(r"[[:xdigit:]]"); + roundtrip(r"[[:^xdigit:]]"); + + roundtrip(r"\pL"); + roundtrip(r"\PL"); + roundtrip(r"\p{L}"); + roundtrip(r"\P{L}"); + roundtrip(r"\p{X=Y}"); + roundtrip(r"\P{X=Y}"); + roundtrip(r"\p{X:Y}"); + roundtrip(r"\P{X:Y}"); + roundtrip(r"\p{X!=Y}"); + roundtrip(r"\P{X!=Y}"); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/ast/visitor.rs b/bash-5.1/vendor/regex-syntax/src/ast/visitor.rs new file mode 100644 index 0000000..268ac45 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/ast/visitor.rs @@ -0,0 +1,557 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; + +use ast::{self, Ast}; + +/// A trait for visiting an abstract syntax tree (AST) in depth first order. +/// +/// The principle aim of this trait is to enable callers to perform case +/// analysis on an abstract syntax tree without necessarily using recursion. +/// In particular, this permits callers to do case analysis with constant stack +/// usage, which can be important since the size of an abstract syntax tree +/// may be proportional to end user input. +/// +/// Typical usage of this trait involves providing an implementation and then +/// running it using the [`visit`](fn.visit.html) function. +/// +/// Note that the abstract syntax tree for a regular expression is quite +/// complex. Unless you specifically need it, you might be able to use the +/// much simpler +/// [high-level intermediate representation](../hir/struct.Hir.html) +/// and its +/// [corresponding `Visitor` trait](../hir/trait.Visitor.html) +/// instead. +pub trait Visitor { + /// The result of visiting an AST. + type Output; + /// An error that visiting an AST might return. + type Err; + + /// All implementors of `Visitor` must provide a `finish` method, which + /// yields the result of visiting the AST or an error. + fn finish(self) -> Result; + + /// This method is called before beginning traversal of the AST. + fn start(&mut self) {} + + /// This method is called on an `Ast` before descending into child `Ast` + /// nodes. + fn visit_pre(&mut self, _ast: &Ast) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on an `Ast` after descending all of its child + /// `Ast` nodes. + fn visit_post(&mut self, _ast: &Ast) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called between child nodes of an + /// [`Alternation`](struct.Alternation.html). + fn visit_alternation_in(&mut self) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetItem`](enum.ClassSetItem.html) + /// before descending into child nodes. + fn visit_class_set_item_pre( + &mut self, + _ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetItem`](enum.ClassSetItem.html) + /// after descending into child nodes. + fn visit_class_set_item_post( + &mut self, + _ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetBinaryOp`](struct.ClassSetBinaryOp.html) + /// before descending into child nodes. + fn visit_class_set_binary_op_pre( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetBinaryOp`](struct.ClassSetBinaryOp.html) + /// after descending into child nodes. + fn visit_class_set_binary_op_post( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called between the left hand and right hand child nodes + /// of a [`ClassSetBinaryOp`](struct.ClassSetBinaryOp.html). + fn visit_class_set_binary_op_in( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + Ok(()) + } +} + +/// Executes an implementation of `Visitor` in constant stack space. +/// +/// This function will visit every node in the given `Ast` while calling the +/// appropriate methods provided by the +/// [`Visitor`](trait.Visitor.html) trait. +/// +/// The primary use case for this method is when one wants to perform case +/// analysis over an `Ast` without using a stack size proportional to the depth +/// of the `Ast`. Namely, this method will instead use constant stack size, but +/// will use heap space proportional to the size of the `Ast`. This may be +/// desirable in cases where the size of `Ast` is proportional to end user +/// input. +/// +/// If the visitor returns an error at any point, then visiting is stopped and +/// the error is returned. +pub fn visit(ast: &Ast, visitor: V) -> Result { + HeapVisitor::new().visit(ast, visitor) +} + +/// HeapVisitor visits every item in an `Ast` recursively using constant stack +/// size and a heap size proportional to the size of the `Ast`. +struct HeapVisitor<'a> { + /// A stack of `Ast` nodes. This is roughly analogous to the call stack + /// used in a typical recursive visitor. + stack: Vec<(&'a Ast, Frame<'a>)>, + /// Similar to the `Ast` stack above, but is used only for character + /// classes. In particular, character classes embed their own mini + /// recursive syntax. + stack_class: Vec<(ClassInduct<'a>, ClassFrame<'a>)>, +} + +/// Represents a single stack frame while performing structural induction over +/// an `Ast`. +enum Frame<'a> { + /// A stack frame allocated just before descending into a repetition + /// operator's child node. + Repetition(&'a ast::Repetition), + /// A stack frame allocated just before descending into a group's child + /// node. + Group(&'a ast::Group), + /// The stack frame used while visiting every child node of a concatenation + /// of expressions. + Concat { + /// The child node we are currently visiting. + head: &'a Ast, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Ast], + }, + /// The stack frame used while visiting every child node of an alternation + /// of expressions. + Alternation { + /// The child node we are currently visiting. + head: &'a Ast, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Ast], + }, +} + +/// Represents a single stack frame while performing structural induction over +/// a character class. +enum ClassFrame<'a> { + /// The stack frame used while visiting every child node of a union of + /// character class items. + Union { + /// The child node we are currently visiting. + head: &'a ast::ClassSetItem, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [ast::ClassSetItem], + }, + /// The stack frame used while a binary class operation. + Binary { + op: &'a ast::ClassSetBinaryOp, + }, + /// A stack frame allocated just before descending into a binary operator's + /// left hand child node. + BinaryLHS { + op: &'a ast::ClassSetBinaryOp, + lhs: &'a ast::ClassSet, + rhs: &'a ast::ClassSet, + }, + /// A stack frame allocated just before descending into a binary operator's + /// right hand child node. + BinaryRHS { + op: &'a ast::ClassSetBinaryOp, + rhs: &'a ast::ClassSet, + }, +} + +/// A representation of the inductive step when performing structural induction +/// over a character class. +/// +/// Note that there is no analogous explicit type for the inductive step for +/// `Ast` nodes because the inductive step is just an `Ast`. For character +/// classes, the inductive step can produce one of two possible child nodes: +/// an item or a binary operation. (An item cannot be a binary operation +/// because that would imply binary operations can be unioned in the concrete +/// syntax, which is not possible.) +enum ClassInduct<'a> { + Item(&'a ast::ClassSetItem), + BinaryOp(&'a ast::ClassSetBinaryOp), +} + +impl<'a> HeapVisitor<'a> { + fn new() -> HeapVisitor<'a> { + HeapVisitor { stack: vec![], stack_class: vec![] } + } + + fn visit( + &mut self, + mut ast: &'a Ast, + mut visitor: V, + ) -> Result { + self.stack.clear(); + self.stack_class.clear(); + + visitor.start(); + loop { + try!(visitor.visit_pre(ast)); + if let Some(x) = try!(self.induct(ast, &mut visitor)) { + let child = x.child(); + self.stack.push((ast, x)); + ast = child; + continue; + } + // No induction means we have a base case, so we can post visit + // it now. + try!(visitor.visit_post(ast)); + + // At this point, we now try to pop our call stack until it is + // either empty or we hit another inductive case. + loop { + let (post_ast, frame) = match self.stack.pop() { + None => return visitor.finish(), + Some((post_ast, frame)) => (post_ast, frame), + }; + // If this is a concat/alternate, then we might have additional + // inductive steps to process. + if let Some(x) = self.pop(frame) { + if let Frame::Alternation {..} = x { + try!(visitor.visit_alternation_in()); + } + ast = x.child(); + self.stack.push((post_ast, x)); + break; + } + // Otherwise, we've finished visiting all the child nodes for + // this AST, so we can post visit it now. + try!(visitor.visit_post(post_ast)); + } + } + } + + /// Build a stack frame for the given AST if one is needed (which occurs if + /// and only if there are child nodes in the AST). Otherwise, return None. + /// + /// If this visits a class, then the underlying visitor implementation may + /// return an error which will be passed on here. + fn induct( + &mut self, + ast: &'a Ast, + visitor: &mut V, + ) -> Result>, V::Err> { + Ok(match *ast { + Ast::Class(ast::Class::Bracketed(ref x)) => { + try!(self.visit_class(x, visitor)); + None + } + Ast::Repetition(ref x) => Some(Frame::Repetition(x)), + Ast::Group(ref x) => Some(Frame::Group(x)), + Ast::Concat(ref x) if x.asts.is_empty() => None, + Ast::Concat(ref x) => { + Some(Frame::Concat { + head: &x.asts[0], + tail: &x.asts[1..], + }) + } + Ast::Alternation(ref x) if x.asts.is_empty() => None, + Ast::Alternation(ref x) => { + Some(Frame::Alternation { + head: &x.asts[0], + tail: &x.asts[1..], + }) + } + _ => None, + }) + } + + /// Pops the given frame. If the frame has an additional inductive step, + /// then return it, otherwise return `None`. + fn pop(&self, induct: Frame<'a>) -> Option> { + match induct { + Frame::Repetition(_) => None, + Frame::Group(_) => None, + Frame::Concat { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Concat { + head: &tail[0], + tail: &tail[1..], + }) + } + } + Frame::Alternation { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Alternation { + head: &tail[0], + tail: &tail[1..], + }) + } + } + } + } + + fn visit_class( + &mut self, + ast: &'a ast::ClassBracketed, + visitor: &mut V, + ) -> Result<(), V::Err> { + let mut ast = ClassInduct::from_bracketed(ast); + loop { + try!(self.visit_class_pre(&ast, visitor)); + if let Some(x) = self.induct_class(&ast) { + let child = x.child(); + self.stack_class.push((ast, x)); + ast = child; + continue; + } + try!(self.visit_class_post(&ast, visitor)); + + // At this point, we now try to pop our call stack until it is + // either empty or we hit another inductive case. + loop { + let (post_ast, frame) = match self.stack_class.pop() { + None => return Ok(()), + Some((post_ast, frame)) => (post_ast, frame), + }; + // If this is a union or a binary op, then we might have + // additional inductive steps to process. + if let Some(x) = self.pop_class(frame) { + if let ClassFrame::BinaryRHS { ref op, .. } = x { + try!(visitor.visit_class_set_binary_op_in(op)); + } + ast = x.child(); + self.stack_class.push((post_ast, x)); + break; + } + // Otherwise, we've finished visiting all the child nodes for + // this class node, so we can post visit it now. + try!(self.visit_class_post(&post_ast, visitor)); + } + } + } + + /// Call the appropriate `Visitor` methods given an inductive step. + fn visit_class_pre( + &self, + ast: &ClassInduct<'a>, + visitor: &mut V, + ) -> Result<(), V::Err> { + match *ast { + ClassInduct::Item(item) => { + try!(visitor.visit_class_set_item_pre(item)); + } + ClassInduct::BinaryOp(op) => { + try!(visitor.visit_class_set_binary_op_pre(op)); + } + } + Ok(()) + } + + /// Call the appropriate `Visitor` methods given an inductive step. + fn visit_class_post( + &self, + ast: &ClassInduct<'a>, + visitor: &mut V, + ) -> Result<(), V::Err> { + match *ast { + ClassInduct::Item(item) => { + try!(visitor.visit_class_set_item_post(item)); + } + ClassInduct::BinaryOp(op) => { + try!(visitor.visit_class_set_binary_op_post(op)); + } + } + Ok(()) + } + + /// Build a stack frame for the given class node if one is needed (which + /// occurs if and only if there are child nodes). Otherwise, return None. + fn induct_class( + &self, + ast: &ClassInduct<'a>, + ) -> Option> { + match *ast { + ClassInduct::Item(&ast::ClassSetItem::Bracketed(ref x)) => { + match x.kind { + ast::ClassSet::Item(ref item) => { + Some(ClassFrame::Union { + head: item, + tail: &[], + }) + } + ast::ClassSet::BinaryOp(ref op) => { + Some(ClassFrame::Binary { op: op }) + } + } + } + ClassInduct::Item(&ast::ClassSetItem::Union(ref x)) => { + if x.items.is_empty() { + None + } else { + Some(ClassFrame::Union { + head: &x.items[0], + tail: &x.items[1..], + }) + } + } + ClassInduct::BinaryOp(op) => { + Some(ClassFrame::BinaryLHS { + op: op, + lhs: &op.lhs, + rhs: &op.rhs, + }) + } + _ => None, + } + } + + /// Pops the given frame. If the frame has an additional inductive step, + /// then return it, otherwise return `None`. + fn pop_class(&self, induct: ClassFrame<'a>) -> Option> { + match induct { + ClassFrame::Union { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(ClassFrame::Union { + head: &tail[0], + tail: &tail[1..], + }) + } + } + ClassFrame::Binary {..} => None, + ClassFrame::BinaryLHS { op, rhs, .. } => { + Some(ClassFrame::BinaryRHS { + op: op, + rhs: rhs, + }) + } + ClassFrame::BinaryRHS {..} => None, + } + } +} + +impl<'a> Frame<'a> { + /// Perform the next inductive step on this frame and return the next + /// child AST node to visit. + fn child(&self) -> &'a Ast { + match *self { + Frame::Repetition(rep) => &rep.ast, + Frame::Group(group) => &group.ast, + Frame::Concat { head, .. } => head, + Frame::Alternation { head, .. } => head, + } + } +} + +impl<'a> ClassFrame<'a> { + /// Perform the next inductive step on this frame and return the next + /// child class node to visit. + fn child(&self) -> ClassInduct<'a> { + match *self { + ClassFrame::Union { head, .. } => ClassInduct::Item(head), + ClassFrame::Binary { op, .. } => ClassInduct::BinaryOp(op), + ClassFrame::BinaryLHS { ref lhs, .. } => { + ClassInduct::from_set(lhs) + } + ClassFrame::BinaryRHS { ref rhs, .. } => { + ClassInduct::from_set(rhs) + } + } + } +} + +impl<'a> ClassInduct<'a> { + fn from_bracketed(ast: &'a ast::ClassBracketed) -> ClassInduct<'a> { + ClassInduct::from_set(&ast.kind) + } + + fn from_set(ast: &'a ast::ClassSet) -> ClassInduct<'a> { + match *ast { + ast::ClassSet::Item(ref item) => ClassInduct::Item(item), + ast::ClassSet::BinaryOp(ref op) => ClassInduct::BinaryOp(op), + } + } +} + +impl<'a> fmt::Debug for ClassFrame<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let x = match *self { + ClassFrame::Union{..} => "Union", + ClassFrame::Binary{..} => "Binary", + ClassFrame::BinaryLHS{..} => "BinaryLHS", + ClassFrame::BinaryRHS{..} => "BinaryRHS", + }; + write!(f, "{}", x) + } +} + +impl<'a> fmt::Debug for ClassInduct<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let x = match *self { + ClassInduct::Item(it) => { + match *it { + ast::ClassSetItem::Empty(_) => "Item(Empty)", + ast::ClassSetItem::Literal(_) => "Item(Literal)", + ast::ClassSetItem::Range(_) => "Item(Range)", + ast::ClassSetItem::Ascii(_) => "Item(Ascii)", + ast::ClassSetItem::Perl(_) => "Item(Perl)", + ast::ClassSetItem::Unicode(_) => "Item(Unicode)", + ast::ClassSetItem::Bracketed(_) => "Item(Bracketed)", + ast::ClassSetItem::Union(_) => "Item(Union)", + } + } + ClassInduct::BinaryOp(it) => { + match it.kind { + ast::ClassSetBinaryOpKind::Intersection => { + "BinaryOp(Intersection)" + } + ast::ClassSetBinaryOpKind::Difference => { + "BinaryOp(Difference)" + } + ast::ClassSetBinaryOpKind::SymmetricDifference => { + "BinaryOp(SymmetricDifference)" + } + } + } + }; + write!(f, "{}", x) + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/either.rs b/bash-5.1/vendor/regex-syntax/src/either.rs new file mode 100644 index 0000000..7ae41e4 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/either.rs @@ -0,0 +1,8 @@ +/// A simple binary sum type. +/// +/// This is occasionally useful in an ad hoc fashion. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Either { + Left(Left), + Right(Right), +} diff --git a/bash-5.1/vendor/regex-syntax/src/error.rs b/bash-5.1/vendor/regex-syntax/src/error.rs new file mode 100644 index 0000000..3f2fade --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/error.rs @@ -0,0 +1,297 @@ +use std::cmp; +use std::error; +use std::fmt; +use std::result; + +use ast; +use hir; + +/// A type alias for dealing with errors returned by this crate. +pub type Result = result::Result; + +/// This error type encompasses any error that can be returned by this crate. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Error { + /// An error that occurred while translating concrete syntax into abstract + /// syntax (AST). + Parse(ast::Error), + /// An error that occurred while translating abstract syntax into a high + /// level intermediate representation (HIR). + Translate(hir::Error), + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl From for Error { + fn from(err: ast::Error) -> Error { + Error::Parse(err) + } +} + +impl From for Error { + fn from(err: hir::Error) -> Error { + Error::Translate(err) + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Parse(ref x) => x.description(), + Error::Translate(ref x) => x.description(), + _ => unreachable!(), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Parse(ref x) => x.fmt(f), + Error::Translate(ref x) => x.fmt(f), + _ => unreachable!(), + } + } +} + +/// A helper type for formatting nice error messages. +/// +/// This type is responsible for reporting regex parse errors in a nice human +/// readable format. Most of its complexity is from interspersing notational +/// markers pointing out the position where an error occurred. +#[derive(Debug)] +pub struct Formatter<'e, E: 'e> { + /// The original regex pattern in which the error occurred. + pattern: &'e str, + /// The error kind. It must impl fmt::Display. + err: &'e E, + /// The primary span of the error. + span: &'e ast::Span, + /// An auxiliary and optional span, in case the error needs to point to + /// two locations (e.g., when reporting a duplicate capture group name). + aux_span: Option<&'e ast::Span>, +} + +impl<'e> From<&'e ast::Error> for Formatter<'e, ast::ErrorKind> { + fn from(err: &'e ast::Error) -> Self { + Formatter { + pattern: err.pattern(), + err: err.kind(), + span: err.span(), + aux_span: err.auxiliary_span(), + } + } +} + +impl<'e> From<&'e hir::Error> for Formatter<'e, hir::ErrorKind> { + fn from(err: &'e hir::Error) -> Self { + Formatter { + pattern: err.pattern(), + err: err.kind(), + span: err.span(), + aux_span: None, + } + } +} + +impl<'e, E: fmt::Display> fmt::Display for Formatter<'e, E> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let spans = Spans::from_formatter(self); + if self.pattern.contains('\n') { + let divider = repeat_char('~', 79); + + try!(writeln!(f, "regex parse error:")); + try!(writeln!(f, "{}", divider)); + let notated = spans.notate(); + try!(write!(f, "{}", notated)); + try!(writeln!(f, "{}", divider)); + // If we have error spans that cover multiple lines, then we just + // note the line numbers. + if !spans.multi_line.is_empty() { + let mut notes = vec![]; + for span in &spans.multi_line { + notes.push(format!( + "on line {} (column {}) through line {} (column {})", + span.start.line, span.start.column, + span.end.line, span.end.column - 1)); + } + try!(writeln!(f, "{}", notes.join("\n"))); + } + try!(write!(f, "error: {}", self.err)); + } else { + try!(writeln!(f, "regex parse error:")); + let notated = Spans::from_formatter(self).notate(); + try!(write!(f, "{}", notated)); + try!(write!(f, "error: {}", self.err)); + } + Ok(()) + } +} + +/// This type represents an arbitrary number of error spans in a way that makes +/// it convenient to notate the regex pattern. ("Notate" means "point out +/// exactly where the error occurred in the regex pattern.") +/// +/// Technically, we can only ever have two spans given our current error +/// structure. However, after toiling with a specific algorithm for handling +/// two spans, it became obvious that an algorithm to handle an arbitrary +/// number of spans was actually much simpler. +struct Spans<'p> { + /// The original regex pattern string. + pattern: &'p str, + /// The total width that should be used for line numbers. The width is + /// used for left padding the line numbers for alignment. + /// + /// A value of `0` means line numbers should not be displayed. That is, + /// the pattern is itself only one line. + line_number_width: usize, + /// All error spans that occur on a single line. This sequence always has + /// length equivalent to the number of lines in `pattern`, where the index + /// of the sequence represents a line number, starting at `0`. The spans + /// in each line are sorted in ascending order. + by_line: Vec>, + /// All error spans that occur over one or more lines. That is, the start + /// and end position of the span have different line numbers. The spans are + /// sorted in ascending order. + multi_line: Vec, +} + +impl<'p> Spans<'p> { + /// Build a sequence of spans from a formatter. + fn from_formatter<'e, E: fmt::Display>( + fmter: &'p Formatter<'e, E>, + ) -> Spans<'p> { + let mut line_count = fmter.pattern.lines().count(); + // If the pattern ends with a `\n` literal, then our line count is + // off by one, since a span can occur immediately after the last `\n`, + // which is consider to be an additional line. + if fmter.pattern.ends_with('\n') { + line_count += 1; + } + let line_number_width = + if line_count <= 1 { + 0 + } else { + line_count.to_string().len() + }; + let mut spans = Spans { + pattern: &fmter.pattern, + line_number_width: line_number_width, + by_line: vec![vec![]; line_count], + multi_line: vec![], + }; + spans.add(fmter.span.clone()); + if let Some(span) = fmter.aux_span { + spans.add(span.clone()); + } + spans + } + + /// Add the given span to this sequence, putting it in the right place. + fn add(&mut self, span: ast::Span) { + // This is grossly inefficient since we sort after each add, but right + // now, we only ever add two spans at most. + if span.is_one_line() { + let i = span.start.line - 1; // because lines are 1-indexed + self.by_line[i].push(span); + self.by_line[i].sort(); + } else { + self.multi_line.push(span); + self.multi_line.sort(); + } + } + + /// Notate the pattern string with carents (`^`) pointing at each span + /// location. This only applies to spans that occur within a single line. + fn notate(&self) -> String { + let mut notated = String::new(); + for (i, line) in self.pattern.lines().enumerate() { + if self.line_number_width > 0 { + notated.push_str(&self.left_pad_line_number(i + 1)); + notated.push_str(": "); + } else { + notated.push_str(" "); + } + notated.push_str(line); + notated.push('\n'); + if let Some(notes) = self.notate_line(i) { + notated.push_str(¬es); + notated.push('\n'); + } + } + notated + } + + /// Return notes for the line indexed at `i` (zero-based). If there are no + /// spans for the given line, then `None` is returned. Otherwise, an + /// appropriately space padded string with correctly positioned `^` is + /// returned, accounting for line numbers. + fn notate_line(&self, i: usize) -> Option { + let spans = &self.by_line[i]; + if spans.is_empty() { + return None; + } + let mut notes = String::new(); + for _ in 0..self.line_number_padding() { + notes.push(' '); + } + let mut pos = 0; + for span in spans { + for _ in pos..(span.start.column - 1) { + notes.push(' '); + pos += 1; + } + let note_len = span.end.column.saturating_sub(span.start.column); + for _ in 0..cmp::max(1, note_len) { + notes.push('^'); + pos += 1; + } + } + Some(notes) + } + + /// Left pad the given line number with spaces such that it is aligned with + /// other line numbers. + fn left_pad_line_number(&self, n: usize) -> String { + let n = n.to_string(); + let pad = self.line_number_width.checked_sub(n.len()).unwrap(); + let mut result = repeat_char(' ', pad); + result.push_str(&n); + result + } + + /// Return the line number padding beginning at the start of each line of + /// the pattern. + /// + /// If the pattern is only one line, then this returns a fixed padding + /// for visual indentation. + fn line_number_padding(&self) -> usize { + if self.line_number_width == 0 { + 4 + } else { + 2 + self.line_number_width + } + } +} + +fn repeat_char(c: char, count: usize) -> String { + ::std::iter::repeat(c).take(count).collect() +} + +#[cfg(test)] +mod tests { + use ast::parse::Parser; + + // See: https://github.com/rust-lang/regex/issues/464 + #[test] + fn regression_464() { + let err = Parser::new().parse("a{\n").unwrap_err(); + // This test checks that the error formatter doesn't panic. + assert!(!err.to_string().is_empty()); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/hir/interval.rs b/bash-5.1/vendor/regex-syntax/src/hir/interval.rs new file mode 100644 index 0000000..a7e70ef --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/hir/interval.rs @@ -0,0 +1,490 @@ +use std::char; +use std::cmp; +use std::fmt::Debug; +use std::slice; +use std::u8; + +// This module contains an *internal* implementation of interval sets. +// +// The primary invariant that interval sets guards is canonical ordering. That +// is, every interval set contains an ordered sequence of intervals where +// no two intervals are overlapping or adjacent. While this invariant is +// ocassionally broken within the implementation, it should be impossible for +// callers to observe it. +// +// Since case folding (as implemented below) breaks that invariant, we roll +// that into this API even though it is a little out of place in an otherwise +// generic interval set. +// +// Some of the implementation complexity here is a result of me wanting to +// preserve the sequential representation without using additional memory. +// In many cases, we do use linear extra memory, but it is at most 2x and it +// is amortized. If we relaxed the memory requirements, this implementation +// could become much simpler. The extra memory is honestly probably OK, but +// character classes (especially of the Unicode variety) can become quite +// large, and it would be nice to keep regex compilation snappy even in debug +// builds. (In the past, I have been careless with this area of code and it has +// caused slow regex compilations in debug mode, so this isn't entirely +// unwarranted.) +// +// Tests on this are relegated to the public API of HIR in src/hir.rs. + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IntervalSet { + ranges: Vec, +} + +impl IntervalSet { + /// Create a new set from a sequence of intervals. Each interval is + /// specified as a pair of bounds, where both bounds are inclusive. + /// + /// The given ranges do not need to be in any specific order, and ranges + /// may overlap. + pub fn new>(intervals: T) -> IntervalSet { + let mut set = IntervalSet { ranges: intervals.into_iter().collect() }; + set.canonicalize(); + set + } + + /// Add a new interval to this set. + pub fn push(&mut self, interval: I) { + // TODO: This could be faster. e.g., Push the interval such that + // it preserves canonicalization. + self.ranges.push(interval); + self.canonicalize(); + } + + /// Return an iterator over all intervals in this set. + /// + /// The iterator yields intervals in ascending order. + pub fn iter(&self) -> IntervalSetIter { + IntervalSetIter(self.ranges.iter()) + } + + /// Return an immutable slice of intervals in this set. + /// + /// The sequence returned is in canonical ordering. + pub fn intervals(&self) -> &[I] { + &self.ranges + } + + /// Expand this interval set such that it contains all case folded + /// characters. For example, if this class consists of the range `a-z`, + /// then applying case folding will result in the class containing both the + /// ranges `a-z` and `A-Z`. + pub fn case_fold_simple(&mut self) { + let len = self.ranges.len(); + for i in 0..len { + let range = self.ranges[i]; + range.case_fold_simple(&mut self.ranges); + } + self.canonicalize(); + } + + /// Union this set with the given set, in place. + pub fn union(&mut self, other: &IntervalSet) { + // This could almost certainly be done more efficiently. + self.ranges.extend(&other.ranges); + self.canonicalize(); + } + + /// Intersect this set with the given set, in place. + pub fn intersect(&mut self, other: &IntervalSet) { + if self.ranges.is_empty() { + return; + } + if other.ranges.is_empty() { + self.ranges.clear(); + return; + } + + // There should be a way to do this in-place with constant memory, + // but I couldn't figure out a simple way to do it. So just append + // the intersection to the end of this range, and then drain it before + // we're done. + let drain_end = self.ranges.len(); + + let mut ita = (0..drain_end).into_iter(); + let mut itb = (0..other.ranges.len()).into_iter(); + let mut a = ita.next().unwrap(); + let mut b = itb.next().unwrap(); + loop { + if let Some(ab) = self.ranges[a].intersect(&other.ranges[b]) { + self.ranges.push(ab); + } + let (it, aorb) = + if self.ranges[a].upper() < other.ranges[b].upper() { + (&mut ita, &mut a) + } else { + (&mut itb, &mut b) + }; + match it.next() { + Some(v) => *aorb = v, + None => break, + } + } + self.ranges.drain(..drain_end); + } + + /// Subtract the given set from this set, in place. + pub fn difference(&mut self, other: &IntervalSet) { + if self.ranges.is_empty() || other.ranges.is_empty() { + return; + } + + // This algorithm is (to me) surprisingly complex. A search of the + // interwebs indicate that this is a potentially interesting problem. + // Folks seem to suggest interval or segment trees, but I'd like to + // avoid the overhead (both runtime and conceptual) of that. + // + // The following is basically my Shitty First Draft. Therefore, in + // order to grok it, you probably need to read each line carefully. + // Simplifications are most welcome! + // + // Remember, we can assume the canonical format invariant here, which + // says that all ranges are sorted, not overlapping and not adjacent in + // each class. + let drain_end = self.ranges.len(); + let (mut a, mut b) = (0, 0); + 'LOOP: + while a < drain_end && b < other.ranges.len() { + // Basically, the easy cases are when neither range overlaps with + // each other. If the `b` range is less than our current `a` + // range, then we can skip it and move on. + if other.ranges[b].upper() < self.ranges[a].lower() { + b += 1; + continue; + } + // ... similarly for the `a` range. If it's less than the smallest + // `b` range, then we can add it as-is. + if self.ranges[a].upper() < other.ranges[b].lower() { + let range = self.ranges[a]; + self.ranges.push(range); + a += 1; + continue; + } + // Otherwise, we have overlapping ranges. + assert!(!self.ranges[a].is_intersection_empty(&other.ranges[b])); + + // This part is tricky and was non-obvious to me without looking + // at explicit examples (see the tests). The trickiness stems from + // two things: 1) subtracting a range from another range could + // yield two ranges and 2) after subtracting a range, it's possible + // that future ranges can have an impact. The loop below advances + // the `b` ranges until they can't possible impact the current + // range. + // + // For example, if our `a` range is `a-t` and our next three `b` + // ranges are `a-c`, `g-i`, `r-t` and `x-z`, then we need to apply + // subtraction three times before moving on to the next `a` range. + let mut range = self.ranges[a]; + while b < other.ranges.len() + && !range.is_intersection_empty(&other.ranges[b]) + { + let old_range = range; + range = match range.difference(&other.ranges[b]) { + (None, None) => { + // We lost the entire range, so move on to the next + // without adding this one. + a += 1; + continue 'LOOP; + } + (Some(range1), None) | (None, Some(range1)) => range1, + (Some(range1), Some(range2)) => { + self.ranges.push(range1); + range2 + } + }; + // It's possible that the `b` range has more to contribute + // here. In particular, if it is greater than the original + // range, then it might impact the next `a` range *and* it + // has impacted the current `a` range as much as possible, + // so we can quit. We don't bump `b` so that the next `a` + // range can apply it. + if other.ranges[b].upper() > old_range.upper() { + break; + } + // Otherwise, the next `b` range might apply to the current + // `a` range. + b += 1; + } + self.ranges.push(range); + a += 1; + } + while a < drain_end { + let range = self.ranges[a]; + self.ranges.push(range); + a += 1; + } + self.ranges.drain(..drain_end); + } + + /// Compute the symmetric difference of the two sets, in place. + /// + /// This computes the symmetric difference of two interval sets. This + /// removes all elements in this set that are also in the given set, + /// but also adds all elements from the given set that aren't in this + /// set. That is, the set will contain all elements in either set, + /// but will not contain any elements that are in both sets. + pub fn symmetric_difference(&mut self, other: &IntervalSet) { + // TODO(burntsushi): Fix this so that it amortizes allocation. + let mut intersection = self.clone(); + intersection.intersect(other); + self.union(other); + self.difference(&intersection); + } + + /// Negate this interval set. + /// + /// For all `x` where `x` is any element, if `x` was in this set, then it + /// will not be in this set after negation. + pub fn negate(&mut self) { + if self.ranges.is_empty() { + let (min, max) = (I::Bound::min_value(), I::Bound::max_value()); + self.ranges.push(I::create(min, max)); + return; + } + + // There should be a way to do this in-place with constant memory, + // but I couldn't figure out a simple way to do it. So just append + // the negation to the end of this range, and then drain it before + // we're done. + let drain_end = self.ranges.len(); + + // We do checked arithmetic below because of the canonical ordering + // invariant. + if self.ranges[0].lower() > I::Bound::min_value() { + let upper = self.ranges[0].lower().decrement(); + self.ranges.push(I::create(I::Bound::min_value(), upper)); + } + for i in 1..drain_end { + let lower = self.ranges[i - 1].upper().increment(); + let upper = self.ranges[i].lower().decrement(); + self.ranges.push(I::create(lower, upper)); + } + if self.ranges[drain_end - 1].upper() < I::Bound::max_value() { + let lower = self.ranges[drain_end - 1].upper().increment(); + self.ranges.push(I::create(lower, I::Bound::max_value())); + } + self.ranges.drain(..drain_end); + } + + /// Converts this set into a canonical ordering. + fn canonicalize(&mut self) { + if self.is_canonical() { + return; + } + self.ranges.sort(); + assert!(!self.ranges.is_empty()); + + // Is there a way to do this in-place with constant memory? I couldn't + // figure out a way to do it. So just append the canonicalization to + // the end of this range, and then drain it before we're done. + let drain_end = self.ranges.len(); + for oldi in 0..drain_end { + // If we've added at least one new range, then check if we can + // merge this range in the previously added range. + if self.ranges.len() > drain_end { + let (last, rest) = self.ranges.split_last_mut().unwrap(); + if let Some(union) = last.union(&rest[oldi]) { + *last = union; + continue; + } + } + let range = self.ranges[oldi]; + self.ranges.push(range); + } + self.ranges.drain(..drain_end); + } + + /// Returns true if and only if this class is in a canonical ordering. + fn is_canonical(&self) -> bool { + for pair in self.ranges.windows(2) { + if pair[0] >= pair[1] { + return false; + } + if pair[0].is_contiguous(&pair[1]) { + return false; + } + } + true + } +} + +/// An iterator over intervals. +#[derive(Debug)] +pub struct IntervalSetIter<'a, I: 'a>(slice::Iter<'a, I>); + +impl<'a, I> Iterator for IntervalSetIter<'a, I> { + type Item = &'a I; + + fn next(&mut self) -> Option<&'a I> { + self.0.next() + } +} + +pub trait Interval: + Clone + Copy + Debug + Default + Eq + PartialEq + PartialOrd + Ord +{ + type Bound: Bound; + + fn lower(&self) -> Self::Bound; + fn upper(&self) -> Self::Bound; + fn set_lower(&mut self, bound: Self::Bound); + fn set_upper(&mut self, bound: Self::Bound); + fn case_fold_simple(&self, intervals: &mut Vec); + + /// Create a new interval. + fn create(lower: Self::Bound, upper: Self::Bound) -> Self { + let mut int = Self::default(); + if lower <= upper { + int.set_lower(lower); + int.set_upper(upper); + } else { + int.set_lower(upper); + int.set_upper(lower); + } + int + } + + /// Union the given overlapping range into this range. + /// + /// If the two ranges aren't contiguous, then this returns `None`. + fn union(&self, other: &Self) -> Option { + if !self.is_contiguous(other) { + return None; + } + let lower = cmp::min(self.lower(), other.lower()); + let upper = cmp::max(self.upper(), other.upper()); + Some(Self::create(lower, upper)) + } + + /// Intersect this range with the given range and return the result. + /// + /// If the intersection is empty, then this returns `None`. + fn intersect(&self, other: &Self) -> Option { + let lower = cmp::max(self.lower(), other.lower()); + let upper = cmp::min(self.upper(), other.upper()); + if lower <= upper { + Some(Self::create(lower, upper)) + } else { + None + } + } + + /// Subtract the given range from this range and return the resulting + /// ranges. + /// + /// If subtraction would result in an empty range, then no ranges are + /// returned. + fn difference(&self, other: &Self) -> (Option, Option) { + if self.is_subset(other) { + return (None, None); + } + if self.is_intersection_empty(other) { + return (Some(self.clone()), None); + } + let add_lower = other.lower() > self.lower(); + let add_upper = other.upper() < self.upper(); + // We know this because !self.is_subset(other) and the ranges have + // a non-empty intersection. + assert!(add_lower || add_upper); + let mut ret = (None, None); + if add_lower { + let upper = other.lower().decrement(); + ret.0 = Some(Self::create(self.lower(), upper)); + } + if add_upper { + let lower = other.upper().increment(); + let range = Self::create(lower, self.upper()); + if ret.0.is_none() { + ret.0 = Some(range); + } else { + ret.1 = Some(range); + } + } + ret + } + + /// Compute the symmetric difference the given range from this range. This + /// returns the union of the two ranges minus its intersection. + fn symmetric_difference( + &self, + other: &Self, + ) -> (Option, Option) { + let union = match self.union(other) { + None => return (Some(self.clone()), Some(other.clone())), + Some(union) => union, + }; + let intersection = match self.intersect(other) { + None => return (Some(self.clone()), Some(other.clone())), + Some(intersection) => intersection, + }; + union.difference(&intersection) + } + + /// Returns true if and only if the two ranges are contiguous. Two ranges + /// are contiguous if and only if the ranges are either overlapping or + /// adjacent. + fn is_contiguous(&self, other: &Self) -> bool { + let lower1 = self.lower().as_u32(); + let upper1 = self.upper().as_u32(); + let lower2 = other.lower().as_u32(); + let upper2 = other.upper().as_u32(); + cmp::max(lower1, lower2) <= cmp::min(upper1, upper2).saturating_add(1) + } + + /// Returns true if and only if the intersection of this range and the + /// other range is empty. + fn is_intersection_empty(&self, other: &Self) -> bool { + let (lower1, upper1) = (self.lower(), self.upper()); + let (lower2, upper2) = (other.lower(), other.upper()); + cmp::max(lower1, lower2) > cmp::min(upper1, upper2) + } + + /// Returns true if and only if this range is a subset of the other range. + fn is_subset(&self, other: &Self) -> bool { + let (lower1, upper1) = (self.lower(), self.upper()); + let (lower2, upper2) = (other.lower(), other.upper()); + (lower2 <= lower1 && lower1 <= upper2) + && (lower2 <= upper1 && upper1 <= upper2) + } +} + +pub trait Bound: Copy + Clone + Debug + Eq + PartialEq + PartialOrd + Ord { + fn min_value() -> Self; + fn max_value() -> Self; + fn as_u32(self) -> u32; + fn increment(self) -> Self; + fn decrement(self) -> Self; +} + +impl Bound for u8 { + fn min_value() -> Self { u8::MIN } + fn max_value() -> Self { u8::MAX } + fn as_u32(self) -> u32 { self as u32 } + fn increment(self) -> Self { self.checked_add(1).unwrap() } + fn decrement(self) -> Self { self.checked_sub(1).unwrap() } +} + +impl Bound for char { + fn min_value() -> Self { '\x00' } + fn max_value() -> Self { '\u{10FFFF}' } + fn as_u32(self) -> u32 { self as u32 } + + fn increment(self) -> Self { + match self { + '\u{D7FF}' => '\u{E000}', + c => char::from_u32((c as u32).checked_add(1).unwrap()).unwrap(), + } + } + + fn decrement(self) -> Self { + match self { + '\u{E000}' => '\u{D7FF}', + c => char::from_u32((c as u32).checked_sub(1).unwrap()).unwrap(), + } + } +} + +// Tests for interval sets are written in src/hir.rs against the public API. diff --git a/bash-5.1/vendor/regex-syntax/src/hir/literal/mod.rs b/bash-5.1/vendor/regex-syntax/src/hir/literal/mod.rs new file mode 100644 index 0000000..3113ec9 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/hir/literal/mod.rs @@ -0,0 +1,1553 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Provides routines for extracting literal prefixes and suffixes from an `Hir`. +*/ + +use std::cmp; +use std::fmt; +use std::iter; +use std::mem; +use std::ops; + +use hir::{self, Hir, HirKind}; +use unicode; + +/// A set of literal byte strings extracted from a regular expression. +/// +/// Every member of the set is a `Literal`, which is represented by a +/// `Vec`. (Notably, it may contain invalid UTF-8.) Every member is +/// said to be either *complete* or *cut*. A complete literal means that +/// it extends until the beginning (or end) of the regular expression. In +/// some circumstances, this can be used to indicate a match in the regular +/// expression. +/// +/// A key aspect of literal extraction is knowing when to stop. It is not +/// feasible to blindly extract all literals from a regular expression, even if +/// there are finitely many. For example, the regular expression `[0-9]{10}` +/// has `10^10` distinct literals. For this reason, literal extraction is +/// bounded to some low number by default using heuristics, but the limits can +/// be tweaked. +/// +/// **WARNING**: Literal extraction uses stack space proportional to the size +/// of the `Hir` expression. At some point, this drawback will be eliminated. +/// To protect yourself, set a reasonable +/// [`nest_limit` on your `Parser`](../../struct.ParserBuilder.html#method.nest_limit). +/// This is done for you by default. +#[derive(Clone, Eq, PartialEq)] +pub struct Literals { + lits: Vec, + limit_size: usize, + limit_class: usize, +} + +/// A single member of a set of literals extracted from a regular expression. +/// +/// This type has `Deref` and `DerefMut` impls to `Vec` so that all slice +/// and `Vec` operations are available. +#[derive(Clone, Eq, Ord)] +pub struct Literal { + v: Vec, + cut: bool, +} + +impl Literals { + /// Returns a new empty set of literals using default limits. + pub fn empty() -> Literals { + Literals { + lits: vec![], + limit_size: 250, + limit_class: 10, + } + } + + /// Returns a set of literal prefixes extracted from the given `Hir`. + pub fn prefixes(expr: &Hir) -> Literals { + let mut lits = Literals::empty(); + lits.union_prefixes(expr); + lits + } + + /// Returns a set of literal suffixes extracted from the given `Hir`. + pub fn suffixes(expr: &Hir) -> Literals { + let mut lits = Literals::empty(); + lits.union_suffixes(expr); + lits + } + + /// Get the approximate size limit (in bytes) of this set. + pub fn limit_size(&self) -> usize { + self.limit_size + } + + /// Set the approximate size limit (in bytes) of this set. + /// + /// If extracting a literal would put the set over this limit, then + /// extraction stops. + /// + /// The new limits will only apply to additions to this set. Existing + /// members remain unchanged, even if the set exceeds the new limit. + pub fn set_limit_size(&mut self, size: usize) -> &mut Literals { + self.limit_size = size; + self + } + + /// Get the character class size limit for this set. + pub fn limit_class(&self) -> usize { + self.limit_class + } + + /// Limits the size of character(or byte) classes considered. + /// + /// A value of `0` prevents all character classes from being considered. + /// + /// This limit also applies to case insensitive literals, since each + /// character in the case insensitive literal is converted to a class, and + /// then case folded. + /// + /// The new limits will only apply to additions to this set. Existing + /// members remain unchanged, even if the set exceeds the new limit. + pub fn set_limit_class(&mut self, size: usize) -> &mut Literals { + self.limit_class = size; + self + } + + /// Returns the set of literals as a slice. Its order is unspecified. + pub fn literals(&self) -> &[Literal] { + &self.lits + } + + /// Returns the length of the smallest literal. + /// + /// Returns None is there are no literals in the set. + pub fn min_len(&self) -> Option { + let mut min = None; + for lit in &self.lits { + match min { + None => min = Some(lit.len()), + Some(m) if lit.len() < m => min = Some(lit.len()), + _ => {} + } + } + min + } + + /// Returns true if all members in this set are complete. + pub fn all_complete(&self) -> bool { + !self.lits.is_empty() && self.lits.iter().all(|l| !l.is_cut()) + } + + /// Returns true if any member in this set is complete. + pub fn any_complete(&self) -> bool { + self.lits.iter().any(|lit| !lit.is_cut()) + } + + /// Returns true if this set contains an empty literal. + pub fn contains_empty(&self) -> bool { + self.lits.iter().any(|lit| lit.is_empty()) + } + + /// Returns true if this set is empty or if all of its members is empty. + pub fn is_empty(&self) -> bool { + self.lits.is_empty() || self.lits.iter().all(|lit| lit.is_empty()) + } + + /// Returns a new empty set of literals using this set's limits. + pub fn to_empty(&self) -> Literals { + let mut lits = Literals::empty(); + lits.set_limit_size(self.limit_size) + .set_limit_class(self.limit_class); + lits + } + + /// Returns the longest common prefix of all members in this set. + pub fn longest_common_prefix(&self) -> &[u8] { + if self.is_empty() { + return &[]; + } + let lit0 = &*self.lits[0]; + let mut len = lit0.len(); + for lit in &self.lits[1..] { + len = cmp::min( + len, + lit.iter() + .zip(lit0) + .take_while(|&(a, b)| a == b) + .count()); + } + &self.lits[0][..len] + } + + /// Returns the longest common suffix of all members in this set. + pub fn longest_common_suffix(&self) -> &[u8] { + if self.is_empty() { + return &[]; + } + let lit0 = &*self.lits[0]; + let mut len = lit0.len(); + for lit in &self.lits[1..] { + len = cmp::min( + len, + lit.iter() + .rev() + .zip(lit0.iter().rev()) + .take_while(|&(a, b)| a == b) + .count()); + } + &self.lits[0][self.lits[0].len() - len..] + } + + /// Returns a new set of literals with the given number of bytes trimmed + /// from the suffix of each literal. + /// + /// If any literal would be cut out completely by trimming, then None is + /// returned. + /// + /// Any duplicates that are created as a result of this transformation are + /// removed. + pub fn trim_suffix(&self, num_bytes: usize) -> Option { + if self.min_len().map(|len| len <= num_bytes).unwrap_or(true) { + return None; + } + let mut new = self.to_empty(); + for mut lit in self.lits.iter().cloned() { + let new_len = lit.len() - num_bytes; + lit.truncate(new_len); + lit.cut(); + new.lits.push(lit); + } + new.lits.sort(); + new.lits.dedup(); + Some(new) + } + + /// Returns a new set of prefixes of this set of literals that are + /// guaranteed to be unambiguous. + /// + /// Any substring match with a member of the set is returned is guaranteed + /// to never overlap with a substring match of another member of the set + /// at the same starting position. + /// + /// Given any two members of the returned set, neither is a substring of + /// the other. + pub fn unambiguous_prefixes(&self) -> Literals { + if self.lits.is_empty() { + return self.to_empty(); + } + let mut old: Vec = self.lits.iter().cloned().collect(); + let mut new = self.to_empty(); + 'OUTER: + while let Some(mut candidate) = old.pop() { + if candidate.is_empty() { + continue; + } + if new.lits.is_empty() { + new.lits.push(candidate); + continue; + } + for lit2 in &mut new.lits { + if lit2.is_empty() { + continue; + } + if &candidate == lit2 { + // If the literal is already in the set, then we can + // just drop it. But make sure that cut literals are + // infectious! + candidate.cut = candidate.cut || lit2.cut; + lit2.cut = candidate.cut; + continue 'OUTER; + } + if candidate.len() < lit2.len() { + if let Some(i) = position(&candidate, &lit2) { + candidate.cut(); + let mut lit3 = lit2.clone(); + lit3.truncate(i); + lit3.cut(); + old.push(lit3); + lit2.clear(); + } + } else { + if let Some(i) = position(&lit2, &candidate) { + lit2.cut(); + let mut new_candidate = candidate.clone(); + new_candidate.truncate(i); + new_candidate.cut(); + old.push(new_candidate); + candidate.clear(); + } + } + // Oops, the candidate is already represented in the set. + if candidate.is_empty() { + continue 'OUTER; + } + } + new.lits.push(candidate); + } + new.lits.retain(|lit| !lit.is_empty()); + new.lits.sort(); + new.lits.dedup(); + new + } + + /// Returns a new set of suffixes of this set of literals that are + /// guaranteed to be unambiguous. + /// + /// Any substring match with a member of the set is returned is guaranteed + /// to never overlap with a substring match of another member of the set + /// at the same ending position. + /// + /// Given any two members of the returned set, neither is a substring of + /// the other. + pub fn unambiguous_suffixes(&self) -> Literals { + // This is a touch wasteful... + let mut lits = self.clone(); + lits.reverse(); + let mut unamb = lits.unambiguous_prefixes(); + unamb.reverse(); + unamb + } + + /// Unions the prefixes from the given expression to this set. + /// + /// If prefixes could not be added (for example, this set would exceed its + /// size limits or the set of prefixes from `expr` includes the empty + /// string), then false is returned. + /// + /// Note that prefix literals extracted from `expr` are said to be complete + /// if and only if the literal extends from the beginning of `expr` to the + /// end of `expr`. + pub fn union_prefixes(&mut self, expr: &Hir) -> bool { + let mut lits = self.to_empty(); + prefixes(expr, &mut lits); + !lits.is_empty() && !lits.contains_empty() && self.union(lits) + } + + /// Unions the suffixes from the given expression to this set. + /// + /// If suffixes could not be added (for example, this set would exceed its + /// size limits or the set of suffixes from `expr` includes the empty + /// string), then false is returned. + /// + /// Note that prefix literals extracted from `expr` are said to be complete + /// if and only if the literal extends from the end of `expr` to the + /// beginning of `expr`. + pub fn union_suffixes(&mut self, expr: &Hir) -> bool { + let mut lits = self.to_empty(); + suffixes(expr, &mut lits); + lits.reverse(); + !lits.is_empty() && !lits.contains_empty() && self.union(lits) + } + + /// Unions this set with another set. + /// + /// If the union would cause the set to exceed its limits, then the union + /// is skipped and it returns false. Otherwise, if the union succeeds, it + /// returns true. + pub fn union(&mut self, lits: Literals) -> bool { + if self.num_bytes() + lits.num_bytes() > self.limit_size { + return false; + } + if lits.is_empty() { + self.lits.push(Literal::empty()); + } else { + self.lits.extend(lits.lits); + } + true + } + + /// Extends this set with another set. + /// + /// The set of literals is extended via a cross product. + /// + /// If a cross product would cause this set to exceed its limits, then the + /// cross product is skipped and it returns false. Otherwise, if the cross + /// product succeeds, it returns true. + pub fn cross_product(&mut self, lits: &Literals) -> bool { + if lits.is_empty() { + return true; + } + // Check that we make sure we stay in our limits. + let mut size_after; + if self.is_empty() || !self.any_complete() { + size_after = self.num_bytes(); + for lits_lit in lits.literals() { + size_after += lits_lit.len(); + } + } else { + size_after = self.lits.iter().fold(0, |accum, lit| { + accum + if lit.is_cut() { lit.len() } else { 0 } + }); + for lits_lit in lits.literals() { + for self_lit in self.literals() { + if !self_lit.is_cut() { + size_after += self_lit.len() + lits_lit.len(); + } + } + } + } + if size_after > self.limit_size { + return false; + } + + let mut base = self.remove_complete(); + if base.is_empty() { + base = vec![Literal::empty()]; + } + for lits_lit in lits.literals() { + for mut self_lit in base.clone() { + self_lit.extend(&**lits_lit); + self_lit.cut = lits_lit.cut; + self.lits.push(self_lit); + } + } + true + } + + /// Extends each literal in this set with the bytes given. + /// + /// If the set is empty, then the given literal is added to the set. + /// + /// If adding any number of bytes to all members of this set causes a limit + /// to be exceeded, then no bytes are added and false is returned. If a + /// prefix of `bytes` can be fit into this set, then it is used and all + /// resulting literals are cut. + pub fn cross_add(&mut self, bytes: &[u8]) -> bool { + // N.B. This could be implemented by simply calling cross_product with + // a literal set containing just `bytes`, but we can be smarter about + // taking shorter prefixes of `bytes` if they'll fit. + if bytes.is_empty() { + return true; + } + if self.lits.is_empty() { + let i = cmp::min(self.limit_size, bytes.len()); + self.lits.push(Literal::new(bytes[..i].to_owned())); + self.lits[0].cut = i < bytes.len(); + return !self.lits[0].is_cut(); + } + let size = self.num_bytes(); + if size + self.lits.len() >= self.limit_size { + return false; + } + let mut i = 1; + while size + (i * self.lits.len()) <= self.limit_size + && i < bytes.len() { + i += 1; + } + for lit in &mut self.lits { + if !lit.is_cut() { + lit.extend(&bytes[..i]); + if i < bytes.len() { + lit.cut(); + } + } + } + true + } + + /// Adds the given literal to this set. + /// + /// Returns false if adding this literal would cause the class to be too + /// big. + pub fn add(&mut self, lit: Literal) -> bool { + if self.num_bytes() + lit.len() > self.limit_size { + return false; + } + self.lits.push(lit); + true + } + + /// Extends each literal in this set with the character class given. + /// + /// Returns false if the character class was too big to add. + pub fn add_char_class(&mut self, cls: &hir::ClassUnicode) -> bool { + self._add_char_class(cls, false) + } + + /// Extends each literal in this set with the character class given, + /// writing the bytes of each character in reverse. + /// + /// Returns false if the character class was too big to add. + fn add_char_class_reverse(&mut self, cls: &hir::ClassUnicode) -> bool { + self._add_char_class(cls, true) + } + + fn _add_char_class( + &mut self, + cls: &hir::ClassUnicode, + reverse: bool, + ) -> bool { + use std::char; + + if self.class_exceeds_limits(cls_char_count(cls)) { + return false; + } + let mut base = self.remove_complete(); + if base.is_empty() { + base = vec![Literal::empty()]; + } + for r in cls.iter() { + let (s, e) = (r.start as u32, r.end as u32 + 1); + for c in (s..e).filter_map(char::from_u32) { + for mut lit in base.clone() { + let mut bytes = c.to_string().into_bytes(); + if reverse { + bytes.reverse(); + } + lit.extend(&bytes); + self.lits.push(lit); + } + } + } + true + } + + /// Extends each literal in this set with the byte class given. + /// + /// Returns false if the byte class was too big to add. + pub fn add_byte_class(&mut self, cls: &hir::ClassBytes) -> bool { + if self.class_exceeds_limits(cls_byte_count(cls)) { + return false; + } + let mut base = self.remove_complete(); + if base.is_empty() { + base = vec![Literal::empty()]; + } + for r in cls.iter() { + let (s, e) = (r.start as u32, r.end as u32 + 1); + for b in (s..e).map(|b| b as u8) { + for mut lit in base.clone() { + lit.push(b); + self.lits.push(lit); + } + } + } + true + } + + /// Cuts every member of this set. When a member is cut, it can never + /// be extended. + pub fn cut(&mut self) { + for lit in &mut self.lits { + lit.cut(); + } + } + + /// Reverses all members in place. + pub fn reverse(&mut self) { + for lit in &mut self.lits { + lit.reverse(); + } + } + + /// Clears this set of all members. + pub fn clear(&mut self) { + self.lits.clear(); + } + + /// Pops all complete literals out of this set. + fn remove_complete(&mut self) -> Vec { + let mut base = vec![]; + for lit in mem::replace(&mut self.lits, vec![]) { + if lit.is_cut() { + self.lits.push(lit); + } else { + base.push(lit); + } + } + base + } + + /// Returns the total number of bytes in this set. + fn num_bytes(&self) -> usize { + self.lits.iter().fold(0, |accum, lit| accum + lit.len()) + } + + /// Returns true if a character class with the given size would cause this + /// set to exceed its limits. + /// + /// The size given should correspond to the number of items in the class. + fn class_exceeds_limits(&self, size: usize) -> bool { + if size > self.limit_class { + return true; + } + // This is an approximation since codepoints in a char class can encode + // to 1-4 bytes. + let new_byte_count = + if self.lits.is_empty() { + size + } else { + self.lits + .iter() + .fold(0, |accum, lit| { + accum + if lit.is_cut() { + // If the literal is cut, then we'll never add + // anything to it, so don't count it. + 0 + } else { + (lit.len() + 1) * size + } + }) + }; + new_byte_count > self.limit_size + } +} + +fn prefixes(expr: &Hir, lits: &mut Literals) { + match *expr.kind() { + HirKind::Literal(hir::Literal::Unicode(c)) => { + let mut buf = [0u8; 4]; + let i = unicode::encode_utf8(c, &mut buf).unwrap(); + lits.cross_add(&buf[..i]); + } + HirKind::Literal(hir::Literal::Byte(b)) => { + lits.cross_add(&[b]); + } + HirKind::Class(hir::Class::Unicode(ref cls)) => { + if !lits.add_char_class(cls) { + lits.cut(); + } + } + HirKind::Class(hir::Class::Bytes(ref cls)) => { + if !lits.add_byte_class(cls) { + lits.cut(); + } + } + HirKind::Group(hir::Group { ref hir, .. }) => { + prefixes(&**hir, lits); + } + HirKind::Repetition(ref x) => { + match x.kind { + hir::RepetitionKind::ZeroOrOne => { + repeat_zero_or_one_literals(&x.hir, lits, prefixes); + } + hir::RepetitionKind::ZeroOrMore => { + repeat_zero_or_more_literals(&x.hir, lits, prefixes); + } + hir::RepetitionKind::OneOrMore => { + repeat_one_or_more_literals(&x.hir, lits, prefixes); + } + hir::RepetitionKind::Range(ref rng) => { + let (min, max) = match *rng { + hir::RepetitionRange::Exactly(m) => { + (m, Some(m)) + } + hir::RepetitionRange::AtLeast(m) => { + (m, None) + } + hir::RepetitionRange::Bounded(m, n) => { + (m, Some(n)) + } + }; + repeat_range_literals( + &x.hir, min, max, x.greedy, lits, prefixes) + } + } + } + HirKind::Concat(ref es) if es.is_empty() => {} + HirKind::Concat(ref es) if es.len() == 1 => prefixes(&es[0], lits), + HirKind::Concat(ref es) => { + for e in es { + if let HirKind::Anchor(hir::Anchor::StartText) = *e.kind() { + if !lits.is_empty() { + lits.cut(); + break; + } + lits.add(Literal::empty()); + continue; + } + let mut lits2 = lits.to_empty(); + prefixes(e, &mut lits2); + if !lits.cross_product(&lits2) || !lits2.any_complete() { + // If this expression couldn't yield any literal that + // could be extended, then we need to quit. Since we're + // short-circuiting, we also need to freeze every member. + lits.cut(); + break; + } + } + } + HirKind::Alternation(ref es) => { + alternate_literals(es, lits, prefixes); + } + _ => lits.cut(), + } +} + +fn suffixes(expr: &Hir, lits: &mut Literals) { + match *expr.kind() { + HirKind::Literal(hir::Literal::Unicode(c)) => { + let mut buf = [0u8; 4]; + let i = unicode::encode_utf8(c, &mut buf).unwrap(); + let mut buf = &mut buf[..i]; + buf.reverse(); + lits.cross_add(buf); + } + HirKind::Literal(hir::Literal::Byte(b)) => { + lits.cross_add(&[b]); + } + HirKind::Class(hir::Class::Unicode(ref cls)) => { + if !lits.add_char_class_reverse(cls) { + lits.cut(); + } + } + HirKind::Class(hir::Class::Bytes(ref cls)) => { + if !lits.add_byte_class(cls) { + lits.cut(); + } + } + HirKind::Group(hir::Group { ref hir, .. }) => { + suffixes(&**hir, lits); + } + HirKind::Repetition(ref x) => { + match x.kind { + hir::RepetitionKind::ZeroOrOne => { + repeat_zero_or_one_literals(&x.hir, lits, suffixes); + } + hir::RepetitionKind::ZeroOrMore => { + repeat_zero_or_more_literals(&x.hir, lits, suffixes); + } + hir::RepetitionKind::OneOrMore => { + repeat_one_or_more_literals(&x.hir, lits, suffixes); + } + hir::RepetitionKind::Range(ref rng) => { + let (min, max) = match *rng { + hir::RepetitionRange::Exactly(m) => { + (m, Some(m)) + } + hir::RepetitionRange::AtLeast(m) => { + (m, None) + } + hir::RepetitionRange::Bounded(m, n) => { + (m, Some(n)) + } + }; + repeat_range_literals( + &x.hir, min, max, x.greedy, lits, suffixes) + } + } + } + HirKind::Concat(ref es) if es.is_empty() => {} + HirKind::Concat(ref es) if es.len() == 1 => suffixes(&es[0], lits), + HirKind::Concat(ref es) => { + for e in es.iter().rev() { + if let HirKind::Anchor(hir::Anchor::EndText) = *e.kind() { + if !lits.is_empty() { + lits.cut(); + break; + } + lits.add(Literal::empty()); + continue; + } + let mut lits2 = lits.to_empty(); + suffixes(e, &mut lits2); + if !lits.cross_product(&lits2) || !lits2.any_complete() { + // If this expression couldn't yield any literal that + // could be extended, then we need to quit. Since we're + // short-circuiting, we also need to freeze every member. + lits.cut(); + break; + } + } + } + HirKind::Alternation(ref es) => { + alternate_literals(es, lits, suffixes); + } + _ => lits.cut(), + } +} + +fn repeat_zero_or_one_literals( + e: &Hir, + lits: &mut Literals, + mut f: F, +) { + let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty()); + lits3.set_limit_size(lits.limit_size() / 2); + f(e, &mut lits3); + + if lits3.is_empty() || !lits2.cross_product(&lits3) { + lits.cut(); + return; + } + lits2.add(Literal::empty()); + if !lits.union(lits2) { + lits.cut(); + } +} + +fn repeat_zero_or_more_literals( + e: &Hir, + lits: &mut Literals, + mut f: F, +) { + let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty()); + lits3.set_limit_size(lits.limit_size() / 2); + f(e, &mut lits3); + + if lits3.is_empty() || !lits2.cross_product(&lits3) { + lits.cut(); + return; + } + lits2.cut(); + lits2.add(Literal::empty()); + if !lits.union(lits2) { + lits.cut(); + } +} + +fn repeat_one_or_more_literals( + e: &Hir, + lits: &mut Literals, + mut f: F, +) { + f(e, lits); + lits.cut(); +} + +fn repeat_range_literals( + e: &Hir, + min: u32, + max: Option, + greedy: bool, + lits: &mut Literals, + mut f: F, +) { + if min == 0 { + // This is a bit conservative. If `max` is set, then we could + // treat this as a finite set of alternations. For now, we + // just treat it as `e*`. + f(&Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: greedy, + hir: Box::new(e.clone()), + }), lits); + } else { + if min > 0 { + let n = cmp::min(lits.limit_size, min as usize); + let es = iter::repeat(e.clone()).take(n).collect(); + f(&Hir::concat(es), lits); + if n < min as usize || lits.contains_empty() { + lits.cut(); + } + } + if max.map_or(true, |max| min < max) { + lits.cut(); + } + } +} + +fn alternate_literals( + es: &[Hir], + lits: &mut Literals, + mut f: F, +) { + let mut lits2 = lits.to_empty(); + for e in es { + let mut lits3 = lits.to_empty(); + lits3.set_limit_size(lits.limit_size() / 5); + f(e, &mut lits3); + if lits3.is_empty() || !lits2.union(lits3) { + // If we couldn't find suffixes for *any* of the + // alternates, then the entire alternation has to be thrown + // away and any existing members must be frozen. Similarly, + // if the union couldn't complete, stop and freeze. + lits.cut(); + return; + } + } + if !lits.cross_product(&lits2) { + lits.cut(); + } +} + +impl fmt::Debug for Literals { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Literals") + .field("lits", &self.lits) + .field("limit_size", &self.limit_size) + .field("limit_class", &self.limit_class) + .finish() + } +} + +impl Literal { + /// Returns a new complete literal with the bytes given. + pub fn new(bytes: Vec) -> Literal { + Literal { v: bytes, cut: false } + } + + /// Returns a new complete empty literal. + pub fn empty() -> Literal { + Literal { v: vec![], cut: false } + } + + /// Returns true if this literal was "cut." + pub fn is_cut(&self) -> bool { + self.cut + } + + /// Cuts this literal. + pub fn cut(&mut self) { + self.cut = true; + } +} + +impl PartialEq for Literal { + fn eq(&self, other: &Literal) -> bool { + self.v == other.v + } +} + +impl PartialOrd for Literal { + fn partial_cmp(&self, other: &Literal) -> Option { + self.v.partial_cmp(&other.v) + } +} + +impl fmt::Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.is_cut() { + write!(f, "Cut({})", escape_unicode(&self.v)) + } else { + write!(f, "Complete({})", escape_unicode(&self.v)) + } + } +} + +impl AsRef<[u8]> for Literal { + fn as_ref(&self) -> &[u8] { &self.v } +} + +impl ops::Deref for Literal { + type Target = Vec; + fn deref(&self) -> &Vec { &self.v } +} + +impl ops::DerefMut for Literal { + fn deref_mut(&mut self) -> &mut Vec { &mut self.v } +} + +fn position(needle: &[u8], mut haystack: &[u8]) -> Option { + let mut i = 0; + while haystack.len() >= needle.len() { + if needle == &haystack[..needle.len()] { + return Some(i); + } + i += 1; + haystack = &haystack[1..]; + } + None +} + +fn escape_unicode(bytes: &[u8]) -> String { + let show = match ::std::str::from_utf8(bytes) { + Ok(v) => v.to_string(), + Err(_) => escape_bytes(bytes), + }; + let mut space_escaped = String::new(); + for c in show.chars() { + if c.is_whitespace() { + let escaped = if c as u32 <= 0x7F { + escape_byte(c as u8) + } else { + if c as u32 <= 0xFFFF { + format!(r"\u{{{:04x}}}", c as u32) + } else { + format!(r"\U{{{:08x}}}", c as u32) + } + }; + space_escaped.push_str(&escaped); + } else { + space_escaped.push(c); + } + } + space_escaped +} + +fn escape_bytes(bytes: &[u8]) -> String { + let mut s = String::new(); + for &b in bytes { + s.push_str(&escape_byte(b)); + } + s +} + +fn escape_byte(byte: u8) -> String { + use std::ascii::escape_default; + + let escaped: Vec = escape_default(byte).collect(); + String::from_utf8_lossy(&escaped).into_owned() +} + +fn cls_char_count(cls: &hir::ClassUnicode) -> usize { + cls.iter() + .map(|&r| 1 + (r.end as u32) - (r.start as u32)) + .sum::() as usize +} + +fn cls_byte_count(cls: &hir::ClassBytes) -> usize { + cls.iter() + .map(|&r| 1 + (r.end as u32) - (r.start as u32)) + .sum::() as usize +} + +#[cfg(test)] +mod tests { + use std::fmt; + + use ParserBuilder; + use hir::Hir; + use super::{Literals, Literal, escape_bytes}; + + // To make test failures easier to read. + #[derive(Debug, Eq, PartialEq)] + struct Bytes(Vec); + #[derive(Debug, Eq, PartialEq)] + struct Unicode(Vec); + + fn escape_lits(blits: &[Literal]) -> Vec { + let mut ulits = vec![]; + for blit in blits { + ulits.push(ULiteral { + v: escape_bytes(&blit), + cut: blit.is_cut(), + }); + } + ulits + } + + fn create_lits>(it: I) -> Literals { + Literals { + lits: it.into_iter().collect(), + limit_size: 0, + limit_class: 0, + } + } + + // Needs to be pub for 1.3? + #[derive(Clone, Eq, PartialEq)] + pub struct ULiteral { + v: String, + cut: bool, + } + + impl ULiteral { + fn is_cut(&self) -> bool { self.cut } + } + + impl fmt::Debug for ULiteral { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.is_cut() { + write!(f, "Cut({})", self.v) + } else { + write!(f, "Complete({})", self.v) + } + } + } + + impl PartialEq for ULiteral { + fn eq(&self, other: &Literal) -> bool { + self.v.as_bytes() == &*other.v && self.is_cut() == other.is_cut() + } + } + + impl PartialEq for Literal { + fn eq(&self, other: &ULiteral) -> bool { + &*self.v == other.v.as_bytes() && self.is_cut() == other.is_cut() + } + } + + #[allow(non_snake_case)] + fn C(s: &'static str) -> ULiteral { + ULiteral { v: s.to_owned(), cut: true } + } + #[allow(non_snake_case)] + fn M(s: &'static str) -> ULiteral { + ULiteral { v: s.to_owned(), cut: false } + } + + fn prefixes(lits: &mut Literals, expr: &Hir) { + lits.union_prefixes(expr); + } + + fn suffixes(lits: &mut Literals, expr: &Hir) { + lits.union_suffixes(expr); + } + + macro_rules! assert_lit_eq { + ($which:ident, $got_lits:expr, $($expected_lit:expr),*) => {{ + let expected: Vec = vec![$($expected_lit),*]; + let lits = $got_lits; + assert_eq!( + $which(expected.clone()), + $which(escape_lits(lits.literals()))); + assert_eq!( + !expected.is_empty() && expected.iter().all(|l| !l.is_cut()), + lits.all_complete()); + assert_eq!( + expected.iter().any(|l| !l.is_cut()), + lits.any_complete()); + }}; + } + + macro_rules! test_lit { + ($name:ident, $which:ident, $re:expr) => { + test_lit!($name, $which, $re,); + }; + ($name:ident, $which:ident, $re:expr, $($lit:expr),*) => { + #[test] + fn $name() { + let expr = ParserBuilder::new() + .build() + .parse($re) + .unwrap(); + let lits = Literals::$which(&expr); + assert_lit_eq!(Unicode, lits, $($lit),*); + + let expr = ParserBuilder::new() + .allow_invalid_utf8(true) + .unicode(false) + .build() + .parse($re) + .unwrap(); + let lits = Literals::$which(&expr); + assert_lit_eq!(Bytes, lits, $($lit),*); + } + }; + } + + // ************************************************************************ + // Tests for prefix literal extraction. + // ************************************************************************ + + // Elementary tests. + test_lit!(pfx_one_lit1, prefixes, "a", M("a")); + test_lit!(pfx_one_lit2, prefixes, "abc", M("abc")); + test_lit!(pfx_one_lit3, prefixes, "(?u)☃", M("\\xe2\\x98\\x83")); + test_lit!(pfx_one_lit4, prefixes, "(?ui)☃", M("\\xe2\\x98\\x83")); + test_lit!(pfx_class1, prefixes, "[1-4]", + M("1"), M("2"), M("3"), M("4")); + test_lit!(pfx_class2, prefixes, "(?u)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x98\\x83")); + test_lit!(pfx_class3, prefixes, "(?ui)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x85\\xb0"), + M("\\xe2\\x98\\x83")); + test_lit!(pfx_one_lit_casei1, prefixes, "(?i)a", + M("A"), M("a")); + test_lit!(pfx_one_lit_casei2, prefixes, "(?i)abc", + M("ABC"), M("aBC"), M("AbC"), M("abC"), + M("ABc"), M("aBc"), M("Abc"), M("abc")); + test_lit!(pfx_group1, prefixes, "(a)", M("a")); + test_lit!(pfx_rep_zero_or_one1, prefixes, "a?"); + test_lit!(pfx_rep_zero_or_one2, prefixes, "(?:abc)?"); + test_lit!(pfx_rep_zero_or_more1, prefixes, "a*"); + test_lit!(pfx_rep_zero_or_more2, prefixes, "(?:abc)*"); + test_lit!(pfx_rep_one_or_more1, prefixes, "a+", C("a")); + test_lit!(pfx_rep_one_or_more2, prefixes, "(?:abc)+", C("abc")); + test_lit!(pfx_rep_nested_one_or_more, prefixes, "(?:a+)+", C("a")); + test_lit!(pfx_rep_range1, prefixes, "a{0}"); + test_lit!(pfx_rep_range2, prefixes, "a{0,}"); + test_lit!(pfx_rep_range3, prefixes, "a{0,1}"); + test_lit!(pfx_rep_range4, prefixes, "a{1}", M("a")); + test_lit!(pfx_rep_range5, prefixes, "a{2}", M("aa")); + test_lit!(pfx_rep_range6, prefixes, "a{1,2}", C("a")); + test_lit!(pfx_rep_range7, prefixes, "a{2,3}", C("aa")); + + // Test regexes with concatenations. + test_lit!(pfx_cat1, prefixes, "(?:a)(?:b)", M("ab")); + test_lit!(pfx_cat2, prefixes, "[ab]z", M("az"), M("bz")); + test_lit!(pfx_cat3, prefixes, "(?i)[ab]z", + M("AZ"), M("BZ"), M("aZ"), M("bZ"), + M("Az"), M("Bz"), M("az"), M("bz")); + test_lit!(pfx_cat4, prefixes, "[ab][yz]", + M("ay"), M("by"), M("az"), M("bz")); + test_lit!(pfx_cat5, prefixes, "a*b", C("a"), M("b")); + test_lit!(pfx_cat6, prefixes, "a*b*c", C("a"), C("b"), M("c")); + test_lit!(pfx_cat7, prefixes, "a*b*c+", C("a"), C("b"), C("c")); + test_lit!(pfx_cat8, prefixes, "a*b+c", C("a"), C("b")); + test_lit!(pfx_cat9, prefixes, "a*b+c*", C("a"), C("b")); + test_lit!(pfx_cat10, prefixes, "ab*", C("ab"), M("a")); + test_lit!(pfx_cat11, prefixes, "ab*c", C("ab"), M("ac")); + test_lit!(pfx_cat12, prefixes, "ab+", C("ab")); + test_lit!(pfx_cat13, prefixes, "ab+c", C("ab")); + test_lit!(pfx_cat14, prefixes, "a^", C("a")); + test_lit!(pfx_cat15, prefixes, "$a"); + test_lit!(pfx_cat16, prefixes, r"ab*c", C("ab"), M("ac")); + test_lit!(pfx_cat17, prefixes, r"ab+c", C("ab")); + test_lit!(pfx_cat18, prefixes, r"z*azb", C("z"), M("azb")); + test_lit!(pfx_cat19, prefixes, "a.z", C("a")); + + // Test regexes with alternations. + test_lit!(pfx_alt1, prefixes, "a|b", M("a"), M("b")); + test_lit!(pfx_alt2, prefixes, "[1-3]|b", M("1"), M("2"), M("3"), M("b")); + test_lit!(pfx_alt3, prefixes, "y(?:a|b)z", M("yaz"), M("ybz")); + test_lit!(pfx_alt4, prefixes, "a|b*"); + test_lit!(pfx_alt5, prefixes, "a|b+", M("a"), C("b")); + test_lit!(pfx_alt6, prefixes, "a|(?:b|c*)"); + test_lit!(pfx_alt7, prefixes, "(a|b)*c|(a|ab)*c", + C("a"), C("b"), M("c"), C("a"), C("ab"), M("c")); + test_lit!(pfx_alt8, prefixes, "a*b|c", C("a"), M("b"), M("c")); + + // Test regexes with empty assertions. + test_lit!(pfx_empty1, prefixes, "^a", M("a")); + test_lit!(pfx_empty2, prefixes, "a${2}", C("a")); + test_lit!(pfx_empty3, prefixes, "^abc", M("abc")); + test_lit!(pfx_empty4, prefixes, "(?:^abc)|(?:^z)", M("abc"), M("z")); + + // Make sure some curious regexes have no prefixes. + test_lit!(pfx_nothing1, prefixes, "."); + test_lit!(pfx_nothing2, prefixes, "(?s)."); + test_lit!(pfx_nothing3, prefixes, "^"); + test_lit!(pfx_nothing4, prefixes, "$"); + test_lit!(pfx_nothing6, prefixes, "(?m)$"); + test_lit!(pfx_nothing7, prefixes, r"\b"); + test_lit!(pfx_nothing8, prefixes, r"\B"); + + // Test a few regexes that defeat any prefix literal detection. + test_lit!(pfx_defeated1, prefixes, ".a"); + test_lit!(pfx_defeated2, prefixes, "(?s).a"); + test_lit!(pfx_defeated3, prefixes, "a*b*c*"); + test_lit!(pfx_defeated4, prefixes, "a|."); + test_lit!(pfx_defeated5, prefixes, ".|a"); + test_lit!(pfx_defeated6, prefixes, "a|^"); + test_lit!(pfx_defeated7, prefixes, ".(?:a(?:b)(?:c))"); + test_lit!(pfx_defeated8, prefixes, "$a"); + test_lit!(pfx_defeated9, prefixes, "(?m)$a"); + test_lit!(pfx_defeated10, prefixes, r"\ba"); + test_lit!(pfx_defeated11, prefixes, r"\Ba"); + test_lit!(pfx_defeated12, prefixes, "^*a"); + test_lit!(pfx_defeated13, prefixes, "^+a"); + + test_lit!( + pfx_crazy1, + prefixes, + r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", + C("Mo\\'am"), C("Mu\\'am"), C("Moam"), C("Muam")); + + // ************************************************************************ + // Tests for quiting prefix literal search. + // ************************************************************************ + + macro_rules! test_exhausted { + ($name:ident, $which:ident, $re:expr) => { + test_exhausted!($name, $which, $re,); + }; + ($name:ident, $which:ident, $re:expr, $($lit:expr),*) => { + #[test] + fn $name() { + let expr = ParserBuilder::new() + .build() + .parse($re) + .unwrap(); + let mut lits = Literals::empty(); + lits.set_limit_size(20).set_limit_class(10); + $which(&mut lits, &expr); + assert_lit_eq!(Unicode, lits, $($lit),*); + + let expr = ParserBuilder::new() + .allow_invalid_utf8(true) + .unicode(false) + .build() + .parse($re) + .unwrap(); + let mut lits = Literals::empty(); + lits.set_limit_size(20).set_limit_class(10); + $which(&mut lits, &expr); + assert_lit_eq!(Bytes, lits, $($lit),*); + } + }; + } + + // These test use a much lower limit than the default so that we can + // write test cases of reasonable size. + test_exhausted!(pfx_exhausted1, prefixes, "[a-z]"); + test_exhausted!(pfx_exhausted2, prefixes, "[a-z]*A"); + test_exhausted!(pfx_exhausted3, prefixes, "A[a-z]Z", C("A")); + test_exhausted!(pfx_exhausted4, prefixes, "(?i)foobar", + C("FO"), C("fO"), C("Fo"), C("fo")); + test_exhausted!(pfx_exhausted5, prefixes, "(?:ab){100}", + C("abababababababababab")); + test_exhausted!(pfx_exhausted6, prefixes, "(?:(?:ab){100})*cd", + C("ababababab"), M("cd")); + test_exhausted!(pfx_exhausted7, prefixes, "z(?:(?:ab){100})*cd", + C("zababababab"), M("zcd")); + test_exhausted!(pfx_exhausted8, prefixes, "aaaaaaaaaaaaaaaaaaaaz", + C("aaaaaaaaaaaaaaaaaaaa")); + + // ************************************************************************ + // Tests for suffix literal extraction. + // ************************************************************************ + + // Elementary tests. + test_lit!(sfx_one_lit1, suffixes, "a", M("a")); + test_lit!(sfx_one_lit2, suffixes, "abc", M("abc")); + test_lit!(sfx_one_lit3, suffixes, "(?u)☃", M("\\xe2\\x98\\x83")); + test_lit!(sfx_one_lit4, suffixes, "(?ui)☃", M("\\xe2\\x98\\x83")); + test_lit!(sfx_class1, suffixes, "[1-4]", + M("1"), M("2"), M("3"), M("4")); + test_lit!(sfx_class2, suffixes, "(?u)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x98\\x83")); + test_lit!(sfx_class3, suffixes, "(?ui)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x85\\xb0"), + M("\\xe2\\x98\\x83")); + test_lit!(sfx_one_lit_casei1, suffixes, "(?i)a", + M("A"), M("a")); + test_lit!(sfx_one_lit_casei2, suffixes, "(?i)abc", + M("ABC"), M("ABc"), M("AbC"), M("Abc"), + M("aBC"), M("aBc"), M("abC"), M("abc")); + test_lit!(sfx_group1, suffixes, "(a)", M("a")); + test_lit!(sfx_rep_zero_or_one1, suffixes, "a?"); + test_lit!(sfx_rep_zero_or_one2, suffixes, "(?:abc)?"); + test_lit!(sfx_rep_zero_or_more1, suffixes, "a*"); + test_lit!(sfx_rep_zero_or_more2, suffixes, "(?:abc)*"); + test_lit!(sfx_rep_one_or_more1, suffixes, "a+", C("a")); + test_lit!(sfx_rep_one_or_more2, suffixes, "(?:abc)+", C("abc")); + test_lit!(sfx_rep_nested_one_or_more, suffixes, "(?:a+)+", C("a")); + test_lit!(sfx_rep_range1, suffixes, "a{0}"); + test_lit!(sfx_rep_range2, suffixes, "a{0,}"); + test_lit!(sfx_rep_range3, suffixes, "a{0,1}"); + test_lit!(sfx_rep_range4, suffixes, "a{1}", M("a")); + test_lit!(sfx_rep_range5, suffixes, "a{2}", M("aa")); + test_lit!(sfx_rep_range6, suffixes, "a{1,2}", C("a")); + test_lit!(sfx_rep_range7, suffixes, "a{2,3}", C("aa")); + + // Test regexes with concatenations. + test_lit!(sfx_cat1, suffixes, "(?:a)(?:b)", M("ab")); + test_lit!(sfx_cat2, suffixes, "[ab]z", M("az"), M("bz")); + test_lit!(sfx_cat3, suffixes, "(?i)[ab]z", + M("AZ"), M("Az"), M("BZ"), M("Bz"), + M("aZ"), M("az"), M("bZ"), M("bz")); + test_lit!(sfx_cat4, suffixes, "[ab][yz]", + M("ay"), M("az"), M("by"), M("bz")); + test_lit!(sfx_cat5, suffixes, "a*b", C("ab"), M("b")); + test_lit!(sfx_cat6, suffixes, "a*b*c", C("bc"), C("ac"), M("c")); + test_lit!(sfx_cat7, suffixes, "a*b*c+", C("c")); + test_lit!(sfx_cat8, suffixes, "a*b+c", C("bc")); + test_lit!(sfx_cat9, suffixes, "a*b+c*", C("c"), C("b")); + test_lit!(sfx_cat10, suffixes, "ab*", C("b"), M("a")); + test_lit!(sfx_cat11, suffixes, "ab*c", C("bc"), M("ac")); + test_lit!(sfx_cat12, suffixes, "ab+", C("b")); + test_lit!(sfx_cat13, suffixes, "ab+c", C("bc")); + test_lit!(sfx_cat14, suffixes, "a^"); + test_lit!(sfx_cat15, suffixes, "$a", C("a")); + test_lit!(sfx_cat16, suffixes, r"ab*c", C("bc"), M("ac")); + test_lit!(sfx_cat17, suffixes, r"ab+c", C("bc")); + test_lit!(sfx_cat18, suffixes, r"z*azb", C("zazb"), M("azb")); + test_lit!(sfx_cat19, suffixes, "a.z", C("z")); + + // Test regexes with alternations. + test_lit!(sfx_alt1, suffixes, "a|b", M("a"), M("b")); + test_lit!(sfx_alt2, suffixes, "[1-3]|b", M("1"), M("2"), M("3"), M("b")); + test_lit!(sfx_alt3, suffixes, "y(?:a|b)z", M("yaz"), M("ybz")); + test_lit!(sfx_alt4, suffixes, "a|b*"); + test_lit!(sfx_alt5, suffixes, "a|b+", M("a"), C("b")); + test_lit!(sfx_alt6, suffixes, "a|(?:b|c*)"); + test_lit!(sfx_alt7, suffixes, "(a|b)*c|(a|ab)*c", + C("ac"), C("bc"), M("c"), C("ac"), C("abc"), M("c")); + test_lit!(sfx_alt8, suffixes, "a*b|c", C("ab"), M("b"), M("c")); + + // Test regexes with empty assertions. + test_lit!(sfx_empty1, suffixes, "a$", M("a")); + test_lit!(sfx_empty2, suffixes, "${2}a", C("a")); + + // Make sure some curious regexes have no suffixes. + test_lit!(sfx_nothing1, suffixes, "."); + test_lit!(sfx_nothing2, suffixes, "(?s)."); + test_lit!(sfx_nothing3, suffixes, "^"); + test_lit!(sfx_nothing4, suffixes, "$"); + test_lit!(sfx_nothing6, suffixes, "(?m)$"); + test_lit!(sfx_nothing7, suffixes, r"\b"); + test_lit!(sfx_nothing8, suffixes, r"\B"); + + // Test a few regexes that defeat any suffix literal detection. + test_lit!(sfx_defeated1, suffixes, "a."); + test_lit!(sfx_defeated2, suffixes, "(?s)a."); + test_lit!(sfx_defeated3, suffixes, "a*b*c*"); + test_lit!(sfx_defeated4, suffixes, "a|."); + test_lit!(sfx_defeated5, suffixes, ".|a"); + test_lit!(sfx_defeated6, suffixes, "a|^"); + test_lit!(sfx_defeated7, suffixes, "(?:a(?:b)(?:c))."); + test_lit!(sfx_defeated8, suffixes, "a^"); + test_lit!(sfx_defeated9, suffixes, "(?m)a$"); + test_lit!(sfx_defeated10, suffixes, r"a\b"); + test_lit!(sfx_defeated11, suffixes, r"a\B"); + test_lit!(sfx_defeated12, suffixes, "a^*"); + test_lit!(sfx_defeated13, suffixes, "a^+"); + + // These test use a much lower limit than the default so that we can + // write test cases of reasonable size. + test_exhausted!(sfx_exhausted1, suffixes, "[a-z]"); + test_exhausted!(sfx_exhausted2, suffixes, "A[a-z]*"); + test_exhausted!(sfx_exhausted3, suffixes, "A[a-z]Z", C("Z")); + test_exhausted!(sfx_exhausted4, suffixes, "(?i)foobar", + C("AR"), C("Ar"), C("aR"), C("ar")); + test_exhausted!(sfx_exhausted5, suffixes, "(?:ab){100}", + C("abababababababababab")); + test_exhausted!(sfx_exhausted6, suffixes, "cd(?:(?:ab){100})*", + C("ababababab"), M("cd")); + test_exhausted!(sfx_exhausted7, suffixes, "cd(?:(?:ab){100})*z", + C("abababababz"), M("cdz")); + test_exhausted!(sfx_exhausted8, suffixes, "zaaaaaaaaaaaaaaaaaaaa", + C("aaaaaaaaaaaaaaaaaaaa")); + + // ************************************************************************ + // Tests for generating unambiguous literal sets. + // ************************************************************************ + + macro_rules! test_unamb { + ($name:ident, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec = + $given + .into_iter() + .map(|ul| { + let cut = ul.is_cut(); + Literal { v: ul.v.into_bytes(), cut: cut } + }) + .collect(); + let lits = create_lits(given); + let got = lits.unambiguous_prefixes(); + assert_eq!($expected, escape_lits(got.literals())); + } + }; + } + + test_unamb!(unambiguous1, vec![M("z"), M("azb")], vec![C("a"), C("z")]); + test_unamb!(unambiguous2, + vec![M("zaaaaaa"), M("aa")], vec![C("aa"), C("z")]); + test_unamb!(unambiguous3, + vec![M("Sherlock"), M("Watson")], + vec![M("Sherlock"), M("Watson")]); + test_unamb!(unambiguous4, vec![M("abc"), M("bc")], vec![C("a"), C("bc")]); + test_unamb!(unambiguous5, vec![M("bc"), M("abc")], vec![C("a"), C("bc")]); + test_unamb!(unambiguous6, vec![M("a"), M("aa")], vec![C("a")]); + test_unamb!(unambiguous7, vec![M("aa"), M("a")], vec![C("a")]); + test_unamb!(unambiguous8, vec![M("ab"), M("a")], vec![C("a")]); + test_unamb!(unambiguous9, + vec![M("ac"), M("bc"), M("c"), M("ac"), M("abc"), M("c")], + vec![C("a"), C("b"), C("c")]); + test_unamb!(unambiguous10, + vec![M("Mo'"), M("Mu'"), M("Mo"), M("Mu")], + vec![C("Mo"), C("Mu")]); + test_unamb!(unambiguous11, + vec![M("zazb"), M("azb")], vec![C("a"), C("z")]); + test_unamb!(unambiguous12, vec![M("foo"), C("foo")], vec![C("foo")]); + test_unamb!(unambiguous13, + vec![M("ABCX"), M("CDAX"), M("BCX")], + vec![C("A"), C("BCX"), C("CD")]); + test_unamb!(unambiguous14, + vec![M("IMGX"), M("MVIX"), M("MGX"), M("DSX")], + vec![M("DSX"), C("I"), C("MGX"), C("MV")]); + test_unamb!(unambiguous15, + vec![M("IMG_"), M("MG_"), M("CIMG")], + vec![C("C"), C("I"), C("MG_")]); + + + // ************************************************************************ + // Tests for suffix trimming. + // ************************************************************************ + macro_rules! test_trim { + ($name:ident, $trim:expr, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec = + $given + .into_iter() + .map(|ul| { + let cut = ul.is_cut(); + Literal { v: ul.v.into_bytes(), cut: cut } + }) + .collect(); + let lits = create_lits(given); + let got = lits.trim_suffix($trim).unwrap(); + assert_eq!($expected, escape_lits(got.literals())); + } + } + } + + test_trim!(trim1, 1, vec![M("ab"), M("yz")], vec![C("a"), C("y")]); + test_trim!(trim2, 1, vec![M("abc"), M("abd")], vec![C("ab")]); + test_trim!(trim3, 2, vec![M("abc"), M("abd")], vec![C("a")]); + test_trim!(trim4, 2, vec![M("abc"), M("ghij")], vec![C("a"), C("gh")]); + + // ************************************************************************ + // Tests for longest common prefix. + // ************************************************************************ + + macro_rules! test_lcp { + ($name:ident, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec = + $given + .into_iter() + .map(|s: &str| Literal { + v: s.to_owned().into_bytes(), + cut: false, + }) + .collect(); + let lits = create_lits(given); + let got = lits.longest_common_prefix(); + assert_eq!($expected, escape_bytes(got)); + } + }; + } + + test_lcp!(lcp1, vec!["a"], "a"); + test_lcp!(lcp2, vec![], ""); + test_lcp!(lcp3, vec!["a", "b"], ""); + test_lcp!(lcp4, vec!["ab", "ab"], "ab"); + test_lcp!(lcp5, vec!["ab", "a"], "a"); + test_lcp!(lcp6, vec!["a", "ab"], "a"); + test_lcp!(lcp7, vec!["ab", "b"], ""); + test_lcp!(lcp8, vec!["b", "ab"], ""); + test_lcp!(lcp9, vec!["foobar", "foobaz"], "fooba"); + test_lcp!(lcp10, vec!["foobar", "foobaz", "a"], ""); + test_lcp!(lcp11, vec!["a", "foobar", "foobaz"], ""); + test_lcp!(lcp12, vec!["foo", "flub", "flab", "floo"], "f"); + + // ************************************************************************ + // Tests for longest common suffix. + // ************************************************************************ + + macro_rules! test_lcs { + ($name:ident, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec = + $given + .into_iter() + .map(|s: &str| Literal { + v: s.to_owned().into_bytes(), + cut: false, + }) + .collect(); + let lits = create_lits(given); + let got = lits.longest_common_suffix(); + assert_eq!($expected, escape_bytes(got)); + } + }; + } + + test_lcs!(lcs1, vec!["a"], "a"); + test_lcs!(lcs2, vec![], ""); + test_lcs!(lcs3, vec!["a", "b"], ""); + test_lcs!(lcs4, vec!["ab", "ab"], "ab"); + test_lcs!(lcs5, vec!["ab", "a"], ""); + test_lcs!(lcs6, vec!["a", "ab"], ""); + test_lcs!(lcs7, vec!["ab", "b"], "b"); + test_lcs!(lcs8, vec!["b", "ab"], "b"); + test_lcs!(lcs9, vec!["barfoo", "bazfoo"], "foo"); + test_lcs!(lcs10, vec!["barfoo", "bazfoo", "a"], ""); + test_lcs!(lcs11, vec!["a", "barfoo", "bazfoo"], ""); + test_lcs!(lcs12, vec!["flub", "bub", "boob", "dub"], "b"); +} diff --git a/bash-5.1/vendor/regex-syntax/src/hir/mod.rs b/bash-5.1/vendor/regex-syntax/src/hir/mod.rs new file mode 100644 index 0000000..903e608 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/hir/mod.rs @@ -0,0 +1,2055 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Defines a high-level intermediate representation for regular expressions. +*/ +use std::char; +use std::cmp; +use std::error; +use std::fmt; +use std::u8; + +use ast::Span; +use hir::interval::{Interval, IntervalSet, IntervalSetIter}; +use unicode; + +pub use hir::visitor::{Visitor, visit}; + +mod interval; +pub mod literal; +pub mod print; +pub mod translate; +mod visitor; + +/// An error that can occur while translating an `Ast` to a `Hir`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Error { + /// The kind of error. + kind: ErrorKind, + /// The original pattern that the translator's Ast was parsed from. Every + /// span in an error is a valid range into this string. + pattern: String, + /// The span of this error, derived from the Ast given to the translator. + span: Span, +} + +impl Error { + /// Return the type of this error. + pub fn kind(&self) -> &ErrorKind { + &self.kind + } + + /// The original pattern string in which this error occurred. + /// + /// Every span reported by this error is reported in terms of this string. + pub fn pattern(&self) -> &str { + &self.pattern + } + + /// Return the span at which this error occurred. + pub fn span(&self) -> &Span { + &self.span + } +} + +/// The type of an error that occurred while building an `Hir`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ErrorKind { + /// This error occurs when a Unicode feature is used when Unicode + /// support is disabled. For example `(?-u:\pL)` would trigger this error. + UnicodeNotAllowed, + /// This error occurs when translating a pattern that could match a byte + /// sequence that isn't UTF-8 and `allow_invalid_utf8` was disabled. + InvalidUtf8, + /// This occurs when an unrecognized Unicode property name could not + /// be found. + UnicodePropertyNotFound, + /// This occurs when an unrecognized Unicode property value could not + /// be found. + UnicodePropertyValueNotFound, + /// This occurs when the translator attempts to construct a character class + /// that is empty. + /// + /// Note that this restriction in the translator may be removed in the + /// future. + EmptyClassNotAllowed, + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl ErrorKind { + fn description(&self) -> &str { + use self::ErrorKind::*; + match *self { + UnicodeNotAllowed => "Unicode not allowed here", + InvalidUtf8 => "pattern can match invalid UTF-8", + UnicodePropertyNotFound => "Unicode property not found", + UnicodePropertyValueNotFound => "Unicode property value not found", + EmptyClassNotAllowed => "empty character classes are not allowed", + _ => unreachable!(), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + self.kind.description() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::error::Formatter::from(self).fmt(f) + } +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(self.description()) + } +} + +/// A high-level intermediate representation (HIR) for a regular expression. +/// +/// The HIR of a regular expression represents an intermediate step between its +/// abstract syntax (a structured description of the concrete syntax) and +/// compiled byte codes. The purpose of HIR is to make regular expressions +/// easier to analyze. In particular, the AST is much more complex than the +/// HIR. For example, while an AST supports arbitrarily nested character +/// classes, the HIR will flatten all nested classes into a single set. The HIR +/// will also "compile away" every flag present in the concrete syntax. For +/// example, users of HIR expressions never need to worry about case folding; +/// it is handled automatically by the translator (e.g., by translating `(?i)A` +/// to `[aA]`). +/// +/// If the HIR was produced by a translator that disallows invalid UTF-8, then +/// the HIR is guaranteed to match UTF-8 exclusively. +/// +/// This type defines its own destructor that uses constant stack space and +/// heap space proportional to the size of the HIR. +/// +/// The specific type of an HIR expression can be accessed via its `kind` +/// or `into_kind` methods. This extra level of indirection exists for two +/// reasons: +/// +/// 1. Construction of an HIR expression *must* use the constructor methods +/// on this `Hir` type instead of building the `HirKind` values directly. +/// This permits construction to enforce invariants like "concatenations +/// always consist of two or more sub-expressions." +/// 2. Every HIR expression contains attributes that are defined inductively, +/// and can be computed cheaply during the construction process. For +/// example, one such attribute is whether the expression must match at the +/// beginning of the text. +/// +/// Also, an `Hir`'s `fmt::Display` implementation prints an HIR as a regular +/// expression pattern string, and uses constant stack space and heap space +/// proportional to the size of the `Hir`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Hir { + /// The underlying HIR kind. + kind: HirKind, + /// Analysis info about this HIR, computed during construction. + info: HirInfo, +} + +/// The kind of an arbitrary `Hir` expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum HirKind { + /// The empty regular expression, which matches everything, including the + /// empty string. + Empty, + /// A single literal character that matches exactly this character. + Literal(Literal), + /// A single character class that matches any of the characters in the + /// class. A class can either consist of Unicode scalar values as + /// characters, or it can use bytes. + Class(Class), + /// An anchor assertion. An anchor assertion match always has zero length. + Anchor(Anchor), + /// A word boundary assertion, which may or may not be Unicode aware. A + /// word boundary assertion match always has zero length. + WordBoundary(WordBoundary), + /// A repetition operation applied to a child expression. + Repetition(Repetition), + /// A possibly capturing group, which contains a child expression. + Group(Group), + /// A concatenation of expressions. A concatenation always has at least two + /// child expressions. + /// + /// A concatenation matches only if each of its child expression matches + /// one after the other. + Concat(Vec), + /// An alternation of expressions. An alternation always has at least two + /// child expressions. + /// + /// An alternation matches only if at least one of its child expression + /// matches. If multiple expressions match, then the leftmost is preferred. + Alternation(Vec), +} + +impl Hir { + /// Returns a reference to the underlying HIR kind. + pub fn kind(&self) -> &HirKind { + &self.kind + } + + /// Consumes ownership of this HIR expression and returns its underlying + /// `HirKind`. + pub fn into_kind(mut self) -> HirKind { + use std::mem; + mem::replace(&mut self.kind, HirKind::Empty) + } + + /// Returns an empty HIR expression. + /// + /// An empty HIR expression always matches, including the empty string. + pub fn empty() -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(true); + Hir { + kind: HirKind::Empty, + info: info, + } + } + + /// Creates a literal HIR expression. + /// + /// If the given literal has a `Byte` variant with an ASCII byte, then this + /// method panics. This enforces the invariant that `Byte` variants are + /// only used to express matching of invalid UTF-8. + pub fn literal(lit: Literal) -> Hir { + if let Literal::Byte(b) = lit { + assert!(b > 0x7F); + } + + let mut info = HirInfo::new(); + info.set_always_utf8(lit.is_unicode()); + info.set_all_assertions(false); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(false); + Hir { + kind: HirKind::Literal(lit), + info: info, + } + } + + /// Creates a class HIR expression. + pub fn class(class: Class) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(class.is_always_utf8()); + info.set_all_assertions(false); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(false); + Hir { + kind: HirKind::Class(class), + info: info, + } + } + + /// Creates an anchor assertion HIR expression. + pub fn anchor(anchor: Anchor) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(true); + if let Anchor::StartText = anchor { + info.set_anchored_start(true); + info.set_any_anchored_start(true); + } + if let Anchor::EndText = anchor { + info.set_anchored_end(true); + info.set_any_anchored_end(true); + } + Hir { + kind: HirKind::Anchor(anchor), + info: info, + } + } + + /// Creates a word boundary assertion HIR expression. + pub fn word_boundary(word_boundary: WordBoundary) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + // A negated word boundary matches the empty string, but a normal + // word boundary does not! + info.set_match_empty(word_boundary.is_negated()); + // Negated ASCII word boundaries can match invalid UTF-8. + if let WordBoundary::AsciiNegate = word_boundary { + info.set_always_utf8(false); + } + Hir { + kind: HirKind::WordBoundary(word_boundary), + info: info, + } + } + + /// Creates a repetition HIR expression. + pub fn repetition(rep: Repetition) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(rep.hir.is_always_utf8()); + info.set_all_assertions(rep.hir.is_all_assertions()); + // If this operator can match the empty string, then it can never + // be anchored. + info.set_anchored_start( + !rep.is_match_empty() && rep.hir.is_anchored_start() + ); + info.set_anchored_end( + !rep.is_match_empty() && rep.hir.is_anchored_end() + ); + info.set_any_anchored_start(rep.hir.is_any_anchored_start()); + info.set_any_anchored_end(rep.hir.is_any_anchored_end()); + info.set_match_empty(rep.is_match_empty() || rep.hir.is_match_empty()); + Hir { + kind: HirKind::Repetition(rep), + info: info, + } + } + + /// Creates a group HIR expression. + pub fn group(group: Group) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(group.hir.is_always_utf8()); + info.set_all_assertions(group.hir.is_all_assertions()); + info.set_anchored_start(group.hir.is_anchored_start()); + info.set_anchored_end(group.hir.is_anchored_end()); + info.set_any_anchored_start(group.hir.is_any_anchored_start()); + info.set_any_anchored_end(group.hir.is_any_anchored_end()); + info.set_match_empty(group.hir.is_match_empty()); + Hir { + kind: HirKind::Group(group), + info: info, + } + } + + /// Returns the concatenation of the given expressions. + /// + /// This flattens the concatenation as appropriate. + pub fn concat(mut exprs: Vec) -> Hir { + match exprs.len() { + 0 => Hir::empty(), + 1 => exprs.pop().unwrap(), + _ => { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(true); + + // Some attributes require analyzing all sub-expressions. + for e in &exprs { + let x = info.is_always_utf8() && e.is_always_utf8(); + info.set_always_utf8(x); + + let x = info.is_all_assertions() && e.is_all_assertions(); + info.set_all_assertions(x); + + let x = + info.is_any_anchored_start() + || e.is_any_anchored_start(); + info.set_any_anchored_start(x); + + let x = + info.is_any_anchored_end() + || e.is_any_anchored_end(); + info.set_any_anchored_end(x); + + let x = info.is_match_empty() && e.is_match_empty(); + info.set_match_empty(x); + } + // Anchored attributes require something slightly more + // sophisticated. Normally, WLOG, to determine whether an + // expression is anchored to the start, we'd only need to check + // the first expression of a concatenation. However, + // expressions like `$\b^` are still anchored to the start, + // but the first expression in the concatenation *isn't* + // anchored to the start. So the "first" expression to look at + // is actually one that is either not an assertion or is + // specifically the StartText assertion. + info.set_anchored_start( + exprs.iter() + .take_while(|e| { + e.is_anchored_start() || e.is_all_assertions() + }) + .any(|e| { + e.is_anchored_start() + })); + // Similarly for the end anchor, but in reverse. + info.set_anchored_end( + exprs.iter() + .rev() + .take_while(|e| { + e.is_anchored_end() || e.is_all_assertions() + }) + .any(|e| { + e.is_anchored_end() + })); + Hir { + kind: HirKind::Concat(exprs), + info: info, + } + } + } + } + + /// Returns the alternation of the given expressions. + /// + /// This flattens the alternation as appropriate. + pub fn alternation(mut exprs: Vec) -> Hir { + match exprs.len() { + 0 => Hir::empty(), + 1 => exprs.pop().unwrap(), + _ => { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(true); + info.set_anchored_end(true); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(false); + + // Some attributes require analyzing all sub-expressions. + for e in &exprs { + let x = info.is_always_utf8() && e.is_always_utf8(); + info.set_always_utf8(x); + + let x = info.is_all_assertions() && e.is_all_assertions(); + info.set_all_assertions(x); + + let x = info.is_anchored_start() && e.is_anchored_start(); + info.set_anchored_start(x); + + let x = info.is_anchored_end() && e.is_anchored_end(); + info.set_anchored_end(x); + + let x = + info.is_any_anchored_start() + || e.is_any_anchored_start(); + info.set_any_anchored_start(x); + + let x = + info.is_any_anchored_end() + || e.is_any_anchored_end(); + info.set_any_anchored_end(x); + + let x = info.is_match_empty() || e.is_match_empty(); + info.set_match_empty(x); + } + Hir { + kind: HirKind::Alternation(exprs), + info: info, + } + } + } + } + + /// Build an HIR expression for `.`. + /// + /// A `.` expression matches any character except for `\n`. To build an + /// expression that matches any character, including `\n`, use the `any` + /// method. + /// + /// If `bytes` is `true`, then this assumes characters are limited to a + /// single byte. + pub fn dot(bytes: bool) -> Hir { + if bytes { + let mut cls = ClassBytes::empty(); + cls.push(ClassBytesRange::new(b'\0', b'\x09')); + cls.push(ClassBytesRange::new(b'\x0B', b'\xFF')); + Hir::class(Class::Bytes(cls)) + } else { + let mut cls = ClassUnicode::empty(); + cls.push(ClassUnicodeRange::new('\0', '\x09')); + cls.push(ClassUnicodeRange::new('\x0B', '\u{10FFFF}')); + Hir::class(Class::Unicode(cls)) + } + } + + /// Build an HIR expression for `(?s).`. + /// + /// A `(?s).` expression matches any character, including `\n`. To build an + /// expression that matches any character except for `\n`, then use the + /// `dot` method. + /// + /// If `bytes` is `true`, then this assumes characters are limited to a + /// single byte. + pub fn any(bytes: bool) -> Hir { + if bytes { + let mut cls = ClassBytes::empty(); + cls.push(ClassBytesRange::new(b'\0', b'\xFF')); + Hir::class(Class::Bytes(cls)) + } else { + let mut cls = ClassUnicode::empty(); + cls.push(ClassUnicodeRange::new('\0', '\u{10FFFF}')); + Hir::class(Class::Unicode(cls)) + } + } + + /// Return true if and only if this HIR will always match valid UTF-8. + /// + /// When this returns false, then it is possible for this HIR expression + /// to match invalid UTF-8. + pub fn is_always_utf8(&self) -> bool { + self.info.is_always_utf8() + } + + /// Returns true if and only if this entire HIR expression is made up of + /// zero-width assertions. + /// + /// This includes expressions like `^$\b\A\z` and even `((\b)+())*^`, but + /// not `^a`. + pub fn is_all_assertions(&self) -> bool { + self.info.is_all_assertions() + } + + /// Return true if and only if this HIR is required to match from the + /// beginning of text. This includes expressions like `^foo`, `^(foo|bar)`, + /// `^foo|^bar` but not `^foo|bar`. + pub fn is_anchored_start(&self) -> bool { + self.info.is_anchored_start() + } + + /// Return true if and only if this HIR is required to match at the end + /// of text. This includes expressions like `foo$`, `(foo|bar)$`, + /// `foo$|bar$` but not `foo$|bar`. + pub fn is_anchored_end(&self) -> bool { + self.info.is_anchored_end() + } + + /// Return true if and only if this HIR contains any sub-expression that + /// is required to match at the beginning of text. Specifically, this + /// returns true if the `^` symbol (when multiline mode is disabled) or the + /// `\A` escape appear anywhere in the regex. + pub fn is_any_anchored_start(&self) -> bool { + self.info.is_any_anchored_start() + } + + /// Return true if and only if this HIR contains any sub-expression that is + /// required to match at the end of text. Specifically, this returns true + /// if the `$` symbol (when multiline mode is disabled) or the `\z` escape + /// appear anywhere in the regex. + pub fn is_any_anchored_end(&self) -> bool { + self.info.is_any_anchored_end() + } + + /// Return true if and only if the empty string is part of the language + /// matched by this regular expression. + /// + /// This includes `a*`, `a?b*`, `a{0}`, `()`, `()+`, `^$`, `a|b?`, `\B`, + /// but not `a`, `a+` or `\b`. + pub fn is_match_empty(&self) -> bool { + self.info.is_match_empty() + } +} + +impl HirKind { + /// Return true if and only if this HIR is the empty regular expression. + /// + /// Note that this is not defined inductively. That is, it only tests if + /// this kind is the `Empty` variant. To get the inductive definition, + /// use the `is_match_empty` method on [`Hir`](struct.Hir.html). + pub fn is_empty(&self) -> bool { + match *self { + HirKind::Empty => true, + _ => false, + } + } + + /// Returns true if and only if this kind has any (including possibly + /// empty) subexpressions. + pub fn has_subexprs(&self) -> bool { + match *self { + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) => false, + HirKind::Group(_) + | HirKind::Repetition(_) + | HirKind::Concat(_) + | HirKind::Alternation(_) => true, + } + } +} + +/// Print a display representation of this Hir. +/// +/// The result of this is a valid regular expression pattern string. +/// +/// This implementation uses constant stack space and heap space proportional +/// to the size of the `Hir`. +impl fmt::Display for Hir { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use hir::print::Printer; + Printer::new().print(self, f) + } +} + +/// The high-level intermediate representation of a literal. +/// +/// A literal corresponds to a single character, where a character is either +/// defined by a Unicode scalar value or an arbitrary byte. Unicode characters +/// are preferred whenever possible. In particular, a `Byte` variant is only +/// ever produced when it could match invalid UTF-8. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Literal { + /// A single character represented by a Unicode scalar value. + Unicode(char), + /// A single character represented by an arbitrary byte. + Byte(u8), +} + +impl Literal { + /// Returns true if and only if this literal corresponds to a Unicode + /// scalar value. + pub fn is_unicode(&self) -> bool { + match *self { + Literal::Unicode(_) => true, + Literal::Byte(b) if b <= 0x7F => true, + Literal::Byte(_) => false, + } + } +} + +/// The high-level intermediate representation of a character class. +/// +/// A character class corresponds to a set of characters. A character is either +/// defined by a Unicode scalar value or a byte. Unicode characters are used +/// by default, while bytes are used when Unicode mode (via the `u` flag) is +/// disabled. +/// +/// A character class, regardless of its character type, is represented by a +/// sequence of non-overlapping non-adjacent ranges of characters. +/// +/// Note that unlike [`Literal`](enum.Literal.html), a `Bytes` variant may +/// be produced even when it exclusively matches valid UTF-8. This is because +/// a `Bytes` variant represents an intention by the author of the regular +/// expression to disable Unicode mode, which in turn impacts the semantics of +/// case insensitive matching. For example, `(?i)k` and `(?i-u)k` will not +/// match the same set of strings. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Class { + /// A set of characters represented by Unicode scalar values. + Unicode(ClassUnicode), + /// A set of characters represented by arbitrary bytes (one byte per + /// character). + Bytes(ClassBytes), +} + +impl Class { + /// Apply Unicode simple case folding to this character class, in place. + /// The character class will be expanded to include all simple case folded + /// character variants. + /// + /// If this is a byte oriented character class, then this will be limited + /// to the ASCII ranges `A-Z` and `a-z`. + pub fn case_fold_simple(&mut self) { + match *self { + Class::Unicode(ref mut x) => x.case_fold_simple(), + Class::Bytes(ref mut x) => x.case_fold_simple(), + } + } + + /// Negate this character class in place. + /// + /// After completion, this character class will contain precisely the + /// characters that weren't previously in the class. + pub fn negate(&mut self) { + match *self { + Class::Unicode(ref mut x) => x.negate(), + Class::Bytes(ref mut x) => x.negate(), + } + } + + /// Returns true if and only if this character class will only ever match + /// valid UTF-8. + /// + /// A character class can match invalid UTF-8 only when the following + /// conditions are met: + /// + /// 1. The translator was configured to permit generating an expression + /// that can match invalid UTF-8. (By default, this is disabled.) + /// 2. Unicode mode (via the `u` flag) was disabled either in the concrete + /// syntax or in the parser builder. By default, Unicode mode is + /// enabled. + pub fn is_always_utf8(&self) -> bool { + match *self { + Class::Unicode(_) => true, + Class::Bytes(ref x) => x.is_all_ascii(), + } + } +} + +/// A set of characters represented by Unicode scalar values. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassUnicode { + set: IntervalSet, +} + +impl ClassUnicode { + /// Create a new class from a sequence of ranges. + /// + /// The given ranges do not need to be in any specific order, and ranges + /// may overlap. + pub fn new(ranges: I) -> ClassUnicode + where I: IntoIterator + { + ClassUnicode { set: IntervalSet::new(ranges) } + } + + /// Create a new class with no ranges. + pub fn empty() -> ClassUnicode { + ClassUnicode::new(vec![]) + } + + /// Add a new range to this set. + pub fn push(&mut self, range: ClassUnicodeRange) { + self.set.push(range); + } + + /// Return an iterator over all ranges in this class. + /// + /// The iterator yields ranges in ascending order. + pub fn iter(&self) -> ClassUnicodeIter { + ClassUnicodeIter(self.set.iter()) + } + + /// Return the underlying ranges as a slice. + pub fn ranges(&self) -> &[ClassUnicodeRange] { + self.set.intervals() + } + + /// Expand this character class such that it contains all case folded + /// characters, according to Unicode's "simple" mapping. For example, if + /// this class consists of the range `a-z`, then applying case folding will + /// result in the class containing both the ranges `a-z` and `A-Z`. + pub fn case_fold_simple(&mut self) { + self.set.case_fold_simple(); + } + + /// Negate this character class. + /// + /// For all `c` where `c` is a Unicode scalar value, if `c` was in this + /// set, then it will not be in this set after negation. + pub fn negate(&mut self) { + self.set.negate(); + } + + /// Union this character class with the given character class, in place. + pub fn union(&mut self, other: &ClassUnicode) { + self.set.union(&other.set); + } + + /// Intersect this character class with the given character class, in + /// place. + pub fn intersect(&mut self, other: &ClassUnicode) { + self.set.intersect(&other.set); + } + + /// Subtract the given character class from this character class, in place. + pub fn difference(&mut self, other: &ClassUnicode) { + self.set.difference(&other.set); + } + + /// Compute the symmetric difference of the given character classes, in + /// place. + /// + /// This computes the symmetric difference of two character classes. This + /// removes all elements in this class that are also in the given class, + /// but all adds all elements from the given class that aren't in this + /// class. That is, the class will contain all elements in either class, + /// but will not contain any elements that are in both classes. + pub fn symmetric_difference(&mut self, other: &ClassUnicode) { + self.set.symmetric_difference(&other.set); + } +} + +/// An iterator over all ranges in a Unicode character class. +/// +/// The lifetime `'a` refers to the lifetime of the underlying class. +#[derive(Debug)] +pub struct ClassUnicodeIter<'a>(IntervalSetIter<'a, ClassUnicodeRange>); + +impl<'a> Iterator for ClassUnicodeIter<'a> { + type Item = &'a ClassUnicodeRange; + + fn next(&mut self) -> Option<&'a ClassUnicodeRange> { + self.0.next() + } +} + +/// A single range of characters represented by Unicode scalar values. +/// +/// The range is closed. That is, the start and end of the range are included +/// in the range. +#[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)] +pub struct ClassUnicodeRange { + start: char, + end: char, +} + +impl fmt::Debug for ClassUnicodeRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let start = + if !self.start.is_whitespace() && !self.start.is_control() { + self.start.to_string() + } else { + format!("0x{:X}", self.start as u32) + }; + let end = + if !self.end.is_whitespace() && !self.end.is_control() { + self.end.to_string() + } else { + format!("0x{:X}", self.end as u32) + }; + f.debug_struct("ClassUnicodeRange") + .field("start", &start) + .field("end", &end) + .finish() + } +} + +impl Interval for ClassUnicodeRange { + type Bound = char; + + #[inline] fn lower(&self) -> char { self.start } + #[inline] fn upper(&self) -> char { self.end } + #[inline] fn set_lower(&mut self, bound: char) { self.start = bound; } + #[inline] fn set_upper(&mut self, bound: char) { self.end = bound; } + + /// Apply simple case folding to this Unicode scalar value range. + /// + /// Additional ranges are appended to the given vector. Canonical ordering + /// is *not* maintained in the given vector. + fn case_fold_simple(&self, ranges: &mut Vec) { + if !unicode::contains_simple_case_mapping(self.start, self.end) { + return; + } + let start = self.start as u32; + let end = (self.end as u32).saturating_add(1); + let mut next_simple_cp = None; + for cp in (start..end).filter_map(char::from_u32) { + if next_simple_cp.map_or(false, |next| cp < next) { + continue; + } + let it = match unicode::simple_fold(cp) { + Ok(it) => it, + Err(next) => { + next_simple_cp = next; + continue; + } + }; + for cp_folded in it { + ranges.push(ClassUnicodeRange::new(cp_folded, cp_folded)); + } + } + } +} + +impl ClassUnicodeRange { + /// Create a new Unicode scalar value range for a character class. + /// + /// The returned range is always in a canonical form. That is, the range + /// returned always satisfies the invariant that `start <= end`. + pub fn new(start: char, end: char) -> ClassUnicodeRange { + ClassUnicodeRange::create(start, end) + } + + /// Return the start of this range. + /// + /// The start of a range is always less than or equal to the end of the + /// range. + pub fn start(&self) -> char { + self.start + } + + /// Return the end of this range. + /// + /// The end of a range is always greater than or equal to the start of the + /// range. + pub fn end(&self) -> char { + self.end + } +} + +/// A set of characters represented by arbitrary bytes (where one byte +/// corresponds to one character). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassBytes { + set: IntervalSet, +} + +impl ClassBytes { + /// Create a new class from a sequence of ranges. + /// + /// The given ranges do not need to be in any specific order, and ranges + /// may overlap. + pub fn new(ranges: I) -> ClassBytes + where I: IntoIterator + { + ClassBytes { set: IntervalSet::new(ranges) } + } + + /// Create a new class with no ranges. + pub fn empty() -> ClassBytes { + ClassBytes::new(vec![]) + } + + /// Add a new range to this set. + pub fn push(&mut self, range: ClassBytesRange) { + self.set.push(range); + } + + /// Return an iterator over all ranges in this class. + /// + /// The iterator yields ranges in ascending order. + pub fn iter(&self) -> ClassBytesIter { + ClassBytesIter(self.set.iter()) + } + + /// Return the underlying ranges as a slice. + pub fn ranges(&self) -> &[ClassBytesRange] { + self.set.intervals() + } + + /// Expand this character class such that it contains all case folded + /// characters. For example, if this class consists of the range `a-z`, + /// then applying case folding will result in the class containing both the + /// ranges `a-z` and `A-Z`. + /// + /// Note that this only applies ASCII case folding, which is limited to the + /// characters `a-z` and `A-Z`. + pub fn case_fold_simple(&mut self) { + self.set.case_fold_simple(); + } + + /// Negate this byte class. + /// + /// For all `b` where `b` is a any byte, if `b` was in this set, then it + /// will not be in this set after negation. + pub fn negate(&mut self) { + self.set.negate(); + } + + /// Union this byte class with the given byte class, in place. + pub fn union(&mut self, other: &ClassBytes) { + self.set.union(&other.set); + } + + /// Intersect this byte class with the given byte class, in place. + pub fn intersect(&mut self, other: &ClassBytes) { + self.set.intersect(&other.set); + } + + /// Subtract the given byte class from this byte class, in place. + pub fn difference(&mut self, other: &ClassBytes) { + self.set.difference(&other.set); + } + + /// Compute the symmetric difference of the given byte classes, in place. + /// + /// This computes the symmetric difference of two byte classes. This + /// removes all elements in this class that are also in the given class, + /// but all adds all elements from the given class that aren't in this + /// class. That is, the class will contain all elements in either class, + /// but will not contain any elements that are in both classes. + pub fn symmetric_difference(&mut self, other: &ClassBytes) { + self.set.symmetric_difference(&other.set); + } + + /// Returns true if and only if this character class will either match + /// nothing or only ASCII bytes. Stated differently, this returns false + /// if and only if this class contains a non-ASCII byte. + pub fn is_all_ascii(&self) -> bool { + self.set.intervals().last().map_or(true, |r| r.end <= 0x7F) + } +} + +/// An iterator over all ranges in a byte character class. +/// +/// The lifetime `'a` refers to the lifetime of the underlying class. +#[derive(Debug)] +pub struct ClassBytesIter<'a>(IntervalSetIter<'a, ClassBytesRange>); + +impl<'a> Iterator for ClassBytesIter<'a> { + type Item = &'a ClassBytesRange; + + fn next(&mut self) -> Option<&'a ClassBytesRange> { + self.0.next() + } +} + +/// A single range of characters represented by arbitrary bytes. +/// +/// The range is closed. That is, the start and end of the range are included +/// in the range. +#[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)] +pub struct ClassBytesRange { + start: u8, + end: u8, +} + +impl Interval for ClassBytesRange { + type Bound = u8; + + #[inline] fn lower(&self) -> u8 { self.start } + #[inline] fn upper(&self) -> u8 { self.end } + #[inline] fn set_lower(&mut self, bound: u8) { self.start = bound; } + #[inline] fn set_upper(&mut self, bound: u8) { self.end = bound; } + + /// Apply simple case folding to this byte range. Only ASCII case mappings + /// (for a-z) are applied. + /// + /// Additional ranges are appended to the given vector. Canonical ordering + /// is *not* maintained in the given vector. + fn case_fold_simple(&self, ranges: &mut Vec) { + if !ClassBytesRange::new(b'a', b'z').is_intersection_empty(self) { + let lower = cmp::max(self.start, b'a'); + let upper = cmp::min(self.end, b'z'); + ranges.push(ClassBytesRange::new(lower - 32, upper - 32)); + } + if !ClassBytesRange::new(b'A', b'Z').is_intersection_empty(self) { + let lower = cmp::max(self.start, b'A'); + let upper = cmp::min(self.end, b'Z'); + ranges.push(ClassBytesRange::new(lower + 32, upper + 32)); + } + } +} + +impl ClassBytesRange { + /// Create a new byte range for a character class. + /// + /// The returned range is always in a canonical form. That is, the range + /// returned always satisfies the invariant that `start <= end`. + pub fn new(start: u8, end: u8) -> ClassBytesRange { + ClassBytesRange::create(start, end) + } + + /// Return the start of this range. + /// + /// The start of a range is always less than or equal to the end of the + /// range. + pub fn start(&self) -> u8 { + self.start + } + + /// Return the end of this range. + /// + /// The end of a range is always greater than or equal to the start of the + /// range. + pub fn end(&self) -> u8 { + self.end + } +} + +impl fmt::Debug for ClassBytesRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut debug = f.debug_struct("ClassBytesRange"); + if self.start <= 0x7F { + debug.field("start", &(self.start as char)); + } else { + debug.field("start", &self.start); + } + if self.end <= 0x7F { + debug.field("end", &(self.end as char)); + } else { + debug.field("end", &self.end); + } + debug.finish() + } +} + +/// The high-level intermediate representation for an anchor assertion. +/// +/// A matching anchor assertion is always zero-length. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Anchor { + /// Match the beginning of a line or the beginning of text. Specifically, + /// this matches at the starting position of the input, or at the position + /// immediately following a `\n` character. + StartLine, + /// Match the end of a line or the end of text. Specifically, + /// this matches at the end position of the input, or at the position + /// immediately preceding a `\n` character. + EndLine, + /// Match the beginning of text. Specifically, this matches at the starting + /// position of the input. + StartText, + /// Match the end of text. Specifically, this matches at the ending + /// position of the input. + EndText, +} + +/// The high-level intermediate representation for a word-boundary assertion. +/// +/// A matching word boundary assertion is always zero-length. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum WordBoundary { + /// Match a Unicode-aware word boundary. That is, this matches a position + /// where the left adjacent character and right adjacent character + /// correspond to a word and non-word or a non-word and word character. + Unicode, + /// Match a Unicode-aware negation of a word boundary. + UnicodeNegate, + /// Match an ASCII-only word boundary. That is, this matches a position + /// where the left adjacent character and right adjacent character + /// correspond to a word and non-word or a non-word and word character. + Ascii, + /// Match an ASCII-only negation of a word boundary. + AsciiNegate, +} + +impl WordBoundary { + /// Returns true if and only if this word boundary assertion is negated. + pub fn is_negated(&self) -> bool { + match *self { + WordBoundary::Unicode | WordBoundary::Ascii => false, + WordBoundary::UnicodeNegate | WordBoundary::AsciiNegate => true, + } + } +} + +/// The high-level intermediate representation for a group. +/// +/// This represents one of three possible group types: +/// +/// 1. A non-capturing group (e.g., `(?:expr)`). +/// 2. A capturing group (e.g., `(expr)`). +/// 3. A named capturing group (e.g., `(?Pexpr)`). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Group { + /// The kind of this group. If it is a capturing group, then the kind + /// contains the capture group index (and the name, if it is a named + /// group). + pub kind: GroupKind, + /// The expression inside the capturing group, which may be empty. + pub hir: Box, +} + +/// The kind of group. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GroupKind { + /// A normal unnamed capturing group. + /// + /// The value is the capture index of the group. + CaptureIndex(u32), + /// A named capturing group. + CaptureName { + /// The name of the group. + name: String, + /// The capture index of the group. + index: u32, + }, + /// A non-capturing group. + NonCapturing, +} + +/// The high-level intermediate representation of a repetition operator. +/// +/// A repetition operator permits the repetition of an arbitrary +/// sub-expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Repetition { + /// The kind of this repetition operator. + pub kind: RepetitionKind, + /// Whether this repetition operator is greedy or not. A greedy operator + /// will match as much as it can. A non-greedy operator will match as + /// little as it can. + /// + /// Typically, operators are greedy by default and are only non-greedy when + /// a `?` suffix is used, e.g., `(expr)*` is greedy while `(expr)*?` is + /// not. However, this can be inverted via the `U` "ungreedy" flag. + pub greedy: bool, + /// The expression being repeated. + pub hir: Box, +} + +impl Repetition { + /// Returns true if and only if this repetition operator makes it possible + /// to match the empty string. + /// + /// Note that this is not defined inductively. For example, while `a*` + /// will report `true`, `()+` will not, even though `()` matches the empty + /// string and one or more occurrences of something that matches the empty + /// string will always match the empty string. In order to get the + /// inductive definition, see the corresponding method on + /// [`Hir`](struct.Hir.html). + pub fn is_match_empty(&self) -> bool { + match self.kind { + RepetitionKind::ZeroOrOne => true, + RepetitionKind::ZeroOrMore => true, + RepetitionKind::OneOrMore => false, + RepetitionKind::Range(RepetitionRange::Exactly(m)) => m == 0, + RepetitionKind::Range(RepetitionRange::AtLeast(m)) => m == 0, + RepetitionKind::Range(RepetitionRange::Bounded(m, _)) => m == 0, + } + } +} + +/// The kind of a repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionKind { + /// Matches a sub-expression zero or one times. + ZeroOrOne, + /// Matches a sub-expression zero or more times. + ZeroOrMore, + /// Matches a sub-expression one or more times. + OneOrMore, + /// Matches a sub-expression within a bounded range of times. + Range(RepetitionRange), +} + +/// The kind of a counted repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionRange { + /// Matches a sub-expression exactly this many times. + Exactly(u32), + /// Matches a sub-expression at least this many times. + AtLeast(u32), + /// Matches a sub-expression at least `m` times and at most `n` times. + Bounded(u32, u32), +} + +/// A custom `Drop` impl is used for `HirKind` such that it uses constant stack +/// space but heap space proportional to the depth of the total `Hir`. +impl Drop for Hir { + fn drop(&mut self) { + use std::mem; + + match *self.kind() { + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) => return, + HirKind::Group(ref x) if !x.hir.kind.has_subexprs() => return, + HirKind::Repetition(ref x) if !x.hir.kind.has_subexprs() => return, + HirKind::Concat(ref x) if x.is_empty() => return, + HirKind::Alternation(ref x) if x.is_empty() => return, + _ => {} + } + + let mut stack = vec![mem::replace(self, Hir::empty())]; + while let Some(mut expr) = stack.pop() { + match expr.kind { + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) => {} + HirKind::Group(ref mut x) => { + stack.push(mem::replace(&mut x.hir, Hir::empty())); + } + HirKind::Repetition(ref mut x) => { + stack.push(mem::replace(&mut x.hir, Hir::empty())); + } + HirKind::Concat(ref mut x) => { + stack.extend(x.drain(..)); + } + HirKind::Alternation(ref mut x) => { + stack.extend(x.drain(..)); + } + } + } + } +} + +/// A type that documents various attributes of an HIR expression. +/// +/// These attributes are typically defined inductively on the HIR. +#[derive(Clone, Debug, Eq, PartialEq)] +struct HirInfo { + /// Represent yes/no questions by a bitfield to conserve space, since + /// this is included in every HIR expression. + /// + /// If more attributes need to be added, it is OK to increase the size of + /// this as appropriate. + bools: u8, +} + +// A simple macro for defining bitfield accessors/mutators. +macro_rules! define_bool { + ($bit:expr, $is_fn_name:ident, $set_fn_name:ident) => { + fn $is_fn_name(&self) -> bool { + self.bools & (0b1 << $bit) > 0 + } + + fn $set_fn_name(&mut self, yes: bool) { + if yes { + self.bools |= 1 << $bit; + } else { + self.bools &= !(1 << $bit); + } + } + } +} + +impl HirInfo { + fn new() -> HirInfo { + HirInfo { + bools: 0, + } + } + + define_bool!(0, is_always_utf8, set_always_utf8); + define_bool!(1, is_all_assertions, set_all_assertions); + define_bool!(2, is_anchored_start, set_anchored_start); + define_bool!(3, is_anchored_end, set_anchored_end); + define_bool!(4, is_any_anchored_start, set_any_anchored_start); + define_bool!(5, is_any_anchored_end, set_any_anchored_end); + define_bool!(6, is_match_empty, set_match_empty); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn uclass(ranges: &[(char, char)]) -> ClassUnicode { + let ranges: Vec = ranges + .iter() + .map(|&(s, e)| ClassUnicodeRange::new(s, e)) + .collect(); + ClassUnicode::new(ranges) + } + + fn bclass(ranges: &[(u8, u8)]) -> ClassBytes { + let ranges: Vec = ranges + .iter() + .map(|&(s, e)| ClassBytesRange::new(s, e)) + .collect(); + ClassBytes::new(ranges) + } + + fn uranges(cls: &ClassUnicode) -> Vec<(char, char)> { + cls.iter().map(|x| (x.start(), x.end())).collect() + } + + fn ucasefold(cls: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls.clone(); + cls_.case_fold_simple(); + cls_ + } + + fn uunion(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.union(cls2); + cls_ + } + + fn uintersect(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.intersect(cls2); + cls_ + } + + fn udifference(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.difference(cls2); + cls_ + } + + fn usymdifference(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.symmetric_difference(cls2); + cls_ + } + + fn unegate(cls: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls.clone(); + cls_.negate(); + cls_ + } + + fn branges(cls: &ClassBytes) -> Vec<(u8, u8)> { + cls.iter().map(|x| (x.start(), x.end())).collect() + } + + fn bcasefold(cls: &ClassBytes) -> ClassBytes { + let mut cls_ = cls.clone(); + cls_.case_fold_simple(); + cls_ + } + + fn bunion(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.union(cls2); + cls_ + } + + fn bintersect(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.intersect(cls2); + cls_ + } + + fn bdifference(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.difference(cls2); + cls_ + } + + fn bsymdifference(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.symmetric_difference(cls2); + cls_ + } + + fn bnegate(cls: &ClassBytes) -> ClassBytes { + let mut cls_ = cls.clone(); + cls_.negate(); + cls_ + } + + #[test] + fn class_range_canonical_unicode() { + let range = ClassUnicodeRange::new('\u{00FF}', '\0'); + assert_eq!('\0', range.start()); + assert_eq!('\u{00FF}', range.end()); + } + + #[test] + fn class_range_canonical_bytes() { + let range = ClassBytesRange::new(b'\xFF', b'\0'); + assert_eq!(b'\0', range.start()); + assert_eq!(b'\xFF', range.end()); + } + + #[test] + fn class_canonicalize_unicode() { + let cls = uclass(&[('a', 'c'), ('x', 'z')]); + let expected = vec![('a', 'c'), ('x', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('x', 'z'), ('a', 'c')]); + let expected = vec![('a', 'c'), ('x', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('x', 'z'), ('w', 'y')]); + let expected = vec![('w', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[ + ('c', 'f'), ('a', 'g'), ('d', 'j'), ('a', 'c'), + ('m', 'p'), ('l', 's'), + ]); + let expected = vec![('a', 'j'), ('l', 's')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('x', 'z'), ('u', 'w')]); + let expected = vec![('u', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('\x00', '\u{10FFFF}'), ('\x00', '\u{10FFFF}')]); + let expected = vec![('\x00', '\u{10FFFF}')]; + assert_eq!(expected, uranges(&cls)); + + + let cls = uclass(&[('a', 'a'), ('b', 'b')]); + let expected = vec![('a', 'b')]; + assert_eq!(expected, uranges(&cls)); + } + + #[test] + fn class_canonicalize_bytes() { + let cls = bclass(&[(b'a', b'c'), (b'x', b'z')]); + let expected = vec![(b'a', b'c'), (b'x', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'x', b'z'), (b'a', b'c')]); + let expected = vec![(b'a', b'c'), (b'x', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'x', b'z'), (b'w', b'y')]); + let expected = vec![(b'w', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[ + (b'c', b'f'), (b'a', b'g'), (b'd', b'j'), (b'a', b'c'), + (b'm', b'p'), (b'l', b's'), + ]); + let expected = vec![(b'a', b'j'), (b'l', b's')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'x', b'z'), (b'u', b'w')]); + let expected = vec![(b'u', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'\x00', b'\xFF'), (b'\x00', b'\xFF')]); + let expected = vec![(b'\x00', b'\xFF')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'a', b'a'), (b'b', b'b')]); + let expected = vec![(b'a', b'b')]; + assert_eq!(expected, branges(&cls)); + } + + #[test] + fn class_case_fold_unicode() { + let cls = uclass(&[ + ('C', 'F'), ('A', 'G'), ('D', 'J'), ('A', 'C'), + ('M', 'P'), ('L', 'S'), ('c', 'f'), + ]); + let expected = uclass(&[ + ('A', 'J'), ('L', 'S'), + ('a', 'j'), ('l', 's'), + ('\u{17F}', '\u{17F}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('A', 'Z')]); + let expected = uclass(&[ + ('A', 'Z'), ('a', 'z'), + ('\u{17F}', '\u{17F}'), + ('\u{212A}', '\u{212A}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('a', 'z')]); + let expected = uclass(&[ + ('A', 'Z'), ('a', 'z'), + ('\u{17F}', '\u{17F}'), + ('\u{212A}', '\u{212A}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('A', 'A'), ('_', '_')]); + let expected = uclass(&[('A', 'A'), ('_', '_'), ('a', 'a')]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('A', 'A'), ('=', '=')]); + let expected = uclass(&[('=', '='), ('A', 'A'), ('a', 'a')]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('\x00', '\x10')]); + assert_eq!(cls, ucasefold(&cls)); + + let cls = uclass(&[('k', 'k')]); + let expected = uclass(&[ + ('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('@', '@')]); + assert_eq!(cls, ucasefold(&cls)); + } + + #[test] + fn class_case_fold_bytes() { + let cls = bclass(&[ + (b'C', b'F'), (b'A', b'G'), (b'D', b'J'), (b'A', b'C'), + (b'M', b'P'), (b'L', b'S'), (b'c', b'f'), + ]); + let expected = bclass(&[ + (b'A', b'J'), (b'L', b'S'), + (b'a', b'j'), (b'l', b's'), + ]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'A', b'Z')]); + let expected = bclass(&[(b'A', b'Z'), (b'a', b'z')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'a', b'z')]); + let expected = bclass(&[(b'A', b'Z'), (b'a', b'z')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'A', b'A'), (b'_', b'_')]); + let expected = bclass(&[(b'A', b'A'), (b'_', b'_'), (b'a', b'a')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'A', b'A'), (b'=', b'=')]); + let expected = bclass(&[(b'=', b'='), (b'A', b'A'), (b'a', b'a')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'\x00', b'\x10')]); + assert_eq!(cls, bcasefold(&cls)); + + let cls = bclass(&[(b'k', b'k')]); + let expected = bclass(&[(b'K', b'K'), (b'k', b'k')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'@', b'@')]); + assert_eq!(cls, bcasefold(&cls)); + } + + #[test] + fn class_negate_unicode() { + let cls = uclass(&[('a', 'a')]); + let expected = uclass(&[('\x00', '\x60'), ('\x62', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('a', 'a'), ('b', 'b')]); + let expected = uclass(&[('\x00', '\x60'), ('\x63', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('a', 'c'), ('x', 'z')]); + let expected = uclass(&[ + ('\x00', '\x60'), ('\x64', '\x77'), ('\x7B', '\u{10FFFF}'), + ]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', 'a')]); + let expected = uclass(&[('\x62', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('a', '\u{10FFFF}')]); + let expected = uclass(&[('\x00', '\x60')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', '\u{10FFFF}')]); + let expected = uclass(&[]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[]); + let expected = uclass(&[('\x00', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[ + ('\x00', '\u{10FFFD}'), ('\u{10FFFF}', '\u{10FFFF}'), + ]); + let expected = uclass(&[('\u{10FFFE}', '\u{10FFFE}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', '\u{D7FF}')]); + let expected = uclass(&[('\u{E000}', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', '\u{D7FE}')]); + let expected = uclass(&[('\u{D7FF}', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\u{E000}', '\u{10FFFF}')]); + let expected = uclass(&[('\x00', '\u{D7FF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\u{E001}', '\u{10FFFF}')]); + let expected = uclass(&[('\x00', '\u{E000}')]); + assert_eq!(expected, unegate(&cls)); + } + + #[test] + fn class_negate_bytes() { + let cls = bclass(&[(b'a', b'a')]); + let expected = bclass(&[(b'\x00', b'\x60'), (b'\x62', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'a', b'a'), (b'b', b'b')]); + let expected = bclass(&[(b'\x00', b'\x60'), (b'\x63', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'a', b'c'), (b'x', b'z')]); + let expected = bclass(&[ + (b'\x00', b'\x60'), (b'\x64', b'\x77'), (b'\x7B', b'\xFF'), + ]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'\x00', b'a')]); + let expected = bclass(&[(b'\x62', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'a', b'\xFF')]); + let expected = bclass(&[(b'\x00', b'\x60')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'\x00', b'\xFF')]); + let expected = bclass(&[]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[]); + let expected = bclass(&[(b'\x00', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'\x00', b'\xFD'), (b'\xFF', b'\xFF')]); + let expected = bclass(&[(b'\xFE', b'\xFE')]); + assert_eq!(expected, bnegate(&cls)); + } + + #[test] + fn class_union_unicode() { + let cls1 = uclass(&[('a', 'g'), ('m', 't'), ('A', 'C')]); + let cls2 = uclass(&[('a', 'z')]); + let expected = uclass(&[('a', 'z'), ('A', 'C')]); + assert_eq!(expected, uunion(&cls1, &cls2)); + } + + #[test] + fn class_union_bytes() { + let cls1 = bclass(&[(b'a', b'g'), (b'm', b't'), (b'A', b'C')]); + let cls2 = bclass(&[(b'a', b'z')]); + let expected = bclass(&[(b'a', b'z'), (b'A', b'C')]); + assert_eq!(expected, bunion(&cls1, &cls2)); + } + + #[test] + fn class_intersect_unicode() { + let cls1 = uclass(&[]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[('a', 'a')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('b', 'b')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('a', 'c')]); + let expected = uclass(&[('a', 'a')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b')]); + let cls2 = uclass(&[('a', 'c')]); + let expected = uclass(&[('a', 'b')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b')]); + let cls2 = uclass(&[('b', 'c')]); + let expected = uclass(&[('b', 'b')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b')]); + let cls2 = uclass(&[('c', 'd')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('b', 'c')]); + let cls2 = uclass(&[('a', 'd')]); + let expected = uclass(&[('b', 'c')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let cls2 = uclass(&[('a', 'h')]); + let expected = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let cls2 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let expected = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('g', 'h')]); + let cls2 = uclass(&[('d', 'e'), ('k', 'l')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let cls2 = uclass(&[('h', 'h')]); + let expected = uclass(&[('h', 'h')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('e', 'f'), ('i', 'j')]); + let cls2 = uclass(&[('c', 'd'), ('g', 'h'), ('k', 'l')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('c', 'd'), ('e', 'f')]); + let cls2 = uclass(&[('b', 'c'), ('d', 'e'), ('f', 'g')]); + let expected = uclass(&[('b', 'f')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + } + + #[test] + fn class_intersect_bytes() { + let cls1 = bclass(&[]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[(b'a', b'a')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'b', b'b')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'a', b'c')]); + let expected = bclass(&[(b'a', b'a')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b')]); + let cls2 = bclass(&[(b'a', b'c')]); + let expected = bclass(&[(b'a', b'b')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b')]); + let cls2 = bclass(&[(b'b', b'c')]); + let expected = bclass(&[(b'b', b'b')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b')]); + let cls2 = bclass(&[(b'c', b'd')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'b', b'c')]); + let cls2 = bclass(&[(b'a', b'd')]); + let expected = bclass(&[(b'b', b'c')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let cls2 = bclass(&[(b'a', b'h')]); + let expected = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let cls2 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let expected = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'g', b'h')]); + let cls2 = bclass(&[(b'd', b'e'), (b'k', b'l')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let cls2 = bclass(&[(b'h', b'h')]); + let expected = bclass(&[(b'h', b'h')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'e', b'f'), (b'i', b'j')]); + let cls2 = bclass(&[(b'c', b'd'), (b'g', b'h'), (b'k', b'l')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'c', b'd'), (b'e', b'f')]); + let cls2 = bclass(&[(b'b', b'c'), (b'd', b'e'), (b'f', b'g')]); + let expected = bclass(&[(b'b', b'f')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + } + + #[test] + fn class_difference_unicode() { + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[]); + let expected = uclass(&[('a', 'a')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[('b', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('z', 'z')]); + let expected = uclass(&[('a', 'y')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('m', 'm')]); + let expected = uclass(&[('a', 'l'), ('n', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('a', 'z')]); + let expected = uclass(&[]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('d', 'v')]); + let expected = uclass(&[('a', 'c')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('b', 'g'), ('s', 'u')]); + let expected = uclass(&[('a', 'a'), ('h', 'i'), ('r', 'r')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('b', 'd'), ('e', 'g'), ('s', 'u')]); + let expected = uclass(&[('a', 'a'), ('h', 'i'), ('r', 'r')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('x', 'z')]); + let cls2 = uclass(&[('a', 'c'), ('e', 'g'), ('s', 'u')]); + let expected = uclass(&[('x', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('a', 'c'), ('e', 'g'), ('s', 'u')]); + let expected = uclass(&[('d', 'd'), ('h', 'r'), ('v', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + } + + #[test] + fn class_difference_bytes() { + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[]); + let expected = bclass(&[(b'a', b'a')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[(b'b', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'z', b'z')]); + let expected = bclass(&[(b'a', b'y')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'm', b'm')]); + let expected = bclass(&[(b'a', b'l'), (b'n', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'a', b'z')]); + let expected = bclass(&[]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'd', b'v')]); + let expected = bclass(&[(b'a', b'c')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'b', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'a', b'a'), (b'h', b'i'), (b'r', b'r')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'b', b'd'), (b'e', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'a', b'a'), (b'h', b'i'), (b'r', b'r')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'x', b'z')]); + let cls2 = bclass(&[(b'a', b'c'), (b'e', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'x', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'a', b'c'), (b'e', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'd', b'd'), (b'h', b'r'), (b'v', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + } + + #[test] + fn class_symmetric_difference_unicode() { + let cls1 = uclass(&[('a', 'm')]); + let cls2 = uclass(&[('g', 't')]); + let expected = uclass(&[('a', 'f'), ('n', 't')]); + assert_eq!(expected, usymdifference(&cls1, &cls2)); + } + + #[test] + fn class_symmetric_difference_bytes() { + let cls1 = bclass(&[(b'a', b'm')]); + let cls2 = bclass(&[(b'g', b't')]); + let expected = bclass(&[(b'a', b'f'), (b'n', b't')]); + assert_eq!(expected, bsymdifference(&cls1, &cls2)); + } + + #[test] + #[should_panic] + fn hir_byte_literal_non_ascii() { + Hir::literal(Literal::Byte(b'a')); + } + + // We use a thread with an explicit stack size to test that our destructor + // for Hir can handle arbitrarily sized expressions in constant stack + // space. In case we run on a platform without threads (WASM?), we limit + // this test to Windows/Unix. + #[test] + #[cfg(any(unix, windows))] + fn no_stack_overflow_on_drop() { + use std::thread; + + let run = || { + let mut expr = Hir::empty(); + for _ in 0..100 { + expr = Hir::group(Group { + kind: GroupKind::NonCapturing, + hir: Box::new(expr), + }); + expr = Hir::repetition(Repetition { + kind: RepetitionKind::ZeroOrOne, + greedy: true, + hir: Box::new(expr), + }); + + expr = Hir { + kind: HirKind::Concat(vec![expr]), + info: HirInfo::new(), + }; + expr = Hir { + kind: HirKind::Alternation(vec![expr]), + info: HirInfo::new(), + }; + } + assert!(!expr.kind.is_empty()); + }; + + // We run our test on a thread with a small stack size so we can + // force the issue more easily. + thread::Builder::new() + .stack_size(1<<10) + .spawn(run) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/hir/print.rs b/bash-5.1/vendor/regex-syntax/src/hir/print.rs new file mode 100644 index 0000000..f314685 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/hir/print.rs @@ -0,0 +1,359 @@ +/*! +This module provides a regular expression printer for `Hir`. +*/ + +use std::fmt; + +use hir::{self, Hir, HirKind}; +use hir::visitor::{self, Visitor}; +use is_meta_character; + +/// A builder for constructing a printer. +/// +/// Note that since a printer doesn't have any configuration knobs, this type +/// remains unexported. +#[derive(Clone, Debug)] +struct PrinterBuilder { + _priv: (), +} + +impl Default for PrinterBuilder { + fn default() -> PrinterBuilder { + PrinterBuilder::new() + } +} + +impl PrinterBuilder { + fn new() -> PrinterBuilder { + PrinterBuilder { + _priv: (), + } + } + + fn build(&self) -> Printer { + Printer { + _priv: (), + } + } +} + +/// A printer for a regular expression's high-level intermediate +/// representation. +/// +/// A printer converts a high-level intermediate representation (HIR) to a +/// regular expression pattern string. This particular printer uses constant +/// stack space and heap space proportional to the size of the HIR. +/// +/// Since this printer is only using the HIR, the pattern it prints will likely +/// not resemble the original pattern at all. For example, a pattern like +/// `\pL` will have its entire class written out. +/// +/// The purpose of this printer is to provide a means to mutate an HIR and then +/// build a regular expression from the result of that mutation. (A regex +/// library could provide a constructor from this HIR explicitly, but that +/// creates an unnecessary public coupling between the regex library and this +/// specific HIR representation.) +#[derive(Debug)] +pub struct Printer { + _priv: (), +} + +impl Printer { + /// Create a new printer. + pub fn new() -> Printer { + PrinterBuilder::new().build() + } + + /// Print the given `Ast` to the given writer. The writer must implement + /// `fmt::Write`. Typical implementations of `fmt::Write` that can be used + /// here are a `fmt::Formatter` (which is available in `fmt::Display` + /// implementations) or a `&mut String`. + pub fn print(&mut self, hir: &Hir, wtr: W) -> fmt::Result { + visitor::visit(hir, Writer { printer: self, wtr: wtr }) + } +} + +#[derive(Debug)] +struct Writer<'p, W> { + printer: &'p mut Printer, + wtr: W, +} + +impl<'p, W: fmt::Write> Visitor for Writer<'p, W> { + type Output = (); + type Err = fmt::Error; + + fn finish(self) -> fmt::Result { + Ok(()) + } + + fn visit_pre(&mut self, hir: &Hir) -> fmt::Result { + match *hir.kind() { + HirKind::Empty + | HirKind::Repetition(_) + | HirKind::Concat(_) + | HirKind::Alternation(_) => {} + HirKind::Literal(hir::Literal::Unicode(c)) => { + try!(self.write_literal_char(c)); + } + HirKind::Literal(hir::Literal::Byte(b)) => { + try!(self.write_literal_byte(b)); + } + HirKind::Class(hir::Class::Unicode(ref cls)) => { + try!(self.wtr.write_str("[")); + for range in cls.iter() { + if range.start() == range.end() { + try!(self.write_literal_char(range.start())); + } else { + try!(self.write_literal_char(range.start())); + try!(self.wtr.write_str("-")); + try!(self.write_literal_char(range.end())); + } + } + try!(self.wtr.write_str("]")); + } + HirKind::Class(hir::Class::Bytes(ref cls)) => { + try!(self.wtr.write_str("(?-u:[")); + for range in cls.iter() { + if range.start() == range.end() { + try!(self.write_literal_class_byte(range.start())); + } else { + try!(self.write_literal_class_byte(range.start())); + try!(self.wtr.write_str("-")); + try!(self.write_literal_class_byte(range.end())); + } + } + try!(self.wtr.write_str("])")); + } + HirKind::Anchor(hir::Anchor::StartLine) => { + try!(self.wtr.write_str("(?m:^)")); + } + HirKind::Anchor(hir::Anchor::EndLine) => { + try!(self.wtr.write_str("(?m:$)")); + } + HirKind::Anchor(hir::Anchor::StartText) => { + try!(self.wtr.write_str(r"\A")); + } + HirKind::Anchor(hir::Anchor::EndText) => { + try!(self.wtr.write_str(r"\z")); + } + HirKind::WordBoundary(hir::WordBoundary::Unicode) => { + try!(self.wtr.write_str(r"\b")); + } + HirKind::WordBoundary(hir::WordBoundary::UnicodeNegate) => { + try!(self.wtr.write_str(r"\B")); + } + HirKind::WordBoundary(hir::WordBoundary::Ascii) => { + try!(self.wtr.write_str(r"(?-u:\b)")); + } + HirKind::WordBoundary(hir::WordBoundary::AsciiNegate) => { + try!(self.wtr.write_str(r"(?-u:\B)")); + } + HirKind::Group(ref x) => { + match x.kind { + hir::GroupKind::CaptureIndex(_) => { + try!(self.wtr.write_str("(")); + } + hir::GroupKind::CaptureName { ref name, .. } => { + try!(write!(self.wtr, "(?P<{}>", name)); + } + hir::GroupKind::NonCapturing => { + try!(self.wtr.write_str("(?:")); + } + } + } + } + Ok(()) + } + + fn visit_post(&mut self, hir: &Hir) -> fmt::Result { + match *hir.kind() { + // Handled during visit_pre + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) + | HirKind::Concat(_) + | HirKind::Alternation(_) => {} + HirKind::Repetition(ref x) => { + match x.kind { + hir::RepetitionKind::ZeroOrOne => { + try!(self.wtr.write_str("?")); + } + hir::RepetitionKind::ZeroOrMore => { + try!(self.wtr.write_str("*")); + } + hir::RepetitionKind::OneOrMore => { + try!(self.wtr.write_str("+")); + } + hir::RepetitionKind::Range(ref x) => { + match *x { + hir::RepetitionRange::Exactly(m) => { + try!(write!(self.wtr, "{{{}}}", m)); + } + hir::RepetitionRange::AtLeast(m) => { + try!(write!(self.wtr, "{{{},}}", m)); + } + hir::RepetitionRange::Bounded(m, n) => { + try!(write!(self.wtr, "{{{},{}}}", m, n)); + } + } + } + } + if !x.greedy { + try!(self.wtr.write_str("?")); + } + } + HirKind::Group(_) => { + try!(self.wtr.write_str(")")); + } + } + Ok(()) + } + + fn visit_alternation_in(&mut self) -> fmt::Result { + self.wtr.write_str("|") + } +} + +impl<'p, W: fmt::Write> Writer<'p, W> { + fn write_literal_char(&mut self, c: char) -> fmt::Result { + if is_meta_character(c) { + try!(self.wtr.write_str("\\")); + } + self.wtr.write_char(c) + } + + fn write_literal_byte(&mut self, b: u8) -> fmt::Result { + let c = b as char; + if c <= 0x7F as char && !c.is_control() && !c.is_whitespace() { + self.wtr.write_char(c) + } else { + write!(self.wtr, "(?-u:\\x{:02X})", b) + } + } + + fn write_literal_class_byte(&mut self, b: u8) -> fmt::Result { + let c = b as char; + if c <= 0x7F as char && !c.is_control() && !c.is_whitespace() { + self.wtr.write_char(c) + } else { + write!(self.wtr, "\\x{:02X}", b) + } + } +} + +#[cfg(test)] +mod tests { + use ParserBuilder; + use super::Printer; + + fn roundtrip(given: &str, expected: &str) { + roundtrip_with(|b| b, given, expected); + } + + fn roundtrip_bytes(given: &str, expected: &str) { + roundtrip_with(|b| b.allow_invalid_utf8(true), given, expected); + } + + fn roundtrip_with(mut f: F, given: &str, expected: &str) + where F: FnMut(&mut ParserBuilder) -> &mut ParserBuilder + { + let mut builder = ParserBuilder::new(); + f(&mut builder); + let hir = builder.build().parse(given).unwrap(); + + let mut printer = Printer::new(); + let mut dst = String::new(); + printer.print(&hir, &mut dst).unwrap(); + assert_eq!(expected, dst); + } + + #[test] + fn print_literal() { + roundtrip("a", "a"); + roundtrip(r"\xff", "\u{FF}"); + roundtrip_bytes(r"\xff", "\u{FF}"); + roundtrip_bytes(r"(?-u)\xff", r"(?-u:\xFF)"); + roundtrip("☃", "☃"); + } + + #[test] + fn print_class() { + roundtrip(r"[a]", r"[a]"); + roundtrip(r"[a-z]", r"[a-z]"); + roundtrip(r"[a-z--b-c--x-y]", r"[ad-wz]"); + roundtrip(r"[^\x01-\u{10FFFF}]", "[\u{0}]"); + roundtrip(r"[-]", r"[\-]"); + roundtrip(r"[☃-⛄]", r"[☃-⛄]"); + + roundtrip(r"(?-u)[a]", r"(?-u:[a])"); + roundtrip(r"(?-u)[a-z]", r"(?-u:[a-z])"); + roundtrip_bytes(r"(?-u)[a-\xFF]", r"(?-u:[a-\xFF])"); + } + + #[test] + fn print_anchor() { + roundtrip(r"^", r"\A"); + roundtrip(r"$", r"\z"); + roundtrip(r"(?m)^", r"(?m:^)"); + roundtrip(r"(?m)$", r"(?m:$)"); + } + + #[test] + fn print_word_boundary() { + roundtrip(r"\b", r"\b"); + roundtrip(r"\B", r"\B"); + roundtrip(r"(?-u)\b", r"(?-u:\b)"); + roundtrip_bytes(r"(?-u)\B", r"(?-u:\B)"); + } + + #[test] + fn print_repetition() { + roundtrip("a?", "a?"); + roundtrip("a??", "a??"); + roundtrip("(?U)a?", "a??"); + + roundtrip("a*", "a*"); + roundtrip("a*?", "a*?"); + roundtrip("(?U)a*", "a*?"); + + roundtrip("a+", "a+"); + roundtrip("a+?", "a+?"); + roundtrip("(?U)a+", "a+?"); + + roundtrip("a{1}", "a{1}"); + roundtrip("a{1,}", "a{1,}"); + roundtrip("a{1,5}", "a{1,5}"); + roundtrip("a{1}?", "a{1}?"); + roundtrip("a{1,}?", "a{1,}?"); + roundtrip("a{1,5}?", "a{1,5}?"); + roundtrip("(?U)a{1}", "a{1}?"); + roundtrip("(?U)a{1,}", "a{1,}?"); + roundtrip("(?U)a{1,5}", "a{1,5}?"); + } + + #[test] + fn print_group() { + roundtrip("()", "()"); + roundtrip("(?P)", "(?P)"); + roundtrip("(?:)", "(?:)"); + + roundtrip("(a)", "(a)"); + roundtrip("(?Pa)", "(?Pa)"); + roundtrip("(?:a)", "(?:a)"); + + roundtrip("((((a))))", "((((a))))"); + } + + #[test] + fn print_alternation() { + roundtrip("|", "|"); + roundtrip("||", "||"); + + roundtrip("a|b", "a|b"); + roundtrip("a|b|c", "a|b|c"); + roundtrip("foo|bar|quux", "foo|bar|quux"); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/hir/translate.rs b/bash-5.1/vendor/regex-syntax/src/hir/translate.rs new file mode 100644 index 0000000..dac85c0 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/hir/translate.rs @@ -0,0 +1,2537 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Defines a translator that converts an `Ast` to an `Hir`. +*/ + +use std::cell::{Cell, RefCell}; +use std::result; + +use ast::{self, Ast, Span, Visitor}; +use hir::{self, Error, ErrorKind, Hir}; +use unicode::{self, ClassQuery}; + +type Result = result::Result; + +/// A builder for constructing an AST->HIR translator. +#[derive(Clone, Debug)] +pub struct TranslatorBuilder { + allow_invalid_utf8: bool, + flags: Flags, +} + +impl Default for TranslatorBuilder { + fn default() -> TranslatorBuilder { + TranslatorBuilder::new() + } +} + +impl TranslatorBuilder { + /// Create a new translator builder with a default c onfiguration. + pub fn new() -> TranslatorBuilder { + TranslatorBuilder { + allow_invalid_utf8: false, + flags: Flags::default(), + } + } + + /// Build a translator using the current configuration. + pub fn build(&self) -> Translator { + Translator { + stack: RefCell::new(vec![]), + flags: Cell::new(self.flags), + allow_invalid_utf8: self.allow_invalid_utf8, + } + } + + /// When enabled, translation will permit the construction of a regular + /// expression that may match invalid UTF-8. + /// + /// When disabled (the default), the translator is guaranteed to produce + /// an expression that will only ever match valid UTF-8 (otherwise, the + /// translator will return an error). + /// + /// Note that currently, even when invalid UTF-8 is banned, the translator + /// will permit a negated ASCII word boundary (i.e., `(?-u:\B)`) even + /// though it can actually match at invalid UTF-8 boundaries. This bug + /// will be fixed on the next semver release. + pub fn allow_invalid_utf8( + &mut self, + yes: bool, + ) -> &mut TranslatorBuilder { + self.allow_invalid_utf8 = yes; + self + } + + /// Enable or disable the case insensitive flag (`i`) by default. + pub fn case_insensitive(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.case_insensitive = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the multi-line matching flag (`m`) by default. + pub fn multi_line(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.multi_line = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the "dot matches any character" flag (`s`) by + /// default. + pub fn dot_matches_new_line( + &mut self, + yes: bool, + ) -> &mut TranslatorBuilder { + self.flags.dot_matches_new_line = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the "swap greed" flag (`U`) by default. + pub fn swap_greed(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.swap_greed = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the Unicode flag (`u`) by default. + pub fn unicode(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.unicode = if yes { None } else { Some(false) }; + self + } +} + +/// A translator maps abstract syntax to a high level intermediate +/// representation. +/// +/// A translator may be benefit from reuse. That is, a translator can translate +/// many abstract syntax trees. +/// +/// A `Translator` can be configured in more detail via a +/// [`TranslatorBuilder`](struct.TranslatorBuilder.html). +#[derive(Clone, Debug)] +pub struct Translator { + /// Our call stack, but on the heap. + stack: RefCell>, + /// The current flag settings. + flags: Cell, + /// Whether we're allowed to produce HIR that can match arbitrary bytes. + allow_invalid_utf8: bool, +} + +impl Translator { + /// Create a new translator using the default configuration. + pub fn new() -> Translator { + TranslatorBuilder::new().build() + } + + /// Translate the given abstract syntax tree (AST) into a high level + /// intermediate representation (HIR). + /// + /// If there was a problem doing the translation, then an HIR-specific + /// error is returned. + /// + /// The original pattern string used to produce the `Ast` *must* also be + /// provided. The translator does not use the pattern string during any + /// correct translation, but is used for error reporting. + pub fn translate(&mut self, pattern: &str, ast: &Ast) -> Result { + ast::visit(ast, TranslatorI::new(self, pattern)) + } +} + +/// An HirFrame is a single stack frame, represented explicitly, which is +/// created for each item in the Ast that we traverse. +/// +/// Note that technically, this type doesn't represent our entire stack +/// frame. In particular, the Ast visitor represents any state associated with +/// traversing the Ast itself. +#[derive(Clone, Debug)] +enum HirFrame { + /// An arbitrary HIR expression. These get pushed whenever we hit a base + /// case in the Ast. They get popped after an inductive (i.e., recursive) + /// step is complete. + Expr(Hir), + /// A Unicode character class. This frame is mutated as we descend into + /// the Ast of a character class (which is itself its own mini recursive + /// structure). + ClassUnicode(hir::ClassUnicode), + /// A byte-oriented character class. This frame is mutated as we descend + /// into the Ast of a character class (which is itself its own mini + /// recursive structure). + /// + /// Byte character classes are created when Unicode mode (`u`) is disabled. + /// If `allow_invalid_utf8` is disabled (the default), then a byte + /// character is only permitted to match ASCII text. + ClassBytes(hir::ClassBytes), + /// This is pushed on to the stack upon first seeing any kind of group, + /// indicated by parentheses (including non-capturing groups). It is popped + /// upon leaving a group. + Group { + /// The old active flags, if any, when this group was opened. + /// + /// If this group sets flags, then the new active flags are set to the + /// result of merging the old flags with the flags introduced by this + /// group. + /// + /// When this group is popped, the active flags should be restored to + /// the flags set here. + /// + /// The "active" flags correspond to whatever flags are set in the + /// Translator. + old_flags: Option, + }, + /// This is pushed whenever a concatenation is observed. After visiting + /// every sub-expression in the concatenation, the translator's stack is + /// popped until it sees a Concat frame. + Concat, + /// This is pushed whenever an alternation is observed. After visiting + /// every sub-expression in the alternation, the translator's stack is + /// popped until it sees an Alternation frame. + Alternation, +} + +impl HirFrame { + /// Assert that the current stack frame is an Hir expression and return it. + fn unwrap_expr(self) -> Hir { + match self { + HirFrame::Expr(expr) => expr, + _ => panic!("tried to unwrap expr from HirFrame, got: {:?}", self) + } + } + + /// Assert that the current stack frame is a Unicode class expression and + /// return it. + fn unwrap_class_unicode(self) -> hir::ClassUnicode { + match self { + HirFrame::ClassUnicode(cls) => cls, + _ => panic!("tried to unwrap Unicode class \ + from HirFrame, got: {:?}", self) + } + } + + /// Assert that the current stack frame is a byte class expression and + /// return it. + fn unwrap_class_bytes(self) -> hir::ClassBytes { + match self { + HirFrame::ClassBytes(cls) => cls, + _ => panic!("tried to unwrap byte class \ + from HirFrame, got: {:?}", self) + } + } + + /// Assert that the current stack frame is a group indicator and return + /// its corresponding flags (the flags that were active at the time the + /// group was entered) if they exist. + fn unwrap_group(self) -> Option { + match self { + HirFrame::Group { old_flags } => old_flags, + _ => panic!("tried to unwrap group from HirFrame, got: {:?}", self) + } + } +} + +impl<'t, 'p> Visitor for TranslatorI<'t, 'p> { + type Output = Hir; + type Err = Error; + + fn finish(self) -> Result { + if self.trans().stack.borrow().is_empty() { + // This can happen if the Ast given consists of a single set of + // flags. e.g., `(?i)`. /shrug + return Ok(Hir::empty()); + } + // ... otherwise, we should have exactly one HIR on the stack. + assert_eq!(self.trans().stack.borrow().len(), 1); + Ok(self.pop().unwrap().unwrap_expr()) + } + + fn visit_pre(&mut self, ast: &Ast) -> Result<()> { + match *ast { + Ast::Class(ast::Class::Bracketed(_)) => { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + } + Ast::Group(ref x) => { + let old_flags = x.flags().map(|ast| self.set_flags(ast)); + self.push(HirFrame::Group { + old_flags: old_flags, + }); + } + Ast::Concat(ref x) if x.asts.is_empty() => {} + Ast::Concat(_) => { + self.push(HirFrame::Concat); + } + Ast::Alternation(ref x) if x.asts.is_empty() => {} + Ast::Alternation(_) => { + self.push(HirFrame::Alternation); + } + _ => {} + } + Ok(()) + } + + fn visit_post(&mut self, ast: &Ast) -> Result<()> { + match *ast { + Ast::Empty(_) => { + self.push(HirFrame::Expr(Hir::empty())); + } + Ast::Flags(ref x) => { + self.set_flags(&x.flags); + } + Ast::Literal(ref x) => { + self.push(HirFrame::Expr(try!(self.hir_literal(x)))); + } + Ast::Dot(span) => { + self.push(HirFrame::Expr(try!(self.hir_dot(span)))); + } + Ast::Assertion(ref x) => { + self.push(HirFrame::Expr(try!(self.hir_assertion(x)))); + } + Ast::Class(ast::Class::Perl(ref x)) => { + if self.flags().unicode() { + let cls = self.hir_perl_unicode_class(x); + let hcls = hir::Class::Unicode(cls); + self.push(HirFrame::Expr(Hir::class(hcls))); + } else { + let cls = self.hir_perl_byte_class(x); + let hcls = hir::Class::Bytes(cls); + self.push(HirFrame::Expr(Hir::class(hcls))); + } + } + Ast::Class(ast::Class::Unicode(ref x)) => { + let cls = hir::Class::Unicode(try!(self.hir_unicode_class(x))); + self.push(HirFrame::Expr(Hir::class(cls))); + } + Ast::Class(ast::Class::Bracketed(ref ast)) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + self.unicode_fold_and_negate(ast.negated, &mut cls); + if cls.iter().next().is_none() { + return Err(self.error( + ast.span, ErrorKind::EmptyClassNotAllowed)); + } + let expr = Hir::class(hir::Class::Unicode(cls)); + self.push(HirFrame::Expr(expr)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + try!(self.bytes_fold_and_negate( + &ast.span, ast.negated, &mut cls)); + if cls.iter().next().is_none() { + return Err(self.error( + ast.span, ErrorKind::EmptyClassNotAllowed)); + } + + let expr = Hir::class(hir::Class::Bytes(cls)); + self.push(HirFrame::Expr(expr)); + } + } + Ast::Repetition(ref x) => { + let expr = self.pop().unwrap().unwrap_expr(); + self.push(HirFrame::Expr(self.hir_repetition(x, expr))); + } + Ast::Group(ref x) => { + let expr = self.pop().unwrap().unwrap_expr(); + if let Some(flags) = self.pop().unwrap().unwrap_group() { + self.trans().flags.set(flags); + } + self.push(HirFrame::Expr(self.hir_group(x, expr))); + } + Ast::Concat(_) => { + let mut exprs = vec![]; + while let Some(HirFrame::Expr(expr)) = self.pop() { + if !expr.kind().is_empty() { + exprs.push(expr); + } + } + exprs.reverse(); + self.push(HirFrame::Expr(Hir::concat(exprs))); + } + Ast::Alternation(_) => { + let mut exprs = vec![]; + while let Some(HirFrame::Expr(expr)) = self.pop() { + exprs.push(expr); + } + exprs.reverse(); + self.push(HirFrame::Expr(Hir::alternation(exprs))); + } + } + Ok(()) + } + + fn visit_class_set_item_pre( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + match *ast { + ast::ClassSetItem::Bracketed(_) => { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + } + // We needn't handle the Union case here since the visitor will + // do it for us. + _ => {} + } + Ok(()) + } + + fn visit_class_set_item_post( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + match *ast { + ast::ClassSetItem::Empty(_) => {} + ast::ClassSetItem::Literal(ref x) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.push(hir::ClassUnicodeRange::new(x.c, x.c)); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + let byte = try!(self.class_literal_byte(x)); + cls.push(hir::ClassBytesRange::new(byte, byte)); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Range(ref x) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.push(hir::ClassUnicodeRange::new(x.start.c, x.end.c)); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + let start = try!(self.class_literal_byte(&x.start)); + let end = try!(self.class_literal_byte(&x.end)); + cls.push(hir::ClassBytesRange::new(start, end)); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Ascii(ref x) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + for &(s, e) in ascii_class(&x.kind) { + cls.push(hir::ClassUnicodeRange::new(s, e)); + } + self.unicode_fold_and_negate(x.negated, &mut cls); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + for &(s, e) in ascii_class(&x.kind) { + cls.push(hir::ClassBytesRange::new(s as u8, e as u8)); + } + try!(self.bytes_fold_and_negate( + &x.span, x.negated, &mut cls)); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Unicode(ref x) => { + let xcls = try!(self.hir_unicode_class(x)); + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.union(&xcls); + self.push(HirFrame::ClassUnicode(cls)); + } + ast::ClassSetItem::Perl(ref x) => { + if self.flags().unicode() { + let xcls = self.hir_perl_unicode_class(x); + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.union(&xcls); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let xcls = self.hir_perl_byte_class(x); + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + cls.union(&xcls); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Bracketed(ref ast) => { + if self.flags().unicode() { + let mut cls1 = self.pop().unwrap().unwrap_class_unicode(); + self.unicode_fold_and_negate(ast.negated, &mut cls1); + + let mut cls2 = self.pop().unwrap().unwrap_class_unicode(); + cls2.union(&cls1); + self.push(HirFrame::ClassUnicode(cls2)); + } else { + let mut cls1 = self.pop().unwrap().unwrap_class_bytes(); + try!(self.bytes_fold_and_negate( + &ast.span, ast.negated, &mut cls1)); + + let mut cls2 = self.pop().unwrap().unwrap_class_bytes(); + cls2.union(&cls1); + self.push(HirFrame::ClassBytes(cls2)); + } + } + // This is handled automatically by the visitor. + ast::ClassSetItem::Union(_) => {} + } + Ok(()) + } + + fn visit_class_set_binary_op_pre( + &mut self, + _op: &ast::ClassSetBinaryOp, + ) -> Result<()> { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + Ok(()) + } + + fn visit_class_set_binary_op_in( + &mut self, + _op: &ast::ClassSetBinaryOp, + ) -> Result<()> { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + Ok(()) + } + + fn visit_class_set_binary_op_post( + &mut self, + op: &ast::ClassSetBinaryOp, + ) -> Result<()> { + use ast::ClassSetBinaryOpKind::*; + + if self.flags().unicode() { + let mut rhs = self.pop().unwrap().unwrap_class_unicode(); + let mut lhs = self.pop().unwrap().unwrap_class_unicode(); + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + if self.flags().case_insensitive() { + rhs.case_fold_simple(); + lhs.case_fold_simple(); + } + match op.kind { + Intersection => lhs.intersect(&rhs), + Difference => lhs.difference(&rhs), + SymmetricDifference => lhs.symmetric_difference(&rhs), + } + cls.union(&lhs); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut rhs = self.pop().unwrap().unwrap_class_bytes(); + let mut lhs = self.pop().unwrap().unwrap_class_bytes(); + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + if self.flags().case_insensitive() { + rhs.case_fold_simple(); + lhs.case_fold_simple(); + } + match op.kind { + Intersection => lhs.intersect(&rhs), + Difference => lhs.difference(&rhs), + SymmetricDifference => lhs.symmetric_difference(&rhs), + } + cls.union(&lhs); + self.push(HirFrame::ClassBytes(cls)); + } + Ok(()) + } +} + +/// The internal implementation of a translator. +/// +/// This type is responsible for carrying around the original pattern string, +/// which is not tied to the internal state of a translator. +/// +/// A TranslatorI exists for the time it takes to translate a single Ast. +#[derive(Clone, Debug)] +struct TranslatorI<'t, 'p> { + trans: &'t Translator, + pattern: &'p str, +} + +impl<'t, 'p> TranslatorI<'t, 'p> { + /// Build a new internal translator. + fn new(trans: &'t Translator, pattern: &'p str) -> TranslatorI<'t, 'p> { + TranslatorI { trans: trans, pattern: pattern } + } + + /// Return a reference to the underlying translator. + fn trans(&self) -> &Translator { + &self.trans + } + + /// Push the given frame on to the call stack. + fn push(&self, frame: HirFrame) { + self.trans().stack.borrow_mut().push(frame); + } + + /// Pop the top of the call stack. If the call stack is empty, return None. + fn pop(&self) -> Option { + self.trans().stack.borrow_mut().pop() + } + + /// Create a new error with the given span and error type. + fn error(&self, span: Span, kind: ErrorKind) -> Error { + Error { kind: kind, pattern: self.pattern.to_string(), span: span } + } + + /// Return a copy of the active flags. + fn flags(&self) -> Flags { + self.trans().flags.get() + } + + /// Set the flags of this translator from the flags set in the given AST. + /// Then, return the old flags. + fn set_flags(&self, ast_flags: &ast::Flags) -> Flags { + let old_flags = self.flags(); + let mut new_flags = Flags::from_ast(ast_flags); + new_flags.merge(&old_flags); + self.trans().flags.set(new_flags); + old_flags + } + + fn hir_literal(&self, lit: &ast::Literal) -> Result { + let ch = match try!(self.literal_to_char(lit)) { + byte @ hir::Literal::Byte(_) => return Ok(Hir::literal(byte)), + hir::Literal::Unicode(ch) => ch, + }; + if self.flags().case_insensitive() { + self.hir_from_char_case_insensitive(lit.span, ch) + } else { + self.hir_from_char(lit.span, ch) + } + } + + /// Convert an Ast literal to its scalar representation. + /// + /// When Unicode mode is enabled, then this always succeeds and returns a + /// `char` (Unicode scalar value). + /// + /// When Unicode mode is disabled, then a raw byte is returned. If that + /// byte is not ASCII and invalid UTF-8 is not allowed, then this returns + /// an error. + fn literal_to_char(&self, lit: &ast::Literal) -> Result { + if self.flags().unicode() { + return Ok(hir::Literal::Unicode(lit.c)); + } + let byte = match lit.byte() { + None => return Ok(hir::Literal::Unicode(lit.c)), + Some(byte) => byte, + }; + if byte <= 0x7F { + return Ok(hir::Literal::Unicode(byte as char)); + } + if !self.trans().allow_invalid_utf8 { + return Err(self.error(lit.span, ErrorKind::InvalidUtf8)); + } + Ok(hir::Literal::Byte(byte)) + } + + fn hir_from_char(&self, span: Span, c: char) -> Result { + if !self.flags().unicode() && c.len_utf8() > 1 { + return Err(self.error(span, ErrorKind::UnicodeNotAllowed)); + } + Ok(Hir::literal(hir::Literal::Unicode(c))) + } + + fn hir_from_char_case_insensitive( + &self, + span: Span, + c: char, + ) -> Result { + // If case folding won't do anything, then don't bother trying. + if !unicode::contains_simple_case_mapping(c, c) { + return self.hir_from_char(span, c); + } + if self.flags().unicode() { + let mut cls = hir::ClassUnicode::new(vec![ + hir::ClassUnicodeRange::new(c, c), + ]); + cls.case_fold_simple(); + Ok(Hir::class(hir::Class::Unicode(cls))) + } else { + if c.len_utf8() > 1 { + return Err(self.error(span, ErrorKind::UnicodeNotAllowed)); + } + let mut cls = hir::ClassBytes::new(vec![ + hir::ClassBytesRange::new(c as u8, c as u8), + ]); + cls.case_fold_simple(); + Ok(Hir::class(hir::Class::Bytes(cls))) + } + } + + fn hir_dot(&self, span: Span) -> Result { + let unicode = self.flags().unicode(); + if !unicode && !self.trans().allow_invalid_utf8 { + return Err(self.error(span, ErrorKind::InvalidUtf8)); + } + Ok(if self.flags().dot_matches_new_line() { + Hir::any(!unicode) + } else { + Hir::dot(!unicode) + }) + } + + fn hir_assertion(&self, asst: &ast::Assertion) -> Result { + let unicode = self.flags().unicode(); + let multi_line = self.flags().multi_line(); + Ok(match asst.kind { + ast::AssertionKind::StartLine => { + Hir::anchor(if multi_line { + hir::Anchor::StartLine + } else { + hir::Anchor::StartText + }) + } + ast::AssertionKind::EndLine => { + Hir::anchor(if multi_line { + hir::Anchor::EndLine + } else { + hir::Anchor::EndText + }) + } + ast::AssertionKind::StartText => { + Hir::anchor(hir::Anchor::StartText) + } + ast::AssertionKind::EndText => { + Hir::anchor(hir::Anchor::EndText) + } + ast::AssertionKind::WordBoundary => { + Hir::word_boundary(if unicode { + hir::WordBoundary::Unicode + } else { + hir::WordBoundary::Ascii + }) + } + ast::AssertionKind::NotWordBoundary => { + Hir::word_boundary(if unicode { + hir::WordBoundary::UnicodeNegate + } else { + // It is possible for negated ASCII word boundaries to + // match at invalid UTF-8 boundaries, even when searching + // valid UTF-8. + // + // TODO(ag): Enable this error when regex goes to 1.0. + // Otherwise, it is too steep of a breaking change. + // if !self.trans().allow_invalid_utf8 { + // return Err(self.error( + // asst.span, ErrorKind::InvalidUtf8)); + // } + hir::WordBoundary::AsciiNegate + }) + } + }) + } + + fn hir_group(&self, group: &ast::Group, expr: Hir) -> Hir { + let kind = match group.kind { + ast::GroupKind::CaptureIndex(idx) => { + hir::GroupKind::CaptureIndex(idx) + } + ast::GroupKind::CaptureName(ref capname) => { + hir::GroupKind::CaptureName { + name: capname.name.clone(), + index: capname.index, + } + } + ast::GroupKind::NonCapturing(_) => hir::GroupKind::NonCapturing, + }; + Hir::group(hir::Group { + kind: kind, + hir: Box::new(expr), + }) + } + + fn hir_repetition(&self, rep: &ast::Repetition, expr: Hir) -> Hir { + let kind = match rep.op.kind { + ast::RepetitionKind::ZeroOrOne => hir::RepetitionKind::ZeroOrOne, + ast::RepetitionKind::ZeroOrMore => hir::RepetitionKind::ZeroOrMore, + ast::RepetitionKind::OneOrMore => hir::RepetitionKind::OneOrMore, + ast::RepetitionKind::Range(ast::RepetitionRange::Exactly(m)) => { + hir::RepetitionKind::Range(hir::RepetitionRange::Exactly(m)) + } + ast::RepetitionKind::Range(ast::RepetitionRange::AtLeast(m)) => { + hir::RepetitionKind::Range(hir::RepetitionRange::AtLeast(m)) + } + ast::RepetitionKind::Range(ast::RepetitionRange::Bounded(m,n)) => { + hir::RepetitionKind::Range(hir::RepetitionRange::Bounded(m, n)) + } + }; + let greedy = + if self.flags().swap_greed() { + !rep.greedy + } else { + rep.greedy + }; + Hir::repetition(hir::Repetition { + kind: kind, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_unicode_class( + &self, + ast_class: &ast::ClassUnicode, + ) -> Result { + use ast::ClassUnicodeKind::*; + + if !self.flags().unicode() { + return Err(self.error( + ast_class.span, + ErrorKind::UnicodeNotAllowed, + )); + } + let query = match ast_class.kind { + OneLetter(name) => ClassQuery::OneLetter(name), + Named(ref name) => ClassQuery::Binary(name), + NamedValue { ref name, ref value, .. } => { + ClassQuery::ByValue { + property_name: name, + property_value: value, + } + } + }; + match unicode::class(query) { + Ok(mut class) => { + self.unicode_fold_and_negate(ast_class.negated, &mut class); + Ok(class) + } + Err(unicode::Error::PropertyNotFound) => { + Err(self.error( + ast_class.span, + ErrorKind::UnicodePropertyNotFound, + )) + } + Err(unicode::Error::PropertyValueNotFound) => { + Err(self.error( + ast_class.span, + ErrorKind::UnicodePropertyValueNotFound, + )) + } + } + } + + fn hir_perl_unicode_class( + &self, + ast_class: &ast::ClassPerl, + ) -> hir::ClassUnicode { + use ast::ClassPerlKind::*; + use unicode_tables::perl_word::PERL_WORD; + + assert!(self.flags().unicode()); + let mut class = match ast_class.kind { + Digit => { + let query = ClassQuery::Binary("Decimal_Number"); + unicode::class(query).unwrap() + } + Space => { + let query = ClassQuery::Binary("Whitespace"); + unicode::class(query).unwrap() + } + Word => unicode::hir_class(PERL_WORD), + }; + // We needn't apply case folding here because the Perl Unicode classes + // are already closed under Unicode simple case folding. + if ast_class.negated { + class.negate(); + } + class + } + + fn hir_perl_byte_class( + &self, + ast_class: &ast::ClassPerl, + ) -> hir::ClassBytes { + use ast::ClassPerlKind::*; + + assert!(!self.flags().unicode()); + let mut class = match ast_class.kind { + Digit => hir_ascii_class_bytes(&ast::ClassAsciiKind::Digit), + Space => hir_ascii_class_bytes(&ast::ClassAsciiKind::Space), + Word => hir_ascii_class_bytes(&ast::ClassAsciiKind::Word), + }; + // We needn't apply case folding here because the Perl ASCII classes + // are already closed (under ASCII case folding). + if ast_class.negated { + class.negate(); + } + class + } + + fn unicode_fold_and_negate( + &self, + negated: bool, + class: &mut hir::ClassUnicode, + ) { + // Note that we must apply case folding before negation! + // Consider `(?i)[^x]`. If we applied negation field, then + // the result would be the character class that matched any + // Unicode scalar value. + if self.flags().case_insensitive() { + class.case_fold_simple(); + } + if negated { + class.negate(); + } + } + + fn bytes_fold_and_negate( + &self, + span: &Span, + negated: bool, + class: &mut hir::ClassBytes, + ) -> Result<()> { + // Note that we must apply case folding before negation! + // Consider `(?i)[^x]`. If we applied negation field, then + // the result would be the character class that matched any + // Unicode scalar value. + if self.flags().case_insensitive() { + class.case_fold_simple(); + } + if negated { + class.negate(); + } + if !self.trans().allow_invalid_utf8 && !class.is_all_ascii() { + return Err(self.error(span.clone(), ErrorKind::InvalidUtf8)); + } + Ok(()) + } + + /// Return a scalar byte value suitable for use as a literal in a byte + /// character class. + fn class_literal_byte(&self, ast: &ast::Literal) -> Result { + match try!(self.literal_to_char(ast)) { + hir::Literal::Byte(byte) => Ok(byte), + hir::Literal::Unicode(ch) => { + if ch <= 0x7F as char { + Ok(ch as u8) + } else { + // We can't feasibly support Unicode in + // byte oriented classes. Byte classes don't + // do Unicode case folding. + Err(self.error(ast.span, ErrorKind::UnicodeNotAllowed)) + } + } + } + } +} + +/// A translator's representation of a regular expression's flags at any given +/// moment in time. +/// +/// Each flag can be in one of three states: absent, present but disabled or +/// present but enabled. +#[derive(Clone, Copy, Debug, Default)] +struct Flags { + case_insensitive: Option, + multi_line: Option, + dot_matches_new_line: Option, + swap_greed: Option, + unicode: Option, + // Note that `ignore_whitespace` is omitted here because it is handled + // entirely in the parser. +} + +impl Flags { + fn from_ast(ast: &ast::Flags) -> Flags { + let mut flags = Flags::default(); + let mut enable = true; + for item in &ast.items { + match item.kind { + ast::FlagsItemKind::Negation => { + enable = false; + } + ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive) => { + flags.case_insensitive = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::MultiLine) => { + flags.multi_line = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::DotMatchesNewLine) => { + flags.dot_matches_new_line = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::SwapGreed) => { + flags.swap_greed = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::Unicode) => { + flags.unicode = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::IgnoreWhitespace) => {} + } + } + flags + } + + fn merge(&mut self, previous: &Flags) { + if self.case_insensitive.is_none() { + self.case_insensitive = previous.case_insensitive; + } + if self.multi_line.is_none() { + self.multi_line = previous.multi_line; + } + if self.dot_matches_new_line.is_none() { + self.dot_matches_new_line = previous.dot_matches_new_line; + } + if self.swap_greed.is_none() { + self.swap_greed = previous.swap_greed; + } + if self.unicode.is_none() { + self.unicode = previous.unicode; + } + } + + fn case_insensitive(&self) -> bool { + self.case_insensitive.unwrap_or(false) + } + + fn multi_line(&self) -> bool { + self.multi_line.unwrap_or(false) + } + + fn dot_matches_new_line(&self) -> bool { + self.dot_matches_new_line.unwrap_or(false) + } + + fn swap_greed(&self) -> bool { + self.swap_greed.unwrap_or(false) + } + + fn unicode(&self) -> bool { + self.unicode.unwrap_or(true) + } +} + +fn hir_ascii_class_bytes(kind: &ast::ClassAsciiKind) -> hir::ClassBytes { + let ranges: Vec<_> = ascii_class(kind).iter().cloned().map(|(s, e)| { + hir::ClassBytesRange::new(s as u8, e as u8) + }).collect(); + hir::ClassBytes::new(ranges) +} + +fn ascii_class(kind: &ast::ClassAsciiKind) -> &'static [(char, char)] { + use ast::ClassAsciiKind::*; + + // TODO: Get rid of these consts, which appear necessary for older + // versions of Rust. + type T = &'static [(char, char)]; + match *kind { + Alnum => { + const X: T = &[('0', '9'), ('A', 'Z'), ('a', 'z')]; + X + } + Alpha => { + const X: T = &[('A', 'Z'), ('a', 'z')]; + X + } + Ascii => { + const X: T = &[('\x00', '\x7F')]; + X + } + Blank => { + const X: T = &[(' ', '\t')]; + X + } + Cntrl => { + const X: T = &[('\x00', '\x1F'), ('\x7F', '\x7F')]; + X + } + Digit => { + const X: T = &[('0', '9')]; + X + } + Graph => { + const X: T = &[('!', '~')]; + X + } + Lower => { + const X: T = &[('a', 'z')]; + X + } + Print => { + const X: T = &[(' ', '~')]; + X + } + Punct => { + const X: T = &[('!', '/'), (':', '@'), ('[', '`'), ('{', '~')]; + X + } + Space => { + const X: T = &[ + ('\t', '\t'), ('\n', '\n'), ('\x0B', '\x0B'), ('\x0C', '\x0C'), + ('\r', '\r'), (' ', ' '), + ]; + X + } + Upper => { + const X: T = &[('A', 'Z')]; + X + } + Word => { + const X: T = &[('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z')]; + X + } + Xdigit => { + const X: T = &[('0', '9'), ('A', 'F'), ('a', 'f')]; + X + } + } +} + +#[cfg(test)] +mod tests { + use ast::{self, Ast, Position, Span}; + use ast::parse::ParserBuilder; + use hir::{self, Hir, HirKind}; + use unicode::{self, ClassQuery}; + + use super::{TranslatorBuilder, ascii_class}; + + // We create these errors to compare with real hir::Errors in the tests. + // We define equality between TestError and hir::Error to disregard the + // pattern string in hir::Error, which is annoying to provide in tests. + #[derive(Clone, Debug)] + struct TestError { + span: Span, + kind: hir::ErrorKind, + } + + impl PartialEq for TestError { + fn eq(&self, other: &hir::Error) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + impl PartialEq for hir::Error { + fn eq(&self, other: &TestError) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + fn parse(pattern: &str) -> Ast { + ParserBuilder::new().octal(true).build().parse(pattern).unwrap() + } + + fn t(pattern: &str) -> Hir { + TranslatorBuilder::new() + .allow_invalid_utf8(false) + .build() + .translate(pattern, &parse(pattern)) + .unwrap() + } + + fn t_err(pattern: &str) -> hir::Error { + TranslatorBuilder::new() + .allow_invalid_utf8(false) + .build() + .translate(pattern, &parse(pattern)) + .unwrap_err() + } + + fn t_bytes(pattern: &str) -> Hir { + TranslatorBuilder::new() + .allow_invalid_utf8(true) + .build() + .translate(pattern, &parse(pattern)) + .unwrap() + } + + fn hir_lit(s: &str) -> Hir { + match s.len() { + 0 => Hir::empty(), + _ => { + let lits = s + .chars() + .map(hir::Literal::Unicode) + .map(Hir::literal) + .collect(); + Hir::concat(lits) + } + } + } + + fn hir_blit(s: &[u8]) -> Hir { + match s.len() { + 0 => Hir::empty(), + 1 => Hir::literal(hir::Literal::Byte(s[0])), + _ => { + let lits = s + .iter() + .cloned() + .map(hir::Literal::Byte) + .map(Hir::literal) + .collect(); + Hir::concat(lits) + } + } + } + + fn hir_group(i: u32, expr: Hir) -> Hir { + Hir::group(hir::Group { + kind: hir::GroupKind::CaptureIndex(i), + hir: Box::new(expr), + }) + } + + fn hir_group_name(i: u32, name: &str, expr: Hir) -> Hir { + Hir::group(hir::Group { + kind: hir::GroupKind::CaptureName { + name: name.to_string(), + index: i, + }, + hir: Box::new(expr), + }) + } + + fn hir_group_nocap(expr: Hir) -> Hir { + Hir::group(hir::Group { + kind: hir::GroupKind::NonCapturing, + hir: Box::new(expr), + }) + } + + fn hir_quest(greedy: bool, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrOne, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_star(greedy: bool, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_plus(greedy: bool, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::OneOrMore, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_range(greedy: bool, range: hir::RepetitionRange, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::Range(range), + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_alt(alts: Vec) -> Hir { + Hir::alternation(alts) + } + + fn hir_cat(exprs: Vec) -> Hir { + Hir::concat(exprs) + } + + fn hir_uclass_query(query: ClassQuery) -> Hir { + Hir::class(hir::Class::Unicode(unicode::class(query).unwrap())) + } + + fn hir_uclass_perl_word() -> Hir { + use unicode_tables::perl_word::PERL_WORD; + Hir::class(hir::Class::Unicode(unicode::hir_class(PERL_WORD))) + } + + fn hir_uclass(ranges: &[(char, char)]) -> Hir { + let ranges: Vec = ranges + .iter() + .map(|&(s, e)| hir::ClassUnicodeRange::new(s, e)) + .collect(); + Hir::class(hir::Class::Unicode(hir::ClassUnicode::new(ranges))) + } + + fn hir_bclass(ranges: &[(u8, u8)]) -> Hir { + let ranges: Vec = ranges + .iter() + .map(|&(s, e)| hir::ClassBytesRange::new(s, e)) + .collect(); + Hir::class(hir::Class::Bytes(hir::ClassBytes::new(ranges))) + } + + fn hir_bclass_from_char(ranges: &[(char, char)]) -> Hir { + let ranges: Vec = ranges + .iter() + .map(|&(s, e)| { + assert!(s as u32 <= 0x7F); + assert!(e as u32 <= 0x7F); + hir::ClassBytesRange::new(s as u8, e as u8) + }) + .collect(); + Hir::class(hir::Class::Bytes(hir::ClassBytes::new(ranges))) + } + + fn hir_case_fold(expr: Hir) -> Hir { + match expr.into_kind() { + HirKind::Class(mut cls) => { + cls.case_fold_simple(); + Hir::class(cls) + } + _ => panic!("cannot case fold non-class Hir expr"), + } + } + + fn hir_negate(expr: Hir) -> Hir { + match expr.into_kind() { + HirKind::Class(mut cls) => { + cls.negate(); + Hir::class(cls) + } + _ => panic!("cannot negate non-class Hir expr"), + } + } + + fn hir_union(expr1: Hir, expr2: Hir) -> Hir { + use hir::Class::{Bytes, Unicode}; + + match (expr1.into_kind(), expr2.into_kind()) { + ( + HirKind::Class(Unicode(mut c1)), + HirKind::Class(Unicode(c2)), + ) => { + c1.union(&c2); + Hir::class(hir::Class::Unicode(c1)) + } + ( + HirKind::Class(Bytes(mut c1)), + HirKind::Class(Bytes(c2)), + ) => { + c1.union(&c2); + Hir::class(hir::Class::Bytes(c1)) + } + _ => panic!("cannot union non-class Hir exprs"), + } + } + + fn hir_difference(expr1: Hir, expr2: Hir) -> Hir { + use hir::Class::{Bytes, Unicode}; + + match (expr1.into_kind(), expr2.into_kind()) { + ( + HirKind::Class(Unicode(mut c1)), + HirKind::Class(Unicode(c2)), + ) => { + c1.difference(&c2); + Hir::class(hir::Class::Unicode(c1)) + } + ( + HirKind::Class(Bytes(mut c1)), + HirKind::Class(Bytes(c2)), + ) => { + c1.difference(&c2); + Hir::class(hir::Class::Bytes(c1)) + } + _ => panic!("cannot difference non-class Hir exprs"), + } + } + + fn hir_anchor(anchor: hir::Anchor) -> Hir { + Hir::anchor(anchor) + } + + fn hir_word(wb: hir::WordBoundary) -> Hir { + Hir::word_boundary(wb) + } + + #[test] + fn empty() { + assert_eq!(t(""), Hir::empty()); + assert_eq!(t("(?i)"), Hir::empty()); + assert_eq!(t("()"), hir_group(1, Hir::empty())); + assert_eq!(t("(?:)"), hir_group_nocap(Hir::empty())); + assert_eq!(t("(?P)"), hir_group_name(1, "wat", Hir::empty())); + assert_eq!(t("|"), hir_alt(vec![Hir::empty(), Hir::empty()])); + assert_eq!(t("()|()"), hir_alt(vec![ + hir_group(1, Hir::empty()), + hir_group(2, Hir::empty()), + ])); + assert_eq!(t("(|b)"), hir_group(1, hir_alt(vec![ + Hir::empty(), + hir_lit("b"), + ]))); + assert_eq!(t("(a|)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + Hir::empty(), + ]))); + assert_eq!(t("(a||c)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + Hir::empty(), + hir_lit("c"), + ]))); + assert_eq!(t("(||)"), hir_group(1, hir_alt(vec![ + Hir::empty(), + Hir::empty(), + Hir::empty(), + ]))); + } + + #[test] + fn literal() { + assert_eq!(t("a"), hir_lit("a")); + assert_eq!(t("(?-u)a"), hir_lit("a")); + assert_eq!(t("☃"), hir_lit("☃")); + assert_eq!(t("abcd"), hir_lit("abcd")); + + assert_eq!(t_bytes("(?-u)a"), hir_lit("a")); + assert_eq!(t_bytes("(?-u)\x61"), hir_lit("a")); + assert_eq!(t_bytes(r"(?-u)\x61"), hir_lit("a")); + assert_eq!(t_bytes(r"(?-u)\xFF"), hir_blit(b"\xFF")); + + assert_eq!(t_err("(?-u)☃"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(8, 1, 7)), + }); + assert_eq!(t_err(r"(?-u)\xFF"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(5, 1, 6), Position::new(9, 1, 10)), + }); + } + + #[test] + fn literal_case_insensitive() { + assert_eq!(t("(?i)a"), hir_uclass(&[ + ('A', 'A'), ('a', 'a'), + ])); + assert_eq!(t("(?i:a)"), hir_group_nocap(hir_uclass(&[ + ('A', 'A'), ('a', 'a')], + ))); + assert_eq!(t("a(?i)a(?-i)a"), hir_cat(vec![ + hir_lit("a"), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_lit("a"), + ])); + assert_eq!(t("(?i)ab@c"), hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_uclass(&[('B', 'B'), ('b', 'b')]), + hir_lit("@"), + hir_uclass(&[('C', 'C'), ('c', 'c')]), + ])); + assert_eq!(t("(?i)β"), hir_uclass(&[ + ('Β', 'Β'), ('β', 'β'), ('ϐ', 'ϐ'), + ])); + + assert_eq!(t("(?i-u)a"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t("(?-u)a(?i)a(?-i)a"), hir_cat(vec![ + hir_lit("a"), + hir_bclass(&[(b'A', b'A'), (b'a', b'a')]), + hir_lit("a"), + ])); + assert_eq!(t("(?i-u)ab@c"), hir_cat(vec![ + hir_bclass(&[(b'A', b'A'), (b'a', b'a')]), + hir_bclass(&[(b'B', b'B'), (b'b', b'b')]), + hir_lit("@"), + hir_bclass(&[(b'C', b'C'), (b'c', b'c')]), + ])); + + assert_eq!(t_bytes("(?i-u)a"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t_bytes("(?i-u)\x61"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t_bytes(r"(?i-u)\x61"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t_bytes(r"(?i-u)\xFF"), hir_blit(b"\xFF")); + + assert_eq!(t_err("(?i-u)β"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new( + Position::new(6, 1, 7), + Position::new(8, 1, 8), + ), + }); + } + + #[test] + fn dot() { + assert_eq!(t("."), hir_uclass(&[ + ('\0', '\t'), + ('\x0B', '\u{10FFFF}'), + ])); + assert_eq!(t("(?s)."), hir_uclass(&[ + ('\0', '\u{10FFFF}'), + ])); + assert_eq!(t_bytes("(?-u)."), hir_bclass(&[ + (b'\0', b'\t'), + (b'\x0B', b'\xFF'), + ])); + assert_eq!(t_bytes("(?s-u)."), hir_bclass(&[ + (b'\0', b'\xFF'), + ])); + + // If invalid UTF-8 isn't allowed, then non-Unicode `.` isn't allowed. + assert_eq!(t_err("(?-u)."), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(5, 1, 6), Position::new(6, 1, 7)), + }); + assert_eq!(t_err("(?s-u)."), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(6, 1, 7), Position::new(7, 1, 8)), + }); + } + + #[test] + fn assertions() { + assert_eq!(t("^"), hir_anchor(hir::Anchor::StartText)); + assert_eq!(t("$"), hir_anchor(hir::Anchor::EndText)); + assert_eq!(t(r"\A"), hir_anchor(hir::Anchor::StartText)); + assert_eq!(t(r"\z"), hir_anchor(hir::Anchor::EndText)); + assert_eq!(t("(?m)^"), hir_anchor(hir::Anchor::StartLine)); + assert_eq!(t("(?m)$"), hir_anchor(hir::Anchor::EndLine)); + assert_eq!(t(r"(?m)\A"), hir_anchor(hir::Anchor::StartText)); + assert_eq!(t(r"(?m)\z"), hir_anchor(hir::Anchor::EndText)); + + assert_eq!(t(r"\b"), hir_word(hir::WordBoundary::Unicode)); + assert_eq!(t(r"\B"), hir_word(hir::WordBoundary::UnicodeNegate)); + assert_eq!(t(r"(?-u)\b"), hir_word(hir::WordBoundary::Ascii)); + assert_eq!( + t_bytes(r"(?-u)\B"), + hir_word(hir::WordBoundary::AsciiNegate)); + + // TODO(ag): Enable this tests when regex goes to 1.0. + // assert_eq!(t_err(r"(?-u)\B"), TestError { + // kind: hir::ErrorKind::InvalidUtf8, + // span: Span::new(Position::new(5, 1, 6), Position::new(7, 1, 8)), + // }); + } + + #[test] + fn group() { + assert_eq!(t("(a)"), hir_group(1, hir_lit("a"))); + assert_eq!(t("(a)(b)"), hir_cat(vec![ + hir_group(1, hir_lit("a")), + hir_group(2, hir_lit("b")), + ])); + assert_eq!(t("(a)|(b)"), hir_alt(vec![ + hir_group(1, hir_lit("a")), + hir_group(2, hir_lit("b")), + ])); + assert_eq!(t("(?P)"), hir_group_name(1, "foo", Hir::empty())); + assert_eq!(t("(?Pa)"), hir_group_name(1, "foo", hir_lit("a"))); + assert_eq!(t("(?Pa)(?Pb)"), hir_cat(vec![ + hir_group_name(1, "foo", hir_lit("a")), + hir_group_name(2, "bar", hir_lit("b")), + ])); + assert_eq!(t("(?:)"), hir_group_nocap(Hir::empty())); + assert_eq!(t("(?:a)"), hir_group_nocap(hir_lit("a"))); + assert_eq!(t("(?:a)(b)"), hir_cat(vec![ + hir_group_nocap(hir_lit("a")), + hir_group(1, hir_lit("b")), + ])); + assert_eq!(t("(a)(?:b)(c)"), hir_cat(vec![ + hir_group(1, hir_lit("a")), + hir_group_nocap(hir_lit("b")), + hir_group(2, hir_lit("c")), + ])); + assert_eq!(t("(a)(?Pb)(c)"), hir_cat(vec![ + hir_group(1, hir_lit("a")), + hir_group_name(2, "foo", hir_lit("b")), + hir_group(3, hir_lit("c")), + ])); + } + + #[test] + fn flags() { + assert_eq!(t("(?i:a)a"), hir_cat(vec![ + hir_group_nocap(hir_uclass(&[('A', 'A'), ('a', 'a')])), + hir_lit("a"), + ])); + assert_eq!(t("(?i-u:a)β"), hir_cat(vec![ + hir_group_nocap(hir_bclass(&[(b'A', b'A'), (b'a', b'a')])), + hir_lit("β"), + ])); + assert_eq!(t("(?i)(?-i:a)a"), hir_cat(vec![ + hir_group_nocap(hir_lit("a")), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + ])); + assert_eq!(t("(?im)a^"), hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_anchor(hir::Anchor::StartLine), + ])); + assert_eq!(t("(?im)a^(?i-m)a^"), hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_anchor(hir::Anchor::StartLine), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_anchor(hir::Anchor::StartText), + ])); + assert_eq!(t("(?U)a*a*?(?-U)a*a*?"), hir_cat(vec![ + hir_star(false, hir_lit("a")), + hir_star(true, hir_lit("a")), + hir_star(true, hir_lit("a")), + hir_star(false, hir_lit("a")), + ])); + assert_eq!(t("(?:a(?i)a)a"), hir_cat(vec![ + hir_group_nocap(hir_cat(vec![ + hir_lit("a"), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + ])), + hir_lit("a"), + ])); + assert_eq!(t("(?i)(?:a(?-i)a)a"), hir_cat(vec![ + hir_group_nocap(hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_lit("a"), + ])), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + ])); + } + + #[test] + fn escape() { + assert_eq!( + t(r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#"), + hir_lit(r"\.+*?()|[]{}^$#"), + ); + } + + #[test] + fn repetition() { + assert_eq!(t("a?"), hir_quest(true, hir_lit("a"))); + assert_eq!(t("a*"), hir_star(true, hir_lit("a"))); + assert_eq!(t("a+"), hir_plus(true, hir_lit("a"))); + assert_eq!(t("a??"), hir_quest(false, hir_lit("a"))); + assert_eq!(t("a*?"), hir_star(false, hir_lit("a"))); + assert_eq!(t("a+?"), hir_plus(false, hir_lit("a"))); + + assert_eq!( + t("a{1}"), + hir_range( + true, + hir::RepetitionRange::Exactly(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,}"), + hir_range( + true, + hir::RepetitionRange::AtLeast(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,2}"), + hir_range( + true, + hir::RepetitionRange::Bounded(1, 2), + hir_lit("a"), + )); + assert_eq!( + t("a{1}?"), + hir_range( + false, + hir::RepetitionRange::Exactly(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,}?"), + hir_range( + false, + hir::RepetitionRange::AtLeast(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,2}?"), + hir_range( + false, + hir::RepetitionRange::Bounded(1, 2), + hir_lit("a"), + )); + + assert_eq!(t("ab?"), hir_cat(vec![ + hir_lit("a"), + hir_quest(true, hir_lit("b")), + ])); + assert_eq!(t("(ab)?"), hir_quest(true, hir_group(1, hir_cat(vec![ + hir_lit("a"), + hir_lit("b"), + ])))); + assert_eq!(t("a|b?"), hir_alt(vec![ + hir_lit("a"), + hir_quest(true, hir_lit("b")), + ])); + } + + #[test] + fn cat_alt() { + assert_eq!(t("(ab)"), hir_group(1, hir_cat(vec![ + hir_lit("a"), + hir_lit("b"), + ]))); + assert_eq!(t("a|b"), hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + ])); + assert_eq!(t("a|b|c"), hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + hir_lit("c"), + ])); + assert_eq!(t("ab|bc|cd"), hir_alt(vec![ + hir_lit("ab"), + hir_lit("bc"), + hir_lit("cd"), + ])); + assert_eq!(t("(a|b)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + ]))); + assert_eq!(t("(a|b|c)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + hir_lit("c"), + ]))); + assert_eq!(t("(ab|bc|cd)"), hir_group(1, hir_alt(vec![ + hir_lit("ab"), + hir_lit("bc"), + hir_lit("cd"), + ]))); + assert_eq!(t("(ab|(bc|(cd)))"), hir_group(1, hir_alt(vec![ + hir_lit("ab"), + hir_group(2, hir_alt(vec![ + hir_lit("bc"), + hir_group(3, hir_lit("cd")), + ])), + ]))); + } + + #[test] + fn class_ascii() { + assert_eq!( + t("[[:alnum:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Alnum))); + assert_eq!( + t("[[:alpha:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Alpha))); + assert_eq!( + t("[[:ascii:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Ascii))); + assert_eq!( + t("[[:blank:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Blank))); + assert_eq!( + t("[[:cntrl:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Cntrl))); + assert_eq!( + t("[[:digit:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Digit))); + assert_eq!( + t("[[:graph:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Graph))); + assert_eq!( + t("[[:lower:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Lower))); + assert_eq!( + t("[[:print:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Print))); + assert_eq!( + t("[[:punct:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Punct))); + assert_eq!( + t("[[:space:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Space))); + assert_eq!( + t("[[:upper:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Upper))); + assert_eq!( + t("[[:word:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Word))); + assert_eq!( + t("[[:xdigit:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Xdigit))); + + assert_eq!( + t("[[:^lower:]]"), + hir_negate(hir_uclass(ascii_class(&ast::ClassAsciiKind::Lower)))); + assert_eq!( + t("(?i)[[:lower:]]"), + hir_uclass(&[ + ('A', 'Z'), ('a', 'z'), + ('\u{17F}', '\u{17F}'), + ('\u{212A}', '\u{212A}'), + ])); + + assert_eq!( + t("(?-u)[[:lower:]]"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Lower))); + assert_eq!( + t("(?i-u)[[:lower:]]"), + hir_case_fold(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Lower)))); + + assert_eq!(t_err("(?-u)[[:^lower:]]"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(6, 1, 7), Position::new(16, 1, 17)), + }); + assert_eq!(t_err("(?i-u)[[:^lower:]]"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(7, 1, 8), Position::new(17, 1, 18)), + }); + } + + #[test] + fn class_perl() { + // Unicode + assert_eq!( + t(r"\d"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"\s"), + hir_uclass_query(ClassQuery::Binary("space"))); + assert_eq!( + t(r"\w"), + hir_uclass_perl_word()); + assert_eq!( + t(r"(?i)\d"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"(?i)\s"), + hir_uclass_query(ClassQuery::Binary("space"))); + assert_eq!( + t(r"(?i)\w"), + hir_uclass_perl_word()); + + // Unicode, negated + assert_eq!( + t(r"\D"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"\S"), + hir_negate(hir_uclass_query(ClassQuery::Binary("space")))); + assert_eq!( + t(r"\W"), + hir_negate(hir_uclass_perl_word())); + assert_eq!( + t(r"(?i)\D"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"(?i)\S"), + hir_negate(hir_uclass_query(ClassQuery::Binary("space")))); + assert_eq!( + t(r"(?i)\W"), + hir_negate(hir_uclass_perl_word())); + + // ASCII only + assert_eq!( + t(r"(?-u)\d"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Digit))); + assert_eq!( + t(r"(?-u)\s"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Space))); + assert_eq!( + t(r"(?-u)\w"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Word))); + assert_eq!( + t(r"(?i-u)\d"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Digit))); + assert_eq!( + t(r"(?i-u)\s"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Space))); + assert_eq!( + t(r"(?i-u)\w"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Word))); + + // ASCII only, negated + assert_eq!( + t(r"(?-u)\D"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t(r"(?-u)\S"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Space)))); + assert_eq!( + t(r"(?-u)\W"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Word)))); + assert_eq!( + t(r"(?i-u)\D"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t(r"(?i-u)\S"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Space)))); + assert_eq!( + t(r"(?i-u)\W"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Word)))); + } + + #[test] + fn class_unicode() { + assert_eq!( + t(r"\pZ"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\pz"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{Separator}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{se PaRa ToR}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{gc:Separator}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{gc=Separator}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{Other}"), + hir_uclass_query(ClassQuery::Binary("Other"))); + assert_eq!( + t(r"\pC"), + hir_uclass_query(ClassQuery::Binary("Other"))); + + assert_eq!( + t(r"\PZ"), + hir_negate(hir_uclass_query(ClassQuery::Binary("Z")))); + assert_eq!( + t(r"\P{separator}"), + hir_negate(hir_uclass_query(ClassQuery::Binary("Z")))); + assert_eq!( + t(r"\P{gc!=separator}"), + hir_negate(hir_uclass_query(ClassQuery::Binary("Z")))); + + assert_eq!( + t(r"\p{Greek}"), + hir_uclass_query(ClassQuery::Binary("Greek"))); + assert_eq!( + t(r"(?i)\p{Greek}"), + hir_case_fold(hir_uclass_query(ClassQuery::Binary("Greek")))); + assert_eq!( + t(r"(?i)\P{Greek}"), + hir_negate(hir_case_fold(hir_uclass_query( + ClassQuery::Binary("Greek"))))); + + assert_eq!( + t(r"\p{any}"), + hir_uclass_query(ClassQuery::Binary("Any"))); + assert_eq!( + t(r"\p{assigned}"), + hir_uclass_query(ClassQuery::Binary("Assigned"))); + assert_eq!( + t(r"\p{ascii}"), + hir_uclass_query(ClassQuery::Binary("ASCII"))); + assert_eq!( + t(r"\p{gc:any}"), + hir_uclass_query(ClassQuery::Binary("Any"))); + assert_eq!( + t(r"\p{gc:assigned}"), + hir_uclass_query(ClassQuery::Binary("Assigned"))); + assert_eq!( + t(r"\p{gc:ascii}"), + hir_uclass_query(ClassQuery::Binary("ASCII"))); + + assert_eq!(t_err(r"(?-u)\pZ"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(8, 1, 9)), + }); + assert_eq!(t_err(r"(?-u)\p{Separator}"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(18, 1, 19)), + }); + assert_eq!(t_err(r"\pE"), TestError { + kind: hir::ErrorKind::UnicodePropertyNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(3, 1, 4)), + }); + assert_eq!(t_err(r"\p{Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(7, 1, 8)), + }); + assert_eq!(t_err(r"\p{gc:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(10, 1, 11)), + }); + assert_eq!(t_err(r"\p{sc:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(10, 1, 11)), + }); + assert_eq!(t_err(r"\p{scx:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(11, 1, 12)), + }); + assert_eq!(t_err(r"\p{age:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(11, 1, 12)), + }); + } + + #[test] + fn class_bracketed() { + assert_eq!(t("[a]"), hir_uclass(&[('a', 'a')])); + assert_eq!(t("[^[a]]"), hir_negate(hir_uclass(&[('a', 'a')]))); + assert_eq!(t("[a-z]"), hir_uclass(&[('a', 'z')])); + assert_eq!(t("[a-fd-h]"), hir_uclass(&[('a', 'h')])); + assert_eq!(t("[a-fg-m]"), hir_uclass(&[('a', 'm')])); + assert_eq!(t(r"[\x00]"), hir_uclass(&[('\0', '\0')])); + assert_eq!(t(r"[\n]"), hir_uclass(&[('\n', '\n')])); + assert_eq!(t("[\n]"), hir_uclass(&[('\n', '\n')])); + assert_eq!( + t(r"[\d]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"[\pZ]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"[\p{separator}]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"[^\D]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"[^\PZ]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"[^\P{separator}]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"(?i)[^\D]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"(?i)[^\P{greek}]"), + hir_case_fold(hir_uclass_query(ClassQuery::Binary("greek")))); + + assert_eq!(t("(?-u)[a]"), hir_bclass(&[(b'a', b'a')])); + assert_eq!(t(r"(?-u)[\x00]"), hir_bclass(&[(b'\0', b'\0')])); + assert_eq!(t_bytes(r"(?-u)[\xFF]"), hir_bclass(&[(b'\xFF', b'\xFF')])); + + assert_eq!(t("(?i)[a]"), hir_uclass(&[('A', 'A'), ('a', 'a')])); + assert_eq!(t("(?i)[k]"), hir_uclass(&[ + ('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}'), + ])); + assert_eq!(t("(?i)[β]"), hir_uclass(&[ + ('Β', 'Β'), ('β', 'β'), ('ϐ', 'ϐ'), + ])); + assert_eq!(t("(?i-u)[k]"), hir_bclass(&[ + (b'K', b'K'), (b'k', b'k'), + ])); + + assert_eq!(t("[^a]"), hir_negate(hir_uclass(&[('a', 'a')]))); + assert_eq!(t(r"[^\x00]"), hir_negate(hir_uclass(&[('\0', '\0')]))); + assert_eq!( + t_bytes("(?-u)[^a]"), + hir_negate(hir_bclass(&[(b'a', b'a')]))); + assert_eq!( + t(r"[^\d]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"[^\pZ]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"[^\p{separator}]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"(?i)[^\p{greek}]"), + hir_negate(hir_case_fold(hir_uclass_query( + ClassQuery::Binary("greek"))))); + assert_eq!( + t(r"(?i)[\P{greek}]"), + hir_negate(hir_case_fold(hir_uclass_query( + ClassQuery::Binary("greek"))))); + + // Test some weird cases. + assert_eq!(t(r"[\[]"), hir_uclass(&[('[', '[')])); + + assert_eq!(t(r"[&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\&\&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\x00-&]"), hir_uclass(&[('\0', '&')])); + assert_eq!(t(r"[&-\xFF]"), hir_uclass(&[('&', '\u{FF}')])); + + assert_eq!(t(r"[~]"), hir_uclass(&[('~', '~')])); + assert_eq!(t(r"[\~]"), hir_uclass(&[('~', '~')])); + assert_eq!(t(r"[\~\~]"), hir_uclass(&[('~', '~')])); + assert_eq!(t(r"[\x00-~]"), hir_uclass(&[('\0', '~')])); + assert_eq!(t(r"[~-\xFF]"), hir_uclass(&[('~', '\u{FF}')])); + + assert_eq!(t(r"[-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\-\-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\x00-\-]"), hir_uclass(&[('\0', '-')])); + assert_eq!(t(r"[\--\xFF]"), hir_uclass(&[('-', '\u{FF}')])); + + assert_eq!(t_err("(?-u)[^a]"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(5, 1, 6), Position::new(9, 1, 10)), + }); + assert_eq!(t_err(r"[^\s\S]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(0, 1, 1), Position::new(7, 1, 8)), + }); + assert_eq!(t_err(r"(?-u)[^\s\S]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(12, 1, 13)), + }); + } + + #[test] + fn class_bracketed_union() { + assert_eq!( + t("[a-zA-Z]"), + hir_uclass(&[('A', 'Z'), ('a', 'z')])); + assert_eq!( + t(r"[a\pZb]"), + hir_union( + hir_uclass(&[('a', 'b')]), + hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"[\pZ\p{Greek}]"), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"[\p{age:3.0}\pZ\p{Greek}]"), + hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator"))))); + assert_eq!( + t(r"[[[\p{age:3.0}\pZ]\p{Greek}][\p{Cyrillic}]]"), + hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("cyrillic")), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))))); + + assert_eq!( + t(r"(?i)[\p{age:3.0}\pZ\p{Greek}]"), + hir_case_fold(hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))))); + assert_eq!( + t(r"[^\p{age:3.0}\pZ\p{Greek}]"), + hir_negate(hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))))); + assert_eq!( + t(r"(?i)[^\p{age:3.0}\pZ\p{Greek}]"), + hir_negate(hir_case_fold(hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator"))))))); + } + + #[test] + fn class_bracketed_nested() { + assert_eq!( + t(r"[a[^c]]"), + hir_negate(hir_uclass(&[('c', 'c')]))); + assert_eq!( + t(r"[a-b[^c]]"), + hir_negate(hir_uclass(&[('c', 'c')]))); + assert_eq!( + t(r"[a-c[^c]]"), + hir_negate(hir_uclass(&[]))); + + assert_eq!( + t(r"[^a[^c]]"), + hir_uclass(&[('c', 'c')])); + assert_eq!( + t(r"[^a-b[^c]]"), + hir_uclass(&[('c', 'c')])); + + assert_eq!( + t(r"(?i)[a[^c]]"), + hir_negate(hir_case_fold(hir_uclass(&[('c', 'c')])))); + assert_eq!( + t(r"(?i)[a-b[^c]]"), + hir_negate(hir_case_fold(hir_uclass(&[('c', 'c')])))); + + assert_eq!( + t(r"(?i)[^a[^c]]"), + hir_uclass(&[('C', 'C'), ('c', 'c')])); + assert_eq!( + t(r"(?i)[^a-b[^c]]"), + hir_uclass(&[('C', 'C'), ('c', 'c')])); + + assert_eq!(t_err(r"[^a-c[^c]]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(0, 1, 1), Position::new(10, 1, 11)), + }); + assert_eq!(t_err(r"(?i)[^a-c[^c]]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(4, 1, 5), Position::new(14, 1, 15)), + }); + } + + #[test] + fn class_bracketed_intersect() { + assert_eq!(t("[abc&&b-c]"), hir_uclass(&[('b', 'c')])); + assert_eq!(t("[abc&&[b-c]]"), hir_uclass(&[('b', 'c')])); + assert_eq!(t("[[abc]&&[b-c]]"), hir_uclass(&[('b', 'c')])); + assert_eq!(t("[a-z&&b-y&&c-x]"), hir_uclass(&[('c', 'x')])); + assert_eq!(t("[c-da-b&&a-d]"), hir_uclass(&[('a', 'd')])); + assert_eq!(t("[a-d&&c-da-b]"), hir_uclass(&[('a', 'd')])); + assert_eq!(t(r"[a-z&&a-c]"), hir_uclass(&[('a', 'c')])); + assert_eq!(t(r"[[a-z&&a-c]]"), hir_uclass(&[('a', 'c')])); + assert_eq!(t(r"[^[a-z&&a-c]]"), hir_negate(hir_uclass(&[('a', 'c')]))); + + assert_eq!(t("(?-u)[abc&&b-c]"), hir_bclass(&[(b'b', b'c')])); + assert_eq!(t("(?-u)[abc&&[b-c]]"), hir_bclass(&[(b'b', b'c')])); + assert_eq!(t("(?-u)[[abc]&&[b-c]]"), hir_bclass(&[(b'b', b'c')])); + assert_eq!(t("(?-u)[a-z&&b-y&&c-x]"), hir_bclass(&[(b'c', b'x')])); + assert_eq!(t("(?-u)[c-da-b&&a-d]"), hir_bclass(&[(b'a', b'd')])); + assert_eq!(t("(?-u)[a-d&&c-da-b]"), hir_bclass(&[(b'a', b'd')])); + + assert_eq!( + t("(?i)[abc&&b-c]"), + hir_case_fold(hir_uclass(&[('b', 'c')]))); + assert_eq!( + t("(?i)[abc&&[b-c]]"), + hir_case_fold(hir_uclass(&[('b', 'c')]))); + assert_eq!( + t("(?i)[[abc]&&[b-c]]"), + hir_case_fold(hir_uclass(&[('b', 'c')]))); + assert_eq!( + t("(?i)[a-z&&b-y&&c-x]"), + hir_case_fold(hir_uclass(&[('c', 'x')]))); + assert_eq!( + t("(?i)[c-da-b&&a-d]"), + hir_case_fold(hir_uclass(&[('a', 'd')]))); + assert_eq!( + t("(?i)[a-d&&c-da-b]"), + hir_case_fold(hir_uclass(&[('a', 'd')]))); + + assert_eq!( + t("(?i-u)[abc&&b-c]"), + hir_case_fold(hir_bclass(&[(b'b', b'c')]))); + assert_eq!( + t("(?i-u)[abc&&[b-c]]"), + hir_case_fold(hir_bclass(&[(b'b', b'c')]))); + assert_eq!( + t("(?i-u)[[abc]&&[b-c]]"), + hir_case_fold(hir_bclass(&[(b'b', b'c')]))); + assert_eq!( + t("(?i-u)[a-z&&b-y&&c-x]"), + hir_case_fold(hir_bclass(&[(b'c', b'x')]))); + assert_eq!( + t("(?i-u)[c-da-b&&a-d]"), + hir_case_fold(hir_bclass(&[(b'a', b'd')]))); + assert_eq!( + t("(?i-u)[a-d&&c-da-b]"), + hir_case_fold(hir_bclass(&[(b'a', b'd')]))); + + // In `[a^]`, `^` does not need to be escaped, so it makes sense that + // `^` is also allowed to be unescaped after `&&`. + assert_eq!(t(r"[\^&&^]"), hir_uclass(&[('^', '^')])); + // `]` needs to be escaped after `&&` since it's not at start of class. + assert_eq!(t(r"[]&&\]]"), hir_uclass(&[(']', ']')])); + assert_eq!(t(r"[-&&-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\&&&&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\&&&\&]"), hir_uclass(&[('&', '&')])); + // Test precedence. + assert_eq!( + t(r"[a-w&&[^c-g]z]"), + hir_uclass(&[('a', 'b'), ('h', 'w')])); + } + + #[test] + fn class_bracketed_intersect_negate() { + assert_eq!( + t(r"[^\w&&\d]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"[^[a-z&&a-c]]"), + hir_negate(hir_uclass(&[('a', 'c')]))); + assert_eq!( + t(r"[^[\w&&\d]]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"[^[^\w&&\d]]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"[[[^\w]&&[^\d]]]"), + hir_negate(hir_uclass_perl_word())); + + assert_eq!( + t_bytes(r"(?-u)[^\w&&\d]"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t_bytes(r"(?-u)[^[a-z&&a-c]]"), + hir_negate(hir_bclass(&[(b'a', b'c')]))); + assert_eq!( + t_bytes(r"(?-u)[^[\w&&\d]]"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t_bytes(r"(?-u)[^[^\w&&\d]]"), + hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit))); + assert_eq!( + t_bytes(r"(?-u)[[[^\w]&&[^\d]]]"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Word)))); + } + + #[test] + fn class_bracketed_difference() { + assert_eq!( + t(r"[\pL--[:ascii:]]"), + hir_difference( + hir_uclass_query(ClassQuery::Binary("letter")), + hir_uclass(&[('\0', '\x7F')]))); + + assert_eq!( + t(r"(?-u)[[:alpha:]--[:lower:]]"), + hir_bclass(&[(b'A', b'Z')])); + } + + #[test] + fn class_bracketed_symmetric_difference() { + assert_eq!( + t(r"[\p{sc:Greek}~~\p{scx:Greek}]"), + hir_uclass(&[ + ('\u{0342}', '\u{0342}'), + ('\u{0345}', '\u{0345}'), + ('\u{1DC0}', '\u{1DC1}'), + ])); + assert_eq!( + t(r"[a-g~~c-j]"), + hir_uclass(&[('a', 'b'), ('h', 'j')])); + + assert_eq!( + t(r"(?-u)[a-g~~c-j]"), + hir_bclass(&[(b'a', b'b'), (b'h', b'j')])); + } + + #[test] + fn ignore_whitespace() { + assert_eq!(t(r"(?x)\12 3"), hir_lit("\n3")); + assert_eq!(t(r"(?x)\x { 53 }"), hir_lit("S")); + assert_eq!(t(r"(?x)\x # comment +{ # comment + 53 # comment +} #comment"), hir_lit("S")); + + assert_eq!(t(r"(?x)\x 53"), hir_lit("S")); + assert_eq!(t(r"(?x)\x # comment + 53 # comment"), hir_lit("S")); + assert_eq!(t(r"(?x)\x5 3"), hir_lit("S")); + + assert_eq!(t(r"(?x)\p # comment +{ # comment + Separator # comment +} # comment"), hir_uclass_query(ClassQuery::Binary("separator"))); + + assert_eq!(t(r"(?x)a # comment +{ # comment + 5 # comment + , # comment + 10 # comment +} # comment"), + hir_range( + true, hir::RepetitionRange::Bounded(5, 10), hir_lit("a"))); + + assert_eq!(t(r"(?x)a\ # hi there"), hir_lit("a ")); + } + + #[test] + fn analysis_is_always_utf8() { + // Positive examples. + assert!(t_bytes(r"a").is_always_utf8()); + assert!(t_bytes(r"ab").is_always_utf8()); + assert!(t_bytes(r"(?-u)a").is_always_utf8()); + assert!(t_bytes(r"(?-u)ab").is_always_utf8()); + assert!(t_bytes(r"\xFF").is_always_utf8()); + assert!(t_bytes(r"\xFF\xFF").is_always_utf8()); + assert!(t_bytes(r"[^a]").is_always_utf8()); + assert!(t_bytes(r"[^a][^a]").is_always_utf8()); + assert!(t_bytes(r"\b").is_always_utf8()); + assert!(t_bytes(r"\B").is_always_utf8()); + assert!(t_bytes(r"(?-u)\b").is_always_utf8()); + + // Negative examples. + assert!(!t_bytes(r"(?-u)\xFF").is_always_utf8()); + assert!(!t_bytes(r"(?-u)\xFF\xFF").is_always_utf8()); + assert!(!t_bytes(r"(?-u)[^a]").is_always_utf8()); + assert!(!t_bytes(r"(?-u)[^a][^a]").is_always_utf8()); + assert!(!t_bytes(r"(?-u)\B").is_always_utf8()); + } + + #[test] + fn analysis_is_all_assertions() { + // Positive examples. + assert!(t(r"\b").is_all_assertions()); + assert!(t(r"\B").is_all_assertions()); + assert!(t(r"^").is_all_assertions()); + assert!(t(r"$").is_all_assertions()); + assert!(t(r"\A").is_all_assertions()); + assert!(t(r"\z").is_all_assertions()); + assert!(t(r"$^\z\A\b\B").is_all_assertions()); + assert!(t(r"$|^|\z|\A|\b|\B").is_all_assertions()); + assert!(t(r"^$|$^").is_all_assertions()); + assert!(t(r"((\b)+())*^").is_all_assertions()); + + // Negative examples. + assert!(!t(r"^a").is_all_assertions()); + } + + #[test] + fn analysis_is_anchored() { + // Positive examples. + assert!(t(r"^").is_anchored_start()); + assert!(t(r"$").is_anchored_end()); + + assert!(t(r"^^").is_anchored_start()); + assert!(t(r"$$").is_anchored_end()); + + assert!(t(r"^$").is_anchored_start()); + assert!(t(r"^$").is_anchored_end()); + + assert!(t(r"^foo").is_anchored_start()); + assert!(t(r"foo$").is_anchored_end()); + + assert!(t(r"^foo|^bar").is_anchored_start()); + assert!(t(r"foo$|bar$").is_anchored_end()); + + assert!(t(r"^(foo|bar)").is_anchored_start()); + assert!(t(r"(foo|bar)$").is_anchored_end()); + + assert!(t(r"^+").is_anchored_start()); + assert!(t(r"$+").is_anchored_end()); + assert!(t(r"^++").is_anchored_start()); + assert!(t(r"$++").is_anchored_end()); + assert!(t(r"(^)+").is_anchored_start()); + assert!(t(r"($)+").is_anchored_end()); + + assert!(t(r"$^").is_anchored_start()); + assert!(t(r"$^").is_anchored_end()); + assert!(t(r"$^|^$").is_anchored_start()); + assert!(t(r"$^|^$").is_anchored_end()); + + assert!(t(r"\b^").is_anchored_start()); + assert!(t(r"$\b").is_anchored_end()); + assert!(t(r"^(?m:^)").is_anchored_start()); + assert!(t(r"(?m:$)$").is_anchored_end()); + assert!(t(r"(?m:^)^").is_anchored_start()); + assert!(t(r"$(?m:$)").is_anchored_end()); + + // Negative examples. + assert!(!t(r"(?m)^").is_anchored_start()); + assert!(!t(r"(?m)$").is_anchored_end()); + assert!(!t(r"(?m:^$)|$^").is_anchored_start()); + assert!(!t(r"(?m:^$)|$^").is_anchored_end()); + assert!(!t(r"$^|(?m:^$)").is_anchored_start()); + assert!(!t(r"$^|(?m:^$)").is_anchored_end()); + + assert!(!t(r"a^").is_anchored_start()); + assert!(!t(r"$a").is_anchored_start()); + + assert!(!t(r"a^").is_anchored_start()); + assert!(!t(r"$a").is_anchored_start()); + + assert!(!t(r"^foo|bar").is_anchored_start()); + assert!(!t(r"foo|bar$").is_anchored_end()); + + assert!(!t(r"^*").is_anchored_start()); + assert!(!t(r"$*").is_anchored_end()); + assert!(!t(r"^*+").is_anchored_start()); + assert!(!t(r"$*+").is_anchored_end()); + assert!(!t(r"^+*").is_anchored_start()); + assert!(!t(r"$+*").is_anchored_end()); + assert!(!t(r"(^)*").is_anchored_start()); + assert!(!t(r"($)*").is_anchored_end()); + } + + #[test] + fn analysis_is_any_anchored() { + // Positive examples. + assert!(t(r"^").is_any_anchored_start()); + assert!(t(r"$").is_any_anchored_end()); + assert!(t(r"\A").is_any_anchored_start()); + assert!(t(r"\z").is_any_anchored_end()); + + // Negative examples. + assert!(!t(r"(?m)^").is_any_anchored_start()); + assert!(!t(r"(?m)$").is_any_anchored_end()); + assert!(!t(r"$").is_any_anchored_start()); + assert!(!t(r"^").is_any_anchored_end()); + } + + #[test] + fn analysis_is_match_empty() { + // Positive examples. + assert!(t(r"").is_match_empty()); + assert!(t(r"()").is_match_empty()); + assert!(t(r"()*").is_match_empty()); + assert!(t(r"()+").is_match_empty()); + assert!(t(r"()?").is_match_empty()); + assert!(t(r"a*").is_match_empty()); + assert!(t(r"a?").is_match_empty()); + assert!(t(r"a{0}").is_match_empty()); + assert!(t(r"a{0,}").is_match_empty()); + assert!(t(r"a{0,1}").is_match_empty()); + assert!(t(r"a{0,10}").is_match_empty()); + assert!(t(r"\pL*").is_match_empty()); + assert!(t(r"a*|b").is_match_empty()); + assert!(t(r"b|a*").is_match_empty()); + assert!(t(r"a*a?(abcd)*").is_match_empty()); + assert!(t(r"^").is_match_empty()); + assert!(t(r"$").is_match_empty()); + assert!(t(r"(?m)^").is_match_empty()); + assert!(t(r"(?m)$").is_match_empty()); + assert!(t(r"\A").is_match_empty()); + assert!(t(r"\z").is_match_empty()); + assert!(t(r"\B").is_match_empty()); + assert!(t_bytes(r"(?-u)\B").is_match_empty()); + + // Negative examples. + assert!(!t(r"a+").is_match_empty()); + assert!(!t(r"a{1}").is_match_empty()); + assert!(!t(r"a{1,}").is_match_empty()); + assert!(!t(r"a{1,2}").is_match_empty()); + assert!(!t(r"a{1,10}").is_match_empty()); + assert!(!t(r"b|a").is_match_empty()); + assert!(!t(r"a*a+(abcd)*").is_match_empty()); + assert!(!t(r"\b").is_match_empty()); + assert!(!t(r"(?-u)\b").is_match_empty()); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/hir/visitor.rs b/bash-5.1/vendor/regex-syntax/src/hir/visitor.rs new file mode 100644 index 0000000..716a96d --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/hir/visitor.rs @@ -0,0 +1,222 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use hir::{self, Hir, HirKind}; + +/// A trait for visiting the high-level IR (HIR) in depth first order. +/// +/// The principle aim of this trait is to enable callers to perform case +/// analysis on a high-level intermediate representation of a regular +/// expression without necessarily using recursion. In particular, this permits +/// callers to do case analysis with constant stack usage, which can be +/// important since the size of an HIR may be proportional to end user input. +/// +/// Typical usage of this trait involves providing an implementation and then +/// running it using the [`visit`](fn.visit.html) function. +pub trait Visitor { + /// The result of visiting an HIR. + type Output; + /// An error that visiting an HIR might return. + type Err; + + /// All implementors of `Visitor` must provide a `finish` method, which + /// yields the result of visiting the HIR or an error. + fn finish(self) -> Result; + + /// This method is called before beginning traversal of the HIR. + fn start(&mut self) {} + + /// This method is called on an `Hir` before descending into child `Hir` + /// nodes. + fn visit_pre(&mut self, _hir: &Hir) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on an `Hir` after descending all of its child + /// `Hir` nodes. + fn visit_post(&mut self, _hir: &Hir) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called between child nodes of an alternation. + fn visit_alternation_in(&mut self) -> Result<(), Self::Err> { + Ok(()) + } +} + +/// Executes an implementation of `Visitor` in constant stack space. +/// +/// This function will visit every node in the given `Hir` while calling +/// appropriate methods provided by the +/// [`Visitor`](trait.Visitor.html) trait. +/// +/// The primary use case for this method is when one wants to perform case +/// analysis over an `Hir` without using a stack size proportional to the depth +/// of the `Hir`. Namely, this method will instead use constant stack space, +/// but will use heap space proportional to the size of the `Hir`. This may be +/// desirable in cases where the size of `Hir` is proportional to end user +/// input. +/// +/// If the visitor returns an error at any point, then visiting is stopped and +/// the error is returned. +pub fn visit(hir: &Hir, visitor: V) -> Result { + HeapVisitor::new().visit(hir, visitor) +} + +/// HeapVisitor visits every item in an `Hir` recursively using constant stack +/// size and a heap size proportional to the size of the `Hir`. +struct HeapVisitor<'a> { + /// A stack of `Hir` nodes. This is roughly analogous to the call stack + /// used in a typical recursive visitor. + stack: Vec<(&'a Hir, Frame<'a>)>, +} + +/// Represents a single stack frame while performing structural induction over +/// an `Hir`. +enum Frame<'a> { + /// A stack frame allocated just before descending into a repetition + /// operator's child node. + Repetition(&'a hir::Repetition), + /// A stack frame allocated just before descending into a group's child + /// node. + Group(&'a hir::Group), + /// The stack frame used while visiting every child node of a concatenation + /// of expressions. + Concat { + /// The child node we are currently visiting. + head: &'a Hir, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Hir], + }, + /// The stack frame used while visiting every child node of an alternation + /// of expressions. + Alternation { + /// The child node we are currently visiting. + head: &'a Hir, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Hir], + }, +} + +impl<'a> HeapVisitor<'a> { + fn new() -> HeapVisitor<'a> { + HeapVisitor { stack: vec![] } + } + + fn visit( + &mut self, + mut hir: &'a Hir, + mut visitor: V, + ) -> Result { + self.stack.clear(); + + visitor.start(); + loop { + try!(visitor.visit_pre(hir)); + if let Some(x) = self.induct(hir) { + let child = x.child(); + self.stack.push((hir, x)); + hir = child; + continue; + } + // No induction means we have a base case, so we can post visit + // it now. + try!(visitor.visit_post(hir)); + + // At this point, we now try to pop our call stack until it is + // either empty or we hit another inductive case. + loop { + let (post_hir, frame) = match self.stack.pop() { + None => return visitor.finish(), + Some((post_hir, frame)) => (post_hir, frame), + }; + // If this is a concat/alternate, then we might have additional + // inductive steps to process. + if let Some(x) = self.pop(frame) { + if let Frame::Alternation {..} = x { + try!(visitor.visit_alternation_in()); + } + hir = x.child(); + self.stack.push((post_hir, x)); + break; + } + // Otherwise, we've finished visiting all the child nodes for + // this HIR, so we can post visit it now. + try!(visitor.visit_post(post_hir)); + } + } + } + + /// Build a stack frame for the given HIR if one is needed (which occurs if + /// and only if there are child nodes in the HIR). Otherwise, return None. + fn induct(&mut self, hir: &'a Hir) -> Option> { + match *hir.kind() { + HirKind::Repetition(ref x) => Some(Frame::Repetition(x)), + HirKind::Group(ref x) => Some(Frame::Group(x)), + HirKind::Concat(ref x) if x.is_empty() => None, + HirKind::Concat(ref x) => { + Some(Frame::Concat { + head: &x[0], + tail: &x[1..], + }) + } + HirKind::Alternation(ref x) if x.is_empty() => None, + HirKind::Alternation(ref x) => { + Some(Frame::Alternation { + head: &x[0], + tail: &x[1..], + }) + } + _ => None, + } + } + + /// Pops the given frame. If the frame has an additional inductive step, + /// then return it, otherwise return `None`. + fn pop(&self, induct: Frame<'a>) -> Option> { + match induct { + Frame::Repetition(_) => None, + Frame::Group(_) => None, + Frame::Concat { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Concat { + head: &tail[0], + tail: &tail[1..], + }) + } + } + Frame::Alternation { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Alternation { + head: &tail[0], + tail: &tail[1..], + }) + } + } + } + } +} + +impl<'a> Frame<'a> { + /// Perform the next inductive step on this frame and return the next + /// child HIR node to visit. + fn child(&self) -> &'a Hir { + match *self { + Frame::Repetition(rep) => &rep.hir, + Frame::Group(group) => &group.hir, + Frame::Concat { head, .. } => head, + Frame::Alternation { head, .. } => head, + } + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/lib.rs b/bash-5.1/vendor/regex-syntax/src/lib.rs new file mode 100644 index 0000000..27a1d45 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/lib.rs @@ -0,0 +1,222 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This crate provides a robust regular expression parser. + +This crate defines two primary types: + +* [`Ast`](ast/enum.Ast.html) is the abstract syntax of a regular expression. + An abstract syntax corresponds to a *structured representation* of the + concrete syntax of a regular expression, where the concrete syntax is the + pattern string itself (e.g., `foo(bar)+`). Given some abstract syntax, it + can be converted back to the original concrete syntax (modulo some details, + like whitespace). To a first approximation, the abstract syntax is complex + and difficult to analyze. +* [`Hir`](hir/struct.Hir.html) is the high-level intermediate representation + ("HIR" or "high-level IR" for short) of regular expression. It corresponds to + an intermediate state of a regular expression that sits between the abstract + syntax and the low level compiled opcodes that are eventually responsible for + executing a regular expression search. Given some high-level IR, it is not + possible to produce the original concrete syntax (although it is possible to + produce an equivalent conrete syntax, but it will likely scarcely resemble + the original pattern). To a first approximation, the high-level IR is simple + and easy to analyze. + +These two types come with conversion routines: + +* An [`ast::parse::Parser`](ast/parse/struct.Parser.html) converts concrete + syntax (a `&str`) to an [`Ast`](ast/enum.Ast.html). +* A [`hir::translate::Translator`](hir/translate/struct.Translator.html) + converts an [`Ast`](ast/enum.Ast.html) to a [`Hir`](hir/struct.Hir.html). + +As a convenience, the above two conversion routines are combined into one via +the top-level [`Parser`](struct.Parser.html) type. This `Parser` will first +convert your pattern to an `Ast` and then convert the `Ast` to an `Hir`. + + +# Example + +This example shows how to parse a pattern string into its HIR: + +``` +use regex_syntax::Parser; +use regex_syntax::hir::{self, Hir}; + +let hir = Parser::new().parse("a|b").unwrap(); +assert_eq!(hir, Hir::alternation(vec![ + Hir::literal(hir::Literal::Unicode('a')), + Hir::literal(hir::Literal::Unicode('b')), +])); +``` + + +# Concrete syntax supported + +The concrete syntax is documented as part of the public API of the +[`regex` crate](https://docs.rs/regex/%2A/regex/#syntax). + + +# Input safety + +A key feature of this library is that it is safe to use with end user facing +input. This plays a significant role in the internal implementation. In +particular: + +1. Parsers provide a `nest_limit` option that permits callers to control how + deeply nested a regular expression is allowed to be. This makes it possible + to do case analysis over an `Ast` or an `Hir` using recursion without + worrying about stack overflow. +2. Since relying on a particular stack size is brittle, this crate goes to + great lengths to ensure that all interactions with both the `Ast` and the + `Hir` do not use recursion. Namely, they use constant stack space and heap + space proportional to the size of the original pattern string (in bytes). + This includes the type's corresponding destructors. (One exception to this + is literal extraction, but this will eventually get fixed.) + + +# Error reporting + +The `Display` implementations on all `Error` types exposed in this library +provide nice human readable errors that are suitable for showing to end users +in a monospace font. + + +# Literal extraction + +This crate provides limited support for +[literal extraction from `Hir` values](hir/literal/struct.Literals.html). +Be warned that literal extraction currently uses recursion, and therefore, +stack size proportional to the size of the `Hir`. + +The purpose of literal extraction is to speed up searches. That is, if you +know a regular expression must match a prefix or suffix literal, then it is +often quicker to search for instances of that literal, and then confirm or deny +the match using the full regular expression engine. These optimizations are +done automatically in the `regex` crate. +*/ + +#![deny(missing_docs)] + +extern crate ucd_util; + +pub use error::{Error, Result}; +pub use parser::{Parser, ParserBuilder}; + +pub mod ast; +mod either; +mod error; +pub mod hir; +mod parser; +mod unicode; +mod unicode_tables; + +/// Escapes all regular expression meta characters in `text`. +/// +/// The string returned may be safely used as a literal in a regular +/// expression. +pub fn escape(text: &str) -> String { + let mut quoted = String::with_capacity(text.len()); + escape_into(text, &mut quoted); + quoted +} + +/// Escapes all meta characters in `text` and writes the result into `buf`. +/// +/// This will append escape characters into the given buffer. The characters +/// that are appended are safe to use as a literal in a regular expression. +pub fn escape_into(text: &str, buf: &mut String) { + for c in text.chars() { + if is_meta_character(c) { + buf.push('\\'); + } + buf.push(c); + } +} + +/// Returns true if the give character has significance in a regex. +/// +/// These are the only characters that are allowed to be escaped, with one +/// exception: an ASCII space character may be escaped when extended mode (with +/// the `x` flag) is enabld. In particular, `is_meta_character(' ')` returns +/// `false`. +/// +/// Note that the set of characters for which this function returns `true` or +/// `false` is fixed and won't change in a semver compatible release. +pub fn is_meta_character(c: char) -> bool { + match c { + '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | + '[' | ']' | '{' | '}' | '^' | '$' | '#' | '&' | '-' | '~' => true, + _ => false, + } +} + +/// Returns true if and only if the given character is a Unicode word +/// character. +/// +/// A Unicode word character is defined by +/// [UTS#18 Annex C](http://unicode.org/reports/tr18/#Compatibility_Properties). +/// In particular, a character +/// is considered a word character if it is in either of the `Alphabetic` or +/// `Join_Control` properties, or is in one of the `Decimal_Number`, `Mark` +/// or `Connector_Punctuation` general categories. +pub fn is_word_character(c: char) -> bool { + use std::cmp::Ordering; + use unicode_tables::perl_word::PERL_WORD; + + if c <= 0x7F as char && is_word_byte(c as u8) { + return true; + } + PERL_WORD + .binary_search_by(|&(start, end)| { + if start <= c && c <= end { + Ordering::Equal + } else if start > c { + Ordering::Greater + } else { + Ordering::Less + } + }).is_ok() +} + +/// Returns true if and only if the given character is an ASCII word character. +/// +/// An ASCII word character is defined by the following character class: +/// `[_0-9a-zA-Z]'. +pub fn is_word_byte(c: u8) -> bool { + match c { + b'_' | b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' => true, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escape_meta() { + assert_eq!( + escape(r"\.+*?()|[]{}^$#&-~"), + r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#\&\-\~".to_string(), + ); + } + + #[test] + fn word() { + assert!(is_word_byte(b'a')); + assert!(!is_word_byte(b'-')); + + assert!(is_word_character('a')); + assert!(is_word_character('β')); + assert!(!is_word_character('-')); + assert!(!is_word_character('☃')); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/parser.rs b/bash-5.1/vendor/regex-syntax/src/parser.rs new file mode 100644 index 0000000..e28d7f3 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/parser.rs @@ -0,0 +1,206 @@ +use ast; +use hir; + +use Result; + +/// A builder for a regular expression parser. +/// +/// This builder permits modifying configuration options for the parser. +/// +/// This type combines the builder options for both the +/// [AST `ParserBuilder`](ast/parse/struct.ParserBuilder.html) +/// and the +/// [HIR `TranslatorBuilder`](hir/translate/struct.TranslatorBuilder.html). +#[derive(Clone, Debug, Default)] +pub struct ParserBuilder { + ast: ast::parse::ParserBuilder, + hir: hir::translate::TranslatorBuilder, +} + +impl ParserBuilder { + /// Create a new parser builder with a default configuration. + pub fn new() -> ParserBuilder { + ParserBuilder::default() + } + + /// Build a parser from this configuration with the given pattern. + pub fn build(&self) -> Parser { + Parser { + ast: self.ast.build(), + hir: self.hir.build(), + } + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut ParserBuilder { + self.ast.nest_limit(limit); + self + } + + /// Whether to support octal syntax or not. + /// + /// Octal syntax is a little-known way of uttering Unicode codepoints in + /// a regular expression. For example, `a`, `\x61`, `\u0061` and + /// `\141` are all equivalent regular expressions, where the last example + /// shows octal syntax. + /// + /// While supporting octal syntax isn't in and of itself a problem, it does + /// make good error messages harder. That is, in PCRE based regex engines, + /// syntax like `\0` invokes a backreference, which is explicitly + /// unsupported in Rust's regex engine. However, many users expect it to + /// be supported. Therefore, when octal support is disabled, the error + /// message will explicitly mention that backreferences aren't supported. + /// + /// Octal syntax is disabled by default. + pub fn octal(&mut self, yes: bool) -> &mut ParserBuilder { + self.ast.octal(yes); + self + } + + /// When enabled, the parser will permit the construction of a regular + /// expression that may match invalid UTF-8. + /// + /// When disabled (the default), the parser is guaranteed to produce + /// an expression that will only ever match valid UTF-8 (otherwise, the + /// parser will return an error). + /// + /// Note that currently, even when invalid UTF-8 is banned, the parser + /// will permit a negated ASCII word boundary (i.e., `(?-u:\B)`) even + /// though it can actually match at invalid UTF-8 boundaries. This bug + /// will be fixed on the next semver release. + pub fn allow_invalid_utf8(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.allow_invalid_utf8(yes); + self + } + + /// Enable verbose mode in the regular expression. + /// + /// When enabled, verbose mode permits insigificant whitespace in many + /// places in the regular expression, as well as comments. Comments are + /// started using `#` and continue until the end of the line. + /// + /// By default, this is disabled. It may be selectively enabled in the + /// regular expression by using the `x` flag regardless of this setting. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut ParserBuilder { + self.ast.ignore_whitespace(yes); + self + } + + /// Enable or disable the case insensitive flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `i` flag. + pub fn case_insensitive(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.case_insensitive(yes); + self + } + + /// Enable or disable the multi-line matching flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `m` flag. + pub fn multi_line(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.multi_line(yes); + self + } + + /// Enable or disable the "dot matches any character" flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `s` flag. + pub fn dot_matches_new_line( + &mut self, + yes: bool, + ) -> &mut ParserBuilder { + self.hir.dot_matches_new_line(yes); + self + } + + /// Enable or disable the "swap greed" flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `U` flag. + pub fn swap_greed(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.swap_greed(yes); + self + } + + /// Enable or disable the Unicode flag (`u`) by default. + /// + /// By default this is **enabled**. It may alternatively be selectively + /// disabled in the regular expression itself via the `u` flag. + /// + /// Note that unless `allow_invalid_utf8` is enabled (it's disabled by + /// default), a regular expression will fail to parse if Unicode mode is + /// disabled and a sub-expression could possibly match invalid UTF-8. + pub fn unicode(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.unicode(yes); + self + } +} + +/// A convenience parser for regular expressions. +/// +/// This parser takes as input a regular expression pattern string (the +/// "concrete syntax") and returns a high-level intermediate representation +/// (the HIR) suitable for most types of analysis. In particular, this parser +/// hides the intermediate state of producing an AST (the "abstract syntax"). +/// The AST is itself far more complex than the HIR, so this parser serves as a +/// convenience for never having to deal with it at all. +/// +/// If callers have more fine grained use cases that need an AST, then please +/// see the [`ast::parse`](ast/parse/index.html) module. +/// +/// A `Parser` can be configured in more detail via a +/// [`ParserBuilder`](struct.ParserBuilder.html). +#[derive(Clone, Debug)] +pub struct Parser { + ast: ast::parse::Parser, + hir: hir::translate::Translator, +} + +impl Parser { + /// Create a new parser with a default configuration. + /// + /// The parser can be run with `parse` method. The parse method returns + /// a high level intermediate representation of the given regular + /// expression. + /// + /// To set configuration options on the parser, use + /// [`ParserBuilder`](struct.ParserBuilder.html). + pub fn new() -> Parser { + ParserBuilder::new().build() + } + + /// Parse the regular expression into a high level intermediate + /// representation. + pub fn parse(&mut self, pattern: &str) -> Result { + let ast = try!(self.ast.parse(pattern)); + let hir = try!(self.hir.translate(pattern, &ast)); + Ok(hir) + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/unicode.rs b/bash-5.1/vendor/regex-syntax/src/unicode.rs new file mode 100644 index 0000000..153c8a5 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode.rs @@ -0,0 +1,472 @@ +use std::cmp::Ordering; +use std::result; + +use ucd_util::{self, PropertyValues}; + +use hir; +use unicode_tables::age; +use unicode_tables::case_folding_simple::CASE_FOLDING_SIMPLE; +use unicode_tables::general_category; +use unicode_tables::property_bool; +use unicode_tables::property_names::PROPERTY_NAMES; +use unicode_tables::property_values::PROPERTY_VALUES; +use unicode_tables::script; +use unicode_tables::script_extension; + +type Result = result::Result; + +/// An error that occurs when dealing with Unicode. +/// +/// We don't impl the Error trait here because these always get converted +/// into other public errors. (This error type isn't exported.) +#[derive(Debug)] +pub enum Error { + PropertyNotFound, + PropertyValueNotFound, +} + +/// Encode the given Unicode character to `dst` as a single UTF-8 sequence. +/// +/// If `dst` is not long enough, then `None` is returned. Otherwise, the number +/// of bytes written is returned. +pub fn encode_utf8(character: char, dst: &mut [u8]) -> Option { + // TODO: Remove this function once we move to at least Rust 1.15, which + // provides char::encode_utf8 for us. + const TAG_CONT: u8 = 0b1000_0000; + const TAG_TWO: u8 = 0b1100_0000; + const TAG_THREE: u8 = 0b1110_0000; + const TAG_FOUR: u8 = 0b1111_0000; + + let code = character as u32; + if code <= 0x7F && !dst.is_empty() { + dst[0] = code as u8; + Some(1) + } else if code <= 0x7FF && dst.len() >= 2 { + dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO; + dst[1] = (code & 0x3F) as u8 | TAG_CONT; + Some(2) + } else if code <= 0xFFFF && dst.len() >= 3 { + dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE; + dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code & 0x3F) as u8 | TAG_CONT; + Some(3) + } else if dst.len() >= 4 { + dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR; + dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[3] = (code & 0x3F) as u8 | TAG_CONT; + Some(4) + } else { + None + } +} + +/// An iterator over a codepoint's simple case equivalence class. +#[derive(Debug)] +pub struct SimpleFoldIter(::std::slice::Iter<'static, char>); + +impl Iterator for SimpleFoldIter { + type Item = char; + + fn next(&mut self) -> Option { + self.0.next().map(|c| *c) + } +} + +/// Return an iterator over the equivalence class of simple case mappings +/// for the given codepoint. The equivalence class does not include the +/// given codepoint. +/// +/// If the equivalence class is empty, then this returns the next scalar +/// value that has a non-empty equivalence class, if it exists. If no such +/// scalar value exists, then `None` is returned. The point of this behavior +/// is to permit callers to avoid calling `simple_fold` more than they need +/// to, since there is some cost to fetching the equivalence class. +pub fn simple_fold(c: char) -> result::Result> { + CASE_FOLDING_SIMPLE + .binary_search_by_key(&c, |&(c1, _)| c1) + .map(|i| SimpleFoldIter(CASE_FOLDING_SIMPLE[i].1.iter())) + .map_err(|i| { + if i >= CASE_FOLDING_SIMPLE.len() { + None + } else { + Some(CASE_FOLDING_SIMPLE[i].0) + } + }) +} + +/// Returns true if and only if the given (inclusive) range contains at least +/// one Unicode scalar value that has a non-empty non-trivial simple case +/// mapping. +/// +/// This function panics if `end < start`. +pub fn contains_simple_case_mapping(start: char, end: char) -> bool { + assert!(start <= end); + CASE_FOLDING_SIMPLE + .binary_search_by(|&(c, _)| { + if start <= c && c <= end { + Ordering::Equal + } else if c > end { + Ordering::Greater + } else { + Ordering::Less + } + }).is_ok() +} + +/// A query for finding a character class defined by Unicode. This supports +/// either use of a property name directly, or lookup by property value. The +/// former generally refers to Binary properties (see UTS#44, Table 8), but +/// as a special exception (see UTS#18, Section 1.2) both general categories +/// (an enumeration) and scripts (a catalog) are supported as if each of their +/// possible values were a binary property. +/// +/// In all circumstances, property names and values are normalized and +/// canonicalized. That is, `GC == gc == GeneralCategory == general_category`. +/// +/// The lifetime `'a` refers to the shorter of the lifetimes of property name +/// and property value. +#[derive(Debug)] +pub enum ClassQuery<'a> { + /// Return a class corresponding to a Unicode binary property, named by + /// a single letter. + OneLetter(char), + /// Return a class corresponding to a Unicode binary property. + /// + /// Note that, by special exception (see UTS#18, Section 1.2), both + /// general category values and script values are permitted here as if + /// they were a binary property. + Binary(&'a str), + /// Return a class corresponding to all codepoints whose property + /// (identified by `property_name`) corresponds to the given value + /// (identified by `property_value`). + ByValue { + /// A property name. + property_name: &'a str, + /// A property value. + property_value: &'a str, + }, +} + +impl<'a> ClassQuery<'a> { + fn canonicalize(&self) -> Result { + match *self { + ClassQuery::OneLetter(c) => self.canonical_binary(&c.to_string()), + ClassQuery::Binary(name) => self.canonical_binary(name), + ClassQuery::ByValue { property_name, property_value } => { + let property_name = normalize(property_name); + let property_value = normalize(property_value); + + let canon_name = match canonical_prop(&property_name) { + None => return Err(Error::PropertyNotFound), + Some(canon_name) => canon_name, + }; + Ok(match canon_name { + "General_Category" => { + let canon = match canonical_gencat(&property_value) { + None => return Err(Error::PropertyValueNotFound), + Some(canon) => canon, + }; + CanonicalClassQuery::GeneralCategory(canon) + } + "Script" => { + let canon = match canonical_script(&property_value) { + None => return Err(Error::PropertyValueNotFound), + Some(canon) => canon, + }; + CanonicalClassQuery::Script(canon) + } + _ => { + let vals = match property_values(canon_name) { + None => return Err(Error::PropertyValueNotFound), + Some(vals) => vals, + }; + let canon_val = match canonical_value( + vals, + &property_value, + ) { + None => return Err(Error::PropertyValueNotFound), + Some(canon_val) => canon_val, + }; + CanonicalClassQuery::ByValue { + property_name: canon_name, + property_value: canon_val, + } + } + }) + } + } + } + + fn canonical_binary(&self, name: &str) -> Result { + let norm = normalize(name); + + if let Some(canon) = canonical_prop(&norm) { + return Ok(CanonicalClassQuery::Binary(canon)); + } + if let Some(canon) = canonical_gencat(&norm) { + return Ok(CanonicalClassQuery::GeneralCategory(canon)); + } + if let Some(canon) = canonical_script(&norm) { + return Ok(CanonicalClassQuery::Script(canon)); + } + Err(Error::PropertyNotFound) + } +} + +/// Like ClassQuery, but its parameters have been canonicalized. This also +/// differentiates binary properties from flattened general categories and +/// scripts. +#[derive(Debug, Eq, PartialEq)] +enum CanonicalClassQuery { + /// The canonical binary property name. + Binary(&'static str), + /// The canonical general category name. + GeneralCategory(&'static str), + /// The canonical script name. + Script(&'static str), + /// An arbitrary association between property and value, both of which + /// have been canonicalized. + /// + /// Note that by construction, the property name of ByValue will never + /// be General_Category or Script. Those two cases are subsumed by the + /// eponymous variants. + ByValue { + /// The canonical property name. + property_name: &'static str, + /// The canonical property value. + property_value: &'static str, + }, +} + +/// Looks up a Unicode class given a query. If one doesn't exist, then +/// `None` is returned. +pub fn class<'a>(query: ClassQuery<'a>) -> Result { + use self::CanonicalClassQuery::*; + + match try!(query.canonicalize()) { + Binary(name) => { + property_set(property_bool::BY_NAME, name) + .map(hir_class) + .ok_or(Error::PropertyNotFound) + } + GeneralCategory("Any") => { + Ok(hir_class(&[('\0', '\u{10FFFF}')])) + } + GeneralCategory("Assigned") => { + let mut cls = + try!(property_set(general_category::BY_NAME, "Unassigned") + .map(hir_class) + .ok_or(Error::PropertyNotFound)); + cls.negate(); + Ok(cls) + } + GeneralCategory("ASCII") => { + Ok(hir_class(&[('\0', '\x7F')])) + } + GeneralCategory(name) => { + property_set(general_category::BY_NAME, name) + .map(hir_class) + .ok_or(Error::PropertyValueNotFound) + } + Script(name) => { + property_set(script::BY_NAME, name) + .map(hir_class) + .ok_or(Error::PropertyValueNotFound) + } + ByValue { property_name: "Age", property_value } => { + let mut class = hir::ClassUnicode::empty(); + for set in try!(ages(property_value)) { + class.union(&hir_class(set)); + } + Ok(class) + } + ByValue { property_name: "Script_Extensions", property_value } => { + property_set(script_extension::BY_NAME, property_value) + .map(hir_class) + .ok_or(Error::PropertyValueNotFound) + } + _ => { + // What else should we support? + Err(Error::PropertyNotFound) + } + } +} + +/// Build a Unicode HIR class from a sequence of Unicode scalar value ranges. +pub fn hir_class(ranges: &[(char, char)]) -> hir::ClassUnicode { + let hir_ranges: Vec = ranges + .iter() + .map(|&(s, e)| hir::ClassUnicodeRange::new(s, e)) + .collect(); + hir::ClassUnicode::new(hir_ranges) +} + +fn canonical_prop(normalized_name: &str) -> Option<&'static str> { + ucd_util::canonical_property_name(PROPERTY_NAMES, normalized_name) +} + +fn canonical_gencat(normalized_value: &str) -> Option<&'static str> { + match normalized_value { + "any" => Some("Any"), + "assigned" => Some("Assigned"), + "ascii" => Some("ASCII"), + _ => { + let gencats = property_values("General_Category").unwrap(); + canonical_value(gencats, normalized_value) + } + } +} + +fn canonical_script(normalized_value: &str) -> Option<&'static str> { + let scripts = property_values("Script").unwrap(); + canonical_value(scripts, normalized_value) +} + +fn canonical_value( + vals: PropertyValues, + normalized_value: &str, +) -> Option<&'static str> { + ucd_util::canonical_property_value(vals, normalized_value) +} + +fn normalize(x: &str) -> String { + let mut x = x.to_string(); + ucd_util::symbolic_name_normalize(&mut x); + x +} + +fn property_values( + canonical_property_name: &'static str, +) -> Option +{ + ucd_util::property_values(PROPERTY_VALUES, canonical_property_name) +} + +fn property_set( + name_map: &'static [(&'static str, &'static [(char, char)])], + canonical: &'static str, +) -> Option<&'static [(char, char)]> { + name_map + .binary_search_by_key(&canonical, |x| x.0) + .ok() + .map(|i| name_map[i].1) +} + +/// An iterator over Unicode Age sets. Each item corresponds to a set of +/// codepoints that were added in a particular revision of Unicode. The +/// iterator yields items in chronological order. +#[derive(Debug)] +struct AgeIter { + ages: &'static [(&'static str, &'static [(char, char)])], +} + +fn ages(canonical_age: &str) -> Result { + const AGES: &'static [(&'static str, &'static [(char, char)])] = &[ + ("V1_1", age::V1_1), + ("V2_0", age::V2_0), + ("V2_1", age::V2_1), + ("V3_0", age::V3_0), + ("V3_1", age::V3_1), + ("V3_2", age::V3_2), + ("V4_0", age::V4_0), + ("V4_1", age::V4_1), + ("V5_0", age::V5_0), + ("V5_1", age::V5_1), + ("V5_2", age::V5_2), + ("V6_0", age::V6_0), + ("V6_1", age::V6_1), + ("V6_2", age::V6_2), + ("V6_3", age::V6_3), + ("V7_0", age::V7_0), + ("V8_0", age::V8_0), + ("V9_0", age::V9_0), + ("V10_0", age::V10_0), + ]; + assert_eq!(AGES.len(), age::BY_NAME.len(), "ages are out of sync"); + + let pos = AGES.iter().position(|&(age, _)| canonical_age == age); + match pos { + None => Err(Error::PropertyValueNotFound), + Some(i) => Ok(AgeIter { ages: &AGES[..i+1] }), + } +} + +impl Iterator for AgeIter { + type Item = &'static [(char, char)]; + + fn next(&mut self) -> Option<&'static [(char, char)]> { + if self.ages.is_empty() { + None + } else { + let set = self.ages[0]; + self.ages = &self.ages[1..]; + Some(set.1) + } + } +} + +#[cfg(test)] +mod tests { + use super::{contains_simple_case_mapping, simple_fold}; + + #[test] + fn simple_fold_k() { + let xs: Vec = simple_fold('k').unwrap().collect(); + assert_eq!(xs, vec!['K', 'K']); + + let xs: Vec = simple_fold('K').unwrap().collect(); + assert_eq!(xs, vec!['k', 'K']); + + let xs: Vec = simple_fold('K').unwrap().collect(); + assert_eq!(xs, vec!['K', 'k']); + } + + #[test] + fn simple_fold_a() { + let xs: Vec = simple_fold('a').unwrap().collect(); + assert_eq!(xs, vec!['A']); + + let xs: Vec = simple_fold('A').unwrap().collect(); + assert_eq!(xs, vec!['a']); + } + + #[test] + fn simple_fold_empty() { + assert_eq!(Some('A'), simple_fold('?').unwrap_err()); + assert_eq!(Some('A'), simple_fold('@').unwrap_err()); + assert_eq!(Some('a'), simple_fold('[').unwrap_err()); + assert_eq!(Some('Ⰰ'), simple_fold('☃').unwrap_err()); + } + + #[test] + fn simple_fold_max() { + assert_eq!(None, simple_fold('\u{10FFFE}').unwrap_err()); + assert_eq!(None, simple_fold('\u{10FFFF}').unwrap_err()); + } + + #[test] + fn range_contains() { + assert!(contains_simple_case_mapping('A', 'A')); + assert!(contains_simple_case_mapping('Z', 'Z')); + assert!(contains_simple_case_mapping('A', 'Z')); + assert!(contains_simple_case_mapping('@', 'A')); + assert!(contains_simple_case_mapping('Z', '[')); + assert!(contains_simple_case_mapping('☃', 'Ⰰ')); + + assert!(!contains_simple_case_mapping('[', '[')); + assert!(!contains_simple_case_mapping('[', '`')); + + assert!(!contains_simple_case_mapping('☃', '☃')); + } + + #[test] + fn regression_466() { + use super::{CanonicalClassQuery, ClassQuery}; + + let q = ClassQuery::OneLetter('C'); + assert_eq!( + q.canonicalize().unwrap(), + CanonicalClassQuery::GeneralCategory("Other")); + } +} diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/age.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/age.rs new file mode 100644 index 0000000..afba3d3 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/age.rs @@ -0,0 +1,424 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate age tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("V10_0", V10_0), ("V1_1", V1_1), ("V2_0", V2_0), ("V2_1", V2_1), + ("V3_0", V3_0), ("V3_1", V3_1), ("V3_2", V3_2), ("V4_0", V4_0), + ("V4_1", V4_1), ("V5_0", V5_0), ("V5_1", V5_1), ("V5_2", V5_2), + ("V6_0", V6_0), ("V6_1", V6_1), ("V6_2", V6_2), ("V6_3", V6_3), + ("V7_0", V7_0), ("V8_0", V8_0), ("V9_0", V9_0), +]; + +pub const V10_0: &'static [(char, char)] = &[ + ('ࡠ', 'ࡪ'), ('ৼ', '৽'), ('ૺ', '૿'), ('ഀ', 'ഀ'), + ('഻', '഼'), ('᳷', '᳷'), ('᷶', '᷹'), ('₿', '₿'), + ('⏿', '⏿'), ('⯒', '⯒'), ('⹅', '⹉'), ('ㄮ', 'ㄮ'), + ('鿖', '鿪'), ('𐌭', '𐌯'), ('𑨀', '𑩇'), ('𑩐', '𑪃'), + ('𑪆', '𑪜'), ('𑪞', '𑪢'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), + ('𑴋', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵇'), + ('𑵐', '𑵙'), ('𖿡', '𖿡'), ('𛀂', '𛄞'), ('𛅰', '𛋻'), + ('🉠', '🉥'), ('🛓', '🛔'), ('🛷', '🛸'), ('🤀', '🤋'), + ('🤟', '🤟'), ('🤨', '🤯'), ('🤱', '🤲'), ('🥌', '🥌'), + ('🥟', '🥫'), ('🦒', '🦗'), ('🧐', '🧦'), ('𬺰', '𮯠'), +]; + +pub const V1_1: &'static [(char, char)] = &[ + ('\u{0}', 'ǵ'), ('Ǻ', 'ȗ'), ('ɐ', 'ʨ'), ('ʰ', '˞'), ('ˠ', '˩'), + ('̀', 'ͅ'), ('͠', '͡'), ('ʹ', '͵'), ('ͺ', 'ͺ'), (';', ';'), + ('΄', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ώ'), ('ϐ', 'ϖ'), + ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), ('Ϡ', 'Ϡ'), ('Ϣ', 'ϳ'), + ('Ё', 'Ќ'), ('Ў', 'я'), ('ё', 'ќ'), ('ў', '҆'), ('Ґ', 'ӄ'), + ('Ӈ', 'ӈ'), ('Ӌ', 'ӌ'), ('Ӑ', 'ӫ'), ('Ӯ', 'ӵ'), ('Ӹ', 'ӹ'), + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('։', '։'), ('ְ', 'ֹ'), + ('ֻ', '׃'), ('א', 'ת'), ('װ', '״'), ('،', '،'), ('؛', '؛'), + ('؟', '؟'), ('ء', 'غ'), ('ـ', 'ْ'), ('٠', '٭'), ('ٰ', 'ڷ'), + ('ں', 'ھ'), ('ۀ', 'ێ'), ('ې', 'ۭ'), ('۰', '۹'), ('ँ', 'ः'), + ('अ', 'ह'), ('़', '्'), ('ॐ', '॔'), ('क़', '॰'), + ('ঁ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), ('ও', 'ন'), + ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), ('়', '়'), + ('া', 'ৄ'), ('ে', 'ৈ'), ('ো', '্'), ('ৗ', 'ৗ'), + ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', '৺'), ('ਂ', 'ਂ'), + ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), + ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('਼', '਼'), + ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ਖ਼', 'ੜ'), + ('ਫ਼', 'ਫ਼'), ('੦', 'ੴ'), ('ઁ', 'ઃ'), ('અ', 'ઋ'), + ('ઍ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), + ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), ('ે', 'ૉ'), + ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૠ'), ('૦', '૯'), + ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), ('ଓ', 'ନ'), + ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଶ', 'ହ'), ('଼', 'ୃ'), + ('େ', 'ୈ'), ('ୋ', '୍'), ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), + ('ୟ', 'ୡ'), ('୦', '୰'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), + ('எ', 'ஐ'), ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), + ('ஞ', 'ட'), ('ண', 'த'), ('ந', 'ப'), ('ம', 'வ'), + ('ஷ', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), ('ொ', '்'), + ('ௗ', 'ௗ'), ('௧', '௲'), ('ఁ', 'ః'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'ళ'), ('వ', 'హ'), + ('ా', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), ('ౕ', 'ౖ'), + ('ౠ', 'ౡ'), ('౦', '౯'), ('ಂ', 'ಃ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('ಾ', 'ೄ'), ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), ('೦', '೯'), ('ം', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ന'), ('പ', 'ഹ'), + ('ാ', 'ൃ'), ('െ', 'ൈ'), ('ൊ', '്'), ('ൗ', 'ൗ'), + ('ൠ', 'ൡ'), ('൦', '൯'), ('ก', 'ฺ'), ('฿', '๛'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໝ'), ('Ⴀ', 'Ⴥ'), ('ა', 'ჶ'), + ('჻', '჻'), ('ᄀ', 'ᅙ'), ('ᅟ', 'ᆢ'), ('ᆨ', 'ᇹ'), + ('Ḁ', 'ẚ'), ('Ạ', 'ỹ'), ('ἀ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ῄ'), ('ῆ', 'ΐ'), ('ῖ', 'Ί'), ('῝', '`'), + ('ῲ', 'ῴ'), ('ῶ', '῾'), ('\u{2000}', '\u{202e}'), ('‰', '⁆'), + ('\u{206a}', '⁰'), ('⁴', '₎'), ('₠', '₪'), ('⃐', '⃡'), + ('℀', 'ℸ'), ('⅓', 'ↂ'), ('←', '⇪'), ('∀', '⋱'), + ('⌀', '⌀'), ('⌂', '⍺'), ('␀', '␤'), ('⑀', '⑊'), + ('①', '⓪'), ('─', '▕'), ('■', '◯'), ('☀', '☓'), + ('☚', '♯'), ('✁', '✄'), ('✆', '✉'), ('✌', '✧'), + ('✩', '❋'), ('❍', '❍'), ('❏', '❒'), ('❖', '❖'), + ('❘', '❞'), ('❡', '❧'), ('❶', '➔'), ('➘', '➯'), + ('➱', '➾'), ('\u{3000}', '〷'), ('〿', '〿'), ('ぁ', 'ゔ'), + ('゙', 'ゞ'), ('ァ', 'ヾ'), ('ㄅ', 'ㄬ'), ('ㄱ', 'ㆎ'), + ('㆐', '㆟'), ('㈀', '㈜'), ('㈠', '㉃'), ('㉠', '㉻'), + ('㉿', '㊰'), ('㋀', '㋋'), ('㋐', '㋾'), ('㌀', '㍶'), + ('㍻', '㏝'), ('㏠', '㏾'), ('一', '龥'), ('\u{e000}', '鶴'), + ('ff', 'st'), ('ﬓ', 'ﬗ'), ('ﬞ', 'זּ'), ('טּ', 'לּ'), + ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), + ('ﯓ', '﴿'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), + ('︠', '︣'), ('︰', '﹄'), ('﹉', '﹒'), ('﹔', '﹦'), + ('﹨', '﹫'), ('ﹰ', 'ﹲ'), ('ﹴ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('\u{feff}', '\u{feff}'), ('!', '~'), ('。', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('¢', '₩'), + ('│', '○'), ('�', '\u{ffff}'), +]; + +pub const V2_0: &'static [(char, char)] = &[ + ('֑', '֡'), ('֣', '֯'), ('ׄ', 'ׄ'), ('ༀ', 'ཇ'), ('ཉ', 'ཀྵ'), + ('ཱ', 'ྋ'), ('ྐ', 'ྕ'), ('ྗ', 'ྗ'), ('ྙ', 'ྭ'), + ('ྱ', 'ྷ'), ('ྐྵ', 'ྐྵ'), ('ẛ', 'ẛ'), ('₫', '₫'), + ('가', '힣'), ('\u{1fffe}', '\u{1ffff}'), ('\u{2fffe}', '\u{2ffff}'), + ('\u{3fffe}', '\u{3ffff}'), ('\u{4fffe}', '\u{4ffff}'), + ('\u{5fffe}', '\u{5ffff}'), ('\u{6fffe}', '\u{6ffff}'), + ('\u{7fffe}', '\u{7ffff}'), ('\u{8fffe}', '\u{8ffff}'), + ('\u{9fffe}', '\u{9ffff}'), ('\u{afffe}', '\u{affff}'), + ('\u{bfffe}', '\u{bffff}'), ('\u{cfffe}', '\u{cffff}'), + ('\u{dfffe}', '\u{dffff}'), ('\u{efffe}', '\u{10ffff}'), +]; + +pub const V2_1: &'static [(char, char)] = &[ + ('€', '€'), ('', ''), +]; + +pub const V3_0: &'static [(char, char)] = &[ + ('Ƕ', 'ǹ'), ('Ș', 'ȟ'), ('Ȣ', 'ȳ'), ('ʩ', 'ʭ'), ('˟', '˟'), + ('˪', 'ˮ'), ('͆', '͎'), ('͢', '͢'), ('ϗ', 'ϗ'), ('ϛ', 'ϛ'), + ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('Ѐ', 'Ѐ'), ('Ѝ', 'Ѝ'), + ('ѐ', 'ѐ'), ('ѝ', 'ѝ'), ('҈', '҉'), ('Ҍ', 'ҏ'), ('Ӭ', 'ӭ'), + ('֊', '֊'), ('ٓ', 'ٕ'), ('ڸ', 'ڹ'), ('ڿ', 'ڿ'), ('ۏ', 'ۏ'), + ('ۺ', '۾'), ('܀', '܍'), ('\u{70f}', 'ܬ'), ('ܰ', '݊'), ('ހ', 'ް'), + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), ('ා', 'ු'), + ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('ෲ', '෴'), ('ཪ', 'ཪ'), + ('ྖ', 'ྖ'), ('ྮ', 'ྰ'), ('ྸ', 'ྸ'), ('ྺ', 'ྼ'), + ('྾', '࿌'), ('࿏', '࿏'), ('က', 'အ'), ('ဣ', 'ဧ'), + ('ဩ', 'ဪ'), ('ာ', 'ဲ'), ('ံ', '္'), ('၀', 'ၙ'), + ('ሀ', 'ሆ'), ('ለ', 'ቆ'), ('ቈ', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኆ'), + ('ኈ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኮ'), ('ኰ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዎ'), ('ዐ', 'ዖ'), ('ዘ', 'ዮ'), ('ደ', 'ጎ'), + ('ጐ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ጞ'), ('ጠ', 'ፆ'), + ('ፈ', 'ፚ'), ('፡', '፼'), ('Ꭰ', 'Ᏼ'), ('ᐁ', 'ᙶ'), + ('\u{1680}', '᚜'), ('ᚠ', 'ᛰ'), ('ក', 'ៜ'), ('០', '៩'), + ('᠀', '\u{180e}'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢩ'), + ('\u{202f}', '\u{202f}'), ('⁈', '⁍'), ('₭', '₯'), ('⃢', '⃣'), + ('ℹ', '℺'), ('Ↄ', 'Ↄ'), ('⇫', '⇳'), ('⌁', '⌁'), + ('⍻', '⍻'), ('⍽', '⎚'), ('␥', '␦'), ('◰', '◷'), + ('☙', '☙'), ('♰', '♱'), ('⠀', '⣿'), ('⺀', '⺙'), + ('⺛', '⻳'), ('⼀', '⿕'), ('⿰', '⿻'), ('〸', '〺'), + ('〾', '〾'), ('ㆠ', 'ㆷ'), ('㐀', '䶵'), ('ꀀ', 'ꒌ'), + ('꒐', '꒡'), ('꒤', '꒳'), ('꒵', '꓀'), ('꓂', '꓄'), + ('꓆', '꓆'), ('יִ', 'יִ'), ('\u{fff9}', '\u{fffb}'), +]; + +pub const V3_1: &'static [(char, char)] = &[ + ('ϴ', 'ϵ'), ('\u{fdd0}', '\u{fdef}'), ('𐌀', '𐌞'), ('𐌠', '𐌣'), + ('𐌰', '𐍊'), ('𐐀', '𐐥'), ('𐐨', '𐑍'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄪', '𝇝'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓀'), ('𝓂', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚣'), ('𝚨', '𝟉'), ('𝟎', '𝟿'), + ('𠀀', '𪛖'), ('丽', '𪘀'), ('\u{e0001}', '\u{e0001}'), + ('\u{e0020}', '\u{e007f}'), +]; + +pub const V3_2: &'static [(char, char)] = &[ + ('Ƞ', 'Ƞ'), ('͏', '͏'), ('ͣ', 'ͯ'), ('Ϙ', 'ϙ'), ('϶', '϶'), + ('Ҋ', 'ҋ'), ('Ӆ', 'ӆ'), ('Ӊ', 'ӊ'), ('Ӎ', 'ӎ'), ('Ԁ', 'ԏ'), + ('ٮ', 'ٯ'), ('ޱ', 'ޱ'), ('ჷ', 'ჸ'), ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), + ('ᜠ', '᜶'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), + ('ᝲ', 'ᝳ'), ('⁇', '⁇'), ('⁎', '⁒'), ('⁗', '⁗'), + ('\u{205f}', '\u{2063}'), ('ⁱ', 'ⁱ'), ('₰', '₱'), ('⃤', '⃪'), + ('ℽ', '⅋'), ('⇴', '⇿'), ('⋲', '⋿'), ('⍼', '⍼'), + ('⎛', '⏎'), ('⓫', '⓾'), ('▖', '▟'), ('◸', '◿'), + ('☖', '☗'), ('♲', '♽'), ('⚀', '⚉'), ('❨', '❵'), + ('⟐', '⟫'), ('⟰', '⟿'), ('⤀', '⫿'), ('〻', '〽'), + ('ゕ', 'ゖ'), ('ゟ', '゠'), ('ヿ', 'ヿ'), ('ㇰ', 'ㇿ'), + ('㉑', '㉟'), ('㊱', '㊿'), ('꒢', '꒣'), ('꒴', '꒴'), + ('꓁', '꓁'), ('꓅', '꓅'), ('侮', '頻'), ('﷼', '﷼'), + ('︀', '️'), ('﹅', '﹆'), ('ﹳ', 'ﹳ'), ('⦅', '⦆'), +]; + +pub const V4_0: &'static [(char, char)] = &[ + ('ȡ', 'ȡ'), ('ȴ', 'ȶ'), ('ʮ', 'ʯ'), ('˯', '˿'), ('͐', '͗'), + ('͝', '͟'), ('Ϸ', 'ϻ'), ('\u{600}', '\u{603}'), ('؍', 'ؕ'), + ('ٖ', '٘'), ('ۮ', 'ۯ'), ('ۿ', 'ۿ'), ('ܭ', 'ܯ'), ('ݍ', 'ݏ'), + ('ऄ', 'ऄ'), ('ঽ', 'ঽ'), ('ਁ', 'ਁ'), ('ਃ', 'ਃ'), + ('ઌ', 'ઌ'), ('ૡ', 'ૣ'), ('૱', '૱'), ('ଵ', 'ଵ'), + ('ୱ', 'ୱ'), ('௳', '௺'), ('಼', 'ಽ'), ('៝', '៝'), + ('៰', '៹'), ('ᤀ', 'ᤜ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), + ('᥀', '᥀'), ('᥄', 'ᥭ'), ('ᥰ', 'ᥴ'), ('᧠', '᧿'), + ('ᴀ', 'ᵫ'), ('⁓', '⁔'), ('℻', '℻'), ('⏏', '⏐'), + ('⓿', '⓿'), ('☔', '☕'), ('⚊', '⚑'), ('⚠', '⚡'), + ('⬀', '⬍'), ('㈝', '㈞'), ('㉐', '㉐'), ('㉼', '㉽'), + ('㋌', '㋏'), ('㍷', '㍺'), ('㏞', '㏟'), ('㏿', '㏿'), + ('䷀', '䷿'), ('﷽', '﷽'), ('﹇', '﹈'), ('𐀀', '𐀋'), + ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), + ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐄀', '𐄂'), ('𐄇', '𐄳'), + ('𐄷', '𐄿'), ('𐎀', '𐎝'), ('𐎟', '𐎟'), ('𐐦', '𐐧'), + ('𐑎', '𐒝'), ('𐒠', '𐒩'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐠿'), + ('𝌀', '𝍖'), ('𝓁', '𝓁'), ('󠄀', '󠇯'), +]; + +pub const V4_1: &'static [(char, char)] = &[ + ('ȷ', 'Ɂ'), ('͘', '͜'), ('ϼ', 'Ͽ'), ('Ӷ', 'ӷ'), ('֢', '֢'), + ('ׅ', 'ׇ'), ('؋', '؋'), ('؞', '؞'), ('ٙ', 'ٞ'), ('ݐ', 'ݭ'), + ('ॽ', 'ॽ'), ('ৎ', 'ৎ'), ('ஶ', 'ஶ'), ('௦', '௦'), + ('࿐', '࿑'), ('ჹ', 'ჺ'), ('ჼ', 'ჼ'), ('ሇ', 'ሇ'), + ('ቇ', 'ቇ'), ('ኇ', 'ኇ'), ('ኯ', 'ኯ'), ('ዏ', 'ዏ'), + ('ዯ', 'ዯ'), ('ጏ', 'ጏ'), ('ጟ', 'ጟ'), ('ፇ', 'ፇ'), + ('፟', '፠'), ('ᎀ', '᎙'), ('ᦀ', 'ᦩ'), ('ᦰ', 'ᧉ'), + ('᧐', '᧙'), ('᧞', '᧟'), ('ᨀ', 'ᨛ'), ('᨞', '᨟'), + ('ᵬ', '᷃'), ('⁕', '⁖'), ('⁘', '⁞'), ('ₐ', 'ₔ'), + ('₲', '₵'), ('⃫', '⃫'), ('ℼ', 'ℼ'), ('⅌', '⅌'), + ('⏑', '⏛'), ('☘', '☘'), ('♾', '♿'), ('⚒', '⚜'), + ('⚢', '⚱'), ('⟀', '⟆'), ('⬎', '⬓'), ('Ⰰ', 'Ⱞ'), + ('ⰰ', 'ⱞ'), ('Ⲁ', '⳪'), ('⳹', 'ⴥ'), ('ⴰ', 'ⵥ'), + ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), + ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), + ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('⸀', '⸗'), ('⸜', '⸝'), + ('㇀', '㇏'), ('㉾', '㉾'), ('龦', '龻'), ('꜀', '꜖'), + ('ꠀ', '꠫'), ('並', '龎'), ('︐', '︙'), ('𐅀', '𐆊'), + ('𐎠', '𐏃'), ('𐏈', '𐏕'), ('𐨀', '𐨃'), ('𐨅', '𐨆'), + ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐨸', '𐨺'), + ('𐨿', '𐩇'), ('𐩐', '𐩘'), ('𝈀', '𝉅'), ('𝚤', '𝚥'), +]; + +pub const V5_0: &'static [(char, char)] = &[ + ('ɂ', 'ɏ'), ('ͻ', 'ͽ'), ('ӏ', 'ӏ'), ('Ӻ', 'ӿ'), ('Ԑ', 'ԓ'), + ('ֺ', 'ֺ'), ('߀', 'ߺ'), ('ॻ', 'ॼ'), ('ॾ', 'ॿ'), ('ೢ', 'ೣ'), + ('ೱ', 'ೲ'), ('ᬀ', 'ᭋ'), ('᭐', '᭼'), ('᷄', '᷊'), + ('᷾', '᷿'), ('⃬', '⃯'), ('⅍', 'ⅎ'), ('ↄ', 'ↄ'), + ('⏜', '⏧'), ('⚲', '⚲'), ('⟇', '⟊'), ('⬔', '⬚'), + ('⬠', '⬣'), ('Ⱡ', 'ⱬ'), ('ⱴ', 'ⱷ'), ('ꜗ', 'ꜚ'), + ('꜠', '꜡'), ('ꡀ', '꡷'), ('𐤀', '𐤙'), ('𐤟', '𐤟'), + ('𒀀', '𒍮'), ('𒐀', '𒑢'), ('𒑰', '𒑳'), ('𝍠', '𝍱'), + ('𝟊', '𝟋'), +]; + +pub const V5_1: &'static [(char, char)] = &[ + ('Ͱ', 'ͳ'), ('Ͷ', 'ͷ'), ('Ϗ', 'Ϗ'), ('҇', '҇'), ('Ԕ', 'ԣ'), + ('؆', '؊'), ('ؖ', 'ؚ'), ('ػ', 'ؿ'), ('ݮ', 'ݿ'), ('ॱ', 'ॲ'), + ('ੑ', 'ੑ'), ('ੵ', 'ੵ'), ('ୄ', 'ୄ'), ('ୢ', 'ୣ'), + ('ௐ', 'ௐ'), ('ఽ', 'ఽ'), ('ౘ', 'ౙ'), ('ౢ', 'ౣ'), + ('౸', '౿'), ('ഽ', 'ഽ'), ('ൄ', 'ൄ'), ('ൢ', 'ൣ'), + ('൰', '൵'), ('൹', 'ൿ'), ('ཫ', 'ཬ'), ('࿎', '࿎'), + ('࿒', '࿔'), ('ဢ', 'ဢ'), ('ဨ', 'ဨ'), ('ါ', 'ါ'), + ('ဳ', 'ဵ'), ('်', 'ဿ'), ('ၚ', '႙'), ('႞', '႟'), + ('ᢪ', 'ᢪ'), ('ᮀ', '᮪'), ('ᮮ', '᮹'), ('ᰀ', '᰷'), + ('᰻', '᱉'), ('ᱍ', '᱿'), ('᷋', 'ᷦ'), ('ẜ', 'ẟ'), + ('Ỻ', 'ỿ'), ('\u{2064}', '\u{2064}'), ('⃰', '⃰'), ('⅏', '⅏'), + ('ↅ', 'ↈ'), ('⚝', '⚝'), ('⚳', '⚼'), ('⛀', '⛃'), + ('⟌', '⟌'), ('⟬', '⟯'), ('⬛', '⬟'), ('⬤', '⭌'), + ('⭐', '⭔'), ('Ɑ', 'Ɐ'), ('ⱱ', 'ⱳ'), ('ⱸ', 'ⱽ'), + ('ⷠ', 'ⷿ'), ('⸘', '⸛'), ('⸞', '⸰'), ('ㄭ', 'ㄭ'), + ('㇐', '㇣'), ('龼', '鿃'), ('ꔀ', 'ꘫ'), ('Ꙁ', 'ꙟ'), + ('Ꙣ', '꙳'), ('꙼', 'ꚗ'), ('ꜛ', 'ꜟ'), ('Ꜣ', 'ꞌ'), + ('ꟻ', 'ꟿ'), ('ꢀ', '꣄'), ('꣎', '꣙'), ('꤀', '꥓'), + ('꥟', '꥟'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), + ('꩜', '꩟'), ('︤', '︦'), ('𐆐', '𐆛'), ('𐇐', '𐇽'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐤠', '𐤹'), ('𐤿', '𐤿'), + ('𝄩', '𝄩'), ('🀀', '🀫'), ('🀰', '🂓'), +]; + +pub const V5_2: &'static [(char, char)] = &[ + ('Ԥ', 'ԥ'), ('ࠀ', '࠭'), ('࠰', '࠾'), ('ऀ', 'ऀ'), + ('ॎ', 'ॎ'), ('ॕ', 'ॕ'), ('ॹ', 'ॺ'), ('৻', '৻'), + ('࿕', '࿘'), ('ႚ', 'ႝ'), ('ᅚ', 'ᅞ'), ('ᆣ', 'ᆧ'), + ('ᇺ', 'ᇿ'), ('᐀', '᐀'), ('ᙷ', 'ᙿ'), ('ᢰ', 'ᣵ'), + ('ᦪ', 'ᦫ'), ('᧚', '᧚'), ('ᨠ', 'ᩞ'), ('᩠', '᩼'), + ('᩿', '᪉'), ('᪐', '᪙'), ('᪠', '᪭'), ('᳐', 'ᳲ'), + ('᷽', '᷽'), ('₶', '₸'), ('⅐', '⅒'), ('↉', '↉'), + ('⏨', '⏨'), ('⚞', '⚟'), ('⚽', '⚿'), ('⛄', '⛍'), + ('⛏', '⛡'), ('⛣', '⛣'), ('⛨', '⛿'), ('❗', '❗'), + ('⭕', '⭙'), ('Ɒ', 'Ɒ'), ('Ȿ', 'Ɀ'), ('Ⳬ', '⳱'), + ('⸱', '⸱'), ('㉄', '㉏'), ('鿄', '鿋'), ('ꓐ', '꓿'), + ('ꚠ', '꛷'), ('꠰', '꠹'), ('꣠', 'ꣻ'), ('ꥠ', 'ꥼ'), + ('ꦀ', '꧍'), ('ꧏ', '꧙'), ('꧞', '꧟'), ('ꩠ', 'ꩻ'), + ('ꪀ', 'ꫂ'), ('ꫛ', '꫟'), ('ꯀ', '꯭'), ('꯰', '꯹'), + ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('恵', '舘'), ('𐡀', '𐡕'), + ('𐡗', '𐡟'), ('𐤚', '𐤛'), ('𐩠', '𐩿'), ('𐬀', '𐬵'), + ('𐬹', '𐭕'), ('𐭘', '𐭲'), ('𐭸', '𐭿'), ('𐰀', '𐱈'), + ('𐹠', '𐹾'), ('𑂀', '𑃁'), ('𓀀', '𓐮'), ('🄀', '🄊'), + ('🄐', '🄮'), ('🄱', '🄱'), ('🄽', '🄽'), ('🄿', '🄿'), + ('🅂', '🅂'), ('🅆', '🅆'), ('🅊', '🅎'), ('🅗', '🅗'), + ('🅟', '🅟'), ('🅹', '🅹'), ('🅻', '🅼'), ('🅿', '🅿'), + ('🆊', '🆍'), ('🆐', '🆐'), ('🈀', '🈀'), ('🈐', '🈱'), + ('🉀', '🉈'), ('𪜀', '𫜴'), +]; + +pub const V6_0: &'static [(char, char)] = &[ + ('Ԧ', 'ԧ'), ('ؠ', 'ؠ'), ('ٟ', 'ٟ'), ('ࡀ', '࡛'), ('࡞', '࡞'), + ('ऺ', 'ऻ'), ('ॏ', 'ॏ'), ('ॖ', 'ॗ'), ('ॳ', 'ॷ'), + ('୲', '୷'), ('ഩ', 'ഩ'), ('ഺ', 'ഺ'), ('ൎ', 'ൎ'), + ('ྌ', 'ྏ'), ('࿙', '࿚'), ('፝', '፞'), ('ᯀ', '᯳'), + ('᯼', '᯿'), ('᷼', '᷼'), ('ₕ', 'ₜ'), ('₹', '₹'), + ('⏩', '⏳'), ('⛎', '⛎'), ('⛢', '⛢'), ('⛤', '⛧'), + ('✅', '✅'), ('✊', '✋'), ('✨', '✨'), ('❌', '❌'), + ('❎', '❎'), ('❓', '❕'), ('❟', '❠'), ('➕', '➗'), + ('➰', '➰'), ('➿', '➿'), ('⟎', '⟏'), ('⵰', '⵰'), + ('⵿', '⵿'), ('ㆸ', 'ㆺ'), ('Ꙡ', 'ꙡ'), ('Ɥ', 'ꞎ'), + ('Ꞑ', 'ꞑ'), ('Ꞡ', 'ꞩ'), ('ꟺ', 'ꟺ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), + ('﮲', '﯁'), ('𑀀', '𑁍'), ('𑁒', '𑁯'), ('𖠀', '𖨸'), + ('𛀀', '𛀁'), ('🂠', '🂮'), ('🂱', '🂾'), ('🃁', '🃏'), + ('🃑', '🃟'), ('🄰', '🄰'), ('🄲', '🄼'), ('🄾', '🄾'), + ('🅀', '🅁'), ('🅃', '🅅'), ('🅇', '🅉'), ('🅏', '🅖'), + ('🅘', '🅞'), ('🅠', '🅩'), ('🅰', '🅸'), ('🅺', '🅺'), + ('🅽', '🅾'), ('🆀', '🆉'), ('🆎', '🆏'), ('🆑', '🆚'), + ('🇦', '🇿'), ('🈁', '🈂'), ('🈲', '🈺'), ('🉐', '🉑'), + ('🌀', '🌠'), ('🌰', '🌵'), ('🌷', '🍼'), ('🎀', '🎓'), + ('🎠', '🏄'), ('🏆', '🏊'), ('🏠', '🏰'), ('🐀', '🐾'), + ('👀', '👀'), ('👂', '📷'), ('📹', '📼'), ('🔀', '🔽'), + ('🕐', '🕧'), ('🗻', '🗿'), ('😁', '😐'), ('😒', '😔'), + ('😖', '😖'), ('😘', '😘'), ('😚', '😚'), ('😜', '😞'), + ('😠', '😥'), ('😨', '😫'), ('😭', '😭'), ('😰', '😳'), + ('😵', '🙀'), ('🙅', '🙏'), ('🚀', '🛅'), ('🜀', '🝳'), + ('𫝀', '𫠝'), +]; + +pub const V6_1: &'static [(char, char)] = &[ + ('֏', '֏'), ('\u{604}', '\u{604}'), ('ࢠ', 'ࢠ'), ('ࢢ', 'ࢬ'), + ('ࣤ', 'ࣾ'), ('૰', '૰'), ('ໞ', 'ໟ'), ('Ⴧ', 'Ⴧ'), + ('Ⴭ', 'Ⴭ'), ('ჽ', 'ჿ'), ('᮫', 'ᮭ'), ('ᮺ', 'ᮿ'), + ('᳀', '᳇'), ('ᳳ', 'ᳶ'), ('⟋', '⟋'), ('⟍', '⟍'), + ('Ⳳ', 'ⳳ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⵦ', 'ⵧ'), + ('⸲', '⸻'), ('鿌', '鿌'), ('ꙴ', 'ꙻ'), ('ꚟ', 'ꚟ'), + ('Ꞓ', 'ꞓ'), ('Ɦ', 'Ɦ'), ('ꟸ', 'ꟹ'), ('ꫠ', '꫶'), + ('郞', '隷'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𑃐', '𑃨'), + ('𑃰', '𑃹'), ('𑄀', '𑄴'), ('𑄶', '𑅃'), ('𑆀', '𑇈'), + ('𑇐', '𑇙'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), ('𖼀', '𖽄'), + ('𖽐', '𖽾'), ('𖾏', '𖾟'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), + ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), + ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), + ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), + ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), + ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), + ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), + ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), + ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), + ('🅪', '🅫'), ('🕀', '🕃'), ('😀', '😀'), ('😑', '😑'), + ('😕', '😕'), ('😗', '😗'), ('😙', '😙'), ('😛', '😛'), + ('😟', '😟'), ('😦', '😧'), ('😬', '😬'), ('😮', '😯'), + ('😴', '😴'), +]; + +pub const V6_2: &'static [(char, char)] = &[ + ('₺', '₺'), +]; + +pub const V6_3: &'static [(char, char)] = &[ + ('\u{61c}', '\u{61c}'), ('\u{2066}', '\u{2069}'), +]; + +pub const V7_0: &'static [(char, char)] = &[ + ('Ϳ', 'Ϳ'), ('Ԩ', 'ԯ'), ('֍', '֎'), ('\u{605}', '\u{605}'), + ('ࢡ', 'ࢡ'), ('ࢭ', 'ࢲ'), ('ࣿ', 'ࣿ'), ('ॸ', 'ॸ'), + ('ঀ', 'ঀ'), ('ఀ', 'ఀ'), ('ఴ', 'ఴ'), ('ಁ', 'ಁ'), + ('ഁ', 'ഁ'), ('෦', '෯'), ('ᛱ', 'ᛸ'), ('ᤝ', 'ᤞ'), + ('᪰', '᪾'), ('᳸', '᳹'), ('ᷧ', '᷵'), ('₻', '₽'), + ('⏴', '⏺'), ('✀', '✀'), ('⭍', '⭏'), ('⭚', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯑'), + ('⸼', '⹂'), ('Ꚙ', 'ꚝ'), ('ꞔ', 'ꞟ'), ('Ɜ', 'Ɬ'), + ('Ʞ', 'Ʇ'), ('ꟷ', 'ꟷ'), ('ꧠ', 'ꧾ'), ('ꩼ', 'ꩿ'), + ('ꬰ', 'ꭟ'), ('ꭤ', 'ꭥ'), ('︧', '︭'), ('𐆋', '𐆌'), + ('𐆠', '𐆠'), ('𐋠', '𐋻'), ('𐌟', '𐌟'), ('𐍐', '𐍺'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐕯', '𐕯'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐡠', '𐢞'), ('𐢧', '𐢯'), + ('𐪀', '𐪟'), ('𐫀', '𐫦'), ('𐫫', '𐫶'), ('𐮀', '𐮑'), + ('𐮙', '𐮜'), ('𐮩', '𐮯'), ('𑁿', '𑁿'), ('𑅐', '𑅶'), + ('𑇍', '𑇍'), ('𑇚', '𑇚'), ('𑇡', '𑇴'), ('𑈀', '𑈑'), + ('𑈓', '𑈽'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), ('𑌁', '𑌃'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), + ('𑍋', '𑍍'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), ('𑒀', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖵'), + ('𑖸', '𑗉'), ('𑘀', '𑙄'), ('𑙐', '𑙙'), ('𑢠', '𑣲'), + ('𑣿', '𑣿'), ('𑫀', '𑫸'), ('𒍯', '𒎘'), ('𒑣', '𒑮'), + ('𒑴', '𒑴'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖩮', '𖩯'), + ('𖫐', '𖫭'), ('𖫰', '𖫵'), ('𖬀', '𖭅'), ('𖭐', '𖭙'), + ('𖭛', '𖭡'), ('𖭣', '𖭷'), ('𖭽', '𖮏'), ('𛰀', '𛱪'), + ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𛲜', '\u{1bca3}'), + ('𞠀', '𞣄'), ('𞣇', '𞣖'), ('🂿', '🂿'), ('🃠', '🃵'), + ('🄋', '🄌'), ('🌡', '🌬'), ('🌶', '🌶'), ('🍽', '🍽'), + ('🎔', '🎟'), ('🏅', '🏅'), ('🏋', '🏎'), ('🏔', '🏟'), + ('🏱', '🏷'), ('🐿', '🐿'), ('👁', '👁'), ('📸', '📸'), + ('📽', '📾'), ('🔾', '🔿'), ('🕄', '🕊'), ('🕨', '🕹'), + ('🕻', '🖣'), ('🖥', '🗺'), ('🙁', '🙂'), ('🙐', '🙿'), + ('🛆', '🛏'), ('🛠', '🛬'), ('🛰', '🛳'), ('🞀', '🟔'), + ('🠀', '🠋'), ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), + ('🢐', '🢭'), +]; + +pub const V8_0: &'static [(char, char)] = &[ + ('ࢳ', 'ࢴ'), ('ࣣ', 'ࣣ'), ('ૹ', 'ૹ'), ('ౚ', 'ౚ'), + ('ൟ', 'ൟ'), ('Ᏽ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('₾', '₾'), + ('↊', '↋'), ('⯬', '⯯'), ('鿍', '鿕'), ('ꚞ', 'ꚞ'), + ('ꞏ', 'ꞏ'), ('Ʝ', 'ꞷ'), ('꣼', 'ꣽ'), ('ꭠ', 'ꭣ'), + ('ꭰ', 'ꮿ'), ('︮', '︯'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐣻', '𐣿'), ('𐦼', '𐦽'), ('𐧀', '𐧏'), ('𐧒', '𐧿'), + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), ('𑇉', '𑇌'), + ('𑇛', '𑇟'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊩'), ('𑌀', '𑌀'), ('𑍐', '𑍐'), + ('𑗊', '𑗝'), ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜿'), + ('𒎙', '𒎙'), ('𒒀', '𒕃'), ('𔐀', '𔙆'), ('𝇞', '𝇨'), + ('𝠀', '𝪋'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('🌭', '🌯'), + ('🍾', '🍿'), ('🏏', '🏓'), ('🏸', '🏿'), ('📿', '📿'), + ('🕋', '🕏'), ('🙃', '🙄'), ('🛐', '🛐'), ('🤐', '🤘'), + ('🦀', '🦄'), ('🧀', '🧀'), ('𫠠', '𬺡'), +]; + +pub const V9_0: &'static [(char, char)] = &[ + ('ࢶ', 'ࢽ'), ('ࣔ', '\u{8e2}'), ('ಀ', 'ಀ'), ('൏', '൏'), + ('ൔ', 'ൖ'), ('൘', '൞'), ('൶', '൸'), ('ᲀ', 'ᲈ'), + ('᷻', '᷻'), ('⏻', '⏾'), ('⹃', '⹄'), ('Ɪ', 'Ɪ'), + ('ꣅ', 'ꣅ'), ('𐆍', '𐆎'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𑈾', '𑈾'), ('𑐀', '𑑙'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), + ('𑙠', '𑙬'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱅'), + ('𑱐', '𑱬'), ('𑱰', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), + ('𖿠', '𖿠'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𞀀', '𞀆'), + ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), + ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞥞', '𞥟'), ('🆛', '🆬'), + ('🈻', '🈻'), ('🕺', '🕺'), ('🖤', '🖤'), ('🛑', '🛒'), + ('🛴', '🛶'), ('🤙', '🤞'), ('🤠', '🤧'), ('🤰', '🤰'), + ('🤳', '🤾'), ('🥀', '🥋'), ('🥐', '🥞'), ('🦅', '🦑'), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/case_folding_simple.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/case_folding_simple.rs new file mode 100644 index 0000000..72ec79f --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/case_folding_simple.rs @@ -0,0 +1,662 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate case-folding-simple /home/andrew/tmp/ucd-10.0.0/ --chars --all-pairs +// +// ucd-generate is available on crates.io. + +pub const CASE_FOLDING_SIMPLE: &'static [(char, &'static [char])] = &[ + ('A', &['a']), ('B', &['b']), ('C', &['c']), ('D', &['d']), ('E', &['e']), + ('F', &['f']), ('G', &['g']), ('H', &['h']), ('I', &['i']), ('J', &['j']), + ('K', &['k', 'K', ]), ('L', &['l']), ('M', &['m']), ('N', &['n']), ('O', &[ + 'o']), ('P', &['p']), ('Q', &['q']), ('R', &['r']), ('S', &['s', 'ſ', ]), + ('T', &['t']), ('U', &['u']), ('V', &['v']), ('W', &['w']), ('X', &['x']), + ('Y', &['y']), ('Z', &['z']), ('a', &['A']), ('b', &['B']), ('c', &['C']), + ('d', &['D']), ('e', &['E']), ('f', &['F']), ('g', &['G']), ('h', &['H']), + ('i', &['I']), ('j', &['J']), ('k', &['K', 'K', ]), ('l', &['L']), ('m', &[ + 'M']), ('n', &['N']), ('o', &['O']), ('p', &['P']), ('q', &['Q']), ('r', &[ + 'R']), ('s', &['S', 'ſ', ]), ('t', &['T']), ('u', &['U']), ('v', &['V']), + ('w', &['W']), ('x', &['X']), ('y', &['Y']), ('z', &['Z']), ('µ', &['Μ', + 'μ', ]), ('À', &['à']), ('Á', &['á']), ('Â', &['â']), ('Ã', &['ã' + ]), ('Ä', &['ä']), ('Å', &['å', 'Å', ]), ('Æ', &['æ']), ('Ç', &['ç' + ]), ('È', &['è']), ('É', &['é']), ('Ê', &['ê']), ('Ë', &['ë']), + ('Ì', &['ì']), ('Í', &['í']), ('Î', &['î']), ('Ï', &['ï']), ('Ð', &[ + 'ð']), ('Ñ', &['ñ']), ('Ò', &['ò']), ('Ó', &['ó']), ('Ô', &['ô']), + ('Õ', &['õ']), ('Ö', &['ö']), ('Ø', &['ø']), ('Ù', &['ù']), ('Ú', &[ + 'ú']), ('Û', &['û']), ('Ü', &['ü']), ('Ý', &['ý']), ('Þ', &['þ']), + ('ß', &['ẞ']), ('à', &['À']), ('á', &['Á']), ('â', &['Â']), + ('ã', &['Ã']), ('ä', &['Ä']), ('å', &['Å', 'Å', ]), ('æ', &['Æ']), + ('ç', &['Ç']), ('è', &['È']), ('é', &['É']), ('ê', &['Ê']), ('ë', &[ + 'Ë']), ('ì', &['Ì']), ('í', &['Í']), ('î', &['Î']), ('ï', &['Ï']), + ('ð', &['Ð']), ('ñ', &['Ñ']), ('ò', &['Ò']), ('ó', &['Ó']), ('ô', &[ + 'Ô']), ('õ', &['Õ']), ('ö', &['Ö']), ('ø', &['Ø']), ('ù', &['Ù']), + ('ú', &['Ú']), ('û', &['Û']), ('ü', &['Ü']), ('ý', &['Ý']), ('þ', &[ + 'Þ']), ('ÿ', &['Ÿ']), ('Ā', &['ā']), ('ā', &['Ā']), ('Ă', &['ă']), + ('ă', &['Ă']), ('Ą', &['ą']), ('ą', &['Ą']), ('Ć', &['ć']), ('ć', &[ + 'Ć']), ('Ĉ', &['ĉ']), ('ĉ', &['Ĉ']), ('Ċ', &['ċ']), ('ċ', &['Ċ']), + ('Č', &['č']), ('č', &['Č']), ('Ď', &['ď']), ('ď', &['Ď']), ('Đ', &[ + 'đ']), ('đ', &['Đ']), ('Ē', &['ē']), ('ē', &['Ē']), ('Ĕ', &['ĕ']), + ('ĕ', &['Ĕ']), ('Ė', &['ė']), ('ė', &['Ė']), ('Ę', &['ę']), ('ę', &[ + 'Ę']), ('Ě', &['ě']), ('ě', &['Ě']), ('Ĝ', &['ĝ']), ('ĝ', &['Ĝ']), + ('Ğ', &['ğ']), ('ğ', &['Ğ']), ('Ġ', &['ġ']), ('ġ', &['Ġ']), ('Ģ', &[ + 'ģ']), ('ģ', &['Ģ']), ('Ĥ', &['ĥ']), ('ĥ', &['Ĥ']), ('Ħ', &['ħ']), + ('ħ', &['Ħ']), ('Ĩ', &['ĩ']), ('ĩ', &['Ĩ']), ('Ī', &['ī']), ('ī', &[ + 'Ī']), ('Ĭ', &['ĭ']), ('ĭ', &['Ĭ']), ('Į', &['į']), ('į', &['Į']), + ('IJ', &['ij']), ('ij', &['IJ']), ('Ĵ', &['ĵ']), ('ĵ', &['Ĵ']), ('Ķ', &[ + 'ķ']), ('ķ', &['Ķ']), ('Ĺ', &['ĺ']), ('ĺ', &['Ĺ']), ('Ļ', &['ļ']), + ('ļ', &['Ļ']), ('Ľ', &['ľ']), ('ľ', &['Ľ']), ('Ŀ', &['ŀ']), ('ŀ', &[ + 'Ŀ']), ('Ł', &['ł']), ('ł', &['Ł']), ('Ń', &['ń']), ('ń', &['Ń']), + ('Ņ', &['ņ']), ('ņ', &['Ņ']), ('Ň', &['ň']), ('ň', &['Ň']), ('Ŋ', &[ + 'ŋ']), ('ŋ', &['Ŋ']), ('Ō', &['ō']), ('ō', &['Ō']), ('Ŏ', &['ŏ']), + ('ŏ', &['Ŏ']), ('Ő', &['ő']), ('ő', &['Ő']), ('Œ', &['œ']), ('œ', &[ + 'Œ']), ('Ŕ', &['ŕ']), ('ŕ', &['Ŕ']), ('Ŗ', &['ŗ']), ('ŗ', &['Ŗ']), + ('Ř', &['ř']), ('ř', &['Ř']), ('Ś', &['ś']), ('ś', &['Ś']), ('Ŝ', &[ + 'ŝ']), ('ŝ', &['Ŝ']), ('Ş', &['ş']), ('ş', &['Ş']), ('Š', &['š']), + ('š', &['Š']), ('Ţ', &['ţ']), ('ţ', &['Ţ']), ('Ť', &['ť']), ('ť', &[ + 'Ť']), ('Ŧ', &['ŧ']), ('ŧ', &['Ŧ']), ('Ũ', &['ũ']), ('ũ', &['Ũ']), + ('Ū', &['ū']), ('ū', &['Ū']), ('Ŭ', &['ŭ']), ('ŭ', &['Ŭ']), ('Ů', &[ + 'ů']), ('ů', &['Ů']), ('Ű', &['ű']), ('ű', &['Ű']), ('Ų', &['ų']), + ('ų', &['Ų']), ('Ŵ', &['ŵ']), ('ŵ', &['Ŵ']), ('Ŷ', &['ŷ']), ('ŷ', &[ + 'Ŷ']), ('Ÿ', &['ÿ']), ('Ź', &['ź']), ('ź', &['Ź']), ('Ż', &['ż']), + ('ż', &['Ż']), ('Ž', &['ž']), ('ž', &['Ž']), ('ſ', &['S', 's', ]), + ('ƀ', &['Ƀ']), ('Ɓ', &['ɓ']), ('Ƃ', &['ƃ']), ('ƃ', &['Ƃ']), ('Ƅ', &[ + 'ƅ']), ('ƅ', &['Ƅ']), ('Ɔ', &['ɔ']), ('Ƈ', &['ƈ']), ('ƈ', &['Ƈ']), + ('Ɖ', &['ɖ']), ('Ɗ', &['ɗ']), ('Ƌ', &['ƌ']), ('ƌ', &['Ƌ']), ('Ǝ', &[ + 'ǝ']), ('Ə', &['ə']), ('Ɛ', &['ɛ']), ('Ƒ', &['ƒ']), ('ƒ', &['Ƒ']), + ('Ɠ', &['ɠ']), ('Ɣ', &['ɣ']), ('ƕ', &['Ƕ']), ('Ɩ', &['ɩ']), ('Ɨ', &[ + 'ɨ']), ('Ƙ', &['ƙ']), ('ƙ', &['Ƙ']), ('ƚ', &['Ƚ']), ('Ɯ', &['ɯ']), + ('Ɲ', &['ɲ']), ('ƞ', &['Ƞ']), ('Ɵ', &['ɵ']), ('Ơ', &['ơ']), ('ơ', &[ + 'Ơ']), ('Ƣ', &['ƣ']), ('ƣ', &['Ƣ']), ('Ƥ', &['ƥ']), ('ƥ', &['Ƥ']), + ('Ʀ', &['ʀ']), ('Ƨ', &['ƨ']), ('ƨ', &['Ƨ']), ('Ʃ', &['ʃ']), ('Ƭ', &[ + 'ƭ']), ('ƭ', &['Ƭ']), ('Ʈ', &['ʈ']), ('Ư', &['ư']), ('ư', &['Ư']), + ('Ʊ', &['ʊ']), ('Ʋ', &['ʋ']), ('Ƴ', &['ƴ']), ('ƴ', &['Ƴ']), ('Ƶ', &[ + 'ƶ']), ('ƶ', &['Ƶ']), ('Ʒ', &['ʒ']), ('Ƹ', &['ƹ']), ('ƹ', &['Ƹ']), + ('Ƽ', &['ƽ']), ('ƽ', &['Ƽ']), ('ƿ', &['Ƿ']), ('DŽ', &['Dž', 'dž', ]), + ('Dž', &['DŽ', 'dž', ]), ('dž', &['DŽ', 'Dž', ]), ('LJ', &['Lj', 'lj', ]), + ('Lj', &['LJ', 'lj', ]), ('lj', &['LJ', 'Lj', ]), ('NJ', &['Nj', 'nj', ]), + ('Nj', &['NJ', 'nj', ]), ('nj', &['NJ', 'Nj', ]), ('Ǎ', &['ǎ']), ('ǎ', &[ + 'Ǎ']), ('Ǐ', &['ǐ']), ('ǐ', &['Ǐ']), ('Ǒ', &['ǒ']), ('ǒ', &['Ǒ']), + ('Ǔ', &['ǔ']), ('ǔ', &['Ǔ']), ('Ǖ', &['ǖ']), ('ǖ', &['Ǖ']), ('Ǘ', &[ + 'ǘ']), ('ǘ', &['Ǘ']), ('Ǚ', &['ǚ']), ('ǚ', &['Ǚ']), ('Ǜ', &['ǜ']), + ('ǜ', &['Ǜ']), ('ǝ', &['Ǝ']), ('Ǟ', &['ǟ']), ('ǟ', &['Ǟ']), ('Ǡ', &[ + 'ǡ']), ('ǡ', &['Ǡ']), ('Ǣ', &['ǣ']), ('ǣ', &['Ǣ']), ('Ǥ', &['ǥ']), + ('ǥ', &['Ǥ']), ('Ǧ', &['ǧ']), ('ǧ', &['Ǧ']), ('Ǩ', &['ǩ']), ('ǩ', &[ + 'Ǩ']), ('Ǫ', &['ǫ']), ('ǫ', &['Ǫ']), ('Ǭ', &['ǭ']), ('ǭ', &['Ǭ']), + ('Ǯ', &['ǯ']), ('ǯ', &['Ǯ']), ('DZ', &['Dz', 'dz', ]), ('Dz', &['DZ', + 'dz', ]), ('dz', &['DZ', 'Dz', ]), ('Ǵ', &['ǵ']), ('ǵ', &['Ǵ']), + ('Ƕ', &['ƕ']), ('Ƿ', &['ƿ']), ('Ǹ', &['ǹ']), ('ǹ', &['Ǹ']), ('Ǻ', &[ + 'ǻ']), ('ǻ', &['Ǻ']), ('Ǽ', &['ǽ']), ('ǽ', &['Ǽ']), ('Ǿ', &['ǿ']), + ('ǿ', &['Ǿ']), ('Ȁ', &['ȁ']), ('ȁ', &['Ȁ']), ('Ȃ', &['ȃ']), ('ȃ', &[ + 'Ȃ']), ('Ȅ', &['ȅ']), ('ȅ', &['Ȅ']), ('Ȇ', &['ȇ']), ('ȇ', &['Ȇ']), + ('Ȉ', &['ȉ']), ('ȉ', &['Ȉ']), ('Ȋ', &['ȋ']), ('ȋ', &['Ȋ']), ('Ȍ', &[ + 'ȍ']), ('ȍ', &['Ȍ']), ('Ȏ', &['ȏ']), ('ȏ', &['Ȏ']), ('Ȑ', &['ȑ']), + ('ȑ', &['Ȑ']), ('Ȓ', &['ȓ']), ('ȓ', &['Ȓ']), ('Ȕ', &['ȕ']), ('ȕ', &[ + 'Ȕ']), ('Ȗ', &['ȗ']), ('ȗ', &['Ȗ']), ('Ș', &['ș']), ('ș', &['Ș']), + ('Ț', &['ț']), ('ț', &['Ț']), ('Ȝ', &['ȝ']), ('ȝ', &['Ȝ']), ('Ȟ', &[ + 'ȟ']), ('ȟ', &['Ȟ']), ('Ƞ', &['ƞ']), ('Ȣ', &['ȣ']), ('ȣ', &['Ȣ']), + ('Ȥ', &['ȥ']), ('ȥ', &['Ȥ']), ('Ȧ', &['ȧ']), ('ȧ', &['Ȧ']), ('Ȩ', &[ + 'ȩ']), ('ȩ', &['Ȩ']), ('Ȫ', &['ȫ']), ('ȫ', &['Ȫ']), ('Ȭ', &['ȭ']), + ('ȭ', &['Ȭ']), ('Ȯ', &['ȯ']), ('ȯ', &['Ȯ']), ('Ȱ', &['ȱ']), ('ȱ', &[ + 'Ȱ']), ('Ȳ', &['ȳ']), ('ȳ', &['Ȳ']), ('Ⱥ', &['ⱥ']), ('Ȼ', &['ȼ']), + ('ȼ', &['Ȼ']), ('Ƚ', &['ƚ']), ('Ⱦ', &['ⱦ']), ('ȿ', &['Ȿ']), + ('ɀ', &['Ɀ']), ('Ɂ', &['ɂ']), ('ɂ', &['Ɂ']), ('Ƀ', &['ƀ']), + ('Ʉ', &['ʉ']), ('Ʌ', &['ʌ']), ('Ɇ', &['ɇ']), ('ɇ', &['Ɇ']), ('Ɉ', &[ + 'ɉ']), ('ɉ', &['Ɉ']), ('Ɋ', &['ɋ']), ('ɋ', &['Ɋ']), ('Ɍ', &['ɍ']), + ('ɍ', &['Ɍ']), ('Ɏ', &['ɏ']), ('ɏ', &['Ɏ']), ('ɐ', &['Ɐ']), + ('ɑ', &['Ɑ']), ('ɒ', &['Ɒ']), ('ɓ', &['Ɓ']), ('ɔ', &['Ɔ']), + ('ɖ', &['Ɖ']), ('ɗ', &['Ɗ']), ('ə', &['Ə']), ('ɛ', &['Ɛ']), ('ɜ', &[ + 'Ɜ']), ('ɠ', &['Ɠ']), ('ɡ', &['Ɡ']), ('ɣ', &['Ɣ']), ('ɥ', &['Ɥ' + ]), ('ɦ', &['Ɦ']), ('ɨ', &['Ɨ']), ('ɩ', &['Ɩ']), ('ɪ', &['Ɪ']), + ('ɫ', &['Ɫ']), ('ɬ', &['Ɬ']), ('ɯ', &['Ɯ']), ('ɱ', &['Ɱ']), + ('ɲ', &['Ɲ']), ('ɵ', &['Ɵ']), ('ɽ', &['Ɽ']), ('ʀ', &['Ʀ']), + ('ʃ', &['Ʃ']), ('ʇ', &['Ʇ']), ('ʈ', &['Ʈ']), ('ʉ', &['Ʉ']), + ('ʊ', &['Ʊ']), ('ʋ', &['Ʋ']), ('ʌ', &['Ʌ']), ('ʒ', &['Ʒ']), ('ʝ', &[ + 'Ʝ']), ('ʞ', &['Ʞ']), ('ͅ', &['Ι', 'ι', 'ι', ]), ('Ͱ', &['ͱ']), + ('ͱ', &['Ͱ']), ('Ͳ', &['ͳ']), ('ͳ', &['Ͳ']), ('Ͷ', &['ͷ']), ('ͷ', &[ + 'Ͷ']), ('ͻ', &['Ͻ']), ('ͼ', &['Ͼ']), ('ͽ', &['Ͽ']), ('Ϳ', &['ϳ']), + ('Ά', &['ά']), ('Έ', &['έ']), ('Ή', &['ή']), ('Ί', &['ί']), ('Ό', &[ + 'ό']), ('Ύ', &['ύ']), ('Ώ', &['ώ']), ('Α', &['α']), ('Β', &['β', + 'ϐ', ]), ('Γ', &['γ']), ('Δ', &['δ']), ('Ε', &['ε', 'ϵ', ]), + ('Ζ', &['ζ']), ('Η', &['η']), ('Θ', &['θ', 'ϑ', 'ϴ', ]), ('Ι', &[ + 'ͅ', 'ι', 'ι', ]), ('Κ', &['κ', 'ϰ', ]), ('Λ', &['λ']), ('Μ', &[ + 'µ', 'μ', ]), ('Ν', &['ν']), ('Ξ', &['ξ']), ('Ο', &['ο']), ('Π', &[ + 'π', 'ϖ', ]), ('Ρ', &['ρ', 'ϱ', ]), ('Σ', &['ς', 'σ', ]), ('Τ', &[ + 'τ']), ('Υ', &['υ']), ('Φ', &['φ', 'ϕ', ]), ('Χ', &['χ']), ('Ψ', &[ + 'ψ']), ('Ω', &['ω', 'Ω', ]), ('Ϊ', &['ϊ']), ('Ϋ', &['ϋ']), ('ά', &[ + 'Ά']), ('έ', &['Έ']), ('ή', &['Ή']), ('ί', &['Ί']), ('α', &['Α']), + ('β', &['Β', 'ϐ', ]), ('γ', &['Γ']), ('δ', &['Δ']), ('ε', &['Ε', + 'ϵ', ]), ('ζ', &['Ζ']), ('η', &['Η']), ('θ', &['Θ', 'ϑ', 'ϴ', ]), + ('ι', &['ͅ', 'Ι', 'ι', ]), ('κ', &['Κ', 'ϰ', ]), ('λ', &['Λ']), + ('μ', &['µ', 'Μ', ]), ('ν', &['Ν']), ('ξ', &['Ξ']), ('ο', &['Ο']), + ('π', &['Π', 'ϖ', ]), ('ρ', &['Ρ', 'ϱ', ]), ('ς', &['Σ', 'σ', ]), + ('σ', &['Σ', 'ς', ]), ('τ', &['Τ']), ('υ', &['Υ']), ('φ', &['Φ', + 'ϕ', ]), ('χ', &['Χ']), ('ψ', &['Ψ']), ('ω', &['Ω', 'Ω', ]), + ('ϊ', &['Ϊ']), ('ϋ', &['Ϋ']), ('ό', &['Ό']), ('ύ', &['Ύ']), ('ώ', &[ + 'Ώ']), ('Ϗ', &['ϗ']), ('ϐ', &['Β', 'β', ]), ('ϑ', &['Θ', 'θ', 'ϴ', + ]), ('ϕ', &['Φ', 'φ', ]), ('ϖ', &['Π', 'π', ]), ('ϗ', &['Ϗ']), + ('Ϙ', &['ϙ']), ('ϙ', &['Ϙ']), ('Ϛ', &['ϛ']), ('ϛ', &['Ϛ']), ('Ϝ', &[ + 'ϝ']), ('ϝ', &['Ϝ']), ('Ϟ', &['ϟ']), ('ϟ', &['Ϟ']), ('Ϡ', &['ϡ']), + ('ϡ', &['Ϡ']), ('Ϣ', &['ϣ']), ('ϣ', &['Ϣ']), ('Ϥ', &['ϥ']), ('ϥ', &[ + 'Ϥ']), ('Ϧ', &['ϧ']), ('ϧ', &['Ϧ']), ('Ϩ', &['ϩ']), ('ϩ', &['Ϩ']), + ('Ϫ', &['ϫ']), ('ϫ', &['Ϫ']), ('Ϭ', &['ϭ']), ('ϭ', &['Ϭ']), ('Ϯ', &[ + 'ϯ']), ('ϯ', &['Ϯ']), ('ϰ', &['Κ', 'κ', ]), ('ϱ', &['Ρ', 'ρ', ]), + ('ϲ', &['Ϲ']), ('ϳ', &['Ϳ']), ('ϴ', &['Θ', 'θ', 'ϑ', ]), ('ϵ', &[ + 'Ε', 'ε', ]), ('Ϸ', &['ϸ']), ('ϸ', &['Ϸ']), ('Ϲ', &['ϲ']), ('Ϻ', &[ + 'ϻ']), ('ϻ', &['Ϻ']), ('Ͻ', &['ͻ']), ('Ͼ', &['ͼ']), ('Ͽ', &['ͽ']), + ('Ѐ', &['ѐ']), ('Ё', &['ё']), ('Ђ', &['ђ']), ('Ѓ', &['ѓ']), ('Є', &[ + 'є']), ('Ѕ', &['ѕ']), ('І', &['і']), ('Ї', &['ї']), ('Ј', &['ј']), + ('Љ', &['љ']), ('Њ', &['њ']), ('Ћ', &['ћ']), ('Ќ', &['ќ']), ('Ѝ', &[ + 'ѝ']), ('Ў', &['ў']), ('Џ', &['џ']), ('А', &['а']), ('Б', &['б']), + ('В', &['в', 'ᲀ', ]), ('Г', &['г']), ('Д', &['д', 'ᲁ', ]), + ('Е', &['е']), ('Ж', &['ж']), ('З', &['з']), ('И', &['и']), ('Й', &[ + 'й']), ('К', &['к']), ('Л', &['л']), ('М', &['м']), ('Н', &['н']), + ('О', &['о', 'ᲂ', ]), ('П', &['п']), ('Р', &['р']), ('С', &['с', + 'ᲃ', ]), ('Т', &['т', 'ᲄ', 'ᲅ', ]), ('У', &['у']), ('Ф', &['ф' + ]), ('Х', &['х']), ('Ц', &['ц']), ('Ч', &['ч']), ('Ш', &['ш']), + ('Щ', &['щ']), ('Ъ', &['ъ', 'ᲆ', ]), ('Ы', &['ы']), ('Ь', &['ь']), + ('Э', &['э']), ('Ю', &['ю']), ('Я', &['я']), ('а', &['А']), ('б', &[ + 'Б']), ('в', &['В', 'ᲀ', ]), ('г', &['Г']), ('д', &['Д', 'ᲁ', ]), + ('е', &['Е']), ('ж', &['Ж']), ('з', &['З']), ('и', &['И']), ('й', &[ + 'Й']), ('к', &['К']), ('л', &['Л']), ('м', &['М']), ('н', &['Н']), + ('о', &['О', 'ᲂ', ]), ('п', &['П']), ('р', &['Р']), ('с', &['С', + 'ᲃ', ]), ('т', &['Т', 'ᲄ', 'ᲅ', ]), ('у', &['У']), ('ф', &['Ф' + ]), ('х', &['Х']), ('ц', &['Ц']), ('ч', &['Ч']), ('ш', &['Ш']), + ('щ', &['Щ']), ('ъ', &['Ъ', 'ᲆ', ]), ('ы', &['Ы']), ('ь', &['Ь']), + ('э', &['Э']), ('ю', &['Ю']), ('я', &['Я']), ('ѐ', &['Ѐ']), ('ё', &[ + 'Ё']), ('ђ', &['Ђ']), ('ѓ', &['Ѓ']), ('є', &['Є']), ('ѕ', &['Ѕ']), + ('і', &['І']), ('ї', &['Ї']), ('ј', &['Ј']), ('љ', &['Љ']), ('њ', &[ + 'Њ']), ('ћ', &['Ћ']), ('ќ', &['Ќ']), ('ѝ', &['Ѝ']), ('ў', &['Ў']), + ('џ', &['Џ']), ('Ѡ', &['ѡ']), ('ѡ', &['Ѡ']), ('Ѣ', &['ѣ', 'ᲇ', ]), + ('ѣ', &['Ѣ', 'ᲇ', ]), ('Ѥ', &['ѥ']), ('ѥ', &['Ѥ']), ('Ѧ', &['ѧ']), + ('ѧ', &['Ѧ']), ('Ѩ', &['ѩ']), ('ѩ', &['Ѩ']), ('Ѫ', &['ѫ']), ('ѫ', &[ + 'Ѫ']), ('Ѭ', &['ѭ']), ('ѭ', &['Ѭ']), ('Ѯ', &['ѯ']), ('ѯ', &['Ѯ']), + ('Ѱ', &['ѱ']), ('ѱ', &['Ѱ']), ('Ѳ', &['ѳ']), ('ѳ', &['Ѳ']), ('Ѵ', &[ + 'ѵ']), ('ѵ', &['Ѵ']), ('Ѷ', &['ѷ']), ('ѷ', &['Ѷ']), ('Ѹ', &['ѹ']), + ('ѹ', &['Ѹ']), ('Ѻ', &['ѻ']), ('ѻ', &['Ѻ']), ('Ѽ', &['ѽ']), ('ѽ', &[ + 'Ѽ']), ('Ѿ', &['ѿ']), ('ѿ', &['Ѿ']), ('Ҁ', &['ҁ']), ('ҁ', &['Ҁ']), + ('Ҋ', &['ҋ']), ('ҋ', &['Ҋ']), ('Ҍ', &['ҍ']), ('ҍ', &['Ҍ']), ('Ҏ', &[ + 'ҏ']), ('ҏ', &['Ҏ']), ('Ґ', &['ґ']), ('ґ', &['Ґ']), ('Ғ', &['ғ']), + ('ғ', &['Ғ']), ('Ҕ', &['ҕ']), ('ҕ', &['Ҕ']), ('Җ', &['җ']), ('җ', &[ + 'Җ']), ('Ҙ', &['ҙ']), ('ҙ', &['Ҙ']), ('Қ', &['қ']), ('қ', &['Қ']), + ('Ҝ', &['ҝ']), ('ҝ', &['Ҝ']), ('Ҟ', &['ҟ']), ('ҟ', &['Ҟ']), ('Ҡ', &[ + 'ҡ']), ('ҡ', &['Ҡ']), ('Ң', &['ң']), ('ң', &['Ң']), ('Ҥ', &['ҥ']), + ('ҥ', &['Ҥ']), ('Ҧ', &['ҧ']), ('ҧ', &['Ҧ']), ('Ҩ', &['ҩ']), ('ҩ', &[ + 'Ҩ']), ('Ҫ', &['ҫ']), ('ҫ', &['Ҫ']), ('Ҭ', &['ҭ']), ('ҭ', &['Ҭ']), + ('Ү', &['ү']), ('ү', &['Ү']), ('Ұ', &['ұ']), ('ұ', &['Ұ']), ('Ҳ', &[ + 'ҳ']), ('ҳ', &['Ҳ']), ('Ҵ', &['ҵ']), ('ҵ', &['Ҵ']), ('Ҷ', &['ҷ']), + ('ҷ', &['Ҷ']), ('Ҹ', &['ҹ']), ('ҹ', &['Ҹ']), ('Һ', &['һ']), ('һ', &[ + 'Һ']), ('Ҽ', &['ҽ']), ('ҽ', &['Ҽ']), ('Ҿ', &['ҿ']), ('ҿ', &['Ҿ']), + ('Ӏ', &['ӏ']), ('Ӂ', &['ӂ']), ('ӂ', &['Ӂ']), ('Ӄ', &['ӄ']), ('ӄ', &[ + 'Ӄ']), ('Ӆ', &['ӆ']), ('ӆ', &['Ӆ']), ('Ӈ', &['ӈ']), ('ӈ', &['Ӈ']), + ('Ӊ', &['ӊ']), ('ӊ', &['Ӊ']), ('Ӌ', &['ӌ']), ('ӌ', &['Ӌ']), ('Ӎ', &[ + 'ӎ']), ('ӎ', &['Ӎ']), ('ӏ', &['Ӏ']), ('Ӑ', &['ӑ']), ('ӑ', &['Ӑ']), + ('Ӓ', &['ӓ']), ('ӓ', &['Ӓ']), ('Ӕ', &['ӕ']), ('ӕ', &['Ӕ']), ('Ӗ', &[ + 'ӗ']), ('ӗ', &['Ӗ']), ('Ә', &['ә']), ('ә', &['Ә']), ('Ӛ', &['ӛ']), + ('ӛ', &['Ӛ']), ('Ӝ', &['ӝ']), ('ӝ', &['Ӝ']), ('Ӟ', &['ӟ']), ('ӟ', &[ + 'Ӟ']), ('Ӡ', &['ӡ']), ('ӡ', &['Ӡ']), ('Ӣ', &['ӣ']), ('ӣ', &['Ӣ']), + ('Ӥ', &['ӥ']), ('ӥ', &['Ӥ']), ('Ӧ', &['ӧ']), ('ӧ', &['Ӧ']), ('Ө', &[ + 'ө']), ('ө', &['Ө']), ('Ӫ', &['ӫ']), ('ӫ', &['Ӫ']), ('Ӭ', &['ӭ']), + ('ӭ', &['Ӭ']), ('Ӯ', &['ӯ']), ('ӯ', &['Ӯ']), ('Ӱ', &['ӱ']), ('ӱ', &[ + 'Ӱ']), ('Ӳ', &['ӳ']), ('ӳ', &['Ӳ']), ('Ӵ', &['ӵ']), ('ӵ', &['Ӵ']), + ('Ӷ', &['ӷ']), ('ӷ', &['Ӷ']), ('Ӹ', &['ӹ']), ('ӹ', &['Ӹ']), ('Ӻ', &[ + 'ӻ']), ('ӻ', &['Ӻ']), ('Ӽ', &['ӽ']), ('ӽ', &['Ӽ']), ('Ӿ', &['ӿ']), + ('ӿ', &['Ӿ']), ('Ԁ', &['ԁ']), ('ԁ', &['Ԁ']), ('Ԃ', &['ԃ']), ('ԃ', &[ + 'Ԃ']), ('Ԅ', &['ԅ']), ('ԅ', &['Ԅ']), ('Ԇ', &['ԇ']), ('ԇ', &['Ԇ']), + ('Ԉ', &['ԉ']), ('ԉ', &['Ԉ']), ('Ԋ', &['ԋ']), ('ԋ', &['Ԋ']), ('Ԍ', &[ + 'ԍ']), ('ԍ', &['Ԍ']), ('Ԏ', &['ԏ']), ('ԏ', &['Ԏ']), ('Ԑ', &['ԑ']), + ('ԑ', &['Ԑ']), ('Ԓ', &['ԓ']), ('ԓ', &['Ԓ']), ('Ԕ', &['ԕ']), ('ԕ', &[ + 'Ԕ']), ('Ԗ', &['ԗ']), ('ԗ', &['Ԗ']), ('Ԙ', &['ԙ']), ('ԙ', &['Ԙ']), + ('Ԛ', &['ԛ']), ('ԛ', &['Ԛ']), ('Ԝ', &['ԝ']), ('ԝ', &['Ԝ']), ('Ԟ', &[ + 'ԟ']), ('ԟ', &['Ԟ']), ('Ԡ', &['ԡ']), ('ԡ', &['Ԡ']), ('Ԣ', &['ԣ']), + ('ԣ', &['Ԣ']), ('Ԥ', &['ԥ']), ('ԥ', &['Ԥ']), ('Ԧ', &['ԧ']), ('ԧ', &[ + 'Ԧ']), ('Ԩ', &['ԩ']), ('ԩ', &['Ԩ']), ('Ԫ', &['ԫ']), ('ԫ', &['Ԫ']), + ('Ԭ', &['ԭ']), ('ԭ', &['Ԭ']), ('Ԯ', &['ԯ']), ('ԯ', &['Ԯ']), ('Ա', &[ + 'ա']), ('Բ', &['բ']), ('Գ', &['գ']), ('Դ', &['դ']), ('Ե', &['ե']), + ('Զ', &['զ']), ('Է', &['է']), ('Ը', &['ը']), ('Թ', &['թ']), ('Ժ', &[ + 'ժ']), ('Ի', &['ի']), ('Լ', &['լ']), ('Խ', &['խ']), ('Ծ', &['ծ']), + ('Կ', &['կ']), ('Հ', &['հ']), ('Ձ', &['ձ']), ('Ղ', &['ղ']), ('Ճ', &[ + 'ճ']), ('Մ', &['մ']), ('Յ', &['յ']), ('Ն', &['ն']), ('Շ', &['շ']), + ('Ո', &['ո']), ('Չ', &['չ']), ('Պ', &['պ']), ('Ջ', &['ջ']), ('Ռ', &[ + 'ռ']), ('Ս', &['ս']), ('Վ', &['վ']), ('Տ', &['տ']), ('Ր', &['ր']), + ('Ց', &['ց']), ('Ւ', &['ւ']), ('Փ', &['փ']), ('Ք', &['ք']), ('Օ', &[ + 'օ']), ('Ֆ', &['ֆ']), ('ա', &['Ա']), ('բ', &['Բ']), ('գ', &['Գ']), + ('դ', &['Դ']), ('ե', &['Ե']), ('զ', &['Զ']), ('է', &['Է']), ('ը', &[ + 'Ը']), ('թ', &['Թ']), ('ժ', &['Ժ']), ('ի', &['Ի']), ('լ', &['Լ']), + ('խ', &['Խ']), ('ծ', &['Ծ']), ('կ', &['Կ']), ('հ', &['Հ']), ('ձ', &[ + 'Ձ']), ('ղ', &['Ղ']), ('ճ', &['Ճ']), ('մ', &['Մ']), ('յ', &['Յ']), + ('ն', &['Ն']), ('շ', &['Շ']), ('ո', &['Ո']), ('չ', &['Չ']), ('պ', &[ + 'Պ']), ('ջ', &['Ջ']), ('ռ', &['Ռ']), ('ս', &['Ս']), ('վ', &['Վ']), + ('տ', &['Տ']), ('ր', &['Ր']), ('ց', &['Ց']), ('ւ', &['Ւ']), ('փ', &[ + 'Փ']), ('ք', &['Ք']), ('օ', &['Օ']), ('ֆ', &['Ֆ']), ('Ⴀ', &['ⴀ' + ]), ('Ⴁ', &['ⴁ']), ('Ⴂ', &['ⴂ']), ('Ⴃ', &['ⴃ']), ('Ⴄ', &['ⴄ' + ]), ('Ⴅ', &['ⴅ']), ('Ⴆ', &['ⴆ']), ('Ⴇ', &['ⴇ']), ('Ⴈ', &['ⴈ' + ]), ('Ⴉ', &['ⴉ']), ('Ⴊ', &['ⴊ']), ('Ⴋ', &['ⴋ']), ('Ⴌ', &['ⴌ' + ]), ('Ⴍ', &['ⴍ']), ('Ⴎ', &['ⴎ']), ('Ⴏ', &['ⴏ']), ('Ⴐ', &['ⴐ' + ]), ('Ⴑ', &['ⴑ']), ('Ⴒ', &['ⴒ']), ('Ⴓ', &['ⴓ']), ('Ⴔ', &['ⴔ' + ]), ('Ⴕ', &['ⴕ']), ('Ⴖ', &['ⴖ']), ('Ⴗ', &['ⴗ']), ('Ⴘ', &['ⴘ' + ]), ('Ⴙ', &['ⴙ']), ('Ⴚ', &['ⴚ']), ('Ⴛ', &['ⴛ']), ('Ⴜ', &['ⴜ' + ]), ('Ⴝ', &['ⴝ']), ('Ⴞ', &['ⴞ']), ('Ⴟ', &['ⴟ']), ('Ⴠ', &['ⴠ' + ]), ('Ⴡ', &['ⴡ']), ('Ⴢ', &['ⴢ']), ('Ⴣ', &['ⴣ']), ('Ⴤ', &['ⴤ' + ]), ('Ⴥ', &['ⴥ']), ('Ⴧ', &['ⴧ']), ('Ⴭ', &['ⴭ']), ('Ꭰ', &['ꭰ' + ]), ('Ꭱ', &['ꭱ']), ('Ꭲ', &['ꭲ']), ('Ꭳ', &['ꭳ']), ('Ꭴ', &['ꭴ' + ]), ('Ꭵ', &['ꭵ']), ('Ꭶ', &['ꭶ']), ('Ꭷ', &['ꭷ']), ('Ꭸ', &['ꭸ' + ]), ('Ꭹ', &['ꭹ']), ('Ꭺ', &['ꭺ']), ('Ꭻ', &['ꭻ']), ('Ꭼ', &['ꭼ' + ]), ('Ꭽ', &['ꭽ']), ('Ꭾ', &['ꭾ']), ('Ꭿ', &['ꭿ']), ('Ꮀ', &['ꮀ' + ]), ('Ꮁ', &['ꮁ']), ('Ꮂ', &['ꮂ']), ('Ꮃ', &['ꮃ']), ('Ꮄ', &['ꮄ' + ]), ('Ꮅ', &['ꮅ']), ('Ꮆ', &['ꮆ']), ('Ꮇ', &['ꮇ']), ('Ꮈ', &['ꮈ' + ]), ('Ꮉ', &['ꮉ']), ('Ꮊ', &['ꮊ']), ('Ꮋ', &['ꮋ']), ('Ꮌ', &['ꮌ' + ]), ('Ꮍ', &['ꮍ']), ('Ꮎ', &['ꮎ']), ('Ꮏ', &['ꮏ']), ('Ꮐ', &['ꮐ' + ]), ('Ꮑ', &['ꮑ']), ('Ꮒ', &['ꮒ']), ('Ꮓ', &['ꮓ']), ('Ꮔ', &['ꮔ' + ]), ('Ꮕ', &['ꮕ']), ('Ꮖ', &['ꮖ']), ('Ꮗ', &['ꮗ']), ('Ꮘ', &['ꮘ' + ]), ('Ꮙ', &['ꮙ']), ('Ꮚ', &['ꮚ']), ('Ꮛ', &['ꮛ']), ('Ꮜ', &['ꮜ' + ]), ('Ꮝ', &['ꮝ']), ('Ꮞ', &['ꮞ']), ('Ꮟ', &['ꮟ']), ('Ꮠ', &['ꮠ' + ]), ('Ꮡ', &['ꮡ']), ('Ꮢ', &['ꮢ']), ('Ꮣ', &['ꮣ']), ('Ꮤ', &['ꮤ' + ]), ('Ꮥ', &['ꮥ']), ('Ꮦ', &['ꮦ']), ('Ꮧ', &['ꮧ']), ('Ꮨ', &['ꮨ' + ]), ('Ꮩ', &['ꮩ']), ('Ꮪ', &['ꮪ']), ('Ꮫ', &['ꮫ']), ('Ꮬ', &['ꮬ' + ]), ('Ꮭ', &['ꮭ']), ('Ꮮ', &['ꮮ']), ('Ꮯ', &['ꮯ']), ('Ꮰ', &['ꮰ' + ]), ('Ꮱ', &['ꮱ']), ('Ꮲ', &['ꮲ']), ('Ꮳ', &['ꮳ']), ('Ꮴ', &['ꮴ' + ]), ('Ꮵ', &['ꮵ']), ('Ꮶ', &['ꮶ']), ('Ꮷ', &['ꮷ']), ('Ꮸ', &['ꮸ' + ]), ('Ꮹ', &['ꮹ']), ('Ꮺ', &['ꮺ']), ('Ꮻ', &['ꮻ']), ('Ꮼ', &['ꮼ' + ]), ('Ꮽ', &['ꮽ']), ('Ꮾ', &['ꮾ']), ('Ꮿ', &['ꮿ']), ('Ᏸ', &['ᏸ' + ]), ('Ᏹ', &['ᏹ']), ('Ᏺ', &['ᏺ']), ('Ᏻ', &['ᏻ']), ('Ᏼ', &['ᏼ' + ]), ('Ᏽ', &['ᏽ']), ('ᏸ', &['Ᏸ']), ('ᏹ', &['Ᏹ']), ('ᏺ', &['Ᏺ' + ]), ('ᏻ', &['Ᏻ']), ('ᏼ', &['Ᏼ']), ('ᏽ', &['Ᏽ']), ('ᲀ', &['В', + 'в', ]), ('ᲁ', &['Д', 'д', ]), ('ᲂ', &['О', 'о', ]), ('ᲃ', &[ + 'С', 'с', ]), ('ᲄ', &['Т', 'т', 'ᲅ', ]), ('ᲅ', &['Т', 'т', + 'ᲄ', ]), ('ᲆ', &['Ъ', 'ъ', ]), ('ᲇ', &['Ѣ', 'ѣ', ]), ('ᲈ', &[ + 'Ꙋ', 'ꙋ', ]), ('ᵹ', &['Ᵹ']), ('ᵽ', &['Ᵽ']), ('Ḁ', &['ḁ']), + ('ḁ', &['Ḁ']), ('Ḃ', &['ḃ']), ('ḃ', &['Ḃ']), ('Ḅ', &['ḅ']), + ('ḅ', &['Ḅ']), ('Ḇ', &['ḇ']), ('ḇ', &['Ḇ']), ('Ḉ', &['ḉ']), + ('ḉ', &['Ḉ']), ('Ḋ', &['ḋ']), ('ḋ', &['Ḋ']), ('Ḍ', &['ḍ']), + ('ḍ', &['Ḍ']), ('Ḏ', &['ḏ']), ('ḏ', &['Ḏ']), ('Ḑ', &['ḑ']), + ('ḑ', &['Ḑ']), ('Ḓ', &['ḓ']), ('ḓ', &['Ḓ']), ('Ḕ', &['ḕ']), + ('ḕ', &['Ḕ']), ('Ḗ', &['ḗ']), ('ḗ', &['Ḗ']), ('Ḙ', &['ḙ']), + ('ḙ', &['Ḙ']), ('Ḛ', &['ḛ']), ('ḛ', &['Ḛ']), ('Ḝ', &['ḝ']), + ('ḝ', &['Ḝ']), ('Ḟ', &['ḟ']), ('ḟ', &['Ḟ']), ('Ḡ', &['ḡ']), + ('ḡ', &['Ḡ']), ('Ḣ', &['ḣ']), ('ḣ', &['Ḣ']), ('Ḥ', &['ḥ']), + ('ḥ', &['Ḥ']), ('Ḧ', &['ḧ']), ('ḧ', &['Ḧ']), ('Ḩ', &['ḩ']), + ('ḩ', &['Ḩ']), ('Ḫ', &['ḫ']), ('ḫ', &['Ḫ']), ('Ḭ', &['ḭ']), + ('ḭ', &['Ḭ']), ('Ḯ', &['ḯ']), ('ḯ', &['Ḯ']), ('Ḱ', &['ḱ']), + ('ḱ', &['Ḱ']), ('Ḳ', &['ḳ']), ('ḳ', &['Ḳ']), ('Ḵ', &['ḵ']), + ('ḵ', &['Ḵ']), ('Ḷ', &['ḷ']), ('ḷ', &['Ḷ']), ('Ḹ', &['ḹ']), + ('ḹ', &['Ḹ']), ('Ḻ', &['ḻ']), ('ḻ', &['Ḻ']), ('Ḽ', &['ḽ']), + ('ḽ', &['Ḽ']), ('Ḿ', &['ḿ']), ('ḿ', &['Ḿ']), ('Ṁ', &['ṁ']), + ('ṁ', &['Ṁ']), ('Ṃ', &['ṃ']), ('ṃ', &['Ṃ']), ('Ṅ', &['ṅ']), + ('ṅ', &['Ṅ']), ('Ṇ', &['ṇ']), ('ṇ', &['Ṇ']), ('Ṉ', &['ṉ']), + ('ṉ', &['Ṉ']), ('Ṋ', &['ṋ']), ('ṋ', &['Ṋ']), ('Ṍ', &['ṍ']), + ('ṍ', &['Ṍ']), ('Ṏ', &['ṏ']), ('ṏ', &['Ṏ']), ('Ṑ', &['ṑ']), + ('ṑ', &['Ṑ']), ('Ṓ', &['ṓ']), ('ṓ', &['Ṓ']), ('Ṕ', &['ṕ']), + ('ṕ', &['Ṕ']), ('Ṗ', &['ṗ']), ('ṗ', &['Ṗ']), ('Ṙ', &['ṙ']), + ('ṙ', &['Ṙ']), ('Ṛ', &['ṛ']), ('ṛ', &['Ṛ']), ('Ṝ', &['ṝ']), + ('ṝ', &['Ṝ']), ('Ṟ', &['ṟ']), ('ṟ', &['Ṟ']), ('Ṡ', &['ṡ', + 'ẛ', ]), ('ṡ', &['Ṡ', 'ẛ', ]), ('Ṣ', &['ṣ']), ('ṣ', &['Ṣ']), + ('Ṥ', &['ṥ']), ('ṥ', &['Ṥ']), ('Ṧ', &['ṧ']), ('ṧ', &['Ṧ']), + ('Ṩ', &['ṩ']), ('ṩ', &['Ṩ']), ('Ṫ', &['ṫ']), ('ṫ', &['Ṫ']), + ('Ṭ', &['ṭ']), ('ṭ', &['Ṭ']), ('Ṯ', &['ṯ']), ('ṯ', &['Ṯ']), + ('Ṱ', &['ṱ']), ('ṱ', &['Ṱ']), ('Ṳ', &['ṳ']), ('ṳ', &['Ṳ']), + ('Ṵ', &['ṵ']), ('ṵ', &['Ṵ']), ('Ṷ', &['ṷ']), ('ṷ', &['Ṷ']), + ('Ṹ', &['ṹ']), ('ṹ', &['Ṹ']), ('Ṻ', &['ṻ']), ('ṻ', &['Ṻ']), + ('Ṽ', &['ṽ']), ('ṽ', &['Ṽ']), ('Ṿ', &['ṿ']), ('ṿ', &['Ṿ']), + ('Ẁ', &['ẁ']), ('ẁ', &['Ẁ']), ('Ẃ', &['ẃ']), ('ẃ', &['Ẃ']), + ('Ẅ', &['ẅ']), ('ẅ', &['Ẅ']), ('Ẇ', &['ẇ']), ('ẇ', &['Ẇ']), + ('Ẉ', &['ẉ']), ('ẉ', &['Ẉ']), ('Ẋ', &['ẋ']), ('ẋ', &['Ẋ']), + ('Ẍ', &['ẍ']), ('ẍ', &['Ẍ']), ('Ẏ', &['ẏ']), ('ẏ', &['Ẏ']), + ('Ẑ', &['ẑ']), ('ẑ', &['Ẑ']), ('Ẓ', &['ẓ']), ('ẓ', &['Ẓ']), + ('Ẕ', &['ẕ']), ('ẕ', &['Ẕ']), ('ẛ', &['Ṡ', 'ṡ', ]), ('ẞ', &[ + 'ß']), ('Ạ', &['ạ']), ('ạ', &['Ạ']), ('Ả', &['ả']), ('ả', &[ + 'Ả']), ('Ấ', &['ấ']), ('ấ', &['Ấ']), ('Ầ', &['ầ']), ('ầ', &[ + 'Ầ']), ('Ẩ', &['ẩ']), ('ẩ', &['Ẩ']), ('Ẫ', &['ẫ']), ('ẫ', &[ + 'Ẫ']), ('Ậ', &['ậ']), ('ậ', &['Ậ']), ('Ắ', &['ắ']), ('ắ', &[ + 'Ắ']), ('Ằ', &['ằ']), ('ằ', &['Ằ']), ('Ẳ', &['ẳ']), ('ẳ', &[ + 'Ẳ']), ('Ẵ', &['ẵ']), ('ẵ', &['Ẵ']), ('Ặ', &['ặ']), ('ặ', &[ + 'Ặ']), ('Ẹ', &['ẹ']), ('ẹ', &['Ẹ']), ('Ẻ', &['ẻ']), ('ẻ', &[ + 'Ẻ']), ('Ẽ', &['ẽ']), ('ẽ', &['Ẽ']), ('Ế', &['ế']), ('ế', &[ + 'Ế']), ('Ề', &['ề']), ('ề', &['Ề']), ('Ể', &['ể']), ('ể', &[ + 'Ể']), ('Ễ', &['ễ']), ('ễ', &['Ễ']), ('Ệ', &['ệ']), ('ệ', &[ + 'Ệ']), ('Ỉ', &['ỉ']), ('ỉ', &['Ỉ']), ('Ị', &['ị']), ('ị', &[ + 'Ị']), ('Ọ', &['ọ']), ('ọ', &['Ọ']), ('Ỏ', &['ỏ']), ('ỏ', &[ + 'Ỏ']), ('Ố', &['ố']), ('ố', &['Ố']), ('Ồ', &['ồ']), ('ồ', &[ + 'Ồ']), ('Ổ', &['ổ']), ('ổ', &['Ổ']), ('Ỗ', &['ỗ']), ('ỗ', &[ + 'Ỗ']), ('Ộ', &['ộ']), ('ộ', &['Ộ']), ('Ớ', &['ớ']), ('ớ', &[ + 'Ớ']), ('Ờ', &['ờ']), ('ờ', &['Ờ']), ('Ở', &['ở']), ('ở', &[ + 'Ở']), ('Ỡ', &['ỡ']), ('ỡ', &['Ỡ']), ('Ợ', &['ợ']), ('ợ', &[ + 'Ợ']), ('Ụ', &['ụ']), ('ụ', &['Ụ']), ('Ủ', &['ủ']), ('ủ', &[ + 'Ủ']), ('Ứ', &['ứ']), ('ứ', &['Ứ']), ('Ừ', &['ừ']), ('ừ', &[ + 'Ừ']), ('Ử', &['ử']), ('ử', &['Ử']), ('Ữ', &['ữ']), ('ữ', &[ + 'Ữ']), ('Ự', &['ự']), ('ự', &['Ự']), ('Ỳ', &['ỳ']), ('ỳ', &[ + 'Ỳ']), ('Ỵ', &['ỵ']), ('ỵ', &['Ỵ']), ('Ỷ', &['ỷ']), ('ỷ', &[ + 'Ỷ']), ('Ỹ', &['ỹ']), ('ỹ', &['Ỹ']), ('Ỻ', &['ỻ']), ('ỻ', &[ + 'Ỻ']), ('Ỽ', &['ỽ']), ('ỽ', &['Ỽ']), ('Ỿ', &['ỿ']), ('ỿ', &[ + 'Ỿ']), ('ἀ', &['Ἀ']), ('ἁ', &['Ἁ']), ('ἂ', &['Ἂ']), ('ἃ', &[ + 'Ἃ']), ('ἄ', &['Ἄ']), ('ἅ', &['Ἅ']), ('ἆ', &['Ἆ']), ('ἇ', &[ + 'Ἇ']), ('Ἀ', &['ἀ']), ('Ἁ', &['ἁ']), ('Ἂ', &['ἂ']), ('Ἃ', &[ + 'ἃ']), ('Ἄ', &['ἄ']), ('Ἅ', &['ἅ']), ('Ἆ', &['ἆ']), ('Ἇ', &[ + 'ἇ']), ('ἐ', &['Ἐ']), ('ἑ', &['Ἑ']), ('ἒ', &['Ἒ']), ('ἓ', &[ + 'Ἓ']), ('ἔ', &['Ἔ']), ('ἕ', &['Ἕ']), ('Ἐ', &['ἐ']), ('Ἑ', &[ + 'ἑ']), ('Ἒ', &['ἒ']), ('Ἓ', &['ἓ']), ('Ἔ', &['ἔ']), ('Ἕ', &[ + 'ἕ']), ('ἠ', &['Ἠ']), ('ἡ', &['Ἡ']), ('ἢ', &['Ἢ']), ('ἣ', &[ + 'Ἣ']), ('ἤ', &['Ἤ']), ('ἥ', &['Ἥ']), ('ἦ', &['Ἦ']), ('ἧ', &[ + 'Ἧ']), ('Ἠ', &['ἠ']), ('Ἡ', &['ἡ']), ('Ἢ', &['ἢ']), ('Ἣ', &[ + 'ἣ']), ('Ἤ', &['ἤ']), ('Ἥ', &['ἥ']), ('Ἦ', &['ἦ']), ('Ἧ', &[ + 'ἧ']), ('ἰ', &['Ἰ']), ('ἱ', &['Ἱ']), ('ἲ', &['Ἲ']), ('ἳ', &[ + 'Ἳ']), ('ἴ', &['Ἴ']), ('ἵ', &['Ἵ']), ('ἶ', &['Ἶ']), ('ἷ', &[ + 'Ἷ']), ('Ἰ', &['ἰ']), ('Ἱ', &['ἱ']), ('Ἲ', &['ἲ']), ('Ἳ', &[ + 'ἳ']), ('Ἴ', &['ἴ']), ('Ἵ', &['ἵ']), ('Ἶ', &['ἶ']), ('Ἷ', &[ + 'ἷ']), ('ὀ', &['Ὀ']), ('ὁ', &['Ὁ']), ('ὂ', &['Ὂ']), ('ὃ', &[ + 'Ὃ']), ('ὄ', &['Ὄ']), ('ὅ', &['Ὅ']), ('Ὀ', &['ὀ']), ('Ὁ', &[ + 'ὁ']), ('Ὂ', &['ὂ']), ('Ὃ', &['ὃ']), ('Ὄ', &['ὄ']), ('Ὅ', &[ + 'ὅ']), ('ὑ', &['Ὑ']), ('ὓ', &['Ὓ']), ('ὕ', &['Ὕ']), ('ὗ', &[ + 'Ὗ']), ('Ὑ', &['ὑ']), ('Ὓ', &['ὓ']), ('Ὕ', &['ὕ']), ('Ὗ', &[ + 'ὗ']), ('ὠ', &['Ὠ']), ('ὡ', &['Ὡ']), ('ὢ', &['Ὢ']), ('ὣ', &[ + 'Ὣ']), ('ὤ', &['Ὤ']), ('ὥ', &['Ὥ']), ('ὦ', &['Ὦ']), ('ὧ', &[ + 'Ὧ']), ('Ὠ', &['ὠ']), ('Ὡ', &['ὡ']), ('Ὢ', &['ὢ']), ('Ὣ', &[ + 'ὣ']), ('Ὤ', &['ὤ']), ('Ὥ', &['ὥ']), ('Ὦ', &['ὦ']), ('Ὧ', &[ + 'ὧ']), ('ὰ', &['Ὰ']), ('ά', &['Ά']), ('ὲ', &['Ὲ']), ('έ', &[ + 'Έ']), ('ὴ', &['Ὴ']), ('ή', &['Ή']), ('ὶ', &['Ὶ']), ('ί', &[ + 'Ί']), ('ὸ', &['Ὸ']), ('ό', &['Ό']), ('ὺ', &['Ὺ']), ('ύ', &[ + 'Ύ']), ('ὼ', &['Ὼ']), ('ώ', &['Ώ']), ('ᾀ', &['ᾈ']), ('ᾁ', &[ + 'ᾉ']), ('ᾂ', &['ᾊ']), ('ᾃ', &['ᾋ']), ('ᾄ', &['ᾌ']), ('ᾅ', &[ + 'ᾍ']), ('ᾆ', &['ᾎ']), ('ᾇ', &['ᾏ']), ('ᾈ', &['ᾀ']), ('ᾉ', &[ + 'ᾁ']), ('ᾊ', &['ᾂ']), ('ᾋ', &['ᾃ']), ('ᾌ', &['ᾄ']), ('ᾍ', &[ + 'ᾅ']), ('ᾎ', &['ᾆ']), ('ᾏ', &['ᾇ']), ('ᾐ', &['ᾘ']), ('ᾑ', &[ + 'ᾙ']), ('ᾒ', &['ᾚ']), ('ᾓ', &['ᾛ']), ('ᾔ', &['ᾜ']), ('ᾕ', &[ + 'ᾝ']), ('ᾖ', &['ᾞ']), ('ᾗ', &['ᾟ']), ('ᾘ', &['ᾐ']), ('ᾙ', &[ + 'ᾑ']), ('ᾚ', &['ᾒ']), ('ᾛ', &['ᾓ']), ('ᾜ', &['ᾔ']), ('ᾝ', &[ + 'ᾕ']), ('ᾞ', &['ᾖ']), ('ᾟ', &['ᾗ']), ('ᾠ', &['ᾨ']), ('ᾡ', &[ + 'ᾩ']), ('ᾢ', &['ᾪ']), ('ᾣ', &['ᾫ']), ('ᾤ', &['ᾬ']), ('ᾥ', &[ + 'ᾭ']), ('ᾦ', &['ᾮ']), ('ᾧ', &['ᾯ']), ('ᾨ', &['ᾠ']), ('ᾩ', &[ + 'ᾡ']), ('ᾪ', &['ᾢ']), ('ᾫ', &['ᾣ']), ('ᾬ', &['ᾤ']), ('ᾭ', &[ + 'ᾥ']), ('ᾮ', &['ᾦ']), ('ᾯ', &['ᾧ']), ('ᾰ', &['Ᾰ']), ('ᾱ', &[ + 'Ᾱ']), ('ᾳ', &['ᾼ']), ('Ᾰ', &['ᾰ']), ('Ᾱ', &['ᾱ']), ('Ὰ', &[ + 'ὰ']), ('Ά', &['ά']), ('ᾼ', &['ᾳ']), ('ι', &['ͅ', 'Ι', 'ι', + ]), ('ῃ', &['ῌ']), ('Ὲ', &['ὲ']), ('Έ', &['έ']), ('Ὴ', &['ὴ' + ]), ('Ή', &['ή']), ('ῌ', &['ῃ']), ('ῐ', &['Ῐ']), ('ῑ', &['Ῑ' + ]), ('Ῐ', &['ῐ']), ('Ῑ', &['ῑ']), ('Ὶ', &['ὶ']), ('Ί', &['ί' + ]), ('ῠ', &['Ῠ']), ('ῡ', &['Ῡ']), ('ῥ', &['Ῥ']), ('Ῠ', &['ῠ' + ]), ('Ῡ', &['ῡ']), ('Ὺ', &['ὺ']), ('Ύ', &['ύ']), ('Ῥ', &['ῥ' + ]), ('ῳ', &['ῼ']), ('Ὸ', &['ὸ']), ('Ό', &['ό']), ('Ὼ', &['ὼ' + ]), ('Ώ', &['ώ']), ('ῼ', &['ῳ']), ('Ω', &['Ω', 'ω', ]), + ('K', &['K', 'k', ]), ('Å', &['Å', 'å', ]), ('Ⅎ', &['ⅎ']), + ('ⅎ', &['Ⅎ']), ('Ⅰ', &['ⅰ']), ('Ⅱ', &['ⅱ']), ('Ⅲ', &['ⅲ']), + ('Ⅳ', &['ⅳ']), ('Ⅴ', &['ⅴ']), ('Ⅵ', &['ⅵ']), ('Ⅶ', &['ⅶ']), + ('Ⅷ', &['ⅷ']), ('Ⅸ', &['ⅸ']), ('Ⅹ', &['ⅹ']), ('Ⅺ', &['ⅺ']), + ('Ⅻ', &['ⅻ']), ('Ⅼ', &['ⅼ']), ('Ⅽ', &['ⅽ']), ('Ⅾ', &['ⅾ']), + ('Ⅿ', &['ⅿ']), ('ⅰ', &['Ⅰ']), ('ⅱ', &['Ⅱ']), ('ⅲ', &['Ⅲ']), + ('ⅳ', &['Ⅳ']), ('ⅴ', &['Ⅴ']), ('ⅵ', &['Ⅵ']), ('ⅶ', &['Ⅶ']), + ('ⅷ', &['Ⅷ']), ('ⅸ', &['Ⅸ']), ('ⅹ', &['Ⅹ']), ('ⅺ', &['Ⅺ']), + ('ⅻ', &['Ⅻ']), ('ⅼ', &['Ⅼ']), ('ⅽ', &['Ⅽ']), ('ⅾ', &['Ⅾ']), + ('ⅿ', &['Ⅿ']), ('Ↄ', &['ↄ']), ('ↄ', &['Ↄ']), ('Ⓐ', &['ⓐ']), + ('Ⓑ', &['ⓑ']), ('Ⓒ', &['ⓒ']), ('Ⓓ', &['ⓓ']), ('Ⓔ', &['ⓔ']), + ('Ⓕ', &['ⓕ']), ('Ⓖ', &['ⓖ']), ('Ⓗ', &['ⓗ']), ('Ⓘ', &['ⓘ']), + ('Ⓙ', &['ⓙ']), ('Ⓚ', &['ⓚ']), ('Ⓛ', &['ⓛ']), ('Ⓜ', &['ⓜ']), + ('Ⓝ', &['ⓝ']), ('Ⓞ', &['ⓞ']), ('Ⓟ', &['ⓟ']), ('Ⓠ', &['ⓠ']), + ('Ⓡ', &['ⓡ']), ('Ⓢ', &['ⓢ']), ('Ⓣ', &['ⓣ']), ('Ⓤ', &['ⓤ']), + ('Ⓥ', &['ⓥ']), ('Ⓦ', &['ⓦ']), ('Ⓧ', &['ⓧ']), ('Ⓨ', &['ⓨ']), + ('Ⓩ', &['ⓩ']), ('ⓐ', &['Ⓐ']), ('ⓑ', &['Ⓑ']), ('ⓒ', &['Ⓒ']), + ('ⓓ', &['Ⓓ']), ('ⓔ', &['Ⓔ']), ('ⓕ', &['Ⓕ']), ('ⓖ', &['Ⓖ']), + ('ⓗ', &['Ⓗ']), ('ⓘ', &['Ⓘ']), ('ⓙ', &['Ⓙ']), ('ⓚ', &['Ⓚ']), + ('ⓛ', &['Ⓛ']), ('ⓜ', &['Ⓜ']), ('ⓝ', &['Ⓝ']), ('ⓞ', &['Ⓞ']), + ('ⓟ', &['Ⓟ']), ('ⓠ', &['Ⓠ']), ('ⓡ', &['Ⓡ']), ('ⓢ', &['Ⓢ']), + ('ⓣ', &['Ⓣ']), ('ⓤ', &['Ⓤ']), ('ⓥ', &['Ⓥ']), ('ⓦ', &['Ⓦ']), + ('ⓧ', &['Ⓧ']), ('ⓨ', &['Ⓨ']), ('ⓩ', &['Ⓩ']), ('Ⰰ', &['ⰰ']), + ('Ⰱ', &['ⰱ']), ('Ⰲ', &['ⰲ']), ('Ⰳ', &['ⰳ']), ('Ⰴ', &['ⰴ']), + ('Ⰵ', &['ⰵ']), ('Ⰶ', &['ⰶ']), ('Ⰷ', &['ⰷ']), ('Ⰸ', &['ⰸ']), + ('Ⰹ', &['ⰹ']), ('Ⰺ', &['ⰺ']), ('Ⰻ', &['ⰻ']), ('Ⰼ', &['ⰼ']), + ('Ⰽ', &['ⰽ']), ('Ⰾ', &['ⰾ']), ('Ⰿ', &['ⰿ']), ('Ⱀ', &['ⱀ']), + ('Ⱁ', &['ⱁ']), ('Ⱂ', &['ⱂ']), ('Ⱃ', &['ⱃ']), ('Ⱄ', &['ⱄ']), + ('Ⱅ', &['ⱅ']), ('Ⱆ', &['ⱆ']), ('Ⱇ', &['ⱇ']), ('Ⱈ', &['ⱈ']), + ('Ⱉ', &['ⱉ']), ('Ⱊ', &['ⱊ']), ('Ⱋ', &['ⱋ']), ('Ⱌ', &['ⱌ']), + ('Ⱍ', &['ⱍ']), ('Ⱎ', &['ⱎ']), ('Ⱏ', &['ⱏ']), ('Ⱐ', &['ⱐ']), + ('Ⱑ', &['ⱑ']), ('Ⱒ', &['ⱒ']), ('Ⱓ', &['ⱓ']), ('Ⱔ', &['ⱔ']), + ('Ⱕ', &['ⱕ']), ('Ⱖ', &['ⱖ']), ('Ⱗ', &['ⱗ']), ('Ⱘ', &['ⱘ']), + ('Ⱙ', &['ⱙ']), ('Ⱚ', &['ⱚ']), ('Ⱛ', &['ⱛ']), ('Ⱜ', &['ⱜ']), + ('Ⱝ', &['ⱝ']), ('Ⱞ', &['ⱞ']), ('ⰰ', &['Ⰰ']), ('ⰱ', &['Ⰱ']), + ('ⰲ', &['Ⰲ']), ('ⰳ', &['Ⰳ']), ('ⰴ', &['Ⰴ']), ('ⰵ', &['Ⰵ']), + ('ⰶ', &['Ⰶ']), ('ⰷ', &['Ⰷ']), ('ⰸ', &['Ⰸ']), ('ⰹ', &['Ⰹ']), + ('ⰺ', &['Ⰺ']), ('ⰻ', &['Ⰻ']), ('ⰼ', &['Ⰼ']), ('ⰽ', &['Ⰽ']), + ('ⰾ', &['Ⰾ']), ('ⰿ', &['Ⰿ']), ('ⱀ', &['Ⱀ']), ('ⱁ', &['Ⱁ']), + ('ⱂ', &['Ⱂ']), ('ⱃ', &['Ⱃ']), ('ⱄ', &['Ⱄ']), ('ⱅ', &['Ⱅ']), + ('ⱆ', &['Ⱆ']), ('ⱇ', &['Ⱇ']), ('ⱈ', &['Ⱈ']), ('ⱉ', &['Ⱉ']), + ('ⱊ', &['Ⱊ']), ('ⱋ', &['Ⱋ']), ('ⱌ', &['Ⱌ']), ('ⱍ', &['Ⱍ']), + ('ⱎ', &['Ⱎ']), ('ⱏ', &['Ⱏ']), ('ⱐ', &['Ⱐ']), ('ⱑ', &['Ⱑ']), + ('ⱒ', &['Ⱒ']), ('ⱓ', &['Ⱓ']), ('ⱔ', &['Ⱔ']), ('ⱕ', &['Ⱕ']), + ('ⱖ', &['Ⱖ']), ('ⱗ', &['Ⱗ']), ('ⱘ', &['Ⱘ']), ('ⱙ', &['Ⱙ']), + ('ⱚ', &['Ⱚ']), ('ⱛ', &['Ⱛ']), ('ⱜ', &['Ⱜ']), ('ⱝ', &['Ⱝ']), + ('ⱞ', &['Ⱞ']), ('Ⱡ', &['ⱡ']), ('ⱡ', &['Ⱡ']), ('Ɫ', &['ɫ']), + ('Ᵽ', &['ᵽ']), ('Ɽ', &['ɽ']), ('ⱥ', &['Ⱥ']), ('ⱦ', &['Ⱦ']), + ('Ⱨ', &['ⱨ']), ('ⱨ', &['Ⱨ']), ('Ⱪ', &['ⱪ']), ('ⱪ', &['Ⱪ']), + ('Ⱬ', &['ⱬ']), ('ⱬ', &['Ⱬ']), ('Ɑ', &['ɑ']), ('Ɱ', &['ɱ']), + ('Ɐ', &['ɐ']), ('Ɒ', &['ɒ']), ('Ⱳ', &['ⱳ']), ('ⱳ', &['Ⱳ']), + ('Ⱶ', &['ⱶ']), ('ⱶ', &['Ⱶ']), ('Ȿ', &['ȿ']), ('Ɀ', &['ɀ']), + ('Ⲁ', &['ⲁ']), ('ⲁ', &['Ⲁ']), ('Ⲃ', &['ⲃ']), ('ⲃ', &['Ⲃ']), + ('Ⲅ', &['ⲅ']), ('ⲅ', &['Ⲅ']), ('Ⲇ', &['ⲇ']), ('ⲇ', &['Ⲇ']), + ('Ⲉ', &['ⲉ']), ('ⲉ', &['Ⲉ']), ('Ⲋ', &['ⲋ']), ('ⲋ', &['Ⲋ']), + ('Ⲍ', &['ⲍ']), ('ⲍ', &['Ⲍ']), ('Ⲏ', &['ⲏ']), ('ⲏ', &['Ⲏ']), + ('Ⲑ', &['ⲑ']), ('ⲑ', &['Ⲑ']), ('Ⲓ', &['ⲓ']), ('ⲓ', &['Ⲓ']), + ('Ⲕ', &['ⲕ']), ('ⲕ', &['Ⲕ']), ('Ⲗ', &['ⲗ']), ('ⲗ', &['Ⲗ']), + ('Ⲙ', &['ⲙ']), ('ⲙ', &['Ⲙ']), ('Ⲛ', &['ⲛ']), ('ⲛ', &['Ⲛ']), + ('Ⲝ', &['ⲝ']), ('ⲝ', &['Ⲝ']), ('Ⲟ', &['ⲟ']), ('ⲟ', &['Ⲟ']), + ('Ⲡ', &['ⲡ']), ('ⲡ', &['Ⲡ']), ('Ⲣ', &['ⲣ']), ('ⲣ', &['Ⲣ']), + ('Ⲥ', &['ⲥ']), ('ⲥ', &['Ⲥ']), ('Ⲧ', &['ⲧ']), ('ⲧ', &['Ⲧ']), + ('Ⲩ', &['ⲩ']), ('ⲩ', &['Ⲩ']), ('Ⲫ', &['ⲫ']), ('ⲫ', &['Ⲫ']), + ('Ⲭ', &['ⲭ']), ('ⲭ', &['Ⲭ']), ('Ⲯ', &['ⲯ']), ('ⲯ', &['Ⲯ']), + ('Ⲱ', &['ⲱ']), ('ⲱ', &['Ⲱ']), ('Ⲳ', &['ⲳ']), ('ⲳ', &['Ⲳ']), + ('Ⲵ', &['ⲵ']), ('ⲵ', &['Ⲵ']), ('Ⲷ', &['ⲷ']), ('ⲷ', &['Ⲷ']), + ('Ⲹ', &['ⲹ']), ('ⲹ', &['Ⲹ']), ('Ⲻ', &['ⲻ']), ('ⲻ', &['Ⲻ']), + ('Ⲽ', &['ⲽ']), ('ⲽ', &['Ⲽ']), ('Ⲿ', &['ⲿ']), ('ⲿ', &['Ⲿ']), + ('Ⳁ', &['ⳁ']), ('ⳁ', &['Ⳁ']), ('Ⳃ', &['ⳃ']), ('ⳃ', &['Ⳃ']), + ('Ⳅ', &['ⳅ']), ('ⳅ', &['Ⳅ']), ('Ⳇ', &['ⳇ']), ('ⳇ', &['Ⳇ']), + ('Ⳉ', &['ⳉ']), ('ⳉ', &['Ⳉ']), ('Ⳋ', &['ⳋ']), ('ⳋ', &['Ⳋ']), + ('Ⳍ', &['ⳍ']), ('ⳍ', &['Ⳍ']), ('Ⳏ', &['ⳏ']), ('ⳏ', &['Ⳏ']), + ('Ⳑ', &['ⳑ']), ('ⳑ', &['Ⳑ']), ('Ⳓ', &['ⳓ']), ('ⳓ', &['Ⳓ']), + ('Ⳕ', &['ⳕ']), ('ⳕ', &['Ⳕ']), ('Ⳗ', &['ⳗ']), ('ⳗ', &['Ⳗ']), + ('Ⳙ', &['ⳙ']), ('ⳙ', &['Ⳙ']), ('Ⳛ', &['ⳛ']), ('ⳛ', &['Ⳛ']), + ('Ⳝ', &['ⳝ']), ('ⳝ', &['Ⳝ']), ('Ⳟ', &['ⳟ']), ('ⳟ', &['Ⳟ']), + ('Ⳡ', &['ⳡ']), ('ⳡ', &['Ⳡ']), ('Ⳣ', &['ⳣ']), ('ⳣ', &['Ⳣ']), + ('Ⳬ', &['ⳬ']), ('ⳬ', &['Ⳬ']), ('Ⳮ', &['ⳮ']), ('ⳮ', &['Ⳮ']), + ('Ⳳ', &['ⳳ']), ('ⳳ', &['Ⳳ']), ('ⴀ', &['Ⴀ']), ('ⴁ', &['Ⴁ']), + ('ⴂ', &['Ⴂ']), ('ⴃ', &['Ⴃ']), ('ⴄ', &['Ⴄ']), ('ⴅ', &['Ⴅ']), + ('ⴆ', &['Ⴆ']), ('ⴇ', &['Ⴇ']), ('ⴈ', &['Ⴈ']), ('ⴉ', &['Ⴉ']), + ('ⴊ', &['Ⴊ']), ('ⴋ', &['Ⴋ']), ('ⴌ', &['Ⴌ']), ('ⴍ', &['Ⴍ']), + ('ⴎ', &['Ⴎ']), ('ⴏ', &['Ⴏ']), ('ⴐ', &['Ⴐ']), ('ⴑ', &['Ⴑ']), + ('ⴒ', &['Ⴒ']), ('ⴓ', &['Ⴓ']), ('ⴔ', &['Ⴔ']), ('ⴕ', &['Ⴕ']), + ('ⴖ', &['Ⴖ']), ('ⴗ', &['Ⴗ']), ('ⴘ', &['Ⴘ']), ('ⴙ', &['Ⴙ']), + ('ⴚ', &['Ⴚ']), ('ⴛ', &['Ⴛ']), ('ⴜ', &['Ⴜ']), ('ⴝ', &['Ⴝ']), + ('ⴞ', &['Ⴞ']), ('ⴟ', &['Ⴟ']), ('ⴠ', &['Ⴠ']), ('ⴡ', &['Ⴡ']), + ('ⴢ', &['Ⴢ']), ('ⴣ', &['Ⴣ']), ('ⴤ', &['Ⴤ']), ('ⴥ', &['Ⴥ']), + ('ⴧ', &['Ⴧ']), ('ⴭ', &['Ⴭ']), ('Ꙁ', &['ꙁ']), ('ꙁ', &['Ꙁ']), + ('Ꙃ', &['ꙃ']), ('ꙃ', &['Ꙃ']), ('Ꙅ', &['ꙅ']), ('ꙅ', &['Ꙅ']), + ('Ꙇ', &['ꙇ']), ('ꙇ', &['Ꙇ']), ('Ꙉ', &['ꙉ']), ('ꙉ', &['Ꙉ']), + ('Ꙋ', &['ᲈ', 'ꙋ', ]), ('ꙋ', &['ᲈ', 'Ꙋ', ]), ('Ꙍ', &['ꙍ']), + ('ꙍ', &['Ꙍ']), ('Ꙏ', &['ꙏ']), ('ꙏ', &['Ꙏ']), ('Ꙑ', &['ꙑ']), + ('ꙑ', &['Ꙑ']), ('Ꙓ', &['ꙓ']), ('ꙓ', &['Ꙓ']), ('Ꙕ', &['ꙕ']), + ('ꙕ', &['Ꙕ']), ('Ꙗ', &['ꙗ']), ('ꙗ', &['Ꙗ']), ('Ꙙ', &['ꙙ']), + ('ꙙ', &['Ꙙ']), ('Ꙛ', &['ꙛ']), ('ꙛ', &['Ꙛ']), ('Ꙝ', &['ꙝ']), + ('ꙝ', &['Ꙝ']), ('Ꙟ', &['ꙟ']), ('ꙟ', &['Ꙟ']), ('Ꙡ', &['ꙡ']), + ('ꙡ', &['Ꙡ']), ('Ꙣ', &['ꙣ']), ('ꙣ', &['Ꙣ']), ('Ꙥ', &['ꙥ']), + ('ꙥ', &['Ꙥ']), ('Ꙧ', &['ꙧ']), ('ꙧ', &['Ꙧ']), ('Ꙩ', &['ꙩ']), + ('ꙩ', &['Ꙩ']), ('Ꙫ', &['ꙫ']), ('ꙫ', &['Ꙫ']), ('Ꙭ', &['ꙭ']), + ('ꙭ', &['Ꙭ']), ('Ꚁ', &['ꚁ']), ('ꚁ', &['Ꚁ']), ('Ꚃ', &['ꚃ']), + ('ꚃ', &['Ꚃ']), ('Ꚅ', &['ꚅ']), ('ꚅ', &['Ꚅ']), ('Ꚇ', &['ꚇ']), + ('ꚇ', &['Ꚇ']), ('Ꚉ', &['ꚉ']), ('ꚉ', &['Ꚉ']), ('Ꚋ', &['ꚋ']), + ('ꚋ', &['Ꚋ']), ('Ꚍ', &['ꚍ']), ('ꚍ', &['Ꚍ']), ('Ꚏ', &['ꚏ']), + ('ꚏ', &['Ꚏ']), ('Ꚑ', &['ꚑ']), ('ꚑ', &['Ꚑ']), ('Ꚓ', &['ꚓ']), + ('ꚓ', &['Ꚓ']), ('Ꚕ', &['ꚕ']), ('ꚕ', &['Ꚕ']), ('Ꚗ', &['ꚗ']), + ('ꚗ', &['Ꚗ']), ('Ꚙ', &['ꚙ']), ('ꚙ', &['Ꚙ']), ('Ꚛ', &['ꚛ']), + ('ꚛ', &['Ꚛ']), ('Ꜣ', &['ꜣ']), ('ꜣ', &['Ꜣ']), ('Ꜥ', &['ꜥ']), + ('ꜥ', &['Ꜥ']), ('Ꜧ', &['ꜧ']), ('ꜧ', &['Ꜧ']), ('Ꜩ', &['ꜩ']), + ('ꜩ', &['Ꜩ']), ('Ꜫ', &['ꜫ']), ('ꜫ', &['Ꜫ']), ('Ꜭ', &['ꜭ']), + ('ꜭ', &['Ꜭ']), ('Ꜯ', &['ꜯ']), ('ꜯ', &['Ꜯ']), ('Ꜳ', &['ꜳ']), + ('ꜳ', &['Ꜳ']), ('Ꜵ', &['ꜵ']), ('ꜵ', &['Ꜵ']), ('Ꜷ', &['ꜷ']), + ('ꜷ', &['Ꜷ']), ('Ꜹ', &['ꜹ']), ('ꜹ', &['Ꜹ']), ('Ꜻ', &['ꜻ']), + ('ꜻ', &['Ꜻ']), ('Ꜽ', &['ꜽ']), ('ꜽ', &['Ꜽ']), ('Ꜿ', &['ꜿ']), + ('ꜿ', &['Ꜿ']), ('Ꝁ', &['ꝁ']), ('ꝁ', &['Ꝁ']), ('Ꝃ', &['ꝃ']), + ('ꝃ', &['Ꝃ']), ('Ꝅ', &['ꝅ']), ('ꝅ', &['Ꝅ']), ('Ꝇ', &['ꝇ']), + ('ꝇ', &['Ꝇ']), ('Ꝉ', &['ꝉ']), ('ꝉ', &['Ꝉ']), ('Ꝋ', &['ꝋ']), + ('ꝋ', &['Ꝋ']), ('Ꝍ', &['ꝍ']), ('ꝍ', &['Ꝍ']), ('Ꝏ', &['ꝏ']), + ('ꝏ', &['Ꝏ']), ('Ꝑ', &['ꝑ']), ('ꝑ', &['Ꝑ']), ('Ꝓ', &['ꝓ']), + ('ꝓ', &['Ꝓ']), ('Ꝕ', &['ꝕ']), ('ꝕ', &['Ꝕ']), ('Ꝗ', &['ꝗ']), + ('ꝗ', &['Ꝗ']), ('Ꝙ', &['ꝙ']), ('ꝙ', &['Ꝙ']), ('Ꝛ', &['ꝛ']), + ('ꝛ', &['Ꝛ']), ('Ꝝ', &['ꝝ']), ('ꝝ', &['Ꝝ']), ('Ꝟ', &['ꝟ']), + ('ꝟ', &['Ꝟ']), ('Ꝡ', &['ꝡ']), ('ꝡ', &['Ꝡ']), ('Ꝣ', &['ꝣ']), + ('ꝣ', &['Ꝣ']), ('Ꝥ', &['ꝥ']), ('ꝥ', &['Ꝥ']), ('Ꝧ', &['ꝧ']), + ('ꝧ', &['Ꝧ']), ('Ꝩ', &['ꝩ']), ('ꝩ', &['Ꝩ']), ('Ꝫ', &['ꝫ']), + ('ꝫ', &['Ꝫ']), ('Ꝭ', &['ꝭ']), ('ꝭ', &['Ꝭ']), ('Ꝯ', &['ꝯ']), + ('ꝯ', &['Ꝯ']), ('Ꝺ', &['ꝺ']), ('ꝺ', &['Ꝺ']), ('Ꝼ', &['ꝼ']), + ('ꝼ', &['Ꝼ']), ('Ᵹ', &['ᵹ']), ('Ꝿ', &['ꝿ']), ('ꝿ', &['Ꝿ']), + ('Ꞁ', &['ꞁ']), ('ꞁ', &['Ꞁ']), ('Ꞃ', &['ꞃ']), ('ꞃ', &['Ꞃ']), + ('Ꞅ', &['ꞅ']), ('ꞅ', &['Ꞅ']), ('Ꞇ', &['ꞇ']), ('ꞇ', &['Ꞇ']), + ('Ꞌ', &['ꞌ']), ('ꞌ', &['Ꞌ']), ('Ɥ', &['ɥ']), ('Ꞑ', &['ꞑ']), + ('ꞑ', &['Ꞑ']), ('Ꞓ', &['ꞓ']), ('ꞓ', &['Ꞓ']), ('Ꞗ', &['ꞗ']), + ('ꞗ', &['Ꞗ']), ('Ꞙ', &['ꞙ']), ('ꞙ', &['Ꞙ']), ('Ꞛ', &['ꞛ']), + ('ꞛ', &['Ꞛ']), ('Ꞝ', &['ꞝ']), ('ꞝ', &['Ꞝ']), ('Ꞟ', &['ꞟ']), + ('ꞟ', &['Ꞟ']), ('Ꞡ', &['ꞡ']), ('ꞡ', &['Ꞡ']), ('Ꞣ', &['ꞣ']), + ('ꞣ', &['Ꞣ']), ('Ꞥ', &['ꞥ']), ('ꞥ', &['Ꞥ']), ('Ꞧ', &['ꞧ']), + ('ꞧ', &['Ꞧ']), ('Ꞩ', &['ꞩ']), ('ꞩ', &['Ꞩ']), ('Ɦ', &['ɦ']), + ('Ɜ', &['ɜ']), ('Ɡ', &['ɡ']), ('Ɬ', &['ɬ']), ('Ɪ', &['ɪ']), + ('Ʞ', &['ʞ']), ('Ʇ', &['ʇ']), ('Ʝ', &['ʝ']), ('Ꭓ', &['ꭓ']), + ('Ꞵ', &['ꞵ']), ('ꞵ', &['Ꞵ']), ('Ꞷ', &['ꞷ']), ('ꞷ', &['Ꞷ']), + ('ꭓ', &['Ꭓ']), ('ꭰ', &['Ꭰ']), ('ꭱ', &['Ꭱ']), ('ꭲ', &['Ꭲ']), + ('ꭳ', &['Ꭳ']), ('ꭴ', &['Ꭴ']), ('ꭵ', &['Ꭵ']), ('ꭶ', &['Ꭶ']), + ('ꭷ', &['Ꭷ']), ('ꭸ', &['Ꭸ']), ('ꭹ', &['Ꭹ']), ('ꭺ', &['Ꭺ']), + ('ꭻ', &['Ꭻ']), ('ꭼ', &['Ꭼ']), ('ꭽ', &['Ꭽ']), ('ꭾ', &['Ꭾ']), + ('ꭿ', &['Ꭿ']), ('ꮀ', &['Ꮀ']), ('ꮁ', &['Ꮁ']), ('ꮂ', &['Ꮂ']), + ('ꮃ', &['Ꮃ']), ('ꮄ', &['Ꮄ']), ('ꮅ', &['Ꮅ']), ('ꮆ', &['Ꮆ']), + ('ꮇ', &['Ꮇ']), ('ꮈ', &['Ꮈ']), ('ꮉ', &['Ꮉ']), ('ꮊ', &['Ꮊ']), + ('ꮋ', &['Ꮋ']), ('ꮌ', &['Ꮌ']), ('ꮍ', &['Ꮍ']), ('ꮎ', &['Ꮎ']), + ('ꮏ', &['Ꮏ']), ('ꮐ', &['Ꮐ']), ('ꮑ', &['Ꮑ']), ('ꮒ', &['Ꮒ']), + ('ꮓ', &['Ꮓ']), ('ꮔ', &['Ꮔ']), ('ꮕ', &['Ꮕ']), ('ꮖ', &['Ꮖ']), + ('ꮗ', &['Ꮗ']), ('ꮘ', &['Ꮘ']), ('ꮙ', &['Ꮙ']), ('ꮚ', &['Ꮚ']), + ('ꮛ', &['Ꮛ']), ('ꮜ', &['Ꮜ']), ('ꮝ', &['Ꮝ']), ('ꮞ', &['Ꮞ']), + ('ꮟ', &['Ꮟ']), ('ꮠ', &['Ꮠ']), ('ꮡ', &['Ꮡ']), ('ꮢ', &['Ꮢ']), + ('ꮣ', &['Ꮣ']), ('ꮤ', &['Ꮤ']), ('ꮥ', &['Ꮥ']), ('ꮦ', &['Ꮦ']), + ('ꮧ', &['Ꮧ']), ('ꮨ', &['Ꮨ']), ('ꮩ', &['Ꮩ']), ('ꮪ', &['Ꮪ']), + ('ꮫ', &['Ꮫ']), ('ꮬ', &['Ꮬ']), ('ꮭ', &['Ꮭ']), ('ꮮ', &['Ꮮ']), + ('ꮯ', &['Ꮯ']), ('ꮰ', &['Ꮰ']), ('ꮱ', &['Ꮱ']), ('ꮲ', &['Ꮲ']), + ('ꮳ', &['Ꮳ']), ('ꮴ', &['Ꮴ']), ('ꮵ', &['Ꮵ']), ('ꮶ', &['Ꮶ']), + ('ꮷ', &['Ꮷ']), ('ꮸ', &['Ꮸ']), ('ꮹ', &['Ꮹ']), ('ꮺ', &['Ꮺ']), + ('ꮻ', &['Ꮻ']), ('ꮼ', &['Ꮼ']), ('ꮽ', &['Ꮽ']), ('ꮾ', &['Ꮾ']), + ('ꮿ', &['Ꮿ']), ('A', &['a']), ('B', &['b']), ('C', &['c']), + ('D', &['d']), ('E', &['e']), ('F', &['f']), ('G', &['g']), + ('H', &['h']), ('I', &['i']), ('J', &['j']), ('K', &['k']), + ('L', &['l']), ('M', &['m']), ('N', &['n']), ('O', &['o']), + ('P', &['p']), ('Q', &['q']), ('R', &['r']), ('S', &['s']), + ('T', &['t']), ('U', &['u']), ('V', &['v']), ('W', &['w']), + ('X', &['x']), ('Y', &['y']), ('Z', &['z']), ('a', &['A']), + ('b', &['B']), ('c', &['C']), ('d', &['D']), ('e', &['E']), + ('f', &['F']), ('g', &['G']), ('h', &['H']), ('i', &['I']), + ('j', &['J']), ('k', &['K']), ('l', &['L']), ('m', &['M']), + ('n', &['N']), ('o', &['O']), ('p', &['P']), ('q', &['Q']), + ('r', &['R']), ('s', &['S']), ('t', &['T']), ('u', &['U']), + ('v', &['V']), ('w', &['W']), ('x', &['X']), ('y', &['Y']), + ('z', &['Z']), ('𐐀', &['𐐨']), ('𐐁', &['𐐩']), ('𐐂', &[ + '𐐪']), ('𐐃', &['𐐫']), ('𐐄', &['𐐬']), ('𐐅', &['𐐭']), + ('𐐆', &['𐐮']), ('𐐇', &['𐐯']), ('𐐈', &['𐐰']), ('𐐉', &[ + '𐐱']), ('𐐊', &['𐐲']), ('𐐋', &['𐐳']), ('𐐌', &['𐐴']), + ('𐐍', &['𐐵']), ('𐐎', &['𐐶']), ('𐐏', &['𐐷']), ('𐐐', &[ + '𐐸']), ('𐐑', &['𐐹']), ('𐐒', &['𐐺']), ('𐐓', &['𐐻']), + ('𐐔', &['𐐼']), ('𐐕', &['𐐽']), ('𐐖', &['𐐾']), ('𐐗', &[ + '𐐿']), ('𐐘', &['𐑀']), ('𐐙', &['𐑁']), ('𐐚', &['𐑂']), + ('𐐛', &['𐑃']), ('𐐜', &['𐑄']), ('𐐝', &['𐑅']), ('𐐞', &[ + '𐑆']), ('𐐟', &['𐑇']), ('𐐠', &['𐑈']), ('𐐡', &['𐑉']), + ('𐐢', &['𐑊']), ('𐐣', &['𐑋']), ('𐐤', &['𐑌']), ('𐐥', &[ + '𐑍']), ('𐐦', &['𐑎']), ('𐐧', &['𐑏']), ('𐐨', &['𐐀']), + ('𐐩', &['𐐁']), ('𐐪', &['𐐂']), ('𐐫', &['𐐃']), ('𐐬', &[ + '𐐄']), ('𐐭', &['𐐅']), ('𐐮', &['𐐆']), ('𐐯', &['𐐇']), + ('𐐰', &['𐐈']), ('𐐱', &['𐐉']), ('𐐲', &['𐐊']), ('𐐳', &[ + '𐐋']), ('𐐴', &['𐐌']), ('𐐵', &['𐐍']), ('𐐶', &['𐐎']), + ('𐐷', &['𐐏']), ('𐐸', &['𐐐']), ('𐐹', &['𐐑']), ('𐐺', &[ + '𐐒']), ('𐐻', &['𐐓']), ('𐐼', &['𐐔']), ('𐐽', &['𐐕']), + ('𐐾', &['𐐖']), ('𐐿', &['𐐗']), ('𐑀', &['𐐘']), ('𐑁', &[ + '𐐙']), ('𐑂', &['𐐚']), ('𐑃', &['𐐛']), ('𐑄', &['𐐜']), + ('𐑅', &['𐐝']), ('𐑆', &['𐐞']), ('𐑇', &['𐐟']), ('𐑈', &[ + '𐐠']), ('𐑉', &['𐐡']), ('𐑊', &['𐐢']), ('𐑋', &['𐐣']), + ('𐑌', &['𐐤']), ('𐑍', &['𐐥']), ('𐑎', &['𐐦']), ('𐑏', &[ + '𐐧']), ('𐒰', &['𐓘']), ('𐒱', &['𐓙']), ('𐒲', &['𐓚']), + ('𐒳', &['𐓛']), ('𐒴', &['𐓜']), ('𐒵', &['𐓝']), ('𐒶', &[ + '𐓞']), ('𐒷', &['𐓟']), ('𐒸', &['𐓠']), ('𐒹', &['𐓡']), + ('𐒺', &['𐓢']), ('𐒻', &['𐓣']), ('𐒼', &['𐓤']), ('𐒽', &[ + '𐓥']), ('𐒾', &['𐓦']), ('𐒿', &['𐓧']), ('𐓀', &['𐓨']), + ('𐓁', &['𐓩']), ('𐓂', &['𐓪']), ('𐓃', &['𐓫']), ('𐓄', &[ + '𐓬']), ('𐓅', &['𐓭']), ('𐓆', &['𐓮']), ('𐓇', &['𐓯']), + ('𐓈', &['𐓰']), ('𐓉', &['𐓱']), ('𐓊', &['𐓲']), ('𐓋', &[ + '𐓳']), ('𐓌', &['𐓴']), ('𐓍', &['𐓵']), ('𐓎', &['𐓶']), + ('𐓏', &['𐓷']), ('𐓐', &['𐓸']), ('𐓑', &['𐓹']), ('𐓒', &[ + '𐓺']), ('𐓓', &['𐓻']), ('𐓘', &['𐒰']), ('𐓙', &['𐒱']), + ('𐓚', &['𐒲']), ('𐓛', &['𐒳']), ('𐓜', &['𐒴']), ('𐓝', &[ + '𐒵']), ('𐓞', &['𐒶']), ('𐓟', &['𐒷']), ('𐓠', &['𐒸']), + ('𐓡', &['𐒹']), ('𐓢', &['𐒺']), ('𐓣', &['𐒻']), ('𐓤', &[ + '𐒼']), ('𐓥', &['𐒽']), ('𐓦', &['𐒾']), ('𐓧', &['𐒿']), + ('𐓨', &['𐓀']), ('𐓩', &['𐓁']), ('𐓪', &['𐓂']), ('𐓫', &[ + '𐓃']), ('𐓬', &['𐓄']), ('𐓭', &['𐓅']), ('𐓮', &['𐓆']), + ('𐓯', &['𐓇']), ('𐓰', &['𐓈']), ('𐓱', &['𐓉']), ('𐓲', &[ + '𐓊']), ('𐓳', &['𐓋']), ('𐓴', &['𐓌']), ('𐓵', &['𐓍']), + ('𐓶', &['𐓎']), ('𐓷', &['𐓏']), ('𐓸', &['𐓐']), ('𐓹', &[ + '𐓑']), ('𐓺', &['𐓒']), ('𐓻', &['𐓓']), ('𐲀', &['𐳀']), + ('𐲁', &['𐳁']), ('𐲂', &['𐳂']), ('𐲃', &['𐳃']), ('𐲄', &[ + '𐳄']), ('𐲅', &['𐳅']), ('𐲆', &['𐳆']), ('𐲇', &['𐳇']), + ('𐲈', &['𐳈']), ('𐲉', &['𐳉']), ('𐲊', &['𐳊']), ('𐲋', &[ + '𐳋']), ('𐲌', &['𐳌']), ('𐲍', &['𐳍']), ('𐲎', &['𐳎']), + ('𐲏', &['𐳏']), ('𐲐', &['𐳐']), ('𐲑', &['𐳑']), ('𐲒', &[ + '𐳒']), ('𐲓', &['𐳓']), ('𐲔', &['𐳔']), ('𐲕', &['𐳕']), + ('𐲖', &['𐳖']), ('𐲗', &['𐳗']), ('𐲘', &['𐳘']), ('𐲙', &[ + '𐳙']), ('𐲚', &['𐳚']), ('𐲛', &['𐳛']), ('𐲜', &['𐳜']), + ('𐲝', &['𐳝']), ('𐲞', &['𐳞']), ('𐲟', &['𐳟']), ('𐲠', &[ + '𐳠']), ('𐲡', &['𐳡']), ('𐲢', &['𐳢']), ('𐲣', &['𐳣']), + ('𐲤', &['𐳤']), ('𐲥', &['𐳥']), ('𐲦', &['𐳦']), ('𐲧', &[ + '𐳧']), ('𐲨', &['𐳨']), ('𐲩', &['𐳩']), ('𐲪', &['𐳪']), + ('𐲫', &['𐳫']), ('𐲬', &['𐳬']), ('𐲭', &['𐳭']), ('𐲮', &[ + '𐳮']), ('𐲯', &['𐳯']), ('𐲰', &['𐳰']), ('𐲱', &['𐳱']), + ('𐲲', &['𐳲']), ('𐳀', &['𐲀']), ('𐳁', &['𐲁']), ('𐳂', &[ + '𐲂']), ('𐳃', &['𐲃']), ('𐳄', &['𐲄']), ('𐳅', &['𐲅']), + ('𐳆', &['𐲆']), ('𐳇', &['𐲇']), ('𐳈', &['𐲈']), ('𐳉', &[ + '𐲉']), ('𐳊', &['𐲊']), ('𐳋', &['𐲋']), ('𐳌', &['𐲌']), + ('𐳍', &['𐲍']), ('𐳎', &['𐲎']), ('𐳏', &['𐲏']), ('𐳐', &[ + '𐲐']), ('𐳑', &['𐲑']), ('𐳒', &['𐲒']), ('𐳓', &['𐲓']), + ('𐳔', &['𐲔']), ('𐳕', &['𐲕']), ('𐳖', &['𐲖']), ('𐳗', &[ + '𐲗']), ('𐳘', &['𐲘']), ('𐳙', &['𐲙']), ('𐳚', &['𐲚']), + ('𐳛', &['𐲛']), ('𐳜', &['𐲜']), ('𐳝', &['𐲝']), ('𐳞', &[ + '𐲞']), ('𐳟', &['𐲟']), ('𐳠', &['𐲠']), ('𐳡', &['𐲡']), + ('𐳢', &['𐲢']), ('𐳣', &['𐲣']), ('𐳤', &['𐲤']), ('𐳥', &[ + '𐲥']), ('𐳦', &['𐲦']), ('𐳧', &['𐲧']), ('𐳨', &['𐲨']), + ('𐳩', &['𐲩']), ('𐳪', &['𐲪']), ('𐳫', &['𐲫']), ('𐳬', &[ + '𐲬']), ('𐳭', &['𐲭']), ('𐳮', &['𐲮']), ('𐳯', &['𐲯']), + ('𐳰', &['𐲰']), ('𐳱', &['𐲱']), ('𐳲', &['𐲲']), ('𑢠', &[ + '𑣀']), ('𑢡', &['𑣁']), ('𑢢', &['𑣂']), ('𑢣', &['𑣃']), + ('𑢤', &['𑣄']), ('𑢥', &['𑣅']), ('𑢦', &['𑣆']), ('𑢧', &[ + '𑣇']), ('𑢨', &['𑣈']), ('𑢩', &['𑣉']), ('𑢪', &['𑣊']), + ('𑢫', &['𑣋']), ('𑢬', &['𑣌']), ('𑢭', &['𑣍']), ('𑢮', &[ + '𑣎']), ('𑢯', &['𑣏']), ('𑢰', &['𑣐']), ('𑢱', &['𑣑']), + ('𑢲', &['𑣒']), ('𑢳', &['𑣓']), ('𑢴', &['𑣔']), ('𑢵', &[ + '𑣕']), ('𑢶', &['𑣖']), ('𑢷', &['𑣗']), ('𑢸', &['𑣘']), + ('𑢹', &['𑣙']), ('𑢺', &['𑣚']), ('𑢻', &['𑣛']), ('𑢼', &[ + '𑣜']), ('𑢽', &['𑣝']), ('𑢾', &['𑣞']), ('𑢿', &['𑣟']), + ('𑣀', &['𑢠']), ('𑣁', &['𑢡']), ('𑣂', &['𑢢']), ('𑣃', &[ + '𑢣']), ('𑣄', &['𑢤']), ('𑣅', &['𑢥']), ('𑣆', &['𑢦']), + ('𑣇', &['𑢧']), ('𑣈', &['𑢨']), ('𑣉', &['𑢩']), ('𑣊', &[ + '𑢪']), ('𑣋', &['𑢫']), ('𑣌', &['𑢬']), ('𑣍', &['𑢭']), + ('𑣎', &['𑢮']), ('𑣏', &['𑢯']), ('𑣐', &['𑢰']), ('𑣑', &[ + '𑢱']), ('𑣒', &['𑢲']), ('𑣓', &['𑢳']), ('𑣔', &['𑢴']), + ('𑣕', &['𑢵']), ('𑣖', &['𑢶']), ('𑣗', &['𑢷']), ('𑣘', &[ + '𑢸']), ('𑣙', &['𑢹']), ('𑣚', &['𑢺']), ('𑣛', &['𑢻']), + ('𑣜', &['𑢼']), ('𑣝', &['𑢽']), ('𑣞', &['𑢾']), ('𑣟', &[ + '𑢿']), ('𞤀', &['𞤢']), ('𞤁', &['𞤣']), ('𞤂', &['𞤤']), + ('𞤃', &['𞤥']), ('𞤄', &['𞤦']), ('𞤅', &['𞤧']), ('𞤆', &[ + '𞤨']), ('𞤇', &['𞤩']), ('𞤈', &['𞤪']), ('𞤉', &['𞤫']), + ('𞤊', &['𞤬']), ('𞤋', &['𞤭']), ('𞤌', &['𞤮']), ('𞤍', &[ + '𞤯']), ('𞤎', &['𞤰']), ('𞤏', &['𞤱']), ('𞤐', &['𞤲']), + ('𞤑', &['𞤳']), ('𞤒', &['𞤴']), ('𞤓', &['𞤵']), ('𞤔', &[ + '𞤶']), ('𞤕', &['𞤷']), ('𞤖', &['𞤸']), ('𞤗', &['𞤹']), + ('𞤘', &['𞤺']), ('𞤙', &['𞤻']), ('𞤚', &['𞤼']), ('𞤛', &[ + '𞤽']), ('𞤜', &['𞤾']), ('𞤝', &['𞤿']), ('𞤞', &['𞥀']), + ('𞤟', &['𞥁']), ('𞤠', &['𞥂']), ('𞤡', &['𞥃']), ('𞤢', &[ + '𞤀']), ('𞤣', &['𞤁']), ('𞤤', &['𞤂']), ('𞤥', &['𞤃']), + ('𞤦', &['𞤄']), ('𞤧', &['𞤅']), ('𞤨', &['𞤆']), ('𞤩', &[ + '𞤇']), ('𞤪', &['𞤈']), ('𞤫', &['𞤉']), ('𞤬', &['𞤊']), + ('𞤭', &['𞤋']), ('𞤮', &['𞤌']), ('𞤯', &['𞤍']), ('𞤰', &[ + '𞤎']), ('𞤱', &['𞤏']), ('𞤲', &['𞤐']), ('𞤳', &['𞤑']), + ('𞤴', &['𞤒']), ('𞤵', &['𞤓']), ('𞤶', &['𞤔']), ('𞤷', &[ + '𞤕']), ('𞤸', &['𞤖']), ('𞤹', &['𞤗']), ('𞤺', &['𞤘']), + ('𞤻', &['𞤙']), ('𞤼', &['𞤚']), ('𞤽', &['𞤛']), ('𞤾', &[ + '𞤜']), ('𞤿', &['𞤝']), ('𞥀', &['𞤞']), ('𞥁', &['𞤟']), + ('𞥂', &['𞤠']), ('𞥃', &['𞤡']), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/general_category.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/general_category.rs new file mode 100644 index 0000000..451a0b2 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/general_category.rs @@ -0,0 +1,1844 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate general-category tmp/ucd-10.0.0/ --chars --exclude surrogate +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("Cased_Letter", CASED_LETTER), ("Close_Punctuation", CLOSE_PUNCTUATION), + ("Connector_Punctuation", CONNECTOR_PUNCTUATION), ("Control", CONTROL), + ("Currency_Symbol", CURRENCY_SYMBOL), + ("Dash_Punctuation", DASH_PUNCTUATION), ("Decimal_Number", DECIMAL_NUMBER), + ("Enclosing_Mark", ENCLOSING_MARK), + ("Final_Punctuation", FINAL_PUNCTUATION), ("Format", FORMAT), + ("Initial_Punctuation", INITIAL_PUNCTUATION), ("Letter", LETTER), + ("Letter_Number", LETTER_NUMBER), ("Line_Separator", LINE_SEPARATOR), + ("Lowercase_Letter", LOWERCASE_LETTER), ("Mark", MARK), + ("Math_Symbol", MATH_SYMBOL), ("Modifier_Letter", MODIFIER_LETTER), + ("Modifier_Symbol", MODIFIER_SYMBOL), ("Nonspacing_Mark", NONSPACING_MARK), + ("Number", NUMBER), ("Open_Punctuation", OPEN_PUNCTUATION), + ("Other", OTHER), ("Other_Letter", OTHER_LETTER), + ("Other_Number", OTHER_NUMBER), ("Other_Punctuation", OTHER_PUNCTUATION), + ("Other_Symbol", OTHER_SYMBOL), + ("Paragraph_Separator", PARAGRAPH_SEPARATOR), ("Private_Use", PRIVATE_USE), + ("Punctuation", PUNCTUATION), ("Separator", SEPARATOR), + ("Space_Separator", SPACE_SEPARATOR), ("Spacing_Mark", SPACING_MARK), + ("Symbol", SYMBOL), ("Titlecase_Letter", TITLECASE_LETTER), + ("Unassigned", UNASSIGNED), ("Uppercase_Letter", UPPERCASE_LETTER), +]; + +pub const CASED_LETTER: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('µ', 'µ'), ('À', 'Ö'), ('Ø', 'ö'), + ('ø', 'ƺ'), ('Ƽ', 'ƿ'), ('DŽ', 'ʓ'), ('ʕ', 'ʯ'), ('Ͱ', 'ͳ'), + ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ա', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᴫ'), + ('ᵫ', 'ᵷ'), ('ᵹ', 'ᶚ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), + ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῼ'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), + ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), + ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℯ', 'ℴ'), ('ℹ', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ↄ', 'ↄ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⱻ'), ('Ȿ', 'ⳤ'), + ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), + ('ⴭ', 'ⴭ'), ('Ꙁ', 'ꙭ'), ('Ꚁ', 'ꚛ'), ('Ꜣ', 'ꝯ'), + ('ꝱ', 'ꞇ'), ('Ꞌ', 'ꞎ'), ('Ꞑ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟺ', 'ꟺ'), ('ꬰ', 'ꭚ'), ('ꭠ', 'ꭥ'), ('ꭰ', 'ꮿ'), + ('ff', 'st'), ('ﬓ', 'ﬗ'), ('A', 'Z'), ('a', 'z'), + ('𐐀', '𐑏'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐲀', '𐲲'), + ('𐳀', '𐳲'), ('𑢠', '𑣟'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), + ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), + ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), + ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), + ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), + ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), + ('𞤀', '𞥃'), +]; + +pub const CLOSE_PUNCTUATION: &'static [(char, char)] = &[ + (')', ')'), (']', ']'), ('}', '}'), ('༻', '༻'), ('༽', '༽'), + ('᚜', '᚜'), ('⁆', '⁆'), ('⁾', '⁾'), ('₎', '₎'), + ('⌉', '⌉'), ('⌋', '⌋'), ('〉', '〉'), ('❩', '❩'), + ('❫', '❫'), ('❭', '❭'), ('❯', '❯'), ('❱', '❱'), + ('❳', '❳'), ('❵', '❵'), ('⟆', '⟆'), ('⟧', '⟧'), + ('⟩', '⟩'), ('⟫', '⟫'), ('⟭', '⟭'), ('⟯', '⟯'), + ('⦄', '⦄'), ('⦆', '⦆'), ('⦈', '⦈'), ('⦊', '⦊'), + ('⦌', '⦌'), ('⦎', '⦎'), ('⦐', '⦐'), ('⦒', '⦒'), + ('⦔', '⦔'), ('⦖', '⦖'), ('⦘', '⦘'), ('⧙', '⧙'), + ('⧛', '⧛'), ('⧽', '⧽'), ('⸣', '⸣'), ('⸥', '⸥'), + ('⸧', '⸧'), ('⸩', '⸩'), ('〉', '〉'), ('》', '》'), + ('」', '」'), ('』', '』'), ('】', '】'), ('〕', '〕'), + ('〗', '〗'), ('〙', '〙'), ('〛', '〛'), ('〞', '〟'), + ('﴾', '﴾'), ('︘', '︘'), ('︶', '︶'), ('︸', '︸'), + ('︺', '︺'), ('︼', '︼'), ('︾', '︾'), ('﹀', '﹀'), + ('﹂', '﹂'), ('﹄', '﹄'), ('﹈', '﹈'), ('﹚', '﹚'), + ('﹜', '﹜'), ('﹞', '﹞'), (')', ')'), (']', ']'), + ('}', '}'), ('⦆', '⦆'), ('」', '」'), +]; + +pub const CONNECTOR_PUNCTUATION: &'static [(char, char)] = &[ + ('_', '_'), ('‿', '⁀'), ('⁔', '⁔'), ('︳', '︴'), ('﹍', '﹏'), + ('_', '_'), +]; + +pub const CONTROL: &'static [(char, char)] = &[ + ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), +]; + +pub const CURRENCY_SYMBOL: &'static [(char, char)] = &[ + ('$', '$'), ('¢', '¥'), ('֏', '֏'), ('؋', '؋'), ('৲', '৳'), + ('৻', '৻'), ('૱', '૱'), ('௹', '௹'), ('฿', '฿'), + ('៛', '៛'), ('₠', '₿'), ('꠸', '꠸'), ('﷼', '﷼'), + ('﹩', '﹩'), ('$', '$'), ('¢', '£'), ('¥', '₩'), +]; + +pub const DASH_PUNCTUATION: &'static [(char, char)] = &[ + ('-', '-'), ('֊', '֊'), ('־', '־'), ('᐀', '᐀'), ('᠆', '᠆'), + ('‐', '―'), ('⸗', '⸗'), ('⸚', '⸚'), ('⸺', '⸻'), + ('⹀', '⹀'), ('〜', '〜'), ('〰', '〰'), ('゠', '゠'), + ('︱', '︲'), ('﹘', '﹘'), ('﹣', '﹣'), ('-', '-'), +]; + +pub const DECIMAL_NUMBER: &'static [(char, char)] = &[ + ('0', '9'), ('٠', '٩'), ('۰', '۹'), ('߀', '߉'), ('०', '९'), + ('০', '৯'), ('੦', '੯'), ('૦', '૯'), ('୦', '୯'), + ('௦', '௯'), ('౦', '౯'), ('೦', '೯'), ('൦', '൯'), + ('෦', '෯'), ('๐', '๙'), ('໐', '໙'), ('༠', '༩'), + ('၀', '၉'), ('႐', '႙'), ('០', '៩'), ('᠐', '᠙'), + ('᥆', '᥏'), ('᧐', '᧙'), ('᪀', '᪉'), ('᪐', '᪙'), + ('᭐', '᭙'), ('᮰', '᮹'), ('᱀', '᱉'), ('᱐', '᱙'), + ('꘠', '꘩'), ('꣐', '꣙'), ('꤀', '꤉'), ('꧐', '꧙'), + ('꧰', '꧹'), ('꩐', '꩙'), ('꯰', '꯹'), ('0', '9'), + ('𐒠', '𐒩'), ('𑁦', '𑁯'), ('𑃰', '𑃹'), ('𑄶', '𑄿'), + ('𑇐', '𑇙'), ('𑋰', '𑋹'), ('𑑐', '𑑙'), ('𑓐', '𑓙'), + ('𑙐', '𑙙'), ('𑛀', '𑛉'), ('𑜰', '𑜹'), ('𑣠', '𑣩'), + ('𑱐', '𑱙'), ('𑵐', '𑵙'), ('𖩠', '𖩩'), ('𖭐', '𖭙'), + ('𝟎', '𝟿'), ('𞥐', '𞥙'), +]; + +pub const ENCLOSING_MARK: &'static [(char, char)] = &[ + ('҈', '҉'), ('᪾', '᪾'), ('⃝', '⃠'), ('⃢', '⃤'), + ('꙰', '꙲'), +]; + +pub const FINAL_PUNCTUATION: &'static [(char, char)] = &[ + ('»', '»'), ('’', '’'), ('”', '”'), ('›', '›'), + ('⸃', '⸃'), ('⸅', '⸅'), ('⸊', '⸊'), ('⸍', '⸍'), + ('⸝', '⸝'), ('⸡', '⸡'), +]; + +pub const FORMAT: &'static [(char, char)] = &[ + ('\u{ad}', '\u{ad}'), ('\u{600}', '\u{605}'), ('\u{61c}', '\u{61c}'), + ('\u{6dd}', '\u{6dd}'), ('\u{70f}', '\u{70f}'), ('\u{8e2}', '\u{8e2}'), + ('\u{180e}', '\u{180e}'), ('\u{200b}', '\u{200f}'), + ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{2064}'), + ('\u{2066}', '\u{206f}'), ('\u{feff}', '\u{feff}'), + ('\u{fff9}', '\u{fffb}'), ('\u{110bd}', '\u{110bd}'), + ('\u{1bca0}', '\u{1bca3}'), ('\u{1d173}', '\u{1d17a}'), + ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}'), +]; + +pub const INITIAL_PUNCTUATION: &'static [(char, char)] = &[ + ('«', '«'), ('‘', '‘'), ('‛', '“'), ('‟', '‟'), + ('‹', '‹'), ('⸂', '⸂'), ('⸄', '⸄'), ('⸉', '⸉'), + ('⸌', '⸌'), ('⸜', '⸜'), ('⸠', '⸠'), +]; + +pub const LETTER: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), + ('ա', 'և'), ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۥ', 'ۦ'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), + ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), + ('ॐ', 'ॐ'), ('क़', 'ॡ'), ('ॱ', 'ঀ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), + ('য়', 'ৡ'), ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੲ', 'ੴ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), + ('ୱ', 'ୱ'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ఽ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), + ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), + ('ವ', 'ಹ'), ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), + ('ೱ', 'ೲ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), + ('ൺ', 'ൿ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'ำ'), + ('เ', 'ๆ'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), + ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), + ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), + ('ອ', 'ະ'), ('າ', 'ຳ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), + ('ໆ', 'ໆ'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), + ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), ('က', 'ဪ'), ('ဿ', 'ဿ'), + ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), + ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), ('ႎ', 'ႎ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛱ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢄ'), ('ᢇ', 'ᢨ'), ('ᢪ', 'ᢪ'), + ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), + ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), ('ᨠ', 'ᩔ'), + ('ᪧ', 'ᪧ'), ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), + ('ᮮ', 'ᮯ'), ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), + ('ᱚ', 'ᱽ'), ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), + ('ᳵ', 'ᳶ'), ('ᴀ', 'ᶿ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), + ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῼ'), ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), + ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), + ('K', 'ℭ'), ('ℯ', 'ℹ'), ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), + ('ⅎ', 'ⅎ'), ('Ↄ', 'ↄ'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), + ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), + ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), + ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), + ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), + ('ⷘ', 'ⷞ'), ('ⸯ', 'ⸯ'), ('々', '〆'), ('〱', '〵'), + ('〻', '〼'), ('ぁ', 'ゖ'), ('ゝ', 'ゟ'), ('ァ', 'ヺ'), + ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), + ('ㇰ', 'ㇿ'), ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꒌ'), + ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘟ'), ('ꘪ', 'ꘫ'), + ('Ꙁ', 'ꙮ'), ('ꙿ', 'ꚝ'), ('ꚠ', 'ꛥ'), ('ꜗ', 'ꜟ'), + ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), + ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), + ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), + ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), + ('ꧏ', 'ꧏ'), ('ꧠ', 'ꧤ'), ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), + ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), ('ꩄ', 'ꩋ'), ('ꩠ', 'ꩶ'), + ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), + ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), + ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫴ'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), + ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), + ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯢ'), ('가', '힣'), ('ힰ', 'ퟆ'), + ('ퟋ', 'ퟻ'), ('豈', '舘'), ('並', '龎'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('יִ', 'יִ'), ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), + ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), + ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), + ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), ('A', 'Z'), + ('a', 'z'), ('ヲ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), + ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), ('𐀍', '𐀦'), + ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), ('𐁐', '𐁝'), + ('𐂀', '𐃺'), ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐌀', '𐌟'), + ('𐌭', '𐍀'), ('𐍂', '𐍉'), ('𐍐', '𐍵'), ('𐎀', '𐎝'), + ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐐀', '𐒝'), ('𐒰', '𐓓'), + ('𐓘', '𐓻'), ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), + ('𐡠', '𐡶'), ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐤀', '𐤕'), ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), + ('𐨀', '𐨀'), ('𐨐', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀃', '𑀷'), + ('𑂃', '𑂯'), ('𑃐', '𑃨'), ('𑄃', '𑄦'), ('𑅐', '𑅲'), + ('𑅶', '𑅶'), ('𑆃', '𑆲'), ('𑇁', '𑇄'), ('𑇚', '𑇚'), + ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈫'), ('𑊀', '𑊆'), + ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊨'), + ('𑊰', '𑋞'), ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), + ('𑌪', '𑌰'), ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌽', '𑌽'), + ('𑍐', '𑍐'), ('𑍝', '𑍡'), ('𑐀', '𑐴'), ('𑑇', '𑑊'), + ('𑒀', '𑒯'), ('𑓄', '𑓅'), ('𑓇', '𑓇'), ('𑖀', '𑖮'), + ('𑗘', '𑗛'), ('𑘀', '𑘯'), ('𑙄', '𑙄'), ('𑚀', '𑚪'), + ('𑜀', '𑜙'), ('𑢠', '𑣟'), ('𑣿', '𑣿'), ('𑨀', '𑨀'), + ('𑨋', '𑨲'), ('𑨺', '𑨺'), ('𑩐', '𑩐'), ('𑩜', '𑪃'), + ('𑪆', '𑪉'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰮'), + ('𑱀', '𑱀'), ('𑱲', '𑲏'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), + ('𑴋', '𑴰'), ('𑵆', '𑵆'), ('𒀀', '𒎙'), ('𒒀', '𒕃'), + ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), + ('𖫐', '𖫭'), ('𖬀', '𖬯'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𞠀', '𞣄'), + ('𞤀', '𞥃'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const LETTER_NUMBER: &'static [(char, char)] = &[ + ('ᛮ', 'ᛰ'), ('Ⅰ', 'ↂ'), ('ↅ', 'ↈ'), ('〇', '〇'), + ('〡', '〩'), ('〸', '〺'), ('ꛦ', 'ꛯ'), ('𐅀', '𐅴'), + ('𐍁', '𐍁'), ('𐍊', '𐍊'), ('𐏑', '𐏕'), ('𒐀', '𒑮'), +]; + +pub const LINE_SEPARATOR: &'static [(char, char)] = &[ + ('\u{2028}', '\u{2028}'), +]; + +pub const LOWERCASE_LETTER: &'static [(char, char)] = &[ + ('a', 'z'), ('µ', 'µ'), ('ß', 'ö'), ('ø', 'ÿ'), ('ā', 'ā'), + ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), ('ĉ', 'ĉ'), ('ċ', 'ċ'), + ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), ('ē', 'ē'), ('ĕ', 'ĕ'), + ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), ('ĝ', 'ĝ'), ('ğ', 'ğ'), + ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), ('ħ', 'ħ'), ('ĩ', 'ĩ'), + ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), ('ı', 'ı'), ('ij', 'ij'), + ('ĵ', 'ĵ'), ('ķ', 'ĸ'), ('ĺ', 'ĺ'), ('ļ', 'ļ'), ('ľ', 'ľ'), + ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), ('ņ', 'ņ'), ('ň', 'ʼn'), + ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), ('ő', 'ő'), ('œ', 'œ'), + ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), ('ś', 'ś'), ('ŝ', 'ŝ'), + ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), ('ť', 'ť'), ('ŧ', 'ŧ'), + ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), ('ů', 'ů'), ('ű', 'ű'), + ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), ('ź', 'ź'), ('ż', 'ż'), + ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), ('ƈ', 'ƈ'), ('ƌ', 'ƍ'), + ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƛ'), ('ƞ', 'ƞ'), ('ơ', 'ơ'), + ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), ('ƪ', 'ƫ'), ('ƭ', 'ƭ'), + ('ư', 'ư'), ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), ('ƹ', 'ƺ'), ('ƽ', 'ƿ'), + ('dž', 'dž'), ('lj', 'lj'), ('nj', 'nj'), ('ǎ', 'ǎ'), ('ǐ', 'ǐ'), + ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), ('ǘ', 'ǘ'), ('ǚ', 'ǚ'), + ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), ('ǣ', 'ǣ'), ('ǥ', 'ǥ'), + ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), ('ǭ', 'ǭ'), ('ǯ', 'ǰ'), + ('dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), ('ǻ', 'ǻ'), ('ǽ', 'ǽ'), + ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), ('ȅ', 'ȅ'), ('ȇ', 'ȇ'), + ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), ('ȏ', 'ȏ'), ('ȑ', 'ȑ'), + ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), ('ș', 'ș'), ('ț', 'ț'), + ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȡ', 'ȡ'), ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), + ('ȧ', 'ȧ'), ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), + ('ȱ', 'ȱ'), ('ȳ', 'ȹ'), ('ȼ', 'ȼ'), ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), + ('ɇ', 'ɇ'), ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), ('ɍ', 'ɍ'), ('ɏ', 'ʓ'), + ('ʕ', 'ʯ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), ('ϙ', 'ϙ'), + ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('ϣ', 'ϣ'), + ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), ('ϭ', 'ϭ'), + ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϼ'), ('а', 'џ'), + ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), ('ѩ', 'ѩ'), + ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), ('ѳ', 'ѳ'), + ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), ('ѽ', 'ѽ'), + ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), ('ҏ', 'ҏ'), + ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), ('ҙ', 'ҙ'), + ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), ('ң', 'ң'), + ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), ('ҭ', 'ҭ'), + ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), ('ҷ', 'ҷ'), + ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), ('ӂ', 'ӂ'), + ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), ('ӌ', 'ӌ'), + ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), ('ӗ', 'ӗ'), + ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), ('ӡ', 'ӡ'), + ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), ('ӫ', 'ӫ'), + ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), ('ӵ', 'ӵ'), + ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), ('ӿ', 'ӿ'), + ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), ('ԉ', 'ԉ'), + ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), ('ԓ', 'ԓ'), + ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), ('ԝ', 'ԝ'), + ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), ('ԧ', 'ԧ'), + ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), ('ա', 'և'), + ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᴫ'), ('ᵫ', 'ᵷ'), + ('ᵹ', 'ᶚ'), ('ḁ', 'ḁ'), ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), + ('ḇ', 'ḇ'), ('ḉ', 'ḉ'), ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), + ('ḏ', 'ḏ'), ('ḑ', 'ḑ'), ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), + ('ḗ', 'ḗ'), ('ḙ', 'ḙ'), ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), + ('ḟ', 'ḟ'), ('ḡ', 'ḡ'), ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), + ('ḧ', 'ḧ'), ('ḩ', 'ḩ'), ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), + ('ḯ', 'ḯ'), ('ḱ', 'ḱ'), ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), + ('ḷ', 'ḷ'), ('ḹ', 'ḹ'), ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), + ('ḿ', 'ḿ'), ('ṁ', 'ṁ'), ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), + ('ṇ', 'ṇ'), ('ṉ', 'ṉ'), ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), + ('ṏ', 'ṏ'), ('ṑ', 'ṑ'), ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), + ('ṗ', 'ṗ'), ('ṙ', 'ṙ'), ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), + ('ṟ', 'ṟ'), ('ṡ', 'ṡ'), ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), + ('ṧ', 'ṧ'), ('ṩ', 'ṩ'), ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), + ('ṯ', 'ṯ'), ('ṱ', 'ṱ'), ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), + ('ṷ', 'ṷ'), ('ṹ', 'ṹ'), ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), + ('ṿ', 'ṿ'), ('ẁ', 'ẁ'), ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), + ('ẇ', 'ẇ'), ('ẉ', 'ẉ'), ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), + ('ẏ', 'ẏ'), ('ẑ', 'ẑ'), ('ẓ', 'ẓ'), ('ẕ', 'ẝ'), + ('ẟ', 'ẟ'), ('ạ', 'ạ'), ('ả', 'ả'), ('ấ', 'ấ'), + ('ầ', 'ầ'), ('ẩ', 'ẩ'), ('ẫ', 'ẫ'), ('ậ', 'ậ'), + ('ắ', 'ắ'), ('ằ', 'ằ'), ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), + ('ặ', 'ặ'), ('ẹ', 'ẹ'), ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), + ('ế', 'ế'), ('ề', 'ề'), ('ể', 'ể'), ('ễ', 'ễ'), + ('ệ', 'ệ'), ('ỉ', 'ỉ'), ('ị', 'ị'), ('ọ', 'ọ'), + ('ỏ', 'ỏ'), ('ố', 'ố'), ('ồ', 'ồ'), ('ổ', 'ổ'), + ('ỗ', 'ỗ'), ('ộ', 'ộ'), ('ớ', 'ớ'), ('ờ', 'ờ'), + ('ở', 'ở'), ('ỡ', 'ỡ'), ('ợ', 'ợ'), ('ụ', 'ụ'), + ('ủ', 'ủ'), ('ứ', 'ứ'), ('ừ', 'ừ'), ('ử', 'ử'), + ('ữ', 'ữ'), ('ự', 'ự'), ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), + ('ỷ', 'ỷ'), ('ỹ', 'ỹ'), ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), + ('ỿ', 'ἇ'), ('ἐ', 'ἕ'), ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), + ('ὀ', 'ὅ'), ('ὐ', 'ὗ'), ('ὠ', 'ὧ'), ('ὰ', 'ώ'), + ('ᾀ', 'ᾇ'), ('ᾐ', 'ᾗ'), ('ᾠ', 'ᾧ'), ('ᾰ', 'ᾴ'), + ('ᾶ', 'ᾷ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), + ('ῐ', 'ΐ'), ('ῖ', 'ῗ'), ('ῠ', 'ῧ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῷ'), ('ℊ', 'ℊ'), ('ℎ', 'ℏ'), ('ℓ', 'ℓ'), + ('ℯ', 'ℯ'), ('ℴ', 'ℴ'), ('ℹ', 'ℹ'), ('ℼ', 'ℽ'), + ('ⅆ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('ↄ', 'ↄ'), ('ⰰ', 'ⱞ'), + ('ⱡ', 'ⱡ'), ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), ('ⱪ', 'ⱪ'), + ('ⱬ', 'ⱬ'), ('ⱱ', 'ⱱ'), ('ⱳ', 'ⱴ'), ('ⱶ', 'ⱻ'), + ('ⲁ', 'ⲁ'), ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), + ('ⲉ', 'ⲉ'), ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), + ('ⲑ', 'ⲑ'), ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), + ('ⲙ', 'ⲙ'), ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), + ('ⲡ', 'ⲡ'), ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), + ('ⲩ', 'ⲩ'), ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), + ('ⲱ', 'ⲱ'), ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), + ('ⲹ', 'ⲹ'), ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), + ('ⳁ', 'ⳁ'), ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), + ('ⳉ', 'ⳉ'), ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), + ('ⳑ', 'ⳑ'), ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), + ('ⳙ', 'ⳙ'), ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), + ('ⳡ', 'ⳡ'), ('ⳣ', 'ⳤ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), + ('ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ꙁ', 'ꙁ'), ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), + ('ꙉ', 'ꙉ'), ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), + ('ꙑ', 'ꙑ'), ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), + ('ꙙ', 'ꙙ'), ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), + ('ꙡ', 'ꙡ'), ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), + ('ꙩ', 'ꙩ'), ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), + ('ꚃ', 'ꚃ'), ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), + ('ꚋ', 'ꚋ'), ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), + ('ꚓ', 'ꚓ'), ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), + ('ꚛ', 'ꚛ'), ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), + ('ꜩ', 'ꜩ'), ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜱ'), + ('ꜳ', 'ꜳ'), ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), + ('ꜻ', 'ꜻ'), ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), + ('ꝃ', 'ꝃ'), ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), + ('ꝋ', 'ꝋ'), ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), + ('ꝓ', 'ꝓ'), ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), + ('ꝛ', 'ꝛ'), ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), + ('ꝣ', 'ꝣ'), ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), + ('ꝫ', 'ꝫ'), ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝯ'), ('ꝱ', 'ꝸ'), + ('ꝺ', 'ꝺ'), ('ꝼ', 'ꝼ'), ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), + ('ꞃ', 'ꞃ'), ('ꞅ', 'ꞅ'), ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), + ('ꞎ', 'ꞎ'), ('ꞑ', 'ꞑ'), ('ꞓ', 'ꞕ'), ('ꞗ', 'ꞗ'), + ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), ('ꞝ', 'ꞝ'), ('ꞟ', 'ꞟ'), + ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), ('ꞥ', 'ꞥ'), ('ꞧ', 'ꞧ'), + ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), ('ꞷ', 'ꞷ'), ('ꟺ', 'ꟺ'), + ('ꬰ', 'ꭚ'), ('ꭠ', 'ꭥ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('a', 'z'), ('𐐨', '𐑏'), ('𐓘', '𐓻'), + ('𐳀', '𐳲'), ('𑣀', '𑣟'), ('𝐚', '𝐳'), ('𝑎', '𝑔'), + ('𝑖', '𝑧'), ('𝒂', '𝒛'), ('𝒶', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝓏'), ('𝓪', '𝔃'), ('𝔞', '𝔷'), + ('𝕒', '𝕫'), ('𝖆', '𝖟'), ('𝖺', '𝗓'), ('𝗮', '𝘇'), + ('𝘢', '𝘻'), ('𝙖', '𝙯'), ('𝚊', '𝚥'), ('𝛂', '𝛚'), + ('𝛜', '𝛡'), ('𝛼', '𝜔'), ('𝜖', '𝜛'), ('𝜶', '𝝎'), + ('𝝐', '𝝕'), ('𝝰', '𝞈'), ('𝞊', '𝞏'), ('𝞪', '𝟂'), + ('𝟄', '𝟉'), ('𝟋', '𝟋'), ('𞤢', '𞥃'), +]; + +pub const MARK: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҃', '҉'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('۟', 'ۤ'), ('ۧ', 'ۨ'), ('۪', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', '݊'), ('ަ', 'ް'), ('߫', '߳'), ('ࠖ', '࠙'), ('ࠛ', 'ࠣ'), + ('ࠥ', 'ࠧ'), ('ࠩ', '࠭'), ('࡙', '࡛'), ('ࣔ', '࣡'), + ('ࣣ', 'ः'), ('ऺ', '़'), ('ा', 'ॏ'), ('॑', 'ॗ'), + ('ॢ', 'ॣ'), ('ঁ', 'ঃ'), ('়', '়'), ('া', 'ৄ'), + ('ে', 'ৈ'), ('ো', '্'), ('ৗ', 'ৗ'), ('ৢ', 'ৣ'), + ('ਁ', 'ਃ'), ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), + ('ઁ', 'ઃ'), ('઼', '઼'), ('ા', 'ૅ'), ('ે', 'ૉ'), + ('ો', '્'), ('ૢ', 'ૣ'), ('ૺ', '૿'), ('ଁ', 'ଃ'), + ('଼', '଼'), ('ା', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', '்'), ('ௗ', 'ௗ'), ('ఀ', 'ః'), + ('ా', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), ('ౕ', 'ౖ'), + ('ౢ', 'ౣ'), ('ಁ', 'ಃ'), ('಼', '಼'), ('ಾ', 'ೄ'), + ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೢ', 'ೣ'), + ('ഀ', 'ഃ'), ('഻', '഼'), ('ാ', 'ൄ'), ('െ', 'ൈ'), + ('ൊ', '്'), ('ൗ', 'ൗ'), ('ൢ', 'ൣ'), ('ං', 'ඃ'), + ('්', '්'), ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), + ('ෲ', 'ෳ'), ('ั', 'ั'), ('ิ', 'ฺ'), ('็', '๎'), + ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), ('່', 'ໍ'), + ('༘', '༙'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('༾', '༿'), ('ཱ', '྄'), ('྆', '྇'), ('ྍ', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('ါ', 'ှ'), ('ၖ', 'ၙ'), + ('ၞ', 'ၠ'), ('ၢ', 'ၤ'), ('ၧ', 'ၭ'), ('ၱ', 'ၴ'), + ('ႂ', 'ႍ'), ('ႏ', 'ႏ'), ('ႚ', 'ႝ'), ('፝', '፟'), + ('ᜒ', '᜔'), ('ᜲ', '᜴'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), + ('឴', '៓'), ('៝', '៝'), ('᠋', '᠍'), ('ᢅ', 'ᢆ'), + ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), ('ᨗ', 'ᨛ'), + ('ᩕ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᩿'), ('᪰', '᪾'), + ('ᬀ', 'ᬄ'), ('᬴', '᭄'), ('᭫', '᭳'), ('ᮀ', 'ᮂ'), + ('ᮡ', 'ᮭ'), ('᯦', '᯳'), ('ᰤ', '᰷'), ('᳐', '᳒'), + ('᳔', '᳨'), ('᳭', '᳭'), ('ᳲ', '᳴'), ('᳷', '᳹'), + ('᷀', '᷹'), ('᷻', '᷿'), ('⃐', '⃰'), ('⳯', '⳱'), + ('⵿', '⵿'), ('ⷠ', 'ⷿ'), ('〪', '〯'), ('゙', '゚'), + ('꙯', '꙲'), ('ꙴ', '꙽'), ('ꚞ', 'ꚟ'), ('꛰', '꛱'), + ('ꠂ', 'ꠂ'), ('꠆', '꠆'), ('ꠋ', 'ꠋ'), ('ꠣ', 'ꠧ'), + ('ꢀ', 'ꢁ'), ('ꢴ', 'ꣅ'), ('꣠', '꣱'), ('ꤦ', '꤭'), + ('ꥇ', '꥓'), ('ꦀ', 'ꦃ'), ('꦳', '꧀'), ('ꧥ', 'ꧥ'), + ('ꨩ', 'ꨶ'), ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩍ'), ('ꩻ', 'ꩽ'), + ('ꪰ', 'ꪰ'), ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), + ('꫁', '꫁'), ('ꫫ', 'ꫯ'), ('ꫵ', '꫶'), ('ꯣ', 'ꯪ'), + ('꯬', '꯭'), ('ﬞ', 'ﬞ'), ('︀', '️'), ('︠', '︯'), + ('𐇽', '𐇽'), ('𐋠', '𐋠'), ('𐍶', '𐍺'), ('𐨁', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨏'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), + ('𐫥', '𐫦'), ('𑀀', '𑀂'), ('𑀸', '𑁆'), ('𑁿', '𑂂'), + ('𑂰', '𑂺'), ('𑄀', '𑄂'), ('𑄧', '𑄴'), ('𑅳', '𑅳'), + ('𑆀', '𑆂'), ('𑆳', '𑇀'), ('𑇊', '𑇌'), ('𑈬', '𑈷'), + ('𑈾', '𑈾'), ('𑋟', '𑋪'), ('𑌀', '𑌃'), ('𑌼', '𑌼'), + ('𑌾', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍗', '𑍗'), + ('𑍢', '𑍣'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑐵', '𑑆'), + ('𑒰', '𑓃'), ('𑖯', '𑖵'), ('𑖸', '𑗀'), ('𑗜', '𑗝'), + ('𑘰', '𑙀'), ('𑚫', '𑚷'), ('𑜝', '𑜫'), ('𑨁', '𑨊'), + ('𑨳', '𑨹'), ('𑨻', '𑨾'), ('𑩇', '𑩇'), ('𑩑', '𑩛'), + ('𑪊', '𑪙'), ('𑰯', '𑰶'), ('𑰸', '𑰿'), ('𑲒', '𑲧'), + ('𑲩', '𑲶'), ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), + ('𑴿', '𑵅'), ('𑵇', '𑵇'), ('𖫰', '𖫴'), ('𖬰', '𖬶'), + ('𖽑', '𖽾'), ('𖾏', '𖾒'), ('𛲝', '𛲞'), ('𝅥', '𝅩'), + ('𝅭', '𝅲'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), + ('𝉂', '𝉄'), ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), + ('𝪄', '𝪄'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), + ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), + ('𞣐', '𞣖'), ('𞥄', '𞥊'), ('󠄀', '󠇯'), +]; + +pub const MATH_SYMBOL: &'static [(char, char)] = &[ + ('+', '+'), ('<', '>'), ('|', '|'), ('~', '~'), ('¬', '¬'), ('±', '±'), + ('×', '×'), ('÷', '÷'), ('϶', '϶'), ('؆', '؈'), ('⁄', '⁄'), + ('⁒', '⁒'), ('⁺', '⁼'), ('₊', '₌'), ('℘', '℘'), + ('⅀', '⅄'), ('⅋', '⅋'), ('←', '↔'), ('↚', '↛'), + ('↠', '↠'), ('↣', '↣'), ('↦', '↦'), ('↮', '↮'), + ('⇎', '⇏'), ('⇒', '⇒'), ('⇔', '⇔'), ('⇴', '⋿'), + ('⌠', '⌡'), ('⍼', '⍼'), ('⎛', '⎳'), ('⏜', '⏡'), + ('▷', '▷'), ('◁', '◁'), ('◸', '◿'), ('♯', '♯'), + ('⟀', '⟄'), ('⟇', '⟥'), ('⟰', '⟿'), ('⤀', '⦂'), + ('⦙', '⧗'), ('⧜', '⧻'), ('⧾', '⫿'), ('⬰', '⭄'), + ('⭇', '⭌'), ('﬩', '﬩'), ('﹢', '﹢'), ('﹤', '﹦'), + ('+', '+'), ('<', '>'), ('|', '|'), ('~', '~'), + ('¬', '¬'), ('←', '↓'), ('𝛁', '𝛁'), ('𝛛', '𝛛'), + ('𝛻', '𝛻'), ('𝜕', '𝜕'), ('𝜵', '𝜵'), ('𝝏', '𝝏'), + ('𝝯', '𝝯'), ('𝞉', '𝞉'), ('𝞩', '𝞩'), ('𝟃', '𝟃'), + ('𞻰', '𞻱'), +]; + +pub const MODIFIER_LETTER: &'static [(char, char)] = &[ + ('ʰ', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), + ('ʹ', 'ʹ'), ('ͺ', 'ͺ'), ('ՙ', 'ՙ'), ('ـ', 'ـ'), ('ۥ', 'ۦ'), + ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠚ', 'ࠚ'), ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), + ('ॱ', 'ॱ'), ('ๆ', 'ๆ'), ('ໆ', 'ໆ'), ('ჼ', 'ჼ'), + ('ៗ', 'ៗ'), ('ᡃ', 'ᡃ'), ('ᪧ', 'ᪧ'), ('ᱸ', 'ᱽ'), + ('ᴬ', 'ᵪ'), ('ᵸ', 'ᵸ'), ('ᶛ', 'ᶿ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ⱼ', 'ⱽ'), ('ⵯ', 'ⵯ'), + ('ⸯ', 'ⸯ'), ('々', '々'), ('〱', '〵'), ('〻', '〻'), + ('ゝ', 'ゞ'), ('ー', 'ヾ'), ('ꀕ', 'ꀕ'), ('ꓸ', 'ꓽ'), + ('ꘌ', 'ꘌ'), ('ꙿ', 'ꙿ'), ('ꚜ', 'ꚝ'), ('ꜗ', 'ꜟ'), + ('ꝰ', 'ꝰ'), ('ꞈ', 'ꞈ'), ('ꟸ', 'ꟹ'), ('ꧏ', 'ꧏ'), + ('ꧦ', 'ꧦ'), ('ꩰ', 'ꩰ'), ('ꫝ', 'ꫝ'), ('ꫳ', 'ꫴ'), + ('ꭜ', 'ꭟ'), ('ー', 'ー'), ('゙', '゚'), ('𖭀', '𖭃'), + ('𖾓', '𖾟'), ('𖿠', '𖿡'), +]; + +pub const MODIFIER_SYMBOL: &'static [(char, char)] = &[ + ('^', '^'), ('`', '`'), ('¨', '¨'), ('¯', '¯'), ('´', '´'), + ('¸', '¸'), ('˂', '˅'), ('˒', '˟'), ('˥', '˫'), ('˭', '˭'), + ('˯', '˿'), ('͵', '͵'), ('΄', '΅'), ('᾽', '᾽'), ('᾿', '῁'), + ('῍', '῏'), ('῝', '῟'), ('῭', '`'), ('´', '῾'), + ('゛', '゜'), ('꜀', '꜖'), ('꜠', '꜡'), ('꞉', '꞊'), + ('꭛', '꭛'), ('﮲', '﯁'), ('^', '^'), ('`', '`'), + (' ̄', ' ̄'), ('🏻', '🏿'), +]; + +pub const NONSPACING_MARK: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҃', '҇'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('۟', 'ۤ'), ('ۧ', 'ۨ'), ('۪', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', '݊'), ('ަ', 'ް'), ('߫', '߳'), ('ࠖ', '࠙'), ('ࠛ', 'ࠣ'), + ('ࠥ', 'ࠧ'), ('ࠩ', '࠭'), ('࡙', '࡛'), ('ࣔ', '࣡'), + ('ࣣ', 'ं'), ('ऺ', 'ऺ'), ('़', '़'), ('ु', 'ै'), + ('्', '्'), ('॑', 'ॗ'), ('ॢ', 'ॣ'), ('ঁ', 'ঁ'), + ('়', '়'), ('ু', 'ৄ'), ('্', '্'), ('ৢ', 'ৣ'), + ('ਁ', 'ਂ'), ('਼', '਼'), ('ੁ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), + ('ઁ', 'ં'), ('઼', '઼'), ('ુ', 'ૅ'), ('ે', 'ૈ'), + ('્', '્'), ('ૢ', 'ૣ'), ('ૺ', '૿'), ('ଁ', 'ଁ'), + ('଼', '଼'), ('ି', 'ି'), ('ୁ', 'ୄ'), ('୍', '୍'), + ('ୖ', 'ୖ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ீ', 'ீ'), + ('்', '்'), ('ఀ', 'ఀ'), ('ా', 'ీ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౢ', 'ౣ'), ('ಁ', 'ಁ'), + ('಼', '಼'), ('ಿ', 'ಿ'), ('ೆ', 'ೆ'), ('ೌ', '್'), + ('ೢ', 'ೣ'), ('ഀ', 'ഁ'), ('഻', '഼'), ('ു', 'ൄ'), + ('്', '്'), ('ൢ', 'ൣ'), ('්', '්'), ('ි', 'ු'), + ('ූ', 'ූ'), ('ั', 'ั'), ('ิ', 'ฺ'), ('็', '๎'), + ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), ('່', 'ໍ'), + ('༘', '༙'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('ཱ', 'ཾ'), ('ྀ', '྄'), ('྆', '྇'), ('ྍ', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('ိ', 'ူ'), ('ဲ', '့'), + ('္', '်'), ('ွ', 'ှ'), ('ၘ', 'ၙ'), ('ၞ', 'ၠ'), + ('ၱ', 'ၴ'), ('ႂ', 'ႂ'), ('ႅ', 'ႆ'), ('ႍ', 'ႍ'), + ('ႝ', 'ႝ'), ('፝', '፟'), ('ᜒ', '᜔'), ('ᜲ', '᜴'), + ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), ('឴', '឵'), ('ិ', 'ួ'), + ('ំ', 'ំ'), ('៉', '៓'), ('៝', '៝'), ('᠋', '᠍'), + ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤢ'), ('ᤧ', 'ᤨ'), + ('ᤲ', 'ᤲ'), ('᤹', '᤻'), ('ᨗ', 'ᨘ'), ('ᨛ', 'ᨛ'), + ('ᩖ', 'ᩖ'), ('ᩘ', 'ᩞ'), ('᩠', '᩠'), ('ᩢ', 'ᩢ'), + ('ᩥ', 'ᩬ'), ('ᩳ', '᩼'), ('᩿', '᩿'), ('᪰', '᪽'), + ('ᬀ', 'ᬃ'), ('᬴', '᬴'), ('ᬶ', 'ᬺ'), ('ᬼ', 'ᬼ'), + ('ᭂ', 'ᭂ'), ('᭫', '᭳'), ('ᮀ', 'ᮁ'), ('ᮢ', 'ᮥ'), + ('ᮨ', 'ᮩ'), ('᮫', 'ᮭ'), ('᯦', '᯦'), ('ᯨ', 'ᯩ'), + ('ᯭ', 'ᯭ'), ('ᯯ', 'ᯱ'), ('ᰬ', 'ᰳ'), ('ᰶ', '᰷'), + ('᳐', '᳒'), ('᳔', '᳠'), ('᳢', '᳨'), ('᳭', '᳭'), + ('᳴', '᳴'), ('᳸', '᳹'), ('᷀', '᷹'), ('᷻', '᷿'), + ('⃐', '⃜'), ('⃡', '⃡'), ('⃥', '⃰'), ('⳯', '⳱'), + ('⵿', '⵿'), ('ⷠ', 'ⷿ'), ('〪', '〭'), ('゙', '゚'), + ('꙯', '꙯'), ('ꙴ', '꙽'), ('ꚞ', 'ꚟ'), ('꛰', '꛱'), + ('ꠂ', 'ꠂ'), ('꠆', '꠆'), ('ꠋ', 'ꠋ'), ('ꠥ', 'ꠦ'), + ('꣄', 'ꣅ'), ('꣠', '꣱'), ('ꤦ', '꤭'), ('ꥇ', 'ꥑ'), + ('ꦀ', 'ꦂ'), ('꦳', '꦳'), ('ꦶ', 'ꦹ'), ('ꦼ', 'ꦼ'), + ('ꧥ', 'ꧥ'), ('ꨩ', 'ꨮ'), ('ꨱ', 'ꨲ'), ('ꨵ', 'ꨶ'), + ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩌ'), ('ꩼ', 'ꩼ'), ('ꪰ', 'ꪰ'), + ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), ('꫁', '꫁'), + ('ꫬ', 'ꫭ'), ('꫶', '꫶'), ('ꯥ', 'ꯥ'), ('ꯨ', 'ꯨ'), + ('꯭', '꯭'), ('ﬞ', 'ﬞ'), ('︀', '️'), ('︠', '︯'), + ('𐇽', '𐇽'), ('𐋠', '𐋠'), ('𐍶', '𐍺'), ('𐨁', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨏'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), + ('𐫥', '𐫦'), ('𑀁', '𑀁'), ('𑀸', '𑁆'), ('𑁿', '𑂁'), + ('𑂳', '𑂶'), ('𑂹', '𑂺'), ('𑄀', '𑄂'), ('𑄧', '𑄫'), + ('𑄭', '𑄴'), ('𑅳', '𑅳'), ('𑆀', '𑆁'), ('𑆶', '𑆾'), + ('𑇊', '𑇌'), ('𑈯', '𑈱'), ('𑈴', '𑈴'), ('𑈶', '𑈷'), + ('𑈾', '𑈾'), ('𑋟', '𑋟'), ('𑋣', '𑋪'), ('𑌀', '𑌁'), + ('𑌼', '𑌼'), ('𑍀', '𑍀'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), + ('𑐸', '𑐿'), ('𑑂', '𑑄'), ('𑑆', '𑑆'), ('𑒳', '𑒸'), + ('𑒺', '𑒺'), ('𑒿', '𑓀'), ('𑓂', '𑓃'), ('𑖲', '𑖵'), + ('𑖼', '𑖽'), ('𑖿', '𑗀'), ('𑗜', '𑗝'), ('𑘳', '𑘺'), + ('𑘽', '𑘽'), ('𑘿', '𑙀'), ('𑚫', '𑚫'), ('𑚭', '𑚭'), + ('𑚰', '𑚵'), ('𑚷', '𑚷'), ('𑜝', '𑜟'), ('𑜢', '𑜥'), + ('𑜧', '𑜫'), ('𑨁', '𑨆'), ('𑨉', '𑨊'), ('𑨳', '𑨸'), + ('𑨻', '𑨾'), ('𑩇', '𑩇'), ('𑩑', '𑩖'), ('𑩙', '𑩛'), + ('𑪊', '𑪖'), ('𑪘', '𑪙'), ('𑰰', '𑰶'), ('𑰸', '𑰽'), + ('𑰿', '𑰿'), ('𑲒', '𑲧'), ('𑲪', '𑲰'), ('𑲲', '𑲳'), + ('𑲵', '𑲶'), ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), + ('𑴿', '𑵅'), ('𑵇', '𑵇'), ('𖫰', '𖫴'), ('𖬰', '𖬶'), + ('𖾏', '𖾒'), ('𛲝', '𛲞'), ('𝅧', '𝅩'), ('𝅻', '𝆂'), + ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), ('𝨀', '𝨶'), + ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), ('𝪛', '𝪟'), + ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞣐', '𞣖'), ('𞥄', '𞥊'), + ('󠄀', '󠇯'), +]; + +pub const NUMBER: &'static [(char, char)] = &[ + ('0', '9'), ('²', '³'), ('¹', '¹'), ('¼', '¾'), ('٠', '٩'), + ('۰', '۹'), ('߀', '߉'), ('०', '९'), ('০', '৯'), ('৴', '৹'), + ('੦', '੯'), ('૦', '૯'), ('୦', '୯'), ('୲', '୷'), + ('௦', '௲'), ('౦', '౯'), ('౸', '౾'), ('೦', '೯'), + ('൘', '൞'), ('൦', '൸'), ('෦', '෯'), ('๐', '๙'), + ('໐', '໙'), ('༠', '༳'), ('၀', '၉'), ('႐', '႙'), + ('፩', '፼'), ('ᛮ', 'ᛰ'), ('០', '៩'), ('៰', '៹'), + ('᠐', '᠙'), ('᥆', '᥏'), ('᧐', '᧚'), ('᪀', '᪉'), + ('᪐', '᪙'), ('᭐', '᭙'), ('᮰', '᮹'), ('᱀', '᱉'), + ('᱐', '᱙'), ('⁰', '⁰'), ('⁴', '⁹'), ('₀', '₉'), + ('⅐', 'ↂ'), ('ↅ', '↉'), ('①', '⒛'), ('⓪', '⓿'), + ('❶', '➓'), ('⳽', '⳽'), ('〇', '〇'), ('〡', '〩'), + ('〸', '〺'), ('㆒', '㆕'), ('㈠', '㈩'), ('㉈', '㉏'), + ('㉑', '㉟'), ('㊀', '㊉'), ('㊱', '㊿'), ('꘠', '꘩'), + ('ꛦ', 'ꛯ'), ('꠰', '꠵'), ('꣐', '꣙'), ('꤀', '꤉'), + ('꧐', '꧙'), ('꧰', '꧹'), ('꩐', '꩙'), ('꯰', '꯹'), + ('0', '9'), ('𐄇', '𐄳'), ('𐅀', '𐅸'), ('𐆊', '𐆋'), + ('𐋡', '𐋻'), ('𐌠', '𐌣'), ('𐍁', '𐍁'), ('𐍊', '𐍊'), + ('𐏑', '𐏕'), ('𐒠', '𐒩'), ('𐡘', '𐡟'), ('𐡹', '𐡿'), + ('𐢧', '𐢯'), ('𐣻', '𐣿'), ('𐤖', '𐤛'), ('𐦼', '𐦽'), + ('𐧀', '𐧏'), ('𐧒', '𐧿'), ('𐩀', '𐩇'), ('𐩽', '𐩾'), + ('𐪝', '𐪟'), ('𐫫', '𐫯'), ('𐭘', '𐭟'), ('𐭸', '𐭿'), + ('𐮩', '𐮯'), ('𐳺', '𐳿'), ('𐹠', '𐹾'), ('𑁒', '𑁯'), + ('𑃰', '𑃹'), ('𑄶', '𑄿'), ('𑇐', '𑇙'), ('𑇡', '𑇴'), + ('𑋰', '𑋹'), ('𑑐', '𑑙'), ('𑓐', '𑓙'), ('𑙐', '𑙙'), + ('𑛀', '𑛉'), ('𑜰', '𑜻'), ('𑣠', '𑣲'), ('𑱐', '𑱬'), + ('𑵐', '𑵙'), ('𒐀', '𒑮'), ('𖩠', '𖩩'), ('𖭐', '𖭙'), + ('𖭛', '𖭡'), ('𝍠', '𝍱'), ('𝟎', '𝟿'), ('𞣇', '𞣏'), + ('𞥐', '𞥙'), ('🄀', '🄌'), +]; + +pub const OPEN_PUNCTUATION: &'static [(char, char)] = &[ + ('(', '('), ('[', '['), ('{', '{'), ('༺', '༺'), ('༼', '༼'), + ('᚛', '᚛'), ('‚', '‚'), ('„', '„'), ('⁅', '⁅'), + ('⁽', '⁽'), ('₍', '₍'), ('⌈', '⌈'), ('⌊', '⌊'), + ('〈', '〈'), ('❨', '❨'), ('❪', '❪'), ('❬', '❬'), + ('❮', '❮'), ('❰', '❰'), ('❲', '❲'), ('❴', '❴'), + ('⟅', '⟅'), ('⟦', '⟦'), ('⟨', '⟨'), ('⟪', '⟪'), + ('⟬', '⟬'), ('⟮', '⟮'), ('⦃', '⦃'), ('⦅', '⦅'), + ('⦇', '⦇'), ('⦉', '⦉'), ('⦋', '⦋'), ('⦍', '⦍'), + ('⦏', '⦏'), ('⦑', '⦑'), ('⦓', '⦓'), ('⦕', '⦕'), + ('⦗', '⦗'), ('⧘', '⧘'), ('⧚', '⧚'), ('⧼', '⧼'), + ('⸢', '⸢'), ('⸤', '⸤'), ('⸦', '⸦'), ('⸨', '⸨'), + ('⹂', '⹂'), ('〈', '〈'), ('《', '《'), ('「', '「'), + ('『', '『'), ('【', '【'), ('〔', '〔'), ('〖', '〖'), + ('〘', '〘'), ('〚', '〚'), ('〝', '〝'), ('﴿', '﴿'), + ('︗', '︗'), ('︵', '︵'), ('︷', '︷'), ('︹', '︹'), + ('︻', '︻'), ('︽', '︽'), ('︿', '︿'), ('﹁', '﹁'), + ('﹃', '﹃'), ('﹇', '﹇'), ('﹙', '﹙'), ('﹛', '﹛'), + ('﹝', '﹝'), ('(', '('), ('[', '['), ('{', '{'), + ('⦅', '⦅'), ('「', '「'), +]; + +pub const OTHER: &'static [(char, char)] = &[ + ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), ('\u{ad}', '\u{ad}'), + ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), + ('\u{38d}', '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), + ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), + ('\u{58b}', '\u{58c}'), ('\u{590}', '\u{590}'), ('\u{5c8}', '\u{5cf}'), + ('\u{5eb}', '\u{5ef}'), ('\u{5f5}', '\u{605}'), ('\u{61c}', '\u{61d}'), + ('\u{6dd}', '\u{6dd}'), ('\u{70e}', '\u{70f}'), ('\u{74b}', '\u{74c}'), + ('\u{7b2}', '\u{7bf}'), ('\u{7fb}', '\u{7ff}'), ('\u{82e}', '\u{82f}'), + ('\u{83f}', '\u{83f}'), ('\u{85c}', '\u{85d}'), ('\u{85f}', '\u{85f}'), + ('\u{86b}', '\u{89f}'), ('\u{8b5}', '\u{8b5}'), ('\u{8be}', '\u{8d3}'), + ('\u{8e2}', '\u{8e2}'), ('\u{984}', '\u{984}'), ('\u{98d}', '\u{98e}'), + ('\u{991}', '\u{992}'), ('\u{9a9}', '\u{9a9}'), ('\u{9b1}', '\u{9b1}'), + ('\u{9b3}', '\u{9b5}'), ('\u{9ba}', '\u{9bb}'), ('\u{9c5}', '\u{9c6}'), + ('\u{9c9}', '\u{9ca}'), ('\u{9cf}', '\u{9d6}'), ('\u{9d8}', '\u{9db}'), + ('\u{9de}', '\u{9de}'), ('\u{9e4}', '\u{9e5}'), ('\u{9fe}', '\u{a00}'), + ('\u{a04}', '\u{a04}'), ('\u{a0b}', '\u{a0e}'), ('\u{a11}', '\u{a12}'), + ('\u{a29}', '\u{a29}'), ('\u{a31}', '\u{a31}'), ('\u{a34}', '\u{a34}'), + ('\u{a37}', '\u{a37}'), ('\u{a3a}', '\u{a3b}'), ('\u{a3d}', '\u{a3d}'), + ('\u{a43}', '\u{a46}'), ('\u{a49}', '\u{a4a}'), ('\u{a4e}', '\u{a50}'), + ('\u{a52}', '\u{a58}'), ('\u{a5d}', '\u{a5d}'), ('\u{a5f}', '\u{a65}'), + ('\u{a76}', '\u{a80}'), ('\u{a84}', '\u{a84}'), ('\u{a8e}', '\u{a8e}'), + ('\u{a92}', '\u{a92}'), ('\u{aa9}', '\u{aa9}'), ('\u{ab1}', '\u{ab1}'), + ('\u{ab4}', '\u{ab4}'), ('\u{aba}', '\u{abb}'), ('\u{ac6}', '\u{ac6}'), + ('\u{aca}', '\u{aca}'), ('\u{ace}', '\u{acf}'), ('\u{ad1}', '\u{adf}'), + ('\u{ae4}', '\u{ae5}'), ('\u{af2}', '\u{af8}'), ('\u{b00}', '\u{b00}'), + ('\u{b04}', '\u{b04}'), ('\u{b0d}', '\u{b0e}'), ('\u{b11}', '\u{b12}'), + ('\u{b29}', '\u{b29}'), ('\u{b31}', '\u{b31}'), ('\u{b34}', '\u{b34}'), + ('\u{b3a}', '\u{b3b}'), ('\u{b45}', '\u{b46}'), ('\u{b49}', '\u{b4a}'), + ('\u{b4e}', '\u{b55}'), ('\u{b58}', '\u{b5b}'), ('\u{b5e}', '\u{b5e}'), + ('\u{b64}', '\u{b65}'), ('\u{b78}', '\u{b81}'), ('\u{b84}', '\u{b84}'), + ('\u{b8b}', '\u{b8d}'), ('\u{b91}', '\u{b91}'), ('\u{b96}', '\u{b98}'), + ('\u{b9b}', '\u{b9b}'), ('\u{b9d}', '\u{b9d}'), ('\u{ba0}', '\u{ba2}'), + ('\u{ba5}', '\u{ba7}'), ('\u{bab}', '\u{bad}'), ('\u{bba}', '\u{bbd}'), + ('\u{bc3}', '\u{bc5}'), ('\u{bc9}', '\u{bc9}'), ('\u{bce}', '\u{bcf}'), + ('\u{bd1}', '\u{bd6}'), ('\u{bd8}', '\u{be5}'), ('\u{bfb}', '\u{bff}'), + ('\u{c04}', '\u{c04}'), ('\u{c0d}', '\u{c0d}'), ('\u{c11}', '\u{c11}'), + ('\u{c29}', '\u{c29}'), ('\u{c3a}', '\u{c3c}'), ('\u{c45}', '\u{c45}'), + ('\u{c49}', '\u{c49}'), ('\u{c4e}', '\u{c54}'), ('\u{c57}', '\u{c57}'), + ('\u{c5b}', '\u{c5f}'), ('\u{c64}', '\u{c65}'), ('\u{c70}', '\u{c77}'), + ('\u{c84}', '\u{c84}'), ('\u{c8d}', '\u{c8d}'), ('\u{c91}', '\u{c91}'), + ('\u{ca9}', '\u{ca9}'), ('\u{cb4}', '\u{cb4}'), ('\u{cba}', '\u{cbb}'), + ('\u{cc5}', '\u{cc5}'), ('\u{cc9}', '\u{cc9}'), ('\u{cce}', '\u{cd4}'), + ('\u{cd7}', '\u{cdd}'), ('\u{cdf}', '\u{cdf}'), ('\u{ce4}', '\u{ce5}'), + ('\u{cf0}', '\u{cf0}'), ('\u{cf3}', '\u{cff}'), ('\u{d04}', '\u{d04}'), + ('\u{d0d}', '\u{d0d}'), ('\u{d11}', '\u{d11}'), ('\u{d45}', '\u{d45}'), + ('\u{d49}', '\u{d49}'), ('\u{d50}', '\u{d53}'), ('\u{d64}', '\u{d65}'), + ('\u{d80}', '\u{d81}'), ('\u{d84}', '\u{d84}'), ('\u{d97}', '\u{d99}'), + ('\u{db2}', '\u{db2}'), ('\u{dbc}', '\u{dbc}'), ('\u{dbe}', '\u{dbf}'), + ('\u{dc7}', '\u{dc9}'), ('\u{dcb}', '\u{dce}'), ('\u{dd5}', '\u{dd5}'), + ('\u{dd7}', '\u{dd7}'), ('\u{de0}', '\u{de5}'), ('\u{df0}', '\u{df1}'), + ('\u{df5}', '\u{e00}'), ('\u{e3b}', '\u{e3e}'), ('\u{e5c}', '\u{e80}'), + ('\u{e83}', '\u{e83}'), ('\u{e85}', '\u{e86}'), ('\u{e89}', '\u{e89}'), + ('\u{e8b}', '\u{e8c}'), ('\u{e8e}', '\u{e93}'), ('\u{e98}', '\u{e98}'), + ('\u{ea0}', '\u{ea0}'), ('\u{ea4}', '\u{ea4}'), ('\u{ea6}', '\u{ea6}'), + ('\u{ea8}', '\u{ea9}'), ('\u{eac}', '\u{eac}'), ('\u{eba}', '\u{eba}'), + ('\u{ebe}', '\u{ebf}'), ('\u{ec5}', '\u{ec5}'), ('\u{ec7}', '\u{ec7}'), + ('\u{ece}', '\u{ecf}'), ('\u{eda}', '\u{edb}'), ('\u{ee0}', '\u{eff}'), + ('\u{f48}', '\u{f48}'), ('\u{f6d}', '\u{f70}'), ('\u{f98}', '\u{f98}'), + ('\u{fbd}', '\u{fbd}'), ('\u{fcd}', '\u{fcd}'), ('\u{fdb}', '\u{fff}'), + ('\u{10c6}', '\u{10c6}'), ('\u{10c8}', '\u{10cc}'), + ('\u{10ce}', '\u{10cf}'), ('\u{1249}', '\u{1249}'), + ('\u{124e}', '\u{124f}'), ('\u{1257}', '\u{1257}'), + ('\u{1259}', '\u{1259}'), ('\u{125e}', '\u{125f}'), + ('\u{1289}', '\u{1289}'), ('\u{128e}', '\u{128f}'), + ('\u{12b1}', '\u{12b1}'), ('\u{12b6}', '\u{12b7}'), + ('\u{12bf}', '\u{12bf}'), ('\u{12c1}', '\u{12c1}'), + ('\u{12c6}', '\u{12c7}'), ('\u{12d7}', '\u{12d7}'), + ('\u{1311}', '\u{1311}'), ('\u{1316}', '\u{1317}'), + ('\u{135b}', '\u{135c}'), ('\u{137d}', '\u{137f}'), + ('\u{139a}', '\u{139f}'), ('\u{13f6}', '\u{13f7}'), + ('\u{13fe}', '\u{13ff}'), ('\u{169d}', '\u{169f}'), + ('\u{16f9}', '\u{16ff}'), ('\u{170d}', '\u{170d}'), + ('\u{1715}', '\u{171f}'), ('\u{1737}', '\u{173f}'), + ('\u{1754}', '\u{175f}'), ('\u{176d}', '\u{176d}'), + ('\u{1771}', '\u{1771}'), ('\u{1774}', '\u{177f}'), + ('\u{17de}', '\u{17df}'), ('\u{17ea}', '\u{17ef}'), + ('\u{17fa}', '\u{17ff}'), ('\u{180e}', '\u{180f}'), + ('\u{181a}', '\u{181f}'), ('\u{1878}', '\u{187f}'), + ('\u{18ab}', '\u{18af}'), ('\u{18f6}', '\u{18ff}'), + ('\u{191f}', '\u{191f}'), ('\u{192c}', '\u{192f}'), + ('\u{193c}', '\u{193f}'), ('\u{1941}', '\u{1943}'), + ('\u{196e}', '\u{196f}'), ('\u{1975}', '\u{197f}'), + ('\u{19ac}', '\u{19af}'), ('\u{19ca}', '\u{19cf}'), + ('\u{19db}', '\u{19dd}'), ('\u{1a1c}', '\u{1a1d}'), + ('\u{1a5f}', '\u{1a5f}'), ('\u{1a7d}', '\u{1a7e}'), + ('\u{1a8a}', '\u{1a8f}'), ('\u{1a9a}', '\u{1a9f}'), + ('\u{1aae}', '\u{1aaf}'), ('\u{1abf}', '\u{1aff}'), + ('\u{1b4c}', '\u{1b4f}'), ('\u{1b7d}', '\u{1b7f}'), + ('\u{1bf4}', '\u{1bfb}'), ('\u{1c38}', '\u{1c3a}'), + ('\u{1c4a}', '\u{1c4c}'), ('\u{1c89}', '\u{1cbf}'), + ('\u{1cc8}', '\u{1ccf}'), ('\u{1cfa}', '\u{1cff}'), + ('\u{1dfa}', '\u{1dfa}'), ('\u{1f16}', '\u{1f17}'), + ('\u{1f1e}', '\u{1f1f}'), ('\u{1f46}', '\u{1f47}'), + ('\u{1f4e}', '\u{1f4f}'), ('\u{1f58}', '\u{1f58}'), + ('\u{1f5a}', '\u{1f5a}'), ('\u{1f5c}', '\u{1f5c}'), + ('\u{1f5e}', '\u{1f5e}'), ('\u{1f7e}', '\u{1f7f}'), + ('\u{1fb5}', '\u{1fb5}'), ('\u{1fc5}', '\u{1fc5}'), + ('\u{1fd4}', '\u{1fd5}'), ('\u{1fdc}', '\u{1fdc}'), + ('\u{1ff0}', '\u{1ff1}'), ('\u{1ff5}', '\u{1ff5}'), + ('\u{1fff}', '\u{1fff}'), ('\u{200b}', '\u{200f}'), + ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{206f}'), + ('\u{2072}', '\u{2073}'), ('\u{208f}', '\u{208f}'), + ('\u{209d}', '\u{209f}'), ('\u{20c0}', '\u{20cf}'), + ('\u{20f1}', '\u{20ff}'), ('\u{218c}', '\u{218f}'), + ('\u{2427}', '\u{243f}'), ('\u{244b}', '\u{245f}'), + ('\u{2b74}', '\u{2b75}'), ('\u{2b96}', '\u{2b97}'), + ('\u{2bba}', '\u{2bbc}'), ('\u{2bc9}', '\u{2bc9}'), + ('\u{2bd3}', '\u{2beb}'), ('\u{2bf0}', '\u{2bff}'), + ('\u{2c2f}', '\u{2c2f}'), ('\u{2c5f}', '\u{2c5f}'), + ('\u{2cf4}', '\u{2cf8}'), ('\u{2d26}', '\u{2d26}'), + ('\u{2d28}', '\u{2d2c}'), ('\u{2d2e}', '\u{2d2f}'), + ('\u{2d68}', '\u{2d6e}'), ('\u{2d71}', '\u{2d7e}'), + ('\u{2d97}', '\u{2d9f}'), ('\u{2da7}', '\u{2da7}'), + ('\u{2daf}', '\u{2daf}'), ('\u{2db7}', '\u{2db7}'), + ('\u{2dbf}', '\u{2dbf}'), ('\u{2dc7}', '\u{2dc7}'), + ('\u{2dcf}', '\u{2dcf}'), ('\u{2dd7}', '\u{2dd7}'), + ('\u{2ddf}', '\u{2ddf}'), ('\u{2e4a}', '\u{2e7f}'), + ('\u{2e9a}', '\u{2e9a}'), ('\u{2ef4}', '\u{2eff}'), + ('\u{2fd6}', '\u{2fef}'), ('\u{2ffc}', '\u{2fff}'), + ('\u{3040}', '\u{3040}'), ('\u{3097}', '\u{3098}'), + ('\u{3100}', '\u{3104}'), ('\u{312f}', '\u{3130}'), + ('\u{318f}', '\u{318f}'), ('\u{31bb}', '\u{31bf}'), + ('\u{31e4}', '\u{31ef}'), ('\u{321f}', '\u{321f}'), + ('\u{32ff}', '\u{32ff}'), ('\u{4db6}', '\u{4dbf}'), + ('\u{9feb}', '\u{9fff}'), ('\u{a48d}', '\u{a48f}'), + ('\u{a4c7}', '\u{a4cf}'), ('\u{a62c}', '\u{a63f}'), + ('\u{a6f8}', '\u{a6ff}'), ('\u{a7af}', '\u{a7af}'), + ('\u{a7b8}', '\u{a7f6}'), ('\u{a82c}', '\u{a82f}'), + ('\u{a83a}', '\u{a83f}'), ('\u{a878}', '\u{a87f}'), + ('\u{a8c6}', '\u{a8cd}'), ('\u{a8da}', '\u{a8df}'), + ('\u{a8fe}', '\u{a8ff}'), ('\u{a954}', '\u{a95e}'), + ('\u{a97d}', '\u{a97f}'), ('\u{a9ce}', '\u{a9ce}'), + ('\u{a9da}', '\u{a9dd}'), ('\u{a9ff}', '\u{a9ff}'), + ('\u{aa37}', '\u{aa3f}'), ('\u{aa4e}', '\u{aa4f}'), + ('\u{aa5a}', '\u{aa5b}'), ('\u{aac3}', '\u{aada}'), + ('\u{aaf7}', '\u{ab00}'), ('\u{ab07}', '\u{ab08}'), + ('\u{ab0f}', '\u{ab10}'), ('\u{ab17}', '\u{ab1f}'), + ('\u{ab27}', '\u{ab27}'), ('\u{ab2f}', '\u{ab2f}'), + ('\u{ab66}', '\u{ab6f}'), ('\u{abee}', '\u{abef}'), + ('\u{abfa}', '\u{abff}'), ('\u{d7a4}', '\u{d7af}'), + ('\u{d7c7}', '\u{d7ca}'), ('\u{d7fc}', '\u{f8ff}'), + ('\u{fa6e}', '\u{fa6f}'), ('\u{fada}', '\u{faff}'), + ('\u{fb07}', '\u{fb12}'), ('\u{fb18}', '\u{fb1c}'), + ('\u{fb37}', '\u{fb37}'), ('\u{fb3d}', '\u{fb3d}'), + ('\u{fb3f}', '\u{fb3f}'), ('\u{fb42}', '\u{fb42}'), + ('\u{fb45}', '\u{fb45}'), ('\u{fbc2}', '\u{fbd2}'), + ('\u{fd40}', '\u{fd4f}'), ('\u{fd90}', '\u{fd91}'), + ('\u{fdc8}', '\u{fdef}'), ('\u{fdfe}', '\u{fdff}'), + ('\u{fe1a}', '\u{fe1f}'), ('\u{fe53}', '\u{fe53}'), + ('\u{fe67}', '\u{fe67}'), ('\u{fe6c}', '\u{fe6f}'), + ('\u{fe75}', '\u{fe75}'), ('\u{fefd}', '\u{ff00}'), + ('\u{ffbf}', '\u{ffc1}'), ('\u{ffc8}', '\u{ffc9}'), + ('\u{ffd0}', '\u{ffd1}'), ('\u{ffd8}', '\u{ffd9}'), + ('\u{ffdd}', '\u{ffdf}'), ('\u{ffe7}', '\u{ffe7}'), + ('\u{ffef}', '\u{fffb}'), ('\u{fffe}', '\u{ffff}'), + ('\u{1000c}', '\u{1000c}'), ('\u{10027}', '\u{10027}'), + ('\u{1003b}', '\u{1003b}'), ('\u{1003e}', '\u{1003e}'), + ('\u{1004e}', '\u{1004f}'), ('\u{1005e}', '\u{1007f}'), + ('\u{100fb}', '\u{100ff}'), ('\u{10103}', '\u{10106}'), + ('\u{10134}', '\u{10136}'), ('\u{1018f}', '\u{1018f}'), + ('\u{1019c}', '\u{1019f}'), ('\u{101a1}', '\u{101cf}'), + ('\u{101fe}', '\u{1027f}'), ('\u{1029d}', '\u{1029f}'), + ('\u{102d1}', '\u{102df}'), ('\u{102fc}', '\u{102ff}'), + ('\u{10324}', '\u{1032c}'), ('\u{1034b}', '\u{1034f}'), + ('\u{1037b}', '\u{1037f}'), ('\u{1039e}', '\u{1039e}'), + ('\u{103c4}', '\u{103c7}'), ('\u{103d6}', '\u{103ff}'), + ('\u{1049e}', '\u{1049f}'), ('\u{104aa}', '\u{104af}'), + ('\u{104d4}', '\u{104d7}'), ('\u{104fc}', '\u{104ff}'), + ('\u{10528}', '\u{1052f}'), ('\u{10564}', '\u{1056e}'), + ('\u{10570}', '\u{105ff}'), ('\u{10737}', '\u{1073f}'), + ('\u{10756}', '\u{1075f}'), ('\u{10768}', '\u{107ff}'), + ('\u{10806}', '\u{10807}'), ('\u{10809}', '\u{10809}'), + ('\u{10836}', '\u{10836}'), ('\u{10839}', '\u{1083b}'), + ('\u{1083d}', '\u{1083e}'), ('\u{10856}', '\u{10856}'), + ('\u{1089f}', '\u{108a6}'), ('\u{108b0}', '\u{108df}'), + ('\u{108f3}', '\u{108f3}'), ('\u{108f6}', '\u{108fa}'), + ('\u{1091c}', '\u{1091e}'), ('\u{1093a}', '\u{1093e}'), + ('\u{10940}', '\u{1097f}'), ('\u{109b8}', '\u{109bb}'), + ('\u{109d0}', '\u{109d1}'), ('\u{10a04}', '\u{10a04}'), + ('\u{10a07}', '\u{10a0b}'), ('\u{10a14}', '\u{10a14}'), + ('\u{10a18}', '\u{10a18}'), ('\u{10a34}', '\u{10a37}'), + ('\u{10a3b}', '\u{10a3e}'), ('\u{10a48}', '\u{10a4f}'), + ('\u{10a59}', '\u{10a5f}'), ('\u{10aa0}', '\u{10abf}'), + ('\u{10ae7}', '\u{10aea}'), ('\u{10af7}', '\u{10aff}'), + ('\u{10b36}', '\u{10b38}'), ('\u{10b56}', '\u{10b57}'), + ('\u{10b73}', '\u{10b77}'), ('\u{10b92}', '\u{10b98}'), + ('\u{10b9d}', '\u{10ba8}'), ('\u{10bb0}', '\u{10bff}'), + ('\u{10c49}', '\u{10c7f}'), ('\u{10cb3}', '\u{10cbf}'), + ('\u{10cf3}', '\u{10cf9}'), ('\u{10d00}', '\u{10e5f}'), + ('\u{10e7f}', '\u{10fff}'), ('\u{1104e}', '\u{11051}'), + ('\u{11070}', '\u{1107e}'), ('\u{110bd}', '\u{110bd}'), + ('\u{110c2}', '\u{110cf}'), ('\u{110e9}', '\u{110ef}'), + ('\u{110fa}', '\u{110ff}'), ('\u{11135}', '\u{11135}'), + ('\u{11144}', '\u{1114f}'), ('\u{11177}', '\u{1117f}'), + ('\u{111ce}', '\u{111cf}'), ('\u{111e0}', '\u{111e0}'), + ('\u{111f5}', '\u{111ff}'), ('\u{11212}', '\u{11212}'), + ('\u{1123f}', '\u{1127f}'), ('\u{11287}', '\u{11287}'), + ('\u{11289}', '\u{11289}'), ('\u{1128e}', '\u{1128e}'), + ('\u{1129e}', '\u{1129e}'), ('\u{112aa}', '\u{112af}'), + ('\u{112eb}', '\u{112ef}'), ('\u{112fa}', '\u{112ff}'), + ('\u{11304}', '\u{11304}'), ('\u{1130d}', '\u{1130e}'), + ('\u{11311}', '\u{11312}'), ('\u{11329}', '\u{11329}'), + ('\u{11331}', '\u{11331}'), ('\u{11334}', '\u{11334}'), + ('\u{1133a}', '\u{1133b}'), ('\u{11345}', '\u{11346}'), + ('\u{11349}', '\u{1134a}'), ('\u{1134e}', '\u{1134f}'), + ('\u{11351}', '\u{11356}'), ('\u{11358}', '\u{1135c}'), + ('\u{11364}', '\u{11365}'), ('\u{1136d}', '\u{1136f}'), + ('\u{11375}', '\u{113ff}'), ('\u{1145a}', '\u{1145a}'), + ('\u{1145c}', '\u{1145c}'), ('\u{1145e}', '\u{1147f}'), + ('\u{114c8}', '\u{114cf}'), ('\u{114da}', '\u{1157f}'), + ('\u{115b6}', '\u{115b7}'), ('\u{115de}', '\u{115ff}'), + ('\u{11645}', '\u{1164f}'), ('\u{1165a}', '\u{1165f}'), + ('\u{1166d}', '\u{1167f}'), ('\u{116b8}', '\u{116bf}'), + ('\u{116ca}', '\u{116ff}'), ('\u{1171a}', '\u{1171c}'), + ('\u{1172c}', '\u{1172f}'), ('\u{11740}', '\u{1189f}'), + ('\u{118f3}', '\u{118fe}'), ('\u{11900}', '\u{119ff}'), + ('\u{11a48}', '\u{11a4f}'), ('\u{11a84}', '\u{11a85}'), + ('\u{11a9d}', '\u{11a9d}'), ('\u{11aa3}', '\u{11abf}'), + ('\u{11af9}', '\u{11bff}'), ('\u{11c09}', '\u{11c09}'), + ('\u{11c37}', '\u{11c37}'), ('\u{11c46}', '\u{11c4f}'), + ('\u{11c6d}', '\u{11c6f}'), ('\u{11c90}', '\u{11c91}'), + ('\u{11ca8}', '\u{11ca8}'), ('\u{11cb7}', '\u{11cff}'), + ('\u{11d07}', '\u{11d07}'), ('\u{11d0a}', '\u{11d0a}'), + ('\u{11d37}', '\u{11d39}'), ('\u{11d3b}', '\u{11d3b}'), + ('\u{11d3e}', '\u{11d3e}'), ('\u{11d48}', '\u{11d4f}'), + ('\u{11d5a}', '\u{11fff}'), ('\u{1239a}', '\u{123ff}'), + ('\u{1246f}', '\u{1246f}'), ('\u{12475}', '\u{1247f}'), + ('\u{12544}', '\u{12fff}'), ('\u{1342f}', '\u{143ff}'), + ('\u{14647}', '\u{167ff}'), ('\u{16a39}', '\u{16a3f}'), + ('\u{16a5f}', '\u{16a5f}'), ('\u{16a6a}', '\u{16a6d}'), + ('\u{16a70}', '\u{16acf}'), ('\u{16aee}', '\u{16aef}'), + ('\u{16af6}', '\u{16aff}'), ('\u{16b46}', '\u{16b4f}'), + ('\u{16b5a}', '\u{16b5a}'), ('\u{16b62}', '\u{16b62}'), + ('\u{16b78}', '\u{16b7c}'), ('\u{16b90}', '\u{16eff}'), + ('\u{16f45}', '\u{16f4f}'), ('\u{16f7f}', '\u{16f8e}'), + ('\u{16fa0}', '\u{16fdf}'), ('\u{16fe2}', '\u{16fff}'), + ('\u{187ed}', '\u{187ff}'), ('\u{18af3}', '\u{1afff}'), + ('\u{1b11f}', '\u{1b16f}'), ('\u{1b2fc}', '\u{1bbff}'), + ('\u{1bc6b}', '\u{1bc6f}'), ('\u{1bc7d}', '\u{1bc7f}'), + ('\u{1bc89}', '\u{1bc8f}'), ('\u{1bc9a}', '\u{1bc9b}'), + ('\u{1bca0}', '\u{1cfff}'), ('\u{1d0f6}', '\u{1d0ff}'), + ('\u{1d127}', '\u{1d128}'), ('\u{1d173}', '\u{1d17a}'), + ('\u{1d1e9}', '\u{1d1ff}'), ('\u{1d246}', '\u{1d2ff}'), + ('\u{1d357}', '\u{1d35f}'), ('\u{1d372}', '\u{1d3ff}'), + ('\u{1d455}', '\u{1d455}'), ('\u{1d49d}', '\u{1d49d}'), + ('\u{1d4a0}', '\u{1d4a1}'), ('\u{1d4a3}', '\u{1d4a4}'), + ('\u{1d4a7}', '\u{1d4a8}'), ('\u{1d4ad}', '\u{1d4ad}'), + ('\u{1d4ba}', '\u{1d4ba}'), ('\u{1d4bc}', '\u{1d4bc}'), + ('\u{1d4c4}', '\u{1d4c4}'), ('\u{1d506}', '\u{1d506}'), + ('\u{1d50b}', '\u{1d50c}'), ('\u{1d515}', '\u{1d515}'), + ('\u{1d51d}', '\u{1d51d}'), ('\u{1d53a}', '\u{1d53a}'), + ('\u{1d53f}', '\u{1d53f}'), ('\u{1d545}', '\u{1d545}'), + ('\u{1d547}', '\u{1d549}'), ('\u{1d551}', '\u{1d551}'), + ('\u{1d6a6}', '\u{1d6a7}'), ('\u{1d7cc}', '\u{1d7cd}'), + ('\u{1da8c}', '\u{1da9a}'), ('\u{1daa0}', '\u{1daa0}'), + ('\u{1dab0}', '\u{1dfff}'), ('\u{1e007}', '\u{1e007}'), + ('\u{1e019}', '\u{1e01a}'), ('\u{1e022}', '\u{1e022}'), + ('\u{1e025}', '\u{1e025}'), ('\u{1e02b}', '\u{1e7ff}'), + ('\u{1e8c5}', '\u{1e8c6}'), ('\u{1e8d7}', '\u{1e8ff}'), + ('\u{1e94b}', '\u{1e94f}'), ('\u{1e95a}', '\u{1e95d}'), + ('\u{1e960}', '\u{1edff}'), ('\u{1ee04}', '\u{1ee04}'), + ('\u{1ee20}', '\u{1ee20}'), ('\u{1ee23}', '\u{1ee23}'), + ('\u{1ee25}', '\u{1ee26}'), ('\u{1ee28}', '\u{1ee28}'), + ('\u{1ee33}', '\u{1ee33}'), ('\u{1ee38}', '\u{1ee38}'), + ('\u{1ee3a}', '\u{1ee3a}'), ('\u{1ee3c}', '\u{1ee41}'), + ('\u{1ee43}', '\u{1ee46}'), ('\u{1ee48}', '\u{1ee48}'), + ('\u{1ee4a}', '\u{1ee4a}'), ('\u{1ee4c}', '\u{1ee4c}'), + ('\u{1ee50}', '\u{1ee50}'), ('\u{1ee53}', '\u{1ee53}'), + ('\u{1ee55}', '\u{1ee56}'), ('\u{1ee58}', '\u{1ee58}'), + ('\u{1ee5a}', '\u{1ee5a}'), ('\u{1ee5c}', '\u{1ee5c}'), + ('\u{1ee5e}', '\u{1ee5e}'), ('\u{1ee60}', '\u{1ee60}'), + ('\u{1ee63}', '\u{1ee63}'), ('\u{1ee65}', '\u{1ee66}'), + ('\u{1ee6b}', '\u{1ee6b}'), ('\u{1ee73}', '\u{1ee73}'), + ('\u{1ee78}', '\u{1ee78}'), ('\u{1ee7d}', '\u{1ee7d}'), + ('\u{1ee7f}', '\u{1ee7f}'), ('\u{1ee8a}', '\u{1ee8a}'), + ('\u{1ee9c}', '\u{1eea0}'), ('\u{1eea4}', '\u{1eea4}'), + ('\u{1eeaa}', '\u{1eeaa}'), ('\u{1eebc}', '\u{1eeef}'), + ('\u{1eef2}', '\u{1efff}'), ('\u{1f02c}', '\u{1f02f}'), + ('\u{1f094}', '\u{1f09f}'), ('\u{1f0af}', '\u{1f0b0}'), + ('\u{1f0c0}', '\u{1f0c0}'), ('\u{1f0d0}', '\u{1f0d0}'), + ('\u{1f0f6}', '\u{1f0ff}'), ('\u{1f10d}', '\u{1f10f}'), + ('\u{1f12f}', '\u{1f12f}'), ('\u{1f16c}', '\u{1f16f}'), + ('\u{1f1ad}', '\u{1f1e5}'), ('\u{1f203}', '\u{1f20f}'), + ('\u{1f23c}', '\u{1f23f}'), ('\u{1f249}', '\u{1f24f}'), + ('\u{1f252}', '\u{1f25f}'), ('\u{1f266}', '\u{1f2ff}'), + ('\u{1f6d5}', '\u{1f6df}'), ('\u{1f6ed}', '\u{1f6ef}'), + ('\u{1f6f9}', '\u{1f6ff}'), ('\u{1f774}', '\u{1f77f}'), + ('\u{1f7d5}', '\u{1f7ff}'), ('\u{1f80c}', '\u{1f80f}'), + ('\u{1f848}', '\u{1f84f}'), ('\u{1f85a}', '\u{1f85f}'), + ('\u{1f888}', '\u{1f88f}'), ('\u{1f8ae}', '\u{1f8ff}'), + ('\u{1f90c}', '\u{1f90f}'), ('\u{1f93f}', '\u{1f93f}'), + ('\u{1f94d}', '\u{1f94f}'), ('\u{1f96c}', '\u{1f97f}'), + ('\u{1f998}', '\u{1f9bf}'), ('\u{1f9c1}', '\u{1f9cf}'), + ('\u{1f9e7}', '\u{1ffff}'), ('\u{2a6d7}', '\u{2a6ff}'), + ('\u{2b735}', '\u{2b73f}'), ('\u{2b81e}', '\u{2b81f}'), + ('\u{2cea2}', '\u{2ceaf}'), ('\u{2ebe1}', '\u{2f7ff}'), + ('\u{2fa1e}', '\u{e00ff}'), ('\u{e01f0}', '\u{10ffff}'), +]; + +pub const OTHER_LETTER: &'static [(char, char)] = &[ + ('ª', 'ª'), ('º', 'º'), ('ƻ', 'ƻ'), ('ǀ', 'ǃ'), ('ʔ', 'ʔ'), + ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ؿ'), ('ف', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), ('ۿ', 'ۿ'), + ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), ('ߊ', 'ߪ'), + ('ࠀ', 'ࠕ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), + ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), ('ॐ', 'ॐ'), + ('क़', 'ॡ'), ('ॲ', 'ঀ'), ('অ', 'ঌ'), ('এ', 'ঐ'), + ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), + ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), ('য়', 'ৡ'), + ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), + ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), + ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('ੲ', 'ੴ'), + ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), + ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), ('ૐ', 'ૐ'), + ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), + ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), + ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), ('ୱ', 'ୱ'), + ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ఽ'), + ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), ('ೱ', 'ೲ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), ('ഽ', 'ഽ'), + ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), ('ൺ', 'ൿ'), + ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), ('ල', 'ල'), + ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'ำ'), ('เ', 'ๅ'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ະ'), + ('າ', 'ຳ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), ('ໜ', 'ໟ'), + ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), + ('က', 'ဪ'), ('ဿ', 'ဿ'), ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), + ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), + ('ႎ', 'ႎ'), ('ა', 'ჺ'), ('ჽ', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኈ'), + ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), + ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), ('ዘ', 'ጐ'), + ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), ('ᐁ', 'ᙬ'), + ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛱ', 'ᛸ'), + ('ᜀ', 'ᜌ'), ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), + ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡂ'), ('ᡄ', 'ᡷ'), ('ᢀ', 'ᢄ'), ('ᢇ', 'ᢨ'), + ('ᢪ', 'ᢪ'), ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), + ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), + ('ᨠ', 'ᩔ'), ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), + ('ᮮ', 'ᮯ'), ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), + ('ᱚ', 'ᱷ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), ('ᳵ', 'ᳶ'), + ('ℵ', 'ℸ'), ('ⴰ', 'ⵧ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('〆', '〆'), + ('〼', '〼'), ('ぁ', 'ゖ'), ('ゟ', 'ゟ'), ('ァ', 'ヺ'), + ('ヿ', 'ヿ'), ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), + ('ㇰ', 'ㇿ'), ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꀔ'), + ('ꀖ', 'ꒌ'), ('ꓐ', 'ꓷ'), ('ꔀ', 'ꘋ'), ('ꘐ', 'ꘟ'), + ('ꘪ', 'ꘫ'), ('ꙮ', 'ꙮ'), ('ꚠ', 'ꛥ'), ('ꞏ', 'ꞏ'), + ('ꟷ', 'ꟷ'), ('ꟻ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), + ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), + ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), ('ꧠ', 'ꧤ'), ('ꧧ', 'ꧯ'), + ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), ('ꩄ', 'ꩋ'), + ('ꩠ', 'ꩯ'), ('ꩱ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫜ'), ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫲ'), + ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), + ('ꬨ', 'ꬮ'), ('ꯀ', 'ꯢ'), ('가', '힣'), ('ힰ', 'ퟆ'), + ('ퟋ', 'ퟻ'), ('豈', '舘'), ('並', '龎'), ('יִ', 'יִ'), + ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('ヲ', 'ッ'), ('ア', 'ン'), ('ᅠ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐊀', '𐊜'), + ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍀'), ('𐍂', '𐍉'), + ('𐍐', '𐍵'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), + ('𐑐', '𐒝'), ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), + ('𐡠', '𐡶'), ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐤀', '𐤕'), ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), + ('𐨀', '𐨀'), ('𐨐', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𑀃', '𑀷'), ('𑂃', '𑂯'), ('𑃐', '𑃨'), + ('𑄃', '𑄦'), ('𑅐', '𑅲'), ('𑅶', '𑅶'), ('𑆃', '𑆲'), + ('𑇁', '𑇄'), ('𑇚', '𑇚'), ('𑇜', '𑇜'), ('𑈀', '𑈑'), + ('𑈓', '𑈫'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋞'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑍐', '𑍐'), ('𑍝', '𑍡'), + ('𑐀', '𑐴'), ('𑑇', '𑑊'), ('𑒀', '𑒯'), ('𑓄', '𑓅'), + ('𑓇', '𑓇'), ('𑖀', '𑖮'), ('𑗘', '𑗛'), ('𑘀', '𑘯'), + ('𑙄', '𑙄'), ('𑚀', '𑚪'), ('𑜀', '𑜙'), ('𑣿', '𑣿'), + ('𑨀', '𑨀'), ('𑨋', '𑨲'), ('𑨺', '𑨺'), ('𑩐', '𑩐'), + ('𑩜', '𑪃'), ('𑪆', '𑪉'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), + ('𑰊', '𑰮'), ('𑱀', '𑱀'), ('𑱲', '𑲏'), ('𑴀', '𑴆'), + ('𑴈', '𑴉'), ('𑴋', '𑴰'), ('𑵆', '𑵆'), ('𒀀', '𒎙'), + ('𒒀', '𒕃'), ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), + ('𖩀', '𖩞'), ('𖫐', '𖫭'), ('𖬀', '𖬯'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𗀀', '𘟬'), + ('𘠀', '𘫲'), ('𛀀', '𛄞'), ('𛅰', '𛋻'), ('𛰀', '𛱪'), + ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𞠀', '𞣄'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), + ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const OTHER_NUMBER: &'static [(char, char)] = &[ + ('²', '³'), ('¹', '¹'), ('¼', '¾'), ('৴', '৹'), ('୲', '୷'), + ('௰', '௲'), ('౸', '౾'), ('൘', '൞'), ('൰', '൸'), + ('༪', '༳'), ('፩', '፼'), ('៰', '៹'), ('᧚', '᧚'), + ('⁰', '⁰'), ('⁴', '⁹'), ('₀', '₉'), ('⅐', '⅟'), + ('↉', '↉'), ('①', '⒛'), ('⓪', '⓿'), ('❶', '➓'), + ('⳽', '⳽'), ('㆒', '㆕'), ('㈠', '㈩'), ('㉈', '㉏'), + ('㉑', '㉟'), ('㊀', '㊉'), ('㊱', '㊿'), ('꠰', '꠵'), + ('𐄇', '𐄳'), ('𐅵', '𐅸'), ('𐆊', '𐆋'), ('𐋡', '𐋻'), + ('𐌠', '𐌣'), ('𐡘', '𐡟'), ('𐡹', '𐡿'), ('𐢧', '𐢯'), + ('𐣻', '𐣿'), ('𐤖', '𐤛'), ('𐦼', '𐦽'), ('𐧀', '𐧏'), + ('𐧒', '𐧿'), ('𐩀', '𐩇'), ('𐩽', '𐩾'), ('𐪝', '𐪟'), + ('𐫫', '𐫯'), ('𐭘', '𐭟'), ('𐭸', '𐭿'), ('𐮩', '𐮯'), + ('𐳺', '𐳿'), ('𐹠', '𐹾'), ('𑁒', '𑁥'), ('𑇡', '𑇴'), + ('𑜺', '𑜻'), ('𑣪', '𑣲'), ('𑱚', '𑱬'), ('𖭛', '𖭡'), + ('𝍠', '𝍱'), ('𞣇', '𞣏'), ('🄀', '🄌'), +]; + +pub const OTHER_PUNCTUATION: &'static [(char, char)] = &[ + ('!', '#'), ('%', '\''), ('*', '*'), (',', ','), ('.', '/'), (':', ';'), + ('?', '@'), ('\\', '\\'), ('¡', '¡'), ('§', '§'), ('¶', '·'), + ('¿', '¿'), (';', ';'), ('·', '·'), ('՚', '՟'), ('։', '։'), + ('׀', '׀'), ('׃', '׃'), ('׆', '׆'), ('׳', '״'), ('؉', '؊'), + ('،', '؍'), ('؛', '؛'), ('؞', '؟'), ('٪', '٭'), ('۔', '۔'), + ('܀', '܍'), ('߷', '߹'), ('࠰', '࠾'), ('࡞', '࡞'), ('।', '॥'), + ('॰', '॰'), ('৽', '৽'), ('૰', '૰'), ('෴', '෴'), + ('๏', '๏'), ('๚', '๛'), ('༄', '༒'), ('༔', '༔'), + ('྅', '྅'), ('࿐', '࿔'), ('࿙', '࿚'), ('၊', '၏'), + ('჻', '჻'), ('፠', '፨'), ('᙭', '᙮'), ('᛫', '᛭'), + ('᜵', '᜶'), ('។', '៖'), ('៘', '៚'), ('᠀', '᠅'), + ('᠇', '᠊'), ('᥄', '᥅'), ('᨞', '᨟'), ('᪠', '᪦'), + ('᪨', '᪭'), ('᭚', '᭠'), ('᯼', '᯿'), ('᰻', '᰿'), + ('᱾', '᱿'), ('᳀', '᳇'), ('᳓', '᳓'), ('‖', '‗'), + ('†', '‧'), ('‰', '‸'), ('※', '‾'), ('⁁', '⁃'), + ('⁇', '⁑'), ('⁓', '⁓'), ('⁕', '⁞'), ('⳹', '⳼'), + ('⳾', '⳿'), ('⵰', '⵰'), ('⸀', '⸁'), ('⸆', '⸈'), + ('⸋', '⸋'), ('⸎', '⸖'), ('⸘', '⸙'), ('⸛', '⸛'), + ('⸞', '⸟'), ('⸪', '⸮'), ('⸰', '⸹'), ('⸼', '⸿'), + ('⹁', '⹁'), ('⹃', '⹉'), ('、', '〃'), ('〽', '〽'), + ('・', '・'), ('꓾', '꓿'), ('꘍', '꘏'), ('꙳', '꙳'), + ('꙾', '꙾'), ('꛲', '꛷'), ('꡴', '꡷'), ('꣎', '꣏'), + ('꣸', '꣺'), ('꣼', '꣼'), ('꤮', '꤯'), ('꥟', '꥟'), + ('꧁', '꧍'), ('꧞', '꧟'), ('꩜', '꩟'), ('꫞', '꫟'), + ('꫰', '꫱'), ('꯫', '꯫'), ('︐', '︖'), ('︙', '︙'), + ('︰', '︰'), ('﹅', '﹆'), ('﹉', '﹌'), ('﹐', '﹒'), + ('﹔', '﹗'), ('﹟', '﹡'), ('﹨', '﹨'), ('﹪', '﹫'), + ('!', '#'), ('%', '''), ('*', '*'), (',', ','), + ('.', '/'), (':', ';'), ('?', '@'), ('\', '\'), + ('。', '。'), ('、', '・'), ('𐄀', '𐄂'), ('𐎟', '𐎟'), + ('𐏐', '𐏐'), ('𐕯', '𐕯'), ('𐡗', '𐡗'), ('𐤟', '𐤟'), + ('𐤿', '𐤿'), ('𐩐', '𐩘'), ('𐩿', '𐩿'), ('𐫰', '𐫶'), + ('𐬹', '𐬿'), ('𐮙', '𐮜'), ('𑁇', '𑁍'), ('𑂻', '𑂼'), + ('𑂾', '𑃁'), ('𑅀', '𑅃'), ('𑅴', '𑅵'), ('𑇅', '𑇉'), + ('𑇍', '𑇍'), ('𑇛', '𑇛'), ('𑇝', '𑇟'), ('𑈸', '𑈽'), + ('𑊩', '𑊩'), ('𑑋', '𑑏'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), + ('𑓆', '𑓆'), ('𑗁', '𑗗'), ('𑙁', '𑙃'), ('𑙠', '𑙬'), + ('𑜼', '𑜾'), ('𑨿', '𑩆'), ('𑪚', '𑪜'), ('𑪞', '𑪢'), + ('𑱁', '𑱅'), ('𑱰', '𑱱'), ('𒑰', '𒑴'), ('𖩮', '𖩯'), + ('𖫵', '𖫵'), ('𖬷', '𖬻'), ('𖭄', '𖭄'), ('𛲟', '𛲟'), + ('𝪇', '𝪋'), ('𞥞', '𞥟'), +]; + +pub const OTHER_SYMBOL: &'static [(char, char)] = &[ + ('¦', '¦'), ('©', '©'), ('®', '®'), ('°', '°'), ('҂', '҂'), + ('֍', '֎'), ('؎', '؏'), ('۞', '۞'), ('۩', '۩'), ('۽', '۾'), + ('߶', '߶'), ('৺', '৺'), ('୰', '୰'), ('௳', '௸'), + ('௺', '௺'), ('౿', '౿'), ('൏', '൏'), ('൹', '൹'), + ('༁', '༃'), ('༓', '༓'), ('༕', '༗'), ('༚', '༟'), + ('༴', '༴'), ('༶', '༶'), ('༸', '༸'), ('྾', '࿅'), + ('࿇', '࿌'), ('࿎', '࿏'), ('࿕', '࿘'), ('႞', '႟'), + ('᎐', '᎙'), ('᥀', '᥀'), ('᧞', '᧿'), ('᭡', '᭪'), + ('᭴', '᭼'), ('℀', '℁'), ('℃', '℆'), ('℈', '℉'), + ('℔', '℔'), ('№', '℗'), ('℞', '℣'), ('℥', '℥'), + ('℧', '℧'), ('℩', '℩'), ('℮', '℮'), ('℺', '℻'), + ('⅊', '⅊'), ('⅌', '⅍'), ('⅏', '⅏'), ('↊', '↋'), + ('↕', '↙'), ('↜', '↟'), ('↡', '↢'), ('↤', '↥'), + ('↧', '↭'), ('↯', '⇍'), ('⇐', '⇑'), ('⇓', '⇓'), + ('⇕', '⇳'), ('⌀', '⌇'), ('⌌', '⌟'), ('⌢', '⌨'), + ('⌫', '⍻'), ('⍽', '⎚'), ('⎴', '⏛'), ('⏢', '␦'), + ('⑀', '⑊'), ('⒜', 'ⓩ'), ('─', '▶'), ('▸', '◀'), + ('◂', '◷'), ('☀', '♮'), ('♰', '❧'), ('➔', '➿'), + ('⠀', '⣿'), ('⬀', '⬯'), ('⭅', '⭆'), ('⭍', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯒'), + ('⯬', '⯯'), ('⳥', '⳪'), ('⺀', '⺙'), ('⺛', '⻳'), + ('⼀', '⿕'), ('⿰', '⿻'), ('〄', '〄'), ('〒', '〓'), + ('〠', '〠'), ('〶', '〷'), ('〾', '〿'), ('㆐', '㆑'), + ('㆖', '㆟'), ('㇀', '㇣'), ('㈀', '㈞'), ('㈪', '㉇'), + ('㉐', '㉐'), ('㉠', '㉿'), ('㊊', '㊰'), ('㋀', '㋾'), + ('㌀', '㏿'), ('䷀', '䷿'), ('꒐', '꓆'), ('꠨', '꠫'), + ('꠶', '꠷'), ('꠹', '꠹'), ('꩷', '꩹'), ('﷽', '﷽'), + ('¦', '¦'), ('│', '│'), ('■', '○'), ('', '�'), + ('𐄷', '𐄿'), ('𐅹', '𐆉'), ('𐆌', '𐆎'), ('𐆐', '𐆛'), + ('𐆠', '𐆠'), ('𐇐', '𐇼'), ('𐡷', '𐡸'), ('𐫈', '𐫈'), + ('𑜿', '𑜿'), ('𖬼', '𖬿'), ('𖭅', '𖭅'), ('𛲜', '𛲜'), + ('𝀀', '𝃵'), ('𝄀', '𝄦'), ('𝄩', '𝅘𝅥𝅲'), ('𝅪', '𝅬'), + ('𝆃', '𝆄'), ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝈀', '𝉁'), + ('𝉅', '𝉅'), ('𝌀', '𝍖'), ('𝠀', '𝧿'), ('𝨷', '𝨺'), + ('𝩭', '𝩴'), ('𝩶', '𝪃'), ('𝪅', '𝪆'), ('🀀', '🀫'), + ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), ('🃁', '🃏'), + ('🃑', '🃵'), ('🄐', '🄮'), ('🄰', '🅫'), ('🅰', '🆬'), + ('🇦', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), ('🉐', '🉑'), + ('🉠', '🉥'), ('🌀', '🏺'), ('🐀', '🛔'), ('🛠', '🛬'), + ('🛰', '🛸'), ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), + ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), + ('🤀', '🤋'), ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), + ('🦀', '🦗'), ('🧀', '🧀'), ('🧐', '🧦'), +]; + +pub const PARAGRAPH_SEPARATOR: &'static [(char, char)] = &[ + ('\u{2029}', '\u{2029}'), +]; + +pub const PRIVATE_USE: &'static [(char, char)] = &[ + ('\u{e000}', '\u{f8ff}'), ('\u{f0000}', '\u{ffffd}'), + ('\u{100000}', '\u{10fffd}'), +]; + +pub const PUNCTUATION: &'static [(char, char)] = &[ + ('!', '#'), ('%', '*'), (',', '/'), (':', ';'), ('?', '@'), ('[', ']'), + ('_', '_'), ('{', '{'), ('}', '}'), ('¡', '¡'), ('§', '§'), + ('«', '«'), ('¶', '·'), ('»', '»'), ('¿', '¿'), (';', ';'), + ('·', '·'), ('՚', '՟'), ('։', '֊'), ('־', '־'), ('׀', '׀'), + ('׃', '׃'), ('׆', '׆'), ('׳', '״'), ('؉', '؊'), ('،', '؍'), + ('؛', '؛'), ('؞', '؟'), ('٪', '٭'), ('۔', '۔'), ('܀', '܍'), + ('߷', '߹'), ('࠰', '࠾'), ('࡞', '࡞'), ('।', '॥'), + ('॰', '॰'), ('৽', '৽'), ('૰', '૰'), ('෴', '෴'), + ('๏', '๏'), ('๚', '๛'), ('༄', '༒'), ('༔', '༔'), + ('༺', '༽'), ('྅', '྅'), ('࿐', '࿔'), ('࿙', '࿚'), + ('၊', '၏'), ('჻', '჻'), ('፠', '፨'), ('᐀', '᐀'), + ('᙭', '᙮'), ('᚛', '᚜'), ('᛫', '᛭'), ('᜵', '᜶'), + ('។', '៖'), ('៘', '៚'), ('᠀', '᠊'), ('᥄', '᥅'), + ('᨞', '᨟'), ('᪠', '᪦'), ('᪨', '᪭'), ('᭚', '᭠'), + ('᯼', '᯿'), ('᰻', '᰿'), ('᱾', '᱿'), ('᳀', '᳇'), + ('᳓', '᳓'), ('‐', '‧'), ('‰', '⁃'), ('⁅', '⁑'), + ('⁓', '⁞'), ('⁽', '⁾'), ('₍', '₎'), ('⌈', '⌋'), + ('〈', '〉'), ('❨', '❵'), ('⟅', '⟆'), ('⟦', '⟯'), + ('⦃', '⦘'), ('⧘', '⧛'), ('⧼', '⧽'), ('⳹', '⳼'), + ('⳾', '⳿'), ('⵰', '⵰'), ('⸀', '⸮'), ('⸰', '⹉'), + ('、', '〃'), ('〈', '】'), ('〔', '〟'), ('〰', '〰'), + ('〽', '〽'), ('゠', '゠'), ('・', '・'), ('꓾', '꓿'), + ('꘍', '꘏'), ('꙳', '꙳'), ('꙾', '꙾'), ('꛲', '꛷'), + ('꡴', '꡷'), ('꣎', '꣏'), ('꣸', '꣺'), ('꣼', '꣼'), + ('꤮', '꤯'), ('꥟', '꥟'), ('꧁', '꧍'), ('꧞', '꧟'), + ('꩜', '꩟'), ('꫞', '꫟'), ('꫰', '꫱'), ('꯫', '꯫'), + ('﴾', '﴿'), ('︐', '︙'), ('︰', '﹒'), ('﹔', '﹡'), + ('﹣', '﹣'), ('﹨', '﹨'), ('﹪', '﹫'), ('!', '#'), + ('%', '*'), (',', '/'), (':', ';'), ('?', '@'), + ('[', ']'), ('_', '_'), ('{', '{'), ('}', '}'), + ('⦅', '・'), ('𐄀', '𐄂'), ('𐎟', '𐎟'), ('𐏐', '𐏐'), + ('𐕯', '𐕯'), ('𐡗', '𐡗'), ('𐤟', '𐤟'), ('𐤿', '𐤿'), + ('𐩐', '𐩘'), ('𐩿', '𐩿'), ('𐫰', '𐫶'), ('𐬹', '𐬿'), + ('𐮙', '𐮜'), ('𑁇', '𑁍'), ('𑂻', '𑂼'), ('𑂾', '𑃁'), + ('𑅀', '𑅃'), ('𑅴', '𑅵'), ('𑇅', '𑇉'), ('𑇍', '𑇍'), + ('𑇛', '𑇛'), ('𑇝', '𑇟'), ('𑈸', '𑈽'), ('𑊩', '𑊩'), + ('𑑋', '𑑏'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), ('𑓆', '𑓆'), + ('𑗁', '𑗗'), ('𑙁', '𑙃'), ('𑙠', '𑙬'), ('𑜼', '𑜾'), + ('𑨿', '𑩆'), ('𑪚', '𑪜'), ('𑪞', '𑪢'), ('𑱁', '𑱅'), + ('𑱰', '𑱱'), ('𒑰', '𒑴'), ('𖩮', '𖩯'), ('𖫵', '𖫵'), + ('𖬷', '𖬻'), ('𖭄', '𖭄'), ('𛲟', '𛲟'), ('𝪇', '𝪋'), + ('𞥞', '𞥟'), +]; + +pub const SEPARATOR: &'static [(char, char)] = &[ + (' ', ' '), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), + ('\u{2000}', '\u{200a}'), ('\u{2028}', '\u{2029}'), + ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'), + ('\u{3000}', '\u{3000}'), +]; + +pub const SPACE_SEPARATOR: &'static [(char, char)] = &[ + (' ', ' '), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), + ('\u{2000}', '\u{200a}'), ('\u{202f}', '\u{202f}'), + ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), +]; + +pub const SPACING_MARK: &'static [(char, char)] = &[ + ('ः', 'ः'), ('ऻ', 'ऻ'), ('ा', 'ी'), ('ॉ', 'ौ'), + ('ॎ', 'ॏ'), ('ং', 'ঃ'), ('া', 'ী'), ('ে', 'ৈ'), + ('ো', 'ৌ'), ('ৗ', 'ৗ'), ('ਃ', 'ਃ'), ('ਾ', 'ੀ'), + ('ઃ', 'ઃ'), ('ા', 'ી'), ('ૉ', 'ૉ'), ('ો', 'ૌ'), + ('ଂ', 'ଃ'), ('ା', 'ା'), ('ୀ', 'ୀ'), ('େ', 'ୈ'), + ('ୋ', 'ୌ'), ('ୗ', 'ୗ'), ('ா', 'ி'), ('ு', 'ூ'), + ('ெ', 'ை'), ('ொ', 'ௌ'), ('ௗ', 'ௗ'), ('ఁ', 'ః'), + ('ు', 'ౄ'), ('ಂ', 'ಃ'), ('ಾ', 'ಾ'), ('ೀ', 'ೄ'), + ('ೇ', 'ೈ'), ('ೊ', 'ೋ'), ('ೕ', 'ೖ'), ('ം', 'ഃ'), + ('ാ', 'ീ'), ('െ', 'ൈ'), ('ൊ', 'ൌ'), ('ൗ', 'ൗ'), + ('ං', 'ඃ'), ('ා', 'ෑ'), ('ෘ', 'ෟ'), ('ෲ', 'ෳ'), + ('༾', '༿'), ('ཿ', 'ཿ'), ('ါ', 'ာ'), ('ေ', 'ေ'), + ('း', 'း'), ('ျ', 'ြ'), ('ၖ', 'ၗ'), ('ၢ', 'ၤ'), + ('ၧ', 'ၭ'), ('ႃ', 'ႄ'), ('ႇ', 'ႌ'), ('ႏ', 'ႏ'), + ('ႚ', 'ႜ'), ('ា', 'ា'), ('ើ', 'ៅ'), ('ះ', 'ៈ'), + ('ᤣ', 'ᤦ'), ('ᤩ', 'ᤫ'), ('ᤰ', 'ᤱ'), ('ᤳ', 'ᤸ'), + ('ᨙ', 'ᨚ'), ('ᩕ', 'ᩕ'), ('ᩗ', 'ᩗ'), ('ᩡ', 'ᩡ'), + ('ᩣ', 'ᩤ'), ('ᩭ', 'ᩲ'), ('ᬄ', 'ᬄ'), ('ᬵ', 'ᬵ'), + ('ᬻ', 'ᬻ'), ('ᬽ', 'ᭁ'), ('ᭃ', '᭄'), ('ᮂ', 'ᮂ'), + ('ᮡ', 'ᮡ'), ('ᮦ', 'ᮧ'), ('᮪', '᮪'), ('ᯧ', 'ᯧ'), + ('ᯪ', 'ᯬ'), ('ᯮ', 'ᯮ'), ('᯲', '᯳'), ('ᰤ', 'ᰫ'), + ('ᰴ', 'ᰵ'), ('᳡', '᳡'), ('ᳲ', 'ᳳ'), ('᳷', '᳷'), + ('〮', '〯'), ('ꠣ', 'ꠤ'), ('ꠧ', 'ꠧ'), ('ꢀ', 'ꢁ'), + ('ꢴ', 'ꣃ'), ('ꥒ', '꥓'), ('ꦃ', 'ꦃ'), ('ꦴ', 'ꦵ'), + ('ꦺ', 'ꦻ'), ('ꦽ', '꧀'), ('ꨯ', 'ꨰ'), ('ꨳ', 'ꨴ'), + ('ꩍ', 'ꩍ'), ('ꩻ', 'ꩻ'), ('ꩽ', 'ꩽ'), ('ꫫ', 'ꫫ'), + ('ꫮ', 'ꫯ'), ('ꫵ', 'ꫵ'), ('ꯣ', 'ꯤ'), ('ꯦ', 'ꯧ'), + ('ꯩ', 'ꯪ'), ('꯬', '꯬'), ('𑀀', '𑀀'), ('𑀂', '𑀂'), + ('𑂂', '𑂂'), ('𑂰', '𑂲'), ('𑂷', '𑂸'), ('𑄬', '𑄬'), + ('𑆂', '𑆂'), ('𑆳', '𑆵'), ('𑆿', '𑇀'), ('𑈬', '𑈮'), + ('𑈲', '𑈳'), ('𑈵', '𑈵'), ('𑋠', '𑋢'), ('𑌂', '𑌃'), + ('𑌾', '𑌿'), ('𑍁', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), + ('𑍗', '𑍗'), ('𑍢', '𑍣'), ('𑐵', '𑐷'), ('𑑀', '𑑁'), + ('𑑅', '𑑅'), ('𑒰', '𑒲'), ('𑒹', '𑒹'), ('𑒻', '𑒾'), + ('𑓁', '𑓁'), ('𑖯', '𑖱'), ('𑖸', '𑖻'), ('𑖾', '𑖾'), + ('𑘰', '𑘲'), ('𑘻', '𑘼'), ('𑘾', '𑘾'), ('𑚬', '𑚬'), + ('𑚮', '𑚯'), ('𑚶', '𑚶'), ('𑜠', '𑜡'), ('𑜦', '𑜦'), + ('𑨇', '𑨈'), ('𑨹', '𑨹'), ('𑩗', '𑩘'), ('𑪗', '𑪗'), + ('𑰯', '𑰯'), ('𑰾', '𑰾'), ('𑲩', '𑲩'), ('𑲱', '𑲱'), + ('𑲴', '𑲴'), ('𖽑', '𖽾'), ('𝅥', '𝅦'), ('𝅭', '𝅲'), +]; + +pub const SYMBOL: &'static [(char, char)] = &[ + ('$', '$'), ('+', '+'), ('<', '>'), ('^', '^'), ('`', '`'), ('|', '|'), + ('~', '~'), ('¢', '¦'), ('¨', '©'), ('¬', '¬'), ('®', '±'), + ('´', '´'), ('¸', '¸'), ('×', '×'), ('÷', '÷'), ('˂', '˅'), + ('˒', '˟'), ('˥', '˫'), ('˭', '˭'), ('˯', '˿'), ('͵', '͵'), + ('΄', '΅'), ('϶', '϶'), ('҂', '҂'), ('֍', '֏'), ('؆', '؈'), + ('؋', '؋'), ('؎', '؏'), ('۞', '۞'), ('۩', '۩'), ('۽', '۾'), + ('߶', '߶'), ('৲', '৳'), ('৺', '৻'), ('૱', '૱'), + ('୰', '୰'), ('௳', '௺'), ('౿', '౿'), ('൏', '൏'), + ('൹', '൹'), ('฿', '฿'), ('༁', '༃'), ('༓', '༓'), + ('༕', '༗'), ('༚', '༟'), ('༴', '༴'), ('༶', '༶'), + ('༸', '༸'), ('྾', '࿅'), ('࿇', '࿌'), ('࿎', '࿏'), + ('࿕', '࿘'), ('႞', '႟'), ('᎐', '᎙'), ('៛', '៛'), + ('᥀', '᥀'), ('᧞', '᧿'), ('᭡', '᭪'), ('᭴', '᭼'), + ('᾽', '᾽'), ('᾿', '῁'), ('῍', '῏'), ('῝', '῟'), + ('῭', '`'), ('´', '῾'), ('⁄', '⁄'), ('⁒', '⁒'), + ('⁺', '⁼'), ('₊', '₌'), ('₠', '₿'), ('℀', '℁'), + ('℃', '℆'), ('℈', '℉'), ('℔', '℔'), ('№', '℘'), + ('℞', '℣'), ('℥', '℥'), ('℧', '℧'), ('℩', '℩'), + ('℮', '℮'), ('℺', '℻'), ('⅀', '⅄'), ('⅊', '⅍'), + ('⅏', '⅏'), ('↊', '↋'), ('←', '⌇'), ('⌌', '⌨'), + ('⌫', '␦'), ('⑀', '⑊'), ('⒜', 'ⓩ'), ('─', '❧'), + ('➔', '⟄'), ('⟇', '⟥'), ('⟰', '⦂'), ('⦙', '⧗'), + ('⧜', '⧻'), ('⧾', '⭳'), ('⭶', '⮕'), ('⮘', '⮹'), + ('⮽', '⯈'), ('⯊', '⯒'), ('⯬', '⯯'), ('⳥', '⳪'), + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('⿰', '⿻'), + ('〄', '〄'), ('〒', '〓'), ('〠', '〠'), ('〶', '〷'), + ('〾', '〿'), ('゛', '゜'), ('㆐', '㆑'), ('㆖', '㆟'), + ('㇀', '㇣'), ('㈀', '㈞'), ('㈪', '㉇'), ('㉐', '㉐'), + ('㉠', '㉿'), ('㊊', '㊰'), ('㋀', '㋾'), ('㌀', '㏿'), + ('䷀', '䷿'), ('꒐', '꓆'), ('꜀', '꜖'), ('꜠', '꜡'), + ('꞉', '꞊'), ('꠨', '꠫'), ('꠶', '꠹'), ('꩷', '꩹'), + ('꭛', '꭛'), ('﬩', '﬩'), ('﮲', '﯁'), ('﷼', '﷽'), + ('﹢', '﹢'), ('﹤', '﹦'), ('﹩', '﹩'), ('$', '$'), + ('+', '+'), ('<', '>'), ('^', '^'), ('`', '`'), + ('|', '|'), ('~', '~'), ('¢', '₩'), ('│', '○'), + ('', '�'), ('𐄷', '𐄿'), ('𐅹', '𐆉'), ('𐆌', '𐆎'), + ('𐆐', '𐆛'), ('𐆠', '𐆠'), ('𐇐', '𐇼'), ('𐡷', '𐡸'), + ('𐫈', '𐫈'), ('𑜿', '𑜿'), ('𖬼', '𖬿'), ('𖭅', '𖭅'), + ('𛲜', '𛲜'), ('𝀀', '𝃵'), ('𝄀', '𝄦'), ('𝄩', '𝅘𝅥𝅲'), + ('𝅪', '𝅬'), ('𝆃', '𝆄'), ('𝆌', '𝆩'), ('𝆮', '𝇨'), + ('𝈀', '𝉁'), ('𝉅', '𝉅'), ('𝌀', '𝍖'), ('𝛁', '𝛁'), + ('𝛛', '𝛛'), ('𝛻', '𝛻'), ('𝜕', '𝜕'), ('𝜵', '𝜵'), + ('𝝏', '𝝏'), ('𝝯', '𝝯'), ('𝞉', '𝞉'), ('𝞩', '𝞩'), + ('𝟃', '𝟃'), ('𝠀', '𝧿'), ('𝨷', '𝨺'), ('𝩭', '𝩴'), + ('𝩶', '𝪃'), ('𝪅', '𝪆'), ('𞻰', '𞻱'), ('🀀', '🀫'), + ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), ('🃁', '🃏'), + ('🃑', '🃵'), ('🄐', '🄮'), ('🄰', '🅫'), ('🅰', '🆬'), + ('🇦', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), ('🉐', '🉑'), + ('🉠', '🉥'), ('🌀', '🛔'), ('🛠', '🛬'), ('🛰', '🛸'), + ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), ('🠐', '🡇'), + ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), ('🤀', '🤋'), + ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), ('🦀', '🦗'), + ('🧀', '🧀'), ('🧐', '🧦'), +]; + +pub const TITLECASE_LETTER: &'static [(char, char)] = &[ + ('Dž', 'Dž'), ('Lj', 'Lj'), ('Nj', 'Nj'), ('Dz', 'Dz'), ('ᾈ', 'ᾏ'), + ('ᾘ', 'ᾟ'), ('ᾨ', 'ᾯ'), ('ᾼ', 'ᾼ'), ('ῌ', 'ῌ'), + ('ῼ', 'ῼ'), +]; + +pub const UNASSIGNED: &'static [(char, char)] = &[ + ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), + ('\u{38d}', '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), + ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), + ('\u{58b}', '\u{58c}'), ('\u{590}', '\u{590}'), ('\u{5c8}', '\u{5cf}'), + ('\u{5eb}', '\u{5ef}'), ('\u{5f5}', '\u{5ff}'), ('\u{61d}', '\u{61d}'), + ('\u{70e}', '\u{70e}'), ('\u{74b}', '\u{74c}'), ('\u{7b2}', '\u{7bf}'), + ('\u{7fb}', '\u{7ff}'), ('\u{82e}', '\u{82f}'), ('\u{83f}', '\u{83f}'), + ('\u{85c}', '\u{85d}'), ('\u{85f}', '\u{85f}'), ('\u{86b}', '\u{89f}'), + ('\u{8b5}', '\u{8b5}'), ('\u{8be}', '\u{8d3}'), ('\u{984}', '\u{984}'), + ('\u{98d}', '\u{98e}'), ('\u{991}', '\u{992}'), ('\u{9a9}', '\u{9a9}'), + ('\u{9b1}', '\u{9b1}'), ('\u{9b3}', '\u{9b5}'), ('\u{9ba}', '\u{9bb}'), + ('\u{9c5}', '\u{9c6}'), ('\u{9c9}', '\u{9ca}'), ('\u{9cf}', '\u{9d6}'), + ('\u{9d8}', '\u{9db}'), ('\u{9de}', '\u{9de}'), ('\u{9e4}', '\u{9e5}'), + ('\u{9fe}', '\u{a00}'), ('\u{a04}', '\u{a04}'), ('\u{a0b}', '\u{a0e}'), + ('\u{a11}', '\u{a12}'), ('\u{a29}', '\u{a29}'), ('\u{a31}', '\u{a31}'), + ('\u{a34}', '\u{a34}'), ('\u{a37}', '\u{a37}'), ('\u{a3a}', '\u{a3b}'), + ('\u{a3d}', '\u{a3d}'), ('\u{a43}', '\u{a46}'), ('\u{a49}', '\u{a4a}'), + ('\u{a4e}', '\u{a50}'), ('\u{a52}', '\u{a58}'), ('\u{a5d}', '\u{a5d}'), + ('\u{a5f}', '\u{a65}'), ('\u{a76}', '\u{a80}'), ('\u{a84}', '\u{a84}'), + ('\u{a8e}', '\u{a8e}'), ('\u{a92}', '\u{a92}'), ('\u{aa9}', '\u{aa9}'), + ('\u{ab1}', '\u{ab1}'), ('\u{ab4}', '\u{ab4}'), ('\u{aba}', '\u{abb}'), + ('\u{ac6}', '\u{ac6}'), ('\u{aca}', '\u{aca}'), ('\u{ace}', '\u{acf}'), + ('\u{ad1}', '\u{adf}'), ('\u{ae4}', '\u{ae5}'), ('\u{af2}', '\u{af8}'), + ('\u{b00}', '\u{b00}'), ('\u{b04}', '\u{b04}'), ('\u{b0d}', '\u{b0e}'), + ('\u{b11}', '\u{b12}'), ('\u{b29}', '\u{b29}'), ('\u{b31}', '\u{b31}'), + ('\u{b34}', '\u{b34}'), ('\u{b3a}', '\u{b3b}'), ('\u{b45}', '\u{b46}'), + ('\u{b49}', '\u{b4a}'), ('\u{b4e}', '\u{b55}'), ('\u{b58}', '\u{b5b}'), + ('\u{b5e}', '\u{b5e}'), ('\u{b64}', '\u{b65}'), ('\u{b78}', '\u{b81}'), + ('\u{b84}', '\u{b84}'), ('\u{b8b}', '\u{b8d}'), ('\u{b91}', '\u{b91}'), + ('\u{b96}', '\u{b98}'), ('\u{b9b}', '\u{b9b}'), ('\u{b9d}', '\u{b9d}'), + ('\u{ba0}', '\u{ba2}'), ('\u{ba5}', '\u{ba7}'), ('\u{bab}', '\u{bad}'), + ('\u{bba}', '\u{bbd}'), ('\u{bc3}', '\u{bc5}'), ('\u{bc9}', '\u{bc9}'), + ('\u{bce}', '\u{bcf}'), ('\u{bd1}', '\u{bd6}'), ('\u{bd8}', '\u{be5}'), + ('\u{bfb}', '\u{bff}'), ('\u{c04}', '\u{c04}'), ('\u{c0d}', '\u{c0d}'), + ('\u{c11}', '\u{c11}'), ('\u{c29}', '\u{c29}'), ('\u{c3a}', '\u{c3c}'), + ('\u{c45}', '\u{c45}'), ('\u{c49}', '\u{c49}'), ('\u{c4e}', '\u{c54}'), + ('\u{c57}', '\u{c57}'), ('\u{c5b}', '\u{c5f}'), ('\u{c64}', '\u{c65}'), + ('\u{c70}', '\u{c77}'), ('\u{c84}', '\u{c84}'), ('\u{c8d}', '\u{c8d}'), + ('\u{c91}', '\u{c91}'), ('\u{ca9}', '\u{ca9}'), ('\u{cb4}', '\u{cb4}'), + ('\u{cba}', '\u{cbb}'), ('\u{cc5}', '\u{cc5}'), ('\u{cc9}', '\u{cc9}'), + ('\u{cce}', '\u{cd4}'), ('\u{cd7}', '\u{cdd}'), ('\u{cdf}', '\u{cdf}'), + ('\u{ce4}', '\u{ce5}'), ('\u{cf0}', '\u{cf0}'), ('\u{cf3}', '\u{cff}'), + ('\u{d04}', '\u{d04}'), ('\u{d0d}', '\u{d0d}'), ('\u{d11}', '\u{d11}'), + ('\u{d45}', '\u{d45}'), ('\u{d49}', '\u{d49}'), ('\u{d50}', '\u{d53}'), + ('\u{d64}', '\u{d65}'), ('\u{d80}', '\u{d81}'), ('\u{d84}', '\u{d84}'), + ('\u{d97}', '\u{d99}'), ('\u{db2}', '\u{db2}'), ('\u{dbc}', '\u{dbc}'), + ('\u{dbe}', '\u{dbf}'), ('\u{dc7}', '\u{dc9}'), ('\u{dcb}', '\u{dce}'), + ('\u{dd5}', '\u{dd5}'), ('\u{dd7}', '\u{dd7}'), ('\u{de0}', '\u{de5}'), + ('\u{df0}', '\u{df1}'), ('\u{df5}', '\u{e00}'), ('\u{e3b}', '\u{e3e}'), + ('\u{e5c}', '\u{e80}'), ('\u{e83}', '\u{e83}'), ('\u{e85}', '\u{e86}'), + ('\u{e89}', '\u{e89}'), ('\u{e8b}', '\u{e8c}'), ('\u{e8e}', '\u{e93}'), + ('\u{e98}', '\u{e98}'), ('\u{ea0}', '\u{ea0}'), ('\u{ea4}', '\u{ea4}'), + ('\u{ea6}', '\u{ea6}'), ('\u{ea8}', '\u{ea9}'), ('\u{eac}', '\u{eac}'), + ('\u{eba}', '\u{eba}'), ('\u{ebe}', '\u{ebf}'), ('\u{ec5}', '\u{ec5}'), + ('\u{ec7}', '\u{ec7}'), ('\u{ece}', '\u{ecf}'), ('\u{eda}', '\u{edb}'), + ('\u{ee0}', '\u{eff}'), ('\u{f48}', '\u{f48}'), ('\u{f6d}', '\u{f70}'), + ('\u{f98}', '\u{f98}'), ('\u{fbd}', '\u{fbd}'), ('\u{fcd}', '\u{fcd}'), + ('\u{fdb}', '\u{fff}'), ('\u{10c6}', '\u{10c6}'), ('\u{10c8}', '\u{10cc}'), + ('\u{10ce}', '\u{10cf}'), ('\u{1249}', '\u{1249}'), + ('\u{124e}', '\u{124f}'), ('\u{1257}', '\u{1257}'), + ('\u{1259}', '\u{1259}'), ('\u{125e}', '\u{125f}'), + ('\u{1289}', '\u{1289}'), ('\u{128e}', '\u{128f}'), + ('\u{12b1}', '\u{12b1}'), ('\u{12b6}', '\u{12b7}'), + ('\u{12bf}', '\u{12bf}'), ('\u{12c1}', '\u{12c1}'), + ('\u{12c6}', '\u{12c7}'), ('\u{12d7}', '\u{12d7}'), + ('\u{1311}', '\u{1311}'), ('\u{1316}', '\u{1317}'), + ('\u{135b}', '\u{135c}'), ('\u{137d}', '\u{137f}'), + ('\u{139a}', '\u{139f}'), ('\u{13f6}', '\u{13f7}'), + ('\u{13fe}', '\u{13ff}'), ('\u{169d}', '\u{169f}'), + ('\u{16f9}', '\u{16ff}'), ('\u{170d}', '\u{170d}'), + ('\u{1715}', '\u{171f}'), ('\u{1737}', '\u{173f}'), + ('\u{1754}', '\u{175f}'), ('\u{176d}', '\u{176d}'), + ('\u{1771}', '\u{1771}'), ('\u{1774}', '\u{177f}'), + ('\u{17de}', '\u{17df}'), ('\u{17ea}', '\u{17ef}'), + ('\u{17fa}', '\u{17ff}'), ('\u{180f}', '\u{180f}'), + ('\u{181a}', '\u{181f}'), ('\u{1878}', '\u{187f}'), + ('\u{18ab}', '\u{18af}'), ('\u{18f6}', '\u{18ff}'), + ('\u{191f}', '\u{191f}'), ('\u{192c}', '\u{192f}'), + ('\u{193c}', '\u{193f}'), ('\u{1941}', '\u{1943}'), + ('\u{196e}', '\u{196f}'), ('\u{1975}', '\u{197f}'), + ('\u{19ac}', '\u{19af}'), ('\u{19ca}', '\u{19cf}'), + ('\u{19db}', '\u{19dd}'), ('\u{1a1c}', '\u{1a1d}'), + ('\u{1a5f}', '\u{1a5f}'), ('\u{1a7d}', '\u{1a7e}'), + ('\u{1a8a}', '\u{1a8f}'), ('\u{1a9a}', '\u{1a9f}'), + ('\u{1aae}', '\u{1aaf}'), ('\u{1abf}', '\u{1aff}'), + ('\u{1b4c}', '\u{1b4f}'), ('\u{1b7d}', '\u{1b7f}'), + ('\u{1bf4}', '\u{1bfb}'), ('\u{1c38}', '\u{1c3a}'), + ('\u{1c4a}', '\u{1c4c}'), ('\u{1c89}', '\u{1cbf}'), + ('\u{1cc8}', '\u{1ccf}'), ('\u{1cfa}', '\u{1cff}'), + ('\u{1dfa}', '\u{1dfa}'), ('\u{1f16}', '\u{1f17}'), + ('\u{1f1e}', '\u{1f1f}'), ('\u{1f46}', '\u{1f47}'), + ('\u{1f4e}', '\u{1f4f}'), ('\u{1f58}', '\u{1f58}'), + ('\u{1f5a}', '\u{1f5a}'), ('\u{1f5c}', '\u{1f5c}'), + ('\u{1f5e}', '\u{1f5e}'), ('\u{1f7e}', '\u{1f7f}'), + ('\u{1fb5}', '\u{1fb5}'), ('\u{1fc5}', '\u{1fc5}'), + ('\u{1fd4}', '\u{1fd5}'), ('\u{1fdc}', '\u{1fdc}'), + ('\u{1ff0}', '\u{1ff1}'), ('\u{1ff5}', '\u{1ff5}'), + ('\u{1fff}', '\u{1fff}'), ('\u{2065}', '\u{2065}'), + ('\u{2072}', '\u{2073}'), ('\u{208f}', '\u{208f}'), + ('\u{209d}', '\u{209f}'), ('\u{20c0}', '\u{20cf}'), + ('\u{20f1}', '\u{20ff}'), ('\u{218c}', '\u{218f}'), + ('\u{2427}', '\u{243f}'), ('\u{244b}', '\u{245f}'), + ('\u{2b74}', '\u{2b75}'), ('\u{2b96}', '\u{2b97}'), + ('\u{2bba}', '\u{2bbc}'), ('\u{2bc9}', '\u{2bc9}'), + ('\u{2bd3}', '\u{2beb}'), ('\u{2bf0}', '\u{2bff}'), + ('\u{2c2f}', '\u{2c2f}'), ('\u{2c5f}', '\u{2c5f}'), + ('\u{2cf4}', '\u{2cf8}'), ('\u{2d26}', '\u{2d26}'), + ('\u{2d28}', '\u{2d2c}'), ('\u{2d2e}', '\u{2d2f}'), + ('\u{2d68}', '\u{2d6e}'), ('\u{2d71}', '\u{2d7e}'), + ('\u{2d97}', '\u{2d9f}'), ('\u{2da7}', '\u{2da7}'), + ('\u{2daf}', '\u{2daf}'), ('\u{2db7}', '\u{2db7}'), + ('\u{2dbf}', '\u{2dbf}'), ('\u{2dc7}', '\u{2dc7}'), + ('\u{2dcf}', '\u{2dcf}'), ('\u{2dd7}', '\u{2dd7}'), + ('\u{2ddf}', '\u{2ddf}'), ('\u{2e4a}', '\u{2e7f}'), + ('\u{2e9a}', '\u{2e9a}'), ('\u{2ef4}', '\u{2eff}'), + ('\u{2fd6}', '\u{2fef}'), ('\u{2ffc}', '\u{2fff}'), + ('\u{3040}', '\u{3040}'), ('\u{3097}', '\u{3098}'), + ('\u{3100}', '\u{3104}'), ('\u{312f}', '\u{3130}'), + ('\u{318f}', '\u{318f}'), ('\u{31bb}', '\u{31bf}'), + ('\u{31e4}', '\u{31ef}'), ('\u{321f}', '\u{321f}'), + ('\u{32ff}', '\u{32ff}'), ('\u{4db6}', '\u{4dbf}'), + ('\u{9feb}', '\u{9fff}'), ('\u{a48d}', '\u{a48f}'), + ('\u{a4c7}', '\u{a4cf}'), ('\u{a62c}', '\u{a63f}'), + ('\u{a6f8}', '\u{a6ff}'), ('\u{a7af}', '\u{a7af}'), + ('\u{a7b8}', '\u{a7f6}'), ('\u{a82c}', '\u{a82f}'), + ('\u{a83a}', '\u{a83f}'), ('\u{a878}', '\u{a87f}'), + ('\u{a8c6}', '\u{a8cd}'), ('\u{a8da}', '\u{a8df}'), + ('\u{a8fe}', '\u{a8ff}'), ('\u{a954}', '\u{a95e}'), + ('\u{a97d}', '\u{a97f}'), ('\u{a9ce}', '\u{a9ce}'), + ('\u{a9da}', '\u{a9dd}'), ('\u{a9ff}', '\u{a9ff}'), + ('\u{aa37}', '\u{aa3f}'), ('\u{aa4e}', '\u{aa4f}'), + ('\u{aa5a}', '\u{aa5b}'), ('\u{aac3}', '\u{aada}'), + ('\u{aaf7}', '\u{ab00}'), ('\u{ab07}', '\u{ab08}'), + ('\u{ab0f}', '\u{ab10}'), ('\u{ab17}', '\u{ab1f}'), + ('\u{ab27}', '\u{ab27}'), ('\u{ab2f}', '\u{ab2f}'), + ('\u{ab66}', '\u{ab6f}'), ('\u{abee}', '\u{abef}'), + ('\u{abfa}', '\u{abff}'), ('\u{d7a4}', '\u{d7af}'), + ('\u{d7c7}', '\u{d7ca}'), ('\u{d7fc}', '\u{d7ff}'), + ('\u{fa6e}', '\u{fa6f}'), ('\u{fada}', '\u{faff}'), + ('\u{fb07}', '\u{fb12}'), ('\u{fb18}', '\u{fb1c}'), + ('\u{fb37}', '\u{fb37}'), ('\u{fb3d}', '\u{fb3d}'), + ('\u{fb3f}', '\u{fb3f}'), ('\u{fb42}', '\u{fb42}'), + ('\u{fb45}', '\u{fb45}'), ('\u{fbc2}', '\u{fbd2}'), + ('\u{fd40}', '\u{fd4f}'), ('\u{fd90}', '\u{fd91}'), + ('\u{fdc8}', '\u{fdef}'), ('\u{fdfe}', '\u{fdff}'), + ('\u{fe1a}', '\u{fe1f}'), ('\u{fe53}', '\u{fe53}'), + ('\u{fe67}', '\u{fe67}'), ('\u{fe6c}', '\u{fe6f}'), + ('\u{fe75}', '\u{fe75}'), ('\u{fefd}', '\u{fefe}'), + ('\u{ff00}', '\u{ff00}'), ('\u{ffbf}', '\u{ffc1}'), + ('\u{ffc8}', '\u{ffc9}'), ('\u{ffd0}', '\u{ffd1}'), + ('\u{ffd8}', '\u{ffd9}'), ('\u{ffdd}', '\u{ffdf}'), + ('\u{ffe7}', '\u{ffe7}'), ('\u{ffef}', '\u{fff8}'), + ('\u{fffe}', '\u{ffff}'), ('\u{1000c}', '\u{1000c}'), + ('\u{10027}', '\u{10027}'), ('\u{1003b}', '\u{1003b}'), + ('\u{1003e}', '\u{1003e}'), ('\u{1004e}', '\u{1004f}'), + ('\u{1005e}', '\u{1007f}'), ('\u{100fb}', '\u{100ff}'), + ('\u{10103}', '\u{10106}'), ('\u{10134}', '\u{10136}'), + ('\u{1018f}', '\u{1018f}'), ('\u{1019c}', '\u{1019f}'), + ('\u{101a1}', '\u{101cf}'), ('\u{101fe}', '\u{1027f}'), + ('\u{1029d}', '\u{1029f}'), ('\u{102d1}', '\u{102df}'), + ('\u{102fc}', '\u{102ff}'), ('\u{10324}', '\u{1032c}'), + ('\u{1034b}', '\u{1034f}'), ('\u{1037b}', '\u{1037f}'), + ('\u{1039e}', '\u{1039e}'), ('\u{103c4}', '\u{103c7}'), + ('\u{103d6}', '\u{103ff}'), ('\u{1049e}', '\u{1049f}'), + ('\u{104aa}', '\u{104af}'), ('\u{104d4}', '\u{104d7}'), + ('\u{104fc}', '\u{104ff}'), ('\u{10528}', '\u{1052f}'), + ('\u{10564}', '\u{1056e}'), ('\u{10570}', '\u{105ff}'), + ('\u{10737}', '\u{1073f}'), ('\u{10756}', '\u{1075f}'), + ('\u{10768}', '\u{107ff}'), ('\u{10806}', '\u{10807}'), + ('\u{10809}', '\u{10809}'), ('\u{10836}', '\u{10836}'), + ('\u{10839}', '\u{1083b}'), ('\u{1083d}', '\u{1083e}'), + ('\u{10856}', '\u{10856}'), ('\u{1089f}', '\u{108a6}'), + ('\u{108b0}', '\u{108df}'), ('\u{108f3}', '\u{108f3}'), + ('\u{108f6}', '\u{108fa}'), ('\u{1091c}', '\u{1091e}'), + ('\u{1093a}', '\u{1093e}'), ('\u{10940}', '\u{1097f}'), + ('\u{109b8}', '\u{109bb}'), ('\u{109d0}', '\u{109d1}'), + ('\u{10a04}', '\u{10a04}'), ('\u{10a07}', '\u{10a0b}'), + ('\u{10a14}', '\u{10a14}'), ('\u{10a18}', '\u{10a18}'), + ('\u{10a34}', '\u{10a37}'), ('\u{10a3b}', '\u{10a3e}'), + ('\u{10a48}', '\u{10a4f}'), ('\u{10a59}', '\u{10a5f}'), + ('\u{10aa0}', '\u{10abf}'), ('\u{10ae7}', '\u{10aea}'), + ('\u{10af7}', '\u{10aff}'), ('\u{10b36}', '\u{10b38}'), + ('\u{10b56}', '\u{10b57}'), ('\u{10b73}', '\u{10b77}'), + ('\u{10b92}', '\u{10b98}'), ('\u{10b9d}', '\u{10ba8}'), + ('\u{10bb0}', '\u{10bff}'), ('\u{10c49}', '\u{10c7f}'), + ('\u{10cb3}', '\u{10cbf}'), ('\u{10cf3}', '\u{10cf9}'), + ('\u{10d00}', '\u{10e5f}'), ('\u{10e7f}', '\u{10fff}'), + ('\u{1104e}', '\u{11051}'), ('\u{11070}', '\u{1107e}'), + ('\u{110c2}', '\u{110cf}'), ('\u{110e9}', '\u{110ef}'), + ('\u{110fa}', '\u{110ff}'), ('\u{11135}', '\u{11135}'), + ('\u{11144}', '\u{1114f}'), ('\u{11177}', '\u{1117f}'), + ('\u{111ce}', '\u{111cf}'), ('\u{111e0}', '\u{111e0}'), + ('\u{111f5}', '\u{111ff}'), ('\u{11212}', '\u{11212}'), + ('\u{1123f}', '\u{1127f}'), ('\u{11287}', '\u{11287}'), + ('\u{11289}', '\u{11289}'), ('\u{1128e}', '\u{1128e}'), + ('\u{1129e}', '\u{1129e}'), ('\u{112aa}', '\u{112af}'), + ('\u{112eb}', '\u{112ef}'), ('\u{112fa}', '\u{112ff}'), + ('\u{11304}', '\u{11304}'), ('\u{1130d}', '\u{1130e}'), + ('\u{11311}', '\u{11312}'), ('\u{11329}', '\u{11329}'), + ('\u{11331}', '\u{11331}'), ('\u{11334}', '\u{11334}'), + ('\u{1133a}', '\u{1133b}'), ('\u{11345}', '\u{11346}'), + ('\u{11349}', '\u{1134a}'), ('\u{1134e}', '\u{1134f}'), + ('\u{11351}', '\u{11356}'), ('\u{11358}', '\u{1135c}'), + ('\u{11364}', '\u{11365}'), ('\u{1136d}', '\u{1136f}'), + ('\u{11375}', '\u{113ff}'), ('\u{1145a}', '\u{1145a}'), + ('\u{1145c}', '\u{1145c}'), ('\u{1145e}', '\u{1147f}'), + ('\u{114c8}', '\u{114cf}'), ('\u{114da}', '\u{1157f}'), + ('\u{115b6}', '\u{115b7}'), ('\u{115de}', '\u{115ff}'), + ('\u{11645}', '\u{1164f}'), ('\u{1165a}', '\u{1165f}'), + ('\u{1166d}', '\u{1167f}'), ('\u{116b8}', '\u{116bf}'), + ('\u{116ca}', '\u{116ff}'), ('\u{1171a}', '\u{1171c}'), + ('\u{1172c}', '\u{1172f}'), ('\u{11740}', '\u{1189f}'), + ('\u{118f3}', '\u{118fe}'), ('\u{11900}', '\u{119ff}'), + ('\u{11a48}', '\u{11a4f}'), ('\u{11a84}', '\u{11a85}'), + ('\u{11a9d}', '\u{11a9d}'), ('\u{11aa3}', '\u{11abf}'), + ('\u{11af9}', '\u{11bff}'), ('\u{11c09}', '\u{11c09}'), + ('\u{11c37}', '\u{11c37}'), ('\u{11c46}', '\u{11c4f}'), + ('\u{11c6d}', '\u{11c6f}'), ('\u{11c90}', '\u{11c91}'), + ('\u{11ca8}', '\u{11ca8}'), ('\u{11cb7}', '\u{11cff}'), + ('\u{11d07}', '\u{11d07}'), ('\u{11d0a}', '\u{11d0a}'), + ('\u{11d37}', '\u{11d39}'), ('\u{11d3b}', '\u{11d3b}'), + ('\u{11d3e}', '\u{11d3e}'), ('\u{11d48}', '\u{11d4f}'), + ('\u{11d5a}', '\u{11fff}'), ('\u{1239a}', '\u{123ff}'), + ('\u{1246f}', '\u{1246f}'), ('\u{12475}', '\u{1247f}'), + ('\u{12544}', '\u{12fff}'), ('\u{1342f}', '\u{143ff}'), + ('\u{14647}', '\u{167ff}'), ('\u{16a39}', '\u{16a3f}'), + ('\u{16a5f}', '\u{16a5f}'), ('\u{16a6a}', '\u{16a6d}'), + ('\u{16a70}', '\u{16acf}'), ('\u{16aee}', '\u{16aef}'), + ('\u{16af6}', '\u{16aff}'), ('\u{16b46}', '\u{16b4f}'), + ('\u{16b5a}', '\u{16b5a}'), ('\u{16b62}', '\u{16b62}'), + ('\u{16b78}', '\u{16b7c}'), ('\u{16b90}', '\u{16eff}'), + ('\u{16f45}', '\u{16f4f}'), ('\u{16f7f}', '\u{16f8e}'), + ('\u{16fa0}', '\u{16fdf}'), ('\u{16fe2}', '\u{16fff}'), + ('\u{187ed}', '\u{187ff}'), ('\u{18af3}', '\u{1afff}'), + ('\u{1b11f}', '\u{1b16f}'), ('\u{1b2fc}', '\u{1bbff}'), + ('\u{1bc6b}', '\u{1bc6f}'), ('\u{1bc7d}', '\u{1bc7f}'), + ('\u{1bc89}', '\u{1bc8f}'), ('\u{1bc9a}', '\u{1bc9b}'), + ('\u{1bca4}', '\u{1cfff}'), ('\u{1d0f6}', '\u{1d0ff}'), + ('\u{1d127}', '\u{1d128}'), ('\u{1d1e9}', '\u{1d1ff}'), + ('\u{1d246}', '\u{1d2ff}'), ('\u{1d357}', '\u{1d35f}'), + ('\u{1d372}', '\u{1d3ff}'), ('\u{1d455}', '\u{1d455}'), + ('\u{1d49d}', '\u{1d49d}'), ('\u{1d4a0}', '\u{1d4a1}'), + ('\u{1d4a3}', '\u{1d4a4}'), ('\u{1d4a7}', '\u{1d4a8}'), + ('\u{1d4ad}', '\u{1d4ad}'), ('\u{1d4ba}', '\u{1d4ba}'), + ('\u{1d4bc}', '\u{1d4bc}'), ('\u{1d4c4}', '\u{1d4c4}'), + ('\u{1d506}', '\u{1d506}'), ('\u{1d50b}', '\u{1d50c}'), + ('\u{1d515}', '\u{1d515}'), ('\u{1d51d}', '\u{1d51d}'), + ('\u{1d53a}', '\u{1d53a}'), ('\u{1d53f}', '\u{1d53f}'), + ('\u{1d545}', '\u{1d545}'), ('\u{1d547}', '\u{1d549}'), + ('\u{1d551}', '\u{1d551}'), ('\u{1d6a6}', '\u{1d6a7}'), + ('\u{1d7cc}', '\u{1d7cd}'), ('\u{1da8c}', '\u{1da9a}'), + ('\u{1daa0}', '\u{1daa0}'), ('\u{1dab0}', '\u{1dfff}'), + ('\u{1e007}', '\u{1e007}'), ('\u{1e019}', '\u{1e01a}'), + ('\u{1e022}', '\u{1e022}'), ('\u{1e025}', '\u{1e025}'), + ('\u{1e02b}', '\u{1e7ff}'), ('\u{1e8c5}', '\u{1e8c6}'), + ('\u{1e8d7}', '\u{1e8ff}'), ('\u{1e94b}', '\u{1e94f}'), + ('\u{1e95a}', '\u{1e95d}'), ('\u{1e960}', '\u{1edff}'), + ('\u{1ee04}', '\u{1ee04}'), ('\u{1ee20}', '\u{1ee20}'), + ('\u{1ee23}', '\u{1ee23}'), ('\u{1ee25}', '\u{1ee26}'), + ('\u{1ee28}', '\u{1ee28}'), ('\u{1ee33}', '\u{1ee33}'), + ('\u{1ee38}', '\u{1ee38}'), ('\u{1ee3a}', '\u{1ee3a}'), + ('\u{1ee3c}', '\u{1ee41}'), ('\u{1ee43}', '\u{1ee46}'), + ('\u{1ee48}', '\u{1ee48}'), ('\u{1ee4a}', '\u{1ee4a}'), + ('\u{1ee4c}', '\u{1ee4c}'), ('\u{1ee50}', '\u{1ee50}'), + ('\u{1ee53}', '\u{1ee53}'), ('\u{1ee55}', '\u{1ee56}'), + ('\u{1ee58}', '\u{1ee58}'), ('\u{1ee5a}', '\u{1ee5a}'), + ('\u{1ee5c}', '\u{1ee5c}'), ('\u{1ee5e}', '\u{1ee5e}'), + ('\u{1ee60}', '\u{1ee60}'), ('\u{1ee63}', '\u{1ee63}'), + ('\u{1ee65}', '\u{1ee66}'), ('\u{1ee6b}', '\u{1ee6b}'), + ('\u{1ee73}', '\u{1ee73}'), ('\u{1ee78}', '\u{1ee78}'), + ('\u{1ee7d}', '\u{1ee7d}'), ('\u{1ee7f}', '\u{1ee7f}'), + ('\u{1ee8a}', '\u{1ee8a}'), ('\u{1ee9c}', '\u{1eea0}'), + ('\u{1eea4}', '\u{1eea4}'), ('\u{1eeaa}', '\u{1eeaa}'), + ('\u{1eebc}', '\u{1eeef}'), ('\u{1eef2}', '\u{1efff}'), + ('\u{1f02c}', '\u{1f02f}'), ('\u{1f094}', '\u{1f09f}'), + ('\u{1f0af}', '\u{1f0b0}'), ('\u{1f0c0}', '\u{1f0c0}'), + ('\u{1f0d0}', '\u{1f0d0}'), ('\u{1f0f6}', '\u{1f0ff}'), + ('\u{1f10d}', '\u{1f10f}'), ('\u{1f12f}', '\u{1f12f}'), + ('\u{1f16c}', '\u{1f16f}'), ('\u{1f1ad}', '\u{1f1e5}'), + ('\u{1f203}', '\u{1f20f}'), ('\u{1f23c}', '\u{1f23f}'), + ('\u{1f249}', '\u{1f24f}'), ('\u{1f252}', '\u{1f25f}'), + ('\u{1f266}', '\u{1f2ff}'), ('\u{1f6d5}', '\u{1f6df}'), + ('\u{1f6ed}', '\u{1f6ef}'), ('\u{1f6f9}', '\u{1f6ff}'), + ('\u{1f774}', '\u{1f77f}'), ('\u{1f7d5}', '\u{1f7ff}'), + ('\u{1f80c}', '\u{1f80f}'), ('\u{1f848}', '\u{1f84f}'), + ('\u{1f85a}', '\u{1f85f}'), ('\u{1f888}', '\u{1f88f}'), + ('\u{1f8ae}', '\u{1f8ff}'), ('\u{1f90c}', '\u{1f90f}'), + ('\u{1f93f}', '\u{1f93f}'), ('\u{1f94d}', '\u{1f94f}'), + ('\u{1f96c}', '\u{1f97f}'), ('\u{1f998}', '\u{1f9bf}'), + ('\u{1f9c1}', '\u{1f9cf}'), ('\u{1f9e7}', '\u{1ffff}'), + ('\u{2a6d7}', '\u{2a6ff}'), ('\u{2b735}', '\u{2b73f}'), + ('\u{2b81e}', '\u{2b81f}'), ('\u{2cea2}', '\u{2ceaf}'), + ('\u{2ebe1}', '\u{2f7ff}'), ('\u{2fa1e}', '\u{e0000}'), + ('\u{e0002}', '\u{e001f}'), ('\u{e0080}', '\u{e00ff}'), + ('\u{e01f0}', '\u{effff}'), ('\u{ffffe}', '\u{fffff}'), + ('\u{10fffe}', '\u{10ffff}'), +]; + +pub const UPPERCASE_LETTER: &'static [(char, char)] = &[ + ('A', 'Z'), ('À', 'Ö'), ('Ø', 'Þ'), ('Ā', 'Ā'), ('Ă', 'Ă'), + ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), ('Č', 'Č'), + ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), ('Ė', 'Ė'), + ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), ('Ġ', 'Ġ'), + ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), ('Ī', 'Ī'), + ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), ('Ĵ', 'Ĵ'), + ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), ('Ŀ', 'Ŀ'), + ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), ('Ŋ', 'Ŋ'), + ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), ('Ŕ', 'Ŕ'), + ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), ('Ş', 'Ş'), + ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), ('Ũ', 'Ũ'), + ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), ('Ų', 'Ų'), + ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), ('Ž', 'Ž'), + ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), + ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), + ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), + ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), ('Ƽ', 'Ƽ'), ('DŽ', 'DŽ'), + ('LJ', 'LJ'), ('NJ', 'NJ'), ('Ǎ', 'Ǎ'), ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), + ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), + ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), + ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), ('Ǯ', 'Ǯ'), ('DZ', 'DZ'), + ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), + ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), + ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), + ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), + ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), + ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), + ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), + ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), ('Ɏ', 'Ɏ'), ('Ͱ', 'Ͱ'), + ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ώ'), ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('Ϗ', 'Ϗ'), + ('ϒ', 'ϔ'), ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), + ('Ϡ', 'Ϡ'), ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), + ('Ϫ', 'Ϫ'), ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϴ', 'ϴ'), ('Ϸ', 'Ϸ'), + ('Ϲ', 'Ϻ'), ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), + ('Ѧ', 'Ѧ'), ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), + ('Ѱ', 'Ѱ'), ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), + ('Ѻ', 'Ѻ'), ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), + ('Ҍ', 'Ҍ'), ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), + ('Җ', 'Җ'), ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), + ('Ҡ', 'Ҡ'), ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), + ('Ҫ', 'Ҫ'), ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), + ('Ҵ', 'Ҵ'), ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), + ('Ҿ', 'Ҿ'), ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), + ('Ӊ', 'Ӊ'), ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), + ('Ӕ', 'Ӕ'), ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), + ('Ӟ', 'Ӟ'), ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), + ('Ө', 'Ө'), ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), + ('Ӳ', 'Ӳ'), ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), + ('Ӽ', 'Ӽ'), ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), + ('Ԇ', 'Ԇ'), ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), + ('Ԑ', 'Ԑ'), ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), + ('Ԛ', 'Ԛ'), ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), + ('Ԥ', 'Ԥ'), ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), + ('Ԯ', 'Ԯ'), ('Ա', 'Ֆ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('Ḁ', 'Ḁ'), ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), + ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), + ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), + ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), + ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), + ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), + ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), + ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), + ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), + ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), + ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), + ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), + ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), + ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), + ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), + ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), + ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), + ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), + ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), + ('ẞ', 'ẞ'), ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), + ('Ầ', 'Ầ'), ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), + ('Ắ', 'Ắ'), ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), + ('Ặ', 'Ặ'), ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), + ('Ế', 'Ế'), ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), + ('Ệ', 'Ệ'), ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), + ('Ỏ', 'Ỏ'), ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), + ('Ỗ', 'Ỗ'), ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), + ('Ở', 'Ở'), ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), + ('Ủ', 'Ủ'), ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), + ('Ữ', 'Ữ'), ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), + ('Ỷ', 'Ỷ'), ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), + ('Ỿ', 'Ỿ'), ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), + ('Ἰ', 'Ἷ'), ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('Ᾰ', 'Ά'), + ('Ὲ', 'Ή'), ('Ῐ', 'Ί'), ('Ῠ', 'Ῥ'), ('Ὸ', 'Ώ'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℋ', 'ℍ'), ('ℐ', 'ℒ'), + ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), + ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℰ', 'ℳ'), ('ℾ', 'ℿ'), + ('ⅅ', 'ⅅ'), ('Ↄ', 'Ↄ'), ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), + ('Ɫ', 'Ɽ'), ('Ⱨ', 'Ⱨ'), ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), + ('Ɑ', 'Ɒ'), ('Ⱳ', 'Ⱳ'), ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), + ('Ⲃ', 'Ⲃ'), ('Ⲅ', 'Ⲅ'), ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), + ('Ⲋ', 'Ⲋ'), ('Ⲍ', 'Ⲍ'), ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), + ('Ⲓ', 'Ⲓ'), ('Ⲕ', 'Ⲕ'), ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), + ('Ⲛ', 'Ⲛ'), ('Ⲝ', 'Ⲝ'), ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), + ('Ⲣ', 'Ⲣ'), ('Ⲥ', 'Ⲥ'), ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), + ('Ⲫ', 'Ⲫ'), ('Ⲭ', 'Ⲭ'), ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), + ('Ⲳ', 'Ⲳ'), ('Ⲵ', 'Ⲵ'), ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), + ('Ⲻ', 'Ⲻ'), ('Ⲽ', 'Ⲽ'), ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), + ('Ⳃ', 'Ⳃ'), ('Ⳅ', 'Ⳅ'), ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), + ('Ⳋ', 'Ⳋ'), ('Ⳍ', 'Ⳍ'), ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), + ('Ⳓ', 'Ⳓ'), ('Ⳕ', 'Ⳕ'), ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), + ('Ⳛ', 'Ⳛ'), ('Ⳝ', 'Ⳝ'), ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), + ('Ⳣ', 'Ⳣ'), ('Ⳬ', 'Ⳬ'), ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), + ('Ꙁ', 'Ꙁ'), ('Ꙃ', 'Ꙃ'), ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), + ('Ꙉ', 'Ꙉ'), ('Ꙋ', 'Ꙋ'), ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), + ('Ꙑ', 'Ꙑ'), ('Ꙓ', 'Ꙓ'), ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), + ('Ꙙ', 'Ꙙ'), ('Ꙛ', 'Ꙛ'), ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), + ('Ꙡ', 'Ꙡ'), ('Ꙣ', 'Ꙣ'), ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), + ('Ꙩ', 'Ꙩ'), ('Ꙫ', 'Ꙫ'), ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), + ('Ꚃ', 'Ꚃ'), ('Ꚅ', 'Ꚅ'), ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), + ('Ꚋ', 'Ꚋ'), ('Ꚍ', 'Ꚍ'), ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), + ('Ꚓ', 'Ꚓ'), ('Ꚕ', 'Ꚕ'), ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), + ('Ꚛ', 'Ꚛ'), ('Ꜣ', 'Ꜣ'), ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), + ('Ꜩ', 'Ꜩ'), ('Ꜫ', 'Ꜫ'), ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), + ('Ꜳ', 'Ꜳ'), ('Ꜵ', 'Ꜵ'), ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), + ('Ꜻ', 'Ꜻ'), ('Ꜽ', 'Ꜽ'), ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), + ('Ꝃ', 'Ꝃ'), ('Ꝅ', 'Ꝅ'), ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), + ('Ꝋ', 'Ꝋ'), ('Ꝍ', 'Ꝍ'), ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), + ('Ꝓ', 'Ꝓ'), ('Ꝕ', 'Ꝕ'), ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), + ('Ꝛ', 'Ꝛ'), ('Ꝝ', 'Ꝝ'), ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), + ('Ꝣ', 'Ꝣ'), ('Ꝥ', 'Ꝥ'), ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), + ('Ꝫ', 'Ꝫ'), ('Ꝭ', 'Ꝭ'), ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), + ('Ꝼ', 'Ꝼ'), ('Ᵹ', 'Ꝿ'), ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), + ('Ꞅ', 'Ꞅ'), ('Ꞇ', 'Ꞇ'), ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), + ('Ꞑ', 'Ꞑ'), ('Ꞓ', 'Ꞓ'), ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), + ('Ꞛ', 'Ꞛ'), ('Ꞝ', 'Ꞝ'), ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), + ('Ꞣ', 'Ꞣ'), ('Ꞥ', 'Ꞥ'), ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), + ('Ɦ', 'Ɪ'), ('Ʞ', 'Ꞵ'), ('Ꞷ', 'Ꞷ'), ('A', 'Z'), + ('𐐀', '𐐧'), ('𐒰', '𐓓'), ('𐲀', '𐲲'), ('𑢠', '𑢿'), + ('𝐀', '𝐙'), ('𝐴', '𝑍'), ('𝑨', '𝒁'), ('𝒜', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒵'), ('𝓐', '𝓩'), ('𝔄', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔸', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕬', '𝖅'), + ('𝖠', '𝖹'), ('𝗔', '𝗭'), ('𝘈', '𝘡'), ('𝘼', '𝙕'), + ('𝙰', '𝚉'), ('𝚨', '𝛀'), ('𝛢', '𝛺'), ('𝜜', '𝜴'), + ('𝝖', '𝝮'), ('𝞐', '𝞨'), ('𝟊', '𝟊'), ('𞤀', '𞤡'), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/mod.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/mod.rs new file mode 100644 index 0000000..6c2e9e7 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/mod.rs @@ -0,0 +1,9 @@ +pub mod age; +pub mod case_folding_simple; +pub mod general_category; +pub mod perl_word; +pub mod property_bool; +pub mod property_names; +pub mod property_values; +pub mod script_extension; +pub mod script; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/perl_word.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/perl_word.rs new file mode 100644 index 0000000..d33f79a --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/perl_word.rs @@ -0,0 +1,179 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate perl-word /home/andrew/tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const PERL_WORD: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), + ('º', 'º'), ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), + ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('̀', 'ʹ'), ('Ͷ', 'ͷ'), + ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('҃', 'ԯ'), ('Ա', 'Ֆ'), + ('ՙ', 'ՙ'), ('ա', 'և'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), ('ؐ', 'ؚ'), + ('ؠ', '٩'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('۟', 'ۨ'), ('۪', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', '݊'), ('ݍ', 'ޱ'), ('߀', 'ߵ'), ('ߺ', 'ߺ'), + ('ࠀ', '࠭'), ('ࡀ', '࡛'), ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), + ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), ('ࣣ', 'ॣ'), ('०', '९'), + ('ॱ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), ('ও', 'ন'), + ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), ('়', 'ৄ'), + ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), + ('য়', 'ৣ'), ('০', 'ৱ'), ('ৼ', 'ৼ'), ('ਁ', 'ਃ'), + ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), + ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('਼', '਼'), + ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ੑ', 'ੑ'), + ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), ('ઁ', 'ઃ'), + ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), + ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), ('ે', 'ૉ'), + ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), ('૦', '૯'), + ('ૹ', '૿'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), + ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), + ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), ('ୖ', 'ୗ'), + ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୯'), ('ୱ', 'ୱ'), + ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), + ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), ('௦', '௯'), + ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), + ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), + ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), ('౦', '౯'), + ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), + ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), ('ೆ', 'ೈ'), + ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), + ('೦', '೯'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), ('അ', 'ഌ'), + ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), ('ൊ', 'ൎ'), + ('ൔ', 'ൗ'), ('ൟ', 'ൣ'), ('൦', '൯'), ('ൺ', 'ൿ'), + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), ('ා', 'ු'), + ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), ('ෲ', 'ෳ'), + ('ก', 'ฺ'), ('เ', '๎'), ('๐', '๙'), ('ກ', 'ຂ'), + ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), + ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), ('ລ', 'ລ'), + ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), ('ົ', 'ຽ'), + ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), ('໐', '໙'), + ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('༘', '༙'), ('༠', '༩'), + ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), ('༾', 'ཇ'), + ('ཉ', 'ཬ'), ('ཱ', '྄'), ('྆', 'ྗ'), ('ྙ', 'ྼ'), + ('࿆', '࿆'), ('က', '၉'), ('ၐ', 'ႝ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('፝', '፟'), + ('ᎀ', 'ᎏ'), ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), + ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), + ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), ('ᜠ', '᜴'), ('ᝀ', 'ᝓ'), + ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), ('ក', '៓'), + ('ៗ', 'ៗ'), ('ៜ', '៝'), ('០', '៩'), ('᠋', '᠍'), + ('᠐', '᠙'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), ('ᢰ', 'ᣵ'), + ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), ('᥆', 'ᥭ'), + ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧙'), + ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᪉'), + ('᪐', '᪙'), ('ᪧ', 'ᪧ'), ('᪰', '᪾'), ('ᬀ', 'ᭋ'), + ('᭐', '᭙'), ('᭫', '᭳'), ('ᮀ', '᯳'), ('ᰀ', '᰷'), + ('᱀', '᱉'), ('ᱍ', 'ᱽ'), ('ᲀ', 'ᲈ'), ('᳐', '᳒'), + ('᳔', '᳹'), ('ᴀ', '᷹'), ('᷻', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), + ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῼ'), ('\u{200c}', '\u{200d}'), ('‿', '⁀'), ('⁔', '⁔'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('⃐', '⃰'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), + ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), + ('K', 'ℭ'), ('ℯ', 'ℹ'), ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), + ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), + ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳳ'), ('ⴀ', 'ⴥ'), + ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), + ('⵿', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), + ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), + ('ⷘ', 'ⷞ'), ('ⷠ', 'ⷿ'), ('ⸯ', 'ⸯ'), ('々', '〇'), + ('〡', '〯'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゙', '゚'), ('ゝ', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), + ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), + ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), + ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘫ'), ('Ꙁ', '꙲'), ('ꙴ', '꙽'), + ('ꙿ', '꛱'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠧ'), ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣅ'), + ('꣐', '꣙'), ('꣠', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), + ('꤀', '꤭'), ('ꤰ', '꥓'), ('ꥠ', 'ꥼ'), ('ꦀ', '꧀'), + ('ꧏ', '꧙'), ('ꧠ', 'ꧾ'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), + ('꩐', '꩙'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꫂ'), ('ꫛ', 'ꫝ'), + ('ꫠ', 'ꫯ'), ('ꫲ', '꫶'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), + ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), + ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯪ'), ('꯬', '꯭'), ('꯰', '꯹'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'ﬨ'), + ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), + ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), + ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('︀', '️'), ('︠', '︯'), + ('︳', '︴'), ('﹍', '﹏'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), + ('ヲ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), + ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), + ('𐀼', '𐀽'), ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), + ('𐅀', '𐅴'), ('𐇽', '𐇽'), ('𐊀', '𐊜'), ('𐊠', '𐋐'), + ('𐋠', '𐋠'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), ('𐍐', '𐍺'), + ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐏑', '𐏕'), + ('𐐀', '𐒝'), ('𐒠', '𐒩'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), + ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), + ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), + ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), + ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐨸', '𐨺'), ('𐨿', '𐨿'), ('𐩠', '𐩼'), ('𐪀', '𐪜'), + ('𐫀', '𐫇'), ('𐫉', '𐫦'), ('𐬀', '𐬵'), ('𐭀', '𐭕'), + ('𐭠', '𐭲'), ('𐮀', '𐮑'), ('𐰀', '𐱈'), ('𐲀', '𐲲'), + ('𐳀', '𐳲'), ('𑀀', '𑁆'), ('𑁦', '𑁯'), ('𑁿', '𑂺'), + ('𑃐', '𑃨'), ('𑃰', '𑃹'), ('𑄀', '𑄴'), ('𑄶', '𑄿'), + ('𑅐', '𑅳'), ('𑅶', '𑅶'), ('𑆀', '𑇄'), ('𑇊', '𑇌'), + ('𑇐', '𑇚'), ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈷'), + ('𑈾', '𑈾'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), + ('𑌀', '𑌃'), ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), + ('𑌪', '𑌰'), ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), + ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), + ('𑍝', '𑍣'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑐀', '𑑊'), + ('𑑐', '𑑙'), ('𑒀', '𑓅'), ('𑓇', '𑓇'), ('𑓐', '𑓙'), + ('𑖀', '𑖵'), ('𑖸', '𑗀'), ('𑗘', '𑗝'), ('𑘀', '𑙀'), + ('𑙄', '𑙄'), ('𑙐', '𑙙'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), + ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜹'), ('𑢠', '𑣩'), + ('𑣿', '𑣿'), ('𑨀', '𑨾'), ('𑩇', '𑩇'), ('𑩐', '𑪃'), + ('𑪆', '𑪙'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), + ('𑰸', '𑱀'), ('𑱐', '𑱙'), ('𑱲', '𑲏'), ('𑲒', '𑲧'), + ('𑲩', '𑲶'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), + ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), + ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), + ('𖫐', '𖫭'), ('𖫰', '𖫴'), ('𖬀', '𖬶'), ('𖭀', '𖭃'), + ('𖭐', '𖭙'), ('𖭣', '𖭷'), ('𖭽', '𖮏'), ('𖼀', '𖽄'), + ('𖽐', '𖽾'), ('𖾏', '𖾟'), ('𖿠', '𖿡'), ('𗀀', '𘟬'), + ('𘠀', '𘫲'), ('𛀀', '𛄞'), ('𛅰', '𛋻'), ('𛰀', '𛱪'), + ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𛲝', '𛲞'), + ('𝅥', '𝅩'), ('𝅭', '𝅲'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), + ('𝆪', '𝆭'), ('𝉂', '𝉄'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), + ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), + ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), + ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), + ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), + ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), + ('𝟎', '𝟿'), ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), + ('𝪄', '𝪄'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), + ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), + ('𞠀', '𞣄'), ('𞣐', '𞣖'), ('𞤀', '𞥊'), ('𞥐', '𞥙'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('🄰', '🅉'), ('🅐', '🅩'), ('🅰', '🆉'), + ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), + ('𬺰', '𮯠'), ('丽', '𪘀'), ('󠄀', '󠇯'), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_bool.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_bool.rs new file mode 100644 index 0000000..ae867e3 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_bool.rs @@ -0,0 +1,2576 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-bool tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("ASCII_Hex_Digit", ASCII_HEX_DIGIT), ("Alphabetic", ALPHABETIC), + ("Bidi_Control", BIDI_CONTROL), ("Case_Ignorable", CASE_IGNORABLE), + ("Cased", CASED), ("Changes_When_Casefolded", CHANGES_WHEN_CASEFOLDED), + ("Changes_When_Casemapped", CHANGES_WHEN_CASEMAPPED), + ("Changes_When_Lowercased", CHANGES_WHEN_LOWERCASED), + ("Changes_When_Titlecased", CHANGES_WHEN_TITLECASED), + ("Changes_When_Uppercased", CHANGES_WHEN_UPPERCASED), ("Dash", DASH), + ("Default_Ignorable_Code_Point", DEFAULT_IGNORABLE_CODE_POINT), + ("Deprecated", DEPRECATED), ("Diacritic", DIACRITIC), + ("Extender", EXTENDER), ("Grapheme_Base", GRAPHEME_BASE), + ("Grapheme_Extend", GRAPHEME_EXTEND), ("Grapheme_Link", GRAPHEME_LINK), + ("Hex_Digit", HEX_DIGIT), ("Hyphen", HYPHEN), + ("IDS_Binary_Operator", IDS_BINARY_OPERATOR), + ("IDS_Trinary_Operator", IDS_TRINARY_OPERATOR), + ("ID_Continue", ID_CONTINUE), ("ID_Start", ID_START), + ("Ideographic", IDEOGRAPHIC), ("Join_Control", JOIN_CONTROL), + ("Logical_Order_Exception", LOGICAL_ORDER_EXCEPTION), + ("Lowercase", LOWERCASE), ("Math", MATH), + ("Noncharacter_Code_Point", NONCHARACTER_CODE_POINT), + ("Other_Alphabetic", OTHER_ALPHABETIC), + ("Other_Default_Ignorable_Code_Point", OTHER_DEFAULT_IGNORABLE_CODE_POINT), + ("Other_Grapheme_Extend", OTHER_GRAPHEME_EXTEND), + ("Other_ID_Continue", OTHER_ID_CONTINUE), + ("Other_ID_Start", OTHER_ID_START), ("Other_Lowercase", OTHER_LOWERCASE), + ("Other_Math", OTHER_MATH), ("Other_Uppercase", OTHER_UPPERCASE), + ("Pattern_Syntax", PATTERN_SYNTAX), + ("Pattern_White_Space", PATTERN_WHITE_SPACE), + ("Prepended_Concatenation_Mark", PREPENDED_CONCATENATION_MARK), + ("Quotation_Mark", QUOTATION_MARK), ("Radical", RADICAL), + ("Regional_Indicator", REGIONAL_INDICATOR), + ("Sentence_Terminal", SENTENCE_TERMINAL), ("Soft_Dotted", SOFT_DOTTED), + ("Terminal_Punctuation", TERMINAL_PUNCTUATION), + ("Unified_Ideograph", UNIFIED_IDEOGRAPH), ("Uppercase", UPPERCASE), + ("Variation_Selector", VARIATION_SELECTOR), ("White_Space", WHITE_SPACE), + ("XID_Continue", XID_CONTINUE), ("XID_Start", XID_START), +]; + +pub const ASCII_HEX_DIGIT: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'F'), ('a', 'f'), +]; + +pub const ALPHABETIC: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('ͅ', 'ͅ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), + ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), + ('ՙ', 'ՙ'), ('ա', 'և'), ('ְ', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), ('ؐ', 'ؚ'), + ('ؠ', 'ٗ'), ('ٙ', 'ٟ'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('ۡ', 'ۨ'), + ('ۭ', 'ۯ'), ('ۺ', 'ۼ'), ('ۿ', 'ۿ'), ('ܐ', 'ܿ'), ('ݍ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠗ'), ('ࠚ', 'ࠬ'), + ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), + ('ࣔ', 'ࣟ'), ('ࣣ', 'ࣩ'), ('ࣰ', 'ऻ'), ('ऽ', 'ौ'), + ('ॎ', 'ॐ'), ('ॕ', 'ॣ'), ('ॱ', 'ঃ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৌ'), + ('ৎ', 'ৎ'), ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), ('য়', 'ৣ'), + ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', 'ੌ'), ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੰ', 'ੵ'), ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), + ('ઓ', 'ન'), ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), + ('ઽ', 'ૅ'), ('ે', 'ૉ'), ('ો', 'ૌ'), ('ૐ', 'ૐ'), + ('ૠ', 'ૣ'), ('ૹ', 'ૼ'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ୄ'), ('େ', 'ୈ'), ('ୋ', 'ୌ'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('ୱ', 'ୱ'), + ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), + ('ொ', 'ௌ'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), ('ఀ', 'ః'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ౄ'), ('ె', 'ై'), ('ొ', 'ౌ'), ('ౕ', 'ౖ'), + ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('ಽ', 'ೄ'), ('ೆ', 'ೈ'), ('ೊ', 'ೌ'), ('ೕ', 'ೖ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), ('ഽ', 'ൄ'), + ('െ', 'ൈ'), ('ൊ', 'ൌ'), ('ൎ', 'ൎ'), ('ൔ', 'ൗ'), + ('ൟ', 'ൣ'), ('ൺ', 'ൿ'), ('ං', 'ඃ'), ('අ', 'ඖ'), + ('ක', 'න'), ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('ෲ', 'ෳ'), + ('ก', 'ฺ'), ('เ', 'ๆ'), ('ํ', 'ํ'), ('ກ', 'ຂ'), + ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), + ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), ('ລ', 'ລ'), + ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), ('ົ', 'ຽ'), + ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('ໍ', 'ໍ'), ('ໜ', 'ໟ'), + ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', 'ཱྀ'), + ('ྈ', 'ྗ'), ('ྙ', 'ྼ'), ('က', 'ံ'), ('း', 'း'), + ('ျ', 'ဿ'), ('ၐ', 'ၢ'), ('ၥ', 'ၨ'), ('ၮ', 'ႆ'), + ('ႎ', 'ႎ'), ('ႜ', 'ႝ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), + ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኈ'), + ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), + ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), ('ዘ', 'ጐ'), + ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('፟', '፟'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜓ'), ('ᜠ', 'ᜳ'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), ('ក', 'ឳ'), ('ា', 'ៈ'), + ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), + ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', 'ᤸ'), + ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), + ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), ('ᩡ', 'ᩴ'), ('ᪧ', 'ᪧ'), + ('ᬀ', 'ᬳ'), ('ᬵ', 'ᭃ'), ('ᭅ', 'ᭋ'), ('ᮀ', 'ᮩ'), + ('ᮬ', 'ᮯ'), ('ᮺ', 'ᯥ'), ('ᯧ', 'ᯱ'), ('ᰀ', 'ᰵ'), + ('ᱍ', 'ᱏ'), ('ᱚ', 'ᱽ'), ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), + ('ᳮ', 'ᳳ'), ('ᳵ', 'ᳶ'), ('ᴀ', 'ᶿ'), ('ᷧ', 'ᷴ'), + ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), + ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℯ', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), + ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), + ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), + ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), + ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), + ('ⷠ', 'ⷿ'), ('ⸯ', 'ⸯ'), ('々', '〇'), ('〡', '〩'), + ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), ('ゝ', 'ゟ'), + ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), + ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), ('一', '鿪'), + ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘟ'), + ('ꘪ', 'ꘫ'), ('Ꙁ', 'ꙮ'), ('ꙴ', 'ꙻ'), ('ꙿ', 'ꛯ'), + ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), ('ꠌ', 'ꠧ'), + ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣃ'), ('ꣅ', 'ꣅ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤪ'), ('ꤰ', 'ꥒ'), + ('ꥠ', 'ꥼ'), ('ꦀ', 'ꦲ'), ('ꦴ', 'ꦿ'), ('ꧏ', 'ꧏ'), + ('ꧠ', 'ꧤ'), ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨶ'), + ('ꩀ', 'ꩍ'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪾ'), + ('ꫀ', 'ꫀ'), ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫯ'), + ('ꫲ', 'ꫵ'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), + ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꯪ'), ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), + ('豈', '舘'), ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), + ('יִ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('A', 'Z'), ('a', 'z'), ('ヲ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), + ('𐍐', '𐍺'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), + ('𐏑', '𐏕'), ('𐐀', '𐒝'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), + ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), + ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), + ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), + ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀀', '𑁅'), + ('𑂂', '𑂸'), ('𑃐', '𑃨'), ('𑄀', '𑄲'), ('𑅐', '𑅲'), + ('𑅶', '𑅶'), ('𑆀', '𑆿'), ('𑇁', '𑇄'), ('𑇚', '𑇚'), + ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈴'), ('𑈷', '𑈷'), + ('𑈾', '𑈾'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋨'), ('𑌀', '𑌃'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌽', '𑍄'), ('𑍇', '𑍈'), + ('𑍋', '𑍌'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), + ('𑐀', '𑑁'), ('𑑃', '𑑅'), ('𑑇', '𑑊'), ('𑒀', '𑓁'), + ('𑓄', '𑓅'), ('𑓇', '𑓇'), ('𑖀', '𑖵'), ('𑖸', '𑖾'), + ('𑗘', '𑗝'), ('𑘀', '𑘾'), ('𑙀', '𑙀'), ('𑙄', '𑙄'), + ('𑚀', '𑚵'), ('𑜀', '𑜙'), ('𑜝', '𑜪'), ('𑢠', '𑣟'), + ('𑣿', '𑣿'), ('𑨀', '𑨲'), ('𑨵', '𑨾'), ('𑩐', '𑪃'), + ('𑪆', '𑪗'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), + ('𑰸', '𑰾'), ('𑱀', '𑱀'), ('𑱲', '𑲏'), ('𑲒', '𑲧'), + ('𑲩', '𑲶'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), + ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵁'), ('𑵃', '𑵃'), + ('𑵆', '𑵇'), ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), + ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), + ('𖫐', '𖫭'), ('𖬀', '𖬶'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𛲞', '𛲞'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), + ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), + ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), + ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), + ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), + ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), + ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), + ('𞀦', '𞀪'), ('𞠀', '𞣄'), ('𞤀', '𞥃'), ('𞥇', '𞥇'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('🄰', '🅉'), ('🅐', '🅩'), ('🅰', '🆉'), + ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), + ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const BIDI_CONTROL: &'static [(char, char)] = &[ + ('\u{61c}', '\u{61c}'), ('\u{200e}', '\u{200f}'), ('\u{202a}', '\u{202e}'), + ('\u{2066}', '\u{2069}'), +]; + +pub const CASE_IGNORABLE: &'static [(char, char)] = &[ + ('\'', '\''), ('.', '.'), (':', ':'), ('^', '^'), ('`', '`'), ('¨', '¨'), + ('\u{ad}', '\u{ad}'), ('¯', '¯'), ('´', '´'), ('·', '¸'), + ('ʰ', 'ͯ'), ('ʹ', '͵'), ('ͺ', 'ͺ'), ('΄', '΅'), ('·', '·'), + ('҃', '҉'), ('ՙ', 'ՙ'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('״', '״'), ('\u{600}', '\u{605}'), + ('ؐ', 'ؚ'), ('\u{61c}', '\u{61c}'), ('ـ', 'ـ'), ('ً', 'ٟ'), + ('ٰ', 'ٰ'), ('ۖ', '\u{6dd}'), ('۟', 'ۨ'), ('۪', 'ۭ'), + ('\u{70f}', '\u{70f}'), ('ܑ', 'ܑ'), ('ܰ', '݊'), ('ަ', 'ް'), + ('߫', 'ߵ'), ('ߺ', 'ߺ'), ('ࠖ', '࠭'), ('࡙', '࡛'), ('ࣔ', 'ं'), + ('ऺ', 'ऺ'), ('़', '़'), ('ु', 'ै'), ('्', '्'), + ('॑', 'ॗ'), ('ॢ', 'ॣ'), ('ॱ', 'ॱ'), ('ঁ', 'ঁ'), + ('়', '়'), ('ু', 'ৄ'), ('্', '্'), ('ৢ', 'ৣ'), + ('ਁ', 'ਂ'), ('਼', '਼'), ('ੁ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), + ('ઁ', 'ં'), ('઼', '઼'), ('ુ', 'ૅ'), ('ે', 'ૈ'), + ('્', '્'), ('ૢ', 'ૣ'), ('ૺ', '૿'), ('ଁ', 'ଁ'), + ('଼', '଼'), ('ି', 'ି'), ('ୁ', 'ୄ'), ('୍', '୍'), + ('ୖ', 'ୖ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ீ', 'ீ'), + ('்', '்'), ('ఀ', 'ఀ'), ('ా', 'ీ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౢ', 'ౣ'), ('ಁ', 'ಁ'), + ('಼', '಼'), ('ಿ', 'ಿ'), ('ೆ', 'ೆ'), ('ೌ', '್'), + ('ೢ', 'ೣ'), ('ഀ', 'ഁ'), ('഻', '഼'), ('ു', 'ൄ'), + ('്', '്'), ('ൢ', 'ൣ'), ('්', '්'), ('ි', 'ු'), + ('ූ', 'ූ'), ('ั', 'ั'), ('ิ', 'ฺ'), ('ๆ', '๎'), + ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), ('ໆ', 'ໆ'), + ('່', 'ໍ'), ('༘', '༙'), ('༵', '༵'), ('༷', '༷'), + ('༹', '༹'), ('ཱ', 'ཾ'), ('ྀ', '྄'), ('྆', '྇'), + ('ྍ', 'ྗ'), ('ྙ', 'ྼ'), ('࿆', '࿆'), ('ိ', 'ူ'), + ('ဲ', '့'), ('္', '်'), ('ွ', 'ှ'), ('ၘ', 'ၙ'), + ('ၞ', 'ၠ'), ('ၱ', 'ၴ'), ('ႂ', 'ႂ'), ('ႅ', 'ႆ'), + ('ႍ', 'ႍ'), ('ႝ', 'ႝ'), ('ჼ', 'ჼ'), ('፝', '፟'), + ('ᜒ', '᜔'), ('ᜲ', '᜴'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), + ('឴', '឵'), ('ិ', 'ួ'), ('ំ', 'ំ'), ('៉', '៓'), + ('ៗ', 'ៗ'), ('៝', '៝'), ('᠋', '\u{180e}'), ('ᡃ', 'ᡃ'), + ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤢ'), ('ᤧ', 'ᤨ'), + ('ᤲ', 'ᤲ'), ('᤹', '᤻'), ('ᨗ', 'ᨘ'), ('ᨛ', 'ᨛ'), + ('ᩖ', 'ᩖ'), ('ᩘ', 'ᩞ'), ('᩠', '᩠'), ('ᩢ', 'ᩢ'), + ('ᩥ', 'ᩬ'), ('ᩳ', '᩼'), ('᩿', '᩿'), ('ᪧ', 'ᪧ'), + ('᪰', '᪾'), ('ᬀ', 'ᬃ'), ('᬴', '᬴'), ('ᬶ', 'ᬺ'), + ('ᬼ', 'ᬼ'), ('ᭂ', 'ᭂ'), ('᭫', '᭳'), ('ᮀ', 'ᮁ'), + ('ᮢ', 'ᮥ'), ('ᮨ', 'ᮩ'), ('᮫', 'ᮭ'), ('᯦', '᯦'), + ('ᯨ', 'ᯩ'), ('ᯭ', 'ᯭ'), ('ᯯ', 'ᯱ'), ('ᰬ', 'ᰳ'), + ('ᰶ', '᰷'), ('ᱸ', 'ᱽ'), ('᳐', '᳒'), ('᳔', '᳠'), + ('᳢', '᳨'), ('᳭', '᳭'), ('᳴', '᳴'), ('᳸', '᳹'), + ('ᴬ', 'ᵪ'), ('ᵸ', 'ᵸ'), ('ᶛ', '᷹'), ('᷻', '᷿'), + ('᾽', '᾽'), ('᾿', '῁'), ('῍', '῏'), ('῝', '῟'), + ('῭', '`'), ('´', '῾'), ('\u{200b}', '\u{200f}'), ('‘', '’'), + ('․', '․'), ('‧', '‧'), ('\u{202a}', '\u{202e}'), + ('\u{2060}', '\u{2064}'), ('\u{2066}', '\u{206f}'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('⃐', '⃰'), ('ⱼ', 'ⱽ'), + ('⳯', '⳱'), ('ⵯ', 'ⵯ'), ('⵿', '⵿'), ('ⷠ', 'ⷿ'), + ('ⸯ', 'ⸯ'), ('々', '々'), ('〪', '〭'), ('〱', '〵'), + ('〻', '〻'), ('゙', 'ゞ'), ('ー', 'ヾ'), ('ꀕ', 'ꀕ'), + ('ꓸ', 'ꓽ'), ('ꘌ', 'ꘌ'), ('꙯', '꙲'), ('ꙴ', '꙽'), + ('ꙿ', 'ꙿ'), ('ꚜ', 'ꚟ'), ('꛰', '꛱'), ('꜀', '꜡'), + ('ꝰ', 'ꝰ'), ('ꞈ', '꞊'), ('ꟸ', 'ꟹ'), ('ꠂ', 'ꠂ'), + ('꠆', '꠆'), ('ꠋ', 'ꠋ'), ('ꠥ', 'ꠦ'), ('꣄', 'ꣅ'), + ('꣠', '꣱'), ('ꤦ', '꤭'), ('ꥇ', 'ꥑ'), ('ꦀ', 'ꦂ'), + ('꦳', '꦳'), ('ꦶ', 'ꦹ'), ('ꦼ', 'ꦼ'), ('ꧏ', 'ꧏ'), + ('ꧥ', 'ꧦ'), ('ꨩ', 'ꨮ'), ('ꨱ', 'ꨲ'), ('ꨵ', 'ꨶ'), + ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩌ'), ('ꩰ', 'ꩰ'), ('ꩼ', 'ꩼ'), + ('ꪰ', 'ꪰ'), ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), + ('꫁', '꫁'), ('ꫝ', 'ꫝ'), ('ꫬ', 'ꫭ'), ('ꫳ', 'ꫴ'), + ('꫶', '꫶'), ('꭛', 'ꭟ'), ('ꯥ', 'ꯥ'), ('ꯨ', 'ꯨ'), + ('꯭', '꯭'), ('ﬞ', 'ﬞ'), ('﮲', '﯁'), ('︀', '️'), + ('︓', '︓'), ('︠', '︯'), ('﹒', '﹒'), ('﹕', '﹕'), + ('\u{feff}', '\u{feff}'), (''', '''), ('.', '.'), (':', ':'), + ('^', '^'), ('`', '`'), ('ー', 'ー'), ('゙', '゚'), + (' ̄', ' ̄'), ('\u{fff9}', '\u{fffb}'), ('𐇽', '𐇽'), + ('𐋠', '𐋠'), ('𐍶', '𐍺'), ('𐨁', '𐨃'), ('𐨅', '𐨆'), + ('𐨌', '𐨏'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), ('𐫥', '𐫦'), + ('𑀁', '𑀁'), ('𑀸', '𑁆'), ('𑁿', '𑂁'), ('𑂳', '𑂶'), + ('𑂹', '𑂺'), ('\u{110bd}', '\u{110bd}'), ('𑄀', '𑄂'), + ('𑄧', '𑄫'), ('𑄭', '𑄴'), ('𑅳', '𑅳'), ('𑆀', '𑆁'), + ('𑆶', '𑆾'), ('𑇊', '𑇌'), ('𑈯', '𑈱'), ('𑈴', '𑈴'), + ('𑈶', '𑈷'), ('𑈾', '𑈾'), ('𑋟', '𑋟'), ('𑋣', '𑋪'), + ('𑌀', '𑌁'), ('𑌼', '𑌼'), ('𑍀', '𑍀'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), ('𑐸', '𑐿'), ('𑑂', '𑑄'), ('𑑆', '𑑆'), + ('𑒳', '𑒸'), ('𑒺', '𑒺'), ('𑒿', '𑓀'), ('𑓂', '𑓃'), + ('𑖲', '𑖵'), ('𑖼', '𑖽'), ('𑖿', '𑗀'), ('𑗜', '𑗝'), + ('𑘳', '𑘺'), ('𑘽', '𑘽'), ('𑘿', '𑙀'), ('𑚫', '𑚫'), + ('𑚭', '𑚭'), ('𑚰', '𑚵'), ('𑚷', '𑚷'), ('𑜝', '𑜟'), + ('𑜢', '𑜥'), ('𑜧', '𑜫'), ('𑨁', '𑨆'), ('𑨉', '𑨊'), + ('𑨳', '𑨸'), ('𑨻', '𑨾'), ('𑩇', '𑩇'), ('𑩑', '𑩖'), + ('𑩙', '𑩛'), ('𑪊', '𑪖'), ('𑪘', '𑪙'), ('𑰰', '𑰶'), + ('𑰸', '𑰽'), ('𑰿', '𑰿'), ('𑲒', '𑲧'), ('𑲪', '𑲰'), + ('𑲲', '𑲳'), ('𑲵', '𑲶'), ('𑴱', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵅'), ('𑵇', '𑵇'), ('𖫰', '𖫴'), + ('𖬰', '𖬶'), ('𖭀', '𖭃'), ('𖾏', '𖾟'), ('𖿠', '𖿡'), + ('𛲝', '𛲞'), ('\u{1bca0}', '\u{1bca3}'), ('𝅧', '𝅩'), + ('\u{1d173}', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), + ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), + ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞣐', '𞣖'), + ('𞥄', '𞥊'), ('🏻', '🏿'), ('\u{e0001}', '\u{e0001}'), + ('\u{e0020}', '\u{e007f}'), ('󠄀', '󠇯'), +]; + +pub const CASED: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ƺ'), ('Ƽ', 'ƿ'), ('DŽ', 'ʓ'), + ('ʕ', 'ʸ'), ('ˀ', 'ˁ'), ('ˠ', 'ˤ'), ('ͅ', 'ͅ'), ('Ͱ', 'ͳ'), + ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ա', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᶿ'), + ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), + ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℯ', 'ℴ'), + ('ℹ', 'ℹ'), ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), + ('Ⅰ', 'ⅿ'), ('Ↄ', 'ↄ'), ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), + ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('Ꙁ', 'ꙭ'), + ('Ꚁ', 'ꚝ'), ('Ꜣ', 'ꞇ'), ('Ꞌ', 'ꞎ'), ('Ꞑ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟸ', 'ꟺ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꮿ'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('A', 'Z'), + ('a', 'z'), ('𐐀', '𐑏'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑢠', '𑣟'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), + ('𝛜', '𝛺'), ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), + ('𝝐', '𝝮'), ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), + ('𝟄', '𝟋'), ('𞤀', '𞥃'), ('🄰', '🅉'), ('🅐', '🅩'), + ('🅰', '🆉'), +]; + +pub const CHANGES_WHEN_CASEFOLDED: &'static [(char, char)] = &[ + ('A', 'Z'), ('µ', 'µ'), ('À', 'Ö'), ('Ø', 'ß'), ('Ā', 'Ā'), + ('Ă', 'Ă'), ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), + ('Č', 'Č'), ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), + ('Ė', 'Ė'), ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), + ('Ġ', 'Ġ'), ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), + ('Ī', 'Ī'), ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), + ('Ĵ', 'Ĵ'), ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), + ('Ŀ', 'Ŀ'), ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), + ('ʼn', 'Ŋ'), ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), + ('Ŕ', 'Ŕ'), ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), + ('Ş', 'Ş'), ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), + ('Ũ', 'Ũ'), ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), + ('Ų', 'Ų'), ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), + ('Ž', 'Ž'), ('ſ', 'ſ'), ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), + ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), + ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), + ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), + ('Ƽ', 'Ƽ'), ('DŽ', 'Dž'), ('LJ', 'Lj'), ('NJ', 'Nj'), ('Ǎ', 'Ǎ'), + ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), + ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), + ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), + ('Ǯ', 'Ǯ'), ('DZ', 'Dz'), ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), + ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), + ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), + ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), + ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), + ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), + ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), + ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), + ('Ɏ', 'Ɏ'), ('ͅ', 'ͅ'), ('Ͱ', 'Ͱ'), ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ώ'), + ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('ς', 'ς'), ('Ϗ', 'ϑ'), ('ϕ', 'ϖ'), + ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), ('Ϡ', 'Ϡ'), + ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), ('Ϫ', 'Ϫ'), + ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϰ', 'ϱ'), ('ϴ', 'ϵ'), ('Ϸ', 'Ϸ'), + ('Ϲ', 'Ϻ'), ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), + ('Ѧ', 'Ѧ'), ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), + ('Ѱ', 'Ѱ'), ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), + ('Ѻ', 'Ѻ'), ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), + ('Ҍ', 'Ҍ'), ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), + ('Җ', 'Җ'), ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), + ('Ҡ', 'Ҡ'), ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), + ('Ҫ', 'Ҫ'), ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), + ('Ҵ', 'Ҵ'), ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), + ('Ҿ', 'Ҿ'), ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), + ('Ӊ', 'Ӊ'), ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), + ('Ӕ', 'Ӕ'), ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), + ('Ӟ', 'Ӟ'), ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), + ('Ө', 'Ө'), ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), + ('Ӳ', 'Ӳ'), ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), + ('Ӽ', 'Ӽ'), ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), + ('Ԇ', 'Ԇ'), ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), + ('Ԑ', 'Ԑ'), ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), + ('Ԛ', 'Ԛ'), ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), + ('Ԥ', 'Ԥ'), ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), + ('Ԯ', 'Ԯ'), ('Ա', 'Ֆ'), ('և', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), + ('Ⴭ', 'Ⴭ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('Ḁ', 'Ḁ'), + ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), + ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), + ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), + ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), + ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), + ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), + ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), + ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), + ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), + ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), + ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), + ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), + ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), + ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), + ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), + ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), + ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), + ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), + ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), ('ẚ', 'ẛ'), ('ẞ', 'ẞ'), + ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), ('Ầ', 'Ầ'), + ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), ('Ắ', 'Ắ'), + ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), ('Ặ', 'Ặ'), + ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), ('Ế', 'Ế'), + ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), ('Ệ', 'Ệ'), + ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), ('Ỏ', 'Ỏ'), + ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), ('Ỗ', 'Ỗ'), + ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), ('Ở', 'Ở'), + ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), ('Ủ', 'Ủ'), + ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), ('Ữ', 'Ữ'), + ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), ('Ỷ', 'Ỷ'), + ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), ('Ỿ', 'Ỿ'), + ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), ('Ἰ', 'Ἷ'), + ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('ᾀ', 'ᾯ'), ('ᾲ', 'ᾴ'), + ('ᾷ', 'ᾼ'), ('ῂ', 'ῄ'), ('ῇ', 'ῌ'), ('Ῐ', 'Ί'), + ('Ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῷ', 'ῼ'), ('Ω', 'Ω'), + ('K', 'Å'), ('Ⅎ', 'Ⅎ'), ('Ⅰ', 'Ⅿ'), ('Ↄ', 'Ↄ'), + ('Ⓐ', 'Ⓩ'), ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), ('Ɫ', 'Ɽ'), + ('Ⱨ', 'Ⱨ'), ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), ('Ɑ', 'Ɒ'), + ('Ⱳ', 'Ⱳ'), ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), ('Ⲃ', 'Ⲃ'), + ('Ⲅ', 'Ⲅ'), ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), ('Ⲋ', 'Ⲋ'), + ('Ⲍ', 'Ⲍ'), ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), ('Ⲓ', 'Ⲓ'), + ('Ⲕ', 'Ⲕ'), ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), ('Ⲛ', 'Ⲛ'), + ('Ⲝ', 'Ⲝ'), ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), ('Ⲣ', 'Ⲣ'), + ('Ⲥ', 'Ⲥ'), ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), ('Ⲫ', 'Ⲫ'), + ('Ⲭ', 'Ⲭ'), ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), ('Ⲳ', 'Ⲳ'), + ('Ⲵ', 'Ⲵ'), ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), ('Ⲻ', 'Ⲻ'), + ('Ⲽ', 'Ⲽ'), ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), ('Ⳃ', 'Ⳃ'), + ('Ⳅ', 'Ⳅ'), ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), ('Ⳋ', 'Ⳋ'), + ('Ⳍ', 'Ⳍ'), ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), ('Ⳓ', 'Ⳓ'), + ('Ⳕ', 'Ⳕ'), ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), ('Ⳛ', 'Ⳛ'), + ('Ⳝ', 'Ⳝ'), ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), ('Ⳣ', 'Ⳣ'), + ('Ⳬ', 'Ⳬ'), ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), ('Ꙁ', 'Ꙁ'), + ('Ꙃ', 'Ꙃ'), ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), ('Ꙉ', 'Ꙉ'), + ('Ꙋ', 'Ꙋ'), ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), ('Ꙑ', 'Ꙑ'), + ('Ꙓ', 'Ꙓ'), ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), ('Ꙙ', 'Ꙙ'), + ('Ꙛ', 'Ꙛ'), ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), ('Ꙡ', 'Ꙡ'), + ('Ꙣ', 'Ꙣ'), ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), ('Ꙩ', 'Ꙩ'), + ('Ꙫ', 'Ꙫ'), ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), ('Ꚃ', 'Ꚃ'), + ('Ꚅ', 'Ꚅ'), ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), ('Ꚋ', 'Ꚋ'), + ('Ꚍ', 'Ꚍ'), ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), ('Ꚓ', 'Ꚓ'), + ('Ꚕ', 'Ꚕ'), ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), ('Ꚛ', 'Ꚛ'), + ('Ꜣ', 'Ꜣ'), ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), ('Ꜩ', 'Ꜩ'), + ('Ꜫ', 'Ꜫ'), ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), ('Ꜳ', 'Ꜳ'), + ('Ꜵ', 'Ꜵ'), ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), ('Ꜻ', 'Ꜻ'), + ('Ꜽ', 'Ꜽ'), ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), ('Ꝃ', 'Ꝃ'), + ('Ꝅ', 'Ꝅ'), ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), ('Ꝋ', 'Ꝋ'), + ('Ꝍ', 'Ꝍ'), ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), ('Ꝓ', 'Ꝓ'), + ('Ꝕ', 'Ꝕ'), ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), ('Ꝛ', 'Ꝛ'), + ('Ꝝ', 'Ꝝ'), ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), ('Ꝣ', 'Ꝣ'), + ('Ꝥ', 'Ꝥ'), ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), ('Ꝫ', 'Ꝫ'), + ('Ꝭ', 'Ꝭ'), ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), ('Ꝼ', 'Ꝼ'), + ('Ᵹ', 'Ꝿ'), ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), ('Ꞅ', 'Ꞅ'), + ('Ꞇ', 'Ꞇ'), ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), ('Ꞑ', 'Ꞑ'), + ('Ꞓ', 'Ꞓ'), ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), ('Ꞛ', 'Ꞛ'), + ('Ꞝ', 'Ꞝ'), ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), ('Ꞣ', 'Ꞣ'), + ('Ꞥ', 'Ꞥ'), ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), ('Ɦ', 'Ɪ'), + ('Ʞ', 'Ꞵ'), ('Ꞷ', 'Ꞷ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('A', 'Z'), ('𐐀', '𐐧'), ('𐒰', '𐓓'), + ('𐲀', '𐲲'), ('𑢠', '𑢿'), ('𞤀', '𞤡'), +]; + +pub const CHANGES_WHEN_CASEMAPPED: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('µ', 'µ'), ('À', 'Ö'), ('Ø', 'ö'), + ('ø', 'ķ'), ('Ĺ', 'ƌ'), ('Ǝ', 'ƚ'), ('Ɯ', 'Ʃ'), ('Ƭ', 'ƹ'), + ('Ƽ', 'ƽ'), ('ƿ', 'ƿ'), ('DŽ', 'Ƞ'), ('Ȣ', 'ȳ'), ('Ⱥ', 'ɔ'), + ('ɖ', 'ɗ'), ('ə', 'ə'), ('ɛ', 'ɜ'), ('ɠ', 'ɡ'), ('ɣ', 'ɣ'), + ('ɥ', 'ɦ'), ('ɨ', 'ɬ'), ('ɯ', 'ɯ'), ('ɱ', 'ɲ'), ('ɵ', 'ɵ'), + ('ɽ', 'ɽ'), ('ʀ', 'ʀ'), ('ʃ', 'ʃ'), ('ʇ', 'ʌ'), ('ʒ', 'ʒ'), + ('ʝ', 'ʞ'), ('ͅ', 'ͅ'), ('Ͱ', 'ͳ'), ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϑ'), ('ϕ', 'ϵ'), ('Ϸ', 'ϻ'), ('Ͻ', 'ҁ'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ա', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᵹ', 'ᵹ'), + ('ᵽ', 'ᵽ'), ('Ḁ', 'ẛ'), ('ẞ', 'ẞ'), ('Ạ', 'ἕ'), + ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), + ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), + ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), + ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), + ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('Ω', 'Ω'), ('K', 'Å'), + ('Ⅎ', 'Ⅎ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ⅿ'), ('Ↄ', 'ↄ'), + ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'Ɒ'), + ('Ⱳ', 'ⱳ'), ('Ⱶ', 'ⱶ'), ('Ȿ', 'ⳣ'), ('Ⳬ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('Ꙁ', 'ꙭ'), ('Ꚁ', 'ꚛ'), ('Ꜣ', 'ꜯ'), ('Ꜳ', 'ꝯ'), + ('Ꝺ', 'ꞇ'), ('Ꞌ', 'Ɥ'), ('Ꞑ', 'ꞓ'), ('Ꞗ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꭓ', 'ꭓ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('A', 'Z'), ('a', 'z'), ('𐐀', '𐑏'), + ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), + ('𑢠', '𑣟'), ('𞤀', '𞥃'), +]; + +pub const CHANGES_WHEN_LOWERCASED: &'static [(char, char)] = &[ + ('A', 'Z'), ('À', 'Ö'), ('Ø', 'Þ'), ('Ā', 'Ā'), ('Ă', 'Ă'), + ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), ('Č', 'Č'), + ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), ('Ė', 'Ė'), + ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), ('Ġ', 'Ġ'), + ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), ('Ī', 'Ī'), + ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), ('Ĵ', 'Ĵ'), + ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), ('Ŀ', 'Ŀ'), + ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), ('Ŋ', 'Ŋ'), + ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), ('Ŕ', 'Ŕ'), + ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), ('Ş', 'Ş'), + ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), ('Ũ', 'Ũ'), + ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), ('Ų', 'Ų'), + ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), ('Ž', 'Ž'), + ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), + ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), + ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), + ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), ('Ƽ', 'Ƽ'), ('DŽ', 'Dž'), + ('LJ', 'Lj'), ('NJ', 'Nj'), ('Ǎ', 'Ǎ'), ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), + ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), + ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), + ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), ('Ǯ', 'Ǯ'), ('DZ', 'Dz'), + ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), + ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), + ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), + ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), + ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), + ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), + ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), + ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), ('Ɏ', 'Ɏ'), ('Ͱ', 'Ͱ'), + ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ώ'), ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('Ϗ', 'Ϗ'), + ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), ('Ϡ', 'Ϡ'), + ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), ('Ϫ', 'Ϫ'), + ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϴ', 'ϴ'), ('Ϸ', 'Ϸ'), ('Ϲ', 'Ϻ'), + ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), ('Ѧ', 'Ѧ'), + ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), ('Ѱ', 'Ѱ'), + ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), ('Ѻ', 'Ѻ'), + ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), ('Ҍ', 'Ҍ'), + ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), ('Җ', 'Җ'), + ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), ('Ҡ', 'Ҡ'), + ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), ('Ҫ', 'Ҫ'), + ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), ('Ҵ', 'Ҵ'), + ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), ('Ҿ', 'Ҿ'), + ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), ('Ӊ', 'Ӊ'), + ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), ('Ӕ', 'Ӕ'), + ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), ('Ӟ', 'Ӟ'), + ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), ('Ө', 'Ө'), + ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), ('Ӳ', 'Ӳ'), + ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), ('Ӽ', 'Ӽ'), + ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), ('Ԇ', 'Ԇ'), + ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), ('Ԑ', 'Ԑ'), + ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), ('Ԛ', 'Ԛ'), + ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), ('Ԥ', 'Ԥ'), + ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), ('Ԯ', 'Ԯ'), + ('Ա', 'Ֆ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('Ḁ', 'Ḁ'), ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), + ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), + ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), + ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), + ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), + ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), + ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), + ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), + ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), + ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), + ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), + ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), + ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), + ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), + ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), + ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), + ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), + ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), + ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), + ('ẞ', 'ẞ'), ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), + ('Ầ', 'Ầ'), ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), + ('Ắ', 'Ắ'), ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), + ('Ặ', 'Ặ'), ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), + ('Ế', 'Ế'), ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), + ('Ệ', 'Ệ'), ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), + ('Ỏ', 'Ỏ'), ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), + ('Ỗ', 'Ỗ'), ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), + ('Ở', 'Ở'), ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), + ('Ủ', 'Ủ'), ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), + ('Ữ', 'Ữ'), ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), + ('Ỷ', 'Ỷ'), ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), + ('Ỿ', 'Ỿ'), ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), + ('Ἰ', 'Ἷ'), ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('ᾈ', 'ᾏ'), + ('ᾘ', 'ᾟ'), ('ᾨ', 'ᾯ'), ('Ᾰ', 'ᾼ'), ('Ὲ', 'ῌ'), + ('Ῐ', 'Ί'), ('Ῠ', 'Ῥ'), ('Ὸ', 'ῼ'), ('Ω', 'Ω'), + ('K', 'Å'), ('Ⅎ', 'Ⅎ'), ('Ⅰ', 'Ⅿ'), ('Ↄ', 'Ↄ'), + ('Ⓐ', 'Ⓩ'), ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), ('Ɫ', 'Ɽ'), + ('Ⱨ', 'Ⱨ'), ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), ('Ɑ', 'Ɒ'), + ('Ⱳ', 'Ⱳ'), ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), ('Ⲃ', 'Ⲃ'), + ('Ⲅ', 'Ⲅ'), ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), ('Ⲋ', 'Ⲋ'), + ('Ⲍ', 'Ⲍ'), ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), ('Ⲓ', 'Ⲓ'), + ('Ⲕ', 'Ⲕ'), ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), ('Ⲛ', 'Ⲛ'), + ('Ⲝ', 'Ⲝ'), ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), ('Ⲣ', 'Ⲣ'), + ('Ⲥ', 'Ⲥ'), ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), ('Ⲫ', 'Ⲫ'), + ('Ⲭ', 'Ⲭ'), ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), ('Ⲳ', 'Ⲳ'), + ('Ⲵ', 'Ⲵ'), ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), ('Ⲻ', 'Ⲻ'), + ('Ⲽ', 'Ⲽ'), ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), ('Ⳃ', 'Ⳃ'), + ('Ⳅ', 'Ⳅ'), ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), ('Ⳋ', 'Ⳋ'), + ('Ⳍ', 'Ⳍ'), ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), ('Ⳓ', 'Ⳓ'), + ('Ⳕ', 'Ⳕ'), ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), ('Ⳛ', 'Ⳛ'), + ('Ⳝ', 'Ⳝ'), ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), ('Ⳣ', 'Ⳣ'), + ('Ⳬ', 'Ⳬ'), ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), ('Ꙁ', 'Ꙁ'), + ('Ꙃ', 'Ꙃ'), ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), ('Ꙉ', 'Ꙉ'), + ('Ꙋ', 'Ꙋ'), ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), ('Ꙑ', 'Ꙑ'), + ('Ꙓ', 'Ꙓ'), ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), ('Ꙙ', 'Ꙙ'), + ('Ꙛ', 'Ꙛ'), ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), ('Ꙡ', 'Ꙡ'), + ('Ꙣ', 'Ꙣ'), ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), ('Ꙩ', 'Ꙩ'), + ('Ꙫ', 'Ꙫ'), ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), ('Ꚃ', 'Ꚃ'), + ('Ꚅ', 'Ꚅ'), ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), ('Ꚋ', 'Ꚋ'), + ('Ꚍ', 'Ꚍ'), ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), ('Ꚓ', 'Ꚓ'), + ('Ꚕ', 'Ꚕ'), ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), ('Ꚛ', 'Ꚛ'), + ('Ꜣ', 'Ꜣ'), ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), ('Ꜩ', 'Ꜩ'), + ('Ꜫ', 'Ꜫ'), ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), ('Ꜳ', 'Ꜳ'), + ('Ꜵ', 'Ꜵ'), ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), ('Ꜻ', 'Ꜻ'), + ('Ꜽ', 'Ꜽ'), ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), ('Ꝃ', 'Ꝃ'), + ('Ꝅ', 'Ꝅ'), ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), ('Ꝋ', 'Ꝋ'), + ('Ꝍ', 'Ꝍ'), ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), ('Ꝓ', 'Ꝓ'), + ('Ꝕ', 'Ꝕ'), ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), ('Ꝛ', 'Ꝛ'), + ('Ꝝ', 'Ꝝ'), ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), ('Ꝣ', 'Ꝣ'), + ('Ꝥ', 'Ꝥ'), ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), ('Ꝫ', 'Ꝫ'), + ('Ꝭ', 'Ꝭ'), ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), ('Ꝼ', 'Ꝼ'), + ('Ᵹ', 'Ꝿ'), ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), ('Ꞅ', 'Ꞅ'), + ('Ꞇ', 'Ꞇ'), ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), ('Ꞑ', 'Ꞑ'), + ('Ꞓ', 'Ꞓ'), ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), ('Ꞛ', 'Ꞛ'), + ('Ꞝ', 'Ꞝ'), ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), ('Ꞣ', 'Ꞣ'), + ('Ꞥ', 'Ꞥ'), ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), ('Ɦ', 'Ɪ'), + ('Ʞ', 'Ꞵ'), ('Ꞷ', 'Ꞷ'), ('A', 'Z'), ('𐐀', '𐐧'), + ('𐒰', '𐓓'), ('𐲀', '𐲲'), ('𑢠', '𑢿'), ('𞤀', '𞤡'), +]; + +pub const CHANGES_WHEN_TITLECASED: &'static [(char, char)] = &[ + ('a', 'z'), ('µ', 'µ'), ('ß', 'ö'), ('ø', 'ÿ'), ('ā', 'ā'), + ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), ('ĉ', 'ĉ'), ('ċ', 'ċ'), + ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), ('ē', 'ē'), ('ĕ', 'ĕ'), + ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), ('ĝ', 'ĝ'), ('ğ', 'ğ'), + ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), ('ħ', 'ħ'), ('ĩ', 'ĩ'), + ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), ('ı', 'ı'), ('ij', 'ij'), + ('ĵ', 'ĵ'), ('ķ', 'ķ'), ('ĺ', 'ĺ'), ('ļ', 'ļ'), ('ľ', 'ľ'), + ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), ('ņ', 'ņ'), ('ň', 'ʼn'), + ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), ('ő', 'ő'), ('œ', 'œ'), + ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), ('ś', 'ś'), ('ŝ', 'ŝ'), + ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), ('ť', 'ť'), ('ŧ', 'ŧ'), + ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), ('ů', 'ů'), ('ű', 'ű'), + ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), ('ź', 'ź'), ('ż', 'ż'), + ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), ('ƈ', 'ƈ'), ('ƌ', 'ƌ'), + ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƚ'), ('ƞ', 'ƞ'), ('ơ', 'ơ'), + ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), ('ƭ', 'ƭ'), ('ư', 'ư'), + ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), ('ƹ', 'ƹ'), ('ƽ', 'ƽ'), ('ƿ', 'ƿ'), + ('DŽ', 'DŽ'), ('dž', 'LJ'), ('lj', 'NJ'), ('nj', 'nj'), ('ǎ', 'ǎ'), + ('ǐ', 'ǐ'), ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), ('ǘ', 'ǘ'), + ('ǚ', 'ǚ'), ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), ('ǣ', 'ǣ'), + ('ǥ', 'ǥ'), ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), ('ǭ', 'ǭ'), + ('ǯ', 'DZ'), ('dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), ('ǻ', 'ǻ'), + ('ǽ', 'ǽ'), ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), ('ȅ', 'ȅ'), + ('ȇ', 'ȇ'), ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), ('ȏ', 'ȏ'), + ('ȑ', 'ȑ'), ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), ('ș', 'ș'), + ('ț', 'ț'), ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), + ('ȧ', 'ȧ'), ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), + ('ȱ', 'ȱ'), ('ȳ', 'ȳ'), ('ȼ', 'ȼ'), ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), + ('ɇ', 'ɇ'), ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), ('ɍ', 'ɍ'), ('ɏ', 'ɔ'), + ('ɖ', 'ɗ'), ('ə', 'ə'), ('ɛ', 'ɜ'), ('ɠ', 'ɡ'), ('ɣ', 'ɣ'), + ('ɥ', 'ɦ'), ('ɨ', 'ɬ'), ('ɯ', 'ɯ'), ('ɱ', 'ɲ'), ('ɵ', 'ɵ'), + ('ɽ', 'ɽ'), ('ʀ', 'ʀ'), ('ʃ', 'ʃ'), ('ʇ', 'ʌ'), ('ʒ', 'ʒ'), + ('ʝ', 'ʞ'), ('ͅ', 'ͅ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), + ('ͻ', 'ͽ'), ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), + ('ϙ', 'ϙ'), ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), + ('ϣ', 'ϣ'), ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), + ('ϭ', 'ϭ'), ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϻ'), + ('а', 'џ'), ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), + ('ѩ', 'ѩ'), ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), + ('ѳ', 'ѳ'), ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), + ('ѽ', 'ѽ'), ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), + ('ҏ', 'ҏ'), ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), + ('ҙ', 'ҙ'), ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), + ('ң', 'ң'), ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), + ('ҭ', 'ҭ'), ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), + ('ҷ', 'ҷ'), ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), + ('ӂ', 'ӂ'), ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), + ('ӌ', 'ӌ'), ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), + ('ӗ', 'ӗ'), ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), + ('ӡ', 'ӡ'), ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), + ('ӫ', 'ӫ'), ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), + ('ӵ', 'ӵ'), ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), + ('ӿ', 'ӿ'), ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), + ('ԉ', 'ԉ'), ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), + ('ԓ', 'ԓ'), ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), + ('ԝ', 'ԝ'), ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), + ('ԧ', 'ԧ'), ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), + ('ա', 'և'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᵹ', 'ᵹ'), + ('ᵽ', 'ᵽ'), ('ḁ', 'ḁ'), ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), + ('ḇ', 'ḇ'), ('ḉ', 'ḉ'), ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), + ('ḏ', 'ḏ'), ('ḑ', 'ḑ'), ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), + ('ḗ', 'ḗ'), ('ḙ', 'ḙ'), ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), + ('ḟ', 'ḟ'), ('ḡ', 'ḡ'), ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), + ('ḧ', 'ḧ'), ('ḩ', 'ḩ'), ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), + ('ḯ', 'ḯ'), ('ḱ', 'ḱ'), ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), + ('ḷ', 'ḷ'), ('ḹ', 'ḹ'), ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), + ('ḿ', 'ḿ'), ('ṁ', 'ṁ'), ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), + ('ṇ', 'ṇ'), ('ṉ', 'ṉ'), ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), + ('ṏ', 'ṏ'), ('ṑ', 'ṑ'), ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), + ('ṗ', 'ṗ'), ('ṙ', 'ṙ'), ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), + ('ṟ', 'ṟ'), ('ṡ', 'ṡ'), ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), + ('ṧ', 'ṧ'), ('ṩ', 'ṩ'), ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), + ('ṯ', 'ṯ'), ('ṱ', 'ṱ'), ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), + ('ṷ', 'ṷ'), ('ṹ', 'ṹ'), ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), + ('ṿ', 'ṿ'), ('ẁ', 'ẁ'), ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), + ('ẇ', 'ẇ'), ('ẉ', 'ẉ'), ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), + ('ẏ', 'ẏ'), ('ẑ', 'ẑ'), ('ẓ', 'ẓ'), ('ẕ', 'ẛ'), + ('ạ', 'ạ'), ('ả', 'ả'), ('ấ', 'ấ'), ('ầ', 'ầ'), + ('ẩ', 'ẩ'), ('ẫ', 'ẫ'), ('ậ', 'ậ'), ('ắ', 'ắ'), + ('ằ', 'ằ'), ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), ('ặ', 'ặ'), + ('ẹ', 'ẹ'), ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), ('ế', 'ế'), + ('ề', 'ề'), ('ể', 'ể'), ('ễ', 'ễ'), ('ệ', 'ệ'), + ('ỉ', 'ỉ'), ('ị', 'ị'), ('ọ', 'ọ'), ('ỏ', 'ỏ'), + ('ố', 'ố'), ('ồ', 'ồ'), ('ổ', 'ổ'), ('ỗ', 'ỗ'), + ('ộ', 'ộ'), ('ớ', 'ớ'), ('ờ', 'ờ'), ('ở', 'ở'), + ('ỡ', 'ỡ'), ('ợ', 'ợ'), ('ụ', 'ụ'), ('ủ', 'ủ'), + ('ứ', 'ứ'), ('ừ', 'ừ'), ('ử', 'ử'), ('ữ', 'ữ'), + ('ự', 'ự'), ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), ('ỷ', 'ỷ'), + ('ỹ', 'ỹ'), ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), ('ỿ', 'ἇ'), + ('ἐ', 'ἕ'), ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), ('ὀ', 'ὅ'), + ('ὐ', 'ὗ'), ('ὠ', 'ὧ'), ('ὰ', 'ώ'), ('ᾀ', 'ᾇ'), + ('ᾐ', 'ᾗ'), ('ᾠ', 'ᾧ'), ('ᾰ', 'ᾴ'), ('ᾶ', 'ᾷ'), + ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), ('ῐ', 'ΐ'), + ('ῖ', 'ῗ'), ('ῠ', 'ῧ'), ('ῲ', 'ῴ'), ('ῶ', 'ῷ'), + ('ⅎ', 'ⅎ'), ('ⅰ', 'ⅿ'), ('ↄ', 'ↄ'), ('ⓐ', 'ⓩ'), + ('ⰰ', 'ⱞ'), ('ⱡ', 'ⱡ'), ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), + ('ⱪ', 'ⱪ'), ('ⱬ', 'ⱬ'), ('ⱳ', 'ⱳ'), ('ⱶ', 'ⱶ'), + ('ⲁ', 'ⲁ'), ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), + ('ⲉ', 'ⲉ'), ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), + ('ⲑ', 'ⲑ'), ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), + ('ⲙ', 'ⲙ'), ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), + ('ⲡ', 'ⲡ'), ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), + ('ⲩ', 'ⲩ'), ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), + ('ⲱ', 'ⲱ'), ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), + ('ⲹ', 'ⲹ'), ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), + ('ⳁ', 'ⳁ'), ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), + ('ⳉ', 'ⳉ'), ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), + ('ⳑ', 'ⳑ'), ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), + ('ⳙ', 'ⳙ'), ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), + ('ⳡ', 'ⳡ'), ('ⳣ', 'ⳣ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), + ('ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ꙁ', 'ꙁ'), ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), + ('ꙉ', 'ꙉ'), ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), + ('ꙑ', 'ꙑ'), ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), + ('ꙙ', 'ꙙ'), ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), + ('ꙡ', 'ꙡ'), ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), + ('ꙩ', 'ꙩ'), ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), + ('ꚃ', 'ꚃ'), ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), + ('ꚋ', 'ꚋ'), ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), + ('ꚓ', 'ꚓ'), ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), + ('ꚛ', 'ꚛ'), ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), + ('ꜩ', 'ꜩ'), ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜯ'), + ('ꜳ', 'ꜳ'), ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), + ('ꜻ', 'ꜻ'), ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), + ('ꝃ', 'ꝃ'), ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), + ('ꝋ', 'ꝋ'), ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), + ('ꝓ', 'ꝓ'), ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), + ('ꝛ', 'ꝛ'), ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), + ('ꝣ', 'ꝣ'), ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), + ('ꝫ', 'ꝫ'), ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝯ'), ('ꝺ', 'ꝺ'), + ('ꝼ', 'ꝼ'), ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), ('ꞃ', 'ꞃ'), + ('ꞅ', 'ꞅ'), ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), ('ꞑ', 'ꞑ'), + ('ꞓ', 'ꞓ'), ('ꞗ', 'ꞗ'), ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), + ('ꞝ', 'ꞝ'), ('ꞟ', 'ꞟ'), ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), + ('ꞥ', 'ꞥ'), ('ꞧ', 'ꞧ'), ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), + ('ꞷ', 'ꞷ'), ('ꭓ', 'ꭓ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('a', 'z'), ('𐐨', '𐑏'), ('𐓘', '𐓻'), + ('𐳀', '𐳲'), ('𑣀', '𑣟'), ('𞤢', '𞥃'), +]; + +pub const CHANGES_WHEN_UPPERCASED: &'static [(char, char)] = &[ + ('a', 'z'), ('µ', 'µ'), ('ß', 'ö'), ('ø', 'ÿ'), ('ā', 'ā'), + ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), ('ĉ', 'ĉ'), ('ċ', 'ċ'), + ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), ('ē', 'ē'), ('ĕ', 'ĕ'), + ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), ('ĝ', 'ĝ'), ('ğ', 'ğ'), + ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), ('ħ', 'ħ'), ('ĩ', 'ĩ'), + ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), ('ı', 'ı'), ('ij', 'ij'), + ('ĵ', 'ĵ'), ('ķ', 'ķ'), ('ĺ', 'ĺ'), ('ļ', 'ļ'), ('ľ', 'ľ'), + ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), ('ņ', 'ņ'), ('ň', 'ʼn'), + ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), ('ő', 'ő'), ('œ', 'œ'), + ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), ('ś', 'ś'), ('ŝ', 'ŝ'), + ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), ('ť', 'ť'), ('ŧ', 'ŧ'), + ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), ('ů', 'ů'), ('ű', 'ű'), + ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), ('ź', 'ź'), ('ż', 'ż'), + ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), ('ƈ', 'ƈ'), ('ƌ', 'ƌ'), + ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƚ'), ('ƞ', 'ƞ'), ('ơ', 'ơ'), + ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), ('ƭ', 'ƭ'), ('ư', 'ư'), + ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), ('ƹ', 'ƹ'), ('ƽ', 'ƽ'), ('ƿ', 'ƿ'), + ('Dž', 'dž'), ('Lj', 'lj'), ('Nj', 'nj'), ('ǎ', 'ǎ'), ('ǐ', 'ǐ'), + ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), ('ǘ', 'ǘ'), ('ǚ', 'ǚ'), + ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), ('ǣ', 'ǣ'), ('ǥ', 'ǥ'), + ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), ('ǭ', 'ǭ'), ('ǯ', 'ǰ'), + ('Dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), ('ǻ', 'ǻ'), ('ǽ', 'ǽ'), + ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), ('ȅ', 'ȅ'), ('ȇ', 'ȇ'), + ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), ('ȏ', 'ȏ'), ('ȑ', 'ȑ'), + ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), ('ș', 'ș'), ('ț', 'ț'), + ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), ('ȧ', 'ȧ'), + ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), ('ȱ', 'ȱ'), + ('ȳ', 'ȳ'), ('ȼ', 'ȼ'), ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), ('ɇ', 'ɇ'), + ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), ('ɍ', 'ɍ'), ('ɏ', 'ɔ'), ('ɖ', 'ɗ'), + ('ə', 'ə'), ('ɛ', 'ɜ'), ('ɠ', 'ɡ'), ('ɣ', 'ɣ'), ('ɥ', 'ɦ'), + ('ɨ', 'ɬ'), ('ɯ', 'ɯ'), ('ɱ', 'ɲ'), ('ɵ', 'ɵ'), ('ɽ', 'ɽ'), + ('ʀ', 'ʀ'), ('ʃ', 'ʃ'), ('ʇ', 'ʌ'), ('ʒ', 'ʒ'), ('ʝ', 'ʞ'), + ('ͅ', 'ͅ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), ('ϙ', 'ϙ'), + ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('ϣ', 'ϣ'), + ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), ('ϭ', 'ϭ'), + ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϻ'), ('а', 'џ'), + ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), ('ѩ', 'ѩ'), + ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), ('ѳ', 'ѳ'), + ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), ('ѽ', 'ѽ'), + ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), ('ҏ', 'ҏ'), + ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), ('ҙ', 'ҙ'), + ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), ('ң', 'ң'), + ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), ('ҭ', 'ҭ'), + ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), ('ҷ', 'ҷ'), + ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), ('ӂ', 'ӂ'), + ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), ('ӌ', 'ӌ'), + ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), ('ӗ', 'ӗ'), + ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), ('ӡ', 'ӡ'), + ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), ('ӫ', 'ӫ'), + ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), ('ӵ', 'ӵ'), + ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), ('ӿ', 'ӿ'), + ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), ('ԉ', 'ԉ'), + ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), ('ԓ', 'ԓ'), + ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), ('ԝ', 'ԝ'), + ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), ('ԧ', 'ԧ'), + ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), ('ա', 'և'), + ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᵹ', 'ᵹ'), ('ᵽ', 'ᵽ'), + ('ḁ', 'ḁ'), ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), ('ḇ', 'ḇ'), + ('ḉ', 'ḉ'), ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), ('ḏ', 'ḏ'), + ('ḑ', 'ḑ'), ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), ('ḗ', 'ḗ'), + ('ḙ', 'ḙ'), ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), ('ḟ', 'ḟ'), + ('ḡ', 'ḡ'), ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), ('ḧ', 'ḧ'), + ('ḩ', 'ḩ'), ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), ('ḯ', 'ḯ'), + ('ḱ', 'ḱ'), ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), ('ḷ', 'ḷ'), + ('ḹ', 'ḹ'), ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), ('ḿ', 'ḿ'), + ('ṁ', 'ṁ'), ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), ('ṇ', 'ṇ'), + ('ṉ', 'ṉ'), ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), ('ṏ', 'ṏ'), + ('ṑ', 'ṑ'), ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), ('ṗ', 'ṗ'), + ('ṙ', 'ṙ'), ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), ('ṟ', 'ṟ'), + ('ṡ', 'ṡ'), ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), ('ṧ', 'ṧ'), + ('ṩ', 'ṩ'), ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), ('ṯ', 'ṯ'), + ('ṱ', 'ṱ'), ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), ('ṷ', 'ṷ'), + ('ṹ', 'ṹ'), ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), ('ṿ', 'ṿ'), + ('ẁ', 'ẁ'), ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), ('ẇ', 'ẇ'), + ('ẉ', 'ẉ'), ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), ('ẏ', 'ẏ'), + ('ẑ', 'ẑ'), ('ẓ', 'ẓ'), ('ẕ', 'ẛ'), ('ạ', 'ạ'), + ('ả', 'ả'), ('ấ', 'ấ'), ('ầ', 'ầ'), ('ẩ', 'ẩ'), + ('ẫ', 'ẫ'), ('ậ', 'ậ'), ('ắ', 'ắ'), ('ằ', 'ằ'), + ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), ('ặ', 'ặ'), ('ẹ', 'ẹ'), + ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), ('ế', 'ế'), ('ề', 'ề'), + ('ể', 'ể'), ('ễ', 'ễ'), ('ệ', 'ệ'), ('ỉ', 'ỉ'), + ('ị', 'ị'), ('ọ', 'ọ'), ('ỏ', 'ỏ'), ('ố', 'ố'), + ('ồ', 'ồ'), ('ổ', 'ổ'), ('ỗ', 'ỗ'), ('ộ', 'ộ'), + ('ớ', 'ớ'), ('ờ', 'ờ'), ('ở', 'ở'), ('ỡ', 'ỡ'), + ('ợ', 'ợ'), ('ụ', 'ụ'), ('ủ', 'ủ'), ('ứ', 'ứ'), + ('ừ', 'ừ'), ('ử', 'ử'), ('ữ', 'ữ'), ('ự', 'ự'), + ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), ('ỷ', 'ỷ'), ('ỹ', 'ỹ'), + ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), ('ỿ', 'ἇ'), ('ἐ', 'ἕ'), + ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), ('ὀ', 'ὅ'), ('ὐ', 'ὗ'), + ('ὠ', 'ὧ'), ('ὰ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾷ'), + ('ᾼ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), + ('ῌ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'ῗ'), ('ῠ', 'ῧ'), + ('ῲ', 'ῴ'), ('ῶ', 'ῷ'), ('ῼ', 'ῼ'), ('ⅎ', 'ⅎ'), + ('ⅰ', 'ⅿ'), ('ↄ', 'ↄ'), ('ⓐ', 'ⓩ'), ('ⰰ', 'ⱞ'), + ('ⱡ', 'ⱡ'), ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), ('ⱪ', 'ⱪ'), + ('ⱬ', 'ⱬ'), ('ⱳ', 'ⱳ'), ('ⱶ', 'ⱶ'), ('ⲁ', 'ⲁ'), + ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), ('ⲉ', 'ⲉ'), + ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), ('ⲑ', 'ⲑ'), + ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), ('ⲙ', 'ⲙ'), + ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), ('ⲡ', 'ⲡ'), + ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), ('ⲩ', 'ⲩ'), + ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), ('ⲱ', 'ⲱ'), + ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), ('ⲹ', 'ⲹ'), + ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), ('ⳁ', 'ⳁ'), + ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), ('ⳉ', 'ⳉ'), + ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), ('ⳑ', 'ⳑ'), + ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), ('ⳙ', 'ⳙ'), + ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), ('ⳡ', 'ⳡ'), + ('ⳣ', 'ⳣ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), ('ⳳ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ꙁ', 'ꙁ'), + ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), ('ꙉ', 'ꙉ'), + ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), ('ꙑ', 'ꙑ'), + ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), ('ꙙ', 'ꙙ'), + ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), ('ꙡ', 'ꙡ'), + ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), ('ꙩ', 'ꙩ'), + ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), ('ꚃ', 'ꚃ'), + ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), ('ꚋ', 'ꚋ'), + ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), ('ꚓ', 'ꚓ'), + ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), ('ꚛ', 'ꚛ'), + ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), ('ꜩ', 'ꜩ'), + ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜯ'), ('ꜳ', 'ꜳ'), + ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), ('ꜻ', 'ꜻ'), + ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), ('ꝃ', 'ꝃ'), + ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), ('ꝋ', 'ꝋ'), + ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), ('ꝓ', 'ꝓ'), + ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), ('ꝛ', 'ꝛ'), + ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), ('ꝣ', 'ꝣ'), + ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), ('ꝫ', 'ꝫ'), + ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝯ'), ('ꝺ', 'ꝺ'), ('ꝼ', 'ꝼ'), + ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), ('ꞃ', 'ꞃ'), ('ꞅ', 'ꞅ'), + ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), ('ꞑ', 'ꞑ'), ('ꞓ', 'ꞓ'), + ('ꞗ', 'ꞗ'), ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), ('ꞝ', 'ꞝ'), + ('ꞟ', 'ꞟ'), ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), ('ꞥ', 'ꞥ'), + ('ꞧ', 'ꞧ'), ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), ('ꞷ', 'ꞷ'), + ('ꭓ', 'ꭓ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), ('ﬓ', 'ﬗ'), + ('a', 'z'), ('𐐨', '𐑏'), ('𐓘', '𐓻'), ('𐳀', '𐳲'), + ('𑣀', '𑣟'), ('𞤢', '𞥃'), +]; + +pub const DASH: &'static [(char, char)] = &[ + ('-', '-'), ('֊', '֊'), ('־', '־'), ('᐀', '᐀'), ('᠆', '᠆'), + ('‐', '―'), ('⁓', '⁓'), ('⁻', '⁻'), ('₋', '₋'), + ('−', '−'), ('⸗', '⸗'), ('⸚', '⸚'), ('⸺', '⸻'), + ('⹀', '⹀'), ('〜', '〜'), ('〰', '〰'), ('゠', '゠'), + ('︱', '︲'), ('﹘', '﹘'), ('﹣', '﹣'), ('-', '-'), +]; + +pub const DEFAULT_IGNORABLE_CODE_POINT: &'static [(char, char)] = &[ + ('\u{ad}', '\u{ad}'), ('͏', '͏'), ('\u{61c}', '\u{61c}'), ('ᅟ', 'ᅠ'), + ('឴', '឵'), ('᠋', '\u{180e}'), ('\u{200b}', '\u{200f}'), + ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{206f}'), ('ㅤ', 'ㅤ'), + ('︀', '️'), ('\u{feff}', '\u{feff}'), ('ᅠ', 'ᅠ'), + ('\u{fff0}', '\u{fff8}'), ('\u{1bca0}', '\u{1bca3}'), + ('\u{1d173}', '\u{1d17a}'), ('\u{e0000}', '\u{e0fff}'), +]; + +pub const DEPRECATED: &'static [(char, char)] = &[ + ('ʼn', 'ʼn'), ('ٳ', 'ٳ'), ('ཷ', 'ཷ'), ('ཹ', 'ཹ'), ('ឣ', 'ឤ'), + ('\u{206a}', '\u{206f}'), ('〈', '〉'), ('\u{e0001}', '\u{e0001}'), +]; + +pub const DIACRITIC: &'static [(char, char)] = &[ + ('^', '^'), ('`', '`'), ('¨', '¨'), ('¯', '¯'), ('´', '´'), + ('·', '¸'), ('ʰ', '͎'), ('͐', '͗'), ('͝', '͢'), ('ʹ', '͵'), + ('ͺ', 'ͺ'), ('΄', '΅'), ('҃', '҇'), ('ՙ', 'ՙ'), ('֑', '֡'), + ('֣', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), ('ׄ', 'ׄ'), ('ً', 'ْ'), + ('ٗ', '٘'), ('۟', '۠'), ('ۥ', 'ۦ'), ('۪', '۬'), ('ܰ', '݊'), + ('ަ', 'ް'), ('߫', 'ߵ'), ('࠘', '࠙'), ('ࣣ', 'ࣾ'), ('़', '़'), + ('्', '्'), ('॑', '॔'), ('ॱ', 'ॱ'), ('়', '়'), + ('্', '্'), ('਼', '਼'), ('੍', '੍'), ('઼', '઼'), + ('્', '્'), ('૽', '૿'), ('଼', '଼'), ('୍', '୍'), + ('்', '்'), ('్', '్'), ('಼', '಼'), ('್', '್'), + ('഻', '഼'), ('്', '്'), ('්', '්'), ('็', '์'), + ('๎', '๎'), ('່', '໌'), ('༘', '༙'), ('༵', '༵'), + ('༷', '༷'), ('༹', '༹'), ('༾', '༿'), ('ྂ', '྄'), + ('྆', '྇'), ('࿆', '࿆'), ('့', '့'), ('္', '်'), + ('ႇ', 'ႍ'), ('ႏ', 'ႏ'), ('ႚ', 'ႛ'), ('៉', '៓'), + ('៝', '៝'), ('᤹', '᤻'), ('᩵', '᩼'), ('᩿', '᩿'), + ('᪰', '᪽'), ('᬴', '᬴'), ('᭄', '᭄'), ('᭫', '᭳'), + ('᮪', '᮫'), ('ᰶ', '᰷'), ('ᱸ', 'ᱽ'), ('᳐', '᳨'), + ('᳭', '᳭'), ('᳴', '᳴'), ('᳷', '᳹'), ('ᴬ', 'ᵪ'), + ('᷄', '᷏'), ('᷵', '᷹'), ('᷽', '᷿'), ('᾽', '᾽'), + ('᾿', '῁'), ('῍', '῏'), ('῝', '῟'), ('῭', '`'), + ('´', '῾'), ('⳯', '⳱'), ('ⸯ', 'ⸯ'), ('〪', '〯'), + ('゙', '゜'), ('ー', 'ー'), ('꙯', '꙯'), ('꙼', '꙽'), + ('ꙿ', 'ꙿ'), ('ꚜ', 'ꚝ'), ('꛰', '꛱'), ('ꜗ', '꜡'), + ('ꞈ', 'ꞈ'), ('ꟸ', 'ꟹ'), ('꣄', '꣄'), ('꣠', '꣱'), + ('꤫', '꤮'), ('꥓', '꥓'), ('꦳', '꦳'), ('꧀', '꧀'), + ('ꧥ', 'ꧥ'), ('ꩻ', 'ꩽ'), ('꪿', 'ꫂ'), ('꫶', '꫶'), + ('꭛', 'ꭟ'), ('꯬', '꯭'), ('ﬞ', 'ﬞ'), ('︠', '︯'), + ('^', '^'), ('`', '`'), ('ー', 'ー'), ('゙', '゚'), + (' ̄', ' ̄'), ('𐋠', '𐋠'), ('𐫥', '𐫦'), ('𑂹', '𑂺'), + ('𑄳', '𑄴'), ('𑅳', '𑅳'), ('𑇀', '𑇀'), ('𑇊', '𑇌'), + ('𑈵', '𑈶'), ('𑋩', '𑋪'), ('𑌼', '𑌼'), ('𑍍', '𑍍'), + ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑑂', '𑑂'), ('𑑆', '𑑆'), + ('𑓂', '𑓃'), ('𑖿', '𑗀'), ('𑘿', '𑘿'), ('𑚶', '𑚷'), + ('𑜫', '𑜫'), ('𑨴', '𑨴'), ('𑩇', '𑩇'), ('𑪙', '𑪙'), + ('𑰿', '𑰿'), ('𑵂', '𑵂'), ('𑵄', '𑵅'), ('𖫰', '𖫴'), + ('𖾏', '𖾟'), ('𝅧', '𝅩'), ('𝅭', '𝅲'), ('𝅻', '𝆂'), + ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𞣐', '𞣖'), ('𞥄', '𞥆'), + ('𞥈', '𞥊'), +]; + +pub const EXTENDER: &'static [(char, char)] = &[ + ('·', '·'), ('ː', 'ˑ'), ('ـ', 'ـ'), ('ߺ', 'ߺ'), ('ๆ', 'ๆ'), + ('ໆ', 'ໆ'), ('᠊', '᠊'), ('ᡃ', 'ᡃ'), ('ᪧ', 'ᪧ'), + ('ᰶ', 'ᰶ'), ('ᱻ', 'ᱻ'), ('々', '々'), ('〱', '〵'), + ('ゝ', 'ゞ'), ('ー', 'ヾ'), ('ꀕ', 'ꀕ'), ('ꘌ', 'ꘌ'), + ('ꧏ', 'ꧏ'), ('ꧦ', 'ꧦ'), ('ꩰ', 'ꩰ'), ('ꫝ', 'ꫝ'), + ('ꫳ', 'ꫴ'), ('ー', 'ー'), ('𑍝', '𑍝'), ('𑗆', '𑗈'), + ('𑪘', '𑪘'), ('𖭂', '𖭃'), ('𖿠', '𖿡'), ('𞥄', '𞥆'), +]; + +pub const GRAPHEME_BASE: &'static [(char, char)] = &[ + (' ', '~'), ('\u{a0}', '¬'), ('®', '˿'), ('Ͱ', 'ͷ'), ('ͺ', 'Ϳ'), + ('΄', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', '҂'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('։', '֊'), ('֍', '֏'), + ('־', '־'), ('׀', '׀'), ('׃', '׃'), ('׆', '׆'), ('א', 'ת'), + ('װ', '״'), ('؆', '؏'), ('؛', '؛'), ('؞', 'ي'), ('٠', 'ٯ'), + ('ٱ', 'ە'), ('۞', '۞'), ('ۥ', 'ۦ'), ('۩', '۩'), ('ۮ', '܍'), + ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), ('߀', 'ߪ'), + ('ߴ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), ('ࠤ', 'ࠤ'), + ('ࠨ', 'ࠨ'), ('࠰', '࠾'), ('ࡀ', 'ࡘ'), ('࡞', '࡞'), + ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ः', 'ह'), + ('ऻ', 'ऻ'), ('ऽ', 'ी'), ('ॉ', 'ौ'), ('ॎ', 'ॐ'), + ('क़', 'ॡ'), ('।', 'ঀ'), ('ং', 'ঃ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ি', 'ী'), ('ে', 'ৈ'), + ('ো', 'ৌ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), ('য়', 'ৡ'), + ('০', '৽'), ('ਃ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), + ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), + ('ਸ', 'ਹ'), ('ਾ', 'ੀ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('੦', '੯'), ('ੲ', 'ੴ'), ('ઃ', 'ઃ'), ('અ', 'ઍ'), + ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), ('લ', 'ળ'), + ('વ', 'હ'), ('ઽ', 'ી'), ('ૉ', 'ૉ'), ('ો', 'ૌ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('૦', '૱'), ('ૹ', 'ૹ'), + ('ଂ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), ('ଓ', 'ନ'), + ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), ('ଽ', 'ଽ'), + ('ୀ', 'ୀ'), ('େ', 'ୈ'), ('ୋ', 'ୌ'), ('ଡ଼', 'ଢ଼'), + ('ୟ', 'ୡ'), ('୦', '୷'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), + ('எ', 'ஐ'), ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), + ('ஞ', 'ட'), ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), + ('ி', 'ி'), ('ு', 'ூ'), ('ெ', 'ை'), ('ொ', 'ௌ'), + ('ௐ', 'ௐ'), ('௦', '௺'), ('ఁ', 'ః'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ఽ'), + ('ు', 'ౄ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('౦', '౯'), + ('౸', 'ಀ'), ('ಂ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), + ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('ಽ', 'ಾ'), + ('ೀ', 'ು'), ('ೃ', 'ೄ'), ('ೇ', 'ೈ'), ('ೊ', 'ೋ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), ('೦', '೯'), ('ೱ', 'ೲ'), + ('ം', 'ഃ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ി', 'ീ'), ('െ', 'ൈ'), ('ൊ', 'ൌ'), + ('ൎ', '൏'), ('ൔ', 'ൖ'), ('൘', 'ൡ'), ('൦', 'ൿ'), + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ැ', 'ෑ'), ('ෘ', 'ෞ'), + ('෦', '෯'), ('ෲ', '෴'), ('ก', 'ะ'), ('า', 'ำ'), + ('฿', 'ๆ'), ('๏', '๛'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), + ('ງ', 'ຈ'), ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), + ('ນ', 'ຟ'), ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), + ('ສ', 'ຫ'), ('ອ', 'ະ'), ('າ', 'ຳ'), ('ຽ', 'ຽ'), + ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('໐', '໙'), ('ໜ', 'ໟ'), + ('ༀ', '༗'), ('༚', '༴'), ('༶', '༶'), ('༸', '༸'), + ('༺', 'ཇ'), ('ཉ', 'ཬ'), ('ཿ', 'ཿ'), ('྅', '྅'), + ('ྈ', 'ྌ'), ('྾', '࿅'), ('࿇', '࿌'), ('࿎', '࿚'), + ('က', 'ာ'), ('ေ', 'ေ'), ('း', 'း'), ('ျ', 'ြ'), + ('ဿ', 'ၗ'), ('ၚ', 'ၝ'), ('ၡ', 'ၰ'), ('ၵ', 'ႁ'), + ('ႃ', 'ႄ'), ('ႇ', 'ႌ'), ('ႎ', 'ႜ'), ('႞', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኈ'), + ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), + ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), ('ዘ', 'ጐ'), + ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('፠', '፼'), ('ᎀ', '᎙'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('᐀', '᚜'), ('ᚠ', 'ᛸ'), + ('ᜀ', 'ᜌ'), ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('᜵', '᜶'), + ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), + ('ា', 'ា'), ('ើ', 'ៅ'), ('ះ', 'ៈ'), ('។', 'ៜ'), + ('០', '៩'), ('៰', '៹'), ('᠀', '᠊'), ('᠐', '᠙'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢄ'), ('ᢇ', 'ᢨ'), ('ᢪ', 'ᢪ'), + ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤣ', 'ᤦ'), ('ᤩ', 'ᤫ'), + ('ᤰ', 'ᤱ'), ('ᤳ', 'ᤸ'), ('᥀', '᥀'), ('᥄', 'ᥭ'), + ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧚'), + ('᧞', 'ᨖ'), ('ᨙ', 'ᨚ'), ('᨞', 'ᩕ'), ('ᩗ', 'ᩗ'), + ('ᩡ', 'ᩡ'), ('ᩣ', 'ᩤ'), ('ᩭ', 'ᩲ'), ('᪀', '᪉'), + ('᪐', '᪙'), ('᪠', '᪭'), ('ᬄ', 'ᬳ'), ('ᬵ', 'ᬵ'), + ('ᬻ', 'ᬻ'), ('ᬽ', 'ᭁ'), ('ᭃ', 'ᭋ'), ('᭐', '᭪'), + ('᭴', '᭼'), ('ᮂ', 'ᮡ'), ('ᮦ', 'ᮧ'), ('᮪', '᮪'), + ('ᮮ', 'ᯥ'), ('ᯧ', 'ᯧ'), ('ᯪ', 'ᯬ'), ('ᯮ', 'ᯮ'), + ('᯲', '᯳'), ('᯼', 'ᰫ'), ('ᰴ', 'ᰵ'), ('᰻', '᱉'), + ('ᱍ', 'ᲈ'), ('᳀', '᳇'), ('᳓', '᳓'), ('᳡', '᳡'), + ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳳ'), ('ᳵ', '᳷'), ('ᴀ', 'ᶿ'), + ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ῄ'), ('ῆ', 'ΐ'), + ('ῖ', 'Ί'), ('῝', '`'), ('ῲ', 'ῴ'), ('ῶ', '῾'), + ('\u{2000}', '\u{200a}'), ('‐', '‧'), ('\u{202f}', '\u{205f}'), + ('⁰', 'ⁱ'), ('⁴', '₎'), ('ₐ', 'ₜ'), ('₠', '₿'), + ('℀', '↋'), ('←', '␦'), ('⑀', '⑊'), ('①', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯒'), + ('⯬', '⯯'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('⳹', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ⴰ', 'ⵧ'), ('ⵯ', '⵰'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('⸀', '⹉'), + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('⿰', '⿻'), + ('\u{3000}', '〩'), ('〰', '〿'), ('ぁ', 'ゖ'), ('゛', 'ヿ'), + ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('㆐', 'ㆺ'), ('㇀', '㇣'), + ('ㇰ', '㈞'), ('㈠', '㋾'), ('㌀', '䶵'), ('䷀', '鿪'), + ('ꀀ', 'ꒌ'), ('꒐', '꓆'), ('ꓐ', 'ꘫ'), ('Ꙁ', 'ꙮ'), + ('꙳', '꙳'), ('꙾', 'ꚝ'), ('ꚠ', 'ꛯ'), ('꛲', '꛷'), + ('꜀', 'Ɪ'), ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), + ('ꠇ', 'ꠊ'), ('ꠌ', 'ꠤ'), ('ꠧ', '꠫'), ('꠰', '꠹'), + ('ꡀ', '꡷'), ('ꢀ', 'ꣃ'), ('꣎', '꣙'), ('ꣲ', 'ꣽ'), + ('꤀', 'ꤥ'), ('꤮', 'ꥆ'), ('ꥒ', '꥓'), ('꥟', 'ꥼ'), + ('ꦃ', 'ꦲ'), ('ꦴ', 'ꦵ'), ('ꦺ', 'ꦻ'), ('ꦽ', '꧍'), + ('ꧏ', '꧙'), ('꧞', 'ꧤ'), ('ꧦ', 'ꧾ'), ('ꨀ', 'ꨨ'), + ('ꨯ', 'ꨰ'), ('ꨳ', 'ꨴ'), ('ꩀ', 'ꩂ'), ('ꩄ', 'ꩋ'), + ('ꩍ', 'ꩍ'), ('꩐', '꩙'), ('꩜', 'ꩻ'), ('ꩽ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫫ'), ('ꫮ', 'ꫵ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), + ('ꬰ', 'ꭥ'), ('ꭰ', 'ꯤ'), ('ꯦ', 'ꯧ'), ('ꯩ', '꯬'), + ('꯰', '꯹'), ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), + ('豈', '舘'), ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), + ('יִ', 'יִ'), ('ײַ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', '﯁'), ('ﯓ', '﴿'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', '﷽'), ('︐', '︙'), + ('︰', '﹒'), ('﹔', '﹦'), ('﹨', '﹫'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('!', 'ン'), ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('¢', '₩'), + ('│', '○'), ('', '�'), ('𐀀', '𐀋'), ('𐀍', '𐀦'), + ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), ('𐁐', '𐁝'), + ('𐂀', '𐃺'), ('𐄀', '𐄂'), ('𐄇', '𐄳'), ('𐄷', '𐆎'), + ('𐆐', '𐆛'), ('𐆠', '𐆠'), ('𐇐', '𐇼'), ('𐊀', '𐊜'), + ('𐊠', '𐋐'), ('𐋡', '𐋻'), ('𐌀', '𐌣'), ('𐌭', '𐍊'), + ('𐍐', '𐍵'), ('𐎀', '𐎝'), ('𐎟', '𐏃'), ('𐏈', '𐏕'), + ('𐐀', '𐒝'), ('𐒠', '𐒩'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐕯', '𐕯'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), + ('𐡗', '𐢞'), ('𐢧', '𐢯'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐣻', '𐤛'), ('𐤟', '𐤹'), ('𐤿', '𐤿'), ('𐦀', '𐦷'), + ('𐦼', '𐧏'), ('𐧒', '𐨀'), ('𐨐', '𐨓'), ('𐨕', '𐨗'), + ('𐨙', '𐨳'), ('𐩀', '𐩇'), ('𐩐', '𐩘'), ('𐩠', '𐪟'), + ('𐫀', '𐫤'), ('𐫫', '𐫶'), ('𐬀', '𐬵'), ('𐬹', '𐭕'), + ('𐭘', '𐭲'), ('𐭸', '𐮑'), ('𐮙', '𐮜'), ('𐮩', '𐮯'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), + ('𐹠', '𐹾'), ('𑀀', '𑀀'), ('𑀂', '𑀷'), ('𑁇', '𑁍'), + ('𑁒', '𑁯'), ('𑂂', '𑂲'), ('𑂷', '𑂸'), ('𑂻', '𑂼'), + ('𑂾', '𑃁'), ('𑃐', '𑃨'), ('𑃰', '𑃹'), ('𑄃', '𑄦'), + ('𑄬', '𑄬'), ('𑄶', '𑅃'), ('𑅐', '𑅲'), ('𑅴', '𑅶'), + ('𑆂', '𑆵'), ('𑆿', '𑇉'), ('𑇍', '𑇍'), ('𑇐', '𑇟'), + ('𑇡', '𑇴'), ('𑈀', '𑈑'), ('𑈓', '𑈮'), ('𑈲', '𑈳'), + ('𑈵', '𑈵'), ('𑈸', '𑈽'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), + ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊩'), ('𑊰', '𑋞'), + ('𑋠', '𑋢'), ('𑋰', '𑋹'), ('𑌂', '𑌃'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑌿', '𑌿'), ('𑍁', '𑍄'), + ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍝', '𑍣'), + ('𑐀', '𑐷'), ('𑑀', '𑑁'), ('𑑅', '𑑅'), ('𑑇', '𑑙'), + ('𑑛', '𑑛'), ('𑑝', '𑑝'), ('𑒀', '𑒯'), ('𑒱', '𑒲'), + ('𑒹', '𑒹'), ('𑒻', '𑒼'), ('𑒾', '𑒾'), ('𑓁', '𑓁'), + ('𑓄', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖮'), ('𑖰', '𑖱'), + ('𑖸', '𑖻'), ('𑖾', '𑖾'), ('𑗁', '𑗛'), ('𑘀', '𑘲'), + ('𑘻', '𑘼'), ('𑘾', '𑘾'), ('𑙁', '𑙄'), ('𑙐', '𑙙'), + ('𑙠', '𑙬'), ('𑚀', '𑚪'), ('𑚬', '𑚬'), ('𑚮', '𑚯'), + ('𑚶', '𑚶'), ('𑛀', '𑛉'), ('𑜀', '𑜙'), ('𑜠', '𑜡'), + ('𑜦', '𑜦'), ('𑜰', '𑜿'), ('𑢠', '𑣲'), ('𑣿', '𑣿'), + ('𑨀', '𑨀'), ('𑨇', '𑨈'), ('𑨋', '𑨲'), ('𑨹', '𑨺'), + ('𑨿', '𑩆'), ('𑩐', '𑩐'), ('𑩗', '𑩘'), ('𑩜', '𑪃'), + ('𑪆', '𑪉'), ('𑪗', '𑪗'), ('𑪚', '𑪜'), ('𑪞', '𑪢'), + ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰯'), ('𑰾', '𑰾'), + ('𑱀', '𑱅'), ('𑱐', '𑱬'), ('𑱰', '𑲏'), ('𑲩', '𑲩'), + ('𑲱', '𑲱'), ('𑲴', '𑲴'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), + ('𑴋', '𑴰'), ('𑵆', '𑵆'), ('𑵐', '𑵙'), ('𒀀', '𒎙'), + ('𒐀', '𒑮'), ('𒑰', '𒑴'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), + ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), + ('𖩮', '𖩯'), ('𖫐', '𖫭'), ('𖫵', '𖫵'), ('𖬀', '𖬯'), + ('𖬷', '𖭅'), ('𖭐', '𖭙'), ('𖭛', '𖭡'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𛲜', '𛲜'), ('𛲟', '𛲟'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄩', '𝅘𝅥𝅲'), ('𝅦', '𝅦'), ('𝅪', '𝅭'), + ('𝆃', '𝆄'), ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝈀', '𝉁'), + ('𝉅', '𝉅'), ('𝌀', '𝍖'), ('𝍠', '𝍱'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), ('𝟎', '𝧿'), + ('𝨷', '𝨺'), ('𝩭', '𝩴'), ('𝩶', '𝪃'), ('𝪅', '𝪋'), + ('𞠀', '𞣄'), ('𞣇', '𞣏'), ('𞤀', '𞥃'), ('𞥐', '𞥙'), + ('𞥞', '𞥟'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), ('🀀', '🀫'), + ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), ('🃁', '🃏'), + ('🃑', '🃵'), ('🄀', '🄌'), ('🄐', '🄮'), ('🄰', '🅫'), + ('🅰', '🆬'), ('🇦', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), + ('🉐', '🉑'), ('🉠', '🉥'), ('🌀', '🛔'), ('🛠', '🛬'), + ('🛰', '🛸'), ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), + ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), + ('🤀', '🤋'), ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), + ('🦀', '🦗'), ('🧀', '🧀'), ('🧐', '🧦'), ('𠀀', '𪛖'), + ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), + ('丽', '𪘀'), +]; + +pub const GRAPHEME_EXTEND: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҃', '҉'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('۟', 'ۤ'), ('ۧ', 'ۨ'), ('۪', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', '݊'), ('ަ', 'ް'), ('߫', '߳'), ('ࠖ', '࠙'), ('ࠛ', 'ࠣ'), + ('ࠥ', 'ࠧ'), ('ࠩ', '࠭'), ('࡙', '࡛'), ('ࣔ', '࣡'), + ('ࣣ', 'ं'), ('ऺ', 'ऺ'), ('़', '़'), ('ु', 'ै'), + ('्', '्'), ('॑', 'ॗ'), ('ॢ', 'ॣ'), ('ঁ', 'ঁ'), + ('়', '়'), ('া', 'া'), ('ু', 'ৄ'), ('্', '্'), + ('ৗ', 'ৗ'), ('ৢ', 'ৣ'), ('ਁ', 'ਂ'), ('਼', '਼'), + ('ੁ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ੑ', 'ੑ'), + ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), ('ઁ', 'ં'), ('઼', '઼'), + ('ુ', 'ૅ'), ('ે', 'ૈ'), ('્', '્'), ('ૢ', 'ૣ'), + ('ૺ', '૿'), ('ଁ', 'ଁ'), ('଼', '଼'), ('ା', 'ି'), + ('ୁ', 'ୄ'), ('୍', '୍'), ('ୖ', 'ୗ'), ('ୢ', 'ୣ'), + ('ஂ', 'ஂ'), ('ா', 'ா'), ('ீ', 'ீ'), ('்', '்'), + ('ௗ', 'ௗ'), ('ఀ', 'ఀ'), ('ా', 'ీ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౢ', 'ౣ'), ('ಁ', 'ಁ'), + ('಼', '಼'), ('ಿ', 'ಿ'), ('ೂ', 'ೂ'), ('ೆ', 'ೆ'), + ('ೌ', '್'), ('ೕ', 'ೖ'), ('ೢ', 'ೣ'), ('ഀ', 'ഁ'), + ('഻', '഼'), ('ാ', 'ാ'), ('ു', 'ൄ'), ('്', '്'), + ('ൗ', 'ൗ'), ('ൢ', 'ൣ'), ('්', '්'), ('ා', 'ා'), + ('ි', 'ු'), ('ූ', 'ූ'), ('ෟ', 'ෟ'), ('ั', 'ั'), + ('ิ', 'ฺ'), ('็', '๎'), ('ັ', 'ັ'), ('ິ', 'ູ'), + ('ົ', 'ຼ'), ('່', 'ໍ'), ('༘', '༙'), ('༵', '༵'), + ('༷', '༷'), ('༹', '༹'), ('ཱ', 'ཾ'), ('ྀ', '྄'), + ('྆', '྇'), ('ྍ', 'ྗ'), ('ྙ', 'ྼ'), ('࿆', '࿆'), + ('ိ', 'ူ'), ('ဲ', '့'), ('္', '်'), ('ွ', 'ှ'), + ('ၘ', 'ၙ'), ('ၞ', 'ၠ'), ('ၱ', 'ၴ'), ('ႂ', 'ႂ'), + ('ႅ', 'ႆ'), ('ႍ', 'ႍ'), ('ႝ', 'ႝ'), ('፝', '፟'), + ('ᜒ', '᜔'), ('ᜲ', '᜴'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), + ('឴', '឵'), ('ិ', 'ួ'), ('ំ', 'ំ'), ('៉', '៓'), + ('៝', '៝'), ('᠋', '᠍'), ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), + ('ᤠ', 'ᤢ'), ('ᤧ', 'ᤨ'), ('ᤲ', 'ᤲ'), ('᤹', '᤻'), + ('ᨗ', 'ᨘ'), ('ᨛ', 'ᨛ'), ('ᩖ', 'ᩖ'), ('ᩘ', 'ᩞ'), + ('᩠', '᩠'), ('ᩢ', 'ᩢ'), ('ᩥ', 'ᩬ'), ('ᩳ', '᩼'), + ('᩿', '᩿'), ('᪰', '᪾'), ('ᬀ', 'ᬃ'), ('᬴', '᬴'), + ('ᬶ', 'ᬺ'), ('ᬼ', 'ᬼ'), ('ᭂ', 'ᭂ'), ('᭫', '᭳'), + ('ᮀ', 'ᮁ'), ('ᮢ', 'ᮥ'), ('ᮨ', 'ᮩ'), ('᮫', 'ᮭ'), + ('᯦', '᯦'), ('ᯨ', 'ᯩ'), ('ᯭ', 'ᯭ'), ('ᯯ', 'ᯱ'), + ('ᰬ', 'ᰳ'), ('ᰶ', '᰷'), ('᳐', '᳒'), ('᳔', '᳠'), + ('᳢', '᳨'), ('᳭', '᳭'), ('᳴', '᳴'), ('᳸', '᳹'), + ('᷀', '᷹'), ('᷻', '᷿'), ('\u{200c}', '\u{200c}'), ('⃐', '⃰'), + ('⳯', '⳱'), ('⵿', '⵿'), ('ⷠ', 'ⷿ'), ('〪', '〯'), + ('゙', '゚'), ('꙯', '꙲'), ('ꙴ', '꙽'), ('ꚞ', 'ꚟ'), + ('꛰', '꛱'), ('ꠂ', 'ꠂ'), ('꠆', '꠆'), ('ꠋ', 'ꠋ'), + ('ꠥ', 'ꠦ'), ('꣄', 'ꣅ'), ('꣠', '꣱'), ('ꤦ', '꤭'), + ('ꥇ', 'ꥑ'), ('ꦀ', 'ꦂ'), ('꦳', '꦳'), ('ꦶ', 'ꦹ'), + ('ꦼ', 'ꦼ'), ('ꧥ', 'ꧥ'), ('ꨩ', 'ꨮ'), ('ꨱ', 'ꨲ'), + ('ꨵ', 'ꨶ'), ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩌ'), ('ꩼ', 'ꩼ'), + ('ꪰ', 'ꪰ'), ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), + ('꫁', '꫁'), ('ꫬ', 'ꫭ'), ('꫶', '꫶'), ('ꯥ', 'ꯥ'), + ('ꯨ', 'ꯨ'), ('꯭', '꯭'), ('ﬞ', 'ﬞ'), ('︀', '️'), + ('︠', '︯'), ('゙', '゚'), ('𐇽', '𐇽'), ('𐋠', '𐋠'), + ('𐍶', '𐍺'), ('𐨁', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨏'), + ('𐨸', '𐨺'), ('𐨿', '𐨿'), ('𐫥', '𐫦'), ('𑀁', '𑀁'), + ('𑀸', '𑁆'), ('𑁿', '𑂁'), ('𑂳', '𑂶'), ('𑂹', '𑂺'), + ('𑄀', '𑄂'), ('𑄧', '𑄫'), ('𑄭', '𑄴'), ('𑅳', '𑅳'), + ('𑆀', '𑆁'), ('𑆶', '𑆾'), ('𑇊', '𑇌'), ('𑈯', '𑈱'), + ('𑈴', '𑈴'), ('𑈶', '𑈷'), ('𑈾', '𑈾'), ('𑋟', '𑋟'), + ('𑋣', '𑋪'), ('𑌀', '𑌁'), ('𑌼', '𑌼'), ('𑌾', '𑌾'), + ('𑍀', '𑍀'), ('𑍗', '𑍗'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), + ('𑐸', '𑐿'), ('𑑂', '𑑄'), ('𑑆', '𑑆'), ('𑒰', '𑒰'), + ('𑒳', '𑒸'), ('𑒺', '𑒺'), ('𑒽', '𑒽'), ('𑒿', '𑓀'), + ('𑓂', '𑓃'), ('𑖯', '𑖯'), ('𑖲', '𑖵'), ('𑖼', '𑖽'), + ('𑖿', '𑗀'), ('𑗜', '𑗝'), ('𑘳', '𑘺'), ('𑘽', '𑘽'), + ('𑘿', '𑙀'), ('𑚫', '𑚫'), ('𑚭', '𑚭'), ('𑚰', '𑚵'), + ('𑚷', '𑚷'), ('𑜝', '𑜟'), ('𑜢', '𑜥'), ('𑜧', '𑜫'), + ('𑨁', '𑨆'), ('𑨉', '𑨊'), ('𑨳', '𑨸'), ('𑨻', '𑨾'), + ('𑩇', '𑩇'), ('𑩑', '𑩖'), ('𑩙', '𑩛'), ('𑪊', '𑪖'), + ('𑪘', '𑪙'), ('𑰰', '𑰶'), ('𑰸', '𑰽'), ('𑰿', '𑰿'), + ('𑲒', '𑲧'), ('𑲪', '𑲰'), ('𑲲', '𑲳'), ('𑲵', '𑲶'), + ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵅'), + ('𑵇', '𑵇'), ('𖫰', '𖫴'), ('𖬰', '𖬶'), ('𖾏', '𖾒'), + ('𛲝', '𛲞'), ('𝅥', '𝅥'), ('𝅧', '𝅩'), ('𝅮', '𝅲'), + ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), + ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), + ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞣐', '𞣖'), + ('𞥄', '𞥊'), ('\u{e0020}', '\u{e007f}'), ('󠄀', '󠇯'), +]; + +pub const GRAPHEME_LINK: &'static [(char, char)] = &[ + ('्', '्'), ('্', '্'), ('੍', '੍'), ('્', '્'), + ('୍', '୍'), ('்', '்'), ('్', '్'), ('್', '್'), + ('഻', '഼'), ('്', '്'), ('්', '්'), ('ฺ', 'ฺ'), + ('྄', '྄'), ('္', '်'), ('᜔', '᜔'), ('᜴', '᜴'), + ('្', '្'), ('᩠', '᩠'), ('᭄', '᭄'), ('᮪', '᮫'), + ('᯲', '᯳'), ('⵿', '⵿'), ('꠆', '꠆'), ('꣄', '꣄'), + ('꥓', '꥓'), ('꧀', '꧀'), ('꫶', '꫶'), ('꯭', '꯭'), + ('𐨿', '𐨿'), ('𑁆', '𑁆'), ('𑁿', '𑁿'), ('𑂹', '𑂹'), + ('𑄳', '𑄴'), ('𑇀', '𑇀'), ('𑈵', '𑈵'), ('𑋪', '𑋪'), + ('𑍍', '𑍍'), ('𑑂', '𑑂'), ('𑓂', '𑓂'), ('𑖿', '𑖿'), + ('𑘿', '𑘿'), ('𑚶', '𑚶'), ('𑜫', '𑜫'), ('𑨴', '𑨴'), + ('𑩇', '𑩇'), ('𑪙', '𑪙'), ('𑰿', '𑰿'), ('𑵄', '𑵅'), +]; + +pub const HEX_DIGIT: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'F'), ('a', 'f'), ('0', '9'), ('A', 'F'), + ('a', 'f'), +]; + +pub const HYPHEN: &'static [(char, char)] = &[ + ('-', '-'), ('\u{ad}', '\u{ad}'), ('֊', '֊'), ('᠆', '᠆'), + ('‐', '‑'), ('⸗', '⸗'), ('・', '・'), ('﹣', '﹣'), + ('-', '-'), ('・', '・'), +]; + +pub const IDS_BINARY_OPERATOR: &'static [(char, char)] = &[ + ('⿰', '⿱'), ('⿴', '⿻'), +]; + +pub const IDS_TRINARY_OPERATOR: &'static [(char, char)] = &[ + ('⿲', '⿳'), +]; + +pub const ID_CONTINUE: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), + ('·', '·'), ('º', 'º'), ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), + ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('̀', 'ʹ'), + ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('҃', '҇'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), ('ա', 'և'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), + ('ׁ', 'ׂ'), ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), + ('ؐ', 'ؚ'), ('ؠ', '٩'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('۟', 'ۨ'), + ('۪', 'ۼ'), ('ۿ', 'ۿ'), ('ܐ', '݊'), ('ݍ', 'ޱ'), ('߀', 'ߵ'), + ('ߺ', 'ߺ'), ('ࠀ', '࠭'), ('ࡀ', '࡛'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), ('ࣣ', 'ॣ'), + ('०', '९'), ('ॱ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), + ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), + ('়', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), + ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', 'ৱ'), ('ৼ', 'ৼ'), + ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), + ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), + ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), + ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), + ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), + ('ે', 'ૉ'), ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), + ('૦', '૯'), ('ૹ', '૿'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୯'), + ('ୱ', 'ୱ'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), + ('௦', '௯'), ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), + ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), + ('౦', '౯'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), + ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), + ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), + ('ೠ', 'ೣ'), ('೦', '೯'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), + ('ൊ', 'ൎ'), ('ൔ', 'ൗ'), ('ൟ', 'ൣ'), ('൦', '൯'), + ('ൺ', 'ൿ'), ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), + ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), + ('ෲ', 'ෳ'), ('ก', 'ฺ'), ('เ', '๎'), ('๐', '๙'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('༘', '༙'), + ('༠', '༩'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('༾', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', '྄'), ('྆', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('က', '၉'), ('ၐ', 'ႝ'), + ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), + ('ჼ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፟'), ('፩', '፱'), ('ᎀ', 'ᎏ'), ('Ꭰ', 'Ᏽ'), + ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), + ('ᜠ', '᜴'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), + ('ᝲ', 'ᝳ'), ('ក', '៓'), ('ៗ', 'ៗ'), ('ៜ', '៝'), + ('០', '៩'), ('᠋', '᠍'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), + ('ᢀ', 'ᢪ'), ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), + ('ᤰ', '᤻'), ('᥆', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), + ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), ('ᪧ', 'ᪧ'), + ('᪰', '᪽'), ('ᬀ', 'ᭋ'), ('᭐', '᭙'), ('᭫', '᭳'), + ('ᮀ', '᯳'), ('ᰀ', '᰷'), ('᱀', '᱉'), ('ᱍ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('᳐', '᳒'), ('᳔', '᳹'), ('ᴀ', '᷹'), + ('᷻', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('‿', '⁀'), + ('⁔', '⁔'), ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), + ('⃐', '⃜'), ('⃡', '⃡'), ('⃥', '⃰'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), + ('ⵯ', 'ⵯ'), ('⵿', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), + ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), + ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ⷠ', 'ⷿ'), ('々', '〇'), + ('〡', '〯'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゙', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), + ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), + ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), + ('ꘐ', 'ꘫ'), ('Ꙁ', '꙯'), ('ꙴ', '꙽'), ('ꙿ', '꛱'), + ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟷ', 'ꠧ'), ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣅ'), ('꣐', '꣙'), + ('꣠', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('꤀', '꤭'), + ('ꤰ', '꥓'), ('ꥠ', 'ꥼ'), ('ꦀ', '꧀'), ('ꧏ', '꧙'), + ('ꧠ', 'ꧾ'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), + ('ꩠ', 'ꩶ'), ('ꩺ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫯ'), + ('ꫲ', '꫶'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), + ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꯪ'), ('꯬', '꯭'), ('꯰', '꯹'), ('가', '힣'), + ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), ('並', '龎'), + ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'ﬨ'), ('שׁ', 'זּ'), + ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), + ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), + ('ﷰ', 'ﷻ'), ('︀', '️'), ('︠', '︯'), ('︳', '︴'), + ('﹍', '﹏'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), ('0', '9'), + ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ヲ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), + ('𐇽', '𐇽'), ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐋠', '𐋠'), + ('𐌀', '𐌟'), ('𐌭', '𐍊'), ('𐍐', '𐍺'), ('𐎀', '𐎝'), + ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐏑', '𐏕'), ('𐐀', '𐒝'), + ('𐒠', '𐒩'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐔀', '𐔧'), + ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), + ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), + ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), ('𐢀', '𐢞'), + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), ('𐤠', '𐤹'), + ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨃'), ('𐨅', '𐨆'), + ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐨸', '𐨺'), + ('𐨿', '𐨿'), ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), + ('𐫉', '𐫦'), ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), + ('𐮀', '𐮑'), ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), + ('𑀀', '𑁆'), ('𑁦', '𑁯'), ('𑁿', '𑂺'), ('𑃐', '𑃨'), + ('𑃰', '𑃹'), ('𑄀', '𑄴'), ('𑄶', '𑄿'), ('𑅐', '𑅳'), + ('𑅶', '𑅶'), ('𑆀', '𑇄'), ('𑇊', '𑇌'), ('𑇐', '𑇚'), + ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈷'), ('𑈾', '𑈾'), + ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), + ('𑊟', '𑊨'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), ('𑌀', '𑌃'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), + ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), + ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑐀', '𑑊'), ('𑑐', '𑑙'), + ('𑒀', '𑓅'), ('𑓇', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖵'), + ('𑖸', '𑗀'), ('𑗘', '𑗝'), ('𑘀', '𑙀'), ('𑙄', '𑙄'), + ('𑙐', '𑙙'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), ('𑜀', '𑜙'), + ('𑜝', '𑜫'), ('𑜰', '𑜹'), ('𑢠', '𑣩'), ('𑣿', '𑣿'), + ('𑨀', '𑨾'), ('𑩇', '𑩇'), ('𑩐', '𑪃'), ('𑪆', '𑪙'), + ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱀'), + ('𑱐', '𑱙'), ('𑱲', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), ('𒀀', '𒎙'), + ('𒐀', '𒑮'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), ('𔐀', '𔙆'), + ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖫐', '𖫭'), + ('𖫰', '𖫴'), ('𖬀', '𖬶'), ('𖭀', '𖭃'), ('𖭐', '𖭙'), + ('𖭣', '𖭷'), ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), + ('𖾏', '𖾟'), ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), + ('𛀀', '𛄞'), ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), + ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𛲝', '𛲞'), ('𝅥', '𝅩'), + ('𝅭', '𝅲'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), + ('𝉂', '𝉄'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𝟎', '𝟿'), + ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), + ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞠀', '𞣄'), + ('𞣐', '𞣖'), ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞸀', '𞸃'), + ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), + ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), + ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), + ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), + ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), + ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), + ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), + ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), + ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), + ('𬺰', '𮯠'), ('丽', '𪘀'), ('󠄀', '󠇯'), +]; + +pub const ID_START: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), + ('ա', 'և'), ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۥ', 'ۦ'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), + ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), + ('ॐ', 'ॐ'), ('क़', 'ॡ'), ('ॱ', 'ঀ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), + ('য়', 'ৡ'), ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੲ', 'ੴ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), + ('ୱ', 'ୱ'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ఽ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), + ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), + ('ವ', 'ಹ'), ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), + ('ೱ', 'ೲ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), + ('ൺ', 'ൿ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'ำ'), + ('เ', 'ๆ'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), + ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), + ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), + ('ອ', 'ະ'), ('າ', 'ຳ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), + ('ໆ', 'ໆ'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), + ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), ('က', 'ဪ'), ('ဿ', 'ဿ'), + ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), + ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), ('ႎ', 'ႎ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢨ'), ('ᢪ', 'ᢪ'), ('ᢰ', 'ᣵ'), + ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), ('ᨠ', 'ᩔ'), ('ᪧ', 'ᪧ'), + ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), ('ᮮ', 'ᮯ'), + ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), ('ᱚ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), ('ᳵ', 'ᳶ'), + ('ᴀ', 'ᶿ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), + ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), + ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), + ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('々', '〇'), + ('〡', '〩'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゛', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), + ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), + ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), + ('ꘐ', 'ꘟ'), ('ꘪ', 'ꘫ'), ('Ꙁ', 'ꙮ'), ('ꙿ', 'ꚝ'), + ('ꚠ', 'ꛯ'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), + ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), + ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), ('ꧏ', 'ꧏ'), ('ꧠ', 'ꧤ'), + ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), + ('ꩄ', 'ꩋ'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫴ'), + ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), + ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯢ'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'יִ'), + ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('A', 'Z'), ('a', 'z'), ('ヲ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), + ('𐍐', '𐍵'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), + ('𐏑', '𐏕'), ('𐐀', '𐒝'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), + ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), + ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), + ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), + ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨀'), + ('𐨐', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐩠', '𐩼'), + ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), ('𐬀', '𐬵'), + ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), ('𐰀', '𐱈'), + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀃', '𑀷'), ('𑂃', '𑂯'), + ('𑃐', '𑃨'), ('𑄃', '𑄦'), ('𑅐', '𑅲'), ('𑅶', '𑅶'), + ('𑆃', '𑆲'), ('𑇁', '𑇄'), ('𑇚', '𑇚'), ('𑇜', '𑇜'), + ('𑈀', '𑈑'), ('𑈓', '𑈫'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), + ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋞'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑍐', '𑍐'), + ('𑍝', '𑍡'), ('𑐀', '𑐴'), ('𑑇', '𑑊'), ('𑒀', '𑒯'), + ('𑓄', '𑓅'), ('𑓇', '𑓇'), ('𑖀', '𑖮'), ('𑗘', '𑗛'), + ('𑘀', '𑘯'), ('𑙄', '𑙄'), ('𑚀', '𑚪'), ('𑜀', '𑜙'), + ('𑢠', '𑣟'), ('𑣿', '𑣿'), ('𑨀', '𑨀'), ('𑨋', '𑨲'), + ('𑨺', '𑨺'), ('𑩐', '𑩐'), ('𑩜', '𑪃'), ('𑪆', '𑪉'), + ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰮'), ('𑱀', '𑱀'), + ('𑱲', '𑲏'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴰'), + ('𑵆', '𑵆'), ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), + ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), + ('𖫐', '𖫭'), ('𖬀', '𖬯'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𞠀', '𞣄'), + ('𞤀', '𞥃'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const IDEOGRAPHIC: &'static [(char, char)] = &[ + ('〆', '〇'), ('〡', '〩'), ('〸', '〺'), ('㐀', '䶵'), + ('一', '鿪'), ('豈', '舘'), ('並', '龎'), ('𗀀', '𘟬'), + ('𘠀', '𘫲'), ('𛅰', '𛋻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const JOIN_CONTROL: &'static [(char, char)] = &[ + ('\u{200c}', '\u{200d}'), +]; + +pub const LOGICAL_ORDER_EXCEPTION: &'static [(char, char)] = &[ + ('เ', 'ไ'), ('ເ', 'ໄ'), ('ᦵ', 'ᦷ'), ('ᦺ', 'ᦺ'), + ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪹ'), ('ꪻ', 'ꪼ'), +]; + +pub const LOWERCASE: &'static [(char, char)] = &[ + ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), ('ß', 'ö'), + ('ø', 'ÿ'), ('ā', 'ā'), ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), + ('ĉ', 'ĉ'), ('ċ', 'ċ'), ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), + ('ē', 'ē'), ('ĕ', 'ĕ'), ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), + ('ĝ', 'ĝ'), ('ğ', 'ğ'), ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), + ('ħ', 'ħ'), ('ĩ', 'ĩ'), ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), + ('ı', 'ı'), ('ij', 'ij'), ('ĵ', 'ĵ'), ('ķ', 'ĸ'), ('ĺ', 'ĺ'), + ('ļ', 'ļ'), ('ľ', 'ľ'), ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), + ('ņ', 'ņ'), ('ň', 'ʼn'), ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), + ('ő', 'ő'), ('œ', 'œ'), ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), + ('ś', 'ś'), ('ŝ', 'ŝ'), ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), + ('ť', 'ť'), ('ŧ', 'ŧ'), ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), + ('ů', 'ů'), ('ű', 'ű'), ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), + ('ź', 'ź'), ('ż', 'ż'), ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), + ('ƈ', 'ƈ'), ('ƌ', 'ƍ'), ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƛ'), + ('ƞ', 'ƞ'), ('ơ', 'ơ'), ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), + ('ƪ', 'ƫ'), ('ƭ', 'ƭ'), ('ư', 'ư'), ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), + ('ƹ', 'ƺ'), ('ƽ', 'ƿ'), ('dž', 'dž'), ('lj', 'lj'), ('nj', 'nj'), + ('ǎ', 'ǎ'), ('ǐ', 'ǐ'), ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), + ('ǘ', 'ǘ'), ('ǚ', 'ǚ'), ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), + ('ǣ', 'ǣ'), ('ǥ', 'ǥ'), ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), + ('ǭ', 'ǭ'), ('ǯ', 'ǰ'), ('dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), + ('ǻ', 'ǻ'), ('ǽ', 'ǽ'), ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), + ('ȅ', 'ȅ'), ('ȇ', 'ȇ'), ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), + ('ȏ', 'ȏ'), ('ȑ', 'ȑ'), ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), + ('ș', 'ș'), ('ț', 'ț'), ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȡ', 'ȡ'), + ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), ('ȧ', 'ȧ'), ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), + ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), ('ȱ', 'ȱ'), ('ȳ', 'ȹ'), ('ȼ', 'ȼ'), + ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), ('ɇ', 'ɇ'), ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), + ('ɍ', 'ɍ'), ('ɏ', 'ʓ'), ('ʕ', 'ʸ'), ('ˀ', 'ˁ'), ('ˠ', 'ˤ'), + ('ͅ', 'ͅ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), ('ͺ', 'ͽ'), + ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), ('ϙ', 'ϙ'), + ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('ϣ', 'ϣ'), + ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), ('ϭ', 'ϭ'), + ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϼ'), ('а', 'џ'), + ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), ('ѩ', 'ѩ'), + ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), ('ѳ', 'ѳ'), + ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), ('ѽ', 'ѽ'), + ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), ('ҏ', 'ҏ'), + ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), ('ҙ', 'ҙ'), + ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), ('ң', 'ң'), + ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), ('ҭ', 'ҭ'), + ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), ('ҷ', 'ҷ'), + ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), ('ӂ', 'ӂ'), + ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), ('ӌ', 'ӌ'), + ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), ('ӗ', 'ӗ'), + ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), ('ӡ', 'ӡ'), + ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), ('ӫ', 'ӫ'), + ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), ('ӵ', 'ӵ'), + ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), ('ӿ', 'ӿ'), + ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), ('ԉ', 'ԉ'), + ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), ('ԓ', 'ԓ'), + ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), ('ԝ', 'ԝ'), + ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), ('ԧ', 'ԧ'), + ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), ('ա', 'և'), + ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᶿ'), ('ḁ', 'ḁ'), + ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), ('ḇ', 'ḇ'), ('ḉ', 'ḉ'), + ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), ('ḏ', 'ḏ'), ('ḑ', 'ḑ'), + ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), ('ḗ', 'ḗ'), ('ḙ', 'ḙ'), + ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), ('ḟ', 'ḟ'), ('ḡ', 'ḡ'), + ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), ('ḧ', 'ḧ'), ('ḩ', 'ḩ'), + ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), ('ḯ', 'ḯ'), ('ḱ', 'ḱ'), + ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), ('ḷ', 'ḷ'), ('ḹ', 'ḹ'), + ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), ('ḿ', 'ḿ'), ('ṁ', 'ṁ'), + ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), ('ṇ', 'ṇ'), ('ṉ', 'ṉ'), + ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), ('ṏ', 'ṏ'), ('ṑ', 'ṑ'), + ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), ('ṗ', 'ṗ'), ('ṙ', 'ṙ'), + ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), ('ṟ', 'ṟ'), ('ṡ', 'ṡ'), + ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), ('ṧ', 'ṧ'), ('ṩ', 'ṩ'), + ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), ('ṯ', 'ṯ'), ('ṱ', 'ṱ'), + ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), ('ṷ', 'ṷ'), ('ṹ', 'ṹ'), + ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), ('ṿ', 'ṿ'), ('ẁ', 'ẁ'), + ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), ('ẇ', 'ẇ'), ('ẉ', 'ẉ'), + ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), ('ẏ', 'ẏ'), ('ẑ', 'ẑ'), + ('ẓ', 'ẓ'), ('ẕ', 'ẝ'), ('ẟ', 'ẟ'), ('ạ', 'ạ'), + ('ả', 'ả'), ('ấ', 'ấ'), ('ầ', 'ầ'), ('ẩ', 'ẩ'), + ('ẫ', 'ẫ'), ('ậ', 'ậ'), ('ắ', 'ắ'), ('ằ', 'ằ'), + ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), ('ặ', 'ặ'), ('ẹ', 'ẹ'), + ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), ('ế', 'ế'), ('ề', 'ề'), + ('ể', 'ể'), ('ễ', 'ễ'), ('ệ', 'ệ'), ('ỉ', 'ỉ'), + ('ị', 'ị'), ('ọ', 'ọ'), ('ỏ', 'ỏ'), ('ố', 'ố'), + ('ồ', 'ồ'), ('ổ', 'ổ'), ('ỗ', 'ỗ'), ('ộ', 'ộ'), + ('ớ', 'ớ'), ('ờ', 'ờ'), ('ở', 'ở'), ('ỡ', 'ỡ'), + ('ợ', 'ợ'), ('ụ', 'ụ'), ('ủ', 'ủ'), ('ứ', 'ứ'), + ('ừ', 'ừ'), ('ử', 'ử'), ('ữ', 'ữ'), ('ự', 'ự'), + ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), ('ỷ', 'ỷ'), ('ỹ', 'ỹ'), + ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), ('ỿ', 'ἇ'), ('ἐ', 'ἕ'), + ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), ('ὀ', 'ὅ'), ('ὐ', 'ὗ'), + ('ὠ', 'ὧ'), ('ὰ', 'ώ'), ('ᾀ', 'ᾇ'), ('ᾐ', 'ᾗ'), + ('ᾠ', 'ᾧ'), ('ᾰ', 'ᾴ'), ('ᾶ', 'ᾷ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), ('ῐ', 'ΐ'), ('ῖ', 'ῗ'), + ('ῠ', 'ῧ'), ('ῲ', 'ῴ'), ('ῶ', 'ῷ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℊ', 'ℊ'), ('ℎ', 'ℏ'), + ('ℓ', 'ℓ'), ('ℯ', 'ℯ'), ('ℴ', 'ℴ'), ('ℹ', 'ℹ'), + ('ℼ', 'ℽ'), ('ⅆ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('ⅰ', 'ⅿ'), + ('ↄ', 'ↄ'), ('ⓐ', 'ⓩ'), ('ⰰ', 'ⱞ'), ('ⱡ', 'ⱡ'), + ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), ('ⱪ', 'ⱪ'), ('ⱬ', 'ⱬ'), + ('ⱱ', 'ⱱ'), ('ⱳ', 'ⱴ'), ('ⱶ', 'ⱽ'), ('ⲁ', 'ⲁ'), + ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), ('ⲉ', 'ⲉ'), + ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), ('ⲑ', 'ⲑ'), + ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), ('ⲙ', 'ⲙ'), + ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), ('ⲡ', 'ⲡ'), + ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), ('ⲩ', 'ⲩ'), + ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), ('ⲱ', 'ⲱ'), + ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), ('ⲹ', 'ⲹ'), + ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), ('ⳁ', 'ⳁ'), + ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), ('ⳉ', 'ⳉ'), + ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), ('ⳑ', 'ⳑ'), + ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), ('ⳙ', 'ⳙ'), + ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), ('ⳡ', 'ⳡ'), + ('ⳣ', 'ⳤ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), ('ⳳ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ꙁ', 'ꙁ'), + ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), ('ꙉ', 'ꙉ'), + ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), ('ꙑ', 'ꙑ'), + ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), ('ꙙ', 'ꙙ'), + ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), ('ꙡ', 'ꙡ'), + ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), ('ꙩ', 'ꙩ'), + ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), ('ꚃ', 'ꚃ'), + ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), ('ꚋ', 'ꚋ'), + ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), ('ꚓ', 'ꚓ'), + ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), ('ꚛ', 'ꚝ'), + ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), ('ꜩ', 'ꜩ'), + ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜱ'), ('ꜳ', 'ꜳ'), + ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), ('ꜻ', 'ꜻ'), + ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), ('ꝃ', 'ꝃ'), + ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), ('ꝋ', 'ꝋ'), + ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), ('ꝓ', 'ꝓ'), + ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), ('ꝛ', 'ꝛ'), + ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), ('ꝣ', 'ꝣ'), + ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), ('ꝫ', 'ꝫ'), + ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝸ'), ('ꝺ', 'ꝺ'), ('ꝼ', 'ꝼ'), + ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), ('ꞃ', 'ꞃ'), ('ꞅ', 'ꞅ'), + ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), ('ꞎ', 'ꞎ'), ('ꞑ', 'ꞑ'), + ('ꞓ', 'ꞕ'), ('ꞗ', 'ꞗ'), ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), + ('ꞝ', 'ꞝ'), ('ꞟ', 'ꞟ'), ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), + ('ꞥ', 'ꞥ'), ('ꞧ', 'ꞧ'), ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), + ('ꞷ', 'ꞷ'), ('ꟸ', 'ꟺ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꮿ'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('a', 'z'), + ('𐐨', '𐑏'), ('𐓘', '𐓻'), ('𐳀', '𐳲'), ('𑣀', '𑣟'), + ('𝐚', '𝐳'), ('𝑎', '𝑔'), ('𝑖', '𝑧'), ('𝒂', '𝒛'), + ('𝒶', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝓏'), + ('𝓪', '𝔃'), ('𝔞', '𝔷'), ('𝕒', '𝕫'), ('𝖆', '𝖟'), + ('𝖺', '𝗓'), ('𝗮', '𝘇'), ('𝘢', '𝘻'), ('𝙖', '𝙯'), + ('𝚊', '𝚥'), ('𝛂', '𝛚'), ('𝛜', '𝛡'), ('𝛼', '𝜔'), + ('𝜖', '𝜛'), ('𝜶', '𝝎'), ('𝝐', '𝝕'), ('𝝰', '𝞈'), + ('𝞊', '𝞏'), ('𝞪', '𝟂'), ('𝟄', '𝟉'), ('𝟋', '𝟋'), + ('𞤢', '𞥃'), +]; + +pub const MATH: &'static [(char, char)] = &[ + ('+', '+'), ('<', '>'), ('^', '^'), ('|', '|'), ('~', '~'), ('¬', '¬'), + ('±', '±'), ('×', '×'), ('÷', '÷'), ('ϐ', 'ϒ'), ('ϕ', 'ϕ'), + ('ϰ', 'ϱ'), ('ϴ', '϶'), ('؆', '؈'), ('‖', '‖'), ('′', '‴'), + ('⁀', '⁀'), ('⁄', '⁄'), ('⁒', '⁒'), ('\u{2061}', '\u{2064}'), + ('⁺', '⁾'), ('₊', '₎'), ('⃐', '⃜'), ('⃡', '⃡'), + ('⃥', '⃦'), ('⃫', '⃯'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), ('ℤ', 'ℤ'), + ('ℨ', '℩'), ('ℬ', 'ℭ'), ('ℯ', 'ℱ'), ('ℳ', 'ℸ'), + ('ℼ', 'ⅉ'), ('⅋', '⅋'), ('←', '↧'), ('↩', '↮'), + ('↰', '↱'), ('↶', '↷'), ('↼', '⇛'), ('⇝', '⇝'), + ('⇤', '⇥'), ('⇴', '⋿'), ('⌈', '⌋'), ('⌠', '⌡'), + ('⍼', '⍼'), ('⎛', '⎵'), ('⎷', '⎷'), ('⏐', '⏐'), + ('⏜', '⏢'), ('■', '□'), ('▮', '▷'), ('▼', '◁'), + ('◆', '◇'), ('◊', '○'), ('●', '◓'), ('◢', '◢'), + ('◤', '◤'), ('◧', '◬'), ('◸', '◿'), ('★', '☆'), + ('♀', '♀'), ('♂', '♂'), ('♠', '♣'), ('♭', '♯'), + ('⟀', '⟿'), ('⤀', '⫿'), ('⬰', '⭄'), ('⭇', '⭌'), + ('﬩', '﬩'), ('﹡', '﹦'), ('﹨', '﹨'), ('+', '+'), + ('<', '>'), ('\', '\'), ('^', '^'), ('|', '|'), + ('~', '~'), ('¬', '¬'), ('←', '↓'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), ('𝟎', '𝟿'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('𞻰', '𞻱'), +]; + +pub const NONCHARACTER_CODE_POINT: &'static [(char, char)] = &[ + ('\u{fdd0}', '\u{fdef}'), ('\u{fffe}', '\u{ffff}'), + ('\u{1fffe}', '\u{1ffff}'), ('\u{2fffe}', '\u{2ffff}'), + ('\u{3fffe}', '\u{3ffff}'), ('\u{4fffe}', '\u{4ffff}'), + ('\u{5fffe}', '\u{5ffff}'), ('\u{6fffe}', '\u{6ffff}'), + ('\u{7fffe}', '\u{7ffff}'), ('\u{8fffe}', '\u{8ffff}'), + ('\u{9fffe}', '\u{9ffff}'), ('\u{afffe}', '\u{affff}'), + ('\u{bfffe}', '\u{bffff}'), ('\u{cfffe}', '\u{cffff}'), + ('\u{dfffe}', '\u{dffff}'), ('\u{efffe}', '\u{effff}'), + ('\u{ffffe}', '\u{fffff}'), ('\u{10fffe}', '\u{10ffff}'), +]; + +pub const OTHER_ALPHABETIC: &'static [(char, char)] = &[ + ('ͅ', 'ͅ'), ('ְ', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), ('ׄ', 'ׅ'), + ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٗ'), ('ٙ', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('ۡ', 'ۤ'), ('ۧ', 'ۨ'), ('ۭ', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', 'ܿ'), ('ަ', 'ް'), ('ࠖ', 'ࠗ'), ('ࠛ', 'ࠣ'), ('ࠥ', 'ࠧ'), + ('ࠩ', 'ࠬ'), ('ࣔ', 'ࣟ'), ('ࣣ', 'ࣩ'), ('ࣰ', 'ः'), + ('ऺ', 'ऻ'), ('ा', 'ौ'), ('ॎ', 'ॏ'), ('ॕ', 'ॗ'), + ('ॢ', 'ॣ'), ('ঁ', 'ঃ'), ('া', 'ৄ'), ('ে', 'ৈ'), + ('ো', 'ৌ'), ('ৗ', 'ৗ'), ('ৢ', 'ৣ'), ('ਁ', 'ਃ'), + ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', 'ੌ'), ('ੑ', 'ੑ'), + ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), ('ઁ', 'ઃ'), ('ા', 'ૅ'), + ('ે', 'ૉ'), ('ો', 'ૌ'), ('ૢ', 'ૣ'), ('ૺ', 'ૼ'), + ('ଁ', 'ଃ'), ('ା', 'ୄ'), ('େ', 'ୈ'), ('ୋ', 'ୌ'), + ('ୖ', 'ୗ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', 'ௌ'), ('ௗ', 'ௗ'), ('ఀ', 'ః'), + ('ా', 'ౄ'), ('ె', 'ై'), ('ొ', 'ౌ'), ('ౕ', 'ౖ'), + ('ౢ', 'ౣ'), ('ಁ', 'ಃ'), ('ಾ', 'ೄ'), ('ೆ', 'ೈ'), + ('ೊ', 'ೌ'), ('ೕ', 'ೖ'), ('ೢ', 'ೣ'), ('ഀ', 'ഃ'), + ('ാ', 'ൄ'), ('െ', 'ൈ'), ('ൊ', 'ൌ'), ('ൗ', 'ൗ'), + ('ൢ', 'ൣ'), ('ං', 'ඃ'), ('ා', 'ු'), ('ූ', 'ූ'), + ('ෘ', 'ෟ'), ('ෲ', 'ෳ'), ('ั', 'ั'), ('ิ', 'ฺ'), + ('ํ', 'ํ'), ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), + ('ໍ', 'ໍ'), ('ཱ', 'ཱྀ'), ('ྍ', 'ྗ'), ('ྙ', 'ྼ'), + ('ါ', 'ံ'), ('း', 'း'), ('ျ', 'ှ'), ('ၖ', 'ၙ'), + ('ၞ', 'ၠ'), ('ၢ', 'ၢ'), ('ၧ', 'ၨ'), ('ၱ', 'ၴ'), + ('ႂ', 'ႆ'), ('ႜ', 'ႝ'), ('፟', '፟'), ('ᜒ', 'ᜓ'), + ('ᜲ', 'ᜳ'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), ('ា', 'ៈ'), + ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤫ'), ('ᤰ', 'ᤸ'), + ('ᨗ', 'ᨛ'), ('ᩕ', 'ᩞ'), ('ᩡ', 'ᩴ'), ('ᬀ', 'ᬄ'), + ('ᬵ', 'ᭃ'), ('ᮀ', 'ᮂ'), ('ᮡ', 'ᮩ'), ('ᮬ', 'ᮭ'), + ('ᯧ', 'ᯱ'), ('ᰤ', 'ᰵ'), ('ᳲ', 'ᳳ'), ('ᷧ', 'ᷴ'), + ('Ⓐ', 'ⓩ'), ('ⷠ', 'ⷿ'), ('ꙴ', 'ꙻ'), ('ꚞ', 'ꚟ'), + ('ꠣ', 'ꠧ'), ('ꢀ', 'ꢁ'), ('ꢴ', 'ꣃ'), ('ꣅ', 'ꣅ'), + ('ꤦ', 'ꤪ'), ('ꥇ', 'ꥒ'), ('ꦀ', 'ꦃ'), ('ꦴ', 'ꦿ'), + ('ꨩ', 'ꨶ'), ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩍ'), ('ꪰ', 'ꪰ'), + ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', 'ꪾ'), ('ꫫ', 'ꫯ'), + ('ꫵ', 'ꫵ'), ('ꯣ', 'ꯪ'), ('ﬞ', 'ﬞ'), ('𐍶', '𐍺'), + ('𐨁', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨏'), ('𑀀', '𑀂'), + ('𑀸', '𑁅'), ('𑂂', '𑂂'), ('𑂰', '𑂸'), ('𑄀', '𑄂'), + ('𑄧', '𑄲'), ('𑆀', '𑆂'), ('𑆳', '𑆿'), ('𑈬', '𑈴'), + ('𑈷', '𑈷'), ('𑈾', '𑈾'), ('𑋟', '𑋨'), ('𑌀', '𑌃'), + ('𑌾', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍌'), ('𑍗', '𑍗'), + ('𑍢', '𑍣'), ('𑐵', '𑑁'), ('𑑃', '𑑅'), ('𑒰', '𑓁'), + ('𑖯', '𑖵'), ('𑖸', '𑖾'), ('𑗜', '𑗝'), ('𑘰', '𑘾'), + ('𑙀', '𑙀'), ('𑚫', '𑚵'), ('𑜝', '𑜪'), ('𑨁', '𑨊'), + ('𑨵', '𑨹'), ('𑨻', '𑨾'), ('𑩑', '𑩛'), ('𑪊', '𑪗'), + ('𑰯', '𑰶'), ('𑰸', '𑰾'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), + ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵁'), + ('𑵃', '𑵃'), ('𑵇', '𑵇'), ('𖬰', '𖬶'), ('𖽑', '𖽾'), + ('𛲞', '𛲞'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞥇', '𞥇'), ('🄰', '🅉'), + ('🅐', '🅩'), ('🅰', '🆉'), +]; + +pub const OTHER_DEFAULT_IGNORABLE_CODE_POINT: &'static [(char, char)] = &[ + ('͏', '͏'), ('ᅟ', 'ᅠ'), ('឴', '឵'), ('\u{2065}', '\u{2065}'), + ('ㅤ', 'ㅤ'), ('ᅠ', 'ᅠ'), ('\u{fff0}', '\u{fff8}'), + ('\u{e0000}', '\u{e0000}'), ('\u{e0002}', '\u{e001f}'), + ('\u{e0080}', '\u{e00ff}'), ('\u{e01f0}', '\u{e0fff}'), +]; + +pub const OTHER_GRAPHEME_EXTEND: &'static [(char, char)] = &[ + ('া', 'া'), ('ৗ', 'ৗ'), ('ା', 'ା'), ('ୗ', 'ୗ'), + ('ா', 'ா'), ('ௗ', 'ௗ'), ('ೂ', 'ೂ'), ('ೕ', 'ೖ'), + ('ാ', 'ാ'), ('ൗ', 'ൗ'), ('ා', 'ා'), ('ෟ', 'ෟ'), + ('\u{200c}', '\u{200c}'), ('〮', '〯'), ('゙', '゚'), ('𑌾', '𑌾'), + ('𑍗', '𑍗'), ('𑒰', '𑒰'), ('𑒽', '𑒽'), ('𑖯', '𑖯'), + ('𝅥', '𝅥'), ('𝅮', '𝅲'), ('\u{e0020}', '\u{e007f}'), +]; + +pub const OTHER_ID_CONTINUE: &'static [(char, char)] = &[ + ('·', '·'), ('·', '·'), ('፩', '፱'), ('᧚', '᧚'), +]; + +pub const OTHER_ID_START: &'static [(char, char)] = &[ + ('ᢅ', 'ᢆ'), ('℘', '℘'), ('℮', '℮'), ('゛', '゜'), +]; + +pub const OTHER_LOWERCASE: &'static [(char, char)] = &[ + ('ª', 'ª'), ('º', 'º'), ('ʰ', 'ʸ'), ('ˀ', 'ˁ'), ('ˠ', 'ˤ'), + ('ͅ', 'ͅ'), ('ͺ', 'ͺ'), ('ᴬ', 'ᵪ'), ('ᵸ', 'ᵸ'), ('ᶛ', 'ᶿ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ⅰ', 'ⅿ'), + ('ⓐ', 'ⓩ'), ('ⱼ', 'ⱽ'), ('ꚜ', 'ꚝ'), ('ꝰ', 'ꝰ'), + ('ꟸ', 'ꟹ'), ('ꭜ', 'ꭟ'), +]; + +pub const OTHER_MATH: &'static [(char, char)] = &[ + ('^', '^'), ('ϐ', 'ϒ'), ('ϕ', 'ϕ'), ('ϰ', 'ϱ'), ('ϴ', 'ϵ'), + ('‖', '‖'), ('′', '‴'), ('⁀', '⁀'), ('\u{2061}', '\u{2064}'), + ('⁽', '⁾'), ('₍', '₎'), ('⃐', '⃜'), ('⃡', '⃡'), + ('⃥', '⃦'), ('⃫', '⃯'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), + ('ℨ', '℩'), ('ℬ', 'ℭ'), ('ℯ', 'ℱ'), ('ℳ', 'ℸ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('↕', '↙'), ('↜', '↟'), + ('↡', '↢'), ('↤', '↥'), ('↧', '↧'), ('↩', '↭'), + ('↰', '↱'), ('↶', '↷'), ('↼', '⇍'), ('⇐', '⇑'), + ('⇓', '⇓'), ('⇕', '⇛'), ('⇝', '⇝'), ('⇤', '⇥'), + ('⌈', '⌋'), ('⎴', '⎵'), ('⎷', '⎷'), ('⏐', '⏐'), + ('⏢', '⏢'), ('■', '□'), ('▮', '▶'), ('▼', '◀'), + ('◆', '◇'), ('◊', '○'), ('●', '◓'), ('◢', '◢'), + ('◤', '◤'), ('◧', '◬'), ('★', '☆'), ('♀', '♀'), + ('♂', '♂'), ('♠', '♣'), ('♭', '♮'), ('⟅', '⟆'), + ('⟦', '⟯'), ('⦃', '⦘'), ('⧘', '⧛'), ('⧼', '⧽'), + ('﹡', '﹡'), ('﹣', '﹣'), ('﹨', '﹨'), ('\', '\'), + ('^', '^'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𝟎', '𝟿'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), +]; + +pub const OTHER_UPPERCASE: &'static [(char, char)] = &[ + ('Ⅰ', 'Ⅿ'), ('Ⓐ', 'Ⓩ'), ('🄰', '🅉'), ('🅐', '🅩'), + ('🅰', '🆉'), +]; + +pub const PATTERN_SYNTAX: &'static [(char, char)] = &[ + ('!', '/'), (':', '@'), ('[', '^'), ('`', '`'), ('{', '~'), ('¡', '§'), + ('©', '©'), ('«', '¬'), ('®', '®'), ('°', '±'), ('¶', '¶'), + ('»', '»'), ('¿', '¿'), ('×', '×'), ('÷', '÷'), ('‐', '‧'), + ('‰', '‾'), ('⁁', '⁓'), ('⁕', '⁞'), ('←', '\u{245f}'), + ('─', '❵'), ('➔', '\u{2bff}'), ('⸀', '\u{2e7f}'), ('、', '〃'), + ('〈', '〠'), ('〰', '〰'), ('﴾', '﴿'), ('﹅', '﹆'), +]; + +pub const PATTERN_WHITE_SPACE: &'static [(char, char)] = &[ + ('\t', '\r'), (' ', ' '), ('\u{85}', '\u{85}'), ('\u{200e}', '\u{200f}'), + ('\u{2028}', '\u{2029}'), +]; + +pub const PREPENDED_CONCATENATION_MARK: &'static [(char, char)] = &[ + ('\u{600}', '\u{605}'), ('\u{6dd}', '\u{6dd}'), ('\u{70f}', '\u{70f}'), + ('\u{8e2}', '\u{8e2}'), ('\u{110bd}', '\u{110bd}'), +]; + +pub const QUOTATION_MARK: &'static [(char, char)] = &[ + ('\"', '\"'), ('\'', '\''), ('«', '«'), ('»', '»'), ('‘', '‟'), + ('‹', '›'), ('⹂', '⹂'), ('「', '』'), ('〝', '〟'), + ('﹁', '﹄'), ('"', '"'), (''', '''), ('「', '」'), +]; + +pub const RADICAL: &'static [(char, char)] = &[ + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), +]; + +pub const REGIONAL_INDICATOR: &'static [(char, char)] = &[ + ('🇦', '🇿'), +]; + +pub const SENTENCE_TERMINAL: &'static [(char, char)] = &[ + ('!', '!'), ('.', '.'), ('?', '?'), ('։', '։'), ('؟', '؟'), + ('۔', '۔'), ('܀', '܂'), ('߹', '߹'), ('।', '॥'), ('၊', '။'), + ('።', '።'), ('፧', '፨'), ('᙮', '᙮'), ('᜵', '᜶'), + ('᠃', '᠃'), ('᠉', '᠉'), ('᥄', '᥅'), ('᪨', '᪫'), + ('᭚', '᭛'), ('᭞', '᭟'), ('᰻', '᰼'), ('᱾', '᱿'), + ('‼', '‽'), ('⁇', '⁉'), ('⸮', '⸮'), ('⸼', '⸼'), + ('。', '。'), ('꓿', '꓿'), ('꘎', '꘏'), ('꛳', '꛳'), + ('꛷', '꛷'), ('꡶', '꡷'), ('꣎', '꣏'), ('꤯', '꤯'), + ('꧈', '꧉'), ('꩝', '꩟'), ('꫰', '꫱'), ('꯫', '꯫'), + ('﹒', '﹒'), ('﹖', '﹗'), ('!', '!'), ('.', '.'), + ('?', '?'), ('。', '。'), ('𐩖', '𐩗'), ('𑁇', '𑁈'), + ('𑂾', '𑃁'), ('𑅁', '𑅃'), ('𑇅', '𑇆'), ('𑇍', '𑇍'), + ('𑇞', '𑇟'), ('𑈸', '𑈹'), ('𑈻', '𑈼'), ('𑊩', '𑊩'), + ('𑑋', '𑑌'), ('𑗂', '𑗃'), ('𑗉', '𑗗'), ('𑙁', '𑙂'), + ('𑜼', '𑜾'), ('𑩂', '𑩃'), ('𑪛', '𑪜'), ('𑱁', '𑱂'), + ('𖩮', '𖩯'), ('𖫵', '𖫵'), ('𖬷', '𖬸'), ('𖭄', '𖭄'), + ('𛲟', '𛲟'), ('𝪈', '𝪈'), +]; + +pub const SOFT_DOTTED: &'static [(char, char)] = &[ + ('i', 'j'), ('į', 'į'), ('ɉ', 'ɉ'), ('ɨ', 'ɨ'), ('ʝ', 'ʝ'), + ('ʲ', 'ʲ'), ('ϳ', 'ϳ'), ('і', 'і'), ('ј', 'ј'), ('ᵢ', 'ᵢ'), + ('ᶖ', 'ᶖ'), ('ᶤ', 'ᶤ'), ('ᶨ', 'ᶨ'), ('ḭ', 'ḭ'), + ('ị', 'ị'), ('ⁱ', 'ⁱ'), ('ⅈ', 'ⅉ'), ('ⱼ', 'ⱼ'), + ('𝐢', '𝐣'), ('𝑖', '𝑗'), ('𝒊', '𝒋'), ('𝒾', '𝒿'), + ('𝓲', '𝓳'), ('𝔦', '𝔧'), ('𝕚', '𝕛'), ('𝖎', '𝖏'), + ('𝗂', '𝗃'), ('𝗶', '𝗷'), ('𝘪', '𝘫'), ('𝙞', '𝙟'), + ('𝚒', '𝚓'), +]; + +pub const TERMINAL_PUNCTUATION: &'static [(char, char)] = &[ + ('!', '!'), (',', ','), ('.', '.'), (':', ';'), ('?', '?'), (';', ';'), + ('·', '·'), ('։', '։'), ('׃', '׃'), ('،', '،'), ('؛', '؛'), + ('؟', '؟'), ('۔', '۔'), ('܀', '܊'), ('܌', '܌'), ('߸', '߹'), + ('࠰', '࠾'), ('࡞', '࡞'), ('।', '॥'), ('๚', '๛'), + ('༈', '༈'), ('།', '༒'), ('၊', '။'), ('፡', '፨'), + ('᙭', '᙮'), ('᛫', '᛭'), ('᜵', '᜶'), ('។', '៖'), + ('៚', '៚'), ('᠂', '᠅'), ('᠈', '᠉'), ('᥄', '᥅'), + ('᪨', '᪫'), ('᭚', '᭛'), ('᭝', '᭟'), ('᰻', '᰿'), + ('᱾', '᱿'), ('‼', '‽'), ('⁇', '⁉'), ('⸮', '⸮'), + ('⸼', '⸼'), ('⹁', '⹁'), ('、', '。'), ('꓾', '꓿'), + ('꘍', '꘏'), ('꛳', '꛷'), ('꡶', '꡷'), ('꣎', '꣏'), + ('꤯', '꤯'), ('꧇', '꧉'), ('꩝', '꩟'), ('꫟', '꫟'), + ('꫰', '꫱'), ('꯫', '꯫'), ('﹐', '﹒'), ('﹔', '﹗'), + ('!', '!'), (',', ','), ('.', '.'), (':', ';'), + ('?', '?'), ('。', '。'), ('、', '、'), ('𐎟', '𐎟'), + ('𐏐', '𐏐'), ('𐡗', '𐡗'), ('𐤟', '𐤟'), ('𐩖', '𐩗'), + ('𐫰', '𐫵'), ('𐬺', '𐬿'), ('𐮙', '𐮜'), ('𑁇', '𑁍'), + ('𑂾', '𑃁'), ('𑅁', '𑅃'), ('𑇅', '𑇆'), ('𑇍', '𑇍'), + ('𑇞', '𑇟'), ('𑈸', '𑈼'), ('𑊩', '𑊩'), ('𑑋', '𑑍'), + ('𑑛', '𑑛'), ('𑗂', '𑗅'), ('𑗉', '𑗗'), ('𑙁', '𑙂'), + ('𑜼', '𑜾'), ('𑩂', '𑩃'), ('𑪛', '𑪜'), ('𑪡', '𑪢'), + ('𑱁', '𑱃'), ('𑱱', '𑱱'), ('𒑰', '𒑴'), ('𖩮', '𖩯'), + ('𖫵', '𖫵'), ('𖬷', '𖬹'), ('𖭄', '𖭄'), ('𛲟', '𛲟'), + ('𝪇', '𝪊'), +]; + +pub const UNIFIED_IDEOGRAPH: &'static [(char, char)] = &[ + ('㐀', '䶵'), ('一', '鿪'), ('﨎', '﨏'), ('﨑', '﨑'), + ('﨓', '﨔'), ('﨟', '﨟'), ('﨡', '﨡'), ('﨣', '﨤'), + ('﨧', '﨩'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), + ('𫠠', '𬺡'), ('𬺰', '𮯠'), +]; + +pub const UPPERCASE: &'static [(char, char)] = &[ + ('A', 'Z'), ('À', 'Ö'), ('Ø', 'Þ'), ('Ā', 'Ā'), ('Ă', 'Ă'), + ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), ('Č', 'Č'), + ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), ('Ė', 'Ė'), + ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), ('Ġ', 'Ġ'), + ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), ('Ī', 'Ī'), + ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), ('Ĵ', 'Ĵ'), + ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), ('Ŀ', 'Ŀ'), + ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), ('Ŋ', 'Ŋ'), + ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), ('Ŕ', 'Ŕ'), + ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), ('Ş', 'Ş'), + ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), ('Ũ', 'Ũ'), + ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), ('Ų', 'Ų'), + ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), ('Ž', 'Ž'), + ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), + ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), + ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), + ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), ('Ƽ', 'Ƽ'), ('DŽ', 'DŽ'), + ('LJ', 'LJ'), ('NJ', 'NJ'), ('Ǎ', 'Ǎ'), ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), + ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), + ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), + ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), ('Ǯ', 'Ǯ'), ('DZ', 'DZ'), + ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), + ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), + ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), + ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), + ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), + ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), + ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), + ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), ('Ɏ', 'Ɏ'), ('Ͱ', 'Ͱ'), + ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ώ'), ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('Ϗ', 'Ϗ'), + ('ϒ', 'ϔ'), ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), + ('Ϡ', 'Ϡ'), ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), + ('Ϫ', 'Ϫ'), ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϴ', 'ϴ'), ('Ϸ', 'Ϸ'), + ('Ϲ', 'Ϻ'), ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), + ('Ѧ', 'Ѧ'), ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), + ('Ѱ', 'Ѱ'), ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), + ('Ѻ', 'Ѻ'), ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), + ('Ҍ', 'Ҍ'), ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), + ('Җ', 'Җ'), ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), + ('Ҡ', 'Ҡ'), ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), + ('Ҫ', 'Ҫ'), ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), + ('Ҵ', 'Ҵ'), ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), + ('Ҿ', 'Ҿ'), ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), + ('Ӊ', 'Ӊ'), ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), + ('Ӕ', 'Ӕ'), ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), + ('Ӟ', 'Ӟ'), ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), + ('Ө', 'Ө'), ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), + ('Ӳ', 'Ӳ'), ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), + ('Ӽ', 'Ӽ'), ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), + ('Ԇ', 'Ԇ'), ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), + ('Ԑ', 'Ԑ'), ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), + ('Ԛ', 'Ԛ'), ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), + ('Ԥ', 'Ԥ'), ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), + ('Ԯ', 'Ԯ'), ('Ա', 'Ֆ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('Ḁ', 'Ḁ'), ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), + ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), + ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), + ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), + ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), + ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), + ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), + ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), + ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), + ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), + ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), + ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), + ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), + ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), + ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), + ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), + ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), + ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), + ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), + ('ẞ', 'ẞ'), ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), + ('Ầ', 'Ầ'), ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), + ('Ắ', 'Ắ'), ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), + ('Ặ', 'Ặ'), ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), + ('Ế', 'Ế'), ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), + ('Ệ', 'Ệ'), ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), + ('Ỏ', 'Ỏ'), ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), + ('Ỗ', 'Ỗ'), ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), + ('Ở', 'Ở'), ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), + ('Ủ', 'Ủ'), ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), + ('Ữ', 'Ữ'), ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), + ('Ỷ', 'Ỷ'), ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), + ('Ỿ', 'Ỿ'), ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), + ('Ἰ', 'Ἷ'), ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('Ᾰ', 'Ά'), + ('Ὲ', 'Ή'), ('Ῐ', 'Ί'), ('Ῠ', 'Ῥ'), ('Ὸ', 'Ώ'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℋ', 'ℍ'), ('ℐ', 'ℒ'), + ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), + ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℰ', 'ℳ'), ('ℾ', 'ℿ'), + ('ⅅ', 'ⅅ'), ('Ⅰ', 'Ⅿ'), ('Ↄ', 'Ↄ'), ('Ⓐ', 'Ⓩ'), + ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), ('Ɫ', 'Ɽ'), ('Ⱨ', 'Ⱨ'), + ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), ('Ɑ', 'Ɒ'), ('Ⱳ', 'Ⱳ'), + ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), ('Ⲃ', 'Ⲃ'), ('Ⲅ', 'Ⲅ'), + ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), ('Ⲋ', 'Ⲋ'), ('Ⲍ', 'Ⲍ'), + ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), ('Ⲓ', 'Ⲓ'), ('Ⲕ', 'Ⲕ'), + ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), ('Ⲛ', 'Ⲛ'), ('Ⲝ', 'Ⲝ'), + ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), ('Ⲣ', 'Ⲣ'), ('Ⲥ', 'Ⲥ'), + ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), ('Ⲫ', 'Ⲫ'), ('Ⲭ', 'Ⲭ'), + ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), ('Ⲳ', 'Ⲳ'), ('Ⲵ', 'Ⲵ'), + ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), ('Ⲻ', 'Ⲻ'), ('Ⲽ', 'Ⲽ'), + ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), ('Ⳃ', 'Ⳃ'), ('Ⳅ', 'Ⳅ'), + ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), ('Ⳋ', 'Ⳋ'), ('Ⳍ', 'Ⳍ'), + ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), ('Ⳓ', 'Ⳓ'), ('Ⳕ', 'Ⳕ'), + ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), ('Ⳛ', 'Ⳛ'), ('Ⳝ', 'Ⳝ'), + ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), ('Ⳣ', 'Ⳣ'), ('Ⳬ', 'Ⳬ'), + ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), ('Ꙁ', 'Ꙁ'), ('Ꙃ', 'Ꙃ'), + ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), ('Ꙉ', 'Ꙉ'), ('Ꙋ', 'Ꙋ'), + ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), ('Ꙑ', 'Ꙑ'), ('Ꙓ', 'Ꙓ'), + ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), ('Ꙙ', 'Ꙙ'), ('Ꙛ', 'Ꙛ'), + ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), ('Ꙡ', 'Ꙡ'), ('Ꙣ', 'Ꙣ'), + ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), ('Ꙩ', 'Ꙩ'), ('Ꙫ', 'Ꙫ'), + ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), ('Ꚃ', 'Ꚃ'), ('Ꚅ', 'Ꚅ'), + ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), ('Ꚋ', 'Ꚋ'), ('Ꚍ', 'Ꚍ'), + ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), ('Ꚓ', 'Ꚓ'), ('Ꚕ', 'Ꚕ'), + ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), ('Ꚛ', 'Ꚛ'), ('Ꜣ', 'Ꜣ'), + ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), ('Ꜩ', 'Ꜩ'), ('Ꜫ', 'Ꜫ'), + ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), ('Ꜳ', 'Ꜳ'), ('Ꜵ', 'Ꜵ'), + ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), ('Ꜻ', 'Ꜻ'), ('Ꜽ', 'Ꜽ'), + ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), ('Ꝃ', 'Ꝃ'), ('Ꝅ', 'Ꝅ'), + ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), ('Ꝋ', 'Ꝋ'), ('Ꝍ', 'Ꝍ'), + ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), ('Ꝓ', 'Ꝓ'), ('Ꝕ', 'Ꝕ'), + ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), ('Ꝛ', 'Ꝛ'), ('Ꝝ', 'Ꝝ'), + ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), ('Ꝣ', 'Ꝣ'), ('Ꝥ', 'Ꝥ'), + ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), ('Ꝫ', 'Ꝫ'), ('Ꝭ', 'Ꝭ'), + ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), ('Ꝼ', 'Ꝼ'), ('Ᵹ', 'Ꝿ'), + ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), ('Ꞅ', 'Ꞅ'), ('Ꞇ', 'Ꞇ'), + ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), ('Ꞑ', 'Ꞑ'), ('Ꞓ', 'Ꞓ'), + ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), ('Ꞛ', 'Ꞛ'), ('Ꞝ', 'Ꞝ'), + ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), ('Ꞣ', 'Ꞣ'), ('Ꞥ', 'Ꞥ'), + ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), ('Ɦ', 'Ɪ'), ('Ʞ', 'Ꞵ'), + ('Ꞷ', 'Ꞷ'), ('A', 'Z'), ('𐐀', '𐐧'), ('𐒰', '𐓓'), + ('𐲀', '𐲲'), ('𑢠', '𑢿'), ('𝐀', '𝐙'), ('𝐴', '𝑍'), + ('𝑨', '𝒁'), ('𝒜', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒵'), ('𝓐', '𝓩'), + ('𝔄', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔸', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕬', '𝖅'), ('𝖠', '𝖹'), ('𝗔', '𝗭'), + ('𝘈', '𝘡'), ('𝘼', '𝙕'), ('𝙰', '𝚉'), ('𝚨', '𝛀'), + ('𝛢', '𝛺'), ('𝜜', '𝜴'), ('𝝖', '𝝮'), ('𝞐', '𝞨'), + ('𝟊', '𝟊'), ('𞤀', '𞤡'), ('🄰', '🅉'), ('🅐', '🅩'), + ('🅰', '🆉'), +]; + +pub const VARIATION_SELECTOR: &'static [(char, char)] = &[ + ('᠋', '᠍'), ('︀', '️'), ('󠄀', '󠇯'), +]; + +pub const WHITE_SPACE: &'static [(char, char)] = &[ + ('\t', '\r'), (' ', ' '), ('\u{85}', '\u{85}'), ('\u{a0}', '\u{a0}'), + ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), + ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), + ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), +]; + +pub const XID_CONTINUE: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), + ('·', '·'), ('º', 'º'), ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), + ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('̀', 'ʹ'), + ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('҃', '҇'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), ('ա', 'և'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), + ('ׁ', 'ׂ'), ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), + ('ؐ', 'ؚ'), ('ؠ', '٩'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('۟', 'ۨ'), + ('۪', 'ۼ'), ('ۿ', 'ۿ'), ('ܐ', '݊'), ('ݍ', 'ޱ'), ('߀', 'ߵ'), + ('ߺ', 'ߺ'), ('ࠀ', '࠭'), ('ࡀ', '࡛'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), ('ࣣ', 'ॣ'), + ('०', '९'), ('ॱ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), + ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), + ('়', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), + ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', 'ৱ'), ('ৼ', 'ৼ'), + ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), + ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), + ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), + ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), + ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), + ('ે', 'ૉ'), ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), + ('૦', '૯'), ('ૹ', '૿'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୯'), + ('ୱ', 'ୱ'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), + ('௦', '௯'), ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), + ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), + ('౦', '౯'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), + ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), + ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), + ('ೠ', 'ೣ'), ('೦', '೯'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), + ('ൊ', 'ൎ'), ('ൔ', 'ൗ'), ('ൟ', 'ൣ'), ('൦', '൯'), + ('ൺ', 'ൿ'), ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), + ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), + ('ෲ', 'ෳ'), ('ก', 'ฺ'), ('เ', '๎'), ('๐', '๙'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('༘', '༙'), + ('༠', '༩'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('༾', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', '྄'), ('྆', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('က', '၉'), ('ၐ', 'ႝ'), + ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), + ('ჼ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፟'), ('፩', '፱'), ('ᎀ', 'ᎏ'), ('Ꭰ', 'Ᏽ'), + ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), + ('ᜠ', '᜴'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), + ('ᝲ', 'ᝳ'), ('ក', '៓'), ('ៗ', 'ៗ'), ('ៜ', '៝'), + ('០', '៩'), ('᠋', '᠍'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), + ('ᢀ', 'ᢪ'), ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), + ('ᤰ', '᤻'), ('᥆', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), + ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), ('ᪧ', 'ᪧ'), + ('᪰', '᪽'), ('ᬀ', 'ᭋ'), ('᭐', '᭙'), ('᭫', '᭳'), + ('ᮀ', '᯳'), ('ᰀ', '᰷'), ('᱀', '᱉'), ('ᱍ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('᳐', '᳒'), ('᳔', '᳹'), ('ᴀ', '᷹'), + ('᷻', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('‿', '⁀'), + ('⁔', '⁔'), ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), + ('⃐', '⃜'), ('⃡', '⃡'), ('⃥', '⃰'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), + ('ⵯ', 'ⵯ'), ('⵿', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), + ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), + ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ⷠ', 'ⷿ'), ('々', '〇'), + ('〡', '〯'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゙', '゚'), ('ゝ', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), + ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), + ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), + ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘫ'), ('Ꙁ', '꙯'), ('ꙴ', '꙽'), + ('ꙿ', '꛱'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠧ'), ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣅ'), + ('꣐', '꣙'), ('꣠', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), + ('꤀', '꤭'), ('ꤰ', '꥓'), ('ꥠ', 'ꥼ'), ('ꦀ', '꧀'), + ('ꧏ', '꧙'), ('ꧠ', 'ꧾ'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), + ('꩐', '꩙'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꫂ'), ('ꫛ', 'ꫝ'), + ('ꫠ', 'ꫯ'), ('ꫲ', '꫶'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), + ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), + ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯪ'), ('꯬', '꯭'), ('꯰', '꯹'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'ﬨ'), + ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), + ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﱝ'), ('ﱤ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷹ'), ('︀', '️'), + ('︠', '︯'), ('︳', '︴'), ('﹍', '﹏'), ('ﹱ', 'ﹱ'), + ('ﹳ', 'ﹳ'), ('ﹷ', 'ﹷ'), ('ﹹ', 'ﹹ'), ('ﹻ', 'ﹻ'), + ('ﹽ', 'ﹽ'), ('ﹿ', 'ﻼ'), ('0', '9'), ('A', 'Z'), + ('_', '_'), ('a', 'z'), ('ヲ', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), + ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), + ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), ('𐇽', '𐇽'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐋠', '𐋠'), ('𐌀', '𐌟'), + ('𐌭', '𐍊'), ('𐍐', '𐍺'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), + ('𐏈', '𐏏'), ('𐏑', '𐏕'), ('𐐀', '𐒝'), ('𐒠', '𐒩'), + ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐔀', '𐔧'), ('𐔰', '𐕣'), + ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), + ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), + ('𐠿', '𐡕'), ('𐡠', '𐡶'), ('𐢀', '𐢞'), ('𐣠', '𐣲'), + ('𐣴', '𐣵'), ('𐤀', '𐤕'), ('𐤠', '𐤹'), ('𐦀', '𐦷'), + ('𐦾', '𐦿'), ('𐨀', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨓'), + ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫦'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀀', '𑁆'), + ('𑁦', '𑁯'), ('𑁿', '𑂺'), ('𑃐', '𑃨'), ('𑃰', '𑃹'), + ('𑄀', '𑄴'), ('𑄶', '𑄿'), ('𑅐', '𑅳'), ('𑅶', '𑅶'), + ('𑆀', '𑇄'), ('𑇊', '𑇌'), ('𑇐', '𑇚'), ('𑇜', '𑇜'), + ('𑈀', '𑈑'), ('𑈓', '𑈷'), ('𑈾', '𑈾'), ('𑊀', '𑊆'), + ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊨'), + ('𑊰', '𑋪'), ('𑋰', '𑋹'), ('𑌀', '𑌃'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), + ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), ('𑐀', '𑑊'), ('𑑐', '𑑙'), ('𑒀', '𑓅'), + ('𑓇', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖵'), ('𑖸', '𑗀'), + ('𑗘', '𑗝'), ('𑘀', '𑙀'), ('𑙄', '𑙄'), ('𑙐', '𑙙'), + ('𑚀', '𑚷'), ('𑛀', '𑛉'), ('𑜀', '𑜙'), ('𑜝', '𑜫'), + ('𑜰', '𑜹'), ('𑢠', '𑣩'), ('𑣿', '𑣿'), ('𑨀', '𑨾'), + ('𑩇', '𑩇'), ('𑩐', '𑪃'), ('𑪆', '𑪙'), ('𑫀', '𑫸'), + ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱀'), ('𑱐', '𑱙'), + ('𑱲', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), ('𑴀', '𑴆'), + ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), + ('𑴿', '𑵇'), ('𑵐', '𑵙'), ('𒀀', '𒎙'), ('𒐀', '𒑮'), + ('𒒀', '𒕃'), ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), + ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖫐', '𖫭'), ('𖫰', '𖫴'), + ('𖬀', '𖬶'), ('𖭀', '𖭃'), ('𖭐', '𖭙'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾏', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𛲝', '𛲞'), ('𝅥', '𝅩'), ('𝅭', '𝅲'), + ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), + ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), + ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), + ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝛀'), + ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), ('𝜖', '𝜴'), + ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), ('𝞊', '𝞨'), + ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𝟎', '𝟿'), ('𝨀', '𝨶'), + ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), ('𝪛', '𝪟'), + ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞠀', '𞣄'), ('𞣐', '𞣖'), + ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), + ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), + ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), + ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), + ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), + ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), + ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), + ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), + ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𠀀', '𪛖'), + ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), + ('丽', '𪘀'), ('󠄀', '󠇯'), +]; + +pub const XID_START: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), + ('ա', 'և'), ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۥ', 'ۦ'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), + ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), + ('ॐ', 'ॐ'), ('क़', 'ॡ'), ('ॱ', 'ঀ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), + ('য়', 'ৡ'), ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੲ', 'ੴ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), + ('ୱ', 'ୱ'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ఽ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), + ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), + ('ವ', 'ಹ'), ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), + ('ೱ', 'ೲ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), + ('ൺ', 'ൿ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'า'), + ('เ', 'ๆ'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), + ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), + ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), + ('ອ', 'ະ'), ('າ', 'າ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), + ('ໆ', 'ໆ'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), + ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), ('က', 'ဪ'), ('ဿ', 'ဿ'), + ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), + ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), ('ႎ', 'ႎ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢨ'), ('ᢪ', 'ᢪ'), ('ᢰ', 'ᣵ'), + ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), ('ᨠ', 'ᩔ'), ('ᪧ', 'ᪧ'), + ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), ('ᮮ', 'ᮯ'), + ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), ('ᱚ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), ('ᳵ', 'ᳶ'), + ('ᴀ', 'ᶿ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), + ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), + ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), + ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('々', '〇'), + ('〡', '〩'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('ゝ', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), + ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), + ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), + ('ꘐ', 'ꘟ'), ('ꘪ', 'ꘫ'), ('Ꙁ', 'ꙮ'), ('ꙿ', 'ꚝ'), + ('ꚠ', 'ꛯ'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), + ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), + ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), ('ꧏ', 'ꧏ'), ('ꧠ', 'ꧤ'), + ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), + ('ꩄ', 'ꩋ'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫴ'), + ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), + ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯢ'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'יִ'), + ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﱝ'), + ('ﱤ', 'ﴽ'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷹ'), + ('ﹱ', 'ﹱ'), ('ﹳ', 'ﹳ'), ('ﹷ', 'ﹷ'), ('ﹹ', 'ﹹ'), + ('ﹻ', 'ﹻ'), ('ﹽ', 'ﹽ'), ('ﹿ', 'ﻼ'), ('A', 'Z'), + ('a', 'z'), ('ヲ', 'ン'), ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), + ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), + ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), ('𐊀', '𐊜'), + ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), ('𐍐', '𐍵'), + ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐏑', '𐏕'), + ('𐐀', '𐒝'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐔀', '𐔧'), + ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), + ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), + ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), ('𐢀', '𐢞'), + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), ('𐤠', '𐤹'), + ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨀'), ('𐨐', '𐨓'), + ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐩠', '𐩼'), ('𐪀', '𐪜'), + ('𐫀', '𐫇'), ('𐫉', '𐫤'), ('𐬀', '𐬵'), ('𐭀', '𐭕'), + ('𐭠', '𐭲'), ('𐮀', '𐮑'), ('𐰀', '𐱈'), ('𐲀', '𐲲'), + ('𐳀', '𐳲'), ('𑀃', '𑀷'), ('𑂃', '𑂯'), ('𑃐', '𑃨'), + ('𑄃', '𑄦'), ('𑅐', '𑅲'), ('𑅶', '𑅶'), ('𑆃', '𑆲'), + ('𑇁', '𑇄'), ('𑇚', '𑇚'), ('𑇜', '𑇜'), ('𑈀', '𑈑'), + ('𑈓', '𑈫'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋞'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑍐', '𑍐'), ('𑍝', '𑍡'), + ('𑐀', '𑐴'), ('𑑇', '𑑊'), ('𑒀', '𑒯'), ('𑓄', '𑓅'), + ('𑓇', '𑓇'), ('𑖀', '𑖮'), ('𑗘', '𑗛'), ('𑘀', '𑘯'), + ('𑙄', '𑙄'), ('𑚀', '𑚪'), ('𑜀', '𑜙'), ('𑢠', '𑣟'), + ('𑣿', '𑣿'), ('𑨀', '𑨀'), ('𑨋', '𑨲'), ('𑨺', '𑨺'), + ('𑩐', '𑩐'), ('𑩜', '𑪃'), ('𑪆', '𑪉'), ('𑫀', '𑫸'), + ('𑰀', '𑰈'), ('𑰊', '𑰮'), ('𑱀', '𑱀'), ('𑱲', '𑲏'), + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴰'), ('𑵆', '𑵆'), + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), + ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖫐', '𖫭'), + ('𖬀', '𖬯'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), ('𖭽', '𖮏'), + ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𖾓', '𖾟'), ('𖿠', '𖿡'), + ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), ('𛅰', '𛋻'), + ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), + ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), + ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), + ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝛀'), + ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), ('𝜖', '𝜴'), + ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), ('𝞊', '𝞨'), + ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𞠀', '𞣄'), ('𞤀', '𞥃'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), + ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_names.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_names.rs new file mode 100644 index 0000000..a000d58 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_names.rs @@ -0,0 +1,145 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-names tmp/ucd-10.0.0/ +// +// ucd-generate is available on crates.io. + +pub const PROPERTY_NAMES: &'static [(&'static str, &'static str)] = &[ + ("age", "Age"), ("ahex", "ASCII_Hex_Digit"), ("alpha", "Alphabetic"), + ("alphabetic", "Alphabetic"), ("asciihexdigit", "ASCII_Hex_Digit"), + ("bc", "Bidi_Class"), ("bidic", "Bidi_Control"), + ("bidiclass", "Bidi_Class"), ("bidicontrol", "Bidi_Control"), + ("bidim", "Bidi_Mirrored"), ("bidimirrored", "Bidi_Mirrored"), + ("bidimirroringglyph", "Bidi_Mirroring_Glyph"), + ("bidipairedbracket", "Bidi_Paired_Bracket"), + ("bidipairedbrackettype", "Bidi_Paired_Bracket_Type"), ("blk", "Block"), + ("block", "Block"), ("bmg", "Bidi_Mirroring_Glyph"), + ("bpb", "Bidi_Paired_Bracket"), ("bpt", "Bidi_Paired_Bracket_Type"), + ("canonicalcombiningclass", "Canonical_Combining_Class"), + ("cased", "Cased"), ("casefolding", "Case_Folding"), + ("caseignorable", "Case_Ignorable"), ("ccc", "Canonical_Combining_Class"), + ("ce", "Composition_Exclusion"), ("cf", "Case_Folding"), + ("changeswhencasefolded", "Changes_When_Casefolded"), + ("changeswhencasemapped", "Changes_When_Casemapped"), + ("changeswhenlowercased", "Changes_When_Lowercased"), + ("changeswhennfkccasefolded", "Changes_When_NFKC_Casefolded"), + ("changeswhentitlecased", "Changes_When_Titlecased"), + ("changeswhenuppercased", "Changes_When_Uppercased"), + ("ci", "Case_Ignorable"), ("cjkaccountingnumeric", "kAccountingNumeric"), + ("cjkcompatibilityvariant", "kCompatibilityVariant"), + ("cjkiicore", "kIICore"), ("cjkirggsource", "kIRG_GSource"), + ("cjkirghsource", "kIRG_HSource"), ("cjkirgjsource", "kIRG_JSource"), + ("cjkirgkpsource", "kIRG_KPSource"), ("cjkirgksource", "kIRG_KSource"), + ("cjkirgmsource", "kIRG_MSource"), ("cjkirgtsource", "kIRG_TSource"), + ("cjkirgusource", "kIRG_USource"), ("cjkirgvsource", "kIRG_VSource"), + ("cjkothernumeric", "kOtherNumeric"), + ("cjkprimarynumeric", "kPrimaryNumeric"), ("cjkrsunicode", "kRSUnicode"), + ("compex", "Full_Composition_Exclusion"), + ("compositionexclusion", "Composition_Exclusion"), + ("cwcf", "Changes_When_Casefolded"), ("cwcm", "Changes_When_Casemapped"), + ("cwkcf", "Changes_When_NFKC_Casefolded"), + ("cwl", "Changes_When_Lowercased"), ("cwt", "Changes_When_Titlecased"), + ("cwu", "Changes_When_Uppercased"), ("dash", "Dash"), + ("decompositionmapping", "Decomposition_Mapping"), + ("decompositiontype", "Decomposition_Type"), + ("defaultignorablecodepoint", "Default_Ignorable_Code_Point"), + ("dep", "Deprecated"), ("deprecated", "Deprecated"), + ("di", "Default_Ignorable_Code_Point"), ("dia", "Diacritic"), + ("diacritic", "Diacritic"), ("dm", "Decomposition_Mapping"), + ("dt", "Decomposition_Type"), ("ea", "East_Asian_Width"), + ("eastasianwidth", "East_Asian_Width"), ("expandsonnfc", "Expands_On_NFC"), + ("expandsonnfd", "Expands_On_NFD"), ("expandsonnfkc", "Expands_On_NFKC"), + ("expandsonnfkd", "Expands_On_NFKD"), ("ext", "Extender"), + ("extender", "Extender"), ("fcnfkc", "FC_NFKC_Closure"), + ("fcnfkcclosure", "FC_NFKC_Closure"), + ("fullcompositionexclusion", "Full_Composition_Exclusion"), + ("gc", "General_Category"), ("gcb", "Grapheme_Cluster_Break"), + ("generalcategory", "General_Category"), ("graphemebase", "Grapheme_Base"), + ("graphemeclusterbreak", "Grapheme_Cluster_Break"), + ("graphemeextend", "Grapheme_Extend"), ("graphemelink", "Grapheme_Link"), + ("grbase", "Grapheme_Base"), ("grext", "Grapheme_Extend"), + ("grlink", "Grapheme_Link"), ("hangulsyllabletype", "Hangul_Syllable_Type"), + ("hex", "Hex_Digit"), ("hexdigit", "Hex_Digit"), + ("hst", "Hangul_Syllable_Type"), ("hyphen", "Hyphen"), + ("idc", "ID_Continue"), ("idcontinue", "ID_Continue"), + ("ideo", "Ideographic"), ("ideographic", "Ideographic"), + ("ids", "ID_Start"), ("idsb", "IDS_Binary_Operator"), + ("idsbinaryoperator", "IDS_Binary_Operator"), + ("idst", "IDS_Trinary_Operator"), ("idstart", "ID_Start"), + ("idstrinaryoperator", "IDS_Trinary_Operator"), + ("indicpositionalcategory", "Indic_Positional_Category"), + ("indicsyllabiccategory", "Indic_Syllabic_Category"), + ("inpc", "Indic_Positional_Category"), ("insc", "Indic_Syllabic_Category"), + ("isc", "ISO_Comment"), ("jamoshortname", "Jamo_Short_Name"), + ("jg", "Joining_Group"), ("joinc", "Join_Control"), + ("joincontrol", "Join_Control"), ("joininggroup", "Joining_Group"), + ("joiningtype", "Joining_Type"), ("jsn", "Jamo_Short_Name"), + ("jt", "Joining_Type"), ("kaccountingnumeric", "kAccountingNumeric"), + ("kcompatibilityvariant", "kCompatibilityVariant"), ("kiicore", "kIICore"), + ("kirggsource", "kIRG_GSource"), ("kirghsource", "kIRG_HSource"), + ("kirgjsource", "kIRG_JSource"), ("kirgkpsource", "kIRG_KPSource"), + ("kirgksource", "kIRG_KSource"), ("kirgmsource", "kIRG_MSource"), + ("kirgtsource", "kIRG_TSource"), ("kirgusource", "kIRG_USource"), + ("kirgvsource", "kIRG_VSource"), ("kothernumeric", "kOtherNumeric"), + ("kprimarynumeric", "kPrimaryNumeric"), ("krsunicode", "kRSUnicode"), + ("lb", "Line_Break"), ("lc", "Lowercase_Mapping"), + ("linebreak", "Line_Break"), ("loe", "Logical_Order_Exception"), + ("logicalorderexception", "Logical_Order_Exception"), + ("lower", "Lowercase"), ("lowercase", "Lowercase"), + ("lowercasemapping", "Lowercase_Mapping"), ("math", "Math"), ("na", "Name"), + ("na1", "Unicode_1_Name"), ("name", "Name"), ("namealias", "Name_Alias"), + ("nchar", "Noncharacter_Code_Point"), ("nfcqc", "NFC_Quick_Check"), + ("nfcquickcheck", "NFC_Quick_Check"), ("nfdqc", "NFD_Quick_Check"), + ("nfdquickcheck", "NFD_Quick_Check"), ("nfkccasefold", "NFKC_Casefold"), + ("nfkccf", "NFKC_Casefold"), ("nfkcqc", "NFKC_Quick_Check"), + ("nfkcquickcheck", "NFKC_Quick_Check"), ("nfkdqc", "NFKD_Quick_Check"), + ("nfkdquickcheck", "NFKD_Quick_Check"), + ("noncharactercodepoint", "Noncharacter_Code_Point"), + ("nt", "Numeric_Type"), ("numerictype", "Numeric_Type"), + ("numericvalue", "Numeric_Value"), ("nv", "Numeric_Value"), + ("oalpha", "Other_Alphabetic"), ("ocomment", "ISO_Comment"), + ("odi", "Other_Default_Ignorable_Code_Point"), + ("ogrext", "Other_Grapheme_Extend"), ("oidc", "Other_ID_Continue"), + ("oids", "Other_ID_Start"), ("olower", "Other_Lowercase"), + ("omath", "Other_Math"), ("otheralphabetic", "Other_Alphabetic"), + ("otherdefaultignorablecodepoint", "Other_Default_Ignorable_Code_Point"), + ("othergraphemeextend", "Other_Grapheme_Extend"), + ("otheridcontinue", "Other_ID_Continue"), + ("otheridstart", "Other_ID_Start"), ("otherlowercase", "Other_Lowercase"), + ("othermath", "Other_Math"), ("otheruppercase", "Other_Uppercase"), + ("oupper", "Other_Uppercase"), ("patsyn", "Pattern_Syntax"), + ("patternsyntax", "Pattern_Syntax"), + ("patternwhitespace", "Pattern_White_Space"), + ("patws", "Pattern_White_Space"), ("pcm", "Prepended_Concatenation_Mark"), + ("prependedconcatenationmark", "Prepended_Concatenation_Mark"), + ("qmark", "Quotation_Mark"), ("quotationmark", "Quotation_Mark"), + ("radical", "Radical"), ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), ("sb", "Sentence_Break"), ("sc", "Script"), + ("scf", "Simple_Case_Folding"), ("script", "Script"), + ("scriptextensions", "Script_Extensions"), ("scx", "Script_Extensions"), + ("sd", "Soft_Dotted"), ("sentencebreak", "Sentence_Break"), + ("sentenceterminal", "Sentence_Terminal"), ("sfc", "Simple_Case_Folding"), + ("simplecasefolding", "Simple_Case_Folding"), + ("simplelowercasemapping", "Simple_Lowercase_Mapping"), + ("simpletitlecasemapping", "Simple_Titlecase_Mapping"), + ("simpleuppercasemapping", "Simple_Uppercase_Mapping"), + ("slc", "Simple_Lowercase_Mapping"), ("softdotted", "Soft_Dotted"), + ("space", "White_Space"), ("stc", "Simple_Titlecase_Mapping"), + ("sterm", "Sentence_Terminal"), ("suc", "Simple_Uppercase_Mapping"), + ("tc", "Titlecase_Mapping"), ("term", "Terminal_Punctuation"), + ("terminalpunctuation", "Terminal_Punctuation"), + ("titlecasemapping", "Titlecase_Mapping"), ("uc", "Uppercase_Mapping"), + ("uideo", "Unified_Ideograph"), ("unicode1name", "Unicode_1_Name"), + ("unicoderadicalstroke", "kRSUnicode"), + ("unifiedideograph", "Unified_Ideograph"), ("upper", "Uppercase"), + ("uppercase", "Uppercase"), ("uppercasemapping", "Uppercase_Mapping"), + ("urs", "kRSUnicode"), ("variationselector", "Variation_Selector"), + ("verticalorientation", "Vertical_Orientation"), + ("vo", "Vertical_Orientation"), ("vs", "Variation_Selector"), + ("wb", "Word_Break"), ("whitespace", "White_Space"), + ("wordbreak", "Word_Break"), ("wspace", "White_Space"), + ("xidc", "XID_Continue"), ("xidcontinue", "XID_Continue"), + ("xids", "XID_Start"), ("xidstart", "XID_Start"), + ("xonfc", "Expands_On_NFC"), ("xonfd", "Expands_On_NFD"), + ("xonfkc", "Expands_On_NFKC"), ("xonfkd", "Expands_On_NFKD"), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_values.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_values.rs new file mode 100644 index 0000000..1ce9795 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/property_values.rs @@ -0,0 +1,277 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-values tmp/ucd-10.0.0 --include gc,script,scx,age +// +// ucd-generate is available on crates.io. + +pub const PROPERTY_VALUES: &'static [(&'static str, &'static [(&'static str, &'static str)])] = &[ + ("Age", &[("1.1", "V1_1"), ("10.0", "V10_0"), ("2.0", "V2_0"), + ("2.1", "V2_1"), ("3.0", "V3_0"), ("3.1", "V3_1"), ("3.2", "V3_2"), + ("4.0", "V4_0"), ("4.1", "V4_1"), ("5.0", "V5_0"), ("5.1", "V5_1"), + ("5.2", "V5_2"), ("6.0", "V6_0"), ("6.1", "V6_1"), ("6.2", "V6_2"), + ("6.3", "V6_3"), ("7.0", "V7_0"), ("8.0", "V8_0"), ("9.0", "V9_0"), + ("na", "Unassigned"), ("unassigned", "Unassigned"), ("v100", "V10_0"), + ("v11", "V1_1"), ("v20", "V2_0"), ("v21", "V2_1"), ("v30", "V3_0"), + ("v31", "V3_1"), ("v32", "V3_2"), ("v40", "V4_0"), ("v41", "V4_1"), + ("v50", "V5_0"), ("v51", "V5_1"), ("v52", "V5_2"), ("v60", "V6_0"), + ("v61", "V6_1"), ("v62", "V6_2"), ("v63", "V6_3"), ("v70", "V7_0"), + ("v80", "V8_0"), ("v90", "V9_0"), ]), + + ("General_Category", &[("c", "Other"), ("casedletter", "Cased_Letter"), + ("cc", "Control"), ("cf", "Format"), + ("closepunctuation", "Close_Punctuation"), ("cn", "Unassigned"), + ("cntrl", "Control"), ("co", "Private_Use"), ("combiningmark", "Mark"), + ("connectorpunctuation", "Connector_Punctuation"), ("control", "Control"), + ("cs", "Surrogate"), ("currencysymbol", "Currency_Symbol"), + ("dashpunctuation", "Dash_Punctuation"), + ("decimalnumber", "Decimal_Number"), ("digit", "Decimal_Number"), + ("enclosingmark", "Enclosing_Mark"), + ("finalpunctuation", "Final_Punctuation"), ("format", "Format"), + ("initialpunctuation", "Initial_Punctuation"), ("l", "Letter"), + ("lc", "Cased_Letter"), ("letter", "Letter"), + ("letternumber", "Letter_Number"), ("lineseparator", "Line_Separator"), + ("ll", "Lowercase_Letter"), ("lm", "Modifier_Letter"), + ("lo", "Other_Letter"), ("lowercaseletter", "Lowercase_Letter"), + ("lt", "Titlecase_Letter"), ("lu", "Uppercase_Letter"), ("m", "Mark"), + ("mark", "Mark"), ("mathsymbol", "Math_Symbol"), ("mc", "Spacing_Mark"), + ("me", "Enclosing_Mark"), ("mn", "Nonspacing_Mark"), + ("modifierletter", "Modifier_Letter"), + ("modifiersymbol", "Modifier_Symbol"), ("n", "Number"), + ("nd", "Decimal_Number"), ("nl", "Letter_Number"), ("no", "Other_Number"), + ("nonspacingmark", "Nonspacing_Mark"), ("number", "Number"), + ("openpunctuation", "Open_Punctuation"), ("other", "Other"), + ("otherletter", "Other_Letter"), ("othernumber", "Other_Number"), + ("otherpunctuation", "Other_Punctuation"), ("othersymbol", "Other_Symbol"), + ("p", "Punctuation"), ("paragraphseparator", "Paragraph_Separator"), + ("pc", "Connector_Punctuation"), ("pd", "Dash_Punctuation"), + ("pe", "Close_Punctuation"), ("pf", "Final_Punctuation"), + ("pi", "Initial_Punctuation"), ("po", "Other_Punctuation"), + ("privateuse", "Private_Use"), ("ps", "Open_Punctuation"), + ("punct", "Punctuation"), ("punctuation", "Punctuation"), ("s", "Symbol"), + ("sc", "Currency_Symbol"), ("separator", "Separator"), + ("sk", "Modifier_Symbol"), ("sm", "Math_Symbol"), ("so", "Other_Symbol"), + ("spaceseparator", "Space_Separator"), ("spacingmark", "Spacing_Mark"), + ("surrogate", "Surrogate"), ("symbol", "Symbol"), + ("titlecaseletter", "Titlecase_Letter"), ("unassigned", "Unassigned"), + ("uppercaseletter", "Uppercase_Letter"), ("z", "Separator"), + ("zl", "Line_Separator"), ("zp", "Paragraph_Separator"), + ("zs", "Space_Separator"), ]), + + ("Script", &[("adlam", "Adlam"), ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), ("arab", "Arabic"), + ("arabic", "Arabic"), ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), ("armn", "Armenian"), ("avestan", "Avestan"), + ("avst", "Avestan"), ("bali", "Balinese"), ("balinese", "Balinese"), + ("bamu", "Bamum"), ("bamum", "Bamum"), ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), ("batak", "Batak"), ("batk", "Batak"), + ("beng", "Bengali"), ("bengali", "Bengali"), ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), ("bopo", "Bopomofo"), ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), ("brahmi", "Brahmi"), ("brai", "Braille"), + ("braille", "Braille"), ("bugi", "Buginese"), ("buginese", "Buginese"), + ("buhd", "Buhid"), ("buhid", "Buhid"), ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), ("cari", "Carian"), ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), ("chakma", "Chakma"), + ("cham", "Cham"), ("cher", "Cherokee"), ("cherokee", "Cherokee"), + ("common", "Common"), ("copt", "Coptic"), ("coptic", "Coptic"), + ("cprt", "Cypriot"), ("cuneiform", "Cuneiform"), ("cypriot", "Cypriot"), + ("cyrillic", "Cyrillic"), ("cyrl", "Cyrillic"), ("deseret", "Deseret"), + ("deva", "Devanagari"), ("devanagari", "Devanagari"), ("dsrt", "Deseret"), + ("dupl", "Duployan"), ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), ("elba", "Elbasan"), + ("elbasan", "Elbasan"), ("ethi", "Ethiopic"), ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), ("georgian", "Georgian"), ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), ("gonm", "Masaram_Gondi"), ("goth", "Gothic"), + ("gothic", "Gothic"), ("gran", "Grantha"), ("grantha", "Grantha"), + ("greek", "Greek"), ("grek", "Greek"), ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), ("gurmukhi", "Gurmukhi"), ("guru", "Gurmukhi"), + ("han", "Han"), ("hang", "Hangul"), ("hangul", "Hangul"), ("hani", "Han"), + ("hano", "Hanunoo"), ("hanunoo", "Hanunoo"), ("hatr", "Hatran"), + ("hatran", "Hatran"), ("hebr", "Hebrew"), ("hebrew", "Hebrew"), + ("hira", "Hiragana"), ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), ("hmng", "Pahawh_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), ("ital", "Old_Italic"), + ("java", "Javanese"), ("javanese", "Javanese"), ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), ("kana", "Katakana"), ("kannada", "Kannada"), + ("katakana", "Katakana"), ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kayahli", "Kayah_Li"), ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), ("khmer", "Khmer"), ("khmr", "Khmer"), + ("khoj", "Khojki"), ("khojki", "Khojki"), ("khudawadi", "Khudawadi"), + ("knda", "Kannada"), ("kthi", "Kaithi"), ("lana", "Tai_Tham"), + ("lao", "Lao"), ("laoo", "Lao"), ("latin", "Latin"), ("latn", "Latin"), + ("lepc", "Lepcha"), ("lepcha", "Lepcha"), ("limb", "Limbu"), + ("limbu", "Limbu"), ("lina", "Linear_A"), ("linb", "Linear_B"), + ("lineara", "Linear_A"), ("linearb", "Linear_B"), ("lisu", "Lisu"), + ("lyci", "Lycian"), ("lycian", "Lycian"), ("lydi", "Lydian"), + ("lydian", "Lydian"), ("mahajani", "Mahajani"), ("mahj", "Mahajani"), + ("malayalam", "Malayalam"), ("mand", "Mandaic"), ("mandaic", "Mandaic"), + ("mani", "Manichaean"), ("manichaean", "Manichaean"), ("marc", "Marchen"), + ("marchen", "Marchen"), ("masaramgondi", "Masaram_Gondi"), + ("meeteimayek", "Meetei_Mayek"), ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), ("miao", "Miao"), + ("mlym", "Malayalam"), ("modi", "Modi"), ("mong", "Mongolian"), + ("mongolian", "Mongolian"), ("mro", "Mro"), ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), ("mult", "Multani"), ("multani", "Multani"), + ("myanmar", "Myanmar"), ("mymr", "Myanmar"), ("nabataean", "Nabataean"), + ("narb", "Old_North_Arabian"), ("nbat", "Nabataean"), ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), ("nko", "Nko"), ("nkoo", "Nko"), + ("nshu", "Nushu"), ("nushu", "Nushu"), ("ogam", "Ogham"), + ("ogham", "Ogham"), ("olchiki", "Ol_Chiki"), ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), ("oriya", "Oriya"), ("orkh", "Old_Turkic"), + ("orya", "Oriya"), ("osage", "Osage"), ("osge", "Osage"), + ("osma", "Osmanya"), ("osmanya", "Osmanya"), + ("pahawhhmong", "Pahawh_Hmong"), ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), ("perm", "Old_Permic"), ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), ("qaai", "Inherited"), ("rejang", "Rejang"), + ("rjng", "Rejang"), ("runic", "Runic"), ("runr", "Runic"), + ("samaritan", "Samaritan"), ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), ("sgnw", "SignWriting"), + ("sharada", "Sharada"), ("shavian", "Shavian"), ("shaw", "Shavian"), + ("shrd", "Sharada"), ("sidd", "Siddham"), ("siddham", "Siddham"), + ("signwriting", "SignWriting"), ("sind", "Khudawadi"), ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), ("sund", "Sundanese"), ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), ("syriac", "Syriac"), ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), ("tagbanwa", "Tagbanwa"), ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), ("taiviet", "Tai_Viet"), ("takr", "Takri"), + ("takri", "Takri"), ("tale", "Tai_Le"), ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), ("taml", "Tamil"), ("tang", "Tangut"), + ("tangut", "Tangut"), ("tavt", "Tai_Viet"), ("telu", "Telugu"), + ("telugu", "Telugu"), ("tfng", "Tifinagh"), ("tglg", "Tagalog"), + ("thaa", "Thaana"), ("thaana", "Thaana"), ("thai", "Thai"), + ("tibetan", "Tibetan"), ("tibt", "Tibetan"), ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), ("tirhuta", "Tirhuta"), ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), ("unknown", "Unknown"), ("vai", "Vai"), + ("vaii", "Vai"), ("wara", "Warang_Citi"), ("warangciti", "Warang_Citi"), + ("xpeo", "Old_Persian"), ("xsux", "Cuneiform"), ("yi", "Yi"), + ("yiii", "Yi"), ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), ("zinh", "Inherited"), ("zyyy", "Common"), + ("zzzz", "Unknown"), ]), + + ("Script_Extensions", &[("adlam", "Adlam"), ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), ("arab", "Arabic"), + ("arabic", "Arabic"), ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), ("armn", "Armenian"), ("avestan", "Avestan"), + ("avst", "Avestan"), ("bali", "Balinese"), ("balinese", "Balinese"), + ("bamu", "Bamum"), ("bamum", "Bamum"), ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), ("batak", "Batak"), ("batk", "Batak"), + ("beng", "Bengali"), ("bengali", "Bengali"), ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), ("bopo", "Bopomofo"), ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), ("brahmi", "Brahmi"), ("brai", "Braille"), + ("braille", "Braille"), ("bugi", "Buginese"), ("buginese", "Buginese"), + ("buhd", "Buhid"), ("buhid", "Buhid"), ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), ("cari", "Carian"), ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), ("chakma", "Chakma"), + ("cham", "Cham"), ("cher", "Cherokee"), ("cherokee", "Cherokee"), + ("common", "Common"), ("copt", "Coptic"), ("coptic", "Coptic"), + ("cprt", "Cypriot"), ("cuneiform", "Cuneiform"), ("cypriot", "Cypriot"), + ("cyrillic", "Cyrillic"), ("cyrl", "Cyrillic"), ("deseret", "Deseret"), + ("deva", "Devanagari"), ("devanagari", "Devanagari"), ("dsrt", "Deseret"), + ("dupl", "Duployan"), ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), ("elba", "Elbasan"), + ("elbasan", "Elbasan"), ("ethi", "Ethiopic"), ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), ("georgian", "Georgian"), ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), ("gonm", "Masaram_Gondi"), ("goth", "Gothic"), + ("gothic", "Gothic"), ("gran", "Grantha"), ("grantha", "Grantha"), + ("greek", "Greek"), ("grek", "Greek"), ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), ("gurmukhi", "Gurmukhi"), ("guru", "Gurmukhi"), + ("han", "Han"), ("hang", "Hangul"), ("hangul", "Hangul"), ("hani", "Han"), + ("hano", "Hanunoo"), ("hanunoo", "Hanunoo"), ("hatr", "Hatran"), + ("hatran", "Hatran"), ("hebr", "Hebrew"), ("hebrew", "Hebrew"), + ("hira", "Hiragana"), ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), ("hmng", "Pahawh_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), ("ital", "Old_Italic"), + ("java", "Javanese"), ("javanese", "Javanese"), ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), ("kana", "Katakana"), ("kannada", "Kannada"), + ("katakana", "Katakana"), ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kayahli", "Kayah_Li"), ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), ("khmer", "Khmer"), ("khmr", "Khmer"), + ("khoj", "Khojki"), ("khojki", "Khojki"), ("khudawadi", "Khudawadi"), + ("knda", "Kannada"), ("kthi", "Kaithi"), ("lana", "Tai_Tham"), + ("lao", "Lao"), ("laoo", "Lao"), ("latin", "Latin"), ("latn", "Latin"), + ("lepc", "Lepcha"), ("lepcha", "Lepcha"), ("limb", "Limbu"), + ("limbu", "Limbu"), ("lina", "Linear_A"), ("linb", "Linear_B"), + ("lineara", "Linear_A"), ("linearb", "Linear_B"), ("lisu", "Lisu"), + ("lyci", "Lycian"), ("lycian", "Lycian"), ("lydi", "Lydian"), + ("lydian", "Lydian"), ("mahajani", "Mahajani"), ("mahj", "Mahajani"), + ("malayalam", "Malayalam"), ("mand", "Mandaic"), ("mandaic", "Mandaic"), + ("mani", "Manichaean"), ("manichaean", "Manichaean"), ("marc", "Marchen"), + ("marchen", "Marchen"), ("masaramgondi", "Masaram_Gondi"), + ("meeteimayek", "Meetei_Mayek"), ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), ("miao", "Miao"), + ("mlym", "Malayalam"), ("modi", "Modi"), ("mong", "Mongolian"), + ("mongolian", "Mongolian"), ("mro", "Mro"), ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), ("mult", "Multani"), ("multani", "Multani"), + ("myanmar", "Myanmar"), ("mymr", "Myanmar"), ("nabataean", "Nabataean"), + ("narb", "Old_North_Arabian"), ("nbat", "Nabataean"), ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), ("nko", "Nko"), ("nkoo", "Nko"), + ("nshu", "Nushu"), ("nushu", "Nushu"), ("ogam", "Ogham"), + ("ogham", "Ogham"), ("olchiki", "Ol_Chiki"), ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), ("oriya", "Oriya"), ("orkh", "Old_Turkic"), + ("orya", "Oriya"), ("osage", "Osage"), ("osge", "Osage"), + ("osma", "Osmanya"), ("osmanya", "Osmanya"), + ("pahawhhmong", "Pahawh_Hmong"), ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), ("perm", "Old_Permic"), ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), ("qaai", "Inherited"), ("rejang", "Rejang"), + ("rjng", "Rejang"), ("runic", "Runic"), ("runr", "Runic"), + ("samaritan", "Samaritan"), ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), ("sgnw", "SignWriting"), + ("sharada", "Sharada"), ("shavian", "Shavian"), ("shaw", "Shavian"), + ("shrd", "Sharada"), ("sidd", "Siddham"), ("siddham", "Siddham"), + ("signwriting", "SignWriting"), ("sind", "Khudawadi"), ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), ("sund", "Sundanese"), ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), ("syriac", "Syriac"), ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), ("tagbanwa", "Tagbanwa"), ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), ("taiviet", "Tai_Viet"), ("takr", "Takri"), + ("takri", "Takri"), ("tale", "Tai_Le"), ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), ("taml", "Tamil"), ("tang", "Tangut"), + ("tangut", "Tangut"), ("tavt", "Tai_Viet"), ("telu", "Telugu"), + ("telugu", "Telugu"), ("tfng", "Tifinagh"), ("tglg", "Tagalog"), + ("thaa", "Thaana"), ("thaana", "Thaana"), ("thai", "Thai"), + ("tibetan", "Tibetan"), ("tibt", "Tibetan"), ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), ("tirhuta", "Tirhuta"), ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), ("unknown", "Unknown"), ("vai", "Vai"), + ("vaii", "Vai"), ("wara", "Warang_Citi"), ("warangciti", "Warang_Citi"), + ("xpeo", "Old_Persian"), ("xsux", "Cuneiform"), ("yi", "Yi"), + ("yiii", "Yi"), ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), ("zinh", "Inherited"), ("zyyy", "Common"), + ("zzzz", "Unknown"), ]), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/script.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/script.rs new file mode 100644 index 0000000..99c5786 --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/script.rs @@ -0,0 +1,765 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate script tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("Adlam", ADLAM), ("Ahom", AHOM), + ("Anatolian_Hieroglyphs", ANATOLIAN_HIEROGLYPHS), ("Arabic", ARABIC), + ("Armenian", ARMENIAN), ("Avestan", AVESTAN), ("Balinese", BALINESE), + ("Bamum", BAMUM), ("Bassa_Vah", BASSA_VAH), ("Batak", BATAK), + ("Bengali", BENGALI), ("Bhaiksuki", BHAIKSUKI), ("Bopomofo", BOPOMOFO), + ("Brahmi", BRAHMI), ("Braille", BRAILLE), ("Buginese", BUGINESE), + ("Buhid", BUHID), ("Canadian_Aboriginal", CANADIAN_ABORIGINAL), + ("Carian", CARIAN), ("Caucasian_Albanian", CAUCASIAN_ALBANIAN), + ("Chakma", CHAKMA), ("Cham", CHAM), ("Cherokee", CHEROKEE), + ("Common", COMMON), ("Coptic", COPTIC), ("Cuneiform", CUNEIFORM), + ("Cypriot", CYPRIOT), ("Cyrillic", CYRILLIC), ("Deseret", DESERET), + ("Devanagari", DEVANAGARI), ("Duployan", DUPLOYAN), + ("Egyptian_Hieroglyphs", EGYPTIAN_HIEROGLYPHS), ("Elbasan", ELBASAN), + ("Ethiopic", ETHIOPIC), ("Georgian", GEORGIAN), ("Glagolitic", GLAGOLITIC), + ("Gothic", GOTHIC), ("Grantha", GRANTHA), ("Greek", GREEK), + ("Gujarati", GUJARATI), ("Gurmukhi", GURMUKHI), ("Han", HAN), + ("Hangul", HANGUL), ("Hanunoo", HANUNOO), ("Hatran", HATRAN), + ("Hebrew", HEBREW), ("Hiragana", HIRAGANA), + ("Imperial_Aramaic", IMPERIAL_ARAMAIC), ("Inherited", INHERITED), + ("Inscriptional_Pahlavi", INSCRIPTIONAL_PAHLAVI), + ("Inscriptional_Parthian", INSCRIPTIONAL_PARTHIAN), ("Javanese", JAVANESE), + ("Kaithi", KAITHI), ("Kannada", KANNADA), ("Katakana", KATAKANA), + ("Kayah_Li", KAYAH_LI), ("Kharoshthi", KHAROSHTHI), ("Khmer", KHMER), + ("Khojki", KHOJKI), ("Khudawadi", KHUDAWADI), ("Lao", LAO), + ("Latin", LATIN), ("Lepcha", LEPCHA), ("Limbu", LIMBU), + ("Linear_A", LINEAR_A), ("Linear_B", LINEAR_B), ("Lisu", LISU), + ("Lycian", LYCIAN), ("Lydian", LYDIAN), ("Mahajani", MAHAJANI), + ("Malayalam", MALAYALAM), ("Mandaic", MANDAIC), ("Manichaean", MANICHAEAN), + ("Marchen", MARCHEN), ("Masaram_Gondi", MASARAM_GONDI), + ("Meetei_Mayek", MEETEI_MAYEK), ("Mende_Kikakui", MENDE_KIKAKUI), + ("Meroitic_Cursive", MEROITIC_CURSIVE), + ("Meroitic_Hieroglyphs", MEROITIC_HIEROGLYPHS), ("Miao", MIAO), + ("Modi", MODI), ("Mongolian", MONGOLIAN), ("Mro", MRO), + ("Multani", MULTANI), ("Myanmar", MYANMAR), ("Nabataean", NABATAEAN), + ("New_Tai_Lue", NEW_TAI_LUE), ("Newa", NEWA), ("Nko", NKO), + ("Nushu", NUSHU), ("Ogham", OGHAM), ("Ol_Chiki", OL_CHIKI), + ("Old_Hungarian", OLD_HUNGARIAN), ("Old_Italic", OLD_ITALIC), + ("Old_North_Arabian", OLD_NORTH_ARABIAN), ("Old_Permic", OLD_PERMIC), + ("Old_Persian", OLD_PERSIAN), ("Old_South_Arabian", OLD_SOUTH_ARABIAN), + ("Old_Turkic", OLD_TURKIC), ("Oriya", ORIYA), ("Osage", OSAGE), + ("Osmanya", OSMANYA), ("Pahawh_Hmong", PAHAWH_HMONG), + ("Palmyrene", PALMYRENE), ("Pau_Cin_Hau", PAU_CIN_HAU), + ("Phags_Pa", PHAGS_PA), ("Phoenician", PHOENICIAN), + ("Psalter_Pahlavi", PSALTER_PAHLAVI), ("Rejang", REJANG), ("Runic", RUNIC), + ("Samaritan", SAMARITAN), ("Saurashtra", SAURASHTRA), ("Sharada", SHARADA), + ("Shavian", SHAVIAN), ("Siddham", SIDDHAM), ("SignWriting", SIGNWRITING), + ("Sinhala", SINHALA), ("Sora_Sompeng", SORA_SOMPENG), ("Soyombo", SOYOMBO), + ("Sundanese", SUNDANESE), ("Syloti_Nagri", SYLOTI_NAGRI), + ("Syriac", SYRIAC), ("Tagalog", TAGALOG), ("Tagbanwa", TAGBANWA), + ("Tai_Le", TAI_LE), ("Tai_Tham", TAI_THAM), ("Tai_Viet", TAI_VIET), + ("Takri", TAKRI), ("Tamil", TAMIL), ("Tangut", TANGUT), ("Telugu", TELUGU), + ("Thaana", THAANA), ("Thai", THAI), ("Tibetan", TIBETAN), + ("Tifinagh", TIFINAGH), ("Tirhuta", TIRHUTA), ("Ugaritic", UGARITIC), + ("Vai", VAI), ("Warang_Citi", WARANG_CITI), ("Yi", YI), + ("Zanabazar_Square", ZANABAZAR_SQUARE), +]; + +pub const ADLAM: &'static [(char, char)] = &[ + ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞥞', '𞥟'), +]; + +pub const AHOM: &'static [(char, char)] = &[ + ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜿'), +]; + +pub const ANATOLIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𔐀', '𔙆'), +]; + +pub const ARABIC: &'static [(char, char)] = &[ + ('\u{600}', '\u{604}'), ('؆', '؋'), ('؍', 'ؚ'), ('\u{61c}', '\u{61c}'), + ('؞', '؞'), ('ؠ', 'ؿ'), ('ف', 'ي'), ('ٖ', 'ٯ'), ('ٱ', 'ۜ'), + ('۞', 'ۿ'), ('ݐ', 'ݿ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), + ('ࣣ', 'ࣿ'), ('ﭐ', '﯁'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), + ('ﶒ', 'ﷇ'), ('ﷰ', '﷽'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('𐹠', '𐹾'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), +]; + +pub const ARMENIAN: &'static [(char, char)] = &[ + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('֊', '֊'), ('֍', '֏'), + ('ﬓ', 'ﬗ'), +]; + +pub const AVESTAN: &'static [(char, char)] = &[ + ('𐬀', '𐬵'), ('𐬹', '𐬿'), +]; + +pub const BALINESE: &'static [(char, char)] = &[ + ('ᬀ', 'ᭋ'), ('᭐', '᭼'), +]; + +pub const BAMUM: &'static [(char, char)] = &[ + ('ꚠ', '꛷'), ('𖠀', '𖨸'), +]; + +pub const BASSA_VAH: &'static [(char, char)] = &[ + ('𖫐', '𖫭'), ('𖫰', '𖫵'), +]; + +pub const BATAK: &'static [(char, char)] = &[ + ('ᯀ', '᯳'), ('᯼', '᯿'), +]; + +pub const BENGALI: &'static [(char, char)] = &[ + ('ঀ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), ('ও', 'ন'), + ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), ('়', 'ৄ'), + ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), + ('য়', 'ৣ'), ('০', '৽'), +]; + +pub const BHAIKSUKI: &'static [(char, char)] = &[ + ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱅'), ('𑱐', '𑱬'), +]; + +pub const BOPOMOFO: &'static [(char, char)] = &[ + ('˪', '˫'), ('ㄅ', 'ㄮ'), ('ㆠ', 'ㆺ'), +]; + +pub const BRAHMI: &'static [(char, char)] = &[ + ('𑀀', '𑁍'), ('𑁒', '𑁯'), ('𑁿', '𑁿'), +]; + +pub const BRAILLE: &'static [(char, char)] = &[ + ('⠀', '⣿'), +]; + +pub const BUGINESE: &'static [(char, char)] = &[ + ('ᨀ', 'ᨛ'), ('᨞', '᨟'), +]; + +pub const BUHID: &'static [(char, char)] = &[ + ('ᝀ', 'ᝓ'), +]; + +pub const CANADIAN_ABORIGINAL: &'static [(char, char)] = &[ + ('᐀', 'ᙿ'), ('ᢰ', 'ᣵ'), +]; + +pub const CARIAN: &'static [(char, char)] = &[ + ('𐊠', '𐋐'), +]; + +pub const CAUCASIAN_ALBANIAN: &'static [(char, char)] = &[ + ('𐔰', '𐕣'), ('𐕯', '𐕯'), +]; + +pub const CHAKMA: &'static [(char, char)] = &[ + ('𑄀', '𑄴'), ('𑄶', '𑅃'), +]; + +pub const CHAM: &'static [(char, char)] = &[ + ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), ('꩜', '꩟'), +]; + +pub const CHEROKEE: &'static [(char, char)] = &[ + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ꭰ', 'ꮿ'), +]; + +pub const COMMON: &'static [(char, char)] = &[ + ('\u{0}', '@'), ('[', '`'), ('{', '©'), ('«', '¹'), ('»', '¿'), + ('×', '×'), ('÷', '÷'), ('ʹ', '˟'), ('˥', '˩'), ('ˬ', '˿'), + ('ʹ', 'ʹ'), (';', ';'), ('΅', '΅'), ('·', '·'), ('։', '։'), + ('\u{605}', '\u{605}'), ('،', '،'), ('؛', '؛'), ('؟', '؟'), + ('ـ', 'ـ'), ('\u{6dd}', '\u{6dd}'), ('\u{8e2}', '\u{8e2}'), + ('।', '॥'), ('฿', '฿'), ('࿕', '࿘'), ('჻', '჻'), + ('᛫', '᛭'), ('᜵', '᜶'), ('᠂', '᠃'), ('᠅', '᠅'), + ('᳓', '᳓'), ('᳡', '᳡'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳳ'), + ('ᳵ', '᳷'), ('\u{2000}', '\u{200b}'), ('\u{200e}', '\u{2064}'), + ('\u{2066}', '⁰'), ('⁴', '⁾'), ('₀', '₎'), ('₠', '₿'), + ('℀', '℥'), ('℧', '℩'), ('ℬ', 'ℱ'), ('ℳ', '⅍'), + ('⅏', '⅟'), ('↉', '↋'), ('←', '␦'), ('⑀', '⑊'), + ('①', '⟿'), ('⤀', '⭳'), ('⭶', '⮕'), ('⮘', '⮹'), + ('⮽', '⯈'), ('⯊', '⯒'), ('⯬', '⯯'), ('⸀', '⹉'), + ('⿰', '⿻'), ('\u{3000}', '〄'), ('〆', '〆'), ('〈', '〠'), + ('〰', '〷'), ('〼', '〿'), ('゛', '゜'), ('゠', '゠'), + ('・', 'ー'), ('㆐', '㆟'), ('㇀', '㇣'), ('㈠', '㉟'), + ('㉿', '㋏'), ('㍘', '㏿'), ('䷀', '䷿'), ('꜀', '꜡'), + ('ꞈ', '꞊'), ('꠰', '꠹'), ('꤮', '꤮'), ('ꧏ', 'ꧏ'), + ('꭛', '꭛'), ('﴾', '﴿'), ('︐', '︙'), ('︰', '﹒'), + ('﹔', '﹦'), ('﹨', '﹫'), ('\u{feff}', '\u{feff}'), ('!', '@'), + ('[', '`'), ('{', '・'), ('ー', 'ー'), ('゙', '゚'), + ('¢', '₩'), ('│', '○'), ('\u{fff9}', '�'), ('𐄀', '𐄂'), + ('𐄇', '𐄳'), ('𐄷', '𐄿'), ('𐆐', '𐆛'), ('𐇐', '𐇼'), + ('𐋡', '𐋻'), ('\u{1bca0}', '\u{1bca3}'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄩', '𝅦'), ('𝅪', '\u{1d17a}'), ('𝆃', '𝆄'), + ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝌀', '𝍖'), ('𝍠', '𝍱'), + ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), + ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), + ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), + ('𝟎', '𝟿'), ('🀀', '🀫'), ('🀰', '🂓'), ('🂠', '🂮'), + ('🂱', '🂿'), ('🃁', '🃏'), ('🃑', '🃵'), ('🄀', '🄌'), + ('🄐', '🄮'), ('🄰', '🅫'), ('🅰', '🆬'), ('🇦', '🇿'), + ('🈁', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), ('🉐', '🉑'), + ('🉠', '🉥'), ('🌀', '🛔'), ('🛠', '🛬'), ('🛰', '🛸'), + ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), ('🠐', '🡇'), + ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), ('🤀', '🤋'), + ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), ('🦀', '🦗'), + ('🧀', '🧀'), ('🧐', '🧦'), ('\u{e0001}', '\u{e0001}'), + ('\u{e0020}', '\u{e007f}'), +]; + +pub const COPTIC: &'static [(char, char)] = &[ + ('Ϣ', 'ϯ'), ('Ⲁ', 'ⳳ'), ('⳹', '⳿'), +]; + +pub const CUNEIFORM: &'static [(char, char)] = &[ + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒑰', '𒑴'), ('𒒀', '𒕃'), +]; + +pub const CYPRIOT: &'static [(char, char)] = &[ + ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), + ('𐠼', '𐠼'), ('𐠿', '𐠿'), +]; + +pub const CYRILLIC: &'static [(char, char)] = &[ + ('Ѐ', '҄'), ('҇', 'ԯ'), ('ᲀ', 'ᲈ'), ('ᴫ', 'ᴫ'), ('ᵸ', 'ᵸ'), + ('ⷠ', 'ⷿ'), ('Ꙁ', 'ꚟ'), ('︮', '︯'), +]; + +pub const DESERET: &'static [(char, char)] = &[ + ('𐐀', '𐑏'), +]; + +pub const DEVANAGARI: &'static [(char, char)] = &[ + ('ऀ', 'ॐ'), ('॓', 'ॣ'), ('०', 'ॿ'), ('꣠', 'ꣽ'), +]; + +pub const DUPLOYAN: &'static [(char, char)] = &[ + ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), + ('𛲜', '𛲟'), +]; + +pub const EGYPTIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𓀀', '𓐮'), +]; + +pub const ELBASAN: &'static [(char, char)] = &[ + ('𐔀', '𐔧'), +]; + +pub const ETHIOPIC: &'static [(char, char)] = &[ + ('ሀ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፼'), ('ᎀ', '᎙'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), +]; + +pub const GEORGIAN: &'static [(char, char)] = &[ + ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), + ('ჼ', 'ჿ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), +]; + +pub const GLAGOLITIC: &'static [(char, char)] = &[ + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), +]; + +pub const GOTHIC: &'static [(char, char)] = &[ + ('𐌰', '𐍊'), +]; + +pub const GRANTHA: &'static [(char, char)] = &[ + ('𑌀', '𑌃'), ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), + ('𑌪', '𑌰'), ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), + ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), + ('𑍝', '𑍣'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), +]; + +pub const GREEK: &'static [(char, char)] = &[ + ('Ͱ', 'ͳ'), ('͵', 'ͷ'), ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('΄', '΄'), + ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ϡ'), + ('ϰ', 'Ͽ'), ('ᴦ', 'ᴪ'), ('ᵝ', 'ᵡ'), ('ᵦ', 'ᵪ'), + ('ᶿ', 'ᶿ'), ('ἀ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), + ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ῄ'), + ('ῆ', 'ΐ'), ('ῖ', 'Ί'), ('῝', '`'), ('ῲ', 'ῴ'), + ('ῶ', '῾'), ('Ω', 'Ω'), ('ꭥ', 'ꭥ'), ('𐅀', '𐆎'), + ('𐆠', '𐆠'), ('𝈀', '𝉅'), +]; + +pub const GUJARATI: &'static [(char, char)] = &[ + ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), + ('ે', 'ૉ'), ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), + ('૦', '૱'), ('ૹ', '૿'), +]; + +pub const GURMUKHI: &'static [(char, char)] = &[ + ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), + ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), + ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), + ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), +]; + +pub const HAN: &'static [(char, char)] = &[ + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('々', '々'), + ('〇', '〇'), ('〡', '〩'), ('〸', '〻'), ('㐀', '䶵'), + ('一', '鿪'), ('豈', '舘'), ('並', '龎'), ('𠀀', '𪛖'), + ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), + ('丽', '𪘀'), +]; + +pub const HANGUL: &'static [(char, char)] = &[ + ('ᄀ', 'ᇿ'), ('〮', '〯'), ('ㄱ', 'ㆎ'), ('㈀', '㈞'), + ('㉠', '㉾'), ('ꥠ', 'ꥼ'), ('가', '힣'), ('ힰ', 'ퟆ'), + ('ퟋ', 'ퟻ'), ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), + ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), +]; + +pub const HANUNOO: &'static [(char, char)] = &[ + ('ᜠ', '᜴'), +]; + +pub const HATRAN: &'static [(char, char)] = &[ + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐣻', '𐣿'), +]; + +pub const HEBREW: &'static [(char, char)] = &[ + ('֑', 'ׇ'), ('א', 'ת'), ('װ', '״'), ('יִ', 'זּ'), ('טּ', 'לּ'), + ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﭏ'), +]; + +pub const HIRAGANA: &'static [(char, char)] = &[ + ('ぁ', 'ゖ'), ('ゝ', 'ゟ'), ('𛀁', '𛄞'), ('🈀', '🈀'), +]; + +pub const IMPERIAL_ARAMAIC: &'static [(char, char)] = &[ + ('𐡀', '𐡕'), ('𐡗', '𐡟'), +]; + +pub const INHERITED: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҅', '҆'), ('ً', 'ٕ'), ('ٰ', 'ٰ'), ('॑', '॒'), + ('᪰', '᪾'), ('᳐', '᳒'), ('᳔', '᳠'), ('᳢', '᳨'), + ('᳭', '᳭'), ('᳴', '᳴'), ('᳸', '᳹'), ('᷀', '᷹'), + ('᷻', '᷿'), ('\u{200c}', '\u{200d}'), ('⃐', '⃰'), ('〪', '〭'), + ('゙', '゚'), ('︀', '️'), ('︠', '︭'), ('𐇽', '𐇽'), + ('𐋠', '𐋠'), ('𝅧', '𝅩'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), + ('𝆪', '𝆭'), ('󠄀', '󠇯'), +]; + +pub const INSCRIPTIONAL_PAHLAVI: &'static [(char, char)] = &[ + ('𐭠', '𐭲'), ('𐭸', '𐭿'), +]; + +pub const INSCRIPTIONAL_PARTHIAN: &'static [(char, char)] = &[ + ('𐭀', '𐭕'), ('𐭘', '𐭟'), +]; + +pub const JAVANESE: &'static [(char, char)] = &[ + ('ꦀ', '꧍'), ('꧐', '꧙'), ('꧞', '꧟'), +]; + +pub const KAITHI: &'static [(char, char)] = &[ + ('𑂀', '𑃁'), +]; + +pub const KANNADA: &'static [(char, char)] = &[ + ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), + ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), ('ೆ', 'ೈ'), + ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), + ('೦', '೯'), ('ೱ', 'ೲ'), +]; + +pub const KATAKANA: &'static [(char, char)] = &[ + ('ァ', 'ヺ'), ('ヽ', 'ヿ'), ('ㇰ', 'ㇿ'), ('㋐', '㋾'), + ('㌀', '㍗'), ('ヲ', 'ッ'), ('ア', 'ン'), ('𛀀', '𛀀'), +]; + +pub const KAYAH_LI: &'static [(char, char)] = &[ + ('꤀', '꤭'), ('꤯', '꤯'), +]; + +pub const KHAROSHTHI: &'static [(char, char)] = &[ + ('𐨀', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), + ('𐨙', '𐨳'), ('𐨸', '𐨺'), ('𐨿', '𐩇'), ('𐩐', '𐩘'), +]; + +pub const KHMER: &'static [(char, char)] = &[ + ('ក', '៝'), ('០', '៩'), ('៰', '៹'), ('᧠', '᧿'), +]; + +pub const KHOJKI: &'static [(char, char)] = &[ + ('𑈀', '𑈑'), ('𑈓', '𑈾'), +]; + +pub const KHUDAWADI: &'static [(char, char)] = &[ + ('𑊰', '𑋪'), ('𑋰', '𑋹'), +]; + +pub const LAO: &'static [(char, char)] = &[ + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), +]; + +pub const LATIN: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('º', 'º'), ('À', 'Ö'), + ('Ø', 'ö'), ('ø', 'ʸ'), ('ˠ', 'ˤ'), ('ᴀ', 'ᴥ'), ('ᴬ', 'ᵜ'), + ('ᵢ', 'ᵥ'), ('ᵫ', 'ᵷ'), ('ᵹ', 'ᶾ'), ('Ḁ', 'ỿ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('K', 'Å'), + ('Ⅎ', 'Ⅎ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), ('Ⱡ', 'Ɀ'), + ('Ꜣ', 'ꞇ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), ('ꟷ', 'ꟿ'), + ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭤ'), ('ff', 'st'), ('A', 'Z'), + ('a', 'z'), +]; + +pub const LEPCHA: &'static [(char, char)] = &[ + ('ᰀ', '᰷'), ('᰻', '᱉'), ('ᱍ', 'ᱏ'), +]; + +pub const LIMBU: &'static [(char, char)] = &[ + ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), ('᥀', '᥀'), + ('᥄', '᥏'), +]; + +pub const LINEAR_A: &'static [(char, char)] = &[ + ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), +]; + +pub const LINEAR_B: &'static [(char, char)] = &[ + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), +]; + +pub const LISU: &'static [(char, char)] = &[ + ('ꓐ', '꓿'), +]; + +pub const LYCIAN: &'static [(char, char)] = &[ + ('𐊀', '𐊜'), +]; + +pub const LYDIAN: &'static [(char, char)] = &[ + ('𐤠', '𐤹'), ('𐤿', '𐤿'), +]; + +pub const MAHAJANI: &'static [(char, char)] = &[ + ('𑅐', '𑅶'), +]; + +pub const MALAYALAM: &'static [(char, char)] = &[ + ('ഀ', 'ഃ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ൄ'), + ('െ', 'ൈ'), ('ൊ', '൏'), ('ൔ', 'ൣ'), ('൦', 'ൿ'), +]; + +pub const MANDAIC: &'static [(char, char)] = &[ + ('ࡀ', '࡛'), ('࡞', '࡞'), +]; + +pub const MANICHAEAN: &'static [(char, char)] = &[ + ('𐫀', '𐫦'), ('𐫫', '𐫶'), +]; + +pub const MARCHEN: &'static [(char, char)] = &[ + ('𑱰', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), +]; + +pub const MASARAM_GONDI: &'static [(char, char)] = &[ + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), +]; + +pub const MEETEI_MAYEK: &'static [(char, char)] = &[ + ('ꫠ', '꫶'), ('ꯀ', '꯭'), ('꯰', '꯹'), +]; + +pub const MENDE_KIKAKUI: &'static [(char, char)] = &[ + ('𞠀', '𞣄'), ('𞣇', '𞣖'), +]; + +pub const MEROITIC_CURSIVE: &'static [(char, char)] = &[ + ('𐦠', '𐦷'), ('𐦼', '𐧏'), ('𐧒', '𐧿'), +]; + +pub const MEROITIC_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𐦀', '𐦟'), +]; + +pub const MIAO: &'static [(char, char)] = &[ + ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾏', '𖾟'), +]; + +pub const MODI: &'static [(char, char)] = &[ + ('𑘀', '𑙄'), ('𑙐', '𑙙'), +]; + +pub const MONGOLIAN: &'static [(char, char)] = &[ + ('᠀', '᠁'), ('᠄', '᠄'), ('᠆', '\u{180e}'), ('᠐', '᠙'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), ('𑙠', '𑙬'), +]; + +pub const MRO: &'static [(char, char)] = &[ + ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖩮', '𖩯'), +]; + +pub const MULTANI: &'static [(char, char)] = &[ + ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), + ('𑊟', '𑊩'), +]; + +pub const MYANMAR: &'static [(char, char)] = &[ + ('က', '႟'), ('ꧠ', 'ꧾ'), ('ꩠ', 'ꩿ'), +]; + +pub const NABATAEAN: &'static [(char, char)] = &[ + ('𐢀', '𐢞'), ('𐢧', '𐢯'), +]; + +pub const NEW_TAI_LUE: &'static [(char, char)] = &[ + ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('᧞', '᧟'), +]; + +pub const NEWA: &'static [(char, char)] = &[ + ('𑐀', '𑑙'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), +]; + +pub const NKO: &'static [(char, char)] = &[ + ('߀', 'ߺ'), +]; + +pub const NUSHU: &'static [(char, char)] = &[ + ('𖿡', '𖿡'), ('𛅰', '𛋻'), +]; + +pub const OGHAM: &'static [(char, char)] = &[ + ('\u{1680}', '᚜'), +]; + +pub const OL_CHIKI: &'static [(char, char)] = &[ + ('᱐', '᱿'), +]; + +pub const OLD_HUNGARIAN: &'static [(char, char)] = &[ + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), +]; + +pub const OLD_ITALIC: &'static [(char, char)] = &[ + ('𐌀', '𐌣'), ('𐌭', '𐌯'), +]; + +pub const OLD_NORTH_ARABIAN: &'static [(char, char)] = &[ + ('𐪀', '𐪟'), +]; + +pub const OLD_PERMIC: &'static [(char, char)] = &[ + ('𐍐', '𐍺'), +]; + +pub const OLD_PERSIAN: &'static [(char, char)] = &[ + ('𐎠', '𐏃'), ('𐏈', '𐏕'), +]; + +pub const OLD_SOUTH_ARABIAN: &'static [(char, char)] = &[ + ('𐩠', '𐩿'), +]; + +pub const OLD_TURKIC: &'static [(char, char)] = &[ + ('𐰀', '𐱈'), +]; + +pub const ORIYA: &'static [(char, char)] = &[ + ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), ('ଓ', 'ନ'), + ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), ('଼', 'ୄ'), + ('େ', 'ୈ'), ('ୋ', '୍'), ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), + ('ୟ', 'ୣ'), ('୦', '୷'), +]; + +pub const OSAGE: &'static [(char, char)] = &[ + ('𐒰', '𐓓'), ('𐓘', '𐓻'), +]; + +pub const OSMANYA: &'static [(char, char)] = &[ + ('𐒀', '𐒝'), ('𐒠', '𐒩'), +]; + +pub const PAHAWH_HMONG: &'static [(char, char)] = &[ + ('𖬀', '𖭅'), ('𖭐', '𖭙'), ('𖭛', '𖭡'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), +]; + +pub const PALMYRENE: &'static [(char, char)] = &[ + ('𐡠', '𐡿'), +]; + +pub const PAU_CIN_HAU: &'static [(char, char)] = &[ + ('𑫀', '𑫸'), +]; + +pub const PHAGS_PA: &'static [(char, char)] = &[ + ('ꡀ', '꡷'), +]; + +pub const PHOENICIAN: &'static [(char, char)] = &[ + ('𐤀', '𐤛'), ('𐤟', '𐤟'), +]; + +pub const PSALTER_PAHLAVI: &'static [(char, char)] = &[ + ('𐮀', '𐮑'), ('𐮙', '𐮜'), ('𐮩', '𐮯'), +]; + +pub const REJANG: &'static [(char, char)] = &[ + ('ꤰ', '꥓'), ('꥟', '꥟'), +]; + +pub const RUNIC: &'static [(char, char)] = &[ + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), +]; + +pub const SAMARITAN: &'static [(char, char)] = &[ + ('ࠀ', '࠭'), ('࠰', '࠾'), +]; + +pub const SAURASHTRA: &'static [(char, char)] = &[ + ('ꢀ', 'ꣅ'), ('꣎', '꣙'), +]; + +pub const SHARADA: &'static [(char, char)] = &[ + ('𑆀', '𑇍'), ('𑇐', '𑇟'), +]; + +pub const SHAVIAN: &'static [(char, char)] = &[ + ('𐑐', '𐑿'), +]; + +pub const SIDDHAM: &'static [(char, char)] = &[ + ('𑖀', '𑖵'), ('𑖸', '𑗝'), +]; + +pub const SIGNWRITING: &'static [(char, char)] = &[ + ('𝠀', '𝪋'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), +]; + +pub const SINHALA: &'static [(char, char)] = &[ + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), ('ා', 'ු'), + ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), ('ෲ', '෴'), + ('𑇡', '𑇴'), +]; + +pub const SORA_SOMPENG: &'static [(char, char)] = &[ + ('𑃐', '𑃨'), ('𑃰', '𑃹'), +]; + +pub const SOYOMBO: &'static [(char, char)] = &[ + ('𑩐', '𑪃'), ('𑪆', '𑪜'), ('𑪞', '𑪢'), +]; + +pub const SUNDANESE: &'static [(char, char)] = &[ + ('ᮀ', 'ᮿ'), ('᳀', '᳇'), +]; + +pub const SYLOTI_NAGRI: &'static [(char, char)] = &[ + ('ꠀ', '꠫'), +]; + +pub const SYRIAC: &'static [(char, char)] = &[ + ('܀', '܍'), ('\u{70f}', '݊'), ('ݍ', 'ݏ'), ('ࡠ', 'ࡪ'), +]; + +pub const TAGALOG: &'static [(char, char)] = &[ + ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), +]; + +pub const TAGBANWA: &'static [(char, char)] = &[ + ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), +]; + +pub const TAI_LE: &'static [(char, char)] = &[ + ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), +]; + +pub const TAI_THAM: &'static [(char, char)] = &[ + ('ᨠ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), + ('᪠', '᪭'), +]; + +pub const TAI_VIET: &'static [(char, char)] = &[ + ('ꪀ', 'ꫂ'), ('ꫛ', '꫟'), +]; + +pub const TAKRI: &'static [(char, char)] = &[ + ('𑚀', '𑚷'), ('𑛀', '𑛉'), +]; + +pub const TAMIL: &'static [(char, char)] = &[ + ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), + ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), ('௦', '௺'), +]; + +pub const TANGUT: &'static [(char, char)] = &[ + ('𖿠', '𖿠'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), +]; + +pub const TELUGU: &'static [(char, char)] = &[ + ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), + ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), + ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), ('౦', '౯'), + ('౸', '౿'), +]; + +pub const THAANA: &'static [(char, char)] = &[ + ('ހ', 'ޱ'), +]; + +pub const THAI: &'static [(char, char)] = &[ + ('ก', 'ฺ'), ('เ', '๛'), +]; + +pub const TIBETAN: &'static [(char, char)] = &[ + ('ༀ', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', 'ྗ'), ('ྙ', 'ྼ'), + ('྾', '࿌'), ('࿎', '࿔'), ('࿙', '࿚'), +]; + +pub const TIFINAGH: &'static [(char, char)] = &[ + ('ⴰ', 'ⵧ'), ('ⵯ', '⵰'), ('⵿', '⵿'), +]; + +pub const TIRHUTA: &'static [(char, char)] = &[ + ('𑒀', '𑓇'), ('𑓐', '𑓙'), +]; + +pub const UGARITIC: &'static [(char, char)] = &[ + ('𐎀', '𐎝'), ('𐎟', '𐎟'), +]; + +pub const VAI: &'static [(char, char)] = &[ + ('ꔀ', 'ꘫ'), +]; + +pub const WARANG_CITI: &'static [(char, char)] = &[ + ('𑢠', '𑣲'), ('𑣿', '𑣿'), +]; + +pub const YI: &'static [(char, char)] = &[ + ('ꀀ', 'ꒌ'), ('꒐', '꓆'), +]; + +pub const ZANABAZAR_SQUARE: &'static [(char, char)] = &[ + ('𑨀', '𑩇'), +]; diff --git a/bash-5.1/vendor/regex-syntax/src/unicode_tables/script_extension.rs b/bash-5.1/vendor/regex-syntax/src/unicode_tables/script_extension.rs new file mode 100644 index 0000000..10b6c3e --- /dev/null +++ b/bash-5.1/vendor/regex-syntax/src/unicode_tables/script_extension.rs @@ -0,0 +1,785 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate script-extension tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("Adlam", ADLAM), ("Ahom", AHOM), + ("Anatolian_Hieroglyphs", ANATOLIAN_HIEROGLYPHS), ("Arabic", ARABIC), + ("Armenian", ARMENIAN), ("Avestan", AVESTAN), ("Balinese", BALINESE), + ("Bamum", BAMUM), ("Bassa_Vah", BASSA_VAH), ("Batak", BATAK), + ("Bengali", BENGALI), ("Bhaiksuki", BHAIKSUKI), ("Bopomofo", BOPOMOFO), + ("Brahmi", BRAHMI), ("Braille", BRAILLE), ("Buginese", BUGINESE), + ("Buhid", BUHID), ("Canadian_Aboriginal", CANADIAN_ABORIGINAL), + ("Carian", CARIAN), ("Caucasian_Albanian", CAUCASIAN_ALBANIAN), + ("Chakma", CHAKMA), ("Cham", CHAM), ("Cherokee", CHEROKEE), + ("Common", COMMON), ("Coptic", COPTIC), ("Cuneiform", CUNEIFORM), + ("Cypriot", CYPRIOT), ("Cyrillic", CYRILLIC), ("Deseret", DESERET), + ("Devanagari", DEVANAGARI), ("Duployan", DUPLOYAN), + ("Egyptian_Hieroglyphs", EGYPTIAN_HIEROGLYPHS), ("Elbasan", ELBASAN), + ("Ethiopic", ETHIOPIC), ("Georgian", GEORGIAN), ("Glagolitic", GLAGOLITIC), + ("Gothic", GOTHIC), ("Grantha", GRANTHA), ("Greek", GREEK), + ("Gujarati", GUJARATI), ("Gurmukhi", GURMUKHI), ("Han", HAN), + ("Hangul", HANGUL), ("Hanunoo", HANUNOO), ("Hatran", HATRAN), + ("Hebrew", HEBREW), ("Hiragana", HIRAGANA), + ("Imperial_Aramaic", IMPERIAL_ARAMAIC), ("Inherited", INHERITED), + ("Inscriptional_Pahlavi", INSCRIPTIONAL_PAHLAVI), + ("Inscriptional_Parthian", INSCRIPTIONAL_PARTHIAN), ("Javanese", JAVANESE), + ("Kaithi", KAITHI), ("Kannada", KANNADA), ("Katakana", KATAKANA), + ("Kayah_Li", KAYAH_LI), ("Kharoshthi", KHAROSHTHI), ("Khmer", KHMER), + ("Khojki", KHOJKI), ("Khudawadi", KHUDAWADI), ("Lao", LAO), + ("Latin", LATIN), ("Lepcha", LEPCHA), ("Limbu", LIMBU), + ("Linear_A", LINEAR_A), ("Linear_B", LINEAR_B), ("Lisu", LISU), + ("Lycian", LYCIAN), ("Lydian", LYDIAN), ("Mahajani", MAHAJANI), + ("Malayalam", MALAYALAM), ("Mandaic", MANDAIC), ("Manichaean", MANICHAEAN), + ("Marchen", MARCHEN), ("Masaram_Gondi", MASARAM_GONDI), + ("Meetei_Mayek", MEETEI_MAYEK), ("Mende_Kikakui", MENDE_KIKAKUI), + ("Meroitic_Cursive", MEROITIC_CURSIVE), + ("Meroitic_Hieroglyphs", MEROITIC_HIEROGLYPHS), ("Miao", MIAO), + ("Modi", MODI), ("Mongolian", MONGOLIAN), ("Mro", MRO), + ("Multani", MULTANI), ("Myanmar", MYANMAR), ("Nabataean", NABATAEAN), + ("New_Tai_Lue", NEW_TAI_LUE), ("Newa", NEWA), ("Nko", NKO), + ("Nushu", NUSHU), ("Ogham", OGHAM), ("Ol_Chiki", OL_CHIKI), + ("Old_Hungarian", OLD_HUNGARIAN), ("Old_Italic", OLD_ITALIC), + ("Old_North_Arabian", OLD_NORTH_ARABIAN), ("Old_Permic", OLD_PERMIC), + ("Old_Persian", OLD_PERSIAN), ("Old_South_Arabian", OLD_SOUTH_ARABIAN), + ("Old_Turkic", OLD_TURKIC), ("Oriya", ORIYA), ("Osage", OSAGE), + ("Osmanya", OSMANYA), ("Pahawh_Hmong", PAHAWH_HMONG), + ("Palmyrene", PALMYRENE), ("Pau_Cin_Hau", PAU_CIN_HAU), + ("Phags_Pa", PHAGS_PA), ("Phoenician", PHOENICIAN), + ("Psalter_Pahlavi", PSALTER_PAHLAVI), ("Rejang", REJANG), ("Runic", RUNIC), + ("Samaritan", SAMARITAN), ("Saurashtra", SAURASHTRA), ("Sharada", SHARADA), + ("Shavian", SHAVIAN), ("Siddham", SIDDHAM), ("SignWriting", SIGNWRITING), + ("Sinhala", SINHALA), ("Sora_Sompeng", SORA_SOMPENG), ("Soyombo", SOYOMBO), + ("Sundanese", SUNDANESE), ("Syloti_Nagri", SYLOTI_NAGRI), + ("Syriac", SYRIAC), ("Tagalog", TAGALOG), ("Tagbanwa", TAGBANWA), + ("Tai_Le", TAI_LE), ("Tai_Tham", TAI_THAM), ("Tai_Viet", TAI_VIET), + ("Takri", TAKRI), ("Tamil", TAMIL), ("Tangut", TANGUT), ("Telugu", TELUGU), + ("Thaana", THAANA), ("Thai", THAI), ("Tibetan", TIBETAN), + ("Tifinagh", TIFINAGH), ("Tirhuta", TIRHUTA), ("Ugaritic", UGARITIC), + ("Vai", VAI), ("Warang_Citi", WARANG_CITI), ("Yi", YI), + ("Zanabazar_Square", ZANABAZAR_SQUARE), +]; + +pub const ADLAM: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞥞', '𞥟'), +]; + +pub const AHOM: &'static [(char, char)] = &[ + ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜿'), +]; + +pub const ANATOLIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𔐀', '𔙆'), +]; + +pub const ARABIC: &'static [(char, char)] = &[ + ('\u{600}', '\u{604}'), ('؆', '\u{61c}'), ('؞', 'ۜ'), ('۞', 'ۿ'), + ('ݐ', 'ݿ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), + ('ࣣ', 'ࣿ'), ('ﭐ', '﯁'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), + ('ﶒ', 'ﷇ'), ('ﷰ', '﷽'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('𐋠', '𐋻'), ('𐹠', '𐹾'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), + ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), + ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), + ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), + ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), + ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), + ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), + ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), + ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), +]; + +pub const ARMENIAN: &'static [(char, char)] = &[ + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('։', '֊'), ('֍', '֏'), + ('ﬓ', 'ﬗ'), +]; + +pub const AVESTAN: &'static [(char, char)] = &[ + ('𐬀', '𐬵'), ('𐬹', '𐬿'), +]; + +pub const BALINESE: &'static [(char, char)] = &[ + ('ᬀ', 'ᭋ'), ('᭐', '᭼'), +]; + +pub const BAMUM: &'static [(char, char)] = &[ + ('ꚠ', '꛷'), ('𖠀', '𖨸'), +]; + +pub const BASSA_VAH: &'static [(char, char)] = &[ + ('𖫐', '𖫭'), ('𖫰', '𖫵'), +]; + +pub const BATAK: &'static [(char, char)] = &[ + ('ᯀ', '᯳'), ('᯼', '᯿'), +]; + +pub const BENGALI: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ঀ', 'ঃ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('়', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৎ'), + ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', '৽'), + ('᳷', '᳷'), ('꣱', '꣱'), +]; + +pub const BHAIKSUKI: &'static [(char, char)] = &[ + ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱅'), ('𑱐', '𑱬'), +]; + +pub const BOPOMOFO: &'static [(char, char)] = &[ + ('˪', '˫'), ('、', '〃'), ('〈', '】'), ('〓', '〟'), + ('〪', '〭'), ('〰', '〰'), ('〷', '〷'), ('・', '・'), + ('ㄅ', 'ㄮ'), ('ㆠ', 'ㆺ'), ('﹅', '﹆'), ('。', '・'), +]; + +pub const BRAHMI: &'static [(char, char)] = &[ + ('𑀀', '𑁍'), ('𑁒', '𑁯'), ('𑁿', '𑁿'), +]; + +pub const BRAILLE: &'static [(char, char)] = &[ + ('⠀', '⣿'), +]; + +pub const BUGINESE: &'static [(char, char)] = &[ + ('ᨀ', 'ᨛ'), ('᨞', '᨟'), ('ꧏ', 'ꧏ'), +]; + +pub const BUHID: &'static [(char, char)] = &[ + ('᜵', '᜶'), ('ᝀ', 'ᝓ'), +]; + +pub const CANADIAN_ABORIGINAL: &'static [(char, char)] = &[ + ('᐀', 'ᙿ'), ('ᢰ', 'ᣵ'), +]; + +pub const CARIAN: &'static [(char, char)] = &[ + ('𐊠', '𐋐'), +]; + +pub const CAUCASIAN_ALBANIAN: &'static [(char, char)] = &[ + ('𐔰', '𐕣'), ('𐕯', '𐕯'), +]; + +pub const CHAKMA: &'static [(char, char)] = &[ + ('০', '৯'), ('၀', '၉'), ('𑄀', '𑄴'), ('𑄶', '𑅃'), +]; + +pub const CHAM: &'static [(char, char)] = &[ + ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), ('꩜', '꩟'), +]; + +pub const CHEROKEE: &'static [(char, char)] = &[ + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ꭰ', 'ꮿ'), +]; + +pub const COMMON: &'static [(char, char)] = &[ + ('\u{0}', '@'), ('[', '`'), ('{', '©'), ('«', '¹'), ('»', '¿'), + ('×', '×'), ('÷', '÷'), ('ʹ', '˟'), ('˥', '˩'), ('ˬ', '˿'), + ('ʹ', 'ʹ'), (';', ';'), ('΅', '΅'), ('·', '·'), + ('\u{605}', '\u{605}'), ('\u{6dd}', '\u{6dd}'), ('\u{8e2}', '\u{8e2}'), + ('฿', '฿'), ('࿕', '࿘'), ('᛫', '᛭'), ('\u{2000}', '\u{200b}'), + ('\u{200e}', '\u{2064}'), ('\u{2066}', '⁰'), ('⁴', '⁾'), + ('₀', '₎'), ('₠', '₿'), ('℀', '℥'), ('℧', '℩'), + ('ℬ', 'ℱ'), ('ℳ', '⅍'), ('⅏', '⅟'), ('↉', '↋'), + ('←', '␦'), ('⑀', '⑊'), ('①', '⟿'), ('⤀', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯒'), + ('⯬', '⯯'), ('⸀', '⹂'), ('⹄', '⹉'), ('⿰', '⿻'), + ('\u{3000}', '\u{3000}'), ('〄', '〄'), ('〒', '〒'), ('〠', '〠'), + ('〶', '〶'), ('㉈', '㉟'), ('㉿', '㉿'), ('㊱', '㊿'), + ('㋌', '㋏'), ('㍱', '㍺'), ('㎀', '㏟'), ('㏿', '㏿'), + ('䷀', '䷿'), ('꜀', '꜡'), ('ꞈ', '꞊'), ('꭛', '꭛'), + ('﴾', '﴿'), ('︐', '︙'), ('︰', '﹄'), ('﹇', '﹒'), + ('﹔', '﹦'), ('﹨', '﹫'), ('\u{feff}', '\u{feff}'), ('!', '@'), + ('[', '`'), ('{', '⦆'), ('¢', '₩'), ('│', '○'), + ('\u{fff9}', '�'), ('𐆐', '𐆛'), ('𐇐', '𐇼'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄩', '𝅦'), ('𝅪', '\u{1d17a}'), ('𝆃', '𝆄'), + ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝌀', '𝍖'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), ('𝟎', '𝟿'), + ('🀀', '🀫'), ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), + ('🃁', '🃏'), ('🃑', '🃵'), ('🄀', '🄌'), ('🄐', '🄮'), + ('🄰', '🅫'), ('🅰', '🆬'), ('🇦', '🇿'), ('🈁', '🈂'), + ('🈐', '🈻'), ('🉀', '🉈'), ('🉠', '🉥'), ('🌀', '🛔'), + ('🛠', '🛬'), ('🛰', '🛸'), ('🜀', '🝳'), ('🞀', '🟔'), + ('🠀', '🠋'), ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), + ('🢐', '🢭'), ('🤀', '🤋'), ('🤐', '🤾'), ('🥀', '🥌'), + ('🥐', '🥫'), ('🦀', '🦗'), ('🧀', '🧀'), ('🧐', '🧦'), + ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}'), +]; + +pub const COPTIC: &'static [(char, char)] = &[ + ('Ϣ', 'ϯ'), ('Ⲁ', 'ⳳ'), ('⳹', '⳿'), ('𐋠', '𐋻'), +]; + +pub const CUNEIFORM: &'static [(char, char)] = &[ + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒑰', '𒑴'), ('𒒀', '𒕃'), +]; + +pub const CYPRIOT: &'static [(char, char)] = &[ + ('𐄀', '𐄂'), ('𐄇', '𐄳'), ('𐄷', '𐄿'), ('𐠀', '𐠅'), + ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), + ('𐠿', '𐠿'), +]; + +pub const CYRILLIC: &'static [(char, char)] = &[ + ('Ѐ', 'ԯ'), ('ᲀ', 'ᲈ'), ('ᴫ', 'ᴫ'), ('ᵸ', 'ᵸ'), + ('ⷠ', 'ⷿ'), ('⹃', '⹃'), ('Ꙁ', 'ꚟ'), ('︮', '︯'), +]; + +pub const DESERET: &'static [(char, char)] = &[ + ('𐐀', '𐑏'), +]; + +pub const DEVANAGARI: &'static [(char, char)] = &[ + ('ऀ', 'ॿ'), ('᳐', 'ᳶ'), ('᳸', '᳹'), ('⃰', '⃰'), + ('꠰', '꠹'), ('꣠', 'ꣽ'), +]; + +pub const DUPLOYAN: &'static [(char, char)] = &[ + ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), + ('𛲜', '\u{1bca3}'), +]; + +pub const EGYPTIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𓀀', '𓐮'), +]; + +pub const ELBASAN: &'static [(char, char)] = &[ + ('𐔀', '𐔧'), +]; + +pub const ETHIOPIC: &'static [(char, char)] = &[ + ('ሀ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፼'), ('ᎀ', '᎙'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), +]; + +pub const GEORGIAN: &'static [(char, char)] = &[ + ('։', '։'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('ა', 'ჿ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), +]; + +pub const GLAGOLITIC: &'static [(char, char)] = &[ + ('҄', '҄'), ('҇', '҇'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('⹃', '⹃'), + ('꙯', '꙯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), +]; + +pub const GOTHIC: &'static [(char, char)] = &[ + ('𐌰', '𐍊'), +]; + +pub const GRANTHA: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ப', 'ப'), ('வ', 'வ'), + ('௦', '௲'), ('᳐', '᳐'), ('᳒', '᳓'), ('ᳲ', '᳴'), + ('᳸', '᳹'), ('⃰', '⃰'), ('𑌀', '𑌃'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), + ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), +]; + +pub const GREEK: &'static [(char, char)] = &[ + ('͂', '͂'), ('ͅ', 'ͅ'), ('Ͱ', 'ͳ'), ('͵', 'ͷ'), ('ͺ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('΄', '΄'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϡ'), ('ϰ', 'Ͽ'), ('ᴦ', 'ᴪ'), ('ᵝ', 'ᵡ'), + ('ᵦ', 'ᵪ'), ('ᶿ', '᷁'), ('ἀ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ῄ'), ('ῆ', 'ΐ'), ('ῖ', 'Ί'), ('῝', '`'), + ('ῲ', 'ῴ'), ('ῶ', '῾'), ('Ω', 'Ω'), ('ꭥ', 'ꭥ'), + ('𐅀', '𐆎'), ('𐆠', '𐆠'), ('𝈀', '𝉅'), +]; + +pub const GUJARATI: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ઁ', 'ઃ'), ('અ', 'ઍ'), + ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), ('લ', 'ળ'), + ('વ', 'હ'), ('઼', 'ૅ'), ('ે', 'ૉ'), ('ો', '્'), + ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), ('૦', '૱'), ('ૹ', '૿'), + ('꠰', '꠹'), +]; + +pub const GURMUKHI: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('਼', '਼'), ('ਾ', 'ੂ'), + ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), + ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), ('꠰', '꠹'), +]; + +pub const HAN: &'static [(char, char)] = &[ + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('、', '〃'), + ('々', '】'), ('〓', '〟'), ('〡', '〭'), ('〰', '〰'), + ('〷', '〿'), ('・', '・'), ('㆐', '㆟'), ('㇀', '㇣'), + ('㈠', '㉇'), ('㊀', '㊰'), ('㋀', '㋋'), ('㍘', '㍰'), + ('㍻', '㍿'), ('㏠', '㏾'), ('㐀', '䶵'), ('一', '鿪'), + ('豈', '舘'), ('並', '龎'), ('﹅', '﹆'), ('。', '・'), + ('𝍠', '𝍱'), ('🉐', '🉑'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const HANGUL: &'static [(char, char)] = &[ + ('ᄀ', 'ᇿ'), ('、', '〃'), ('〈', '】'), ('〓', '〟'), + ('〮', '〰'), ('〷', '〷'), ('・', '・'), ('ㄱ', 'ㆎ'), + ('㈀', '㈞'), ('㉠', '㉾'), ('ꥠ', 'ꥼ'), ('가', '힣'), + ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('﹅', '﹆'), ('。', '・'), + ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), + ('ᅳ', 'ᅵ'), +]; + +pub const HANUNOO: &'static [(char, char)] = &[ + ('ᜠ', '᜶'), +]; + +pub const HATRAN: &'static [(char, char)] = &[ + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐣻', '𐣿'), +]; + +pub const HEBREW: &'static [(char, char)] = &[ + ('֑', 'ׇ'), ('א', 'ת'), ('װ', '״'), ('יִ', 'זּ'), ('טּ', 'לּ'), + ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﭏ'), +]; + +pub const HIRAGANA: &'static [(char, char)] = &[ + ('、', '〃'), ('〈', '】'), ('〓', '〟'), ('〰', '〵'), + ('〷', '〷'), ('〼', '〽'), ('ぁ', 'ゖ'), ('゙', '゠'), + ('・', 'ー'), ('﹅', '﹆'), ('。', '・'), ('ー', 'ー'), + ('゙', '゚'), ('𛀁', '𛄞'), ('🈀', '🈀'), +]; + +pub const IMPERIAL_ARAMAIC: &'static [(char, char)] = &[ + ('𐡀', '𐡕'), ('𐡗', '𐡟'), +]; + +pub const INHERITED: &'static [(char, char)] = &[ + ('̀', '́'), ('̓', '̈́'), ('͆', '͢'), ('᪰', '᪾'), ('᷂', '᷹'), + ('᷻', '᷿'), ('\u{200c}', '\u{200d}'), ('⃐', '⃯'), ('︀', '️'), + ('︠', '︭'), ('𐇽', '𐇽'), ('𝅧', '𝅩'), ('𝅻', '𝆂'), + ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('󠄀', '󠇯'), +]; + +pub const INSCRIPTIONAL_PAHLAVI: &'static [(char, char)] = &[ + ('𐭠', '𐭲'), ('𐭸', '𐭿'), +]; + +pub const INSCRIPTIONAL_PARTHIAN: &'static [(char, char)] = &[ + ('𐭀', '𐭕'), ('𐭘', '𐭟'), +]; + +pub const JAVANESE: &'static [(char, char)] = &[ + ('ꦀ', '꧍'), ('ꧏ', '꧙'), ('꧞', '꧟'), +]; + +pub const KAITHI: &'static [(char, char)] = &[ + ('०', '९'), ('꠰', '꠹'), ('𑂀', '𑃁'), +]; + +pub const KANNADA: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('಼', 'ೄ'), ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), ('೦', '೯'), ('ೱ', 'ೲ'), + ('᳚', '᳚'), ('ᳵ', 'ᳵ'), ('꠰', '꠵'), +]; + +pub const KATAKANA: &'static [(char, char)] = &[ + ('、', '〃'), ('〈', '】'), ('〓', '〟'), ('〰', '〵'), + ('〷', '〷'), ('〼', '〽'), ('゙', '゜'), ('゠', 'ヿ'), + ('ㇰ', 'ㇿ'), ('㋐', '㋾'), ('㌀', '㍗'), ('﹅', '﹆'), + ('。', '゚'), ('𛀀', '𛀀'), +]; + +pub const KAYAH_LI: &'static [(char, char)] = &[ + ('꤀', '꤯'), +]; + +pub const KHAROSHTHI: &'static [(char, char)] = &[ + ('𐨀', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), + ('𐨙', '𐨳'), ('𐨸', '𐨺'), ('𐨿', '𐩇'), ('𐩐', '𐩘'), +]; + +pub const KHMER: &'static [(char, char)] = &[ + ('ក', '៝'), ('០', '៩'), ('៰', '៹'), ('᧠', '᧿'), +]; + +pub const KHOJKI: &'static [(char, char)] = &[ + ('૦', '૯'), ('𑈀', '𑈑'), ('𑈓', '𑈾'), +]; + +pub const KHUDAWADI: &'static [(char, char)] = &[ + ('।', '॥'), ('꠰', '꠹'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), +]; + +pub const LAO: &'static [(char, char)] = &[ + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), +]; + +pub const LATIN: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('º', 'º'), ('À', 'Ö'), + ('Ø', 'ö'), ('ø', 'ʸ'), ('ˠ', 'ˤ'), ('ͣ', 'ͯ'), ('҅', '҆'), + ('॑', '॒'), ('჻', '჻'), ('ᴀ', 'ᴥ'), ('ᴬ', 'ᵜ'), + ('ᵢ', 'ᵥ'), ('ᵫ', 'ᵷ'), ('ᵹ', 'ᶾ'), ('Ḁ', 'ỿ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('⃰', '⃰'), + ('K', 'Å'), ('Ⅎ', 'Ⅎ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⱡ', 'Ɀ'), ('Ꜣ', 'ꞇ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟷ', 'ꟿ'), ('꤮', '꤮'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭤ'), + ('ff', 'st'), ('A', 'Z'), ('a', 'z'), +]; + +pub const LEPCHA: &'static [(char, char)] = &[ + ('ᰀ', '᰷'), ('᰻', '᱉'), ('ᱍ', 'ᱏ'), +]; + +pub const LIMBU: &'static [(char, char)] = &[ + ('॥', '॥'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), + ('᥀', '᥀'), ('᥄', '᥏'), +]; + +pub const LINEAR_A: &'static [(char, char)] = &[ + ('𐄇', '𐄳'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), +]; + +pub const LINEAR_B: &'static [(char, char)] = &[ + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐄀', '𐄂'), + ('𐄇', '𐄳'), ('𐄷', '𐄿'), +]; + +pub const LISU: &'static [(char, char)] = &[ + ('ꓐ', '꓿'), +]; + +pub const LYCIAN: &'static [(char, char)] = &[ + ('𐊀', '𐊜'), +]; + +pub const LYDIAN: &'static [(char, char)] = &[ + ('𐤠', '𐤹'), ('𐤿', '𐤿'), +]; + +pub const MAHAJANI: &'static [(char, char)] = &[ + ('।', '९'), ('꠰', '꠹'), ('𑅐', '𑅶'), +]; + +pub const MALAYALAM: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ഀ', 'ഃ'), ('അ', 'ഌ'), + ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), ('ൊ', '൏'), + ('ൔ', 'ൣ'), ('൦', 'ൿ'), ('᳚', '᳚'), +]; + +pub const MANDAIC: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('ࡀ', '࡛'), ('࡞', '࡞'), +]; + +pub const MANICHAEAN: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('𐫀', '𐫦'), ('𐫫', '𐫶'), +]; + +pub const MARCHEN: &'static [(char, char)] = &[ + ('𑱰', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), +]; + +pub const MASARAM_GONDI: &'static [(char, char)] = &[ + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), +]; + +pub const MEETEI_MAYEK: &'static [(char, char)] = &[ + ('ꫠ', '꫶'), ('ꯀ', '꯭'), ('꯰', '꯹'), +]; + +pub const MENDE_KIKAKUI: &'static [(char, char)] = &[ + ('𞠀', '𞣄'), ('𞣇', '𞣖'), +]; + +pub const MEROITIC_CURSIVE: &'static [(char, char)] = &[ + ('𐦠', '𐦷'), ('𐦼', '𐧏'), ('𐧒', '𐧿'), +]; + +pub const MEROITIC_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𐦀', '𐦟'), +]; + +pub const MIAO: &'static [(char, char)] = &[ + ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾏', '𖾟'), +]; + +pub const MODI: &'static [(char, char)] = &[ + ('꠰', '꠹'), ('𑘀', '𑙄'), ('𑙐', '𑙙'), +]; + +pub const MONGOLIAN: &'static [(char, char)] = &[ + ('᠀', '\u{180e}'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), + ('𑙠', '𑙬'), +]; + +pub const MRO: &'static [(char, char)] = &[ + ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖩮', '𖩯'), +]; + +pub const MULTANI: &'static [(char, char)] = &[ + ('੦', '੯'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊩'), +]; + +pub const MYANMAR: &'static [(char, char)] = &[ + ('က', '႟'), ('꤮', '꤮'), ('ꧠ', 'ꧾ'), ('ꩠ', 'ꩿ'), +]; + +pub const NABATAEAN: &'static [(char, char)] = &[ + ('𐢀', '𐢞'), ('𐢧', '𐢯'), +]; + +pub const NEW_TAI_LUE: &'static [(char, char)] = &[ + ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('᧞', '᧟'), +]; + +pub const NEWA: &'static [(char, char)] = &[ + ('𑐀', '𑑙'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), +]; + +pub const NKO: &'static [(char, char)] = &[ + ('߀', 'ߺ'), +]; + +pub const NUSHU: &'static [(char, char)] = &[ + ('𖿡', '𖿡'), ('𛅰', '𛋻'), +]; + +pub const OGHAM: &'static [(char, char)] = &[ + ('\u{1680}', '᚜'), +]; + +pub const OL_CHIKI: &'static [(char, char)] = &[ + ('᱐', '᱿'), +]; + +pub const OLD_HUNGARIAN: &'static [(char, char)] = &[ + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), +]; + +pub const OLD_ITALIC: &'static [(char, char)] = &[ + ('𐌀', '𐌣'), ('𐌭', '𐌯'), +]; + +pub const OLD_NORTH_ARABIAN: &'static [(char, char)] = &[ + ('𐪀', '𐪟'), +]; + +pub const OLD_PERMIC: &'static [(char, char)] = &[ + ('҃', '҃'), ('𐍐', '𐍺'), +]; + +pub const OLD_PERSIAN: &'static [(char, char)] = &[ + ('𐎠', '𐏃'), ('𐏈', '𐏕'), +]; + +pub const OLD_SOUTH_ARABIAN: &'static [(char, char)] = &[ + ('𐩠', '𐩿'), +]; + +pub const OLD_TURKIC: &'static [(char, char)] = &[ + ('𐰀', '𐱈'), +]; + +pub const ORIYA: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୷'), +]; + +pub const OSAGE: &'static [(char, char)] = &[ + ('𐒰', '𐓓'), ('𐓘', '𐓻'), +]; + +pub const OSMANYA: &'static [(char, char)] = &[ + ('𐒀', '𐒝'), ('𐒠', '𐒩'), +]; + +pub const PAHAWH_HMONG: &'static [(char, char)] = &[ + ('𖬀', '𖭅'), ('𖭐', '𖭙'), ('𖭛', '𖭡'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), +]; + +pub const PALMYRENE: &'static [(char, char)] = &[ + ('𐡠', '𐡿'), +]; + +pub const PAU_CIN_HAU: &'static [(char, char)] = &[ + ('𑫀', '𑫸'), +]; + +pub const PHAGS_PA: &'static [(char, char)] = &[ + ('᠂', '᠃'), ('᠅', '᠅'), ('ꡀ', '꡷'), +]; + +pub const PHOENICIAN: &'static [(char, char)] = &[ + ('𐤀', '𐤛'), ('𐤟', '𐤟'), +]; + +pub const PSALTER_PAHLAVI: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('𐮀', '𐮑'), ('𐮙', '𐮜'), ('𐮩', '𐮯'), +]; + +pub const REJANG: &'static [(char, char)] = &[ + ('ꤰ', '꥓'), ('꥟', '꥟'), +]; + +pub const RUNIC: &'static [(char, char)] = &[ + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), +]; + +pub const SAMARITAN: &'static [(char, char)] = &[ + ('ࠀ', '࠭'), ('࠰', '࠾'), +]; + +pub const SAURASHTRA: &'static [(char, char)] = &[ + ('ꢀ', 'ꣅ'), ('꣎', '꣙'), +]; + +pub const SHARADA: &'static [(char, char)] = &[ + ('॑', '॑'), ('᳗', '᳗'), ('᳙', '᳙'), ('᳜', '᳝'), + ('᳠', '᳠'), ('𑆀', '𑇍'), ('𑇐', '𑇟'), +]; + +pub const SHAVIAN: &'static [(char, char)] = &[ + ('𐑐', '𐑿'), +]; + +pub const SIDDHAM: &'static [(char, char)] = &[ + ('𑖀', '𑖵'), ('𑖸', '𑗝'), +]; + +pub const SIGNWRITING: &'static [(char, char)] = &[ + ('𝠀', '𝪋'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), +]; + +pub const SINHALA: &'static [(char, char)] = &[ + ('।', '॥'), ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), + ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), + ('ෲ', '෴'), ('𑇡', '𑇴'), +]; + +pub const SORA_SOMPENG: &'static [(char, char)] = &[ + ('𑃐', '𑃨'), ('𑃰', '𑃹'), +]; + +pub const SOYOMBO: &'static [(char, char)] = &[ + ('𑩐', '𑪃'), ('𑪆', '𑪜'), ('𑪞', '𑪢'), +]; + +pub const SUNDANESE: &'static [(char, char)] = &[ + ('ᮀ', 'ᮿ'), ('᳀', '᳇'), +]; + +pub const SYLOTI_NAGRI: &'static [(char, char)] = &[ + ('।', '॥'), ('০', '৯'), ('ꠀ', '꠫'), +]; + +pub const SYRIAC: &'static [(char, char)] = &[ + ('،', '،'), ('؛', '\u{61c}'), ('؟', '؟'), ('ـ', 'ـ'), ('ً', 'ٕ'), + ('ٰ', 'ٰ'), ('܀', '܍'), ('\u{70f}', '݊'), ('ݍ', 'ݏ'), ('ࡠ', 'ࡪ'), +]; + +pub const TAGALOG: &'static [(char, char)] = &[ + ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), ('᜵', '᜶'), +]; + +pub const TAGBANWA: &'static [(char, char)] = &[ + ('᜵', '᜶'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), +]; + +pub const TAI_LE: &'static [(char, char)] = &[ + ('၀', '၉'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), +]; + +pub const TAI_THAM: &'static [(char, char)] = &[ + ('ᨠ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), + ('᪠', '᪭'), +]; + +pub const TAI_VIET: &'static [(char, char)] = &[ + ('ꪀ', 'ꫂ'), ('ꫛ', '꫟'), +]; + +pub const TAKRI: &'static [(char, char)] = &[ + ('।', '॥'), ('꠰', '꠹'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), +]; + +pub const TAMIL: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), + ('எ', 'ஐ'), ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), + ('ஞ', 'ட'), ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), + ('ா', 'ூ'), ('ெ', 'ை'), ('ொ', '்'), ('ௐ', 'ௐ'), + ('ௗ', 'ௗ'), ('௦', '௺'), ('᳚', '᳚'), ('ꣳ', 'ꣳ'), + ('𑌁', '𑌁'), ('𑌃', '𑌃'), ('𑌼', '𑌼'), +]; + +pub const TANGUT: &'static [(char, char)] = &[ + ('𖿠', '𖿠'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), +]; + +pub const TELUGU: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ఀ', 'ః'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ౄ'), + ('ె', 'ై'), ('ొ', '్'), ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), + ('ౠ', 'ౣ'), ('౦', '౯'), ('౸', '౿'), ('᳚', '᳚'), +]; + +pub const THAANA: &'static [(char, char)] = &[ + ('،', '،'), ('؛', '\u{61c}'), ('؟', '؟'), ('٠', '٩'), ('ހ', 'ޱ'), + ('ﷲ', 'ﷲ'), ('﷽', '﷽'), +]; + +pub const THAI: &'static [(char, char)] = &[ + ('ก', 'ฺ'), ('เ', '๛'), +]; + +pub const TIBETAN: &'static [(char, char)] = &[ + ('ༀ', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', 'ྗ'), ('ྙ', 'ྼ'), + ('྾', '࿌'), ('࿎', '࿔'), ('࿙', '࿚'), +]; + +pub const TIFINAGH: &'static [(char, char)] = &[ + ('ⴰ', 'ⵧ'), ('ⵯ', '⵰'), ('⵿', '⵿'), +]; + +pub const TIRHUTA: &'static [(char, char)] = &[ + ('।', '॥'), ('꠰', '꠹'), ('𑒀', '𑓇'), ('𑓐', '𑓙'), +]; + +pub const UGARITIC: &'static [(char, char)] = &[ + ('𐎀', '𐎝'), ('𐎟', '𐎟'), +]; + +pub const VAI: &'static [(char, char)] = &[ + ('ꔀ', 'ꘫ'), +]; + +pub const WARANG_CITI: &'static [(char, char)] = &[ + ('𑢠', '𑣲'), ('𑣿', '𑣿'), +]; + +pub const YI: &'static [(char, char)] = &[ + ('、', '。'), ('〈', '】'), ('〔', '〛'), ('・', '・'), + ('ꀀ', 'ꒌ'), ('꒐', '꓆'), ('。', '・'), +]; + +pub const ZANABAZAR_SQUARE: &'static [(char, char)] = &[ + ('𑨀', '𑩇'), +]; diff --git a/bash-5.1/vendor/regex/.cargo-checksum.json b/bash-5.1/vendor/regex/.cargo-checksum.json new file mode 100644 index 0000000..d87976e --- /dev/null +++ b/bash-5.1/vendor/regex/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"fcd7f49e6346b83a49bd5012241b6d324bb5e3b8a2e28af4538fe3bf22ba0109","Cargo.toml":"a9480d427f34198d1a14806cbc22469a7a044f8fce07e801556cdf83e920333b","HACKING.md":"2e32478f02437c77376e79c697bc871e364d55ef296d246e8e9cc23e68384b5e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","PERFORMANCE.md":"c776b18758b6dc8f2f9d37e9a95261f75c5f744925e8ddf216b83953bf7467b7","README.md":"5715d9be2f5d0bfc0cbf6de2bfb0e6c21fc86176e47a0fb9f02dce5785efcac6","UNICODE.md":"d7992c142299cb79f524c964ca8d4cf247b5db99fcf4103e4eebaf6c54cf06f6","appveyor.yml":"3cc9496bd76b8ce1cd4be1c369974fd43798352aad595a36d6f4229bdeeb13d7","build.rs":"c0d78243f69dcab2cccb21fce62cffb761273865039d60b6c0019f4bd5936efd","ci/after_success.sh":"9a6089e0a64057e97b11158219921c664a6ac956c0fad20f007da29ef11c19af","ci/run-kcov":"a81cad2c3de4c6d704502cdc4227d7432b7765613c7b8c426db66ab03fe23bfb","ci/run-shootout-test":"be7edb66a4a65eaef6a2b7e6036b4b732effa8dcd931bf4cbd591d0ca32b8264","ci/script.sh":"96f45b854cc75ccf79d7e6525b356b1832ab84ee47d71c537f2ae86b081ab1f0","examples/regexdna-input.txt":"156a49710bb3e1ed4bc2bbb0af0f383b747b3d0281453cfff39c296124c598f8","examples/regexdna-output.txt":"35e85b19b70a893d752fd43e54e1e9da08bac43559191cea85b33387c24c4cc1","examples/shootout-regex-dna-bytes.rs":"f097a923fef2e9bd9a9abd3686eea84830e8050bb750bcab840b6575873227ff","examples/shootout-regex-dna-cheat.rs":"4b5a590ec88a9ba67cc4a34621cb038a400d45e64a15a354f3e07fdaf41a935b","examples/shootout-regex-dna-replace.rs":"15677e7de356427fe2b983e918de073a7a730337b090d4ab0e815e1e66f74f73","examples/shootout-regex-dna-single-cheat.rs":"5e743b3a6ec968713ce064a289b1fbd11c302add824d1c749a2ffb546c73128e","examples/shootout-regex-dna-single.rs":"c86969adb0fb08c5e23f749ec6922a58404da7d0e1925c848957a5144ddc8815","examples/shootout-regex-dna.rs":"e627f1e5e24c1cf4e9c9d52b844b6d971c59b7169b0e8762d8d9d1cb7debc6e6","scripts/frequencies.py":"df2cac150bc4ed42d2d97762535a5f260f3fe06d9d516721f68a52671a3b7a3b","scripts/regex-match-tests.py":"f1b3ad870c893510172bd84f8328b66ee99cd7aee7715a95a858468ff3e33635","src/backtrack.rs":"0372ada608dca9c8d3e1fabf56e33498f8ff4fbdfd445873c4a4be6657465c68","src/compile.rs":"19e26080022d036883bee8ca0595f3563cf67f114fe2dd564c83519a9f2a226d","src/dfa.rs":"163aa4ec0dcdb1ffc7dd687debc1d64acffeeca7861cb4bb303d2da0ad33b3a6","src/error.rs":"ef2224dfbb427ac15ad52f64a34da8b3c1d567483e31065dc73702e982b660e8","src/exec.rs":"6d60f56cbcf3309c6dd3d0134c14c145b44743cd974972f81d55bdb3d5749ac5","src/expand.rs":"4333da32d6fbb05ec05bead810eb659c5b012e2d361a9bb9e24bb30e8939fb88","src/freqs.rs":"e25871eec51d1c02c15abbc04d61dbea71fb2dbc15f370c98279687416c969de","src/input.rs":"9b092fe88a66b46dee0dfe0a2e67e4b78b01a32f53b28443b5f382b8514d0cfb","src/lib.rs":"a81f9edd271c1ffa86570e3094f17e51acccfb68eae34172b853ac196f2bb3d5","src/literal/mod.rs":"c395221efe19f36edd9d92c8f8283e5b30553e0e9b408ccb1430d11f038730f8","src/literal/teddy_avx2/fallback.rs":"f24b70f9dd028eefe2802b7bbc6b2dca97663b03a931058e3a59750f0693a15c","src/literal/teddy_avx2/imp.rs":"b0e4634bc9fbc793e3b0938b97a236df4b8fb17a0ac08040a6394bc73042aa8b","src/literal/teddy_avx2/mod.rs":"2feb1a41e3df8a77e8dbb3a08492ee3cf0bac2f05abddc0e35b964d6f5a86c0c","src/literal/teddy_ssse3/fallback.rs":"f24b70f9dd028eefe2802b7bbc6b2dca97663b03a931058e3a59750f0693a15c","src/literal/teddy_ssse3/imp.rs":"be4565c47a3807ab09343f2da4ef0e3297d4776719472efb60dee8e55380c2ec","src/literal/teddy_ssse3/mod.rs":"7554e6598326f3662f7632cc0c7d05aa48baed4a765f4b99647fab3c1b40f750","src/pattern.rs":"4e820c17a2b983050f47d3fd13282094ce9f27b75fd852fcec438d61f07f0b0b","src/pikevm.rs":"9600a8b135075f8cf62683e6b08c73834873a203347d275f1e9ca3a97221dbeb","src/prog.rs":"16426f718f1e111ef4784050b11aba3c0562ceaa186f45169db90d50b40717d6","src/re_builder.rs":"e0da4e925558c2afa8bf1d271750ac33e6603175408daffca85c19bb4ffaad4a","src/re_bytes.rs":"07e5a01581e304072dc710458211eefa84fa5984b9a33f46c605e4f7695f568e","src/re_set.rs":"f0fa1a98f8aa1eeee209fae70f9efd3f9043557de30dc1a940279555b21b688b","src/re_trait.rs":"8ecbdd8db8c8e4194acd71e4a751aa8409bbd495015a01bb7c8b425677f3fa39","src/re_unicode.rs":"02c95c63842144aacb6c74bc17e75266ad621b0fe993f29c8d6144fe24ff6179","src/sparse.rs":"04e70bb0bd006f806e8c9cf19825625e907036304823bc03b6c8f2e5046a38ef","src/testdata/LICENSE":"58cf078acc03da3e280a938c2bd9943f554fc9b6ced89ad93ba35ca436872899","src/testdata/README":"45f869e37f798905c773bfbe0ef19a5fb7e585cbf0b7c21b5b5a784e8cec3c14","src/testdata/basic.dat":"3756a5bdd6f387ed34731197fbdaab8521b0ae1726250100ba235756cb42b4b1","src/testdata/nullsubexpr.dat":"496ac0278eec3b6d9170faace14554569032dd3d909618364d9326156de39ecf","src/testdata/repetition.dat":"1f7959063015b284b18a4a2c1c8b416d438a2d6c4b1a362da43406b865f50e69","src/utf8.rs":"b0db05e53f2922219a5725fdae61c7715921bb3cf69ffe5045cdc78da10dc97e","src/vector/avx2.rs":"9ad5da7e09c3351474f9e05748118ac24894217297d36773c035486bd15195a1","src/vector/mod.rs":"8fe24ee6848eb7bf14c33ed26f13221ea00a868c9857fda3784a71147087cd55","src/vector/ssse3.rs":"42224541ec05e4d9aa520cf69d9747124155219cb316f97f099789438b66964e","tests/api.rs":"803faacd9ac5efc149959ff63a2132f5ca155f75a246b79807c549b464b5c497","tests/api_str.rs":"8ccb6c3dfe0220229ad33fcaf9dea420b414aea17c7498d978efd1b8aceaa980","tests/bytes.rs":"701422f68d55f950fdba32550e16b4bd20b06b37cbac06749558d16f7f58a3a7","tests/crazy.rs":"b0c593be5022341606ddb15b3d28aa39d2d52977db4b1b72c41c6133a7f7a7e0","tests/flags.rs":"cd3788760defc667b32adb2732b6657b289372e1051fc240dfd0e435e2835353","tests/fowler.rs":"e0b7420fa5b636301d4c11cd4dfb803ec09fa7b27be47c594d231167de1241e3","tests/macros.rs":"f021b62e3ce8d122f6450a5aab36972eccf4c21c62a53c604924d4d01d90c0d8","tests/macros_bytes.rs":"dffa91e2e572f5b223b83eba4d32732b1d76cfcfebfbd7f836eeaa929f637657","tests/macros_str.rs":"4f665f039cd5408fc7b4c0fab2983ef3ebd3dc1cd52f7b7e46d7644a2e85b428","tests/misc.rs":"c8cc85ac916980ebd053df2444fe9b795a00f2ac42c5cd828fc3df487f689265","tests/multiline.rs":"4e872a9473bc229d955716c18c77aa3530625a8f3a28ecaefdb70b9aff0f0a8b","tests/noparse.rs":"8850d31cb95e413e3a67edecce8590cd158f49779abcc2e5722381113346179c","tests/regression.rs":"dc2404111c1f4d5ac0f8f31ea62acb40a635c17a3870b273dc9ec6ea6ff84567","tests/replace.rs":"f1b8ce1a6fede222c6151d37416458515541da285ec2720d6ac950cbad7991e2","tests/searcher.rs":"124c9909a1e8fcfddee8ecfae3a1fb9d76f9ddac62fda23d9b895744728a0aa8","tests/set.rs":"0cecf5d2acb3d0df2b051e0ab56a4a853bb58c0e922480f5e460b9a05a0d16af","tests/shortest_match.rs":"7ca223e0a61b1a26a1f36465ab49de021475295e18f4d6421497461af1e107be","tests/suffix_reverse.rs":"cd497c1a51246a8fc727062133470e0c6300620ad80333d20d63c0ee4224ef1c","tests/test_backtrack.rs":"b07a114b2eb7f1f17357629be9c8458e31f7952fb2c327d66d9415f08855c624","tests/test_backtrack_bytes.rs":"dd3cec3c630d6f41892c9111bee87227bf47126651b2402672c30b084fa9c28c","tests/test_backtrack_utf8bytes.rs":"b576b933d6be21f8cedb281e456441d4278350b0145a139dbccb1861639a54f9","tests/test_default.rs":"768a1fabafc7eb815bfaf55c22606dc884e1dbb88d7fc40fd561e8faaa61e6d9","tests/test_default_bytes.rs":"c5228278e0a1d8fab5157dfd2b52642fd0ec68db346dc133f4c16f178d63e856","tests/test_nfa.rs":"aad36ca01f3f7eb23633a1207056e9056d686be2ef6e3661fad83805fa482927","tests/test_nfa_bytes.rs":"198f7b58c5c7dd0a05f16ddb3b9b63dab29ef2a56448378ac602c5d087c01e4e","tests/test_nfa_utf8bytes.rs":"854d80114ca1bed14d4ad3f2b3bf292ff0fa44e12d7d3f2ec6dd17cbbaa82175","tests/unicode.rs":"cadd620a5d70216d6a3100d18f21598bd3ed6c343023697a7d3c57b7dc45149e","tests/word_boundary.rs":"7081317ddcec1e82dd4a2090a571c6abf2ff4bbfa8cd10395e1eb3f386157fae","tests/word_boundary_ascii.rs":"cd0be5b5b485de0ba7994b42e2864585556c3d2d8bf5eab05b58931d9aaf4b87","tests/word_boundary_unicode.rs":"ae4ac0689c6b42ff7628a681d6d99a124d254f35eb1b809137859d3a8afe84fc"},"package":"9329abc99e39129fcceabd24cf5d85b4671ef7c29c50e972bc5afe32438ec384"} \ No newline at end of file diff --git a/bash-5.1/vendor/regex/CHANGELOG.md b/bash-5.1/vendor/regex/CHANGELOG.md new file mode 100644 index 0000000..b63625f --- /dev/null +++ b/bash-5.1/vendor/regex/CHANGELOG.md @@ -0,0 +1,445 @@ +0.2.11 (2018-05-01) +=================== +This release primarily contains bug fixes. Some of them resolve bugs where +the parser could panic. + +New features: + +* [FEATURE #459](https://github.com/rust-lang/regex/pull/459): + Include C++'s standard regex library and Boost's regex library in the + benchmark harness. We now include D/libphobos, C++/std, C++/boost, Oniguruma, + PCRE1, PCRE2, RE2 and Tcl in the harness. + +Bug fixes: + +* [BUG #445](https://github.com/rust-lang/regex/issues/445): + Clarify order of indices returned by RegexSet match iterator. +* [BUG #461](https://github.com/rust-lang/regex/issues/461): + Improve error messages for invalid regexes like `[\d-a]`. +* [BUG #464](https://github.com/rust-lang/regex/issues/464): + Fix a bug in the error message pretty printer that could cause a panic when + a regex contained a literal `\n` character. +* [BUG #465](https://github.com/rust-lang/regex/issues/465): + Fix a panic in the parser that was caused by applying a repetition operator + to `(?flags)`. +* [BUG #466](https://github.com/rust-lang/regex/issues/466): + Fix a bug where `\pC` was not recognized as an alias for `\p{Other}`. +* [BUG #470](https://github.com/rust-lang/regex/pull/470): + Fix a bug where literal searches did more work than necessary for anchored + regexes. + + +0.2.10 (2018-03-16) +=================== +This release primarily updates the regex crate to changes made in `std::arch` +on nightly Rust. + +New features: + +* [FEATURE #458](https://github.com/rust-lang/regex/pull/458): + The `Hir` type in `regex-syntax` now has a printer. + + +0.2.9 (2018-03-12) +================== +This release introduces a new nightly only feature, `unstable`, which enables +SIMD optimizations for certain types of regexes. No additional compile time +options are necessary, and the regex crate will automatically choose the +best CPU features at run time. As a result, the `simd` (nightly only) crate +dependency has been dropped. + +New features: + +* [FEATURE #456](https://github.com/rust-lang/regex/pull/456): + The regex crate now includes AVX2 optimizations in addition to the extant + SSSE3 optimization. + +Bug fixes: + +* [BUG #455](https://github.com/rust-lang/regex/pull/455): + Fix a bug where `(?x)[ / - ]` failed to parse. + + +0.2.8 (2018-03-12) +================== +Bug gixes: + +* [BUG #454](https://github.com/rust-lang/regex/pull/454): + Fix a bug in the nest limit checker being too aggressive. + + +0.2.7 (2018-03-07) +================== +This release includes a ground-up rewrite of the regex-syntax crate, which has +been in development for over a year. + +New features: + +* Error messages for invalid regexes have been greatly improved. You get these + automatically; you don't need to do anything. In addition to better + formatting, error messages will now explicitly call out the use of look + around. When regex 1.0 is released, this will happen for backreferences as + well. +* Full support for intersection, difference and symmetric difference of + character classes. These can be used via the `&&`, `--` and `~~` binary + operators within classes. +* A Unicode Level 1 conformat implementation of `\p{..}` character classes. + Things like `\p{scx:Hira}`, `\p{age:3.2}` or `\p{Changes_When_Casefolded}` + now work. All property name and value aliases are supported, and properties + are selected via loose matching. e.g., `\p{Greek}` is the same as + `\p{G r E e K}`. +* A new `UNICODE.md` document has been added to this repository that + exhaustively documents support for UTS#18. +* Empty sub-expressions are now permitted in most places. That is, `()+` is + now a valid regex. +* Almost everything in regex-syntax now uses constant stack space, even when + performing anaylsis that requires structural induction. This reduces the risk + of a user provided regular expression causing a stack overflow. +* [FEATURE #174](https://github.com/rust-lang/regex/issues/174): + The `Ast` type in `regex-syntax` now contains span information. +* [FEATURE #424](https://github.com/rust-lang/regex/issues/424): + Support `\u`, `\u{...}`, `\U` and `\U{...}` syntax for specifying code points + in a regular expression. +* [FEATURE #449](https://github.com/rust-lang/regex/pull/449): + Add a `Replace::by_ref` adapter for use of a replacer without consuming it. + +Bug fixes: + +* [BUG #446](https://github.com/rust-lang/regex/issues/446): + We re-enable the Boyer-Moore literal matcher. + + +0.2.6 (2018-02-08) +================== +Bug fixes: + +* [BUG #446](https://github.com/rust-lang/regex/issues/446): + Fixes a bug in the new Boyer-Moore searcher that results in a match failure. + We fix this bug by temporarily disabling Boyer-Moore. + + +0.2.5 (2017-12-30) +================== +Bug fixes: + +* [BUG #437](https://github.com/rust-lang/regex/issues/437): + Fixes a bug in the new Boyer-Moore searcher that results in a panic. + + +0.2.4 (2017-12-30) +================== +New features: + +* [FEATURE #348](https://github.com/rust-lang/regex/pull/348): + Improve performance for capture searches on anchored regex. + (Contributed by @ethanpailes. Nice work!) +* [FEATURE #419](https://github.com/rust-lang/regex/pull/419): + Expand literal searching to include Tuned Boyer-Moore in some cases. + (Contributed by @ethanpailes. Nice work!) + +Bug fixes: + +* [BUG](https://github.com/rust-lang/regex/pull/436): + The regex compiler plugin has been removed. +* [BUG](https://github.com/rust-lang/regex/pull/436): + `simd` has been bumped to `0.2.1`, which fixes a Rust nightly build error. +* [BUG](https://github.com/rust-lang/regex/pull/436): + Bring the benchmark harness up to date. + + +0.2.3 (2017-11-30) +================== +New features: + +* [FEATURE #374](https://github.com/rust-lang/regex/pull/374): + Add `impl From for &str`. +* [FEATURE #380](https://github.com/rust-lang/regex/pull/380): + Derive `Clone` and `PartialEq` on `Error`. +* [FEATURE #400](https://github.com/rust-lang/regex/pull/400): + Update to Unicode 10. + +Bug fixes: + +* [BUG #375](https://github.com/rust-lang/regex/issues/375): + Fix a bug that prevented the bounded backtracker from terminating. +* [BUG #393](https://github.com/rust-lang/regex/issues/393), + [BUG #394](https://github.com/rust-lang/regex/issues/394): + Fix bug with `replace` methods for empty matches. + + +0.2.2 (2017-05-21) +================== +New features: + +* [FEATURE #341](https://github.com/rust-lang/regex/issues/341): + Support nested character classes and intersection operation. + For example, `[\p{Greek}&&\pL]` matches greek letters and + `[[0-9]&&[^4]]` matches every decimal digit except `4`. + (Much thanks to @robinst, who contributed this awesome feature.) + +Bug fixes: + +* [BUG #321](https://github.com/rust-lang/regex/issues/321): + Fix bug in literal extraction and UTF-8 decoding. +* [BUG #326](https://github.com/rust-lang/regex/issues/326): + Add documentation tip about the `(?x)` flag. +* [BUG #333](https://github.com/rust-lang/regex/issues/333): + Show additional replacement example using curly braces. +* [BUG #334](https://github.com/rust-lang/regex/issues/334): + Fix bug when resolving captures after a match. +* [BUG #338](https://github.com/rust-lang/regex/issues/338): + Add example that uses `Captures::get` to API documentation. +* [BUG #353](https://github.com/rust-lang/regex/issues/353): + Fix RegexSet bug that caused match failure in some cases. +* [BUG #354](https://github.com/rust-lang/regex/pull/354): + Fix panic in parser when `(?x)` is used. +* [BUG #358](https://github.com/rust-lang/regex/issues/358): + Fix literal optimization bug with RegexSet. +* [BUG #359](https://github.com/rust-lang/regex/issues/359): + Fix example code in README. +* [BUG #365](https://github.com/rust-lang/regex/pull/365): + Fix bug in `rure_captures_len` in the C binding. +* [BUG #367](https://github.com/rust-lang/regex/issues/367): + Fix byte class bug that caused a panic. + + +0.2.1 +===== +One major bug with `replace_all` has been fixed along with a couple of other +touchups. + +* [BUG #312](https://github.com/rust-lang/regex/issues/312): + Fix documentation for `NoExpand` to reference correct lifetime parameter. +* [BUG #314](https://github.com/rust-lang/regex/issues/314): + Fix a bug with `replace_all` when replacing a match with the empty string. +* [BUG #316](https://github.com/rust-lang/regex/issues/316): + Note a missing breaking change from the `0.2.0` CHANGELOG entry. + (`RegexBuilder::compile` was renamed to `RegexBuilder::build`.) +* [BUG #324](https://github.com/rust-lang/regex/issues/324): + Compiling `regex` should only require one version of `memchr` crate. + + +0.2.0 +===== +This is a new major release of the regex crate, and is an implementation of the +[regex 1.0 RFC](https://github.com/rust-lang/rfcs/blob/master/text/1620-regex-1.0.md). +We are releasing a `0.2` first, and if there are no major problems, we will +release a `1.0` shortly. For `0.2`, the minimum *supported* Rust version is +1.12. + +There are a number of **breaking changes** in `0.2`. They are split into two +types. The first type correspond to breaking changes in regular expression +syntax. The second type correspond to breaking changes in the API. + +Breaking changes for regex syntax: + +* POSIX character classes now require double bracketing. Previously, the regex + `[:upper:]` would parse as the `upper` POSIX character class. Now it parses + as the character class containing the characters `:upper:`. The fix to this + change is to use `[[:upper:]]` instead. Note that variants like + `[[:upper:][:blank:]]` continue to work. +* The character `[` must always be escaped inside a character class. +* The characters `&`, `-` and `~` must be escaped if any one of them are + repeated consecutively. For example, `[&]`, `[\&]`, `[\&\&]`, `[&-&]` are all + equivalent while `[&&]` is illegal. (The motivation for this and the prior + change is to provide a backwards compatible path for adding character class + set notation.) +* A `bytes::Regex` now has Unicode mode enabled by default (like the main + `Regex` type). This means regexes compiled with `bytes::Regex::new` that + don't have the Unicode flag set should add `(?-u)` to recover the original + behavior. + +Breaking changes for the regex API: + +* `find` and `find_iter` now **return `Match` values instead of + `(usize, usize)`.** `Match` values have `start` and `end` methods, which + return the match offsets. `Match` values also have an `as_str` method, + which returns the text of the match itself. +* The `Captures` type now only provides a single iterator over all capturing + matches, which should replace uses of `iter` and `iter_pos`. Uses of + `iter_named` should use the `capture_names` method on `Regex`. +* The `at` method on the `Captures` type has been renamed to `get`, and it + now returns a `Match`. Similarly, the `name` method on `Captures` now returns + a `Match`. +* The `replace` methods now return `Cow` values. The `Cow::Borrowed` variant + is returned when no replacements are made. +* The `Replacer` trait has been completely overhauled. This should only + impact clients that implement this trait explicitly. Standard uses of + the `replace` methods should continue to work unchanged. If you implement + the `Replacer` trait, please consult the new documentation. +* The `quote` free function has been renamed to `escape`. +* The `Regex::with_size_limit` method has been removed. It is replaced by + `RegexBuilder::size_limit`. +* The `RegexBuilder` type has switched from owned `self` method receivers to + `&mut self` method receivers. Most uses will continue to work unchanged, but + some code may require naming an intermediate variable to hold the builder. +* The `compile` method on `RegexBuilder` has been renamed to `build`. +* The free `is_match` function has been removed. It is replaced by compiling + a `Regex` and calling its `is_match` method. +* The `PartialEq` and `Eq` impls on `Regex` have been dropped. If you relied + on these impls, the fix is to define a wrapper type around `Regex`, impl + `Deref` on it and provide the necessary impls. +* The `is_empty` method on `Captures` has been removed. This always returns + `false`, so its use is superfluous. +* The `Syntax` variant of the `Error` type now contains a string instead of + a `regex_syntax::Error`. If you were examining syntax errors more closely, + you'll need to explicitly use the `regex_syntax` crate to re-parse the regex. +* The `InvalidSet` variant of the `Error` type has been removed since it is + no longer used. +* Most of the iterator types have been renamed to match conventions. If you + were using these iterator types explicitly, please consult the documentation + for its new name. For example, `RegexSplits` has been renamed to `Split`. + +A number of bugs have been fixed: + +* [BUG #151](https://github.com/rust-lang/regex/issues/151): + The `Replacer` trait has been changed to permit the caller to control + allocation. +* [BUG #165](https://github.com/rust-lang/regex/issues/165): + Remove the free `is_match` function. +* [BUG #166](https://github.com/rust-lang/regex/issues/166): + Expose more knobs (available in `0.1`) and remove `with_size_limit`. +* [BUG #168](https://github.com/rust-lang/regex/issues/168): + Iterators produced by `Captures` now have the correct lifetime parameters. +* [BUG #175](https://github.com/rust-lang/regex/issues/175): + Fix a corner case in the parsing of POSIX character classes. +* [BUG #178](https://github.com/rust-lang/regex/issues/178): + Drop the `PartialEq` and `Eq` impls on `Regex`. +* [BUG #179](https://github.com/rust-lang/regex/issues/179): + Remove `is_empty` from `Captures` since it always returns false. +* [BUG #276](https://github.com/rust-lang/regex/issues/276): + Position of named capture can now be retrieved from a `Captures`. +* [BUG #296](https://github.com/rust-lang/regex/issues/296): + Remove winapi/kernel32-sys dependency on UNIX. +* [BUG #307](https://github.com/rust-lang/regex/issues/307): + Fix error on emscripten. + + +0.1.80 +====== +* [PR #292](https://github.com/rust-lang/regex/pull/292): + Fixes bug #291, which was introduced by PR #290. + +0.1.79 +====== +* Require regex-syntax 0.3.8. + +0.1.78 +====== +* [PR #290](https://github.com/rust-lang/regex/pull/290): + Fixes bug #289, which caused some regexes with a certain combination + of literals to match incorrectly. + +0.1.77 +====== +* [PR #281](https://github.com/rust-lang/regex/pull/281): + Fixes bug #280 by disabling all literal optimizations when a pattern + is partially anchored. + +0.1.76 +====== +* Tweak criteria for using the Teddy literal matcher. + +0.1.75 +====== +* [PR #275](https://github.com/rust-lang/regex/pull/275): + Improves match verification performance in the Teddy SIMD searcher. +* [PR #278](https://github.com/rust-lang/regex/pull/278): + Replaces slow substring loop in the Teddy SIMD searcher with Aho-Corasick. +* Implemented DoubleEndedIterator on regex set match iterators. + +0.1.74 +====== +* Release regex-syntax 0.3.5 with a minor bug fix. +* Fix bug #272. +* Fix bug #277. +* [PR #270](https://github.com/rust-lang/regex/pull/270): + Fixes bugs #264, #268 and an unreported where the DFA cache size could be + drastically under estimated in some cases (leading to high unexpected memory + usage). + +0.1.73 +====== +* Release `regex-syntax 0.3.4`. +* Bump `regex-syntax` dependency version for `regex` to `0.3.4`. + +0.1.72 +====== +* [PR #262](https://github.com/rust-lang/regex/pull/262): + Fixes a number of small bugs caught by fuzz testing (AFL). + +0.1.71 +====== +* [PR #236](https://github.com/rust-lang/regex/pull/236): + Fix a bug in how suffix literals were extracted, which could lead + to invalid match behavior in some cases. + +0.1.70 +====== +* [PR #231](https://github.com/rust-lang/regex/pull/231): + Add SIMD accelerated multiple pattern search. +* [PR #228](https://github.com/rust-lang/regex/pull/228): + Reintroduce the reverse suffix literal optimization. +* [PR #226](https://github.com/rust-lang/regex/pull/226): + Implements NFA state compression in the lazy DFA. +* [PR #223](https://github.com/rust-lang/regex/pull/223): + A fully anchored RegexSet can now short-circuit. + +0.1.69 +====== +* [PR #216](https://github.com/rust-lang/regex/pull/216): + Tweak the threshold for running backtracking. +* [PR #217](https://github.com/rust-lang/regex/pull/217): + Add upper limit (from the DFA) to capture search (for the NFA). +* [PR #218](https://github.com/rust-lang/regex/pull/218): + Add rure, a C API. + +0.1.68 +====== +* [PR #210](https://github.com/rust-lang/regex/pull/210): + Fixed a performance bug in `bytes::Regex::replace` where `extend` was used + instead of `extend_from_slice`. +* [PR #211](https://github.com/rust-lang/regex/pull/211): + Fixed a bug in the handling of word boundaries in the DFA. +* [PR #213](https://github.com/rust-lang/pull/213): + Added RE2 and Tcl to the benchmark harness. Also added a CLI utility from + running regexes using any of the following regex engines: PCRE1, PCRE2, + Oniguruma, RE2, Tcl and of course Rust's own regexes. + +0.1.67 +====== +* [PR #201](https://github.com/rust-lang/regex/pull/201): + Fix undefined behavior in the `regex!` compiler plugin macro. +* [PR #205](https://github.com/rust-lang/regex/pull/205): + More improvements to DFA performance. Competitive with RE2. See PR for + benchmarks. +* [PR #209](https://github.com/rust-lang/regex/pull/209): + Release 0.1.66 was semver incompatible since it required a newer version + of Rust than previous releases. This PR fixes that. (And `0.1.66` was + yanked.) + +0.1.66 +====== +* Speculative support for Unicode word boundaries was added to the DFA. This + should remove the last common case that disqualified use of the DFA. +* An optimization that scanned for suffix literals and then matched the regular + expression in reverse was removed because it had worst case quadratic time + complexity. It was replaced with a more limited optimization where, given any + regex of the form `re$`, it will be matched in reverse from the end of the + haystack. +* [PR #202](https://github.com/rust-lang/regex/pull/202): + The inner loop of the DFA was heavily optimized to improve cache locality + and reduce the overall number of instructions run on each iteration. This + represents the first use of `unsafe` in `regex` (to elide bounds checks). +* [PR #200](https://github.com/rust-lang/regex/pull/200): + Use of the `mempool` crate (which used thread local storage) was replaced + with a faster version of a similar API in @Amanieu's `thread_local` crate. + It should reduce contention when using a regex from multiple threads + simultaneously. +* PCRE2 JIT benchmarks were added. A benchmark comparison can be found + [here](https://gist.github.com/anonymous/14683c01993e91689f7206a18675901b). + (Includes a comparison with PCRE1's JIT and Oniguruma.) +* A bug where word boundaries weren't being matched correctly in the DFA was + fixed. This only affected use of `bytes::Regex`. +* [#160](https://github.com/rust-lang/regex/issues/160): + `Captures` now has a `Debug` impl. diff --git a/bash-5.1/vendor/regex/Cargo.toml b/bash-5.1/vendor/regex/Cargo.toml new file mode 100644 index 0000000..53ed614 --- /dev/null +++ b/bash-5.1/vendor/regex/Cargo.toml @@ -0,0 +1,100 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "regex" +version = "0.2.11" +authors = ["The Rust Project Developers"] +description = "An implementation of regular expressions for Rust. This implementation uses\nfinite automata and guarantees linear time matching on all inputs.\n" +homepage = "https://github.com/rust-lang/regex" +documentation = "https://docs.rs/regex" +readme = "README.md" +categories = ["text-processing"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/regex" +[profile.test] +debug = true + +[profile.bench] +debug = true + +[profile.release] +debug = true + +[lib] +bench = false + +[[test]] +name = "default" +path = "tests/test_default.rs" + +[[test]] +name = "default-bytes" +path = "tests/test_default_bytes.rs" + +[[test]] +name = "nfa" +path = "tests/test_nfa.rs" + +[[test]] +name = "nfa-utf8bytes" +path = "tests/test_nfa_utf8bytes.rs" + +[[test]] +name = "nfa-bytes" +path = "tests/test_nfa_bytes.rs" + +[[test]] +name = "backtrack" +path = "tests/test_backtrack.rs" + +[[test]] +name = "backtrack-utf8bytes" +path = "tests/test_backtrack_utf8bytes.rs" + +[[test]] +name = "backtrack-bytes" +path = "tests/test_backtrack_bytes.rs" +[dependencies.aho-corasick] +version = "0.6.0" + +[dependencies.memchr] +version = "2.0.0" + +[dependencies.regex-syntax] +version = "0.5.6" + +[dependencies.thread_local] +version = "0.3.2" + +[dependencies.utf8-ranges] +version = "1.0.0" +[dev-dependencies.lazy_static] +version = "1" + +[dev-dependencies.quickcheck] +version = "0.6" +default-features = false + +[dev-dependencies.rand] +version = "0.4" + +[features] +default = [] +pattern = [] +simd-accel = [] +unstable = ["pattern"] +[badges.appveyor] +repository = "rust-lang-libs/regex" + +[badges.travis-ci] +repository = "rust-lang/regex" diff --git a/bash-5.1/vendor/regex/HACKING.md b/bash-5.1/vendor/regex/HACKING.md new file mode 100644 index 0000000..b216d0d --- /dev/null +++ b/bash-5.1/vendor/regex/HACKING.md @@ -0,0 +1,330 @@ +Your friendly guide to hacking and navigating the regex library. + +This guide assumes familiarity with Rust and Cargo, and at least a perusal of +the user facing documentation for this crate. + +If you're looking for background on the implementation in this library, then +you can do no better than Russ Cox's article series on implementing regular +expressions using finite automata: https://swtch.com/~rsc/regexp/ + + +## Architecture overview + +As you probably already know, this library executes regular expressions using +finite automata. In particular, a design goal is to make searching linear +with respect to both the regular expression and the text being searched. +Meeting that design goal on its own is not so hard and can be done with an +implementation of the Pike VM (similar to Thompson's construction, but supports +capturing groups), as described in: https://swtch.com/~rsc/regexp/regexp2.html +--- This library contains such an implementation in src/pikevm.rs. + +Making it fast is harder. One of the key problems with the Pike VM is that it +can be in more than one state at any point in time, and must shuffle capture +positions between them. The Pike VM also spends a lot of time following the +same epsilon transitions over and over again. We can employ one trick to +speed up the Pike VM: extract one or more literal prefixes from the regular +expression and execute specialized code to quickly find matches of those +prefixes in the search text. The Pike VM can then be avoided for most the +search, and instead only executed when a prefix is found. The code to find +prefixes is in the regex-syntax crate (in this repository). The code to search +for literals is in src/literals.rs. When more than one literal prefix is found, +we fall back to an Aho-Corasick DFA using the aho-corasick crate. For one +literal, we use a variant of the Boyer-Moore algorithm. Both Aho-Corasick and +Boyer-Moore use `memchr` when appropriate. The Boyer-Moore variant in this +library also uses elementary frequency analysis to choose the right byte to run +`memchr` with. + +Of course, detecting prefix literals can only take us so far. Not all regular +expressions have literal prefixes. To remedy this, we try another approach +to executing the Pike VM: backtracking, whose implementation can be found in +src/backtrack.rs. One reason why backtracking can be faster is that it avoids +excessive shuffling of capture groups. Of course, backtracking is susceptible +to exponential runtimes, so we keep track of every state we've visited to make +sure we never visit it again. This guarantees linear time execution, but we +pay for it with the memory required to track visited states. Because of the +memory requirement, we only use this engine on small search strings *and* small +regular expressions. + +Lastly, the real workhorse of this library is the "lazy" DFA in src/dfa.rs. +It is distinct from the Pike VM in that the DFA is explicitly represented in +memory and is only ever in one state at a time. It is said to be "lazy" because +the DFA is computed as text is searched, where each byte in the search text +results in at most one new DFA state. It is made fast by caching states. DFAs +are susceptible to exponential state blow up (where the worst case is computing +a new state for every input byte, regardless of what's in the state cache). To +avoid using a lot of memory, the lazy DFA uses a bounded cache. Once the cache +is full, it is wiped and state computation starts over again. If the cache is +wiped too frequently, then the DFA gives up and searching falls back to one of +the aforementioned algorithms. + +All of the above matching engines expose precisely the same matching semantics. +This is indeed tested. (See the section below about testing.) + +The following sub-sections describe the rest of the library and how each of the +matching engines are actually used. + +### Parsing + +Regular expressions are parsed using the regex-syntax crate, which is +maintained in this repository. The regex-syntax crate defines an abstract +syntax and provides very detailed error messages when a parse error is +encountered. Parsing is done in a separate crate so that others may benefit +from its existence, and because it is relatively divorced from the rest of the +regex library. + +The regex-syntax crate also provides sophisticated support for extracting +prefix and suffix literals from regular expressions. + +### Compilation + +The compiler is in src/compile.rs. The input to the compiler is some abstract +syntax for a regular expression and the output is a sequence of opcodes that +matching engines use to execute a search. (One can think of matching engines as +mini virtual machines.) The sequence of opcodes is a particular encoding of a +non-deterministic finite automaton. In particular, the opcodes explicitly rely +on epsilon transitions. + +Consider a simple regular expression like `a|b`. Its compiled form looks like +this: + + 000 Save(0) + 001 Split(2, 3) + 002 'a' (goto: 4) + 003 'b' + 004 Save(1) + 005 Match + +The first column is the instruction pointer and the second column is the +instruction. Save instructions indicate that the current position in the input +should be stored in a captured location. Split instructions represent a binary +branch in the program (i.e., epsilon transitions). The instructions `'a'` and +`'b'` indicate that the literal bytes `'a'` or `'b'` should match. + +In older versions of this library, the compilation looked like this: + + 000 Save(0) + 001 Split(2, 3) + 002 'a' + 003 Jump(5) + 004 'b' + 005 Save(1) + 006 Match + +In particular, empty instructions that merely served to move execution from one +point in the program to another were removed. Instead, every instruction has a +`goto` pointer embedded into it. This resulted in a small performance boost for +the Pike VM, because it was one fewer epsilon transition that it had to follow. + +There exist more instructions and they are defined and documented in +src/prog.rs. + +Compilation has several knobs and a few unfortunately complicated invariants. +Namely, the output of compilation can be one of two types of programs: a +program that executes on Unicode scalar values or a program that executes +on raw bytes. In the former case, the matching engine is responsible for +performing UTF-8 decoding and executing instructions using Unicode codepoints. +In the latter case, the program handles UTF-8 decoding implicitly, so that the +matching engine can execute on raw bytes. All matching engines can execute +either Unicode or byte based programs except for the lazy DFA, which requires +byte based programs. In general, both representations were kept because (1) the +lazy DFA requires byte based programs so that states can be encoded in a memory +efficient manner and (2) the Pike VM benefits greatly from inlining Unicode +character classes into fewer instructions as it results in fewer epsilon +transitions. + +N.B. UTF-8 decoding is built into the compiled program by making use of the +utf8-ranges crate. The compiler in this library factors out common suffixes to +reduce the size of huge character classes (e.g., `\pL`). + +A regrettable consequence of this split in instruction sets is we generally +need to compile two programs; one for NFA execution and one for the lazy DFA. + +In fact, it is worse than that: the lazy DFA is not capable of finding the +starting location of a match in a single scan, and must instead execute a +backwards search after finding the end location. To execute a backwards search, +we must have compiled the regular expression *in reverse*. + +This means that every compilation of a regular expression generally results in +three distinct programs. It would be possible to lazily compile the Unicode +program, since it is never needed if (1) the regular expression uses no word +boundary assertions and (2) the caller never asks for sub-capture locations. + +### Execution + +At the time of writing, there are four matching engines in this library: + +1. The Pike VM (supports captures). +2. Bounded backtracking (supports captures). +3. Literal substring or multi-substring search. +4. Lazy DFA (no support for Unicode word boundary assertions). + +Only the first two matching engines are capable of executing every regular +expression program. They also happen to be the slowest, which means we need +some logic that (1) knows various facts about the regular expression and (2) +knows what the caller wants. Using this information, we can determine which +engine (or engines) to use. + +The logic for choosing which engine to execute is in src/exec.rs and is +documented on the Exec type. Exec values contain regular expression Programs +(defined in src/prog.rs), which contain all the necessary tidbits for actually +executing a regular expression on search text. + +For the most part, the execution logic is straight-forward and follows the +limitations of each engine described above pretty faithfully. The hairiest +part of src/exec.rs by far is the execution of the lazy DFA, since it requires +a forwards and backwards search, and then falls back to either the Pike VM or +backtracking if the caller requested capture locations. + +The Exec type also contains mutable scratch space for each type of matching +engine. This scratch space is used during search (for example, for the lazy +DFA, it contains compiled states that are reused on subsequent searches). + +### Programs + +A regular expression program is essentially a sequence of opcodes produced by +the compiler plus various facts about the regular expression (such as whether +it is anchored, its capture names, etc.). + +### The regex! macro + +The `regex!` macro no longer exists. It was developed in a bygone era as a +compiler plugin during the infancy of the regex crate. Back then, then only +matching engine in the crate was the Pike VM. The `regex!` macro was, itself, +also a Pike VM. The only advantages it offered over the dynamic Pike VM that +was built at runtime were the following: + + 1. Syntax checking was done at compile time. Your Rust program wouldn't + compile if your regex didn't compile. + 2. Reduction of overhead that was proportional to the size of the regex. + For the most part, this overhead consisted of heap allocation, which + was nearly eliminated in the compiler plugin. + +The main takeaway here is that the compiler plugin was a marginally faster +version of a slow regex engine. As the regex crate evolved, it grew other regex +engines (DFA, bounded backtracker) and sophisticated literal optimizations. +The regex macro didn't keep pace, and it therefore became (dramatically) slower +than the dynamic engines. The only reason left to use it was for the compile +time guarantee that your regex is correct. Fortunately, Clippy (the Rust lint +tool) has a lint that checks your regular expression validity, which mostly +replaces that use case. + +Additionally, the regex compiler plugin stopped receiving maintenance. Nobody +complained. At that point, it seemed prudent to just remove it. + +Will a compiler plugin be brought back? The future is murky, but there is +definitely an opportunity there to build something that is faster than the +dynamic engines in some cases. But it will be challenging! As of now, there +are no plans to work on this. + + +## Testing + +A key aspect of any mature regex library is its test suite. A subset of the +tests in this library come from Glenn Fowler's AT&T test suite (its online +presence seems gone at the time of writing). The source of the test suite is +located in src/testdata. The scripts/regex-match-tests.py takes the test suite +in src/testdata and generates tests/matches.rs. + +There are also many other manually crafted tests and regression tests in +tests/tests.rs. Some of these tests were taken from RE2. + +The biggest source of complexity in the tests is related to answering this +question: how can we reuse the tests to check all of our matching engines? One +approach would have been to encode every test into some kind of format (like +the AT&T test suite) and code generate tests for each matching engine. The +approach we use in this library is to create a Cargo.toml entry point for each +matching engine we want to test. The entry points are: + +* `tests/test_default.rs` - tests `Regex::new` +* `tests/test_default_bytes.rs` - tests `bytes::Regex::new` +* `tests/test_nfa.rs` - tests `Regex::new`, forced to use the NFA + algorithm on every regex. +* `tests/test_nfa_bytes.rs` - tests `Regex::new`, forced to use the NFA + algorithm on every regex and use *arbitrary* byte based programs. +* `tests/test_nfa_utf8bytes.rs` - tests `Regex::new`, forced to use the NFA + algorithm on every regex and use *UTF-8* byte based programs. +* `tests/test_backtrack.rs` - tests `Regex::new`, forced to use + backtracking on every regex. +* `tests/test_backtrack_bytes.rs` - tests `Regex::new`, forced to use + backtracking on every regex and use *arbitrary* byte based programs. +* `tests/test_backtrack_utf8bytes.rs` - tests `Regex::new`, forced to use + backtracking on every regex and use *UTF-8* byte based programs. + +The lazy DFA and pure literal engines are absent from this list because +they cannot be used on every regular expression. Instead, we rely on +`tests/test_dynamic.rs` to test the lazy DFA and literal engines when possible. + +Since the tests are repeated several times, and because `cargo test` runs all +entry points, it can take a while to compile everything. To reduce compile +times slightly, try using `cargo test --test default`, which will only use the +`tests/test_default.rs` entry point. + + +## Benchmarking + +The benchmarking in this crate is made up of many micro-benchmarks. Currently, +there are two primary sets of benchmarks: the benchmarks that were adopted +at this library's inception (in `bench/src/misc.rs`) and a newer set of +benchmarks meant to test various optimizations. Specifically, the latter set +contain some analysis and are in `bench/src/sherlock.rs`. Also, the latter +set are all executed on the same lengthy input whereas the former benchmarks +are executed on strings of varying length. + +There is also a smattering of benchmarks for parsing and compilation. + +Benchmarks are in a separate crate so that its dependencies can be managed +separately from the main regex crate. + +Benchmarking follows a similarly wonky setup as tests. There are multiple entry +points: + +* `bench_rust.rs` - benchmarks `Regex::new` +* `bench_rust_bytes.rs` benchmarks `bytes::Regex::new` +* `bench_pcre.rs` - benchmarks PCRE +* `bench_onig.rs` - benchmarks Oniguruma + +The PCRE and Oniguruma benchmarks exist as a comparison point to a mature +regular expression library. In general, this regex library compares favorably +(there are even a few benchmarks that PCRE simply runs too slowly on or +outright can't execute at all). I would love to add other regular expression +library benchmarks (especially RE2). + +If you're hacking on one of the matching engines and just want to see +benchmarks, then all you need to run is: + + $ ./bench/run rust + +If you want to compare your results with older benchmarks, then try: + + $ ./bench/run rust | tee old + $ ... make it faster + $ ./bench/run rust | tee new + $ cargo benchcmp old new --improvements + +The `cargo-benchcmp` utility is available here: +https://github.com/BurntSushi/cargo-benchcmp + +The `./bench/run` utility can run benchmarks for PCRE and Oniguruma too. See +`./bench/bench --help`. + +## Dev Docs + +When digging your teeth into the codebase for the first time, the +crate documentation can be a great resource. By default `rustdoc` +will strip out all documentation of private crate members in an +effort to help consumers of the crate focus on the *interface* +without having to concern themselves with the *implementation*. +Normally this is a great thing, but if you want to start hacking +on regex internals it is not what you want. Many of the private members +of this crate are well documented with rustdoc style comments, and +it would be a shame to miss out on the opportunity that presents. +You can generate the private docs with: + +``` +$ rustdoc --crate-name docs src/lib.rs -o target/doc -L target/debug/deps --no-defaults --passes collapse-docs --passes unindent-comments +``` + +Then just point your browser at `target/doc/regex/index.html`. + +See https://github.com/rust-lang/rust/issues/15347 for more info +about generating developer docs for internal use. diff --git a/bash-5.1/vendor/regex/LICENSE-APACHE b/bash-5.1/vendor/regex/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/regex/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/regex/LICENSE-MIT b/bash-5.1/vendor/regex/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/regex/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/regex/PERFORMANCE.md b/bash-5.1/vendor/regex/PERFORMANCE.md new file mode 100644 index 0000000..b4aeb89 --- /dev/null +++ b/bash-5.1/vendor/regex/PERFORMANCE.md @@ -0,0 +1,279 @@ +Your friendly guide to understanding the performance characteristics of this +crate. + +This guide assumes some familiarity with the public API of this crate, which +can be found here: https://docs.rs/regex + +## Theory vs. Practice + +One of the design goals of this crate is to provide worst case linear time +behavior with respect to the text searched using finite state automata. This +means that, *in theory*, the performance of this crate is much better than most +regex implementations, which typically use backtracking which has worst case +exponential time. + +For example, try opening a Python interpreter and typing this: + + >>> import re + >>> re.search('(a*)*c', 'a' * 30).span() + +I'll wait. + +At some point, you'll figure out that it won't terminate any time soon. ^C it. + +The promise of this crate is that *this pathological behavior can't happen*. + +With that said, just because we have protected ourselves against worst case +exponential behavior doesn't mean we are immune from large constant factors +or places where the current regex engine isn't quite optimal. This guide will +detail those cases and provide guidance on how to avoid them, among other +bits of general advice. + +## Thou Shalt Not Compile Regular Expressions In A Loop + +**Advice**: Use `lazy_static` to amortize the cost of `Regex` compilation. + +Don't do it unless you really don't mind paying for it. Compiling a regular +expression in this crate is quite expensive. It is conceivable that it may get +faster some day, but I wouldn't hold out hope for, say, an order of magnitude +improvement. In particular, compilation can take any where from a few dozen +microseconds to a few dozen milliseconds. Yes, milliseconds. Unicode character +classes, in particular, have the largest impact on compilation performance. At +the time of writing, for example, `\pL{100}` takes around 44ms to compile. This +is because `\pL` corresponds to every letter in Unicode and compilation must +turn it into a proper automaton that decodes a subset of UTF-8 which +corresponds to those letters. Compilation also spends some cycles shrinking the +size of the automaton. + +This means that in order to realize efficient regex matching, one must +*amortize the cost of compilation*. Trivially, if a call to `is_match` is +inside a loop, then make sure your call to `Regex::new` is *outside* that loop. + +In many programming languages, regular expressions can be conveniently defined +and compiled in a global scope, and code can reach out and use them as if +they were global static variables. In Rust, there is really no concept of +life-before-main, and therefore, one cannot utter this: + + static MY_REGEX: Regex = Regex::new("...").unwrap(); + +Unfortunately, this would seem to imply that one must pass `Regex` objects +around to everywhere they are used, which can be especially painful depending +on how your program is structured. Thankfully, the +[`lazy_static`](https://crates.io/crates/lazy_static) +crate provides an answer that works well: + + #[macro_use] extern crate lazy_static; + extern crate regex; + + use regex::Regex; + + fn some_helper_function(text: &str) -> bool { + lazy_static! { + static ref MY_REGEX: Regex = Regex::new("...").unwrap(); + } + MY_REGEX.is_match(text) + } + +In other words, the `lazy_static!` macro enables us to define a `Regex` *as if* +it were a global static value. What is actually happening under the covers is +that the code inside the macro (i.e., `Regex::new(...)`) is run on *first use* +of `MY_REGEX` via a `Deref` impl. The implementation is admittedly magical, but +it's self contained and everything works exactly as you expect. In particular, +`MY_REGEX` can be used from multiple threads without wrapping it in an `Arc` or +a `Mutex`. On that note... + +## Using a regex from multiple threads + +**Advice**: The performance impact from using a `Regex` from multiple threads +is likely negligible. If necessary, clone the `Regex` so that each thread gets +its own copy. Cloning a regex does not incur any additional memory overhead +than what would be used by using a `Regex` from multiple threads +simultaneously. *Its only cost is ergonomics.* + +It is supported and encouraged to define your regexes using `lazy_static!` as +if they were global static values, and then use them to search text from +multiple threads simultaneously. + +One might imagine that this is possible because a `Regex` represents a +*compiled* program, so that any allocation or mutation is already done, and is +therefore read-only. Unfortunately, this is not true. Each type of search +strategy in this crate requires some kind of mutable scratch space to use +*during search*. For example, when executing a DFA, its states are computed +lazily and reused on subsequent searches. Those states go into that mutable +scratch space. + +The mutable scratch space is an implementation detail, and in general, its +mutation should not be observable from users of this crate. Therefore, it uses +interior mutability. This implies that `Regex` can either only be used from one +thread, or it must do some sort of synchronization. Either choice is +reasonable, but this crate chooses the latter, in particular because it is +ergonomic and makes use with `lazy_static!` straight forward. + +Synchronization implies *some* amount of overhead. When a `Regex` is used from +a single thread, this overhead is negligible. When a `Regex` is used from +multiple threads simultaneously, it is possible for the overhead of +synchronization from contention to impact performance. The specific cases where +contention may happen is if you are calling any of these methods repeatedly +from multiple threads simultaneously: + +* shortest_match +* is_match +* find +* captures + +In particular, every invocation of one of these methods must synchronize with +other threads to retrieve its mutable scratch space before searching can start. +If, however, you are using one of these methods: + +* find_iter +* captures_iter + +Then you may not suffer from contention since the cost of synchronization is +amortized on *construction of the iterator*. That is, the mutable scratch space +is obtained when the iterator is created and retained throughout its lifetime. + +## Only ask for what you need + +**Advice**: Prefer in this order: `is_match`, `find`, `captures`. + +There are three primary search methods on a `Regex`: + +* is_match +* find +* captures + +In general, these are ordered from fastest to slowest. + +`is_match` is fastest because it doesn't actually need to find the start or the +end of the leftmost-first match. It can quit immediately after it knows there +is a match. For example, given the regex `a+` and the haystack, `aaaaa`, the +search will quit after examing the first byte. + +In constrast, `find` must return both the start and end location of the +leftmost-first match. It can use the DFA matcher for this, but must run it +forwards once to find the end of the match *and then run it backwards* to find +the start of the match. The two scans and the cost of finding the real end of +the leftmost-first match make this more expensive than `is_match`. + +`captures` is the most expensive of them all because it must do what `find` +does, and then run either the bounded backtracker or the Pike VM to fill in the +capture group locations. Both of these are simulations of an NFA, which must +spend a lot of time shuffling states around. The DFA limits the performance hit +somewhat by restricting the amount of text that must be searched via an NFA +simulation. + +One other method not mentioned is `shortest_match`. This method has precisely +the same performance characteristics as `is_match`, except it will return the +end location of when it discovered a match. For example, given the regex `a+` +and the haystack `aaaaa`, `shortest_match` may return `1` as opposed to `5`, +the latter of which being the correct end location of the leftmost-first match. + +## Literals in your regex may make it faster + +**Advice**: Literals can reduce the work that the regex engine needs to do. Use +them if you can, especially as prefixes. + +In particular, if your regex starts with a prefix literal, the prefix is +quickly searched before entering the (much slower) regex engine. For example, +given the regex `foo\w+`, the literal `foo` will be searched for using +Boyer-Moore. If there's no match, then no regex engine is ever used. Only when +there's a match is the regex engine invoked at the location of the match, which +effectively permits the regex engine to skip large portions of a haystack. +If a regex is comprised entirely of literals (possibly more than one), then +it's possible that the regex engine can be avoided entirely even when there's a +match. + +When one literal is found, Boyer-Moore is used. When multiple literals are +found, then an optimized version of Aho-Corasick is used. + +This optimization is in particular extended quite a bit in this crate. Here are +a few examples of regexes that get literal prefixes detected: + +* `(foo|bar)` detects `foo` and `bar` +* `(a|b)c` detects `ac` and `bc` +* `[ab]foo[yz]` detects `afooy`, `afooz`, `bfooy` and `bfooz` +* `a?b` detects `a` and `b` +* `a*b` detects `a` and `b` +* `(ab){3,6}` detects `ababab` + +Literals in anchored regexes can also be used for detecting non-matches very +quickly. For example, `^foo\w+` and `\w+foo$` may be able to detect a non-match +just by examing the first (or last) three bytes of the haystack. + +## Unicode word boundaries may prevent the DFA from being used + +**Advice**: In most cases, `\b` should work well. If not, use `(?-u:\b)` +instead of `\b` if you care about consistent performance more than correctness. + +It's a sad state of the current implementation. At the moment, the DFA will try +to interpret Unicode word boundaries as if they were ASCII word boundaries. +If the DFA comes across any non-ASCII byte, it will quit and fall back to an +alternative matching engine that can handle Unicode word boundaries correctly. +The alternate matching engine is generally quite a bit slower (perhaps by an +order of magnitude). If necessary, this can be ameliorated in two ways. + +The first way is to add some number of literal prefixes to your regular +expression. Even though the DFA may not be used, specialized routines will +still kick in to find prefix literals quickly, which limits how much work the +NFA simulation will need to do. + +The second way is to give up on Unicode and use an ASCII word boundary instead. +One can use an ASCII word boundary by disabling Unicode support. That is, +instead of using `\b`, use `(?-u:\b)`. Namely, given the regex `\b.+\b`, it +can be transformed into a regex that uses the DFA with `(?-u:\b).+(?-u:\b)`. It +is important to limit the scope of disabling the `u` flag, since it might lead +to a syntax error if the regex could match arbitrary bytes. For example, if one +wrote `(?-u)\b.+\b`, then a syntax error would be returned because `.` matches +any *byte* when the Unicode flag is disabled. + +The second way isn't appreciably different than just using a Unicode word +boundary in the first place, since the DFA will speculatively interpret it as +an ASCII word boundary anyway. The key difference is that if an ASCII word +boundary is used explicitly, then the DFA won't quit in the presence of +non-ASCII UTF-8 bytes. This results in giving up correctness in exchange for +more consistent performance. + +N.B. When using `bytes::Regex`, Unicode support is disabled by default, so one +can simply write `\b` to get an ASCII word boundary. + +## Excessive counting can lead to exponential state blow up in the DFA + +**Advice**: Don't write regexes that cause DFA state blow up if you care about +match performance. + +Wait, didn't I say that this crate guards against exponential worst cases? +Well, it turns out that the process of converting an NFA to a DFA can lead to +an exponential blow up in the number of states. This crate specifically guards +against exponential blow up by doing two things: + +1. The DFA is computed lazily. That is, a state in the DFA only exists in + memory if it is visited. In particular, the lazy DFA guarantees that *at + most* one state is created for every byte of input. This, on its own, + guarantees linear time complexity. +2. Of course, creating a new state for *every* byte of input means that search + will go incredibly slow because of very large constant factors. On top of + that, creating a state for every byte in a large haystack could result in + exorbitant memory usage. To ameliorate this, the DFA bounds the number of + states it can store. Once it reaches its limit, it flushes its cache. This + prevents reuse of states that it already computed. If the cache is flushed + too frequently, then the DFA will give up and execution will fall back to + one of the NFA simulations. + +In effect, this crate will detect exponential state blow up and fall back to +a search routine with fixed memory requirements. This does, however, mean that +searching will be much slower than one might expect. Regexes that rely on +counting in particular are strong aggravators of this behavior. For example, +matching `[01]*1[01]{20}$` against a random sequence of `0`s and `1`s. + +In the future, it may be possible to increase the bound that the DFA uses, +which would allow the caller to choose how much memory they're willing to +spend. + +## Resist the temptation to "optimize" regexes + +**Advice**: This ain't a backtracking engine. + +An entire book was written on how to optimize Perl-style regular expressions. +Most of those techniques are not applicable for this library. For example, +there is no problem with using non-greedy matching or having lots of +alternations in your regex. diff --git a/bash-5.1/vendor/regex/README.md b/bash-5.1/vendor/regex/README.md new file mode 100644 index 0000000..c61ba4a --- /dev/null +++ b/bash-5.1/vendor/regex/README.md @@ -0,0 +1,222 @@ +regex +===== +A Rust library for parsing, compiling, and executing regular expressions. Its +syntax is similar to Perl-style regular expressions, but lacks a few features +like look around and backreferences. In exchange, all searches execute in +linear time with respect to the size of the regular expression and search text. +Much of the syntax and implementation is inspired +by [RE2](https://github.com/google/re2). + +[![Build Status](https://travis-ci.org/rust-lang/regex.svg?branch=master)](https://travis-ci.org/rust-lang/regex) +[![Build status](https://ci.appveyor.com/api/projects/status/github/rust-lang/regex?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/regex) +[![Coverage Status](https://coveralls.io/repos/github/rust-lang/regex/badge.svg?branch=master)](https://coveralls.io/github/rust-lang/regex?branch=master) +[![](http://meritbadge.herokuapp.com/regex)](https://crates.io/crates/regex) + +### Documentation + +[Module documentation with examples](https://docs.rs/regex). +The module documentation also includes a comprehensive description of the +syntax supported. + +Documentation with examples for the various matching functions and iterators +can be found on the +[`Regex` type](https://docs.rs/regex/*/regex/struct.Regex.html). + +### Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +regex = "0.2" +``` + +and this to your crate root: + +```rust +extern crate regex; +``` + +Here's a simple example that matches a date in YYYY-MM-DD format and prints the +year, month and day: + +```rust +extern crate regex; + +use regex::Regex; + +fn main() { + let re = Regex::new(r"(?x) +(?P\d{4}) # the year +- +(?P\d{2}) # the month +- +(?P\d{2}) # the day +").unwrap(); + let caps = re.captures("2010-03-14").unwrap(); + + assert_eq!("2010", &caps["year"]); + assert_eq!("03", &caps["month"]); + assert_eq!("14", &caps["day"]); +} +``` + +If you have lots of dates in text that you'd like to iterate over, then it's +easy to adapt the above example with an iterator: + +```rust +extern crate regex; + +use regex::Regex; + +const TO_SEARCH: &'static str = " +On 2010-03-14, foo happened. On 2014-10-14, bar happened. +"; + +fn main() { + let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); + + for caps in re.captures_iter(TO_SEARCH) { + // Note that all of the unwraps are actually OK for this regex + // because the only way for the regex to match is if all of the + // capture groups match. This is not true in general though! + println!("year: {}, month: {}, day: {}", + caps.get(1).unwrap().as_str(), + caps.get(2).unwrap().as_str(), + caps.get(3).unwrap().as_str()); + } +} +``` + +This example outputs: + +``` +year: 2010, month: 03, day: 14 +year: 2014, month: 10, day: 14 +``` + +### Usage: Avoid compiling the same regex in a loop + +It is an anti-pattern to compile the same regular expression in a loop since +compilation is typically expensive. (It takes anywhere from a few microseconds +to a few **milliseconds** depending on the size of the regex.) Not only is +compilation itself expensive, but this also prevents optimizations that reuse +allocations internally to the matching engines. + +In Rust, it can sometimes be a pain to pass regular expressions around if +they're used from inside a helper function. Instead, we recommend using the +[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that +regular expressions are compiled exactly once. + +For example: + +```rust +#[macro_use] extern crate lazy_static; +extern crate regex; + +use regex::Regex; + +fn some_helper_function(text: &str) -> bool { + lazy_static! { + static ref RE: Regex = Regex::new("...").unwrap(); + } + RE.is_match(text) +} +``` + +Specifically, in this example, the regex will be compiled when it is used for +the first time. On subsequent uses, it will reuse the previous compilation. + +### Usage: match regular expressions on `&[u8]` + +The main API of this crate (`regex::Regex`) requires the caller to pass a +`&str` for searching. In Rust, an `&str` is required to be valid UTF-8, which +means the main API can't be used for searching arbitrary bytes. + +To match on arbitrary bytes, use the `regex::bytes::Regex` API. The API +is identical to the main API, except that it takes an `&[u8]` to search +on instead of an `&str`. By default, `.` will match any *byte* using +`regex::bytes::Regex`, while `.` will match any *UTF-8 encoded Unicode scalar +value* using the main API. + +This example shows how to find all null-terminated strings in a slice of bytes: + +```rust +use regex::bytes::Regex; + +let re = Regex::new(r"(?P[^\x00]+)\x00").unwrap(); +let text = b"foo\x00bar\x00baz\x00"; + +// Extract all of the strings without the null terminator from each match. +// The unwrap is OK here since a match requires the `cstr` capture to match. +let cstrs: Vec<&[u8]> = + re.captures_iter(text) + .map(|c| c.name("cstr").unwrap().as_bytes()) + .collect(); +assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs); +``` + +Notice here that the `[^\x00]+` will match any *byte* except for `NUL`. When +using the main API, `[^\x00]+` would instead match any valid UTF-8 sequence +except for `NUL`. + +### Usage: match multiple regular expressions simultaneously + +This demonstrates how to use a `RegexSet` to match multiple (possibly +overlapping) regular expressions in a single scan of the search text: + +```rust +use regex::RegexSet; + +let set = RegexSet::new(&[ + r"\w+", + r"\d+", + r"\pL+", + r"foo", + r"bar", + r"barfoo", + r"foobar", +]).unwrap(); + +// Iterate over and collect all of the matches. +let matches: Vec<_> = set.matches("foobar").into_iter().collect(); +assert_eq!(matches, vec![0, 2, 3, 4, 6]); + +// You can also test whether a particular regex matched: +let matches = set.matches("foobar"); +assert!(!matches.matched(5)); +assert!(matches.matched(6)); +``` + +### Usage: enable SIMD optimizations + +This crate provides an `unstable` feature that can only be enabled on nightly +Rust. When this feature is enabled, the regex crate will use SIMD optimizations +if your CPU supports them. No additional compile time flags are required; the +regex crate will detect your CPU support at runtime. + +When `std::arch` becomes stable, then these optimizations will be enabled +automatically. + + +### Usage: a regular expression parser + +This repository contains a crate that provides a well tested regular expression +parser, abstract syntax and a high-level intermediate representation for +convenient analysis. It provides no facilities for compilation or execution. +This may be useful if you're implementing your own regex engine or otherwise +need to do analysis on the syntax of a regular expression. It is otherwise not +recommended for general use. + +[Documentation `regex-syntax`.](https://docs.rs/regex-syntax) + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. diff --git a/bash-5.1/vendor/regex/UNICODE.md b/bash-5.1/vendor/regex/UNICODE.md new file mode 100644 index 0000000..0a3b783 --- /dev/null +++ b/bash-5.1/vendor/regex/UNICODE.md @@ -0,0 +1,250 @@ +# Unicode conformance + +This document describes the regex crate's conformance to Unicode's +[UTS#18](http://unicode.org/reports/tr18/) +report, which lays out 3 levels of support: Basic, Extended and Tailored. + +Full support for Level 1 ("Basic Unicode Support") is provided with two +exceptions: + +1. Line boundaries are not Unicode aware. Namely, only the `\n` + (`END OF LINE`) character is recognized as a line boundary. +2. The compatibility properties specified by + [RL1.2a](http://unicode.org/reports/tr18/#RL1.2a) + are ASCII-only definitions. + +Little to no support is provided for either Level 2 or Level 3. For the most +part, this is because the features are either complex/hard to implement, or at +the very least, very difficult to implement without sacrificing performance. +For example, tackling canonical equivalence such that matching worked as one +would expect regardless of normalization form would be a significant +undertaking. This is at least partially a result of the fact that this regex +engine is based on finite automata, which admits less flexibility normally +associated with backtracking implementations. + + +## RL1.1 Hex Notation + +[UTS#18 RL1.1](https://unicode.org/reports/tr18/#Hex_notation) + +Hex Notation refers to the ability to specify a Unicode code point in a regular +expression via its hexadecimal code point representation. This is useful in +environments that have poor Unicode font rendering or if you need to express a +code point that is not normally displayable. All forms of hexadecimal notation +are supported + + \x7F hex character code (exactly two digits) + \x{10FFFF} any hex character code corresponding to a Unicode code point + \u007F hex character code (exactly four digits) + \u{7F} any hex character code corresponding to a Unicode code point + \U0000007F hex character code (exactly eight digits) + \U{7F} any hex character code corresponding to a Unicode code point + +Briefly, the `\x{...}`, `\u{...}` and `\U{...}` are all exactly equivalent ways +of expressing hexadecimal code points. Any number of digits can be written +within the brackets. In contrast, `\xNN`, `\uNNNN`, `\UNNNNNNNN` are all +fixed-width variants of the same idea. + +Note that when Unicode mode is disabled, any non-ASCII Unicode codepoint is +banned. Additionally, the `\xNN` syntax represents arbitrary bytes when Unicode +mode is disabled. That is, the regex `\xFF` matches the Unicode codepoint +U+00FF (encoded as `\xC3\xBF` in UTF-8) while the regex `(?-u)\xFF` matches +the literal byte `\xFF`. + + +## RL1.2 Properties + +[UTS#18 RL1.2](https://unicode.org/reports/tr18/#Categories) + +Full support for Unicode property syntax is provided. Unicode properties +provide a convenient way to construct character classes of groups of code +points specified by Unicode. The regex crate does not provide exhaustive +support, but covers a useful subset. In particular: + +* [General categories](http://unicode.org/reports/tr18/#General_Category_Property) +* [Scripts and Script Extensions](http://unicode.org/reports/tr18/#Script_Property) +* [Age](http://unicode.org/reports/tr18/#Age) +* A smattering of boolean properties, including all of those specified by + [RL1.2](http://unicode.org/reports/tr18/#RL1.2) explicitly. + +In all cases, property name and value abbreviations are supported, and all +names/values are matched loosely without regard for case, whitespace or +underscores. Property name aliases can be found in Unicode's +[`PropertyAliases.txt`](http://www.unicode.org/Public/UCD/latest/ucd/PropertyAliases.txt) +file, while property value aliases can be found in Unicode's +[`PropertyValueAliases.txt`](http://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt) +file. + +The syntax supported is also consistent with the UTS#18 recommendation: + +* `\p{Greek}` selects the `Greek` script. Equivalent expressions follow: + `\p{sc:Greek}`, `\p{Script:Greek}`, `\p{Sc=Greek}`, `\p{script=Greek}`, + `\P{sc!=Greek}`. Similarly for `General_Category` (or `gc` for short) and + `Script_Extensions` (or `scx` for short). +* `\p{age:3.2}` selects all code points in Unicode 3.2. +* `\p{Alphabetic}` selects the "alphabetic" property and can be abbreviated + via `\p{alpha}` (for example). +* Single letter variants for properties with single letter abbreviations. + For example, `\p{Letter}` can be equivalently written as `\pL`. + +The following is a list of all properties supported by the regex crate (starred +properties correspond to properties required by RL1.2): + +* `General_Category` \* (including `Any`, `ASCII` and `Assigned`) +* `Script` \* +* `Script_Extensions` \* +* `Age` +* `ASCII_Hex_Digit` +* `Alphabetic` \* +* `Bidi_Control` +* `Case_Ignorable` +* `Cased` +* `Changes_When_Casefolded` +* `Changes_When_Casemapped` +* `Changes_When_Lowercased` +* `Changes_When_Titlecased` +* `Changes_When_Uppercased` +* `Dash` +* `Default_Ignorable_Code_Point` \* +* `Deprecated` +* `Diacritic` +* `Extender` +* `Grapheme_Base` +* `Grapheme_Extend` +* `Hex_Digit` +* `IDS_Binary_Operator` +* `IDS_Trinary_Operator` +* `ID_Continue` +* `ID_Start` +* `Join_Control` +* `Logical_Order_Exception` +* `Lowercase` \* +* `Math` +* `Noncharacter_Code_Point` \* +* `Pattern_Syntax` +* `Pattern_White_Space` +* `Prepended_Concatenation_Mark` +* `Quotation_Mark` +* `Radical` +* `Regional_Indicator` +* `Sentence_Terminal` +* `Soft_Dotted` +* `Terminal_Punctuation` +* `Unified_Ideograph` +* `Uppercase` \* +* `Variation_Selector` +* `White_Space` \* +* `XID_Continue` +* `XID_Start` + + +## RL1.2a Compatibility Properties + +[UTS#18 RL1.2a](http://unicode.org/reports/tr18/#RL1.2a) + +The regex crate only provides ASCII definitions of the +[compatibility properties documented in UTS#18 Annex C](http://unicode.org/reports/tr18/#Compatibility_Properties) +(sans the `\X` class, for matching grapheme clusters, which isn't provided +at all). This is because it seems to be consistent with most other regular +expression engines, and in particular, because these are often referred to as +"ASCII" or "POSIX" character classes. + +Note that the `\w`, `\s` and `\d` character classes **are** Unicode aware. +Their traditional ASCII definition can be used by disabling Unicode. That is, +`[[:word:]]` and `(?-u)\w` are equivalent. + + +## RL1.3 Subtraction and Intersection + +[UTS#18 RL1.3](http://unicode.org/reports/tr18/#Subtraction_and_Intersection) + +The regex crate provides full support for nested character classes, along with +union, intersection (`&&`), difference (`--`) and symmetric difference (`~~`) +operations on arbitrary character classes. + +For example, to match all non-ASCII letters, you could use either +`[\p{Letter}--\p{Ascii}]` (difference) or `[\p{Letter}&&[^\p{Ascii}]]` +(intersecting the negation). + + +## RL1.4 Simple Word Boundaries + +[UTS#18 RL1.4](http://unicode.org/reports/tr18/#Simple_Word_Boundaries) + +The regex crate provides basic Unicode aware word boundary assertions. A word +boundary assertion can be written as `\b`, or `\B` as its negation. A word +boundary negation corresponds to a zero-width match, where its adjacent +characters correspond to word and non-word, or non-word and word characters. + +Conformance in this case chooses to define word character in the same way that +the `\w` character class is defined: a code point that is a member of one of +the following classes: + +* `\p{Alphabetic}` +* `\p{Join_Control}` +* `\p{gc:Mark}` +* `\p{gc:Decimal_Number}` +* `\p{gc:Connector_Punctuation}` + +In particular, this differs slightly from the +[prescription given in RL1.4](http://unicode.org/reports/tr18/#Simple_Word_Boundaries) +but is permissible according to +[UTS#18 Annex C](http://unicode.org/reports/tr18/#Compatibility_Properties). +Namely, it is convenient and simpler to have `\w` and `\b` be in sync with +one another. + +Finally, Unicode word boundaries can be disabled, which will cause ASCII word +boundaries to be used instead. That is, `\b` is a Unicode word boundary while +`(?-u)\b` is an ASCII-only word boundary. This can occasionally be beneficial +if performance is important, since the implementation of Unicode word +boundaries is currently sub-optimal on non-ASCII text. + + +## RL1.5 Simple Loose Matches + +[UTS#18 RL1.5](http://unicode.org/reports/tr18/#Simple_Loose_Matches) + +The regex crate provides full support for case insensitive matching in +accordance with RL1.5. That is, it uses the "simple" case folding mapping. The +"simple" mapping was chosen because of a key convenient property: every +"simple" mapping is a mapping from exactly one code point to exactly one other +code point. This makes case insensitive matching of character classes, for +example, straight-forward to implement. + +When case insensitive mode is enabled (e.g., `(?i)[a]` is equivalent to `a|A`), +then all characters classes are case folded as well. + + +## RL1.6 Line Boundaries + +[UTS#18 RL1.6](http://unicode.org/reports/tr18/#Line_Boundaries) + +The regex crate only provides support for recognizing the `\n` (`END OF LINE`) +character as a line boundary. This choice was made mostly for implementation +convenience, and to avoid performance cliffs that Unicode word boundaries are +subject to. + +Ideally, it would be nice to at least support `\r\n` as a line boundary as +well, and in theory, this could be done efficiently. + + +## RL1.7 Code Points + +[UTS#18 RL1.7](http://unicode.org/reports/tr18/#Supplementary_Characters) + +The regex crate provides full support for Unicode code point matching. Namely, +the fundamental atom of any match is always a single code point. + +Given Rust's strong ties to UTF-8, the following guarantees are also provided: + +* All matches are reported on valid UTF-8 code unit boundaries. That is, any + match range returned by the public regex API is guaranteed to successfully + slice the string that was searched. +* By consequence of the above, it is impossible to match surrogode code points. + No support for UTF-16 is provided, so this is never necessary. + +Note that when Unicode mode is disabled, the fundamental atom of matching is +no longer a code point but a single byte. When Unicode mode is disabled, many +Unicode features are disabled as well. For example, `(?-u)\pL` is not a valid +regex but `\pL(?-u)\xFF` (matches any Unicode `Letter` followed by the literal +byte `\xFF`) is, for example. diff --git a/bash-5.1/vendor/regex/appveyor.yml b/bash-5.1/vendor/regex/appveyor.yml new file mode 100644 index 0000000..c67ab0e --- /dev/null +++ b/bash-5.1/vendor/regex/appveyor.yml @@ -0,0 +1,19 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V +build: false +test_script: + - cargo test --verbose --jobs 4 +branches: + only: + - master + - auto diff --git a/bash-5.1/vendor/regex/build.rs b/bash-5.1/vendor/regex/build.rs new file mode 100644 index 0000000..ad27991 --- /dev/null +++ b/bash-5.1/vendor/regex/build.rs @@ -0,0 +1,27 @@ +use std::env; +use std::ffi::OsString; +use std::process::Command; + +fn main() { + let rustc = env::var_os("RUSTC").unwrap_or(OsString::from("rustc")); + let output = Command::new(&rustc) + .arg("--version") + .output() + .unwrap() + .stdout; + let version = String::from_utf8(output).unwrap(); + + // If we're using nightly Rust, then we can enable vector optimizations. + // Note that these aren't actually activated unless the `nightly` feature + // is enabled. + // + // We also don't activate these if we've explicitly disabled auto + // optimizations. Disabling auto optimizations is intended for use in + // tests, so that we can reliably test fallback implementations. + if env::var_os("CARGO_CFG_REGEX_DISABLE_AUTO_OPTIMIZATIONS").is_none() { + if version.contains("nightly") { + println!("cargo:rustc-cfg=regex_runtime_teddy_ssse3"); + println!("cargo:rustc-cfg=regex_runtime_teddy_avx2"); + } + } +} diff --git a/bash-5.1/vendor/regex/ci/after_success.sh b/bash-5.1/vendor/regex/ci/after_success.sh new file mode 100755 index 0000000..4e11477 --- /dev/null +++ b/bash-5.1/vendor/regex/ci/after_success.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# This runs only when a commit is pushed to master. It is responsible for +# updating docs and computing coverage statistics. + +set -e + +if [ "$TRAVIS_RUST_VERSION" != "nightly" ] || [ "$TRAVIS_PULL_REQUEST" != "false" ] || [ "$TRAVIS_BRANCH" != "master" ]; then + exit 0 +fi + +env + +# Install kcov. +tmp=$(mktemp -d) +pushd "$tmp" +wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz +tar zxf master.tar.gz +mkdir kcov-master/build +cd kcov-master/build +cmake .. +make +make install DESTDIR="$tmp" +popd +PATH="$tmp/usr/local/bin:$PATH" ./ci/run-kcov --coveralls-id $TRAVIS_JOB_ID diff --git a/bash-5.1/vendor/regex/ci/run-kcov b/bash-5.1/vendor/regex/ci/run-kcov new file mode 100755 index 0000000..78f5b96 --- /dev/null +++ b/bash-5.1/vendor/regex/ci/run-kcov @@ -0,0 +1,44 @@ +#!/bin/bash + +set -e + +tests=( + default + default_bytes + backtrack + backtrack_utf8bytes + backtrack_bytes + nfa + nfa_utf8bytes + nfa_bytes + regex +) +tmpdir=$(mktemp -d) +coveralls_id= + +while true; do + case "$1" in + --coveralls-id) + coveralls_id="$2" + shift 2 + ;; + *) + break + ;; + esac +done + +cargo test --no-run --verbose --jobs 4 --features unstable +for t in ${tests[@]}; do + kcov \ + --verify \ + --include-pattern '/regex/src/' \ + "$tmpdir/$t" \ + $(find ./target/debug -executable -wholename "./target/debug/$t-*" | head -n1) +done + +if [ -n "$coveralls_id" ]; then + kcov --verify --coveralls-id=$coveralls_id --merge target/cov "$tmpdir"/* +else + kcov --verify --merge target/cov "$tmpdir"/* +fi diff --git a/bash-5.1/vendor/regex/ci/run-shootout-test b/bash-5.1/vendor/regex/ci/run-shootout-test new file mode 100755 index 0000000..5d1dc1d --- /dev/null +++ b/bash-5.1/vendor/regex/ci/run-shootout-test @@ -0,0 +1,18 @@ +#!/bin/bash + +set -e + +cargo build --example shootout-regex-dna +diff \ + ./examples/regexdna-output.txt \ + <(./target/debug/examples/shootout-regex-dna < ./examples/regexdna-input.txt) + +cargo build --example shootout-regex-dna-single +diff \ + ./examples/regexdna-output.txt \ + <(./target/debug/examples/shootout-regex-dna-single < ./examples/regexdna-input.txt) + +cargo build --example shootout-regex-dna-cheat +diff \ + ./examples/regexdna-output.txt \ + <(./target/debug/examples/shootout-regex-dna-cheat < ./examples/regexdna-input.txt) diff --git a/bash-5.1/vendor/regex/ci/script.sh b/bash-5.1/vendor/regex/ci/script.sh new file mode 100755 index 0000000..baaca96 --- /dev/null +++ b/bash-5.1/vendor/regex/ci/script.sh @@ -0,0 +1,46 @@ +#!/bin/sh + +# This is the main CI script for testing the regex crate and its sub-crates. + +set -ex + +# Builds the regex crate and runs tests. +cargo build --verbose +cargo doc --verbose + +# If we're testing on an older version of Rust, then only check that we +# can build the crate. This is because the dev dependencies might be updated +# more frequently, and therefore might require a newer version of Rust. +# +# This isn't ideal. It's a compromise. +if [ "$TRAVIS_RUST_VERSION" = "1.12.0" ]; then + exit +fi + +# Run tests. If we have nightly, then enable our nightly features. +if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then + cargo test --verbose --features unstable +else + cargo test --verbose +fi + +# Run a test that confirms the shootout benchmarks are correct. +ci/run-shootout-test + +# Run tests on regex-syntax crate. +cargo test --verbose --manifest-path regex-syntax/Cargo.toml +cargo doc --verbose --manifest-path regex-syntax/Cargo.toml + +# Run tests on regex-capi crate. +cargo build --verbose --manifest-path regex-capi/Cargo.toml +(cd regex-capi/ctest && ./compile && LD_LIBRARY_PATH=../../target/debug ./test) +(cd regex-capi/examples && ./compile && LD_LIBRARY_PATH=../../target/debug ./iter) + +# Make sure benchmarks compile. Don't run them though because they take a +# very long time. Also, check that we can build the regex-debug tool. +if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then + cargo build --verbose --manifest-path regex-debug/Cargo.toml + for x in rust rust-bytes pcre1 onig; do + (cd bench && ./run $x --no-run --verbose) + done +fi diff --git a/bash-5.1/vendor/regex/examples/regexdna-input.txt b/bash-5.1/vendor/regex/examples/regexdna-input.txt new file mode 100644 index 0000000..fb23263 --- /dev/null +++ b/bash-5.1/vendor/regex/examples/regexdna-input.txt @@ -0,0 +1,1671 @@ +>ONE Homo sapiens alu +GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA +TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT +AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG +GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG +CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT +GGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCA +GGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAA +TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAG +AATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCA +GCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGT +AATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACC +AGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTG +GTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACC +CGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAG +AGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTT +TGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACA +TGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCT +GTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGG +TTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGT +CTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGG +CGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCG +TCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTA +CTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCG +AGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCG +GGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACC +TGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAA +TACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGA +GGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACT +GCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTC +ACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGT +TCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGC +CGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCG +CTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTG +GGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCC +CAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCT +GGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGC +GCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGA +GGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGA +GACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGA +GGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTG +AAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT +CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCA +GTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAA +AAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGC +GGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCT +ACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGG +GAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATC +GCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGC +GGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGG +TCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAA +AAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAG +GAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACT +CCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCC +TGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAG +ACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGC +GTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGA +ACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGA +CAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCA +CTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCA +ACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCG +CCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGG +AGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTC +CGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCG +AGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACC +CCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAG +CTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAG +CCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGG +CCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATC +ACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAA +AAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGC +TGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCC +ACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGG +CTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGG +AGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATT +AGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAA +TCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGC +CTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAA +TCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAG +CCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGT +GGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCG +GGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAG +CGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG +GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATG +GTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGT +AATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTT +GCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCT +CAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCG +GGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTC +TCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACT +CGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAG +ATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGG +CGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTG +AGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATA +CAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGG +CAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGC +ACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCAC +GCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTC +GAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCG +GGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCT +TGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGG +CGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCA +GCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGG +CCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGC +GCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGG +CGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGA +CTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGG +CCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAA +ACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCC +CAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGT +GAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAA +AGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGG +ATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTAC +TAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGA +GGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGC +GCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGG +TGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTC +AGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAA +ATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGA +GAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC +AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTG +TAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGAC +CAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGT +GGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC +CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACA +GAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACT +TTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAAC +ATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCC +TGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAG +GTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCG +TCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAG +GCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCC +GTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCT +ACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCC +GAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCC +GGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCAC +CTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAA +ATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTG +AGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCAC +TGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCT +CACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAG +TTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAG +CCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATC +GCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCT +GGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATC +CCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCC +TGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGG +CGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG +AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCG +AGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGG +AGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGT +GAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAA +TCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGC +AGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCA +AAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGG +CGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTC +TACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCG +GGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGAT +CGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCG +CGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAG +GTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACA +AAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCA +GGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCAC +TCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGC +CTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA +GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGG +CGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTG +AACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCG +ACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGC +ACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCC +AACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGC +GCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCG +GAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACT +CCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCC +GAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAAC +CCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA +GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGA +GCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAG +GCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGAT +CACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTA +AAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGG +CTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGC +CACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTG +GCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAG +GAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAAT +TAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGA +ATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAG +CCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTA +ATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCA +GCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGG +TGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCC +GGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGA +GCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTT +GGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACAT +GGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTG +TAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGT +TGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTC +TCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGC +GGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGT +CTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTAC +TCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGA +GATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGG +GCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCT +GAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT +ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAG +GCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG +CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCA +CGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTT +CGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCC +GGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGC +TTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGG +GCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCC +AGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTG +GCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCG +CGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAG +GCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAG +ACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAG +GCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGA +AACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATC +CCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAG +TGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAA +AAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCG +GATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTA +CTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGG +AGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCG +CGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCG +GTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGT +CAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAA +AATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGG +AGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTC +CAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCT +GTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA +CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCG +TGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAA +CCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGAC +AGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCAC +TTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAA +CATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGC +CTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGA +GGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCC +GTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGA +GGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCC +CGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGC +TACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGC +CGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGC +CGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCA +CCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA +AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCT +GAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCA +CTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGC +TCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGA +GTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTA +GCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAAT +CGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCC +TGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAAT +CCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGC +CTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTG +GCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGG +GAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGC +GAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG +GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGG +TGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTA +ATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTG +CAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTC +AAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGG +GCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCT +CTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTC +GGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGA +TCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGC +GCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGA +GGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATAC +AAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGC +AGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCA +CTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACG +CCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCG +AGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGG +GCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTT +GAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGC +GACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAG +CACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGC +CAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCG +CGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGC +GGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGAC +TCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGC +CGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAA +CCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCC +AGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTG +AGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA +GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA +TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT +AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG +GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG +CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT +GGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCA +GGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAA +TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAG +AATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCA +GCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGT +AATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACC +AGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTG +GTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACC +CGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAG +AGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTT +TGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACA +TGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCT +GTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGG +TTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGT +CTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGG +CGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCG +TCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTA +CTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCG +AGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCG +GGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACC +TGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAA +TACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGA +GGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACT +GCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTC +ACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGT +TCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGC +CGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCG +CTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTG +GGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCC +CAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCT +GGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGC +GCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGA +GGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGA +GACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGA +GGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTG +AAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT +CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCA +GTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAA +AAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGC +GGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCT +ACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGG +GAGGCTGAGGCAGGAGAATC +>TWO IUB ambiguity codes +cttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg +tactDtDagcctatttSVHtHttKtgtHMaSattgWaHKHttttagacatWatgtRgaaa +NtactMcSMtYtcMgRtacttctWBacgaaatatagScDtttgaagacacatagtVgYgt +cattHWtMMWcStgttaggKtSgaYaaccWStcgBttgcgaMttBYatcWtgacaYcaga +gtaBDtRacttttcWatMttDBcatWtatcttactaBgaYtcttgttttttttYaaScYa +HgtgttNtSatcMtcVaaaStccRcctDaataataStcYtRDSaMtDttgttSagtRRca +tttHatSttMtWgtcgtatSSagactYaaattcaMtWatttaSgYttaRgKaRtccactt +tattRggaMcDaWaWagttttgacatgttctacaaaRaatataataaMttcgDacgaSSt +acaStYRctVaNMtMgtaggcKatcttttattaaaaagVWaHKYagtttttatttaacct +tacgtVtcVaattVMBcttaMtttaStgacttagattWWacVtgWYagWVRctDattBYt +gtttaagaagattattgacVatMaacattVctgtBSgaVtgWWggaKHaatKWcBScSWa +accRVacacaaactaccScattRatatKVtactatatttHttaagtttSKtRtacaaagt +RDttcaaaaWgcacatWaDgtDKacgaacaattacaRNWaatHtttStgttattaaMtgt +tgDcgtMgcatBtgcttcgcgaDWgagctgcgaggggVtaaScNatttacttaatgacag +cccccacatYScaMgtaggtYaNgttctgaMaacNaMRaacaaacaKctacatagYWctg +ttWaaataaaataRattagHacacaagcgKatacBttRttaagtatttccgatctHSaat +actcNttMaagtattMtgRtgaMgcataatHcMtaBSaRattagttgatHtMttaaKagg +YtaaBataSaVatactWtataVWgKgttaaaacagtgcgRatatacatVtHRtVYataSa +KtWaStVcNKHKttactatccctcatgWHatWaRcttactaggatctataDtDHBttata +aaaHgtacVtagaYttYaKcctattcttcttaataNDaaggaaaDYgcggctaaWSctBa +aNtgctggMBaKctaMVKagBaactaWaDaMaccYVtNtaHtVWtKgRtcaaNtYaNacg +gtttNattgVtttctgtBaWgtaattcaagtcaVWtactNggattctttaYtaaagccgc +tcttagHVggaYtgtNcDaVagctctctKgacgtatagYcctRYHDtgBattDaaDgccK +tcHaaStttMcctagtattgcRgWBaVatHaaaataYtgtttagMDMRtaataaggatMt +ttctWgtNtgtgaaaaMaatatRtttMtDgHHtgtcattttcWattRSHcVagaagtacg +ggtaKVattKYagactNaatgtttgKMMgYNtcccgSKttctaStatatNVataYHgtNa +BKRgNacaactgatttcctttaNcgatttctctataScaHtataRagtcRVttacDSDtt +aRtSatacHgtSKacYagttMHtWataggatgactNtatSaNctataVtttRNKtgRacc +tttYtatgttactttttcctttaaacatacaHactMacacggtWataMtBVacRaSaatc +cgtaBVttccagccBcttaRKtgtgcctttttRtgtcagcRttKtaaacKtaaatctcac +aattgcaNtSBaaccgggttattaaBcKatDagttactcttcattVtttHaaggctKKga +tacatcBggScagtVcacattttgaHaDSgHatRMaHWggtatatRgccDttcgtatcga +aacaHtaagttaRatgaVacttagattVKtaaYttaaatcaNatccRttRRaMScNaaaD +gttVHWgtcHaaHgacVaWtgttScactaagSgttatcttagggDtaccagWattWtRtg +ttHWHacgattBtgVcaYatcggttgagKcWtKKcaVtgaYgWctgYggVctgtHgaNcV +taBtWaaYatcDRaaRtSctgaHaYRttagatMatgcatttNattaDttaattgttctaa +ccctcccctagaWBtttHtBccttagaVaatMcBHagaVcWcagBVttcBtaYMccagat +gaaaaHctctaacgttagNWRtcggattNatcRaNHttcagtKttttgWatWttcSaNgg +gaWtactKKMaacatKatacNattgctWtatctaVgagctatgtRaHtYcWcttagccaa +tYttWttaWSSttaHcaaaaagVacVgtaVaRMgattaVcDactttcHHggHRtgNcctt +tYatcatKgctcctctatVcaaaaKaaaagtatatctgMtWtaaaacaStttMtcgactt +taSatcgDataaactaaacaagtaaVctaggaSccaatMVtaaSKNVattttgHccatca +cBVctgcaVatVttRtactgtVcaattHgtaaattaaattttYtatattaaRSgYtgBag +aHSBDgtagcacRHtYcBgtcacttacactaYcgctWtattgSHtSatcataaatataHt +cgtYaaMNgBaatttaRgaMaatatttBtttaaaHHKaatctgatWatYaacttMctctt +ttVctagctDaaagtaVaKaKRtaacBgtatccaaccactHHaagaagaaggaNaaatBW +attccgStaMSaMatBttgcatgRSacgttVVtaaDMtcSgVatWcaSatcttttVatag +ttactttacgatcaccNtaDVgSRcgVcgtgaacgaNtaNatatagtHtMgtHcMtagaa +attBgtataRaaaacaYKgtRccYtatgaagtaataKgtaaMttgaaRVatgcagaKStc +tHNaaatctBBtcttaYaBWHgtVtgacagcaRcataWctcaBcYacYgatDgtDHccta +aagacYRcaggattHaYgtKtaatgcVcaataMYacccatatcacgWDBtgaatcBaata +cKcttRaRtgatgaBDacggtaattaaYtataStgVHDtDctgactcaaatKtacaatgc +gYatBtRaDatHaactgtttatatDttttaaaKVccYcaaccNcBcgHaaVcattHctcg +attaaatBtatgcaaaaatYMctSactHatacgaWacattacMBgHttcgaatVaaaaca +BatatVtctgaaaaWtctRacgBMaatSgRgtgtcgactatcRtattaScctaStagKga +DcWgtYtDDWKRgRtHatRtggtcgaHgggcgtattaMgtcagccaBggWVcWctVaaat +tcgNaatcKWagcNaHtgaaaSaaagctcYctttRVtaaaatNtataaccKtaRgtttaM +tgtKaBtRtNaggaSattHatatWactcagtgtactaKctatttgRYYatKatgtccgtR +tttttatttaatatVgKtttgtatgtNtataRatWYNgtRtHggtaaKaYtKSDcatcKg +taaYatcSRctaVtSMWtVtRWHatttagataDtVggacagVcgKWagBgatBtaaagNc +aRtagcataBggactaacacRctKgttaatcctHgDgttKHHagttgttaatgHBtatHc +DaagtVaBaRccctVgtgDtacRHSctaagagcggWYaBtSaKtHBtaaactYacgNKBa +VYgtaacttagtVttcttaatgtBtatMtMtttaattaatBWccatRtttcatagVgMMt +agctStKctaMactacDNYgKYHgaWcgaHgagattacVgtttgtRaSttaWaVgataat +gtgtYtaStattattMtNgWtgttKaccaatagNYttattcgtatHcWtctaaaNVYKKt +tWtggcDtcgaagtNcagatacgcattaagaccWctgcagcttggNSgaNcHggatgtVt +catNtRaaBNcHVagagaaBtaaSggDaatWaatRccaVgggStctDaacataKttKatt +tggacYtattcSatcttagcaatgaVBMcttDattctYaaRgatgcattttNgVHtKcYR +aatRKctgtaaacRatVSagctgtWacBtKVatctgttttKcgtctaaDcaagtatcSat +aWVgcKKataWaYttcccSaatgaaaacccWgcRctWatNcWtBRttYaattataaNgac +acaatagtttVNtataNaYtaatRaVWKtBatKagtaatataDaNaaaaataMtaagaaS +tccBcaatNgaataWtHaNactgtcDtRcYaaVaaaaaDgtttRatctatgHtgttKtga +aNSgatactttcgagWaaatctKaaDaRttgtggKKagcDgataaattgSaacWaVtaNM +acKtcaDaaatttctRaaVcagNacaScRBatatctRatcctaNatWgRtcDcSaWSgtt +RtKaRtMtKaatgttBHcYaaBtgatSgaSWaScMgatNtctcctatttctYtatMatMt +RRtSaattaMtagaaaaStcgVgRttSVaScagtgDtttatcatcatacRcatatDctta +tcatVRtttataaHtattcYtcaaaatactttgVctagtaaYttagatagtSYacKaaac +gaaKtaaatagataatSatatgaaatSgKtaatVtttatcctgKHaatHattagaaccgt +YaaHactRcggSBNgtgctaaBagBttgtRttaaattYtVRaaaattgtaatVatttctc +ttcatgBcVgtgKgaHaaatattYatagWacNctgaaMcgaattStagWaSgtaaKagtt +ttaagaDgatKcctgtaHtcatggKttVDatcaaggtYcgccagNgtgcVttttagagat +gctaccacggggtNttttaSHaNtatNcctcatSaaVgtactgBHtagcaYggYVKNgta +KBcRttgaWatgaatVtagtcgattYgatgtaatttacDacSctgctaaaStttaWMagD +aaatcaVYctccgggcgaVtaaWtStaKMgDtttcaaMtVgBaatccagNaaatcYRMBg +gttWtaaScKttMWtYataRaDBMaDataatHBcacDaaKDactaMgagttDattaHatH +taYatDtattDcRNStgaatattSDttggtattaaNSYacttcDMgYgBatWtaMagact +VWttctttgYMaYaacRgHWaattgRtaagcattctMKVStatactacHVtatgatcBtV +NataaBttYtSttacKgggWgYDtgaVtYgatDaacattYgatggtRDaVDttNactaSa +MtgNttaacaaSaBStcDctaccacagacgcaHatMataWKYtaYattMcaMtgSttDag +cHacgatcaHttYaKHggagttccgatYcaatgatRaVRcaagatcagtatggScctata +ttaNtagcgacgtgKaaWaactSgagtMYtcttccaKtStaacggMtaagNttattatcg +tctaRcactctctDtaacWYtgaYaSaagaWtNtatttRacatgNaatgttattgWDDcN +aHcctgaaHacSgaataaRaataMHttatMtgaSDSKatatHHaNtacagtccaYatWtc +actaactatKDacSaStcggataHgYatagKtaatKagStaNgtatactatggRHacttg +tattatgtDVagDVaRctacMYattDgtttYgtctatggtKaRSttRccRtaaccttaga +gRatagSaaMaacgcaNtatgaaatcaRaagataatagatactcHaaYKBctccaagaRa +BaStNagataggcgaatgaMtagaatgtcaKttaaatgtaWcaBttaatRcggtgNcaca +aKtttScRtWtgcatagtttWYaagBttDKgcctttatMggNttattBtctagVtacata +aaYttacacaaRttcYtWttgHcaYYtaMgBaBatctNgcDtNttacgacDcgataaSat +YaSttWtcctatKaatgcagHaVaacgctgcatDtgttaSataaaaYSNttatagtaNYt +aDaaaNtggggacttaBggcHgcgtNtaaMcctggtVtaKcgNacNtatVaSWctWtgaW +cggNaBagctctgaYataMgaagatBSttctatacttgtgtKtaattttRagtDtacata +tatatgatNHVgBMtKtaKaNttDHaagatactHaccHtcatttaaagttVaMcNgHata +tKtaNtgYMccttatcaaNagctggacStttcNtggcaVtattactHaSttatgNMVatt +MMDtMactattattgWMSgtHBttStStgatatRaDaagattttctatMtaaaaaggtac +taaVttaSacNaatactgMttgacHaHRttgMacaaaatagttaatatWKRgacDgaRta +tatttattatcYttaWtgtBRtWatgHaaattHataagtVaDtWaVaWtgStcgtMSgaS +RgMKtaaataVacataatgtaSaatttagtcgaaHtaKaatgcacatcggRaggSKctDc +agtcSttcccStYtccRtctctYtcaaKcgagtaMttttcRaYDttgttatctaatcata +NctctgctatcaMatactataggDaHaaSttMtaDtcNatataattctMcStaaBYtaNa +gatgtaatHagagSttgWHVcttatKaYgDctcttggtgttMcRaVgSgggtagacaata +aDtaattSaDaNaHaBctattgNtaccaaRgaVtKNtaaYggHtaKKgHcatctWtctDt +ttctttggSDtNtaStagttataaacaattgcaBaBWggHgcaaaBtYgctaatgaaatW +cDcttHtcMtWWattBHatcatcaaatctKMagtDNatttWaBtHaaaNgMttaaStagt +tctctaatDtcRVaYttgttMtRtgtcaSaaYVgSWDRtaatagctcagDgcWWaaaBaa +RaBctgVgggNgDWStNaNBKcBctaaKtttDcttBaaggBttgaccatgaaaNgttttt +tttatctatgttataccaaDRaaSagtaVtDtcaWatBtacattaWacttaSgtattggD +gKaaatScaattacgWcagKHaaccaYcRcaRttaDttRtttHgaHVggcttBaRgtccc +tDatKaVtKtcRgYtaKttacgtatBtStaagcaattaagaRgBagSaattccSWYttta +ttVaataNctgHgttaaNBgcVYgtRtcccagWNaaaacaDNaBcaaaaRVtcWMgBagM +tttattacgDacttBtactatcattggaaatVccggttRttcatagttVYcatYaSHaHc +ttaaagcNWaHataaaRWtctVtRYtagHtaaaYMataHYtNBctNtKaatattStgaMc +BtRgctaKtgcScSttDgYatcVtggaaKtaagatWccHccgKYctaNNctacaWctttt +gcRtgtVcgaKttcMRHgctaHtVaataaDtatgKDcttatBtDttggNtacttttMtga +acRattaaNagaactcaaaBBVtcDtcgaStaDctgaaaSgttMaDtcgttcaccaaaag +gWtcKcgSMtcDtatgtttStaaBtatagDcatYatWtaaaBacaKgcaDatgRggaaYc +taRtccagattDaWtttggacBaVcHtHtaacDacYgtaatataMagaatgHMatcttat +acgtatttttatattacHactgttataMgStYaattYaccaattgagtcaaattaYtgta +tcatgMcaDcgggtcttDtKgcatgWRtataatatRacacNRBttcHtBgcRttgtgcgt +catacMtttBctatctBaatcattMttMYgattaaVYatgDaatVagtattDacaacDMa +tcMtHcccataagatgBggaccattVWtRtSacatgctcaaggggYtttDtaaNgNtaaB +atggaatgtctRtaBgBtcNYatatNRtagaacMgagSaSDDSaDcctRagtVWSHtVSR +ggaacaBVaccgtttaStagaacaMtactccagtttVctaaRaaHttNcttagcaattta +ttaatRtaaaatctaacDaBttggSagagctacHtaaRWgattcaaBtctRtSHaNtgta +cattVcaHaNaagtataccacaWtaRtaaVKgMYaWgttaKggKMtKcgWatcaDatYtK +SttgtacgaccNctSaattcDcatcttcaaaDKttacHtggttHggRRaRcaWacaMtBW +VHSHgaaMcKattgtaRWttScNattBBatYtaNRgcggaagacHSaattRtttcYgacc +BRccMacccKgatgaacttcgDgHcaaaaaRtatatDtatYVtttttHgSHaSaatagct +NYtaHYaVYttattNtttgaaaYtaKttWtctaNtgagaaaNctNDctaaHgttagDcRt +tatagccBaacgcaRBtRctRtggtaMYYttWtgataatcgaataattattataVaaaaa +ttacNRVYcaaMacNatRttcKatMctgaagactaattataaYgcKcaSYaatMNctcaa +cgtgatttttBacNtgatDccaattattKWWcattttatatatgatBcDtaaaagttgaa +VtaHtaHHtBtataRBgtgDtaataMttRtDgDcttattNtggtctatctaaBcatctaR +atgNacWtaatgaagtcMNaacNgHttatactaWgcNtaStaRgttaaHacccgaYStac +aaaatWggaYaWgaattattcMaactcBKaaaRVNcaNRDcYcgaBctKaacaaaaaSgc +tccYBBHYaVagaatagaaaacagYtctVccaMtcgtttVatcaatttDRtgWctagtac +RttMctgtDctttcKtWttttataaatgVttgBKtgtKWDaWagMtaaagaaattDVtag +gttacatcatttatgtcgMHaVcttaBtVRtcgtaYgBRHatttHgaBcKaYWaatcNSc +tagtaaaaatttacaatcactSWacgtaatgKttWattagttttNaggtctcaagtcact +attcttctaagKggaataMgtttcataagataaaaatagattatDgcBVHWgaBKttDgc +atRHaagcaYcRaattattatgtMatatattgHDtcaDtcaaaHctStattaatHaccga +cNattgatatattttgtgtDtRatagSacaMtcRtcattcccgacacSattgttKaWatt +NHcaacttccgtttSRtgtctgDcgctcaaMagVtBctBMcMcWtgtaacgactctcttR +ggRKSttgYtYatDccagttDgaKccacgVatWcataVaaagaataMgtgataaKYaaat +cHDaacgataYctRtcYatcgcaMgtNttaBttttgatttaRtStgcaacaaaataccVg +aaDgtVgDcStctatatttattaaaaRKDatagaaagaKaaYYcaYSgKStctccSttac +agtcNactttDVttagaaagMHttRaNcSaRaMgBttattggtttaRMggatggcKDgWR +tNaataataWKKacttcKWaaagNaBttaBatMHtccattaacttccccYtcBcYRtaga +ttaagctaaYBDttaNtgaaaccHcaRMtKtaaHMcNBttaNaNcVcgVttWNtDaBatg +ataaVtcWKcttRggWatcattgaRagHgaattNtatttctctattaattaatgaDaaMa +tacgttgggcHaYVaaNaDDttHtcaaHtcVVDgBVagcMacgtgttaaBRNtatRtcag +taagaggtttaagacaVaaggttaWatctccgtVtaDtcDatttccVatgtacNtttccg +tHttatKgScBatgtVgHtYcWagcaKtaMYaaHgtaattaSaHcgcagtWNaatNccNN +YcacgVaagaRacttctcattcccRtgtgtaattagcSttaaStWaMtctNNcSMacatt +ataaactaDgtatWgtagtttaagaaaattgtagtNagtcaataaatttgatMMYactaa +tatcggBWDtVcYttcDHtVttatacYaRgaMaacaStaatcRttttVtagaDtcacWat +ttWtgaaaagaaagNRacDtttStVatBaDNtaactatatcBSMcccaSttccggaMatg +attaaWatKMaBaBatttgataNctgttKtVaagtcagScgaaaDggaWgtgttttKtWt +atttHaatgtagttcactaaKMagttSYBtKtaYgaactcagagRtatagtVtatcaaaW +YagcgNtaDagtacNSaaYDgatBgtcgataacYDtaaactacagWDcYKaagtttatta +gcatcgagttKcatDaattgattatDtcagRtWSKtcgNtMaaaaacaMttKcaWcaaSV +MaaaccagMVtaMaDtMaHaBgaacataBBVtaatVYaNSWcSgNtDNaaKacacBttta +tKtgtttcaaHaMctcagtaacgtcgYtactDcgcctaNgagagcYgatattttaaattt +ccattttacatttDaaRctattttWctttacgtDatYtttcagacgcaaVttagtaaKaa +aRtgVtccataBggacttatttgtttaWNtgttVWtaWNVDaattgtatttBaagcBtaa +BttaaVatcHcaVgacattccNggtcgacKttaaaRtagRtctWagaYggtgMtataatM +tgaaRttattttgWcttNtDRRgMDKacagaaaaggaaaRStcccagtYccVattaNaaK +StNWtgacaVtagaagcttSaaDtcacaacgDYacWDYtgtttKatcVtgcMaDaSKStV +cgtagaaWaKaagtttcHaHgMgMtctataagBtKaaaKKcactggagRRttaagaBaaN +atVVcgRcKSttDaactagtSttSattgttgaaRYatggttVttaataaHttccaagDtg +atNWtaagHtgcYtaactRgcaatgMgtgtRaatRaNaacHKtagactactggaatttcg +ccataacgMctRgatgttaccctaHgtgWaYcactcacYaattcttaBtgacttaaacct +gYgaWatgBttcttVttcgttWttMcNYgtaaaatctYgMgaaattacNgaHgaacDVVM +tttggtHtctaaRgtacagacgHtVtaBMNBgattagcttaRcttacaHcRctgttcaaD +BggttKaacatgKtttYataVaNattccgMcgcgtagtRaVVaattaKaatggttRgaMc +agtatcWBttNtHagctaatctagaaNaaacaYBctatcgcVctBtgcaaagDgttVtga +HtactSNYtaaNccatgtgDacgaVtDcgKaRtacDcttgctaagggcagMDagggtBWR +tttSgccttttttaacgtcHctaVtVDtagatcaNMaVtcVacatHctDWNaataRgcgt +aVHaggtaaaaSgtttMtattDgBtctgatSgtRagagYtctSaKWaataMgattRKtaa +catttYcgtaacacattRWtBtcggtaaatMtaaacBatttctKagtcDtttgcBtKYYB +aKttctVttgttaDtgattttcttccacttgSaaacggaaaNDaattcYNNaWcgaaYat +tttMgcBtcatRtgtaaagatgaWtgaccaYBHgaatagataVVtHtttVgYBtMctaMt +cctgaDcYttgtccaaaRNtacagcMctKaaaggatttacatgtttaaWSaYaKttBtag +DacactagctMtttNaKtctttcNcSattNacttggaacaatDagtattRtgSHaataat +gccVgacccgatactatccctgtRctttgagaSgatcatatcgDcagWaaHSgctYYWta +tHttggttctttatVattatcgactaagtgtagcatVgtgHMtttgtttcgttaKattcM +atttgtttWcaaStNatgtHcaaaDtaagBaKBtRgaBgDtSagtatMtaacYaatYtVc +KatgtgcaacVaaaatactKcRgtaYtgtNgBBNcKtcttaccttKgaRaYcaNKtactt +tgagSBtgtRagaNgcaaaNcacagtVtttHWatgttaNatBgtttaatNgVtctgaata +tcaRtattcttttttttRaaKcRStctcggDgKagattaMaaaKtcaHacttaataataK +taRgDtKVBttttcgtKaggHHcatgttagHggttNctcgtatKKagVagRaaaggaaBt +NatttVKcRttaHctaHtcaaatgtaggHccaBataNaNaggttgcWaatctgatYcaaa +HaatWtaVgaaBttagtaagaKKtaaaKtRHatMaDBtBctagcatWtatttgWttVaaa +ScMNattRactttgtYtttaaaagtaagtMtaMaSttMBtatgaBtttaKtgaatgagYg +tNNacMtcNRacMMHcttWtgtRtctttaacaacattattcYaMagBaacYttMatcttK +cRMtgMNccattaRttNatHaHNaSaaHMacacaVaatacaKaSttHatattMtVatWga +ttttttaYctttKttHgScWaacgHtttcaVaaMgaacagNatcgttaacaaaaagtaca +HBNaattgttKtcttVttaaBtctgctacgBgcWtttcaggacacatMgacatcccagcg +gMgaVKaBattgacttaatgacacacaaaaaatRKaaBctacgtRaDcgtagcVBaacDS +BHaaaaSacatatacagacRNatcttNaaVtaaaataHattagtaaaaSWccgtatWatg +gDttaactattgcccatcttHaSgYataBttBaactattBtcHtgatcaataSttaBtat +KSHYttWggtcYtttBttaataccRgVatStaHaKagaatNtagRMNgtcttYaaSaact +cagDSgagaaYtMttDtMRVgWKWtgMaKtKaDttttgactatacataatcNtatNaHat +tVagacgYgatatatttttgtStWaaatctWaMgagaRttRatacgStgattcttaagaD +taWccaaatRcagcagaaNKagtaaDggcgccBtYtagSBMtactaaataMataBSacRM +gDgattMMgtcHtcaYDtRaDaacggttDaggcMtttatgttaNctaattaVacgaaMMt +aatDccSgtattgaRtWWaccaccgagtactMcgVNgctDctaMScatagcgtcaactat +acRacgHRttgctatttaatgaattataYKttgtaagWgtYttgcHgMtaMattWaWVta +RgcttgYgttBHtYataSccStBtgtagMgtDtggcVaaSBaatagDttgBgtctttctc +attttaNagtHKtaMWcYactVcgcgtatMVtttRacVagDaatcttgctBBcRDgcaac +KttgatSKtYtagBMagaRtcgBattHcBWcaactgatttaatttWDccatttatcgagS +KaWttataHactaHMttaatHtggaHtHagaatgtKtaaRactgtttMatacgatcaagD +gatKaDctataMggtHDtggHacctttRtatcttYattttgacttgaaSaataaatYcgB +aaaaccgNatVBttMacHaKaataagtatKgtcaagactcttaHttcggaattgttDtct +aaccHttttWaaatgaaatataaaWattccYDtKtaaaacggtgaggWVtctattagtga +ctattaagtMgtttaagcatttgSgaaatatccHaaggMaaaattttcWtatKctagDtY +tMcctagagHcactttactatacaaacattaacttaHatcVMYattYgVgtMttaaRtga +aataaDatcaHgtHHatKcDYaatcttMtNcgatYatgSaMaNtcttKcWataScKggta +tcttacgcttWaaagNatgMgHtctttNtaacVtgttcMaaRatccggggactcMtttaY +MtcWRgNctgNccKatcttgYDcMgattNYaRagatHaaHgKctcataRDttacatBatc +cattgDWttatttaWgtcggagaaaaatacaatacSNtgggtttccttacSMaagBatta +caMaNcactMttatgaRBacYcYtcaaaWtagctSaacttWgDMHgaggatgBVgcHaDt +ggaactttggtcNatNgtaKaBcccaNtaagttBaacagtatacDYttcctNgWgcgSMc +acatStctHatgRcNcgtacacaatRttMggaNKKggataaaSaYcMVcMgtaMaHtgat +tYMatYcggtcttcctHtcDccgtgRatcattgcgccgatatMaaYaataaYSggatagc +gcBtNtaaaScaKgttBgagVagttaKagagtatVaactaSacWactSaKatWccaKaaa +atBKgaaKtDMattttgtaaatcRctMatcaaMagMttDgVatggMaaWgttcgaWatga +aatttgRtYtattaWHKcRgctacatKttctaccaaHttRatctaYattaaWatVNccat +NgagtcKttKataStRaatatattcctRWatDctVagttYDgSBaatYgttttgtVaatt +taatagcagMatRaacttBctattgtMagagattaaactaMatVtHtaaatctRgaaaaa +aaatttWacaacaYccYDSaattMatgaccKtaBKWBattgtcaagcHKaagttMMtaat +ttcKcMagNaaKagattggMagaggtaatttYacatcWaaDgatMgKHacMacgcVaaca +DtaDatatYggttBcgtatgWgaSatttgtagaHYRVacaRtctHaaRtatgaactaata +tctSSBgggaaHMWtcaagatKgagtDaSatagttgattVRatNtctMtcSaagaSHaat +aNataataRaaRgattctttaataaagWaRHcYgcatgtWRcttgaaggaMcaataBRaa +ccagStaaacNtttcaatataYtaatatgHaDgcStcWttaacctaRgtYaRtataKtgM +ttttatgactaaaatttacYatcccRWtttHRtattaaatgtttatatttgttYaatMca +RcSVaaDatcgtaYMcatgtagacatgaaattgRtcaaYaaYtRBatKacttataccaNa +aattVaBtctggacaagKaaYaaatatWtMtatcYaaVNtcgHaactBaagKcHgtctac +aatWtaDtSgtaHcataHtactgataNctRgttMtDcDttatHtcgtacatcccaggStt +aBgtcacacWtccNMcNatMVaVgtccDYStatMaccDatggYaRKaaagataRatttHK +tSaaatDgataaacttaHgttgVBtcttVttHgDacgaKatgtatatNYataactctSat +atatattgcHRRYttStggaactHgttttYtttaWtatMcttttctatctDtagVHYgMR +BgtHttcctaatYRttKtaagatggaVRataKDctaMtKBNtMtHNtWtttYcVtattMc +gRaacMcctNSctcatttaaagDcaHtYccSgatgcaatYaaaaDcttcgtaWtaattct +cgttttScttggtaatctttYgtctaactKataHacctMctcttacHtKataacacagcN +RatgKatttttSaaatRYcgDttaMRcgaaattactMtgcgtaagcgttatBtttttaat +taagtNacatHgttcRgacKcBBtVgatKttcgaBaatactDRgtRtgaNacWtcacYtt +aaKcgttctHaKttaNaMgWgWaggtctRgaKgWttSttBtDcNtgtttacaaatYcDRt +gVtgcctattcNtctaaaDMNttttNtggctgagaVctDaacVtWccaagtaacacaNct +gaScattccDHcVBatcgatgtMtaatBgHaatDctMYgagaatgYWKcctaatNaStHa +aaKccgHgcgtYaaYtattgtStgtgcaaRtattaKatattagaWVtcaMtBagttatta +gNaWHcVgcaattttDcMtgtaRHVYtHtctgtaaaaHVtMKacatcgNaatttMatatg +ttgttactagWYtaRacgataKagYNKcattataNaRtgaacKaYgcaaYYacaNccHat +MatDcNgtHttRaWttagaaDcaaaaaatagggtKDtStaDaRtaVtHWKNtgtattVct +SVgRgataDaRaWataBgaagaaKtaataaYgDcaStaNgtaDaaggtattHaRaWMYaY +aWtggttHYgagVtgtgcttttcaaDKcagVcgttagacNaaWtagtaataDttctggtt +VcatcataaagtgKaaaNaMtaBBaattaatWaattgctHaVKaSgDaaVKaHtatatat +HatcatSBagNgHtatcHYMHgttDgtaHtBttWatcgtttaRaattgStKgSKNWKatc +agDtctcagatttctRtYtBatBgHHtKaWtgYBgacVVWaKtacKcDttKMaKaVcggt +gttataagaataaHaatattagtataatMHgttYgaRttagtaRtcaaVatacggtcMcg +agtaaRttacWgactKRYataaaagSattYaWgagatYagKagatgSaagKgttaatMgg +tataatgttWYttatgagaaacctNVataatHcccKtDctcctaatactggctHggaSag +gRtKHaWaattcgSatMatttagaggcYtctaMcgctcataSatatgRagacNaaDagga +VBagaYttKtacNaKgtSYtagttggaWcatcWttaatctatgaVtcgtgtMtatcaYcg +tRccaaYgDctgcMgtgtWgacWtgataacacgcgctBtgttaKtYDtatDcatcagKaV +MctaatcttgVcaaRgcRMtDcgattaHttcaNatgaatMtactacVgtRgatggaWttt +actaaKatgagSaaKggtaNtactVaYtaaKRagaacccacaMtaaMtKtatBcttgtaa +WBtMctaataaVcDaaYtcRHBtcgttNtaaHatttBNgRStVDattBatVtaagttaYa +tVattaagaBcacggtSgtVtatttaRattgatgtaHDKgcaatattKtggcctatgaWD +KRYcggattgRctatNgatacaatMNttctgtcRBYRaaaHctNYattcHtaWcaattct +BtMKtVgYataatMgYtcagcttMDataVtggRtKtgaatgccNcRttcaMtRgattaac +attRcagcctHtWMtgtDRagaKaBtgDttYaaaaKatKgatctVaaYaacWcgcatagB +VtaNtRtYRaggBaaBtgKgttacataagagcatgtRattccacttaccatRaaatgWgD +aMHaYVgVtaSctatcgKaatatattaDgacccYagtgtaYNaaatKcagtBRgagtcca +tgKgaaaccBgaagBtgSttWtacgatWHaYatcgatttRaaNRgcaNaKVacaNtDgat +tgHVaatcDaagcgtatgcNttaDataatcSataaKcaataaHWataBtttatBtcaKtK +tatagttaDgSaYctacaRatNtaWctSaatatttYaKaKtaccWtatcRagacttaYtt +VcKgSDcgagaagatccHtaattctSttatggtKYgtMaHagVaBRatttctgtRgtcta +tgggtaHKgtHacHtSYacgtacacHatacKaaBaVaccaDtatcSaataaHaagagaat +ScagactataaRttagcaaVcaHataKgDacatWccccaagcaBgagWatctaYttgaaa +tctVNcYtttWagHcgcgcDcVaaatgttKcHtNtcaatagtgtNRaactttttcaatgg +WgBcgDtgVgtttctacMtaaataaaRggaaacWaHttaRtNtgctaaRRtVBctYtVta +tDcattDtgaccYatagatYRKatNYKttNgcctagtaWtgaactaMVaacctgaStttc +tgaKVtaaVaRKDttVtVctaDNtataaaDtccccaagtWtcgatcactDgYaBcatcct +MtVtacDaaBtYtMaKNatNtcaNacgDatYcatcgcaRatWBgaacWttKttagYtaat +tcggttgSWttttDWctttacYtatatWtcatDtMgtBttgRtVDggttaacYtacgtac +atgaattgaaWcttMStaDgtatattgaDtcRBcattSgaaVBRgagccaaKtttcDgcg +aSMtatgWattaKttWtgDBMaggBBttBaatWttRtgcNtHcgttttHtKtcWtagHSt +aacagttgatatBtaWSaWggtaataaMttaKacDaatactcBttcaatatHttcBaaSa +aatYggtaRtatNtHcaatcaHtagVtgtattataNggaMtcttHtNagctaaaggtaga +YctMattNaMVNtcKtactBKcaHHcBttaSagaKacataYgctaKaYgttYcgacWVtt +WtSagcaacatcccHaccKtcttaacgaKttcacKtNtacHtatatRtaaatacactaBt +ttgaHaRttggttWtatYagcatYDatcggagagcWBataagRtacctataRKgtBgatg +aDatataSttagBaHtaatNtaDWcWtgtaattacagKttcNtMagtattaNgtctcgtc +ctcttBaHaKcKccgtRcaaYagSattaagtKataDatatatagtcDtaacaWHcaKttD +gaaRcgtgYttgtcatatNtatttttatggccHtgDtYHtWgttatYaacaattcaWtat +NgctcaaaSttRgctaatcaaatNatcgtttaBtNNVtgttataagcaaagattBacgtD +atttNatttaaaDcBgtaSKgacgtagataatttcHMVNttgttBtDtgtaWKaaRMcKM +tHtaVtagataWctccNNaSWtVaHatctcMgggDgtNHtDaDttatatVWttgttattt +aacctttcacaaggaSaDcggttttttatatVtctgVtaacaStDVaKactaMtttaSNa +gtgaaattaNacttSKctattcctctaSagKcaVttaagNaVcttaVaaRNaHaaHttat +gtHttgtgatMccaggtaDcgaccgtWgtWMtttaHcRtattgScctatttKtaaccaag +tYagaHgtWcHaatgccKNRtttagtMYSgaDatctgtgaWDtccMNcgHgcaaacNDaa +aRaStDWtcaaaaHKtaNBctagBtgtattaactaattttVctagaatggcWSatMaccc +ttHttaSgSgtgMRcatRVKtatctgaaaccDNatYgaaVHNgatMgHRtacttaaaRta +tStRtDtatDttYatattHggaBcttHgcgattgaKcKtttcRataMtcgaVttWacatN +catacctRataDDatVaWNcggttgaHtgtMacVtttaBHtgagVttMaataattatgtt +cttagtttgtgcDtSatttgBtcaacHattaaBagVWcgcaSYttMgcttacYKtVtatc +aYaKctgBatgcgggcYcaaaaacgNtctagKBtattatctttKtaVttatagtaYtRag +NtaYataaVtgaatatcHgcaaRataHtacacatgtaNtgtcgYatWMatttgaactacR +ctaWtWtatacaatctBatatgYtaagtatgtgtatSttactVatcttYtaBcKgRaSgg +RaaaaatgcagtaaaWgtaRgcgataatcBaataccgtatttttccatcNHtatWYgatH +SaaaDHttgctgtccHtggggcctaataatttttctatattYWtcattBtgBRcVttaVM +RSgctaatMagtYtttaaaaatBRtcBttcaaVtaacagctccSaaSttKNtHtKYcagc +agaaaccccRtttttaaDcDtaStatccaagcgctHtatcttaDRYgatDHtWcaaaBcW +gKWHttHataagHacgMNKttMKHccaYcatMVaacgttaKgYcaVaaBtacgcaacttt +MctaaHaatgtBatgagaSatgtatgSRgHgWaVWgataaatatttccKagVgataattW +aHNcYggaaatgctHtKtaDtctaaagtMaatVDVactWtSaaWaaMtaHtaSKtcBRaN +cttStggtBttacNagcatagRgtKtgcgaacaacBcgKaatgataagatgaaaattgta +ctgcgggtccHHWHaaNacaBttNKtKtcaaBatatgctaHNgtKcDWgtttatNgVDHg +accaacWctKaaggHttgaRgYaatHcaBacaatgagcaaattactgtaVaaYaDtagat +tgagNKggtggtgKtWKaatacagDRtatRaMRtgattDggtcaaYRtatttNtagaDtc +acaaSDctDtataatcgtactaHttatacaatYaacaaHttHatHtgcgatRRttNgcat +SVtacWWgaaggagtatVMaVaaattScDDKNcaYBYaDatHgtctatBagcaacaagaa +tgagaaRcataaKNaRtBDatcaaacgcattttttaaBtcSgtacaRggatgtMNaattg +gatatWtgagtattaaaVctgcaYMtatgatttttYgaHtgtcttaagWBttHttgtctt +attDtcgtatWtataataSgctaHagcDVcNtaatcaagtaBDaWaDgtttagYctaNcc +DtaKtaHcttaataacccaRKtacaVaatNgcWRaMgaattatgaBaaagattVYaHMDc +aDHtcRcgYtcttaaaWaaaVKgatacRtttRRKYgaatacaWVacVcRtatMacaBtac +tggMataaattttHggNagSctacHgtBagcgtcgtgattNtttgatSaaggMttctttc +ttNtYNagBtaaacaaatttMgaccttacataattgYtcgacBtVMctgStgMDtagtaR +ctHtatgttcatatVRNWataDKatWcgaaaaagttaaaagcacgHNacgtaatctttMR +tgacttttDacctataaacgaaatatgattagaactccSYtaBctttaataacWgaaaYa +tagatgWttcatKtNgatttttcaagHtaYgaaRaDaagtaggagcttatVtagtctttc +attaaaatcgKtattaRttacagVaDatgcatVgattgggtctttHVtagKaaRBtaHta +aggccccaaaaKatggtttaMWgtBtaaacttcactttKHtcgatctccctaYaBacMgt +cttBaBaNgcgaaacaatctagtHccHtKttcRtRVttccVctttcatacYagMVtMcag +aMaaacaataBctgYtaatRaaagattaaccatVRatHtaRagcgcaBcgDttStttttc +VtttaDtKgcaaWaaaaatSccMcVatgtKgtaKgcgatatgtagtSaaaDttatacaaa +catYaRRcVRHctKtcgacKttaaVctaDaatgttMggRcWaacttttHaDaKaDaBctg +taggcgtttaHBccatccattcNHtDaYtaataMttacggctNVaacDattgatatttta +cVttSaattacaaRtataNDgacVtgaacataVRttttaDtcaaacataYDBtttaatBa +DtttYDaDaMccMttNBttatatgagaaMgaNtattHccNataattcaHagtgaaggDga +tgtatatatgYatgaStcataaBStWacgtcccataRMaaDattggttaaattcMKtctM +acaBSactcggaatDDgatDgcWctaacaccgggaVcacWKVacggtaNatatacctMta +tgatagtgcaKagggVaDtgtaacttggagtcKatatcgMcttRaMagcattaBRaStct +YSggaHYtacaactMBaagDcaBDRaaacMYacaHaattagcattaaaHgcgctaaggSc +cKtgaaKtNaBtatDDcKBSaVtgatVYaagVtctSgMctacgttaacWaaattctSgtD +actaaStaaattgcagBBRVctaatatacctNttMcRggctttMttagacRaHcaBaacV +KgaataHttttMgYgattcYaNRgttMgcVaaacaVVcDHaatttgKtMYgtatBtVVct +WgVtatHtacaaHttcacgatagcagtaaNattBatatatttcVgaDagcggttMaagtc +ScHagaaatgcYNggcgtttttMtStggtRatctacttaaatVVtBacttHNttttaRca +aatcacagHgagagtMgatcSWaNRacagDtatactaaDKaSRtgattctccatSaaRtt +aaYctacacNtaRtaactggatgaccYtacactttaattaattgattYgttcagDtNKtt +agDttaaaaaaaBtttaaNaYWKMBaaaacVcBMtatWtgBatatgaacVtattMtYatM +NYDKNcKgDttDaVtaaaatgggatttctgtaaatWtctcWgtVVagtcgRgacttcccc +taDcacagcRcagagtgtWSatgtacatgttaaSttgtaaHcgatgggMagtgaacttat +RtttaVcaccaWaMgtactaatSSaHtcMgaaYtatcgaaggYgggcgtgaNDtgttMNg +aNDMtaattcgVttttaacatgVatgtWVMatatcaKgaaattcaBcctccWcttgaaWH +tWgHtcgNWgaRgctcBgSgaattgcaaHtgattgtgNagtDttHHgBttaaWcaaWagc +aSaHHtaaaVctRaaMagtaDaatHtDMtcVaWMtagSagcttHSattaacaaagtRacM +tRtctgttagcMtcaBatVKtKtKacgagaSNatSactgtatatcBctgagVtYactgta +aattaaaggcYgDHgtaacatSRDatMMccHatKgttaacgactKtgKagtcttcaaHRV +tccttKgtSataatttacaactggatDNgaacttcaRtVaagDcaWatcBctctHYatHa +DaaatttagYatSatccaWtttagaaatVaacBatHcatcgtacaatatcgcNYRcaata +YaRaYtgattVttgaatgaVaactcRcaNStgtgtattMtgaggtNttBaDRcgaaaagc +tNgBcWaWgtSaDcVtgVaatMKBtttcgtttctaaHctaaagYactgMtatBDtcStga +ccgtSDattYaataHctgggaYYttcggttaWaatctggtRagWMaDagtaacBccacta +cgHWMKaatgatWatcctgHcaBaSctVtcMtgtDttacctaVgatYcWaDRaaaaRtag +atcgaMagtggaRaWctctgMgcWttaagKBRtaaDaaWtctgtaagYMttactaHtaat +cttcataacggcacBtSgcgttNHtgtHccatgttttaaagtatcgaKtMttVcataYBB +aKtaMVaVgtattNDSataHcagtWMtaggtaSaaKgttgBtVtttgttatcatKcgHac +acRtctHatNVagSBgatgHtgaRaSgttRcctaacaaattDNttgacctaaYtBgaaaa +tagttattactcttttgatgtNNtVtgtatMgtcttRttcatttgatgacacttcHSaaa +ccaWWDtWagtaRDDVNacVaRatgttBccttaatHtgtaaacStcVNtcacaSRttcYa +gacagaMMttttgMcNttBcgWBtactgVtaRttctccaaYHBtaaagaBattaYacgat +ttacatctgtaaMKaRYtttttactaaVatWgctBtttDVttctggcDaHaggDaagtcg +aWcaagtagtWttHtgKtVataStccaMcWcaagataagatcactctHatgtcYgaKcat +cagatactaagNSStHcctRRNtattgtccttagttagMVgtatagactaactctVcaat +MctgtttgtgttgccttatWgtaBVtttctggMcaaKgDWtcgtaaYStgSactatttHg +atctgKagtagBtVacRaagRtMctatgggcaaaKaaaatacttcHctaRtgtDcttDat +taggaaatttcYHaRaaBttaatggcacKtgctHVcaDcaaaVDaaaVcgMttgtNagcg +taDWgtcgttaatDgKgagcSatatcSHtagtagttggtgtHaWtaHKtatagctgtVga +ttaBVaatgaataagtaatVatSttaHctttKtttgtagttaccttaatcgtagtcctgB +cgactatttVcMacHaaaggaatgDatggKtaHtgStatattaaSagctWcctccRtata +BaDYcgttgcNaagaggatRaaaYtaWgNtSMcaatttactaacatttaaWttHtatBat +tgtcgacaatNgattgcNgtMaaaKaBDattHacttggtRtttaYaacgVactBtaBaKt +gBttatgVttgtVttcaatcWcNctDBaaBgaDHacBttattNtgtDtatttVSaaacag +gatgcRatSgtaSaNtgBatagttcHBgcBBaaattaHgtDattatDaKaatBaaYaaMa +ataaataKtttYtagtBgMatNcatgtttgaNagtgttgtgKaNaSagtttgaSMaYBca +aaacDStagttVacaaaaactaaWttBaagtctgtgcgtMgtaattctcctacctcaNtt +taaccaaaaVtBcacataacaccccBcWMtatVtggaatgaWtcaaWaaaaaaaaWtDta +atatRcctDWtcctaccMtVVatKttaWaaKaaatataaagScHBagaggBaSMtaWaVt +atattactSaaaKNaactatNatccttgaYctattcaaaVgatttYHcRagattttaSat +aggttattcVtaaagaKgtattattKtRttNcggcRgtgtgtWYtaacHgKatKgatYta +cYagDtWcHBDctctgRaYKaYagcactKcacSaRtBttttBHKcMtNtcBatttatttt +tgSatVgaaagaWtcDtagDatatgMacaacRgatatatgtttgtKtNRaatatNatgYc +aHtgHataacKtgagtagtaacYttaNccaaatHcacaacaVDtagtaYtccagcattNt +acKtBtactaaagaBatVtKaaHBctgStgtBgtatgaSNtgDataaccctgtagcaBgt +gatcttaDataStgaMaccaSBBgWagtacKcgattgaDgNNaaaacacagtSatBacKD +gcgtataBKcatacactaSaatYtYcDaactHttcatRtttaatcaattataRtttgtaa +gMcgNttcatcBtYBagtNWNMtSHcattcRctttttRWgaKacKttgggagBcgttcgc +MaWHtaatactgtctctatttataVgtttaBScttttaBMaNaatMacactYtBMggtHa +cMagtaRtctgcatttaHtcaaaatttgagKtgNtactBacaHtcgtatttctMaSRagc +agttaatgtNtaaattgagagWcKtaNttagVtacgatttgaatttcgRtgtWcVatcgt +taaDVctgtttBWgaccagaaagtcSgtVtatagaBccttttcctaaattgHtatcggRa +ttttcaaggcYSKaagWaWtRactaaaacccBatMtttBaatYtaagaactSttcgaaSc +aatagtattgaccaagtgttttctaacatgtttNVaatcaaagagaaaNattaaRtttta +VaaaccgcaggNMtatattVctcaagaggaacgBgtttaacaagttcKcYaatatactaa +ccBaaaSggttcNtattctagttRtBacgScVctcaatttaatYtaaaaaaatgSaatga +tagaMBRatgRcMcgttgaWHtcaVYgaatYtaatctttYttatRaWtctgBtDcgatNa +tcKaBaDgatgtaNatWKctccgatattaacattNaaacDatgBgttctgtDtaaaMggt +gaBaSHataacgccSctaBtttaRBtcNHcDatcDcctagagtcRtaBgWttDRVHagat +tYatgtatcWtaHtttYcattWtaaagtctNgtStggRNcgcggagSSaaagaaaatYcH +DtcgctttaatgYcKBVSgtattRaYBaDaaatBgtatgaHtaaRaRgcaSWNtagatHa +acttNctBtcaccatctMcatattccaSatttgcgaDagDgtatYtaaaVDtaagtttWV +aagtagYatRttaagDcNgacKBcScagHtattatcDaDactaaaaaYgHttBcgaDttg +gataaaKSRcBMaBcgaBSttcWtgNBatRaccgattcatttataacggHVtaattcaca +agagVttaaRaatVVRKcgWtVgacctgDgYaaHaWtctttcacMagggatVgactagMa +aataKaaNWagKatagNaaWtaaaatttgaattttatttgctaaVgaHatBatcaaBWcB +gttcMatcgBaaNgttcgSNaggSaRtttgHtRtattaNttcDcatSaVttttcgaaaaa +ttgHatctaRaggSaNatMDaaatDcacgattttagaHgHaWtYgattaatHNSttatMS +gggNtcKtYatRggtttgtMWVtttaYtagcagBagHaYagttatatggtBacYcattaR +SataBatMtttaaatctHcaaaSaaaagttNSaaWcWRccRtKaagtBWtcaaattSttM +tattggaaaccttaacgttBtWatttatatWcDaatagattcctScacctaagggRaaYt +aNaatgVtBcttaaBaacaMVaaattatStYgRcctgtactatcMcVKatttcgSgatRH +MaaaHtagtaaHtVgcaaataatatcgKKtgccaatBNgaaWcVttgagttaKatagttc +aggKDatDtattgaKaVcaKtaataDataataHSaHcattagttaatRVYcNaHtaRcaa +ggtNHcgtcaaccaBaaagYtHWaaaRcKgaYaaDttgcWYtataRgaatatgtYtgcKt +aNttWacatYHctRaDtYtattcBttttatcSataYaYgttWaRagcacHMgtttHtYtt +YaatcggtatStttcgtRSattaaDaKMaatatactaNBaWgctacacYtgaYVgtgHta +aaRaaRgHtagtWattataaaSDaaWtgMattatcgaaaagtaYRSaWtSgNtBgagcRY +aMDtactaacttaWgtatctagacaagNtattHggataatYttYatcataDcgHgttBtt +ctttVttgccgaaWtaaaacgKgtatctaaaaaNtccDtaDatBMaMggaatNKtatBaa +atVtccRaHtaSacataHattgtttKVYattcataVaattWtcgtgMttcttKtgtctaa +cVtatctatatBRataactcgKatStatattcatHHRttKtccaacgtgggtgRgtgaMt +attattggctatcgtgacMtRcBDtcttgtactaatRHttttaagatcgVMDStattatY +BtttDttgtBtNttgRcMtYtgBacHaWaBaatDKctaagtgaaactaatgRaaKgatcc +aagNaaaatattaggWNtaagtatacttttKcgtcggSYtcttgRctataYcttatataa +agtatattaatttataVaacacaDHatctatttttKYVatHRactttaBHccaWagtact +BtcacgaVgcgttRtttttttSVgtSagtBaaattctgaHgactcttgMcattttagVta +agaattHctHtcaDaaNtaacRggWatagttcgtSttgaDatcNgNagctagDgatcNtt +KgttgtaDtctttRaaYStRatDtgMggactSttaDtagSaVtBDttgtDgccatcacaM +attaaaMtNacaVcgSWcVaaDatcaHaatgaattaMtatccVtctBtaattgtWattat +BRcWcaatgNNtactWYtDaKttaaatcactcagtRaaRgatggtKgcgccaaHgaggat +StattYcaNMtcaBttacttatgagDaNtaMgaaWtgtttcttctaHtMNgttatctaWW +atMtBtaaatagDVatgtBYtatcggcttaagacMRtaHScgatatYgRDtcattatSDa +HggaaataNgaWSRRaaaBaatagBattaDctttgHWNttacaataaaaaaatacggttt +gHgVtaHtWMttNtBtctagtMcgKMgHgYtataHaNagWtcaacYattaataYRgtaWK +gaBctataaccgatttaHaNBRaRaMtccggtNgacMtctcatttgcaattcWgMactta +caaDaaNtactWatVtttagccttMaatcagVaagtctVaaDaBtattaattaYtNaYtg +gattaKtaKctYaMtattYgatattataatKtVgDcttatatNBtcgttgtStttttMag +aggttaHYSttcKgtcKtDNtataagttataagSgttatDtRttattgttttSNggRtca +aKMNatgaatattgtBWtaMacctgggYgaSgaagYataagattacgagaatBtggtRcV +HtgYggaDgaYaKagWagctatagacgaaHgtWaNgacttHRatVaWacKYtgRVNgVcS +gRWctacatcKSactctgWYtBggtataagcttNRttVtgRcaWaaatDMatYattaact +ttcgaagRatSctgccttgcRKaccHtttSNVagtagHagBagttagaccaRtataBcca +taatSHatRtcHagacBWatagcaMtacaRtgtgaaBatctKRtScttccaNaatcNgta +atatWtcaMgactctBtWtaaNactHaaaaRctcgcatggctMcaaNtcagaaaaacaca +gtggggWttRttagtaagaVctVMtcgaatcttcMaaaHcaHBttcgattatgtcaDagc +YRtBtYcgacMgtDcagcgaNgttaataatagcagKYYtcgtaBtYctMaRtaRtDagaa +aacacatgYaBttgattattcgaaNttBctSataaMataWRgaHtttccgtDgaYtatgg +tDgHKgMtatttVtMtVagttaRatMattRagataaccctKctMtSttgaHagtcStcta +tttccSagatgttccacgaggYNttHRacgattcDatatDcataaaatBBttatcgaHtN +HaaatatDNaggctgaNcaaggagttBttMgRagVatBcRtaWgatgBtSgaKtcgHttt +gaatcaaDaHttcSBgHcagtVaaSttDcagccgttNBtgttHagYtattctttRWaaVt +SttcatatKaaRaaaNacaVtVctMtSDtDtRHRcgtaatgctcttaaatSacacaatcg +HattcaWcttaaaatHaaatcNctWttaNMcMtaKctVtcctaagYgatgatcYaaaRac +tctaRDaYagtaacgtDgaggaaatctcaaacatcaScttcKttNtaccatNtaNataca +tttHaaDHgcaDatMWaaBttcRggctMaagctVYcacgatcaDttatYtaatcKatWat +caatVYtNagatttgattgaYttttYgacttVtcKaRagaaaHVgDtaMatKYagagttN +atWttaccNtYtcDWgSatgaRgtMatgKtcgacaagWtacttaagtcgKtgatccttNc +ttatagMatHVggtagcgHctatagccctYttggtaattKNaacgaaYatatVctaataM +aaaYtgVtcKaYtaataacagaatHcacVagatYWHttagaaSMaatWtYtgtaaagNaa +acaVgaWtcacNWgataNttcaSagctMDaRttgNactaccgataMaaatgtttattDtc +aagacgctDHYYatggttcaagccNctccttcMctttagacBtaaWtaWVHggaaaaNat +ttaDtDtgctaaHHtMtatNtMtagtcatttgcaaaRatacagRHtatDNtgtDgaatVg +tVNtcaaatYBMaaaagcaKgtgatgatMgWWMaHttttMgMagatDtataaattaacca +actMtacataaattgRataatacgBtKtaataattRgtatDagDtcRDacctatRcagag +cSHatNtcaScNtttggacNtaaggaccgtgKNttgttNcttgaaRgYgRtNtcagttBc +ttttcHtKtgcttYaaNgYagtaaatgaatggWaMattBHtatctatSgtcYtgcHtaat +tHgaaMtHcagaaSatggtatgccaHBtYtcNattWtgtNgctttaggtttgtWatNtgH +tgcDttactttttttgcNtactKtWRaVcttcatagtgSNKaNccgaataaBttataata +YtSagctttaaatSttggctaaKSaatRccgWHgagDttaaatcatgagMtcgagtVtaD +ggaBtatttgDacataaacgtagYRagBWtgDStKDgatgaagttcattatttaKWcata +aatWRgatataRgttRacaaNKttNtKagaaYaStaactScattattaacgatttaaatg +DtaattagatHgaYataaactatggggatVHtgccgtNgatNYcaStRtagaccacWcaM +tatRagHgVactYtWHtcttcatgatWgagaKggagtatgaWtDtVtNaNtcgYYgtaaa +ctttaDtBactagtaDctatagtaatatttatatataacgHaaaRagKattSagttYtSt +>THREE Homo sapiens frequency +agagagacgatgaaaattaatcgtcaatacgctggcgaacactgagggggacccaatgct +cttctcggtctaaaaaggaatgtgtcagaaattggtcagttcaaaagtagaccggatctt +tgcggagaacaattcacggaacgtagcgttgggaaatatcctttctaccacacatcggat +tttcgccctctcccattatttattgtgttctcacatagaattattgtttagacatccctc +gttgtatggagagttgcccgagcgtaaaggcataatccatataccgccgggtgagtgacc +tgaaattgtttttagttgggatttcgctatggattagcttacacgaagagattctaatgg +tactataggataattataatgctgcgtggcgcagtacaccgttacaaacgtcgttcgcat +atgtggctaacacggtgaaaatacctacatcgtatttgcaatttcggtcgtttcatagag +cgcattgaattactcaaaaattatatatgttgattatttgattagactgcgtggaaagaa +ggggtactcaagccatttgtaaaagctgcatctcgcttaagtttgagagcttacattagt +ctatttcagtcttctaggaaatgtctgtgtgagtggttgtcgtccataggtcactggcat +atgcgattcatgacatgctaaactaagaaagtagattactattaccggcatgcctaatgc +gattgcactgctatgaaggtgcggacgtcgcgcccatgtagccctgataataccaatact +tacatttggtcagcaattctgacattatacctagcacccataaatttactcagacttgag +gacaggctcttggagtcgatcttctgtttgtatgcatgtgatcatatagatgaataagcg +atgcgactagttagggcatagtatagatctgtgtatacagttcagctgaacgtccgcgag +tggaagtacagctgagatctatcctaaaatgcaaccatatcgttcacacatgatatgaac +ccagggggaaacattgagttcagttaaattggcagcgaatcccccaagaagaaggcggag +tgacgttgaacgggcttatggtttttcagtacttcctccgtataagttgagcgaaatgta +aacagaataatcgttgtgttaacaacattaaaatcgcggaatatgatgagaatacacagt +gtgagcatttcacttgtaaaatatctttggtagaacttactttgctttaaatatgttaaa +ccgatctaataatctacaaaacggtagattttgcctagcacattgcgtccttctctattc +agatagaggcaatactcagaaggttttatccaaagcactgtgttgactaacctaagtttt +agtctaataatcatgattgattataggtgccgtggactacatgactcgtccacaaataat +acttagcagatcagcaattggccaagcacccgacttttatttaatggttgtgcaatagtc +cagattcgtattcgggactctttcaaataatagtttcctggcatctaagtaagaaaagct +cataaggaagcgatattatgacacgctcttccgccgctgttttgaaacttgagtattgct +cgtccgaaattgagggtcacttcaaaatttactgagaagacgaagatcgactaaagttaa +aatgctagtccacagttggtcaagttgaattcatccacgagttatatagctattttaatt +tatagtcgagtgtacaaaaaacatccacaataagatttatcttagaataacaacccccgt +atcatcgaaatcctccgttatggcctgactcctcgagcttatagcatttgtgctggcgct +cttgccaggaacttgctcgcgaggtggtgacgagtgagatgatcagtttcattatgatga +tacgattttatcgcgactagttaatcatcatagcaagtaaaatttgaattatgtcattat +catgctccattaacaggttatttaattgatactgacgaaattttttcacaatgggttttc +tagaatttaatatcagtaattgaagccttcataggggtcctactagtatcctacacgacg +caggtccgcagtatcctggagggacgtgttactgattaaaagggtcaaaggaatgaaggc +tcacaatgttacctgcttcaccatagtgagccgatgagttttacattagtactaaatccc +aaatcatactttacgatgaggcttgctagcgctaaagagaatacatacaccaccacatag +aattgttagcgatgatatcaaatagactcctggaagtgtcagggggaaactgttcaatat +ttcgtccacaggactgaccaggcatggaaaagactgacgttggaaactataccatctcac +gcccgacgcttcactaattgatgatccaaaaaatatagcccggattcctgattagcaaag +ggttcacagagaaagatattatcgacgtatatcccaaaaaacagacgtaatgtgcatctt +cgaatcgggatgaatacttgtatcataaaaatgtgacctctagtatacaggttaatgtta +gtgatacacaatactcgtgggccatgggttctcaaataaaatgtaatattgcgtcgatca +ctcacccacgtatttggtctaattatgttttatttagtgacaatccaatagataaccggt +cctattaagggctatatttttagcgaccacgcgtttaaacaaaggattgtatgtagatgg +taccagtttaattgccagtgggcaatcctaagcaaaatgagattctatcctaaagtttgg +gcttgatataagatttcggatgtatgggttttataatcgttggagagctcaatcatgagc +taatacatggatttcgctacctcaccgagagaccttgcatgaagaattctaaccaaaagt +ttaataggccggattggattgagttaattaagaccttgttcagtcatagtaaaaaccctt +aaattttaccgattgacaaagtgagcagtcgcaataccctatgcgaaacgcctcgatagt +gactaggtatacaaggtttttgagttcctttgaaatagttaactaatttaaaattaatta +acgacatggaaatcacagaacctaatgctttgtaggagttatttatgctgtttactgcct +ctacaaccctaataaagcagtcctaagaatgaaacgcatcttttagttcagaaagtggta +tccagggtggtcaatttaataaattcaacatcgggtctcaggatattcggtcatataatt +tattaagggctcttcgagtcttactctgagtgaaattggaaacagtcatccttttcgttg +tgaggcatcttacaccgctatcgatatacaatgcattccaccgcggtgtcccgtacacaa +ggaaacttgttaccttggggatataagaaaactcacacgtctcattattaaactgagtac +aatttttgcacgagaaagtaatgcaatacaatatgatgaaagccagctaatgaaaaggga +tggaacgcacctcggatctgttgcactggattaaaatccgattatttttaaaaatattca +gtgctagagcatatcaggtctacttttttatctggtatgtaaagcccacggagcgatagt +gagatccttacgactcaacgaaaagttataacataactcccgttagccaaagcccaatcc +cgattactgccctaccctaacgtctgccatctaaatatcgaacttgttatgatcaatgtg +actacctcccaccctttccccttcatttgttccactggggataagctagcgttttcagaa +tcaatgcaataagaatagccaattgtctcacttcatcagagctcttggcaattccaggcg +ctacgtggttctggaatatattcatttttcaaatagtaatacgtttagtgttgctattgt +ctacacgtttggatattacgttatgtgagcggacatcaatagttgtctaactctttagta +agccagagatagcactcttagcgaatggataccatcttccataagtttagttaatagtcc +gaaacaactgcttcgagcatatttgaacctccttgtaggcaaatagcctcttcaaagcaa +tcttactaatagatagagtttgttttaagggactactagaaatgggacaatcttaatagt +atgacctaaactgacatttaaagatatatccaggtggcaagcataaagatcattgcgcca +cctccaccgtgggattacttatcagtcgatatcctatatgctaagtttgcgacggcagaa +tacaaactaagctgagttgatgctaaccttacctatgataccccattggaccggttaaca +gccctacttattccaaataaaagaacttttatgctgtagaagctattatagtgatgcctg +gtaacttcagtatattaaaatgacacacatacgccatatagagctcctggaactttgaat +aatgagcgaacttcgaagttgaagagcaagaaaccatatgtcacggttgcctaaagcccg +gtaaccagacatgtgctatcattgatcattatcgaggttttcataaccttgacccattat +cggctgtgcgcggacaagtacttaaatcactagtttcttcacctgcttatcggtaagaaa +taaggttggcaaagaatcgcataagacggacgtagagccgcagcgttgtgcgagtccagg +tgcatgcgcagcaataggattttaaattttgttccatttttaatttagccgtaaggatgt +ccgtaaatgattgaaaattggattcaatctttgggcctatgctactggaacctgatcgac +aaaatttcaaacatacgttaactccgaaagaccgtatttttgcggctagaatagtcagtc +gcttggagccatataccttaccacttaaacgacgtgctcctgtagttgaaatataaacag +aacacaaagactaccgatcatatcaactgaagatctttgtaactttgaggcgaagcaccc +tcttcgagacaactaagagtaaagtaccgggcgccgcaaggagtcgattgggaccctaaa +tcttgacgaattgctaagaggctcagagctaccactgtaatttctctagagcccataata +aatgaacgatacatccgtaggtagcacctaagggattataatggaagccaaatgcagtta +ataatattatatactggcgtacacgattcgacggatctctcacatagtgattcacgaccc +ccccctttgattgacacagcgtcagcattttgcaagaacgatcttctgcatagggtgcgc +caccgtaaggatgacgtcgaagctacaactgggtataatttaccatgcttccctgatgct +gagtgcaatacactaagaatgagtttttaccccatatcaccagtatttgttctgttattg +cgaagaaatggctatgctgagttggcgactaaagtcacccatcctttttattaggtaacc +ccctcccttaaactaactgatttgctggagctgccctgcatacatatactttatcattta +tggacgtccgtgacgcttattatccaccatagtcgatatgctacacggattcattaatgg +atcgtaggagtttaagttatatttactaagatcggtctcggctactatcccgccttaccc +ggcgctatttacggccatttttaatatattgacggtaattattcctatggtttcgaccgc +acgtccttggacaagaaagaatggcaaaaaaaatgtaaaagaaaaaaaatattgagtccc +taccatcatataaaaaatatgtgatgagtaacttgacgaaatgttagtggttattaaaga +ctatctattacaccttttgttttctgtcgtagtatattaaagtctagaagccttacagga +aaatcagggttatacagccgatactccgcagcatgaatcatcgaggaggtgtcctaccat +cgcgccttgtaatcttgtctgtgtatactgtatttagaccttttatacaaagtaaatatc +tcggctttatgtgattgggaggggcctactcaaacatgatgacttgacctaataatcact +gtgcgggcgtcttatgactagctattccttgaaatccaccaccaaatggttaatatgtaa +aaactttgacgatgaaacaaggtgaatgtgtagttactttgtgtaattagctgcgtcgag +cattgcttgtaaaaccgtcaatcgcacacgttacttccataaaatttctacgaatacacc +cttcttaaaaaaaacgtaggaattcacgagtttaacaaacgataactgtataaagtggaa +gtccgaagaaagcagatgcccgaactactcgaagatgtttcgttttcttaaccatagggg +cttcttaatggcccactacgcacattttgttcaagcccgagagggacatccccattacgg +gagtattactaaaactgttccgtaatacgttcagcaagggatgaaaaaggccactgctca +agttattgacgtgggagtattacatcggaagcctgaatcccacactatgatggtctgtac +aggcctagggactgcgtctagacggtattaccggcttctaatcatacgatcgtgagtctt +aacgggaagtaaggctcacacctaccccaaaccatttatctatgtaagtataaaattgtg +cgtaagtgttcaaagtggacaataaagacgtggcaaaaacccccgcacataagccgcttt +agatttcacaaataccaatgcggttaaaaacatccttgagtcgtacatacaccatactcg +cgttaaacggatataacagaagataataaatccggatgtggagtcggtgtaactatagaa +agccaagtgaaataatgcttaccagtcatttagctatacggctttcatttcatgtcaaga +gggtggagtttgacctgtacagttgatatatcaccgatacttagaactcacctaaagcta +aaattgctcgcagcgtgtaatccgcatattacaaacaatagatgggattcattatacata +agacacgatgatctgctttttcaggttgcgagatgttgcctatcgtcaatcgagtcctgc +cttacaccacttaaacaaaagtattgacagggaacctattttcgaggtattatatagtcc +agcttgaatatcaatttgacagttaacctagtgaaaatcagtaagaggaaatacgccaca +ttctccagtgaaattctacgggttatcgtctagtccaactatcaattataactcacgaga +tataagtaaattctcgtacttggcctgatttttattatactttggatccttagtaaacag +gaagggagaaaccttcaacgaaaaacactggattttgttttactctcaaagctcttatat +gacggaaataccctgtcaagtcttaactttattactagactaatgaaatgggcttggggt +ggccagaatcatagtacaatttagcggatacactattcggactttcctatcggctgtctg +gttggataagtatggggactaataggctagacatacctatacttaaactatacaggcgtc +atctatctctgcaactttggagttccctgatgttctcccgccctttgggttcacatcttc +tataccgacacccctaataacgattagtttgtgggttagagtaaattaatacggttaata +ttaatgtatcgttgaaaagctggtgtcgccaataaggtaaccggctaggcagagtatatg +tcacgaagtataactaccctaatgataagctgtaggaataaaattaatgctgtctctaag +cgaagagatatttccgactctgttttaatgacgaatctcattacttctgacttgcaaatg +ttcaatatggcacggtttcacggcacctttgtgacgcatataatgaacttagaagattat +aacgacggaactttatatgataatccgttacgattaaagaatctgttaaatatcataatg +gcattcagttctagaccgtgcatcatggtaaacttactttctctgcatggcgacatacat +ttcgctattcaaattcgcgtgtggttacacccactcgcacctttggaatattaagagaag +atgatcagaaaatccattcgctcaatttttctgacgtacgtctaatttatcctaggagac +aaatcgttttatgtctctcacatttttgaagaaaggttcgagagacaatactcaggtcct +gaactgctagaagatactcggtggagcgtggcaacaatgaaaaactcgtgacataaatga +atgatacttttccaagttcagttaagtgaatatgtttaacatacccggcttttcgatctt +aagctgacgctggacgtgcgagtaatgtcagtctcttacatacactagtgactccaagtt +tcgtcaaaaacgccccctcccttctcgagcccactcacgctatgtattgacgcgaacttg +ttcgggatcagacttttcaggagttcggtcgcgtgtccctatgtgctaatatataagtta +gatcgcattagatgctaatctgaatacttatagacgaccttcaacgagaacgggtaccac +cttgaggctagagttaggtgtgaaacgacaggtagggacatataaaatttgagtgcggct +ttagttaagggtttaattacctactcaaacatcacgctcgcgcccttcgtacgtaatcga +ccatctagaggctaaggggactgtactaggtagtgattaatgatatcctagacgcacgtg +ccttagatcttcagactctgatggtccgcgatcaccgtaattgtagtcctccaactcgat +cactttgttggcgtcaaagaaattacgatatctaaatacttataatacaataaccaagga +tgagaatgactcatcgcgttggagttatattgcttgaagttctatggaatgaaagcacgt +tatctgccgtcccaatatctccagtgagctaattcattggacggtccactttgatcaatc +cccgaggagatgttcggacactttagtctgtaacacttagcgttgagaccacgaacaatt +gattactcagtcttgaaggtgttttccaaagttcattttaaataagactacgataggcct +ttcctattgatataaactacccggctctgttgttcgtgtgagtcgtacttctctgtgttt +ttctgattatagcaagattcgattcttagtgtaaacagcgatttttatttgacccgtcaa +tgagaagcgcataggatctaagcaaaattatcaagttgtgccacaaggtaagatctttcc +agttattgcaggtaggatgtatcccacgttgatagtatgaggtctgacgtcaactgtcta +ggagagttgaccgcgtgcgggtacaccggatttgcatcgatgttgagaacgcagaactcc +cactgtcgtggcggcgttcctgatatttagcaagaggcgttgataaagccctcatcatct +agatctcgacctcatctgccctcttgctccatcattttctacacagactactttcctatc +tacgttagtataattgctttctatcttagtatcatttagagcttctccgtcaacaggttc +gtgctattaaagttagtacgaaagggacaacttgtagcaacgcatttaatcggttttcga +ctacttcgcacaaaatcagataaagaagtttgtcattctattagacattgaattgcgcaa +ttgacttgtaccacttatgatcgaacactgaatcaagactgtgattaactaaaatagaca +agccactatatcaactaataaaaacgcccctggtggtcgaacatagttgactacaggata +attaattggactggagccattacattctctacaatcgtatcacttcccaagtagacaact +ttgaccttgtagtttcatgtacaaaaaaatgctttcgcaggagcacattggtagttcaat +agtttcatgggaacctcttgagccgtcttctgtgggtgtgttcggatagtaggtactgat +aaagtcgtgtcgctttcgatgagagggaattcaccggaaaacaccttggttaacaggata +gtctatgtaaacttcgagacatgtttaagagttaccagcttaatccacggtgctctacta +gtatcatcagctgtcttgcctcgcctagaaatatgcattctatcgttatcctatcaacgg +ttgccgtactgagcagccttattgtggaagagtaatatataaatgtagtcttgtctttac +gaagcagacgtaagtaataatgacttggaataccaaaactaaacatagtggattatcata +ctcaagaactctccagataaataacagtttttacgatacgtcaccaatgagcttaaagat +taggatcctcaaaactgatacaaacgctaattcatttgttattggatccagtatcagtta +aactgaatggagtgaagattgtagaatgttgttctggcctcgcatggggtctaggtgata +tacaatttctcatacttacacggtagtggaaatctgattctagcttcgtagctgactata +ctcaaggaaccactgctcaaggtaggagactagttccgaccctacagtcaaagtggccga +agcttaaactatagactagttgttaaatgctgatttcaagatatcatctatatacagttt +ggacaattatgtgtgcgaaactaaaattcatgctattcagatggatttcacttatgcctt +agaaacagatattgcccgagctcaatcaacagttttagccggaaacaatcgaagcatagg +gacaatgtatcttttcctaaattgccatgtgcagatttctgagtgtcacgaagcgcataa +tagaatcttgtgttgcctcaactcgttgaaaagtttaaaacaatcgcagcagtctttttg +gggtctactgtgtgtttgcaaaataactgaaagaaacgcttgaacaactctgaagtagct +cgagtactcattaaagtgtaacacattagtgaatatcggccaatgaaccaaacgcttccc +ggtacgctatctctctcatcgggaggcgatgtgcaggttatctacgaaagcatcccttta +cgttgagagtgtcgatgcatgaacctcattgtaacaatagcccagcaaattctcatacgt +gcctcagggtccgggcgtactcctccatggaagggcgcgcatctagtgttataccaactc +gctttttaactactatgctgtagttctacaggcatagtggccagtattttctaacttctc +tggatagatgctctcactcctcatccatcacggcttcagtttacgtcttacttgcttgtt +cagcaacggatggaggcattaagtatcttcactgttccctaaaattgctgttcaatatca +aagtaaggacgatacagggaaagctcaagcacactcattgaatactgccccagttgcaac +ctcacttaatctgacaaaaataatgactactctaagtgttgcggaagcagtctcttccac +gagcttgtctgtatcacttcgtataggcatgtaactcgatagacacgaacaccgagtgag +aaactatattcttgcttccgtgtgtgtgacaccaggtaattgatgcggatataagctgga +gatcactcacgcccacacaaggcgctgctacctctttattccaatgtgtaagaatttgct +aacttcatttctagaccgcagctttgcggtcataatttcacggtacggacccttgggtta +gagacttgataacacacttcgcagtttccaccgcgcacatgttttagtggcttctaacat +agaatttttgttgtgacataaagagtgcgtgggagacttgcccgaccgttaagccataat +caattgaaagccccgtgagtcacatctaattggttgtactgcgcatttagctatccttta +gctgactcgaagagattcgattcctaatataggttaattagatggctgccgcgcgaagta +aaacgtgaaaaacgtagtgcgcagatctgcataactcgcgcttaattacttatgagtagt +tccaagttcgctacgttatgagagagattggaattaagcaaatatgttttatggtgattt +tgggatgagaaggactgctaagtacggctactaaacaaatttctaaaaccgccatctacc +ttatcttggagacatttaagttgtatatgtcactagtctagcttttgtctgtgggacgcg +ttctcggaatgagggaaatgcaagagccgattcatcaaatgcttatctaagaaagtagtg +gactattacaccaagcacgaatgccagggaactgctttcttgctcaggacctcgcgacaa +ggtaccccgcataagtcctagaattacatttggtcagcaatgctgacatttgaccgtgaa +aacataattttaatcagaaggcagctcacccgcttgctctagatcttatctttgtatgaa +tgtcagaatttactgcaatatccgttccgaatagtgagggcttagtatagttctctgtat +acaggtcacatcaaactccccctgtcctagtacagctctgagctttaattaattgcatac +atttccttcaatcatcagatgaaaacaccgcgaatcatgctcttctcgtatagggcaaga +gaagcaacaaacaactagcccgactcacgttcatccgccgtatccttgttcagttcttac +tccgtattaggtcagcgaaatctaatcagaataatcggtcgcgtatcaaaattaaaatcc +cgcttgaggttgacaattaaaacgctgagcagttatcggctattagatagtggggtgaaa +gtaattggctggaattatgttaaaacgtgatattaagctaaaatacgctacttgttgccg +acctaattcagtcattcgatattcagttagagccaagaataacaagcttgtataaattga +acggggtgcactaaacgatgtgttactctaatattcagcttggagtatacctgaaggcga +attcatgtatcggccaataataagacgttgaagatcacaatttggactagcaaaagaagg +tgatttatgcgtggggattgagtccactgtacgagtacggtctctggaaaattataggtt +cagggaatataaggaagtaaagataattaccaagagatttttggtatcgctatgacccag +aggtgttctaacgtctgttttgatccgcagaatttctgcctcaatgcatatttgacggac +ttgaactagagcctctaaagttaaatggcgacgcaactgttcctaaacttcaattattac +tactctttttttcctagggtattgtagaggccagtggacaaaataaatcaaatttaagat +gtttcggacattaacatcccccgtagcatagaaatcatcagttatccaatctctcatcga +gcttttacaatttctgctggcgctatggacagcatatgccgcgagacctccgcaagactc +acttgatcactgtaagtatcttcattagaggttagagcctatagttaagctgctgaccta +gtaaaattggtattttctaattttattgctcaagttaaaggttagtgaagggataatgac +gttatttttgaacaatgggttgtattcaattttatatcacgaatggaacccttcattccc +ggcataatactagacgacacgaacaagctccgatctatcagccaggcacgtgttaaggtt +taattccggcaaaccaatgaagcatcaaaaggtgacctgatgcaacttagggtcacgatg +agtttttcaggactacttattacctattaataagttaacatgagccttcataccccgtaa +gacaatacatactccaccaattagaattctgagccatcttatctttttgtatcatcgaag +ggtatggccgaataggttaattagttactcctaacgtctctacaggcatgcatttgacgc +accttcgaaaatagtcaatctctcgccacacgcgtctagtatgcagcatcaaaaatatag +tccacggtttccggattaccaaacgcggcaaagagaaacattgtatcgacggagataact +taatacagaaggaaggggcatcttcgaatacggatgaataattctatctgtttattctga +catcttgttttcaggttaatcttacgcattcaaatgacgcctgccccatgcgtgcgcaat +tattttctaatattgacgagagcaatctcactccttttgggtctatttatgttttattga +ggcacaagcctatacagaacaggtactattaaggccgtgagtgtgagactcaaaccgtgg +aaacaaaggatgggttgttcttggtacaagttttagtgcatgtgggcaatccttaccaaa +atcagatgctatccttaactttgggctgcatttaagatggcggttggaggcctgtgagaa +tcctgcgtgtcatctttaatgaccgaattcatccatgtagattcagatcacacactcatt +ccttgatgttgtctaaacaaaagttgttgtggacgcattggagggagttaagtaacaact +tgggatcgcatacttataaaaattatatgttaaactttcacaaacgctgaagtccaaagt +aactagcccaaacgcctcgagagtcactaggtattaatggtgtttgagttcctgtgaaat +agtgttcgaaggtaaaatttatgtaccaaatcgaaagaacacttaataaggcttgcttgc +acggaggtatgatgtttactgactctacaaccctaattttccagtacgtacattcattcc +aataggttagttctcaaagtgctatacaggctcctcaattgatgatatgcttcagccgct +ctatggatattagctcattttatttaggaagcccgcttagaggcttactatgagggaaat +gccaaaatgtcatacttttcggtgtgtcccatatgacaccgctttacatagaatttgaat +taaaacgcgctctcccgttcactaccatacttggtaccgtgcgcatattacatatagata +taggatcattttttaaagctgtactaggtttgatcgacaatcttatgctatactatatga +tgtaaccctcataatcaataccgatcgtacgatcctagcataggtggcaagcgattttat +gccgattattgtgttaaatagtctgtgagtgtgattatcagggctacgttggtagagggg +ttgtatagacctcgcacacattgtgacatacttaacaatatacgaaaactgatataataa +atccccttacccaaacaccaatcccgttgaatcaactaccataacgtctcccatataaat +tgcctacttgtttgcataaatctgaatacataacaccattgcaccttcttgtgttccaat +cccgttaagattgccttgtcagatgatatgcaagaacaatagcatttgctagcaattatt +aacagctcttcgaattgcctccacataacgcgggagggtatattttaatttggcaaatac +taagtactgttggcgtcatatgctattaacggttggatattaagttatgtcagccgtaag +caagagtgggcgaaatattttgttacccagtgagagcactcttagagtttggatacaata +ggccatatgttgacttaagaggacgtaactacgccgtacaccattgttcaaccgacttct +tggcaaatagaatcgtattagcaatcttaagaatagagacacgttcgtgttagggtatac +tacaaatccgaaaatcttaagaggatcacctaaactgaaatttatacatatttcaacgtg +gatagatttaacataattcagccacctccaacctgggagtaattttcagtagatttacta +gatgattagtggcccaacgcacttgactatataagatctggggatcctaacctgacctat +gagacaaaattggaaacgttaacagcccttatgtgtacaaagaaaagtaagttgttgctg +ttcaacagatgatagtcatgacgcgtaacttcactatagtaaattgaaacaaatacgcaa +tttagacagaatggtacggtcatgaatgacagtaattcgaagtgctagaccaacttaaaa +taggtaaacgtgcccgaaaccccccttaacagaaagctgctatcatggtgcagtatcgac +gtgttcagaaacttgtaacttttgagcaggtccgagcacatggaagtatatcacgtgttt +ctgaaccggcttatccctaagatatatccgtcgcaaactttcgatttagtcccacgtaga +gcccaagcgttgtgcgactccacgtgcatgcccagaaatacgagtttaaatttggttaca +tggttaattttgaccgaagcatcgcactttatgattgataattggattcaatatgtcgcc +ctatgcgaatgcaacatgatccacaatttggctataagacgtttaatccgtatcacactt +tgtttgcggctagtatagtaacgcccgtgcaccaagagtcagtaacaattataagtactc +cgcaggtacttcaaatataaaaactaatcaaacacgacccatatgatcatctgaagatat +ttggaactttctcgacaaccaccctcgtactcaatacttacactaatcgacaggcacacg +caacgtgtacagtcgcaccatattgagtcaagatttgcttagtggcgatgagcgtacacg +cttatttctctagtcacaattagttatctacgagacatcacgagggagcaaataagcgat +gttatggctacacataggcacgtatgaatatgatataagccagttaaacagtcgaaccat +cgagcaaattctcatgcaccaacccacacgttgaggcacaaagagtaagctgtttgaatg +taacttcttctgctgagcgggccccaacgtaaggatcaactagaagagaaaactcggtat +tagtttaaatgcgtcacggagcatgagtgcatttcactaagaatgtctgtgtaaccaata +taacatctatttgttatctgattgcctacttatggctttgcggtcgtggcgactaatgtc +tccaatccttttgaggtcggtaccaactccctttaaattacgctgtgcaggctcatgcac +tgcatacatatacggtagcaggtagggacctcacgcacccttattataatcaatagtagt +tatcagtcaacgaggcaggaatgctgaggtcgaggtgttggtatattttctatgtgccgt +ctaggcgactatcacgcattaccaggcgagatttaagccaattttgaatatagtcaacgt +aatttttactatgggttccaccgaaacgccttgcacaactaagaatcccataaaatatcg +atatcaaataaaagattgtgtcaataccttcatatatattttttcggttgactaacgtga +actaaggttaggggttttgtatgtctatataggaaacagtttcttttctgtcctacttta +gtaaagtcttcaagccttactccaaaatcacggtgattaagccgttactcagcagcatga +ttctgcctgctcgggtcctaaaatccagccttgtaagagtcgctgtgtattagctaggga +gacctttgttaaaaaggatatatcgcggcgggatgtgagtgcgtggcgcatactcaatct +tcagctcgtgtcattataatatctctcccccacgcttttcactagatatgccgtgtaagc +aaacaccttatgcttaatttcgaaaatattggtacttgaaaaaagctgtaggggtactta +atgtctggtaggagatcaggagagaattgagtgtaaaaccgtaaagccctcacctgactt +catgtaaatggcttagaagactccatgatttaataaatactacgaaggaaagactggatc +taaagataactctagtaaggccaactcccttcaatgctgttgccagttataatccaagag +ctgtccttttctgaaccatagcggcttctgaagcgaactagaagcaaagttggttctagc +cagacagccacataccctgtacgggtgtattactaaaactggtccggtattagttcacca +agggaggaattaggcaaaggatctaggtatgcaagtcggagtattacatccctaccctga +atccatcaataggttcctctgtactggccttcgcaatgagtattcaaggttgtacagccg +tataataataagatagtgactatgaacgggaagtaacccgctcaccttccccaaaacatt +gttatatctaagtattaaagtctgccgtagtgttaatactcgaaaataaacaactggcaa +attacaccgcacttaagccgcttttgatttatatttttccaatgcgcttttaaaaataat +tcagtcctacatactaattaagacccttaaacggagatatcacaagttaagttttaacca +tctcgactaggtggaactatagatacccaactcaatttatcattacctgtaatgttccta +gaaggattgcatttcatgtcaagacggtggagtttcacagcgaaacttcagtgtgaacag +attctgagaaatcacctaaacctattagtcagagcacccggttagaaccagttgtcaaaa +aatagagcggttgcatgagacagaagtaacgatgagatccgttgtaacgttgagacatct +ggcctatcgtcaatacagtcctcccttaaaaatatttttaaatactaggcaaacccaaca +taggttagtcctatgtgatacgccacatggtatatcattttgtaacgttacctagggata +atcaggaagtggaattacgcaaaagtagacagtgaaatgcttagggttatagtctagtcc +aaagataaaggataaagcacgtcagagaactatattagccgaatgggaatcattgttagg +agactgtggatcatgtctaaaaagcaacgcagaaacagtcatcgaaaaaatctcgttttt +gtttgaatctaaaagagctttgatgaccgatagtacctgtatactagttactgtattacg +tgtctaatgatttcggattggggtccccagaatcagacgtcattgtagacgattcaagtt +taccaatttaatttcccagctctccttggagaactatcgccaataattgcagtcactttc +cttttctgaaacgataaagccgtcagagttctctgcaacgttggacttacctgaggttct +aacccactttcggttctaatagtagttaacgacacaacgaataacctttactgtggggct +ttcacgatattttttcgcttattattaatggttacgtcataagctggtgtccaaattaag +gttaccggcttcgcagagtagttgtatccaagtataacttccctaatcataagatcgagg +tagaaaattaatgctgtctctaaccgaacagatatgtcccactatgtggtatggacgttg +ctaattacttctgaagggaaattggtcattatggatacgtgtctaccatcaggtcggacg +cagatatggttctgtcttcagttgatccaccgttctttataggataataactgacgatta +aagattatggtaaatagattaagccaattctcttcttgtcagtgaagcatccttaactga +cttgctctgcagcccctcatacatttagctattcaaagtaccggctcgtttcaaactctc +ccacctttggaagaggttgtcaacttgataagtatatcatttacagcattttttcggacg +tacctctaatgtttcattgcagaaaattagttttttctatcgcacattttgcaagtaacg +ttagagacacaattatctgcgaatgaactgctagatctgacgaccgggagcctcgcaaat +atcaaaaaagactgacatatatcaaggagtcgttgacaagtgctggtaagtcaattggtt +tatctgtcccggcgtttcgatcttaagctgaccatgcacggcagagtaatgtcactctcg +ttcttacaagtctgtctccaagggtcggcaaaaaagacccctccattctcgagcccactc +acgatatgtagggacgacaacttgtgcggcttatgaattgtctggactgcgggcgagggt +ccatatctccgaagttagaagggacatacctttagatgataagatcaattcttattgacg +aaattcatccacaacggggaacaacttcaccctagacttacgtctgaaaagacacctagc +gtcttataaaaggtcagtgccccgtttcgtaaggctggaattacctacgcaaacttaaac +ctcgcgcccttccttacgtatcgacaagatagaggctatcgcgaatgtactacggaggca +tgaatcatatactagaaccaagtgcctgtgatattaacaagatgatccgacgcgagcacc +gtaattctaggcataaaactccagcaatttgggggccgaaaacaaatgacgttagctaat +taattatatgacatgatcaaaggaggtcaatcacgcatcgagttcgacgtatattcattg +aacttcgtgcgtttgaaagaaacttttatgaaggcaaaattgatcctgtctcctatttca +tgcgtacctcctagttgataattccccgagcagtggttaggacacttttgtcggtatcaa +gttccggtctcaaaacgtaaaattctgtaatctgtatggatggtctgtgaattagttaat +ttttatgaagtcgtcgagacgcagttcctattgatttattctaaacggagatgtgcttcg +tgggactcggaagtagatctgtgtttatgattattgctactttagatgctgactgttaac +tccgtgttgtttttcaaccgtatatcacaaccgaattggatagaacctatagtttcaagt +tctgccacaaggtatcatatttacagttagtgctggttgcttctttcaaacgtggtgagt +ttgtgctatcacgtcaacggtagagctcagtggaccgagtgcgcgttcaaccctgttcca +gagagggtgtgatagcacatataccacgctcgtcgaggcgttcatgatagtttgcaagag +ccggtgttaaacacatattattattgttatccaactaatcggacctatgcataaagcatt +gtctaaacagaataattgcctatatacggtagttttagtgatttatatcttagtatcagt +tagagcttcgaactcttcaggttcctcatatttaacgttcttcgaaagcgaaaacttcta +caaacgaatgtaagcggttttccaagtagtacctataaatcacagaaagatctgtctcag +tatagttgaaatggtattcagctagtgacgtgtaccaattatcatagttcactcaagcaa +gacgctcattaacgaatatagacaagacactatatcatataataaaaaagaacatggtgc +tcgaacatagttgaattcaccatattgaaggggaatgctgacatgtaattcgctactaga +cgatcaattccctacttgtcaaagttgaactggtacgttcttggaattaaatatgattgc +gctggaccaaattgcgacttcttgagtttcagggcaaacgattgagccggaggatgtccg +tctcttacctttcttgcttatgataaacgacggtccctgtacatcactgggaattctcag +caaaaataattgggtaaatcgagactcgatgtattcggccacaaaggtgttagacgttaa +agattattcaacggggcgataataggatcataaccggtatgcaagcgcattgaaagagcc +atgagatccttatccgataaacgctgcacggtatgtgcagccttattgtcgatcacgaat +ttataaatgtagtctgggctgtaagttgaagacctaagttataatgaagtgcaataccaa +atcgattcatagtggattatcagactcaagatatctcctgataaattacagttgttaaga +tacggataaaatgagatttaagattagcagcctctaatctgtttcaatcccgttggaatg +tggtatgcgatcaaggttaagttaaaatcaagcctgtcttcagtcttgattcttgttctg +ccatcgcatgcggtctacgtgagttaatatgtagcttacgttctagcttgtgctaatctg +agtatagattcgtagaggaatattatcaagcttccacgcctcaacgtacgtgtattggtc +acacaagacactaaaagtggaagtagcgtaaactatagtctagttgttaaatgctcagtt +cttgttatattcgatatactcttggctaatttatgtctgagtatataaaattaatgatat +taacttgcatttcacggatcccttagaaaaagattttgaccgagcgcattataaacggtt +acaccgaatcaatagaagcatacccaatagctttctttgaatttattgcctgcgcaactt +ggctgactctctagatccgaataattctatatggtcgtgacgaaactagttcattactgt +ttaaaatgccaacatgtcttttgggccgataatggctctttgcaaaattactcaatgata +cgattgatcaaagcggtagttgctagtggtagcatgtaagtctatcaaatgtctgattat +ccgaaaatcttccaaaagagtccacgtaccatatctatctcatagcgacgcgaggggaac +cttatctaactatcattccatttaccgggtgactctcgatgcaggatccgattgggataa +attgcccagaaatggctcattcctgactaagggtaaggccgttctcagcaagggaacccc +gcgaatctaggcttataccatctagattgttaactacttgcctgtagttctacagccata +ctggacagttgtttctaaatgatcgggattcatgctagcactcctctgaatgcaccgcgt +aagtttaactattacgtccgtgggcagataaggatggaggctgtatgtatcttaactgtt +acctaatatggctggtaattatcaaagtaaggaccttaatgccatagcgctagcaatcgc +tttgtatactgaccatgtgccaacctctcttaatctgtaaaatataatgtcttagctaac +tgtggacgatcatgtctctgcctagagcttcgctgtatcaattcctatagccagcgtact +agtgacacaacaacaccgtgtgagaaaagatattagtccttacgtctgtctctctacagc +ttattgatgaggattgaacatggacatatagctccccctcaaaagcagatgctacctctt +tattccattctcgaacatttgccgaacttaatttcgacaaacctgaggtcacgtcttaat +ttatcggtaacgtcacgtccctttgagactggataaatatattaccaggggccaacgagc +aattgttggaggcgcttctataatacaaggtgtcttgtcaaagaaagacggcgtgcgtct +cgtgcaactcacttaaccaatattaatgtgaaacccccctctctcacatcttatgcggtg +tactgccctggtacatttcctgtacaggactccaacagtgtagattcctaagatagctgt +tggagttgcctcacgccagatcgaaaaactgaataaactagtgagctgagctgcagaaat +accgcttaattacttatgactagttcaaagggacctacgtgatgtcagacattgcaagga +agaaattaggtttgtgcgtcattttggctggactagcactccttacttcccctactattc +aaatgtcgtaaacagcatgagacaggatcgtgctgacatttaaggtctattgggaacgag +gctacctttggtcgcgcgctcgcgttctccgaatgaccgaaatgcatgagcacagtatgc +aattgcttatagatctaaggtctggtcgttgaaaccaagcacgtaggcctgggaaatcag +ttcttcctcagcaactacacaaaagcgtccaagcattagtacttgtagtaaatgtccgaa +cctatgcgctcatttgaaagtcaaaaaatatttttaagcagtaggcacctaacccgattc +ctctacttagtagctttctttgattctcagaattgactgcaatatcactgcacaattctg +tgccattactagacttctctgtattaacgtctcatcttactaacactcgcctaggacaca +tctgagagtgaagtatttcaatacatttactgaaatcttcagttctaaaatccccgaata +aggctcttatcggtttggccaacacaagaaaaaaacttcttgcaccactcaccttcatac +gcaggagcctggggaacttagtaataactatttcggcagacaaagcttataacaagttgc +cggcgcgtataatatttaaaagaccccttgagctgctcaattaaaacgctcacctggtat +aggctattagatagtgccgtcttagtaaggggcgggaattatcggataaactgatatttt +gataaaataaccgacttgttcacgacataagtcactaaggagattttatctttctccaaa +gtatatcttccttggataatttcaaagcgctgcaatttaagttctgttactagtttatgc +tgctgggaggtgaccggaaggcgtagtaatctagaggcaaattataagaagttcatcata +tcattttcgactacaaaaacaaggtgttgtatgccggcgcattgtgtaaactggacgagt +accctagatggaaaattatacgttaagccaagatttcgatgtaatgataattacctacac +atttttgctatccataggaacaagagctgttctataggctcgtggcatacgaacatttgc +tgccgctatgaatattggaagctcttcaactacagactctattcttaattgccgtcgaaa +atgggccgaatcggctattattaatactcggtttttccgaggggattgttgtcgacagtc +gtaattattattaatattgatgttggtgaggtcatttaaatacaaccttgcagacaatga +ataagggatccaatctctcatactccttttacaattgctcatgcccctatgcaaacctta +tgccgccacacctccgcaactctctcttctgaactgtaagtagcttcattactggtttga +gactatactgaagctgatgacattctaaaatggctattttcgaatgtgattcataatgtt +tatcgtttgggatggcagaatcacgttatttttgatatagcccgggtattctattgtata +gaacgtatgctacaagtcattccccgaagaagactagaagtaaacaacatgcgaccatcg +ttaagccacgcaaggctgtagctttatttcccgataacctatcttccataaatagcggac +agcaggatactgacgctcaacatcagtggttatggtctaatttttaacttttaataaggt +aacttcagcaggcatacacagtaactctttaatttataatcaaattagaagtctgacact +tcttatatttttctatcatccaacgcgatcgcccattagcttattgtgttactaataacg +tatctaaaccaatccttttcaagctactgcctatattgtcaatatatacaaacaacagga +tagtaggctgcttaaaaaatattgtcaaccgtgtacgctttacaatacccggaaatcaca +aactttgtagacaacgagtgaaatttatacactacgaagggccagcgtacaagacccatg +aattaggcgatatgtttattctgacatattggtttatccttaatctgtcgctgtaaaatg +aagccgcccccatccctgcgaattttttttcgaagattcacgactgaaatataaatacgt +ttggctatatttatgttggagggaggcaatagcctttactgttaaccgaagatttagcca +gtgagtgtgacactaaaacactggaataaatgcaggcgttcttctgggtaaaaggtttag +tcaatctcgcctataagttcatatagctctggatataattatctggcccatgcatttatc +atggcgcttggtgccctgtgtgaagccggcctctcatattgaaggtccgaagtattccat +gtacattaagatcactctctcattcatgcatcttggcttaacaaatctggttgtccaagc +tttccaggcacgtatggtacaaattcggatcgaatacttataaaaatgatatgttaaact +gtctaaaacgctcatctacaaagtaaagtgcactaaccaatagagtctcaagaccgtgta +atgctggtgcactgaatgtgtaatacggttagaagggattagttatgttacaaatccatt +gaaaacttaagaagcattgcgtgctcggagggtgcatcttttatcaagagactaacatta +ttttcaacgacgtacatgctttacaatagggtacttatcaaacgccgagaaacgcgccta +tagtgatgttatgattatgacccgatatccattggaccgaattttatgtaggttcccagc +gtactcgcgtaatatctcggtattgccataatgtaatacttgtcggtctctcccagatga +aaaagcgttacagagtatttcaatgaaaaacagcgcgcaacgtcaatacctttaggggta +acggccgctgatttcatatagatatacgataagttggtatagctctactaggtggcatcc +acaatcgttgcatttactatagctggttacaatcataatctataccgttccttacatact +accatagcgggatagcgtttttttgccgttgattgggtttaagaggatgtcagtctcatt +atatccgattcggtgggagagccgttgttttcaaatcgcacactttgtgacataatgtac +aagataacaaaactgatataagatataaactgtcaatatcaccttgacacttgaatcaaa +gtaaattaactcgcaaatataatttgactaattgggtgcagatttctcaattaataaaaa +aatggcaccggatgggcttacaagccccttatcattcacttgtatcatgatttccaagaa +caatagaatttgctagcaagtatgaacagagattcgaattgcatccacagtacgccggag +cgtttattttaatgtggatatgacgatgtactgttggcggcatttgctagtaaccggtcc +ttatttacgtagcgcacacgtaagcatgtctgggagaaatatggtggtacaatctcagag +aaagattacagtttggtttaaataggacttatcgggtcggaagtggaacttaataagcag +tacacaattgggcaacagacgtcttgcctattacaataggattacaatgcgttagatttc +agacacgttcgtgtttggctattcgtcaattccctaaatagttagacgatcaactattat +caaagtgattctttgttcatcctccattcatgtaacagatggcacactacgcataacgcc +gaggaattttaacgagatttaagagagcagttcgggcacaacccacttgactttataaca +gctcggcagcataaacggtaatatgtgacaaatttccaaacgttataagaacgtatgtgt +acttagaaaactaagtggttcatgttcaacagatgtgacgcagcaagcctaacttatcta +ttggttttgctataaaagaacaaagttacacagaatcctaagggcttgtttcacacttat +gcctagtgcttcaccatcttaaaatagcgaaaccggcacgaatcaaaccttaaaacaatg +cgcagatattggtgatggtgactccgggtatgataatggtaactgttgaccagcgcccac +ctcatcgaagtatagaaagtggttaggataaggatgagaccgaacttatttccggccata +actttagattttctacctagtacacaacatcagggcggacacgaaaccgccatcacatca +tataccaggtttaatttgcttaatgggggaagtgtcaacgaaccttcgaactttagcagg +catatggccattatatatggccccagagcagaatgctacagcagacaaaatttggattta +tgtagtttaatacctatcaaacttggtgtgaccatacttgtctaacgacagtgcacaaag +tgtaagttacaattattactactcagcagcttctgcaatgataaaatcttatcatacacg +tcacatatgataatatctacttagggggaacgggctccacaacctacatagtactcaata +cttacactattcgacaggcacaccaaacctgtacagtcccaaaagattgagtcaactttg +cagtactgcagatcacagtaatagcttagttagcgagtcaaaattagttttctacgagac +tgcacgaccgtgcaaatttccgatgtgttggctacaaatagcaacgtatgaatttgtttg +aagccacgtaaactgtacaaccttagagataagtctcaggctactaaaaacacgttgtgg +cactaacaggatcatggttgattcttacttattcggctgaccggcccaataagtaacctt +caactagaacagaataatcgggagtagtttaattcagtcaaggtgcaggtctcattgtaa +ctaacaagctctgtgtaaccaagttaaaatcgttttcttagcggattccctacttatgga +tttgagctcgtccacaatattcgatacaagaagtttgtggtccgtaacaacgaaatttta +attacgctgtgcagcctcatccaaggaattaatagaaggttgatggtaggctccgaacgc +tccatgattataatcaagtggactgtgcagtaaacgaggaaggtatcctgacgtcgtggt +gttcgtttttgttatttgtgccctatacgagtagataaaccatgaacagcacagtgtgaa +cccatggttgattttaggctaccttatttttaatttccgttacacagaaacgaattccac +aactaacatgccattaatttttcgatatcttataaaagatggtcgaaattcattcattta +ttttttttcggttctcgaaagtcaactaagctgtcgcgttttgtttctctttagaggtaa +aagtggctttgatctcctacgtttggatactagtcaaccattactccatttgatccgtga +gtatcacctgtctaacatccagcattatgactcctcggcgaagaaaagacacacttctta +gagtcgatgtgtattagctagggacacagttgtttaatacgatagtgagcccagggaggg +cagtgcgtcccccagtagatttattcagctagtgtaagtataagatatctcacccacgag +gttcaagtgatatgcagtcttagaataatacttatcctgaatttcgatattatgggtact +tcaataatccgctagcgctactttatgtctcgttggacagcaggacacatggcagtctta +aacactaaagacatcacctgaatgaatgtaatgggattacaagaatcaatgaggtattat +atacgacgtaggaaactctggatatatacagtaatctagttacgccatcgcacttcattc +ctctggaaacttagaagacatcagctgtacgtggaggaaccagacccccgtatgtagcca +aatagaaccaaagttgcttatacaaacacacccaatgacaatggaccgctggagttcgta +aactcggaacgtagtactgcacaaacccagcatttagcaataggagctacgtatgcaact +cccacgtggtaataccttcaagctatcaatatataggtgcctagctaatcgcattcgcaa +gcagtattcaagcttgtaaaccagtataataattacagaggctctatgaaacccaacttt +ccagctaaaagtcccaattaaatggttatttcgtacttttaaagtcgcccgttctgttat +tacgcgaattgattctactccaaaattaaacacaaattatcaaccgtttcatttatattt +gtcaatgcagctgtttaaaataaggctctactaaattataattaagacacttattaccag +atttctctagttaagtttgaaccagctcgactaccgcgaaagatacattcccttctctat +ttttcagttcatctatgggtcagagaagcattgaatttattctattcaccctcgtcgttc +acagcgaatcgtcagtgtgatcagtgtatgagaaatatcctaaaccgtttagtcagacca +cacgcttagaacaagtggtctaaaaagactgccctggaaggagtaagaagtatacagctg +atccggtgtatccttcagtcatctgccctatactaattacacgacgcaaggaaaaatagg +tttattttctaggcaaacccttcataggtgactccgatgtgttacgaatcatgcttgaga +atgtgctatcgttaccgacggataataacgatctccaatgaaccaaatgtagaatgtcta +ttgattacccttttactattcgacttagagataggagatagaacctcagtgtactttttt +agccgaatgggaatctttgggaggtgaatggccataaggtcgtaaatccaaccctcttaa +agtcttccatattatatcgttgttcgtggaatcgataacagatttgttgacccatagtaa +atgtatactagtttatgttgtaagtgtagattgttttccgattgccgtccaaactttatg +tcgtaattgtagaccagtaaagttgaccaaggtaagtgcccagcgatcctgcgagatcga +tcgccaatttttccagtcactgtaagtgtaggtttagataaagccgtatgagttatatca +taagggcctcggaaagcagcttcgaaccaaagttcccttataatagtagtttaactataa +aagtatatactggtctgtcgccctttcacgatttgttttaccggtttatgaagcgttacg +tcattagagcggctccaatttaaggttaacggcttccatgtgtagttgtatacaaggata +acttaaagtatctgttcagcgagctagttaagttatcctcgatagaacacaactcagagg +tcccaagatcgggtttgcaacttgctaatttattctcaaggcaaattgggaattatcgat +acctgtataccataaggtcgctcgatgtgatgcttatgtcttctggtgatcctaccttag +ttagtgctgattaacggaacattaatgtttatcgttttgagatttagccaattctctgat +tctaactcaagatgccttatctgacgtgctatgcagcccctaagtattttacattgtaat +aggacacgctcctttaaaactcgccaaaaggtcgttgtggttctctactggttaactata +taatttacagctttgttgagctagttcctctttggtttaagtcctcaatattagttggtt +cgagcgataagttggctagttaccttagtcactatattagatccgaatgttatgcttcat +ctgaagaccgccaccctccaaaatttcttttaagactcacttattgcaaggtgtaggtga +attcggctcgtttctcaagtggtgtatctgtacacgagtttccatattttcatcaacagc +caccgcacacttatgtcactctaggtattaaaagtcgctctacaaggggacgcaattaag +aaacagacatgctagtcaaaaataaacatagcgaggcaccactaattcggccgcttatca +atgggatgctctgcgcgagacgcgccagagctcagtagttagttcggacatacatttact +tcagatgatcaattagttttctacaaatgcttactctaccccgaaaaaagtcaccagact +cttacgtctctttagtatccttccgtcttatataaggtcagtcccccgtttcggtaccct +ggaatttactaagaataatgaaacagcccccaaggacgtacgtttacaaatgatagacca +gatcgcctagcttattccgacgcatgttgcatagaattgaaccaacggaatgtgagagta +actagatgagccgaccacagcacccgtttgcgtcgcagaatacgcctgatagttcggcca +cgaaatcatatgtcctttgagtattaagtatttgtaatgatcaatcgagctcaagcaagc +ttacacttcctcggatattcagggaacttagtgcctttgaaagatacgttgatcaacgaa +aaattgataatggctcatatggaatgcctacctcatagtgctgaattaacacagcactgc +ggacctaacttttcgaggtttcaagttcacgtctcaaaacctaataggctggaatatgta +gggatcctcggtgaatttgtgattgggtttgttgtagtactgaccaagtgaatattcttt +ttttctaaaagcagatctgctgccgggcactacgaaggagatctctgtgtatcattattg +cttcttgacatgatgactcttaaatcactgtgggtgtgcaaaacgatagcacaacccaat +tcgatagtacatattgttgatacttcgcactaaaccgttcatatttaaaggttgtgctcc +ttccttcgttaaatactggtgacttggtcctatctactattagctagacctctggggaac +cacgcccccgtaaaacctgtgcaagagagggggtcatacatcttagacatcgcgcctcca +ccagggaagcattgggtgattgaccaggtgtgtaacaaatatgattattcttatactaat +attagcaaagatgcataatgatttgtattaaatgtataattgaattgataagggtctttt +agtcagtgatagagtagtataaggtagacattagaactcttaaccggacgcagatttttc +ggtcttagtaagccaattagtcgacaaaacaaggtaagagcggttactagtagtacctat +aatgcactgaatcttcggtcgaagtatagttctaatgctatgcagattgtgacggcgaca +aatgttcagacttatatcatgaaacaagctcttgtaagtattgacaaatgaaaagattga +atatttttaaatacaaaatgcgcctacttattaggggaattaaccagattgaaggccaat +cctcacatgtaatgagataatagacgataaatgaaattcttgtaatagttgaactgctac +gtgatgggtattatatatgattgagatcctccaattgccgacgtcttgtcttgatgccca +aaagattgtcaacgaggagctccctcgcgtacctgtcgtccgtatcataaacgacgcgac +atgtacagcactccgaagtataagcaataataatgcgggtaatccagactagatcttttc +ggactcaatgcggtttcacggtaaacatgattaataccggagagtagtcgagcttatcag +cgatgcaagcgaattcattgtgccaggagatacgttgcagataaaaccggcaacgtatgt +caacaagttttggcgatctcgttgtttgtattcgacgaggcgcgggaacttcaagaacta +tcgtatattcaagtccattaccttttagtttcagactggtggagctgactaaagttatat +catcattttgtacactggtttagttaacgataatttcagatttaacatgaccagacgata +atcgctgtatatccagttggaatgtggtttgccagaaaggttaacttataatcaagcctc +tcttcagtcttgattcgtcgtatcccatccattgcgctatacctcagtgtatttggagct +gtagttataccgtgtgctaagatcagtagacatgacgagagcaatattatctaccttaca +agcatcaacggacgtctagtcggaacaaaagactctaaaactcgaacttcaggttaatat +actatagttctgtattcagcagttattcttatattcgatattatcttgcctattggatgt +ctgactttagtatattaatcatagtatctgccatgtaaaggtgccagtactaaatctgtt +tcacagtgcgaattataaacggttacaaccattaaagacaacaagaccctatagctttat +ttgaattttgtcaatgcgcaacttggagctcgcgatacatcccaattagtctatagggtc +gggacgattctacggcatttctggttataatgacaacatggattgtggcccgagaatcgc +tctttcattaattaagcaatcattacagtcttataagcgctacttccgagtggtagcagg +taactcgatataaggtcgcatgagccgaatagcttaaaaaacaggccaccgaacattgat +agagaataccgaccacagcgcaacctttgattactttcattaaattgtacggctcactcg +acatcaagcttaagattgcgataatgtgaactcaaatggatcagtactgaagaaccgtaa +cccacttcgcagaaagcgtacccagagaagatacgctgttacaatatacagggtgaaatt +attgcctgttcttcgtaaccatttcgccaaacttggttagaaatgatagccattcatgat +agaaataagctgaatgataccagtatctttaactatgtagtcagggggaagataacgatg +gtccatgtatgtttctgatatgtgacagtattggccgcgtaatttgctaacgaagctact +taatgcctttgagcttcatatagatttctttaatcaaaatcggcaaaaagatagtatgag +ctataatatatgctagtagagaactctggaccatcatctatatgaatactgattcgagcg +tgcaattactttagcctgcgtactactgactctacaaaacactctgagataagtttgtag +tcagtaagtcgctctctataaaccttttggatgaccattgtacagccacttatagatccc +aataaatagcacaggagacagagtttttcaatgctcgatcatttgccgatagtattttcg +tctaacctcagggcacctattatttgatacctaacctaacggccctttcacaatggagaa +atatatgacatcgggacaaacacaaatggtgggtggccaggagatatgacatggtggcgt +ctctaagaaacacggactccctctaggcaaactcacgtaaccaattttaatgtcaaacaa +aacgctcgaaaagattttgccgtgtaatgacctggtacattgactggtcaggaatacatc +actgtagttgccgtagtgtcctgttggtgttccatcaagacacatcgtataacgcaattt +acgacggacatcagatcaagttatacagattatttaagtatcacgtgtgcattgggacat +aagggatctcacacatgccttggaacatttttgctttgtgccgctttttcgctgcactac +caatccttacttaccagtatattcaaaggtcgttaacagaatgagaaaggttagggctct +aagttatcgtcgattgggatagacgagacatttgcgagcgccctccacggatacgaatct +cccatatcaatgtgaactggatgctatgcagtttagttcttacgtctcctagtggtaaaa +atcaaagtagcactcgcatagcagttattcagaacctaatacacaaaaccgtcaaacatt +ttctaattctaggtatgggccgatcataggagctaaggtgaaactcataaatgttttgtt +agatctagcatcctaaaaagatgcatatactgagtagctggcgtgcattctctcaattgt +atcctttttaactgaactagtcggtcccatttcgtgactgagatctattaaccgataaga +ttaataacactcgcattcgtatcagctcagagtgaagtttttcaataatttgactgatat +attaacttctaaaataaccctttaagcctcggatccgtttcccaatcacatcaaaaattc +ttattccaactatctacggattaacaacgtgcatggggatcgtagtaagaacttgttccg +atcactttgagtatatcaagttgacggcccggttattattgaatagaaacattcacctgc +taaattaaataccgcacatcggatacccgatttcagagggccgtcttactaagggcaggc +tttgttcggtttaactgagatgttcattattttacagtatgcttcaactaatatgtaacg +aaggacagtggatctgtctccatagtagatcttcagtcgtgaatttcataccgctcctat +ttaagttcgcgttcgagttgttgatcatggcacgtgaaagcaacccctagtattctagac +gaaaattttttctagttcatctgataatttgccaattcaaaaacaaccgctggtttcccg +gcgcattctctaaaatggaagtcgaacctagagccattatttgtcggtaacccatgagtt +ccttcttttcagaagttaatacactgtggtcctatacagaggaaaaacagcggttatata +cgatcgtggcataacaacattggatcaagatagcaatttggctacctattctaattctca +ctagattcggtattccactacaatatcggcagattaggattggatgaataatcggtgttt +aagtccggttgcgtctccaatctcctaatttttattaatattgatcttggtgacctattg +taaataaaaacttcaagactttgaataacggtgaaaagatagaagactcatttgaaaatg +gatcatccacagatccaaacattagcaagacactaatccccaactagctattctgatcgc +gatcgtgctgcagtactcctgtcacaatagtctgttcatgatctaattctttttgggctt +tgttcgatggtgattcagaatctttatccggtcgcttccctgtagctactttgtggggat +attgcccggggattatagggttgagatcgtttcctaaaagtatttaaaccaagtagactt +caactaaactacatcagaacatcgtgaagacaccatacgcggtacctttatttaccgata +acatttcttcaagaaataccggtaagcagcataatgaccctaaacagctcggggtatcgt +cgtagttttaaattttatttaggttactgctcaaggaataaaaactaactatttaattta +taataatattacaaggctcacactgattagatttgtctataagacttcgcgatcccccat +taccggattgtcttaagaataaactagataaaccatgcattttctagataaggcctttag +tctaattagatacaaaaaacacgatagttgcatccttaatttattgtgtcaaacctggaa +ccttttaattacccgcaaatcactttatgtcgagactacctctgaaatttattatctacc +taccgcatgaggacttgaaccatcttgtaggagttatgtttattagctaagattcgttta +tcctgtagcggtccatgtatattcaacaagcaaaaagcactcagaattgtttttagttga +gtcaagactgatatataaataagtttccctagttttttcgtggtgggacgatattgaatt +gaatcttaaccgaagagtttcccactctgtcgcacaataatacacgccaatatttccagc +cctgcttatgccttaatcggttactcaatctcccattgaagttcattttgatctgcatag +aagtttcgggcccagccttttttctgccaccttcctccaagctctgtagacgcactctaa +gattgatgctcacatgtattaattctacattaacataaatatataagtcatgcatcttcg +agtaaaatatctggttctccaacatgtcctggcacgtatcgttataatgcccatacatgt +agtattaaaatgattgggttaactggatattaagatcatcgaaattgtaaagtcaaatta +acaatactgtctcaagaccgtgtattcctcgtgctcggaagggctattacgcttacttcc +gttttggtatcttaatatgactttcaaaaattaagttgcagtgagtcctacctgcgtgca +tcggttagcaagagtataaaagttgtttaaacgaactacttgctttacaataccggtcgt +atatatcgccgtgaatccagaagattgtcttctttggattatcaaccgagatcctgtgga +ccgatgttttgggaccttcacagaggactccaggtagagctcgcttttgcattaatctaa +gaattgtacctctctaaaagatctaaaacagtgaatgtgtatttcatggaaaaacacaga +gaaacgtaaattactttaggccgaaaggcacatgagttattatacatatacgagatggtg +gtatacatcgaattcggggcatacactatagttgcattgtatttagctgctttaaataat +atgatattaccttccttacataagacattaccggcataccctggttttcaacttgtgggg +ctttttgacgatcgcactctcatttgatccgagtagggcggtgacccctgcttttcaaat +acaaaaatttcgctatgaaggtaatagattacttttcgctgttatgatagaaacggtaaa +tttaaaattgaaacttctagaaaagtaaagtaacgagaaatgattttgtgaataatgcgg +tcatgattgcgcaagtaagaaaaaaaggcaaaaggatgcgcggaatagaaacttatcagt +cacgggtatcttgatttcattcttcttgtcaattgccgacataggatgaaatcagattcc +aatgcaatacacagtaacccccacccttgattgtaatgtcgatttgaagttgtacgcgtc +gacgaagtggatagtatacgggccttttgtacggtgcgatcaactatgaatctcggcgag +ttagatggtcgtacaatctcacacatagaggtcacttgcctgtaatgacgaattttcggc +taggtactcgaactttattagaagtaaaaatgtgggcaaaagaaggattccattttacaa +gacgattacaatgagttacatgtctctcaacgtagtctttccctagtagtctttgaacta +tttaggtactccagaaaattttagcaaagggtttctgtgtgaatccgccattcatgttta +tgatggaacaataagaataacgccctcgtatgttatcgacagtgaagtcagcagttcggc +caaaaacatattcaatttagtacagatccccagaagttaagctaagtgctctaaaatggc +ctaaacggttatcaaagtaggtctaattactatactaacgggtgcatcgtaataactgct +gtcgatgcaacactatatgatagtgtcgttttgctatatatgtacaatgtgacaaagaag +ccttagcgattcttgcaaacttaggacttcggattctcaatcttaaatgtccgaaaacgc +aaagattcaaaaatttaatctatgagcagatatgcctgatggtgactacgcgtatgttaa +ggctaaatgttgacaaccgcacacataatcgaactattgatagtcgggagcataaccagg +tgaacgtactttgttcacgacatttattgacatgttctaaatacgtctcaaaatcacggc +gcactagaaaacgcaatcaaatcattgtcctggtttaagggccgtaatgccggtagtgtc +aaacttcatgagaactttagctggcttttggccagtatttagggaccaagagcactagcc +ttaagctgaatattttgccatttatctactgttataactttaaaacttggtggcaccaga +cttgtcgatacacacgcatcaatctgtaacgtaaaaggtttactaagaacaagcgtagga +attgagtttatattatatttaaactaaaagatgatattagcttctgagggcgatagggct +ccaaatcataaagaggaatatattattacacgattagaaacccacaacatacctcgaatc +gcccaaaagtttgacgaaacttggcagtactccacatctcagtaatacagttgggagagt +ctcaaatgttgttttattactcaatgaaccaccctcataatttcactgctgttccattaa +atttgcaaacgatcatttgctttgaagaaacgtaaaatcgacaaaattacagataagtag +atgcataataaaaaaaactgctcgctataacacgatcatcgtgcattcttacttaggagc +atcacccgcacaataacgtaccttaaactacaacactattagaccgagtactgtaattca +cgaaagctcaagctcgcattgtaaagaacttgctctctcgtaaaatgtgataatagtttg +cggagaggattcaattattttccattgcacctactccactagattcgataaaagaaggtg +gtcctcccttaaaaagaaatgttaagtaacatcggaaccataagcaaagcatgtaagtga +accgtcatccttccctaagaaacataaaggtttttaataatgtcgactgtgaactataac +tgcatcctttcctgacctactccggttccttgttgttatttctgaacgagaccagtagat +aaacaatgtaaaccacagtgggtaccaatggtgcatgtgacgctaccgttgttttaagtg +cccgtacaaacataagaagtcataatcttacttgaaattaattttgccttttattttttt +tcaggctcgaaattaatgatttgttttttttgaccttctagttacgctaatatgcggtcg +cctgtggtttctattgagtcctataacgggatgggatctaatacgtttggttactagtaa +acaaggtataaatttgataccggagtatcaactgtataacatcaagctttatgactcata +cgcgaagtaatgacacaaggctttcaggagatcgcgagtacagagccactaaggggtgta +ttacgatagtgacaccaccgagcgcactcactccccaagtagatttatgatcctacgcta +agtattagatatataaccaaagaggttctagtcagtgcaactcttagaataataattagc +cggttttgcctttttaggcctaatgcaatattcagctagcccttatgtatctcgcgttcc +acagcaccactcatggcacgcgtttaaactaatcaaatataatctatgaatgttatgcca +gtacttgaataaatcaggttttttataagtccttgcatactctcgttatatactgttaga +gtcttaccccatagaaattctttcatctgcaaacttagaagaattctcagctacggggag +cataaagtccccaggatgttgacaaatacaacaaatgtggcttatacaaacactccatat +gaaaatcgaaccctcgtggtagttttagccgaaccttgtacggataaatccctccatttt +ccaatagcagatacctatcctactacctcgtggtattaaattaaagcttgaaatatagag +ctgcatagcttatccaattcccaagcacgagtctaccgtcgtaaccacgatttgatttac +agacgctagagcaaacccatctttaaacatataagtaaaaattaaagggtgagtgcgtac +gtgtttactagcaacttcgcttattaagacaattgtttataagccataattaaaaacata +tgttcaacaggttcattgatatttgtaattgcacaggtttttaataaggatctacgtaag +tataatgaacaaactttttaccagagttatattctgtactttgaaaatgctcctctaccg +ccttagagactttcaattagattttttgcagttaatctatgcgtaagtgaaccatgcaag +ggatgcgattcaaccgcctcgtgctaaccctatcgtctgtctcataactgtaggtctaat +ataattttcagttttcgaacacataaccctttgaaaatctgctatttaatgtctcacctg +catgcactatcttctatactgctcagaacggctatacgtcactatgctccaagtgacgat +ttaaacgaagcaaggaataataggtttattttagtgcaaaacaattaagtgcggactacg +tgctctttacaataagccttgtgattgggctataggttaagtcccatattaacgatctcc +aatgtacaaaatcgacaatcgctttgcattacccggttactagtcgaattacagatagct +gttagatactcactctaattttggacaacaatcccaatcttggggtcgtctatcgcctga +agctcgtaaatccttccatcttaaacgattacatattatagacttgttcggggtagagat +atcacagttgtgcaaacattgtaaatcgatactagtttatgttggtagtctagttgcttt +taccattccccgaaaaacttgatctactatttcgacaacagtaaacttgaactaggtaag +tgaaaacagagaatgcctcatagtgccactatttgtccactatatgtaagtgtagcttta +cataatccactatgactgagatcattacggcctaggaaagcagcgtagaaaaaaagggcc +cggatattacgactgtaactataaaactagttactggtagcgcgccatgtatagatttgt +tttaccggttgtggttgcgttaacgaatttcagccgcgaaaattgatccgttaaccagtc +catctcgacttctataaaacgataaagtaaagttgatgttcagcctccttcttatggttg +catcgagagtacactactcagtgggaaatagatcggggttcctacttcagattgtattat +ctaggcaattgccgattgtgccatacctggataaaataagctacctacatgtgatgctta +tctattatcgtcatactaccttagggtgtcctgttgaacgctacattaatctttagccgt +ttgagatgttccaatggataggagtctaacgcatgatgaagtttaggaaggcagagcatc +ccactaagtatgtgacagtgtatttcgaaacgagacgttataaatagaaaaaaggtcctt +ctggttctattctgctgaactattgaatggaaagattggttgacctacgtactatttgct +tgaagtcatcaatttgacggggtgagagacatatggtgcatactttacggactctatatt +ttagatcagaagcttagcagtcttctctacaccccctcacgacataattgcttttaagaa +tctatgtttgattcctctacgggaattcggatccgttcgcatgtgcggtttatctaaacc +aggggacatatgttcagctaaagcatacgaacactttgctaactagacgtatgtatagta +gctataaatcccgacgatatttacaaaaagaaatgagactcaaatatatacatagcgacc +ctacacttattcgcaccctgatctaggcgatcctagcacccacacccgaaagtgagcact +agtgtcttccgtattaaatttactgcagttgagattttagttgtctactaaggattactc +taacccgtaataaggatcaagactcggtactagctttactatcattccctatgtgttttc +ctaactcacaagggtacgtaccagcctatgtaattacaataatgataaagacacaaagga +agtaactttacaaatgagtctccagttacactagcttagtccctcccatcttgctttgaa +gtctaaatacgcaatctctgaggatatacagcagaagaacactcataacgttggagtcca +agaattagactcatagggcccccaacatttaatatgtactgtgagtttgaaggtgttcta +ttgttaattcctgctcttgatacatgacacgtactccgtgtttaaggcttcggactgact +ttctttcataagttgagcaacgaaaatttcagaatcgataagttggattcactaactaat +acggctgattgaaaactccactccggacctatatggtcgacctttatacgtaaccgatat +aaaacttataggctggtatatcgagccttcctagcgcaatttcggatggggtttcttcta +ctactcaacaacggaatagtctttgtttagtaaaccagagctcaggacgcccaatacgta +ggagagcgctgtggagcatgtgtcattatggactggagcactcttaaatcactctgcgtg +tgctaaacgatagatcataacatgtcctgagtaaattttcttgatacgtcgcaatatacc +gttattagttaaacgttctcatccgtcatgcgtgaaatacggctgtcgtgctcagatata +ctattagcgactcatctcgcctaacacgcacacgtataaactcggaatgactgccgctct +tacatattagaaatacagactacaccacggaagcattgggtcattctcaaccgctgtata +aaagatgattagtcttataataagattaccaaagaggcagaatcatgggtagtaaatcta +ttattcaagtgattaccgtcgtgtaggcagggagtgaggacgagatggtactcaggacaa +atattaaccggacgaagtggtttacgtcgtactttcactattagtagtaaatacaaggta +acaccggggaatagtactaaatataatgatatctatcttcgggagaacgagtcgtctatt +gctttgaacattctcaaggcgtaaaatgtgctgacttatagcatgatacaaccgattgtt +acttttgtctattcaaaagattgaatagttttttatacaaaagccgcatacttatgacgg +ctagtatacagtttcatcccctagcatcaatgctatggacagtattgaacttataggaaa +ttcttctaatagggcaaatccgtcgtgatgcctattttttttcagtcacatcctcaaatg +gcactagtattgtcgggatcccattaacaggctcaaccacgagctcacgcgaggacatgt +agtccgtatctttaacgaagcgacagcgacagaactcccatggataaccaattataaggc +ccgtaatcctctagacatcgtttaccaataaatccgctttctccgtaatcatgttgaata +ccccagagtagtccagatgataaccgatgaaacacaagtctttctcaatgcacttacggt +gaacttattaccgccaacgtagctcatcaaggttgcgacatctagttgtgtgtttgcgac +gagcccagcgaacttcatcaactttcgtatattcaacgccttgtaattttactttaagac +gcctggtgatgtagattcttagataatcagtttgttatcggctgtactttaccataattt +cacaggtttcaggtcaagaagattatagctgtatatacagttccatgctcggtgcacaga +aacgtgatcggataataatcaatcgcttatgtcgtctttaggcgtatccaatacatgccc +cgataccgcagtgtatttcgacatgtaggtataccgtcgcatttgagctcgagtcaggac +gtcagctagattagattccttaatagaatataccgacctctagtccgaactaaactatag +ataacgccaacttcaggttaattgtctagtcgtctgtttgcagatgggattcttagatga +gtgagtatcggccatattggttcgagcactttagtttttgatgcataggatatgcaatgt +atagctgaaagtactttatctgtttcaaactcacattgattaaaccggtaaacctttaaa +gactacaagaaaatattcagtgagggcaattttgtcaatcacaatcttccagctagagat +acttcacaatttgtcttgaggctacgcaacattagacggattttcgcgttttattgaaat +aatcgaggggcccaagagtatccatagttcattttgtaagatttctttacaggcttatta +cagcttcttcagactcctacatgcttacgagttatatgctagcatgtgaacaatagatta +atatacaggaaaacgtacattgagagagatgaccctacacagcgcaaccgttgagtactt +tcattaaagggtaacgctctcgagacagcatccttaagatggccttattgtcaaatcatt +tgcagaagtacgcaagatccctaaccaacgtagaagaatccctacaaacacatgagacgc +ggtgaaaatagacagggtgttagtattcaatcttcggagtatcaatttcgccaatcttgg +tgagaaagcataccctttcttcagagaaagaagatcaatcataacactatctttaacgag +gtacgcacgcgcatcattacctgcctccatggatctttaggatagcggaaagtattggca +gcgtattgtgatttcgttcctactttatcaatttcacattcatatacatgtcttttatca +aaatcgccaataagataggatgagctatattagatgctagtagagttcgcgccaacatca +tcgataggaatactcaggacagcgtgataggacttttcaatccctaatactctctataat +tataactctctcttaagtttggaggcagtaacgcgctctatataatcagtttgctgcacc +attcttcagcctctgatacatacaaataaattccacagcagtaagagggtttaattgaga +catcttgggaacttaggattttactctaacatcaccgaaacgattattggataccgtacc +taaacgaactttctcaaggcagtaatataggacatccgcaataacacaaatgctgcctcc +ccaggagttatgtcttcctggaggctatatcttacacccactcactataggcaaactaaa +gtttaaatgttgattgtctaaaaaaaagatagataagagttggccggcgtagcacatgcg +aaagtgaatcgtaagctataattctctggacttgaagttctgtcctgttcctctgcaaga +aacaaacttcctttaaagctatttacgacgcacatctcagcaagttataaacatgttgga +agtttctagtcggaattcccaaagaacggatctatctaatgcattcctacatttttcctg +tctgccgatggtgccatcctattcaaagaatttcttaaaagtagattaaatgggactttt +aacaatgagtaaccttacgcctctaagggttcctcgagtgccatacaccagtcaggtccg +agccacatacacggagaacattctaacatagcattctcaactcgatcatttgcaggttac +ttctttcctatcctagtgctaaaaatcatacttgcaatcccatagcacggattaagaacc +taagaaacaattcagtaaaacatgttcgaattcttggtatgggaacatcattgcagctat +ggtctaacgcattaatgtttgggtacatcttccatcatataaacaggaagagtctgacga +cagggagtgcttgcgatcatgtctatcattgtgaaatcaaattgtagctcacatgtcgtc +tatgagagcgtgtatccgataagatttagaaaaatagaagtcgtataagatctcactgaa +cttttgaatgaatgtgaagcatatatgatctgctttaataaaactttatccataggatac +gtttccaaatcaattcaataattattagtcaaaatagataaggatgaacaacctgaaggc +cgatcggacgtagaaagtggtcccatcactttgagttgatattgttgaaccacacgttat +tatggttttcaaacagtctcaggatattgtatatacagataatccgataccagttgtctg +acgcccctcttacgtaccccaccctttgtgacgtttaaagcagttgttcagtattttaaa +ctaggcggcaactaatttggaaagaagcacagtggatatgtctaaattcttgttattcag +gcctgaatttaatacaccgcatagttaacttcgcggtagagttgttcatcatgcctcctc +taagctaccacttctatgatacaccaatagttgttctacggaatctgataattggccaag +tcataaacttccgctgcgttcaacccccttgctcgaatatccaactcgaaaagacagcct +tttggtgtccggaacaaatcagttacttcttttctgatgttaattctctgtggtcagata +cagaccaaaaactccgcggatttaccatcctccaagaacaaatttgcatcaacatagcat +tttggctacatattctaagtctcaatagtttaggttttcaactacattatcccaacatta +ggattggaggaataatagctgggtaagtccccttgcgtctacaatcgactattttttatg +aatatgcttctgccgcacctatggttattaaaaaagtcatgactttgaagaaccctgaaa +agatagatgaatcaggtgtaatggcagcagccaaagagcatataattagcaacactctaa +gaacattatagatatgatgatagcgatcgtcatgatgttatccggtcacaatagtagctt +catcagctaattcgttttgccagtggtgacttgcgctggaagaatcgttatacggtccct +tccctcttgatacggtgggggcttattcaaccgcgtggattgggttgtcatacttgcatt +aaacgatgtaaaccatctagtagtcaactatactaaatcacaaaatagtgatcaatacat +acccgcttcatggttttaaccatttaattgattaaagatattccgctaagaaccattatc +tacctaaactgatcgccgtatcctagtagtttgaaatttgatgtaccgtaatgatcaacg +aagtaaaacgttatattgtatgtagaataataggtcttggagctaaatgatgtgattggt +agtgaagacttacccttacaactttaccggtttctcggaagaatatactagagaatcaat +gcatgggctacataagcactttagtctaatgagataaaaaatacacgagtcttccatcat +gaattttttgtcgaaaaactcgaacctggtaatttaaaccatatatctttatgtcgtcaa +taactctcatatgttttatataacttcccaatcacgacttgtaactgcttgttcgactga +gctgtttgagctatgaggccgggatccggttgagctacatctatttgctacaagaaaaat +gaaagcacatttgttgggagttctggctacactcatagagaaataagtggcccgagtggg +tgcggcctgcctccatattcaagtgtatcttaaaccaagtggttccaacgctcgcgctaa +agaattaaagcctttatttcctccacggagtagcccgtaatccggttcgaaagagaccat +tgaagttaattttcatatccagtgaagtttaggcacaagcatgtgttctgccacatgcct +caaagcgctcttcaaccaagatatgattcatcctaacttcgatgaatgcgtctgtaacat +aaatatagaaggaatgattcggcgagttaattttcgccttctccaacatggcatccctac +gttcgttataaggaccatacatgtaggttttaaaggtttgcggttaatcgatatttacat +catagaaattctatagtcaaatttacaagactctagatactcactcgttgcagccggcta +ggaagcgctttgtaccttacttcccttttcgttgcgtaatatgaatttcatatagtaagt +tcaaggcactcatacctccgtgaagagggtagatagactattaaagttgtttaatagtac +gtattgatggaaatgacccgtaggagatttaccactcaatccacaagattcgctgctgtg +cattatcaaaacagtgcatgtcgaaacatgggttgggtccttcaaacacgaatccaggta +gagatacctttgcaattttt diff --git a/bash-5.1/vendor/regex/examples/regexdna-output.txt b/bash-5.1/vendor/regex/examples/regexdna-output.txt new file mode 100644 index 0000000..d36baa5 --- /dev/null +++ b/bash-5.1/vendor/regex/examples/regexdna-output.txt @@ -0,0 +1,13 @@ +agggtaaa|tttaccct 0 +[cgt]gggtaaa|tttaccc[acg] 3 +a[act]ggtaaa|tttacc[agt]t 9 +ag[act]gtaaa|tttac[agt]ct 8 +agg[act]taaa|ttta[agt]cct 10 +aggg[acg]aaa|ttt[cgt]ccct 3 +agggt[cgt]aa|tt[acg]accct 4 +agggta[cgt]a|t[acg]taccct 3 +agggtaa[cgt]|[acg]ttaccct 5 + +101745 +100000 +133640 diff --git a/bash-5.1/vendor/regex/examples/shootout-regex-dna-bytes.rs b/bash-5.1/vendor/regex/examples/shootout-regex-dna-bytes.rs new file mode 100644 index 0000000..4010324 --- /dev/null +++ b/bash-5.1/vendor/regex/examples/shootout-regex-dna-bytes.rs @@ -0,0 +1,66 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; +use std::sync::Arc; +use std::thread; + +macro_rules! regex { ($re:expr) => { ::regex::bytes::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = Vec::with_capacity(51 * (1 << 20)); + io::stdin().read_to_end(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, &b""[..]).into_owned(); + let clen = seq.len(); + let seq_arc = Arc::new(seq.clone()); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + let mut counts = vec![]; + for variant in variants { + let seq = seq_arc.clone(); + let restr = variant.to_string(); + let future = thread::spawn(move || variant.find_iter(&seq).count()); + counts.push((restr, future)); + } + + let substs = vec![ + (regex!("B"), &b"(c|g|t)"[..]), + (regex!("D"), &b"(a|g|t)"[..]), + (regex!("H"), &b"(a|c|t)"[..]), + (regex!("K"), &b"(g|t)"[..]), + (regex!("M"), &b"(a|c)"[..]), + (regex!("N"), &b"(a|c|g|t)"[..]), + (regex!("R"), &b"(a|g)"[..]), + (regex!("S"), &b"(c|g)"[..]), + (regex!("V"), &b"(a|c|g)"[..]), + (regex!("W"), &b"(a|t)"[..]), + (regex!("Y"), &b"(c|t)"[..]), + ]; + let mut seq = seq; + for (re, replacement) in substs { + seq = re.replace_all(&seq, replacement).into_owned(); + } + + for (variant, count) in counts { + println!("{} {}", variant, count.join().unwrap()); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} diff --git a/bash-5.1/vendor/regex/examples/shootout-regex-dna-cheat.rs b/bash-5.1/vendor/regex/examples/shootout-regex-dna-cheat.rs new file mode 100644 index 0000000..a421d20 --- /dev/null +++ b/bash-5.1/vendor/regex/examples/shootout-regex-dna-cheat.rs @@ -0,0 +1,88 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +// This technically solves the problem posed in the `regex-dna` benchmark, but +// it cheats by combining all of the replacements into a single regex and +// replacing them with a single linear scan. i.e., it re-implements +// `replace_all`. As a result, this is around 25% faster. ---AG + +extern crate regex; + +use std::io::{self, Read}; +use std::sync::Arc; +use std::thread; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + let seq_arc = Arc::new(seq.clone()); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + let mut counts = vec![]; + for variant in variants { + let seq = seq_arc.clone(); + let restr = variant.to_string(); + let future = thread::spawn(move || variant.find_iter(&seq).count()); + counts.push((restr, future)); + } + + let substs = vec![ + (b'B', "(c|g|t)"), + (b'D', "(a|g|t)"), + (b'H', "(a|c|t)"), + (b'K', "(g|t)"), + (b'M', "(a|c)"), + (b'N', "(a|c|g|t)"), + (b'R', "(a|g)"), + (b'S', "(c|g)"), + (b'V', "(a|c|g)"), + (b'W', "(a|t)"), + (b'Y', "(c|t)"), + ]; // combined into one regex in `replace_all` + let seq = replace_all(&seq, substs); + + for (variant, count) in counts { + println!("{} {}", variant, count.join().unwrap()); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} + +fn replace_all(text: &str, substs: Vec<(u8, &str)>) -> String { + let mut replacements = vec![""; 256]; + let mut alternates = vec![]; + for (re, replacement) in substs { + replacements[re as usize] = replacement; + alternates.push((re as char).to_string()); + } + + let re = regex!(&alternates.join("|")); + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for m in re.find_iter(text) { + new.push_str(&text[last_match..m.start()]); + new.push_str(replacements[text.as_bytes()[m.start()] as usize]); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + new +} diff --git a/bash-5.1/vendor/regex/examples/shootout-regex-dna-replace.rs b/bash-5.1/vendor/regex/examples/shootout-regex-dna-replace.rs new file mode 100644 index 0000000..857d8bf --- /dev/null +++ b/bash-5.1/vendor/regex/examples/shootout-regex-dna-replace.rs @@ -0,0 +1,19 @@ +extern crate regex; + +use std::io::{self, Read}; + +macro_rules! regex { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re).build().unwrap().into_regex() + }} +} + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + println!("original: {}, replaced: {}", ilen, seq.len()); +} diff --git a/bash-5.1/vendor/regex/examples/shootout-regex-dna-single-cheat.rs b/bash-5.1/vendor/regex/examples/shootout-regex-dna-single-cheat.rs new file mode 100644 index 0000000..64d2104 --- /dev/null +++ b/bash-5.1/vendor/regex/examples/shootout-regex-dna-single-cheat.rs @@ -0,0 +1,73 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + for re in variants { + println!("{} {}", re.to_string(), re.find_iter(&seq).count()); + } + + let substs = vec![ + (b'B', "(c|g|t)"), + (b'D', "(a|g|t)"), + (b'H', "(a|c|t)"), + (b'K', "(g|t)"), + (b'M', "(a|c)"), + (b'N', "(a|c|g|t)"), + (b'R', "(a|g)"), + (b'S', "(c|g)"), + (b'V', "(a|c|g)"), + (b'W', "(a|t)"), + (b'Y', "(c|t)"), + ]; // combined into one regex in `replace_all` + let seq = replace_all(&seq, substs); + + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} + +fn replace_all(text: &str, substs: Vec<(u8, &str)>) -> String { + let mut replacements = vec![""; 256]; + let mut alternates = vec![]; + for (re, replacement) in substs { + replacements[re as usize] = replacement; + alternates.push((re as char).to_string()); + } + + let re = regex!(&alternates.join("|")); + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for m in re.find_iter(text) { + new.push_str(&text[last_match..m.start()]); + new.push_str(replacements[text.as_bytes()[m.start()] as usize]); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + new +} diff --git a/bash-5.1/vendor/regex/examples/shootout-regex-dna-single.rs b/bash-5.1/vendor/regex/examples/shootout-regex-dna-single.rs new file mode 100644 index 0000000..ed48b8b --- /dev/null +++ b/bash-5.1/vendor/regex/examples/shootout-regex-dna-single.rs @@ -0,0 +1,55 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + for re in variants { + println!("{} {}", re.to_string(), re.find_iter(&seq).count()); + } + + let substs = vec![ + (regex!("B"), "(c|g|t)"), + (regex!("D"), "(a|g|t)"), + (regex!("H"), "(a|c|t)"), + (regex!("K"), "(g|t)"), + (regex!("M"), "(a|c)"), + (regex!("N"), "(a|c|g|t)"), + (regex!("R"), "(a|g)"), + (regex!("S"), "(c|g)"), + (regex!("V"), "(a|c|g)"), + (regex!("W"), "(a|t)"), + (regex!("Y"), "(c|t)"), + ]; + let mut seq = seq; + for (re, replacement) in substs { + seq = re.replace_all(&seq, replacement).into_owned(); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} diff --git a/bash-5.1/vendor/regex/examples/shootout-regex-dna.rs b/bash-5.1/vendor/regex/examples/shootout-regex-dna.rs new file mode 100644 index 0000000..2171bb3 --- /dev/null +++ b/bash-5.1/vendor/regex/examples/shootout-regex-dna.rs @@ -0,0 +1,66 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; +use std::sync::Arc; +use std::thread; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(51 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + let seq_arc = Arc::new(seq.clone()); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + let mut counts = vec![]; + for variant in variants { + let seq = seq_arc.clone(); + let restr = variant.to_string(); + let future = thread::spawn(move || variant.find_iter(&seq).count()); + counts.push((restr, future)); + } + + let substs = vec![ + (regex!("B"), "(c|g|t)"), + (regex!("D"), "(a|g|t)"), + (regex!("H"), "(a|c|t)"), + (regex!("K"), "(g|t)"), + (regex!("M"), "(a|c)"), + (regex!("N"), "(a|c|g|t)"), + (regex!("R"), "(a|g)"), + (regex!("S"), "(c|g)"), + (regex!("V"), "(a|c|g)"), + (regex!("W"), "(a|t)"), + (regex!("Y"), "(c|t)"), + ]; + let mut seq = seq; + for (re, replacement) in substs { + seq = re.replace_all(&seq, replacement).into_owned(); + } + + for (variant, count) in counts { + println!("{} {}", variant, count.join().unwrap()); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} diff --git a/bash-5.1/vendor/regex/scripts/frequencies.py b/bash-5.1/vendor/regex/scripts/frequencies.py new file mode 100755 index 0000000..c800b0b --- /dev/null +++ b/bash-5.1/vendor/regex/scripts/frequencies.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +# This does simple normalized frequency analysis on UTF-8 encoded text. The +# result of the analysis is translated to a ranked list, where every byte is +# assigned a rank. This list is written to src/freqs.rs. +# +# Currently, the frequencies are generated from the following corpuses: +# +# * The CIA world fact book +# * The source code of rustc +# * Septuaginta + +from __future__ import absolute_import, division, print_function + +import argparse +from collections import Counter +import sys + +preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/frequencies.py", do not +// edit directly +''' + + +def eprint(*args, **kwargs): + kwargs['file'] = sys.stderr + print(*args, **kwargs) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('corpus', metavar='FILE', nargs='+') + args = p.parse_args() + + # Get frequency counts of each byte. + freqs = Counter() + for i in range(0, 256): + freqs[i] = 0 + + eprint('reading entire corpus into memory') + corpus = [] + for fpath in args.corpus: + corpus.append(open(fpath, 'rb').read()) + + eprint('computing byte frequencies') + for c in corpus: + for byte in c: + freqs[byte] += 1.0 / float(len(c)) + + eprint('writing Rust code') + # Get the rank of each byte. A lower rank => lower relative frequency. + rank = [0] * 256 + for i, (byte, _) in enumerate(freqs.most_common()): + # print(byte) + rank[byte] = 255 - i + + # Forcefully set the highest rank possible for bytes that start multi-byte + # UTF-8 sequences. The idea here is that a continuation byte will be more + # discerning in a homogenous haystack. + for byte in range(0xC0, 0xFF + 1): + rank[byte] = 255 + + # Now write Rust. + olines = ['pub const BYTE_FREQUENCIES: [u8; 256] = ['] + for byte in range(256): + olines.append(' %3d, // %r' % (rank[byte], chr(byte))) + olines.append('];') + + print(preamble) + print('\n'.join(olines)) + +if __name__ == '__main__': + main() diff --git a/bash-5.1/vendor/regex/scripts/regex-match-tests.py b/bash-5.1/vendor/regex/scripts/regex-match-tests.py new file mode 100755 index 0000000..24635e7 --- /dev/null +++ b/bash-5.1/vendor/regex/scripts/regex-match-tests.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python2 + +# Copyright 2014 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +from __future__ import absolute_import, division, print_function +import argparse +import datetime +import os.path as path + + +def print_tests(tests): + print('\n'.join([test_tostr(t) for t in tests])) + + +def read_tests(f): + basename, _ = path.splitext(path.basename(f)) + tests = [] + for lineno, line in enumerate(open(f), 1): + fields = filter(None, map(str.strip, line.split('\t'))) + if not (4 <= len(fields) <= 5) \ + or 'E' not in fields[0] or fields[0][0] == '#': + continue + + opts, pat, text, sgroups = fields[0:4] + groups = [] # groups as integer ranges + if sgroups == 'NOMATCH': + groups = [None] + elif ',' in sgroups: + noparen = map(lambda s: s.strip('()'), sgroups.split(')(')) + for g in noparen: + s, e = map(str.strip, g.split(',')) + if s == '?' and e == '?': + groups.append(None) + else: + groups.append((int(s), int(e))) + else: + # This skips tests that should result in an error. + # There aren't many, so I think we can just capture those + # manually. Possibly fix this in future. + continue + + if pat == 'SAME': + pat = tests[-1][1] + if '$' in opts: + pat = pat.decode('string_escape') + text = text.decode('string_escape') + if 'i' in opts: + pat = '(?i)%s' % pat + + name = '%s_%d' % (basename, lineno) + tests.append((name, pat, text, groups)) + return tests + + +def test_tostr(t): + lineno, pat, text, groups = t + options = map(group_tostr, groups) + return 'mat!(match_%s, r"%s", r"%s", %s);' \ + % (lineno, pat, '' if text == "NULL" else text, ', '.join(options)) + + +def group_tostr(g): + if g is None: + return 'None' + else: + return 'Some((%d, %d))' % (g[0], g[1]) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description='Generate match tests from an AT&T POSIX test file.') + aa = parser.add_argument + aa('files', nargs='+', + help='A list of dat AT&T POSIX test files. See src/testdata') + args = parser.parse_args() + + tests = [] + for f in args.files: + tests += read_tests(f) + + tpl = '''// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py' +// on {date}. +''' + print(tpl.format(date=str(datetime.datetime.now()))) + + for f in args.files: + print('// Tests from %s' % path.basename(f)) + print_tests(read_tests(f)) + print('') diff --git a/bash-5.1/vendor/regex/src/backtrack.rs b/bash-5.1/vendor/regex/src/backtrack.rs new file mode 100644 index 0000000..6e71e2c --- /dev/null +++ b/bash-5.1/vendor/regex/src/backtrack.rs @@ -0,0 +1,302 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This is the backtracking matching engine. It has the same exact capability +// as the full NFA simulation, except it is artificially restricted to small +// regexes on small inputs because of its memory requirements. +// +// In particular, this is a *bounded* backtracking engine. It retains worst +// case linear time by keeping track of the states that it has visited (using a +// bitmap). Namely, once a state is visited, it is never visited again. Since a +// state is keyed by `(instruction index, input index)`, we have that its time +// complexity is `O(mn)` (i.e., linear in the size of the search text). +// +// The backtracking engine can beat out the NFA simulation on small +// regexes/inputs because it doesn't have to keep track of multiple copies of +// the capture groups. In benchmarks, the backtracking engine is roughly twice +// as fast as the full NFA simulation. Note though that its performance doesn't +// scale, even if you're willing to live with the memory requirements. Namely, +// the bitset has to be zeroed on each execution, which becomes quite expensive +// on large bitsets. + +use exec::ProgramCache; +use input::{Input, InputAt}; +use prog::{Program, InstPtr}; +use re_trait::Slot; + +type Bits = u32; + +const BIT_SIZE: usize = 32; +const MAX_SIZE_BYTES: usize = 256 * (1 << 10); // 256 KB + +/// Returns true iff the given regex and input should be executed by this +/// engine with reasonable memory usage. +pub fn should_exec(num_insts: usize, text_len: usize) -> bool { + // Total memory usage in bytes is determined by: + // + // ((len(insts) * (len(input) + 1) + bits - 1) / bits) * (size_of(u32)) + // + // The actual limit picked is pretty much a heuristic. + // See: https://github.com/rust-lang/regex/issues/215 + let size = ((num_insts * (text_len + 1) + BIT_SIZE - 1) / BIT_SIZE) * 4; + size <= MAX_SIZE_BYTES +} + +/// A backtracking matching engine. +#[derive(Debug)] +pub struct Bounded<'a, 'm, 'r, 's, I> { + prog: &'r Program, + input: I, + matches: &'m mut [bool], + slots: &'s mut [Slot], + m: &'a mut Cache, +} + +/// Shared cached state between multiple invocations of a backtracking engine +/// in the same thread. +#[derive(Clone, Debug)] +pub struct Cache { + jobs: Vec, + visited: Vec, +} + +impl Cache { + /// Create new empty cache for the backtracking engine. + pub fn new(_prog: &Program) -> Self { + Cache { jobs: vec![], visited: vec![] } + } +} + +/// A job is an explicit unit of stack space in the backtracking engine. +/// +/// The "normal" representation is a single state transition, which corresponds +/// to an NFA state and a character in the input. However, the backtracking +/// engine must keep track of old capture group values. We use the explicit +/// stack to do it. +#[derive(Clone, Copy, Debug)] +enum Job { + Inst { ip: InstPtr, at: InputAt }, + SaveRestore { slot: usize, old_pos: Option }, +} + +impl<'a, 'm, 'r, 's, I: Input> Bounded<'a, 'm, 'r, 's, I> { + /// Execute the backtracking matching engine. + /// + /// If there's a match, `exec` returns `true` and populates the given + /// captures accordingly. + pub fn exec( + prog: &'r Program, + cache: &ProgramCache, + matches: &'m mut [bool], + slots: &'s mut [Slot], + input: I, + start: usize, + ) -> bool { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.backtrack; + let start = input.at(start); + let mut b = Bounded { + prog: prog, + input: input, + matches: matches, + slots: slots, + m: cache, + }; + b.exec_(start) + } + + /// Clears the cache such that the backtracking engine can be executed + /// on some input of fixed length. + fn clear(&mut self) { + // Reset the job memory so that we start fresh. + self.m.jobs.clear(); + + // Now we need to clear the bit state set. + // We do this by figuring out how much space we need to keep track + // of the states we've visited. + // Then we reset all existing allocated space to 0. + // Finally, we request more space if we need it. + // + // This is all a little circuitous, but doing this unsafely + // doesn't seem to have a measurable impact on performance. + // (Probably because backtracking is limited to such small + // inputs/regexes in the first place.) + let visited_len = + (self.prog.len() * (self.input.len() + 1) + BIT_SIZE - 1) + / + BIT_SIZE; + self.m.visited.truncate(visited_len); + for v in &mut self.m.visited { + *v = 0; + } + if visited_len > self.m.visited.len() { + let len = self.m.visited.len(); + self.m.visited.reserve_exact(visited_len - len); + for _ in 0..(visited_len - len) { + self.m.visited.push(0); + } + } + } + + /// Start backtracking at the given position in the input, but also look + /// for literal prefixes. + fn exec_(&mut self, mut at: InputAt) -> bool { + self.clear(); + // If this is an anchored regex at the beginning of the input, then + // we're either already done or we only need to try backtracking once. + if self.prog.is_anchored_start { + return if !at.is_start() { + false + } else { + self.backtrack(at) + }; + } + let mut matched = false; + loop { + if !self.prog.prefixes.is_empty() { + at = match self.input.prefix_at(&self.prog.prefixes, at) { + None => break, + Some(at) => at, + }; + } + matched = self.backtrack(at) || matched; + if matched && self.prog.matches.len() == 1 { + return true; + } + if at.is_end() { + break; + } + at = self.input.at(at.next_pos()); + } + matched + } + + /// The main backtracking loop starting at the given input position. + fn backtrack(&mut self, start: InputAt) -> bool { + // N.B. We use an explicit stack to avoid recursion. + // To avoid excessive pushing and popping, most transitions are handled + // in the `step` helper function, which only pushes to the stack when + // there's a capture or a branch. + let mut matched = false; + self.m.jobs.push(Job::Inst { ip: 0, at: start }); + while let Some(job) = self.m.jobs.pop() { + match job { + Job::Inst { ip, at } => { + if self.step(ip, at) { + // Only quit if we're matching one regex. + // If we're matching a regex set, then mush on and + // try to find other matches (if we want them). + if self.prog.matches.len() == 1 { + return true; + } + matched = true; + } + } + Job::SaveRestore { slot, old_pos } => { + if slot < self.slots.len() { + self.slots[slot] = old_pos; + } + } + } + } + matched + } + + fn step(&mut self, mut ip: InstPtr, mut at: InputAt) -> bool { + use prog::Inst::*; + loop { + // This loop is an optimization to avoid constantly pushing/popping + // from the stack. Namely, if we're pushing a job only to run it + // next, avoid the push and just mutate `ip` (and possibly `at`) + // in place. + if self.has_visited(ip, at) { + return false; + } + match self.prog[ip] { + Match(slot) => { + if slot < self.matches.len() { + self.matches[slot] = true; + } + return true; + } + Save(ref inst) => { + if let Some(&old_pos) = self.slots.get(inst.slot) { + // If this path doesn't work out, then we save the old + // capture index (if one exists) in an alternate + // job. If the next path fails, then the alternate + // job is popped and the old capture index is restored. + self.m.jobs.push(Job::SaveRestore { + slot: inst.slot, + old_pos: old_pos, + }); + self.slots[inst.slot] = Some(at.pos()); + } + ip = inst.goto; + } + Split(ref inst) => { + self.m.jobs.push(Job::Inst { ip: inst.goto2, at: at }); + ip = inst.goto1; + } + EmptyLook(ref inst) => { + if self.input.is_empty_match(at, inst) { + ip = inst.goto; + } else { + return false; + } + } + Char(ref inst) => { + if inst.c == at.char() { + ip = inst.goto; + at = self.input.at(at.next_pos()); + } else { + return false; + } + } + Ranges(ref inst) => { + if inst.matches(at.char()) { + ip = inst.goto; + at = self.input.at(at.next_pos()); + } else { + return false; + } + } + Bytes(ref inst) => { + if let Some(b) = at.byte() { + if inst.matches(b) { + ip = inst.goto; + at = self.input.at(at.next_pos()); + continue; + } + } + return false; + } + } + } + } + + fn has_visited(&mut self, ip: InstPtr, at: InputAt) -> bool { + let k = ip * (self.input.len() + 1) + at.pos(); + let k1 = k / BIT_SIZE; + let k2 = usize_to_u32(1 << (k & (BIT_SIZE - 1))); + if self.m.visited[k1] & k2 == 0 { + self.m.visited[k1] |= k2; + false + } else { + true + } + } +} + +fn usize_to_u32(n: usize) -> u32 { + if (n as u64) > (::std::u32::MAX as u64) { + panic!("BUG: {} is too big to fit into u32", n) + } + n as u32 +} diff --git a/bash-5.1/vendor/regex/src/compile.rs b/bash-5.1/vendor/regex/src/compile.rs new file mode 100644 index 0000000..c765f01 --- /dev/null +++ b/bash-5.1/vendor/regex/src/compile.rs @@ -0,0 +1,1151 @@ +// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::collections::HashMap; +use std::iter; +use std::result; +use std::sync::Arc; + +use syntax::is_word_byte; +use syntax::hir::{self, Hir}; +use utf8_ranges::{Utf8Range, Utf8Sequence, Utf8Sequences}; + +use prog::{ + Program, Inst, InstPtr, EmptyLook, + InstSave, InstSplit, InstEmptyLook, InstChar, InstRanges, InstBytes, +}; + +use Error; + +type Result = result::Result; + +#[derive(Debug)] +struct Patch { + hole: Hole, + entry: InstPtr, +} + +/// A compiler translates a regular expression AST to a sequence of +/// instructions. The sequence of instructions represents an NFA. +pub struct Compiler { + insts: Vec, + compiled: Program, + capture_name_idx: HashMap, + num_exprs: usize, + size_limit: usize, + suffix_cache: SuffixCache, + utf8_seqs: Option, + byte_classes: ByteClassSet, +} + +impl Compiler { + /// Create a new regular expression compiler. + /// + /// Various options can be set before calling `compile` on an expression. + pub fn new() -> Self { + Compiler { + insts: vec![], + compiled: Program::new(), + capture_name_idx: HashMap::new(), + num_exprs: 0, + size_limit: 10 * (1 << 20), + suffix_cache: SuffixCache::new(1000), + utf8_seqs: Some(Utf8Sequences::new('\x00', '\x00')), + byte_classes: ByteClassSet::new(), + } + } + + /// The size of the resulting program is limited by size_limit. If + /// the program approximately exceeds the given size (in bytes), then + /// compilation will stop and return an error. + pub fn size_limit(mut self, size_limit: usize) -> Self { + self.size_limit = size_limit; + self + } + + /// If bytes is true, then the program is compiled as a byte based + /// automaton, which incorporates UTF-8 decoding into the machine. If it's + /// false, then the automaton is Unicode scalar value based, e.g., an + /// engine utilizing such an automaton is resposible for UTF-8 decoding. + /// + /// The specific invariant is that when returning a byte based machine, + /// the neither the `Char` nor `Ranges` instructions are produced. + /// Conversely, when producing a Unicode scalar value machine, the `Bytes` + /// instruction is never produced. + /// + /// Note that `dfa(true)` implies `bytes(true)`. + pub fn bytes(mut self, yes: bool) -> Self { + self.compiled.is_bytes = yes; + self + } + + /// When disabled, the program compiled may match arbitrary bytes. + /// + /// When enabled (the default), all compiled programs exclusively match + /// valid UTF-8 bytes. + pub fn only_utf8(mut self, yes: bool) -> Self { + self.compiled.only_utf8 = yes; + self + } + + /// When set, the machine returned is suitable for use in the DFA matching + /// engine. + /// + /// In particular, this ensures that if the regex is not anchored in the + /// beginning, then a preceding `.*?` is included in the program. (The NFA + /// based engines handle the preceding `.*?` explicitly, which is difficult + /// or impossible in the DFA engine.) + pub fn dfa(mut self, yes: bool) -> Self { + self.compiled.is_dfa = yes; + self + } + + /// When set, the machine returned is suitable for matching text in + /// reverse. In particular, all concatenations are flipped. + pub fn reverse(mut self, yes: bool) -> Self { + self.compiled.is_reverse = yes; + self + } + + /// Compile a regular expression given its AST. + /// + /// The compiler is guaranteed to succeed unless the program exceeds the + /// specified size limit. If the size limit is exceeded, then compilation + /// stops and returns an error. + pub fn compile( + mut self, + exprs: &[Hir], + ) -> result::Result { + debug_assert!(exprs.len() >= 1); + self.num_exprs = exprs.len(); + if exprs.len() == 1 { + self.compile_one(&exprs[0]) + } else { + self.compile_many(exprs) + } + } + + fn compile_one(mut self, expr: &Hir) -> result::Result { + // If we're compiling a forward DFA and we aren't anchored, then + // add a `.*?` before the first capture group. + // Other matching engines handle this by baking the logic into the + // matching engine itself. + let mut dotstar_patch = Patch { hole: Hole::None, entry: 0 }; + self.compiled.is_anchored_start = expr.is_anchored_start(); + self.compiled.is_anchored_end = expr.is_anchored_end(); + if self.compiled.needs_dotstar() { + dotstar_patch = try!(self.c_dotstar()); + self.compiled.start = dotstar_patch.entry; + } + self.compiled.captures = vec![None]; + let patch = try!(self.c_capture(0, expr)); + if self.compiled.needs_dotstar() { + self.fill(dotstar_patch.hole, patch.entry); + } else { + self.compiled.start = patch.entry; + } + self.fill_to_next(patch.hole); + self.compiled.matches = vec![self.insts.len()]; + self.push_compiled(Inst::Match(0)); + self.compile_finish() + } + + fn compile_many( + mut self, + exprs: &[Hir], + ) -> result::Result { + debug_assert!(exprs.len() > 1); + + self.compiled.is_anchored_start = + exprs.iter().all(|e| e.is_anchored_start()); + self.compiled.is_anchored_end = + exprs.iter().all(|e| e.is_anchored_end()); + let mut dotstar_patch = Patch { hole: Hole::None, entry: 0 }; + if self.compiled.needs_dotstar() { + dotstar_patch = try!(self.c_dotstar()); + self.compiled.start = dotstar_patch.entry; + } else { + self.compiled.start = 0; // first instruction is always split + } + self.fill_to_next(dotstar_patch.hole); + + let mut prev_hole = Hole::None; + for (i, expr) in exprs[0..exprs.len() - 1].iter().enumerate() { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let Patch { hole, entry } = try!(self.c_capture(0, expr)); + self.fill_to_next(hole); + self.compiled.matches.push(self.insts.len()); + self.push_compiled(Inst::Match(i)); + prev_hole = self.fill_split(split, Some(entry), None); + } + let i = exprs.len() - 1; + let Patch { hole, entry } = try!(self.c_capture(0, &exprs[i])); + self.fill(prev_hole, entry); + self.fill_to_next(hole); + self.compiled.matches.push(self.insts.len()); + self.push_compiled(Inst::Match(i)); + self.compile_finish() + } + + fn compile_finish(mut self) -> result::Result { + self.compiled.insts = + self.insts.into_iter().map(|inst| inst.unwrap()).collect(); + self.compiled.byte_classes = self.byte_classes.byte_classes(); + self.compiled.capture_name_idx = Arc::new(self.capture_name_idx); + Ok(self.compiled) + } + + /// Compile expr into self.insts, returning a patch on success, + /// or an error if we run out of memory. + /// + /// All of the c_* methods of the compiler share the contract outlined + /// here. + /// + /// The main thing that a c_* method does is mutate `self.insts` + /// to add a list of mostly compiled instructions required to execute + /// the given expression. `self.insts` contains MaybeInsts rather than + /// Insts because there is some backpatching required. + /// + /// The `Patch` value returned by each c_* method provides metadata + /// about the compiled instructions emitted to `self.insts`. The + /// `entry` member of the patch refers to the first instruction + /// (the entry point), while the `hole` member contains zero or + /// more offsets to partial instructions that need to be backpatched. + /// The c_* routine can't know where its list of instructions are going to + /// jump to after execution, so it is up to the caller to patch + /// these jumps to point to the right place. So compiling some + /// expression, e, we would end up with a situation that looked like: + /// + /// ```text + /// self.insts = [ ..., i1, i2, ..., iexit1, ..., iexitn, ...] + /// ^ ^ ^ + /// | \ / + /// entry \ / + /// hole + /// ``` + /// + /// To compile two expressions, e1 and e2, concatinated together we + /// would do: + /// + /// ```ignore + /// let patch1 = self.c(e1); + /// let patch2 = self.c(e2); + /// ``` + /// + /// while leaves us with a situation that looks like + /// + /// ```text + /// self.insts = [ ..., i1, ..., iexit1, ..., i2, ..., iexit2 ] + /// ^ ^ ^ ^ + /// | | | | + /// entry1 hole1 entry2 hole2 + /// ``` + /// + /// Then to merge the two patches together into one we would backpatch + /// hole1 with entry2 and return a new patch that enters at entry1 + /// and has hole2 for a hole. In fact, if you look at the c_concat + /// method you will see that it does exactly this, though it handles + /// a list of expressions rather than just the two that we use for + /// an example. + fn c(&mut self, expr: &Hir) -> Result { + use prog; + use syntax::hir::HirKind::*; + + try!(self.check_size()); + match *expr.kind() { + Empty => Ok(Patch { hole: Hole::None, entry: self.insts.len() }), + Literal(hir::Literal::Unicode(c)) => { + self.c_literal(&[c]) + } + Literal(hir::Literal::Byte(b)) => { + assert!(self.compiled.uses_bytes()); + self.c_bytes(&[b]) + } + Class(hir::Class::Unicode(ref cls)) => { + self.c_class(cls.ranges()) + } + Class(hir::Class::Bytes(ref cls)) => { + if self.compiled.uses_bytes() { + self.c_class_bytes(cls.ranges()) + } else { + assert!(cls.is_all_ascii()); + let mut char_ranges = vec![]; + for r in cls.iter() { + let (s, e) = (r.start() as char, r.end() as char); + char_ranges.push(hir::ClassUnicodeRange::new(s, e)); + } + self.c_class(&char_ranges) + } + } + Anchor(hir::Anchor::StartLine) if self.compiled.is_reverse => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::EndLine) + } + Anchor(hir::Anchor::StartLine) => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::StartLine) + } + Anchor(hir::Anchor::EndLine) if self.compiled.is_reverse => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::StartLine) + } + Anchor(hir::Anchor::EndLine) => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::EndLine) + } + Anchor(hir::Anchor::StartText) if self.compiled.is_reverse => { + self.c_empty_look(prog::EmptyLook::EndText) + } + Anchor(hir::Anchor::StartText) => { + self.c_empty_look(prog::EmptyLook::StartText) + } + Anchor(hir::Anchor::EndText) if self.compiled.is_reverse => { + self.c_empty_look(prog::EmptyLook::StartText) + } + Anchor(hir::Anchor::EndText) => { + self.c_empty_look(prog::EmptyLook::EndText) + } + WordBoundary(hir::WordBoundary::Unicode) => { + self.compiled.has_unicode_word_boundary = true; + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::WordBoundary) + } + WordBoundary(hir::WordBoundary::UnicodeNegate) => { + self.compiled.has_unicode_word_boundary = true; + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::NotWordBoundary) + } + WordBoundary(hir::WordBoundary::Ascii) => { + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::WordBoundaryAscii) + } + WordBoundary(hir::WordBoundary::AsciiNegate) => { + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::NotWordBoundaryAscii) + } + Group(ref g) => { + match g.kind { + hir::GroupKind::NonCapturing => self.c(&g.hir), + hir::GroupKind::CaptureIndex(index) => { + if index as usize >= self.compiled.captures.len() { + self.compiled.captures.push(None); + } + self.c_capture(2 * index as usize, &g.hir) + } + hir::GroupKind::CaptureName { index, ref name } => { + if index as usize >= self.compiled.captures.len() { + let n = name.to_string(); + self.compiled.captures.push(Some(n.clone())); + self.capture_name_idx.insert(n, index as usize); + } + self.c_capture(2 * index as usize, &g.hir) + } + } + } + Concat(ref es) => { + if self.compiled.is_reverse { + self.c_concat(es.iter().rev()) + } else { + self.c_concat(es) + } + } + Alternation(ref es) => self.c_alternate(&**es), + Repetition(ref rep) => self.c_repeat(rep), + } + } + + fn c_capture(&mut self, first_slot: usize, expr: &Hir) -> Result { + if self.num_exprs > 1 || self.compiled.is_dfa { + // Don't ever compile Save instructions for regex sets because + // they are never used. They are also never used in DFA programs + // because DFAs can't handle captures. + self.c(expr) + } else { + let entry = self.insts.len(); + let hole = self.push_hole(InstHole::Save { slot: first_slot }); + let patch = try!(self.c(expr)); + self.fill(hole, patch.entry); + self.fill_to_next(patch.hole); + let hole = self.push_hole(InstHole::Save { slot: first_slot + 1 }); + Ok(Patch { hole: hole, entry: entry }) + } + } + + fn c_dotstar(&mut self) -> Result { + Ok(if !self.compiled.only_utf8() { + try!(self.c(&Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: false, + hir: Box::new(Hir::any(true)), + }))) + } else { + try!(self.c(&Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: false, + hir: Box::new(Hir::any(false)), + }))) + }) + } + + fn c_literal(&mut self, chars: &[char]) -> Result { + debug_assert!(!chars.is_empty()); + let mut chars: Box> = + if self.compiled.is_reverse { + Box::new(chars.iter().rev()) + } else { + Box::new(chars.iter()) + }; + let first = *chars.next().expect("non-empty literal"); + let Patch { mut hole, entry } = try!(self.c_char(first)); + for &c in chars { + let p = try!(self.c_char(c)); + self.fill(hole, p.entry); + hole = p.hole; + } + Ok(Patch { hole: hole, entry: entry }) + } + + fn c_char(&mut self, c: char) -> Result { + self.c_class(&[hir::ClassUnicodeRange::new(c, c)]) + } + + fn c_class(&mut self, ranges: &[hir::ClassUnicodeRange]) -> Result { + assert!(!ranges.is_empty()); + if self.compiled.uses_bytes() { + CompileClass { + c: self, + ranges: ranges, + }.compile() + } else { + let ranges: Vec<(char, char)> = + ranges.iter().map(|r| (r.start(), r.end())).collect(); + let hole = if ranges.len() == 1 && ranges[0].0 == ranges[0].1 { + self.push_hole(InstHole::Char { c: ranges[0].0 }) + } else { + self.push_hole(InstHole::Ranges { ranges: ranges }) + }; + Ok(Patch { hole: hole, entry: self.insts.len() - 1 }) + } + } + + fn c_bytes(&mut self, bytes: &[u8]) -> Result { + debug_assert!(!bytes.is_empty()); + let mut bytes: Box> = + if self.compiled.is_reverse { + Box::new(bytes.iter().rev()) + } else { + Box::new(bytes.iter()) + }; + let first = *bytes.next().expect("non-empty literal"); + let Patch { mut hole, entry } = try!(self.c_byte(first)); + for &b in bytes { + let p = try!(self.c_byte(b)); + self.fill(hole, p.entry); + hole = p.hole; + } + Ok(Patch { hole: hole, entry: entry }) + } + + fn c_byte(&mut self, b: u8) -> Result { + self.c_class_bytes(&[hir::ClassBytesRange::new(b, b)]) + } + + fn c_class_bytes(&mut self, ranges: &[hir::ClassBytesRange]) -> Result { + debug_assert!(!ranges.is_empty()); + + let first_split_entry = self.insts.len(); + let mut holes = vec![]; + let mut prev_hole = Hole::None; + for r in &ranges[0..ranges.len() - 1] { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let next = self.insts.len(); + self.byte_classes.set_range(r.start(), r.end()); + holes.push(self.push_hole(InstHole::Bytes { + start: r.start(), end: r.end(), + })); + prev_hole = self.fill_split(split, Some(next), None); + } + let next = self.insts.len(); + let r = &ranges[ranges.len() - 1]; + self.byte_classes.set_range(r.start(), r.end()); + holes.push(self.push_hole(InstHole::Bytes { + start: r.start(), end: r.end(), + })); + self.fill(prev_hole, next); + Ok(Patch { hole: Hole::Many(holes), entry: first_split_entry }) + } + + fn c_empty_look(&mut self, look: EmptyLook) -> Result { + let hole = self.push_hole(InstHole::EmptyLook { look: look }); + Ok(Patch { hole: hole, entry: self.insts.len() - 1 }) + } + + fn c_concat<'a, I>(&mut self, exprs: I) -> Result + where I: IntoIterator { + let mut exprs = exprs.into_iter(); + let first = match exprs.next() { + Some(expr) => expr, + None => { + return Ok(Patch { hole: Hole::None, entry: self.insts.len() }) + } + }; + let Patch { mut hole, entry } = try!(self.c(first)); + for e in exprs { + let p = try!(self.c(e)); + self.fill(hole, p.entry); + hole = p.hole; + } + Ok(Patch { hole: hole, entry: entry }) + } + + fn c_alternate(&mut self, exprs: &[Hir]) -> Result { + debug_assert!( + exprs.len() >= 2, "alternates must have at least 2 exprs"); + + // Initial entry point is always the first split. + let first_split_entry = self.insts.len(); + + // Save up all of the holes from each alternate. They will all get + // patched to point to the same location. + let mut holes = vec![]; + + let mut prev_hole = Hole::None; + for e in &exprs[0..exprs.len() - 1] { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let prev_entry = self.insts.len(); + let Patch { hole, entry } = try!(self.c(e)); + if prev_entry == self.insts.len() { + // TODO(burntsushi): It is kind of silly that we don't support + // empty-subexpressions in alternates, but it is supremely + // awkward to support them in the existing compiler + // infrastructure. This entire compiler needs to be thrown out + // anyway, so don't feel too bad. + return Err(Error::Syntax( + "alternations cannot currently contain \ + empty sub-expressions".to_string())); + } + holes.push(hole); + prev_hole = self.fill_split(split, Some(entry), None); + } + let prev_entry = self.insts.len(); + let Patch { hole, entry } = try!(self.c(&exprs[exprs.len() - 1])); + if prev_entry == self.insts.len() { + // TODO(burntsushi): See TODO above. + return Err(Error::Syntax( + "alternations cannot currently contain \ + empty sub-expressions".to_string())); + } + holes.push(hole); + self.fill(prev_hole, entry); + Ok(Patch { hole: Hole::Many(holes), entry: first_split_entry }) + } + + fn c_repeat(&mut self, rep: &hir::Repetition) -> Result { + use syntax::hir::RepetitionKind::*; + match rep.kind { + ZeroOrOne => self.c_repeat_zero_or_one(&rep.hir, rep.greedy), + ZeroOrMore => self.c_repeat_zero_or_more(&rep.hir, rep.greedy), + OneOrMore => self.c_repeat_one_or_more(&rep.hir, rep.greedy), + Range(hir::RepetitionRange::Exactly(min_max)) => { + self.c_repeat_range(&rep.hir, rep.greedy, min_max, min_max) + } + Range(hir::RepetitionRange::AtLeast(min)) => { + self.c_repeat_range_min_or_more(&rep.hir, rep.greedy, min) + } + Range(hir::RepetitionRange::Bounded(min, max)) => { + self.c_repeat_range(&rep.hir, rep.greedy, min, max) + } + } + } + + fn c_repeat_zero_or_one(&mut self, expr: &Hir, greedy: bool) -> Result { + let split_entry = self.insts.len(); + let split = self.push_split_hole(); + let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); + + let split_hole = if greedy { + self.fill_split(split, Some(entry_rep), None) + } else { + self.fill_split(split, None, Some(entry_rep)) + }; + let holes = vec![hole_rep, split_hole]; + Ok(Patch { hole: Hole::Many(holes), entry: split_entry }) + } + + fn c_repeat_zero_or_more(&mut self, expr: &Hir, greedy: bool) -> Result { + let split_entry = self.insts.len(); + let split = self.push_split_hole(); + let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); + + self.fill(hole_rep, split_entry); + let split_hole = if greedy { + self.fill_split(split, Some(entry_rep), None) + } else { + self.fill_split(split, None, Some(entry_rep)) + }; + Ok(Patch { hole: split_hole, entry: split_entry }) + } + + fn c_repeat_one_or_more(&mut self, expr: &Hir, greedy: bool) -> Result { + let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); + self.fill_to_next(hole_rep); + let split = self.push_split_hole(); + + let split_hole = if greedy { + self.fill_split(split, Some(entry_rep), None) + } else { + self.fill_split(split, None, Some(entry_rep)) + }; + Ok(Patch { hole: split_hole, entry: entry_rep }) + } + + fn c_repeat_range_min_or_more( + &mut self, + expr: &Hir, + greedy: bool, + min: u32, + ) -> Result { + let min = u32_to_usize(min); + let patch_concat = try!(self.c_concat(iter::repeat(expr).take(min))); + let patch_rep = try!(self.c_repeat_zero_or_more(expr, greedy)); + self.fill(patch_concat.hole, patch_rep.entry); + Ok(Patch { hole: patch_rep.hole, entry: patch_concat.entry }) + } + + fn c_repeat_range( + &mut self, + expr: &Hir, + greedy: bool, + min: u32, + max: u32, + ) -> Result { + let (min, max) = (u32_to_usize(min), u32_to_usize(max)); + let patch_concat = try!(self.c_concat(iter::repeat(expr).take(min))); + let initial_entry = patch_concat.entry; + if min == max { + return Ok(patch_concat); + } + // It is much simpler to compile, e.g., `a{2,5}` as: + // + // aaa?a?a? + // + // But you end up with a sequence of instructions like this: + // + // 0: 'a' + // 1: 'a', + // 2: split(3, 4) + // 3: 'a' + // 4: split(5, 6) + // 5: 'a' + // 6: split(7, 8) + // 7: 'a' + // 8: MATCH + // + // This is *incredibly* inefficient because the splits end + // up forming a chain, which has to be resolved everything a + // transition is followed. + let mut holes = vec![]; + let mut prev_hole = patch_concat.hole; + for _ in min..max { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let Patch { hole, entry } = try!(self.c(expr)); + prev_hole = hole; + if greedy { + holes.push(self.fill_split(split, Some(entry), None)); + } else { + holes.push(self.fill_split(split, None, Some(entry))); + } + } + holes.push(prev_hole); + Ok(Patch { hole: Hole::Many(holes), entry: initial_entry }) + } + + fn fill(&mut self, hole: Hole, goto: InstPtr) { + match hole { + Hole::None => {} + Hole::One(pc) => { + self.insts[pc].fill(goto); + } + Hole::Many(holes) => { + for hole in holes { + self.fill(hole, goto); + } + } + } + } + + fn fill_to_next(&mut self, hole: Hole) { + let next = self.insts.len(); + self.fill(hole, next); + } + + fn fill_split( + &mut self, + hole: Hole, + goto1: Option, + goto2: Option, + ) -> Hole { + match hole { + Hole::None => Hole::None, + Hole::One(pc) => { + match (goto1, goto2) { + (Some(goto1), Some(goto2)) => { + self.insts[pc].fill_split(goto1, goto2); + Hole::None + } + (Some(goto1), None) => { + self.insts[pc].half_fill_split_goto1(goto1); + Hole::One(pc) + } + (None, Some(goto2)) => { + self.insts[pc].half_fill_split_goto2(goto2); + Hole::One(pc) + } + (None, None) => unreachable!("at least one of the split \ + holes must be filled"), + } + } + Hole::Many(holes) => { + let mut new_holes = vec![]; + for hole in holes { + new_holes.push(self.fill_split(hole, goto1, goto2)); + } + if new_holes.is_empty() { + Hole::None + } else if new_holes.len() == 1 { + new_holes.pop().unwrap() + } else { + Hole::Many(new_holes) + } + } + } + } + + fn push_compiled(&mut self, inst: Inst) { + self.insts.push(MaybeInst::Compiled(inst)); + } + + fn push_hole(&mut self, inst: InstHole) -> Hole { + let hole = self.insts.len(); + self.insts.push(MaybeInst::Uncompiled(inst)); + Hole::One(hole) + } + + fn push_split_hole(&mut self) -> Hole { + let hole = self.insts.len(); + self.insts.push(MaybeInst::Split); + Hole::One(hole) + } + + fn check_size(&self) -> result::Result<(), Error> { + use std::mem::size_of; + + if self.insts.len() * size_of::() > self.size_limit { + Err(Error::CompiledTooBig(self.size_limit)) + } else { + Ok(()) + } + } +} + +#[derive(Debug)] +enum Hole { + None, + One(InstPtr), + Many(Vec), +} + +#[derive(Clone, Debug)] +enum MaybeInst { + Compiled(Inst), + Uncompiled(InstHole), + Split, + Split1(InstPtr), + Split2(InstPtr), +} + +impl MaybeInst { + fn fill(&mut self, goto: InstPtr) { + let filled = match *self { + MaybeInst::Uncompiled(ref inst) => inst.fill(goto), + MaybeInst::Split1(goto1) => { + Inst::Split(InstSplit { goto1: goto1, goto2: goto }) + } + MaybeInst::Split2(goto2) => { + Inst::Split(InstSplit { goto1: goto, goto2: goto2 }) + } + _ => unreachable!("not all instructions were compiled! \ + found uncompiled instruction: {:?}", self), + }; + *self = MaybeInst::Compiled(filled); + } + + fn fill_split(&mut self, goto1: InstPtr, goto2: InstPtr) { + let filled = match *self { + MaybeInst::Split => { + Inst::Split(InstSplit { goto1: goto1, goto2: goto2 }) + } + _ => unreachable!("must be called on Split instruction, \ + instead it was called on: {:?}", self), + }; + *self = MaybeInst::Compiled(filled); + } + + fn half_fill_split_goto1(&mut self, goto1: InstPtr) { + let half_filled = match *self { + MaybeInst::Split => goto1, + _ => unreachable!("must be called on Split instruction, \ + instead it was called on: {:?}", self), + }; + *self = MaybeInst::Split1(half_filled); + } + + fn half_fill_split_goto2(&mut self, goto2: InstPtr) { + let half_filled = match *self { + MaybeInst::Split => goto2, + _ => unreachable!("must be called on Split instruction, \ + instead it was called on: {:?}", self), + }; + *self = MaybeInst::Split2(half_filled); + } + + fn unwrap(self) -> Inst { + match self { + MaybeInst::Compiled(inst) => inst, + _ => unreachable!("must be called on a compiled instruction, \ + instead it was called on: {:?}", self), + } + } +} + +#[derive(Clone, Debug)] +enum InstHole { + Save { slot: usize }, + EmptyLook { look: EmptyLook }, + Char { c: char }, + Ranges { ranges: Vec<(char, char)> }, + Bytes { start: u8, end: u8 }, +} + +impl InstHole { + fn fill(&self, goto: InstPtr) -> Inst { + match *self { + InstHole::Save { slot } => Inst::Save(InstSave { + goto: goto, + slot: slot, + }), + InstHole::EmptyLook { look } => Inst::EmptyLook(InstEmptyLook { + goto: goto, + look: look, + }), + InstHole::Char { c } => Inst::Char(InstChar { + goto: goto, + c: c, + }), + InstHole::Ranges { ref ranges } => Inst::Ranges(InstRanges { + goto: goto, + ranges: ranges.clone(), + }), + InstHole::Bytes { start, end } => Inst::Bytes(InstBytes { + goto: goto, + start: start, + end: end, + }), + } + } +} + +struct CompileClass<'a, 'b> { + c: &'a mut Compiler, + ranges: &'b [hir::ClassUnicodeRange], +} + +impl<'a, 'b> CompileClass<'a, 'b> { + fn compile(mut self) -> Result { + let mut holes = vec![]; + let mut initial_entry = None; + let mut last_split = Hole::None; + let mut utf8_seqs = self.c.utf8_seqs.take().unwrap(); + self.c.suffix_cache.clear(); + + for (i, range) in self.ranges.iter().enumerate() { + let is_last_range = i + 1 == self.ranges.len(); + utf8_seqs.reset(range.start(), range.end()); + let mut it = (&mut utf8_seqs).peekable(); + loop { + let utf8_seq = match it.next() { + None => break, + Some(utf8_seq) => utf8_seq, + }; + if is_last_range && it.peek().is_none() { + let Patch { hole, entry } = try!(self.c_utf8_seq(&utf8_seq)); + holes.push(hole); + self.c.fill(last_split, entry); + last_split = Hole::None; + if initial_entry.is_none() { + initial_entry = Some(entry); + } + } else { + if initial_entry.is_none() { + initial_entry = Some(self.c.insts.len()); + } + self.c.fill_to_next(last_split); + last_split = self.c.push_split_hole(); + let Patch { hole, entry } = try!(self.c_utf8_seq(&utf8_seq)); + holes.push(hole); + last_split = self.c.fill_split(last_split, Some(entry), None); + } + } + } + self.c.utf8_seqs = Some(utf8_seqs); + Ok(Patch { + hole: Hole::Many(holes), + entry: initial_entry.unwrap(), + }) + } + + fn c_utf8_seq(&mut self, seq: &Utf8Sequence) -> Result { + if self.c.compiled.is_reverse { + self.c_utf8_seq_(seq) + } else { + self.c_utf8_seq_(seq.into_iter().rev()) + } + } + + fn c_utf8_seq_<'r, I>(&mut self, seq: I) -> Result + where I: IntoIterator { + // The initial instruction for each UTF-8 sequence should be the same. + let mut from_inst = ::std::usize::MAX; + let mut last_hole = Hole::None; + for byte_range in seq { + let key = SuffixCacheKey { + from_inst: from_inst, + start: byte_range.start, + end: byte_range.end, + }; + { + let pc = self.c.insts.len(); + if let Some(cached_pc) = self.c.suffix_cache.get(key, pc) { + from_inst = cached_pc; + continue; + } + } + self.c.byte_classes.set_range(byte_range.start, byte_range.end); + if from_inst == ::std::usize::MAX { + last_hole = self.c.push_hole(InstHole::Bytes { + start: byte_range.start, + end: byte_range.end, + }); + } else { + self.c.push_compiled(Inst::Bytes(InstBytes { + goto: from_inst, + start: byte_range.start, + end: byte_range.end, + })); + } + from_inst = self.c.insts.len().checked_sub(1).unwrap(); + debug_assert!(from_inst < ::std::usize::MAX); + } + debug_assert!(from_inst < ::std::usize::MAX); + Ok(Patch { hole: last_hole, entry: from_inst }) + } +} + +/// `SuffixCache` is a simple bounded hash map for caching suffix entries in +/// UTF-8 automata. For example, consider the Unicode range \u{0}-\u{FFFF}. +/// The set of byte ranges looks like this: +/// +/// [0-7F] +/// [C2-DF][80-BF] +/// [E0][A0-BF][80-BF] +/// [E1-EC][80-BF][80-BF] +/// [ED][80-9F][80-BF] +/// [EE-EF][80-BF][80-BF] +/// +/// Each line above translates to one alternate in the compiled regex program. +/// However, all but one of the alternates end in the same suffix, which is +/// a waste of an instruction. The suffix cache facilitates reusing them across +/// alternates. +/// +/// Note that a HashMap could be trivially used for this, but we don't need its +/// overhead. Some small bounded space (LRU style) is more than enough. +struct SuffixCache { + table: Vec, + // Every time the cache is cleared, we increment the version number instead + // of actually zeroing memory. Since we store a copy of the current version + // in every element, all we need to do is make sure to invalidate any stale + // entries upon access. This saves quite a bit of time! + version: usize, +} + +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +struct SuffixCacheEntry { + key: SuffixCacheKey, + pc: InstPtr, + version: usize, +} + +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +struct SuffixCacheKey { + from_inst: InstPtr, + start: u8, + end: u8, +} + +impl SuffixCache { + fn new(size: usize) -> Self { + SuffixCache { + table: vec![SuffixCacheEntry::default(); size], + version: 0, + } + } + + fn get(&mut self, key: SuffixCacheKey, pc: InstPtr) -> Option { + let h = self.hash(&key); + let e = self.table[h]; + if e.key == key && e.version == self.version { + Some(e.pc) + } else { + self.table[h] = SuffixCacheEntry { + key: key, + pc: pc, + version: self.version, + }; + None + } + } + + fn clear(&mut self) { + self.version += 1; + } + + fn hash(&self, suffix: &SuffixCacheKey) -> usize { + // Basic FNV-1a hash as described: + // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function + const FNV_PRIME: u64 = 1099511628211; + let mut h = 14695981039346656037; + h = (h ^ (suffix.from_inst as u64)).wrapping_mul(FNV_PRIME); + h = (h ^ (suffix.start as u64)).wrapping_mul(FNV_PRIME); + h = (h ^ (suffix.end as u64)).wrapping_mul(FNV_PRIME); + (h as usize) % self.table.len() + } +} + +struct ByteClassSet([bool; 256]); + +impl ByteClassSet { + fn new() -> Self { + ByteClassSet([false; 256]) + } + + fn set_range(&mut self, start: u8, end: u8) { + debug_assert!(start <= end); + if start > 0 { + self.0[start as usize - 1] = true; + } + self.0[end as usize] = true; + } + + fn set_word_boundary(&mut self) { + // We need to mark all ranges of bytes whose pairs result in + // evaluating \b differently. + let iswb = is_word_byte; + let mut b1: u16 = 0; + let mut b2: u16; + while b1 <= 255 { + b2 = b1 + 1; + while b2 <= 255 && iswb(b1 as u8) == iswb(b2 as u8) { + b2 += 1; + } + self.set_range(b1 as u8, (b2 - 1) as u8); + b1 = b2; + } + } + + fn byte_classes(&self) -> Vec { + // N.B. If you're debugging the DFA, it's useful to simply return + // `(0..256).collect()`, which effectively removes the byte classes + // and makes the transitions easier to read. + // (0usize..256).map(|x| x as u8).collect() + let mut byte_classes = vec![0; 256]; + let mut class = 0u8; + let mut i = 0; + loop { + byte_classes[i] = class as u8; + if i >= 255 { + break; + } + if self.0[i] { + class = class.checked_add(1).unwrap(); + } + i += 1; + } + byte_classes + } +} + +fn u32_to_usize(n: u32) -> usize { + // In case usize is less than 32 bits, we need to guard against overflow. + // On most platforms this compiles to nothing. + // TODO Use `std::convert::TryFrom` once it's stable. + if (n as u64) > (::std::usize::MAX as u64) { + panic!("BUG: {} is too big to be pointer sized", n) + } + n as usize +} + +#[cfg(test)] +mod tests { + use super::ByteClassSet; + + #[test] + fn byte_classes() { + let mut set = ByteClassSet::new(); + set.set_range(b'a', b'z'); + let classes = set.byte_classes(); + assert_eq!(classes[0], 0); + assert_eq!(classes[1], 0); + assert_eq!(classes[2], 0); + assert_eq!(classes[b'a' as usize - 1], 0); + assert_eq!(classes[b'a' as usize], 1); + assert_eq!(classes[b'm' as usize], 1); + assert_eq!(classes[b'z' as usize], 1); + assert_eq!(classes[b'z' as usize + 1], 2); + assert_eq!(classes[254], 2); + assert_eq!(classes[255], 2); + + let mut set = ByteClassSet::new(); + set.set_range(0, 2); + set.set_range(4, 6); + let classes = set.byte_classes(); + assert_eq!(classes[0], 0); + assert_eq!(classes[1], 0); + assert_eq!(classes[2], 0); + assert_eq!(classes[3], 1); + assert_eq!(classes[4], 2); + assert_eq!(classes[5], 2); + assert_eq!(classes[6], 2); + assert_eq!(classes[7], 3); + assert_eq!(classes[255], 3); + } + + #[test] + fn full_byte_classes() { + let mut set = ByteClassSet::new(); + for i in 0..256u16 { + set.set_range(i as u8, i as u8); + } + assert_eq!(set.byte_classes().len(), 256); + } +} diff --git a/bash-5.1/vendor/regex/src/dfa.rs b/bash-5.1/vendor/regex/src/dfa.rs new file mode 100644 index 0000000..992a45c --- /dev/null +++ b/bash-5.1/vendor/regex/src/dfa.rs @@ -0,0 +1,1894 @@ +// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +The DFA matching engine. + +A DFA provides faster matching because the engine is in exactly one state at +any point in time. In the NFA, there may be multiple active states, and +considerable CPU cycles are spent shuffling them around. In finite automata +speak, the DFA follows epsilon transitions in the regex far less than the NFA. + +A DFA is a classic trade off between time and space. The NFA is slower, but +its memory requirements are typically small and predictable. The DFA is faster, +but given the right regex and the right input, the number of states in the +DFA can grow exponentially. To mitigate this space problem, we do two things: + +1. We implement an *online* DFA. That is, the DFA is constructed from the NFA + during a search. When a new state is computed, it is stored in a cache so + that it may be reused. An important consequence of this implementation + is that states that are never reached for a particular input are never + computed. (This is impossible in an "offline" DFA which needs to compute + all possible states up front.) +2. If the cache gets too big, we wipe it and continue matching. + +In pathological cases, a new state can be created for every byte of input. +(e.g., The regex `(a|b)*a(a|b){20}` on a long sequence of a's and b's.) +In this case, performance regresses to slightly slower than the full NFA +simulation, in large part because the cache becomes useless. If the cache +is wiped too frequently, the DFA quits and control falls back to one of the +NFA simulations. + +Because of the "lazy" nature of this DFA, the inner matching loop is +considerably more complex than one might expect out of a DFA. A number of +tricks are employed to make it fast. Tread carefully. + +N.B. While this implementation is heavily commented, Russ Cox's series of +articles on regexes is strongly recommended: https://swtch.com/~rsc/regexp/ +(As is the DFA implementation in RE2, which heavily influenced this +implementation.) +*/ + +use std::collections::HashMap; +use std::fmt; +use std::iter::repeat; +use std::mem; + +use exec::ProgramCache; +use prog::{Inst, Program}; +use sparse::SparseSet; + +/// Return true if and only if the given program can be executed by a DFA. +/// +/// Generally, a DFA is always possible. A pathological case where it is not +/// possible is if the number of NFA states exceeds `u32::MAX`, in which case, +/// this function will return false. +/// +/// This function will also return false if the given program has any Unicode +/// instructions (Char or Ranges) since the DFA operates on bytes only. +pub fn can_exec(insts: &Program) -> bool { + use prog::Inst::*; + // If for some reason we manage to allocate a regex program with more + // than i32::MAX instructions, then we can't execute the DFA because we + // use 32 bit instruction pointer deltas for memory savings. + // If i32::MAX is the largest positive delta, + // then -i32::MAX == i32::MIN + 1 is the largest negative delta, + // and we are OK to use 32 bits. + if insts.dfa_size_limit == 0 || insts.len() > ::std::i32::MAX as usize { + return false; + } + for inst in insts { + match *inst { + Char(_) | Ranges(_) => return false, + EmptyLook(_) | Match(_) | Save(_) | Split(_) | Bytes(_) => {} + } + } + true +} + +/// A reusable cache of DFA states. +/// +/// This cache is reused between multiple invocations of the same regex +/// program. (It is not shared simultaneously between threads. If there is +/// contention, then new caches are created.) +#[derive(Clone, Debug)] +pub struct Cache { + /// Group persistent DFA related cache state together. The sparse sets + /// listed below are used as scratch space while computing uncached states. + inner: CacheInner, + /// qcur and qnext are ordered sets with constant time + /// addition/membership/clearing-whole-set and linear time iteration. They + /// are used to manage the sets of NFA states in DFA states when computing + /// cached DFA states. In particular, the order of the NFA states matters + /// for leftmost-first style matching. Namely, when computing a cached + /// state, the set of NFA states stops growing as soon as the first Match + /// instruction is observed. + qcur: SparseSet, + qnext: SparseSet, +} + +/// `CacheInner` is logically just a part of Cache, but groups together fields +/// that aren't passed as function parameters throughout search. (This split +/// is mostly an artifact of the borrow checker. It is happily paid.) +#[derive(Clone, Debug)] +struct CacheInner { + /// A cache of pre-compiled DFA states, keyed by the set of NFA states + /// and the set of empty-width flags set at the byte in the input when the + /// state was observed. + /// + /// A StatePtr is effectively a `*State`, but to avoid various inconvenient + /// things, we just pass indexes around manually. The performance impact of + /// this is probably an instruction or two in the inner loop. However, on + /// 64 bit, each StatePtr is half the size of a *State. + compiled: HashMap, + /// The transition table. + /// + /// The transition table is laid out in row-major order, where states are + /// rows and the transitions for each state are columns. At a high level, + /// given state `s` and byte `b`, the next state can be found at index + /// `s * 256 + b`. + /// + /// This is, of course, a lie. A StatePtr is actually a pointer to the + /// *start* of a row in this table. When indexing in the DFA's inner loop, + /// this removes the need to multiply the StatePtr by the stride. Yes, it + /// matters. This reduces the number of states we can store, but: the + /// stride is rarely 256 since we define transitions in terms of + /// *equivalence classes* of bytes. Each class corresponds to a set of + /// bytes that never discriminate a distinct path through the DFA from each + /// other. + trans: Transitions, + /// Our set of states. Note that `StatePtr / num_byte_classes` indexes + /// this Vec rather than just a `StatePtr`. + states: Vec, + /// A set of cached start states, which are limited to the number of + /// permutations of flags set just before the initial byte of input. (The + /// index into this vec is a `EmptyFlags`.) + /// + /// N.B. A start state can be "dead" (i.e., no possible match), so we + /// represent it with a StatePtr. + start_states: Vec, + /// Stack scratch space used to follow epsilon transitions in the NFA. + /// (This permits us to avoid recursion.) + /// + /// The maximum stack size is the number of NFA states. + stack: Vec, + /// The total number of times this cache has been flushed by the DFA + /// because of space constraints. + flush_count: u64, + /// The total heap size of the DFA's cache. We use this to determine when + /// we should flush the cache. + size: usize, +} + +/// The transition table. +/// +/// It is laid out in row-major order, with states as rows and byte class +/// transitions as columns. +/// +/// The transition table is responsible for producing valid `StatePtrs`. A +/// `StatePtr` points to the start of a particular row in this table. When +/// indexing to find the next state this allows us to avoid a multiplication +/// when computing an index into the table. +#[derive(Clone)] +struct Transitions { + /// The table. + table: Vec, + /// The stride. + num_byte_classes: usize, +} + +/// Fsm encapsulates the actual execution of the DFA. +#[derive(Debug)] +pub struct Fsm<'a> { + /// prog contains the NFA instruction opcodes. DFA execution uses either + /// the `dfa` instructions or the `dfa_reverse` instructions from + /// `exec::ExecReadOnly`. (It never uses `ExecReadOnly.nfa`, which may have + /// Unicode opcodes that cannot be executed by the DFA.) + prog: &'a Program, + /// The start state. We record it here because the pointer may change + /// when the cache is wiped. + start: StatePtr, + /// The current position in the input. + at: usize, + /// Should we quit after seeing the first match? e.g., When the caller + /// uses `is_match` or `shortest_match`. + quit_after_match: bool, + /// The last state that matched. + /// + /// When no match has occurred, this is set to STATE_UNKNOWN. + /// + /// This is only useful when matching regex sets. The last match state + /// is useful because it contains all of the match instructions seen, + /// thereby allowing us to enumerate which regexes in the set matched. + last_match_si: StatePtr, + /// The input position of the last cache flush. We use this to determine + /// if we're thrashing in the cache too often. If so, the DFA quits so + /// that we can fall back to the NFA algorithm. + last_cache_flush: usize, + /// All cached DFA information that is persisted between searches. + cache: &'a mut CacheInner, +} + +/// The result of running the DFA. +/// +/// Generally, the result is either a match or not a match, but sometimes the +/// DFA runs too slowly because the cache size is too small. In that case, it +/// gives up with the intent of falling back to the NFA algorithm. +/// +/// The DFA can also give up if it runs out of room to create new states, or if +/// it sees non-ASCII bytes in the presence of a Unicode word boundary. +#[derive(Clone, Debug)] +pub enum Result { + Match(T), + NoMatch(usize), + Quit, +} + +impl Result { + /// Returns true if this result corresponds to a match. + pub fn is_match(&self) -> bool { + match *self { + Result::Match(_) => true, + Result::NoMatch(_) | Result::Quit => false, + } + } + + /// Maps the given function onto T and returns the result. + /// + /// If this isn't a match, then this is a no-op. + pub fn map U>(self, mut f: F) -> Result { + match self { + Result::Match(t) => Result::Match(f(t)), + Result::NoMatch(x) => Result::NoMatch(x), + Result::Quit => Result::Quit, + } + } + + /// Sets the non-match position. + /// + /// If this isn't a non-match, then this is a no-op. + fn set_non_match(self, at: usize) -> Result { + match self { + Result::NoMatch(_) => Result::NoMatch(at), + r => r, + } + } +} + +/// `State` is a DFA state. It contains an ordered set of NFA states (not +/// necessarily complete) and a smattering of flags. +/// +/// The flags are packed into the first byte of data. +/// +/// States don't carry their transitions. Instead, transitions are stored in +/// a single row-major table. +/// +/// Delta encoding is used to store the instruction pointers. +/// The first instruction pointer is stored directly starting +/// at data[1], and each following pointer is stored as an offset +/// to the previous one. If a delta is in the range -127..127, +/// it is packed into a single byte; Otherwise the byte 128 (-128 as an i8) +/// is coded as a flag, followed by 4 bytes encoding the delta. +#[derive(Clone, Eq, Hash, PartialEq)] +struct State{ + data: Box<[u8]>, +} + +/// `InstPtr` is a 32 bit pointer into a sequence of opcodes (i.e., it indexes +/// an NFA state). +/// +/// Throughout this library, this is usually set to `usize`, but we force a +/// `u32` here for the DFA to save on space. +type InstPtr = u32; + +/// Adds ip to data using delta encoding with respect to prev. +/// +/// After completion, `data` will contain `ip` and `prev` will be set to `ip`. +fn push_inst_ptr(data: &mut Vec, prev: &mut InstPtr, ip: InstPtr) { + let delta = (ip as i32) - (*prev as i32); + write_vari32(data, delta); + *prev = ip; +} + +struct InstPtrs<'a> { + base: usize, + data: &'a [u8], +} + +impl <'a>Iterator for InstPtrs<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + if self.data.is_empty() { + return None; + } + let (delta, nread) = read_vari32(self.data); + let base = self.base as i32 + delta; + debug_assert!(base >= 0); + debug_assert!(nread > 0); + self.data = &self.data[nread..]; + self.base = base as usize; + Some(self.base) + } +} + +impl State { + fn flags(&self) -> StateFlags { + StateFlags(self.data[0]) + } + + fn inst_ptrs(&self) -> InstPtrs { + InstPtrs { + base: 0, + data: &self.data[1..], + } + } +} + +/// `StatePtr` is a 32 bit pointer to the start of a row in the transition +/// table. +/// +/// It has many special values. There are two types of special values: +/// sentinels and flags. +/// +/// Sentinels corresponds to special states that carry some kind of +/// significance. There are three such states: unknown, dead and quit states. +/// +/// Unknown states are states that haven't been computed yet. They indicate +/// that a transition should be filled in that points to either an existing +/// cached state or a new state altogether. In general, an unknown state means +/// "follow the NFA's epsilon transitions." +/// +/// Dead states are states that can never lead to a match, no matter what +/// subsequent input is observed. This means that the DFA should quit +/// immediately and return the longest match it has found thus far. +/// +/// Quit states are states that imply the DFA is not capable of matching the +/// regex correctly. Currently, this is only used when a Unicode word boundary +/// exists in the regex *and* a non-ASCII byte is observed. +/// +/// The other type of state pointer is a state pointer with special flag bits. +/// There are two flags: a start flag and a match flag. The lower bits of both +/// kinds always contain a "valid" `StatePtr` (indicated by the `STATE_MAX` +/// mask). +/// +/// The start flag means that the state is a start state, and therefore may be +/// subject to special prefix scanning optimizations. +/// +/// The match flag means that the state is a match state, and therefore the +/// current position in the input (while searching) should be recorded. +/// +/// The above exists mostly in the service of making the inner loop fast. +/// In particular, the inner *inner* loop looks something like this: +/// +/// ```ignore +/// while state <= STATE_MAX and i < len(text): +/// state = state.next[i] +/// ``` +/// +/// This is nice because it lets us execute a lazy DFA as if it were an +/// entirely offline DFA (i.e., with very few instructions). The loop will +/// quit only when we need to examine a case that needs special attention. +type StatePtr = u32; + +/// An unknown state means that the state has not been computed yet, and that +/// the only way to progress is to compute it. +const STATE_UNKNOWN: StatePtr = 1<<31; + +/// A dead state means that the state has been computed and it is known that +/// once it is entered, no future match can ever occur. +const STATE_DEAD: StatePtr = STATE_UNKNOWN + 1; + +/// A quit state means that the DFA came across some input that it doesn't +/// know how to process correctly. The DFA should quit and another matching +/// engine should be run in its place. +const STATE_QUIT: StatePtr = STATE_DEAD + 1; + +/// A start state is a state that the DFA can start in. +/// +/// Note that start states have their lower bits set to a state pointer. +const STATE_START: StatePtr = 1<<30; + +/// A match state means that the regex has successfully matched. +/// +/// Note that match states have their lower bits set to a state pointer. +const STATE_MATCH: StatePtr = 1<<29; + +/// The maximum state pointer. This is useful to mask out the "valid" state +/// pointer from a state with the "start" or "match" bits set. +/// +/// It doesn't make sense to use this with unknown, dead or quit state +/// pointers, since those pointers are sentinels and never have their lower +/// bits set to anything meaningful. +const STATE_MAX: StatePtr = STATE_MATCH - 1; + +/// Byte is a u8 in spirit, but a u16 in practice so that we can represent the +/// special EOF sentinel value. +#[derive(Copy, Clone, Debug)] +struct Byte(u16); + +/// A set of flags for zero-width assertions. +#[derive(Clone, Copy, Eq, Debug, Default, Hash, PartialEq)] +struct EmptyFlags { + start: bool, + end: bool, + start_line: bool, + end_line: bool, + word_boundary: bool, + not_word_boundary: bool, +} + +/// A set of flags describing various configurations of a DFA state. This is +/// represented by a `u8` so that it is compact. +#[derive(Clone, Copy, Eq, Default, Hash, PartialEq)] +struct StateFlags(u8); + +impl Cache { + /// Create new empty cache for the DFA engine. + pub fn new(prog: &Program) -> Self { + // We add 1 to account for the special EOF byte. + let num_byte_classes = (prog.byte_classes[255] as usize + 1) + 1; + let starts = vec![STATE_UNKNOWN; 256]; + let mut cache = Cache { + inner: CacheInner { + compiled: HashMap::new(), + trans: Transitions::new(num_byte_classes), + states: vec![], + start_states: starts, + stack: vec![], + flush_count: 0, + size: 0, + }, + qcur: SparseSet::new(prog.insts.len()), + qnext: SparseSet::new(prog.insts.len()), + }; + cache.inner.reset_size(); + cache + } +} + +impl CacheInner { + /// Resets the cache size to account for fixed costs, such as the program + /// and stack sizes. + fn reset_size(&mut self) { + self.size = + (self.start_states.len() * mem::size_of::()) + + (self.stack.len() * mem::size_of::()); + } +} + +impl<'a> Fsm<'a> { + #[inline(always)] // reduces constant overhead + pub fn forward( + prog: &'a Program, + cache: &ProgramCache, + quit_after_match: bool, + text: &[u8], + at: usize, + ) -> Result { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.dfa; + let mut dfa = Fsm { + prog: prog, + start: 0, // filled in below + at: at, + quit_after_match: quit_after_match, + last_match_si: STATE_UNKNOWN, + last_cache_flush: at, + cache: &mut cache.inner, + }; + let (empty_flags, state_flags) = dfa.start_flags(text, at); + dfa.start = match dfa.start_state( + &mut cache.qcur, + empty_flags, + state_flags, + ) { + None => return Result::Quit, + Some(STATE_DEAD) => return Result::NoMatch(at), + Some(si) => si, + }; + debug_assert!(dfa.start != STATE_UNKNOWN); + dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text) + } + + #[inline(always)] // reduces constant overhead + pub fn reverse( + prog: &'a Program, + cache: &ProgramCache, + quit_after_match: bool, + text: &[u8], + at: usize, + ) -> Result { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.dfa_reverse; + let mut dfa = Fsm { + prog: prog, + start: 0, // filled in below + at: at, + quit_after_match: quit_after_match, + last_match_si: STATE_UNKNOWN, + last_cache_flush: at, + cache: &mut cache.inner, + }; + let (empty_flags, state_flags) = dfa.start_flags_reverse(text, at); + dfa.start = match dfa.start_state( + &mut cache.qcur, + empty_flags, + state_flags, + ) { + None => return Result::Quit, + Some(STATE_DEAD) => return Result::NoMatch(at), + Some(si) => si, + }; + debug_assert!(dfa.start != STATE_UNKNOWN); + dfa.exec_at_reverse(&mut cache.qcur, &mut cache.qnext, text) + } + + #[inline(always)] // reduces constant overhead + pub fn forward_many( + prog: &'a Program, + cache: &ProgramCache, + matches: &mut [bool], + text: &[u8], + at: usize, + ) -> Result { + debug_assert!(matches.len() == prog.matches.len()); + let mut cache = cache.borrow_mut(); + let cache = &mut cache.dfa; + let mut dfa = Fsm { + prog: prog, + start: 0, // filled in below + at: at, + quit_after_match: false, + last_match_si: STATE_UNKNOWN, + last_cache_flush: at, + cache: &mut cache.inner, + }; + let (empty_flags, state_flags) = dfa.start_flags(text, at); + dfa.start = match dfa.start_state( + &mut cache.qcur, + empty_flags, + state_flags, + ) { + None => return Result::Quit, + Some(STATE_DEAD) => return Result::NoMatch(at), + Some(si) => si, + }; + debug_assert!(dfa.start != STATE_UNKNOWN); + let result = dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text); + if result.is_match() { + if matches.len() == 1 { + matches[0] = true; + } else { + debug_assert!(dfa.last_match_si != STATE_UNKNOWN); + debug_assert!(dfa.last_match_si != STATE_DEAD); + for ip in dfa.state(dfa.last_match_si).inst_ptrs() { + if let Inst::Match(slot) = dfa.prog[ip] { + matches[slot] = true; + } + } + } + } + result + } + + /// Executes the DFA on a forward NFA. + /// + /// {qcur,qnext} are scratch ordered sets which may be non-empty. + #[inline(always)] // reduces constant overhead + fn exec_at( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + text: &[u8], + ) -> Result { + // For the most part, the DFA is basically: + // + // last_match = null + // while current_byte != EOF: + // si = current_state.next[current_byte] + // if si is match + // last_match = si + // return last_match + // + // However, we need to deal with a few things: + // + // 1. This is an *online* DFA, so the current state's next list + // may not point to anywhere yet, so we must go out and compute + // them. (They are then cached into the current state's next list + // to avoid re-computation.) + // 2. If we come across a state that is known to be dead (i.e., never + // leads to a match), then we can quit early. + // 3. If the caller just wants to know if a match occurs, then we + // can quit as soon as we know we have a match. (Full leftmost + // first semantics require continuing on.) + // 4. If we're in the start state, then we can use a pre-computed set + // of prefix literals to skip quickly along the input. + // 5. After the input is exhausted, we run the DFA on one symbol + // that stands for EOF. This is useful for handling empty width + // assertions. + // 6. We can't actually do state.next[byte]. Instead, we have to do + // state.next[byte_classes[byte]], which permits us to keep the + // 'next' list very small. + // + // Since there's a bunch of extra stuff we need to consider, we do some + // pretty hairy tricks to get the inner loop to run as fast as + // possible. + debug_assert!(!self.prog.is_reverse); + + // The last match is the currently known ending match position. It is + // reported as an index to the most recent byte that resulted in a + // transition to a match state and is always stored in capture slot `1` + // when searching forwards. Its maximum value is `text.len()`. + let mut result = Result::NoMatch(self.at); + let (mut prev_si, mut next_si) = (self.start, self.start); + let mut at = self.at; + while at < text.len() { + // This is the real inner loop. We take advantage of special bits + // set in the state pointer to determine whether a state is in the + // "common" case or not. Specifically, the common case is a + // non-match non-start non-dead state that has already been + // computed. So long as we remain in the common case, this inner + // loop will chew through the input. + // + // We also unroll the loop 4 times to amortize the cost of checking + // whether we've consumed the entire input. We are also careful + // to make sure that `prev_si` always represents the previous state + // and `next_si` always represents the next state after the loop + // exits, even if it isn't always true inside the loop. + while next_si <= STATE_MAX && at < text.len() { + // Argument for safety is in the definition of next_si. + prev_si = unsafe { self.next_si(next_si, text, at) }; + at += 1; + if prev_si > STATE_MAX || at + 2 >= text.len() { + mem::swap(&mut prev_si, &mut next_si); + break; + } + next_si = unsafe { self.next_si(prev_si, text, at) }; + at += 1; + if next_si > STATE_MAX { + break; + } + prev_si = unsafe { self.next_si(next_si, text, at) }; + at += 1; + if prev_si > STATE_MAX { + mem::swap(&mut prev_si, &mut next_si); + break; + } + next_si = unsafe { self.next_si(prev_si, text, at) }; + at += 1; + } + if next_si & STATE_MATCH > 0 { + // A match state is outside of the common case because it needs + // special case analysis. In particular, we need to record the + // last position as having matched and possibly quit the DFA if + // we don't need to keep matching. + next_si &= !STATE_MATCH; + result = Result::Match(at - 1); + if self.quit_after_match { + return result; + } + self.last_match_si = next_si; + prev_si = next_si; + + // This permits short-circuiting when matching a regex set. + // In particular, if this DFA state contains only match states, + // then it's impossible to extend the set of matches since + // match states are final. Therefore, we can quit. + if self.prog.matches.len() > 1 { + let state = self.state(next_si); + let just_matches = state.inst_ptrs() + .all(|ip| self.prog[ip].is_match()); + if just_matches { + return result; + } + } + + // Another inner loop! If the DFA stays in this particular + // match state, then we can rip through all of the input + // very quickly, and only recording the match location once + // we've left this particular state. + let cur = at; + while (next_si & !STATE_MATCH) == prev_si + && at + 2 < text.len() { + // Argument for safety is in the definition of next_si. + next_si = unsafe { + self.next_si(next_si & !STATE_MATCH, text, at) + }; + at += 1; + } + if at > cur { + result = Result::Match(at - 2); + } + } else if next_si & STATE_START > 0 { + // A start state isn't in the common case because we may + // what to do quick prefix scanning. If the program doesn't + // have a detected prefix, then start states are actually + // considered common and this case is never reached. + debug_assert!(self.has_prefix()); + next_si &= !STATE_START; + prev_si = next_si; + at = match self.prefix_at(text, at) { + None => return Result::NoMatch(text.len()), + Some(i) => i, + }; + } else if next_si >= STATE_UNKNOWN { + if next_si == STATE_QUIT { + return Result::Quit; + } + // Finally, this corresponds to the case where the transition + // entered a state that can never lead to a match or a state + // that hasn't been computed yet. The latter being the "slow" + // path. + let byte = Byte::byte(text[at - 1]); + // We no longer care about the special bits in the state + // pointer. + prev_si &= STATE_MAX; + // Record where we are. This is used to track progress for + // determining whether we should quit if we've flushed the + // cache too much. + self.at = at; + next_si = match self.next_state(qcur, qnext, prev_si, byte) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(at), + Some(si) => si, + }; + debug_assert!(next_si != STATE_UNKNOWN); + if next_si & STATE_MATCH > 0 { + next_si &= !STATE_MATCH; + result = Result::Match(at - 1); + if self.quit_after_match { + return result; + } + self.last_match_si = next_si; + } + prev_si = next_si; + } else { + prev_si = next_si; + } + } + + // Run the DFA once more on the special EOF senitnel value. + // We don't care about the special bits in the state pointer any more, + // so get rid of them. + prev_si &= STATE_MAX; + prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(text.len()), + Some(si) => si & !STATE_START, + }; + debug_assert!(prev_si != STATE_UNKNOWN); + if prev_si & STATE_MATCH > 0 { + prev_si &= !STATE_MATCH; + self.last_match_si = prev_si; + result = Result::Match(text.len()); + } + result + } + + /// Executes the DFA on a reverse NFA. + #[inline(always)] // reduces constant overhead + fn exec_at_reverse( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + text: &[u8], + ) -> Result { + // The comments in `exec_at` above mostly apply here too. The main + // difference is that we move backwards over the input and we look for + // the longest possible match instead of the leftmost-first match. + // + // N.B. The code duplication here is regrettable. Efforts to improve + // it without sacrificing performance are welcome. ---AG + debug_assert!(self.prog.is_reverse); + let mut result = Result::NoMatch(self.at); + let (mut prev_si, mut next_si) = (self.start, self.start); + let mut at = self.at; + while at > 0 { + while next_si <= STATE_MAX && at > 0 { + // Argument for safety is in the definition of next_si. + at -= 1; + prev_si = unsafe { self.next_si(next_si, text, at) }; + if prev_si > STATE_MAX || at <= 4 { + mem::swap(&mut prev_si, &mut next_si); + break; + } + at -= 1; + next_si = unsafe { self.next_si(prev_si, text, at) }; + if next_si > STATE_MAX { + break; + } + at -= 1; + prev_si = unsafe { self.next_si(next_si, text, at) }; + if prev_si > STATE_MAX { + mem::swap(&mut prev_si, &mut next_si); + break; + } + at -= 1; + next_si = unsafe { self.next_si(prev_si, text, at) }; + } + if next_si & STATE_MATCH > 0 { + next_si &= !STATE_MATCH; + result = Result::Match(at + 1); + if self.quit_after_match { + return result + } + self.last_match_si = next_si; + prev_si = next_si; + let cur = at; + while (next_si & !STATE_MATCH) == prev_si && at >= 2 { + // Argument for safety is in the definition of next_si. + at -= 1; + next_si = unsafe { + self.next_si(next_si & !STATE_MATCH, text, at) + }; + } + if at < cur { + result = Result::Match(at + 2); + } + } else if next_si >= STATE_UNKNOWN { + if next_si == STATE_QUIT { + return Result::Quit; + } + let byte = Byte::byte(text[at]); + prev_si &= STATE_MAX; + self.at = at; + next_si = match self.next_state(qcur, qnext, prev_si, byte) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(at), + Some(si) => si, + }; + debug_assert!(next_si != STATE_UNKNOWN); + if next_si & STATE_MATCH > 0 { + next_si &= !STATE_MATCH; + result = Result::Match(at + 1); + if self.quit_after_match { + return result; + } + self.last_match_si = next_si; + } + prev_si = next_si; + } else { + prev_si = next_si; + } + } + + // Run the DFA once more on the special EOF senitnel value. + prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(0), + Some(si) => si, + }; + debug_assert!(prev_si != STATE_UNKNOWN); + if prev_si & STATE_MATCH > 0 { + prev_si &= !STATE_MATCH; + self.last_match_si = prev_si; + result = Result::Match(0); + } + result + } + + /// next_si transitions to the next state, where the transition input + /// corresponds to text[i]. + /// + /// This elides bounds checks, and is therefore unsafe. + #[inline(always)] + unsafe fn next_si(&self, si: StatePtr, text: &[u8], i: usize) -> StatePtr { + // What is the argument for safety here? + // We have three unchecked accesses that could possibly violate safety: + // + // 1. The given byte of input (`text[i]`). + // 2. The class of the byte of input (`classes[text[i]]`). + // 3. The transition for the class (`trans[si + cls]`). + // + // (1) is only safe when calling next_si is guarded by + // `i < text.len()`. + // + // (2) is the easiest case to guarantee since `text[i]` is always a + // `u8` and `self.prog.byte_classes` always has length `u8::MAX`. + // (See `ByteClassSet.byte_classes` in `compile.rs`.) + // + // (3) is only safe if (1)+(2) are safe. Namely, the transitions + // of every state are defined to have length equal to the number of + // byte classes in the program. Therefore, a valid class leads to a + // valid transition. (All possible transitions are valid lookups, even + // if it points to a state that hasn't been computed yet.) (3) also + // relies on `si` being correct, but StatePtrs should only ever be + // retrieved from the transition table, which ensures they are correct. + debug_assert!(i < text.len()); + let b = *text.get_unchecked(i); + debug_assert!((b as usize) < self.prog.byte_classes.len()); + let cls = *self.prog.byte_classes.get_unchecked(b as usize); + self.cache.trans.next_unchecked(si, cls as usize) + } + + /// Computes the next state given the current state and the current input + /// byte (which may be EOF). + /// + /// If STATE_DEAD is returned, then there is no valid state transition. + /// This implies that no permutation of future input can lead to a match + /// state. + /// + /// STATE_UNKNOWN can never be returned. + fn exec_byte( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + mut si: StatePtr, + b: Byte, + ) -> Option { + use prog::Inst::*; + + // Initialize a queue with the current DFA state's NFA states. + qcur.clear(); + for ip in self.state(si).inst_ptrs() { + qcur.insert(ip); + } + + // Before inspecting the current byte, we may need to also inspect + // whether the position immediately preceding the current byte + // satisfies the empty assertions found in the current state. + // + // We only need to do this step if there are any empty assertions in + // the current state. + let is_word_last = self.state(si).flags().is_word(); + let is_word = b.is_ascii_word(); + if self.state(si).flags().has_empty() { + // Compute the flags immediately preceding the current byte. + // This means we only care about the "end" or "end line" flags. + // (The "start" flags are computed immediately proceding the + // current byte and is handled below.) + let mut flags = EmptyFlags::default(); + if b.is_eof() { + flags.end = true; + flags.end_line = true; + } else if b.as_byte().map_or(false, |b| b == b'\n') { + flags.end_line = true; + } + if is_word_last == is_word { + flags.not_word_boundary = true; + } else { + flags.word_boundary = true; + } + // Now follow epsilon transitions from every NFA state, but make + // sure we only follow transitions that satisfy our flags. + qnext.clear(); + for &ip in &*qcur { + self.follow_epsilons(usize_to_u32(ip), qnext, flags); + } + mem::swap(qcur, qnext); + } + + // Now we set flags for immediately after the current byte. Since start + // states are processed separately, and are the only states that can + // have the StartText flag set, we therefore only need to worry about + // the StartLine flag here. + // + // We do also keep track of whether this DFA state contains a NFA state + // that is a matching state. This is precisely how we delay the DFA + // matching by one byte in order to process the special EOF sentinel + // byte. Namely, if this DFA state containing a matching NFA state, + // then it is the *next* DFA state that is marked as a match. + let mut empty_flags = EmptyFlags::default(); + let mut state_flags = StateFlags::default(); + empty_flags.start_line = b.as_byte().map_or(false, |b| b == b'\n'); + if b.is_ascii_word() { + state_flags.set_word(); + } + // Now follow all epsilon transitions again, but only after consuming + // the current byte. + qnext.clear(); + for &ip in &*qcur { + match self.prog[ip as usize] { + // These states never happen in a byte-based program. + Char(_) | Ranges(_) => unreachable!(), + // These states are handled when following epsilon transitions. + Save(_) | Split(_) | EmptyLook(_) => {} + Match(_) => { + state_flags.set_match(); + if !self.continue_past_first_match() { + break; + } else if self.prog.matches.len() > 1 + && !qnext.contains(ip as usize) { + // If we are continuing on to find other matches, + // then keep a record of the match states we've seen. + qnext.insert(ip); + } + } + Bytes(ref inst) => { + if b.as_byte().map_or(false, |b| inst.matches(b)) { + self.follow_epsilons( + inst.goto as InstPtr, qnext, empty_flags); + } + } + } + } + + let cache = + if b.is_eof() && self.prog.matches.len() > 1 { + // If we're processing the last byte of the input and we're + // matching a regex set, then make the next state contain the + // previous states transitions. We do this so that the main + // matching loop can extract all of the match instructions. + mem::swap(qcur, qnext); + // And don't cache this state because it's totally bunk. + false + } else { + true + }; + + // We've now built up the set of NFA states that ought to comprise the + // next DFA state, so try to find it in the cache, and if it doesn't + // exist, cache it. + // + // N.B. We pass `&mut si` here because the cache may clear itself if + // it has gotten too full. When that happens, the location of the + // current state may change. + let mut next = match self.cached_state( + qnext, + state_flags, + Some(&mut si), + ) { + None => return None, + Some(next) => next, + }; + if (self.start & !STATE_START) == next { + // Start states can never be match states since all matches are + // delayed by one byte. + debug_assert!(!self.state(next).flags().is_match()); + next = self.start_ptr(next); + } + if next <= STATE_MAX && self.state(next).flags().is_match() { + next |= STATE_MATCH; + } + debug_assert!(next != STATE_UNKNOWN); + // And now store our state in the current state's next list. + if cache { + let cls = self.byte_class(b); + self.cache.trans.set_next(si, cls, next); + } + Some(next) + } + + /// Follows the epsilon transitions starting at (and including) `ip`. The + /// resulting states are inserted into the ordered set `q`. + /// + /// Conditional epsilon transitions (i.e., empty width assertions) are only + /// followed if they are satisfied by the given flags, which should + /// represent the flags set at the current location in the input. + /// + /// If the current location corresponds to the empty string, then only the + /// end line and/or end text flags may be set. If the current location + /// corresponds to a real byte in the input, then only the start line + /// and/or start text flags may be set. + /// + /// As an exception to the above, when finding the initial state, any of + /// the above flags may be set: + /// + /// If matching starts at the beginning of the input, then start text and + /// start line should be set. If the input is empty, then end text and end + /// line should also be set. + /// + /// If matching starts after the beginning of the input, then only start + /// line should be set if the preceding byte is `\n`. End line should never + /// be set in this case. (Even if the proceding byte is a `\n`, it will + /// be handled in a subsequent DFA state.) + fn follow_epsilons( + &mut self, + ip: InstPtr, + q: &mut SparseSet, + flags: EmptyFlags, + ) { + use prog::Inst::*; + use prog::EmptyLook::*; + + // We need to traverse the NFA to follow epsilon transitions, so avoid + // recursion with an explicit stack. + self.cache.stack.push(ip); + while let Some(mut ip) = self.cache.stack.pop() { + // Try to munch through as many states as possible without + // pushes/pops to the stack. + loop { + // Don't visit states we've already added. + if q.contains(ip as usize) { + break; + } + q.insert(ip as usize); + match self.prog[ip as usize] { + Char(_) | Ranges(_) => unreachable!(), + Match(_) | Bytes(_) => { + break; + } + EmptyLook(ref inst) => { + // Only follow empty assertion states if our flags + // satisfy the assertion. + match inst.look { + StartLine if flags.start_line => { + ip = inst.goto as InstPtr; + } + EndLine if flags.end_line => { + ip = inst.goto as InstPtr; + } + StartText if flags.start => { + ip = inst.goto as InstPtr; + } + EndText if flags.end => { + ip = inst.goto as InstPtr; + } + WordBoundaryAscii if flags.word_boundary => { + ip = inst.goto as InstPtr; + } + NotWordBoundaryAscii if flags.not_word_boundary => { + ip = inst.goto as InstPtr; + } + WordBoundary if flags.word_boundary => { + ip = inst.goto as InstPtr; + } + NotWordBoundary if flags.not_word_boundary => { + ip = inst.goto as InstPtr; + } + StartLine | EndLine | StartText | EndText + | WordBoundaryAscii | NotWordBoundaryAscii + | WordBoundary | NotWordBoundary => { + break; + } + } + } + Save(ref inst) => { + ip = inst.goto as InstPtr; + } + Split(ref inst) => { + self.cache.stack.push(inst.goto2 as InstPtr); + ip = inst.goto1 as InstPtr; + } + } + } + } + } + + /// Find a previously computed state matching the given set of instructions + /// and is_match bool. + /// + /// The given set of instructions should represent a single state in the + /// NFA along with all states reachable without consuming any input. + /// + /// The is_match bool should be true if and only if the preceding DFA state + /// contains an NFA matching state. The cached state produced here will + /// then signify a match. (This enables us to delay a match by one byte, + /// in order to account for the EOF sentinel byte.) + /// + /// If the cache is full, then it is wiped before caching a new state. + /// + /// The current state should be specified if it exists, since it will need + /// to be preserved if the cache clears itself. (Start states are + /// always saved, so they should not be passed here.) It takes a mutable + /// pointer to the index because if the cache is cleared, the state's + /// location may change. + fn cached_state( + &mut self, + q: &SparseSet, + mut state_flags: StateFlags, + current_state: Option<&mut StatePtr>, + ) -> Option { + // If we couldn't come up with a non-empty key to represent this state, + // then it is dead and can never lead to a match. + // + // Note that inst_flags represent the set of empty width assertions + // in q. We use this as an optimization in exec_byte to determine when + // we should follow epsilon transitions at the empty string preceding + // the current byte. + let key = match self.cached_state_key(q, &mut state_flags) { + None => return Some(STATE_DEAD), + Some(v) => v, + }; + // In the cache? Cool. Done. + if let Some(&si) = self.cache.compiled.get(&key) { + return Some(si); + } + // If the cache has gotten too big, wipe it. + if self.approximate_size() > self.prog.dfa_size_limit + && !self.clear_cache_and_save(current_state) + { + // Ooops. DFA is giving up. + return None; + } + // Allocate room for our state and add it. + self.add_state(key) + } + + /// Produces a key suitable for describing a state in the DFA cache. + /// + /// The key invariant here is that equivalent keys are produced for any two + /// sets of ordered NFA states (and toggling of whether the previous NFA + /// states contain a match state) that do not discriminate a match for any + /// input. + /// + /// Specifically, q should be an ordered set of NFA states and is_match + /// should be true if and only if the previous NFA states contained a match + /// state. + fn cached_state_key( + &mut self, + q: &SparseSet, + state_flags: &mut StateFlags, + ) -> Option { + use prog::Inst::*; + + // We need to build up enough information to recognize pre-built states + // in the DFA. Generally speaking, this includes every instruction + // except for those which are purely epsilon transitions, e.g., the + // Save and Split instructions. + // + // Empty width assertions are also epsilon transitions, but since they + // are conditional, we need to make them part of a state's key in the + // cache. + + // Reserve 1 byte for flags. + let mut insts = vec![0]; + let mut prev = 0; + for &ip in q { + let ip = usize_to_u32(ip); + match self.prog[ip as usize] { + Char(_) | Ranges(_) => unreachable!(), + Save(_) | Split(_) => {} + Bytes(_) => push_inst_ptr(&mut insts, &mut prev, ip), + EmptyLook(_) => { + state_flags.set_empty(); + push_inst_ptr(&mut insts, &mut prev, ip) + } + Match(_) => { + push_inst_ptr(&mut insts, &mut prev, ip); + if !self.continue_past_first_match() { + break; + } + } + } + } + // If we couldn't transition to any other instructions and we didn't + // see a match when expanding NFA states previously, then this is a + // dead state and no amount of additional input can transition out + // of this state. + if insts.len() == 1 && !state_flags.is_match() { + None + } else { + let StateFlags(f) = *state_flags; + insts[0] = f; + Some(State { data: insts.into_boxed_slice() }) + } + } + + /// Clears the cache, but saves and restores current_state if it is not + /// none. + /// + /// The current state must be provided here in case its location in the + /// cache changes. + /// + /// This returns false if the cache is not cleared and the DFA should + /// give up. + fn clear_cache_and_save( + &mut self, + current_state: Option<&mut StatePtr>, + ) -> bool { + if self.cache.states.is_empty() { + // Nothing to clear... + return true; + } + match current_state { + None => self.clear_cache(), + Some(si) => { + let cur = self.state(*si).clone(); + if !self.clear_cache() { + return false; + } + // The unwrap is OK because we just cleared the cache and + // therefore know that the next state pointer won't exceed + // STATE_MAX. + *si = self.restore_state(cur).unwrap(); + true + } + } + } + + /// Wipes the state cache, but saves and restores the current start state. + /// + /// This returns false if the cache is not cleared and the DFA should + /// give up. + fn clear_cache(&mut self) -> bool { + // Bail out of the DFA if we're moving too "slowly." + // A heuristic from RE2: assume the DFA is too slow if it is processing + // 10 or fewer bytes per state. + // Additionally, we permit the cache to be flushed a few times before + // caling it quits. + let nstates = self.cache.states.len(); + if self.cache.flush_count >= 3 + && self.at >= self.last_cache_flush + && (self.at - self.last_cache_flush) <= 10 * nstates { + return false; + } + // Update statistics tracking cache flushes. + self.last_cache_flush = self.at; + self.cache.flush_count += 1; + + // OK, actually flush the cache. + let start = self.state(self.start & !STATE_START).clone(); + let last_match = if self.last_match_si <= STATE_MAX { + Some(self.state(self.last_match_si).clone()) + } else { + None + }; + self.cache.reset_size(); + self.cache.trans.clear(); + self.cache.states.clear(); + self.cache.compiled.clear(); + for s in &mut self.cache.start_states { + *s = STATE_UNKNOWN; + } + // The unwraps are OK because we just cleared the cache and therefore + // know that the next state pointer won't exceed STATE_MAX. + let start_ptr = self.restore_state(start).unwrap(); + self.start = self.start_ptr(start_ptr); + if let Some(last_match) = last_match { + self.last_match_si = self.restore_state(last_match).unwrap(); + } + true + } + + /// Restores the given state back into the cache, and returns a pointer + /// to it. + fn restore_state(&mut self, state: State) -> Option { + // If we've already stored this state, just return a pointer to it. + // None will be the wiser. + if let Some(&si) = self.cache.compiled.get(&state) { + return Some(si); + } + self.add_state(state) + } + + /// Returns the next state given the current state si and current byte + /// b. {qcur,qnext} are used as scratch space for storing ordered NFA + /// states. + /// + /// This tries to fetch the next state from the cache, but if that fails, + /// it computes the next state, caches it and returns a pointer to it. + /// + /// The pointer can be to a real state, or it can be STATE_DEAD. + /// STATE_UNKNOWN cannot be returned. + /// + /// None is returned if a new state could not be allocated (i.e., the DFA + /// ran out of space and thinks it's running too slowly). + fn next_state( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + si: StatePtr, + b: Byte, + ) -> Option { + if si == STATE_DEAD { + return Some(STATE_DEAD); + } + match self.cache.trans.next(si, self.byte_class(b)) { + STATE_UNKNOWN => self.exec_byte(qcur, qnext, si, b), + STATE_QUIT => None, + STATE_DEAD => Some(STATE_DEAD), + nsi => Some(nsi), + } + } + + /// Computes and returns the start state, where searching begins at + /// position `at` in `text`. If the state has already been computed, + /// then it is pulled from the cache. If the state hasn't been cached, + /// then it is computed, cached and a pointer to it is returned. + /// + /// This may return STATE_DEAD but never STATE_UNKNOWN. + #[inline(always)] // reduces constant overhead + fn start_state( + &mut self, + q: &mut SparseSet, + empty_flags: EmptyFlags, + state_flags: StateFlags, + ) -> Option { + // Compute an index into our cache of start states based on the set + // of empty/state flags set at the current position in the input. We + // don't use every flag since not all flags matter. For example, since + // matches are delayed by one byte, start states can never be match + // states. + let flagi = { + (((empty_flags.start as u8) << 0) | + ((empty_flags.end as u8) << 1) | + ((empty_flags.start_line as u8) << 2) | + ((empty_flags.end_line as u8) << 3) | + ((empty_flags.word_boundary as u8) << 4) | + ((empty_flags.not_word_boundary as u8) << 5) | + ((state_flags.is_word() as u8) << 6)) + as usize + }; + match self.cache.start_states[flagi] { + STATE_UNKNOWN => {} + STATE_DEAD => return Some(STATE_DEAD), + si => return Some(si), + } + q.clear(); + let start = usize_to_u32(self.prog.start); + self.follow_epsilons(start, q, empty_flags); + // Start states can never be match states because we delay every match + // by one byte. Given an empty string and an empty match, the match + // won't actually occur until the DFA processes the special EOF + // sentinel byte. + let sp = match self.cached_state(q, state_flags, None) { + None => return None, + Some(sp) => self.start_ptr(sp), + }; + self.cache.start_states[flagi] = sp; + Some(sp) + } + + /// Computes the set of starting flags for the given position in text. + /// + /// This should only be used when executing the DFA forwards over the + /// input. + fn start_flags(&self, text: &[u8], at: usize) -> (EmptyFlags, StateFlags) { + let mut empty_flags = EmptyFlags::default(); + let mut state_flags = StateFlags::default(); + empty_flags.start = at == 0; + empty_flags.end = text.is_empty(); + empty_flags.start_line = at == 0 || text[at - 1] == b'\n'; + empty_flags.end_line = text.is_empty(); + + let is_word_last = at > 0 && Byte::byte(text[at - 1]).is_ascii_word(); + let is_word = at < text.len() && Byte::byte(text[at]).is_ascii_word(); + if is_word_last { + state_flags.set_word(); + } + if is_word == is_word_last { + empty_flags.not_word_boundary = true; + } else { + empty_flags.word_boundary = true; + } + (empty_flags, state_flags) + } + + /// Computes the set of starting flags for the given position in text. + /// + /// This should only be used when executing the DFA in reverse over the + /// input. + fn start_flags_reverse( + &self, + text: &[u8], + at: usize, + ) -> (EmptyFlags, StateFlags) { + let mut empty_flags = EmptyFlags::default(); + let mut state_flags = StateFlags::default(); + empty_flags.start = at == text.len(); + empty_flags.end = text.is_empty(); + empty_flags.start_line = at == text.len() || text[at] == b'\n'; + empty_flags.end_line = text.is_empty(); + + let is_word_last = + at < text.len() && Byte::byte(text[at]).is_ascii_word(); + let is_word = at > 0 && Byte::byte(text[at - 1]).is_ascii_word(); + if is_word_last { + state_flags.set_word(); + } + if is_word == is_word_last { + empty_flags.not_word_boundary = true; + } else { + empty_flags.word_boundary = true; + } + (empty_flags, state_flags) + } + + /// Returns a reference to a State given a pointer to it. + fn state(&self, si: StatePtr) -> &State { + &self.cache.states[si as usize / self.num_byte_classes()] + } + + /// Adds the given state to the DFA. + /// + /// This allocates room for transitions out of this state in + /// self.cache.trans. The transitions can be set with the returned + /// StatePtr. + /// + /// If None is returned, then the state limit was reached and the DFA + /// should quit. + fn add_state(&mut self, state: State) -> Option { + // This will fail if the next state pointer exceeds STATE_PTR. In + // practice, the cache limit will prevent us from ever getting here, + // but maybe callers will set the cache size to something ridiculous... + let si = match self.cache.trans.add() { + None => return None, + Some(si) => si, + }; + // If the program has a Unicode word boundary, then set any transitions + // for non-ASCII bytes to STATE_QUIT. If the DFA stumbles over such a + // transition, then it will quit and an alternative matching engine + // will take over. + if self.prog.has_unicode_word_boundary { + for b in 128..256 { + let cls = self.byte_class(Byte::byte(b as u8)); + self.cache.trans.set_next(si, cls, STATE_QUIT); + } + } + // Finally, put our actual state on to our heap of states and index it + // so we can find it later. + self.cache.size += + self.cache.trans.state_heap_size() + + (2 * state.data.len()) + + (2 * mem::size_of::()) + + mem::size_of::(); + self.cache.states.push(state.clone()); + self.cache.compiled.insert(state, si); + // Transition table and set of states and map should all be in sync. + debug_assert!(self.cache.states.len() + == self.cache.trans.num_states()); + debug_assert!(self.cache.states.len() + == self.cache.compiled.len()); + Some(si) + } + + /// Quickly finds the next occurrence of any literal prefixes in the regex. + /// If there are no literal prefixes, then the current position is + /// returned. If there are literal prefixes and one could not be found, + /// then None is returned. + /// + /// This should only be called when the DFA is in a start state. + fn prefix_at(&self, text: &[u8], at: usize) -> Option { + self.prog.prefixes.find(&text[at..]).map(|(s, _)| at + s) + } + + /// Returns the number of byte classes required to discriminate transitions + /// in each state. + /// + /// invariant: num_byte_classes() == len(State.next) + fn num_byte_classes(&self) -> usize { + // We add 1 to account for the special EOF byte. + (self.prog.byte_classes[255] as usize + 1) + 1 + } + + /// Given an input byte or the special EOF sentinel, return its + /// corresponding byte class. + #[inline(always)] + fn byte_class(&self, b: Byte) -> usize { + match b.as_byte() { + None => self.num_byte_classes() - 1, + Some(b) => self.u8_class(b), + } + } + + /// Like byte_class, but explicitly for u8s. + #[inline(always)] + fn u8_class(&self, b: u8) -> usize { + self.prog.byte_classes[b as usize] as usize + } + + /// Returns true if the DFA should continue searching past the first match. + /// + /// Leftmost first semantics in the DFA are preserved by not following NFA + /// transitions after the first match is seen. + /// + /// On occasion, we want to avoid leftmost first semantics to find either + /// the longest match (for reverse search) or all possible matches (for + /// regex sets). + fn continue_past_first_match(&self) -> bool { + self.prog.is_reverse || self.prog.matches.len() > 1 + } + + /// Returns true if there is a prefix we can quickly search for. + fn has_prefix(&self) -> bool { + !self.prog.is_reverse + && !self.prog.prefixes.is_empty() + && !self.prog.is_anchored_start + } + + /// Sets the STATE_START bit in the given state pointer if and only if + /// we have a prefix to scan for. + /// + /// If there's no prefix, then it's a waste to treat the start state + /// specially. + fn start_ptr(&self, si: StatePtr) -> StatePtr { + if self.has_prefix() { + si | STATE_START + } else { + si + } + } + + /// Approximate size returns the approximate heap space currently used by + /// the DFA. It is used to determine whether the DFA's state cache needs to + /// be wiped. Namely, it is possible that for certain regexes on certain + /// inputs, a new state could be created for every byte of input. (This is + /// bad for memory use, so we bound it with a cache.) + fn approximate_size(&self) -> usize { + self.cache.size + self.prog.approximate_size() + } +} + +impl Transitions { + /// Create a new transition table. + /// + /// The number of byte classes corresponds to the stride. Every state will + /// have `num_byte_classes` slots for transitions. + fn new(num_byte_classes: usize) -> Transitions { + Transitions { + table: vec![], + num_byte_classes: num_byte_classes, + } + } + + /// Returns the total number of states currently in this table. + fn num_states(&self) -> usize { + self.table.len() / self.num_byte_classes + } + + /// Allocates room for one additional state and returns a pointer to it. + /// + /// If there's no more room, None is returned. + fn add(&mut self) -> Option { + let si = self.table.len(); + if si > STATE_MAX as usize { + return None; + } + self.table.extend(repeat(STATE_UNKNOWN).take(self.num_byte_classes)); + Some(usize_to_u32(si)) + } + + /// Clears the table of all states. + fn clear(&mut self) { + self.table.clear(); + } + + /// Sets the transition from (si, cls) to next. + fn set_next(&mut self, si: StatePtr, cls: usize, next: StatePtr) { + self.table[si as usize + cls] = next; + } + + /// Returns the transition corresponding to (si, cls). + fn next(&self, si: StatePtr, cls: usize) -> StatePtr { + self.table[si as usize + cls] + } + + /// The heap size, in bytes, of a single state in the transition table. + fn state_heap_size(&self) -> usize { + self.num_byte_classes * mem::size_of::() + } + + /// Like `next`, but uses unchecked access and is therefore unsafe. + unsafe fn next_unchecked(&self, si: StatePtr, cls: usize) -> StatePtr { + debug_assert!((si as usize) < self.table.len()); + debug_assert!(cls < self.num_byte_classes); + *self.table.get_unchecked(si as usize + cls) + } +} + +impl StateFlags { + fn is_match(&self) -> bool { + self.0 & 0b0000000_1 > 0 + } + + fn set_match(&mut self) { + self.0 |= 0b0000000_1; + } + + fn is_word(&self) -> bool { + self.0 & 0b000000_1_0 > 0 + } + + fn set_word(&mut self) { + self.0 |= 0b000000_1_0; + } + + fn has_empty(&self) -> bool { + self.0 & 0b00000_1_00 > 0 + } + + fn set_empty(&mut self) { + self.0 |= 0b00000_1_00; + } +} + +impl Byte { + fn byte(b: u8) -> Self { Byte(b as u16) } + fn eof() -> Self { Byte(256) } + fn is_eof(&self) -> bool { self.0 == 256 } + + fn is_ascii_word(&self) -> bool { + let b = match self.as_byte() { + None => return false, + Some(b) => b, + }; + match b { + b'A'...b'Z' | b'a'...b'z' | b'0'...b'9' | b'_' => true, + _ => false, + } + } + + fn as_byte(&self) -> Option { + if self.is_eof() { + None + } else { + Some(self.0 as u8) + } + } +} + +impl fmt::Debug for State { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let ips: Vec = self.inst_ptrs().collect(); + f.debug_struct("State") + .field("flags", &self.flags()) + .field("insts", &ips) + .finish() + } +} + +impl fmt::Debug for Transitions { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut fmtd = f.debug_map(); + for si in 0..self.num_states() { + let s = si * self.num_byte_classes; + let e = s + self.num_byte_classes; + fmtd.entry(&si.to_string(), &TransitionsRow(&self.table[s..e])); + } + fmtd.finish() + } +} + +struct TransitionsRow<'a>(&'a [StatePtr]); + +impl<'a> fmt::Debug for TransitionsRow<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut fmtd = f.debug_map(); + for (b, si) in self.0.iter().enumerate() { + match *si { + STATE_UNKNOWN => {} + STATE_DEAD => { + fmtd.entry(&vb(b as usize), &"DEAD"); + } + si => { + fmtd.entry(&vb(b as usize), &si.to_string()); + } + } + } + fmtd.finish() + } +} + +impl fmt::Debug for StateFlags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("StateFlags") + .field("is_match", &self.is_match()) + .field("is_word", &self.is_word()) + .field("has_empty", &self.has_empty()) + .finish() + } +} + +/// Helper function for formatting a byte as a nice-to-read escaped string. +fn vb(b: usize) -> String { + use std::ascii::escape_default; + + if b > ::std::u8::MAX as usize { + "EOF".to_owned() + } else { + let escaped = escape_default(b as u8).collect::>(); + String::from_utf8_lossy(&escaped).into_owned() + } +} + +fn usize_to_u32(n: usize) -> u32 { + if (n as u64) > (::std::u32::MAX as u64) { + panic!("BUG: {} is too big to fit into u32", n) + } + n as u32 +} + +#[allow(dead_code)] // useful for debugging +fn show_state_ptr(si: StatePtr) -> String { + let mut s = format!("{:?}", si & STATE_MAX); + if si == STATE_UNKNOWN { + s = format!("{} (unknown)", s); + } + if si == STATE_DEAD { + s = format!("{} (dead)", s); + } + if si == STATE_QUIT { + s = format!("{} (quit)", s); + } + if si & STATE_START > 0 { + s = format!("{} (start)", s); + } + if si & STATE_MATCH > 0 { + s = format!("{} (match)", s); + } + s +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn write_vari32(data: &mut Vec, n: i32) { + let mut un = (n as u32) << 1; + if n < 0 { + un = !un; + } + write_varu32(data, un) +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn read_vari32(data: &[u8]) -> (i32, usize) { + let (un, i) = read_varu32(data); + let mut n = (un >> 1) as i32; + if un & 1 != 0 { + n = !n; + } + (n, i) +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn write_varu32(data: &mut Vec, mut n: u32) { + while n >= 0b1000_0000 { + data.push((n as u8) | 0b1000_0000); + n >>= 7; + } + data.push(n as u8); +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn read_varu32(data: &[u8]) -> (u32, usize) { + let mut n: u32 = 0; + let mut shift: u32 = 0; + for (i, &b) in data.iter().enumerate() { + if b < 0b1000_0000 { + return (n | ((b as u32) << shift), i + 1); + } + n |= ((b as u32) & 0b0111_1111) << shift; + shift += 7; + } + (0, 0) +} + +#[cfg(test)] +mod tests { + extern crate rand; + + use quickcheck::{QuickCheck, StdGen, quickcheck}; + use super::{ + StateFlags, State, push_inst_ptr, + write_varu32, read_varu32, write_vari32, read_vari32, + }; + + #[test] + fn prop_state_encode_decode() { + fn p(ips: Vec, flags: u8) -> bool { + let mut data = vec![flags]; + let mut prev = 0; + for &ip in ips.iter() { + push_inst_ptr(&mut data, &mut prev, ip); + } + let state = State { data: data.into_boxed_slice() }; + + let expected: Vec = + ips.into_iter().map(|ip| ip as usize).collect(); + let got: Vec = state.inst_ptrs().collect(); + expected == got && state.flags() == StateFlags(flags) + } + QuickCheck::new() + .gen(StdGen::new(self::rand::thread_rng(), 10_000)) + .quickcheck(p as fn(Vec, u8) -> bool); + } + + #[test] + fn prop_read_write_u32() { + fn p(n: u32) -> bool { + let mut buf = vec![]; + write_varu32(&mut buf, n); + let (got, nread) = read_varu32(&buf); + nread == buf.len() && got == n + } + quickcheck(p as fn(u32) -> bool); + } + + #[test] + fn prop_read_write_i32() { + fn p(n: i32) -> bool { + let mut buf = vec![]; + write_vari32(&mut buf, n); + let (got, nread) = read_vari32(&buf); + nread == buf.len() && got == n + } + quickcheck(p as fn(i32) -> bool); + } +} diff --git a/bash-5.1/vendor/regex/src/error.rs b/bash-5.1/vendor/regex/src/error.rs new file mode 100644 index 0000000..b02aa3e --- /dev/null +++ b/bash-5.1/vendor/regex/src/error.rs @@ -0,0 +1,92 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; +use std::iter::repeat; + +use syntax; + +/// An error that occurred during parsing or compiling a regular expression. +#[derive(Clone, PartialEq)] +pub enum Error { + /// A syntax error. + Syntax(String), + /// The compiled program exceeded the set size limit. + /// The argument is the size limit imposed. + CompiledTooBig(usize), + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl ::std::error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Syntax(ref err) => err, + Error::CompiledTooBig(_) => "compiled program too big", + Error::__Nonexhaustive => unreachable!(), + } + } + + fn cause(&self) -> Option<&::std::error::Error> { + None + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Syntax(ref err) => err.fmt(f), + Error::CompiledTooBig(limit) => { + write!(f, "Compiled regex exceeds size limit of {} bytes.", + limit) + } + Error::__Nonexhaustive => unreachable!(), + } + } +} + +// We implement our own Debug implementation so that we show nicer syntax +// errors when people use `Regex::new(...).unwrap()`. It's a little weird, +// but the `Syntax` variant is already storing a `String` anyway, so we might +// as well format it nicely. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Syntax(ref err) => { + let hr: String = repeat('~').take(79).collect(); + try!(writeln!(f, "Syntax(")); + try!(writeln!(f, "{}", hr)); + try!(writeln!(f, "{}", err)); + try!(writeln!(f, "{}", hr)); + try!(write!(f, ")")); + Ok(()) + } + Error::CompiledTooBig(limit) => { + f.debug_tuple("CompiledTooBig") + .field(&limit) + .finish() + } + Error::__Nonexhaustive => { + f.debug_tuple("__Nonexhaustive").finish() + } + } + } +} + +impl From for Error { + fn from(err: syntax::Error) -> Error { + Error::Syntax(err.to_string()) + } +} diff --git a/bash-5.1/vendor/regex/src/exec.rs b/bash-5.1/vendor/regex/src/exec.rs new file mode 100644 index 0000000..1358fd9 --- /dev/null +++ b/bash-5.1/vendor/regex/src/exec.rs @@ -0,0 +1,1352 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::cmp; +use std::sync::Arc; + +use thread_local::CachedThreadLocal; +use syntax::ParserBuilder; +use syntax::hir::Hir; +use syntax::hir::literal::Literals; + +use backtrack; +use compile::Compiler; +use dfa; +use error::Error; +use input::{ByteInput, CharInput}; +use literal::LiteralSearcher; +use pikevm; +use prog::Program; +use re_builder::RegexOptions; +use re_bytes; +use re_set; +use re_trait::{RegularExpression, Slot, Locations, as_slots}; +use re_unicode; +use utf8::next_utf8; + +/// `Exec` manages the execution of a regular expression. +/// +/// In particular, this manages the various compiled forms of a single regular +/// expression and the choice of which matching engine to use to execute a +/// regular expression. +pub struct Exec { + /// All read only state. + ro: Arc, + /// Caches for the various matching engines. + cache: CachedThreadLocal, +} + +/// `ExecNoSync` is like `Exec`, except it embeds a reference to a cache. This +/// means it is no longer Sync, but we can now avoid the overhead of +/// synchronization to fetch the cache. +#[derive(Debug)] +pub struct ExecNoSync<'c> { + /// All read only state. + ro: &'c Arc, + /// Caches for the various matching engines. + cache: &'c ProgramCache, +} + +/// `ExecNoSyncStr` is like `ExecNoSync`, but matches on &str instead of &[u8]. +pub struct ExecNoSyncStr<'c>(ExecNoSync<'c>); + +/// `ExecReadOnly` comprises all read only state for a regex. Namely, all such +/// state is determined at compile time and never changes during search. +#[derive(Debug)] +struct ExecReadOnly { + /// The original regular expressions given by the caller to compile. + res: Vec, + /// A compiled program that is used in the NFA simulation and backtracking. + /// It can be byte-based or Unicode codepoint based. + /// + /// N.B. It is not possibly to make this byte-based from the public API. + /// It is only used for testing byte based programs in the NFA simulations. + nfa: Program, + /// A compiled byte based program for DFA execution. This is only used + /// if a DFA can be executed. (Currently, only word boundary assertions are + /// not supported.) Note that this program contains an embedded `.*?` + /// preceding the first capture group, unless the regex is anchored at the + /// beginning. + dfa: Program, + /// The same as above, except the program is reversed (and there is no + /// preceding `.*?`). This is used by the DFA to find the starting location + /// of matches. + dfa_reverse: Program, + /// A set of suffix literals extracted from the regex. + /// + /// Prefix literals are stored on the `Program`, since they are used inside + /// the matching engines. + suffixes: LiteralSearcher, + /// match_type encodes as much upfront knowledge about how we're going to + /// execute a search as possible. + match_type: MatchType, +} + +/// Facilitates the construction of an executor by exposing various knobs +/// to control how a regex is executed and what kinds of resources it's +/// permitted to use. +pub struct ExecBuilder { + options: RegexOptions, + match_type: Option, + bytes: bool, + only_utf8: bool, +} + +/// Parsed represents a set of parsed regular expressions and their detected +/// literals. +struct Parsed { + exprs: Vec, + prefixes: Literals, + suffixes: Literals, + bytes: bool, +} + +impl ExecBuilder { + /// Create a regex execution builder. + /// + /// This uses default settings for everything except the regex itself, + /// which must be provided. Further knobs can be set by calling methods, + /// and then finally, `build` to actually create the executor. + pub fn new(re: &str) -> Self { + Self::new_many(&[re]) + } + + /// Like new, but compiles the union of the given regular expressions. + /// + /// Note that when compiling 2 or more regular expressions, capture groups + /// are completely unsupported. (This means both `find` and `captures` + /// wont work.) + pub fn new_many(res: I) -> Self + where S: AsRef, I: IntoIterator { + let mut opts = RegexOptions::default(); + opts.pats = res.into_iter().map(|s| s.as_ref().to_owned()).collect(); + Self::new_options(opts) + } + + /// Create a regex execution builder. + pub fn new_options(opts: RegexOptions) -> Self { + ExecBuilder { + options: opts, + match_type: None, + bytes: false, + only_utf8: true, + } + } + + /// Set the matching engine to be automatically determined. + /// + /// This is the default state and will apply whatever optimizations are + /// possible, such as running a DFA. + /// + /// This overrides whatever was previously set via the `nfa` or + /// `bounded_backtracking` methods. + pub fn automatic(mut self) -> Self { + self.match_type = None; + self + } + + /// Sets the matching engine to use the NFA algorithm no matter what + /// optimizations are possible. + /// + /// This overrides whatever was previously set via the `automatic` or + /// `bounded_backtracking` methods. + pub fn nfa(mut self) -> Self { + self.match_type = Some(MatchType::Nfa(MatchNfaType::PikeVM)); + self + } + + /// Sets the matching engine to use a bounded backtracking engine no + /// matter what optimizations are possible. + /// + /// One must use this with care, since the bounded backtracking engine + /// uses memory proportion to `len(regex) * len(text)`. + /// + /// This overrides whatever was previously set via the `automatic` or + /// `nfa` methods. + pub fn bounded_backtracking(mut self) -> Self { + self.match_type = Some(MatchType::Nfa(MatchNfaType::Backtrack)); + self + } + + /// Compiles byte based programs for use with the NFA matching engines. + /// + /// By default, the NFA engines match on Unicode scalar values. They can + /// be made to use byte based programs instead. In general, the byte based + /// programs are slower because of a less efficient encoding of character + /// classes. + /// + /// Note that this does not impact DFA matching engines, which always + /// execute on bytes. + pub fn bytes(mut self, yes: bool) -> Self { + self.bytes = yes; + self + } + + /// When disabled, the program compiled may match arbitrary bytes. + /// + /// When enabled (the default), all compiled programs exclusively match + /// valid UTF-8 bytes. + pub fn only_utf8(mut self, yes: bool) -> Self { + self.only_utf8 = yes; + self + } + + /// Set the Unicode flag. + pub fn unicode(mut self, yes: bool) -> Self { + self.options.unicode = yes; + self + } + + /// Parse the current set of patterns into their AST and extract literals. + fn parse(&self) -> Result { + let mut exprs = Vec::with_capacity(self.options.pats.len()); + let mut prefixes = Some(Literals::empty()); + let mut suffixes = Some(Literals::empty()); + let mut bytes = false; + let is_set = self.options.pats.len() > 1; + // If we're compiling a regex set and that set has any anchored + // expressions, then disable all literal optimizations. + for pat in &self.options.pats { + let mut parser = + ParserBuilder::new() + // TODO(burntsushi): Disable octal in regex 1.0. Nobody + // uses it, and we'll get better error messages when + // someone tries to use a backreference. Provide a new + // opt-in toggle for it though. + .octal(true) + .case_insensitive(self.options.case_insensitive) + .multi_line(self.options.multi_line) + .dot_matches_new_line(self.options.dot_matches_new_line) + .swap_greed(self.options.swap_greed) + .ignore_whitespace(self.options.ignore_whitespace) + .unicode(self.options.unicode) + .allow_invalid_utf8(!self.only_utf8) + .nest_limit(self.options.nest_limit) + .build(); + let expr = try!(parser.parse(pat)); + bytes = bytes || !expr.is_always_utf8(); + + if !expr.is_anchored_start() && expr.is_any_anchored_start() { + // Partial anchors unfortunately make it hard to use prefixes, + // so disable them. + prefixes = None; + } else if is_set && expr.is_anchored_start() { + // Regex sets with anchors do not go well with literal + // optimizations. + prefixes = None; + } + prefixes = prefixes.and_then(|mut prefixes| { + if !prefixes.union_prefixes(&expr) { + None + } else { + Some(prefixes) + } + }); + + if !expr.is_anchored_end() && expr.is_any_anchored_end() { + // Partial anchors unfortunately make it hard to use suffixes, + // so disable them. + suffixes = None; + } else if is_set && expr.is_anchored_end() { + // Regex sets with anchors do not go well with literal + // optimizations. + suffixes = None; + } + suffixes = suffixes.and_then(|mut suffixes| { + if !suffixes.union_suffixes(&expr) { + None + } else { + Some(suffixes) + } + }); + exprs.push(expr); + } + Ok(Parsed { + exprs: exprs, + prefixes: prefixes.unwrap_or_else(Literals::empty), + suffixes: suffixes.unwrap_or_else(Literals::empty), + bytes: bytes, + }) + } + + /// Build an executor that can run a regular expression. + pub fn build(self) -> Result { + // Special case when we have no patterns to compile. + // This can happen when compiling a regex set. + if self.options.pats.is_empty() { + let ro = Arc::new(ExecReadOnly { + res: vec![], + nfa: Program::new(), + dfa: Program::new(), + dfa_reverse: Program::new(), + suffixes: LiteralSearcher::empty(), + match_type: MatchType::Nothing, + }); + return Ok(Exec { ro: ro, cache: CachedThreadLocal::new() }); + } + let parsed = try!(self.parse()); + let mut nfa = try!( + Compiler::new() + .size_limit(self.options.size_limit) + .bytes(self.bytes || parsed.bytes) + .only_utf8(self.only_utf8) + .compile(&parsed.exprs)); + let mut dfa = try!( + Compiler::new() + .size_limit(self.options.size_limit) + .dfa(true) + .only_utf8(self.only_utf8) + .compile(&parsed.exprs)); + let mut dfa_reverse = try!( + Compiler::new() + .size_limit(self.options.size_limit) + .dfa(true) + .only_utf8(self.only_utf8) + .reverse(true) + .compile(&parsed.exprs)); + + let prefixes = parsed.prefixes.unambiguous_prefixes(); + let suffixes = parsed.suffixes.unambiguous_suffixes(); + nfa.prefixes = LiteralSearcher::prefixes(prefixes); + dfa.prefixes = nfa.prefixes.clone(); + dfa.dfa_size_limit = self.options.dfa_size_limit; + dfa_reverse.dfa_size_limit = self.options.dfa_size_limit; + + let mut ro = ExecReadOnly { + res: self.options.pats, + nfa: nfa, + dfa: dfa, + dfa_reverse: dfa_reverse, + suffixes: LiteralSearcher::suffixes(suffixes), + match_type: MatchType::Nothing, + }; + ro.match_type = ro.choose_match_type(self.match_type); + + let ro = Arc::new(ro); + Ok(Exec { ro: ro, cache: CachedThreadLocal::new() }) + } +} + +impl<'c> RegularExpression for ExecNoSyncStr<'c> { + type Text = str; + + fn slots_len(&self) -> usize { self.0.slots_len() } + + fn next_after_empty(&self, text: &str, i: usize) -> usize { + next_utf8(text.as_bytes(), i) + } + + #[inline(always)] // reduces constant overhead + fn shortest_match_at(&self, text: &str, start: usize) -> Option { + self.0.shortest_match_at(text.as_bytes(), start) + } + + #[inline(always)] // reduces constant overhead + fn is_match_at(&self, text: &str, start: usize) -> bool { + self.0.is_match_at(text.as_bytes(), start) + } + + #[inline(always)] // reduces constant overhead + fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> { + self.0.find_at(text.as_bytes(), start) + } + + #[inline(always)] // reduces constant overhead + fn read_captures_at( + &self, + locs: &mut Locations, + text: &str, + start: usize, + ) -> Option<(usize, usize)> { + self.0.read_captures_at(locs, text.as_bytes(), start) + } +} + +impl<'c> RegularExpression for ExecNoSync<'c> { + type Text = [u8]; + + /// Returns the number of capture slots in the regular expression. (There + /// are two slots for every capture group, corresponding to possibly empty + /// start and end locations of the capture.) + fn slots_len(&self) -> usize { + self.ro.nfa.captures.len() * 2 + } + + fn next_after_empty(&self, _text: &[u8], i: usize) -> usize { + i + 1 + } + + /// Returns the end of a match location, possibly occurring before the + /// end location of the correct leftmost-first match. + #[inline(always)] // reduces constant overhead + fn shortest_match_at(&self, text: &[u8], start: usize) -> Option { + if !self.is_anchor_end_match(text) { + return None; + } + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start).map(|(_, e)| e) + } + MatchType::Dfa | MatchType::DfaMany => { + match self.shortest_dfa(text, start) { + dfa::Result::Match(end) => Some(end), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.shortest_nfa(text, start), + } + } + MatchType::DfaAnchoredReverse => { + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + true, + &text[start..], + text.len(), + ) { + dfa::Result::Match(_) => Some(text.len()), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.shortest_nfa(text, start), + } + } + MatchType::DfaSuffix => { + match self.shortest_dfa_reverse_suffix(text, start) { + dfa::Result::Match(e) => Some(e), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.shortest_nfa(text, start), + } + } + MatchType::Nfa(ty) => self.shortest_nfa_type(ty, text, start), + MatchType::Nothing => None, + } + } + + /// Returns true if and only if the regex matches text. + /// + /// For single regular expressions, this is equivalent to calling + /// shortest_match(...).is_some(). + #[inline(always)] // reduces constant overhead + fn is_match_at(&self, text: &[u8], start: usize) -> bool { + if !self.is_anchor_end_match(text) { + return false; + } + // We need to do this dance because shortest_match relies on the NFA + // filling in captures[1], but a RegexSet has no captures. In other + // words, a RegexSet can't (currently) use shortest_match. ---AG + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start).is_some() + } + MatchType::Dfa | MatchType::DfaMany => { + match self.shortest_dfa(text, start) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => self.match_nfa(text, start), + } + } + MatchType::DfaAnchoredReverse => { + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + true, + &text[start..], + text.len(), + ) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => self.match_nfa(text, start), + } + } + MatchType::DfaSuffix => { + match self.shortest_dfa_reverse_suffix(text, start) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => self.match_nfa(text, start), + } + } + MatchType::Nfa(ty) => self.match_nfa_type(ty, text, start), + MatchType::Nothing => false, + } + } + + /// Finds the start and end location of the leftmost-first match, starting + /// at the given location. + #[inline(always)] // reduces constant overhead + fn find_at(&self, text: &[u8], start: usize) -> Option<(usize, usize)> { + if !self.is_anchor_end_match(text) { + return None; + } + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start) + } + MatchType::Dfa => { + match self.find_dfa_forward(text, start) { + dfa::Result::Match((s, e)) => Some((s, e)), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => { + self.find_nfa(MatchNfaType::Auto, text, start) + } + } + } + MatchType::DfaAnchoredReverse => { + match self.find_dfa_anchored_reverse(text, start) { + dfa::Result::Match((s, e)) => Some((s, e)), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => { + self.find_nfa(MatchNfaType::Auto, text, start) + } + } + } + MatchType::DfaSuffix => { + match self.find_dfa_reverse_suffix(text, start) { + dfa::Result::Match((s, e)) => Some((s, e)), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => { + self.find_nfa(MatchNfaType::Auto, text, start) + } + } + } + MatchType::Nfa(ty) => self.find_nfa(ty, text, start), + MatchType::Nothing => None, + MatchType::DfaMany => { + unreachable!("BUG: RegexSet cannot be used with find") + } + } + } + + /// Finds the start and end location of the leftmost-first match and also + /// fills in all matching capture groups. + /// + /// The number of capture slots given should be equal to the total number + /// of capture slots in the compiled program. + /// + /// Note that the first two slots always correspond to the start and end + /// locations of the overall match. + fn read_captures_at( + &self, + locs: &mut Locations, + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + let slots = as_slots(locs); + for slot in slots.iter_mut() { + *slot = None; + } + // If the caller unnecessarily uses this, then we try to save them + // from themselves. + match slots.len() { + 0 => return self.find_at(text, start), + 2 => { + return self.find_at(text, start).map(|(s, e)| { + slots[0] = Some(s); + slots[1] = Some(e); + (s, e) + }); + } + _ => {} // fallthrough + } + if !self.is_anchor_end_match(text) { + return None; + } + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start).and_then(|(s, e)| { + self.captures_nfa_with_match(slots, text, s, e) + }) + } + MatchType::Dfa => { + if self.ro.nfa.is_anchored_start { + self.captures_nfa(slots, text, start) + } else { + match self.find_dfa_forward(text, start) { + dfa::Result::Match((s, e)) => { + self.captures_nfa_with_match(slots, text, s, e) + } + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.captures_nfa(slots, text, start), + } + } + } + MatchType::DfaAnchoredReverse => { + match self.find_dfa_anchored_reverse(text, start) { + dfa::Result::Match((s, e)) => { + self.captures_nfa_with_match(slots, text, s, e) + } + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.captures_nfa(slots, text, start), + } + } + MatchType::DfaSuffix => { + match self.find_dfa_reverse_suffix(text, start) { + dfa::Result::Match((s, e)) => { + self.captures_nfa_with_match(slots, text, s, e) + } + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.captures_nfa(slots, text, start), + } + } + MatchType::Nfa(ty) => { + self.captures_nfa_type(ty, slots, text, start) + } + MatchType::Nothing => None, + MatchType::DfaMany => { + unreachable!("BUG: RegexSet cannot be used with captures") + } + } + } +} + +impl<'c> ExecNoSync<'c> { + /// Finds the leftmost-first match using only literal search. + #[inline(always)] // reduces constant overhead + fn find_literals( + &self, + ty: MatchLiteralType, + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + use self::MatchLiteralType::*; + match ty { + Unanchored => { + let lits = &self.ro.nfa.prefixes; + lits.find(&text[start..]) + .map(|(s, e)| (start + s, start + e)) + } + AnchoredStart => { + let lits = &self.ro.nfa.prefixes; + if !self.ro.nfa.is_anchored_start + || (self.ro.nfa.is_anchored_start && start == 0) { + lits.find_start(&text[start..]) + .map(|(s, e)| (start + s, start + e)) + } else { + None + } + } + AnchoredEnd => { + let lits = &self.ro.suffixes; + lits.find_end(&text[start..]) + .map(|(s, e)| (start + s, start + e)) + } + } + } + + /// Finds the leftmost-first match (start and end) using only the DFA. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn find_dfa_forward( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result<(usize, usize)> { + use dfa::Result::*; + let end = match dfa::Fsm::forward( + &self.ro.dfa, + self.cache, + false, + text, + start, + ) { + NoMatch(i) => return NoMatch(i), + Quit => return Quit, + Match(end) if start == end => return Match((start, start)), + Match(end) => end, + }; + // Now run the DFA in reverse to find the start of the match. + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + false, + &text[start..], + end - start, + ) { + Match(s) => Match((start + s, end)), + NoMatch(i) => NoMatch(i), + Quit => Quit, + } + } + + /// Finds the leftmost-first match (start and end) using only the DFA, + /// but assumes the regex is anchored at the end and therefore starts at + /// the end of the regex and matches in reverse. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn find_dfa_anchored_reverse( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result<(usize, usize)> { + use dfa::Result::*; + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + false, + &text[start..], + text.len() - start, + ) { + Match(s) => Match((start + s, text.len())), + NoMatch(i) => NoMatch(i), + Quit => Quit, + } + } + + /// Finds the end of the shortest match using only the DFA. + #[inline(always)] // reduces constant overhead + fn shortest_dfa(&self, text: &[u8], start: usize) -> dfa::Result { + dfa::Fsm::forward(&self.ro.dfa, self.cache, true, text, start) + } + + /// Finds the end of the shortest match using only the DFA by scanning for + /// suffix literals. + /// + #[inline(always)] // reduces constant overhead + fn shortest_dfa_reverse_suffix( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result { + match self.exec_dfa_reverse_suffix(text, start) { + None => self.shortest_dfa(text, start), + Some(r) => r.map(|(_, end)| end), + } + } + + /// Finds the end of the shortest match using only the DFA by scanning for + /// suffix literals. It also reports the start of the match. + /// + /// Note that if None is returned, then the optimization gave up to avoid + /// worst case quadratic behavior. A forward scanning DFA should be tried + /// next. + /// + /// If a match is returned and the full leftmost-first match is desired, + /// then a forward scan starting from the beginning of the match must be + /// done. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn exec_dfa_reverse_suffix( + &self, + text: &[u8], + original_start: usize, + ) -> Option> { + use dfa::Result::*; + + let lcs = self.ro.suffixes.lcs(); + debug_assert!(lcs.len() >= 1); + let mut start = original_start; + let mut end = start; + while end <= text.len() { + start = end; + end += match lcs.find(&text[end..]) { + None => return Some(NoMatch(text.len())), + Some(start) => start + lcs.len(), + }; + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + false, + &text[start..end], + end - start, + ) { + Match(0) | NoMatch(0) => return None, + Match(s) => return Some(Match((s + start, end))), + NoMatch(_) => continue, + Quit => return Some(Quit), + }; + } + Some(NoMatch(text.len())) + } + + /// Finds the leftmost-first match (start and end) using only the DFA + /// by scanning for suffix literals. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn find_dfa_reverse_suffix( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result<(usize, usize)> { + use dfa::Result::*; + + let match_start = match self.exec_dfa_reverse_suffix(text, start) { + None => return self.find_dfa_forward(text, start), + Some(Match((start, _))) => start, + Some(r) => return r, + }; + // At this point, we've found a match. The only way to quit now + // without a match is if the DFA gives up (seems unlikely). + // + // Now run the DFA forwards to find the proper end of the match. + // (The suffix literal match can only indicate the earliest + // possible end location, which may appear before the end of the + // leftmost-first match.) + match dfa::Fsm::forward( + &self.ro.dfa, + self.cache, + false, + text, + match_start, + ) { + NoMatch(_) => panic!("BUG: reverse match implies forward match"), + Quit => Quit, + Match(e) => Match((match_start, e)), + } + } + + /// Executes the NFA engine to return whether there is a match or not. + /// + /// Ideally, we could use shortest_nfa(...).is_some() and get the same + /// performance characteristics, but regex sets don't have captures, which + /// shortest_nfa depends on. + fn match_nfa( + &self, + text: &[u8], + start: usize, + ) -> bool { + self.match_nfa_type(MatchNfaType::Auto, text, start) + } + + /// Like match_nfa, but allows specification of the type of NFA engine. + fn match_nfa_type( + &self, + ty: MatchNfaType, + text: &[u8], + start: usize, + ) -> bool { + self.exec_nfa(ty, &mut [false], &mut [], true, text, start) + } + + /// Finds the shortest match using an NFA. + fn shortest_nfa(&self, text: &[u8], start: usize) -> Option { + self.shortest_nfa_type(MatchNfaType::Auto, text, start) + } + + /// Like shortest_nfa, but allows specification of the type of NFA engine. + fn shortest_nfa_type( + &self, + ty: MatchNfaType, + text: &[u8], + start: usize, + ) -> Option { + let mut slots = [None, None]; + if self.exec_nfa(ty, &mut [false], &mut slots, true, text, start) { + slots[1] + } else { + None + } + } + + /// Like find, but executes an NFA engine. + fn find_nfa( + &self, + ty: MatchNfaType, + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + let mut slots = [None, None]; + if self.exec_nfa(ty, &mut [false], &mut slots, false, text, start) { + match (slots[0], slots[1]) { + (Some(s), Some(e)) => Some((s, e)), + _ => None, + } + } else { + None + } + } + + /// Like find_nfa, but fills in captures and restricts the search space + /// using previously found match information. + /// + /// `slots` should have length equal to `2 * nfa.captures.len()`. + fn captures_nfa_with_match( + &self, + slots: &mut [Slot], + text: &[u8], + match_start: usize, + match_end: usize, + ) -> Option<(usize, usize)> { + // We can't use match_end directly, because we may need to examine one + // "character" after the end of a match for lookahead operators. We + // need to move two characters beyond the end, since some look-around + // operations may falsely assume a premature end of text otherwise. + let e = cmp::min( + next_utf8(text, next_utf8(text, match_end)), text.len()); + self.captures_nfa(slots, &text[..e], match_start) + } + + /// Like find_nfa, but fills in captures. + /// + /// `slots` should have length equal to `2 * nfa.captures.len()`. + fn captures_nfa( + &self, + slots: &mut [Slot], + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + self.captures_nfa_type(MatchNfaType::Auto, slots, text, start) + } + + /// Like captures_nfa, but allows specification of type of NFA engine. + fn captures_nfa_type( + &self, + ty: MatchNfaType, + slots: &mut [Slot], + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + if self.exec_nfa(ty, &mut [false], slots, false, text, start) { + match (slots[0], slots[1]) { + (Some(s), Some(e)) => Some((s, e)), + _ => None, + } + } else { + None + } + } + + fn exec_nfa( + &self, + mut ty: MatchNfaType, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + text: &[u8], + start: usize, + ) -> bool { + use self::MatchNfaType::*; + if let Auto = ty { + if backtrack::should_exec(self.ro.nfa.len(), text.len()) { + ty = Backtrack; + } else { + ty = PikeVM; + } + } + match ty { + Auto => unreachable!(), + Backtrack => self.exec_backtrack(matches, slots, text, start), + PikeVM => { + self.exec_pikevm( + matches, slots, quit_after_match, text, start) + } + } + } + + /// Always run the NFA algorithm. + fn exec_pikevm( + &self, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + text: &[u8], + start: usize, + ) -> bool { + if self.ro.nfa.uses_bytes() { + pikevm::Fsm::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + quit_after_match, + ByteInput::new(text, self.ro.nfa.only_utf8), + start) + } else { + pikevm::Fsm::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + quit_after_match, + CharInput::new(text), + start) + } + } + + /// Always runs the NFA using bounded backtracking. + fn exec_backtrack( + &self, + matches: &mut [bool], + slots: &mut [Slot], + text: &[u8], + start: usize, + ) -> bool { + if self.ro.nfa.uses_bytes() { + backtrack::Bounded::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + ByteInput::new(text, self.ro.nfa.only_utf8), + start) + } else { + backtrack::Bounded::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + CharInput::new(text), + start) + } + } + + /// Finds which regular expressions match the given text. + /// + /// `matches` should have length equal to the number of regexes being + /// searched. + /// + /// This is only useful when one wants to know which regexes in a set + /// match some text. + pub fn many_matches_at( + &self, + matches: &mut [bool], + text: &[u8], + start: usize, + ) -> bool { + use self::MatchType::*; + if !self.is_anchor_end_match(text) { + return false; + } + match self.ro.match_type { + Literal(ty) => { + debug_assert_eq!(matches.len(), 1); + matches[0] = self.find_literals(ty, text, start).is_some(); + matches[0] + } + Dfa | DfaAnchoredReverse | DfaSuffix | DfaMany => { + match dfa::Fsm::forward_many( + &self.ro.dfa, + self.cache, + matches, + text, + start, + ) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => { + self.exec_nfa( + MatchNfaType::Auto, + matches, + &mut [], + false, + text, + start) + } + } + } + Nfa(ty) => self.exec_nfa(ty, matches, &mut [], false, text, start), + Nothing => false, + } + } + + #[inline(always)] // reduces constant overhead + fn is_anchor_end_match(&self, text: &[u8]) -> bool { + // Only do this check if the haystack is big (>1MB). + if text.len() > (1<<20) && self.ro.nfa.is_anchored_end { + let lcs = self.ro.suffixes.lcs(); + if lcs.len() >= 1 && !lcs.is_suffix(text) { + return false; + } + } + true + } + + pub fn capture_name_idx(&self) -> &Arc> { + &self.ro.nfa.capture_name_idx + } +} + +impl<'c> ExecNoSyncStr<'c> { + pub fn capture_name_idx(&self) -> &Arc> { + self.0.capture_name_idx() + } +} + +impl Exec { + /// Get a searcher that isn't Sync. + #[inline(always)] // reduces constant overhead + pub fn searcher(&self) -> ExecNoSync { + let create = || Box::new(RefCell::new(ProgramCacheInner::new(&self.ro))); + ExecNoSync { + ro: &self.ro, // a clone is too expensive here! (and not needed) + cache: self.cache.get_or(create), + } + } + + /// Get a searcher that isn't Sync and can match on &str. + #[inline(always)] // reduces constant overhead + pub fn searcher_str(&self) -> ExecNoSyncStr { + ExecNoSyncStr(self.searcher()) + } + + /// Build a Regex from this executor. + pub fn into_regex(self) -> re_unicode::Regex { + re_unicode::Regex::from(self) + } + + /// Build a RegexSet from this executor. + pub fn into_regex_set(self) -> re_set::unicode::RegexSet { + re_set::unicode::RegexSet::from(self) + } + + /// Build a Regex from this executor that can match arbitrary bytes. + pub fn into_byte_regex(self) -> re_bytes::Regex { + re_bytes::Regex::from(self) + } + + /// Build a RegexSet from this executor that can match arbitrary bytes. + pub fn into_byte_regex_set(self) -> re_set::bytes::RegexSet { + re_set::bytes::RegexSet::from(self) + } + + /// The original regular expressions given by the caller that were + /// compiled. + pub fn regex_strings(&self) -> &[String] { + &self.ro.res + } + + /// Return a slice of capture names. + /// + /// Any capture that isn't named is None. + pub fn capture_names(&self) -> &[Option] { + &self.ro.nfa.captures + } + + /// Return a reference to named groups mapping (from group name to + /// group position). + pub fn capture_name_idx(&self) -> &Arc> { + &self.ro.nfa.capture_name_idx + } +} + +impl Clone for Exec { + fn clone(&self) -> Exec { + Exec { + ro: self.ro.clone(), + cache: CachedThreadLocal::new(), + } + } +} + +impl ExecReadOnly { + fn choose_match_type(&self, hint: Option) -> MatchType { + use self::MatchType::*; + if let Some(Nfa(_)) = hint { + return hint.unwrap(); + } + // If the NFA is empty, then we'll never match anything. + if self.nfa.insts.is_empty() { + return Nothing; + } + // If our set of prefixes is complete, then we can use it to find + // a match in lieu of a regex engine. This doesn't quite work well in + // the presence of multiple regexes, so only do it when there's one. + // + // TODO(burntsushi): Also, don't try to match literals if the regex is + // partially anchored. We could technically do it, but we'd need to + // create two sets of literals: all of them and then the subset that + // aren't anchored. We would then only search for all of them when at + // the beginning of the input and use the subset in all other cases. + if self.res.len() == 1 { + if self.nfa.prefixes.complete() { + return if self.nfa.is_anchored_start { + Literal(MatchLiteralType::AnchoredStart) + } else { + Literal(MatchLiteralType::Unanchored) + }; + } + if self.suffixes.complete() { + return if self.nfa.is_anchored_end { + Literal(MatchLiteralType::AnchoredEnd) + } else { + // This case shouldn't happen. When the regex isn't + // anchored, then complete prefixes should imply complete + // suffixes. + Literal(MatchLiteralType::Unanchored) + }; + } + } + // If we can execute the DFA, then we totally should. + if dfa::can_exec(&self.dfa) { + // Regex sets require a slightly specialized path. + if self.res.len() >= 2 { + return DfaMany; + } + // If the regex is anchored at the end but not the start, then + // just match in reverse from the end of the haystack. + if !self.nfa.is_anchored_start && self.nfa.is_anchored_end { + return DfaAnchoredReverse; + } + // If there's a longish suffix literal, then it might be faster + // to look for that first. + if self.should_suffix_scan() { + return DfaSuffix; + } + // Fall back to your garden variety forward searching lazy DFA. + return Dfa; + } + // We're so totally hosed. + Nfa(MatchNfaType::Auto) + } + + /// Returns true if the program is amenable to suffix scanning. + /// + /// When this is true, as a heuristic, we assume it is OK to quickly scan + /// for suffix literals and then do a *reverse* DFA match from any matches + /// produced by the literal scan. (And then followed by a forward DFA + /// search, since the previously found suffix literal maybe not actually be + /// the end of a match.) + /// + /// This is a bit of a specialized optimization, but can result in pretty + /// big performance wins if 1) there are no prefix literals and 2) the + /// suffix literals are pretty rare in the text. (1) is obviously easy to + /// account for but (2) is harder. As a proxy, we assume that longer + /// strings are generally rarer, so we only enable this optimization when + /// we have a meaty suffix. + fn should_suffix_scan(&self) -> bool { + if self.suffixes.is_empty() { + return false; + } + let lcs_len = self.suffixes.lcs().char_len(); + lcs_len >= 3 && lcs_len > self.dfa.prefixes.lcp().char_len() + } +} + +#[derive(Clone, Copy, Debug)] +enum MatchType { + /// A single or multiple literal search. This is only used when the regex + /// can be decomposed into unambiguous literal search. + Literal(MatchLiteralType), + /// A normal DFA search. + Dfa, + /// A reverse DFA search starting from the end of a haystack. + DfaAnchoredReverse, + /// A reverse DFA search with suffix literal scanning. + DfaSuffix, + /// Use the DFA on two or more regular expressions. + DfaMany, + /// An NFA variant. + Nfa(MatchNfaType), + /// No match is ever possible, so don't ever try to search. + Nothing, +} + +#[derive(Clone, Copy, Debug)] +enum MatchLiteralType { + /// Match literals anywhere in text. + Unanchored, + /// Match literals only at the start of text. + AnchoredStart, + /// Match literals only at the end of text. + AnchoredEnd, +} + +#[derive(Clone, Copy, Debug)] +enum MatchNfaType { + /// Choose between Backtrack and PikeVM. + Auto, + /// NFA bounded backtracking. + /// + /// (This is only set by tests, since it never makes sense to always want + /// backtracking.) + Backtrack, + /// The Pike VM. + /// + /// (This is only set by tests, since it never makes sense to always want + /// the Pike VM.) + PikeVM, +} + +/// `ProgramCache` maintains reusable allocations for each matching engine +/// available to a particular program. +pub type ProgramCache = RefCell; + +#[derive(Clone, Debug)] +pub struct ProgramCacheInner { + pub pikevm: pikevm::Cache, + pub backtrack: backtrack::Cache, + pub dfa: dfa::Cache, + pub dfa_reverse: dfa::Cache, +} + +impl ProgramCacheInner { + fn new(ro: &ExecReadOnly) -> Self { + ProgramCacheInner { + pikevm: pikevm::Cache::new(&ro.nfa), + backtrack: backtrack::Cache::new(&ro.nfa), + dfa: dfa::Cache::new(&ro.dfa), + dfa_reverse: dfa::Cache::new(&ro.dfa_reverse), + } + } +} + +#[cfg(test)] +mod test { + #[test] + fn uppercut_s_backtracking_bytes_default_bytes_mismatch() { + use internal::ExecBuilder; + + let backtrack_bytes_re = ExecBuilder::new("^S") + .bounded_backtracking() + .only_utf8(false) + .build() + .map(|exec| exec.into_byte_regex()) + .map_err(|err| format!("{}", err)) + .unwrap(); + + let default_bytes_re = ExecBuilder::new("^S") + .only_utf8(false) + .build() + .map(|exec| exec.into_byte_regex()) + .map_err(|err| format!("{}", err)) + .unwrap(); + + let input = vec![83, 83]; + + let s1 = backtrack_bytes_re.split(&input); + let s2 = default_bytes_re.split(&input); + for (chunk1, chunk2) in s1.zip(s2) { + assert_eq!(chunk1, chunk2); + } + } + + #[test] + fn unicode_lit_star_backtracking_utf8bytes_default_utf8bytes_mismatch() { + use internal::ExecBuilder; + + let backtrack_bytes_re = ExecBuilder::new(r"^(?u:\*)") + .bounded_backtracking() + .bytes(true) + .build() + .map(|exec| exec.into_regex()) + .map_err(|err| format!("{}", err)) + .unwrap(); + + let default_bytes_re = ExecBuilder::new(r"^(?u:\*)") + .bytes(true) + .build() + .map(|exec| exec.into_regex()) + .map_err(|err| format!("{}", err)) + .unwrap(); + + let input = "**"; + + let s1 = backtrack_bytes_re.split(input); + let s2 = default_bytes_re.split(input); + for (chunk1, chunk2) in s1.zip(s2) { + assert_eq!(chunk1, chunk2); + } + } +} diff --git a/bash-5.1/vendor/regex/src/expand.rs b/bash-5.1/vendor/regex/src/expand.rs new file mode 100644 index 0000000..a5e43b5 --- /dev/null +++ b/bash-5.1/vendor/regex/src/expand.rs @@ -0,0 +1,215 @@ +use std::str; + +use memchr::memchr; + +use re_bytes; +use re_unicode; + +pub fn expand_str( + caps: &re_unicode::Captures, + mut replacement: &str, + dst: &mut String, +) { + while !replacement.is_empty() { + match memchr(b'$', replacement.as_bytes()) { + None => break, + Some(i) => { + dst.push_str(&replacement[..i]); + replacement = &replacement[i..]; + } + } + if replacement.as_bytes().get(1).map_or(false, |&b| b == b'$') { + dst.push_str("$"); + replacement = &replacement[2..]; + continue; + } + debug_assert!(!replacement.is_empty()); + let cap_ref = match find_cap_ref(replacement) { + Some(cap_ref) => cap_ref, + None => { + dst.push_str("$"); + replacement = &replacement[1..]; + continue; + } + }; + replacement = &replacement[cap_ref.end..]; + match cap_ref.cap { + Ref::Number(i) => { + dst.push_str( + caps.get(i).map(|m| m.as_str()).unwrap_or("")); + } + Ref::Named(name) => { + dst.push_str( + caps.name(name).map(|m| m.as_str()).unwrap_or("")); + } + } + } + dst.push_str(replacement); +} + +pub fn expand_bytes( + caps: &re_bytes::Captures, + mut replacement: &[u8], + dst: &mut Vec, +) { + while !replacement.is_empty() { + match memchr(b'$', replacement) { + None => break, + Some(i) => { + dst.extend(&replacement[..i]); + replacement = &replacement[i..]; + } + } + if replacement.get(1).map_or(false, |&b| b == b'$') { + dst.push(b'$'); + replacement = &replacement[2..]; + continue; + } + debug_assert!(!replacement.is_empty()); + let cap_ref = match find_cap_ref(replacement) { + Some(cap_ref) => cap_ref, + None => { + dst.push(b'$'); + replacement = &replacement[1..]; + continue; + } + }; + replacement = &replacement[cap_ref.end..]; + match cap_ref.cap { + Ref::Number(i) => { + dst.extend( + caps.get(i).map(|m| m.as_bytes()).unwrap_or(b"")); + } + Ref::Named(name) => { + dst.extend( + caps.name(name).map(|m| m.as_bytes()).unwrap_or(b"")); + } + } + } + dst.extend(replacement); +} + +/// `CaptureRef` represents a reference to a capture group inside some text. +/// The reference is either a capture group name or a number. +/// +/// It is also tagged with the position in the text immediately proceding the +/// capture reference. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct CaptureRef<'a> { + cap: Ref<'a>, + end: usize, +} + +/// A reference to a capture group in some text. +/// +/// e.g., `$2`, `$foo`, `${foo}`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Ref<'a> { + Named(&'a str), + Number(usize), +} + +impl<'a> From<&'a str> for Ref<'a> { + fn from(x: &'a str) -> Ref<'a> { + Ref::Named(x) + } +} + +impl From for Ref<'static> { + fn from(x: usize) -> Ref<'static> { + Ref::Number(x) + } +} + +/// Parses a possible reference to a capture group name in the given text, +/// starting at the beginning of `replacement`. +/// +/// If no such valid reference could be found, None is returned. +fn find_cap_ref>( + replacement: &T, +) -> Option { + let mut i = 0; + let rep: &[u8] = replacement.as_ref(); + if rep.len() <= 1 || rep[0] != b'$' { + return None; + } + let mut brace = false; + i += 1; + if rep[i] == b'{' { + brace = true; + i += 1; + } + let mut cap_end = i; + while rep.get(cap_end).map_or(false, is_valid_cap_letter) { + cap_end += 1; + } + if cap_end == i { + return None; + } + // We just verified that the range 0..cap_end is valid ASCII, so it must + // therefore be valid UTF-8. If we really cared, we could avoid this UTF-8 + // check with either unsafe or by parsing the number straight from &[u8]. + let cap = str::from_utf8(&rep[i..cap_end]) + .expect("valid UTF-8 capture name"); + if brace { + if !rep.get(cap_end).map_or(false, |&b| b == b'}') { + return None; + } + cap_end += 1; + } + Some(CaptureRef { + cap: match cap.parse::() { + Ok(i) => Ref::Number(i as usize), + Err(_) => Ref::Named(cap), + }, + end: cap_end, + }) +} + +/// Returns true if and only if the given byte is allowed in a capture name. +fn is_valid_cap_letter(b: &u8) -> bool { + match *b { + b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' | b'_' => true, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::{CaptureRef, find_cap_ref}; + + macro_rules! find { + ($name:ident, $text:expr) => { + #[test] + fn $name() { + assert_eq!(None, find_cap_ref($text)); + } + }; + ($name:ident, $text:expr, $capref:expr) => { + #[test] + fn $name() { + assert_eq!(Some($capref), find_cap_ref($text)); + } + }; + } + + macro_rules! c { + ($name_or_number:expr, $pos:expr) => { + CaptureRef { cap: $name_or_number.into(), end: $pos } + }; + } + + find!(find_cap_ref1, "$foo", c!("foo", 4)); + find!(find_cap_ref2, "${foo}", c!("foo", 6)); + find!(find_cap_ref3, "$0", c!(0, 2)); + find!(find_cap_ref4, "$5", c!(5, 2)); + find!(find_cap_ref5, "$10", c!(10, 3)); + find!(find_cap_ref6, "$42a", c!("42a", 4)); + find!(find_cap_ref7, "${42}a", c!(42, 5)); + find!(find_cap_ref8, "${42"); + find!(find_cap_ref9, "${42 "); + find!(find_cap_ref10, " $0 "); + find!(find_cap_ref11, "$"); + find!(find_cap_ref12, " "); + find!(find_cap_ref13, ""); +} diff --git a/bash-5.1/vendor/regex/src/freqs.rs b/bash-5.1/vendor/regex/src/freqs.rs new file mode 100644 index 0000000..92bafc1 --- /dev/null +++ b/bash-5.1/vendor/regex/src/freqs.rs @@ -0,0 +1,271 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/frequencies.py", do not +// edit directly + +pub const BYTE_FREQUENCIES: [u8; 256] = [ + 55, // '\x00' + 52, // '\x01' + 51, // '\x02' + 50, // '\x03' + 49, // '\x04' + 48, // '\x05' + 47, // '\x06' + 46, // '\x07' + 45, // '\x08' + 103, // '\t' + 242, // '\n' + 66, // '\x0b' + 67, // '\x0c' + 229, // '\r' + 44, // '\x0e' + 43, // '\x0f' + 42, // '\x10' + 41, // '\x11' + 40, // '\x12' + 39, // '\x13' + 38, // '\x14' + 37, // '\x15' + 36, // '\x16' + 35, // '\x17' + 34, // '\x18' + 33, // '\x19' + 56, // '\x1a' + 32, // '\x1b' + 31, // '\x1c' + 30, // '\x1d' + 29, // '\x1e' + 28, // '\x1f' + 255, // ' ' + 148, // '!' + 164, // '"' + 149, // '#' + 136, // '$' + 160, // '%' + 155, // '&' + 173, // "'" + 221, // '(' + 222, // ')' + 134, // '*' + 122, // '+' + 232, // ',' + 202, // '-' + 215, // '.' + 224, // '/' + 208, // '0' + 220, // '1' + 204, // '2' + 187, // '3' + 183, // '4' + 179, // '5' + 177, // '6' + 168, // '7' + 178, // '8' + 200, // '9' + 226, // ':' + 195, // ';' + 154, // '<' + 184, // '=' + 174, // '>' + 126, // '?' + 120, // '@' + 191, // 'A' + 157, // 'B' + 194, // 'C' + 170, // 'D' + 189, // 'E' + 162, // 'F' + 161, // 'G' + 150, // 'H' + 193, // 'I' + 142, // 'J' + 137, // 'K' + 171, // 'L' + 176, // 'M' + 185, // 'N' + 167, // 'O' + 186, // 'P' + 112, // 'Q' + 175, // 'R' + 192, // 'S' + 188, // 'T' + 156, // 'U' + 140, // 'V' + 143, // 'W' + 123, // 'X' + 133, // 'Y' + 128, // 'Z' + 147, // '[' + 138, // '\\' + 146, // ']' + 114, // '^' + 223, // '_' + 151, // '`' + 249, // 'a' + 216, // 'b' + 238, // 'c' + 236, // 'd' + 253, // 'e' + 227, // 'f' + 218, // 'g' + 230, // 'h' + 247, // 'i' + 135, // 'j' + 180, // 'k' + 241, // 'l' + 233, // 'm' + 246, // 'n' + 244, // 'o' + 231, // 'p' + 139, // 'q' + 245, // 'r' + 243, // 's' + 251, // 't' + 235, // 'u' + 201, // 'v' + 196, // 'w' + 240, // 'x' + 214, // 'y' + 152, // 'z' + 182, // '{' + 205, // '|' + 181, // '}' + 127, // '~' + 27, // '\x7f' + 212, // '\x80' + 211, // '\x81' + 210, // '\x82' + 213, // '\x83' + 228, // '\x84' + 197, // '\x85' + 169, // '\x86' + 159, // '\x87' + 131, // '\x88' + 172, // '\x89' + 105, // '\x8a' + 80, // '\x8b' + 98, // '\x8c' + 96, // '\x8d' + 97, // '\x8e' + 81, // '\x8f' + 207, // '\x90' + 145, // '\x91' + 116, // '\x92' + 115, // '\x93' + 144, // '\x94' + 130, // '\x95' + 153, // '\x96' + 121, // '\x97' + 107, // '\x98' + 132, // '\x99' + 109, // '\x9a' + 110, // '\x9b' + 124, // '\x9c' + 111, // '\x9d' + 82, // '\x9e' + 108, // '\x9f' + 118, // '\xa0' + 141, // '¡' + 113, // '¢' + 129, // '£' + 119, // '¤' + 125, // '¥' + 165, // '¦' + 117, // '§' + 92, // '¨' + 106, // '©' + 83, // 'ª' + 72, // '«' + 99, // '¬' + 93, // '\xad' + 65, // '®' + 79, // '¯' + 166, // '°' + 237, // '±' + 163, // '²' + 199, // '³' + 190, // '´' + 225, // 'µ' + 209, // '¶' + 203, // '·' + 198, // '¸' + 217, // '¹' + 219, // 'º' + 206, // '»' + 234, // '¼' + 248, // '½' + 158, // '¾' + 239, // '¿' + 255, // 'À' + 255, // 'Á' + 255, // 'Â' + 255, // 'Ã' + 255, // 'Ä' + 255, // 'Å' + 255, // 'Æ' + 255, // 'Ç' + 255, // 'È' + 255, // 'É' + 255, // 'Ê' + 255, // 'Ë' + 255, // 'Ì' + 255, // 'Í' + 255, // 'Î' + 255, // 'Ï' + 255, // 'Ð' + 255, // 'Ñ' + 255, // 'Ò' + 255, // 'Ó' + 255, // 'Ô' + 255, // 'Õ' + 255, // 'Ö' + 255, // '×' + 255, // 'Ø' + 255, // 'Ù' + 255, // 'Ú' + 255, // 'Û' + 255, // 'Ü' + 255, // 'Ý' + 255, // 'Þ' + 255, // 'ß' + 255, // 'à' + 255, // 'á' + 255, // 'â' + 255, // 'ã' + 255, // 'ä' + 255, // 'å' + 255, // 'æ' + 255, // 'ç' + 255, // 'è' + 255, // 'é' + 255, // 'ê' + 255, // 'ë' + 255, // 'ì' + 255, // 'í' + 255, // 'î' + 255, // 'ï' + 255, // 'ð' + 255, // 'ñ' + 255, // 'ò' + 255, // 'ó' + 255, // 'ô' + 255, // 'õ' + 255, // 'ö' + 255, // '÷' + 255, // 'ø' + 255, // 'ù' + 255, // 'ú' + 255, // 'û' + 255, // 'ü' + 255, // 'ý' + 255, // 'þ' + 255, // 'ÿ' +]; diff --git a/bash-5.1/vendor/regex/src/input.rs b/bash-5.1/vendor/regex/src/input.rs new file mode 100644 index 0000000..56097bd --- /dev/null +++ b/bash-5.1/vendor/regex/src/input.rs @@ -0,0 +1,420 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::char; +use std::cmp::Ordering; +use std::fmt; +use std::ops; +use std::u32; + +use syntax; + +use literal::LiteralSearcher; +use prog::InstEmptyLook; +use utf8::{decode_utf8, decode_last_utf8}; + +/// Represents a location in the input. +#[derive(Clone, Copy, Debug)] +pub struct InputAt { + pos: usize, + c: Char, + byte: Option, + len: usize, +} + +impl InputAt { + /// Returns true iff this position is at the beginning of the input. + pub fn is_start(&self) -> bool { + self.pos == 0 + } + + /// Returns true iff this position is past the end of the input. + pub fn is_end(&self) -> bool { + self.c.is_none() && self.byte.is_none() + } + + /// Returns the character at this position. + /// + /// If this position is just before or after the input, then an absent + /// character is returned. + pub fn char(&self) -> Char { + self.c + } + + /// Returns the byte at this position. + pub fn byte(&self) -> Option { + self.byte + } + + /// Returns the UTF-8 width of the character at this position. + pub fn len(&self) -> usize { + self.len + } + + /// Returns whether the UTF-8 width of the character at this position + /// is zero. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Returns the byte offset of this position. + pub fn pos(&self) -> usize { + self.pos + } + + /// Returns the byte offset of the next position in the input. + pub fn next_pos(&self) -> usize { + self.pos + self.len + } +} + +/// An abstraction over input used in the matching engines. +pub trait Input { + /// Return an encoding of the position at byte offset `i`. + fn at(&self, i: usize) -> InputAt; + + /// Return the Unicode character occurring next to `at`. + /// + /// If no such character could be decoded, then `Char` is absent. + fn next_char(&self, at: InputAt) -> Char; + + /// Return the Unicode character occurring previous to `at`. + /// + /// If no such character could be decoded, then `Char` is absent. + fn previous_char(&self, at: InputAt) -> Char; + + /// Return true if the given empty width instruction matches at the + /// input position given. + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool; + + /// Scan the input for a matching prefix. + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option; + + /// The number of bytes in the input. + fn len(&self) -> usize; + + /// Whether the input is empty. + fn is_empty(&self) -> bool { self.len() == 0 } + + /// Return the given input as a sequence of bytes. + fn as_bytes(&self) -> &[u8]; +} + +impl<'a, T: Input> Input for &'a T { + fn at(&self, i: usize) -> InputAt { (**self).at(i) } + + fn next_char(&self, at: InputAt) -> Char { (**self).next_char(at) } + + fn previous_char(&self, at: InputAt) -> Char { (**self).previous_char(at) } + + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { + (**self).is_empty_match(at, empty) + } + + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option { + (**self).prefix_at(prefixes, at) + } + + fn len(&self) -> usize { (**self).len() } + + fn as_bytes(&self) -> &[u8] { (**self).as_bytes() } +} + +/// An input reader over characters. +#[derive(Clone, Copy, Debug)] +pub struct CharInput<'t>(&'t [u8]); + +impl<'t> CharInput<'t> { + /// Return a new character input reader for the given string. + pub fn new(s: &'t [u8]) -> CharInput<'t> { + CharInput(s) + } +} + +impl<'t> ops::Deref for CharInput<'t> { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + self.0 + } +} + +impl<'t> Input for CharInput<'t> { + fn at(&self, i: usize) -> InputAt { + let c = decode_utf8(&self[i..]).map(|(c, _)| c).into(); + InputAt { + pos: i, + c: c, + byte: None, + len: c.len_utf8(), + } + } + + fn next_char(&self, at: InputAt) -> Char { + at.char() + } + + fn previous_char(&self, at: InputAt) -> Char { + decode_last_utf8(&self[..at.pos()]).map(|(c, _)| c).into() + } + + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { + use prog::EmptyLook::*; + match empty.look { + StartLine => { + let c = self.previous_char(at); + at.pos() == 0 || c == '\n' + } + EndLine => { + let c = self.next_char(at); + at.pos() == self.len() || c == '\n' + } + StartText => at.pos() == 0, + EndText => at.pos() == self.len(), + WordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() != c2.is_word_char() + } + NotWordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() == c2.is_word_char() + } + WordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_byte() != c2.is_word_byte() + } + NotWordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_byte() == c2.is_word_byte() + } + } + } + + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option { + prefixes.find(&self[at.pos()..]).map(|(s, _)| self.at(at.pos() + s)) + } + + fn len(&self) -> usize { + self.0.len() + } + + fn as_bytes(&self) -> &[u8] { + self.0 + } +} + +/// An input reader over bytes. +#[derive(Clone, Copy, Debug)] +pub struct ByteInput<'t> { + text: &'t [u8], + only_utf8: bool, +} + +impl<'t> ByteInput<'t> { + /// Return a new byte-based input reader for the given string. + pub fn new(text: &'t [u8], only_utf8: bool) -> ByteInput<'t> { + ByteInput { + text: text, + only_utf8: only_utf8, + } + } +} + +impl<'t> ops::Deref for ByteInput<'t> { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + self.text + } +} + +impl<'t> Input for ByteInput<'t> { + fn at(&self, i: usize) -> InputAt { + InputAt { + pos: i, + c: None.into(), + byte: self.get(i).cloned(), + len: 1, + } + } + + fn next_char(&self, at: InputAt) -> Char { + decode_utf8(&self[at.pos()..]).map(|(c, _)| c).into() + } + + fn previous_char(&self, at: InputAt) -> Char { + decode_last_utf8(&self[..at.pos()]).map(|(c, _)| c).into() + } + + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { + use prog::EmptyLook::*; + match empty.look { + StartLine => { + let c = self.previous_char(at); + at.pos() == 0 || c == '\n' + } + EndLine => { + let c = self.next_char(at); + at.pos() == self.len() || c == '\n' + } + StartText => at.pos() == 0, + EndText => at.pos() == self.len(), + WordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() != c2.is_word_char() + } + NotWordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() == c2.is_word_char() + } + WordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + if self.only_utf8 { + // If we must match UTF-8, then we can't match word + // boundaries at invalid UTF-8. + if c1.is_none() && !at.is_start() { + return false; + } + if c2.is_none() && !at.is_end() { + return false; + } + } + c1.is_word_byte() != c2.is_word_byte() + } + NotWordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + if self.only_utf8 { + // If we must match UTF-8, then we can't match word + // boundaries at invalid UTF-8. + if c1.is_none() && !at.is_start() { + return false; + } + if c2.is_none() && !at.is_end() { + return false; + } + } + c1.is_word_byte() == c2.is_word_byte() + } + } + } + + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option { + prefixes.find(&self[at.pos()..]).map(|(s, _)| self.at(at.pos() + s)) + } + + fn len(&self) -> usize { + self.text.len() + } + + fn as_bytes(&self) -> &[u8] { + self.text + } +} + +/// An inline representation of `Option`. +/// +/// This eliminates the need to do case analysis on `Option` to determine +/// ordinality with other characters. +/// +/// (The `Option` is not related to encoding. Instead, it is used in the +/// matching engines to represent the beginning and ending boundaries of the +/// search text.) +#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] +pub struct Char(u32); + +impl fmt::Debug for Char { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match char::from_u32(self.0) { + None => write!(f, "Empty"), + Some(c) => write!(f, "{:?}", c), + } + } +} + +impl Char { + /// Returns true iff the character is absent. + #[inline] + pub fn is_none(self) -> bool { self.0 == u32::MAX } + + /// Returns the length of the character's UTF-8 encoding. + /// + /// If the character is absent, then `0` is returned. + #[inline] + pub fn len_utf8(self) -> usize { + char::from_u32(self.0).map_or(0, |c| c.len_utf8()) + } + + /// Returns true iff the character is a word character. + /// + /// If the character is absent, then false is returned. + pub fn is_word_char(self) -> bool { + char::from_u32(self.0).map_or(false, syntax::is_word_character) + } + + /// Returns true iff the byte is a word byte. + /// + /// If the byte is absent, then false is returned. + pub fn is_word_byte(self) -> bool { + match char::from_u32(self.0) { + Some(c) if c <= '\u{7F}' => syntax::is_word_byte(c as u8), + None | Some(_) => false, + } + } +} + +impl From for Char { + fn from(c: char) -> Char { Char(c as u32) } +} + +impl From> for Char { + fn from(c: Option) -> Char { + c.map_or(Char(u32::MAX), |c| c.into()) + } +} + +impl PartialEq for Char { + #[inline] + fn eq(&self, other: &char) -> bool { self.0 == *other as u32 } +} + +impl PartialEq for char { + #[inline] + fn eq(&self, other: &Char) -> bool { *self as u32 == other.0 } +} + +impl PartialOrd for Char { + #[inline] + fn partial_cmp(&self, other: &char) -> Option { + self.0.partial_cmp(&(*other as u32)) + } +} + +impl PartialOrd for char { + #[inline] + fn partial_cmp(&self, other: &Char) -> Option { + (*self as u32).partial_cmp(&other.0) + } +} diff --git a/bash-5.1/vendor/regex/src/lib.rs b/bash-5.1/vendor/regex/src/lib.rs new file mode 100644 index 0000000..f82eb9c --- /dev/null +++ b/bash-5.1/vendor/regex/src/lib.rs @@ -0,0 +1,672 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This crate provides a library for parsing, compiling, and executing regular +expressions. Its syntax is similar to Perl-style regular expressions, but lacks +a few features like look around and backreferences. In exchange, all searches +execute in linear time with respect to the size of the regular expression and +search text. + +This crate's documentation provides some simple examples, describes +[Unicode support](#unicode) and exhaustively lists the +[supported syntax](#syntax). + +For more specific details on the API for regular expressions, please see the +documentation for the [`Regex`](struct.Regex.html) type. + +# Usage + +This crate is [on crates.io](https://crates.io/crates/regex) and can be +used by adding `regex` to your dependencies in your project's `Cargo.toml`. + +```toml +[dependencies] +regex = "0.2" +``` + +and this to your crate root: + +```rust +extern crate regex; +``` + +# Example: find a date + +General use of regular expressions in this package involves compiling an +expression and then using it to search, split or replace text. For example, +to confirm that some text resembles a date: + +```rust +use regex::Regex; +let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); +assert!(re.is_match("2014-01-01")); +``` + +Notice the use of the `^` and `$` anchors. In this crate, every expression +is executed with an implicit `.*?` at the beginning and end, which allows +it to match anywhere in the text. Anchors can be used to ensure that the +full text matches an expression. + +This example also demonstrates the utility of +[raw strings](https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals) +in Rust, which +are just like regular strings except they are prefixed with an `r` and do +not process any escape sequences. For example, `"\\d"` is the same +expression as `r"\d"`. + +# Example: Avoid compiling the same regex in a loop + +It is an anti-pattern to compile the same regular expression in a loop +since compilation is typically expensive. (It takes anywhere from a few +microseconds to a few **milliseconds** depending on the size of the +regex.) Not only is compilation itself expensive, but this also prevents +optimizations that reuse allocations internally to the matching engines. + +In Rust, it can sometimes be a pain to pass regular expressions around if +they're used from inside a helper function. Instead, we recommend using the +[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that +regular expressions are compiled exactly once. + +For example: + +```rust +#[macro_use] extern crate lazy_static; +extern crate regex; + +use regex::Regex; + +fn some_helper_function(text: &str) -> bool { + lazy_static! { + static ref RE: Regex = Regex::new("...").unwrap(); + } + RE.is_match(text) +} + +fn main() {} +``` + +Specifically, in this example, the regex will be compiled when it is used for +the first time. On subsequent uses, it will reuse the previous compilation. + +# Example: iterating over capture groups + +This crate provides convenient iterators for matching an expression +repeatedly against a search string to find successive non-overlapping +matches. For example, to find all dates in a string and be able to access +them by their component pieces: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); +let text = "2012-03-14, 2013-01-01 and 2014-07-05"; +for cap in re.captures_iter(text) { + println!("Month: {} Day: {} Year: {}", &cap[2], &cap[3], &cap[1]); +} +// Output: +// Month: 03 Day: 14 Year: 2012 +// Month: 01 Day: 01 Year: 2013 +// Month: 07 Day: 05 Year: 2014 +# } +``` + +Notice that the year is in the capture group indexed at `1`. This is +because the *entire match* is stored in the capture group at index `0`. + +# Example: replacement with named capture groups + +Building on the previous example, perhaps we'd like to rearrange the date +formats. This can be done with text replacement. But to make the code +clearer, we can *name* our capture groups and use those names as variables +in our replacement text: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?P\d{4})-(?P\d{2})-(?P\d{2})").unwrap(); +let before = "2012-03-14, 2013-01-01 and 2014-07-05"; +let after = re.replace_all(before, "$m/$d/$y"); +assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); +# } +``` + +The `replace` methods are actually polymorphic in the replacement, which +provides more flexibility than is seen here. (See the documentation for +`Regex::replace` for more details.) + +Note that if your regex gets complicated, you can use the `x` flag to +enable insigificant whitespace mode, which also lets you write comments: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?x) + (?P\d{4}) # the year + - + (?P\d{2}) # the month + - + (?P\d{2}) # the day +").unwrap(); +let before = "2012-03-14, 2013-01-01 and 2014-07-05"; +let after = re.replace_all(before, "$m/$d/$y"); +assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); +# } +``` + +If you wish to match against whitespace in this mode, you can still use `\s`, +`\n`, `\t`, etc. For escaping a single space character, you can use its hex +character code `\x20` or temporarily disable the `x` flag, e.g., `(?-x: )`. + +# Example: match multiple regular expressions simultaneously + +This demonstrates how to use a `RegexSet` to match multiple (possibly +overlapping) regular expressions in a single scan of the search text: + +```rust +use regex::RegexSet; + +let set = RegexSet::new(&[ + r"\w+", + r"\d+", + r"\pL+", + r"foo", + r"bar", + r"barfoo", + r"foobar", +]).unwrap(); + +// Iterate over and collect all of the matches. +let matches: Vec<_> = set.matches("foobar").into_iter().collect(); +assert_eq!(matches, vec![0, 2, 3, 4, 6]); + +// You can also test whether a particular regex matched: +let matches = set.matches("foobar"); +assert!(!matches.matched(5)); +assert!(matches.matched(6)); +``` + +# Pay for what you use + +With respect to searching text with a regular expression, there are three +questions that can be asked: + +1. Does the text match this expression? +2. If so, where does it match? +3. Where did the capturing groups match? + +Generally speaking, this crate could provide a function to answer only #3, +which would subsume #1 and #2 automatically. However, it can be significantly +more expensive to compute the location of capturing group matches, so it's best +not to do it if you don't need to. + +Therefore, only use what you need. For example, don't use `find` if you +only need to test if an expression matches a string. (Use `is_match` +instead.) + +# Unicode + +This implementation executes regular expressions **only** on valid UTF-8 +while exposing match locations as byte indices into the search string. + +Only simple case folding is supported. Namely, when matching +case-insensitively, the characters are first mapped using the "simple" case +folding rules defined by Unicode. + +Regular expressions themselves are **only** interpreted as a sequence of +Unicode scalar values. This means you can use Unicode characters directly +in your expression: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?i)Δ+").unwrap(); +let mat = re.find("ΔδΔ").unwrap(); +assert_eq!((mat.start(), mat.end()), (0, 6)); +# } +``` + +Most features of the regular expressions in this crate are Unicode aware. Here +are some examples: + +* `.` will match any valid UTF-8 encoded Unicode scalar value except for `\n`. + (To also match `\n`, enable the `s` flag, e.g., `(?s:.)`.) +* `\w`, `\d` and `\s` are Unicode aware. For example, `\s` will match all forms + of whitespace categorized by Unicode. +* `\b` matches a Unicode word boundary. +* Negated character classes like `[^a]` match all Unicode scalar values except + for `a`. +* `^` and `$` are **not** Unicode aware in multi-line mode. Namely, they only + recognize `\n` and not any of the other forms of line terminators defined + by Unicode. + +Unicode general categories, scripts, script extensions, ages and a smattering +of boolean properties are available as character classes. For example, you can +match a sequence of numerals, Greek or Cherokee letters: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap(); +let mat = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap(); +assert_eq!((mat.start(), mat.end()), (3, 23)); +# } +``` + +For a more detailed breakdown of Unicode support with respect to +[UTS#18](http://unicode.org/reports/tr18/), +please see the +[UNICODE](https://github.com/rust-lang/regex/blob/master/UNICODE.md) +document in the root of the regex repository. + +# Opt out of Unicode support + +The `bytes` sub-module provides a `Regex` type that can be used to match +on `&[u8]`. By default, text is interpreted as UTF-8 just like it is with +the main `Regex` type. However, this behavior can be disabled by turning +off the `u` flag, even if doing so could result in matching invalid UTF-8. +For example, when the `u` flag is disabled, `.` will match any byte instead +of any Unicode scalar value. + +Disabling the `u` flag is also possible with the standard `&str`-based `Regex` +type, but it is only allowed where the UTF-8 invariant is maintained. For +example, `(?-u:\w)` is an ASCII-only `\w` character class and is legal in an +`&str`-based `Regex`, but `(?-u:\xFF)` will attempt to match the raw byte +`\xFF`, which is invalid UTF-8 and therefore is illegal in `&str`-based +regexes. + +# Syntax + +The syntax supported in this crate is documented below. + +Note that the regular expression parser and abstract syntax are exposed in +a separate crate, [`regex-syntax`](../regex_syntax/index.html). + +## Matching one character + +

+.             any character except new line (includes new line with s flag)
+\d            digit (\p{Nd})
+\D            not digit
+\pN           One-letter name Unicode character class
+\p{Greek}     Unicode character class (general category or script)
+\PN           Negated one-letter name Unicode character class
+\P{Greek}     negated Unicode character class (general category or script)
+
+ +### Character classes + +
+[xyz]         A character class matching either x, y or z (union).
+[^xyz]        A character class matching any character except x, y and z.
+[a-z]         A character class matching any character in range a-z.
+[[:alpha:]]   ASCII character class ([A-Za-z])
+[[:^alpha:]]  Negated ASCII character class ([^A-Za-z])
+[x[^xyz]]     Nested/grouping character class (matching any character except y and z)
+[a-y&&xyz]    Intersection (matching x or y)
+[0-9&&[^4]]   Subtraction using intersection and negation (matching 0-9 except 4)
+[0-9--4]      Direct subtraction (matching 0-9 except 4)
+[a-g~~b-h]    Symmetric difference (matching `a` and `h` only)
+[\[\]]        Escaping in character classes (matching [ or ])
+
+ +Any named character class may appear inside a bracketed `[...]` character +class. For example, `[\p{Greek}[:digit:]]` matches any Greek or ASCII +digit. `[\p{Greek}&&\pL]` matches Greek letters. + +Precedence in character classes, from most binding to least: + +1. Ranges: `a-cd` == `[a-c]d` +2. Union: `ab&&bc` == `[ab]&&[bc]` +3. Intersection: `^a-z&&b` == `^[a-z&&b]` +4. Negation + +## Composites + +
+xy    concatenation (x followed by y)
+x|y   alternation (x or y, prefer x)
+
+ +## Repetitions + +
+x*        zero or more of x (greedy)
+x+        one or more of x (greedy)
+x?        zero or one of x (greedy)
+x*?       zero or more of x (ungreedy/lazy)
+x+?       one or more of x (ungreedy/lazy)
+x??       zero or one of x (ungreedy/lazy)
+x{n,m}    at least n x and at most m x (greedy)
+x{n,}     at least n x (greedy)
+x{n}      exactly n x
+x{n,m}?   at least n x and at most m x (ungreedy/lazy)
+x{n,}?    at least n x (ungreedy/lazy)
+x{n}?     exactly n x
+
+ +## Empty matches + +
+^     the beginning of text (or start-of-line with multi-line mode)
+$     the end of text (or end-of-line with multi-line mode)
+\A    only the beginning of text (even with multi-line mode enabled)
+\z    only the end of text (even with multi-line mode enabled)
+\b    a Unicode word boundary (\w on one side and \W, \A, or \z on other)
+\B    not a Unicode word boundary
+
+ +## Grouping and flags + +
+(exp)          numbered capture group (indexed by opening parenthesis)
+(?P<name>exp)  named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
+(?:exp)        non-capturing group
+(?flags)       set flags within current group
+(?flags:exp)   set flags for exp (non-capturing)
+
+ +Flags are each a single character. For example, `(?x)` sets the flag `x` +and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at +the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets +the `x` flag and clears the `y` flag. + +All flags are by default disabled unless stated otherwise. They are: + +
+i     case-insensitive: letters match both upper and lower case
+m     multi-line mode: ^ and $ match begin/end of line
+s     allow . to match \n
+U     swap the meaning of x* and x*?
+u     Unicode support (enabled by default)
+x     ignore whitespace and allow line comments (starting with `#`)
+
+ +Flags can be toggled within a pattern. Here's an example that matches +case-insensitively for the first part but case-sensitively for the second part: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?i)a+(?-i)b+").unwrap(); +let cap = re.captures("AaAaAbbBBBb").unwrap(); +assert_eq!(&cap[0], "AaAaAbb"); +# } +``` + +Notice that the `a+` matches either `a` or `A`, but the `b+` only matches +`b`. + +Multi-line mode means `^` and `$` no longer match just at the beginning/end of +the input, but at the beginning/end of lines: + +``` +# use regex::Regex; +let re = Regex::new(r"(?m)^line \d+").unwrap(); +let m = re.find("line one\nline 2\n").unwrap(); +assert_eq!(m.as_str(), "line 2"); +``` + +Note that `^` matches after new lines, even at the end of input: + +``` +# use regex::Regex; +let re = Regex::new(r"(?m)^").unwrap(); +let m = re.find_iter("test\n").last().unwrap(); +assert_eq!((m.start(), m.end()), (5, 5)); +``` + +Here is an example that uses an ASCII word boundary instead of a Unicode +word boundary: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap(); +let cap = re.captures("$$abc$$").unwrap(); +assert_eq!(&cap[0], "abc"); +# } +``` + +## Escape sequences + +
+\*          literal *, works for any punctuation character: \.+*?()|[]{}^$
+\a          bell (\x07)
+\f          form feed (\x0C)
+\t          horizontal tab
+\n          new line
+\r          carriage return
+\v          vertical tab (\x0B)
+\123        octal character code (up to three digits)
+\x7F        hex character code (exactly two digits)
+\x{10FFFF}  any hex character code corresponding to a Unicode code point
+\u007F      hex character code (exactly four digits)
+\u{7F}      any hex character code corresponding to a Unicode code point
+\U0000007F  hex character code (exactly eight digits)
+\U{7F}      any hex character code corresponding to a Unicode code point
+
+ +## Perl character classes (Unicode friendly) + +These classes are based on the definitions provided in +[UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties): + +
+\d     digit (\p{Nd})
+\D     not digit
+\s     whitespace (\p{White_Space})
+\S     not whitespace
+\w     word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
+\W     not word character
+
+ +## ASCII character classes + +
+[[:alnum:]]    alphanumeric ([0-9A-Za-z])
+[[:alpha:]]    alphabetic ([A-Za-z])
+[[:ascii:]]    ASCII ([\x00-\x7F])
+[[:blank:]]    blank ([\t ])
+[[:cntrl:]]    control ([\x00-\x1F\x7F])
+[[:digit:]]    digits ([0-9])
+[[:graph:]]    graphical ([!-~])
+[[:lower:]]    lower case ([a-z])
+[[:print:]]    printable ([ -~])
+[[:punct:]]    punctuation ([!-/:-@\[-`{-~])
+[[:space:]]    whitespace ([\t\n\v\f\r ])
+[[:upper:]]    upper case ([A-Z])
+[[:word:]]     word characters ([0-9A-Za-z_])
+[[:xdigit:]]   hex digit ([0-9A-Fa-f])
+
+ +# Untrusted input + +This crate can handle both untrusted regular expressions and untrusted +search text. + +Untrusted regular expressions are handled by capping the size of a compiled +regular expression. +(See [`RegexBuilder::size_limit`](struct.RegexBuilder.html#method.size_limit).) +Without this, it would be trivial for an attacker to exhaust your system's +memory with expressions like `a{100}{100}{100}`. + +Untrusted search text is allowed because the matching engine(s) in this +crate have time complexity `O(mn)` (with `m ~ regex` and `n ~ search +text`), which means there's no way to cause exponential blow-up like with +some other regular expression engines. (We pay for this by disallowing +features like arbitrary look-ahead and backreferences.) + +When a DFA is used, pathological cases with exponential state blow up are +avoided by constructing the DFA lazily or in an "online" manner. Therefore, +at most one new state can be created for each byte of input. This satisfies +our time complexity guarantees, but can lead to unbounded memory growth +proportional to the size of the input. As a stopgap, the DFA is only +allowed to store a fixed number of states. When the limit is reached, its +states are wiped and continues on, possibly duplicating previous work. If +the limit is reached too frequently, it gives up and hands control off to +another matching engine with fixed memory requirements. +(The DFA size limit can also be tweaked. See +[`RegexBuilder::dfa_size_limit`](struct.RegexBuilder.html#method.dfa_size_limit).) +*/ + +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate aho_corasick; +extern crate memchr; +extern crate thread_local; +#[cfg(test)] +#[macro_use] +extern crate quickcheck; +extern crate regex_syntax as syntax; +extern crate utf8_ranges; + +pub use error::Error; +pub use re_builder::unicode::*; +pub use re_builder::set_unicode::*; +pub use re_set::unicode::*; +pub use re_trait::Locations; +pub use re_unicode::{ + Regex, Match, Captures, + CaptureNames, Matches, CaptureMatches, SubCaptureMatches, + Replacer, ReplacerRef, NoExpand, Split, SplitN, + escape, +}; + +/** +Match regular expressions on arbitrary bytes. + +This module provides a nearly identical API to the one found in the +top-level of this crate. There are two important differences: + +1. Matching is done on `&[u8]` instead of `&str`. Additionally, `Vec` +is used where `String` would have been used. +2. Unicode support can be disabled even when disabling it would result in +matching invalid UTF-8 bytes. + +# Example: match null terminated string + +This shows how to find all null-terminated strings in a slice of bytes: + +```rust +# use regex::bytes::Regex; +let re = Regex::new(r"(?-u)(?P[^\x00]+)\x00").unwrap(); +let text = b"foo\x00bar\x00baz\x00"; + +// Extract all of the strings without the null terminator from each match. +// The unwrap is OK here since a match requires the `cstr` capture to match. +let cstrs: Vec<&[u8]> = + re.captures_iter(text) + .map(|c| c.name("cstr").unwrap().as_bytes()) + .collect(); +assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs); +``` + +# Example: selectively enable Unicode support + +This shows how to match an arbitrary byte pattern followed by a UTF-8 encoded +string (e.g., to extract a title from a Matroska file): + +```rust +# use std::str; +# use regex::bytes::Regex; +let re = Regex::new( + r"(?-u)\x7b\xa9(?:[\x80-\xfe]|[\x40-\xff].)(?u:(.*))" +).unwrap(); +let text = b"\x12\xd0\x3b\x5f\x7b\xa9\x85\xe2\x98\x83\x80\x98\x54\x76\x68\x65"; +let caps = re.captures(text).unwrap(); + +// Notice that despite the `.*` at the end, it will only match valid UTF-8 +// because Unicode mode was enabled with the `u` flag. Without the `u` flag, +// the `.*` would match the rest of the bytes. +let mat = caps.get(1).unwrap(); +assert_eq!((7, 10), (mat.start(), mat.end())); + +// If there was a match, Unicode mode guarantees that `title` is valid UTF-8. +let title = str::from_utf8(&caps[1]).unwrap(); +assert_eq!("☃", title); +``` + +In general, if the Unicode flag is enabled in a capture group and that capture +is part of the overall match, then the capture is *guaranteed* to be valid +UTF-8. + +# Syntax + +The supported syntax is pretty much the same as the syntax for Unicode +regular expressions with a few changes that make sense for matching arbitrary +bytes: + +1. The `u` flag can be disabled even when disabling it might cause the regex to +match invalid UTF-8. When the `u` flag is disabled, the regex is said to be in +"ASCII compatible" mode. +2. In ASCII compatible mode, neither Unicode scalar values nor Unicode +character classes are allowed. +3. In ASCII compatible mode, Perl character classes (`\w`, `\d` and `\s`) +revert to their typical ASCII definition. `\w` maps to `[[:word:]]`, `\d` maps +to `[[:digit:]]` and `\s` maps to `[[:space:]]`. +4. In ASCII compatible mode, word boundaries use the ASCII compatible `\w` to +determine whether a byte is a word byte or not. +5. Hexadecimal notation can be used to specify arbitrary bytes instead of +Unicode codepoints. For example, in ASCII compatible mode, `\xFF` matches the +literal byte `\xFF`, while in Unicode mode, `\xFF` is a Unicode codepoint that +matches its UTF-8 encoding of `\xC3\xBF`. Similarly for octal notation. +6. `.` matches any *byte* except for `\n` instead of any Unicode scalar value. +When the `s` flag is enabled, `.` matches any byte. + +# Performance + +In general, one should expect performance on `&[u8]` to be roughly similar to +performance on `&str`. +*/ +pub mod bytes { + pub use re_builder::bytes::*; + pub use re_builder::set_bytes::*; + pub use re_bytes::*; + pub use re_set::bytes::*; + pub use re_trait::Locations; +} + +mod backtrack; +mod utf8; +mod compile; +mod dfa; +mod error; +mod exec; +mod expand; +mod freqs; +mod input; +mod literal; +#[cfg(feature = "pattern")] +mod pattern; +mod pikevm; +mod prog; +mod re_builder; +mod re_bytes; +mod re_set; +mod re_trait; +mod re_unicode; +mod sparse; +#[cfg(feature = "unstable")] +mod vector; + +/// The `internal` module exists to support suspicious activity, such as +/// testing different matching engines and supporting the `regex-debug` CLI +/// utility. +#[doc(hidden)] +pub mod internal { + pub use compile::Compiler; + pub use exec::{Exec, ExecBuilder}; + pub use input::{Char, Input, CharInput, InputAt}; + pub use literal::LiteralSearcher; + pub use prog::{Program, Inst, EmptyLook, InstRanges}; +} diff --git a/bash-5.1/vendor/regex/src/literal/mod.rs b/bash-5.1/vendor/regex/src/literal/mod.rs new file mode 100644 index 0000000..de1bd53 --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/mod.rs @@ -0,0 +1,1141 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::mem; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use memchr::{memchr, memchr2, memchr3}; +use syntax::hir::literal::{Literal, Literals}; + +use freqs::BYTE_FREQUENCIES; +use self::teddy_avx2::{Teddy as TeddyAVX2}; +use self::teddy_ssse3::{Teddy as TeddySSSE3}; + +mod teddy_avx2; +mod teddy_ssse3; + +/// A prefix extracted from a compiled regular expression. +/// +/// A regex prefix is a set of literal strings that *must* be matched at the +/// beginning of a regex in order for the entire regex to match. Similarly +/// for a regex suffix. +#[derive(Clone, Debug)] +pub struct LiteralSearcher { + complete: bool, + lcp: FreqyPacked, + lcs: FreqyPacked, + matcher: Matcher, +} + +#[derive(Clone, Debug)] +enum Matcher { + /// No literals. (Never advances through the input.) + Empty, + /// A set of four or more single byte literals. + Bytes(SingleByteSet), + /// A single substring, find using memchr and frequency analysis. + FreqyPacked(FreqyPacked), + /// A single substring, find using Boyer-Moore. + BoyerMoore(BoyerMooreSearch), + /// An Aho-Corasick automaton. + AC(FullAcAutomaton), + /// A simd accelerated multiple string matcher. Used only for a small + /// number of small literals. + TeddySSSE3(TeddySSSE3), + /// A simd accelerated multiple string matcher. Used only for a small + /// number of small literals. This uses 256-bit vectors. + TeddyAVX2(TeddyAVX2), +} + +impl LiteralSearcher { + /// Returns a matcher that never matches and never advances the input. + pub fn empty() -> Self { + Self::new(Literals::empty(), Matcher::Empty) + } + + /// Returns a matcher for literal prefixes from the given set. + pub fn prefixes(lits: Literals) -> Self { + let matcher = Matcher::prefixes(&lits); + Self::new(lits, matcher) + } + + /// Returns a matcher for literal suffixes from the given set. + pub fn suffixes(lits: Literals) -> Self { + let matcher = Matcher::suffixes(&lits); + Self::new(lits, matcher) + } + + fn new(lits: Literals, matcher: Matcher) -> Self { + let complete = lits.all_complete(); + LiteralSearcher { + complete: complete, + lcp: FreqyPacked::new(lits.longest_common_prefix().to_vec()), + lcs: FreqyPacked::new(lits.longest_common_suffix().to_vec()), + matcher: matcher, + } + } + + /// Returns true if all matches comprise the entire regular expression. + /// + /// This does not necessarily mean that a literal match implies a match + /// of the regular expression. For example, the regular expresison `^a` + /// is comprised of a single complete literal `a`, but the regular + /// expression demands that it only match at the beginning of a string. + pub fn complete(&self) -> bool { + self.complete && !self.is_empty() + } + + /// Find the position of a literal in `haystack` if it exists. + #[inline(always)] // reduces constant overhead + pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { + use self::Matcher::*; + match self.matcher { + Empty => Some((0, 0)), + Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), + FreqyPacked(ref s) => s.find(haystack).map(|i| (i, i + s.len())), + BoyerMoore(ref s) => s.find(haystack).map(|i| (i, i + s.len())), + AC(ref aut) => aut.find(haystack).next().map(|m| (m.start, m.end)), + TeddySSSE3(ref t) => t.find(haystack).map(|m| (m.start, m.end)), + TeddyAVX2(ref t) => t.find(haystack).map(|m| (m.start, m.end)), + } + } + + /// Like find, except matches must start at index `0`. + pub fn find_start(&self, haystack: &[u8]) -> Option<(usize, usize)> { + for lit in self.iter() { + if lit.len() > haystack.len() { + continue; + } + if lit == &haystack[0..lit.len()] { + return Some((0, lit.len())); + } + } + None + } + + /// Like find, except matches must end at index `haystack.len()`. + pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { + for lit in self.iter() { + if lit.len() > haystack.len() { + continue; + } + if lit == &haystack[haystack.len() - lit.len()..] { + return Some((haystack.len() - lit.len(), haystack.len())); + } + } + None + } + + /// Returns an iterator over all literals to be matched. + pub fn iter(&self) -> LiteralIter { + match self.matcher { + Matcher::Empty => LiteralIter::Empty, + Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), + Matcher::FreqyPacked(ref s) => LiteralIter::Single(&s.pat), + Matcher::BoyerMoore(ref s) => LiteralIter::Single(&s.pattern), + Matcher::AC(ref ac) => LiteralIter::AC(ac.patterns()), + Matcher::TeddySSSE3(ref ted) => { + LiteralIter::TeddySSSE3(ted.patterns()) + } + Matcher::TeddyAVX2(ref ted) => { + LiteralIter::TeddyAVX2(ted.patterns()) + } + } + } + + /// Returns a matcher for the longest common prefix of this matcher. + pub fn lcp(&self) -> &FreqyPacked { + &self.lcp + } + + /// Returns a matcher for the longest common suffix of this matcher. + pub fn lcs(&self) -> &FreqyPacked { + &self.lcs + } + + /// Returns true iff this prefix is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the number of prefixes in this machine. + pub fn len(&self) -> usize { + use self::Matcher::*; + match self.matcher { + Empty => 0, + Bytes(ref sset) => sset.dense.len(), + FreqyPacked(_) => 1, + BoyerMoore(_) => 1, + AC(ref aut) => aut.len(), + TeddySSSE3(ref ted) => ted.len(), + TeddyAVX2(ref ted) => ted.len(), + } + } + + /// Return the approximate heap usage of literals in bytes. + pub fn approximate_size(&self) -> usize { + use self::Matcher::*; + match self.matcher { + Empty => 0, + Bytes(ref sset) => sset.approximate_size(), + FreqyPacked(ref single) => single.approximate_size(), + BoyerMoore(ref single) => single.approximate_size(), + AC(ref aut) => aut.heap_bytes(), + TeddySSSE3(ref ted) => ted.approximate_size(), + TeddyAVX2(ref ted) => ted.approximate_size(), + } + } +} + +impl Matcher { + fn prefixes(lits: &Literals) -> Self { + let sset = SingleByteSet::prefixes(lits); + Matcher::new(lits, sset) + } + + fn suffixes(lits: &Literals) -> Self { + let sset = SingleByteSet::suffixes(lits); + Matcher::new(lits, sset) + } + + fn new(lits: &Literals, sset: SingleByteSet) -> Self { + if lits.literals().is_empty() { + return Matcher::Empty; + } + if sset.dense.len() >= 26 { + // Avoid trying to match a large number of single bytes. + // This is *very* sensitive to a frequency analysis comparison + // between the bytes in sset and the composition of the haystack. + // No matter the size of sset, if its members all are rare in the + // haystack, then it'd be worth using it. How to tune this... IDK. + // ---AG + return Matcher::Empty; + } + if sset.complete { + return Matcher::Bytes(sset); + } + if lits.literals().len() == 1 { + let lit = lits.literals()[0].to_vec(); + if BoyerMooreSearch::should_use(lit.as_slice()) { + return Matcher::BoyerMoore(BoyerMooreSearch::new(lit)); + } else { + return Matcher::FreqyPacked(FreqyPacked::new(lit)); + } + } + let is_aho_corasick_fast = sset.dense.len() == 1 && sset.all_ascii; + if TeddyAVX2::available() && !is_aho_corasick_fast { + const MAX_TEDDY_LITERALS: usize = 32; + if lits.literals().len() <= MAX_TEDDY_LITERALS { + if let Some(ted) = TeddyAVX2::new(lits) { + return Matcher::TeddyAVX2(ted); + } + } + } + if TeddySSSE3::available() && !is_aho_corasick_fast { + // Only try Teddy if Aho-Corasick can't use memchr on an ASCII + // byte. Also, in its current form, Teddy doesn't scale well to + // lots of literals. + // + // We impose the ASCII restriction since an alternation of + // non-ASCII string literals in the same language is likely to all + // start with the same byte. Even worse, the corpus being searched + // probably has a similar composition, which ends up completely + // negating the benefit of memchr. + const MAX_TEDDY_LITERALS: usize = 32; + if lits.literals().len() <= MAX_TEDDY_LITERALS { + if let Some(ted) = TeddySSSE3::new(lits) { + return Matcher::TeddySSSE3(ted); + } + } + // Fallthrough to ol' reliable Aho-Corasick... + } + let pats = lits.literals().to_owned(); + Matcher::AC(AcAutomaton::new(pats).into_full()) + } +} + +pub enum LiteralIter<'a> { + Empty, + Bytes(&'a [u8]), + Single(&'a [u8]), + AC(&'a [Literal]), + TeddySSSE3(&'a [Vec]), + TeddyAVX2(&'a [Vec]), +} + +impl<'a> Iterator for LiteralIter<'a> { + type Item = &'a [u8]; + + fn next(&mut self) -> Option { + match *self { + LiteralIter::Empty => None, + LiteralIter::Bytes(ref mut many) => { + if many.is_empty() { + None + } else { + let next = &many[0..1]; + *many = &many[1..]; + Some(next) + } + } + LiteralIter::Single(ref mut one) => { + if one.is_empty() { + None + } else { + let next = &one[..]; + *one = &[]; + Some(next) + } + } + LiteralIter::AC(ref mut lits) => { + if lits.is_empty() { + None + } else { + let next = &lits[0]; + *lits = &lits[1..]; + Some(&**next) + } + } + LiteralIter::TeddySSSE3(ref mut lits) => { + if lits.is_empty() { + None + } else { + let next = &lits[0]; + *lits = &lits[1..]; + Some(&**next) + } + } + LiteralIter::TeddyAVX2(ref mut lits) => { + if lits.is_empty() { + None + } else { + let next = &lits[0]; + *lits = &lits[1..]; + Some(&**next) + } + } + } + } +} + +#[derive(Clone, Debug)] +struct SingleByteSet { + sparse: Vec, + dense: Vec, + complete: bool, + all_ascii: bool, +} + +impl SingleByteSet { + fn new() -> SingleByteSet { + SingleByteSet { + sparse: vec![false; 256], + dense: vec![], + complete: true, + all_ascii: true, + } + } + + fn prefixes(lits: &Literals) -> SingleByteSet { + let mut sset = SingleByteSet::new(); + for lit in lits.literals() { + sset.complete = sset.complete && lit.len() == 1; + if let Some(&b) = lit.get(0) { + if !sset.sparse[b as usize] { + if b > 0x7F { + sset.all_ascii = false; + } + sset.dense.push(b); + sset.sparse[b as usize] = true; + } + } + } + sset + } + + fn suffixes(lits: &Literals) -> SingleByteSet { + let mut sset = SingleByteSet::new(); + for lit in lits.literals() { + sset.complete = sset.complete && lit.len() == 1; + if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { + if !sset.sparse[b as usize] { + if b > 0x7F { + sset.all_ascii = false; + } + sset.dense.push(b); + sset.sparse[b as usize] = true; + } + } + } + sset + } + + /// Faster find that special cases certain sizes to use memchr. + #[inline(always)] // reduces constant overhead + fn find(&self, text: &[u8]) -> Option { + match self.dense.len() { + 0 => None, + 1 => memchr(self.dense[0], text), + 2 => memchr2(self.dense[0], self.dense[1], text), + 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), + _ => self._find(text), + } + } + + /// Generic find that works on any sized set. + fn _find(&self, haystack: &[u8]) -> Option { + for (i, &b) in haystack.iter().enumerate() { + if self.sparse[b as usize] { + return Some(i); + } + } + None + } + + fn approximate_size(&self) -> usize { + (self.dense.len() * mem::size_of::()) + + (self.sparse.len() * mem::size_of::()) + } +} + +/// Provides an implementation of fast subtring search using frequency +/// analysis. +/// +/// memchr is so fast that we do everything we can to keep the loop in memchr +/// for as long as possible. The easiest way to do this is to intelligently +/// pick the byte to send to memchr. The best byte is the byte that occurs +/// least frequently in the haystack. Since doing frequency analysis on the +/// haystack is far too expensive, we compute a set of fixed frequencies up +/// front and hard code them in src/freqs.rs. Frequency analysis is done via +/// scripts/frequencies.py. +#[derive(Clone, Debug)] +pub struct FreqyPacked { + /// The pattern. + pat: Vec, + /// The number of Unicode characters in the pattern. This is useful for + /// determining the effective length of a pattern when deciding which + /// optimizations to perform. A trailing incomplete UTF-8 sequence counts + /// as one character. + char_len: usize, + /// The rarest byte in the pattern, according to pre-computed frequency + /// analysis. + rare1: u8, + /// The offset of the rarest byte in `pat`. + rare1i: usize, + /// The second rarest byte in the pattern, according to pre-computed + /// frequency analysis. (This may be equivalent to the rarest byte.) + /// + /// The second rarest byte is used as a type of guard for quickly detecting + /// a mismatch after memchr locates an instance of the rarest byte. This + /// is a hedge against pathological cases where the pre-computed frequency + /// analysis may be off. (But of course, does not prevent *all* + /// pathological cases.) + rare2: u8, + /// The offset of the second rarest byte in `pat`. + rare2i: usize, +} + +impl FreqyPacked { + fn new(pat: Vec) -> FreqyPacked { + if pat.is_empty() { + return FreqyPacked::empty(); + } + + // Find the rarest two bytes. Try to make them distinct (but it's not + // required). + let mut rare1 = pat[0]; + let mut rare2 = pat[0]; + for b in pat[1..].iter().cloned() { + if freq_rank(b) < freq_rank(rare1) { + rare1 = b; + } + } + for &b in &pat { + if rare1 == rare2 { + rare2 = b + } else if b != rare1 && freq_rank(b) < freq_rank(rare2) { + rare2 = b; + } + } + + // And find the offsets of their last occurrences. + let rare1i = pat.iter().rposition(|&b| b == rare1).unwrap(); + let rare2i = pat.iter().rposition(|&b| b == rare2).unwrap(); + + let char_len = char_len_lossy(&pat); + FreqyPacked { + pat: pat, + char_len: char_len, + rare1: rare1, + rare1i: rare1i, + rare2: rare2, + rare2i: rare2i, + } + } + + fn empty() -> FreqyPacked { + FreqyPacked { + pat: vec![], + char_len: 0, + rare1: 0, + rare1i: 0, + rare2: 0, + rare2i: 0, + } + } + + #[inline(always)] // reduces constant overhead + pub fn find(&self, haystack: &[u8]) -> Option { + let pat = &*self.pat; + if haystack.len() < pat.len() || pat.is_empty() { + return None; + } + let mut i = self.rare1i; + while i < haystack.len() { + i += match memchr(self.rare1, &haystack[i..]) { + None => return None, + Some(i) => i, + }; + let start = i - self.rare1i; + let end = start + pat.len(); + if end > haystack.len() { + return None; + } + let aligned = &haystack[start..end]; + if aligned[self.rare2i] == self.rare2 && aligned == &*self.pat { + return Some(start); + } + i += 1; + } + None + } + + #[inline(always)] // reduces constant overhead + pub fn is_suffix(&self, text: &[u8]) -> bool { + if text.len() < self.len() { + return false; + } + text[text.len() - self.len()..] == *self.pat + } + + pub fn len(&self) -> usize { + self.pat.len() + } + + pub fn char_len(&self) -> usize { + self.char_len + } + + fn approximate_size(&self) -> usize { + self.pat.len() * mem::size_of::() + } +} + +fn char_len_lossy(bytes: &[u8]) -> usize { + String::from_utf8_lossy(bytes).chars().count() +} + +/// An implementation of Tuned Boyer-Moore as laid out by +/// Andrew Hume and Daniel Sunday in "Fast String Searching". +/// O(n) in the size of the input. +/// +/// Fast string searching algorithms come in many variations, +/// but they can generally be described in terms of three main +/// components. +/// +/// The skip loop is where the string searcher wants to spend +/// as much time as possible. Exactly which character in the +/// pattern the skip loop examines varies from algorithm to +/// algorithm, but in the simplest case this loop repeated +/// looks at the last character in the pattern and jumps +/// forward in the input if it is not in the pattern. +/// Robert Boyer and J Moore called this the "fast" loop in +/// their original paper. +/// +/// The match loop is responsible for actually examining the +/// whole potentially matching substring. In order to fail +/// faster, the match loop sometimes has a guard test attached. +/// The guard test uses frequency analysis of the different +/// characters in the pattern to choose the least frequency +/// occurring character and use it to find match failures +/// as quickly as possible. +/// +/// The shift rule governs how the algorithm will shuffle its +/// test window in the event of a failure during the match loop. +/// Certain shift rules allow the worst-case run time of the +/// algorithm to be shown to be O(n) in the size of the input +/// rather than O(nm) in the size of the input and the size +/// of the pattern (as naive Boyer-Moore is). +/// +/// "Fast String Searching", in addition to presenting a tuned +/// algorithm, provides a comprehensive taxonomy of the many +/// different flavors of string searchers. Under that taxonomy +/// TBM, the algorithm implemented here, uses an unrolled fast +/// skip loop with memchr fallback, a forward match loop with guard, +/// and the mini Sunday's delta shift rule. To unpack that you'll have to +/// read the paper. +#[derive(Clone, Debug)] +pub struct BoyerMooreSearch { + /// The pattern we are going to look for in the haystack. + pattern: Vec, + + /// The skip table for the skip loop. + /// + /// Maps the character at the end of the input + /// to a shift. + skip_table: Vec, + + /// The guard character (least frequently occurring char). + guard: u8, + /// The reverse-index of the guard character in the pattern. + guard_reverse_idx: usize, + + /// Daniel Sunday's mini generalized delta2 shift table. + /// + /// We use a skip loop, so we only have to provide a shift + /// for the skip char (last char). This is why it is a mini + /// shift rule. + md2_shift: usize, +} + +impl BoyerMooreSearch { + /// Create a new string searcher, performing whatever + /// compilation steps are required. + fn new(pattern: Vec) -> Self { + debug_assert!(pattern.len() > 0); + + let (g, gi) = Self::select_guard(pattern.as_slice()); + let skip_table = Self::compile_skip_table(pattern.as_slice()); + let md2_shift = Self::compile_md2_shift(pattern.as_slice()); + BoyerMooreSearch { + pattern: pattern, + skip_table: skip_table, + guard: g, + guard_reverse_idx: gi, + md2_shift: md2_shift, + } + } + + /// Find the pattern in `haystack`, returning the offset + /// of the start of the first occurrence of the pattern + /// in `haystack`. + #[inline] + fn find(&self, haystack: &[u8]) -> Option { + if haystack.len() < self.pattern.len() { + return None; + } + + let mut window_end = self.pattern.len() - 1; + + // Inspired by the grep source. It is a way + // to do correct loop unrolling without having to place + // a crashpad of terminating charicters at the end in + // the way described in the Fast String Searching paper. + const NUM_UNROLL: usize = 10; + // 1 for the initial position, and 1 for the md2 shift + let short_circut = (NUM_UNROLL + 2) * self.pattern.len(); + + if haystack.len() > short_circut { + // just 1 for the md2 shift + let backstop = haystack.len() - ((NUM_UNROLL + 1) * self.pattern.len()); + loop { + window_end = match self.skip_loop(haystack, window_end, backstop) { + Some(i) => i, + None => return None, + }; + if window_end >= backstop { + break; + } + + if self.check_match(haystack, window_end) { + return Some(window_end - (self.pattern.len() - 1)); + } else { + let skip = self.skip_table[haystack[window_end] as usize]; + window_end += + if skip == 0 { self.md2_shift } else { skip }; + continue; + } + } + } + + // now process the input after the backstop + while window_end < haystack.len() { + let mut skip = self.skip_table[haystack[window_end] as usize]; + if skip == 0 { + if self.check_match(haystack, window_end) { + return Some(window_end - (self.pattern.len() - 1)); + } else { + skip = self.md2_shift; + } + } + window_end += skip; + } + + None + } + + fn len(&self) -> usize { + return self.pattern.len() + } + + /// The key heuristic behind which the BoyerMooreSearch lives. + /// + /// See `rust-lang/regex/issues/408`. + /// + /// Tuned Boyer-Moore is actually pretty slow! It turns out a handrolled + /// platform-specific memchr routine with a bit of frequency + /// analysis sprinkled on top actually wins most of the time. + /// However, there are a few cases where Tuned Boyer-Moore still + /// wins. + /// + /// If the haystack is random, frequency analysis doesn't help us, + /// so Boyer-Moore will win for sufficiently large needles. + /// Unfortunately, there is no obvious way to determine this + /// ahead of time. + /// + /// If the pattern itself consists of very common characters, + /// frequency analysis won't get us anywhere. The most extreme + /// example of this is a pattern like `eeeeeeeeeeeeeeee`. Fortunately, + /// this case is wholly determined by the pattern, so we can actually + /// implement the heuristic. + /// + /// A third case is if the pattern is sufficiently long. The idea + /// here is that once the pattern gets long enough the Tuned + /// Boyer-Moore skip loop will start making strides long enough + /// to beat the asm deep magic that is memchr. + fn should_use(pattern: &[u8]) -> bool { + // The minimum pattern length required to use TBM. + const MIN_LEN: usize = 9; + // The minimum frequency rank (lower is rarer) that every byte in the + // pattern must have in order to use TBM. That is, if the pattern + // contains _any_ byte with a lower rank, then TBM won't be used. + const MIN_CUTOFF: usize = 150; + // The maximum frequency rank for any byte. + const MAX_CUTOFF: usize = 255; + // The scaling factor used to determine the actual cutoff frequency + // to use (keeping in mind that the minimum frequency rank is bounded + // by MIN_CUTOFF). This scaling factor is an attempt to make TBM more + // likely to be used as the pattern grows longer. That is, longer + // patterns permit somewhat less frequent bytes than shorter patterns, + // under the assumption that TBM gets better as the pattern gets + // longer. + const LEN_CUTOFF_PROPORTION: usize = 4; + + let scaled_rank = pattern.len().wrapping_mul(LEN_CUTOFF_PROPORTION); + let cutoff = cmp::max( + MIN_CUTOFF, + MAX_CUTOFF - cmp::min(MAX_CUTOFF, scaled_rank), + ); + // The pattern must be long enough to be worthwhile. e.g., memchr will + // be faster on `e` because it is short even though e is quite common. + pattern.len() > MIN_LEN + // all the bytes must be more common than the cutoff. + && pattern.iter().all(|c| freq_rank(*c) >= cutoff) + } + + /// Check to see if there is a match at the given position + #[inline] + fn check_match(&self, haystack: &[u8], window_end: usize) -> bool { + // guard test + if haystack[window_end - self.guard_reverse_idx] != self.guard { + return false; + } + + // match loop + let window_start = window_end - (self.pattern.len() - 1); + for i in 0..self.pattern.len() { + if self.pattern[i] != haystack[window_start + i] { + return false; + } + } + + true + } + + /// Skip forward according to the shift table. + /// + /// Returns the offset of the next occurrence + /// of the last char in the pattern, or the none + /// if it never reappears. If `skip_loop` hits the backstop + /// it will leave early. + #[inline] + fn skip_loop(&self, + haystack: &[u8], + mut window_end: usize, + backstop: usize, + ) -> Option { + use std::mem; + + let window_end_snapshot = window_end; + let skip_of = |we: usize| -> usize { + // Unsafe might make this faster, but the benchmarks + // were hard to interpret. + self.skip_table[haystack[we] as usize] + }; + + loop { + let mut skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + if skip != 0 { + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + if skip != 0 { + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + if skip != 0 { + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + + // If ten iterations did not make at least 16 words + // worth of progress, we just fall back on memchr. + if window_end - window_end_snapshot > + 16 * mem::size_of::() { + + // Returning a window_end >= backstop will immediatly + // break us out of the inner loop in `find`. + if window_end >= backstop { + return Some(window_end); + } + + continue; // we made enough progress + } else { + // In case we are already there, and so that + // we will catch the guard char. + window_end = window_end + .checked_sub(1 + self.guard_reverse_idx) + .unwrap_or(0); + + match memchr(self.guard, &haystack[window_end..]) { + None => return None, + Some(g_idx) => { + return Some(window_end + g_idx + self.guard_reverse_idx); + } + } + } + } + } + } + + return Some(window_end); + } + } + + /// Compute the ufast skip table. + fn compile_skip_table(pattern: &[u8]) -> Vec { + let mut tab = vec![pattern.len(); 256]; + + // For every char in the pattern, we write a skip + // that will line us up with the rightmost occurrence. + // + // N.B. the sentinel (0) is written by the last + // loop iteration. + for (i, c) in pattern.iter().enumerate() { + tab[*c as usize] = (pattern.len() - 1) - i; + } + + tab + } + + /// Select the guard character based off of the precomputed + /// frequency table. + fn select_guard(pattern: &[u8]) -> (u8, usize) { + let mut rarest = pattern[0]; + let mut rarest_rev_idx = pattern.len() - 1; + for (i, c) in pattern.iter().enumerate() { + if freq_rank(*c) < freq_rank(rarest) { + rarest = *c; + rarest_rev_idx = (pattern.len() - 1) - i; + } + } + + (rarest, rarest_rev_idx) + } + + /// If there is another occurrence of the skip + /// char, shift to it, otherwise just shift to + /// the next window. + fn compile_md2_shift(pattern: &[u8]) -> usize { + let shiftc = *pattern.last().unwrap(); + + // For a pattern of length 1 we will never apply the + // shift rule, so we use a poison value on the principle + // that failing fast is a good thing. + if pattern.len() == 1 { + return 0xDEADBEAF; + } + + let mut i = pattern.len() - 2; + while i > 0 { + if pattern[i] == shiftc { + return (pattern.len() - 1) - i; + } + i -= 1; + } + + // The skip char never re-occurs in the pattern, so + // we can just shift the whole window length. + pattern.len() - 1 + } + + fn approximate_size(&self) -> usize { + (self.pattern.len() * mem::size_of::()) + + (256 * mem::size_of::()) // skip table + } +} + +fn freq_rank(b: u8) -> usize { + BYTE_FREQUENCIES[b as usize] as usize +} + +#[cfg(test)] +mod tests { + use super::{BoyerMooreSearch, FreqyPacked}; + + // + // Unit Tests + // + + // The "hello, world" of string searching + #[test] + fn bm_find_subs() { + let searcher = BoyerMooreSearch::new(Vec::from(&b"pattern"[..])); + let haystack = b"I keep seeing patterns in this text"; + assert_eq!(14, searcher.find(haystack).unwrap()); + } + + #[test] + fn bm_find_no_subs() { + let searcher = BoyerMooreSearch::new(Vec::from(&b"pattern"[..])); + let haystack = b"I keep seeing needles in this text"; + assert_eq!(None, searcher.find(haystack)); + } + + // + // Regression Tests + // + + #[test] + fn bm_skip_reset_bug() { + let haystack = vec![0, 0, 0, 0, 0, 1, 1, 0]; + let needle = vec![0, 1, 1, 0]; + + let searcher = BoyerMooreSearch::new(needle); + let offset = searcher.find(haystack.as_slice()).unwrap(); + assert_eq!(4, offset); + } + + #[test] + fn bm_backstop_underflow_bug() { + let haystack = vec![0, 0]; + let needle = vec![0, 0]; + + let searcher = BoyerMooreSearch::new(needle); + let offset = searcher.find(haystack.as_slice()).unwrap(); + assert_eq!(0, offset); + } + + #[test] + fn bm_naive_off_by_one_bug() { + let haystack = vec![91]; + let needle = vec![91]; + + let naive_offset = naive_find(&needle, &haystack).unwrap(); + assert_eq!(0, naive_offset); + } + + #[test] + fn bm_memchr_fallback_indexing_bug() { + let mut haystack = vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let needle = vec![1, 1, 1, 1, 32, 32, 87]; + let needle_start = haystack.len(); + haystack.extend(needle.clone()); + + let searcher = BoyerMooreSearch::new(needle); + assert_eq!(needle_start, searcher.find(haystack.as_slice()).unwrap()); + } + + #[test] + fn bm_backstop_boundary() { + let haystack = b"\ +// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +e_data.clone_created(entity_id, entity_to_add.entity_id); +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +".to_vec(); + let needle = b"clone_created".to_vec(); + + let searcher = BoyerMooreSearch::new(needle); + let result = searcher.find(&haystack); + assert_eq!(Some(43), result); + } + + #[test] + fn bm_win_gnu_indexing_bug() { + let haystack_raw = vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let needle = vec![1, 1, 1, 1, 1, 1, 1]; + let haystack = haystack_raw.as_slice(); + + BoyerMooreSearch::new(needle.clone()).find(haystack); + } + + // + // QuickCheck Properties + // + + use quickcheck::TestResult; + + fn naive_find(needle: &[u8], haystack: &[u8]) -> Option { + assert!(needle.len() <= haystack.len()); + + for i in 0..(haystack.len() - (needle.len() - 1)) { + if haystack[i] == needle[0] + && &haystack[i..(i+needle.len())] == needle { + return Some(i) + } + } + + None + } + + quickcheck! { + fn qc_bm_equals_nieve_find(pile1: Vec, pile2: Vec) -> TestResult { + if pile1.len() == 0 || pile2.len() == 0 { + return TestResult::discard(); + } + + let (needle, haystack) = if pile1.len() < pile2.len() { + (pile1, pile2.as_slice()) + } else { + (pile2, pile1.as_slice()) + }; + + let searcher = BoyerMooreSearch::new(needle.clone()); + TestResult::from_bool( + searcher.find(haystack) == naive_find(&needle, haystack)) + } + + fn qc_bm_equals_single(pile1: Vec, pile2: Vec) -> TestResult { + if pile1.len() == 0 || pile2.len() == 0 { + return TestResult::discard(); + } + + let (needle, haystack) = if pile1.len() < pile2.len() { + (pile1, pile2.as_slice()) + } else { + (pile2, pile1.as_slice()) + }; + + let bm_searcher = BoyerMooreSearch::new(needle.clone()); + let freqy_memchr = FreqyPacked::new(needle); + TestResult::from_bool( + bm_searcher.find(haystack) == freqy_memchr.find(haystack)) + } + + fn qc_bm_finds_trailing_needle( + haystack_pre: Vec, + needle: Vec + ) -> TestResult { + if needle.len() == 0 { + return TestResult::discard(); + } + + let mut haystack = haystack_pre.clone(); + let searcher = BoyerMooreSearch::new(needle.clone()); + + if haystack.len() >= needle.len() && + searcher.find(haystack.as_slice()).is_some() { + return TestResult::discard(); + } + + haystack.extend(needle.clone()); + + // What if the the tail of the haystack can start the + // needle? + let start = haystack_pre.len() + .checked_sub(needle.len()) + .unwrap_or(0); + for i in 0..(needle.len() - 1) { + if searcher.find(&haystack[(i + start)..]).is_some() { + return TestResult::discard(); + } + } + + TestResult::from_bool( + searcher.find(haystack.as_slice()) + .map(|x| x == haystack_pre.len()) + .unwrap_or(false)) + } + + // qc_equals_* is only testing the negative case as @burntsushi + // pointed out in https://github.com/rust-lang/regex/issues/446. + // This quickcheck prop represents an effort to force testing of + // the positive case. qc_bm_finds_first and qc_bm_finds_trailing_needle + // already check some of the positive cases, but they don't cover + // cases where the needle is in the middle of haystack. This prop + // fills that hole. + fn qc_bm_finds_subslice( + haystack: Vec, + needle_start: usize, + needle_length: usize + ) -> TestResult { + if haystack.len() == 0 { + return TestResult::discard(); + } + + let needle_start = needle_start % haystack.len(); + let needle_length = needle_length % (haystack.len() - needle_start); + + if needle_length == 0 { + return TestResult::discard(); + } + + let needle = &haystack[needle_start..(needle_start + needle_length)]; + + let bm_searcher = BoyerMooreSearch::new(needle.to_vec()); + + let start = naive_find(&needle, &haystack); + match start { + None => TestResult::from_bool(false), + Some(nf_start) => + TestResult::from_bool( + nf_start <= needle_start + && bm_searcher.find(&haystack) == start + ) + } + } + + fn qc_bm_finds_first(needle: Vec) -> TestResult { + if needle.len() == 0 { + return TestResult::discard(); + } + + let mut haystack = needle.clone(); + let searcher = BoyerMooreSearch::new(needle.clone()); + haystack.extend(needle); + + TestResult::from_bool( + searcher.find(haystack.as_slice()) + .map(|x| x == 0) + .unwrap_or(false)) + } + } +} diff --git a/bash-5.1/vendor/regex/src/literal/teddy_avx2/fallback.rs b/bash-5.1/vendor/regex/src/literal/teddy_avx2/fallback.rs new file mode 100644 index 0000000..20524aa --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/teddy_avx2/fallback.rs @@ -0,0 +1,20 @@ +use syntax::hir::literal::Literals; + +#[derive(Debug, Clone)] +pub struct Teddy(()); + +#[derive(Debug, Clone)] +pub struct Match { + pub pat: usize, + pub start: usize, + pub end: usize, +} + +impl Teddy { + pub fn available() -> bool { false } + pub fn new(_pats: &Literals) -> Option { None } + pub fn patterns(&self) -> &[Vec] { &[] } + pub fn len(&self) -> usize { 0 } + pub fn approximate_size(&self) -> usize { 0 } + pub fn find(&self, _haystack: &[u8]) -> Option { None } +} diff --git a/bash-5.1/vendor/regex/src/literal/teddy_avx2/imp.rs b/bash-5.1/vendor/regex/src/literal/teddy_avx2/imp.rs new file mode 100644 index 0000000..62015d0 --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/teddy_avx2/imp.rs @@ -0,0 +1,468 @@ +/*! +This is the Teddy searcher, but ported to AVX2. + +See the module comments in the SSSE3 Teddy searcher for a more in depth +explanation of how this algorithm works. For the most part, this port is +basically the same as the SSSE3 version, but using 256-bit vectors instead of +128-bit vectors, which increases throughput. +*/ + +use std::cmp; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use syntax::hir::literal::Literals; + +use vector::avx2::{AVX2VectorBuilder, u8x32}; + +/// Corresponds to the number of bytes read at a time in the haystack. +const BLOCK_SIZE: usize = 32; + +/// Match reports match information. +#[derive(Debug, Clone)] +pub struct Match { + /// The index of the pattern that matched. The index is in correspondence + /// with the order of the patterns given at construction. + pub pat: usize, + /// The start byte offset of the match. + pub start: usize, + /// The end byte offset of the match. This is always `start + pat.len()`. + pub end: usize, +} + +/// A SIMD accelerated multi substring searcher. +#[derive(Debug, Clone)] +pub struct Teddy { + /// A builder for AVX2 empowered vectors. + vb: AVX2VectorBuilder, + /// A list of substrings to match. + pats: Vec>, + /// An Aho-Corasick automaton of the patterns. We use this when we need to + /// search pieces smaller than the Teddy block size. + ac: FullAcAutomaton>, + /// A set of 8 buckets. Each bucket corresponds to a single member of a + /// bitset. A bucket contains zero or more substrings. This is useful + /// when the number of substrings exceeds 8, since our bitsets cannot have + /// more than 8 members. + buckets: Vec>, + /// Our set of masks. There's one mask for each byte in the fingerprint. + masks: Masks, +} + +impl Teddy { + /// Returns true if and only if Teddy is supported on this platform. + /// + /// If this returns `false`, then `Teddy::new(...)` is guaranteed to + /// return `None`. + pub fn available() -> bool { + AVX2VectorBuilder::new().is_some() + } + + /// Create a new `Teddy` multi substring matcher. + /// + /// If a `Teddy` matcher could not be created (e.g., `pats` is empty or has + /// an empty substring), then `None` is returned. + pub fn new(pats: &Literals) -> Option { + let vb = match AVX2VectorBuilder::new() { + None => return None, + Some(vb) => vb, + }; + if !Teddy::available() { + return None; + } + + let pats: Vec<_> = pats.literals().iter().map(|p|p.to_vec()).collect(); + let min_len = pats.iter().map(|p| p.len()).min().unwrap_or(0); + // Don't allow any empty patterns and require that we have at + // least one pattern. + if min_len < 1 { + return None; + } + // Pick the largest mask possible, but no larger than 3. + let nmasks = cmp::min(3, min_len); + let mut masks = Masks::new(vb, nmasks); + let mut buckets = vec![vec![]; 8]; + // Assign a substring to each bucket, and add the bucket's bitfield to + // the appropriate position in the mask. + for (pati, pat) in pats.iter().enumerate() { + let bucket = pati % 8; + buckets[bucket].push(pati); + masks.add(bucket as u8, pat); + } + Some(Teddy { + vb: vb, + pats: pats.to_vec(), + ac: AcAutomaton::new(pats.to_vec()).into_full(), + buckets: buckets, + masks: masks, + }) + } + + /// Returns all of the substrings matched by this `Teddy`. + pub fn patterns(&self) -> &[Vec] { + &self.pats + } + + /// Returns the number of substrings in this matcher. + pub fn len(&self) -> usize { + self.pats.len() + } + + /// Returns the approximate size on the heap used by this matcher. + pub fn approximate_size(&self) -> usize { + self.pats.iter().fold(0, |a, b| a + b.len()) + } + + /// Searches `haystack` for the substrings in this `Teddy`. If a match was + /// found, then it is returned. Otherwise, `None` is returned. + pub fn find(&self, haystack: &[u8]) -> Option { + // This is safe because the only way we can construct a Teddy type + // is if AVX2 is available. + unsafe { self.find_impl(haystack) } + } + + #[allow(unused_attributes)] + #[target_feature(enable = "avx2")] + unsafe fn find_impl(&self, haystack: &[u8]) -> Option { + // If our haystack is smaller than the block size, then fall back to + // a naive brute force search. + if haystack.is_empty() || haystack.len() < (BLOCK_SIZE + 2) { + return self.slow(haystack, 0); + } + match self.masks.len() { + 0 => None, + 1 => self.find1(haystack), + 2 => self.find2(haystack), + 3 => self.find3(haystack), + _ => unreachable!(), + } + } + + /// `find1` is used when there is only 1 mask. This is the easy case and is + /// pretty much as described in the module documentation. + #[inline(always)] + fn find1(&self, haystack: &[u8]) -> Option { + let mut pos = 0; + let zero = self.vb.u8x32_splat(0); + let len = haystack.len(); + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-32. + let p = haystack.get_unchecked(pos..); + self.vb.u8x32_load_unchecked_unaligned(p) + }; + // N.B. `res0` is our `C` in the module documentation. + let res0 = self.masks.members1(h); + // Only do expensive verification if there are any non-zero bits. + let bitfield = res0.ne(zero).movemask(); + if bitfield != 0 { + if let Some(m) = self.verify(haystack, pos, res0, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + self.slow(haystack, pos) + } + + /// `find2` is used when there are 2 masks, e.g., the fingerprint is 2 bytes + /// long. + #[inline(always)] + fn find2(&self, haystack: &[u8]) -> Option { + // This is an exotic way to right shift a SIMD vector across lanes. + // See below at use for more details. + let zero = self.vb.u8x32_splat(0); + let len = haystack.len(); + // The previous value of `C` (from the module documentation) for the + // *first* byte in the fingerprint. On subsequent iterations, we take + // the last bitset from the previous `C` and insert it into the first + // position of the current `C`, shifting all other bitsets to the right + // one lane. This causes `C` for the first byte to line up with `C` for + // the second byte, so that they can be `AND`'d together. + let mut prev0 = self.vb.u8x32_splat(0xFF); + let mut pos = 1; + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-32. + let p = haystack.get_unchecked(pos..); + self.vb.u8x32_load_unchecked_unaligned(p) + }; + let (res0, res1) = self.masks.members2(h); + + // Do this: + // + // (prev0 << 15) | (res0 >> 1) + // + // This lets us line up our C values for each byte. + let res0prev0 = res0.alignr_15(prev0); + + // `AND`'s our `C` values together. + let res = res0prev0.and(res1); + prev0 = res0; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(1).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last byte in the last + // window, so start the slow search at the last byte of the last + // window. + self.slow(haystack, pos.checked_sub(1).unwrap()) + } + + /// `find3` is used when there are 3 masks, e.g., the fingerprint is 3 bytes + /// long. + /// + /// N.B. This is a straight-forward extrapolation of `find2`. The only + /// difference is that we need to keep track of two previous values of `C`, + /// since we now need to align for three bytes. + #[inline(always)] + fn find3(&self, haystack: &[u8]) -> Option { + let zero = self.vb.u8x32_splat(0); + let len = haystack.len(); + let mut prev0 = self.vb.u8x32_splat(0xFF); + let mut prev1 = self.vb.u8x32_splat(0xFF); + let mut pos = 2; + + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-32. + let p = haystack.get_unchecked(pos..); + self.vb.u8x32_load_unchecked_unaligned(p) + }; + let (res0, res1, res2) = self.masks.members3(h); + + let res0prev0 = res0.alignr_14(prev0); + let res1prev1 = res1.alignr_15(prev1); + let res = res0prev0.and(res1prev1).and(res2); + + prev0 = res0; + prev1 = res1; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(2).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last two bytes in the last + // window, so start the slow search at the penultimate byte of the + // last window. + // self.slow(haystack, pos.saturating_sub(2)) + self.slow(haystack, pos.checked_sub(2).unwrap()) + } + + /// Runs the verification procedure on `res` (i.e., `C` from the module + /// documentation), where the haystack block starts at `pos` in + /// `haystack`. `bitfield` has ones in the bit positions that `res` has + /// non-zero bytes. + /// + /// If a match exists, it returns the first one. + #[inline(always)] + fn verify( + &self, + haystack: &[u8], + pos: usize, + res: u8x32, + mut bitfield: u32, + ) -> Option { + while bitfield != 0 { + // The next offset, relative to pos, where some fingerprint + // matched. + let byte_pos = bitfield.trailing_zeros() as usize; + bitfield &= !(1 << byte_pos); + + // Offset relative to the beginning of the haystack. + let start = pos + byte_pos; + + // The bitfield telling us which patterns had fingerprints that + // match at this starting position. + let mut patterns = res.extract(byte_pos); + while patterns != 0 { + let bucket = patterns.trailing_zeros() as usize; + patterns &= !(1 << bucket); + + // Actual substring search verification. + if let Some(m) = self.verify_bucket(haystack, bucket, start) { + return Some(m); + } + } + } + + None + } + + /// Verifies whether any substring in the given bucket matches in haystack + /// at the given starting position. + #[inline(always)] + fn verify_bucket( + &self, + haystack: &[u8], + bucket: usize, + start: usize, + ) -> Option { + // This cycles through the patterns in the bucket in the order that + // the patterns were given. Therefore, we guarantee leftmost-first + // semantics. + for &pati in &self.buckets[bucket] { + let pat = &*self.pats[pati]; + if start + pat.len() > haystack.len() { + continue; + } + if pat == &haystack[start..start + pat.len()] { + return Some(Match { + pat: pati, + start: start, + end: start + pat.len(), + }); + } + } + None + } + + /// Slow substring search through all patterns in this matcher. + /// + /// This is used when we don't have enough bytes in the haystack for our + /// block based approach. + #[inline(never)] + fn slow(&self, haystack: &[u8], pos: usize) -> Option { + self.ac.find(&haystack[pos..]).next().map(|m| { + Match { + pat: m.pati, + start: pos + m.start, + end: pos + m.end, + } + }) + } +} + +/// A list of masks. This has length equal to the length of the fingerprint. +/// The length of the fingerprint is always `min(3, len(smallest_substring))`. +#[derive(Debug, Clone)] +struct Masks { + vb: AVX2VectorBuilder, + masks: [Mask; 3], + size: usize, +} + +impl Masks { + /// Create a new set of masks of size `n`, where `n` corresponds to the + /// number of bytes in a fingerprint. + fn new(vb: AVX2VectorBuilder, n: usize) -> Masks { + Masks { + vb: vb, + masks: [Mask::new(vb), Mask::new(vb), Mask::new(vb)], + size: n, + } + } + + /// Returns the number of masks. + fn len(&self) -> usize { + self.size + } + + /// Adds the given pattern to the given bucket. The bucket should be a + /// power of `2 <= 2^7`. + fn add(&mut self, bucket: u8, pat: &[u8]) { + for i in 0..self.len() { + self.masks[i].add(bucket, pat[i]); + } + } + + /// Finds the fingerprints that are in the given haystack block. i.e., this + /// returns `C` as described in the module documentation. + /// + /// More specifically, `for i in 0..16` and `j in 0..8, C[i][j] == 1` if and + /// only if `haystack_block[i]` corresponds to a fingerprint that is part + /// of a pattern in bucket `j`. + #[inline(always)] + fn members1(&self, haystack_block: u8x32) -> u8x32 { + let masklo = self.vb.u8x32_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)) + } + + /// Like members1, but computes C for the first and second bytes in the + /// fingerprint. + #[inline(always)] + fn members2(&self, haystack_block: u8x32) -> (u8x32, u8x32) { + let masklo = self.vb.u8x32_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + (res0, res1) + } + + /// Like `members1`, but computes `C` for the first, second and third bytes + /// in the fingerprint. + #[inline(always)] + fn members3(&self, haystack_block: u8x32) -> (u8x32, u8x32, u8x32) { + let masklo = self.vb.u8x32_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + let res2 = + self.masks[2].lo.shuffle(hlo).and(self.masks[2].hi.shuffle(hhi)); + (res0, res1, res2) + } +} + +/// A single mask. +#[derive(Debug, Clone, Copy)] +struct Mask { + /// Bitsets for the low nybbles in a fingerprint. + lo: u8x32, + /// Bitsets for the high nybbles in a fingerprint. + hi: u8x32, +} + +impl Mask { + /// Create a new mask with no members. + fn new(vb: AVX2VectorBuilder) -> Mask { + Mask { + lo: vb.u8x32_splat(0), + hi: vb.u8x32_splat(0), + } + } + + /// Adds the given byte to the given bucket. + fn add(&mut self, bucket: u8, byte: u8) { + // Split our byte into two nybbles, and add each nybble to our + // mask. + let byte_lo = (byte & 0xF) as usize; + let byte_hi = (byte >> 4) as usize; + + let lo = self.lo.extract(byte_lo) | ((1 << bucket) as u8); + self.lo.replace(byte_lo, lo); + self.lo.replace(byte_lo + 16, lo); + + let hi = self.hi.extract(byte_hi) | ((1 << bucket) as u8); + self.hi.replace(byte_hi, hi); + self.hi.replace(byte_hi + 16, hi); + } +} diff --git a/bash-5.1/vendor/regex/src/literal/teddy_avx2/mod.rs b/bash-5.1/vendor/regex/src/literal/teddy_avx2/mod.rs new file mode 100644 index 0000000..78b6e20 --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/teddy_avx2/mod.rs @@ -0,0 +1,16 @@ +pub use self::imp::*; + +#[cfg(all( + feature = "unstable", + regex_runtime_teddy_avx2, + any(target_arch = "x86_64"), +))] +mod imp; + +#[cfg(not(all( + feature = "unstable", + regex_runtime_teddy_avx2, + any(target_arch = "x86_64"), +)))] +#[path = "fallback.rs"] +mod imp; diff --git a/bash-5.1/vendor/regex/src/literal/teddy_ssse3/fallback.rs b/bash-5.1/vendor/regex/src/literal/teddy_ssse3/fallback.rs new file mode 100644 index 0000000..20524aa --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/teddy_ssse3/fallback.rs @@ -0,0 +1,20 @@ +use syntax::hir::literal::Literals; + +#[derive(Debug, Clone)] +pub struct Teddy(()); + +#[derive(Debug, Clone)] +pub struct Match { + pub pat: usize, + pub start: usize, + pub end: usize, +} + +impl Teddy { + pub fn available() -> bool { false } + pub fn new(_pats: &Literals) -> Option { None } + pub fn patterns(&self) -> &[Vec] { &[] } + pub fn len(&self) -> usize { 0 } + pub fn approximate_size(&self) -> usize { 0 } + pub fn find(&self, _haystack: &[u8]) -> Option { None } +} diff --git a/bash-5.1/vendor/regex/src/literal/teddy_ssse3/imp.rs b/bash-5.1/vendor/regex/src/literal/teddy_ssse3/imp.rs new file mode 100644 index 0000000..85422b6 --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/teddy_ssse3/imp.rs @@ -0,0 +1,776 @@ +/*! +Teddy is a simd accelerated multiple substring matching algorithm. The name +and the core ideas in the algorithm were learned from the [Hyperscan][1_u] +project. + + +Background +---------- + +The key idea of Teddy is to do *packed* substring matching. In the literature, +packed substring matching is the idea of examing multiple bytes in a haystack +at a time to detect matches. Implementations of, for example, memchr (which +detects matches of a single byte) have been doing this for years. Only +recently, with the introduction of various SIMD instructions, has this been +extended to substring matching. The PCMPESTRI instruction (and its relatives), +for example, implements substring matching in hardware. It is, however, limited +to substrings of length 16 bytes or fewer, but this restriction is fine in a +regex engine, since we rarely care about the performance difference between +searching for a 16 byte literal and a 16 + N literal; 16 is already long +enough. The key downside of the PCMPESTRI instruction, on current (2016) CPUs +at least, is its latency and throughput. As a result, it is often faster to do +substring search with a Boyer-Moore variant and a well placed memchr to quickly +skip through the haystack. + +There are fewer results from the literature on packed substring matching, +and even fewer for packed multiple substring matching. Ben-Kiki et al. [2] +describes use of PCMPESTRI for substring matching, but is mostly theoretical +and hand-waves performance. There is other theoretical work done by Bille [3] +as well. + +The rest of the work in the field, as far as I'm aware, is by Faro and Kulekci +and is generally focused on multiple pattern search. Their first paper [4a] +introduces the concept of a fingerprint, which is computed for every block of +N bytes in every pattern. The haystack is then scanned N bytes at a time and +a fingerprint is computed in the same way it was computed for blocks in the +patterns. If the fingerprint corresponds to one that was found in a pattern, +then a verification step follows to confirm that one of the substrings with the +corresponding fingerprint actually matches at the current location. Various +implementation tricks are employed to make sure the fingerprint lookup is fast; +typically by truncating the fingerprint. (This may, of course, provoke more +steps in the verification process, so a balance must be struck.) + +The main downside of [4a] is that the minimum substring length is 32 bytes, +presumably because of how the algorithm uses certain SIMD instructions. This +essentially makes it useless for general purpose regex matching, where a small +number of short patterns is far more likely. + +Faro and Kulekci published another paper [4b] that is conceptually very similar +to [4a]. The key difference is that it uses the CRC32 instruction (introduced +as part of SSE 4.2) to compute fingerprint values. This also enables the +algorithm to work effectively on substrings as short as 7 bytes with 4 byte +windows. 7 bytes is unfortunately still too long. The window could be +technically shrunk to 2 bytes, thereby reducing minimum length to 3, but the +small window size ends up negating most performance benefits—and it's likely +the common case in a general purpose regex engine. + +Faro and Kulekci also published [4c] that appears to be intended as a +replacement to using PCMPESTRI. In particular, it is specifically motivated by +the high throughput/latency time of PCMPESTRI and therefore chooses other SIMD +instructions that are faster. While this approach works for short substrings, +I personally couldn't see a way to generalize it to multiple substring search. + +Faro and Kulekci have another paper [4d] that I haven't been able to read +because it is behind a paywall. + + +Teddy +----- + +Finally, we get to Teddy. If the above literature review is complete, then it +appears that Teddy is a novel algorithm. More than that, in my experience, it +completely blows away the competition for short substrings, which is exactly +what we want in a general purpose regex engine. Again, the algorithm appears +to be developed by the authors of [Hyperscan][1_u]. Hyperscan was open sourced +late 2015, and no earlier history could be found. Therefore, tracking the exact +provenance of the algorithm with respect to the published literature seems +difficult. + +DISCLAIMER: My understanding of Teddy is limited to reading auto-generated C +code, its disassembly and observing its runtime behavior. + +At a high level, Teddy works somewhat similarly to the fingerprint algorithms +published by Faro and Kulekci, but Teddy does it in a way that scales a bit +better. Namely: + +1. Teddy's core algorithm scans the haystack in 16 byte chunks. 16 is + significant because it corresponds to the number of bytes in a SIMD vector. + If one used AVX2 instructions, then we could scan the haystack in 32 byte + chunks. Similarly, if one used AVX512 instructions, we could scan the + haystack in 64 byte chunks. Hyperscan implements SSE + AVX2, we only + implement SSE for the moment. +2. Bitwise operations are performed on each chunk to discover if any region of + it matches a set of precomputed fingerprints from the patterns. If there are + matches, then a verification step is performed. In this implementation, our + verification step is naive. This can be improved upon. + +The details to make this work are quite clever. First, we must choose how to +pick our fingerprints. In Hyperscan's implementation, I *believe* they use the +last N bytes of each substring, where N must be at least the minimum length of +any substring in the set being searched. In this implementation, we use the +first N bytes of each substring. (The tradeoffs between these choices aren't +yet clear to me.) We then must figure out how to quickly test whether an +occurrence of any fingerprint from the set of patterns appears in a 16 byte +block from the haystack. To keep things simple, let's assume N = 1 and examine +some examples to motivate the approach. Here are our patterns: + +```ignore +foo +bar +baz +``` + +The corresponding fingerprints, for N = 1, are `f`, `b` and `b`. Now let's set +our 16 byte block to: + +```ignore +bat cat foo bump +xxxxxxxxxxxxxxxx +``` + +To cut to the chase, Teddy works by using bitsets. In particular, Teddy creates +a mask that allows us to quickly compute membership of a fingerprint in a 16 +byte block that also tells which pattern the fingerprint corresponds to. In +this case, our fingerprint is a single byte, so an appropriate abstraction is +a map from a single byte to a list of patterns that contain that fingerprint: + +```ignore +f |--> foo +b |--> bar, baz +``` + +Now, all we need to do is figure out how to represent this map in vector space +and use normal SIMD operations to perform a lookup. The first simplification +we can make is to represent our patterns as bit fields occupying a single +byte. This is important, because a single SIMD vector can store 16 bytes. + +```ignore +f |--> 00000001 +b |--> 00000010, 00000100 +``` + +How do we perform lookup though? It turns out that SSSE3 introduced a very cool +instruction called PSHUFB. The instruction takes two SIMD vectors, `A` and `B`, +and returns a third vector `C`. All vectors are treated as 16 8-bit integers. +`C` is formed by `C[i] = A[B[i]]`. (This is a bit of a simplification, but true +for the purposes of this algorithm. For full details, see [Intel's Intrinsics +Guide][5_u].) This essentially lets us use the values in `B` to lookup values +in `A`. + +If we could somehow cause `B` to contain our 16 byte block from the haystack, +and if `A` could contain our bitmasks, then we'd end up with something like +this for `A`: + +```ignore + 0x00 0x01 ... 0x62 ... 0x66 ... 0xFF +A = 0 0 00000110 00000001 0 +``` + +And if `B` contains our window from our haystack, we could use shuffle to take +the values from `B` and use them to look up our bitsets in `A`. But of course, +we can't do this because `A` in the above example contains 256 bytes, which +is much larger than the size of a SIMD vector. + +Nybbles to the rescue! A nybble is 4 bits. Instead of one mask to hold all of +our bitsets, we can use two masks, where one mask corresponds to the lower four +bits of our fingerprint and the other mask corresponds to the upper four bits. +So our map now looks like: + +```ignore +'f' & 0xF = 0x6 |--> 00000001 +'f' >> 4 = 0x6 |--> 00000111 +'b' & 0xF = 0x2 |--> 00000110 +'b' >> 4 = 0x6 |--> 00000111 +``` + +Notice that the bitsets for each nybble correspond to the union of all +fingerprints that contain that nybble. For example, both `f` and `b` have the +same upper 4 bits but differ on the lower 4 bits. Putting this together, we +have `A0`, `A1` and `B`, where `A0` is our mask for the lower nybble, `A1` is +our mask for the upper nybble and `B` is our 16 byte block from the haystack: + +```ignore + 0x00 0x01 0x02 0x03 ... 0x06 ... 0xF +A0 = 0 0 00000110 0 00000001 0 +A1 = 0 0 0 0 00000111 0 +B = b a t _ t p +B = 0x62 0x61 0x74 0x20 0x74 0x70 +``` + +But of course, we can't use `B` with `PSHUFB` yet, since its values are 8 bits, +and we need indexes that are at most 4 bits (corresponding to one of 16 +values). We can apply the same transformation to split `B` into lower and upper +nybbles as we did `A`. As before, `B0` corresponds to the lower nybbles and +`B1` corresponds to the upper nybbles: + +```ignore + b a t _ c a t _ f o o _ b u m p +B0 = 0x2 0x1 0x4 0x0 0x3 0x1 0x4 0x0 0x6 0xF 0xF 0x0 0x2 0x5 0xD 0x0 +B1 = 0x6 0x6 0x7 0x2 0x6 0x6 0x7 0x2 0x6 0x6 0x6 0x2 0x6 0x7 0x6 0x7 +``` + +And now we have a nice correspondence. `B0` can index `A0` and `B1` can index +`A1`. Here's what we get when we apply `C0 = PSHUFB(A0, B0)`: + +```ignore + b a ... f o ... p + A0[0x2] A0[0x1] A0[0x6] A0[0xF] A0[0x0] +C0 = 00000110 0 00000001 0 0 +``` + +And `C1 = PSHUFB(A1, B1)`: + +```ignore + b a ... f o ... p + A1[0x6] A1[0x6] A1[0x6] A1[0x6] A1[0x7] +C1 = 00000111 00000111 00000111 00000111 0 +``` + +Notice how neither one of `C0` or `C1` is guaranteed to report fully correct +results all on its own. For example, `C1` claims that `b` is a fingerprint for +the pattern `foo` (since `A1[0x6] = 00000111`), and that `o` is a fingerprint +for all of our patterns. But if we combined `C0` and `C1` with an `AND` +operation: + +```ignore + b a ... f o ... p +C = 00000110 0 00000001 0 0 +``` + +Then we now have that `C[i]` contains a bitset corresponding to the matching +fingerprints in a haystack's 16 byte block, where `i` is the `ith` byte in that +block. + +Once we have that, we can look for the position of the least significant bit +in `C`. That position, modulo `8`, gives us the pattern that the fingerprint +matches. That position, integer divided by `8`, also gives us the byte offset +that the fingerprint occurs in inside the 16 byte haystack block. Using those +two pieces of information, we can run a verification procedure that tries +to match all substrings containing that fingerprint at that position in the +haystack. + + +Implementation notes +-------------------- + +The problem with the algorithm as described above is that it uses a single byte +for a fingerprint. This will work well if the fingerprints are rare in the +haystack (e.g., capital letters or special characters in normal English text), +but if the fingerprints are common, you'll wind up spending too much time in +the verification step, which effectively negate the performance benefits of +scanning 16 bytes at a time. Remember, the key to the performance of this +algorithm is to do as little work as possible per 16 bytes. + +This algorithm can be extrapolated in a relatively straight-forward way to use +larger fingerprints. That is, instead of a single byte prefix, we might use a +three byte prefix. The implementation below implements N = {1, 2, 3} and always +picks the largest N possible. The rationale is that the bigger the fingerprint, +the fewer verification steps we'll do. Of course, if N is too large, then we'll +end up doing too much on each step. + +The way to extend it is: + +1. Add a mask for each byte in the fingerprint. (Remember that each mask is + composed of two SIMD vectors.) This results in a value of `C` for each byte + in the fingerprint while searching. +2. When testing each 16 byte block, each value of `C` must be shifted so that + they are aligned. Once aligned, they should all be `AND`'d together. This + will give you only the bitsets corresponding to the full match of the + fingerprint. + +The implementation below is commented to fill in the nitty gritty details. + +References +---------- + +- **[1]** [Hyperscan on GitHub](https://github.com/01org/hyperscan), + [webpage](https://01.org/hyperscan) +- **[2a]** Ben-Kiki, O., Bille, P., Breslauer, D., Gasieniec, L., Grossi, R., + & Weimann, O. (2011). + _Optimal packed string matching_. + In LIPIcs-Leibniz International Proceedings in Informatics (Vol. 13). + Schloss Dagstuhl-Leibniz-Zentrum fuer Informatik. + DOI: 10.4230/LIPIcs.FSTTCS.2011.423. + [PDF](http://drops.dagstuhl.de/opus/volltexte/2011/3355/pdf/37.pdf). +- **[2b]** Ben-Kiki, O., Bille, P., Breslauer, D., Ga̧sieniec, L., Grossi, R., + & Weimann, O. (2014). + _Towards optimal packed string matching_. + Theoretical Computer Science, 525, 111-129. + DOI: 10.1016/j.tcs.2013.06.013. + [PDF](http://www.cs.haifa.ac.il/~oren/Publications/bpsm.pdf). +- **[3]** Bille, P. (2011). + _Fast searching in packed strings_. + Journal of Discrete Algorithms, 9(1), 49-56. + DOI: 10.1016/j.jda.2010.09.003. + [PDF](http://www.sciencedirect.com/science/article/pii/S1570866710000353). +- **[4a]** Faro, S., & Külekci, M. O. (2012, October). + _Fast multiple string matching using streaming SIMD extensions technology_. + In String Processing and Information Retrieval (pp. 217-228). + Springer Berlin Heidelberg. + DOI: 10.1007/978-3-642-34109-0_23. + [PDF](http://www.dmi.unict.it/~faro/papers/conference/faro32.pdf). +- **[4b]** Faro, S., & Külekci, M. O. (2013, September). + _Towards a Very Fast Multiple String Matching Algorithm for Short Patterns_. + In Stringology (pp. 78-91). + [PDF](http://www.dmi.unict.it/~faro/papers/conference/faro36.pdf). +- **[4c]** Faro, S., & Külekci, M. O. (2013, January). + _Fast packed string matching for short patterns_. + In Proceedings of the Meeting on Algorithm Engineering & Expermiments + (pp. 113-121). + Society for Industrial and Applied Mathematics. + [PDF](http://arxiv.org/pdf/1209.6449.pdf). +- **[4d]** Faro, S., & Külekci, M. O. (2014). + _Fast and flexible packed string matching_. + Journal of Discrete Algorithms, 28, 61-72. + DOI: 10.1016/j.jda.2014.07.003. + +[1_u]: https://github.com/01org/hyperscan +[5_u]: https://software.intel.com/sites/landingpage/IntrinsicsGuide +*/ + +use std::cmp; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use syntax::hir::literal::Literals; + +use vector::ssse3::{SSSE3VectorBuilder, u8x16}; + +/// Corresponds to the number of bytes read at a time in the haystack. +const BLOCK_SIZE: usize = 16; + +/// Match reports match information. +#[derive(Debug, Clone)] +pub struct Match { + /// The index of the pattern that matched. The index is in correspondence + /// with the order of the patterns given at construction. + pub pat: usize, + /// The start byte offset of the match. + pub start: usize, + /// The end byte offset of the match. This is always `start + pat.len()`. + pub end: usize, +} + +/// A SIMD accelerated multi substring searcher. +#[derive(Debug, Clone)] +pub struct Teddy { + /// A builder for SSSE3 empowered vectors. + vb: SSSE3VectorBuilder, + /// A list of substrings to match. + pats: Vec>, + /// An Aho-Corasick automaton of the patterns. We use this when we need to + /// search pieces smaller than the Teddy block size. + ac: FullAcAutomaton>, + /// A set of 8 buckets. Each bucket corresponds to a single member of a + /// bitset. A bucket contains zero or more substrings. This is useful + /// when the number of substrings exceeds 8, since our bitsets cannot have + /// more than 8 members. + buckets: Vec>, + /// Our set of masks. There's one mask for each byte in the fingerprint. + masks: Masks, +} + +impl Teddy { + /// Returns true if and only if Teddy is supported on this platform. + /// + /// If this returns `false`, then `Teddy::new(...)` is guaranteed to + /// return `None`. + pub fn available() -> bool { + SSSE3VectorBuilder::new().is_some() + } + + /// Create a new `Teddy` multi substring matcher. + /// + /// If a `Teddy` matcher could not be created (e.g., `pats` is empty or has + /// an empty substring), then `None` is returned. + pub fn new(pats: &Literals) -> Option { + let vb = match SSSE3VectorBuilder::new() { + None => return None, + Some(vb) => vb, + }; + if !Teddy::available() { + return None; + } + + let pats: Vec<_> = pats.literals().iter().map(|p|p.to_vec()).collect(); + let min_len = pats.iter().map(|p| p.len()).min().unwrap_or(0); + // Don't allow any empty patterns and require that we have at + // least one pattern. + if min_len < 1 { + return None; + } + // Pick the largest mask possible, but no larger than 3. + let nmasks = cmp::min(3, min_len); + let mut masks = Masks::new(vb, nmasks); + let mut buckets = vec![vec![]; 8]; + // Assign a substring to each bucket, and add the bucket's bitfield to + // the appropriate position in the mask. + for (pati, pat) in pats.iter().enumerate() { + let bucket = pati % 8; + buckets[bucket].push(pati); + masks.add(bucket as u8, pat); + } + Some(Teddy { + vb: vb, + pats: pats.to_vec(), + ac: AcAutomaton::new(pats.to_vec()).into_full(), + buckets: buckets, + masks: masks, + }) + } + + /// Returns all of the substrings matched by this `Teddy`. + pub fn patterns(&self) -> &[Vec] { + &self.pats + } + + /// Returns the number of substrings in this matcher. + pub fn len(&self) -> usize { + self.pats.len() + } + + /// Returns the approximate size on the heap used by this matcher. + pub fn approximate_size(&self) -> usize { + self.pats.iter().fold(0, |a, b| a + b.len()) + } + + /// Searches `haystack` for the substrings in this `Teddy`. If a match was + /// found, then it is returned. Otherwise, `None` is returned. + pub fn find(&self, haystack: &[u8]) -> Option { + // This is safe because the only way we can construct a Teddy type + // is if SSSE3 is available. + unsafe { self.find_impl(haystack) } + } + + #[allow(unused_attributes)] + #[target_feature(enable = "ssse3")] + unsafe fn find_impl(&self, haystack: &[u8]) -> Option { + // If our haystack is smaller than the block size, then fall back to + // a naive brute force search. + if haystack.is_empty() || haystack.len() < (BLOCK_SIZE + 2) { + return self.slow(haystack, 0); + } + match self.masks.len() { + 0 => None, + 1 => self.find1(haystack), + 2 => self.find2(haystack), + 3 => self.find3(haystack), + _ => unreachable!(), + } + } + + /// `find1` is used when there is only 1 mask. This is the easy case and is + /// pretty much as described in the module documentation. + #[inline(always)] + fn find1(&self, haystack: &[u8]) -> Option { + let mut pos = 0; + let zero = self.vb.u8x16_splat(0); + let len = haystack.len(); + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-16. + let p = haystack.get_unchecked(pos..); + self.vb.u8x16_load_unchecked_unaligned(p) + }; + // N.B. `res0` is our `C` in the module documentation. + let res0 = self.masks.members1(h); + // Only do expensive verification if there are any non-zero bits. + let bitfield = res0.ne(zero).movemask(); + if bitfield != 0 { + if let Some(m) = self.verify(haystack, pos, res0, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + self.slow(haystack, pos) + } + + /// `find2` is used when there are 2 masks, e.g., the fingerprint is 2 bytes + /// long. + #[inline(always)] + fn find2(&self, haystack: &[u8]) -> Option { + // This is an exotic way to right shift a SIMD vector across lanes. + // See below at use for more details. + let zero = self.vb.u8x16_splat(0); + let len = haystack.len(); + // The previous value of `C` (from the module documentation) for the + // *first* byte in the fingerprint. On subsequent iterations, we take + // the last bitset from the previous `C` and insert it into the first + // position of the current `C`, shifting all other bitsets to the right + // one lane. This causes `C` for the first byte to line up with `C` for + // the second byte, so that they can be `AND`'d together. + let mut prev0 = self.vb.u8x16_splat(0xFF); + let mut pos = 1; + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-16. + let p = haystack.get_unchecked(pos..); + self.vb.u8x16_load_unchecked_unaligned(p) + }; + let (res0, res1) = self.masks.members2(h); + + // Do this: + // + // (prev0 << 15) | (res0 >> 1) + // + // This lets us line up our C values for each byte. + let res0prev0 = res0.alignr_15(prev0); + + // `AND`'s our `C` values together. + let res = res0prev0.and(res1); + prev0 = res0; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(1).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last byte in the last + // window, so start the slow search at the last byte of the last + // window. + self.slow(haystack, pos.checked_sub(1).unwrap()) + } + + /// `find3` is used when there are 3 masks, e.g., the fingerprint is 3 bytes + /// long. + /// + /// N.B. This is a straight-forward extrapolation of `find2`. The only + /// difference is that we need to keep track of two previous values of `C`, + /// since we now need to align for three bytes. + #[inline(always)] + fn find3(&self, haystack: &[u8]) -> Option { + let zero = self.vb.u8x16_splat(0); + let len = haystack.len(); + let mut prev0 = self.vb.u8x16_splat(0xFF); + let mut prev1 = self.vb.u8x16_splat(0xFF); + let mut pos = 2; + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-16. + let p = haystack.get_unchecked(pos..); + self.vb.u8x16_load_unchecked_unaligned(p) + }; + let (res0, res1, res2) = self.masks.members3(h); + + let res0prev0 = res0.alignr_14(prev0); + let res1prev1 = res1.alignr_15(prev1); + let res = res0prev0.and(res1prev1).and(res2); + + prev0 = res0; + prev1 = res1; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(2).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last two bytes in the last + // window, so start the slow search at the penultimate byte of the + // last window. + // self.slow(haystack, pos.saturating_sub(2)) + self.slow(haystack, pos.checked_sub(2).unwrap()) + } + + /// Runs the verification procedure on `res` (i.e., `C` from the module + /// documentation), where the haystack block starts at `pos` in + /// `haystack`. `bitfield` has ones in the bit positions that `res` has + /// non-zero bytes. + /// + /// If a match exists, it returns the first one. + #[inline(always)] + fn verify( + &self, + haystack: &[u8], + pos: usize, + res: u8x16, + mut bitfield: u32, + ) -> Option { + while bitfield != 0 { + // The next offset, relative to pos, where some fingerprint + // matched. + let byte_pos = bitfield.trailing_zeros() as usize; + bitfield &= !(1 << byte_pos); + + // Offset relative to the beginning of the haystack. + let start = pos + byte_pos; + + // The bitfield telling us which patterns had fingerprints that + // match at this starting position. + let mut patterns = res.extract(byte_pos); + while patterns != 0 { + let bucket = patterns.trailing_zeros() as usize; + patterns &= !(1 << bucket); + + // Actual substring search verification. + if let Some(m) = self.verify_bucket(haystack, bucket, start) { + return Some(m); + } + } + } + + None + } + + /// Verifies whether any substring in the given bucket matches in haystack + /// at the given starting position. + #[inline(always)] + fn verify_bucket( + &self, + haystack: &[u8], + bucket: usize, + start: usize, + ) -> Option { + // This cycles through the patterns in the bucket in the order that + // the patterns were given. Therefore, we guarantee leftmost-first + // semantics. + for &pati in &self.buckets[bucket] { + let pat = &*self.pats[pati]; + if start + pat.len() > haystack.len() { + continue; + } + if pat == &haystack[start..start + pat.len()] { + return Some(Match { + pat: pati, + start: start, + end: start + pat.len(), + }); + } + } + None + } + + /// Slow substring search through all patterns in this matcher. + /// + /// This is used when we don't have enough bytes in the haystack for our + /// block based approach. + #[inline(never)] + fn slow(&self, haystack: &[u8], pos: usize) -> Option { + self.ac.find(&haystack[pos..]).next().map(|m| { + Match { + pat: m.pati, + start: pos + m.start, + end: pos + m.end, + } + }) + } +} + +/// A list of masks. This has length equal to the length of the fingerprint. +/// The length of the fingerprint is always `min(3, len(smallest_substring))`. +#[derive(Debug, Clone)] +struct Masks { + vb: SSSE3VectorBuilder, + masks: [Mask; 3], + size: usize, +} + +impl Masks { + /// Create a new set of masks of size `n`, where `n` corresponds to the + /// number of bytes in a fingerprint. + fn new(vb: SSSE3VectorBuilder, n: usize) -> Masks { + Masks { + vb: vb, + masks: [Mask::new(vb), Mask::new(vb), Mask::new(vb)], + size: n, + } + } + + /// Returns the number of masks. + fn len(&self) -> usize { + self.size + } + + /// Adds the given pattern to the given bucket. The bucket should be a + /// power of `2 <= 2^7`. + fn add(&mut self, bucket: u8, pat: &[u8]) { + for i in 0..self.len() { + self.masks[i].add(bucket, pat[i]); + } + } + + /// Finds the fingerprints that are in the given haystack block. i.e., this + /// returns `C` as described in the module documentation. + /// + /// More specifically, `for i in 0..16` and `j in 0..8, C[i][j] == 1` if and + /// only if `haystack_block[i]` corresponds to a fingerprint that is part + /// of a pattern in bucket `j`. + #[inline(always)] + fn members1(&self, haystack_block: u8x16) -> u8x16 { + let masklo = self.vb.u8x16_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)) + } + + /// Like members1, but computes C for the first and second bytes in the + /// fingerprint. + #[inline(always)] + fn members2(&self, haystack_block: u8x16) -> (u8x16, u8x16) { + let masklo = self.vb.u8x16_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + (res0, res1) + } + + /// Like `members1`, but computes `C` for the first, second and third bytes + /// in the fingerprint. + #[inline(always)] + fn members3(&self, haystack_block: u8x16) -> (u8x16, u8x16, u8x16) { + let masklo = self.vb.u8x16_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + let res2 = + self.masks[2].lo.shuffle(hlo).and(self.masks[2].hi.shuffle(hhi)); + (res0, res1, res2) + } +} + +/// A single mask. +#[derive(Debug, Clone, Copy)] +struct Mask { + /// Bitsets for the low nybbles in a fingerprint. + lo: u8x16, + /// Bitsets for the high nybbles in a fingerprint. + hi: u8x16, +} + +impl Mask { + /// Create a new mask with no members. + fn new(vb: SSSE3VectorBuilder) -> Mask { + Mask { + lo: vb.u8x16_splat(0), + hi: vb.u8x16_splat(0), + } + } + + /// Adds the given byte to the given bucket. + fn add(&mut self, bucket: u8, byte: u8) { + // Split our byte into two nybbles, and add each nybble to our + // mask. + let byte_lo = (byte & 0xF) as usize; + let byte_hi = (byte >> 4) as usize; + + let lo = self.lo.extract(byte_lo); + self.lo.replace(byte_lo, ((1 << bucket) as u8) | lo); + + let hi = self.hi.extract(byte_hi); + self.hi.replace(byte_hi, ((1 << bucket) as u8) | hi); + } +} diff --git a/bash-5.1/vendor/regex/src/literal/teddy_ssse3/mod.rs b/bash-5.1/vendor/regex/src/literal/teddy_ssse3/mod.rs new file mode 100644 index 0000000..2221159 --- /dev/null +++ b/bash-5.1/vendor/regex/src/literal/teddy_ssse3/mod.rs @@ -0,0 +1,16 @@ +pub use self::imp::*; + +#[cfg(all( + feature = "unstable", + regex_runtime_teddy_ssse3, + any(target_arch = "x86", target_arch = "x86_64"), +))] +mod imp; + +#[cfg(not(all( + feature = "unstable", + regex_runtime_teddy_ssse3, + any(target_arch = "x86", target_arch = "x86_64"), +)))] +#[path = "fallback.rs"] +mod imp; diff --git a/bash-5.1/vendor/regex/src/pattern.rs b/bash-5.1/vendor/regex/src/pattern.rs new file mode 100644 index 0000000..37183c2 --- /dev/null +++ b/bash-5.1/vendor/regex/src/pattern.rs @@ -0,0 +1,62 @@ +use std::str::pattern::{Pattern, Searcher, SearchStep}; + +use re_unicode::{Regex, Matches}; + +pub struct RegexSearcher<'r, 't> { + haystack: &'t str, + it: Matches<'r, 't>, + last_step_end: usize, + next_match: Option<(usize, usize)>, +} + +impl<'r, 't> Pattern<'t> for &'r Regex { + type Searcher = RegexSearcher<'r, 't>; + + fn into_searcher(self, haystack: &'t str) -> RegexSearcher<'r, 't> { + RegexSearcher { + haystack: haystack, + it: self.find_iter(haystack), + last_step_end: 0, + next_match: None, + } + } +} + +unsafe impl<'r, 't> Searcher<'t> for RegexSearcher<'r, 't> { + #[inline] + fn haystack(&self) -> &'t str { + self.haystack + } + + #[inline] + fn next(&mut self) -> SearchStep { + if let Some((s, e)) = self.next_match { + self.next_match = None; + self.last_step_end = e; + return SearchStep::Match(s, e); + } + match self.it.next() { + None => { + if self.last_step_end < self.haystack().len() { + let last = self.last_step_end; + self.last_step_end = self.haystack().len(); + SearchStep::Reject(last, self.haystack().len()) + } else { + SearchStep::Done + } + } + Some(m) => { + let (s, e) = (m.start(), m.end()); + if s == self.last_step_end { + self.last_step_end = e; + SearchStep::Match(s, e) + } else { + self.next_match = Some((s, e)); + let last = self.last_step_end; + self.last_step_end = s; + SearchStep::Reject(last, s) + } + } + } + } +} diff --git a/bash-5.1/vendor/regex/src/pikevm.rs b/bash-5.1/vendor/regex/src/pikevm.rs new file mode 100644 index 0000000..80d4471 --- /dev/null +++ b/bash-5.1/vendor/regex/src/pikevm.rs @@ -0,0 +1,377 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This module implements the Pike VM. That is, it guarantees linear time +// search of a regex on any text with memory use proportional to the size of +// the regex. +// +// It is equal in power to the backtracking engine in this crate, except the +// backtracking engine is typically faster on small regexes/texts at the +// expense of a bigger memory footprint. +// +// It can do more than the DFA can (specifically, record capture locations +// and execute Unicode word boundary assertions), but at a slower speed. +// Specifically, the Pike VM exectues a DFA implicitly by repeatedly expanding +// epsilon transitions. That is, the Pike VM engine can be in multiple states +// at once where as the DFA is only ever in one state at a time. +// +// Therefore, the Pike VM is generally treated as the fallback when the other +// matching engines either aren't feasible to run or are insufficient. + +use std::mem; + +use exec::ProgramCache; +use input::{Input, InputAt}; +use prog::{Program, InstPtr}; +use re_trait::Slot; +use sparse::SparseSet; + +/// An NFA simulation matching engine. +#[derive(Debug)] +pub struct Fsm<'r, I> { + /// The sequence of opcodes (among other things) that is actually executed. + /// + /// The program may be byte oriented or Unicode codepoint oriented. + prog: &'r Program, + /// An explicit stack used for following epsilon transitions. (This is + /// borrowed from the cache.) + stack: &'r mut Vec, + /// The input to search. + input: I, +} + +/// A cached allocation that can be reused on each execution. +#[derive(Clone, Debug)] +pub struct Cache { + /// A pair of ordered sets for tracking NFA states. + clist: Threads, + nlist: Threads, + /// An explicit stack used for following epsilon transitions. + stack: Vec, +} + +/// An ordered set of NFA states and their captures. +#[derive(Clone, Debug)] +struct Threads { + /// An ordered set of opcodes (each opcode is an NFA state). + set: SparseSet, + /// Captures for every NFA state. + /// + /// It is stored in row-major order, where the columns are the capture + /// slots and the rows are the states. + caps: Vec, + /// The number of capture slots stored per thread. (Every capture has + /// two slots.) + slots_per_thread: usize, +} + +/// A representation of an explicit stack frame when following epsilon +/// transitions. This is used to avoid recursion. +#[derive(Clone, Debug)] +enum FollowEpsilon { + /// Follow transitions at the given instruction pointer. + IP(InstPtr), + /// Restore the capture slot with the given position in the input. + Capture { slot: usize, pos: Slot }, +} + +impl Cache { + /// Create a new allocation used by the NFA machine to record execution + /// and captures. + pub fn new(_prog: &Program) -> Self { + Cache { + clist: Threads::new(), + nlist: Threads::new(), + stack: vec![], + } + } +} + +impl<'r, I: Input> Fsm<'r, I> { + /// Execute the NFA matching engine. + /// + /// If there's a match, `exec` returns `true` and populates the given + /// captures accordingly. + pub fn exec( + prog: &'r Program, + cache: &ProgramCache, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + input: I, + start: usize, + ) -> bool { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.pikevm; + cache.clist.resize(prog.len(), prog.captures.len()); + cache.nlist.resize(prog.len(), prog.captures.len()); + let at = input.at(start); + Fsm { + prog: prog, + stack: &mut cache.stack, + input: input, + }.exec_( + &mut cache.clist, + &mut cache.nlist, + matches, + slots, + quit_after_match, + at, + ) + } + + fn exec_( + &mut self, + mut clist: &mut Threads, + mut nlist: &mut Threads, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + mut at: InputAt, + ) -> bool { + let mut matched = false; + let mut all_matched = false; + clist.set.clear(); + nlist.set.clear(); +'LOOP: loop { + if clist.set.is_empty() { + // Three ways to bail out when our current set of threads is + // empty. + // + // 1. We have a match---so we're done exploring any possible + // alternatives. Time to quit. (We can't do this if we're + // looking for matches for multiple regexes, unless we know + // they all matched.) + // + // 2. If the expression starts with a '^' we can terminate as + // soon as the last thread dies. + if (matched && matches.len() <= 1) + || all_matched + || (!at.is_start() && self.prog.is_anchored_start) { + break; + } + + // 3. If there's a literal prefix for the program, try to + // jump ahead quickly. If it can't be found, then we can + // bail out early. + if !self.prog.prefixes.is_empty() { + at = match self.input.prefix_at(&self.prog.prefixes, at) { + None => break, + Some(at) => at, + }; + } + } + + // This simulates a preceding '.*?' for every regex by adding + // a state starting at the current position in the input for the + // beginning of the program only if we don't already have a match. + if clist.set.is_empty() + || (!self.prog.is_anchored_start && !all_matched) { + self.add(&mut clist, slots, 0, at); + } + // The previous call to "add" actually inspects the position just + // before the current character. For stepping through the machine, + // we can to look at the current character, so we advance the + // input. + let at_next = self.input.at(at.next_pos()); + for i in 0..clist.set.len() { + let ip = clist.set[i]; + if self.step( + &mut nlist, + matches, + slots, + clist.caps(ip), + ip, + at, + at_next, + ) { + matched = true; + all_matched = all_matched || matches.iter().all(|&b| b); + if quit_after_match { + // If we only care if a match occurs (not its + // position), then we can quit right now. + break 'LOOP; + } + if self.prog.matches.len() == 1 { + // We don't need to check the rest of the threads + // in this set because we've matched something + // ("leftmost-first"). However, we still need to check + // threads in the next set to support things like + // greedy matching. + // + // This is only true on normal regexes. For regex sets, + // we need to mush on to observe other matches. + break; + } + } + } + if at.is_end() { + break; + } + at = at_next; + mem::swap(clist, nlist); + nlist.set.clear(); + } + matched + } + + /// Step through the input, one token (byte or codepoint) at a time. + /// + /// nlist is the set of states that will be processed on the next token + /// in the input. + /// + /// caps is the set of captures passed by the caller of the NFA. They are + /// written to only when a match state is visited. + /// + /// thread_caps is the set of captures set for the current NFA state, ip. + /// + /// at and at_next are the current and next positions in the input. at or + /// at_next may be EOF. + fn step( + &mut self, + nlist: &mut Threads, + matches: &mut [bool], + slots: &mut [Slot], + thread_caps: &mut [Option], + ip: usize, + at: InputAt, + at_next: InputAt, + ) -> bool { + use prog::Inst::*; + match self.prog[ip] { + Match(match_slot) => { + if match_slot < matches.len() { + matches[match_slot] = true; + } + for (slot, val) in slots.iter_mut().zip(thread_caps.iter()) { + *slot = *val; + } + true + } + Char(ref inst) => { + if inst.c == at.char() { + self.add(nlist, thread_caps, inst.goto, at_next); + } + false + } + Ranges(ref inst) => { + if inst.matches(at.char()) { + self.add(nlist, thread_caps, inst.goto, at_next); + } + false + } + Bytes(ref inst) => { + if let Some(b) = at.byte() { + if inst.matches(b) { + self.add(nlist, thread_caps, inst.goto, at_next); + } + } + false + } + EmptyLook(_) | Save(_) | Split(_) => false, + } + } + + /// Follows epsilon transitions and adds them for processing to nlist, + /// starting at and including ip. + fn add( + &mut self, + nlist: &mut Threads, + thread_caps: &mut [Option], + ip: usize, + at: InputAt, + ) { + self.stack.push(FollowEpsilon::IP(ip)); + while let Some(frame) = self.stack.pop() { + match frame { + FollowEpsilon::IP(ip) => { + self.add_step(nlist, thread_caps, ip, at); + } + FollowEpsilon::Capture { slot, pos } => { + thread_caps[slot] = pos; + } + } + } + } + + /// A helper function for add that avoids excessive pushing to the stack. + fn add_step( + &mut self, + nlist: &mut Threads, + thread_caps: &mut [Option], + mut ip: usize, + at: InputAt, + ) { + // Instead of pushing and popping to the stack, we mutate ip as we + // traverse the set of states. We only push to the stack when we + // absolutely need recursion (restoring captures or following a + // branch). + use prog::Inst::*; + loop { + // Don't visit states we've already added. + if nlist.set.contains(ip) { + return; + } + nlist.set.insert(ip); + match self.prog[ip] { + EmptyLook(ref inst) => { + if self.input.is_empty_match(at, inst) { + ip = inst.goto; + } + } + Save(ref inst) => { + if inst.slot < thread_caps.len() { + self.stack.push(FollowEpsilon::Capture { + slot: inst.slot, + pos: thread_caps[inst.slot], + }); + thread_caps[inst.slot] = Some(at.pos()); + } + ip = inst.goto; + } + Split(ref inst) => { + self.stack.push(FollowEpsilon::IP(inst.goto2)); + ip = inst.goto1; + } + Match(_) | Char(_) | Ranges(_) | Bytes(_) => { + let t = &mut nlist.caps(ip); + for (slot, val) in t.iter_mut().zip(thread_caps.iter()) { + *slot = *val; + } + return; + } + } + } + } +} + +impl Threads { + fn new() -> Self { + Threads { + set: SparseSet::new(0), + caps: vec![], + slots_per_thread: 0, + } + } + + fn resize(&mut self, num_insts: usize, ncaps: usize) { + if num_insts == self.set.capacity() { + return; + } + self.slots_per_thread = ncaps * 2; + self.set = SparseSet::new(num_insts); + self.caps = vec![None; self.slots_per_thread * num_insts]; + } + + fn caps(&mut self, pc: usize) -> &mut [Option] { + let i = pc * self.slots_per_thread; + &mut self.caps[i..i + self.slots_per_thread] + } +} diff --git a/bash-5.1/vendor/regex/src/prog.rs b/bash-5.1/vendor/regex/src/prog.rs new file mode 100644 index 0000000..4262aa9 --- /dev/null +++ b/bash-5.1/vendor/regex/src/prog.rs @@ -0,0 +1,425 @@ +use std::collections::HashMap; +use std::cmp::Ordering; +use std::fmt; +use std::ops::Deref; +use std::mem; +use std::slice; +use std::sync::Arc; + +use input::Char; +use literal::LiteralSearcher; + +/// `InstPtr` represents the index of an instruction in a regex program. +pub type InstPtr = usize; + +/// Program is a sequence of instructions and various facts about thos +/// instructions. +#[derive(Clone)] +pub struct Program { + /// A sequence of instructions that represents an NFA. + pub insts: Vec, + /// Pointers to each Match instruction in the sequence. + /// + /// This is always length 1 unless this program represents a regex set. + pub matches: Vec, + /// The ordered sequence of all capture groups extracted from the AST. + /// Unnamed groups are `None`. + pub captures: Vec>, + /// Pointers to all named capture groups into `captures`. + pub capture_name_idx: Arc>, + /// A pointer to the start instruction. This can vary depending on how + /// the program was compiled. For example, programs for use with the DFA + /// engine have a `.*?` inserted at the beginning of unanchored regular + /// expressions. The actual starting point of the program is after the + /// `.*?`. + pub start: InstPtr, + /// A set of equivalence classes for discriminating bytes in the compiled + /// program. + pub byte_classes: Vec, + /// When true, this program can only match valid UTF-8. + pub only_utf8: bool, + /// When true, this program uses byte range instructions instead of Unicode + /// range instructions. + pub is_bytes: bool, + /// When true, the program is compiled for DFA matching. For example, this + /// implies `is_bytes` and also inserts a preceding `.*?` for unanchored + /// regexes. + pub is_dfa: bool, + /// When true, the program matches text in reverse (for use only in the + /// DFA). + pub is_reverse: bool, + /// Whether the regex must match from the start of the input. + pub is_anchored_start: bool, + /// Whether the regex must match at the end of the input. + pub is_anchored_end: bool, + /// Whether this program contains a Unicode word boundary instruction. + pub has_unicode_word_boundary: bool, + /// A possibly empty machine for very quickly matching prefix literals. + pub prefixes: LiteralSearcher, + /// A limit on the size of the cache that the DFA is allowed to use while + /// matching. + /// + /// The cache limit specifies approximately how much space we're willing to + /// give to the state cache. Once the state cache exceeds the size, it is + /// wiped and all states must be re-computed. + /// + /// Note that this value does not impact correctness. It can be set to 0 + /// and the DFA will run just fine. (It will only ever store exactly one + /// state in the cache, and will likely run very slowly, but it will work.) + /// + /// Also note that this limit is *per thread of execution*. That is, + /// if the same regex is used to search text across multiple threads + /// simultaneously, then the DFA cache is not shared. Instead, copies are + /// made. + pub dfa_size_limit: usize, +} + +impl Program { + /// Creates an empty instruction sequence. Fields are given default + /// values. + pub fn new() -> Self { + Program { + insts: vec![], + matches: vec![], + captures: vec![], + capture_name_idx: Arc::new(HashMap::new()), + start: 0, + byte_classes: vec![0; 256], + only_utf8: true, + is_bytes: false, + is_dfa: false, + is_reverse: false, + is_anchored_start: false, + is_anchored_end: false, + has_unicode_word_boundary: false, + prefixes: LiteralSearcher::empty(), + dfa_size_limit: 2 * (1<<20), + } + } + + /// If pc is an index to a no-op instruction (like Save), then return the + /// next pc that is not a no-op instruction. + pub fn skip(&self, mut pc: usize) -> usize { + loop { + match self[pc] { + Inst::Save(ref i) => pc = i.goto, + _ => return pc, + } + } + } + + /// Return true if and only if an execution engine at instruction `pc` will + /// always lead to a match. + pub fn leads_to_match(&self, pc: usize) -> bool { + if self.matches.len() > 1 { + // If we have a regex set, then we have more than one ending + // state, so leading to one of those states is generally + // meaningless. + return false; + } + match self[self.skip(pc)] { + Inst::Match(_) => true, + _ => false, + } + } + + /// Returns true if the current configuration demands that an implicit + /// `.*?` be prepended to the instruction sequence. + pub fn needs_dotstar(&self) -> bool { + self.is_dfa && !self.is_reverse && !self.is_anchored_start + } + + /// Returns true if this program uses Byte instructions instead of + /// Char/Range instructions. + pub fn uses_bytes(&self) -> bool { + self.is_bytes || self.is_dfa + } + + /// Returns true if this program exclusively matches valid UTF-8 bytes. + /// + /// That is, if an invalid UTF-8 byte is seen, then no match is possible. + pub fn only_utf8(&self) -> bool { + self.only_utf8 + } + + /// Return the approximate heap usage of this instruction sequence in + /// bytes. + pub fn approximate_size(&self) -> usize { + // The only instruction that uses heap space is Ranges (for + // Unicode codepoint programs) to store non-overlapping codepoint + // ranges. To keep this operation constant time, we ignore them. + (self.len() * mem::size_of::()) + + (self.matches.len() * mem::size_of::()) + + (self.captures.len() * mem::size_of::>()) + + (self.capture_name_idx.len() * + (mem::size_of::() + mem::size_of::())) + + (self.byte_classes.len() * mem::size_of::()) + + self.prefixes.approximate_size() + } +} + +impl Deref for Program { + type Target = [Inst]; + + fn deref(&self) -> &Self::Target { + &*self.insts + } +} + +impl fmt::Debug for Program { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Inst::*; + + fn with_goto(cur: usize, goto: usize, fmtd: String) -> String { + if goto == cur + 1 { + fmtd + } else { + format!("{} (goto: {})", fmtd, goto) + } + } + + fn visible_byte(b: u8) -> String { + use std::ascii::escape_default; + let escaped = escape_default(b).collect::>(); + String::from_utf8_lossy(&escaped).into_owned() + } + + for (pc, inst) in self.iter().enumerate() { + match *inst { + Match(slot) => { + try!(write!(f, "{:04} Match({:?})", pc, slot)) + } + Save(ref inst) => { + let s = format!("{:04} Save({})", pc, inst.slot); + try!(write!(f, "{}", with_goto(pc, inst.goto, s))); + } + Split(ref inst) => { + try!(write!(f, "{:04} Split({}, {})", + pc, inst.goto1, inst.goto2)); + } + EmptyLook(ref inst) => { + let s = format!("{:?}", inst.look); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, s))); + } + Char(ref inst) => { + let s = format!("{:?}", inst.c); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, s))); + } + Ranges(ref inst) => { + let ranges = inst.ranges + .iter() + .map(|r| format!("{:?}-{:?}", r.0, r.1)) + .collect::>() + .join(", "); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, ranges))); + } + Bytes(ref inst) => { + let s = format!( + "Bytes({}, {})", + visible_byte(inst.start), + visible_byte(inst.end)); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, s))); + } + } + if pc == self.start { + try!(write!(f, " (start)")); + } + try!(write!(f, "\n")); + } + Ok(()) + } +} + +impl<'a> IntoIterator for &'a Program { + type Item = &'a Inst; + type IntoIter = slice::Iter<'a, Inst>; + fn into_iter(self) -> Self::IntoIter { self.iter() } +} + +/// Inst is an instruction code in a Regex program. +/// +/// Regrettably, a regex program either contains Unicode codepoint +/// instructions (Char and Ranges) or it contains byte instructions (Bytes). +/// A regex program can never contain both. +/// +/// It would be worth investigating splitting this into two distinct types and +/// then figuring out how to make the matching engines polymorphic over those +/// types without sacrificing performance. +/// +/// Other than the benefit of moving invariants into the type system, another +/// benefit is the decreased size. If we remove the `Char` and `Ranges` +/// instructions from the `Inst` enum, then its size shrinks from 40 bytes to +/// 24 bytes. (This is because of the removal of a `Vec` in the `Ranges` +/// variant.) Given that byte based machines are typically much bigger than +/// their Unicode analogues (because they can decode UTF-8 directly), this ends +/// up being a pretty significant savings. +#[derive(Clone, Debug)] +pub enum Inst { + /// Match indicates that the program has reached a match state. + /// + /// The number in the match corresponds to the Nth logical regular + /// expression in this program. This index is always 0 for normal regex + /// programs. Values greater than 0 appear when compiling regex sets, and + /// each match instruction gets its own unique value. The value corresponds + /// to the Nth regex in the set. + Match(usize), + /// Save causes the program to save the current location of the input in + /// the slot indicated by InstSave. + Save(InstSave), + /// Split causes the program to diverge to one of two paths in the + /// program, preferring goto1 in InstSplit. + Split(InstSplit), + /// EmptyLook represents a zero-width assertion in a regex program. A + /// zero-width assertion does not consume any of the input text. + EmptyLook(InstEmptyLook), + /// Char requires the regex program to match the character in InstChar at + /// the current position in the input. + Char(InstChar), + /// Ranges requires the regex program to match the character at the current + /// position in the input with one of the ranges specified in InstRanges. + Ranges(InstRanges), + /// Bytes is like Ranges, except it expresses a single byte range. It is + /// used in conjunction with Split instructions to implement multi-byte + /// character classes. + Bytes(InstBytes), +} + +impl Inst { + /// Returns true if and only if this is a match instruction. + pub fn is_match(&self) -> bool { + match *self { + Inst::Match(_) => true, + _ => false, + } + } +} + +/// Representation of the Save instruction. +#[derive(Clone, Debug)] +pub struct InstSave { + /// The next location to execute in the program. + pub goto: InstPtr, + /// The capture slot (there are two slots for every capture in a regex, + /// including the zeroth capture for the entire match). + pub slot: usize, +} + +/// Representation of the Split instruction. +#[derive(Clone, Debug)] +pub struct InstSplit { + /// The first instruction to try. A match resulting from following goto1 + /// has precedence over a match resulting from following goto2. + pub goto1: InstPtr, + /// The second instruction to try. A match resulting from following goto1 + /// has precedence over a match resulting from following goto2. + pub goto2: InstPtr, +} + +/// Representation of the `EmptyLook` instruction. +#[derive(Clone, Debug)] +pub struct InstEmptyLook { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The type of zero-width assertion to check. + pub look: EmptyLook, +} + +/// The set of zero-width match instructions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EmptyLook { + /// Start of line or input. + StartLine, + /// End of line or input. + EndLine, + /// Start of input. + StartText, + /// End of input. + EndText, + /// Word character on one side and non-word character on other. + WordBoundary, + /// Word character on both sides or non-word character on both sides. + NotWordBoundary, + /// ASCII word boundary. + WordBoundaryAscii, + /// Not ASCII word boundary. + NotWordBoundaryAscii, +} + +/// Representation of the Char instruction. +#[derive(Clone, Debug)] +pub struct InstChar { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The character to test. + pub c: char, +} + +/// Representation of the Ranges instruction. +#[derive(Clone, Debug)] +pub struct InstRanges { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The set of Unicode scalar value ranges to test. + pub ranges: Vec<(char, char)>, +} + +impl InstRanges { + /// Tests whether the given input character matches this instruction. + pub fn matches(&self, c: Char) -> bool { + // This speeds up the `match_class_unicode` benchmark by checking + // some common cases quickly without binary search. e.g., Matching + // a Unicode class on predominantly ASCII text. + for r in self.ranges.iter().take(4) { + if c < r.0 { + return false; + } + if c <= r.1 { + return true; + } + } + self.ranges.binary_search_by(|r| { + if r.1 < c { + Ordering::Less + } else if r.0 > c { + Ordering::Greater + } else { + Ordering::Equal + } + }).is_ok() + } + + /// Return the number of distinct characters represented by all of the + /// ranges. + pub fn num_chars(&self) -> usize { + self.ranges.iter() + .map(|&(s, e)| 1 + (e as u32) - (s as u32)) + .fold(0, |acc, len| acc + len) + as usize + } +} + +/// Representation of the Bytes instruction. +#[derive(Clone, Debug)] +pub struct InstBytes { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The start (inclusive) of this byte range. + pub start: u8, + /// The end (inclusive) of this byte range. + pub end: u8, +} + +impl InstBytes { + /// Returns true if and only if the given byte is in this range. + pub fn matches(&self, byte: u8) -> bool { + self.start <= byte && byte <= self.end + } +} diff --git a/bash-5.1/vendor/regex/src/re_builder.rs b/bash-5.1/vendor/regex/src/re_builder.rs new file mode 100644 index 0000000..ae60ecf --- /dev/null +++ b/bash-5.1/vendor/regex/src/re_builder.rs @@ -0,0 +1,346 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// The set of user configurable options for compiling zero or more regexes. +#[derive(Clone, Debug)] +#[allow(missing_docs)] +pub struct RegexOptions { + pub pats: Vec, + pub size_limit: usize, + pub dfa_size_limit: usize, + pub nest_limit: u32, + pub case_insensitive: bool, + pub multi_line: bool, + pub dot_matches_new_line: bool, + pub swap_greed: bool, + pub ignore_whitespace: bool, + pub unicode: bool, +} + +impl Default for RegexOptions { + fn default() -> Self { + RegexOptions { + pats: vec![], + size_limit: 10 * (1<<20), + dfa_size_limit: 2 * (1<<20), + nest_limit: 250, + case_insensitive: false, + multi_line: false, + dot_matches_new_line: false, + swap_greed: false, + ignore_whitespace: false, + unicode: true, + } + } +} + +macro_rules! define_builder { + ($name:ident, $regex_mod:ident, $only_utf8:expr) => { + pub mod $name { + use error::Error; + use exec::ExecBuilder; + use super::RegexOptions; + + use $regex_mod::Regex; + +/// A configurable builder for a regular expression. +/// +/// A builder can be used to configure how the regex is built, for example, by +/// setting the default flags (which can be overridden in the expression +/// itself) or setting various limits. +pub struct RegexBuilder(RegexOptions); + +impl RegexBuilder { + /// Create a new regular expression builder with the given pattern. + /// + /// If the pattern is invalid, then an error will be returned when + /// `build` is called. + pub fn new(pattern: &str) -> RegexBuilder { + let mut builder = RegexBuilder(RegexOptions::default()); + builder.0.pats.push(pattern.to_owned()); + builder + } + + /// Consume the builder and compile the regular expression. + /// + /// Note that calling `as_str` on the resulting `Regex` will produce the + /// pattern given to `new` verbatim. Notably, it will not incorporate any + /// of the flags set on this builder. + pub fn build(&self) -> Result { + ExecBuilder::new_options(self.0.clone()) + .only_utf8($only_utf8) + .build() + .map(Regex::from) + } + + /// Set the value for the case insensitive (`i`) flag. + /// + /// When enabled, letters in the pattern will match both upper case and + /// lower case variants. + pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.case_insensitive = yes; + self + } + + /// Set the value for the multi-line matching (`m`) flag. + /// + /// When enabled, `^` matches the beginning of lines and `$` matches the + /// end of lines. + /// + /// By default, they match beginning/end of the input. + pub fn multi_line(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.multi_line = yes; + self + } + + /// Set the value for the any character (`s`) flag, where in `.` matches + /// anything when `s` is set and matches anything except for new line when + /// it is not set (the default). + /// + /// N.B. "matches anything" means "any byte" for `regex::bytes::Regex` + /// expressions and means "any Unicode scalar value" for `regex::Regex` + /// expressions. + pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.dot_matches_new_line = yes; + self + } + + /// Set the value for the greedy swap (`U`) flag. + /// + /// When enabled, a pattern like `a*` is lazy (tries to find shortest + /// match) and `a*?` is greedy (tries to find longest match). + /// + /// By default, `a*` is greedy and `a*?` is lazy. + pub fn swap_greed(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.swap_greed = yes; + self + } + + /// Set the value for the ignore whitespace (`x`) flag. + /// + /// When enabled, whitespace such as new lines and spaces will be ignored + /// between expressions of the pattern, and `#` can be used to start a + /// comment until the next new line. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.ignore_whitespace = yes; + self + } + + /// Set the value for the Unicode (`u`) flag. + /// + /// Enabled by default. When disabled, character classes such as `\w` only + /// match ASCII word characters instead of all Unicode word characters. + pub fn unicode(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.unicode = yes; + self + } + + /// Set the approximate size limit of the compiled regular expression. + /// + /// This roughly corresponds to the number of bytes occupied by a single + /// compiled program. If the program exceeds this number, then a + /// compilation error is returned. + pub fn size_limit(&mut self, limit: usize) -> &mut RegexBuilder { + self.0.size_limit = limit; + self + } + + /// Set the approximate size of the cache used by the DFA. + /// + /// This roughly corresponds to the number of bytes that the DFA will + /// use while searching. + /// + /// Note that this is a *per thread* limit. There is no way to set a global + /// limit. In particular, if a regex is used from multiple threads + /// simultaneously, then each thread may use up to the number of bytes + /// specified here. + pub fn dfa_size_limit(&mut self, limit: usize) -> &mut RegexBuilder { + self.0.dfa_size_limit = limit; + self + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut RegexBuilder { + self.0.nest_limit = limit; + self + } +} + } + } +} + +define_builder!(bytes, re_bytes, false); +define_builder!(unicode, re_unicode, true); + +macro_rules! define_set_builder { + ($name:ident, $regex_mod:ident, $only_utf8:expr) => { + pub mod $name { + use error::Error; + use exec::ExecBuilder; + use super::RegexOptions; + + use re_set::$regex_mod::RegexSet; + +/// A configurable builder for a set of regular expressions. +/// +/// A builder can be used to configure how the regexes are built, for example, +/// by setting the default flags (which can be overridden in the expression +/// itself) or setting various limits. +pub struct RegexSetBuilder(RegexOptions); + +impl RegexSetBuilder { + /// Create a new regular expression builder with the given pattern. + /// + /// If the pattern is invalid, then an error will be returned when + /// `build` is called. + pub fn new(patterns: I) -> RegexSetBuilder + where S: AsRef, I: IntoIterator { + let mut builder = RegexSetBuilder(RegexOptions::default()); + for pat in patterns { + builder.0.pats.push(pat.as_ref().to_owned()); + } + builder + } + + /// Consume the builder and compile the regular expressions into a set. + pub fn build(&self) -> Result { + ExecBuilder::new_options(self.0.clone()) + .only_utf8($only_utf8) + .build() + .map(RegexSet::from) + } + + /// Set the value for the case insensitive (`i`) flag. + pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.case_insensitive = yes; + self + } + + /// Set the value for the multi-line matching (`m`) flag. + pub fn multi_line(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.multi_line = yes; + self + } + + /// Set the value for the any character (`s`) flag, where in `.` matches + /// anything when `s` is set and matches anything except for new line when + /// it is not set (the default). + /// + /// N.B. "matches anything" means "any byte" for `regex::bytes::RegexSet` + /// expressions and means "any Unicode scalar value" for `regex::RegexSet` + /// expressions. + pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.dot_matches_new_line = yes; + self + } + + /// Set the value for the greedy swap (`U`) flag. + pub fn swap_greed(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.swap_greed = yes; + self + } + + /// Set the value for the ignore whitespace (`x`) flag. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.ignore_whitespace = yes; + self + } + + /// Set the value for the Unicode (`u`) flag. + pub fn unicode(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.unicode = yes; + self + } + + /// Set the approximate size limit of the compiled regular expression. + /// + /// This roughly corresponds to the number of bytes occupied by a single + /// compiled program. If the program exceeds this number, then a + /// compilation error is returned. + pub fn size_limit(&mut self, limit: usize) -> &mut RegexSetBuilder { + self.0.size_limit = limit; + self + } + + /// Set the approximate size of the cache used by the DFA. + /// + /// This roughly corresponds to the number of bytes that the DFA will + /// use while searching. + /// + /// Note that this is a *per thread* limit. There is no way to set a global + /// limit. In particular, if a regex is used from multiple threads + /// simulanteously, then each thread may use up to the number of bytes + /// specified here. + pub fn dfa_size_limit(&mut self, limit: usize) -> &mut RegexSetBuilder { + self.0.dfa_size_limit = limit; + self + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut RegexSetBuilder { + self.0.nest_limit = limit; + self + } + +} + } + } +} + +define_set_builder!(set_bytes, bytes, false); +define_set_builder!(set_unicode, unicode, true); diff --git a/bash-5.1/vendor/regex/src/re_bytes.rs b/bash-5.1/vendor/regex/src/re_bytes.rs new file mode 100644 index 0000000..d577d6b --- /dev/null +++ b/bash-5.1/vendor/regex/src/re_bytes.rs @@ -0,0 +1,1072 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt; +use std::ops::Index; +use std::str::FromStr; +use std::sync::Arc; + +use memchr::memchr; + +use exec::{Exec, ExecNoSync}; +use expand::expand_bytes; +use error::Error; +use re_builder::bytes::RegexBuilder; +use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter}; + +/// Match represents a single match of a regex in a haystack. +/// +/// The lifetime parameter `'t` refers to the lifetime of the matched text. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Match<'t> { + text: &'t [u8], + start: usize, + end: usize, +} + +impl<'t> Match<'t> { + /// Returns the starting byte offset of the match in the haystack. + #[inline] + pub fn start(&self) -> usize { + self.start + } + + /// Returns the ending byte offset of the match in the haystack. + #[inline] + pub fn end(&self) -> usize { + self.end + } + + /// Returns the matched text. + #[inline] + pub fn as_bytes(&self) -> &'t [u8] { + &self.text[self.start..self.end] + } + + /// Creates a new match from the given haystack and byte offsets. + #[inline] + fn new(haystack: &'t [u8], start: usize, end: usize) -> Match<'t> { + Match { + text: haystack, + start: start, + end: end, + } + } +} + +/// A compiled regular expression for matching arbitrary bytes. +/// +/// It can be used to search, split or replace text. All searching is done with +/// an implicit `.*?` at the beginning and end of an expression. To force an +/// expression to match the whole string (or a prefix or a suffix), you must +/// use an anchor like `^` or `$` (or `\A` and `\z`). +/// +/// Like the `Regex` type in the parent module, matches with this regex return +/// byte offsets into the search text. **Unlike** the parent `Regex` type, +/// these byte offsets may not correspond to UTF-8 sequence boundaries since +/// the regexes in this module can match arbitrary bytes. +#[derive(Clone)] +pub struct Regex(Exec); + +impl fmt::Display for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.as_str()) + } +} + +impl fmt::Debug for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +/// A constructor for Regex from an Exec. +/// +/// This is hidden because Exec isn't actually part of the public API. +#[doc(hidden)] +impl From for Regex { + fn from(exec: Exec) -> Regex { + Regex(exec) + } +} + +impl FromStr for Regex { + type Err = Error; + + /// Attempts to parse a string into a regular expression + fn from_str(s: &str) -> Result { + Regex::new(s) + } +} + +/// Core regular expression methods. +impl Regex { + /// Compiles a regular expression. Once compiled, it can be used repeatedly + /// to search, split or replace text in a string. + /// + /// If an invalid expression is given, then an error is returned. + pub fn new(re: &str) -> Result { + RegexBuilder::new(re).build() + } + + /// Returns true if and only if the regex matches the string given. + /// + /// It is recommended to use this method if all you need to do is test + /// a match, since the underlying matching engine may be able to do less + /// work. + /// + /// # Example + /// + /// Test if some text contains at least one word with exactly 13 ASCII word + /// bytes: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"I categorically deny having triskaidekaphobia."; + /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); + /// # } + /// ``` + pub fn is_match(&self, text: &[u8]) -> bool { + self.is_match_at(text, 0) + } + + /// Returns the start and end byte range of the leftmost-first match in + /// `text`. If no match exists, then `None` is returned. + /// + /// Note that this should only be used if you want to discover the position + /// of the match. Testing the existence of a match is faster if you use + /// `is_match`. + /// + /// # Example + /// + /// Find the start and end location of the first word with exactly 13 + /// ASCII word bytes: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"I categorically deny having triskaidekaphobia."; + /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); + /// assert_eq!((mat.start(), mat.end()), (2, 15)); + /// # } + /// ``` + pub fn find<'t>(&self, text: &'t [u8]) -> Option> { + self.find_at(text, 0) + } + + /// Returns an iterator for each successive non-overlapping match in + /// `text`, returning the start and end byte indices with respect to + /// `text`. + /// + /// # Example + /// + /// Find the start and end location of every word with exactly 13 ASCII + /// word bytes: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"Retroactively relinquishing remunerations is reprehensible."; + /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { + /// println!("{:?}", mat); + /// } + /// # } + /// ``` + pub fn find_iter<'r, 't>(&'r self, text: &'t [u8]) -> Matches<'r, 't> { + Matches(self.0.searcher().find_iter(text)) + } + + /// Returns the capture groups corresponding to the leftmost-first + /// match in `text`. Capture group `0` always corresponds to the entire + /// match. If no match is found, then `None` is returned. + /// + /// You should only use `captures` if you need access to the location of + /// capturing group matches. Otherwise, `find` is faster for discovering + /// the location of the overall match. + /// + /// # Examples + /// + /// Say you have some text with movie names and their release years, + /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text + /// looking like that, while also extracting the movie name and its release + /// year separately. + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); + /// let text = b"Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(&caps[1], &b"Citizen Kane"[..]); + /// assert_eq!(&caps[2], &b"1941"[..]); + /// assert_eq!(&caps[0], &b"'Citizen Kane' (1941)"[..]); + /// // You can also access the groups by index using the Index notation. + /// // Note that this will panic on an invalid index. + /// assert_eq!(&caps[1], b"Citizen Kane"); + /// assert_eq!(&caps[2], b"1941"); + /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)"); + /// # } + /// ``` + /// + /// Note that the full match is at capture group `0`. Each subsequent + /// capture group is indexed by the order of its opening `(`. + /// + /// We can make this example a bit clearer by using *named* capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = b"Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(&caps["title"], &b"Citizen Kane"[..]); + /// assert_eq!(&caps["year"], &b"1941"[..]); + /// assert_eq!(&caps[0], &b"'Citizen Kane' (1941)"[..]); + /// // You can also access the groups by name using the Index notation. + /// // Note that this will panic on an invalid group name. + /// assert_eq!(&caps["title"], b"Citizen Kane"); + /// assert_eq!(&caps["year"], b"1941"); + /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)"); + /// + /// # } + /// ``` + /// + /// Here we name the capture groups, which we can access with the `name` + /// method or the `Index` notation with a `&str`. Note that the named + /// capture groups are still accessible with `get` or the `Index` notation + /// with a `usize`. + /// + /// The `0`th capture group is always unnamed, so it must always be + /// accessed with `get(0)` or `[0]`. + pub fn captures<'t>(&self, text: &'t [u8]) -> Option<Captures<'t>> { + let mut locs = self.locations(); + self.read_captures_at(&mut locs, text, 0).map(|_| Captures { + text: text, + locs: locs, + named_groups: self.0.capture_name_idx().clone(), + }) + } + + /// Returns an iterator over all the non-overlapping capture groups matched + /// in `text`. This is operationally the same as `find_iter`, except it + /// yields information about capturing group matches. + /// + /// # Example + /// + /// We can use this to find all movie titles and their release years in + /// some text, where the movie is formatted like "'Title' (xxxx)": + /// + /// ```rust + /// # extern crate regex; use std::str; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; + /// for caps in re.captures_iter(text) { + /// let title = str::from_utf8(&caps["title"]).unwrap(); + /// let year = str::from_utf8(&caps["year"]).unwrap(); + /// println!("Movie: {:?}, Released: {:?}", title, year); + /// } + /// // Output: + /// // Movie: Citizen Kane, Released: 1941 + /// // Movie: The Wizard of Oz, Released: 1939 + /// // Movie: M, Released: 1931 + /// # } + /// ``` + pub fn captures_iter<'r, 't>( + &'r self, + text: &'t [u8], + ) -> CaptureMatches<'r, 't> { + CaptureMatches(self.0.searcher().captures_iter(text)) + } + + /// Returns an iterator of substrings of `text` delimited by a match of the + /// regular expression. Namely, each element of the iterator corresponds to + /// text that *isn't* matched by the regular expression. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// To split a string delimited by arbitrary amounts of spaces or tabs: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"[ \t]+").unwrap(); + /// let fields: Vec<&[u8]> = re.split(b"a b \t c\td e").collect(); + /// assert_eq!(fields, vec![ + /// &b"a"[..], &b"b"[..], &b"c"[..], &b"d"[..], &b"e"[..], + /// ]); + /// # } + /// ``` + pub fn split<'r, 't>(&'r self, text: &'t [u8]) -> Split<'r, 't> { + Split { + finder: self.find_iter(text), + last: 0, + } + } + + /// Returns an iterator of at most `limit` substrings of `text` delimited + /// by a match of the regular expression. (A `limit` of `0` will return no + /// substrings.) Namely, each element of the iterator corresponds to text + /// that *isn't* matched by the regular expression. The remainder of the + /// string that is not split will be the last element in the iterator. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// Get the first two words in some text: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"\W+").unwrap(); + /// let fields: Vec<&[u8]> = re.splitn(b"Hey! How are you?", 3).collect(); + /// assert_eq!(fields, vec![&b"Hey"[..], &b"How"[..], &b"are you?"[..]]); + /// # } + /// ``` + pub fn splitn<'r, 't>( + &'r self, + text: &'t [u8], + limit: usize, + ) -> SplitN<'r, 't> { + SplitN { + splits: self.split(text), + n: limit, + } + } + + /// Replaces the leftmost-first match with the replacement provided. The + /// replacement can be a regular byte string (where `$N` and `$name` are + /// expanded to match capture groups) or a function that takes the matches' + /// `Captures` and returns the replaced byte string. + /// + /// If no match is found, then a copy of the byte string is returned + /// unchanged. + /// + /// # Replacement string syntax + /// + /// All instances of `$name` in the replacement text is replaced with the + /// corresponding capture group `name`. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + /// + /// # Examples + /// + /// Note that this function is polymorphic with respect to the replacement. + /// In typical usage, this can just be a normal byte string: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new("[^01]+").unwrap(); + /// assert_eq!(re.replace(b"1078910", &b""[..]), &b"1010"[..]); + /// # } + /// ``` + /// + /// But anything satisfying the `Replacer` trait will work. For example, a + /// closure of type `|&Captures| -> Vec<u8>` provides direct access to the + /// captures corresponding to a match. This allows one to access capturing + /// group matches easily: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # use regex::bytes::Captures; fn main() { + /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace(b"Springsteen, Bruce", |caps: &Captures| { + /// let mut replacement = caps[2].to_owned(); + /// replacement.push(b' '); + /// replacement.extend(&caps[1]); + /// replacement + /// }); + /// assert_eq!(result, &b"Bruce Springsteen"[..]); + /// # } + /// ``` + /// + /// But this is a bit cumbersome to use all the time. Instead, a simple + /// syntax is supported that expands `$name` into the corresponding capture + /// group. Here's the last example, but using this expansion technique + /// with named capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); + /// let result = re.replace(b"Springsteen, Bruce", &b"$first $last"[..]); + /// assert_eq!(result, &b"Bruce Springsteen"[..]); + /// # } + /// ``` + /// + /// Note that using `$2` instead of `$first` or `$1` instead of `$last` + /// would produce the same result. To write a literal `$` use `$$`. + /// + /// Sometimes the replacement string requires use of curly braces to + /// delineate a capture group replacement and surrounding literal text. + /// For example, if we wanted to join two words together with an + /// underscore: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); + /// let result = re.replace(b"deep fried", &b"${first}_$second"[..]); + /// assert_eq!(result, &b"deep_fried"[..]); + /// # } + /// ``` + /// + /// Without the curly braces, the capture group name `first_` would be + /// used, and since it doesn't exist, it would be replaced with the empty + /// string. + /// + /// Finally, sometimes you just want to replace a literal string with no + /// regard for capturing group expansion. This can be done by wrapping a + /// byte string with `NoExpand`: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// use regex::bytes::NoExpand; + /// + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace(b"Springsteen, Bruce", NoExpand(b"$2 $last")); + /// assert_eq!(result, &b"$2 $last"[..]); + /// # } + /// ``` + pub fn replace<'t, R: Replacer>( + &self, + text: &'t [u8], + rep: R, + ) -> Cow<'t, [u8]> { + self.replacen(text, 1, rep) + } + + /// Replaces all non-overlapping matches in `text` with the replacement + /// provided. This is the same as calling `replacen` with `limit` set to + /// `0`. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement text. + pub fn replace_all<'t, R: Replacer>( + &self, + text: &'t [u8], + rep: R, + ) -> Cow<'t, [u8]> { + self.replacen(text, 0, rep) + } + + /// Replaces at most `limit` non-overlapping matches in `text` with the + /// replacement provided. If `limit` is 0, then all non-overlapping matches + /// are replaced. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement text. + pub fn replacen<'t, R: Replacer>( + &self, + text: &'t [u8], + limit: usize, + mut rep: R, + ) -> Cow<'t, [u8]> { + if let Some(rep) = rep.no_expansion() { + let mut it = self.find_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = Vec::with_capacity(text.len()); + let mut last_match = 0; + for (i, m) in it { + if limit > 0 && i >= limit { + break + } + new.extend_from_slice(&text[last_match..m.start()]); + new.extend_from_slice(&rep); + last_match = m.end(); + } + new.extend_from_slice(&text[last_match..]); + return Cow::Owned(new); + } + + // The slower path, which we use if the replacement needs access to + // capture groups. + let mut it = self.captures_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = Vec::with_capacity(text.len()); + let mut last_match = 0; + for (i, cap) in it { + if limit > 0 && i >= limit { + break + } + // unwrap on 0 is OK because captures only reports matches + let m = cap.get(0).unwrap(); + new.extend_from_slice(&text[last_match..m.start()]); + rep.replace_append(&cap, &mut new); + last_match = m.end(); + } + new.extend_from_slice(&text[last_match..]); + Cow::Owned(new) + } +} + +/// Advanced or "lower level" search methods. +impl Regex { + /// Returns the end location of a match in the text given. + /// + /// This method may have the same performance characteristics as + /// `is_match`, except it provides an end location for a match. In + /// particular, the location returned *may be shorter* than the proper end + /// of the leftmost-first match. + /// + /// # Example + /// + /// Typically, `a+` would match the entire first sequence of `a` in some + /// text, but `shortest_match` can give up as soon as it sees the first + /// `a`. + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"aaaaa"; + /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); + /// assert_eq!(pos, Some(1)); + /// # } + /// ``` + pub fn shortest_match(&self, text: &[u8]) -> Option<usize> { + self.shortest_match_at(text, 0) + } + + /// Returns the same as shortest_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn shortest_match_at( + &self, + text: &[u8], + start: usize, + ) -> Option<usize> { + self.0.searcher().shortest_match_at(text, start) + } + + /// Returns the same as is_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn is_match_at(&self, text: &[u8], start: usize) -> bool { + self.shortest_match_at(text, start).is_some() + } + + /// Returns the same as find, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn find_at<'t>( + &self, + text: &'t [u8], + start: usize, + ) -> Option<Match<'t>> { + self.0.searcher().find_at(text, start) + .map(|(s, e)| Match::new(text, s, e)) + } + + /// Returns the same as captures, but starts the search at the given + /// offset and populates the capture locations given. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn read_captures_at<'t>( + &self, + locs: &mut Locations, + text: &'t [u8], + start: usize, + ) -> Option<Match<'t>> { + self.0.searcher().read_captures_at(locs, text, start) + .map(|(s, e)| Match::new(text, s, e)) + } +} + +/// Auxiliary methods. +impl Regex { + /// Returns the original string of this regex. + pub fn as_str(&self) -> &str { + &self.0.regex_strings()[0] + } + + /// Returns an iterator over the capture names. + pub fn capture_names(&self) -> CaptureNames { + CaptureNames(self.0.capture_names().iter()) + } + + /// Returns the number of captures. + pub fn captures_len(&self) -> usize { + self.0.capture_names().len() + } + + /// Returns an empty set of locations that can be reused in multiple calls + /// to `read_captures`. + #[doc(hidden)] + pub fn locations(&self) -> Locations { + self.0.searcher().locations() + } +} + +/// An iterator over all non-overlapping matches for a particular string. +/// +/// The iterator yields a tuple of integers corresponding to the start and end +/// of the match. The indices are byte offsets. The iterator stops when no more +/// matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched byte string. +pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSync<'r>>); + +impl<'r, 't> Iterator for Matches<'r, 't> { + type Item = Match<'t>; + + fn next(&mut self) -> Option<Match<'t>> { + let text = self.0.text(); + self.0.next().map(|(s, e)| Match::new(text, s, e)) + } +} + +/// An iterator that yields all non-overlapping capture groups matching a +/// particular regular expression. +/// +/// The iterator stops when no more matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched byte string. +pub struct CaptureMatches<'r, 't>(re_trait::CaptureMatches<'t, ExecNoSync<'r>>); + +impl<'r, 't> Iterator for CaptureMatches<'r, 't> { + type Item = Captures<'t>; + + fn next(&mut self) -> Option<Captures<'t>> { + self.0.next().map(|locs| Captures { + text: self.0.text(), + locs: locs, + named_groups: self.0.regex().capture_name_idx().clone(), + }) + } +} + +/// Yields all substrings delimited by a regular expression match. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the byte string being split. +pub struct Split<'r, 't> { + finder: Matches<'r, 't>, + last: usize, +} + +impl<'r, 't> Iterator for Split<'r, 't> { + type Item = &'t [u8]; + + fn next(&mut self) -> Option<&'t [u8]> { + let text = self.finder.0.text(); + match self.finder.next() { + None => { + if self.last >= text.len() { + None + } else { + let s = &text[self.last..]; + self.last = text.len(); + Some(s) + } + } + Some(m) => { + let matched = &text[self.last..m.start()]; + self.last = m.end(); + Some(matched) + } + } + } +} + +/// Yields at most `N` substrings delimited by a regular expression match. +/// +/// The last substring will be whatever remains after splitting. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the byte string being split. +pub struct SplitN<'r, 't> { + splits: Split<'r, 't>, + n: usize, +} + +impl<'r, 't> Iterator for SplitN<'r, 't> { + type Item = &'t [u8]; + + fn next(&mut self) -> Option<&'t [u8]> { + if self.n == 0 { + return None + } + self.n -= 1; + if self.n == 0 { + let text = self.splits.finder.0.text(); + Some(&text[self.splits.last..]) + } else { + self.splits.next() + } + } +} + +/// An iterator over the names of all possible captures. +/// +/// `None` indicates an unnamed capture; the first element (capture 0, the +/// whole matched region) is always unnamed. +/// +/// `'r` is the lifetime of the compiled regular expression. +pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); + +impl<'r> Iterator for CaptureNames<'r> { + type Item = Option<&'r str>; + + fn next(&mut self) -> Option<Option<&'r str>> { + self.0.next().as_ref() + .map(|slot| slot.as_ref().map(|name| name.as_ref())) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.0.size_hint() + } +} + +/// Captures represents a group of captured byte strings for a single match. +/// +/// The 0th capture always corresponds to the entire match. Each subsequent +/// index corresponds to the next capture group in the regex. If a capture +/// group is named, then the matched byte string is *also* available via the +/// `name` method. (Note that the 0th capture is always unnamed and so must be +/// accessed with the `get` method.) +/// +/// Positions returned from a capture group are always byte indices. +/// +/// `'t` is the lifetime of the matched text. +pub struct Captures<'t> { + text: &'t [u8], + locs: Locations, + named_groups: Arc<HashMap<String, usize>>, +} + +impl<'t> Captures<'t> { + /// Returns the match associated with the capture group at index `i`. If + /// `i` does not correspond to a capture group, or if the capture group + /// did not participate in the match, then `None` is returned. + /// + /// # Examples + /// + /// Get the text of the match with a default of an empty string if this + /// group didn't participate in the match: + /// + /// ```rust + /// # use regex::bytes::Regex; + /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); + /// let caps = re.captures(b"abc123").unwrap(); + /// + /// let text1 = caps.get(1).map_or(&b""[..], |m| m.as_bytes()); + /// let text2 = caps.get(2).map_or(&b""[..], |m| m.as_bytes()); + /// assert_eq!(text1, &b"123"[..]); + /// assert_eq!(text2, &b""[..]); + /// ``` + pub fn get(&self, i: usize) -> Option<Match<'t>> { + self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) + } + + /// Returns the match for the capture group named `name`. If `name` isn't a + /// valid capture group or didn't match anything, then `None` is returned. + pub fn name(&self, name: &str) -> Option<Match<'t>> { + self.named_groups.get(name).and_then(|&i| self.get(i)) + } + + /// An iterator that yields all capturing matches in the order in which + /// they appear in the regex. If a particular capture group didn't + /// participate in the match, then `None` is yielded for that capture. + /// + /// The first match always corresponds to the overall match of the regex. + pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { + SubCaptureMatches { + caps: self, + it: self.locs.iter(), + } + } + + /// Expands all instances of `$name` in `replacement` to the corresponding + /// capture group `name`, and writes them to the `dst` buffer given. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + pub fn expand(&self, replacement: &[u8], dst: &mut Vec<u8>) { + expand_bytes(self, replacement, dst) + } + + /// Returns the number of captured groups. + /// + /// This is always at least `1`, since every regex has at least one capture + /// group that corresponds to the full match. + #[inline] + pub fn len(&self) -> usize { + self.locs.len() + } +} + +impl<'t> fmt::Debug for Captures<'t> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() + } +} + +struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>); + +impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn escape_bytes(bytes: &[u8]) -> String { + let mut s = String::new(); + for &b in bytes { + s.push_str(&escape_byte(b)); + } + s + } + + fn escape_byte(byte: u8) -> String { + use std::ascii::escape_default; + + let escaped: Vec<u8> = escape_default(byte).collect(); + String::from_utf8_lossy(&escaped).into_owned() + } + + // We'd like to show something nice here, even if it means an + // allocation to build a reverse index. + let slot_to_name: HashMap<&usize, &String> = + self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); + let mut map = f.debug_map(); + for (slot, m) in self.0.locs.iter().enumerate() { + let m = m.map(|(s, e)| escape_bytes(&self.0.text[s..e])); + if let Some(name) = slot_to_name.get(&slot) { + map.entry(&name, &m); + } else { + map.entry(&slot, &m); + } + } + map.finish() + } +} + +/// Get a group by index. +/// +/// `'t` is the lifetime of the matched text. +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `get()` instead. +/// +/// # Panics +/// +/// If there is no group at the given index. +impl<'t> Index<usize> for Captures<'t> { + type Output = [u8]; + + fn index(&self, i: usize) -> &[u8] { + self.get(i).map(|m| m.as_bytes()) + .unwrap_or_else(|| panic!("no group at index '{}'", i)) + } +} + +/// Get a group by name. +/// +/// `'t` is the lifetime of the matched text and `'i` is the lifetime +/// of the group name (the index). +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `name` instead. +/// +/// # Panics +/// +/// If there is no group named by the given value. +impl<'t, 'i> Index<&'i str> for Captures<'t> { + type Output = [u8]; + + fn index<'a>(&'a self, name: &'i str) -> &'a [u8] { + self.name(name).map(|m| m.as_bytes()) + .unwrap_or_else(|| panic!("no group named '{}'", name)) + } +} + +/// An iterator that yields all capturing matches in the order in which they +/// appear in the regex. +/// +/// If a particular capture group didn't participate in the match, then `None` +/// is yielded for that capture. The first match always corresponds to the +/// overall match of the regex. +/// +/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and +/// the lifetime `'t` corresponds to the originally matched text. +pub struct SubCaptureMatches<'c, 't: 'c> { + caps: &'c Captures<'t>, + it: SubCapturesPosIter<'c>, +} + +impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { + type Item = Option<Match<'t>>; + + fn next(&mut self) -> Option<Option<Match<'t>>> { + self.it.next() + .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) + } +} + +/// Replacer describes types that can be used to replace matches in a byte +/// string. +/// +/// In general, users of this crate shouldn't need to implement this trait, +/// since implementations are already provided for `&[u8]` and +/// `FnMut(&Captures) -> Vec<u8>`, which covers most use cases. +pub trait Replacer { + /// Appends text to `dst` to replace the current match. + /// + /// The current match is represented by `caps`, which is guaranteed to + /// have a match at capture group `0`. + /// + /// For example, a no-op replacement would be + /// `dst.extend(&caps[0])`. + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>); + + /// Return a fixed unchanging replacement byte string. + /// + /// When doing replacements, if access to `Captures` is not needed (e.g., + /// the replacement byte string does not need `$` expansion), then it can + /// be beneficial to avoid finding sub-captures. + /// + /// In general, this is called once for every call to `replacen`. + fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> { + None + } + + /// Return a `Replacer` that borrows and wraps this `Replacer`. + /// + /// This is useful when you want to take a generic `Replacer` (which might + /// not be cloneable) and use it without consuming it, so it can be used + /// more than once. + /// + /// # Example + /// + /// ``` + /// use regex::bytes::{Regex, Replacer}; + /// + /// fn replace_all_twice<R: Replacer>( + /// re: Regex, + /// src: &[u8], + /// mut rep: R, + /// ) -> Vec<u8> { + /// let dst = re.replace_all(src, rep.by_ref()); + /// let dst = re.replace_all(&dst, rep.by_ref()); + /// dst.into_owned() + /// } + /// ``` + fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> { + ReplacerRef(self) + } +} + +/// By-reference adaptor for a `Replacer` +/// +/// Returned by [`Replacer::by_ref`](trait.Replacer.html#method.by_ref). +#[derive(Debug)] +pub struct ReplacerRef<'a, R: ?Sized + 'a>(&'a mut R); + +impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> { + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { + self.0.replace_append(caps, dst) + } + fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> { + self.0.no_expansion() + } +} + +impl<'a> Replacer for &'a [u8] { + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { + caps.expand(*self, dst); + } + + fn no_expansion(&mut self) -> Option<Cow<[u8]>> { + match memchr(b'$', *self) { + Some(_) => None, + None => Some(Cow::Borrowed(*self)), + } + } +} + +impl<F> Replacer for F where F: FnMut(&Captures) -> Vec<u8> { + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { + dst.extend_from_slice(&(*self)(caps)); + } +} + +/// `NoExpand` indicates literal byte string replacement. +/// +/// It can be used with `replace` and `replace_all` to do a literal byte string +/// replacement without expanding `$name` to their corresponding capture +/// groups. This can be both convenient (to avoid escaping `$`, for example) +/// and performant (since capture groups don't need to be found). +/// +/// `'t` is the lifetime of the literal text. +pub struct NoExpand<'t>(pub &'t [u8]); + +impl<'t> Replacer for NoExpand<'t> { + fn replace_append(&mut self, _: &Captures, dst: &mut Vec<u8>) { + dst.extend_from_slice(self.0); + } + + fn no_expansion(&mut self) -> Option<Cow<[u8]>> { + Some(Cow::Borrowed(self.0)) + } +} diff --git a/bash-5.1/vendor/regex/src/re_set.rs b/bash-5.1/vendor/regex/src/re_set.rs new file mode 100644 index 0000000..66b0151 --- /dev/null +++ b/bash-5.1/vendor/regex/src/re_set.rs @@ -0,0 +1,423 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +macro_rules! define_set { + ($name:ident, $builder_mod:ident, $text_ty:ty, $as_bytes:expr, + $(#[$doc_regexset_example:meta])* ) => { + pub mod $name { + use std::fmt; + use std::iter; + use std::slice; + use std::vec; + + use error::Error; + use exec::Exec; + use re_builder::$builder_mod::RegexSetBuilder; + use re_trait::RegularExpression; + +/// Match multiple (possibly overlapping) regular expressions in a single scan. +/// +/// A regex set corresponds to the union of two or more regular expressions. +/// That is, a regex set will match text where at least one of its +/// constituent regular expressions matches. A regex set as its formulated here +/// provides a touch more power: it will also report *which* regular +/// expressions in the set match. Indeed, this is the key difference between +/// regex sets and a single `Regex` with many alternates, since only one +/// alternate can match at a time. +/// +/// For example, consider regular expressions to match email addresses and +/// domains: `[a-z]+@[a-z]+\.(com|org|net)` and `[a-z]+\.(com|org|net)`. If a +/// regex set is constructed from those regexes, then searching the text +/// `foo@example.com` will report both regexes as matching. Of course, one +/// could accomplish this by compiling each regex on its own and doing two +/// searches over the text. The key advantage of using a regex set is that it +/// will report the matching regexes using a *single pass through the text*. +/// If one has hundreds or thousands of regexes to match repeatedly (like a URL +/// router for a complex web application or a user agent matcher), then a regex +/// set can realize huge performance gains. +/// +/// # Example +/// +/// This shows how the above two regexes (for matching email addresses and +/// domains) might work: +/// +$(#[$doc_regexset_example])* +/// +/// Note that it would be possible to adapt the above example to using `Regex` +/// with an expression like: +/// +/// ```ignore +/// (?P<email>[a-z]+@(?P<email_domain>[a-z]+[.](com|org|net)))|(?P<domain>[a-z]+[.](com|org|net)) +/// ``` +/// +/// After a match, one could then inspect the capture groups to figure out +/// which alternates matched. The problem is that it is hard to make this +/// approach scale when there are many regexes since the overlap between each +/// alternate isn't always obvious to reason about. +/// +/// # Limitations +/// +/// Regex sets are limited to answering the following two questions: +/// +/// 1. Does any regex in the set match? +/// 2. If so, which regexes in the set match? +/// +/// As with the main `Regex` type, it is cheaper to ask (1) instead of (2) +/// since the matching engines can stop after the first match is found. +/// +/// Other features like finding the location of successive matches or their +/// sub-captures aren't supported. If you need this functionality, the +/// recommended approach is to compile each regex in the set independently and +/// selectively match them based on which regexes in the set matched. +/// +/// # Performance +/// +/// A `RegexSet` has the same performance characteristics as `Regex`. Namely, +/// search takes `O(mn)` time, where `m` is proportional to the size of the +/// regex set and `n` is proportional to the length of the search text. +#[derive(Clone)] +pub struct RegexSet(Exec); + +impl RegexSet { + /// Create a new regex set with the given regular expressions. + /// + /// This takes an iterator of `S`, where `S` is something that can produce + /// a `&str`. If any of the strings in the iterator are not valid regular + /// expressions, then an error is returned. + /// + /// # Example + /// + /// Create a new regex set from an iterator of strings: + /// + /// ```rust + /// # use regex::RegexSet; + /// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap(); + /// assert!(set.is_match("foo")); + /// ``` + pub fn new<I, S>(exprs: I) -> Result<RegexSet, Error> + where S: AsRef<str>, I: IntoIterator<Item=S> { + RegexSetBuilder::new(exprs).build() + } + + /// Returns true if and only if one of the regexes in this set matches + /// the text given. + /// + /// This method should be preferred if you only need to test whether any + /// of the regexes in the set should match, but don't care about *which* + /// regexes matched. This is because the underlying matching engine will + /// quit immediately after seeing the first match instead of continuing to + /// find all matches. + /// + /// Note that as with searches using `Regex`, the expression is unanchored + /// by default. That is, if the regex does not start with `^` or `\A`, or + /// end with `$` or `\z`, then it is permitted to match anywhere in the + /// text. + /// + /// # Example + /// + /// Tests whether a set matches some text: + /// + /// ```rust + /// # use regex::RegexSet; + /// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap(); + /// assert!(set.is_match("foo")); + /// assert!(!set.is_match("☃")); + /// ``` + pub fn is_match(&self, text: $text_ty) -> bool { + self.is_match_at(text, 0) + } + + /// Returns the same as is_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn is_match_at(&self, text: $text_ty, start: usize) -> bool { + self.0.searcher().is_match_at($as_bytes(text), start) + } + + /// Returns the set of regular expressions that match in the given text. + /// + /// The set returned contains the index of each regular expression that + /// matches in the given text. The index is in correspondence with the + /// order of regular expressions given to `RegexSet`'s constructor. + /// + /// The set can also be used to iterate over the matched indices. + /// + /// Note that as with searches using `Regex`, the expression is unanchored + /// by default. That is, if the regex does not start with `^` or `\A`, or + /// end with `$` or `\z`, then it is permitted to match anywhere in the + /// text. + /// + /// # Example + /// + /// Tests which regular expressions match the given text: + /// + /// ```rust + /// # use regex::RegexSet; + /// let set = RegexSet::new(&[ + /// r"\w+", + /// r"\d+", + /// r"\pL+", + /// r"foo", + /// r"bar", + /// r"barfoo", + /// r"foobar", + /// ]).unwrap(); + /// let matches: Vec<_> = set.matches("foobar").into_iter().collect(); + /// assert_eq!(matches, vec![0, 2, 3, 4, 6]); + /// + /// // You can also test whether a particular regex matched: + /// let matches = set.matches("foobar"); + /// assert!(!matches.matched(5)); + /// assert!(matches.matched(6)); + /// ``` + pub fn matches(&self, text: $text_ty) -> SetMatches { + let mut matches = vec![false; self.0.regex_strings().len()]; + let any = self.read_matches_at(&mut matches, text, 0); + SetMatches { + matched_any: any, + matches: matches, + } + } + + /// Returns the same as matches, but starts the search at the given + /// offset and stores the matches into the slice given. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + /// + /// `matches` must have a length that is at least the number of regexes + /// in this set. + /// + /// This method returns true if and only if at least one member of + /// `matches` is true after executing the set against `text`. + #[doc(hidden)] + pub fn read_matches_at( + &self, + matches: &mut [bool], + text: $text_ty, + start: usize, + ) -> bool { + self.0.searcher().many_matches_at(matches, $as_bytes(text), start) + } + + /// Returns the total number of regular expressions in this set. + pub fn len(&self) -> usize { + self.0.regex_strings().len() + } +} + +/// A set of matches returned by a regex set. +#[derive(Clone, Debug)] +pub struct SetMatches { + matched_any: bool, + matches: Vec<bool>, +} + +impl SetMatches { + /// Whether this set contains any matches. + pub fn matched_any(&self) -> bool { + self.matched_any + } + + /// Whether the regex at the given index matched. + /// + /// The index for a regex is determined by its insertion order upon the + /// initial construction of a `RegexSet`, starting at `0`. + /// + /// # Panics + /// + /// If `regex_index` is greater than or equal to `self.len()`. + pub fn matched(&self, regex_index: usize) -> bool { + self.matches[regex_index] + } + + /// The total number of regexes in the set that created these matches. + pub fn len(&self) -> usize { + self.matches.len() + } + + /// Returns an iterator over indexes in the regex that matched. + /// + /// This will always produces matches in ascending order of index, where + /// the index corresponds to the index of the regex that matched with + /// respect to its position when initially building the set. + pub fn iter(&self) -> SetMatchesIter { + SetMatchesIter((&*self.matches).into_iter().enumerate()) + } +} + +impl IntoIterator for SetMatches { + type IntoIter = SetMatchesIntoIter; + type Item = usize; + + fn into_iter(self) -> Self::IntoIter { + SetMatchesIntoIter(self.matches.into_iter().enumerate()) + } +} + +impl<'a> IntoIterator for &'a SetMatches { + type IntoIter = SetMatchesIter<'a>; + type Item = usize; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// An owned iterator over the set of matches from a regex set. +/// +/// This will always produces matches in ascending order of index, where the +/// index corresponds to the index of the regex that matched with respect to +/// its position when initially building the set. +pub struct SetMatchesIntoIter(iter::Enumerate<vec::IntoIter<bool>>); + +impl Iterator for SetMatchesIntoIter { + type Item = usize; + + fn next(&mut self) -> Option<usize> { + loop { + match self.0.next() { + None => return None, + Some((_, false)) => {} + Some((i, true)) => return Some(i), + } + } + } +} + +impl DoubleEndedIterator for SetMatchesIntoIter { + fn next_back(&mut self) -> Option<usize> { + loop { + match self.0.next_back() { + None => return None, + Some((_, false)) => {} + Some((i, true)) => return Some(i), + } + } + } +} + +/// A borrowed iterator over the set of matches from a regex set. +/// +/// The lifetime `'a` refers to the lifetime of a `SetMatches` value. +/// +/// This will always produces matches in ascending order of index, where the +/// index corresponds to the index of the regex that matched with respect to +/// its position when initially building the set. +#[derive(Clone)] +pub struct SetMatchesIter<'a>(iter::Enumerate<slice::Iter<'a, bool>>); + +impl<'a> Iterator for SetMatchesIter<'a> { + type Item = usize; + + fn next(&mut self) -> Option<usize> { + loop { + match self.0.next() { + None => return None, + Some((_, &false)) => {} + Some((i, &true)) => return Some(i), + } + } + } +} + +impl<'a> DoubleEndedIterator for SetMatchesIter<'a> { + fn next_back(&mut self) -> Option<usize> { + loop { + match self.0.next_back() { + None => return None, + Some((_, &false)) => {} + Some((i, &true)) => return Some(i), + } + } + } +} + +#[doc(hidden)] +impl From<Exec> for RegexSet { + fn from(exec: Exec) -> Self { + RegexSet(exec) + } +} + +impl fmt::Debug for RegexSet { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "RegexSet({:?})", self.0.regex_strings()) + } +} + +#[allow(dead_code)] fn as_bytes_str(text: &str) -> &[u8] { text.as_bytes() } +#[allow(dead_code)] fn as_bytes_bytes(text: &[u8]) -> &[u8] { text } + } + } +} + +define_set! { + unicode, + set_unicode, + &str, + as_bytes_str, +/// ```rust +/// # use regex::RegexSet; +/// let set = RegexSet::new(&[ +/// r"[a-z]+@[a-z]+\.(com|org|net)", +/// r"[a-z]+\.(com|org|net)", +/// ]).unwrap(); +/// +/// // Ask whether any regexes in the set match. +/// assert!(set.is_match("foo@example.com")); +/// +/// // Identify which regexes in the set match. +/// let matches: Vec<_> = set.matches("foo@example.com").into_iter().collect(); +/// assert_eq!(vec![0, 1], matches); +/// +/// // Try again, but with text that only matches one of the regexes. +/// let matches: Vec<_> = set.matches("example.com").into_iter().collect(); +/// assert_eq!(vec![1], matches); +/// +/// // Try again, but with text that doesn't match any regex in the set. +/// let matches: Vec<_> = set.matches("example").into_iter().collect(); +/// assert!(matches.is_empty()); +/// ``` +} + +define_set! { + bytes, + set_bytes, + &[u8], + as_bytes_bytes, +/// ```rust +/// # use regex::bytes::RegexSet; +/// let set = RegexSet::new(&[ +/// r"[a-z]+@[a-z]+\.(com|org|net)", +/// r"[a-z]+\.(com|org|net)", +/// ]).unwrap(); +/// +/// // Ask whether any regexes in the set match. +/// assert!(set.is_match(b"foo@example.com")); +/// +/// // Identify which regexes in the set match. +/// let matches: Vec<_> = set.matches(b"foo@example.com").into_iter().collect(); +/// assert_eq!(vec![0, 1], matches); +/// +/// // Try again, but with text that only matches one of the regexes. +/// let matches: Vec<_> = set.matches(b"example.com").into_iter().collect(); +/// assert_eq!(vec![1], matches); +/// +/// // Try again, but with text that doesn't match any regex in the set. +/// let matches: Vec<_> = set.matches(b"example").into_iter().collect(); +/// assert!(matches.is_empty()); +/// ``` +} diff --git a/bash-5.1/vendor/regex/src/re_trait.rs b/bash-5.1/vendor/regex/src/re_trait.rs new file mode 100644 index 0000000..de674bd --- /dev/null +++ b/bash-5.1/vendor/regex/src/re_trait.rs @@ -0,0 +1,268 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// Slot is a single saved capture location. Note that there are two slots for +/// every capture in a regular expression (one slot each for the start and end +/// of the capture). +pub type Slot = Option<usize>; + +/// Locations represents the offsets of each capturing group in a regex for +/// a single match. +/// +/// Unlike `Captures`, a `Locations` value only stores offsets. +#[doc(hidden)] +pub struct Locations(Vec<Slot>); + +impl Locations { + /// Returns the start and end positions of the Nth capture group. Returns + /// `None` if `i` is not a valid capture group or if the capture group did + /// not match anything. The positions returned are *always* byte indices + /// with respect to the original string matched. + pub fn pos(&self, i: usize) -> Option<(usize, usize)> { + let (s, e) = (i * 2, i * 2 + 1); + match (self.0.get(s), self.0.get(e)) { + (Some(&Some(s)), Some(&Some(e))) => Some((s, e)), + _ => None, + } + } + + /// Creates an iterator of all the capture group positions in order of + /// appearance in the regular expression. Positions are byte indices + /// in terms of the original string matched. + pub fn iter(&self) -> SubCapturesPosIter { + SubCapturesPosIter { idx: 0, locs: self } + } + + /// Returns the total number of capturing groups. + /// + /// This is always at least `1` since every regex has at least `1` + /// capturing group that corresponds to the entire match. + pub fn len(&self) -> usize { + self.0.len() / 2 + } +} + +/// This is a hack to make Locations -> &mut [Slot] be available internally +/// without exposing it in the public API. +pub fn as_slots(locs: &mut Locations) -> &mut [Slot] { + &mut locs.0 +} + +/// An iterator over capture group positions for a particular match of a +/// regular expression. +/// +/// Positions are byte indices in terms of the original string matched. +/// +/// `'c` is the lifetime of the captures. +pub struct SubCapturesPosIter<'c> { + idx: usize, + locs: &'c Locations, +} + +impl<'c> Iterator for SubCapturesPosIter<'c> { + type Item = Option<(usize, usize)>; + + fn next(&mut self) -> Option<Option<(usize, usize)>> { + if self.idx >= self.locs.len() { + return None; + } + let x = match self.locs.pos(self.idx) { + None => Some(None), + Some((s, e)) => { + Some(Some((s, e))) + } + }; + self.idx += 1; + x + } +} + +/// `RegularExpression` describes types that can implement regex searching. +/// +/// This trait is my attempt at reducing code duplication and to standardize +/// the internal API. Specific duplication that is avoided are the `find` +/// and `capture` iterators, which are slightly tricky. +/// +/// It's not clear whether this trait is worth it, and it also isn't +/// clear whether it's useful as a public trait or not. Methods like +/// `next_after_empty` reak of bad design, but the rest of the methods seem +/// somewhat reasonable. One particular thing this trait would expose would be +/// the ability to start the search of a regex anywhere in a haystack, which +/// isn't possible in the current public API. +pub trait RegularExpression: Sized { + /// The type of the haystack. + type Text: ?Sized; + + /// The number of capture slots in the compiled regular expression. This is + /// always two times the number of capture groups (two slots per group). + fn slots_len(&self) -> usize; + + /// Allocates fresh space for all capturing groups in this regex. + fn locations(&self) -> Locations { + Locations(vec![None; self.slots_len()]) + } + + /// Returns the position of the next character after `i`. + /// + /// For example, a haystack with type `&[u8]` probably returns `i+1`, + /// whereas a haystack with type `&str` probably returns `i` plus the + /// length of the next UTF-8 sequence. + fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; + + /// Returns the location of the shortest match. + fn shortest_match_at( + &self, + text: &Self::Text, + start: usize, + ) -> Option<usize>; + + /// Returns whether the regex matches the text given. + fn is_match_at( + &self, + text: &Self::Text, + start: usize, + ) -> bool; + + /// Returns the leftmost-first match location if one exists. + fn find_at( + &self, + text: &Self::Text, + start: usize, + ) -> Option<(usize, usize)>; + + /// Returns the leftmost-first match location if one exists, and also + /// fills in any matching capture slot locations. + fn read_captures_at( + &self, + locs: &mut Locations, + text: &Self::Text, + start: usize, + ) -> Option<(usize, usize)>; + + /// Returns an iterator over all non-overlapping successive leftmost-first + /// matches. + fn find_iter ( + self, + text: &Self::Text, + ) -> Matches<Self> { + Matches { + re: self, + text: text, + last_end: 0, + last_match: None, + } + } + + /// Returns an iterator over all non-overlapping successive leftmost-first + /// matches with captures. + fn captures_iter( + self, + text: &Self::Text, + ) -> CaptureMatches<Self> { + CaptureMatches(self.find_iter(text)) + } +} + +/// An iterator over all non-overlapping successive leftmost-first matches. +pub struct Matches<'t, R> where R: RegularExpression, R::Text: 't { + re: R, + text: &'t R::Text, + last_end: usize, + last_match: Option<usize>, +} + +impl<'t, R> Matches<'t, R> where R: RegularExpression, R::Text: 't { + /// Return the text being searched. + pub fn text(&self) -> &'t R::Text { + self.text + } + + /// Return the underlying regex. + pub fn regex(&self) -> &R { + &self.re + } +} + +impl<'t, R> Iterator for Matches<'t, R> + where R: RegularExpression, R::Text: 't + AsRef<[u8]> { + type Item = (usize, usize); + + fn next(&mut self) -> Option<(usize, usize)> { + if self.last_end > self.text.as_ref().len() { + return None; + } + let (s, e) = match self.re.find_at(self.text, self.last_end) { + None => return None, + Some((s, e)) => (s, e), + }; + if s == e { + // This is an empty match. To ensure we make progress, start + // the next search at the smallest possible starting position + // of the next match following this one. + self.last_end = self.re.next_after_empty(self.text, e); + // Don't accept empty matches immediately following a match. + // Just move on to the next match. + if Some(e) == self.last_match { + return self.next(); + } + } else { + self.last_end = e; + } + self.last_match = Some(e); + Some((s, e)) + } +} + +/// An iterator over all non-overlapping successive leftmost-first matches with +/// captures. +pub struct CaptureMatches<'t, R>(Matches<'t, R>) + where R: RegularExpression, R::Text: 't; + +impl<'t, R> CaptureMatches<'t, R> where R: RegularExpression, R::Text: 't { + /// Return the text being searched. + pub fn text(&self) -> &'t R::Text { + self.0.text() + } + + /// Return the underlying regex. + pub fn regex(&self) -> &R { + self.0.regex() + } +} + +impl<'t, R> Iterator for CaptureMatches<'t, R> + where R: RegularExpression, R::Text: 't + AsRef<[u8]> { + type Item = Locations; + + fn next(&mut self) -> Option<Locations> { + if self.0.last_end > self.0.text.as_ref().len() { + return None + } + let mut locs = self.0.re.locations(); + let (s, e) = match self.0.re.read_captures_at( + &mut locs, + self.0.text, + self.0.last_end, + ) { + None => return None, + Some((s, e)) => (s, e), + }; + if s == e { + self.0.last_end = self.0.re.next_after_empty(self.0.text, e); + if Some(e) == self.0.last_match { + return self.next(); + } + } else { + self.0.last_end = e; + } + self.0.last_match = Some(e); + Some(locs) + } +} diff --git a/bash-5.1/vendor/regex/src/re_unicode.rs b/bash-5.1/vendor/regex/src/re_unicode.rs new file mode 100644 index 0000000..fb78e56 --- /dev/null +++ b/bash-5.1/vendor/regex/src/re_unicode.rs @@ -0,0 +1,1116 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt; +use std::ops::Index; +use std::str::FromStr; +use std::sync::Arc; + +use memchr::memchr; +use syntax; + +use error::Error; +use exec::{Exec, ExecNoSyncStr}; +use expand::expand_str; +use re_builder::unicode::RegexBuilder; +use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter}; + +/// Escapes all regular expression meta characters in `text`. +/// +/// The string returned may be safely used as a literal in a regular +/// expression. +pub fn escape(text: &str) -> String { + syntax::escape(text) +} + +/// Match represents a single match of a regex in a haystack. +/// +/// The lifetime parameter `'t` refers to the lifetime of the matched text. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Match<'t> { + text: &'t str, + start: usize, + end: usize, +} + +impl<'t> Match<'t> { + /// Returns the starting byte offset of the match in the haystack. + #[inline] + pub fn start(&self) -> usize { + self.start + } + + /// Returns the ending byte offset of the match in the haystack. + #[inline] + pub fn end(&self) -> usize { + self.end + } + + /// Returns the matched text. + #[inline] + pub fn as_str(&self) -> &'t str { + &self.text[self.start..self.end] + } + + /// Creates a new match from the given haystack and byte offsets. + #[inline] + fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> { + Match { + text: haystack, + start: start, + end: end, + } + } +} + +impl<'t> From<Match<'t>> for &'t str { + fn from(m: Match<'t>) -> &'t str { + m.as_str() + } +} + +/// A compiled regular expression for matching Unicode strings. +/// +/// It is represented as either a sequence of bytecode instructions (dynamic) +/// or as a specialized Rust function (native). It can be used to search, split +/// or replace text. All searching is done with an implicit `.*?` at the +/// beginning and end of an expression. To force an expression to match the +/// whole string (or a prefix or a suffix), you must use an anchor like `^` or +/// `$` (or `\A` and `\z`). +/// +/// While this crate will handle Unicode strings (whether in the regular +/// expression or in the search text), all positions returned are **byte +/// indices**. Every byte index is guaranteed to be at a Unicode code point +/// boundary. +/// +/// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a +/// compiled regular expression and text to search, respectively. +/// +/// The only methods that allocate new strings are the string replacement +/// methods. All other methods (searching and splitting) return borrowed +/// pointers into the string given. +/// +/// # Examples +/// +/// Find the location of a US phone number: +/// +/// ```rust +/// # use regex::Regex; +/// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap(); +/// let mat = re.find("phone: 111-222-3333").unwrap(); +/// assert_eq!((mat.start(), mat.end()), (7, 19)); +/// ``` +/// +/// # Using the `std::str::pattern` methods with `Regex` +/// +/// > **Note**: This section requires that this crate is compiled with the +/// > `pattern` Cargo feature enabled, which **requires nightly Rust**. +/// +/// Since `Regex` implements `Pattern`, you can use regexes with methods +/// defined on `&str`. For example, `is_match`, `find`, `find_iter` +/// and `split` can be replaced with `str::contains`, `str::find`, +/// `str::match_indices` and `str::split`. +/// +/// Here are some examples: +/// +/// ```rust,ignore +/// # use regex::Regex; +/// let re = Regex::new(r"\d+").unwrap(); +/// let haystack = "a111b222c"; +/// +/// assert!(haystack.contains(&re)); +/// assert_eq!(haystack.find(&re), Some(1)); +/// assert_eq!(haystack.match_indices(&re).collect::<Vec<_>>(), +/// vec![(1, 4), (5, 8)]); +/// assert_eq!(haystack.split(&re).collect::<Vec<_>>(), vec!["a", "b", "c"]); +/// ``` +#[derive(Clone)] +pub struct Regex(Exec); + +impl fmt::Display for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.as_str()) + } +} + +impl fmt::Debug for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +#[doc(hidden)] +impl From<Exec> for Regex { + fn from(exec: Exec) -> Regex { + Regex(exec) + } +} + +impl FromStr for Regex { + type Err = Error; + + /// Attempts to parse a string into a regular expression + fn from_str(s: &str) -> Result<Regex, Error> { + Regex::new(s) + } +} + +/// Core regular expression methods. +impl Regex { + /// Compiles a regular expression. Once compiled, it can be used repeatedly + /// to search, split or replace text in a string. + /// + /// If an invalid expression is given, then an error is returned. + pub fn new(re: &str) -> Result<Regex, Error> { + RegexBuilder::new(re).build() + } + + /// Returns true if and only if the regex matches the string given. + /// + /// It is recommended to use this method if all you need to do is test + /// a match, since the underlying matching engine may be able to do less + /// work. + /// + /// # Example + /// + /// Test if some text contains at least one word with exactly 13 + /// Unicode word characters: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "I categorically deny having triskaidekaphobia."; + /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); + /// # } + /// ``` + pub fn is_match(&self, text: &str) -> bool { + self.is_match_at(text, 0) + } + + /// Returns the start and end byte range of the leftmost-first match in + /// `text`. If no match exists, then `None` is returned. + /// + /// Note that this should only be used if you want to discover the position + /// of the match. Testing the existence of a match is faster if you use + /// `is_match`. + /// + /// # Example + /// + /// Find the start and end location of the first word with exactly 13 + /// Unicode word characters: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "I categorically deny having triskaidekaphobia."; + /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); + /// assert_eq!(mat.start(), 2); + /// assert_eq!(mat.end(), 15); + /// # } + /// ``` + pub fn find<'t>(&self, text: &'t str) -> Option<Match<'t>> { + self.find_at(text, 0) + } + + /// Returns an iterator for each successive non-overlapping match in + /// `text`, returning the start and end byte indices with respect to + /// `text`. + /// + /// # Example + /// + /// Find the start and end location of every word with exactly 13 Unicode + /// word characters: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "Retroactively relinquishing remunerations is reprehensible."; + /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { + /// println!("{:?}", mat); + /// } + /// # } + /// ``` + pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> Matches<'r, 't> { + Matches(self.0.searcher_str().find_iter(text)) + } + + /// Returns the capture groups corresponding to the leftmost-first + /// match in `text`. Capture group `0` always corresponds to the entire + /// match. If no match is found, then `None` is returned. + /// + /// You should only use `captures` if you need access to the location of + /// capturing group matches. Otherwise, `find` is faster for discovering + /// the location of the overall match. + /// + /// # Examples + /// + /// Say you have some text with movie names and their release years, + /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text + /// looking like that, while also extracting the movie name and its release + /// year separately. + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); + /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane"); + /// assert_eq!(caps.get(2).unwrap().as_str(), "1941"); + /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); + /// // You can also access the groups by index using the Index notation. + /// // Note that this will panic on an invalid index. + /// assert_eq!(&caps[1], "Citizen Kane"); + /// assert_eq!(&caps[2], "1941"); + /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); + /// # } + /// ``` + /// + /// Note that the full match is at capture group `0`. Each subsequent + /// capture group is indexed by the order of its opening `(`. + /// + /// We can make this example a bit clearer by using *named* capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(&caps["title"], "Citizen Kane"); + /// assert_eq!(&caps["year"], "1941"); + /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); + /// // You can also access the groups by name using the Index notation. + /// // Note that this will panic on an invalid group name. + /// assert_eq!(&caps["title"], "Citizen Kane"); + /// assert_eq!(&caps["year"], "1941"); + /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); + /// + /// # } + /// ``` + /// + /// Here we name the capture groups, which we can access with the `name` + /// method or the `Index` notation with a `&str`. Note that the named + /// capture groups are still accessible with `get` or the `Index` notation + /// with a `usize`. + /// + /// The `0`th capture group is always unnamed, so it must always be + /// accessed with `get(0)` or `[0]`. + pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { + let mut locs = self.locations(); + self.read_captures_at(&mut locs, text, 0).map(|_| Captures { + text: text, + locs: locs, + named_groups: self.0.capture_name_idx().clone(), + }) + } + + /// Returns an iterator over all the non-overlapping capture groups matched + /// in `text`. This is operationally the same as `find_iter`, except it + /// yields information about capturing group matches. + /// + /// # Example + /// + /// We can use this to find all movie titles and their release years in + /// some text, where the movie is formatted like "'Title' (xxxx)": + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; + /// for caps in re.captures_iter(text) { + /// println!("Movie: {:?}, Released: {:?}", + /// &caps["title"], &caps["year"]); + /// } + /// // Output: + /// // Movie: Citizen Kane, Released: 1941 + /// // Movie: The Wizard of Oz, Released: 1939 + /// // Movie: M, Released: 1931 + /// # } + /// ``` + pub fn captures_iter<'r, 't>( + &'r self, + text: &'t str, + ) -> CaptureMatches<'r, 't> { + CaptureMatches(self.0.searcher_str().captures_iter(text)) + } + + /// Returns an iterator of substrings of `text` delimited by a match of the + /// regular expression. Namely, each element of the iterator corresponds to + /// text that *isn't* matched by the regular expression. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// To split a string delimited by arbitrary amounts of spaces or tabs: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"[ \t]+").unwrap(); + /// let fields: Vec<&str> = re.split("a b \t c\td e").collect(); + /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]); + /// # } + /// ``` + pub fn split<'r, 't>(&'r self, text: &'t str) -> Split<'r, 't> { + Split { + finder: self.find_iter(text), + last: 0, + } + } + + /// Returns an iterator of at most `limit` substrings of `text` delimited + /// by a match of the regular expression. (A `limit` of `0` will return no + /// substrings.) Namely, each element of the iterator corresponds to text + /// that *isn't* matched by the regular expression. The remainder of the + /// string that is not split will be the last element in the iterator. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// Get the first two words in some text: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"\W+").unwrap(); + /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect(); + /// assert_eq!(fields, vec!("Hey", "How", "are you?")); + /// # } + /// ``` + pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: usize) + -> SplitN<'r, 't> { + SplitN { + splits: self.split(text), + n: limit, + } + } + + /// Replaces the leftmost-first match with the replacement provided. + /// The replacement can be a regular string (where `$N` and `$name` are + /// expanded to match capture groups) or a function that takes the matches' + /// `Captures` and returns the replaced string. + /// + /// If no match is found, then a copy of the string is returned unchanged. + /// + /// # Replacement string syntax + /// + /// All instances of `$name` in the replacement text is replaced with the + /// corresponding capture group `name`. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + /// + /// # Examples + /// + /// Note that this function is polymorphic with respect to the replacement. + /// In typical usage, this can just be a normal string: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new("[^01]+").unwrap(); + /// assert_eq!(re.replace("1078910", ""), "1010"); + /// # } + /// ``` + /// + /// But anything satisfying the `Replacer` trait will work. For example, + /// a closure of type `|&Captures| -> String` provides direct access to the + /// captures corresponding to a match. This allows one to access + /// capturing group matches easily: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # use regex::Captures; fn main() { + /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| { + /// format!("{} {}", &caps[2], &caps[1]) + /// }); + /// assert_eq!(result, "Bruce Springsteen"); + /// # } + /// ``` + /// + /// But this is a bit cumbersome to use all the time. Instead, a simple + /// syntax is supported that expands `$name` into the corresponding capture + /// group. Here's the last example, but using this expansion technique + /// with named capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); + /// let result = re.replace("Springsteen, Bruce", "$first $last"); + /// assert_eq!(result, "Bruce Springsteen"); + /// # } + /// ``` + /// + /// Note that using `$2` instead of `$first` or `$1` instead of `$last` + /// would produce the same result. To write a literal `$` use `$$`. + /// + /// Sometimes the replacement string requires use of curly braces to + /// delineate a capture group replacement and surrounding literal text. + /// For example, if we wanted to join two words together with an + /// underscore: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); + /// let result = re.replace("deep fried", "${first}_$second"); + /// assert_eq!(result, "deep_fried"); + /// # } + /// ``` + /// + /// Without the curly braces, the capture group name `first_` would be + /// used, and since it doesn't exist, it would be replaced with the empty + /// string. + /// + /// Finally, sometimes you just want to replace a literal string with no + /// regard for capturing group expansion. This can be done by wrapping a + /// byte string with `NoExpand`: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// use regex::NoExpand; + /// + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last")); + /// assert_eq!(result, "$2 $last"); + /// # } + /// ``` + pub fn replace<'t, R: Replacer>( + &self, + text: &'t str, + rep: R, + ) -> Cow<'t, str> { + self.replacen(text, 1, rep) + } + + /// Replaces all non-overlapping matches in `text` with the replacement + /// provided. This is the same as calling `replacen` with `limit` set to + /// `0`. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement string. + pub fn replace_all<'t, R: Replacer>( + &self, + text: &'t str, + rep: R, + ) -> Cow<'t, str> { + self.replacen(text, 0, rep) + } + + /// Replaces at most `limit` non-overlapping matches in `text` with the + /// replacement provided. If `limit` is 0, then all non-overlapping matches + /// are replaced. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement string. + pub fn replacen<'t, R: Replacer>( + &self, + text: &'t str, + limit: usize, + mut rep: R, + ) -> Cow<'t, str> { + // If we know that the replacement doesn't have any capture expansions, + // then we can fast path. The fast path can make a tremendous + // difference: + // + // 1) We use `find_iter` instead of `captures_iter`. Not asking for + // captures generally makes the regex engines faster. + // 2) We don't need to look up all of the capture groups and do + // replacements inside the replacement string. We just push it + // at each match and be done with it. + if let Some(rep) = rep.no_expansion() { + let mut it = self.find_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for (i, m) in it { + if limit > 0 && i >= limit { + break + } + new.push_str(&text[last_match..m.start()]); + new.push_str(&rep); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + return Cow::Owned(new); + } + + // The slower path, which we use if the replacement needs access to + // capture groups. + let mut it = self.captures_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for (i, cap) in it { + if limit > 0 && i >= limit { + break + } + // unwrap on 0 is OK because captures only reports matches + let m = cap.get(0).unwrap(); + new.push_str(&text[last_match..m.start()]); + rep.replace_append(&cap, &mut new); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + Cow::Owned(new) + } +} + +/// Advanced or "lower level" search methods. +impl Regex { + /// Returns the end location of a match in the text given. + /// + /// This method may have the same performance characteristics as + /// `is_match`, except it provides an end location for a match. In + /// particular, the location returned *may be shorter* than the proper end + /// of the leftmost-first match. + /// + /// # Example + /// + /// Typically, `a+` would match the entire first sequence of `a` in some + /// text, but `shortest_match` can give up as soon as it sees the first + /// `a`. + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "aaaaa"; + /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); + /// assert_eq!(pos, Some(1)); + /// # } + /// ``` + pub fn shortest_match(&self, text: &str) -> Option<usize> { + self.shortest_match_at(text, 0) + } + + /// Returns the same as shortest_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn shortest_match_at( + &self, + text: &str, + start: usize, + ) -> Option<usize> { + self.0.searcher_str().shortest_match_at(text, start) + } + + /// Returns the same as is_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn is_match_at(&self, text: &str, start: usize) -> bool { + self.shortest_match_at(text, start).is_some() + } + + /// Returns the same as find, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn find_at<'t>( + &self, + text: &'t str, + start: usize, + ) -> Option<Match<'t>> { + self.0.searcher_str().find_at(text, start).map(|(s, e)| { + Match::new(text, s, e) + }) + } + + /// Returns the same as captures, but starts the search at the given + /// offset and populates the capture locations given. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn read_captures_at<'t>( + &self, + locs: &mut Locations, + text: &'t str, + start: usize, + ) -> Option<Match<'t>> { + self.0 + .searcher_str() + .read_captures_at(locs, text, start) + .map(|(s, e)| Match::new(text, s, e)) + } +} + +/// Auxiliary methods. +impl Regex { + /// Returns the original string of this regex. + pub fn as_str(&self) -> &str { + &self.0.regex_strings()[0] + } + + /// Returns an iterator over the capture names. + pub fn capture_names(&self) -> CaptureNames { + CaptureNames(self.0.capture_names().iter()) + } + + /// Returns the number of captures. + pub fn captures_len(&self) -> usize { + self.0.capture_names().len() + } + + /// Returns an empty set of locations that can be reused in multiple calls + /// to `read_captures`. + #[doc(hidden)] + pub fn locations(&self) -> Locations { + self.0.searcher_str().locations() + } +} + +/// An iterator over the names of all possible captures. +/// +/// `None` indicates an unnamed capture; the first element (capture 0, the +/// whole matched region) is always unnamed. +/// +/// `'r` is the lifetime of the compiled regular expression. +pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); + +impl<'r> Iterator for CaptureNames<'r> { + type Item = Option<&'r str>; + + fn next(&mut self) -> Option<Option<&'r str>> { + self.0 + .next() + .as_ref() + .map(|slot| slot.as_ref().map(|name| name.as_ref())) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.0.size_hint() + } +} + +/// Yields all substrings delimited by a regular expression match. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the string being split. +pub struct Split<'r, 't> { + finder: Matches<'r, 't>, + last: usize, +} + +impl<'r, 't> Iterator for Split<'r, 't> { + type Item = &'t str; + + fn next(&mut self) -> Option<&'t str> { + let text = self.finder.0.text(); + match self.finder.next() { + None => { + if self.last >= text.len() { + None + } else { + let s = &text[self.last..]; + self.last = text.len(); + Some(s) + } + } + Some(m) => { + let matched = &text[self.last..m.start()]; + self.last = m.end(); + Some(matched) + } + } + } +} + +/// Yields at most `N` substrings delimited by a regular expression match. +/// +/// The last substring will be whatever remains after splitting. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the string being split. +pub struct SplitN<'r, 't> { + splits: Split<'r, 't>, + n: usize, +} + +impl<'r, 't> Iterator for SplitN<'r, 't> { + type Item = &'t str; + + fn next(&mut self) -> Option<&'t str> { + if self.n == 0 { + return None + } + self.n -= 1; + if self.n == 0 { + let text = self.splits.finder.0.text(); + Some(&text[self.splits.last..]) + } else { + self.splits.next() + } + } +} + +/// Captures represents a group of captured strings for a single match. +/// +/// The 0th capture always corresponds to the entire match. Each subsequent +/// index corresponds to the next capture group in the regex. If a capture +/// group is named, then the matched string is *also* available via the `name` +/// method. (Note that the 0th capture is always unnamed and so must be +/// accessed with the `get` method.) +/// +/// Positions returned from a capture group are always byte indices. +/// +/// `'t` is the lifetime of the matched text. +pub struct Captures<'t> { + text: &'t str, + locs: Locations, + named_groups: Arc<HashMap<String, usize>>, +} + +impl<'t> Captures<'t> { + /// Returns the match associated with the capture group at index `i`. If + /// `i` does not correspond to a capture group, or if the capture group + /// did not participate in the match, then `None` is returned. + /// + /// # Examples + /// + /// Get the text of the match with a default of an empty string if this + /// group didn't participate in the match: + /// + /// ```rust + /// # use regex::Regex; + /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); + /// let caps = re.captures("abc123").unwrap(); + /// + /// let text1 = caps.get(1).map_or("", |m| m.as_str()); + /// let text2 = caps.get(2).map_or("", |m| m.as_str()); + /// assert_eq!(text1, "123"); + /// assert_eq!(text2, ""); + /// ``` + pub fn get(&self, i: usize) -> Option<Match<'t>> { + self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) + } + + /// Returns the match for the capture group named `name`. If `name` isn't a + /// valid capture group or didn't match anything, then `None` is returned. + pub fn name(&self, name: &str) -> Option<Match<'t>> { + self.named_groups.get(name).and_then(|&i| self.get(i)) + } + + /// An iterator that yields all capturing matches in the order in which + /// they appear in the regex. If a particular capture group didn't + /// participate in the match, then `None` is yielded for that capture. + /// + /// The first match always corresponds to the overall match of the regex. + pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { + SubCaptureMatches { + caps: self, + it: self.locs.iter(), + } + } + + /// Expands all instances of `$name` in `replacement` to the corresponding + /// capture group `name`, and writes them to the `dst` buffer given. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + pub fn expand(&self, replacement: &str, dst: &mut String) { + expand_str(self, replacement, dst) + } + + /// Returns the number of captured groups. + /// + /// This is always at least `1`, since every regex has at least one capture + /// group that corresponds to the full match. + #[inline] + pub fn len(&self) -> usize { + self.locs.len() + } +} + +impl<'t> fmt::Debug for Captures<'t> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() + } +} + +struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>); + +impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // We'd like to show something nice here, even if it means an + // allocation to build a reverse index. + let slot_to_name: HashMap<&usize, &String> = + self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); + let mut map = f.debug_map(); + for (slot, m) in self.0.locs.iter().enumerate() { + let m = m.map(|(s, e)| &self.0.text[s..e]); + if let Some(name) = slot_to_name.get(&slot) { + map.entry(&name, &m); + } else { + map.entry(&slot, &m); + } + } + map.finish() + } +} + +/// Get a group by index. +/// +/// `'t` is the lifetime of the matched text. +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `get()` instead. +/// +/// # Panics +/// +/// If there is no group at the given index. +impl<'t> Index<usize> for Captures<'t> { + type Output = str; + + fn index(&self, i: usize) -> &str { + self.get(i).map(|m| m.as_str()) + .unwrap_or_else(|| panic!("no group at index '{}'", i)) + } +} + +/// Get a group by name. +/// +/// `'t` is the lifetime of the matched text and `'i` is the lifetime +/// of the group name (the index). +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `name` instead. +/// +/// # Panics +/// +/// If there is no group named by the given value. +impl<'t, 'i> Index<&'i str> for Captures<'t> { + type Output = str; + + fn index<'a>(&'a self, name: &'i str) -> &'a str { + self.name(name).map(|m| m.as_str()) + .unwrap_or_else(|| panic!("no group named '{}'", name)) + } +} + +/// An iterator that yields all capturing matches in the order in which they +/// appear in the regex. +/// +/// If a particular capture group didn't participate in the match, then `None` +/// is yielded for that capture. The first match always corresponds to the +/// overall match of the regex. +/// +/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and +/// the lifetime `'t` corresponds to the originally matched text. +pub struct SubCaptureMatches<'c, 't: 'c> { + caps: &'c Captures<'t>, + it: SubCapturesPosIter<'c>, +} + +impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { + type Item = Option<Match<'t>>; + + fn next(&mut self) -> Option<Option<Match<'t>>> { + self.it.next() + .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) + } +} + +/// An iterator that yields all non-overlapping capture groups matching a +/// particular regular expression. +/// +/// The iterator stops when no more matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched string. +pub struct CaptureMatches<'r, 't>(re_trait::CaptureMatches<'t, ExecNoSyncStr<'r>>); + +impl<'r, 't> Iterator for CaptureMatches<'r, 't> { + type Item = Captures<'t>; + + fn next(&mut self) -> Option<Captures<'t>> { + self.0.next().map(|locs| Captures { + text: self.0.text(), + locs: locs, + named_groups: self.0.regex().capture_name_idx().clone(), + }) + } +} + +/// An iterator over all non-overlapping matches for a particular string. +/// +/// The iterator yields a `Match` value. The iterator stops when no more +/// matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched string. +pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSyncStr<'r>>); + +impl<'r, 't> Iterator for Matches<'r, 't> { + type Item = Match<'t>; + + fn next(&mut self) -> Option<Match<'t>> { + let text = self.0.text(); + self.0.next().map(|(s, e)| Match::new(text, s, e)) + } +} + +/// Replacer describes types that can be used to replace matches in a string. +/// +/// In general, users of this crate shouldn't need to implement this trait, +/// since implementations are already provided for `&str` and +/// `FnMut(&Captures) -> String`, which covers most use cases. +pub trait Replacer { + /// Appends text to `dst` to replace the current match. + /// + /// The current match is represented by `caps`, which is guaranteed to + /// have a match at capture group `0`. + /// + /// For example, a no-op replacement would be + /// `dst.extend(caps.get(0).unwrap().as_str())`. + fn replace_append(&mut self, caps: &Captures, dst: &mut String); + + /// Return a fixed unchanging replacement string. + /// + /// When doing replacements, if access to `Captures` is not needed (e.g., + /// the replacement byte string does not need `$` expansion), then it can + /// be beneficial to avoid finding sub-captures. + /// + /// In general, this is called once for every call to `replacen`. + fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> { + None + } + + /// Return a `Replacer` that borrows and wraps this `Replacer`. + /// + /// This is useful when you want to take a generic `Replacer` (which might + /// not be cloneable) and use it without consuming it, so it can be used + /// more than once. + /// + /// # Example + /// + /// ``` + /// use regex::{Regex, Replacer}; + /// + /// fn replace_all_twice<R: Replacer>( + /// re: Regex, + /// src: &str, + /// mut rep: R, + /// ) -> String { + /// let dst = re.replace_all(src, rep.by_ref()); + /// let dst = re.replace_all(&dst, rep.by_ref()); + /// dst.into_owned() + /// } + /// ``` + fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> { + ReplacerRef(self) + } +} + +/// By-reference adaptor for a `Replacer` +/// +/// Returned by [`Replacer::by_ref`](trait.Replacer.html#method.by_ref). +#[derive(Debug)] +pub struct ReplacerRef<'a, R: ?Sized + 'a>(&'a mut R); + +impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> { + fn replace_append(&mut self, caps: &Captures, dst: &mut String) { + self.0.replace_append(caps, dst) + } + fn no_expansion(&mut self) -> Option<Cow<str>> { + self.0.no_expansion() + } +} + +impl<'a> Replacer for &'a str { + fn replace_append(&mut self, caps: &Captures, dst: &mut String) { + caps.expand(*self, dst); + } + + fn no_expansion(&mut self) -> Option<Cow<str>> { + match memchr(b'$', self.as_bytes()) { + Some(_) => None, + None => Some(Cow::Borrowed(*self)), + } + } +} + +impl<F> Replacer for F where F: FnMut(&Captures) -> String { + fn replace_append(&mut self, caps: &Captures, dst: &mut String) { + dst.push_str(&(*self)(caps)); + } +} + +/// `NoExpand` indicates literal string replacement. +/// +/// It can be used with `replace` and `replace_all` to do a literal string +/// replacement without expanding `$name` to their corresponding capture +/// groups. This can be both convenient (to avoid escaping `$`, for example) +/// and performant (since capture groups don't need to be found). +/// +/// `'t` is the lifetime of the literal text. +pub struct NoExpand<'t>(pub &'t str); + +impl<'t> Replacer for NoExpand<'t> { + fn replace_append(&mut self, _: &Captures, dst: &mut String) { + dst.push_str(self.0); + } + + fn no_expansion(&mut self) -> Option<Cow<str>> { + Some(Cow::Borrowed(self.0)) + } +} diff --git a/bash-5.1/vendor/regex/src/sparse.rs b/bash-5.1/vendor/regex/src/sparse.rs new file mode 100644 index 0000000..34c05e7 --- /dev/null +++ b/bash-5.1/vendor/regex/src/sparse.rs @@ -0,0 +1,78 @@ +use std::ops::Deref; +use std::slice; + +/// A sparse set used for representing ordered NFA states. +/// +/// This supports constant time addition and membership testing. Clearing an +/// entire set can also be done in constant time. Iteration yields elements +/// in the order in which they were inserted. +/// +/// The data structure is based on: http://research.swtch.com/sparse +/// Note though that we don't actually use unitialized memory. We generally +/// reuse allocations, so the initial allocation cost is bareable. However, +/// its other properties listed above are extremely useful. +#[derive(Clone, Debug)] +pub struct SparseSet { + /// Dense contains the instruction pointers in the order in which they + /// were inserted. Accessing elements >= self.size is illegal. + dense: Vec<usize>, + /// Sparse maps instruction pointers to their location in dense. + /// + /// An instruction pointer is in the set if and only if + /// sparse[ip] < size && ip == dense[sparse[ip]]. + sparse: Vec<usize>, + /// The number of elements in the set. + size: usize, +} + +impl SparseSet { + pub fn new(size: usize) -> SparseSet { + SparseSet { + dense: vec![0; size], + sparse: vec![0; size], + size: 0, + } + } + + pub fn len(&self) -> usize { + self.size + } + + pub fn is_empty(&self) -> bool { + self.size == 0 + } + + pub fn capacity(&self) -> usize { + self.dense.len() + } + + pub fn insert(&mut self, value: usize) { + let i = self.size; + self.dense[i] = value; + self.sparse[value] = i; + self.size += 1; + } + + pub fn contains(&self, value: usize) -> bool { + let i = self.sparse[value]; + i < self.size && self.dense[i] == value + } + + pub fn clear(&mut self) { + self.size = 0; + } +} + +impl Deref for SparseSet { + type Target = [usize]; + + fn deref(&self) -> &Self::Target { + &self.dense[0..self.size] + } +} + +impl<'a> IntoIterator for &'a SparseSet { + type Item = &'a usize; + type IntoIter = slice::Iter<'a, usize>; + fn into_iter(self) -> Self::IntoIter { self.iter() } +} diff --git a/bash-5.1/vendor/regex/src/testdata/LICENSE b/bash-5.1/vendor/regex/src/testdata/LICENSE new file mode 100644 index 0000000..f47dbf4 --- /dev/null +++ b/bash-5.1/vendor/regex/src/testdata/LICENSE @@ -0,0 +1,19 @@ +The following license covers testregex.c and all associated test data. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of THIS SOFTWARE FILE (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do +so, subject to the following disclaimer: + +THIS SOFTWARE IS PROVIDED BY AT&T ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL AT&T BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/bash-5.1/vendor/regex/src/testdata/README b/bash-5.1/vendor/regex/src/testdata/README new file mode 100644 index 0000000..6efc2da --- /dev/null +++ b/bash-5.1/vendor/regex/src/testdata/README @@ -0,0 +1,17 @@ +Test data was taken from the Go distribution, which was in turn taken from the +testregex test suite: + + http://www2.research.att.com/~astopen/testregex/testregex.html + +The LICENSE in this directory corresponds to the LICENSE that the data was +released under. + +The tests themselves were modified for RE2/Go. A couple were modified further +by me (Andrew Gallant) (only in repetition.dat) so that RE2/Go would pass them. +(Yes, it seems like RE2/Go includes failing test cases.) This may or may not +have been a bad idea, but I think being consistent with an established Regex +library is worth something. + +Note that these files are read by 'scripts/regex-match-tests.py' and turned +into Rust tests found in 'regex_macros/tests/matches.rs'. + diff --git a/bash-5.1/vendor/regex/src/testdata/basic.dat b/bash-5.1/vendor/regex/src/testdata/basic.dat new file mode 100644 index 0000000..e55efae --- /dev/null +++ b/bash-5.1/vendor/regex/src/testdata/basic.dat @@ -0,0 +1,221 @@ +NOTE all standard compliant implementations should pass these : 2002-05-31 + +BE abracadabra$ abracadabracadabra (7,18) +BE a...b abababbb (2,7) +BE XXXXXX ..XXXXXX (2,8) +E \) () (1,2) +BE a] a]a (0,2) +B } } (0,1) +E \} } (0,1) +BE \] ] (0,1) +B ] ] (0,1) +E ] ] (0,1) +B { { (0,1) +B } } (0,1) +BE ^a ax (0,1) +BE \^a a^a (1,3) +BE a\^ a^ (0,2) +BE a$ aa (1,2) +BE a\$ a$ (0,2) +BE ^$ NULL (0,0) +E $^ NULL (0,0) +E a($) aa (1,2)(2,2) +E a*(^a) aa (0,1)(0,1) +E (..)*(...)* a (0,0) +E (..)*(...)* abcd (0,4)(2,4) +E (ab|a)(bc|c) abc (0,3)(0,2)(2,3) +E (ab)c|abc abc (0,3)(0,2) +E a{0}b ab (1,2) +E (a*)(b?)(b+)b{3} aaabbbbbbb (0,10)(0,3)(3,4)(4,7) +E (a*)(b{0,1})(b{1,})b{3} aaabbbbbbb (0,10)(0,3)(3,4)(4,7) +E a{9876543210} NULL BADBR +E ((a|a)|a) a (0,1)(0,1)(0,1) +E (a*)(a|aa) aaaa (0,4)(0,3)(3,4) +E a*(a.|aa) aaaa (0,4)(2,4) +E a(b)|c(d)|a(e)f aef (0,3)(?,?)(?,?)(1,2) +E (a|b)?.* b (0,1)(0,1) +E (a|b)c|a(b|c) ac (0,2)(0,1) +E (a|b)c|a(b|c) ab (0,2)(?,?)(1,2) +E (a|b)*c|(a|ab)*c abc (0,3)(1,2) +E (a|b)*c|(a|ab)*c xc (1,2) +E (.a|.b).*|.*(.a|.b) xa (0,2)(0,2) +E a?(ab|ba)ab abab (0,4)(0,2) +E a?(ac{0}b|ba)ab abab (0,4)(0,2) +E ab|abab abbabab (0,2) +E aba|bab|bba baaabbbaba (5,8) +E aba|bab baaabbbaba (6,9) +E (aa|aaa)*|(a|aaaaa) aa (0,2)(0,2) +E (a.|.a.)*|(a|.a...) aa (0,2)(0,2) +E ab|a xabc (1,3) +E ab|a xxabc (2,4) +Ei (Ab|cD)* aBcD (0,4)(2,4) +BE [^-] --a (2,3) +BE [a-]* --a (0,3) +BE [a-m-]* --amoma-- (0,4) +E :::1:::0:|:::1:1:0: :::0:::1:::1:::0: (8,17) +E :::1:::0:|:::1:1:1: :::0:::1:::1:::0: (8,17) +{E [[:upper:]] A (0,1) [[<element>]] not supported +E [[:lower:]]+ `az{ (1,3) +E [[:upper:]]+ @AZ[ (1,3) +# No collation in Go +#BE [[-]] [[-]] (2,4) +#BE [[.NIL.]] NULL ECOLLATE +#BE [[=aleph=]] NULL ECOLLATE +} +BE$ \n \n (0,1) +BEn$ \n \n (0,1) +BE$ [^a] \n (0,1) +BE$ \na \na (0,2) +E (a)(b)(c) abc (0,3)(0,1)(1,2)(2,3) +BE xxx xxx (0,3) +E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) feb 6, (0,6) +E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) 2/7 (0,3) +E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) feb 1,Feb 6 (5,11) +E3 ((((((((((((((((((((((((((((((x)))))))))))))))))))))))))))))) x (0,1)(0,1)(0,1) +E3 ((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))* xx (0,2)(1,2)(1,2) +E a?(ab|ba)* ababababababababababababababababababababababababababababababababababababababababa (0,81)(79,81) +E abaa|abbaa|abbbaa|abbbbaa ababbabbbabbbabbbbabbbbaa (18,25) +E abaa|abbaa|abbbaa|abbbbaa ababbabbbabbbabbbbabaa (18,22) +E aaac|aabc|abac|abbc|baac|babc|bbac|bbbc baaabbbabac (7,11) +BE$ .* \x01\x7f (0,2) +E aaaa|bbbb|cccc|ddddd|eeeeee|fffffff|gggg|hhhh|iiiii|jjjjj|kkkkk|llll XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa (53,57) +L aaaa\nbbbb\ncccc\nddddd\neeeeee\nfffffff\ngggg\nhhhh\niiiii\njjjjj\nkkkkk\nllll XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa NOMATCH +E a*a*a*a*a*b aaaaaaaaab (0,10) +BE ^ NULL (0,0) +BE $ NULL (0,0) +BE ^$ NULL (0,0) +BE ^a$ a (0,1) +BE abc abc (0,3) +BE abc xabcy (1,4) +BE abc ababc (2,5) +BE ab*c abc (0,3) +BE ab*bc abc (0,3) +BE ab*bc abbc (0,4) +BE ab*bc abbbbc (0,6) +E ab+bc abbc (0,4) +E ab+bc abbbbc (0,6) +E ab?bc abbc (0,4) +E ab?bc abc (0,3) +E ab?c abc (0,3) +BE ^abc$ abc (0,3) +BE ^abc abcc (0,3) +BE abc$ aabc (1,4) +BE ^ abc (0,0) +BE $ abc (3,3) +BE a.c abc (0,3) +BE a.c axc (0,3) +BE a.*c axyzc (0,5) +BE a[bc]d abd (0,3) +BE a[b-d]e ace (0,3) +BE a[b-d] aac (1,3) +BE a[-b] a- (0,2) +BE a[b-] a- (0,2) +BE a] a] (0,2) +BE a[]]b a]b (0,3) +BE a[^bc]d aed (0,3) +BE a[^-b]c adc (0,3) +BE a[^]b]c adc (0,3) +E ab|cd abc (0,2) +E ab|cd abcd (0,2) +E a\(b a(b (0,3) +E a\(*b ab (0,2) +E a\(*b a((b (0,4) +E ((a)) abc (0,1)(0,1)(0,1) +E (a)b(c) abc (0,3)(0,1)(2,3) +E a+b+c aabbabc (4,7) +E a* aaa (0,3) +#E (a*)* - (0,0)(0,0) +E (a*)* - (0,0)(?,?) RE2/Go +E (a*)+ - (0,0)(0,0) +#E (a*|b)* - (0,0)(0,0) +E (a*|b)* - (0,0)(?,?) RE2/Go +E (a+|b)* ab (0,2)(1,2) +E (a+|b)+ ab (0,2)(1,2) +E (a+|b)? ab (0,1)(0,1) +BE [^ab]* cde (0,3) +#E (^)* - (0,0)(0,0) +E (^)* - (0,0)(?,?) RE2/Go +BE a* NULL (0,0) +E ([abc])*d abbbcd (0,6)(4,5) +E ([abc])*bcd abcd (0,4)(0,1) +E a|b|c|d|e e (0,1) +E (a|b|c|d|e)f ef (0,2)(0,1) +#E ((a*|b))* - (0,0)(0,0)(0,0) +E ((a*|b))* - (0,0)(?,?)(?,?) RE2/Go +BE abcd*efg abcdefg (0,7) +BE ab* xabyabbbz (1,3) +BE ab* xayabbbz (1,2) +E (ab|cd)e abcde (2,5)(2,4) +BE [abhgefdc]ij hij (0,3) +E (a|b)c*d abcd (1,4)(1,2) +E (ab|ab*)bc abc (0,3)(0,1) +E a([bc]*)c* abc (0,3)(1,3) +E a([bc]*)(c*d) abcd (0,4)(1,3)(3,4) +E a([bc]+)(c*d) abcd (0,4)(1,3)(3,4) +E a([bc]*)(c+d) abcd (0,4)(1,2)(2,4) +E a[bcd]*dcdcde adcdcde (0,7) +E (ab|a)b*c abc (0,3)(0,2) +E ((a)(b)c)(d) abcd (0,4)(0,3)(0,1)(1,2)(3,4) +BE [A-Za-z_][A-Za-z0-9_]* alpha (0,5) +E ^a(bc+|b[eh])g|.h$ abh (1,3) +E (bc+d$|ef*g.|h?i(j|k)) effgz (0,5)(0,5) +E (bc+d$|ef*g.|h?i(j|k)) ij (0,2)(0,2)(1,2) +E (bc+d$|ef*g.|h?i(j|k)) reffgz (1,6)(1,6) +E (((((((((a))))))))) a (0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1) +BE multiple words multiple words yeah (0,14) +E (.*)c(.*) abcde (0,5)(0,2)(3,5) +BE abcd abcd (0,4) +E a(bc)d abcd (0,4)(1,3) +E a[-]?c ac (0,3) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Qaddafi (0,15)(?,?)(10,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mo'ammar Gadhafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Kaddafi (0,15)(?,?)(10,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Qadhafi (0,15)(?,?)(10,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Gadafi (0,14)(?,?)(10,11) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mu'ammar Qadafi (0,15)(?,?)(11,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moamar Gaddafi (0,14)(?,?)(9,11) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mu'ammar Qadhdhafi (0,18)(?,?)(13,15) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Khaddafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghaddafy (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghadafi (0,15)(?,?)(11,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghaddafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muamar Kaddafi (0,14)(?,?)(9,11) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Quathafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Gheddafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moammar Khadafy (0,15)(?,?)(11,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moammar Qudhafi (0,15)(?,?)(10,12) +E a+(b|c)*d+ aabcdd (0,6)(3,4) +E ^.+$ vivi (0,4) +E ^(.+)$ vivi (0,4)(0,4) +E ^([^!.]+).att.com!(.+)$ gryphon.att.com!eby (0,19)(0,7)(16,19) +E ^([^!]+!)?([^!]+)$ bas (0,3)(?,?)(0,3) +E ^([^!]+!)?([^!]+)$ bar!bas (0,7)(0,4)(4,7) +E ^([^!]+!)?([^!]+)$ foo!bas (0,7)(0,4)(4,7) +E ^.+!([^!]+!)([^!]+)$ foo!bar!bas (0,11)(4,8)(8,11) +E ((foo)|(bar))!bas bar!bas (0,7)(0,3)(?,?)(0,3) +E ((foo)|(bar))!bas foo!bar!bas (4,11)(4,7)(?,?)(4,7) +E ((foo)|(bar))!bas foo!bas (0,7)(0,3)(0,3) +E ((foo)|bar)!bas bar!bas (0,7)(0,3) +E ((foo)|bar)!bas foo!bar!bas (4,11)(4,7) +E ((foo)|bar)!bas foo!bas (0,7)(0,3)(0,3) +E (foo|(bar))!bas bar!bas (0,7)(0,3)(0,3) +E (foo|(bar))!bas foo!bar!bas (4,11)(4,7)(4,7) +E (foo|(bar))!bas foo!bas (0,7)(0,3) +E (foo|bar)!bas bar!bas (0,7)(0,3) +E (foo|bar)!bas foo!bar!bas (4,11)(4,7) +E (foo|bar)!bas foo!bas (0,7)(0,3) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bar!bas (0,11)(0,11)(?,?)(?,?)(4,8)(8,11) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ bas (0,3)(?,?)(0,3) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ bar!bas (0,7)(0,4)(4,7) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ foo!bar!bas (0,11)(?,?)(?,?)(4,8)(8,11) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ foo!bas (0,7)(0,4)(4,7) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ bas (0,3)(0,3)(?,?)(0,3) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ bar!bas (0,7)(0,7)(0,4)(4,7) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bar!bas (0,11)(0,11)(?,?)(?,?)(4,8)(8,11) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bas (0,7)(0,7)(0,4)(4,7) +E .*(/XXX).* /XXX (0,4)(0,4) +E .*(\\XXX).* \XXX (0,4)(0,4) +E \\XXX \XXX (0,4) +E .*(/000).* /000 (0,4)(0,4) +E .*(\\000).* \000 (0,4)(0,4) +E \\000 \000 (0,4) diff --git a/bash-5.1/vendor/regex/src/testdata/nullsubexpr.dat b/bash-5.1/vendor/regex/src/testdata/nullsubexpr.dat new file mode 100644 index 0000000..2e18fbb --- /dev/null +++ b/bash-5.1/vendor/regex/src/testdata/nullsubexpr.dat @@ -0,0 +1,79 @@ +NOTE null subexpression matches : 2002-06-06 + +E (a*)* a (0,1)(0,1) +#E SAME x (0,0)(0,0) +E SAME x (0,0)(?,?) RE2/Go +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E (a*)+ a (0,1)(0,1) +E SAME x (0,0)(0,0) +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E (a+)* a (0,1)(0,1) +E SAME x (0,0) +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E (a+)+ a (0,1)(0,1) +E SAME x NOMATCH +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) + +E ([a]*)* a (0,1)(0,1) +#E SAME x (0,0)(0,0) +E SAME x (0,0)(?,?) RE2/Go +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E ([a]*)+ a (0,1)(0,1) +E SAME x (0,0)(0,0) +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E ([^b]*)* a (0,1)(0,1) +#E SAME b (0,0)(0,0) +E SAME b (0,0)(?,?) RE2/Go +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaab (0,6)(0,6) +E ([ab]*)* a (0,1)(0,1) +E SAME aaaaaa (0,6)(0,6) +E SAME ababab (0,6)(0,6) +E SAME bababa (0,6)(0,6) +E SAME b (0,1)(0,1) +E SAME bbbbbb (0,6)(0,6) +E SAME aaaabcde (0,5)(0,5) +E ([^a]*)* b (0,1)(0,1) +E SAME bbbbbb (0,6)(0,6) +#E SAME aaaaaa (0,0)(0,0) +E SAME aaaaaa (0,0)(?,?) RE2/Go +E ([^ab]*)* ccccxx (0,6)(0,6) +#E SAME ababab (0,0)(0,0) +E SAME ababab (0,0)(?,?) RE2/Go + +E ((z)+|a)* zabcde (0,2)(1,2) + +#{E a+? aaaaaa (0,1) no *? +? mimimal match ops +#E (a) aaa (0,1)(0,1) +#E (a*?) aaa (0,0)(0,0) +#E (a)*? aaa (0,0) +#E (a*?)*? aaa (0,0) +#} + +B \(a*\)*\(x\) x (0,1)(0,0)(0,1) +B \(a*\)*\(x\) ax (0,2)(0,1)(1,2) +B \(a*\)*\(x\) axa (0,2)(0,1)(1,2) +B \(a*\)*\(x\)\(\1\) x (0,1)(0,0)(0,1)(1,1) +B \(a*\)*\(x\)\(\1\) ax (0,2)(1,1)(1,2)(2,2) +B \(a*\)*\(x\)\(\1\) axa (0,3)(0,1)(1,2)(2,3) +B \(a*\)*\(x\)\(\1\)\(x\) axax (0,4)(0,1)(1,2)(2,3)(3,4) +B \(a*\)*\(x\)\(\1\)\(x\) axxa (0,3)(1,1)(1,2)(2,2)(2,3) + +#E (a*)*(x) x (0,1)(0,0)(0,1) +E (a*)*(x) x (0,1)(?,?)(0,1) RE2/Go +E (a*)*(x) ax (0,2)(0,1)(1,2) +E (a*)*(x) axa (0,2)(0,1)(1,2) + +E (a*)+(x) x (0,1)(0,0)(0,1) +E (a*)+(x) ax (0,2)(0,1)(1,2) +E (a*)+(x) axa (0,2)(0,1)(1,2) + +E (a*){2}(x) x (0,1)(0,0)(0,1) +E (a*){2}(x) ax (0,2)(1,1)(1,2) +E (a*){2}(x) axa (0,2)(1,1)(1,2) diff --git a/bash-5.1/vendor/regex/src/testdata/repetition.dat b/bash-5.1/vendor/regex/src/testdata/repetition.dat new file mode 100644 index 0000000..3bb2121 --- /dev/null +++ b/bash-5.1/vendor/regex/src/testdata/repetition.dat @@ -0,0 +1,163 @@ +NOTE implicit vs. explicit repetitions : 2009-02-02 + +# Glenn Fowler <gsf@research.att.com> +# conforming matches (column 4) must match one of the following BREs +# NOMATCH +# (0,.)\((\(.\),\(.\))(?,?)(\2,\3)\)* +# (0,.)\((\(.\),\(.\))(\2,\3)(?,?)\)* +# i.e., each 3-tuple has two identical elements and one (?,?) + +E ((..)|(.)) NULL NOMATCH +E ((..)|(.))((..)|(.)) NULL NOMATCH +E ((..)|(.))((..)|(.))((..)|(.)) NULL NOMATCH + +E ((..)|(.)){1} NULL NOMATCH +E ((..)|(.)){2} NULL NOMATCH +E ((..)|(.)){3} NULL NOMATCH + +E ((..)|(.))* NULL (0,0) + +E ((..)|(.)) a (0,1)(0,1)(?,?)(0,1) +E ((..)|(.))((..)|(.)) a NOMATCH +E ((..)|(.))((..)|(.))((..)|(.)) a NOMATCH + +E ((..)|(.)){1} a (0,1)(0,1)(?,?)(0,1) +E ((..)|(.)){2} a NOMATCH +E ((..)|(.)){3} a NOMATCH + +E ((..)|(.))* a (0,1)(0,1)(?,?)(0,1) + +E ((..)|(.)) aa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aa (0,2)(0,1)(?,?)(0,1)(1,2)(?,?)(1,2) +E ((..)|(.))((..)|(.))((..)|(.)) aa NOMATCH + +E ((..)|(.)){1} aa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aa (0,2)(1,2)(?,?)(1,2) +E ((..)|(.)){3} aa NOMATCH + +E ((..)|(.))* aa (0,2)(0,2)(0,2)(?,?) + +E ((..)|(.)) aaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaa (0,3)(0,2)(0,2)(?,?)(2,3)(?,?)(2,3) +E ((..)|(.))((..)|(.))((..)|(.)) aaa (0,3)(0,1)(?,?)(0,1)(1,2)(?,?)(1,2)(2,3)(?,?)(2,3) + +E ((..)|(.)){1} aaa (0,2)(0,2)(0,2)(?,?) +#E ((..)|(.)){2} aaa (0,3)(2,3)(?,?)(2,3) +E ((..)|(.)){2} aaa (0,3)(2,3)(0,2)(2,3) RE2/Go +E ((..)|(.)){3} aaa (0,3)(2,3)(?,?)(2,3) + +#E ((..)|(.))* aaa (0,3)(2,3)(?,?)(2,3) +E ((..)|(.))* aaa (0,3)(2,3)(0,2)(2,3) RE2/Go + +E ((..)|(.)) aaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) +E ((..)|(.))((..)|(.))((..)|(.)) aaaa (0,4)(0,2)(0,2)(?,?)(2,3)(?,?)(2,3)(3,4)(?,?)(3,4) + +E ((..)|(.)){1} aaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aaaa (0,4)(2,4)(2,4)(?,?) +#E ((..)|(.)){3} aaaa (0,4)(3,4)(?,?)(3,4) +E ((..)|(.)){3} aaaa (0,4)(3,4)(0,2)(3,4) RE2/Go + +E ((..)|(.))* aaaa (0,4)(2,4)(2,4)(?,?) + +E ((..)|(.)) aaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) +E ((..)|(.))((..)|(.))((..)|(.)) aaaaa (0,5)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?)(4,5)(?,?)(4,5) + +E ((..)|(.)){1} aaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aaaaa (0,4)(2,4)(2,4)(?,?) +#E ((..)|(.)){3} aaaaa (0,5)(4,5)(?,?)(4,5) +E ((..)|(.)){3} aaaaa (0,5)(4,5)(2,4)(4,5) RE2/Go + +#E ((..)|(.))* aaaaa (0,5)(4,5)(?,?)(4,5) +E ((..)|(.))* aaaaa (0,5)(4,5)(2,4)(4,5) RE2/Go + +E ((..)|(.)) aaaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaaaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) +E ((..)|(.))((..)|(.))((..)|(.)) aaaaaa (0,6)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?)(4,6)(4,6)(?,?) + +E ((..)|(.)){1} aaaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aaaaaa (0,4)(2,4)(2,4)(?,?) +E ((..)|(.)){3} aaaaaa (0,6)(4,6)(4,6)(?,?) + +E ((..)|(.))* aaaaaa (0,6)(4,6)(4,6)(?,?) + +NOTE additional repetition tests graciously provided by Chris Kuklewicz www.haskell.org 2009-02-02 + +# These test a bug in OS X / FreeBSD / NetBSD, and libtree. +# Linux/GLIBC gets the {8,} and {8,8} wrong. + +:HA#100:E X(.?){0,}Y X1234567Y (0,9)(7,8) +:HA#101:E X(.?){1,}Y X1234567Y (0,9)(7,8) +:HA#102:E X(.?){2,}Y X1234567Y (0,9)(7,8) +:HA#103:E X(.?){3,}Y X1234567Y (0,9)(7,8) +:HA#104:E X(.?){4,}Y X1234567Y (0,9)(7,8) +:HA#105:E X(.?){5,}Y X1234567Y (0,9)(7,8) +:HA#106:E X(.?){6,}Y X1234567Y (0,9)(7,8) +:HA#107:E X(.?){7,}Y X1234567Y (0,9)(7,8) +:HA#108:E X(.?){8,}Y X1234567Y (0,9)(8,8) +#:HA#110:E X(.?){0,8}Y X1234567Y (0,9)(7,8) +:HA#110:E X(.?){0,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#111:E X(.?){1,8}Y X1234567Y (0,9)(7,8) +:HA#111:E X(.?){1,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#112:E X(.?){2,8}Y X1234567Y (0,9)(7,8) +:HA#112:E X(.?){2,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#113:E X(.?){3,8}Y X1234567Y (0,9)(7,8) +:HA#113:E X(.?){3,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#114:E X(.?){4,8}Y X1234567Y (0,9)(7,8) +:HA#114:E X(.?){4,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#115:E X(.?){5,8}Y X1234567Y (0,9)(7,8) +:HA#115:E X(.?){5,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#116:E X(.?){6,8}Y X1234567Y (0,9)(7,8) +:HA#116:E X(.?){6,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#117:E X(.?){7,8}Y X1234567Y (0,9)(7,8) +:HA#117:E X(.?){7,8}Y X1234567Y (0,9)(8,8) RE2/Go +:HA#118:E X(.?){8,8}Y X1234567Y (0,9)(8,8) + +# These test a fixed bug in my regex-tdfa that did not keep the expanded +# form properly grouped, so right association did the wrong thing with +# these ambiguous patterns (crafted just to test my code when I became +# suspicious of my implementation). The first subexpression should use +# "ab" then "a" then "bcd". + +# OS X / FreeBSD / NetBSD badly fail many of these, with impossible +# results like (0,6)(4,5)(6,6). + +:HA#260:E (a|ab|c|bcd){0,}(d*) ababcd (0,1)(0,1)(1,1) +:HA#261:E (a|ab|c|bcd){1,}(d*) ababcd (0,1)(0,1)(1,1) +:HA#262:E (a|ab|c|bcd){2,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#263:E (a|ab|c|bcd){3,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#264:E (a|ab|c|bcd){4,}(d*) ababcd NOMATCH +:HA#265:E (a|ab|c|bcd){0,10}(d*) ababcd (0,1)(0,1)(1,1) +:HA#266:E (a|ab|c|bcd){1,10}(d*) ababcd (0,1)(0,1)(1,1) +:HA#267:E (a|ab|c|bcd){2,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#268:E (a|ab|c|bcd){3,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#269:E (a|ab|c|bcd){4,10}(d*) ababcd NOMATCH +:HA#270:E (a|ab|c|bcd)*(d*) ababcd (0,1)(0,1)(1,1) +:HA#271:E (a|ab|c|bcd)+(d*) ababcd (0,1)(0,1)(1,1) + +# The above worked on Linux/GLIBC but the following often fail. +# They also trip up OS X / FreeBSD / NetBSD: + +#:HA#280:E (ab|a|c|bcd){0,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#280:E (ab|a|c|bcd){0,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#281:E (ab|a|c|bcd){1,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#281:E (ab|a|c|bcd){1,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#282:E (ab|a|c|bcd){2,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#282:E (ab|a|c|bcd){2,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#283:E (ab|a|c|bcd){3,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#283:E (ab|a|c|bcd){3,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +:HA#284:E (ab|a|c|bcd){4,}(d*) ababcd NOMATCH +#:HA#285:E (ab|a|c|bcd){0,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#285:E (ab|a|c|bcd){0,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#286:E (ab|a|c|bcd){1,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#286:E (ab|a|c|bcd){1,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#287:E (ab|a|c|bcd){2,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#287:E (ab|a|c|bcd){2,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#288:E (ab|a|c|bcd){3,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#288:E (ab|a|c|bcd){3,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +:HA#289:E (ab|a|c|bcd){4,10}(d*) ababcd NOMATCH +#:HA#290:E (ab|a|c|bcd)*(d*) ababcd (0,6)(3,6)(6,6) +:HA#290:E (ab|a|c|bcd)*(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#291:E (ab|a|c|bcd)+(d*) ababcd (0,6)(3,6)(6,6) +:HA#291:E (ab|a|c|bcd)+(d*) ababcd (0,6)(4,5)(5,6) RE2/Go diff --git a/bash-5.1/vendor/regex/src/utf8.rs b/bash-5.1/vendor/regex/src/utf8.rs new file mode 100644 index 0000000..75616f5 --- /dev/null +++ b/bash-5.1/vendor/regex/src/utf8.rs @@ -0,0 +1,290 @@ +/// A few elementary UTF-8 encoding and decoding functions used by the matching +/// engines. +/// +/// In an ideal world, the matching engines operate on `&str` and we can just +/// lean on the standard library for all our UTF-8 needs. However, to support +/// byte based regexes (that can match on arbitrary bytes which may contain +/// UTF-8), we need to be capable of searching and decoding UTF-8 on a `&[u8]`. +/// The standard library doesn't really recognize this use case, so we have +/// to build it out ourselves. +/// +/// Should this be factored out into a separate crate? It seems independently +/// useful. There are other crates that already exist (e.g., `utf-8`) that have +/// overlapping use cases. Not sure what to do. + +use std::char; + +const TAG_CONT: u8 = 0b1000_0000; +const TAG_TWO: u8 = 0b1100_0000; +const TAG_THREE: u8 = 0b1110_0000; +const TAG_FOUR: u8 = 0b1111_0000; + +/// Returns the smallest possible index of the next valid UTF-8 sequence +/// starting after `i`. +pub fn next_utf8(text: &[u8], i: usize) -> usize { + let b = match text.get(i) { + None => return i + 1, + Some(&b) => b, + }; + let inc = if b <= 0x7F { + 1 + } else if b <= 0b110_11111 { + 2 + } else if b <= 0b1110_1111 { + 3 + } else { + 4 + }; + i + inc +} + +/// Encode the given Unicode character to `dst` as a single UTF-8 sequence. +/// +/// If `dst` is not long enough, then `None` is returned. Otherwise, the number +/// of bytes written is returned. +#[allow(dead_code)] +#[inline] +pub fn encode_utf8(character: char, dst: &mut [u8]) -> Option<usize> { + let code = character as u32; + if code <= 0x7F && !dst.is_empty() { + dst[0] = code as u8; + Some(1) + } else if code <= 0x7FF && dst.len() >= 2 { + dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO; + dst[1] = (code & 0x3F) as u8 | TAG_CONT; + Some(2) + } else if code <= 0xFFFF && dst.len() >= 3 { + dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE; + dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code & 0x3F) as u8 | TAG_CONT; + Some(3) + } else if dst.len() >= 4 { + dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR; + dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[3] = (code & 0x3F) as u8 | TAG_CONT; + Some(4) + } else { + None + } +} + +/// Decode a single UTF-8 sequence into a single Unicode codepoint from `src`. +/// +/// If no valid UTF-8 sequence could be found, then `None` is returned. +/// Otherwise, the decoded codepoint and the number of bytes read is returned. +/// The number of bytes read (for a valid UTF-8 sequence) is guaranteed to be +/// 1, 2, 3 or 4. +/// +/// Note that a UTF-8 sequence is invalid if it is incorrect UTF-8, encodes a +/// codepoint that is out of range (surrogate codepoints are out of range) or +/// is not the shortest possible UTF-8 sequence for that codepoint. +#[inline] +pub fn decode_utf8(src: &[u8]) -> Option<(char, usize)> { + let b0 = match src.get(0) { + None => return None, + Some(&b) if b <= 0x7F => return Some((b as char, 1)), + Some(&b) => b, + }; + match b0 { + 0b110_00000 ... 0b110_11111 => { + if src.len() < 2 { + return None; + } + let b1 = src[1]; + if 0b11_000000 & b1 != TAG_CONT { + return None; + } + let cp = ((b0 & !TAG_TWO) as u32) << 6 + | ((b1 & !TAG_CONT) as u32); + match cp { + 0x80 ... 0x7FF => char::from_u32(cp).map(|cp| (cp, 2)), + _ => None, + } + } + 0b1110_0000 ... 0b1110_1111 => { + if src.len() < 3 { + return None; + } + let (b1, b2) = (src[1], src[2]); + if 0b11_000000 & b1 != TAG_CONT { + return None; + } + if 0b11_000000 & b2 != TAG_CONT { + return None; + } + let cp = ((b0 & !TAG_THREE) as u32) << 12 + | ((b1 & !TAG_CONT) as u32) << 6 + | ((b2 & !TAG_CONT) as u32); + match cp { + // char::from_u32 will disallow surrogate codepoints. + 0x800 ... 0xFFFF => char::from_u32(cp).map(|cp| (cp, 3)), + _ => None, + } + } + 0b11110_000 ... 0b11110_111 => { + if src.len() < 4 { + return None; + } + let (b1, b2, b3) = (src[1], src[2], src[3]); + if 0b11_000000 & b1 != TAG_CONT { + return None; + } + if 0b11_000000 & b2 != TAG_CONT { + return None; + } + if 0b11_000000 & b3 != TAG_CONT { + return None; + } + let cp = ((b0 & !TAG_FOUR) as u32) << 18 + | ((b1 & !TAG_CONT) as u32) << 12 + | ((b2 & !TAG_CONT) as u32) << 6 + | ((b3 & !TAG_CONT) as u32); + match cp { + 0x10000 ... 0x10FFFF => char::from_u32(cp).map(|cp| (cp, 4)), + _ => None, + } + } + _ => None, + } +} + +/// Like `decode_utf8`, but decodes the last UTF-8 sequence in `src` instead +/// of the first. +pub fn decode_last_utf8(src: &[u8]) -> Option<(char, usize)> { + if src.is_empty() { + return None; + } + let mut start = src.len() - 1; + if src[start] <= 0x7F { + return Some((src[start] as char, 1)); + } + while start > src.len().saturating_sub(4) { + start -= 1; + if is_start_byte(src[start]) { + break; + } + } + match decode_utf8(&src[start..]) { + None => None, + Some((_, n)) if n < src.len() - start => None, + Some((cp, n)) => Some((cp, n)), + } +} + +fn is_start_byte(b: u8) -> bool { + b & 0b11_000000 != 0b1_0000000 +} + +#[cfg(test)] +mod tests { + use std::str; + + use quickcheck::quickcheck; + + use super::{ + TAG_CONT, TAG_TWO, TAG_THREE, TAG_FOUR, + decode_utf8, decode_last_utf8, encode_utf8, + }; + + #[test] + fn prop_roundtrip() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let encoded_len = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, got_len) = decode_utf8(&tmp[..encoded_len]).unwrap(); + encoded_len == got_len && given_cp == got_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_roundtrip_last() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let encoded_len = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, got_len) = + decode_last_utf8(&tmp[..encoded_len]).unwrap(); + encoded_len == got_len && given_cp == got_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_encode_matches_std() { + fn p(cp: char) -> bool { + let mut got = [0; 4]; + let n = encode_utf8(cp, &mut got).unwrap(); + let expected = cp.to_string(); + &got[..n] == expected.as_bytes() + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_decode_matches_std() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let n = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, _) = decode_utf8(&tmp[..n]).unwrap(); + let expected_cp = + str::from_utf8(&tmp[..n]).unwrap().chars().next().unwrap(); + got_cp == expected_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_decode_last_matches_std() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let n = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, _) = decode_last_utf8(&tmp[..n]).unwrap(); + let expected_cp = + str::from_utf8(&tmp[..n]).unwrap() + .chars().rev().next().unwrap(); + got_cp == expected_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn reject_invalid() { + // Invalid start byte + assert_eq!(decode_utf8(&[0xFF]), None); + // Surrogate pair + assert_eq!(decode_utf8(&[0xED, 0xA0, 0x81]), None); + // Invalid continuation byte. + assert_eq!(decode_utf8(&[0xD4, 0xC2]), None); + // Bad lengths + assert_eq!(decode_utf8(&[0xC3]), None); // 2 bytes + assert_eq!(decode_utf8(&[0xEF, 0xBF]), None); // 3 bytes + assert_eq!(decode_utf8(&[0xF4, 0x8F, 0xBF]), None); // 4 bytes + // Not a minimal UTF-8 sequence + assert_eq!(decode_utf8(&[TAG_TWO, TAG_CONT | b'a']), None); + assert_eq!(decode_utf8(&[TAG_THREE, TAG_CONT, TAG_CONT | b'a']), None); + assert_eq!(decode_utf8(&[ + TAG_FOUR, TAG_CONT, TAG_CONT, TAG_CONT | b'a', + ]), None); + } + + #[test] + fn reject_invalid_last() { + // Invalid start byte + assert_eq!(decode_last_utf8(&[0xFF]), None); + // Surrogate pair + assert_eq!(decode_last_utf8(&[0xED, 0xA0, 0x81]), None); + // Bad lengths + assert_eq!(decode_last_utf8(&[0xC3]), None); // 2 bytes + assert_eq!(decode_last_utf8(&[0xEF, 0xBF]), None); // 3 bytes + assert_eq!(decode_last_utf8(&[0xF4, 0x8F, 0xBF]), None); // 4 bytes + // Not a minimal UTF-8 sequence + assert_eq!(decode_last_utf8(&[TAG_TWO, TAG_CONT | b'a']), None); + assert_eq!(decode_last_utf8(&[ + TAG_THREE, TAG_CONT, TAG_CONT | b'a', + ]), None); + assert_eq!(decode_last_utf8(&[ + TAG_FOUR, TAG_CONT, TAG_CONT, TAG_CONT | b'a', + ]), None); + } +} diff --git a/bash-5.1/vendor/regex/src/vector/avx2.rs b/bash-5.1/vendor/regex/src/vector/avx2.rs new file mode 100644 index 0000000..28f89d6 --- /dev/null +++ b/bash-5.1/vendor/regex/src/vector/avx2.rs @@ -0,0 +1,195 @@ +#![allow(dead_code)] + +use std::arch::x86_64::*; +use std::fmt; + +#[derive(Clone, Copy, Debug)] +pub struct AVX2VectorBuilder(()); + +impl AVX2VectorBuilder { + pub fn new() -> Option<AVX2VectorBuilder> { + if is_x86_feature_detected!("avx2") { + Some(AVX2VectorBuilder(())) + } else { + None + } + } + + /// Create a new u8x32 AVX2 vector where all of the bytes are set to + /// the given value. + #[inline] + pub fn u8x32_splat(self, n: u8) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { u8x32::splat(n) } + } + + /// Load 32 bytes from the given slice, with bounds checks. + #[inline] + pub fn u8x32_load_unaligned(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { u8x32::load_unaligned(slice) } + } + + /// Load 32 bytes from the given slice, without bounds checks. + #[inline] + pub unsafe fn u8x32_load_unchecked_unaligned(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x32::load_unchecked_unaligned(slice) + } + + /// Load 32 bytes from the given slice, with bound and alignment checks. + #[inline] + pub fn u8x32_load(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { u8x32::load(slice) } + } + + /// Load 32 bytes from the given slice, without bound or alignment checks. + #[inline] + pub unsafe fn u8x32_load_unchecked(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x32::load_unchecked(slice) + } +} + +// We define our union with a macro so that our code continues to compile on +// Rust 1.12. +macro_rules! defunion { + () => { + #[derive(Clone, Copy)] + #[allow(non_camel_case_types)] + pub union u8x32 { + vector: __m256i, + bytes: [u8; 32], + } + } +} + +defunion!(); + +impl u8x32 { + #[inline] + unsafe fn splat(n: u8) -> u8x32 { + u8x32 { vector: _mm256_set1_epi8(n as i8) } + } + + #[inline] + unsafe fn load_unaligned(slice: &[u8]) -> u8x32 { + assert!(slice.len() >= 32); + u8x32::load_unchecked_unaligned(slice) + } + + #[inline] + unsafe fn load_unchecked_unaligned(slice: &[u8]) -> u8x32 { + let p = slice.as_ptr() as *const u8 as *const __m256i; + u8x32 { vector: _mm256_loadu_si256(p) } + } + + #[inline] + unsafe fn load(slice: &[u8]) -> u8x32 { + assert!(slice.len() >= 32); + assert!(slice.as_ptr() as usize % 32 == 0); + u8x32::load_unchecked(slice) + } + + #[inline] + unsafe fn load_unchecked(slice: &[u8]) -> u8x32 { + let p = slice.as_ptr() as *const u8 as *const __m256i; + u8x32 { vector: _mm256_load_si256(p) } + } + + #[inline] + pub fn extract(self, i: usize) -> u8 { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] } + } + + #[inline] + pub fn replace(&mut self, i: usize, byte: u8) { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] = byte; } + } + + #[inline] + pub fn shuffle(self, indices: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + u8x32 { vector: _mm256_shuffle_epi8(self.vector, indices.vector) } + } + } + + #[inline] + pub fn ne(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + let boolv = _mm256_cmpeq_epi8(self.vector, other.vector); + let ones = _mm256_set1_epi8(0xFF as u8 as i8); + u8x32 { vector: _mm256_andnot_si256(boolv, ones) } + } + } + + #[inline] + pub fn and(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + u8x32 { vector: _mm256_and_si256(self.vector, other.vector) } + } + } + + #[inline] + pub fn movemask(self) -> u32 { + // Safe because we know AVX2 is enabled. + unsafe { + _mm256_movemask_epi8(self.vector) as u32 + } + } + + #[inline] + pub fn alignr_14(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + // Credit goes to jneem for figuring this out: + // https://github.com/jneem/teddy/blob/9ab5e899ad6ef6911aecd3cf1033f1abe6e1f66c/src/x86/teddy_simd.rs#L145-L184 + // + // TL;DR avx2's PALIGNR instruction is actually just two 128-bit + // PALIGNR instructions, which is not what we want, so we need to + // do some extra shuffling. + let v = _mm256_permute2x128_si256(other.vector, self.vector, 0x21); + let v = _mm256_alignr_epi8(self.vector, v, 14); + u8x32 { vector: v } + } + } + + #[inline] + pub fn alignr_15(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + // Credit goes to jneem for figuring this out: + // https://github.com/jneem/teddy/blob/9ab5e899ad6ef6911aecd3cf1033f1abe6e1f66c/src/x86/teddy_simd.rs#L145-L184 + // + // TL;DR avx2's PALIGNR instruction is actually just two 128-bit + // PALIGNR instructions, which is not what we want, so we need to + // do some extra shuffling. + let v = _mm256_permute2x128_si256(other.vector, self.vector, 0x21); + let v = _mm256_alignr_epi8(self.vector, v, 15); + u8x32 { vector: v } + } + } + + #[inline] + pub fn bit_shift_right_4(self) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + u8x32 { vector: _mm256_srli_epi16(self.vector, 4) } + } + } +} + +impl fmt::Debug for u8x32 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Safe because `bytes` is always accessible. + unsafe { self.bytes.fmt(f) } + } +} diff --git a/bash-5.1/vendor/regex/src/vector/mod.rs b/bash-5.1/vendor/regex/src/vector/mod.rs new file mode 100644 index 0000000..880dbc1 --- /dev/null +++ b/bash-5.1/vendor/regex/src/vector/mod.rs @@ -0,0 +1,4 @@ +#[cfg(target_arch = "x86_64")] +pub mod avx2; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +pub mod ssse3; diff --git a/bash-5.1/vendor/regex/src/vector/ssse3.rs b/bash-5.1/vendor/regex/src/vector/ssse3.rs new file mode 100644 index 0000000..4107381 --- /dev/null +++ b/bash-5.1/vendor/regex/src/vector/ssse3.rs @@ -0,0 +1,200 @@ +#![allow(dead_code)] + +use std::arch::x86_64::*; +use std::fmt; + +/// A builder for SSSE3 empowered vectors. +/// +/// This builder represents a receipt that the SSSE3 target feature is enabled +/// on the currently running CPU. Namely, the only way to get a value of this +/// type is if the SSSE3 feature is enabled. +/// +/// This type can then be used to build vector types that use SSSE3 features +/// safely. +#[derive(Clone, Copy, Debug)] +pub struct SSSE3VectorBuilder(()); + +impl SSSE3VectorBuilder { + /// Create a new SSSE3 vector builder. + /// + /// If the SSSE3 feature is not enabled for the current target, then + /// return `None`. + pub fn new() -> Option<SSSE3VectorBuilder> { + if is_x86_feature_detected!("ssse3") { + Some(SSSE3VectorBuilder(())) + } else { + None + } + } + + /// Create a new u8x16 SSSE3 vector where all of the bytes are set to + /// the given value. + #[inline] + pub fn u8x16_splat(self, n: u8) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { u8x16::splat(n) } + } + + /// Load 16 bytes from the given slice, with bounds checks. + #[inline] + pub fn u8x16_load_unaligned(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { u8x16::load_unaligned(slice) } + } + + /// Load 16 bytes from the given slice, without bounds checks. + #[inline] + pub unsafe fn u8x16_load_unchecked_unaligned(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x16::load_unchecked_unaligned(slice) + } + + /// Load 16 bytes from the given slice, with bound and alignment checks. + #[inline] + pub fn u8x16_load(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { u8x16::load(slice) } + } + + /// Load 16 bytes from the given slice, without bound or alignment checks. + #[inline] + pub unsafe fn u8x16_load_unchecked(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x16::load_unchecked(slice) + } +} + +// We define our union with a macro so that our code continues to compile on +// Rust 1.12. +macro_rules! defunion { + () => { + /// A u8x16 is a 128-bit vector with 16 single-byte lanes. + /// + /// It provides a safe API that uses only SSE2 or SSSE3 instructions. + /// The only way for callers to construct a value of this type is + /// through the SSSE3VectorBuilder type, and the only way to get a + /// SSSE3VectorBuilder is if the `ssse3` target feature is enabled. + /// + /// Note that generally speaking, all uses of this type should get + /// inlined, otherwise you probably have a performance bug. + #[derive(Clone, Copy)] + #[allow(non_camel_case_types)] + pub union u8x16 { + vector: __m128i, + bytes: [u8; 16], + } + } +} + +defunion!(); + +impl u8x16 { + #[inline] + unsafe fn splat(n: u8) -> u8x16 { + u8x16 { vector: _mm_set1_epi8(n as i8) } + } + + #[inline] + unsafe fn load_unaligned(slice: &[u8]) -> u8x16 { + assert!(slice.len() >= 16); + u8x16::load_unchecked(slice) + } + + #[inline] + unsafe fn load_unchecked_unaligned(slice: &[u8]) -> u8x16 { + let v = _mm_loadu_si128(slice.as_ptr() as *const u8 as *const __m128i); + u8x16 { vector: v } + } + + #[inline] + unsafe fn load(slice: &[u8]) -> u8x16 { + assert!(slice.len() >= 16); + assert!(slice.as_ptr() as usize % 16 == 0); + u8x16::load_unchecked(slice) + } + + #[inline] + unsafe fn load_unchecked(slice: &[u8]) -> u8x16 { + let v = _mm_load_si128(slice.as_ptr() as *const u8 as *const __m128i); + u8x16 { vector: v } + } + + #[inline] + pub fn extract(self, i: usize) -> u8 { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] } + } + + #[inline] + pub fn replace(&mut self, i: usize, byte: u8) { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] = byte; } + } + + #[inline] + pub fn shuffle(self, indices: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_shuffle_epi8(self.vector, indices.vector) } + } + } + + #[inline] + pub fn ne(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + let boolv = _mm_cmpeq_epi8(self.vector, other.vector); + let ones = _mm_set1_epi8(0xFF as u8 as i8); + u8x16 { vector: _mm_andnot_si128(boolv, ones) } + } + } + + #[inline] + pub fn and(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_and_si128(self.vector, other.vector) } + } + } + + #[inline] + pub fn movemask(self) -> u32 { + // Safe because we know SSSE3 is enabled. + unsafe { + _mm_movemask_epi8(self.vector) as u32 + } + } + + #[inline] + pub fn alignr_14(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_alignr_epi8(self.vector, other.vector, 14) } + } + } + + #[inline] + pub fn alignr_15(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_alignr_epi8(self.vector, other.vector, 15) } + } + } + + #[inline] + pub fn bit_shift_right_4(self) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_srli_epi16(self.vector, 4) } + } + } +} + +impl fmt::Debug for u8x16 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Safe because `bytes` is always accessible. + unsafe { self.bytes.fmt(f) } + } +} diff --git a/bash-5.1/vendor/regex/tests/api.rs b/bash-5.1/vendor/regex/tests/api.rs new file mode 100644 index 0000000..e17afa9 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/api.rs @@ -0,0 +1,182 @@ +#[test] +fn empty_regex_empty_match() { + let re = regex!(""); + assert_eq!(vec![(0, 0)], findall!(re, "")); +} + +#[test] +fn empty_regex_nonempty_match() { + let re = regex!(""); + assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], findall!(re, "abc")); +} + +#[test] +fn one_zero_length_match() { + let re = regex!(r"\d*"); + assert_eq!(vec![(0, 0), (1, 2), (3, 4)], findall!(re, "a1b2")); +} + +#[test] +fn many_zero_length_match() { + let re = regex!(r"\d*"); + assert_eq!(vec![(0, 0), (1, 2), (3, 3), (4, 4), (5, 6)], + findall!(re, "a1bbb2")); +} + +#[test] +fn many_sequential_zero_length_match() { + let re = regex!(r"\d?"); + assert_eq!(vec![(0, 0), (1, 2), (2, 3), (4, 5), (6, 6)], + findall!(re, "a12b3c")); +} + +#[test] +fn quoted_bracket_set() { + let re = regex!(r"([\x{5b}\x{5d}])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); + let re = regex!(r"([\[\]])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); +} + +#[test] +fn first_range_starts_with_left_bracket() { + let re = regex!(r"([\[-z])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); +} + +#[test] +fn range_ends_with_escape() { + let re = regex!(r"([\[-\x{5d}])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); +} + +#[test] +fn empty_match_find_iter() { + let re = regex!(r".*?"); + assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], findall!(re, "abc")); +} + +#[test] +fn empty_match_captures_iter() { + let re = regex!(r".*?"); + let ms: Vec<_> = re.captures_iter(text!("abc")) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); +} + +#[test] +fn capture_names() { + let re = regex!(r"(.)(?P<a>.)"); + assert_eq!(3, re.captures_len()); + assert_eq!((3, Some(3)), re.capture_names().size_hint()); + assert_eq!(vec![None, None, Some("a")], + re.capture_names().collect::<Vec<_>>()); +} + +#[test] +fn regex_string() { + assert_eq!(r"[a-zA-Z0-9]+", regex!(r"[a-zA-Z0-9]+").as_str()); + assert_eq!(r"[a-zA-Z0-9]+", &format!("{}", regex!(r"[a-zA-Z0-9]+"))); + assert_eq!(r"[a-zA-Z0-9]+", &format!("{:?}", regex!(r"[a-zA-Z0-9]+"))); +} + +#[test] +fn capture_index() { + let re = regex!(r"^(?P<name>.+)$"); + let cap = re.captures(t!("abc")).unwrap(); + assert_eq!(&cap[0], t!("abc")); + assert_eq!(&cap[1], t!("abc")); + assert_eq!(&cap["name"], t!("abc")); +} + +#[test] +#[should_panic] +#[cfg_attr(all(target_env = "msvc", target_pointer_width = "32"), ignore)] +fn capture_index_panic_usize() { + let re = regex!(r"^(?P<name>.+)$"); + let cap = re.captures(t!("abc")).unwrap(); + let _ = cap[2]; +} + +#[test] +#[should_panic] +#[cfg_attr(all(target_env = "msvc", target_pointer_width = "32"), ignore)] +fn capture_index_panic_name() { + let re = regex!(r"^(?P<name>.+)$"); + let cap = re.captures(t!("abc")).unwrap(); + let _ = cap["bad name"]; +} + +#[test] +fn capture_index_lifetime() { + // This is a test of whether the types on `caps["..."]` are general + // enough. If not, this will fail to typecheck. + fn inner(s: &str) -> usize { + let re = regex!(r"(?P<number>\d+)"); + let caps = re.captures(t!(s)).unwrap(); + caps["number"].len() + } + assert_eq!(3, inner("123")); +} + +#[test] +fn capture_misc() { + let re = regex!(r"(.)(?P<a>a)?(.)(?P<b>.)"); + let cap = re.captures(t!("abc")).unwrap(); + + assert_eq!(5, cap.len()); + + assert_eq!((0, 3), { let m = cap.get(0).unwrap(); (m.start(), m.end()) }); + assert_eq!(None, cap.get(2)); + assert_eq!((2, 3), { let m = cap.get(4).unwrap(); (m.start(), m.end()) }); + + assert_eq!(t!("abc"), match_text!(cap.get(0).unwrap())); + assert_eq!(None, cap.get(2)); + assert_eq!(t!("c"), match_text!(cap.get(4).unwrap())); + + assert_eq!(None, cap.name("a")); + assert_eq!(t!("c"), match_text!(cap.name("b").unwrap())); +} + +#[test] +fn sub_capture_matches() { + let re = regex!(r"([a-z])(([a-z])|([0-9]))"); + let cap = re.captures(t!("a5")).unwrap(); + let subs: Vec<_> = cap.iter().collect(); + + assert_eq!(5, subs.len()); + assert!(subs[0].is_some()); + assert!(subs[1].is_some()); + assert!(subs[2].is_some()); + assert!(subs[3].is_none()); + assert!(subs[4].is_some()); + + assert_eq!(t!("a5"), match_text!(subs[0].unwrap())); + assert_eq!(t!("a"), match_text!(subs[1].unwrap())); + assert_eq!(t!("5"), match_text!(subs[2].unwrap())); + assert_eq!(t!("5"), match_text!(subs[4].unwrap())); +} + +expand!(expand1, r"(?P<foo>\w+)", "abc", "$foo", "abc"); +expand!(expand2, r"(?P<foo>\w+)", "abc", "$0", "abc"); +expand!(expand3, r"(?P<foo>\w+)", "abc", "$1", "abc"); +expand!(expand4, r"(?P<foo>\w+)", "abc", "$$1", "$1"); +expand!(expand5, r"(?P<foo>\w+)", "abc", "$$foo", "$foo"); +expand!(expand6, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", "$b$a", "123abc"); +expand!(expand7, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", "z$bz$az", "z"); +expand!(expand8, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", ".$b.$a.", ".123.abc."); +expand!(expand9, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", " $b $a ", " 123 abc "); +expand!(expand10, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", "$bz$az", ""); + +split!(split1, r"\s+", "a b\nc\td\n\t e", + &[t!("a"), t!("b"), t!("c"), t!("d"), t!("e")]); +split!(split2, r"\b", "a b c", + &[t!(""), t!("a"), t!(" "), t!("b"), t!(" "), t!("c")]); +split!(split3, r"a$", "a", &[t!("")]); diff --git a/bash-5.1/vendor/regex/tests/api_str.rs b/bash-5.1/vendor/regex/tests/api_str.rs new file mode 100644 index 0000000..410bd90 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/api_str.rs @@ -0,0 +1,31 @@ +// These tests don't really make sense with the bytes API, so we only test them +// on the Unicode API. + +#[test] +fn empty_match_unicode_find_iter() { + // Tests that we still yield byte ranges at valid UTF-8 sequence boundaries + // even when we're susceptible to empty width matches. + let re = regex!(r".*?"); + assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], + findall!(re, "Ⅰ1Ⅱ2")); +} + +#[test] +fn empty_match_unicode_captures_iter() { + // Same as empty_match_unicode_find_iter, but tests capture iteration. + let re = regex!(r".*?"); + let ms: Vec<_> = re.captures_iter(text!("Ⅰ1Ⅱ2")) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms); +} + +#[test] +fn match_as_str() { + let re = regex!(r"fo+"); + let caps = re.captures("barfoobar").unwrap(); + assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo")); + assert_eq!(caps.get(0).map(From::from), Some("foo")); + assert_eq!(caps.get(0).map(Into::into), Some("foo")); +} diff --git a/bash-5.1/vendor/regex/tests/bytes.rs b/bash-5.1/vendor/regex/tests/bytes.rs new file mode 100644 index 0000000..0285950 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/bytes.rs @@ -0,0 +1,62 @@ +// These are tests specifically crafted for regexes that can match arbitrary +// bytes. + +// A silly wrapper to make it possible to write and match raw bytes. +struct R<'a>(&'a [u8]); +impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } + +mat!(word_boundary, r"(?-u) \b", " δ", None); +mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); +mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); +mat!(word_not_boundary_unicode, r" \B", " δ", None); + +mat!(perl_w_ascii, r"(?-u)\w+", "aδ", Some((0, 1))); +mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); +mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); +mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); +mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); +mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); + +// The first `(.+)` matches two Unicode codepoints, but can't match the 5th +// byte, which isn't valid UTF-8. The second (byte based) `(.+)` takes over and +// matches. +mat!(mixed1, r"(.+)(?-u)(.+)", R(b"\xCE\x93\xCE\x94\xFF"), + Some((0, 5)), Some((0, 4)), Some((4, 5))); + +mat!(case_ascii_one, r"(?i-u)a", "A", Some((0, 1))); +mat!(case_ascii_class, r"(?i-u)[a-z]+", "AaAaA", Some((0, 5))); +mat!(case_unicode, r"(?i)[a-z]+", "aA\u{212A}aA", Some((0, 7))); +mat!(case_not_unicode, r"(?i-u)[a-z]+", "aA\u{212A}aA", Some((0, 2))); + +mat!(negate_unicode, r"[^a]", "δ", Some((0, 2))); +mat!(negate_not_unicode, r"(?-u)[^a]", "δ", Some((0, 1))); + +// This doesn't match in a normal Unicode regex because the implicit preceding +// `.*?` is Unicode aware. +mat!(dotstar_prefix_not_unicode1, r"(?-u)a", R(b"\xFFa"), Some((1, 2))); +mat!(dotstar_prefix_not_unicode2, r"a", R(b"\xFFa"), Some((1, 2))); + +// Have fun with null bytes. +mat!(null_bytes, r"(?-u)(?P<cstr>[^\x00]+)\x00", + R(b"foo\x00"), Some((0, 4)), Some((0, 3))); + +// Test that lookahead operators work properly in the face of invalid UTF-8. +// See: https://github.com/rust-lang/regex/issues/277 +matiter!(invalidutf8_anchor1, + r"(?-u)\xcc?^", + R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), + (0, 0)); +matiter!(invalidutf8_anchor2, + r"(?-u)^\xf7|4\xff\d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########[] d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########\[] #####\x80\S7|$", + R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), + (22, 22)); +matiter!(invalidutf8_anchor3, + r"(?-u)^|ddp\xff\xffdddddlQd@\x80", + R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), + (0, 0)); + +// See https://github.com/rust-lang/regex/issues/303 +#[test] +fn negated_full_byte_range() { + assert!(::regex::bytes::Regex::new(r#"(?-u)[^\x00-\xff]"#).is_err()); +} diff --git a/bash-5.1/vendor/regex/tests/crazy.rs b/bash-5.1/vendor/regex/tests/crazy.rs new file mode 100644 index 0000000..6fc4980 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/crazy.rs @@ -0,0 +1,401 @@ +mat!(ascii_literal, r"a", "a", Some((0, 1))); + +// Some crazy expressions from regular-expressions.info. +mat!(match_ranges, + r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", + "num: 255", Some((5, 8))); +mat!(match_ranges_not, + r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", + "num: 256", None); +mat!(match_float1, r"[-+]?[0-9]*\.?[0-9]+", "0.1", Some((0, 3))); +mat!(match_float2, r"[-+]?[0-9]*\.?[0-9]+", "0.1.2", Some((0, 3))); +mat!(match_float3, r"[-+]?[0-9]*\.?[0-9]+", "a1.2", Some((1, 4))); +mat!(match_float4, r"^[-+]?[0-9]*\.?[0-9]+$", "1.a", None); +mat!(match_email, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", + "mine is jam.slam@gmail.com ", Some((8, 26))); +mat!(match_email_not, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", + "mine is jam.slam@gmail ", None); +mat!(match_email_big, r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", + "mine is jam.slam@gmail.com ", Some((8, 26))); +mat!(match_date1, + r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", + "1900-01-01", Some((0, 10))); +mat!(match_date2, + r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", + "1900-00-01", None); +mat!(match_date3, + r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", + "1900-13-01", None); + +// Do some crazy dancing with the start/end assertions. +matiter!(match_start_end_empty, r"^$", "", (0, 0)); +matiter!(match_start_end_empty_many_1, r"^$^$^$", "", (0, 0)); +matiter!(match_start_end_empty_many_2, r"^^^$$$", "", (0, 0)); +matiter!(match_start_end_empty_rev, r"$^", "", (0, 0)); +matiter!(match_start_end_empty_rep, r"(?:^$)*", "a\nb\nc", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); +matiter!(match_start_end_empty_rep_rev, r"(?:$^)*", "a\nb\nc", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); + +// Test negated character classes. +mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); +mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); +mat!(negclass_letter_space, r"[^a\s]", "a x", Some((2, 3))); +mat!(negclass_comma, r"[^,]", ",,x", Some((2, 3))); +mat!(negclass_space, r"[^\s]", " a", Some((1, 2))); +mat!(negclass_space_comma, r"[^,\s]", ", a", Some((2, 3))); +mat!(negclass_comma_space, r"[^\s,]", " ,a", Some((2, 3))); +mat!(negclass_ascii, r"[^[:alpha:]Z]", "A1", Some((1, 2))); + +// Test that repeated empty expressions don't loop forever. +mat!(lazy_many_many, r"((?:.*)*?)=", "a=b", Some((0, 2))); +mat!(lazy_many_optional, r"((?:.?)*?)=", "a=b", Some((0, 2))); +mat!(lazy_one_many_many, r"((?:.*)+?)=", "a=b", Some((0, 2))); +mat!(lazy_one_many_optional, r"((?:.?)+?)=", "a=b", Some((0, 2))); +mat!(lazy_range_min_many, r"((?:.*){1,}?)=", "a=b", Some((0, 2))); +mat!(lazy_range_many, r"((?:.*){1,2}?)=", "a=b", Some((0, 2))); +mat!(greedy_many_many, r"((?:.*)*)=", "a=b", Some((0, 2))); +mat!(greedy_many_optional, r"((?:.?)*)=", "a=b", Some((0, 2))); +mat!(greedy_one_many_many, r"((?:.*)+)=", "a=b", Some((0, 2))); +mat!(greedy_one_many_optional, r"((?:.?)+)=", "a=b", Some((0, 2))); +mat!(greedy_range_min_many, r"((?:.*){1,})=", "a=b", Some((0, 2))); +mat!(greedy_range_many, r"((?:.*){1,2})=", "a=b", Some((0, 2))); + +// Test that we handle various flavors of empty expressions. +matiter!(match_empty1, r"", "", (0, 0)); +matiter!(match_empty2, r"", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty3, r"()", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty4, r"()*", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty5, r"()+", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty6, r"()?", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty7, r"()()", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty8, r"()+|z", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty9, r"z|()+", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty10, r"()+|b", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty11, r"b|()+", "abc", (0, 0), (1, 2), (3, 3)); + +// Test that the DFA can handle pathological cases. +// (This should result in the DFA's cache being flushed too frequently, which +// should cause it to quit and fall back to the NFA algorithm.) +#[test] +fn dfa_handles_pathological_case() { + fn ones_and_zeroes(count: usize) -> String { + use rand::{Rng, thread_rng}; + + let mut rng = thread_rng(); + let mut s = String::new(); + for _ in 0..count { + if rng.gen() { + s.push('1'); + } else { + s.push('0'); + } + } + s + } + + let re = regex!(r"[01]*1[01]{20}$"); + let text = { + let mut pieces = ones_and_zeroes(100_000); + pieces.push('1'); + pieces.push_str(&ones_and_zeroes(20)); + pieces + }; + assert!(re.is_match(text!(&*text))); +} + +#[test] +fn nest_limit_makes_it_parse() { + use regex::RegexBuilder; + + RegexBuilder::new( + r#" + 2(?: + [45]\d{3}| + 7(?: + 1[0-267]| + 2[0-289]| + 3[0-29]| + 4[01]| + 5[1-3]| + 6[013]| + 7[0178]| + 91 + )| + 8(?: + 0[125]| + [139][1-6]| + 2[0157-9]| + 41| + 6[1-35]| + 7[1-5]| + 8[1-8]| + 90 + )| + 9(?: + 0[0-2]| + 1[0-4]| + 2[568]| + 3[3-6]| + 5[5-7]| + 6[0167]| + 7[15]| + 8[0146-9] + ) + )\d{4}| + 3(?: + 12?[5-7]\d{2}| + 0(?: + 2(?: + [025-79]\d| + [348]\d{1,2} + )| + 3(?: + [2-4]\d| + [56]\d? + ) + )| + 2(?: + 1\d{2}| + 2(?: + [12]\d| + [35]\d{1,2}| + 4\d? + ) + )| + 3(?: + 1\d{2}| + 2(?: + [2356]\d| + 4\d{1,2} + ) + )| + 4(?: + 1\d{2}| + 2(?: + 2\d{1,2}| + [47]| + 5\d{2} + ) + )| + 5(?: + 1\d{2}| + 29 + )| + [67]1\d{2}| + 8(?: + 1\d{2}| + 2(?: + 2\d{2}| + 3| + 4\d + ) + ) + )\d{3}| + 4(?: + 0(?: + 2(?: + [09]\d| + 7 + )| + 33\d{2} + )| + 1\d{3}| + 2(?: + 1\d{2}| + 2(?: + [25]\d?| + [348]\d| + [67]\d{1,2} + ) + )| + 3(?: + 1\d{2}(?: + \d{2} + )?| + 2(?: + [045]\d| + [236-9]\d{1,2} + )| + 32\d{2} + )| + 4(?: + [18]\d{2}| + 2(?: + [2-46]\d{2}| + 3 + )| + 5[25]\d{2} + )| + 5(?: + 1\d{2}| + 2(?: + 3\d| + 5 + ) + )| + 6(?: + [18]\d{2}| + 2(?: + 3(?: + \d{2} + )?| + [46]\d{1,2}| + 5\d{2}| + 7\d + )| + 5(?: + 3\d?| + 4\d| + [57]\d{1,2}| + 6\d{2}| + 8 + ) + )| + 71\d{2}| + 8(?: + [18]\d{2}| + 23\d{2}| + 54\d{2} + )| + 9(?: + [18]\d{2}| + 2[2-5]\d{2}| + 53\d{1,2} + ) + )\d{3}| + 5(?: + 02[03489]\d{2}| + 1\d{2}| + 2(?: + 1\d{2}| + 2(?: + 2(?: + \d{2} + )?| + [457]\d{2} + ) + )| + 3(?: + 1\d{2}| + 2(?: + [37](?: + \d{2} + )?| + [569]\d{2} + ) + )| + 4(?: + 1\d{2}| + 2[46]\d{2} + )| + 5(?: + 1\d{2}| + 26\d{1,2} + )| + 6(?: + [18]\d{2}| + 2| + 53\d{2} + )| + 7(?: + 1| + 24 + )\d{2}| + 8(?: + 1| + 26 + )\d{2}| + 91\d{2} + )\d{3}| + 6(?: + 0(?: + 1\d{2}| + 2(?: + 3\d{2}| + 4\d{1,2} + ) + )| + 2(?: + 2[2-5]\d{2}| + 5(?: + [3-5]\d{2}| + 7 + )| + 8\d{2} + )| + 3(?: + 1| + 2[3478] + )\d{2}| + 4(?: + 1| + 2[34] + )\d{2}| + 5(?: + 1| + 2[47] + )\d{2}| + 6(?: + [18]\d{2}| + 6(?: + 2(?: + 2\d| + [34]\d{2} + )| + 5(?: + [24]\d{2}| + 3\d| + 5\d{1,2} + ) + ) + )| + 72[2-5]\d{2}| + 8(?: + 1\d{2}| + 2[2-5]\d{2} + )| + 9(?: + 1\d{2}| + 2[2-6]\d{2} + ) + )\d{3}| + 7(?: + (?: + 02| + [3-589]1| + 6[12]| + 72[24] + )\d{2}| + 21\d{3}| + 32 + )\d{3}| + 8(?: + (?: + 4[12]| + [5-7]2| + 1\d? + )| + (?: + 0| + 3[12]| + [5-7]1| + 217 + )\d + )\d{4}| + 9(?: + [35]1| + (?: + [024]2| + 81 + )\d| + (?: + 1| + [24]1 + )\d{2} + )\d{3} + "# + ) + .build() + .unwrap(); +} diff --git a/bash-5.1/vendor/regex/tests/flags.rs b/bash-5.1/vendor/regex/tests/flags.rs new file mode 100644 index 0000000..0c9b36c --- /dev/null +++ b/bash-5.1/vendor/regex/tests/flags.rs @@ -0,0 +1,11 @@ +mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); +mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); +mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); +mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); +mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); +mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); +mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2))); +mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11))); +mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); +mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); +mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2))); diff --git a/bash-5.1/vendor/regex/tests/fowler.rs b/bash-5.1/vendor/regex/tests/fowler.rs new file mode 100644 index 0000000..a4d1a5b --- /dev/null +++ b/bash-5.1/vendor/regex/tests/fowler.rs @@ -0,0 +1,371 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py' +// on 2015-02-28 11:00:00.161706. + +// Tests from basic.dat +mat!(match_basic_3, r"abracadabra$", r"abracadabracadabra", Some((7, 18))); +mat!(match_basic_4, r"a...b", r"abababbb", Some((2, 7))); +mat!(match_basic_5, r"XXXXXX", r"..XXXXXX", Some((2, 8))); +mat!(match_basic_6, r"\)", r"()", Some((1, 2))); +mat!(match_basic_7, r"a]", r"a]a", Some((0, 2))); +mat!(match_basic_9, r"\}", r"}", Some((0, 1))); +mat!(match_basic_10, r"\]", r"]", Some((0, 1))); +mat!(match_basic_12, r"]", r"]", Some((0, 1))); +mat!(match_basic_15, r"^a", r"ax", Some((0, 1))); +mat!(match_basic_16, r"\^a", r"a^a", Some((1, 3))); +mat!(match_basic_17, r"a\^", r"a^", Some((0, 2))); +mat!(match_basic_18, r"a$", r"aa", Some((1, 2))); +mat!(match_basic_19, r"a\$", r"a$", Some((0, 2))); +mat!(match_basic_20, r"^$", r"", Some((0, 0))); +mat!(match_basic_21, r"$^", r"", Some((0, 0))); +mat!(match_basic_22, r"a($)", r"aa", Some((1, 2)), Some((2, 2))); +mat!(match_basic_23, r"a*(^a)", r"aa", Some((0, 1)), Some((0, 1))); +mat!(match_basic_24, r"(..)*(...)*", r"a", Some((0, 0))); +mat!(match_basic_25, r"(..)*(...)*", r"abcd", Some((0, 4)), Some((2, 4))); +mat!(match_basic_26, r"(ab|a)(bc|c)", r"abc", Some((0, 3)), Some((0, 2)), Some((2, 3))); +mat!(match_basic_27, r"(ab)c|abc", r"abc", Some((0, 3)), Some((0, 2))); +mat!(match_basic_28, r"a{0}b", r"ab", Some((1, 2))); +mat!(match_basic_29, r"(a*)(b?)(b+)b{3}", r"aaabbbbbbb", Some((0, 10)), Some((0, 3)), Some((3, 4)), Some((4, 7))); +mat!(match_basic_30, r"(a*)(b{0,1})(b{1,})b{3}", r"aaabbbbbbb", Some((0, 10)), Some((0, 3)), Some((3, 4)), Some((4, 7))); +mat!(match_basic_32, r"((a|a)|a)", r"a", Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_33, r"(a*)(a|aa)", r"aaaa", Some((0, 4)), Some((0, 3)), Some((3, 4))); +mat!(match_basic_34, r"a*(a.|aa)", r"aaaa", Some((0, 4)), Some((2, 4))); +mat!(match_basic_35, r"a(b)|c(d)|a(e)f", r"aef", Some((0, 3)), None, None, Some((1, 2))); +mat!(match_basic_36, r"(a|b)?.*", r"b", Some((0, 1)), Some((0, 1))); +mat!(match_basic_37, r"(a|b)c|a(b|c)", r"ac", Some((0, 2)), Some((0, 1))); +mat!(match_basic_38, r"(a|b)c|a(b|c)", r"ab", Some((0, 2)), None, Some((1, 2))); +mat!(match_basic_39, r"(a|b)*c|(a|ab)*c", r"abc", Some((0, 3)), Some((1, 2))); +mat!(match_basic_40, r"(a|b)*c|(a|ab)*c", r"xc", Some((1, 2))); +mat!(match_basic_41, r"(.a|.b).*|.*(.a|.b)", r"xa", Some((0, 2)), Some((0, 2))); +mat!(match_basic_42, r"a?(ab|ba)ab", r"abab", Some((0, 4)), Some((0, 2))); +mat!(match_basic_43, r"a?(ac{0}b|ba)ab", r"abab", Some((0, 4)), Some((0, 2))); +mat!(match_basic_44, r"ab|abab", r"abbabab", Some((0, 2))); +mat!(match_basic_45, r"aba|bab|bba", r"baaabbbaba", Some((5, 8))); +mat!(match_basic_46, r"aba|bab", r"baaabbbaba", Some((6, 9))); +mat!(match_basic_47, r"(aa|aaa)*|(a|aaaaa)", r"aa", Some((0, 2)), Some((0, 2))); +mat!(match_basic_48, r"(a.|.a.)*|(a|.a...)", r"aa", Some((0, 2)), Some((0, 2))); +mat!(match_basic_49, r"ab|a", r"xabc", Some((1, 3))); +mat!(match_basic_50, r"ab|a", r"xxabc", Some((2, 4))); +mat!(match_basic_51, r"(?i)(Ab|cD)*", r"aBcD", Some((0, 4)), Some((2, 4))); +mat!(match_basic_52, r"[^-]", r"--a", Some((2, 3))); +mat!(match_basic_53, r"[a-]*", r"--a", Some((0, 3))); +mat!(match_basic_54, r"[a-m-]*", r"--amoma--", Some((0, 4))); +mat!(match_basic_55, r":::1:::0:|:::1:1:0:", r":::0:::1:::1:::0:", Some((8, 17))); +mat!(match_basic_56, r":::1:::0:|:::1:1:1:", r":::0:::1:::1:::0:", Some((8, 17))); +mat!(match_basic_57, r"[[:upper:]]", r"A", Some((0, 1))); +mat!(match_basic_58, r"[[:lower:]]+", r"`az{", Some((1, 3))); +mat!(match_basic_59, r"[[:upper:]]+", r"@AZ[", Some((1, 3))); +mat!(match_basic_65, r" +", r" +", Some((0, 1))); +mat!(match_basic_66, r" +", r" +", Some((0, 1))); +mat!(match_basic_67, r"[^a]", r" +", Some((0, 1))); +mat!(match_basic_68, r" +a", r" +a", Some((0, 2))); +mat!(match_basic_69, r"(a)(b)(c)", r"abc", Some((0, 3)), Some((0, 1)), Some((1, 2)), Some((2, 3))); +mat!(match_basic_70, r"xxx", r"xxx", Some((0, 3))); +mat!(match_basic_71, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 6,", Some((0, 6))); +mat!(match_basic_72, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"2/7", Some((0, 3))); +mat!(match_basic_73, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 1,Feb 6", Some((5, 11))); +mat!(match_basic_74, r"((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))", r"x", Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_75, r"((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))*", r"xx", Some((0, 2)), Some((1, 2)), Some((1, 2))); +mat!(match_basic_76, r"a?(ab|ba)*", r"ababababababababababababababababababababababababababababababababababababababababa", Some((0, 81)), Some((79, 81))); +mat!(match_basic_77, r"abaa|abbaa|abbbaa|abbbbaa", r"ababbabbbabbbabbbbabbbbaa", Some((18, 25))); +mat!(match_basic_78, r"abaa|abbaa|abbbaa|abbbbaa", r"ababbabbbabbbabbbbabaa", Some((18, 22))); +mat!(match_basic_79, r"aaac|aabc|abac|abbc|baac|babc|bbac|bbbc", r"baaabbbabac", Some((7, 11))); +mat!(match_basic_80, r".*", r"", Some((0, 2))); +mat!(match_basic_81, r"aaaa|bbbb|cccc|ddddd|eeeeee|fffffff|gggg|hhhh|iiiii|jjjjj|kkkkk|llll", r"XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa", Some((53, 57))); +mat!(match_basic_83, r"a*a*a*a*a*b", r"aaaaaaaaab", Some((0, 10))); +mat!(match_basic_84, r"^", r"", Some((0, 0))); +mat!(match_basic_85, r"$", r"", Some((0, 0))); +mat!(match_basic_86, r"^$", r"", Some((0, 0))); +mat!(match_basic_87, r"^a$", r"a", Some((0, 1))); +mat!(match_basic_88, r"abc", r"abc", Some((0, 3))); +mat!(match_basic_89, r"abc", r"xabcy", Some((1, 4))); +mat!(match_basic_90, r"abc", r"ababc", Some((2, 5))); +mat!(match_basic_91, r"ab*c", r"abc", Some((0, 3))); +mat!(match_basic_92, r"ab*bc", r"abc", Some((0, 3))); +mat!(match_basic_93, r"ab*bc", r"abbc", Some((0, 4))); +mat!(match_basic_94, r"ab*bc", r"abbbbc", Some((0, 6))); +mat!(match_basic_95, r"ab+bc", r"abbc", Some((0, 4))); +mat!(match_basic_96, r"ab+bc", r"abbbbc", Some((0, 6))); +mat!(match_basic_97, r"ab?bc", r"abbc", Some((0, 4))); +mat!(match_basic_98, r"ab?bc", r"abc", Some((0, 3))); +mat!(match_basic_99, r"ab?c", r"abc", Some((0, 3))); +mat!(match_basic_100, r"^abc$", r"abc", Some((0, 3))); +mat!(match_basic_101, r"^abc", r"abcc", Some((0, 3))); +mat!(match_basic_102, r"abc$", r"aabc", Some((1, 4))); +mat!(match_basic_103, r"^", r"abc", Some((0, 0))); +mat!(match_basic_104, r"$", r"abc", Some((3, 3))); +mat!(match_basic_105, r"a.c", r"abc", Some((0, 3))); +mat!(match_basic_106, r"a.c", r"axc", Some((0, 3))); +mat!(match_basic_107, r"a.*c", r"axyzc", Some((0, 5))); +mat!(match_basic_108, r"a[bc]d", r"abd", Some((0, 3))); +mat!(match_basic_109, r"a[b-d]e", r"ace", Some((0, 3))); +mat!(match_basic_110, r"a[b-d]", r"aac", Some((1, 3))); +mat!(match_basic_111, r"a[-b]", r"a-", Some((0, 2))); +mat!(match_basic_112, r"a[b-]", r"a-", Some((0, 2))); +mat!(match_basic_113, r"a]", r"a]", Some((0, 2))); +mat!(match_basic_114, r"a[]]b", r"a]b", Some((0, 3))); +mat!(match_basic_115, r"a[^bc]d", r"aed", Some((0, 3))); +mat!(match_basic_116, r"a[^-b]c", r"adc", Some((0, 3))); +mat!(match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))); +mat!(match_basic_118, r"ab|cd", r"abc", Some((0, 2))); +mat!(match_basic_119, r"ab|cd", r"abcd", Some((0, 2))); +mat!(match_basic_120, r"a\(b", r"a(b", Some((0, 3))); +mat!(match_basic_121, r"a\(*b", r"ab", Some((0, 2))); +mat!(match_basic_122, r"a\(*b", r"a((b", Some((0, 4))); +mat!(match_basic_123, r"((a))", r"abc", Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_124, r"(a)b(c)", r"abc", Some((0, 3)), Some((0, 1)), Some((2, 3))); +mat!(match_basic_125, r"a+b+c", r"aabbabc", Some((4, 7))); +mat!(match_basic_126, r"a*", r"aaa", Some((0, 3))); +mat!(match_basic_128, r"(a*)*", r"-", Some((0, 0)), None); +mat!(match_basic_129, r"(a*)+", r"-", Some((0, 0)), Some((0, 0))); +mat!(match_basic_131, r"(a*|b)*", r"-", Some((0, 0)), None); +mat!(match_basic_132, r"(a+|b)*", r"ab", Some((0, 2)), Some((1, 2))); +mat!(match_basic_133, r"(a+|b)+", r"ab", Some((0, 2)), Some((1, 2))); +mat!(match_basic_134, r"(a+|b)?", r"ab", Some((0, 1)), Some((0, 1))); +mat!(match_basic_135, r"[^ab]*", r"cde", Some((0, 3))); +mat!(match_basic_137, r"(^)*", r"-", Some((0, 0)), None); +mat!(match_basic_138, r"a*", r"", Some((0, 0))); +mat!(match_basic_139, r"([abc])*d", r"abbbcd", Some((0, 6)), Some((4, 5))); +mat!(match_basic_140, r"([abc])*bcd", r"abcd", Some((0, 4)), Some((0, 1))); +mat!(match_basic_141, r"a|b|c|d|e", r"e", Some((0, 1))); +mat!(match_basic_142, r"(a|b|c|d|e)f", r"ef", Some((0, 2)), Some((0, 1))); +mat!(match_basic_144, r"((a*|b))*", r"-", Some((0, 0)), None, None); +mat!(match_basic_145, r"abcd*efg", r"abcdefg", Some((0, 7))); +mat!(match_basic_146, r"ab*", r"xabyabbbz", Some((1, 3))); +mat!(match_basic_147, r"ab*", r"xayabbbz", Some((1, 2))); +mat!(match_basic_148, r"(ab|cd)e", r"abcde", Some((2, 5)), Some((2, 4))); +mat!(match_basic_149, r"[abhgefdc]ij", r"hij", Some((0, 3))); +mat!(match_basic_150, r"(a|b)c*d", r"abcd", Some((1, 4)), Some((1, 2))); +mat!(match_basic_151, r"(ab|ab*)bc", r"abc", Some((0, 3)), Some((0, 1))); +mat!(match_basic_152, r"a([bc]*)c*", r"abc", Some((0, 3)), Some((1, 3))); +mat!(match_basic_153, r"a([bc]*)(c*d)", r"abcd", Some((0, 4)), Some((1, 3)), Some((3, 4))); +mat!(match_basic_154, r"a([bc]+)(c*d)", r"abcd", Some((0, 4)), Some((1, 3)), Some((3, 4))); +mat!(match_basic_155, r"a([bc]*)(c+d)", r"abcd", Some((0, 4)), Some((1, 2)), Some((2, 4))); +mat!(match_basic_156, r"a[bcd]*dcdcde", r"adcdcde", Some((0, 7))); +mat!(match_basic_157, r"(ab|a)b*c", r"abc", Some((0, 3)), Some((0, 2))); +mat!(match_basic_158, r"((a)(b)c)(d)", r"abcd", Some((0, 4)), Some((0, 3)), Some((0, 1)), Some((1, 2)), Some((3, 4))); +mat!(match_basic_159, r"[A-Za-z_][A-Za-z0-9_]*", r"alpha", Some((0, 5))); +mat!(match_basic_160, r"^a(bc+|b[eh])g|.h$", r"abh", Some((1, 3))); +mat!(match_basic_161, r"(bc+d$|ef*g.|h?i(j|k))", r"effgz", Some((0, 5)), Some((0, 5))); +mat!(match_basic_162, r"(bc+d$|ef*g.|h?i(j|k))", r"ij", Some((0, 2)), Some((0, 2)), Some((1, 2))); +mat!(match_basic_163, r"(bc+d$|ef*g.|h?i(j|k))", r"reffgz", Some((1, 6)), Some((1, 6))); +mat!(match_basic_164, r"(((((((((a)))))))))", r"a", Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_165, r"multiple words", r"multiple words yeah", Some((0, 14))); +mat!(match_basic_166, r"(.*)c(.*)", r"abcde", Some((0, 5)), Some((0, 2)), Some((3, 5))); +mat!(match_basic_167, r"abcd", r"abcd", Some((0, 4))); +mat!(match_basic_168, r"a(bc)d", r"abcd", Some((0, 4)), Some((1, 3))); +mat!(match_basic_169, r"a[-]?c", r"ac", Some((0, 3))); +mat!(match_basic_170, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Qaddafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_171, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mo'ammar Gadhafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_172, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Kaddafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_173, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Qadhafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_174, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Gadafi", Some((0, 14)), None, Some((10, 11))); +mat!(match_basic_175, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mu'ammar Qadafi", Some((0, 15)), None, Some((11, 12))); +mat!(match_basic_176, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moamar Gaddafi", Some((0, 14)), None, Some((9, 11))); +mat!(match_basic_177, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mu'ammar Qadhdhafi", Some((0, 18)), None, Some((13, 15))); +mat!(match_basic_178, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Khaddafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_179, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghaddafy", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_180, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghadafi", Some((0, 15)), None, Some((11, 12))); +mat!(match_basic_181, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghaddafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_182, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muamar Kaddafi", Some((0, 14)), None, Some((9, 11))); +mat!(match_basic_183, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Quathafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_184, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Gheddafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_185, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moammar Khadafy", Some((0, 15)), None, Some((11, 12))); +mat!(match_basic_186, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moammar Qudhafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_187, r"a+(b|c)*d+", r"aabcdd", Some((0, 6)), Some((3, 4))); +mat!(match_basic_188, r"^.+$", r"vivi", Some((0, 4))); +mat!(match_basic_189, r"^(.+)$", r"vivi", Some((0, 4)), Some((0, 4))); +mat!(match_basic_190, r"^([^!.]+).att.com!(.+)$", r"gryphon.att.com!eby", Some((0, 19)), Some((0, 7)), Some((16, 19))); +mat!(match_basic_191, r"^([^!]+!)?([^!]+)$", r"bas", Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_192, r"^([^!]+!)?([^!]+)$", r"bar!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_193, r"^([^!]+!)?([^!]+)$", r"foo!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_194, r"^.+!([^!]+!)([^!]+)$", r"foo!bar!bas", Some((0, 11)), Some((4, 8)), Some((8, 11))); +mat!(match_basic_195, r"((foo)|(bar))!bas", r"bar!bas", Some((0, 7)), Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_196, r"((foo)|(bar))!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7)), None, Some((4, 7))); +mat!(match_basic_197, r"((foo)|(bar))!bas", r"foo!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); +mat!(match_basic_198, r"((foo)|bar)!bas", r"bar!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_199, r"((foo)|bar)!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7))); +mat!(match_basic_200, r"((foo)|bar)!bas", r"foo!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); +mat!(match_basic_201, r"(foo|(bar))!bas", r"bar!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); +mat!(match_basic_202, r"(foo|(bar))!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7)), Some((4, 7))); +mat!(match_basic_203, r"(foo|(bar))!bas", r"foo!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_204, r"(foo|bar)!bas", r"bar!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_205, r"(foo|bar)!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7))); +mat!(match_basic_206, r"(foo|bar)!bas", r"foo!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_207, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bar!bas", Some((0, 11)), Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); +mat!(match_basic_208, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"bas", Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_209, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"bar!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_210, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"foo!bar!bas", Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); +mat!(match_basic_211, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"foo!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_212, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"bas", Some((0, 3)), Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_213, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"bar!bas", Some((0, 7)), Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_214, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bar!bas", Some((0, 11)), Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); +mat!(match_basic_215, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bas", Some((0, 7)), Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_216, r".*(/XXX).*", r"/XXX", Some((0, 4)), Some((0, 4))); +mat!(match_basic_217, r".*(\\XXX).*", r"\XXX", Some((0, 4)), Some((0, 4))); +mat!(match_basic_218, r"\\XXX", r"\XXX", Some((0, 4))); +mat!(match_basic_219, r".*(/000).*", r"/000", Some((0, 4)), Some((0, 4))); +mat!(match_basic_220, r".*(\\000).*", r"\000", Some((0, 4)), Some((0, 4))); +mat!(match_basic_221, r"\\000", r"\000", Some((0, 4))); + +// Tests from nullsubexpr.dat +mat!(match_nullsubexpr_3, r"(a*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_5, r"(a*)*", r"x", Some((0, 0)), None); +mat!(match_nullsubexpr_6, r"(a*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_7, r"(a*)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_8, r"(a*)+", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_9, r"(a*)+", r"x", Some((0, 0)), Some((0, 0))); +mat!(match_nullsubexpr_10, r"(a*)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_11, r"(a*)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_12, r"(a+)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_13, r"(a+)*", r"x", Some((0, 0))); +mat!(match_nullsubexpr_14, r"(a+)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_15, r"(a+)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_16, r"(a+)+", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_17, r"(a+)+", r"x", None); +mat!(match_nullsubexpr_18, r"(a+)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_19, r"(a+)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_21, r"([a]*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_23, r"([a]*)*", r"x", Some((0, 0)), None); +mat!(match_nullsubexpr_24, r"([a]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_25, r"([a]*)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_26, r"([a]*)+", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_27, r"([a]*)+", r"x", Some((0, 0)), Some((0, 0))); +mat!(match_nullsubexpr_28, r"([a]*)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_29, r"([a]*)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_30, r"([^b]*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_32, r"([^b]*)*", r"b", Some((0, 0)), None); +mat!(match_nullsubexpr_33, r"([^b]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_34, r"([^b]*)*", r"aaaaaab", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_35, r"([ab]*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_36, r"([ab]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_37, r"([ab]*)*", r"ababab", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_38, r"([ab]*)*", r"bababa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_39, r"([ab]*)*", r"b", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_40, r"([ab]*)*", r"bbbbbb", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_41, r"([ab]*)*", r"aaaabcde", Some((0, 5)), Some((0, 5))); +mat!(match_nullsubexpr_42, r"([^a]*)*", r"b", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_43, r"([^a]*)*", r"bbbbbb", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_45, r"([^a]*)*", r"aaaaaa", Some((0, 0)), None); +mat!(match_nullsubexpr_46, r"([^ab]*)*", r"ccccxx", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_48, r"([^ab]*)*", r"ababab", Some((0, 0)), None); +mat!(match_nullsubexpr_50, r"((z)+|a)*", r"zabcde", Some((0, 2)), Some((1, 2))); +mat!(match_nullsubexpr_69, r"(a*)*(x)", r"x", Some((0, 1)), None, Some((0, 1))); +mat!(match_nullsubexpr_70, r"(a*)*(x)", r"ax", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_71, r"(a*)*(x)", r"axa", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_73, r"(a*)+(x)", r"x", Some((0, 1)), Some((0, 0)), Some((0, 1))); +mat!(match_nullsubexpr_74, r"(a*)+(x)", r"ax", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_75, r"(a*)+(x)", r"axa", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_77, r"(a*){2}(x)", r"x", Some((0, 1)), Some((0, 0)), Some((0, 1))); +mat!(match_nullsubexpr_78, r"(a*){2}(x)", r"ax", Some((0, 2)), Some((1, 1)), Some((1, 2))); +mat!(match_nullsubexpr_79, r"(a*){2}(x)", r"axa", Some((0, 2)), Some((1, 1)), Some((1, 2))); + +// Tests from repetition.dat +mat!(match_repetition_10, r"((..)|(.))", r"", None); +mat!(match_repetition_11, r"((..)|(.))((..)|(.))", r"", None); +mat!(match_repetition_12, r"((..)|(.))((..)|(.))((..)|(.))", r"", None); +mat!(match_repetition_14, r"((..)|(.)){1}", r"", None); +mat!(match_repetition_15, r"((..)|(.)){2}", r"", None); +mat!(match_repetition_16, r"((..)|(.)){3}", r"", None); +mat!(match_repetition_18, r"((..)|(.))*", r"", Some((0, 0))); +mat!(match_repetition_20, r"((..)|(.))", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); +mat!(match_repetition_21, r"((..)|(.))((..)|(.))", r"a", None); +mat!(match_repetition_22, r"((..)|(.))((..)|(.))((..)|(.))", r"a", None); +mat!(match_repetition_24, r"((..)|(.)){1}", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); +mat!(match_repetition_25, r"((..)|(.)){2}", r"a", None); +mat!(match_repetition_26, r"((..)|(.)){3}", r"a", None); +mat!(match_repetition_28, r"((..)|(.))*", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); +mat!(match_repetition_30, r"((..)|(.))", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_31, r"((..)|(.))((..)|(.))", r"aa", Some((0, 2)), Some((0, 1)), None, Some((0, 1)), Some((1, 2)), None, Some((1, 2))); +mat!(match_repetition_32, r"((..)|(.))((..)|(.))((..)|(.))", r"aa", None); +mat!(match_repetition_34, r"((..)|(.)){1}", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_35, r"((..)|(.)){2}", r"aa", Some((0, 2)), Some((1, 2)), None, Some((1, 2))); +mat!(match_repetition_36, r"((..)|(.)){3}", r"aa", None); +mat!(match_repetition_38, r"((..)|(.))*", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_40, r"((..)|(.))", r"aaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_41, r"((..)|(.))((..)|(.))", r"aaa", Some((0, 3)), Some((0, 2)), Some((0, 2)), None, Some((2, 3)), None, Some((2, 3))); +mat!(match_repetition_42, r"((..)|(.))((..)|(.))((..)|(.))", r"aaa", Some((0, 3)), Some((0, 1)), None, Some((0, 1)), Some((1, 2)), None, Some((1, 2)), Some((2, 3)), None, Some((2, 3))); +mat!(match_repetition_44, r"((..)|(.)){1}", r"aaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_46, r"((..)|(.)){2}", r"aaa", Some((0, 3)), Some((2, 3)), Some((0, 2)), Some((2, 3))); +mat!(match_repetition_47, r"((..)|(.)){3}", r"aaa", Some((0, 3)), Some((2, 3)), None, Some((2, 3))); +mat!(match_repetition_50, r"((..)|(.))*", r"aaa", Some((0, 3)), Some((2, 3)), Some((0, 2)), Some((2, 3))); +mat!(match_repetition_52, r"((..)|(.))", r"aaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_53, r"((..)|(.))((..)|(.))", r"aaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_54, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 3)), None, Some((2, 3)), Some((3, 4)), None, Some((3, 4))); +mat!(match_repetition_56, r"((..)|(.)){1}", r"aaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_57, r"((..)|(.)){2}", r"aaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_59, r"((..)|(.)){3}", r"aaaa", Some((0, 4)), Some((3, 4)), Some((0, 2)), Some((3, 4))); +mat!(match_repetition_61, r"((..)|(.))*", r"aaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_63, r"((..)|(.))", r"aaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_64, r"((..)|(.))((..)|(.))", r"aaaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_65, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaaa", Some((0, 5)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None, Some((4, 5)), None, Some((4, 5))); +mat!(match_repetition_67, r"((..)|(.)){1}", r"aaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_68, r"((..)|(.)){2}", r"aaaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_70, r"((..)|(.)){3}", r"aaaaa", Some((0, 5)), Some((4, 5)), Some((2, 4)), Some((4, 5))); +mat!(match_repetition_73, r"((..)|(.))*", r"aaaaa", Some((0, 5)), Some((4, 5)), Some((2, 4)), Some((4, 5))); +mat!(match_repetition_75, r"((..)|(.))", r"aaaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_76, r"((..)|(.))((..)|(.))", r"aaaaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_77, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaaaa", Some((0, 6)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None, Some((4, 6)), Some((4, 6)), None); +mat!(match_repetition_79, r"((..)|(.)){1}", r"aaaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_80, r"((..)|(.)){2}", r"aaaaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_81, r"((..)|(.)){3}", r"aaaaaa", Some((0, 6)), Some((4, 6)), Some((4, 6)), None); +mat!(match_repetition_83, r"((..)|(.))*", r"aaaaaa", Some((0, 6)), Some((4, 6)), Some((4, 6)), None); +mat!(match_repetition_90, r"X(.?){0,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_91, r"X(.?){1,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_92, r"X(.?){2,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_93, r"X(.?){3,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_94, r"X(.?){4,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_95, r"X(.?){5,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_96, r"X(.?){6,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_97, r"X(.?){7,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_98, r"X(.?){8,}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_100, r"X(.?){0,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_102, r"X(.?){1,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_104, r"X(.?){2,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_106, r"X(.?){3,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_108, r"X(.?){4,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_110, r"X(.?){5,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_112, r"X(.?){6,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_114, r"X(.?){7,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_115, r"X(.?){8,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_126, r"(a|ab|c|bcd){0,}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_127, r"(a|ab|c|bcd){1,}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_128, r"(a|ab|c|bcd){2,}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_129, r"(a|ab|c|bcd){3,}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_130, r"(a|ab|c|bcd){4,}(d*)", r"ababcd", None); +mat!(match_repetition_131, r"(a|ab|c|bcd){0,10}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_132, r"(a|ab|c|bcd){1,10}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_133, r"(a|ab|c|bcd){2,10}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_134, r"(a|ab|c|bcd){3,10}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_135, r"(a|ab|c|bcd){4,10}(d*)", r"ababcd", None); +mat!(match_repetition_136, r"(a|ab|c|bcd)*(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_137, r"(a|ab|c|bcd)+(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_143, r"(ab|a|c|bcd){0,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_145, r"(ab|a|c|bcd){1,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_147, r"(ab|a|c|bcd){2,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_149, r"(ab|a|c|bcd){3,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_150, r"(ab|a|c|bcd){4,}(d*)", r"ababcd", None); +mat!(match_repetition_152, r"(ab|a|c|bcd){0,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_154, r"(ab|a|c|bcd){1,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_156, r"(ab|a|c|bcd){2,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_158, r"(ab|a|c|bcd){3,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_159, r"(ab|a|c|bcd){4,10}(d*)", r"ababcd", None); +mat!(match_repetition_161, r"(ab|a|c|bcd)*(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_163, r"(ab|a|c|bcd)+(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); + diff --git a/bash-5.1/vendor/regex/tests/macros.rs b/bash-5.1/vendor/regex/tests/macros.rs new file mode 100644 index 0000000..3c4b888 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/macros.rs @@ -0,0 +1,149 @@ +// Convenience macros. + +macro_rules! findall { + ($re:expr, $text:expr) => {{ + $re.find_iter(text!($text)) + .map(|m| (m.start(), m.end())).collect::<Vec<_>>() + }} +} + +// Macros for automatically producing tests. + +macro_rules! ismatch { + ($name:ident, $re:expr, $text:expr, $ismatch:expr) => { + #[test] + fn $name() { + let re = regex!($re); + assert_eq!($ismatch, re.is_match(text!($text))); + } + }; +} + +macro_rules! mat( + ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( + #[test] + fn $name() { + let text = text!($text); + let expected: Vec<Option<_>> = vec![$($loc)+]; + let r = regex!($re); + let got: Vec<Option<_>> = match r.captures(text) { + Some(c) => { + assert!(r.is_match(text)); + assert!(r.shortest_match(text).is_some()); + r.capture_names() + .enumerate() + .map(|(i, _)| c.get(i).map(|m| (m.start(), m.end()))) + .collect() + } + None => vec![None], + }; + // The test set sometimes leave out capture groups, so truncate + // actual capture groups to match test set. + let mut sgot = &got[..]; + if sgot.len() > expected.len() { + sgot = &sgot[0..expected.len()] + } + if expected != sgot { + panic!("For RE '{}' against '{:?}', \ + expected '{:?}' but got '{:?}'", + $re, text, expected, sgot); + } + } + ); +); + +macro_rules! matiter( + ($name:ident, $re:expr, $text:expr) => ( + #[test] + fn $name() { + let text = text!($text); + let expected: Vec<(usize, usize)> = vec![]; + let r = regex!($re); + let got: Vec<_> = + r.find_iter(text).map(|m| (m.start(), m.end())).collect(); + if expected != got { + panic!("For RE '{}' against '{:?}', \ + expected '{:?}' but got '{:?}'", + $re, text, expected, got); + } + let captures_got: Vec<_> = + r.captures_iter(text) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + if captures_got != got { + panic!("For RE '{}' against '{:?}', \ + got '{:?}' using find_iter but got '{:?}' \ + using captures_iter", + $re, text, got, captures_got); + } + } + ); + ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( + #[test] + fn $name() { + let text = text!($text); + let expected: Vec<_> = vec![$($loc)+]; + let r = regex!($re); + let got: Vec<_> = + r.find_iter(text).map(|m| (m.start(), m.end())).collect(); + if expected != got { + panic!("For RE '{}' against '{:?}', \ + expected '{:?}' but got '{:?}'", + $re, text, expected, got); + } + let captures_got: Vec<_> = + r.captures_iter(text) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + if captures_got != got { + panic!("For RE '{}' against '{:?}', \ + got '{:?}' using find_iter but got '{:?}' \ + using captures_iter", + $re, text, got, captures_got); + } + } + ); +); + +macro_rules! matset { + ($name:ident, $res:expr, $text:expr, $($match_index:expr),*) => { + #[test] + fn $name() { + let text = text!($text); + let set = regex_set!($res); + assert!(set.is_match(text)); + let expected = vec![$($match_index),*]; + let matches = set.matches(text); + assert!(matches.matched_any()); + let got: Vec<_> = matches.into_iter().collect(); + assert_eq!(expected, got); + } + } +} + +macro_rules! nomatset { + ($name:ident, $res:expr, $text:expr) => { + #[test] + fn $name() { + let text = text!($text); + let set = regex_set!($res); + assert!(!set.is_match(text)); + let matches = set.matches(text); + assert!(!matches.matched_any()); + assert_eq!(0, matches.into_iter().count()); + } + } +} + +macro_rules! split { + ($name:ident, $re:expr, $text:expr, $expected:expr) => { + #[test] + fn $name() { + let re = regex!($re); + let splitted: Vec<_> = re.split(t!($text)).collect(); + assert_eq!($expected, &*splitted); + } + } +} diff --git a/bash-5.1/vendor/regex/tests/macros_bytes.rs b/bash-5.1/vendor/regex/tests/macros_bytes.rs new file mode 100644 index 0000000..d6e406b --- /dev/null +++ b/bash-5.1/vendor/regex/tests/macros_bytes.rs @@ -0,0 +1,38 @@ +// Macros for use in writing tests generic over &str/&[u8]. +macro_rules! text { ($text:expr) => { $text.as_bytes() } } +macro_rules! t { ($re:expr) => { text!($re) } } +macro_rules! match_text { ($text:expr) => { $text.as_bytes() } } + +macro_rules! bytes { ($text:expr) => { $text } } + +macro_rules! no_expand { + ($text:expr) => {{ + use regex::bytes::NoExpand; + NoExpand(text!($text)) + }} +} + +macro_rules! show { + ($text:expr) => {{ + use std::ascii::escape_default; + let mut s = vec![]; + for &b in bytes!($text) { + s.extend(escape_default(b)); + } + String::from_utf8(s).unwrap() + }} +} + +macro_rules! expand { + ($name:ident, $re:expr, $text:expr, $expand:expr, $expected:expr) => { + #[test] + fn $name() { + let re = regex!($re); + let cap = re.captures(t!($text)).unwrap(); + + let mut got = vec![]; + cap.expand(t!($expand), &mut got); + assert_eq!(show!(t!($expected)), show!(&*got)); + } + } +} diff --git a/bash-5.1/vendor/regex/tests/macros_str.rs b/bash-5.1/vendor/regex/tests/macros_str.rs new file mode 100644 index 0000000..8f490f1 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/macros_str.rs @@ -0,0 +1,35 @@ +// Macros for use in writing tests generic over &str/&[u8]. +macro_rules! text { ($text:expr) => { $text } } +macro_rules! t { ($text:expr) => { text!($text) } } +macro_rules! match_text { ($text:expr) => { $text.as_str() } } + +macro_rules! no_expand { + ($text:expr) => {{ + use regex::NoExpand; + NoExpand(text!($text)) + }} +} + +macro_rules! show { ($text:expr) => { $text } } + +// N.B. The expansion API for &str and &[u8] APIs differs slightly for now, +// but they should be unified in 1.0. Then we can move this macro back into +// tests/api.rs where it is used. ---AG +macro_rules! expand { + ($name:ident, $re:expr, $text:expr, $expand:expr, $expected:expr) => { + #[test] + fn $name() { + let re = regex!($re); + let cap = re.captures(t!($text)).unwrap(); + + let mut got = String::new(); + cap.expand(t!($expand), &mut got); + assert_eq!(show!(t!($expected)), show!(&*got)); + } + } +} + +#[cfg(feature = "pattern")] +macro_rules! searcher_expr { ($e:expr) => ($e) } +#[cfg(not(feature = "pattern"))] +macro_rules! searcher_expr { ($e:expr) => ({}) } diff --git a/bash-5.1/vendor/regex/tests/misc.rs b/bash-5.1/vendor/regex/tests/misc.rs new file mode 100644 index 0000000..dfe28c9 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/misc.rs @@ -0,0 +1,14 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mat!(prefix_literal_match, r"^abc", r"abc", Some((0, 3))); +mat!(prefix_literal_nomatch, r"^abc", r"zabc", None); +mat!(one_literal_edge, r"abc", r"xxxxxab", None); +matiter!(terminates, r"a$", r"a", (0, 1)); diff --git a/bash-5.1/vendor/regex/tests/multiline.rs b/bash-5.1/vendor/regex/tests/multiline.rs new file mode 100644 index 0000000..191504a --- /dev/null +++ b/bash-5.1/vendor/regex/tests/multiline.rs @@ -0,0 +1,49 @@ +matiter!(match_multi_1, r"(?m)^[a-z]+$", "abc\ndef\nxyz", + (0, 3), (4, 7), (8, 11)); +matiter!(match_multi_2, r"(?m)^$", "abc\ndef\nxyz"); +matiter!(match_multi_3, r"(?m)^", "abc\ndef\nxyz", + (0, 0), (4, 4), (8, 8)); +matiter!(match_multi_4, r"(?m)$", "abc\ndef\nxyz", + (3, 3), (7, 7), (11, 11)); +matiter!(match_multi_5, r"(?m)^[a-z]", "abc\ndef\nxyz", + (0, 1), (4, 5), (8, 9)); +matiter!(match_multi_6, r"(?m)[a-z]^", "abc\ndef\nxyz"); +matiter!(match_multi_7, r"(?m)[a-z]$", "abc\ndef\nxyz", + (2, 3), (6, 7), (10, 11)); +matiter!(match_multi_8, r"(?m)$[a-z]", "abc\ndef\nxyz"); +matiter!(match_multi_9, r"(?m)^$", "", (0, 0)); + +matiter!(match_multi_rep_1, r"(?m)(?:^$)*", "a\nb\nc", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); +matiter!(match_multi_rep_2, r"(?m)(?:^|a)+", "a\naaa\n", + (0, 0), (2, 2), (3, 5), (6, 6)); +matiter!(match_multi_rep_3, r"(?m)(?:^|a)*", "a\naaa\n", + (0, 1), (2, 5), (6, 6)); +matiter!(match_multi_rep_4, r"(?m)(?:^[a-z])+", "abc\ndef\nxyz", + (0, 1), (4, 5), (8, 9)); +matiter!(match_multi_rep_5, r"(?m)(?:^[a-z]{3}\n?)+", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_6, r"(?m)(?:^[a-z]{3}\n?)*", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_7, r"(?m)(?:\n?[a-z]{3}$)+", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_8, r"(?m)(?:\n?[a-z]{3}$)*", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_9, r"(?m)^*", "\naa\n", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)); +matiter!(match_multi_rep_10, r"(?m)^+", "\naa\n", + (0, 0), (1, 1), (4, 4)); +matiter!(match_multi_rep_11, r"(?m)$*", "\naa\n", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)); +matiter!(match_multi_rep_12, r"(?m)$+", "\naa\n", + (0, 0), (3, 3), (4, 4)); +matiter!(match_multi_rep_13, r"(?m)(?:$\n)+", "\n\naaa\n\n", + (0, 2), (5, 7)); +matiter!(match_multi_rep_14, r"(?m)(?:$\n)*", "\n\naaa\n\n", + (0, 2), (3, 3), (4, 4), (5, 7)); +matiter!(match_multi_rep_15, r"(?m)(?:$\n^)+", "\n\naaa\n\n", + (0, 2), (5, 7)); +matiter!(match_multi_rep_16, r"(?m)(?:^|$)+", "\n\naaa\n\n", + (0, 0), (1, 1), (2, 2), (5, 5), (6, 6), (7, 7)); +matiter!(match_multi_rep_17, r"(?m)(?:$\n)*", "\n\naaa\n\n", + (0, 2), (3, 3), (4, 4), (5, 7)); diff --git a/bash-5.1/vendor/regex/tests/noparse.rs b/bash-5.1/vendor/regex/tests/noparse.rs new file mode 100644 index 0000000..62eb5be --- /dev/null +++ b/bash-5.1/vendor/regex/tests/noparse.rs @@ -0,0 +1,50 @@ +macro_rules! noparse( + ($name:ident, $re:expr) => ( + #[test] + fn $name() { + let re = $re; + match regex_new!(re) { + Err(_) => {}, + Ok(_) => panic!("Regex '{}' should cause a parse error.", re), + } + } + ); +); + +noparse!(fail_no_repeat_arg, "*"); +noparse!(fail_incomplete_escape, "\\"); +noparse!(fail_class_incomplete, "[A-"); +noparse!(fail_class_not_closed, "[A"); +noparse!(fail_class_no_begin, r"[\A]"); +noparse!(fail_class_no_end, r"[\z]"); +noparse!(fail_class_no_boundary, r"[\b]"); +noparse!(fail_open_paren, "("); +noparse!(fail_close_paren, ")"); +noparse!(fail_invalid_range, "[a-Z]"); +noparse!(fail_empty_capture_name, "(?P<>a)"); +noparse!(fail_bad_capture_name, "(?P<na-me>)"); +noparse!(fail_bad_flag, "(?a)a"); +noparse!(fail_too_big, "a{10000000}"); +noparse!(fail_counted_no_close, "a{1001"); +noparse!(fail_unfinished_cap, "(?"); +noparse!(fail_unfinished_escape, "\\"); +noparse!(fail_octal_digit, r"\8"); +noparse!(fail_hex_digit, r"\xG0"); +noparse!(fail_hex_short, r"\xF"); +noparse!(fail_hex_long_digits, r"\x{fffg}"); +noparse!(fail_flag_bad, "(?a)"); +noparse!(fail_flag_empty, "(?)"); +noparse!(fail_double_neg, "(?-i-i)"); +noparse!(fail_neg_empty, "(?i-)"); +noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); +noparse!(fail_range_end_no_class, "[a-[:lower:]]"); +noparse!(fail_range_end_no_begin, r"[a-\A]"); +noparse!(fail_range_end_no_end, r"[a-\z]"); +noparse!(fail_range_end_no_boundary, r"[a-\b]"); +noparse!(fail_empty_alt1, r"|z"); +noparse!(fail_empty_alt2, r"z|"); +noparse!(fail_empty_alt3, r"|"); +noparse!(fail_empty_alt4, r"||"); +noparse!(fail_empty_alt5, r"()|z"); +noparse!(fail_empty_alt6, r"z|()"); +noparse!(fail_empty_alt7, r"(|)"); diff --git a/bash-5.1/vendor/regex/tests/regression.rs b/bash-5.1/vendor/regex/tests/regression.rs new file mode 100644 index 0000000..1bc79ac --- /dev/null +++ b/bash-5.1/vendor/regex/tests/regression.rs @@ -0,0 +1,99 @@ +// See: https://github.com/rust-lang/regex/issues/48 +#[test] +fn invalid_regexes_no_crash() { + assert!(regex_new!("(*)").is_err()); + assert!(regex_new!("(?:?)").is_err()); + assert!(regex_new!("(?)").is_err()); + assert!(regex_new!("*").is_err()); +} + +// See: https://github.com/rust-lang/regex/issues/98 +#[test] +fn regression_many_repeat_stack_overflow() { + let re = regex!("^.{1,2500}"); + assert_eq!(vec![(0, 1)], findall!(re, "a")); +} + +// See: https://github.com/rust-lang/regex/issues/75 +mat!(regression_unsorted_binary_search_1, r"(?i)[a_]+", "A_", Some((0, 2))); +mat!(regression_unsorted_binary_search_2, r"(?i)[A_]+", "a_", Some((0, 2))); + +// See: https://github.com/rust-lang/regex/issues/99 +mat!(regression_negated_char_class_1, r"(?i)[^x]", "x", None); +mat!(regression_negated_char_class_2, r"(?i)[^x]", "X", None); + +// See: https://github.com/rust-lang/regex/issues/101 +mat!(regression_ascii_word_underscore, r"[[:word:]]", "_", Some((0, 1))); + +// See: https://github.com/rust-lang/regex/issues/129 +#[test] +fn regression_captures_rep() { + let re = regex!(r"([a-f]){2}(?P<foo>[x-z])"); + let caps = re.captures(text!("abx")).unwrap(); + assert_eq!(match_text!(caps.name("foo").unwrap()), text!("x")); +} + +// See: https://github.com/rust-lang/regex/issues/153 +mat!(regression_alt_in_alt1, r"ab?|$", "az", Some((0, 1))); +mat!(regression_alt_in_alt2, r"^(.*?)(\n|\r\n?|$)", "ab\rcd", Some((0, 3))); + +// See: https://github.com/rust-lang/regex/issues/169 +mat!(regression_leftmost_first_prefix, r"z*azb", "azb", Some((0, 3))); + +// See: https://github.com/rust-lang/regex/issues/76 +mat!(uni_case_lower_nocase_flag, r"(?i)\p{Ll}+", "ΛΘΓΔα", Some((0, 10))); + +// See: https://github.com/rust-lang/regex/issues/191 +mat!(many_alternates, r"1|2|3|4|5|6|7|8|9|10|int", "int", Some((0, 3))); + +// burntsushi was bad and didn't create an issue for this bug. +mat!(anchored_prefix1, r"^a\S", "a ", None); +mat!(anchored_prefix2, r"^a\S", "foo boo a ", None); +mat!(anchored_prefix3, r"^-[a-z]", "r-f", None); + +// See: https://github.com/rust-lang/regex/issues/204 +split!(split_on_word_boundary, r"\b", r"Should this (work?)", + &[t!(""), t!("Should"), t!(" "), t!("this"), + t!(" ("), t!("work"), t!("?)")]); +matiter!(word_boundary_dfa, r"\b", "a b c", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); + +// See: https://github.com/rust-lang/regex/issues/268 +matiter!(partial_anchor, r"^a|b", "ba", (0, 1)); + +// See: https://github.com/rust-lang/regex/issues/264 +mat!(ascii_boundary_no_capture, r"(?-u)\B", "\u{28f3e}", Some((0, 0))); +mat!(ascii_boundary_capture, r"(?-u)(\B)", "\u{28f3e}", Some((0, 0))); + +// See: https://github.com/rust-lang/regex/issues/280 +ismatch!(partial_anchor_alternate_begin, r"^a|z", "yyyyya", false); +ismatch!(partial_anchor_alternate_end, r"a$|z", "ayyyyy", false); + +// See: https://github.com/rust-lang/regex/issues/289 +mat!(lits_unambiguous1, r"(ABC|CDA|BC)X", "CDAX", Some((0, 4))); + +// See: https://github.com/rust-lang/regex/issues/291 +mat!(lits_unambiguous2, r"((IMG|CAM|MG|MB2)_|(DSCN|CIMG))(?P<n>[0-9]+)$", + "CIMG2341", Some((0, 8)), Some((0, 4)), None, Some((0, 4)), Some((4, 8))); + +// See: https://github.com/rust-lang/regex/issues/271 +mat!(end_not_wb, r"$(?-u:\B)", "\u{5c124}\u{b576c}", Some((8, 8))); +mat!(endl_or_wb, r"(?m:$)|(?-u:\b)", "\u{6084e}", Some((4, 4))); +mat!(zero_or_end, r"(?i-u:\x00)|$", "\u{e682f}", Some((4, 4))); +mat!(y_or_endl, r"(?i-u:y)|(?m:$)", "\u{b4331}", Some((4, 4))); +mat!(wb_start_x, r"(?u:\b)^(?-u:X)", "X", Some((0, 1))); + +// See: https://github.com/rust-lang/regex/issues/321 +ismatch!(strange_anchor_non_complete_prefix, r"a^{2}", "", false); +ismatch!(strange_anchor_non_complete_suffix, r"${2}a", "", false); + +// See: https://github.com/rust-lang/regex/issues/334 +mat!(captures_after_dfa_premature_end, r"a(b*(X|$))?", "abcbX", + Some((0, 1)), None, None); + +// See: https://github.com/rust-lang/regex/issues/437 +ismatch!( + literal_panic, + r"typename type\-parameter\-\d+\-\d+::.+", + "test", + false); diff --git a/bash-5.1/vendor/regex/tests/replace.rs b/bash-5.1/vendor/regex/tests/replace.rs new file mode 100644 index 0000000..28b9df9 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/replace.rs @@ -0,0 +1,44 @@ +macro_rules! replace( + ($name:ident, $which:ident, $re:expr, + $search:expr, $replace:expr, $result:expr) => ( + #[test] + fn $name() { + let re = regex!($re); + assert_eq!(re.$which(text!($search), $replace), text!($result)); + } + ); +); + +replace!(first, replace, r"\d", "age: 26", t!("Z"), "age: Z6"); +replace!(plus, replace, r"\d+", "age: 26", t!("Z"), "age: Z"); +replace!(all, replace_all, r"\d", "age: 26", t!("Z"), "age: ZZ"); +replace!(groups, replace, r"(\S+)\s+(\S+)", "w1 w2", t!("$2 $1"), "w2 w1"); +replace!(double_dollar, replace, + r"(\S+)\s+(\S+)", "w1 w2", t!("$2 $$1"), "w2 $1"); +// replace!(adjacent_index, replace, + // r"([^aeiouy])ies$", "skies", t!("$1y"), "sky"); +replace!(named, replace_all, + r"(?P<first>\S+)\s+(?P<last>\S+)(?P<space>\s*)", + "w1 w2 w3 w4", t!("$last $first$space"), "w2 w1 w4 w3"); +replace!(trim, replace_all, "^[ \t]+|[ \t]+$", " \t trim me\t \t", + t!(""), "trim me"); +replace!(number_hypen, replace, r"(.)(.)", "ab", t!("$1-$2"), "a-b"); +// replace!(number_underscore, replace, r"(.)(.)", "ab", t!("$1_$2"), "a_b"); +replace!(simple_expand, replace_all, r"(\w) (\w)", "a b", t!("$2 $1"), "b a"); +replace!(literal_dollar1, replace_all, + r"(\w+) (\w+)", "a b", t!("$$1"), "$1"); +replace!(literal_dollar2, replace_all, + r"(\w+) (\w+)", "a b", t!("$2 $$c $1"), "b $c a"); +replace!(no_expand1, replace, + r"(\S+)\s+(\S+)", "w1 w2", no_expand!("$2 $1"), "$2 $1"); +replace!(no_expand2, replace, + r"(\S+)\s+(\S+)", "w1 w2", no_expand!("$$1"), "$$1"); + +// See https://github.com/rust-lang/regex/issues/314 +replace!(match_at_start_replace_with_empty, replace_all, r"foo", "foobar", t!(""), "bar"); + +// See https://github.com/rust-lang/regex/issues/393 +replace!(single_empty_match, replace, r"^", "bar", t!("foo"), "foobar"); + +// See https://github.com/rust-lang/regex/issues/399 +replace!(capture_longest_possible_name, replace_all, r"(.)", "b", t!("${1}a $1a"), "ba "); diff --git a/bash-5.1/vendor/regex/tests/searcher.rs b/bash-5.1/vendor/regex/tests/searcher.rs new file mode 100644 index 0000000..073fa5f --- /dev/null +++ b/bash-5.1/vendor/regex/tests/searcher.rs @@ -0,0 +1,66 @@ +macro_rules! searcher { + ($name:ident, $re:expr, $haystack:expr) => ( + searcher!($name, $re, $haystack, vec vec![]); + ); + ($name:ident, $re:expr, $haystack:expr, $($steps:expr,)*) => ( + searcher!($name, $re, $haystack, vec vec![$($steps),*]); + ); + ($name:ident, $re:expr, $haystack:expr, $($steps:expr),*) => ( + searcher!($name, $re, $haystack, vec vec![$($steps),*]); + ); + ($name:ident, $re:expr, $haystack:expr, vec $expect_steps:expr) => ( + #[test] + #[allow(unused_imports)] + fn $name() { + searcher_expr! {{ + use std::str::pattern::{Pattern, Searcher}; + use std::str::pattern::SearchStep::{Match, Reject, Done}; + let re = regex!($re); + let mut se = re.into_searcher($haystack); + let mut got_steps = vec![]; + loop { + match se.next() { + Done => break, + step => { got_steps.push(step); } + } + } + assert_eq!(got_steps, $expect_steps); + }} + } + ); +} + +searcher!(searcher_empty_regex_empty_haystack, r"", "", Match(0, 0)); +searcher!(searcher_empty_regex, r"", "ab", + Match(0, 0), Reject(0, 1), Match(1, 1), Reject(1, 2), Match(2, 2)); +searcher!(searcher_empty_haystack, r"\d", ""); +searcher!(searcher_one_match, r"\d", "5", + Match(0, 1)); +searcher!(searcher_no_match, r"\d", "a", + Reject(0, 1)); +searcher!(searcher_two_adjacent_matches, r"\d", "56", + Match(0, 1), Match(1, 2)); +searcher!(searcher_two_non_adjacent_matches, r"\d", "5a6", + Match(0, 1), Reject(1, 2), Match(2, 3)); +searcher!(searcher_reject_first, r"\d", "a6", + Reject(0, 1), Match(1, 2)); +searcher!(searcher_one_zero_length_matches, r"\d*", "a1b2", + Match(0, 0), // ^ + Reject(0, 1), // a + Match(1, 2), // a1 + Reject(2, 3), // a1b + Match(3, 4), // a1b2 +); +searcher!(searcher_many_zero_length_matches, r"\d*", "a1bbb2", + Match(0, 0), // ^ + Reject(0, 1), // a + Match(1, 2), // a1 + Reject(2, 3), // a1b + Match(3, 3), // a1bb + Reject(3, 4), // a1bb + Match(4, 4), // a1bbb + Reject(4, 5), // a1bbb + Match(5, 6), // a1bbba +); +searcher!(searcher_unicode, r".+?", "Ⅰ1Ⅱ2", + Match(0, 3), Match(3, 4), Match(4, 7), Match(7, 8)); diff --git a/bash-5.1/vendor/regex/tests/set.rs b/bash-5.1/vendor/regex/tests/set.rs new file mode 100644 index 0000000..d9842ac --- /dev/null +++ b/bash-5.1/vendor/regex/tests/set.rs @@ -0,0 +1,32 @@ +matset!(set1, &["a", "a"], "a", 0, 1); +matset!(set2, &["a", "a"], "ba", 0, 1); +matset!(set3, &["a", "b"], "a", 0); +matset!(set4, &["a", "b"], "b", 1); +matset!(set5, &["a|b", "b|a"], "b", 0, 1); +matset!(set6, &["foo", "oo"], "foo", 0, 1); +matset!(set7, &["^foo", "bar$"], "foo", 0); +matset!(set8, &["^foo", "bar$"], "foo bar", 0, 1); +matset!(set9, &["^foo", "bar$"], "bar", 1); +matset!(set10, &[r"[a-z]+$", "foo"], "01234 foo", 0, 1); +matset!(set11, &[r"[a-z]+$", "foo"], "foo 01234", 1); +matset!(set12, &[r".*?", "a"], "zzzzzza", 0, 1); +matset!(set13, &[r".*", "a"], "zzzzzza", 0, 1); +matset!(set14, &[r".*", "a"], "zzzzzz", 0); +matset!(set15, &[r"\ba\b"], "hello a bye", 0); +matset!(set16, &["a"], "a", 0); +matset!(set17, &[".*a"], "a", 0); +matset!(set18, &["a", "β"], "β", 1); + +nomatset!(nset1, &["a", "a"], "b"); +nomatset!(nset2, &["^foo", "bar$"], "bar foo"); +nomatset!(nset3, { let xs: &[&str] = &[]; xs }, "a"); +nomatset!(nset4, &[r"^rooted$", r"\.log$"], "notrooted"); + +// See: https://github.com/rust-lang/regex/issues/187 +#[test] +fn regression_subsequent_matches() { + let set = regex_set!(&["ab", "b"]); + let text = text!("ba"); + assert!(set.matches(text).matched(1)); + assert!(set.matches(text).matched(1)); +} diff --git a/bash-5.1/vendor/regex/tests/shortest_match.rs b/bash-5.1/vendor/regex/tests/shortest_match.rs new file mode 100644 index 0000000..c964ab9 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/shortest_match.rs @@ -0,0 +1,14 @@ +macro_rules! shortmat { + ($name:ident, $re:expr, $text:expr, $shortest_match:expr) => { + #[test] + fn $name() { + let text = text!($text); + let re = regex!($re); + assert_eq!($shortest_match, re.shortest_match(text)); + } + } +} + +shortmat!(t01, r"a+", r"aa", Some(1)); +// Test that the reverse suffix optimization gets it right. +shortmat!(t02, r".*(?:abcd)+", r"abcdabcd", Some(4)); diff --git a/bash-5.1/vendor/regex/tests/suffix_reverse.rs b/bash-5.1/vendor/regex/tests/suffix_reverse.rs new file mode 100644 index 0000000..f299355 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/suffix_reverse.rs @@ -0,0 +1,16 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mat!(t01, r".*abcd", r"abcd", Some((0, 4))); +mat!(t02, r".*(?:abcd)+", r"abcd", Some((0, 4))); +mat!(t03, r".*(?:abcd)+", r"abcdabcd", Some((0, 8))); +mat!(t04, r".*(?:abcd)+", r"abcdxabcd", Some((0, 9))); +mat!(t05, r".*x(?:abcd)+", r"abcdxabcd", Some((0, 9))); +mat!(t06, r"[^abcd]*x(?:abcd)+", r"abcdxabcd", Some((4, 9))); diff --git a/bash-5.1/vendor/regex/tests/test_backtrack.rs b/bash-5.1/vendor/regex/tests/test_backtrack.rs new file mode 100644 index 0000000..5516c84 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_backtrack.rs @@ -0,0 +1,64 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .bounded_backtracking().build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .bounded_backtracking() + .build() + .map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff --git a/bash-5.1/vendor/regex/tests/test_backtrack_bytes.rs b/bash-5.1/vendor/regex/tests/test_backtrack_bytes.rs new file mode 100644 index 0000000..4ea60e7 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_backtrack_bytes.rs @@ -0,0 +1,65 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .bounded_backtracking() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .bounded_backtracking() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_bytes.rs"); +include!("macros.rs"); + +mod api; +mod bytes; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_ascii; diff --git a/bash-5.1/vendor/regex/tests/test_backtrack_utf8bytes.rs b/bash-5.1/vendor/regex/tests/test_backtrack_utf8bytes.rs new file mode 100644 index 0000000..a170d19 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_backtrack_utf8bytes.rs @@ -0,0 +1,65 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .bounded_backtracking().bytes(true).build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .bounded_backtracking() + .bytes(true) + .build() + .map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff --git a/bash-5.1/vendor/regex/tests/test_default.rs b/bash-5.1/vendor/regex/tests/test_default.rs new file mode 100644 index 0000000..e6cf92f --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_default.rs @@ -0,0 +1,77 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +// Due to macro scoping rules, this definition only applies for the modules +// defined below. Effectively, it allows us to use the same tests for both +// native and dynamic regexes. +// +// This is also used to test the various matching engines. This one exercises +// the normal code path which automatically chooses the engine based on the +// regex and the input. Other dynamic tests explicitly set the engine to use. +macro_rules! regex_new { + ($re:expr) => {{ + use regex::Regex; + Regex::new($re) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::RegexSet; + RegexSet::new($re) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod misc; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod shortest_match; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; + +#[test] +fn disallow_non_utf8() { + assert!(regex::Regex::new(r"(?-u)\xFF").is_err()); + assert!(regex::Regex::new(r"(?-u).").is_err()); + assert!(regex::Regex::new(r"(?-u)[\xFF]").is_err()); + assert!(regex::Regex::new(r"(?-u)☃").is_err()); +} diff --git a/bash-5.1/vendor/regex/tests/test_default_bytes.rs b/bash-5.1/vendor/regex/tests/test_default_bytes.rs new file mode 100644 index 0000000..3ac3ce4 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_default_bytes.rs @@ -0,0 +1,73 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::bytes::Regex; + Regex::new($re) + }} +} + +macro_rules! regex_set_new { + ($res:expr) => {{ + use regex::bytes::RegexSet; + RegexSet::new($res) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_bytes.rs"); +include!("macros.rs"); + +// A silly wrapper to make it possible to write and match raw bytes. +struct R<'a>(&'a [u8]); +impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } + +// See: https://github.com/rust-lang/regex/issues/321 +// +// These tests are here because they do not have the same behavior in every +// regex engine. +mat!(invalid_utf8_nfa1, r".", R(b"\xD4\xC2\x65\x2B\x0E\xFE"), Some((2, 3))); +mat!(invalid_utf8_nfa2, r"${2}ä", R(b"\xD4\xC2\x65\x2B\x0E\xFE"), None); +mat!(invalid_utf8_nfa3, r".", R(b"\x0A\xDB\x82\x6E\x33\x01\xDD\x33\xCD"), + Some((1, 3))); +mat!(invalid_utf8_nfa4, r"${2}ä", R(b"\x0A\xDB\x82\x6E\x33\x01\xDD\x33\xCD"), + None); + +mod api; +mod bytes; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod set; +mod shortest_match; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_ascii; diff --git a/bash-5.1/vendor/regex/tests/test_nfa.rs b/bash-5.1/vendor/regex/tests/test_nfa.rs new file mode 100644 index 0000000..8a831c4 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_nfa.rs @@ -0,0 +1,60 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re).nfa().build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re).nfa().build().map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff --git a/bash-5.1/vendor/regex/tests/test_nfa_bytes.rs b/bash-5.1/vendor/regex/tests/test_nfa_bytes.rs new file mode 100644 index 0000000..f376cef --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_nfa_bytes.rs @@ -0,0 +1,65 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .nfa() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .nfa() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_bytes.rs"); +include!("macros.rs"); + +mod api; +mod bytes; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_ascii; diff --git a/bash-5.1/vendor/regex/tests/test_nfa_utf8bytes.rs b/bash-5.1/vendor/regex/tests/test_nfa_utf8bytes.rs new file mode 100644 index 0000000..5d13685 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/test_nfa_utf8bytes.rs @@ -0,0 +1,61 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re).nfa().bytes(true).build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .nfa().bytes(true).build().map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff --git a/bash-5.1/vendor/regex/tests/unicode.rs b/bash-5.1/vendor/regex/tests/unicode.rs new file mode 100644 index 0000000..9b65bc2 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/unicode.rs @@ -0,0 +1,110 @@ +mat!(uni_literal, r"☃", "☃", Some((0, 3))); +mat!(uni_literal_plus, r"☃+", "☃", Some((0, 3))); +mat!(uni_literal_casei_plus, r"(?i)☃+", "☃", Some((0, 3))); +mat!(uni_class_plus, r"[☃Ⅰ]+", "☃", Some((0, 3))); +mat!(uni_one, r"\pN", "Ⅰ", Some((0, 3))); +mat!(uni_mixed, r"\pN+", "Ⅰ1Ⅱ2", Some((0, 8))); +mat!(uni_not, r"\PN+", "abⅠ", Some((0, 2))); +mat!(uni_not_class, r"[\PN]+", "abⅠ", Some((0, 2))); +mat!(uni_not_class_neg, r"[^\PN]+", "abⅠ", Some((2, 5))); +mat!(uni_case, r"(?i)Δ", "δ", Some((0, 2))); +mat!(uni_case_upper, r"\p{Lu}+", "ΛΘΓΔα", Some((0, 8))); +mat!(uni_case_upper_nocase_flag, r"(?i)\p{Lu}+", "ΛΘΓΔα", Some((0, 10))); +mat!(uni_case_upper_nocase, r"\p{L}+", "ΛΘΓΔα", Some((0, 10))); +mat!(uni_case_lower, r"\p{Ll}+", "ΛΘΓΔα", Some((8, 10))); + +// Test the Unicode friendliness of Perl character classes. +mat!(uni_perl_w, r"\w+", "dδd", Some((0, 4))); +mat!(uni_perl_w_not, r"\w+", "⥡", None); +mat!(uni_perl_w_neg, r"\W+", "⥡", Some((0, 3))); +mat!(uni_perl_d, r"\d+", "1२३9", Some((0, 8))); +mat!(uni_perl_d_not, r"\d+", "Ⅱ", None); +mat!(uni_perl_d_neg, r"\D+", "Ⅱ", Some((0, 3))); +mat!(uni_perl_s, r"\s+", " ", Some((0, 3))); +mat!(uni_perl_s_not, r"\s+", "☃", None); +mat!(uni_perl_s_neg, r"\S+", "☃", Some((0, 3))); + +// And do the same for word boundaries. +mat!(uni_boundary_none, r"\d\b", "6δ", None); +mat!(uni_boundary_ogham, r"\d\b", "6 ", Some((0, 1))); +mat!(uni_not_boundary_none, r"\d\B", "6δ", Some((0, 1))); +mat!(uni_not_boundary_ogham, r"\d\B", "6 ", None); + +// Test general categories. +// +// We should test more, but there's a lot. Write a script to generate more of +// these tests. +mat!(uni_class_gencat_cased_letter, + r"\p{Cased_Letter}", "A", Some((0, 3))); +mat!(uni_class_gencat_close_punctuation, + r"\p{Close_Punctuation}", "❯", Some((0, 3))); +mat!(uni_class_gencat_connector_punctuation, + r"\p{Connector_Punctuation}", "⁀", Some((0, 3))); +mat!(uni_class_gencat_control, + r"\p{Control}", "\u{9f}", Some((0, 2))); +mat!(uni_class_gencat_currency_symbol, + r"\p{Currency_Symbol}", "£", Some((0, 3))); +mat!(uni_class_gencat_dash_punctuation, + r"\p{Dash_Punctuation}", "〰", Some((0, 3))); +mat!(uni_class_gencat_decimal_numer, + r"\p{Decimal_Number}", "𑓙", Some((0, 4))); +mat!(uni_class_gencat_enclosing_mark, + r"\p{Enclosing_Mark}", "\u{A672}", Some((0, 3))); +mat!(uni_class_gencat_final_punctuation, + r"\p{Final_Punctuation}", "⸡", Some((0, 3))); +mat!(uni_class_gencat_format, + r"\p{Format}", "\u{E007F}", Some((0, 4))); +mat!(uni_class_gencat_initial_punctuation, + r"\p{Initial_Punctuation}", "⸜", Some((0, 3))); +mat!(uni_class_gencat_letter, + r"\p{Letter}", "Έ", Some((0, 2))); +mat!(uni_class_gencat_letter_number, + r"\p{Letter_Number}", "ↂ", Some((0, 3))); +mat!(uni_class_gencat_line_separator, + r"\p{Line_Separator}", "\u{2028}", Some((0, 3))); +mat!(uni_class_gencat_lowercase_letter, + r"\p{Lowercase_Letter}", "ϛ", Some((0, 2))); +mat!(uni_class_gencat_mark, + r"\p{Mark}", "\u{E01EF}", Some((0, 4))); +mat!(uni_class_gencat_math, + r"\p{Math}", "⋿", Some((0, 3))); +mat!(uni_class_gencat_modifier_letter, + r"\p{Modifier_Letter}", "𖭃", Some((0, 4))); +mat!(uni_class_gencat_modifier_symbol, + r"\p{Modifier_Symbol}", "🏿", Some((0, 4))); +mat!(uni_class_gencat_nonspacing_mark, + r"\p{Nonspacing_Mark}", "\u{1E94A}", Some((0, 4))); +mat!(uni_class_gencat_number, + r"\p{Number}", "⓿", Some((0, 3))); +mat!(uni_class_gencat_open_punctuation, + r"\p{Open_Punctuation}", "⦅", Some((0, 3))); +mat!(uni_class_gencat_other, + r"\p{Other}", "\u{bc9}", Some((0, 3))); +mat!(uni_class_gencat_other_letter, + r"\p{Other_Letter}", "ꓷ", Some((0, 3))); +mat!(uni_class_gencat_other_number, + r"\p{Other_Number}", "㉏", Some((0, 3))); +mat!(uni_class_gencat_other_punctuation, + r"\p{Other_Punctuation}", "𞥞", Some((0, 4))); +mat!(uni_class_gencat_other_symbol, + r"\p{Other_Symbol}", "⅌", Some((0, 3))); +mat!(uni_class_gencat_paragraph_separator, + r"\p{Paragraph_Separator}", "\u{2029}", Some((0, 3))); +mat!(uni_class_gencat_private_use, + r"\p{Private_Use}", "\u{10FFFD}", Some((0, 4))); +mat!(uni_class_gencat_punctuation, + r"\p{Punctuation}", "𑁍", Some((0, 4))); +mat!(uni_class_gencat_separator, + r"\p{Separator}", "\u{3000}", Some((0, 3))); +mat!(uni_class_gencat_space_separator, + r"\p{Space_Separator}", "\u{205F}", Some((0, 3))); +mat!(uni_class_gencat_spacing_mark, + r"\p{Spacing_Mark}", "\u{16F7E}", Some((0, 4))); +mat!(uni_class_gencat_symbol, + r"\p{Symbol}", "⯈", Some((0, 3))); +mat!(uni_class_gencat_titlecase_letter, + r"\p{Titlecase_Letter}", "ῼ", Some((0, 3))); +mat!(uni_class_gencat_unassigned, + r"\p{Unassigned}", "\u{10FFFF}", Some((0, 4))); +mat!(uni_class_gencat_uppercase_letter, + r"\p{Uppercase_Letter}", "Ꝋ", Some((0, 3))); diff --git a/bash-5.1/vendor/regex/tests/word_boundary.rs b/bash-5.1/vendor/regex/tests/word_boundary.rs new file mode 100644 index 0000000..7fe97a2 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/word_boundary.rs @@ -0,0 +1,89 @@ +// Many of these are cribbed from RE2's test suite. + +matiter!(wb1, r"\b", ""); +matiter!(wb2, r"\b", "a", (0, 0), (1, 1)); +matiter!(wb3, r"\b", "ab", (0, 0), (2, 2)); +matiter!(wb4, r"^\b", "ab", (0, 0)); +matiter!(wb5, r"\b$", "ab", (2, 2)); +matiter!(wb6, r"^\b$", "ab"); +matiter!(wb7, r"\bbar\b", "nobar bar foo bar", (6, 9), (14, 17)); +matiter!(wb8, r"a\b", "faoa x", (3, 4)); +matiter!(wb9, r"\bbar", "bar x", (0, 3)); +matiter!(wb10, r"\bbar", "foo\nbar x", (4, 7)); +matiter!(wb11, r"bar\b", "foobar", (3, 6)); +matiter!(wb12, r"bar\b", "foobar\nxxx", (3, 6)); +matiter!(wb13, r"(foo|bar|[A-Z])\b", "foo", (0, 3)); +matiter!(wb14, r"(foo|bar|[A-Z])\b", "foo\n", (0, 3)); +matiter!(wb15, r"\b(foo|bar|[A-Z])", "foo", (0, 3)); +matiter!(wb16, r"\b(foo|bar|[A-Z])\b", "X", (0, 1)); +matiter!(wb17, r"\b(foo|bar|[A-Z])\b", "XY"); +matiter!(wb18, r"\b(foo|bar|[A-Z])\b", "bar", (0, 3)); +matiter!(wb19, r"\b(foo|bar|[A-Z])\b", "foo", (0, 3)); +matiter!(wb20, r"\b(foo|bar|[A-Z])\b", "foo\n", (0, 3)); +matiter!(wb21, r"\b(foo|bar|[A-Z])\b", "ffoo bbar N x", (10, 11)); +matiter!(wb22, r"\b(fo|foo)\b", "fo", (0, 2)); +matiter!(wb23, r"\b(fo|foo)\b", "foo", (0, 3)); +matiter!(wb24, r"\b\b", ""); +matiter!(wb25, r"\b\b", "a", (0, 0), (1, 1)); +matiter!(wb26, r"\b$", ""); +matiter!(wb27, r"\b$", "x", (1, 1)); +matiter!(wb28, r"\b$", "y x", (3, 3)); +matiter!(wb29, r"\b.$", "x", (0, 1)); +matiter!(wb30, r"^\b(fo|foo)\b", "fo", (0, 2)); +matiter!(wb31, r"^\b(fo|foo)\b", "foo", (0, 3)); +matiter!(wb32, r"^\b$", ""); +matiter!(wb33, r"^\b$", "x"); +matiter!(wb34, r"^\b.$", "x", (0, 1)); +matiter!(wb35, r"^\b.\b$", "x", (0, 1)); +matiter!(wb36, r"^^^^^\b$$$$$", ""); +matiter!(wb37, r"^^^^^\b.$$$$$", "x", (0, 1)); +matiter!(wb38, r"^^^^^\b$$$$$", "x"); +matiter!(wb39, r"^^^^^\b\b\b.\b\b\b$$$$$", "x", (0, 1)); +matiter!(wb40, r"\b.+\b", "$$abc$$", (2, 5)); +matiter!(wb41, r"\b", "a b c", (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); + +matiter!(nb1, r"\Bfoo\B", "n foo xfoox that", (7, 10)); +matiter!(nb2, r"a\B", "faoa x", (1, 2)); +matiter!(nb3, r"\Bbar", "bar x"); +matiter!(nb4, r"\Bbar", "foo\nbar x"); +matiter!(nb5, r"bar\B", "foobar"); +matiter!(nb6, r"bar\B", "foobar\nxxx"); +matiter!(nb7, r"(foo|bar|[A-Z])\B", "foox", (0, 3)); +matiter!(nb8, r"(foo|bar|[A-Z])\B", "foo\n"); +matiter!(nb9, r"\B", "", (0, 0)); +matiter!(nb10, r"\B", "x"); +matiter!(nb11, r"\B(foo|bar|[A-Z])", "foo"); +matiter!(nb12, r"\B(foo|bar|[A-Z])\B", "xXy", (1, 2)); +matiter!(nb13, r"\B(foo|bar|[A-Z])\B", "XY"); +matiter!(nb14, r"\B(foo|bar|[A-Z])\B", "XYZ", (1, 2)); +matiter!(nb15, r"\B(foo|bar|[A-Z])\B", "abara", (1, 4)); +matiter!(nb16, r"\B(foo|bar|[A-Z])\B", "xfoo_", (1, 4)); +matiter!(nb17, r"\B(foo|bar|[A-Z])\B", "xfoo\n"); +matiter!(nb18, r"\B(foo|bar|[A-Z])\B", "foo bar vNX", (9, 10)); +matiter!(nb19, r"\B(fo|foo)\B", "xfoo", (1, 3)); +matiter!(nb20, r"\B(foo|fo)\B", "xfooo", (1, 4)); +matiter!(nb21, r"\B\B", "", (0, 0)); +matiter!(nb22, r"\B\B", "x"); +matiter!(nb23, r"\B$", "", (0, 0)); +matiter!(nb24, r"\B$", "x"); +matiter!(nb25, r"\B$", "y x"); +matiter!(nb26, r"\B.$", "x"); +matiter!(nb27, r"^\B(fo|foo)\B", "fo"); +matiter!(nb28, r"^\B(fo|foo)\B", "foo"); +matiter!(nb29, r"^\B", "", (0, 0)); +matiter!(nb30, r"^\B", "x"); +matiter!(nb31, r"^\B\B", "", (0, 0)); +matiter!(nb32, r"^\B\B", "x"); +matiter!(nb33, r"^\B$", "", (0, 0)); +matiter!(nb34, r"^\B$", "x"); +matiter!(nb35, r"^\B.$", "x"); +matiter!(nb36, r"^\B.\B$", "x"); +matiter!(nb37, r"^^^^^\B$$$$$", "", (0, 0)); +matiter!(nb38, r"^^^^^\B.$$$$$", "x"); +matiter!(nb39, r"^^^^^\B$$$$$", "x"); + +// These work for both Unicode and ASCII because all matches are reported as +// byte offsets, and « and » do not correspond to word boundaries at either +// the character or byte level. +matiter!(unicode1, r"\bx\b", "«x", (2, 3)); +matiter!(unicode2, r"\bx\b", "x»", (0, 1)); diff --git a/bash-5.1/vendor/regex/tests/word_boundary_ascii.rs b/bash-5.1/vendor/regex/tests/word_boundary_ascii.rs new file mode 100644 index 0000000..5a3cf11 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/word_boundary_ascii.rs @@ -0,0 +1,9 @@ +// ASCII word boundaries are completely oblivious to Unicode characters. +// For Unicode word boundaries, the tests are precisely inverted. +matiter!(ascii1, r"(?-u:\b)x(?-u:\b)", "áxβ", (2, 3)); +matiter!(ascii2, r"(?-u:\B)x(?-u:\B)", "áxβ"); +matiter!(ascii3, r"(?-u:\B)", "0\u{7EF5E}", (2, 2), (3, 3), (4, 4), (5, 5)); + +// We still get Unicode word boundaries by default in byte regexes. +matiter!(unicode1, r"\bx\b", "áxβ"); +matiter!(unicode2, r"\Bx\B", "áxβ", (2, 3)); diff --git a/bash-5.1/vendor/regex/tests/word_boundary_unicode.rs b/bash-5.1/vendor/regex/tests/word_boundary_unicode.rs new file mode 100644 index 0000000..43612a9 --- /dev/null +++ b/bash-5.1/vendor/regex/tests/word_boundary_unicode.rs @@ -0,0 +1,8 @@ +// Unicode word boundaries know about Unicode characters. +// For ASCII word boundaries, the tests are precisely inverted. +matiter!(unicode1, r"\bx\b", "áxβ"); +matiter!(unicode2, r"\Bx\B", "áxβ", (2, 3)); + +matiter!(ascii1, r"(?-u:\b)x(?-u:\b)", "áxβ", (2, 3)); +matiter!(ascii2, r"(?-u:\B)x(?-u:\B)", "áxβ"); +matiter!(ascii3, r"(?-u:\B)", "0\u{7EF5E}", (5, 5)); diff --git a/bash-5.1/vendor/rustc-serialize/.cargo-checksum.json b/bash-5.1/vendor/rustc-serialize/.cargo-checksum.json new file mode 100644 index 0000000..5c6ba3c --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"01199fa6ca6337a7513e9ef8951268b8882347e5affaa50e710ac4960d9c65e0","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"0aebc3beb6fc32d6073582d5fea170761689a2c83cddb5436aa26e57b7d04e7b","appveyor.yml":"da991211b72fa6f231af7adb84c9fb72f5a9131d1c0a3d47b8ceffe5a82c8542","benches/base64.rs":"96f7d0c7d260362e41b8cefb4839f1e1b3c18c2f10344f6ccafac7c434f99ca9","benches/hex.rs":"057821307b4b7de02f2c267f9248457386035382916c5afe4b72d6f2e905062c","benches/json.rs":"659f2ae2e1ad5ed022fafce6418d17dfe09c3dcb3f054857dce0effc907da850","src/base64.rs":"57649c590c1fba643ff955910f1d4427feda43414bb0863cd279bea56c3ff178","src/collection_impls.rs":"8ae6bc0d61a4777d834c2b24fa987550cb13c570e1564f87ee32eceff3cb2d5b","src/hex.rs":"a2ba86cf47035b5d9cbf4adf8dc3e941d4e0a6ce1a61a29cbb14ea1fdabac6bb","src/json.rs":"75a788a46612c73bfd14af20fb48855dc8c930747c5255a288d2d09de25ea960","src/lib.rs":"a0e4a368a609f019434e7584f54448cf33ebf3e37e3fb1dd5537d300088184b1","src/serialize.rs":"7ddcc3c32843850e30d05b82a8cda8ae63ec0016e2b0bfbcc46a03ea3ea986e8"},"package":"dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda"} \ No newline at end of file diff --git a/bash-5.1/vendor/rustc-serialize/Cargo.toml b/bash-5.1/vendor/rustc-serialize/Cargo.toml new file mode 100644 index 0000000..2f44e0c --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/Cargo.toml @@ -0,0 +1,18 @@ +[package] + +name = "rustc-serialize" +version = "0.3.24" +authors = ["The Rust Project Developers"] +license = "MIT/Apache-2.0" +readme = "README.md" +repository = "https://github.com/rust-lang/rustc-serialize" +homepage = "https://github.com/rust-lang/rustc-serialize" +documentation = "https://doc.rust-lang.org/rustc-serialize" +description = """ +Generic serialization/deserialization support corresponding to the +`derive(RustcEncodable, RustcDecodable)` mode in the compiler. Also includes +support for hex, base64, and json encoding and decoding. +""" + +[dev-dependencies] +rand = "0.3" diff --git a/bash-5.1/vendor/rustc-serialize/LICENSE-APACHE b/bash-5.1/vendor/rustc-serialize/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/rustc-serialize/LICENSE-MIT b/bash-5.1/vendor/rustc-serialize/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/rustc-serialize/README.md b/bash-5.1/vendor/rustc-serialize/README.md new file mode 100644 index 0000000..f680842 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/README.md @@ -0,0 +1,31 @@ +# rustc-serialize + +> **NOTE**: This crate is deprecated in favor of [`serde`]. No new feature +> development will happen in this crate, although bug fixes proposed through PRs +> will still be merged. It is very highly recommended by the Rust Library Team +> that you use [`serde`], not this crate. + +[`serde`]: https://serde.rs + +Serialization and deserialization support provided by the compiler in the form +of `derive(RustcEncodable, RustcDecodable)`. + +[![Linux Build Status](https://travis-ci.org/rust-lang-nursery/rustc-serialize.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/rustc-serialize) +[![Windows Build Status](https://ci.appveyor.com/api/projects/status/ka194de75aapwpft?svg=true)](https://ci.appveyor.com/project/alexcrichton/rustc-serialize) + +[Documentation](https://doc.rust-lang.org/rustc-serialize) + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +rustc-serialize = "0.3" +``` + +and this to your crate root: + +```rust +extern crate rustc_serialize; +``` diff --git a/bash-5.1/vendor/rustc-serialize/appveyor.yml b/bash-5.1/vendor/rustc-serialize/appveyor.yml new file mode 100644 index 0000000..6a1b8dc --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/appveyor.yml @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose diff --git a/bash-5.1/vendor/rustc-serialize/benches/base64.rs b/bash-5.1/vendor/rustc-serialize/benches/base64.rs new file mode 100644 index 0000000..6a6565b --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/benches/base64.rs @@ -0,0 +1,48 @@ +#![feature(test)] + +extern crate test; +extern crate rustc_serialize; + +use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; +use test::Bencher; + +#[bench] +fn bench_to_base64(b: &mut Bencher) { + let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ + ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; + b.iter(|| { + s.as_bytes().to_base64(STANDARD); + }); + b.bytes = s.len() as u64; +} + +#[bench] +fn bench_from_base64(b: &mut Bencher) { + let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ + ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; + let sb = s.as_bytes().to_base64(STANDARD); + b.iter(|| { + sb.from_base64().unwrap(); + }); + b.bytes = sb.len() as u64; +} + + +#[bench] +fn bench_to_base64_large(b: &mut Bencher) { + let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); + b.iter(|| { + s.to_base64(STANDARD); + }); + b.bytes = s.len() as u64; +} + +#[bench] +fn bench_from_base64_large(b: &mut Bencher) { + let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); + let sb = s.to_base64(STANDARD); + b.iter(|| { + sb.from_base64().unwrap(); + }); + b.bytes = sb.len() as u64; +} diff --git a/bash-5.1/vendor/rustc-serialize/benches/hex.rs b/bash-5.1/vendor/rustc-serialize/benches/hex.rs new file mode 100644 index 0000000..97a7735 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/benches/hex.rs @@ -0,0 +1,28 @@ +#![feature(test)] + +extern crate test; +extern crate rustc_serialize; + +use test::Bencher; +use rustc_serialize::hex::{FromHex, ToHex}; + +#[bench] +fn bench_to_hex(b: &mut Bencher) { + let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ + ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; + b.iter(|| { + s.as_bytes().to_hex(); + }); + b.bytes = s.len() as u64; +} + +#[bench] +fn bench_from_hex(b: &mut Bencher) { + let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ + ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; + let sb = s.as_bytes().to_hex(); + b.iter(|| { + sb.from_hex().unwrap(); + }); + b.bytes = sb.len() as u64; +} diff --git a/bash-5.1/vendor/rustc-serialize/benches/json.rs b/bash-5.1/vendor/rustc-serialize/benches/json.rs new file mode 100644 index 0000000..20768e1 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/benches/json.rs @@ -0,0 +1,84 @@ +#![feature(test)] + +extern crate test; +extern crate rustc_serialize; + +use std::string; +use rustc_serialize::json::{Json, Parser}; +use test::Bencher; + +#[bench] +fn bench_streaming_small(b: &mut Bencher) { + b.iter( || { + let mut parser = Parser::new( + r#"{ + "a": 1.0, + "b": [ + true, + "foo\nbar", + { "c": {"d": null} } + ] + }"#.chars() + ); + loop { + match parser.next() { + None => return, + _ => {} + } + } + }); +} +#[bench] +fn bench_small(b: &mut Bencher) { + b.iter( || { + let _ = Json::from_str(r#"{ + "a": 1.0, + "b": [ + true, + "foo\nbar", + { "c": {"d": null} } + ] + }"#); + }); +} + +#[bench] +fn bench_decode_hex_escape(b: &mut Bencher) { + let mut src = "\"".to_string(); + for _ in 0..10 { + src.push_str("\\uF975\\uf9bc\\uF9A0\\uF9C4\\uF975\\uf9bc\\uF9A0\\uF9C4"); + } + src.push_str("\""); + b.iter( || { + let _ = Json::from_str(&src); + }); +} + +fn big_json() -> string::String { + let mut src = "[\n".to_string(); + for _ in 0..500 { + src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \ + [1,2,3]},"#); + } + src.push_str("{}]"); + return src; +} + +#[bench] +fn bench_streaming_large(b: &mut Bencher) { + let src = big_json(); + b.iter( || { + let mut parser = Parser::new(src.chars()); + loop { + match parser.next() { + None => return, + _ => {} + } + } + }); +} +#[bench] +fn bench_large(b: &mut Bencher) { + let src = big_json(); + b.iter( || { let _ = Json::from_str(&src); }); +} diff --git a/bash-5.1/vendor/rustc-serialize/src/base64.rs b/bash-5.1/vendor/rustc-serialize/src/base64.rs new file mode 100644 index 0000000..3c346b8 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/src/base64.rs @@ -0,0 +1,489 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +// +// ignore-lexer-test FIXME #15679 + +//! Base64 binary-to-text encoding + +pub use self::FromBase64Error::*; +pub use self::CharacterSet::*; + +use std::fmt; +use std::error; + +/// Available encoding character sets +#[derive(Clone, Copy, Debug)] +pub enum CharacterSet { + /// The standard character set (uses `+` and `/`) + Standard, + /// The URL safe character set (uses `-` and `_`) + UrlSafe +} + +/// Available newline types +#[derive(Clone, Copy, Debug)] +pub enum Newline { + /// A linefeed (i.e. Unix-style newline) + LF, + /// A carriage return and a linefeed (i.e. Windows-style newline) + CRLF +} + +/// Contains configuration parameters for `to_base64`. +#[derive(Clone, Copy, Debug)] +pub struct Config { + /// Character set to use + pub char_set: CharacterSet, + /// Newline to use + pub newline: Newline, + /// True to pad output with `=` characters + pub pad: bool, + /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping + pub line_length: Option<usize> +} + +/// Configuration for RFC 4648 standard base64 encoding +pub static STANDARD: Config = + Config {char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None}; + +/// Configuration for RFC 4648 base64url encoding +pub static URL_SAFE: Config = + Config {char_set: UrlSafe, newline: Newline::CRLF, pad: false, line_length: None}; + +/// Configuration for RFC 2045 MIME base64 encoding +pub static MIME: Config = + Config {char_set: Standard, newline: Newline::CRLF, pad: true, line_length: Some(76)}; + +static STANDARD_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ + abcdefghijklmnopqrstuvwxyz\ + 0123456789+/"; + +static URLSAFE_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ + abcdefghijklmnopqrstuvwxyz\ + 0123456789-_"; + +/// A trait for converting a value to base64 encoding. +pub trait ToBase64 { + /// Converts the value of `self` to a base64 value following the specified + /// format configuration, returning the owned string. + fn to_base64(&self, config: Config) -> String; +} + +impl ToBase64 for [u8] { + /// Turn a vector of `u8` bytes into a base64 string. + /// + /// # Example + /// + /// ```rust + /// extern crate rustc_serialize; + /// use rustc_serialize::base64::{ToBase64, STANDARD}; + /// + /// fn main () { + /// let str = [52,32].to_base64(STANDARD); + /// println!("base 64 output: {:?}", str); + /// } + /// ``` + fn to_base64(&self, config: Config) -> String { + let bytes = match config.char_set { + Standard => STANDARD_CHARS, + UrlSafe => URLSAFE_CHARS + }; + + let len = self.len(); + let newline = match config.newline { + Newline::LF => "\n", + Newline::CRLF => "\r\n", + }; + + // Preallocate memory. + let mut prealloc_len = (len + 2) / 3 * 4; + if let Some(line_length) = config.line_length { + let num_lines = match prealloc_len { + 0 => 0, + n => (n - 1) / line_length + }; + prealloc_len += num_lines * newline.bytes().count(); + } + + let mut out_bytes = vec![b'='; prealloc_len]; + + // Deal with padding bytes + let mod_len = len % 3; + + // Use iterators to reduce branching + { + let mut cur_length = 0; + + let mut s_in = self[..len - mod_len].iter().map(|&x| x as u32); + let mut s_out = out_bytes.iter_mut(); + + // Convenient shorthand + let enc = |val| bytes[val as usize]; + let mut write = |val| *s_out.next().unwrap() = val; + + // Iterate though blocks of 4 + while let (Some(first), Some(second), Some(third)) = + (s_in.next(), s_in.next(), s_in.next()) { + + // Line break if needed + if let Some(line_length) = config.line_length { + if cur_length >= line_length { + for b in newline.bytes() { write(b) }; + cur_length = 0; + } + } + + let n = first << 16 | second << 8 | third; + + // This 24-bit number gets separated into four 6-bit numbers. + write(enc((n >> 18) & 63)); + write(enc((n >> 12) & 63)); + write(enc((n >> 6 ) & 63)); + write(enc((n >> 0 ) & 63)); + + cur_length += 4; + } + + // Line break only needed if padding is required + if mod_len != 0 { + if let Some(line_length) = config.line_length { + if cur_length >= line_length { + for b in newline.bytes() { write(b) }; + } + } + } + + // Heh, would be cool if we knew this was exhaustive + // (the dream of bounded integer types) + match mod_len { + 0 => (), + 1 => { + let n = (self[len-1] as u32) << 16; + write(enc((n >> 18) & 63)); + write(enc((n >> 12) & 63)); + } + 2 => { + let n = (self[len-2] as u32) << 16 | + (self[len-1] as u32) << 8; + write(enc((n >> 18) & 63)); + write(enc((n >> 12) & 63)); + write(enc((n >> 6 ) & 63)); + } + _ => panic!("Algebra is broken, please alert the math police") + } + } + + // We get padding for "free", so only have to drop it if unwanted. + if !config.pad { + while let Some(&b'=') = out_bytes.last() { + out_bytes.pop(); + } + } + + unsafe { String::from_utf8_unchecked(out_bytes) } + } +} + +impl<'a, T: ?Sized + ToBase64> ToBase64 for &'a T { + fn to_base64(&self, config: Config) -> String { + (**self).to_base64(config) + } +} + +/// A trait for converting from base64 encoded values. +pub trait FromBase64 { + /// Converts the value of `self`, interpreted as base64 encoded data, into + /// an owned vector of bytes, returning the vector. + fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>; +} + +/// Errors that can occur when decoding a base64 encoded string +#[derive(Clone, Copy)] +pub enum FromBase64Error { + /// The input contained a character not part of the base64 format + InvalidBase64Byte(u8, usize), + /// The input had an invalid length + InvalidBase64Length, +} + +impl fmt::Debug for FromBase64Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + InvalidBase64Byte(ch, idx) => + write!(f, "Invalid character '{}' at position {}", ch, idx), + InvalidBase64Length => write!(f, "Invalid length"), + } + } +} + +impl error::Error for FromBase64Error { + fn description(&self) -> &str { + match *self { + InvalidBase64Byte(_, _) => "invalid character", + InvalidBase64Length => "invalid length", + } + } +} + +impl fmt::Display for FromBase64Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self, f) + } +} + +impl FromBase64 for str { + /// Convert any base64 encoded string (literal, `@`, `&`, or `~`) + /// to the byte values it encodes. + /// + /// You can use the `String::from_utf8` function to turn a `Vec<u8>` into a + /// string with characters corresponding to those values. + /// + /// # Example + /// + /// This converts a string literal to base64 and back. + /// + /// ```rust + /// extern crate rustc_serialize; + /// use rustc_serialize::base64::{ToBase64, FromBase64, STANDARD}; + /// + /// fn main () { + /// let hello_str = b"Hello, World".to_base64(STANDARD); + /// println!("base64 output: {}", hello_str); + /// let res = hello_str.from_base64(); + /// if res.is_ok() { + /// let opt_bytes = String::from_utf8(res.unwrap()); + /// if opt_bytes.is_ok() { + /// println!("decoded from base64: {:?}", opt_bytes.unwrap()); + /// } + /// } + /// } + /// ``` + #[inline] + fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { + self.as_bytes().from_base64() + } +} + +impl FromBase64 for [u8] { + fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { + let mut r = Vec::with_capacity(self.len()); + let mut buf: u32 = 0; + let mut modulus = 0; + + let mut it = self.iter(); + for byte in it.by_ref() { + let code = DECODE_TABLE[*byte as usize]; + if code >= SPECIAL_CODES_START { + match code { + NEWLINE_CODE => continue, + EQUALS_CODE => break, + INVALID_CODE => return Err(InvalidBase64Byte( + *byte, (byte as *const _ as usize) - self.as_ptr() as usize)), + _ => unreachable!(), + } + } + buf = (buf | code as u32) << 6; + modulus += 1; + if modulus == 4 { + modulus = 0; + r.push((buf >> 22) as u8); + r.push((buf >> 14) as u8); + r.push((buf >> 6 ) as u8); + } + } + + for byte in it { + match *byte { + b'=' | b'\r' | b'\n' => continue, + _ => return Err(InvalidBase64Byte( + *byte, (byte as *const _ as usize) - self.as_ptr() as usize)), + } + } + + match modulus { + 2 => { + r.push((buf >> 10) as u8); + } + 3 => { + r.push((buf >> 16) as u8); + r.push((buf >> 8 ) as u8); + } + 0 => (), + _ => return Err(InvalidBase64Length), + } + + Ok(r) + } +} + +impl<'a, T: ?Sized + FromBase64> FromBase64 for &'a T { + fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { + (**self).from_base64() + } +} + +/// Base64 decoding lookup table, generated using: +/// +/// ``` +/// let mut ch = 0u8; +/// for ch in 0..255 { +/// let mut ch = ch as u8; +/// let code = match ch { +/// b'A'...b'Z' => ch - 0x41, +/// b'a'...b'z' => ch - 0x47, +/// b'0'...b'9' => ch + 0x04, +/// b'+' | b'-' => 0x3E, +/// b'/' | b'_' => 0x3F, +/// b'=' => 0xFE, +/// b'\r' | b'\n' => 0xFD, +/// _ => 0xFF, +/// }; +/// print!("0x{:02X}, ", code); +/// if ch % 16 == 15 { println!(""); } +/// else if ch == 0xFF { break; } +/// ch += 1; +/// } +/// println!(""); +/// ``` +const DECODE_TABLE: [u8; 256] = [ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD, 0xFF, 0xFF, 0xFD, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0x3E, 0xFF, 0x3F, + 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, + 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, + 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, +]; +const INVALID_CODE: u8 = 0xFF; +const EQUALS_CODE: u8 = 0xFE; +const NEWLINE_CODE: u8 = 0xFD; +const SPECIAL_CODES_START: u8 = NEWLINE_CODE; + +#[cfg(test)] +mod tests { + use base64::{Config, Newline, FromBase64, ToBase64, STANDARD, URL_SAFE}; + + #[test] + fn test_to_base64_basic() { + assert_eq!("".as_bytes().to_base64(STANDARD), ""); + assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg=="); + assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8="); + assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v"); + assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg=="); + assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE="); + assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy"); + } + + #[test] + fn test_to_base64_crlf_line_break() { + assert!(![0; 1000].to_base64(Config {line_length: None, ..STANDARD}) + .contains("\r\n")); + assert_eq!(b"foobar".to_base64(Config {line_length: Some(4), + ..STANDARD}), + "Zm9v\r\nYmFy"); + } + + #[test] + fn test_to_base64_lf_line_break() { + assert!(![0; 1000].to_base64(Config {line_length: None, + newline: Newline::LF, + ..STANDARD}) + .contains("\n")); + assert_eq!(b"foobar".to_base64(Config {line_length: Some(4), + newline: Newline::LF, + ..STANDARD}), + "Zm9v\nYmFy"); + } + + #[test] + fn test_to_base64_padding() { + assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg"); + assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8"); + } + + #[test] + fn test_to_base64_url_safe() { + assert_eq!([251, 255].to_base64(URL_SAFE), "-_8"); + assert_eq!([251, 255].to_base64(STANDARD), "+/8="); + } + + #[test] + fn test_to_base64_empty_line_length() { + [].to_base64(Config {line_length: Some(72), ..STANDARD}); + } + + #[test] + fn test_from_base64_basic() { + assert_eq!("".from_base64().unwrap(), b""); + assert_eq!("Zg==".from_base64().unwrap(), b"f"); + assert_eq!("Zm8=".from_base64().unwrap(), b"fo"); + assert_eq!("Zm9v".from_base64().unwrap(), b"foo"); + assert_eq!("Zm9vYg==".from_base64().unwrap(), b"foob"); + assert_eq!("Zm9vYmE=".from_base64().unwrap(), b"fooba"); + assert_eq!("Zm9vYmFy".from_base64().unwrap(), b"foobar"); + } + + #[test] + fn test_from_base64_bytes() { + assert_eq!(b"Zm9vYmFy".from_base64().unwrap(), b"foobar"); + } + + #[test] + fn test_from_base64_newlines() { + assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(), + b"foobar"); + assert_eq!("Zm9vYg==\r\n".from_base64().unwrap(), + b"foob"); + assert_eq!("Zm9v\nYmFy".from_base64().unwrap(), + b"foobar"); + assert_eq!("Zm9vYg==\n".from_base64().unwrap(), + b"foob"); + } + + #[test] + fn test_from_base64_urlsafe() { + assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap()); + } + + #[test] + fn test_from_base64_invalid_char() { + assert!("Zm$=".from_base64().is_err()); + assert!("Zg==$".from_base64().is_err()); + } + + #[test] + fn test_from_base64_invalid_padding() { + assert!("Z===".from_base64().is_err()); + } + + #[test] + fn test_base64_random() { + use rand::{thread_rng, Rng}; + + for _ in 0..1000 { + let times = thread_rng().gen_range(1, 100); + let v = thread_rng().gen_iter::<u8>().take(times) + .collect::<Vec<_>>(); + assert_eq!(v.to_base64(STANDARD) + .from_base64() + .unwrap(), + v); + } + } +} diff --git a/bash-5.1/vendor/rustc-serialize/src/collection_impls.rs b/bash-5.1/vendor/rustc-serialize/src/collection_impls.rs new file mode 100644 index 0000000..f8074c9 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/src/collection_impls.rs @@ -0,0 +1,186 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Implementations of serialization for structures found in libcollections + +use std::hash::Hash; + +use {Decodable, Encodable, Decoder, Encoder, cap_capacity}; +use std::collections::{LinkedList, VecDeque, BTreeMap, BTreeSet, HashMap, HashSet}; + +impl< + T: Encodable +> Encodable for LinkedList<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_seq(self.len(), |s| { + for (i, e) in self.iter().enumerate() { + try!(s.emit_seq_elt(i, |s| e.encode(s))); + } + Ok(()) + }) + } +} + +impl<T:Decodable> Decodable for LinkedList<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<LinkedList<T>, D::Error> { + d.read_seq(|d, len| { + let mut list = LinkedList::new(); + for i in 0..len { + list.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); + } + Ok(list) + }) + } +} + +impl<T: Encodable> Encodable for VecDeque<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_seq(self.len(), |s| { + for (i, e) in self.iter().enumerate() { + try!(s.emit_seq_elt(i, |s| e.encode(s))); + } + Ok(()) + }) + } +} + +impl<T:Decodable> Decodable for VecDeque<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<VecDeque<T>, D::Error> { + d.read_seq(|d, len| { + let mut deque: VecDeque<T> = VecDeque::new(); + for i in 0..len { + deque.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); + } + Ok(deque) + }) + } +} + +impl< + K: Encodable + Ord, + V: Encodable +> Encodable for BTreeMap<K, V> { + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { + e.emit_map(self.len(), |e| { + let mut i = 0; + for (key, val) in self.iter() { + try!(e.emit_map_elt_key(i, |e| key.encode(e))); + try!(e.emit_map_elt_val(i, |e| val.encode(e))); + i += 1; + } + Ok(()) + }) + } +} + +impl< + K: Decodable + Ord, + V: Decodable +> Decodable for BTreeMap<K, V> { + fn decode<D: Decoder>(d: &mut D) -> Result<BTreeMap<K, V>, D::Error> { + d.read_map(|d, len| { + let mut map = BTreeMap::new(); + for i in 0..len { + let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d))); + let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d))); + map.insert(key, val); + } + Ok(map) + }) + } +} + +impl< + T: Encodable + Ord +> Encodable for BTreeSet<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_seq(self.len(), |s| { + let mut i = 0; + for e in self.iter() { + try!(s.emit_seq_elt(i, |s| e.encode(s))); + i += 1; + } + Ok(()) + }) + } +} + +impl< + T: Decodable + Ord +> Decodable for BTreeSet<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<BTreeSet<T>, D::Error> { + d.read_seq(|d, len| { + let mut set = BTreeSet::new(); + for i in 0..len { + set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); + } + Ok(set) + }) + } +} + +impl<K, V> Encodable for HashMap<K, V> + where K: Encodable + Hash + Eq, + V: Encodable, +{ + fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> { + e.emit_map(self.len(), |e| { + let mut i = 0; + for (key, val) in self.iter() { + try!(e.emit_map_elt_key(i, |e| key.encode(e))); + try!(e.emit_map_elt_val(i, |e| val.encode(e))); + i += 1; + } + Ok(()) + }) + } +} + +impl<K, V> Decodable for HashMap<K, V> + where K: Decodable + Hash + Eq, + V: Decodable, +{ + fn decode<D: Decoder>(d: &mut D) -> Result<HashMap<K, V>, D::Error> { + d.read_map(|d, len| { + let mut map = HashMap::with_capacity(cap_capacity::<(K, V)>(len)); + for i in 0..len { + let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d))); + let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d))); + map.insert(key, val); + } + Ok(map) + }) + } +} + +impl<T> Encodable for HashSet<T> where T: Encodable + Hash + Eq { + fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> { + s.emit_seq(self.len(), |s| { + let mut i = 0; + for e in self.iter() { + try!(s.emit_seq_elt(i, |s| e.encode(s))); + i += 1; + } + Ok(()) + }) + } +} + +impl<T> Decodable for HashSet<T> where T: Decodable + Hash + Eq, { + fn decode<D: Decoder>(d: &mut D) -> Result<HashSet<T>, D::Error> { + d.read_seq(|d, len| { + let mut set = HashSet::with_capacity(cap_capacity::<T>(len)); + for i in 0..len { + set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); + } + Ok(set) + }) + } +} diff --git a/bash-5.1/vendor/rustc-serialize/src/hex.rs b/bash-5.1/vendor/rustc-serialize/src/hex.rs new file mode 100644 index 0000000..3c7df19 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/src/hex.rs @@ -0,0 +1,221 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +// +// ignore-lexer-test FIXME #15679 + +//! Hex binary-to-text encoding + +pub use self::FromHexError::*; + +use std::fmt; +use std::error; + +/// A trait for converting a value to hexadecimal encoding +pub trait ToHex { + /// Converts the value of `self` to a hex value, returning the owned + /// string. + fn to_hex(&self) -> String; +} + +static CHARS: &'static[u8] = b"0123456789abcdef"; + +impl ToHex for [u8] { + /// Turn a vector of `u8` bytes into a hexadecimal string. + /// + /// # Example + /// + /// ```rust + /// extern crate rustc_serialize; + /// use rustc_serialize::hex::ToHex; + /// + /// fn main () { + /// let str = [52,32].to_hex(); + /// println!("{}", str); + /// } + /// ``` + fn to_hex(&self) -> String { + let mut v = Vec::with_capacity(self.len() * 2); + for &byte in self.iter() { + v.push(CHARS[(byte >> 4) as usize]); + v.push(CHARS[(byte & 0xf) as usize]); + } + + unsafe { + String::from_utf8_unchecked(v) + } + } +} + +impl<'a, T: ?Sized + ToHex> ToHex for &'a T { + fn to_hex(&self) -> String { + (**self).to_hex() + } +} + +/// A trait for converting hexadecimal encoded values +pub trait FromHex { + /// Converts the value of `self`, interpreted as hexadecimal encoded data, + /// into an owned vector of bytes, returning the vector. + fn from_hex(&self) -> Result<Vec<u8>, FromHexError>; +} + +/// Errors that can occur when decoding a hex encoded string +#[derive(Clone, Copy)] +pub enum FromHexError { + /// The input contained a character not part of the hex format + InvalidHexCharacter(char, usize), + /// The input had an invalid length + InvalidHexLength, +} + +impl fmt::Debug for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + InvalidHexCharacter(ch, idx) => + write!(f, "Invalid character '{}' at position {}", ch, idx), + InvalidHexLength => write!(f, "Invalid input length"), + } + } +} + +impl error::Error for FromHexError { + fn description(&self) -> &str { + match *self { + InvalidHexCharacter(_, _) => "invalid character", + InvalidHexLength => "invalid length", + } + } +} + +impl fmt::Display for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self, f) + } +} + +impl FromHex for str { + /// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) + /// to the byte values it encodes. + /// + /// You can use the `String::from_utf8` function to turn a + /// `Vec<u8>` into a string with characters corresponding to those values. + /// + /// # Example + /// + /// This converts a string literal to hexadecimal and back. + /// + /// ```rust + /// extern crate rustc_serialize; + /// use rustc_serialize::hex::{FromHex, ToHex}; + /// + /// fn main () { + /// let hello_str = "Hello, World".as_bytes().to_hex(); + /// println!("{}", hello_str); + /// let bytes = hello_str.from_hex().unwrap(); + /// println!("{:?}", bytes); + /// let result_str = String::from_utf8(bytes).unwrap(); + /// println!("{}", result_str); + /// } + /// ``` + fn from_hex(&self) -> Result<Vec<u8>, FromHexError> { + // This may be an overestimate if there is any whitespace + let mut b = Vec::with_capacity(self.len() / 2); + let mut modulus = 0; + let mut buf = 0; + + for (idx, byte) in self.bytes().enumerate() { + buf <<= 4; + + match byte { + b'A'...b'F' => buf |= byte - b'A' + 10, + b'a'...b'f' => buf |= byte - b'a' + 10, + b'0'...b'9' => buf |= byte - b'0', + b' '|b'\r'|b'\n'|b'\t' => { + buf >>= 4; + continue + } + _ => { + let ch = self[idx..].chars().next().unwrap(); + return Err(InvalidHexCharacter(ch, idx)) + } + } + + modulus += 1; + if modulus == 2 { + modulus = 0; + b.push(buf); + } + } + + match modulus { + 0 => Ok(b.into_iter().collect()), + _ => Err(InvalidHexLength), + } + } +} + +impl<'a, T: ?Sized + FromHex> FromHex for &'a T { + fn from_hex(&self) -> Result<Vec<u8>, FromHexError> { + (**self).from_hex() + } +} + +#[cfg(test)] +mod tests { + use hex::{FromHex, ToHex}; + + #[test] + pub fn test_to_hex() { + assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172"); + } + + #[test] + pub fn test_from_hex_okay() { + assert_eq!("666f6f626172".from_hex().unwrap(), + b"foobar"); + assert_eq!("666F6F626172".from_hex().unwrap(), + b"foobar"); + } + + #[test] + pub fn test_from_hex_odd_len() { + assert!("666".from_hex().is_err()); + assert!("66 6".from_hex().is_err()); + } + + #[test] + pub fn test_from_hex_invalid_char() { + assert!("66y6".from_hex().is_err()); + } + + #[test] + pub fn test_from_hex_ignores_whitespace() { + assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), + b"foobar"); + } + + #[test] + pub fn test_to_hex_all_bytes() { + for i in 0..256 { + assert_eq!([i as u8].to_hex(), format!("{:02x}", i)); + } + } + + #[test] + pub fn test_from_hex_all_bytes() { + for i in 0..256 { + let ii: &[u8] = &[i as u8]; + assert_eq!(format!("{:02x}", i).from_hex().unwrap(), + ii); + assert_eq!(format!("{:02X}", i).from_hex().unwrap(), + ii); + } + } +} diff --git a/bash-5.1/vendor/rustc-serialize/src/json.rs b/bash-5.1/vendor/rustc-serialize/src/json.rs new file mode 100644 index 0000000..e478fe8 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/src/json.rs @@ -0,0 +1,3999 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Rust JSON serialization library +// Copyright (c) 2011 Google Inc. + +//! JSON parsing and serialization +//! +//! # What is JSON? +//! +//! JSON (JavaScript Object Notation) is a way to write data in Javascript. +//! Like XML, it allows encoding structured data in a text format that can be +//! easily read by humans. Its simple syntax and native compatibility with +//! JavaScript have made it a widely used format. +//! +//! Data types that can be encoded are JavaScript types (see the `Json` enum +//! for more details): +//! +//! * `I64`: equivalent to rust's `i64` +//! * `U64`: equivalent to rust's `u64` +//! * `F64`: equivalent to rust's `f64` +//! * `Boolean`: equivalent to rust's `bool` +//! * `String`: equivalent to rust's `String` +//! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of +//! different types in the +//! same array +//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>` +//! * `Null` +//! +//! An object is a series of string keys mapping to values, in `"key": value` +//! format. Arrays are enclosed in square brackets ([ ... ]) and objects in +//! curly brackets ({ ... }). A simple JSON document encoding a person, +//! their age, address and phone numbers could look like +//! +//! ```ignore +//! { +//! "FirstName": "John", +//! "LastName": "Doe", +//! "Age": 43, +//! "Address": { +//! "Street": "Downing Street 10", +//! "City": "London", +//! "Country": "Great Britain" +//! }, +//! "PhoneNumbers": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! } +//! ``` +//! +//! # Rust Type-based Encoding and Decoding +//! +//! Rust provides a mechanism for low boilerplate encoding & decoding of values +//! to and from JSON via the serialization API. To be able to encode a piece +//! of data, it must implement the `rustc_serialize::Encodable` trait. To be +//! able to decode a piece of data, it must implement the +//! `rustc_serialize::Decodable` trait. The Rust compiler provides an +//! annotation to automatically generate the code for these traits: +//! `#[derive(RustcDecodable, RustcEncodable)]` +//! +//! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode +//! objects. The `ToJson` trait provides a `to_json` method to convert an +//! object into a `json::Json` value. A `json::Json` value can be encoded as a +//! string or buffer using the functions described above. You can also use the +//! `json::Encoder` object, which implements the `Encoder` trait. +//! +//! When using `ToJson`, the `Encodable` trait implementation is not +//! mandatory. +//! +//! # Examples of use +//! +//! ## Using Autoserialization +//! +//! Create a struct called `TestStruct` and serialize and deserialize it to and +//! from JSON using the serialization API, using the derived serialization code. +//! +//! ```rust +//! extern crate rustc_serialize; +//! use rustc_serialize::json; +//! +//! // Automatically generate `RustcDecodable` and `RustcEncodable` trait +//! // implementations +//! #[derive(RustcDecodable, RustcEncodable)] +//! pub struct TestStruct { +//! data_int: u8, +//! data_str: String, +//! data_vector: Vec<u8>, +//! } +//! +//! fn main() { +//! let object = TestStruct { +//! data_int: 1, +//! data_str: "homura".to_string(), +//! data_vector: vec![2,3,4,5], +//! }; +//! +//! // Serialize using `json::encode` +//! let encoded = json::encode(&object).unwrap(); +//! +//! // Deserialize using `json::decode` +//! let decoded: TestStruct = json::decode(&encoded).unwrap(); +//! } +//! ``` +//! +//! ## Using the `ToJson` trait +//! +//! The examples below use the `ToJson` trait to generate the JSON string, +//! which is required for custom mappings. +//! +//! ### Simple example of `ToJson` usage +//! +//! ```rust +//! extern crate rustc_serialize; +//! use rustc_serialize::json::{self, ToJson, Json}; +//! +//! // A custom data structure +//! struct ComplexNum { +//! a: f64, +//! b: f64, +//! } +//! +//! // JSON value representation +//! impl ToJson for ComplexNum { +//! fn to_json(&self) -> Json { +//! Json::String(format!("{}+{}i", self.a, self.b)) +//! } +//! } +//! +//! // Only generate `RustcEncodable` trait implementation +//! #[derive(RustcEncodable)] +//! pub struct ComplexNumRecord { +//! uid: u8, +//! dsc: String, +//! val: Json, +//! } +//! +//! fn main() { +//! let num = ComplexNum { a: 0.0001, b: 12.539 }; +//! let data: String = json::encode(&ComplexNumRecord{ +//! uid: 1, +//! dsc: "test".to_string(), +//! val: num.to_json(), +//! }).unwrap(); +//! println!("data: {}", data); +//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"}; +//! } +//! ``` +//! +//! ### Verbose example of `ToJson` usage +//! +//! ```rust +//! extern crate rustc_serialize; +//! use std::collections::BTreeMap; +//! use rustc_serialize::json::{self, Json, ToJson}; +//! +//! // Only generate `Decodable` trait implementation +//! #[derive(RustcDecodable)] +//! pub struct TestStruct { +//! data_int: u8, +//! data_str: String, +//! data_vector: Vec<u8>, +//! } +//! +//! // Specify encoding method manually +//! impl ToJson for TestStruct { +//! fn to_json(&self) -> Json { +//! let mut d = BTreeMap::new(); +//! // All standard types implement `to_json()`, so use it +//! d.insert("data_int".to_string(), self.data_int.to_json()); +//! d.insert("data_str".to_string(), self.data_str.to_json()); +//! d.insert("data_vector".to_string(), self.data_vector.to_json()); +//! Json::Object(d) +//! } +//! } +//! +//! fn main() { +//! // Serialize using `ToJson` +//! let input_data = TestStruct { +//! data_int: 1, +//! data_str: "madoka".to_string(), +//! data_vector: vec![2,3,4,5], +//! }; +//! let json_obj: Json = input_data.to_json(); +//! let json_str: String = json_obj.to_string(); +//! +//! // Deserialize like before +//! let decoded: TestStruct = json::decode(&json_str).unwrap(); +//! } +//! ``` +//! +//! ## Parsing a `str` to `Json` and reading the result +//! +//! ```rust +//! extern crate rustc_serialize; +//! use rustc_serialize::json::Json; +//! +//! fn main() { +//! let data = Json::from_str("{\"foo\": 13, \"bar\": \"baz\"}").unwrap(); +//! println!("data: {}", data); +//! // data: {"bar":"baz","foo":13} +//! println!("object? {}", data.is_object()); +//! // object? true +//! +//! let obj = data.as_object().unwrap(); +//! let foo = obj.get("foo").unwrap(); +//! +//! println!("array? {:?}", foo.as_array()); +//! // array? None +//! println!("u64? {:?}", foo.as_u64()); +//! // u64? Some(13u64) +//! +//! for (key, value) in obj.iter() { +//! println!("{}: {}", key, match *value { +//! Json::U64(v) => format!("{} (u64)", v), +//! Json::String(ref v) => format!("{} (string)", v), +//! _ => format!("other") +//! }); +//! } +//! // bar: baz (string) +//! // foo: 13 (u64) +//! } +//! ``` +//! +//! # The status of this library +//! +//! While this library is the standard way of working with JSON in Rust, +//! there is a next-generation library called Serde that's in the works (it's +//! faster, overcomes some design limitations of rustc-serialize and has more +//! features). You might consider using it when starting a new project or +//! evaluating Rust JSON performance. + +use self::JsonEvent::*; +use self::ErrorCode::*; +use self::ParserError::*; +use self::DecoderError::*; +use self::ParserState::*; +use self::InternalStackElement::*; + +use std::collections::{HashMap, BTreeMap}; +use std::error::Error as StdError; +use std::i64; +use std::io::prelude::*; +use std::mem::swap; +use std::ops::Index; +use std::str::FromStr; +use std::string; +use std::{char, f64, fmt, io, str}; + +use Encodable; + +/// Represents a json value +#[derive(Clone, PartialEq, PartialOrd, Debug)] +pub enum Json { + I64(i64), + U64(u64), + F64(f64), + String(string::String), + Boolean(bool), + Array(self::Array), + Object(self::Object), + Null, +} + +pub type Array = Vec<Json>; +pub type Object = BTreeMap<string::String, Json>; + +pub struct PrettyJson<'a> { inner: &'a Json } + +pub struct AsJson<'a, T: 'a> { inner: &'a T } +pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<u32> } + +/// The errors that can arise while parsing a JSON stream. +#[derive(Clone, Copy, PartialEq)] +pub enum ErrorCode { + InvalidSyntax, + InvalidNumber, + EOFWhileParsingObject, + EOFWhileParsingArray, + EOFWhileParsingValue, + EOFWhileParsingString, + KeyMustBeAString, + ExpectedColon, + TrailingCharacters, + TrailingComma, + InvalidEscape, + InvalidUnicodeCodePoint, + LoneLeadingSurrogateInHexEscape, + UnexpectedEndOfHexEscape, + UnrecognizedHex, + NotFourDigit, + ControlCharacterInString, + NotUtf8, +} + +#[derive(Debug)] +pub enum ParserError { + /// msg, line, col + SyntaxError(ErrorCode, usize, usize), + IoError(io::Error), +} + +impl PartialEq for ParserError { + fn eq(&self, other: &ParserError) -> bool { + match (self, other) { + (&SyntaxError(msg0, line0, col0), &SyntaxError(msg1, line1, col1)) => + msg0 == msg1 && line0 == line1 && col0 == col1, + (&IoError(_), _) => false, + (_, &IoError(_)) => false, + } + } +} + +// Builder and Parser have the same errors. +pub type BuilderError = ParserError; + +#[derive(PartialEq, Debug)] +pub enum DecoderError { + ParseError(ParserError), + ExpectedError(string::String, string::String), + MissingFieldError(string::String), + UnknownVariantError(string::String), + ApplicationError(string::String), + EOF, +} + +#[derive(Copy, Debug)] +pub enum EncoderError { + FmtError(fmt::Error), + BadHashmapKey, +} + +impl PartialEq for EncoderError { + fn eq(&self, other: &EncoderError) -> bool { + match (*self, *other) { + (EncoderError::FmtError(_), EncoderError::FmtError(_)) => true, + (EncoderError::BadHashmapKey, EncoderError::BadHashmapKey) => true, + _ => false, + } + } +} + +impl Clone for EncoderError { + fn clone(&self) -> Self { *self } +} + +/// Returns a readable error string for a given error code. +pub fn error_str(error: ErrorCode) -> &'static str { + match error { + InvalidSyntax => "invalid syntax", + InvalidNumber => "invalid number", + EOFWhileParsingObject => "EOF While parsing object", + EOFWhileParsingArray => "EOF While parsing array", + EOFWhileParsingValue => "EOF While parsing value", + EOFWhileParsingString => "EOF While parsing string", + KeyMustBeAString => "key must be a string", + ExpectedColon => "expected `:`", + TrailingCharacters => "trailing characters", + TrailingComma => "trailing comma", + InvalidEscape => "invalid escape", + UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)", + NotFourDigit => "invalid \\u{ esc}ape (not four digits)", + ControlCharacterInString => "unescaped control character in string", + NotUtf8 => "contents not utf-8", + InvalidUnicodeCodePoint => "invalid Unicode code point", + LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape", + UnexpectedEndOfHexEscape => "unexpected end of hex escape", + } +} + +/// Shortcut function to decode a JSON `&str` into an object +pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> { + let json = match Json::from_str(s) { + Ok(x) => x, + Err(e) => return Err(ParseError(e)) + }; + + let mut decoder = Decoder::new(json); + ::Decodable::decode(&mut decoder) +} + +/// Shortcut function to encode a `T` into a JSON `String` +pub fn encode<T: ::Encodable>(object: &T) -> EncodeResult<string::String> { + let mut s = String::new(); + { + let mut encoder = Encoder::new(&mut s); + try!(object.encode(&mut encoder)); + } + Ok(s) +} + +impl fmt::Debug for ErrorCode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + error_str(*self).fmt(f) + } +} + +impl StdError for DecoderError { + fn description(&self) -> &str { "decoder error" } + fn cause(&self) -> Option<&StdError> { + match *self { + DecoderError::ParseError(ref e) => Some(e), + _ => None, + } + } +} + +impl fmt::Display for DecoderError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self, f) + } +} + +impl From<ParserError> for DecoderError { + fn from(err: ParserError) -> DecoderError { + ParseError(From::from(err)) + } +} + +impl StdError for ParserError { + fn description(&self) -> &str { "failed to parse json" } +} + +impl fmt::Display for ParserError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self, f) + } +} + +impl From<io::Error> for ParserError { + fn from(err: io::Error) -> ParserError { + IoError(err) + } +} + +impl StdError for EncoderError { + fn description(&self) -> &str { "encoder error" } +} + +impl fmt::Display for EncoderError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self, f) + } +} + +impl From<fmt::Error> for EncoderError { + fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) } +} + +pub type EncodeResult<T> = Result<T, EncoderError>; +pub type DecodeResult<T> = Result<T, DecoderError>; + +fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult<()> { + try!(wr.write_str("\"")); + + let mut start = 0; + + for (i, byte) in v.bytes().enumerate() { + let escaped = match byte { + b'"' => "\\\"", + b'\\' => "\\\\", + b'\x00' => "\\u0000", + b'\x01' => "\\u0001", + b'\x02' => "\\u0002", + b'\x03' => "\\u0003", + b'\x04' => "\\u0004", + b'\x05' => "\\u0005", + b'\x06' => "\\u0006", + b'\x07' => "\\u0007", + b'\x08' => "\\b", + b'\t' => "\\t", + b'\n' => "\\n", + b'\x0b' => "\\u000b", + b'\x0c' => "\\f", + b'\r' => "\\r", + b'\x0e' => "\\u000e", + b'\x0f' => "\\u000f", + b'\x10' => "\\u0010", + b'\x11' => "\\u0011", + b'\x12' => "\\u0012", + b'\x13' => "\\u0013", + b'\x14' => "\\u0014", + b'\x15' => "\\u0015", + b'\x16' => "\\u0016", + b'\x17' => "\\u0017", + b'\x18' => "\\u0018", + b'\x19' => "\\u0019", + b'\x1a' => "\\u001a", + b'\x1b' => "\\u001b", + b'\x1c' => "\\u001c", + b'\x1d' => "\\u001d", + b'\x1e' => "\\u001e", + b'\x1f' => "\\u001f", + b'\x7f' => "\\u007f", + _ => { continue; } + }; + + if start < i { + try!(wr.write_str(&v[start..i])); + } + + try!(wr.write_str(escaped)); + + start = i + 1; + } + + if start != v.len() { + try!(wr.write_str(&v[start..])); + } + + try!(wr.write_str("\"")); + Ok(()) +} + +fn escape_char(writer: &mut fmt::Write, v: char) -> EncodeResult<()> { + let mut buf = [0; 4]; + let _ = write!(&mut &mut buf[..], "{}", v); + let buf = unsafe { str::from_utf8_unchecked(&buf[..v.len_utf8()]) }; + escape_str(writer, buf) +} + +fn spaces(wr: &mut fmt::Write, n: u32) -> EncodeResult<()> { + let mut n = n as usize; + const BUF: &'static str = " "; + + while n >= BUF.len() { + try!(wr.write_str(BUF)); + n -= BUF.len(); + } + + if n > 0 { + try!(wr.write_str(&BUF[..n])); + } + Ok(()) +} + +fn fmt_number_or_null(v: f64) -> string::String { + use std::num::FpCategory::{Nan, Infinite}; + + match v.classify() { + Nan | Infinite => "null".to_string(), + _ => { + let s = v.to_string(); + if s.contains(".") {s} else {s + ".0"} + } + } +} + +macro_rules! emit_enquoted_if_mapkey { + ($enc:ident,$e:expr) => { + if $enc.is_emitting_map_key { + try!(write!($enc.writer, "\"{}\"", $e)); + Ok(()) + } else { + try!(write!($enc.writer, "{}", $e)); + Ok(()) + } + } +} + +enum EncodingFormat { + Compact, + Pretty { + curr_indent: u32, + indent: u32 + } +} + +/// A structure for implementing serialization to JSON. +pub struct Encoder<'a> { + writer: &'a mut (fmt::Write+'a), + format : EncodingFormat, + is_emitting_map_key: bool, +} + +impl<'a> Encoder<'a> { + /// Creates a new encoder whose output will be written in human-readable + /// JSON to the specified writer + pub fn new_pretty(writer: &'a mut fmt::Write) -> Encoder<'a> { + Encoder { + writer: writer, + format: EncodingFormat::Pretty { + curr_indent: 0, + indent: 2, + }, + is_emitting_map_key: false, + } + } + + /// Creates a new encoder whose output will be written in compact + /// JSON to the specified writer + pub fn new(writer: &'a mut fmt::Write) -> Encoder<'a> { + Encoder { + writer: writer, + format: EncodingFormat::Compact, + is_emitting_map_key: false, + } + } + + /// Set the number of spaces to indent for each level. + /// This is safe to set during encoding. + pub fn set_indent(&mut self, new_indent: u32) -> Result<(), ()> { + if let EncodingFormat::Pretty{ref mut curr_indent, ref mut indent} = self.format { + // self.indent very well could be 0 so we need to use checked division. + let level = curr_indent.checked_div(*indent).unwrap_or(0); + *indent = new_indent; + *curr_indent = level * *indent; + Ok(()) + } else { + Err(()) + } + } +} + +impl<'a> ::Encoder for Encoder<'a> { + type Error = EncoderError; + + fn emit_nil(&mut self) -> EncodeResult<()> { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + try!(write!(self.writer, "null")); + Ok(()) + } + + fn emit_usize(&mut self, v: usize) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_u64(&mut self, v: u64) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_u32(&mut self, v: u32) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_u16(&mut self, v: u16) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_u8(&mut self, v: u8) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + + fn emit_isize(&mut self, v: isize) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_i64(&mut self, v: i64) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_i32(&mut self, v: i32) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_i16(&mut self, v: i16) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + fn emit_i8(&mut self, v: i8) -> EncodeResult<()> { emit_enquoted_if_mapkey!(self, v) } + + fn emit_bool(&mut self, v: bool) -> EncodeResult<()> { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if v { + try!(write!(self.writer, "true")); + } else { + try!(write!(self.writer, "false")); + } + Ok(()) + } + + fn emit_f64(&mut self, v: f64) -> EncodeResult<()> { + emit_enquoted_if_mapkey!(self, fmt_number_or_null(v)) + } + fn emit_f32(&mut self, v: f32) -> EncodeResult<()> { + self.emit_f64(v as f64) + } + + fn emit_char(&mut self, v: char) -> EncodeResult<()> { + escape_char(self.writer, v) + } + fn emit_str(&mut self, v: &str) -> EncodeResult<()> { + escape_str(self.writer, v) + } + + fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + f(self) + } + + fn emit_enum_variant<F>(&mut self, + name: &str, + _id: usize, + cnt: usize, + f: F) + -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + // enums are encoded as strings or objects + // Bunny => "Bunny" + // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]} + if cnt == 0 { + escape_str(self.writer, name) + } else { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + try!(write!(self.writer, "{{\n")); + *curr_indent += indent; + try!(spaces(self.writer, *curr_indent)); + try!(write!(self.writer, "\"variant\": ")); + try!(escape_str(self.writer, name)); + try!(write!(self.writer, ",\n")); + try!(spaces(self.writer, *curr_indent)); + try!(write!(self.writer, "\"fields\": [\n")); + *curr_indent += indent; + } else { + try!(write!(self.writer, "{{\"variant\":")); + try!(escape_str(self.writer, name)); + try!(write!(self.writer, ",\"fields\":[")); + } + try!(f(self)); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent -= indent; + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, *curr_indent)); + *curr_indent -= indent; + try!(write!(self.writer, "]\n")); + try!(spaces(self.writer, *curr_indent)); + try!(write!(self.writer, "}}")); + } else { + try!(write!(self.writer, "]}}")); + } + Ok(()) + } + } + + fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if idx != 0 { + try!(write!(self.writer, ",")); + if let EncodingFormat::Pretty{..} = self.format { + try!(write!(self.writer, "\n")); + } + } + if let EncodingFormat::Pretty{curr_indent, ..} = self.format { + try!(spaces(self.writer, curr_indent)); + } + f(self) + } + + fn emit_enum_struct_variant<F>(&mut self, + name: &str, + id: usize, + cnt: usize, + f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_enum_variant(name, id, cnt, f) + } + + fn emit_enum_struct_variant_field<F>(&mut self, + _: &str, + idx: usize, + f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_enum_variant_arg(idx, f) + } + + + fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if len == 0 { + try!(write!(self.writer, "{{}}")); + } else { + try!(write!(self.writer, "{{")); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent += indent; + } + try!(f(self)); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent -= indent; + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, *curr_indent)); + } + try!(write!(self.writer, "}}")); + } + Ok(()) + } + + fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if idx != 0 { + try!(write!(self.writer, ",")); + } + if let EncodingFormat::Pretty{curr_indent, ..} = self.format { + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, curr_indent)); + } + try!(escape_str(self.writer, name)); + if let EncodingFormat::Pretty{..} = self.format { + try!(write!(self.writer, ": ")); + } else { + try!(write!(self.writer, ":")); + } + f(self) + } + + fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_seq(len, f) + } + fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_seq_elt(idx, f) + } + + fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_seq(len, f) + } + fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_seq_elt(idx, f) + } + + fn emit_option<F>(&mut self, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + f(self) + } + fn emit_option_none(&mut self) -> EncodeResult<()> { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + self.emit_nil() + } + fn emit_option_some<F>(&mut self, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + f(self) + } + + fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if len == 0 { + try!(write!(self.writer, "[]")); + } else { + try!(write!(self.writer, "[")); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent += indent; + } + try!(f(self)); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent -= indent; + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, *curr_indent)); + } + try!(write!(self.writer, "]")); + } + Ok(()) + } + + fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if idx != 0 { + try!(write!(self.writer, ",")); + } + if let EncodingFormat::Pretty{ref mut curr_indent, ..} = self.format { + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, *curr_indent)); + } + f(self) + } + + fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if len == 0 { + try!(write!(self.writer, "{{}}")); + } else { + try!(write!(self.writer, "{{")); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent += indent; + } + try!(f(self)); + if let EncodingFormat::Pretty{ref mut curr_indent, indent} = self.format { + *curr_indent -= indent; + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, *curr_indent)); + } + try!(write!(self.writer, "}}")); + } + Ok(()) + } + + fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if idx != 0 { + try!(write!(self.writer, ",")); + } + if let EncodingFormat::Pretty{curr_indent, ..} = self.format { + try!(write!(self.writer, "\n")); + try!(spaces(self.writer, curr_indent)); + } + self.is_emitting_map_key = true; + try!(f(self)); + self.is_emitting_map_key = false; + Ok(()) + } + + fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult<()> where + F: FnOnce(&mut Encoder<'a>) -> EncodeResult<()>, + { + if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if let EncodingFormat::Pretty{..} = self.format { + try!(write!(self.writer, ": ")); + } else { + try!(write!(self.writer, ":")); + } + f(self) + } +} + +impl Encodable for Json { + fn encode<S: ::Encoder>(&self, e: &mut S) -> Result<(), S::Error> { + match *self { + Json::I64(v) => v.encode(e), + Json::U64(v) => v.encode(e), + Json::F64(v) => v.encode(e), + Json::String(ref v) => v.encode(e), + Json::Boolean(v) => v.encode(e), + Json::Array(ref v) => v.encode(e), + Json::Object(ref v) => v.encode(e), + Json::Null => e.emit_nil(), + } + } +} + +/// Create an `AsJson` wrapper which can be used to print a value as JSON +/// on-the-fly via `write!` +pub fn as_json<T: Encodable>(t: &T) -> AsJson<T> { + AsJson { inner: t } +} + +/// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON +/// on-the-fly via `write!` +pub fn as_pretty_json<T: Encodable>(t: &T) -> AsPrettyJson<T> { + AsPrettyJson { inner: t, indent: None } +} + +impl Json { + /// Decodes a json value from an `&mut io::Read` + pub fn from_reader(rdr: &mut io::Read) -> Result<Self, BuilderError> { + let contents = { + let mut c = Vec::new(); + try!(rdr.read_to_end(&mut c)); + c + }; + let s = match str::from_utf8(&contents).ok() { + Some(s) => s, + _ => return Err(SyntaxError(NotUtf8, 0, 0)) + }; + let mut builder = Builder::new(s.chars()); + builder.build() + } + + /// Decodes a json value from a string + pub fn from_str(s: &str) -> Result<Self, BuilderError> { + let mut builder = Builder::new(s.chars()); + builder.build() + } + + /// Borrow this json object as a pretty object to generate a pretty + /// representation for it via `Display`. + pub fn pretty(&self) -> PrettyJson { + PrettyJson { inner: self } + } + + /// If the Json value is an Object, returns the value associated with the provided key. + /// Otherwise, returns None. + pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{ + match self { + &Json::Object(ref map) => map.get(key), + _ => None + } + } + + /// Attempts to get a nested Json Object for each key in `keys`. + /// If any key is found not to exist, find_path will return None. + /// Otherwise, it will return the Json value associated with the final key. + pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{ + let mut target = self; + for key in keys.iter() { + match target.find(*key) { + Some(t) => { target = t; }, + None => return None + } + } + Some(target) + } + + /// If the Json value is an Object, performs a depth-first search until + /// a value associated with the provided key is found. If no value is found + /// or the Json value is not an Object, returns None. + pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> { + match self { + &Json::Object(ref map) => { + match map.get(key) { + Some(json_value) => Some(json_value), + None => { + for (_, v) in map.iter() { + match v.search(key) { + x if x.is_some() => return x, + _ => () + } + } + None + } + } + }, + _ => None + } + } + + /// Returns true if the Json value is an Object. Returns false otherwise. + pub fn is_object<'a>(&'a self) -> bool { + self.as_object().is_some() + } + + /// If the Json value is an Object, returns a reference to the associated BTreeMap. + /// Returns None otherwise. + pub fn as_object<'a>(&'a self) -> Option<&'a Object> { + match self { + &Json::Object(ref map) => Some(map), + _ => None + } + } + + /// If the Json value is an Object, returns a mutable reference to the associated BTreeMap. + /// Returns None otherwise. + pub fn as_object_mut<'a>(&'a mut self) -> Option<&'a mut Object> { + match self { + &mut Json::Object(ref mut map) => Some(map), + _ => None + } + } + + /// If the Json value is an Object, returns the associated BTreeMap. + /// Returns None otherwise. + pub fn into_object(self) -> Option<Object> { + match self { + Json::Object(map) => Some(map), + _ => None + } + } + + /// Returns true if the Json value is an Array. Returns false otherwise. + pub fn is_array<'a>(&'a self) -> bool { + self.as_array().is_some() + } + + /// If the Json value is an Array, returns a reference to the associated vector. + /// Returns None otherwise. + pub fn as_array<'a>(&'a self) -> Option<&'a Array> { + match self { + &Json::Array(ref array) => Some(&*array), + _ => None + } + } + + /// If the Json value is an Array, returns a mutable reference to the associated vector. + /// Returns None otherwise. + pub fn as_array_mut<'a>(&'a mut self) -> Option<&'a mut Array> { + match self { + &mut Json::Array(ref mut list) => Some(list), + _ => None + } + } + + /// If the Json value is an Array, returns the associated vector. + /// Returns None otherwise. + pub fn into_array(self) -> Option<Array> { + match self { + Json::Array(array) => Some(array), + _ => None + } + } + + /// Returns true if the Json value is a String. Returns false otherwise. + pub fn is_string<'a>(&'a self) -> bool { + self.as_string().is_some() + } + + /// If the Json value is a String, returns the associated str. + /// Returns None otherwise. + pub fn as_string<'a>(&'a self) -> Option<&'a str> { + match *self { + Json::String(ref s) => Some(&s), + _ => None + } + } + + /// Returns true if the Json value is a Number. Returns false otherwise. + pub fn is_number(&self) -> bool { + match *self { + Json::I64(_) | Json::U64(_) | Json::F64(_) => true, + _ => false, + } + } + + /// Returns true if the Json value is a i64. Returns false otherwise. + pub fn is_i64(&self) -> bool { + match *self { + Json::I64(_) => true, + _ => false, + } + } + + /// Returns true if the Json value is a u64. Returns false otherwise. + pub fn is_u64(&self) -> bool { + match *self { + Json::U64(_) => true, + _ => false, + } + } + + /// Returns true if the Json value is a f64. Returns false otherwise. + pub fn is_f64(&self) -> bool { + match *self { + Json::F64(_) => true, + _ => false, + } + } + + /// If the Json value is a number, return or cast it to a i64. + /// Returns None otherwise. + pub fn as_i64(&self) -> Option<i64> { + match *self { + Json::I64(n) => Some(n), + Json::U64(n) if n >= i64::MAX as u64 => None, + Json::U64(n) => Some(n as i64), + _ => None + } + } + + /// If the Json value is a number, return or cast it to a u64. + /// Returns None otherwise. + pub fn as_u64(&self) -> Option<u64> { + match *self { + Json::I64(n) if n >= 0 => Some(n as u64), + Json::U64(n) => Some(n), + _ => None + } + } + + /// If the Json value is a number, return or cast it to a f64. + /// Returns None otherwise. + pub fn as_f64(&self) -> Option<f64> { + match *self { + Json::I64(n) => Some(n as f64), + Json::U64(n) => Some(n as f64), + Json::F64(n) => Some(n), + _ => None + } + } + + /// Returns true if the Json value is a Boolean. Returns false otherwise. + pub fn is_boolean(&self) -> bool { + self.as_boolean().is_some() + } + + /// If the Json value is a Boolean, returns the associated bool. + /// Returns None otherwise. + pub fn as_boolean(&self) -> Option<bool> { + match self { + &Json::Boolean(b) => Some(b), + _ => None + } + } + + /// Returns true if the Json value is a Null. Returns false otherwise. + pub fn is_null(&self) -> bool { + self.as_null().is_some() + } + + /// If the Json value is a Null, returns (). + /// Returns None otherwise. + pub fn as_null(&self) -> Option<()> { + match self { + &Json::Null => Some(()), + _ => None + } + } +} + +impl<'a> Index<&'a str> for Json { + type Output = Json; + + fn index(&self, idx: &str) -> &Json { + self.find(idx).unwrap() + } +} + +impl Index<usize> for Json { + type Output = Json; + + fn index<'a>(&'a self, idx: usize) -> &'a Json { + match self { + &Json::Array(ref v) => &v[idx], + _ => panic!("can only index Json with usize if it is an array") + } + } +} + +/// The output of the streaming parser. +#[derive(PartialEq, Debug)] +pub enum JsonEvent { + ObjectStart, + ObjectEnd, + ArrayStart, + ArrayEnd, + BooleanValue(bool), + I64Value(i64), + U64Value(u64), + F64Value(f64), + StringValue(string::String), + NullValue, + Error(ParserError), +} + +#[derive(PartialEq, Debug)] +enum ParserState { + // Parse a value in an array, true means first element. + ParseArray(bool), + // Parse ',' or ']' after an element in an array. + ParseArrayComma, + // Parse a key:value in an object, true means first element. + ParseObject(bool), + // Parse ',' or ']' after an element in an object. + ParseObjectComma, + // Initial state. + ParseStart, + // Expecting the stream to end. + ParseBeforeFinish, + // Parsing can't continue. + ParseFinished, +} + +/// A Stack represents the current position of the parser in the logical +/// structure of the JSON stream. +/// For example foo.bar[3].x +pub struct Stack { + stack: Vec<InternalStackElement>, + str_buffer: Vec<u8>, +} + +/// StackElements compose a Stack. +/// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the +/// StackElements compositing the stack that represents foo.bar[3].x +#[derive(PartialEq, Clone, Debug)] +pub enum StackElement<'l> { + Index(u32), + Key(&'l str), +} + +// Internally, Key elements are stored as indices in a buffer to avoid +// allocating a string for every member of an object. +#[derive(PartialEq, Clone, Debug)] +enum InternalStackElement { + InternalIndex(u32), + InternalKey(u16, u16), // start, size +} + +impl Stack { + pub fn new() -> Stack { + Stack { stack: Vec::new(), str_buffer: Vec::new() } + } + + /// Returns The number of elements in the Stack. + pub fn len(&self) -> usize { self.stack.len() } + + /// Returns true if the stack is empty. + pub fn is_empty(&self) -> bool { self.stack.is_empty() } + + /// Provides access to the StackElement at a given index. + /// lower indices are at the bottom of the stack while higher indices are + /// at the top. + pub fn get<'l>(&'l self, idx: usize) -> StackElement<'l> { + match self.stack[idx] { + InternalIndex(i) => StackElement::Index(i), + InternalKey(start, size) => { + StackElement::Key(str::from_utf8( + &self.str_buffer[start as usize .. start as usize + size as usize]).unwrap()) + } + } + } + + /// Compares this stack with an array of StackElements. + pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool { + if self.stack.len() != rhs.len() { return false; } + for i in 0..rhs.len() { + if self.get(i) != rhs[i] { return false; } + } + return true; + } + + /// Returns true if the bottom-most elements of this stack are the same as + /// the ones passed as parameter. + pub fn starts_with(&self, rhs: &[StackElement]) -> bool { + if self.stack.len() < rhs.len() { return false; } + for i in 0..rhs.len() { + if self.get(i) != rhs[i] { return false; } + } + return true; + } + + /// Returns true if the top-most elements of this stack are the same as + /// the ones passed as parameter. + pub fn ends_with(&self, rhs: &[StackElement]) -> bool { + if self.stack.len() < rhs.len() { return false; } + let offset = self.stack.len() - rhs.len(); + for i in 0..rhs.len() { + if self.get(i + offset) != rhs[i] { return false; } + } + return true; + } + + /// Returns the top-most element (if any). + pub fn top<'l>(&'l self) -> Option<StackElement<'l>> { + return match self.stack.last() { + None => None, + Some(&InternalIndex(i)) => Some(StackElement::Index(i)), + Some(&InternalKey(start, size)) => { + Some(StackElement::Key(str::from_utf8( + &self.str_buffer[start as usize .. (start+size) as usize] + ).unwrap())) + } + } + } + + // Used by Parser to insert Key elements at the top of the stack. + fn push_key(&mut self, key: string::String) { + self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16)); + for c in key.as_bytes().iter() { + self.str_buffer.push(*c); + } + } + + // Used by Parser to insert Index elements at the top of the stack. + fn push_index(&mut self, index: u32) { + self.stack.push(InternalIndex(index)); + } + + // Used by Parser to remove the top-most element of the stack. + fn pop(&mut self) { + assert!(!self.is_empty()); + match *self.stack.last().unwrap() { + InternalKey(_, sz) => { + let new_size = self.str_buffer.len() - sz as usize; + self.str_buffer.truncate(new_size); + } + InternalIndex(_) => {} + } + self.stack.pop(); + } + + // Used by Parser to test whether the top-most element is an index. + fn last_is_index(&self) -> bool { + if self.is_empty() { return false; } + return match *self.stack.last().unwrap() { + InternalIndex(_) => true, + _ => false, + } + } + + // Used by Parser to increment the index of the top-most element. + fn bump_index(&mut self) { + let len = self.stack.len(); + let idx = match *self.stack.last().unwrap() { + InternalIndex(i) => { i + 1 } + _ => { panic!(); } + }; + self.stack[len - 1] = InternalIndex(idx); + } +} + +/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming +/// an iterator of char. +pub struct Parser<T> { + rdr: T, + ch: Option<char>, + line: usize, + col: usize, + // We maintain a stack representing where we are in the logical structure + // of the JSON stream. + stack: Stack, + // A state machine is kept to make it possible to interrupt and resume parsing. + state: ParserState, +} + +impl<T: Iterator<Item = char>> Iterator for Parser<T> { + type Item = JsonEvent; + + fn next(&mut self) -> Option<JsonEvent> { + if self.state == ParseFinished { + return None; + } + + if self.state == ParseBeforeFinish { + self.parse_whitespace(); + // Make sure there is no trailing characters. + if self.eof() { + self.state = ParseFinished; + return None; + } else { + return Some(self.error_event(TrailingCharacters)); + } + } + + return Some(self.parse()); + } +} + +impl<T: Iterator<Item = char>> Parser<T> { + /// Creates the JSON parser. + pub fn new(rdr: T) -> Parser<T> { + let mut p = Parser { + rdr: rdr, + ch: Some('\x00'), + line: 1, + col: 0, + stack: Stack::new(), + state: ParseStart, + }; + p.bump(); + return p; + } + + /// Provides access to the current position in the logical structure of the + /// JSON stream. + pub fn stack<'l>(&'l self) -> &'l Stack { + return &self.stack; + } + + fn eof(&self) -> bool { self.ch.is_none() } + fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') } + fn bump(&mut self) { + self.ch = self.rdr.next(); + + if self.ch_is('\n') { + self.line += 1; + self.col = 1; + } else { + self.col += 1; + } + } + + fn next_char(&mut self) -> Option<char> { + self.bump(); + self.ch + } + fn ch_is(&self, c: char) -> bool { + self.ch == Some(c) + } + + fn error<E>(&self, reason: ErrorCode) -> Result<E, ParserError> { + Err(SyntaxError(reason, self.line, self.col)) + } + + fn parse_whitespace(&mut self) { + while self.ch_is(' ') || + self.ch_is('\n') || + self.ch_is('\t') || + self.ch_is('\r') { self.bump(); } + } + + fn parse_number(&mut self) -> JsonEvent { + let mut neg = false; + + if self.ch_is('-') { + self.bump(); + neg = true; + } + + let res = match self.parse_u64() { + Ok(res) => res, + Err(e) => { return Error(e); } + }; + + if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') { + let mut res = res as f64; + + if self.ch_is('.') { + res = match self.parse_decimal(res) { + Ok(res) => res, + Err(e) => { return Error(e); } + }; + } + + if self.ch_is('e') || self.ch_is('E') { + res = match self.parse_exponent(res) { + Ok(res) => res, + Err(e) => { return Error(e); } + }; + } + + if neg { + res *= -1.0; + } + + F64Value(res) + } else { + if neg { + // Make sure we don't underflow. + if res > (i64::MAX as u64) + 1 { + Error(SyntaxError(InvalidNumber, self.line, self.col)) + } else if res == 0 { + I64Value(res as i64) + } else { + I64Value((!res + 1) as i64) + } + } else { + U64Value(res) + } + } + } + + fn parse_u64(&mut self) -> Result<u64, ParserError> { + let mut accum: u64 = 0; + + match self.ch_or_null() { + '0' => { + self.bump(); + + // A leading '0' must be the only digit before the decimal point. + match self.ch_or_null() { + '0' ... '9' => return self.error(InvalidNumber), + _ => () + } + }, + '1' ... '9' => { + while !self.eof() { + match self.ch_or_null() { + c @ '0' ... '9' => { + macro_rules! try_or_invalid { + ($e: expr) => { + match $e { + Some(v) => v, + None => return self.error(InvalidNumber) + } + } + } + accum = try_or_invalid!(accum.checked_mul(10)); + accum = try_or_invalid!(accum.checked_add((c as u64) - ('0' as u64))); + + self.bump(); + } + _ => break, + } + } + } + _ => return self.error(InvalidNumber), + } + + Ok(accum) + } + + fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> { + self.bump(); + + // Make sure a digit follows the decimal place. + match self.ch_or_null() { + '0' ... '9' => (), + _ => return self.error(InvalidNumber) + } + + let mut dec = 1.0; + let mut frac = 0.0; + while !self.eof() { + match self.ch_or_null() { + c @ '0' ... '9' => { + dec /= 10.0; + frac += (((c as isize) - ('0' as isize)) as f64) * dec; + self.bump(); + } + _ => break, + } + } + + res += frac; + + Ok(res) + } + + fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> { + self.bump(); + + let mut exp = 0; + let mut neg_exp = false; + + if self.ch_is('+') { + self.bump(); + } else if self.ch_is('-') { + self.bump(); + neg_exp = true; + } + + // Make sure a digit follows the exponent place. + match self.ch_or_null() { + '0' ... '9' => (), + _ => return self.error(InvalidNumber) + } + while !self.eof() { + match self.ch_or_null() { + c @ '0' ... '9' => { + exp *= 10; + exp += (c as usize) - ('0' as usize); + + self.bump(); + } + _ => break + } + } + + let exp = 10_f64.powi(exp as i32); + if neg_exp { + res /= exp; + } else { + res *= exp; + } + + Ok(res) + } + + fn decode_hex_escape(&mut self) -> Result<u16, ParserError> { + let mut i = 0; + let mut n = 0; + while i < 4 { + self.bump(); + n = match self.ch_or_null() { + c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)), + c @ 'a' ... 'f' => n * 16 + (10 + (c as u16) - ('a' as u16)), + c @ 'A' ... 'F' => n * 16 + (10 + (c as u16) - ('A' as u16)), + _ => return self.error(InvalidEscape) + }; + + i += 1; + } + + Ok(n) + } + + fn parse_str(&mut self) -> Result<string::String, ParserError> { + let mut escape = false; + let mut res = string::String::new(); + + loop { + self.bump(); + if self.eof() { + return self.error(EOFWhileParsingString); + } + + if escape { + match self.ch_or_null() { + '"' => res.push('"'), + '\\' => res.push('\\'), + '/' => res.push('/'), + 'b' => res.push('\x08'), + 'f' => res.push('\x0c'), + 'n' => res.push('\n'), + 'r' => res.push('\r'), + 't' => res.push('\t'), + 'u' => match try!(self.decode_hex_escape()) { + 0xDC00 ... 0xDFFF => { + return self.error(LoneLeadingSurrogateInHexEscape) + } + + // Non-BMP characters are encoded as a sequence of + // two hex escapes, representing UTF-16 surrogates. + n1 @ 0xD800 ... 0xDBFF => { + match (self.next_char(), self.next_char()) { + (Some('\\'), Some('u')) => (), + _ => return self.error(UnexpectedEndOfHexEscape), + } + + let n2 = try!(self.decode_hex_escape()); + if n2 < 0xDC00 || n2 > 0xDFFF { + return self.error(LoneLeadingSurrogateInHexEscape) + } + let c = (((n1 - 0xD800) as u32) << 10 | + (n2 - 0xDC00) as u32) + 0x1_0000; + res.push(char::from_u32(c).unwrap()); + } + + n => match char::from_u32(n as u32) { + Some(c) => res.push(c), + None => return self.error(InvalidUnicodeCodePoint), + }, + }, + _ => return self.error(InvalidEscape), + } + escape = false; + } else if self.ch_is('\\') { + escape = true; + } else { + match self.ch { + Some('"') => { + self.bump(); + return Ok(res); + }, + Some(c) if c <= '\u{1F}' => + return self.error(ControlCharacterInString), + Some(c) => res.push(c), + None => unreachable!() + } + } + } + } + + // Invoked at each iteration, consumes the stream until it has enough + // information to return a JsonEvent. + // Manages an internal state so that parsing can be interrupted and resumed. + // Also keeps track of the position in the logical structure of the json + // stream int the form of a stack that can be queried by the user using the + // stack() method. + fn parse(&mut self) -> JsonEvent { + loop { + // The only paths where the loop can spin a new iteration + // are in the cases ParseArrayComma and ParseObjectComma if ',' + // is parsed. In these cases the state is set to (respectively) + // ParseArray(false) and ParseObject(false), which always return, + // so there is no risk of getting stuck in an infinite loop. + // All other paths return before the end of the loop's iteration. + self.parse_whitespace(); + + match self.state { + ParseStart => { + return self.parse_start(); + } + ParseArray(first) => { + return self.parse_array(first); + } + ParseArrayComma => { + match self.parse_array_comma_or_end() { + Some(evt) => { return evt; } + None => {} + } + } + ParseObject(first) => { + return self.parse_object(first); + } + ParseObjectComma => { + self.stack.pop(); + if self.ch_is(',') { + self.state = ParseObject(false); + self.bump(); + } else { + return self.parse_object_end(); + } + } + _ => { + return self.error_event(InvalidSyntax); + } + } + } + } + + fn parse_start(&mut self) -> JsonEvent { + let val = self.parse_value(); + self.state = match val { + Error(_) => ParseFinished, + ArrayStart => ParseArray(true), + ObjectStart => ParseObject(true), + _ => ParseBeforeFinish, + }; + return val; + } + + fn parse_array(&mut self, first: bool) -> JsonEvent { + if self.ch_is(']') { + if !first { + self.error_event(InvalidSyntax) + } else { + self.state = if self.stack.is_empty() { + ParseBeforeFinish + } else if self.stack.last_is_index() { + ParseArrayComma + } else { + ParseObjectComma + }; + self.bump(); + ArrayEnd + } + } else { + if first { + self.stack.push_index(0); + } + let val = self.parse_value(); + self.state = match val { + Error(_) => ParseFinished, + ArrayStart => ParseArray(true), + ObjectStart => ParseObject(true), + _ => ParseArrayComma, + }; + val + } + } + + fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> { + if self.ch_is(',') { + self.stack.bump_index(); + self.state = ParseArray(false); + self.bump(); + None + } else if self.ch_is(']') { + self.stack.pop(); + self.state = if self.stack.is_empty() { + ParseBeforeFinish + } else if self.stack.last_is_index() { + ParseArrayComma + } else { + ParseObjectComma + }; + self.bump(); + Some(ArrayEnd) + } else if self.eof() { + Some(self.error_event(EOFWhileParsingArray)) + } else { + Some(self.error_event(InvalidSyntax)) + } + } + + fn parse_object(&mut self, first: bool) -> JsonEvent { + if self.ch_is('}') { + if !first { + if self.stack.is_empty() { + return self.error_event(TrailingComma); + } else { + self.stack.pop(); + } + } + self.state = if self.stack.is_empty() { + ParseBeforeFinish + } else if self.stack.last_is_index() { + ParseArrayComma + } else { + ParseObjectComma + }; + self.bump(); + return ObjectEnd; + } + if self.eof() { + return self.error_event(EOFWhileParsingObject); + } + if !self.ch_is('"') { + return self.error_event(KeyMustBeAString); + } + let s = match self.parse_str() { + Ok(s) => s, + Err(e) => { + self.state = ParseFinished; + return Error(e); + } + }; + self.parse_whitespace(); + if self.eof() { + return self.error_event(EOFWhileParsingObject); + } else if self.ch_or_null() != ':' { + return self.error_event(ExpectedColon); + } + self.stack.push_key(s); + self.bump(); + self.parse_whitespace(); + + let val = self.parse_value(); + + self.state = match val { + Error(_) => ParseFinished, + ArrayStart => ParseArray(true), + ObjectStart => ParseObject(true), + _ => ParseObjectComma, + }; + return val; + } + + fn parse_object_end(&mut self) -> JsonEvent { + if self.ch_is('}') { + self.state = if self.stack.is_empty() { + ParseBeforeFinish + } else if self.stack.last_is_index() { + ParseArrayComma + } else { + ParseObjectComma + }; + self.bump(); + ObjectEnd + } else if self.eof() { + self.error_event(EOFWhileParsingObject) + } else { + self.error_event(InvalidSyntax) + } + } + + fn parse_value(&mut self) -> JsonEvent { + if self.eof() { return self.error_event(EOFWhileParsingValue); } + match self.ch_or_null() { + 'n' => { self.parse_ident("ull", NullValue) } + 't' => { self.parse_ident("rue", BooleanValue(true)) } + 'f' => { self.parse_ident("alse", BooleanValue(false)) } + '0' ... '9' | '-' => self.parse_number(), + '"' => match self.parse_str() { + Ok(s) => StringValue(s), + Err(e) => Error(e), + }, + '[' => { + self.bump(); + ArrayStart + } + '{' => { + self.bump(); + ObjectStart + } + _ => { self.error_event(InvalidSyntax) } + } + } + + fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent { + if ident.chars().all(|c| Some(c) == self.next_char()) { + self.bump(); + value + } else { + Error(SyntaxError(InvalidSyntax, self.line, self.col)) + } + } + + fn error_event(&mut self, reason: ErrorCode) -> JsonEvent { + self.state = ParseFinished; + Error(SyntaxError(reason, self.line, self.col)) + } +} + +/// A Builder consumes a json::Parser to create a generic Json structure. +pub struct Builder<T> { + parser: Parser<T>, + token: Option<JsonEvent>, +} + +impl<T: Iterator<Item = char>> Builder<T> { + /// Create a JSON Builder. + pub fn new(src: T) -> Builder<T> { + Builder { parser: Parser::new(src), token: None, } + } + + // Decode a Json value from a Parser. + pub fn build(&mut self) -> Result<Json, BuilderError> { + self.bump(); + let result = self.build_value(); + self.bump(); + match self.token.take() { + None => {} + Some(Error(e)) => { return Err(e); } + _ => { return Err(SyntaxError(InvalidSyntax, self.parser.line, self.parser.col)); } + } + result + } + + fn bump(&mut self) { + self.token = self.parser.next(); + } + + fn build_value(&mut self) -> Result<Json, BuilderError> { + return match self.token.take() { + Some(NullValue) => Ok(Json::Null), + Some(I64Value(n)) => Ok(Json::I64(n)), + Some(U64Value(n)) => Ok(Json::U64(n)), + Some(F64Value(n)) => Ok(Json::F64(n)), + Some(BooleanValue(b)) => Ok(Json::Boolean(b)), + Some(StringValue(ref mut s)) => { + let mut temp = string::String::new(); + swap(s, &mut temp); + Ok(Json::String(temp)) + } + Some(Error(e)) => Err(e), + Some(ArrayStart) => self.build_array(), + Some(ObjectStart) => self.build_object(), + Some(ObjectEnd) => self.parser.error(InvalidSyntax), + Some(ArrayEnd) => self.parser.error(InvalidSyntax), + None => self.parser.error(EOFWhileParsingValue), + } + } + + fn build_array(&mut self) -> Result<Json, BuilderError> { + self.bump(); + let mut values = Vec::new(); + + loop { + if let Some(ArrayEnd) = self.token { + return Ok(Json::Array(values.into_iter().collect())); + } + match self.build_value() { + Ok(v) => values.push(v), + Err(e) => { return Err(e) } + } + self.bump(); + } + } + + fn build_object(&mut self) -> Result<Json, BuilderError> { + self.bump(); + + let mut values = BTreeMap::new(); + + loop { + match self.token.take() { + Some(ObjectEnd) => { return Ok(Json::Object(values)); } + Some(Error(e)) => { return Err(e); } + None => { break; } + token => { self.token = token; } + } + let key = match self.parser.stack().top() { + Some(StackElement::Key(k)) => { k.to_string() } + _ => { panic!("invalid state"); } + }; + match self.build_value() { + Ok(value) => { values.insert(key, value); } + Err(e) => { return Err(e); } + } + self.bump(); + } + return self.parser.error(EOFWhileParsingObject); + } +} + +/// A structure to decode JSON to values in rust. +pub struct Decoder { + stack: Vec<Json>, +} + +impl Decoder { + /// Creates a new decoder instance for decoding the specified JSON value. + pub fn new(json: Json) -> Decoder { + Decoder { stack: vec![json] } + } +} + +impl Decoder { + fn pop(&mut self) -> DecodeResult<Json> { + match self.stack.pop() { + Some(s) => Ok(s), + None => Err(EOF), + } + } +} + +macro_rules! expect { + ($e:expr, Null) => ({ + match try!($e) { + Json::Null => Ok(()), + other => Err(ExpectedError("Null".to_string(), + format!("{}", other))) + } + }); + ($e:expr, $t:ident) => ({ + match try!($e) { + Json::$t(v) => Ok(v), + other => { + Err(ExpectedError(stringify!($t).to_string(), + format!("{}", other))) + } + } + }) +} + +macro_rules! read_primitive { + ($name:ident, $ty:ident) => { + #[allow(unused_comparisons)] + fn $name(&mut self) -> DecodeResult<$ty> { + match try!(self.pop()) { + Json::I64(i) => { + let other = i as $ty; + if i == other as i64 && (other > 0) == (i > 0) { + Ok(other) + } else { + Err(ExpectedError("Number".to_string(), i.to_string())) + } + } + Json::U64(u) => { + let other = u as $ty; + if u == other as u64 && other >= 0 { + Ok(other) + } else { + Err(ExpectedError("Number".to_string(), u.to_string())) + } + } + Json::F64(f) => { + Err(ExpectedError("Integer".to_string(), f.to_string())) + } + // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc) + // is going to have a string here, as per JSON spec. + Json::String(s) => match s.parse() { + Ok(f) => Ok(f), + Err(_) => Err(ExpectedError("Number".to_string(), s)), + }, + value => { + Err(ExpectedError("Number".to_string(), value.to_string())) + } + } + } + } +} + +impl ::Decoder for Decoder { + type Error = DecoderError; + + fn read_nil(&mut self) -> DecodeResult<()> { + expect!(self.pop(), Null) + } + + read_primitive! { read_usize, usize } + read_primitive! { read_u8, u8 } + read_primitive! { read_u16, u16 } + read_primitive! { read_u32, u32 } + read_primitive! { read_u64, u64 } + read_primitive! { read_isize, isize } + read_primitive! { read_i8, i8 } + read_primitive! { read_i16, i16 } + read_primitive! { read_i32, i32 } + read_primitive! { read_i64, i64 } + + fn read_f32(&mut self) -> DecodeResult<f32> { + self.read_f64().map(|x| x as f32) + } + + fn read_f64(&mut self) -> DecodeResult<f64> { + match try!(self.pop()) { + Json::I64(f) => Ok(f as f64), + Json::U64(f) => Ok(f as f64), + Json::F64(f) => Ok(f), + Json::String(s) => { + // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc) + // is going to have a string here, as per JSON spec. + match s.parse() { + Ok(f) => Ok(f), + Err(_) => Err(ExpectedError("Number".to_string(), s)), + } + }, + Json::Null => Ok(f64::NAN), + value => Err(ExpectedError("Number".to_string(), format!("{}", value))) + } + } + + fn read_bool(&mut self) -> DecodeResult<bool> { + expect!(self.pop(), Boolean) + } + + fn read_char(&mut self) -> DecodeResult<char> { + let s = try!(self.read_str()); + { + let mut it = s.chars(); + match (it.next(), it.next()) { + // exactly one character + (Some(c), None) => return Ok(c), + _ => () + } + } + Err(ExpectedError("single character string".to_string(), format!("{}", s))) + } + + fn read_str(&mut self) -> DecodeResult<string::String> { + expect!(self.pop(), String) + } + + fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + f(self) + } + + fn read_enum_variant<T, F>(&mut self, names: &[&str], + mut f: F) -> DecodeResult<T> + where F: FnMut(&mut Decoder, usize) -> DecodeResult<T>, + { + let name = match try!(self.pop()) { + Json::String(s) => s, + Json::Object(mut o) => { + let n = match o.remove(&"variant".to_string()) { + Some(Json::String(s)) => s, + Some(val) => { + return Err(ExpectedError("String".to_string(), format!("{}", val))) + } + None => { + return Err(MissingFieldError("variant".to_string())) + } + }; + match o.remove(&"fields".to_string()) { + Some(Json::Array(l)) => { + for field in l.into_iter().rev() { + self.stack.push(field); + } + }, + Some(val) => { + return Err(ExpectedError("Array".to_string(), format!("{}", val))) + } + None => { + return Err(MissingFieldError("fields".to_string())) + } + } + n + } + json => { + return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) + } + }; + let idx = match names.iter().position(|n| *n == name) { + Some(idx) => idx, + None => return Err(UnknownVariantError(name)) + }; + f(self, idx) + } + + fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + f(self) + } + + fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where + F: FnMut(&mut Decoder, usize) -> DecodeResult<T>, + { + self.read_enum_variant(names, f) + } + + + fn read_enum_struct_variant_field<T, F>(&mut self, + _name: &str, + idx: usize, + f: F) + -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + self.read_enum_variant_arg(idx, f) + } + + fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + let value = try!(f(self)); + try!(self.pop()); + Ok(value) + } + + fn read_struct_field<T, F>(&mut self, + name: &str, + _idx: usize, + f: F) + -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + let mut obj = try!(expect!(self.pop(), Object)); + + let value = match obj.remove(&name.to_string()) { + None => { + // Add a Null and try to parse it as an Option<_> + // to get None as a default value. + self.stack.push(Json::Null); + match f(self) { + Ok(x) => x, + Err(_) => return Err(MissingFieldError(name.to_string())), + } + }, + Some(json) => { + self.stack.push(json); + try!(f(self)) + } + }; + self.stack.push(Json::Object(obj)); + Ok(value) + } + + fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + self.read_seq(move |d, len| { + if len == tuple_len { + f(d) + } else { + Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len))) + } + }) + } + + fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + self.read_seq_elt(idx, f) + } + + fn read_tuple_struct<T, F>(&mut self, + _name: &str, + len: usize, + f: F) + -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + self.read_tuple(len, f) + } + + fn read_tuple_struct_arg<T, F>(&mut self, + idx: usize, + f: F) + -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + self.read_tuple_arg(idx, f) + } + + fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where + F: FnMut(&mut Decoder, bool) -> DecodeResult<T>, + { + match try!(self.pop()) { + Json::Null => f(self, false), + value => { self.stack.push(value); f(self, true) } + } + } + + fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>, + { + let array = try!(expect!(self.pop(), Array)); + let len = array.len(); + for v in array.into_iter().rev() { + self.stack.push(v); + } + f(self, len) + } + + fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + f(self) + } + + fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>, + { + let obj = try!(expect!(self.pop(), Object)); + let len = obj.len(); + for (key, value) in obj.into_iter() { + self.stack.push(value); + self.stack.push(Json::String(key)); + } + f(self, len) + } + + fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + f(self) + } + + fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, + { + f(self) + } + + fn error(&mut self, err: &str) -> DecoderError { + ApplicationError(err.to_string()) + } +} + +/// A trait for converting values to JSON +pub trait ToJson { + /// Converts the value of `self` to an instance of JSON + fn to_json(&self) -> Json; +} + +macro_rules! to_json_impl_i64 { + ($($t:ty), +) => ( + $(impl ToJson for $t { + fn to_json(&self) -> Json { Json::I64(*self as i64) } + })+ + ) +} + +to_json_impl_i64! { isize, i8, i16, i32, i64 } + +macro_rules! to_json_impl_u64 { + ($($t:ty), +) => ( + $(impl ToJson for $t { + fn to_json(&self) -> Json { Json::U64(*self as u64) } + })+ + ) +} + +to_json_impl_u64! { usize, u8, u16, u32, u64 } + +impl ToJson for Json { + fn to_json(&self) -> Json { self.clone() } +} + +impl ToJson for f32 { + fn to_json(&self) -> Json { (*self as f64).to_json() } +} + +impl ToJson for f64 { + fn to_json(&self) -> Json { + use std::num::FpCategory::{Nan, Infinite}; + + match self.classify() { + Nan | Infinite => Json::Null, + _ => Json::F64(*self) + } + } +} + +impl ToJson for () { + fn to_json(&self) -> Json { Json::Null } +} + +impl ToJson for bool { + fn to_json(&self) -> Json { Json::Boolean(*self) } +} + +impl ToJson for str { + fn to_json(&self) -> Json { Json::String(self.to_string()) } +} + +impl ToJson for string::String { + fn to_json(&self) -> Json { Json::String((*self).clone()) } +} + +macro_rules! tuple_impl { + // use variables to indicate the arity of the tuple + ($($tyvar:ident),* ) => { + // the trailing commas are for the 1 tuple + impl< + $( $tyvar : ToJson ),* + > ToJson for ( $( $tyvar ),* , ) { + + #[inline] + #[allow(non_snake_case)] + fn to_json(&self) -> Json { + match *self { + ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*]) + } + } + } + } +} + +tuple_impl!{A} +tuple_impl!{A, B} +tuple_impl!{A, B, C} +tuple_impl!{A, B, C, D} +tuple_impl!{A, B, C, D, E} +tuple_impl!{A, B, C, D, E, F} +tuple_impl!{A, B, C, D, E, F, G} +tuple_impl!{A, B, C, D, E, F, G, H} +tuple_impl!{A, B, C, D, E, F, G, H, I} +tuple_impl!{A, B, C, D, E, F, G, H, I, J} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} + +impl<A: ToJson> ToJson for [A] { + fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) } +} + +impl<A: ToJson> ToJson for Vec<A> { + fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) } +} + +impl<A: ToJson> ToJson for BTreeMap<string::String, A> { + fn to_json(&self) -> Json { + let mut d = BTreeMap::new(); + for (key, value) in self.iter() { + d.insert((*key).clone(), value.to_json()); + } + Json::Object(d) + } +} + +impl<A: ToJson> ToJson for HashMap<string::String, A> { + fn to_json(&self) -> Json { + let mut d = BTreeMap::new(); + for (key, value) in self.iter() { + d.insert((*key).clone(), value.to_json()); + } + Json::Object(d) + } +} + +impl<A:ToJson> ToJson for Option<A> { + fn to_json(&self) -> Json { + match *self { + None => Json::Null, + Some(ref value) => value.to_json() + } + } +} + +struct FormatShim<'a, 'b: 'a> { + inner: &'a mut fmt::Formatter<'b>, +} + +impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> { + fn write_str(&mut self, s: &str) -> fmt::Result { + match self.inner.write_str(s) { + Ok(_) => Ok(()), + Err(_) => Err(fmt::Error) + } + } +} + +impl fmt::Display for Json { + /// Encodes a json value into a string + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut shim = FormatShim { inner: f }; + let mut encoder = Encoder::new(&mut shim); + match self.encode(&mut encoder) { + Ok(_) => Ok(()), + Err(_) => Err(fmt::Error) + } + } +} + +impl<'a> fmt::Display for PrettyJson<'a> { + /// Encodes a json value into a string + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut shim = FormatShim { inner: f }; + let mut encoder = Encoder::new_pretty(&mut shim); + match self.inner.encode(&mut encoder) { + Ok(_) => Ok(()), + Err(_) => Err(fmt::Error) + } + } +} + +impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> { + /// Encodes a json value into a string + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut shim = FormatShim { inner: f }; + let mut encoder = Encoder::new(&mut shim); + match self.inner.encode(&mut encoder) { + Ok(_) => Ok(()), + Err(_) => Err(fmt::Error) + } + } +} + +impl<'a, T> AsPrettyJson<'a, T> { + /// Set the indentation level for the emitted JSON + pub fn indent(mut self, indent: u32) -> AsPrettyJson<'a, T> { + self.indent = Some(indent); + self + } +} + +impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> { + /// Encodes a json value into a string + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut shim = FormatShim { inner: f }; + let mut encoder = Encoder::new_pretty(&mut shim); + if let Some(n) = self.indent { + // unwrap cannot panic for pretty encoders + let _ = encoder.set_indent(n); + } + match self.inner.encode(&mut encoder) { + Ok(_) => Ok(()), + Err(_) => Err(fmt::Error) + } + } +} + +impl FromStr for Json { + type Err = ParserError; + fn from_str(s: &str) -> Result<Json, ParserError> { + Json::from_str(s) + } +} + +#[cfg(test)] +mod tests { + use self::Animal::*; + use {Encodable, Decodable}; + use super::Json::*; + use super::ErrorCode::*; + use super::ParserError::*; + use super::DecoderError::*; + use super::JsonEvent::*; + use super::StackElement::*; + use super::{Json, DecodeResult, DecoderError, JsonEvent, Parser, + StackElement, Stack, Decoder, Encoder, EncoderError}; + use std::{i64, u64, f32, f64}; + use std::collections::BTreeMap; + use std::string; + + #[derive(RustcDecodable, Eq, PartialEq, Debug)] + struct OptionData { + opt: Option<usize>, + } + + #[test] + fn test_decode_option_none() { + let s ="{}"; + let obj: OptionData = super::decode(s).unwrap(); + assert_eq!(obj, OptionData { opt: None }); + } + + #[test] + fn test_decode_option_some() { + let s = "{ \"opt\": 10 }"; + let obj: OptionData = super::decode(s).unwrap(); + assert_eq!(obj, OptionData { opt: Some(10) }); + } + + #[test] + fn test_decode_option_malformed() { + check_err::<OptionData>("{ \"opt\": [] }", + ExpectedError("Number".to_string(), "[]".to_string())); + check_err::<OptionData>("{ \"opt\": false }", + ExpectedError("Number".to_string(), "false".to_string())); + } + + #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)] + enum Animal { + Dog, + Frog(string::String, isize) + } + + #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)] + struct Inner { + a: (), + b: usize, + c: Vec<string::String>, + } + + #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)] + struct Outer { + inner: Vec<Inner>, + } + + fn mk_object(items: &[(string::String, Json)]) -> Json { + let mut d = BTreeMap::new(); + + for item in items.iter() { + match *item { + (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); }, + } + }; + + Object(d) + } + + #[test] + fn test_from_str_trait() { + let s = "null"; + assert!(s.parse::<Json>().unwrap() == s.parse().unwrap()); + } + + #[test] + fn test_write_null() { + assert_eq!(Null.to_string(), "null"); + assert_eq!(Null.pretty().to_string(), "null"); + } + + #[test] + fn test_write_i64() { + assert_eq!(U64(0).to_string(), "0"); + assert_eq!(U64(0).pretty().to_string(), "0"); + + assert_eq!(U64(1234).to_string(), "1234"); + assert_eq!(U64(1234).pretty().to_string(), "1234"); + + assert_eq!(I64(-5678).to_string(), "-5678"); + assert_eq!(I64(-5678).pretty().to_string(), "-5678"); + + assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000"); + assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000"); + } + + #[test] + fn test_write_f64() { + assert_eq!(F64(3.0).to_string(), "3.0"); + assert_eq!(F64(3.0).pretty().to_string(), "3.0"); + + assert_eq!(F64(3.1).to_string(), "3.1"); + assert_eq!(F64(3.1).pretty().to_string(), "3.1"); + + assert_eq!(F64(-1.5).to_string(), "-1.5"); + assert_eq!(F64(-1.5).pretty().to_string(), "-1.5"); + + assert_eq!(F64(0.5).to_string(), "0.5"); + assert_eq!(F64(0.5).pretty().to_string(), "0.5"); + + assert_eq!(F64(f64::NAN).to_string(), "null"); + assert_eq!(F64(f64::NAN).pretty().to_string(), "null"); + + assert_eq!(F64(f64::INFINITY).to_string(), "null"); + assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null"); + + assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null"); + assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null"); + } + + #[test] + fn test_write_str() { + assert_eq!(String("".to_string()).to_string(), "\"\""); + assert_eq!(String("".to_string()).pretty().to_string(), "\"\""); + + assert_eq!(String("homura".to_string()).to_string(), "\"homura\""); + assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\""); + } + + #[test] + fn test_write_bool() { + assert_eq!(Boolean(true).to_string(), "true"); + assert_eq!(Boolean(true).pretty().to_string(), "true"); + + assert_eq!(Boolean(false).to_string(), "false"); + assert_eq!(Boolean(false).pretty().to_string(), "false"); + } + + #[test] + fn test_write_array() { + assert_eq!(Array(vec![]).to_string(), "[]"); + assert_eq!(Array(vec![]).pretty().to_string(), "[]"); + + assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]"); + assert_eq!( + Array(vec![Boolean(true)]).pretty().to_string(), + "\ + [\n \ + true\n\ + ]" + ); + + let long_test_array = Array(vec![ + Boolean(false), + Null, + Array(vec![String("foo\nbar".to_string()), F64(3.5)])]); + + assert_eq!(long_test_array.to_string(), + "[false,null,[\"foo\\nbar\",3.5]]"); + assert_eq!( + long_test_array.pretty().to_string(), + "\ + [\n \ + false,\n \ + null,\n \ + [\n \ + \"foo\\nbar\",\n \ + 3.5\n \ + ]\n\ + ]" + ); + } + + #[test] + fn test_write_object() { + assert_eq!(mk_object(&[]).to_string(), "{}"); + assert_eq!(mk_object(&[]).pretty().to_string(), "{}"); + + assert_eq!( + mk_object(&[ + ("a".to_string(), Boolean(true)) + ]).to_string(), + "{\"a\":true}" + ); + assert_eq!( + mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(), + "\ + {\n \ + \"a\": true\n\ + }" + ); + + let complex_obj = mk_object(&[ + ("b".to_string(), Array(vec![ + mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), + mk_object(&[("d".to_string(), String("".to_string()))]) + ])) + ]); + + assert_eq!( + complex_obj.to_string(), + "{\ + \"b\":[\ + {\"c\":\"\\f\\r\"},\ + {\"d\":\"\"}\ + ]\ + }" + ); + assert_eq!( + complex_obj.pretty().to_string(), + "\ + {\n \ + \"b\": [\n \ + {\n \ + \"c\": \"\\f\\r\"\n \ + },\n \ + {\n \ + \"d\": \"\"\n \ + }\n \ + ]\n\ + }" + ); + + let a = mk_object(&[ + ("a".to_string(), Boolean(true)), + ("b".to_string(), Array(vec![ + mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), + mk_object(&[("d".to_string(), String("".to_string()))]) + ])) + ]); + + // We can't compare the strings directly because the object fields be + // printed in a different order. + assert_eq!(a.clone(), a.to_string().parse().unwrap()); + assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap()); + } + + #[test] + fn test_write_enum() { + let animal = Dog; + assert_eq!( + format!("{}", super::as_json(&animal)), + "\"Dog\"" + ); + assert_eq!( + format!("{}", super::as_pretty_json(&animal)), + "\"Dog\"" + ); + + let animal = Frog("Henry".to_string(), 349); + assert_eq!( + format!("{}", super::as_json(&animal)), + "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}" + ); + assert_eq!( + format!("{}", super::as_pretty_json(&animal)), + "{\n \ + \"variant\": \"Frog\",\n \ + \"fields\": [\n \ + \"Henry\",\n \ + 349\n \ + ]\n\ + }" + ); + } + + macro_rules! check_encoder_for_simple { + ($value:expr, $expected:expr) => ({ + let s = format!("{}", super::as_json(&$value)); + assert_eq!(s, $expected); + + let s = format!("{}", super::as_pretty_json(&$value)); + assert_eq!(s, $expected); + }) + } + + #[test] + fn test_write_some() { + check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\""); + } + + #[test] + fn test_write_none() { + check_encoder_for_simple!(None::<string::String>, "null"); + } + + #[test] + fn test_write_char() { + check_encoder_for_simple!('a', "\"a\""); + check_encoder_for_simple!('\t', "\"\\t\""); + check_encoder_for_simple!('\u{0000}', "\"\\u0000\""); + check_encoder_for_simple!('\u{001b}', "\"\\u001b\""); + check_encoder_for_simple!('\u{007f}', "\"\\u007f\""); + check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\""); + check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\""); + check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\""); + } + + #[test] + fn test_trailing_characters() { + assert_eq!(Json::from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(Json::from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(Json::from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6))); + assert_eq!(Json::from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2))); + assert_eq!(Json::from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3))); + assert_eq!(Json::from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3))); + } + + #[test] + fn test_read_identifiers() { + assert_eq!(Json::from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(Json::from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(Json::from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(Json::from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(Json::from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(Json::from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3))); + + assert_eq!(Json::from_str("null"), Ok(Null)); + assert_eq!(Json::from_str("true"), Ok(Boolean(true))); + assert_eq!(Json::from_str("false"), Ok(Boolean(false))); + assert_eq!(Json::from_str(" null "), Ok(Null)); + assert_eq!(Json::from_str(" true "), Ok(Boolean(true))); + assert_eq!(Json::from_str(" false "), Ok(Boolean(false))); + } + + #[test] + fn test_decode_identifiers() { + let v: () = super::decode("null").unwrap(); + assert_eq!(v, ()); + + let v: bool = super::decode("true").unwrap(); + assert_eq!(v, true); + + let v: bool = super::decode("false").unwrap(); + assert_eq!(v, false); + } + + #[test] + fn test_read_number() { + assert_eq!(Json::from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1))); + assert_eq!(Json::from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1))); + assert_eq!(Json::from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1))); + assert_eq!(Json::from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2))); + assert_eq!(Json::from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2))); + assert_eq!(Json::from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3))); + assert_eq!(Json::from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3))); + assert_eq!(Json::from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4))); + + assert_eq!(Json::from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20))); + assert_eq!(Json::from_str("18446744073709551617"), Err(SyntaxError(InvalidNumber, 1, 20))); + assert_eq!(Json::from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21))); + + assert_eq!(Json::from_str("3"), Ok(U64(3))); + assert_eq!(Json::from_str("3.1"), Ok(F64(3.1))); + assert_eq!(Json::from_str("-1.2"), Ok(F64(-1.2))); + assert_eq!(Json::from_str("0.4"), Ok(F64(0.4))); + assert_eq!(Json::from_str("0.4e5"), Ok(F64(0.4e5))); + assert_eq!(Json::from_str("0.4e+15"), Ok(F64(0.4e15))); + assert_eq!(Json::from_str("0.4e-01"), Ok(F64(0.4e-01))); + assert_eq!(Json::from_str("123456789.5024"), Ok(F64(123456789.5024))); + assert_eq!(Json::from_str(" 3 "), Ok(U64(3))); + + assert_eq!(Json::from_str("-9223372036854775808"), Ok(I64(i64::MIN))); + assert_eq!(Json::from_str("9223372036854775807"), Ok(U64(i64::MAX as u64))); + assert_eq!(Json::from_str("18446744073709551615"), Ok(U64(u64::MAX))); + } + + #[test] + fn test_decode_numbers() { + let v: f64 = super::decode("3").unwrap(); + assert_eq!(v, 3.0); + + let v: f64 = super::decode("3.1").unwrap(); + assert_eq!(v, 3.1); + + let v: f64 = super::decode("-1.2").unwrap(); + assert_eq!(v, -1.2); + + let v: f64 = super::decode("0.4").unwrap(); + assert_eq!(v, 0.4); + + let v: f64 = super::decode("0.4e5").unwrap(); + assert_eq!(v, 0.4e5); + + let v: f64 = super::decode("0.4e15").unwrap(); + assert_eq!(v, 0.4e15); + + let v: f64 = super::decode("0.4e-01").unwrap(); + assert_eq!(v, 0.4e-01); + + let v: f64 = super::decode("123456789.5024").unwrap(); + assert_eq!(v, 123456789.5024); + + let v: u64 = super::decode("0").unwrap(); + assert_eq!(v, 0); + + let v: u64 = super::decode("18446744073709551615").unwrap(); + assert_eq!(v, u64::MAX); + + let v: i64 = super::decode("-9223372036854775808").unwrap(); + assert_eq!(v, i64::MIN); + + let v: i64 = super::decode("9223372036854775807").unwrap(); + assert_eq!(v, i64::MAX); + + let res: DecodeResult<i64> = super::decode("765.25252"); + match res { + Ok(..) => panic!("expected an error"), + Err(ExpectedError(ref s, _)) => assert_eq!(s, "Integer"), + Err(..) => panic!("expected an 'expected integer' error"), + } + } + + #[test] + fn test_read_str() { + assert_eq!(Json::from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2))); + assert_eq!(Json::from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5))); + assert_eq!(Json::from_str("\"\n\""), Err(SyntaxError(ControlCharacterInString, 2, 1))); + assert_eq!(Json::from_str("\"\0\""), Err(SyntaxError(ControlCharacterInString, 1, 2))); + assert_eq!(Json::from_str("\"\u{1}\""), Err(SyntaxError(ControlCharacterInString, 1, 2))); + assert_eq!(Json::from_str("\"\u{1F}\""), Err(SyntaxError(ControlCharacterInString, 1, 2))); + + // Only C0 control characters are excluded. + assert!('\u{7F}'.is_control()); + assert!('\u{80}'.is_control()); + assert!('\u{9F}'.is_control()); + let c1_controls = "\u{7F}\u{80}\u{9F}".to_string(); + assert_eq!(Json::from_str(&format!("\"{}\"", c1_controls)), Ok(String(c1_controls))); + + assert_eq!(Json::from_str("\"\""), Ok(String("".to_string()))); + assert_eq!(Json::from_str("\"foo\""), Ok(String("foo".to_string()))); + assert_eq!(Json::from_str("\"\\\"\""), Ok(String("\"".to_string()))); + assert_eq!(Json::from_str("\"\\b\""), Ok(String("\x08".to_string()))); + assert_eq!(Json::from_str("\"\\n\""), Ok(String("\n".to_string()))); + assert_eq!(Json::from_str("\"\\r\""), Ok(String("\r".to_string()))); + assert_eq!(Json::from_str("\"\\t\""), Ok(String("\t".to_string()))); + assert_eq!(Json::from_str(" \"foo\" "), Ok(String("foo".to_string()))); + assert_eq!(Json::from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string()))); + assert_eq!(Json::from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string()))); + } + + #[test] + fn test_decode_str() { + let s = [("\"\"", ""), + ("\"foo\"", "foo"), + ("\"\\\"\"", "\""), + ("\"\\b\"", "\x08"), + ("\"\\n\"", "\n"), + ("\"\\r\"", "\r"), + ("\"\\t\"", "\t"), + ("\"\\u12ab\"", "\u{12ab}"), + ("\"\\uAB12\"", "\u{AB12}")]; + + for &(i, o) in s.iter() { + let v: string::String = super::decode(i).unwrap(); + assert_eq!(v, o); + } + } + + #[test] + fn test_read_array() { + assert_eq!(Json::from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); + assert_eq!(Json::from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); + assert_eq!(Json::from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); + assert_eq!(Json::from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(Json::from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + + assert_eq!(Json::from_str("[]"), Ok(Array(vec![]))); + assert_eq!(Json::from_str("[ ]"), Ok(Array(vec![]))); + assert_eq!(Json::from_str("[true]"), Ok(Array(vec![Boolean(true)]))); + assert_eq!(Json::from_str("[ false ]"), Ok(Array(vec![Boolean(false)]))); + assert_eq!(Json::from_str("[null]"), Ok(Array(vec![Null]))); + assert_eq!(Json::from_str("[3, 1]"), + Ok(Array(vec![U64(3), U64(1)]))); + assert_eq!(Json::from_str("\n[3, 2]\n"), + Ok(Array(vec![U64(3), U64(2)]))); + assert_eq!(Json::from_str("[2, [4, 1]]"), + Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])]))); + } + + #[test] + fn test_decode_array() { + let v: Vec<()> = super::decode("[]").unwrap(); + assert_eq!(v, vec![]); + + let v: Vec<()> = super::decode("[null]").unwrap(); + assert_eq!(v, vec![()]); + + let v: Vec<bool> = super::decode("[true]").unwrap(); + assert_eq!(v, vec![true]); + + let v: Vec<isize> = super::decode("[3, 1]").unwrap(); + assert_eq!(v, vec![3, 1]); + + let v: Vec<Vec<usize>> = super::decode("[[3], [1, 2]]").unwrap(); + assert_eq!(v, vec![vec![3], vec![1, 2]]); + } + + #[test] + fn test_decode_tuple() { + let t: (usize, usize, usize) = super::decode("[1, 2, 3]").unwrap(); + assert_eq!(t, (1, 2, 3)); + + let t: (usize, string::String) = super::decode("[1, \"two\"]").unwrap(); + assert_eq!(t, (1, "two".to_string())); + } + + #[test] + fn test_decode_tuple_malformed_types() { + assert!(super::decode::<(usize, string::String)>("[1, 2]").is_err()); + } + + #[test] + fn test_decode_tuple_malformed_length() { + assert!(super::decode::<(usize, usize)>("[1, 2, 3]").is_err()); + } + + #[test] + fn test_read_object() { + assert_eq!(Json::from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2))); + assert_eq!(Json::from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3))); + assert_eq!(Json::from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2))); + assert_eq!(Json::from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6))); + assert_eq!(Json::from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5))); + assert_eq!(Json::from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6))); + + assert_eq!(Json::from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6))); + assert_eq!(Json::from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6))); + assert_eq!(Json::from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7))); + assert_eq!(Json::from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8))); + assert_eq!(Json::from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8))); + + assert_eq!(Json::from_str("{}").unwrap(), mk_object(&[])); + assert_eq!(Json::from_str("{\"a\": 3}").unwrap(), + mk_object(&[("a".to_string(), U64(3))])); + + assert_eq!(Json::from_str( + "{ \"a\": null, \"b\" : true }").unwrap(), + mk_object(&[ + ("a".to_string(), Null), + ("b".to_string(), Boolean(true))])); + assert_eq!(Json::from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(), + mk_object(&[ + ("a".to_string(), Null), + ("b".to_string(), Boolean(true))])); + assert_eq!(Json::from_str( + "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(), + mk_object(&[ + ("a".to_string(), F64(1.0)), + ("b".to_string(), Array(vec![Boolean(true)])) + ])); + assert_eq!(Json::from_str( + "{\ + \"a\": 1.0, \ + \"b\": [\ + true,\ + \"foo\\nbar\", \ + { \"c\": {\"d\": null} } \ + ]\ + }").unwrap(), + mk_object(&[ + ("a".to_string(), F64(1.0)), + ("b".to_string(), Array(vec![ + Boolean(true), + String("foo\nbar".to_string()), + mk_object(&[ + ("c".to_string(), mk_object(&[("d".to_string(), Null)])) + ]) + ])) + ])); + } + + #[test] + fn test_decode_struct() { + let s = "{ + \"inner\": [ + { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] } + ] + }"; + + let v: Outer = super::decode(s).unwrap(); + assert_eq!( + v, + Outer { + inner: vec![ + Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] } + ] + } + ); + } + + #[derive(RustcDecodable)] + struct FloatStruct { + f: f64, + a: Vec<f64> + } + #[test] + fn test_decode_struct_with_nan() { + let s = "{\"f\":null,\"a\":[null,123]}"; + let obj: FloatStruct = super::decode(s).unwrap(); + assert!(obj.f.is_nan()); + assert!(obj.a[0].is_nan()); + assert_eq!(obj.a[1], 123f64); + } + + #[test] + fn test_decode_option() { + let value: Option<string::String> = super::decode("null").unwrap(); + assert_eq!(value, None); + + let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap(); + assert_eq!(value, Some("jodhpurs".to_string())); + } + + #[test] + fn test_decode_enum() { + let value: Animal = super::decode("\"Dog\"").unwrap(); + assert_eq!(value, Dog); + + let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"; + let value: Animal = super::decode(s).unwrap(); + assert_eq!(value, Frog("Henry".to_string(), 349)); + } + + #[test] + fn test_decode_result() { + let value: Result<i32, i8> = Ok(4); + let json_value = super::encode(&value).unwrap(); + assert_eq!(json_value, "{\"variant\":\"Ok\",\"fields\":[4]}"); + let decoded_value: Result<i32, i8> = super::decode(&json_value).unwrap(); + assert_eq!(decoded_value, Ok(4)); + } + + #[test] + fn test_decode_map() { + let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\ + \"fields\":[\"Henry\", 349]}}"; + let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap(); + + assert_eq!(map.remove(&"a".to_string()), Some(Dog)); + assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349))); + } + + #[test] + fn test_multiline_errors() { + assert_eq!(Json::from_str("{\n \"foo\":\n \"bar\""), + Err(SyntaxError(EOFWhileParsingObject, 3, 8))); + } + + #[derive(RustcDecodable)] + #[allow(dead_code)] + struct DecodeStruct { + x: f64, + y: bool, + z: string::String, + w: Vec<DecodeStruct> + } + #[derive(RustcDecodable)] + enum DecodeEnum { + A(f64), + B(string::String) + } + fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) { + let res: DecodeResult<T> = match Json::from_str(to_parse) { + Err(e) => Err(ParseError(e)), + Ok(json) => Decodable::decode(&mut Decoder::new(json)) + }; + match res { + Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`", + to_parse, expected), + Err(ParseError(e)) => panic!("`{}` is not valid json: {:?}", + to_parse, e), + Err(e) => { + assert_eq!(e, expected); + } + } + } + #[test] + fn test_decode_errors_struct() { + check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string())); + check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}", + ExpectedError("Number".to_string(), "true".to_string())); + check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}", + ExpectedError("Boolean".to_string(), "[]".to_string())); + check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}", + ExpectedError("String".to_string(), "{}".to_string())); + check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}", + ExpectedError("Array".to_string(), "null".to_string())); + check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}", + MissingFieldError("w".to_string())); + } + #[test] + fn test_decode_errors_enum() { + check_err::<DecodeEnum>("{}", + MissingFieldError("variant".to_string())); + check_err::<DecodeEnum>("{\"variant\": 1}", + ExpectedError("String".to_string(), "1".to_string())); + check_err::<DecodeEnum>("{\"variant\": \"A\"}", + MissingFieldError("fields".to_string())); + check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}", + ExpectedError("Array".to_string(), "null".to_string())); + check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}", + UnknownVariantError("C".to_string())); + } + + #[test] + fn test_find(){ + let json_value = Json::from_str("{\"dog\" : \"cat\"}").unwrap(); + let found_str = json_value.find("dog"); + assert!(found_str.unwrap().as_string().unwrap() == "cat"); + } + + #[test] + fn test_find_path(){ + let json_value = Json::from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap(); + let found_str = json_value.find_path(&["dog", "cat", "mouse"]); + assert!(found_str.unwrap().as_string().unwrap() == "cheese"); + } + + #[test] + fn test_search(){ + let json_value = Json::from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap(); + let found_str = json_value.search("mouse").and_then(|j| j.as_string()); + assert!(found_str.unwrap() == "cheese"); + } + + #[test] + fn test_index(){ + let json_value = Json::from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap(); + let ref array = json_value["animals"]; + assert_eq!(array[0].as_string().unwrap(), "dog"); + assert_eq!(array[1].as_string().unwrap(), "cat"); + assert_eq!(array[2].as_string().unwrap(), "mouse"); + } + + #[test] + fn test_is_object(){ + let json_value = Json::from_str("{}").unwrap(); + assert!(json_value.is_object()); + } + + #[test] + fn test_as_object(){ + let json_value = Json::from_str("{}").unwrap(); + let json_object = json_value.as_object(); + assert!(json_object.is_some()); + } + + #[test] + fn test_is_array(){ + let json_value = Json::from_str("[1, 2, 3]").unwrap(); + assert!(json_value.is_array()); + } + + #[test] + fn test_as_array(){ + let json_value = Json::from_str("[1, 2, 3]").unwrap(); + let json_array = json_value.as_array(); + let expected_length = 3; + assert!(json_array.is_some() && json_array.unwrap().len() == expected_length); + } + + #[test] + fn test_is_string(){ + let json_value = Json::from_str("\"dog\"").unwrap(); + assert!(json_value.is_string()); + } + + #[test] + fn test_as_string(){ + let json_value = Json::from_str("\"dog\"").unwrap(); + let json_str = json_value.as_string(); + let expected_str = "dog"; + assert_eq!(json_str, Some(expected_str)); + } + + #[test] + fn test_is_number(){ + let json_value = Json::from_str("12").unwrap(); + assert!(json_value.is_number()); + } + + #[test] + fn test_is_i64(){ + let json_value = Json::from_str("-12").unwrap(); + assert!(json_value.is_i64()); + + let json_value = Json::from_str("12").unwrap(); + assert!(!json_value.is_i64()); + + let json_value = Json::from_str("12.0").unwrap(); + assert!(!json_value.is_i64()); + } + + #[test] + fn test_is_u64(){ + let json_value = Json::from_str("12").unwrap(); + assert!(json_value.is_u64()); + + let json_value = Json::from_str("-12").unwrap(); + assert!(!json_value.is_u64()); + + let json_value = Json::from_str("12.0").unwrap(); + assert!(!json_value.is_u64()); + } + + #[test] + fn test_is_f64(){ + let json_value = Json::from_str("12").unwrap(); + assert!(!json_value.is_f64()); + + let json_value = Json::from_str("-12").unwrap(); + assert!(!json_value.is_f64()); + + let json_value = Json::from_str("12.0").unwrap(); + assert!(json_value.is_f64()); + + let json_value = Json::from_str("-12.0").unwrap(); + assert!(json_value.is_f64()); + } + + #[test] + fn test_as_i64(){ + let json_value = Json::from_str("-12").unwrap(); + let json_num = json_value.as_i64(); + assert_eq!(json_num, Some(-12)); + } + + #[test] + fn test_as_u64(){ + let json_value = Json::from_str("12").unwrap(); + let json_num = json_value.as_u64(); + assert_eq!(json_num, Some(12)); + } + + #[test] + fn test_as_f64(){ + let json_value = Json::from_str("12.0").unwrap(); + let json_num = json_value.as_f64(); + assert_eq!(json_num, Some(12f64)); + } + + #[test] + fn test_is_boolean(){ + let json_value = Json::from_str("false").unwrap(); + assert!(json_value.is_boolean()); + } + + #[test] + fn test_as_boolean(){ + let json_value = Json::from_str("false").unwrap(); + let json_bool = json_value.as_boolean(); + let expected_bool = false; + assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool); + } + + #[test] + fn test_is_null(){ + let json_value = Json::from_str("null").unwrap(); + assert!(json_value.is_null()); + } + + #[test] + fn test_as_null(){ + let json_value = Json::from_str("null").unwrap(); + let json_null = json_value.as_null(); + let expected_null = (); + assert!(json_null.is_some() && json_null.unwrap() == expected_null); + } + + #[test] + fn test_encode_hashmap_with_numeric_key() { + use std::collections::HashMap; + let mut hm: HashMap<usize, bool> = HashMap::new(); + hm.insert(1, true); + let json_str = super::as_pretty_json(&hm).to_string(); + match Json::from_str(&json_str) { + Err(_) => panic!("Unable to parse json_str: {}", json_str), + _ => {} // it parsed and we are good to go + } + } + + #[test] + fn test_negative_zero() { + Json::from_str("{\"test\":-0}").unwrap(); + } + + #[test] + fn test_prettyencode_hashmap_with_numeric_key() { + use std::collections::HashMap; + let mut hm: HashMap<usize, bool> = HashMap::new(); + hm.insert(1, true); + let json_str = super::as_pretty_json(&hm).to_string(); + match Json::from_str(&json_str) { + Err(_) => panic!("Unable to parse json_str: {}", json_str), + _ => {} // it parsed and we are good to go + } + } + + #[test] + fn test_prettyencoder_indent_level_param() { + use std::collections::BTreeMap; + + let mut tree = BTreeMap::new(); + + tree.insert("hello".to_string(), String("guten tag".to_string())); + tree.insert("goodbye".to_string(), String("sayonara".to_string())); + + let json = Array( + // The following layout below should look a lot like + // the pretty-printed JSON (indent * x) + vec! + ( // 0x + String("greetings".to_string()), // 1x + Object(tree), // 1x + 2x + 2x + 1x + ) // 0x + // End JSON array (7 lines) + ); + + // Helper function for counting indents + fn indents(source: &str) -> usize { + let trimmed = source.trim_left_matches(' '); + source.len() - trimmed.len() + } + + // Test up to 4 spaces of indents (more?) + for i in 0..4 { + let printed = super::as_pretty_json(&json).indent(i as u32) + .to_string(); + + // Check for indents at each line + let lines: Vec<&str> = printed.lines().collect(); + assert_eq!(lines.len(), 7); // JSON should be 7 lines + + assert_eq!(indents(lines[0]), 0 * i); // [ + assert_eq!(indents(lines[1]), 1 * i); // "greetings", + assert_eq!(indents(lines[2]), 1 * i); // { + assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag", + assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara" + assert_eq!(indents(lines[5]), 1 * i); // }, + assert_eq!(indents(lines[6]), 0 * i); // ] + + // Finally, test that the pretty-printed JSON is valid + Json::from_str(&printed).ok() + .expect("Pretty-printed JSON is invalid!"); + } + } + + #[test] + fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() { + use std::collections::HashMap; + use Decodable; + let json_str = "{\"1\":true}"; + let json_obj = match Json::from_str(json_str) { + Err(_) => panic!("Unable to parse json_str: {}", json_str), + Ok(o) => o + }; + let mut decoder = Decoder::new(json_obj); + let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap(); + } + + #[test] + fn test_hashmap_with_enum_key() { + use std::collections::HashMap; + use json; + #[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Debug)] + enum Enum { + Foo, + #[allow(dead_code)] + Bar, + } + let mut map = HashMap::new(); + map.insert(Enum::Foo, 0); + let result = json::encode(&map).unwrap(); + assert_eq!(result, r#"{"Foo":0}"#); + let decoded: HashMap<Enum, _> = json::decode(&result).unwrap(); + assert_eq!(map, decoded); + } + + #[test] + fn test_hashmap_with_numeric_key_will_error_with_string_keys() { + use std::collections::HashMap; + use Decodable; + let json_str = "{\"a\":true}"; + let json_obj = match Json::from_str(json_str) { + Err(_) => panic!("Unable to parse json_str: {}", json_str), + Ok(o) => o + }; + let mut decoder = Decoder::new(json_obj); + let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder); + assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string()))); + } + + fn assert_stream_equal(src: &str, + expected: Vec<(JsonEvent, Vec<StackElement>)>) { + let mut parser = Parser::new(src.chars()); + let mut i = 0; + loop { + let evt = match parser.next() { + Some(e) => e, + None => { break; } + }; + let (ref expected_evt, ref expected_stack) = expected[i]; + if !parser.stack().is_equal_to(&expected_stack) { + panic!("Parser stack is not equal to {:?}", expected_stack); + } + assert_eq!(&evt, expected_evt); + i+=1; + } + } + #[test] + #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) + fn test_streaming_parser() { + assert_stream_equal( + r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#, + vec![ + (ObjectStart, vec![]), + (StringValue("bar".to_string()), vec![Key("foo")]), + (ArrayStart, vec![Key("array")]), + (U64Value(0), vec![Key("array"), Index(0)]), + (U64Value(1), vec![Key("array"), Index(1)]), + (U64Value(2), vec![Key("array"), Index(2)]), + (U64Value(3), vec![Key("array"), Index(3)]), + (U64Value(4), vec![Key("array"), Index(4)]), + (U64Value(5), vec![Key("array"), Index(5)]), + (ArrayEnd, vec![Key("array")]), + (ArrayStart, vec![Key("idents")]), + (NullValue, vec![Key("idents"), Index(0)]), + (BooleanValue(true), vec![Key("idents"), Index(1)]), + (BooleanValue(false), vec![Key("idents"), Index(2)]), + (ArrayEnd, vec![Key("idents")]), + (ObjectEnd, vec![]), + ] + ); + } + fn last_event(src: &str) -> JsonEvent { + let mut parser = Parser::new(src.chars()); + let mut evt = NullValue; + loop { + evt = match parser.next() { + Some(e) => e, + None => return evt, + } + } + } + + #[test] + #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) + fn test_read_object_streaming() { + assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3))); + assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2))); + assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6))); + assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5))); + assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6))); + + assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6))); + assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6))); + assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7))); + assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8))); + assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8))); + assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8))); + + assert_stream_equal( + "{}", + vec![(ObjectStart, vec![]), (ObjectEnd, vec![])] + ); + assert_stream_equal( + "{\"a\": 3}", + vec![ + (ObjectStart, vec![]), + (U64Value(3), vec![Key("a")]), + (ObjectEnd, vec![]), + ] + ); + assert_stream_equal( + "{ \"a\": null, \"b\" : true }", + vec![ + (ObjectStart, vec![]), + (NullValue, vec![Key("a")]), + (BooleanValue(true), vec![Key("b")]), + (ObjectEnd, vec![]), + ] + ); + assert_stream_equal( + "{\"a\" : 1.0 ,\"b\": [ true ]}", + vec![ + (ObjectStart, vec![]), + (F64Value(1.0), vec![Key("a")]), + (ArrayStart, vec![Key("b")]), + (BooleanValue(true),vec![Key("b"), Index(0)]), + (ArrayEnd, vec![Key("b")]), + (ObjectEnd, vec![]), + ] + ); + assert_stream_equal( + r#"{ + "a": 1.0, + "b": [ + true, + "foo\nbar", + { "c": {"d": null} }, + "\uD834\uDF06" + ] + }"#, + vec![ + (ObjectStart, vec![]), + (F64Value(1.0), vec![Key("a")]), + (ArrayStart, vec![Key("b")]), + (BooleanValue(true), vec![Key("b"), Index(0)]), + (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]), + (ObjectStart, vec![Key("b"), Index(2)]), + (ObjectStart, vec![Key("b"), Index(2), Key("c")]), + (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]), + (ObjectEnd, vec![Key("b"), Index(2), Key("c")]), + (ObjectEnd, vec![Key("b"), Index(2)]), + (StringValue("\u{1D306}".to_string()), vec![Key("b"), Index(3)]), + (ArrayEnd, vec![Key("b")]), + (ObjectEnd, vec![]), + ] + ); + } + #[test] + #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) + fn test_read_array_streaming() { + assert_stream_equal( + "[]", + vec![ + (ArrayStart, vec![]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "[ ]", + vec![ + (ArrayStart, vec![]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "[true]", + vec![ + (ArrayStart, vec![]), + (BooleanValue(true), vec![Index(0)]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "[ false ]", + vec![ + (ArrayStart, vec![]), + (BooleanValue(false), vec![Index(0)]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "[null]", + vec![ + (ArrayStart, vec![]), + (NullValue, vec![Index(0)]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "[3, 1]", + vec![ + (ArrayStart, vec![]), + (U64Value(3), vec![Index(0)]), + (U64Value(1), vec![Index(1)]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "\n[3, 2]\n", + vec![ + (ArrayStart, vec![]), + (U64Value(3), vec![Index(0)]), + (U64Value(2), vec![Index(1)]), + (ArrayEnd, vec![]), + ] + ); + assert_stream_equal( + "[2, [4, 1]]", + vec![ + (ArrayStart, vec![]), + (U64Value(2), vec![Index(0)]), + (ArrayStart, vec![Index(1)]), + (U64Value(4), vec![Index(1), Index(0)]), + (U64Value(1), vec![Index(1), Index(1)]), + (ArrayEnd, vec![Index(1)]), + (ArrayEnd, vec![]), + ] + ); + + assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2))); + + assert_eq!(Json::from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); + assert_eq!(Json::from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); + assert_eq!(Json::from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); + assert_eq!(Json::from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(Json::from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + + } + #[test] + fn test_trailing_characters_streaming() { + assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6))); + assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2))); + assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3))); + assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3))); + } + #[test] + fn test_read_identifiers_streaming() { + assert_eq!(Parser::new("null".chars()).next(), Some(NullValue)); + assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true))); + assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false))); + + assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3))); + } + + #[test] + fn test_stack() { + let mut stack = Stack::new(); + + assert!(stack.is_empty()); + assert!(stack.len() == 0); + assert!(!stack.last_is_index()); + + stack.push_index(0); + stack.bump_index(); + + assert!(stack.len() == 1); + assert!(stack.is_equal_to(&[Index(1)])); + assert!(stack.starts_with(&[Index(1)])); + assert!(stack.ends_with(&[Index(1)])); + assert!(stack.last_is_index()); + assert!(stack.get(0) == Index(1)); + + stack.push_key("foo".to_string()); + + assert!(stack.len() == 2); + assert!(stack.is_equal_to(&[Index(1), Key("foo")])); + assert!(stack.starts_with(&[Index(1), Key("foo")])); + assert!(stack.starts_with(&[Index(1)])); + assert!(stack.ends_with(&[Index(1), Key("foo")])); + assert!(stack.ends_with(&[Key("foo")])); + assert!(!stack.last_is_index()); + assert!(stack.get(0) == Index(1)); + assert!(stack.get(1) == Key("foo")); + + stack.push_key("bar".to_string()); + + assert!(stack.len() == 3); + assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")])); + assert!(stack.starts_with(&[Index(1)])); + assert!(stack.starts_with(&[Index(1), Key("foo")])); + assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")])); + assert!(stack.ends_with(&[Key("bar")])); + assert!(stack.ends_with(&[Key("foo"), Key("bar")])); + assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")])); + assert!(!stack.last_is_index()); + assert!(stack.get(0) == Index(1)); + assert!(stack.get(1) == Key("foo")); + assert!(stack.get(2) == Key("bar")); + + stack.pop(); + + assert!(stack.len() == 2); + assert!(stack.is_equal_to(&[Index(1), Key("foo")])); + assert!(stack.starts_with(&[Index(1), Key("foo")])); + assert!(stack.starts_with(&[Index(1)])); + assert!(stack.ends_with(&[Index(1), Key("foo")])); + assert!(stack.ends_with(&[Key("foo")])); + assert!(!stack.last_is_index()); + assert!(stack.get(0) == Index(1)); + assert!(stack.get(1) == Key("foo")); + } + + #[test] + fn test_to_json() { + use std::collections::{HashMap,BTreeMap}; + use super::ToJson; + + let array2 = Array(vec!(I64(1), I64(2))); + let array3 = Array(vec!(I64(1), I64(2), I64(3))); + let object = { + let mut tree_map = BTreeMap::new(); + tree_map.insert("a".to_string(), U64(1)); + tree_map.insert("b".to_string(), U64(2)); + Object(tree_map) + }; + + assert_eq!(array2.to_json(), array2); + assert_eq!(object.to_json(), object); + assert_eq!(3_isize.to_json(), I64(3)); + assert_eq!(4_i8.to_json(), I64(4)); + assert_eq!(5_i16.to_json(), I64(5)); + assert_eq!(6_i32.to_json(), I64(6)); + assert_eq!(7_i64.to_json(), I64(7)); + assert_eq!(8_usize.to_json(), U64(8)); + assert_eq!(9_u8.to_json(), U64(9)); + assert_eq!(10_u16.to_json(), U64(10)); + assert_eq!(11_u32.to_json(), U64(11)); + assert_eq!(12_u64.to_json(), U64(12)); + assert_eq!(13.0_f32.to_json(), F64(13.0_f64)); + assert_eq!(14.0_f64.to_json(), F64(14.0_f64)); + assert_eq!(().to_json(), Null); + assert_eq!(f32::INFINITY.to_json(), Null); + assert_eq!(f64::NAN.to_json(), Null); + assert_eq!(true.to_json(), Boolean(true)); + assert_eq!(false.to_json(), Boolean(false)); + assert_eq!("abc".to_json(), String("abc".to_string())); + assert_eq!("abc".to_string().to_json(), String("abc".to_string())); + assert_eq!((1, 2).to_json(), array2); + assert_eq!((1, 2, 3).to_json(), array3); + assert_eq!([1, 2].to_json(), array2); + assert_eq!((&[1, 2, 3]).to_json(), array3); + assert_eq!((vec![1, 2]).to_json(), array2); + assert_eq!(vec!(1, 2, 3).to_json(), array3); + let mut tree_map = BTreeMap::new(); + tree_map.insert("a".to_string(), 1 as u32); + tree_map.insert("b".to_string(), 2); + assert_eq!(tree_map.to_json(), object); + let mut hash_map = HashMap::new(); + hash_map.insert("a".to_string(), 1 as u32); + hash_map.insert("b".to_string(), 2); + assert_eq!(hash_map.to_json(), object); + assert_eq!(Some(15).to_json(), I64(15)); + assert_eq!(Some(15 as u32).to_json(), U64(15)); + assert_eq!(None::<isize>.to_json(), Null); + } + + #[test] + fn test_encode_hashmap_with_arbitrary_key() { + use std::collections::HashMap; + #[derive(PartialEq, Eq, Hash, RustcEncodable)] + struct ArbitraryType(u32); + let mut hm: HashMap<ArbitraryType, bool> = HashMap::new(); + hm.insert(ArbitraryType(1), true); + let mut mem_buf = string::String::new(); + let mut encoder = Encoder::new(&mut mem_buf); + let result = hm.encode(&mut encoder); + match result.err().unwrap() { + EncoderError::BadHashmapKey => (), + _ => panic!("expected bad hash map key") + } + } + + #[test] + fn test_encode_decode_phantom_data() { + use std::marker::PhantomData; + + #[derive(Debug, RustcDecodable, RustcEncodable, Eq, PartialEq)] + struct Foo<P> { + phantom_data: PhantomData<P> + } + + let f: Foo<u8> = Foo { + phantom_data: PhantomData + }; + let s = super::encode(&f).unwrap(); + let d: Foo<u8> = super::decode(&s).unwrap(); + assert_eq!(f, d); + } + + #[test] + fn test_bad_json_stack_depleted() { + use json; + #[derive(Debug, RustcDecodable)] + enum ChatEvent { + Variant(i32) + } + let serialized = "{\"variant\": \"Variant\", \"fields\": []}"; + let r: Result<ChatEvent, _> = json::decode(serialized); + assert!(r.unwrap_err() == EOF); + } + + #[test] + fn fixed_length_array() { + #[derive(Debug, RustcDecodable, RustcEncodable, Eq, PartialEq)] + struct Foo { + a: [u8; 1], + b: [i32; 2], + c: [u64; 3], + } + let f = Foo { + a: [0], + b: [1, 2], + c: [3, 4, 5], + }; + let s = super::encode(&f).unwrap(); + let d = super::decode(&s).unwrap(); + assert_eq!(f, d); + } + + #[test] + fn test_unexpected_token() { + match Json::from_str("{\"\":\"\",\"\":{\"\":\"\",\"\":[{\"\":\"\",}}}") { + Err(e) => assert_eq!(e, SyntaxError(InvalidSyntax, 1, 32)), + _ => () + }; + } +} diff --git a/bash-5.1/vendor/rustc-serialize/src/lib.rs b/bash-5.1/vendor/rustc-serialize/src/lib.rs new file mode 100644 index 0000000..8b0fb22 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/src/lib.rs @@ -0,0 +1,79 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Support code for encoding and decoding types. +//! +//! > **NOTE**: This crate is deprecated in favor of [`serde`]. No new feature +//! > development will happen in this crate, although bug fixes proposed through +//! > PRs will still be merged. It is very highly recommended by the Rust +//! > Library Team that you use [`serde`], not this crate. +//! +//! [`serde`]: https://serde.rs +//! +//! # Usage +//! +//! This crate is [on crates.io](https://crates.io/crates/rustc-serialize) and +//! can be used by adding `rustc-serialize` to the dependencies in your +//! project's `Cargo.toml`. +//! +//! ```toml +//! [dependencies] +//! rustc-serialize = "0.3" +//! ``` +//! +//! and this to your crate root: +//! +//! ```rust +//! extern crate rustc_serialize; +//! ``` + +#![cfg_attr(rustbuild, feature(staged_api, rustc_private))] +#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/rustc-serialize/")] +#![cfg_attr(test, deny(warnings))] +#![allow(trivial_numeric_casts)] +#![cfg_attr(rust_build, feature(staged_api))] +#![cfg_attr(rust_build, staged_api)] +#![cfg_attr(rust_build, + unstable(feature = "rustc_private", + reason = "use the crates.io `rustc-serialize` library instead"))] + +#[cfg(test)] extern crate rand; + +pub use self::serialize::{Decoder, Encoder, Decodable, Encodable, + DecoderHelpers, EncoderHelpers}; + + +// Limit collections from allocating more than +// 1 MB for calls to `with_capacity`. +fn cap_capacity<T>(given_len: usize) -> usize { + use std::cmp::min; + use std::mem::size_of; + const PRE_ALLOCATE_CAP: usize = 0x100000; + + match size_of::<T>() { + 0 => min(given_len, PRE_ALLOCATE_CAP), + n => min(given_len, PRE_ALLOCATE_CAP / n) + } +} + +mod serialize; +mod collection_impls; + +pub mod base64; +pub mod hex; +pub mod json; + +mod rustc_serialize { + pub use serialize::*; +} diff --git a/bash-5.1/vendor/rustc-serialize/src/serialize.rs b/bash-5.1/vendor/rustc-serialize/src/serialize.rs new file mode 100644 index 0000000..296f3d4 --- /dev/null +++ b/bash-5.1/vendor/rustc-serialize/src/serialize.rs @@ -0,0 +1,1671 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Support code for encoding and decoding types. +//! +//! In order to allow extensibility in both what types can be encoded and how +//! they are encoded, encoding and decoding are split into two part each. An +//! implementation of the Encodable trait knows how to turn a specific type into +//! a generic form, and then uses an implementation of the Encoder trait to turn +//! this into concrete output (such as a JSON string). Decoder and Decodable do +//! the same for decoding. + +/* +Core encoding and decoding interfaces. +*/ + +use std::cell::{Cell, RefCell}; +use std::ffi::OsString; +use std::path; +use std::rc::Rc; +use std::sync::Arc; +use std::marker::PhantomData; +use std::borrow::Cow; + +use cap_capacity; + +/// Trait for writing out an encoding when serializing. +/// +/// This trait provides methods to encode basic types and generic forms of +/// collections. Implementations of `Encodable` use it to perform the actual +/// encoding of a type. +/// +/// It is unspecified what is done with the encoding - it could be stored in a +/// variable, or written directly to a file, for example. +/// +/// Encoders can expect to only have a single "root" method call made on this +/// trait. Non-trivial types will call one of the collection-emitting methods, +/// passing a function that may call other methods on the trait, but once the +/// collection-emitting method has returned, encoding should be complete. +pub trait Encoder { + /// The error type for method results. + type Error; + + // Primitive types: + /// Emit a nil value. + /// + /// For example, this might be stored as the null keyword in JSON. + fn emit_nil(&mut self) -> Result<(), Self::Error>; + + /// Emit a usize value. + fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>; + + /// Emit a u64 value. + fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>; + + /// Emit a u32 value. + fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>; + + /// Emit a u16 value. + fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>; + + /// Emit a u8 value. + fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>; + + /// Emit a isize value. + fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>; + + /// Emit a i64 value. + fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>; + + /// Emit a i32 value. + fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>; + + /// Emit a i16 value. + fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>; + + /// Emit a i8 value. + fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>; + + /// Emit a bool value. + /// + /// For example, this might be stored as the true and false keywords in + /// JSON. + fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>; + + /// Emit a f64 value. + fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>; + + /// Emit a f32 value. + fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>; + + /// Emit a char value. + /// + /// Note that strings should be emitted using `emit_str`, not as a sequence + /// of `emit_char` calls. + fn emit_char(&mut self, v: char) -> Result<(), Self::Error>; + + /// Emit a string value. + fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>; + + // Compound types: + /// Emit an enumeration value. + /// + /// * `name` indicates the enumeration type name. + /// * `f` is a function that will call `emit_enum_variant` or + /// `emit_enum_struct_variant` as appropriate to write the actual value. + fn emit_enum<F>(&mut self, name: &str, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a enumeration variant value with no or unnamed data. + /// + /// This should only be called from a function passed to `emit_enum`. + /// Variants with named data should use `emit_enum_struct_variant`. + /// + /// * `v_name` is the variant name + /// * `v_id` is the numeric identifier for the variant. + /// * `len` is the number of data items associated with the variant. + /// * `f` is a function that will call `emit_enum_variant_arg` for each data + /// item. It may not be called if len is 0. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Encodable; + /// use rustc_serialize::Encoder; + /// + /// enum Message { + /// Quit, + /// ChangeColor(i32, i32, i32), + /// } + /// + /// impl Encodable for Message { + /// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + /// s.emit_enum("Message", |s| { + /// match *self { + /// Message::Quit => { + /// s.emit_enum_variant("Quit", 0, 0, |s| Ok(())) + /// } + /// Message::ChangeColor(r, g, b) => { + /// s.emit_enum_variant("ChangeColor", 1, 3, |s| { + /// try!(s.emit_enum_variant_arg(0, |s| { + /// s.emit_i32(r) + /// })); + /// try!(s.emit_enum_variant_arg(1, |s| { + /// s.emit_i32(g) + /// })); + /// try!(s.emit_enum_variant_arg(2, |s| { + /// s.emit_i32(b) + /// })); + /// Ok(()) + /// }) + /// } + /// } + /// }) + /// } + /// } + /// ``` + fn emit_enum_variant<F>(&mut self, v_name: &str, + v_id: usize, + len: usize, + f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit an unnamed data item for an enumeration variant. + /// + /// This should only be called from a function passed to + /// `emit_enum_variant`. + /// + /// * `a_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// Note that variant data items must be emitted in order - starting with + /// index `0` and finishing with index `len-1`. + fn emit_enum_variant_arg<F>(&mut self, a_idx: usize, f: F) + -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a enumeration variant value with no or named data. + /// + /// This should only be called from a function passed to `emit_enum`. + /// Variants with unnamed data should use `emit_enum_variant`. + /// + /// * `v_name` is the variant name. + /// * `v_id` is the numeric identifier for the variant. + /// * `len` is the number of data items associated with the variant. + /// * `f` is a function that will call `emit_enum_struct_variant_field` for + /// each data item. It may not be called if `len` is `0`. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Encodable; + /// use rustc_serialize::Encoder; + /// + /// enum Message { + /// Quit, + /// Move { x: i32, y: i32 }, + /// } + /// + /// impl Encodable for Message { + /// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + /// s.emit_enum("Message", |s| { + /// match *self { + /// Message::Quit => { + /// s.emit_enum_struct_variant("Quit", 0, 0, |s| Ok(())) + /// } + /// Message::Move { x: x, y: y } => { + /// s.emit_enum_struct_variant("Move", 1, 2, |s| { + /// try!(s.emit_enum_struct_variant_field("x", 0, |s| { + /// s.emit_i32(x) + /// })); + /// try!(s.emit_enum_struct_variant_field("y", 1, |s| { + /// s.emit_i32(y) + /// })); + /// Ok(()) + /// }) + /// } + /// } + /// }) + /// } + /// } + /// ``` + fn emit_enum_struct_variant<F>(&mut self, v_name: &str, + v_id: usize, + len: usize, + f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a named data item for an enumeration variant. + /// + /// This should only be called from a function passed to + /// `emit_enum_struct_variant`. + /// + /// * `f_name` is the name of the data item field. + /// * `f_idx` is its (zero-based) index. + /// * `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// Note that fields must be emitted in order - starting with index `0` and + /// finishing with index `len-1`. + fn emit_enum_struct_variant_field<F>(&mut self, + f_name: &str, + f_idx: usize, + f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a struct value. + /// + /// * `name` is the name of the struct. + /// * `len` is the number of members. + /// * `f` is a function that calls `emit_struct_field` for each member. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Encodable; + /// use rustc_serialize::Encoder; + /// + /// struct Point { + /// x: i32, + /// y: i32, + /// } + /// + /// impl Encodable for Point { + /// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + /// s.emit_struct("Point", 2, |s| { + /// try!(s.emit_struct_field("x", 0, |s| { + /// s.emit_i32(self.x) + /// })); + /// try!(s.emit_struct_field("y", 1, |s| { + /// s.emit_i32(self.y) + /// })); + /// Ok(()) + /// }) + /// } + /// } + /// ``` + fn emit_struct<F>(&mut self, name: &str, len: usize, f: F) + -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + /// Emit a field item for a struct. + /// + /// This should only be called from a function passed to `emit_struct`. + /// + /// * `f_name` is the name of the data item field. + /// * `f_idx` is its (zero-based) index. + /// * `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// Note that fields must be emitted in order - starting with index `0` and + /// finishing with index `len-1`. + fn emit_struct_field<F>(&mut self, f_name: &str, f_idx: usize, f: F) + -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a tuple value. + /// + /// * `len` is the number of items in the tuple. + /// * `f` is a function that calls `emit_tuple_arg` for each member. + /// + /// Note that external `Encodable` implementations should not normally need + /// to use this method directly; it is meant for the use of this module's + /// own implementation of `Encodable` for tuples. + fn emit_tuple<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a data item for a tuple. + /// + /// This should only be called from a function passed to `emit_tuple`. + /// + /// * `idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// Note that tuple items must be emitted in order - starting with index `0` + /// and finishing with index `len-1`. + fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a tuple struct value. + /// + /// * `name` is the name of the tuple struct. + /// * `len` is the number of items in the tuple struct. + /// * `f` is a function that calls `emit_tuple_struct_arg` for each member. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Encodable; + /// use rustc_serialize::Encoder; + /// + /// struct Pair(i32,i32); + /// + /// impl Encodable for Pair { + /// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + /// let Pair(first,second) = *self; + /// s.emit_tuple_struct("Pair", 2, |s| { + /// try!(s.emit_tuple_arg(0, |s| { + /// s.emit_i32(first) + /// })); + /// try!(s.emit_tuple_arg(1, |s| { + /// s.emit_i32(second) + /// })); + /// Ok(()) + /// }) + /// } + /// } + /// ``` + fn emit_tuple_struct<F>(&mut self, name: &str, len: usize, f: F) + -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a data item for a tuple struct. + /// + /// This should only be called from a function passed to + /// `emit_tuple_struct`. + /// + /// * `f_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// Note that tuple items must be emitted in order - starting with index `0` + /// and finishing with index `len-1`. + fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) + -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + // Specialized types: + /// Emit an optional value. + /// + /// `f` is a function that will call either `emit_option_none` or + /// `emit_option_some` as appropriate. + /// + /// This method allows encoders to handle `Option<T>` values specially, + /// rather than using the generic enum methods, because many encoding + /// formats have a built-in "optional" concept. + /// + /// Note that external `Encodable` implementations should not normally need + /// to use this method directly; it is meant for the use of this module's + /// own implementation of `Encodable` for `Option<T>`. + fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit the `None` optional value. + /// + /// This should only be called from a function passed to `emit_option`. + fn emit_option_none(&mut self) -> Result<(), Self::Error>; + + /// Emit the `Some(x)` optional value. + /// + /// `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// This should only be called from a function passed to `emit_option`. + fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit a sequence of values. + /// + /// This should be used for both array-like ordered sequences and set-like + /// unordered ones. + /// + /// * `len` is the number of values in the sequence. + /// * `f` is a function that will call `emit_seq_elt` for each value in the + /// sequence. + fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit an element in a sequence. + /// + /// This should only be called from a function passed to `emit_seq`. + /// + /// * `idx` is the (zero-based) index of the value in the sequence. + /// * `f` is a function that will call the appropriate emit method to encode + /// the data object. + /// + /// Note that sequence elements must be emitted in order - starting with + /// index `0` and finishing with index `len-1`. + fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit an associative container (map). + /// + /// * `len` is the number of entries in the map. + /// * `f` is a function that will call `emit_map_elt_key` and + /// `emit_map_elt_val` for each entry in the map. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Encodable; + /// use rustc_serialize::Encoder; + /// + /// struct SimpleMap<K,V> { + /// entries: Vec<(K,V)>, + /// } + /// + /// impl<K:Encodable,V:Encodable> Encodable for SimpleMap<K,V> { + /// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + /// s.emit_map(self.entries.len(), |s| { + /// for (i, e) in self.entries.iter().enumerate() { + /// let (ref k, ref v) = *e; + /// try!(s.emit_map_elt_key(i, |s| k.encode(s))); + /// try!(s.emit_map_elt_val(i, |s| v.encode(s))); + /// } + /// Ok(()) + /// }) + /// } + /// } + /// ``` + fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit the key for an entry in a map. + /// + /// This should only be called from a function passed to `emit_map`. + /// + /// * `idx` is the (zero-based) index of the entry in the map + /// * `f` is a function that will call the appropriate emit method to encode + /// the key. + /// + /// Note that map entries must be emitted in order - starting with index `0` + /// and finishing with index `len-1` - and for each entry, the key should be + /// emitted followed immediately by the value. + fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; + + /// Emit the value for an entry in a map. + /// + /// This should only be called from a function passed to `emit_map`. + /// + /// * `idx` is the (zero-based) index of the entry in the map + /// * `f` is a function that will call the appropriate emit method to encode + /// the value. + /// + /// Note that map entries must be emitted in order - starting with index `0` + /// and finishing with index `len-1` - and for each entry, the key should be + /// emitted followed immediately by the value. + fn emit_map_elt_val<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error> + where F: FnOnce(&mut Self) -> Result<(), Self::Error>; +} + +/// Trait for reading in an encoding for deserialization. +/// +/// This trait provides methods to decode basic types and generic forms of +/// collections. Implementations of `Decodable` use it to perform the actual +/// decoding of a type. +/// +/// Note that, as is typical with deserialization, the design of this API +/// assumes you know in advance the form of the data you are decoding (ie: what +/// type is encoded). +/// +/// Decoders can expect to only have a single "root" method call made on this +/// trait. Non-trivial types will call one of the collection-reading methods, +/// passing a function that may call other methods on the trait, but once the +/// collection-reading method has returned, decoding should be complete. +pub trait Decoder { + /// The error type for method results. + type Error; + + // Primitive types: + /// Read a nil value. + fn read_nil(&mut self) -> Result<(), Self::Error>; + + /// Read a usize value. + fn read_usize(&mut self) -> Result<usize, Self::Error>; + + /// Read a u64 value. + fn read_u64(&mut self) -> Result<u64, Self::Error>; + + /// Read a u32 value. + fn read_u32(&mut self) -> Result<u32, Self::Error>; + + /// Read a u16 value. + fn read_u16(&mut self) -> Result<u16, Self::Error>; + + /// Read a u8 value. + fn read_u8(&mut self) -> Result<u8, Self::Error>; + + /// Read a isize value. + fn read_isize(&mut self) -> Result<isize, Self::Error>; + + /// Read a i64 value. + fn read_i64(&mut self) -> Result<i64, Self::Error>; + + /// Read a i32 value. + fn read_i32(&mut self) -> Result<i32, Self::Error>; + + /// Read a i16 value. + fn read_i16(&mut self) -> Result<i16, Self::Error>; + + /// Read a i8 value. + fn read_i8(&mut self) -> Result<i8, Self::Error>; + + /// Read a bool value. + fn read_bool(&mut self) -> Result<bool, Self::Error>; + + /// Read a f64 value. + fn read_f64(&mut self) -> Result<f64, Self::Error>; + + /// Read a f32 value. + fn read_f32(&mut self) -> Result<f32, Self::Error>; + + /// Read a char value. + fn read_char(&mut self) -> Result<char, Self::Error>; + + /// Read a string value. + fn read_str(&mut self) -> Result<String, Self::Error>; + + // Compound types: + /// Read an enumeration value. + /// + /// * `name` indicates the enumeration type name. It may be used to + /// sanity-check the data being read. + /// * `f` is a function that will call `read_enum_variant` (or + /// `read_enum_struct_variant`) to read the actual value. + fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read an enumeration value. + /// + /// * `names` is a list of the enumeration variant names. + /// * `f` is a function that will call `read_enum_variant_arg` or + /// `read_enum_struct_variant_field` as appropriate to read the + /// associated values. It will be passed the index into `names` for the + /// variant that is encoded. + fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F) + -> Result<T, Self::Error> + where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>; + + /// Read an unnamed data item for an enumeration variant. + /// + /// This should only be called from a function passed to `read_enum_variant` + /// or `read_enum_struct_variant`, and only when the index provided to that + /// function indicates that the variant has associated unnamed data. It + /// should be called once for each associated data item. + /// + /// * `a_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate read method to deocde + /// the data object. + /// + /// Note that variant data items must be read in order - starting with index + /// `0` and finishing with index `len-1`. Implementations may use `a_idx`, + /// the call order or both to select the correct data to decode. + fn read_enum_variant_arg<T, F>(&mut self, a_idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read an enumeration value. + /// + /// This is identical to `read_enum_variant`, and is only provided for + /// symmetry with the `Encoder` API. + fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) + -> Result<T, Self::Error> + where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>; + + /// Read a named data item for an enumeration variant. + /// + /// This should only be called from a function passed to `read_enum_variant` + /// or `read_enum_struct_variant`, and only when the index provided to that + /// function indicates that the variant has associated named data. It should + /// be called once for each associated field. + /// + /// * `f_name` is the name of the field. + /// * `f_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate read method to deocde + /// the data object. + /// + /// Note that fields must be read in order - starting with index `0` and + /// finishing with index `len-1`. Implementations may use `f_idx`, `f_name`, + /// the call order or any combination to choose the correct data to decode, + /// and may (but are not required to) return an error if these are + /// inconsistent. + fn read_enum_struct_variant_field<T, F>(&mut self, + f_name: &str, + f_idx: usize, + f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read an struct value. + /// + /// * `s_name` indicates the struct type name. It may be used to + /// sanity-check the data being read. + /// * `len` indicates the number of fields in the struct. + /// * `f` is a function that will call `read_struct_field` for each field in + /// the struct. + fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read a field for a struct value. + /// + /// This should only be called from a function passed to `read_struct`. It + /// should be called once for each associated field. + /// + /// * `f_name` is the name of the field. + /// * `f_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate read method to deocde + /// the data object. + /// + /// Note that fields must be read in order - starting with index `0` and + /// finishing with index `len-1`. Implementations may use `f_idx`, `f_name`, + /// the call order or any combination to choose the correct data to decode, + /// and may (but are not required to) return an error if these are + /// inconsistent. + fn read_struct_field<T, F>(&mut self, + f_name: &str, + f_idx: usize, + f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read a tuple value. + /// + /// * `len` is the number of items in the tuple. + /// * `f` is a function that will call `read_tuple_arg` for each item in the + /// tuple. + /// + /// Note that external `Decodable` implementations should not normally need + /// to use this method directly; it is meant for the use of this module's + /// own implementation of `Decodable` for tuples. + fn read_tuple<T, F>(&mut self, len: usize, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read a data item for a tuple. + /// + /// This should only be called from a function passed to `read_tuple`. + /// + /// * `a_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate read method to encode + /// the data object. + /// + /// Note that tuple items must be read in order - starting with index `0` + /// and finishing with index `len-1`. + fn read_tuple_arg<T, F>(&mut self, a_idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read a tuple struct value. + /// + /// * `s_name` is the name of the tuple struct. + /// * `len` is the number of items in the tuple struct. + /// * `f` is a function that calls `read_tuple_struct_arg` for each member. + fn read_tuple_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read a data item for a tuple struct. + /// + /// This should only be called from a function passed to + /// `read_tuple_struct`. + /// + /// * `a_idx` is the (zero-based) index of the data item. + /// * `f` is a function that will call the appropriate read method to encode + /// the data object. + /// + /// Note that tuple struct items must be read in order - starting with index + /// `0` and finishing with index `len-1`. + fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + // Specialized types: + /// Read an optional value. + /// + /// `f` is a function that will will be passed be passed `false` if the + /// value is unset, and `true` if it is set. If the function is passed + /// `true`, it will call the appropriate read methods to read the associated + /// data type. + /// + /// This method allows decoders to handle `Option<T>` values specially, + /// rather than using the generic enum methods, because many encoding + /// formats have a built-in "optional" concept. + /// + /// Note that external `Decodable` implementations should not normally need + /// to use this method directly; it is meant for the use of this module's + /// own implementation of `Decodable` for `Option<T>`. + fn read_option<T, F>(&mut self, f: F) -> Result<T, Self::Error> + where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>; + + /// Read a sequence of values. + /// + /// This should be used for both array-like ordered sequences and set-like + /// unordered ones. + /// + /// * `f` is a function that will be passed the length of the sequence, and + /// will call `read_seq_elt` for each value in the sequence. + fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>; + + /// Read an element in the sequence. + /// + /// This should only be called from a function passed to `read_seq`. + /// + /// * `idx` is the (zero-based) index of the value in the sequence. + /// * `f` is a function that will call the appropriate read method to decode + /// the data object. + /// + /// Note that sequence elements must be read in order - starting with index + /// `0` and finishing with index `len-1`. + fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read an associative container (map). + /// + /// * `f` is a function that will be passed the number of entries in the + /// map, and will call `read_map_elt_key` and `read_map_elt_val` to decode + /// each entry. + fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>; + + /// Read the key for an entry in a map. + /// + /// This should only be called from a function passed to `read_map`. + /// + /// * `idx` is the (zero-based) index of the entry in the map + /// * `f` is a function that will call the appropriate read method to decode + /// the key. + /// + /// Note that map entries must be read in order - starting with index `0` + /// and finishing with index `len-1` - and for each entry, the key should be + /// read followed immediately by the value. + fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + /// Read the value for an entry in a map. + /// + /// This should only be called from a function passed to `read_map`. + /// + /// * `idx` is the (zero-based) index of the entry in the map + /// * `f` is a function that will call the appropriate read method to decode + /// the value. + /// + /// Note that map entries must be read in order - starting with index `0` + /// and finishing with index `len-1` - and for each entry, the key should be + /// read followed immediately by the value. + fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error>; + + // Failure + /// Record a decoding error. + /// + /// This allows `Decodable` implementations to report an error using a + /// `Decoder` implementation's error type when inconsistent data is read. + /// For example, when reading a fixed-length array and the wrong length is + /// given by `read_seq`. + fn error(&mut self, err: &str) -> Self::Error; +} + +/// Trait for serializing a type. +/// +/// This can be implemented for custom data types to allow them to be encoded +/// with `Encoder` implementations. Most of Rust's built-in or standard data +/// types (like `i32` and `Vec<T>`) have `Encodable` implementations provided by +/// this module. +/// +/// Note that, in general, you should let the compiler implement this for you by +/// using the `derive(RustcEncodable)` attribute. +/// +/// # Examples +/// +/// ```rust +/// extern crate rustc_serialize; +/// +/// #[derive(RustcEncodable)] +/// struct Point { +/// x: i32, +/// y: i32, +/// } +/// # fn main() {} +/// ``` +/// +/// This generates code equivalent to: +/// +/// ```rust +/// extern crate rustc_serialize; +/// use rustc_serialize::Encodable; +/// use rustc_serialize::Encoder; +/// +/// struct Point { +/// x: i32, +/// y: i32, +/// } +/// +/// impl Encodable for Point { +/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { +/// s.emit_struct("Point", 2, |s| { +/// try!(s.emit_struct_field("x", 0, |s| { +/// s.emit_i32(self.x) +/// })); +/// try!(s.emit_struct_field("y", 1, |s| { +/// s.emit_i32(self.y) +/// })); +/// Ok(()) +/// }) +/// } +/// } +/// # fn main() {} +/// ``` +pub trait Encodable { + /// Serialize a value using an `Encoder`. + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>; +} + +/// Trait for deserializing a type. +/// +/// This can be implemented for custom data types to allow them to be decoded +/// with `Decoder` implementations. Most of Rust's built-in or standard data +/// types (like `i32` and `Vec<T>`) have `Decodable` implementations provided by +/// this module. +/// +/// Note that, in general, you should let the compiler implement this for you by +/// using the `derive(RustcDecodable)` attribute. +/// +/// # Examples +/// +/// ```rust +/// extern crate rustc_serialize; +/// +/// #[derive(RustcDecodable)] +/// struct Point { +/// x: i32, +/// y: i32, +/// } +/// # fn main() {} +/// ``` +/// +/// This generates code equivalent to: +/// +/// ```rust +/// extern crate rustc_serialize; +/// use rustc_serialize::Decodable; +/// use rustc_serialize::Decoder; +/// +/// struct Point { +/// x: i32, +/// y: i32, +/// } +/// +/// impl Decodable for Point { +/// fn decode<D: Decoder>(d: &mut D) -> Result<Point, D::Error> { +/// d.read_struct("Point", 2, |d| { +/// let x = try!(d.read_struct_field("x", 0, |d| { d.read_i32() })); +/// let y = try!(d.read_struct_field("y", 1, |d| { d.read_i32() })); +/// Ok(Point{ x: x, y: y }) +/// }) +/// } +/// } +/// # fn main() {} +/// ``` +pub trait Decodable: Sized { + /// Deserialize a value using a `Decoder`. + fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>; +} + +impl Encodable for usize { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_usize(*self) + } +} + +impl Decodable for usize { + fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> { + d.read_usize() + } +} + +impl Encodable for u8 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_u8(*self) + } +} + +impl Decodable for u8 { + fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> { + d.read_u8() + } +} + +impl Encodable for u16 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_u16(*self) + } +} + +impl Decodable for u16 { + fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> { + d.read_u16() + } +} + +impl Encodable for u32 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_u32(*self) + } +} + +impl Decodable for u32 { + fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> { + d.read_u32() + } +} + +impl Encodable for u64 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_u64(*self) + } +} + +impl Decodable for u64 { + fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> { + d.read_u64() + } +} + +impl Encodable for isize { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_isize(*self) + } +} + +impl Decodable for isize { + fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> { + d.read_isize() + } +} + +impl Encodable for i8 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_i8(*self) + } +} + +impl Decodable for i8 { + fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> { + d.read_i8() + } +} + +impl Encodable for i16 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_i16(*self) + } +} + +impl Decodable for i16 { + fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> { + d.read_i16() + } +} + +impl Encodable for i32 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_i32(*self) + } +} + +impl Decodable for i32 { + fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> { + d.read_i32() + } +} + +impl Encodable for i64 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_i64(*self) + } +} + +impl Decodable for i64 { + fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> { + d.read_i64() + } +} + +impl Encodable for str { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_str(self) + } +} + +impl Encodable for String { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_str(self) + } +} + +impl Decodable for String { + fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> { + d.read_str() + } +} + +impl Encodable for f32 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_f32(*self) + } +} + +impl Decodable for f32 { + fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> { + d.read_f32() + } +} + +impl Encodable for f64 { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_f64(*self) + } +} + +impl Decodable for f64 { + fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> { + d.read_f64() + } +} + +impl Encodable for bool { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_bool(*self) + } +} + +impl Decodable for bool { + fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> { + d.read_bool() + } +} + +impl Encodable for char { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_char(*self) + } +} + +impl Decodable for char { + fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> { + d.read_char() + } +} + +impl Encodable for () { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_nil() + } +} + +impl Decodable for () { + fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> { + d.read_nil() + } +} + +impl<'a, T: ?Sized + Encodable> Encodable for &'a T { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl<T: ?Sized + Encodable> Encodable for Box<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl< T: Decodable> Decodable for Box<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> { + Ok(Box::new(try!(Decodable::decode(d)))) + } +} + +impl< T: Decodable> Decodable for Box<[T]> { + fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> { + let v: Vec<T> = try!(Decodable::decode(d)); + Ok(v.into_boxed_slice()) + } +} + +impl<T:Encodable> Encodable for Rc<T> { + #[inline] + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl<T:Decodable> Decodable for Rc<T> { + #[inline] + fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> { + Ok(Rc::new(try!(Decodable::decode(d)))) + } +} + +impl<'a, T:Encodable + ToOwned + ?Sized> Encodable for Cow<'a, T> { + #[inline] + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl<'a, T: ?Sized> Decodable for Cow<'a, T> + where T: ToOwned, T::Owned: Decodable +{ + #[inline] + fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, T>, D::Error> { + Ok(Cow::Owned(try!(Decodable::decode(d)))) + } +} + +impl<T:Encodable> Encodable for [T] { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_seq(self.len(), |s| { + for (i, e) in self.iter().enumerate() { + try!(s.emit_seq_elt(i, |s| e.encode(s))) + } + Ok(()) + }) + } +} + +impl<T:Encodable> Encodable for Vec<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_seq(self.len(), |s| { + for (i, e) in self.iter().enumerate() { + try!(s.emit_seq_elt(i, |s| e.encode(s))) + } + Ok(()) + }) + } +} + +impl<T:Decodable> Decodable for Vec<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> { + d.read_seq(|d, len| { + let mut v = Vec::with_capacity(cap_capacity::<T>(len)); + for i in 0..len { + v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); + } + Ok(v) + }) + } +} + +impl<T:Encodable> Encodable for Option<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_option(|s| { + match *self { + None => s.emit_option_none(), + Some(ref v) => s.emit_option_some(|s| v.encode(s)), + } + }) + } +} + +impl<T:Decodable> Decodable for Option<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> { + d.read_option(|d, b| { + if b { + Ok(Some(try!(Decodable::decode(d)))) + } else { + Ok(None) + } + }) + } +} + +impl<T:Encodable, E:Encodable> Encodable for Result<T, E> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_enum("Result", |s| { + match *self { + Ok(ref v) => { + s.emit_enum_variant("Ok", 0, 1, |s| { + try!(s.emit_enum_variant_arg(0, |s| { + v.encode(s) + })); + Ok(()) + }) + } + Err(ref v) => { + s.emit_enum_variant("Err", 1, 1, |s| { + try!(s.emit_enum_variant_arg(0, |s| { + v.encode(s) + })); + Ok(()) + }) + } + } + }) + } +} + +impl<T: Decodable, E: Decodable> Decodable for Result<T, E> { + fn decode<D: Decoder>(d: &mut D) -> Result<Result<T, E>, D::Error> { + d.read_enum("Result", |d| { + d.read_enum_variant(&["Ok", "Err"], |d, idx| { + match idx { + 0 => { + d.read_enum_variant_arg(0, |d| { + T::decode(d) + }).map(|v| Ok(v)) + } + 1 => { + d.read_enum_variant_arg(0, |d| { + E::decode(d) + }).map(|v| Err(v)) + } + _ => panic!("Internal error"), + } + }) + }) + } +} + +impl<T> Encodable for PhantomData<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_nil() + } +} + +impl<T> Decodable for PhantomData<T> { + fn decode<D: Decoder>(_d: &mut D) -> Result<PhantomData<T>, D::Error> { + Ok(PhantomData) + } +} + +macro_rules! peel { + ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* }) +} + +/// Evaluates to the number of identifiers passed to it, for example: +/// `count_idents!(a, b, c) == 3 +macro_rules! count_idents { + () => { 0 }; + ($_i:ident, $($rest:ident,)*) => { 1 + count_idents!($($rest,)*) } +} + +macro_rules! tuple { + () => (); + ( $($name:ident,)+ ) => ( + impl<$($name:Decodable),*> Decodable for ($($name,)*) { + fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)*), D::Error> { + let len: usize = count_idents!($($name,)*); + d.read_tuple(len, |d| { + let mut i = 0; + let ret = ($(try!(d.read_tuple_arg({ i+=1; i-1 }, + |d| -> Result<$name,D::Error> { + Decodable::decode(d) + })),)*); + return Ok(ret); + }) + } + } + impl<$($name:Encodable),*> Encodable for ($($name,)*) { + #[allow(non_snake_case)] + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + let ($(ref $name,)*) = *self; + let mut n = 0; + $(let $name = $name; n += 1;)* + s.emit_tuple(n, |s| { + let mut i = 0; + $(try!(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s)));)* + Ok(()) + }) + } + } + peel! { $($name,)* } + ) +} + +tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } + +macro_rules! array { + () => (); + ($len:expr, $($idx:expr,)*) => { + impl<T:Decodable> Decodable for [T; $len] { + fn decode<D: Decoder>(d: &mut D) -> Result<[T; $len], D::Error> { + d.read_seq(|d, len| { + if len != $len { + return Err(d.error("wrong array length")); + } + Ok([$( + try!(d.read_seq_elt($len - $idx - 1, + |d| Decodable::decode(d))) + ),*]) + }) + } + } + + impl<T:Encodable> Encodable for [T; $len] { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_seq($len, |s| { + for i in 0..$len { + try!(s.emit_seq_elt(i, |s| self[i].encode(s))); + } + Ok(()) + }) + } + } + array! { $($idx,)* } + } +} + +array! { + 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +} + +impl Encodable for path::Path { + #[cfg(target_os = "redox")] + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { + self.as_os_str().to_str().unwrap().encode(e) + } + #[cfg(unix)] + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { + use std::os::unix::prelude::*; + self.as_os_str().as_bytes().encode(e) + } + #[cfg(windows)] + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { + use std::os::windows::prelude::*; + let v = self.as_os_str().encode_wide().collect::<Vec<_>>(); + v.encode(e) + } +} + +impl Encodable for path::PathBuf { + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { + (**self).encode(e) + } +} + +impl Decodable for path::PathBuf { + #[cfg(target_os = "redox")] + fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> { + let string: String = try!(Decodable::decode(d)); + let s: OsString = OsString::from(string); + let mut p = path::PathBuf::new(); + p.push(s); + Ok(p) + } + #[cfg(unix)] + fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> { + use std::os::unix::prelude::*; + let bytes: Vec<u8> = try!(Decodable::decode(d)); + let s: OsString = OsStringExt::from_vec(bytes); + let mut p = path::PathBuf::new(); + p.push(s); + Ok(p) + } + #[cfg(windows)] + fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> { + use std::os::windows::prelude::*; + let bytes: Vec<u16> = try!(Decodable::decode(d)); + let s: OsString = OsStringExt::from_wide(&bytes); + let mut p = path::PathBuf::new(); + p.push(s); + Ok(p) + } +} + +impl<T: Encodable + Copy> Encodable for Cell<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + self.get().encode(s) + } +} + +impl<T: Decodable + Copy> Decodable for Cell<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> { + Ok(Cell::new(try!(Decodable::decode(d)))) + } +} + +// FIXME: #15036 +// Should use `try_borrow`, returning a +// `encoder.error("attempting to Encode borrowed RefCell")` +// from `encode` when `try_borrow` returns `None`. + +impl<T: Encodable> Encodable for RefCell<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + self.borrow().encode(s) + } +} + +impl<T: Decodable> Decodable for RefCell<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> { + Ok(RefCell::new(try!(Decodable::decode(d)))) + } +} + +impl<T:Encodable> Encodable for Arc<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl<T:Decodable+Send+Sync> Decodable for Arc<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> { + Ok(Arc::new(try!(Decodable::decode(d)))) + } +} + +// ___________________________________________________________________________ +// Helper routines + +/// Trait with helper functions for implementing `Encodable`. +/// +/// This trait is implemented for everything that implements `Encoder`. +/// `Encodable` implementations can make use of it to make their implementations +/// easier. +pub trait EncoderHelpers: Encoder { + /// Emit a vector as a sequence. + /// + /// Storing sequences as vectors is a common pattern. This method makes + /// encoding such sequences easier by wrapping the calls to + /// `Encoder::emit_seq` and `Encoder::emit_seq_elt`. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Encodable; + /// use rustc_serialize::Encoder; + /// use rustc_serialize::EncoderHelpers; + /// + /// struct NumberSequence { + /// elements: Vec<i32>, + /// } + /// + /// impl Encodable for NumberSequence { + /// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + /// s.emit_struct("NumberSequence", 1, |s| { + /// s.emit_struct_field("elements", 0, |s| { + /// s.emit_from_vec(&self.elements, |s,e| { + /// s.emit_i32(*e) + /// }) + /// }) + /// }) + /// } + /// } + /// ``` + fn emit_from_vec<T, F>(&mut self, v: &[T], f: F) + -> Result<(), <Self as Encoder>::Error> + where F: FnMut(&mut Self, &T) -> Result<(), <Self as Encoder>::Error>; +} + +impl<S:Encoder> EncoderHelpers for S { + fn emit_from_vec<T, F>(&mut self, v: &[T], mut f: F) -> Result<(), S::Error> where + F: FnMut(&mut S, &T) -> Result<(), S::Error>, + { + self.emit_seq(v.len(), |this| { + for (i, e) in v.iter().enumerate() { + try!(this.emit_seq_elt(i, |this| { + f(this, e) + })); + } + Ok(()) + }) + } +} + +/// Trait with helper functions for implementing `Decodable`. +/// +/// This trait is implemented for everything that implements `Decoder`. +/// `Decodable` implementations can make use of it to make their implementations +/// easier. +pub trait DecoderHelpers: Decoder { + /// Read a sequence into a vector. + /// + /// Storing sequences as vectors is a common pattern. This method makes + /// deserializing such sequences easier by wrapping the calls to + /// `Decoder::read_seq` and `Decoder::read_seq_elt`. + /// + /// # Examples + /// + /// ``` + /// use rustc_serialize::Decodable; + /// use rustc_serialize::Decoder; + /// use rustc_serialize::DecoderHelpers; + /// + /// struct NumberSequence { + /// elements: Vec<i32>, + /// } + /// + /// impl Decodable for NumberSequence { + /// fn decode<D: Decoder>(d: &mut D) -> Result<NumberSequence, D::Error> { + /// d.read_struct("NumberSequence", 2, |d| { + /// Ok(NumberSequence{ + /// elements: try!(d.read_struct_field("elements", 0, |d| { + /// d.read_to_vec(|d| { d.read_i32() }) + /// })) + /// }) + /// }) + /// } + /// } + /// ``` + fn read_to_vec<T, F>(&mut self, f: F) + -> Result<Vec<T>, <Self as Decoder>::Error> where + F: FnMut(&mut Self) -> Result<T, <Self as Decoder>::Error>; +} + +impl<D: Decoder> DecoderHelpers for D { + fn read_to_vec<T, F>(&mut self, mut f: F) -> Result<Vec<T>, D::Error> where F: + FnMut(&mut D) -> Result<T, D::Error>, + { + self.read_seq(|this, len| { + let mut v = Vec::with_capacity(cap_capacity::<T>(len)); + for i in 0..len { + v.push(try!(this.read_seq_elt(i, |this| f(this)))); + } + Ok(v) + }) + } +} + +#[test] +#[allow(unused_variables)] +fn capacity_rules() { + use std::usize::MAX; + use std::collections::{HashMap, HashSet}; + + struct MyDecoder; + impl Decoder for MyDecoder { + type Error = (); + + // Primitive types: + fn read_nil(&mut self) -> Result<(), Self::Error> { Err(()) } + fn read_usize(&mut self) -> Result<usize, Self::Error> { Err(()) } + fn read_u64(&mut self) -> Result<u64, Self::Error> { Err(()) } + fn read_u32(&mut self) -> Result<u32, Self::Error> { Err(()) } + fn read_u16(&mut self) -> Result<u16, Self::Error> { Err(()) } + fn read_u8(&mut self) -> Result<u8, Self::Error> { Err(()) } + fn read_isize(&mut self) -> Result<isize, Self::Error> { Err(()) } + fn read_i64(&mut self) -> Result<i64, Self::Error> { Err(()) } + fn read_i32(&mut self) -> Result<i32, Self::Error> { Err(()) } + fn read_i16(&mut self) -> Result<i16, Self::Error> { Err(()) } + fn read_i8(&mut self) -> Result<i8, Self::Error> { Err(()) } + fn read_bool(&mut self) -> Result<bool, Self::Error> { Err(()) } + fn read_f64(&mut self) -> Result<f64, Self::Error> { Err(()) } + fn read_f32(&mut self) -> Result<f32, Self::Error> { Err(()) } + fn read_char(&mut self) -> Result<char, Self::Error> { Err(()) } + fn read_str(&mut self) -> Result<String, Self::Error> { Err(()) } + + // Compound types: + fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F) + -> Result<T, Self::Error> + where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> { Err(()) } + fn read_enum_variant_arg<T, F>(&mut self, a_idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) + -> Result<T, Self::Error> + where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> { Err(()) } + fn read_enum_struct_variant_field<T, F>(&mut self, + f_name: &str, + f_idx: usize, + f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + fn read_struct_field<T, F>(&mut self, + f_name: &str, + f_idx: usize, + f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + fn read_tuple<T, F>(&mut self, len: usize, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + fn read_tuple_arg<T, F>(&mut self, a_idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + fn read_tuple_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + // Specialized types: + fn read_option<T, F>(&mut self, f: F) -> Result<T, Self::Error> + where F: FnMut(&mut Self, bool) -> Result<T, Self::Error> { Err(()) } + + fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> { + f(self, MAX) + } + fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error> + where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> { + f(self, MAX) + } + fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F) + -> Result<T, Self::Error> + where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) } + + // Failure + fn error(&mut self, err: &str) -> Self::Error { () } + } + + let mut dummy = MyDecoder; + let vec_result: Result<Vec<u8>, ()> = Decodable::decode(&mut dummy); + assert!(vec_result.is_err()); + + let map_result: Result<HashMap<u8, u8>, ()> = Decodable::decode(&mut dummy); + assert!(map_result.is_err()); + + let set_result: Result<HashSet<u8>, ()> = Decodable::decode(&mut dummy); + assert!(set_result.is_err()); +} diff --git a/bash-5.1/vendor/serde/.cargo-checksum.json b/bash-5.1/vendor/serde/.cargo-checksum.json new file mode 100644 index 0000000..0876ba8 --- /dev/null +++ b/bash-5.1/vendor/serde/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"c71542adb7717ea07c4f8c150eb5d8c8561ed9a819c558590b3d0cb964080e3f","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"213afbe4b2ef4033e8c40d11925ae1effff5a11fb5cdae7ca978e26564ca4880","src/bytes.rs":"2b6a9c2c3d6eabe8633adee6655a3b94f0d1e931e740e72699b6965bee21e226","src/de/content.rs":"11ce91ca6a5644e3338d683b8268485195341751b51731b9b48e2c452e10db66","src/de/from_primitive.rs":"b1bd165e343a4380965551709119ef9ed895e4b025045a810dabd671511ba3ab","src/de/impls.rs":"5c8031cf33ad510f5bb1a75069bb1e1d558f74deb762f5da92bbf005a047a9a3","src/de/mod.rs":"34841a85df55bafb7ba64a972d0a0c966d7a9dce8b21f740f739ec9d8aaea784","src/de/private.rs":"2578dbc89c2f2a852caed3fdc40f710d4828d085c4e954dd96789d678583424e","src/de/value.rs":"1bf57858a42a987a697b876a96a4765069422a6bb60f2d8dc69c360686b7c280","src/error.rs":"3af5286c1daad9bfd504693f8a8587f7044c9b9520e23e072549c43a72e4821d","src/export.rs":"85e7a5cb5e3c5a36717bb53187b14ee55ae1ec114e2da538c11d68bbbccc8253","src/iter.rs":"af3c43712c240b3a06870e0b0b6e837b142d5a65c62742fa358fe36a9d9319a7","src/lib.rs":"ca38922d87bdab2a09d13e0e7804d85256118f9b7e8cfc54f4064b499a44fb04","src/macros.rs":"6da960dd67285e47721724871ce5594ba90feeba304f083a0378677db6e6cbcb","src/ser/content.rs":"585febe877e59b43bcc66a60c88e5661560917e824bc4cf251c71168b6673c98","src/ser/impls.rs":"98a5f7cadec2798bceee5dbfe9af25b30861ac5c308c7d3d4a61358b345789d8","src/ser/impossible.rs":"f1332a1250f9c1d85d679653ade502cf99bdff0344b9f864e6cf1a1789d7c597","src/ser/mod.rs":"96a65af2ce0aedf4592f096896e1ee23fcc2a16aa1bb839cd781c667a75b7f48","src/ser/private.rs":"d2a98eeda64e7d203e435b885dd56d03fb69888ccf6c70cc938a9b81e0794ebf","src/utils.rs":"cceeac48898b5dceff934befc5b9685997221cbba5b3e17d80b640bd2229fe86"},"package":"34b623917345a631dc9608d5194cc206b3fe6c3554cd1c75b937e55e285254af"} \ No newline at end of file diff --git a/bash-5.1/vendor/serde/Cargo.toml b/bash-5.1/vendor/serde/Cargo.toml new file mode 100644 index 0000000..7d0330f --- /dev/null +++ b/bash-5.1/vendor/serde/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "serde" +version = "0.9.15" +authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"] +license = "MIT/Apache-2.0" +description = "A generic serialization/deserialization framework" +homepage = "https://serde.rs" +repository = "https://github.com/serde-rs/serde" +documentation = "https://docs.serde.rs/serde/" +keywords = ["serde", "serialization", "no_std"] +categories = ["encoding"] +readme = "../README.md" +include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] + +[badges] +travis-ci = { repository = "serde-rs/serde" } + +[features] +default = ["std"] +derive = ["serde_derive"] + +std = [] +unstable = [] +alloc = ["unstable"] +collections = ["alloc"] +unstable-testing = ["unstable", "std"] + +# to get serde_derive picked up by play.integer32.com +playground = ["serde_derive"] + +[dependencies] +serde_derive = { version = "0.9", optional = true, path = "../serde_derive" } + +[dev-dependencies] +serde_derive = { version = "0.9", path = "../serde_derive" } diff --git a/bash-5.1/vendor/serde/LICENSE-APACHE b/bash-5.1/vendor/serde/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/serde/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/serde/LICENSE-MIT b/bash-5.1/vendor/serde/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/serde/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/serde/README.md b/bash-5.1/vendor/serde/README.md new file mode 100644 index 0000000..358f9b2 --- /dev/null +++ b/bash-5.1/vendor/serde/README.md @@ -0,0 +1,76 @@ +# Serde   [![Build Status](https://api.travis-ci.org/serde-rs/serde.svg?branch=master)](https://travis-ci.org/serde-rs/serde) [![Latest Version](https://img.shields.io/crates/v/serde.svg)](https://crates.io/crates/serde) + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.serde.rs/serde/) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank"> +<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> +</a> + +```rust +#[macro_use] +extern crate serde_derive; + +extern crate serde; +extern crate serde_json; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde developers live in the #serde channel on +[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a +good resource with generally faster response time but less specific knowledge +about Serde. If IRC is not your thing or you don't get a good response, we are +happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) +as well. + +## License + +Serde is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bash-5.1/vendor/serde/src/bytes.rs b/bash-5.1/vendor/serde/src/bytes.rs new file mode 100644 index 0000000..d1ea018 --- /dev/null +++ b/bash-5.1/vendor/serde/src/bytes.rs @@ -0,0 +1,315 @@ +//! Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`. +//! +//! Without specialization, Rust forces us to treat `&[u8]` just like any other +//! slice and `Vec<u8>` just like any other vector. In reality this particular +//! slice and vector can often be serialized and deserialized in a more +//! efficient, compact representation in many formats. +//! +//! When working with such a format, you can opt into specialized handling of +//! `&[u8]` by wrapping it in `bytes::Bytes` and `Vec<u8>` by wrapping it in +//! `bytes::ByteBuf`. +//! +//! Rust support for specialization is being tracked in +//! [rust-lang/rust#31844][specialization]. Once it lands in the stable compiler +//! we will be deprecating these wrapper types in favor of optimizing `&[u8]` +//! and `Vec<u8>` out of the box. +//! +//! [specialization]: https://github.com/rust-lang/rust/issues/31844 + +use core::{ops, fmt, char, iter, slice}; +use core::fmt::Write; + +use ser; + +#[cfg(any(feature = "std", feature = "collections"))] +pub use self::bytebuf::ByteBuf; + +#[cfg(any(feature = "std", feature = "collections"))] +#[doc(hidden)] // does anybody need this? +pub use self::bytebuf::ByteBufVisitor; + +#[cfg(feature = "collections")] +use collections::Vec; + +/////////////////////////////////////////////////////////////////////////////// + +/// Wraps a `&[u8]` in order to serialize in an efficient way. Does not support +/// deserialization. +/// +/// ```rust +/// # #[macro_use] extern crate serde_derive; +/// # extern crate serde; +/// # use std::net::IpAddr; +/// # +/// use serde::bytes::Bytes; +/// +/// # #[allow(dead_code)] +/// #[derive(Serialize)] +/// struct Packet<'a> { +/// destination: IpAddr, +/// payload: Bytes<'a>, +/// } +/// # +/// # fn main() {} +/// ``` +#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)] +pub struct Bytes<'a> { + bytes: &'a [u8], +} + +impl<'a> Bytes<'a> { + /// Wrap an existing `&[u8]`. + pub fn new(bytes: &'a [u8]) -> Self { + Bytes { bytes: bytes } + } +} + +impl<'a> fmt::Debug for Bytes<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(f.write_str("b\"")); + for c in escape_bytestring(self.bytes) { + try!(f.write_char(c)); + } + f.write_char('"') + } +} + +impl<'a> From<&'a [u8]> for Bytes<'a> { + fn from(bytes: &'a [u8]) -> Self { + Bytes::new(bytes) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a> From<&'a Vec<u8>> for Bytes<'a> { + fn from(bytes: &'a Vec<u8>) -> Self { + Bytes::new(bytes) + } +} + +impl<'a> Into<&'a [u8]> for Bytes<'a> { + fn into(self) -> &'a [u8] { + self.bytes + } +} + +impl<'a> ops::Deref for Bytes<'a> { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + self.bytes + } +} + +impl<'a> ser::Serialize for Bytes<'a> { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: ser::Serializer + { + serializer.serialize_bytes(self.bytes) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "collections"))] +mod bytebuf { + use core::cmp; + use core::ops; + use core::fmt; + use core::fmt::Write; + + use ser; + use de; + + #[cfg(feature = "collections")] + use collections::{String, Vec}; + + /// Wraps a `Vec<u8>` in order to serialize and deserialize in an efficient + /// way. + /// + /// ```rust + /// # #[macro_use] extern crate serde_derive; + /// # extern crate serde; + /// # use std::net::IpAddr; + /// # + /// use serde::bytes::ByteBuf; + /// + /// # #[allow(dead_code)] + /// #[derive(Serialize, Deserialize)] + /// struct Packet { + /// destination: IpAddr, + /// payload: ByteBuf, + /// } + /// # + /// # fn main() {} + /// ``` + #[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] + pub struct ByteBuf { + bytes: Vec<u8>, + } + + impl ByteBuf { + /// Construct a new, empty `ByteBuf`. + pub fn new() -> Self { + ByteBuf::from(Vec::new()) + } + + /// Construct a new, empty `ByteBuf` with the specified capacity. + pub fn with_capacity(cap: usize) -> Self { + ByteBuf::from(Vec::with_capacity(cap)) + } + + /// Wrap existing bytes in a `ByteBuf`. + pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self { + ByteBuf { bytes: bytes.into() } + } + } + + impl fmt::Debug for ByteBuf { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(f.write_str("b\"")); + for c in super::escape_bytestring(self.bytes.as_ref()) { + try!(f.write_char(c)); + } + f.write_char('"') + } + } + + impl Into<Vec<u8>> for ByteBuf { + fn into(self) -> Vec<u8> { + self.bytes + } + } + + impl From<Vec<u8>> for ByteBuf { + fn from(bytes: Vec<u8>) -> Self { + ByteBuf::from(bytes) + } + } + + impl AsRef<Vec<u8>> for ByteBuf { + fn as_ref(&self) -> &Vec<u8> { + &self.bytes + } + } + + impl AsRef<[u8]> for ByteBuf { + fn as_ref(&self) -> &[u8] { + &self.bytes + } + } + + impl AsMut<Vec<u8>> for ByteBuf { + fn as_mut(&mut self) -> &mut Vec<u8> { + &mut self.bytes + } + } + + impl AsMut<[u8]> for ByteBuf { + fn as_mut(&mut self) -> &mut [u8] { + &mut self.bytes + } + } + + impl ops::Deref for ByteBuf { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + &self.bytes[..] + } + } + + impl ops::DerefMut for ByteBuf { + fn deref_mut(&mut self) -> &mut [u8] { + &mut self.bytes[..] + } + } + + impl ser::Serialize for ByteBuf { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: ser::Serializer + { + serializer.serialize_bytes(self) + } + } + + /// This type implements the `serde::de::Visitor` trait for a `ByteBuf`. + pub struct ByteBufVisitor; + + impl de::Visitor for ByteBufVisitor { + type Value = ByteBuf; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("byte array") + } + + #[inline] + fn visit_unit<E>(self) -> Result<ByteBuf, E> + where E: de::Error + { + Ok(ByteBuf::new()) + } + + #[inline] + fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error> + where V: de::SeqVisitor + { + let len = cmp::min(visitor.size_hint().0, 4096); + let mut values = Vec::with_capacity(len); + + while let Some(value) = try!(visitor.visit()) { + values.push(value); + } + + Ok(ByteBuf::from(values)) + } + + #[inline] + fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E> + where E: de::Error + { + Ok(ByteBuf::from(v)) + } + + #[inline] + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E> + where E: de::Error + { + Ok(ByteBuf::from(v)) + } + + fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E> + where E: de::Error + { + Ok(ByteBuf::from(v)) + } + + fn visit_string<E>(self, v: String) -> Result<ByteBuf, E> + where E: de::Error + { + Ok(ByteBuf::from(v)) + } + } + + impl de::Deserialize for ByteBuf { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error> + where D: de::Deserializer + { + deserializer.deserialize_byte_buf(ByteBufVisitor) + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[inline] +fn escape_bytestring<'a> + (bytes: &'a [u8]) + -> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> { + fn f(b: &u8) -> char::EscapeDefault { + char::from_u32(*b as u32).unwrap().escape_default() + } + bytes.iter().flat_map(f as fn(&u8) -> char::EscapeDefault) +} diff --git a/bash-5.1/vendor/serde/src/de/content.rs b/bash-5.1/vendor/serde/src/de/content.rs new file mode 100644 index 0000000..e784b4e --- /dev/null +++ b/bash-5.1/vendor/serde/src/de/content.rs @@ -0,0 +1,1338 @@ +// This module is doc(hidden) and nothing here should be used outside of +// generated code. +// +// We will iterate on the implementation for a few releases and only have to +// worry about backward compatibility for the `untagged` and `tag` attributes +// rather than for this entire mechanism. +// +// This issue is tracking making some of this stuff public: +// https://github.com/serde-rs/serde/issues/741 + +#![doc(hidden)] + +use core::cmp; +use core::fmt; +use core::marker::PhantomData; + +#[cfg(all(not(feature = "std"), feature = "collections"))] +use collections::{String, Vec}; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::boxed::Box; + +use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor, + EnumVisitor, Unexpected}; + +/// Used from generated code to buffer the contents of the Deserializer when +/// deserializing untagged enums and internally tagged enums. +/// +/// Not public API. Use serde-value instead. +#[derive(Debug)] +pub enum Content { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Bytes(Vec<u8>), + + None, + Some(Box<Content>), + + Unit, + Newtype(Box<Content>), + Seq(Vec<Content>), + Map(Vec<(Content, Content)>), +} + +impl Content { + fn unexpected(&self) -> Unexpected { + match *self { + Content::Bool(b) => Unexpected::Bool(b), + Content::U8(n) => Unexpected::Unsigned(n as u64), + Content::U16(n) => Unexpected::Unsigned(n as u64), + Content::U32(n) => Unexpected::Unsigned(n as u64), + Content::U64(n) => Unexpected::Unsigned(n), + Content::I8(n) => Unexpected::Signed(n as i64), + Content::I16(n) => Unexpected::Signed(n as i64), + Content::I32(n) => Unexpected::Signed(n as i64), + Content::I64(n) => Unexpected::Signed(n), + Content::F32(f) => Unexpected::Float(f as f64), + Content::F64(f) => Unexpected::Float(f), + Content::Char(c) => Unexpected::Char(c), + Content::String(ref s) => Unexpected::Str(s), + Content::Bytes(ref b) => Unexpected::Bytes(b), + Content::None | Content::Some(_) => Unexpected::Option, + Content::Unit => Unexpected::Unit, + Content::Newtype(_) => Unexpected::NewtypeStruct, + Content::Seq(_) => Unexpected::Seq, + Content::Map(_) => Unexpected::Map, + } + } +} + +impl Deserialize for Content { + fn deserialize<D: Deserializer>(deserializer: D) -> Result<Self, D::Error> { + // Untagged and internally tagged enums are only supported in + // self-describing formats. + deserializer.deserialize(ContentVisitor) + } +} + +struct ContentVisitor; + +impl Visitor for ContentVisitor { + type Value = Content; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("any value") + } + + fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::Bool(value)) + } + + fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::I8(value)) + } + + fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::I16(value)) + } + + fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::I32(value)) + } + + fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::I64(value)) + } + + fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::U8(value)) + } + + fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::U16(value)) + } + + fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::U32(value)) + } + + fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::U64(value)) + } + + fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::F32(value)) + } + + fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::F64(value)) + } + + fn visit_char<F>(self, value: char) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::Char(value)) + } + + fn visit_str<F>(self, value: &str) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::String(value.into())) + } + + fn visit_string<F>(self, value: String) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::String(value)) + } + + fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::Bytes(value.into())) + } + + fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::Bytes(value)) + } + + fn visit_unit<F>(self) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::Unit) + } + + fn visit_none<F>(self) -> Result<Self::Value, F> + where F: de::Error + { + Ok(Content::None) + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) + } + + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) + } + + fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where V: SeqVisitor + { + let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); + while let Some(e) = try!(visitor.visit()) { + vec.push(e); + } + Ok(Content::Seq(vec)) + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where V: MapVisitor + { + let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); + while let Some(kv) = try!(visitor.visit()) { + vec.push(kv); + } + Ok(Content::Map(vec)) + } + + fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error> + where V: EnumVisitor + { + Err(de::Error::custom("untagged and internally tagged enums do not support enum input")) + } +} + +/// This is the type of the map keys in an internally tagged enum. +/// +/// Not public API. +pub enum TagOrContent { + Tag, + Content(Content), +} + +struct TagOrContentVisitor { + name: &'static str, +} + +impl TagOrContentVisitor { + fn new(name: &'static str) -> Self { + TagOrContentVisitor { name: name } + } +} + +impl DeserializeSeed for TagOrContentVisitor { + type Value = TagOrContent; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize(self) + } +} + +impl Visitor for TagOrContentVisitor { + type Value = TagOrContent; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "a type tag `{}` or any other value", self.name) + } + + fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_bool(value).map(TagOrContent::Content) + } + + fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_i8(value).map(TagOrContent::Content) + } + + fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_i16(value).map(TagOrContent::Content) + } + + fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_i32(value).map(TagOrContent::Content) + } + + fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_i64(value).map(TagOrContent::Content) + } + + fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_u8(value).map(TagOrContent::Content) + } + + fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_u16(value).map(TagOrContent::Content) + } + + fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_u32(value).map(TagOrContent::Content) + } + + fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_u64(value).map(TagOrContent::Content) + } + + fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_f32(value).map(TagOrContent::Content) + } + + fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_f64(value).map(TagOrContent::Content) + } + + fn visit_char<F>(self, value: char) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_char(value).map(TagOrContent::Content) + } + + fn visit_str<F>(self, value: &str) -> Result<Self::Value, F> + where F: de::Error + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_str(value).map(TagOrContent::Content) + } + } + + fn visit_string<F>(self, value: String) -> Result<Self::Value, F> + where F: de::Error + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_string(value).map(TagOrContent::Content) + } + } + + fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F> + where F: de::Error + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_bytes(value).map(TagOrContent::Content) + } + } + + fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F> + where F: de::Error + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_byte_buf(value).map(TagOrContent::Content) + } + } + + fn visit_unit<F>(self) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_unit().map(TagOrContent::Content) + } + + fn visit_none<F>(self) -> Result<Self::Value, F> + where F: de::Error + { + ContentVisitor.visit_none().map(TagOrContent::Content) + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + ContentVisitor.visit_some(deserializer).map(TagOrContent::Content) + } + + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + ContentVisitor.visit_newtype_struct(deserializer).map(TagOrContent::Content) + } + + fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where V: SeqVisitor + { + ContentVisitor.visit_seq(visitor).map(TagOrContent::Content) + } + + fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where V: MapVisitor + { + ContentVisitor.visit_map(visitor).map(TagOrContent::Content) + } + + fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where V: EnumVisitor + { + ContentVisitor.visit_enum(visitor).map(TagOrContent::Content) + } +} + +/// Used by generated code to deserialize an internally tagged enum. +/// +/// Not public API. +pub struct TaggedContent<T> { + pub tag: T, + pub content: Content, +} + +/// Not public API. +pub struct TaggedContentVisitor<T> { + tag_name: &'static str, + tag: PhantomData<T>, +} + +impl<T> TaggedContentVisitor<T> { + /// Visitor for the content of an internally tagged enum with the given tag + /// name. + pub fn new(name: &'static str) -> Self { + TaggedContentVisitor { + tag_name: name, + tag: PhantomData, + } + } +} + +impl<T> DeserializeSeed for TaggedContentVisitor<T> + where T: Deserialize +{ + type Value = TaggedContent<T>; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize(self) + } +} + +impl<T> Visitor for TaggedContentVisitor<T> + where T: Deserialize +{ + type Value = TaggedContent<T>; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("any value") + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where V: MapVisitor + { + let mut tag = None; + let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); + while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) { + match k { + TagOrContent::Tag => { + if tag.is_some() { + return Err(de::Error::duplicate_field(self.tag_name)); + } + tag = Some(try!(visitor.visit_value())); + } + TagOrContent::Content(k) => { + let v = try!(visitor.visit_value()); + vec.push((k, v)); + } + } + } + match tag { + None => Err(de::Error::missing_field(self.tag_name)), + Some(tag) => { + Ok(TaggedContent { + tag: tag, + content: Content::Map(vec), + }) + } + } + } +} + +/// Used by generated code to deserialize an adjacently tagged enum. +/// +/// Not public API. +pub enum TagOrContentField { + Tag, + Content, +} + +/// Not public API. +pub struct TagOrContentFieldVisitor { + pub tag: &'static str, + pub content: &'static str, +} + +impl DeserializeSeed for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + deserializer.deserialize_str(self) + } +} + +impl Visitor for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{:?} or {:?}", self.tag, self.content) + } + + fn visit_str<E>(self, field: &str) -> Result<Self::Value, E> + where E: de::Error + { + if field == self.tag { + Ok(TagOrContentField::Tag) + } else if field == self.content { + Ok(TagOrContentField::Content) + } else { + Err(de::Error::invalid_value(Unexpected::Str(field), &self)) + } + } +} + +/// Not public API +pub struct ContentDeserializer<E> { + content: Content, + err: PhantomData<E>, +} + +/// Used when deserializing an internally tagged enum because the content will +/// be used exactly once. +impl<E> Deserializer for ContentDeserializer<E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor + { + match self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(v) => visitor.visit_string(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), + Content::Seq(v) => { + let seq = v.into_iter().map(ContentDeserializer::new); + let mut seq_visitor = de::value::SeqDeserializer::new(seq); + let value = try!(visitor.visit_seq(&mut seq_visitor)); + try!(seq_visitor.end()); + Ok(value) + } + Content::Map(v) => { + let map = v.into_iter().map(|(k, v)| { + (ContentDeserializer::new(k), + ContentDeserializer::new(v)) + }); + let mut map_visitor = de::value::MapDeserializer::new(map); + let value = try!(visitor.visit_map(&mut map_visitor)); + try!(map_visitor.end()); + Ok(value) + } + Content::Bytes(v) => visitor.visit_byte_buf(v), + } + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor + { + match self.content { + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum<V>(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor + { + let (variant, value) = match self.content { + Content::Map(value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + (variant, Some(value)) + } + Content::String(variant) => (Content::String(variant), None), + other => { + return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); + } + }; + + visitor.visit_enum(EnumDeserializer { + variant: variant, + value: value, + err: PhantomData, + }) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct + struct_field tuple ignored_any + } +} + +impl<E> ContentDeserializer<E> { + /// private API, don't use + pub fn new(content: Content) -> Self { + ContentDeserializer { + content: content, + err: PhantomData, + } + } +} + +struct EnumDeserializer<E> + where E: de::Error +{ + variant: Content, + value: Option<Content>, + err: PhantomData<E>, +} + +impl<E> de::EnumVisitor for EnumDeserializer<E> + where E: de::Error +{ + type Error = E; + type Variant = VariantDeserializer<Self::Error>; + + fn visit_variant_seed<V>(self, + seed: V) + -> Result<(V::Value, VariantDeserializer<E>), Self::Error> + where V: de::DeserializeSeed + { + let visitor = VariantDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentDeserializer::new(self.variant)).map(|v| (v, visitor)) + } +} + +struct VariantDeserializer<E> + where E: de::Error +{ + value: Option<Content>, + err: PhantomData<E>, +} + +impl<E> de::VariantVisitor for VariantDeserializer<E> + where E: de::Error +{ + type Error = E; + + fn visit_unit(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)), + None => Ok(()), + } + } + + fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, E> + where T: de::DeserializeSeed + { + match self.value { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant")), + } + } + + fn visit_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + match self.value { + Some(Content::Seq(v)) => { + de::Deserializer::deserialize(SeqDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant")), + } + } + + fn visit_struct<V>(self, + _fields: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + match self.value { + Some(Content::Map(v)) => { + de::Deserializer::deserialize(MapDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), + _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant")), + } + } +} + +struct SeqDeserializer<E> + where E: de::Error +{ + iter: <Vec<Content> as IntoIterator>::IntoIter, + err: PhantomData<E>, +} + +impl<E> SeqDeserializer<E> + where E: de::Error +{ + fn new(vec: Vec<Content>) -> Self { + SeqDeserializer { + iter: vec.into_iter(), + err: PhantomData, + } + } +} + +impl<E> de::Deserializer for SeqDeserializer<E> + where E: de::Error +{ + type Error = E; + + #[inline] + fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl<E> de::SeqVisitor for SeqDeserializer<E> + where E: de::Error +{ + type Error = E; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + match self.iter.next() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +struct MapDeserializer<E> + where E: de::Error +{ + iter: <Vec<(Content, Content)> as IntoIterator>::IntoIter, + value: Option<Content>, + err: PhantomData<E>, +} + +impl<E> MapDeserializer<E> + where E: de::Error +{ + fn new(map: Vec<(Content, Content)>) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + err: PhantomData, + } + } +} + +impl<E> de::MapVisitor for MapDeserializer<E> + where E: de::Error +{ + type Error = E; + + fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(ContentDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where T: de::DeserializeSeed + { + match self.value.take() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +impl<E> de::Deserializer for MapDeserializer<E> + where E: de::Error +{ + type Error = E; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_map(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + + +/// Not public API. +pub struct ContentRefDeserializer<'a, E> { + content: &'a Content, + err: PhantomData<E>, +} + +/// Used when deserializing an untagged enum because the content may need to be +/// used more than once. +impl<'a, E> Deserializer for ContentRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, E> + where V: Visitor + { + match *self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(ref v) => visitor.visit_str(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)), + Content::Seq(ref v) => { + let seq = v.into_iter().map(ContentRefDeserializer::new); + let mut seq_visitor = de::value::SeqDeserializer::new(seq); + let value = try!(visitor.visit_seq(&mut seq_visitor)); + try!(seq_visitor.end()); + Ok(value) + } + Content::Map(ref v) => { + let map = v.into_iter().map(|&(ref k, ref v)| { + (ContentRefDeserializer::new(k), + ContentRefDeserializer::new(v)) + }); + let mut map_visitor = de::value::MapDeserializer::new(map); + let value = try!(visitor.visit_map(&mut map_visitor)); + try!(map_visitor.end()); + Ok(value) + } + Content::Bytes(ref v) => visitor.visit_bytes(v), + } + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E> + where V: Visitor + { + match *self.content { + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E> + where V: Visitor + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum<V>(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor + { + let (variant, value) = match *self.content { + Content::Map(ref value) => { + let mut iter = value.into_iter(); + let &(ref variant, ref value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + (variant, Some(value)) + } + ref s @ Content::String(_) => (s, None), + ref other => { + return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); + } + }; + + visitor.visit_enum(EnumRefDeserializer { + variant: variant, + value: value, + err: PhantomData, + }) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct + struct_field tuple ignored_any + } +} + +impl<'a, E> ContentRefDeserializer<'a, E> { + /// private API, don't use + pub fn new(content: &'a Content) -> Self { + ContentRefDeserializer { + content: content, + err: PhantomData, + } + } +} + +struct EnumRefDeserializer<'a, E> + where E: de::Error +{ + variant: &'a Content, + value: Option<&'a Content>, + err: PhantomData<E>, +} + +impl<'a, E> de::EnumVisitor for EnumRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + type Variant = VariantRefDeserializer<'a, Self::Error>; + + fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where V: de::DeserializeSeed + { + let visitor = VariantRefDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentRefDeserializer::new(self.variant)).map(|v| (v, visitor)) + } +} + +struct VariantRefDeserializer<'a, E> + where E: de::Error +{ + value: Option<&'a Content>, + err: PhantomData<E>, +} + +impl<'a, E> de::VariantVisitor for VariantRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn visit_unit(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), + None => Ok(()), + } + } + + fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, E> + where T: de::DeserializeSeed + { + match self.value { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant")), + } + } + + fn visit_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + match self.value { + Some(&Content::Seq(ref v)) => { + de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant")), + } + } + + fn visit_struct<V>(self, + _fields: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + match self.value { + Some(&Content::Map(ref v)) => { + de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), + _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant")), + } + } +} + +struct SeqRefDeserializer<'a, E> + where E: de::Error +{ + iter: <&'a [Content] as IntoIterator>::IntoIter, + err: PhantomData<E>, +} + +impl<'a, E> SeqRefDeserializer<'a, E> + where E: de::Error +{ + fn new(vec: &'a [Content]) -> Self { + SeqRefDeserializer { + iter: vec.into_iter(), + err: PhantomData, + } + } +} + +impl<'a, E> de::Deserializer for SeqRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + #[inline] + fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl<'a, E> de::SeqVisitor for SeqRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + match self.iter.next() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +struct MapRefDeserializer<'a, E> + where E: de::Error +{ + iter: <&'a [(Content, Content)] as IntoIterator>::IntoIter, + value: Option<&'a Content>, + err: PhantomData<E>, +} + +impl<'a, E> MapRefDeserializer<'a, E> + where E: de::Error +{ + fn new(map: &'a [(Content, Content)]) -> Self { + MapRefDeserializer { + iter: map.into_iter(), + value: None, + err: PhantomData, + } + } +} + +impl<'a, E> de::MapVisitor for MapRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + match self.iter.next() { + Some(&(ref key, ref value)) => { + self.value = Some(value); + seed.deserialize(ContentRefDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where T: de::DeserializeSeed + { + match self.value.take() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +impl<'a, E> de::Deserializer for MapRefDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_map(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl<E> de::value::ValueDeserializer<E> for ContentDeserializer<E> + where E: de::Error +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'a, E> de::value::ValueDeserializer<E> for ContentRefDeserializer<'a, E> + where E: de::Error +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +/// Visitor for deserializing an internally tagged unit variant. +/// +/// Not public API. +pub struct InternallyTaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, +} + +impl<'a> InternallyTaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + InternallyTaggedUnitVisitor { + type_name: type_name, + variant_name: variant_name, + } + } +} + +impl<'a> Visitor for InternallyTaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name) + } + + fn visit_map<V>(self, _: V) -> Result<(), V::Error> + where V: MapVisitor + { + Ok(()) + } +} + +/// Visitor for deserializing an untagged unit variant. +/// +/// Not public API. +pub struct UntaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, +} + +impl<'a> UntaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + UntaggedUnitVisitor { + type_name: type_name, + variant_name: variant_name, + } + } +} + +impl<'a> Visitor for UntaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name) + } + + fn visit_unit<E>(self) -> Result<(), E> + where E: de::Error + { + Ok(()) + } +} diff --git a/bash-5.1/vendor/serde/src/de/from_primitive.rs b/bash-5.1/vendor/serde/src/de/from_primitive.rs new file mode 100644 index 0000000..14e5186 --- /dev/null +++ b/bash-5.1/vendor/serde/src/de/from_primitive.rs @@ -0,0 +1,409 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Extracted from https://github.com/rust-num/num. + +// Rust 1.5 is unhappy that this private module is undocumented. +#![allow(missing_docs)] + +use core::{usize, u8, u16, u32, u64}; +use core::{isize, i8, i16, i32, i64}; +use core::{f32, f64}; +use core::mem::size_of; + +/// Numbers which have upper and lower bounds +pub trait Bounded { + // FIXME (#5527): These should be associated constants + /// returns the smallest finite number this type can represent + fn min_value() -> Self; + /// returns the largest finite number this type can represent + fn max_value() -> Self; +} + +macro_rules! bounded_impl { + ($t:ty, $min:expr, $max:expr) => { + impl Bounded for $t { + #[inline] + fn min_value() -> $t { $min } + + #[inline] + fn max_value() -> $t { $max } + } + } +} + +bounded_impl!(usize, usize::MIN, usize::MAX); +bounded_impl!(u8, u8::MIN, u8::MAX); +bounded_impl!(u16, u16::MIN, u16::MAX); +bounded_impl!(u32, u32::MIN, u32::MAX); +bounded_impl!(u64, u64::MIN, u64::MAX); + +bounded_impl!(isize, isize::MIN, isize::MAX); +bounded_impl!(i8, i8::MIN, i8::MAX); +bounded_impl!(i16, i16::MIN, i16::MAX); +bounded_impl!(i32, i32::MIN, i32::MAX); +bounded_impl!(i64, i64::MIN, i64::MAX); + +bounded_impl!(f32, f32::MIN, f32::MAX); +bounded_impl!(f64, f64::MIN, f64::MAX); + +/// A generic trait for converting a value to a number. +pub trait ToPrimitive { + /// Converts the value of `self` to an `isize`. + #[inline] + fn to_isize(&self) -> Option<isize> { + self.to_i64().and_then(|x| x.to_isize()) + } + + /// Converts the value of `self` to an `i8`. + #[inline] + fn to_i8(&self) -> Option<i8> { + self.to_i64().and_then(|x| x.to_i8()) + } + + /// Converts the value of `self` to an `i16`. + #[inline] + fn to_i16(&self) -> Option<i16> { + self.to_i64().and_then(|x| x.to_i16()) + } + + /// Converts the value of `self` to an `i32`. + #[inline] + fn to_i32(&self) -> Option<i32> { + self.to_i64().and_then(|x| x.to_i32()) + } + + /// Converts the value of `self` to an `i64`. + fn to_i64(&self) -> Option<i64>; + + /// Converts the value of `self` to a `usize`. + #[inline] + fn to_usize(&self) -> Option<usize> { + self.to_u64().and_then(|x| x.to_usize()) + } + + /// Converts the value of `self` to an `u8`. + #[inline] + fn to_u8(&self) -> Option<u8> { + self.to_u64().and_then(|x| x.to_u8()) + } + + /// Converts the value of `self` to an `u16`. + #[inline] + fn to_u16(&self) -> Option<u16> { + self.to_u64().and_then(|x| x.to_u16()) + } + + /// Converts the value of `self` to an `u32`. + #[inline] + fn to_u32(&self) -> Option<u32> { + self.to_u64().and_then(|x| x.to_u32()) + } + + /// Converts the value of `self` to an `u64`. + #[inline] + fn to_u64(&self) -> Option<u64>; + + /// Converts the value of `self` to an `f32`. + #[inline] + fn to_f32(&self) -> Option<f32> { + self.to_f64().and_then(|x| x.to_f32()) + } + + /// Converts the value of `self` to an `f64`. + #[inline] + fn to_f64(&self) -> Option<f64> { + self.to_i64().and_then(|x| x.to_f64()) + } +} + +macro_rules! impl_to_primitive_int_to_int { + ($SrcT:ty, $DstT:ty, $slf:expr) => ( + { + if size_of::<$SrcT>() <= size_of::<$DstT>() { + Some($slf as $DstT) + } else { + let n = $slf as i64; + let min_value: $DstT = Bounded::min_value(); + let max_value: $DstT = Bounded::max_value(); + if min_value as i64 <= n && n <= max_value as i64 { + Some($slf as $DstT) + } else { + None + } + } + } + ) +} + +macro_rules! impl_to_primitive_int_to_uint { + ($SrcT:ty, $DstT:ty, $slf:expr) => ( + { + let zero: $SrcT = 0; + let max_value: $DstT = Bounded::max_value(); + if zero <= $slf && $slf as u64 <= max_value as u64 { + Some($slf as $DstT) + } else { + None + } + } + ) +} + +macro_rules! impl_to_primitive_int { + ($T:ty) => ( + impl ToPrimitive for $T { + #[inline] + fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) } + #[inline] + fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) } + #[inline] + fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) } + #[inline] + fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) } + #[inline] + fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) } + + #[inline] + fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) } + #[inline] + fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) } + #[inline] + fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) } + #[inline] + fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) } + #[inline] + fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) } + + #[inline] + fn to_f32(&self) -> Option<f32> { Some(*self as f32) } + #[inline] + fn to_f64(&self) -> Option<f64> { Some(*self as f64) } + } + ) +} + +impl_to_primitive_int! { isize } +impl_to_primitive_int! { i8 } +impl_to_primitive_int! { i16 } +impl_to_primitive_int! { i32 } +impl_to_primitive_int! { i64 } + +macro_rules! impl_to_primitive_uint_to_int { + ($DstT:ty, $slf:expr) => ( + { + let max_value: $DstT = Bounded::max_value(); + if $slf as u64 <= max_value as u64 { + Some($slf as $DstT) + } else { + None + } + } + ) +} + +macro_rules! impl_to_primitive_uint_to_uint { + ($SrcT:ty, $DstT:ty, $slf:expr) => ( + { + if size_of::<$SrcT>() <= size_of::<$DstT>() { + Some($slf as $DstT) + } else { + let zero: $SrcT = 0; + let max_value: $DstT = Bounded::max_value(); + if zero <= $slf && $slf as u64 <= max_value as u64 { + Some($slf as $DstT) + } else { + None + } + } + } + ) +} + +macro_rules! impl_to_primitive_uint { + ($T:ty) => ( + impl ToPrimitive for $T { + #[inline] + fn to_isize(&self) -> Option<isize> { impl_to_primitive_uint_to_int!(isize, *self) } + #[inline] + fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) } + #[inline] + fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) } + #[inline] + fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) } + #[inline] + fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) } + + #[inline] + fn to_usize(&self) -> Option<usize> { + impl_to_primitive_uint_to_uint!($T, usize, *self) + } + #[inline] + fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) } + #[inline] + fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) } + #[inline] + fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) } + #[inline] + fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) } + + #[inline] + fn to_f32(&self) -> Option<f32> { Some(*self as f32) } + #[inline] + fn to_f64(&self) -> Option<f64> { Some(*self as f64) } + } + ) +} + +impl_to_primitive_uint! { usize } +impl_to_primitive_uint! { u8 } +impl_to_primitive_uint! { u16 } +impl_to_primitive_uint! { u32 } +impl_to_primitive_uint! { u64 } + +macro_rules! impl_to_primitive_float_to_float { + ($SrcT:ident, $DstT:ident, $slf:expr) => ( + if size_of::<$SrcT>() <= size_of::<$DstT>() { + Some($slf as $DstT) + } else { + let n = $slf as f64; + let max_value: $SrcT = ::core::$SrcT::MAX; + if -max_value as f64 <= n && n <= max_value as f64 { + Some($slf as $DstT) + } else { + None + } + } + ) +} + +macro_rules! impl_to_primitive_float { + ($T:ident) => ( + impl ToPrimitive for $T { + #[inline] + fn to_isize(&self) -> Option<isize> { Some(*self as isize) } + #[inline] + fn to_i8(&self) -> Option<i8> { Some(*self as i8) } + #[inline] + fn to_i16(&self) -> Option<i16> { Some(*self as i16) } + #[inline] + fn to_i32(&self) -> Option<i32> { Some(*self as i32) } + #[inline] + fn to_i64(&self) -> Option<i64> { Some(*self as i64) } + + #[inline] + fn to_usize(&self) -> Option<usize> { Some(*self as usize) } + #[inline] + fn to_u8(&self) -> Option<u8> { Some(*self as u8) } + #[inline] + fn to_u16(&self) -> Option<u16> { Some(*self as u16) } + #[inline] + fn to_u32(&self) -> Option<u32> { Some(*self as u32) } + #[inline] + fn to_u64(&self) -> Option<u64> { Some(*self as u64) } + + #[inline] + fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) } + #[inline] + fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) } + } + ) +} + +impl_to_primitive_float! { f32 } +impl_to_primitive_float! { f64 } + +pub trait FromPrimitive: Sized { + #[inline] + fn from_isize(n: isize) -> Option<Self> { + FromPrimitive::from_i64(n as i64) + } + + #[inline] + fn from_i8(n: i8) -> Option<Self> { + FromPrimitive::from_i64(n as i64) + } + + #[inline] + fn from_i16(n: i16) -> Option<Self> { + FromPrimitive::from_i64(n as i64) + } + + #[inline] + fn from_i32(n: i32) -> Option<Self> { + FromPrimitive::from_i64(n as i64) + } + + fn from_i64(n: i64) -> Option<Self>; + + #[inline] + fn from_usize(n: usize) -> Option<Self> { + FromPrimitive::from_u64(n as u64) + } + + #[inline] + fn from_u8(n: u8) -> Option<Self> { + FromPrimitive::from_u64(n as u64) + } + + #[inline] + fn from_u16(n: u16) -> Option<Self> { + FromPrimitive::from_u64(n as u64) + } + + #[inline] + fn from_u32(n: u32) -> Option<Self> { + FromPrimitive::from_u64(n as u64) + } + + fn from_u64(n: u64) -> Option<Self>; + + #[inline] + fn from_f32(n: f32) -> Option<Self> { + FromPrimitive::from_f64(n as f64) + } + + #[inline] + fn from_f64(n: f64) -> Option<Self> { + FromPrimitive::from_i64(n as i64) + } +} + +macro_rules! impl_from_primitive { + ($T:ty, $to_ty:ident) => ( + impl FromPrimitive for $T { + #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() } + } + ) +} + +impl_from_primitive! { isize, to_isize } +impl_from_primitive! { i8, to_i8 } +impl_from_primitive! { i16, to_i16 } +impl_from_primitive! { i32, to_i32 } +impl_from_primitive! { i64, to_i64 } +impl_from_primitive! { usize, to_usize } +impl_from_primitive! { u8, to_u8 } +impl_from_primitive! { u16, to_u16 } +impl_from_primitive! { u32, to_u32 } +impl_from_primitive! { u64, to_u64 } +impl_from_primitive! { f32, to_f32 } +impl_from_primitive! { f64, to_f64 } diff --git a/bash-5.1/vendor/serde/src/de/impls.rs b/bash-5.1/vendor/serde/src/de/impls.rs new file mode 100644 index 0000000..dbdcc01 --- /dev/null +++ b/bash-5.1/vendor/serde/src/de/impls.rs @@ -0,0 +1,1635 @@ +//! This module contains `Deserialize` and `Visitor` implementations. + +#[cfg(feature = "std")] +use std::borrow::Cow; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::borrow::Cow; + +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, Vec, String}; + +#[cfg(feature = "std")] +use std::collections::{HashMap, HashSet, BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque}; + +#[cfg(feature = "collections")] +use collections::borrow::ToOwned; + +#[cfg(any(feature = "std", feature = "collections"))] +use core::cmp; +use core::fmt; +#[cfg(feature = "std")] +use core::hash::{Hash, BuildHasher}; +use core::marker::PhantomData; +#[cfg(all(feature="unstable"))] +use core::mem; +#[cfg(feature = "std")] +use std::net; +#[cfg(feature = "std")] +use std::path; +#[cfg(all(feature="unstable"))] +use core::slice; +use core::str; +#[cfg(feature = "std")] +use std::ffi::{CString, OsString}; +#[cfg(all(feature = "std", feature="unstable"))] +use std::ffi::CStr; + +#[cfg(feature = "std")] +use std::rc::Rc; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::rc::Rc; + +#[cfg(feature = "std")] +use std::sync::Arc; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::arc::Arc; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::boxed::Box; + +use core::cell::{Cell, RefCell}; + +#[cfg(feature = "std")] +use std::sync::{Mutex, RwLock}; + +#[cfg(feature = "std")] +use std::time::Duration; + +#[cfg(feature = "std")] +use std; + +#[cfg(feature = "unstable")] +use core::nonzero::{NonZero, Zeroable}; + +use de::{Deserialize, Deserializer, EnumVisitor, Error, MapVisitor, SeqVisitor, Unexpected, + VariantVisitor, Visitor}; +use de::from_primitive::FromPrimitive; + +#[cfg(feature = "std")] +use bytes::ByteBuf; + +/////////////////////////////////////////////////////////////////////////////// + +/// A visitor that produces a `()`. +pub struct UnitVisitor; + +impl Visitor for UnitVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + fn visit_unit<E>(self) -> Result<(), E> + where E: Error + { + Ok(()) + } + + fn visit_seq<V>(self, _: V) -> Result<(), V::Error> + where V: SeqVisitor + { + Ok(()) + } +} + +impl Deserialize for () { + fn deserialize<D>(deserializer: D) -> Result<(), D::Error> + where D: Deserializer + { + deserializer.deserialize_unit(UnitVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A visitor that produces a `bool`. +pub struct BoolVisitor; + +impl Visitor for BoolVisitor { + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a boolean") + } + + fn visit_bool<E>(self, v: bool) -> Result<bool, E> + where E: Error + { + Ok(v) + } + + fn visit_str<E>(self, s: &str) -> Result<bool, E> + where E: Error + { + match s.trim_matches(::utils::Pattern_White_Space) { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(Error::invalid_type(Unexpected::Str(s), &self)), + } + } +} + +impl Deserialize for bool { + fn deserialize<D>(deserializer: D) -> Result<bool, D::Error> + where D: Deserializer + { + deserializer.deserialize_bool(BoolVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! impl_deserialize_num_method { + ($ty:ident, $src_ty:ident, $method:ident, $from_method:ident, $group:ident, $group_ty:ident) => { + #[inline] + fn $method<E>(self, v: $src_ty) -> Result<$ty, E> + where E: Error, + { + match FromPrimitive::$from_method(v) { + Some(v) => Ok(v), + None => Err(Error::invalid_value(Unexpected::$group(v as $group_ty), &self)), + } + } + } +} + +macro_rules! impl_deserialize_num { + ($ty:ident, $method:ident) => { + impl Deserialize for $ty { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error> + where D: Deserializer, + { + struct PrimitiveVisitor; + + impl Visitor for PrimitiveVisitor { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(stringify!($ty)) + } + + impl_deserialize_num_method!($ty, i8, visit_i8, from_i8, Signed, i64); + impl_deserialize_num_method!($ty, i16, visit_i16, from_i16, Signed, i64); + impl_deserialize_num_method!($ty, i32, visit_i32, from_i32, Signed, i64); + impl_deserialize_num_method!($ty, i64, visit_i64, from_i64, Signed, i64); + impl_deserialize_num_method!($ty, u8, visit_u8, from_u8, Unsigned, u64); + impl_deserialize_num_method!($ty, u16, visit_u16, from_u16, Unsigned, u64); + impl_deserialize_num_method!($ty, u32, visit_u32, from_u32, Unsigned, u64); + impl_deserialize_num_method!($ty, u64, visit_u64, from_u64, Unsigned, u64); + impl_deserialize_num_method!($ty, f32, visit_f32, from_f32, Float, f64); + impl_deserialize_num_method!($ty, f64, visit_f64, from_f64, Float, f64); + + #[inline] + fn visit_str<E>(self, s: &str) -> Result<$ty, E> + where E: Error, + { + str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| { + Err(Error::invalid_type(Unexpected::Str(s), &self)) + }) + } + } + + deserializer.$method(PrimitiveVisitor) + } + } + } +} + +impl_deserialize_num!(isize, deserialize_i64); +impl_deserialize_num!(i8, deserialize_i8); +impl_deserialize_num!(i16, deserialize_i16); +impl_deserialize_num!(i32, deserialize_i32); +impl_deserialize_num!(i64, deserialize_i64); +impl_deserialize_num!(usize, deserialize_u64); +impl_deserialize_num!(u8, deserialize_u8); +impl_deserialize_num!(u16, deserialize_u16); +impl_deserialize_num!(u32, deserialize_u32); +impl_deserialize_num!(u64, deserialize_u64); +impl_deserialize_num!(f32, deserialize_f32); +impl_deserialize_num!(f64, deserialize_f64); + +/////////////////////////////////////////////////////////////////////////////// + +struct CharVisitor; + +impl Visitor for CharVisitor { + type Value = char; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a character") + } + + #[inline] + fn visit_char<E>(self, v: char) -> Result<char, E> + where E: Error + { + Ok(v) + } + + #[inline] + fn visit_str<E>(self, v: &str) -> Result<char, E> + where E: Error + { + let mut iter = v.chars(); + match (iter.next(), iter.next()) { + (Some(c), None) => Ok(c), + _ => Err(Error::invalid_value(Unexpected::Str(v), &self)), + } + } +} + +impl Deserialize for char { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<char, D::Error> + where D: Deserializer + { + deserializer.deserialize_char(CharVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "collections"))] +struct StringVisitor; + +#[cfg(any(feature = "std", feature = "collections"))] +impl Visitor for StringVisitor { + type Value = String; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str<E>(self, v: &str) -> Result<String, E> + where E: Error + { + Ok(v.to_owned()) + } + + fn visit_string<E>(self, v: String) -> Result<String, E> + where E: Error + { + Ok(v) + } + + fn visit_unit<E>(self) -> Result<String, E> + where E: Error + { + Ok(String::new()) + } + + fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E> + where E: Error + { + match str::from_utf8(v) { + Ok(s) => Ok(s.to_owned()), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<String, E> + where E: Error + { + match String::from_utf8(v) { + Ok(s) => Ok(s), + Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)), + } + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl Deserialize for String { + fn deserialize<D>(deserializer: D) -> Result<String, D::Error> + where D: Deserializer + { + deserializer.deserialize_string(StringVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(all(feature = "std", feature="unstable"))] +impl Deserialize for Box<CStr> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(CString::deserialize(deserializer)); + Ok(s.into_boxed_c_str()) + } +} + +#[cfg(feature = "std")] +impl Deserialize for CString { + fn deserialize<D>(deserializer: D) -> Result<CString, D::Error> + where D: Deserializer + { + let bytes = try!(ByteBuf::deserialize(deserializer)); + CString::new(bytes).map_err(Error::custom) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +struct OptionVisitor<T> { + marker: PhantomData<T>, +} + +impl<T: Deserialize> Visitor for OptionVisitor<T> { + type Value = Option<T>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("option") + } + + #[inline] + fn visit_unit<E>(self) -> Result<Option<T>, E> + where E: Error + { + Ok(None) + } + + #[inline] + fn visit_none<E>(self) -> Result<Option<T>, E> + where E: Error + { + Ok(None) + } + + #[inline] + fn visit_some<D>(self, deserializer: D) -> Result<Option<T>, D::Error> + where D: Deserializer + { + Ok(Some(try!(Deserialize::deserialize(deserializer)))) + } +} + +impl<T> Deserialize for Option<T> + where T: Deserialize +{ + fn deserialize<D>(deserializer: D) -> Result<Option<T>, D::Error> + where D: Deserializer + { + deserializer.deserialize_option(OptionVisitor { marker: PhantomData }) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A visitor that produces a `PhantomData`. +pub struct PhantomDataVisitor<T> { + marker: PhantomData<T>, +} + +impl<T> Visitor for PhantomDataVisitor<T> { + type Value = PhantomData<T>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + #[inline] + fn visit_unit<E>(self) -> Result<PhantomData<T>, E> + where E: Error + { + Ok(PhantomData) + } +} + +impl<T> Deserialize for PhantomData<T> { + fn deserialize<D>(deserializer: D) -> Result<PhantomData<T>, D::Error> + where D: Deserializer + { + let visitor = PhantomDataVisitor { marker: PhantomData }; + deserializer.deserialize_unit_struct("PhantomData", visitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! seq_impl { + ( + $ty:ty, + $visitor_ty:ident < $($typaram:ident : $bound1:ident $(+ $bound2:ident)*),* >, + $visitor:ident, + $ctor:expr, + $with_capacity:expr, + $insert:expr + ) => { + /// A visitor that produces a sequence. + pub struct $visitor_ty<$($typaram),*> { + marker: PhantomData<$ty>, + } + + impl<$($typaram),*> $visitor_ty<$($typaram),*> + where $($typaram: $bound1 $(+ $bound2)*),* + { + /// Construct a new sequence visitor. + pub fn new() -> Self { + $visitor_ty { + marker: PhantomData, + } + } + } + + impl<$($typaram),*> Visitor for $visitor_ty<$($typaram),*> + where $($typaram: $bound1 $(+ $bound2)*),* + { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_unit<E>(self) -> Result<$ty, E> + where E: Error, + { + Ok($ctor) + } + + #[inline] + fn visit_seq<V>(self, mut $visitor: V) -> Result<$ty, V::Error> + where V: SeqVisitor, + { + let mut values = $with_capacity; + + while let Some(value) = try!($visitor.visit()) { + $insert(&mut values, value); + } + + Ok(values) + } + } + + impl<$($typaram),*> Deserialize for $ty + where $($typaram: $bound1 $(+ $bound2)*),* + { + fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error> + where D: Deserializer, + { + deserializer.deserialize_seq($visitor_ty::new()) + } + } + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +seq_impl!( + BinaryHeap<T>, + BinaryHeapVisitor<T: Deserialize + Ord>, + visitor, + BinaryHeap::new(), + BinaryHeap::with_capacity(cmp::min(visitor.size_hint().0, 4096)), + BinaryHeap::push); + +#[cfg(any(feature = "std", feature = "collections"))] +seq_impl!( + BTreeSet<T>, + BTreeSetVisitor<T: Deserialize + Eq + Ord>, + visitor, + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::insert); + +#[cfg(any(feature = "std", feature = "collections"))] +seq_impl!( + LinkedList<T>, + LinkedListVisitor<T: Deserialize>, + visitor, + LinkedList::new(), + LinkedList::new(), + LinkedList::push_back); + +#[cfg(feature = "std")] +seq_impl!( + HashSet<T, S>, + HashSetVisitor<T: Deserialize + Eq + Hash, + S: BuildHasher + Default>, + visitor, + HashSet::with_hasher(S::default()), + HashSet::with_capacity_and_hasher(cmp::min(visitor.size_hint().0, 4096), S::default()), + HashSet::insert); + +#[cfg(any(feature = "std", feature = "collections"))] +seq_impl!( + Vec<T>, + VecVisitor<T: Deserialize>, + visitor, + Vec::new(), + Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)), + Vec::push); + +#[cfg(any(feature = "std", feature = "collections"))] +seq_impl!( + VecDeque<T>, + VecDequeVisitor<T: Deserialize>, + visitor, + VecDeque::new(), + VecDeque::with_capacity(cmp::min(visitor.size_hint().0, 4096)), + VecDeque::push_back); + +/////////////////////////////////////////////////////////////////////////////// + +struct ArrayVisitor<A> { + marker: PhantomData<A>, +} + +impl<A> ArrayVisitor<A> { + pub fn new() -> Self { + ArrayVisitor { marker: PhantomData } + } +} + +impl<T> Visitor for ArrayVisitor<[T; 0]> + where T: Deserialize +{ + type Value = [T; 0]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("an empty array") + } + + #[inline] + fn visit_unit<E>(self) -> Result<[T; 0], E> + where E: Error + { + Ok([]) + } + + #[inline] + fn visit_seq<V>(self, _: V) -> Result<[T; 0], V::Error> + where V: SeqVisitor + { + Ok([]) + } +} + +impl<T> Deserialize for [T; 0] + where T: Deserialize +{ + fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error> + where D: Deserializer + { + deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new()) + } +} + +macro_rules! array_impls { + ($($len:expr => ($($n:tt $name:ident)+))+) => { + $( + impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize { + type Value = [T; $len]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq<V>(self, mut visitor: V) -> Result<[T; $len], V::Error> + where V: SeqVisitor, + { + $( + let $name = match try!(visitor.visit()) { + Some(val) => val, + None => return Err(Error::invalid_length($n, &self)), + }; + )+ + + Ok([$($name),+]) + } + } + + impl<T> Deserialize for [T; $len] + where T: Deserialize, + { + fn deserialize<D>(deserializer: D) -> Result<[T; $len], D::Error> + where D: Deserializer, + { + deserializer.deserialize_seq_fixed_size($len, ArrayVisitor::<[T; $len]>::new()) + } + } + )+ + } +} + +array_impls! { + 1 => (0 a) + 2 => (0 a 1 b) + 3 => (0 a 1 b 2 c) + 4 => (0 a 1 b 2 c 3 d) + 5 => (0 a 1 b 2 c 3 d 4 e) + 6 => (0 a 1 b 2 c 3 d 4 e 5 f) + 7 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g) + 8 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h) + 9 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i) + 10 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j) + 11 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k) + 12 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l) + 13 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m) + 14 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n) + 15 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o) + 16 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p) + 17 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q) + 18 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r) + 19 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s) + 20 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t) + 21 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u) + 22 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v) + 23 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w) + 24 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x) + 25 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y) + 26 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z) + 27 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa) + 28 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab) + 29 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac) + 30 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad) + 31 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae) + 32 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae 31 af) +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:expr => $visitor:ident => ($($n:tt $name:ident)+))+) => { + $( + /// Construct a tuple visitor. + pub struct $visitor<$($name,)+> { + marker: PhantomData<($($name,)+)>, + } + + impl<$($name: Deserialize,)+> $visitor<$($name,)+> { + /// Construct a `TupleVisitor*<T>`. + pub fn new() -> Self { + $visitor { marker: PhantomData } + } + } + + impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> { + type Value = ($($name,)+); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq<V>(self, mut visitor: V) -> Result<($($name,)+), V::Error> + where V: SeqVisitor, + { + $( + let $name = match try!(visitor.visit()) { + Some(value) => value, + None => return Err(Error::invalid_length($n, &self)), + }; + )+ + + Ok(($($name,)+)) + } + } + + impl<$($name: Deserialize),+> Deserialize for ($($name,)+) { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<($($name,)+), D::Error> + where D: Deserializer, + { + deserializer.deserialize_tuple($len, $visitor::new()) + } + } + )+ + } +} + +tuple_impls! { + 1 => TupleVisitor1 => (0 T0) + 2 => TupleVisitor2 => (0 T0 1 T1) + 3 => TupleVisitor3 => (0 T0 1 T1 2 T2) + 4 => TupleVisitor4 => (0 T0 1 T1 2 T2 3 T3) + 5 => TupleVisitor5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => TupleVisitor6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => TupleVisitor7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => TupleVisitor8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => TupleVisitor9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => TupleVisitor10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => TupleVisitor11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => TupleVisitor12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => TupleVisitor13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => TupleVisitor14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => TupleVisitor15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => TupleVisitor16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! map_impl { + ( + $ty:ty, + $visitor_ty:ident < $($typaram:ident : $bound1:ident $(+ $bound2:ident)*),* >, + $visitor:ident, + $ctor:expr, + $with_capacity:expr + ) => { + /// A visitor that produces a map. + pub struct $visitor_ty<$($typaram),*> { + marker: PhantomData<$ty>, + } + + impl<$($typaram),*> $visitor_ty<$($typaram),*> + where $($typaram: $bound1 $(+ $bound2)*),* + { + /// Construct a `MapVisitor*<T>`. + pub fn new() -> Self { + $visitor_ty { + marker: PhantomData, + } + } + } + + impl<$($typaram),*> Visitor for $visitor_ty<$($typaram),*> + where $($typaram: $bound1 $(+ $bound2)*),* + { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map") + } + + #[inline] + fn visit_unit<E>(self) -> Result<$ty, E> + where E: Error, + { + Ok($ctor) + } + + #[inline] + fn visit_map<Visitor>(self, mut $visitor: Visitor) -> Result<$ty, Visitor::Error> + where Visitor: MapVisitor, + { + let mut values = $with_capacity; + + while let Some((key, value)) = try!($visitor.visit()) { + values.insert(key, value); + } + + Ok(values) + } + } + + impl<$($typaram),*> Deserialize for $ty + where $($typaram: $bound1 $(+ $bound2)*),* + { + fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error> + where D: Deserializer, + { + deserializer.deserialize_map($visitor_ty::new()) + } + } + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +map_impl!( + BTreeMap<K, V>, + BTreeMapVisitor<K: Deserialize + Ord, + V: Deserialize>, + visitor, + BTreeMap::new(), + BTreeMap::new()); + +#[cfg(feature = "std")] +map_impl!( + HashMap<K, V, S>, + HashMapVisitor<K: Deserialize + Eq + Hash, + V: Deserialize, + S: BuildHasher + Default>, + visitor, + HashMap::with_hasher(S::default()), + HashMap::with_capacity_and_hasher(cmp::min(visitor.size_hint().0, 4096), S::default())); + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Deserialize for net::IpAddr { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + match s.parse() { + Ok(s) => Ok(s), + Err(err) => Err(D::Error::custom(err)), + } + } +} + +#[cfg(feature = "std")] +impl Deserialize for net::Ipv4Addr { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + match s.parse() { + Ok(s) => Ok(s), + Err(err) => Err(D::Error::custom(err)), + } + } +} + +#[cfg(feature = "std")] +impl Deserialize for net::Ipv6Addr { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + match s.parse() { + Ok(s) => Ok(s), + Err(err) => Err(D::Error::custom(err)), + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Deserialize for net::SocketAddr { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + match s.parse() { + Ok(s) => Ok(s), + Err(err) => Err(D::Error::custom(err)), + } + } +} + +#[cfg(feature = "std")] +impl Deserialize for net::SocketAddrV4 { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + match s.parse() { + Ok(s) => Ok(s), + Err(err) => Err(D::Error::custom(err)), + } + } +} + +#[cfg(feature = "std")] +impl Deserialize for net::SocketAddrV6 { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + match s.parse() { + Ok(s) => Ok(s), + Err(err) => Err(D::Error::custom(err)), + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +struct PathBufVisitor; + +#[cfg(feature = "std")] +impl Visitor for PathBufVisitor { + type Value = path::PathBuf; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("path string") + } + + fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E> + where E: Error + { + Ok(From::from(v)) + } + + fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E> + where E: Error + { + Ok(From::from(v)) + } +} + + +#[cfg(feature = "std")] +impl Deserialize for path::PathBuf { + fn deserialize<D>(deserializer: D) -> Result<path::PathBuf, D::Error> + where D: Deserializer + { + deserializer.deserialize_string(PathBufVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(all(feature = "std", any(unix, windows)))] +enum OsStringKind { + Unix, + Windows, +} + +#[cfg(all(feature = "std", any(unix, windows)))] +static OSSTR_VARIANTS: &'static [&'static str] = &["Unix", "Windows"]; + +#[cfg(all(feature = "std", any(unix, windows)))] +impl Deserialize for OsStringKind { + fn deserialize<D>(deserializer: D) -> Result<OsStringKind, D::Error> + where D: Deserializer + { + struct KindVisitor; + + impl Visitor for KindVisitor { + type Value = OsStringKind; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Unix` or `Windows`") + } + + fn visit_u32<E>(self, value: u32) -> Result<OsStringKind, E> + where E: Error, + { + match value { + 0 => Ok(OsStringKind::Unix), + 1 => Ok(OsStringKind::Windows), + _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)) + } + } + + fn visit_str<E>(self, value: &str) -> Result<OsStringKind, E> + where E: Error, + { + match value { + "Unix" => Ok(OsStringKind::Unix), + "Windows" => Ok(OsStringKind::Windows), + _ => Err(Error::unknown_variant(value, OSSTR_VARIANTS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<OsStringKind, E> + where E: Error, + { + match value { + b"Unix" => Ok(OsStringKind::Unix), + b"Windows" => Ok(OsStringKind::Windows), + _ => { + match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, OSSTR_VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + } + } + } + } + } + + deserializer.deserialize(KindVisitor) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +struct OsStringVisitor; + +#[cfg(all(feature = "std", any(unix, windows)))] +impl Visitor for OsStringVisitor { + type Value = OsString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("os string") + } + + #[cfg(unix)] + fn visit_enum<V>(self, visitor: V) -> Result<OsString, V::Error> + where V: EnumVisitor, + { + use std::os::unix::ffi::OsStringExt; + + match try!(visitor.visit_variant()) { + (OsStringKind::Unix, variant) => { + variant.visit_newtype().map(OsString::from_vec) + } + (OsStringKind::Windows, _) => { + Err(Error::custom("cannot deserialize Windows OS string on Unix")) + } + } + } + + #[cfg(windows)] + fn visit_enum<V>(self, visitor: V) -> Result<OsString, V::Error> + where V: EnumVisitor, + { + use std::os::windows::ffi::OsStringExt; + + match try!(visitor.visit_variant()) { + (OsStringKind::Windows, variant) => { + variant.visit_newtype::<Vec<u16>>().map(|vec| OsString::from_wide(&vec)) + } + (OsStringKind::Unix, _) => { + Err(Error::custom("cannot deserialize Unix OS string on Windows")) + } + } + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +impl Deserialize for OsString { + fn deserialize<D>(deserializer: D) -> Result<OsString, D::Error> + where D: Deserializer + { + deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<T: Deserialize> Deserialize for Box<T> { + fn deserialize<D>(deserializer: D) -> Result<Box<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(Box::new(val)) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T: Deserialize> Deserialize for Box<[T]> { + fn deserialize<D>(deserializer: D) -> Result<Box<[T]>, D::Error> + where D: Deserializer + { + let v: Vec<T> = try!(Deserialize::deserialize(deserializer)); + Ok(v.into_boxed_slice()) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl Deserialize for Box<str> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + let s = try!(String::deserialize(deserializer)); + Ok(s.into_boxed_str()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<T: Deserialize> Deserialize for Arc<T> { + fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(Arc::new(val)) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<T: Deserialize> Deserialize for Rc<T> { + fn deserialize<D>(deserializer: D) -> Result<Rc<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(Rc::new(val)) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a, T: ?Sized> Deserialize for Cow<'a, T> + where T: ToOwned, + T::Owned: Deserialize +{ + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Cow<'a, T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(Cow::Owned(val)) + } +} + +impl<T: Deserialize + Copy> Deserialize for Cell<T> { + fn deserialize<D>(deserializer: D) -> Result<Cell<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(Cell::new(val)) + } +} + +impl<T: Deserialize> Deserialize for RefCell<T> { + fn deserialize<D>(deserializer: D) -> Result<RefCell<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(RefCell::new(val)) + } +} + +#[cfg(feature = "std")] +impl<T: Deserialize> Deserialize for Mutex<T> { + fn deserialize<D>(deserializer: D) -> Result<Mutex<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(Mutex::new(val)) + } +} + +#[cfg(feature = "std")] +impl<T: Deserialize> Deserialize for RwLock<T> { + fn deserialize<D>(deserializer: D) -> Result<RwLock<T>, D::Error> + where D: Deserializer + { + let val = try!(Deserialize::deserialize(deserializer)); + Ok(RwLock::new(val)) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +// This is a cleaned-up version of the impl generated by: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Duration { +// secs: u64, +// nanos: u32, +// } +#[cfg(feature = "std")] +impl Deserialize for Duration { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + enum Field { + Secs, + Nanos, + }; + + impl Deserialize for Field { + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where D: Deserializer + { + struct FieldVisitor; + + impl Visitor for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs` or `nanos`") + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where E: Error + { + match value { + "secs" => Ok(Field::Secs), + "nanos" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where E: Error + { + match value { + b"secs" => Ok(Field::Secs), + b"nanos" => Ok(Field::Nanos), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_struct_field(FieldVisitor) + } + } + + struct DurationVisitor; + + impl Visitor for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Duration") + } + + fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error> + where V: SeqVisitor + { + let secs: u64 = match try!(visitor.visit()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match try!(visitor.visit()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok(Duration::new(secs, nanos)) + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Duration, V::Error> + where V: MapVisitor + { + let mut secs: Option<u64> = None; + let mut nanos: Option<u32> = None; + while let Some(key) = try!(visitor.visit_key::<Field>()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(<V::Error as Error>::duplicate_field("secs")); + } + secs = Some(try!(visitor.visit_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(<V::Error as Error>::duplicate_field("nanos")); + } + nanos = Some(try!(visitor.visit_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(<V::Error as Error>::missing_field("secs")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(<V::Error as Error>::missing_field("nanos")), + }; + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &'static [&'static str] = &["secs", "nanos"]; + deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Range { +// start: u64, +// end: u32, +// } +#[cfg(feature = "std")] +impl<Idx: Deserialize> Deserialize for std::ops::Range<Idx> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: Deserializer + { + enum Field { + Start, + End, + }; + + impl Deserialize for Field { + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where D: Deserializer + { + struct FieldVisitor; + + impl Visitor for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`start` or `end`") + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where E: Error + { + match value { + "start" => Ok(Field::Start), + "end" => Ok(Field::End), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where E: Error + { + match value { + b"start" => Ok(Field::Start), + b"end" => Ok(Field::End), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_struct_field(FieldVisitor) + } + } + + struct RangeVisitor<Idx> { + phantom: PhantomData<Idx>, + } + + impl<Idx: Deserialize> Visitor for RangeVisitor<Idx> { + type Value = std::ops::Range<Idx>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Range") + } + + fn visit_seq<V>(self, mut visitor: V) -> Result<std::ops::Range<Idx>, V::Error> + where V: SeqVisitor + { + let start: Idx = match try!(visitor.visit()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let end: Idx = match try!(visitor.visit()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok(start..end) + } + + fn visit_map<V>(self, mut visitor: V) -> Result<std::ops::Range<Idx>, V::Error> + where V: MapVisitor + { + let mut start: Option<Idx> = None; + let mut end: Option<Idx> = None; + while let Some(key) = try!(visitor.visit_key::<Field>()) { + match key { + Field::Start => { + if start.is_some() { + return Err(<V::Error as Error>::duplicate_field("start")); + } + start = Some(try!(visitor.visit_value())); + } + Field::End => { + if end.is_some() { + return Err(<V::Error as Error>::duplicate_field("end")); + } + end = Some(try!(visitor.visit_value())); + } + } + } + let start = match start { + Some(start) => start, + None => return Err(<V::Error as Error>::missing_field("start")), + }; + let end = match end { + Some(end) => end, + None => return Err(<V::Error as Error>::missing_field("end")), + }; + Ok(start..end) + } + } + + const FIELDS: &'static [&'static str] = &["start", "end"]; + deserializer.deserialize_struct("Range", FIELDS, RangeVisitor { phantom: PhantomData }) + } +} + +/////////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "unstable")] +impl<T> Deserialize for NonZero<T> + where T: Deserialize + Zeroable +{ + fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> + where D: Deserializer + { + let value = try!(Deserialize::deserialize(deserializer)); + unsafe { + let ptr = &value as *const T as *const u8; + if slice::from_raw_parts(ptr, mem::size_of::<T>()).iter().all(|&b| b == 0) { + return Err(Error::custom("expected a non-zero value")); + } + // Waiting for a safe way to construct NonZero<T>: + // https://github.com/rust-lang/rust/issues/27730#issuecomment-269726075 + Ok(NonZero::new(value)) + } + + } +} + +/////////////////////////////////////////////////////////////////////////////// + + +impl<T, E> Deserialize for Result<T, E> + where T: Deserialize, + E: Deserialize +{ + fn deserialize<D>(deserializer: D) -> Result<Result<T, E>, D::Error> + where D: Deserializer + { + enum Field { + Ok, + Err, + } + + impl Deserialize for Field { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where D: Deserializer + { + struct FieldVisitor; + + impl Visitor for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Ok` or `Err`") + } + + fn visit_u32<E>(self, value: u32) -> Result<Field, E> + where E: Error + { + match value { + 0 => Ok(Field::Ok), + 1 => Ok(Field::Err), + _ => { + Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)) + } + } + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where E: Error + { + match value { + "Ok" => Ok(Field::Ok), + "Err" => Ok(Field::Err), + _ => Err(Error::unknown_variant(value, VARIANTS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where E: Error + { + match value { + b"Ok" => Ok(Field::Ok), + b"Err" => Ok(Field::Err), + _ => { + match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + } + } + } + } + } + + deserializer.deserialize(FieldVisitor) + } + } + + struct ResultVisitor<T, E>(PhantomData<Result<T, E>>); + + impl<T, E> Visitor for ResultVisitor<T, E> + where T: Deserialize, + E: Deserialize + { + type Value = Result<T, E>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("enum Result") + } + + fn visit_enum<V>(self, visitor: V) -> Result<Result<T, E>, V::Error> + where V: EnumVisitor + { + match try!(visitor.visit_variant()) { + (Field::Ok, variant) => variant.visit_newtype().map(Ok), + (Field::Err, variant) => variant.visit_newtype().map(Err), + } + } + } + + const VARIANTS: &'static [&'static str] = &["Ok", "Err"]; + + deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData)) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A target for deserializers that want to ignore data. Implements +/// Deserialize and silently eats data given to it. +pub struct IgnoredAny; + +impl Deserialize for IgnoredAny { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<IgnoredAny, D::Error> + where D: Deserializer + { + struct IgnoredAnyVisitor; + + impl Visitor for IgnoredAnyVisitor { + type Value = IgnoredAny; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("anything at all") + } + + #[inline] + fn visit_bool<E>(self, _: bool) -> Result<IgnoredAny, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_i64<E>(self, _: i64) -> Result<IgnoredAny, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_u64<E>(self, _: u64) -> Result<IgnoredAny, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_f64<E>(self, _: f64) -> Result<IgnoredAny, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_str<E>(self, _: &str) -> Result<IgnoredAny, E> + where E: Error + { + Ok(IgnoredAny) + } + + #[inline] + fn visit_none<E>(self) -> Result<IgnoredAny, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_some<D>(self, _: D) -> Result<IgnoredAny, D::Error> + where D: Deserializer + { + Ok(IgnoredAny) + } + + #[inline] + fn visit_newtype_struct<D>(self, _: D) -> Result<IgnoredAny, D::Error> + where D: Deserializer + { + Ok(IgnoredAny) + } + + #[inline] + fn visit_unit<E>(self) -> Result<IgnoredAny, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_seq<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error> + where V: SeqVisitor + { + while let Some(_) = try!(visitor.visit::<IgnoredAny>()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_map<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error> + where V: MapVisitor + { + while let Some((_, _)) = try!(visitor.visit::<IgnoredAny, IgnoredAny>()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_bytes<E>(self, _: &[u8]) -> Result<IgnoredAny, E> + where E: Error + { + Ok(IgnoredAny) + } + } + + // TODO maybe not necessary with impl specialization + deserializer.deserialize_ignored_any(IgnoredAnyVisitor) + } +} diff --git a/bash-5.1/vendor/serde/src/de/mod.rs b/bash-5.1/vendor/serde/src/de/mod.rs new file mode 100644 index 0000000..72c1bce --- /dev/null +++ b/bash-5.1/vendor/serde/src/de/mod.rs @@ -0,0 +1,1535 @@ +//! Generic data structure deserialization framework. +//! +//! The two most important traits in this module are `Deserialize` and +//! `Deserializer`. +//! +//! - **A type that implements `Deserialize` is a data structure** that can be +//! deserialized from any data format supported by Serde, and conversely +//! - **A type that implements `Deserializer` is a data format** that can +//! deserialize any data structure supported by Serde. +//! +//! # The Deserialize trait +//! +//! Serde provides `Deserialize` implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! deserialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called `serde_derive` to +//! automatically generate `Deserialize` implementations for structs and enums +//! in your program. See the [codegen section of the manual][codegen] for how to +//! use this. +//! +//! In rare cases it may be necessary to implement `Deserialize` manually for +//! some type in your program. See the [Implementing +//! `Deserialize`][impl-deserialize] section of the manual for more about this. +//! +//! Third-party crates may provide `Deserialize` implementations for types that +//! they expose. For example the `linked-hash-map` crate provides a +//! `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate +//! provides an implementation of `Deserialize` for it. +//! +//! # The Deserializer trait +//! +//! `Deserializer` implementations are provided by third-party crates, for +//! example [`serde_json`][serde_json], [`serde_yaml`][serde_yaml] and +//! [`bincode`][bincode]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data-formats]. +//! +//! # Implementations of Deserialize provided by Serde +//! +//! This is a slightly different set of types than what is supported for +//! serialization. Some types can be serialized by Serde but not deserialized. +//! One example is `&str`. +//! +//! - **Primitive types**: +//! - bool +//! - isize, i8, i16, i32, i64 +//! - usize, u8, u16, u32, u64 +//! - f32, f64 +//! - char +//! - **Compound types**: +//! - [T; 0] through [T; 32] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\<T\> +//! - Result\<T, E\> +//! - PhantomData\<T\> +//! - **Wrapper types**: +//! - Box\<T\> +//! - Box\<[T]\> +//! - Box\<str\> +//! - Rc\<T\> +//! - Arc\<T\> +//! - Cow\<'a, T\> +//! - Cell\<T\> +//! - RefCell\<T\> +//! - Mutex\<T\> +//! - RwLock\<T\> +//! - **Collection types**: +//! - BTreeMap\<K, V\> +//! - BTreeSet\<T\> +//! - BinaryHeap\<T\> +//! - HashMap\<K, V, H\> +//! - HashSet\<T, H\> +//! - LinkedList\<T\> +//! - VecDeque\<T\> +//! - Vec\<T\> +//! - EnumSet\<T\> (unstable) +//! - **Miscellaneous standard library types**: +//! - Duration +//! - Path +//! - PathBuf +//! - NonZero\<T\> (unstable) +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [codegen]: https://serde.rs/codegen.html +//! [impl-deserialize]: https://serde.rs/impl-deserialize.html +//! [serde_json]: https://github.com/serde-rs/json +//! [serde_yaml]: https://github.com/dtolnay/serde-yaml +//! [bincode]: https://github.com/TyOverby/bincode +//! [data-formats]: https://serde.rs/#data-formats + +#[cfg(feature = "std")] +use std::error; +#[cfg(not(feature = "std"))] +use error; + +#[cfg(all(not(feature = "std"), feature = "collections"))] +use collections::{String, Vec}; + +use core::fmt::{self, Display}; +use core::marker::PhantomData; + +/////////////////////////////////////////////////////////////////////////////// + +#[doc(hidden)] +pub mod impls; +pub mod value; +mod from_primitive; + +// Helpers used by generated code. Not public API. +#[doc(hidden)] +pub mod private; +#[cfg(any(feature = "std", feature = "collections"))] +mod content; + +/////////////////////////////////////////////////////////////////////////////// + +/// The `Error` trait allows `Deserialize` implementations to create descriptive +/// error messages belonging to the `Deserializer` against which they are +/// currently running. +/// +/// Every `Deserializer` declares an `Error` type that encompasses both +/// general-purpose deserialization errors as well as errors specific to the +/// particular deserialization format. For example the `Error` type of +/// `serde_json` can represent errors like an invalid JSON escape sequence or an +/// unterminated string literal, in addition to the error cases that are part of +/// this trait. +/// +/// Most deserializers should only need to provide the `Error::custom` method +/// and inherit the default behavior for the other methods. +pub trait Error: Sized + error::Error { + /// Raised when there is general error when deserializing a type. + /// + /// The message should not be capitalized and should not end with a period. + /// + /// ```rust + /// # use serde::de::{Deserialize, Deserializer, Error}; + /// # use std::str::FromStr; + /// # #[allow(dead_code)] + /// # struct IpAddr; + /// # impl FromStr for IpAddr { + /// # type Err = String; + /// # fn from_str(_: &str) -> Result<Self, String> { unimplemented!() } + /// # } + /// impl Deserialize for IpAddr { + /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + /// where D: Deserializer + /// { + /// let s = try!(String::deserialize(deserializer)); + /// s.parse().map_err(Error::custom) + /// } + /// } + /// ``` + fn custom<T: Display>(msg: T) -> Self; + + /// Raised when a `Deserialize` receives a type different from what it was + /// expecting. + /// + /// The `unexp` argument provides information about what type was received. + /// This is the type that was present in the input file or other source data + /// of the Deserializer. + /// + /// The `exp` argument provides information about what type was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of a JSON file + /// containing an integer, the unexpected type is the integer and the + /// expected type is the string. + fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self { + Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) + } + + /// Raised when a `Deserialize` receives a value of the right type but that + /// is wrong for some other reason. + /// + /// The `unexp` argument provides information about what value was received. + /// This is the value that was present in the input file or other source + /// data of the Deserializer. + /// + /// The `exp` argument provides information about what value was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of some binary data + /// that is not valid UTF-8, the unexpected value is the bytes and the + /// expected value is a string. + fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self { + Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp)) + } + + /// Raised when deserializing a sequence or map and the input data contains + /// too many or too few elements. + /// + /// The `len` argument is the number of elements encountered. The sequence + /// or map may have expected more arguments or fewer arguments. + /// + /// The `exp` argument provides information about what data was being + /// expected. For example `exp` might say that a tuple of size 6 was + /// expected. + fn invalid_length(len: usize, exp: &Expected) -> Self { + Error::custom(format_args!("invalid length {}, expected {}", len, exp)) + } + + /// Raised when a `Deserialize` enum type received a variant with an + /// unrecognized name. + fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!("unknown variant `{}`, there are no variants", + variant)) + } else { + Error::custom(format_args!("unknown variant `{}`, expected {}", + variant, + OneOf { names: expected })) + } + } + + /// Raised when a `Deserialize` struct type received a field with an + /// unrecognized name. + fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!("unknown field `{}`, there are no fields", + field)) + } else { + Error::custom(format_args!("unknown field `{}`, expected {}", + field, + OneOf { names: expected })) + } + } + + /// Raised when a `Deserialize` struct type expected to receive a required + /// field with a particular name but that field was not present in the + /// input. + fn missing_field(field: &'static str) -> Self { + Error::custom(format_args!("missing field `{}`", field)) + } + + /// Raised when a `Deserialize` struct type received more than one of the + /// same field. + fn duplicate_field(field: &'static str) -> Self { + Error::custom(format_args!("duplicate field `{}`", field)) + } +} + +/// `Unexpected` represents an unexpected invocation of any one of the `Visitor` +/// trait methods. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. +/// +/// ```rust +/// # use serde::de::{Error, Unexpected, Visitor}; +/// # use std::fmt; +/// # #[allow(dead_code)] +/// # struct Example; +/// # impl Visitor for Example { +/// # type Value = (); +/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> +/// where E: Error +/// { +/// Err(Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # } +/// ``` +#[derive(Clone, PartialEq, Debug)] +pub enum Unexpected<'a> { + /// The input contained a boolean value that was not expected. + Bool(bool), + + /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that + /// was not expected. + Unsigned(u64), + + /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that + /// was not expected. + Signed(i64), + + /// The input contained a floating point `f32` or `f64` that was not + /// expected. + Float(f64), + + /// The input contained a `char` that was not expected. + Char(char), + + /// The input contained a `&str` or `String` that was not expected. + Str(&'a str), + + /// The input contained a `&[u8]` or `Vec<u8>` that was not expected. + Bytes(&'a [u8]), + + /// The input contained a unit `()` that was not expected. + Unit, + + /// The input contained an `Option<T>` that was not expected. + Option, + + /// The input contained a newtype struct that was not expected. + NewtypeStruct, + + /// The input contained a sequence that was not expected. + Seq, + + /// The input contained a map that was not expected. + Map, + + /// The input contained an enum that was not expected. + Enum, + + /// The input contained a unit variant that was not expected. + UnitVariant, + + /// The input contained a newtype variant that was not expected. + NewtypeVariant, + + /// The input contained a tuple variant that was not expected. + TupleVariant, + + /// The input contained a struct variant that was not expected. + StructVariant, + + /// A message stating what uncategorized thing the input contained that was + /// not expected. + /// + /// The message should be a noun or noun phrase, not capitalized and without + /// a period. An example message is "unoriginal superhero". + Other(&'a str), +} + +impl<'a> fmt::Display for Unexpected<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + use self::Unexpected::*; + match *self { + Bool(b) => write!(formatter, "boolean `{}`", b), + Unsigned(i) => write!(formatter, "integer `{}`", i), + Signed(i) => write!(formatter, "integer `{}`", i), + Float(f) => write!(formatter, "floating point `{}`", f), + Char(c) => write!(formatter, "character `{}`", c), + Str(s) => write!(formatter, "string {:?}", s), + Bytes(_) => write!(formatter, "byte array"), + Unit => write!(formatter, "unit value"), + Option => write!(formatter, "Option value"), + NewtypeStruct => write!(formatter, "newtype struct"), + Seq => write!(formatter, "sequence"), + Map => write!(formatter, "map"), + Enum => write!(formatter, "enum"), + UnitVariant => write!(formatter, "unit variant"), + NewtypeVariant => write!(formatter, "newtype variant"), + TupleVariant => write!(formatter, "tuple variant"), + StructVariant => write!(formatter, "struct variant"), + Other(other) => formatter.write_str(other), + } + } +} + +/// `Expected` represents an explanation of what data a `Visitor` was expecting +/// to receive. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. The +/// message should be a noun or noun phrase that completes the sentence "This +/// Visitor expects to receive ...", for example the message could be "an +/// integer between 0 and 64". The message should not be capitalized and should +/// not end with a period. +/// +/// Within the context of a `Visitor` implementation, the `Visitor` itself +/// (`&self`) is an implementation of this trait. +/// +/// ```rust +/// # use serde::de::{Error, Unexpected, Visitor}; +/// # use std::fmt; +/// # #[allow(dead_code)] +/// # struct Example; +/// # impl Visitor for Example { +/// # type Value = (); +/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> +/// where E: Error +/// { +/// Err(Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # } +/// ``` +/// +/// Outside of a `Visitor`, `&"..."` can be used. +/// +/// ```rust +/// # use serde::de::{Error, Unexpected}; +/// # #[allow(dead_code)] +/// # fn example<E: Error>() -> Result<(), E> { +/// # let v = true; +/// return Err(Error::invalid_type(Unexpected::Bool(v), &"a negative integer")); +/// # } +/// ``` +pub trait Expected { + /// Format an explanation of what data was being expected. Same signature as + /// the `Display` and `Debug` traits. + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result; +} + +impl<T> Expected for T + where T: Visitor +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.expecting(formatter) + } +} + +impl<'a> Expected for &'a str { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self) + } +} + +impl<'a> Display for Expected + 'a { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Expected::fmt(self, formatter) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be deserialized from any data format supported +/// by Serde. +/// +/// Serde provides `Deserialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][de]. All of these can +/// be deserialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called `serde_derive` to +/// automatically generate `Deserialize` implementations for structs and enums +/// in your program. See the [codegen section of the manual][codegen] for how to +/// use this. +/// +/// In rare cases it may be necessary to implement `Deserialize` manually for +/// some type in your program. See the [Implementing +/// `Deserialize`][impl-deserialize] section of the manual for more about this. +/// +/// Third-party crates may provide `Deserialize` implementations for types that +/// they expose. For example the `linked-hash-map` crate provides a +/// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate +/// provides an implementation of `Deserialize` for it. +/// +/// [de]: https://docs.serde.rs/serde/de/index.html +/// [codegen]: https://serde.rs/codegen.html +/// [impl-deserialize]: https://serde.rs/impl-deserialize.html +pub trait Deserialize: Sized { + /// Deserialize this value from the given Serde deserializer. + /// + /// See the [Implementing `Deserialize`][impl-deserialize] section of the + /// manual for more information about how to implement this method. + /// + /// [impl-deserialize]: https://serde.rs/impl-deserialize.html + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer; +} + +/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you +/// ever find yourself looking for a way to pass data into a `Deserialize` impl, +/// this trait is the way to do it. +/// +/// As one example of stateful deserialization consider deserializing a JSON +/// array into an existing buffer. Using the `Deserialize` trait we could +/// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated +/// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated +/// buffer. Using `DeserializeSeed` instead makes this possible as in the +/// example code below. +/// +/// The canonical API for stateless deserialization looks like this: +/// +/// ```rust +/// # use serde::Deserialize; +/// # #[allow(dead_code)] +/// # enum Error {} +/// # #[allow(dead_code)] +/// fn func<T: Deserialize>() -> Result<T, Error> +/// # { unimplemented!() } +/// ``` +/// +/// Adjusting an API like this to support stateful deserialization is a matter +/// of accepting a seed as input: +/// +/// ```rust +/// # use serde::de::DeserializeSeed; +/// # #[allow(dead_code)] +/// # enum Error {} +/// # #[allow(dead_code)] +/// fn func_seed<T: DeserializeSeed>(seed: T) -> Result<T::Value, Error> +/// # { +/// # let _ = seed; +/// # unimplemented!() +/// # } +/// ``` +/// +/// In practice the majority of deserialization is stateless. An API expecting a +/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the +/// case of stateless deserialization. +/// +/// # Example +/// +/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need +/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`. +/// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we +/// would like to allocate a single `Vec<T>` and then deserialize each subarray +/// into it. This requires stateful deserialization using the `DeserializeSeed` +/// trait. +/// +/// ```rust +/// # use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor}; +/// # use std::fmt; +/// # use std::marker::PhantomData; +/// # +/// // A DeserializeSeed implementation that uses stateful deserialization to +/// // append array elements onto the end of an existing vector. The preexisting +/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of +/// // `ExtendVec` will be traversing the inner arrays of the JSON input and +/// // appending each integer into the existing Vec. +/// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>); +/// +/// impl<'a, T> DeserializeSeed for ExtendVec<'a, T> +/// where T: Deserialize +/// { +/// // The return type of the `deserialize` method. This implementation +/// // appends onto an existing vector but does not create any new data +/// // structure, so the return type is (). +/// type Value = (); +/// +/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> +/// where D: Deserializer +/// { +/// // Visitor implementation that will walk an inner array of the JSON +/// // input. +/// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>); +/// +/// impl<'a, T> Visitor for ExtendVecVisitor<'a, T> +/// where T: Deserialize +/// { +/// type Value = (); +/// +/// fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error> +/// where V: SeqVisitor +/// { +/// // Visit each element in the inner array and push it onto +/// // the existing vector. +/// while let Some(elem) = visitor.visit()? { +/// self.0.push(elem); +/// } +/// Ok(()) +/// } +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "an array of integers") +/// # } +/// } +/// +/// deserializer.deserialize_seq(ExtendVecVisitor(self.0)) +/// } +/// } +/// +/// // Visitor implementation that will walk the outer array of the JSON input. +/// struct FlattenedVecVisitor<T>(PhantomData<T>); +/// +/// impl<T> Visitor for FlattenedVecVisitor<T> +/// where T: Deserialize +/// { +/// // This Visitor constructs a single Vec<T> to hold the flattened +/// // contents of the inner arrays. +/// type Value = Vec<T>; +/// +/// fn visit_seq<V>(self, mut visitor: V) -> Result<Vec<T>, V::Error> +/// where V: SeqVisitor +/// { +/// // Create a single Vec to hold the flattened contents. +/// let mut vec = Vec::new(); +/// +/// // Each iteration through this loop is one inner array. +/// while let Some(()) = visitor.visit_seed(ExtendVec(&mut vec))? { +/// // Nothing to do; inner array has been appended into `vec`. +/// } +/// +/// // Return the finished vec. +/// Ok(vec) +/// } +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "an array of arrays") +/// # } +/// } +/// +/// # #[allow(dead_code)] +/// # fn example<D: Deserializer>(deserializer: D) -> Result<(), D::Error> { +/// let visitor = FlattenedVecVisitor(PhantomData); +/// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?; +/// # let _ = flattened; +/// # Ok(()) } +/// ``` +pub trait DeserializeSeed: Sized { + /// The type produced by using this seed. + type Value; + + /// Equivalent to the more common `Deserialize::deserialize` method, except + /// with some initial piece of data (the seed) passed in. + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer; +} + +impl<T> DeserializeSeed for PhantomData<T> + where T: Deserialize +{ + type Value = T; + + #[inline] + fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error> + where D: Deserializer + { + T::deserialize(deserializer) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can deserialize any data structure supported by +/// Serde. +/// +/// The role of this trait is to define the deserialization half of the Serde +/// data model, which is a way to categorize every Rust data type into one of 28 +/// possible types. Each method of the `Serializer` trait corresponds to one of +/// the types of the data model. +/// +/// Implementations of `Deserialize` map themselves into this data model by +/// passing to the `Deserializer` a `Visitor` implementation that can receive +/// these various types. +/// +/// The types that make up the Serde data model are: +/// +/// - 12 primitive types: +/// - bool +/// - i8, i16, i32, i64 +/// - u8, u16, u32, u64 +/// - f32, f64 +/// - char +/// - string +/// - byte array - [u8] +/// - option +/// - either none or some value +/// - unit +/// - unit is the type of () in Rust +/// - unit_struct +/// - for example `struct Unit` or `PhantomData<T>` +/// - unit_variant +/// - the `E::A` and `E::B` in `enum E { A, B }` +/// - newtype_struct +/// - for example `struct Millimeters(u8)` +/// - newtype_variant +/// - the `E::N` in `enum E { N(u8) }` +/// - seq +/// - a dynamically sized sequence of values, for example `Vec<T>` or +/// `HashSet<T>` +/// - seq_fixed_size +/// - a statically sized sequence of values for which the size will be known +/// at deserialization time without looking at the serialized data, for +/// example `[u64; 10]` +/// - tuple +/// - for example `(u8,)` or `(String, u64, Vec<T>)` +/// - tuple_struct +/// - for example `struct Rgb(u8, u8, u8)` +/// - tuple_variant +/// - the `E::T` in `enum E { T(u8, u8) }` +/// - map +/// - for example `BTreeMap<K, V>` +/// - struct +/// - a key-value pairing in which the keys will be known at deserialization +/// time without looking at the serialized data, for example `struct S { r: +/// u8, g: u8, b: u8 }` +/// - struct_variant +/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }` +/// +/// The `Deserializer` trait supports two entry point styles which enables +/// different kinds of deserialization. +/// +/// 1. The `deserialize` method. Self-describing data formats like JSON are able +/// to look at the serialized data and tell what it represents. For example +/// the JSON deserializer may see an opening curly brace (`{`) and know that +/// it is seeing a map. If the data format supports +/// `Deserializer::deserialize`, it will drive the Visitor using whatever +/// type it sees in the input. JSON uses this approach when deserializing +/// `serde_json::Value` which is an enum that can represent any JSON +/// document. Without knowing what is in a JSON document, we can deserialize +/// it to `serde_json::Value` by going through `Deserializer::deserialize`. +/// +/// 2. The various `deserialize_*` methods. Non-self-describing formats like +/// Bincode need to be told what is in the input in order to deserialize it. +/// The `deserialize_*` methods are hints to the deserializer for how to +/// interpret the next piece of input. Non-self-describing formats are not +/// able to deserialize something like `serde_json::Value` which relies on +/// `Deserializer::deserialize`. +/// +/// When implementing `Deserialize`, you should avoid relying on +/// `Deserializer::deserialize` unless you need to be told by the Deserializer +/// what type is in the input. Know that relying on `Deserializer::deserialize` +/// means your data type will be able to deserialize from self-describing +/// formats only, ruling out Bincode and many others. +pub trait Deserializer: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// Require the `Deserializer` to figure out how to drive the visitor based + /// on what data type is in the input. + /// + /// When implementing `Deserialize`, you should avoid relying on + /// `Deserializer::deserialize` unless you need to be told by the + /// Deserializer what type is in the input. Know that relying on + /// `Deserializer::deserialize` means your data type will be able to + /// deserialize from self-describing formats only, ruling out Bincode and + /// many others. + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `bool` value. + fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `u8` value. + fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `u16` value. + fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `u32` value. + fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `u64` value. + fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting an `i8` value. + fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting an `i16` value. + fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting an `i32` value. + fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting an `i64` value. + fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `f32` value. + fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `f64` value. + fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a `char` value. + fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a string value and does + /// not benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `String` data, + /// indiciate this to the `Deserializer` by using `deserialize_string` + /// instead. + fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a string value and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `String` + /// data, indicate that to the `Deserializer` by using `deserialize_str` + /// instead. + fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a byte array and does not + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data, + /// indicate this to the `Deserializer` by using `deserialize_byte_buf` + /// instead. + fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a byte array and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>` + /// data, indicate that to the `Deserializer` by using `deserialize_bytes` + /// instead. + fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting an optional value. + /// + /// This allows deserializers that encode an optional value as a nullable + /// value to convert the null value into `None` and a regular value into + /// `Some(value)`. + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a unit value. + fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a unit struct with a + /// particular name. + fn deserialize_unit_struct<V>(self, + name: &'static str, + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a newtype struct with a + /// particular name. + fn deserialize_newtype_struct<V>(self, + name: &'static str, + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a sequence of values. + fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a sequence of values and + /// knows how many values there are without looking at the serialized data. + fn deserialize_seq_fixed_size<V>(self, + len: usize, + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a tuple value with a + /// particular number of elements. + fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a tuple struct with a + /// particular name and number of fields. + fn deserialize_tuple_struct<V>(self, + name: &'static str, + len: usize, + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a map of key-value pairs. + fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor; + + /// Hint that the `Deserialize` type is expecting a struct with a particular + /// name and fields. + fn deserialize_struct<V>(self, + name: &'static str, + fields: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting the name of a struct + /// field. + fn deserialize_struct_field<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type is expecting an enum value with a + /// particular name and possible variants. + fn deserialize_enum<V>(self, + name: &'static str, + variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Hint that the `Deserialize` type needs to deserialize a value whose type + /// doesn't matter because it is ignored. + /// + /// Deserializers for non-self-describing formats may not support this mode. + fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor; +} + +/////////////////////////////////////////////////////////////////////////////// + +/// This trait represents a visitor that walks through a deserializer. +/// +/// ```rust +/// # use serde::de::{Error, Unexpected, Visitor}; +/// # use std::fmt; +/// /// A visitor that deserializes a long string - a string containing at least +/// /// some minimum number of bytes. +/// # #[allow(dead_code)] +/// struct LongString { +/// min: usize, +/// } +/// +/// impl Visitor for LongString { +/// type Value = String; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "a string containing at least {} bytes", self.min) +/// } +/// +/// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> +/// where E: Error +/// { +/// if s.len() >= self.min { +/// Ok(s.to_owned()) +/// } else { +/// Err(Error::invalid_value(Unexpected::Str(s), &self)) +/// } +/// } +/// } +/// ``` +pub trait Visitor: Sized { + /// The value produced by this visitor. + type Value; + + /// Format a message stating what data this Visitor expects to receive. + /// + /// This is used in error messages. The message should complete the sentence + /// "This Visitor expects to receive ...", for example the message could be + /// "an integer between 0 and 64". The message should not be capitalized and + /// should not end with a period. + /// + /// ```rust + /// # use std::fmt; + /// # #[allow(dead_code)] + /// # struct S { max: usize } + /// # impl serde::de::Visitor for S { + /// # type Value = (); + /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// write!(formatter, "an integer between 0 and {}", self.max) + /// } + /// # } + /// ``` + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result; + + /// Deserialize a `bool` into a `Value`. + fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Bool(v), &self)) + } + + /// Deserialize an `i8` into a `Value`. + fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E> + where E: Error + { + self.visit_i64(v as i64) + } + + /// Deserialize an `i16` into a `Value`. + fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E> + where E: Error + { + self.visit_i64(v as i64) + } + + /// Deserialize an `i32` into a `Value`. + fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E> + where E: Error + { + self.visit_i64(v as i64) + } + + /// Deserialize an `i64` into a `Value`. + fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Signed(v), &self)) + } + + /// Deserialize a `u8` into a `Value`. + fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E> + where E: Error + { + self.visit_u64(v as u64) + } + + /// Deserialize a `u16` into a `Value`. + fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E> + where E: Error + { + self.visit_u64(v as u64) + } + + /// Deserialize a `u32` into a `Value`. + fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E> + where E: Error + { + self.visit_u64(v as u64) + } + + /// Deserialize a `u64` into a `Value`. + fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Unsigned(v), &self)) + } + + /// Deserialize a `f32` into a `Value`. + fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E> + where E: Error + { + self.visit_f64(v as f64) + } + + /// Deserialize a `f64` into a `Value`. + fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Float(v), &self)) + } + + /// Deserialize a `char` into a `Value`. + #[inline] + fn visit_char<E>(self, v: char) -> Result<Self::Value, E> + where E: Error + { + self.visit_str(::utils::encode_utf8(v).as_str()) + } + + /// Deserialize a `&str` into a `Value`. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_str` rather than + /// `Deserializer::deserialize_string`. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Str(v), &self)) + } + + /// Deserialize a `String` into a `Value`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a string created by the `Deserializer`. `Deserialize` implementations + /// that benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_string` rather + /// than `Deserializer::deserialize_str`, although not every deserializer + /// will honor such a request. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + /// + /// The default implementation forwards to `visit_str` and then drops the + /// `String`. + #[inline] + #[cfg(any(feature = "std", feature = "collections"))] + fn visit_string<E>(self, v: String) -> Result<Self::Value, E> + where E: Error + { + self.visit_str(&v) + } + + /// Deserialize a `()` into a `Value`. + fn visit_unit<E>(self) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Unit, &self)) + } + + /// Deserialize an absent optional `Value`. + fn visit_none<E>(self) -> Result<Self::Value, E> + where E: Error + { + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// Deserialize a present optional `Value`. + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// Deserialize `Value` as a newtype struct. + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: Deserializer + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::NewtypeStruct, &self)) + } + + /// Deserialize `Value` as a sequence of elements. + fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where V: SeqVisitor + { + let _ = visitor; + Err(Error::invalid_type(Unexpected::Seq, &self)) + } + + /// Deserialize `Value` as a key-value map. + fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where V: MapVisitor + { + let _ = visitor; + Err(Error::invalid_type(Unexpected::Map, &self)) + } + + /// Deserialize `Value` as an enum. + fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where V: EnumVisitor + { + let _ = visitor; + Err(Error::invalid_type(Unexpected::Enum, &self)) + } + + /// Deserialize a `&[u8]` into a `Value`. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `Vec<u8>` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_bytes` rather + /// than `Deserializer::deserialize_byte_buf`. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> + where E: Error + { + let _ = v; + Err(Error::invalid_type(Unexpected::Bytes(v), &self)) + } + + /// Deserialize a `Vec<u8>` into a `Value`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a byte buffer created by the `Deserializer`. `Deserialize` + /// implementations that benefit from taking ownership of `Vec<u8>` data + /// should indicate that to the deserializer by using + /// `Deserializer::deserialize_byte_buf` rather than + /// `Deserializer::deserialize_bytes`, although not every deserializer will + /// honor such a request. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + /// + /// The default implementation forwards to `visit_bytes` and then drops the + /// `Vec<u8>`. + #[cfg(any(feature = "std", feature = "collections"))] + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> + where E: Error + { + self.visit_bytes(&v) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// `SeqVisitor` visits each item in a sequence. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation, +/// which deserializes each item in a sequence. +pub trait SeqVisitor { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// `Deserialize` implementations should typically use `SeqVisitor::visit` + /// instead. + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: DeserializeSeed; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `SeqVisitor` implementations should not override the default behavior. + #[inline] + fn visit<T>(&mut self) -> Result<Option<T>, Self::Error> + where T: Deserialize + { + self.visit_seed(PhantomData) + } + + /// Return the lower and upper bound of items remaining in the sequence. + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (0, None) + } +} + +impl<'a, V> SeqVisitor for &'a mut V + where V: SeqVisitor +{ + type Error = V::Error; + + #[inline] + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, V::Error> + where T: DeserializeSeed + { + (**self).visit_seed(seed) + } + + #[inline] + fn visit<T>(&mut self) -> Result<Option<T>, V::Error> + where T: Deserialize + { + (**self).visit() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (**self).size_hint() + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// `MapVisitor` visits each item in a sequence. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation. +pub trait MapVisitor { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// `Deserialize` implementations should typically use + /// `MapVisitor::visit_key` or `MapVisitor::visit` instead. + fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> + where K: DeserializeSeed; + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// `Deserialize` implementations should typically use + /// `MapVisitor::visit_value` instead. + fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> + where V: DeserializeSeed; + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// `MapVisitor` implementations should override the default behavior if a + /// more efficient implementation is possible. + /// + /// `Deserialize` implementations should typically use `MapVisitor::visit` + /// instead. + #[inline] + fn visit_seed<K, V>(&mut self, + kseed: K, + vseed: V) + -> Result<Option<(K::Value, V::Value)>, Self::Error> + where K: DeserializeSeed, + V: DeserializeSeed + { + match try!(self.visit_key_seed(kseed)) { + Some(key) => { + let value = try!(self.visit_value_seed(vseed)); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapVisitor` implementations should not override the default behavior. + #[inline] + fn visit_key<K>(&mut self) -> Result<Option<K>, Self::Error> + where K: Deserialize + { + self.visit_key_seed(PhantomData) + } + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapVisitor` implementations should not override the default behavior. + #[inline] + fn visit_value<V>(&mut self) -> Result<V, Self::Error> + where V: Deserialize + { + self.visit_value_seed(PhantomData) + } + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapVisitor` implementations should not override the default behavior. + #[inline] + fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> + where K: Deserialize, + V: Deserialize + { + self.visit_seed(PhantomData, PhantomData) + } + + /// Return the lower and upper bound of items remaining in the sequence. + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (0, None) + } +} + +impl<'a, V_> MapVisitor for &'a mut V_ + where V_: MapVisitor +{ + type Error = V_::Error; + + #[inline] + fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> + where K: DeserializeSeed + { + (**self).visit_key_seed(seed) + } + + #[inline] + fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> + where V: DeserializeSeed + { + (**self).visit_value_seed(seed) + } + + #[inline] + fn visit_seed<K, V>(&mut self, + kseed: K, + vseed: V) + -> Result<Option<(K::Value, V::Value)>, Self::Error> + where K: DeserializeSeed, + V: DeserializeSeed + { + (**self).visit_seed(kseed, vseed) + } + + #[inline] + fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error> + where K: Deserialize, + V: Deserialize + { + (**self).visit() + } + + #[inline] + fn visit_key<K>(&mut self) -> Result<Option<K>, V_::Error> + where K: Deserialize + { + (**self).visit_key() + } + + #[inline] + fn visit_value<V>(&mut self) -> Result<V, V_::Error> + where V: Deserialize + { + (**self).visit_value() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (**self).size_hint() + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// `EnumVisitor` is a visitor that is created by the `Deserializer` and passed +/// to the `Deserialize` in order to identify which variant of an enum to +/// deserialize. +pub trait EnumVisitor: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + /// The `Visitor` that will be used to deserialize the content of the enum + /// variant. + type Variant: VariantVisitor<Error = Self::Error>; + + /// `visit_variant` is called to identify which variant to deserialize. + /// + /// `Deserialize` implementations should typically use + /// `EnumVisitor::visit_variant` instead. + fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where V: DeserializeSeed; + + /// `visit_variant` is called to identify which variant to deserialize. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `EnumVisitor` implementations should not override the default behavior. + #[inline] + fn visit_variant<V>(self) -> Result<(V, Self::Variant), Self::Error> + where V: Deserialize + { + self.visit_variant_seed(PhantomData) + } +} + +/// `VariantVisitor` is a visitor that is created by the `Deserializer` and +/// passed to the `Deserialize` to deserialize the content of a particular enum +/// variant. +pub trait VariantVisitor: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. Must match the error type of our `EnumVisitor`. + type Error: Error; + + /// Called when deserializing a variant with no values. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust,ignore + /// fn visit_unit(self) -> Result<(), Self::Error> { + /// // What the data actually contained; suppose it is a tuple variant. + /// let unexp = Unexpected::TupleVariant; + /// Err(de::Error::invalid_type(unexp, &"unit variant")) + /// } + /// ``` + fn visit_unit(self) -> Result<(), Self::Error>; + + /// Called when deserializing a variant with a single value. + /// + /// `Deserialize` implementations should typically use + /// `VariantVisitor::visit_newtype` instead. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust,ignore + /// fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> + /// where T: de::DeserializeSeed + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"newtype variant")) + /// } + /// ``` + fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> + where T: DeserializeSeed; + + /// Called when deserializing a variant with a single value. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `VariantVisitor` implementations should not override the default + /// behavior. + #[inline] + fn visit_newtype<T>(self) -> Result<T, Self::Error> + where T: Deserialize + { + self.visit_newtype_seed(PhantomData) + } + + /// Called when deserializing a tuple-like variant. + /// + /// The `len` is the number of fields expected in the tuple variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust,ignore + /// fn visit_tuple<V>(self, + /// _len: usize, + /// _visitor: V) -> Result<V::Value, Self::Error> + /// where V: Visitor + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(Error::invalid_type(unexp, &"tuple variant")) + /// } + /// ``` + fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where V: Visitor; + + /// Called when deserializing a struct-like variant. + /// + /// The `fields` are the names of the fields of the struct variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust,ignore + /// fn visit_struct<V>(self, + /// _fields: &'static [&'static str], + /// _visitor: V) -> Result<V::Value, Self::Error> + /// where V: Visitor + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(Error::invalid_type(unexp, &"struct variant")) + /// } + /// ``` + fn visit_struct<V>(self, + fields: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: Visitor; +} + +/////////////////////////////////////////////////////////////////////////////// + +/// Used in error messages. +/// +/// - expected `a` +/// - expected `a` or `b` +/// - expected one of `a`, `b`, `c` +/// +/// The slice of names must not be empty. +struct OneOf { + names: &'static [&'static str], +} + +impl Display for OneOf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.names.len() { + 0 => panic!(), // special case elsewhere + 1 => write!(formatter, "`{}`", self.names[0]), + 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]), + _ => { + try!(write!(formatter, "one of ")); + for (i, alt) in self.names.iter().enumerate() { + if i > 0 { + try!(write!(formatter, ", ")); + } + try!(write!(formatter, "`{}`", alt)); + } + Ok(()) + } + } + } +} diff --git a/bash-5.1/vendor/serde/src/de/private.rs b/bash-5.1/vendor/serde/src/de/private.rs new file mode 100644 index 0000000..092d66a --- /dev/null +++ b/bash-5.1/vendor/serde/src/de/private.rs @@ -0,0 +1,44 @@ +use core::marker::PhantomData; + +use de::{Deserialize, Deserializer, Error, Visitor}; + +#[cfg(any(feature = "std", feature = "collections"))] +pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor, + TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor, + UntaggedUnitVisitor}; + +/// If the missing field is of type `Option<T>` then treat is as `None`, +/// otherwise it is an error. +pub fn missing_field<V, E>(field: &'static str) -> Result<V, E> + where V: Deserialize, + E: Error +{ + struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>); + + impl<E> Deserializer for MissingFieldDeserializer<E> + where E: Error + { + type Error = E; + + fn deserialize<V>(self, _visitor: V) -> Result<V::Value, E> + where V: Visitor + { + Err(Error::missing_field(self.0)) + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E> + where V: Visitor + { + visitor.visit_none() + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } + } + + let deserializer = MissingFieldDeserializer(field, PhantomData); + Deserialize::deserialize(deserializer) +} diff --git a/bash-5.1/vendor/serde/src/de/value.rs b/bash-5.1/vendor/serde/src/de/value.rs new file mode 100644 index 0000000..00f32d6 --- /dev/null +++ b/bash-5.1/vendor/serde/src/de/value.rs @@ -0,0 +1,1107 @@ +//! This module supports deserializing from primitives with the `ValueDeserializer` trait. + +#[cfg(feature = "std")] +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map, btree_set, hash_map, + hash_set}; +#[cfg(feature = "std")] +use std::borrow::Cow; +#[cfg(feature = "std")] +use std::vec; + +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::{BTreeMap, BTreeSet, Vec, String, btree_map, btree_set, vec}; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::borrow::Cow; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::boxed::Box; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::string::ToString; + +#[cfg(feature = "std")] +use core::hash::Hash; +#[cfg(feature = "std")] +use std::error; +#[cfg(not(feature = "std"))] +use error; + +use core::fmt::{self, Display}; +use core::iter::{self, Iterator}; +use core::marker::PhantomData; + +use de::{self, Expected, SeqVisitor}; +use bytes; + +/////////////////////////////////////////////////////////////////////////////// + +/// This represents all the possible errors that can occur using the `ValueDeserializer`. +#[derive(Clone, Debug, PartialEq)] +pub struct Error { + err: ErrorImpl, +} + +#[cfg(any(feature = "std", feature = "collections"))] +type ErrorImpl = Box<str>; +#[cfg(not(any(feature = "std", feature = "collections")))] +type ErrorImpl = (); + +impl de::Error for Error { + #[cfg(any(feature = "std", feature = "collections"))] + fn custom<T: Display>(msg: T) -> Self { + Error { err: msg.to_string().into_boxed_str() } + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn custom<T: Display>(_msg: T) -> Self { + Error { err: () } + } +} + +impl Display for Error { + #[cfg(any(feature = "std", feature = "collections"))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + formatter.write_str(&self.err) + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + formatter.write_str("Serde deserialization error") + } +} + +impl error::Error for Error { + #[cfg(any(feature = "std", feature = "collections"))] + fn description(&self) -> &str { + &self.err + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn description(&self) -> &str { + "Serde deserialization error" + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// This trait converts primitive types into a deserializer. +pub trait ValueDeserializer<E: de::Error = Error> { + /// The actual deserializer type. + type Deserializer: de::Deserializer<Error = E>; + + /// Convert this value into a deserializer. + fn into_deserializer(self) -> Self::Deserializer; +} + +/////////////////////////////////////////////////////////////////////////////// + +impl<E> ValueDeserializer<E> for () + where E: de::Error +{ + type Deserializer = UnitDeserializer<E>; + + fn into_deserializer(self) -> UnitDeserializer<E> { + UnitDeserializer { marker: PhantomData } + } +} + +/// A helper deserializer that deserializes a `()`. +pub struct UnitDeserializer<E> { + marker: PhantomData<E>, +} + +impl<E> de::Deserializer for UnitDeserializer<E> + where E: de::Error +{ + type Error = E; + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes map unit_struct newtype_struct tuple_struct struct + struct_field tuple enum ignored_any byte_buf + } + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_unit() + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_none() + } +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_deserializer { + ($ty:ty, $name:ident, $method:ident $($cast:tt)*) => { + /// A helper deserializer that deserializes a number. + pub struct $name<E> { + value: $ty, + marker: PhantomData<E> + } + + impl<E> ValueDeserializer<E> for $ty + where E: de::Error, + { + type Deserializer = $name<E>; + + fn into_deserializer(self) -> $name<E> { + $name { + value: self, + marker: PhantomData, + } + } + } + + impl<E> de::Deserializer for $name<E> + where E: de::Error, + { + type Error = E; + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit + option seq seq_fixed_size bytes map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any byte_buf + } + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor, + { + visitor.$method(self.value $($cast)*) + } + } + } +} + +primitive_deserializer!(bool, BoolDeserializer, visit_bool); +primitive_deserializer!(i8, I8Deserializer, visit_i8); +primitive_deserializer!(i16, I16Deserializer, visit_i16); +primitive_deserializer!(i32, I32Deserializer, visit_i32); +primitive_deserializer!(i64, I64Deserializer, visit_i64); +primitive_deserializer!(isize, IsizeDeserializer, visit_i64 as i64); +primitive_deserializer!(u8, U8Deserializer, visit_u8); +primitive_deserializer!(u16, U16Deserializer, visit_u16); +primitive_deserializer!(u64, U64Deserializer, visit_u64); +primitive_deserializer!(usize, UsizeDeserializer, visit_u64 as u64); +primitive_deserializer!(f32, F32Deserializer, visit_f32); +primitive_deserializer!(f64, F64Deserializer, visit_f64); +primitive_deserializer!(char, CharDeserializer, visit_char); + +/// A helper deserializer that deserializes a number. +pub struct U32Deserializer<E> { + value: u32, + marker: PhantomData<E>, +} + +impl<E> ValueDeserializer<E> for u32 + where E: de::Error +{ + type Deserializer = U32Deserializer<E>; + + fn into_deserializer(self) -> U32Deserializer<E> { + U32Deserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<E> de::Deserializer for U32Deserializer<E> + where E: de::Error +{ + type Error = E; + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple ignored_any byte_buf + } + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_u32(self.value) + } + + fn deserialize_enum<V>(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_enum(self) + } +} + +impl<E> de::EnumVisitor for U32Deserializer<E> + where E: de::Error +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where T: de::DeserializeSeed + { + seed.deserialize(self).map(private::unit_only) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a `&str`. +pub struct StrDeserializer<'a, E> { + value: &'a str, + marker: PhantomData<E>, +} + +impl<'a, E> ValueDeserializer<E> for &'a str + where E: de::Error +{ + type Deserializer = StrDeserializer<'a, E>; + + fn into_deserializer(self) -> StrDeserializer<'a, E> { + StrDeserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<'a, E> de::Deserializer for StrDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_str(self.value) + } + + fn deserialize_enum<V>(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_enum(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple ignored_any byte_buf + } +} + +impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where T: de::DeserializeSeed + { + seed.deserialize(self).map(private::unit_only) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a `String`. +#[cfg(any(feature = "std", feature = "collections"))] +pub struct StringDeserializer<E> { + value: String, + marker: PhantomData<E>, +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<E> ValueDeserializer<E> for String + where E: de::Error +{ + type Deserializer = StringDeserializer<E>; + + fn into_deserializer(self) -> StringDeserializer<E> { + StringDeserializer { + value: self, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<E> de::Deserializer for StringDeserializer<E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_string(self.value) + } + + fn deserialize_enum<V>(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_enum(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple ignored_any byte_buf + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a, E> de::EnumVisitor for StringDeserializer<E> + where E: de::Error +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where T: de::DeserializeSeed + { + seed.deserialize(self).map(private::unit_only) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a `String`. +#[cfg(any(feature = "std", feature = "collections"))] +pub struct CowStrDeserializer<'a, E> { + value: Cow<'a, str>, + marker: PhantomData<E>, +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a, E> ValueDeserializer<E> for Cow<'a, str> + where E: de::Error +{ + type Deserializer = CowStrDeserializer<'a, E>; + + fn into_deserializer(self) -> CowStrDeserializer<'a, E> { + CowStrDeserializer { + value: self, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + match self.value { + Cow::Borrowed(string) => visitor.visit_str(string), + Cow::Owned(string) => visitor.visit_string(string), + } + } + + fn deserialize_enum<V>(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_enum(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple ignored_any byte_buf + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where T: de::DeserializeSeed + { + seed.deserialize(self).map(private::unit_only) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a sequence. +pub struct SeqDeserializer<I, E> { + iter: iter::Fuse<I>, + count: usize, + marker: PhantomData<E>, +} + +impl<I, E> SeqDeserializer<I, E> + where I: Iterator, + E: de::Error +{ + /// Construct a new `SeqDeserializer<I>`. + pub fn new(iter: I) -> Self { + SeqDeserializer { + iter: iter.fuse(), + count: 0, + marker: PhantomData, + } + } + + /// Check for remaining elements after passing a `SeqDeserializer` to + /// `Visitor::visit_seq`. + pub fn end(mut self) -> Result<(), E> { + let mut remaining = 0; + while self.iter.next().is_some() { + remaining += 1; + } + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(self.count + remaining, &ExpectedInSeq(self.count))) + } + } +} + +impl<I, T, E> de::Deserializer for SeqDeserializer<I, E> + where I: Iterator<Item = T>, + T: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + let v = try!(visitor.visit_seq(&mut self)); + try!(self.end()); + Ok(v) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple enum ignored_any byte_buf + } +} + +impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E> + where I: Iterator<Item = T>, + T: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + fn visit_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error> + where V: de::DeserializeSeed + { + match self.iter.next() { + Some(value) => { + self.count += 1; + seed.deserialize(value.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +struct ExpectedInSeq(usize); + +impl Expected for ExpectedInSeq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + write!(formatter, "1 element in sequence") + } else { + write!(formatter, "{} elements in sequence", self.0) + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T, E> ValueDeserializer<E> for Vec<T> + where T: ValueDeserializer<E>, + E: de::Error +{ + type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T, E> ValueDeserializer<E> for BTreeSet<T> + where T: ValueDeserializer<E> + Eq + Ord, + E: de::Error +{ + type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +impl<T, E> ValueDeserializer<E> for HashSet<T> + where T: ValueDeserializer<E> + Eq + Hash, + E: de::Error +{ + type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a sequence using a `SeqVisitor`. +pub struct SeqVisitorDeserializer<V_, E> { + visitor: V_, + marker: PhantomData<E>, +} + +impl<V_, E> SeqVisitorDeserializer<V_, E> + where V_: de::SeqVisitor<Error = E>, + E: de::Error +{ + /// Construct a new `SeqVisitorDeserializer<V_, E>`. + pub fn new(visitor: V_) -> Self { + SeqVisitorDeserializer { + visitor: visitor, + marker: PhantomData, + } + } +} + +impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E> + where V_: de::SeqVisitor<Error = E>, + E: de::Error +{ + type Error = E; + + fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> { + visitor.visit_seq(self.visitor) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple enum ignored_any byte_buf + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a map. +pub struct MapDeserializer<I, E> + where I: Iterator, + I::Item: private::Pair, + <I::Item as private::Pair>::First: ValueDeserializer<E>, + <I::Item as private::Pair>::Second: ValueDeserializer<E>, + E: de::Error +{ + iter: iter::Fuse<I>, + value: Option<<I::Item as private::Pair>::Second>, + count: usize, + marker: PhantomData<E>, +} + +impl<I, E> MapDeserializer<I, E> + where I: Iterator, + I::Item: private::Pair, + <I::Item as private::Pair>::First: ValueDeserializer<E>, + <I::Item as private::Pair>::Second: ValueDeserializer<E>, + E: de::Error +{ + /// Construct a new `MapDeserializer<I, K, V, E>`. + pub fn new(iter: I) -> Self { + MapDeserializer { + iter: iter.fuse(), + value: None, + count: 0, + marker: PhantomData, + } + } + + /// Check for remaining elements after passing a `MapDeserializer` to + /// `Visitor::visit_map`. + pub fn end(mut self) -> Result<(), E> { + let mut remaining = 0; + while self.iter.next().is_some() { + remaining += 1; + } + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(self.count + remaining, &ExpectedInMap(self.count))) + } + } + + fn next_pair + (&mut self) + -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> { + match self.iter.next() { + Some(kv) => { + self.count += 1; + Some(private::Pair::split(kv)) + } + None => None, + } + } +} + +impl<I, E> de::Deserializer for MapDeserializer<I, E> + where I: Iterator, + I::Item: private::Pair, + <I::Item as private::Pair>::First: ValueDeserializer<E>, + <I::Item as private::Pair>::Second: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error> + where V_: de::Visitor + { + let value = try!(visitor.visit_map(&mut self)); + try!(self.end()); + Ok(value) + } + + fn deserialize_seq<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error> + where V_: de::Visitor + { + let value = try!(visitor.visit_seq(&mut self)); + try!(self.end()); + Ok(value) + } + + fn deserialize_seq_fixed_size<V_>(self, + _len: usize, + visitor: V_) + -> Result<V_::Value, Self::Error> + where V_: de::Visitor + { + self.deserialize_seq(visitor) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + bytes map unit_struct newtype_struct tuple_struct struct struct_field + tuple enum ignored_any byte_buf + } +} + +impl<I, E> de::MapVisitor for MapDeserializer<I, E> + where I: Iterator, + I::Item: private::Pair, + <I::Item as private::Pair>::First: ValueDeserializer<E>, + <I::Item as private::Pair>::Second: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + match self.next_pair() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where T: de::DeserializeSeed + { + let value = self.value.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let value = value.expect("MapVisitor::visit_value called before visit_key"); + seed.deserialize(value.into_deserializer()) + } + + fn visit_seed<TK, TV>(&mut self, + kseed: TK, + vseed: TV) + -> Result<Option<(TK::Value, TV::Value)>, Self::Error> + where TK: de::DeserializeSeed, + TV: de::DeserializeSeed + { + match self.next_pair() { + Some((key, value)) => { + let key = try!(kseed.deserialize(key.into_deserializer())); + let value = try!(vseed.deserialize(value.into_deserializer())); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +impl<I, E> de::SeqVisitor for MapDeserializer<I, E> + where I: Iterator, + I::Item: private::Pair, + <I::Item as private::Pair>::First: ValueDeserializer<E>, + <I::Item as private::Pair>::Second: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + match self.next_pair() { + Some((k, v)) => { + let de = PairDeserializer(k, v, PhantomData); + seed.deserialize(de).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +// Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a +// sequence of pairs. +struct PairDeserializer<A, B, E>(A, B, PhantomData<E>); + +impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E> + where A: ValueDeserializer<E>, + B: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + bytes map unit_struct newtype_struct tuple_struct struct struct_field + tuple enum ignored_any byte_buf + } + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + self.deserialize_seq(visitor) + } + + fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData); + let pair = try!(visitor.visit_seq(&mut pair_visitor)); + if pair_visitor.1.is_none() { + Ok(pair) + } else { + let remaining = pair_visitor.size_hint().0; + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) + } + } + + fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + if len == 2 { + self.deserialize_seq(visitor) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) + } + } +} + +struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>); + +impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E> + where A: ValueDeserializer<E>, + B: ValueDeserializer<E>, + E: de::Error +{ + type Error = E; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where T: de::DeserializeSeed + { + if let Some(k) = self.0.take() { + seed.deserialize(k.into_deserializer()).map(Some) + } else if let Some(v) = self.1.take() { + seed.deserialize(v.into_deserializer()).map(Some) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + let len = if self.0.is_some() { + 2 + } else if self.1.is_some() { + 1 + } else { + 0 + }; + (len, Some(len)) + } +} + +struct ExpectedInMap(usize); + +impl Expected for ExpectedInMap { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + write!(formatter, "1 element in map") + } else { + write!(formatter, "{} elements in map", self.0) + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "collections"))] +impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V> + where K: ValueDeserializer<E> + Eq + Ord, + V: ValueDeserializer<E>, + E: de::Error +{ + type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +impl<K, V, E> ValueDeserializer<E> for HashMap<K, V> + where K: ValueDeserializer<E> + Eq + Hash, + V: ValueDeserializer<E>, + E: de::Error +{ + type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A helper deserializer that deserializes a map using a `MapVisitor`. +pub struct MapVisitorDeserializer<V_, E> { + visitor: V_, + marker: PhantomData<E>, +} + +impl<V_, E> MapVisitorDeserializer<V_, E> + where V_: de::MapVisitor<Error = E>, + E: de::Error +{ + /// Construct a new `MapVisitorDeserializer<V_, E>`. + pub fn new(visitor: V_) -> Self { + MapVisitorDeserializer { + visitor: visitor, + marker: PhantomData, + } + } +} + +impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E> + where V_: de::MapVisitor<Error = E>, + E: de::Error +{ + type Error = E; + + fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> { + visitor.visit_map(self.visitor) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple enum ignored_any byte_buf + } +} + +/////////////////////////////////////////////////////////////////////////////// + +impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a> + where E: de::Error +{ + type Deserializer = BytesDeserializer<'a, E>; + + fn into_deserializer(self) -> BytesDeserializer<'a, E> { + BytesDeserializer { + value: self.into(), + marker: PhantomData, + } + } +} + +/// A helper deserializer that deserializes a `&[u8]`. +pub struct BytesDeserializer<'a, E> { + value: &'a [u8], + marker: PhantomData<E>, +} + +impl<'a, E> de::Deserializer for BytesDeserializer<'a, E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_bytes(self.value) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple enum ignored_any byte_buf + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "collections"))] +impl<E> ValueDeserializer<E> for bytes::ByteBuf + where E: de::Error +{ + type Deserializer = ByteBufDeserializer<E>; + + fn into_deserializer(self) -> Self::Deserializer { + ByteBufDeserializer { + value: self.into(), + marker: PhantomData, + } + } +} + +/// A helper deserializer that deserializes a `Vec<u8>`. +#[cfg(any(feature = "std", feature = "collections"))] +pub struct ByteBufDeserializer<E> { + value: Vec<u8>, + marker: PhantomData<E>, +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<E> de::Deserializer for ByteBufDeserializer<E> + where E: de::Error +{ + type Error = E; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + visitor.visit_byte_buf(self.value) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct + struct struct_field tuple enum ignored_any byte_buf + } +} + +/////////////////////////////////////////////////////////////////////////////// + +mod private { + use de::{self, Unexpected}; + use core::marker::PhantomData; + + pub struct UnitOnly<E> { + marker: PhantomData<E>, + } + + pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) { + (t, UnitOnly { marker: PhantomData }) + } + + impl<E> de::VariantVisitor for UnitOnly<E> + where E: de::Error + { + type Error = E; + + fn visit_unit(self) -> Result<(), Self::Error> { + Ok(()) + } + + fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> + where T: de::DeserializeSeed + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")) + } + + fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> + where V: de::Visitor + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant")) + } + + fn visit_struct<V>(self, + _fields: &'static [&'static str], + _visitor: V) + -> Result<V::Value, Self::Error> + where V: de::Visitor + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant")) + } + } + + /// Avoid having to restate the generic types on `MapDeserializer`. The + /// `Iterator::Item` contains enough information to figure out K and V. + pub trait Pair { + type First; + type Second; + fn split(self) -> (Self::First, Self::Second); + } + + impl<A, B> Pair for (A, B) { + type First = A; + type Second = B; + fn split(self) -> (A, B) { + self + } + } +} diff --git a/bash-5.1/vendor/serde/src/error.rs b/bash-5.1/vendor/serde/src/error.rs new file mode 100644 index 0000000..fe91c28 --- /dev/null +++ b/bash-5.1/vendor/serde/src/error.rs @@ -0,0 +1,17 @@ +//! A stand-in for `std::error` +use core::fmt::{Debug, Display}; + +/// A stand-in for `std::error::Error`, which requires no allocation. +pub trait Error: Debug + Display { + /// A short description of the error. + /// + /// The description should not contain newlines or sentence-ending + /// punctuation, to facilitate embedding in larger user-facing + /// strings. + fn description(&self) -> &str; + + /// The lower-level cause of this error, if any. + fn cause(&self) -> Option<&Error> { + None + } +} diff --git a/bash-5.1/vendor/serde/src/export.rs b/bash-5.1/vendor/serde/src/export.rs new file mode 100644 index 0000000..c4fd3c6 --- /dev/null +++ b/bash-5.1/vendor/serde/src/export.rs @@ -0,0 +1,36 @@ +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::String; + +#[cfg(feature = "std")] +use std::borrow::Cow; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::borrow::Cow; + +pub use core::clone::Clone; +pub use core::convert::{From, Into}; +pub use core::default::Default; +pub use core::fmt; +pub use core::marker::PhantomData; +pub use core::option::Option::{self, None, Some}; +pub use core::result::Result::{self, Ok, Err}; + +#[cfg(any(feature = "collections", feature = "std"))] +pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> { + String::from_utf8_lossy(bytes) +} + +// The generated code calls this like: +// +// let value = &_serde::export::from_utf8_lossy(bytes); +// Err(_serde::de::Error::unknown_variant(value, VARIANTS)) +// +// so it is okay for the return type to be different from the std case as long +// as the above works. +#[cfg(not(any(feature = "collections", feature = "std")))] +pub fn from_utf8_lossy(bytes: &[u8]) -> &str { + use core::str; + // Three unicode replacement characters if it fails. They look like a + // white-on-black question mark. The user will recognize it as invalid + // UTF-8. + str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") +} diff --git a/bash-5.1/vendor/serde/src/iter.rs b/bash-5.1/vendor/serde/src/iter.rs new file mode 100644 index 0000000..784fe9b --- /dev/null +++ b/bash-5.1/vendor/serde/src/iter.rs @@ -0,0 +1,73 @@ +//! Module that contains helper iterators. + +use std::io; +use std::iter::Peekable; + +/// Iterator over a byte stream that tracks the current position's line and column. +pub struct LineColIterator<Iter: Iterator<Item = io::Result<u8>>> { + iter: Iter, + line: usize, + col: usize, +} + +impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Iter> { + /// Construct a new `LineColIterator<Iter>`. + pub fn new(iter: Iter) -> LineColIterator<Iter> { + LineColIterator { + iter: iter, + line: 1, + col: 0, + } + } + + /// Report the current line inside the iterator. + pub fn line(&self) -> usize { + self.line + } + + /// Report the current column inside the iterator. + pub fn col(&self) -> usize { + self.col + } + + /// Gets a reference to the underlying iterator. + pub fn get_ref(&self) -> &Iter { + &self.iter + } + + /// Gets a mutable reference to the underlying iterator. + pub fn get_mut(&mut self) -> &mut Iter { + &mut self.iter + } + + /// Unwraps this `LineColIterator`, returning the underlying iterator. + pub fn into_inner(self) -> Iter { + self.iter + } +} + +impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Peekable<Iter>> { + /// peeks at the next value + pub fn peek(&mut self) -> Option<&io::Result<u8>> { + self.iter.peek() + } +} + +impl<Iter: Iterator<Item = io::Result<u8>>> Iterator for LineColIterator<Iter> { + type Item = io::Result<u8>; + fn next(&mut self) -> Option<io::Result<u8>> { + match self.iter.next() { + None => None, + Some(Ok(b'\n')) => { + self.line += 1; + self.col = 0; + Some(Ok(b'\n')) + } + Some(Ok(c)) => { + self.col += 1; + Some(Ok(c)) + } + Some(Err(e)) => Some(Err(e)), + } + } +} diff --git a/bash-5.1/vendor/serde/src/lib.rs b/bash-5.1/vendor/serde/src/lib.rs new file mode 100644 index 0000000..ec11a46 --- /dev/null +++ b/bash-5.1/vendor/serde/src/lib.rs @@ -0,0 +1,155 @@ +//! # Serde +//! +//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data +//! structures efficiently and generically. +//! +//! The Serde ecosystem consists of data structures that know how to serialize +//! and deserialize themselves along with data formats that know how to +//! serialize and deserialize other things. Serde provides the layer by which +//! these two groups interact with each other, allowing any supported data +//! structure to be serialized and deserialized using any supported data format. +//! +//! See the Serde website https://serde.rs/ for additional documentation and +//! usage examples. +//! +//! ### Design +//! +//! Where many other languages rely on runtime reflection for serializing data, +//! Serde is instead built on Rust's powerful trait system. A data structure +//! that knows how to serialize and deserialize itself is one that implements +//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's code +//! generation to automatically derive implementations at compile time). This +//! avoids any overhead of reflection or runtime type information. In fact in +//! many situations the interaction between data structure and data format can +//! be completely optimized away by the Rust compiler, leaving Serde +//! serialization to perform roughly the same speed as a handwritten serializer +//! for the specific selection of data structure and data format. +//! +//! ### Data formats +//! +//! The following is a partial list of data formats that have been implemented +//! for Serde by the community. +//! +//! - [JSON](https://github.com/serde-rs/json), the ubiquitous JavaScript Object +//! Notation used by many HTTP APIs. +//! - [Bincode](https://github.com/TyOverby/bincode), a compact binary format +//! used for IPC within the Servo rendering engine. +//! - [CBOR](https://github.com/pyfisch/cbor), a Concise Binary Object +//! Representation designed for small message size without the need for +//! version negotiation. +//! - [YAML](https://github.com/dtolnay/serde-yaml), a popular human-friendly +//! configuration language that ain't markup language. +//! - [MessagePack](https://github.com/3Hren/msgpack-rust), an efficient binary +//! format that resembles a compact JSON. +//! - [TOML](https://github.com/alexcrichton/toml-rs), a minimal configuration +//! format used by [Cargo](http://doc.crates.io/manifest.html). +//! - [Pickle](https://github.com/birkenfeld/serde-pickle), a format common in +//! the Python world. +//! - [Hjson](https://github.com/laktak/hjson-rust), a variant of JSON designed +//! to be readable and writable by humans. +//! - [BSON](https://github.com/zonyitoo/bson-rs), the data storage and network +//! transfer format used by MongoDB. +//! - [URL](https://github.com/nox/serde_urlencoded), the x-www-form-urlencoded +//! format. +//! - [XML](https://github.com/serde-rs/xml), the flexible machine-friendly W3C +//! standard. *(deserialization only)* +//! - [Envy](https://github.com/softprops/envy), a way to deserialize +//! environment variables into Rust structs. *(deserialization only)* +//! - [Redis](https://github.com/OneSignal/serde-redis), deserialize values from +//! Redis when using [redis-rs](https://crates.io/crates/redis). +//! *(deserialization only)* + +#![doc(html_root_url="https://docs.serde.rs")] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(feature = "unstable", feature(nonzero, specialization, into_boxed_c_str))] +#![cfg_attr(feature = "alloc", feature(alloc))] +#![cfg_attr(feature = "collections", feature(collections))] +#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))] +#![deny(missing_docs)] + +#[cfg(feature = "collections")] +extern crate collections; + +#[cfg(feature = "alloc")] +extern crate alloc; + +#[cfg(feature = "unstable")] +extern crate core as actual_core; + +#[cfg(feature = "std")] +mod core { + pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize, + usize, f32, f64, char, str, num, slice, iter, cell, default, result, option, + clone, convert}; + #[cfg(feature = "unstable")] + pub use actual_core::nonzero; +} + +#[doc(inline)] +pub use ser::{Serialize, Serializer}; +#[doc(inline)] +pub use de::{Deserialize, Deserializer}; + +#[macro_use] +mod macros; + +pub mod bytes; +pub mod de; +#[cfg(feature = "std")] +#[doc(hidden)] +pub mod iter; +pub mod ser; +#[cfg_attr(feature = "std", doc(hidden))] +pub mod error; +mod utils; + +// Generated code uses these to support no_std. Not public API. +#[doc(hidden)] +pub mod export; + +// Re-export #[derive(Serialize, Deserialize)]. +// +// This is a workaround for https://github.com/rust-lang/cargo/issues/1286. +// Without this re-export, crates that put Serde derives behind a cfg_attr would +// need to use some silly feature name that depends on both serde and +// serde_derive. +// +// [features] +// serde-impls = ["serde", "serde_derive"] +// +// [dependencies] +// serde = { version = "1.0", optional = true } +// serde_derive = { version = "1.0", optional = true } +// +// # Used like this: +// # #[cfg(feature = "serde-impls")] +// # #[macro_use] +// # extern crate serde_derive; +// # +// # #[cfg_attr(feature = "serde-impls", derive(Serialize, Deserialize))] +// # struct S { /* ... */ } +// +// The re-exported derives allow crates to use "serde" as the name of their +// Serde feature which is more intuitive. +// +// [dependencies] +// serde = { version = "1.0", optional = true, features = ["derive"] } +// +// # Used like this: +// # #[cfg(feature = "serde")] +// # #[macro_use] +// # extern crate serde; +// # +// # #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +// # struct S { /* ... */ } +// +// The reason re-exporting is not enabled by default is that disabling it would +// be annoying for crates that provide handwritten impls or data formats. They +// would need to disable default features and then explicitly re-enable std. +#[cfg(feature = "serde_derive")] +#[allow(unused_imports)] +#[macro_use] +extern crate serde_derive; +#[cfg(feature = "serde_derive")] +#[doc(hidden)] +pub use serde_derive::*; diff --git a/bash-5.1/vendor/serde/src/macros.rs b/bash-5.1/vendor/serde/src/macros.rs new file mode 100644 index 0000000..0a83a13 --- /dev/null +++ b/bash-5.1/vendor/serde/src/macros.rs @@ -0,0 +1,207 @@ +#[doc(hidden)] +#[macro_export] +macro_rules! forward_to_deserialize_method { + ($func:ident($($arg:ty),*)) => { + #[inline] + fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> $crate::export::Result<__V::Value, Self::Error> + where __V: $crate::de::Visitor + { + self.deserialize(visitor) + } + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! forward_to_deserialize_helper { + (bool) => { + forward_to_deserialize_method!{deserialize_bool()} + }; + (u8) => { + forward_to_deserialize_method!{deserialize_u8()} + }; + (u16) => { + forward_to_deserialize_method!{deserialize_u16()} + }; + (u32) => { + forward_to_deserialize_method!{deserialize_u32()} + }; + (u64) => { + forward_to_deserialize_method!{deserialize_u64()} + }; + (i8) => { + forward_to_deserialize_method!{deserialize_i8()} + }; + (i16) => { + forward_to_deserialize_method!{deserialize_i16()} + }; + (i32) => { + forward_to_deserialize_method!{deserialize_i32()} + }; + (i64) => { + forward_to_deserialize_method!{deserialize_i64()} + }; + (f32) => { + forward_to_deserialize_method!{deserialize_f32()} + }; + (f64) => { + forward_to_deserialize_method!{deserialize_f64()} + }; + (char) => { + forward_to_deserialize_method!{deserialize_char()} + }; + (str) => { + forward_to_deserialize_method!{deserialize_str()} + }; + (string) => { + forward_to_deserialize_method!{deserialize_string()} + }; + (unit) => { + forward_to_deserialize_method!{deserialize_unit()} + }; + (option) => { + forward_to_deserialize_method!{deserialize_option()} + }; + (seq) => { + forward_to_deserialize_method!{deserialize_seq()} + }; + (seq_fixed_size) => { + forward_to_deserialize_method!{deserialize_seq_fixed_size(usize)} + }; + (bytes) => { + forward_to_deserialize_method!{deserialize_bytes()} + }; + (byte_buf) => { + forward_to_deserialize_method!{deserialize_byte_buf()} + }; + (map) => { + forward_to_deserialize_method!{deserialize_map()} + }; + (unit_struct) => { + forward_to_deserialize_method!{deserialize_unit_struct(&'static str)} + }; + (newtype_struct) => { + forward_to_deserialize_method!{deserialize_newtype_struct(&'static str)} + }; + (tuple_struct) => { + forward_to_deserialize_method!{deserialize_tuple_struct(&'static str, usize)} + }; + (struct) => { + forward_to_deserialize_method!{deserialize_struct(&'static str, &'static [&'static str])} + }; + (struct_field) => { + forward_to_deserialize_method!{deserialize_struct_field()} + }; + (tuple) => { + forward_to_deserialize_method!{deserialize_tuple(usize)} + }; + (enum) => { + forward_to_deserialize_method!{deserialize_enum(&'static str, &'static [&'static str])} + }; + (ignored_any) => { + forward_to_deserialize_method!{deserialize_ignored_any()} + }; +} + +// Super explicit first paragraph because this shows up at the top level and +// trips up people who are just looking for basic Serialize / Deserialize +// documentation. +// +/// Helper macro when implementing the `Deserializer` part of a new data format +/// for Serde. +/// +/// Some `Deserializer` implementations for self-describing formats do not care +/// what hint the `Visitor` gives them, they just want to blindly call the +/// `Visitor` method corresponding to the data they can tell is in the input. +/// This requires repetitive implementations of all the `Deserializer` trait +/// methods. +/// +/// ```rust +/// # #[macro_use] extern crate serde; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # pub struct MyDeserializer; +/// # impl Deserializer for MyDeserializer { +/// # type Error = value::Error; +/// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error> +/// # where V: Visitor +/// # { unimplemented!() } +/// # +/// #[inline] +/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> +/// where V: Visitor +/// { +/// self.deserialize(visitor) +/// } +/// # forward_to_deserialize! { +/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option +/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct +/// # tuple_struct struct struct_field tuple enum ignored_any +/// # } +/// # } +/// # fn main() {} +/// ``` +/// +/// The `forward_to_deserialize!` macro implements these simple forwarding +/// methods so that they forward directly to `Deserializer::deserialize`. You +/// can choose which methods to forward. +/// +/// ```rust +/// # #[macro_use] extern crate serde; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # pub struct MyDeserializer; +/// impl Deserializer for MyDeserializer { +/// # type Error = value::Error; +/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> +/// where V: Visitor +/// { +/// /* ... */ +/// # let _ = visitor; +/// # unimplemented!() +/// } +/// +/// forward_to_deserialize! { +/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option +/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct +/// tuple_struct struct struct_field tuple enum ignored_any +/// } +/// } +/// # fn main() {} +/// ``` +#[macro_export] +macro_rules! forward_to_deserialize { + ($($func:ident)*) => { + $(forward_to_deserialize_helper!{$func})* + }; +} + +/// Seralize the `$value` that implements Display as a string, +/// when that string is statically known to never have more than +/// a constant `$MAX_LEN` bytes. +/// +/// Panics if the Display impl tries to write more than `$MAX_LEN` bytes. +#[cfg(feature = "std")] +// Not exported +macro_rules! serialize_display_bounded_length { + ($value: expr, $MAX_LEN: expr, $serializer: expr) => { + { + use std::io::Write; + let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() }; + let remaining_len; + { + let mut remaining = &mut buffer[..]; + write!(remaining, "{}", $value).unwrap(); + remaining_len = remaining.len() + } + let written_len = buffer.len() - remaining_len; + let written = &buffer[..written_len]; + + // write! only provides std::fmt::Formatter to Display implementations, + // which has methods write_str and write_char but no method to write arbitrary bytes. + // Therefore, `written` is well-formed in UTF-8. + let written_str = unsafe { + ::std::str::from_utf8_unchecked(written) + }; + $serializer.serialize_str(written_str) + } + } +} diff --git a/bash-5.1/vendor/serde/src/ser/content.rs b/bash-5.1/vendor/serde/src/ser/content.rs new file mode 100644 index 0000000..75482b0 --- /dev/null +++ b/bash-5.1/vendor/serde/src/ser/content.rs @@ -0,0 +1,607 @@ +use core::marker::PhantomData; + +#[cfg(all(not(feature = "std"), feature = "collections"))] +use collections::{String, Vec}; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::boxed::Box; + +#[cfg(feature = "collections")] +use collections::borrow::ToOwned; + +use ser::{self, Serialize, Serializer}; + +pub struct SerializeTupleVariantAsMapValue<M> { + map: M, + name: &'static str, + fields: Vec<Content>, +} + +impl<M> SerializeTupleVariantAsMapValue<M> { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeTupleVariantAsMapValue { + map: map, + name: name, + fields: Vec::with_capacity(len), + } + } +} + +impl<M> ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<M> + where M: ser::SerializeMap +{ + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), M::Error> { + let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); + self.fields.push(value); + Ok(()) + } + + fn end(mut self) -> Result<M::Ok, M::Error> { + try!(self.map.serialize_value(&Content::TupleStruct(self.name, self.fields))); + self.map.end() + } +} + +pub struct SerializeStructVariantAsMapValue<M> { + map: M, + name: &'static str, + fields: Vec<(&'static str, Content)>, +} + +impl<M> SerializeStructVariantAsMapValue<M> { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeStructVariantAsMapValue { + map: map, + name: name, + fields: Vec::with_capacity(len), + } + } +} + +impl<M> ser::SerializeStructVariant for SerializeStructVariantAsMapValue<M> + where M: ser::SerializeMap +{ + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, + key: &'static str, + value: &T) + -> Result<(), M::Error> { + let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(mut self) -> Result<M::Ok, M::Error> { + try!(self.map.serialize_value(&Content::Struct(self.name, self.fields))); + self.map.end() + } +} + +#[derive(Debug)] +enum Content { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Bytes(Vec<u8>), + + None, + Some(Box<Content>), + + Unit, + UnitStruct(&'static str), + UnitVariant(&'static str, usize, &'static str), + NewtypeStruct(&'static str, Box<Content>), + NewtypeVariant(&'static str, usize, &'static str, Box<Content>), + + Seq(Vec<Content>), + SeqFixedSize(Vec<Content>), + Tuple(Vec<Content>), + TupleStruct(&'static str, Vec<Content>), + TupleVariant(&'static str, usize, &'static str, Vec<Content>), + Map(Vec<(Content, Content)>), + Struct(&'static str, Vec<(&'static str, Content)>), + StructVariant(&'static str, usize, &'static str, Vec<(&'static str, Content)>), +} + +impl Serialize for Content { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match *self { + Content::Bool(b) => serializer.serialize_bool(b), + Content::U8(u) => serializer.serialize_u8(u), + Content::U16(u) => serializer.serialize_u16(u), + Content::U32(u) => serializer.serialize_u32(u), + Content::U64(u) => serializer.serialize_u64(u), + Content::I8(i) => serializer.serialize_i8(i), + Content::I16(i) => serializer.serialize_i16(i), + Content::I32(i) => serializer.serialize_i32(i), + Content::I64(i) => serializer.serialize_i64(i), + Content::F32(f) => serializer.serialize_f32(f), + Content::F64(f) => serializer.serialize_f64(f), + Content::Char(c) => serializer.serialize_char(c), + Content::String(ref s) => serializer.serialize_str(s), + Content::Bytes(ref b) => serializer.serialize_bytes(b), + Content::None => serializer.serialize_none(), + Content::Some(ref c) => serializer.serialize_some(&**c), + Content::Unit => serializer.serialize_unit(), + Content::UnitStruct(n) => serializer.serialize_unit_struct(n), + Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v), + Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c), + Content::NewtypeVariant(n, i, v, ref c) => { + serializer.serialize_newtype_variant(n, i, v, &**c) + } + Content::Seq(ref elements) => elements.serialize(serializer), + Content::SeqFixedSize(ref elements) => { + use ser::SerializeSeq; + let mut seq = try!(serializer.serialize_seq_fixed_size(elements.len())); + for e in elements { + try!(seq.serialize_element(e)); + } + seq.end() + } + Content::Tuple(ref elements) => { + use ser::SerializeTuple; + let mut tuple = try!(serializer.serialize_tuple(elements.len())); + for e in elements { + try!(tuple.serialize_element(e)); + } + tuple.end() + } + Content::TupleStruct(n, ref fields) => { + use ser::SerializeTupleStruct; + let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len())); + for f in fields { + try!(ts.serialize_field(f)); + } + ts.end() + } + Content::TupleVariant(n, i, v, ref fields) => { + use ser::SerializeTupleVariant; + let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len())); + for f in fields { + try!(tv.serialize_field(f)); + } + tv.end() + } + Content::Map(ref entries) => { + use ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(entries.len()))); + for &(ref k, ref v) in entries { + try!(map.serialize_entry(k, v)); + } + map.end() + } + Content::Struct(n, ref fields) => { + use ser::SerializeStruct; + let mut s = try!(serializer.serialize_struct(n, fields.len())); + for &(k, ref v) in fields { + try!(s.serialize_field(k, v)); + } + s.end() + } + Content::StructVariant(n, i, v, ref fields) => { + use ser::SerializeStructVariant; + let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len())); + for &(k, ref v) in fields { + try!(sv.serialize_field(k, v)); + } + sv.end() + } + } + } +} + +struct ContentSerializer<E> { + error: PhantomData<E>, +} + +impl<E> ContentSerializer<E> { + fn new() -> Self { + ContentSerializer { error: PhantomData } + } +} + +impl<E> Serializer for ContentSerializer<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + type SerializeSeq = SerializeSeq<E>; + type SerializeTuple = SerializeTuple<E>; + type SerializeTupleStruct = SerializeTupleStruct<E>; + type SerializeTupleVariant = SerializeTupleVariant<E>; + type SerializeMap = SerializeMap<E>; + type SerializeStruct = SerializeStruct<E>; + type SerializeStructVariant = SerializeStructVariant<E>; + + fn serialize_bool(self, v: bool) -> Result<Content, E> { + Ok(Content::Bool(v)) + } + + fn serialize_i8(self, v: i8) -> Result<Content, E> { + Ok(Content::I8(v)) + } + + fn serialize_i16(self, v: i16) -> Result<Content, E> { + Ok(Content::I16(v)) + } + + fn serialize_i32(self, v: i32) -> Result<Content, E> { + Ok(Content::I32(v)) + } + + fn serialize_i64(self, v: i64) -> Result<Content, E> { + Ok(Content::I64(v)) + } + + fn serialize_u8(self, v: u8) -> Result<Content, E> { + Ok(Content::U8(v)) + } + + fn serialize_u16(self, v: u16) -> Result<Content, E> { + Ok(Content::U16(v)) + } + + fn serialize_u32(self, v: u32) -> Result<Content, E> { + Ok(Content::U32(v)) + } + + fn serialize_u64(self, v: u64) -> Result<Content, E> { + Ok(Content::U64(v)) + } + + fn serialize_f32(self, v: f32) -> Result<Content, E> { + Ok(Content::F32(v)) + } + + fn serialize_f64(self, v: f64) -> Result<Content, E> { + Ok(Content::F64(v)) + } + + fn serialize_char(self, v: char) -> Result<Content, E> { + Ok(Content::Char(v)) + } + + fn serialize_str(self, value: &str) -> Result<Content, E> { + Ok(Content::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> { + Ok(Content::Bytes(value.to_owned())) + } + + fn serialize_none(self) -> Result<Content, E> { + Ok(Content::None) + } + + fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Content, E> { + Ok(Content::Some(Box::new(try!(value.serialize(self))))) + } + + fn serialize_unit(self) -> Result<Content, E> { + Ok(Content::Unit) + } + + fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> { + Ok(Content::UnitStruct(name)) + } + + fn serialize_unit_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str) + -> Result<Content, E> { + Ok(Content::UnitVariant(name, variant_index, variant)) + } + + fn serialize_newtype_struct<T: ?Sized + Serialize>(self, + name: &'static str, + value: &T) + -> Result<Content, E> { + Ok(Content::NewtypeStruct(name, Box::new(try!(value.serialize(self))))) + } + + fn serialize_newtype_variant<T: ?Sized + Serialize>(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + value: &T) + -> Result<Content, E> { + Ok(Content::NewtypeVariant(name, + variant_index, + variant, + Box::new(try!(value.serialize(self))))) + } + + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> { + Ok(SerializeSeq { + fixed_size: false, + elements: Vec::with_capacity(len.unwrap_or(0)), + error: PhantomData, + }) + } + + fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, E> { + Ok(SerializeSeq { + fixed_size: true, + elements: Vec::with_capacity(size), + error: PhantomData, + }) + } + + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> { + Ok(SerializeTuple { + elements: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_struct(self, + name: &'static str, + len: usize) + -> Result<Self::SerializeTupleStruct, E> { + Ok(SerializeTupleStruct { + name: name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + len: usize) + -> Result<Self::SerializeTupleVariant, E> { + Ok(SerializeTupleVariant { + name: name, + variant_index: variant_index, + variant: variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> { + Ok(SerializeMap { + entries: Vec::with_capacity(len.unwrap_or(0)), + key: None, + error: PhantomData, + }) + } + + fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, E> { + Ok(SerializeStruct { + name: name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_struct_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + len: usize) + -> Result<Self::SerializeStructVariant, E> { + Ok(SerializeStructVariant { + name: name, + variant_index: variant_index, + variant: variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } +} + +struct SerializeSeq<E> { + fixed_size: bool, + elements: Vec<Content>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeSeq for SerializeSeq<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(if self.fixed_size { + Content::SeqFixedSize(self.elements) + } else { + Content::Seq(self.elements) + }) + } +} + +struct SerializeTuple<E> { + elements: Vec<Content>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeTuple for SerializeTuple<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Tuple(self.elements)) + } +} + +struct SerializeTupleStruct<E> { + name: &'static str, + fields: Vec<Content>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::TupleStruct(self.name, self.fields)) + } +} + +struct SerializeTupleVariant<E> { + name: &'static str, + variant_index: usize, + variant: &'static str, + fields: Vec<Content>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::TupleVariant(self.name, self.variant_index, self.variant, self.fields)) + } +} + +struct SerializeMap<E> { + entries: Vec<(Content, Content)>, + key: Option<Content>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeMap for SerializeMap<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), E> { + let key = try!(key.serialize(ContentSerializer::<E>::new())); + self.key = Some(key); + Ok(()) + } + + fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), E> { + let key = self.key.take().expect("serialize_value called before serialize_key"); + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.entries.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Map(self.entries)) + } + + fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(&mut self, + key: &K, + value: &V) + -> Result<(), E> { + let key = try!(key.serialize(ContentSerializer::<E>::new())); + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.entries.push((key, value)); + Ok(()) + } +} + +struct SerializeStruct<E> { + name: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeStruct for SerializeStruct<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, + key: &'static str, + value: &T) + -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Struct(self.name, self.fields)) + } +} + +struct SerializeStructVariant<E> { + name: &'static str, + variant_index: usize, + variant: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData<E>, +} + +impl<E> ser::SerializeStructVariant for SerializeStructVariant<E> + where E: ser::Error +{ + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, + key: &'static str, + value: &T) + -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::StructVariant(self.name, self.variant_index, self.variant, self.fields)) + } +} diff --git a/bash-5.1/vendor/serde/src/ser/impls.rs b/bash-5.1/vendor/serde/src/ser/impls.rs new file mode 100644 index 0000000..0afaf97 --- /dev/null +++ b/bash-5.1/vendor/serde/src/ser/impls.rs @@ -0,0 +1,818 @@ +#[cfg(feature = "std")] +use std::borrow::Cow; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::borrow::Cow; + +#[cfg(feature = "std")] +use std::collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, HashMap, HashSet, VecDeque}; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, String, Vec}; + +#[cfg(feature = "collections")] +use collections::borrow::ToOwned; + +#[cfg(feature = "std")] +use core::hash::{Hash, BuildHasher}; +#[cfg(feature = "std")] +use std::net; +#[cfg(any(feature = "std", feature = "unstable"))] +use core::ops; +#[cfg(feature = "std")] +use std::path; +#[cfg(feature = "std")] +use std::ffi::{CString, CStr, OsString, OsStr}; +#[cfg(feature = "std")] +use std::rc::Rc; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::rc::Rc; +#[cfg(feature = "std")] +use std::time::Duration; + +#[cfg(feature = "std")] +use std::sync::Arc; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::arc::Arc; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::boxed::Box; + +use core::cell::{Cell, RefCell}; + +#[cfg(feature = "std")] +use std::sync::{Mutex, RwLock}; + +use core::marker::PhantomData; + +#[cfg(feature = "unstable")] +use core::nonzero::{NonZero, Zeroable}; + +use super::{Serialize, SerializeSeq, SerializeTuple, Serializer}; +#[cfg(feature = "std")] +use super::Error; + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! impl_visit { + ($ty:ty, $method:ident $($cast:tt)*) => { + impl Serialize for $ty { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer, + { + serializer.$method(*self $($cast)*) + } + } + } +} + +impl_visit!(bool, serialize_bool); +impl_visit!(isize, serialize_i64 as i64); +impl_visit!(i8, serialize_i8); +impl_visit!(i16, serialize_i16); +impl_visit!(i32, serialize_i32); +impl_visit!(i64, serialize_i64); +impl_visit!(usize, serialize_u64 as u64); +impl_visit!(u8, serialize_u8); +impl_visit!(u16, serialize_u16); +impl_visit!(u32, serialize_u32); +impl_visit!(u64, serialize_u64); +impl_visit!(f32, serialize_f32); +impl_visit!(f64, serialize_f64); +impl_visit!(char, serialize_char); + +/////////////////////////////////////////////////////////////////////////////// + +impl Serialize for str { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + serializer.serialize_str(self) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl Serialize for String { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (&self[..]).serialize(serializer) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for CStr { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +#[cfg(feature = "std")] +impl Serialize for CString { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +impl<T> Serialize for Option<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match *self { + Some(ref value) => serializer.serialize_some(value), + None => serializer.serialize_none(), + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +impl<T> Serialize for PhantomData<T> { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + serializer.serialize_unit_struct("PhantomData") + } +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! array_impls { + ($len:expr) => { + impl<T> Serialize for [T; $len] where T: Serialize { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer, + { + let mut seq = try!(serializer.serialize_seq_fixed_size($len)); + for e in self { + try!(seq.serialize_element(e)); + } + seq.end() + } + } + } +} + +array_impls!(0); +array_impls!(1); +array_impls!(2); +array_impls!(3); +array_impls!(4); +array_impls!(5); +array_impls!(6); +array_impls!(7); +array_impls!(8); +array_impls!(9); +array_impls!(10); +array_impls!(11); +array_impls!(12); +array_impls!(13); +array_impls!(14); +array_impls!(15); +array_impls!(16); +array_impls!(17); +array_impls!(18); +array_impls!(19); +array_impls!(20); +array_impls!(21); +array_impls!(22); +array_impls!(23); +array_impls!(24); +array_impls!(25); +array_impls!(26); +array_impls!(27); +array_impls!(28); +array_impls!(29); +array_impls!(30); +array_impls!(31); +array_impls!(32); + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! serialize_seq { + () => { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer, + { + serializer.collect_seq(self) + } + } +} + +impl<T> Serialize for [T] + where T: Serialize +{ + serialize_seq!(); +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T> Serialize for BinaryHeap<T> + where T: Serialize + Ord +{ + serialize_seq!(); +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T> Serialize for BTreeSet<T> + where T: Serialize + Ord +{ + serialize_seq!(); +} + +#[cfg(feature = "std")] +impl<T, H> Serialize for HashSet<T, H> + where T: Serialize + Eq + Hash, + H: BuildHasher +{ + serialize_seq!(); +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T> Serialize for LinkedList<T> + where T: Serialize +{ + serialize_seq!(); +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T> Serialize for Vec<T> + where T: Serialize +{ + serialize_seq!(); +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<T> Serialize for VecDeque<T> + where T: Serialize +{ + serialize_seq!(); +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl<Idx: Serialize> Serialize for ops::Range<Idx> { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + use super::SerializeStruct; + let mut state = try!(serializer.serialize_struct("Range", 2)); + try!(state.serialize_field("start", &self.start)); + try!(state.serialize_field("end", &self.end)); + state.end() + } +} + +/////////////////////////////////////////////////////////////////////////////// + +impl Serialize for () { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + serializer.serialize_unit() + } +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($( + $TupleVisitor:ident ($len:expr, $($T:ident),+) { + $($state:pat => $idx:tt,)+ + } + )+) => { + $( + impl<$($T),+> Serialize for ($($T,)+) + where $($T: Serialize),+ + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer, + { + let mut tuple = try!(serializer.serialize_tuple($len)); + $( + try!(tuple.serialize_element(&self.$idx)); + )+ + tuple.end() + } + } + )+ + } +} + +tuple_impls! { + TupleVisitor1 (1, T0) { + 0 => 0, + } + TupleVisitor2 (2, T0, T1) { + 0 => 0, + 1 => 1, + } + TupleVisitor3 (3, T0, T1, T2) { + 0 => 0, + 1 => 1, + 2 => 2, + } + TupleVisitor4 (4, T0, T1, T2, T3) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + } + TupleVisitor5 (5, T0, T1, T2, T3, T4) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + } + TupleVisitor6 (6, T0, T1, T2, T3, T4, T5) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + } + TupleVisitor7 (7, T0, T1, T2, T3, T4, T5, T6) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + } + TupleVisitor8 (8, T0, T1, T2, T3, T4, T5, T6, T7) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + } + TupleVisitor9 (9, T0, T1, T2, T3, T4, T5, T6, T7, T8) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + } + TupleVisitor10 (10, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + } + TupleVisitor11 (11, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + 10 => 10, + } + TupleVisitor12 (12, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + 10 => 10, + 11 => 11, + } + TupleVisitor13 (13, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + 10 => 10, + 11 => 11, + 12 => 12, + } + TupleVisitor14 (14, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + 10 => 10, + 11 => 11, + 12 => 12, + 13 => 13, + } + TupleVisitor15 (15, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + 10 => 10, + 11 => 11, + 12 => 12, + 13 => 13, + 14 => 14, + } + TupleVisitor16 (16, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, + 10 => 10, + 11 => 11, + 12 => 12, + 13 => 13, + 14 => 14, + 15 => 15, + } +} + +/////////////////////////////////////////////////////////////////////////////// + +macro_rules! serialize_map { + () => { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer, + { + serializer.collect_map(self) + } + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<K, V> Serialize for BTreeMap<K, V> + where K: Serialize + Ord, + V: Serialize +{ + serialize_map!(); +} + +#[cfg(feature = "std")] +impl<K, V, H> Serialize for HashMap<K, V, H> + where K: Serialize + Eq + Hash, + V: Serialize, + H: BuildHasher +{ + serialize_map!(); +} + +/////////////////////////////////////////////////////////////////////////////// + +impl<'a, T: ?Sized> Serialize for &'a T + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} + +impl<'a, T: ?Sized> Serialize for &'a mut T + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<T: ?Sized> Serialize for Box<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<T> Serialize for Rc<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<T> Serialize for Arc<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +impl<'a, T: ?Sized> Serialize for Cow<'a, T> + where T: Serialize + ToOwned +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} + +impl<T> Serialize for Cell<T> + where T: Serialize + Copy +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + self.get().serialize(serializer) + } +} + +impl<T> Serialize for RefCell<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + self.borrow().serialize(serializer) + } +} + +#[cfg(feature = "std")] +impl<T> Serialize for Mutex<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match self.lock() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +#[cfg(feature = "std")] +impl<T> Serialize for RwLock<T> + where T: Serialize +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match self.read() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +impl<T, E> Serialize for Result<T, E> + where T: Serialize, + E: Serialize +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match *self { + Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value), + Result::Err(ref value) => { + serializer.serialize_newtype_variant("Result", 1, "Err", value) + } + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for Duration { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + use super::SerializeStruct; + let mut state = try!(serializer.serialize_struct("Duration", 2)); + try!(state.serialize_field("secs", &self.as_secs())); + try!(state.serialize_field("nanos", &self.subsec_nanos())); + state.end() + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for net::IpAddr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match *self { + net::IpAddr::V4(ref a) => a.serialize(serializer), + net::IpAddr::V6(ref a) => a.serialize(serializer), + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::Ipv4Addr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + /// "101.102.103.104".len() + const MAX_LEN: usize = 15; + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } +} + +#[cfg(feature = "std")] +impl Serialize for net::Ipv6Addr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + /// "1000:1002:1003:1004:1005:1006:1007:1008".len() + const MAX_LEN: usize = 39; + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for net::SocketAddr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match *self { + net::SocketAddr::V4(ref addr) => addr.serialize(serializer), + net::SocketAddr::V6(ref addr) => addr.serialize(serializer), + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::SocketAddrV4 { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + /// "101.102.103.104:65000".len() + const MAX_LEN: usize = 21; + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } +} + +#[cfg(feature = "std")] +impl Serialize for net::SocketAddrV6 { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + /// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len() + const MAX_LEN: usize = 47; + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for path::Path { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match self.to_str() { + Some(s) => s.serialize(serializer), + None => Err(Error::custom("path contains invalid UTF-8 characters")), + } + } +} + +#[cfg(feature = "std")] +impl Serialize for path::PathBuf { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + self.as_path().serialize(serializer) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +impl Serialize for OsStr { + #[cfg(unix)] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + use std::os::unix::ffi::OsStrExt; + serializer.serialize_newtype_variant("OsString", + 0, + "Unix", + self.as_bytes()) + } + #[cfg(windows)] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + use std::os::windows::ffi::OsStrExt; + let val = self.encode_wide().collect::<Vec<_>>(); + serializer.serialize_newtype_variant("OsString", + 1, + "Windows", + &val) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg(feature = "std")] +impl Serialize for OsString { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + self.as_os_str().serialize(serializer) + } +} + +#[cfg(feature = "unstable")] +impl<T> Serialize for NonZero<T> + where T: Serialize + Zeroable +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + (**self).serialize(serializer) + } +} diff --git a/bash-5.1/vendor/serde/src/ser/impossible.rs b/bash-5.1/vendor/serde/src/ser/impossible.rs new file mode 100644 index 0000000..6b8e7c2 --- /dev/null +++ b/bash-5.1/vendor/serde/src/ser/impossible.rs @@ -0,0 +1,156 @@ +//! This module contains `Impossible` serializer and its implementations. + +use core::marker::PhantomData; + +use ser::{self, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct, + SerializeTupleVariant, SerializeMap, SerializeStruct, SerializeStructVariant}; + +/// Helper type for implementing a `Serializer` that does not support +/// serializing one of the compound types. +/// +/// This type cannot be instantiated, but implements every one of the traits +/// corresponding to the `Serializer` compound types: `SerializeSeq`, +/// `SerializeTuple`, `SerializeTupleStruct`, `SerializeTupleVariant`, +/// `SerializeMap`, `SerializeStruct`, and `SerializeStructVariant`. +/// +/// ```rust,ignore +/// impl Serializer for MySerializer { +/// type Ok = (); +/// type Error = Error; +/// +/// type SerializeSeq = Impossible<(), Error>; +/// /* other associated types */ +/// +/// /// This data format does not support serializing sequences. +/// fn serialize_seq(self, +/// len: Option<usize>) +/// -> Result<Self::SerializeSeq, Error> { +/// // Given Impossible cannot be instantiated, the only +/// // thing we can do here is to return an error. +/// Err(...) +/// } +/// +/// /* other Serializer methods */ +/// } +/// ``` +pub struct Impossible<Ok, E> { + void: Void, + _marker: PhantomData<(Ok, E)>, +} + +enum Void {} + +impl<Ok, E> SerializeSeq for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} + +impl<Ok, E> SerializeTuple for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} + +impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} + +impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} + +impl<Ok, E> SerializeMap for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_key<T: ?Sized + Serialize>(&mut self, _key: &T) -> Result<(), E> { + match self.void {} + } + + fn serialize_value<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} + +impl<Ok, E> SerializeStruct for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, + _key: &'static str, + _value: &T) + -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} + +impl<Ok, E> SerializeStructVariant for Impossible<Ok, E> + where E: ser::Error +{ + type Ok = Ok; + type Error = E; + + fn serialize_field<T: ?Sized + Serialize>(&mut self, + _key: &'static str, + _value: &T) + -> Result<(), E> { + match self.void {} + } + + fn end(self) -> Result<Ok, E> { + match self.void {} + } +} diff --git a/bash-5.1/vendor/serde/src/ser/mod.rs b/bash-5.1/vendor/serde/src/ser/mod.rs new file mode 100644 index 0000000..460b687 --- /dev/null +++ b/bash-5.1/vendor/serde/src/ser/mod.rs @@ -0,0 +1,919 @@ +//! Generic data structure serialization framework. +//! +//! The two most important traits in this module are `Serialize` and +//! `Serializer`. +//! +//! - **A type that implements `Serialize` is a data structure** that can be +//! serialized to any data format supported by Serde, and conversely +//! - **A type that implements `Serializer` is a data format** that can +//! serialize any data structure supported by Serde. +//! +//! # The Serialize trait +//! +//! Serde provides `Serialize` implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! serialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called `serde_derive` to +//! automatically generate `Serialize` implementations for structs and enums in +//! your program. See the [codegen section of the manual][codegen] for how to +//! use this. +//! +//! In rare cases it may be necessary to implement `Serialize` manually for some +//! type in your program. See the [Implementing `Serialize`][impl-serialize] +//! section of the manual for more about this. +//! +//! Third-party crates may provide `Serialize` implementations for types that +//! they expose. For example the `linked-hash-map` crate provides a +//! `LinkedHashMap<K, V>` type that is serializable by Serde because the crate +//! provides an implementation of `Serialize` for it. +//! +//! # The Serializer trait +//! +//! `Serializer` implementations are provided by third-party crates, for example +//! [`serde_json`][serde_json], [`serde_yaml`][serde_yaml] and +//! [`bincode`][bincode]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data-formats]. +//! +//! # Implementations of Serialize provided by Serde +//! +//! - **Primitive types**: +//! - bool +//! - isize, i8, i16, i32, i64 +//! - usize, u8, u16, u32, u64 +//! - f32, f64 +//! - char +//! - str +//! - &T and &mut T +//! - **Compound types**: +//! - [T] +//! - [T; 0] through [T; 32] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\<T\> +//! - Result\<T, E\> +//! - PhantomData\<T\> +//! - **Wrapper types**: +//! - Box\<T\> +//! - Rc\<T\> +//! - Arc\<T\> +//! - Cow\<'a, T\> +//! - Cell\<T\> +//! - RefCell\<T\> +//! - Mutex\<T\> +//! - RwLock\<T\> +//! - **Collection types**: +//! - BTreeMap\<K, V\> +//! - BTreeSet\<T\> +//! - BinaryHeap\<T\> +//! - HashMap\<K, V, H\> +//! - HashSet\<T, H\> +//! - LinkedList\<T\> +//! - VecDeque\<T\> +//! - Vec\<T\> +//! - EnumSet\<T\> (unstable) +//! - **Miscellaneous standard library types**: +//! - Duration +//! - Path +//! - PathBuf +//! - Range\<T\> +//! - NonZero\<T\> (unstable) +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [codegen]: https://serde.rs/codegen.html +//! [impl-serialize]: https://serde.rs/impl-serialize.html +//! [serde_json]: https://github.com/serde-rs/json +//! [serde_yaml]: https://github.com/dtolnay/serde-yaml +//! [bincode]: https://github.com/TyOverby/bincode +//! [data-formats]: https://serde.rs/#data-formats + +#[cfg(feature = "std")] +use std::error; +#[cfg(not(feature = "std"))] +use error; + +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::string::String; +use core::fmt::Display; +#[cfg(any(feature = "std", feature = "collections"))] +use core::fmt::Write; +use core::iter::IntoIterator; + +mod impls; +mod impossible; + +// Helpers used by generated code. Not public API. +#[doc(hidden)] +pub mod private; +#[cfg(any(feature = "std", feature = "collections"))] +mod content; + +pub use self::impossible::Impossible; + +/////////////////////////////////////////////////////////////////////////////// + +/// Trait used by `Serialize` implementations to generically construct errors +/// belonging to the `Serializer` against which they are currently running. +pub trait Error: Sized + error::Error { + /// Raised when a `Serialize` implementation encounters a general error + /// while serializing a type. + /// + /// The message should not be capitalized and should not end with a period. + /// + /// For example, a filesystem `Path` may refuse to serialize itself if it + /// contains invalid UTF-8 data. + /// + /// ```rust + /// # use serde::ser::{Serialize, Serializer, Error}; + /// # struct Path; + /// # impl Path { fn to_str(&self) -> Option<&str> { unimplemented!() } } + /// impl Serialize for Path { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match self.to_str() { + /// Some(s) => s.serialize(serializer), + /// None => Err(Error::custom("path contains invalid UTF-8 characters")), + /// } + /// } + /// } + /// ``` + fn custom<T: Display>(msg: T) -> Self; +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be serialized into any data format supported +/// by Serde. +/// +/// Serde provides `Serialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][ser]. All of these can +/// be serialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called `serde_derive` to +/// automatically generate `Serialize` implementations for structs and enums in +/// your program. See the [codegen section of the manual][codegen] for how to +/// use this. +/// +/// In rare cases it may be necessary to implement `Serialize` manually for some +/// type in your program. See the [Implementing `Serialize`][impl-serialize] +/// section of the manual for more about this. +/// +/// Third-party crates may provide `Serialize` implementations for types that +/// they expose. For example the `linked-hash-map` crate provides a +/// `LinkedHashMap<K, V>` type that is serializable by Serde because the crate +/// provides an implementation of `Serialize` for it. +/// +/// [ser]: https://docs.serde.rs/serde/ser/index.html +/// [codegen]: https://serde.rs/codegen.html +/// [impl-serialize]: https://serde.rs/impl-serialize.html +pub trait Serialize { + /// Serialize this value into the given Serde serializer. + /// + /// See the [Implementing `Serialize`][impl-serialize] section of the manual + /// for more information about how to implement this method. + /// + /// [impl-serialize]: https://serde.rs/impl-serialize.html + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer; +} + +/////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can serialize any data structure supported by Serde. +/// +/// The role of this trait is to define the serialization half of the Serde data +/// model, which is a way to categorize every Rust data structure into one of 28 +/// possible types. Each method of the `Serializer` trait corresponds to one of +/// the types of the data model. +/// +/// Implementations of `Serialize` map themselves into this data model by +/// invoking exactly one of the `Serializer` methods. +/// +/// The types that make up the Serde data model are: +/// +/// - 12 primitive types: +/// - bool +/// - i8, i16, i32, i64 +/// - u8, u16, u32, u64 +/// - f32, f64 +/// - char +/// - string +/// - byte array - [u8] +/// - option +/// - either none or some value +/// - unit +/// - unit is the type of () in Rust +/// - unit_struct +/// - for example `struct Unit` or `PhantomData<T>` +/// - unit_variant +/// - the `E::A` and `E::B` in `enum E { A, B }` +/// - newtype_struct +/// - for example `struct Millimeters(u8)` +/// - newtype_variant +/// - the `E::N` in `enum E { N(u8) }` +/// - seq +/// - a dynamically sized sequence of values, for example `Vec<T>` or +/// `HashSet<T>` +/// - seq_fixed_size +/// - a statically sized sequence of values for which the size will be known +/// at deserialization time without looking at the serialized data, for +/// example `[u64; 10]` +/// - tuple +/// - for example `(u8,)` or `(String, u64, Vec<T>)` +/// - tuple_struct +/// - for example `struct Rgb(u8, u8, u8)` +/// - tuple_variant +/// - the `E::T` in `enum E { T(u8, u8) }` +/// - map +/// - for example `BTreeMap<K, V>` +/// - struct +/// - a key-value pairing in which the keys will be known at deserialization +/// time without looking at the serialized data, for example `struct S { r: +/// u8, g: u8, b: u8 }` +/// - struct_variant +/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }` +/// +/// Many Serde serializers produce text or binary data as output, for example +/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and +/// there are serializers that do not produce text or binary output. One example +/// is the `serde_json::value::Serializer` (distinct from the main `serde_json` +/// serializer) that produces a `serde_json::Value` data structure in memory as +/// output. +pub trait Serializer: Sized { + /// The output type produced by this `Serializer` during successful + /// serialization. Most serializers that produce text or binary output + /// should set `Ok = ()` and serialize into an `io::Write` or buffer + /// contained within the `Serializer` instance. Serializers that build + /// in-memory data structures may be simplified by using `Ok` to propagate + /// the data structure around. + type Ok; + + /// The error type when some error occurs during serialization. + type Error: Error; + + /// Type returned from `serialize_seq` and `serialize_seq_fixed_size` for + /// serializing the content of the sequence. + type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from `serialize_tuple` for serializing the content of the + /// tuple. + type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from `serialize_tuple_struct` for serializing the content + /// of the tuple struct. + type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from `serialize_tuple_variant` for serializing the content + /// of the tuple variant. + type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from `serialize_map` for serializing the content of the + /// map. + type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from `serialize_struct` for serializing the content of the + /// struct. + type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from `serialize_struct_variant` for serializing the + /// content of the struct variant. + type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>; + + /// Serialize a `bool` value. + fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i8` value. + /// + /// If the format does not differentiate between `i8` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i16` value. + /// + /// If the format does not differentiate between `i16` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i32` value. + /// + /// If the format does not differentiate between `i32` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i64` value. + fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u8` value. + /// + /// If the format does not differentiate between `u8` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u16` value. + /// + /// If the format does not differentiate between `u16` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u32` value. + /// + /// If the format does not differentiate between `u32` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u64` value. + fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `f32` value. + /// + /// If the format does not differentiate between `f32` and `f64`, a + /// reasonable implementation would be to cast the value to `f64` and + /// forward to `serialize_f64`. + fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `f64` value. + fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>; + + /// Serialize a character. + /// + /// If the format does not support characters, it is reasonable to serialize + /// it as a single element `str` or a `u32`. + fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `&str`. + fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>; + + /// Serialize a chunk of raw byte data. + /// + /// Enables serializers to serialize byte slices more compactly or more + /// efficiently than other types of slices. If no efficient implementation + /// is available, a reasonable implementation would be to forward to + /// `serialize_seq`. If forwarded, the implementation looks usually just + /// like this: + /// + /// ```rust,ignore + /// let mut seq = self.serialize_seq(Some(value.len()))?; + /// for b in value { + /// seq.serialize_element(b)?; + /// } + /// seq.end() + /// ``` + fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `None` value. + fn serialize_none(self) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `Some(T)` value. + fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `()` value. + fn serialize_unit(self) -> Result<Self::Ok, Self::Error>; + + /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`. + /// + /// A reasonable implementation would be to forward to `serialize_unit`. + fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>; + + /// Serialize a unit variant like `E::A` in `enum E { A, B }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. + /// + /// A reasonable implementation would be to forward to `serialize_unit`. + /// + /// ```rust,ignore + /// match *self { + /// E::A => serializer.serialize_unit_variant("E", 0, "A"), + /// E::B => serializer.serialize_unit_variant("E", 1, "B"), + /// } + /// ``` + fn serialize_unit_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str) + -> Result<Self::Ok, Self::Error>; + + /// Serialize a newtype struct like `struct Millimeters(u8)`. + /// + /// Serializers are encouraged to treat newtype structs as insignificant + /// wrappers around the data they contain. A reasonable implementation would + /// be to forward to `value.serialize(self)`. + /// + /// ```rust,ignore + /// serializer.serialize_newtype_struct("Millimeters", &self.0) + /// ``` + fn serialize_newtype_struct<T: ?Sized + Serialize>(self, + name: &'static str, + value: &T) + -> Result<Self::Ok, Self::Error>; + + /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. The `value` is the data contained within this newtype variant. + /// + /// ```rust,ignore + /// match *self { + /// E::N(ref n) => serializer.serialize_newtype_variant("E", 0, "N", n), + /// } + /// ``` + fn serialize_newtype_variant<T: ?Sized + Serialize>(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + value: &T) + -> Result<Self::Ok, Self::Error>; + + /// Begin to serialize a dynamically sized sequence. This call must be + /// followed by zero or more calls to `serialize_element`, then a call to + /// `end`. + /// + /// The argument is the number of elements in the sequence, which may or may + /// not be computable before the sequence is iterated. Some serializers only + /// support sequences whose length is known up front. + /// + /// ```rust,ignore + /// let mut seq = serializer.serialize_seq(Some(self.len()))?; + /// for element in self { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// ``` + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>; + + /// Begin to serialize a statically sized sequence whose length will be + /// known at deserialization time without looking at the serialized data. + /// This call must be followed by zero or more calls to `serialize_element`, + /// then a call to `end`. + /// + /// ```rust,ignore + /// let mut seq = serializer.serialize_seq_fixed_size(self.len())?; + /// for element in self { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// ``` + fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, Self::Error>; + + /// Begin to serialize a tuple. This call must be followed by zero or more + /// calls to `serialize_element`, then a call to `end`. + /// + /// ```rust,ignore + /// let mut tup = serializer.serialize_tuple(3)?; + /// tup.serialize_element(&self.0)?; + /// tup.serialize_element(&self.1)?; + /// tup.serialize_element(&self.2)?; + /// tup.end() + /// ``` + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>; + + /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This + /// call must be followed by zero or more calls to `serialize_field`, then a + /// call to `end`. + /// + /// The `name` is the name of the tuple struct and the `len` is the number + /// of data fields that will be serialized. + /// + /// ```rust,ignore + /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; + /// ts.serialize_field(&self.0)?; + /// ts.serialize_field(&self.1)?; + /// ts.serialize_field(&self.2)?; + /// ts.end() + /// ``` + fn serialize_tuple_struct(self, + name: &'static str, + len: usize) + -> Result<Self::SerializeTupleStruct, Self::Error>; + + /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) + /// }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// + /// ```rust,ignore + /// match *self { + /// E::T(ref a, ref b) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.end() + /// } + /// } + /// ``` + fn serialize_tuple_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + len: usize) + -> Result<Self::SerializeTupleVariant, Self::Error>; + + /// Begin to serialize a map. This call must be followed by zero or more + /// calls to `serialize_key` and `serialize_value`, then a call to `end`. + /// + /// The argument is the number of elements in the map, which may or may not + /// be computable before the map is iterated. Some serializers only support + /// maps whose length is known up front. + /// + /// ```rust,ignore + /// let mut map = serializer.serialize_map(Some(self.len()))?; + /// for (k, v) in self { + /// map.serialize_entry(k, v)?; + /// } + /// map.end() + /// ``` + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>; + + /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. + /// This call must be followed by zero or more calls to `serialize_field`, + /// then a call to `end`. + /// + /// The `name` is the name of the struct and the `len` is the number of + /// data fields that will be serialized. + /// + /// ```rust,ignore + /// let mut struc = serializer.serialize_struct("Rgb", 3)?; + /// struc.serialize_field("r", &self.r)?; + /// struc.serialize_field("g", &self.g)?; + /// struc.serialize_field("b", &self.b)?; + /// struc.end() + /// ``` + fn serialize_struct(self, + name: &'static str, + len: usize) + -> Result<Self::SerializeStruct, Self::Error>; + + /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, + /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// + /// ```rust,ignore + /// match *self { + /// E::S { ref r, ref g, ref b } => { + /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; + /// sv.serialize_field("r", r)?; + /// sv.serialize_field("g", g)?; + /// sv.serialize_field("b", b)?; + /// sv.end() + /// } + /// } + /// ``` + fn serialize_struct_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + len: usize) + -> Result<Self::SerializeStructVariant, Self::Error>; + + /// Collect an iterator as a sequence. + /// + /// The default implementation serializes each item yielded by the iterator + /// using `Self::SerializeSeq`. Implementors should not need to override + /// this method. + fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> + where I: IntoIterator, + <I as IntoIterator>::Item: Serialize + { + let iter = iter.into_iter(); + let mut serializer = try!(self.serialize_seq(iter.len_hint())); + for item in iter { + try!(serializer.serialize_element(&item)); + } + serializer.end() + } + + /// Collect an iterator as a map. + /// + /// The default implementation serializes each pair yielded by the iterator + /// using `Self::SerializeMap`. Implementors should not need to override + /// this method. + fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> + where K: Serialize, + V: Serialize, + I: IntoIterator<Item = (K, V)> + { + let iter = iter.into_iter(); + let mut serializer = try!(self.serialize_map(iter.len_hint())); + for (key, value) in iter { + try!(serializer.serialize_entry(&key, &value)); + } + serializer.end() + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// The default implementation builds a heap-allocated `String` and + /// delegates to `serialize_str`. Serializers are encouraged to provide a + /// more efficient implementation if possible. + /// + /// ```rust + /// # use serde::{Serialize, Serializer}; + /// # struct DateTime; + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// impl Serialize for DateTime { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", + /// self.naive_local(), + /// self.offset())) + /// } + /// } + /// ``` + #[cfg(any(feature = "std", feature = "collections"))] + fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> + where T: Display + { + let mut string = String::new(); + write!(string, "{}", value).unwrap(); + self.serialize_str(&string) + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// The default implementation returns an error unconditionally when + /// compiled with `no_std`. + /// + /// ```rust + /// # use serde::{Serialize, Serializer}; + /// # struct DateTime; + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// impl Serialize for DateTime { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", + /// self.naive_local(), + /// self.offset())) + /// } + /// } + /// ``` + #[cfg(not(any(feature = "std", feature = "collections")))] + fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> + where T: Display + { + // TODO https://github.com/serde-rs/serde/issues/805 + // Remove this impl and force no_std formats to implement collect_str. + let _ = value; + Err(Error::custom("this no_std format does not support serializing strings with collect_str")) + } +} + +/// Returned from `Serializer::serialize_seq` and +/// `Serializer::serialize_seq_fixed_size`. +/// +/// ```rust,ignore +/// let mut seq = serializer.serialize_seq(Some(self.len()))?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// ``` +pub trait SerializeSeq { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a sequence element. + fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>; + + /// Finish serializing a sequence. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_tuple`. +/// +/// ```rust,ignore +/// let mut tup = serializer.serialize_tuple(3)?; +/// tup.serialize_element(&self.0)?; +/// tup.serialize_element(&self.1)?; +/// tup.serialize_element(&self.2)?; +/// tup.end() +/// ``` +pub trait SerializeTuple { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple element. + fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>; + + /// Finish serializing a tuple. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_tuple_struct`. +/// +/// ```rust,ignore +/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; +/// ts.serialize_field(&self.0)?; +/// ts.serialize_field(&self.1)?; +/// ts.serialize_field(&self.2)?; +/// ts.end() +/// ``` +pub trait SerializeTupleStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple struct field. + fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>; + + /// Finish serializing a tuple struct. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_tuple_variant`. +/// +/// ```rust,ignore +/// match *self { +/// E::T(ref a, ref b) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.end() +/// } +/// } +/// ``` +pub trait SerializeTupleVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple variant field. + fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>; + + /// Finish serializing a tuple variant. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_map`. +/// +/// ```rust,ignore +/// let mut map = serializer.serialize_map(Some(self.len()))?; +/// for (k, v) in self { +/// map.serialize_entry(k, v)?; +/// } +/// map.end() +/// ``` +pub trait SerializeMap { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a map key. + fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>; + + /// Serialize a map value. + fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>; + + /// Serialize a map entry consisting of a key and a value. + /// + /// Some `Serialize` types are not able to hold a key and value in memory at + /// the same time so `SerializeMap` implementations are required to support + /// `serialize_key` and `serialize_value` individually. The + /// `serialize_entry` method allows serializers to optimize for the case + /// where key and value are both available. `Serialize` implementations are + /// encouraged to use `serialize_entry` if possible. + /// + /// The default implementation delegates to `serialize_key` and + /// `serialize_value`. This is appropriate for serializers that do not care + /// about performance or are not able to optimize `serialize_entry` any + /// better than this. + fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(&mut self, + key: &K, + value: &V) + -> Result<(), Self::Error> { + try!(self.serialize_key(key)); + self.serialize_value(value) + } + + /// Finish serializing a map. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_struct`. +/// +/// ```rust,ignore +/// let mut struc = serializer.serialize_struct("Rgb", 3)?; +/// struc.serialize_field("r", &self.r)?; +/// struc.serialize_field("g", &self.g)?; +/// struc.serialize_field("b", &self.b)?; +/// struc.end() +/// ``` +pub trait SerializeStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct field. + fn serialize_field<T: ?Sized + Serialize>(&mut self, + key: &'static str, + value: &T) + -> Result<(), Self::Error>; + + /// Finish serializing a struct. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_struct_variant`. +/// +/// ```rust,ignore +/// match *self { +/// E::S { ref r, ref g, ref b } => { +/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; +/// sv.serialize_field("r", r)?; +/// sv.serialize_field("g", g)?; +/// sv.serialize_field("b", b)?; +/// sv.end() +/// } +/// } +/// ``` +pub trait SerializeStructVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct variant field. + fn serialize_field<T: ?Sized + Serialize>(&mut self, + key: &'static str, + value: &T) + -> Result<(), Self::Error>; + + /// Finish serializing a struct variant. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +trait LenHint: Iterator { + fn len_hint(&self) -> Option<usize>; +} + +impl<I: Iterator> LenHint for I { + #[cfg(not(feature = "unstable"))] + fn len_hint(&self) -> Option<usize> { + iterator_len_hint(self) + } + + #[cfg(feature = "unstable")] + default fn len_hint(&self) -> Option<usize> { + iterator_len_hint(self) + } +} + +#[cfg(feature = "unstable")] +impl<I: ExactSizeIterator> LenHint for I { + fn len_hint(&self) -> Option<usize> { + Some(self.len()) + } +} + +fn iterator_len_hint<I: Iterator>(iter: &I) -> Option<usize> { + match iter.size_hint() { + (lo, Some(hi)) if lo == hi => Some(lo), + _ => None, + } +} diff --git a/bash-5.1/vendor/serde/src/ser/private.rs b/bash-5.1/vendor/serde/src/ser/private.rs new file mode 100644 index 0000000..0297c8a --- /dev/null +++ b/bash-5.1/vendor/serde/src/ser/private.rs @@ -0,0 +1,315 @@ +use core::fmt::{self, Display}; + +use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct, Impossible}; + +#[cfg(any(feature = "std", feature = "collections"))] +use ser::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMapValue}; + +/// Not public API. +pub fn serialize_tagged_newtype<S, T>(serializer: S, + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + value: &T) + -> Result<S::Ok, S::Error> + where S: Serializer, + T: Serialize +{ + value.serialize(TaggedSerializer { + type_ident: type_ident, + variant_ident: variant_ident, + tag: tag, + variant_name: variant_name, + delegate: serializer, + }) +} + +struct TaggedSerializer<S> { + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + delegate: S, +} + +enum Unsupported { + Boolean, + Integer, + Float, + Char, + String, + ByteArray, + Optional, + Unit, + UnitStruct, + Sequence, + Tuple, + TupleStruct, + #[cfg(not(any(feature = "std", feature = "collections")))] + Enum, +} + +impl Display for Unsupported { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self { + Unsupported::Boolean => formatter.write_str("a boolean"), + Unsupported::Integer => formatter.write_str("an integer"), + Unsupported::Float => formatter.write_str("a float"), + Unsupported::Char => formatter.write_str("a char"), + Unsupported::String => formatter.write_str("a string"), + Unsupported::ByteArray => formatter.write_str("a byte array"), + Unsupported::Optional => formatter.write_str("an optional"), + Unsupported::Unit => formatter.write_str("unit"), + Unsupported::UnitStruct => formatter.write_str("a unit struct"), + Unsupported::Sequence => formatter.write_str("a sequence"), + Unsupported::Tuple => formatter.write_str("a tuple"), + Unsupported::TupleStruct => formatter.write_str("a tuple struct"), + #[cfg(not(any(feature = "std", feature = "collections")))] + Unsupported::Enum => formatter.write_str("an enum"), + } + } +} + +struct Error { + type_ident: &'static str, + variant_ident: &'static str, + ty: Unsupported, +} + +impl Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, + "cannot serialize tagged newtype variant {}::{} containing {}", + self.type_ident, + self.variant_ident, + self.ty) + } +} + +impl<S> TaggedSerializer<S> + where S: Serializer +{ + fn bad_type(self, what: Unsupported) -> S::Error { + ser::Error::custom(Error { + type_ident: self.type_ident, + variant_ident: self.variant_ident, + ty: what, + }) + } +} + +impl<S> Serializer for TaggedSerializer<S> + where S: Serializer +{ + type Ok = S::Ok; + type Error = S::Error; + + type SerializeSeq = Impossible<S::Ok, S::Error>; + type SerializeTuple = Impossible<S::Ok, S::Error>; + type SerializeTupleStruct = Impossible<S::Ok, S::Error>; + type SerializeMap = S::SerializeMap; + type SerializeStruct = S::SerializeStruct; + + #[cfg(not(any(feature = "std", feature = "collections")))] + type SerializeTupleVariant = Impossible<S::Ok, S::Error>; + #[cfg(any(feature = "std", feature = "collections"))] + type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>; + + #[cfg(not(any(feature = "std", feature = "collections")))] + type SerializeStructVariant = Impossible<S::Ok, S::Error>; + #[cfg(any(feature = "std", feature = "collections"))] + type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>; + + fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Boolean)) + } + + fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Char)) + } + + fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::String)) + } + + fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::ByteArray)) + } + + fn serialize_none(self) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> + where T: Serialize + { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Unit)) + } + + fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::UnitStruct)) + } + + fn serialize_unit_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str) + -> Result<Self::Ok, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_entry(inner_variant, &())); + map.end() + } + + fn serialize_newtype_struct<T: ?Sized>(self, + _: &'static str, + value: &T) + -> Result<Self::Ok, Self::Error> + where T: Serialize + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _: &'static str, + _: usize, + inner_variant: &'static str, + inner_value: &T) + -> Result<Self::Ok, Self::Error> + where T: Serialize + { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_entry(inner_variant, inner_value)); + map.end() + } + + fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> { + Err(self.bad_type(Unsupported::Tuple)) + } + + fn serialize_tuple_struct(self, + _: &'static str, + _: usize) + -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(self.bad_type(Unsupported::TupleStruct)) + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn serialize_tuple_variant(self, + _: &'static str, + _: usize, + _: &'static str, + _: usize) + -> Result<Self::SerializeTupleVariant, Self::Error> { + // Lack of push-based serialization means we need to buffer the content + // of the tuple variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "collections"))] + fn serialize_tuple_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str, + len: usize) + -> Result<Self::SerializeTupleVariant, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_key(inner_variant)); + Ok(SerializeTupleVariantAsMapValue::new(map, inner_variant, len)) + } + + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { + let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1))); + try!(map.serialize_entry(self.tag, self.variant_name)); + Ok(map) + } + + fn serialize_struct(self, + name: &'static str, + len: usize) + -> Result<Self::SerializeStruct, Self::Error> { + let mut state = try!(self.delegate.serialize_struct(name, len + 1)); + try!(state.serialize_field(self.tag, self.variant_name)); + Ok(state) + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn serialize_struct_variant(self, + _: &'static str, + _: usize, + _: &'static str, + _: usize) + -> Result<Self::SerializeStructVariant, Self::Error> { + // Lack of push-based serialization means we need to buffer the content + // of the struct variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "collections"))] + fn serialize_struct_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str, + len: usize) + -> Result<Self::SerializeStructVariant, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_key(inner_variant)); + Ok(SerializeStructVariantAsMapValue::new(map, inner_variant, len)) + } +} diff --git a/bash-5.1/vendor/serde/src/utils.rs b/bash-5.1/vendor/serde/src/utils.rs new file mode 100644 index 0000000..927d125 --- /dev/null +++ b/bash-5.1/vendor/serde/src/utils.rs @@ -0,0 +1,74 @@ +//! Private utility functions + +const TAG_CONT: u8 = 0b1000_0000; +const TAG_TWO_B: u8 = 0b1100_0000; +const TAG_THREE_B: u8 = 0b1110_0000; +const TAG_FOUR_B: u8 = 0b1111_0000; +const MAX_ONE_B: u32 = 0x80; +const MAX_TWO_B: u32 = 0x800; +const MAX_THREE_B: u32 = 0x10000; + +#[inline] +pub fn encode_utf8(c: char) -> EncodeUtf8 { + let code = c as u32; + let mut buf = [0; 4]; + let pos = if code < MAX_ONE_B { + buf[3] = code as u8; + 3 + } else if code < MAX_TWO_B { + buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; + buf[3] = (code & 0x3F) as u8 | TAG_CONT; + 2 + } else if code < MAX_THREE_B { + buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; + buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + buf[3] = (code & 0x3F) as u8 | TAG_CONT; + 1 + } else { + buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; + buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + buf[3] = (code & 0x3F) as u8 | TAG_CONT; + 0 + }; + EncodeUtf8 { + buf: buf, + pos: pos, + } +} + +pub struct EncodeUtf8 { + buf: [u8; 4], + pos: usize, +} + +impl EncodeUtf8 { + // FIXME: use this from_utf8_unchecked, since we know it can never fail + pub fn as_str(&self) -> &str { + ::core::str::from_utf8(&self.buf[self.pos..]).unwrap() + } +} + +#[allow(non_upper_case_globals)] +const Pattern_White_Space_table: &'static [(char, char)] = &[('\u{9}', '\u{d}'), + ('\u{20}', '\u{20}'), + ('\u{85}', '\u{85}'), + ('\u{200e}', '\u{200f}'), + ('\u{2028}', '\u{2029}')]; + +fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool { + use core::cmp::Ordering::{Equal, Less, Greater}; + r.binary_search_by(|&(lo, hi)| if c < lo { + Greater + } else if hi < c { + Less + } else { + Equal + }) + .is_ok() +} + +#[allow(non_snake_case)] +pub fn Pattern_White_Space(c: char) -> bool { + bsearch_range_table(c, Pattern_White_Space_table) +} diff --git a/bash-5.1/vendor/serde_json/.cargo-checksum.json b/bash-5.1/vendor/serde_json/.cargo-checksum.json new file mode 100644 index 0000000..dae3b0e --- /dev/null +++ b/bash-5.1/vendor/serde_json/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"694893a6512fa3f71e7562c81366cfbbf11ea6922f5a872bc3e0f74dc6f1a936","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"ea5aacdf7067bf6e0e68ccf1b4a4a30b15af45fcfa628425b0cceee2cd632574","src/de.rs":"2bae69cb34dd06f573fc4b18c590a400802124a42e9039ee19022c6ba785ac6e","src/error.rs":"12b23907fe39540fdbeddd74f70d69671bba12060755ae5c8aff943705336899","src/lib.rs":"ec6758d1f31d9a2e9a1c2f103aa3f5536486b6a8d0357dd5137637f31d4ede61","src/macros.rs":"8f2fdf0b101ec510d4ee21169f54a6a343d68831d80d5872fd9a3d9335150dc1","src/map.rs":"a6bccaeeba053c3ef7f06cb91e2668d995629b1a6d88c6cc823ebd41d6654536","src/number.rs":"7b684584a57aaf609462a709dafa646b1efdad75c7373f8cfec8c2d2c4271e26","src/read.rs":"49b94985ebb073af0e85c222c20117f7e99d578f376b7f5b95a27d6844a00a6a","src/ser.rs":"7a575408c8e2cbb9e3fae32bc2998dd978aac7e807cfd997a85f042f9620b6f9","src/value.rs":"000475c06b3e8b80b985e8abfc473ba97060c2ff0780ad5b4d43d3802e11a612"},"package":"ad8bcf487be7d2e15d3d543f04312de991d631cfe1b43ea0ade69e6a8a5b16a1"} \ No newline at end of file diff --git a/bash-5.1/vendor/serde_json/Cargo.toml b/bash-5.1/vendor/serde_json/Cargo.toml new file mode 100644 index 0000000..3810118 --- /dev/null +++ b/bash-5.1/vendor/serde_json/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "serde_json" +version = "0.9.10" +authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"] +license = "MIT/Apache-2.0" +description = "A JSON serialization file format" +repository = "https://github.com/serde-rs/json" +documentation = "http://docs.serde.rs/serde_json/" +keywords = ["json", "serde", "serialization"] +categories = ["encoding"] +readme = "../README.md" +include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] + +[badges] +travis-ci = { repository = "serde-rs/json" } + +[features] +preserve_order = ["linked-hash-map"] + +[dependencies] +serde = "0.9.11" +num-traits = "0.1.32" +linked-hash-map = { version = "0.4.1", optional = true } +itoa = "0.3" +dtoa = "0.4" + +[dev-dependencies] +serde_derive = "0.9" diff --git a/bash-5.1/vendor/serde_json/LICENSE-APACHE b/bash-5.1/vendor/serde_json/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/serde_json/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/serde_json/LICENSE-MIT b/bash-5.1/vendor/serde_json/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/serde_json/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/serde_json/README.md b/bash-5.1/vendor/serde_json/README.md new file mode 100644 index 0000000..23a6dce --- /dev/null +++ b/bash-5.1/vendor/serde_json/README.md @@ -0,0 +1,252 @@ +# Serde JSON   [![Build Status](https://api.travis-ci.org/serde-rs/json.svg?branch=master)](https://travis-ci.org/serde-rs/json) [![Latest Version](https://img.shields.io/crates/v/serde_json.svg)](https://crates.io/crates/serde\_json) + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +```toml +[dependencies] +serde_json = "0.9" +``` + +You may be looking for: + +- [JSON API documentation](https://docs.serde.rs/serde_json/) +- [Serde API documentation](https://docs.serde.rs/serde/) +- [Detailed documentation about Serde](https://serde.rs/) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) +- [Release notes](https://github.com/serde-rs/json/releases) + +JSON is a ubiquitous open-standard format that uses human-readable text to +transmit data objects consisting of key-value pairs. + +```json,ignore +{ + "name": "John Doe", + "age": 43, + "address": { + "street": "10 Downing Street", + "city": "London" + }, + "phones": [ + "+44 1234567", + "+44 2345678" + ] +} +``` + +There are three common ways that you might find yourself needing to work +with JSON data in Rust. + + - **As text data.** An unprocessed string of JSON data that you receive on + an HTTP endpoint, read from a file, or prepare to send to a remote + server. + - **As an untyped or loosely typed representation.** Maybe you want to + check that some JSON data is valid before passing it on, but without + knowing the structure of what it contains. Or you want to do very basic + manipulations like add a level of nesting. + - **As a strongly typed Rust data structure.** When you expect all or most + of your data to conform to a particular structure and want to get real + work done without JSON's loosey-goosey nature tripping you up. + +Serde JSON provides efficient, flexible, safe ways of converting data +between each of these representations. + +## JSON to the Value enum + +Any valid JSON data can be manipulated in the following recursive enum +representation. This data structure is [`serde_json::Value`][value]. + +```rust,ignore +enum Value { + Null, + Bool(bool), + Number(Number), + String(String), + Array(Vec<Value>), + Object(Map<String, Value>), +} +``` + +A string of JSON data can be parsed into a `serde_json::Value` by the +[`serde_json::from_str`][from_str] function. There is also +[`from_slice`][from_slice] for parsing from a byte slice &[u8], +[`from_iter`][from_iter] for parsing from an iterator of bytes, and +[`from_reader`][from_reader] for parsing from any `io::Read` like a File or +a TCP stream. + +```rust +use serde_json::Value; + +let data = r#" { "name": "John Doe", "age": 43, ... } "#; +let v: Value = serde_json::from_str(data)?; +println!("Please call {} at the number {}", v["name"], v["phones"][0]); +``` + +The `Value` representation is sufficient for very basic tasks but is brittle +and tedious to work with. Error handling is verbose to implement correctly, +for example imagine trying to detect the presence of unrecognized fields in +the input data. The compiler is powerless to help you when you make a +mistake, for example imagine typoing `v["name"]` as `v["nmae"]` in one of +the dozens of places it is used in your code. + +## JSON to strongly typed data structures + +Serde provides a powerful way of mapping JSON data into Rust data structures +largely automatically. + +```rust +#[derive(Serialize, Deserialize)] +struct Person { + name: String, + age: u8, + address: Address, + phones: Vec<String>, +} + +#[derive(Serialize, Deserialize)] +struct Address { + street: String, + city: String, +} + +let data = r#" { "name": "John Doe", "age": 43, ... } "#; +let p: Person = serde_json::from_str(data)?; +println!("Please call {} at the number {}", p.name, p.phones[0]); +``` + +This is the same `serde_json::from_str` function as before, but this time we +assign the return value to a variable of type `Person` so Serde JSON will +automatically interpret the input data as a `Person` and produce informative +error messages if the layout does not conform to what a `Person` is expected +to look like. + +Any type that implements Serde's `Deserialize` trait can be deserialized +this way. This includes built-in Rust standard library types like `Vec<T>` +and `HashMap<K, V>`, as well as any structs or enums annotated with +`#[derive(Deserialize)]`. + +Once we have `p` of type `Person`, our IDE and the Rust compiler can help us +use it correctly like they do for any other Rust code. The IDE can +autocomplete field names to prevent typos, which was impossible in the +`serde_json::Value` representation. And the Rust compiler can check that +when we write `p.phones[0]`, then `p.phones` is guaranteed to be a +`Vec<String>` so indexing into it makes sense and produces a `String`. + +## Constructing JSON + +Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +objects with very natural JSON syntax. In order to use this macro, +`serde_json` needs to be imported with the `#[macro_use]` attribute. + +```rust +#[macro_use] +extern crate serde_json; + +fn main() { + // The type of `john` is `serde_json::Value` + let john = json!({ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }); + + println!("first phone number: {}", john["phones"][0]); + + // Convert to a string of JSON and print it out + println!("{}", john.to_string()); +} +``` + +The `Value::to_string()` function converts a `serde_json::Value` into a +`String` of JSON text. + +One neat thing about the `json!` macro is that variables and expressions can +be interpolated directly into the JSON value as you are building it. Serde +will check at compile time that the value you are interpolating is able to +be represented as JSON. + +```rust +let full_name = "John Doe"; +let age_last_year = 42; + +// The type of `john` is `serde_json::Value` +let john = json!({ + "name": full_name, + "age": age_last_year + 1, + "phones": [ + format!("+44 {}", random_phone()) + ] +}); +``` + +This is amazingly convenient but we have the problem we had before with +`Value` which is that the IDE and Rust compiler cannot help us if we get it +wrong. Serde JSON provides a better way of serializing strongly-typed data +structures into JSON text. + +## Serializing data structures + +A data structure can be converted to a JSON string by +[`serde_json::to_string`][to_string]. There is also +[`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and +[`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +such as a File or a TCP stream. + +```rust +#[derive(Serialize, Deserialize)] +struct Address { + street: String, + city: String, +} + +let address = Address { + street: "10 Downing Street".to_owned(), + city: "London".to_owned(), +}; + +let j = serde_json::to_string(&address)?; +``` + +Any type that implements Serde's `Serialize` trait can be serialized this +way. This includes built-in Rust standard library types like `Vec<T>` and +`HashMap<K, V>`, as well as any structs or enums annotated with +`#[derive(Serialize)]`. + +## Getting help + +Serde developers live in the #serde channel on +[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a +good resource with generally faster response time but less specific knowledge +about Serde. If IRC is not your thing, we are happy to respond to [GitHub +issues](https://github.com/serde-rs/json/issues/new) as well. + +## License + +Serde JSON is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Serde JSON by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + +[value]: https://docs.serde.rs/serde_json/value/enum.Value.html +[from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html +[from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html +[from_iter]: https://docs.serde.rs/serde_json/de/fn.from_iter.html +[from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html +[to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html +[to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html +[to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html +[macro]: https://docs.serde.rs/serde_json/macro.json.html diff --git a/bash-5.1/vendor/serde_json/src/de.rs b/bash-5.1/vendor/serde_json/src/de.rs new file mode 100644 index 0000000..b93aad7 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/de.rs @@ -0,0 +1,1091 @@ +//! Deserialize JSON data to a Rust data structure. + +use std::{i32, u64}; +use std::io; +use std::marker::PhantomData; + +use serde::de::{self, Unexpected}; + +use super::error::{Error, ErrorCode, Result}; + +use read; + +pub use read::{Read, IoRead, IteratorRead, SliceRead, StrRead}; + +////////////////////////////////////////////////////////////////////////////// + +/// A structure that deserializes JSON into Rust values. +pub struct Deserializer<R> { + read: R, + str_buf: Vec<u8>, + remaining_depth: u8, +} + +impl<R> Deserializer<R> + where R: read::Read +{ + /// Create a JSON deserializer from one of the possible serde_json input + /// sources. + /// + /// Typically it is more convenient to use one of these methods instead: + /// + /// - Deserializer::from_str + /// - Deserializer::from_bytes + /// - Deserializer::from_iter + /// - Deserializer::from_reader + pub fn new(read: R) -> Self { + Deserializer { + read: read, + str_buf: Vec::with_capacity(128), + remaining_depth: 128, + } + } +} + +impl<I> Deserializer<read::IteratorRead<I>> + where I: Iterator<Item = io::Result<u8>> +{ + /// Creates a JSON deserializer from a `std::iter::Iterator`. + pub fn from_iter(iter: I) -> Self { + Deserializer::new(read::IteratorRead::new(iter)) + } +} + +impl<R> Deserializer<read::IoRead<R>> + where R: io::Read +{ + /// Creates a JSON deserializer from an `io::Read`. + pub fn from_reader(reader: R) -> Self { + Deserializer::new(read::IoRead::new(reader)) + } +} + +impl<'a> Deserializer<read::SliceRead<'a>> { + /// Creates a JSON deserializer from a `&[u8]`. + pub fn from_slice(bytes: &'a [u8]) -> Self { + Deserializer::new(read::SliceRead::new(bytes)) + } +} + +impl<'a> Deserializer<read::StrRead<'a>> { + /// Creates a JSON deserializer from a `&str`. + pub fn from_str(s: &'a str) -> Self { + Deserializer::new(read::StrRead::new(s)) + } +} + +macro_rules! overflow { + ($a:ident * 10 + $b:ident, $c:expr) => { + $a >= $c / 10 && ($a > $c / 10 || $b > $c % 10) + } +} + +impl<R: Read> Deserializer<R> { + /// The `Deserializer::end` method should be called after a value has been fully deserialized. + /// This allows the `Deserializer` to validate that the input stream is at the end or that it + /// only has trailing whitespace. + pub fn end(&mut self) -> Result<()> { + if try!(self.parse_whitespace()) { // true if eof + Ok(()) + } else { + Err(self.peek_error(ErrorCode::TrailingCharacters)) + } + } + + /// Turn a JSON deserializer into an iterator over values of type T. + pub fn into_iter<T>(self) -> StreamDeserializer<R, T> + where T: de::Deserialize + { + // This cannot be an implementation of std::iter::IntoIterator because + // we need the caller to choose what T is. + StreamDeserializer { + de: self, + _marker: PhantomData, + } + } + + fn peek(&mut self) -> Result<Option<u8>> { + self.read.peek().map_err(Into::into) + } + + fn peek_or_null(&mut self) -> Result<u8> { + Ok(try!(self.peek()).unwrap_or(b'\x00')) + } + + fn eat_char(&mut self) { + self.read.discard(); + } + + fn next_char(&mut self) -> Result<Option<u8>> { + self.read.next().map_err(Into::into) + } + + fn next_char_or_null(&mut self) -> Result<u8> { + Ok(try!(self.next_char()).unwrap_or(b'\x00')) + } + + /// Error caused by a byte from next_char(). + fn error(&mut self, reason: ErrorCode) -> Error { + let pos = self.read.position(); + Error::syntax(reason, pos.line, pos.column) + } + + /// Error caused by a byte from peek(). + fn peek_error(&mut self, reason: ErrorCode) -> Error { + let pos = self.read.peek_position(); + Error::syntax(reason, pos.line, pos.column) + } + + /// Consume whitespace until the next non-whitespace character. + /// + /// Return `Ok(true)` if EOF was encountered in the process and `Ok(false)` otherwise. + fn parse_whitespace(&mut self) -> Result<bool> { + loop { + match try!(self.peek()) { + Some(b) => match b { + b' ' | b'\n' | b'\t' | b'\r' => { + self.eat_char(); + } + _ => { + return Ok(false); + } + }, + None => return Ok(true), + } + } + } + + fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value> + where V: de::Visitor, + { + if try!(self.parse_whitespace()) { // true if eof + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + + let value = match try!(self.peek_or_null()) { + b'n' => { + self.eat_char(); + try!(self.parse_ident(b"ull")); + visitor.visit_unit() + } + b't' => { + self.eat_char(); + try!(self.parse_ident(b"rue")); + visitor.visit_bool(true) + } + b'f' => { + self.eat_char(); + try!(self.parse_ident(b"alse")); + visitor.visit_bool(false) + } + b'-' => { + self.eat_char(); + self.parse_integer(false, visitor) + } + b'0'...b'9' => self.parse_integer(true, visitor), + b'"' => { + self.eat_char(); + self.str_buf.clear(); + let s = try!(self.read.parse_str(&mut self.str_buf)); + visitor.visit_str(s) + } + b'[' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_seq(SeqVisitor::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_seq()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + b'{' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_map(MapVisitor::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_map()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + _ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), + }; + + match value { + Ok(value) => Ok(value), + // The de::Error and From<de::value::Error> impls both create errors + // with unknown line and column. Fill in the position here by + // looking at the current index in the input. There is no way to + // tell whether this should call `error` or `peek_error` so pick the + // one that seems correct more often. Worst case, the position is + // off by one character. + Err(err) => Err(err.fix_position(|code| self.error(code))), + } + } + + fn parse_ident(&mut self, ident: &[u8]) -> Result<()> { + for c in ident { + if Some(*c) != try!(self.next_char()) { + return Err(self.error(ErrorCode::ExpectedSomeIdent)); + } + } + + Ok(()) + } + + fn parse_integer<V>(&mut self, pos: bool, visitor: V) -> Result<V::Value> + where V: de::Visitor, + { + match try!(self.next_char_or_null()) { + b'0' => { + // There can be only one leading '0'. + match try!(self.peek_or_null()) { + b'0'...b'9' => { + Err(self.peek_error(ErrorCode::InvalidNumber)) + } + _ => self.parse_number(pos, 0, visitor), + } + } + c @ b'1'...b'9' => { + let mut res = (c - b'0') as u64; + + loop { + match try!(self.peek_or_null()) { + c @ b'0'...b'9' => { + self.eat_char(); + let digit = (c - b'0') as u64; + + // We need to be careful with overflow. If we can, try to keep the + // number as a `u64` until we grow too large. At that point, switch to + // parsing the value as a `f64`. + if overflow!(res * 10 + digit, u64::MAX) { + return self.parse_long_integer(pos, + res, + 1, // res * 10^1 + visitor); + } + + res = res * 10 + digit; + } + _ => { + return self.parse_number(pos, res, visitor); + } + } + } + } + _ => Err(self.error(ErrorCode::InvalidNumber)), + } + } + + fn parse_long_integer<V>( + &mut self, + pos: bool, + significand: u64, + mut exponent: i32, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + loop { + match try!(self.peek_or_null()) { + b'0'...b'9' => { + self.eat_char(); + // This could overflow... if your integer is gigabytes long. + // Ignore that possibility. + exponent += 1; + } + b'.' => { + return self.parse_decimal(pos, significand, exponent, visitor); + } + b'e' | b'E' => { + return self.parse_exponent(pos, significand, exponent, visitor); + } + _ => { + return self.visit_f64_from_parts(pos, + significand, + exponent, + visitor); + } + } + } + } + + fn parse_number<V>( + &mut self, + pos: bool, + significand: u64, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + match try!(self.peek_or_null()) { + b'.' => self.parse_decimal(pos, significand, 0, visitor), + b'e' | b'E' => self.parse_exponent(pos, significand, 0, visitor), + _ => { + if pos { + visitor.visit_u64(significand) + } else { + let neg = (significand as i64).wrapping_neg(); + + // Convert into a float if we underflow. + if neg > 0 { + visitor.visit_f64(-(significand as f64)) + } else { + visitor.visit_i64(neg) + } + } + } + } + } + + fn parse_decimal<V>( + &mut self, + pos: bool, + mut significand: u64, + mut exponent: i32, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + self.eat_char(); + + let mut at_least_one_digit = false; + while let c @ b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + let digit = (c - b'0') as u64; + at_least_one_digit = true; + + if overflow!(significand * 10 + digit, u64::MAX) { + // The next multiply/add would overflow, so just ignore all + // further digits. + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + } + break; + } + + significand = significand * 10 + digit; + exponent -= 1; + } + + if !at_least_one_digit { + return Err(self.peek_error(ErrorCode::InvalidNumber)); + } + + match try!(self.peek_or_null()) { + b'e' | b'E' => { + self.parse_exponent(pos, significand, exponent, visitor) + } + _ => self.visit_f64_from_parts(pos, significand, exponent, visitor), + } + } + + fn parse_exponent<V>( + &mut self, + pos: bool, + significand: u64, + starting_exp: i32, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + self.eat_char(); + + let pos_exp = match try!(self.peek_or_null()) { + b'+' => { + self.eat_char(); + true + } + b'-' => { + self.eat_char(); + false + } + _ => true, + }; + + // Make sure a digit follows the exponent place. + let mut exp = match try!(self.next_char_or_null()) { + c @ b'0'...b'9' => (c - b'0') as i32, + _ => { + return Err(self.error(ErrorCode::InvalidNumber)); + } + }; + + while let c @ b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + let digit = (c - b'0') as i32; + + if overflow!(exp * 10 + digit, i32::MAX) { + return self.parse_exponent_overflow(pos, + significand, + pos_exp, + visitor); + } + + exp = exp * 10 + digit; + } + + let final_exp = if pos_exp { + starting_exp.saturating_add(exp) + } else { + starting_exp.saturating_sub(exp) + }; + + self.visit_f64_from_parts(pos, significand, final_exp, visitor) + } + + // This cold code should not be inlined into the middle of the hot + // exponent-parsing loop above. + #[cold] + #[inline(never)] + fn parse_exponent_overflow<V>( + &mut self, + pos: bool, + significand: u64, + pos_exp: bool, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + // Error instead of +/- infinity. + if significand != 0 && pos_exp { + return Err(self.error(ErrorCode::NumberOutOfRange)); + } + + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + } + visitor.visit_f64(if pos { + 0.0 + } else { + -0.0 + }) + } + + fn visit_f64_from_parts<V>( + &mut self, + pos: bool, + significand: u64, + mut exponent: i32, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + let mut f = significand as f64; + loop { + match POW10.get(exponent.abs() as usize) { + Some(&pow) => { + if exponent >= 0 { + f *= pow; + if f.is_infinite() { + return Err(self.error(ErrorCode::NumberOutOfRange)); + } + } else { + f /= pow; + } + break; + } + None => { + if f == 0.0 { + break; + } + if exponent >= 0 { + return Err(self.error(ErrorCode::NumberOutOfRange)); + } + f /= 1e308; + exponent += 308; + } + } + } + visitor.visit_f64(if pos { + f + } else { + -f + }) + } + + fn parse_object_colon(&mut self) -> Result<()> { + try!(self.parse_whitespace()); + + match try!(self.peek()) { + Some(b':') => { + self.eat_char(); + Ok(()) + } + Some(_) => Err(self.peek_error(ErrorCode::ExpectedColon)), + None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), + } + } + + fn end_seq(&mut self) -> Result<()> { + try!(self.parse_whitespace()); + + match try!(self.next_char()) { + Some(b']') => Ok(()), + Some(_) => Err(self.error(ErrorCode::TrailingCharacters)), + None => Err(self.error(ErrorCode::EofWhileParsingList)), + } + } + + fn end_map(&mut self) -> Result<()> { + try!(self.parse_whitespace()); + + match try!(self.next_char()) { + Some(b'}') => Ok(()), + Some(_) => Err(self.error(ErrorCode::TrailingCharacters)), + None => Err(self.error(ErrorCode::EofWhileParsingObject)), + } + } +} + +static POW10: [f64; 309] = + [1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009, + 1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019, + 1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029, + 1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039, + 1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049, + 1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059, + 1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069, + 1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079, + 1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089, + 1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099, + 1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109, + 1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119, + 1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129, + 1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139, + 1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149, + 1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159, + 1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169, + 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179, + 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189, + 1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199, + 1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209, + 1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219, + 1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229, + 1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239, + 1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249, + 1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259, + 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269, + 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279, + 1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289, + 1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299, + 1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308]; + +impl<'a, R: Read> de::Deserializer for &'a mut Deserializer<R> { + type Error = Error; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value> + where V: de::Visitor, + { + self.parse_value(visitor) + } + + /// Parses a `null` as a None, and any other values as a `Some(...)`. + #[inline] + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> + where V: de::Visitor, + { + try!(self.parse_whitespace()); + + match try!(self.peek_or_null()) { + b'n' => { + self.eat_char(); + try!(self.parse_ident(b"ull")); + visitor.visit_none() + } + _ => visitor.visit_some(self), + } + } + + /// Parses a newtype struct as the underlying value. + #[inline] + fn deserialize_newtype_struct<V>( + self, + _name: &str, + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + visitor.visit_newtype_struct(self) + } + + /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight + /// value, a `[..]`, or a `{..}`. + #[inline] + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + try!(self.parse_whitespace()); + + match try!(self.peek_or_null()) { + b'{' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let value = try!(visitor.visit_enum(VariantVisitor::new(self))); + + self.remaining_depth += 1; + + try!(self.parse_whitespace()); + + match try!(self.next_char_or_null()) { + b'}' => Ok(value), + _ => Err(self.error(ErrorCode::ExpectedSomeValue)), + } + } + b'"' => visitor.visit_enum(UnitVariantVisitor::new(self)), + _ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), + } + } + + /// Parses a JSON string as bytes. Note that this function does not + /// check whether the bytes represent valid unicode code points. + /// + /// The JSON specification requires that strings only contain valid + /// unicode characters. To deal with non-conforming JSON, you may use + /// this function, which attempts to parse a string without checking + /// whether the bytes represent valid unicode code points. + /// + /// Escape sequences are processed as usual, and for `\uXXXX` escapes + /// it is still checked if the hex number represents a valid unicode + /// code point. + /// + /// # Example usage + /// + /// You can use this to parse JSON strings containing non-unicode bytes: + /// + /// ``` + /// # extern crate serde; + /// # extern crate serde_json; + /// # + /// let bytes = serde::bytes::ByteBuf::from(b"some raw bytes: \xe5\x00\xe5".to_vec()); + /// let parsed = serde_json::from_slice( b"\"some raw bytes: \xe5\x00\xe5\"").unwrap(); + /// + /// assert_eq!(bytes, parsed); + /// ``` + /// + /// `\u` escape sequences with invalid unicode code points still fail to parse: + /// + /// ``` + /// # extern crate serde; + /// # extern crate serde_json; + /// # + /// let json = "\"invalid unicode surrogate: \\uD801\""; + /// let parsed: Result<serde::bytes::ByteBuf, _> = serde_json::from_str(json); + /// assert!(parsed.is_err(), "{} should not parse: {:?}", json, parsed); + /// ``` + fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> + where V: de::Visitor + { + try!(self.parse_whitespace()); + + match try!(self.peek_or_null()) { + b'"' => { + self.eat_char(); + self.str_buf.clear(); + let slice = try!(self.read.parse_str_raw(&mut self.str_buf)); + visitor.visit_bytes(slice) + } + _ => self.deserialize(visitor), + } + + } + + #[inline] + fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> + where V: de::Visitor + { + self.deserialize_bytes(visitor) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size map unit_struct tuple_struct struct + struct_field tuple ignored_any + } +} + +struct SeqVisitor<'a, R: Read + 'a> { + de: &'a mut Deserializer<R>, + first: bool, +} + +impl<'a, R: Read + 'a> SeqVisitor<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + SeqVisitor { + de: de, + first: true, + } + } +} + +impl<'a, R: Read + 'a> de::SeqVisitor for SeqVisitor<'a, R> { + type Error = Error; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> + where T: de::DeserializeSeed, + { + try!(self.de.parse_whitespace()); + + match try!(self.de.peek()) { + Some(b']') => { + return Ok(None); + } + Some(b',') if !self.first => { + self.de.eat_char(); + } + Some(_) => { + if self.first { + self.first = false; + } else { + return Err(self.de + .peek_error(ErrorCode::ExpectedListCommaOrEnd)); + } + } + None => { + return Err(self.de.peek_error(ErrorCode::EofWhileParsingList)); + } + } + + let value = try!(seed.deserialize(&mut *self.de)); + Ok(Some(value)) + } +} + +struct MapVisitor<'a, R: Read + 'a> { + de: &'a mut Deserializer<R>, + first: bool, +} + +impl<'a, R: Read + 'a> MapVisitor<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + MapVisitor { + de: de, + first: true, + } + } +} + +impl<'a, R: Read + 'a> de::MapVisitor for MapVisitor<'a, R> { + type Error = Error; + + fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> + where K: de::DeserializeSeed, + { + try!(self.de.parse_whitespace()); + + match try!(self.de.peek()) { + Some(b'}') => { + return Ok(None); + } + Some(b',') if !self.first => { + self.de.eat_char(); + try!(self.de.parse_whitespace()); + } + Some(_) => { + if self.first { + self.first = false; + } else { + return Err(self.de + .peek_error(ErrorCode::ExpectedObjectCommaOrEnd)); + } + } + None => { + return Err(self.de + .peek_error(ErrorCode::EofWhileParsingObject)); + } + } + + match try!(self.de.peek()) { + Some(b'"') => Ok(Some(try!(seed.deserialize(&mut *self.de)))), + Some(_) => Err(self.de.peek_error(ErrorCode::KeyMustBeAString)), + None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)), + } + } + + fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value> + where V: de::DeserializeSeed, + { + try!(self.de.parse_object_colon()); + + seed.deserialize(&mut *self.de) + } +} + +struct VariantVisitor<'a, R: Read + 'a> { + de: &'a mut Deserializer<R>, +} + +impl<'a, R: Read + 'a> VariantVisitor<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + VariantVisitor { + de: de, + } + } +} + +impl<'a, R: Read + 'a> de::EnumVisitor for VariantVisitor<'a, R> { + type Error = Error; + type Variant = Self; + + fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> + where V: de::DeserializeSeed, + { + let val = try!(seed.deserialize(&mut *self.de)); + try!(self.de.parse_object_colon()); + Ok((val, self)) + } +} + +impl<'a, R: Read + 'a> de::VariantVisitor for VariantVisitor<'a, R> { + type Error = Error; + + fn visit_unit(self) -> Result<()> { + de::Deserialize::deserialize(self.de) + } + + fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value> + where T: de::DeserializeSeed, + { + seed.deserialize(self.de) + } + + fn visit_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value> + where V: de::Visitor, + { + de::Deserializer::deserialize(self.de, visitor) + } + + fn visit_struct<V>( + self, + _fields: &'static [&'static str], + visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + de::Deserializer::deserialize(self.de, visitor) + } +} + +struct UnitVariantVisitor<'a, R: Read + 'a> { + de: &'a mut Deserializer<R>, +} + +impl<'a, R: Read + 'a> UnitVariantVisitor<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + UnitVariantVisitor { + de: de, + } + } +} + +impl<'a, R: Read + 'a> de::EnumVisitor for UnitVariantVisitor<'a, R> { + type Error = Error; + type Variant = Self; + + fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> + where V: de::DeserializeSeed, + { + let variant = try!(seed.deserialize(&mut *self.de)); + Ok((variant, self)) + } +} + +impl<'a, R: Read + 'a> de::VariantVisitor for UnitVariantVisitor<'a, R> { + type Error = Error; + + fn visit_unit(self) -> Result<()> { + Ok(()) + } + + fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value> + where T: de::DeserializeSeed, + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")) + } + + fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value> + where V: de::Visitor, + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant")) + } + + fn visit_struct<V>( + self, + _fields: &'static [&'static str], + _visitor: V + ) -> Result<V::Value> + where V: de::Visitor, + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant")) + } +} + +////////////////////////////////////////////////////////////////////////////// + +/// Iterator that deserializes a stream into multiple JSON values. +/// +/// A stream deserializer can be created from any JSON deserializer using the +/// `Deserializer::into_iter` method. +/// +/// ```rust +/// extern crate serde_json; +/// +/// use serde_json::{Deserializer, Value}; +/// +/// fn main() { +/// let data = "1 2 {\"k\": 3}"; +/// +/// let stream = Deserializer::from_str(data).into_iter::<Value>(); +/// +/// for value in stream { +/// println!("{}", value.unwrap()); +/// } +/// } +/// ``` +pub struct StreamDeserializer<R, T> { + de: Deserializer<R>, + _marker: PhantomData<T>, +} + +impl<R, T> StreamDeserializer<R, T> + where R: read::Read, + T: de::Deserialize +{ + /// Create a JSON stream deserializer from one of the possible serde_json + /// input sources. + /// + /// Typically it is more convenient to use one of these methods instead: + /// + /// - Deserializer::from_str(...).into_iter() + /// - Deserializer::from_bytes(...).into_iter() + /// - Deserializer::from_iter(...).into_iter() + /// - Deserializer::from_reader(...).into_iter() + pub fn new(read: R) -> Self { + StreamDeserializer { + de: Deserializer::new(read), + _marker: PhantomData, + } + } +} + +impl<R, T> Iterator for StreamDeserializer<R, T> + where R: Read, + T: de::Deserialize, +{ + type Item = Result<T>; + + fn next(&mut self) -> Option<Result<T>> { + // skip whitespaces, if any + // this helps with trailing whitespaces, since whitespaces between + // values are handled for us. + match self.de.parse_whitespace() { + Ok(true) => None, // eof + Ok(false) => { + match de::Deserialize::deserialize(&mut self.de) { + Ok(v) => Some(Ok(v)), + Err(e) => Some(Err(e)), + } + } + Err(e) => Some(Err(e)), + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +fn from_trait<R, T>(read: R) -> Result<T> + where R: Read, + T: de::Deserialize, +{ + let mut de = Deserializer::new(read); + let value = try!(de::Deserialize::deserialize(&mut de)); + + // Make sure the whole stream has been consumed. + try!(de.end()); + Ok(value) +} + +/// Deserialize an instance of type `T` from an iterator over bytes of JSON. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +pub fn from_iter<I, T>(iter: I) -> Result<T> + where I: Iterator<Item = io::Result<u8>>, + T: de::Deserialize, +{ + from_trait(read::IteratorRead::new(iter)) +} + +/// Deserialize an instance of type `T` from an IO stream of JSON. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +pub fn from_reader<R, T>(rdr: R) -> Result<T> + where R: io::Read, + T: de::Deserialize, +{ + from_iter(rdr.bytes()) +} + +/// Deserialize an instance of type `T` from bytes of JSON text. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +pub fn from_slice<T>(v: &[u8]) -> Result<T> + where T: de::Deserialize, +{ + from_trait(read::SliceRead::new(v)) +} + +/// Deserialize an instance of type `T` from a string of JSON text. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +pub fn from_str<T>(s: &str) -> Result<T> + where T: de::Deserialize, +{ + from_trait(read::StrRead::new(s)) +} diff --git a/bash-5.1/vendor/serde_json/src/error.rs b/bash-5.1/vendor/serde_json/src/error.rs new file mode 100644 index 0000000..1d5ecbf --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/error.rs @@ -0,0 +1,373 @@ +//! When serializing or deserializing JSON goes wrong. + +use std::error; +use std::fmt::{self, Debug, Display}; +use std::io; +use std::result; + +use serde::de; +use serde::ser; + +/// This type represents all possible errors that can occur when serializing or +/// deserializing JSON data. +pub struct Error { + /// This `Box` allows us to keep the size of `Error` as small as possible. A + /// larger `Error` type was substantially slower due to all the functions + /// that pass around `Result<T, Error>`. + err: Box<ErrorImpl>, +} + +/// Alias for a `Result` with the error type `serde_json::Error`. +pub type Result<T> = result::Result<T, Error>; + +impl Error { + /// One-based line number at which the error was detected. + /// + /// Characters in the first line of the input (before the first newline + /// character) are in line 1. + pub fn line(&self) -> usize { + self.err.line + } + + /// One-based column number at which the error was detected. + /// + /// The first character in the input and any characters immediately + /// following a newline character are in column 1. + /// + /// Note that errors may occur in column 0, for example if a read from an IO + /// stream fails immediately following a previously read newline character. + pub fn column(&self) -> usize { + self.err.column + } + + /// Categorizes the cause of this error. + /// + /// - `Category::Io` - failure to read or write bytes on an IO stream + /// - `Category::Syntax` - input that is not syntactically valid JSON + /// - `Category::Data` - input data that is semantically incorrect + /// - `Category::Eof` - unexpected end of the input data + pub fn classify(&self) -> Category { + match self.err.code { + ErrorCode::Message(_) => Category::Data, + ErrorCode::Io(_) => Category::Io, + ErrorCode::EofWhileParsingList | + ErrorCode::EofWhileParsingObject | + ErrorCode::EofWhileParsingString | + ErrorCode::EofWhileParsingValue => Category::Eof, + ErrorCode::ExpectedColon | + ErrorCode::ExpectedListCommaOrEnd | + ErrorCode::ExpectedObjectCommaOrEnd | + ErrorCode::ExpectedSomeIdent | + ErrorCode::ExpectedSomeValue | + ErrorCode::ExpectedSomeString | + ErrorCode::InvalidEscape | + ErrorCode::InvalidNumber | + ErrorCode::NumberOutOfRange | + ErrorCode::InvalidUnicodeCodePoint | + ErrorCode::KeyMustBeAString | + ErrorCode::LoneLeadingSurrogateInHexEscape | + ErrorCode::TrailingCharacters | + ErrorCode::UnexpectedEndOfHexEscape | + ErrorCode::RecursionLimitExceeded => Category::Syntax, + } + } + + /// Returns true if this error was caused by a failure to read or write + /// bytes on an IO stream. + pub fn is_io(&self) -> bool { + self.classify() == Category::Io + } + + /// Returns true if this error was caused by input that was not + /// syntactically valid JSON. + pub fn is_syntax(&self) -> bool { + self.classify() == Category::Syntax + } + + /// Returns true if this error was caused by input data that was + /// semantically incorrect. + /// + /// For example, JSON containing a number is semantically incorrect when the + /// type being deserialized into holds a String. + pub fn is_data(&self) -> bool { + self.classify() == Category::Data + } + + /// Returns true if this error was caused by prematurely reaching the end of + /// the input data. + /// + /// Callers that process streaming input may be interested in retrying the + /// deserialization once more data is available. + pub fn is_eof(&self) -> bool { + self.classify() == Category::Eof + } +} + +/// Categorizes the cause of a `serde_json::Error`. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum Category { + /// The error was caused by a failure to read or write bytes on an IO + /// stream. + Io, + + /// The error was caused by input that was not syntactically valid JSON. + Syntax, + + /// The error was caused by input data that was semantically incorrect. + /// + /// For example, JSON containing a number is semantically incorrect when the + /// type being deserialized into holds a String. + Data, + + /// The error was caused by prematurely reaching the end of the input data. + /// + /// Callers that process streaming input may be interested in retrying the + /// deserialization once more data is available. + Eof, +} + +#[derive(Debug)] +struct ErrorImpl { + code: ErrorCode, + line: usize, + column: usize, +} + +// Not public API. Should be pub(crate). +#[doc(hidden)] +#[derive(Debug)] +pub enum ErrorCode { + /// Catchall for syntax error messages + Message(String), + + /// Some IO error occurred while serializing or deserializing. + Io(io::Error), + + /// EOF while parsing a list. + EofWhileParsingList, + + /// EOF while parsing an object. + EofWhileParsingObject, + + /// EOF while parsing a string. + EofWhileParsingString, + + /// EOF while parsing a JSON value. + EofWhileParsingValue, + + /// Expected this character to be a `':'`. + ExpectedColon, + + /// Expected this character to be either a `','` or a `]`. + ExpectedListCommaOrEnd, + + /// Expected this character to be either a `','` or a `}`. + ExpectedObjectCommaOrEnd, + + /// Expected to parse either a `true`, `false`, or a `null`. + ExpectedSomeIdent, + + /// Expected this character to start a JSON value. + ExpectedSomeValue, + + /// Expected this character to start a JSON string. + ExpectedSomeString, + + /// Invalid hex escape code. + InvalidEscape, + + /// Invalid number. + InvalidNumber, + + /// Number is bigger than the maximum value of its type. + NumberOutOfRange, + + /// Invalid unicode code point. + InvalidUnicodeCodePoint, + + /// Object key is not a string. + KeyMustBeAString, + + /// Lone leading surrogate in hex escape. + LoneLeadingSurrogateInHexEscape, + + /// JSON has non-whitespace trailing characters after the value. + TrailingCharacters, + + /// Unexpected end of hex excape. + UnexpectedEndOfHexEscape, + + /// Encountered nesting of JSON maps and arrays more than 128 layers deep. + RecursionLimitExceeded, +} + +impl Error { + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn syntax(code: ErrorCode, line: usize, column: usize) -> Self { + Error { + err: Box::new(ErrorImpl { code: code, line: line, column: column }), + } + } + + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn fix_position<F>(self, f: F) -> Self + where F: FnOnce(ErrorCode) -> Error + { + if self.err.line == 0 { + f(self.err.code) + } else { + self + } + } +} + +impl Display for ErrorCode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + ErrorCode::Message(ref msg) => f.write_str(msg), + ErrorCode::Io(ref err) => Display::fmt(err, f), + ErrorCode::EofWhileParsingList => { + f.write_str("EOF while parsing a list") + } + ErrorCode::EofWhileParsingObject => { + f.write_str("EOF while parsing an object") + } + ErrorCode::EofWhileParsingString => { + f.write_str("EOF while parsing a string") + } + ErrorCode::EofWhileParsingValue => { + f.write_str("EOF while parsing a value") + } + ErrorCode::ExpectedColon => { + f.write_str("expected `:`") + } + ErrorCode::ExpectedListCommaOrEnd => { + f.write_str("expected `,` or `]`") + } + ErrorCode::ExpectedObjectCommaOrEnd => { + f.write_str("expected `,` or `}`") + } + ErrorCode::ExpectedSomeIdent => { + f.write_str("expected ident") + } + ErrorCode::ExpectedSomeValue => { + f.write_str("expected value") + } + ErrorCode::ExpectedSomeString => { + f.write_str("expected string") + } + ErrorCode::InvalidEscape => { + f.write_str("invalid escape") + } + ErrorCode::InvalidNumber => { + f.write_str("invalid number") + } + ErrorCode::NumberOutOfRange => { + f.write_str("number out of range") + } + ErrorCode::InvalidUnicodeCodePoint => { + f.write_str("invalid unicode code point") + } + ErrorCode::KeyMustBeAString => { + f.write_str("key must be a string") + } + ErrorCode::LoneLeadingSurrogateInHexEscape => { + f.write_str("lone leading surrogate in hex escape") + } + ErrorCode::TrailingCharacters => { + f.write_str("trailing characters") + } + ErrorCode::UnexpectedEndOfHexEscape => { + f.write_str("unexpected end of hex escape") + } + ErrorCode::RecursionLimitExceeded => { + f.write_str("recursion limit exceeded") + } + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match self.err.code { + ErrorCode::Io(ref err) => error::Error::description(err), + _ => { + // If you want a better message, use Display::fmt or to_string(). + "JSON error" + } + } + } + + fn cause(&self) -> Option<&error::Error> { + match self.err.code { + ErrorCode::Io(ref err) => Some(err), + _ => None, + } + } +} + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&*self.err, f) + } +} + +impl Display for ErrorImpl { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.line == 0 { + Display::fmt(&self.code, f) + } else { + write!(f, "{} at line {} column {}", self.code, self.line, self.column) + } + } +} + +// Remove two layers of verbosity from the debug representation. Humans often +// end up seeing this representation because it is what unwrap() shows. +impl Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&*self.err, f) + } +} + +impl From<ErrorImpl> for Error { + fn from(error: ErrorImpl) -> Error { + Error { + err: Box::new(error), + } + } +} + +impl From<io::Error> for Error { + fn from(error: io::Error) -> Error { + Error { + err: Box::new(ErrorImpl { code: ErrorCode::Io(error), line: 0, column: 0 }), + } + } +} + +impl From<de::value::Error> for Error { + fn from(error: de::value::Error) -> Error { + Error { + err: Box::new(ErrorImpl { code: ErrorCode::Message(error.to_string()), line: 0, column: 0 }), + } + } +} + +impl de::Error for Error { + fn custom<T: Display>(msg: T) -> Error { + Error { + err: Box::new(ErrorImpl { code: ErrorCode::Message(msg.to_string()), line: 0, column: 0 }), + } + } +} + +impl ser::Error for Error { + fn custom<T: Display>(msg: T) -> Error { + Error { + err: Box::new(ErrorImpl { code: ErrorCode::Message(msg.to_string()), line: 0, column: 0 }), + } + } +} diff --git a/bash-5.1/vendor/serde_json/src/lib.rs b/bash-5.1/vendor/serde_json/src/lib.rs new file mode 100644 index 0000000..2c49eb3 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/lib.rs @@ -0,0 +1,291 @@ +//! # Serde JSON +//! +//! JSON is a ubiquitous open-standard format that uses human-readable text to +//! transmit data objects consisting of key-value pairs. +//! +//! ```json,ignore +//! { +//! "name": "John Doe", +//! "age": 43, +//! "address": { +//! "street": "10 Downing Street", +//! "city": "London" +//! }, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! } +//! ``` +//! +//! There are three common ways that you might find yourself needing to work +//! with JSON data in Rust. +//! +//! - **As text data.** An unprocessed string of JSON data that you receive on +//! an HTTP endpoint, read from a file, or prepare to send to a remote +//! server. +//! - **As an untyped or loosely typed representation.** Maybe you want to +//! check that some JSON data is valid before passing it on, but without +//! knowing the structure of what it contains. Or you want to do very basic +//! manipulations like add a level of nesting. +//! - **As a strongly typed Rust data structure.** When you expect all or most +//! of your data to conform to a particular structure and want to get real +//! work done without JSON's loosey-goosey nature tripping you up. +//! +//! Serde JSON provides efficient, flexible, safe ways of converting data +//! between each of these representations. +//! +//! # JSON to the Value enum +//! +//! Any valid JSON data can be manipulated in the following recursive enum +//! representation. This data structure is [`serde_json::Value`][value]. +//! +//! ```rust +//! # use serde_json::{Number, Map}; +//! # #[allow(dead_code)] +//! enum Value { +//! Null, +//! Bool(bool), +//! Number(Number), +//! String(String), +//! Array(Vec<Value>), +//! Object(Map<String, Value>), +//! } +//! ``` +//! +//! A string of JSON data can be parsed into a `serde_json::Value` by the +//! [`serde_json::from_str`][from_str] function. There is also +//! [`from_slice`][from_slice] for parsing from a byte slice &[u8], +//! [`from_iter`][from_iter] for parsing from an iterator of bytes, and +//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or +//! a TCP stream. +//! +//! ```rust +//! # extern crate serde_json; +//! # use serde_json::Error; +//! # pub fn example() -> Result<(), Error> { +//! use serde_json::Value; +//! +//! let data = r#" { "name": "John Doe", "age": 43, ... } "#; +//! let v: Value = serde_json::from_str(data)?; +//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); +//! # Ok(()) } +//! # fn main() {} +//! ``` +//! +//! The `Value` representation is sufficient for very basic tasks but is brittle +//! and tedious to work with. Error handling is verbose to implement correctly, +//! for example imagine trying to detect the presence of unrecognized fields in +//! the input data. The compiler is powerless to help you when you make a +//! mistake, for example imagine typoing `v["name"]` as `v["nmae"]` in one of +//! the dozens of places it is used in your code. +//! +//! # JSON to strongly typed data structures +//! +//! Serde provides a powerful way of mapping JSON data into Rust data structures +//! largely automatically. +//! +//! ```rust +//! # extern crate serde_json; +//! # #[macro_use] extern crate serde_derive; +//! # use serde_json::Error; +//! # pub fn example() -> Result<(), Error> { +//! #[derive(Serialize, Deserialize)] +//! struct Person { +//! name: String, +//! age: u8, +//! address: Address, +//! phones: Vec<String>, +//! } +//! +//! #[derive(Serialize, Deserialize)] +//! struct Address { +//! street: String, +//! city: String, +//! } +//! +//! let data = r#" { "name": "John Doe", "age": 43, ... } "#; +//! let p: Person = serde_json::from_str(data)?; +//! println!("Please call {} at the number {}", p.name, p.phones[0]); +//! # Ok(()) } +//! # fn main() {} +//! ``` +//! +//! This is the same `serde_json::from_str` function as before, but this time we +//! assign the return value to a variable of type `Person` so Serde JSON will +//! automatically interpret the input data as a `Person` and produce informative +//! error messages if the layout does not conform to what a `Person` is expected +//! to look like. +//! +//! Any type that implements Serde's `Deserialize` trait can be deserialized +//! this way. This includes built-in Rust standard library types like `Vec<T>` +//! and `HashMap<K, V>`, as well as any structs or enums annotated with +//! `#[derive(Deserialize)]`. +//! +//! Once we have `p` of type `Person`, our IDE and the Rust compiler can help us +//! use it correctly like they do for any other Rust code. The IDE can +//! autocomplete field names to prevent typos, which was impossible in the +//! `serde_json::Value` representation. And the Rust compiler can check that +//! when we write `p.phones[0]`, then `p.phones` is guaranteed to be a +//! `Vec<String>` so indexing into it makes sense and produces a `String`. +//! +//! # Constructing JSON +//! +//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +//! objects with very natural JSON syntax. In order to use this macro, +//! `serde_json` needs to be imported with the `#[macro_use]` attribute. +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_json; +//! +//! fn main() { +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }); +//! +//! println!("first phone number: {}", john["phones"][0]); +//! +//! // Convert to a string of JSON and print it out +//! println!("{}", john.to_string()); +//! } +//! ``` +//! +//! The `Value::to_string()` function converts a `serde_json::Value` into a +//! `String` of JSON text. +//! +//! One neat thing about the `json!` macro is that variables and expressions can +//! be interpolated directly into the JSON value as you are building it. Serde +//! will check at compile time that the value you are interpolating is able to +//! be represented as JSON. +//! +//! ```rust +//! # #[macro_use] extern crate serde_json; +//! # fn random_phone() -> u16 { 0 } +//! # fn main() { +//! let full_name = "John Doe"; +//! let age_last_year = 42; +//! +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": full_name, +//! "age": age_last_year + 1, +//! "phones": [ +//! format!("+44 {}", random_phone()) +//! ] +//! }); +//! # let _ = john; +//! # } +//! ``` +//! +//! This is amazingly convenient but we have the problem we had before with +//! `Value` which is that the IDE and Rust compiler cannot help us if we get it +//! wrong. Serde JSON provides a better way of serializing strongly-typed data +//! structures into JSON text. +//! +//! # Serializing data structures +//! +//! A data structure can be converted to a JSON string by +//! [`serde_json::to_string`][to_string]. There is also +//! [`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and +//! [`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +//! such as a File or a TCP stream. +//! +//! ```rust +//! # extern crate serde_json; +//! # #[macro_use] extern crate serde_derive; +//! # use serde_json::Error; +//! # pub fn example() -> Result<String, Error> { +//! #[derive(Serialize, Deserialize)] +//! struct Address { +//! street: String, +//! city: String, +//! } +//! +//! let address = Address { +//! street: "10 Downing Street".to_owned(), +//! city: "London".to_owned(), +//! }; +//! +//! let j = serde_json::to_string(&address)?; +//! # Ok(j) } +//! # fn main() {} +//! ``` +//! +//! Any type that implements Serde's `Serialize` trait can be serialized this +//! way. This includes built-in Rust standard library types like `Vec<T>` and +//! `HashMap<K, V>`, as well as any structs or enums annotated with +//! `#[derive(Serialize)]`. +//! +//! [value]: https://docs.serde.rs/serde_json/value/enum.Value.html +//! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html +//! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html +//! [from_iter]: https://docs.serde.rs/serde_json/de/fn.from_iter.html +//! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html +//! [to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html +//! [to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html +//! [to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html +//! [macro]: https://docs.serde.rs/serde_json/macro.json.html + +#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] +// Because of "JavaScript"... fixed in Manishearth/rust-clippy#1071 +#![cfg_attr(feature = "cargo-clippy", allow(doc_markdown))] +// Whitelisted clippy_pedantic lints +#![cfg_attr(feature = "cargo-clippy", allow( +// Deserializer::from_str, from_iter, into_iter + should_implement_trait, +// integer and float ser/de requires these sorts of casts + cast_possible_truncation, + cast_possible_wrap, + cast_precision_loss, + cast_sign_loss, +// string ser/de uses indexing and slicing + indexing_slicing, +// things are often more readable this way + shadow_reuse, + shadow_unrelated, + single_match_else, + stutter, +// not practical + missing_docs_in_private_items, +))] + +#![deny(missing_docs)] + +extern crate num_traits; +extern crate core; +#[macro_use] +extern crate serde; +extern crate itoa; +extern crate dtoa; +#[cfg(feature = "preserve_order")] +extern crate linked_hash_map; + +#[doc(inline)] +pub use self::de::{Deserializer, StreamDeserializer, from_iter, from_reader, + from_slice, from_str}; +#[doc(inline)] +pub use self::error::{Error, Result}; +#[doc(inline)] +pub use self::ser::{Serializer, to_string, to_string_pretty, to_vec, + to_vec_pretty, to_writer, to_writer_pretty}; +#[doc(inline)] +pub use self::value::{Map, Number, Value, from_value, to_value}; + +#[macro_use] +mod macros; + +pub mod de; +pub mod error; +pub mod map; +pub mod ser; +pub mod value; + +mod number; +mod read; diff --git a/bash-5.1/vendor/serde_json/src/macros.rs b/bash-5.1/vendor/serde_json/src/macros.rs new file mode 100644 index 0000000..4145737 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/macros.rs @@ -0,0 +1,271 @@ +/// Construct a `serde_json::Value` from a JSON literal. +/// +/// ```rust +/// # #![allow(unused_variables)] +/// # #[macro_use] extern crate serde_json; +/// # fn main() { +/// let value = json!({ +/// "code": 200, +/// "success": true, +/// "payload": { +/// "features": [ +/// "serde", +/// "json" +/// ] +/// } +/// }); +/// # } +/// ``` +/// +/// Variables or expressions can be interpolated into the JSON literal. Any type +/// interpolated into an array element or object value must implement Serde's +/// `Serialize` trait, while any type interpolated into a object key must +/// implement `Into<String>`. If the `Serialize` implementation of the +/// interpolated type decides to fail, or if the interpolated type contains a +/// map with non-string keys, the `json!` macro will panic. +/// +/// ```rust +/// # #![allow(unused_variables)] +/// # #[macro_use] extern crate serde_json; +/// # fn main() { +/// let code = 200; +/// let features = vec!["serde", "json"]; +/// +/// let value = json!({ +/// "code": code, +/// "success": code == 200, +/// "payload": { +/// features[0]: features[1] +/// } +/// }); +/// # } +/// ``` +/// +/// Trailing commas are allowed inside both arrays and objects. +/// +/// ```rust +/// # #![allow(unused_variables)] +/// # #[macro_use] extern crate serde_json; +/// # fn main() { +/// let value = json!([ +/// "notice", +/// "the", +/// "trailing", +/// "comma -->", +/// ]); +/// # } +/// ``` +#[macro_export] +macro_rules! json { + // Hide distracting implementation details from the generated rustdoc. + ($($json:tt)+) => { + json_internal!($($json)+) + }; +} + +// Rocket relies on this because they export their own `json!` with a different +// doc comment than ours, and various Rust bugs prevent them from calling our +// `json!` from their `json!` so they call `json_internal!` directly. Check with +// @SergioBenitez before making breaking changes to this macro. +// +// Changes are fine as long as `json_internal!` does not call any new helper +// macros and can still be invoked as `json_internal!($($json)+)`. +#[macro_export] +#[doc(hidden)] +macro_rules! json_internal { + ////////////////////////////////////////////////////////////////////////// + // TT muncher for parsing the inside of an array [...]. Produces a vec![...] + // of the elements. + // + // Must be invoked as: json_internal!(@array [] $($tt)*) + ////////////////////////////////////////////////////////////////////////// + + // Done with trailing comma. + (@array [$($elems:expr,)*]) => { + vec![$($elems,)*] + }; + + // Done without trailing comma. + (@array [$($elems:expr),*]) => { + vec![$($elems),*] + }; + + // Next element is `null`. + (@array [$($elems:expr,)*] null $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!(null)] $($rest)*) + }; + + // Next element is `true`. + (@array [$($elems:expr,)*] true $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!(true)] $($rest)*) + }; + + // Next element is `false`. + (@array [$($elems:expr,)*] false $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!(false)] $($rest)*) + }; + + // Next element is an array. + (@array [$($elems:expr,)*] [$($array:tt)*] $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!([$($array)*])] $($rest)*) + }; + + // Next element is a map. + (@array [$($elems:expr,)*] {$($map:tt)*} $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!({$($map)*})] $($rest)*) + }; + + // Next element is an expression followed by comma. + (@array [$($elems:expr,)*] $next:expr, $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!($next),] $($rest)*) + }; + + // Last element is an expression with no trailing comma. + (@array [$($elems:expr,)*] $last:expr) => { + json_internal!(@array [$($elems,)* json_internal!($last)]) + }; + + // Comma after the most recent element. + (@array [$($elems:expr),*] , $($rest:tt)*) => { + json_internal!(@array [$($elems,)*] $($rest)*) + }; + + ////////////////////////////////////////////////////////////////////////// + // TT muncher for parsing the inside of an object {...}. Each entry is + // inserted into the given map variable. + // + // Must be invoked as: json_internal!(@object $map () ($($tt)*) ($($tt)*)) + // + // We require two copies of the input tokens so that we can match on one + // copy and trigger errors on the other copy. + ////////////////////////////////////////////////////////////////////////// + + // Done. + (@object $object:ident () () ()) => {}; + + // Insert the current entry followed by trailing comma. + (@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => { + $object.insert(($($key)+).into(), $value); + json_internal!(@object $object () ($($rest)*) ($($rest)*)); + }; + + // Insert the last entry without trailing comma. + (@object $object:ident [$($key:tt)+] ($value:expr)) => { + $object.insert(($($key)+).into(), $value); + }; + + // Next value is `null`. + (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!(null)) $($rest)*); + }; + + // Next value is `true`. + (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!(true)) $($rest)*); + }; + + // Next value is `false`. + (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!(false)) $($rest)*); + }; + + // Next value is an array. + (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!([$($array)*])) $($rest)*); + }; + + // Next value is a map. + (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!({$($map)*})) $($rest)*); + }; + + // Next value is an expression followed by comma. + (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!($value)) , $($rest)*); + }; + + // Last value is an expression with no trailing comma. + (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!($value))); + }; + + // Missing value for last entry. Trigger a reasonable error message. + (@object $object:ident ($($key:tt)+) (:) $copy:tt) => { + // "unexpected end of macro invocation" + json_internal!(); + }; + + // Missing colon and value for last entry. Trigger a reasonable error + // message. + (@object $object:ident ($($key:tt)+) () $copy:tt) => { + // "unexpected end of macro invocation" + json_internal!(); + }; + + // Misplaced colon. Trigger a reasonable error message. + (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => { + // Takes no arguments so "no rules expected the token `:`". + unimplemented!($colon); + }; + + // Found a comma inside a key. Trigger a reasonable error message. + (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => { + // Takes no arguments so "no rules expected the token `,`". + unimplemented!($comma); + }; + + // Key is fully parenthesized. This avoids clippy double_parens false + // positives because the parenthesization may be necessary here. + (@object $object:ident () (($key:expr) : $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*)); + }; + + // Munch a token into the current key. + (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*)); + }; + + ////////////////////////////////////////////////////////////////////////// + // The main implementation. + // + // Must be invoked as: json_internal!($($json)+) + ////////////////////////////////////////////////////////////////////////// + + (null) => { + $crate::Value::Null + }; + + (true) => { + $crate::Value::Bool(true) + }; + + (false) => { + $crate::Value::Bool(false) + }; + + ([]) => { + $crate::Value::Array(vec![]) + }; + + ([ $($tt:tt)+ ]) => { + $crate::Value::Array(json_internal!(@array [] $($tt)+)) + }; + + ({}) => { + $crate::Value::Object($crate::Map::new()) + }; + + ({ $($tt:tt)+ }) => { + $crate::Value::Object({ + let mut object = $crate::Map::new(); + json_internal!(@object object () ($($tt)+) ($($tt)+)); + object + }) + }; + + // Any Serialize type: numbers, strings, struct literals, variables etc. + // Must be below every other rule. + ($other:expr) => { + $crate::value::ToJson::to_json(&$other).unwrap() + }; +} diff --git a/bash-5.1/vendor/serde_json/src/map.rs b/bash-5.1/vendor/serde_json/src/map.rs new file mode 100644 index 0000000..d6493eb --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/map.rs @@ -0,0 +1,775 @@ +//! A map of String to serde_json::Value. +//! +//! By default the map is backed by a BTreeMap. Enable the `preserve_order` +//! feature of serde_json to use LinkedHashMap instead. + +use serde::{ser, de}; +use std::fmt::{self, Debug}; +use value::Value; +use std::hash::Hash; +use std::iter::FromIterator; +use std::borrow::Borrow; +use std::ops; + +#[cfg(not(feature = "preserve_order"))] +use std::collections::{BTreeMap, btree_map}; + +#[cfg(feature = "preserve_order")] +use linked_hash_map::{self, LinkedHashMap}; + +/// Represents a JSON key/value type. +pub struct Map<K, V> { + map: MapImpl<K, V>, +} + +#[cfg(not(feature = "preserve_order"))] +type MapImpl<K, V> = BTreeMap<K, V>; +#[cfg(feature = "preserve_order")] +type MapImpl<K, V> = LinkedHashMap<K, V>; + +impl Map<String, Value> { + /// Makes a new empty Map. + #[inline] + pub fn new() -> Self { + Map { + map: MapImpl::new(), + } + } + + #[cfg(not(feature = "preserve_order"))] + /// Makes a new empty Map with the given initial capacity. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + // does not support with_capacity + let _ = capacity; + Map { + map: BTreeMap::new(), + } + } + + #[cfg(feature = "preserve_order")] + /// Makes a new empty Map with the given initial capacity. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Map { + map: LinkedHashMap::with_capacity(capacity), + } + } + + /// Clears the map, removing all values. + #[inline] + pub fn clear(&mut self) { + self.map.clear() + } + + /// Returns a reference to the value corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&Value> + where String: Borrow<Q>, + Q: Ord + Eq + Hash + { + self.map.get(key) + } + + /// Returns true if the map contains a value for the specified key. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool + where String: Borrow<Q>, + Q: Ord + Eq + Hash + { + self.map.contains_key(key) + } + + /// Returns a mutable reference to the value corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut Value> + where String: Borrow<Q>, + Q: Ord + Eq + Hash + { + self.map.get_mut(key) + } + + /// Inserts a key-value pair into the map. + /// + /// If the map did not have this key present, `None` is returned. + /// + /// If the map did have this key present, the value is updated, and the old + /// value is returned. The key is not updated, though; this matters for + /// types that can be `==` without being identical. + #[inline] + pub fn insert(&mut self, k: String, v: Value) -> Option<Value> { + self.map.insert(k, v) + } + + /// Removes a key from the map, returning the value at the key if the key + /// was previously in the map. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Value> + where String: Borrow<Q>, + Q: Ord + Eq + Hash + { + self.map.remove(key) + } + + /// Gets the given key's corresponding entry in the map for in-place + /// manipulation. + pub fn entry<S>(&mut self, key: S) -> Entry + where S: Into<String> + { + #[cfg(not(feature = "preserve_order"))] + use std::collections::btree_map::Entry as EntryImpl; + #[cfg(feature = "preserve_order")] + use linked_hash_map::Entry as EntryImpl; + + match self.map.entry(key.into()) { + EntryImpl::Vacant(vacant) => { + Entry::Vacant(VacantEntry { vacant: vacant }) + } + EntryImpl::Occupied(occupied) => { + Entry::Occupied(OccupiedEntry { occupied: occupied }) + } + } + } + + /// Returns the number of elements in the map. + #[inline] + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns true if the map contains no elements. + #[inline] + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + /// Gets an iterator over the entries of the map. + #[inline] + pub fn iter(&self) -> Iter { + Iter { + iter: self.map.iter(), + } + } + + /// Gets a mutable iterator over the entries of the map. + #[inline] + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + iter: self.map.iter_mut(), + } + } + + /// Gets an iterator over the keys of the map. + #[inline] + pub fn keys(&self) -> Keys { + Keys { + iter: self.map.keys(), + } + } + + /// Gets an iterator over the values of the map. + #[inline] + pub fn values(&self) -> Values { + Values { + iter: self.map.values(), + } + } +} + +impl Default for Map<String, Value> { + #[inline] + fn default() -> Self { + Map { + map: MapImpl::new(), + } + } +} + +impl Clone for Map<String, Value> { + #[inline] + fn clone(&self) -> Self { + Map { + map: self.map.clone(), + } + } +} + +impl PartialEq for Map<String, Value> { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.map.eq(&other.map) + } +} + +/// Access an element of this map. Panics if the given key is not present in the +/// map. +/// +/// ```rust +/// # use serde_json::Value; +/// # let val = &Value::String("".to_owned()); +/// # let _ = +/// match *val { +/// Value::String(ref s) => Some(s.as_str()), +/// Value::Array(ref arr) => arr[0].as_str(), +/// Value::Object(ref map) => map["type"].as_str(), +/// _ => None, +/// } +/// # ; +/// ``` +impl<'a, Q: ?Sized> ops::Index<&'a Q> for Map<String, Value> + where String: Borrow<Q>, + Q: Ord + Eq + Hash +{ + type Output = Value; + + fn index(&self, index: &Q) -> &Value { + self.map.index(index) + } +} + +/// Mutably access an element of this map. Panics if the given key is not +/// present in the map. +/// +/// ```rust +/// # #[macro_use] extern crate serde_json; +/// # fn main() { +/// # let mut map = serde_json::Map::new(); +/// # map.insert("key".to_owned(), serde_json::Value::Null); +/// map["key"] = json!("value"); +/// # } +/// ``` +impl<'a, Q: ?Sized> ops::IndexMut<&'a Q> for Map<String, Value> + where String: Borrow<Q>, + Q: Ord + Eq + Hash +{ + fn index_mut(&mut self, index: &Q) -> &mut Value { + self.map.get_mut(index).expect("no entry found for key") + } +} + +impl Debug for Map<String, Value> { + #[inline] + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + self.map.fmt(formatter) + } +} + +impl ser::Serialize for Map<String, Value> { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: ser::Serializer + { + use serde::ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(self.len()))); + for (k, v) in self { + try!(map.serialize_key(k)); + try!(map.serialize_value(v)); + } + map.end() + } +} + +impl de::Deserialize for Map<String, Value> { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where D: de::Deserializer + { + struct Visitor; + + impl de::Visitor for Visitor { + type Value = Map<String, Value>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map") + } + + #[inline] + fn visit_unit<E>(self) -> Result<Self::Value, E> + where E: de::Error + { + Ok(Map::new()) + } + + #[inline] + fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where V: de::MapVisitor + { + let mut values = Map::with_capacity(visitor.size_hint().0); + + while let Some((key, value)) = try!(visitor.visit()) { + values.insert(key, value); + } + + Ok(values) + } + } + + deserializer.deserialize_map(Visitor) + } +} + +impl FromIterator<(String, Value)> for Map<String, Value> { + fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=(String, Value)> { + Map { + map: FromIterator::from_iter(iter) + } + } +} + +impl Extend<(String, Value)> for Map<String, Value> { + fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=(String, Value)> { + self.map.extend(iter); + } +} + +macro_rules! delegate_iterator { + (($name:ident $($generics:tt)*) => $item:ty) => { + impl $($generics)* Iterator for $name $($generics)* { + type Item = $item; + #[inline] + fn next(&mut self) -> Option<Self::Item> { + self.iter.next() + } + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } + } + + impl $($generics)* DoubleEndedIterator for $name $($generics)* { + #[inline] + fn next_back(&mut self) -> Option<Self::Item> { + self.iter.next_back() + } + } + + impl $($generics)* ExactSizeIterator for $name $($generics)* { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +/// A view into a single entry in a map, which may either be vacant or occupied. +/// This enum is constructed from the [`entry`] method on [`Map`]. +/// +/// [`entry`]: struct.Map.html#method.entry +/// [`BTreeMap`]: struct.Map.html +pub enum Entry<'a> { + /// A vacant Entry. + Vacant(VacantEntry<'a>), + /// An occupied Entry. + Occupied(OccupiedEntry<'a>), +} + +/// A vacant Entry. It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +pub struct VacantEntry<'a> { + vacant: VacantEntryImpl<'a>, +} + +/// An occupied Entry. It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +pub struct OccupiedEntry<'a> { + occupied: OccupiedEntryImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type VacantEntryImpl<'a> = linked_hash_map::VacantEntry<'a, String, Value>; + +#[cfg(not(feature = "preserve_order"))] +type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type OccupiedEntryImpl<'a> = linked_hash_map::OccupiedEntry<'a, String, Value>; + +impl<'a> Entry<'a> { + /// Returns a reference to this entry's key. + /// + /// # Examples + /// + /// ```rust + /// let mut map = serde_json::Map::new(); + /// assert_eq!(map.entry("serde").key(), &"serde"); + /// ``` + pub fn key(&self) -> &String { + match *self { + Entry::Vacant(ref e) => e.key(), + Entry::Occupied(ref e) => e.key(), + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and + /// returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let mut map = serde_json::Map::new(); + /// map.entry("serde").or_insert(json!(12)); + /// + /// assert_eq!(map["serde"], 12); + /// # } + /// ``` + pub fn or_insert(self, default: Value) -> &'a mut Value { + match self { + Entry::Vacant(entry) => entry.insert(default.into()), + Entry::Occupied(entry) => entry.into_mut(), + } + } + + /// Ensures a value is in the entry by inserting the result of the default + /// function if empty, and returns a mutable reference to the value in the + /// entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let mut map = serde_json::Map::new(); + /// map.entry("serde").or_insert_with(|| json!("hoho")); + /// + /// assert_eq!(map["serde"], "hoho".to_owned()); + /// # } + /// ``` + pub fn or_insert_with<F>(self, default: F) -> &'a mut Value + where F: FnOnce() -> Value + { + match self { + Entry::Vacant(entry) => entry.insert(default()), + Entry::Occupied(entry) => entry.into_mut(), + } + } +} + +impl<'a> VacantEntry<'a> { + /// Gets a reference to the key that would be used when inserting a value + /// through the VacantEntry. + /// + /// # Examples + /// + /// ```rust + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// + /// match map.entry("serde") { + /// Entry::Vacant(vacant) => { + /// assert_eq!(vacant.key(), &"serde"); + /// } + /// Entry::Occupied(_) => unimplemented!(), + /// } + /// ``` + #[inline] + pub fn key(&self) -> &String { + self.vacant.key() + } + + /// Sets the value of the entry with the VacantEntry's key, and returns a + /// mutable reference to it. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// + /// match map.entry("serde") { + /// Entry::Vacant(vacant) => { + /// vacant.insert(json!("hoho")); + /// } + /// Entry::Occupied(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn insert(self, value: Value) -> &'a mut Value { + self.vacant.insert(value.into()) + } +} + +impl<'a> OccupiedEntry<'a> { + /// Gets a reference to the key in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(occupied) => { + /// assert_eq!(occupied.key(), &"serde"); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn key(&self) -> &String { + self.occupied.key() + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(occupied) => { + /// assert_eq!(occupied.get(), 12); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn get(&self) -> &Value { + self.occupied.get() + } + + /// Gets a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!([1, 2, 3])); + /// + /// match map.entry("serde") { + /// Entry::Occupied(mut occupied) => { + /// occupied.get_mut().as_array_mut().unwrap().push(json!(4)); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// + /// assert_eq!(map["serde"].as_array().unwrap().len(), 4); + /// # } + /// ``` + #[inline] + pub fn get_mut(&mut self) -> &mut Value { + self.occupied.get_mut() + } + + /// Converts the entry into a mutable reference to its value. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!([1, 2, 3])); + /// + /// match map.entry("serde") { + /// Entry::Occupied(mut occupied) => { + /// occupied.into_mut().as_array_mut().unwrap().push(json!(4)); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// + /// assert_eq!(map["serde"].as_array().unwrap().len(), 4); + /// # } + /// ``` + #[inline] + pub fn into_mut(self) -> &'a mut Value { + self.occupied.into_mut() + } + + /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns + /// the entry's old value. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(mut occupied) => { + /// assert_eq!(occupied.insert(json!(13)), 12); + /// assert_eq!(occupied.get(), 13); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn insert(&mut self, value: Value) -> Value { + self.occupied.insert(value.into()) + } + + /// Takes the value of the entry out of the map, and returns it. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(occupied) => { + /// assert_eq!(occupied.remove(), 12); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn remove(self) -> Value { + self.occupied.remove() + } +} + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> IntoIterator for &'a Map<String, Value> { + type Item = (&'a String, &'a Value); + type IntoIter = Iter<'a>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + Iter { + iter: self.map.iter(), + } + } +} + +/// An iterator over a serde_json::Map's entries. +pub struct Iter<'a> { + iter: IterImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type IterImpl<'a> = btree_map::Iter<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type IterImpl<'a> = linked_hash_map::Iter<'a, String, Value>; + +delegate_iterator!((Iter<'a>) => (&'a String, &'a Value)); + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> IntoIterator for &'a mut Map<String, Value> { + type Item = (&'a String, &'a mut Value); + type IntoIter = IterMut<'a>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IterMut { + iter: self.map.iter_mut(), + } + } +} + +/// A mutable iterator over a serde_json::Map's entries. +pub struct IterMut<'a> { + iter: IterMutImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type IterMutImpl<'a> = linked_hash_map::IterMut<'a, String, Value>; + +delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value)); + +////////////////////////////////////////////////////////////////////////////// + +impl IntoIterator for Map<String, Value> { + type Item = (String, Value); + type IntoIter = IntoIter; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IntoIter { + iter: self.map.into_iter(), + } + } +} + +/// An owning iterator over a serde_json::Map's entries. +pub struct IntoIter { + iter: IntoIterImpl, +} + +#[cfg(not(feature = "preserve_order"))] +type IntoIterImpl = btree_map::IntoIter<String, Value>; +#[cfg(feature = "preserve_order")] +type IntoIterImpl = linked_hash_map::IntoIter<String, Value>; + +delegate_iterator!((IntoIter) => (String, Value)); + +////////////////////////////////////////////////////////////////////////////// + +/// An iterator over a serde_json::Map's keys. +pub struct Keys<'a> { + iter: KeysImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type KeysImpl<'a> = btree_map::Keys<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type KeysImpl<'a> = linked_hash_map::Keys<'a, String, Value>; + +delegate_iterator!((Keys<'a>) => &'a String); + +////////////////////////////////////////////////////////////////////////////// + +/// An iterator over a serde_json::Map's values. +pub struct Values<'a> { + iter: ValuesImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type ValuesImpl<'a> = btree_map::Values<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type ValuesImpl<'a> = linked_hash_map::Values<'a, String, Value>; + +delegate_iterator!((Values<'a>) => &'a Value); diff --git a/bash-5.1/vendor/serde_json/src/number.rs b/bash-5.1/vendor/serde_json/src/number.rs new file mode 100644 index 0000000..ff401d9 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/number.rs @@ -0,0 +1,235 @@ +use error::Error; +use num_traits::NumCast; +use serde::de::{self, Visitor}; +use serde::{Serialize, Serializer, Deserialize, Deserializer}; +use std::fmt::{self, Debug, Display}; +use std::i64; + +/// Represents a JSON number, whether integer or floating point. +#[derive(Clone, PartialEq)] +pub struct Number { + n: N, +} + +// "N" is a prefix of "NegInt"... this is a false positive. +// https://github.com/Manishearth/rust-clippy/issues/1241 +#[cfg_attr(feature = "cargo-clippy", allow(enum_variant_names))] +#[derive(Copy, Clone, Debug, PartialEq)] +enum N { + PosInt(u64), + /// Always less than zero. + NegInt(i64), + /// Always finite. + Float(f64), +} + +impl Number { + /// Returns `true` if the number can be represented as `i64`. + #[inline] + pub fn is_i64(&self) -> bool { + match self.n { + N::PosInt(v) => v <= i64::MAX as u64, + N::NegInt(_) => true, + N::Float(_) => false, + } + } + + /// Returns `true` if the number can be represented as `u64`. + #[inline] + pub fn is_u64(&self) -> bool { + match self.n { + N::PosInt(_) => true, + N::NegInt(_) | N::Float(_) => false, + } + } + + /// Returns `true` if the number can be represented as `f64`. + #[inline] + pub fn is_f64(&self) -> bool { + match self.n { + N::Float(_) => true, + N::PosInt(_) | N::NegInt(_) => false, + } + } + + /// Returns the number represented as `i64` if possible, or else `None`. + #[inline] + pub fn as_i64(&self) -> Option<i64> { + match self.n { + N::PosInt(n) => NumCast::from(n), + N::NegInt(n) => Some(n), + N::Float(_) => None, + } + } + + /// Returns the number represented as `u64` if possible, or else `None`. + #[inline] + pub fn as_u64(&self) -> Option<u64> { + match self.n { + N::PosInt(n) => Some(n), + N::NegInt(n) => NumCast::from(n), + N::Float(_) => None, + } + } + + /// Returns the number represented as `f64` if possible, or else `None`. + #[inline] + pub fn as_f64(&self) -> Option<f64> { + match self.n { + N::PosInt(n) => NumCast::from(n), + N::NegInt(n) => NumCast::from(n), + N::Float(n) => Some(n), + } + } + + /// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON + /// numbers. + #[inline] + pub fn from_f64(f: f64) -> Option<Number> { + if f.is_finite() { + Some(Number { n: N::Float(f) }) + } else { + None + } + } +} + +impl fmt::Display for Number { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.n { + N::PosInt(i) => Display::fmt(&i, formatter), + N::NegInt(i) => Display::fmt(&i, formatter), + N::Float(f) => Display::fmt(&f, formatter), + } + } +} + +impl Debug for Number { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.n, formatter) + } +} + +impl Serialize for Number { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: Serializer + { + match self.n { + N::PosInt(i) => serializer.serialize_u64(i), + N::NegInt(i) => serializer.serialize_i64(i), + N::Float(f) => serializer.serialize_f64(f), + } + } +} + +impl Deserialize for Number { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Number, D::Error> + where D: Deserializer + { + struct NumberVisitor; + + impl Visitor for NumberVisitor { + type Value = Number; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a number") + } + + #[inline] + fn visit_i64<E>(self, value: i64) -> Result<Number, E> { + Ok(value.into()) + } + + #[inline] + fn visit_u64<E>(self, value: u64) -> Result<Number, E> { + Ok(value.into()) + } + + #[inline] + fn visit_f64<E>(self, value: f64) -> Result<Number, E> + where E: de::Error + { + Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number")) + } + } + + deserializer.deserialize(NumberVisitor) + } +} + +impl Deserializer for Number { + type Error = Error; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where V: Visitor + { + match self.n { + N::PosInt(i) => visitor.visit_u64(i), + N::NegInt(i) => visitor.visit_i64(i), + N::Float(f) => visitor.visit_f64(f), + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl<'a> Deserializer for &'a Number { + type Error = Error; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where V: Visitor + { + match self.n { + N::PosInt(i) => visitor.visit_u64(i), + N::NegInt(i) => visitor.visit_i64(i), + N::Float(f) => visitor.visit_f64(f), + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +macro_rules! from_signed { + ($($signed_ty:ident)*) => { + $( + impl From<$signed_ty> for Number { + #[inline] + fn from(i: $signed_ty) -> Self { + if i < 0 { + Number { n: N::NegInt(i as i64) } + } else { + Number { n: N::PosInt(i as u64) } + } + } + } + )* + }; +} + +macro_rules! from_unsigned { + ($($unsigned_ty:ident)*) => { + $( + impl From<$unsigned_ty> for Number { + #[inline] + fn from(u: $unsigned_ty) -> Self { + Number { n: N::PosInt(u as u64) } + } + } + )* + }; +} + +from_signed!(i8 i16 i32 i64 isize); +from_unsigned!(u8 u16 u32 u64 usize); diff --git a/bash-5.1/vendor/serde_json/src/read.rs b/bash-5.1/vendor/serde_json/src/read.rs new file mode 100644 index 0000000..a352b20 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/read.rs @@ -0,0 +1,624 @@ +use std::{char, cmp, io, str}; + +use serde::iter::LineColIterator; + +use super::error::{Error, ErrorCode, Result}; + +/// Trait used by the deserializer for iterating over input. This is manually +/// "specialized" for iterating over &[u8]. Once feature(specialization) is +/// stable we can use actual specialization. +/// +/// This trait is sealed and cannot be implemented for types outside of +/// `serde_json`. +pub trait Read: private::Sealed { + #[doc(hidden)] + fn next(&mut self) -> io::Result<Option<u8>>; + #[doc(hidden)] + fn peek(&mut self) -> io::Result<Option<u8>>; + + /// Only valid after a call to peek(). Discards the peeked byte. + #[doc(hidden)] + fn discard(&mut self); + + /// Position of the most recent call to next(). + /// + /// The most recent call was probably next() and not peek(), but this method + /// should try to return a sensible result if the most recent call was + /// actually peek() because we don't always know. + /// + /// Only called in case of an error, so performance is not important. + #[doc(hidden)] + fn position(&self) -> Position; + + /// Position of the most recent call to peek(). + /// + /// The most recent call was probably peek() and not next(), but this method + /// should try to return a sensible result if the most recent call was + /// actually next() because we don't always know. + /// + /// Only called in case of an error, so performance is not important. + #[doc(hidden)] + fn peek_position(&self) -> Position; + + /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped + /// string until the next quotation mark using the given scratch space if + /// necessary. The scratch space is initially empty. + #[doc(hidden)] + fn parse_str<'s>( + &'s mut self, + scratch: &'s mut Vec<u8>, + ) -> Result<&'s str>; + + /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped + /// string until the next quotation mark using the given scratch space if + /// necessary. The scratch space is initially empty. + /// + /// This function returns the raw bytes in the string with escape sequences + /// expanded but without performing unicode validation. + #[doc(hidden)] + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s [u8]>; +} + +pub struct Position { + pub line: usize, + pub column: usize, +} + +/// JSON input source that reads from an iterator of bytes. +pub struct IteratorRead<Iter> + where Iter: Iterator<Item = io::Result<u8>>, +{ + iter: LineColIterator<Iter>, + /// Temporary storage of peeked byte. + ch: Option<u8>, +} + +/// JSON input source that reads from a std::io input stream. +pub struct IoRead<R> + where R: io::Read +{ + delegate: IteratorRead<io::Bytes<R>>, +} + +/// JSON input source that reads from a slice of bytes. +// +// This is more efficient than other iterators because peek() can be read-only +// and we can compute line/col position only if an error happens. +pub struct SliceRead<'a> { + slice: &'a [u8], + /// Index of the *next* byte that will be returned by next() or peek(). + index: usize, +} + +/// JSON input source that reads from a UTF-8 string. +// +// Able to elide UTF-8 checks by assuming that the input is valid UTF-8. +pub struct StrRead<'a> { + delegate: SliceRead<'a>, +} + +// Prevent users from implementing the Read trait. +mod private { + pub trait Sealed {} +} + +////////////////////////////////////////////////////////////////////////////// + +impl<Iter> IteratorRead<Iter> + where Iter: Iterator<Item = io::Result<u8>>, +{ + /// Create a JSON input source to read from an iterator of bytes. + pub fn new(iter: Iter) -> Self { + IteratorRead { + iter: LineColIterator::new(iter), + ch: None, + } + } +} + +impl<Iter> private::Sealed for IteratorRead<Iter> + where Iter: Iterator<Item = io::Result<u8>> {} + +impl<Iter> IteratorRead<Iter> + where Iter: Iterator<Item = io::Result<u8>> +{ + fn parse_str_bytes<'s, T, F>( + &'s mut self, + scratch: &'s mut Vec<u8>, + validate: bool, + result: F + ) -> Result<T> + where T: 's, + F: FnOnce(&'s Self, &'s [u8]) -> Result<T>, + { + loop { + let ch = try!(next_or_eof(self)); + if !ESCAPE[ch as usize] { + scratch.push(ch); + continue; + } + match ch { + b'"' => { + return result(self, scratch); + } + b'\\' => { + try!(parse_escape(self, scratch)); + } + _ => { + if validate { + return error(self, ErrorCode::InvalidUnicodeCodePoint); + } + scratch.push(ch); + } + } + } + } +} + +impl<Iter> Read for IteratorRead<Iter> + where Iter: Iterator<Item = io::Result<u8>>, +{ + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + match self.ch.take() { + Some(ch) => Ok(Some(ch)), + None => { + match self.iter.next() { + Some(Err(err)) => Err(err), + Some(Ok(ch)) => Ok(Some(ch)), + None => Ok(None), + } + } + } + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + match self.ch { + Some(ch) => Ok(Some(ch)), + None => { + match self.iter.next() { + Some(Err(err)) => Err(err), + Some(Ok(ch)) => { + self.ch = Some(ch); + Ok(self.ch) + } + None => Ok(None), + } + } + } + } + + #[inline] + fn discard(&mut self) { + self.ch = None; + } + + fn position(&self) -> Position { + Position { + line: self.iter.line(), + column: self.iter.col(), + } + } + + fn peek_position(&self) -> Position { + // The LineColIterator updates its position during peek() so it has the + // right one here. + self.position() + } + + fn parse_str<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s str> { + self.parse_str_bytes(scratch, true, as_str) + } + + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s [u8]> { + self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes)) + } +} + +////////////////////////////////////////////////////////////////////////////// + +impl<R> IoRead<R> + where R: io::Read +{ + /// Create a JSON input source to read from a std::io input stream. + pub fn new(reader: R) -> Self { + IoRead { + delegate: IteratorRead::new(reader.bytes()), + } + } +} + +impl<R> private::Sealed for IoRead<R> + where R: io::Read {} + +impl<R> Read for IoRead<R> + where R: io::Read +{ + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + self.delegate.next() + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + self.delegate.peek() + } + + #[inline] + fn discard(&mut self) { + self.delegate.discard(); + } + + #[inline] + fn position(&self) -> Position { + self.delegate.position() + } + + #[inline] + fn peek_position(&self) -> Position { + self.delegate.peek_position() + } + + #[inline] + fn parse_str<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s str> { + self.delegate.parse_str(scratch) + } + + #[inline] + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s [u8]> { + self.delegate.parse_str_raw(scratch) + } +} + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> SliceRead<'a> { + /// Create a JSON input source to read from a slice of bytes. + pub fn new(slice: &'a [u8]) -> Self { + SliceRead { + slice: slice, + index: 0, + } + } + + fn position_of_index(&self, i: usize) -> Position { + let mut pos = Position { + line: 1, + column: 0, + }; + for ch in &self.slice[..i] { + match *ch { + b'\n' => { + pos.line += 1; + pos.column = 0; + } + _ => { + pos.column += 1; + } + } + } + pos + } + + /// The big optimization here over IteratorRead is that if the string + /// contains no backslash escape sequences, the returned &str is a slice of + /// the raw JSON data so we avoid copying into the scratch space. + fn parse_str_bytes<'s, T, F>( + &'s mut self, + scratch: &'s mut Vec<u8>, + validate: bool, + result: F + ) -> Result<T> + where T: 's, + F: FnOnce(&'s Self, &'s [u8]) -> Result<T>, + { + // Index of the first byte not yet copied into the scratch space. + let mut start = self.index; + + loop { + while self.index < self.slice.len() && + !ESCAPE[self.slice[self.index] as usize] { + self.index += 1; + } + if self.index == self.slice.len() { + return error(self, ErrorCode::EofWhileParsingString); + } + match self.slice[self.index] { + b'"' => { + let string = if scratch.is_empty() { + // Fast path: return a slice of the raw JSON without any + // copying. + &self.slice[start..self.index] + } else { + scratch.extend_from_slice(&self.slice[start .. self.index]); + // "as &[u8]" is required for rustc 1.8.0 + scratch as &[u8] + }; + self.index += 1; + return result(self, string); + } + b'\\' => { + scratch.extend_from_slice(&self.slice[start..self.index]); + self.index += 1; + try!(parse_escape(self, scratch)); + start = self.index; + } + _ => { + if validate { + return error(self, ErrorCode::InvalidUnicodeCodePoint); + } + self.index += 1; + } + } + } + } +} + +impl<'a> private::Sealed for SliceRead<'a> {} + +impl<'a> Read for SliceRead<'a> { + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + // `Ok(self.slice.get(self.index).map(|ch| { self.index += 1; *ch }))` + // is about 10% slower. + Ok(if self.index < self.slice.len() { + let ch = self.slice[self.index]; + self.index += 1; + Some(ch) + } else { + None + }) + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + // `Ok(self.slice.get(self.index).map(|ch| *ch))` is about 10% slower + // for some reason. + Ok(if self.index < self.slice.len() { + Some(self.slice[self.index]) + } else { + None + }) + } + + #[inline] + fn discard(&mut self) { + self.index += 1; + } + + fn position(&self) -> Position { + self.position_of_index(self.index) + } + + fn peek_position(&self) -> Position { + // Cap it at slice.len() just in case the most recent call was next() + // and it returned the last byte. + self.position_of_index(cmp::min(self.slice.len(), self.index + 1)) + } + + fn parse_str<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s str> { + self.parse_str_bytes(scratch, true, as_str) + } + + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s [u8]> { + self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes)) + } + +} + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> StrRead<'a> { + /// Create a JSON input source to read from a UTF-8 string. + pub fn new(s: &'a str) -> Self { + StrRead { + delegate: SliceRead::new(s.as_bytes()), + } + } +} + +impl<'a> private::Sealed for StrRead<'a> {} + +impl<'a> Read for StrRead<'a> { + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + self.delegate.next() + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + self.delegate.peek() + } + + #[inline] + fn discard(&mut self) { + self.delegate.discard(); + } + + fn position(&self) -> Position { + self.delegate.position() + } + + fn peek_position(&self) -> Position { + self.delegate.peek_position() + } + + fn parse_str<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s str> { + self.delegate.parse_str_bytes(scratch, true, |_, bytes| { + // The input is assumed to be valid UTF-8 and the \u-escapes are + // checked along the way, so don't need to check here. + Ok(unsafe { str::from_utf8_unchecked(bytes) }) + }) + } + + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8> + ) -> Result<&'s [u8]> { + self.delegate.parse_str_raw(scratch) + } +} + +////////////////////////////////////////////////////////////////////////////// + +const CT: bool = true; // control character \x00...\x1F +const QU: bool = true; // quote \x22 +const BS: bool = true; // backslash \x5C +const O: bool = false; // allow unescaped + +// Lookup table of bytes that must be escaped. A value of true at index i means +// that byte i requires an escape sequence in the input. +#[cfg_attr(rustfmt, rustfmt_skip)] +static ESCAPE: [bool; 256] = [ + // 1 2 3 4 5 6 7 8 9 A B C D E F + CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, // 0 + CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, // 1 + O, O, QU, O, O, O, O, O, O, O, O, O, O, O, O, O, // 2 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 3 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 4 + O, O, O, O, O, O, O, O, O, O, O, O, BS, O, O, O, // 5 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 6 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 7 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 8 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 9 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // A + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // B + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // C + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // D + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // E + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // F +]; + +fn next_or_eof<R: Read>(read: &mut R) -> Result<u8> { + match try!(read.next()) { + Some(b) => Ok(b), + None => error(read, ErrorCode::EofWhileParsingString), + } +} + +fn error<R: Read, T>(read: &R, reason: ErrorCode) -> Result<T> { + let pos = read.position(); + Err(Error::syntax(reason, pos.line, pos.column)) +} + +fn as_str<'s, R: Read>(read: &R, slice: &'s [u8]) -> Result<&'s str> { + str::from_utf8(slice) + .or_else(|_| error(read, ErrorCode::InvalidUnicodeCodePoint)) +} + +/// Parses a JSON escape sequence and appends it into the scratch space. Assumes +/// the previous byte read was a backslash. +fn parse_escape<R: Read>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> { + let ch = try!(next_or_eof(read)); + + match ch { + b'"' => scratch.push(b'"'), + b'\\' => scratch.push(b'\\'), + b'/' => scratch.push(b'/'), + b'b' => scratch.push(b'\x08'), + b'f' => scratch.push(b'\x0c'), + b'n' => scratch.push(b'\n'), + b'r' => scratch.push(b'\r'), + b't' => scratch.push(b'\t'), + b'u' => { + let c = + match try!(decode_hex_escape(read)) { + 0xDC00...0xDFFF => { + return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); + } + + // Non-BMP characters are encoded as a sequence of + // two hex escapes, representing UTF-16 surrogates. + n1 @ 0xD800...0xDBFF => { + if try!(next_or_eof(read)) != b'\\' { + return error(read, ErrorCode::UnexpectedEndOfHexEscape); + } + if try!(next_or_eof(read)) != b'u' { + return error(read, ErrorCode::UnexpectedEndOfHexEscape); + } + + let n2 = try!(decode_hex_escape(read)); + + if n2 < 0xDC00 || n2 > 0xDFFF { + return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); + } + + let n = (((n1 - 0xD800) as u32) << 10 | + (n2 - 0xDC00) as u32) + + 0x1_0000; + + match char::from_u32(n as u32) { + Some(c) => c, + None => { + return error(read, ErrorCode::InvalidUnicodeCodePoint); + } + } + } + + n => { + match char::from_u32(n as u32) { + Some(c) => c, + None => { + return error(read, ErrorCode::InvalidUnicodeCodePoint); + } + } + } + }; + + // FIXME: this allocation is required in order to be compatible with stable + // rust, which doesn't support encoding a `char` into a stack buffer. + let mut buf = String::new(); + buf.push(c); + scratch.extend(buf.bytes()); + } + _ => { + return error(read, ErrorCode::InvalidEscape); + } + } + + Ok(()) +} + +fn decode_hex_escape<R: Read>(read: &mut R) -> Result<u16> { + let mut n = 0; + for _ in 0..4 { + n = match try!(next_or_eof(read)) { + c @ b'0'...b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)), + b'a' | b'A' => n * 16_u16 + 10_u16, + b'b' | b'B' => n * 16_u16 + 11_u16, + b'c' | b'C' => n * 16_u16 + 12_u16, + b'd' | b'D' => n * 16_u16 + 13_u16, + b'e' | b'E' => n * 16_u16 + 14_u16, + b'f' | b'F' => n * 16_u16 + 15_u16, + _ => { + return error(read, ErrorCode::InvalidEscape); + } + }; + } + Ok(n) +} diff --git a/bash-5.1/vendor/serde_json/src/ser.rs b/bash-5.1/vendor/serde_json/src/ser.rs new file mode 100644 index 0000000..74bae37 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/ser.rs @@ -0,0 +1,1411 @@ +//! Serialize a Rust data structure into JSON data. + +use std::fmt; +use std::io; +use std::num::FpCategory; +use std::str; + +use serde::ser::{self, Impossible}; +use super::error::{Error, ErrorCode, Result}; + +use itoa; +use dtoa; + +/// A structure for serializing Rust values into JSON. +pub struct Serializer<W, F = CompactFormatter> { + writer: W, + formatter: F, +} + +impl<W> Serializer<W> + where W: io::Write, +{ + /// Creates a new JSON serializer. + #[inline] + pub fn new(writer: W) -> Self { + Serializer::with_formatter(writer, CompactFormatter) + } +} + +impl<'a, W> Serializer<W, PrettyFormatter<'a>> + where W: io::Write, +{ + /// Creates a new JSON pretty print serializer. + #[inline] + pub fn pretty(writer: W) -> Self { + Serializer::with_formatter(writer, PrettyFormatter::new()) + } +} + +impl<W, F> Serializer<W, F> + where W: io::Write, + F: Formatter, +{ + /// Creates a new JSON visitor whose output will be written to the writer + /// specified. + #[inline] + pub fn with_formatter(writer: W, formatter: F) -> Self { + Serializer { + writer: writer, + formatter: formatter, + } + } + + /// Unwrap the `Writer` from the `Serializer`. + #[inline] + pub fn into_inner(self) -> W { + self.writer + } +} + +impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F> + where W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + type SerializeSeq = Compound<'a, W, F>; + type SerializeTuple = Compound<'a, W, F>; + type SerializeTupleStruct = Compound<'a, W, F>; + type SerializeTupleVariant = Compound<'a, W, F>; + type SerializeMap = Compound<'a, W, F>; + type SerializeStruct = Compound<'a, W, F>; + type SerializeStructVariant = Compound<'a, W, F>; + + #[inline] + fn serialize_bool(self, value: bool) -> Result<()> { + self.formatter.write_bool(&mut self.writer, value) + } + + #[inline] + fn serialize_i8(self, value: i8) -> Result<()> { + self.formatter.write_i8(&mut self.writer, value) + } + + #[inline] + fn serialize_i16(self, value: i16) -> Result<()> { + self.formatter.write_i16(&mut self.writer, value) + } + + #[inline] + fn serialize_i32(self, value: i32) -> Result<()> { + self.formatter.write_i32(&mut self.writer, value) + } + + #[inline] + fn serialize_i64(self, value: i64) -> Result<()> { + self.formatter.write_i64(&mut self.writer, value) + } + + #[inline] + fn serialize_u8(self, value: u8) -> Result<()> { + self.formatter.write_u8(&mut self.writer, value) + } + + #[inline] + fn serialize_u16(self, value: u16) -> Result<()> { + self.formatter.write_u16(&mut self.writer, value) + } + + #[inline] + fn serialize_u32(self, value: u32) -> Result<()> { + self.formatter.write_u32(&mut self.writer, value) + } + + #[inline] + fn serialize_u64(self, value: u64) -> Result<()> { + self.formatter.write_u64(&mut self.writer, value) + } + + #[inline] + fn serialize_f32(self, value: f32) -> Result<()> { + match value.classify() { + FpCategory::Nan | FpCategory::Infinite => { + self.formatter.write_null(&mut self.writer) + } + _ => { + self.formatter.write_f32(&mut self.writer, value) + } + } + } + + #[inline] + fn serialize_f64(self, value: f64) -> Result<()> { + match value.classify() { + FpCategory::Nan | FpCategory::Infinite => { + self.formatter.write_null(&mut self.writer) + } + _ => { + self.formatter.write_f64(&mut self.writer, value) + } + } + } + + #[inline] + fn serialize_char(self, value: char) -> Result<()> { + format_escaped_char(&mut self.writer, &mut self.formatter, value).map_err(From::from) + } + + #[inline] + fn serialize_str(self, value: &str) -> Result<()> { + format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(From::from) + } + + #[inline] + fn serialize_bytes(self, value: &[u8]) -> Result<()> { + use serde::ser::SerializeSeq; + let mut seq = try!(self.serialize_seq(Some(value.len()))); + for byte in value { + try!(seq.serialize_element(byte)); + } + seq.end() + } + + #[inline] + fn serialize_unit(self) -> Result<()> { + self.formatter.write_null(&mut self.writer) + } + + #[inline] + fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { + self.serialize_unit() + } + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str + ) -> Result<()> { + self.serialize_str(variant) + } + + /// Serialize newtypes without an object wrapper. + #[inline] + fn serialize_newtype_struct<T: ?Sized>( + self, + _name: &'static str, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + value.serialize(self) + } + + #[inline] + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + try!(self.formatter.begin_object(&mut self.writer)); + try!(self.formatter.begin_object_key(&mut self.writer, true)); + try!(self.serialize_str(variant)); + try!(self.formatter.end_object_key(&mut self.writer)); + try!(self.formatter.begin_object_value(&mut self.writer)); + try!(value.serialize(&mut *self)); + try!(self.formatter.end_object_value(&mut self.writer)); + self.formatter.end_object(&mut self.writer) + } + + #[inline] + fn serialize_none(self) -> Result<()> { + self.serialize_unit() + } + + #[inline] + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<()> + where T: ser::Serialize, + { + value.serialize(self) + } + + #[inline] + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { + if len == Some(0) { + try!(self.formatter.begin_array(&mut self.writer)); + try!(self.formatter.end_array(&mut self.writer)); + Ok(Compound { ser: self, state: State::Empty }) + } else { + try!(self.formatter.begin_array(&mut self.writer)); + Ok(Compound { ser: self, state: State::First }) + } + } + + #[inline] + fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq> { + self.serialize_seq(Some(size)) + } + + #[inline] + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { + self.serialize_seq(Some(len)) + } + + #[inline] + fn serialize_tuple_struct( + self, + _name: &'static str, + len: usize + ) -> Result<Self::SerializeTupleStruct> { + self.serialize_seq(Some(len)) + } + + #[inline] + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str, + len: usize + ) -> Result<Self::SerializeTupleVariant> { + try!(self.formatter.begin_object(&mut self.writer)); + try!(self.formatter.begin_object_key(&mut self.writer, true)); + try!(self.serialize_str(variant)); + try!(self.formatter.end_object_key(&mut self.writer)); + try!(self.formatter.begin_object_value(&mut self.writer)); + self.serialize_seq(Some(len)) + } + + #[inline] + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { + if len == Some(0) { + try!(self.formatter.begin_object(&mut self.writer)); + try!(self.formatter.end_object(&mut self.writer)); + Ok(Compound { ser: self, state: State::Empty }) + } else { + try!(self.formatter.begin_object(&mut self.writer)); + Ok(Compound { ser: self, state: State::First }) + } + } + + #[inline] + fn serialize_struct( + self, + _name: &'static str, + len: usize + ) -> Result<Self::SerializeStruct> { + self.serialize_map(Some(len)) + } + + #[inline] + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str, + len: usize + ) -> Result<Self::SerializeStructVariant> { + try!(self.formatter.begin_object(&mut self.writer)); + try!(self.formatter.begin_object_key(&mut self.writer, true)); + try!(self.serialize_str(variant)); + try!(self.formatter.end_object_key(&mut self.writer)); + try!(self.formatter.begin_object_value(&mut self.writer)); + self.serialize_map(Some(len)) + } + + fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok> + where T: fmt::Display, + { + use std::fmt::Write; + + struct Adapter<'ser, W: 'ser, F: 'ser> { + writer: &'ser mut W, + formatter: &'ser mut F, + error: Option<Error>, + } + + impl<'ser, W, F> Write for Adapter<'ser, W, F> + where W: io::Write, + F: Formatter, + { + fn write_str(&mut self, s: &str) -> fmt::Result { + assert!(self.error.is_none()); + match format_escaped_str_contents(self.writer, self.formatter, s) { + Ok(()) => Ok(()), + Err(err) => { + self.error = Some(err); + Err(fmt::Error) + } + } + } + } + + try!(self.formatter.begin_string(&mut self.writer)); + { + let mut adapter = Adapter { + writer: &mut self.writer, + formatter: &mut self.formatter, + error: None + }; + match write!(adapter, "{}", value) { + Ok(()) => assert!(adapter.error.is_none()), + Err(_) => { + return Err(adapter.error.expect("there should be an error")); + }, + } + } + self.formatter.end_string(&mut self.writer) + } +} + +#[doc(hidden)] +#[derive(Eq, PartialEq)] +pub enum State { + Empty, + First, + Rest, +} + +#[doc(hidden)] +pub struct Compound<'a, W: 'a, F: 'a> { + ser: &'a mut Serializer<W, F>, + state: State, +} + +impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_element<T: ?Sized>( + &mut self, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + try!(self.ser.formatter.begin_array_value(&mut self.ser.writer, self.state == State::First)); + self.state = State::Rest; + try!(value.serialize(&mut *self.ser)); + self.ser.formatter.end_array_value(&mut self.ser.writer) + } + + #[inline] + fn end(self) -> Result<()> { + match self.state { + State::Empty => Ok(()), + _ => self.ser.formatter.end_array(&mut self.ser.writer), + } + } +} + +impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_element<T: ?Sized>( + &mut self, + value: &T, + ) -> Result<()> + where T: ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + ser::SerializeSeq::end(self) + } +} + +impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>( + &mut self, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + ser::SerializeSeq::end(self) + } +} + +impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>( + &mut self, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + match self.state { + State::Empty => {} + _ => try!(self.ser.formatter.end_array(&mut self.ser.writer)), + } + try!(self.ser.formatter.end_object_value(&mut self.ser.writer)); + self.ser.formatter.end_object(&mut self.ser.writer) + } +} + +impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_key<T: ?Sized>( + &mut self, + key: &T, + ) -> Result<()> + where T: ser::Serialize, + { + try!(self.ser.formatter.begin_object_key(&mut self.ser.writer, self.state == State::First)); + self.state = State::Rest; + + try!(key.serialize(MapKeySerializer { + ser: self.ser, + })); + + self.ser.formatter.end_object_key(&mut self.ser.writer) + } + + #[inline] + fn serialize_value<T: ?Sized>( + &mut self, + value: &T, + ) -> Result<()> + where T: ser::Serialize, + { + try!(self.ser.formatter.begin_object_value(&mut self.ser.writer)); + try!(value.serialize(&mut *self.ser)); + self.ser.formatter.end_object_value(&mut self.ser.writer) + } + + #[inline] + fn end(self) -> Result<()> { + match self.state { + State::Empty => Ok(()), + _ => self.ser.formatter.end_object(&mut self.ser.writer), + } + } +} + +impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + try!(ser::SerializeMap::serialize_key(self, key)); + ser::SerializeMap::serialize_value(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + ser::SerializeMap::end(self) + } +} + +impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F> + where W: io::Write, + F: Formatter +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + ser::SerializeStruct::serialize_field(self, key, value) + } + + #[inline] + fn end(self) -> Result<()> { + match self.state { + State::Empty => {} + _ => try!(self.ser.formatter.end_object(&mut self.ser.writer)), + } + try!(self.ser.formatter.end_object_value(&mut self.ser.writer)); + self.ser.formatter.end_object(&mut self.ser.writer) + } +} + +struct MapKeySerializer<'a, W: 'a, F: 'a> { + ser: &'a mut Serializer<W, F>, +} + +fn key_must_be_a_string() -> Error { + Error::syntax(ErrorCode::KeyMustBeAString, 0, 0) +} + +impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F> + where W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_str(self, value: &str) -> Result<()> { + self.ser.serialize_str(value) + } + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str + ) -> Result<()> { + self.ser.serialize_str(variant) + } + + #[inline] + fn serialize_newtype_struct<T: ?Sized>( + self, + _name: &'static str, + value: &T + ) -> Result<()> + where T: ser::Serialize, + { + value.serialize(self) + } + + type SerializeSeq = Impossible<(), Error>; + type SerializeTuple = Impossible<(), Error>; + type SerializeTupleStruct = Impossible<(), Error>; + type SerializeTupleVariant = Impossible<(), Error>; + type SerializeMap = Impossible<(), Error>; + type SerializeStruct = Impossible<(), Error>; + type SerializeStructVariant = Impossible<(), Error>; + + fn serialize_bool(self, _value: bool) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_i8(self, value: i8) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_i8(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_i16(self, value: i16) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_i16(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_i32(self, value: i32) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_i32(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_i64(self, value: i64) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_i64(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_u8(self, value: u8) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_u8(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_u16(self, value: u16) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_u16(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_u32(self, value: u32) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_u32(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_u64(self, value: u64) -> Result<()> { + try!(self.ser.formatter.begin_string(&mut self.ser.writer)); + try!(self.ser.formatter.write_u64(&mut self.ser.writer, value)); + self.ser.formatter.end_string(&mut self.ser.writer) + } + + fn serialize_f32(self, _value: f32) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_f64(self, _value: f64) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_char(self, _value: char) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_unit(self) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: usize, + _variant: &'static str, + _value: &T + ) -> Result<()> + where T: ser::Serialize, + { + Err(key_must_be_a_string()) + } + + fn serialize_none(self) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<()> + where T: ser::Serialize, + { + Err(key_must_be_a_string()) + } + + fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { + Err(key_must_be_a_string()) + } + + fn serialize_seq_fixed_size(self, _size: usize) -> Result<Self::SerializeSeq> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize + ) -> Result<Self::SerializeTupleStruct> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: usize, + _variant: &'static str, + _len: usize + ) -> Result<Self::SerializeTupleVariant> { + Err(key_must_be_a_string()) + } + + fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { + Err(key_must_be_a_string()) + } + + fn serialize_struct( + self, + _name: &'static str, + _len: usize + ) -> Result<Self::SerializeStruct> { + Err(key_must_be_a_string()) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: usize, + _variant: &'static str, + _len: usize + ) -> Result<Self::SerializeStructVariant> { + Err(key_must_be_a_string()) + } +} + +/// Represents a character escape code in a type-safe manner. +pub enum CharEscape { + /// An escaped quote `"` + Quote, + /// An escaped reverse solidus `\` + ReverseSolidus, + /// An escaped solidus `/` + Solidus, + /// An escaped backspace character (usually escaped as `\b`) + Backspace, + /// An escaped form feed character (usually escaped as `\f`) + FormFeed, + /// An escaped line feed character (usually escaped as `\n`) + LineFeed, + /// An escaped carriage return character (usually escaped as `\r`) + CarriageReturn, + /// An escaped tab character (usually escaped as `\t`) + Tab, + /// An escaped ASCII plane control character (usually escaped as + /// `\u00XX` where `XX` are two hex characters) + AsciiControl(u8), +} + +impl CharEscape { + #[inline] + fn from_escape_table(escape: u8, byte: u8) -> CharEscape { + match escape { + self::BB => CharEscape::Backspace, + self::TT => CharEscape::Tab, + self::NN => CharEscape::LineFeed, + self::FF => CharEscape::FormFeed, + self::RR => CharEscape::CarriageReturn, + self::QU => CharEscape::Quote, + self::BS => CharEscape::ReverseSolidus, + self::U => CharEscape::AsciiControl(byte), + _ => unreachable!(), + } + } +} + +/// This trait abstracts away serializing the JSON control characters, which allows the user to +/// optionally pretty print the JSON output. +pub trait Formatter { + /// Writes a `null` value to the specified writer. + #[inline] + fn write_null<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"null").map_err(From::from) + } + + /// Writes a `true` or `false` value to the specified writer. + #[inline] + fn write_bool<W: ?Sized>(&mut self, writer: &mut W, value: bool) -> Result<()> + where W: io::Write + { + let s = if value { + b"true" as &[u8] + } else { + b"false" as &[u8] + }; + writer.write_all(s).map_err(From::from) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i8<W: ?Sized>(&mut self, writer: &mut W, value: i8) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i16<W: ?Sized>(&mut self, writer: &mut W, value: i16) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i32<W: ?Sized>(&mut self, writer: &mut W, value: i32) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i64<W: ?Sized>(&mut self, writer: &mut W, value: i64) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u8<W: ?Sized>(&mut self, writer: &mut W, value: u8) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u16<W: ?Sized>(&mut self, writer: &mut W, value: u16) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u32<W: ?Sized>(&mut self, writer: &mut W, value: u32) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u64<W: ?Sized>(&mut self, writer: &mut W, value: u64) -> Result<()> + where W: io::Write + { + itoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes a floating point value like `-31.26e+12` to the specified writer. + #[inline] + fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> Result<()> + where W: io::Write + { + dtoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Writes a floating point value like `-31.26e+12` to the specified writer. + #[inline] + fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> Result<()> + where W: io::Write + { + dtoa::write(writer, value) + .map(|_| ()) + .map_err(From::from) + } + + /// Called before each series of `write_string_fragment` and + /// `write_char_escape`. Writes a `"` to the specified writer. + #[inline] + fn begin_string<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"\"").map_err(From::from) + } + + /// Called after each series of `write_string_fragment` and + /// `write_char_escape`. Writes a `"` to the specified writer. + #[inline] + fn end_string<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"\"").map_err(From::from) + } + + /// Writes a string fragment that doesn't need any escaping to the + /// specified writer. + #[inline] + fn write_string_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &[u8]) -> Result<()> + where W: io::Write + { + writer.write_all(fragment).map_err(From::from) + } + + /// Writes a character escape code to the specified writer. + #[inline] + fn write_char_escape<W: ?Sized>(&mut self, writer: &mut W, char_escape: CharEscape) -> Result<()> + where W: io::Write + { + use self::CharEscape::*; + + let s = match char_escape { + Quote => b"\\\"", + ReverseSolidus => b"\\\\", + Solidus => b"\\/", + Backspace => b"\\b", + FormFeed => b"\\f", + LineFeed => b"\\n", + CarriageReturn => b"\\r", + Tab => b"\\t", + AsciiControl(byte) => { + static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef"; + let bytes = &[b'\\', b'u', b'0', b'0', + HEX_DIGITS[(byte >> 4) as usize], + HEX_DIGITS[(byte & 0xF) as usize]]; + return writer.write_all(bytes).map_err(From::from); + } + }; + + writer.write_all(s).map_err(From::from) + } + + /// Called before every array. Writes a `[` to the specified + /// writer. + #[inline] + fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"[").map_err(From::from) + } + + /// Called after every array. Writes a `]` to the specified + /// writer. + #[inline] + fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"]").map_err(From::from) + } + + /// Called before every array value. Writes a `,` if needed to + /// the specified writer. + #[inline] + fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()> + where W: io::Write + { + if first { + Ok(()) + } else { + writer.write_all(b",").map_err(From::from) + } + } + + /// Called after every array value. + #[inline] + fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()> + where W: io::Write + { + Ok(()) + } + + /// Called before every object. Writes a `{` to the specified + /// writer. + #[inline] + fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"{").map_err(From::from) + } + + /// Called after every object. Writes a `}` to the specified + /// writer. + #[inline] + fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b"}").map_err(From::from) + } + + /// Called before every object key. + #[inline] + fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()> + where W: io::Write + { + if first { + Ok(()) + } else { + writer.write_all(b",").map_err(From::from) + } + } + + /// Called after every object key. A `:` should be written to the + /// specified writer by either this method or + /// `begin_object_value`. + #[inline] + fn end_object_key<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()> + where W: io::Write + { + Ok(()) + } + + /// Called before every object value. A `:` should be written to + /// the specified writer by either this method or + /// `end_object_key`. + #[inline] + fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b":").map_err(From::from) + } + + /// Called after every object value. + #[inline] + fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()> + where W: io::Write + { + Ok(()) + } +} + +/// This structure compacts a JSON value with no extra whitespace. +#[derive(Clone, Debug)] +pub struct CompactFormatter; + +impl Formatter for CompactFormatter {} + +/// This structure pretty prints a JSON value to make it human readable. +#[derive(Clone, Debug)] +pub struct PrettyFormatter<'a> { + current_indent: usize, + has_value: bool, + indent: &'a [u8], +} + +impl<'a> PrettyFormatter<'a> { + /// Construct a pretty printer formatter that defaults to using two spaces for indentation. + pub fn new() -> Self { + PrettyFormatter::with_indent(b" ") + } + + /// Construct a pretty printer formatter that uses the `indent` string for indentation. + pub fn with_indent(indent: &'a [u8]) -> Self { + PrettyFormatter { + current_indent: 0, + has_value: false, + indent: indent, + } + } +} + +impl<'a> Default for PrettyFormatter<'a> { + fn default() -> Self { + PrettyFormatter::new() + } +} + +impl<'a> Formatter for PrettyFormatter<'a> { + #[inline] + fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + self.current_indent += 1; + self.has_value = false; + writer.write_all(b"[").map_err(From::from) + } + + #[inline] + fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + self.current_indent -= 1; + + if self.has_value { + try!(writer.write_all(b"\n")); + try!(indent(writer, self.current_indent, self.indent)); + } + + writer.write_all(b"]").map_err(From::from) + } + + #[inline] + fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()> + where W: io::Write + { + if first { + try!(writer.write_all(b"\n")); + } else { + try!(writer.write_all(b",\n")); + } + try!(indent(writer, self.current_indent, self.indent)); + Ok(()) + } + + #[inline] + fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()> + where W: io::Write + { + self.has_value = true; + Ok(()) + } + + #[inline] + fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + self.current_indent += 1; + self.has_value = false; + writer.write_all(b"{").map_err(From::from) + } + + #[inline] + fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + self.current_indent -= 1; + + if self.has_value { + try!(writer.write_all(b"\n")); + try!(indent(writer, self.current_indent, self.indent)); + } + + writer.write_all(b"}").map_err(From::from) + } + + #[inline] + fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()> + where W: io::Write + { + if first { + try!(writer.write_all(b"\n")); + } else { + try!(writer.write_all(b",\n")); + } + indent(writer, self.current_indent, self.indent) + } + + #[inline] + fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> Result<()> + where W: io::Write + { + writer.write_all(b": ").map_err(From::from) + } + + #[inline] + fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()> + where W: io::Write + { + self.has_value = true; + Ok(()) + } +} + +fn format_escaped_str<W: ?Sized, F: ?Sized>(writer: &mut W, formatter: &mut F, value: &str) -> Result<()> + where W: io::Write, + F: Formatter +{ + try!(formatter.begin_string(writer)); + try!(format_escaped_str_contents(writer, formatter, value)); + try!(formatter.end_string(writer)); + Ok(()) +} + +fn format_escaped_str_contents<W: ?Sized, F: ?Sized>(writer: &mut W, + formatter: &mut F, + value: &str) + -> Result<()> + where W: io::Write, + F: Formatter, +{ + let bytes = value.as_bytes(); + + let mut start = 0; + + for (i, &byte) in bytes.iter().enumerate() { + let escape = ESCAPE[byte as usize]; + if escape == 0 { + continue; + } + + if start < i { + try!(formatter.write_string_fragment(writer, &bytes[start..i])); + } + + let char_escape = CharEscape::from_escape_table(escape, byte); + try!(formatter.write_char_escape(writer, char_escape)); + + start = i + 1; + } + + if start != bytes.len() { + try!(formatter.write_string_fragment(writer, &bytes[start..])); + } + + Ok(()) +} + +const BB: u8 = b'b'; // \x08 +const TT: u8 = b't'; // \x09 +const NN: u8 = b'n'; // \x0A +const FF: u8 = b'f'; // \x0C +const RR: u8 = b'r'; // \x0D +const QU: u8 = b'"'; // \x22 +const BS: u8 = b'\\'; // \x5C +const U: u8 = b'u'; // \x00...\x1F except the ones above + +// Lookup table of escape sequences. A value of b'x' at index i means that byte +// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped. +#[cfg_attr(rustfmt, rustfmt_skip)] +static ESCAPE: [u8; 256] = [ + // 1 2 3 4 5 6 7 8 9 A B C D E F + U, U, U, U, U, U, U, U, BB, TT, NN, U, FF, RR, U, U, // 0 + U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, // 1 + 0, 0, QU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, BS, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F +]; + +#[inline] +fn format_escaped_char<W: ?Sized, F: ?Sized>(wr: &mut W, formatter: &mut F, value: char) -> Result<()> + where W: io::Write, + F: Formatter, +{ + use std::io::Write; + // A char encoded as UTF-8 takes 4 bytes at most. + let mut buf = [0; 4]; + write!(&mut buf[..], "{}", value).expect("write char to 4-byte buffer"); + // Writing a char successfully always produce valid UTF-8. + // Once we do not support Rust <1.15 we will be able to just use + // the method `char::encode_utf8`. + // See https://github.com/serde-rs/json/issues/270. + let slice = unsafe { str::from_utf8_unchecked(&buf[0..value.len_utf8()]) }; + format_escaped_str(wr, formatter, slice) +} + +/// Serialize the given data structure as JSON into the IO stream. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_writer<W: ?Sized, T: ?Sized>(writer: &mut W, value: &T) -> Result<()> + where W: io::Write, + T: ser::Serialize, +{ + let mut ser = Serializer::new(writer); + try!(value.serialize(&mut ser)); + Ok(()) +} + +/// Serialize the given data structure as pretty-printed JSON into the IO +/// stream. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_writer_pretty<W: ?Sized, T: ?Sized>(writer: &mut W, value: &T) -> Result<()> + where W: io::Write, + T: ser::Serialize, +{ + let mut ser = Serializer::pretty(writer); + try!(value.serialize(&mut ser)); + Ok(()) +} + +/// Serialize the given data structure as a JSON byte vector. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>> + where T: ser::Serialize, +{ + let mut writer = Vec::with_capacity(128); + try!(to_writer(&mut writer, value)); + Ok(writer) +} + +/// Serialize the given data structure as a pretty-printed JSON byte vector. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>> + where T: ser::Serialize, +{ + let mut writer = Vec::with_capacity(128); + try!(to_writer_pretty(&mut writer, value)); + Ok(writer) +} + +/// Serialize the given data structure as a String of JSON. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_string<T: ?Sized>(value: &T) -> Result<String> + where T: ser::Serialize, +{ + let vec = try!(to_vec(value)); + let string = unsafe { + // We do not emit invalid UTF-8. + String::from_utf8_unchecked(vec) + }; + Ok(string) +} + +/// Serialize the given data structure as a pretty-printed String of JSON. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String> + where T: ser::Serialize, +{ + let vec = try!(to_vec_pretty(value)); + let string = unsafe { + // We do not emit invalid UTF-8. + String::from_utf8_unchecked(vec) + }; + Ok(string) +} + +fn indent<W: ?Sized>(wr: &mut W, n: usize, s: &[u8]) -> Result<()> + where W: io::Write, +{ + for _ in 0..n { + try!(wr.write_all(s)); + } + + Ok(()) +} diff --git a/bash-5.1/vendor/serde_json/src/value.rs b/bash-5.1/vendor/serde_json/src/value.rs new file mode 100644 index 0000000..15066c7 --- /dev/null +++ b/bash-5.1/vendor/serde_json/src/value.rs @@ -0,0 +1,2267 @@ +//! The Value enum, a loosely typed way of representing any valid JSON value. +//! +//! # Constructing JSON +//! +//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +//! objects with very natural JSON syntax. In order to use this macro, +//! `serde_json` needs to be imported with the `#[macro_use]` attribute. +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_json; +//! +//! fn main() { +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }); +//! +//! println!("first phone number: {}", john["phones"][0]); +//! +//! // Convert to a string of JSON and print it out +//! println!("{}", john.to_string()); +//! } +//! ``` +//! +//! The `Value::to_string()` function converts a `serde_json::Value` into a +//! `String` of JSON text. +//! +//! One neat thing about the `json!` macro is that variables and expressions can +//! be interpolated directly into the JSON value as you are building it. Serde +//! will check at compile time that the value you are interpolating is able to +//! be represented as JSON. +//! +//! ```rust +//! # #[macro_use] extern crate serde_json; +//! # fn random_phone() -> u16 { 0 } +//! # fn main() { +//! let full_name = "John Doe"; +//! let age_last_year = 42; +//! +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": full_name, +//! "age": age_last_year + 1, +//! "phones": [ +//! format!("+44 {}", random_phone()) +//! ] +//! }); +//! # let _ = john; +//! # } +//! ``` +//! +//! A string of JSON data can be parsed into a `serde_json::Value` by the +//! [`serde_json::from_str`][from_str] function. There is also +//! [`from_slice`][from_slice] for parsing from a byte slice &[u8], +//! [`from_iter`][from_iter] for parsing from an iterator of bytes, and +//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or +//! a TCP stream. +//! +//! ```rust +//! # extern crate serde_json; +//! # use serde_json::Error; +//! # pub fn example() -> Result<(), Error> { +//! use serde_json::Value; +//! +//! let data = r#" { "name": "John Doe", "age": 43, ... } "#; +//! let v: Value = serde_json::from_str(data)?; +//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); +//! # Ok(()) } +//! # fn main() {} +//! ``` +//! +//! [macro]: https://docs.serde.rs/serde_json/macro.json.html +//! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html +//! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html +//! [from_iter]: https://docs.serde.rs/serde_json/de/fn.from_iter.html +//! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html + +use std::fmt; +use std::i64; +use std::io; +use std::ops; +use std::slice; +use std::str; +use std::vec; +use std::borrow::Cow; + +use serde::de::{self, Unexpected}; +use serde::ser; +use serde::de::value::ValueDeserializer; + +use error::{Error, ErrorCode}; + +pub use map::Map; +pub use number::Number; + +/// Represents any valid JSON value. +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + /// Represents a JSON null value. + Null, + + /// Represents a JSON boolean. + Bool(bool), + + /// Represents a JSON number, whether integer or floating point. + Number(Number), + + /// Represents a JSON string. + String(String), + + /// Represents a JSON array. + Array(Vec<Value>), + + /// Represents a JSON object. + Object(Map<String, Value>), +} + +fn parse_index(s: &str) -> Option<usize> { + if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { + return None; + } + s.parse().ok() +} + +impl Value { + /// Index into a JSON array or map. A string index can be used to access a + /// value in a map, and a usize index can be used to access an element of an + /// array. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is an array or a + /// number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the array. + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let object = json!({ "A": 65, "B": 66, "C": 67 }); + /// assert_eq!(*object.get("A").unwrap(), json!(65)); + /// + /// let array = json!([ "A", "B", "C" ]); + /// assert_eq!(*array.get(2).unwrap(), json!("C")); + /// + /// assert_eq!(array.get("A"), None); + /// # } + /// ``` + /// + /// Square brackets can also be used to index into a value in a more concise + /// way. This returns `Value::Null` in cases where `get` would have returned + /// `None`. + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let object = json!({ + /// "A": ["a", "á", "à"], + /// "B": ["b", "b́"], + /// "C": ["c", "ć", "ć̣", "ḉ"], + /// }); + /// assert_eq!(object["B"][0], json!("b")); + /// + /// assert_eq!(object["D"], json!(null)); + /// assert_eq!(object[0]["x"]["y"]["z"], json!(null)); + /// # } + /// ``` + pub fn get<I: Index>(&self, index: I) -> Option<&Value> { + index.index_into(self) + } + + /// Mutably index into a JSON array or map. A string index can be used to + /// access a value in a map, and a usize index can be used to access an + /// element of an array. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is an array or a + /// number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the array. + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let mut object = json!({ "A": 65, "B": 66, "C": 67 }); + /// *object.get_mut("A").unwrap() = json!(69); + /// + /// let mut array = json!([ "A", "B", "C" ]); + /// *array.get_mut(2).unwrap() = json!("D"); + /// # } + /// ``` + pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { + index.index_into_mut(self) + } + + /// Returns true if the `Value` is an Object. Returns false otherwise. + pub fn is_object(&self) -> bool { + self.as_object().is_some() + } + + /// If the `Value` is an Object, returns the associated Map. + /// Returns None otherwise. + pub fn as_object(&self) -> Option<&Map<String, Value>> { + match *self { + Value::Object(ref map) => Some(map), + _ => None, + } + } + + /// If the `Value` is an Object, returns the associated mutable Map. + /// Returns None otherwise. + pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> { + match *self { + Value::Object(ref mut map) => Some(map), + _ => None, + } + } + + /// Returns true if the `Value` is an Array. Returns false otherwise. + pub fn is_array(&self) -> bool { + self.as_array().is_some() + } + + /// If the `Value` is an Array, returns the associated vector. + /// Returns None otherwise. + pub fn as_array(&self) -> Option<&Vec<Value>> { + match *self { + Value::Array(ref array) => Some(&*array), + _ => None, + } + } + + /// If the `Value` is an Array, returns the associated mutable vector. + /// Returns None otherwise. + pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { + match *self { + Value::Array(ref mut list) => Some(list), + _ => None, + } + } + + /// Returns true if the `Value` is a String. Returns false otherwise. + pub fn is_string(&self) -> bool { + self.as_str().is_some() + } + + /// If the `Value` is a String, returns the associated str. + /// Returns None otherwise. + pub fn as_str(&self) -> Option<&str> { + match *self { + Value::String(ref s) => Some(s), + _ => None, + } + } + + /// Returns true if the `Value` is a Number. Returns false otherwise. + pub fn is_number(&self) -> bool { + match *self { + Value::Number(_) => true, + _ => false, + } + } + + /// Returns true if the `Value` is a number that can be represented by i64. + pub fn is_i64(&self) -> bool { + match *self { + Value::Number(ref n) => n.is_i64(), + _ => false, + } + } + + /// Returns true if the `Value` is a number that can be represented by u64. + pub fn is_u64(&self) -> bool { + match *self { + Value::Number(ref n) => n.is_u64(), + _ => false, + } + } + + /// Returns true if the `Value` is a number that can be represented by f64. + pub fn is_f64(&self) -> bool { + match *self { + Value::Number(ref n) => n.is_f64(), + _ => false, + } + } + + /// If the `Value` is a number, represent it as i64 if possible. + /// Returns None otherwise. + pub fn as_i64(&self) -> Option<i64> { + match *self { + Value::Number(ref n) => n.as_i64(), + _ => None, + } + } + + /// If the `Value` is a number, represent it as u64 if possible. + /// Returns None otherwise. + pub fn as_u64(&self) -> Option<u64> { + match *self { + Value::Number(ref n) => n.as_u64(), + _ => None, + } + } + + /// If the `Value` is a number, represent it as f64 if possible. + /// Returns None otherwise. + pub fn as_f64(&self) -> Option<f64> { + match *self { + Value::Number(ref n) => n.as_f64(), + _ => None, + } + } + + /// Returns true if the `Value` is a Boolean. Returns false otherwise. + pub fn is_boolean(&self) -> bool { + self.as_bool().is_some() + } + + /// If the `Value` is a Boolean, returns the associated bool. + /// Returns None otherwise. + pub fn as_bool(&self) -> Option<bool> { + match *self { + Value::Bool(b) => Some(b), + _ => None, + } + } + + /// Returns true if the `Value` is a Null. Returns false otherwise. + pub fn is_null(&self) -> bool { + self.as_null().is_some() + } + + /// If the `Value` is a Null, returns (). + /// Returns None otherwise. + pub fn as_null(&self) -> Option<()> { + match *self { + Value::Null => Some(()), + _ => None, + } + } + + /// Looks up a value by a JSON Pointer. + /// + /// JSON Pointer defines a string syntax for identifying a specific value + /// within a JavaScript Object Notation (JSON) document. + /// + /// A Pointer is a Unicode string with the reference tokens separated by `/`. + /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The + /// addressed value is returned and if there is no such value `None` is + /// returned. + /// + /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let data = json!({ + /// "x": { + /// "y": ["z", "zz"] + /// } + /// }); + /// + /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz")); + /// assert_eq!(data.pointer("/a/b/c"), None); + /// # } + /// ``` + pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> { + if pointer == "" { + return Some(self); + } + if !pointer.starts_with('/') { + return None; + } + let tokens = pointer.split('/').skip(1).map(|x| x.replace("~1", "/").replace("~0", "~")); + let mut target = self; + + for token in tokens { + let target_opt = match *target { + Value::Object(ref map) => map.get(&token), + Value::Array(ref list) => parse_index(&token).and_then(|x| list.get(x)), + _ => return None, + }; + if let Some(t) = target_opt { + target = t; + } else { + return None; + } + } + Some(target) + } + + /// Looks up a value by a JSON Pointer and returns a mutable reference to + /// that value. + /// + /// JSON Pointer defines a string syntax for identifying a specific value + /// within a JavaScript Object Notation (JSON) document. + /// + /// A Pointer is a Unicode string with the reference tokens separated by `/`. + /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The + /// addressed value is returned and if there is no such value `None` is + /// returned. + /// + /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). + /// + /// # Example of Use + /// + /// ```rust + /// extern crate serde_json; + /// + /// use serde_json::Value; + /// use std::mem; + /// + /// fn main() { + /// let s = r#"{"x": 1.0, "y": 2.0}"#; + /// let mut value: Value = serde_json::from_str(s).unwrap(); + /// + /// // Check value using read-only pointer + /// assert_eq!(value.pointer("/x"), Some(&1.0.into())); + /// // Change value with direct assignment + /// *value.pointer_mut("/x").unwrap() = 1.5.into(); + /// // Check that new value was written + /// assert_eq!(value.pointer("/x"), Some(&1.5.into())); + /// + /// // "Steal" ownership of a value. Can replace with any valid Value. + /// let old_x = value.pointer_mut("/x").map(|x| mem::replace(x, Value::Null)).unwrap(); + /// assert_eq!(old_x, 1.5); + /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null); + /// } + /// ``` + pub fn pointer_mut<'a>(&'a mut self, pointer: &str) -> Option<&'a mut Value> { + if pointer == "" { + return Some(self); + } + if !pointer.starts_with('/') { + return None; + } + let tokens = pointer.split('/').skip(1).map(|x| x.replace("~1", "/").replace("~0", "~")); + let mut target = self; + + for token in tokens { + // borrow checker gets confused about `target` being mutably borrowed too many times because of the loop + // this once-per-loop binding makes the scope clearer and circumvents the error + let target_once = target; + let target_opt = match *target_once { + Value::Object(ref mut map) => map.get_mut(&token), + Value::Array(ref mut list) => parse_index(&token).and_then(move |x| list.get_mut(x)), + _ => return None, + }; + if let Some(t) = target_opt { + target = t; + } else { + return None; + } + } + Some(target) + } +} + +/// The default value is `Value::Null`. +/// +/// This is useful for handling omitted `Value` fields when deserializing. +/// +/// # Examples +/// +/// ```rust +/// # extern crate serde_json; +/// # #[macro_use] extern crate serde_derive; +/// use serde_json::Value; +/// +/// #[derive(Deserialize)] +/// struct Settings { +/// level: i32, +/// #[serde(default)] +/// extras: Value, +/// } +/// +/// # pub fn try_main() -> Result<(), serde_json::Error> { +/// let data = r#" { "level": 42 } "#; +/// let s: Settings = serde_json::from_str(data)?; +/// +/// assert_eq!(s.level, 42); +/// assert_eq!(s.extras, Value::Null); +/// # Ok(()) } +/// # fn main() { try_main().unwrap() } +/// ``` +impl Default for Value { + fn default() -> Value { + Value::Null + } +} + +/// A type that can be used to index into a `serde_json::Value`. See the `get` +/// and `get_mut` methods of `Value`. +/// +/// This trait is sealed and cannot be implemented for types outside of +/// `serde_json`. +pub trait Index: private::Sealed { + /// Return None if the key is not already in the array or object. + #[doc(hidden)] + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>; + + /// Return None if the key is not already in the array or object. + #[doc(hidden)] + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>; + + /// Panic if array index out of bounds. If key is not already in the object, + /// insert it with a value of null. Panic if Value is a type that cannot be + /// indexed into, except if Value is null then it can be treated as an empty + /// object. + #[doc(hidden)] + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value; +} + +impl Index for usize { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + match *v { + Value::Array(ref vec) => vec.get(*self), + _ => None, + } + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + match *v { + Value::Array(ref mut vec) => vec.get_mut(*self), + _ => None, + } + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + match *v { + Value::Array(ref mut vec) => { + let len = vec.len(); + vec.get_mut(*self).unwrap_or_else(|| { + panic!("cannot access index {} of JSON array of length {}", + self, len) + }) + } + _ => panic!("cannot access index {} of JSON {}", self, Type(v)), + } + } +} + +impl Index for str { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + match *v { + Value::Object(ref map) => map.get(self), + _ => None, + } + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + match *v { + Value::Object(ref mut map) => map.get_mut(self), + _ => None, + } + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + if let Value::Null = *v { + let mut map = Map::new(); + map.insert(self.to_owned(), Value::Null); + *v = Value::Object(map); + } + match *v { + Value::Object(ref mut map) => { + // TODO: use entry() once LinkedHashMap supports entry() + // https://github.com/contain-rs/linked-hash-map/issues/5 + if !map.contains_key(self) { + map.insert(self.to_owned(), Value::Null); + } + map.get_mut(self).unwrap() + } + _ => panic!("cannot access key {:?} in JSON {}", self, Type(v)), + } + } +} + +impl Index for String { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + self[..].index_into(v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + self[..].index_into_mut(v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + self[..].index_or_insert(v) + } +} + +impl<'a, T: ?Sized> Index for &'a T where T: Index { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + (**self).index_into(v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + (**self).index_into_mut(v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + (**self).index_or_insert(v) + } +} + +// Prevent users from implementing the Index trait. +mod private { + pub trait Sealed {} + impl Sealed for usize {} + impl Sealed for str {} + impl Sealed for String {} + impl<'a, T: ?Sized> Sealed for &'a T where T: Sealed {} +} + +/// Used in panic messages. +struct Type<'a>(&'a Value); + +impl<'a> fmt::Display for Type<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self.0 { + Value::Null => formatter.write_str("null"), + Value::Bool(_) => formatter.write_str("boolean"), + Value::Number(_) => formatter.write_str("number"), + Value::String(_) => formatter.write_str("string"), + Value::Array(_) => formatter.write_str("array"), + Value::Object(_) => formatter.write_str("object"), + } + } +} + +// The usual semantics of Index is to panic on invalid indexing. +// +// That said, the usual semantics are for things like Vec and BTreeMap which +// have different use cases than Value. If you are working with a Vec, you know +// that you are working with a Vec and you can get the len of the Vec and make +// sure your indices are within bounds. The Value use cases are more +// loosey-goosey. You got some JSON from an endpoint and you want to pull values +// out of it. Outside of this Index impl, you already have the option of using +// value.as_array() and working with the Vec directly, or matching on +// Value::Array and getting the Vec directly. The Index impl means you can skip +// that and index directly into the thing using a concise syntax. You don't have +// to check the type, you don't have to check the len, it is all about what you +// expect the Value to look like. +// +// Basically the use cases that would be well served by panicking here are +// better served by using one of the other approaches: get and get_mut, +// as_array, or match. The value of this impl is that it adds a way of working +// with Value that is not well served by the existing approaches: concise and +// careless and sometimes that is exactly what you want. +impl<I> ops::Index<I> for Value where I: Index { + type Output = Value; + + /// Index into a `serde_json::Value` using the syntax `value[0]` or + /// `value["k"]`. + /// + /// Returns `Value::Null` if the type of `self` does not match the type of + /// the index, for example if the index is a string and `self` is an array + /// or a number. Also returns `Value::Null` if the given key does not exist + /// in the map or the given index is not within the bounds of the array. + /// + /// For retrieving deeply nested values, you should have a look at the + /// `Value::pointer` method. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let data = json!({ + /// "x": { + /// "y": ["z", "zz"] + /// } + /// }); + /// + /// assert_eq!(data["x"]["y"], json!(["z", "zz"])); + /// assert_eq!(data["x"]["y"][0], json!("z")); + /// + /// assert_eq!(data["a"], json!(null)); // returns null for undefined values + /// assert_eq!(data["a"]["b"], json!(null)); // does not panic + /// # } + /// ``` + fn index(&self, index: I) -> &Value { + static NULL: Value = Value::Null; + index.index_into(self).unwrap_or(&NULL) + } +} + +impl<I> ops::IndexMut<I> for Value where I: Index { + /// Write into a `serde_json::Value` using the syntax `value[0] = ...` or + /// `value["k"] = ...`. + /// + /// If the index is a number, the value must be an array of length bigger + /// than the index. Indexing into a value that is not an array or an array + /// that is too small will panic. + /// + /// If the index is a string, the value must be an object or null which is + /// treated like an empty object. If the key is not already present in the + /// object, it will be inserted with a value of null. Indexing into a value + /// that is neither an object nor null will panic. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let mut data = json!({ "x": 0 }); + /// + /// // replace an existing key + /// data["x"] = json!(1); + /// + /// // insert a new key + /// data["y"] = json!([false, false, false]); + /// + /// // replace an array value + /// data["y"][0] = json!(true); + /// + /// // inserted a deeply nested key + /// data["a"]["b"]["c"]["d"] = json!(true); + /// + /// println!("{}", data); + /// # } + /// ``` + fn index_mut(&mut self, index: I) -> &mut Value { + index.index_or_insert(self) + } +} + +impl PartialEq<str> for Value { + fn eq(&self, other: &str) -> bool { + self.as_str().map_or(false, |s| s == other) + } +} + +impl<'a> PartialEq<&'a str> for Value { + fn eq(&self, other: &&str) -> bool { + self.as_str().map_or(false, |s| s == *other) + } +} + +impl PartialEq<Value> for str { + fn eq(&self, other: &Value) -> bool { + other.as_str().map_or(false, |s| s == self) + } +} + +impl<'a> PartialEq<Value> for &'a str { + fn eq(&self, other: &Value) -> bool { + other.as_str().map_or(false, |s| s == *self) + } +} + +impl PartialEq<String> for Value { + fn eq(&self, other: &String) -> bool { + self.as_str().map_or(false, |s| s == other) + } +} + + +impl PartialEq<Value> for String { + fn eq(&self, other: &Value) -> bool { + other.as_str().map_or(false, |s| s == self) + } +} + +macro_rules! partialeq_numeric { + ($([$($ty:ty)*], $conversion:ident, $base:ty)*) => { + $($( + impl PartialEq<$ty> for Value { + fn eq(&self, other: &$ty) -> bool { + self.$conversion().map_or(false, |i| i == (*other as $base)) + } + } + + impl PartialEq<Value> for $ty { + fn eq(&self, other: &Value) -> bool { + other.$conversion().map_or(false, |i| i == (*self as $base)) + } + } + + impl<'a> PartialEq<$ty> for &'a Value { + fn eq(&self, other: &$ty) -> bool { + self.$conversion().map_or(false, |i| i == (*other as $base)) + } + } + + impl<'a> PartialEq<$ty> for &'a mut Value { + fn eq(&self, other: &$ty) -> bool { + self.$conversion().map_or(false, |i| i == (*other as $base)) + } + } + )*)* + } +} + +partialeq_numeric! { + [i8 i16 i32 i64 isize], as_i64, i64 + [u8 u16 u32 u64 usize], as_u64, u64 + [f32 f64], as_f64, f64 +} + +macro_rules! from_integer { + ($($ty:ident)*) => { + $( + impl From<$ty> for Value { + fn from(n: $ty) -> Self { + Value::Number(n.into()) + } + } + )* + }; +} + +from_integer! { + i8 i16 i32 i64 isize + u8 u16 u32 u64 usize +} + +impl From<f32> for Value { + /// Convert 32-bit floating point number to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// + /// # fn main() { + /// let f: f32 = 13.37; + /// let x: Value = f.into(); + /// # } + /// ``` + fn from(f: f32) -> Self { + From::from(f as f64) + } +} + +impl From<f64> for Value { + /// Convert 64-bit floating point number to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// + /// # fn main() { + /// let f: f64 = 13.37; + /// let x: Value = f.into(); + /// # } + /// ``` + fn from(f: f64) -> Self { + Number::from_f64(f).map_or(Value::Null, Value::Number) + } +} + +impl From<bool> for Value { + /// Convert boolean to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// + /// # fn main() { + /// let b = false; + /// let x: Value = b.into(); + /// # } + /// ``` + fn from(f: bool) -> Self { + Value::Bool(f) + } +} + +impl From<String> for Value { + /// Convert `String` to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// + /// # fn main() { + /// let s: String = "lorem".to_string(); + /// let x: Value = s.into(); + /// # } + /// ``` + fn from(f: String) -> Self { + Value::String(f) + } +} + +impl<'a> From<&'a str> for Value { + /// Convert string slice to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// + /// # fn main() { + /// let s: &str = "lorem"; + /// let x: Value = s.into(); + /// # } + /// ``` + fn from(f: &str) -> Self { + Value::String(f.to_string()) + } +} + +impl<'a> From<Cow<'a, str>> for Value { + /// Convert copy-on-write string to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// use std::borrow::Cow; + /// # fn main() { + /// + /// let s: Cow<str> = Cow::Borrowed("lorem"); + /// let x: Value = s.into(); + /// # } + /// ``` + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// use std::borrow::Cow; + /// + /// # fn main() { + /// let s: Cow<str> = Cow::Owned("lorem".to_string()); + /// let x: Value = s.into(); + /// # } + /// ``` + fn from(f: Cow<'a, str>) -> Self { + Value::String(f.to_string()) + } +} + +impl From<Map<String, Value>> for Value { + /// Convert map (with string keys) to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::{Map, Value}; + /// # fn main() { + /// + /// let mut m = Map::new(); + /// m.insert("Lorem".to_string(), "ipsum".into()); + /// let x: Value = m.into(); + /// # } + /// ``` + fn from(f: Map<String, Value>) -> Self { + Value::Object(f) + } +} + +impl<T: Into<Value>> From<Vec<T>> for Value { + /// Convert a `Vec` to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// # fn main() { + /// + /// let v = vec!["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into(); + /// # } + /// ``` + fn from(f: Vec<T>) -> Self { + Value::Array(f.into_iter().map(Into::into).collect()) + } +} + +impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value { + /// Convert a slice to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// # fn main() { + /// + /// let v: &[&str] = &["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into(); + /// # } + /// ``` + fn from(f: &'a [T]) -> Self { + Value::Array(f.into_iter().cloned().map(Into::into).collect()) + } +} + +impl<T: Into<Value>> ::std::iter::FromIterator<T> for Value { + /// Convert an iteratable type to a `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// # fn main() { + /// + /// let v = std::iter::repeat(42).take(5); + /// let x: Value = v.collect(); + /// # } + /// ``` + /// + /// ```rust + /// # extern crate serde_json; + /// use serde_json::Value; + /// + /// # fn main() { + /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into_iter().collect(); + /// # } + /// ``` + /// + /// ```rust + /// # extern crate serde_json; + /// use std::iter::FromIterator; + /// use serde_json::Value; + /// + /// # fn main() { + /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]); + /// # } + /// ``` + fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self { + let vec: Vec<Value> = iter.into_iter().map(|x| x.into()).collect(); + + Value::Array(vec) + } +} + +impl ser::Serialize for Value { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: ser::Serializer, + { + match *self { + Value::Null => serializer.serialize_unit(), + Value::Bool(b) => serializer.serialize_bool(b), + Value::Number(ref n) => n.serialize(serializer), + Value::String(ref s) => serializer.serialize_str(s), + Value::Array(ref v) => v.serialize(serializer), + Value::Object(ref m) => { + use serde::ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(m.len()))); + for (k, v) in m { + try!(map.serialize_key(k)); + try!(map.serialize_value(v)); + } + map.end() + } + } + } +} + +impl de::Deserialize for Value { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> + where D: de::Deserializer, + { + struct ValueVisitor; + + impl de::Visitor for ValueVisitor { + type Value = Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("any valid JSON value") + } + + #[inline] + fn visit_bool<E>(self, value: bool) -> Result<Value, E> { + Ok(Value::Bool(value)) + } + + #[inline] + fn visit_i64<E>(self, value: i64) -> Result<Value, E> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn visit_u64<E>(self, value: u64) -> Result<Value, E> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn visit_f64<E>(self, value: f64) -> Result<Value, E> { + Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) + } + + #[inline] + fn visit_str<E>(self, value: &str) -> Result<Value, E> + where E: de::Error, + { + self.visit_string(String::from(value)) + } + + #[inline] + fn visit_string<E>(self, value: String) -> Result<Value, E> { + Ok(Value::String(value)) + } + + #[inline] + fn visit_none<E>(self) -> Result<Value, E> { + Ok(Value::Null) + } + + #[inline] + fn visit_some<D>( + self, + deserializer: D + ) -> Result<Value, D::Error> + where D: de::Deserializer, + { + de::Deserialize::deserialize(deserializer) + } + + #[inline] + fn visit_unit<E>(self) -> Result<Value, E> { + Ok(Value::Null) + } + + #[inline] + fn visit_seq<V>(self, visitor: V) -> Result<Value, V::Error> + where V: de::SeqVisitor, + { + let values = try!(de::impls::VecVisitor::new() + .visit_seq(visitor)); + Ok(Value::Array(values)) + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> + where V: de::MapVisitor, + { + let mut values = Map::with_capacity(visitor.size_hint().0); + + while let Some((key, value)) = try!(visitor.visit()) { + values.insert(key, value); + } + + Ok(Value::Object(values)) + } + } + + deserializer.deserialize(ValueVisitor) + } +} + +struct WriterFormatter<'a, 'b: 'a> { + inner: &'a mut fmt::Formatter<'b>, +} + +impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + fn io_error<E>(_: E) -> io::Error { + // Value does not matter because fmt::Debug and fmt::Display impls + // below just map it to fmt::Error + io::Error::new(io::ErrorKind::Other, "fmt error") + } + let s = try!(str::from_utf8(buf).map_err(io_error)); + try!(self.inner.write_str(s).map_err(io_error)); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Display for Value { + /// Display a JSON value as a string. + /// + /// ```rust + /// # #[macro_use] extern crate serde_json; + /// # fn main() { + /// let json = json!({ "city": "London", "street": "10 Downing Street" }); + /// + /// // Compact format: + /// // + /// // {"city":"London","street":"10 Downing Street"} + /// let compact = format!("{}", json); + /// assert_eq!(compact, + /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}"); + /// + /// // Pretty format: + /// // + /// // { + /// // "city": "London", + /// // "street": "10 Downing Street" + /// // } + /// let pretty = format!("{:#}", json); + /// assert_eq!(pretty, + /// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}"); + /// # } + /// ``` + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let alternate = f.alternate(); + let mut wr = WriterFormatter { + inner: f, + }; + if alternate { + // {:#} + super::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error) + } else { + // {} + super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error) + } + } +} + +impl str::FromStr for Value { + type Err = Error; + fn from_str(s: &str) -> Result<Value, Error> { + super::de::from_str(s) + } +} + +struct Serializer; + +impl ser::Serializer for Serializer { + type Ok = Value; + type Error = Error; + + type SerializeSeq = SerializeVec; + type SerializeTuple = SerializeVec; + type SerializeTupleStruct = SerializeVec; + type SerializeTupleVariant = SerializeTupleVariant; + type SerializeMap = SerializeMap; + type SerializeStruct = SerializeMap; + type SerializeStructVariant = SerializeStructVariant; + + #[inline] + fn serialize_bool(self, value: bool) -> Result<Value, Error> { + Ok(Value::Bool(value)) + } + + #[inline] + fn serialize_i8(self, value: i8) -> Result<Value, Error> { + self.serialize_i64(value as i64) + } + + #[inline] + fn serialize_i16(self, value: i16) -> Result<Value, Error> { + self.serialize_i64(value as i64) + } + + #[inline] + fn serialize_i32(self, value: i32) -> Result<Value, Error> { + self.serialize_i64(value as i64) + } + + fn serialize_i64(self, value: i64) -> Result<Value, Error> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn serialize_u8(self, value: u8) -> Result<Value, Error> { + self.serialize_u64(value as u64) + } + + #[inline] + fn serialize_u16(self, value: u16) -> Result<Value, Error> { + self.serialize_u64(value as u64) + } + + #[inline] + fn serialize_u32(self, value: u32) -> Result<Value, Error> { + self.serialize_u64(value as u64) + } + + #[inline] + fn serialize_u64(self, value: u64) -> Result<Value, Error> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn serialize_f32(self, value: f32) -> Result<Value, Error> { + self.serialize_f64(value as f64) + } + + #[inline] + fn serialize_f64(self, value: f64) -> Result<Value, Error> { + Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) + } + + #[inline] + fn serialize_char(self, value: char) -> Result<Value, Error> { + let mut s = String::new(); + s.push(value); + self.serialize_str(&s) + } + + #[inline] + fn serialize_str(self, value: &str) -> Result<Value, Error> { + Ok(Value::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> { + let vec = value.iter().map(|&b| Value::Number(b.into())).collect(); + Ok(Value::Array(vec)) + } + + #[inline] + fn serialize_unit(self) -> Result<Value, Error> { + Ok(Value::Null) + } + + #[inline] + fn serialize_unit_struct( + self, + _name: &'static str + ) -> Result<Value, Error> { + self.serialize_unit() + } + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str + ) -> Result<Value, Error> { + self.serialize_str(variant) + } + + #[inline] + fn serialize_newtype_struct<T: ?Sized>( + self, + _name: &'static str, + value: &T + ) -> Result<Value, Error> + where T: ser::Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str, + value: &T + ) -> Result<Value, Error> + where T: ser::Serialize, + { + let mut values = Map::new(); + values.insert(String::from(variant), try!(to_value(&value))); + Ok(Value::Object(values)) + } + + #[inline] + fn serialize_none(self) -> Result<Value, Error> { + self.serialize_unit() + } + + #[inline] + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, Error> + where T: ser::Serialize, + { + value.serialize(self) + } + + fn serialize_seq( + self, + len: Option<usize> + ) -> Result<Self::SerializeSeq, Error> { + Ok(SerializeVec { + vec: Vec::with_capacity(len.unwrap_or(0)) + }) + } + + fn serialize_seq_fixed_size( + self, + size: usize + ) -> Result<Self::SerializeSeq, Error> { + self.serialize_seq(Some(size)) + } + + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> { + self.serialize_seq(Some(len)) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + len: usize + ) -> Result<Self::SerializeTupleStruct, Error> { + self.serialize_seq(Some(len)) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str, + len: usize + ) -> Result<Self::SerializeTupleVariant, Error> { + Ok(SerializeTupleVariant { + name: String::from(variant), + vec: Vec::with_capacity(len), + }) + } + + fn serialize_map( + self, + _len: Option<usize> + ) -> Result<Self::SerializeMap, Error> { + Ok(SerializeMap { + map: Map::new(), + next_key: None, + }) + } + + fn serialize_struct( + self, + _name: &'static str, + len: usize + ) -> Result<Self::SerializeStruct, Error> { + self.serialize_map(Some(len)) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: usize, + variant: &'static str, + _len: usize + ) -> Result<Self::SerializeStructVariant, Error> { + Ok(SerializeStructVariant { + name: String::from(variant), + map: Map::new(), + }) + } +} + +#[doc(hidden)] +pub struct SerializeVec { + vec: Vec<Value>, +} + +#[doc(hidden)] +pub struct SerializeTupleVariant { + name: String, + vec: Vec<Value>, +} + +#[doc(hidden)] +pub struct SerializeMap { + map: Map<String, Value>, + next_key: Option<String>, +} + +#[doc(hidden)] +pub struct SerializeStructVariant { + name: String, + map: Map<String, Value>, +} + +impl ser::SerializeSeq for SerializeVec { + type Ok = Value; + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + self.vec.push(try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + Ok(Value::Array(self.vec)) + } +} + +impl ser::SerializeTuple for SerializeVec { + type Ok = Value; + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + ser::SerializeSeq::serialize_element(self, value) + } + + fn end(self) -> Result<Value, Error> { + ser::SerializeSeq::end(self) + } +} + +impl ser::SerializeTupleStruct for SerializeVec { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + ser::SerializeSeq::serialize_element(self, value) + } + + fn end(self) -> Result<Value, Error> { + ser::SerializeSeq::end(self) + } +} + +impl ser::SerializeTupleVariant for SerializeTupleVariant { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + self.vec.push(try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + let mut object = Map::new(); + + object.insert(self.name, Value::Array(self.vec)); + + Ok(Value::Object(object)) + } +} + +impl ser::SerializeMap for SerializeMap { + type Ok = Value; + type Error = Error; + + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error> + where T: ser::Serialize + { + match try!(to_value(&key)) { + Value::String(s) => self.next_key = Some(s), + Value::Number(n) => { + if n.is_u64() || n.is_i64() { + self.next_key = Some(n.to_string()) + } else { + return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)) + } + } + _ => return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)), + }; + Ok(()) + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + let key = self.next_key.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let key = key.expect("serialize_value called before serialize_key"); + self.map.insert(key, try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + Ok(Value::Object(self.map)) + } +} + +impl ser::SerializeStruct for SerializeMap { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + try!(ser::SerializeMap::serialize_key(self, key)); + ser::SerializeMap::serialize_value(self, value) + } + + fn end(self) -> Result<Value, Error> { + ser::SerializeMap::end(self) + } +} + +impl ser::SerializeStructVariant for SerializeStructVariant { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where T: ser::Serialize + { + self.map.insert(String::from(key), try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + let mut object = Map::new(); + + object.insert(self.name, Value::Object(self.map)); + + Ok(Value::Object(object)) + } +} + +impl de::Deserializer for Value { + type Error = Error; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor, + { + match self { + Value::Null => visitor.visit_unit(), + Value::Bool(v) => visitor.visit_bool(v), + Value::Number(n) => n.deserialize(visitor), + Value::String(v) => visitor.visit_string(v), + Value::Array(v) => { + let len = v.len(); + let mut deserializer = SeqDeserializer::new(v); + let seq = try!(visitor.visit_seq(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + Value::Object(v) => { + let len = v.len(); + let mut deserializer = MapDeserializer::new(v); + let map = try!(visitor.visit_map(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(map) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in map")) + } + } + } + } + + #[inline] + fn deserialize_option<V>( + self, + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + match self { + Value::Null => visitor.visit_none(), + _ => visitor.visit_some(self), + } + } + + #[inline] + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + let (variant, value) = match self { + Value::Object(value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key")); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key")); + } + (variant, Some(value)) + } + Value::String(variant) => (variant, None), + other => { + return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); + } + }; + + visitor.visit_enum(EnumDeserializer { + variant: variant, + value: value, + }) + } + + #[inline] + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V + ) -> Result<V::Value, Self::Error> + where V: de::Visitor, + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct + struct_field tuple ignored_any + } +} + +struct EnumDeserializer { + variant: String, + value: Option<Value>, +} + +impl de::EnumVisitor for EnumDeserializer { + type Error = Error; + type Variant = VariantDeserializer; + + fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), Error> + where V: de::DeserializeSeed, + { + let variant = self.variant.into_deserializer(); + let visitor = VariantDeserializer { value: self.value }; + seed.deserialize(variant).map(|v| (v, visitor)) + } +} + +struct VariantDeserializer { + value: Option<Value>, +} + +impl de::VariantVisitor for VariantDeserializer { + type Error = Error; + + fn visit_unit(self) -> Result<(), Error> { + match self.value { + Some(value) => de::Deserialize::deserialize(value), + None => Ok(()), + } + } + + fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Error> + where T: de::DeserializeSeed, + { + match self.value { + Some(value) => seed.deserialize(value), + None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")), + } + } + + fn visit_tuple<V>( + self, + _len: usize, + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + match self.value { + Some(Value::Array(v)) => { + de::Deserializer::deserialize(SeqDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), + None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant")) + } + } + + fn visit_struct<V>( + self, + _fields: &'static [&'static str], + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + match self.value { + Some(Value::Object(v)) => { + de::Deserializer::deserialize(MapDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), + _ => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant")) + } + } +} + +struct SeqDeserializer { + iter: vec::IntoIter<Value>, +} + +impl SeqDeserializer { + fn new(vec: Vec<Value>) -> Self { + SeqDeserializer { + iter: vec.into_iter(), + } + } +} + +impl de::Deserializer for SeqDeserializer { + type Error = Error; + + #[inline] + fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl de::SeqVisitor for SeqDeserializer { + type Error = Error; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where T: de::DeserializeSeed, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +struct MapDeserializer { + iter: <Map<String, Value> as IntoIterator>::IntoIter, + value: Option<Value>, +} + +impl MapDeserializer { + fn new(map: Map<String, Value>) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + } + } +} + +impl de::MapVisitor for MapDeserializer { + type Error = Error; + + fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where T: de::DeserializeSeed, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error> + where T: de::DeserializeSeed, + { + match self.value.take() { + Some(value) => seed.deserialize(value), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +impl de::Deserializer for MapDeserializer { + type Error = Error; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor, + { + visitor.visit_map(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl<'a> de::Deserializer for &'a Value { + type Error = Error; + + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor, + { + match *self { + Value::Null => visitor.visit_unit(), + Value::Bool(v) => visitor.visit_bool(v), + Value::Number(ref n) => n.deserialize(visitor), + Value::String(ref v) => visitor.visit_str(v), + Value::Array(ref v) => { + let len = v.len(); + let mut deserializer = SeqRefDeserializer::new(v); + let seq = try!(visitor.visit_seq(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + Value::Object(ref v) => { + let len = v.len(); + let mut deserializer = MapRefDeserializer::new(v); + let map = try!(visitor.visit_map(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(map) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in map")) + } + } + } + } + + fn deserialize_option<V>( + self, + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + match *self { + Value::Null => visitor.visit_none(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + let (variant, value) = match *self { + Value::Object(ref value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key")); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key")); + } + (variant, Some(value)) + } + Value::String(ref variant) => (variant, None), + ref other => { + return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); + } + }; + + visitor.visit_enum(EnumRefDeserializer { + variant: variant, + value: value, + }) + } + + #[inline] + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V + ) -> Result<V::Value, Self::Error> + where V: de::Visitor, + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct + struct_field tuple ignored_any + } +} + +struct EnumRefDeserializer<'a> { + variant: &'a str, + value: Option<&'a Value>, +} + +impl<'a> de::EnumVisitor for EnumRefDeserializer<'a> { + type Error = Error; + type Variant = VariantRefDeserializer<'a>; + + fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error> + where V: de::DeserializeSeed, + { + let variant = self.variant.into_deserializer(); + let visitor = VariantRefDeserializer { value: self.value }; + seed.deserialize(variant).map(|v| (v, visitor)) + } +} + +struct VariantRefDeserializer<'a> { + value: Option<&'a Value>, +} + +impl<'a> de::VariantVisitor for VariantRefDeserializer<'a> { + type Error = Error; + + fn visit_unit(self) -> Result<(), Error> { + match self.value { + Some(value) => de::Deserialize::deserialize(value), + None => Ok(()), + } + } + + fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Error> + where T: de::DeserializeSeed, + { + match self.value { + Some(value) => seed.deserialize(value), + None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")), + } + } + + fn visit_tuple<V>( + self, + _len: usize, + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + match self.value { + Some(&Value::Array(ref v)) => { + de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), + None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant")) + } + } + + fn visit_struct<V>( + self, + _fields: &'static [&'static str], + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor, + { + match self.value { + Some(&Value::Object(ref v)) => { + de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), + _ => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant")) + } + } +} + +struct SeqRefDeserializer<'a> { + iter: slice::Iter<'a, Value>, +} + +impl<'a> SeqRefDeserializer<'a> { + fn new(slice: &'a [Value]) -> Self { + SeqRefDeserializer { + iter: slice.iter(), + } + } +} + +impl<'a> de::Deserializer for SeqRefDeserializer<'a> { + type Error = Error; + + #[inline] + fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl<'a> de::SeqVisitor for SeqRefDeserializer<'a> { + type Error = Error; + + fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where T: de::DeserializeSeed, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +struct MapRefDeserializer<'a> { + iter: <&'a Map<String, Value> as IntoIterator>::IntoIter, + value: Option<&'a Value>, +} + +impl<'a> MapRefDeserializer<'a> { + fn new(map: &'a Map<String, Value>) -> Self { + MapRefDeserializer { + iter: map.into_iter(), + value: None, + } + } +} + +impl<'a> de::MapVisitor for MapRefDeserializer<'a> { + type Error = Error; + + fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where T: de::DeserializeSeed, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize((&**key).into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error> + where T: de::DeserializeSeed, + { + match self.value.take() { + Some(value) => seed.deserialize(value), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +impl<'a> de::Deserializer for MapRefDeserializer<'a> { + type Error = Error; + + #[inline] + fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor, + { + visitor.visit_map(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } +} + +impl Value { + fn unexpected(&self) -> Unexpected { + match *self { + Value::Null => Unexpected::Unit, + Value::Bool(b) => Unexpected::Bool(b), + Value::Number(ref n) => { + if let Some(u) = n.as_u64() { + Unexpected::Unsigned(u) + } else if let Some(i) = n.as_i64() { + Unexpected::Signed(i) + } else if let Some(f) = n.as_f64() { + Unexpected::Float(f) + } else { + panic!("unexpected number") + } + } + Value::String(ref s) => Unexpected::Str(s), + Value::Array(_) => Unexpected::Seq, + Value::Object(_) => Unexpected::Map, + } + } +} + +/// Convert a `T` into `serde_json::Value` which is an enum that can represent +/// any valid JSON data. +/// +/// This conversion can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +/// +/// ```rust +/// # use serde_json::Value; +/// let val = serde_json::to_value("s").unwrap(); +/// assert_eq!(val, Value::String("s".to_owned())); +/// ``` +#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] +// Taking by value is more friendly to iterator adapters, option and result +// consumers, etc. See https://github.com/serde-rs/json/pull/149. +pub fn to_value<T>(value: T) -> Result<Value, Error> + where T: ser::Serialize, +{ + value.serialize(Serializer) +} + +/// Interpret a `serde_json::Value` as an instance of type `T`. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +pub fn from_value<T>(value: Value) -> Result<T, Error> + where T: de::Deserialize, +{ + de::Deserialize::deserialize(value) +} + +/// Representation of any serializable data as a `serde_json::Value`. +pub trait ToJson { + /// Represent `self` as a `serde_json::Value`. Note that `Value` is not a + /// JSON string. If you need a string, use `serde_json::to_string` instead. + /// + /// This conversion can fail if `T`'s implementation of `Serialize` decides + /// to fail, or if `T` contains a map with non-string keys. + fn to_json(&self) -> Result<Value, Error>; +} + +impl<T: ?Sized> ToJson for T + where T: ser::Serialize, +{ + fn to_json(&self) -> Result<Value, Error> { + to_value(self) + } +} diff --git a/bash-5.1/vendor/siphasher/.cargo-checksum.json b/bash-5.1/vendor/siphasher/.cargo-checksum.json new file mode 100644 index 0000000..ad9fa0e --- /dev/null +++ b/bash-5.1/vendor/siphasher/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYING":"8634fd107e2eeb3c4b37856fbaeea46abe175205be4226ddc77d10fa37ed475e","Cargo.toml":"ebfdbbb9ab183ec790e7705ab2e6bb95adfd5544afe88049ffeeb465861c293d","README.md":"5a13cf8735463c1e79b42f374491bd863e4d6d252cd233003184874b913f8e28","src/lib.rs":"a4be809996378de27017d2aa1b6ef0de17e96b84a2cdb210d69241597de208c1","src/sip.rs":"247dcf5239933e323fffceaa296b14e20a0e90f4e7d950ed92dfa8e909a8e574","src/sip128.rs":"bf05d1621ed7185b2d9c0889dde16dfe90d8bb6ad25113895ced956f2999fac1","src/tests.rs":"0898410224336ad8ac1b8979a2cdb203833e41f065f337282012fbd8f0921ea9","src/tests128.rs":"bbe8f587edb4bd42dff796077b9150251fe7999ad91f9398ec3c4b683da81d46"},"package":"0b8de496cf83d4ed58b6be86c3a275b8602f6ffe98d3024a869e124147a9a3ac"} \ No newline at end of file diff --git a/bash-5.1/vendor/siphasher/COPYING b/bash-5.1/vendor/siphasher/COPYING new file mode 100644 index 0000000..23dc10e --- /dev/null +++ b/bash-5.1/vendor/siphasher/COPYING @@ -0,0 +1,6 @@ +Copyright 2012-2016 The Rust Project Developers. + +Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +<LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +option. diff --git a/bash-5.1/vendor/siphasher/Cargo.toml b/bash-5.1/vendor/siphasher/Cargo.toml new file mode 100644 index 0000000..cd0bfbd --- /dev/null +++ b/bash-5.1/vendor/siphasher/Cargo.toml @@ -0,0 +1,30 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "siphasher" +version = "0.2.3" +authors = ["Frank Denis <github@pureftpd.org>"] +description = "SipHash functions from rust-core < 1.13" +homepage = "https://docs.rs/siphasher" +documentation = "https://docs.rs/siphasher" +readme = "README.md" +keywords = ["crypto", "hash", "siphash"] +categories = ["algorithms", "cryptography"] +license = "MIT/Apache-2.0" +repository = "https://github.com/jedisct1/rust-siphash" +[profile.release] +opt-level = 3 +lto = true +panic = "abort" +[badges.travis-ci] +repository = "jedisct1/rust-siphash" diff --git a/bash-5.1/vendor/siphasher/README.md b/bash-5.1/vendor/siphasher/README.md new file mode 100644 index 0000000..d2b81a7 --- /dev/null +++ b/bash-5.1/vendor/siphasher/README.md @@ -0,0 +1,37 @@ +SipHash implementation for Rust +=============================== + +SipHash was recently removed from rust-core. + +This crate brings `SipHasher`, `SipHasher13` and `SipHash24` back. +It is based on the original implementation from rust-core and exposes the +same API. + +In addition, it can return 128-bit tags. + +The `sip` module implements the standard 64-bit mode, whereas the `sip128` +module implements the 128-bit mode. + +Usage +----- +In `Cargo.toml`: + +```toml +[dependencies] +siphasher = "~0.2" +``` + +64-bit mode: +```rust +extern crate siphasher; + +use siphasher::sip::{SipHasher, SipHasher13, SipHasher24}; +``` + +128-bit mode: +```rust +use siphasher::sip128::{Hasher128, Siphasher, SipHasher13, SipHasher24}; +``` + +[API documentation](https://docs.rs/siphasher/) +----------------------------------------------- diff --git a/bash-5.1/vendor/siphasher/src/lib.rs b/bash-5.1/vendor/siphasher/src/lib.rs new file mode 100644 index 0000000..6cb2702 --- /dev/null +++ b/bash-5.1/vendor/siphasher/src/lib.rs @@ -0,0 +1,13 @@ +#![cfg_attr(not(test), no_std)] + +#[cfg(test)] +extern crate core; + +pub mod sip; +pub mod sip128; + +#[cfg(test)] +mod tests; + +#[cfg(test)] +mod tests128; diff --git a/bash-5.1/vendor/siphasher/src/sip.rs b/bash-5.1/vendor/siphasher/src/sip.rs new file mode 100644 index 0000000..f442c17 --- /dev/null +++ b/bash-5.1/vendor/siphasher/src/sip.rs @@ -0,0 +1,411 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! An implementation of SipHash. + +use core::cmp; +use core::hash; +use core::marker::PhantomData; +use core::mem; +use core::ptr; +use core::slice; + +/// An implementation of SipHash 1-3. +/// +/// See: <https://131002.net/siphash/> +#[derive(Debug, Clone, Copy, Default)] +pub struct SipHasher13 { + hasher: Hasher<Sip13Rounds>, +} + +/// An implementation of SipHash 2-4. +/// +/// See: <https://131002.net/siphash/> +#[derive(Debug, Clone, Copy, Default)] +pub struct SipHasher24 { + hasher: Hasher<Sip24Rounds>, +} + +/// An implementation of SipHash 2-4. +/// +/// See: <https://131002.net/siphash/> +/// +/// SipHash is a general-purpose hashing function: it runs at a good +/// speed (competitive with Spooky and City) and permits strong _keyed_ +/// hashing. This lets you key your hashtables from a strong RNG, such as +/// [`rand::os::OsRng`](https://doc.rust-lang.org/rand/rand/os/struct.OsRng.html). +/// +/// Although the SipHash algorithm is considered to be generally strong, +/// it is not intended for cryptographic purposes. As such, all +/// cryptographic uses of this implementation are _strongly discouraged_. +#[derive(Debug, Clone, Copy, Default)] +pub struct SipHasher(SipHasher24); + +#[derive(Debug, Clone, Copy)] +struct Hasher<S: Sip> { + k0: u64, + k1: u64, + length: usize, // how many bytes we've processed + state: State, // hash State + tail: u64, // unprocessed bytes le + ntail: usize, // how many bytes in tail are valid + _marker: PhantomData<S>, +} + +#[derive(Debug, Clone, Copy)] +struct State { + // v0, v2 and v1, v3 show up in pairs in the algorithm, + // and simd implementations of SipHash will use vectors + // of v02 and v13. By placing them in this order in the struct, + // the compiler can pick up on just a few simd optimizations by itself. + v0: u64, + v2: u64, + v1: u64, + v3: u64, +} + +macro_rules! compress { + ($state:expr) => ({ + compress!($state.v0, $state.v1, $state.v2, $state.v3) + }); + ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => + ({ + $v0 = $v0.wrapping_add($v1); $v1 = $v1.rotate_left(13); $v1 ^= $v0; + $v0 = $v0.rotate_left(32); + $v2 = $v2.wrapping_add($v3); $v3 = $v3.rotate_left(16); $v3 ^= $v2; + $v0 = $v0.wrapping_add($v3); $v3 = $v3.rotate_left(21); $v3 ^= $v0; + $v2 = $v2.wrapping_add($v1); $v1 = $v1.rotate_left(17); $v1 ^= $v2; + $v2 = $v2.rotate_left(32); + }); +} + +/// Load an integer of the desired type from a byte stream, in LE order. Uses +/// `copy_nonoverlapping` to let the compiler generate the most efficient way +/// to load it from a possibly unaligned address. +/// +/// Unsafe because: unchecked indexing at `i..i+size_of(int_ty)` +macro_rules! load_int_le { + ($buf:expr, $i:expr, $int_ty:ident) => + ({ + debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len()); + let mut data = 0 as $int_ty; + ptr::copy_nonoverlapping($buf.get_unchecked($i), + &mut data as *mut _ as *mut u8, + mem::size_of::<$int_ty>()); + data.to_le() + }); +} + +/// Load an u64 using up to 7 bytes of a byte slice. +/// +/// Unsafe because: unchecked indexing at start..start+len +#[inline] +unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { + debug_assert!(len < 8); + let mut i = 0; // current byte index (from LSB) in the output u64 + let mut out = 0; + if i + 3 < len { + out = load_int_le!(buf, start + i, u32) as u64; + i += 4; + } + if i + 1 < len { + out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8); + i += 2 + } + if i < len { + out |= (*buf.get_unchecked(start + i) as u64) << (i * 8); + i += 1; + } + debug_assert_eq!(i, len); + out +} + +impl SipHasher { + /// Creates a new `SipHasher` with the two initial keys set to 0. + #[inline] + pub fn new() -> SipHasher { + SipHasher::new_with_keys(0, 0) + } + + /// Creates a `SipHasher` that is keyed off the provided keys. + #[inline] + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher { + SipHasher(SipHasher24::new_with_keys(key0, key1)) + } + + /// Get the keys used by this hasher + pub fn keys(&self) -> (u64, u64) { + (self.0.hasher.k0, self.0.hasher.k1) + } +} + +impl SipHasher13 { + /// Creates a new `SipHasher13` with the two initial keys set to 0. + #[inline] + pub fn new() -> SipHasher13 { + SipHasher13::new_with_keys(0, 0) + } + + /// Creates a `SipHasher13` that is keyed off the provided keys. + #[inline] + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { + SipHasher13 { + hasher: Hasher::new_with_keys(key0, key1), + } + } + + /// Get the keys used by this hasher + pub fn keys(&self) -> (u64, u64) { + (self.hasher.k0, self.hasher.k1) + } +} + +impl SipHasher24 { + /// Creates a new `SipHasher24` with the two initial keys set to 0. + #[inline] + pub fn new() -> SipHasher24 { + SipHasher24::new_with_keys(0, 0) + } + + /// Creates a `SipHasher24` that is keyed off the provided keys. + #[inline] + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher24 { + SipHasher24 { + hasher: Hasher::new_with_keys(key0, key1), + } + } + + /// Get the keys used by this hasher + pub fn keys(&self) -> (u64, u64) { + (self.hasher.k0, self.hasher.k1) + } +} + +impl<S: Sip> Hasher<S> { + #[inline] + fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> { + let mut state = Hasher { + k0: key0, + k1: key1, + length: 0, + state: State { + v0: 0, + v1: 0, + v2: 0, + v3: 0, + }, + tail: 0, + ntail: 0, + _marker: PhantomData, + }; + state.reset(); + state + } + + #[inline] + fn reset(&mut self) { + self.length = 0; + self.state.v0 = self.k0 ^ 0x736f6d6570736575; + self.state.v1 = self.k1 ^ 0x646f72616e646f6d; + self.state.v2 = self.k0 ^ 0x6c7967656e657261; + self.state.v3 = self.k1 ^ 0x7465646279746573; + self.ntail = 0; + } + + // Specialized write function that is only valid for buffers with len <= 8. + // It's used to force inlining of write_u8 and write_usize, those would normally be inlined + // except for composite types (that includes slices and str hashing because of delimiter). + // Without this extra push the compiler is very reluctant to inline delimiter writes, + // degrading performance substantially for the most common use cases. + #[inline(always)] + fn short_write(&mut self, msg: &[u8]) { + debug_assert!(msg.len() <= 8); + let length = msg.len(); + self.length += length; + + let needed = 8 - self.ntail; + let fill = cmp::min(length, needed); + if fill == 8 { + self.tail = unsafe { load_int_le!(msg, 0, u64) }; + } else { + self.tail |= unsafe { u8to64_le(msg, 0, fill) } << (8 * self.ntail); + if length < needed { + self.ntail += length; + return; + } + } + self.state.v3 ^= self.tail; + S::c_rounds(&mut self.state); + self.state.v0 ^= self.tail; + + // Buffered tail is now flushed, process new input. + self.ntail = length - needed; + self.tail = unsafe { u8to64_le(msg, needed, self.ntail) }; + } +} + +impl hash::Hasher for SipHasher { + #[inline] + fn write(&mut self, msg: &[u8]) { + self.0.write(msg) + } + + #[inline] + fn finish(&self) -> u64 { + self.0.finish() + } +} + +impl hash::Hasher for SipHasher13 { + #[inline] + fn write(&mut self, msg: &[u8]) { + self.hasher.write(msg) + } + + #[inline] + fn finish(&self) -> u64 { + self.hasher.finish() + } +} + +impl hash::Hasher for SipHasher24 { + #[inline] + fn write(&mut self, msg: &[u8]) { + self.hasher.write(msg) + } + + #[inline] + fn finish(&self) -> u64 { + self.hasher.finish() + } +} + +impl<S: Sip> hash::Hasher for Hasher<S> { + // see short_write comment for explanation + #[inline] + fn write_usize(&mut self, i: usize) { + let bytes = unsafe { + slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>()) + }; + self.short_write(bytes); + } + + // see short_write comment for explanation + #[inline] + fn write_u8(&mut self, i: u8) { + self.short_write(&[i]); + } + + #[inline] + fn write(&mut self, msg: &[u8]) { + let length = msg.len(); + self.length += length; + + let mut needed = 0; + + if self.ntail != 0 { + needed = 8 - self.ntail; + self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); + if length < needed { + self.ntail += length; + return; + } else { + self.state.v3 ^= self.tail; + S::c_rounds(&mut self.state); + self.state.v0 ^= self.tail; + self.ntail = 0; + } + } + + // Buffered tail is now flushed, process new input. + let len = length - needed; + let left = len & 0x7; + + let mut i = needed; + while i < len - left { + let mi = unsafe { load_int_le!(msg, i, u64) }; + + self.state.v3 ^= mi; + S::c_rounds(&mut self.state); + self.state.v0 ^= mi; + + i += 8; + } + + self.tail = unsafe { u8to64_le(msg, i, left) }; + self.ntail = left; + } + + #[inline] + fn finish(&self) -> u64 { + let mut state = self.state; + + let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; + + state.v3 ^= b; + S::c_rounds(&mut state); + state.v0 ^= b; + + state.v2 ^= 0xff; + S::d_rounds(&mut state); + + state.v0 ^ state.v1 ^ state.v2 ^ state.v3 + } +} + +impl<S: Sip> Default for Hasher<S> { + /// Creates a `Hasher<S>` with the two initial keys set to 0. + #[inline] + fn default() -> Hasher<S> { + Hasher::new_with_keys(0, 0) + } +} + +#[doc(hidden)] +trait Sip { + fn c_rounds(_: &mut State); + fn d_rounds(_: &mut State); +} + +#[derive(Debug, Clone, Copy, Default)] +struct Sip13Rounds; + +impl Sip for Sip13Rounds { + #[inline] + fn c_rounds(state: &mut State) { + compress!(state); + } + + #[inline] + fn d_rounds(state: &mut State) { + compress!(state); + compress!(state); + compress!(state); + } +} + +#[derive(Debug, Clone, Copy, Default)] +struct Sip24Rounds; + +impl Sip for Sip24Rounds { + #[inline] + fn c_rounds(state: &mut State) { + compress!(state); + compress!(state); + } + + #[inline] + fn d_rounds(state: &mut State) { + compress!(state); + compress!(state); + compress!(state); + compress!(state); + } +} diff --git a/bash-5.1/vendor/siphasher/src/sip128.rs b/bash-5.1/vendor/siphasher/src/sip128.rs new file mode 100644 index 0000000..790eb00 --- /dev/null +++ b/bash-5.1/vendor/siphasher/src/sip128.rs @@ -0,0 +1,482 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! An implementation of SipHash with a 128-bit output. + +use core::cmp; +use core::hash; +use core::marker::PhantomData; +use core::mem; +use core::ptr; +use core::slice; + +/// A 128-bit (2x64) hash output +#[derive(Debug, Clone, Copy, Default)] +pub struct Hash128 { + pub h1: u64, + pub h2: u64, +} + +/// An implementation of SipHash128 1-3. +#[derive(Debug, Clone, Copy, Default)] +pub struct SipHasher13 { + hasher: Hasher<Sip13Rounds>, +} + +/// An implementation of SipHash128 2-4. +#[derive(Debug, Clone, Copy, Default)] +pub struct SipHasher24 { + hasher: Hasher<Sip24Rounds>, +} + +/// An implementation of SipHash128 2-4. +/// +/// SipHash is a general-purpose hashing function: it runs at a good +/// speed (competitive with Spooky and City) and permits strong _keyed_ +/// hashing. This lets you key your hashtables from a strong RNG, such as +/// [`rand::os::OsRng`](https://doc.rust-lang.org/rand/rand/os/struct.OsRng.html). +/// +/// Although the SipHash algorithm is considered to be generally strong, +/// it is not intended for cryptographic purposes. As such, all +/// cryptographic uses of this implementation are _strongly discouraged_. +#[derive(Debug, Clone, Copy, Default)] +pub struct SipHasher(SipHasher24); + +#[derive(Debug, Copy)] +struct Hasher<S: Sip> { + k0: u64, + k1: u64, + length: usize, // how many bytes we've processed + state: State, // hash State + tail: u64, // unprocessed bytes le + ntail: usize, // how many bytes in tail are valid + _marker: PhantomData<S>, +} + +#[derive(Debug, Clone, Copy)] +struct State { + // v0, v2 and v1, v3 show up in pairs in the algorithm, + // and simd implementations of SipHash will use vectors + // of v02 and v13. By placing them in this order in the struct, + // the compiler can pick up on just a few simd optimizations by itself. + v0: u64, + v2: u64, + v1: u64, + v3: u64, +} + +macro_rules! compress { + ($state:expr) => ({ + compress!($state.v0, $state.v1, $state.v2, $state.v3) + }); + ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => + ({ + $v0 = $v0.wrapping_add($v1); $v1 = $v1.rotate_left(13); $v1 ^= $v0; + $v0 = $v0.rotate_left(32); + $v2 = $v2.wrapping_add($v3); $v3 = $v3.rotate_left(16); $v3 ^= $v2; + $v0 = $v0.wrapping_add($v3); $v3 = $v3.rotate_left(21); $v3 ^= $v0; + $v2 = $v2.wrapping_add($v1); $v1 = $v1.rotate_left(17); $v1 ^= $v2; + $v2 = $v2.rotate_left(32); + }); +} + +/// Load an integer of the desired type from a byte stream, in LE order. Uses +/// `copy_nonoverlapping` to let the compiler generate the most efficient way +/// to load it from a possibly unaligned address. +/// +/// Unsafe because: unchecked indexing at `i..i+size_of(int_ty)` +macro_rules! load_int_le { + ($buf:expr, $i:expr, $int_ty:ident) => + ({ + debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len()); + let mut data = 0 as $int_ty; + ptr::copy_nonoverlapping($buf.get_unchecked($i), + &mut data as *mut _ as *mut u8, + mem::size_of::<$int_ty>()); + data.to_le() + }); +} + +/// Load an u64 using up to 7 bytes of a byte slice. +/// +/// Unsafe because: unchecked indexing at start..start+len +#[inline] +unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { + debug_assert!(len < 8); + let mut i = 0; // current byte index (from LSB) in the output u64 + let mut out = 0; + if i + 3 < len { + out = load_int_le!(buf, start + i, u32) as u64; + i += 4; + } + if i + 1 < len { + out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8); + i += 2 + } + if i < len { + out |= (*buf.get_unchecked(start + i) as u64) << (i * 8); + i += 1; + } + debug_assert_eq!(i, len); + out +} + +pub trait Hasher128 { + /// Return a 128-bit hash + fn finish128(&self) -> Hash128; +} + +impl SipHasher { + /// Creates a new `SipHasher` with the two initial keys set to 0. + #[inline] + pub fn new() -> SipHasher { + SipHasher::new_with_keys(0, 0) + } + + /// Creates a `SipHasher` that is keyed off the provided keys. + #[inline] + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher { + SipHasher(SipHasher24::new_with_keys(key0, key1)) + } + + /// Get the keys used by this hasher + pub fn keys(&self) -> (u64, u64) { + (self.0.hasher.k0, self.0.hasher.k1) + } +} + +impl Hasher128 for SipHasher { + /// Return a 128-bit hash + #[inline] + fn finish128(&self) -> Hash128 { + self.0.finish128() + } +} + +impl SipHasher13 { + /// Creates a new `SipHasher13` with the two initial keys set to 0. + #[inline] + pub fn new() -> SipHasher13 { + SipHasher13::new_with_keys(0, 0) + } + + /// Creates a `SipHasher13` that is keyed off the provided keys. + #[inline] + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { + SipHasher13 { + hasher: Hasher::new_with_keys(key0, key1), + } + } + + /// Get the keys used by this hasher + pub fn keys(&self) -> (u64, u64) { + (self.hasher.k0, self.hasher.k1) + } +} + +impl Hasher128 for SipHasher13 { + /// Return a 128-bit hash + #[inline] + fn finish128(&self) -> Hash128 { + self.hasher.finish128() + } +} + +impl SipHasher24 { + /// Creates a new `SipHasher24` with the two initial keys set to 0. + #[inline] + pub fn new() -> SipHasher24 { + SipHasher24::new_with_keys(0, 0) + } + + /// Creates a `SipHasher24` that is keyed off the provided keys. + #[inline] + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher24 { + SipHasher24 { + hasher: Hasher::new_with_keys(key0, key1), + } + } + + /// Get the keys used by this hasher + pub fn keys(&self) -> (u64, u64) { + (self.hasher.k0, self.hasher.k1) + } +} + +impl Hasher128 for SipHasher24 { + /// Return a 128-bit hash + #[inline] + fn finish128(&self) -> Hash128 { + self.hasher.finish128() + } +} + +impl<S: Sip> Hasher<S> { + #[inline] + fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> { + let mut state = Hasher { + k0: key0, + k1: key1, + length: 0, + state: State { + v0: 0, + v1: 0xee, + v2: 0, + v3: 0, + }, + tail: 0, + ntail: 0, + _marker: PhantomData, + }; + state.reset(); + state + } + + #[inline] + fn reset(&mut self) { + self.length = 0; + self.state.v0 = self.k0 ^ 0x736f6d6570736575; + self.state.v1 = self.k1 ^ 0x646f72616e646f83; + self.state.v2 = self.k0 ^ 0x6c7967656e657261; + self.state.v3 = self.k1 ^ 0x7465646279746573; + self.ntail = 0; + } + + // Specialized write function that is only valid for buffers with len <= 8. + // It's used to force inlining of write_u8 and write_usize, those would normally be inlined + // except for composite types (that includes slices and str hashing because of delimiter). + // Without this extra push the compiler is very reluctant to inline delimiter writes, + // degrading performance substantially for the most common use cases. + #[inline(always)] + fn short_write(&mut self, msg: &[u8]) { + debug_assert!(msg.len() <= 8); + let length = msg.len(); + self.length += length; + + let needed = 8 - self.ntail; + let fill = cmp::min(length, needed); + if fill == 8 { + self.tail = unsafe { load_int_le!(msg, 0, u64) }; + } else { + self.tail |= unsafe { u8to64_le(msg, 0, fill) } << (8 * self.ntail); + if length < needed { + self.ntail += length; + return; + } + } + self.state.v3 ^= self.tail; + S::c_rounds(&mut self.state); + self.state.v0 ^= self.tail; + + // Buffered tail is now flushed, process new input. + self.ntail = length - needed; + self.tail = unsafe { u8to64_le(msg, needed, self.ntail) }; + } +} + +impl<S: Sip> Hasher<S> { + #[inline] + pub fn finish128(&self) -> Hash128 { + let mut state = self.state; + + let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; + + state.v3 ^= b; + S::c_rounds(&mut state); + state.v0 ^= b; + + state.v2 ^= 0xee; + S::d_rounds(&mut state); + let h1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; + + state.v1 ^= 0xdd; + S::d_rounds(&mut state); + let h2 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; + + Hash128 { h1: h1, h2: h2 } + } +} + +impl hash::Hasher for SipHasher { + #[inline] + fn write(&mut self, msg: &[u8]) { + self.0.write(msg) + } + + #[inline] + fn finish(&self) -> u64 { + self.0.finish() + } +} + +impl hash::Hasher for SipHasher13 { + #[inline] + fn write(&mut self, msg: &[u8]) { + self.hasher.write(msg) + } + + #[inline] + fn finish(&self) -> u64 { + self.hasher.finish() + } +} + +impl hash::Hasher for SipHasher24 { + #[inline] + fn write(&mut self, msg: &[u8]) { + self.hasher.write(msg) + } + + #[inline] + fn finish(&self) -> u64 { + self.hasher.finish() + } +} + +impl<S: Sip> hash::Hasher for Hasher<S> { + // see short_write comment for explanation + #[inline] + fn write_usize(&mut self, i: usize) { + let bytes = unsafe { + slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>()) + }; + self.short_write(bytes); + } + + // see short_write comment for explanation + #[inline] + fn write_u8(&mut self, i: u8) { + self.short_write(&[i]); + } + + #[inline] + fn write(&mut self, msg: &[u8]) { + let length = msg.len(); + self.length += length; + + let mut needed = 0; + + if self.ntail != 0 { + needed = 8 - self.ntail; + self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); + if length < needed { + self.ntail += length; + return; + } else { + self.state.v3 ^= self.tail; + S::c_rounds(&mut self.state); + self.state.v0 ^= self.tail; + self.ntail = 0; + } + } + + // Buffered tail is now flushed, process new input. + let len = length - needed; + let left = len & 0x7; + + let mut i = needed; + while i < len - left { + let mi = unsafe { load_int_le!(msg, i, u64) }; + + self.state.v3 ^= mi; + S::c_rounds(&mut self.state); + self.state.v0 ^= mi; + + i += 8; + } + + self.tail = unsafe { u8to64_le(msg, i, left) }; + self.ntail = left; + } + + #[inline] + fn finish(&self) -> u64 { + self.finish128().h2 + } +} + +impl<S: Sip> Clone for Hasher<S> { + #[inline] + fn clone(&self) -> Hasher<S> { + Hasher { + k0: self.k0, + k1: self.k1, + length: self.length, + state: self.state, + tail: self.tail, + ntail: self.ntail, + _marker: self._marker, + } + } +} + +impl<S: Sip> Default for Hasher<S> { + /// Creates a `Hasher<S>` with the two initial keys set to 0. + #[inline] + fn default() -> Hasher<S> { + Hasher::new_with_keys(0, 0) + } +} + +#[doc(hidden)] +trait Sip { + fn c_rounds(_: &mut State); + fn d_rounds(_: &mut State); +} + +#[derive(Debug, Clone, Copy, Default)] +struct Sip13Rounds; + +impl Sip for Sip13Rounds { + #[inline] + fn c_rounds(state: &mut State) { + compress!(state); + } + + #[inline] + fn d_rounds(state: &mut State) { + compress!(state); + compress!(state); + compress!(state); + } +} + +#[derive(Debug, Clone, Copy, Default)] +struct Sip24Rounds; + +impl Sip for Sip24Rounds { + #[inline] + fn c_rounds(state: &mut State) { + compress!(state); + compress!(state); + } + + #[inline] + fn d_rounds(state: &mut State) { + compress!(state); + compress!(state); + compress!(state); + compress!(state); + } +} + +impl Hash128 { + /// Convert into a 16-bytes vector + pub fn as_bytes(&self) -> [u8; 16] { + let mut bytes = [0u8; 16]; + let h1 = self.h1.to_le(); + let h2 = self.h2.to_le(); + unsafe { + ptr::copy_nonoverlapping(&h1 as *const _ as *const u8, bytes.get_unchecked_mut(0), 8); + ptr::copy_nonoverlapping(&h2 as *const _ as *const u8, bytes.get_unchecked_mut(8), 8); + } + bytes + } +} diff --git a/bash-5.1/vendor/siphasher/src/tests.rs b/bash-5.1/vendor/siphasher/src/tests.rs new file mode 100644 index 0000000..c7705fc --- /dev/null +++ b/bash-5.1/vendor/siphasher/src/tests.rs @@ -0,0 +1,322 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::hash::{Hash, Hasher}; +use sip::{SipHasher, SipHasher13, SipHasher24}; + +// Hash just the bytes of the slice, without length prefix +struct Bytes<'a>(&'a [u8]); + +impl<'a> Hash for Bytes<'a> { + #[allow(unused_must_use)] + fn hash<H: Hasher>(&self, state: &mut H) { + let Bytes(v) = *self; + state.write(v); + } +} + +macro_rules! u8to64_le { + ($buf:expr, $i:expr) => + ($buf[0+$i] as u64 | + ($buf[1+$i] as u64) << 8 | + ($buf[2+$i] as u64) << 16 | + ($buf[3+$i] as u64) << 24 | + ($buf[4+$i] as u64) << 32 | + ($buf[5+$i] as u64) << 40 | + ($buf[6+$i] as u64) << 48 | + ($buf[7+$i] as u64) << 56); + ($buf:expr, $i:expr, $len:expr) => + ({ + let mut t = 0; + let mut out = 0; + while t < $len { + out |= ($buf[t+$i] as u64) << t*8; + t += 1; + } + out + }); +} + +fn hash_with<H: Hasher, T: Hash>(mut st: H, x: &T) -> u64 { + x.hash(&mut st); + st.finish() +} + +fn hash<T: Hash>(x: &T) -> u64 { + hash_with(SipHasher::new(), x) +} + +#[test] +#[allow(unused_must_use)] +fn test_siphash_1_3() { + let vecs: [[u8; 8]; 64] = [ + [0xdc, 0xc4, 0x0f, 0x05, 0x58, 0x01, 0xac, 0xab], + [0x93, 0xca, 0x57, 0x7d, 0xf3, 0x9b, 0xf4, 0xc9], + [0x4d, 0xd4, 0xc7, 0x4d, 0x02, 0x9b, 0xcb, 0x82], + [0xfb, 0xf7, 0xdd, 0xe7, 0xb8, 0x0a, 0xf8, 0x8b], + [0x28, 0x83, 0xd3, 0x88, 0x60, 0x57, 0x75, 0xcf], + [0x67, 0x3b, 0x53, 0x49, 0x2f, 0xd5, 0xf9, 0xde], + [0xa7, 0x22, 0x9f, 0xc5, 0x50, 0x2b, 0x0d, 0xc5], + [0x40, 0x11, 0xb1, 0x9b, 0x98, 0x7d, 0x92, 0xd3], + [0x8e, 0x9a, 0x29, 0x8d, 0x11, 0x95, 0x90, 0x36], + [0xe4, 0x3d, 0x06, 0x6c, 0xb3, 0x8e, 0xa4, 0x25], + [0x7f, 0x09, 0xff, 0x92, 0xee, 0x85, 0xde, 0x79], + [0x52, 0xc3, 0x4d, 0xf9, 0xc1, 0x18, 0xc1, 0x70], + [0xa2, 0xd9, 0xb4, 0x57, 0xb1, 0x84, 0xa3, 0x78], + [0xa7, 0xff, 0x29, 0x12, 0x0c, 0x76, 0x6f, 0x30], + [0x34, 0x5d, 0xf9, 0xc0, 0x11, 0xa1, 0x5a, 0x60], + [0x56, 0x99, 0x51, 0x2a, 0x6d, 0xd8, 0x20, 0xd3], + [0x66, 0x8b, 0x90, 0x7d, 0x1a, 0xdd, 0x4f, 0xcc], + [0x0c, 0xd8, 0xdb, 0x63, 0x90, 0x68, 0xf2, 0x9c], + [0x3e, 0xe6, 0x73, 0xb4, 0x9c, 0x38, 0xfc, 0x8f], + [0x1c, 0x7d, 0x29, 0x8d, 0xe5, 0x9d, 0x1f, 0xf2], + [0x40, 0xe0, 0xcc, 0xa6, 0x46, 0x2f, 0xdc, 0xc0], + [0x44, 0xf8, 0x45, 0x2b, 0xfe, 0xab, 0x92, 0xb9], + [0x2e, 0x87, 0x20, 0xa3, 0x9b, 0x7b, 0xfe, 0x7f], + [0x23, 0xc1, 0xe6, 0xda, 0x7f, 0x0e, 0x5a, 0x52], + [0x8c, 0x9c, 0x34, 0x67, 0xb2, 0xae, 0x64, 0xf4], + [0x79, 0x09, 0x5b, 0x70, 0x28, 0x59, 0xcd, 0x45], + [0xa5, 0x13, 0x99, 0xca, 0xe3, 0x35, 0x3e, 0x3a], + [0x35, 0x3b, 0xde, 0x4a, 0x4e, 0xc7, 0x1d, 0xa9], + [0x0d, 0xd0, 0x6c, 0xef, 0x02, 0xed, 0x0b, 0xfb], + [0xf4, 0xe1, 0xb1, 0x4a, 0xb4, 0x3c, 0xd9, 0x88], + [0x63, 0xe6, 0xc5, 0x43, 0xd6, 0x11, 0x0f, 0x54], + [0xbc, 0xd1, 0x21, 0x8c, 0x1f, 0xdd, 0x70, 0x23], + [0x0d, 0xb6, 0xa7, 0x16, 0x6c, 0x7b, 0x15, 0x81], + [0xbf, 0xf9, 0x8f, 0x7a, 0xe5, 0xb9, 0x54, 0x4d], + [0x3e, 0x75, 0x2a, 0x1f, 0x78, 0x12, 0x9f, 0x75], + [0x91, 0x6b, 0x18, 0xbf, 0xbe, 0xa3, 0xa1, 0xce], + [0x06, 0x62, 0xa2, 0xad, 0xd3, 0x08, 0xf5, 0x2c], + [0x57, 0x30, 0xc3, 0xa3, 0x2d, 0x1c, 0x10, 0xb6], + [0xa1, 0x36, 0x3a, 0xae, 0x96, 0x74, 0xf4, 0xb3], + [0x92, 0x83, 0x10, 0x7b, 0x54, 0x57, 0x6b, 0x62], + [0x31, 0x15, 0xe4, 0x99, 0x32, 0x36, 0xd2, 0xc1], + [0x44, 0xd9, 0x1a, 0x3f, 0x92, 0xc1, 0x7c, 0x66], + [0x25, 0x88, 0x13, 0xc8, 0xfe, 0x4f, 0x70, 0x65], + [0xa6, 0x49, 0x89, 0xc2, 0xd1, 0x80, 0xf2, 0x24], + [0x6b, 0x87, 0xf8, 0xfa, 0xed, 0x1c, 0xca, 0xc2], + [0x96, 0x21, 0x04, 0x9f, 0xfc, 0x4b, 0x16, 0xc2], + [0x23, 0xd6, 0xb1, 0x68, 0x93, 0x9c, 0x6e, 0xa1], + [0xfd, 0x14, 0x51, 0x8b, 0x9c, 0x16, 0xfb, 0x49], + [0x46, 0x4c, 0x07, 0xdf, 0xf8, 0x43, 0x31, 0x9f], + [0xb3, 0x86, 0xcc, 0x12, 0x24, 0xaf, 0xfd, 0xc6], + [0x8f, 0x09, 0x52, 0x0a, 0xd1, 0x49, 0xaf, 0x7e], + [0x9a, 0x2f, 0x29, 0x9d, 0x55, 0x13, 0xf3, 0x1c], + [0x12, 0x1f, 0xf4, 0xa2, 0xdd, 0x30, 0x4a, 0xc4], + [0xd0, 0x1e, 0xa7, 0x43, 0x89, 0xe9, 0xfa, 0x36], + [0xe6, 0xbc, 0xf0, 0x73, 0x4c, 0xb3, 0x8f, 0x31], + [0x80, 0xe9, 0xa7, 0x70, 0x36, 0xbf, 0x7a, 0xa2], + [0x75, 0x6d, 0x3c, 0x24, 0xdb, 0xc0, 0xbc, 0xb4], + [0x13, 0x15, 0xb7, 0xfd, 0x52, 0xd8, 0xf8, 0x23], + [0x08, 0x8a, 0x7d, 0xa6, 0x4d, 0x5f, 0x03, 0x8f], + [0x48, 0xf1, 0xe8, 0xb7, 0xe5, 0xd0, 0x9c, 0xd8], + [0xee, 0x44, 0xa6, 0xf7, 0xbc, 0xe6, 0xf4, 0xf6], + [0xf2, 0x37, 0x18, 0x0f, 0xd8, 0x9a, 0xc5, 0xae], + [0xe0, 0x94, 0x66, 0x4b, 0x15, 0xf6, 0xb2, 0xc3], + [0xa8, 0xb3, 0xbb, 0xb7, 0x62, 0x90, 0x19, 0x9d], + ]; + + let k0 = 0x_07_06_05_04_03_02_01_00; + let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08; + let mut buf = Vec::new(); + let mut t = 0; + let mut state_inc = SipHasher13::new_with_keys(k0, k1); + + while t < 64 { + let vec = u8to64_le!(vecs[t], 0); + let out = hash_with(SipHasher13::new_with_keys(k0, k1), &Bytes(&buf)); + assert_eq!(vec, out); + + let full = hash_with(SipHasher13::new_with_keys(k0, k1), &Bytes(&buf)); + let i = state_inc.finish(); + + assert_eq!(full, i); + assert_eq!(full, vec); + + buf.push(t as u8); + Hasher::write(&mut state_inc, &[t as u8]); + + t += 1; + } +} + +#[test] +#[allow(unused_must_use)] +fn test_siphash_2_4() { + let vecs: [[u8; 8]; 64] = [ + [0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72], + [0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74], + [0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d], + [0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85], + [0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf], + [0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18], + [0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb], + [0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab], + [0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93], + [0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e], + [0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a], + [0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4], + [0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75], + [0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14], + [0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7], + [0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1], + [0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f], + [0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69], + [0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b], + [0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb], + [0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe], + [0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0], + [0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93], + [0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8], + [0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8], + [0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc], + [0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17], + [0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f], + [0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde], + [0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6], + [0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad], + [0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32], + [0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71], + [0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7], + [0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12], + [0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15], + [0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31], + [0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02], + [0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca], + [0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a], + [0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e], + [0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad], + [0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18], + [0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4], + [0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9], + [0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9], + [0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb], + [0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0], + [0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6], + [0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7], + [0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee], + [0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1], + [0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a], + [0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81], + [0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f], + [0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24], + [0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7], + [0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea], + [0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60], + [0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66], + [0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c], + [0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f], + [0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5], + [0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95], + ]; + + let k0 = 0x_07_06_05_04_03_02_01_00; + let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08; + let mut buf = Vec::new(); + let mut t = 0; + let mut state_inc = SipHasher24::new_with_keys(k0, k1); + + while t < 64 { + let vec = u8to64_le!(vecs[t], 0); + let out = hash_with(SipHasher24::new_with_keys(k0, k1), &Bytes(&buf)); + assert_eq!(vec, out); + + let full = hash_with(SipHasher24::new_with_keys(k0, k1), &Bytes(&buf)); + let i = state_inc.finish(); + + assert_eq!(full, i); + assert_eq!(full, vec); + + buf.push(t as u8); + Hasher::write(&mut state_inc, &[t as u8]); + + t += 1; + } +} +#[test] +#[cfg(target_arch = "arm")] +fn test_hash_usize() { + let val = 0xdeadbeef_deadbeef_u64; + assert_ne!(hash(&(val as u64)), hash(&(val as usize))); + assert_eq!(hash(&(val as u32)), hash(&(val as usize))); +} +#[test] +#[cfg(target_arch = "x86_64")] +fn test_hash_usize() { + let val = 0xdeadbeef_deadbeef_u64; + assert_eq!(hash(&(val as u64)), hash(&(val as usize))); + assert_ne!(hash(&(val as u32)), hash(&(val as usize))); +} +#[test] +#[cfg(target_arch = "x86")] +fn test_hash_usize() { + let val = 0xdeadbeef_deadbeef_u64; + assert_ne!(hash(&(val as u64)), hash(&(val as usize))); + assert_eq!(hash(&(val as u32)), hash(&(val as usize))); +} + +#[test] +fn test_hash_idempotent() { + let val64 = 0xdeadbeef_deadbeef_u64; + assert_eq!(hash(&val64), hash(&val64)); + let val32 = 0xdeadbeef_u32; + assert_eq!(hash(&val32), hash(&val32)); +} + +#[test] +fn test_hash_no_bytes_dropped_64() { + let val = 0xdeadbeef_deadbeef_u64; + + assert_ne!(hash(&val), hash(&zero_byte(val, 0))); + assert_ne!(hash(&val), hash(&zero_byte(val, 1))); + assert_ne!(hash(&val), hash(&zero_byte(val, 2))); + assert_ne!(hash(&val), hash(&zero_byte(val, 3))); + assert_ne!(hash(&val), hash(&zero_byte(val, 4))); + assert_ne!(hash(&val), hash(&zero_byte(val, 5))); + assert_ne!(hash(&val), hash(&zero_byte(val, 6))); + assert_ne!(hash(&val), hash(&zero_byte(val, 7))); + + fn zero_byte(val: u64, byte: usize) -> u64 { + assert!(byte < 8); + val & !(0xff << (byte * 8)) + } +} + +#[test] +fn test_hash_no_bytes_dropped_32() { + let val = 0xdeadbeef_u32; + + assert_ne!(hash(&val), hash(&zero_byte(val, 0))); + assert_ne!(hash(&val), hash(&zero_byte(val, 1))); + assert_ne!(hash(&val), hash(&zero_byte(val, 2))); + assert_ne!(hash(&val), hash(&zero_byte(val, 3))); + + fn zero_byte(val: u32, byte: usize) -> u32 { + assert!(byte < 4); + val & !(0xff << (byte * 8)) + } +} + +#[test] +fn test_hash_no_concat_alias() { + let s = ("aa", "bb"); + let t = ("aabb", ""); + let u = ("a", "abb"); + + assert!(s != t && t != u); + assert!(hash(&s) != hash(&t) && hash(&s) != hash(&u)); + + let u = [1, 0, 0, 0]; + let v = (&u[..1], &u[1..3], &u[3..]); + let w = (&u[..], &u[4..4], &u[4..4]); + + assert_ne!(v, w); + assert_ne!(hash(&v), hash(&w)); +} diff --git a/bash-5.1/vendor/siphasher/src/tests128.rs b/bash-5.1/vendor/siphasher/src/tests128.rs new file mode 100644 index 0000000..0474a15 --- /dev/null +++ b/bash-5.1/vendor/siphasher/src/tests128.rs @@ -0,0 +1,116 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::hash::{Hash, Hasher}; +use sip128::{Hasher128, SipHasher13, SipHasher24}; + +// Hash just the bytes of the slice, without length prefix +struct Bytes<'a>(&'a [u8]); + +impl<'a> Hash for Bytes<'a> { + #[allow(unused_must_use)] + fn hash<H: Hasher>(&self, state: &mut H) { + let Bytes(v) = *self; + state.write(v); + } +} + +macro_rules! u8to64_le { + ($buf:expr, $i:expr) => + ($buf[0+$i] as u64 | + ($buf[1+$i] as u64) << 8 | + ($buf[2+$i] as u64) << 16 | + ($buf[3+$i] as u64) << 24 | + ($buf[4+$i] as u64) << 32 | + ($buf[5+$i] as u64) << 40 | + ($buf[6+$i] as u64) << 48 | + ($buf[7+$i] as u64) << 56); + ($buf:expr, $i:expr, $len:expr) => + ({ + let mut t = 0; + let mut out = 0; + while t < $len { + out |= ($buf[t+$i] as u64) << t*8; + t += 1; + } + out + }); +} + +fn hash_with<H: Hasher + Hasher128, T: Hash>(mut st: H, x: &T) -> [u8; 16] { + x.hash(&mut st); + st.finish128().as_bytes() +} + +#[test] +#[allow(unused_must_use)] +fn test_siphash128_1_3() { + let vecs: [[u8; 16]; 1] = [ + [ + 231, 126, 188, 178, 39, 136, 165, 190, 253, 98, 219, 106, 221, 48, 48, 1 + ], + ]; + + let k0 = 0x_07_06_05_04_03_02_01_00; + let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08; + let mut buf = Vec::new(); + let mut t = 0; + let mut state_inc = SipHasher13::new_with_keys(k0, k1); + + while t < 1 { + let vec = vecs[t]; + let out = hash_with(SipHasher13::new_with_keys(k0, k1), &Bytes(&buf)); + assert_eq!(vec, out[..]); + + let full = hash_with(SipHasher13::new_with_keys(k0, k1), &Bytes(&buf)); + let i = state_inc.finish128().as_bytes(); + + assert_eq!(full, i); + assert_eq!(full, vec); + + buf.push(t as u8); + Hasher::write(&mut state_inc, &[t as u8]); + + t += 1; + } +} + +#[test] +#[allow(unused_must_use)] +fn test_siphash128_2_4() { + let vecs: [[u8; 16]; 1] = [ + [ + 163, 129, 127, 4, 186, 37, 168, 230, 109, 246, 114, 20, 199, 85, 2, 147 + ], + ]; + + let k0 = 0x_07_06_05_04_03_02_01_00; + let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08; + let mut buf = Vec::new(); + let mut t = 0; + let mut state_inc = SipHasher24::new_with_keys(k0, k1); + + while t < 1 { + let vec = vecs[t]; + let out = hash_with(SipHasher24::new_with_keys(k0, k1), &Bytes(&buf)); + assert_eq!(vec, out[..]); + + let full = hash_with(SipHasher24::new_with_keys(k0, k1), &Bytes(&buf)); + let i = state_inc.finish128().as_bytes(); + + assert_eq!(full, i); + assert_eq!(full, vec); + + buf.push(t as u8); + Hasher::write(&mut state_inc, &[t as u8]); + + t += 1; + } +} diff --git a/bash-5.1/vendor/slab/src/builder.rs b/bash-5.1/vendor/slab/src/builder.rs new file mode 100644 index 0000000..8e50a20 --- /dev/null +++ b/bash-5.1/vendor/slab/src/builder.rs @@ -0,0 +1,63 @@ +use crate::{Entry, Slab}; + +// Building `Slab` from pairs (usize, T). +pub(crate) struct Builder<T> { + slab: Slab<T>, + vacant_list_broken: bool, + first_vacant_index: Option<usize>, +} + +impl<T> Builder<T> { + pub(crate) fn with_capacity(capacity: usize) -> Self { + Self { + slab: Slab::with_capacity(capacity), + vacant_list_broken: false, + first_vacant_index: None, + } + } + pub(crate) fn pair(&mut self, key: usize, value: T) { + let slab = &mut self.slab; + if key < slab.entries.len() { + // iterator is not sorted, might need to recreate vacant list + if let Entry::Vacant(_) = slab.entries[key] { + self.vacant_list_broken = true; + slab.len += 1; + } + // if an element with this key already exists, replace it. + // This is consistent with HashMap and BtreeMap + slab.entries[key] = Entry::Occupied(value); + } else { + if self.first_vacant_index.is_none() && slab.entries.len() < key { + self.first_vacant_index = Some(slab.entries.len()); + } + // insert holes as necessary + while slab.entries.len() < key { + // add the entry to the start of the vacant list + let next = slab.next; + slab.next = slab.entries.len(); + slab.entries.push(Entry::Vacant(next)); + } + slab.entries.push(Entry::Occupied(value)); + slab.len += 1; + } + } + + pub(crate) fn build(self) -> Slab<T> { + let mut slab = self.slab; + if slab.len == slab.entries.len() { + // no vacant entries, so next might not have been updated + slab.next = slab.entries.len(); + } else if self.vacant_list_broken { + slab.recreate_vacant_list(); + } else if let Some(first_vacant_index) = self.first_vacant_index { + let next = slab.entries.len(); + match &mut slab.entries[first_vacant_index] { + Entry::Vacant(n) => *n = next, + _ => unreachable!(), + } + } else { + unreachable!() + } + slab + } +} diff --git a/bash-5.1/vendor/smallvec/.cargo-checksum.json b/bash-5.1/vendor/smallvec/.cargo-checksum.json index 8f4d7bf..e9fa9e1 100644 --- a/bash-5.1/vendor/smallvec/.cargo-checksum.json +++ b/bash-5.1/vendor/smallvec/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"03ae7e6a133c5fd1685687aee67bc841642a4fd0deeb0d4d88b9fe27af37ba9e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0b28172679e0009b655da42797c03fd163a3379d5cfa67ba1f1655e974a2a1a9","README.md":"a01127c37308457e8d396b176fb790846be0978c173be3f13260b62efcef011b","benches/bench.rs":"e2a235d68be20996014c00468b369887d2041ce95486625de3cef35b8f2e4acd","scripts/run_miri.sh":"0d0b8c54c73fa9da1217d29ed0984f8328dd9fb61bb5a02db44458c360cdc3c4","src/arbitrary.rs":"22e55cfbf60374945b30e6d0855129eff67cd8b878cef6fa997e1f4be67b9e3d","src/lib.rs":"264a6e6863aeb21cd779588c2add8421ea1a5861a9bb8ef49e9dc529be8d3b20","src/specialization.rs":"46433586203399251cba496d67b88d34e1be3c2b591986b77463513da1c66471","src/tests.rs":"2bcf69dc0597e4e8a59a92566a3dd5c82ec3a1ea563aa006ea0f4a2722cb2d17","tests/macro.rs":"22ad4f6f104a599fdcba19cad8834105b8656b212fb6c7573a427d447f5db14f"},"package":"2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1"} \ No newline at end of file +{"files":{"Cargo.toml":"e8b7e22c87fa34e053c12b3751ec0c7b25b37bd1285959710321a7a00861f392","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0b28172679e0009b655da42797c03fd163a3379d5cfa67ba1f1655e974a2a1a9","README.md":"a01127c37308457e8d396b176fb790846be0978c173be3f13260b62efcef011b","benches/bench.rs":"e2a235d68be20996014c00468b369887d2041ce95486625de3cef35b8f2e4acd","debug_metadata/README.md":"dc8fbf896055359a94f7bfdfae7604e0bcfc8b10998a218d484d9fffdf83637c","debug_metadata/smallvec.natvis":"68aed2322bdc13ed6fa2021dc9625346174d73590929acbc2f95c98785c8dee4","scripts/run_miri.sh":"74a9f9adc43f986e81977b03846f7dd00122a0150bd8ec3fe4842a1a787e0f07","src/arbitrary.rs":"22e55cfbf60374945b30e6d0855129eff67cd8b878cef6fa997e1f4be67b9e3d","src/lib.rs":"35c60a9d9240853e9f6f84b7a44ff6a3197a87ab404f5ab1cd8ebeeeb72e54da","src/specialization.rs":"46433586203399251cba496d67b88d34e1be3c2b591986b77463513da1c66471","src/tests.rs":"2bcf69dc0597e4e8a59a92566a3dd5c82ec3a1ea563aa006ea0f4a2722cb2d17","tests/debugger_visualizer.rs":"87480900add8579e1285741d5a0041063b6d888328e11854ab2cdc2960d7ddb1","tests/macro.rs":"22ad4f6f104a599fdcba19cad8834105b8656b212fb6c7573a427d447f5db14f"},"package":"a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"} \ No newline at end of file diff --git a/bash-5.1/vendor/smallvec/Cargo.toml b/bash-5.1/vendor/smallvec/Cargo.toml index fd490da..a365ca1 100644 --- a/bash-5.1/vendor/smallvec/Cargo.toml +++ b/bash-5.1/vendor/smallvec/Cargo.toml @@ -12,18 +12,35 @@ [package] edition = "2018" name = "smallvec" -version = "1.9.0" +version = "1.10.0" authors = ["The Servo Project Developers"] description = "'Small vector' optimization: store up to a small number of items on the stack" documentation = "https://docs.rs/smallvec/" readme = "README.md" -keywords = ["small", "vec", "vector", "stack", "no_std"] +keywords = [ + "small", + "vec", + "vector", + "stack", + "no_std", +] categories = ["data-structures"] license = "MIT OR Apache-2.0" repository = "https://github.com/servo/rust-smallvec" + [package.metadata.docs.rs] all-features = true -rustdoc-args = ["--cfg", "docsrs"] +rustdoc-args = [ + "--cfg", + "docsrs", +] + +[[test]] +name = "debugger_visualizer" +path = "tests/debugger_visualizer.rs" +test = false +required-features = ["debugger_visualizer"] + [dependencies.arbitrary] version = "1" optional = true @@ -32,12 +49,20 @@ optional = true version = "1" optional = true default-features = false + [dev-dependencies.bincode] version = "1.0.1" +[dev-dependencies.debugger_test] +version = "0.1.0" + +[dev-dependencies.debugger_test_parser] +version = "0.1.0" + [features] const_generics = [] const_new = ["const_generics"] +debugger_visualizer = [] may_dangle = [] specialization = [] union = [] diff --git a/bash-5.1/vendor/smallvec/debug_metadata/README.md b/bash-5.1/vendor/smallvec/debug_metadata/README.md new file mode 100644 index 0000000..1375008 --- /dev/null +++ b/bash-5.1/vendor/smallvec/debug_metadata/README.md @@ -0,0 +1,111 @@ +## Debugger Visualizers + +Many languages and debuggers enable developers to control how a type is +displayed in a debugger. These are called "debugger visualizations" or "debugger +views". + +The Windows debuggers (WinDbg\CDB) support defining custom debugger visualizations using +the `Natvis` framework. To use Natvis, developers write XML documents using the natvis +schema that describe how debugger types should be displayed with the `.natvis` extension. +(See: https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects?view=vs-2019) +The Natvis files provide patterns which match type names a description of how to display +those types. + +The Natvis schema can be found either online (See: https://code.visualstudio.com/docs/cpp/natvis#_schema) +or locally at `<VS Installation Folder>\Xml\Schemas\1033\natvis.xsd`. + +The GNU debugger (GDB) supports defining custom debugger views using Pretty Printers. +Pretty printers are written as python scripts that describe how a type should be displayed +when loaded up in GDB/LLDB. (See: https://sourceware.org/gdb/onlinedocs/gdb/Pretty-Printing.html#Pretty-Printing) +The pretty printers provide patterns, which match type names, and for matching +types, descibe how to display those types. (For writing a pretty printer, see: https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Pretty_002dPrinter.html#Writing-a-Pretty_002dPrinter). + +### Embedding Visualizers + +Through the use of the currently unstable `#[debugger_visualizer]` attribute, the `smallvec` +crate can embed debugger visualizers into the crate metadata. + +Currently the two types of visualizers supported are Natvis and Pretty printers. + +For Natvis files, when linking an executable with a crate that includes Natvis files, +the MSVC linker will embed the contents of all Natvis files into the generated `PDB`. + +For pretty printers, the compiler will encode the contents of the pretty printer +in the `.debug_gdb_scripts` section of the `ELF` generated. + +### Testing Visualizers + +The `smallvec` crate supports testing debugger visualizers defined for this crate. The entry point for +these tests are `tests/debugger_visualizer.rs`. These tests are defined using the `debugger_test` and +`debugger_test_parser` crates. The `debugger_test` crate is a proc macro crate which defines a +single proc macro attribute, `#[debugger_test]`. For more detailed information about this crate, +see https://crates.io/crates/debugger_test. The CI pipeline for the `smallvec` crate has been updated +to run the debugger visualizer tests to ensure debugger visualizers do not become broken/stale. + +The `#[debugger_test]` proc macro attribute may only be used on test functions and will run the +function under the debugger specified by the `debugger` meta item. + +This proc macro attribute has 3 required values: + +1. The first required meta item, `debugger`, takes a string value which specifies the debugger to launch. +2. The second required meta item, `commands`, takes a string of new line (`\n`) separated list of debugger +commands to run. +3. The third required meta item, `expected_statements`, takes a string of new line (`\n`) separated list of +statements that must exist in the debugger output. Pattern matching through regular expressions is also +supported by using the `pattern:` prefix for each expected statement. + +#### Example: + +```rust +#[debugger_test( + debugger = "cdb", + commands = "command1\ncommand2\ncommand3", + expected_statements = "statement1\nstatement2\nstatement3")] +fn test() { + +} +``` + +Using a multiline string is also supported, with a single debugger command/expected statement per line: + +```rust +#[debugger_test( + debugger = "cdb", + commands = " +command1 +command2 +command3", + expected_statements = " +statement1 +pattern:statement[0-9]+ +statement3")] +fn test() { + +} +``` + +In the example above, the second expected statement uses pattern matching through a regular expression +by using the `pattern:` prefix. + +#### Testing Locally + +Currently, only Natvis visualizations have been defined for the `smallvec` crate via `debug_metadata/smallvec.natvis`, +which means the `tests/debugger_visualizer.rs` tests need to be run on Windows using the `*-pc-windows-msvc` targets. +To run these tests locally, first ensure the debugging tools for Windows are installed or install them following +the steps listed here, [Debugging Tools for Windows](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/). +Once the debugging tools have been installed, the tests can be run in the same manner as they are in the CI +pipeline. + +#### Note + +When running the debugger visualizer tests, `tests/debugger_visualizer.rs`, they need to be run consecutively +and not in parallel. This can be achieved by passing the flag `--test-threads=1` to rustc. This is due to +how the debugger tests are run. Each test marked with the `#[debugger_test]` attribute launches a debugger +and attaches it to the current test process. If tests are running in parallel, the test will try to attach +a debugger to the current process which may already have a debugger attached causing the test to fail. + +For example: + +``` +cargo test --test debugger_visualizer --features debugger_visualizer -- --test-threads=1 +``` diff --git a/bash-5.1/vendor/smallvec/debug_metadata/smallvec.natvis b/bash-5.1/vendor/smallvec/debug_metadata/smallvec.natvis new file mode 100644 index 0000000..b38d47c --- /dev/null +++ b/bash-5.1/vendor/smallvec/debug_metadata/smallvec.natvis @@ -0,0 +1,35 @@ +<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> + <Type Name="smallvec::SmallVec<array$<*,*>>" Priority="Medium"> + <Intrinsic Name="is_inline" Expression="$T2 > capacity" /> + <Intrinsic Name="len" Expression="is_inline() ? capacity : data.variant1.value.__0.__1" /> + <Intrinsic Name="data_ptr" Expression="is_inline() ? data.variant0.value.__0.value.value : data.variant1.value.__0.__0" /> + + <DisplayString>{{ len={len()} }}</DisplayString> + <Expand> + <Item Name="[capacity]">is_inline() ? $T2 : capacity</Item> + <Item Name="[len]">len()</Item> + + <ArrayItems> + <Size>len()</Size> + <ValuePointer>data_ptr()</ValuePointer> + </ArrayItems> + </Expand> + </Type> + + <Type Name="smallvec::SmallVec<array$<*,*>>" Priority="MediumLow"> + <Intrinsic Name="is_inline" Expression="$T2 > capacity" /> + <Intrinsic Name="len" Expression="is_inline() ? capacity : data.heap.__1" /> + <Intrinsic Name="data_ptr" Expression="is_inline() ? data.inline.value.value.value : data.heap.__0" /> + + <DisplayString>{{ len={len()} }}</DisplayString> + <Expand> + <Item Name="[capacity]">is_inline() ? $T2 : capacity</Item> + <Item Name="[len]">len()</Item> + + <ArrayItems> + <Size>len()</Size> + <ValuePointer>data_ptr()</ValuePointer> + </ArrayItems> + </Expand> + </Type> +</AutoVisualizer> \ No newline at end of file diff --git a/bash-5.1/vendor/smallvec/scripts/run_miri.sh b/bash-5.1/vendor/smallvec/scripts/run_miri.sh index 817928a..010ceb0 100644 --- a/bash-5.1/vendor/smallvec/scripts/run_miri.sh +++ b/bash-5.1/vendor/smallvec/scripts/run_miri.sh @@ -11,6 +11,7 @@ cargo clean MIRI_NIGHTLY=nightly-$(curl -s https://rust-lang.github.io/rustup-components-history/x86_64-unknown-linux-gnu/miri) echo "Installing latest nightly with Miri: $MIRI_NIGHTLY" +rustup override unset rustup default "$MIRI_NIGHTLY" rustup component add miri @@ -19,3 +20,5 @@ cargo miri setup cargo miri test --verbose cargo miri test --verbose --features union cargo miri test --verbose --all-features + +rustup override set nightly diff --git a/bash-5.1/vendor/smallvec/src/lib.rs b/bash-5.1/vendor/smallvec/src/lib.rs index 921347a..a335ca4 100644 --- a/bash-5.1/vendor/smallvec/src/lib.rs +++ b/bash-5.1/vendor/smallvec/src/lib.rs @@ -81,6 +81,11 @@ #![cfg_attr(feature = "specialization", allow(incomplete_features))] #![cfg_attr(feature = "specialization", feature(specialization))] #![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))] +#![cfg_attr( + feature = "debugger_visualizer", + feature(debugger_visualizer), + debugger_visualizer(natvis_file = "../debug_metadata/smallvec.natvis") +)] #![deny(missing_docs)] #[doc(hidden)] @@ -2084,6 +2089,7 @@ impl<T, const N: usize> SmallVec<[T; N]> { #[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))] unsafe impl<T, const N: usize> Array for [T; N] { type Item = T; + #[inline] fn size() -> usize { N } @@ -2095,6 +2101,7 @@ macro_rules! impl_array( $( unsafe impl<T> Array for [T; $size] { type Item = T; + #[inline] fn size() -> usize { $size } } )+ diff --git a/bash-5.1/vendor/smallvec/tests/debugger_visualizer.rs b/bash-5.1/vendor/smallvec/tests/debugger_visualizer.rs new file mode 100644 index 0000000..210f539 --- /dev/null +++ b/bash-5.1/vendor/smallvec/tests/debugger_visualizer.rs @@ -0,0 +1,68 @@ +use debugger_test::debugger_test; +use smallvec::{smallvec, SmallVec}; + +#[inline(never)] +fn __break() {} + +#[debugger_test( + debugger = "cdb", + commands = r#" +.nvlist +dx sv + +g + +dx sv + +g + +dx sv +"#, + expected_statements = r#" +sv : { len=0x2 } [Type: smallvec::SmallVec<array$<i32,4> >] + [<Raw View>] [Type: smallvec::SmallVec<array$<i32,4> >] + [capacity] : 4 + [len] : 0x2 [Type: unsigned __int64] + [0] : 1 [Type: int] + [1] : 2 [Type: int] + +sv : { len=0x5 } [Type: smallvec::SmallVec<array$<i32,4> >] + [<Raw View>] [Type: smallvec::SmallVec<array$<i32,4> >] + [capacity] : 0x8 [Type: unsigned __int64] + [len] : 0x5 [Type: unsigned __int64] + [0] : 5 [Type: int] + [1] : 2 [Type: int] + [2] : 3 [Type: int] + [3] : 4 [Type: int] + [4] : 5 [Type: int] + +sv : { len=0x5 } [Type: smallvec::SmallVec<array$<i32,4> >] + [<Raw View>] [Type: smallvec::SmallVec<array$<i32,4> >] + [capacity] : 0x8 [Type: unsigned __int64] + [len] : 0x5 [Type: unsigned __int64] + [0] : 2 [Type: int] + [1] : 3 [Type: int] + [2] : 4 [Type: int] + [3] : 5 [Type: int] + [4] : 5 [Type: int] +"# +)] +#[inline(never)] +fn test_debugger_visualizer() { + // This SmallVec can hold up to 4 items on the stack: + let mut sv: SmallVec<[i32; 4]> = smallvec![1, 2]; + __break(); + + // Overfill the SmallVec to move its contents to the heap + for i in 3..6 { + sv.push(i); + } + + // Update the contents of the first value of the SmallVec. + sv[0] = sv[1] + sv[2]; + __break(); + + // Sort the SmallVec in place. + sv.sort(); + __break(); +} diff --git a/bash-5.1/vendor/static_assertions/.cargo-checksum.json b/bash-5.1/vendor/static_assertions/.cargo-checksum.json new file mode 100644 index 0000000..eb917cb --- /dev/null +++ b/bash-5.1/vendor/static_assertions/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"750f74f3b520672a81dd2ede5c097cfe972c0da181dd8fd010e7131a3526d4fd","Cargo.toml":"6531dbe3d557e427f9e3510e50cdf3de751a319eece11c9a937b35cfab8744c4","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"ea084a2373ebc1f0902c09266e7bf25a05ab3814c1805bb017ffa7308f90c061","README.md":"88cc779ada8c6e1362c2d095c179284ec2755797729946ebccfe8264fcff0f8e","src/assert_cfg.rs":"ce9230bcc055d8df21ceefbed4233df5e73ecb832829ba23ac8d7f54ec457522","src/assert_eq_align.rs":"f09c4ec30e476446ab337a4a9ed950edf21c780a42ece7613f0ffc20225331ae","src/assert_eq_size.rs":"c06d2ff44e1f7af8a57b7c2fe5a9c69aa2a90d12cd41614c9d4f3ae551cdb64c","src/assert_fields.rs":"9c5baeac0215be557213eec9e80fc00de10a721d9b2c369fece743fcc6ccdc8e","src/assert_impl.rs":"fe5a2fffcbb78f60991bbc590481e74fd0d5f7ed8fa75718644599e1fae117ce","src/assert_obj_safe.rs":"88584809f3aa2dfce966b0adbeb6128191229465d653e57b68f968be001eff03","src/assert_trait.rs":"87b2d4dbd4334d9ace9880b81f3a1fbf91725c5e152b34a74c86457ca40ece30","src/assert_type.rs":"7cd942341efa7ed0b89b5e4fe1faa62bafb537ec6cf72ee6866115daee931885","src/const_assert.rs":"e0dcfe9016e34455f5efcb23500f716386d42b9fb09c6d08566d03dce8249e51","src/lib.rs":"4cbaaff38a6ac16631e774ab5a349056cbd2335ac570aeb46c5616eaf9700c3b"},"package":"a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"} \ No newline at end of file diff --git a/bash-5.1/vendor/static_assertions/CHANGELOG.md b/bash-5.1/vendor/static_assertions/CHANGELOG.md new file mode 100644 index 0000000..80d5507 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/CHANGELOG.md @@ -0,0 +1,181 @@ +# Changelog [![Crates.io][crate-badge]][crate] +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog] and this project adheres to +[Semantic Versioning]. + +## [Unreleased] + +## [1.1.0] - 2019-11-03 +### Added +- `assert_impl_any!` macro +- `assert_impl_one!` macro +- `assert_trait_sub_all!` macro +- `assert_trait_super_all!` macro +- Frequently asked questions to `README.md` + +### Fixed +- `assert_eq_size_val!`, `const_assert_eq!`, and `const_assert_ne!` to export + their local inner macros. Not having this prevented them from working when + `use`d or called directly via `static_assertions::macro!(...)` + +### Removed +- Unused `_assert_obj_safe!` from pre-1.0 + +## [1.0.0] - 2019-10-02 +### Added +- `assert_eq_align!` macro + +### Removed +- **[breaking]** Labels from macros that needed them 🎉 + - Made possible by [`const _`] in Rust 1.37 +- **[breaking]** `assert_impl!` macro + +### Fixed +- `assert_fields!` now works for `enum` types with multiple variants + +### Changed +- **[breaking]** `const_assert!` macro to only take one expression + - Reasoning: when custom error messages are added in the future (via + [`assert!`]), having the macro allow for multiple comma-separated + expressions may lead to ambiguity +- **[breaking]** Trait assertions to use `Type: Trait` syntax +- **[breaking]** Field assertions to use `Type: field1, field2` syntax +- **[breaking]** Renamed `assert_{ne,eq}_type!` to `assert_type_{ne,eq}_all!` + +## [0.3.4] - 2019-06-12 +### Changed +- Aliased `assert_impl!` to `assert_impl_all!` and deprecated `assert_impl!` + +### Added +- `assert_impl_all!` as replacement to `assert_impl!` +- `assert_not_impl_all!` and `assert_not_impl_any!` macro counterparts to + `assert_impl_all!` + +### Fixed +- `assert_eq_type!` now works with types involving lifetimes + +## [0.3.3] - 2019-06-12 +### Added +- `const_assert_ne!` macro counterpart to `const_assert_eq!` + +### Fixed +- `assert_eq_type!` would pass when types can coerce via `Deref`, such as with + `str` and `String` + +## [0.3.2] - 2019-05-15 +### Added +- A `assert_eq_type!` macro that allows for checking whether inputs are the same + concrete type +- A `assert_ne_type!` macro for checking whether inputs all refer to different + types + +### Fixed +- `const_assert!` now only takes `bool` values whereas integer (or other type) + values could previously be passed + +## [0.3.1] - 2018-11-15 +### Fixed +- Macros that refer to other internal macros can now be imported when compiling + for Rust 2018 ([issue + #10](https://github.com/nvzqz/static-assertions-rs/issues/10)) + +## [0.3.0] - 2018-11-14 +### Changed +- Bumped minimum supported (automatically tested) Rust version to 1.24.0 +- Moved message parameter for `assert_cfg!()` to last argument position, making + it consistent with other macros + +### Removed +- No need to use `macro!(label; ...)` syntax when compiling on nightly Rust and + enabling the `nightly` feature flag + +## [0.2.5] - 2017-12-12 +### Changed +- `assert_eq_size_ptr` wraps its code inside of a closure, ensuring that the + unsafe code inside never runs +- Clippy no longer warns about `unneeded_field_pattern` within `assert_fields` + +### Added +- Much better documentation with test examples that are guaranteed to fail at + compile-time + +### Removed +- Removed testing features; compile failure tests are now done via doc tests + +## [0.2.4] - 2017-12-11 +### Removed +- Removed the actual call to `mem::transmute` while still utilizing it for size + verification ([Simon Sapin], [#5]) + +### Added +- `assert_cfg` macro that asserts that the given configuration is set +- `assert_fields` macro to assert that a struct type or enum variant has a given + field + +### Fixed +- Allow more generics flexibility in `assert_impl` + +## [0.2.3] - 2017-08-24 +### Fixed +- Trailing commas are now allowed + +### Removed +- Removed clippy warnings + +## [0.2.2] - 2017-08-13 +### Added +- Added `assert_impl` macro to ensure a type implements a given set of traits + +## [0.2.1] - 2017-08-13 +### Added +- Added `assert_obj_safe` macro for ensuring that a trait is object-safe + +## [0.2.0] - 2017-08-12 +### Added +- Added `assert_eq_size_ptr` macro + +### Fixed +- Allow `assert_eq_size`, `const_assert`, and `const_assert_eq` in non-function + contexts via providing a unique label [#1] + +### Removed +- **[Breaking]** Semicolon-separated `assert_eq_size` is no longer allowed + +## [0.1.1] - 2017-08-12 +### Added +- Added `const_assert_eq` macro + +## 0.1.0 - 2017-08-12 + +Initial release + +[Simon Sapin]: https://github.com/SimonSapin + +[`assert!`]: https://doc.rust-lang.org/stable/std/macro.assert.html +[`const _`]: https://github.com/rust-lang/rfcs/blob/master/text/2526-const-wildcard.md + +[#1]: https://github.com/nvzqz/static-assertions-rs/issues/1 +[#5]: https://github.com/nvzqz/static-assertions-rs/pull/5 + +[crate]: https://crates.io/crates/static_assertions +[crate-badge]: https://img.shields.io/crates/v/static_assertions.svg + +[Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ +[Semantic Versioning]: http://semver.org/spec/v2.0.0.html + +[Unreleased]: https://github.com/nvzqz/static-assertions-rs/compare/v1.1.0...HEAD +[1.1.0]: https://github.com/nvzqz/static-assertions-rs/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/nvzqz/static-assertions-rs/compare/v0.3.4...v1.0.0 +[0.3.4]: https://github.com/nvzqz/static-assertions-rs/compare/v0.3.3...v0.3.4 +[0.3.3]: https://github.com/nvzqz/static-assertions-rs/compare/v0.3.2...v0.3.3 +[0.3.2]: https://github.com/nvzqz/static-assertions-rs/compare/v0.3.1...v0.3.2 +[0.3.1]: https://github.com/nvzqz/static-assertions-rs/compare/v0.3.0...v0.3.1 +[0.3.0]: https://github.com/nvzqz/static-assertions-rs/compare/v0.2.5...v0.3.0 +[0.2.5]: https://github.com/nvzqz/static-assertions-rs/compare/v0.2.4...v0.2.5 +[0.2.4]: https://github.com/nvzqz/static-assertions-rs/compare/v0.2.3...v0.2.4 +[0.2.3]: https://github.com/nvzqz/static-assertions-rs/compare/v0.2.2...v0.2.3 +[0.2.2]: https://github.com/nvzqz/static-assertions-rs/compare/v0.2.1...v0.2.2 +[0.2.1]: https://github.com/nvzqz/static-assertions-rs/compare/v0.2.0...v0.2.1 +[0.2.0]: https://github.com/nvzqz/static-assertions-rs/compare/v0.1.1...v0.2.0 +[0.1.1]: https://github.com/nvzqz/static-assertions-rs/compare/v0.1.0...v0.1.1 diff --git a/bash-5.1/vendor/static_assertions/Cargo.toml b/bash-5.1/vendor/static_assertions/Cargo.toml new file mode 100644 index 0000000..8651ce1 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/Cargo.toml @@ -0,0 +1,39 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "static_assertions" +version = "1.1.0" +authors = ["Nikolai Vazquez"] +include = ["Cargo.toml", "src/**/*.rs", "README.md", "CHANGELOG.md", "LICENSE*"] +description = "Compile-time assertions to ensure that invariants are met." +homepage = "https://github.com/nvzqz/static-assertions-rs" +documentation = "https://docs.rs/static_assertions/" +readme = "README.md" +keywords = ["assert", "static", "testing"] +categories = ["no-std", "rust-patterns", "development-tools::testing"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/nvzqz/static-assertions-rs" + +[features] +nightly = [] +[badges.is-it-maintained-issue-resolution] +repository = "nvzqz/static-assertions-rs" + +[badges.is-it-maintained-open-issues] +repository = "nvzqz/static-assertions-rs" + +[badges.maintenance] +status = "passively-maintained" + +[badges.travis-ci] +repository = "nvzqz/static-assertions-rs" diff --git a/bash-5.1/vendor/static_assertions/LICENSE-APACHE b/bash-5.1/vendor/static_assertions/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/bash-5.1/vendor/static_assertions/LICENSE-MIT b/bash-5.1/vendor/static_assertions/LICENSE-MIT new file mode 100644 index 0000000..ccc9445 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Nikolai Vazquez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bash-5.1/vendor/static_assertions/README.md b/bash-5.1/vendor/static_assertions/README.md new file mode 100644 index 0000000..bca222e --- /dev/null +++ b/bash-5.1/vendor/static_assertions/README.md @@ -0,0 +1,188 @@ +[![Banner](https://raw.githubusercontent.com/nvzqz/static-assertions-rs/assets/Banner.png)](https://github.com/nvzqz/static-assertions-rs) + +<div align="center"> + <a href="https://crates.io/crates/static_assertions"> + <img src="https://img.shields.io/crates/v/static_assertions.svg" alt="Crates.io"> + <img src="https://img.shields.io/crates/d/static_assertions.svg" alt="Downloads"> + </a> + <a href="https://travis-ci.org/nvzqz/static-assertions-rs"> + <img src="https://travis-ci.org/nvzqz/static-assertions-rs.svg?branch=master" alt="Build Status"> + </a> + <img src="https://img.shields.io/badge/rustc-^1.37.0-blue.svg" alt="rustc ^1.37.0"> + <br> + <a href="https://www.patreon.com/nvzqz"> + <img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" alt="Become a Patron!" height="35"> + </a> + <a href="https://www.paypal.me/nvzqz"> + <img src="https://buymecoffee.intm.org/img/button-paypal-white.png" alt="Buy me a coffee" height="35"> + </a> +</div> + +Compile-time assertions for Rust, brought to you by +[Nikolai Vazquez](https://twitter.com/NikolaiVazquez). + +This library lets you ensure correct assumptions about constants, types, and +more. See the [docs] and [FAQ](#faq) for more info! + +## Installation + +This crate is available +[on crates.io](https://crates.io/crates/static_assertions) and can be used by +adding the following to your project's +[`Cargo.toml`](https://doc.rust-lang.org/cargo/reference/manifest.html): + +```toml +[dependencies] +static_assertions = "1.1.0" +``` + +and this to your crate root (`main.rs` or `lib.rs`): + +```rust +#[macro_use] +extern crate static_assertions; +``` + +## Usage + +This crate exposes the following macros: +- [`assert_cfg!`] +- [`assert_eq_align!`] +- [`assert_eq_size!`] +- [`assert_eq_size_ptr!`] +- [`assert_eq_size_val!`] +- [`assert_fields!`] +- [`assert_impl_all!`] +- [`assert_impl_any!`] +- [`assert_impl_one!`] +- [`assert_not_impl_all!`] +- [`assert_not_impl_any!`] +- [`assert_obj_safe!`] +- [`assert_trait_sub_all!`] +- [`assert_trait_super_all!`] +- [`assert_type_eq_all!`] +- [`assert_type_ne_all!`] +- [`const_assert!`] +- [`const_assert_eq!`] +- [`const_assert_ne!`] + +## FAQ + +- **Q:** When would I want to use this? + + **A:** This library is useful for when wanting to ensure properties of + constants, types, and traits. + + Basic examples: + + - With the release of 1.39, `str::len` can be called in a `const` + context. Using [`const_assert!`], one can check that a string generated from + elsewhere is of a given size: + + ```rust + const DATA: &str = include_str!("path/to/string.txt"); + + const_assert!(DATA.len() < 512); + ``` + + - Have a type that absolutely must implement certain traits? With + [`assert_impl_all!`], one can ensure this: + + ```rust + struct Foo { + value: // ... + } + + assert_impl_all!(Foo: Send, Sync); + ``` + +- **Q:** How can I contribute? + + **A:** A couple of ways! You can: + + - Attempt coming up with some form of static analysis that you'd like to see + implemented. Create a [new issue] and describe how you'd imagine your + assertion to work, with example code to demonstrate. + + - Implement your own static assertion and create a [pull request]. + + - Give feedback. What are some pain points? Where is it unpleasant? + + - Write docs. If you're familiar with how this library works, sharing your + knowledge with the rest its users would be great! + +- **Q:** Will this affect my compiled binary? + + **A:** Nope! There is zero runtime cost to using this because all checks are + at compile-time, and so no code is emitted to run. + +- **Q:** Will this affect my compile times? + + **A:** Likely not by anything perceivable. If this is a concern, this library + can be put in `dev-dependencies`: + + ```toml + [dev-dependencies] + static_assertions = "1.1.0" + ``` + + and then assertions can be conditionally run behind `#[cfg(test)]`: + + ```rust + #[cfg(test)] + const_assert_eq!(MEANING_OF_LIFE, 42); + ``` + + However, the assertions will only be checked when running `cargo test`. This + somewhat defeats the purpose of catching false static conditions up-front with + a compilation failure. + +- **Q:** What is `const _`? + + **A:** It's a way of creating an unnamed constant. This is used so that macros + can be called from a global scope without requiring a scope-unique label. This + library makes use of the side effects of evaluating the `const` expression. + See the feature's + [tracking issue](https://github.com/rust-lang/rust/issues/54912) + and + [issue #1](https://github.com/nvzqz/static-assertions-rs/issues/1) + for more info. + +## Changes + +See [`CHANGELOG.md`](https://github.com/nvzqz/static-assertions-rs/blob/master/CHANGELOG.md) +for a complete list of what has changed from one version to another. + +## License + +This project is released under either: + +- [MIT License](https://github.com/nvzqz/static-assertions-rs/blob/master/LICENSE-MIT) + +- [Apache License (Version 2.0)](https://github.com/nvzqz/static-assertions-rs/blob/master/LICENSE-APACHE) + +at your choosing. + +[new issue]: https://github.com/nvzqz/static-assertions-rs/issues/new +[pull request]: https://github.com/nvzqz/static-assertions-rs/pulls +[docs]: https://docs.rs/static_assertions + +[`assert_cfg!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_cfg.html +[`assert_eq_align!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_eq_align.html +[`assert_eq_size!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_eq_size.html +[`assert_eq_size_ptr!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_eq_size_ptr.html +[`assert_eq_size_val!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_eq_size_val.html +[`assert_fields!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_fields.html +[`assert_impl_all!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_impl_all.html +[`assert_impl_any!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_impl_any.html +[`assert_impl_one!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_impl_one.html +[`assert_not_impl_all!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_not_impl_all.html +[`assert_not_impl_any!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_not_impl_any.html +[`assert_obj_safe!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_obj_safe.html +[`assert_trait_sub_all!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_trait_sub_all.html +[`assert_trait_super_all!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_trait_super_all.html +[`assert_type_eq_all!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_type_eq_all.html +[`assert_type_ne_all!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.assert_type_ne_all.html +[`const_assert!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.const_assert.html +[`const_assert_eq!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.const_assert_eq.html +[`const_assert_ne!`]: https://docs.rs/static_assertions/1.1.0/static_assertions/macro.const_assert_ne.html diff --git a/bash-5.1/vendor/static_assertions/src/assert_cfg.rs b/bash-5.1/vendor/static_assertions/src/assert_cfg.rs new file mode 100644 index 0000000..24282c1 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_cfg.rs @@ -0,0 +1,49 @@ +/// Asserts that a given configuration is set. +/// +/// # Examples +/// +/// A project will simply fail to compile if the given configuration is not set. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// // We're not masochists +/// # #[cfg(not(target_pointer_width = "16"))] // Just in case +/// assert_cfg!(not(target_pointer_width = "16")); +/// ``` +/// +/// If a project does not support a set of configurations, you may want to +/// report why. There is the option of providing a compile error message string: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// # #[cfg(any(unix, windows))] +/// assert_cfg!(any(unix, windows), "There is only support for Unix or Windows"); +/// +/// // User needs to specify a database back-end +/// # #[cfg(target_pointer_width = "0")] // Impossible +/// assert_cfg!(all(not(all(feature = "mysql", feature = "mongodb")), +/// any( feature = "mysql", feature = "mongodb")), +/// "Must exclusively use MySQL or MongoDB as database back-end"); +/// ``` +/// +/// Some configurations are impossible. For example, we can't be compiling for +/// both macOS _and_ Windows simultaneously: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_cfg!(all(target_os = "macos", +/// target_os = "windows"), +/// "No, that's not how it works! ಠ_ಠ"); +/// ``` +#[macro_export] +macro_rules! assert_cfg { + () => {}; + ($($cfg:meta)+, $msg:expr $(,)?) => { + #[cfg(not($($cfg)+))] + compile_error!($msg); + }; + ($($cfg:tt)*) => { + #[cfg(not($($cfg)*))] + compile_error!(concat!("Cfg does not pass: ", stringify!($($cfg)*))); + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_eq_align.rs b/bash-5.1/vendor/static_assertions/src/assert_eq_align.rs new file mode 100644 index 0000000..69412da --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_eq_align.rs @@ -0,0 +1,45 @@ +/// Asserts that types are equal in alignment. +/// +/// This is useful when ensuring that pointer arithmetic is done correctly, or +/// when [FFI] requires a type to have the same alignment as some foreign type. +/// +/// # Examples +/// +/// A `usize` has the same alignment as any pointer type: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_eq_align!(usize, *const u8, *mut u8); +/// ``` +/// +/// The following passes because `[i32; 4]` has the same alignment as `i32`: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_eq_align!([i32; 4], i32); +/// ``` +/// +/// The following example fails to compile because `i32x4` explicitly has 4 +/// times the alignment as `[i32; 4]`: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// # #[allow(non_camel_case_types)] +/// #[repr(align(16))] +/// struct i32x4([i32; 4]); +/// +/// assert_eq_align!(i32x4, [i32; 4]); +/// ``` +/// +/// [FFI]: https://en.wikipedia.org/wiki/Foreign_function_interface +#[macro_export] +macro_rules! assert_eq_align { + ($x:ty, $($xs:ty),+ $(,)?) => { + const _: fn() = || { + // Assigned instance must match the annotated type or else it will + // fail to compile + use $crate::_core::mem::align_of; + $(let _: [(); align_of::<$x>()] = [(); align_of::<$xs>()];)+ + }; + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_eq_size.rs b/bash-5.1/vendor/static_assertions/src/assert_eq_size.rs new file mode 100644 index 0000000..9c3c490 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_eq_size.rs @@ -0,0 +1,123 @@ +/// Asserts that types are equal in size. +/// +/// When performing operations such as pointer casts or dealing with [`usize`] +/// versus [`u64`] versus [`u32`], the size of your types matter. That is where +/// this macro comes into play. +/// +/// # Alternatives +/// +/// There also exists [`assert_eq_size_val`](macro.assert_eq_size_val.html) and +/// [`assert_eq_size_ptr`](macro.assert_eq_size_ptr.html). Instead of specifying +/// types to compare, values' sizes can be directly compared against each other. +/// +/// # Examples +/// +/// These three types, despite being very different, all have the same size: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_eq_size!([u8; 4], (u16, u16), u32); +/// ``` +/// +/// The following example fails to compile because `u32` has 4 times the size of +/// `u8`: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_eq_size!(u32, u8); +/// ``` +/// +/// [`usize`]: https://doc.rust-lang.org/std/primitive.usize.html +/// [`u64`]: https://doc.rust-lang.org/std/primitive.u64.html +/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html +#[macro_export] +macro_rules! assert_eq_size { + ($x:ty, $($xs:ty),+ $(,)?) => { + const _: fn() = || { + $(let _ = $crate::_core::mem::transmute::<$x, $xs>;)+ + }; + }; +} + +/// Asserts that values pointed to are equal in size. +/// +/// # Examples +/// +/// This especially is useful for when coercing pointers between different types +/// and ensuring the underlying values are the same size. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// fn operation(x: &(u32, u32), y: &[u16; 4]) { +/// assert_eq_size_ptr!(x, y); +/// // ... +/// } +/// ``` +/// +/// The following example fails to compile because byte arrays of different +/// lengths have different sizes: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; +/// # fn main() { +/// static BYTES: &[u8; 4] = &[ +/// /* ... */ +/// # 0; 4 +/// ]; +/// +/// static TABLE: &[u8; 16] = &[ +/// /* ... */ +/// # 0; 16 +/// ]; +/// +/// assert_eq_size_ptr!(BYTES, TABLE); +/// ``` +#[macro_export] +macro_rules! assert_eq_size_ptr { + ($x:expr, $($xs:expr),+ $(,)?) => { + #[allow(unknown_lints, unsafe_code, forget_copy, useless_transmute)] + let _ = || unsafe { + use $crate::_core::{mem, ptr}; + let mut copy = ptr::read($x); + $(ptr::write(&mut copy, mem::transmute(ptr::read($xs)));)+ + mem::forget(copy); + }; + } +} + +/// Asserts that values are equal in size. +/// +/// This macro doesn't consume its arguments and thus works for +/// non-[`Clone`]able values. +/// +/// # Examples +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; +/// # fn main() { +/// struct Byte(u8); +/// +/// let x = 10u8; +/// let y = Byte(42); // Works for non-cloneable types +/// +/// assert_eq_size_val!(x, y); +/// assert_eq_size_val!(x, y, 0u8); +/// # } +/// ``` +/// +/// Even though both values are 0, they are of types with different sizes: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; +/// # fn main() { +/// assert_eq_size_val!(0u8, 0u32); +/// # } +/// ``` +/// +/// [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html +#[macro_export(local_inner_macros)] +macro_rules! assert_eq_size_val { + ($x:expr, $($xs:expr),+ $(,)?) => { + assert_eq_size_ptr!(&$x, $(&$xs),+); + } +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_fields.rs b/bash-5.1/vendor/static_assertions/src/assert_fields.rs new file mode 100644 index 0000000..00f6242 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_fields.rs @@ -0,0 +1,72 @@ +/// Asserts that the type has the given fields. +/// +/// # Examples +/// +/// One common use case is when types have fields defined multiple times as a +/// result of `#[cfg]`. This can be an issue when exposing a public API. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; +/// pub struct Ty { +/// #[cfg(windows)] +/// pub val1: u8, +/// #[cfg(not(windows))] +/// pub val1: usize, +/// +/// #[cfg(unix)] +/// pub val2: u32, +/// #[cfg(not(unix))] +/// pub val2: usize, +/// } +/// +/// // Always have `val2` regardless of OS +/// assert_fields!(Ty: val2); +/// ``` +/// +/// This macro even works with `enum` variants: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// enum Data { +/// Val { +/// id: i32, +/// name: String, +/// bytes: [u8; 128], +/// }, +/// Ptr(*const u8), +/// } +/// +/// assert_fields!(Data::Val: id, bytes); +/// ``` +/// +/// The following example fails to compile because [`Range`] does not have a field named `middle`: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// use std::ops::Range; +/// +/// assert_fields!(Range<u32>: middle); +/// ``` +/// +/// [`Range`]: https://doc.rust-lang.org/std/ops/struct.Range.html +#[macro_export] +macro_rules! assert_fields { + ($t:ident::$v:ident: $($f:ident),+) => { + #[allow(unknown_lints, unneeded_field_pattern)] + const _: fn() = || { + #[allow(dead_code, unreachable_patterns)] + fn assert(value: $t) { + match value { + $($t::$v { $f: _, .. } => {},)+ + _ => {} + } + } + }; + }; + ($t:path: $($f:ident),+) => { + #[allow(unknown_lints, unneeded_field_pattern)] + const _: fn() = || { + $(let $t { $f: _, .. };)+ + }; + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_impl.rs b/bash-5.1/vendor/static_assertions/src/assert_impl.rs new file mode 100644 index 0000000..480b6b6 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_impl.rs @@ -0,0 +1,356 @@ +/// Asserts that the type implements exactly one in a set of traits. +/// +/// Related: +/// - [`assert_impl_any!`] +/// - [`assert_impl_all!`] +/// - [`assert_not_impl_all!`] +/// - [`assert_not_impl_any!`] +/// +/// # Examples +/// +/// Given some type `Foo`, it is expected to implement either `Snap`, `Crackle`, +/// or `Pop`: +/// +/// ```compile_fail +/// # use static_assertions::assert_impl_one; fn main() {} +/// struct Foo; +/// +/// trait Snap {} +/// trait Crackle {} +/// trait Pop {} +/// +/// assert_impl_one!(Foo: Snap, Crackle, Pop); +/// ``` +/// +/// If _only_ `Crackle` is implemented, the assertion passes: +/// +/// ``` +/// # use static_assertions::assert_impl_one; fn main() {} +/// # struct Foo; +/// # trait Snap {} +/// # trait Crackle {} +/// # trait Pop {} +/// impl Crackle for Foo {} +/// +/// assert_impl_one!(Foo: Snap, Crackle, Pop); +/// ``` +/// +/// If `Snap` or `Pop` is _also_ implemented, the assertion fails: +/// +/// ```compile_fail +/// # use static_assertions::assert_impl_one; fn main() {} +/// # struct Foo; +/// # trait Snap {} +/// # trait Crackle {} +/// # trait Pop {} +/// # impl Crackle for Foo {} +/// impl Pop for Foo {} +/// +/// assert_impl_one!(Foo: Snap, Crackle, Pop); +/// ``` +/// +/// [`assert_impl_any!`]: macro.assert_impl_any.html +/// [`assert_impl_all!`]: macro.assert_impl_all.html +/// [`assert_not_impl_all!`]: macro.assert_not_impl_all.html +/// [`assert_not_impl_any!`]: macro.assert_not_impl_any.html +#[macro_export] +macro_rules! assert_impl_one { + ($x:ty: $($t:path),+ $(,)?) => { + const _: fn() = || { + // Generic trait that must be implemented for `$x` exactly once. + trait AmbiguousIfMoreThanOne<A> { + // Required for actually being able to reference the trait. + fn some_item() {} + } + + // Creates multiple scoped `Token` types for each trait `$t`, over + // which a specialized `AmbiguousIfMoreThanOne<Token>` is + // implemented for every type that implements `$t`. + $({ + #[allow(dead_code)] + struct Token; + + impl<T: ?Sized + $t> AmbiguousIfMoreThanOne<Token> for T {} + })+ + + // If there is only one specialized trait impl, type inference with + // `_` can be resolved and this can compile. Fails to compile if + // `$x` implements more than one `AmbiguousIfMoreThanOne<Token>` or + // does not implement any at all. + let _ = <$x as AmbiguousIfMoreThanOne<_>>::some_item; + }; + }; +} + +/// Asserts that the type implements _all_ of the given traits. +/// +/// See [`assert_not_impl_all!`] for achieving the opposite effect. +/// +/// # Examples +/// +/// This can be used to ensure types implement auto traits such as [`Send`] and +/// [`Sync`], as well as traits with [blanket `impl`s][blanket]. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_impl_all!(u32: Copy, Send); +/// assert_impl_all!(&str: Into<String>); +/// ``` +/// +/// The following example fails to compile because raw pointers do not implement +/// [`Send`] since they cannot be moved between threads safely: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_impl_all!(*const u8: Send); +/// ``` +/// +/// [`assert_not_impl_all!`]: macro.assert_not_impl_all.html +/// [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html +/// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +/// [blanket]: https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods +#[macro_export] +macro_rules! assert_impl_all { + ($type:ty: $($trait:path),+ $(,)?) => { + const _: fn() = || { + // Only callable when `$type` implements all traits in `$($trait)+`. + fn assert_impl_all<T: ?Sized $(+ $trait)+>() {} + assert_impl_all::<$type>(); + }; + }; +} + +/// Asserts that the type implements _any_ of the given traits. +/// +/// See [`assert_not_impl_any!`] for achieving the opposite effect. +/// +/// # Examples +/// +/// `u8` cannot be converted from `u16`, but it can be converted into `u16`: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_impl_any!(u8: From<u16>, Into<u16>); +/// ``` +/// +/// The unit type cannot be converted from `u8` or `u16`, but it does implement +/// [`Send`]: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_impl_any!((): From<u8>, From<u16>, Send); +/// ``` +/// +/// The following example fails to compile because raw pointers do not implement +/// [`Send`] or [`Sync`] since they cannot be moved or shared between threads +/// safely: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_impl_any!(*const u8: Send, Sync); +/// ``` +/// +/// [`assert_not_impl_any!`]: macro.assert_not_impl_any.html +/// [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html +/// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +#[macro_export] +macro_rules! assert_impl_any { + ($x:ty: $($t:path),+ $(,)?) => { + const _: fn() = || { + use $crate::_core::marker::PhantomData; + use $crate::_core::ops::Deref; + + // Fallback to use as the first iterative assignment to `previous`. + let previous = AssertImplAnyFallback; + struct AssertImplAnyFallback; + + // Ensures that blanket traits can't impersonate the method. This + // prevents a false positive attack where---if a blanket trait is in + // scope that has `_static_assertions_impl_any`---the macro will + // compile when it shouldn't. + // + // See https://github.com/nvzqz/static-assertions-rs/issues/19 for + // more info. + struct ActualAssertImplAnyToken; + trait AssertImplAnyToken {} + impl AssertImplAnyToken for ActualAssertImplAnyToken {} + fn assert_impl_any_token<T: AssertImplAnyToken>(_: T) {} + + $(let previous = { + struct Wrapper<T, N>(PhantomData<T>, N); + + // If the method for this wrapper can't be called then the + // compiler will insert a deref and try again. This forwards the + // compiler's next attempt to the previous wrapper. + impl<T, N> Deref for Wrapper<T, N> { + type Target = N; + + fn deref(&self) -> &Self::Target { + &self.1 + } + } + + // This impl is bounded on the `$t` trait, so the method can + // only be called if `$x` implements `$t`. This is why a new + // `Wrapper` is defined for each `previous`. + impl<T: $t, N> Wrapper<T, N> { + fn _static_assertions_impl_any(&self) -> ActualAssertImplAnyToken { + ActualAssertImplAnyToken + } + } + + Wrapper::<$x, _>(PhantomData, previous) + };)+ + + // Attempt to find the method that can actually be called. The found + // method must return a type that implements the sealed `Token` + // trait, this ensures that blanket trait methods can't cause this + // macro to compile. + assert_impl_any_token(previous._static_assertions_impl_any()); + }; + }; +} + +/// Asserts that the type does **not** implement _all_ of the given traits. +/// +/// This can be used to ensure types do not implement auto traits such as +/// [`Send`] and [`Sync`], as well as traits with [blanket `impl`s][blanket]. +/// +/// Note that the combination of all provided traits is required to not be +/// implemented. If you want to check that none of multiple traits are +/// implemented you should invoke [`assert_not_impl_any!`] instead. +/// +/// # Examples +/// +/// Although `u32` implements `From<u16>`, it does not implement `Into<usize>`: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_not_impl_all!(u32: From<u16>, Into<usize>); +/// ``` +/// +/// The following example fails to compile since `u32` can be converted into +/// `u64`. +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_not_impl_all!(u32: Into<u64>); +/// ``` +/// +/// The following compiles because [`Cell`] is not both [`Sync`] _and_ [`Send`]: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// use std::cell::Cell; +/// +/// assert_not_impl_all!(Cell<u32>: Sync, Send); +/// ``` +/// +/// But it is [`Send`], so this fails to compile: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// # std::cell::Cell; +/// assert_not_impl_all!(Cell<u32>: Send); +/// ``` +/// +/// [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html +/// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +/// [`assert_not_impl_any!`]: macro.assert_not_impl_any.html +/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html +/// [blanket]: https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods +#[macro_export] +macro_rules! assert_not_impl_all { + ($x:ty: $($t:path),+ $(,)?) => { + const _: fn() = || { + // Generic trait with a blanket impl over `()` for all types. + trait AmbiguousIfImpl<A> { + // Required for actually being able to reference the trait. + fn some_item() {} + } + + impl<T: ?Sized> AmbiguousIfImpl<()> for T {} + + // Used for the specialized impl when *all* traits in + // `$($t)+` are implemented. + #[allow(dead_code)] + struct Invalid; + + impl<T: ?Sized $(+ $t)+> AmbiguousIfImpl<Invalid> for T {} + + // If there is only one specialized trait impl, type inference with + // `_` can be resolved and this can compile. Fails to compile if + // `$x` implements `AmbiguousIfImpl<Invalid>`. + let _ = <$x as AmbiguousIfImpl<_>>::some_item; + }; + }; +} + +/// Asserts that the type does **not** implement _any_ of the given traits. +/// +/// This can be used to ensure types do not implement auto traits such as +/// [`Send`] and [`Sync`], as well as traits with [blanket `impl`s][blanket]. +/// +/// This macro causes a compilation failure if any of the provided individual +/// traits are implemented for the type. If you want to check that a combination +/// of traits is not implemented you should invoke [`assert_not_impl_all!`] +/// instead. For single traits both macros behave the same. +/// +/// # Examples +/// +/// If `u32` were to implement `Into` conversions for `usize` _and_ for `u8`, +/// the following would fail to compile: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_not_impl_any!(u32: Into<usize>, Into<u8>); +/// ``` +/// +/// This is also good for simple one-off cases: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_not_impl_any!(&'static mut u8: Copy); +/// ``` +/// +/// The following example fails to compile since `u32` can be converted into +/// `u64` even though it can not be converted into a `u16`: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_not_impl_any!(u32: Into<u64>, Into<u16>); +/// ``` +/// +/// [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html +/// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +/// [`assert_not_impl_all!`]: macro.assert_not_impl_all.html +/// [blanket]: https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods +#[macro_export] +macro_rules! assert_not_impl_any { + ($x:ty: $($t:path),+ $(,)?) => { + const _: fn() = || { + // Generic trait with a blanket impl over `()` for all types. + trait AmbiguousIfImpl<A> { + // Required for actually being able to reference the trait. + fn some_item() {} + } + + impl<T: ?Sized> AmbiguousIfImpl<()> for T {} + + // Creates multiple scoped `Invalid` types for each trait `$t`, over + // which a specialized `AmbiguousIfImpl<Invalid>` is implemented for + // every type that implements `$t`. + $({ + #[allow(dead_code)] + struct Invalid; + + impl<T: ?Sized + $t> AmbiguousIfImpl<Invalid> for T {} + })+ + + // If there is only one specialized trait impl, type inference with + // `_` can be resolved and this can compile. Fails to compile if + // `$x` implements any `AmbiguousIfImpl<Invalid>`. + let _ = <$x as AmbiguousIfImpl<_>>::some_item; + }; + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_obj_safe.rs b/bash-5.1/vendor/static_assertions/src/assert_obj_safe.rs new file mode 100644 index 0000000..ecbba96 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_obj_safe.rs @@ -0,0 +1,76 @@ +// FIXME: Link below is required to render in index +/// Asserts that the traits support dynamic dispatch +/// ([object-safety](https://doc.rust-lang.org/book/ch17-02-trait-objects.html#object-safety-is-required-for-trait-objects)). +/// +/// This is useful for when changes are made to a trait that accidentally +/// prevent it from being used as an [object]. Such a case would be adding a +/// generic method and forgetting to add `where Self: Sized` after it. If left +/// unnoticed, that mistake will affect crate users and break both forward and +/// backward compatibility. +/// +/// # Examples +/// +/// When exposing a public API, it's important that traits that could previously +/// use dynamic dispatch can still do so in future compatible crate versions. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// trait MySafeTrait { +/// fn foo(&self) -> u32; +/// } +/// +/// assert_obj_safe!(std::fmt::Write, MySafeTrait); +/// ``` +/// +/// Works with traits that are not in the calling module: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// mod inner { +/// pub trait BasicTrait { +/// fn bar(&self); +/// } +/// assert_obj_safe!(BasicTrait); +/// } +/// +/// assert_obj_safe!(inner::BasicTrait); +/// ``` +/// +/// The following example fails to compile because raw pointers cannot be sent +/// between threads safely: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_impl!(*const u8, Send); +/// ``` +/// +/// The following example fails to compile because generics without +/// `where Self: Sized` are not allowed in [object-safe][object] trait methods: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// trait MyUnsafeTrait { +/// fn baz<T>(&self) -> T; +/// } +/// +/// assert_obj_safe!(MyUnsafeTrait); +/// ``` +/// +/// When we fix that, the previous code will compile: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// trait MyUnsafeTrait { +/// fn baz<T>(&self) -> T where Self: Sized; +/// } +/// +/// assert_obj_safe!(MyUnsafeTrait); +/// ``` +/// +/// [object]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#object-safety-is-required-for-trait-objects +#[macro_export] +macro_rules! assert_obj_safe { + ($($xs:path),+ $(,)?) => { + $(const _: Option<&$xs> = None;)+ + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_trait.rs b/bash-5.1/vendor/static_assertions/src/assert_trait.rs new file mode 100644 index 0000000..c231492 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_trait.rs @@ -0,0 +1,105 @@ +/// Asserts that the trait is a child of all of the other traits. +/// +/// Related: +/// - [`assert_trait_super_all!`] +/// +/// # Examples +/// +/// All types that implement [`Copy`] must implement [`Clone`]: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_trait_sub_all!(Copy: Clone); +/// ``` +/// +/// All types that implement [`Ord`] must implement [`PartialEq`], [`Eq`], and +/// [`PartialOrd`]: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_trait_sub_all!(Ord: PartialEq, Eq, PartialOrd); +/// ``` +/// +/// The following example fails to compile because [`Eq`] is not required for +/// [`PartialOrd`]: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_trait_sub_all!(PartialOrd: Eq); +/// ``` +/// +/// [`assert_trait_super_all!`]: macro.assert_trait_super_all.html +/// +/// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html +/// [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html +/// [`Ord`]: https://doc.rust-lang.org/std/cmp/trait.Ord.html +/// [`PartialOrd`]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html +/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html +#[macro_export] +macro_rules! assert_trait_sub_all { + ($sub:path: $($super:path),+ $(,)?) => { + const _: () = { + // One scope per super-trait. + $({ + #[allow(non_camel_case_types)] + trait __Impl_Implication: $super {} + + // Can only be implemented for `$sub` types if `$super` is + // also implemented. + impl<T: $sub> __Impl_Implication for T {} + })+ + }; + }; +} + +/// Asserts that the trait is a parent of all of the other traits. +/// +/// Related: +/// - [`assert_trait_sub_all!`] +/// +/// # Examples +/// +/// With this, traits `A` and `B` can both be tested to require [`Copy`] on a +/// single line: +/// +/// ``` +/// # use static_assertions::assert_trait_super_all; +/// trait A: Copy {} +/// trait B: Copy {} +/// +/// assert_trait_super_all!(Copy: A, B); +/// ``` +/// +/// Otherwise, each sub-trait would require its own call to +/// [`assert_trait_sub_all!`]: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// # trait A: Copy {} +/// # trait B: Copy {} +/// assert_trait_sub_all!(A: Copy); +/// assert_trait_sub_all!(B: Copy); +/// ``` +/// +/// The following example fails to compile because trait `C` does not require +/// [`Copy`]: +/// +/// ```compile_fail +/// # use static_assertions::assert_trait_super_all; +/// # trait A: Copy {} +/// # trait B: Copy {} +/// trait C {} +/// +/// assert_trait_super_all!(Copy: A, B, C); +/// ``` +/// +/// [`assert_trait_sub_all!`]: macro.assert_trait_sub_all.html +/// +/// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html +#[macro_export(local_inner_macros)] +macro_rules! assert_trait_super_all { + ($super:path: $($sub:path),+ $(,)?) => { + $(assert_trait_sub_all!($sub: $super);)+ + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/assert_type.rs b/bash-5.1/vendor/static_assertions/src/assert_type.rs new file mode 100644 index 0000000..dd2dc2a --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/assert_type.rs @@ -0,0 +1,101 @@ +/// Asserts that _all_ types in a list are equal to each other. +/// +/// # Examples +/// +/// Often times, type aliases are used to express usage semantics via naming. In +/// some cases, the underlying type may differ based on platform. However, other +/// types like [`c_float`] will always alias the same type. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// use std::os::raw::c_float; +/// +/// assert_type_eq_all!(c_float, f32); +/// ``` +/// +/// This macro can also be used to compare types that involve lifetimes! Just +/// use `'static` in that case: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; +/// # fn main() { +/// type Buf<'a> = &'a [u8]; +/// +/// assert_type_eq_all!(Buf<'static>, &'static [u8]); +/// # } +/// ``` +/// +/// The following example fails to compile because `String` and `str` do not +/// refer to the same type: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_type_eq_all!(String, str); +/// ``` +/// +/// This should also work the other way around, regardless of [`Deref`] +/// implementations. +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_type_eq_all!(str, String); +/// ``` +/// +/// [`c_float`]: https://doc.rust-lang.org/std/os/raw/type.c_float.html +/// [`Deref`]: https://doc.rust-lang.org/std/ops/trait.Deref.html +#[macro_export] +macro_rules! assert_type_eq_all { + ($x:ty, $($xs:ty),+ $(,)*) => { + const _: fn() = || { $({ + trait TypeEq { + type This: ?Sized; + } + + impl<T: ?Sized> TypeEq for T { + type This = Self; + } + + fn assert_type_eq_all<T, U>() + where + T: ?Sized + TypeEq<This = U>, + U: ?Sized, + {} + + assert_type_eq_all::<$x, $xs>(); + })+ }; + }; +} + +/// Asserts that _all_ types are **not** equal to each other. +/// +/// # Examples +/// +/// Rust has all sorts of slices, but they represent different types of data: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// assert_type_ne_all!([u8], [u16], str); +/// ``` +/// +/// The following example fails to compile because [`c_uchar`] is a type alias +/// for [`u8`]: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// use std::os::raw::c_uchar; +/// +/// assert_type_ne_all!(c_uchar, u8, u32); +/// ``` +/// +/// [`c_uchar`]: https://doc.rust-lang.org/std/os/raw/type.c_uchar.html +/// [`u8`]: https://doc.rust-lang.org/std/primitive.u8.html +#[macro_export] +macro_rules! assert_type_ne_all { + ($x:ty, $($y:ty),+ $(,)?) => { + const _: fn() = || { + trait MutuallyExclusive {} + impl MutuallyExclusive for $x {} + $(impl MutuallyExclusive for $y {})+ + }; + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/const_assert.rs b/bash-5.1/vendor/static_assertions/src/const_assert.rs new file mode 100644 index 0000000..16ae4a6 --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/const_assert.rs @@ -0,0 +1,109 @@ +/// Asserts that constant expressions evaluate to `true`. +/// +/// Constant expressions can be ensured to have certain properties via this +/// macro If the expression evaluates to `false`, the file will fail to compile. +/// This is synonymous to [`static_assert` in C++][static_assert]. +/// +/// # Alternatives +/// +/// There also exists [`const_assert_eq`](macro.const_assert_eq.html) for +/// validating whether a sequence of expressions are equal to one another. +/// +/// # Examples +/// +/// A common use case is to guarantee properties about a constant value that's +/// generated via meta-programming. +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const VALUE: i32 = // ... +/// # 3; +/// +/// const_assert!(VALUE >= 2); +/// ``` +/// +/// Inputs are type-checked as booleans: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const_assert!(!0); +/// ``` +/// +/// Despite this being a macro, we see this produces a type error: +/// +/// ```txt +/// | const_assert!(!0); +/// | ^^ expected bool, found integral variable +/// | +/// = note: expected type `bool` +/// found type `{integer}` +/// ``` +/// +/// The following fails to compile because multiplying by 5 does not have an +/// identity property: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const_assert!(5 * 5 == 5); +/// ``` +/// +/// [static_assert]: http://en.cppreference.com/w/cpp/language/static_assert +#[macro_export] +macro_rules! const_assert { + ($x:expr $(,)?) => { + #[allow(unknown_lints, eq_op)] + const _: [(); 0 - !{ const ASSERT: bool = $x; ASSERT } as usize] = []; + }; +} + +/// Asserts that constants are equal in value. +/// +/// # Examples +/// +/// This works as a shorthand for `const_assert!(a == b)`: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const TWO: usize = 2; +/// +/// const_assert_eq!(TWO * TWO, TWO + TWO); +/// ``` +/// +/// Just because 2 × 2 = 2 + 2 doesn't mean it holds true for other numbers: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const_assert_eq!(4 + 4, 4 * 4); +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! const_assert_eq { + ($x:expr, $y:expr $(,)?) => { + const_assert!($x == $y); + }; +} + +/// Asserts that constants are **not** equal in value. +/// +/// # Examples +/// +/// This works as a shorthand for `const_assert!(a != b)`: +/// +/// ``` +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const NUM: usize = 32; +/// +/// const_assert_ne!(NUM * NUM, 64); +/// ``` +/// +/// The following example fails to compile because 2 is magic and 2 × 2 = 2 + 2: +/// +/// ```compile_fail +/// # #[macro_use] extern crate static_assertions; fn main() {} +/// const_assert_ne!(2 + 2, 2 * 2); +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! const_assert_ne { + ($x:expr, $y:expr $(,)?) => { + const_assert!($x != $y); + }; +} diff --git a/bash-5.1/vendor/static_assertions/src/lib.rs b/bash-5.1/vendor/static_assertions/src/lib.rs new file mode 100644 index 0000000..a43cc1f --- /dev/null +++ b/bash-5.1/vendor/static_assertions/src/lib.rs @@ -0,0 +1,97 @@ +//! [![Banner](https://raw.githubusercontent.com/nvzqz/static-assertions-rs/assets/Banner.png)](https://github.com/nvzqz/static-assertions-rs) +//! +//! <div align="center"> +//! <a href="https://crates.io/crates/static_assertions"> +//! <img src="https://img.shields.io/crates/d/static_assertions.svg" alt="Downloads"> +//! </a> +//! <a href="https://travis-ci.org/nvzqz/static-assertions-rs"> +//! <img src="https://travis-ci.org/nvzqz/static-assertions-rs.svg?branch=master" alt="Build Status"> +//! </a> +//! <img src="https://img.shields.io/badge/rustc-^1.37.0-blue.svg" alt="rustc ^1.37.0"> +//! <br><br> +//! </div> +//! +//! Assertions to ensure correct assumptions about constants, types, and more. +//! +//! _All_ checks provided by this crate are performed at [compile-time]. This +//! allows for finding errors quickly and early when it comes to ensuring +//! certain features or aspects of a codebase. These macros are especially +//! important when exposing a public API that requires types to be the same size +//! or implement certain traits. +//! +//! # Usage +//! +//! This crate is available [on crates.io][crate] and can be used by adding the +//! following to your project's [`Cargo.toml`]: +//! +//! ```toml +//! [dependencies] +//! static_assertions = "1.1.0" +//! ``` +//! +//! and this to your crate root (`main.rs` or `lib.rs`): +//! +//! ``` +//! #[macro_use] +//! extern crate static_assertions; +//! # fn main() {} +//! ``` +//! +//! When using [Rust 2018 edition][2018], the following shorthand can help if +//! having `#[macro_use]` is undesirable. +//! +//! ```edition2018 +//! extern crate static_assertions as sa; +//! +//! sa::const_assert!(true); +//! ``` +//! +//! # Examples +//! +//! Very thorough examples are provided in the docs for +//! [each individual macro](#macros). Failure case examples are also documented. +//! +//! # Changes +//! +//! See [`CHANGELOG.md`](https://github.com/nvzqz/static-assertions-rs/blob/master/CHANGELOG.md) +//! for an exhaustive list of what has changed from one version to another. +//! +//! # Donate +//! +//! This project is made freely available (as in free beer), but unfortunately +//! not all beer is free! So, if you would like to buy me a beer (or coffee or +//! *more*), then consider supporting my work that's benefited your project +//! and thousands of others. +//! +//! <a href="https://www.patreon.com/nvzqz"> +//! <img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" alt="Become a Patron!" height="35"> +//! </a> +//! <a href="https://www.paypal.me/nvzqz"> +//! <img src="https://buymecoffee.intm.org/img/button-paypal-white.png" alt="Buy me a coffee" height="35"> +//! </a> +//! +//! [Rust 1.37]: https://blog.rust-lang.org/2019/08/15/Rust-1.37.0.html +//! [2018]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html#rust-2018 +//! [crate]: https://crates.io/crates/static_assertions +//! [compile-time]: https://en.wikipedia.org/wiki/Compile_time +//! [`Cargo.toml`]: https://doc.rust-lang.org/cargo/reference/manifest.html + +#![doc(html_root_url = "https://docs.rs/static_assertions/1.1.0")] +#![doc(html_logo_url = "https://raw.githubusercontent.com/nvzqz/static-assertions-rs/assets/Icon.png")] + +#![no_std] + +#![deny(unused_macros)] + +#[doc(hidden)] +pub extern crate core as _core; + +mod assert_cfg; +mod assert_eq_align; +mod assert_eq_size; +mod assert_fields; +mod assert_impl; +mod assert_obj_safe; +mod assert_trait; +mod assert_type; +mod const_assert; diff --git a/bash-5.1/vendor/strsim/.cargo-checksum.json b/bash-5.1/vendor/strsim/.cargo-checksum.json new file mode 100644 index 0000000..6b073e9 --- /dev/null +++ b/bash-5.1/vendor/strsim/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"18e89ab18be7d22dd835924a38b1198651e870dfd0a2904a344120d341c4bc0e","Cargo.toml":"dd189fa732c00b7d1b036b43220253ef6ff2a0b1ff5ca7cf13f0669113a2055e","LICENSE":"1738b51502ae831fb59ffbeb22ebdd90bf17e5c72fe57c00b47552415f133fd8","README.md":"cfb01477df60cd0780ba59cbbc388f3f71d83bf51bab77e004fc7b811aff0efd","appveyor.yml":"b41eae9798a9bb250f6046509d9bbd6e63bac9ad2655d342b3d9c8975584f0c0","benches/benches.rs":"e277857c44afdc08b2acf35fc05be6226529c588eb9da397382b0a74c58615ab","dev":"5bd26dc2c86f777627abe96c5992b6c45e6b5dea52f42b7107fa5c106abe2ab4","src/lib.rs":"26a960216567e5dea46033b3383a69e7da498095c092e195e92c05faef52f915","tests/lib.rs":"de2b1181c379a0f55de7b86021a9afb77dbe81053a6acf99623bec3663f9b7c4"},"package":"8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"} \ No newline at end of file diff --git a/bash-5.1/vendor/strsim/CHANGELOG.md b/bash-5.1/vendor/strsim/CHANGELOG.md new file mode 100644 index 0000000..48d6359 --- /dev/null +++ b/bash-5.1/vendor/strsim/CHANGELOG.md @@ -0,0 +1,123 @@ +# Change Log +This project attempts to adhere to [Semantic Versioning](http://semver.org). + +## [Unreleased] + +## [0.8.0] - (2018-08-19) +### Added +- Normalized versions of Levenshtein and Damerau-Levenshtein (thanks [@gentoid](https://github.com/gentoid)) + +## [0.7.0] - (2018-01-17) +### Changed +- Faster Levenshtein implementation (thanks [@wdv4758h](https://github.com/wdv4758h)) + +### Removed +- Remove the "against_vec" functions. They are one-liners now, so they don't + seem to add enough value to justify making the API larger. I didn't find + anybody using them when I skimmed through a GitHub search. If you do use them, + you can change the calls to something like: +```rust +let distances = strings.iter().map(|a| jaro(target, a)).collect(); +``` + +## [0.6.0] - (2016-12-26) +### Added +- Add optimal string alignment distance + +### Fixed +- Fix Damerau-Levenshtein implementation (previous implementation was actually + optimal string alignment; see this [Damerau-Levenshtein explanation]) + +## [0.5.2] - (2016-11-21) +### Changed +- Remove Cargo generated documentation in favor of a [docs.rs] link + +## [0.5.1] - (2016-08-23) +### Added +- Add Cargo generated documentation + +### Fixed +- Fix panic when Jaro or Jaro-Winkler are given strings both with a length of + one + +## [0.5.0] - (2016-08-11) +### Changed +- Make Hamming faster (thanks @IBUzPE9) when the two strings have the same + length but slower when they have different lengths + +## [0.4.1] - (2016-04-18) +### Added +- Add Vagrant setup for development +- Add AppVeyor configuration for Windows CI + +### Fixed +- Fix metrics when given strings with multibyte characters (thanks @WanzenBug) + +## [0.4.0] - (2015-06-10) +### Added +- For each metric, add a function that takes a vector of strings and returns a +vector of results (thanks @ovarene) + +## [0.3.0] - (2015-04-30) +### Changed +- Remove usage of unstable Rust features + +## [0.2.5] - (2015-04-24) +### Fixed +- Remove unnecessary `Float` import from doc tests + +## [0.2.4] - (2015-04-15) +### Fixed +- Remove unused `core` feature flag + +## [0.2.3] - (2015-04-01) +### Fixed +- Remove now unnecessary `Float` import + +## [0.2.2] - (2015-03-29) +### Fixed +- Remove usage of `char_at` (marked as unstable) + +## [0.2.1] - (2015-02-20) +### Fixed +- Update bit vector import to match Rust update + +## [0.2.0] - (2015-02-19) +### Added +- Implement Damerau-Levenshtein +- Add tests in docs + +## [0.1.1] - (2015-02-10) +### Added +- Configure Travis for CI +- Add rustdoc comments + +### Fixed +- Limit Jaro-Winkler return value to a maximum of 1.0 +- Fix float comparisons in tests + +## [0.1.0] - (2015-02-09) +### Added +- Implement Hamming, Jaro, Jaro-Winkler, and Levenshtein + +[Unreleased]: https://github.com/dguo/strsim-rs/compare/0.8.0...HEAD +[0.8.0]: https://github.com/dguo/strsim-rs/compare/0.7.0...0.8.0 +[0.7.0]: https://github.com/dguo/strsim-rs/compare/0.6.0...0.7.0 +[0.6.0]: https://github.com/dguo/strsim-rs/compare/0.5.2...0.6.0 +[0.5.2]: https://github.com/dguo/strsim-rs/compare/0.5.1...0.5.2 +[0.5.1]: https://github.com/dguo/strsim-rs/compare/0.5.0...0.5.1 +[0.5.0]: https://github.com/dguo/strsim-rs/compare/0.4.1...0.5.0 +[0.4.1]: https://github.com/dguo/strsim-rs/compare/0.4.0...0.4.1 +[0.4.0]: https://github.com/dguo/strsim-rs/compare/0.3.0...0.4.0 +[0.3.0]: https://github.com/dguo/strsim-rs/compare/0.2.5...0.3.0 +[0.2.5]: https://github.com/dguo/strsim-rs/compare/0.2.4...0.2.5 +[0.2.4]: https://github.com/dguo/strsim-rs/compare/0.2.3...0.2.4 +[0.2.3]: https://github.com/dguo/strsim-rs/compare/0.2.2...0.2.3 +[0.2.2]: https://github.com/dguo/strsim-rs/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/dguo/strsim-rs/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/dguo/strsim-rs/compare/0.1.1...0.2.0 +[0.1.1]: https://github.com/dguo/strsim-rs/compare/0.1.0...0.1.1 +[0.1.0]: https://github.com/dguo/strsim-rs/compare/fabad4...0.1.0 +[docs.rs]: https://docs.rs/strsim/ +[Damerau-Levenshtein explanation]: +http://scarcitycomputing.blogspot.com/2013/04/damerau-levenshtein-edit-distance.html diff --git a/bash-5.1/vendor/strsim/Cargo.toml b/bash-5.1/vendor/strsim/Cargo.toml new file mode 100644 index 0000000..38d37ae --- /dev/null +++ b/bash-5.1/vendor/strsim/Cargo.toml @@ -0,0 +1,28 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "strsim" +version = "0.8.0" +authors = ["Danny Guo <dannyguo91@gmail.com>"] +description = "Implementations of string similarity metrics.\nIncludes Hamming, Levenshtein, OSA, Damerau-Levenshtein, Jaro, and Jaro-Winkler.\n" +homepage = "https://github.com/dguo/strsim-rs" +documentation = "https://docs.rs/strsim/" +readme = "README.md" +keywords = ["string", "similarity", "Hamming", "Levenshtein", "Jaro"] +license = "MIT" +repository = "https://github.com/dguo/strsim-rs" +[badges.appveyor] +repository = "dguo/strsim-rs" + +[badges.travis-ci] +repository = "dguo/strsim-rs" diff --git a/bash-5.1/vendor/strsim/LICENSE b/bash-5.1/vendor/strsim/LICENSE new file mode 100644 index 0000000..1aacdb8 --- /dev/null +++ b/bash-5.1/vendor/strsim/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2015 Danny Guo +Copyright (c) 2016 Titus Wormer <tituswormer@gmail.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/bash-5.1/vendor/strsim/README.md b/bash-5.1/vendor/strsim/README.md new file mode 100644 index 0000000..8765ea8 --- /dev/null +++ b/bash-5.1/vendor/strsim/README.md @@ -0,0 +1,69 @@ +# strsim-rs [![Crates.io](https://img.shields.io/crates/v/strsim.svg)](https://crates.io/crates/strsim) [![Crates.io](https://img.shields.io/crates/l/strsim.svg?maxAge=2592000)](https://github.com/dguo/strsim-rs/blob/master/LICENSE) [![Linux build status](https://travis-ci.org/dguo/strsim-rs.svg?branch=master)](https://travis-ci.org/dguo/strsim-rs) [![Windows build status](https://ci.appveyor.com/api/projects/status/ggue6i785618a39w?svg=true)](https://ci.appveyor.com/project/dguo/strsim-rs) + +[Rust](https://www.rust-lang.org) implementations of [string similarity metrics]: + - [Hamming] + - [Levenshtein] - distance & normalized + - [Optimal string alignment] + - [Damerau-Levenshtein] - distance & normalized + - [Jaro and Jaro-Winkler] - this implementation of Jaro-Winkler does not limit the common prefix length + +### Installation +```toml +# Cargo.toml +[dependencies] +strsim = "0.8.0" +``` + +### [Documentation](https://docs.rs/strsim/) +You can change the version in the url to see the documentation for an older +version in the +[changelog](https://github.com/dguo/strsim-rs/blob/master/CHANGELOG.md). + +### Usage +```rust +extern crate strsim; + +use strsim::{hamming, levenshtein, normalized_levenshtein, osa_distance, + damerau_levenshtein, normalized_damerau_levenshtein, jaro, + jaro_winkler}; + +fn main() { + match hamming("hamming", "hammers") { + Ok(distance) => assert_eq!(3, distance), + Err(why) => panic!("{:?}", why) + } + + assert_eq!(3, levenshtein("kitten", "sitting")); + + assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001); + + assert_eq!(3, osa_distance("ac", "cba")); + + assert_eq!(2, damerau_levenshtein("ac", "cba")); + + assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001) + + assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() < + 0.001); + + assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() < + 0.001); +} +``` + +### Development +If you don't want to install Rust itself, you can run `$ ./dev` for a +development CLI if you have [Docker] installed. + +Benchmarks require a Nightly toolchain. They are run by `cargo +nightly bench`. + +### License +[MIT](https://github.com/dguo/strsim-rs/blob/master/LICENSE) + +[string similarity metrics]:http://en.wikipedia.org/wiki/String_metric +[Damerau-Levenshtein]:http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance +[Jaro and Jaro-Winkler]:http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance +[Levenshtein]:http://en.wikipedia.org/wiki/Levenshtein_distance +[Hamming]:http://en.wikipedia.org/wiki/Hamming_distance +[Optimal string alignment]:https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance +[Docker]:https://docs.docker.com/engine/installation/ diff --git a/bash-5.1/vendor/strsim/appveyor.yml b/bash-5.1/vendor/strsim/appveyor.yml new file mode 100644 index 0000000..fb992db --- /dev/null +++ b/bash-5.1/vendor/strsim/appveyor.yml @@ -0,0 +1,13 @@ +install: + - ps: Start-FileDownload 'https://static.rust-lang.org/dist/rust-beta-x86_64-pc-windows-gnu.exe' + - rust-beta-x86_64-pc-windows-gnu.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo build + - cargo test --verbose + diff --git a/bash-5.1/vendor/strsim/benches/benches.rs b/bash-5.1/vendor/strsim/benches/benches.rs new file mode 100644 index 0000000..a6d5372 --- /dev/null +++ b/bash-5.1/vendor/strsim/benches/benches.rs @@ -0,0 +1,84 @@ +//! Benchmarks for strsim. + +#![feature(test)] + +extern crate strsim; + +mod benches { + use super::*; + + extern crate test; + use self::test::Bencher; + + #[bench] + fn bench_hamming(bencher: &mut Bencher) { + let a = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGG"; + let b = "CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGC"; + bencher.iter(|| { + strsim::hamming(&a, &b).unwrap(); + }) + } + + #[bench] + fn bench_jaro(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::jaro(&a, &b); + }) + } + + #[bench] + fn bench_jaro_winkler(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::jaro_winkler(&a, &b); + }) + } + + #[bench] + fn bench_levenshtein(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::levenshtein(&a, &b); + }) + } + + #[bench] + fn bench_normalized_levenshtein(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::normalized_levenshtein(&a, &b); + }) + } + + #[bench] + fn bench_osa_distance(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::osa_distance(&a, &b); + }) + } + + #[bench] + fn bench_damerau_levenshtein(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::damerau_levenshtein(&a, &b); + }) + } + + #[bench] + fn bench_normalized_damerau_levenshtein(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::normalized_damerau_levenshtein(&a, &b); + }) + } +} diff --git a/bash-5.1/vendor/strsim/dev b/bash-5.1/vendor/strsim/dev new file mode 100755 index 0000000..4c85a49 --- /dev/null +++ b/bash-5.1/vendor/strsim/dev @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +# ./dev --help + +import argparse +import os +from subprocess import run +import sys + +parser = argparse.ArgumentParser(prog='./dev') +subparsers = parser.add_subparsers(metavar='<command>', title='commands') +command = [ + 'docker', 'run', '-it', '--rm', '-v', os.getcwd() + ':/src:cached', + '-w=/src', 'rust:1.21.0' +] + +def cargo(args, remaining): + sys.exit(run(command + ['cargo'] + remaining or []).returncode) + +parser_cargo = subparsers.add_parser('cargo', help='run a cargo command') +parser_cargo.set_defaults(func=cargo) + +def sh(args, remaining): + sys.exit(run(command + ['bash']).returncode) + +parser_sh = subparsers.add_parser('sh', help='bring up a shell') +parser_sh.set_defaults(func=sh) + +def test(args, remaining): + sys.exit(run(command + ['cargo', 'test']).returncode) + +parser_test = subparsers.add_parser('test', help='run tests') +parser_test.set_defaults(func=test) + +if len(sys.argv) > 1: + args, remaining = parser.parse_known_args() + try: + args.func(args, remaining) + except FileNotFoundError: + sys.exit('Please install Docker.') +else: + parser.print_help() diff --git a/bash-5.1/vendor/strsim/src/lib.rs b/bash-5.1/vendor/strsim/src/lib.rs new file mode 100644 index 0000000..8c56843 --- /dev/null +++ b/bash-5.1/vendor/strsim/src/lib.rs @@ -0,0 +1,786 @@ +//! This library implements string similarity metrics. + +use std::char; +use std::cmp::{max, min}; +use std::collections::HashMap; + +#[derive(Debug, PartialEq)] +pub enum StrSimError { + DifferentLengthArgs +} + +pub type HammingResult = Result<usize, StrSimError>; + +/// Calculates the number of positions in the two strings where the characters +/// differ. Returns an error if the strings have different lengths. +/// +/// ``` +/// use strsim::hamming; +/// +/// match hamming("hamming", "hammers") { +/// Ok(distance) => assert_eq!(3, distance), +/// Err(why) => panic!("{:?}", why) +/// } +/// ``` +pub fn hamming(a: &str, b: &str) -> HammingResult { + let (mut ita, mut itb, mut count) = (a.chars(), b.chars(), 0); + loop { + match (ita.next(), itb.next()){ + (Some(x), Some(y)) => if x != y { count += 1 }, + (None, None) => return Ok(count), + _ => return Err(StrSimError::DifferentLengthArgs), + } + } +} + +/// Calculates the Jaro similarity between two strings. The returned value +/// is between 0.0 and 1.0 (higher value means more similar). +/// +/// ``` +/// use strsim::jaro; +/// +/// assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() < +/// 0.001); +/// ``` +pub fn jaro(a: &str, b: &str) -> f64 { + if a == b { return 1.0; } + + let a_len = a.chars().count(); + let b_len = b.chars().count(); + + // The check for lengths of one here is to prevent integer overflow when + // calculating the search range. + if a_len == 0 || b_len == 0 || (a_len == 1 && b_len == 1) { + return 0.0; + } + + let search_range = (max(a_len, b_len) / 2) - 1; + + let mut b_consumed = Vec::with_capacity(b_len); + for _ in 0..b_len { + b_consumed.push(false); + } + let mut matches = 0.0; + + let mut transpositions = 0.0; + let mut b_match_index = 0; + + for (i, a_char) in a.chars().enumerate() { + let min_bound = + // prevent integer wrapping + if i > search_range { + max(0, i - search_range) + } else { + 0 + }; + + let max_bound = min(b_len - 1, i + search_range); + + if min_bound > max_bound { + continue; + } + + for (j, b_char) in b.chars().enumerate() { + if min_bound <= j && j <= max_bound && a_char == b_char && + !b_consumed[j] { + b_consumed[j] = true; + matches += 1.0; + + if j < b_match_index { + transpositions += 1.0; + } + b_match_index = j; + + break; + } + } + } + + if matches == 0.0 { + 0.0 + } else { + (1.0 / 3.0) * ((matches / a_len as f64) + + (matches / b_len as f64) + + ((matches - transpositions) / matches)) + } +} + +/// Like Jaro but gives a boost to strings that have a common prefix. +/// +/// ``` +/// use strsim::jaro_winkler; +/// +/// assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() < +/// 0.001); +/// ``` +pub fn jaro_winkler(a: &str, b: &str) -> f64 { + let jaro_distance = jaro(a, b); + + // Don't limit the length of the common prefix + let prefix_length = a.chars() + .zip(b.chars()) + .take_while(|&(a_char, b_char)| a_char == b_char) + .count(); + + let jaro_winkler_distance = + jaro_distance + (0.1 * prefix_length as f64 * (1.0 - jaro_distance)); + + if jaro_winkler_distance <= 1.0 { + jaro_winkler_distance + } else { + 1.0 + } +} + +/// Calculates the minimum number of insertions, deletions, and substitutions +/// required to change one string into the other. +/// +/// ``` +/// use strsim::levenshtein; +/// +/// assert_eq!(3, levenshtein("kitten", "sitting")); +/// ``` +pub fn levenshtein(a: &str, b: &str) -> usize { + if a == b { return 0; } + + let a_len = a.chars().count(); + let b_len = b.chars().count(); + + if a_len == 0 { return b_len; } + if b_len == 0 { return a_len; } + + let mut cache: Vec<usize> = (1..b_len+1).collect(); + + let mut result = 0; + let mut distance_a; + let mut distance_b; + + for (i, a_char) in a.chars().enumerate() { + result = i; + distance_b = i; + + for (j, b_char) in b.chars().enumerate() { + let cost = if a_char == b_char { 0 } else { 1 }; + distance_a = distance_b + cost; + distance_b = cache[j]; + result = min(result + 1, min(distance_a, distance_b + 1)); + cache[j] = result; + } + } + + result +} + +/// Calculates a normalized score of the Levenshtein algorithm between 0.0 and +/// 1.0 (inclusive), where 1.0 means the strings are the same. +/// +/// ``` +/// use strsim::normalized_levenshtein; +/// +/// assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001); +/// assert!((normalized_levenshtein("", "") - 1.0).abs() < 0.00001); +/// assert!(normalized_levenshtein("", "second").abs() < 0.00001); +/// assert!(normalized_levenshtein("first", "").abs() < 0.00001); +/// assert!((normalized_levenshtein("string", "string") - 1.0).abs() < 0.00001); +/// ``` +pub fn normalized_levenshtein(a: &str, b: &str) -> f64 { + if a.is_empty() && b.is_empty() { + return 1.0; + } + 1.0 - (levenshtein(a, b) as f64) / (a.chars().count().max(b.chars().count()) as f64) +} + +/// Like Levenshtein but allows for adjacent transpositions. Each substring can +/// only be edited once. +/// +/// ``` +/// use strsim::osa_distance; +/// +/// assert_eq!(3, osa_distance("ab", "bca")); +/// ``` +pub fn osa_distance(a: &str, b: &str) -> usize { + let a_len = a.chars().count(); + let b_len = b.chars().count(); + if a == b { return 0; } + else if a_len == 0 { return b_len; } + else if b_len == 0 { return a_len; } + + let mut prev_two_distances: Vec<usize> = Vec::with_capacity(b_len + 1); + let mut prev_distances: Vec<usize> = Vec::with_capacity(b_len + 1); + let mut curr_distances: Vec<usize> = Vec::with_capacity(b_len + 1); + + let mut prev_a_char = char::MAX; + let mut prev_b_char = char::MAX; + + for i in 0..(b_len + 1) { + prev_two_distances.push(i); + prev_distances.push(i); + curr_distances.push(0); + } + + for (i, a_char) in a.chars().enumerate() { + curr_distances[0] = i + 1; + + for (j, b_char) in b.chars().enumerate() { + let cost = if a_char == b_char { 0 } else { 1 }; + curr_distances[j + 1] = min(curr_distances[j] + 1, + min(prev_distances[j + 1] + 1, + prev_distances[j] + cost)); + if i > 0 && j > 0 && a_char != b_char && + a_char == prev_b_char && b_char == prev_a_char { + curr_distances[j + 1] = min(curr_distances[j + 1], + prev_two_distances[j - 1] + 1); + } + + prev_b_char = b_char; + } + + prev_two_distances.clone_from(&prev_distances); + prev_distances.clone_from(&curr_distances); + prev_a_char = a_char; + } + + curr_distances[b_len] + +} + +/// Like optimal string alignment, but substrings can be edited an unlimited +/// number of times, and the triangle inequality holds. +/// +/// ``` +/// use strsim::damerau_levenshtein; +/// +/// assert_eq!(2, damerau_levenshtein("ab", "bca")); +/// ``` +pub fn damerau_levenshtein(a: &str, b: &str) -> usize { + if a == b { return 0; } + + let a_chars: Vec<char> = a.chars().collect(); + let b_chars: Vec<char> = b.chars().collect(); + let a_len = a_chars.len(); + let b_len = b_chars.len(); + + if a_len == 0 { return b_len; } + if b_len == 0 { return a_len; } + + let mut distances = vec![vec![0; b_len + 2]; a_len + 2]; + let max_distance = a_len + b_len; + distances[0][0] = max_distance; + + for i in 0..(a_len + 1) { + distances[i + 1][0] = max_distance; + distances[i + 1][1] = i; + } + + for j in 0..(b_len + 1) { + distances[0][j + 1] = max_distance; + distances[1][j + 1] = j; + } + + let mut chars: HashMap<char, usize> = HashMap::new(); + + for i in 1..(a_len + 1) { + let mut db = 0; + + for j in 1..(b_len + 1) { + let k = match chars.get(&b_chars[j - 1]) { + Some(value) => value.clone(), + None => 0 + }; + + let l = db; + + let mut cost = 1; + if a_chars[i - 1] == b_chars[j - 1] { + cost = 0; + db = j; + } + + let substitution_cost = distances[i][j] + cost; + let insertion_cost = distances[i][j + 1] + 1; + let deletion_cost = distances[i + 1][j] + 1; + let transposition_cost = distances[k][l] + (i - k - 1) + 1 + + (j - l - 1); + + distances[i + 1][j + 1] = min(substitution_cost, + min(insertion_cost, + min(deletion_cost, + transposition_cost))); + } + + chars.insert(a_chars[i - 1], i); + } + + distances[a_len + 1][b_len + 1] +} + +/// Calculates a normalized score of the Damerau–Levenshtein algorithm between +/// 0.0 and 1.0 (inclusive), where 1.0 means the strings are the same. +/// +/// ``` +/// use strsim::normalized_damerau_levenshtein; +/// +/// assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001); +/// assert!((normalized_damerau_levenshtein("", "") - 1.0).abs() < 0.00001); +/// assert!(normalized_damerau_levenshtein("", "flower").abs() < 0.00001); +/// assert!(normalized_damerau_levenshtein("tree", "").abs() < 0.00001); +/// assert!((normalized_damerau_levenshtein("sunglasses", "sunglasses") - 1.0).abs() < 0.00001); +/// ``` +pub fn normalized_damerau_levenshtein(a: &str, b: &str) -> f64 { + if a.is_empty() && b.is_empty() { + return 1.0; + } + 1.0 - (damerau_levenshtein(a, b) as f64) / (a.chars().count().max(b.chars().count()) as f64) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hamming_empty() { + match hamming("", "") { + Ok(distance) => { assert_eq!(0, distance); }, + Err(why) => { panic!("{:?}", why); } + } + } + + #[test] + fn hamming_same() { + match hamming("hamming", "hamming") { + Ok(distance) => { assert_eq!(0, distance); }, + Err(why) => { panic!("{:?}", why); } + } + } + + #[test] + fn hamming_diff() { + match hamming("hamming", "hammers") { + Ok(distance) => { assert_eq!(3, distance); }, + Err(why) => { panic!("{:?}", why); } + } + } + + #[test] + fn hamming_diff_multibyte() { + match hamming("hamming", "h香mmüng") { + Ok(distance) => { assert_eq!(2, distance); }, + Err(why) => { panic!("{:?}", why); } + } + } + + #[test] + fn hamming_unequal_length() { + match hamming("ham", "hamming") { + Ok(_) => { panic!(); }, + Err(why) => { assert_eq!(why, StrSimError::DifferentLengthArgs); } + } + } + + #[test] + fn hamming_names() { + match hamming("Friedrich Nietzs", "Jean-Paul Sartre") { + Ok(distance) => { assert_eq!(14, distance); }, + Err(why) => { panic!("{:?}", why); } + } + } + + #[test] + fn jaro_both_empty() { + assert_eq!(1.0, jaro("", "")); + } + + #[test] + fn jaro_first_empty() { + assert_eq!(0.0, jaro("", "jaro")); + } + + #[test] + fn jaro_second_empty() { + assert_eq!(0.0, jaro("distance", "")); + } + + #[test] + fn jaro_same() { + assert_eq!(1.0, jaro("jaro", "jaro")); + } + + #[test] + fn jaro_multibyte() { + assert!((0.818 - jaro("testabctest", "testöঙ香test")) < 0.001); + assert!((0.818 - jaro("testöঙ香test", "testabctest")) < 0.001); + } + + #[test] + fn jaro_diff_short() { + assert!((0.767 - jaro("dixon", "dicksonx")).abs() < 0.001); + } + + #[test] + fn jaro_diff_one_character() { + assert_eq!(0.0, jaro("a", "b")); + } + + #[test] + fn jaro_diff_one_and_two() { + assert!((0.83 - jaro("a", "ab")).abs() < 0.01); + } + + #[test] + fn jaro_diff_two_and_one() { + assert!((0.83 - jaro("ab", "a")).abs() < 0.01); + } + + #[test] + fn jaro_diff_no_transposition() { + assert!((0.822 - jaro("dwayne", "duane")).abs() < 0.001); + } + + #[test] + fn jaro_diff_with_transposition() { + assert!((0.944 - jaro("martha", "marhta")).abs() < 0.001); + } + + #[test] + fn jaro_names() { + assert!((0.392 - jaro("Friedrich Nietzsche", + "Jean-Paul Sartre")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_both_empty() { + assert_eq!(1.0, jaro_winkler("", "")); + } + + #[test] + fn jaro_winkler_first_empty() { + assert_eq!(0.0, jaro_winkler("", "jaro-winkler")); + } + + #[test] + fn jaro_winkler_second_empty() { + assert_eq!(0.0, jaro_winkler("distance", "")); + } + + #[test] + fn jaro_winkler_same() { + assert_eq!(1.0, jaro_winkler("Jaro-Winkler", "Jaro-Winkler")); + } + + #[test] + fn jaro_winkler_multibyte() { + assert!((0.89 - jaro_winkler("testabctest", "testöঙ香test")).abs() < + 0.001); + assert!((0.89 - jaro_winkler("testöঙ香test", "testabctest")).abs() < + 0.001); + } + + #[test] + fn jaro_winkler_diff_short() { + assert!((0.813 - jaro_winkler("dixon", "dicksonx")).abs() < 0.001); + assert!((0.813 - jaro_winkler("dicksonx", "dixon")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_diff_one_character() { + assert_eq!(0.0, jaro_winkler("a", "b")); + } + + #[test] + fn jaro_winkler_diff_no_transposition() { + assert!((0.840 - jaro_winkler("dwayne", "duane")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_diff_with_transposition() { + assert!((0.961 - jaro_winkler("martha", "marhta")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_names() { + assert!((0.562 - jaro_winkler("Friedrich Nietzsche", + "Fran-Paul Sartre")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_long_prefix() { + assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() < + 0.001); + } + + #[test] + fn jaro_winkler_more_names() { + assert!((0.868 - jaro_winkler("Thorkel", "Thorgier")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_length_of_one() { + assert!((0.738 - jaro_winkler("Dinsdale", "D")).abs() < 0.001); + } + + #[test] + fn jaro_winkler_very_long_prefix() { + assert!((1.0 - jaro_winkler("thequickbrownfoxjumpedoverx", + "thequickbrownfoxjumpedovery")).abs() < + 0.001); + } + + #[test] + fn levenshtein_empty() { + assert_eq!(0, levenshtein("", "")); + } + + #[test] + fn levenshtein_same() { + assert_eq!(0, levenshtein("levenshtein", "levenshtein")); + } + + #[test] + fn levenshtein_diff_short() { + assert_eq!(3, levenshtein("kitten", "sitting")); + } + + #[test] + fn levenshtein_diff_with_space() { + assert_eq!(5, levenshtein("hello, world", "bye, world")); + } + + #[test] + fn levenshtein_diff_multibyte() { + assert_eq!(3, levenshtein("öঙ香", "abc")); + assert_eq!(3, levenshtein("abc", "öঙ香")); + } + + #[test] + fn levenshtein_diff_longer() { + let a = "The quick brown fox jumped over the angry dog."; + let b = "Lorem ipsum dolor sit amet, dicta latine an eam."; + assert_eq!(37, levenshtein(a, b)); + } + + #[test] + fn levenshtein_first_empty() { + assert_eq!(7, levenshtein("", "sitting")); + } + + #[test] + fn levenshtein_second_empty() { + assert_eq!(6, levenshtein("kitten", "")); + } + + #[test] + fn normalized_levenshtein_diff_short() { + assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001); + } + + #[test] + fn normalized_levenshtein_for_empty_strings() { + assert!((normalized_levenshtein("", "") - 1.0).abs() < 0.00001); + } + + #[test] + fn normalized_levenshtein_first_empty() { + assert!(normalized_levenshtein("", "second").abs() < 0.00001); + } + + #[test] + fn normalized_levenshtein_second_empty() { + assert!(normalized_levenshtein("first", "").abs() < 0.00001); + } + + #[test] + fn normalized_levenshtein_identical_strings() { + assert!((normalized_levenshtein("identical", "identical") - 1.0).abs() < 0.00001); + } + + #[test] + fn osa_distance_empty() { + assert_eq!(0, osa_distance("", "")); + } + + #[test] + fn osa_distance_same() { + assert_eq!(0, osa_distance("damerau", "damerau")); + } + + #[test] + fn osa_distance_first_empty() { + assert_eq!(7, osa_distance("", "damerau")); + } + + #[test] + fn osa_distance_second_empty() { + assert_eq!(7, osa_distance("damerau", "")); + } + + #[test] + fn osa_distance_diff() { + assert_eq!(3, osa_distance("ca", "abc")); + } + + #[test] + fn osa_distance_diff_short() { + assert_eq!(3, osa_distance("damerau", "aderua")); + } + + #[test] + fn osa_distance_diff_reversed() { + assert_eq!(3, osa_distance("aderua", "damerau")); + } + + #[test] + fn osa_distance_diff_multibyte() { + assert_eq!(3, osa_distance("öঙ香", "abc")); + assert_eq!(3, osa_distance("abc", "öঙ香")); + } + + #[test] + fn osa_distance_diff_unequal_length() { + assert_eq!(6, osa_distance("damerau", "aderuaxyz")); + } + + #[test] + fn osa_distance_diff_unequal_length_reversed() { + assert_eq!(6, osa_distance("aderuaxyz", "damerau")); + } + + #[test] + fn osa_distance_diff_comedians() { + assert_eq!(5, osa_distance("Stewart", "Colbert")); + } + + #[test] + fn osa_distance_many_transpositions() { + assert_eq!(4, osa_distance("abcdefghijkl", "bacedfgihjlk")); + } + + #[test] + fn osa_distance_diff_longer() { + let a = "The quick brown fox jumped over the angry dog."; + let b = "Lehem ipsum dolor sit amet, dicta latine an eam."; + assert_eq!(36, osa_distance(a, b)); + } + + #[test] + fn osa_distance_beginning_transposition() { + assert_eq!(1, osa_distance("foobar", "ofobar")); + } + + #[test] + fn osa_distance_end_transposition() { + assert_eq!(1, osa_distance("specter", "spectre")); + } + + #[test] + fn osa_distance_restricted_edit() { + assert_eq!(4, osa_distance("a cat", "an abct")); + } + + #[test] + fn damerau_levenshtein_empty() { + assert_eq!(0, damerau_levenshtein("", "")); + } + + #[test] + fn damerau_levenshtein_same() { + assert_eq!(0, damerau_levenshtein("damerau", "damerau")); + } + + #[test] + fn damerau_levenshtein_first_empty() { + assert_eq!(7, damerau_levenshtein("", "damerau")); + } + + #[test] + fn damerau_levenshtein_second_empty() { + assert_eq!(7, damerau_levenshtein("damerau", "")); + } + + #[test] + fn damerau_levenshtein_diff() { + assert_eq!(2, damerau_levenshtein("ca", "abc")); + } + + #[test] + fn damerau_levenshtein_diff_short() { + assert_eq!(3, damerau_levenshtein("damerau", "aderua")); + } + + #[test] + fn damerau_levenshtein_diff_reversed() { + assert_eq!(3, damerau_levenshtein("aderua", "damerau")); + } + + #[test] + fn damerau_levenshtein_diff_multibyte() { + assert_eq!(3, damerau_levenshtein("öঙ香", "abc")); + assert_eq!(3, damerau_levenshtein("abc", "öঙ香")); + } + + #[test] + fn damerau_levenshtein_diff_unequal_length() { + assert_eq!(6, damerau_levenshtein("damerau", "aderuaxyz")); + } + + #[test] + fn damerau_levenshtein_diff_unequal_length_reversed() { + assert_eq!(6, damerau_levenshtein("aderuaxyz", "damerau")); + } + + #[test] + fn damerau_levenshtein_diff_comedians() { + assert_eq!(5, damerau_levenshtein("Stewart", "Colbert")); + } + + #[test] + fn damerau_levenshtein_many_transpositions() { + assert_eq!(4, damerau_levenshtein("abcdefghijkl", "bacedfgihjlk")); + } + + #[test] + fn damerau_levenshtein_diff_longer() { + let a = "The quick brown fox jumped over the angry dog."; + let b = "Lehem ipsum dolor sit amet, dicta latine an eam."; + assert_eq!(36, damerau_levenshtein(a, b)); + } + + #[test] + fn damerau_levenshtein_beginning_transposition() { + assert_eq!(1, damerau_levenshtein("foobar", "ofobar")); + } + + #[test] + fn damerau_levenshtein_end_transposition() { + assert_eq!(1, damerau_levenshtein("specter", "spectre")); + } + + #[test] + fn damerau_levenshtein_unrestricted_edit() { + assert_eq!(3, damerau_levenshtein("a cat", "an abct")); + } + + #[test] + fn normalized_damerau_levenshtein_diff_short() { + assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001); + } + + #[test] + fn normalized_damerau_levenshtein_for_empty_strings() { + assert!((normalized_damerau_levenshtein("", "") - 1.0).abs() < 0.00001); + } + + #[test] + fn normalized_damerau_levenshtein_first_empty() { + assert!(normalized_damerau_levenshtein("", "flower").abs() < 0.00001); + } + + #[test] + fn normalized_damerau_levenshtein_second_empty() { + assert!(normalized_damerau_levenshtein("tree", "").abs() < 0.00001); + } + + #[test] + fn normalized_damerau_levenshtein_identical_strings() { + assert!((normalized_damerau_levenshtein("sunglasses", "sunglasses") - 1.0).abs() < 0.00001); + } +} diff --git a/bash-5.1/vendor/strsim/tests/lib.rs b/bash-5.1/vendor/strsim/tests/lib.rs new file mode 100644 index 0000000..ad7af51 --- /dev/null +++ b/bash-5.1/vendor/strsim/tests/lib.rs @@ -0,0 +1,49 @@ +extern crate strsim; + +use strsim::{hamming, levenshtein, normalized_levenshtein, osa_distance,damerau_levenshtein, + normalized_damerau_levenshtein, jaro, jaro_winkler}; + +#[test] +fn hamming_works() { + match hamming("hamming", "hammers") { + Ok(distance) => assert_eq!(3, distance), + Err(why) => panic!("{:?}", why) + } +} + +#[test] +fn levenshtein_works() { + assert_eq!(3, levenshtein("kitten", "sitting")); +} + +#[test] +fn normalized_levenshtein_works() { + assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001); +} + +#[test] +fn osa_distance_works() { + assert_eq!(3, osa_distance("ac", "cba")); +} + +#[test] +fn damerau_levenshtein_works() { + assert_eq!(2, damerau_levenshtein("ac", "cba")); +} + +#[test] +fn normalized_damerau_levenshtein_works() { + assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001); +} + +#[test] +fn jaro_works() { + assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() < + 0.001); +} + +#[test] +fn jaro_winkler_works() { + assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() < + 0.001); +} diff --git a/bash-5.1/vendor/syn/.cargo-checksum.json b/bash-5.1/vendor/syn/.cargo-checksum.json index 691cc4e..8b90dae 100644 --- a/bash-5.1/vendor/syn/.cargo-checksum.json +++ b/bash-5.1/vendor/syn/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"598185e9190166e7f3217ced440d8b3e555ae2a6a84b51ee5ea0a5c7f55bdd0b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"b1546652aefba564455c1ebbf0f276450d4fdb19755e08bfa03c13c8bab241fc","benches/file.rs":"39e124e8ebb7f7171af29e87debbcaeb87c1eb465ef1436cfd8f218b340ef580","benches/rust.rs":"22dfbffc39f8d091ef74cca849e7e7c69e9a47f2a06f7dec91c0382401055c14","build.rs":"b815649fd2929d3debd93a58f5da2fb8eba506047a6a5ba538347305828a87b0","src/attr.rs":"234d9cebe2c5e92cd0f5e1117bf5755037e2e905788a337000a65d4bd82b63aa","src/await.rs":"8aa22e3c201cb2bdb6b4817fa00901f308ab06817607aa7b884c58c957705969","src/bigint.rs":"efc7f64959980653d73fe4f8bc2a3a2904dc05f45b02c6dc15cd316fa3d7c338","src/buffer.rs":"bd5762429e5eb3c899167e820620e7e2a66b4573c48e17326ed12d7461962536","src/custom_keyword.rs":"5c706fc3611e73d16b8c019d7ecb848a86b1ccfcd9e556f80bb6e6a4abe058a8","src/custom_punctuation.rs":"8a666298e774b0d326642f0f73284f6677d0d0a7c9e4a712c9c98d010b4d8a2c","src/data.rs":"75d2c2b5d6a01bf8a6fa2845e41663d8045a78b4b191f1a1bd7c93619d20017a","src/derive.rs":"ee24a202be2d36ccdff576dd9cd765e94b33ef2286946e6725d75b08e777d462","src/discouraged.rs":"6c6a9298f8d24f578da119557bc588f3bd928f7b79fca27d6bdfe3e786dd005f","src/error.rs":"e548cc5b7c6f742ab6c19788755980594c4cb8086f99e6709f1cbc982961102d","src/export.rs":"0cf50d70c32d5fddba8b1193032df62e560237c113df3e86ba26b565cc82838e","src/expr.rs":"0d441100457567b7b18372fdcbbe833d7516b5a43f17f1cfc4d7f354141b8206","src/ext.rs":"1f648cff1d705a1cea64b32b77482b97a82d2fe0aaf63b40cade91e5c02dc969","src/file.rs":"f86697655222ae294215114f4eae8e6b0b5e2a935d6c479ff8f8f889c4efd2e2","src/gen/clone.rs":"c43199af10b9963476a1ef6b9e0540363a8383c611f8999463235a0939817da8","src/gen/debug.rs":"12e07500a09d1d15b7a148d9155af357c7ac9b65ac100906cf0fac604403274e","src/gen/eq.rs":"e0928a9f4e81a7ede04853d1837abccaf29dd4ffb56d864fad2f4c3a4c76f1b4","src/gen/fold.rs":"43b34e7a951c180b65c6dd97c380f067ea91776f52e70f61555bd8a4120170b1","src/gen/hash.rs":"b66425846386e2168990b3bee2461f5c01695acd8c4b6360619a07108b260f3d","src/gen/visit.rs":"d559f661ab4a4c5b058af91ef244f30f906b6be82d1dd61bf0d058236f8c6a35","src/gen/visit_mut.rs":"fe384074919cdb1a6f54b93f8a9c768da7d3751e5bbfaf8c6c7133a7ebd390ae","src/gen_helper.rs":"ea6c66388365971db6a2fc86cbb208f7eacde77e245bc8623f27a3642a3d7741","src/generics.rs":"46ed41bf116448822ddfefcb62e803fd33264ca8ba672efc0612674d85b6dd11","src/group.rs":"166f0fbb365471ffa3e4f554b72c2b460cbf7e3a1f9bec6c01ef6bbbcd751041","src/ident.rs":"2443e43561abea7eea577b141422258237a663499c839923d8a5ca6fea2470db","src/item.rs":"2745d8bc068f821fc7dc8f480aceac1d10adc578a0b8b7317eb78f5c9048c68c","src/lib.rs":"143cbfa606d88ed75d3f80a27ca582c4b5285e2e60b78991bec02393ffebf334","src/lifetime.rs":"b18862ef1e690037a4f308ea897debad7bc5038584e3b26c6d8809752ea0e3c2","src/lit.rs":"9134ff103d943cfabdbfae56e78881680f91f9902172b890884a05c58131602a","src/lookahead.rs":"e2c2b6d55906421e83dab51463b58bc6dcb582f1bff9303c8b62afefb8d71e5f","src/mac.rs":"004cb89f9697564f6c9ee837e08ead68463ef946fb4c13c6c105adf2ba364b2b","src/macros.rs":"936f503c2fcde602f05220954ecaf87625c6138d0af13d33d56c7b6530110084","src/op.rs":"9d499022902743a6a0a19223b356449a979b90e60552d0446497d72750e646a4","src/parse.rs":"7b2f8caddf25a5734cbcdf7cbf043cbf9afbc07b484966cd59ddfcec9f970fb3","src/parse_macro_input.rs":"88929a1a7e5e72aa2d0b3459e52d8975afea856d159047ba4ab02ecbc5878a9c","src/parse_quote.rs":"d7d996f1382c68b5fbfd4b7327ce1d389cd43c3bb3c4f382a35994d0bb79d8ab","src/pat.rs":"1e0223ca92c160e07b17a593bb93dd5d451fc9b7014012b403377a4f0f21bfce","src/path.rs":"1ad8b8335628f67a013b7ce2f662aa2feab4583ff67bc959a9dea1dcb51be8a3","src/print.rs":"da6529c1d9d21aaf6c835f66b4e67eacb7cf91a10eb5e9a2143b49bf99b3b5e1","src/punctuated.rs":"f687c23bd3ae512e7412c28ac68030d3bc7a384d1ca8b3da6620e364b0cbbb78","src/reserved.rs":"e70e028bd55cfa43e23cab4ba29e4dc53a3d91eff685ef2b6e57efc2b87a3428","src/sealed.rs":"896a495a5340eec898527f18bd4ddca408ea03ea0ee3af30074ff48deace778d","src/span.rs":"748c51c6feb223c26d3b1701f5bb98aee823666c775c98106cfa24fe29d8cec1","src/spanned.rs":"3ca016a943637653ab98e373dfb826a120f3c159867346fa38a844439944eb39","src/stmt.rs":"8115bc96090022baad91660d7e5e986664c3f1fbd2f112d1c5d1d77e5c3f227e","src/thread.rs":"815eca6bd64f4eef7c447f0809e84108f5428ff50225224b373efd8fbb696874","src/token.rs":"5e423a696f80e281c322f37c87577f9fdc28607e9c007e24896a2b12da62d5ad","src/tt.rs":"32402645b6e82ef1e882945721b59b5fb7b0ee337d1972876362ecacef643d0f","src/ty.rs":"5c05b000d4884334bed729c3345732fbbb4136a75df9dd5002c493ebb6cd091b","src/verbatim.rs":"802a97df997432f18cac6e6200ff6ea29fb2474986005e0fcdbc2b65197f87f7","src/whitespace.rs":"e63dd0aa3d34029f17766a8b09c1a6e4479e36c552c8b7023d710a399333aace","tests/.gitignore":"22e782449a3c216db3f7215d5fb8882e316768e40beeec3833aae419ad8941db","tests/common/eq.rs":"529ae94214c0666045a4c16d9beab6c71eedb40e100be8f990674d44480b5ba6","tests/common/mod.rs":"432ad35577f836a20b517d8c26ed994ac25fe73ef2f461c67688b61b99762015","tests/common/parse.rs":"81580f23583723f7a2a337c4d13ebc021057cd825562fb4e474caa7cc641fed9","tests/debug/gen.rs":"4937074a11fe8266431d05177435bad28340763d408d0a4c45bd0c0acc90a86a","tests/debug/mod.rs":"3a6bb799f478101f71c84c6f1a854a58afe2f9db43c39017909346ca20262d94","tests/macros/mod.rs":"aff805b35cfd55aef6a1359ff747e4023afcb08d69d86aff4c19465d29dda088","tests/regression.rs":"f962ebf24007f631f7e702e34e142d07581da7c9a36321ac142cafed1a0afc69","tests/regression/issue1108.rs":"f32db35244a674e22ff824ca9e5bbec2184e287b59f022db68c418b5878a2edc","tests/repo/mod.rs":"947b678f50df8716ef5c946885a3096e91ab2ec4ce2251cea83d6e6d2ab82eb5","tests/repo/progress.rs":"c08d0314a7f3ecf760d471f27da3cd2a500aeb9f1c8331bffb2aa648f9fabf3f","tests/test_asyncness.rs":"cff01db49d28ab23b0b258bc6c0a5cc4071be4fe7248eef344a5d79d2fb649b7","tests/test_attribute.rs":"0ffd99384e1a52ae17d9fed5c4053e411e8f9018decef07ffa621d1faa7329d8","tests/test_derive_input.rs":"62bb86aaaaf730187a46ff700a8e3b2d1a163039b109b6a483aa44ed2b6806fe","tests/test_expr.rs":"a639728866a063b590430965a4840c01755e398b89be12d8d09b0aa97837ecac","tests/test_generics.rs":"54b7d2afc19aa6e9049585f4c8f7d3f0c29ac3bd11a2c769e9df76f18a4f5ecb","tests/test_grouping.rs":"6276c3c73bba649dec5c97904ad2492879f918bc887a2c425d095c654ca0d925","tests/test_ident.rs":"9eb53d1e21edf23e7c9e14dc74dcc2b2538e9221e19dbcc0a44e3acc2e90f3f6","tests/test_item.rs":"a3642c80066f1e7787becfd0278af90a6b7968d6c1249e25e81663aa454cfb2a","tests/test_iterators.rs":"53ed6078d37550bd6765d2411e3660be401aef8a31a407350cc064a7d08c7c33","tests/test_lit.rs":"19740ea9cd4a980bcab9b0dcaa4b032bb6ebb137fa5e4237140b97da1d9679fa","tests/test_meta.rs":"65d4586d131f6cac66694ca5e936748ec4e7f7423af6d8da509240e6be14800b","tests/test_parse_buffer.rs":"68d857f776396d064fcc0023c37093c2fbf75ee68e8241d4014d00d1423c18e9","tests/test_parse_stream.rs":"2f449a2c41a3dee6fd14bee24e1666a453cb808eda17332fd91afd127fcdd2a6","tests/test_pat.rs":"d4465f4fc3fd5d6e534ba8efabe1e0ed6da89de4ac7c96effa6bfb880c4287cf","tests/test_path.rs":"71092a5ae2c9143b92a8fe15a92d39958b3c28bd4d4275cfb2d22cbdd53ada07","tests/test_precedence.rs":"1069d979cec0e6c650bebb58be272d23080ce89e83d194dfa2718d22912e481d","tests/test_receiver.rs":"084eca59984b9a18651da52f2c4407355da3de1335916a12477652999e2d01cc","tests/test_round_trip.rs":"b47662e35be2729f28bacdbbea20f1879c111889430e735a7bcb5f2a5c0b9e5c","tests/test_shebang.rs":"f5772cadad5b56e3112cb16308b779f92bce1c3a48091fc9933deb2276a69331","tests/test_should_parse.rs":"1d3535698a446e2755bfc360676bdb161841a1f454cdef6e7556c6d06a95c89d","tests/test_size.rs":"1aa0dd489bd844a4a9cf32a5310abd66dad1dae3ffb24fe1288b62a26bfdd8dc","tests/test_stmt.rs":"0601fc32131b5501dfcdc4b4248d46bf21e0a98a49eb19439e1a46869dfb30b7","tests/test_token_trees.rs":"43e56a701817e3c3bfd0cae54a457dd7a38ccb3ca19da41e2b995fdf20e6ed18","tests/test_ty.rs":"f71d7f7f1c038aaabea8dd4c03c0d5752c76d570f8b4885a81659825bbb4d576","tests/test_visibility.rs":"7456fcb3a6634db509748aededff9c2d8b242d511a3e5ee3022e40b232892704","tests/zzz_stable.rs":"2a862e59cb446235ed99aec0e6ada8e16d3ecc30229b29d825b7c0bbc2602989"},"package":"58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13"} \ No newline at end of file +{"files":{"Cargo.toml":"8366f3b0e0c3a589f43424b1837bb43aa8b4dd224184d355ad38a63bac915210","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"b1546652aefba564455c1ebbf0f276450d4fdb19755e08bfa03c13c8bab241fc","benches/file.rs":"3d737ef3878f6e242b003af9bd539e565f98439a12ee44d9548d84e3fdd7af0c","benches/rust.rs":"11ac9fe898a7bf1bd63e8a8cc9c08bd795b01f0248215cff99afaaf28ce87fab","build.rs":"b815649fd2929d3debd93a58f5da2fb8eba506047a6a5ba538347305828a87b0","src/attr.rs":"234d9cebe2c5e92cd0f5e1117bf5755037e2e905788a337000a65d4bd82b63aa","src/await.rs":"8aa22e3c201cb2bdb6b4817fa00901f308ab06817607aa7b884c58c957705969","src/bigint.rs":"efc7f64959980653d73fe4f8bc2a3a2904dc05f45b02c6dc15cd316fa3d7c338","src/buffer.rs":"2b48296087f096c9630e1e4b03a00ae703407d1b352902b3197370b2f56c62ff","src/custom_keyword.rs":"5c706fc3611e73d16b8c019d7ecb848a86b1ccfcd9e556f80bb6e6a4abe058a8","src/custom_punctuation.rs":"8a666298e774b0d326642f0f73284f6677d0d0a7c9e4a712c9c98d010b4d8a2c","src/data.rs":"75d2c2b5d6a01bf8a6fa2845e41663d8045a78b4b191f1a1bd7c93619d20017a","src/derive.rs":"ee24a202be2d36ccdff576dd9cd765e94b33ef2286946e6725d75b08e777d462","src/discouraged.rs":"6c6a9298f8d24f578da119557bc588f3bd928f7b79fca27d6bdfe3e786dd005f","src/error.rs":"e548cc5b7c6f742ab6c19788755980594c4cb8086f99e6709f1cbc982961102d","src/export.rs":"0cf50d70c32d5fddba8b1193032df62e560237c113df3e86ba26b565cc82838e","src/expr.rs":"5eea3828f3291b0ce5463ed5f0c23fc8a39aeceae68a3247ae02ae467dd35a98","src/ext.rs":"1f648cff1d705a1cea64b32b77482b97a82d2fe0aaf63b40cade91e5c02dc969","src/file.rs":"f86697655222ae294215114f4eae8e6b0b5e2a935d6c479ff8f8f889c4efd2e2","src/gen/clone.rs":"76e89fe155fedf43bc4a252af7e35319b82ce455f584bad8698fdc3f9b7f5d4e","src/gen/debug.rs":"4b05e474e864ce6bf1a5a6ab48ee6c0ecdf41a0d750237990cf2e31963bc1208","src/gen/eq.rs":"79f84836fdcd5cfa352f38055dab7c3246c7757650946c1c701234b11021652a","src/gen/fold.rs":"fcd6a05c8c8e0c36e7ede8593002528b553c8b648fbed452106fd6a8a8c9212a","src/gen/hash.rs":"575e8beae303c1eabda12bf76cbd82672268c502a8ebb8517aab18b40fdbc44e","src/gen/visit.rs":"ced9f6c17d2b3eb3553faab710cb2b3d44d6bca7d1862c8c5da09c3d45debecb","src/gen/visit_mut.rs":"966ea340c53461bf8a1c6bed3c882e4ab8b8907fd18ac35531266f7891ae5f46","src/gen_helper.rs":"ea6c66388365971db6a2fc86cbb208f7eacde77e245bc8623f27a3642a3d7741","src/generics.rs":"46ed41bf116448822ddfefcb62e803fd33264ca8ba672efc0612674d85b6dd11","src/group.rs":"166f0fbb365471ffa3e4f554b72c2b460cbf7e3a1f9bec6c01ef6bbbcd751041","src/ident.rs":"2443e43561abea7eea577b141422258237a663499c839923d8a5ca6fea2470db","src/item.rs":"419c4d6135a7ca7b8f94b5ba038b6af8fcb3939ae807153a19e3c82e9b01e0b7","src/lib.rs":"7875551b227d19f083115d48a83e8c35e3e6d31dbd749bdd03556e2762f7d4fd","src/lifetime.rs":"b18862ef1e690037a4f308ea897debad7bc5038584e3b26c6d8809752ea0e3c2","src/lit.rs":"fc06ddd523f7f9971d8abdb4c8d5d51030ffb3d6810615d5575ae210a7800695","src/lookahead.rs":"e2c2b6d55906421e83dab51463b58bc6dcb582f1bff9303c8b62afefb8d71e5f","src/mac.rs":"004cb89f9697564f6c9ee837e08ead68463ef946fb4c13c6c105adf2ba364b2b","src/macros.rs":"936f503c2fcde602f05220954ecaf87625c6138d0af13d33d56c7b6530110084","src/op.rs":"9d499022902743a6a0a19223b356449a979b90e60552d0446497d72750e646a4","src/parse.rs":"7b2f8caddf25a5734cbcdf7cbf043cbf9afbc07b484966cd59ddfcec9f970fb3","src/parse_macro_input.rs":"a5d16859b782bb6a2754c1066468a2f1ea05b57390caa32175bb84064973be7b","src/parse_quote.rs":"d7d996f1382c68b5fbfd4b7327ce1d389cd43c3bb3c4f382a35994d0bb79d8ab","src/pat.rs":"b2de04ae6c01df50eab9d1c3908287aca8424adc2007b926c7bcf74d1f64d40a","src/path.rs":"269d5d8b0c21eaf96e1c49bcb1ec2a03175a8adcc103c142e550b3f5e79825d8","src/print.rs":"da6529c1d9d21aaf6c835f66b4e67eacb7cf91a10eb5e9a2143b49bf99b3b5e1","src/punctuated.rs":"f687c23bd3ae512e7412c28ac68030d3bc7a384d1ca8b3da6620e364b0cbbb78","src/reserved.rs":"e70e028bd55cfa43e23cab4ba29e4dc53a3d91eff685ef2b6e57efc2b87a3428","src/sealed.rs":"896a495a5340eec898527f18bd4ddca408ea03ea0ee3af30074ff48deace778d","src/span.rs":"748c51c6feb223c26d3b1701f5bb98aee823666c775c98106cfa24fe29d8cec1","src/spanned.rs":"3ca016a943637653ab98e373dfb826a120f3c159867346fa38a844439944eb39","src/stmt.rs":"601a6914f1e0bf97ae0d31d474a531d195b8c251a4ded11aa8746ac0018d367b","src/thread.rs":"815eca6bd64f4eef7c447f0809e84108f5428ff50225224b373efd8fbb696874","src/token.rs":"5e423a696f80e281c322f37c87577f9fdc28607e9c007e24896a2b12da62d5ad","src/tt.rs":"32402645b6e82ef1e882945721b59b5fb7b0ee337d1972876362ecacef643d0f","src/ty.rs":"7e678749af18fc84ae9220435e467e520de05eea66adeeed3b5d634cd744561c","src/verbatim.rs":"802a97df997432f18cac6e6200ff6ea29fb2474986005e0fcdbc2b65197f87f7","src/whitespace.rs":"e63dd0aa3d34029f17766a8b09c1a6e4479e36c552c8b7023d710a399333aace","tests/common/eq.rs":"953f5db261a3334eba1d37df4247463e9234c7988da04f43028b5273d24bf2da","tests/common/mod.rs":"432ad35577f836a20b517d8c26ed994ac25fe73ef2f461c67688b61b99762015","tests/common/parse.rs":"81580f23583723f7a2a337c4d13ebc021057cd825562fb4e474caa7cc641fed9","tests/debug/gen.rs":"1b7f875344cb04a7dd3df62deac2f410a9d107c097986e68006d87465f5f5306","tests/debug/mod.rs":"3a6bb799f478101f71c84c6f1a854a58afe2f9db43c39017909346ca20262d94","tests/macros/mod.rs":"aff805b35cfd55aef6a1359ff747e4023afcb08d69d86aff4c19465d29dda088","tests/regression.rs":"f962ebf24007f631f7e702e34e142d07581da7c9a36321ac142cafed1a0afc69","tests/regression/issue1108.rs":"adcc55a42239d344da74216ed85fc14153ddd6ca4dec4872d8339604ba78c185","tests/repo/mod.rs":"1ea18f9430e75cabc4b23b826544c2bf2f950b679a04b237a11e17aabc16e2e9","tests/repo/progress.rs":"c08d0314a7f3ecf760d471f27da3cd2a500aeb9f1c8331bffb2aa648f9fabf3f","tests/test_asyncness.rs":"cff01db49d28ab23b0b258bc6c0a5cc4071be4fe7248eef344a5d79d2fb649b7","tests/test_attribute.rs":"0ffd99384e1a52ae17d9fed5c4053e411e8f9018decef07ffa621d1faa7329d8","tests/test_derive_input.rs":"62bb86aaaaf730187a46ff700a8e3b2d1a163039b109b6a483aa44ed2b6806fe","tests/test_expr.rs":"a639728866a063b590430965a4840c01755e398b89be12d8d09b0aa97837ecac","tests/test_generics.rs":"54b7d2afc19aa6e9049585f4c8f7d3f0c29ac3bd11a2c769e9df76f18a4f5ecb","tests/test_grouping.rs":"6276c3c73bba649dec5c97904ad2492879f918bc887a2c425d095c654ca0d925","tests/test_ident.rs":"9eb53d1e21edf23e7c9e14dc74dcc2b2538e9221e19dbcc0a44e3acc2e90f3f6","tests/test_item.rs":"a3642c80066f1e7787becfd0278af90a6b7968d6c1249e25e81663aa454cfb2a","tests/test_iterators.rs":"53ed6078d37550bd6765d2411e3660be401aef8a31a407350cc064a7d08c7c33","tests/test_lit.rs":"19740ea9cd4a980bcab9b0dcaa4b032bb6ebb137fa5e4237140b97da1d9679fa","tests/test_meta.rs":"65d4586d131f6cac66694ca5e936748ec4e7f7423af6d8da509240e6be14800b","tests/test_parse_buffer.rs":"68d857f776396d064fcc0023c37093c2fbf75ee68e8241d4014d00d1423c18e9","tests/test_parse_stream.rs":"bf1db6fab7ac396fa61012faccbe6ffbc9c3d795ed2900be75e91c5b09b0c62f","tests/test_pat.rs":"d4465f4fc3fd5d6e534ba8efabe1e0ed6da89de4ac7c96effa6bfb880c4287cf","tests/test_path.rs":"71092a5ae2c9143b92a8fe15a92d39958b3c28bd4d4275cfb2d22cbdd53ada07","tests/test_precedence.rs":"736eee861c4c7a3d7d4387d2fb1b5eced1541790d34974f72b0a5532797e73c3","tests/test_receiver.rs":"084eca59984b9a18651da52f2c4407355da3de1335916a12477652999e2d01cc","tests/test_round_trip.rs":"b47662e35be2729f28bacdbbea20f1879c111889430e735a7bcb5f2a5c0b9e5c","tests/test_shebang.rs":"f5772cadad5b56e3112cb16308b779f92bce1c3a48091fc9933deb2276a69331","tests/test_should_parse.rs":"1d3535698a446e2755bfc360676bdb161841a1f454cdef6e7556c6d06a95c89d","tests/test_size.rs":"697906d892ab8186eebdf6bc7696fde7a42376d50bee846ba69f031bdb847e01","tests/test_stmt.rs":"0601fc32131b5501dfcdc4b4248d46bf21e0a98a49eb19439e1a46869dfb30b7","tests/test_token_trees.rs":"43e56a701817e3c3bfd0cae54a457dd7a38ccb3ca19da41e2b995fdf20e6ed18","tests/test_ty.rs":"f71d7f7f1c038aaabea8dd4c03c0d5752c76d570f8b4885a81659825bbb4d576","tests/test_visibility.rs":"7456fcb3a6634db509748aededff9c2d8b242d511a3e5ee3022e40b232892704","tests/zzz_stable.rs":"2a862e59cb446235ed99aec0e6ada8e16d3ecc30229b29d825b7c0bbc2602989"},"package":"3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1"} \ No newline at end of file diff --git a/bash-5.1/vendor/syn/Cargo.toml b/bash-5.1/vendor/syn/Cargo.toml index d03ee2e..7b14125 100644 --- a/bash-5.1/vendor/syn/Cargo.toml +++ b/bash-5.1/vendor/syn/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.31" name = "syn" -version = "1.0.99" +version = "1.0.102" authors = ["David Tolnay <dtolnay@gmail.com>"] include = [ "/benches/**", @@ -72,7 +72,7 @@ required-features = [ ] [dependencies.proc-macro2] -version = "1.0.39" +version = "1.0.46" default-features = false [dependencies.quote] diff --git a/bash-5.1/vendor/syn/benches/file.rs b/bash-5.1/vendor/syn/benches/file.rs index c500dc2..bd4a247 100644 --- a/bash-5.1/vendor/syn/benches/file.rs +++ b/bash-5.1/vendor/syn/benches/file.rs @@ -1,4 +1,4 @@ -// $ cargo bench --features full --bench file +// $ cargo bench --features full,test --bench file #![feature(rustc_private, test)] #![recursion_limit = "1024"] diff --git a/bash-5.1/vendor/syn/benches/rust.rs b/bash-5.1/vendor/syn/benches/rust.rs index 5e4fba1..e3f8f55 100644 --- a/bash-5.1/vendor/syn/benches/rust.rs +++ b/bash-5.1/vendor/syn/benches/rust.rs @@ -1,7 +1,7 @@ -// $ cargo bench --features full --bench rust +// $ cargo bench --features full,test --bench rust // // Syn only, useful for profiling: -// $ RUSTFLAGS='--cfg syn_only' cargo build --release --features full --bench rust +// $ RUSTFLAGS='--cfg syn_only' cargo build --release --features full,test --bench rust #![cfg_attr(not(syn_only), feature(rustc_private))] #![recursion_limit = "1024"] @@ -46,7 +46,7 @@ mod librustc_parse { use rustc_data_structures::sync::Lrc; use rustc_error_messages::FluentBundle; - use rustc_errors::{emitter::Emitter, Diagnostic, Handler}; + use rustc_errors::{emitter::Emitter, translation::Translate, Diagnostic, Handler}; use rustc_session::parse::ParseSess; use rustc_span::source_map::{FilePathMapping, SourceMap}; use rustc_span::{edition::Edition, FileName}; @@ -59,6 +59,9 @@ mod librustc_parse { fn source_map(&self) -> Option<&Lrc<SourceMap>> { None } + } + + impl Translate for SilentEmitter { fn fluent_bundle(&self) -> Option<&Lrc<FluentBundle>> { None } @@ -88,7 +91,7 @@ mod librustc_parse { #[cfg(not(syn_only))] mod read_from_disk { pub fn bench(content: &str) -> Result<(), ()> { - let _ = content; + _ = content; Ok(()) } } diff --git a/bash-5.1/vendor/syn/src/buffer.rs b/bash-5.1/vendor/syn/src/buffer.rs index 2c8e21b..161b614 100644 --- a/bash-5.1/vendor/syn/src/buffer.rs +++ b/bash-5.1/vendor/syn/src/buffer.rs @@ -14,23 +14,18 @@ use crate::proc_macro as pm; use crate::Lifetime; use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; -use std::hint; use std::marker::PhantomData; -use std::mem; -use std::ptr; -use std::slice; /// Internal type which is used instead of `TokenTree` to represent a token tree /// within a `TokenBuffer`. enum Entry { // Mimicking types from proc-macro. - Group(Group, TokenBuffer), + // Group entries contain the offset to the matching End entry. + Group(Group, usize), Ident(Ident), Punct(Punct), Literal(Literal), - // End entries contain a raw pointer to the entry from the containing - // token tree, or null if this is the outermost level. - End(*const Entry), + End, } /// A buffer that can be efficiently traversed multiple times, unlike @@ -39,102 +34,29 @@ enum Entry { /// /// *This type is available only if Syn is built with the `"parsing"` feature.* pub struct TokenBuffer { - // NOTE: Do not implement clone on this - there are raw pointers inside - // these entries which will be messed up. Moving the `TokenBuffer` itself is - // safe as the data pointed to won't be moved. - ptr: *const Entry, - len: usize, -} - -impl Drop for TokenBuffer { - fn drop(&mut self) { - unsafe { - let slice = slice::from_raw_parts_mut(self.ptr as *mut Entry, self.len); - let _ = Box::from_raw(slice); - } - } + // NOTE: Do not implement clone on this - while the current design could be + // cloned, other designs which could be desirable may not be cloneable. + entries: Box<[Entry]>, } impl TokenBuffer { - // NOTE: Do not mutate the Vec returned from this function once it returns; - // the address of its backing memory must remain stable. - fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer { - let iterator = stream.into_iter(); - let mut entries = Vec::with_capacity(iterator.size_hint().0 + 1); - let mut next_index_after_last_group = 0; - for tt in iterator { + fn recursive_new(entries: &mut Vec<Entry>, stream: TokenStream) { + for tt in stream { match tt { - TokenTree::Ident(ident) => { - entries.push(Entry::Ident(ident)); - } - TokenTree::Punct(punct) => { - entries.push(Entry::Punct(punct)); - } - TokenTree::Literal(literal) => { - entries.push(Entry::Literal(literal)); - } + TokenTree::Ident(ident) => entries.push(Entry::Ident(ident)), + TokenTree::Punct(punct) => entries.push(Entry::Punct(punct)), + TokenTree::Literal(literal) => entries.push(Entry::Literal(literal)), TokenTree::Group(group) => { - // We cannot fill in a real `End` pointer until `entries` is - // finished growing and getting potentially reallocated. - // Instead, we temporarily coopt the spot where the end - // pointer would go, and use it to string together an - // intrusive linked list of all the Entry::Group entries in - // the vector. Later after `entries` is done growing, we'll - // traverse the linked list and fill in all the end - // pointers with a correct value. - let group_up = - ptr::null::<u8>().wrapping_add(next_index_after_last_group) as *const Entry; - - let inner = Self::inner_new(group.stream(), group_up); - entries.push(Entry::Group(group, inner)); - next_index_after_last_group = entries.len(); + let group_start_index = entries.len(); + entries.push(Entry::End); // we replace this below + Self::recursive_new(entries, group.stream()); + let group_end_index = entries.len(); + entries.push(Entry::End); + let group_end_offset = group_end_index - group_start_index; + entries[group_start_index] = Entry::Group(group, group_end_offset); } } } - - // Add an `End` entry to the end with a reference to the enclosing token - // stream which was passed in. - entries.push(Entry::End(up)); - - // NOTE: This is done to ensure that we don't accidentally modify the - // length of the backing buffer. The backing buffer must remain at a - // constant address after this point, as we are going to store a raw - // pointer into it. - let entries = entries.into_boxed_slice(); - let len = entries.len(); - - // Convert boxed slice into a pointer to the first element early, to - // avoid invalidating pointers into this slice when we move the Box. - // See https://github.com/rust-lang/unsafe-code-guidelines/issues/326 - let entries = Box::into_raw(entries) as *mut Entry; - - // Traverse intrusive linked list of Entry::Group entries and fill in - // correct End pointers. - while let Some(idx) = next_index_after_last_group.checked_sub(1) { - // We know that idx refers to one of the Entry::Group entries, and - // that the very last entry is an Entry::End, so the next index - // after any group entry is a valid index. - let group_up = unsafe { entries.add(next_index_after_last_group) }; - - // Linked list only takes us to entries which are of type Group. - let token_buffer = match unsafe { &*entries.add(idx) } { - Entry::Group(_group, token_buffer) => token_buffer, - _ => unsafe { hint::unreachable_unchecked() }, - }; - - // Last entry in any TokenBuffer is of type End. - let buffer_ptr = token_buffer.ptr as *mut Entry; - let last_entry = unsafe { &mut *buffer_ptr.add(token_buffer.len - 1) }; - let end_ptr_slot = match last_entry { - Entry::End(end_ptr_slot) => end_ptr_slot, - _ => unsafe { hint::unreachable_unchecked() }, - }; - - // Step to next element in linked list. - next_index_after_last_group = mem::replace(end_ptr_slot, group_up) as usize; - } - - TokenBuffer { ptr: entries, len } } /// Creates a `TokenBuffer` containing all the tokens from the input @@ -153,13 +75,19 @@ impl TokenBuffer { /// Creates a `TokenBuffer` containing all the tokens from the input /// `proc_macro2::TokenStream`. pub fn new2(stream: TokenStream) -> Self { - Self::inner_new(stream, ptr::null()) + let mut entries = Vec::new(); + Self::recursive_new(&mut entries, stream); + entries.push(Entry::End); + Self { + entries: entries.into_boxed_slice(), + } } /// Creates a cursor referencing the first token in the buffer and able to /// traverse until the end of the buffer. pub fn begin(&self) -> Cursor { - unsafe { Cursor::create(self.ptr, self.ptr.add(self.len - 1)) } + let ptr = self.entries.as_ptr(); + unsafe { Cursor::create(ptr, ptr.add(self.entries.len() - 1)) } } } @@ -179,7 +107,7 @@ impl TokenBuffer { pub struct Cursor<'a> { // The current entry which the `Cursor` is pointing at. ptr: *const Entry, - // This is the only `Entry::End(..)` object which this cursor is allowed to + // This is the only `Entry::End` object which this cursor is allowed to // point at. All other `End` objects are skipped over in `Cursor::create`. scope: *const Entry, // Cursor is covariant in 'a. This field ensures that our pointers are still @@ -199,7 +127,7 @@ impl<'a> Cursor<'a> { // object in global storage. struct UnsafeSyncEntry(Entry); unsafe impl Sync for UnsafeSyncEntry {} - static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry)); + static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End); Cursor { ptr: &EMPTY_ENTRY.0, @@ -212,15 +140,15 @@ impl<'a> Cursor<'a> { /// `None`-delimited scopes when the cursor reaches the end of them, /// allowing for them to be treated transparently. unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self { - // NOTE: If we're looking at a `End(..)`, we want to advance the cursor + // NOTE: If we're looking at a `End`, we want to advance the cursor // past it, unless `ptr == scope`, which means that we're at the edge of // our cursor's scope. We should only have `ptr != scope` at the exit // from None-delimited groups entered with `ignore_none`. - while let Entry::End(exit) = *ptr { + while let Entry::End = *ptr { if ptr == scope { break; } - ptr = exit; + ptr = ptr.add(1); } Cursor { @@ -238,7 +166,10 @@ impl<'a> Cursor<'a> { /// Bump the cursor to point at the next token after the current one. This /// is undefined behavior if the cursor is currently looking at an /// `Entry::End`. - unsafe fn bump(self) -> Cursor<'a> { + /// + /// If the cursor is looking at an `Entry::Group`, the bumped cursor will + /// point at the first token in the group (with the same scope end). + unsafe fn bump_ignore_group(self) -> Cursor<'a> { Cursor::create(self.ptr.offset(1), self.scope) } @@ -248,14 +179,9 @@ impl<'a> Cursor<'a> { /// /// WARNING: This mutates its argument. fn ignore_none(&mut self) { - while let Entry::Group(group, buf) = self.entry() { + while let Entry::Group(group, _) = self.entry() { if group.delimiter() == Delimiter::None { - // NOTE: We call `Cursor::create` here to make sure that - // situations where we should immediately exit the span after - // entering it are handled correctly. - unsafe { - *self = Cursor::create(buf.ptr, self.scope); - } + unsafe { *self = self.bump_ignore_group() }; } else { break; } @@ -279,9 +205,12 @@ impl<'a> Cursor<'a> { self.ignore_none(); } - if let Entry::Group(group, buf) = self.entry() { + if let Entry::Group(group, end_offset) = self.entry() { if group.delimiter() == delim { - return Some((buf.begin(), group.span(), unsafe { self.bump() })); + let end_of_group = unsafe { self.ptr.add(*end_offset) }; + let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; + let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; + return Some((inside_of_group, group.span(), after_group)); } } @@ -293,7 +222,7 @@ impl<'a> Cursor<'a> { pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> { self.ignore_none(); match self.entry() { - Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump() })), + Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump_ignore_group() })), _ => None, } } @@ -304,7 +233,7 @@ impl<'a> Cursor<'a> { self.ignore_none(); match self.entry() { Entry::Punct(punct) if punct.as_char() != '\'' => { - Some((punct.clone(), unsafe { self.bump() })) + Some((punct.clone(), unsafe { self.bump_ignore_group() })) } _ => None, } @@ -315,7 +244,7 @@ impl<'a> Cursor<'a> { pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> { self.ignore_none(); match self.entry() { - Entry::Literal(literal) => Some((literal.clone(), unsafe { self.bump() })), + Entry::Literal(literal) => Some((literal.clone(), unsafe { self.bump_ignore_group() })), _ => None, } } @@ -326,17 +255,13 @@ impl<'a> Cursor<'a> { self.ignore_none(); match self.entry() { Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => { - let next = unsafe { self.bump() }; - match next.ident() { - Some((ident, rest)) => { - let lifetime = Lifetime { - apostrophe: punct.span(), - ident, - }; - Some((lifetime, rest)) - } - None => None, - } + let next = unsafe { self.bump_ignore_group() }; + let (ident, rest) = next.ident()?; + let lifetime = Lifetime { + apostrophe: punct.span(), + ident, + }; + Some((lifetime, rest)) } _ => None, } @@ -362,15 +287,16 @@ impl<'a> Cursor<'a> { /// This method does not treat `None`-delimited groups as transparent, and /// will return a `Group(None, ..)` if the cursor is looking at one. pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> { - let tree = match self.entry() { - Entry::Group(group, _) => group.clone().into(), - Entry::Literal(literal) => literal.clone().into(), - Entry::Ident(ident) => ident.clone().into(), - Entry::Punct(punct) => punct.clone().into(), - Entry::End(..) => return None, + let (tree, len) = match self.entry() { + Entry::Group(group, end_offset) => (group.clone().into(), *end_offset), + Entry::Literal(literal) => (literal.clone().into(), 1), + Entry::Ident(ident) => (ident.clone().into(), 1), + Entry::Punct(punct) => (punct.clone().into(), 1), + Entry::End => return None, }; - Some((tree, unsafe { self.bump() })) + let rest = unsafe { Cursor::create(self.ptr.add(len), self.scope) }; + Some((tree, rest)) } /// Returns the `Span` of the current token, or `Span::call_site()` if this @@ -381,7 +307,7 @@ impl<'a> Cursor<'a> { Entry::Literal(literal) => literal.span(), Entry::Ident(ident) => ident.span(), Entry::Punct(punct) => punct.span(), - Entry::End(..) => Span::call_site(), + Entry::End => Span::call_site(), } } @@ -390,19 +316,22 @@ impl<'a> Cursor<'a> { /// /// This method treats `'lifetimes` as a single token. pub(crate) fn skip(self) -> Option<Cursor<'a>> { - match self.entry() { - Entry::End(..) => None, + let len = match self.entry() { + Entry::End => return None, // Treat lifetimes as a single tt for the purposes of 'skip'. Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => { - let next = unsafe { self.bump() }; - match next.entry() { - Entry::Ident(_) => Some(unsafe { next.bump() }), - _ => Some(next), + match unsafe { &*self.ptr.add(1) } { + Entry::Ident(_) => 2, + _ => 1, } } - _ => Some(unsafe { self.bump() }), - } + + Entry::Group(_, end_offset) => *end_offset, + _ => 1, + }; + + Some(unsafe { Cursor::create(self.ptr.add(len), self.scope) }) } } diff --git a/bash-5.1/vendor/syn/src/drops.rs b/bash-5.1/vendor/syn/src/drops.rs new file mode 100644 index 0000000..89b42d8 --- /dev/null +++ b/bash-5.1/vendor/syn/src/drops.rs @@ -0,0 +1,58 @@ +use std::iter; +use std::mem::ManuallyDrop; +use std::ops::{Deref, DerefMut}; +use std::option; +use std::slice; + +#[repr(transparent)] +pub(crate) struct NoDrop<T: ?Sized>(ManuallyDrop<T>); + +impl<T> NoDrop<T> { + pub(crate) fn new(value: T) -> Self + where + T: TrivialDrop, + { + NoDrop(ManuallyDrop::new(value)) + } +} + +impl<T: ?Sized> Deref for NoDrop<T> { + type Target = T; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<T: ?Sized> DerefMut for NoDrop<T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +pub(crate) trait TrivialDrop {} + +impl<T> TrivialDrop for iter::Empty<T> {} +impl<'a, T> TrivialDrop for slice::Iter<'a, T> {} +impl<'a, T> TrivialDrop for slice::IterMut<'a, T> {} +impl<'a, T> TrivialDrop for option::IntoIter<&'a T> {} +impl<'a, T> TrivialDrop for option::IntoIter<&'a mut T> {} + +#[test] +fn test_needs_drop() { + use std::mem::needs_drop; + + struct NeedsDrop; + + impl Drop for NeedsDrop { + fn drop(&mut self) {} + } + + assert!(needs_drop::<NeedsDrop>()); + + // Test each of the types with a handwritten TrivialDrop impl above. + assert!(!needs_drop::<iter::Empty<NeedsDrop>>()); + assert!(!needs_drop::<slice::Iter<NeedsDrop>>()); + assert!(!needs_drop::<slice::IterMut<NeedsDrop>>()); + assert!(!needs_drop::<option::IntoIter<&NeedsDrop>>()); + assert!(!needs_drop::<option::IntoIter<&mut NeedsDrop>>()); +} diff --git a/bash-5.1/vendor/syn/src/expr.rs b/bash-5.1/vendor/syn/src/expr.rs index cf0fa0a..93a59b0 100644 --- a/bash-5.1/vendor/syn/src/expr.rs +++ b/bash-5.1/vendor/syn/src/expr.rs @@ -1371,7 +1371,9 @@ pub(crate) mod parsing { }); } else if Precedence::Cast >= base && input.peek(Token![as]) { let as_token: Token![as] = input.parse()?; - let ty = input.call(Type::without_plus)?; + let allow_plus = false; + let allow_group_generic = false; + let ty = ty::parsing::ambig_ty(input, allow_plus, allow_group_generic)?; check_cast(input)?; lhs = Expr::Cast(ExprCast { attrs: Vec::new(), @@ -1381,7 +1383,9 @@ pub(crate) mod parsing { }); } else if Precedence::Cast >= base && input.peek(Token![:]) && !input.peek(Token![::]) { let colon_token: Token![:] = input.parse()?; - let ty = input.call(Type::without_plus)?; + let allow_plus = false; + let allow_group_generic = false; + let ty = ty::parsing::ambig_ty(input, allow_plus, allow_group_generic)?; check_cast(input)?; lhs = Expr::Type(ExprType { attrs: Vec::new(), @@ -1429,7 +1433,9 @@ pub(crate) mod parsing { }); } else if Precedence::Cast >= base && input.peek(Token![as]) { let as_token: Token![as] = input.parse()?; - let ty = input.call(Type::without_plus)?; + let allow_plus = false; + let allow_group_generic = false; + let ty = ty::parsing::ambig_ty(input, allow_plus, allow_group_generic)?; check_cast(input)?; lhs = Expr::Cast(ExprCast { attrs: Vec::new(), @@ -1727,7 +1733,10 @@ pub(crate) mod parsing { || input.peek(Token![move]) { expr_closure(input, allow_struct).map(Expr::Closure) - } else if input.peek(Token![for]) && input.peek2(Token![<]) && input.peek3(Lifetime) { + } else if input.peek(Token![for]) + && input.peek2(Token![<]) + && (input.peek3(Lifetime) || input.peek3(Token![>])) + { let begin = input.fork(); input.parse::<BoundLifetimes>()?; expr_closure(input, allow_struct)?; @@ -2010,7 +2019,9 @@ pub(crate) mod parsing { Expr::If(input.parse()?) } else if input.peek(Token![while]) { Expr::While(input.parse()?) - } else if input.peek(Token![for]) { + } else if input.peek(Token![for]) + && !(input.peek2(Token![<]) && (input.peek3(Lifetime) || input.peek3(Token![>]))) + { Expr::ForLoop(input.parse()?) } else if input.peek(Token![loop]) { Expr::Loop(input.parse()?) diff --git a/bash-5.1/vendor/syn/src/gen/clone.rs b/bash-5.1/vendor/syn/src/gen/clone.rs index 8de1cd8..a413e3e 100644 --- a/bash-5.1/vendor/syn/src/gen/clone.rs +++ b/bash-5.1/vendor/syn/src/gen/clone.rs @@ -910,9 +910,9 @@ impl Clone for GenericArgument { match self { GenericArgument::Lifetime(v0) => GenericArgument::Lifetime(v0.clone()), GenericArgument::Type(v0) => GenericArgument::Type(v0.clone()), + GenericArgument::Const(v0) => GenericArgument::Const(v0.clone()), GenericArgument::Binding(v0) => GenericArgument::Binding(v0.clone()), GenericArgument::Constraint(v0) => GenericArgument::Constraint(v0.clone()), - GenericArgument::Const(v0) => GenericArgument::Const(v0.clone()), } } } diff --git a/bash-5.1/vendor/syn/src/gen/debug.rs b/bash-5.1/vendor/syn/src/gen/debug.rs index 4adf8c5..a1f0afa 100644 --- a/bash-5.1/vendor/syn/src/gen/debug.rs +++ b/bash-5.1/vendor/syn/src/gen/debug.rs @@ -1268,6 +1268,11 @@ impl Debug for GenericArgument { formatter.field(v0); formatter.finish() } + GenericArgument::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } GenericArgument::Binding(v0) => { let mut formatter = formatter.debug_tuple("Binding"); formatter.field(v0); @@ -1278,11 +1283,6 @@ impl Debug for GenericArgument { formatter.field(v0); formatter.finish() } - GenericArgument::Const(v0) => { - let mut formatter = formatter.debug_tuple("Const"); - formatter.field(v0); - formatter.finish() - } } } } diff --git a/bash-5.1/vendor/syn/src/gen/eq.rs b/bash-5.1/vendor/syn/src/gen/eq.rs index 40fed0b..20acb80 100644 --- a/bash-5.1/vendor/syn/src/gen/eq.rs +++ b/bash-5.1/vendor/syn/src/gen/eq.rs @@ -878,13 +878,13 @@ impl PartialEq for GenericArgument { (GenericArgument::Type(self0), GenericArgument::Type(other0)) => { self0 == other0 } - (GenericArgument::Binding(self0), GenericArgument::Binding(other0)) => { + (GenericArgument::Const(self0), GenericArgument::Const(other0)) => { self0 == other0 } - (GenericArgument::Constraint(self0), GenericArgument::Constraint(other0)) => { + (GenericArgument::Binding(self0), GenericArgument::Binding(other0)) => { self0 == other0 } - (GenericArgument::Const(self0), GenericArgument::Const(other0)) => { + (GenericArgument::Constraint(self0), GenericArgument::Constraint(other0)) => { self0 == other0 } _ => false, diff --git a/bash-5.1/vendor/syn/src/gen/fold.rs b/bash-5.1/vendor/syn/src/gen/fold.rs index 6e19e6f..98bb579 100644 --- a/bash-5.1/vendor/syn/src/gen/fold.rs +++ b/bash-5.1/vendor/syn/src/gen/fold.rs @@ -1787,15 +1787,15 @@ where GenericArgument::Type(_binding_0) => { GenericArgument::Type(f.fold_type(_binding_0)) } + GenericArgument::Const(_binding_0) => { + GenericArgument::Const(f.fold_expr(_binding_0)) + } GenericArgument::Binding(_binding_0) => { GenericArgument::Binding(f.fold_binding(_binding_0)) } GenericArgument::Constraint(_binding_0) => { GenericArgument::Constraint(f.fold_constraint(_binding_0)) } - GenericArgument::Const(_binding_0) => { - GenericArgument::Const(f.fold_expr(_binding_0)) - } } } #[cfg(feature = "full")] diff --git a/bash-5.1/vendor/syn/src/gen/hash.rs b/bash-5.1/vendor/syn/src/gen/hash.rs index f68a763..d0400e1 100644 --- a/bash-5.1/vendor/syn/src/gen/hash.rs +++ b/bash-5.1/vendor/syn/src/gen/hash.rs @@ -1184,15 +1184,15 @@ impl Hash for GenericArgument { state.write_u8(1u8); v0.hash(state); } - GenericArgument::Binding(v0) => { + GenericArgument::Const(v0) => { state.write_u8(2u8); v0.hash(state); } - GenericArgument::Constraint(v0) => { + GenericArgument::Binding(v0) => { state.write_u8(3u8); v0.hash(state); } - GenericArgument::Const(v0) => { + GenericArgument::Constraint(v0) => { state.write_u8(4u8); v0.hash(state); } diff --git a/bash-5.1/vendor/syn/src/gen/visit.rs b/bash-5.1/vendor/syn/src/gen/visit.rs index 051b659..19ddd2e 100644 --- a/bash-5.1/vendor/syn/src/gen/visit.rs +++ b/bash-5.1/vendor/syn/src/gen/visit.rs @@ -1974,15 +1974,15 @@ where GenericArgument::Type(_binding_0) => { v.visit_type(_binding_0); } + GenericArgument::Const(_binding_0) => { + v.visit_expr(_binding_0); + } GenericArgument::Binding(_binding_0) => { v.visit_binding(_binding_0); } GenericArgument::Constraint(_binding_0) => { v.visit_constraint(_binding_0); } - GenericArgument::Const(_binding_0) => { - v.visit_expr(_binding_0); - } } } #[cfg(feature = "full")] diff --git a/bash-5.1/vendor/syn/src/gen/visit_mut.rs b/bash-5.1/vendor/syn/src/gen/visit_mut.rs index 3ddbe9c..239709d 100644 --- a/bash-5.1/vendor/syn/src/gen/visit_mut.rs +++ b/bash-5.1/vendor/syn/src/gen/visit_mut.rs @@ -1975,15 +1975,15 @@ where GenericArgument::Type(_binding_0) => { v.visit_type_mut(_binding_0); } + GenericArgument::Const(_binding_0) => { + v.visit_expr_mut(_binding_0); + } GenericArgument::Binding(_binding_0) => { v.visit_binding_mut(_binding_0); } GenericArgument::Constraint(_binding_0) => { v.visit_constraint_mut(_binding_0); } - GenericArgument::Const(_binding_0) => { - v.visit_expr_mut(_binding_0); - } } } #[cfg(feature = "full")] diff --git a/bash-5.1/vendor/syn/src/item.rs b/bash-5.1/vendor/syn/src/item.rs index 1ce970e..a1ef7ab 100644 --- a/bash-5.1/vendor/syn/src/item.rs +++ b/bash-5.1/vendor/syn/src/item.rs @@ -2765,7 +2765,6 @@ mod printing { use super::*; use crate::attr::FilterAttrs; use crate::print::TokensOrDefault; - use crate::punctuated::Pair; use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; @@ -3283,16 +3282,9 @@ mod printing { self.generics.to_tokens(tokens); self.paren_token.surround(tokens, |tokens| { let mut last_is_variadic = false; - for input in self.inputs.pairs() { - match input { - Pair::Punctuated(input, comma) => { - maybe_variadic_to_tokens(input, tokens); - comma.to_tokens(tokens); - } - Pair::End(input) => { - last_is_variadic = maybe_variadic_to_tokens(input, tokens); - } - } + for pair in self.inputs.pairs() { + last_is_variadic = maybe_variadic_to_tokens(pair.value(), tokens); + pair.punct().to_tokens(tokens); } if self.variadic.is_some() && !last_is_variadic { if !self.inputs.empty_or_trailing() { diff --git a/bash-5.1/vendor/syn/src/lib.rs b/bash-5.1/vendor/syn/src/lib.rs index 09addd3..81f03e1 100644 --- a/bash-5.1/vendor/syn/src/lib.rs +++ b/bash-5.1/vendor/syn/src/lib.rs @@ -250,10 +250,11 @@ //! dynamic library libproc_macro from rustc toolchain. // Syn types in rustdoc of other crates get linked to here. -#![doc(html_root_url = "https://docs.rs/syn/1.0.99")] +#![doc(html_root_url = "https://docs.rs/syn/1.0.102")] #![cfg_attr(doc_cfg, feature(doc_cfg))] #![allow(non_camel_case_types)] #![allow( + clippy::bool_to_int_with_if, clippy::cast_lossless, clippy::cast_possible_truncation, clippy::cast_ptr_alignment, @@ -812,14 +813,6 @@ mod print; //////////////////////////////////////////////////////////////////////////////// -// https://github.com/rust-lang/rust/issues/62830 -#[cfg(feature = "parsing")] -mod rustdoc_workaround { - pub use crate::parse::{self as parse_module}; -} - -//////////////////////////////////////////////////////////////////////////////// - mod error; pub use crate::error::{Error, Result}; diff --git a/bash-5.1/vendor/syn/src/lit.rs b/bash-5.1/vendor/syn/src/lit.rs index 2600dc8..130b40e 100644 --- a/bash-5.1/vendor/syn/src/lit.rs +++ b/bash-5.1/vendor/syn/src/lit.rs @@ -224,7 +224,7 @@ impl LitStr { // Parse string literal into a token stream with every span equal to the // original literal's span. - let mut tokens = crate::parse_str(&self.value())?; + let mut tokens = TokenStream::from_str(&self.value())?; tokens = respan_token_stream(tokens, self.span()); parser.parse2(tokens) diff --git a/bash-5.1/vendor/syn/src/parse_macro_input.rs b/bash-5.1/vendor/syn/src/parse_macro_input.rs index 8e1a5ec..6163cd7 100644 --- a/bash-5.1/vendor/syn/src/parse_macro_input.rs +++ b/bash-5.1/vendor/syn/src/parse_macro_input.rs @@ -4,7 +4,7 @@ /// Refer to the [`parse` module] documentation for more details about parsing /// in Syn. /// -/// [`parse` module]: crate::rustdoc_workaround::parse_module +/// [`parse` module]: mod@crate::parse /// /// <br> /// @@ -51,7 +51,7 @@ /// This macro can also be used with the [`Parser` trait] for types that have /// multiple ways that they can be parsed. /// -/// [`Parser` trait]: crate::rustdoc_workaround::parse_module::Parser +/// [`Parser` trait]: crate::parse::Parser /// /// ``` /// # extern crate proc_macro; diff --git a/bash-5.1/vendor/syn/src/pat.rs b/bash-5.1/vendor/syn/src/pat.rs index fa0818c..b279186 100644 --- a/bash-5.1/vendor/syn/src/pat.rs +++ b/bash-5.1/vendor/syn/src/pat.rs @@ -400,11 +400,11 @@ pub mod parsing { } if input.peek(token::Brace) { - let pat = pat_struct(input, path)?; + let pat = pat_struct(begin.fork(), input, path)?; if qself.is_some() { Ok(Pat::Verbatim(verbatim::between(begin, input))) } else { - Ok(Pat::Struct(pat)) + Ok(pat) } } else if input.peek(token::Paren) { let pat = pat_tuple_struct(input, path)?; @@ -465,13 +465,23 @@ pub mod parsing { }) } - fn pat_struct(input: ParseStream, path: Path) -> Result<PatStruct> { + fn pat_struct(begin: ParseBuffer, input: ParseStream, path: Path) -> Result<Pat> { let content; let brace_token = braced!(content in input); let mut fields = Punctuated::new(); - while !content.is_empty() && !content.peek(Token![..]) { - let value = content.call(field_pat)?; + let mut dot2_token = None; + while !content.is_empty() { + let attrs = content.call(Attribute::parse_outer)?; + if content.peek(Token![..]) { + dot2_token = Some(content.parse()?); + if !attrs.is_empty() { + return Ok(Pat::Verbatim(verbatim::between(begin, input))); + } + break; + } + let mut value = content.call(field_pat)?; + value.attrs = attrs; fields.push_value(value); if content.is_empty() { break; @@ -480,19 +490,13 @@ pub mod parsing { fields.push_punct(punct); } - let dot2_token = if fields.empty_or_trailing() && content.peek(Token![..]) { - Some(content.parse()?) - } else { - None - }; - - Ok(PatStruct { + Ok(Pat::Struct(PatStruct { attrs: Vec::new(), path, brace_token, fields, dot2_token, - }) + })) } impl Member { @@ -505,7 +509,6 @@ pub mod parsing { } fn field_pat(input: ParseStream) -> Result<FieldPat> { - let attrs = input.call(Attribute::parse_outer)?; let boxed: Option<Token![box]> = input.parse()?; let by_ref: Option<Token![ref]> = input.parse()?; let mutability: Option<Token![mut]> = input.parse()?; @@ -515,7 +518,7 @@ pub mod parsing { || member.is_unnamed() { return Ok(FieldPat { - attrs, + attrs: Vec::new(), member, colon_token: input.parse()?, pat: Box::new(multi_pat_with_leading_vert(input)?), @@ -544,7 +547,7 @@ pub mod parsing { } Ok(FieldPat { - attrs, + attrs: Vec::new(), member: Member::Named(ident), colon_token: None, pat: Box::new(pat), diff --git a/bash-5.1/vendor/syn/src/path.rs b/bash-5.1/vendor/syn/src/path.rs index 00be352..742273a 100644 --- a/bash-5.1/vendor/syn/src/path.rs +++ b/bash-5.1/vendor/syn/src/path.rs @@ -109,16 +109,16 @@ ast_enum! { Lifetime(Lifetime), /// A type argument. Type(Type), - /// A binding (equality constraint) on an associated type: the `Item = - /// u8` in `Iterator<Item = u8>`. - Binding(Binding), - /// An associated type bound: `Iterator<Item: Display>`. - Constraint(Constraint), /// A const expression. Must be inside of a block. /// /// NOTE: Identity expressions are represented as Type arguments, as /// they are indistinguishable syntactically. Const(Expr), + /// A binding (equality constraint) on an associated type: the `Item = + /// u8` in `Iterator<Item = u8>`. + Binding(Binding), + /// An associated type bound: `Iterator<Item: Display>`. + Constraint(Constraint), } } @@ -729,8 +729,6 @@ pub(crate) mod printing { match self { GenericArgument::Lifetime(lt) => lt.to_tokens(tokens), GenericArgument::Type(ty) => ty.to_tokens(tokens), - GenericArgument::Binding(tb) => tb.to_tokens(tokens), - GenericArgument::Constraint(tc) => tc.to_tokens(tokens), GenericArgument::Const(e) => match *e { Expr::Lit(_) => e.to_tokens(tokens), @@ -746,6 +744,8 @@ pub(crate) mod printing { e.to_tokens(tokens); }), }, + GenericArgument::Binding(tb) => tb.to_tokens(tokens), + GenericArgument::Constraint(tc) => tc.to_tokens(tokens), } } } @@ -756,11 +756,8 @@ pub(crate) mod printing { self.colon2_token.to_tokens(tokens); self.lt_token.to_tokens(tokens); - // Print lifetimes before types and consts, all before bindings, - // regardless of their order in self.args. - // - // TODO: ordering rules for const arguments vs type arguments have - // not been settled yet. https://github.com/rust-lang/rust/issues/44580 + // Print lifetimes before types/consts/bindings, regardless of their + // order in self.args. let mut trailing_or_empty = true; for param in self.args.pairs() { match **param.value() { @@ -769,37 +766,24 @@ pub(crate) mod printing { trailing_or_empty = param.punct().is_some(); } GenericArgument::Type(_) - | GenericArgument::Binding(_) - | GenericArgument::Constraint(_) - | GenericArgument::Const(_) => {} - } - } - for param in self.args.pairs() { - match **param.value() { - GenericArgument::Type(_) | GenericArgument::Const(_) => { - if !trailing_or_empty { - <Token![,]>::default().to_tokens(tokens); - } - param.to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); - } - GenericArgument::Lifetime(_) + | GenericArgument::Const(_) | GenericArgument::Binding(_) | GenericArgument::Constraint(_) => {} } } for param in self.args.pairs() { match **param.value() { - GenericArgument::Binding(_) | GenericArgument::Constraint(_) => { + GenericArgument::Type(_) + | GenericArgument::Const(_) + | GenericArgument::Binding(_) + | GenericArgument::Constraint(_) => { if !trailing_or_empty { <Token![,]>::default().to_tokens(tokens); } param.to_tokens(tokens); trailing_or_empty = param.punct().is_some(); } - GenericArgument::Lifetime(_) - | GenericArgument::Type(_) - | GenericArgument::Const(_) => {} + GenericArgument::Lifetime(_) => {} } } diff --git a/bash-5.1/vendor/syn/src/stmt.rs b/bash-5.1/vendor/syn/src/stmt.rs index 3e2c71b..58bd013 100644 --- a/bash-5.1/vendor/syn/src/stmt.rs +++ b/bash-5.1/vendor/syn/src/stmt.rs @@ -175,7 +175,11 @@ pub mod parsing { || input.peek(Token![crate]) && !input.peek2(Token![::]) || input.peek(Token![extern]) || input.peek(Token![use]) - || input.peek(Token![static]) && (input.peek2(Token![mut]) || input.peek2(Ident)) + || input.peek(Token![static]) + && (input.peek2(Token![mut]) + || input.peek2(Ident) + && !(input.peek2(Token![async]) + && (input.peek3(Token![move]) || input.peek3(Token![|])))) || input.peek(Token![const]) && !input.peek2(token::Brace) || input.peek(Token![unsafe]) && !input.peek2(token::Brace) || input.peek(Token![async]) diff --git a/bash-5.1/vendor/syn/src/ty.rs b/bash-5.1/vendor/syn/src/ty.rs index 0f1341f..4068be3 100644 --- a/bash-5.1/vendor/syn/src/ty.rs +++ b/bash-5.1/vendor/syn/src/ty.rs @@ -343,7 +343,8 @@ pub mod parsing { impl Parse for Type { fn parse(input: ParseStream) -> Result<Self> { let allow_plus = true; - ambig_ty(input, allow_plus) + let allow_group_generic = true; + ambig_ty(input, allow_plus, allow_group_generic) } } @@ -356,11 +357,16 @@ pub mod parsing { #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn without_plus(input: ParseStream) -> Result<Self> { let allow_plus = false; - ambig_ty(input, allow_plus) + let allow_group_generic = true; + ambig_ty(input, allow_plus, allow_group_generic) } } - fn ambig_ty(input: ParseStream, allow_plus: bool) -> Result<Type> { + pub(crate) fn ambig_ty( + input: ParseStream, + allow_plus: bool, + allow_group_generic: bool, + ) -> Result<Type> { let begin = input.fork(); if input.peek(token::Group) { @@ -381,7 +387,9 @@ pub mod parsing { path: Path::parse_helper(input, false)?, })); } - } else if input.peek(Token![<]) || input.peek(Token![::]) && input.peek3(Token![<]) { + } else if input.peek(Token![<]) && allow_group_generic + || input.peek(Token![::]) && input.peek3(Token![<]) + { if let Type::Path(mut ty) = *group.elem { let arguments = &mut ty.path.segments.last_mut().unwrap().arguments; if let PathArguments::None = arguments { @@ -537,9 +545,15 @@ pub mod parsing { || lookahead.peek(Token![::]) || lookahead.peek(Token![<]) { - if input.peek(Token![dyn]) { - let trait_object = TypeTraitObject::parse(input, allow_plus)?; - return Ok(Type::TraitObject(trait_object)); + let dyn_token: Option<Token![dyn]> = input.parse()?; + if dyn_token.is_some() { + let star_token: Option<Token![*]> = input.parse()?; + let bounds = TypeTraitObject::parse_bounds(input, allow_plus)?; + return Ok(if star_token.is_some() { + Type::Verbatim(verbatim::between(begin, input)) + } else { + Type::TraitObject(TypeTraitObject { dyn_token, bounds }) + }); } let ty: TypePath = input.parse()?; @@ -819,15 +833,28 @@ pub mod parsing { #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypePath { fn parse(input: ParseStream) -> Result<Self> { - let (qself, mut path) = path::parsing::qpath(input, false)?; + let expr_style = false; + let (qself, mut path) = path::parsing::qpath(input, expr_style)?; - if path.segments.last().unwrap().arguments.is_empty() + while path.segments.last().unwrap().arguments.is_empty() && (input.peek(token::Paren) || input.peek(Token![::]) && input.peek3(token::Paren)) { input.parse::<Option<Token![::]>>()?; let args: ParenthesizedGenericArguments = input.parse()?; + let allow_associated_type = cfg!(feature = "full") + && match &args.output { + ReturnType::Default => true, + ReturnType::Type(_, ty) => match **ty { + // TODO: probably some of the other kinds allow this too. + Type::Paren(_) => true, + _ => false, + }, + }; let parenthesized = PathArguments::Parenthesized(args); path.segments.last_mut().unwrap().arguments = parenthesized; + if allow_associated_type { + Path::parse_rest(input, &mut path, expr_style)?; + } } Ok(TypePath { qself, path }) @@ -844,7 +871,8 @@ pub mod parsing { pub(crate) fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> { if input.peek(Token![->]) { let arrow = input.parse()?; - let ty = ambig_ty(input, allow_plus)?; + let allow_group_generic = true; + let ty = ambig_ty(input, allow_plus, allow_group_generic)?; Ok(ReturnType::Type(arrow, Box::new(ty))) } else { Ok(ReturnType::Default) @@ -967,7 +995,10 @@ pub mod parsing { let content; Ok(TypeParen { paren_token: parenthesized!(content in input), - elem: Box::new(ambig_ty(&content, allow_plus)?), + elem: Box::new({ + let allow_group_generic = true; + ambig_ty(&content, allow_plus, allow_group_generic)? + }), }) } } diff --git a/bash-5.1/vendor/syn/tests/common/eq.rs b/bash-5.1/vendor/syn/tests/common/eq.rs index ff100aa..a531462 100644 --- a/bash-5.1/vendor/syn/tests/common/eq.rs +++ b/bash-5.1/vendor/syn/tests/common/eq.rs @@ -3,6 +3,7 @@ extern crate rustc_ast; extern crate rustc_data_structures; extern crate rustc_span; +extern crate thin_vec; use rustc_ast::ast::AngleBracketedArg; use rustc_ast::ast::AngleBracketedArgs; @@ -19,10 +20,11 @@ use rustc_ast::ast::AttrStyle; use rustc_ast::ast::Attribute; use rustc_ast::ast::BareFnTy; use rustc_ast::ast::BinOpKind; -use rustc_ast::ast::BindingMode; +use rustc_ast::ast::BindingAnnotation; use rustc_ast::ast::Block; use rustc_ast::ast::BlockCheckMode; use rustc_ast::ast::BorrowKind; +use rustc_ast::ast::ByRef; use rustc_ast::ast::CaptureBy; use rustc_ast::ast::ClosureBinder; use rustc_ast::ast::Const; @@ -82,6 +84,7 @@ use rustc_ast::ast::Movability; use rustc_ast::ast::MutTy; use rustc_ast::ast::Mutability; use rustc_ast::ast::NodeId; +use rustc_ast::ast::NormalAttr; use rustc_ast::ast::Param; use rustc_ast::ast::ParenthesizedArgs; use rustc_ast::ast::Pat; @@ -127,14 +130,14 @@ use rustc_ast::ast::WhereRegionPredicate; use rustc_ast::ptr::P; use rustc_ast::token::{self, CommentKind, Delimiter, Nonterminal, Token, TokenKind}; use rustc_ast::tokenstream::{ - AttrAnnotatedTokenStream, AttrAnnotatedTokenTree, AttributesData, DelimSpan, LazyTokenStream, - Spacing, TokenStream, TokenTree, + AttrTokenStream, AttrTokenTree, AttributesData, DelimSpan, LazyAttrTokenStream, Spacing, + TokenStream, TokenTree, }; use rustc_data_structures::sync::Lrc; -use rustc_data_structures::thin_vec::ThinVec; use rustc_span::source_map::Spanned; use rustc_span::symbol::{sym, Ident}; use rustc_span::{Span, Symbol, SyntaxContext, DUMMY_SP}; +use thin_vec::ThinVec; pub trait SpanlessEq { fn eq(&self, other: &Self) -> bool; @@ -401,11 +404,12 @@ spanless_eq_struct!(AngleBracketedArgs; span args); spanless_eq_struct!(AnonConst; id value); spanless_eq_struct!(Arm; attrs pat guard body span id is_placeholder); spanless_eq_struct!(AssocConstraint; id ident gen_args kind span); -spanless_eq_struct!(AttrAnnotatedTokenStream; 0); spanless_eq_struct!(AttrItem; path args tokens); +spanless_eq_struct!(AttrTokenStream; 0); spanless_eq_struct!(Attribute; kind id style span); spanless_eq_struct!(AttributesData; attrs tokens); spanless_eq_struct!(BareFnTy; unsafety ext generic_params decl decl_span); +spanless_eq_struct!(BindingAnnotation; 0 1); spanless_eq_struct!(Block; stmts id rules span tokens could_be_bare_literal); spanless_eq_struct!(Crate; attrs items spans id is_placeholder); spanless_eq_struct!(EnumDef; variants); @@ -425,13 +429,14 @@ spanless_eq_struct!(InlineAsmSym; id qself path); spanless_eq_struct!(Item<K>; attrs id span vis ident kind !tokens); spanless_eq_struct!(Label; ident); spanless_eq_struct!(Lifetime; id ident); -spanless_eq_struct!(Lit; token kind span); +spanless_eq_struct!(Lit; token_lit kind span); spanless_eq_struct!(Local; pat ty kind id span attrs !tokens); spanless_eq_struct!(MacCall; path args prior_type_ascription); spanless_eq_struct!(MacCallStmt; mac style attrs tokens); spanless_eq_struct!(MacroDef; body macro_rules); spanless_eq_struct!(ModSpans; !inner_span !inject_use_span); spanless_eq_struct!(MutTy; ty mutbl); +spanless_eq_struct!(NormalAttr; item tokens); spanless_eq_struct!(ParenthesizedArgs; span inputs inputs_span output); spanless_eq_struct!(Pat; id kind span tokens); spanless_eq_struct!(PatField; ident pat is_shorthand attrs id span is_placeholder); @@ -453,19 +458,19 @@ spanless_eq_struct!(Variant; attrs id span !vis ident data disr_expr is_placehol spanless_eq_struct!(Visibility; kind span tokens); spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds); spanless_eq_struct!(WhereClause; has_where_token predicates span); -spanless_eq_struct!(WhereEqPredicate; id span lhs_ty rhs_ty); +spanless_eq_struct!(WhereEqPredicate; span lhs_ty rhs_ty); spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds); spanless_eq_struct!(token::Lit; kind symbol suffix); spanless_eq_enum!(AngleBracketedArg; Arg(0) Constraint(0)); spanless_eq_enum!(AssocItemKind; Const(0 1 2) Fn(0) TyAlias(0) MacCall(0)); spanless_eq_enum!(AssocConstraintKind; Equality(term) Bound(bounds)); spanless_eq_enum!(Async; Yes(span closure_id return_impl_trait_id) No); -spanless_eq_enum!(AttrAnnotatedTokenTree; Token(0) Delimited(0 1 2) Attributes(0)); spanless_eq_enum!(AttrStyle; Outer Inner); +spanless_eq_enum!(AttrTokenTree; Token(0 1) Delimited(0 1 2) Attributes(0)); spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt); -spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0)); spanless_eq_enum!(BlockCheckMode; Default Unsafe(0)); spanless_eq_enum!(BorrowKind; Ref Raw); +spanless_eq_enum!(ByRef; Yes No); spanless_eq_enum!(CaptureBy; Value Ref); spanless_eq_enum!(ClosureBinder; NotPresent For(span generic_params)); spanless_eq_enum!(Const; Yes(0) No); @@ -502,22 +507,23 @@ spanless_eq_enum!(StructRest; Base(0) Rest(0) None); spanless_eq_enum!(Term; Ty(0) Const(0)); spanless_eq_enum!(TokenTree; Token(0 1) Delimited(0 1 2)); spanless_eq_enum!(TraitBoundModifier; None Maybe MaybeConst MaybeConstMaybe); -spanless_eq_enum!(TraitObjectSyntax; Dyn None); +spanless_eq_enum!(TraitObjectSyntax; Dyn DynStar None); spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128); spanless_eq_enum!(UnOp; Deref Not Neg); spanless_eq_enum!(Unsafe; Yes(0) No); spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided); spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob); spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0)); -spanless_eq_enum!(VisibilityKind; Public Restricted(path id) Inherited); +spanless_eq_enum!(VisibilityKind; Public Restricted(path id shorthand) Inherited); spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0)); spanless_eq_enum!(ExprKind; Box(0) Array(0) ConstBlock(0) Call(0 1) - MethodCall(0 1 2) Tup(0) Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1) - Let(0 1 2) If(0 1 2) While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1) - Closure(0 1 2 3 4 5 6) Block(0 1) Async(0 1 2) Await(0) TryBlock(0) - Assign(0 1 2) AssignOp(0 1 2) Field(0 1) Index(0 1) Underscore Range(0 1 2) - Path(0 1) AddrOf(0 1 2) Break(0 1) Continue(0) Ret(0) InlineAsm(0) - MacCall(0) Struct(0) Repeat(0 1) Paren(0) Try(0) Yield(0) Yeet(0) Err); + MethodCall(0 1 2 3) Tup(0) Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) + Type(0 1) Let(0 1 2) If(0 1 2) While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) + Match(0 1) Closure(0 1 2 3 4 5 6) Block(0 1) Async(0 1 2) Await(0) + TryBlock(0) Assign(0 1 2) AssignOp(0 1 2) Field(0 1) Index(0 1) Underscore + Range(0 1 2) Path(0 1) AddrOf(0 1 2) Break(0 1) Continue(0) Ret(0) + InlineAsm(0) MacCall(0) Struct(0) Repeat(0 1) Paren(0) Try(0) Yield(0) + Yeet(0) Err); spanless_eq_enum!(InlineAsmOperand; In(reg expr) Out(reg late expr) InOut(reg late expr) SplitInOut(reg late in_expr out_expr) Const(anon_const) Sym(sym)); @@ -525,7 +531,7 @@ spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1 2) Fn(0) Mod(0 1) ForeignMod(0) GlobalAsm(0) TyAlias(0) Enum(0 1) Struct(0 1) Union(0 1) Trait(0) TraitAlias(0 1) Impl(0) MacCall(0) MacroDef(0)); spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1) - Float(0 1) Bool(0) Err(0)); + Float(0 1) Bool(0) Err); spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2 3) TupleStruct(0 1 2) Or(0) Path(0 1) Tuple(0) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest Paren(0) MacCall(0)); @@ -691,7 +697,7 @@ fn is_escaped_literal_token(token: &Token, unescaped: Symbol) -> bool { Token { kind: TokenKind::Literal(lit), span: _, - } => match Lit::from_lit_token(*lit, DUMMY_SP) { + } => match Lit::from_token_lit(*lit, DUMMY_SP) { Ok(lit) => is_escaped_literal(&lit, unescaped), Err(_) => false, }, @@ -722,7 +728,7 @@ fn is_escaped_literal_macro_arg(arg: &MacArgsEq, unescaped: Symbol) -> bool { fn is_escaped_literal(lit: &Lit, unescaped: Symbol) -> bool { match lit { Lit { - token: + token_lit: token::Lit { kind: token::LitKind::Str, symbol: _, @@ -735,10 +741,10 @@ fn is_escaped_literal(lit: &Lit, unescaped: Symbol) -> bool { } } -impl SpanlessEq for LazyTokenStream { +impl SpanlessEq for LazyAttrTokenStream { fn eq(&self, other: &Self) -> bool { - let this = self.create_token_stream(); - let other = other.create_token_stream(); + let this = self.to_attr_token_stream(); + let other = other.to_attr_token_stream(); SpanlessEq::eq(&this, &other) } } @@ -746,26 +752,26 @@ impl SpanlessEq for LazyTokenStream { impl SpanlessEq for AttrKind { fn eq(&self, other: &Self) -> bool { match (self, other) { - (AttrKind::Normal(item, tokens), AttrKind::Normal(item2, tokens2)) => { - SpanlessEq::eq(item, item2) && SpanlessEq::eq(tokens, tokens2) + (AttrKind::Normal(normal), AttrKind::Normal(normal2)) => { + SpanlessEq::eq(normal, normal2) } (AttrKind::DocComment(kind, symbol), AttrKind::DocComment(kind2, symbol2)) => { SpanlessEq::eq(kind, kind2) && SpanlessEq::eq(symbol, symbol2) } - (AttrKind::DocComment(kind, unescaped), AttrKind::Normal(item2, _tokens)) => { + (AttrKind::DocComment(kind, unescaped), AttrKind::Normal(normal2)) => { match kind { CommentKind::Line | CommentKind::Block => {} } let path = Path::from_ident(Ident::with_dummy_span(sym::doc)); - SpanlessEq::eq(&path, &item2.path) - && match &item2.args { + SpanlessEq::eq(&path, &normal2.item.path) + && match &normal2.item.args { MacArgs::Empty | MacArgs::Delimited(..) => false, MacArgs::Eq(_span, token) => { is_escaped_literal_macro_arg(token, *unescaped) } } } - (AttrKind::Normal(..), AttrKind::DocComment(..)) => SpanlessEq::eq(other, self), + (AttrKind::Normal(_), AttrKind::DocComment(..)) => SpanlessEq::eq(other, self), } } } diff --git a/bash-5.1/vendor/syn/tests/regression/issue1108.rs b/bash-5.1/vendor/syn/tests/regression/issue1108.rs index 11a82ad..4fd30c0 100644 --- a/bash-5.1/vendor/syn/tests/regression/issue1108.rs +++ b/bash-5.1/vendor/syn/tests/regression/issue1108.rs @@ -1,5 +1,5 @@ #[test] fn issue1108() { let data = "impl<x<>>::x for"; - let _ = syn::parse_file(data); + _ = syn::parse_file(data); } diff --git a/bash-5.1/vendor/syn/tests/regression/issue1235.rs b/bash-5.1/vendor/syn/tests/regression/issue1235.rs new file mode 100644 index 0000000..8836030 --- /dev/null +++ b/bash-5.1/vendor/syn/tests/regression/issue1235.rs @@ -0,0 +1,32 @@ +use proc_macro2::{Delimiter, Group}; +use quote::quote; + +#[test] +fn main() { + // Okay. Rustc allows top-level `static` with no value syntactically, but + // not semantically. Syn parses as Item::Verbatim. + let tokens = quote! { + pub static FOO: usize; + pub static BAR: usize; + }; + let file = syn::parse2::<syn::File>(tokens).unwrap(); + println!("{:#?}", file); + + // Okay. + let inner = Group::new( + Delimiter::None, + quote!(static FOO: usize = 0; pub static BAR: usize = 0), + ); + let tokens = quote!(pub #inner;); + let file = syn::parse2::<syn::File>(tokens).unwrap(); + println!("{:#?}", file); + + // Formerly parser crash. + let inner = Group::new( + Delimiter::None, + quote!(static FOO: usize; pub static BAR: usize), + ); + let tokens = quote!(pub #inner;); + let file = syn::parse2::<syn::File>(tokens).unwrap(); + println!("{:#?}", file); +} diff --git a/bash-5.1/vendor/syn/tests/repo/mod.rs b/bash-5.1/vendor/syn/tests/repo/mod.rs index 0bafe67..4c7be85 100644 --- a/bash-5.1/vendor/syn/tests/repo/mod.rs +++ b/bash-5.1/vendor/syn/tests/repo/mod.rs @@ -10,10 +10,10 @@ use std::path::Path; use tar::Archive; use walkdir::DirEntry; -const REVISION: &str = "ee160f2f5e73b6f5954bc33f059c316d9e8582c4"; +const REVISION: &str = "98ad6a5519651af36e246c0335c964dd52c554ba"; #[rustfmt::skip] -static EXCLUDE: &[&str] = &[ +static EXCLUDE_FILES: &[&str] = &[ // TODO: impl ~const T {} // https://github.com/dtolnay/syn/issues/1051 "src/test/ui/rfc-2632-const-trait-impl/syntax.rs", @@ -33,6 +33,21 @@ static EXCLUDE: &[&str] = &[ "src/tools/rustfmt/tests/source/trait.rs", "src/tools/rustfmt/tests/target/trait.rs", + // Various extensions to Rust syntax made up by rust-analyzer + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0012_type_item_where_clause.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0040_crate_keyword_vis.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0131_existential_type.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0179_use_tree_abs_star.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0188_const_param_default_path.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0015_use_tree.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0029_range_forms.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0051_parameter_attrs.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0055_dot_dot_dot.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0068_item_modifiers.rs", + "src/tools/rust-analyzer/crates/syntax/test_data/parser/validation/0031_block_inner_attrs.rs", + "src/tools/rust-analyzer/crates/syntax/test_data/parser/validation/0045_ambiguous_trait_object.rs", + "src/tools/rust-analyzer/crates/syntax/test_data/parser/validation/0046_mutable_const_item.rs", + // Placeholder syntax for "throw expressions" "src/test/pretty/yeet-expr.rs", "src/test/ui/try-trait/yeet-for-option.rs", @@ -41,7 +56,9 @@ static EXCLUDE: &[&str] = &[ // Excessive nesting "src/test/ui/issues/issue-74564-if-expr-stack-overflow.rs", - // Testing rustfmt on invalid syntax + // Testing tools on invalid syntax + "src/test/run-make/translation/test.rs", + "src/test/ui/generics/issue-94432-garbage-ice.rs", "src/tools/rustfmt/tests/coverage/target/comments.rs", "src/tools/rustfmt/tests/parser/issue-4126/invalid.rs", "src/tools/rustfmt/tests/parser/issue_4418.rs", @@ -54,8 +71,8 @@ static EXCLUDE: &[&str] = &[ "src/tools/rustfmt/tests/target/configs/spaces_around_ranges/true.rs", "src/tools/rustfmt/tests/target/type.rs", - // Testing compiler diagnostic localization on invalid syntax - "src/test/run-make/translation/basic-translation.rs", + // Generated file containing a top-level expression, used with `include!` + "compiler/rustc_codegen_gcc/src/intrinsic/archs.rs", // Clippy lint lists represented as expressions "src/tools/clippy/clippy_lints/src/lib.deprecated.rs", @@ -73,9 +90,6 @@ static EXCLUDE: &[&str] = &[ "src/tools/clippy/clippy_lints/src/lib.register_suspicious.rs", // Not actually test cases - "src/test/rustdoc-ui/test-compile-fail2.rs", - "src/test/rustdoc-ui/test-compile-fail3.rs", - "src/test/ui/json-bom-plus-crlf-multifile-aux.rs", "src/test/ui/lint/expansion-time-include.rs", "src/test/ui/macros/auxiliary/macro-comma-support.rs", "src/test/ui/macros/auxiliary/macro-include-items-expr.rs", @@ -84,38 +98,52 @@ static EXCLUDE: &[&str] = &[ "src/test/ui/parser/issues/auxiliary/issue-21146-inc.rs", ]; +#[rustfmt::skip] +static EXCLUDE_DIRS: &[&str] = &[ + // Inputs that intentionally do not parse + "src/tools/rust-analyzer/crates/parser/test_data/parser/err", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/err", + + // Inputs that lex but do not necessarily parse + "src/tools/rust-analyzer/crates/parser/test_data/lexer", + + // Inputs that used to crash rust-analyzer, but aren't necessarily supposed to parse + "src/tools/rust-analyzer/crates/syntax/test_data/parser/fuzz-failures", + "src/tools/rust-analyzer/crates/syntax/test_data/reparse/fuzz-failures", +]; + pub fn base_dir_filter(entry: &DirEntry) -> bool { let path = entry.path(); - if path.is_dir() { - return true; // otherwise walkdir does not visit the files - } - if path.extension().map_or(true, |e| e != "rs") { - return false; - } let mut path_string = path.to_string_lossy(); if cfg!(windows) { path_string = path_string.replace('\\', "/").into(); } - let path = if let Some(path) = path_string.strip_prefix("tests/rust/") { + let path_string = if path_string == "tests/rust" { + return true; + } else if let Some(path) = path_string.strip_prefix("tests/rust/") { path } else { panic!("unexpected path in Rust dist: {}", path_string); }; - if path.starts_with("src/test/compile-fail") || path.starts_with("src/test/rustfix") { + if path.is_dir() { + return !EXCLUDE_DIRS.contains(&path_string); + } + + if path.extension().map_or(true, |e| e != "rs") { return false; } - if path.starts_with("src/test/ui") { - let stderr_path = entry.path().with_extension("stderr"); + if path_string.starts_with("src/test/ui") || path_string.starts_with("src/test/rustdoc-ui") { + let stderr_path = path.with_extension("stderr"); if stderr_path.exists() { // Expected to fail in some way return false; } } - !EXCLUDE.contains(&path) + !EXCLUDE_FILES.contains(&path_string) } #[allow(dead_code)] @@ -137,10 +165,17 @@ pub fn clone_rust() { } let mut missing = String::new(); let test_src = Path::new("tests/rust"); - for exclude in EXCLUDE { - if !test_src.join(exclude).exists() { + for exclude in EXCLUDE_FILES { + if !test_src.join(exclude).is_file() { + missing += "\ntests/rust/"; + missing += exclude; + } + } + for exclude in EXCLUDE_DIRS { + if !test_src.join(exclude).is_dir() { missing += "\ntests/rust/"; missing += exclude; + missing += "/"; } } if !missing.is_empty() { diff --git a/bash-5.1/vendor/syn/tests/test_parse_stream.rs b/bash-5.1/vendor/syn/tests/test_parse_stream.rs index 76bd065..cc14fa0 100644 --- a/bash-5.1/vendor/syn/tests/test_parse_stream.rs +++ b/bash-5.1/vendor/syn/tests/test_parse_stream.rs @@ -4,9 +4,9 @@ use syn::{Ident, Token}; #[test] fn test_peek() { - let _ = |input: ParseStream| { - let _ = input.peek(Ident); - let _ = input.peek(Ident::peek_any); - let _ = input.peek(Token![::]); + _ = |input: ParseStream| { + _ = input.peek(Ident); + _ = input.peek(Ident::peek_any); + _ = input.peek(Token![::]); }; } diff --git a/bash-5.1/vendor/syn/tests/test_precedence.rs b/bash-5.1/vendor/syn/tests/test_precedence.rs index bd273a5..dbcd74f 100644 --- a/bash-5.1/vendor/syn/tests/test_precedence.rs +++ b/bash-5.1/vendor/syn/tests/test_precedence.rs @@ -24,6 +24,7 @@ extern crate rustc_ast; extern crate rustc_data_structures; extern crate rustc_span; +extern crate thin_vec; use crate::common::eq::SpanlessEq; use crate::common::parse; @@ -207,10 +208,10 @@ fn librustc_brackets(mut librustc_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { }; use rustc_ast::mut_visit::{noop_visit_generic_arg, noop_visit_local, MutVisitor}; use rustc_data_structures::map_in_place::MapInPlace; - use rustc_data_structures::thin_vec::ThinVec; use rustc_span::DUMMY_SP; use std::mem; use std::ops::DerefMut; + use thin_vec::ThinVec; struct BracketsVisitor { failed: bool, @@ -243,7 +244,7 @@ fn librustc_brackets(mut librustc_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { } fn noop_visit_expr<T: MutVisitor>(e: &mut Expr, vis: &mut T) { - use rustc_ast::mut_visit::{noop_visit_expr, visit_thin_attrs}; + use rustc_ast::mut_visit::{noop_visit_expr, visit_attrs}; match &mut e.kind { ExprKind::AddrOf(BorrowKind::Raw, ..) => {} ExprKind::Struct(expr) => { @@ -261,7 +262,7 @@ fn librustc_brackets(mut librustc_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { } vis.visit_id(&mut e.id); vis.visit_span(&mut e.span); - visit_thin_attrs(&mut e.attrs, vis); + visit_attrs(&mut e.attrs, vis); } _ => noop_visit_expr(e, vis), } @@ -322,15 +323,15 @@ fn librustc_brackets(mut librustc_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { // types yet. We'll look into comparing those in the future. For now // focus on expressions appearing in other places. fn visit_pat(&mut self, pat: &mut P<Pat>) { - let _ = pat; + _ = pat; } fn visit_ty(&mut self, ty: &mut P<Ty>) { - let _ = ty; + _ = ty; } fn visit_attribute(&mut self, attr: &mut Attribute) { - let _ = attr; + _ = attr; } } @@ -426,7 +427,7 @@ fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr { fn collect_exprs(file: syn::File) -> Vec<syn::Expr> { use syn::fold::Fold; use syn::punctuated::Punctuated; - use syn::{token, Expr, ExprTuple, Path}; + use syn::{token, ConstParam, Expr, ExprTuple, Path}; struct CollectExprs(Vec<Expr>); impl Fold for CollectExprs { @@ -447,6 +448,10 @@ fn collect_exprs(file: syn::File) -> Vec<syn::Expr> { // Skip traversing into const generic path arguments path } + + fn fold_const_param(&mut self, const_param: ConstParam) -> ConstParam { + const_param + } } let mut folder = CollectExprs(vec![]); diff --git a/bash-5.1/vendor/syn/tests/test_size.rs b/bash-5.1/vendor/syn/tests/test_size.rs index e172df2..02b0700 100644 --- a/bash-5.1/vendor/syn/tests/test_size.rs +++ b/bash-5.1/vendor/syn/tests/test_size.rs @@ -5,17 +5,17 @@ use syn::{Expr, Item, Lit, Pat, Type}; #[test] fn test_expr_size() { - assert_eq!(mem::size_of::<Expr>(), 280); + assert_eq!(mem::size_of::<Expr>(), 264); } #[test] fn test_item_size() { - assert_eq!(mem::size_of::<Item>(), 344); + assert_eq!(mem::size_of::<Item>(), 320); } #[test] fn test_type_size() { - assert_eq!(mem::size_of::<Type>(), 304); + assert_eq!(mem::size_of::<Type>(), 280); } #[test] @@ -25,5 +25,5 @@ fn test_pat_size() { #[test] fn test_lit_size() { - assert_eq!(mem::size_of::<Lit>(), 40); + assert_eq!(mem::size_of::<Lit>(), 32); } diff --git a/bash-5.1/vendor/syntex/.cargo-checksum.json b/bash-5.1/vendor/syntex/.cargo-checksum.json new file mode 100644 index 0000000..6e94e23 --- /dev/null +++ b/bash-5.1/vendor/syntex/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"cfa0e51c2177698edca724439fda05af5bbf0013d26b805d22c5b26f8b61348a","src/error.rs":"c99d5582e76ca9f9b06989517e866d0078834b3db3d4e51b3b193cae06b55526","src/lib.rs":"1679bbd38be948783e508648cf075fe27174ed2e717efa80609befcf6d772f55","src/registry.rs":"6d8a40c82f274a2d4fb413ef1f29b2c540c436051933e5b81cb488c34623d4b9","src/resolver.rs":"c01be55f360ee1d55f5ff001f05623a318175a7b8cf2c21a2eab9610c2f5f61e","src/stack.rs":"130dc7ff3851288a0e8e701f69af99f8f52f203a1419976d09ebc0075abe97e7"},"package":"bb3f52553a966675982404dc34028291b347e0c9a9c0b0b34f2da6be8a0443f8"} \ No newline at end of file diff --git a/bash-5.1/vendor/syntex/Cargo.toml b/bash-5.1/vendor/syntex/Cargo.toml new file mode 100644 index 0000000..15a9219 --- /dev/null +++ b/bash-5.1/vendor/syntex/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "syntex" +version = "0.54.0" +authors = [ "erick.tryzelaar@gmail.com" ] +license = "MIT/Apache-2.0" +description = "A library that enables compile time syntax extension expansion" +repository = "https://github.com/erickt/rust-syntex" +readme = "../README.md" +include = ["Cargo.toml", "src/**/*.rs"] + +[dependencies] +syntex_errors = { version = "^0.54.0", path = "../syntex_errors" } +syntex_syntax = { version = "^0.54.0", path = "../syntex_syntax" } diff --git a/bash-5.1/vendor/syntex/src/error.rs b/bash-5.1/vendor/syntex/src/error.rs new file mode 100644 index 0000000..9d9292f --- /dev/null +++ b/bash-5.1/vendor/syntex/src/error.rs @@ -0,0 +1,46 @@ +use std::error; +use std::fmt; +use std::io; + +use errors::DiagnosticBuilder; + +#[derive(Debug)] +pub enum Error { + Parse, + Expand, + Io(io::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Parse | Error::Expand => { + write!(f, "{}", error::Error::description(self)) + } + Error::Io(ref err) => err.fmt(f), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Parse => "failed to parse input", + Error::Expand => "failed to expand input", + Error::Io(ref err) => err.description(), + } + } +} + +impl From<io::Error> for Error { + fn from(err: io::Error) -> Self { + Error::Io(err) + } +} + +impl<'a> From<DiagnosticBuilder<'a>> for Error { + fn from(mut diagnostic: DiagnosticBuilder<'a>) -> Self { + diagnostic.emit(); + Error::Parse + } +} diff --git a/bash-5.1/vendor/syntex/src/lib.rs b/bash-5.1/vendor/syntex/src/lib.rs new file mode 100644 index 0000000..18f4ff6 --- /dev/null +++ b/bash-5.1/vendor/syntex/src/lib.rs @@ -0,0 +1,11 @@ +extern crate syntex_syntax; +extern crate syntex_errors as errors; + +mod error; +mod registry; +mod resolver; +mod stack; + +pub use error::Error; +pub use registry::{Registry, Pass}; +pub use stack::with_extra_stack; diff --git a/bash-5.1/vendor/syntex/src/registry.rs b/bash-5.1/vendor/syntex/src/registry.rs new file mode 100644 index 0000000..a33f19c --- /dev/null +++ b/bash-5.1/vendor/syntex/src/registry.rs @@ -0,0 +1,234 @@ +use std::fs::File; +use std::io::Write; +use std::path::Path; +use std::rc::Rc; + +use syntex_syntax::ast; +use syntex_syntax::attr; +use syntex_syntax::codemap::DUMMY_SP; +use syntex_syntax::ext::base::{ + ExtCtxt, + IdentMacroExpander, + MultiItemDecorator, + MultiItemModifier, + NamedSyntaxExtension, + Resolver, + SyntaxExtension, + TTMacroExpander, +}; +use syntex_syntax::ext::expand; +use syntex_syntax::feature_gate; +use syntex_syntax::parse; +use syntex_syntax::print::pprust; +use syntex_syntax::symbol::Symbol; + +use super::resolver; +use super::error::Error; + +pub type Pass = fn(ast::Crate) -> ast::Crate; + +pub struct Registry { + syntax_exts: Vec<NamedSyntaxExtension>, + pre_expansion_passes: Vec<Box<Pass>>, + post_expansion_passes: Vec<Box<Pass>>, + cfg: Vec<ast::MetaItem>, + attrs: Vec<ast::Attribute>, +} + +impl Registry { + pub fn new() -> Registry { + Registry { + syntax_exts: Vec::new(), + pre_expansion_passes: Vec::new(), + post_expansion_passes: Vec::new(), + cfg: Vec::new(), + attrs: Vec::new(), + } + } + + pub fn add_cfg(&mut self, cfg: &str) { + let parse_sess = parse::ParseSess::new(); + let meta_item = parse::parse_meta_from_source_str( + "cfgspec".to_string(), + cfg.to_string(), + &parse_sess).unwrap(); + + self.cfg.push(meta_item); + } + + pub fn add_attr(&mut self, attr: &str) { + let parse_sess = parse::ParseSess::new(); + let meta_item = parse::parse_meta_from_source_str( + "attrspec".to_string(), + attr.to_string(), + &parse_sess).unwrap(); + + self.attrs.push(ast::Attribute { + id: attr::mk_attr_id(), + style: ast::AttrStyle::Outer, + value: meta_item, + is_sugared_doc: false, + span: DUMMY_SP, + }); + } + + pub fn add_macro<F>(&mut self, name: &str, extension: F) + where F: TTMacroExpander + 'static + { + let name = Symbol::intern(name); + let syntax_extension = SyntaxExtension::NormalTT( + Box::new(extension), + None, + false + ); + self.syntax_exts.push((name, syntax_extension)); + } + + pub fn add_ident_macro<F>(&mut self, name: &str, extension: F) + where F: IdentMacroExpander + 'static + { + let name = Symbol::intern(name); + let syntax_extension = SyntaxExtension::IdentTT( + Box::new(extension), + None, + false + ); + self.syntax_exts.push((name, syntax_extension)); + } + + pub fn add_decorator<F>(&mut self, name: &str, extension: F) + where F: MultiItemDecorator + 'static + { + let name = Symbol::intern(name); + let syntax_extension = SyntaxExtension::MultiDecorator(Box::new(extension)); + self.syntax_exts.push((name, syntax_extension)); + } + + pub fn add_modifier<F>(&mut self, name: &str, extension: F) + where F: MultiItemModifier + 'static + { + let name = Symbol::intern(name); + let syntax_extension = SyntaxExtension::MultiModifier(Box::new(extension)); + self.syntax_exts.push((name, syntax_extension)); + } + + pub fn add_pre_expansion_pass(&mut self, pass: Pass) { + self.pre_expansion_passes.push(Box::new(pass)) + } + + pub fn add_post_expansion_pass(&mut self, pass: Pass) { + self.post_expansion_passes.push(Box::new(pass)) + } + + pub fn expand<S, D>(self, crate_name: &str, src: S, dst: D) -> Result<(), Error> + where S: AsRef<Path>, + D: AsRef<Path>, + { + let src = src.as_ref(); + let dst = dst.as_ref(); + + let sess = parse::ParseSess::new(); + + let krate = try!(parse::parse_crate_from_file( + src, + &sess)); + + if sess.span_diagnostic.has_errors() { + return Err(Error::Parse); + } + + let src_name = src.to_str().unwrap().to_string(); + + let out = try!(self.expand_crate( + crate_name, + &sess, + src_name, + krate)); + + if sess.span_diagnostic.has_errors() { + return Err(Error::Expand); + } + + let mut dst = try!(File::create(dst)); + try!(dst.write_all(&out)); + Ok(()) + } + + /// This method will expand all macros in the source string `src`, and return the results in a + /// string. + pub fn expand_str(self, + crate_name: &str, + src_name: &str, + src: &str) -> Result<String, Error> { + let sess = parse::ParseSess::new(); + + let src_name = src_name.to_owned(); + + let krate = try!(parse::parse_crate_from_source_str( + src_name.clone(), + src.to_owned(), + &sess)); + + let out = try!(self.expand_crate(crate_name, &sess, src_name, krate)); + + Ok(String::from_utf8(out).unwrap()) + } + + fn expand_crate(self, + crate_name: &str, + sess: &parse::ParseSess, + src_name: String, + mut krate: ast::Crate) -> Result<Vec<u8>, Error> { + krate.attrs.extend(self.attrs.iter().cloned()); + + let features = feature_gate::get_features( + &sess.span_diagnostic, + &krate.attrs); + + let krate = self.pre_expansion_passes.iter() + .fold(krate, |krate, f| (f)(krate)); + + let mut ecfg = expand::ExpansionConfig::default(crate_name.to_owned()); + ecfg.features = Some(&features); + ecfg.keep_macs = true; + + let mut resolver = resolver::Resolver::new(sess); + + for (name, ext) in self.syntax_exts { + let ident = ast::Ident::with_empty_ctxt(name); + resolver.add_ext(ident, Rc::new(ext)); + } + + let mut ecx = ExtCtxt::new(&sess, ecfg, &mut resolver); + let krate = ecx.monotonic_expander().expand_crate(krate); + + let krate = self.post_expansion_passes.iter() + .fold(krate, |krate, f| (f)(krate)); + + let src = sess.codemap() + .get_filemap(&src_name) + .unwrap() + .src + .as_ref() + .unwrap() + .as_bytes() + .to_vec(); + + let mut rdr = &src[..]; + + let mut out = Vec::new(); + let annotation = pprust::NoAnn; + + try!(pprust::print_crate( + sess.codemap(), + &sess.span_diagnostic, + &krate, + src_name, + &mut rdr, + Box::new(&mut out), + &annotation, + false)); + + Ok(out) + } +} diff --git a/bash-5.1/vendor/syntex/src/resolver.rs b/bash-5.1/vendor/syntex/src/resolver.rs new file mode 100644 index 0000000..e246a3b --- /dev/null +++ b/bash-5.1/vendor/syntex/src/resolver.rs @@ -0,0 +1,92 @@ +use std::collections::HashMap; +use std::rc::Rc; + +use syntex_syntax::ast::{self, Attribute, Name}; +use syntex_syntax::ext::base::{ + self, + Determinacy, + MultiDecorator, + MultiModifier, + SyntaxExtension, +}; +use syntex_syntax::ext::expand::Expansion; +use syntex_syntax::ext::hygiene::Mark; +use syntex_syntax::parse::ParseSess; +use syntex_syntax::ptr::P; + +pub struct Resolver<'a> { + session: &'a ParseSess, + extensions: HashMap<ast::Name, Rc<SyntaxExtension>>, +} + +impl<'a> Resolver<'a> { + pub fn new(session: &'a ParseSess) -> Self { + Resolver { + session: session, + extensions: HashMap::new(), + } + } +} + +impl<'a> base::Resolver for Resolver<'a> { + fn next_node_id(&mut self) -> ast::NodeId { + ast::DUMMY_NODE_ID + } + fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() } + fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item } + fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false } + + fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion) {} + fn add_ext(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>) { + self.extensions.insert(ident.name, ext); + } + fn add_expansions_at_stmt(&mut self, _id: ast::NodeId, _macros: Vec<Mark>) {} + + fn resolve_imports(&mut self) {} + fn find_attr_invoc(&mut self, attrs: &mut Vec<Attribute>) -> Option<Attribute> { + for i in 0..attrs.len() { + if let Some(ext) = self.extensions.get(&attrs[i].value.name) { + match **ext { + MultiModifier(..) | MultiDecorator(..) => return Some(attrs.remove(i)), + _ => {} + } + } + } + None + } + fn find_extension(&mut self, _scope: Mark, name: ast::Name) -> Option<Rc<SyntaxExtension>> { + self.extensions.get(&name).map(|ext| ext.clone()) + } + fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, force: bool) + -> Result<Rc<SyntaxExtension>, Determinacy> { + let ast::Path { ref segments, span } = *path; + if segments.iter().any(|segment| segment.parameters.is_some()) { + let kind = + if segments.last().unwrap().parameters.is_some() { "macro" } else { "module" }; + let msg = format!("type parameters are not allowed on {}s", kind); + self.session.span_diagnostic.span_err(path.span, &msg); + return Err(Determinacy::Determined); + } + + let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect(); + + if path.len() > 1 { + // FIXME(syntex): Pass macros with module separators through to the generated source. + self.session.span_diagnostic.span_err(span, "expected macro name without module separators"); + return Err(Determinacy::Determined); + } + + let name = path[0].name; + + self.find_extension(scope, name).ok_or_else(|| { + if force { + let mut err = + self.session.span_diagnostic.struct_span_err(span, &format!("macro undefined: '{}!'", name)); + err.emit(); + Determinacy::Determined + } else { + Determinacy::Undetermined + } + }) + } +} diff --git a/bash-5.1/vendor/syntex/src/stack.rs b/bash-5.1/vendor/syntex/src/stack.rs new file mode 100644 index 0000000..2d96a6a --- /dev/null +++ b/bash-5.1/vendor/syntex/src/stack.rs @@ -0,0 +1,63 @@ +use std::env; +use std::ffi::OsStr; +use std::ops::Drop; +use std::thread; + +const STACK_ENV_VAR: &'static str = "RUST_MIN_STACK"; +const EXTRA_STACK: &'static str = "16777216"; // 16 MB + +/// Runs a function in a thread with extra stack space (16 MB or +/// `$RUST_MIN_STACK` if set). +/// +/// The Rust parser uses a lot of stack space so codegen sometimes requires more +/// than is available by default. +/// +/// ```rust,ignore +/// syntex::with_extra_stack(move || { +/// let mut reg = syntex::Registry::new(); +/// reg.add_decorator(/* ... */); +/// reg.expand("", src, dst) +/// }) +/// ``` +/// +/// This function runs with a 16 MB stack by default but a different value can +/// be set by the RUST_MIN_STACK environment variable. +pub fn with_extra_stack<F, T>(f: F) -> T + where F: Send + 'static + FnOnce() -> T, + T: Send + 'static +{ + let _tmp_env = set_if_unset(STACK_ENV_VAR, EXTRA_STACK); + + thread::spawn(f).join().unwrap() +} + +fn set_if_unset<K, V>(k: K, v: V) -> TmpEnv<K> + where K: AsRef<OsStr>, + V: AsRef<OsStr>, +{ + match env::var(&k) { + Ok(_) => TmpEnv::WasAlreadySet, + Err(_) => { + env::set_var(&k, v); + TmpEnv::WasNotSet(k) + } + } +} + +#[must_use] +enum TmpEnv<K> + where K: AsRef<OsStr>, +{ + WasAlreadySet, + WasNotSet(K), +} + +impl<K> Drop for TmpEnv<K> + where K: AsRef<OsStr>, +{ + fn drop(&mut self) { + if let TmpEnv::WasNotSet(ref k) = *self { + env::remove_var(k); + } + } +} diff --git a/bash-5.1/vendor/syntex_errors/.cargo-checksum.json b/bash-5.1/vendor/syntex_errors/.cargo-checksum.json new file mode 100644 index 0000000..f265811 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"3442bb8acc6f060590055401c2ed655933cf3006df7a7a7c4ce04bd4034ca4cf","src/diagnostic.rs":"c469bbeb9bc0bff1dc7da90f12fbf686de53b7920e8a8ec509171d7ee7939f9e","src/diagnostic_builder.rs":"535a903c0961e85d8ad9eb88a08e3095fbc251c6f032f84cb48a1f1d36c1b716","src/emitter.rs":"393b6dec613e03a9e248c0245248a17f3836750d6ef4591334fd4474b94416eb","src/lib.rs":"33d43a964af5efd3ec43bd44a8fe07db70db349f7247baf966cf7e46c95695e5","src/lock.rs":"77e185b48b20509596d9778d7dcca02b92e09be061ed57a9ef37ccfb9fa781ae","src/registry.rs":"ab229b7c6d3016917638d15e754df421be8f4b88b95518773c5c33a07a005274","src/snippet.rs":"436f7a9d20d39de14ae84c3d368d23a59c3436b63b6298578728a16b20143190","src/styled_buffer.rs":"a00d37a0c57b0c16cafa28dff936c1689e0d64a0002570b731f9f34a8ecdc61c"},"package":"dee2f6e49c075f71332bb775219d5982bee6732d26227fa1ae1b53cdb12f5cc5"} \ No newline at end of file diff --git a/bash-5.1/vendor/syntex_errors/Cargo.toml b/bash-5.1/vendor/syntex_errors/Cargo.toml new file mode 100644 index 0000000..76eb75b --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "syntex_errors" +version = "0.54.0" +authors = [ "erick.tryzelaar@gmail.com" ] +license = "MIT/Apache-2.0" +description = "Export of librustc_errors for code generation" +repository = "https://github.com/serde-rs/syntex" +include = ["Cargo.toml", "src/**/*.rs"] + +[dependencies] +libc = "^0.2.13" +log = "^0.3.3" +rustc-serialize = "^0.3.16" +syntex_pos = { version = "^0.54.0", path = "../syntex_pos" } +term = "^0.4.4" +unicode-xid = "^0.0.4" diff --git a/bash-5.1/vendor/syntex_errors/src/diagnostic.rs b/bash-5.1/vendor/syntex_errors/src/diagnostic.rs new file mode 100644 index 0000000..730ca8f --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/diagnostic.rs @@ -0,0 +1,202 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use CodeSuggestion; +use Level; +use RenderSpan; +use RenderSpan::Suggestion; +use std::fmt; +use syntax_pos::{MultiSpan, Span}; + +#[must_use] +#[derive(Clone, Debug, PartialEq)] +pub struct Diagnostic { + pub level: Level, + pub message: String, + pub code: Option<String>, + pub span: MultiSpan, + pub children: Vec<SubDiagnostic>, +} + +/// For example a note attached to an error. +#[derive(Clone, Debug, PartialEq)] +pub struct SubDiagnostic { + pub level: Level, + pub message: String, + pub span: MultiSpan, + pub render_span: Option<RenderSpan>, +} + +impl Diagnostic { + pub fn new(level: Level, message: &str) -> Self { + Diagnostic::new_with_code(level, None, message) + } + + pub fn new_with_code(level: Level, code: Option<String>, message: &str) -> Self { + Diagnostic { + level: level, + message: message.to_owned(), + code: code, + span: MultiSpan::new(), + children: vec![], + } + } + + /// Cancel the diagnostic (a structured diagnostic must either be emitted or + /// cancelled or it will panic when dropped). + /// BEWARE: if this DiagnosticBuilder is an error, then creating it will + /// bump the error count on the Handler and cancelling it won't undo that. + /// If you want to decrement the error count you should use `Handler::cancel`. + pub fn cancel(&mut self) { + self.level = Level::Cancelled; + } + + pub fn cancelled(&self) -> bool { + self.level == Level::Cancelled + } + + pub fn is_fatal(&self) -> bool { + self.level == Level::Fatal + } + + /// Add a span/label to be included in the resulting snippet. + /// This is pushed onto the `MultiSpan` that was created when the + /// diagnostic was first built. If you don't call this function at + /// all, and you just supplied a `Span` to create the diagnostic, + /// then the snippet will just include that `Span`, which is + /// called the primary span. + pub fn span_label(&mut self, span: Span, label: &fmt::Display) + -> &mut Self { + self.span.push_span_label(span, format!("{}", label)); + self + } + + pub fn note_expected_found(&mut self, + label: &fmt::Display, + expected: &fmt::Display, + found: &fmt::Display) + -> &mut Self + { + self.note_expected_found_extra(label, expected, found, &"", &"") + } + + pub fn note_expected_found_extra(&mut self, + label: &fmt::Display, + expected: &fmt::Display, + found: &fmt::Display, + expected_extra: &fmt::Display, + found_extra: &fmt::Display) + -> &mut Self + { + // For now, just attach these as notes + self.note(&format!("expected {} `{}`{}", label, expected, expected_extra)); + self.note(&format!(" found {} `{}`{}", label, found, found_extra)); + self + } + + pub fn note(&mut self, msg: &str) -> &mut Self { + self.sub(Level::Note, msg, MultiSpan::new(), None); + self + } + + pub fn span_note<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str) + -> &mut Self { + self.sub(Level::Note, msg, sp.into(), None); + self + } + + pub fn warn(&mut self, msg: &str) -> &mut Self { + self.sub(Level::Warning, msg, MultiSpan::new(), None); + self + } + + pub fn span_warn<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str) + -> &mut Self { + self.sub(Level::Warning, msg, sp.into(), None); + self + } + + pub fn help(&mut self , msg: &str) -> &mut Self { + self.sub(Level::Help, msg, MultiSpan::new(), None); + self + } + + pub fn span_help<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str) + -> &mut Self { + self.sub(Level::Help, msg, sp.into(), None); + self + } + + /// Prints out a message with a suggested edit of the code. + /// + /// See `diagnostic::RenderSpan::Suggestion` for more information. + pub fn span_suggestion<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str, + suggestion: String) + -> &mut Self { + self.sub(Level::Help, + msg, + MultiSpan::new(), + Some(Suggestion(CodeSuggestion { + msp: sp.into(), + substitutes: vec![suggestion], + }))); + self + } + + pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self { + self.span = sp.into(); + self + } + + pub fn code(&mut self, s: String) -> &mut Self { + self.code = Some(s); + self + } + + pub fn message(&self) -> &str { + &self.message + } + + pub fn level(&self) -> Level { + self.level + } + + /// Used by a lint. Copies over all details *but* the "main + /// message". + pub fn copy_details_not_message(&mut self, from: &Diagnostic) { + self.span = from.span.clone(); + self.code = from.code.clone(); + self.children.extend(from.children.iter().cloned()) + } + + /// Convenience function for internal use, clients should use one of the + /// public methods above. + fn sub(&mut self, + level: Level, + message: &str, + span: MultiSpan, + render_span: Option<RenderSpan>) { + let sub = SubDiagnostic { + level: level, + message: message.to_owned(), + span: span, + render_span: render_span, + }; + self.children.push(sub); + } +} diff --git a/bash-5.1/vendor/syntex_errors/src/diagnostic_builder.rs b/bash-5.1/vendor/syntex_errors/src/diagnostic_builder.rs new file mode 100644 index 0000000..7dfea6b --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/diagnostic_builder.rs @@ -0,0 +1,196 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use Diagnostic; +use Level; +use Handler; +use std::fmt::{self, Debug}; +use std::ops::{Deref, DerefMut}; +use std::thread::panicking; +use syntax_pos::{MultiSpan, Span}; + +/// Used for emitting structured error messages and other diagnostic information. +#[must_use] +#[derive(Clone)] +pub struct DiagnosticBuilder<'a> { + handler: &'a Handler, + diagnostic: Diagnostic, +} + +/// In general, the `DiagnosticBuilder` uses deref to allow access to +/// the fields and methods of the embedded `diagnostic` in a +/// transparent way. *However,* many of the methods are intended to +/// be used in a chained way, and hence ought to return `self`. In +/// that case, we can't just naively forward to the method on the +/// `diagnostic`, because the return type would be a `&Diagnostic` +/// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes +/// it easy to declare such methods on the builder. +macro_rules! forward { + // Forward pattern for &self -> &Self + (pub fn $n:ident(&self, $($name:ident: $ty:ty),*) -> &Self) => { + pub fn $n(&self, $($name: $ty),*) -> &Self { + self.diagnostic.$n($($name),*); + self + } + }; + + // Forward pattern for &mut self -> &mut Self + (pub fn $n:ident(&mut self, $($name:ident: $ty:ty),*) -> &mut Self) => { + pub fn $n(&mut self, $($name: $ty),*) -> &mut Self { + self.diagnostic.$n($($name),*); + self + } + }; + + // Forward pattern for &mut self -> &mut Self, with S: Into<MultiSpan> + // type parameter. No obvious way to make this more generic. + (pub fn $n:ident<S: Into<MultiSpan>>(&mut self, $($name:ident: $ty:ty),*) -> &mut Self) => { + pub fn $n<S: Into<MultiSpan>>(&mut self, $($name: $ty),*) -> &mut Self { + self.diagnostic.$n($($name),*); + self + } + }; +} + +impl<'a> Deref for DiagnosticBuilder<'a> { + type Target = Diagnostic; + + fn deref(&self) -> &Diagnostic { + &self.diagnostic + } +} + +impl<'a> DerefMut for DiagnosticBuilder<'a> { + fn deref_mut(&mut self) -> &mut Diagnostic { + &mut self.diagnostic + } +} + +impl<'a> DiagnosticBuilder<'a> { + /// Emit the diagnostic. + pub fn emit(&mut self) { + if self.cancelled() { + return; + } + + match self.level { + Level::Bug | + Level::Fatal | + Level::PhaseFatal | + Level::Error => { + self.handler.bump_err_count(); + } + + Level::Warning | + Level::Note | + Level::Help | + Level::Cancelled => { + } + } + + self.handler.emitter.borrow_mut().emit(&self); + self.cancel(); + self.handler.panic_if_treat_err_as_bug(); + + // if self.is_fatal() { + // panic!(FatalError); + // } + } + + /// Add a span/label to be included in the resulting snippet. + /// This is pushed onto the `MultiSpan` that was created when the + /// diagnostic was first built. If you don't call this function at + /// all, and you just supplied a `Span` to create the diagnostic, + /// then the snippet will just include that `Span`, which is + /// called the primary span. + forward!(pub fn span_label(&mut self, span: Span, label: &fmt::Display) + -> &mut Self); + + forward!(pub fn note_expected_found(&mut self, + label: &fmt::Display, + expected: &fmt::Display, + found: &fmt::Display) + -> &mut Self); + + forward!(pub fn note_expected_found_extra(&mut self, + label: &fmt::Display, + expected: &fmt::Display, + found: &fmt::Display, + expected_extra: &fmt::Display, + found_extra: &fmt::Display) + -> &mut Self); + + forward!(pub fn note(&mut self, msg: &str) -> &mut Self); + forward!(pub fn span_note<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str) + -> &mut Self); + forward!(pub fn warn(&mut self, msg: &str) -> &mut Self); + forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self); + forward!(pub fn help(&mut self , msg: &str) -> &mut Self); + forward!(pub fn span_help<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str) + -> &mut Self); + forward!(pub fn span_suggestion<S: Into<MultiSpan>>(&mut self, + sp: S, + msg: &str, + suggestion: String) + -> &mut Self); + forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self); + forward!(pub fn code(&mut self, s: String) -> &mut Self); + + /// Convenience function for internal use, clients should use one of the + /// struct_* methods on Handler. + pub fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> { + DiagnosticBuilder::new_with_code(handler, level, None, message) + } + + /// Convenience function for internal use, clients should use one of the + /// struct_* methods on Handler. + pub fn new_with_code(handler: &'a Handler, + level: Level, + code: Option<String>, + message: &str) + -> DiagnosticBuilder<'a> { + DiagnosticBuilder { + handler: handler, + diagnostic: Diagnostic::new_with_code(level, code, message) + } + } + + pub fn into_diagnostic(mut self) -> Diagnostic { + // annoyingly, the Drop impl means we can't actually move + let result = self.diagnostic.clone(); + self.cancel(); + result + } +} + +impl<'a> Debug for DiagnosticBuilder<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.diagnostic.fmt(f) + } +} + +/// Destructor bomb - a DiagnosticBuilder must be either emitted or cancelled or +/// we emit a bug. +impl<'a> Drop for DiagnosticBuilder<'a> { + fn drop(&mut self) { + if !panicking() && !self.cancelled() { + let mut db = DiagnosticBuilder::new(self.handler, + Level::Bug, + "Error constructed but not emitted"); + db.emit(); + panic!(); + } + } +} + diff --git a/bash-5.1/vendor/syntex_errors/src/emitter.rs b/bash-5.1/vendor/syntex_errors/src/emitter.rs new file mode 100644 index 0000000..b999601 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/emitter.rs @@ -0,0 +1,1219 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use self::Destination::*; + +use syntax_pos::{COMMAND_LINE_SP, DUMMY_SP, FileMap, Span, MultiSpan, CharPos}; + +use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapper}; +use RenderSpan::*; +use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style}; +use styled_buffer::StyledBuffer; + +use std::io::prelude::*; +use std::io; +use std::ops; +use std::rc::Rc; +use term; + +/// Emitter trait for emitting errors. +pub trait Emitter { + /// Emit a structured diagnostic. + fn emit(&mut self, db: &DiagnosticBuilder); +} + +impl Emitter for EmitterWriter { + fn emit(&mut self, db: &DiagnosticBuilder) { + let mut primary_span = db.span.clone(); + let mut children = db.children.clone(); + self.fix_multispans_in_std_macros(&mut primary_span, &mut children); + self.emit_messages_default(&db.level, &db.message, &db.code, &primary_span, &children); + } +} + +/// maximum number of lines we will print for each error; arbitrary. +pub const MAX_HIGHLIGHT_LINES: usize = 6; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColorConfig { + Auto, + Always, + Never, +} + +impl ColorConfig { + fn use_color(&self) -> bool { + match *self { + ColorConfig::Always => true, + ColorConfig::Never => false, + ColorConfig::Auto => stderr_isatty(), + } + } +} + +pub struct EmitterWriter { + dst: Destination, + cm: Option<Rc<CodeMapper>>, +} + +struct FileWithAnnotatedLines { + file: Rc<FileMap>, + lines: Vec<Line>, + multiline_depth: usize, +} + + +/// Do not use this for messages that end in `\n` – use `println_maybe_styled` instead. See +/// `EmitterWriter::print_maybe_styled` for details. +macro_rules! print_maybe_styled { + ($dst: expr, $style: expr, $($arg: tt)*) => { + $dst.print_maybe_styled(format_args!($($arg)*), $style, false) + } +} + +macro_rules! println_maybe_styled { + ($dst: expr, $style: expr, $($arg: tt)*) => { + $dst.print_maybe_styled(format_args!($($arg)*), $style, true) + } +} + +impl EmitterWriter { + pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter { + if color_config.use_color() { + let dst = Destination::from_stderr(); + EmitterWriter { + dst: dst, + cm: code_map, + } + } else { + EmitterWriter { + dst: Raw(Box::new(io::stderr())), + cm: code_map, + } + } + } + + pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter { + EmitterWriter { + dst: Raw(dst), + cm: code_map, + } + } + + fn preprocess_annotations(&self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> { + fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>, + file: Rc<FileMap>, + line_index: usize, + ann: Annotation) { + + for slot in file_vec.iter_mut() { + // Look through each of our files for the one we're adding to + if slot.file.name == file.name { + // See if we already have a line for it + for line_slot in &mut slot.lines { + if line_slot.line_index == line_index { + line_slot.annotations.push(ann); + return; + } + } + // We don't have a line yet, create one + slot.lines.push(Line { + line_index: line_index, + annotations: vec![ann], + }); + slot.lines.sort(); + return; + } + } + // This is the first time we're seeing the file + file_vec.push(FileWithAnnotatedLines { + file: file, + lines: vec![Line { + line_index: line_index, + annotations: vec![ann], + }], + multiline_depth: 0, + }); + } + + let mut output = vec![]; + let mut multiline_annotations = vec![]; + + if let Some(ref cm) = self.cm { + for span_label in msp.span_labels() { + if span_label.span == DUMMY_SP || span_label.span == COMMAND_LINE_SP { + continue; + } + let lo = cm.lookup_char_pos(span_label.span.lo); + let mut hi = cm.lookup_char_pos(span_label.span.hi); + let mut is_minimized = false; + + // If the span is long multi-line, simplify down to the span of one character + let max_multiline_span_length = 8; + if lo.line != hi.line && (hi.line - lo.line) > max_multiline_span_length { + hi.line = lo.line; + hi.col = CharPos(lo.col.0 + 1); + is_minimized = true; + } + + // Watch out for "empty spans". If we get a span like 6..6, we + // want to just display a `^` at 6, so convert that to + // 6..7. This is degenerate input, but it's best to degrade + // gracefully -- and the parser likes to supply a span like + // that for EOF, in particular. + if lo.col == hi.col && lo.line == hi.line { + hi.col = CharPos(lo.col.0 + 1); + } + + let mut ann = Annotation { + start_col: lo.col.0, + end_col: hi.col.0, + is_primary: span_label.is_primary, + label: span_label.label.clone(), + annotation_type: AnnotationType::Singleline, + }; + if is_minimized { + ann.annotation_type = AnnotationType::Minimized; + } else if lo.line != hi.line { + let ml = MultilineAnnotation { + depth: 1, + line_start: lo.line, + line_end: hi.line, + start_col: lo.col.0, + end_col: hi.col.0, + is_primary: span_label.is_primary, + label: span_label.label.clone(), + }; + ann.annotation_type = AnnotationType::Multiline(ml.clone()); + multiline_annotations.push((lo.file.clone(), ml)); + }; + + if !ann.is_multiline() { + add_annotation_to_file(&mut output, + lo.file, + lo.line, + ann); + } + } + } + + // Find overlapping multiline annotations, put them at different depths + multiline_annotations.sort_by(|a, b| { + (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end)) + }); + for item in multiline_annotations.clone() { + let ann = item.1; + for item in multiline_annotations.iter_mut() { + let ref mut a = item.1; + // Move all other multiline annotations overlapping with this one + // one level to the right. + if &ann != a && + num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true) + { + a.increase_depth(); + } else { + break; + } + } + } + + let mut max_depth = 0; // max overlapping multiline spans + for (file, ann) in multiline_annotations { + if ann.depth > max_depth { + max_depth = ann.depth; + } + add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start()); + for line in ann.line_start + 1..ann.line_end { + add_annotation_to_file(&mut output, file.clone(), line, ann.as_line()); + } + add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end()); + } + for file_vec in output.iter_mut() { + file_vec.multiline_depth = max_depth; + } + output + } + + fn render_source_line(&self, + buffer: &mut StyledBuffer, + file: Rc<FileMap>, + line: &Line, + width_offset: usize, + multiline_depth: usize) { + let source_string = file.get_line(line.line_index - 1) + .unwrap_or(""); + + let line_offset = buffer.num_lines(); + let code_offset = if multiline_depth == 0 { + width_offset + } else { + width_offset + multiline_depth + 1 + }; + + // First create the source line we will highlight. + buffer.puts(line_offset, code_offset, &source_string, Style::Quotation); + buffer.puts(line_offset, + 0, + &(line.line_index.to_string()), + Style::LineNumber); + + draw_col_separator(buffer, line_offset, width_offset - 2); + + // We want to display like this: + // + // vec.push(vec.pop().unwrap()); + // --- ^^^ - previous borrow ends here + // | | + // | error occurs here + // previous borrow of `vec` occurs here + // + // But there are some weird edge cases to be aware of: + // + // vec.push(vec.pop().unwrap()); + // -------- - previous borrow ends here + // || + // |this makes no sense + // previous borrow of `vec` occurs here + // + // For this reason, we group the lines into "highlight lines" + // and "annotations lines", where the highlight lines have the `~`. + + // Sort the annotations by (start, end col) + let mut annotations = line.annotations.clone(); + annotations.sort(); + annotations.reverse(); + + // First, figure out where each label will be positioned. + // + // In the case where you have the following annotations: + // + // vec.push(vec.pop().unwrap()); + // -------- - previous borrow ends here [C] + // || + // |this makes no sense [B] + // previous borrow of `vec` occurs here [A] + // + // `annotations_position` will hold [(2, A), (1, B), (0, C)]. + // + // We try, when possible, to stick the rightmost annotation at the end + // of the highlight line: + // + // vec.push(vec.pop().unwrap()); + // --- --- - previous borrow ends here + // + // But sometimes that's not possible because one of the other + // annotations overlaps it. For example, from the test + // `span_overlap_label`, we have the following annotations + // (written on distinct lines for clarity): + // + // fn foo(x: u32) { + // -------------- + // - + // + // In this case, we can't stick the rightmost-most label on + // the highlight line, or we would get: + // + // fn foo(x: u32) { + // -------- x_span + // | + // fn_span + // + // which is totally weird. Instead we want: + // + // fn foo(x: u32) { + // -------------- + // | | + // | x_span + // fn_span + // + // which is...less weird, at least. In fact, in general, if + // the rightmost span overlaps with any other span, we should + // use the "hang below" version, so we can at least make it + // clear where the span *starts*. + let mut annotations_position = vec![]; + let mut line_len = 0; + let mut p = 0; + let mut ann_iter = annotations.iter().peekable(); + while let Some(annotation) = ann_iter.next() { + let is_line = if let AnnotationType::MultilineLine(_) = annotation.annotation_type { + true + } else { + false + }; + let peek = ann_iter.peek(); + if let Some(next) = peek { + let next_is_line = if let AnnotationType::MultilineLine(_) = next.annotation_type { + true + } else { + false + }; + + if overlaps(next, annotation) && !is_line && !next_is_line { + p += 1; + } + } + annotations_position.push((p, annotation)); + if let Some(next) = peek { + let next_is_line = if let AnnotationType::MultilineLine(_) = next.annotation_type { + true + } else { + false + }; + let l = if let Some(ref label) = next.label { + label.len() + 2 + } else { + 0 + }; + if (overlaps(next, annotation) || next.end_col + l > annotation.start_col) + && !is_line && !next_is_line + { + p += 1; + } + } + if line_len < p { + line_len = p; + } + } + if line_len != 0 { + line_len += 1; + } + + // If there are no annotations or the only annotations on this line are + // MultilineLine, then there's only code being shown, stop processing. + if line.annotations.is_empty() || line.annotations.iter() + .filter(|a| { + // Set the multiline annotation vertical lines to the left of + // the code in this line. + if let AnnotationType::MultilineLine(depth) = a.annotation_type { + buffer.putc(line_offset, + width_offset + depth - 1, + '|', + if a.is_primary { + Style::UnderlinePrimary + } else { + Style::UnderlineSecondary + }); + false + } else { + true + } + }).collect::<Vec<_>>().len() == 0 + { + return; + } + + for pos in 0..line_len + 1 { + draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2); + buffer.putc(line_offset + pos + 1, + width_offset - 2, + '|', + Style::LineNumber); + } + + // Write the horizontal lines for multiline annotations + // (only the first and last lines need this). + // + // After this we will have: + // + // 2 | fn foo() { + // | __________ + // | + // | + // 3 | + // 4 | } + // | _ + for &(pos, annotation) in &annotations_position { + let style = if annotation.is_primary { + Style::UnderlinePrimary + } else { + Style::UnderlineSecondary + }; + let pos = pos + 1; + match annotation.annotation_type { + AnnotationType::MultilineStart(depth) | + AnnotationType::MultilineEnd(depth) => { + draw_range(buffer, + '_', + line_offset + pos, + width_offset + depth, + code_offset + annotation.start_col, + style); + } + _ => (), + } + } + + // Write the vertical lines for multiline spans and for labels that are + // on a different line as the underline. + // + // After this we will have: + // + // 2 | fn foo() { + // | __________ + // | | | + // | | + // 3 | | + // 4 | | } + // | |_ + for &(pos, annotation) in &annotations_position { + let style = if annotation.is_primary { + Style::UnderlinePrimary + } else { + Style::UnderlineSecondary + }; + let pos = pos + 1; + if pos > 1 { + for p in line_offset + 1..line_offset + pos + 1 { + buffer.putc(p, + code_offset + annotation.start_col, + '|', + style); + } + } + match annotation.annotation_type { + AnnotationType::MultilineStart(depth) => { + for p in line_offset + pos + 1..line_offset + line_len + 2 { + buffer.putc(p, + width_offset + depth - 1, + '|', + style); + } + } + AnnotationType::MultilineEnd(depth) => { + for p in line_offset..line_offset + pos + 1 { + buffer.putc(p, + width_offset + depth - 1, + '|', + style); + } + } + AnnotationType::MultilineLine(depth) => { + // the first line will have already be filled when we checked + // wether there were any annotations for this line. + for p in line_offset + 1..line_offset + line_len + 2 { + buffer.putc(p, + width_offset + depth - 1, + '|', + style); + } + } + _ => (), + } + } + + // Write the labels on the annotations that actually have a label. + // + // After this we will have: + // + // 2 | fn foo() { + // | __________ starting here... + // | | | + // | | something about `foo` + // 3 | | + // 4 | | } + // | |_ ...ending here: test + for &(pos, annotation) in &annotations_position { + let style = if annotation.is_primary { + Style::LabelPrimary + } else { + Style::LabelSecondary + }; + let (pos, col) = if pos == 0 { + (pos + 1, annotation.end_col + 1) + } else { + (pos + 2, annotation.start_col) + }; + if let Some(ref label) = annotation.label { + buffer.puts(line_offset + pos, + code_offset + col, + &label, + style); + } + } + + // Sort from biggest span to smallest span so that smaller spans are + // represented in the output: + // + // x | fn foo() + // | ^^^---^^ + // | | | + // | | something about `foo` + // | something about `fn foo()` + annotations_position.sort_by(|a, b| { + fn len(a: &Annotation) -> usize { + // Account for usize underflows + if a.end_col > a.start_col { + a.end_col - a.start_col + } else { + a.start_col - a.end_col + } + } + // Decreasing order + len(a.1).cmp(&len(b.1)).reverse() + }); + + // Write the underlines. + // + // After this we will have: + // + // 2 | fn foo() { + // | ____-_____^ starting here... + // | | | + // | | something about `foo` + // 3 | | + // 4 | | } + // | |_^ ...ending here: test + for &(_, annotation) in &annotations_position { + let (underline, style) = if annotation.is_primary { + ('^', Style::UnderlinePrimary) + } else { + ('-', Style::UnderlineSecondary) + }; + for p in annotation.start_col..annotation.end_col { + buffer.putc(line_offset + 1, + code_offset + p, + underline, + style); + } + } + } + + fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize { + let mut max = 0; + if let Some(ref cm) = self.cm { + for primary_span in msp.primary_spans() { + if primary_span != &DUMMY_SP && primary_span != &COMMAND_LINE_SP { + let hi = cm.lookup_char_pos(primary_span.hi); + if hi.line > max { + max = hi.line; + } + } + } + for span_label in msp.span_labels() { + if span_label.span != DUMMY_SP && span_label.span != COMMAND_LINE_SP { + let hi = cm.lookup_char_pos(span_label.span.hi); + if hi.line > max { + max = hi.line; + } + } + } + } + max + } + + fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize { + let mut max = 0; + + let primary = self.get_multispan_max_line_num(span); + max = if primary > max { primary } else { max }; + + for sub in children { + let sub_result = self.get_multispan_max_line_num(&sub.span); + max = if sub_result > max { primary } else { max }; + } + max + } + + // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of + // <*macros>. Since these locations are often difficult to read, we move these Spans from + // <*macros> to their corresponding use site. + fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool { + let mut spans_updated = false; + + if let Some(ref cm) = self.cm { + let mut before_after: Vec<(Span, Span)> = vec![]; + let mut new_labels: Vec<(Span, String)> = vec![]; + + // First, find all the spans in <*macros> and point instead at their use site + for sp in span.primary_spans() { + if (*sp == COMMAND_LINE_SP) || (*sp == DUMMY_SP) { + continue; + } + if cm.span_to_filename(sp.clone()).contains("macros>") { + let v = cm.macro_backtrace(sp.clone()); + if let Some(use_site) = v.last() { + before_after.push((sp.clone(), use_site.call_site.clone())); + } + } + for trace in cm.macro_backtrace(sp.clone()).iter().rev() { + // Only show macro locations that are local + // and display them like a span_note + if let Some(def_site) = trace.def_site_span { + if (def_site == COMMAND_LINE_SP) || (def_site == DUMMY_SP) { + continue; + } + // Check to make sure we're not in any <*macros> + if !cm.span_to_filename(def_site).contains("macros>") && + !trace.macro_decl_name.starts_with("#[") { + new_labels.push((trace.call_site, + "in this macro invocation".to_string())); + break; + } + } + } + } + for (label_span, label_text) in new_labels { + span.push_span_label(label_span, label_text); + } + for sp_label in span.span_labels() { + if (sp_label.span == COMMAND_LINE_SP) || (sp_label.span == DUMMY_SP) { + continue; + } + if cm.span_to_filename(sp_label.span.clone()).contains("macros>") { + let v = cm.macro_backtrace(sp_label.span.clone()); + if let Some(use_site) = v.last() { + before_after.push((sp_label.span.clone(), use_site.call_site.clone())); + } + } + } + // After we have them, make sure we replace these 'bad' def sites with their use sites + for (before, after) in before_after { + span.replace(before, after); + spans_updated = true; + } + } + + spans_updated + } + + // This does a small "fix" for multispans by looking to see if it can find any that + // point directly at <*macros>. Since these are often difficult to read, this + // will change the span to point at the use site. + fn fix_multispans_in_std_macros(&mut self, + span: &mut MultiSpan, + children: &mut Vec<SubDiagnostic>) { + let mut spans_updated = self.fix_multispan_in_std_macros(span); + for child in children.iter_mut() { + spans_updated |= self.fix_multispan_in_std_macros(&mut child.span); + } + if spans_updated { + children.push(SubDiagnostic { + level: Level::Note, + message: "this error originates in a macro outside of the current crate" + .to_string(), + span: MultiSpan::new(), + render_span: None, + }); + } + } + + fn emit_message_default(&mut self, + msp: &MultiSpan, + msg: &str, + code: &Option<String>, + level: &Level, + max_line_num_len: usize, + is_secondary: bool) + -> io::Result<()> { + let mut buffer = StyledBuffer::new(); + + if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary { + // This is a secondary message with no span info + for _ in 0..max_line_num_len { + buffer.prepend(0, " ", Style::NoStyle); + } + draw_note_separator(&mut buffer, 0, max_line_num_len + 1); + buffer.append(0, &level.to_string(), Style::HeaderMsg); + buffer.append(0, ": ", Style::NoStyle); + buffer.append(0, msg, Style::NoStyle); + } else { + buffer.append(0, &level.to_string(), Style::Level(level.clone())); + match code { + &Some(ref code) => { + buffer.append(0, "[", Style::Level(level.clone())); + buffer.append(0, &code, Style::Level(level.clone())); + buffer.append(0, "]", Style::Level(level.clone())); + } + _ => {} + } + buffer.append(0, ": ", Style::HeaderMsg); + buffer.append(0, msg, Style::HeaderMsg); + } + + // Preprocess all the annotations so that they are grouped by file and by line number + // This helps us quickly iterate over the whole message (including secondary file spans) + let mut annotated_files = self.preprocess_annotations(msp); + + // Make sure our primary file comes first + let primary_lo = if let (Some(ref cm), Some(ref primary_span)) = + (self.cm.as_ref(), msp.primary_span().as_ref()) { + if primary_span != &&DUMMY_SP && primary_span != &&COMMAND_LINE_SP { + cm.lookup_char_pos(primary_span.lo) + } else { + try!(emit_to_destination(&buffer.render(), level, &mut self.dst)); + return Ok(()); + } + } else { + // If we don't have span information, emit and exit + try!(emit_to_destination(&buffer.render(), level, &mut self.dst)); + return Ok(()); + }; + if let Ok(pos) = + annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) { + annotated_files.swap(0, pos); + } + + // Print out the annotate source lines that correspond with the error + for annotated_file in annotated_files { + // print out the span location and spacer before we print the annotated source + // to do this, we need to know if this span will be primary + let is_primary = primary_lo.file.name == annotated_file.file.name; + if is_primary { + // remember where we are in the output buffer for easy reference + let buffer_msg_line_offset = buffer.num_lines(); + + buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber); + let loc = primary_lo.clone(); + buffer.append(buffer_msg_line_offset, + &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1), + Style::LineAndColumn); + for _ in 0..max_line_num_len { + buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle); + } + } else { + // remember where we are in the output buffer for easy reference + let buffer_msg_line_offset = buffer.num_lines(); + + // Add spacing line + draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1); + + // Then, the secondary file indicator + buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber); + buffer.append(buffer_msg_line_offset + 1, + &annotated_file.file.name, + Style::LineAndColumn); + for _ in 0..max_line_num_len { + buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle); + } + } + + // Put in the spacer between the location and annotated source + let buffer_msg_line_offset = buffer.num_lines(); + draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1); + + // Next, output the annotate source for this file + for line_idx in 0..annotated_file.lines.len() { + self.render_source_line(&mut buffer, + annotated_file.file.clone(), + &annotated_file.lines[line_idx], + 3 + max_line_num_len, + annotated_file.multiline_depth); + + // check to see if we need to print out or elide lines that come between + // this annotated line and the next one + if line_idx < (annotated_file.lines.len() - 1) { + let line_idx_delta = annotated_file.lines[line_idx + 1].line_index - + annotated_file.lines[line_idx].line_index; + if line_idx_delta > 2 { + let last_buffer_line_num = buffer.num_lines(); + buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber); + } else if line_idx_delta == 2 { + let unannotated_line = annotated_file.file + .get_line(annotated_file.lines[line_idx].line_index) + .unwrap_or(""); + + let last_buffer_line_num = buffer.num_lines(); + + buffer.puts(last_buffer_line_num, + 0, + &(annotated_file.lines[line_idx + 1].line_index - 1) + .to_string(), + Style::LineNumber); + draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len); + buffer.puts(last_buffer_line_num, + 3 + max_line_num_len, + &unannotated_line, + Style::Quotation); + } + } + } + } + + // final step: take our styled buffer, render it, then output it + try!(emit_to_destination(&buffer.render(), level, &mut self.dst)); + + Ok(()) + } + fn emit_suggestion_default(&mut self, + suggestion: &CodeSuggestion, + level: &Level, + msg: &str, + max_line_num_len: usize) + -> io::Result<()> { + use std::borrow::Borrow; + + let primary_span = suggestion.msp.primary_span().unwrap(); + if let Some(ref cm) = self.cm { + let mut buffer = StyledBuffer::new(); + + buffer.append(0, &level.to_string(), Style::Level(level.clone())); + buffer.append(0, ": ", Style::HeaderMsg); + buffer.append(0, msg, Style::HeaderMsg); + + let lines = cm.span_to_lines(primary_span).unwrap(); + + assert!(!lines.lines.is_empty()); + + let complete = suggestion.splice_lines(cm.borrow()); + + // print the suggestion without any line numbers, but leave + // space for them. This helps with lining up with previous + // snippets from the actual error being reported. + let mut lines = complete.lines(); + let mut row_num = 1; + for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) { + draw_col_separator(&mut buffer, row_num, max_line_num_len + 1); + buffer.append(row_num, line, Style::NoStyle); + row_num += 1; + } + + // if we elided some lines, add an ellipsis + if let Some(_) = lines.next() { + buffer.append(row_num, "...", Style::NoStyle); + } + try!(emit_to_destination(&buffer.render(), level, &mut self.dst)); + } + Ok(()) + } + fn emit_messages_default(&mut self, + level: &Level, + message: &String, + code: &Option<String>, + span: &MultiSpan, + children: &Vec<SubDiagnostic>) { + let max_line_num = self.get_max_line_num(span, children); + let max_line_num_len = max_line_num.to_string().len(); + + match self.emit_message_default(span, message, code, level, max_line_num_len, false) { + Ok(()) => { + if !children.is_empty() { + let mut buffer = StyledBuffer::new(); + draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1); + match emit_to_destination(&buffer.render(), level, &mut self.dst) { + Ok(()) => (), + Err(e) => panic!("failed to emit error: {}", e) + } + } + for child in children { + match child.render_span { + Some(FullSpan(ref msp)) => { + match self.emit_message_default(msp, + &child.message, + &None, + &child.level, + max_line_num_len, + true) { + Err(e) => panic!("failed to emit error: {}", e), + _ => () + } + }, + Some(Suggestion(ref cs)) => { + match self.emit_suggestion_default(cs, + &child.level, + &child.message, + max_line_num_len) { + Err(e) => panic!("failed to emit error: {}", e), + _ => () + } + }, + None => { + match self.emit_message_default(&child.span, + &child.message, + &None, + &child.level, + max_line_num_len, + true) { + Err(e) => panic!("failed to emit error: {}", e), + _ => () + } + } + } + } + } + Err(e) => panic!("failed to emit error: {}", e), + } + match write!(&mut self.dst, "\n") { + Err(e) => panic!("failed to emit error: {}", e), + _ => { + match self.dst.flush() { + Err(e) => panic!("failed to emit error: {}", e), + _ => (), + } + } + } + } +} + +fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) { + buffer.puts(line, col, "| ", Style::LineNumber); +} + +fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) { + draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber); +} + +fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer, + line: usize, + col: usize, + style: Style) { + buffer.putc(line, col, '|', style); +} + +fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize, + col_from: usize, col_to: usize, style: Style) { + for col in col_from..col_to { + buffer.putc(line, col, symbol, style); + } +} + +fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) { + buffer.puts(line, col, "= ", Style::LineNumber); +} + +trait SyntexContains<Idx> { + fn syntex_contains(&self, item: Idx) -> bool; +} + +impl<Idx> SyntexContains<Idx> for ops::Range<Idx> where Idx: PartialOrd { + fn syntex_contains(&self, item: Idx) -> bool { + (self.start <= item) && (item < self.end) + } +} + +fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool { + let extra = if inclusive { + 1 + } else { + 0 + }; + (b_start..b_end + extra).syntex_contains(a_start) || + (a_start..a_end + extra).syntex_contains(b_start) +} +fn overlaps(a1: &Annotation, a2: &Annotation) -> bool { + num_overlap(a1.start_col, a1.end_col, a2.start_col, a2.end_col, false) +} + +fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>, + lvl: &Level, + dst: &mut Destination) + -> io::Result<()> { + use lock; + + // In order to prevent error message interleaving, where multiple error lines get intermixed + // when multiple compiler processes error simultaneously, we emit errors with additional + // steps. + // + // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When + // the .flush() is called we take the buffer created from the buffered writes and write it at + // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling + // scheme, this buffered approach works and maintains the styling. + // + // On Windows, styling happens through calls to a terminal API. This prevents us from using the + // same buffering approach. Instead, we use a global Windows mutex, which we acquire long + // enough to output the full error message, then we release. + let _buffer_lock = lock::acquire_global_lock("rustc_errors"); + for line in rendered_buffer { + for part in line { + try!(dst.apply_style(lvl.clone(), part.style)); + try!(write!(dst, "{}", part.text)); + try!(dst.reset_attrs()); + } + try!(write!(dst, "\n")); + } + try!(dst.flush()); + Ok(()) +} + +#[cfg(unix)] +fn stderr_isatty() -> bool { + use libc; + unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } +} +#[cfg(windows)] +fn stderr_isatty() -> bool { + type DWORD = u32; + type BOOL = i32; + type HANDLE = *mut u8; + const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; + extern "system" { + fn GetStdHandle(which: DWORD) -> HANDLE; + fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL; + } + unsafe { + let handle = GetStdHandle(STD_ERROR_HANDLE); + let mut out = 0; + GetConsoleMode(handle, &mut out) != 0 + } +} + +pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send; + +pub enum Destination { + Terminal(Box<term::StderrTerminal>), + BufferedTerminal(Box<BufferedStderr>), + Raw(Box<Write + Send>), +} + +/// Buffered writer gives us a way on Unix to buffer up an entire error message before we output +/// it. This helps to prevent interleaving of multiple error messages when multiple compiler +/// processes error simultaneously +pub struct BufferedWriter { + buffer: Vec<u8>, +} + +impl BufferedWriter { + // note: we use _new because the conditional compilation at its use site may make this + // this function unused on some platforms + fn _new() -> BufferedWriter { + BufferedWriter { buffer: vec![] } + } +} + +impl Write for BufferedWriter { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + for b in buf { + self.buffer.push(*b); + } + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + let mut stderr = io::stderr(); + let result = (|| { + try!(stderr.write_all(&self.buffer)); + stderr.flush() + })(); + self.buffer.clear(); + result + } +} + +impl Destination { + #[cfg(not(windows))] + /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error + /// to be emitted at one time. + fn from_stderr() -> Destination { + let stderr: Option<Box<BufferedStderr>> = + term::TerminfoTerminal::new(BufferedWriter::_new()) + .map(|t| Box::new(t) as Box<BufferedStderr>); + + match stderr { + Some(t) => BufferedTerminal(t), + None => Raw(Box::new(io::stderr())), + } + } + + #[cfg(windows)] + /// Return a normal, unbuffered terminal when on Windows. + fn from_stderr() -> Destination { + let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr()) + .map(|t| Box::new(t) as Box<term::StderrTerminal>) + .or_else(|| { + term::WinConsole::new(io::stderr()) + .ok() + .map(|t| Box::new(t) as Box<term::StderrTerminal>) + }); + + match stderr { + Some(t) => Terminal(t), + None => Raw(Box::new(io::stderr())), + } + } + + fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> { + match style { + Style::FileNameStyle | Style::LineAndColumn => {} + Style::LineNumber => { + try!(self.start_attr(term::Attr::Bold)); + if cfg!(windows) { + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))); + } else { + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))); + } + } + Style::ErrorCode => { + try!(self.start_attr(term::Attr::Bold)); + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA))); + } + Style::Quotation => {} + Style::OldSchoolNote => { + try!(self.start_attr(term::Attr::Bold)); + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_GREEN))); + } + Style::OldSchoolNoteText | Style::HeaderMsg => { + try!(self.start_attr(term::Attr::Bold)); + if cfg!(windows) { + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))); + } + } + Style::UnderlinePrimary | Style::LabelPrimary => { + try!(self.start_attr(term::Attr::Bold)); + try!(self.start_attr(term::Attr::ForegroundColor(lvl.color()))); + } + Style::UnderlineSecondary | + Style::LabelSecondary => { + try!(self.start_attr(term::Attr::Bold)); + if cfg!(windows) { + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))); + } else { + try!(self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))); + } + } + Style::NoStyle => {} + Style::Level(l) => { + try!(self.start_attr(term::Attr::Bold)); + try!(self.start_attr(term::Attr::ForegroundColor(l.color()))); + } + } + Ok(()) + } + + fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> { + match *self { + Terminal(ref mut t) => { + try!(t.attr(attr)); + } + BufferedTerminal(ref mut t) => { + try!(t.attr(attr)); + } + Raw(_) => {} + } + Ok(()) + } + + fn reset_attrs(&mut self) -> io::Result<()> { + match *self { + Terminal(ref mut t) => { + try!(t.reset()); + } + BufferedTerminal(ref mut t) => { + try!(t.reset()); + } + Raw(_) => {} + } + Ok(()) + } +} + +impl Write for Destination { + fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { + match *self { + Terminal(ref mut t) => t.write(bytes), + BufferedTerminal(ref mut t) => t.write(bytes), + Raw(ref mut w) => w.write(bytes), + } + } + fn flush(&mut self) -> io::Result<()> { + match *self { + Terminal(ref mut t) => t.flush(), + BufferedTerminal(ref mut t) => t.flush(), + Raw(ref mut w) => w.flush(), + } + } +} diff --git a/bash-5.1/vendor/syntex_errors/src/lib.rs b/bash-5.1/vendor/syntex_errors/src/lib.rs new file mode 100644 index 0000000..a5754e2 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/lib.rs @@ -0,0 +1,533 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![crate_type = "dylib"] +#![crate_type = "rlib"] +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://doc.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/nightly/")] +#![cfg_attr(not(stage0), deny(warnings))] + +extern crate rustc_serialize as serialize; +extern crate term; +#[macro_use] +extern crate log; +#[macro_use] +extern crate libc; +extern crate unicode_xid as std_unicode; +extern crate rustc_serialize; // used by deriving +extern crate syntex_pos as syntax_pos; + +pub use emitter::ColorConfig; + +use self::Level::*; + +use emitter::{Emitter, EmitterWriter}; + +use std::cell::{RefCell, Cell}; +use std::{error, fmt}; +use std::rc::Rc; + +pub mod diagnostic; +pub mod diagnostic_builder; +pub mod emitter; +pub mod snippet; +pub mod registry; +pub mod styled_buffer; +mod lock; + +use syntax_pos::{BytePos, Loc, FileLinesResult, FileName, MultiSpan, Span, NO_EXPANSION}; +use syntax_pos::MacroBacktrace; + +#[derive(Clone, Debug, PartialEq)] +pub enum RenderSpan { + /// A FullSpan renders with both with an initial line for the + /// message, prefixed by file:linenum, followed by a summary of + /// the source code covered by the span. + FullSpan(MultiSpan), + + /// A suggestion renders with both with an initial line for the + /// message, prefixed by file:linenum, followed by a summary + /// of hypothetical source code, where each `String` is spliced + /// into the lines in place of the code covered by each span. + Suggestion(CodeSuggestion), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CodeSuggestion { + pub msp: MultiSpan, + pub substitutes: Vec<String>, +} + +pub trait CodeMapper { + fn lookup_char_pos(&self, pos: BytePos) -> Loc; + fn span_to_lines(&self, sp: Span) -> FileLinesResult; + fn span_to_string(&self, sp: Span) -> String; + fn span_to_filename(&self, sp: Span) -> FileName; + fn macro_backtrace(&self, span: Span) -> Vec<MacroBacktrace>; + fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>; +} + +impl CodeSuggestion { + /// Returns the assembled code suggestion. + pub fn splice_lines(&self, cm: &CodeMapper) -> String { + use syntax_pos::{CharPos, Loc, Pos}; + + fn push_trailing(buf: &mut String, + line_opt: Option<&str>, + lo: &Loc, + hi_opt: Option<&Loc>) { + let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize())); + if let Some(line) = line_opt { + if line.len() > lo { + buf.push_str(match hi_opt { + Some(hi) => &line[lo..hi], + None => &line[lo..], + }); + } + if let None = hi_opt { + buf.push('\n'); + } + } + } + + let mut primary_spans = self.msp.primary_spans().to_owned(); + + assert_eq!(primary_spans.len(), self.substitutes.len()); + if primary_spans.is_empty() { + return format!(""); + } + + // Assumption: all spans are in the same file, and all spans + // are disjoint. Sort in ascending order. + primary_spans.sort_by_key(|sp| sp.lo); + + // Find the bounding span. + let lo = primary_spans.iter().map(|sp| sp.lo).min().unwrap(); + let hi = primary_spans.iter().map(|sp| sp.hi).min().unwrap(); + let bounding_span = Span { + lo: lo, + hi: hi, + expn_id: NO_EXPANSION, + }; + let lines = cm.span_to_lines(bounding_span).unwrap(); + assert!(!lines.lines.is_empty()); + + // To build up the result, we do this for each span: + // - push the line segment trailing the previous span + // (at the beginning a "phantom" span pointing at the start of the line) + // - push lines between the previous and current span (if any) + // - if the previous and current span are not on the same line + // push the line segment leading up to the current span + // - splice in the span substitution + // + // Finally push the trailing line segment of the last span + let fm = &lines.file; + let mut prev_hi = cm.lookup_char_pos(bounding_span.lo); + prev_hi.col = CharPos::from_usize(0); + + let mut prev_line = fm.get_line(lines.lines[0].line_index); + let mut buf = String::new(); + + for (sp, substitute) in primary_spans.iter().zip(self.substitutes.iter()) { + let cur_lo = cm.lookup_char_pos(sp.lo); + if prev_hi.line == cur_lo.line { + push_trailing(&mut buf, prev_line, &prev_hi, Some(&cur_lo)); + } else { + push_trailing(&mut buf, prev_line, &prev_hi, None); + // push lines between the previous and current span (if any) + for idx in prev_hi.line..(cur_lo.line - 1) { + if let Some(line) = fm.get_line(idx) { + buf.push_str(line); + buf.push('\n'); + } + } + if let Some(cur_line) = fm.get_line(cur_lo.line - 1) { + buf.push_str(&cur_line[..cur_lo.col.to_usize()]); + } + } + buf.push_str(substitute); + prev_hi = cm.lookup_char_pos(sp.hi); + prev_line = fm.get_line(prev_hi.line - 1); + } + push_trailing(&mut buf, prev_line, &prev_hi, None); + // remove trailing newline + buf.pop(); + buf + } +} + +/// Used as a return value to signify a fatal error occurred. (It is also +/// used as the argument to panic at the moment, but that will eventually +/// not be true.) +#[derive(Copy, Clone, Debug)] +#[must_use] +pub struct FatalError; + +impl fmt::Display for FatalError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write!(f, "parser fatal error") + } +} + +impl error::Error for FatalError { + fn description(&self) -> &str { + "The parser has encountered a fatal error" + } +} + +/// Signifies that the compiler died with an explicit call to `.bug` +/// or `.span_bug` rather than a failed assertion, etc. +#[derive(Copy, Clone, Debug)] +pub struct ExplicitBug; + +impl fmt::Display for ExplicitBug { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write!(f, "parser internal bug") + } +} + +impl error::Error for ExplicitBug { + fn description(&self) -> &str { + "The parser has encountered an internal bug" + } +} + +pub use diagnostic::{Diagnostic, SubDiagnostic}; +pub use diagnostic_builder::DiagnosticBuilder; + +/// A handler deals with errors; certain errors +/// (fatal, bug, unimpl) may cause immediate exit, +/// others log errors for later reporting. +pub struct Handler { + err_count: Cell<usize>, + emitter: RefCell<Box<Emitter>>, + pub can_emit_warnings: bool, + treat_err_as_bug: bool, + continue_after_error: Cell<bool>, + delayed_span_bug: RefCell<Option<(MultiSpan, String)>>, +} + +impl Handler { + pub fn with_tty_emitter(color_config: ColorConfig, + can_emit_warnings: bool, + treat_err_as_bug: bool, + cm: Option<Rc<CodeMapper>>) + -> Handler { + let emitter = Box::new(EmitterWriter::stderr(color_config, cm)); + Handler::with_emitter(can_emit_warnings, treat_err_as_bug, emitter) + } + + pub fn with_emitter(can_emit_warnings: bool, + treat_err_as_bug: bool, + e: Box<Emitter>) + -> Handler { + Handler { + err_count: Cell::new(0), + emitter: RefCell::new(e), + can_emit_warnings: can_emit_warnings, + treat_err_as_bug: treat_err_as_bug, + continue_after_error: Cell::new(true), + delayed_span_bug: RefCell::new(None), + } + } + + pub fn set_continue_after_error(&self, continue_after_error: bool) { + self.continue_after_error.set(continue_after_error); + } + + pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> { + DiagnosticBuilder::new(self, Level::Cancelled, "") + } + + pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Warning, msg); + result.set_span(sp); + if !self.can_emit_warnings { + result.cancel(); + } + result + } + pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str, + code: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Warning, msg); + result.set_span(sp); + result.code(code.to_owned()); + if !self.can_emit_warnings { + result.cancel(); + } + result + } + pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Warning, msg); + if !self.can_emit_warnings { + result.cancel(); + } + result + } + pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Error, msg); + result.set_span(sp); + result + } + pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str, + code: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Error, msg); + result.set_span(sp); + result.code(code.to_owned()); + result + } + pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> { + DiagnosticBuilder::new(self, Level::Error, msg) + } + pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg); + result.set_span(sp); + result + } + pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str, + code: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg); + result.set_span(sp); + result.code(code.to_owned()); + result + } + pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> { + DiagnosticBuilder::new(self, Level::Fatal, msg) + } + + pub fn cancel(&self, err: &mut DiagnosticBuilder) { + err.cancel(); + } + + fn panic_if_treat_err_as_bug(&self) { + if self.treat_err_as_bug { + panic!("encountered error with `-Z treat_err_as_bug"); + } + } + + pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError { + self.emit(&sp.into(), msg, Fatal); + self.panic_if_treat_err_as_bug(); + return FatalError; + } + pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, + sp: S, + msg: &str, + code: &str) + -> FatalError { + self.emit_with_code(&sp.into(), msg, code, Fatal); + self.panic_if_treat_err_as_bug(); + return FatalError; + } + pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + self.emit(&sp.into(), msg, Error); + self.panic_if_treat_err_as_bug(); + } + pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self, + sp: S, + msg: &str) + -> DiagnosticBuilder<'a> { + let mut result = DiagnosticBuilder::new(self, Level::Error, msg); + result.set_span(sp); + result + } + pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) { + self.emit_with_code(&sp.into(), msg, code, Error); + self.panic_if_treat_err_as_bug(); + } + pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + self.emit(&sp.into(), msg, Warning); + } + pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) { + self.emit_with_code(&sp.into(), msg, code, Warning); + } + pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! { + self.emit(&sp.into(), msg, Bug); + panic!(ExplicitBug); + } + pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + let mut delayed = self.delayed_span_bug.borrow_mut(); + *delayed = Some((sp.into(), msg.to_string())); + } + pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + self.emit(&sp.into(), msg, Bug); + } + pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + self.emit(&sp.into(), msg, Note); + } + pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! { + self.span_bug(sp, &format!("unimplemented {}", msg)); + } + pub fn fatal(&self, msg: &str) -> FatalError { + if self.treat_err_as_bug { + self.bug(msg); + } + let mut db = DiagnosticBuilder::new(self, Fatal, msg); + db.emit(); + FatalError + } + pub fn err(&self, msg: &str) { + if self.treat_err_as_bug { + self.bug(msg); + } + let mut db = DiagnosticBuilder::new(self, Error, msg); + db.emit(); + } + pub fn warn(&self, msg: &str) { + let mut db = DiagnosticBuilder::new(self, Warning, msg); + db.emit(); + } + pub fn note_without_error(&self, msg: &str) { + let mut db = DiagnosticBuilder::new(self, Note, msg); + db.emit(); + } + pub fn bug(&self, msg: &str) -> ! { + let mut db = DiagnosticBuilder::new(self, Bug, msg); + db.emit(); + panic!(ExplicitBug); + } + pub fn unimpl(&self, msg: &str) -> ! { + self.bug(&format!("unimplemented {}", msg)); + } + + pub fn bump_err_count(&self) { + self.err_count.set(self.err_count.get() + 1); + } + + pub fn err_count(&self) -> usize { + self.err_count.get() + } + + pub fn has_errors(&self) -> bool { + self.err_count.get() > 0 + } + pub fn abort_if_errors(&self) { + let s; + match self.err_count.get() { + 0 => { + let delayed_bug = self.delayed_span_bug.borrow(); + match *delayed_bug { + Some((ref span, ref errmsg)) => { + self.span_bug(span.clone(), errmsg); + } + _ => {} + } + + return; + } + 1 => s = "aborting due to previous error".to_string(), + _ => { + s = format!("aborting due to {} previous errors", self.err_count.get()); + } + } + + panic!(self.fatal(&s)); + } + pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) { + if lvl == Warning && !self.can_emit_warnings { + return; + } + let mut db = DiagnosticBuilder::new(self, lvl, msg); + db.set_span(msp.clone()); + db.emit(); + if !self.continue_after_error.get() { + self.abort_if_errors(); + } + } + pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: &str, lvl: Level) { + if lvl == Warning && !self.can_emit_warnings { + return; + } + let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code.to_owned()), msg); + db.set_span(msp.clone()); + db.emit(); + if !self.continue_after_error.get() { + self.abort_if_errors(); + } + } +} + + +#[derive(Copy, PartialEq, Clone, Debug)] +pub enum Level { + Bug, + Fatal, + // An error which while not immediately fatal, should stop the compiler + // progressing beyond the current phase. + PhaseFatal, + Error, + Warning, + Note, + Help, + Cancelled, +} + +impl fmt::Display for Level { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.to_str().fmt(f) + } +} + +impl Level { + pub fn color(self) -> term::color::Color { + match self { + Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED, + Warning => { + if cfg!(windows) { + term::color::BRIGHT_YELLOW + } else { + term::color::YELLOW + } + } + Note => term::color::BRIGHT_GREEN, + Help => term::color::BRIGHT_CYAN, + Cancelled => unreachable!(), + } + } + + pub fn to_str(self) -> &'static str { + match self { + Bug => "error: internal compiler error", + Fatal | PhaseFatal | Error => "error", + Warning => "warning", + Note => "note", + Help => "help", + Cancelled => panic!("Shouldn't call on cancelled error"), + } + } +} + +pub fn expect<T, M>(diag: &Handler, opt: Option<T>, msg: M) -> T + where M: FnOnce() -> String +{ + match opt { + Some(t) => t, + None => diag.bug(&msg()), + } +} diff --git a/bash-5.1/vendor/syntex_errors/src/lock.rs b/bash-5.1/vendor/syntex_errors/src/lock.rs new file mode 100644 index 0000000..4c29822 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/lock.rs @@ -0,0 +1,115 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Bindings to acquire a global named lock. +//! +//! This is intended to be used to synchronize multiple compiler processes to +//! ensure that we can output complete errors without interleaving on Windows. +//! Note that this is currently only needed for allowing only one 32-bit MSVC +//! linker to execute at once on MSVC hosts, so this is only implemented for +//! `cfg(windows)`. Also note that this may not always be used on Windows, +//! only when targeting 32-bit MSVC. +//! +//! For more information about why this is necessary, see where this is called. + +use std::any::Any; + +#[cfg(windows)] +#[allow(bad_style)] +pub fn acquire_global_lock(name: &str) -> Box<Any> { + use std::ffi::CString; + use std::io; + + type LPSECURITY_ATTRIBUTES = *mut u8; + type BOOL = i32; + type LPCSTR = *const u8; + type HANDLE = *mut u8; + type DWORD = u32; + + const INFINITE: DWORD = !0; + const WAIT_OBJECT_0: DWORD = 0; + const WAIT_ABANDONED: DWORD = 0x00000080; + + extern "system" { + fn CreateMutexA(lpMutexAttributes: LPSECURITY_ATTRIBUTES, + bInitialOwner: BOOL, + lpName: LPCSTR) + -> HANDLE; + fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; + fn ReleaseMutex(hMutex: HANDLE) -> BOOL; + fn CloseHandle(hObject: HANDLE) -> BOOL; + } + + struct Handle(HANDLE); + + impl Drop for Handle { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } + } + + struct Guard(Handle); + + impl Drop for Guard { + fn drop(&mut self) { + unsafe { + ReleaseMutex((self.0).0); + } + } + } + + let cname = CString::new(name).unwrap(); + unsafe { + // Create a named mutex, with no security attributes and also not + // acquired when we create it. + // + // This will silently create one if it doesn't already exist, or it'll + // open up a handle to one if it already exists. + let mutex = CreateMutexA(0 as *mut _, 0, cname.as_ptr() as *const u8); + if mutex.is_null() { + panic!("failed to create global mutex named `{}`: {}", + name, + io::Error::last_os_error()); + } + let mutex = Handle(mutex); + + // Acquire the lock through `WaitForSingleObject`. + // + // A return value of `WAIT_OBJECT_0` means we successfully acquired it. + // + // A return value of `WAIT_ABANDONED` means that the previous holder of + // the thread exited without calling `ReleaseMutex`. This can happen, + // for example, when the compiler crashes or is interrupted via ctrl-c + // or the like. In this case, however, we are still transferred + // ownership of the lock so we continue. + // + // If an error happens.. well... that's surprising! + match WaitForSingleObject(mutex.0, INFINITE) { + WAIT_OBJECT_0 | WAIT_ABANDONED => {} + code => { + panic!("WaitForSingleObject failed on global mutex named \ + `{}`: {} (ret={:x})", + name, + io::Error::last_os_error(), + code); + } + } + + // Return a guard which will call `ReleaseMutex` when dropped. + Box::new(Guard(mutex)) + } +} + +#[cfg(unix)] +pub fn acquire_global_lock(_name: &str) -> Box<Any> { + Box::new(()) +} diff --git a/bash-5.1/vendor/syntex_errors/src/registry.rs b/bash-5.1/vendor/syntex_errors/src/registry.rs new file mode 100644 index 0000000..8373768 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/registry.rs @@ -0,0 +1,26 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::collections::HashMap; + +#[derive(Clone)] +pub struct Registry { + descriptions: HashMap<&'static str, &'static str>, +} + +impl Registry { + pub fn new(descriptions: &[(&'static str, &'static str)]) -> Registry { + Registry { descriptions: descriptions.iter().cloned().collect() } + } + + pub fn find_description(&self, code: &str) -> Option<&'static str> { + self.descriptions.get(code).cloned() + } +} diff --git a/bash-5.1/vendor/syntex_errors/src/snippet.rs b/bash-5.1/vendor/syntex_errors/src/snippet.rs new file mode 100644 index 0000000..b8c1726 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/snippet.rs @@ -0,0 +1,188 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Code for annotating snippets. + +use syntax_pos::{Span, FileMap}; +use CodeMapper; +use std::rc::Rc; +use Level; + +#[derive(Clone)] +pub struct SnippetData { + codemap: Rc<CodeMapper>, + files: Vec<FileInfo>, +} + +#[derive(Clone)] +pub struct FileInfo { + file: Rc<FileMap>, + + /// The "primary file", if any, gets a `-->` marker instead of + /// `>>>`, and has a line-number/column printed and not just a + /// filename. It appears first in the listing. It is known to + /// contain at least one primary span, though primary spans (which + /// are designated with `^^^`) may also occur in other files. + primary_span: Option<Span>, + + lines: Vec<Line>, +} + +#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] +pub struct Line { + pub line_index: usize, + pub annotations: Vec<Annotation>, +} + + +#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] +pub struct MultilineAnnotation { + pub depth: usize, + pub line_start: usize, + pub line_end: usize, + pub start_col: usize, + pub end_col: usize, + pub is_primary: bool, + pub label: Option<String>, +} + +impl MultilineAnnotation { + pub fn increase_depth(&mut self) { + self.depth += 1; + } + + pub fn as_start(&self) -> Annotation { + Annotation { + start_col: self.start_col, + end_col: self.start_col + 1, + is_primary: self.is_primary, + label: Some("starting here...".to_owned()), + annotation_type: AnnotationType::MultilineStart(self.depth) + } + } + + pub fn as_end(&self) -> Annotation { + Annotation { + start_col: self.end_col - 1, + end_col: self.end_col, + is_primary: self.is_primary, + label: match self.label { + Some(ref label) => Some(format!("...ending here: {}", label)), + None => Some("...ending here".to_owned()), + }, + annotation_type: AnnotationType::MultilineEnd(self.depth) + } + } + + pub fn as_line(&self) -> Annotation { + Annotation { + start_col: 0, + end_col: 0, + is_primary: self.is_primary, + label: None, + annotation_type: AnnotationType::MultilineLine(self.depth) + } + } +} + +#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] +pub enum AnnotationType { + /// Annotation under a single line of code + Singleline, + + /// Annotation under the first character of a multiline span + Minimized, + + /// Annotation enclosing the first and last character of a multiline span + Multiline(MultilineAnnotation), + + // The Multiline type above is replaced with the following three in order + // to reuse the current label drawing code. + // + // Each of these corresponds to one part of the following diagram: + // + // x | foo(1 + bar(x, + // | _________^ starting here... < MultilineStart + // x | | y), < MultilineLine + // | |______________^ ...ending here: label < MultilineEnd + // x | z); + /// Annotation marking the first character of a fully shown multiline span + MultilineStart(usize), + /// Annotation marking the last character of a fully shown multiline span + MultilineEnd(usize), + /// Line at the left enclosing the lines of a fully shown multiline span + MultilineLine(usize), +} + +#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] +pub struct Annotation { + /// Start column, 0-based indexing -- counting *characters*, not + /// utf-8 bytes. Note that it is important that this field goes + /// first, so that when we sort, we sort orderings by start + /// column. + pub start_col: usize, + + /// End column within the line (exclusive) + pub end_col: usize, + + /// Is this annotation derived from primary span + pub is_primary: bool, + + /// Optional label to display adjacent to the annotation. + pub label: Option<String>, + + /// Is this a single line, multiline or multiline span minimized down to a + /// smaller span. + pub annotation_type: AnnotationType, +} + +impl Annotation { + pub fn is_minimized(&self) -> bool { + match self.annotation_type { + AnnotationType::Minimized => true, + _ => false, + } + } + + pub fn is_multiline(&self) -> bool { + match self.annotation_type { + AnnotationType::Multiline(_) | + AnnotationType::MultilineStart(_) | + AnnotationType::MultilineLine(_) | + AnnotationType::MultilineEnd(_) => true, + _ => false, + } + } + +} + +#[derive(Debug)] +pub struct StyledString { + pub text: String, + pub style: Style, +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum Style { + HeaderMsg, + FileNameStyle, + LineAndColumn, + LineNumber, + Quotation, + UnderlinePrimary, + UnderlineSecondary, + LabelPrimary, + LabelSecondary, + OldSchoolNoteText, + OldSchoolNote, + NoStyle, + ErrorCode, + Level(Level), +} diff --git a/bash-5.1/vendor/syntex_errors/src/styled_buffer.rs b/bash-5.1/vendor/syntex_errors/src/styled_buffer.rs new file mode 100644 index 0000000..dfc7c64 --- /dev/null +++ b/bash-5.1/vendor/syntex_errors/src/styled_buffer.rs @@ -0,0 +1,145 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Code for creating styled buffers + +use snippet::{Style, StyledString}; + +#[derive(Debug)] +pub struct StyledBuffer { + text: Vec<Vec<char>>, + styles: Vec<Vec<Style>>, +} + +impl StyledBuffer { + pub fn new() -> StyledBuffer { + StyledBuffer { + text: vec![], + styles: vec![], + } + } + + pub fn copy_tabs(&mut self, row: usize) { + if row < self.text.len() { + for i in row + 1..self.text.len() { + for j in 0..self.text[i].len() { + if self.text[row].len() > j && self.text[row][j] == '\t' && + self.text[i][j] == ' ' { + self.text[i][j] = '\t'; + } + } + } + } + } + + pub fn render(&mut self) -> Vec<Vec<StyledString>> { + let mut output: Vec<Vec<StyledString>> = vec![]; + let mut styled_vec: Vec<StyledString> = vec![]; + + // before we render, do a little patch-up work to support tabs + self.copy_tabs(3); + + for (row, row_style) in self.text.iter().zip(&self.styles) { + let mut current_style = Style::NoStyle; + let mut current_text = String::new(); + + for (&c, &s) in row.iter().zip(row_style) { + if s != current_style { + if !current_text.is_empty() { + styled_vec.push(StyledString { + text: current_text, + style: current_style, + }); + } + current_style = s; + current_text = String::new(); + } + current_text.push(c); + } + if !current_text.is_empty() { + styled_vec.push(StyledString { + text: current_text, + style: current_style, + }); + } + + // We're done with the row, push and keep going + output.push(styled_vec); + + styled_vec = vec![]; + } + + output + } + + fn ensure_lines(&mut self, line: usize) { + while line >= self.text.len() { + self.text.push(vec![]); + self.styles.push(vec![]); + } + } + + pub fn putc(&mut self, line: usize, col: usize, chr: char, style: Style) { + self.ensure_lines(line); + if col < self.text[line].len() { + self.text[line][col] = chr; + self.styles[line][col] = style; + } else { + let mut i = self.text[line].len(); + while i < col { + self.text[line].push(' '); + self.styles[line].push(Style::NoStyle); + i += 1; + } + self.text[line].push(chr); + self.styles[line].push(style); + } + } + + pub fn puts(&mut self, line: usize, col: usize, string: &str, style: Style) { + let mut n = col; + for c in string.chars() { + self.putc(line, n, c, style); + n += 1; + } + } + + pub fn set_style(&mut self, line: usize, col: usize, style: Style) { + if self.styles.len() > line && self.styles[line].len() > col { + self.styles[line][col] = style; + } + } + + pub fn prepend(&mut self, line: usize, string: &str, style: Style) { + self.ensure_lines(line); + let string_len = string.len(); + + // Push the old content over to make room for new content + for _ in 0..string_len { + self.styles[line].insert(0, Style::NoStyle); + self.text[line].insert(0, ' '); + } + + self.puts(line, 0, string, style); + } + + pub fn append(&mut self, line: usize, string: &str, style: Style) { + if line >= self.text.len() { + self.puts(line, 0, string, style); + } else { + let col = self.text[line].len(); + self.puts(line, col, string, style); + } + } + + pub fn num_lines(&self) -> usize { + self.text.len() + } +} diff --git a/bash-5.1/vendor/syntex_pos/.cargo-checksum.json b/bash-5.1/vendor/syntex_pos/.cargo-checksum.json new file mode 100644 index 0000000..1f98dc0 --- /dev/null +++ b/bash-5.1/vendor/syntex_pos/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"7391dd7ba851027f98067fef453fe0b71252ddf89f914257f9c2bb0874256f1c","src/lib.rs":"5bcf6170629a9afb40f06028d4708bb2cd9d278988e57f7269abcefc437f4616"},"package":"8df3921c7945dfb9ffc53aa35adb2cf4313b5ab5f079c3619b3d4eb82a0efc2b"} \ No newline at end of file diff --git a/bash-5.1/vendor/syntex_pos/Cargo.toml b/bash-5.1/vendor/syntex_pos/Cargo.toml new file mode 100644 index 0000000..db05408 --- /dev/null +++ b/bash-5.1/vendor/syntex_pos/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "syntex_pos" +version = "0.54.0" +authors = [ "erick.tryzelaar@gmail.com" ] +license = "MIT/Apache-2.0" +description = "Export of libsyntax_pos for code generation" +repository = "https://github.com/serde-rs/syntex" +include = ["Cargo.toml", "src/**/*.rs"] + +[dependencies] +rustc-serialize = "^0.3.16" diff --git a/bash-5.1/vendor/syntex_pos/src/lib.rs b/bash-5.1/vendor/syntex_pos/src/lib.rs new file mode 100644 index 0000000..e727076 --- /dev/null +++ b/bash-5.1/vendor/syntex_pos/src/lib.rs @@ -0,0 +1,725 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The source positions and related helper functions +//! +//! # Note +//! +//! This API is completely unstable and subject to change. + +#![crate_type = "dylib"] +#![crate_type = "rlib"] +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://doc.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/nightly/")] +#![cfg_attr(not(stage0), deny(warnings))] + +use std::cell::{Cell, RefCell}; +use std::ops::{Add, Sub}; +use std::rc::Rc; +use std::cmp; + +use std::fmt; + +use serialize::{Encodable, Decodable, Encoder, Decoder}; + +extern crate rustc_serialize; +extern crate rustc_serialize as serialize; + +pub type FileName = String; + +/// Spans represent a region of code, used for error reporting. Positions in spans +/// are *absolute* positions from the beginning of the codemap, not positions +/// relative to FileMaps. Methods on the CodeMap can be used to relate spans back +/// to the original source. +/// You must be careful if the span crosses more than one file - you will not be +/// able to use many of the functions on spans in codemap and you cannot assume +/// that the length of the span = hi - lo; there may be space in the BytePos +/// range between files. +#[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)] +pub struct Span { + pub lo: BytePos, + pub hi: BytePos, + /// Information about where the macro came from, if this piece of + /// code was created by a macro expansion. + pub expn_id: ExpnId +} + +/// A collection of spans. Spans have two orthogonal attributes: +/// +/// - they can be *primary spans*. In this case they are the locus of +/// the error, and would be rendered with `^^^`. +/// - they can have a *label*. In this case, the label is written next +/// to the mark in the snippet when we render. +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +pub struct MultiSpan { + primary_spans: Vec<Span>, + span_labels: Vec<(Span, String)>, +} + +impl Span { + /// Returns a new span representing just the end-point of this span + pub fn end_point(self) -> Span { + let lo = cmp::max(self.hi.0 - 1, self.lo.0); + Span { lo: BytePos(lo), hi: self.hi, expn_id: self.expn_id} + } + + /// Returns `self` if `self` is not the dummy span, and `other` otherwise. + pub fn substitute_dummy(self, other: Span) -> Span { + if self.source_equal(&DUMMY_SP) { other } else { self } + } + + pub fn contains(self, other: Span) -> bool { + self.lo <= other.lo && other.hi <= self.hi + } + + /// Return true if the spans are equal with regards to the source text. + /// + /// Use this instead of `==` when either span could be generated code, + /// and you only care that they point to the same bytes of source text. + pub fn source_equal(&self, other: &Span) -> bool { + self.lo == other.lo && self.hi == other.hi + } + + /// Returns `Some(span)`, where the start is trimmed by the end of `other` + pub fn trim_start(self, other: Span) -> Option<Span> { + if self.hi > other.hi { + Some(Span { lo: cmp::max(self.lo, other.hi), .. self }) + } else { + None + } + } +} + +#[derive(Clone, Debug)] +pub struct SpanLabel { + /// The span we are going to include in the final snippet. + pub span: Span, + + /// Is this a primary span? This is the "locus" of the message, + /// and is indicated with a `^^^^` underline, versus `----`. + pub is_primary: bool, + + /// What label should we attach to this span (if any)? + pub label: Option<String>, +} + +impl Encodable for Span { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_struct("Span", 2, |s| { + try!(s.emit_struct_field("lo", 0, |s| { + self.lo.encode(s) + })); + + s.emit_struct_field("hi", 1, |s| { + self.hi.encode(s) + }) + }) + } +} + +impl Decodable for Span { + fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> { + d.read_struct("Span", 2, |d| { + let lo = try!(d.read_struct_field("lo", 0, Decodable::decode)); + let hi = try!(d.read_struct_field("hi", 1, Decodable::decode)); + Ok(mk_sp(lo, hi)) + }) + } +} + +fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}", + span.lo, span.hi, span.expn_id) +} + +impl fmt::Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f)) + } +} + +pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION }; + +// Generic span to be used for code originating from the command line +pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0), + hi: BytePos(0), + expn_id: COMMAND_LINE_EXPN }; + +impl MultiSpan { + pub fn new() -> MultiSpan { + MultiSpan { + primary_spans: vec![], + span_labels: vec![] + } + } + + pub fn from_span(primary_span: Span) -> MultiSpan { + MultiSpan { + primary_spans: vec![primary_span], + span_labels: vec![] + } + } + + pub fn from_spans(vec: Vec<Span>) -> MultiSpan { + MultiSpan { + primary_spans: vec, + span_labels: vec![] + } + } + + pub fn push_span_label(&mut self, span: Span, label: String) { + self.span_labels.push((span, label)); + } + + /// Selects the first primary span (if any) + pub fn primary_span(&self) -> Option<Span> { + self.primary_spans.first().cloned() + } + + /// Returns all primary spans. + pub fn primary_spans(&self) -> &[Span] { + &self.primary_spans + } + + /// Replaces all occurances of one Span with another. Used to move Spans in areas that don't + /// display well (like std macros). Returns true if replacements occurred. + pub fn replace(&mut self, before: Span, after: Span) -> bool { + let mut replacements_occurred = false; + for primary_span in &mut self.primary_spans { + if *primary_span == before { + *primary_span = after; + replacements_occurred = true; + } + } + for span_label in &mut self.span_labels { + if span_label.0 == before { + span_label.0 = after; + replacements_occurred = true; + } + } + replacements_occurred + } + + /// Returns the strings to highlight. We always ensure that there + /// is an entry for each of the primary spans -- for each primary + /// span P, if there is at least one label with span P, we return + /// those labels (marked as primary). But otherwise we return + /// `SpanLabel` instances with empty labels. + pub fn span_labels(&self) -> Vec<SpanLabel> { + let is_primary = |span| self.primary_spans.contains(&span); + let mut span_labels = vec![]; + + for &(span, ref label) in &self.span_labels { + span_labels.push(SpanLabel { + span: span, + is_primary: is_primary(span), + label: Some(label.clone()) + }); + } + + for &span in &self.primary_spans { + if !span_labels.iter().any(|sl| sl.span == span) { + span_labels.push(SpanLabel { + span: span, + is_primary: true, + label: None + }); + } + } + + span_labels + } +} + +impl From<Span> for MultiSpan { + fn from(span: Span) -> MultiSpan { + MultiSpan::from_span(span) + } +} + +#[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy, Ord, PartialOrd)] +pub struct ExpnId(pub u32); + +pub const NO_EXPANSION: ExpnId = ExpnId(!0); +// For code appearing from the command line +pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1); + +// For code generated by a procedural macro, without knowing which +// Used in `qquote!` +pub const PROC_EXPN: ExpnId = ExpnId(!2); + +impl ExpnId { + pub fn from_u32(id: u32) -> ExpnId { + ExpnId(id) + } + + pub fn into_u32(self) -> u32 { + self.0 + } +} + +/// Identifies an offset of a multi-byte character in a FileMap +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)] +pub struct MultiByteChar { + /// The absolute offset of the character in the CodeMap + pub pos: BytePos, + /// The number of bytes, >=2 + pub bytes: usize, +} + +/// A single source in the CodeMap. +pub struct FileMap { + /// The name of the file that the source came from, source that doesn't + /// originate from files has names between angle brackets by convention, + /// e.g. `<anon>` + pub name: FileName, + /// The absolute path of the file that the source came from. + pub abs_path: Option<FileName>, + /// The complete source code + pub src: Option<Rc<String>>, + /// The start position of this source in the CodeMap + pub start_pos: BytePos, + /// The end position of this source in the CodeMap + pub end_pos: BytePos, + /// Locations of lines beginnings in the source code + pub lines: RefCell<Vec<BytePos>>, + /// Locations of multi-byte characters in the source code + pub multibyte_chars: RefCell<Vec<MultiByteChar>>, +} + +impl Encodable for FileMap { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_struct("FileMap", 6, |s| { + try!(s.emit_struct_field("name", 0, |s| self.name.encode(s))); + try!(s.emit_struct_field("abs_path", 1, |s| self.abs_path.encode(s))); + try!(s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))); + try!(s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))); + try!(s.emit_struct_field("lines", 4, |s| { + let lines = self.lines.borrow(); + // store the length + try!(s.emit_u32(lines.len() as u32)); + + if !lines.is_empty() { + // In order to preserve some space, we exploit the fact that + // the lines list is sorted and individual lines are + // probably not that long. Because of that we can store lines + // as a difference list, using as little space as possible + // for the differences. + let max_line_length = if lines.len() == 1 { + 0 + } else { + lines.windows(2) + .map(|w| w[1] - w[0]) + .map(|bp| bp.to_usize()) + .max() + .unwrap() + }; + + let bytes_per_diff: u8 = match max_line_length { + 0 ... 0xFF => 1, + 0x100 ... 0xFFFF => 2, + _ => 4 + }; + + // Encode the number of bytes used per diff. + try!(bytes_per_diff.encode(s)); + + // Encode the first element. + try!(lines[0].encode(s)); + + let diff_iter = (&lines[..]).windows(2) + .map(|w| (w[1] - w[0])); + + match bytes_per_diff { + 1 => for diff in diff_iter { try!((diff.0 as u8).encode(s)) }, + 2 => for diff in diff_iter { try!((diff.0 as u16).encode(s)) }, + 4 => for diff in diff_iter { try!(diff.0.encode(s)) }, + _ => unreachable!() + } + } + + Ok(()) + })); + s.emit_struct_field("multibyte_chars", 5, |s| { + (*self.multibyte_chars.borrow()).encode(s) + }) + }) + } +} + +impl Decodable for FileMap { + fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> { + + d.read_struct("FileMap", 6, |d| { + let name: String = try!(d.read_struct_field("name", 0, |d| Decodable::decode(d))); + let abs_path: Option<String> = + try!(d.read_struct_field("abs_path", 1, |d| Decodable::decode(d))); + let start_pos: BytePos = try!(d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))); + let end_pos: BytePos = try!(d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))); + let lines: Vec<BytePos> = try!(d.read_struct_field("lines", 4, |d| { + let num_lines: u32 = try!(Decodable::decode(d)); + let mut lines = Vec::with_capacity(num_lines as usize); + + if num_lines > 0 { + // Read the number of bytes used per diff. + let bytes_per_diff: u8 = try!(Decodable::decode(d)); + + // Read the first element. + let mut line_start: BytePos = try!(Decodable::decode(d)); + lines.push(line_start); + + for _ in 1..num_lines { + let diff = match bytes_per_diff { + 1 => try!(d.read_u8()) as u32, + 2 => try!(d.read_u16()) as u32, + 4 => try!(d.read_u32()), + _ => unreachable!() + }; + + line_start = line_start + BytePos(diff); + + lines.push(line_start); + } + } + + Ok(lines) + })); + let multibyte_chars: Vec<MultiByteChar> = + try!(d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))); + Ok(FileMap { + name: name, + abs_path: abs_path, + start_pos: start_pos, + end_pos: end_pos, + src: None, + lines: RefCell::new(lines), + multibyte_chars: RefCell::new(multibyte_chars) + }) + }) + } +} + +impl fmt::Debug for FileMap { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "FileMap({})", self.name) + } +} + +impl FileMap { + /// EFFECT: register a start-of-line offset in the + /// table of line-beginnings. + /// UNCHECKED INVARIANT: these offsets must be added in the right + /// order and must be in the right places; there is shared knowledge + /// about what ends a line between this file and parse.rs + /// WARNING: pos param here is the offset relative to start of CodeMap, + /// and CodeMap will append a newline when adding a filemap without a newline at the end, + /// so the safe way to call this is with value calculated as + /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap. + pub fn next_line(&self, pos: BytePos) { + // the new charpos must be > the last one (or it's the first one). + let mut lines = self.lines.borrow_mut(); + let line_len = lines.len(); + assert!(line_len == 0 || ((*lines)[line_len - 1] < pos)); + lines.push(pos); + } + + /// get a line from the list of pre-computed line-beginnings. + /// line-number here is 0-based. + pub fn get_line(&self, line_number: usize) -> Option<&str> { + match self.src { + Some(ref src) => { + let lines = self.lines.borrow(); + lines.get(line_number).map(|&line| { + let begin: BytePos = line - self.start_pos; + let begin = begin.to_usize(); + // We can't use `lines.get(line_number+1)` because we might + // be parsing when we call this function and thus the current + // line is the last one we have line info for. + let slice = &src[begin..]; + match slice.find('\n') { + Some(e) => &slice[..e], + None => slice + } + }) + } + None => None + } + } + + pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) { + assert!(bytes >=2 && bytes <= 4); + let mbc = MultiByteChar { + pos: pos, + bytes: bytes, + }; + self.multibyte_chars.borrow_mut().push(mbc); + } + + pub fn is_real_file(&self) -> bool { + !(self.name.starts_with("<") && + self.name.ends_with(">")) + } + + pub fn is_imported(&self) -> bool { + self.src.is_none() + } + + pub fn byte_length(&self) -> u32 { + self.end_pos.0 - self.start_pos.0 + } + pub fn count_lines(&self) -> usize { + self.lines.borrow().len() + } + + /// Find the line containing the given position. The return value is the + /// index into the `lines` array of this FileMap, not the 1-based line + /// number. If the filemap is empty or the position is located before the + /// first line, None is returned. + pub fn lookup_line(&self, pos: BytePos) -> Option<usize> { + let lines = self.lines.borrow(); + if lines.len() == 0 { + return None; + } + + let line_index = lookup_line(&lines[..], pos); + assert!(line_index < lines.len() as isize); + if line_index >= 0 { + Some(line_index as usize) + } else { + None + } + } + + pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) { + if self.start_pos == self.end_pos { + return (self.start_pos, self.end_pos); + } + + let lines = self.lines.borrow(); + assert!(line_index < lines.len()); + if line_index == (lines.len() - 1) { + (lines[line_index], self.end_pos) + } else { + (lines[line_index], lines[line_index + 1]) + } + } +} + +// _____________________________________________________________________________ +// Pos, BytePos, CharPos +// + +pub trait Pos { + fn from_usize(n: usize) -> Self; + fn to_usize(&self) -> usize; +} + +/// A byte offset. Keep this small (currently 32-bits), as AST contains +/// a lot of them. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] +pub struct BytePos(pub u32); + +/// A character offset. Because of multibyte utf8 characters, a byte offset +/// is not equivalent to a character offset. The CodeMap will convert BytePos +/// values to CharPos values as necessary. +#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] +pub struct CharPos(pub usize); + +// FIXME: Lots of boilerplate in these impls, but so far my attempts to fix +// have been unsuccessful + +impl Pos for BytePos { + fn from_usize(n: usize) -> BytePos { BytePos(n as u32) } + fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize } +} + +impl Add for BytePos { + type Output = BytePos; + + fn add(self, rhs: BytePos) -> BytePos { + BytePos((self.to_usize() + rhs.to_usize()) as u32) + } +} + +impl Sub for BytePos { + type Output = BytePos; + + fn sub(self, rhs: BytePos) -> BytePos { + BytePos((self.to_usize() - rhs.to_usize()) as u32) + } +} + +impl Encodable for BytePos { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_u32(self.0) + } +} + +impl Decodable for BytePos { + fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> { + Ok(BytePos(try!(d.read_u32()))) + } +} + +impl Pos for CharPos { + fn from_usize(n: usize) -> CharPos { CharPos(n) } + fn to_usize(&self) -> usize { let CharPos(n) = *self; n } +} + +impl Add for CharPos { + type Output = CharPos; + + fn add(self, rhs: CharPos) -> CharPos { + CharPos(self.to_usize() + rhs.to_usize()) + } +} + +impl Sub for CharPos { + type Output = CharPos; + + fn sub(self, rhs: CharPos) -> CharPos { + CharPos(self.to_usize() - rhs.to_usize()) + } +} + +// _____________________________________________________________________________ +// Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos +// + +/// A source code location used for error reporting +#[derive(Debug, Clone)] +pub struct Loc { + /// Information about the original source + pub file: Rc<FileMap>, + /// The (1-based) line number + pub line: usize, + /// The (0-based) column offset + pub col: CharPos +} + +/// A source code location used as the result of lookup_char_pos_adj +// Actually, *none* of the clients use the filename *or* file field; +// perhaps they should just be removed. +#[derive(Debug)] +pub struct LocWithOpt { + pub filename: FileName, + pub line: usize, + pub col: CharPos, + pub file: Option<Rc<FileMap>>, +} + +// used to be structural records. Better names, anyone? +#[derive(Debug)] +pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize } +#[derive(Debug)] +pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct LineInfo { + /// Index of line, starting from 0. + pub line_index: usize, + + /// Column in line where span begins, starting from 0. + pub start_col: CharPos, + + /// Column in line where span ends, starting from 0, exclusive. + pub end_col: CharPos, +} + +pub struct FileLines { + pub file: Rc<FileMap>, + pub lines: Vec<LineInfo> +} + +thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> = + Cell::new(default_span_debug)); + +/* assuming that we're not in macro expansion */ +pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span { + Span {lo: lo, hi: hi, expn_id: NO_EXPANSION} +} + +pub struct MacroBacktrace { + /// span where macro was applied to generate this code + pub call_site: Span, + + /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]") + pub macro_decl_name: String, + + /// span where macro was defined (if known) + pub def_site_span: Option<Span>, +} + +// _____________________________________________________________________________ +// SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions +// + +pub type FileLinesResult = Result<FileLines, SpanLinesError>; + +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum SpanLinesError { + IllFormedSpan(Span), + DistinctSources(DistinctSources), +} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum SpanSnippetError { + IllFormedSpan(Span), + DistinctSources(DistinctSources), + MalformedForCodemap(MalformedCodemapPositions), + SourceNotAvailable { filename: String } +} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct DistinctSources { + pub begin: (String, BytePos), + pub end: (String, BytePos) +} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct MalformedCodemapPositions { + pub name: String, + pub source_len: usize, + pub begin_pos: BytePos, + pub end_pos: BytePos +} + +// Given a slice of line start positions and a position, returns the index of +// the line the position is on. Returns -1 if the position is located before +// the first line. +fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize { + match lines.binary_search(&pos) { + Ok(line) => line as isize, + Err(line) => line as isize - 1 + } +} + +#[cfg(test)] +mod tests { + use super::{lookup_line, BytePos}; + + #[test] + fn test_lookup_line() { + + let lines = &[BytePos(3), BytePos(17), BytePos(28)]; + + assert_eq!(lookup_line(lines, BytePos(0)), -1); + assert_eq!(lookup_line(lines, BytePos(3)), 0); + assert_eq!(lookup_line(lines, BytePos(4)), 0); + + assert_eq!(lookup_line(lines, BytePos(16)), 0); + assert_eq!(lookup_line(lines, BytePos(17)), 1); + assert_eq!(lookup_line(lines, BytePos(18)), 1); + + assert_eq!(lookup_line(lines, BytePos(28)), 2); + assert_eq!(lookup_line(lines, BytePos(29)), 2); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/.cargo-checksum.json b/bash-5.1/vendor/syntex_syntax/.cargo-checksum.json new file mode 100644 index 0000000..99a3087 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"ed5a74058ed7922d5c0cd841003054b358dd1c1e16bd1854503a91b2af446317","src/abi.rs":"f2d06309ef3cfa116dccf961ca7caa4fecfa573825deca5e50c410fb986d50d5","src/ast.rs":"a45698b20d4ba82c34047fb8e68018830c0c1669e8a8ce86f9f6c68cdbdf17a1","src/attr.rs":"d481cd2b400992d6b07c7ea070a3629442051e8d8541d61a90feaa8c0de3f289","src/codemap.rs":"a2d47cb66467d3febb2c8842e7ae9a7934351b7bd9eeb21762e4f3f7db2b624e","src/config.rs":"6088f23b4ec32a9e1de38e3ffcacfa0c806cde94f1729b21f20b2b9983d83287","src/diagnostic_list.rs":"69240654107a937e38d030907323cfd7fa9542f5af5e1a77af03c47022ceb3ac","src/diagnostics/macros.rs":"81c36c9164ef238407540f7b026ae12117eb551630ae522c55a90ff9d01fff62","src/diagnostics/metadata.rs":"55570cb118892c25d98f1c120903caa88b212d83eee846594bf32d30245a00aa","src/diagnostics/plugin.rs":"920fbb6404b714318eb83f875fa1cd8cde765607c818116d3beeddc397d7ee97","src/entry.rs":"a75ebd163348ea408d4888677a9298e369b8b91a7a377a9eab5eae045128a035","src/ext/base.rs":"2bc79c0a30549d9ec2dd336023994ce5861bd5c3fdccf2ce38f4f0afaf694b8f","src/ext/build.rs":"ee1cc3ce999eae3767ad46b9207f21c6a5ac1ccc8fa172424347bebc7b012fd7","src/ext/decorator.rs":"d7cb4b233eb77988664cb80202aa2d3abab05b155da125b0f06449df996030af","src/ext/env.rs":"ecb9803589052bb4c7be18f813fdb934094ee939f07b608f880eb0ae6e160b2e","src/ext/expand.rs":"156860e7f79d37537f303caa1f52bca82118a53b5e728824c9f26057ef79b319","src/ext/hygiene.rs":"8766603dabbc52b3d5c8cffbf7781c1e365f7d5769faba307c759b296bfb82d8","src/ext/placeholders.rs":"50369498e363dd7fdf27cf2ca7def4d83dddd069a885de7fad875b10b880b096","src/ext/proc_macro_shim.rs":"263e9d6ea32041765e6de84c9b1e7d9cc62b634421935aa7b143ab8e4a53d9f1","src/ext/quote.rs":"c6a4a781cb1a9e2c3799c8a9ef32e2200ea9f6a1d4fd9270964c5f0aaedf7f34","src/ext/source_util.rs":"a3e85ed7af1d8b5e51d64aa3d97ca399787301aba8565ddb2aed3f8a8029896a","src/ext/tt/macro_parser.rs":"f63abcdabb24c948a37ec1b28d1b99f5f476b0a81f1b182a92851c1805fbf953","src/ext/tt/macro_rules.rs":"d9b54e9180f150356db296c2e7b999c06e456b36a300b77478bc0441277eadfa","src/ext/tt/transcribe.rs":"9b1a3248b38b205661502bb93397dfe2f15b1620d865fc4d5720dae6e5a1e7e3","src/feature_gate.rs":"b5ac00d9559b9c167325a8b9f3c3762aca4d7563c101fe774177eeca263aa38e","src/fold.rs":"e0ebe13db46836f5ea2fd07c7f5cc2c2ae2fe22798247e4ae2f0156acf3329a1","src/json.rs":"8c93c81515a127c8f780d27bded4968ed17f5b6fcc909319cac8d6b098e24bd9","src/lib.rs":"ae244be362e1c2990f1c7a925d72ad9f22f7c6e9a98f8aa1395132df6182932f","src/parse/attr.rs":"d7003d982c33480f966b4a567c0575add01577268774d250f74a369af2c94021","src/parse/classify.rs":"4e859c566e98bc11e7cc05f3b5f7f7a67caa6c53b8b10366eaf32e58bcfdc7ca","src/parse/common.rs":"f231aece27f62694d1146c5b40b24daf8e0e2e0152b159ca6693a8f583679f43","src/parse/lexer/comments.rs":"d6b1b4a723032a27d65128df823d8e97d1512dbbdb363dc7556c1abe01cce0fc","src/parse/lexer/mod.rs":"5db51fa14517a04aa5aa808fab94f2039c10fa7d8225ada85fd478db792c2124","src/parse/lexer/unicode_chars.rs":"92bdf17f281215b5b98e5d7ec8528142e7c04eaa7dba87c3b87b189a39161c63","src/parse/mod.rs":"107f49adb8ceafec6dc38feae4be083f0642fb7752b6bcd7d08f1034365a9604","src/parse/obsolete.rs":"cd83ee6f4a01086b736594638492969c6cec9522527fc576886186b9ad6cff03","src/parse/parser.rs":"beae4fbb842248e14798afc3b1d4f7a3eb632ff47c48505a77725036dfd8c2da","src/parse/token.rs":"9a9736da506848753ec755f40b1340ebd7114862d90518dc9f43c1c831f29987","src/print/pp.rs":"ef6752db3a36c7a614d43d767c788985a78f33e120b39a85e2156a576630afd4","src/print/pprust.rs":"fec3f7fa9f0bd24d466397952016fc70f70f1787c25a4a68509abe405ffa0c2b","src/ptr.rs":"2f0ecadd1d19b1e11bb067cee99ac6fff7c48dd33222ed67fb61f240e1ca820e","src/show_span.rs":"b55effca7a512b9705e793f092ca1b5af5842f5484ab61660a546b04dd10eb4f","src/std_inject.rs":"5a4b0f451f3dc23c2d6021b435f801bb2b95a485f0b53acb446535b4d4497034","src/str.rs":"023289c93979354cf6074e94327e5c71b5144e0d12042304c0c91b9dd974b26f","src/symbol.rs":"fdc04df4a729a17bc07860635e0d2c0206dc5c6eed19cad587bc6d1a0d74c69a","src/test.rs":"a8eef2643a2b30204240606d4c1673478c38407b1111a5794cce4e9b7954cd84","src/test_snippet.rs":"893a02a5e725286750bf1d0851cbe38edf746fecf18dbfe5e3dd95e939f50bfd","src/tokenstream.rs":"abc6d96fb98b2577780b9d1290ab830a36a52f8f3196736f32e39036745c030e","src/util/lev_distance.rs":"323704c761cd216568f70b2131c6010a5a68dc978a24dc3b2dcf17a4361599c0","src/util/move_map.rs":"8bf1a3546325872892ca5d4f04771af01566913d84fa678df7c862fda75fa16c","src/util/node_count.rs":"54268f87eb4d692b11362f1ef2021e8c7c63aa14f383711780d76216eeb5ee0f","src/util/parser.rs":"0aeb1cc7cbec319a8955e696cf46820ab9af7c89691dea2e2285ebb8a299a67d","src/util/parser_testing.rs":"cc500701e79628503dce4af4e792407460247e5caf5f781b83a74b157c1c79fa","src/util/small_vector.rs":"5f3de1a28196c60ff2efdbf0f61056de30aafc64b827531c3bb735b0bebed52f","src/util/thin_vec.rs":"eda6e0ab93dce5e45bb7a2ddeae9120fdb0df3c1d6a5d4e0c8ca3648d404177e","src/visit.rs":"c9061c24cf819373d0c3fac0671159ef3272054d2d1dd0ae2378eb915eb6d456"},"package":"dc960085bae44591e22d01f6c0e82a8aec832f8659aca556cdf8ecbdac2bb47b"} \ No newline at end of file diff --git a/bash-5.1/vendor/syntex_syntax/Cargo.toml b/bash-5.1/vendor/syntex_syntax/Cargo.toml new file mode 100644 index 0000000..0ea6d86 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "syntex_syntax" +version = "0.54.0" +authors = [ "erick.tryzelaar@gmail.com" ] +license = "MIT/Apache-2.0" +description = "Export of libsyntax for code generation" +repository = "https://github.com/serde-rs/syntex" +include = ["Cargo.toml", "src/**/*.rs"] + +[dependencies] +bitflags = "^0.7.0" +libc = "^0.2.13" +log = "^0.3.6" +rustc-serialize = "^0.3.16" +syntex_errors = { version = "^0.54.0", path = "../syntex_errors" } +syntex_pos = { version = "^0.54.0", path = "../syntex_pos" } +term = "^0.4.4" +unicode-xid = "^0.0.4" diff --git a/bash-5.1/vendor/syntex_syntax/src/abi.rs b/bash-5.1/vendor/syntex_syntax/src/abi.rs new file mode 100644 index 0000000..75554f2 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/abi.rs @@ -0,0 +1,178 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[allow(non_camel_case_types)] +pub enum Os { + Windows, + Macos, + Linux, + Android, + Freebsd, + iOS, + Dragonfly, + Bitrig, + Netbsd, + Openbsd, + NaCl, + Haiku, + Solaris, +} + +#[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy, Debug)] +pub enum Abi { + // NB: This ordering MUST match the AbiDatas array below. + // (This is ensured by the test indices_are_correct().) + + // Single platform ABIs + Cdecl, + Stdcall, + Fastcall, + Vectorcall, + Aapcs, + Win64, + SysV64, + PtxKernel, + + // Multiplatform / generic ABIs + Rust, + C, + System, + RustIntrinsic, + RustCall, + PlatformIntrinsic, + Unadjusted +} + +#[allow(non_camel_case_types)] +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum Architecture { + X86, + X86_64, + Arm, + Mips, + Mipsel +} + +#[derive(Copy, Clone)] +pub struct AbiData { + abi: Abi, + + /// Name of this ABI as we like it called. + name: &'static str, + + /// A generic ABI is supported on all platforms. + generic: bool, +} + +#[allow(non_upper_case_globals)] +const AbiDatas: &'static [AbiData] = &[ + // Platform-specific ABIs + AbiData {abi: Abi::Cdecl, name: "cdecl", generic: false }, + AbiData {abi: Abi::Stdcall, name: "stdcall", generic: false }, + AbiData {abi: Abi::Fastcall, name: "fastcall", generic: false }, + AbiData {abi: Abi::Vectorcall, name: "vectorcall", generic: false}, + AbiData {abi: Abi::Aapcs, name: "aapcs", generic: false }, + AbiData {abi: Abi::Win64, name: "win64", generic: false }, + AbiData {abi: Abi::SysV64, name: "sysv64", generic: false }, + AbiData {abi: Abi::PtxKernel, name: "ptx-kernel", generic: false }, + + // Cross-platform ABIs + AbiData {abi: Abi::Rust, name: "Rust", generic: true }, + AbiData {abi: Abi::C, name: "C", generic: true }, + AbiData {abi: Abi::System, name: "system", generic: true }, + AbiData {abi: Abi::RustIntrinsic, name: "rust-intrinsic", generic: true }, + AbiData {abi: Abi::RustCall, name: "rust-call", generic: true }, + AbiData {abi: Abi::PlatformIntrinsic, name: "platform-intrinsic", generic: true }, + AbiData {abi: Abi::Unadjusted, name: "unadjusted", generic: true }, +]; + +/// Returns the ABI with the given name (if any). +pub fn lookup(name: &str) -> Option<Abi> { + AbiDatas.iter().find(|abi_data| name == abi_data.name).map(|&x| x.abi) +} + +pub fn all_names() -> Vec<&'static str> { + AbiDatas.iter().map(|d| d.name).collect() +} + +impl Abi { + #[inline] + pub fn index(&self) -> usize { + *self as usize + } + + #[inline] + pub fn data(&self) -> &'static AbiData { + &AbiDatas[self.index()] + } + + pub fn name(&self) -> &'static str { + self.data().name + } + + pub fn generic(&self) -> bool { + self.data().generic + } +} + +impl fmt::Display for Abi { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "\"{}\"", self.name()) + } +} + +impl fmt::Display for Os { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Os::Linux => "linux".fmt(f), + Os::Windows => "windows".fmt(f), + Os::Macos => "macos".fmt(f), + Os::iOS => "ios".fmt(f), + Os::Android => "android".fmt(f), + Os::Freebsd => "freebsd".fmt(f), + Os::Dragonfly => "dragonfly".fmt(f), + Os::Bitrig => "bitrig".fmt(f), + Os::Netbsd => "netbsd".fmt(f), + Os::Openbsd => "openbsd".fmt(f), + Os::NaCl => "nacl".fmt(f), + Os::Haiku => "haiku".fmt(f), + Os::Solaris => "solaris".fmt(f), + } + } +} + +#[allow(non_snake_case)] +#[test] +fn lookup_Rust() { + let abi = lookup("Rust"); + assert!(abi.is_some() && abi.unwrap().data().name == "Rust"); +} + +#[test] +fn lookup_cdecl() { + let abi = lookup("cdecl"); + assert!(abi.is_some() && abi.unwrap().data().name == "cdecl"); +} + +#[test] +fn lookup_baz() { + let abi = lookup("baz"); + assert!(abi.is_none()); +} + +#[test] +fn indices_are_correct() { + for (i, abi_data) in AbiDatas.iter().enumerate() { + assert_eq!(i, abi_data.abi.index()); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ast.rs b/bash-5.1/vendor/syntex_syntax/src/ast.rs new file mode 100644 index 0000000..c5f1f45 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ast.rs @@ -0,0 +1,1924 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// The Rust abstract syntax tree. + +pub use self::TyParamBound::*; +pub use self::UnsafeSource::*; +pub use self::ViewPath_::*; +pub use self::PathParameters::*; +pub use symbol::Symbol as Name; +pub use util::ThinVec; + +use syntax_pos::{mk_sp, Span, DUMMY_SP, ExpnId}; +use codemap::{respan, Spanned}; +use abi::Abi; +use ext::hygiene::SyntaxContext; +use print::pprust; +use ptr::P; +use symbol::{Symbol, keywords}; +use tokenstream::{TokenTree}; + +use std::collections::HashSet; +use std::fmt; +use std::rc::Rc; +use std::u32; + +use serialize::{self, Encodable, Decodable, Encoder, Decoder}; + +/// An identifier contains a Name (index into the interner +/// table) and a SyntaxContext to track renaming and +/// macro expansion per Flatt et al., "Macros That Work Together" +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct Ident { + pub name: Symbol, + pub ctxt: SyntaxContext +} + +impl Ident { + pub fn with_empty_ctxt(name: Name) -> Ident { + Ident { name: name, ctxt: SyntaxContext::empty() } + } + + /// Maps a string to an identifier with an empty syntax context. + pub fn from_str(s: &str) -> Ident { + Ident::with_empty_ctxt(Symbol::intern(s)) + } + + pub fn unhygienize(&self) -> Ident { + Ident { name: self.name, ctxt: SyntaxContext::empty() } + } +} + +impl fmt::Debug for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}{:?}", self.name, self.ctxt) + } +} + +impl fmt::Display for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.name, f) + } +} + +impl Encodable for Ident { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + self.name.encode(s) + } +} + +impl Decodable for Ident { + fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> { + Ok(Ident::with_empty_ctxt(try!(Name::decode(d)))) + } +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +pub struct Lifetime { + pub id: NodeId, + pub span: Span, + pub name: Name +} + +impl fmt::Debug for Lifetime { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self)) + } +} + +/// A lifetime definition, e.g. `'a: 'b+'c+'d` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct LifetimeDef { + pub attrs: ThinVec<Attribute>, + pub lifetime: Lifetime, + pub bounds: Vec<Lifetime> +} + +/// A "Path" is essentially Rust's notion of a name. +/// +/// It's represented as a sequence of identifiers, +/// along with a bunch of supporting information. +/// +/// E.g. `std::cmp::PartialEq` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub struct Path { + pub span: Span, + /// The segments in the path: the things separated by `::`. + /// Global paths begin with `keywords::CrateRoot`. + pub segments: Vec<PathSegment>, +} + +impl fmt::Debug for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "path({})", pprust::path_to_string(self)) + } +} + +impl fmt::Display for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", pprust::path_to_string(self)) + } +} + +impl Path { + // convert a span and an identifier to the corresponding + // 1-segment path + pub fn from_ident(s: Span, identifier: Ident) -> Path { + Path { + span: s, + segments: vec![identifier.into()], + } + } + + pub fn default_to_global(mut self) -> Path { + let name = self.segments[0].identifier.name; + if !self.is_global() && name != "$crate" && + name != keywords::SelfValue.name() && name != keywords::Super.name() { + self.segments.insert(0, PathSegment::crate_root()); + } + self + } + + pub fn is_global(&self) -> bool { + !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name() + } +} + +/// A segment of a path: an identifier, an optional lifetime, and a set of types. +/// +/// E.g. `std`, `String` or `Box<T>` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct PathSegment { + /// The identifier portion of this path segment. + pub identifier: Ident, + + /// Type/lifetime parameters attached to this path. They come in + /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that + /// this is more than just simple syntactic sugar; the use of + /// parens affects the region binding rules, so we preserve the + /// distinction. + /// The `Option<P<..>>` wrapper is purely a size optimization; + /// `None` is used to represent both `Path` and `Path<>`. + pub parameters: Option<P<PathParameters>>, +} + +impl From<Ident> for PathSegment { + fn from(id: Ident) -> Self { + PathSegment { identifier: id, parameters: None } + } +} + +impl PathSegment { + pub fn crate_root() -> Self { + PathSegment { + identifier: keywords::CrateRoot.ident(), + parameters: None, + } + } +} + +/// Parameters of a path segment. +/// +/// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum PathParameters { + /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>` + AngleBracketed(AngleBracketedParameterData), + /// The `(A,B)` and `C` in `Foo(A,B) -> C` + Parenthesized(ParenthesizedParameterData), +} + +/// A path like `Foo<'a, T>` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)] +pub struct AngleBracketedParameterData { + /// The lifetime parameters for this path segment. + pub lifetimes: Vec<Lifetime>, + /// The type parameters for this path segment, if present. + pub types: P<[P<Ty>]>, + /// Bindings (equality constraints) on associated types, if present. + /// + /// E.g., `Foo<A=Bar>`. + pub bindings: P<[TypeBinding]>, +} + +impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData { + fn into(self) -> Option<P<PathParameters>> { + let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty(); + if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) } + } +} + +/// A path like `Foo(A,B) -> C` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct ParenthesizedParameterData { + /// Overall span + pub span: Span, + + /// `(A,B)` + pub inputs: Vec<P<Ty>>, + + /// `C` + pub output: Option<P<Ty>>, +} + +#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)] +pub struct NodeId(u32); + +impl NodeId { + pub fn new(x: usize) -> NodeId { + assert!(x < (u32::MAX as usize)); + NodeId(x as u32) + } + + pub fn from_u32(x: u32) -> NodeId { + NodeId(x) + } + + pub fn as_usize(&self) -> usize { + self.0 as usize + } + + pub fn as_u32(&self) -> u32 { + self.0 + } +} + +impl fmt::Display for NodeId { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } +} + +impl serialize::Encodable for NodeId { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_u32(self.0) + } +} + +impl serialize::Decodable for NodeId { + fn decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> { + d.read_u32().map(NodeId) + } +} + +/// Node id used to represent the root of the crate. +pub const CRATE_NODE_ID: NodeId = NodeId(0); + +/// When parsing and doing expansions, we initially give all AST nodes this AST +/// node value. Then later, in the renumber pass, we renumber them to have +/// small, positive ids. +pub const DUMMY_NODE_ID: NodeId = NodeId(!0); + +/// The AST represents all type param bounds as types. +/// typeck::collect::compute_bounds matches these against +/// the "special" built-in traits (see middle::lang_items) and +/// detects Copy, Send and Sync. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum TyParamBound { + TraitTyParamBound(PolyTraitRef, TraitBoundModifier), + RegionTyParamBound(Lifetime) +} + +/// A modifier on a bound, currently this is only used for `?Sized`, where the +/// modifier is `Maybe`. Negative bounds should also be handled here. +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum TraitBoundModifier { + None, + Maybe, +} + +pub type TyParamBounds = P<[TyParamBound]>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct TyParam { + pub attrs: ThinVec<Attribute>, + pub ident: Ident, + pub id: NodeId, + pub bounds: TyParamBounds, + pub default: Option<P<Ty>>, + pub span: Span, +} + +/// Represents lifetimes and type parameters attached to a declaration +/// of a function, enum, trait, etc. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Generics { + pub lifetimes: Vec<LifetimeDef>, + pub ty_params: P<[TyParam]>, + pub where_clause: WhereClause, + pub span: Span, +} + +impl Generics { + pub fn is_lt_parameterized(&self) -> bool { + !self.lifetimes.is_empty() + } + pub fn is_type_parameterized(&self) -> bool { + !self.ty_params.is_empty() + } + pub fn is_parameterized(&self) -> bool { + self.is_lt_parameterized() || self.is_type_parameterized() + } + pub fn span_for_name(&self, name: &str) -> Option<Span> { + for t in &self.ty_params { + if t.ident.name == name { + return Some(t.span); + } + } + None + } +} + +impl Default for Generics { + /// Creates an instance of `Generics`. + fn default() -> Generics { + Generics { + lifetimes: Vec::new(), + ty_params: P::new(), + where_clause: WhereClause { + id: DUMMY_NODE_ID, + predicates: Vec::new(), + }, + span: DUMMY_SP, + } + } +} + +/// A `where` clause in a definition +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct WhereClause { + pub id: NodeId, + pub predicates: Vec<WherePredicate>, +} + +/// A single predicate in a `where` clause +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum WherePredicate { + /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c` + BoundPredicate(WhereBoundPredicate), + /// A lifetime predicate, e.g. `'a: 'b+'c` + RegionPredicate(WhereRegionPredicate), + /// An equality predicate (unsupported) + EqPredicate(WhereEqPredicate), +} + +/// A type bound. +/// +/// E.g. `for<'c> Foo: Send+Clone+'c` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct WhereBoundPredicate { + pub span: Span, + /// Any lifetimes from a `for` binding + pub bound_lifetimes: Vec<LifetimeDef>, + /// The type being bounded + pub bounded_ty: P<Ty>, + /// Trait and lifetime bounds (`Clone+Send+'static`) + pub bounds: TyParamBounds, +} + +/// A lifetime predicate. +/// +/// E.g. `'a: 'b+'c` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct WhereRegionPredicate { + pub span: Span, + pub lifetime: Lifetime, + pub bounds: Vec<Lifetime>, +} + +/// An equality predicate (unsupported). +/// +/// E.g. `T=int` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct WhereEqPredicate { + pub id: NodeId, + pub span: Span, + pub path: Path, + pub ty: P<Ty>, +} + +/// The set of MetaItems that define the compilation environment of the crate, +/// used to drive conditional compilation +pub type CrateConfig = HashSet<(Name, Option<Symbol>)>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Crate { + pub module: Mod, + pub attrs: Vec<Attribute>, + pub span: Span, + pub exported_macros: Vec<MacroDef>, +} + +/// A spanned compile-time attribute list item. +pub type NestedMetaItem = Spanned<NestedMetaItemKind>; + +/// Possible values inside of compile-time attribute lists. +/// +/// E.g. the '..' in `#[name(..)]`. +#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)] +pub enum NestedMetaItemKind { + /// A full MetaItem, for recursive meta items. + MetaItem(MetaItem), + /// A literal. + /// + /// E.g. "foo", 64, true + Literal(Lit), +} + +/// A spanned compile-time attribute item. +/// +/// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct MetaItem { + pub name: Name, + pub node: MetaItemKind, + pub span: Span, +} + +/// A compile-time attribute item. +/// +/// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum MetaItemKind { + /// Word meta item. + /// + /// E.g. `test` as in `#[test]` + Word, + /// List meta item. + /// + /// E.g. `derive(..)` as in `#[derive(..)]` + List(Vec<NestedMetaItem>), + /// Name value meta item. + /// + /// E.g. `feature = "foo"` as in `#[feature = "foo"]` + NameValue(Lit) +} + +/// A Block (`{ .. }`). +/// +/// E.g. `{ .. }` as in `fn foo() { .. }` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Block { + /// Statements in a block + pub stmts: Vec<Stmt>, + pub id: NodeId, + /// Distinguishes between `unsafe { ... }` and `{ ... }` + pub rules: BlockCheckMode, + pub span: Span, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub struct Pat { + pub id: NodeId, + pub node: PatKind, + pub span: Span, +} + +impl fmt::Debug for Pat { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self)) + } +} + +impl Pat { + pub fn walk<F>(&self, it: &mut F) -> bool + where F: FnMut(&Pat) -> bool + { + if !it(self) { + return false; + } + + match self.node { + PatKind::Ident(_, _, Some(ref p)) => p.walk(it), + PatKind::Struct(_, ref fields, _) => { + fields.iter().all(|field| field.node.pat.walk(it)) + } + PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => { + s.iter().all(|p| p.walk(it)) + } + PatKind::Box(ref s) | PatKind::Ref(ref s, _) => { + s.walk(it) + } + PatKind::Slice(ref before, ref slice, ref after) => { + before.iter().all(|p| p.walk(it)) && + slice.iter().all(|p| p.walk(it)) && + after.iter().all(|p| p.walk(it)) + } + PatKind::Wild | + PatKind::Lit(_) | + PatKind::Range(..) | + PatKind::Ident(..) | + PatKind::Path(..) | + PatKind::Mac(_) => { + true + } + } + } +} + +/// A single field in a struct pattern +/// +/// Patterns like the fields of Foo `{ x, ref y, ref mut z }` +/// are treated the same as` x: x, y: ref y, z: ref mut z`, +/// except is_shorthand is true +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct FieldPat { + /// The identifier for the field + pub ident: Ident, + /// The pattern the field is destructured to + pub pat: P<Pat>, + pub is_shorthand: bool, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum BindingMode { + ByRef(Mutability), + ByValue(Mutability), +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum PatKind { + /// Represents a wildcard pattern (`_`) + Wild, + + /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`), + /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third + /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens + /// during name resolution. + Ident(BindingMode, SpannedIdent, Option<P<Pat>>), + + /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`. + /// The `bool` is `true` in the presence of a `..`. + Struct(Path, Vec<Spanned<FieldPat>>, bool), + + /// A tuple struct/variant pattern `Variant(x, y, .., z)`. + /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position. + /// 0 <= position <= subpats.len() + TupleStruct(Path, Vec<P<Pat>>, Option<usize>), + + /// A possibly qualified path pattern. + /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants + /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can + /// only legally refer to associated constants. + Path(Option<QSelf>, Path), + + /// A tuple pattern `(a, b)`. + /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position. + /// 0 <= position <= subpats.len() + Tuple(Vec<P<Pat>>, Option<usize>), + /// A `box` pattern + Box(P<Pat>), + /// A reference pattern, e.g. `&mut (a, b)` + Ref(P<Pat>, Mutability), + /// A literal + Lit(P<Expr>), + /// A range pattern, e.g. `1...2` + Range(P<Expr>, P<Expr>), + /// `[a, b, ..i, y, z]` is represented as: + /// `PatKind::Slice(box [a, b], Some(i), box [y, z])` + Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>), + /// A macro pattern; pre-expansion + Mac(Mac), +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum Mutability { + Mutable, + Immutable, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum BinOpKind { + /// The `+` operator (addition) + Add, + /// The `-` operator (subtraction) + Sub, + /// The `*` operator (multiplication) + Mul, + /// The `/` operator (division) + Div, + /// The `%` operator (modulus) + Rem, + /// The `&&` operator (logical and) + And, + /// The `||` operator (logical or) + Or, + /// The `^` operator (bitwise xor) + BitXor, + /// The `&` operator (bitwise and) + BitAnd, + /// The `|` operator (bitwise or) + BitOr, + /// The `<<` operator (shift left) + Shl, + /// The `>>` operator (shift right) + Shr, + /// The `==` operator (equality) + Eq, + /// The `<` operator (less than) + Lt, + /// The `<=` operator (less than or equal to) + Le, + /// The `!=` operator (not equal to) + Ne, + /// The `>=` operator (greater than or equal to) + Ge, + /// The `>` operator (greater than) + Gt, +} + +impl BinOpKind { + pub fn to_string(&self) -> &'static str { + use self::BinOpKind::*; + match *self { + Add => "+", + Sub => "-", + Mul => "*", + Div => "/", + Rem => "%", + And => "&&", + Or => "||", + BitXor => "^", + BitAnd => "&", + BitOr => "|", + Shl => "<<", + Shr => ">>", + Eq => "==", + Lt => "<", + Le => "<=", + Ne => "!=", + Ge => ">=", + Gt => ">", + } + } + pub fn lazy(&self) -> bool { + match *self { + BinOpKind::And | BinOpKind::Or => true, + _ => false + } + } + + pub fn is_shift(&self) -> bool { + match *self { + BinOpKind::Shl | BinOpKind::Shr => true, + _ => false + } + } + pub fn is_comparison(&self) -> bool { + use self::BinOpKind::*; + match *self { + Eq | Lt | Le | Ne | Gt | Ge => + true, + And | Or | Add | Sub | Mul | Div | Rem | + BitXor | BitAnd | BitOr | Shl | Shr => + false, + } + } + /// Returns `true` if the binary operator takes its arguments by value + pub fn is_by_value(&self) -> bool { + !self.is_comparison() + } +} + +pub type BinOp = Spanned<BinOpKind>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum UnOp { + /// The `*` operator for dereferencing + Deref, + /// The `!` operator for logical inversion + Not, + /// The `-` operator for negation + Neg, +} + +impl UnOp { + /// Returns `true` if the unary operator takes its argument by value + pub fn is_by_value(u: UnOp) -> bool { + match u { + UnOp::Neg | UnOp::Not => true, + _ => false, + } + } + + pub fn to_string(op: UnOp) -> &'static str { + match op { + UnOp::Deref => "*", + UnOp::Not => "!", + UnOp::Neg => "-", + } + } +} + +/// A statement +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub struct Stmt { + pub id: NodeId, + pub node: StmtKind, + pub span: Span, +} + +impl Stmt { + pub fn add_trailing_semicolon(mut self) -> Self { + self.node = match self.node { + StmtKind::Expr(expr) => StmtKind::Semi(expr), + StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| { + (mac, MacStmtStyle::Semicolon, attrs) + })), + node @ _ => node, + }; + self + } +} + +impl fmt::Debug for Stmt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self)) + } +} + + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub enum StmtKind { + /// A local (let) binding. + Local(P<Local>), + + /// An item definition. + Item(P<Item>), + + /// Expr without trailing semi-colon. + Expr(P<Expr>), + + Semi(P<Expr>), + + Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>), +} + +#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum MacStmtStyle { + /// The macro statement had a trailing semicolon, e.g. `foo! { ... };` + /// `foo!(...);`, `foo![...];` + Semicolon, + /// The macro statement had braces; e.g. foo! { ... } + Braces, + /// The macro statement had parentheses or brackets and no semicolon; e.g. + /// `foo!(...)`. All of these will end up being converted into macro + /// expressions. + NoBraces, +} + +// FIXME (pending discussion of #1697, #2178...): local should really be +// a refinement on pat. +/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Local { + pub pat: P<Pat>, + pub ty: Option<P<Ty>>, + /// Initializer expression to set the value, if any + pub init: Option<P<Expr>>, + pub id: NodeId, + pub span: Span, + pub attrs: ThinVec<Attribute>, +} + +/// An arm of a 'match'. +/// +/// E.g. `0...10 => { println!("match!") }` as in +/// +/// ```rust,ignore +/// match n { +/// 0...10 => { println!("match!") }, +/// // .. +/// } +/// ``` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Arm { + pub attrs: Vec<Attribute>, + pub pats: Vec<P<Pat>>, + pub guard: Option<P<Expr>>, + pub body: P<Expr>, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Field { + pub ident: SpannedIdent, + pub expr: P<Expr>, + pub span: Span, + pub is_shorthand: bool, +} + +pub type SpannedIdent = Spanned<Ident>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum BlockCheckMode { + Default, + Unsafe(UnsafeSource), +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum UnsafeSource { + CompilerGenerated, + UserProvided, +} + +/// An expression +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)] +pub struct Expr { + pub id: NodeId, + pub node: ExprKind, + pub span: Span, + pub attrs: ThinVec<Attribute> +} + +impl fmt::Debug for Expr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self)) + } +} + +/// Limit types of a range (inclusive or exclusive) +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum RangeLimits { + /// Inclusive at the beginning, exclusive at the end + HalfOpen, + /// Inclusive at the beginning and end + Closed, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum ExprKind { + /// A `box x` expression. + Box(P<Expr>), + /// First expr is the place; second expr is the value. + InPlace(P<Expr>, P<Expr>), + /// An array (`[a, b, c, d]`) + Vec(Vec<P<Expr>>), + /// A function call + /// + /// The first field resolves to the function itself, + /// and the second field is the list of arguments + Call(P<Expr>, Vec<P<Expr>>), + /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`) + /// + /// The `SpannedIdent` is the identifier for the method name. + /// The vector of `Ty`s are the ascripted type parameters for the method + /// (within the angle brackets). + /// + /// The first element of the vector of `Expr`s is the expression that evaluates + /// to the object on which the method is being called on (the receiver), + /// and the remaining elements are the rest of the arguments. + /// + /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as + /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`. + MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>), + /// A tuple (`(a, b, c ,d)`) + Tup(Vec<P<Expr>>), + /// A binary operation (For example: `a + b`, `a * b`) + Binary(BinOp, P<Expr>, P<Expr>), + /// A unary operation (For example: `!x`, `*x`) + Unary(UnOp, P<Expr>), + /// A literal (For example: `1`, `"foo"`) + Lit(P<Lit>), + /// A cast (`foo as f64`) + Cast(P<Expr>, P<Ty>), + Type(P<Expr>, P<Ty>), + /// An `if` block, with an optional else block + /// + /// `if expr { block } else { expr }` + If(P<Expr>, P<Block>, Option<P<Expr>>), + /// An `if let` expression with an optional else block + /// + /// `if let pat = expr { block } else { expr }` + /// + /// This is desugared to a `match` expression. + IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>), + /// A while loop, with an optional label + /// + /// `'label: while expr { block }` + While(P<Expr>, P<Block>, Option<SpannedIdent>), + /// A while-let loop, with an optional label + /// + /// `'label: while let pat = expr { block }` + /// + /// This is desugared to a combination of `loop` and `match` expressions. + WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>), + /// A for loop, with an optional label + /// + /// `'label: for pat in expr { block }` + /// + /// This is desugared to a combination of `loop` and `match` expressions. + ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>), + /// Conditionless loop (can be exited with break, continue, or return) + /// + /// `'label: loop { block }` + Loop(P<Block>, Option<SpannedIdent>), + /// A `match` block. + Match(P<Expr>, Vec<Arm>), + /// A closure (for example, `move |a, b, c| a + b + c`) + /// + /// The final span is the span of the argument block `|...|` + Closure(CaptureBy, P<FnDecl>, P<Expr>, Span), + /// A block (`{ ... }`) + Block(P<Block>), + + /// An assignment (`a = foo()`) + Assign(P<Expr>, P<Expr>), + /// An assignment with an operator + /// + /// For example, `a += 1`. + AssignOp(BinOp, P<Expr>, P<Expr>), + /// Access of a named struct field (`obj.foo`) + Field(P<Expr>, SpannedIdent), + /// Access of an unnamed field of a struct or tuple-struct + /// + /// For example, `foo.0`. + TupField(P<Expr>, Spanned<usize>), + /// An indexing operation (`foo[2]`) + Index(P<Expr>, P<Expr>), + /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`) + Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits), + + /// Variable reference, possibly containing `::` and/or type + /// parameters, e.g. foo::bar::<baz>. + /// + /// Optionally "qualified", + /// E.g. `<Vec<T> as SomeTrait>::SomeType`. + Path(Option<QSelf>, Path), + + /// A referencing operation (`&a` or `&mut a`) + AddrOf(Mutability, P<Expr>), + /// A `break`, with an optional label to break, and an optional expression + Break(Option<SpannedIdent>, Option<P<Expr>>), + /// A `continue`, with an optional label + Continue(Option<SpannedIdent>), + /// A `return`, with an optional value to be returned + Ret(Option<P<Expr>>), + + /// Output of the `asm!()` macro + InlineAsm(P<InlineAsm>), + + /// A macro invocation; pre-expansion + Mac(Mac), + + /// A struct literal expression. + /// + /// For example, `Foo {x: 1, y: 2}`, or + /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`. + Struct(Path, Vec<Field>, Option<P<Expr>>), + + /// An array literal constructed from one repeated element. + /// + /// For example, `[1; 5]`. The first expression is the element + /// to be repeated; the second is the number of times to repeat it. + Repeat(P<Expr>, P<Expr>), + + /// No-op: used solely so we can pretty-print faithfully + Paren(P<Expr>), + + /// `expr?` + Try(P<Expr>), +} + +/// The explicit Self type in a "qualified path". The actual +/// path, including the trait and the associated item, is stored +/// separately. `position` represents the index of the associated +/// item qualified with this Self type. +/// +/// ```rust,ignore +/// <Vec<T> as a::b::Trait>::AssociatedItem +/// ^~~~~ ~~~~~~~~~~~~~~^ +/// ty position = 3 +/// +/// <Vec<T>>::AssociatedItem +/// ^~~~~ ^ +/// ty position = 0 +/// ``` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct QSelf { + pub ty: P<Ty>, + pub position: usize +} + +/// A capture clause +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum CaptureBy { + Value, + Ref, +} + +pub type Mac = Spanned<Mac_>; + +/// Represents a macro invocation. The Path indicates which macro +/// is being invoked, and the vector of token-trees contains the source +/// of the macro invocation. +/// +/// NB: the additional ident for a macro_rules-style macro is actually +/// stored in the enclosing item. Oog. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Mac_ { + pub path: Path, + pub tts: Vec<TokenTree>, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum StrStyle { + /// A regular string, like `"foo"` + Cooked, + /// A raw string, like `r##"foo"##` + /// + /// The uint is the number of `#` symbols used + Raw(usize) +} + +/// A literal +pub type Lit = Spanned<LitKind>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum LitIntType { + Signed(IntTy), + Unsigned(UintTy), + Unsuffixed, +} + +/// Literal kind. +/// +/// E.g. `"foo"`, `42`, `12.34` or `bool` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum LitKind { + /// A string literal (`"foo"`) + Str(Symbol, StrStyle), + /// A byte string (`b"foo"`) + ByteStr(Rc<Vec<u8>>), + /// A byte char (`b'f'`) + Byte(u8), + /// A character literal (`'a'`) + Char(char), + /// An integer literal (`1`) + Int(u64, LitIntType), + /// A float literal (`1f64` or `1E10f64`) + Float(Symbol, FloatTy), + /// A float literal without a suffix (`1.0 or 1.0E10`) + FloatUnsuffixed(Symbol), + /// A boolean literal + Bool(bool), +} + +impl LitKind { + /// Returns true if this literal is a string and false otherwise. + pub fn is_str(&self) -> bool { + match *self { + LitKind::Str(..) => true, + _ => false, + } + } + + /// Returns true if this literal has no suffix. Note: this will return true + /// for literals with prefixes such as raw strings and byte strings. + pub fn is_unsuffixed(&self) -> bool { + match *self { + // unsuffixed variants + LitKind::Str(..) => true, + LitKind::ByteStr(..) => true, + LitKind::Byte(..) => true, + LitKind::Char(..) => true, + LitKind::Int(_, LitIntType::Unsuffixed) => true, + LitKind::FloatUnsuffixed(..) => true, + LitKind::Bool(..) => true, + // suffixed variants + LitKind::Int(_, LitIntType::Signed(..)) => false, + LitKind::Int(_, LitIntType::Unsigned(..)) => false, + LitKind::Float(..) => false, + } + } + + /// Returns true if this literal has a suffix. + pub fn is_suffixed(&self) -> bool { + !self.is_unsuffixed() + } +} + +// NB: If you change this, you'll probably want to change the corresponding +// type structure in middle/ty.rs as well. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct MutTy { + pub ty: P<Ty>, + pub mutbl: Mutability, +} + +/// Represents a method's signature in a trait declaration, +/// or in an implementation. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct MethodSig { + pub unsafety: Unsafety, + pub constness: Spanned<Constness>, + pub abi: Abi, + pub decl: P<FnDecl>, + pub generics: Generics, +} + +/// Represents an item declaration within a trait declaration, +/// possibly including a default implementation. A trait item is +/// either required (meaning it doesn't have an implementation, just a +/// signature) or provided (meaning it has a default implementation). +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct TraitItem { + pub id: NodeId, + pub ident: Ident, + pub attrs: Vec<Attribute>, + pub node: TraitItemKind, + pub span: Span, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum TraitItemKind { + Const(P<Ty>, Option<P<Expr>>), + Method(MethodSig, Option<P<Block>>), + Type(TyParamBounds, Option<P<Ty>>), + Macro(Mac), +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct ImplItem { + pub id: NodeId, + pub ident: Ident, + pub vis: Visibility, + pub defaultness: Defaultness, + pub attrs: Vec<Attribute>, + pub node: ImplItemKind, + pub span: Span, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum ImplItemKind { + Const(P<Ty>, P<Expr>), + Method(MethodSig, P<Block>), + Type(P<Ty>), + Macro(Mac), +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +pub enum IntTy { + Is, + I8, + I16, + I32, + I64, + I128, +} + +impl fmt::Debug for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.ty_to_string()) + } +} + +impl IntTy { + pub fn ty_to_string(&self) -> &'static str { + match *self { + IntTy::Is => "isize", + IntTy::I8 => "i8", + IntTy::I16 => "i16", + IntTy::I32 => "i32", + IntTy::I64 => "i64", + IntTy::I128 => "i128", + } + } + + pub fn val_to_string(&self, val: i64) -> String { + // cast to a u64 so we can correctly print INT64_MIN. All integral types + // are parsed as u64, so we wouldn't want to print an extra negative + // sign. + format!("{}{}", val as u64, self.ty_to_string()) + } + + pub fn bit_width(&self) -> Option<usize> { + Some(match *self { + IntTy::Is => return None, + IntTy::I8 => 8, + IntTy::I16 => 16, + IntTy::I32 => 32, + IntTy::I64 => 64, + IntTy::I128 => 128, + }) + } +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +pub enum UintTy { + Us, + U8, + U16, + U32, + U64, + U128, +} + +impl UintTy { + pub fn ty_to_string(&self) -> &'static str { + match *self { + UintTy::Us => "usize", + UintTy::U8 => "u8", + UintTy::U16 => "u16", + UintTy::U32 => "u32", + UintTy::U64 => "u64", + UintTy::U128 => "u128", + } + } + + pub fn val_to_string(&self, val: u64) -> String { + format!("{}{}", val, self.ty_to_string()) + } + + pub fn bit_width(&self) -> Option<usize> { + Some(match *self { + UintTy::Us => return None, + UintTy::U8 => 8, + UintTy::U16 => 16, + UintTy::U32 => 32, + UintTy::U64 => 64, + UintTy::U128 => 128, + }) + } +} + +impl fmt::Debug for UintTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for UintTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.ty_to_string()) + } +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +pub enum FloatTy { + F32, + F64, +} + +impl fmt::Debug for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.ty_to_string()) + } +} + +impl FloatTy { + pub fn ty_to_string(&self) -> &'static str { + match *self { + FloatTy::F32 => "f32", + FloatTy::F64 => "f64", + } + } + + pub fn bit_width(&self) -> usize { + match *self { + FloatTy::F32 => 32, + FloatTy::F64 => 64, + } + } +} + +// Bind a type to an associated type: `A=Foo`. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct TypeBinding { + pub id: NodeId, + pub ident: Ident, + pub ty: P<Ty>, + pub span: Span, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub struct Ty { + pub id: NodeId, + pub node: TyKind, + pub span: Span, +} + +impl fmt::Debug for Ty { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "type({})", pprust::ty_to_string(self)) + } +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct BareFnTy { + pub unsafety: Unsafety, + pub abi: Abi, + pub lifetimes: Vec<LifetimeDef>, + pub decl: P<FnDecl> +} + +/// The different kinds of types recognized by the compiler +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum TyKind { + /// A variable-length slice (`[T]`) + Slice(P<Ty>), + /// A fixed length array (`[T; n]`) + Array(P<Ty>, P<Expr>), + /// A raw pointer (`*const T` or `*mut T`) + Ptr(MutTy), + /// A reference (`&'a T` or `&'a mut T`) + Rptr(Option<Lifetime>, MutTy), + /// A bare function (e.g. `fn(usize) -> bool`) + BareFn(P<BareFnTy>), + /// The never type (`!`) + Never, + /// A tuple (`(A, B, C, D,...)`) + Tup(Vec<P<Ty>> ), + /// A path (`module::module::...::Type`), optionally + /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`. + /// + /// Type parameters are stored in the Path itself + Path(Option<QSelf>, Path), + /// Something like `A+B`. Note that `B` must always be a path. + ObjectSum(P<Ty>, TyParamBounds), + /// A type like `for<'a> Foo<&'a Bar>` + PolyTraitRef(TyParamBounds), + /// An `impl TraitA+TraitB` type. + ImplTrait(TyParamBounds), + /// No-op; kept solely so that we can pretty-print faithfully + Paren(P<Ty>), + /// Unused for now + Typeof(P<Expr>), + /// TyKind::Infer means the type should be inferred instead of it having been + /// specified. This can appear anywhere in a type. + Infer, + /// Inferred type of a `self` or `&self` argument in a method. + ImplicitSelf, + // A macro in the type position. + Mac(Mac), +} + +/// Inline assembly dialect. +/// +/// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum AsmDialect { + Att, + Intel, +} + +/// Inline assembly. +/// +/// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct InlineAsmOutput { + pub constraint: Symbol, + pub expr: P<Expr>, + pub is_rw: bool, + pub is_indirect: bool, +} + +/// Inline assembly. +/// +/// E.g. `asm!("NOP");` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct InlineAsm { + pub asm: Symbol, + pub asm_str_style: StrStyle, + pub outputs: Vec<InlineAsmOutput>, + pub inputs: Vec<(Symbol, P<Expr>)>, + pub clobbers: Vec<Symbol>, + pub volatile: bool, + pub alignstack: bool, + pub dialect: AsmDialect, + pub expn_id: ExpnId, +} + +/// An argument in a function header. +/// +/// E.g. `bar: usize` as in `fn foo(bar: usize)` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Arg { + pub ty: P<Ty>, + pub pat: P<Pat>, + pub id: NodeId, +} + +/// Alternative representation for `Arg`s describing `self` parameter of methods. +/// +/// E.g. `&mut self` as in `fn foo(&mut self)` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum SelfKind { + /// `self`, `mut self` + Value(Mutability), + /// `&'lt self`, `&'lt mut self` + Region(Option<Lifetime>, Mutability), + /// `self: TYPE`, `mut self: TYPE` + Explicit(P<Ty>, Mutability), +} + +pub type ExplicitSelf = Spanned<SelfKind>; + +impl Arg { + pub fn to_self(&self) -> Option<ExplicitSelf> { + if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node { + if ident.node.name == keywords::SelfValue.name() { + return match self.ty.node { + TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))), + TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => { + Some(respan(self.pat.span, SelfKind::Region(lt, mutbl))) + } + _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi), + SelfKind::Explicit(self.ty.clone(), mutbl))), + } + } + } + None + } + + pub fn is_self(&self) -> bool { + if let PatKind::Ident(_, ident, _) = self.pat.node { + ident.node.name == keywords::SelfValue.name() + } else { + false + } + } + + pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg { + let span = mk_sp(eself.span.lo, eself_ident.span.hi); + let infer_ty = P(Ty { + id: DUMMY_NODE_ID, + node: TyKind::ImplicitSelf, + span: span, + }); + let arg = |mutbl, ty| Arg { + pat: P(Pat { + id: DUMMY_NODE_ID, + node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None), + span: span, + }), + ty: ty, + id: DUMMY_NODE_ID, + }; + match eself.node { + SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty), + SelfKind::Value(mutbl) => arg(mutbl, infer_ty), + SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty { + id: DUMMY_NODE_ID, + node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }), + span: span, + })), + } + } +} + +/// Header (not the body) of a function declaration. +/// +/// E.g. `fn foo(bar: baz)` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct FnDecl { + pub inputs: Vec<Arg>, + pub output: FunctionRetTy, + pub variadic: bool +} + +impl FnDecl { + pub fn get_self(&self) -> Option<ExplicitSelf> { + self.inputs.get(0).and_then(Arg::to_self) + } + pub fn has_self(&self) -> bool { + self.inputs.get(0).map(Arg::is_self).unwrap_or(false) + } +} + +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum Unsafety { + Unsafe, + Normal, +} + +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum Constness { + Const, + NotConst, +} + +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum Defaultness { + Default, + Final, +} + +impl fmt::Display for Unsafety { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(match *self { + Unsafety::Normal => "normal", + Unsafety::Unsafe => "unsafe", + }, f) + } +} + +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub enum ImplPolarity { + /// `impl Trait for Type` + Positive, + /// `impl !Trait for Type` + Negative, +} + +impl fmt::Debug for ImplPolarity { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + ImplPolarity::Positive => "positive".fmt(f), + ImplPolarity::Negative => "negative".fmt(f), + } + } +} + + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum FunctionRetTy { + /// Return type is not specified. + /// + /// Functions default to `()` and + /// closures default to inference. Span points to where return + /// type would be inserted. + Default(Span), + /// Everything else + Ty(P<Ty>), +} + +impl FunctionRetTy { + pub fn span(&self) -> Span { + match *self { + FunctionRetTy::Default(span) => span, + FunctionRetTy::Ty(ref ty) => ty.span, + } + } +} + +/// Module declaration. +/// +/// E.g. `mod foo;` or `mod foo { .. }` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Mod { + /// A span from the first token past `{` to the last token until `}`. + /// For `mod foo;`, the inner span ranges from the first token + /// to the last token in the external file. + pub inner: Span, + pub items: Vec<P<Item>>, +} + +/// Foreign module declaration. +/// +/// E.g. `extern { .. }` or `extern C { .. }` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct ForeignMod { + pub abi: Abi, + pub items: Vec<ForeignItem>, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct EnumDef { + pub variants: Vec<Variant>, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Variant_ { + pub name: Ident, + pub attrs: Vec<Attribute>, + pub data: VariantData, + /// Explicit discriminant, e.g. `Foo = 1` + pub disr_expr: Option<P<Expr>>, +} + +pub type Variant = Spanned<Variant_>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub struct PathListItem_ { + pub name: Ident, + /// renamed in list, e.g. `use foo::{bar as baz};` + pub rename: Option<Ident>, + pub id: NodeId, +} + +pub type PathListItem = Spanned<PathListItem_>; + +pub type ViewPath = Spanned<ViewPath_>; + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum ViewPath_ { + + /// `foo::bar::baz as quux` + /// + /// or just + /// + /// `foo::bar::baz` (with `as baz` implicitly on the right) + ViewPathSimple(Ident, Path), + + /// `foo::bar::*` + ViewPathGlob(Path), + + /// `foo::bar::{a,b,c}` + ViewPathList(Path, Vec<PathListItem>) +} + +impl ViewPath_ { + pub fn path(&self) -> &Path { + match *self { + ViewPathSimple(_, ref path) | + ViewPathGlob (ref path) | + ViewPathList(ref path, _) => path + } + } +} + + +/// Distinguishes between Attributes that decorate items and Attributes that +/// are contained as statements within items. These two cases need to be +/// distinguished for pretty-printing. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum AttrStyle { + Outer, + Inner, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub struct AttrId(pub usize); + +/// Meta-data associated with an item +/// Doc-comments are promoted to attributes that have is_sugared_doc = true +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Attribute { + pub id: AttrId, + pub style: AttrStyle, + pub value: MetaItem, + pub is_sugared_doc: bool, + pub span: Span, +} + +/// TraitRef's appear in impls. +/// +/// resolve maps each TraitRef's ref_id to its defining trait; that's all +/// that the ref_id is for. The impl_id maps to the "self type" of this impl. +/// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the +/// same as the impl's node id). +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct TraitRef { + pub path: Path, + pub ref_id: NodeId, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct PolyTraitRef { + /// The `'a` in `<'a> Foo<&'a T>` + pub bound_lifetimes: Vec<LifetimeDef>, + + /// The `Foo<&'a T>` in `<'a> Foo<&'a T>` + pub trait_ref: TraitRef, + + pub span: Span, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum Visibility { + Public, + Crate(Span), + Restricted { path: P<Path>, id: NodeId }, + Inherited, +} + +/// Field of a struct. +/// +/// E.g. `bar: usize` as in `struct Foo { bar: usize }` +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct StructField { + pub span: Span, + pub ident: Option<Ident>, + pub vis: Visibility, + pub id: NodeId, + pub ty: P<Ty>, + pub attrs: Vec<Attribute>, +} + +/// Fields and Ids of enum variants and structs +/// +/// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all +/// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants). +/// One shared Id can be successfully used for these two purposes. +/// Id of the whole enum lives in `Item`. +/// +/// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually +/// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of +/// the variant itself" from enum variants. +/// Id of the whole struct lives in `Item`. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum VariantData { + /// Struct variant. + /// + /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }` + Struct(Vec<StructField>, NodeId), + /// Tuple variant. + /// + /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }` + Tuple(Vec<StructField>, NodeId), + /// Unit variant. + /// + /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }` + Unit(NodeId), +} + +impl VariantData { + pub fn fields(&self) -> &[StructField] { + match *self { + VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields, + _ => &[], + } + } + pub fn id(&self) -> NodeId { + match *self { + VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id + } + } + pub fn is_struct(&self) -> bool { + if let VariantData::Struct(..) = *self { true } else { false } + } + pub fn is_tuple(&self) -> bool { + if let VariantData::Tuple(..) = *self { true } else { false } + } + pub fn is_unit(&self) -> bool { + if let VariantData::Unit(..) = *self { true } else { false } + } +} + +/// An item +/// +/// The name might be a dummy name in case of anonymous items +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Item { + pub ident: Ident, + pub attrs: Vec<Attribute>, + pub id: NodeId, + pub node: ItemKind, + pub vis: Visibility, + pub span: Span, +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum ItemKind { + /// An`extern crate` item, with optional original crate name. + /// + /// E.g. `extern crate foo` or `extern crate foo_bar as foo` + ExternCrate(Option<Name>), + /// A use declaration (`use` or `pub use`) item. + /// + /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;` + Use(P<ViewPath>), + /// A static item (`static` or `pub static`). + /// + /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";` + Static(P<Ty>, Mutability, P<Expr>), + /// A constant item (`const` or `pub const`). + /// + /// E.g. `const FOO: i32 = 42;` + Const(P<Ty>, P<Expr>), + /// A function declaration (`fn` or `pub fn`). + /// + /// E.g. `fn foo(bar: usize) -> usize { .. }` + Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>), + /// A module declaration (`mod` or `pub mod`). + /// + /// E.g. `mod foo;` or `mod foo { .. }` + Mod(Mod), + /// An external module (`extern` or `pub extern`). + /// + /// E.g. `extern {}` or `extern "C" {}` + ForeignMod(ForeignMod), + /// A type alias (`type` or `pub type`). + /// + /// E.g. `type Foo = Bar<u8>;` + Ty(P<Ty>, Generics), + /// An enum definition (`enum` or `pub enum`). + /// + /// E.g. `enum Foo<A, B> { C<A>, D<B> }` + Enum(EnumDef, Generics), + /// A struct definition (`struct` or `pub struct`). + /// + /// E.g. `struct Foo<A> { x: A }` + Struct(VariantData, Generics), + /// A union definition (`union` or `pub union`). + /// + /// E.g. `union Foo<A, B> { x: A, y: B }` + Union(VariantData, Generics), + /// A Trait declaration (`trait` or `pub trait`). + /// + /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }` + Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>), + // Default trait implementation. + /// + /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}` + DefaultImpl(Unsafety, TraitRef), + /// An implementation. + /// + /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }` + Impl(Unsafety, + ImplPolarity, + Generics, + Option<TraitRef>, // (optional) trait this impl implements + P<Ty>, // self + Vec<ImplItem>), + /// A macro invocation (which includes macro definition). + /// + /// E.g. `macro_rules! foo { .. }` or `foo!(..)` + Mac(Mac), +} + +impl ItemKind { + pub fn descriptive_variant(&self) -> &str { + match *self { + ItemKind::ExternCrate(..) => "extern crate", + ItemKind::Use(..) => "use", + ItemKind::Static(..) => "static item", + ItemKind::Const(..) => "constant item", + ItemKind::Fn(..) => "function", + ItemKind::Mod(..) => "module", + ItemKind::ForeignMod(..) => "foreign module", + ItemKind::Ty(..) => "type alias", + ItemKind::Enum(..) => "enum", + ItemKind::Struct(..) => "struct", + ItemKind::Union(..) => "union", + ItemKind::Trait(..) => "trait", + ItemKind::Mac(..) | + ItemKind::Impl(..) | + ItemKind::DefaultImpl(..) => "item" + } + } +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct ForeignItem { + pub ident: Ident, + pub attrs: Vec<Attribute>, + pub node: ForeignItemKind, + pub id: NodeId, + pub span: Span, + pub vis: Visibility, +} + +/// An item within an `extern` block +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum ForeignItemKind { + /// A foreign function + Fn(P<FnDecl>, Generics), + /// A foreign static item (`static ext: u8`), with optional mutability + /// (the boolean is true when mutable) + Static(P<Ty>, bool), +} + +impl ForeignItemKind { + pub fn descriptive_variant(&self) -> &str { + match *self { + ForeignItemKind::Fn(..) => "foreign function", + ForeignItemKind::Static(..) => "foreign static item" + } + } +} + +/// A macro definition, in this crate or imported from another. +/// +/// Not parsed directly, but created on macro import or `macro_rules!` expansion. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct MacroDef { + pub ident: Ident, + pub attrs: Vec<Attribute>, + pub id: NodeId, + pub span: Span, + pub body: Vec<TokenTree>, +} + +#[cfg(test)] +mod tests { + use serialize; + use super::*; + + // are ASTs encodable? + #[test] + fn check_asts_encodable() { + fn assert_encodable<T: serialize::Encodable>() {} + assert_encodable::<Crate>(); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/attr.rs b/bash-5.1/vendor/syntex_syntax/src/attr.rs new file mode 100644 index 0000000..ab8a49b --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/attr.rs @@ -0,0 +1,1037 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Functions dealing with attributes and meta items + +pub use self::StabilityLevel::*; +pub use self::ReprAttr::*; +pub use self::IntType::*; + +use ast; +use ast::{AttrId, Attribute, Name}; +use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind}; +use ast::{Lit, Expr, Item, Local, Stmt, StmtKind}; +use codemap::{spanned, dummy_spanned, mk_sp}; +use syntax_pos::{Span, BytePos, DUMMY_SP}; +use errors::Handler; +use feature_gate::{Features, GatedCfg}; +use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration}; +use parse::ParseSess; +use ptr::P; +use symbol::Symbol; +use util::ThinVec; + +use std::cell::{RefCell, Cell}; + +thread_local! { + static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new()); + static KNOWN_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new()); +} + +enum AttrError { + MultipleItem(Name), + UnknownMetaItem(Name), + MissingSince, + MissingFeature, + MultipleStabilityLevels, + UnsupportedLiteral +} + +fn handle_errors(diag: &Handler, span: Span, error: AttrError) { + match error { + AttrError::MultipleItem(item) => span_err!(diag, span, E0538, + "multiple '{}' items", item), + AttrError::UnknownMetaItem(item) => span_err!(diag, span, E0541, + "unknown meta item '{}'", item), + AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"), + AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"), + AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544, + "multiple stability levels"), + AttrError::UnsupportedLiteral => span_err!(diag, span, E0565, "unsupported literal"), + } +} + +pub fn mark_used(attr: &Attribute) { + debug!("Marking {:?} as used.", attr); + let AttrId(id) = attr.id; + USED_ATTRS.with(|slot| { + let idx = (id / 64) as usize; + let shift = id % 64; + if slot.borrow().len() <= idx { + slot.borrow_mut().resize(idx + 1, 0); + } + slot.borrow_mut()[idx] |= 1 << shift; + }); +} + +pub fn is_used(attr: &Attribute) -> bool { + let AttrId(id) = attr.id; + USED_ATTRS.with(|slot| { + let idx = (id / 64) as usize; + let shift = id % 64; + slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0) + .unwrap_or(false) + }) +} + +pub fn mark_known(attr: &Attribute) { + debug!("Marking {:?} as known.", attr); + let AttrId(id) = attr.id; + KNOWN_ATTRS.with(|slot| { + let idx = (id / 64) as usize; + let shift = id % 64; + if slot.borrow().len() <= idx { + slot.borrow_mut().resize(idx + 1, 0); + } + slot.borrow_mut()[idx] |= 1 << shift; + }); +} + +pub fn is_known(attr: &Attribute) -> bool { + let AttrId(id) = attr.id; + KNOWN_ATTRS.with(|slot| { + let idx = (id / 64) as usize; + let shift = id % 64; + slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0) + .unwrap_or(false) + }) +} + +impl NestedMetaItem { + /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem. + pub fn meta_item(&self) -> Option<&MetaItem> { + match self.node { + NestedMetaItemKind::MetaItem(ref item) => Some(&item), + _ => None + } + } + + /// Returns the Lit if self is a NestedMetaItemKind::Literal. + pub fn literal(&self) -> Option<&Lit> { + match self.node { + NestedMetaItemKind::Literal(ref lit) => Some(&lit), + _ => None + } + } + + /// Returns the Span for `self`. + pub fn span(&self) -> Span { + self.span + } + + /// Returns true if this list item is a MetaItem with a name of `name`. + pub fn check_name(&self, name: &str) -> bool { + self.meta_item().map_or(false, |meta_item| meta_item.check_name(name)) + } + + /// Returns the name of the meta item, e.g. `foo` in `#[foo]`, + /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem + pub fn name(&self) -> Option<Name> { + self.meta_item().and_then(|meta_item| Some(meta_item.name())) + } + + /// Gets the string value if self is a MetaItem and the MetaItem is a + /// MetaItemKind::NameValue variant containing a string, otherwise None. + pub fn value_str(&self) -> Option<Symbol> { + self.meta_item().and_then(|meta_item| meta_item.value_str()) + } + + /// Returns a MetaItem if self is a MetaItem with Kind Word. + pub fn word(&self) -> Option<&MetaItem> { + self.meta_item().and_then(|meta_item| if meta_item.is_word() { + Some(meta_item) + } else { + None + }) + } + + /// Gets a list of inner meta items from a list MetaItem type. + pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { + self.meta_item().and_then(|meta_item| meta_item.meta_item_list()) + } + + /// Returns `true` if the variant is MetaItem. + pub fn is_meta_item(&self) -> bool { + self.meta_item().is_some() + } + + /// Returns `true` if the variant is Literal. + pub fn is_literal(&self) -> bool { + self.literal().is_some() + } + + /// Returns `true` if self is a MetaItem and the meta item is a word. + pub fn is_word(&self) -> bool { + self.word().is_some() + } + + /// Returns `true` if self is a MetaItem and the meta item is a ValueString. + pub fn is_value_str(&self) -> bool { + self.value_str().is_some() + } + + /// Returns `true` if self is a MetaItem and the meta item is a list. + pub fn is_meta_item_list(&self) -> bool { + self.meta_item_list().is_some() + } +} + +impl Attribute { + pub fn check_name(&self, name: &str) -> bool { + let matches = self.name() == name; + if matches { + mark_used(self); + } + matches + } + + pub fn name(&self) -> Name { self.meta().name() } + + pub fn value_str(&self) -> Option<Symbol> { + self.meta().value_str() + } + + pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { + self.meta().meta_item_list() + } + + pub fn is_word(&self) -> bool { self.meta().is_word() } + + pub fn span(&self) -> Span { self.meta().span } + + pub fn is_meta_item_list(&self) -> bool { + self.meta_item_list().is_some() + } + + /// Indicates if the attribute is a Value String. + pub fn is_value_str(&self) -> bool { + self.value_str().is_some() + } +} + +impl MetaItem { + pub fn name(&self) -> Name { + self.name + } + + pub fn value_str(&self) -> Option<Symbol> { + match self.node { + MetaItemKind::NameValue(ref v) => { + match v.node { + ast::LitKind::Str(ref s, _) => Some((*s).clone()), + _ => None, + } + }, + _ => None + } + } + + pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { + match self.node { + MetaItemKind::List(ref l) => Some(&l[..]), + _ => None + } + } + + pub fn is_word(&self) -> bool { + match self.node { + MetaItemKind::Word => true, + _ => false, + } + } + + pub fn span(&self) -> Span { self.span } + + pub fn check_name(&self, name: &str) -> bool { + self.name() == name + } + + pub fn is_value_str(&self) -> bool { + self.value_str().is_some() + } + + pub fn is_meta_item_list(&self) -> bool { + self.meta_item_list().is_some() + } +} + +impl Attribute { + /// Extract the MetaItem from inside this Attribute. + pub fn meta(&self) -> &MetaItem { + &self.value + } + + /// Convert self to a normal #[doc="foo"] comment, if it is a + /// comment like `///` or `/** */`. (Returns self unchanged for + /// non-sugared doc attributes.) + pub fn with_desugared_doc<T, F>(&self, f: F) -> T where + F: FnOnce(&Attribute) -> T, + { + if self.is_sugared_doc { + let comment = self.value_str().unwrap(); + let meta = mk_name_value_item_str( + Symbol::intern("doc"), + Symbol::intern(&strip_doc_comment_decoration(&comment.as_str()))); + if self.style == ast::AttrStyle::Outer { + f(&mk_attr_outer(self.id, meta)) + } else { + f(&mk_attr_inner(self.id, meta)) + } + } else { + f(self) + } + } +} + +/* Constructors */ + +pub fn mk_name_value_item_str(name: Name, value: Symbol) -> MetaItem { + let value_lit = dummy_spanned(ast::LitKind::Str(value, ast::StrStyle::Cooked)); + mk_spanned_name_value_item(DUMMY_SP, name, value_lit) +} + +pub fn mk_name_value_item(name: Name, value: ast::Lit) -> MetaItem { + mk_spanned_name_value_item(DUMMY_SP, name, value) +} + +pub fn mk_list_item(name: Name, items: Vec<NestedMetaItem>) -> MetaItem { + mk_spanned_list_item(DUMMY_SP, name, items) +} + +pub fn mk_list_word_item(name: Name) -> ast::NestedMetaItem { + dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name))) +} + +pub fn mk_word_item(name: Name) -> MetaItem { + mk_spanned_word_item(DUMMY_SP, name) +} + +pub fn mk_spanned_name_value_item(sp: Span, name: Name, value: ast::Lit) -> MetaItem { + MetaItem { span: sp, name: name, node: MetaItemKind::NameValue(value) } +} + +pub fn mk_spanned_list_item(sp: Span, name: Name, items: Vec<NestedMetaItem>) -> MetaItem { + MetaItem { span: sp, name: name, node: MetaItemKind::List(items) } +} + +pub fn mk_spanned_word_item(sp: Span, name: Name) -> MetaItem { + MetaItem { span: sp, name: name, node: MetaItemKind::Word } +} + + + +thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) } + +pub fn mk_attr_id() -> AttrId { + let id = NEXT_ATTR_ID.with(|slot| { + let r = slot.get(); + slot.set(r + 1); + r + }); + AttrId(id) +} + +/// Returns an inner attribute with the given value. +pub fn mk_attr_inner(id: AttrId, item: MetaItem) -> Attribute { + mk_spanned_attr_inner(DUMMY_SP, id, item) +} + +/// Returns an innter attribute with the given value and span. +pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute { + Attribute { + id: id, + style: ast::AttrStyle::Inner, + value: item, + is_sugared_doc: false, + span: sp, + } +} + + +/// Returns an outer attribute with the given value. +pub fn mk_attr_outer(id: AttrId, item: MetaItem) -> Attribute { + mk_spanned_attr_outer(DUMMY_SP, id, item) +} + +/// Returns an outer attribute with the given value and span. +pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute { + Attribute { + id: id, + style: ast::AttrStyle::Outer, + value: item, + is_sugared_doc: false, + span: sp, + } +} + +pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, lo: BytePos, hi: BytePos) + -> Attribute { + let style = doc_comment_style(&text.as_str()); + let lit = spanned(lo, hi, ast::LitKind::Str(text, ast::StrStyle::Cooked)); + Attribute { + id: id, + style: style, + value: MetaItem { + span: mk_sp(lo, hi), + name: Symbol::intern("doc"), + node: MetaItemKind::NameValue(lit), + }, + is_sugared_doc: true, + span: mk_sp(lo, hi), + } +} + +pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool { + debug!("attr::list_contains_name (name={})", name); + items.iter().any(|item| { + debug!(" testing: {:?}", item.name()); + item.check_name(name) + }) +} + +pub fn contains_name(attrs: &[Attribute], name: &str) -> bool { + debug!("attr::contains_name (name={})", name); + attrs.iter().any(|item| { + debug!(" testing: {}", item.name()); + item.check_name(name) + }) +} + +pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> { + attrs.iter() + .find(|at| at.check_name(name)) + .and_then(|at| at.value_str()) +} + +/* Higher-level applications */ + +pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> { + first_attr_value_str_by_name(attrs, "crate_name") +} + +/// Find the value of #[export_name=*] attribute and check its validity. +pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<Symbol> { + attrs.iter().fold(None, |ia,attr| { + if attr.check_name("export_name") { + if let s@Some(_) = attr.value_str() { + s + } else { + struct_span_err!(diag, attr.span, E0558, + "export_name attribute has invalid format") + .span_label(attr.span, + &format!("did you mean #[export_name=\"*\"]?")) + .emit(); + None + } + } else { + ia + } + }) +} + +pub fn contains_extern_indicator(diag: &Handler, attrs: &[Attribute]) -> bool { + contains_name(attrs, "no_mangle") || + find_export_name_attr(diag, attrs).is_some() +} + +#[derive(Copy, Clone, PartialEq)] +pub enum InlineAttr { + None, + Hint, + Always, + Never, +} + +/// Determine what `#[inline]` attribute is present in `attrs`, if any. +pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr { + attrs.iter().fold(InlineAttr::None, |ia, attr| { + match attr.value.node { + _ if attr.value.name != "inline" => ia, + MetaItemKind::Word => { + mark_used(attr); + InlineAttr::Hint + } + MetaItemKind::List(ref items) => { + mark_used(attr); + if items.len() != 1 { + diagnostic.map(|d|{ span_err!(d, attr.span, E0534, "expected one argument"); }); + InlineAttr::None + } else if list_contains_name(&items[..], "always") { + InlineAttr::Always + } else if list_contains_name(&items[..], "never") { + InlineAttr::Never + } else { + diagnostic.map(|d| { + span_err!(d, items[0].span, E0535, "invalid argument"); + }); + + InlineAttr::None + } + } + _ => ia, + } + }) +} + +/// True if `#[inline]` or `#[inline(always)]` is present in `attrs`. +pub fn requests_inline(attrs: &[Attribute]) -> bool { + match find_inline_attr(None, attrs) { + InlineAttr::Hint | InlineAttr::Always => true, + InlineAttr::None | InlineAttr::Never => false, + } +} + +/// Tests if a cfg-pattern matches the cfg set +pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool { + match cfg.node { + ast::MetaItemKind::List(ref mis) => { + for mi in mis.iter() { + if !mi.is_meta_item() { + handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral); + return false; + } + } + + // The unwraps below may look dangerous, but we've already asserted + // that they won't fail with the loop above. + match &*cfg.name.as_str() { + "any" => mis.iter().any(|mi| { + cfg_matches(mi.meta_item().unwrap(), sess, features) + }), + "all" => mis.iter().all(|mi| { + cfg_matches(mi.meta_item().unwrap(), sess, features) + }), + "not" => { + if mis.len() != 1 { + span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern"); + return false; + } + + !cfg_matches(mis[0].meta_item().unwrap(), sess, features) + }, + p => { + span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p); + false + } + } + }, + ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => { + if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) { + gated_cfg.check_and_emit(sess, feats); + } + sess.config.contains(&(cfg.name(), cfg.value_str())) + } + } +} + +/// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes. +#[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)] +pub struct Stability { + pub level: StabilityLevel, + pub feature: Symbol, + pub rustc_depr: Option<RustcDeprecation>, +} + +/// The available stability levels. +#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)] +pub enum StabilityLevel { + // Reason for the current stability level and the relevant rust-lang issue + Unstable { reason: Option<Symbol>, issue: u32 }, + Stable { since: Symbol }, +} + +#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)] +pub struct RustcDeprecation { + pub since: Symbol, + pub reason: Symbol, +} + +#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)] +pub struct Deprecation { + pub since: Option<Symbol>, + pub note: Option<Symbol>, +} + +impl StabilityLevel { + pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }} + pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }} +} + +fn find_stability_generic<'a, I>(diagnostic: &Handler, + attrs_iter: I, + item_sp: Span) + -> Option<Stability> + where I: Iterator<Item = &'a Attribute> +{ + let mut stab: Option<Stability> = None; + let mut rustc_depr: Option<RustcDeprecation> = None; + + 'outer: for attr in attrs_iter { + let tag = attr.name(); + if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" { + continue // not a stability level + } + + mark_used(attr); + + if let Some(metas) = attr.meta_item_list() { + let get = |meta: &MetaItem, item: &mut Option<Symbol>| { + if item.is_some() { + handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name())); + return false + } + if let Some(v) = meta.value_str() { + *item = Some(v); + true + } else { + span_err!(diagnostic, meta.span, E0539, "incorrect meta item"); + false + } + }; + + match &*tag.as_str() { + "rustc_deprecated" => { + if rustc_depr.is_some() { + span_err!(diagnostic, item_sp, E0540, + "multiple rustc_deprecated attributes"); + break + } + + let mut since = None; + let mut reason = None; + for meta in metas { + if let Some(mi) = meta.meta_item() { + match &*mi.name().as_str() { + "since" => if !get(mi, &mut since) { continue 'outer }, + "reason" => if !get(mi, &mut reason) { continue 'outer }, + _ => { + handle_errors(diagnostic, mi.span, + AttrError::UnknownMetaItem(mi.name())); + continue 'outer + } + } + } else { + handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral); + continue 'outer + } + } + + match (since, reason) { + (Some(since), Some(reason)) => { + rustc_depr = Some(RustcDeprecation { + since: since, + reason: reason, + }) + } + (None, _) => { + handle_errors(diagnostic, attr.span(), AttrError::MissingSince); + continue + } + _ => { + span_err!(diagnostic, attr.span(), E0543, "missing 'reason'"); + continue + } + } + } + "unstable" => { + if stab.is_some() { + handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels); + break + } + + let mut feature = None; + let mut reason = None; + let mut issue = None; + for meta in metas { + if let Some(mi) = meta.meta_item() { + match &*mi.name().as_str() { + "feature" => if !get(mi, &mut feature) { continue 'outer }, + "reason" => if !get(mi, &mut reason) { continue 'outer }, + "issue" => if !get(mi, &mut issue) { continue 'outer }, + _ => { + handle_errors(diagnostic, meta.span, + AttrError::UnknownMetaItem(mi.name())); + continue 'outer + } + } + } else { + handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral); + continue 'outer + } + } + + match (feature, reason, issue) { + (Some(feature), reason, Some(issue)) => { + stab = Some(Stability { + level: Unstable { + reason: reason, + issue: { + if let Ok(issue) = issue.as_str().parse() { + issue + } else { + span_err!(diagnostic, attr.span(), E0545, + "incorrect 'issue'"); + continue + } + } + }, + feature: feature, + rustc_depr: None, + }) + } + (None, _, _) => { + handle_errors(diagnostic, attr.span(), AttrError::MissingFeature); + continue + } + _ => { + span_err!(diagnostic, attr.span(), E0547, "missing 'issue'"); + continue + } + } + } + "stable" => { + if stab.is_some() { + handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels); + break + } + + let mut feature = None; + let mut since = None; + for meta in metas { + if let NestedMetaItemKind::MetaItem(ref mi) = meta.node { + match &*mi.name().as_str() { + "feature" => if !get(mi, &mut feature) { continue 'outer }, + "since" => if !get(mi, &mut since) { continue 'outer }, + _ => { + handle_errors(diagnostic, meta.span, + AttrError::UnknownMetaItem(mi.name())); + continue 'outer + } + } + } else { + handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral); + continue 'outer + } + } + + match (feature, since) { + (Some(feature), Some(since)) => { + stab = Some(Stability { + level: Stable { + since: since, + }, + feature: feature, + rustc_depr: None, + }) + } + (None, _) => { + handle_errors(diagnostic, attr.span(), AttrError::MissingFeature); + continue + } + _ => { + handle_errors(diagnostic, attr.span(), AttrError::MissingSince); + continue + } + } + } + _ => unreachable!() + } + } else { + span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type"); + continue + } + } + + // Merge the deprecation info into the stability info + if let Some(rustc_depr) = rustc_depr { + if let Some(ref mut stab) = stab { + stab.rustc_depr = Some(rustc_depr); + } else { + span_err!(diagnostic, item_sp, E0549, + "rustc_deprecated attribute must be paired with \ + either stable or unstable attribute"); + } + } + + stab +} + +fn find_deprecation_generic<'a, I>(diagnostic: &Handler, + attrs_iter: I, + item_sp: Span) + -> Option<Deprecation> + where I: Iterator<Item = &'a Attribute> +{ + let mut depr: Option<Deprecation> = None; + + 'outer: for attr in attrs_iter { + if attr.name() != "deprecated" { + continue + } + + mark_used(attr); + + if depr.is_some() { + span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes"); + break + } + + depr = if let Some(metas) = attr.meta_item_list() { + let get = |meta: &MetaItem, item: &mut Option<Symbol>| { + if item.is_some() { + handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name())); + return false + } + if let Some(v) = meta.value_str() { + *item = Some(v); + true + } else { + span_err!(diagnostic, meta.span, E0551, "incorrect meta item"); + false + } + }; + + let mut since = None; + let mut note = None; + for meta in metas { + if let NestedMetaItemKind::MetaItem(ref mi) = meta.node { + match &*mi.name().as_str() { + "since" => if !get(mi, &mut since) { continue 'outer }, + "note" => if !get(mi, &mut note) { continue 'outer }, + _ => { + handle_errors(diagnostic, meta.span, + AttrError::UnknownMetaItem(mi.name())); + continue 'outer + } + } + } else { + handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral); + continue 'outer + } + } + + Some(Deprecation {since: since, note: note}) + } else { + Some(Deprecation{since: None, note: None}) + } + } + + depr +} + +/// Find the first stability attribute. `None` if none exists. +pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute], + item_sp: Span) -> Option<Stability> { + find_stability_generic(diagnostic, attrs.iter(), item_sp) +} + +/// Find the deprecation attribute. `None` if none exists. +pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute], + item_sp: Span) -> Option<Deprecation> { + find_deprecation_generic(diagnostic, attrs.iter(), item_sp) +} + + +/// Parse #[repr(...)] forms. +/// +/// Valid repr contents: any of the primitive integral type names (see +/// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use +/// the same discriminant size that the corresponding C enum would or C +/// structure layout, and `packed` to remove padding. +pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> { + let mut acc = Vec::new(); + match attr.value.node { + ast::MetaItemKind::List(ref items) if attr.value.name == "repr" => { + mark_used(attr); + for item in items { + if !item.is_meta_item() { + handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral); + continue + } + + if let Some(mi) = item.word() { + let word = &*mi.name().as_str(); + let hint = match word { + // Can't use "extern" because it's not a lexical identifier. + "C" => Some(ReprExtern), + "packed" => Some(ReprPacked), + "simd" => Some(ReprSimd), + _ => match int_type_of_word(word) { + Some(ity) => Some(ReprInt(ity)), + None => { + // Not a word we recognize + span_err!(diagnostic, item.span, E0552, + "unrecognized representation hint"); + None + } + } + }; + + if let Some(h) = hint { + acc.push(h); + } + } else { + span_err!(diagnostic, item.span, E0553, + "unrecognized enum representation hint"); + } + } + } + // Not a "repr" hint: ignore. + _ => { } + } + acc +} + +fn int_type_of_word(s: &str) -> Option<IntType> { + match s { + "i8" => Some(SignedInt(ast::IntTy::I8)), + "u8" => Some(UnsignedInt(ast::UintTy::U8)), + "i16" => Some(SignedInt(ast::IntTy::I16)), + "u16" => Some(UnsignedInt(ast::UintTy::U16)), + "i32" => Some(SignedInt(ast::IntTy::I32)), + "u32" => Some(UnsignedInt(ast::UintTy::U32)), + "i64" => Some(SignedInt(ast::IntTy::I64)), + "u64" => Some(UnsignedInt(ast::UintTy::U64)), + "i128" => Some(SignedInt(ast::IntTy::I128)), + "u128" => Some(UnsignedInt(ast::UintTy::U128)), + "isize" => Some(SignedInt(ast::IntTy::Is)), + "usize" => Some(UnsignedInt(ast::UintTy::Us)), + _ => None + } +} + +#[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)] +pub enum ReprAttr { + ReprAny, + ReprInt(IntType), + ReprExtern, + ReprPacked, + ReprSimd, +} + +impl ReprAttr { + pub fn is_ffi_safe(&self) -> bool { + match *self { + ReprAny => false, + ReprInt(ity) => ity.is_ffi_safe(), + ReprExtern => true, + ReprPacked => false, + ReprSimd => true, + } + } +} + +#[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)] +pub enum IntType { + SignedInt(ast::IntTy), + UnsignedInt(ast::UintTy) +} + +impl IntType { + #[inline] + pub fn is_signed(self) -> bool { + match self { + SignedInt(..) => true, + UnsignedInt(..) => false + } + } + fn is_ffi_safe(self) -> bool { + match self { + SignedInt(ast::IntTy::I8) | UnsignedInt(ast::UintTy::U8) | + SignedInt(ast::IntTy::I16) | UnsignedInt(ast::UintTy::U16) | + SignedInt(ast::IntTy::I32) | UnsignedInt(ast::UintTy::U32) | + SignedInt(ast::IntTy::I64) | UnsignedInt(ast::UintTy::U64) | + SignedInt(ast::IntTy::I128) | UnsignedInt(ast::UintTy::U128) => true, + SignedInt(ast::IntTy::Is) | UnsignedInt(ast::UintTy::Us) => false + } + } +} + +pub trait HasAttrs: Sized { + fn attrs(&self) -> &[ast::Attribute]; + fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self; +} + +impl HasAttrs for Vec<Attribute> { + fn attrs(&self) -> &[Attribute] { + &self + } + fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { + f(self) + } +} + +impl HasAttrs for ThinVec<Attribute> { + fn attrs(&self) -> &[Attribute] { + &self + } + fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { + f(self.into()).into() + } +} + +impl<T: HasAttrs + 'static> HasAttrs for P<T> { + fn attrs(&self) -> &[Attribute] { + (**self).attrs() + } + fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { + self.map(|t| t.map_attrs(f)) + } +} + +impl HasAttrs for StmtKind { + fn attrs(&self) -> &[Attribute] { + match *self { + StmtKind::Local(ref local) => local.attrs(), + StmtKind::Item(..) => &[], + StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(), + StmtKind::Mac(ref mac) => { + let (_, _, ref attrs) = **mac; + attrs.attrs() + } + } + } + + fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { + match self { + StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)), + StmtKind::Item(..) => self, + StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)), + StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)), + StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| { + (mac, style, attrs.map_attrs(f)) + })), + } + } +} + +macro_rules! derive_has_attrs_from_field { + ($($ty:path),*) => { derive_has_attrs_from_field!($($ty: .attrs),*); }; + ($($ty:path : $(.$field:ident)*),*) => { $( + impl HasAttrs for $ty { + fn attrs(&self) -> &[Attribute] { + self $(.$field)* .attrs() + } + + fn map_attrs<F>(mut self, f: F) -> Self + where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>, + { + self $(.$field)* = self $(.$field)* .map_attrs(f); + self + } + } + )* } +} + +derive_has_attrs_from_field! { + Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm +} + +derive_has_attrs_from_field! { Stmt: .node, ast::Variant: .node.attrs } diff --git a/bash-5.1/vendor/syntex_syntax/src/codemap.rs b/bash-5.1/vendor/syntex_syntax/src/codemap.rs new file mode 100644 index 0000000..0c5a841 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/codemap.rs @@ -0,0 +1,1278 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The CodeMap tracks all the source code used within a single crate, mapping +//! from integer byte positions to the original source code location. Each bit +//! of source parsed during crate parsing (typically files, in-memory strings, +//! or various bits of macro expansion) cover a continuous range of bytes in the +//! CodeMap and are represented by FileMaps. Byte positions are stored in +//! `spans` and used pervasively in the compiler. They are absolute positions +//! within the CodeMap, which upon request can be converted to line and column +//! information, source code snippets, etc. + +pub use self::ExpnFormat::*; + +use std::cell::RefCell; +use std::path::{Path,PathBuf}; +use std::rc::Rc; + +use std::env; +use std::fs; +use std::io::{self, Read}; +pub use syntax_pos::*; +use errors::CodeMapper; + +use ast::Name; + +/// Return the span itself if it doesn't come from a macro expansion, +/// otherwise return the call site span up to the `enclosing_sp` by +/// following the `expn_info` chain. +pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span { + let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site)); + let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site)); + match (call_site1, call_site2) { + (None, _) => sp, + (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp, + (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp), + } +} + +/// The source of expansion. +#[derive(Clone, Hash, Debug, PartialEq, Eq)] +pub enum ExpnFormat { + /// e.g. #[derive(...)] <item> + MacroAttribute(Name), + /// e.g. `format!()` + MacroBang(Name), + /// Desugaring done by the compiler during HIR lowering. + CompilerDesugaring(Name) +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub struct Spanned<T> { + pub node: T, + pub span: Span, +} + +pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> { + respan(mk_sp(lo, hi), t) +} + +pub fn respan<T>(sp: Span, t: T) -> Spanned<T> { + Spanned {node: t, span: sp} +} + +pub fn dummy_spanned<T>(t: T) -> Spanned<T> { + respan(DUMMY_SP, t) +} + +/// Build a span that covers the two provided spans. +pub fn combine_spans(sp1: Span, sp2: Span) -> Span { + if sp1 == DUMMY_SP && sp2 == DUMMY_SP { + DUMMY_SP + } else if sp1 == DUMMY_SP { + sp2 + } else if sp2 == DUMMY_SP { + sp1 + } else { + Span { + lo: if sp1.lo < sp2.lo { sp1.lo } else { sp2.lo }, + hi: if sp1.hi > sp2.hi { sp1.hi } else { sp2.hi }, + expn_id: if sp1.expn_id == sp2.expn_id { sp1.expn_id } else { NO_EXPANSION }, + } + } +} + +#[derive(Clone, Hash, Debug)] +pub struct NameAndSpan { + /// The format with which the macro was invoked. + pub format: ExpnFormat, + /// Whether the macro is allowed to use #[unstable]/feature-gated + /// features internally without forcing the whole crate to opt-in + /// to them. + pub allow_internal_unstable: bool, + /// The span of the macro definition itself. The macro may not + /// have a sensible definition span (e.g. something defined + /// completely inside libsyntax) in which case this is None. + pub span: Option<Span> +} + +impl NameAndSpan { + pub fn name(&self) -> Name { + match self.format { + ExpnFormat::MacroAttribute(s) | + ExpnFormat::MacroBang(s) | + ExpnFormat::CompilerDesugaring(s) => s, + } + } +} + +/// Extra information for tracking spans of macro and syntax sugar expansion +#[derive(Hash, Debug)] +pub struct ExpnInfo { + /// The location of the actual macro invocation or syntax sugar , e.g. + /// `let x = foo!();` or `if let Some(y) = x {}` + /// + /// This may recursively refer to other macro invocations, e.g. if + /// `foo!()` invoked `bar!()` internally, and there was an + /// expression inside `bar!`; the call_site of the expression in + /// the expansion would point to the `bar!` invocation; that + /// call_site span would have its own ExpnInfo, with the call_site + /// pointing to the `foo!` invocation. + pub call_site: Span, + /// Information about the expansion. + pub callee: NameAndSpan +} + +// _____________________________________________________________________________ +// FileMap, MultiByteChar, FileName, FileLines +// + +/// An abstraction over the fs operations used by the Parser. +pub trait FileLoader { + /// Query the existence of a file. + fn file_exists(&self, path: &Path) -> bool; + + /// Return an absolute path to a file, if possible. + fn abs_path(&self, path: &Path) -> Option<PathBuf>; + + /// Read the contents of an UTF-8 file into memory. + fn read_file(&self, path: &Path) -> io::Result<String>; +} + +/// A FileLoader that uses std::fs to load real files. +pub struct RealFileLoader; + +impl FileLoader for RealFileLoader { + fn file_exists(&self, path: &Path) -> bool { + fs::metadata(path).is_ok() + } + + fn abs_path(&self, path: &Path) -> Option<PathBuf> { + if path.is_absolute() { + Some(path.to_path_buf()) + } else { + env::current_dir() + .ok() + .map(|cwd| cwd.join(path)) + } + } + + fn read_file(&self, path: &Path) -> io::Result<String> { + let mut src = String::new(); + try!(try!(fs::File::open(path)).read_to_string(&mut src)); + Ok(src) + } +} + +// _____________________________________________________________________________ +// CodeMap +// + +pub struct CodeMap { + pub files: RefCell<Vec<Rc<FileMap>>>, + expansions: RefCell<Vec<ExpnInfo>>, + file_loader: Box<FileLoader> +} + +impl CodeMap { + pub fn new() -> CodeMap { + CodeMap { + files: RefCell::new(Vec::new()), + expansions: RefCell::new(Vec::new()), + file_loader: Box::new(RealFileLoader) + } + } + + pub fn with_file_loader(file_loader: Box<FileLoader>) -> CodeMap { + CodeMap { + files: RefCell::new(Vec::new()), + expansions: RefCell::new(Vec::new()), + file_loader: file_loader + } + } + + pub fn file_exists(&self, path: &Path) -> bool { + self.file_loader.file_exists(path) + } + + pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> { + let src = try!(self.file_loader.read_file(path)); + let abs_path = self.file_loader.abs_path(path).map(|p| p.to_str().unwrap().to_string()); + Ok(self.new_filemap(path.to_str().unwrap().to_string(), abs_path, src)) + } + + fn next_start_pos(&self) -> usize { + let files = self.files.borrow(); + match files.last() { + None => 0, + // Add one so there is some space between files. This lets us distinguish + // positions in the codemap, even in the presence of zero-length files. + Some(last) => last.end_pos.to_usize() + 1, + } + } + + /// Creates a new filemap without setting its line information. If you don't + /// intend to set the line information yourself, you should use new_filemap_and_lines. + pub fn new_filemap(&self, filename: FileName, abs_path: Option<FileName>, + mut src: String) -> Rc<FileMap> { + let start_pos = self.next_start_pos(); + let mut files = self.files.borrow_mut(); + + // Remove utf-8 BOM if any. + if src.starts_with("\u{feff}") { + src.drain(..3); + } + + let end_pos = start_pos + src.len(); + + let filemap = Rc::new(FileMap { + name: filename, + abs_path: abs_path, + src: Some(Rc::new(src)), + start_pos: Pos::from_usize(start_pos), + end_pos: Pos::from_usize(end_pos), + lines: RefCell::new(Vec::new()), + multibyte_chars: RefCell::new(Vec::new()), + }); + + files.push(filemap.clone()); + + filemap + } + + /// Creates a new filemap and sets its line information. + pub fn new_filemap_and_lines(&self, filename: &str, abs_path: Option<&str>, + src: &str) -> Rc<FileMap> { + let fm = self.new_filemap(filename.to_string(), + abs_path.map(|s| s.to_owned()), + src.to_owned()); + let mut byte_pos: u32 = fm.start_pos.0; + for line in src.lines() { + // register the start of this line + fm.next_line(BytePos(byte_pos)); + + // update byte_pos to include this line and the \n at the end + byte_pos += line.len() as u32 + 1; + } + fm + } + + + /// Allocates a new FileMap representing a source file from an external + /// crate. The source code of such an "imported filemap" is not available, + /// but we still know enough to generate accurate debuginfo location + /// information for things inlined from other crates. + pub fn new_imported_filemap(&self, + filename: FileName, + abs_path: Option<FileName>, + source_len: usize, + mut file_local_lines: Vec<BytePos>, + mut file_local_multibyte_chars: Vec<MultiByteChar>) + -> Rc<FileMap> { + let start_pos = self.next_start_pos(); + let mut files = self.files.borrow_mut(); + + let end_pos = Pos::from_usize(start_pos + source_len); + let start_pos = Pos::from_usize(start_pos); + + for pos in &mut file_local_lines { + *pos = *pos + start_pos; + } + + for mbc in &mut file_local_multibyte_chars { + mbc.pos = mbc.pos + start_pos; + } + + let filemap = Rc::new(FileMap { + name: filename, + abs_path: abs_path, + src: None, + start_pos: start_pos, + end_pos: end_pos, + lines: RefCell::new(file_local_lines), + multibyte_chars: RefCell::new(file_local_multibyte_chars), + }); + + files.push(filemap.clone()); + + filemap + } + + pub fn mk_substr_filename(&self, sp: Span) -> String { + let pos = self.lookup_char_pos(sp.lo); + (format!("<{}:{}:{}>", + pos.file.name, + pos.line, + pos.col.to_usize() + 1)).to_string() + } + + /// Lookup source information about a BytePos + pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { + let chpos = self.bytepos_to_file_charpos(pos); + match self.lookup_line(pos) { + Ok(FileMapAndLine { fm: f, line: a }) => { + let line = a + 1; // Line numbers start at 1 + let linebpos = (*f.lines.borrow())[a]; + let linechpos = self.bytepos_to_file_charpos(linebpos); + debug!("byte pos {:?} is on the line at byte pos {:?}", + pos, linebpos); + debug!("char pos {:?} is on the line at char pos {:?}", + chpos, linechpos); + debug!("byte is on line: {}", line); + assert!(chpos >= linechpos); + Loc { + file: f, + line: line, + col: chpos - linechpos, + } + } + Err(f) => { + Loc { + file: f, + line: 0, + col: chpos, + } + } + } + } + + // If the relevant filemap is empty, we don't return a line number. + fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> { + let idx = self.lookup_filemap_idx(pos); + + let files = self.files.borrow(); + let f = (*files)[idx].clone(); + + match f.lookup_line(pos) { + Some(line) => Ok(FileMapAndLine { fm: f, line: line }), + None => Err(f) + } + } + + pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt { + let loc = self.lookup_char_pos(pos); + LocWithOpt { + filename: loc.file.name.to_string(), + line: loc.line, + col: loc.col, + file: Some(loc.file) + } + } + + /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If + /// there are gaps between lhs and rhs, the resulting union will cross these gaps. + /// For this to work, the spans have to be: + /// * the expn_id of both spans much match + /// * the lhs span needs to end on the same line the rhs span begins + /// * the lhs span must start at or before the rhs span + pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> { + use std::cmp; + + // make sure we're at the same expansion id + if sp_lhs.expn_id != sp_rhs.expn_id { + return None; + } + + let lhs_end = match self.lookup_line(sp_lhs.hi) { + Ok(x) => x, + Err(_) => return None + }; + let rhs_begin = match self.lookup_line(sp_rhs.lo) { + Ok(x) => x, + Err(_) => return None + }; + + // if we must cross lines to merge, don't merge + if lhs_end.line != rhs_begin.line { + return None; + } + + // ensure these follow the expected order and we don't overlap + if (sp_lhs.lo <= sp_rhs.lo) && (sp_lhs.hi <= sp_rhs.lo) { + Some(Span { + lo: cmp::min(sp_lhs.lo, sp_rhs.lo), + hi: cmp::max(sp_lhs.hi, sp_rhs.hi), + expn_id: sp_lhs.expn_id, + }) + } else { + None + } + } + + pub fn span_to_string(&self, sp: Span) -> String { + if sp == COMMAND_LINE_SP { + return "<command line option>".to_string(); + } + + if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) { + return "no-location".to_string(); + } + + let lo = self.lookup_char_pos_adj(sp.lo); + let hi = self.lookup_char_pos_adj(sp.hi); + return (format!("{}:{}:{}: {}:{}", + lo.filename, + lo.line, + lo.col.to_usize() + 1, + hi.line, + hi.col.to_usize() + 1)).to_string() + } + + // Returns true if two spans have the same callee + // (Assumes the same ExpnFormat implies same callee) + fn match_callees(&self, sp_a: &Span, sp_b: &Span) -> bool { + let fmt_a = self + .with_expn_info(sp_a.expn_id, + |ei| ei.map(|ei| ei.callee.format.clone())); + + let fmt_b = self + .with_expn_info(sp_b.expn_id, + |ei| ei.map(|ei| ei.callee.format.clone())); + fmt_a == fmt_b + } + + /// Returns a formatted string showing the expansion chain of a span + /// + /// Spans are printed in the following format: + /// + /// filename:start_line:col: end_line:col + /// snippet + /// Callee: + /// Callee span + /// Callsite: + /// Callsite span + /// + /// Callees and callsites are printed recursively (if available, otherwise header + /// and span is omitted), expanding into their own callee/callsite spans. + /// Each layer of recursion has an increased indent, and snippets are truncated + /// to at most 50 characters. Finally, recursive calls to the same macro are squashed, + /// with '...' used to represent any number of recursive calls. + pub fn span_to_expanded_string(&self, sp: Span) -> String { + self.span_to_expanded_string_internal(sp, "") + } + + fn span_to_expanded_string_internal(&self, sp:Span, indent: &str) -> String { + let mut indent = indent.to_owned(); + let mut output = "".to_owned(); + let span_str = self.span_to_string(sp); + let mut span_snip = self.span_to_snippet(sp) + .unwrap_or("Snippet unavailable".to_owned()); + + // Truncate by code points - in worst case this will be more than 50 characters, + // but ensures at least 50 characters and respects byte boundaries. + let char_vec: Vec<(usize, char)> = span_snip.char_indices().collect(); + if char_vec.len() > 50 { + span_snip.truncate(char_vec[49].0); + span_snip.push_str("..."); + } + + output.push_str(&format!("{}{}\n{}`{}`\n", indent, span_str, indent, span_snip)); + + if sp.expn_id == NO_EXPANSION || sp.expn_id == COMMAND_LINE_EXPN { + return output; + } + + let mut callee = self.with_expn_info(sp.expn_id, + |ei| ei.and_then(|ei| ei.callee.span.clone())); + let mut callsite = self.with_expn_info(sp.expn_id, + |ei| ei.map(|ei| ei.call_site.clone())); + + indent.push_str(" "); + let mut is_recursive = false; + + while callee.is_some() && self.match_callees(&sp, &callee.unwrap()) { + callee = self.with_expn_info(callee.unwrap().expn_id, + |ei| ei.and_then(|ei| ei.callee.span.clone())); + is_recursive = true; + } + if let Some(span) = callee { + output.push_str(&indent); + output.push_str("Callee:\n"); + if is_recursive { + output.push_str(&indent); + output.push_str("...\n"); + } + output.push_str(&(self.span_to_expanded_string_internal(span, &indent))); + } + + is_recursive = false; + while callsite.is_some() && self.match_callees(&sp, &callsite.unwrap()) { + callsite = self.with_expn_info(callsite.unwrap().expn_id, + |ei| ei.map(|ei| ei.call_site.clone())); + is_recursive = true; + } + if let Some(span) = callsite { + output.push_str(&indent); + output.push_str("Callsite:\n"); + if is_recursive { + output.push_str(&indent); + output.push_str("...\n"); + } + output.push_str(&(self.span_to_expanded_string_internal(span, &indent))); + } + output + } + + /// Return the source span - this is either the supplied span, or the span for + /// the macro callsite that expanded to it. + pub fn source_callsite(&self, sp: Span) -> Span { + let mut span = sp; + // Special case - if a macro is parsed as an argument to another macro, the source + // callsite is the first callsite, which is also source-equivalent to the span. + let mut first = true; + while span.expn_id != NO_EXPANSION && span.expn_id != COMMAND_LINE_EXPN { + if let Some(callsite) = self.with_expn_info(span.expn_id, + |ei| ei.map(|ei| ei.call_site.clone())) { + if first && span.source_equal(&callsite) { + if self.lookup_char_pos(span.lo).file.is_real_file() { + return Span { expn_id: NO_EXPANSION, .. span }; + } + } + first = false; + span = callsite; + } + else { + break; + } + } + span + } + + /// Return the source callee. + /// + /// Returns None if the supplied span has no expansion trace, + /// else returns the NameAndSpan for the macro definition + /// corresponding to the source callsite. + pub fn source_callee(&self, sp: Span) -> Option<NameAndSpan> { + let mut span = sp; + // Special case - if a macro is parsed as an argument to another macro, the source + // callsite is source-equivalent to the span, and the source callee is the first callee. + let mut first = true; + while let Some(callsite) = self.with_expn_info(span.expn_id, + |ei| ei.map(|ei| ei.call_site.clone())) { + if first && span.source_equal(&callsite) { + if self.lookup_char_pos(span.lo).file.is_real_file() { + return self.with_expn_info(span.expn_id, + |ei| ei.map(|ei| ei.callee.clone())); + } + } + first = false; + if let Some(_) = self.with_expn_info(callsite.expn_id, + |ei| ei.map(|ei| ei.call_site.clone())) { + span = callsite; + } + else { + return self.with_expn_info(span.expn_id, + |ei| ei.map(|ei| ei.callee.clone())); + } + } + None + } + + pub fn span_to_filename(&self, sp: Span) -> FileName { + self.lookup_char_pos(sp.lo).file.name.to_string() + } + + pub fn span_to_lines(&self, sp: Span) -> FileLinesResult { + debug!("span_to_lines(sp={:?})", sp); + + if sp.lo > sp.hi { + return Err(SpanLinesError::IllFormedSpan(sp)); + } + + let lo = self.lookup_char_pos(sp.lo); + debug!("span_to_lines: lo={:?}", lo); + let hi = self.lookup_char_pos(sp.hi); + debug!("span_to_lines: hi={:?}", hi); + + if lo.file.start_pos != hi.file.start_pos { + return Err(SpanLinesError::DistinctSources(DistinctSources { + begin: (lo.file.name.clone(), lo.file.start_pos), + end: (hi.file.name.clone(), hi.file.start_pos), + })); + } + assert!(hi.line >= lo.line); + + let mut lines = Vec::with_capacity(hi.line - lo.line + 1); + + // The span starts partway through the first line, + // but after that it starts from offset 0. + let mut start_col = lo.col; + + // For every line but the last, it extends from `start_col` + // and to the end of the line. Be careful because the line + // numbers in Loc are 1-based, so we subtract 1 to get 0-based + // lines. + for line_index in lo.line-1 .. hi.line-1 { + let line_len = lo.file.get_line(line_index) + .map(|s| s.chars().count()) + .unwrap_or(0); + lines.push(LineInfo { line_index: line_index, + start_col: start_col, + end_col: CharPos::from_usize(line_len) }); + start_col = CharPos::from_usize(0); + } + + // For the last line, it extends from `start_col` to `hi.col`: + lines.push(LineInfo { line_index: hi.line - 1, + start_col: start_col, + end_col: hi.col }); + + Ok(FileLines {file: lo.file, lines: lines}) + } + + pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> { + if sp.lo > sp.hi { + return Err(SpanSnippetError::IllFormedSpan(sp)); + } + + let local_begin = self.lookup_byte_offset(sp.lo); + let local_end = self.lookup_byte_offset(sp.hi); + + if local_begin.fm.start_pos != local_end.fm.start_pos { + return Err(SpanSnippetError::DistinctSources(DistinctSources { + begin: (local_begin.fm.name.clone(), + local_begin.fm.start_pos), + end: (local_end.fm.name.clone(), + local_end.fm.start_pos) + })); + } else { + match local_begin.fm.src { + Some(ref src) => { + let start_index = local_begin.pos.to_usize(); + let end_index = local_end.pos.to_usize(); + let source_len = (local_begin.fm.end_pos - + local_begin.fm.start_pos).to_usize(); + + if start_index > end_index || end_index > source_len { + return Err(SpanSnippetError::MalformedForCodemap( + MalformedCodemapPositions { + name: local_begin.fm.name.clone(), + source_len: source_len, + begin_pos: local_begin.pos, + end_pos: local_end.pos, + })); + } + + return Ok((&src[start_index..end_index]).to_string()) + } + None => { + return Err(SpanSnippetError::SourceNotAvailable { + filename: local_begin.fm.name.clone() + }); + } + } + } + } + + pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> { + for fm in self.files.borrow().iter() { + if filename == fm.name { + return Some(fm.clone()); + } + } + None + } + + /// For a global BytePos compute the local offset within the containing FileMap + pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { + let idx = self.lookup_filemap_idx(bpos); + let fm = (*self.files.borrow())[idx].clone(); + let offset = bpos - fm.start_pos; + FileMapAndBytePos {fm: fm, pos: offset} + } + + /// Converts an absolute BytePos to a CharPos relative to the filemap. + pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { + let idx = self.lookup_filemap_idx(bpos); + let files = self.files.borrow(); + let map = &(*files)[idx]; + + // The number of extra bytes due to multibyte chars in the FileMap + let mut total_extra_bytes = 0; + + for mbc in map.multibyte_chars.borrow().iter() { + debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); + if mbc.pos < bpos { + // every character is at least one byte, so we only + // count the actual extra bytes. + total_extra_bytes += mbc.bytes - 1; + // We should never see a byte position in the middle of a + // character + assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes); + } else { + break; + } + } + + assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize()); + CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes) + } + + // Return the index of the filemap (in self.files) which contains pos. + pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize { + let files = self.files.borrow(); + let files = &*files; + let count = files.len(); + + // Binary search for the filemap. + let mut a = 0; + let mut b = count; + while b - a > 1 { + let m = (a + b) / 2; + if files[m].start_pos > pos { + b = m; + } else { + a = m; + } + } + + assert!(a < count, "position {} does not resolve to a source location", pos.to_usize()); + + return a; + } + + pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId { + let mut expansions = self.expansions.borrow_mut(); + expansions.push(expn_info); + let len = expansions.len(); + if len > u32::max_value() as usize { + panic!("too many ExpnInfo's!"); + } + ExpnId(len as u32 - 1) + } + + pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where + F: FnOnce(Option<&ExpnInfo>) -> T, + { + match id { + NO_EXPANSION | COMMAND_LINE_EXPN => f(None), + ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize])) + } + } + + /// Check if a span is "internal" to a macro in which #[unstable] + /// items can be used (that is, a macro marked with + /// `#[allow_internal_unstable]`). + pub fn span_allows_unstable(&self, span: Span) -> bool { + debug!("span_allows_unstable(span = {:?})", span); + let mut allows_unstable = false; + let mut expn_id = span.expn_id; + loop { + let quit = self.with_expn_info(expn_id, |expninfo| { + debug!("span_allows_unstable: expninfo = {:?}", expninfo); + expninfo.map_or(/* hit the top level */ true, |info| { + + let span_comes_from_this_expansion = + info.callee.span.map_or(span.source_equal(&info.call_site), |mac_span| { + mac_span.contains(span) + }); + + debug!("span_allows_unstable: span: {:?} call_site: {:?} callee: {:?}", + (span.lo, span.hi), + (info.call_site.lo, info.call_site.hi), + info.callee.span.map(|x| (x.lo, x.hi))); + debug!("span_allows_unstable: from this expansion? {}, allows unstable? {}", + span_comes_from_this_expansion, + info.callee.allow_internal_unstable); + if span_comes_from_this_expansion { + allows_unstable = info.callee.allow_internal_unstable; + // we've found the right place, stop looking + true + } else { + // not the right place, keep looking + expn_id = info.call_site.expn_id; + false + } + }) + }); + if quit { + break + } + } + debug!("span_allows_unstable? {}", allows_unstable); + allows_unstable + } + + pub fn count_lines(&self) -> usize { + self.files.borrow().iter().fold(0, |a, f| a + f.count_lines()) + } + + pub fn macro_backtrace(&self, span: Span) -> Vec<MacroBacktrace> { + let mut prev_span = DUMMY_SP; + let mut span = span; + let mut result = vec![]; + loop { + let span_name_span = self.with_expn_info(span.expn_id, |expn_info| { + expn_info.map(|ei| { + let (pre, post) = match ei.callee.format { + MacroAttribute(..) => ("#[", "]"), + MacroBang(..) => ("", "!"), + CompilerDesugaring(..) => ("desugaring of `", "`"), + }; + let macro_decl_name = format!("{}{}{}", + pre, + ei.callee.name(), + post); + let def_site_span = ei.callee.span; + (ei.call_site, macro_decl_name, def_site_span) + }) + }); + + match span_name_span { + None => break, + Some((call_site, macro_decl_name, def_site_span)) => { + // Don't print recursive invocations + if !call_site.source_equal(&prev_span) { + result.push(MacroBacktrace { + call_site: call_site, + macro_decl_name: macro_decl_name, + def_site_span: def_site_span, + }); + } + prev_span = span; + span = call_site; + } + } + } + result + } +} + +impl CodeMapper for CodeMap { + fn lookup_char_pos(&self, pos: BytePos) -> Loc { + self.lookup_char_pos(pos) + } + fn span_to_lines(&self, sp: Span) -> FileLinesResult { + self.span_to_lines(sp) + } + fn span_to_string(&self, sp: Span) -> String { + self.span_to_string(sp) + } + fn span_to_filename(&self, sp: Span) -> FileName { + self.span_to_filename(sp) + } + fn macro_backtrace(&self, span: Span) -> Vec<MacroBacktrace> { + self.macro_backtrace(span) + } + fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> { + self.merge_spans(sp_lhs, sp_rhs) + } +} + +// _____________________________________________________________________________ +// Tests +// + +#[cfg(test)] +mod tests { + use super::*; + use symbol::keywords; + use std::rc::Rc; + + #[test] + fn t1 () { + let cm = CodeMap::new(); + let fm = cm.new_filemap("blork.rs".to_string(), + None, + "first line.\nsecond line".to_string()); + fm.next_line(BytePos(0)); + // Test we can get lines with partial line info. + assert_eq!(fm.get_line(0), Some("first line.")); + // TESTING BROKEN BEHAVIOR: line break declared before actual line break. + fm.next_line(BytePos(10)); + assert_eq!(fm.get_line(1), Some(".")); + fm.next_line(BytePos(12)); + assert_eq!(fm.get_line(2), Some("second line")); + } + + #[test] + #[should_panic] + fn t2 () { + let cm = CodeMap::new(); + let fm = cm.new_filemap("blork.rs".to_string(), + None, + "first line.\nsecond line".to_string()); + // TESTING *REALLY* BROKEN BEHAVIOR: + fm.next_line(BytePos(0)); + fm.next_line(BytePos(10)); + fm.next_line(BytePos(2)); + } + + fn init_code_map() -> CodeMap { + let cm = CodeMap::new(); + let fm1 = cm.new_filemap("blork.rs".to_string(), + None, + "first line.\nsecond line".to_string()); + let fm2 = cm.new_filemap("empty.rs".to_string(), + None, + "".to_string()); + let fm3 = cm.new_filemap("blork2.rs".to_string(), + None, + "first line.\nsecond line".to_string()); + + fm1.next_line(BytePos(0)); + fm1.next_line(BytePos(12)); + fm2.next_line(fm2.start_pos); + fm3.next_line(fm3.start_pos); + fm3.next_line(fm3.start_pos + BytePos(12)); + + cm + } + + #[test] + fn t3() { + // Test lookup_byte_offset + let cm = init_code_map(); + + let fmabp1 = cm.lookup_byte_offset(BytePos(23)); + assert_eq!(fmabp1.fm.name, "blork.rs"); + assert_eq!(fmabp1.pos, BytePos(23)); + + let fmabp1 = cm.lookup_byte_offset(BytePos(24)); + assert_eq!(fmabp1.fm.name, "empty.rs"); + assert_eq!(fmabp1.pos, BytePos(0)); + + let fmabp2 = cm.lookup_byte_offset(BytePos(25)); + assert_eq!(fmabp2.fm.name, "blork2.rs"); + assert_eq!(fmabp2.pos, BytePos(0)); + } + + #[test] + fn t4() { + // Test bytepos_to_file_charpos + let cm = init_code_map(); + + let cp1 = cm.bytepos_to_file_charpos(BytePos(22)); + assert_eq!(cp1, CharPos(22)); + + let cp2 = cm.bytepos_to_file_charpos(BytePos(25)); + assert_eq!(cp2, CharPos(0)); + } + + #[test] + fn t5() { + // Test zero-length filemaps. + let cm = init_code_map(); + + let loc1 = cm.lookup_char_pos(BytePos(22)); + assert_eq!(loc1.file.name, "blork.rs"); + assert_eq!(loc1.line, 2); + assert_eq!(loc1.col, CharPos(10)); + + let loc2 = cm.lookup_char_pos(BytePos(25)); + assert_eq!(loc2.file.name, "blork2.rs"); + assert_eq!(loc2.line, 1); + assert_eq!(loc2.col, CharPos(0)); + } + + fn init_code_map_mbc() -> CodeMap { + let cm = CodeMap::new(); + // € is a three byte utf8 char. + let fm1 = + cm.new_filemap("blork.rs".to_string(), + None, + "fir€st €€€€ line.\nsecond line".to_string()); + let fm2 = cm.new_filemap("blork2.rs".to_string(), + None, + "first line€€.\n€ second line".to_string()); + + fm1.next_line(BytePos(0)); + fm1.next_line(BytePos(28)); + fm2.next_line(fm2.start_pos); + fm2.next_line(fm2.start_pos + BytePos(20)); + + fm1.record_multibyte_char(BytePos(3), 3); + fm1.record_multibyte_char(BytePos(9), 3); + fm1.record_multibyte_char(BytePos(12), 3); + fm1.record_multibyte_char(BytePos(15), 3); + fm1.record_multibyte_char(BytePos(18), 3); + fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3); + fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3); + fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3); + + cm + } + + #[test] + fn t6() { + // Test bytepos_to_file_charpos in the presence of multi-byte chars + let cm = init_code_map_mbc(); + + let cp1 = cm.bytepos_to_file_charpos(BytePos(3)); + assert_eq!(cp1, CharPos(3)); + + let cp2 = cm.bytepos_to_file_charpos(BytePos(6)); + assert_eq!(cp2, CharPos(4)); + + let cp3 = cm.bytepos_to_file_charpos(BytePos(56)); + assert_eq!(cp3, CharPos(12)); + + let cp4 = cm.bytepos_to_file_charpos(BytePos(61)); + assert_eq!(cp4, CharPos(15)); + } + + #[test] + fn t7() { + // Test span_to_lines for a span ending at the end of filemap + let cm = init_code_map(); + let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION}; + let file_lines = cm.span_to_lines(span).unwrap(); + + assert_eq!(file_lines.file.name, "blork.rs"); + assert_eq!(file_lines.lines.len(), 1); + assert_eq!(file_lines.lines[0].line_index, 1); + } + + /// Given a string like " ~~~~~~~~~~~~ ", produces a span + /// coverting that range. The idea is that the string has the same + /// length as the input, and we uncover the byte positions. Note + /// that this can span lines and so on. + fn span_from_selection(input: &str, selection: &str) -> Span { + assert_eq!(input.len(), selection.len()); + let left_index = selection.find('~').unwrap() as u32; + let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index); + Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), expn_id: NO_EXPANSION } + } + + /// Test span_to_snippet and span_to_lines for a span coverting 3 + /// lines in the middle of a file. + #[test] + fn span_to_snippet_and_lines_spanning_multiple_lines() { + let cm = CodeMap::new(); + let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n"; + let selection = " \n ~~\n~~~\n~~~~~ \n \n"; + cm.new_filemap_and_lines("blork.rs", None, inputtext); + let span = span_from_selection(inputtext, selection); + + // check that we are extracting the text we thought we were extracting + assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD"); + + // check that span_to_lines gives us the complete result with the lines/cols we expected + let lines = cm.span_to_lines(span).unwrap(); + let expected = vec![ + LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) }, + LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) }, + LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) } + ]; + assert_eq!(lines.lines, expected); + } + + #[test] + fn t8() { + // Test span_to_snippet for a span ending at the end of filemap + let cm = init_code_map(); + let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION}; + let snippet = cm.span_to_snippet(span); + + assert_eq!(snippet, Ok("second line".to_string())); + } + + #[test] + fn t9() { + // Test span_to_str for a span ending at the end of filemap + let cm = init_code_map(); + let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION}; + let sstr = cm.span_to_string(span); + + assert_eq!(sstr, "blork.rs:2:1: 2:12"); + } + + #[test] + fn t10() { + // Test span_to_expanded_string works in base case (no expansion) + let cm = init_code_map(); + let span = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION }; + let sstr = cm.span_to_expanded_string(span); + assert_eq!(sstr, "blork.rs:1:1: 1:12\n`first line.`\n"); + + let span = Span { lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION }; + let sstr = cm.span_to_expanded_string(span); + assert_eq!(sstr, "blork.rs:2:1: 2:12\n`second line`\n"); + } + + #[test] + fn t11() { + // Test span_to_expanded_string works with expansion + let cm = init_code_map(); + let root = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION }; + let format = ExpnFormat::MacroBang(keywords::Invalid.name()); + let callee = NameAndSpan { format: format, + allow_internal_unstable: false, + span: None }; + + let info = ExpnInfo { call_site: root, callee: callee }; + let id = cm.record_expansion(info); + let sp = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id }; + + let sstr = cm.span_to_expanded_string(sp); + assert_eq!(sstr, + "blork.rs:2:1: 2:12\n`second line`\n Callsite:\n \ + blork.rs:1:1: 1:12\n `first line.`\n"); + } + + /// Test merging two spans on the same line + #[test] + fn span_merging() { + let cm = CodeMap::new(); + let inputtext = "bbbb BB bb CCC\n"; + let selection1 = " ~~ \n"; + let selection2 = " ~~~\n"; + cm.new_filemap_and_lines("blork.rs", None, inputtext); + let span1 = span_from_selection(inputtext, selection1); + let span2 = span_from_selection(inputtext, selection2); + + if let Some(sp) = cm.merge_spans(span1, span2) { + let sstr = cm.span_to_expanded_string(sp); + assert_eq!(sstr, "blork.rs:1:6: 1:15\n`BB bb CCC`\n"); + } + else { + assert!(false); + } + } + + /// Test failing to merge two spans on different lines + #[test] + fn span_merging_fail() { + let cm = CodeMap::new(); + let inputtext = "bbbb BB\ncc CCC\n"; + let selection1 = " ~~\n \n"; + let selection2 = " \n ~~~\n"; + cm.new_filemap_and_lines("blork.rs", None, inputtext); + let span1 = span_from_selection(inputtext, selection1); + let span2 = span_from_selection(inputtext, selection2); + + assert!(cm.merge_spans(span1, span2).is_none()); + } + + /// Returns the span corresponding to the `n`th occurrence of + /// `substring` in `source_text`. + trait CodeMapExtension { + fn span_substr(&self, + file: &Rc<FileMap>, + source_text: &str, + substring: &str, + n: usize) + -> Span; + } + + impl CodeMapExtension for CodeMap { + fn span_substr(&self, + file: &Rc<FileMap>, + source_text: &str, + substring: &str, + n: usize) + -> Span + { + println!("span_substr(file={:?}/{:?}, substring={:?}, n={})", + file.name, file.start_pos, substring, n); + let mut i = 0; + let mut hi = 0; + loop { + let offset = source_text[hi..].find(substring).unwrap_or_else(|| { + panic!("source_text `{}` does not have {} occurrences of `{}`, only {}", + source_text, n, substring, i); + }); + let lo = hi + offset; + hi = lo + substring.len(); + if i == n { + let span = Span { + lo: BytePos(lo as u32 + file.start_pos.0), + hi: BytePos(hi as u32 + file.start_pos.0), + expn_id: NO_EXPANSION, + }; + assert_eq!(&self.span_to_snippet(span).unwrap()[..], + substring); + return span; + } + i += 1; + } + } + } + + fn init_expansion_chain(cm: &CodeMap) -> Span { + // Creates an expansion chain containing two recursive calls + // root -> expA -> expA -> expB -> expB -> end + let root = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION }; + + let format_root = ExpnFormat::MacroBang(keywords::Invalid.name()); + let callee_root = NameAndSpan { format: format_root, + allow_internal_unstable: false, + span: Some(root) }; + + let info_a1 = ExpnInfo { call_site: root, callee: callee_root }; + let id_a1 = cm.record_expansion(info_a1); + let span_a1 = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id_a1 }; + + let format_a = ExpnFormat::MacroBang(keywords::As.name()); + let callee_a = NameAndSpan { format: format_a, + allow_internal_unstable: false, + span: Some(span_a1) }; + + let info_a2 = ExpnInfo { call_site: span_a1, callee: callee_a.clone() }; + let id_a2 = cm.record_expansion(info_a2); + let span_a2 = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id_a2 }; + + let info_b1 = ExpnInfo { call_site: span_a2, callee: callee_a }; + let id_b1 = cm.record_expansion(info_b1); + let span_b1 = Span { lo: BytePos(25), hi: BytePos(36), expn_id: id_b1 }; + + let format_b = ExpnFormat::MacroBang(keywords::Box.name()); + let callee_b = NameAndSpan { format: format_b, + allow_internal_unstable: false, + span: None }; + + let info_b2 = ExpnInfo { call_site: span_b1, callee: callee_b.clone() }; + let id_b2 = cm.record_expansion(info_b2); + let span_b2 = Span { lo: BytePos(25), hi: BytePos(36), expn_id: id_b2 }; + + let info_end = ExpnInfo { call_site: span_b2, callee: callee_b }; + let id_end = cm.record_expansion(info_end); + Span { lo: BytePos(37), hi: BytePos(48), expn_id: id_end } + } + + #[test] + fn t12() { + // Test span_to_expanded_string collapses recursive macros and handles + // recursive callsite and callee expansions + let cm = init_code_map(); + let end = init_expansion_chain(&cm); + let sstr = cm.span_to_expanded_string(end); + let res_str = +r"blork2.rs:2:1: 2:12 +`second line` + Callsite: + ... + blork2.rs:1:1: 1:12 + `first line.` + Callee: + blork.rs:2:1: 2:12 + `second line` + Callee: + blork.rs:1:1: 1:12 + `first line.` + Callsite: + blork.rs:1:1: 1:12 + `first line.` + Callsite: + ... + blork.rs:2:1: 2:12 + `second line` + Callee: + blork.rs:1:1: 1:12 + `first line.` + Callsite: + blork.rs:1:1: 1:12 + `first line.` +"; + assert_eq!(sstr, res_str); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/config.rs b/bash-5.1/vendor/syntex_syntax/src/config.rs new file mode 100644 index 0000000..d08f9d9 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/config.rs @@ -0,0 +1,312 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use attr::HasAttrs; +use feature_gate::{feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue}; +use {fold, attr}; +use ast; +use codemap::Spanned; +use parse::ParseSess; +use ptr::P; + +use util::small_vector::SmallVector; + +/// A folder that strips out items that do not belong in the current configuration. +pub struct StripUnconfigured<'a> { + pub should_test: bool, + pub sess: &'a ParseSess, + pub features: Option<&'a Features>, +} + +// `cfg_attr`-process the crate's attributes and compute the crate's features. +pub fn features(mut krate: ast::Crate, sess: &ParseSess, should_test: bool) + -> (ast::Crate, Features) { + let features; + { + let mut strip_unconfigured = StripUnconfigured { + should_test: should_test, + sess: sess, + features: None, + }; + + let unconfigured_attrs = krate.attrs.clone(); + let err_count = sess.span_diagnostic.err_count(); + if let Some(attrs) = strip_unconfigured.configure(krate.attrs) { + krate.attrs = attrs; + } else { // the entire crate is unconfigured + krate.attrs = Vec::new(); + krate.module.items = Vec::new(); + return (krate, Features::new()); + } + + features = get_features(&sess.span_diagnostic, &krate.attrs); + + // Avoid reconfiguring malformed `cfg_attr`s + if err_count == sess.span_diagnostic.err_count() { + strip_unconfigured.features = Some(&features); + strip_unconfigured.configure(unconfigured_attrs); + } + } + + (krate, features) +} + +macro_rules! configure { + ($this:ident, $node:ident) => { + match $this.configure($node) { + Some(node) => node, + None => return Default::default(), + } + } +} + +impl<'a> StripUnconfigured<'a> { + pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> { + let node = self.process_cfg_attrs(node); + // FIXME(syntex): ignore unknown attributes + //if self.in_cfg(node.attrs()) { Some(node) } else { None } + Some(node) + } + + pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T { + node.map_attrs(|attrs| { + attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect() + }) + } + + fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> { + if !attr.check_name("cfg_attr") { + return Some(attr); + } + + let attr_list = match attr.meta_item_list() { + Some(attr_list) => attr_list, + None => { + let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"; + self.sess.span_diagnostic.span_err(attr.span, msg); + return None; + } + }; + + let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) { + (2, Some(cfg), Some(mi)) => (cfg, mi), + _ => { + let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"; + self.sess.span_diagnostic.span_err(attr.span, msg); + return None; + } + }; + + use attr::cfg_matches; + match (cfg.meta_item(), mi.meta_item()) { + (Some(cfg), Some(mi)) => + if cfg_matches(&cfg, self.sess, self.features) { + self.process_cfg_attr(ast::Attribute { + id: attr::mk_attr_id(), + style: attr.style, + value: mi.clone(), + is_sugared_doc: false, + span: mi.span, + }) + } else { + None + }, + _ => { + let msg = "unexpected literal(s) in `#[cfg_attr(<cfg pattern>, <attr>)]`"; + self.sess.span_diagnostic.span_err(attr.span, msg); + None + } + } + } + + // Determine if a node with the given attributes should be included in this configuation. + pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool { + attrs.iter().all(|attr| { + // When not compiling with --test we should not compile the #[test] functions + if !self.should_test && is_test_or_bench(attr) { + return false; + } + + let mis = match attr.value.node { + ast::MetaItemKind::List(ref mis) if is_cfg(&attr) => mis, + _ => return true + }; + + if mis.len() != 1 { + self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern"); + return true; + } + + if !mis[0].is_meta_item() { + self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal"); + return true; + } + + attr::cfg_matches(mis[0].meta_item().unwrap(), self.sess, self.features) + }) + } + + // Visit attributes on expression and statements (but not attributes on items in blocks). + fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) { + // flag the offending attributes + for attr in attrs.iter() { + if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) { + let mut err = feature_err(&self.sess, + "stmt_expr_attributes", + attr.span, + GateIssue::Language, + EXPLAIN_STMT_ATTR_SYNTAX); + if attr.is_sugared_doc { + err.help("`///` is for documentation comments. For a plain comment, use `//`."); + } + err.emit(); + } + } + } + + pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { + ast::ForeignMod { + abi: foreign_mod.abi, + items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(), + } + } + + fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData { + match vdata { + ast::VariantData::Struct(fields, id) => { + let fields = fields.into_iter().filter_map(|field| self.configure(field)); + ast::VariantData::Struct(fields.collect(), id) + } + ast::VariantData::Tuple(fields, id) => { + let fields = fields.into_iter().filter_map(|field| self.configure(field)); + ast::VariantData::Tuple(fields.collect(), id) + } + ast::VariantData::Unit(id) => ast::VariantData::Unit(id) + } + } + + pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind { + match item { + ast::ItemKind::Struct(def, generics) => { + ast::ItemKind::Struct(self.configure_variant_data(def), generics) + } + ast::ItemKind::Union(def, generics) => { + ast::ItemKind::Union(self.configure_variant_data(def), generics) + } + ast::ItemKind::Enum(def, generics) => { + let variants = def.variants.into_iter().filter_map(|v| { + self.configure(v).map(|v| { + Spanned { + node: ast::Variant_ { + name: v.node.name, + attrs: v.node.attrs, + data: self.configure_variant_data(v.node.data), + disr_expr: v.node.disr_expr, + }, + span: v.span + } + }) + }); + ast::ItemKind::Enum(ast::EnumDef { + variants: variants.collect(), + }, generics) + } + item => item, + } + } + + pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind { + if let ast::ExprKind::Match(m, arms) = expr_kind { + let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect(); + ast::ExprKind::Match(m, arms) + } else { + expr_kind + } + } + + pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { + self.visit_expr_attrs(expr.attrs()); + + // If an expr is valid to cfg away it will have been removed by the + // outer stmt or expression folder before descending in here. + // Anything else is always required, and thus has to error out + // in case of a cfg attr. + // + // NB: This is intentionally not part of the fold_expr() function + // in order for fold_opt_expr() to be able to avoid this check + if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) { + let msg = "removing an expression is not supported in this position"; + self.sess.span_diagnostic.span_err(attr.span, msg); + } + + self.process_cfg_attrs(expr) + } + + pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> { + self.configure(stmt) + } +} + +impl<'a> fold::Folder for StripUnconfigured<'a> { + fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { + let foreign_mod = self.configure_foreign_mod(foreign_mod); + fold::noop_fold_foreign_mod(foreign_mod, self) + } + + fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind { + let item = self.configure_item_kind(item); + fold::noop_fold_item_kind(item, self) + } + + fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { + let mut expr = self.configure_expr(expr).unwrap(); + expr.node = self.configure_expr_kind(expr.node); + P(fold::noop_fold_expr(expr, self)) + } + + fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> { + let mut expr = configure!(self, expr).unwrap(); + expr.node = self.configure_expr_kind(expr.node); + Some(P(fold::noop_fold_expr(expr, self))) + } + + fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> { + match self.configure_stmt(stmt) { + Some(stmt) => fold::noop_fold_stmt(stmt, self), + None => return SmallVector::new(), + } + } + + fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { + fold::noop_fold_item(configure!(self, item), self) + } + + fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> { + fold::noop_fold_impl_item(configure!(self, item), self) + } + + fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> { + fold::noop_fold_trait_item(configure!(self, item), self) + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + // Don't configure interpolated AST (c.f. #34171). + // Interpolated AST will get configured once the surrounding tokens are parsed. + mac + } +} + +fn is_cfg(attr: &ast::Attribute) -> bool { + attr.check_name("cfg") +} + +pub fn is_test_or_bench(attr: &ast::Attribute) -> bool { + attr.check_name("test") || attr.check_name("bench") +} diff --git a/bash-5.1/vendor/syntex_syntax/src/diagnostic_list.rs b/bash-5.1/vendor/syntex_syntax/src/diagnostic_list.rs new file mode 100644 index 0000000..9110e98 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/diagnostic_list.rs @@ -0,0 +1,205 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_snake_case)] + +// Error messages for EXXXX errors. +// Each message should start and end with a new line, and be wrapped to 80 characters. +// In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable. +register_long_diagnostics! { + +E0534: r##" +The `inline` attribute was malformed. + +Erroneous code example: + +```compile_fail,E0534 +#[inline()] // error: expected one argument +pub fn something() {} + +fn main() {} +``` + +The parenthesized `inline` attribute requires the parameter to be specified: + +```ignore +#[inline(always)] +fn something() {} + +// or: + +#[inline(never)] +fn something() {} +``` + +Alternatively, a paren-less version of the attribute may be used to hint the +compiler about inlining opportunity: + +``` +#[inline] +fn something() {} +``` + +For more information about the inline attribute, read: +https://doc.rust-lang.org/reference.html#inline-attributes +"##, + +E0535: r##" +An unknown argument was given to the `inline` attribute. + +Erroneous code example: + +```compile_fail,E0535 +#[inline(unknown)] // error: invalid argument +pub fn something() {} + +fn main() {} +``` + +The `inline` attribute only supports two arguments: + + * always + * never + +All other arguments given to the `inline` attribute will return this error. +Example: + +``` +#[inline(never)] // ok! +pub fn something() {} + +fn main() {} +``` + +For more information about the inline attribute, https: +read://doc.rust-lang.org/reference.html#inline-attributes +"##, + +E0536: r##" +The `not` cfg-predicate was malformed. + +Erroneous code example: + +```compile_fail,E0536 +#[cfg(not())] // error: expected 1 cfg-pattern +pub fn something() {} + +pub fn main() {} +``` + +The `not` predicate expects one cfg-pattern. Example: + +``` +#[cfg(not(target_os = "linux"))] // ok! +pub fn something() {} + +pub fn main() {} +``` + +For more information about the cfg attribute, read: +https://doc.rust-lang.org/reference.html#conditional-compilation +"##, + +E0537: r##" +An unknown predicate was used inside the `cfg` attribute. + +Erroneous code example: + +```compile_fail,E0537 +#[cfg(unknown())] // error: invalid predicate `unknown` +pub fn something() {} + +pub fn main() {} +``` + +The `cfg` attribute supports only three kinds of predicates: + + * any + * all + * not + +Example: + +``` +#[cfg(not(target_os = "linux"))] // ok! +pub fn something() {} + +pub fn main() {} +``` + +For more information about the cfg attribute, read: +https://doc.rust-lang.org/reference.html#conditional-compilation +"##, + +E0558: r##" +The `export_name` attribute was malformed. + +Erroneous code example: + +```compile_fail,E0558 +#[export_name] // error: export_name attribute has invalid format +pub fn something() {} + +fn main() {} +``` + +The `export_name` attribute expects a string in order to determine the name of +the exported symbol. Example: + +``` +#[export_name = "some_function"] // ok! +pub fn something() {} + +fn main() {} +``` +"##, + +E0565: r##" +A literal was used in an attribute that doesn't support literals. + +Erroneous code example: + +```compile_fail,E0565 +#[inline("always")] // error: unsupported literal +pub fn something() {} +``` + +Literals in attributes are new and largely unsupported. Work to support literals +where appropriate is ongoing. Try using an unquoted name instead: + +``` +#[inline(always)] +pub fn something() {} +``` +"##, +} + +register_diagnostics! { + E0538, // multiple [same] items + E0539, // incorrect meta item + E0540, // multiple rustc_deprecated attributes + E0541, // unknown meta item + E0542, // missing 'since' + E0543, // missing 'reason' + E0544, // multiple stability levels + E0545, // incorrect 'issue' + E0546, // missing 'feature' + E0547, // missing 'issue' + E0548, // incorrect stability attribute type + E0549, // rustc_deprecated attribute must be paired with either stable or unstable attribute + E0550, // multiple deprecated attributes + E0551, // incorrect meta item + E0552, // unrecognized representation hint + E0553, // unrecognized enum representation hint + E0554, // #[feature] may not be used on the [] release channel + E0555, // malformed feature attribute, expected #![feature(...)] + E0556, // malformed feature, expected just one word + E0557, // feature has been removed +} diff --git a/bash-5.1/vendor/syntex_syntax/src/diagnostics/macros.rs b/bash-5.1/vendor/syntex_syntax/src/diagnostics/macros.rs new file mode 100644 index 0000000..53ab9a9 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/diagnostics/macros.rs @@ -0,0 +1,138 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// ==== SYNTEX ==== +macro_rules! __register_diagnostic { + ($code:tt, $description:tt) => (); + ($code:tt) => (); +} +macro_rules! __diagnostic_used { + ($code:tt) => (); +} +// ==== SYNTEX ==== + +#[macro_export] +macro_rules! register_diagnostic { + ($code:tt, $description:tt) => (__register_diagnostic! { $code, $description }); + ($code:tt) => (__register_diagnostic! { $code }) +} + +#[macro_export] +macro_rules! span_fatal { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.span_fatal_with_code($span, &format!($($message)*), stringify!($code)) + }) +} + +#[macro_export] +macro_rules! span_err { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.span_err_with_code($span, &format!($($message)*), stringify!($code)) + }) +} + +#[macro_export] +macro_rules! span_warn { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.span_warn_with_code($span, &format!($($message)*), stringify!($code)) + }) +} + +#[macro_export] +macro_rules! span_err_or_warn { + ($is_warning:expr, $session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + if $is_warning { + $session.span_warn_with_code($span, &format!($($message)*), stringify!($code)) + } else { + $session.span_err_with_code($span, &format!($($message)*), stringify!($code)) + } + }) +} + +#[macro_export] +macro_rules! struct_span_fatal { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.struct_span_fatal_with_code($span, &format!($($message)*), stringify!($code)) + }) +} + +#[macro_export] +macro_rules! struct_span_err { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.struct_span_err_with_code($span, &format!($($message)*), stringify!($code)) + }) +} + +#[macro_export] +macro_rules! struct_span_warn { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.struct_span_warn_with_code($span, &format!($($message)*), stringify!($code)) + }) +} + +#[macro_export] +macro_rules! struct_span_err_or_warn { + ($is_warning:expr, $session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + if $is_warning { + $session.struct_span_warn_with_code($span, &format!($($message)*), stringify!($code)) + } else { + $session.struct_span_err_with_code($span, &format!($($message)*), stringify!($code)) + } + }) +} + +#[macro_export] +macro_rules! span_note { + ($err:expr, $span:expr, $($message:tt)*) => ({ + ($err).span_note($span, &format!($($message)*)); + }) +} + +#[macro_export] +macro_rules! span_help { + ($err:expr, $span:expr, $($message:tt)*) => ({ + ($err).span_help($span, &format!($($message)*)); + }) +} + +#[macro_export] +macro_rules! help { + ($err:expr, $($message:tt)*) => ({ + ($err).help(&format!($($message)*)); + }) +} + +#[macro_export] +macro_rules! register_diagnostics { + ($($code:tt),*) => ( + $(register_diagnostic! { $code })* + ); + ($($code:tt),*,) => ( + $(register_diagnostic! { $code })* + ) +} + +#[macro_export] +macro_rules! register_long_diagnostics { + ($($code:tt: $description:tt),*) => ( + $(register_diagnostic! { $code, $description })* + ); + ($($code:tt: $description:tt),*,) => ( + $(register_diagnostic! { $code, $description })* + ) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/diagnostics/metadata.rs b/bash-5.1/vendor/syntex_syntax/src/diagnostics/metadata.rs new file mode 100644 index 0000000..ee826b6 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/diagnostics/metadata.rs @@ -0,0 +1,101 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! This module contains utilities for outputting metadata for diagnostic errors. +//! +//! Each set of errors is mapped to a metadata file by a name, which is +//! currently always a crate name. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::fs::{remove_file, create_dir_all, File}; +use std::io::Write; +use std::error::Error; +use rustc_serialize::json::as_json; + +use syntax_pos::Span; +use ext::base::ExtCtxt; +use diagnostics::plugin::{ErrorMap, ErrorInfo}; + +// Default metadata directory to use for extended error JSON. +const ERROR_METADATA_PREFIX: &'static str = "tmp/extended-errors"; + +/// JSON encodable/decodable version of `ErrorInfo`. +#[derive(PartialEq, RustcDecodable, RustcEncodable)] +pub struct ErrorMetadata { + pub description: Option<String>, + pub use_site: Option<ErrorLocation> +} + +/// Mapping from error codes to metadata that can be (de)serialized. +pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>; + +/// JSON encodable error location type with filename and line number. +#[derive(PartialEq, RustcDecodable, RustcEncodable)] +pub struct ErrorLocation { + pub filename: String, + pub line: usize +} + +impl ErrorLocation { + /// Create an error location from a span. + pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation { + let loc = ecx.codemap().lookup_char_pos_adj(sp.lo); + ErrorLocation { + filename: loc.filename, + line: loc.line + } + } +} + +/// Get the directory where metadata for a given `prefix` should be stored. +/// +/// See `output_metadata`. +pub fn get_metadata_dir(prefix: &str) -> PathBuf { + PathBuf::from(ERROR_METADATA_PREFIX).join(prefix) +} + +/// Map `name` to a path in the given directory: <directory>/<name>.json +fn get_metadata_path(directory: PathBuf, name: &str) -> PathBuf { + directory.join(format!("{}.json", name)) +} + +/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `prefix/name`. +/// +/// For our current purposes the prefix is the target architecture and the name is a crate name. +/// If an error occurs steps will be taken to ensure that no file is created. +pub fn output_metadata(ecx: &ExtCtxt, prefix: &str, name: &str, err_map: &ErrorMap) + -> Result<(), Box<Error>> +{ + // Create the directory to place the file in. + let metadata_dir = get_metadata_dir(prefix); + try!(create_dir_all(&metadata_dir)); + + // Open the metadata file. + let metadata_path = get_metadata_path(metadata_dir, name); + let mut metadata_file = try!(File::create(&metadata_path)); + + // Construct a serializable map. + let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| { + let key = k.as_str().to_string(); + let value = ErrorMetadata { + description: description.map(|n| n.as_str().to_string()), + use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp)) + }; + (key, value) + }).collect::<ErrorMetadataMap>(); + + // Write the data to the file, deleting it if the write fails. + let result = write!(&mut metadata_file, "{}", as_json(&json_map)); + if result.is_err() { + try!(remove_file(&metadata_path)); + } + result.map_err(|e| e.into()) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/diagnostics/plugin.rs b/bash-5.1/vendor/syntex_syntax/src/diagnostics/plugin.rs new file mode 100644 index 0000000..fe5cb87 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/diagnostics/plugin.rs @@ -0,0 +1,241 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::env; + +use ast; +use ast::{Ident, Name}; +use syntax_pos::Span; +use ext::base::{ExtCtxt, MacEager, MacResult}; +use ext::build::AstBuilder; +use parse::token; +use ptr::P; +use symbol::Symbol; +use tokenstream::{TokenTree}; +use util::small_vector::SmallVector; + +use diagnostics::metadata::output_metadata; + +pub use errors::*; + +// Maximum width of any line in an extended error description (inclusive). +const MAX_DESCRIPTION_WIDTH: usize = 80; + +thread_local! { + static REGISTERED_DIAGNOSTICS: RefCell<ErrorMap> = { + RefCell::new(BTreeMap::new()) + } +} + +/// Error information type. +pub struct ErrorInfo { + pub description: Option<Name>, + pub use_site: Option<Span> +} + +/// Mapping from error codes to metadata. +pub type ErrorMap = BTreeMap<Name, ErrorInfo>; + +fn with_registered_diagnostics<T, F>(f: F) -> T where + F: FnOnce(&mut ErrorMap) -> T, +{ + REGISTERED_DIAGNOSTICS.with(move |slot| { + f(&mut *slot.borrow_mut()) + }) +} + +pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, + span: Span, + token_tree: &[TokenTree]) + -> Box<MacResult+'cx> { + let code = match (token_tree.len(), token_tree.get(0)) { + (1, Some(&TokenTree::Token(_, token::Ident(code)))) => code, + _ => unreachable!() + }; + + with_registered_diagnostics(|diagnostics| { + match diagnostics.get_mut(&code.name) { + // Previously used errors. + Some(&mut ErrorInfo { description: _, use_site: Some(previous_span) }) => { + ecx.struct_span_warn(span, &format!( + "diagnostic code {} already used", code + )).span_note(previous_span, "previous invocation") + .emit(); + } + // Newly used errors. + Some(ref mut info) => { + info.use_site = Some(span); + } + // Unregistered errors. + None => { + ecx.span_err(span, &format!( + "used diagnostic code {} not registered", code + )); + } + } + }); + MacEager::expr(ecx.expr_tuple(span, Vec::new())) +} + +pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, + span: Span, + token_tree: &[TokenTree]) + -> Box<MacResult+'cx> { + let (code, description) = match ( + token_tree.len(), + token_tree.get(0), + token_tree.get(1), + token_tree.get(2) + ) { + (1, Some(&TokenTree::Token(_, token::Ident(ref code))), None, None) => { + (code, None) + }, + (3, Some(&TokenTree::Token(_, token::Ident(ref code))), + Some(&TokenTree::Token(_, token::Comma)), + Some(&TokenTree::Token(_, token::Literal(token::StrRaw(description, _), None)))) => { + (code, Some(description)) + } + _ => unreachable!() + }; + + // Check that the description starts and ends with a newline and doesn't + // overflow the maximum line width. + description.map(|raw_msg| { + let msg = raw_msg.as_str(); + if !msg.starts_with("\n") || !msg.ends_with("\n") { + ecx.span_err(span, &format!( + "description for error code {} doesn't start and end with a newline", + code + )); + } + + // URLs can be unavoidably longer than the line limit, so we allow them. + // Allowed format is: `[name]: https://www.rust-lang.org/` + let is_url = |l: &str| l.starts_with('[') && l.contains("]:") && l.contains("http"); + + if msg.lines().any(|line| line.len() > MAX_DESCRIPTION_WIDTH && !is_url(line)) { + ecx.span_err(span, &format!( + "description for error code {} contains a line longer than {} characters.\n\ + if you're inserting a long URL use the footnote style to bypass this check.", + code, MAX_DESCRIPTION_WIDTH + )); + } + }); + // Add the error to the map. + with_registered_diagnostics(|diagnostics| { + let info = ErrorInfo { + description: description, + use_site: None + }; + if diagnostics.insert(code.name, info).is_some() { + ecx.span_err(span, &format!( + "diagnostic code {} already registered", code + )); + } + }); + let sym = Ident::with_empty_ctxt(Symbol::gensym(&format!( + "__register_diagnostic_{}", code + ))); + MacEager::items(SmallVector::many(vec![ + ecx.item_mod( + span, + span, + sym, + Vec::new(), + Vec::new() + ) + ])) +} + +pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, + span: Span, + token_tree: &[TokenTree]) + -> Box<MacResult+'cx> { + assert_eq!(token_tree.len(), 3); + let (crate_name, name) = match (&token_tree[0], &token_tree[2]) { + ( + // Crate name. + &TokenTree::Token(_, token::Ident(ref crate_name)), + // DIAGNOSTICS ident. + &TokenTree::Token(_, token::Ident(ref name)) + ) => (*&crate_name, name), + _ => unreachable!() + }; + + // Output error metadata to `tmp/extended-errors/<target arch>/<crate name>.json` + if let Ok(target_triple) = env::var("CFG_COMPILER_HOST_TRIPLE") { + with_registered_diagnostics(|diagnostics| { + if let Err(e) = output_metadata(ecx, + &target_triple, + &crate_name.name.as_str(), + &diagnostics) { + ecx.span_bug(span, &format!( + "error writing metadata for triple `{}` and crate `{}`, error: {}, \ + cause: {:?}", + target_triple, crate_name, e.description(), e.cause() + )); + } + }); + } else { + ecx.span_err(span, &format!( + "failed to write metadata for crate `{}` because $CFG_COMPILER_HOST_TRIPLE is not set", + crate_name)); + } + + // Construct the output expression. + let (count, expr) = + with_registered_diagnostics(|diagnostics| { + let descriptions: Vec<P<ast::Expr>> = + diagnostics.iter().filter_map(|(&code, info)| { + info.description.map(|description| { + ecx.expr_tuple(span, vec![ + ecx.expr_str(span, code), + ecx.expr_str(span, description) + ]) + }) + }).collect(); + (descriptions.len(), ecx.expr_vec(span, descriptions)) + }); + + let static_ = ecx.lifetime(span, ecx.name_of("'static")); + let ty_str = ecx.ty_rptr( + span, + ecx.ty_ident(span, ecx.ident_of("str")), + Some(static_), + ast::Mutability::Immutable, + ); + + let ty = ecx.ty( + span, + ast::TyKind::Array( + ecx.ty( + span, + ast::TyKind::Tup(vec![ty_str.clone(), ty_str]) + ), + ecx.expr_usize(span, count), + ), + ); + + MacEager::items(SmallVector::many(vec![ + P(ast::Item { + ident: name.clone(), + attrs: Vec::new(), + id: ast::DUMMY_NODE_ID, + node: ast::ItemKind::Const( + ty, + expr, + ), + vis: ast::Visibility::Public, + span: span, + }) + ])) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/entry.rs b/bash-5.1/vendor/syntex_syntax/src/entry.rs new file mode 100644 index 0000000..93ca194 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/entry.rs @@ -0,0 +1,44 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use attr; +use ast::{Item, ItemKind}; + +pub enum EntryPointType { + None, + MainNamed, + MainAttr, + Start, + OtherMain, // Not an entry point, but some other function named main +} + +// Beware, this is duplicated in librustc/middle/entry.rs, make sure to keep +// them in sync. +pub fn entry_point_type(item: &Item, depth: usize) -> EntryPointType { + match item.node { + ItemKind::Fn(..) => { + if attr::contains_name(&item.attrs, "start") { + EntryPointType::Start + } else if attr::contains_name(&item.attrs, "main") { + EntryPointType::MainAttr + } else if item.ident.name == "main" { + if depth == 1 { + // This is a top-level function so can be 'main' + EntryPointType::MainNamed + } else { + EntryPointType::OtherMain + } + } else { + EntryPointType::None + } + } + _ => EntryPointType::None, + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/base.rs b/bash-5.1/vendor/syntex_syntax/src/ext/base.rs new file mode 100644 index 0000000..a476a8f --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/base.rs @@ -0,0 +1,849 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use self::SyntaxExtension::{MultiDecorator, MultiModifier, NormalTT, IdentTT}; + +use ast::{self, Attribute, Name, PatKind}; +use attr::HasAttrs; +use codemap::{self, CodeMap, ExpnInfo, Spanned, respan}; +use syntax_pos::{Span, ExpnId, NO_EXPANSION}; +use errors::DiagnosticBuilder; +use ext::expand::{self, Expansion}; +use ext::hygiene::Mark; +use fold::{self, Folder}; +use parse::{self, parser, DirectoryOwnership}; +use parse::token; +use ptr::P; +use symbol::Symbol; +use util::small_vector::SmallVector; + +use std::path::PathBuf; +use std::rc::Rc; +use std::default::Default; +use tokenstream::{self, TokenStream}; + + +#[derive(Debug,Clone)] +pub enum Annotatable { + Item(P<ast::Item>), + TraitItem(P<ast::TraitItem>), + ImplItem(P<ast::ImplItem>), +} + +impl HasAttrs for Annotatable { + fn attrs(&self) -> &[Attribute] { + match *self { + Annotatable::Item(ref item) => &item.attrs, + Annotatable::TraitItem(ref trait_item) => &trait_item.attrs, + Annotatable::ImplItem(ref impl_item) => &impl_item.attrs, + } + } + + fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { + match self { + Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)), + Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)), + Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)), + } + } +} + +impl Annotatable { + pub fn expect_item(self) -> P<ast::Item> { + match self { + Annotatable::Item(i) => i, + _ => panic!("expected Item") + } + } + + pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable + where F: FnMut(P<ast::Item>) -> P<ast::Item>, + G: FnMut(Annotatable) -> Annotatable + { + match self { + Annotatable::Item(i) => Annotatable::Item(f(i)), + _ => or(self) + } + } + + pub fn expect_trait_item(self) -> ast::TraitItem { + match self { + Annotatable::TraitItem(i) => i.unwrap(), + _ => panic!("expected Item") + } + } + + pub fn expect_impl_item(self) -> ast::ImplItem { + match self { + Annotatable::ImplItem(i) => i.unwrap(), + _ => panic!("expected Item") + } + } +} + +// A more flexible ItemDecorator. +pub trait MultiItemDecorator { + fn expand(&self, + ecx: &mut ExtCtxt, + sp: Span, + meta_item: &ast::MetaItem, + item: &Annotatable, + push: &mut FnMut(Annotatable)); +} + +impl<F> MultiItemDecorator for F + where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable)) +{ + fn expand(&self, + ecx: &mut ExtCtxt, + sp: Span, + meta_item: &ast::MetaItem, + item: &Annotatable, + push: &mut FnMut(Annotatable)) { + (*self)(ecx, sp, meta_item, item, push) + } +} + +// `meta_item` is the annotation, and `item` is the item being modified. +// FIXME Decorators should follow the same pattern too. +pub trait MultiItemModifier { + fn expand(&self, + ecx: &mut ExtCtxt, + span: Span, + meta_item: &ast::MetaItem, + item: Annotatable) + -> Vec<Annotatable>; +} + +impl<F, T> MultiItemModifier for F + where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T, + T: Into<Vec<Annotatable>>, +{ + fn expand(&self, + ecx: &mut ExtCtxt, + span: Span, + meta_item: &ast::MetaItem, + item: Annotatable) + -> Vec<Annotatable> { + (*self)(ecx, span, meta_item, item).into() + } +} + +impl Into<Vec<Annotatable>> for Annotatable { + fn into(self) -> Vec<Annotatable> { + vec![self] + } +} + +pub trait ProcMacro { + fn expand<'cx>(&self, + ecx: &'cx mut ExtCtxt, + span: Span, + ts: TokenStream) + -> TokenStream; +} + +impl<F> ProcMacro for F + where F: Fn(TokenStream) -> TokenStream +{ + fn expand<'cx>(&self, + _ecx: &'cx mut ExtCtxt, + _span: Span, + ts: TokenStream) + -> TokenStream { + // FIXME setup implicit context in TLS before calling self. + (*self)(ts) + } +} + +pub trait AttrProcMacro { + fn expand<'cx>(&self, + ecx: &'cx mut ExtCtxt, + span: Span, + annotation: TokenStream, + annotated: TokenStream) + -> TokenStream; +} + +impl<F> AttrProcMacro for F + where F: Fn(TokenStream, TokenStream) -> TokenStream +{ + fn expand<'cx>(&self, + _ecx: &'cx mut ExtCtxt, + _span: Span, + annotation: TokenStream, + annotated: TokenStream) + -> TokenStream { + // FIXME setup implicit context in TLS before calling self. + (*self)(annotation, annotated) + } +} + +/// Represents a thing that maps token trees to Macro Results +pub trait TTMacroExpander { + fn expand<'cx>(&self, + ecx: &'cx mut ExtCtxt, + span: Span, + token_tree: &[tokenstream::TokenTree]) + -> Box<MacResult+'cx>; +} + +pub type MacroExpanderFn = + for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree]) + -> Box<MacResult+'cx>; + +impl<F> TTMacroExpander for F + where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree]) + -> Box<MacResult+'cx> +{ + fn expand<'cx>(&self, + ecx: &'cx mut ExtCtxt, + span: Span, + token_tree: &[tokenstream::TokenTree]) + -> Box<MacResult+'cx> { + (*self)(ecx, span, token_tree) + } +} + +pub trait IdentMacroExpander { + fn expand<'cx>(&self, + cx: &'cx mut ExtCtxt, + sp: Span, + ident: ast::Ident, + token_tree: Vec<tokenstream::TokenTree>) + -> Box<MacResult+'cx>; +} + +pub type IdentMacroExpanderFn = + for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>) + -> Box<MacResult+'cx>; + +impl<F> IdentMacroExpander for F + where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident, + Vec<tokenstream::TokenTree>) -> Box<MacResult+'cx> +{ + fn expand<'cx>(&self, + cx: &'cx mut ExtCtxt, + sp: Span, + ident: ast::Ident, + token_tree: Vec<tokenstream::TokenTree>) + -> Box<MacResult+'cx> + { + (*self)(cx, sp, ident, token_tree) + } +} + +// Use a macro because forwarding to a simple function has type system issues +macro_rules! make_stmts_default { + ($me:expr) => { + $me.make_expr().map(|e| SmallVector::one(ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: e.span, + node: ast::StmtKind::Expr(e), + })) + } +} + +/// The result of a macro expansion. The return values of the various +/// methods are spliced into the AST at the callsite of the macro. +pub trait MacResult { + /// Create an expression. + fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> { + None + } + /// Create zero or more items. + fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> { + None + } + + /// Create zero or more impl items. + fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> { + None + } + + /// Create zero or more trait items. + fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> { + None + } + + /// Create a pattern. + fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> { + None + } + + /// Create zero or more statements. + /// + /// By default this attempts to create an expression statement, + /// returning None if that fails. + fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> { + make_stmts_default!(self) + } + + fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> { + None + } +} + +macro_rules! make_MacEager { + ( $( $fld:ident: $t:ty, )* ) => { + /// `MacResult` implementation for the common case where you've already + /// built each form of AST that you might return. + #[derive(Default)] + pub struct MacEager { + $( + pub $fld: Option<$t>, + )* + } + + impl MacEager { + $( + pub fn $fld(v: $t) -> Box<MacResult> { + Box::new(MacEager { + $fld: Some(v), + ..Default::default() + }) + } + )* + } + } +} + +make_MacEager! { + expr: P<ast::Expr>, + pat: P<ast::Pat>, + items: SmallVector<P<ast::Item>>, + impl_items: SmallVector<ast::ImplItem>, + trait_items: SmallVector<ast::TraitItem>, + stmts: SmallVector<ast::Stmt>, + ty: P<ast::Ty>, +} + +impl MacResult for MacEager { + fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> { + self.expr + } + + fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> { + self.items + } + + fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> { + self.impl_items + } + + fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> { + self.trait_items + } + + fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> { + match self.stmts.as_ref().map_or(0, |s| s.len()) { + 0 => make_stmts_default!(self), + _ => self.stmts, + } + } + + fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> { + if let Some(p) = self.pat { + return Some(p); + } + if let Some(e) = self.expr { + if let ast::ExprKind::Lit(_) = e.node { + return Some(P(ast::Pat { + id: ast::DUMMY_NODE_ID, + span: e.span, + node: PatKind::Lit(e), + })); + } + } + None + } + + fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> { + self.ty + } +} + +/// Fill-in macro expansion result, to allow compilation to continue +/// after hitting errors. +#[derive(Copy, Clone)] +pub struct DummyResult { + expr_only: bool, + span: Span +} + +impl DummyResult { + /// Create a default MacResult that can be anything. + /// + /// Use this as a return value after hitting any errors and + /// calling `span_err`. + pub fn any(sp: Span) -> Box<MacResult+'static> { + Box::new(DummyResult { expr_only: false, span: sp }) + } + + /// Create a default MacResult that can only be an expression. + /// + /// Use this for macros that must expand to an expression, so even + /// if an error is encountered internally, the user will receive + /// an error that they also used it in the wrong place. + pub fn expr(sp: Span) -> Box<MacResult+'static> { + Box::new(DummyResult { expr_only: true, span: sp }) + } + + /// A plain dummy expression. + pub fn raw_expr(sp: Span) -> P<ast::Expr> { + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Lit(P(codemap::respan(sp, ast::LitKind::Bool(false)))), + span: sp, + attrs: ast::ThinVec::new(), + }) + } + + /// A plain dummy pattern. + pub fn raw_pat(sp: Span) -> ast::Pat { + ast::Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Wild, + span: sp, + } + } + + pub fn raw_ty(sp: Span) -> P<ast::Ty> { + P(ast::Ty { + id: ast::DUMMY_NODE_ID, + node: ast::TyKind::Infer, + span: sp + }) + } +} + +impl MacResult for DummyResult { + fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> { + Some(DummyResult::raw_expr(self.span)) + } + + fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> { + Some(P(DummyResult::raw_pat(self.span))) + } + + fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> { + // this code needs a comment... why not always just return the Some() ? + if self.expr_only { + None + } else { + Some(SmallVector::new()) + } + } + + fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<ast::ImplItem>> { + if self.expr_only { + None + } else { + Some(SmallVector::new()) + } + } + + fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVector<ast::TraitItem>> { + if self.expr_only { + None + } else { + Some(SmallVector::new()) + } + } + + fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<ast::Stmt>> { + Some(SmallVector::one(ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)), + span: self.span, + })) + } + + fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> { + Some(DummyResult::raw_ty(self.span)) + } +} + +/// An enum representing the different kinds of syntax extensions. +pub enum SyntaxExtension { + /// A syntax extension that is attached to an item and creates new items + /// based upon it. + /// + /// `#[derive(...)]` is a `MultiItemDecorator`. + /// + /// Prefer ProcMacro or MultiModifier since they are more flexible. + MultiDecorator(Box<MultiItemDecorator>), + + /// A syntax extension that is attached to an item and modifies it + /// in-place. Also allows decoration, i.e., creating new items. + MultiModifier(Box<MultiItemModifier>), + + /// A function-like procedural macro. TokenStream -> TokenStream. + ProcMacro(Box<ProcMacro>), + + /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream. + /// The first TokenSteam is the attribute, the second is the annotated item. + /// Allows modification of the input items and adding new items, similar to + /// MultiModifier, but uses TokenStreams, rather than AST nodes. + AttrProcMacro(Box<AttrProcMacro>), + + /// A normal, function-like syntax extension. + /// + /// `bytes!` is a `NormalTT`. + /// + /// The `bool` dictates whether the contents of the macro can + /// directly use `#[unstable]` things (true == yes). + NormalTT(Box<TTMacroExpander>, Option<Span>, bool), + + /// A function-like syntax extension that has an extra ident before + /// the block. + /// + IdentTT(Box<IdentMacroExpander>, Option<Span>, bool), + + CustomDerive(Box<MultiItemModifier>), +} + +pub type NamedSyntaxExtension = (Name, SyntaxExtension); + +pub trait Resolver { + fn next_node_id(&mut self) -> ast::NodeId; + fn get_module_scope(&mut self, id: ast::NodeId) -> Mark; + fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>; + fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool; + + fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion); + fn add_ext(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>); + fn add_expansions_at_stmt(&mut self, id: ast::NodeId, macros: Vec<Mark>); + + fn resolve_imports(&mut self); + fn find_attr_invoc(&mut self, attrs: &mut Vec<Attribute>) -> Option<Attribute>; + // FIXME(syntax): ignore unknown macros + fn find_extension(&mut self, scope: Mark, name: ast::Name) -> Option<Rc<SyntaxExtension>>; + fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, force: bool) + -> Result<Rc<SyntaxExtension>, Determinacy>; +} + +#[derive(Copy, Clone, Debug)] +pub enum Determinacy { + Determined, + Undetermined, +} + +pub struct DummyResolver; + +impl Resolver for DummyResolver { + fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID } + fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() } + fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item } + fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false } + + fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion) {} + fn add_ext(&mut self, _ident: ast::Ident, _ext: Rc<SyntaxExtension>) {} + fn add_expansions_at_stmt(&mut self, _id: ast::NodeId, _macros: Vec<Mark>) {} + + fn resolve_imports(&mut self) {} + fn find_attr_invoc(&mut self, _attrs: &mut Vec<Attribute>) -> Option<Attribute> { None } + fn find_extension(&mut self, _scope: Mark, _name: ast::Name) -> Option<Rc<SyntaxExtension>> { + None + } + fn resolve_macro(&mut self, _scope: Mark, _path: &ast::Path, _force: bool) + -> Result<Rc<SyntaxExtension>, Determinacy> { + Err(Determinacy::Determined) + } +} + +#[derive(Clone)] +pub struct ModuleData { + pub mod_path: Vec<ast::Ident>, + pub directory: PathBuf, +} + +#[derive(Clone)] +pub struct ExpansionData { + pub mark: Mark, + pub depth: usize, + pub backtrace: ExpnId, + pub module: Rc<ModuleData>, + pub directory_ownership: DirectoryOwnership, +} + +/// One of these is made during expansion and incrementally updated as we go; +/// when a macro expansion occurs, the resulting nodes have the backtrace() +/// -> expn_info of their expansion context stored into their span. +pub struct ExtCtxt<'a> { + pub parse_sess: &'a parse::ParseSess, + pub ecfg: expand::ExpansionConfig<'a>, + pub crate_root: Option<&'static str>, + pub resolver: &'a mut Resolver, + pub resolve_err_count: usize, + pub current_expansion: ExpansionData, +} + +impl<'a> ExtCtxt<'a> { + pub fn new(parse_sess: &'a parse::ParseSess, + ecfg: expand::ExpansionConfig<'a>, + resolver: &'a mut Resolver) + -> ExtCtxt<'a> { + ExtCtxt { + parse_sess: parse_sess, + ecfg: ecfg, + crate_root: None, + resolver: resolver, + resolve_err_count: 0, + current_expansion: ExpansionData { + mark: Mark::root(), + depth: 0, + backtrace: NO_EXPANSION, + module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }), + directory_ownership: DirectoryOwnership::Owned, + }, + } + } + + /// Returns a `Folder` for deeply expanding all macros in an AST node. + pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> { + expand::MacroExpander::new(self, false) + } + + /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node. + /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified. + pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> { + expand::MacroExpander::new(self, true) + } + + pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) + -> parser::Parser<'a> { + let mut parser = parse::tts_to_parser(self.parse_sess, tts.to_vec()); + parser.allow_interpolated_tts = false; // FIXME(jseyfried) `quote!` can't handle these yet + parser + } + pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() } + pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess } + pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config } + pub fn call_site(&self) -> Span { + self.codemap().with_expn_info(self.backtrace(), |ei| match ei { + Some(expn_info) => expn_info.call_site, + None => self.bug("missing top span") + }) + } + pub fn backtrace(&self) -> ExpnId { self.current_expansion.backtrace } + + /// Returns span for the macro which originally caused the current expansion to happen. + /// + /// Stops backtracing at include! boundary. + pub fn expansion_cause(&self) -> Span { + let mut expn_id = self.backtrace(); + let mut last_macro = None; + loop { + if self.codemap().with_expn_info(expn_id, |info| { + info.map_or(None, |i| { + if i.callee.name() == "include" { + // Stop going up the backtrace once include! is encountered + return None; + } + expn_id = i.call_site.expn_id; + last_macro = Some(i.call_site); + return Some(()); + }) + }).is_none() { + break + } + } + last_macro.expect("missing expansion backtrace") + } + + pub fn bt_push(&mut self, ei: ExpnInfo) { + if self.current_expansion.depth > self.ecfg.recursion_limit { + self.span_fatal(ei.call_site, + &format!("recursion limit reached while expanding the macro `{}`", + ei.callee.name())); + } + + let mut call_site = ei.call_site; + call_site.expn_id = self.backtrace(); + self.current_expansion.backtrace = self.codemap().record_expansion(ExpnInfo { + call_site: call_site, + callee: ei.callee + }); + } + pub fn bt_pop(&mut self) {} + + pub fn struct_span_warn(&self, + sp: Span, + msg: &str) + -> DiagnosticBuilder<'a> { + self.parse_sess.span_diagnostic.struct_span_warn(sp, msg) + } + pub fn struct_span_err(&self, + sp: Span, + msg: &str) + -> DiagnosticBuilder<'a> { + self.parse_sess.span_diagnostic.struct_span_err(sp, msg) + } + pub fn struct_span_fatal(&self, + sp: Span, + msg: &str) + -> DiagnosticBuilder<'a> { + self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg) + } + + /// Emit `msg` attached to `sp`, and stop compilation immediately. + /// + /// `span_err` should be strongly preferred where-ever possible: + /// this should *only* be used when + /// - continuing has a high risk of flow-on errors (e.g. errors in + /// declaring a macro would cause all uses of that macro to + /// complain about "undefined macro"), or + /// - there is literally nothing else that can be done (however, + /// in most cases one can construct a dummy expression/item to + /// substitute; we never hit resolve/type-checking so the dummy + /// value doesn't have to match anything) + pub fn span_fatal(&self, sp: Span, msg: &str) -> ! { + panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg)); + } + + /// Emit `msg` attached to `sp`, without immediately stopping + /// compilation. + /// + /// Compilation will be stopped in the near future (at the end of + /// the macro expansion phase). + pub fn span_err(&self, sp: Span, msg: &str) { + self.parse_sess.span_diagnostic.span_err(sp, msg); + } + pub fn span_warn(&self, sp: Span, msg: &str) { + self.parse_sess.span_diagnostic.span_warn(sp, msg); + } + pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! { + self.parse_sess.span_diagnostic.span_unimpl(sp, msg); + } + pub fn span_bug(&self, sp: Span, msg: &str) -> ! { + self.parse_sess.span_diagnostic.span_bug(sp, msg); + } + pub fn bug(&self, msg: &str) -> ! { + self.parse_sess.span_diagnostic.bug(msg); + } + pub fn trace_macros(&self) -> bool { + self.ecfg.trace_mac + } + pub fn set_trace_macros(&mut self, x: bool) { + self.ecfg.trace_mac = x + } + pub fn ident_of(&self, st: &str) -> ast::Ident { + ast::Ident::from_str(st) + } + pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> { + let mut v = Vec::new(); + if let Some(s) = self.crate_root { + v.push(self.ident_of(s)); + } + v.extend(components.iter().map(|s| self.ident_of(s))); + return v + } + pub fn name_of(&self, st: &str) -> ast::Name { + Symbol::intern(st) + } +} + +/// Extract a string literal from the macro expanded version of `expr`, +/// emitting `err_msg` if `expr` is not a string literal. This does not stop +/// compilation on error, merely emits a non-fatal error and returns None. +pub fn expr_to_spanned_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str) + -> Option<Spanned<(Symbol, ast::StrStyle)>> { + // Update `expr.span`'s expn_id now in case expr is an `include!` macro invocation. + let expr = expr.map(|mut expr| { + expr.span.expn_id = cx.backtrace(); + expr + }); + + // we want to be able to handle e.g. concat("foo", "bar") + let expr = cx.expander().fold_expr(expr); + match expr.node { + ast::ExprKind::Lit(ref l) => match l.node { + ast::LitKind::Str(s, style) => return Some(respan(expr.span, (s, style))), + _ => cx.span_err(l.span, err_msg) + }, + _ => cx.span_err(expr.span, err_msg) + } + None +} + +pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str) + -> Option<(Symbol, ast::StrStyle)> { + expr_to_spanned_string(cx, expr, err_msg).map(|s| s.node) +} + +/// Non-fatally assert that `tts` is empty. Note that this function +/// returns even when `tts` is non-empty, macros that *need* to stop +/// compilation should call +/// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be +/// done as rarely as possible). +pub fn check_zero_tts(cx: &ExtCtxt, + sp: Span, + tts: &[tokenstream::TokenTree], + name: &str) { + if !tts.is_empty() { + cx.span_err(sp, &format!("{} takes no arguments", name)); + } +} + +/// Extract the string literal from the first token of `tts`. If this +/// is not a string literal, emit an error and return None. +pub fn get_single_str_from_tts(cx: &mut ExtCtxt, + sp: Span, + tts: &[tokenstream::TokenTree], + name: &str) + -> Option<String> { + let mut p = cx.new_parser_from_tts(tts); + if p.token == token::Eof { + cx.span_err(sp, &format!("{} takes 1 argument", name)); + return None + } + let ret = panictry!(p.parse_expr()); + if p.token != token::Eof { + cx.span_err(sp, &format!("{} takes 1 argument", name)); + } + expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| { + s.to_string() + }) +} + +/// Extract comma-separated expressions from `tts`. If there is a +/// parsing error, emit a non-fatal error and return None. +pub fn get_exprs_from_tts(cx: &mut ExtCtxt, + sp: Span, + tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> { + let mut p = cx.new_parser_from_tts(tts); + let mut es = Vec::new(); + while p.token != token::Eof { + es.push(cx.expander().fold_expr(panictry!(p.parse_expr()))); + if p.eat(&token::Comma) { + continue; + } + if p.token != token::Eof { + cx.span_err(sp, "expected token: `,`"); + return None; + } + } + Some(es) +} + +pub struct ChangeSpan { + pub span: Span +} + +impl Folder for ChangeSpan { + fn new_span(&mut self, _sp: Span) -> Span { + self.span + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + fold::noop_fold_mac(mac, self) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/build.rs b/bash-5.1/vendor/syntex_syntax/src/ext/build.rs new file mode 100644 index 0000000..b101148 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/build.rs @@ -0,0 +1,1208 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use abi::Abi; +use ast::{self, Ident, Generics, Expr, BlockCheckMode, UnOp, PatKind}; +use attr; +use syntax_pos::{Span, DUMMY_SP}; +use codemap::{dummy_spanned, respan, Spanned}; +use ext::base::ExtCtxt; +use ptr::P; +use symbol::{Symbol, keywords}; + +// Transitional reexports so qquote can find the paths it is looking for +mod syntax { + pub use ext; + pub use parse; +} + +pub trait AstBuilder { + // paths + fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path; + fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path; + fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path; + fn path_all(&self, sp: Span, + global: bool, + idents: Vec<ast::Ident> , + lifetimes: Vec<ast::Lifetime>, + types: Vec<P<ast::Ty>>, + bindings: Vec<ast::TypeBinding> ) + -> ast::Path; + + fn qpath(&self, self_type: P<ast::Ty>, + trait_path: ast::Path, + ident: ast::Ident) + -> (ast::QSelf, ast::Path); + fn qpath_all(&self, self_type: P<ast::Ty>, + trait_path: ast::Path, + ident: ast::Ident, + lifetimes: Vec<ast::Lifetime>, + types: Vec<P<ast::Ty>>, + bindings: Vec<ast::TypeBinding>) + -> (ast::QSelf, ast::Path); + + // types + fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy; + + fn ty(&self, span: Span, ty: ast::TyKind) -> P<ast::Ty>; + fn ty_path(&self, ast::Path) -> P<ast::Ty>; + fn ty_sum(&self, ast::Path, ast::TyParamBounds) -> P<ast::Ty>; + fn ty_ident(&self, span: Span, idents: ast::Ident) -> P<ast::Ty>; + + fn ty_rptr(&self, span: Span, + ty: P<ast::Ty>, + lifetime: Option<ast::Lifetime>, + mutbl: ast::Mutability) -> P<ast::Ty>; + fn ty_ptr(&self, span: Span, + ty: P<ast::Ty>, + mutbl: ast::Mutability) -> P<ast::Ty>; + + fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty>; + fn ty_infer(&self, sp: Span) -> P<ast::Ty>; + + fn ty_vars(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> ; + fn ty_vars_global(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> ; + + fn typaram(&self, + span: Span, + id: ast::Ident, + attrs: Vec<ast::Attribute>, + bounds: ast::TyParamBounds, + default: Option<P<ast::Ty>>) -> ast::TyParam; + + fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; + fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; + fn typarambound(&self, path: ast::Path) -> ast::TyParamBound; + fn lifetime(&self, span: Span, ident: ast::Name) -> ast::Lifetime; + fn lifetime_def(&self, + span: Span, + name: ast::Name, + attrs: Vec<ast::Attribute>, + bounds: Vec<ast::Lifetime>) + -> ast::LifetimeDef; + + // statements + fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt; + fn stmt_semi(&self, expr: P<ast::Expr>) -> ast::Stmt; + fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, ex: P<ast::Expr>) -> ast::Stmt; + fn stmt_let_typed(&self, + sp: Span, + mutbl: bool, + ident: ast::Ident, + typ: P<ast::Ty>, + ex: P<ast::Expr>) + -> ast::Stmt; + fn stmt_let_type_only(&self, span: Span, ty: P<ast::Ty>) -> ast::Stmt; + fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt; + + // blocks + fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block>; + fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block>; + + // expressions + fn expr(&self, span: Span, node: ast::ExprKind) -> P<ast::Expr>; + fn expr_path(&self, path: ast::Path) -> P<ast::Expr>; + fn expr_qpath(&self, span: Span, qself: ast::QSelf, path: ast::Path) -> P<ast::Expr>; + fn expr_ident(&self, span: Span, id: ast::Ident) -> P<ast::Expr>; + + fn expr_self(&self, span: Span) -> P<ast::Expr>; + fn expr_binary(&self, sp: Span, op: ast::BinOpKind, + lhs: P<ast::Expr>, rhs: P<ast::Expr>) -> P<ast::Expr>; + fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; + fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P<ast::Expr>) -> P<ast::Expr>; + + fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; + fn expr_mut_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; + fn expr_field_access(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>; + fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, + idx: usize) -> P<ast::Expr>; + fn expr_call(&self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>) -> P<ast::Expr>; + fn expr_call_ident(&self, span: Span, id: ast::Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr>; + fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident>, + args: Vec<P<ast::Expr>> ) -> P<ast::Expr>; + fn expr_method_call(&self, span: Span, + expr: P<ast::Expr>, ident: ast::Ident, + args: Vec<P<ast::Expr>> ) -> P<ast::Expr>; + fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr>; + fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr>; + + fn field_imm(&self, span: Span, name: Ident, e: P<ast::Expr>) -> ast::Field; + fn expr_struct(&self, span: Span, path: ast::Path, fields: Vec<ast::Field>) -> P<ast::Expr>; + fn expr_struct_ident(&self, span: Span, id: ast::Ident, + fields: Vec<ast::Field>) -> P<ast::Expr>; + + fn expr_lit(&self, sp: Span, lit: ast::LitKind) -> P<ast::Expr>; + + fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr>; + fn expr_isize(&self, sp: Span, i: isize) -> P<ast::Expr>; + fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr>; + fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr>; + fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr>; + + fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr>; + fn expr_vec_ng(&self, sp: Span) -> P<ast::Expr>; + fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr>; + fn expr_str(&self, sp: Span, s: Symbol) -> P<ast::Expr>; + + fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr>; + fn expr_none(&self, sp: Span) -> P<ast::Expr>; + + fn expr_break(&self, sp: Span) -> P<ast::Expr>; + + fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr>; + + fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr>; + fn expr_unreachable(&self, span: Span) -> P<ast::Expr>; + + fn expr_ok(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Expr>; + fn expr_err(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Expr>; + fn expr_try(&self, span: Span, head: P<ast::Expr>) -> P<ast::Expr>; + + fn pat(&self, span: Span, pat: PatKind) -> P<ast::Pat>; + fn pat_wild(&self, span: Span) -> P<ast::Pat>; + fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat>; + fn pat_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Pat>; + + fn pat_ident_binding_mode(&self, + span: Span, + ident: ast::Ident, + bm: ast::BindingMode) -> P<ast::Pat>; + fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat>; + fn pat_tuple_struct(&self, span: Span, path: ast::Path, + subpats: Vec<P<ast::Pat>>) -> P<ast::Pat>; + fn pat_struct(&self, span: Span, path: ast::Path, + field_pats: Vec<Spanned<ast::FieldPat>>) -> P<ast::Pat>; + fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat>; + + fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat>; + fn pat_none(&self, span: Span) -> P<ast::Pat>; + + fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat>; + fn pat_err(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat>; + + fn arm(&self, span: Span, pats: Vec<P<ast::Pat>>, expr: P<ast::Expr>) -> ast::Arm; + fn arm_unreachable(&self, span: Span) -> ast::Arm; + + fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm> ) -> P<ast::Expr>; + fn expr_if(&self, span: Span, + cond: P<ast::Expr>, then: P<ast::Expr>, els: Option<P<ast::Expr>>) -> P<ast::Expr>; + fn expr_loop(&self, span: Span, block: P<ast::Block>) -> P<ast::Expr>; + + fn lambda_fn_decl(&self, + span: Span, + fn_decl: P<ast::FnDecl>, + body: P<ast::Expr>, + fn_decl_span: Span) + -> P<ast::Expr>; + + fn lambda(&self, span: Span, ids: Vec<ast::Ident>, body: P<ast::Expr>) -> P<ast::Expr>; + fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr>; + fn lambda1(&self, span: Span, body: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>; + + fn lambda_stmts(&self, span: Span, ids: Vec<ast::Ident>, + blk: Vec<ast::Stmt>) -> P<ast::Expr>; + fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr>; + fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, + ident: ast::Ident) -> P<ast::Expr>; + + // items + fn item(&self, span: Span, + name: Ident, attrs: Vec<ast::Attribute> , node: ast::ItemKind) -> P<ast::Item>; + + fn arg(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> ast::Arg; + // FIXME unused self + fn fn_decl(&self, inputs: Vec<ast::Arg> , output: P<ast::Ty>) -> P<ast::FnDecl>; + + fn item_fn_poly(&self, + span: Span, + name: Ident, + inputs: Vec<ast::Arg> , + output: P<ast::Ty>, + generics: Generics, + body: P<ast::Block>) -> P<ast::Item>; + fn item_fn(&self, + span: Span, + name: Ident, + inputs: Vec<ast::Arg> , + output: P<ast::Ty>, + body: P<ast::Block>) -> P<ast::Item>; + + fn variant(&self, span: Span, name: Ident, tys: Vec<P<ast::Ty>> ) -> ast::Variant; + fn item_enum_poly(&self, + span: Span, + name: Ident, + enum_definition: ast::EnumDef, + generics: Generics) -> P<ast::Item>; + fn item_enum(&self, span: Span, name: Ident, enum_def: ast::EnumDef) -> P<ast::Item>; + + fn item_struct_poly(&self, + span: Span, + name: Ident, + struct_def: ast::VariantData, + generics: Generics) -> P<ast::Item>; + fn item_struct(&self, span: Span, name: Ident, struct_def: ast::VariantData) -> P<ast::Item>; + + fn item_mod(&self, span: Span, inner_span: Span, + name: Ident, attrs: Vec<ast::Attribute>, + items: Vec<P<ast::Item>>) -> P<ast::Item>; + + fn item_static(&self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + mutbl: ast::Mutability, + expr: P<ast::Expr>) + -> P<ast::Item>; + + fn item_const(&self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + expr: P<ast::Expr>) + -> P<ast::Item>; + + fn item_ty_poly(&self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + generics: Generics) -> P<ast::Item>; + fn item_ty(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> P<ast::Item>; + + fn attribute(&self, sp: Span, mi: ast::MetaItem) -> ast::Attribute; + + fn meta_word(&self, sp: Span, w: ast::Name) -> ast::MetaItem; + + fn meta_list_item_word(&self, sp: Span, w: ast::Name) -> ast::NestedMetaItem; + + fn meta_list(&self, + sp: Span, + name: ast::Name, + mis: Vec<ast::NestedMetaItem> ) + -> ast::MetaItem; + fn meta_name_value(&self, + sp: Span, + name: ast::Name, + value: ast::LitKind) + -> ast::MetaItem; + + fn item_use(&self, sp: Span, + vis: ast::Visibility, vp: P<ast::ViewPath>) -> P<ast::Item>; + fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item>; + fn item_use_simple_(&self, sp: Span, vis: ast::Visibility, + ident: ast::Ident, path: ast::Path) -> P<ast::Item>; + fn item_use_list(&self, sp: Span, vis: ast::Visibility, + path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item>; + fn item_use_glob(&self, sp: Span, + vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item>; +} + +impl<'a> AstBuilder for ExtCtxt<'a> { + fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { + self.path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new()) + } + fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path { + self.path(span, vec![id]) + } + fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { + self.path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new()) + } + fn path_all(&self, + sp: Span, + global: bool, + mut idents: Vec<ast::Ident> , + lifetimes: Vec<ast::Lifetime>, + types: Vec<P<ast::Ty>>, + bindings: Vec<ast::TypeBinding> ) + -> ast::Path { + let last_identifier = idents.pop().unwrap(); + let mut segments: Vec<ast::PathSegment> = Vec::new(); + if global { + segments.push(ast::PathSegment::crate_root()); + } + + segments.extend(idents.into_iter().map(Into::into)); + let parameters = if lifetimes.is_empty() && types.is_empty() && bindings.is_empty() { + None + } else { + Some(P(ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData { + lifetimes: lifetimes, + types: P::from_vec(types), + bindings: P::from_vec(bindings), + }))) + }; + segments.push(ast::PathSegment { identifier: last_identifier, parameters: parameters }); + ast::Path { + span: sp, + segments: segments, + } + } + + /// Constructs a qualified path. + /// + /// Constructs a path like `<self_type as trait_path>::ident`. + fn qpath(&self, + self_type: P<ast::Ty>, + trait_path: ast::Path, + ident: ast::Ident) + -> (ast::QSelf, ast::Path) { + self.qpath_all(self_type, trait_path, ident, vec![], vec![], vec![]) + } + + /// Constructs a qualified path. + /// + /// Constructs a path like `<self_type as trait_path>::ident<'a, T, A=Bar>`. + fn qpath_all(&self, + self_type: P<ast::Ty>, + trait_path: ast::Path, + ident: ast::Ident, + lifetimes: Vec<ast::Lifetime>, + types: Vec<P<ast::Ty>>, + bindings: Vec<ast::TypeBinding>) + -> (ast::QSelf, ast::Path) { + let mut path = trait_path; + let parameters = ast::AngleBracketedParameterData { + lifetimes: lifetimes, + types: P::from_vec(types), + bindings: P::from_vec(bindings), + }; + path.segments.push(ast::PathSegment { + identifier: ident, + parameters: Some(P(ast::PathParameters::AngleBracketed(parameters))), + }); + + (ast::QSelf { + ty: self_type, + position: path.segments.len() - 1 + }, path) + } + + fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy { + ast::MutTy { + ty: ty, + mutbl: mutbl + } + } + + fn ty(&self, span: Span, ty: ast::TyKind) -> P<ast::Ty> { + P(ast::Ty { + id: ast::DUMMY_NODE_ID, + span: span, + node: ty + }) + } + + fn ty_path(&self, path: ast::Path) -> P<ast::Ty> { + self.ty(path.span, ast::TyKind::Path(None, path)) + } + + fn ty_sum(&self, path: ast::Path, bounds: ast::TyParamBounds) -> P<ast::Ty> { + self.ty(path.span, + ast::TyKind::ObjectSum(self.ty_path(path), + bounds)) + } + + // Might need to take bounds as an argument in the future, if you ever want + // to generate a bounded existential trait type. + fn ty_ident(&self, span: Span, ident: ast::Ident) + -> P<ast::Ty> { + self.ty_path(self.path_ident(span, ident)) + } + + fn ty_rptr(&self, + span: Span, + ty: P<ast::Ty>, + lifetime: Option<ast::Lifetime>, + mutbl: ast::Mutability) + -> P<ast::Ty> { + self.ty(span, + ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl))) + } + + fn ty_ptr(&self, + span: Span, + ty: P<ast::Ty>, + mutbl: ast::Mutability) + -> P<ast::Ty> { + self.ty(span, + ast::TyKind::Ptr(self.ty_mt(ty, mutbl))) + } + + fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty> { + self.ty_path( + self.path_all(DUMMY_SP, + true, + self.std_path(&["option", "Option"]), + Vec::new(), + vec![ ty ], + Vec::new())) + } + + fn ty_infer(&self, span: Span) -> P<ast::Ty> { + self.ty(span, ast::TyKind::Infer) + } + + fn typaram(&self, + span: Span, + id: ast::Ident, + attrs: Vec<ast::Attribute>, + bounds: ast::TyParamBounds, + default: Option<P<ast::Ty>>) -> ast::TyParam { + ast::TyParam { + ident: id, + id: ast::DUMMY_NODE_ID, + attrs: attrs.into(), + bounds: bounds, + default: default, + span: span + } + } + + // these are strange, and probably shouldn't be used outside of + // pipes. Specifically, the global version possible generates + // incorrect code. + fn ty_vars(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> { + ty_params.iter().map(|p| self.ty_ident(DUMMY_SP, p.ident)).collect() + } + + fn ty_vars_global(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> { + ty_params + .iter() + .map(|p| self.ty_path(self.path_global(DUMMY_SP, vec![p.ident]))) + .collect() + } + + fn trait_ref(&self, path: ast::Path) -> ast::TraitRef { + ast::TraitRef { + path: path, + ref_id: ast::DUMMY_NODE_ID, + } + } + + fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef { + ast::PolyTraitRef { + bound_lifetimes: Vec::new(), + trait_ref: self.trait_ref(path), + span: span, + } + } + + fn typarambound(&self, path: ast::Path) -> ast::TyParamBound { + ast::TraitTyParamBound(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) + } + + fn lifetime(&self, span: Span, name: ast::Name) -> ast::Lifetime { + ast::Lifetime { id: ast::DUMMY_NODE_ID, span: span, name: name } + } + + fn lifetime_def(&self, + span: Span, + name: ast::Name, + attrs: Vec<ast::Attribute>, + bounds: Vec<ast::Lifetime>) + -> ast::LifetimeDef { + ast::LifetimeDef { + attrs: attrs.into(), + lifetime: self.lifetime(span, name), + bounds: bounds + } + } + + fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt { + ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: expr.span, + node: ast::StmtKind::Expr(expr), + } + } + + fn stmt_semi(&self, expr: P<ast::Expr>) -> ast::Stmt { + ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: expr.span, + node: ast::StmtKind::Semi(expr), + } + } + + fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, + ex: P<ast::Expr>) -> ast::Stmt { + let pat = if mutbl { + let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable); + self.pat_ident_binding_mode(sp, ident, binding_mode) + } else { + self.pat_ident(sp, ident) + }; + let local = P(ast::Local { + pat: pat, + ty: None, + init: Some(ex), + id: ast::DUMMY_NODE_ID, + span: sp, + attrs: ast::ThinVec::new(), + }); + ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: ast::StmtKind::Local(local), + span: sp, + } + } + + fn stmt_let_typed(&self, + sp: Span, + mutbl: bool, + ident: ast::Ident, + typ: P<ast::Ty>, + ex: P<ast::Expr>) + -> ast::Stmt { + let pat = if mutbl { + let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable); + self.pat_ident_binding_mode(sp, ident, binding_mode) + } else { + self.pat_ident(sp, ident) + }; + let local = P(ast::Local { + pat: pat, + ty: Some(typ), + init: Some(ex), + id: ast::DUMMY_NODE_ID, + span: sp, + attrs: ast::ThinVec::new(), + }); + ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: ast::StmtKind::Local(local), + span: sp, + } + } + + // Generate `let _: Type;`, usually used for type assertions. + fn stmt_let_type_only(&self, span: Span, ty: P<ast::Ty>) -> ast::Stmt { + let local = P(ast::Local { + pat: self.pat_wild(span), + ty: Some(ty), + init: None, + id: ast::DUMMY_NODE_ID, + span: span, + attrs: ast::ThinVec::new(), + }); + ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: ast::StmtKind::Local(local), + span: span, + } + } + + fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt { + ast::Stmt { + id: ast::DUMMY_NODE_ID, + node: ast::StmtKind::Item(item), + span: sp, + } + } + + fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> { + self.block(expr.span, vec![ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: expr.span, + node: ast::StmtKind::Expr(expr), + }]) + } + fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block> { + P(ast::Block { + stmts: stmts, + id: ast::DUMMY_NODE_ID, + rules: BlockCheckMode::Default, + span: span, + }) + } + + fn expr(&self, span: Span, node: ast::ExprKind) -> P<ast::Expr> { + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: node, + span: span, + attrs: ast::ThinVec::new(), + }) + } + + fn expr_path(&self, path: ast::Path) -> P<ast::Expr> { + self.expr(path.span, ast::ExprKind::Path(None, path)) + } + + /// Constructs a QPath expression. + fn expr_qpath(&self, span: Span, qself: ast::QSelf, path: ast::Path) -> P<ast::Expr> { + self.expr(span, ast::ExprKind::Path(Some(qself), path)) + } + + fn expr_ident(&self, span: Span, id: ast::Ident) -> P<ast::Expr> { + self.expr_path(self.path_ident(span, id)) + } + fn expr_self(&self, span: Span) -> P<ast::Expr> { + self.expr_ident(span, keywords::SelfValue.ident()) + } + + fn expr_binary(&self, sp: Span, op: ast::BinOpKind, + lhs: P<ast::Expr>, rhs: P<ast::Expr>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs)) + } + + fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> { + self.expr_unary(sp, UnOp::Deref, e) + } + fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P<ast::Expr>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Unary(op, e)) + } + + fn expr_field_access(&self, sp: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> { + let id = Spanned { node: ident, span: sp }; + self.expr(sp, ast::ExprKind::Field(expr, id)) + } + fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, idx: usize) -> P<ast::Expr> { + let id = Spanned { node: idx, span: sp }; + self.expr(sp, ast::ExprKind::TupField(expr, id)) + } + fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::AddrOf(ast::Mutability::Immutable, e)) + } + fn expr_mut_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::AddrOf(ast::Mutability::Mutable, e)) + } + + fn expr_call(&self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>) -> P<ast::Expr> { + self.expr(span, ast::ExprKind::Call(expr, args)) + } + fn expr_call_ident(&self, span: Span, id: ast::Ident, + args: Vec<P<ast::Expr>>) -> P<ast::Expr> { + self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args)) + } + fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident> , + args: Vec<P<ast::Expr>> ) -> P<ast::Expr> { + let pathexpr = self.expr_path(self.path_global(sp, fn_path)); + self.expr_call(sp, pathexpr, args) + } + fn expr_method_call(&self, span: Span, + expr: P<ast::Expr>, + ident: ast::Ident, + mut args: Vec<P<ast::Expr>> ) -> P<ast::Expr> { + let id = Spanned { node: ident, span: span }; + args.insert(0, expr); + self.expr(span, ast::ExprKind::MethodCall(id, Vec::new(), args)) + } + fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr> { + self.expr(b.span, ast::ExprKind::Block(b)) + } + fn field_imm(&self, span: Span, name: Ident, e: P<ast::Expr>) -> ast::Field { + ast::Field { ident: respan(span, name), expr: e, span: span, is_shorthand: false } + } + fn expr_struct(&self, span: Span, path: ast::Path, fields: Vec<ast::Field>) -> P<ast::Expr> { + self.expr(span, ast::ExprKind::Struct(path, fields, None)) + } + fn expr_struct_ident(&self, span: Span, + id: ast::Ident, fields: Vec<ast::Field>) -> P<ast::Expr> { + self.expr_struct(span, self.path_ident(span, id), fields) + } + + fn expr_lit(&self, sp: Span, lit: ast::LitKind) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Lit(P(respan(sp, lit)))) + } + fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> { + self.expr_lit(span, ast::LitKind::Int(i as u64, + ast::LitIntType::Unsigned(ast::UintTy::Us))) + } + fn expr_isize(&self, sp: Span, i: isize) -> P<ast::Expr> { + if i < 0 { + let i = (-i) as u64; + let lit_ty = ast::LitIntType::Signed(ast::IntTy::Is); + let lit = self.expr_lit(sp, ast::LitKind::Int(i, lit_ty)); + self.expr_unary(sp, ast::UnOp::Neg, lit) + } else { + self.expr_lit(sp, ast::LitKind::Int(i as u64, + ast::LitIntType::Signed(ast::IntTy::Is))) + } + } + fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> { + self.expr_lit(sp, ast::LitKind::Int(u as u64, + ast::LitIntType::Unsigned(ast::UintTy::U32))) + } + fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr> { + self.expr_lit(sp, ast::LitKind::Int(u as u64, ast::LitIntType::Unsigned(ast::UintTy::U8))) + } + fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> { + self.expr_lit(sp, ast::LitKind::Bool(value)) + } + + fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Vec(exprs)) + } + fn expr_vec_ng(&self, sp: Span) -> P<ast::Expr> { + self.expr_call_global(sp, self.std_path(&["vec", "Vec", "new"]), + Vec::new()) + } + fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> { + self.expr_addr_of(sp, self.expr_vec(sp, exprs)) + } + fn expr_str(&self, sp: Span, s: Symbol) -> P<ast::Expr> { + self.expr_lit(sp, ast::LitKind::Str(s, ast::StrStyle::Cooked)) + } + + fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Cast(expr, ty)) + } + + + fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { + let some = self.std_path(&["option", "Option", "Some"]); + self.expr_call_global(sp, some, vec![expr]) + } + + fn expr_none(&self, sp: Span) -> P<ast::Expr> { + let none = self.std_path(&["option", "Option", "None"]); + let none = self.path_global(sp, none); + self.expr_path(none) + } + + + fn expr_break(&self, sp: Span) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Break(None, None)) + } + + + fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> { + self.expr(sp, ast::ExprKind::Tup(exprs)) + } + + fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> { + let loc = self.codemap().lookup_char_pos(span.lo); + let expr_file = self.expr_str(span, Symbol::intern(&loc.file.name)); + let expr_line = self.expr_u32(span, loc.line as u32); + let expr_file_line_tuple = self.expr_tuple(span, vec![expr_file, expr_line]); + let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); + self.expr_call_global( + span, + self.std_path(&["rt", "begin_panic"]), + vec![ + self.expr_str(span, msg), + expr_file_line_ptr]) + } + + fn expr_unreachable(&self, span: Span) -> P<ast::Expr> { + self.expr_fail(span, Symbol::intern("internal error: entered unreachable code")) + } + + fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { + let ok = self.std_path(&["result", "Result", "Ok"]); + self.expr_call_global(sp, ok, vec![expr]) + } + + fn expr_err(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { + let err = self.std_path(&["result", "Result", "Err"]); + self.expr_call_global(sp, err, vec![expr]) + } + + fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> { + let ok = self.std_path(&["result", "Result", "Ok"]); + let ok_path = self.path_global(sp, ok); + let err = self.std_path(&["result", "Result", "Err"]); + let err_path = self.path_global(sp, err); + + let binding_variable = self.ident_of("__try_var"); + let binding_pat = self.pat_ident(sp, binding_variable); + let binding_expr = self.expr_ident(sp, binding_variable); + + // Ok(__try_var) pattern + let ok_pat = self.pat_tuple_struct(sp, ok_path, vec![binding_pat.clone()]); + + // Err(__try_var) (pattern and expression resp.) + let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]); + let err_inner_expr = self.expr_call(sp, self.expr_path(err_path), + vec![binding_expr.clone()]); + // return Err(__try_var) + let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr))); + + // Ok(__try_var) => __try_var + let ok_arm = self.arm(sp, vec![ok_pat], binding_expr); + // Err(__try_var) => return Err(__try_var) + let err_arm = self.arm(sp, vec![err_pat], err_expr); + + // match head { Ok() => ..., Err() => ... } + self.expr_match(sp, head, vec![ok_arm, err_arm]) + } + + + fn pat(&self, span: Span, pat: PatKind) -> P<ast::Pat> { + P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: span }) + } + fn pat_wild(&self, span: Span) -> P<ast::Pat> { + self.pat(span, PatKind::Wild) + } + fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat> { + self.pat(span, PatKind::Lit(expr)) + } + fn pat_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Pat> { + let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Immutable); + self.pat_ident_binding_mode(span, ident, binding_mode) + } + + fn pat_ident_binding_mode(&self, + span: Span, + ident: ast::Ident, + bm: ast::BindingMode) -> P<ast::Pat> { + let pat = PatKind::Ident(bm, Spanned{span: span, node: ident}, None); + self.pat(span, pat) + } + fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat> { + self.pat(span, PatKind::Path(None, path)) + } + fn pat_tuple_struct(&self, span: Span, path: ast::Path, + subpats: Vec<P<ast::Pat>>) -> P<ast::Pat> { + self.pat(span, PatKind::TupleStruct(path, subpats, None)) + } + fn pat_struct(&self, span: Span, path: ast::Path, + field_pats: Vec<Spanned<ast::FieldPat>>) -> P<ast::Pat> { + self.pat(span, PatKind::Struct(path, field_pats, false)) + } + fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> { + self.pat(span, PatKind::Tuple(pats, None)) + } + + fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> { + let some = self.std_path(&["option", "Option", "Some"]); + let path = self.path_global(span, some); + self.pat_tuple_struct(span, path, vec![pat]) + } + + fn pat_none(&self, span: Span) -> P<ast::Pat> { + let some = self.std_path(&["option", "Option", "None"]); + let path = self.path_global(span, some); + self.pat_path(span, path) + } + + fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> { + let some = self.std_path(&["result", "Result", "Ok"]); + let path = self.path_global(span, some); + self.pat_tuple_struct(span, path, vec![pat]) + } + + fn pat_err(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> { + let some = self.std_path(&["result", "Result", "Err"]); + let path = self.path_global(span, some); + self.pat_tuple_struct(span, path, vec![pat]) + } + + fn arm(&self, _span: Span, pats: Vec<P<ast::Pat>>, expr: P<ast::Expr>) -> ast::Arm { + ast::Arm { + attrs: vec![], + pats: pats, + guard: None, + body: expr + } + } + + fn arm_unreachable(&self, span: Span) -> ast::Arm { + self.arm(span, vec![self.pat_wild(span)], self.expr_unreachable(span)) + } + + fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> { + self.expr(span, ast::ExprKind::Match(arg, arms)) + } + + fn expr_if(&self, span: Span, cond: P<ast::Expr>, + then: P<ast::Expr>, els: Option<P<ast::Expr>>) -> P<ast::Expr> { + let els = els.map(|x| self.expr_block(self.block_expr(x))); + self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els)) + } + + fn expr_loop(&self, span: Span, block: P<ast::Block>) -> P<ast::Expr> { + self.expr(span, ast::ExprKind::Loop(block, None)) + } + + fn lambda_fn_decl(&self, + span: Span, + fn_decl: P<ast::FnDecl>, + body: P<ast::Expr>, + fn_decl_span: Span) // span of the `|...|` part + -> P<ast::Expr> { + self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref, + fn_decl, + body, + fn_decl_span)) + } + + fn lambda(&self, + span: Span, + ids: Vec<ast::Ident>, + body: P<ast::Expr>) + -> P<ast::Expr> { + let fn_decl = self.fn_decl( + ids.iter().map(|id| self.arg(span, *id, self.ty_infer(span))).collect(), + self.ty_infer(span)); + + // FIXME -- We are using `span` as the span of the `|...|` + // part of the lambda, but it probably (maybe?) corresponds to + // the entire lambda body. Probably we should extend the API + // here, but that's not entirely clear. + self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref, fn_decl, body, span)) + } + + fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr> { + self.lambda(span, Vec::new(), body) + } + + fn lambda1(&self, span: Span, body: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> { + self.lambda(span, vec![ident], body) + } + + fn lambda_stmts(&self, + span: Span, + ids: Vec<ast::Ident>, + stmts: Vec<ast::Stmt>) + -> P<ast::Expr> { + self.lambda(span, ids, self.expr_block(self.block(span, stmts))) + } + fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr> { + self.lambda0(span, self.expr_block(self.block(span, stmts))) + } + fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, + ident: ast::Ident) -> P<ast::Expr> { + self.lambda1(span, self.expr_block(self.block(span, stmts)), ident) + } + + fn arg(&self, span: Span, ident: ast::Ident, ty: P<ast::Ty>) -> ast::Arg { + let arg_pat = self.pat_ident(span, ident); + ast::Arg { + ty: ty, + pat: arg_pat, + id: ast::DUMMY_NODE_ID + } + } + + // FIXME unused self + fn fn_decl(&self, inputs: Vec<ast::Arg>, output: P<ast::Ty>) -> P<ast::FnDecl> { + P(ast::FnDecl { + inputs: inputs, + output: ast::FunctionRetTy::Ty(output), + variadic: false + }) + } + + fn item(&self, span: Span, name: Ident, + attrs: Vec<ast::Attribute>, node: ast::ItemKind) -> P<ast::Item> { + // FIXME: Would be nice if our generated code didn't violate + // Rust coding conventions + P(ast::Item { + ident: name, + attrs: attrs, + id: ast::DUMMY_NODE_ID, + node: node, + vis: ast::Visibility::Inherited, + span: span + }) + } + + fn item_fn_poly(&self, + span: Span, + name: Ident, + inputs: Vec<ast::Arg> , + output: P<ast::Ty>, + generics: Generics, + body: P<ast::Block>) -> P<ast::Item> { + self.item(span, + name, + Vec::new(), + ast::ItemKind::Fn(self.fn_decl(inputs, output), + ast::Unsafety::Normal, + dummy_spanned(ast::Constness::NotConst), + Abi::Rust, + generics, + body)) + } + + fn item_fn(&self, + span: Span, + name: Ident, + inputs: Vec<ast::Arg> , + output: P<ast::Ty>, + body: P<ast::Block> + ) -> P<ast::Item> { + self.item_fn_poly( + span, + name, + inputs, + output, + Generics::default(), + body) + } + + fn variant(&self, span: Span, name: Ident, tys: Vec<P<ast::Ty>> ) -> ast::Variant { + let fields: Vec<_> = tys.into_iter().map(|ty| { + ast::StructField { + span: ty.span, + ty: ty, + ident: None, + vis: ast::Visibility::Inherited, + attrs: Vec::new(), + id: ast::DUMMY_NODE_ID, + } + }).collect(); + + let vdata = if fields.is_empty() { + ast::VariantData::Unit(ast::DUMMY_NODE_ID) + } else { + ast::VariantData::Tuple(fields, ast::DUMMY_NODE_ID) + }; + + respan(span, + ast::Variant_ { + name: name, + attrs: Vec::new(), + data: vdata, + disr_expr: None, + }) + } + + fn item_enum_poly(&self, span: Span, name: Ident, + enum_definition: ast::EnumDef, + generics: Generics) -> P<ast::Item> { + self.item(span, name, Vec::new(), ast::ItemKind::Enum(enum_definition, generics)) + } + + fn item_enum(&self, span: Span, name: Ident, + enum_definition: ast::EnumDef) -> P<ast::Item> { + self.item_enum_poly(span, name, enum_definition, + Generics::default()) + } + + fn item_struct(&self, span: Span, name: Ident, + struct_def: ast::VariantData) -> P<ast::Item> { + self.item_struct_poly( + span, + name, + struct_def, + Generics::default() + ) + } + + fn item_struct_poly(&self, span: Span, name: Ident, + struct_def: ast::VariantData, generics: Generics) -> P<ast::Item> { + self.item(span, name, Vec::new(), ast::ItemKind::Struct(struct_def, generics)) + } + + fn item_mod(&self, span: Span, inner_span: Span, name: Ident, + attrs: Vec<ast::Attribute>, + items: Vec<P<ast::Item>>) -> P<ast::Item> { + self.item( + span, + name, + attrs, + ast::ItemKind::Mod(ast::Mod { + inner: inner_span, + items: items, + }) + ) + } + + fn item_static(&self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + mutbl: ast::Mutability, + expr: P<ast::Expr>) + -> P<ast::Item> { + self.item(span, name, Vec::new(), ast::ItemKind::Static(ty, mutbl, expr)) + } + + fn item_const(&self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + expr: P<ast::Expr>) + -> P<ast::Item> { + self.item(span, name, Vec::new(), ast::ItemKind::Const(ty, expr)) + } + + fn item_ty_poly(&self, span: Span, name: Ident, ty: P<ast::Ty>, + generics: Generics) -> P<ast::Item> { + self.item(span, name, Vec::new(), ast::ItemKind::Ty(ty, generics)) + } + + fn item_ty(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> P<ast::Item> { + self.item_ty_poly(span, name, ty, Generics::default()) + } + + fn attribute(&self, sp: Span, mi: ast::MetaItem) -> ast::Attribute { + attr::mk_spanned_attr_outer(sp, attr::mk_attr_id(), mi) + } + + fn meta_word(&self, sp: Span, w: ast::Name) -> ast::MetaItem { + attr::mk_spanned_word_item(sp, w) + } + + fn meta_list_item_word(&self, sp: Span, w: ast::Name) -> ast::NestedMetaItem { + respan(sp, ast::NestedMetaItemKind::MetaItem(attr::mk_spanned_word_item(sp, w))) + } + + fn meta_list(&self, sp: Span, name: ast::Name, mis: Vec<ast::NestedMetaItem>) + -> ast::MetaItem { + attr::mk_spanned_list_item(sp, name, mis) + } + + fn meta_name_value(&self, sp: Span, name: ast::Name, value: ast::LitKind) + -> ast::MetaItem { + attr::mk_spanned_name_value_item(sp, name, respan(sp, value)) + } + + fn item_use(&self, sp: Span, + vis: ast::Visibility, vp: P<ast::ViewPath>) -> P<ast::Item> { + P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: keywords::Invalid.ident(), + attrs: vec![], + node: ast::ItemKind::Use(vp), + vis: vis, + span: sp + }) + } + + fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item> { + let last = path.segments.last().unwrap().identifier; + self.item_use_simple_(sp, vis, last, path) + } + + fn item_use_simple_(&self, sp: Span, vis: ast::Visibility, + ident: ast::Ident, path: ast::Path) -> P<ast::Item> { + self.item_use(sp, vis, + P(respan(sp, + ast::ViewPathSimple(ident, + path)))) + } + + fn item_use_list(&self, sp: Span, vis: ast::Visibility, + path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item> { + let imports = imports.iter().map(|id| { + let item = ast::PathListItem_ { + name: *id, + rename: None, + id: ast::DUMMY_NODE_ID, + }; + respan(sp, item) + }).collect(); + + self.item_use(sp, vis, + P(respan(sp, + ast::ViewPathList(self.path(sp, path), + imports)))) + } + + fn item_use_glob(&self, sp: Span, + vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item> { + self.item_use(sp, vis, + P(respan(sp, + ast::ViewPathGlob(self.path(sp, path))))) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/decorator.rs b/bash-5.1/vendor/syntex_syntax/src/ext/decorator.rs new file mode 100644 index 0000000..4451b31 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/decorator.rs @@ -0,0 +1,316 @@ +use ast::{self, Name}; +use attr::{self, HasAttrs}; +use fold::*; +use codemap::{ExpnInfo, MacroAttribute, NameAndSpan, respan}; +use ext::base::*; +use ext::build::AstBuilder; +use ptr::P; +use symbol::Symbol; +use util::small_vector::SmallVector; + +pub fn expand_attributes(cx: &mut ExtCtxt, krate: ast::Crate) -> ast::Crate { + MacroExpander { cx: cx }.fold_crate(krate) +} + +struct MacroExpander<'a, 'b: 'a> { + cx: &'a mut ExtCtxt<'b>, +} + +impl<'a, 'b: 'a> Folder for MacroExpander<'a, 'b> { + fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { + let annotatable = Annotatable::Item(item); + expand_annotatable(annotatable, self).into_iter().flat_map(|annotatable| { + match annotatable { + Annotatable::Item(item) => noop_fold_item(item, self), + _ => panic!() + } + }).collect() + } + + fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> { + let annotatable = Annotatable::TraitItem(P(item)); + expand_annotatable(annotatable, self).into_iter().flat_map(|annotatable| { + match annotatable { + Annotatable::TraitItem(item) => noop_fold_trait_item(item.unwrap(), self), + _ => panic!() + } + }).collect() + } + + fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> { + let annotatable = Annotatable::ImplItem(P(item)); + expand_annotatable(annotatable, self).into_iter().flat_map(|annotatable| { + match annotatable { + Annotatable::ImplItem(item) => noop_fold_impl_item(item.unwrap(), self), + _ => panic!() + } + }).collect() + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + noop_fold_mac(mac, self) + } +} + +fn expand_annotatable( + mut item: Annotatable, + fld: &mut MacroExpander, +) -> SmallVector<Annotatable> { + let mut out_items = SmallVector::zero(); + let mut new_attrs = Vec::new(); + + item = expand_1(item, fld, &mut out_items, &mut new_attrs); + + item = item.map_attrs(|_| new_attrs); + out_items.push(item); + + out_items +} + +// Responsible for expanding `cfg_attr` and delegating to expand_2. +// +// The expansion turns this: +// +// #[cfg_attr(COND1, SPEC1)] +// #[cfg_attr(COND2, SPEC2)] +// struct Item { ... } +// +// into this: +// +// #[cfg(COND1)] +// impl Trait for Item { ... } +// #[cfg_attr(COND2, SPEC3)] +// struct Item { ... } +// +// In the example, SPEC1 was handled by expand_2 to create the impl, and the +// handling of SPEC2 resulted in a new attribute SPEC3 which remains +// conditional. +fn expand_1( + mut item: Annotatable, + fld: &mut MacroExpander, + out_items: &mut SmallVector<Annotatable>, + new_attrs: &mut Vec<ast::Attribute>, +) -> Annotatable { + while !item.attrs().is_empty() { + // Pop the first attribute. + let mut attr = None; + item = item.map_attrs(|mut attrs| { + attr = Some(attrs.remove(0)); + attrs + }); + let attr = attr.unwrap(); + + if let ast::MetaItemKind::List(ref vec) = attr.value.node { + // #[cfg_attr(COND, SPEC)] + if attr.value.name == "cfg_attr" && vec.len() == 2 { + if let ast::NestedMetaItemKind::MetaItem(ref spec) = vec[1].node { + // #[cfg(COND)] + let cond = fld.cx.attribute( + attr.span, + fld.cx.meta_list( + attr.value.span, + Symbol::intern("cfg"), + vec[..1].to_vec())); + // #[SPEC] + let spec = fld.cx.attribute( + attr.span, + spec.clone()); + let mut items = SmallVector::zero(); + let mut attrs = Vec::new(); + item = expand_2(item, &spec, fld, &mut items, &mut attrs); + for new_item in items { + let new_item = new_item.map_attrs(|mut attrs| { + attrs.push(cond.clone()); + attrs + }); + out_items.push(new_item); + } + for new_attr in attrs { + let new_spec = respan(attr.span, + ast::NestedMetaItemKind::MetaItem(new_attr.value)); + // #[cfg_attr(COND, NEW_SPEC)] + let new_attr = fld.cx.attribute( + attr.span, + fld.cx.meta_list( + attr.value.span, + attr.value.name.clone(), + vec![vec[0].clone(), new_spec])); + new_attrs.push(new_attr); + } + continue; + } + } + } + item = expand_2(item, &attr, fld, out_items, new_attrs); + } + item +} + +// Responsible for expanding `derive` and delegating to expand_3. +// +// The expansion turns this: +// +// #[derive(Serialize, Clone)] +// #[other_attr] +// struct Item { ... } +// +// into this: +// +// impl Serialize for Item { ... } +// #[derive(Clone)] +// #[other_attr] +// struct Item { ... } +// +// In the example, `derive_Serialize` was handled by expand_3 to create the impl +// but `derive_Clone` and `other_attr` were not handled. Attributes that are not +// handled by expand_3 are preserved. +fn expand_2( + mut item: Annotatable, + attr: &ast::Attribute, + fld: &mut MacroExpander, + out_items: &mut SmallVector<Annotatable>, + new_attrs: &mut Vec<ast::Attribute>, +) -> Annotatable { + let mname = attr.value.name; + let mitem = &attr.value; + if mname == "derive" { + let traits = mitem.meta_item_list().unwrap_or(&[]); + if traits.is_empty() { + fld.cx.span_warn(mitem.span, "empty trait list in `derive`"); + } + let mut not_handled = Vec::new(); + for titem in traits.iter().rev() { + let tname = match titem.node { + ast::NestedMetaItemKind::MetaItem(ref inner) => { + match inner.node { + ast::MetaItemKind::Word => inner.name, + _ => { + fld.cx.span_err(titem.span, "malformed `derive` entry"); + continue; + } + } + } + _ => { + fld.cx.span_err(titem.span, "malformed `derive` entry"); + continue; + } + }; + let tname = Symbol::intern(&format!("derive_{}", tname)); + // #[derive_Trait] + let derive = fld.cx.attribute( + attr.span, + fld.cx.meta_word(titem.span, tname)); + item = match expand_3(item, &derive, fld, out_items, tname) { + Expansion::Handled(item) => item, + Expansion::NotHandled(item) => { + not_handled.push((*titem).clone()); + item + } + }; + } + if !not_handled.is_empty() { + // #[derive(Trait, ...)] + let derive = fld.cx.attribute( + attr.span, + fld.cx.meta_list(mitem.span, mname, not_handled)); + new_attrs.push(derive); + } + item + } else { + match expand_3(item, attr, fld, out_items, mname) { + Expansion::Handled(item) => item, + Expansion::NotHandled(item) => { + new_attrs.push((*attr).clone()); + item + } + } + } +} + +enum Expansion { + Handled(Annotatable), + /// Here is your `Annotatable` back. + NotHandled(Annotatable), +} + +// Responsible for expanding attributes that match a MultiDecorator or +// MultiModifier registered in the syntax_env. Returns the item to continue +// processing. +// +// Syntex supports only a special case of MultiModifier - those that produce +// exactly one output. If a MultiModifier produces zero or more than one output +// this function panics. The problematic case we cannot support is: +// +// #[decorator] // not registered with Syntex +// #[modifier] // registered +// struct A; +fn expand_3( + item: Annotatable, + attr: &ast::Attribute, + fld: &mut MacroExpander, + out_items: &mut SmallVector<Annotatable>, + mname: Name, +) -> Expansion { + let scope = fld.cx.current_expansion.mark; + match fld.cx.resolver.find_extension(scope, mname) { + Some(rc) => match *rc { + MultiDecorator(ref mac) => { + attr::mark_used(&attr); + fld.cx.bt_push(ExpnInfo { + call_site: attr.span, + callee: NameAndSpan { + format: MacroAttribute(mname), + span: Some(attr.span), + // attributes can do whatever they like, for now. + allow_internal_unstable: true, + } + }); + + let mut modified = Vec::new(); + mac.expand(fld.cx, attr.span, &attr.value, &item, + &mut |item| modified.push(item)); + + fld.cx.bt_pop(); + out_items.extend(modified.into_iter() + .flat_map(|ann| expand_annotatable(ann, fld).into_iter())); + Expansion::Handled(item) + } + MultiModifier(ref mac) => { + attr::mark_used(&attr); + fld.cx.bt_push(ExpnInfo { + call_site: attr.span, + callee: NameAndSpan { + format: MacroAttribute(mname), + span: Some(attr.span), + // attributes can do whatever they like, for now. + allow_internal_unstable: true, + } + }); + + let mut modified = mac.expand(fld.cx, + attr.span, + &attr.value, + item); + if modified.len() != 1 { + panic!("syntex limitation: expected 1 output from `#[{}]` but got {}", + mname, modified.len()); + } + let modified = modified.pop().unwrap(); + + fld.cx.bt_pop(); + + let mut expanded = expand_annotatable(modified, fld); + if expanded.is_empty() { + panic!("syntex limitation: output of `#[{}]` must not expand further", + mname); + } + let last = expanded.pop().unwrap(); + + out_items.extend(expanded); + Expansion::Handled(last) + } + _ => Expansion::NotHandled(item), + }, + _ => Expansion::NotHandled(item), + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/env.rs b/bash-5.1/vendor/syntex_syntax/src/ext/env.rs new file mode 100644 index 0000000..dae8d4f --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/env.rs @@ -0,0 +1,99 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/* + * The compiler code necessary to support the env! extension. Eventually this + * should all get sucked into either the compiler syntax extension plugin + * interface. + */ + +use ast; +use ext::base::*; +use ext::base; +use ext::build::AstBuilder; +use symbol::Symbol; +use syntax_pos::Span; +use tokenstream; + +use std::env; + +pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult + 'cx> { + let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") { + None => return DummyResult::expr(sp), + Some(v) => v, + }; + + let e = match env::var(&*var.as_str()) { + Err(..) => { + cx.expr_path(cx.path_all(sp, + true, + cx.std_path(&["option", "Option", "None"]), + Vec::new(), + vec![cx.ty_rptr(sp, + cx.ty_ident(sp, cx.ident_of("str")), + Some(cx.lifetime(sp, + cx.ident_of("'static") + .name)), + ast::Mutability::Immutable)], + Vec::new())) + } + Ok(s) => { + cx.expr_call_global(sp, + cx.std_path(&["option", "Option", "Some"]), + vec![cx.expr_str(sp, Symbol::intern(&s))]) + } + }; + MacEager::expr(e) +} + +pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult + 'cx> { + let mut exprs = match get_exprs_from_tts(cx, sp, tts) { + Some(ref exprs) if exprs.is_empty() => { + cx.span_err(sp, "env! takes 1 or 2 arguments"); + return DummyResult::expr(sp); + } + None => return DummyResult::expr(sp), + Some(exprs) => exprs.into_iter(), + }; + + let var = match expr_to_string(cx, exprs.next().unwrap(), "expected string literal") { + None => return DummyResult::expr(sp), + Some((v, _style)) => v, + }; + let msg = match exprs.next() { + None => Symbol::intern(&format!("environment variable `{}` not defined", var)), + Some(second) => { + match expr_to_string(cx, second, "expected string literal") { + None => return DummyResult::expr(sp), + Some((s, _style)) => s, + } + } + }; + + if let Some(_) = exprs.next() { + cx.span_err(sp, "env! takes 1 or 2 arguments"); + return DummyResult::expr(sp); + } + + let e = match env::var(&*var.as_str()) { + Err(_) => { + cx.span_err(sp, &msg.as_str()); + cx.expr_usize(sp, 0) + } + Ok(s) => cx.expr_str(sp, Symbol::intern(&s)), + }; + MacEager::expr(e) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/expand.rs b/bash-5.1/vendor/syntex_syntax/src/ext/expand.rs new file mode 100644 index 0000000..4043b6d --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/expand.rs @@ -0,0 +1,1008 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast::{Block, Ident, Mac_, PatKind}; +use ast::{Name, MacStmtStyle, StmtKind, ItemKind}; +use ast; +use ext::hygiene::Mark; +use ext::placeholders::{placeholder, PlaceholderExpander}; +use attr::{self, HasAttrs}; +use codemap::{ExpnInfo, NameAndSpan, MacroBang, MacroAttribute}; +use syntax_pos::{self, Span, ExpnId}; +use config::{is_test_or_bench, StripUnconfigured}; +use ext::base::*; +use ext::decorator::expand_attributes; +use feature_gate::{self, Features}; +use fold; +use fold::*; +use parse::{ParseSess, DirectoryOwnership, PResult, lexer}; +use parse::parser::Parser; +use parse::token; +use print::pprust; +use ptr::P; +use std_inject; +use symbol::keywords; +use tokenstream::{TokenTree, TokenStream}; +use util::small_vector::SmallVector; +use visit::Visitor; + +use std::mem; +use std::path::PathBuf; +use std::rc::Rc; + +macro_rules! expansions { + ($($kind:ident: $ty:ty [$($vec:ident, $ty_elt:ty)*], $kind_name:expr, .$make:ident, + $(.$fold:ident)* $(lift .$fold_elt:ident)*, + $(.$visit:ident)* $(lift .$visit_elt:ident)*;)*) => { + #[derive(Copy, Clone, PartialEq, Eq)] + pub enum ExpansionKind { OptExpr, $( $kind, )* } + pub enum Expansion { OptExpr(Option<P<ast::Expr>>), $( $kind($ty), )* } + + impl ExpansionKind { + pub fn name(self) -> &'static str { + match self { + ExpansionKind::OptExpr => "expression", + $( ExpansionKind::$kind => $kind_name, )* + } + } + + fn make_from<'a>(self, result: Box<MacResult + 'a>) -> Option<Expansion> { + match self { + ExpansionKind::OptExpr => result.make_expr().map(Some).map(Expansion::OptExpr), + $( ExpansionKind::$kind => result.$make().map(Expansion::$kind), )* + } + } + } + + impl Expansion { + pub fn make_opt_expr(self) -> Option<P<ast::Expr>> { + match self { + Expansion::OptExpr(expr) => expr, + _ => panic!("Expansion::make_* called on the wrong kind of expansion"), + } + } + $( pub fn $make(self) -> $ty { + match self { + Expansion::$kind(ast) => ast, + _ => panic!("Expansion::make_* called on the wrong kind of expansion"), + } + } )* + + pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self { + use self::Expansion::*; + match self { + OptExpr(expr) => OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))), + $($( $kind(ast) => $kind(folder.$fold(ast)), )*)* + $($( $kind(ast) => { + $kind(ast.into_iter().flat_map(|ast| folder.$fold_elt(ast)).collect()) + }, )*)* + } + } + + pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { + match *self { + Expansion::OptExpr(Some(ref expr)) => visitor.visit_expr(expr), + Expansion::OptExpr(None) => {} + $($( Expansion::$kind(ref ast) => visitor.$visit(ast), )*)* + $($( Expansion::$kind(ref ast) => for ast in &ast[..] { + visitor.$visit_elt(ast); + }, )*)* + } + } + } + + impl<'a, 'b> Folder for MacroExpander<'a, 'b> { + fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> { + self.expand(Expansion::OptExpr(Some(expr))).make_opt_expr() + } + $($(fn $fold(&mut self, node: $ty) -> $ty { + self.expand(Expansion::$kind(node)).$make() + })*)* + $($(fn $fold_elt(&mut self, node: $ty_elt) -> $ty { + self.expand(Expansion::$kind(SmallVector::one(node))).$make() + })*)* + } + + impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> { + $(fn $make(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>) -> Option<$ty> { + Some(self.make(ExpansionKind::$kind).$make()) + })* + } + } +} + +expansions! { + Expr: P<ast::Expr> [], "expression", .make_expr, .fold_expr, .visit_expr; + Pat: P<ast::Pat> [], "pattern", .make_pat, .fold_pat, .visit_pat; + Ty: P<ast::Ty> [], "type", .make_ty, .fold_ty, .visit_ty; + Stmts: SmallVector<ast::Stmt> [SmallVector, ast::Stmt], + "statement", .make_stmts, lift .fold_stmt, lift .visit_stmt; + Items: SmallVector<P<ast::Item>> [SmallVector, P<ast::Item>], + "item", .make_items, lift .fold_item, lift .visit_item; + TraitItems: SmallVector<ast::TraitItem> [SmallVector, ast::TraitItem], + "trait item", .make_trait_items, lift .fold_trait_item, lift .visit_trait_item; + ImplItems: SmallVector<ast::ImplItem> [SmallVector, ast::ImplItem], + "impl item", .make_impl_items, lift .fold_impl_item, lift .visit_impl_item; +} + +impl ExpansionKind { + fn dummy(self, span: Span) -> Expansion { + self.make_from(DummyResult::any(span)).unwrap() + } + + fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I) -> Expansion { + let items = items.into_iter(); + match self { + ExpansionKind::Items => + Expansion::Items(items.map(Annotatable::expect_item).collect()), + ExpansionKind::ImplItems => + Expansion::ImplItems(items.map(Annotatable::expect_impl_item).collect()), + ExpansionKind::TraitItems => + Expansion::TraitItems(items.map(Annotatable::expect_trait_item).collect()), + _ => unreachable!(), + } + } +} + +pub struct Invocation { + pub kind: InvocationKind, + expansion_kind: ExpansionKind, + expansion_data: ExpansionData, +} + +pub enum InvocationKind { + Bang { + mac: ast::Mac, + ident: Option<Ident>, + span: Span, + }, + Attr { + attr: ast::Attribute, + item: Annotatable, + }, +} + +impl Invocation { + fn span(&self) -> Span { + match self.kind { + InvocationKind::Bang { span, .. } => span, + InvocationKind::Attr { ref attr, .. } => attr.span, + } + } +} + +pub struct MacroExpander<'a, 'b:'a> { + pub cx: &'a mut ExtCtxt<'b>, + monotonic: bool, // c.f. `cx.monotonic_expander()` +} + +impl<'a, 'b> MacroExpander<'a, 'b> { + pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { + MacroExpander { cx: cx, monotonic: monotonic } + } + + pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate { + self.cx.crate_root = std_inject::injected_crate_name(&krate); + let mut module = ModuleData { + mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)], + directory: PathBuf::from(self.cx.codemap().span_to_filename(krate.span)), + }; + module.directory.pop(); + self.cx.current_expansion.module = Rc::new(module); + + // FIXME(syntex): Expand attributes + let mut krate = expand_attributes(self.cx, krate); + + let krate_item = Expansion::Items(SmallVector::one(P(ast::Item { + attrs: krate.attrs, + span: krate.span, + node: ast::ItemKind::Mod(krate.module), + ident: keywords::Invalid.ident(), + id: ast::DUMMY_NODE_ID, + vis: ast::Visibility::Public, + }))); + + match self.expand(krate_item).make_items().pop().unwrap().unwrap() { + ast::Item { attrs, node: ast::ItemKind::Mod(module), .. } => { + krate.attrs = attrs; + krate.module = module; + }, + _ => unreachable!(), + }; + + krate + } + + // Fully expand all the invocations in `expansion`. + fn expand(&mut self, expansion: Expansion) -> Expansion { + let orig_expansion_data = self.cx.current_expansion.clone(); + self.cx.current_expansion.depth = 0; + + let (expansion, mut invocations) = self.collect_invocations(expansion); + self.resolve_imports(); + invocations.reverse(); + + let mut expansions = Vec::new(); + let mut undetermined_invocations = Vec::new(); + let (mut progress, mut force) = (false, !self.monotonic); + loop { + let invoc = if let Some(invoc) = invocations.pop() { + invoc + } else { + self.resolve_imports(); + if undetermined_invocations.is_empty() { break } + invocations = mem::replace(&mut undetermined_invocations, Vec::new()); + force = !mem::replace(&mut progress, false); + continue + }; + + let scope = + if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark }; + let resolution = match invoc.kind { + InvocationKind::Bang { ref mac, .. } => { + self.cx.resolver.resolve_macro(scope, &mac.node.path, force) + } + InvocationKind::Attr { ref attr, .. } => { + let ident = Ident::with_empty_ctxt(attr.name()); + let path = ast::Path::from_ident(attr.span, ident); + self.cx.resolver.resolve_macro(scope, &path, force) + } + }; + let ext = match resolution { + Ok(ext) => Some(ext), + Err(Determinacy::Determined) => None, + Err(Determinacy::Undetermined) => { + undetermined_invocations.push(invoc); + continue + } + }; + + progress = true; + let ExpansionData { depth, mark, .. } = invoc.expansion_data; + self.cx.current_expansion = invoc.expansion_data.clone(); + + self.cx.current_expansion.mark = scope; + let expansion = match ext { + Some(ext) => self.expand_invoc(invoc, ext), + None => invoc.expansion_kind.dummy(invoc.span()), + }; + + let (expansion, new_invocations) = self.collect_invocations(expansion); + + if expansions.len() < depth { + expansions.push(Vec::new()); + } + expansions[depth - 1].push((mark, expansion)); + if !self.cx.ecfg.single_step { + invocations.extend(new_invocations.into_iter().rev()); + } + } + + self.cx.current_expansion = orig_expansion_data; + + let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic); + while let Some(expansions) = expansions.pop() { + for (mark, expansion) in expansions.into_iter().rev() { + placeholder_expander.add(mark.as_placeholder_id(), expansion); + } + } + + expansion.fold_with(&mut placeholder_expander) + } + + fn resolve_imports(&mut self) { + if self.monotonic { + let err_count = self.cx.parse_sess.span_diagnostic.err_count(); + self.cx.resolver.resolve_imports(); + self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count; + } + } + + fn collect_invocations(&mut self, expansion: Expansion) -> (Expansion, Vec<Invocation>) { + let result = { + let mut collector = InvocationCollector { + cfg: StripUnconfigured { + should_test: self.cx.ecfg.should_test, + sess: self.cx.parse_sess, + features: self.cx.ecfg.features, + }, + cx: self.cx, + invocations: Vec::new(), + monotonic: self.monotonic, + }; + (expansion.fold_with(&mut collector), collector.invocations) + }; + + if self.monotonic { + let err_count = self.cx.parse_sess.span_diagnostic.err_count(); + let mark = self.cx.current_expansion.mark; + self.cx.resolver.visit_expansion(mark, &result.0); + self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count; + } + + result + } + + fn expand_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion { + match invoc.kind { + InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext), + InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext), + } + } + + fn expand_attr_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion { + let Invocation { expansion_kind: kind, .. } = invoc; + let (attr, item) = match invoc.kind { + InvocationKind::Attr { attr, item } => (attr, item), + _ => unreachable!(), + }; + + attr::mark_used(&attr); + let name = attr.name(); + self.cx.bt_push(ExpnInfo { + call_site: attr.span, + callee: NameAndSpan { + format: MacroAttribute(name), + span: Some(attr.span), + allow_internal_unstable: false, + } + }); + + match *ext { + MultiModifier(ref mac) => { + let items = mac.expand(self.cx, attr.span, &attr.value, item); + kind.expect_from_annotatables(items) + } + MultiDecorator(ref mac) => { + let mut items = Vec::new(); + mac.expand(self.cx, attr.span, &attr.value, &item, + &mut |item| items.push(item)); + items.push(item); + kind.expect_from_annotatables(items) + } + SyntaxExtension::AttrProcMacro(ref mac) => { + let attr_toks = TokenStream::from_tts(tts_for_attr(&attr, &self.cx.parse_sess)); + let item_toks = TokenStream::from_tts(tts_for_item(&item, &self.cx.parse_sess)); + + let tok_result = mac.expand(self.cx, attr.span, attr_toks, item_toks); + self.parse_expansion(tok_result, kind, name, attr.span) + } + SyntaxExtension::CustomDerive(_) => { + self.cx.span_err(attr.span, &format!("`{}` is a derive mode", name)); + kind.dummy(attr.span) + } + _ => { + let msg = &format!("macro `{}` may not be used in attributes", name); + self.cx.span_err(attr.span, &msg); + kind.dummy(attr.span) + } + } + } + + /// Expand a macro invocation. Returns the result of expansion. + fn expand_bang_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion { + let (mark, kind) = (invoc.expansion_data.mark, invoc.expansion_kind); + let (mac, ident, span) = match invoc.kind { + InvocationKind::Bang { mac, ident, span } => (mac, ident, span), + _ => unreachable!(), + }; + let Mac_ { path, tts, .. } = mac.node; + + let extname = path.segments.last().unwrap().identifier.name; + let ident = ident.unwrap_or(keywords::Invalid.ident()); + let marked_tts = mark_tts(&tts, mark); + let opt_expanded = match *ext { + NormalTT(ref expandfun, exp_span, allow_internal_unstable) => { + if ident.name != keywords::Invalid.name() { + let msg = + format!("macro {}! expects no ident argument, given '{}'", extname, ident); + self.cx.span_err(path.span, &msg); + return kind.dummy(span); + } + + self.cx.bt_push(ExpnInfo { + call_site: span, + callee: NameAndSpan { + format: MacroBang(extname), + span: exp_span, + allow_internal_unstable: allow_internal_unstable, + }, + }); + + kind.make_from(expandfun.expand(self.cx, span, &marked_tts)) + } + + IdentTT(ref expander, tt_span, allow_internal_unstable) => { + if ident.name == keywords::Invalid.name() { + self.cx.span_err(path.span, + &format!("macro {}! expects an ident argument", extname)); + return kind.dummy(span); + }; + + self.cx.bt_push(ExpnInfo { + call_site: span, + callee: NameAndSpan { + format: MacroBang(extname), + span: tt_span, + allow_internal_unstable: allow_internal_unstable, + } + }); + + kind.make_from(expander.expand(self.cx, span, ident, marked_tts)) + } + + MultiDecorator(..) | MultiModifier(..) | SyntaxExtension::AttrProcMacro(..) => { + self.cx.span_err(path.span, + &format!("`{}` can only be used in attributes", extname)); + return kind.dummy(span); + } + + SyntaxExtension::CustomDerive(..) => { + self.cx.span_err(path.span, &format!("`{}` is a derive mode", extname)); + return kind.dummy(span); + } + + SyntaxExtension::ProcMacro(ref expandfun) => { + if ident.name != keywords::Invalid.name() { + let msg = + format!("macro {}! expects no ident argument, given '{}'", extname, ident); + self.cx.span_err(path.span, &msg); + return kind.dummy(span); + } + + self.cx.bt_push(ExpnInfo { + call_site: span, + callee: NameAndSpan { + format: MacroBang(extname), + // FIXME procedural macros do not have proper span info + // yet, when they do, we should use it here. + span: None, + // FIXME probably want to follow macro_rules macros here. + allow_internal_unstable: false, + }, + }); + + let toks = TokenStream::from_tts(marked_tts); + let tok_result = expandfun.expand(self.cx, span, toks); + Some(self.parse_expansion(tok_result, kind, extname, span)) + } + }; + + let expanded = if let Some(expanded) = opt_expanded { + expanded + } else { + let msg = format!("non-{kind} macro in {kind} position: {name}", + name = path.segments[0].identifier.name, kind = kind.name()); + self.cx.span_err(path.span, &msg); + return kind.dummy(span); + }; + + expanded.fold_with(&mut Marker { + mark: mark, + expn_id: Some(self.cx.backtrace()), + }) + } + + fn parse_expansion(&mut self, toks: TokenStream, kind: ExpansionKind, name: Name, span: Span) + -> Expansion { + let mut parser = self.cx.new_parser_from_tts(&toks.to_tts()); + let expansion = match parser.parse_expansion(kind, false) { + Ok(expansion) => expansion, + Err(mut err) => { + err.emit(); + return kind.dummy(span); + } + }; + parser.ensure_complete_parse(name, kind.name(), span); + // FIXME better span info + expansion.fold_with(&mut ChangeSpan { span: span }) + } +} + +impl<'a> Parser<'a> { + pub fn parse_expansion(&mut self, kind: ExpansionKind, macro_legacy_warnings: bool) + -> PResult<'a, Expansion> { + Ok(match kind { + ExpansionKind::Items => { + let mut items = SmallVector::new(); + while let Some(item) = try!(self.parse_item()) { + items.push(item); + } + Expansion::Items(items) + } + ExpansionKind::TraitItems => { + let mut items = SmallVector::new(); + while self.token != token::Eof { + items.push(try!(self.parse_trait_item())); + } + Expansion::TraitItems(items) + } + ExpansionKind::ImplItems => { + let mut items = SmallVector::new(); + while self.token != token::Eof { + items.push(try!(self.parse_impl_item())); + } + Expansion::ImplItems(items) + } + ExpansionKind::Stmts => { + let mut stmts = SmallVector::new(); + while self.token != token::Eof && + // won't make progress on a `}` + self.token != token::CloseDelim(token::Brace) { + if let Some(stmt) = try!(self.parse_full_stmt(macro_legacy_warnings)) { + stmts.push(stmt); + } + } + Expansion::Stmts(stmts) + } + ExpansionKind::Expr => Expansion::Expr(try!(self.parse_expr())), + ExpansionKind::OptExpr => Expansion::OptExpr(Some(try!(self.parse_expr()))), + ExpansionKind::Ty => Expansion::Ty(try!(self.parse_ty())), + ExpansionKind::Pat => Expansion::Pat(try!(self.parse_pat())), + }) + } + + pub fn ensure_complete_parse(&mut self, macro_name: ast::Name, kind_name: &str, span: Span) { + if self.token != token::Eof { + let msg = format!("macro expansion ignores token `{}` and any following", + self.this_token_to_string()); + let mut err = self.diagnostic().struct_span_err(self.span, &msg); + let msg = format!("caused by the macro expansion here; the usage \ + of `{}!` is likely invalid in {} context", + macro_name, kind_name); + err.span_note(span, &msg).emit(); + } + } +} + +struct InvocationCollector<'a, 'b: 'a> { + cx: &'a mut ExtCtxt<'b>, + cfg: StripUnconfigured<'a>, + invocations: Vec<Invocation>, + monotonic: bool, +} + +macro_rules! fully_configure { + ($this:ident, $node:ident, $noop_fold:ident) => { + match $noop_fold($node, &mut $this.cfg).pop() { + Some(node) => node, + None => return SmallVector::new(), + } + } +} + +impl<'a, 'b> InvocationCollector<'a, 'b> { + fn collect(&mut self, expansion_kind: ExpansionKind, kind: InvocationKind) -> Expansion { + let mark = Mark::fresh(); + self.invocations.push(Invocation { + kind: kind, + expansion_kind: expansion_kind, + expansion_data: ExpansionData { + mark: mark, + depth: self.cx.current_expansion.depth + 1, + ..self.cx.current_expansion.clone() + }, + }); + placeholder(expansion_kind, mark.as_placeholder_id()) + } + + fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: ExpansionKind) -> Expansion { + self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span }) + } + + fn collect_attr(&mut self, attr: ast::Attribute, item: Annotatable, kind: ExpansionKind) + -> Expansion { + self.collect(kind, InvocationKind::Attr { attr: attr, item: item }) + } + + // If `item` is an attr invocation, remove and return the macro attribute. + fn classify_item<T: HasAttrs>(&mut self, mut item: T) -> (T, Option<ast::Attribute>) { + let mut attr = None; + item = item.map_attrs(|mut attrs| { + attr = self.cx.resolver.find_attr_invoc(&mut attrs); + attrs + }); + (item, attr) + } + + fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> { + self.cfg.configure(node) + } + + // Detect use of feature-gated or invalid attributes on macro invocations + // since they will not be detected after macro expansion. + fn check_attributes(&mut self, attrs: &[ast::Attribute]) { + let codemap = &self.cx.parse_sess.codemap(); + let features = self.cx.ecfg.features.unwrap(); + for attr in attrs.iter() { + feature_gate::check_attribute(&attr, &self.cx.parse_sess, codemap, features); + } + } +} + +// These are pretty nasty. Ideally, we would keep the tokens around, linked from +// the AST. However, we don't so we need to create new ones. Since the item might +// have come from a macro expansion (possibly only in part), we can't use the +// existing codemap. +// +// Therefore, we must use the pretty printer (yuck) to turn the AST node into a +// string, which we then re-tokenise (double yuck), but first we have to patch +// the pretty-printed string on to the end of the existing codemap (infinity-yuck). +fn tts_for_item(item: &Annotatable, parse_sess: &ParseSess) -> Vec<TokenTree> { + let text = match *item { + Annotatable::Item(ref i) => pprust::item_to_string(i), + Annotatable::TraitItem(ref ti) => pprust::trait_item_to_string(ti), + Annotatable::ImplItem(ref ii) => pprust::impl_item_to_string(ii), + }; + string_to_tts(text, parse_sess) +} + +fn tts_for_attr(attr: &ast::Attribute, parse_sess: &ParseSess) -> Vec<TokenTree> { + string_to_tts(pprust::attr_to_string(attr), parse_sess) +} + +fn string_to_tts(text: String, parse_sess: &ParseSess) -> Vec<TokenTree> { + let filemap = parse_sess.codemap() + .new_filemap(String::from("<macro expansion>"), None, text); + + let lexer = lexer::StringReader::new(&parse_sess.span_diagnostic, filemap); + let mut parser = Parser::new(parse_sess, Box::new(lexer), None, false); + panictry!(parser.parse_all_token_trees()) +} + +impl<'a, 'b> Folder for InvocationCollector<'a, 'b> { + fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { + let mut expr = self.cfg.configure_expr(expr).unwrap(); + expr.node = self.cfg.configure_expr_kind(expr.node); + + if let ast::ExprKind::Mac(mac) = expr.node { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + return P(ast::Expr { node: ast::ExprKind::Mac(mac), .. expr }); + } + + self.check_attributes(&expr.attrs); + self.collect_bang(mac, expr.span, ExpansionKind::Expr).make_expr() + } else { + P(noop_fold_expr(expr, self)) + } + } + + fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> { + let mut expr = configure!(self, expr).unwrap(); + expr.node = self.cfg.configure_expr_kind(expr.node); + + if let ast::ExprKind::Mac(mac) = expr.node { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + return Some(P(ast::Expr { node: ast::ExprKind::Mac(mac), .. expr })); + } + + self.check_attributes(&expr.attrs); + self.collect_bang(mac, expr.span, ExpansionKind::OptExpr).make_opt_expr() + } else { + Some(P(noop_fold_expr(expr, self))) + } + } + + fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> { + match pat.node { + PatKind::Mac(_) => {} + _ => return noop_fold_pat(pat, self), + } + + pat.and_then(|pat| match pat.node { + PatKind::Mac(mac) => { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + return P(ast::Pat { node: PatKind::Mac(mac), .. pat }); + } + + self.collect_bang(mac, pat.span, ExpansionKind::Pat).make_pat() + } + _ => unreachable!(), + }) + } + + fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> { + let stmt = match self.cfg.configure_stmt(stmt) { + Some(stmt) => stmt, + None => return SmallVector::new(), + }; + + let (mac, style, attrs) = if let StmtKind::Mac(mac) = stmt.node { + // FIXME(syntex): ignore unknown macros. + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.0.node.path, false).is_err() { + let stmt = ast::Stmt { node: StmtKind::Mac(mac), .. stmt }; + return SmallVector::one(stmt); + } + + mac.unwrap() + } else { + // The placeholder expander gives ids to statements, so we avoid folding the id here. + let ast::Stmt { id, node, span } = stmt; + return noop_fold_stmt_kind(node, self).into_iter().map(|node| { + ast::Stmt { id: id, node: node, span: span } + }).collect() + }; + + self.check_attributes(&attrs); + let mut placeholder = self.collect_bang(mac, stmt.span, ExpansionKind::Stmts).make_stmts(); + + // If this is a macro invocation with a semicolon, then apply that + // semicolon to the final statement produced by expansion. + if style == MacStmtStyle::Semicolon { + if let Some(stmt) = placeholder.pop() { + placeholder.push(stmt.add_trailing_semicolon()); + } + } + + placeholder + } + + fn fold_block(&mut self, block: P<Block>) -> P<Block> { + let old_directory_ownership = self.cx.current_expansion.directory_ownership; + self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock; + let result = noop_fold_block(block, self); + self.cx.current_expansion.directory_ownership = old_directory_ownership; + result + } + + fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { + let item = configure!(self, item); + + let (mut item, attr) = self.classify_item(item); + if let Some(attr) = attr { + let item = Annotatable::Item(fully_configure!(self, item, noop_fold_item)); + return self.collect_attr(attr, item, ExpansionKind::Items).make_items(); + } + + match item.node { + ast::ItemKind::Mac(..) => { + self.check_attributes(&item.attrs); + let is_macro_def = if let ItemKind::Mac(ref mac) = item.node { + mac.node.path.segments[0].identifier.name == "macro_rules" + } else { + unreachable!() + }; + + item.and_then(|mut item| match item.node { + ItemKind::Mac(_) if is_macro_def => { + item.id = Mark::fresh().as_placeholder_id(); + SmallVector::one(P(item)) + } + ItemKind::Mac(mac) => { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + let item = ast::Item { node: ItemKind::Mac(mac), .. item }; + return SmallVector::one(P(item)); + } + + self.collect(ExpansionKind::Items, InvocationKind::Bang { + mac: mac, + ident: Some(item.ident), + span: item.span, + }).make_items() + } + _ => unreachable!(), + }) + } + ast::ItemKind::Mod(ast::Mod { inner, .. }) => { + if item.ident == keywords::Invalid.ident() { + return noop_fold_item(item, self); + } + + let orig_directory_ownership = self.cx.current_expansion.directory_ownership; + let mut module = (*self.cx.current_expansion.module).clone(); + module.mod_path.push(item.ident); + + // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`). + // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`). + // Thus, if `inner` is the dummy span, we know the module is inline. + let inline_module = item.span.contains(inner) || inner == syntax_pos::DUMMY_SP; + + if inline_module { + if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") { + self.cx.current_expansion.directory_ownership = DirectoryOwnership::Owned; + module.directory.push(&*path.as_str()); + } else { + module.directory.push(&*item.ident.name.as_str()); + } + } else { + let mut path = + PathBuf::from(self.cx.parse_sess.codemap().span_to_filename(inner)); + let directory_ownership = match path.file_name().unwrap().to_str() { + Some("mod.rs") => DirectoryOwnership::Owned, + _ => DirectoryOwnership::UnownedViaMod(false), + }; + path.pop(); + module.directory = path; + self.cx.current_expansion.directory_ownership = directory_ownership; + } + + let orig_module = + mem::replace(&mut self.cx.current_expansion.module, Rc::new(module)); + let result = noop_fold_item(item, self); + self.cx.current_expansion.module = orig_module; + self.cx.current_expansion.directory_ownership = orig_directory_ownership; + return result; + } + // Ensure that test functions are accessible from the test harness. + ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => { + if item.attrs.iter().any(|attr| is_test_or_bench(attr)) { + item = item.map(|mut item| { item.vis = ast::Visibility::Public; item }); + } + noop_fold_item(item, self) + } + _ => noop_fold_item(item, self), + } + } + + fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> { + let item = configure!(self, item); + + let (item, attr) = self.classify_item(item); + if let Some(attr) = attr { + let item = + Annotatable::TraitItem(P(fully_configure!(self, item, noop_fold_trait_item))); + return self.collect_attr(attr, item, ExpansionKind::TraitItems).make_trait_items() + } + + match item.node { + ast::TraitItemKind::Macro(mac) => { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + let item = ast::TraitItem { node: ast::TraitItemKind::Macro(mac), .. item }; + return SmallVector::one(item); + } + + let ast::TraitItem { attrs, span, .. } = item; + self.check_attributes(&attrs); + self.collect_bang(mac, span, ExpansionKind::TraitItems).make_trait_items() + } + _ => fold::noop_fold_trait_item(item, self), + } + } + + fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> { + let item = configure!(self, item); + + let (item, attr) = self.classify_item(item); + if let Some(attr) = attr { + let item = Annotatable::ImplItem(P(fully_configure!(self, item, noop_fold_impl_item))); + return self.collect_attr(attr, item, ExpansionKind::ImplItems).make_impl_items(); + } + + match item.node { + ast::ImplItemKind::Macro(mac) => { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + let item = ast::ImplItem { node: ast::ImplItemKind::Macro(mac), .. item }; + return SmallVector::one(item); + } + + let ast::ImplItem { attrs, span, .. } = item; + self.check_attributes(&attrs); + self.collect_bang(mac, span, ExpansionKind::ImplItems).make_impl_items() + } + _ => fold::noop_fold_impl_item(item, self), + } + } + + fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> { + let ty = match ty.node { + ast::TyKind::Mac(_) => ty.unwrap(), + _ => return fold::noop_fold_ty(ty, self), + }; + + match ty.node { + ast::TyKind::Mac(mac) => { + // FIXME(syntex): ignore unknown macros + if self.cx.resolver.resolve_macro(self.cx.current_expansion.mark, &mac.node.path, false).is_err() { + return P(ast::Ty { node: ast::TyKind::Mac(mac), .. ty }); + } + + self.collect_bang(mac, ty.span, ExpansionKind::Ty).make_ty() + } + _ => unreachable!(), + } + } + + fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { + noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self) + } + + fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind { + noop_fold_item_kind(self.cfg.configure_item_kind(item), self) + } + + fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId { + if self.monotonic { + assert_eq!(id, ast::DUMMY_NODE_ID); + self.cx.resolver.next_node_id() + } else { + id + } + } +} + +pub struct ExpansionConfig<'feat> { + pub crate_name: String, + pub features: Option<&'feat Features>, + pub recursion_limit: usize, + pub trace_mac: bool, + pub should_test: bool, // If false, strip `#[test]` nodes + pub single_step: bool, + pub keep_macs: bool, +} + +macro_rules! feature_tests { + ($( fn $getter:ident = $field:ident, )*) => { + $( + pub fn $getter(&self) -> bool { + match self.features { + Some(&Features { $field: true, .. }) => true, + _ => false, + } + } + )* + } +} + +impl<'feat> ExpansionConfig<'feat> { + pub fn default(crate_name: String) -> ExpansionConfig<'static> { + ExpansionConfig { + crate_name: crate_name, + features: None, + recursion_limit: 64, + trace_mac: false, + should_test: false, + single_step: false, + keep_macs: false, + } + } + + feature_tests! { + fn enable_quotes = quote, + fn enable_asm = asm, + fn enable_log_syntax = log_syntax, + fn enable_concat_idents = concat_idents, + fn enable_trace_macros = trace_macros, + fn enable_allow_internal_unstable = allow_internal_unstable, + fn enable_custom_derive = custom_derive, + fn enable_pushpop_unsafe = pushpop_unsafe, + } +} + +// A Marker adds the given mark to the syntax context and +// sets spans' `expn_id` to the given expn_id (unless it is `None`). +struct Marker { mark: Mark, expn_id: Option<ExpnId> } + +impl Folder for Marker { + fn fold_ident(&mut self, mut ident: Ident) -> Ident { + ident.ctxt = ident.ctxt.apply_mark(self.mark); + ident + } + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + noop_fold_mac(mac, self) + } + + fn new_span(&mut self, mut span: Span) -> Span { + if let Some(expn_id) = self.expn_id { + span.expn_id = expn_id; + } + span + } +} + +// apply a given mark to the given token trees. Used prior to expansion of a macro. +pub fn mark_tts(tts: &[TokenTree], m: Mark) -> Vec<TokenTree> { + noop_fold_tts(tts, &mut Marker{mark:m, expn_id: None}) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/hygiene.rs b/bash-5.1/vendor/syntex_syntax/src/ext/hygiene.rs new file mode 100644 index 0000000..468479e --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/hygiene.rs @@ -0,0 +1,134 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Machinery for hygienic macros, inspired by the MTWT[1] paper. +//! +//! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. +//! 2012. *Macros that work together: Compile-time bindings, partial expansion, +//! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216. +//! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093 + +use ast::NodeId; +use std::cell::RefCell; +use std::collections::HashMap; +use std::fmt; + +/// A SyntaxContext represents a chain of macro expansions (represented by marks). +#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Default)] +pub struct SyntaxContext(pub u32); + +#[derive(Copy, Clone)] +pub struct SyntaxContextData { + pub outer_mark: Mark, + pub prev_ctxt: SyntaxContext, +} + +/// A mark is a unique id associated with a macro expansion. +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)] +pub struct Mark(u32); + +impl Mark { + pub fn fresh() -> Self { + HygieneData::with(|data| { + let next_mark = Mark(data.next_mark.0 + 1); + ::std::mem::replace(&mut data.next_mark, next_mark) + }) + } + + /// The mark of the theoretical expansion that generates freshly parsed, unexpanded AST. + pub fn root() -> Self { + Mark(0) + } + + pub fn from_placeholder_id(id: NodeId) -> Self { + Mark(id.as_u32()) + } + + pub fn as_placeholder_id(self) -> NodeId { + NodeId::from_u32(self.0) + } + + pub fn as_u32(self) -> u32 { + self.0 + } +} + +struct HygieneData { + syntax_contexts: Vec<SyntaxContextData>, + markings: HashMap<(SyntaxContext, Mark), SyntaxContext>, + next_mark: Mark, +} + +impl HygieneData { + fn new() -> Self { + HygieneData { + syntax_contexts: vec![SyntaxContextData { + outer_mark: Mark::root(), + prev_ctxt: SyntaxContext::empty(), + }], + markings: HashMap::new(), + next_mark: Mark(1), + } + } + + fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T { + thread_local! { + static HYGIENE_DATA: RefCell<HygieneData> = RefCell::new(HygieneData::new()) + } + HYGIENE_DATA.with(|data| f(&mut *data.borrow_mut())) + } +} + +pub fn reset_hygiene_data() { + HygieneData::with(|data| *data = HygieneData::new()) +} + +impl SyntaxContext { + pub fn empty() -> Self { + SyntaxContext(0) + } + + pub fn data(self) -> SyntaxContextData { + HygieneData::with(|data| data.syntax_contexts[self.0 as usize]) + } + + /// Extend a syntax context with a given mark + pub fn apply_mark(self, mark: Mark) -> SyntaxContext { + // Applying the same mark twice is a no-op + let ctxt_data = self.data(); + if mark == ctxt_data.outer_mark { + return ctxt_data.prev_ctxt; + } + + HygieneData::with(|data| { + let syntax_contexts = &mut data.syntax_contexts; + *data.markings.entry((self, mark)).or_insert_with(|| { + syntax_contexts.push(SyntaxContextData { + outer_mark: mark, + prev_ctxt: self, + }); + SyntaxContext(syntax_contexts.len() as u32 - 1) + }) + }) + } + + /// If `ident` is macro expanded, return the source ident from the macro definition + /// and the mark of the expansion that created the macro definition. + pub fn source(self) -> (Self /* source context */, Mark /* source macro */) { + let macro_def_ctxt = self.data().prev_ctxt.data(); + (macro_def_ctxt.prev_ctxt, macro_def_ctxt.outer_mark) + } +} + +impl fmt::Debug for SyntaxContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "#{}", self.0) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/placeholders.rs b/bash-5.1/vendor/syntex_syntax/src/ext/placeholders.rs new file mode 100644 index 0000000..e832285 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/placeholders.rs @@ -0,0 +1,236 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast; +use codemap::{DUMMY_SP, dummy_spanned}; +use ext::base::ExtCtxt; +use ext::expand::{Expansion, ExpansionKind}; +use ext::hygiene::Mark; +use fold::*; +use ptr::P; +use symbol::keywords; +use util::move_map::MoveMap; +use util::small_vector::SmallVector; + +use std::collections::HashMap; +use std::mem; + +pub fn placeholder(kind: ExpansionKind, id: ast::NodeId) -> Expansion { + fn mac_placeholder() -> ast::Mac { + dummy_spanned(ast::Mac_ { + path: ast::Path { span: DUMMY_SP, segments: Vec::new() }, + tts: Vec::new(), + }) + } + + let ident = keywords::Invalid.ident(); + let attrs = Vec::new(); + let vis = ast::Visibility::Inherited; + let span = DUMMY_SP; + let expr_placeholder = || P(ast::Expr { + id: id, span: span, + attrs: ast::ThinVec::new(), + node: ast::ExprKind::Mac(mac_placeholder()), + }); + + match kind { + ExpansionKind::Expr => Expansion::Expr(expr_placeholder()), + ExpansionKind::OptExpr => Expansion::OptExpr(Some(expr_placeholder())), + ExpansionKind::Items => Expansion::Items(SmallVector::one(P(ast::Item { + id: id, span: span, ident: ident, vis: vis, attrs: attrs, + node: ast::ItemKind::Mac(mac_placeholder()), + }))), + ExpansionKind::TraitItems => Expansion::TraitItems(SmallVector::one(ast::TraitItem { + id: id, span: span, ident: ident, attrs: attrs, + node: ast::TraitItemKind::Macro(mac_placeholder()), + })), + ExpansionKind::ImplItems => Expansion::ImplItems(SmallVector::one(ast::ImplItem { + id: id, span: span, ident: ident, vis: vis, attrs: attrs, + node: ast::ImplItemKind::Macro(mac_placeholder()), + defaultness: ast::Defaultness::Final, + })), + ExpansionKind::Pat => Expansion::Pat(P(ast::Pat { + id: id, span: span, node: ast::PatKind::Mac(mac_placeholder()), + })), + ExpansionKind::Ty => Expansion::Ty(P(ast::Ty { + id: id, span: span, node: ast::TyKind::Mac(mac_placeholder()), + })), + ExpansionKind::Stmts => Expansion::Stmts(SmallVector::one({ + let mac = P((mac_placeholder(), ast::MacStmtStyle::Braces, ast::ThinVec::new())); + ast::Stmt { id: id, span: span, node: ast::StmtKind::Mac(mac) } + })), + } +} + +pub struct PlaceholderExpander<'a, 'b: 'a> { + expansions: HashMap<ast::NodeId, Expansion>, + cx: &'a mut ExtCtxt<'b>, + monotonic: bool, +} + +impl<'a, 'b> PlaceholderExpander<'a, 'b> { + pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { + PlaceholderExpander { + cx: cx, + expansions: HashMap::new(), + monotonic: monotonic, + } + } + + pub fn add(&mut self, id: ast::NodeId, expansion: Expansion) { + let expansion = expansion.fold_with(self); + self.expansions.insert(id, expansion); + } + + fn remove(&mut self, id: ast::NodeId) -> Expansion { + self.expansions.remove(&id).unwrap() + } +} + +impl<'a, 'b> Folder for PlaceholderExpander<'a, 'b> { + fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { + match item.node { + ast::ItemKind::Mac(ref mac) if !mac.node.path.segments.is_empty() => {} + // FIXME(syntex): ignore unknown macros + ast::ItemKind::Mac(_) if self.expansions.contains_key(&item.id) => return self.remove(item.id).make_items(), + _ => {} + } + + noop_fold_item(item, self) + } + + fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> { + match item.node { + // FIXME(syntex): ignore unknown macros + ast::TraitItemKind::Macro(_) if self.expansions.contains_key(&item.id) => self.remove(item.id).make_trait_items(), + _ => noop_fold_trait_item(item, self), + } + } + + fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> { + match item.node { + // FIXME(syntex): ignore unknown macros + ast::ImplItemKind::Macro(_) if self.expansions.contains_key(&item.id) => self.remove(item.id).make_impl_items(), + _ => noop_fold_impl_item(item, self), + } + } + + fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> { + match expr.node { + // FIXME(syntex): ignore unknown macros + ast::ExprKind::Mac(_) if self.expansions.contains_key(&expr.id) => self.remove(expr.id).make_expr(), + _ => expr.map(|expr| noop_fold_expr(expr, self)), + } + } + + fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> { + match expr.node { + // FIXME(syntex): ignore unknown macros + ast::ExprKind::Mac(_) if self.expansions.contains_key(&expr.id) => self.remove(expr.id).make_opt_expr(), + _ => noop_fold_opt_expr(expr, self), + } + } + + fn fold_stmt(&mut self, mut stmt: ast::Stmt) -> SmallVector<ast::Stmt> { + let (style, mut expansion) = match stmt.node { + // FIXME(syntex): ignore unknown macros + ast::StmtKind::Mac(mac) => { + if self.expansions.contains_key(&stmt.id) { + (mac.1, self.remove(stmt.id).make_stmts()) + } else { + stmt.node = ast::StmtKind::Mac(mac); + return noop_fold_stmt(stmt, self); + } + } + _ => return noop_fold_stmt(stmt, self), + }; + + if style == ast::MacStmtStyle::Semicolon { + if let Some(stmt) = expansion.pop() { + expansion.push(stmt.add_trailing_semicolon()); + } + } + + expansion + } + + fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> { + match pat.node { + // FIXME(syntex): ignore unknown macros + ast::PatKind::Mac(_) if self.expansions.contains_key(&pat.id) => self.remove(pat.id).make_pat(), + _ => noop_fold_pat(pat, self), + } + } + + fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> { + match ty.node { + // FIXME(syntex): ignore unknown macros + ast::TyKind::Mac(_) if self.expansions.contains_key(&ty.id) => self.remove(ty.id).make_ty(), + _ => noop_fold_ty(ty, self), + } + } + + fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> { + noop_fold_block(block, self).map(|mut block| { + let mut macros = Vec::new(); + let mut remaining_stmts = block.stmts.len(); + + block.stmts = block.stmts.move_flat_map(|mut stmt| { + remaining_stmts -= 1; + + // `macro_rules!` macro definition + if let ast::StmtKind::Item(ref item) = stmt.node { + if let ast::ItemKind::Mac(_) = item.node { + macros.push(Mark::from_placeholder_id(item.id)); + return None; + } + } + + match stmt.node { + // Avoid wasting a node id on a trailing expression statement, + // which shares a HIR node with the expression itself. + ast::StmtKind::Expr(ref expr) if remaining_stmts == 0 => stmt.id = expr.id, + + _ if self.monotonic => { + assert_eq!(stmt.id, ast::DUMMY_NODE_ID); + stmt.id = self.cx.resolver.next_node_id(); + } + + _ => {} + } + + if self.monotonic && !macros.is_empty() { + let macros = mem::replace(&mut macros, Vec::new()); + self.cx.resolver.add_expansions_at_stmt(stmt.id, macros); + } + + Some(stmt) + }); + + block + }) + } + + fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod { + let mut module = noop_fold_mod(module, self); + module.items = module.items.move_flat_map(|item| match item.node { + ast::ItemKind::Mac(_) if !self.cx.ecfg.keep_macs => None, // remove macro definitions + // FIXME(syntex): ignore unknown macros + ast::ItemKind::Mac(_) if self.expansions.contains_key(&item.id) => None, + _ => Some(item), + }); + module + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + // FIXME(syntex): ignore unknown macros + noop_fold_mac(mac, self) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/proc_macro_shim.rs b/bash-5.1/vendor/syntex_syntax/src/ext/proc_macro_shim.rs new file mode 100644 index 0000000..21ce89a --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/proc_macro_shim.rs @@ -0,0 +1,72 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! This is a shim file to ease the transition to the final procedural macro interface for +//! Macros 2.0. It currently exposes the `libsyntax` operations that the quasiquoter's +//! output needs to compile correctly, along with the following operators: +//! +//! - `build_block_emitter`, which produces a `block` output macro result from the +//! provided TokenStream. + +use ast; +use codemap::Span; +use parse::parser::Parser; +use ptr::P; +use tokenstream::TokenStream; +use ext::base::*; + +/// Take a `ExtCtxt`, `Span`, and `TokenStream`, and produce a Macro Result that parses +/// the TokenStream as a block and returns it as an `Expr`. +pub fn build_block_emitter<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + output: TokenStream) + -> Box<MacResult + 'cx> { + let parser = cx.new_parser_from_tts(&output.to_tts()); + + struct Result<'a> { + prsr: Parser<'a>, + span: Span, + }; //FIXME is this the right lifetime + + impl<'a> Result<'a> { + fn block(&mut self) -> P<ast::Block> { + let res = self.prsr.parse_block().unwrap(); + res + } + } + + impl<'a> MacResult for Result<'a> { + fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> { + let mut me = *self; + Some(P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Block(me.block()), + span: me.span, + attrs: ast::ThinVec::new(), + })) + + } + } + + Box::new(Result { + prsr: parser, + span: sp, + }) +} + +pub mod prelude { + pub use super::build_block_emitter; + pub use ast::Ident; + pub use codemap::{DUMMY_SP, Span}; + pub use ext::base::{ExtCtxt, MacResult}; + pub use parse::token::{self, Token, DelimToken}; + pub use symbol::keywords; + pub use tokenstream::{TokenTree, TokenStream}; +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/quote.rs b/bash-5.1/vendor/syntex_syntax/src/ext/quote.rs new file mode 100644 index 0000000..de64163 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/quote.rs @@ -0,0 +1,950 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast::{self, Arg, Arm, Block, Expr, Item, Pat, Stmt, Ty}; +use syntax_pos::Span; +use ext::base::ExtCtxt; +use ext::base; +use ext::build::AstBuilder; +use parse::parser::{Parser, PathStyle}; +use parse::token::*; +use parse::token; +use ptr::P; +use tokenstream::{self, TokenTree}; + + +/// Quasiquoting works via token trees. +/// +/// This is registered as a set of expression syntax extension called quote! +/// that lifts its argument token-tree to an AST representing the +/// construction of the same token tree, with token::SubstNt interpreted +/// as antiquotes (splices). + +pub mod rt { + use ast; + use codemap::Spanned; + use ext::base::ExtCtxt; + use parse::{self, token, classify}; + use ptr::P; + use std::rc::Rc; + use symbol::Symbol; + + use tokenstream::{self, TokenTree}; + + pub use parse::new_parser_from_tts; + pub use syntax_pos::{BytePos, Span, DUMMY_SP}; + pub use codemap::{dummy_spanned}; + + pub trait ToTokens { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree>; + } + + impl ToTokens for TokenTree { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + vec![self.clone()] + } + } + + impl<T: ToTokens> ToTokens for Vec<T> { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + self.iter().flat_map(|t| t.to_tokens(cx)).collect() + } + } + + impl<T: ToTokens> ToTokens for Spanned<T> { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + // FIXME: use the span? + self.node.to_tokens(cx) + } + } + + impl<T: ToTokens> ToTokens for Option<T> { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + match *self { + Some(ref t) => t.to_tokens(cx), + None => Vec::new(), + } + } + } + + impl ToTokens for ast::Ident { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + vec![TokenTree::Token(DUMMY_SP, token::Ident(*self))] + } + } + + impl ToTokens for ast::Path { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtPath(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Ty { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtTy(P(self.clone())); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Block { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtBlock(P(self.clone())); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Generics { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtGenerics(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::WhereClause { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtWhereClause(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for P<ast::Item> { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtItem(self.clone()); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::ImplItem { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtImplItem(self.clone()); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for P<ast::ImplItem> { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtImplItem((**self).clone()); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::TraitItem { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtTraitItem(self.clone()); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Stmt { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtStmt(self.clone()); + let mut tts = vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]; + + // Some statements require a trailing semicolon. + if classify::stmt_ends_with_semi(&self.node) { + tts.push(TokenTree::Token(self.span, token::Semi)); + } + + tts + } + } + + impl ToTokens for P<ast::Expr> { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtExpr(self.clone()); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for P<ast::Pat> { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtPat(self.clone()); + vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Arm { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtArm(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Arg { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtArg(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for P<ast::Block> { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtBlock(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + macro_rules! impl_to_tokens_slice { + ($t: ty, $sep: expr) => { + impl ToTokens for [$t] { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + let mut v = vec![]; + for (i, x) in self.iter().enumerate() { + if i > 0 { + v.extend_from_slice(&$sep); + } + v.extend(x.to_tokens(cx)); + } + v + } + } + }; + } + + impl_to_tokens_slice! { ast::Ty, [TokenTree::Token(DUMMY_SP, token::Comma)] } + impl_to_tokens_slice! { P<ast::Item>, [] } + impl_to_tokens_slice! { ast::Arg, [TokenTree::Token(DUMMY_SP, token::Comma)] } + + impl ToTokens for ast::MetaItem { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + let nt = token::NtMeta(self.clone()); + vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))] + } + } + + impl ToTokens for ast::Attribute { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + let mut r = vec![]; + // FIXME: The spans could be better + r.push(TokenTree::Token(self.span, token::Pound)); + if self.style == ast::AttrStyle::Inner { + r.push(TokenTree::Token(self.span, token::Not)); + } + r.push(TokenTree::Delimited(self.span, Rc::new(tokenstream::Delimited { + delim: token::Bracket, + open_span: self.span, + tts: self.value.to_tokens(cx), + close_span: self.span, + }))); + r + } + } + + impl ToTokens for str { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + let lit = ast::LitKind::Str(Symbol::intern(self), ast::StrStyle::Cooked); + dummy_spanned(lit).to_tokens(cx) + } + } + + impl ToTokens for () { + fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { + vec![TokenTree::Delimited(DUMMY_SP, Rc::new(tokenstream::Delimited { + delim: token::Paren, + open_span: DUMMY_SP, + tts: vec![], + close_span: DUMMY_SP, + }))] + } + } + + impl ToTokens for ast::Lit { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + // FIXME: This is wrong + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Lit(P(self.clone())), + span: DUMMY_SP, + attrs: ast::ThinVec::new(), + }).to_tokens(cx) + } + } + + impl ToTokens for bool { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + dummy_spanned(ast::LitKind::Bool(*self)).to_tokens(cx) + } + } + + impl ToTokens for char { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + dummy_spanned(ast::LitKind::Char(*self)).to_tokens(cx) + } + } + + macro_rules! impl_to_tokens_int { + (signed, $t:ty, $tag:expr) => ( + impl ToTokens for $t { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + let val = if *self < 0 { + -self + } else { + *self + }; + let lit = ast::LitKind::Int(val as u64, ast::LitIntType::Signed($tag)); + let lit = P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Lit(P(dummy_spanned(lit))), + span: DUMMY_SP, + attrs: ast::ThinVec::new(), + }); + if *self >= 0 { + return lit.to_tokens(cx); + } + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Unary(ast::UnOp::Neg, lit), + span: DUMMY_SP, + attrs: ast::ThinVec::new(), + }).to_tokens(cx) + } + } + ); + (unsigned, $t:ty, $tag:expr) => ( + impl ToTokens for $t { + fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { + let lit = ast::LitKind::Int(*self as u64, ast::LitIntType::Unsigned($tag)); + dummy_spanned(lit).to_tokens(cx) + } + } + ); + } + + impl_to_tokens_int! { signed, isize, ast::IntTy::Is } + impl_to_tokens_int! { signed, i8, ast::IntTy::I8 } + impl_to_tokens_int! { signed, i16, ast::IntTy::I16 } + impl_to_tokens_int! { signed, i32, ast::IntTy::I32 } + impl_to_tokens_int! { signed, i64, ast::IntTy::I64 } + + impl_to_tokens_int! { unsigned, usize, ast::UintTy::Us } + impl_to_tokens_int! { unsigned, u8, ast::UintTy::U8 } + impl_to_tokens_int! { unsigned, u16, ast::UintTy::U16 } + impl_to_tokens_int! { unsigned, u32, ast::UintTy::U32 } + impl_to_tokens_int! { unsigned, u64, ast::UintTy::U64 } + + pub trait ExtParseUtils { + fn parse_item(&self, s: String) -> P<ast::Item>; + fn parse_expr(&self, s: String) -> P<ast::Expr>; + fn parse_stmt(&self, s: String) -> ast::Stmt; + fn parse_tts(&self, s: String) -> Vec<TokenTree>; + } + + impl<'a> ExtParseUtils for ExtCtxt<'a> { + fn parse_item(&self, s: String) -> P<ast::Item> { + panictry!(parse::parse_item_from_source_str( + "<quote expansion>".to_string(), + s, + self.parse_sess())).expect("parse error") + } + + fn parse_stmt(&self, s: String) -> ast::Stmt { + panictry!(parse::parse_stmt_from_source_str( + "<quote expansion>".to_string(), + s, + self.parse_sess())).expect("parse error") + } + + fn parse_expr(&self, s: String) -> P<ast::Expr> { + panictry!(parse::parse_expr_from_source_str( + "<quote expansion>".to_string(), + s, + self.parse_sess())) + } + + fn parse_tts(&self, s: String) -> Vec<TokenTree> { + panictry!(parse::parse_tts_from_source_str( + "<quote expansion>".to_string(), + s, + self.parse_sess())) + } + } +} + +// These panicking parsing functions are used by the quote_*!() syntax extensions, +// but shouldn't be used otherwise. +pub fn parse_expr_panic(parser: &mut Parser) -> P<Expr> { + panictry!(parser.parse_expr()) +} + +pub fn parse_item_panic(parser: &mut Parser) -> Option<P<Item>> { + panictry!(parser.parse_item()) +} + +pub fn parse_pat_panic(parser: &mut Parser) -> P<Pat> { + panictry!(parser.parse_pat()) +} + +pub fn parse_arm_panic(parser: &mut Parser) -> Arm { + panictry!(parser.parse_arm()) +} + +pub fn parse_ty_panic(parser: &mut Parser) -> P<Ty> { + panictry!(parser.parse_ty()) +} + +pub fn parse_stmt_panic(parser: &mut Parser) -> Option<Stmt> { + panictry!(parser.parse_stmt()) +} + +pub fn parse_attribute_panic(parser: &mut Parser, permit_inner: bool) -> ast::Attribute { + panictry!(parser.parse_attribute(permit_inner)) +} + +pub fn parse_arg_panic(parser: &mut Parser) -> Arg { + panictry!(parser.parse_arg()) +} + +pub fn parse_block_panic(parser: &mut Parser) -> P<Block> { + panictry!(parser.parse_block()) +} + +pub fn parse_meta_item_panic(parser: &mut Parser) -> ast::MetaItem { + panictry!(parser.parse_meta_item()) +} + +pub fn parse_path_panic(parser: &mut Parser, mode: PathStyle) -> ast::Path { + panictry!(parser.parse_path(mode)) +} + +pub fn expand_quote_tokens<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'cx> { + let (cx_expr, expr) = expand_tts(cx, sp, tts); + let expanded = expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_expr<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'cx> { + let expanded = expand_parse_call(cx, sp, "parse_expr_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_item<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'cx> { + let expanded = expand_parse_call(cx, sp, "parse_item_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_pat<'cx>(cx: &'cx mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'cx> { + let expanded = expand_parse_call(cx, sp, "parse_pat_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_arm(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_arm_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_ty(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_ty_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_stmt(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_stmt_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_attr(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_attribute_panic", + vec![cx.expr_bool(sp, true)], tts); + + base::MacEager::expr(expanded) +} + +pub fn expand_quote_arg(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_arg_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_block(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_block_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_meta_item(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let expanded = expand_parse_call(cx, sp, "parse_meta_item_panic", vec![], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_path(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let mode = mk_parser_path(cx, sp, &["PathStyle", "Type"]); + let expanded = expand_parse_call(cx, sp, "parse_path_panic", vec![mode], tts); + base::MacEager::expr(expanded) +} + +pub fn expand_quote_matcher(cx: &mut ExtCtxt, + sp: Span, + tts: &[TokenTree]) + -> Box<base::MacResult+'static> { + let (cx_expr, tts) = parse_arguments_to_quote(cx, tts); + let mut vector = mk_stmts_let(cx, sp); + vector.extend(statements_mk_tts(cx, &tts[..], true)); + vector.push(cx.stmt_expr(cx.expr_ident(sp, id_ext("tt")))); + let block = cx.expr_block(cx.block(sp, vector)); + + let expanded = expand_wrapper(cx, sp, cx_expr, block, &[&["syntax", "ext", "quote", "rt"]]); + base::MacEager::expr(expanded) +} + +fn ids_ext(strs: Vec<String>) -> Vec<ast::Ident> { + strs.iter().map(|s| ast::Ident::from_str(s)).collect() +} + +fn id_ext(s: &str) -> ast::Ident { + ast::Ident::from_str(s) +} + +// Lift an ident to the expr that evaluates to that ident. +fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> { + let e_str = cx.expr_str(sp, ident.name); + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("ext_cx")), + id_ext("ident_of"), + vec![e_str]) +} + +// Lift a name to the expr that evaluates to that name +fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> { + let e_str = cx.expr_str(sp, ident.name); + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("ext_cx")), + id_ext("name_of"), + vec![e_str]) +} + +fn mk_tt_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> { + let idents = vec![id_ext("syntax"), id_ext("tokenstream"), id_ext("TokenTree"), id_ext(name)]; + cx.expr_path(cx.path_global(sp, idents)) +} + +fn mk_token_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> { + let idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name)]; + cx.expr_path(cx.path_global(sp, idents)) +} + +fn mk_parser_path(cx: &ExtCtxt, sp: Span, names: &[&str]) -> P<ast::Expr> { + let mut idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("parser")]; + idents.extend(names.iter().cloned().map(id_ext)); + cx.expr_path(cx.path_global(sp, idents)) +} + +fn mk_binop(cx: &ExtCtxt, sp: Span, bop: token::BinOpToken) -> P<ast::Expr> { + let name = match bop { + token::Plus => "Plus", + token::Minus => "Minus", + token::Star => "Star", + token::Slash => "Slash", + token::Percent => "Percent", + token::Caret => "Caret", + token::And => "And", + token::Or => "Or", + token::Shl => "Shl", + token::Shr => "Shr" + }; + mk_token_path(cx, sp, name) +} + +fn mk_delim(cx: &ExtCtxt, sp: Span, delim: token::DelimToken) -> P<ast::Expr> { + let name = match delim { + token::Paren => "Paren", + token::Bracket => "Bracket", + token::Brace => "Brace", + token::NoDelim => "NoDelim", + }; + mk_token_path(cx, sp, name) +} + +#[allow(non_upper_case_globals)] +fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> { + macro_rules! mk_lit { + ($name: expr, $suffix: expr, $($args: expr),*) => {{ + let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![$($args),*]); + let suffix = match $suffix { + Some(name) => cx.expr_some(sp, mk_name(cx, sp, ast::Ident::with_empty_ctxt(name))), + None => cx.expr_none(sp) + }; + cx.expr_call(sp, mk_token_path(cx, sp, "Literal"), vec![inner, suffix]) + }} + } + match *tok { + token::BinOp(binop) => { + return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec![mk_binop(cx, sp, binop)]); + } + token::BinOpEq(binop) => { + return cx.expr_call(sp, mk_token_path(cx, sp, "BinOpEq"), + vec![mk_binop(cx, sp, binop)]); + } + + token::OpenDelim(delim) => { + return cx.expr_call(sp, mk_token_path(cx, sp, "OpenDelim"), + vec![mk_delim(cx, sp, delim)]); + } + token::CloseDelim(delim) => { + return cx.expr_call(sp, mk_token_path(cx, sp, "CloseDelim"), + vec![mk_delim(cx, sp, delim)]); + } + + token::Literal(token::Byte(i), suf) => { + let e_byte = mk_name(cx, sp, ast::Ident::with_empty_ctxt(i)); + return mk_lit!("Byte", suf, e_byte); + } + + token::Literal(token::Char(i), suf) => { + let e_char = mk_name(cx, sp, ast::Ident::with_empty_ctxt(i)); + return mk_lit!("Char", suf, e_char); + } + + token::Literal(token::Integer(i), suf) => { + let e_int = mk_name(cx, sp, ast::Ident::with_empty_ctxt(i)); + return mk_lit!("Integer", suf, e_int); + } + + token::Literal(token::Float(fident), suf) => { + let e_fident = mk_name(cx, sp, ast::Ident::with_empty_ctxt(fident)); + return mk_lit!("Float", suf, e_fident); + } + + token::Literal(token::Str_(ident), suf) => { + return mk_lit!("Str_", suf, mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident))) + } + + token::Literal(token::StrRaw(ident, n), suf) => { + return mk_lit!("StrRaw", suf, mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident)), + cx.expr_usize(sp, n)) + } + + token::Ident(ident) => { + return cx.expr_call(sp, + mk_token_path(cx, sp, "Ident"), + vec![mk_ident(cx, sp, ident)]); + } + + token::Lifetime(ident) => { + return cx.expr_call(sp, + mk_token_path(cx, sp, "Lifetime"), + vec![mk_ident(cx, sp, ident)]); + } + + token::DocComment(ident) => { + return cx.expr_call(sp, + mk_token_path(cx, sp, "DocComment"), + vec![mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident))]); + } + + token::MatchNt(name, kind) => { + return cx.expr_call(sp, + mk_token_path(cx, sp, "MatchNt"), + vec![mk_ident(cx, sp, name), mk_ident(cx, sp, kind)]); + } + + token::Interpolated(_) => panic!("quote! with interpolated token"), + + _ => () + } + + let name = match *tok { + token::Eq => "Eq", + token::Lt => "Lt", + token::Le => "Le", + token::EqEq => "EqEq", + token::Ne => "Ne", + token::Ge => "Ge", + token::Gt => "Gt", + token::AndAnd => "AndAnd", + token::OrOr => "OrOr", + token::Not => "Not", + token::Tilde => "Tilde", + token::At => "At", + token::Dot => "Dot", + token::DotDot => "DotDot", + token::Comma => "Comma", + token::Semi => "Semi", + token::Colon => "Colon", + token::ModSep => "ModSep", + token::RArrow => "RArrow", + token::LArrow => "LArrow", + token::FatArrow => "FatArrow", + token::Pound => "Pound", + token::Dollar => "Dollar", + token::Question => "Question", + token::Underscore => "Underscore", + token::Eof => "Eof", + _ => panic!("unhandled token in quote!"), + }; + mk_token_path(cx, sp, name) +} + +fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<ast::Stmt> { + match *tt { + TokenTree::Token(sp, SubstNt(ident)) => { + // tt.extend($ident.to_tokens(ext_cx)) + + let e_to_toks = + cx.expr_method_call(sp, + cx.expr_ident(sp, ident), + id_ext("to_tokens"), + vec![cx.expr_ident(sp, id_ext("ext_cx"))]); + let e_to_toks = + cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]); + + let e_push = + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("tt")), + id_ext("extend"), + vec![e_to_toks]); + + vec![cx.stmt_expr(e_push)] + } + ref tt @ TokenTree::Token(_, MatchNt(..)) if !matcher => { + let mut seq = vec![]; + for i in 0..tt.len() { + seq.push(tt.get_tt(i)); + } + statements_mk_tts(cx, &seq[..], matcher) + } + TokenTree::Token(sp, ref tok) => { + let e_sp = cx.expr_ident(sp, id_ext("_sp")); + let e_tok = cx.expr_call(sp, + mk_tt_path(cx, sp, "Token"), + vec![e_sp, expr_mk_token(cx, sp, tok)]); + let e_push = + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("tt")), + id_ext("push"), + vec![e_tok]); + vec![cx.stmt_expr(e_push)] + }, + TokenTree::Delimited(_, ref delimed) => { + statements_mk_tt(cx, &delimed.open_tt(), matcher).into_iter() + .chain(delimed.tts.iter() + .flat_map(|tt| statements_mk_tt(cx, tt, matcher))) + .chain(statements_mk_tt(cx, &delimed.close_tt(), matcher)) + .collect() + }, + TokenTree::Sequence(sp, ref seq) => { + if !matcher { + panic!("TokenTree::Sequence in quote!"); + } + + let e_sp = cx.expr_ident(sp, id_ext("_sp")); + + let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); + let mut tts_stmts = vec![stmt_let_tt]; + tts_stmts.extend(statements_mk_tts(cx, &seq.tts[..], matcher)); + tts_stmts.push(cx.stmt_expr(cx.expr_ident(sp, id_ext("tt")))); + let e_tts = cx.expr_block(cx.block(sp, tts_stmts)); + + let e_separator = match seq.separator { + Some(ref sep) => cx.expr_some(sp, expr_mk_token(cx, sp, sep)), + None => cx.expr_none(sp), + }; + let e_op = match seq.op { + tokenstream::KleeneOp::ZeroOrMore => "ZeroOrMore", + tokenstream::KleeneOp::OneOrMore => "OneOrMore", + }; + let e_op_idents = vec![ + id_ext("syntax"), + id_ext("tokenstream"), + id_ext("KleeneOp"), + id_ext(e_op), + ]; + let e_op = cx.expr_path(cx.path_global(sp, e_op_idents)); + let fields = vec![cx.field_imm(sp, id_ext("tts"), e_tts), + cx.field_imm(sp, id_ext("separator"), e_separator), + cx.field_imm(sp, id_ext("op"), e_op), + cx.field_imm(sp, id_ext("num_captures"), + cx.expr_usize(sp, seq.num_captures))]; + let seq_path = vec![id_ext("syntax"), + id_ext("tokenstream"), + id_ext("SequenceRepetition")]; + let e_seq_struct = cx.expr_struct(sp, cx.path_global(sp, seq_path), fields); + let e_rc_new = cx.expr_call_global(sp, vec![id_ext("std"), + id_ext("rc"), + id_ext("Rc"), + id_ext("new")], + vec![e_seq_struct]); + let e_tok = cx.expr_call(sp, + mk_tt_path(cx, sp, "Sequence"), + vec![e_sp, e_rc_new]); + let e_push = + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("tt")), + id_ext("push"), + vec![e_tok]); + vec![cx.stmt_expr(e_push)] + } + } +} + +fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[TokenTree]) + -> (P<ast::Expr>, Vec<TokenTree>) { + // NB: It appears that the main parser loses its mind if we consider + // $foo as a SubstNt during the main parse, so we have to re-parse + // under quote_depth > 0. This is silly and should go away; the _guess_ is + // it has to do with transition away from supporting old-style macros, so + // try removing it when enough of them are gone. + + let mut p = cx.new_parser_from_tts(tts); + p.quote_depth += 1; + + let cx_expr = panictry!(p.parse_expr()); + if !p.eat(&token::Comma) { + let _ = p.diagnostic().fatal("expected token `,`"); + } + + let tts = panictry!(p.parse_all_token_trees()); + p.abort_if_errors(); + + (cx_expr, tts) +} + +fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<ast::Stmt> { + // We also bind a single value, sp, to ext_cx.call_site() + // + // This causes every span in a token-tree quote to be attributed to the + // call site of the extension using the quote. We can't really do much + // better since the source of the quote may well be in a library that + // was not even parsed by this compilation run, that the user has no + // source code for (eg. in libsyntax, which they're just _using_). + // + // The old quasiquoter had an elaborate mechanism for denoting input + // file locations from which quotes originated; unfortunately this + // relied on feeding the source string of the quote back into the + // compiler (which we don't really want to do) and, in any case, only + // pushed the problem a very small step further back: an error + // resulting from a parse of the resulting quote is still attributed to + // the site the string literal occurred, which was in a source file + // _other_ than the one the user has control over. For example, an + // error in a quote from the protocol compiler, invoked in user code + // using macro_rules! for example, will be attributed to the macro_rules.rs + // file in libsyntax, which the user might not even have source to (unless + // they happen to have a compiler on hand). Over all, the phase distinction + // just makes quotes "hard to attribute". Possibly this could be fixed + // by recreating some of the original qq machinery in the tt regime + // (pushing fake FileMaps onto the parser to account for original sites + // of quotes, for example) but at this point it seems not likely to be + // worth the hassle. + + let e_sp = cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("ext_cx")), + id_ext("call_site"), + Vec::new()); + + let stmt_let_sp = cx.stmt_let(sp, false, + id_ext("_sp"), + e_sp); + + let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); + + vec![stmt_let_sp, stmt_let_tt] +} + +fn statements_mk_tts(cx: &ExtCtxt, tts: &[TokenTree], matcher: bool) -> Vec<ast::Stmt> { + let mut ss = Vec::new(); + for tt in tts { + ss.extend(statements_mk_tt(cx, tt, matcher)); + } + ss +} + +fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[TokenTree]) + -> (P<ast::Expr>, P<ast::Expr>) { + let (cx_expr, tts) = parse_arguments_to_quote(cx, tts); + + let mut vector = mk_stmts_let(cx, sp); + vector.extend(statements_mk_tts(cx, &tts[..], false)); + vector.push(cx.stmt_expr(cx.expr_ident(sp, id_ext("tt")))); + let block = cx.expr_block(cx.block(sp, vector)); + + (cx_expr, block) +} + +fn expand_wrapper(cx: &ExtCtxt, + sp: Span, + cx_expr: P<ast::Expr>, + expr: P<ast::Expr>, + imports: &[&[&str]]) -> P<ast::Expr> { + // Explicitly borrow to avoid moving from the invoker (#16992) + let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr)); + let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow); + + let mut stmts = imports.iter().map(|path| { + // make item: `use ...;` + let path = path.iter().map(|s| s.to_string()).collect(); + cx.stmt_item(sp, cx.item_use_glob(sp, ast::Visibility::Inherited, ids_ext(path))) + }).chain(Some(stmt_let_ext_cx)).collect::<Vec<_>>(); + stmts.push(cx.stmt_expr(expr)); + + cx.expr_block(cx.block(sp, stmts)) +} + +fn expand_parse_call(cx: &ExtCtxt, + sp: Span, + parse_method: &str, + arg_exprs: Vec<P<ast::Expr>> , + tts: &[TokenTree]) -> P<ast::Expr> { + let (cx_expr, tts_expr) = expand_tts(cx, sp, tts); + + let parse_sess_call = || cx.expr_method_call( + sp, cx.expr_ident(sp, id_ext("ext_cx")), + id_ext("parse_sess"), Vec::new()); + + let new_parser_call = + cx.expr_call(sp, + cx.expr_ident(sp, id_ext("new_parser_from_tts")), + vec![parse_sess_call(), tts_expr]); + + let path = vec![id_ext("syntax"), id_ext("ext"), id_ext("quote"), id_ext(parse_method)]; + let mut args = vec![cx.expr_mut_addr_of(sp, new_parser_call)]; + args.extend(arg_exprs); + let expr = cx.expr_call_global(sp, path, args); + + if parse_method == "parse_attribute" { + expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"], + &["syntax", "parse", "attr"]]) + } else { + expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/source_util.rs b/bash-5.1/vendor/syntex_syntax/src/ext/source_util.rs new file mode 100644 index 0000000..39b92c7 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/source_util.rs @@ -0,0 +1,196 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast; +use syntax_pos::{self, Pos, Span}; +use ext::base::*; +use ext::base; +use ext::build::AstBuilder; +use parse::{token, DirectoryOwnership}; +use parse; +use print::pprust; +use ptr::P; +use symbol::Symbol; +use tokenstream; +use util::small_vector::SmallVector; + +use std::fs::File; +use std::io::prelude::*; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +// These macros all relate to the file system; they either return +// the column/row/filename of the expression, or they include +// a given file into the current one. + +/// line!(): expands to the current line number +pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + base::check_zero_tts(cx, sp, tts, "line!"); + + let topmost = cx.expansion_cause(); + let loc = cx.codemap().lookup_char_pos(topmost.lo); + + base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32)) +} + +/* column!(): expands to the current column number */ +pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + base::check_zero_tts(cx, sp, tts, "column!"); + + let topmost = cx.expansion_cause(); + let loc = cx.codemap().lookup_char_pos(topmost.lo); + + base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32)) +} + +/// file!(): expands to the current filename */ +/// The filemap (`loc.file`) contains a bunch more information we could spit +/// out if we wanted. +pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + base::check_zero_tts(cx, sp, tts, "file!"); + + let topmost = cx.expansion_cause(); + let loc = cx.codemap().lookup_char_pos(topmost.lo); + base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name))) +} + +pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + let s = pprust::tts_to_string(tts); + base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s))) +} + +pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + base::check_zero_tts(cx, sp, tts, "module_path!"); + let mod_path = &cx.current_expansion.module.mod_path; + let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::"); + + base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string))) +} + +/// include! : parse the given file as an expr +/// This is generally a bad idea because it's going to behave +/// unhygienically. +pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'cx> { + let file = match get_single_str_from_tts(cx, sp, tts, "include!") { + Some(f) => f, + None => return DummyResult::expr(sp), + }; + // The file will be added to the code map by the parser + let path = res_rel_file(cx, sp, Path::new(&file)); + let directory_ownership = DirectoryOwnership::Owned; + let p = parse::new_sub_parser_from_file(cx.parse_sess(), &path, directory_ownership, None, sp); + + struct ExpandResult<'a> { + p: parse::parser::Parser<'a>, + } + impl<'a> base::MacResult for ExpandResult<'a> { + fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> { + Some(panictry!(self.p.parse_expr())) + } + fn make_items(mut self: Box<ExpandResult<'a>>) + -> Option<SmallVector<P<ast::Item>>> { + let mut ret = SmallVector::new(); + while self.p.token != token::Eof { + match panictry!(self.p.parse_item()) { + Some(item) => ret.push(item), + None => panic!(self.p.diagnostic().span_fatal(self.p.span, + &format!("expected item, found `{}`", + self.p.this_token_to_string()))) + } + } + Some(ret) + } + } + + Box::new(ExpandResult { p: p }) +} + +// include_str! : read the given file, insert it as a literal string expr +pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") { + Some(f) => f, + None => return DummyResult::expr(sp) + }; + let file = res_rel_file(cx, sp, Path::new(&file)); + let mut bytes = Vec::new(); + match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) { + Ok(..) => {} + Err(e) => { + cx.span_err(sp, + &format!("couldn't read {}: {}", + file.display(), + e)); + return DummyResult::expr(sp); + } + }; + match String::from_utf8(bytes) { + Ok(src) => { + // Add this input file to the code map to make it available as + // dependency information + let filename = format!("{}", file.display()); + cx.codemap().new_filemap_and_lines(&filename, None, &src); + + base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&src))) + } + Err(_) => { + cx.span_err(sp, + &format!("{} wasn't a utf-8 file", + file.display())); + return DummyResult::expr(sp); + } + } +} + +pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) + -> Box<base::MacResult+'static> { + let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") { + Some(f) => f, + None => return DummyResult::expr(sp) + }; + let file = res_rel_file(cx, sp, Path::new(&file)); + let mut bytes = Vec::new(); + match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) { + Err(e) => { + cx.span_err(sp, + &format!("couldn't read {}: {}", file.display(), e)); + return DummyResult::expr(sp); + } + Ok(..) => { + // Add this input file to the code map to make it available as + // dependency information, but don't enter it's contents + let filename = format!("{}", file.display()); + cx.codemap().new_filemap_and_lines(&filename, None, ""); + + base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Rc::new(bytes)))) + } + } +} + +// resolve a file-system path to an absolute file-system path (if it +// isn't already) +fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: &Path) -> PathBuf { + // NB: relative paths are resolved relative to the compilation unit + if !arg.is_absolute() { + let callsite = cx.codemap().source_callsite(sp); + let mut cu = PathBuf::from(&cx.codemap().span_to_filename(callsite)); + cu.pop(); + cu.push(arg); + cu + } else { + arg.to_path_buf() + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_parser.rs b/bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_parser.rs new file mode 100644 index 0000000..ff732bb --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_parser.rs @@ -0,0 +1,547 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! This is an Earley-like parser, without support for in-grammar nonterminals, +//! only by calling out to the main rust parser for named nonterminals (which it +//! commits to fully when it hits one in a grammar). This means that there are no +//! completer or predictor rules, and therefore no need to store one column per +//! token: instead, there's a set of current Earley items and a set of next +//! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in +//! pathological cases, is worse than traditional Earley parsing, but it's an +//! easier fit for Macro-by-Example-style rules, and I think the overhead is +//! lower. (In order to prevent the pathological case, we'd need to lazily +//! construct the resulting `NamedMatch`es at the very end. It'd be a pain, +//! and require more memory to keep around old items, but it would also save +//! overhead) +//! +//! Quick intro to how the parser works: +//! +//! A 'position' is a dot in the middle of a matcher, usually represented as a +//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. +//! +//! The parser walks through the input a character at a time, maintaining a list +//! of items consistent with the current position in the input string: `cur_eis`. +//! +//! As it processes them, it fills up `eof_eis` with items that would be valid if +//! the macro invocation is now over, `bb_eis` with items that are waiting on +//! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting +//! on a particular token. Most of the logic concerns moving the · through the +//! repetitions indicated by Kleene stars. It only advances or calls out to the +//! real Rust parser when no `cur_eis` items remain +//! +//! Example: Start parsing `a a a a b` against [· a $( a )* a b]. +//! +//! Remaining input: `a a a a b` +//! next_eis: [· a $( a )* a b] +//! +//! - - - Advance over an `a`. - - - +//! +//! Remaining input: `a a a b` +//! cur: [a · $( a )* a b] +//! Descend/Skip (first item). +//! next: [a $( · a )* a b] [a $( a )* · a b]. +//! +//! - - - Advance over an `a`. - - - +//! +//! Remaining input: `a a b` +//! cur: [a $( a · )* a b] next: [a $( a )* a · b] +//! Finish/Repeat (first item) +//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] +//! +//! - - - Advance over an `a`. - - - (this looks exactly like the last step) +//! +//! Remaining input: `a b` +//! cur: [a $( a · )* a b] next: [a $( a )* a · b] +//! Finish/Repeat (first item) +//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] +//! +//! - - - Advance over an `a`. - - - (this looks exactly like the last step) +//! +//! Remaining input: `b` +//! cur: [a $( a · )* a b] next: [a $( a )* a · b] +//! Finish/Repeat (first item) +//! next: [a $( a )* · a b] [a $( · a )* a b] +//! +//! - - - Advance over a `b`. - - - +//! +//! Remaining input: `` +//! eof: [a $( a )* a b ·] + +pub use self::NamedMatch::*; +pub use self::ParseResult::*; +use self::TokenTreeOrTokenTreeVec::*; + +use ast::Ident; +use syntax_pos::{self, BytePos, mk_sp, Span}; +use codemap::Spanned; +use errors::FatalError; +use parse::lexer::*; //resolve bug? +use parse::{Directory, ParseSess}; +use parse::parser::{PathStyle, Parser}; +use parse::token::{DocComment, MatchNt, SubstNt}; +use parse::token::{Token, Nonterminal}; +use parse::token; +use print::pprust; +use tokenstream::{self, TokenTree}; +use util::small_vector::SmallVector; + +use std::mem; +use std::rc::Rc; +use std::collections::HashMap; +use std::collections::hash_map::Entry::{Vacant, Occupied}; + +// To avoid costly uniqueness checks, we require that `MatchSeq` always has +// a nonempty body. + +#[derive(Clone)] +enum TokenTreeOrTokenTreeVec { + Tt(tokenstream::TokenTree), + TtSeq(Vec<tokenstream::TokenTree>), +} + +impl TokenTreeOrTokenTreeVec { + fn len(&self) -> usize { + match *self { + TtSeq(ref v) => v.len(), + Tt(ref tt) => tt.len(), + } + } + + fn get_tt(&self, index: usize) -> TokenTree { + match *self { + TtSeq(ref v) => v[index].clone(), + Tt(ref tt) => tt.get_tt(index), + } + } +} + +/// an unzipping of `TokenTree`s +#[derive(Clone)] +struct MatcherTtFrame { + elts: TokenTreeOrTokenTreeVec, + idx: usize, +} + +#[derive(Clone)] +struct MatcherPos { + stack: Vec<MatcherTtFrame>, + top_elts: TokenTreeOrTokenTreeVec, + sep: Option<Token>, + idx: usize, + up: Option<Box<MatcherPos>>, + matches: Vec<Vec<Rc<NamedMatch>>>, + match_lo: usize, + match_cur: usize, + match_hi: usize, + sp_lo: BytePos, +} + +pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>; + +pub fn count_names(ms: &[TokenTree]) -> usize { + ms.iter().fold(0, |count, elt| { + count + match *elt { + TokenTree::Sequence(_, ref seq) => { + seq.num_captures + } + TokenTree::Delimited(_, ref delim) => { + count_names(&delim.tts) + } + TokenTree::Token(_, MatchNt(..)) => { + 1 + } + TokenTree::Token(..) => 0, + } + }) +} + +fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> { + let match_idx_hi = count_names(&ms[..]); + let matches = create_matches(match_idx_hi); + Box::new(MatcherPos { + stack: vec![], + top_elts: TtSeq(ms), + sep: None, + idx: 0, + up: None, + matches: matches, + match_lo: 0, + match_cur: 0, + match_hi: match_idx_hi, + sp_lo: lo + }) +} + +/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL: +/// so it is associated with a single ident in a parse, and all +/// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type +/// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a +/// single token::MATCH_NONTERMINAL in the TokenTree that produced it. +/// +/// The in-memory structure of a particular NamedMatch represents the match +/// that occurred when a particular subset of a matcher was applied to a +/// particular token tree. +/// +/// The width of each MatchedSeq in the NamedMatch, and the identity of the +/// `MatchedNonterminal`s, will depend on the token tree it was applied to: +/// each MatchedSeq corresponds to a single TTSeq in the originating +/// token tree. The depth of the NamedMatch structure will therefore depend +/// only on the nesting depth of `ast::TTSeq`s in the originating +/// token tree it was derived from. + +pub enum NamedMatch { + MatchedSeq(Vec<Rc<NamedMatch>>, syntax_pos::Span), + MatchedNonterminal(Rc<Nonterminal>) +} + +fn nameize<I: Iterator<Item=Rc<NamedMatch>>>(ms: &[TokenTree], mut res: I) -> NamedParseResult { + fn n_rec<I: Iterator<Item=Rc<NamedMatch>>>(m: &TokenTree, mut res: &mut I, + ret_val: &mut HashMap<Ident, Rc<NamedMatch>>) + -> Result<(), (syntax_pos::Span, String)> { + match *m { + TokenTree::Sequence(_, ref seq) => { + for next_m in &seq.tts { + try!(n_rec(next_m, res.by_ref(), ret_val)) + } + } + TokenTree::Delimited(_, ref delim) => { + for next_m in &delim.tts { + try!(n_rec(next_m, res.by_ref(), ret_val)); + } + } + TokenTree::Token(sp, MatchNt(bind_name, _)) => { + match ret_val.entry(bind_name) { + Vacant(spot) => { + spot.insert(res.next().unwrap()); + } + Occupied(..) => { + return Err((sp, format!("duplicated bind name: {}", bind_name))) + } + } + } + TokenTree::Token(sp, SubstNt(..)) => { + return Err((sp, "missing fragment specifier".to_string())) + } + TokenTree::Token(..) => (), + } + + Ok(()) + } + + let mut ret_val = HashMap::new(); + for m in ms { + match n_rec(m, res.by_ref(), &mut ret_val) { + Ok(_) => {}, + Err((sp, msg)) => return Error(sp, msg), + } + } + + Success(ret_val) +} + +pub enum ParseResult<T> { + Success(T), + /// Arm failed to match. If the second parameter is `token::Eof`, it + /// indicates an unexpected end of macro invocation. Otherwise, it + /// indicates that no rules expected the given token. + Failure(syntax_pos::Span, Token), + /// Fatal error (malformed macro?). Abort compilation. + Error(syntax_pos::Span, String) +} + +pub fn parse_failure_msg(tok: Token) -> String { + match tok { + token::Eof => "unexpected end of macro invocation".to_string(), + _ => format!("no rules expected the token `{}`", pprust::token_to_string(&tok)), + } +} + +/// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison) +fn token_name_eq(t1 : &Token, t2 : &Token) -> bool { + match (t1,t2) { + (&token::Ident(id1),&token::Ident(id2)) + | (&token::Lifetime(id1),&token::Lifetime(id2)) => + id1.name == id2.name, + _ => *t1 == *t2 + } +} + +fn create_matches(len: usize) -> Vec<Vec<Rc<NamedMatch>>> { + (0..len).into_iter().map(|_| Vec::new()).collect() +} + +fn inner_parse_loop(cur_eis: &mut SmallVector<Box<MatcherPos>>, + next_eis: &mut Vec<Box<MatcherPos>>, + eof_eis: &mut SmallVector<Box<MatcherPos>>, + bb_eis: &mut SmallVector<Box<MatcherPos>>, + token: &Token, span: &syntax_pos::Span) -> ParseResult<()> { + while let Some(mut ei) = cur_eis.pop() { + // When unzipped trees end, remove them + while ei.idx >= ei.top_elts.len() { + match ei.stack.pop() { + Some(MatcherTtFrame { elts, idx }) => { + ei.top_elts = elts; + ei.idx = idx + 1; + } + None => break + } + } + + let idx = ei.idx; + let len = ei.top_elts.len(); + + // at end of sequence + if idx >= len { + // We are repeating iff there is a parent + if ei.up.is_some() { + // Disregarding the separator, add the "up" case to the tokens that should be + // examined. + // (remove this condition to make trailing seps ok) + if idx == len { + let mut new_pos = ei.up.clone().unwrap(); + + // update matches (the MBE "parse tree") by appending + // each tree as a subtree. + + // I bet this is a perf problem: we're preemptively + // doing a lot of array work that will get thrown away + // most of the time. + + // Only touch the binders we have actually bound + for idx in ei.match_lo..ei.match_hi { + let sub = ei.matches[idx].clone(); + new_pos.matches[idx] + .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, + span.hi)))); + } + + new_pos.match_cur = ei.match_hi; + new_pos.idx += 1; + cur_eis.push(new_pos); + } + + // Check if we need a separator + if idx == len && ei.sep.is_some() { + // We have a separator, and it is the current token. + if ei.sep.as_ref().map(|ref sep| token_name_eq(&token, sep)).unwrap_or(false) { + ei.idx += 1; + next_eis.push(ei); + } + } else { // we don't need a separator + ei.match_cur = ei.match_lo; + ei.idx = 0; + cur_eis.push(ei); + } + } else { + // We aren't repeating, so we must be potentially at the end of the input. + eof_eis.push(ei); + } + } else { + match ei.top_elts.get_tt(idx) { + /* need to descend into sequence */ + TokenTree::Sequence(sp, seq) => { + if seq.op == tokenstream::KleeneOp::ZeroOrMore { + // Examine the case where there are 0 matches of this sequence + let mut new_ei = ei.clone(); + new_ei.match_cur += seq.num_captures; + new_ei.idx += 1; + for idx in ei.match_cur..ei.match_cur + seq.num_captures { + new_ei.matches[idx].push(Rc::new(MatchedSeq(vec![], sp))); + } + cur_eis.push(new_ei); + } + + // Examine the case where there is at least one match of this sequence + let matches = create_matches(ei.matches.len()); + cur_eis.push(Box::new(MatcherPos { + stack: vec![], + sep: seq.separator.clone(), + idx: 0, + matches: matches, + match_lo: ei.match_cur, + match_cur: ei.match_cur, + match_hi: ei.match_cur + seq.num_captures, + up: Some(ei), + sp_lo: sp.lo, + top_elts: Tt(TokenTree::Sequence(sp, seq)), + })); + } + TokenTree::Token(_, MatchNt(..)) => { + // Built-in nonterminals never start with these tokens, + // so we can eliminate them from consideration. + match *token { + token::CloseDelim(_) => {}, + _ => bb_eis.push(ei), + } + } + TokenTree::Token(sp, SubstNt(..)) => { + return Error(sp, "missing fragment specifier".to_string()) + } + seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => { + let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq)); + let idx = ei.idx; + ei.stack.push(MatcherTtFrame { + elts: lower_elts, + idx: idx, + }); + ei.idx = 0; + cur_eis.push(ei); + } + TokenTree::Token(_, ref t) => { + if token_name_eq(t, &token) { + ei.idx += 1; + next_eis.push(ei); + } + } + } + } + } + + Success(()) +} + +pub fn parse(sess: &ParseSess, rdr: TtReader, ms: &[TokenTree], directory: Option<Directory>) + -> NamedParseResult { + let mut parser = Parser::new(sess, Box::new(rdr), directory, true); + let mut cur_eis = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo)); + let mut next_eis = Vec::new(); // or proceed normally + + loop { + let mut bb_eis = SmallVector::new(); // black-box parsed by parser.rs + let mut eof_eis = SmallVector::new(); + assert!(next_eis.is_empty()); + + match inner_parse_loop(&mut cur_eis, &mut next_eis, &mut eof_eis, &mut bb_eis, + &parser.token, &parser.span) { + Success(_) => {}, + Failure(sp, tok) => return Failure(sp, tok), + Error(sp, msg) => return Error(sp, msg), + } + + // inner parse loop handled all cur_eis, so it's empty + assert!(cur_eis.is_empty()); + + /* error messages here could be improved with links to orig. rules */ + if token_name_eq(&parser.token, &token::Eof) { + if eof_eis.len() == 1 { + return nameize(ms, eof_eis[0].matches.iter_mut().map(|mut dv| dv.pop().unwrap())); + } else if eof_eis.len() > 1 { + return Error(parser.span, "ambiguity: multiple successful parses".to_string()); + } else { + return Failure(parser.span, token::Eof); + } + } else if (!bb_eis.is_empty() && !next_eis.is_empty()) || bb_eis.len() > 1 { + let nts = bb_eis.iter().map(|ei| match ei.top_elts.get_tt(ei.idx) { + TokenTree::Token(_, MatchNt(bind, name)) => { + format!("{} ('{}')", name, bind) + } + _ => panic!() + }).collect::<Vec<String>>().join(" or "); + + return Error(parser.span, format!( + "local ambiguity: multiple parsing options: {}", + match next_eis.len() { + 0 => format!("built-in NTs {}.", nts), + 1 => format!("built-in NTs {} or 1 other option.", nts), + n => format!("built-in NTs {} or {} other options.", nts, n), + } + )); + } else if bb_eis.is_empty() && next_eis.is_empty() { + return Failure(parser.span, parser.token); + } else if !next_eis.is_empty() { + /* Now process the next token */ + cur_eis.extend(next_eis.drain(..)); + parser.bump(); + } else /* bb_eis.len() == 1 */ { + let mut ei = bb_eis.pop().unwrap(); + if let TokenTree::Token(span, MatchNt(_, ident)) = ei.top_elts.get_tt(ei.idx) { + let match_cur = ei.match_cur; + ei.matches[match_cur].push(Rc::new(MatchedNonterminal( + Rc::new(parse_nt(&mut parser, span, &ident.name.as_str()))))); + ei.idx += 1; + ei.match_cur += 1; + } else { + unreachable!() + } + cur_eis.push(ei); + } + + assert!(!cur_eis.is_empty()); + } +} + +fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal { + match name { + "tt" => { + p.quote_depth += 1; //but in theory, non-quoted tts might be useful + let mut tt = panictry!(p.parse_token_tree()); + p.quote_depth -= 1; + while let TokenTree::Token(sp, token::Interpolated(nt)) = tt { + if let token::NtTT(..) = *nt { + match Rc::try_unwrap(nt) { + Ok(token::NtTT(sub_tt)) => tt = sub_tt, + Ok(_) => unreachable!(), + Err(nt_rc) => match *nt_rc { + token::NtTT(ref sub_tt) => tt = sub_tt.clone(), + _ => unreachable!(), + }, + } + } else { + tt = TokenTree::Token(sp, token::Interpolated(nt.clone())); + break + } + } + return token::NtTT(tt); + } + _ => {} + } + // check at the beginning and the parser checks after each bump + p.check_unknown_macro_variable(); + match name { + "item" => match panictry!(p.parse_item()) { + Some(i) => token::NtItem(i), + None => { + p.fatal("expected an item keyword").emit(); + panic!(FatalError); + } + }, + "block" => token::NtBlock(panictry!(p.parse_block())), + "stmt" => match panictry!(p.parse_stmt()) { + Some(s) => token::NtStmt(s), + None => { + p.fatal("expected a statement").emit(); + panic!(FatalError); + } + }, + "pat" => token::NtPat(panictry!(p.parse_pat())), + "expr" => token::NtExpr(panictry!(p.parse_expr())), + "ty" => token::NtTy(panictry!(p.parse_ty())), + // this could be handled like a token, since it is one + "ident" => match p.token { + token::Ident(sn) => { + p.bump(); + token::NtIdent(Spanned::<Ident>{node: sn, span: p.span}) + } + _ => { + let token_str = pprust::token_to_string(&p.token); + p.fatal(&format!("expected ident, found {}", + &token_str[..])).emit(); + panic!(FatalError) + } + }, + "path" => { + token::NtPath(panictry!(p.parse_path(PathStyle::Type))) + }, + "meta" => token::NtMeta(panictry!(p.parse_meta_item())), + // this is not supposed to happen, since it has been checked + // when compiling the macro. + _ => p.span_bug(sp, "invalid fragment specifier") + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_rules.rs b/bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_rules.rs new file mode 100644 index 0000000..3abd24b --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/tt/macro_rules.rs @@ -0,0 +1,810 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use {ast, attr}; +use syntax_pos::{Span, DUMMY_SP}; +use ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension}; +use ext::base::{NormalTT, TTMacroExpander}; +use ext::expand::{Expansion, ExpansionKind}; +use ext::tt::macro_parser::{Success, Error, Failure}; +use ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal}; +use ext::tt::macro_parser::{parse, parse_failure_msg}; +use parse::{Directory, ParseSess}; +use parse::lexer::new_tt_reader; +use parse::parser::Parser; +use parse::token::{self, NtTT, Token}; +use parse::token::Token::*; +use print; +use symbol::Symbol; +use tokenstream::{self, TokenTree}; + +use std::collections::{HashMap}; +use std::collections::hash_map::{Entry}; +use std::rc::Rc; + +pub struct ParserAnyMacro<'a> { + parser: Parser<'a>, + + /// Span of the expansion site of the macro this parser is for + site_span: Span, + /// The ident of the macro we're parsing + macro_ident: ast::Ident +} + +impl<'a> ParserAnyMacro<'a> { + pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: ExpansionKind) -> Expansion { + let ParserAnyMacro { site_span, macro_ident, ref mut parser } = *self; + let expansion = panictry!(parser.parse_expansion(kind, true)); + + // We allow semicolons at the end of expressions -- e.g. the semicolon in + // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`, + // but `m!()` is allowed in expression positions (c.f. issue #34706). + if kind == ExpansionKind::Expr && parser.token == token::Semi { + parser.bump(); + } + + // Make sure we don't have any tokens left to parse so we don't silently drop anything. + parser.ensure_complete_parse(macro_ident.name, kind.name(), site_span); + expansion + } +} + +struct MacroRulesMacroExpander { + name: ast::Ident, + lhses: Vec<TokenTree>, + rhses: Vec<TokenTree>, + valid: bool, +} + +impl TTMacroExpander for MacroRulesMacroExpander { + fn expand<'cx>(&self, + cx: &'cx mut ExtCtxt, + sp: Span, + arg: &[TokenTree]) + -> Box<MacResult+'cx> { + if !self.valid { + return DummyResult::any(sp); + } + generic_extension(cx, + sp, + self.name, + arg, + &self.lhses, + &self.rhses) + } +} + +/// Given `lhses` and `rhses`, this is the new macro we create +fn generic_extension<'cx>(cx: &'cx ExtCtxt, + sp: Span, + name: ast::Ident, + arg: &[TokenTree], + lhses: &[TokenTree], + rhses: &[TokenTree]) + -> Box<MacResult+'cx> { + if cx.trace_macros() { + println!("{}! {{ {} }}", + name, + print::pprust::tts_to_string(arg)); + } + + // Which arm's failure should we report? (the one furthest along) + let mut best_fail_spot = DUMMY_SP; + let mut best_fail_tok = None; + + for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers + let lhs_tt = match *lhs { + TokenTree::Delimited(_, ref delim) => &delim.tts[..], + _ => cx.span_bug(sp, "malformed macro lhs") + }; + + match TokenTree::parse(cx, lhs_tt, arg) { + Success(named_matches) => { + let rhs = match rhses[i] { + // ignore delimiters + TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(), + _ => cx.span_bug(sp, "malformed macro rhs"), + }; + // rhs has holes ( `$id` and `$(...)` that need filled) + let trncbr = + new_tt_reader(&cx.parse_sess.span_diagnostic, Some(named_matches), rhs); + let directory = Directory { + path: cx.current_expansion.module.directory.clone(), + ownership: cx.current_expansion.directory_ownership, + }; + let mut p = Parser::new(cx.parse_sess(), Box::new(trncbr), Some(directory), false); + p.root_module_name = cx.current_expansion.module.mod_path.last() + .map(|id| (*id.name.as_str()).to_owned()); + + p.check_unknown_macro_variable(); + // Let the context choose how to interpret the result. + // Weird, but useful for X-macros. + return Box::new(ParserAnyMacro { + parser: p, + + // Pass along the original expansion site and the name of the macro + // so we can print a useful error message if the parse of the expanded + // macro leaves unparsed tokens. + site_span: sp, + macro_ident: name + }) + } + Failure(sp, tok) => if sp.lo >= best_fail_spot.lo { + best_fail_spot = sp; + best_fail_tok = Some(tok); + }, + Error(err_sp, ref msg) => { + cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..]) + } + } + } + + let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers")); + cx.span_fatal(best_fail_spot.substitute_dummy(sp), &best_fail_msg); +} + +// Note that macro-by-example's input is also matched against a token tree: +// $( $lhs:tt => $rhs:tt );+ +// +// Holy self-referential! + +/// Converts a `macro_rules!` invocation into a syntax extension. +pub fn compile(sess: &ParseSess, def: &ast::MacroDef) -> SyntaxExtension { + let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs")); + let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs")); + + // The pattern that macro_rules matches. + // The grammar for macro_rules! is: + // $( $lhs:tt => $rhs:tt );+ + // ...quasiquoting this would be nice. + // These spans won't matter, anyways + let match_lhs_tok = MatchNt(lhs_nm, ast::Ident::from_str("tt")); + let match_rhs_tok = MatchNt(rhs_nm, ast::Ident::from_str("tt")); + let argument_gram = vec![ + TokenTree::Sequence(DUMMY_SP, Rc::new(tokenstream::SequenceRepetition { + tts: vec![ + TokenTree::Token(DUMMY_SP, match_lhs_tok), + TokenTree::Token(DUMMY_SP, token::FatArrow), + TokenTree::Token(DUMMY_SP, match_rhs_tok), + ], + separator: Some(token::Semi), + op: tokenstream::KleeneOp::OneOrMore, + num_captures: 2, + })), + // to phase into semicolon-termination instead of semicolon-separation + TokenTree::Sequence(DUMMY_SP, Rc::new(tokenstream::SequenceRepetition { + tts: vec![TokenTree::Token(DUMMY_SP, token::Semi)], + separator: None, + op: tokenstream::KleeneOp::ZeroOrMore, + num_captures: 0 + })), + ]; + + // Parse the macro_rules! invocation (`none` is for no interpolations): + let arg_reader = new_tt_reader(&sess.span_diagnostic, None, def.body.clone()); + + let argument_map = match parse(sess, arg_reader, &argument_gram, None) { + Success(m) => m, + Failure(sp, tok) => { + let s = parse_failure_msg(tok); + panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s)); + } + Error(sp, s) => { + panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s)); + } + }; + + let mut valid = true; + + // Extract the arguments: + let lhses = match **argument_map.get(&lhs_nm).unwrap() { + MatchedSeq(ref s, _) => { + s.iter().map(|m| { + if let MatchedNonterminal(ref nt) = **m { + if let NtTT(ref tt) = **nt { + valid &= check_lhs_nt_follows(sess, tt); + return (*tt).clone(); + } + } + sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") + }).collect::<Vec<TokenTree>>() + } + _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") + }; + + let rhses = match **argument_map.get(&rhs_nm).unwrap() { + MatchedSeq(ref s, _) => { + s.iter().map(|m| { + if let MatchedNonterminal(ref nt) = **m { + if let NtTT(ref tt) = **nt { + return (*tt).clone(); + } + } + sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") + }).collect() + } + _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs") + }; + + for rhs in &rhses { + valid &= check_rhs(sess, rhs); + } + + // don't abort iteration early, so that errors for multiple lhses can be reported + for lhs in &lhses { + valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()]) + } + + let exp: Box<_> = Box::new(MacroRulesMacroExpander { + name: def.ident, + lhses: lhses, + rhses: rhses, + valid: valid, + }); + + NormalTT(exp, Some(def.span), attr::contains_name(&def.attrs, "allow_internal_unstable")) +} + +fn check_lhs_nt_follows(sess: &ParseSess, lhs: &TokenTree) -> bool { + // lhs is going to be like TokenTree::Delimited(...), where the + // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens. + match lhs { + &TokenTree::Delimited(_, ref tts) => check_matcher(sess, &tts.tts), + _ => { + let msg = "invalid macro matcher; matchers must be contained in balanced delimiters"; + sess.span_diagnostic.span_err(lhs.get_span(), msg); + false + } + } + // we don't abort on errors on rejection, the driver will do that for us + // after parsing/expansion. we can report every error in every macro this way. +} + +/// Check that the lhs contains no repetition which could match an empty token +/// tree, because then the matcher would hang indefinitely. +fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[TokenTree]) -> bool { + for tt in tts { + match *tt { + TokenTree::Token(_, _) => (), + TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) { + return false; + }, + TokenTree::Sequence(span, ref seq) => { + if seq.separator.is_none() { + if seq.tts.iter().all(|seq_tt| { + match *seq_tt { + TokenTree::Sequence(_, ref sub_seq) => + sub_seq.op == tokenstream::KleeneOp::ZeroOrMore, + _ => false, + } + }) { + sess.span_diagnostic.span_err(span, "repetition matches empty token tree"); + return false; + } + } + if !check_lhs_no_empty_seq(sess, &seq.tts) { + return false; + } + } + } + } + + true +} + +fn check_rhs(sess: &ParseSess, rhs: &TokenTree) -> bool { + match *rhs { + TokenTree::Delimited(..) => return true, + _ => sess.span_diagnostic.span_err(rhs.get_span(), "macro rhs must be delimited") + } + false +} + +fn check_matcher(sess: &ParseSess, matcher: &[TokenTree]) -> bool { + let first_sets = FirstSets::new(matcher); + let empty_suffix = TokenSet::empty(); + let err = sess.span_diagnostic.err_count(); + check_matcher_core(sess, &first_sets, matcher, &empty_suffix); + err == sess.span_diagnostic.err_count() +} + +// The FirstSets for a matcher is a mapping from subsequences in the +// matcher to the FIRST set for that subsequence. +// +// This mapping is partially precomputed via a backwards scan over the +// token trees of the matcher, which provides a mapping from each +// repetition sequence to its FIRST set. +// +// (Hypothetically sequences should be uniquely identifiable via their +// spans, though perhaps that is false e.g. for macro-generated macros +// that do not try to inject artificial span information. My plan is +// to try to catch such cases ahead of time and not include them in +// the precomputed mapping.) +struct FirstSets { + // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its + // span in the original matcher to the First set for the inner sequence `tt ...`. + // + // If two sequences have the same span in a matcher, then map that + // span to None (invalidating the mapping here and forcing the code to + // use a slow path). + first: HashMap<Span, Option<TokenSet>>, +} + +impl FirstSets { + fn new(tts: &[TokenTree]) -> FirstSets { + let mut sets = FirstSets { first: HashMap::new() }; + build_recur(&mut sets, tts); + return sets; + + // walks backward over `tts`, returning the FIRST for `tts` + // and updating `sets` at the same time for all sequence + // substructure we find within `tts`. + fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet { + let mut first = TokenSet::empty(); + for tt in tts.iter().rev() { + match *tt { + TokenTree::Token(sp, ref tok) => { + first.replace_with((sp, tok.clone())); + } + TokenTree::Delimited(_, ref delimited) => { + build_recur(sets, &delimited.tts[..]); + first.replace_with((delimited.open_span, + Token::OpenDelim(delimited.delim))); + } + TokenTree::Sequence(sp, ref seq_rep) => { + let subfirst = build_recur(sets, &seq_rep.tts[..]); + + match sets.first.entry(sp) { + Entry::Vacant(vac) => { + vac.insert(Some(subfirst.clone())); + } + Entry::Occupied(mut occ) => { + // if there is already an entry, then a span must have collided. + // This should not happen with typical macro_rules macros, + // but syntax extensions need not maintain distinct spans, + // so distinct syntax trees can be assigned the same span. + // In such a case, the map cannot be trusted; so mark this + // entry as unusable. + occ.insert(None); + } + } + + // If the sequence contents can be empty, then the first + // token could be the separator token itself. + + if let (Some(ref sep), true) = (seq_rep.separator.clone(), + subfirst.maybe_empty) { + first.add_one_maybe((sp, sep.clone())); + } + + // Reverse scan: Sequence comes before `first`. + if subfirst.maybe_empty || seq_rep.op == tokenstream::KleeneOp::ZeroOrMore { + // If sequence is potentially empty, then + // union them (preserving first emptiness). + first.add_all(&TokenSet { maybe_empty: true, ..subfirst }); + } else { + // Otherwise, sequence guaranteed + // non-empty; replace first. + first = subfirst; + } + } + } + } + + return first; + } + } + + // walks forward over `tts` until all potential FIRST tokens are + // identified. + fn first(&self, tts: &[TokenTree]) -> TokenSet { + let mut first = TokenSet::empty(); + for tt in tts.iter() { + assert!(first.maybe_empty); + match *tt { + TokenTree::Token(sp, ref tok) => { + first.add_one((sp, tok.clone())); + return first; + } + TokenTree::Delimited(_, ref delimited) => { + first.add_one((delimited.open_span, + Token::OpenDelim(delimited.delim))); + return first; + } + TokenTree::Sequence(sp, ref seq_rep) => { + match self.first.get(&sp) { + Some(&Some(ref subfirst)) => { + + // If the sequence contents can be empty, then the first + // token could be the separator token itself. + + if let (Some(ref sep), true) = (seq_rep.separator.clone(), + subfirst.maybe_empty) { + first.add_one_maybe((sp, sep.clone())); + } + + assert!(first.maybe_empty); + first.add_all(subfirst); + if subfirst.maybe_empty || + seq_rep.op == tokenstream::KleeneOp::ZeroOrMore { + // continue scanning for more first + // tokens, but also make sure we + // restore empty-tracking state + first.maybe_empty = true; + continue; + } else { + return first; + } + } + + Some(&None) => { + panic!("assume all sequences have (unique) spans for now"); + } + + None => { + panic!("We missed a sequence during FirstSets construction"); + } + } + } + } + } + + // we only exit the loop if `tts` was empty or if every + // element of `tts` matches the empty sequence. + assert!(first.maybe_empty); + return first; + } +} + +// A set of Tokens, which may include MatchNt tokens (for +// macro-by-example syntactic variables). It also carries the +// `maybe_empty` flag; that is true if and only if the matcher can +// match an empty token sequence. +// +// The First set is computed on submatchers like `$($a:expr b),* $(c)* d`, +// which has corresponding FIRST = {$a:expr, c, d}. +// Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}. +// +// (Notably, we must allow for *-op to occur zero times.) +#[derive(Clone, Debug)] +struct TokenSet { + tokens: Vec<(Span, Token)>, + maybe_empty: bool, +} + +impl TokenSet { + // Returns a set for the empty sequence. + fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } } + + // Returns the set `{ tok }` for the single-token (and thus + // non-empty) sequence [tok]. + fn singleton(tok: (Span, Token)) -> Self { + TokenSet { tokens: vec![tok], maybe_empty: false } + } + + // Changes self to be the set `{ tok }`. + // Since `tok` is always present, marks self as non-empty. + fn replace_with(&mut self, tok: (Span, Token)) { + self.tokens.clear(); + self.tokens.push(tok); + self.maybe_empty = false; + } + + // Changes self to be the empty set `{}`; meant for use when + // the particular token does not matter, but we want to + // record that it occurs. + fn replace_with_irrelevant(&mut self) { + self.tokens.clear(); + self.maybe_empty = false; + } + + // Adds `tok` to the set for `self`, marking sequence as non-empy. + fn add_one(&mut self, tok: (Span, Token)) { + if !self.tokens.contains(&tok) { + self.tokens.push(tok); + } + self.maybe_empty = false; + } + + // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.) + fn add_one_maybe(&mut self, tok: (Span, Token)) { + if !self.tokens.contains(&tok) { + self.tokens.push(tok); + } + } + + // Adds all elements of `other` to this. + // + // (Since this is a set, we filter out duplicates.) + // + // If `other` is potentially empty, then preserves the previous + // setting of the empty flag of `self`. If `other` is guaranteed + // non-empty, then `self` is marked non-empty. + fn add_all(&mut self, other: &Self) { + for tok in &other.tokens { + if !self.tokens.contains(tok) { + self.tokens.push(tok.clone()); + } + } + if !other.maybe_empty { + self.maybe_empty = false; + } + } +} + +// Checks that `matcher` is internally consistent and that it +// can legally by followed by a token N, for all N in `follow`. +// (If `follow` is empty, then it imposes no constraint on +// the `matcher`.) +// +// Returns the set of NT tokens that could possibly come last in +// `matcher`. (If `matcher` matches the empty sequence, then +// `maybe_empty` will be set to true.) +// +// Requires that `first_sets` is pre-computed for `matcher`; +// see `FirstSets::new`. +fn check_matcher_core(sess: &ParseSess, + first_sets: &FirstSets, + matcher: &[TokenTree], + follow: &TokenSet) -> TokenSet { + use print::pprust::token_to_string; + + let mut last = TokenSet::empty(); + + // 2. For each token and suffix [T, SUFFIX] in M: + // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty, + // then ensure T can also be followed by any element of FOLLOW. + 'each_token: for i in 0..matcher.len() { + let token = &matcher[i]; + let suffix = &matcher[i+1..]; + + let build_suffix_first = || { + let mut s = first_sets.first(suffix); + if s.maybe_empty { s.add_all(follow); } + return s; + }; + + // (we build `suffix_first` on demand below; you can tell + // which cases are supposed to fall through by looking for the + // initialization of this variable.) + let suffix_first; + + // First, update `last` so that it corresponds to the set + // of NT tokens that might end the sequence `... token`. + match *token { + TokenTree::Token(sp, ref tok) => { + let can_be_followed_by_any; + if let Err(bad_frag) = has_legal_fragment_specifier(tok) { + let msg = format!("invalid fragment specifier `{}`", bad_frag); + sess.span_diagnostic.struct_span_err(sp, &msg) + .help("valid fragment specifiers are `ident`, `block`, \ + `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \ + and `item`") + .emit(); + // (This eliminates false positives and duplicates + // from error messages.) + can_be_followed_by_any = true; + } else { + can_be_followed_by_any = token_can_be_followed_by_any(tok); + } + + if can_be_followed_by_any { + // don't need to track tokens that work with any, + last.replace_with_irrelevant(); + // ... and don't need to check tokens that can be + // followed by anything against SUFFIX. + continue 'each_token; + } else { + last.replace_with((sp, tok.clone())); + suffix_first = build_suffix_first(); + } + } + TokenTree::Delimited(_, ref d) => { + let my_suffix = TokenSet::singleton((d.close_span, Token::CloseDelim(d.delim))); + check_matcher_core(sess, first_sets, &d.tts, &my_suffix); + // don't track non NT tokens + last.replace_with_irrelevant(); + + // also, we don't need to check delimited sequences + // against SUFFIX + continue 'each_token; + } + TokenTree::Sequence(sp, ref seq_rep) => { + suffix_first = build_suffix_first(); + // The trick here: when we check the interior, we want + // to include the separator (if any) as a potential + // (but not guaranteed) element of FOLLOW. So in that + // case, we make a temp copy of suffix and stuff + // delimiter in there. + // + // FIXME: Should I first scan suffix_first to see if + // delimiter is already in it before I go through the + // work of cloning it? But then again, this way I may + // get a "tighter" span? + let mut new; + let my_suffix = if let Some(ref u) = seq_rep.separator { + new = suffix_first.clone(); + new.add_one_maybe((sp, u.clone())); + &new + } else { + &suffix_first + }; + + // At this point, `suffix_first` is built, and + // `my_suffix` is some TokenSet that we can use + // for checking the interior of `seq_rep`. + let next = check_matcher_core(sess, first_sets, &seq_rep.tts, my_suffix); + if next.maybe_empty { + last.add_all(&next); + } else { + last = next; + } + + // the recursive call to check_matcher_core already ran the 'each_last + // check below, so we can just keep going forward here. + continue 'each_token; + } + } + + // (`suffix_first` guaranteed initialized once reaching here.) + + // Now `last` holds the complete set of NT tokens that could + // end the sequence before SUFFIX. Check that every one works with `suffix`. + 'each_last: for &(_sp, ref t) in &last.tokens { + if let MatchNt(ref name, ref frag_spec) = *t { + for &(sp, ref next_token) in &suffix_first.tokens { + match is_in_follow(next_token, &frag_spec.name.as_str()) { + Err((msg, help)) => { + sess.span_diagnostic.struct_span_err(sp, &msg).help(help).emit(); + // don't bother reporting every source of + // conflict for a particular element of `last`. + continue 'each_last; + } + Ok(true) => {} + Ok(false) => { + let may_be = if last.tokens.len() == 1 && + suffix_first.tokens.len() == 1 + { + "is" + } else { + "may be" + }; + + sess.span_diagnostic.span_err( + sp, + &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \ + is not allowed for `{frag}` fragments", + name=name, + frag=frag_spec, + next=token_to_string(next_token), + may_be=may_be) + ); + } + } + } + } + } + } + last +} + +fn token_can_be_followed_by_any(tok: &Token) -> bool { + if let &MatchNt(_, ref frag_spec) = tok { + frag_can_be_followed_by_any(&frag_spec.name.as_str()) + } else { + // (Non NT's can always be followed by anthing in matchers.) + true + } +} + +/// True if a fragment of type `frag` can be followed by any sort of +/// token. We use this (among other things) as a useful approximation +/// for when `frag` can be followed by a repetition like `$(...)*` or +/// `$(...)+`. In general, these can be a bit tricky to reason about, +/// so we adopt a conservative position that says that any fragment +/// specifier which consumes at most one token tree can be followed by +/// a fragment specifier (indeed, these fragments can be followed by +/// ANYTHING without fear of future compatibility hazards). +fn frag_can_be_followed_by_any(frag: &str) -> bool { + match frag { + "item" | // always terminated by `}` or `;` + "block" | // exactly one token tree + "ident" | // exactly one token tree + "meta" | // exactly one token tree + "tt" => // exactly one token tree + true, + + _ => + false, + } +} + +/// True if `frag` can legally be followed by the token `tok`. For +/// fragments that can consume an unbounded number of tokens, `tok` +/// must be within a well-defined follow set. This is intended to +/// guarantee future compatibility: for example, without this rule, if +/// we expanded `expr` to include a new binary operator, we might +/// break macros that were relying on that binary operator as a +/// separator. +// when changing this do not forget to update doc/book/macros.md! +fn is_in_follow(tok: &Token, frag: &str) -> Result<bool, (String, &'static str)> { + if let &CloseDelim(_) = tok { + // closing a token tree can never be matched by any fragment; + // iow, we always require that `(` and `)` match, etc. + Ok(true) + } else { + match frag { + "item" => { + // since items *must* be followed by either a `;` or a `}`, we can + // accept anything after them + Ok(true) + }, + "block" => { + // anything can follow block, the braces provide an easy boundary to + // maintain + Ok(true) + }, + "stmt" | "expr" => { + match *tok { + FatArrow | Comma | Semi => Ok(true), + _ => Ok(false) + } + }, + "pat" => { + match *tok { + FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true), + Ident(i) if i.name == "if" || i.name == "in" => Ok(true), + _ => Ok(false) + } + }, + "path" | "ty" => { + match *tok { + OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) | + Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true), + MatchNt(_, ref frag) if frag.name == "block" => Ok(true), + Ident(i) if i.name == "as" || i.name == "where" => Ok(true), + _ => Ok(false) + } + }, + "ident" => { + // being a single token, idents are harmless + Ok(true) + }, + "meta" | "tt" => { + // being either a single token or a delimited sequence, tt is + // harmless + Ok(true) + }, + _ => Err((format!("invalid fragment specifier `{}`", frag), + "valid fragment specifiers are `ident`, `block`, \ + `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \ + and `item`")) + } + } +} + +fn has_legal_fragment_specifier(tok: &Token) -> Result<(), String> { + debug!("has_legal_fragment_specifier({:?})", tok); + if let &MatchNt(_, ref frag_spec) = tok { + let s = &frag_spec.name.as_str(); + if !is_legal_fragment_specifier(s) { + return Err(s.to_string()); + } + } + Ok(()) +} + +fn is_legal_fragment_specifier(frag: &str) -> bool { + match frag { + "item" | "block" | "stmt" | "expr" | "pat" | + "path" | "ty" | "ident" | "meta" | "tt" => true, + _ => false, + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ext/tt/transcribe.rs b/bash-5.1/vendor/syntex_syntax/src/ext/tt/transcribe.rs new file mode 100644 index 0000000..37e329e --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ext/tt/transcribe.rs @@ -0,0 +1,300 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +use self::LockstepIterSize::*; + +use ast::Ident; +use errors::{Handler, DiagnosticBuilder}; +use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal}; +use parse::token::{self, MatchNt, SubstNt, Token, NtIdent}; +use parse::lexer::TokenAndSpan; +use syntax_pos::{Span, DUMMY_SP}; +use tokenstream::{self, TokenTree}; +use util::small_vector::SmallVector; + +use std::rc::Rc; +use std::ops::Add; +use std::collections::HashMap; + +///an unzipping of `TokenTree`s +#[derive(Clone)] +struct TtFrame { + forest: TokenTree, + idx: usize, + dotdotdoted: bool, + sep: Option<Token>, +} + +#[derive(Clone)] +pub struct TtReader<'a> { + pub sp_diag: &'a Handler, + /// the unzipped tree: + stack: SmallVector<TtFrame>, + /* for MBE-style macro transcription */ + interpolations: HashMap<Ident, Rc<NamedMatch>>, + + repeat_idx: Vec<usize>, + repeat_len: Vec<usize>, + /* cached: */ + pub cur_tok: Token, + pub cur_span: Span, + /// Transform doc comments. Only useful in macro invocations + pub fatal_errs: Vec<DiagnosticBuilder<'a>>, +} + +/// This can do Macro-By-Example transcription. On the other hand, if +/// `src` contains no `TokenTree::Sequence`s, `MatchNt`s or `SubstNt`s, `interp` can +/// (and should) be None. +pub fn new_tt_reader(sp_diag: &Handler, + interp: Option<HashMap<Ident, Rc<NamedMatch>>>, + src: Vec<tokenstream::TokenTree>) + -> TtReader { + let mut r = TtReader { + sp_diag: sp_diag, + stack: SmallVector::one(TtFrame { + forest: TokenTree::Sequence(DUMMY_SP, Rc::new(tokenstream::SequenceRepetition { + tts: src, + // doesn't matter. This merely holds the root unzipping. + separator: None, op: tokenstream::KleeneOp::ZeroOrMore, num_captures: 0 + })), + idx: 0, + dotdotdoted: false, + sep: None, + }), + interpolations: match interp { /* just a convenience */ + None => HashMap::new(), + Some(x) => x, + }, + repeat_idx: Vec::new(), + repeat_len: Vec::new(), + /* dummy values, never read: */ + cur_tok: token::Eof, + cur_span: DUMMY_SP, + fatal_errs: Vec::new(), + }; + tt_next_token(&mut r); /* get cur_tok and cur_span set up */ + r +} + +fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc<NamedMatch>) -> Rc<NamedMatch> { + r.repeat_idx.iter().fold(start, |ad, idx| { + match *ad { + MatchedNonterminal(_) => { + // end of the line; duplicate henceforth + ad.clone() + } + MatchedSeq(ref ads, _) => ads[*idx].clone() + } + }) +} + +fn lookup_cur_matched(r: &TtReader, name: Ident) -> Option<Rc<NamedMatch>> { + let matched_opt = r.interpolations.get(&name).cloned(); + matched_opt.map(|s| lookup_cur_matched_by_matched(r, s)) +} + +#[derive(Clone)] +enum LockstepIterSize { + LisUnconstrained, + LisConstraint(usize, Ident), + LisContradiction(String), +} + +impl Add for LockstepIterSize { + type Output = LockstepIterSize; + + fn add(self, other: LockstepIterSize) -> LockstepIterSize { + match self { + LisUnconstrained => other, + LisContradiction(_) => self, + LisConstraint(l_len, ref l_id) => match other { + LisUnconstrained => self.clone(), + LisContradiction(_) => other, + LisConstraint(r_len, _) if l_len == r_len => self.clone(), + LisConstraint(r_len, r_id) => { + LisContradiction(format!("inconsistent lockstep iteration: \ + '{}' has {} items, but '{}' has {}", + l_id, l_len, r_id, r_len)) + } + }, + } + } +} + +fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize { + match *t { + TokenTree::Delimited(_, ref delimed) => { + delimed.tts.iter().fold(LisUnconstrained, |size, tt| { + size + lockstep_iter_size(tt, r) + }) + }, + TokenTree::Sequence(_, ref seq) => { + seq.tts.iter().fold(LisUnconstrained, |size, tt| { + size + lockstep_iter_size(tt, r) + }) + }, + TokenTree::Token(_, SubstNt(name)) | TokenTree::Token(_, MatchNt(name, _)) => + match lookup_cur_matched(r, name) { + Some(matched) => match *matched { + MatchedNonterminal(_) => LisUnconstrained, + MatchedSeq(ref ads, _) => LisConstraint(ads.len(), name), + }, + _ => LisUnconstrained + }, + TokenTree::Token(..) => LisUnconstrained, + } +} + +/// Return the next token from the TtReader. +/// EFFECT: advances the reader's token field +pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { + // FIXME(pcwalton): Bad copy? + let ret_val = TokenAndSpan { + tok: r.cur_tok.clone(), + sp: r.cur_span.clone(), + }; + loop { + let should_pop = match r.stack.last() { + None => { + assert_eq!(ret_val.tok, token::Eof); + return ret_val; + } + Some(frame) => { + if frame.idx < frame.forest.len() { + break; + } + !frame.dotdotdoted || + *r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1 + } + }; + + /* done with this set; pop or repeat? */ + if should_pop { + let prev = r.stack.pop().unwrap(); + match r.stack.last_mut() { + None => { + r.cur_tok = token::Eof; + return ret_val; + } + Some(frame) => { + frame.idx += 1; + } + } + if prev.dotdotdoted { + r.repeat_idx.pop(); + r.repeat_len.pop(); + } + } else { /* repeat */ + *r.repeat_idx.last_mut().unwrap() += 1; + r.stack.last_mut().unwrap().idx = 0; + if let Some(tk) = r.stack.last().unwrap().sep.clone() { + r.cur_tok = tk; // repeat same span, I guess + return ret_val; + } + } + } + loop { /* because it's easiest, this handles `TokenTree::Delimited` not starting + with a `TokenTree::Token`, even though it won't happen */ + let t = { + let frame = r.stack.last().unwrap(); + // FIXME(pcwalton): Bad copy. + frame.forest.get_tt(frame.idx) + }; + match t { + TokenTree::Sequence(sp, seq) => { + // FIXME(pcwalton): Bad copy. + match lockstep_iter_size(&TokenTree::Sequence(sp, seq.clone()), + r) { + LisUnconstrained => { + panic!(r.sp_diag.span_fatal( + sp.clone(), /* blame macro writer */ + "attempted to repeat an expression \ + containing no syntax \ + variables matched as repeating at this depth")); + } + LisContradiction(ref msg) => { + // FIXME #2887 blame macro invoker instead + panic!(r.sp_diag.span_fatal(sp.clone(), &msg[..])); + } + LisConstraint(len, _) => { + if len == 0 { + if seq.op == tokenstream::KleeneOp::OneOrMore { + // FIXME #2887 blame invoker + panic!(r.sp_diag.span_fatal(sp.clone(), + "this must repeat at least once")); + } + + r.stack.last_mut().unwrap().idx += 1; + return tt_next_token(r); + } + r.repeat_len.push(len); + r.repeat_idx.push(0); + r.stack.push(TtFrame { + idx: 0, + dotdotdoted: true, + sep: seq.separator.clone(), + forest: TokenTree::Sequence(sp, seq), + }); + } + } + } + // FIXME #2887: think about span stuff here + TokenTree::Token(sp, SubstNt(ident)) => { + r.stack.last_mut().unwrap().idx += 1; + match lookup_cur_matched(r, ident) { + None => { + r.cur_span = sp; + r.cur_tok = SubstNt(ident); + return ret_val; + // this can't be 0 length, just like TokenTree::Delimited + } + Some(cur_matched) => if let MatchedNonterminal(ref nt) = *cur_matched { + match **nt { + // sidestep the interpolation tricks for ident because + // (a) idents can be in lots of places, so it'd be a pain + // (b) we actually can, since it's a token. + NtIdent(ref sn) => { + r.cur_span = sn.span; + r.cur_tok = token::Ident(sn.node); + return ret_val; + } + _ => { + // FIXME(pcwalton): Bad copy. + r.cur_span = sp; + r.cur_tok = token::Interpolated(nt.clone()); + return ret_val; + } + } + } else { + panic!(r.sp_diag.span_fatal( + sp, /* blame the macro writer */ + &format!("variable '{}' is still repeating at this depth", ident))); + } + } + } + // TokenTree::Delimited or any token that can be unzipped + seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, MatchNt(..)) => { + // do not advance the idx yet + r.stack.push(TtFrame { + forest: seq, + idx: 0, + dotdotdoted: false, + sep: None + }); + // if this could be 0-length, we'd need to potentially recur here + } + TokenTree::Token(sp, tok) => { + r.cur_span = sp; + r.cur_tok = tok; + r.stack.last_mut().unwrap().idx += 1; + return ret_val; + } + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/feature_gate.rs b/bash-5.1/vendor/syntex_syntax/src/feature_gate.rs new file mode 100644 index 0000000..cbc0142 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/feature_gate.rs @@ -0,0 +1,1489 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Feature gating +//! +//! This module implements the gating necessary for preventing certain compiler +//! features from being used by default. This module will crawl a pre-expanded +//! AST to ensure that there are no features which are used that are not +//! enabled. +//! +//! Features are enabled in programs via the crate-level attributes of +//! `#![feature(...)]` with a comma-separated list of features. +//! +//! For the purpose of future feature-tracking, once code for detection of feature +//! gate usage is added, *do not remove it again* even once the feature +//! becomes stable. + +use self::AttributeType::*; +use self::AttributeGate::*; + +use abi::Abi; +use ast::{self, NodeId, PatKind}; +use attr; +use codemap::{CodeMap, Spanned}; +use syntax_pos::Span; +use errors::{DiagnosticBuilder, Handler}; +use visit::{self, FnKind, Visitor}; +use parse::ParseSess; +use symbol::Symbol; + +use std::ascii::AsciiExt; +use std::env; + +macro_rules! setter { + ($field: ident) => {{ + fn f(features: &mut Features) -> &mut bool { + &mut features.$field + } + f as fn(&mut Features) -> &mut bool + }} +} + +macro_rules! declare_features { + ($((active, $feature: ident, $ver: expr, $issue: expr),)+) => { + /// Represents active features that are currently being implemented or + /// currently being considered for addition/removal. + const ACTIVE_FEATURES: &'static [(&'static str, &'static str, + Option<u32>, fn(&mut Features) -> &mut bool)] = &[ + $((stringify!($feature), $ver, $issue, setter!($feature))),+ + ]; + + /// A set of features to be used by later passes. + pub struct Features { + /// #![feature] attrs for stable language features, for error reporting + pub declared_stable_lang_features: Vec<(Symbol, Span)>, + /// #![feature] attrs for non-language (library) features + pub declared_lib_features: Vec<(Symbol, Span)>, + $(pub $feature: bool),+ + } + + impl Features { + pub fn new() -> Features { + Features { + declared_stable_lang_features: Vec::new(), + declared_lib_features: Vec::new(), + $($feature: false),+ + } + } + } + }; + + ($((removed, $feature: ident, $ver: expr, $issue: expr),)+) => { + /// Represents features which has since been removed (it was once Active) + const REMOVED_FEATURES: &'static [(&'static str, &'static str, Option<u32>)] = &[ + $((stringify!($feature), $ver, $issue)),+ + ]; + }; + + ($((accepted, $feature: ident, $ver: expr, $issue: expr),)+) => { + /// Those language feature has since been Accepted (it was once Active) + const ACCEPTED_FEATURES: &'static [(&'static str, &'static str, Option<u32>)] = &[ + $((stringify!($feature), $ver, $issue)),+ + ]; + } +} + +// If you change this list without updating src/doc/reference.md, @cmr will be sad +// Don't ever remove anything from this list; set them to 'Removed'. +// The version numbers here correspond to the version in which the current status +// was set. This is most important for knowing when a particular feature became +// stable (active). +// NB: The featureck.py script parses this information directly out of the source +// so take care when modifying it. + +declare_features! ( + (active, asm, "1.0.0", Some(29722)), + (active, concat_idents, "1.0.0", Some(29599)), + (active, link_args, "1.0.0", Some(29596)), + (active, log_syntax, "1.0.0", Some(29598)), + (active, non_ascii_idents, "1.0.0", Some(28979)), + (active, plugin_registrar, "1.0.0", Some(29597)), + (active, thread_local, "1.0.0", Some(29594)), + (active, trace_macros, "1.0.0", Some(29598)), + + // rustc internal, for now: + (active, intrinsics, "1.0.0", None), + (active, lang_items, "1.0.0", None), + + (active, link_llvm_intrinsics, "1.0.0", Some(29602)), + (active, linkage, "1.0.0", Some(29603)), + (active, quote, "1.0.0", Some(29601)), + (active, simd, "1.0.0", Some(27731)), + + + // rustc internal + (active, rustc_diagnostic_macros, "1.0.0", None), + (active, advanced_slice_patterns, "1.0.0", Some(23121)), + (active, box_syntax, "1.0.0", Some(27779)), + (active, placement_in_syntax, "1.0.0", Some(27779)), + (active, reflect, "1.0.0", Some(27749)), + (active, unboxed_closures, "1.0.0", Some(29625)), + + // rustc internal. + (active, pushpop_unsafe, "1.2.0", None), + + (active, allocator, "1.0.0", Some(27389)), + (active, fundamental, "1.0.0", Some(29635)), + (active, main, "1.0.0", Some(29634)), + (active, needs_allocator, "1.4.0", Some(27389)), + (active, on_unimplemented, "1.0.0", Some(29628)), + (active, plugin, "1.0.0", Some(29597)), + (active, simd_ffi, "1.0.0", Some(27731)), + (active, start, "1.0.0", Some(29633)), + (active, structural_match, "1.8.0", Some(31434)), + (active, panic_runtime, "1.10.0", Some(32837)), + (active, needs_panic_runtime, "1.10.0", Some(32837)), + + // OIBIT specific features + (active, optin_builtin_traits, "1.0.0", Some(13231)), + + // macro reexport needs more discussion and stabilization + (active, macro_reexport, "1.0.0", Some(29638)), + + // Allows use of #[staged_api] + // rustc internal + (active, staged_api, "1.0.0", None), + + // Allows using #![no_core] + (active, no_core, "1.3.0", Some(29639)), + + // Allows using `box` in patterns; RFC 469 + (active, box_patterns, "1.0.0", Some(29641)), + + // Allows using the unsafe_destructor_blind_to_params attribute; + // RFC 1238 + (active, dropck_parametricity, "1.3.0", Some(28498)), + + // Allows using the may_dangle attribute; RFC 1327 + (active, dropck_eyepatch, "1.10.0", Some(34761)), + + // Allows the use of custom attributes; RFC 572 + (active, custom_attribute, "1.0.0", Some(29642)), + + // Allows the use of #[derive(Anything)] as sugar for + // #[derive_Anything]. + (active, custom_derive, "1.0.0", Some(29644)), + + // Allows the use of rustc_* attributes; RFC 572 + (active, rustc_attrs, "1.0.0", Some(29642)), + + // Allows the use of #[allow_internal_unstable]. This is an + // attribute on macro_rules! and can't use the attribute handling + // below (it has to be checked before expansion possibly makes + // macros disappear). + // + // rustc internal + (active, allow_internal_unstable, "1.0.0", None), + + // #23121. Array patterns have some hazards yet. + (active, slice_patterns, "1.0.0", Some(23121)), + + // Allows the definition of associated constants in `trait` or `impl` + // blocks. + (active, associated_consts, "1.0.0", Some(29646)), + + // Allows the definition of `const fn` functions. + (active, const_fn, "1.2.0", Some(24111)), + + // Allows indexing into constant arrays. + (active, const_indexing, "1.4.0", Some(29947)), + + // Allows using #[prelude_import] on glob `use` items. + // + // rustc internal + (active, prelude_import, "1.2.0", None), + + // Allows the definition recursive static items. + (active, static_recursion, "1.3.0", Some(29719)), + + // Allows default type parameters to influence type inference. + (active, default_type_parameter_fallback, "1.3.0", Some(27336)), + + // Allows associated type defaults + (active, associated_type_defaults, "1.2.0", Some(29661)), + + // allow `repr(simd)`, and importing the various simd intrinsics + (active, repr_simd, "1.4.0", Some(27731)), + + // Allows cfg(target_feature = "..."). + (active, cfg_target_feature, "1.4.0", Some(29717)), + + // allow `extern "platform-intrinsic" { ... }` + (active, platform_intrinsics, "1.4.0", Some(27731)), + + // allow `#[unwind]` + // rust runtime internal + (active, unwind_attributes, "1.4.0", None), + + // allow the use of `#[naked]` on functions. + (active, naked_functions, "1.9.0", Some(32408)), + + // allow `#[no_debug]` + (active, no_debug, "1.5.0", Some(29721)), + + // allow `#[omit_gdb_pretty_printer_section]` + // rustc internal. + (active, omit_gdb_pretty_printer_section, "1.5.0", None), + + // Allows cfg(target_vendor = "..."). + (active, cfg_target_vendor, "1.5.0", Some(29718)), + + // Allow attributes on expressions and non-item statements + (active, stmt_expr_attributes, "1.6.0", Some(15701)), + + // allow using type ascription in expressions + (active, type_ascription, "1.6.0", Some(23416)), + + // Allows cfg(target_thread_local) + (active, cfg_target_thread_local, "1.7.0", Some(29594)), + + // rustc internal + (active, abi_vectorcall, "1.7.0", None), + + // a...b and ...b + (active, inclusive_range_syntax, "1.7.0", Some(28237)), + + // impl specialization (RFC 1210) + (active, specialization, "1.7.0", Some(31844)), + + // pub(restricted) visibilities (RFC 1422) + (active, pub_restricted, "1.9.0", Some(32409)), + + // Allow Drop types in statics/const functions (RFC 1440) + (active, drop_types_in_const, "1.9.0", Some(33156)), + + // Allows cfg(target_has_atomic = "..."). + (active, cfg_target_has_atomic, "1.9.0", Some(32976)), + + // Allows `impl Trait` in function return types. + (active, conservative_impl_trait, "1.12.0", Some(34511)), + + // Permits numeric fields in struct expressions and patterns. + (active, relaxed_adts, "1.12.0", Some(35626)), + + // The `!` type + (active, never_type, "1.13.0", Some(35121)), + + // Allows all literals in attribute lists and values of key-value pairs. + (active, attr_literals, "1.13.0", Some(34981)), + + // Allows the sysV64 ABI to be specified on all platforms + // instead of just the platforms on which it is the C ABI + (active, abi_sysv64, "1.13.0", Some(36167)), + + // Allows untagged unions `union U { ... }` + (active, untagged_unions, "1.13.0", Some(32836)), + + // elide `'static` lifetimes in `static`s and `const`s + (active, static_in_const, "1.13.0", Some(35897)), + + // Used to identify the `compiler_builtins` crate + // rustc internal + (active, compiler_builtins, "1.13.0", None), + + // Allows attributes on lifetime/type formal parameters in generics (RFC 1327) + (active, generic_param_attrs, "1.11.0", Some(34761)), + + // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions. + (active, field_init_shorthand, "1.14.0", Some(37340)), + + // The #![windows_subsystem] attribute + (active, windows_subsystem, "1.14.0", Some(37499)), + + // Allows using `Self` and associated types in struct expressions and patterns. + (active, more_struct_aliases, "1.14.0", Some(37544)), + + + // Allows #[link(..., cfg(..))] + (active, link_cfg, "1.14.0", Some(37406)), + + (active, use_extern_macros, "1.15.0", Some(35896)), + + // Allows `break {expr}` with a value inside `loop`s. + (active, loop_break_value, "1.14.0", Some(37339)), + + // Allows #[target_feature(...)] + (active, target_feature, "1.15.0", None), + + // Allow safe suggestions for potential type conversions. + (active, safe_suggestion, "1.0.0", Some(37384)), + + // `extern "ptx-*" fn()` + (active, abi_ptx, "1.15.0", None), + + // The `i128` type + (active, i128_type, "1.16.0", Some(35118)), + + // The `unadjusted` ABI. Perma unstable. + (active, abi_unadjusted, "1.16.0", None), +); + +declare_features! ( + (removed, import_shadowing, "1.0.0", None), + (removed, managed_boxes, "1.0.0", None), + // Allows use of unary negate on unsigned integers, e.g. -e for e: u8 + (removed, negate_unsigned, "1.0.0", Some(29645)), + // A way to temporarily opt out of opt in copy. This will *never* be accepted. + (removed, opt_out_copy, "1.0.0", None), + (removed, quad_precision_float, "1.0.0", None), + (removed, struct_inherit, "1.0.0", None), + (removed, test_removed_feature, "1.0.0", None), + (removed, visible_private_types, "1.0.0", None), + (removed, unsafe_no_drop_flag, "1.0.0", None), + // Allows using items which are missing stability attributes + // rustc internal + (removed, unmarked_api, "1.0.0", None), +); + +declare_features! ( + (accepted, associated_types, "1.0.0", None), + // allow overloading augmented assignment operations like `a += b` + (accepted, augmented_assignments, "1.8.0", Some(28235)), + // allow empty structs and enum variants with braces + (accepted, braced_empty_structs, "1.8.0", Some(29720)), + (accepted, default_type_params, "1.0.0", None), + (accepted, globs, "1.0.0", None), + (accepted, if_let, "1.0.0", None), + // A temporary feature gate used to enable parser extensions needed + // to bootstrap fix for #5723. + (accepted, issue_5723_bootstrap, "1.0.0", None), + (accepted, macro_rules, "1.0.0", None), + // Allows using #![no_std] + (accepted, no_std, "1.6.0", None), + (accepted, slicing_syntax, "1.0.0", None), + (accepted, struct_variant, "1.0.0", None), + // These are used to test this portion of the compiler, they don't actually + // mean anything + (accepted, test_accepted_feature, "1.0.0", None), + (accepted, tuple_indexing, "1.0.0", None), + // Allows macros to appear in the type position. + (accepted, type_macros, "1.13.0", Some(27245)), + (accepted, while_let, "1.0.0", None), + // Allows `#[deprecated]` attribute + (accepted, deprecated, "1.9.0", Some(29935)), + // `expr?` + (accepted, question_mark, "1.13.0", Some(31436)), + // Allows `..` in tuple (struct) patterns + (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627)), + (accepted, item_like_imports, "1.14.0", Some(35120)), + // Macros 1.1 + (accepted, proc_macro, "1.15.0", Some(35900)), +); +// (changing above list without updating src/doc/reference.md makes @cmr sad) + +#[derive(PartialEq, Copy, Clone, Debug)] +pub enum AttributeType { + /// Normal, builtin attribute that is consumed + /// by the compiler before the unused_attribute check + Normal, + + /// Builtin attribute that may not be consumed by the compiler + /// before the unused_attribute check. These attributes + /// will be ignored by the unused_attribute lint + Whitelisted, + + /// Builtin attribute that is only allowed at the crate level + CrateLevel, +} + +pub enum AttributeGate { + /// Is gated by a given feature gate, reason + /// and function to check if enabled + Gated(Stability, &'static str, &'static str, fn(&Features) -> bool), + + /// Ungated attribute, can be used on all release channels + Ungated, +} + +impl AttributeGate { + fn is_deprecated(&self) -> bool { + match *self { + Gated(Stability::Deprecated(_), _, _, _) => true, + _ => false, + } + } +} + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum Stability { + Unstable, + // Argument is tracking issue link. + Deprecated(&'static str), +} + +// fn() is not Debug +impl ::std::fmt::Debug for AttributeGate { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + Gated(ref stab, ref name, ref expl, _) => + write!(fmt, "Gated({:?}, {}, {})", stab, name, expl), + Ungated => write!(fmt, "Ungated") + } + } +} + +macro_rules! cfg_fn { + ($field: ident) => {{ + fn f(features: &Features) -> bool { + features.$field + } + f as fn(&Features) -> bool + }} +} + +pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType, AttributeGate)> { + BUILTIN_ATTRIBUTES.iter().filter(|a| a.2.is_deprecated()).collect() +} + +// Attributes that have a special meaning to rustc or rustdoc +pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeGate)] = &[ + // Normal attributes + + ("warn", Normal, Ungated), + ("allow", Normal, Ungated), + ("forbid", Normal, Ungated), + ("deny", Normal, Ungated), + + ("macro_reexport", Normal, Ungated), + ("macro_use", Normal, Ungated), + ("macro_export", Normal, Ungated), + ("plugin_registrar", Normal, Ungated), + + ("cfg", Normal, Ungated), + ("cfg_attr", Normal, Ungated), + ("main", Normal, Ungated), + ("start", Normal, Ungated), + ("test", Normal, Ungated), + ("bench", Normal, Ungated), + ("simd", Normal, Ungated), + ("repr", Normal, Ungated), + ("path", Normal, Ungated), + ("abi", Normal, Ungated), + ("automatically_derived", Normal, Ungated), + ("no_mangle", Normal, Ungated), + ("no_link", Normal, Ungated), + ("derive", Normal, Ungated), + ("should_panic", Normal, Ungated), + ("ignore", Normal, Ungated), + ("no_implicit_prelude", Normal, Ungated), + ("reexport_test_harness_main", Normal, Ungated), + ("link_args", Normal, Ungated), + ("macro_escape", Normal, Ungated), + + // RFC #1445. + ("structural_match", Whitelisted, Gated(Stability::Unstable, + "structural_match", + "the semantics of constant patterns is \ + not yet settled", + cfg_fn!(structural_match))), + + // Not used any more, but we can't feature gate it + ("no_stack_check", Normal, Ungated), + + ("plugin", CrateLevel, Gated(Stability::Unstable, + "plugin", + "compiler plugins are experimental \ + and possibly buggy", + cfg_fn!(plugin))), + + ("no_std", CrateLevel, Ungated), + ("no_core", CrateLevel, Gated(Stability::Unstable, + "no_core", + "no_core is experimental", + cfg_fn!(no_core))), + ("lang", Normal, Gated(Stability::Unstable, + "lang_items", + "language items are subject to change", + cfg_fn!(lang_items))), + ("linkage", Whitelisted, Gated(Stability::Unstable, + "linkage", + "the `linkage` attribute is experimental \ + and not portable across platforms", + cfg_fn!(linkage))), + ("thread_local", Whitelisted, Gated(Stability::Unstable, + "thread_local", + "`#[thread_local]` is an experimental feature, and does \ + not currently handle destructors. There is no \ + corresponding `#[task_local]` mapping to the task \ + model", + cfg_fn!(thread_local))), + + ("rustc_on_unimplemented", Normal, Gated(Stability::Unstable, + "on_unimplemented", + "the `#[rustc_on_unimplemented]` attribute \ + is an experimental feature", + cfg_fn!(on_unimplemented))), + ("allocator", Whitelisted, Gated(Stability::Unstable, + "allocator", + "the `#[allocator]` attribute is an experimental feature", + cfg_fn!(allocator))), + ("needs_allocator", Normal, Gated(Stability::Unstable, + "needs_allocator", + "the `#[needs_allocator]` \ + attribute is an experimental \ + feature", + cfg_fn!(needs_allocator))), + ("panic_runtime", Whitelisted, Gated(Stability::Unstable, + "panic_runtime", + "the `#[panic_runtime]` attribute is \ + an experimental feature", + cfg_fn!(panic_runtime))), + ("needs_panic_runtime", Whitelisted, Gated(Stability::Unstable, + "needs_panic_runtime", + "the `#[needs_panic_runtime]` \ + attribute is an experimental \ + feature", + cfg_fn!(needs_panic_runtime))), + ("rustc_variance", Normal, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_variance]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_error", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_error]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_if_this_changed", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_if_this_changed]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_then_this_would_need", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_if_this_changed]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_dirty", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_dirty]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_clean", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_clean]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_metadata_dirty", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_metadata_dirty]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_metadata_clean", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_metadata_clean]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_partition_reused", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "this attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_partition_translated", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "this attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_symbol_name", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "internal rustc attributes will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_item_path", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "internal rustc attributes will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_move_fragments", Normal, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_move_fragments]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_mir", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_mir]` attribute \ + is just used for rustc unit tests \ + and will never be stable", + cfg_fn!(rustc_attrs))), + ("rustc_inherit_overflow_checks", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "the `#[rustc_inherit_overflow_checks]` \ + attribute is just used to control \ + overflow checking behavior of several \ + libcore functions that are inlined \ + across crates and will never be stable", + cfg_fn!(rustc_attrs))), + ("compiler_builtins", Whitelisted, Gated(Stability::Unstable, + "compiler_builtins", + "the `#[compiler_builtins]` attribute is used to \ + identify the `compiler_builtins` crate which \ + contains compiler-rt intrinsics and will never be \ + stable", + cfg_fn!(compiler_builtins))), + + ("allow_internal_unstable", Normal, Gated(Stability::Unstable, + "allow_internal_unstable", + EXPLAIN_ALLOW_INTERNAL_UNSTABLE, + cfg_fn!(allow_internal_unstable))), + + ("fundamental", Whitelisted, Gated(Stability::Unstable, + "fundamental", + "the `#[fundamental]` attribute \ + is an experimental feature", + cfg_fn!(fundamental))), + + ("proc_macro_derive", Normal, Ungated), + + ("rustc_copy_clone_marker", Whitelisted, Gated(Stability::Unstable, + "rustc_attrs", + "internal implementation detail", + cfg_fn!(rustc_attrs))), + + // FIXME: #14408 whitelist docs since rustdoc looks at them + ("doc", Whitelisted, Ungated), + + // FIXME: #14406 these are processed in trans, which happens after the + // lint pass + ("cold", Whitelisted, Ungated), + ("naked", Whitelisted, Gated(Stability::Unstable, + "naked_functions", + "the `#[naked]` attribute \ + is an experimental feature", + cfg_fn!(naked_functions))), + ("target_feature", Whitelisted, Gated( + Stability::Unstable, "target_feature", + "the `#[target_feature]` attribute is an experimental feature", + cfg_fn!(target_feature))), + ("export_name", Whitelisted, Ungated), + ("inline", Whitelisted, Ungated), + ("link", Whitelisted, Ungated), + ("link_name", Whitelisted, Ungated), + ("link_section", Whitelisted, Ungated), + ("no_builtins", Whitelisted, Ungated), + ("no_mangle", Whitelisted, Ungated), + ("no_debug", Whitelisted, Gated( + Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721"), + "no_debug", + "the `#[no_debug]` attribute is an experimental feature", + cfg_fn!(no_debug))), + ("omit_gdb_pretty_printer_section", Whitelisted, Gated(Stability::Unstable, + "omit_gdb_pretty_printer_section", + "the `#[omit_gdb_pretty_printer_section]` \ + attribute is just used for the Rust test \ + suite", + cfg_fn!(omit_gdb_pretty_printer_section))), + ("unsafe_destructor_blind_to_params", + Normal, + Gated(Stability::Unstable, + "dropck_parametricity", + "unsafe_destructor_blind_to_params has unstable semantics \ + and may be removed in the future", + cfg_fn!(dropck_parametricity))), + ("may_dangle", + Normal, + Gated(Stability::Unstable, + "dropck_eyepatch", + "may_dangle has unstable semantics and may be removed in the future", + cfg_fn!(dropck_eyepatch))), + ("unwind", Whitelisted, Gated(Stability::Unstable, + "unwind_attributes", + "#[unwind] is experimental", + cfg_fn!(unwind_attributes))), + + // used in resolve + ("prelude_import", Whitelisted, Gated(Stability::Unstable, + "prelude_import", + "`#[prelude_import]` is for use by rustc only", + cfg_fn!(prelude_import))), + + // FIXME: #14407 these are only looked at on-demand so we can't + // guarantee they'll have already been checked + ("rustc_deprecated", Whitelisted, Ungated), + ("must_use", Whitelisted, Ungated), + ("stable", Whitelisted, Ungated), + ("unstable", Whitelisted, Ungated), + ("deprecated", Normal, Ungated), + + ("rustc_paren_sugar", Normal, Gated(Stability::Unstable, + "unboxed_closures", + "unboxed_closures are still evolving", + cfg_fn!(unboxed_closures))), + ("rustc_reflect_like", Whitelisted, Gated(Stability::Unstable, + "reflect", + "defining reflective traits is still evolving", + cfg_fn!(reflect))), + + ("windows_subsystem", Whitelisted, Gated(Stability::Unstable, + "windows_subsystem", + "the windows subsystem attribute \ + is currently unstable", + cfg_fn!(windows_subsystem))), + + // Crate level attributes + ("crate_name", CrateLevel, Ungated), + ("crate_type", CrateLevel, Ungated), + ("crate_id", CrateLevel, Ungated), + ("feature", CrateLevel, Ungated), + ("no_start", CrateLevel, Ungated), + ("no_main", CrateLevel, Ungated), + ("no_builtins", CrateLevel, Ungated), + ("recursion_limit", CrateLevel, Ungated), + ("type_length_limit", CrateLevel, Ungated), +]; + +// cfg(...)'s that are feature gated +const GATED_CFGS: &'static [(&'static str, &'static str, fn(&Features) -> bool)] = &[ + // (name in cfg, feature, function to check if the feature is enabled) + ("target_feature", "cfg_target_feature", cfg_fn!(cfg_target_feature)), + ("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)), + ("target_thread_local", "cfg_target_thread_local", cfg_fn!(cfg_target_thread_local)), + ("target_has_atomic", "cfg_target_has_atomic", cfg_fn!(cfg_target_has_atomic)), +]; + +#[derive(Debug, Eq, PartialEq)] +pub struct GatedCfg { + span: Span, + index: usize, +} + +impl GatedCfg { + pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> { + let name = &*cfg.name().as_str(); + GATED_CFGS.iter() + .position(|info| info.0 == name) + .map(|idx| { + GatedCfg { + span: cfg.span, + index: idx + } + }) + } + + pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) { + let (cfg, feature, has_feature) = GATED_CFGS[self.index]; + if !has_feature(features) && !sess.codemap().span_allows_unstable(self.span) { + let explain = format!("`cfg({})` is experimental and subject to change", cfg); + emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain); + } + } +} + +struct Context<'a> { + features: &'a Features, + parse_sess: &'a ParseSess, + cm: &'a CodeMap, + plugin_attributes: &'a [(String, AttributeType)], +} + +macro_rules! gate_feature_fn { + ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{ + let (cx, has_feature, span, name, explain) = ($cx, $has_feature, $span, $name, $explain); + let has_feature: bool = has_feature(&$cx.features); + debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature); + if !has_feature && !cx.cm.span_allows_unstable(span) { + emit_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain); + } + }} +} + +macro_rules! gate_feature { + ($cx: expr, $feature: ident, $span: expr, $explain: expr) => { + gate_feature_fn!($cx, |x:&Features| x.$feature, $span, stringify!($feature), $explain) + } +} + +impl<'a> Context<'a> { + fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) { + debug!("check_attribute(attr = {:?})", attr); + let name = &*attr.name().as_str(); + for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES { + if n == name { + if let &Gated(_, ref name, ref desc, ref has_feature) = gateage { + gate_feature_fn!(self, has_feature, attr.span, name, desc); + } + debug!("check_attribute: {:?} is builtin, {:?}, {:?}", name, ty, gateage); + return; + } + } + for &(ref n, ref ty) in self.plugin_attributes { + if n == name { + // Plugins can't gate attributes, so we don't check for it + // unlike the code above; we only use this loop to + // short-circuit to avoid the checks below + debug!("check_attribute: {:?} is registered by a plugin, {:?}", name, ty); + return; + } + } + if name.starts_with("rustc_") { + gate_feature!(self, rustc_attrs, attr.span, + "unless otherwise specified, attributes \ + with the prefix `rustc_` \ + are reserved for internal compiler diagnostics"); + } else if name.starts_with("derive_") { + gate_feature!(self, custom_derive, attr.span, EXPLAIN_DERIVE_UNDERSCORE); + } else if attr::is_known(attr) { + debug!("check_attribute: {:?} is known", name); + } else { + // Only run the custom attribute lint during regular + // feature gate checking. Macro gating runs + // before the plugin attributes are registered + // so we skip this then + if !is_macro { + gate_feature!(self, custom_attribute, attr.span, + &format!("The attribute `{}` is currently \ + unknown to the compiler and \ + may have meaning \ + added to it in the future", + name)); + } + } + } +} + +pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, + cm: &CodeMap, features: &Features) { + let cx = Context { + features: features, parse_sess: parse_sess, + cm: cm, plugin_attributes: &[] + }; + cx.check_attribute(attr, true); +} + +pub fn find_lang_feature_accepted_version(feature: &str) -> Option<&'static str> { + ACCEPTED_FEATURES.iter().find(|t| t.0 == feature).map(|t| t.1) +} + +fn find_lang_feature_issue(feature: &str) -> Option<u32> { + if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) { + let issue = info.2; + // FIXME (#28244): enforce that active features have issue numbers + // assert!(issue.is_some()) + issue + } else { + // search in Accepted or Removed features + ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES.iter()) + .find(|t| t.0 == feature) + .unwrap().2 + } +} + +pub enum GateIssue { + Language, + Library(Option<u32>) +} + +pub fn emit_feature_err(sess: &ParseSess, feature: &str, span: Span, issue: GateIssue, + explain: &str) { + feature_err(sess, feature, span, issue, explain).emit(); +} + +pub fn feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue, + explain: &str) -> DiagnosticBuilder<'a> { + let diag = &sess.span_diagnostic; + + let issue = match issue { + GateIssue::Language => find_lang_feature_issue(feature), + GateIssue::Library(lib) => lib, + }; + + let mut err = if let Some(n) = issue { + diag.struct_span_err(span, &format!("{} (see issue #{})", explain, n)) + } else { + diag.struct_span_err(span, explain) + }; + + // #23973: do not suggest `#![feature(...)]` if we are in beta/stable + if sess.unstable_features.is_nightly_build() { + err.help(&format!("add #![feature({})] to the \ + crate attributes to enable", + feature)); + } + + err +} + +const EXPLAIN_BOX_SYNTAX: &'static str = + "box expression syntax is experimental; you can call `Box::new` instead."; + +pub const EXPLAIN_STMT_ATTR_SYNTAX: &'static str = + "attributes on non-item statements and expressions are experimental."; + +pub const EXPLAIN_ASM: &'static str = + "inline assembly is not stable enough for use and is subject to change"; + +pub const EXPLAIN_LOG_SYNTAX: &'static str = + "`log_syntax!` is not stable enough for use and is subject to change"; + +pub const EXPLAIN_CONCAT_IDENTS: &'static str = + "`concat_idents` is not stable enough for use and is subject to change"; + +pub const EXPLAIN_TRACE_MACROS: &'static str = + "`trace_macros` is not stable enough for use and is subject to change"; +pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str = + "allow_internal_unstable side-steps feature gating and stability checks"; + +pub const EXPLAIN_CUSTOM_DERIVE: &'static str = + "`#[derive]` for custom traits is not stable enough for use. It is deprecated and will \ + be removed in v1.15"; + +pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &'static str = + "`#[derive]` for custom traits is deprecated and will be removed in v1.15. Prefer using \ + procedural macro custom derive"; + +pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = + "attributes of the form `#[derive_*]` are reserved for the compiler"; + +pub const EXPLAIN_PLACEMENT_IN: &'static str = + "placement-in expression syntax is experimental and subject to change."; + +struct PostExpansionVisitor<'a> { + context: &'a Context<'a>, +} + +macro_rules! gate_feature_post { + ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{ + let (cx, span) = ($cx, $span); + if !cx.context.cm.span_allows_unstable(span) { + gate_feature!(cx.context, $feature, span, $explain) + } + }} +} + +impl<'a> PostExpansionVisitor<'a> { + fn check_abi(&self, abi: Abi, span: Span) { + match abi { + Abi::RustIntrinsic => { + gate_feature_post!(&self, intrinsics, span, + "intrinsics are subject to change"); + }, + Abi::PlatformIntrinsic => { + gate_feature_post!(&self, platform_intrinsics, span, + "platform intrinsics are experimental and possibly buggy"); + }, + Abi::Vectorcall => { + gate_feature_post!(&self, abi_vectorcall, span, + "vectorcall is experimental and subject to change"); + }, + Abi::RustCall => { + gate_feature_post!(&self, unboxed_closures, span, + "rust-call ABI is subject to change"); + }, + Abi::SysV64 => { + gate_feature_post!(&self, abi_sysv64, span, + "sysv64 ABI is experimental and subject to change"); + }, + Abi::PtxKernel => { + gate_feature_post!(&self, abi_ptx, span, + "PTX ABIs are experimental and subject to change"); + }, + Abi::Unadjusted => { + gate_feature_post!(&self, abi_unadjusted, span, + "unadjusted ABI is an implementation detail and perma-unstable"); + }, + // Stable + Abi::Cdecl | + Abi::Stdcall | + Abi::Fastcall | + Abi::Aapcs | + Abi::Win64 | + Abi::Rust | + Abi::C | + Abi::System => {} + } + } +} + +fn contains_novel_literal(item: &ast::MetaItem) -> bool { + use ast::MetaItemKind::*; + use ast::NestedMetaItemKind::*; + + match item.node { + Word => false, + NameValue(ref lit) => !lit.node.is_str(), + List(ref list) => list.iter().any(|li| { + match li.node { + MetaItem(ref mi) => contains_novel_literal(&mi), + Literal(_) => true, + } + }), + } +} + +fn starts_with_digit(s: &str) -> bool { + s.as_bytes().first().cloned().map_or(false, |b| b >= b'0' && b <= b'9') +} + +impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { + fn visit_attribute(&mut self, attr: &ast::Attribute) { + if !self.context.cm.span_allows_unstable(attr.span) { + // check for gated attributes + self.context.check_attribute(attr, false); + } + + if contains_novel_literal(&attr.value) { + gate_feature_post!(&self, attr_literals, attr.span, + "non-string literals in attributes, or string \ + literals in top-level positions, are experimental"); + } + } + + fn visit_name(&mut self, sp: Span, name: ast::Name) { + if !name.as_str().is_ascii() { + gate_feature_post!(&self, non_ascii_idents, sp, + "non-ascii idents are not fully supported."); + } + } + + fn visit_item(&mut self, i: &'a ast::Item) { + match i.node { + ast::ItemKind::ExternCrate(_) => { + if attr::contains_name(&i.attrs[..], "macro_reexport") { + gate_feature_post!(&self, macro_reexport, i.span, + "macros reexports are experimental \ + and possibly buggy"); + } + } + + ast::ItemKind::ForeignMod(ref foreign_module) => { + if attr::contains_name(&i.attrs[..], "link_args") { + gate_feature_post!(&self, link_args, i.span, + "the `link_args` attribute is not portable \ + across platforms, it is recommended to \ + use `#[link(name = \"foo\")]` instead") + } + self.check_abi(foreign_module.abi, i.span); + } + + ast::ItemKind::Fn(..) => { + if attr::contains_name(&i.attrs[..], "plugin_registrar") { + gate_feature_post!(&self, plugin_registrar, i.span, + "compiler plugins are experimental and possibly buggy"); + } + if attr::contains_name(&i.attrs[..], "start") { + gate_feature_post!(&self, start, i.span, + "a #[start] function is an experimental \ + feature whose signature may change \ + over time"); + } + if attr::contains_name(&i.attrs[..], "main") { + gate_feature_post!(&self, main, i.span, + "declaration of a nonstandard #[main] \ + function may change over time, for now \ + a top-level `fn main()` is required"); + } + } + + ast::ItemKind::Struct(..) => { + if attr::contains_name(&i.attrs[..], "simd") { + gate_feature_post!(&self, simd, i.span, + "SIMD types are experimental and possibly buggy"); + self.context.parse_sess.span_diagnostic.span_warn(i.span, + "the `#[simd]` attribute \ + is deprecated, use \ + `#[repr(simd)]` instead"); + } + for attr in &i.attrs { + if attr.name() == "repr" { + for item in attr.meta_item_list().unwrap_or(&[]) { + if item.check_name("simd") { + gate_feature_post!(&self, repr_simd, i.span, + "SIMD types are experimental \ + and possibly buggy"); + + } + } + } + } + } + + ast::ItemKind::Union(..) => { + gate_feature_post!(&self, untagged_unions, + i.span, + "unions are unstable and possibly buggy"); + } + + ast::ItemKind::DefaultImpl(..) => { + gate_feature_post!(&self, optin_builtin_traits, + i.span, + "default trait implementations are experimental \ + and possibly buggy"); + } + + ast::ItemKind::Impl(_, polarity, _, _, _, _) => { + match polarity { + ast::ImplPolarity::Negative => { + gate_feature_post!(&self, optin_builtin_traits, + i.span, + "negative trait bounds are not yet fully implemented; \ + use marker types for now"); + }, + _ => {} + } + } + + _ => {} + } + + visit::walk_item(self, i); + } + + fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) { + let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs, "link_name") { + Some(val) => val.as_str().starts_with("llvm."), + _ => false + }; + if links_to_llvm { + gate_feature_post!(&self, link_llvm_intrinsics, i.span, + "linking to LLVM intrinsics is experimental"); + } + + visit::walk_foreign_item(self, i) + } + + fn visit_ty(&mut self, ty: &'a ast::Ty) { + match ty.node { + ast::TyKind::BareFn(ref bare_fn_ty) => { + self.check_abi(bare_fn_ty.abi, ty.span); + } + ast::TyKind::ImplTrait(..) => { + gate_feature_post!(&self, conservative_impl_trait, ty.span, + "`impl Trait` is experimental"); + } + ast::TyKind::Never => { + gate_feature_post!(&self, never_type, ty.span, + "The `!` type is experimental"); + }, + _ => {} + } + visit::walk_ty(self, ty) + } + + fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) { + if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty { + match output_ty.node { + ast::TyKind::Never => return, + _ => (), + }; + self.visit_ty(output_ty) + } + } + + fn visit_expr(&mut self, e: &'a ast::Expr) { + match e.node { + ast::ExprKind::Box(_) => { + gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX); + } + ast::ExprKind::Type(..) => { + gate_feature_post!(&self, type_ascription, e.span, + "type ascription is experimental"); + } + ast::ExprKind::Range(_, _, ast::RangeLimits::Closed) => { + gate_feature_post!(&self, inclusive_range_syntax, + e.span, + "inclusive range syntax is experimental"); + } + ast::ExprKind::InPlace(..) => { + gate_feature_post!(&self, placement_in_syntax, e.span, EXPLAIN_PLACEMENT_IN); + } + ast::ExprKind::Struct(_, ref fields, _) => { + for field in fields { + if field.is_shorthand { + gate_feature_post!(&self, field_init_shorthand, field.span, + "struct field shorthands are unstable"); + } + if starts_with_digit(&field.ident.node.name.as_str()) { + gate_feature_post!(&self, relaxed_adts, + field.span, + "numeric fields in struct expressions are unstable"); + } + } + } + ast::ExprKind::Break(_, Some(_)) => { + gate_feature_post!(&self, loop_break_value, e.span, + "`break` with a value is experimental"); + } + ast::ExprKind::Lit(ref lit) => { + if let ast::LitKind::Int(_, ref ty) = lit.node { + match *ty { + ast::LitIntType::Signed(ast::IntTy::I128) | + ast::LitIntType::Unsigned(ast::UintTy::U128) => { + gate_feature_post!(&self, i128_type, e.span, + "128-bit integers are not stable"); + } + _ => {} + } + } + } + _ => {} + } + visit::walk_expr(self, e); + } + + fn visit_pat(&mut self, pattern: &'a ast::Pat) { + match pattern.node { + PatKind::Slice(_, Some(_), ref last) if !last.is_empty() => { + gate_feature_post!(&self, advanced_slice_patterns, + pattern.span, + "multiple-element slice matches anywhere \ + but at the end of a slice (e.g. \ + `[0, ..xs, 0]`) are experimental") + } + PatKind::Slice(..) => { + gate_feature_post!(&self, slice_patterns, + pattern.span, + "slice pattern syntax is experimental"); + } + PatKind::Box(..) => { + gate_feature_post!(&self, box_patterns, + pattern.span, + "box pattern syntax is experimental"); + } + PatKind::Struct(_, ref fields, _) => { + for field in fields { + if starts_with_digit(&field.node.ident.name.as_str()) { + gate_feature_post!(&self, relaxed_adts, + field.span, + "numeric fields in struct patterns are unstable"); + } + } + } + _ => {} + } + visit::walk_pat(self, pattern) + } + + fn visit_fn(&mut self, + fn_kind: FnKind<'a>, + fn_decl: &'a ast::FnDecl, + span: Span, + _node_id: NodeId) { + // check for const fn declarations + match fn_kind { + FnKind::ItemFn(_, _, _, Spanned { node: ast::Constness::Const, .. }, _, _, _) => { + gate_feature_post!(&self, const_fn, span, "const fn is unstable"); + } + _ => { + // stability of const fn methods are covered in + // visit_trait_item and visit_impl_item below; this is + // because default methods don't pass through this + // point. + } + } + + match fn_kind { + FnKind::ItemFn(_, _, _, _, abi, _, _) | + FnKind::Method(_, &ast::MethodSig { abi, .. }, _, _) => { + self.check_abi(abi, span); + } + _ => {} + } + visit::walk_fn(self, fn_kind, fn_decl, span); + } + + fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) { + match ti.node { + ast::TraitItemKind::Const(..) => { + gate_feature_post!(&self, associated_consts, + ti.span, + "associated constants are experimental") + } + ast::TraitItemKind::Method(ref sig, ref block) => { + if block.is_none() { + self.check_abi(sig.abi, ti.span); + } + if sig.constness.node == ast::Constness::Const { + gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable"); + } + } + ast::TraitItemKind::Type(_, Some(_)) => { + gate_feature_post!(&self, associated_type_defaults, ti.span, + "associated type defaults are unstable"); + } + _ => {} + } + visit::walk_trait_item(self, ti); + } + + fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) { + if ii.defaultness == ast::Defaultness::Default { + gate_feature_post!(&self, specialization, + ii.span, + "specialization is unstable"); + } + + match ii.node { + ast::ImplItemKind::Const(..) => { + gate_feature_post!(&self, associated_consts, + ii.span, + "associated constants are experimental") + } + ast::ImplItemKind::Method(ref sig, _) => { + if sig.constness.node == ast::Constness::Const { + gate_feature_post!(&self, const_fn, ii.span, "const fn is unstable"); + } + } + _ => {} + } + visit::walk_impl_item(self, ii); + } + + fn visit_vis(&mut self, vis: &'a ast::Visibility) { + let span = match *vis { + ast::Visibility::Crate(span) => span, + ast::Visibility::Restricted { ref path, .. } => path.span, + _ => return, + }; + gate_feature_post!(&self, pub_restricted, span, "`pub(restricted)` syntax is experimental"); + + visit::walk_vis(self, vis) + } + + fn visit_generics(&mut self, g: &'a ast::Generics) { + for t in &g.ty_params { + if !t.attrs.is_empty() { + gate_feature_post!(&self, generic_param_attrs, t.attrs[0].span, + "attributes on type parameter bindings are experimental"); + } + } + visit::walk_generics(self, g) + } + + fn visit_lifetime_def(&mut self, lifetime_def: &'a ast::LifetimeDef) { + if !lifetime_def.attrs.is_empty() { + gate_feature_post!(&self, generic_param_attrs, lifetime_def.attrs[0].span, + "attributes on lifetime bindings are experimental"); + } + visit::walk_lifetime_def(self, lifetime_def) + } +} + +pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute]) -> Features { + let mut features = Features::new(); + + for attr in krate_attrs { + if !attr.check_name("feature") { + continue + } + + match attr.meta_item_list() { + None => { + span_err!(span_handler, attr.span, E0555, + "malformed feature attribute, expected #![feature(...)]"); + } + Some(list) => { + for mi in list { + let name = if let Some(word) = mi.word() { + word.name() + } else { + span_err!(span_handler, mi.span, E0556, + "malformed feature, expected just one word"); + continue + }; + + if let Some(&(_, _, _, setter)) = ACTIVE_FEATURES.iter() + .find(|& &(n, _, _, _)| name == n) { + *(setter(&mut features)) = true; + } + else if let Some(&(_, _, _)) = REMOVED_FEATURES.iter() + .find(|& &(n, _, _)| name == n) { + span_err!(span_handler, mi.span, E0557, "feature has been removed"); + } + else if let Some(&(_, _, _)) = ACCEPTED_FEATURES.iter() + .find(|& &(n, _, _)| name == n) { + features.declared_stable_lang_features.push((name, mi.span)); + } else { + features.declared_lib_features.push((name, mi.span)); + } + } + } + } + } + + features +} + +pub fn check_crate(krate: &ast::Crate, + sess: &ParseSess, + features: &Features, + plugin_attributes: &[(String, AttributeType)], + unstable: UnstableFeatures) { + maybe_stage_features(&sess.span_diagnostic, krate, unstable); + let ctx = Context { + features: features, + parse_sess: sess, + cm: sess.codemap(), + plugin_attributes: plugin_attributes, + }; + visit::walk_crate(&mut PostExpansionVisitor { context: &ctx }, krate); +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub enum UnstableFeatures { + /// Hard errors for unstable features are active, as on + /// beta/stable channels. + Disallow, + /// Allow features to be activated, as on nightly. + Allow, + /// Errors are bypassed for bootstrapping. This is required any time + /// during the build that feature-related lints are set to warn or above + /// because the build turns on warnings-as-errors and uses lots of unstable + /// features. As a result, this is always required for building Rust itself. + Cheat +} + +impl UnstableFeatures { + pub fn from_environment() -> UnstableFeatures { + // Whether this is a feature-staged build, i.e. on the beta or stable channel + let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); + // Whether we should enable unstable features for bootstrapping + let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok(); + match (disable_unstable_features, bootstrap) { + (_, true) => UnstableFeatures::Cheat, + (true, _) => UnstableFeatures::Disallow, + (false, _) => UnstableFeatures::Allow + } + } + + pub fn is_nightly_build(&self) -> bool { + match *self { + UnstableFeatures::Allow | UnstableFeatures::Cheat => true, + _ => false, + } + } +} + +fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, + unstable: UnstableFeatures) { + let allow_features = match unstable { + UnstableFeatures::Allow => true, + UnstableFeatures::Disallow => false, + UnstableFeatures::Cheat => true + }; + if !allow_features { + for attr in &krate.attrs { + if attr.check_name("feature") { + let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"); + span_err!(span_handler, attr.span, E0554, + "#[feature] may not be used on the {} release channel", + release_channel); + } + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/fold.rs b/bash-5.1/vendor/syntex_syntax/src/fold.rs new file mode 100644 index 0000000..9797e00 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/fold.rs @@ -0,0 +1,1399 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A Folder represents an AST->AST fold; it accepts an AST piece, +//! and returns a piece of the same type. So, for instance, macro +//! expansion is a Folder that walks over an AST and produces another +//! AST. +//! +//! Note: using a Folder (other than the MacroExpander Folder) on +//! an AST before macro expansion is probably a bad idea. For instance, +//! a folder renaming item names in a module will miss all of those +//! that are created by the expansion of a macro. + +use ast::*; +use ast; +use syntax_pos::Span; +use codemap::{Spanned, respan}; +use parse::token; +use ptr::P; +use symbol::keywords; +use tokenstream::*; +use util::small_vector::SmallVector; +use util::move_map::MoveMap; + +use std::rc::Rc; + +pub trait Folder : Sized { + // Any additions to this trait should happen in form + // of a call to a public `noop_*` function that only calls + // out to the folder again, not other `noop_*` functions. + // + // This is a necessary API workaround to the problem of not + // being able to call out to the super default method + // in an overridden default method. + + fn fold_crate(&mut self, c: Crate) -> Crate { + noop_fold_crate(c, self) + } + + fn fold_meta_items(&mut self, meta_items: Vec<MetaItem>) -> Vec<MetaItem> { + noop_fold_meta_items(meta_items, self) + } + + fn fold_meta_list_item(&mut self, list_item: NestedMetaItem) -> NestedMetaItem { + noop_fold_meta_list_item(list_item, self) + } + + fn fold_meta_item(&mut self, meta_item: MetaItem) -> MetaItem { + noop_fold_meta_item(meta_item, self) + } + + fn fold_view_path(&mut self, view_path: P<ViewPath>) -> P<ViewPath> { + noop_fold_view_path(view_path, self) + } + + fn fold_foreign_item(&mut self, ni: ForeignItem) -> ForeignItem { + noop_fold_foreign_item(ni, self) + } + + fn fold_item(&mut self, i: P<Item>) -> SmallVector<P<Item>> { + noop_fold_item(i, self) + } + + fn fold_item_simple(&mut self, i: Item) -> Item { + noop_fold_item_simple(i, self) + } + + fn fold_struct_field(&mut self, sf: StructField) -> StructField { + noop_fold_struct_field(sf, self) + } + + fn fold_item_kind(&mut self, i: ItemKind) -> ItemKind { + noop_fold_item_kind(i, self) + } + + fn fold_trait_item(&mut self, i: TraitItem) -> SmallVector<TraitItem> { + noop_fold_trait_item(i, self) + } + + fn fold_impl_item(&mut self, i: ImplItem) -> SmallVector<ImplItem> { + noop_fold_impl_item(i, self) + } + + fn fold_fn_decl(&mut self, d: P<FnDecl>) -> P<FnDecl> { + noop_fold_fn_decl(d, self) + } + + fn fold_block(&mut self, b: P<Block>) -> P<Block> { + noop_fold_block(b, self) + } + + fn fold_stmt(&mut self, s: Stmt) -> SmallVector<Stmt> { + noop_fold_stmt(s, self) + } + + fn fold_arm(&mut self, a: Arm) -> Arm { + noop_fold_arm(a, self) + } + + fn fold_pat(&mut self, p: P<Pat>) -> P<Pat> { + noop_fold_pat(p, self) + } + + fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> { + e.map(|e| noop_fold_expr(e, self)) + } + + fn fold_opt_expr(&mut self, e: P<Expr>) -> Option<P<Expr>> { + noop_fold_opt_expr(e, self) + } + + fn fold_exprs(&mut self, es: Vec<P<Expr>>) -> Vec<P<Expr>> { + noop_fold_exprs(es, self) + } + + fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> { + noop_fold_ty(t, self) + } + + fn fold_ty_binding(&mut self, t: TypeBinding) -> TypeBinding { + noop_fold_ty_binding(t, self) + } + + fn fold_mod(&mut self, m: Mod) -> Mod { + noop_fold_mod(m, self) + } + + fn fold_foreign_mod(&mut self, nm: ForeignMod) -> ForeignMod { + noop_fold_foreign_mod(nm, self) + } + + fn fold_variant(&mut self, v: Variant) -> Variant { + noop_fold_variant(v, self) + } + + fn fold_ident(&mut self, i: Ident) -> Ident { + noop_fold_ident(i, self) + } + + fn fold_usize(&mut self, i: usize) -> usize { + noop_fold_usize(i, self) + } + + fn fold_path(&mut self, p: Path) -> Path { + noop_fold_path(p, self) + } + + fn fold_path_parameters(&mut self, p: PathParameters) -> PathParameters { + noop_fold_path_parameters(p, self) + } + + fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData) + -> AngleBracketedParameterData + { + noop_fold_angle_bracketed_parameter_data(p, self) + } + + fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedParameterData) + -> ParenthesizedParameterData + { + noop_fold_parenthesized_parameter_data(p, self) + } + + fn fold_local(&mut self, l: P<Local>) -> P<Local> { + noop_fold_local(l, self) + } + + fn fold_mac(&mut self, _mac: Mac) -> Mac { + panic!("fold_mac disabled by default"); + // NB: see note about macros above. + // if you really want a folder that + // works on macros, use this + // definition in your trait impl: + // fold::noop_fold_mac(_mac, self) + } + + fn fold_lifetime(&mut self, l: Lifetime) -> Lifetime { + noop_fold_lifetime(l, self) + } + + fn fold_lifetime_def(&mut self, l: LifetimeDef) -> LifetimeDef { + noop_fold_lifetime_def(l, self) + } + + fn fold_attribute(&mut self, at: Attribute) -> Option<Attribute> { + noop_fold_attribute(at, self) + } + + fn fold_arg(&mut self, a: Arg) -> Arg { + noop_fold_arg(a, self) + } + + fn fold_generics(&mut self, generics: Generics) -> Generics { + noop_fold_generics(generics, self) + } + + fn fold_trait_ref(&mut self, p: TraitRef) -> TraitRef { + noop_fold_trait_ref(p, self) + } + + fn fold_poly_trait_ref(&mut self, p: PolyTraitRef) -> PolyTraitRef { + noop_fold_poly_trait_ref(p, self) + } + + fn fold_variant_data(&mut self, vdata: VariantData) -> VariantData { + noop_fold_variant_data(vdata, self) + } + + fn fold_lifetimes(&mut self, lts: Vec<Lifetime>) -> Vec<Lifetime> { + noop_fold_lifetimes(lts, self) + } + + fn fold_lifetime_defs(&mut self, lts: Vec<LifetimeDef>) -> Vec<LifetimeDef> { + noop_fold_lifetime_defs(lts, self) + } + + fn fold_ty_param(&mut self, tp: TyParam) -> TyParam { + noop_fold_ty_param(tp, self) + } + + fn fold_ty_params(&mut self, tps: P<[TyParam]>) -> P<[TyParam]> { + noop_fold_ty_params(tps, self) + } + + fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree { + noop_fold_tt(tt, self) + } + + fn fold_tts(&mut self, tts: &[TokenTree]) -> Vec<TokenTree> { + noop_fold_tts(tts, self) + } + + fn fold_token(&mut self, t: token::Token) -> token::Token { + noop_fold_token(t, self) + } + + fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal { + noop_fold_interpolated(nt, self) + } + + fn fold_opt_lifetime(&mut self, o_lt: Option<Lifetime>) -> Option<Lifetime> { + noop_fold_opt_lifetime(o_lt, self) + } + + fn fold_opt_bounds(&mut self, b: Option<TyParamBounds>) + -> Option<TyParamBounds> { + noop_fold_opt_bounds(b, self) + } + + fn fold_bounds(&mut self, b: TyParamBounds) + -> TyParamBounds { + noop_fold_bounds(b, self) + } + + fn fold_ty_param_bound(&mut self, tpb: TyParamBound) -> TyParamBound { + noop_fold_ty_param_bound(tpb, self) + } + + fn fold_mt(&mut self, mt: MutTy) -> MutTy { + noop_fold_mt(mt, self) + } + + fn fold_field(&mut self, field: Field) -> Field { + noop_fold_field(field, self) + } + + fn fold_where_clause(&mut self, where_clause: WhereClause) + -> WhereClause { + noop_fold_where_clause(where_clause, self) + } + + fn fold_where_predicate(&mut self, where_predicate: WherePredicate) + -> WherePredicate { + noop_fold_where_predicate(where_predicate, self) + } + + fn fold_vis(&mut self, vis: Visibility) -> Visibility { + noop_fold_vis(vis, self) + } + + fn new_id(&mut self, i: NodeId) -> NodeId { + i + } + + fn new_span(&mut self, sp: Span) -> Span { + sp + } +} + +pub fn noop_fold_meta_items<T: Folder>(meta_items: Vec<MetaItem>, fld: &mut T) -> Vec<MetaItem> { + meta_items.move_map(|x| fld.fold_meta_item(x)) +} + +pub fn noop_fold_view_path<T: Folder>(view_path: P<ViewPath>, fld: &mut T) -> P<ViewPath> { + view_path.map(|Spanned {node, span}| Spanned { + node: match node { + ViewPathSimple(ident, path) => { + ViewPathSimple(fld.fold_ident(ident), fld.fold_path(path)) + } + ViewPathGlob(path) => { + ViewPathGlob(fld.fold_path(path)) + } + ViewPathList(path, path_list_idents) => { + let path = fld.fold_path(path); + let path_list_idents = path_list_idents.move_map(|path_list_ident| Spanned { + node: PathListItem_ { + id: fld.new_id(path_list_ident.node.id), + rename: path_list_ident.node.rename.map(|ident| fld.fold_ident(ident)), + name: fld.fold_ident(path_list_ident.node.name), + }, + span: fld.new_span(path_list_ident.span) + }); + ViewPathList(path, path_list_idents) + } + }, + span: fld.new_span(span) + }) +} + +pub fn fold_attrs<T: Folder>(attrs: Vec<Attribute>, fld: &mut T) -> Vec<Attribute> { + attrs.move_flat_map(|x| fld.fold_attribute(x)) +} + +pub fn fold_thin_attrs<T: Folder>(attrs: ThinVec<Attribute>, fld: &mut T) -> ThinVec<Attribute> { + fold_attrs(attrs.into(), fld).into() +} + +pub fn noop_fold_arm<T: Folder>(Arm {attrs, pats, guard, body}: Arm, fld: &mut T) -> Arm { + Arm { + attrs: fold_attrs(attrs, fld), + pats: pats.move_map(|x| fld.fold_pat(x)), + guard: guard.map(|x| fld.fold_expr(x)), + body: fld.fold_expr(body), + } +} + +pub fn noop_fold_ty_binding<T: Folder>(b: TypeBinding, fld: &mut T) -> TypeBinding { + TypeBinding { + id: fld.new_id(b.id), + ident: fld.fold_ident(b.ident), + ty: fld.fold_ty(b.ty), + span: fld.new_span(b.span), + } +} + +pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> { + t.map(|Ty {id, node, span}| Ty { + id: fld.new_id(id), + node: match node { + TyKind::Infer | TyKind::ImplicitSelf => node, + TyKind::Slice(ty) => TyKind::Slice(fld.fold_ty(ty)), + TyKind::Ptr(mt) => TyKind::Ptr(fld.fold_mt(mt)), + TyKind::Rptr(region, mt) => { + TyKind::Rptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt)) + } + TyKind::BareFn(f) => { + TyKind::BareFn(f.map(|BareFnTy {lifetimes, unsafety, abi, decl}| BareFnTy { + lifetimes: fld.fold_lifetime_defs(lifetimes), + unsafety: unsafety, + abi: abi, + decl: fld.fold_fn_decl(decl) + })) + } + TyKind::Never => node, + TyKind::Tup(tys) => TyKind::Tup(tys.move_map(|ty| fld.fold_ty(ty))), + TyKind::Paren(ty) => TyKind::Paren(fld.fold_ty(ty)), + TyKind::Path(qself, path) => { + let qself = qself.map(|QSelf { ty, position }| { + QSelf { + ty: fld.fold_ty(ty), + position: position + } + }); + TyKind::Path(qself, fld.fold_path(path)) + } + TyKind::ObjectSum(ty, bounds) => { + TyKind::ObjectSum(fld.fold_ty(ty), + fld.fold_bounds(bounds)) + } + TyKind::Array(ty, e) => { + TyKind::Array(fld.fold_ty(ty), fld.fold_expr(e)) + } + TyKind::Typeof(expr) => { + TyKind::Typeof(fld.fold_expr(expr)) + } + TyKind::PolyTraitRef(bounds) => { + TyKind::PolyTraitRef(bounds.move_map(|b| fld.fold_ty_param_bound(b))) + } + TyKind::ImplTrait(bounds) => { + TyKind::ImplTrait(bounds.move_map(|b| fld.fold_ty_param_bound(b))) + } + TyKind::Mac(mac) => { + TyKind::Mac(fld.fold_mac(mac)) + } + }, + span: fld.new_span(span) + }) +} + +pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, items}: ForeignMod, + fld: &mut T) -> ForeignMod { + ForeignMod { + abi: abi, + items: items.move_map(|x| fld.fold_foreign_item(x)), + } +} + +pub fn noop_fold_variant<T: Folder>(v: Variant, fld: &mut T) -> Variant { + Spanned { + node: Variant_ { + name: v.node.name, + attrs: fold_attrs(v.node.attrs, fld), + data: fld.fold_variant_data(v.node.data), + disr_expr: v.node.disr_expr.map(|e| fld.fold_expr(e)), + }, + span: fld.new_span(v.span), + } +} + +pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident { + i +} + +pub fn noop_fold_usize<T: Folder>(i: usize, _: &mut T) -> usize { + i +} + +pub fn noop_fold_path<T: Folder>(Path { segments, span }: Path, fld: &mut T) -> Path { + Path { + segments: segments.move_map(|PathSegment {identifier, parameters}| PathSegment { + identifier: fld.fold_ident(identifier), + parameters: parameters.map(|ps| ps.map(|ps| fld.fold_path_parameters(ps))), + }), + span: fld.new_span(span) + } +} + +pub fn noop_fold_path_parameters<T: Folder>(path_parameters: PathParameters, fld: &mut T) + -> PathParameters +{ + match path_parameters { + PathParameters::AngleBracketed(data) => + PathParameters::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)), + PathParameters::Parenthesized(data) => + PathParameters::Parenthesized(fld.fold_parenthesized_parameter_data(data)), + } +} + +pub fn noop_fold_angle_bracketed_parameter_data<T: Folder>(data: AngleBracketedParameterData, + fld: &mut T) + -> AngleBracketedParameterData +{ + let AngleBracketedParameterData { lifetimes, types, bindings } = data; + AngleBracketedParameterData { lifetimes: fld.fold_lifetimes(lifetimes), + types: types.move_map(|ty| fld.fold_ty(ty)), + bindings: bindings.move_map(|b| fld.fold_ty_binding(b)) } +} + +pub fn noop_fold_parenthesized_parameter_data<T: Folder>(data: ParenthesizedParameterData, + fld: &mut T) + -> ParenthesizedParameterData +{ + let ParenthesizedParameterData { inputs, output, span } = data; + ParenthesizedParameterData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)), + output: output.map(|ty| fld.fold_ty(ty)), + span: fld.new_span(span) } +} + +pub fn noop_fold_local<T: Folder>(l: P<Local>, fld: &mut T) -> P<Local> { + l.map(|Local {id, pat, ty, init, span, attrs}| Local { + id: fld.new_id(id), + pat: fld.fold_pat(pat), + ty: ty.map(|t| fld.fold_ty(t)), + init: init.map(|e| fld.fold_expr(e)), + span: fld.new_span(span), + attrs: fold_attrs(attrs.into(), fld).into(), + }) +} + +pub fn noop_fold_attribute<T: Folder>(attr: Attribute, fld: &mut T) -> Option<Attribute> { + Some(Attribute { + id: attr.id, + style: attr.style, + value: fld.fold_meta_item(attr.value), + is_sugared_doc: attr.is_sugared_doc, + span: fld.new_span(attr.span), + }) +} + +pub fn noop_fold_mac<T: Folder>(Spanned {node, span}: Mac, fld: &mut T) -> Mac { + Spanned { + node: Mac_ { + path: fld.fold_path(node.path), + tts: fld.fold_tts(&node.tts), + }, + span: fld.new_span(span) + } +} + +pub fn noop_fold_meta_list_item<T: Folder>(li: NestedMetaItem, fld: &mut T) + -> NestedMetaItem { + Spanned { + node: match li.node { + NestedMetaItemKind::MetaItem(mi) => { + NestedMetaItemKind::MetaItem(fld.fold_meta_item(mi)) + }, + NestedMetaItemKind::Literal(lit) => NestedMetaItemKind::Literal(lit) + }, + span: fld.new_span(li.span) + } +} + +pub fn noop_fold_meta_item<T: Folder>(mi: MetaItem, fld: &mut T) -> MetaItem { + MetaItem { + name: mi.name, + node: match mi.node { + MetaItemKind::Word => MetaItemKind::Word, + MetaItemKind::List(mis) => { + MetaItemKind::List(mis.move_map(|e| fld.fold_meta_list_item(e))) + }, + MetaItemKind::NameValue(s) => MetaItemKind::NameValue(s), + }, + span: fld.new_span(mi.span) + } +} + +pub fn noop_fold_arg<T: Folder>(Arg {id, pat, ty}: Arg, fld: &mut T) -> Arg { + Arg { + id: fld.new_id(id), + pat: fld.fold_pat(pat), + ty: fld.fold_ty(ty) + } +} + +pub fn noop_fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree { + match *tt { + TokenTree::Token(span, ref tok) => + TokenTree::Token(span, fld.fold_token(tok.clone())), + TokenTree::Delimited(span, ref delimed) => { + TokenTree::Delimited(span, Rc::new( + Delimited { + delim: delimed.delim, + open_span: delimed.open_span, + tts: fld.fold_tts(&delimed.tts), + close_span: delimed.close_span, + } + )) + }, + TokenTree::Sequence(span, ref seq) => + TokenTree::Sequence(span, + Rc::new(SequenceRepetition { + tts: fld.fold_tts(&seq.tts), + separator: seq.separator.clone().map(|tok| fld.fold_token(tok)), + ..**seq + })), + } +} + +pub fn noop_fold_tts<T: Folder>(tts: &[TokenTree], fld: &mut T) -> Vec<TokenTree> { + tts.iter().map(|tt| fld.fold_tt(tt)).collect() +} + +// apply ident folder if it's an ident, apply other folds to interpolated nodes +pub fn noop_fold_token<T: Folder>(t: token::Token, fld: &mut T) -> token::Token { + match t { + token::Ident(id) => token::Ident(fld.fold_ident(id)), + token::Lifetime(id) => token::Lifetime(fld.fold_ident(id)), + token::Interpolated(nt) => { + let nt = match Rc::try_unwrap(nt) { + Ok(nt) => nt, + Err(nt) => (*nt).clone(), + }; + token::Interpolated(Rc::new(fld.fold_interpolated(nt))) + } + token::SubstNt(ident) => token::SubstNt(fld.fold_ident(ident)), + token::MatchNt(name, kind) => token::MatchNt(fld.fold_ident(name), fld.fold_ident(kind)), + _ => t + } +} + +/// apply folder to elements of interpolated nodes +// +// NB: this can occur only when applying a fold to partially expanded code, where +// parsed pieces have gotten implanted ito *other* macro invocations. This is relevant +// for macro hygiene, but possibly not elsewhere. +// +// One problem here occurs because the types for fold_item, fold_stmt, etc. allow the +// folder to return *multiple* items; this is a problem for the nodes here, because +// they insist on having exactly one piece. One solution would be to mangle the fold +// trait to include one-to-many and one-to-one versions of these entry points, but that +// would probably confuse a lot of people and help very few. Instead, I'm just going +// to put in dynamic checks. I think the performance impact of this will be pretty much +// nonexistent. The danger is that someone will apply a fold to a partially expanded +// node, and will be confused by the fact that their "fold_item" or "fold_stmt" isn't +// getting called on NtItem or NtStmt nodes. Hopefully they'll wind up reading this +// comment, and doing something appropriate. +// +// BTW, design choice: I considered just changing the type of, e.g., NtItem to contain +// multiple items, but decided against it when I looked at parse_item_or_view_item and +// tried to figure out what I would do with multiple items there.... +pub fn noop_fold_interpolated<T: Folder>(nt: token::Nonterminal, fld: &mut T) + -> token::Nonterminal { + match nt { + token::NtItem(item) => + token::NtItem(fld.fold_item(item) + // this is probably okay, because the only folds likely + // to peek inside interpolated nodes will be renamings/markings, + // which map single items to single items + .expect_one("expected fold to produce exactly one item")), + token::NtBlock(block) => token::NtBlock(fld.fold_block(block)), + token::NtStmt(stmt) => + token::NtStmt(fld.fold_stmt(stmt) + // this is probably okay, because the only folds likely + // to peek inside interpolated nodes will be renamings/markings, + // which map single items to single items + .expect_one("expected fold to produce exactly one statement")), + token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)), + token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)), + token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)), + token::NtIdent(id) => token::NtIdent(Spanned::<Ident>{node: fld.fold_ident(id.node), ..id}), + token::NtMeta(meta_item) => token::NtMeta(fld.fold_meta_item(meta_item)), + token::NtPath(path) => token::NtPath(fld.fold_path(path)), + token::NtTT(tt) => token::NtTT(fld.fold_tt(&tt)), + token::NtArm(arm) => token::NtArm(fld.fold_arm(arm)), + token::NtImplItem(item) => + token::NtImplItem(fld.fold_impl_item(item) + .expect_one("expected fold to produce exactly one item")), + token::NtTraitItem(item) => + token::NtTraitItem(fld.fold_trait_item(item) + .expect_one("expected fold to produce exactly one item")), + token::NtGenerics(generics) => token::NtGenerics(fld.fold_generics(generics)), + token::NtWhereClause(where_clause) => + token::NtWhereClause(fld.fold_where_clause(where_clause)), + token::NtArg(arg) => token::NtArg(fld.fold_arg(arg)), + } +} + +pub fn noop_fold_fn_decl<T: Folder>(decl: P<FnDecl>, fld: &mut T) -> P<FnDecl> { + decl.map(|FnDecl {inputs, output, variadic}| FnDecl { + inputs: inputs.move_map(|x| fld.fold_arg(x)), + output: match output { + FunctionRetTy::Ty(ty) => FunctionRetTy::Ty(fld.fold_ty(ty)), + FunctionRetTy::Default(span) => FunctionRetTy::Default(span), + }, + variadic: variadic + }) +} + +pub fn noop_fold_ty_param_bound<T>(tpb: TyParamBound, fld: &mut T) + -> TyParamBound + where T: Folder { + match tpb { + TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier), + RegionTyParamBound(lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)), + } +} + +pub fn noop_fold_ty_param<T: Folder>(tp: TyParam, fld: &mut T) -> TyParam { + let TyParam {attrs, id, ident, bounds, default, span} = tp; + let attrs: Vec<_> = attrs.into(); + TyParam { + attrs: attrs.into_iter() + .flat_map(|x| fld.fold_attribute(x).into_iter()) + .collect::<Vec<_>>() + .into(), + id: fld.new_id(id), + ident: fld.fold_ident(ident), + bounds: fld.fold_bounds(bounds), + default: default.map(|x| fld.fold_ty(x)), + span: span + } +} + +pub fn noop_fold_ty_params<T: Folder>(tps: P<[TyParam]>, fld: &mut T) + -> P<[TyParam]> { + tps.move_map(|tp| fld.fold_ty_param(tp)) +} + +pub fn noop_fold_lifetime<T: Folder>(l: Lifetime, fld: &mut T) -> Lifetime { + Lifetime { + id: fld.new_id(l.id), + name: l.name, + span: fld.new_span(l.span) + } +} + +pub fn noop_fold_lifetime_def<T: Folder>(l: LifetimeDef, fld: &mut T) + -> LifetimeDef { + let attrs: Vec<_> = l.attrs.into(); + LifetimeDef { + attrs: attrs.into_iter() + .flat_map(|x| fld.fold_attribute(x).into_iter()) + .collect::<Vec<_>>() + .into(), + lifetime: fld.fold_lifetime(l.lifetime), + bounds: fld.fold_lifetimes(l.bounds), + } +} + +pub fn noop_fold_lifetimes<T: Folder>(lts: Vec<Lifetime>, fld: &mut T) -> Vec<Lifetime> { + lts.move_map(|l| fld.fold_lifetime(l)) +} + +pub fn noop_fold_lifetime_defs<T: Folder>(lts: Vec<LifetimeDef>, fld: &mut T) + -> Vec<LifetimeDef> { + lts.move_map(|l| fld.fold_lifetime_def(l)) +} + +pub fn noop_fold_opt_lifetime<T: Folder>(o_lt: Option<Lifetime>, fld: &mut T) + -> Option<Lifetime> { + o_lt.map(|lt| fld.fold_lifetime(lt)) +} + +pub fn noop_fold_generics<T: Folder>(Generics {ty_params, lifetimes, where_clause, span}: Generics, + fld: &mut T) -> Generics { + Generics { + ty_params: fld.fold_ty_params(ty_params), + lifetimes: fld.fold_lifetime_defs(lifetimes), + where_clause: fld.fold_where_clause(where_clause), + span: fld.new_span(span), + } +} + +pub fn noop_fold_where_clause<T: Folder>( + WhereClause {id, predicates}: WhereClause, + fld: &mut T) + -> WhereClause { + WhereClause { + id: fld.new_id(id), + predicates: predicates.move_map(|predicate| { + fld.fold_where_predicate(predicate) + }) + } +} + +pub fn noop_fold_where_predicate<T: Folder>( + pred: WherePredicate, + fld: &mut T) + -> WherePredicate { + match pred { + ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{bound_lifetimes, + bounded_ty, + bounds, + span}) => { + ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { + bound_lifetimes: fld.fold_lifetime_defs(bound_lifetimes), + bounded_ty: fld.fold_ty(bounded_ty), + bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)), + span: fld.new_span(span) + }) + } + ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{lifetime, + bounds, + span}) => { + ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { + span: fld.new_span(span), + lifetime: fld.fold_lifetime(lifetime), + bounds: bounds.move_map(|bound| fld.fold_lifetime(bound)) + }) + } + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{id, + path, + ty, + span}) => { + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ + id: fld.new_id(id), + path: fld.fold_path(path), + ty:fld.fold_ty(ty), + span: fld.new_span(span) + }) + } + } +} + +pub fn noop_fold_variant_data<T: Folder>(vdata: VariantData, fld: &mut T) -> VariantData { + match vdata { + ast::VariantData::Struct(fields, id) => { + ast::VariantData::Struct(fields.move_map(|f| fld.fold_struct_field(f)), + fld.new_id(id)) + } + ast::VariantData::Tuple(fields, id) => { + ast::VariantData::Tuple(fields.move_map(|f| fld.fold_struct_field(f)), + fld.new_id(id)) + } + ast::VariantData::Unit(id) => ast::VariantData::Unit(fld.new_id(id)) + } +} + +pub fn noop_fold_trait_ref<T: Folder>(p: TraitRef, fld: &mut T) -> TraitRef { + let id = fld.new_id(p.ref_id); + let TraitRef { + path, + ref_id: _, + } = p; + ast::TraitRef { + path: fld.fold_path(path), + ref_id: id, + } +} + +pub fn noop_fold_poly_trait_ref<T: Folder>(p: PolyTraitRef, fld: &mut T) -> PolyTraitRef { + ast::PolyTraitRef { + bound_lifetimes: fld.fold_lifetime_defs(p.bound_lifetimes), + trait_ref: fld.fold_trait_ref(p.trait_ref), + span: fld.new_span(p.span), + } +} + +pub fn noop_fold_struct_field<T: Folder>(f: StructField, fld: &mut T) -> StructField { + StructField { + span: fld.new_span(f.span), + id: fld.new_id(f.id), + ident: f.ident.map(|ident| fld.fold_ident(ident)), + vis: fld.fold_vis(f.vis), + ty: fld.fold_ty(f.ty), + attrs: fold_attrs(f.attrs, fld), + } +} + +pub fn noop_fold_field<T: Folder>(f: Field, folder: &mut T) -> Field { + Field { + ident: respan(f.ident.span, folder.fold_ident(f.ident.node)), + expr: folder.fold_expr(f.expr), + span: folder.new_span(f.span), + is_shorthand: f.is_shorthand, + } +} + +pub fn noop_fold_mt<T: Folder>(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutTy { + MutTy { + ty: folder.fold_ty(ty), + mutbl: mutbl, + } +} + +pub fn noop_fold_opt_bounds<T: Folder>(b: Option<TyParamBounds>, folder: &mut T) + -> Option<TyParamBounds> { + b.map(|bounds| folder.fold_bounds(bounds)) +} + +fn noop_fold_bounds<T: Folder>(bounds: TyParamBounds, folder: &mut T) + -> TyParamBounds { + bounds.move_map(|bound| folder.fold_ty_param_bound(bound)) +} + +pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> { + b.map(|Block {id, stmts, rules, span}| Block { + id: folder.new_id(id), + stmts: stmts.move_flat_map(|s| folder.fold_stmt(s).into_iter()), + rules: rules, + span: folder.new_span(span), + }) +} + +pub fn noop_fold_item_kind<T: Folder>(i: ItemKind, folder: &mut T) -> ItemKind { + match i { + ItemKind::ExternCrate(string) => ItemKind::ExternCrate(string), + ItemKind::Use(view_path) => { + ItemKind::Use(folder.fold_view_path(view_path)) + } + ItemKind::Static(t, m, e) => { + ItemKind::Static(folder.fold_ty(t), m, folder.fold_expr(e)) + } + ItemKind::Const(t, e) => { + ItemKind::Const(folder.fold_ty(t), folder.fold_expr(e)) + } + ItemKind::Fn(decl, unsafety, constness, abi, generics, body) => { + let generics = folder.fold_generics(generics); + let decl = folder.fold_fn_decl(decl); + let body = folder.fold_block(body); + ItemKind::Fn(decl, unsafety, constness, abi, generics, body) + } + ItemKind::Mod(m) => ItemKind::Mod(folder.fold_mod(m)), + ItemKind::ForeignMod(nm) => ItemKind::ForeignMod(folder.fold_foreign_mod(nm)), + ItemKind::Ty(t, generics) => { + ItemKind::Ty(folder.fold_ty(t), folder.fold_generics(generics)) + } + ItemKind::Enum(enum_definition, generics) => { + let generics = folder.fold_generics(generics); + let variants = enum_definition.variants.move_map(|x| folder.fold_variant(x)); + ItemKind::Enum(ast::EnumDef { variants: variants }, generics) + } + ItemKind::Struct(struct_def, generics) => { + let generics = folder.fold_generics(generics); + ItemKind::Struct(folder.fold_variant_data(struct_def), generics) + } + ItemKind::Union(struct_def, generics) => { + let generics = folder.fold_generics(generics); + ItemKind::Union(folder.fold_variant_data(struct_def), generics) + } + ItemKind::DefaultImpl(unsafety, ref trait_ref) => { + ItemKind::DefaultImpl(unsafety, folder.fold_trait_ref((*trait_ref).clone())) + } + ItemKind::Impl(unsafety, polarity, generics, ifce, ty, impl_items) => ItemKind::Impl( + unsafety, + polarity, + folder.fold_generics(generics), + ifce.map(|trait_ref| folder.fold_trait_ref(trait_ref.clone())), + folder.fold_ty(ty), + impl_items.move_flat_map(|item| folder.fold_impl_item(item)), + ), + ItemKind::Trait(unsafety, generics, bounds, items) => ItemKind::Trait( + unsafety, + folder.fold_generics(generics), + folder.fold_bounds(bounds), + items.move_flat_map(|item| folder.fold_trait_item(item)), + ), + ItemKind::Mac(m) => ItemKind::Mac(folder.fold_mac(m)), + } +} + +pub fn noop_fold_trait_item<T: Folder>(i: TraitItem, folder: &mut T) + -> SmallVector<TraitItem> { + SmallVector::one(TraitItem { + id: folder.new_id(i.id), + ident: folder.fold_ident(i.ident), + attrs: fold_attrs(i.attrs, folder), + node: match i.node { + TraitItemKind::Const(ty, default) => { + TraitItemKind::Const(folder.fold_ty(ty), + default.map(|x| folder.fold_expr(x))) + } + TraitItemKind::Method(sig, body) => { + TraitItemKind::Method(noop_fold_method_sig(sig, folder), + body.map(|x| folder.fold_block(x))) + } + TraitItemKind::Type(bounds, default) => { + TraitItemKind::Type(folder.fold_bounds(bounds), + default.map(|x| folder.fold_ty(x))) + } + ast::TraitItemKind::Macro(mac) => { + TraitItemKind::Macro(folder.fold_mac(mac)) + } + }, + span: folder.new_span(i.span) + }) +} + +pub fn noop_fold_impl_item<T: Folder>(i: ImplItem, folder: &mut T) + -> SmallVector<ImplItem> { + SmallVector::one(ImplItem { + id: folder.new_id(i.id), + vis: folder.fold_vis(i.vis), + ident: folder.fold_ident(i.ident), + attrs: fold_attrs(i.attrs, folder), + defaultness: i.defaultness, + node: match i.node { + ast::ImplItemKind::Const(ty, expr) => { + ast::ImplItemKind::Const(folder.fold_ty(ty), folder.fold_expr(expr)) + } + ast::ImplItemKind::Method(sig, body) => { + ast::ImplItemKind::Method(noop_fold_method_sig(sig, folder), + folder.fold_block(body)) + } + ast::ImplItemKind::Type(ty) => ast::ImplItemKind::Type(folder.fold_ty(ty)), + ast::ImplItemKind::Macro(mac) => ast::ImplItemKind::Macro(folder.fold_mac(mac)) + }, + span: folder.new_span(i.span) + }) +} + +pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod { + Mod { + inner: folder.new_span(inner), + items: items.move_flat_map(|x| folder.fold_item(x)), + } +} + +pub fn noop_fold_crate<T: Folder>(Crate {module, attrs, mut exported_macros, span}: Crate, + folder: &mut T) -> Crate { + let mut items = folder.fold_item(P(ast::Item { + ident: keywords::Invalid.ident(), + attrs: attrs, + id: ast::DUMMY_NODE_ID, + vis: ast::Visibility::Public, + span: span, + node: ast::ItemKind::Mod(module), + })).into_iter(); + + let (module, attrs, span) = match items.next() { + Some(item) => { + assert!(items.next().is_none(), + "a crate cannot expand to more than one item"); + item.and_then(|ast::Item { attrs, span, node, .. }| { + match node { + ast::ItemKind::Mod(m) => (m, attrs, span), + _ => panic!("fold converted a module to not a module"), + } + }) + } + None => (ast::Mod { + inner: span, + items: vec![], + }, vec![], span) + }; + + for def in &mut exported_macros { + def.id = folder.new_id(def.id); + } + + Crate { + module: module, + attrs: attrs, + exported_macros: exported_macros, + span: span, + } +} + +// fold one item into possibly many items +pub fn noop_fold_item<T: Folder>(i: P<Item>, folder: &mut T) -> SmallVector<P<Item>> { + SmallVector::one(i.map(|i| folder.fold_item_simple(i))) +} + +// fold one item into exactly one item +pub fn noop_fold_item_simple<T: Folder>(Item {id, ident, attrs, node, vis, span}: Item, + folder: &mut T) -> Item { + Item { + id: folder.new_id(id), + vis: folder.fold_vis(vis), + ident: folder.fold_ident(ident), + attrs: fold_attrs(attrs, folder), + node: folder.fold_item_kind(node), + span: folder.new_span(span) + } +} + +pub fn noop_fold_foreign_item<T: Folder>(ni: ForeignItem, folder: &mut T) -> ForeignItem { + ForeignItem { + id: folder.new_id(ni.id), + vis: folder.fold_vis(ni.vis), + ident: folder.fold_ident(ni.ident), + attrs: fold_attrs(ni.attrs, folder), + node: match ni.node { + ForeignItemKind::Fn(fdec, generics) => { + ForeignItemKind::Fn(folder.fold_fn_decl(fdec), folder.fold_generics(generics)) + } + ForeignItemKind::Static(t, m) => { + ForeignItemKind::Static(folder.fold_ty(t), m) + } + }, + span: folder.new_span(ni.span) + } +} + +pub fn noop_fold_method_sig<T: Folder>(sig: MethodSig, folder: &mut T) -> MethodSig { + MethodSig { + generics: folder.fold_generics(sig.generics), + abi: sig.abi, + unsafety: sig.unsafety, + constness: sig.constness, + decl: folder.fold_fn_decl(sig.decl) + } +} + +pub fn noop_fold_pat<T: Folder>(p: P<Pat>, folder: &mut T) -> P<Pat> { + p.map(|Pat {id, node, span}| Pat { + id: folder.new_id(id), + node: match node { + PatKind::Wild => PatKind::Wild, + PatKind::Ident(binding_mode, pth1, sub) => { + PatKind::Ident(binding_mode, + Spanned{span: folder.new_span(pth1.span), + node: folder.fold_ident(pth1.node)}, + sub.map(|x| folder.fold_pat(x))) + } + PatKind::Lit(e) => PatKind::Lit(folder.fold_expr(e)), + PatKind::TupleStruct(pth, pats, ddpos) => { + PatKind::TupleStruct(folder.fold_path(pth), + pats.move_map(|x| folder.fold_pat(x)), ddpos) + } + PatKind::Path(opt_qself, pth) => { + let opt_qself = opt_qself.map(|qself| { + QSelf { ty: folder.fold_ty(qself.ty), position: qself.position } + }); + PatKind::Path(opt_qself, folder.fold_path(pth)) + } + PatKind::Struct(pth, fields, etc) => { + let pth = folder.fold_path(pth); + let fs = fields.move_map(|f| { + Spanned { span: folder.new_span(f.span), + node: ast::FieldPat { + ident: folder.fold_ident(f.node.ident), + pat: folder.fold_pat(f.node.pat), + is_shorthand: f.node.is_shorthand, + }} + }); + PatKind::Struct(pth, fs, etc) + } + PatKind::Tuple(elts, ddpos) => { + PatKind::Tuple(elts.move_map(|x| folder.fold_pat(x)), ddpos) + } + PatKind::Box(inner) => PatKind::Box(folder.fold_pat(inner)), + PatKind::Ref(inner, mutbl) => PatKind::Ref(folder.fold_pat(inner), mutbl), + PatKind::Range(e1, e2) => { + PatKind::Range(folder.fold_expr(e1), folder.fold_expr(e2)) + }, + PatKind::Slice(before, slice, after) => { + PatKind::Slice(before.move_map(|x| folder.fold_pat(x)), + slice.map(|x| folder.fold_pat(x)), + after.move_map(|x| folder.fold_pat(x))) + } + PatKind::Mac(mac) => PatKind::Mac(folder.fold_mac(mac)) + }, + span: folder.new_span(span) + }) +} + +pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mut T) -> Expr { + Expr { + node: match node { + ExprKind::Box(e) => { + ExprKind::Box(folder.fold_expr(e)) + } + ExprKind::InPlace(p, e) => { + ExprKind::InPlace(folder.fold_expr(p), folder.fold_expr(e)) + } + ExprKind::Vec(exprs) => { + ExprKind::Vec(folder.fold_exprs(exprs)) + } + ExprKind::Repeat(expr, count) => { + ExprKind::Repeat(folder.fold_expr(expr), folder.fold_expr(count)) + } + ExprKind::Tup(exprs) => ExprKind::Tup(folder.fold_exprs(exprs)), + ExprKind::Call(f, args) => { + ExprKind::Call(folder.fold_expr(f), + folder.fold_exprs(args)) + } + ExprKind::MethodCall(i, tps, args) => { + ExprKind::MethodCall( + respan(folder.new_span(i.span), folder.fold_ident(i.node)), + tps.move_map(|x| folder.fold_ty(x)), + folder.fold_exprs(args)) + } + ExprKind::Binary(binop, lhs, rhs) => { + ExprKind::Binary(binop, + folder.fold_expr(lhs), + folder.fold_expr(rhs)) + } + ExprKind::Unary(binop, ohs) => { + ExprKind::Unary(binop, folder.fold_expr(ohs)) + } + ExprKind::Lit(l) => ExprKind::Lit(l), + ExprKind::Cast(expr, ty) => { + ExprKind::Cast(folder.fold_expr(expr), folder.fold_ty(ty)) + } + ExprKind::Type(expr, ty) => { + ExprKind::Type(folder.fold_expr(expr), folder.fold_ty(ty)) + } + ExprKind::AddrOf(m, ohs) => ExprKind::AddrOf(m, folder.fold_expr(ohs)), + ExprKind::If(cond, tr, fl) => { + ExprKind::If(folder.fold_expr(cond), + folder.fold_block(tr), + fl.map(|x| folder.fold_expr(x))) + } + ExprKind::IfLet(pat, expr, tr, fl) => { + ExprKind::IfLet(folder.fold_pat(pat), + folder.fold_expr(expr), + folder.fold_block(tr), + fl.map(|x| folder.fold_expr(x))) + } + ExprKind::While(cond, body, opt_ident) => { + ExprKind::While(folder.fold_expr(cond), + folder.fold_block(body), + opt_ident.map(|label| respan(folder.new_span(label.span), + folder.fold_ident(label.node)))) + } + ExprKind::WhileLet(pat, expr, body, opt_ident) => { + ExprKind::WhileLet(folder.fold_pat(pat), + folder.fold_expr(expr), + folder.fold_block(body), + opt_ident.map(|label| respan(folder.new_span(label.span), + folder.fold_ident(label.node)))) + } + ExprKind::ForLoop(pat, iter, body, opt_ident) => { + ExprKind::ForLoop(folder.fold_pat(pat), + folder.fold_expr(iter), + folder.fold_block(body), + opt_ident.map(|label| respan(folder.new_span(label.span), + folder.fold_ident(label.node)))) + } + ExprKind::Loop(body, opt_ident) => { + ExprKind::Loop(folder.fold_block(body), + opt_ident.map(|label| respan(folder.new_span(label.span), + folder.fold_ident(label.node)))) + } + ExprKind::Match(expr, arms) => { + ExprKind::Match(folder.fold_expr(expr), + arms.move_map(|x| folder.fold_arm(x))) + } + ExprKind::Closure(capture_clause, decl, body, span) => { + ExprKind::Closure(capture_clause, + folder.fold_fn_decl(decl), + folder.fold_expr(body), + folder.new_span(span)) + } + ExprKind::Block(blk) => ExprKind::Block(folder.fold_block(blk)), + ExprKind::Assign(el, er) => { + ExprKind::Assign(folder.fold_expr(el), folder.fold_expr(er)) + } + ExprKind::AssignOp(op, el, er) => { + ExprKind::AssignOp(op, + folder.fold_expr(el), + folder.fold_expr(er)) + } + ExprKind::Field(el, ident) => { + ExprKind::Field(folder.fold_expr(el), + respan(folder.new_span(ident.span), + folder.fold_ident(ident.node))) + } + ExprKind::TupField(el, ident) => { + ExprKind::TupField(folder.fold_expr(el), + respan(folder.new_span(ident.span), + folder.fold_usize(ident.node))) + } + ExprKind::Index(el, er) => { + ExprKind::Index(folder.fold_expr(el), folder.fold_expr(er)) + } + ExprKind::Range(e1, e2, lim) => { + ExprKind::Range(e1.map(|x| folder.fold_expr(x)), + e2.map(|x| folder.fold_expr(x)), + lim) + } + ExprKind::Path(qself, path) => { + let qself = qself.map(|QSelf { ty, position }| { + QSelf { + ty: folder.fold_ty(ty), + position: position + } + }); + ExprKind::Path(qself, folder.fold_path(path)) + } + ExprKind::Break(opt_ident, opt_expr) => { + ExprKind::Break(opt_ident.map(|label| respan(folder.new_span(label.span), + folder.fold_ident(label.node))), + opt_expr.map(|e| folder.fold_expr(e))) + } + ExprKind::Continue(opt_ident) => ExprKind::Continue(opt_ident.map(|label| + respan(folder.new_span(label.span), + folder.fold_ident(label.node))) + ), + ExprKind::Ret(e) => ExprKind::Ret(e.map(|x| folder.fold_expr(x))), + ExprKind::InlineAsm(asm) => ExprKind::InlineAsm(asm.map(|asm| { + InlineAsm { + inputs: asm.inputs.move_map(|(c, input)| { + (c, folder.fold_expr(input)) + }), + outputs: asm.outputs.move_map(|out| { + InlineAsmOutput { + constraint: out.constraint, + expr: folder.fold_expr(out.expr), + is_rw: out.is_rw, + is_indirect: out.is_indirect, + } + }), + ..asm + } + })), + ExprKind::Mac(mac) => ExprKind::Mac(folder.fold_mac(mac)), + ExprKind::Struct(path, fields, maybe_expr) => { + ExprKind::Struct(folder.fold_path(path), + fields.move_map(|x| folder.fold_field(x)), + maybe_expr.map(|x| folder.fold_expr(x))) + }, + ExprKind::Paren(ex) => { + let sub_expr = folder.fold_expr(ex); + return Expr { + // Nodes that are equal modulo `Paren` sugar no-ops should have the same ids. + id: sub_expr.id, + node: ExprKind::Paren(sub_expr), + span: folder.new_span(span), + attrs: fold_attrs(attrs.into(), folder).into(), + }; + } + ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)), + }, + id: folder.new_id(id), + span: folder.new_span(span), + attrs: fold_attrs(attrs.into(), folder).into(), + } +} + +pub fn noop_fold_opt_expr<T: Folder>(e: P<Expr>, folder: &mut T) -> Option<P<Expr>> { + Some(folder.fold_expr(e)) +} + +pub fn noop_fold_exprs<T: Folder>(es: Vec<P<Expr>>, folder: &mut T) -> Vec<P<Expr>> { + es.move_flat_map(|e| folder.fold_opt_expr(e)) +} + +pub fn noop_fold_stmt<T: Folder>(Stmt {node, span, id}: Stmt, folder: &mut T) -> SmallVector<Stmt> { + let id = folder.new_id(id); + let span = folder.new_span(span); + noop_fold_stmt_kind(node, folder).into_iter().map(|node| { + Stmt { id: id, node: node, span: span } + }).collect() +} + +pub fn noop_fold_stmt_kind<T: Folder>(node: StmtKind, folder: &mut T) -> SmallVector<StmtKind> { + match node { + StmtKind::Local(local) => SmallVector::one(StmtKind::Local(folder.fold_local(local))), + StmtKind::Item(item) => folder.fold_item(item).into_iter().map(StmtKind::Item).collect(), + StmtKind::Expr(expr) => { + folder.fold_opt_expr(expr).into_iter().map(StmtKind::Expr).collect() + } + StmtKind::Semi(expr) => { + folder.fold_opt_expr(expr).into_iter().map(StmtKind::Semi).collect() + } + StmtKind::Mac(mac) => SmallVector::one(StmtKind::Mac(mac.map(|(mac, semi, attrs)| { + (folder.fold_mac(mac), semi, fold_attrs(attrs.into(), folder).into()) + }))), + } +} + +pub fn noop_fold_vis<T: Folder>(vis: Visibility, folder: &mut T) -> Visibility { + match vis { + Visibility::Restricted { path, id } => Visibility::Restricted { + path: path.map(|path| folder.fold_path(path)), + id: folder.new_id(id) + }, + _ => vis, + } +} + +#[cfg(test)] +mod tests { + use std::io; + use ast::{self, Ident}; + use util::parser_testing::{string_to_crate, matches_codepattern}; + use print::pprust; + use fold; + use super::*; + + // this version doesn't care about getting comments or docstrings in. + fn fake_print_crate(s: &mut pprust::State, + krate: &ast::Crate) -> io::Result<()> { + s.print_mod(&krate.module, &krate.attrs) + } + + // change every identifier to "zz" + struct ToZzIdentFolder; + + impl Folder for ToZzIdentFolder { + fn fold_ident(&mut self, _: ast::Ident) -> ast::Ident { + Ident::from_str("zz") + } + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + fold::noop_fold_mac(mac, self) + } + } + + // maybe add to expand.rs... + macro_rules! assert_pred { + ($pred:expr, $predname:expr, $a:expr , $b:expr) => ( + { + let pred_val = $pred; + let a_val = $a; + let b_val = $b; + if !(pred_val(&a_val, &b_val)) { + panic!("expected args satisfying {}, got {} and {}", + $predname, a_val, b_val); + } + } + ) + } + + // make sure idents get transformed everywhere + #[test] fn ident_transformation () { + let mut zz_fold = ToZzIdentFolder; + let ast = string_to_crate( + "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); + let folded_crate = zz_fold.fold_crate(ast); + assert_pred!( + matches_codepattern, + "matches_codepattern", + pprust::to_string(|s| fake_print_crate(s, &folded_crate)), + "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()); + } + + // even inside macro defs.... + #[test] fn ident_transformation_in_defs () { + let mut zz_fold = ToZzIdentFolder; + let ast = string_to_crate( + "macro_rules! a {(b $c:expr $(d $e:token)f+ => \ + (g $(d $d $e)+))} ".to_string()); + let folded_crate = zz_fold.fold_crate(ast); + assert_pred!( + matches_codepattern, + "matches_codepattern", + pprust::to_string(|s| fake_print_crate(s, &folded_crate)), + "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)));".to_string()); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/json.rs b/bash-5.1/vendor/syntex_syntax/src/json.rs new file mode 100644 index 0000000..a1c273b --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/json.rs @@ -0,0 +1,356 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A JSON emitter for errors. +//! +//! This works by converting errors to a simplified structural format (see the +//! structs at the start of the file) and then serialising them. These should +//! contain as much information about the error as possible. +//! +//! The format of the JSON output should be considered *unstable*. For now the +//! structs at the end of this file (Diagnostic*) specify the error format. + +// FIXME spec the JSON output properly. + +use codemap::CodeMap; +use syntax_pos::{self, MacroBacktrace, Span, SpanLabel, MultiSpan}; +use errors::registry::Registry; +use errors::{DiagnosticBuilder, SubDiagnostic, RenderSpan, CodeSuggestion, CodeMapper}; +use errors::emitter::Emitter; + +use std::rc::Rc; +use std::io::{self, Write}; +use std::vec; + +use rustc_serialize::json::as_json; + +pub struct JsonEmitter { + dst: Box<Write + Send>, + registry: Option<Registry>, + cm: Rc<CodeMapper + 'static>, +} + +impl JsonEmitter { + pub fn stderr(registry: Option<Registry>, + code_map: Rc<CodeMap>) -> JsonEmitter { + JsonEmitter { + dst: Box::new(io::stderr()), + registry: registry, + cm: code_map, + } + } + + pub fn basic() -> JsonEmitter { + JsonEmitter::stderr(None, Rc::new(CodeMap::new())) + } + + pub fn new(dst: Box<Write + Send>, + registry: Option<Registry>, + code_map: Rc<CodeMap>) -> JsonEmitter { + JsonEmitter { + dst: dst, + registry: registry, + cm: code_map, + } + } +} + +impl Emitter for JsonEmitter { + fn emit(&mut self, db: &DiagnosticBuilder) { + let data = Diagnostic::from_diagnostic_builder(db, self); + if let Err(e) = writeln!(&mut self.dst, "{}", as_json(&data)) { + panic!("failed to print diagnostics: {:?}", e); + } + } +} + +// The following data types are provided just for serialisation. + +#[derive(RustcEncodable)] +struct Diagnostic<'a> { + /// The primary error message. + message: &'a str, + code: Option<DiagnosticCode>, + /// "error: internal compiler error", "error", "warning", "note", "help". + level: &'static str, + spans: Vec<DiagnosticSpan>, + /// Associated diagnostic messages. + children: Vec<Diagnostic<'a>>, + /// The message as rustc would render it. Currently this is only + /// `Some` for "suggestions", but eventually it will include all + /// snippets. + rendered: Option<String>, +} + +#[derive(RustcEncodable)] +struct DiagnosticSpan { + file_name: String, + byte_start: u32, + byte_end: u32, + /// 1-based. + line_start: usize, + line_end: usize, + /// 1-based, character offset. + column_start: usize, + column_end: usize, + /// Is this a "primary" span -- meaning the point, or one of the points, + /// where the error occurred? + is_primary: bool, + /// Source text from the start of line_start to the end of line_end. + text: Vec<DiagnosticSpanLine>, + /// Label that should be placed at this location (if any) + label: Option<String>, + /// If we are suggesting a replacement, this will contain text + /// that should be sliced in atop this span. You may prefer to + /// load the fully rendered version from the parent `Diagnostic`, + /// however. + suggested_replacement: Option<String>, + /// Macro invocations that created the code at this span, if any. + expansion: Option<Box<DiagnosticSpanMacroExpansion>>, +} + +#[derive(RustcEncodable)] +struct DiagnosticSpanLine { + text: String, + + /// 1-based, character offset in self.text. + highlight_start: usize, + + highlight_end: usize, +} + +#[derive(RustcEncodable)] +struct DiagnosticSpanMacroExpansion { + /// span where macro was applied to generate this code; note that + /// this may itself derive from a macro (if + /// `span.expansion.is_some()`) + span: DiagnosticSpan, + + /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]") + macro_decl_name: String, + + /// span where macro was defined (if known) + def_site_span: Option<DiagnosticSpan>, +} + +#[derive(RustcEncodable)] +struct DiagnosticCode { + /// The code itself. + code: String, + /// An explanation for the code. + explanation: Option<&'static str>, +} + +impl<'a> Diagnostic<'a> { + fn from_diagnostic_builder<'c>(db: &'c DiagnosticBuilder, + je: &JsonEmitter) + -> Diagnostic<'c> { + Diagnostic { + message: &db.message, + code: DiagnosticCode::map_opt_string(db.code.clone(), je), + level: db.level.to_str(), + spans: DiagnosticSpan::from_multispan(&db.span, je), + children: db.children.iter().map(|c| { + Diagnostic::from_sub_diagnostic(c, je) + }).collect(), + rendered: None, + } + } + + fn from_sub_diagnostic<'c>(db: &'c SubDiagnostic, je: &JsonEmitter) -> Diagnostic<'c> { + Diagnostic { + message: &db.message, + code: None, + level: db.level.to_str(), + spans: db.render_span.as_ref() + .map(|sp| DiagnosticSpan::from_render_span(sp, je)) + .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)), + children: vec![], + rendered: db.render_span.as_ref() + .and_then(|rsp| je.render(rsp)), + } + } +} + +impl DiagnosticSpan { + fn from_span_label(span: SpanLabel, + suggestion: Option<&String>, + je: &JsonEmitter) + -> DiagnosticSpan { + Self::from_span_etc(span.span, + span.is_primary, + span.label, + suggestion, + je) + } + + fn from_span_etc(span: Span, + is_primary: bool, + label: Option<String>, + suggestion: Option<&String>, + je: &JsonEmitter) + -> DiagnosticSpan { + // obtain the full backtrace from the `macro_backtrace` + // helper; in some ways, it'd be better to expand the + // backtrace ourselves, but the `macro_backtrace` helper makes + // some decision, such as dropping some frames, and I don't + // want to duplicate that logic here. + let backtrace = je.cm.macro_backtrace(span).into_iter(); + DiagnosticSpan::from_span_full(span, + is_primary, + label, + suggestion, + backtrace, + je) + } + + fn from_span_full(span: Span, + is_primary: bool, + label: Option<String>, + suggestion: Option<&String>, + mut backtrace: vec::IntoIter<MacroBacktrace>, + je: &JsonEmitter) + -> DiagnosticSpan { + let start = je.cm.lookup_char_pos(span.lo); + let end = je.cm.lookup_char_pos(span.hi); + let backtrace_step = backtrace.next().map(|bt| { + let call_site = + Self::from_span_full(bt.call_site, + false, + None, + None, + backtrace, + je); + let def_site_span = bt.def_site_span.map(|sp| { + Self::from_span_full(sp, + false, + None, + None, + vec![].into_iter(), + je) + }); + Box::new(DiagnosticSpanMacroExpansion { + span: call_site, + macro_decl_name: bt.macro_decl_name, + def_site_span: def_site_span, + }) + }); + DiagnosticSpan { + file_name: start.file.name.clone(), + byte_start: span.lo.0, + byte_end: span.hi.0, + line_start: start.line, + line_end: end.line, + column_start: start.col.0 + 1, + column_end: end.col.0 + 1, + is_primary: is_primary, + text: DiagnosticSpanLine::from_span(span, je), + suggested_replacement: suggestion.cloned(), + expansion: backtrace_step, + label: label, + } + } + + fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> { + msp.span_labels() + .into_iter() + .map(|span_str| Self::from_span_label(span_str, None, je)) + .collect() + } + + fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) + -> Vec<DiagnosticSpan> { + assert_eq!(suggestion.msp.span_labels().len(), suggestion.substitutes.len()); + suggestion.msp.span_labels() + .into_iter() + .zip(&suggestion.substitutes) + .map(|(span_label, suggestion)| { + DiagnosticSpan::from_span_label(span_label, + Some(suggestion), + je) + }) + .collect() + } + + fn from_render_span(rsp: &RenderSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> { + match *rsp { + RenderSpan::FullSpan(ref msp) => + DiagnosticSpan::from_multispan(msp, je), + RenderSpan::Suggestion(ref suggestion) => + DiagnosticSpan::from_suggestion(suggestion, je), + } + } +} + +impl DiagnosticSpanLine { + fn line_from_filemap(fm: &syntax_pos::FileMap, + index: usize, + h_start: usize, + h_end: usize) + -> DiagnosticSpanLine { + DiagnosticSpanLine { + text: fm.get_line(index).unwrap().to_owned(), + highlight_start: h_start, + highlight_end: h_end, + } + } + + /// Create a list of DiagnosticSpanLines from span - each line with any part + /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the + /// `span` within the line. + fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> { + je.cm.span_to_lines(span) + .map(|lines| { + let fm = &*lines.file; + lines.lines + .iter() + .map(|line| { + DiagnosticSpanLine::line_from_filemap(fm, + line.line_index, + line.start_col.0 + 1, + line.end_col.0 + 1) + }) + .collect() + }) + .unwrap_or(vec![]) + } +} + +impl DiagnosticCode { + fn map_opt_string(s: Option<String>, je: &JsonEmitter) -> Option<DiagnosticCode> { + s.map(|s| { + + let explanation = je.registry + .as_ref() + .and_then(|registry| registry.find_description(&s)); + + DiagnosticCode { + code: s, + explanation: explanation, + } + }) + } +} + +impl JsonEmitter { + fn render(&self, render_span: &RenderSpan) -> Option<String> { + use std::borrow::Borrow; + + match *render_span { + RenderSpan::FullSpan(_) => { + None + } + RenderSpan::Suggestion(ref suggestion) => { + Some(suggestion.splice_lines(self.cm.borrow())) + } + } + } +} + diff --git a/bash-5.1/vendor/syntex_syntax/src/lib.rs b/bash-5.1/vendor/syntex_syntax/src/lib.rs new file mode 100644 index 0000000..d0f7bbe --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/lib.rs @@ -0,0 +1,135 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Rust parser and macro expander. +//! +//! # Note +//! +//! This API is completely unstable and subject to change. + +#![crate_type = "dylib"] +#![crate_type = "rlib"] +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://doc.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/nightly/", + test(attr(deny(warnings))))] +#![cfg_attr(not(stage0), deny(warnings))] + +extern crate rustc_serialize; +extern crate term; +extern crate libc; +#[macro_use] extern crate log; +#[macro_use] extern crate bitflags; +extern crate syntex_errors as errors; +extern crate syntex_pos as syntax_pos; + +extern crate rustc_serialize as serialize; +extern crate unicode_xid; + +// A variant of 'try!' that panics on an Err. This is used as a crutch on the +// way towards a non-panic!-prone parser. It should be used for fatal parsing +// errors; eventually we plan to convert all code using panictry to just use +// normal try. +// Exported for syntax_ext, not meant for general use. +#[macro_export] +macro_rules! panictry { + ($e:expr) => ({ + use std::result::Result::{Ok, Err}; + use errors::FatalError; + match $e { + Ok(e) => e, + Err(mut e) => { + e.emit(); + panic!(FatalError); + } + } + }) +} + +#[macro_use] +pub mod diagnostics { + #[macro_use] + pub mod macros; + pub mod plugin; + pub mod metadata; +} + +// NB: This module needs to be declared first so diagnostics are +// registered before they are used. +pub mod diagnostic_list; + +pub mod util { + pub mod lev_distance; + pub mod node_count; + pub mod parser; + #[cfg(test)] + pub mod parser_testing; + pub mod small_vector; + pub mod move_map; + + mod thin_vec; + pub use self::thin_vec::ThinVec; +} + +pub mod json; + +pub mod syntax { + pub use ext; + pub use parse; + pub use ast; +} + +pub mod abi; +pub mod ast; +pub mod attr; +pub mod codemap; +#[macro_use] +pub mod config; +pub mod entry; +pub mod feature_gate; +pub mod fold; +pub mod parse; +pub mod ptr; +pub mod show_span; +pub mod std_inject; +pub mod str; +pub mod symbol; +pub mod test; +pub mod tokenstream; +pub mod visit; + +pub mod print { + pub mod pp; + pub mod pprust; +} + +pub mod ext { + pub mod base; + pub mod build; + pub mod decorator; + pub mod env; + pub mod expand; + pub mod placeholders; + pub mod hygiene; + pub mod proc_macro_shim; + pub mod quote; + pub mod source_util; + + pub mod tt { + pub mod transcribe; + pub mod macro_parser; + pub mod macro_rules; + } +} + +#[cfg(test)] +mod test_snippet; + +// __build_diagnostic_array! { libsyntax, DIAGNOSTICS } diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/attr.rs b/bash-5.1/vendor/syntex_syntax/src/parse/attr.rs new file mode 100644 index 0000000..3009bf0 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/attr.rs @@ -0,0 +1,266 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use attr; +use ast; +use syntax_pos::{mk_sp, Span}; +use codemap::spanned; +use parse::common::SeqSep; +use parse::PResult; +use parse::token; +use parse::parser::{Parser, TokenType}; + +#[derive(PartialEq, Eq, Debug)] +enum InnerAttributeParsePolicy<'a> { + Permitted, + NotPermitted { reason: &'a str }, +} + +const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &'static str = "an inner attribute is not \ + permitted in this context"; + +impl<'a> Parser<'a> { + /// Parse attributes that appear before an item + pub fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> { + let mut attrs: Vec<ast::Attribute> = Vec::new(); + let mut just_parsed_doc_comment = false; + loop { + debug!("parse_outer_attributes: self.token={:?}", self.token); + match self.token { + token::Pound => { + let inner_error_reason = if just_parsed_doc_comment { + "an inner attribute is not permitted following an outer doc comment" + } else if !attrs.is_empty() { + "an inner attribute is not permitted following an outer attribute" + } else { + DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG + }; + let inner_parse_policy = + InnerAttributeParsePolicy::NotPermitted { reason: inner_error_reason }; + attrs.push(try!(self.parse_attribute_with_inner_parse_policy(inner_parse_policy))); + just_parsed_doc_comment = false; + } + token::DocComment(s) => { + let Span { lo, hi, .. } = self.span; + let attr = attr::mk_sugared_doc_attr(attr::mk_attr_id(), s, lo, hi); + if attr.style != ast::AttrStyle::Outer { + let mut err = self.fatal("expected outer doc comment"); + err.note("inner doc comments like this (starting with \ + `//!` or `/*!`) can only appear before items"); + return Err(err); + } + attrs.push(attr); + self.bump(); + just_parsed_doc_comment = true; + } + _ => break, + } + } + return Ok(attrs); + } + + /// Matches `attribute = # ! [ meta_item ]` + /// + /// If permit_inner is true, then a leading `!` indicates an inner + /// attribute + pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> { + debug!("parse_attribute: permit_inner={:?} self.token={:?}", + permit_inner, + self.token); + let inner_parse_policy = if permit_inner { + InnerAttributeParsePolicy::Permitted + } else { + InnerAttributeParsePolicy::NotPermitted + { reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG } + }; + self.parse_attribute_with_inner_parse_policy(inner_parse_policy) + } + + /// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy` + /// that prescribes how to handle inner attributes. + fn parse_attribute_with_inner_parse_policy(&mut self, + inner_parse_policy: InnerAttributeParsePolicy) + -> PResult<'a, ast::Attribute> { + debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}", + inner_parse_policy, + self.token); + let (span, value, mut style) = match self.token { + token::Pound => { + let lo = self.span.lo; + self.bump(); + + if inner_parse_policy == InnerAttributeParsePolicy::Permitted { + self.expected_tokens.push(TokenType::Token(token::Not)); + } + let style = if self.token == token::Not { + self.bump(); + if let InnerAttributeParsePolicy::NotPermitted { reason } = inner_parse_policy + { + let span = self.span; + self.diagnostic() + .struct_span_err(span, reason) + .note("inner attributes and doc comments, like `#![no_std]` or \ + `//! My crate`, annotate the item enclosing them, and are \ + usually found at the beginning of source files. Outer \ + attributes and doc comments, like `#[test]` and + `/// My function`, annotate the item following them.") + .emit() + } + ast::AttrStyle::Inner + } else { + ast::AttrStyle::Outer + }; + + try!(self.expect(&token::OpenDelim(token::Bracket))); + let meta_item = try!(self.parse_meta_item()); + try!(self.expect(&token::CloseDelim(token::Bracket))); + let hi = self.prev_span.hi; + + (mk_sp(lo, hi), meta_item, style) + } + _ => { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected `#`, found `{}`", token_str))); + } + }; + + if inner_parse_policy == InnerAttributeParsePolicy::Permitted && + self.token == token::Semi { + self.bump(); + self.span_warn(span, + "this inner attribute syntax is deprecated. The new syntax is \ + `#![foo]`, with a bang and no semicolon"); + style = ast::AttrStyle::Inner; + } + + Ok(ast::Attribute { + id: attr::mk_attr_id(), + style: style, + value: value, + is_sugared_doc: false, + span: span, + }) + } + + /// Parse attributes that appear after the opening of an item. These should + /// be preceded by an exclamation mark, but we accept and warn about one + /// terminated by a semicolon. + + /// matches inner_attrs* + pub fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> { + let mut attrs: Vec<ast::Attribute> = vec![]; + loop { + match self.token { + token::Pound => { + // Don't even try to parse if it's not an inner attribute. + if !self.look_ahead(1, |t| t == &token::Not) { + break; + } + + let attr = try!(self.parse_attribute(true)); + assert!(attr.style == ast::AttrStyle::Inner); + attrs.push(attr); + } + token::DocComment(s) => { + // we need to get the position of this token before we bump. + let Span { lo, hi, .. } = self.span; + let attr = attr::mk_sugared_doc_attr(attr::mk_attr_id(), s, lo, hi); + if attr.style == ast::AttrStyle::Inner { + attrs.push(attr); + self.bump(); + } else { + break; + } + } + _ => break, + } + } + Ok(attrs) + } + + fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> { + let lit = try!(self.parse_lit()); + debug!("Checking if {:?} is unusuffixed.", lit); + + if !lit.node.is_unsuffixed() { + let msg = "suffixed literals are not allowed in attributes"; + self.diagnostic().struct_span_err(lit.span, msg) + .help("instead of using a suffixed literal \ + (1u8, 1.0f32, etc.), use an unsuffixed version \ + (1, 1.0, etc.).") + .emit() + } + + Ok(lit) + } + + /// Per RFC#1559, matches the following grammar: + /// + /// meta_item : IDENT ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ; + /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ; + pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { + let nt_meta = match self.token { + token::Interpolated(ref nt) => match **nt { + token::NtMeta(ref e) => Some(e.clone()), + _ => None, + }, + _ => None, + }; + + if let Some(meta) = nt_meta { + self.bump(); + return Ok(meta); + } + + let lo = self.span.lo; + let ident = try!(self.parse_ident()); + let node = if self.eat(&token::Eq) { + ast::MetaItemKind::NameValue(try!(self.parse_unsuffixed_lit())) + } else if self.token == token::OpenDelim(token::Paren) { + ast::MetaItemKind::List(try!(self.parse_meta_seq())) + } else { + ast::MetaItemKind::Word + }; + let hi = self.prev_span.hi; + Ok(ast::MetaItem { name: ident.name, node: node, span: mk_sp(lo, hi) }) + } + + /// matches meta_item_inner : (meta_item | UNSUFFIXED_LIT) ; + fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> { + let sp = self.span; + let lo = self.span.lo; + + match self.parse_unsuffixed_lit() { + Ok(lit) => { + return Ok(spanned(lo, self.prev_span.hi, ast::NestedMetaItemKind::Literal(lit))) + } + Err(ref mut err) => self.diagnostic().cancel(err) + } + + match self.parse_meta_item() { + Ok(mi) => { + return Ok(spanned(lo, self.prev_span.hi, ast::NestedMetaItemKind::MetaItem(mi))) + } + Err(ref mut err) => self.diagnostic().cancel(err) + } + + let found = self.this_token_to_string(); + let msg = format!("expected unsuffixed literal or identifier, found {}", found); + Err(self.diagnostic().struct_span_err(sp, &msg)) + } + + /// matches meta_seq = ( COMMASEP(meta_item_inner) ) + fn parse_meta_seq(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> { + self.parse_unspanned_seq(&token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p: &mut Parser<'a>| p.parse_meta_item_inner()) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/classify.rs b/bash-5.1/vendor/syntex_syntax/src/parse/classify.rs new file mode 100644 index 0000000..4fe4ec7 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/classify.rs @@ -0,0 +1,56 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Routines the parser uses to classify AST nodes + +// Predicates on exprs and stmts that the pretty-printer and parser use + +use ast::{self, BlockCheckMode}; + +/// Does this expression require a semicolon to be treated +/// as a statement? The negation of this: 'can this expression +/// be used as a statement without a semicolon' -- is used +/// as an early-bail-out in the parser so that, for instance, +/// if true {...} else {...} +/// |x| 5 +/// isn't parsed as (if true {...} else {...} | x) | 5 +pub fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool { + match e.node { + ast::ExprKind::If(..) | + ast::ExprKind::IfLet(..) | + ast::ExprKind::Match(..) | + ast::ExprKind::Block(_) | + ast::ExprKind::While(..) | + ast::ExprKind::WhileLet(..) | + ast::ExprKind::Loop(..) | + ast::ExprKind::ForLoop(..) => false, + _ => true, + } +} + +pub fn expr_is_simple_block(e: &ast::Expr) -> bool { + match e.node { + ast::ExprKind::Block(ref block) => block.rules == BlockCheckMode::Default, + _ => false, + } +} + +/// this statement requires a semicolon after it. +/// note that in one case (stmt_semi), we've already +/// seen the semicolon, and thus don't need another. +pub fn stmt_ends_with_semi(stmt: &ast::StmtKind) -> bool { + match *stmt { + ast::StmtKind::Local(_) => true, + ast::StmtKind::Item(_) => false, + ast::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(e), + ast::StmtKind::Semi(..) => false, + ast::StmtKind::Mac(..) => false, + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/common.rs b/bash-5.1/vendor/syntex_syntax/src/parse/common.rs new file mode 100644 index 0000000..b57708f --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/common.rs @@ -0,0 +1,36 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Common routines shared by parser mods + +use parse::token; + +/// SeqSep : a sequence separator (token) +/// and whether a trailing separator is allowed. +pub struct SeqSep { + pub sep: Option<token::Token>, + pub trailing_sep_allowed: bool, +} + +impl SeqSep { + pub fn trailing_allowed(t: token::Token) -> SeqSep { + SeqSep { + sep: Some(t), + trailing_sep_allowed: true, + } + } + + pub fn none() -> SeqSep { + SeqSep { + sep: None, + trailing_sep_allowed: false, + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/lexer/comments.rs b/bash-5.1/vendor/syntex_syntax/src/parse/lexer/comments.rs new file mode 100644 index 0000000..ba83a55 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/lexer/comments.rs @@ -0,0 +1,456 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use self::CommentStyle::*; + +use ast; +use codemap::CodeMap; +use syntax_pos::{BytePos, CharPos, Pos}; +use errors; +use parse::lexer::is_block_doc_comment; +use parse::lexer::{StringReader, TokenAndSpan}; +use parse::lexer::{is_pattern_whitespace, Reader}; +use parse::lexer; +use print::pprust; +use str::char_at; + +use std::io::Read; +use std::usize; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum CommentStyle { + /// No code on either side of each line of the comment + Isolated, + /// Code exists to the left of the comment + Trailing, + /// Code before /* foo */ and after the comment + Mixed, + /// Just a manual blank line "\n\n", for layout + BlankLine, +} + +#[derive(Clone)] +pub struct Comment { + pub style: CommentStyle, + pub lines: Vec<String>, + pub pos: BytePos, +} + +pub fn is_doc_comment(s: &str) -> bool { + (s.starts_with("///") && super::is_doc_comment(s)) || s.starts_with("//!") || + (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") +} + +pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { + assert!(is_doc_comment(comment)); + if comment.starts_with("//!") || comment.starts_with("/*!") { + ast::AttrStyle::Inner + } else { + ast::AttrStyle::Outer + } +} + +pub fn strip_doc_comment_decoration(comment: &str) -> String { + /// remove whitespace-only lines from the start/end of lines + fn vertical_trim(lines: Vec<String>) -> Vec<String> { + let mut i = 0; + let mut j = lines.len(); + // first line of all-stars should be omitted + if !lines.is_empty() && lines[0].chars().all(|c| c == '*') { + i += 1; + } + while i < j && lines[i].trim().is_empty() { + i += 1; + } + // like the first, a last line of all stars should be omitted + if j > i && + lines[j - 1] + .chars() + .skip(1) + .all(|c| c == '*') { + j -= 1; + } + while j > i && lines[j - 1].trim().is_empty() { + j -= 1; + } + lines[i..j].iter().cloned().collect() + } + + /// remove a "[ \t]*\*" block from each line, if possible + fn horizontal_trim(lines: Vec<String>) -> Vec<String> { + let mut i = usize::MAX; + let mut can_trim = true; + let mut first = true; + for line in &lines { + for (j, c) in line.chars().enumerate() { + if j > i || !"* \t".contains(c) { + can_trim = false; + break; + } + if c == '*' { + if first { + i = j; + first = false; + } else if i != j { + can_trim = false; + } + break; + } + } + if i > line.len() { + can_trim = false; + } + if !can_trim { + break; + } + } + + if can_trim { + lines.iter() + .map(|line| (&line[i + 1..line.len()]).to_string()) + .collect() + } else { + lines + } + } + + // one-line comments lose their prefix + const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; + for prefix in ONELINERS { + if comment.starts_with(*prefix) { + return (&comment[prefix.len()..]).to_string(); + } + } + + if comment.starts_with("/*") { + let lines = comment[3..comment.len() - 2] + .lines() + .map(|s| s.to_string()) + .collect::<Vec<String>>(); + + let lines = vertical_trim(lines); + let lines = horizontal_trim(lines); + + return lines.join("\n"); + } + + panic!("not a doc-comment: {}", comment); +} + +fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { + debug!(">>> blank-line comment"); + comments.push(Comment { + style: BlankLine, + lines: Vec::new(), + pos: rdr.pos, + }); +} + +fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>) { + while is_pattern_whitespace(rdr.ch) && !rdr.is_eof() { + if rdr.ch_is('\n') { + push_blank_line_comment(rdr, &mut *comments); + } + rdr.bump(); + } +} + +fn read_shebang_comment(rdr: &mut StringReader, + code_to_the_left: bool, + comments: &mut Vec<Comment>) { + debug!(">>> shebang comment"); + let p = rdr.pos; + debug!("<<< shebang comment"); + comments.push(Comment { + style: if code_to_the_left { Trailing } else { Isolated }, + lines: vec![rdr.read_one_line_comment()], + pos: p, + }); +} + +fn read_line_comments(rdr: &mut StringReader, + code_to_the_left: bool, + comments: &mut Vec<Comment>) { + debug!(">>> line comments"); + let p = rdr.pos; + let mut lines: Vec<String> = Vec::new(); + while rdr.ch_is('/') && rdr.nextch_is('/') { + let line = rdr.read_one_line_comment(); + debug!("{}", line); + // Doc comments are not put in comments. + if is_doc_comment(&line[..]) { + break; + } + lines.push(line); + rdr.consume_non_eol_whitespace(); + } + debug!("<<< line comments"); + if !lines.is_empty() { + comments.push(Comment { + style: if code_to_the_left { Trailing } else { Isolated }, + lines: lines, + pos: p, + }); + } +} + +/// Returns None if the first col chars of s contain a non-whitespace char. +/// Otherwise returns Some(k) where k is first char offset after that leading +/// whitespace. Note k may be outside bounds of s. +fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { + let len = s.len(); + let mut col = col.to_usize(); + let mut cursor: usize = 0; + while col > 0 && cursor < len { + let ch = char_at(s, cursor); + if !ch.is_whitespace() { + return None; + } + cursor += ch.len_utf8(); + col -= 1; + } + return Some(cursor); +} + +fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String>, s: String, col: CharPos) { + let len = s.len(); + let s1 = match all_whitespace(&s[..], col) { + Some(col) => { + if col < len { + (&s[col..len]).to_string() + } else { + "".to_string() + } + } + None => s, + }; + debug!("pushing line: {}", s1); + lines.push(s1); +} + +fn read_block_comment(rdr: &mut StringReader, + code_to_the_left: bool, + comments: &mut Vec<Comment>) { + debug!(">>> block comment"); + let p = rdr.pos; + let mut lines: Vec<String> = Vec::new(); + let col = rdr.col; + rdr.bump(); + rdr.bump(); + + let mut curr_line = String::from("/*"); + + // doc-comments are not really comments, they are attributes + if (rdr.ch_is('*') && !rdr.nextch_is('*')) || rdr.ch_is('!') { + while !(rdr.ch_is('*') && rdr.nextch_is('/')) && !rdr.is_eof() { + curr_line.push(rdr.ch.unwrap()); + rdr.bump(); + } + if !rdr.is_eof() { + curr_line.push_str("*/"); + rdr.bump(); + rdr.bump(); + } + if is_block_doc_comment(&curr_line[..]) { + return; + } + assert!(!curr_line.contains('\n')); + lines.push(curr_line); + } else { + let mut level: isize = 1; + while level > 0 { + debug!("=== block comment level {}", level); + if rdr.is_eof() { + panic!(rdr.fatal("unterminated block comment")); + } + if rdr.ch_is('\n') { + trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); + curr_line = String::new(); + rdr.bump(); + } else { + curr_line.push(rdr.ch.unwrap()); + if rdr.ch_is('/') && rdr.nextch_is('*') { + rdr.bump(); + rdr.bump(); + curr_line.push('*'); + level += 1; + } else { + if rdr.ch_is('*') && rdr.nextch_is('/') { + rdr.bump(); + rdr.bump(); + curr_line.push('/'); + level -= 1; + } else { + rdr.bump(); + } + } + } + } + if !curr_line.is_empty() { + trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); + } + } + + let mut style = if code_to_the_left { + Trailing + } else { + Isolated + }; + rdr.consume_non_eol_whitespace(); + if !rdr.is_eof() && !rdr.ch_is('\n') && lines.len() == 1 { + style = Mixed; + } + debug!("<<< block comment"); + comments.push(Comment { + style: style, + lines: lines, + pos: p, + }); +} + + +fn consume_comment(rdr: &mut StringReader, + comments: &mut Vec<Comment>, + code_to_the_left: &mut bool, + anything_to_the_left: &mut bool) { + debug!(">>> consume comment"); + if rdr.ch_is('/') && rdr.nextch_is('/') { + read_line_comments(rdr, *code_to_the_left, comments); + *code_to_the_left = false; + *anything_to_the_left = false; + } else if rdr.ch_is('/') && rdr.nextch_is('*') { + read_block_comment(rdr, *code_to_the_left, comments); + *anything_to_the_left = true; + } else if rdr.ch_is('#') && rdr.nextch_is('!') { + read_shebang_comment(rdr, *code_to_the_left, comments); + *code_to_the_left = false; + *anything_to_the_left = false; + } else { + panic!(); + } + debug!("<<< consume comment"); +} + +#[derive(Clone)] +pub struct Literal { + pub lit: String, + pub pos: BytePos, +} + +// it appears this function is called only from pprust... that's +// probably not a good thing. +pub fn gather_comments_and_literals(span_diagnostic: &errors::Handler, + path: String, + srdr: &mut Read) + -> (Vec<Comment>, Vec<Literal>) { + let mut src = Vec::new(); + srdr.read_to_end(&mut src).unwrap(); + let src = String::from_utf8(src).unwrap(); + let cm = CodeMap::new(); + let filemap = cm.new_filemap(path, None, src); + let mut rdr = lexer::StringReader::new_raw(span_diagnostic, filemap); + + let mut comments: Vec<Comment> = Vec::new(); + let mut literals: Vec<Literal> = Vec::new(); + let mut code_to_the_left = false; // Only code + let mut anything_to_the_left = false; // Code or comments + while !rdr.is_eof() { + loop { + // Eat all the whitespace and count blank lines. + rdr.consume_non_eol_whitespace(); + if rdr.ch_is('\n') { + if anything_to_the_left { + rdr.bump(); // The line is not blank, do not count. + } + consume_whitespace_counting_blank_lines(&mut rdr, &mut comments); + code_to_the_left = false; + anything_to_the_left = false; + } + // Eat one comment group + if rdr.peeking_at_comment() { + consume_comment(&mut rdr, &mut comments, + &mut code_to_the_left, &mut anything_to_the_left); + } else { + break + } + } + + let bstart = rdr.pos; + rdr.next_token(); + // discard, and look ahead; we're working with internal state + let TokenAndSpan { tok, sp } = rdr.peek(); + if tok.is_lit() { + rdr.with_str_from(bstart, |s| { + debug!("tok lit: {}", s); + literals.push(Literal { + lit: s.to_string(), + pos: sp.lo, + }); + }) + } else { + debug!("tok: {}", pprust::token_to_string(&tok)); + } + code_to_the_left = true; + anything_to_the_left = true; + } + + (comments, literals) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_block_doc_comment_1() { + let comment = "/**\n * Test \n ** Test\n * Test\n*/"; + let stripped = strip_doc_comment_decoration(comment); + assert_eq!(stripped, " Test \n* Test\n Test"); + } + + #[test] + fn test_block_doc_comment_2() { + let comment = "/**\n * Test\n * Test\n*/"; + let stripped = strip_doc_comment_decoration(comment); + assert_eq!(stripped, " Test\n Test"); + } + + #[test] + fn test_block_doc_comment_3() { + let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; + let stripped = strip_doc_comment_decoration(comment); + assert_eq!(stripped, " let a: *i32;\n *a = 5;"); + } + + #[test] + fn test_block_doc_comment_4() { + let comment = "/*******************\n test\n *********************/"; + let stripped = strip_doc_comment_decoration(comment); + assert_eq!(stripped, " test"); + } + + #[test] + fn test_line_doc_comment() { + let stripped = strip_doc_comment_decoration("/// test"); + assert_eq!(stripped, " test"); + let stripped = strip_doc_comment_decoration("///! test"); + assert_eq!(stripped, " test"); + let stripped = strip_doc_comment_decoration("// test"); + assert_eq!(stripped, " test"); + let stripped = strip_doc_comment_decoration("// test"); + assert_eq!(stripped, " test"); + let stripped = strip_doc_comment_decoration("///test"); + assert_eq!(stripped, "test"); + let stripped = strip_doc_comment_decoration("///!test"); + assert_eq!(stripped, "test"); + let stripped = strip_doc_comment_decoration("//test"); + assert_eq!(stripped, "test"); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/lexer/mod.rs b/bash-5.1/vendor/syntex_syntax/src/parse/lexer/mod.rs new file mode 100644 index 0000000..2c281d9 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/lexer/mod.rs @@ -0,0 +1,1929 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast::{self, Ident}; +use syntax_pos::{self, BytePos, CharPos, Pos, Span}; +use codemap::CodeMap; +use errors::{FatalError, Handler, DiagnosticBuilder}; +use ext::tt::transcribe::tt_next_token; +use parse::token; +use str::char_at; +use symbol::{Symbol, keywords}; + +use std::borrow::Cow; +use std::char; +use std::mem::replace; +use std::rc::Rc; + +use unicode_xid::UnicodeXID; + +pub use ext::tt::transcribe::{TtReader, new_tt_reader}; + +pub mod comments; +mod unicode_chars; + +pub trait Reader { + fn is_eof(&self) -> bool; + fn try_next_token(&mut self) -> Result<TokenAndSpan, ()>; + fn next_token(&mut self) -> TokenAndSpan where Self: Sized { + let res = self.try_next_token(); + self.unwrap_or_abort(res) + } + /// Report a fatal error with the current span. + fn fatal(&self, &str) -> FatalError; + /// Report a non-fatal error with the current span. + fn err(&self, &str); + fn emit_fatal_errors(&mut self); + fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan { + match res { + Ok(tok) => tok, + Err(_) => { + self.emit_fatal_errors(); + panic!(FatalError); + } + } + } + fn peek(&self) -> TokenAndSpan; + /// Get a token the parser cares about. + fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> { + let mut t = try!(self.try_next_token()); + loop { + match t.tok { + token::Whitespace | token::Comment | token::Shebang(_) => { + t = try!(self.try_next_token()); + } + _ => break, + } + } + Ok(t) + } + fn real_token(&mut self) -> TokenAndSpan { + let res = self.try_real_token(); + self.unwrap_or_abort(res) + } +} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct TokenAndSpan { + pub tok: token::Token, + pub sp: Span, +} + +impl Default for TokenAndSpan { + fn default() -> Self { + TokenAndSpan { tok: token::Underscore, sp: syntax_pos::DUMMY_SP } + } +} + +pub struct StringReader<'a> { + pub span_diagnostic: &'a Handler, + /// The absolute offset within the codemap of the next character to read + pub next_pos: BytePos, + /// The absolute offset within the codemap of the current character + pub pos: BytePos, + /// The column of the next character to read + pub col: CharPos, + /// The current character (which has been read from self.pos) + pub ch: Option<char>, + pub filemap: Rc<syntax_pos::FileMap>, + /// If Some, stop reading the source at this position (inclusive). + pub terminator: Option<BytePos>, + /// Whether to record new-lines in filemap. This is only necessary the first + /// time a filemap is lexed. If part of a filemap is being re-lexed, this + /// should be set to false. + pub save_new_lines: bool, + // cached: + pub peek_tok: token::Token, + pub peek_span: Span, + pub fatal_errs: Vec<DiagnosticBuilder<'a>>, + // cache a direct reference to the source text, so that we don't have to + // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time. + source_text: Rc<String>, +} + +impl<'a> Reader for StringReader<'a> { + fn is_eof(&self) -> bool { + if self.ch.is_none() { + return true; + } + + match self.terminator { + Some(t) => self.next_pos > t, + None => false, + } + } + /// Return the next token. EFFECT: advances the string_reader. + fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> { + assert!(self.fatal_errs.is_empty()); + let ret_val = TokenAndSpan { + tok: replace(&mut self.peek_tok, token::Underscore), + sp: self.peek_span, + }; + try!(self.advance_token()); + Ok(ret_val) + } + fn fatal(&self, m: &str) -> FatalError { + self.fatal_span(self.peek_span, m) + } + fn err(&self, m: &str) { + self.err_span(self.peek_span, m) + } + fn emit_fatal_errors(&mut self) { + for err in &mut self.fatal_errs { + err.emit(); + } + self.fatal_errs.clear(); + } + fn peek(&self) -> TokenAndSpan { + // FIXME(pcwalton): Bad copy! + TokenAndSpan { + tok: self.peek_tok.clone(), + sp: self.peek_span, + } + } +} + +impl<'a> Reader for TtReader<'a> { + fn is_eof(&self) -> bool { + self.peek().tok == token::Eof + } + fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> { + assert!(self.fatal_errs.is_empty()); + let r = tt_next_token(self); + debug!("TtReader: r={:?}", r); + Ok(r) + } + fn fatal(&self, m: &str) -> FatalError { + self.sp_diag.span_fatal(self.cur_span, m) + } + fn err(&self, m: &str) { + self.sp_diag.span_err(self.cur_span, m); + } + fn emit_fatal_errors(&mut self) { + for err in &mut self.fatal_errs { + err.emit(); + } + self.fatal_errs.clear(); + } + fn peek(&self) -> TokenAndSpan { + TokenAndSpan { + tok: self.cur_tok.clone(), + sp: self.cur_span, + } + } +} + +impl<'a> StringReader<'a> { + /// For comments.rs, which hackily pokes into next_pos and ch + pub fn new_raw<'b>(span_diagnostic: &'b Handler, + filemap: Rc<syntax_pos::FileMap>) + -> StringReader<'b> { + let mut sr = StringReader::new_raw_internal(span_diagnostic, filemap); + sr.bump(); + sr + } + + fn new_raw_internal<'b>(span_diagnostic: &'b Handler, + filemap: Rc<syntax_pos::FileMap>) + -> StringReader<'b> { + if filemap.src.is_none() { + span_diagnostic.bug(&format!("Cannot lex filemap \ + without source: {}", + filemap.name)[..]); + } + + let source_text = (*filemap.src.as_ref().unwrap()).clone(); + + StringReader { + span_diagnostic: span_diagnostic, + next_pos: filemap.start_pos, + pos: filemap.start_pos, + col: CharPos(0), + ch: Some('\n'), + filemap: filemap, + terminator: None, + save_new_lines: true, + // dummy values; not read + peek_tok: token::Eof, + peek_span: syntax_pos::DUMMY_SP, + source_text: source_text, + fatal_errs: Vec::new(), + } + } + + pub fn new<'b>(span_diagnostic: &'b Handler, + filemap: Rc<syntax_pos::FileMap>) + -> StringReader<'b> { + let mut sr = StringReader::new_raw(span_diagnostic, filemap); + if let Err(_) = sr.advance_token() { + sr.emit_fatal_errors(); + panic!(FatalError); + } + sr + } + + pub fn ch_is(&self, c: char) -> bool { + self.ch == Some(c) + } + + /// Report a fatal lexical error with a given span. + pub fn fatal_span(&self, sp: Span, m: &str) -> FatalError { + self.span_diagnostic.span_fatal(sp, m) + } + + /// Report a lexical error with a given span. + pub fn err_span(&self, sp: Span, m: &str) { + self.span_diagnostic.span_err(sp, m) + } + + + /// Report a fatal error spanning [`from_pos`, `to_pos`). + fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError { + self.fatal_span(syntax_pos::mk_sp(from_pos, to_pos), m) + } + + /// Report a lexical error spanning [`from_pos`, `to_pos`). + fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) { + self.err_span(syntax_pos::mk_sp(from_pos, to_pos), m) + } + + /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an + /// escaped character to the error message + fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError { + let mut m = m.to_string(); + m.push_str(": "); + for c in c.escape_default() { + m.push(c) + } + self.fatal_span_(from_pos, to_pos, &m[..]) + } + fn struct_fatal_span_char(&self, + from_pos: BytePos, + to_pos: BytePos, + m: &str, + c: char) + -> DiagnosticBuilder<'a> { + let mut m = m.to_string(); + m.push_str(": "); + for c in c.escape_default() { + m.push(c) + } + self.span_diagnostic.struct_span_fatal(syntax_pos::mk_sp(from_pos, to_pos), &m[..]) + } + + /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an + /// escaped character to the error message + fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) { + let mut m = m.to_string(); + m.push_str(": "); + for c in c.escape_default() { + m.push(c) + } + self.err_span_(from_pos, to_pos, &m[..]); + } + fn struct_err_span_char(&self, + from_pos: BytePos, + to_pos: BytePos, + m: &str, + c: char) + -> DiagnosticBuilder<'a> { + let mut m = m.to_string(); + m.push_str(": "); + for c in c.escape_default() { + m.push(c) + } + self.span_diagnostic.struct_span_err(syntax_pos::mk_sp(from_pos, to_pos), &m[..]) + } + + /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the + /// offending string to the error message + fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError { + m.push_str(": "); + let from = self.byte_offset(from_pos).to_usize(); + let to = self.byte_offset(to_pos).to_usize(); + m.push_str(&self.source_text[from..to]); + self.fatal_span_(from_pos, to_pos, &m[..]) + } + + /// Advance peek_tok and peek_span to refer to the next token, and + /// possibly update the interner. + fn advance_token(&mut self) -> Result<(), ()> { + match self.scan_whitespace_or_comment() { + Some(comment) => { + self.peek_span = comment.sp; + self.peek_tok = comment.tok; + } + None => { + if self.is_eof() { + self.peek_tok = token::Eof; + self.peek_span = syntax_pos::mk_sp(self.filemap.end_pos, self.filemap.end_pos); + } else { + let start_bytepos = self.pos; + self.peek_tok = try!(self.next_token_inner()); + self.peek_span = syntax_pos::mk_sp(start_bytepos, self.pos); + }; + } + } + Ok(()) + } + + fn byte_offset(&self, pos: BytePos) -> BytePos { + (pos - self.filemap.start_pos) + } + + /// Calls `f` with a string slice of the source text spanning from `start` + /// up to but excluding `self.pos`, meaning the slice does not include + /// the character `self.ch`. + pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T + where F: FnOnce(&str) -> T + { + self.with_str_from_to(start, self.pos, f) + } + + /// Create a Name from a given offset to the current offset, each + /// adjusted 1 towards each other (assumes that on either side there is a + /// single-byte delimiter). + pub fn name_from(&self, start: BytePos) -> ast::Name { + debug!("taking an ident from {:?} to {:?}", start, self.pos); + self.with_str_from(start, Symbol::intern) + } + + /// As name_from, with an explicit endpoint. + pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name { + debug!("taking an ident from {:?} to {:?}", start, end); + self.with_str_from_to(start, end, Symbol::intern) + } + + /// Calls `f` with a string slice of the source text spanning from `start` + /// up to but excluding `end`. + fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T + where F: FnOnce(&str) -> T + { + f(&self.source_text[self.byte_offset(start).to_usize()..self.byte_offset(end).to_usize()]) + } + + /// Converts CRLF to LF in the given string, raising an error on bare CR. + fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> { + let mut i = 0; + while i < s.len() { + let ch = char_at(s, i); + let next = i + ch.len_utf8(); + if ch == '\r' { + if next < s.len() && char_at(s, next) == '\n' { + return translate_crlf_(self, start, s, errmsg, i).into(); + } + let pos = start + BytePos(i as u32); + let end_pos = start + BytePos(next as u32); + self.err_span_(pos, end_pos, errmsg); + } + i = next; + } + return s.into(); + + fn translate_crlf_(rdr: &StringReader, + start: BytePos, + s: &str, + errmsg: &str, + mut i: usize) + -> String { + let mut buf = String::with_capacity(s.len()); + let mut j = 0; + while i < s.len() { + let ch = char_at(s, i); + let next = i + ch.len_utf8(); + if ch == '\r' { + if j < i { + buf.push_str(&s[j..i]); + } + j = next; + if next >= s.len() || char_at(s, next) != '\n' { + let pos = start + BytePos(i as u32); + let end_pos = start + BytePos(next as u32); + rdr.err_span_(pos, end_pos, errmsg); + } + } + i = next; + } + if j < s.len() { + buf.push_str(&s[j..]); + } + buf + } + } + + + /// Advance the StringReader by one character. If a newline is + /// discovered, add it to the FileMap's list of line start offsets. + pub fn bump(&mut self) { + let new_pos = self.next_pos; + let new_byte_offset = self.byte_offset(new_pos).to_usize(); + if new_byte_offset < self.source_text.len() { + let old_ch_is_newline = self.ch.unwrap() == '\n'; + let new_ch = char_at(&self.source_text, new_byte_offset); + let new_ch_len = new_ch.len_utf8(); + + self.ch = Some(new_ch); + self.pos = new_pos; + self.next_pos = new_pos + Pos::from_usize(new_ch_len); + if old_ch_is_newline { + if self.save_new_lines { + self.filemap.next_line(self.pos); + } + self.col = CharPos(0); + } else { + self.col = self.col + CharPos(1); + } + if new_ch_len > 1 { + self.filemap.record_multibyte_char(self.pos, new_ch_len); + } + } else { + self.ch = None; + self.pos = new_pos; + } + } + + pub fn nextch(&self) -> Option<char> { + let offset = self.byte_offset(self.next_pos).to_usize(); + if offset < self.source_text.len() { + Some(char_at(&self.source_text, offset)) + } else { + None + } + } + + pub fn nextch_is(&self, c: char) -> bool { + self.nextch() == Some(c) + } + + pub fn nextnextch(&self) -> Option<char> { + let offset = self.byte_offset(self.next_pos).to_usize(); + let s = &self.source_text[..]; + if offset >= s.len() { + return None; + } + let next = offset + char_at(s, offset).len_utf8(); + if next < s.len() { + Some(char_at(s, next)) + } else { + None + } + } + + pub fn nextnextch_is(&self, c: char) -> bool { + self.nextnextch() == Some(c) + } + + /// Eats <XID_start><XID_continue>*, if possible. + fn scan_optional_raw_name(&mut self) -> Option<ast::Name> { + if !ident_start(self.ch) { + return None; + } + let start = self.pos; + while ident_continue(self.ch) { + self.bump(); + } + + self.with_str_from(start, |string| { + if string == "_" { + None + } else { + Some(Symbol::intern(string)) + } + }) + } + + /// PRECONDITION: self.ch is not whitespace + /// Eats any kind of comment. + fn scan_comment(&mut self) -> Option<TokenAndSpan> { + if let Some(c) = self.ch { + if c.is_whitespace() { + self.span_diagnostic.span_err(syntax_pos::mk_sp(self.pos, self.pos), + "called consume_any_line_comment, but there \ + was whitespace"); + } + } + + if self.ch_is('/') { + match self.nextch() { + Some('/') => { + self.bump(); + self.bump(); + + // line comments starting with "///" or "//!" are doc-comments + let doc_comment = self.ch_is('/') || self.ch_is('!'); + let start_bpos = self.pos - BytePos(2); + + while !self.is_eof() { + match self.ch.unwrap() { + '\n' => break, + '\r' => { + if self.nextch_is('\n') { + // CRLF + break; + } else if doc_comment { + self.err_span_(self.pos, + self.next_pos, + "bare CR not allowed in doc-comment"); + } + } + _ => (), + } + self.bump(); + } + + return if doc_comment { + self.with_str_from(start_bpos, |string| { + // comments with only more "/"s are not doc comments + let tok = if is_doc_comment(string) { + token::DocComment(Symbol::intern(string)) + } else { + token::Comment + }; + + Some(TokenAndSpan { + tok: tok, + sp: syntax_pos::mk_sp(start_bpos, self.pos), + }) + }) + } else { + Some(TokenAndSpan { + tok: token::Comment, + sp: syntax_pos::mk_sp(start_bpos, self.pos), + }) + }; + } + Some('*') => { + self.bump(); + self.bump(); + self.scan_block_comment() + } + _ => None, + } + } else if self.ch_is('#') { + if self.nextch_is('!') { + + // Parse an inner attribute. + if self.nextnextch_is('[') { + return None; + } + + // I guess this is the only way to figure out if + // we're at the beginning of the file... + let cmap = CodeMap::new(); + cmap.files.borrow_mut().push(self.filemap.clone()); + let loc = cmap.lookup_char_pos_adj(self.pos); + debug!("Skipping a shebang"); + if loc.line == 1 && loc.col == CharPos(0) { + // FIXME: Add shebang "token", return it + let start = self.pos; + while !self.ch_is('\n') && !self.is_eof() { + self.bump(); + } + return Some(TokenAndSpan { + tok: token::Shebang(self.name_from(start)), + sp: syntax_pos::mk_sp(start, self.pos), + }); + } + } + None + } else { + None + } + } + + /// If there is whitespace, shebang, or a comment, scan it. Otherwise, + /// return None. + fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> { + match self.ch.unwrap_or('\0') { + // # to handle shebang at start of file -- this is the entry point + // for skipping over all "junk" + '/' | '#' => { + let c = self.scan_comment(); + debug!("scanning a comment {:?}", c); + c + }, + c if is_pattern_whitespace(Some(c)) => { + let start_bpos = self.pos; + while is_pattern_whitespace(self.ch) { + self.bump(); + } + let c = Some(TokenAndSpan { + tok: token::Whitespace, + sp: syntax_pos::mk_sp(start_bpos, self.pos), + }); + debug!("scanning whitespace: {:?}", c); + c + } + _ => None, + } + } + + /// Might return a sugared-doc-attr + fn scan_block_comment(&mut self) -> Option<TokenAndSpan> { + // block comments starting with "/**" or "/*!" are doc-comments + let is_doc_comment = self.ch_is('*') || self.ch_is('!'); + let start_bpos = self.pos - BytePos(2); + + let mut level: isize = 1; + let mut has_cr = false; + while level > 0 { + if self.is_eof() { + let msg = if is_doc_comment { + "unterminated block doc-comment" + } else { + "unterminated block comment" + }; + let last_bpos = self.pos; + panic!(self.fatal_span_(start_bpos, last_bpos, msg)); + } + let n = self.ch.unwrap(); + match n { + '/' if self.nextch_is('*') => { + level += 1; + self.bump(); + } + '*' if self.nextch_is('/') => { + level -= 1; + self.bump(); + } + '\r' => { + has_cr = true; + } + _ => (), + } + self.bump(); + } + + self.with_str_from(start_bpos, |string| { + // but comments with only "*"s between two "/"s are not + let tok = if is_block_doc_comment(string) { + let string = if has_cr { + self.translate_crlf(start_bpos, + string, + "bare CR not allowed in block doc-comment") + } else { + string.into() + }; + token::DocComment(Symbol::intern(&string[..])) + } else { + token::Comment + }; + + Some(TokenAndSpan { + tok: tok, + sp: syntax_pos::mk_sp(start_bpos, self.pos), + }) + }) + } + + /// Scan through any digits (base `scan_radix`) or underscores, + /// and return how many digits there were. + /// + /// `real_radix` represents the true radix of the number we're + /// interested in, and errors will be emitted for any digits + /// between `real_radix` and `scan_radix`. + fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize { + assert!(real_radix <= scan_radix); + let mut len = 0; + loop { + let c = self.ch; + if c == Some('_') { + debug!("skipping a _"); + self.bump(); + continue; + } + match c.and_then(|cc| cc.to_digit(scan_radix)) { + Some(_) => { + debug!("{:?} in scan_digits", c); + // check that the hypothetical digit is actually + // in range for the true radix + if c.unwrap().to_digit(real_radix).is_none() { + self.err_span_(self.pos, + self.next_pos, + &format!("invalid digit for a base {} literal", real_radix)); + } + len += 1; + self.bump(); + } + _ => return len, + } + } + } + + /// Lex a LIT_INTEGER or a LIT_FLOAT + fn scan_number(&mut self, c: char) -> token::Lit { + let num_digits; + let mut base = 10; + let start_bpos = self.pos; + + self.bump(); + + if c == '0' { + match self.ch.unwrap_or('\0') { + 'b' => { + self.bump(); + base = 2; + num_digits = self.scan_digits(2, 10); + } + 'o' => { + self.bump(); + base = 8; + num_digits = self.scan_digits(8, 10); + } + 'x' => { + self.bump(); + base = 16; + num_digits = self.scan_digits(16, 16); + } + '0'...'9' | '_' | '.' => { + num_digits = self.scan_digits(10, 10) + 1; + } + _ => { + // just a 0 + return token::Integer(self.name_from(start_bpos)); + } + } + } else if c.is_digit(10) { + num_digits = self.scan_digits(10, 10) + 1; + } else { + num_digits = 0; + } + + if num_digits == 0 { + self.err_span_(start_bpos, + self.pos, + "no valid digits found for number"); + return token::Integer(Symbol::intern("0")); + } + + // might be a float, but don't be greedy if this is actually an + // integer literal followed by field/method access or a range pattern + // (`0..2` and `12.foo()`) + if self.ch_is('.') && !self.nextch_is('.') && + !UnicodeXID::is_xid_start(self.nextch().unwrap_or('\0')) + { + // might have stuff after the ., and if it does, it needs to start + // with a number + self.bump(); + if self.ch.unwrap_or('\0').is_digit(10) { + self.scan_digits(10, 10); + self.scan_float_exponent(); + } + let pos = self.pos; + self.check_float_base(start_bpos, pos, base); + return token::Float(self.name_from(start_bpos)); + } else { + // it might be a float if it has an exponent + if self.ch_is('e') || self.ch_is('E') { + self.scan_float_exponent(); + let pos = self.pos; + self.check_float_base(start_bpos, pos, base); + return token::Float(self.name_from(start_bpos)); + } + // but we certainly have an integer! + return token::Integer(self.name_from(start_bpos)); + } + } + + /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an + /// error if too many or too few digits are encountered. + fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool { + debug!("scanning {} digits until {:?}", n_digits, delim); + let start_bpos = self.pos; + let mut accum_int = 0; + + let mut valid = true; + for _ in 0..n_digits { + if self.is_eof() { + let last_bpos = self.pos; + panic!(self.fatal_span_(start_bpos, + last_bpos, + "unterminated numeric character escape")); + } + if self.ch_is(delim) { + let last_bpos = self.pos; + self.err_span_(start_bpos, + last_bpos, + "numeric character escape is too short"); + valid = false; + break; + } + let c = self.ch.unwrap_or('\x00'); + accum_int *= 16; + accum_int += c.to_digit(16).unwrap_or_else(|| { + self.err_span_char(self.pos, + self.next_pos, + "invalid character in numeric character escape", + c); + + valid = false; + 0 + }); + self.bump(); + } + + if below_0x7f_only && accum_int >= 0x80 { + self.err_span_(start_bpos, + self.pos, + "this form of character escape may only be used with characters in \ + the range [\\x00-\\x7f]"); + valid = false; + } + + match char::from_u32(accum_int) { + Some(_) => valid, + None => { + let last_bpos = self.pos; + self.err_span_(start_bpos, last_bpos, "invalid numeric character escape"); + false + } + } + } + + /// Scan for a single (possibly escaped) byte or char + /// in a byte, (non-raw) byte string, char, or (non-raw) string literal. + /// `start` is the position of `first_source_char`, which is already consumed. + /// + /// Returns true if there was a valid char/byte, false otherwise. + fn scan_char_or_byte(&mut self, + start: BytePos, + first_source_char: char, + ascii_only: bool, + delim: char) + -> bool { + match first_source_char { + '\\' => { + // '\X' for some X must be a character constant: + let escaped = self.ch; + let escaped_pos = self.pos; + self.bump(); + match escaped { + None => {} // EOF here is an error that will be checked later. + Some(e) => { + return match e { + 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true, + 'x' => self.scan_byte_escape(delim, !ascii_only), + 'u' => { + let valid = if self.ch_is('{') { + self.scan_unicode_escape(delim) && !ascii_only + } else { + let span = syntax_pos::mk_sp(start, self.pos); + self.span_diagnostic + .struct_span_err(span, "incorrect unicode escape sequence") + .span_help(span, + "format of unicode escape sequences is \ + `\\u{…}`") + .emit(); + false + }; + if ascii_only { + self.err_span_(start, + self.pos, + "unicode escape sequences cannot be used as a \ + byte or in a byte string"); + } + valid + + } + '\n' if delim == '"' => { + self.consume_whitespace(); + true + } + '\r' if delim == '"' && self.ch_is('\n') => { + self.consume_whitespace(); + true + } + c => { + let pos = self.pos; + let mut err = self.struct_err_span_char(escaped_pos, + pos, + if ascii_only { + "unknown byte escape" + } else { + "unknown character \ + escape" + }, + c); + if e == '\r' { + err.span_help(syntax_pos::mk_sp(escaped_pos, pos), + "this is an isolated carriage return; consider \ + checking your editor and version control \ + settings"); + } + if (e == '{' || e == '}') && !ascii_only { + err.span_help(syntax_pos::mk_sp(escaped_pos, pos), + "if used in a formatting string, curly braces \ + are escaped with `{{` and `}}`"); + } + err.emit(); + false + } + } + } + } + } + '\t' | '\n' | '\r' | '\'' if delim == '\'' => { + let pos = self.pos; + self.err_span_char(start, + pos, + if ascii_only { + "byte constant must be escaped" + } else { + "character constant must be escaped" + }, + first_source_char); + return false; + } + '\r' => { + if self.ch_is('\n') { + self.bump(); + return true; + } else { + self.err_span_(start, + self.pos, + "bare CR not allowed in string, use \\r instead"); + return false; + } + } + _ => { + if ascii_only && first_source_char > '\x7F' { + let pos = self.pos; + self.err_span_(start, + pos, + "byte constant must be ASCII. Use a \\xHH escape for a \ + non-ASCII byte"); + return false; + } + } + } + true + } + + /// Scan over a \u{...} escape + /// + /// At this point, we have already seen the \ and the u, the { is the current character. We + /// will read at least one digit, and up to 6, and pass over the }. + fn scan_unicode_escape(&mut self, delim: char) -> bool { + self.bump(); // past the { + let start_bpos = self.pos; + let mut count = 0; + let mut accum_int = 0; + let mut valid = true; + + while !self.ch_is('}') && count <= 6 { + let c = match self.ch { + Some(c) => c, + None => { + panic!(self.fatal_span_(start_bpos, + self.pos, + "unterminated unicode escape (found EOF)")); + } + }; + accum_int *= 16; + accum_int += c.to_digit(16).unwrap_or_else(|| { + if c == delim { + panic!(self.fatal_span_(self.pos, + self.next_pos, + "unterminated unicode escape (needed a `}`)")); + } else { + self.err_span_char(self.pos, + self.next_pos, + "invalid character in unicode escape", + c); + } + valid = false; + 0 + }); + self.bump(); + count += 1; + } + + if count > 6 { + self.err_span_(start_bpos, + self.pos, + "overlong unicode escape (can have at most 6 hex digits)"); + valid = false; + } + + if valid && (char::from_u32(accum_int).is_none() || count == 0) { + self.err_span_(start_bpos, + self.pos, + "invalid unicode character escape"); + valid = false; + } + + self.bump(); // past the ending } + valid + } + + /// Scan over a float exponent. + fn scan_float_exponent(&mut self) { + if self.ch_is('e') || self.ch_is('E') { + self.bump(); + if self.ch_is('-') || self.ch_is('+') { + self.bump(); + } + if self.scan_digits(10, 10) == 0 { + self.err_span_(self.pos, + self.next_pos, + "expected at least one digit in exponent") + } + } + } + + /// Check that a base is valid for a floating literal, emitting a nice + /// error if it isn't. + fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) { + match base { + 16 => { + self.err_span_(start_bpos, + last_bpos, + "hexadecimal float literal is not supported") + } + 8 => { + self.err_span_(start_bpos, + last_bpos, + "octal float literal is not supported") + } + 2 => { + self.err_span_(start_bpos, + last_bpos, + "binary float literal is not supported") + } + _ => (), + } + } + + fn binop(&mut self, op: token::BinOpToken) -> token::Token { + self.bump(); + if self.ch_is('=') { + self.bump(); + return token::BinOpEq(op); + } else { + return token::BinOp(op); + } + } + + /// Return the next token from the string, advances the input past that + /// token, and updates the interner + fn next_token_inner(&mut self) -> Result<token::Token, ()> { + let c = self.ch; + if ident_start(c) && + match (c.unwrap(), self.nextch(), self.nextnextch()) { + // Note: r as in r" or r#" is part of a raw string literal, + // b as in b' is part of a byte literal. + // They are not identifiers, and are handled further down. + ('r', Some('"'), _) | + ('r', Some('#'), _) | + ('b', Some('"'), _) | + ('b', Some('\''), _) | + ('b', Some('r'), Some('"')) | + ('b', Some('r'), Some('#')) => false, + _ => true, + } { + let start = self.pos; + while ident_continue(self.ch) { + self.bump(); + } + + return Ok(self.with_str_from(start, |string| { + if string == "_" { + token::Underscore + } else { + // FIXME: perform NFKC normalization here. (Issue #2253) + token::Ident(Ident::from_str(string)) + } + })); + } + + if is_dec_digit(c) { + let num = self.scan_number(c.unwrap()); + let suffix = self.scan_optional_raw_name(); + debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix); + return Ok(token::Literal(num, suffix)); + } + + match c.expect("next_token_inner called at EOF") { + // One-byte tokens. + ';' => { + self.bump(); + return Ok(token::Semi); + } + ',' => { + self.bump(); + return Ok(token::Comma); + } + '.' => { + self.bump(); + return if self.ch_is('.') { + self.bump(); + if self.ch_is('.') { + self.bump(); + Ok(token::DotDotDot) + } else { + Ok(token::DotDot) + } + } else { + Ok(token::Dot) + }; + } + '(' => { + self.bump(); + return Ok(token::OpenDelim(token::Paren)); + } + ')' => { + self.bump(); + return Ok(token::CloseDelim(token::Paren)); + } + '{' => { + self.bump(); + return Ok(token::OpenDelim(token::Brace)); + } + '}' => { + self.bump(); + return Ok(token::CloseDelim(token::Brace)); + } + '[' => { + self.bump(); + return Ok(token::OpenDelim(token::Bracket)); + } + ']' => { + self.bump(); + return Ok(token::CloseDelim(token::Bracket)); + } + '@' => { + self.bump(); + return Ok(token::At); + } + '#' => { + self.bump(); + return Ok(token::Pound); + } + '~' => { + self.bump(); + return Ok(token::Tilde); + } + '?' => { + self.bump(); + return Ok(token::Question); + } + ':' => { + self.bump(); + if self.ch_is(':') { + self.bump(); + return Ok(token::ModSep); + } else { + return Ok(token::Colon); + } + } + + '$' => { + self.bump(); + return Ok(token::Dollar); + } + + // Multi-byte tokens. + '=' => { + self.bump(); + if self.ch_is('=') { + self.bump(); + return Ok(token::EqEq); + } else if self.ch_is('>') { + self.bump(); + return Ok(token::FatArrow); + } else { + return Ok(token::Eq); + } + } + '!' => { + self.bump(); + if self.ch_is('=') { + self.bump(); + return Ok(token::Ne); + } else { + return Ok(token::Not); + } + } + '<' => { + self.bump(); + match self.ch.unwrap_or('\x00') { + '=' => { + self.bump(); + return Ok(token::Le); + } + '<' => { + return Ok(self.binop(token::Shl)); + } + '-' => { + self.bump(); + match self.ch.unwrap_or('\x00') { + _ => { + return Ok(token::LArrow); + } + } + } + _ => { + return Ok(token::Lt); + } + } + } + '>' => { + self.bump(); + match self.ch.unwrap_or('\x00') { + '=' => { + self.bump(); + return Ok(token::Ge); + } + '>' => { + return Ok(self.binop(token::Shr)); + } + _ => { + return Ok(token::Gt); + } + } + } + '\'' => { + // Either a character constant 'a' OR a lifetime name 'abc + let start_with_quote = self.pos; + self.bump(); + let start = self.pos; + + // the eof will be picked up by the final `'` check below + let c2 = self.ch.unwrap_or('\x00'); + self.bump(); + + // If the character is an ident start not followed by another single + // quote, then this is a lifetime name: + if ident_start(Some(c2)) && !self.ch_is('\'') { + while ident_continue(self.ch) { + self.bump(); + } + // lifetimes shouldn't end with a single quote + // if we find one, then this is an invalid character literal + if self.ch_is('\'') { + panic!(self.fatal_span_verbose( + start_with_quote, self.next_pos, + String::from("character literal may only contain one codepoint"))); + + } + + // Include the leading `'` in the real identifier, for macro + // expansion purposes. See #12512 for the gory details of why + // this is necessary. + let ident = self.with_str_from(start, |lifetime_name| { + Ident::from_str(&format!("'{}", lifetime_name)) + }); + + // Conjure up a "keyword checking ident" to make sure that + // the lifetime name is not a keyword. + let keyword_checking_ident = self.with_str_from(start, |lifetime_name| { + Ident::from_str(lifetime_name) + }); + let keyword_checking_token = &token::Ident(keyword_checking_ident); + let last_bpos = self.pos; + if keyword_checking_token.is_any_keyword() && + !keyword_checking_token.is_keyword(keywords::Static) { + self.err_span_(start, last_bpos, "lifetimes cannot use keyword names"); + } + + return Ok(token::Lifetime(ident)); + } + + let valid = self.scan_char_or_byte(start, + c2, + // ascii_only = + false, + '\''); + + if !self.ch_is('\'') { + panic!(self.fatal_span_verbose( + start_with_quote, self.pos, + String::from("character literal may only contain one codepoint"))); + } + + let id = if valid { + self.name_from(start) + } else { + Symbol::intern("0") + }; + self.bump(); // advance ch past token + let suffix = self.scan_optional_raw_name(); + return Ok(token::Literal(token::Char(id), suffix)); + } + 'b' => { + self.bump(); + let lit = match self.ch { + Some('\'') => self.scan_byte(), + Some('"') => self.scan_byte_string(), + Some('r') => self.scan_raw_byte_string(), + _ => unreachable!(), // Should have been a token::Ident above. + }; + let suffix = self.scan_optional_raw_name(); + return Ok(token::Literal(lit, suffix)); + } + '"' => { + let start_bpos = self.pos; + let mut valid = true; + self.bump(); + while !self.ch_is('"') { + if self.is_eof() { + let last_bpos = self.pos; + panic!(self.fatal_span_(start_bpos, + last_bpos, + "unterminated double quote string")); + } + + let ch_start = self.pos; + let ch = self.ch.unwrap(); + self.bump(); + valid &= self.scan_char_or_byte(ch_start, + ch, + // ascii_only = + false, + '"'); + } + // adjust for the ASCII " at the start of the literal + let id = if valid { + self.name_from(start_bpos + BytePos(1)) + } else { + Symbol::intern("??") + }; + self.bump(); + let suffix = self.scan_optional_raw_name(); + return Ok(token::Literal(token::Str_(id), suffix)); + } + 'r' => { + let start_bpos = self.pos; + self.bump(); + let mut hash_count = 0; + while self.ch_is('#') { + self.bump(); + hash_count += 1; + } + + if self.is_eof() { + let last_bpos = self.pos; + panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string")); + } else if !self.ch_is('"') { + let last_bpos = self.pos; + let curr_char = self.ch.unwrap(); + panic!(self.fatal_span_char(start_bpos, + last_bpos, + "found invalid character; only `#` is allowed \ + in raw string delimitation", + curr_char)); + } + self.bump(); + let content_start_bpos = self.pos; + let mut content_end_bpos; + let mut valid = true; + 'outer: loop { + if self.is_eof() { + let last_bpos = self.pos; + panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string")); + } + // if self.ch_is('"') { + // content_end_bpos = self.pos; + // for _ in 0..hash_count { + // self.bump(); + // if !self.ch_is('#') { + // continue 'outer; + let c = self.ch.unwrap(); + match c { + '"' => { + content_end_bpos = self.pos; + for _ in 0..hash_count { + self.bump(); + if !self.ch_is('#') { + continue 'outer; + } + } + break; + } + '\r' => { + if !self.nextch_is('\n') { + let last_bpos = self.pos; + self.err_span_(start_bpos, + last_bpos, + "bare CR not allowed in raw string, use \\r \ + instead"); + valid = false; + } + } + _ => (), + } + self.bump(); + } + self.bump(); + let id = if valid { + self.name_from_to(content_start_bpos, content_end_bpos) + } else { + Symbol::intern("??") + }; + let suffix = self.scan_optional_raw_name(); + return Ok(token::Literal(token::StrRaw(id, hash_count), suffix)); + } + '-' => { + if self.nextch_is('>') { + self.bump(); + self.bump(); + return Ok(token::RArrow); + } else { + return Ok(self.binop(token::Minus)); + } + } + '&' => { + if self.nextch_is('&') { + self.bump(); + self.bump(); + return Ok(token::AndAnd); + } else { + return Ok(self.binop(token::And)); + } + } + '|' => { + match self.nextch() { + Some('|') => { + self.bump(); + self.bump(); + return Ok(token::OrOr); + } + _ => { + return Ok(self.binop(token::Or)); + } + } + } + '+' => { + return Ok(self.binop(token::Plus)); + } + '*' => { + return Ok(self.binop(token::Star)); + } + '/' => { + return Ok(self.binop(token::Slash)); + } + '^' => { + return Ok(self.binop(token::Caret)); + } + '%' => { + return Ok(self.binop(token::Percent)); + } + c => { + let last_bpos = self.pos; + let bpos = self.next_pos; + let mut err = self.struct_fatal_span_char(last_bpos, + bpos, + "unknown start of token", + c); + unicode_chars::check_for_substitution(&self, c, &mut err); + self.fatal_errs.push(err); + Err(()) + } + } + } + + fn consume_whitespace(&mut self) { + while is_pattern_whitespace(self.ch) && !self.is_eof() { + self.bump(); + } + } + + fn read_to_eol(&mut self) -> String { + let mut val = String::new(); + while !self.ch_is('\n') && !self.is_eof() { + val.push(self.ch.unwrap()); + self.bump(); + } + if self.ch_is('\n') { + self.bump(); + } + return val; + } + + fn read_one_line_comment(&mut self) -> String { + let val = self.read_to_eol(); + assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') || + (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!')); + return val; + } + + fn consume_non_eol_whitespace(&mut self) { + while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() { + self.bump(); + } + } + + fn peeking_at_comment(&self) -> bool { + (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) || + // consider shebangs comments, but not inner attributes + (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('[')) + } + + fn scan_byte(&mut self) -> token::Lit { + self.bump(); + let start = self.pos; + + // the eof will be picked up by the final `'` check below + let c2 = self.ch.unwrap_or('\x00'); + self.bump(); + + let valid = self.scan_char_or_byte(start, + c2, + // ascii_only = + true, + '\''); + if !self.ch_is('\'') { + // Byte offsetting here is okay because the + // character before position `start` are an + // ascii single quote and ascii 'b'. + let pos = self.pos; + panic!(self.fatal_span_verbose(start - BytePos(2), + pos, + "unterminated byte constant".to_string())); + } + + let id = if valid { + self.name_from(start) + } else { + Symbol::intern("?") + }; + self.bump(); // advance ch past token + return token::Byte(id); + } + + fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool { + self.scan_hex_digits(2, delim, below_0x7f_only) + } + + fn scan_byte_string(&mut self) -> token::Lit { + self.bump(); + let start = self.pos; + let mut valid = true; + + while !self.ch_is('"') { + if self.is_eof() { + let pos = self.pos; + panic!(self.fatal_span_(start, pos, "unterminated double quote byte string")); + } + + let ch_start = self.pos; + let ch = self.ch.unwrap(); + self.bump(); + valid &= self.scan_char_or_byte(ch_start, + ch, + // ascii_only = + true, + '"'); + } + let id = if valid { + self.name_from(start) + } else { + Symbol::intern("??") + }; + self.bump(); + return token::ByteStr(id); + } + + fn scan_raw_byte_string(&mut self) -> token::Lit { + let start_bpos = self.pos; + self.bump(); + let mut hash_count = 0; + while self.ch_is('#') { + self.bump(); + hash_count += 1; + } + + if self.is_eof() { + let pos = self.pos; + panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string")); + } else if !self.ch_is('"') { + let pos = self.pos; + let ch = self.ch.unwrap(); + panic!(self.fatal_span_char(start_bpos, + pos, + "found invalid character; only `#` is allowed in raw \ + string delimitation", + ch)); + } + self.bump(); + let content_start_bpos = self.pos; + let mut content_end_bpos; + 'outer: loop { + match self.ch { + None => { + let pos = self.pos; + panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string")) + } + Some('"') => { + content_end_bpos = self.pos; + for _ in 0..hash_count { + self.bump(); + if !self.ch_is('#') { + continue 'outer; + } + } + break; + } + Some(c) => { + if c > '\x7F' { + let pos = self.pos; + self.err_span_char(pos, pos, "raw byte string must be ASCII", c); + } + } + } + self.bump(); + } + self.bump(); + return token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), + hash_count); + } +} + +// This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which +// is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3 +pub fn is_pattern_whitespace(c: Option<char>) -> bool { + // Please note, the function signature is the one which uses rustc_unicode + // but the function body is from the prior version. + match c.unwrap_or('\x00') { + ' ' | '\n' | '\t' | '\r' => true, + _ => false + } +} + +fn in_range(c: Option<char>, lo: char, hi: char) -> bool { + match c { + Some(c) => lo <= c && c <= hi, + _ => false, + } +} + +fn is_dec_digit(c: Option<char>) -> bool { + return in_range(c, '0', '9'); +} + +pub fn is_doc_comment(s: &str) -> bool { + let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') || + s.starts_with("//!"); + debug!("is {:?} a doc comment? {}", s, res); + res +} + +pub fn is_block_doc_comment(s: &str) -> bool { + // Prevent `/**/` from being parsed as a doc comment + let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') || + s.starts_with("/*!")) && s.len() >= 5; + debug!("is {:?} a doc comment? {}", s, res); + res +} + +fn ident_start(c: Option<char>) -> bool { + let c = match c { + Some(c) => c, + None => return false, + }; + + (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && UnicodeXID::is_xid_start(c)) +} + +fn ident_continue(c: Option<char>) -> bool { + let c = match c { + Some(c) => c, + None => return false, + }; + + (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || + (c > '\x7f' && UnicodeXID::is_xid_continue(c)) +} + +#[cfg(test)] +mod tests { + use super::*; + + use ast::Ident; + use symbol::Symbol; + use syntax_pos::{BytePos, Span, NO_EXPANSION}; + use codemap::CodeMap; + use errors; + use parse::token; + use std::io; + use std::rc::Rc; + + fn mk_sh(cm: Rc<CodeMap>) -> errors::Handler { + // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. + let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()), + Some(cm)); + errors::Handler::with_emitter(true, false, Box::new(emitter)) + } + + // open a string reader for the given string + fn setup<'a>(cm: &CodeMap, + span_handler: &'a errors::Handler, + teststr: String) + -> StringReader<'a> { + let fm = cm.new_filemap("zebra.rs".to_string(), None, teststr); + StringReader::new(span_handler, fm) + } + + #[test] + fn t1() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + let mut string_reader = setup(&cm, + &sh, + "/* my source file */ fn main() { println!(\"zebra\"); }\n" + .to_string()); + let id = Ident::from_str("fn"); + assert_eq!(string_reader.next_token().tok, token::Comment); + assert_eq!(string_reader.next_token().tok, token::Whitespace); + let tok1 = string_reader.next_token(); + let tok2 = TokenAndSpan { + tok: token::Ident(id), + sp: Span { + lo: BytePos(21), + hi: BytePos(23), + expn_id: NO_EXPANSION, + }, + }; + assert_eq!(tok1, tok2); + assert_eq!(string_reader.next_token().tok, token::Whitespace); + // the 'main' id is already read: + assert_eq!(string_reader.pos.clone(), BytePos(28)); + // read another token: + let tok3 = string_reader.next_token(); + let tok4 = TokenAndSpan { + tok: token::Ident(Ident::from_str("main")), + sp: Span { + lo: BytePos(24), + hi: BytePos(28), + expn_id: NO_EXPANSION, + }, + }; + assert_eq!(tok3, tok4); + // the lparen is already read: + assert_eq!(string_reader.pos.clone(), BytePos(29)) + } + + // check that the given reader produces the desired stream + // of tokens (stop checking after exhausting the expected vec) + fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) { + for expected_tok in &expected { + assert_eq!(&string_reader.next_token().tok, expected_tok); + } + } + + // make the identifier by looking up the string in the interner + fn mk_ident(id: &str) -> token::Token { + token::Ident(Ident::from_str(id)) + } + + #[test] + fn doublecolonparsing() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + check_tokenization(setup(&cm, &sh, "a b".to_string()), + vec![mk_ident("a"), token::Whitespace, mk_ident("b")]); + } + + #[test] + fn dcparsing_2() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + check_tokenization(setup(&cm, &sh, "a::b".to_string()), + vec![mk_ident("a"), token::ModSep, mk_ident("b")]); + } + + #[test] + fn dcparsing_3() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + check_tokenization(setup(&cm, &sh, "a ::b".to_string()), + vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]); + } + + #[test] + fn dcparsing_4() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + check_tokenization(setup(&cm, &sh, "a:: b".to_string()), + vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]); + } + + #[test] + fn character_a() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok, + token::Literal(token::Char(Symbol::intern("a")), None)); + } + + #[test] + fn character_space() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok, + token::Literal(token::Char(Symbol::intern(" ")), None)); + } + + #[test] + fn character_escaped() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok, + token::Literal(token::Char(Symbol::intern("\\n")), None)); + } + + #[test] + fn lifetime_name() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok, + token::Lifetime(Ident::from_str("'abc"))); + } + + #[test] + fn raw_string() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()) + .next_token() + .tok, + token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None)); + } + + #[test] + fn literal_suffixes() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + macro_rules! test { + ($input: expr, $tok_type: ident, $tok_contents: expr) => {{ + assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok, + token::Literal(token::$tok_type(Symbol::intern($tok_contents)), + Some(Symbol::intern("suffix")))); + // with a whitespace separator: + assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok, + token::Literal(token::$tok_type(Symbol::intern($tok_contents)), + None)); + }} + } + + test!("'a'", Char, "a"); + test!("b'a'", Byte, "a"); + test!("\"a\"", Str_, "a"); + test!("b\"a\"", ByteStr, "a"); + test!("1234", Integer, "1234"); + test!("0b101", Integer, "0b101"); + test!("0xABC", Integer, "0xABC"); + test!("1.0", Float, "1.0"); + test!("1.0e10", Float, "1.0e10"); + + assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok, + token::Literal(token::Integer(Symbol::intern("2")), + Some(Symbol::intern("us")))); + assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok, + token::Literal(token::StrRaw(Symbol::intern("raw"), 3), + Some(Symbol::intern("suffix")))); + assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok, + token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3), + Some(Symbol::intern("suffix")))); + } + + #[test] + fn line_doc_comments() { + assert!(is_doc_comment("///")); + assert!(is_doc_comment("/// blah")); + assert!(!is_doc_comment("////")); + } + + #[test] + fn nested_block_comments() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string()); + match lexer.next_token().tok { + token::Comment => {} + _ => panic!("expected a comment!"), + } + assert_eq!(lexer.next_token().tok, + token::Literal(token::Char(Symbol::intern("a")), None)); + } + + #[test] + fn crlf_comments() { + let cm = Rc::new(CodeMap::new()); + let sh = mk_sh(cm.clone()); + let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string()); + let comment = lexer.next_token(); + assert_eq!(comment.tok, token::Comment); + assert_eq!(comment.sp, ::syntax_pos::mk_sp(BytePos(0), BytePos(7))); + assert_eq!(lexer.next_token().tok, token::Whitespace); + assert_eq!(lexer.next_token().tok, + token::DocComment(Symbol::intern("/// test"))); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/lexer/unicode_chars.rs b/bash-5.1/vendor/syntex_syntax/src/parse/lexer/unicode_chars.rs new file mode 100644 index 0000000..1e08b20 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/lexer/unicode_chars.rs @@ -0,0 +1,253 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Characters and their corresponding confusables were collected from +// http://www.unicode.org/Public/security/revision-06/confusables.txt + +use syntax_pos::mk_sp as make_span; +use errors::DiagnosticBuilder; +use super::StringReader; + +const UNICODE_ARRAY: &'static [(char, &'static str, char)] = &[ + (' ', "No-Break Space", ' '), + (' ', "Ogham Space Mark", ' '), + (' ', "En Quad", ' '), + (' ', "Em Quad", ' '), + (' ', "En Space", ' '), + (' ', "Em Space", ' '), + (' ', "Three-Per-Em Space", ' '), + (' ', "Four-Per-Em Space", ' '), + (' ', "Six-Per-Em Space", ' '), + (' ', "Figure Space", ' '), + (' ', "Punctuation Space", ' '), + (' ', "Thin Space", ' '), + (' ', "Hair Space", ' '), + (' ', "Narrow No-Break Space", ' '), + (' ', "Medium Mathematical Space", ' '), + (' ', "Ideographic Space", ' '), + ('ߺ', "Nko Lajanyalan", '_'), + ('﹍', "Dashed Low Line", '_'), + ('﹎', "Centreline Low Line", '_'), + ('﹏', "Wavy Low Line", '_'), + ('‐', "Hyphen", '-'), + ('‑', "Non-Breaking Hyphen", '-'), + ('‒', "Figure Dash", '-'), + ('–', "En Dash", '-'), + ('—', "Em Dash", '-'), + ('﹘', "Small Em Dash", '-'), + ('⁃', "Hyphen Bullet", '-'), + ('˗', "Modifier Letter Minus Sign", '-'), + ('−', "Minus Sign", '-'), + ('ー', "Katakana-Hiragana Prolonged Sound Mark", '-'), + ('٫', "Arabic Decimal Separator", ','), + ('‚', "Single Low-9 Quotation Mark", ','), + ('ꓹ', "Lisu Letter Tone Na Po", ','), + (',', "Fullwidth Comma", ','), + (';', "Greek Question Mark", ';'), + (';', "Fullwidth Semicolon", ';'), + ('ः', "Devanagari Sign Visarga", ':'), + ('ઃ', "Gujarati Sign Visarga", ':'), + (':', "Fullwidth Colon", ':'), + ('։', "Armenian Full Stop", ':'), + ('܃', "Syriac Supralinear Colon", ':'), + ('܄', "Syriac Sublinear Colon", ':'), + ('︰', "Presentation Form For Vertical Two Dot Leader", ':'), + ('᠃', "Mongolian Full Stop", ':'), + ('᠉', "Mongolian Manchu Full Stop", ':'), + ('⁚', "Two Dot Punctuation", ':'), + ('׃', "Hebrew Punctuation Sof Pasuq", ':'), + ('˸', "Modifier Letter Raised Colon", ':'), + ('꞉', "Modifier Letter Colon", ':'), + ('∶', "Ratio", ':'), + ('ː', "Modifier Letter Triangular Colon", ':'), + ('ꓽ', "Lisu Letter Tone Mya Jeu", ':'), + ('!', "Fullwidth Exclamation Mark", '!'), + ('ǃ', "Latin Letter Retroflex Click", '!'), + ('ʔ', "Latin Letter Glottal Stop", '?'), + ('ॽ', "Devanagari Letter Glottal Stop", '?'), + ('Ꭾ', "Cherokee Letter He", '?'), + ('?', "Fullwidth Question Mark", '?'), + ('𝅭', "Musical Symbol Combining Augmentation Dot", '.'), + ('․', "One Dot Leader", '.'), + ('۔', "Arabic Full Stop", '.'), + ('܁', "Syriac Supralinear Full Stop", '.'), + ('܂', "Syriac Sublinear Full Stop", '.'), + ('꘎', "Vai Full Stop", '.'), + ('𐩐', "Kharoshthi Punctuation Dot", '.'), + ('·', "Middle Dot", '.'), + ('٠', "Arabic-Indic Digit Zero", '.'), + ('۰', "Extended Arabic-Indic Digit Zero", '.'), + ('ꓸ', "Lisu Letter Tone Mya Ti", '.'), + ('。', "Ideographic Full Stop", '.'), + ('・', "Katakana Middle Dot", '.'), + ('՝', "Armenian Comma", '\''), + (''', "Fullwidth Apostrophe", '\''), + ('‘', "Left Single Quotation Mark", '\''), + ('’', "Right Single Quotation Mark", '\''), + ('‛', "Single High-Reversed-9 Quotation Mark", '\''), + ('′', "Prime", '\''), + ('‵', "Reversed Prime", '\''), + ('՚', "Armenian Apostrophe", '\''), + ('׳', "Hebrew Punctuation Geresh", '\''), + ('`', "Greek Varia", '\''), + ('`', "Fullwidth Grave Accent", '\''), + ('΄', "Greek Tonos", '\''), + ('´', "Greek Oxia", '\''), + ('᾽', "Greek Koronis", '\''), + ('᾿', "Greek Psili", '\''), + ('῾', "Greek Dasia", '\''), + ('ʹ', "Modifier Letter Prime", '\''), + ('ʹ', "Greek Numeral Sign", '\''), + ('ˊ', "Modifier Letter Acute Accent", '\''), + ('ˋ', "Modifier Letter Grave Accent", '\''), + ('˴', "Modifier Letter Middle Grave Accent", '\''), + ('ʻ', "Modifier Letter Turned Comma", '\''), + ('ʽ', "Modifier Letter Reversed Comma", '\''), + ('ʼ', "Modifier Letter Apostrophe", '\''), + ('ʾ', "Modifier Letter Right Half Ring", '\''), + ('ꞌ', "Latin Small Letter Saltillo", '\''), + ('י', "Hebrew Letter Yod", '\''), + ('ߴ', "Nko High Tone Apostrophe", '\''), + ('ߵ', "Nko Low Tone Apostrophe", '\''), + ('"', "Fullwidth Quotation Mark", '"'), + ('“', "Left Double Quotation Mark", '"'), + ('”', "Right Double Quotation Mark", '"'), + ('‟', "Double High-Reversed-9 Quotation Mark", '"'), + ('″', "Double Prime", '"'), + ('‶', "Reversed Double Prime", '"'), + ('〃', "Ditto Mark", '"'), + ('״', "Hebrew Punctuation Gershayim", '"'), + ('˝', "Double Acute Accent", '"'), + ('ʺ', "Modifier Letter Double Prime", '"'), + ('˶', "Modifier Letter Middle Double Acute Accent", '"'), + ('˵', "Modifier Letter Middle Double Grave Accent", '"'), + ('ˮ', "Modifier Letter Double Apostrophe", '"'), + ('ײ', "Hebrew Ligature Yiddish Double Yod", '"'), + ('❞', "Heavy Double Comma Quotation Mark Ornament", '"'), + ('❝', "Heavy Double Turned Comma Quotation Mark Ornament", '"'), + ('❨', "Medium Left Parenthesis Ornament", '('), + ('﴾', "Ornate Left Parenthesis", '('), + ('(', "Fullwidth Left Parenthesis", '('), + ('❩', "Medium Right Parenthesis Ornament", ')'), + ('﴿', "Ornate Right Parenthesis", ')'), + (')', "Fullwidth Right Parenthesis", ')'), + ('[', "Fullwidth Left Square Bracket", '['), + ('❲', "Light Left Tortoise Shell Bracket Ornament", '['), + ('「', "Left Corner Bracket", '['), + ('『', "Left White Corner Bracket", '['), + ('【', "Left Black Lenticular Bracket", '['), + ('〔', "Left Tortoise Shell Bracket", '['), + ('〖', "Left White Lenticular Bracket", '['), + ('〘', "Left White Tortoise Shell Bracket", '['), + ('〚', "Left White Square Bracket", '['), + (']', "Fullwidth Right Square Bracket", ']'), + ('❳', "Light Right Tortoise Shell Bracket Ornament", ']'), + ('」', "Right Corner Bracket", ']'), + ('』', "Right White Corner Bracket", ']'), + ('】', "Right Black Lenticular Bracket", ']'), + ('〕', "Right Tortoise Shell Bracket", ']'), + ('〗', "Right White Lenticular Bracket", ']'), + ('〙', "Right White Tortoise Shell Bracket", ']'), + ('〛', "Right White Square Bracket", ']'), + ('❴', "Medium Left Curly Bracket Ornament", '{'), + ('❵', "Medium Right Curly Bracket Ornament", '}'), + ('⁎', "Low Asterisk", '*'), + ('٭', "Arabic Five Pointed Star", '*'), + ('∗', "Asterisk Operator", '*'), + ('᜵', "Philippine Single Punctuation", '/'), + ('⁁', "Caret Insertion Point", '/'), + ('∕', "Division Slash", '/'), + ('⁄', "Fraction Slash", '/'), + ('╱', "Box Drawings Light Diagonal Upper Right To Lower Left", '/'), + ('⟋', "Mathematical Rising Diagonal", '/'), + ('⧸', "Big Solidus", '/'), + ('㇓', "Cjk Stroke Sp", '/'), + ('〳', "Vertical Kana Repeat Mark Upper Half", '/'), + ('丿', "Cjk Unified Ideograph-4E3F", '/'), + ('⼃', "Kangxi Radical Slash", '/'), + ('\', "Fullwidth Reverse Solidus", '\\'), + ('﹨', "Small Reverse Solidus", '\\'), + ('∖', "Set Minus", '\\'), + ('⟍', "Mathematical Falling Diagonal", '\\'), + ('⧵', "Reverse Solidus Operator", '\\'), + ('⧹', "Big Reverse Solidus", '\\'), + ('、', "Ideographic Comma", '\\'), + ('ヽ', "Katakana Iteration Mark", '\\'), + ('㇔', "Cjk Stroke D", '\\'), + ('丶', "Cjk Unified Ideograph-4E36", '\\'), + ('⼂', "Kangxi Radical Dot", '\\'), + ('ꝸ', "Latin Small Letter Um", '&'), + ('﬩', "Hebrew Letter Alternative Plus Sign", '+'), + ('‹', "Single Left-Pointing Angle Quotation Mark", '<'), + ('❮', "Heavy Left-Pointing Angle Quotation Mark Ornament", '<'), + ('˂', "Modifier Letter Left Arrowhead", '<'), + ('〈', "Left Angle Bracket", '<'), + ('《', "Left Double Angle Bracket", '<'), + ('꓿', "Lisu Punctuation Full Stop", '='), + ('›', "Single Right-Pointing Angle Quotation Mark", '>'), + ('❯', "Heavy Right-Pointing Angle Quotation Mark Ornament", '>'), + ('˃', "Modifier Letter Right Arrowhead", '>'), + ('〉', "Right Angle Bracket", '>'), + ('》', "Right Double Angle Bracket", '>'), + ('Ⲻ', "Coptic Capital Letter Dialect-P Ni", '-'), + ('Ɂ', "Latin Capital Letter Glottal Stop", '?'), + ('Ⳇ', "Coptic Capital Letter Old Coptic Esh", '/'), ]; + +const ASCII_ARRAY: &'static [(char, &'static str)] = &[ + (' ', "Space"), + ('_', "Underscore"), + ('-', "Minus/Hyphen"), + (',', "Comma"), + (';', "Semicolon"), + (':', "Colon"), + ('!', "Exclamation Mark"), + ('?', "Question Mark"), + ('.', "Period"), + ('\'', "Single Quote"), + ('"', "Quotation Mark"), + ('(', "Left Parenthesis"), + (')', "Right Parenthesis"), + ('[', "Left Square Bracket"), + (']', "Right Square Bracket"), + ('{', "Left Curly Brace"), + ('}', "Right Curly Brace"), + ('*', "Asterisk"), + ('/', "Slash"), + ('\\', "Backslash"), + ('&', "Ampersand"), + ('+', "Plus Sign"), + ('<', "Less-Than Sign"), + ('=', "Equals Sign"), + ('>', "Greater-Than Sign"), ]; + +pub fn check_for_substitution<'a>(reader: &StringReader<'a>, + ch: char, + err: &mut DiagnosticBuilder<'a>) { + UNICODE_ARRAY + .iter() + .find(|&&(c, _, _)| c == ch) + .map(|&(_, u_name, ascii_char)| { + let span = make_span(reader.pos, reader.next_pos); + match ASCII_ARRAY.iter().find(|&&(c, _)| c == ascii_char) { + Some(&(ascii_char, ascii_name)) => { + let msg = + format!("unicode character '{}' ({}) looks much like '{}' ({}), but it's not", + ch, u_name, ascii_char, ascii_name); + err.span_help(span, &msg); + }, + None => { + reader + .span_diagnostic + .span_bug_no_panic(span, + &format!("substitution character not found for '{}'", ch)); + } + } + }); +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/mod.rs b/bash-5.1/vendor/syntex_syntax/src/parse/mod.rs new file mode 100644 index 0000000..dc71550 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/mod.rs @@ -0,0 +1,1006 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The main parser interface + +use ast::{self, CrateConfig}; +use codemap::CodeMap; +use syntax_pos::{self, Span, FileMap}; +use errors::{Handler, ColorConfig, DiagnosticBuilder}; +use feature_gate::UnstableFeatures; +use parse::parser::Parser; +use ptr::P; +use str::char_at; +use symbol::Symbol; +use tokenstream; + +use std::cell::RefCell; +use std::collections::HashSet; +use std::iter; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::str; + +pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>; + +#[macro_use] +pub mod parser; + +pub mod lexer; +pub mod token; +pub mod attr; + +pub mod common; +pub mod classify; +pub mod obsolete; + +/// Info about a parsing session. +pub struct ParseSess { + pub span_diagnostic: Handler, // better be the same as the one in the reader! + pub unstable_features: UnstableFeatures, + pub config: CrateConfig, + /// Used to determine and report recursive mod inclusions + included_mod_stack: RefCell<Vec<PathBuf>>, + code_map: Rc<CodeMap>, +} + +impl ParseSess { + pub fn new() -> Self { + let cm = Rc::new(CodeMap::new()); + let handler = Handler::with_tty_emitter(ColorConfig::Auto, + true, + false, + Some(cm.clone())); + ParseSess::with_span_handler(handler, cm) + } + + pub fn with_span_handler(handler: Handler, code_map: Rc<CodeMap>) -> ParseSess { + ParseSess { + span_diagnostic: handler, + unstable_features: UnstableFeatures::from_environment(), + config: HashSet::new(), + included_mod_stack: RefCell::new(vec![]), + code_map: code_map + } + } + + pub fn codemap(&self) -> &CodeMap { + &self.code_map + } +} + +#[derive(Clone)] +pub struct Directory { + pub path: PathBuf, + pub ownership: DirectoryOwnership, +} + +#[derive(Copy, Clone)] +pub enum DirectoryOwnership { + Owned, + UnownedViaBlock, + UnownedViaMod(bool /* legacy warnings? */), +} + +// a bunch of utility functions of the form parse_<thing>_from_<source> +// where <thing> includes crate, expr, item, stmt, tts, and one that +// uses a HOF to parse anything, and <source> includes file and +// source_str. + +pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> { + let mut parser = new_parser_from_file(sess, input); + parser.parse_crate_mod() +} + +pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess) + -> PResult<'a, Vec<ast::Attribute>> { + let mut parser = new_parser_from_file(sess, input); + parser.parse_inner_attributes() +} + +pub fn parse_crate_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, ast::Crate> { + new_parser_from_source_str(sess, name, source).parse_crate_mod() +} + +pub fn parse_crate_attrs_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, Vec<ast::Attribute>> { + new_parser_from_source_str(sess, name, source).parse_inner_attributes() +} + +pub fn parse_expr_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, P<ast::Expr>> { + new_parser_from_source_str(sess, name, source).parse_expr() +} + +/// Parses an item. +/// +/// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err` +/// when a syntax error occurred. +pub fn parse_item_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, Option<P<ast::Item>>> { + new_parser_from_source_str(sess, name, source).parse_item() +} + +pub fn parse_meta_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, ast::MetaItem> { + new_parser_from_source_str(sess, name, source).parse_meta_item() +} + +pub fn parse_stmt_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, Option<ast::Stmt>> { + new_parser_from_source_str(sess, name, source).parse_stmt() +} + +// Warning: This parses with quote_depth > 0, which is not the default. +pub fn parse_tts_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) + -> PResult<'a, Vec<tokenstream::TokenTree>> { + let mut p = new_parser_from_source_str(sess, name, source); + p.quote_depth += 1; + // right now this is re-creating the token trees from ... token trees. + p.parse_all_token_trees() +} + +// Create a new parser from a source string +pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess, name: String, source: String) + -> Parser<'a> { + filemap_to_parser(sess, sess.codemap().new_filemap(name, None, source)) +} + +/// Create a new parser, handling errors as appropriate +/// if the file doesn't exist +pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> { + filemap_to_parser(sess, file_to_filemap(sess, path, None)) +} + +/// Given a session, a crate config, a path, and a span, add +/// the file at the given path to the codemap, and return a parser. +/// On an error, use the given span as the source of the problem. +pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess, + path: &Path, + directory_ownership: DirectoryOwnership, + module_name: Option<String>, + sp: Span) -> Parser<'a> { + let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp))); + p.directory.ownership = directory_ownership; + p.root_module_name = module_name; + p +} + +/// Given a filemap and config, return a parser +pub fn filemap_to_parser<'a>(sess: &'a ParseSess, filemap: Rc<FileMap>, ) -> Parser<'a> { + let end_pos = filemap.end_pos; + let mut parser = tts_to_parser(sess, filemap_to_tts(sess, filemap)); + + if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP { + parser.span = syntax_pos::mk_sp(end_pos, end_pos); + } + + parser +} + +// must preserve old name for now, because quote! from the *existing* +// compiler expands into it +pub fn new_parser_from_tts<'a>(sess: &'a ParseSess, tts: Vec<tokenstream::TokenTree>) + -> Parser<'a> { + tts_to_parser(sess, tts) +} + +pub fn new_parser_from_ts<'a>(sess: &'a ParseSess, ts: tokenstream::TokenStream) -> Parser<'a> { + tts_to_parser(sess, ts.to_tts()) +} + + +// base abstractions + +/// Given a session and a path and an optional span (for error reporting), +/// add the path to the session's codemap and return the new filemap. +fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>) + -> Rc<FileMap> { + match sess.codemap().load_file(path) { + Ok(filemap) => filemap, + Err(e) => { + let msg = format!("couldn't read {:?}: {}", path.display(), e); + match spanopt { + Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)), + None => panic!(sess.span_diagnostic.fatal(&msg)) + } + } + } +} + +/// Given a filemap, produce a sequence of token-trees +pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>) + -> Vec<tokenstream::TokenTree> { + // it appears to me that the cfg doesn't matter here... indeed, + // parsing tt's probably shouldn't require a parser at all. + let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap); + let mut p1 = Parser::new(sess, Box::new(srdr), None, false); + panictry!(p1.parse_all_token_trees()) +} + +/// Given tts and the ParseSess, produce a parser +pub fn tts_to_parser<'a>(sess: &'a ParseSess, tts: Vec<tokenstream::TokenTree>) -> Parser<'a> { + let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, tts); + let mut p = Parser::new(sess, Box::new(trdr), None, false); + p.check_unknown_macro_variable(); + p +} + +/// Parse a string representing a character literal into its final form. +/// Rather than just accepting/rejecting a given literal, unescapes it as +/// well. Can take any slice prefixed by a character escape. Returns the +/// character and the number of characters consumed. +pub fn char_lit(lit: &str) -> (char, isize) { + use std::char; + + // Handle non-escaped chars first. + if lit.as_bytes()[0] != b'\\' { + // If the first byte isn't '\\' it might part of a multi-byte char, so + // get the char with chars(). + let c = lit.chars().next().unwrap(); + return (c, 1); + } + + // Handle escaped chars. + match lit.as_bytes()[1] as char { + '"' => ('"', 2), + 'n' => ('\n', 2), + 'r' => ('\r', 2), + 't' => ('\t', 2), + '\\' => ('\\', 2), + '\'' => ('\'', 2), + '0' => ('\0', 2), + 'x' => { + let v = u32::from_str_radix(&lit[2..4], 16).unwrap(); + let c = char::from_u32(v).unwrap(); + (c, 4) + } + 'u' => { + assert!(lit.as_bytes()[2] == b'{'); + let idx = lit.find('}').unwrap(); + let v = u32::from_str_radix(&lit[3..idx], 16).unwrap(); + let c = char::from_u32(v).unwrap(); + (c, (idx + 1) as isize) + } + _ => panic!("lexer should have rejected a bad character escape {}", lit) + } +} + +/// Parse a string representing a string literal into its final form. Does +/// unescaping. +pub fn str_lit(lit: &str) -> String { + debug!("parse_str_lit: given {}", + lit.chars().flat_map(char::escape_default).collect::<String>()); + let mut res = String::with_capacity(lit.len()); + + // FIXME #8372: This could be a for-loop if it didn't borrow the iterator + let error = |i| format!("lexer should have rejected {} at {}", lit, i); + + /// Eat everything up to a non-whitespace + fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) { + loop { + match it.peek().map(|x| x.1) { + Some(' ') | Some('\n') | Some('\r') | Some('\t') => { + it.next(); + }, + _ => { break; } + } + } + } + + let mut chars = lit.char_indices().peekable(); + loop { + match chars.next() { + Some((i, c)) => { + match c { + '\\' => { + let ch = chars.peek().unwrap_or_else(|| { + panic!("{}", error(i)) + }).1; + + if ch == '\n' { + eat(&mut chars); + } else if ch == '\r' { + chars.next(); + let ch = chars.peek().unwrap_or_else(|| { + panic!("{}", error(i)) + }).1; + + if ch != '\n' { + panic!("lexer accepted bare CR"); + } + eat(&mut chars); + } else { + // otherwise, a normal escape + let (c, n) = char_lit(&lit[i..]); + for _ in 0..n - 1 { // we don't need to move past the first \ + chars.next(); + } + res.push(c); + } + }, + '\r' => { + let ch = chars.peek().unwrap_or_else(|| { + panic!("{}", error(i)) + }).1; + + if ch != '\n' { + panic!("lexer accepted bare CR"); + } + chars.next(); + res.push('\n'); + } + c => res.push(c), + } + }, + None => break + } + } + + res.shrink_to_fit(); // probably not going to do anything, unless there was an escape. + debug!("parse_str_lit: returning {}", res); + res +} + +/// Parse a string representing a raw string literal into its final form. The +/// only operation this does is convert embedded CRLF into a single LF. +pub fn raw_str_lit(lit: &str) -> String { + debug!("raw_str_lit: given {}", + lit.chars().flat_map(char::escape_default).collect::<String>()); + let mut res = String::with_capacity(lit.len()); + + // FIXME #8372: This could be a for-loop if it didn't borrow the iterator + let mut chars = lit.chars().peekable(); + loop { + match chars.next() { + Some(c) => { + if c == '\r' { + if *chars.peek().unwrap() != '\n' { + panic!("lexer accepted bare CR"); + } + chars.next(); + res.push('\n'); + } else { + res.push(c); + } + }, + None => break + } + } + + res.shrink_to_fit(); + res +} + +// check if `s` looks like i32 or u1234 etc. +fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { + s.len() > 1 && + first_chars.contains(&char_at(s, 0)) && + s[1..].chars().all(|c| '0' <= c && c <= '9') +} + +fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, sd: &Handler, sp: Span) + -> ast::LitKind { + debug!("filtered_float_lit: {}, {:?}", data, suffix); + let suffix = match suffix { + Some(suffix) => suffix, + None => return ast::LitKind::FloatUnsuffixed(data), + }; + + match &*suffix.as_str() { + "f32" => ast::LitKind::Float(data, ast::FloatTy::F32), + "f64" => ast::LitKind::Float(data, ast::FloatTy::F64), + suf => { + if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) { + // if it looks like a width, lets try to be helpful. + sd.struct_span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..])) + .help("valid widths are 32 and 64") + .emit(); + } else { + sd.struct_span_err(sp, &format!("invalid suffix `{}` for float literal", suf)) + .help("valid suffixes are `f32` and `f64`") + .emit(); + } + + ast::LitKind::FloatUnsuffixed(data) + } + } +} +pub fn float_lit(s: &str, suffix: Option<Symbol>, sd: &Handler, sp: Span) -> ast::LitKind { + debug!("float_lit: {:?}, {:?}", s, suffix); + // FIXME #2252: bounds checking float literals is deferred until trans + let s = s.chars().filter(|&c| c != '_').collect::<String>(); + filtered_float_lit(Symbol::intern(&s), suffix, sd, sp) +} + +/// Parse a string representing a byte literal into its final form. Similar to `char_lit` +pub fn byte_lit(lit: &str) -> (u8, usize) { + let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i); + + if lit.len() == 1 { + (lit.as_bytes()[0], 1) + } else { + assert!(lit.as_bytes()[0] == b'\\', err(0)); + let b = match lit.as_bytes()[1] { + b'"' => b'"', + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'\\' => b'\\', + b'\'' => b'\'', + b'0' => b'\0', + _ => { + match u64::from_str_radix(&lit[2..4], 16).ok() { + Some(c) => + if c > 0xFF { + panic!(err(2)) + } else { + return (c as u8, 4) + }, + None => panic!(err(3)) + } + } + }; + return (b, 2); + } +} + +pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> { + let mut res = Vec::with_capacity(lit.len()); + + // FIXME #8372: This could be a for-loop if it didn't borrow the iterator + let error = |i| format!("lexer should have rejected {} at {}", lit, i); + + /// Eat everything up to a non-whitespace + fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) { + loop { + match it.peek().map(|x| x.1) { + Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => { + it.next(); + }, + _ => { break; } + } + } + } + + // byte string literals *must* be ASCII, but the escapes don't have to be + let mut chars = lit.bytes().enumerate().peekable(); + loop { + match chars.next() { + Some((i, b'\\')) => { + let em = error(i); + match chars.peek().expect(&em).1 { + b'\n' => eat(&mut chars), + b'\r' => { + chars.next(); + if chars.peek().expect(&em).1 != b'\n' { + panic!("lexer accepted bare CR"); + } + eat(&mut chars); + } + _ => { + // otherwise, a normal escape + let (c, n) = byte_lit(&lit[i..]); + // we don't need to move past the first \ + for _ in 0..n - 1 { + chars.next(); + } + res.push(c); + } + } + }, + Some((i, b'\r')) => { + let em = error(i); + if chars.peek().expect(&em).1 != b'\n' { + panic!("lexer accepted bare CR"); + } + chars.next(); + res.push(b'\n'); + } + Some((_, c)) => res.push(c), + None => break, + } + } + + Rc::new(res) +} + +pub fn integer_lit(s: &str, suffix: Option<Symbol>, sd: &Handler, sp: Span) -> ast::LitKind { + // s can only be ascii, byte indexing is fine + + let s2 = s.chars().filter(|&c| c != '_').collect::<String>(); + let mut s = &s2[..]; + + debug!("integer_lit: {}, {:?}", s, suffix); + + let mut base = 10; + let orig = s; + let mut ty = ast::LitIntType::Unsuffixed; + + if char_at(s, 0) == '0' && s.len() > 1 { + match char_at(s, 1) { + 'x' => base = 16, + 'o' => base = 8, + 'b' => base = 2, + _ => { } + } + } + + // 1f64 and 2f32 etc. are valid float literals. + if let Some(suf) = suffix { + if looks_like_width_suffix(&['f'], &suf.as_str()) { + match base { + 16 => sd.span_err(sp, "hexadecimal float literal is not supported"), + 8 => sd.span_err(sp, "octal float literal is not supported"), + 2 => sd.span_err(sp, "binary float literal is not supported"), + _ => () + } + return filtered_float_lit(Symbol::intern(&s), Some(suf), sd, sp) + } + } + + if base != 10 { + s = &s[2..]; + } + + if let Some(suf) = suffix { + if suf.as_str().is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")} + ty = match &*suf.as_str() { + "isize" => ast::LitIntType::Signed(ast::IntTy::Is), + "i8" => ast::LitIntType::Signed(ast::IntTy::I8), + "i16" => ast::LitIntType::Signed(ast::IntTy::I16), + "i32" => ast::LitIntType::Signed(ast::IntTy::I32), + "i64" => ast::LitIntType::Signed(ast::IntTy::I64), + "i128" => ast::LitIntType::Signed(ast::IntTy::I128), + "usize" => ast::LitIntType::Unsigned(ast::UintTy::Us), + "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8), + "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16), + "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32), + "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64), + "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128), + suf => { + // i<digits> and u<digits> look like widths, so lets + // give an error message along those lines + if looks_like_width_suffix(&['i', 'u'], suf) { + sd.struct_span_err(sp, &format!("invalid width `{}` for integer literal", + &suf[1..])) + .help("valid widths are 8, 16, 32, 64 and 128") + .emit(); + } else { + sd.struct_span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf)) + .help("the suffix must be one of the integral types \ + (`u32`, `isize`, etc)") + .emit(); + } + + ty + } + } + } + + debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \ + string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix); + + match u64::from_str_radix(s, base) { + Ok(r) => ast::LitKind::Int(r, ty), + Err(_) => { + // small bases are lexed as if they were base 10, e.g, the string + // might be `0b10201`. This will cause the conversion above to fail, + // but these cases have errors in the lexer: we don't want to emit + // two errors, and we especially don't want to emit this error since + // it isn't necessarily true. + let already_errored = base < 10 && + s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base)); + + if !already_errored { + sd.span_err(sp, "int literal is too large"); + } + ast::LitKind::Int(0, ty) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::rc::Rc; + use syntax_pos::{self, Span, BytePos, Pos, NO_EXPANSION}; + use codemap::Spanned; + use ast::{self, Ident, PatKind}; + use abi::Abi; + use attr::first_attr_value_str_by_name; + use parse; + use parse::parser::Parser; + use print::pprust::item_to_string; + use ptr::P; + use tokenstream::{self, TokenTree}; + use util::parser_testing::{string_to_tts, string_to_parser}; + use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt}; + use util::ThinVec; + + // produce a syntax_pos::span + fn sp(a: u32, b: u32) -> Span { + Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION} + } + + #[test] fn path_exprs_1() { + assert!(string_to_expr("a".to_string()) == + P(ast::Expr{ + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Path(None, ast::Path { + span: sp(0, 1), + segments: vec![Ident::from_str("a").into()], + }), + span: sp(0, 1), + attrs: ThinVec::new(), + })) + } + + #[test] fn path_exprs_2 () { + assert!(string_to_expr("::a::b".to_string()) == + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Path(None, ast::Path { + span: sp(0, 6), + segments: vec![ast::PathSegment::crate_root(), + Ident::from_str("a").into(), + Ident::from_str("b").into()] + }), + span: sp(0, 6), + attrs: ThinVec::new(), + })) + } + + #[should_panic] + #[test] fn bad_path_expr_1() { + string_to_expr("::abc::def::return".to_string()); + } + + // check the token-tree-ization of macros + #[test] + fn string_to_tts_macro () { + let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string()); + let tts: &[tokenstream::TokenTree] = &tts[..]; + + match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) { + ( + 4, + Some(&TokenTree::Token(_, token::Ident(name_macro_rules))), + Some(&TokenTree::Token(_, token::Not)), + Some(&TokenTree::Token(_, token::Ident(name_zip))), + Some(&TokenTree::Delimited(_, ref macro_delimed)), + ) + if name_macro_rules.name == "macro_rules" + && name_zip.name == "zip" => { + let tts = ¯o_delimed.tts[..]; + match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) { + ( + 3, + Some(&TokenTree::Delimited(_, ref first_delimed)), + Some(&TokenTree::Token(_, token::FatArrow)), + Some(&TokenTree::Delimited(_, ref second_delimed)), + ) + if macro_delimed.delim == token::Paren => { + let tts = &first_delimed.tts[..]; + match (tts.len(), tts.get(0), tts.get(1)) { + ( + 2, + Some(&TokenTree::Token(_, token::Dollar)), + Some(&TokenTree::Token(_, token::Ident(ident))), + ) + if first_delimed.delim == token::Paren && ident.name == "a" => {}, + _ => panic!("value 3: {:?}", **first_delimed), + } + let tts = &second_delimed.tts[..]; + match (tts.len(), tts.get(0), tts.get(1)) { + ( + 2, + Some(&TokenTree::Token(_, token::Dollar)), + Some(&TokenTree::Token(_, token::Ident(ident))), + ) + if second_delimed.delim == token::Paren + && ident.name == "a" => {}, + _ => panic!("value 4: {:?}", **second_delimed), + } + }, + _ => panic!("value 2: {:?}", **macro_delimed), + } + }, + _ => panic!("value: {:?}",tts), + } + } + + #[test] + fn string_to_tts_1() { + let tts = string_to_tts("fn a (b : i32) { b; }".to_string()); + + let expected = vec![ + TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"))), + TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"))), + TokenTree::Delimited( + sp(5, 14), + Rc::new(tokenstream::Delimited { + delim: token::DelimToken::Paren, + open_span: sp(5, 6), + tts: vec![ + TokenTree::Token(sp(6, 7), token::Ident(Ident::from_str("b"))), + TokenTree::Token(sp(8, 9), token::Colon), + TokenTree::Token(sp(10, 13), token::Ident(Ident::from_str("i32"))), + ], + close_span: sp(13, 14), + })), + TokenTree::Delimited( + sp(15, 21), + Rc::new(tokenstream::Delimited { + delim: token::DelimToken::Brace, + open_span: sp(15, 16), + tts: vec![ + TokenTree::Token(sp(17, 18), token::Ident(Ident::from_str("b"))), + TokenTree::Token(sp(18, 19), token::Semi), + ], + close_span: sp(20, 21), + })) + ]; + + assert_eq!(tts, expected); + } + + #[test] fn ret_expr() { + assert!(string_to_expr("return d".to_string()) == + P(ast::Expr{ + id: ast::DUMMY_NODE_ID, + node:ast::ExprKind::Ret(Some(P(ast::Expr{ + id: ast::DUMMY_NODE_ID, + node:ast::ExprKind::Path(None, ast::Path{ + span: sp(7, 8), + segments: vec![Ident::from_str("d").into()], + }), + span:sp(7,8), + attrs: ThinVec::new(), + }))), + span:sp(0,8), + attrs: ThinVec::new(), + })) + } + + #[test] fn parse_stmt_1 () { + assert!(string_to_stmt("b;".to_string()) == + Some(ast::Stmt { + node: ast::StmtKind::Expr(P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Path(None, ast::Path { + span:sp(0,1), + segments: vec![Ident::from_str("b").into()], + }), + span: sp(0,1), + attrs: ThinVec::new()})), + id: ast::DUMMY_NODE_ID, + span: sp(0,1)})) + + } + + fn parser_done(p: Parser){ + assert_eq!(p.token.clone(), token::Eof); + } + + #[test] fn parse_ident_pat () { + let sess = ParseSess::new(); + let mut parser = string_to_parser(&sess, "b".to_string()); + assert!(panictry!(parser.parse_pat()) + == P(ast::Pat{ + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Immutable), + Spanned{ span:sp(0, 1), + node: Ident::from_str("b") + }, + None), + span: sp(0,1)})); + parser_done(parser); + } + + // check the contents of the tt manually: + #[test] fn parse_fundecl () { + // this test depends on the intern order of "fn" and "i32" + assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()), + Some( + P(ast::Item{ident:Ident::from_str("a"), + attrs:Vec::new(), + id: ast::DUMMY_NODE_ID, + node: ast::ItemKind::Fn(P(ast::FnDecl { + inputs: vec![ast::Arg{ + ty: P(ast::Ty{id: ast::DUMMY_NODE_ID, + node: ast::TyKind::Path(None, ast::Path{ + span:sp(10,13), + segments: vec![Ident::from_str("i32").into()], + }), + span:sp(10,13) + }), + pat: P(ast::Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident( + ast::BindingMode::ByValue(ast::Mutability::Immutable), + Spanned{ + span: sp(6,7), + node: Ident::from_str("b")}, + None + ), + span: sp(6,7) + }), + id: ast::DUMMY_NODE_ID + }], + output: ast::FunctionRetTy::Default(sp(15, 15)), + variadic: false + }), + ast::Unsafety::Normal, + Spanned { + span: sp(0,2), + node: ast::Constness::NotConst, + }, + Abi::Rust, + ast::Generics{ // no idea on either of these: + lifetimes: Vec::new(), + ty_params: P::new(), + where_clause: ast::WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + }, + span: syntax_pos::DUMMY_SP, + }, + P(ast::Block { + stmts: vec![ast::Stmt { + node: ast::StmtKind::Semi(P(ast::Expr{ + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Path(None, + ast::Path{ + span:sp(17,18), + segments: vec![Ident::from_str("b").into()], + }), + span: sp(17,18), + attrs: ThinVec::new()})), + id: ast::DUMMY_NODE_ID, + span: sp(17,19)}], + id: ast::DUMMY_NODE_ID, + rules: ast::BlockCheckMode::Default, // no idea + span: sp(15,21), + })), + vis: ast::Visibility::Inherited, + span: sp(0,21)}))); + } + + #[test] fn parse_use() { + let use_s = "use foo::bar::baz;"; + let vitem = string_to_item(use_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], use_s); + + let use_s = "use foo::bar as baz;"; + let vitem = string_to_item(use_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], use_s); + } + + #[test] fn parse_extern_crate() { + let ex_s = "extern crate foo;"; + let vitem = string_to_item(ex_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], ex_s); + + let ex_s = "extern crate foo as bar;"; + let vitem = string_to_item(ex_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], ex_s); + } + + fn get_spans_of_pat_idents(src: &str) -> Vec<Span> { + let item = string_to_item(src.to_string()).unwrap(); + + struct PatIdentVisitor { + spans: Vec<Span> + } + impl<'a> ::visit::Visitor<'a> for PatIdentVisitor { + fn visit_pat(&mut self, p: &'a ast::Pat) { + match p.node { + PatKind::Ident(_ , ref spannedident, _) => { + self.spans.push(spannedident.span.clone()); + } + _ => { + ::visit::walk_pat(self, p); + } + } + } + } + let mut v = PatIdentVisitor { spans: Vec::new() }; + ::visit::walk_item(&mut v, &item); + return v.spans; + } + + #[test] fn span_of_self_arg_pat_idents_are_correct() { + + let srcs = ["impl z { fn a (&self, &myarg: i32) {} }", + "impl z { fn a (&mut self, &myarg: i32) {} }", + "impl z { fn a (&'a self, &myarg: i32) {} }", + "impl z { fn a (self, &myarg: i32) {} }", + "impl z { fn a (self: Foo, &myarg: i32) {} }", + ]; + + for &src in &srcs { + let spans = get_spans_of_pat_idents(src); + let Span{ lo, hi, .. } = spans[0]; + assert!("self" == &src[lo.to_usize()..hi.to_usize()], + "\"{}\" != \"self\". src=\"{}\"", + &src[lo.to_usize()..hi.to_usize()], src) + } + } + + #[test] fn parse_exprs () { + // just make sure that they parse.... + string_to_expr("3 + 4".to_string()); + string_to_expr("a::z.froob(b,&(987+3))".to_string()); + } + + #[test] fn attrs_fix_bug () { + string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) + -> Result<Box<Writer>, String> { + #[cfg(windows)] + fn wb() -> c_int { + (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int + } + + #[cfg(unix)] + fn wb() -> c_int { O_WRONLY as c_int } + + let mut fflags: c_int = wb(); +}".to_string()); + } + + #[test] fn crlf_doc_comments() { + let sess = ParseSess::new(); + + let name = "<source>".to_string(); + let source = "/// doc comment\r\nfn foo() {}".to_string(); + let item = parse_item_from_source_str(name.clone(), source, &sess) + .unwrap().unwrap(); + let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap(); + assert_eq!(doc, "/// doc comment"); + + let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); + let item = parse_item_from_source_str(name.clone(), source, &sess) + .unwrap().unwrap(); + let docs = item.attrs.iter().filter(|a| a.name() == "doc") + .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>(); + let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; + assert_eq!(&docs[..], b); + + let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); + let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap(); + let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap(); + assert_eq!(doc, "/** doc comment\n * with CRLF */"); + } + + #[test] + fn ttdelim_span() { + let sess = ParseSess::new(); + let expr = parse::parse_expr_from_source_str("foo".to_string(), + "foo!( fn main() { body } )".to_string(), &sess).unwrap(); + + let tts = match expr.node { + ast::ExprKind::Mac(ref mac) => mac.node.tts.clone(), + _ => panic!("not a macro"), + }; + + let span = tts.iter().rev().next().unwrap().get_span(); + + match sess.codemap().span_to_snippet(span) { + Ok(s) => assert_eq!(&s[..], "{ body }"), + Err(_) => panic!("could not get snippet"), + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/obsolete.rs b/bash-5.1/vendor/syntex_syntax/src/parse/obsolete.rs new file mode 100644 index 0000000..a46a788 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/obsolete.rs @@ -0,0 +1,66 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Support for parsing unsupported, old syntaxes, for the purpose of reporting errors. Parsing of +//! these syntaxes is tested by compile-test/obsolete-syntax.rs. +//! +//! Obsolete syntax that becomes too hard to parse can be removed. + +use syntax_pos::Span; +use parse::parser; + +/// The specific types of unsupported syntax +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub enum ObsoleteSyntax { + // Nothing here at the moment +} + +pub trait ParserObsoleteMethods { + /// Reports an obsolete syntax non-fatal error. + fn obsolete(&mut self, sp: Span, kind: ObsoleteSyntax); + fn report(&mut self, + sp: Span, + kind: ObsoleteSyntax, + kind_str: &str, + desc: &str, + error: bool); +} + +impl<'a> ParserObsoleteMethods for parser::Parser<'a> { + /// Reports an obsolete syntax non-fatal error. + #[allow(unused_variables)] + fn obsolete(&mut self, sp: Span, kind: ObsoleteSyntax) { + let (kind_str, desc, error) = match kind { + // Nothing here at the moment + }; + + self.report(sp, kind, kind_str, desc, error); + } + + fn report(&mut self, + sp: Span, + kind: ObsoleteSyntax, + kind_str: &str, + desc: &str, + error: bool) { + let mut err = if error { + self.diagnostic().struct_span_err(sp, &format!("obsolete syntax: {}", kind_str)) + } else { + self.diagnostic().struct_span_warn(sp, &format!("obsolete syntax: {}", kind_str)) + }; + + if !self.obsolete_set.contains(&kind) && + (error || self.sess.span_diagnostic.can_emit_warnings) { + err.note(&format!("{}", desc)); + self.obsolete_set.insert(kind); + } + err.emit(); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/parser.rs b/bash-5.1/vendor/syntex_syntax/src/parse/parser.rs new file mode 100644 index 0000000..0395073 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/parser.rs @@ -0,0 +1,6172 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use abi::{self, Abi}; +use ast::BareFnTy; +use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; +use ast::Unsafety; +use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind}; +use ast::Block; +use ast::{BlockCheckMode, CaptureBy}; +use ast::{Constness, Crate}; +use ast::Defaultness; +use ast::EnumDef; +use ast::{Expr, ExprKind, RangeLimits}; +use ast::{Field, FnDecl}; +use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; +use ast::{Ident, ImplItem, Item, ItemKind}; +use ast::{Lit, LitKind, UintTy}; +use ast::Local; +use ast::MacStmtStyle; +use ast::Mac_; +use ast::{MutTy, Mutability}; +use ast::{Pat, PatKind}; +use ast::{PolyTraitRef, QSelf}; +use ast::{Stmt, StmtKind}; +use ast::{VariantData, StructField}; +use ast::StrStyle; +use ast::SelfKind; +use ast::{TraitItem, TraitRef}; +use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds}; +use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; +use ast::{Visibility, WhereClause}; +use ast::{BinOpKind, UnOp}; +use {ast, attr}; +use codemap::{self, CodeMap, Spanned, spanned, respan}; +use syntax_pos::{self, Span, BytePos, mk_sp}; +use errors::{self, DiagnosticBuilder}; +use ext::tt::macro_parser; +use parse; +use parse::classify; +use parse::common::SeqSep; +use parse::lexer::{Reader, TokenAndSpan}; +use parse::obsolete::ObsoleteSyntax; +use parse::token::{self, MatchNt, SubstNt}; +use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership}; +use util::parser::{AssocOp, Fixity}; +use print::pprust; +use ptr::P; +use parse::PResult; +use tokenstream::{self, Delimited, SequenceRepetition, TokenTree}; +use symbol::{Symbol, keywords}; +use util::ThinVec; + +use std::collections::HashSet; +use std::mem; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::slice; + +bitflags! { + pub flags Restrictions: u8 { + const RESTRICTION_STMT_EXPR = 1 << 0, + const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1, + } +} + +impl Restrictions { + // Hack to work around differences between bitflags built-in and the bitflags crate + pub fn restriction_stmt_expr() -> Self { + RESTRICTION_STMT_EXPR + } + pub fn restriction_no_struct_literal() -> Self { + RESTRICTION_NO_STRUCT_LITERAL + } +} + +type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >); + +/// How to parse a path. There are three different kinds of paths, all of which +/// are parsed somewhat differently. +#[derive(Copy, Clone, PartialEq)] +pub enum PathStyle { + /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities. + Mod, + /// A path with a lifetime and type parameters, with no double colons + /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`, used in types. + /// Paths using this style can be passed into macros expecting `path` nonterminals. + Type, + /// A path with a lifetime and type parameters with double colons before + /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`, used in expressions or patterns. + Expr, +} + +#[derive(Clone, Copy, PartialEq)] +pub enum SemiColonMode { + Break, + Ignore, +} + +/// Possibly accept an `token::Interpolated` expression (a pre-parsed expression +/// dropped into the token stream, which happens while parsing the result of +/// macro expansion). Placement of these is not as complex as I feared it would +/// be. The important thing is to make sure that lookahead doesn't balk at +/// `token::Interpolated` tokens. +macro_rules! maybe_whole_expr { + ($p:expr) => { + if let token::Interpolated(nt) = $p.token.clone() { + match *nt { + token::NtExpr(ref e) => { + $p.bump(); + return Ok((*e).clone()); + } + token::NtPath(ref path) => { + $p.bump(); + let span = $p.span; + let kind = ExprKind::Path(None, (*path).clone()); + return Ok($p.mk_expr(span.lo, span.hi, kind, ThinVec::new())); + } + token::NtBlock(ref block) => { + $p.bump(); + let span = $p.span; + let kind = ExprKind::Block((*block).clone()); + return Ok($p.mk_expr(span.lo, span.hi, kind, ThinVec::new())); + } + _ => {}, + }; + } + } +} + +/// As maybe_whole_expr, but for things other than expressions +macro_rules! maybe_whole { + ($p:expr, $constructor:ident, |$x:ident| $e:expr) => { + if let token::Interpolated(nt) = $p.token.clone() { + if let token::$constructor($x) = (*nt).clone() { + $p.bump(); + return Ok($e); + } + } + }; +} + +fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>) + -> Vec<Attribute> { + if let Some(ref attrs) = rhs { + lhs.extend(attrs.iter().cloned()) + } + lhs +} + +#[derive(PartialEq)] +enum PrevTokenKind { + DocComment, + Comma, + Interpolated, + Eof, + Other, +} + +// Simple circular buffer used for keeping few next tokens. +#[derive(Default)] +struct LookaheadBuffer { + buffer: [TokenAndSpan; LOOKAHEAD_BUFFER_CAPACITY], + start: usize, + end: usize, +} + +const LOOKAHEAD_BUFFER_CAPACITY: usize = 8; + +impl LookaheadBuffer { + fn len(&self) -> usize { + (LOOKAHEAD_BUFFER_CAPACITY + self.end - self.start) % LOOKAHEAD_BUFFER_CAPACITY + } +} + +/* ident is handled by common.rs */ + +pub struct Parser<'a> { + pub sess: &'a ParseSess, + /// the current token: + pub token: token::Token, + /// the span of the current token: + pub span: Span, + /// the span of the previous token: + pub prev_span: Span, + /// the previous token kind + prev_token_kind: PrevTokenKind, + lookahead_buffer: LookaheadBuffer, + pub tokens_consumed: usize, + pub restrictions: Restrictions, + pub quote_depth: usize, // not (yet) related to the quasiquoter + parsing_token_tree: bool, + pub reader: Box<Reader+'a>, + /// The set of seen errors about obsolete syntax. Used to suppress + /// extra detail when the same error is seen twice + pub obsolete_set: HashSet<ObsoleteSyntax>, + /// Used to determine the path to externally loaded source files + pub directory: Directory, + /// Stack of open delimiters and their spans. Used for error message. + pub open_braces: Vec<(token::DelimToken, Span)>, + /// Name of the root module this parser originated from. If `None`, then the + /// name is not known. This does not change while the parser is descending + /// into modules, and sub-parsers have new values for this name. + pub root_module_name: Option<String>, + pub expected_tokens: Vec<TokenType>, + pub tts: Vec<(TokenTree, usize)>, + pub desugar_doc_comments: bool, + pub allow_interpolated_tts: bool, +} + +#[derive(PartialEq, Eq, Clone)] +pub enum TokenType { + Token(token::Token), + Keyword(keywords::Keyword), + Operator, +} + +impl TokenType { + fn to_string(&self) -> String { + match *self { + TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)), + TokenType::Operator => "an operator".to_string(), + TokenType::Keyword(kw) => format!("`{}`", kw.name()), + } + } +} + +fn is_ident_or_underscore(t: &token::Token) -> bool { + t.is_ident() || *t == token::Underscore +} + +/// Information about the path to a module. +pub struct ModulePath { + pub name: String, + pub path_exists: bool, + pub result: Result<ModulePathSuccess, ModulePathError>, +} + +pub struct ModulePathSuccess { + pub path: PathBuf, + pub directory_ownership: DirectoryOwnership, + warn: bool, +} + +pub struct ModulePathError { + pub err_msg: String, + pub help_msg: String, +} + +pub enum LhsExpr { + NotYetParsed, + AttributesParsed(ThinVec<Attribute>), + AlreadyParsed(P<Expr>), +} + +impl From<Option<ThinVec<Attribute>>> for LhsExpr { + fn from(o: Option<ThinVec<Attribute>>) -> Self { + if let Some(attrs) = o { + LhsExpr::AttributesParsed(attrs) + } else { + LhsExpr::NotYetParsed + } + } +} + +impl From<P<Expr>> for LhsExpr { + fn from(expr: P<Expr>) -> Self { + LhsExpr::AlreadyParsed(expr) + } +} + +impl<'a> Parser<'a> { + pub fn new(sess: &'a ParseSess, + rdr: Box<Reader+'a>, + directory: Option<Directory>, + desugar_doc_comments: bool) + -> Self { + let mut parser = Parser { + reader: rdr, + sess: sess, + token: token::Underscore, + span: syntax_pos::DUMMY_SP, + prev_span: syntax_pos::DUMMY_SP, + prev_token_kind: PrevTokenKind::Other, + lookahead_buffer: Default::default(), + tokens_consumed: 0, + restrictions: Restrictions::empty(), + quote_depth: 0, + parsing_token_tree: false, + obsolete_set: HashSet::new(), + directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned }, + open_braces: Vec::new(), + root_module_name: None, + expected_tokens: Vec::new(), + tts: Vec::new(), + desugar_doc_comments: desugar_doc_comments, + allow_interpolated_tts: true, + }; + + let tok = parser.next_tok(); + parser.token = tok.tok; + parser.span = tok.sp; + if let Some(directory) = directory { + parser.directory = directory; + } else if parser.span != syntax_pos::DUMMY_SP { + parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span)); + parser.directory.path.pop(); + } + parser + } + + fn next_tok(&mut self) -> TokenAndSpan { + 'outer: loop { + let mut tok = if let Some((tts, i)) = self.tts.pop() { + let tt = tts.get_tt(i); + if i + 1 < tts.len() { + self.tts.push((tts, i + 1)); + } + if let TokenTree::Token(sp, tok) = tt { + TokenAndSpan { tok: tok, sp: sp } + } else { + self.tts.push((tt, 0)); + continue + } + } else { + self.reader.real_token() + }; + + loop { + let nt = match tok.tok { + token::Interpolated(ref nt) => nt.clone(), + token::DocComment(name) if self.desugar_doc_comments => { + self.tts.push((TokenTree::Token(tok.sp, token::DocComment(name)), 0)); + continue 'outer + } + _ => return tok, + }; + match *nt { + token::NtTT(TokenTree::Token(sp, ref t)) => { + tok = TokenAndSpan { tok: t.clone(), sp: sp }; + } + token::NtTT(ref tt) => { + self.tts.push((tt.clone(), 0)); + continue 'outer + } + _ => return tok, + } + } + } + } + + /// Convert a token to a string using self's reader + pub fn token_to_string(token: &token::Token) -> String { + pprust::token_to_string(token) + } + + /// Convert the current token to a string using self's reader + pub fn this_token_to_string(&self) -> String { + Parser::token_to_string(&self.token) + } + + pub fn this_token_descr(&self) -> String { + let s = self.this_token_to_string(); + if self.token.is_strict_keyword() { + format!("keyword `{}`", s) + } else if self.token.is_reserved_keyword() { + format!("reserved keyword `{}`", s) + } else { + format!("`{}`", s) + } + } + + pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> { + let token_str = Parser::token_to_string(t); + Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str))) + } + + pub fn unexpected<T>(&mut self) -> PResult<'a, T> { + match self.expect_one_of(&[], &[]) { + Err(e) => Err(e), + Ok(_) => unreachable!(), + } + } + + /// Expect and consume the token t. Signal an error if + /// the next token is not t. + pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> { + if self.expected_tokens.is_empty() { + if self.token == *t { + self.bump(); + Ok(()) + } else { + let token_str = Parser::token_to_string(t); + let this_token_str = self.this_token_to_string(); + Err(self.fatal(&format!("expected `{}`, found `{}`", + token_str, + this_token_str))) + } + } else { + self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[]) + } + } + + /// Expect next token to be edible or inedible token. If edible, + /// then consume it; if inedible, then return without consuming + /// anything. Signal a fatal error if next token is unexpected. + pub fn expect_one_of(&mut self, + edible: &[token::Token], + inedible: &[token::Token]) -> PResult<'a, ()>{ + fn tokens_to_string(tokens: &[TokenType]) -> String { + let mut i = tokens.iter(); + // This might be a sign we need a connect method on Iterator. + let b = i.next() + .map_or("".to_string(), |t| t.to_string()); + i.enumerate().fold(b, |mut b, (i, ref a)| { + if tokens.len() > 2 && i == tokens.len() - 2 { + b.push_str(", or "); + } else if tokens.len() == 2 && i == tokens.len() - 2 { + b.push_str(" or "); + } else { + b.push_str(", "); + } + b.push_str(&a.to_string()); + b + }) + } + if edible.contains(&self.token) { + self.bump(); + Ok(()) + } else if inedible.contains(&self.token) { + // leave it in the input + Ok(()) + } else { + let mut expected = edible.iter() + .map(|x| TokenType::Token(x.clone())) + .chain(inedible.iter().map(|x| TokenType::Token(x.clone()))) + .chain(self.expected_tokens.iter().cloned()) + .collect::<Vec<_>>(); + expected.sort_by(|a, b| a.to_string().cmp(&b.to_string())); + expected.dedup(); + let expect = tokens_to_string(&expected[..]); + let actual = self.this_token_to_string(); + Err(self.fatal( + &(if expected.len() > 1 { + (format!("expected one of {}, found `{}`", + expect, + actual)) + } else if expected.is_empty() { + (format!("unexpected token: `{}`", + actual)) + } else { + (format!("expected {}, found `{}`", + expect, + actual)) + })[..] + )) + } + } + + /// returns the span of expr, if it was not interpolated or the span of the interpolated token + fn interpolated_or_expr_span(&self, + expr: PResult<'a, P<Expr>>) + -> PResult<'a, (Span, P<Expr>)> { + expr.map(|e| { + if self.prev_token_kind == PrevTokenKind::Interpolated { + (self.prev_span, e) + } else { + (e.span, e) + } + }) + } + + pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> { + self.check_strict_keywords(); + self.check_reserved_keywords(); + match self.token { + token::Ident(i) => { + self.bump(); + Ok(i) + } + _ => { + Err(if self.prev_token_kind == PrevTokenKind::DocComment { + self.span_fatal_help(self.prev_span, + "found a documentation comment that doesn't document anything", + "doc comments must come before what they document, maybe a comment was \ + intended with `//`?") + } else { + let mut err = self.fatal(&format!("expected identifier, found `{}`", + self.this_token_to_string())); + if self.token == token::Underscore { + err.note("`_` is a wildcard pattern, not an identifier"); + } + err + }) + } + } + } + + /// Check if the next token is `tok`, and return `true` if so. + /// + /// This method will automatically add `tok` to `expected_tokens` if `tok` is not + /// encountered. + pub fn check(&mut self, tok: &token::Token) -> bool { + let is_present = self.token == *tok; + if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); } + is_present + } + + /// Consume token 'tok' if it exists. Returns true if the given + /// token was present, false otherwise. + pub fn eat(&mut self, tok: &token::Token) -> bool { + let is_present = self.check(tok); + if is_present { self.bump() } + is_present + } + + pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool { + self.expected_tokens.push(TokenType::Keyword(kw)); + self.token.is_keyword(kw) + } + + /// If the next token is the given keyword, eat it and return + /// true. Otherwise, return false. + pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool { + if self.check_keyword(kw) { + self.bump(); + true + } else { + false + } + } + + pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool { + if self.token.is_keyword(kw) { + self.bump(); + true + } else { + false + } + } + + pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool { + self.expected_tokens.push(TokenType::Token(token::Ident(ident))); + if let token::Ident(ref cur_ident) = self.token { + cur_ident.name == ident.name + } else { + false + } + } + + pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool { + if self.check_contextual_keyword(ident) { + self.bump(); + true + } else { + false + } + } + + /// If the given word is not a keyword, signal an error. + /// If the next token is not the given word, signal an error. + /// Otherwise, eat it. + pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> { + if !self.eat_keyword(kw) { + self.unexpected() + } else { + Ok(()) + } + } + + /// Signal an error if the given string is a strict keyword + pub fn check_strict_keywords(&mut self) { + if self.token.is_strict_keyword() { + let token_str = self.this_token_to_string(); + let span = self.span; + self.span_err(span, + &format!("expected identifier, found keyword `{}`", + token_str)); + } + } + + /// Signal an error if the current token is a reserved keyword + pub fn check_reserved_keywords(&mut self) { + if self.token.is_reserved_keyword() { + let token_str = self.this_token_to_string(); + self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit() + } + } + + /// Expect and consume an `&`. If `&&` is seen, replace it with a single + /// `&` and continue. If an `&` is not seen, signal an error. + fn expect_and(&mut self) -> PResult<'a, ()> { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::And))); + match self.token { + token::BinOp(token::And) => { + self.bump(); + Ok(()) + } + token::AndAnd => { + let span = self.span; + let lo = span.lo + BytePos(1); + Ok(self.bump_with(token::BinOp(token::And), lo, span.hi)) + } + _ => self.unexpected() + } + } + + pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) { + match suffix { + None => {/* everything ok */} + Some(suf) => { + let text = suf.as_str(); + if text.is_empty() { + self.span_bug(sp, "found empty literal suffix in Some") + } + self.span_err(sp, &format!("{} with a suffix is invalid", kind)); + } + } + } + + /// Attempt to consume a `<`. If `<<` is seen, replace it with a single + /// `<` and continue. If a `<` is not seen, return false. + /// + /// This is meant to be used when parsing generics on a path to get the + /// starting token. + fn eat_lt(&mut self) -> bool { + self.expected_tokens.push(TokenType::Token(token::Lt)); + match self.token { + token::Lt => { + self.bump(); + true + } + token::BinOp(token::Shl) => { + let span = self.span; + let lo = span.lo + BytePos(1); + self.bump_with(token::Lt, lo, span.hi); + true + } + _ => false, + } + } + + fn expect_lt(&mut self) -> PResult<'a, ()> { + if !self.eat_lt() { + self.unexpected() + } else { + Ok(()) + } + } + + /// Expect and consume a GT. if a >> is seen, replace it + /// with a single > and continue. If a GT is not seen, + /// signal an error. + pub fn expect_gt(&mut self) -> PResult<'a, ()> { + self.expected_tokens.push(TokenType::Token(token::Gt)); + match self.token { + token::Gt => { + self.bump(); + Ok(()) + } + token::BinOp(token::Shr) => { + let span = self.span; + let lo = span.lo + BytePos(1); + Ok(self.bump_with(token::Gt, lo, span.hi)) + } + token::BinOpEq(token::Shr) => { + let span = self.span; + let lo = span.lo + BytePos(1); + Ok(self.bump_with(token::Ge, lo, span.hi)) + } + token::Ge => { + let span = self.span; + let lo = span.lo + BytePos(1); + Ok(self.bump_with(token::Eq, lo, span.hi)) + } + _ => { + let gt_str = Parser::token_to_string(&token::Gt); + let this_token_str = self.this_token_to_string(); + Err(self.fatal(&format!("expected `{}`, found `{}`", + gt_str, + this_token_str))) + } + } + } + + pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self, + sep: Option<token::Token>, + mut f: F) + -> PResult<'a, (P<[T]>, bool)> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>, + { + let mut v = Vec::new(); + // This loop works by alternating back and forth between parsing types + // and commas. For example, given a string `A, B,>`, the parser would + // first parse `A`, then a comma, then `B`, then a comma. After that it + // would encounter a `>` and stop. This lets the parser handle trailing + // commas in generic parameters, because it can stop either after + // parsing a type or after parsing a comma. + for i in 0.. { + if self.check(&token::Gt) + || self.token == token::BinOp(token::Shr) + || self.token == token::Ge + || self.token == token::BinOpEq(token::Shr) { + break; + } + + if i % 2 == 0 { + match try!(f(self)) { + Some(result) => v.push(result), + None => return Ok((P::from_vec(v), true)) + } + } else { + if let Some(t) = sep.as_ref() { + try!(self.expect(t)); + } + + } + } + return Ok((P::from_vec(v), false)); + } + + /// Parse a sequence bracketed by '<' and '>', stopping + /// before the '>'. + pub fn parse_seq_to_before_gt<T, F>(&mut self, + sep: Option<token::Token>, + mut f: F) + -> PResult<'a, P<[T]>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, + |p| Ok(Some(try!(f(p)))))); + assert!(!returned); + return Ok(result); + } + + pub fn parse_seq_to_gt<T, F>(&mut self, + sep: Option<token::Token>, + f: F) + -> PResult<'a, P<[T]>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + let v = try!(self.parse_seq_to_before_gt(sep, f)); + try!(self.expect_gt()); + return Ok(v); + } + + pub fn parse_seq_to_gt_or_return<T, F>(&mut self, + sep: Option<token::Token>, + f: F) + -> PResult<'a, (P<[T]>, bool)> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>, + { + let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f)); + if !returned { + try!(self.expect_gt()); + } + return Ok((v, returned)); + } + + /// Eat and discard tokens until one of `kets` is encountered. Respects token trees, + /// passes through any errors encountered. Used for error recovery. + pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) { + let handler = self.diagnostic(); + + self.parse_seq_to_before_tokens(kets, + SeqSep::none(), + |p| p.parse_token_tree(), + |mut e| handler.cancel(&mut e)); + } + + /// Parse a sequence, including the closing delimiter. The function + /// f must consume tokens until reaching the next separator or + /// closing bracket. + pub fn parse_seq_to_end<T, F>(&mut self, + ket: &token::Token, + sep: SeqSep, + f: F) + -> PResult<'a, Vec<T>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + let val = self.parse_seq_to_before_end(ket, sep, f); + self.bump(); + Ok(val) + } + + /// Parse a sequence, not including the closing delimiter. The function + /// f must consume tokens until reaching the next separator or + /// closing bracket. + pub fn parse_seq_to_before_end<T, F>(&mut self, + ket: &token::Token, + sep: SeqSep, + f: F) + -> Vec<T> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, T> + { + self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit()) + } + + // `fe` is an error handler. + fn parse_seq_to_before_tokens<T, F, Fe>(&mut self, + kets: &[&token::Token], + sep: SeqSep, + mut f: F, + mut fe: Fe) + -> Vec<T> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + Fe: FnMut(DiagnosticBuilder) + { + let mut first: bool = true; + let mut v = vec![]; + while !kets.contains(&&self.token) { + match sep.sep { + Some(ref t) => { + if first { + first = false; + } else { + if let Err(e) = self.expect(t) { + fe(e); + break; + } + } + } + _ => () + } + if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) { + break; + } + + match f(self) { + Ok(t) => v.push(t), + Err(e) => { + fe(e); + break; + } + } + } + + v + } + + /// Parse a sequence, including the closing delimiter. The function + /// f must consume tokens until reaching the next separator or + /// closing bracket. + pub fn parse_unspanned_seq<T, F>(&mut self, + bra: &token::Token, + ket: &token::Token, + sep: SeqSep, + f: F) + -> PResult<'a, Vec<T>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + try!(self.expect(bra)); + let result = self.parse_seq_to_before_end(ket, sep, f); + if self.token == *ket { + self.bump(); + } + Ok(result) + } + + // NB: Do not use this function unless you actually plan to place the + // spanned list in the AST. + pub fn parse_seq<T, F>(&mut self, + bra: &token::Token, + ket: &token::Token, + sep: SeqSep, + f: F) + -> PResult<'a, Spanned<Vec<T>>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + let lo = self.span.lo; + try!(self.expect(bra)); + let result = self.parse_seq_to_before_end(ket, sep, f); + let hi = self.span.hi; + self.bump(); + Ok(spanned(lo, hi, result)) + } + + /// Advance the parser by one token + pub fn bump(&mut self) { + if self.prev_token_kind == PrevTokenKind::Eof { + // Bumping after EOF is a bad sign, usually an infinite loop. + self.bug("attempted to bump the parser past EOF (may be stuck in a loop)"); + } + + self.prev_span = self.span; + + // Record last token kind for possible error recovery. + self.prev_token_kind = match self.token { + token::DocComment(..) => PrevTokenKind::DocComment, + token::Comma => PrevTokenKind::Comma, + token::Interpolated(..) => PrevTokenKind::Interpolated, + token::Eof => PrevTokenKind::Eof, + _ => PrevTokenKind::Other, + }; + + let next = if self.lookahead_buffer.start == self.lookahead_buffer.end { + self.next_tok() + } else { + // Avoid token copies with `replace`. + let old_start = self.lookahead_buffer.start; + self.lookahead_buffer.start = (old_start + 1) % LOOKAHEAD_BUFFER_CAPACITY; + mem::replace(&mut self.lookahead_buffer.buffer[old_start], Default::default()) + }; + self.span = next.sp; + self.token = next.tok; + self.tokens_consumed += 1; + self.expected_tokens.clear(); + // check after each token + self.check_unknown_macro_variable(); + } + + /// Advance the parser by one token and return the bumped token. + pub fn bump_and_get(&mut self) -> token::Token { + let old_token = mem::replace(&mut self.token, token::Underscore); + self.bump(); + old_token + } + + /// Advance the parser using provided token as a next one. Use this when + /// consuming a part of a token. For example a single `<` from `<<`. + pub fn bump_with(&mut self, + next: token::Token, + lo: BytePos, + hi: BytePos) { + self.prev_span = mk_sp(self.span.lo, lo); + // It would be incorrect to record the kind of the current token, but + // fortunately for tokens currently using `bump_with`, the + // prev_token_kind will be of no use anyway. + self.prev_token_kind = PrevTokenKind::Other; + self.span = mk_sp(lo, hi); + self.token = next; + self.expected_tokens.clear(); + } + + pub fn look_ahead<R, F>(&mut self, dist: usize, f: F) -> R where + F: FnOnce(&token::Token) -> R, + { + if dist == 0 { + f(&self.token) + } else if dist < LOOKAHEAD_BUFFER_CAPACITY { + while self.lookahead_buffer.len() < dist { + self.lookahead_buffer.buffer[self.lookahead_buffer.end] = self.next_tok(); + self.lookahead_buffer.end = + (self.lookahead_buffer.end + 1) % LOOKAHEAD_BUFFER_CAPACITY; + } + let index = (self.lookahead_buffer.start + dist - 1) % LOOKAHEAD_BUFFER_CAPACITY; + f(&self.lookahead_buffer.buffer[index].tok) + } else { + self.bug("lookahead distance is too large"); + } + } + pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_fatal(self.span, m) + } + pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_fatal(sp, m) + } + pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> { + let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m); + err.help(help); + err + } + pub fn bug(&self, m: &str) -> ! { + self.sess.span_diagnostic.span_bug(self.span, m) + } + pub fn warn(&self, m: &str) { + self.sess.span_diagnostic.span_warn(self.span, m) + } + pub fn span_warn(&self, sp: Span, m: &str) { + self.sess.span_diagnostic.span_warn(sp, m) + } + pub fn span_err(&self, sp: Span, m: &str) { + self.sess.span_diagnostic.span_err(sp, m) + } + pub fn span_err_help(&self, sp: Span, m: &str, h: &str) { + let mut err = self.sess.span_diagnostic.mut_span_err(sp, m); + err.help(h); + err.emit(); + } + pub fn span_bug(&self, sp: Span, m: &str) -> ! { + self.sess.span_diagnostic.span_bug(sp, m) + } + pub fn abort_if_errors(&self) { + self.sess.span_diagnostic.abort_if_errors(); + } + + fn cancel(&self, err: &mut DiagnosticBuilder) { + self.sess.span_diagnostic.cancel(err) + } + + pub fn diagnostic(&self) -> &'a errors::Handler { + &self.sess.span_diagnostic + } + + /// Is the current token one of the keywords that signals a bare function + /// type? + pub fn token_is_bare_fn_keyword(&mut self) -> bool { + self.check_keyword(keywords::Fn) || + self.check_keyword(keywords::Unsafe) || + self.check_keyword(keywords::Extern) + } + + pub fn get_lifetime(&mut self) -> ast::Ident { + match self.token { + token::Lifetime(ref ident) => *ident, + _ => self.bug("not a lifetime"), + } + } + + pub fn parse_for_in_type(&mut self) -> PResult<'a, TyKind> { + /* + Parses whatever can come after a `for` keyword in a type. + The `for` hasn't been consumed. + + Deprecated: + + - for <'lt> |S| -> T + + Eventually: + + - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T + - for <'lt> path::foo(a, b) + + */ + + // parse <'lt> + let lo = self.span.lo; + + let lifetime_defs = try!(self.parse_late_bound_lifetime_defs()); + + // examine next token to decide to do + if self.token_is_bare_fn_keyword() { + self.parse_ty_bare_fn(lifetime_defs) + } else { + let hi = self.span.hi; + let trait_ref = try!(self.parse_trait_ref()); + let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs, + trait_ref: trait_ref, + span: mk_sp(lo, hi)}; + let other_bounds = if self.eat(&token::BinOp(token::Plus)) { + try!(self.parse_ty_param_bounds()) + } else { + P::new() + }; + let all_bounds = + Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter() + .chain(other_bounds.into_vec()) + .collect(); + Ok(ast::TyKind::PolyTraitRef(all_bounds)) + } + } + + pub fn parse_impl_trait_type(&mut self) -> PResult<'a, TyKind> { + /* + Parses whatever can come after a `impl` keyword in a type. + The `impl` has already been consumed. + */ + + let bounds = try!(self.parse_ty_param_bounds()); + + if !bounds.iter().any(|b| if let TraitTyParamBound(..) = *b { true } else { false }) { + self.span_err(self.prev_span, "at least one trait must be specified"); + } + + Ok(ast::TyKind::ImplTrait(bounds)) + } + + pub fn parse_ty_path(&mut self) -> PResult<'a, TyKind> { + Ok(TyKind::Path(None, try!(self.parse_path(PathStyle::Type)))) + } + + /// parse a TyKind::BareFn type: + pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) + -> PResult<'a, TyKind> { + /* + + [unsafe] [extern "ABI"] fn (S) -> T + ^~~~^ ^~~~^ ^~^ ^ + | | | | + | | | Return type + | | Argument types + | | + | ABI + Function Style + */ + + let unsafety = try!(self.parse_unsafety()); + let abi = if self.eat_keyword(keywords::Extern) { + try!(self.parse_opt_abi()).unwrap_or(Abi::C) + } else { + Abi::Rust + }; + + try!(self.expect_keyword(keywords::Fn)); + let (inputs, variadic) = try!(self.parse_fn_args(false, true)); + let ret_ty = try!(self.parse_ret_ty()); + let decl = P(FnDecl { + inputs: inputs, + output: ret_ty, + variadic: variadic + }); + Ok(TyKind::BareFn(P(BareFnTy { + abi: abi, + unsafety: unsafety, + lifetimes: lifetime_defs, + decl: decl + }))) + } + + pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> { + if self.eat_keyword(keywords::Unsafe) { + return Ok(Unsafety::Unsafe); + } else { + return Ok(Unsafety::Normal); + } + } + + /// Parse the items in a trait declaration + pub fn parse_trait_item(&mut self) -> PResult<'a, TraitItem> { + maybe_whole!(self, NtTraitItem, |x| x); + let mut attrs = try!(self.parse_outer_attributes()); + let lo = self.span.lo; + + let (name, node) = if self.eat_keyword(keywords::Type) { + let TyParam {ident, bounds, default, ..} = try!(self.parse_ty_param(vec![])); + try!(self.expect(&token::Semi)); + (ident, TraitItemKind::Type(bounds, default)) + } else if self.is_const_item() { + try!(self.expect_keyword(keywords::Const)); + let ident = try!(self.parse_ident()); + try!(self.expect(&token::Colon)); + let ty = try!(self.parse_ty_sum()); + let default = if self.check(&token::Eq) { + self.bump(); + let expr = try!(self.parse_expr()); + try!(self.expect(&token::Semi)); + Some(expr) + } else { + try!(self.expect(&token::Semi)); + None + }; + (ident, TraitItemKind::Const(ty, default)) + } else if self.token.is_path_start() { + // trait item macro. + // code copied from parse_macro_use_or_failure... abstraction! + let lo = self.span.lo; + let pth = try!(self.parse_path(PathStyle::Mod)); + try!(self.expect(&token::Not)); + + // eat a matched-delimiter token tree: + let delim = try!(self.expect_open_delim()); + let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim), + SeqSep::none(), + |pp| pp.parse_token_tree())); + if delim != token::Brace { + try!(self.expect(&token::Semi)) + } + + let mac = spanned(lo, self.prev_span.hi, Mac_ { path: pth, tts: tts }); + (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac)) + } else { + let (constness, unsafety, abi) = match self.parse_fn_front_matter() { + Ok(cua) => cua, + Err(e) => { + loop { + match self.token { + token::Eof => break, + token::CloseDelim(token::Brace) | + token::Semi => { + self.bump(); + break; + } + token::OpenDelim(token::Brace) => { + try!(self.parse_token_tree()); + break; + } + _ => self.bump(), + } + } + + return Err(e); + } + }; + + let ident = try!(self.parse_ident()); + let mut generics = try!(self.parse_generics()); + + let d = try!(self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{ + // This is somewhat dubious; We don't want to allow + // argument names to be left off if there is a + // definition... + p.parse_arg_general(false) + })); + + generics.where_clause = try!(self.parse_where_clause()); + let sig = ast::MethodSig { + unsafety: unsafety, + constness: constness, + decl: d, + generics: generics, + abi: abi, + }; + + let body = match self.token { + token::Semi => { + self.bump(); + debug!("parse_trait_methods(): parsing required method"); + None + } + token::OpenDelim(token::Brace) => { + debug!("parse_trait_methods(): parsing provided method"); + let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block()); + attrs.extend(inner_attrs.iter().cloned()); + Some(body) + } + _ => { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str))); + } + }; + (ident, ast::TraitItemKind::Method(sig, body)) + }; + + Ok(TraitItem { + id: ast::DUMMY_NODE_ID, + ident: name, + attrs: attrs, + node: node, + span: mk_sp(lo, self.prev_span.hi), + }) + } + + + /// Parse the items in a trait declaration + pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<TraitItem>> { + self.parse_unspanned_seq( + &token::OpenDelim(token::Brace), + &token::CloseDelim(token::Brace), + SeqSep::none(), + |p| -> PResult<'a, TraitItem> { + p.parse_trait_item() + }) + } + + /// Parse a possibly mutable type + pub fn parse_mt(&mut self) -> PResult<'a, MutTy> { + let mutbl = try!(self.parse_mutability()); + let t = try!(self.parse_ty()); + Ok(MutTy { ty: t, mutbl: mutbl }) + } + + /// Parse optional return type [ -> TY ] in function decl + pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> { + if self.eat(&token::RArrow) { + Ok(FunctionRetTy::Ty(try!(self.parse_ty()))) + } else { + let pos = self.span.lo; + Ok(FunctionRetTy::Default(mk_sp(pos, pos))) + } + } + + /// Parse a type in a context where `T1+T2` is allowed. + pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> { + let lo = self.span.lo; + let lhs = try!(self.parse_ty()); + + if !self.eat(&token::BinOp(token::Plus)) { + return Ok(lhs); + } + + let bounds = try!(self.parse_ty_param_bounds()); + + // In type grammar, `+` is treated like a binary operator, + // and hence both L and R side are required. + if bounds.is_empty() { + let prev_span = self.prev_span; + self.span_err(prev_span, + "at least one type parameter bound \ + must be specified"); + } + + let sp = mk_sp(lo, self.prev_span.hi); + let sum = ast::TyKind::ObjectSum(lhs, bounds); + Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})) + } + + /// Parse a type. + pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> { + maybe_whole!(self, NtTy, |x| x); + + let lo = self.span.lo; + + let t = if self.check(&token::OpenDelim(token::Paren)) { + self.bump(); + + // (t) is a parenthesized ty + // (t,) is the type of a tuple with only one field, + // of type t + let mut ts = vec![]; + let mut last_comma = false; + while self.token != token::CloseDelim(token::Paren) { + ts.push(try!(self.parse_ty_sum())); + if self.check(&token::Comma) { + last_comma = true; + self.bump(); + } else { + last_comma = false; + break; + } + } + + try!(self.expect(&token::CloseDelim(token::Paren))); + if ts.len() == 1 && !last_comma { + TyKind::Paren(ts.into_iter().nth(0).unwrap()) + } else { + TyKind::Tup(ts) + } + } else if self.eat(&token::Not) { + TyKind::Never + } else if self.check(&token::BinOp(token::Star)) { + // STAR POINTER (bare pointer?) + self.bump(); + TyKind::Ptr(try!(self.parse_ptr())) + } else if self.check(&token::OpenDelim(token::Bracket)) { + // VECTOR + try!(self.expect(&token::OpenDelim(token::Bracket))); + let t = try!(self.parse_ty_sum()); + + // Parse the `; e` in `[ i32; e ]` + // where `e` is a const expression + let t = match try!(self.maybe_parse_fixed_length_of_vec()) { + None => TyKind::Slice(t), + Some(suffix) => TyKind::Array(t, suffix) + }; + try!(self.expect(&token::CloseDelim(token::Bracket))); + t + } else if self.check(&token::BinOp(token::And)) || + self.token == token::AndAnd { + // BORROWED POINTER + try!(self.expect_and()); + try!(self.parse_borrowed_pointee()) + } else if self.check_keyword(keywords::For) { + try!(self.parse_for_in_type()) + } else if self.eat_keyword(keywords::Impl) { + try!(self.parse_impl_trait_type()) + } else if self.token_is_bare_fn_keyword() { + // BARE FUNCTION + try!(self.parse_ty_bare_fn(Vec::new())) + } else if self.eat_keyword_noexpect(keywords::Typeof) { + // TYPEOF + // In order to not be ambiguous, the type must be surrounded by parens. + try!(self.expect(&token::OpenDelim(token::Paren))); + let e = try!(self.parse_expr()); + try!(self.expect(&token::CloseDelim(token::Paren))); + TyKind::Typeof(e) + } else if self.eat_lt() { + + let (qself, path) = + try!(self.parse_qualified_path(PathStyle::Type)); + + TyKind::Path(Some(qself), path) + } else if self.token.is_path_start() { + let path = try!(self.parse_path(PathStyle::Type)); + if self.eat(&token::Not) { + // MACRO INVOCATION + let delim = try!(self.expect_open_delim()); + let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim), + SeqSep::none(), + |p| p.parse_token_tree())); + let hi = self.span.hi; + TyKind::Mac(spanned(lo, hi, Mac_ { path: path, tts: tts })) + } else { + // NAMED TYPE + TyKind::Path(None, path) + } + } else if self.eat(&token::Underscore) { + // TYPE TO BE INFERRED + TyKind::Infer + } else { + let msg = format!("expected type, found {}", self.this_token_descr()); + return Err(self.fatal(&msg)); + }; + + let sp = mk_sp(lo, self.prev_span.hi); + Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})) + } + + pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> { + // look for `&'lt` or `&'foo ` and interpret `foo` as the region name: + let opt_lifetime = try!(self.parse_opt_lifetime()); + + let mt = try!(self.parse_mt()); + return Ok(TyKind::Rptr(opt_lifetime, mt)); + } + + pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> { + let mutbl = if self.eat_keyword(keywords::Mut) { + Mutability::Mutable + } else if self.eat_keyword(keywords::Const) { + Mutability::Immutable + } else { + let span = self.prev_span; + self.span_err(span, + "expected mut or const in raw pointer type (use \ + `*mut T` or `*const T` as appropriate)"); + Mutability::Immutable + }; + let t = try!(self.parse_ty()); + Ok(MutTy { ty: t, mutbl: mutbl }) + } + + pub fn is_named_argument(&mut self) -> bool { + let offset = match self.token { + token::BinOp(token::And) => 1, + token::AndAnd => 1, + _ if self.token.is_keyword(keywords::Mut) => 1, + _ => 0 + }; + + debug!("parser is_named_argument offset:{}", offset); + + if offset == 0 { + is_ident_or_underscore(&self.token) + && self.look_ahead(1, |t| *t == token::Colon) + } else { + self.look_ahead(offset, |t| is_ident_or_underscore(t)) + && self.look_ahead(offset + 1, |t| *t == token::Colon) + } + } + + /// This version of parse arg doesn't necessarily require + /// identifier names. + pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> { + maybe_whole!(self, NtArg, |x| x); + + let pat = if require_name || self.is_named_argument() { + debug!("parse_arg_general parse_pat (require_name:{})", + require_name); + let pat = try!(self.parse_pat()); + + try!(self.expect(&token::Colon)); + pat + } else { + debug!("parse_arg_general ident_to_pat"); + let sp = self.prev_span; + let spanned = Spanned { span: sp, node: keywords::Invalid.ident() }; + P(Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), + spanned, None), + span: sp + }) + }; + + let t = try!(self.parse_ty_sum()); + + Ok(Arg { + ty: t, + pat: pat, + id: ast::DUMMY_NODE_ID, + }) + } + + /// Parse a single function argument + pub fn parse_arg(&mut self) -> PResult<'a, Arg> { + self.parse_arg_general(true) + } + + /// Parse an argument in a lambda header e.g. |arg, arg| + pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> { + let pat = try!(self.parse_pat()); + let t = if self.eat(&token::Colon) { + try!(self.parse_ty_sum()) + } else { + P(Ty { + id: ast::DUMMY_NODE_ID, + node: TyKind::Infer, + span: mk_sp(self.span.lo, self.span.hi), + }) + }; + Ok(Arg { + ty: t, + pat: pat, + id: ast::DUMMY_NODE_ID + }) + } + + pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> { + if self.check(&token::Semi) { + self.bump(); + Ok(Some(try!(self.parse_expr()))) + } else { + Ok(None) + } + } + + /// Matches token_lit = LIT_INTEGER | ... + pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> { + let out = match self.token { + token::Interpolated(ref nt) => match **nt { + token::NtExpr(ref v) => match v.node { + ExprKind::Lit(ref lit) => { lit.node.clone() } + _ => { return self.unexpected_last(&self.token); } + }, + _ => { return self.unexpected_last(&self.token); } + }, + token::Literal(lit, suf) => { + let (suffix_illegal, out) = match lit { + token::Byte(i) => (true, LitKind::Byte(parse::byte_lit(&i.as_str()).0)), + token::Char(i) => (true, LitKind::Char(parse::char_lit(&i.as_str()).0)), + + // there are some valid suffixes for integer and + // float literals, so all the handling is done + // internally. + token::Integer(s) => { + let diag = &self.sess.span_diagnostic; + (false, parse::integer_lit(&s.as_str(), suf, diag, self.span)) + } + token::Float(s) => { + let diag = &self.sess.span_diagnostic; + (false, parse::float_lit(&s.as_str(), suf, diag, self.span)) + } + + token::Str_(s) => { + let s = Symbol::intern(&parse::str_lit(&s.as_str())); + (true, LitKind::Str(s, ast::StrStyle::Cooked)) + } + token::StrRaw(s, n) => { + let s = Symbol::intern(&parse::raw_str_lit(&s.as_str())); + (true, LitKind::Str(s, ast::StrStyle::Raw(n))) + } + token::ByteStr(i) => { + (true, LitKind::ByteStr(parse::byte_str_lit(&i.as_str()))) + } + token::ByteStrRaw(i, _) => { + (true, LitKind::ByteStr(Rc::new(i.to_string().into_bytes()))) + } + }; + + if suffix_illegal { + let sp = self.span; + self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf) + } + + out + } + _ => { return self.unexpected_last(&self.token); } + }; + + self.bump(); + Ok(out) + } + + /// Matches lit = true | false | token_lit + pub fn parse_lit(&mut self) -> PResult<'a, Lit> { + let lo = self.span.lo; + let lit = if self.eat_keyword(keywords::True) { + LitKind::Bool(true) + } else if self.eat_keyword(keywords::False) { + LitKind::Bool(false) + } else { + let lit = try!(self.parse_lit_token()); + lit + }; + Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.prev_span.hi) }) + } + + /// matches '-' lit | lit + pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> { + let minus_lo = self.span.lo; + let minus_present = self.eat(&token::BinOp(token::Minus)); + let lo = self.span.lo; + let literal = P(try!(self.parse_lit())); + let hi = self.prev_span.hi; + let expr = self.mk_expr(lo, hi, ExprKind::Lit(literal), ThinVec::new()); + + if minus_present { + let minus_hi = self.prev_span.hi; + let unary = self.mk_unary(UnOp::Neg, expr); + Ok(self.mk_expr(minus_lo, minus_hi, unary, ThinVec::new())) + } else { + Ok(expr) + } + } + + pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> { + match self.token { + token::Ident(sid) if self.token.is_path_segment_keyword() => { + self.bump(); + Ok(sid) + } + _ => self.parse_ident(), + } + } + + /// Parses qualified path. + /// + /// Assumes that the leading `<` has been parsed already. + /// + /// Qualifed paths are a part of the universal function call + /// syntax (UFCS). + /// + /// `qualified_path = <type [as trait_ref]>::path` + /// + /// See `parse_path` for `mode` meaning. + /// + /// # Examples: + /// + /// `<T as U>::a` + /// `<T as U>::F::a::<S>` + pub fn parse_qualified_path(&mut self, mode: PathStyle) + -> PResult<'a, (QSelf, ast::Path)> { + let span = self.prev_span; + let self_type = try!(self.parse_ty_sum()); + let mut path = if self.eat_keyword(keywords::As) { + try!(self.parse_path(PathStyle::Type)) + } else { + ast::Path { + span: span, + segments: vec![] + } + }; + + let qself = QSelf { + ty: self_type, + position: path.segments.len() + }; + + try!(self.expect(&token::Gt)); + try!(self.expect(&token::ModSep)); + + let segments = match mode { + PathStyle::Type => { + try!(self.parse_path_segments_without_colons()) + } + PathStyle::Expr => { + try!(self.parse_path_segments_with_colons()) + } + PathStyle::Mod => { + try!(self.parse_path_segments_without_types()) + } + }; + path.segments.extend(segments); + + path.span.hi = self.prev_span.hi; + + Ok((qself, path)) + } + + /// Parses a path and optional type parameter bounds, depending on the + /// mode. The `mode` parameter determines whether lifetimes, types, and/or + /// bounds are permitted and whether `::` must precede type parameter + /// groups. + pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> { + maybe_whole!(self, NtPath, |x| x); + + let lo = self.span.lo; + let is_global = self.eat(&token::ModSep); + + // Parse any number of segments and bound sets. A segment is an + // identifier followed by an optional lifetime and a set of types. + // A bound set is a set of type parameter bounds. + let mut segments = match mode { + PathStyle::Type => { + try!(self.parse_path_segments_without_colons()) + } + PathStyle::Expr => { + try!(self.parse_path_segments_with_colons()) + } + PathStyle::Mod => { + try!(self.parse_path_segments_without_types()) + } + }; + + if is_global { + segments.insert(0, ast::PathSegment::crate_root()); + } + + // Assemble the span. + let span = mk_sp(lo, self.prev_span.hi); + + // Assemble the result. + Ok(ast::Path { + span: span, + segments: segments, + }) + } + + /// Examples: + /// - `a::b<T,U>::c<V,W>` + /// - `a::b<T,U>::c(V) -> W` + /// - `a::b<T,U>::c(V)` + pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> { + let mut segments = Vec::new(); + loop { + // First, parse an identifier. + let identifier = try!(self.parse_path_segment_ident()); + + if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) { + self.bump(); + let prev_span = self.prev_span; + + let mut err = self.diagnostic().struct_span_err(prev_span, + "unexpected token: `::`"); + err.help( + "use `<...>` instead of `::<...>` if you meant to specify type arguments"); + err.emit(); + } + + // Parse types, optionally. + let parameters = if self.eat_lt() { + let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt()); + ast::AngleBracketedParameterData { + lifetimes: lifetimes, + types: P::from_vec(types), + bindings: P::from_vec(bindings), + }.into() + } else if self.eat(&token::OpenDelim(token::Paren)) { + let lo = self.prev_span.lo; + + let inputs = try!(self.parse_seq_to_end( + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| p.parse_ty_sum())); + + let output_ty = if self.eat(&token::RArrow) { + Some(try!(self.parse_ty())) + } else { + None + }; + + let hi = self.prev_span.hi; + + Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData { + span: mk_sp(lo, hi), + inputs: inputs, + output: output_ty, + }))) + } else { + None + }; + + // Assemble and push the result. + segments.push(ast::PathSegment { identifier: identifier, parameters: parameters }); + + // Continue only if we see a `::` + if !self.eat(&token::ModSep) { + return Ok(segments); + } + } + } + + /// Examples: + /// - `a::b::<T,U>::c` + pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> { + let mut segments = Vec::new(); + loop { + // First, parse an identifier. + let identifier = try!(self.parse_path_segment_ident()); + + // If we do not see a `::`, stop. + if !self.eat(&token::ModSep) { + segments.push(identifier.into()); + return Ok(segments); + } + + // Check for a type segment. + if self.eat_lt() { + // Consumed `a::b::<`, go look for types + let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt()); + segments.push(ast::PathSegment { + identifier: identifier, + parameters: ast::AngleBracketedParameterData { + lifetimes: lifetimes, + types: P::from_vec(types), + bindings: P::from_vec(bindings), + }.into(), + }); + + // Consumed `a::b::<T,U>`, check for `::` before proceeding + if !self.eat(&token::ModSep) { + return Ok(segments); + } + } else { + // Consumed `a::`, go look for `b` + segments.push(identifier.into()); + } + } + } + + /// Examples: + /// - `a::b::c` + pub fn parse_path_segments_without_types(&mut self) + -> PResult<'a, Vec<ast::PathSegment>> { + let mut segments = Vec::new(); + loop { + // First, parse an identifier. + let identifier = try!(self.parse_path_segment_ident()); + + // Assemble and push the result. + segments.push(identifier.into()); + + // If we do not see a `::` or see `::{`/`::*`, stop. + if !self.check(&token::ModSep) || self.is_import_coupler() { + return Ok(segments); + } else { + self.bump(); + } + } + } + + /// parses 0 or 1 lifetime + pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> { + match self.token { + token::Lifetime(..) => { + Ok(Some(try!(self.parse_lifetime()))) + } + _ => { + Ok(None) + } + } + } + + /// Parses a single lifetime + /// Matches lifetime = LIFETIME + pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> { + match self.token { + token::Lifetime(i) => { + let span = self.span; + self.bump(); + return Ok(ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: span, + name: i.name + }); + } + _ => { + return Err(self.fatal("expected a lifetime name")); + } + } + } + + /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def = + /// lifetime [':' lifetimes]` + /// + /// If `followed_by_ty_params` is None, then we are in a context + /// where only lifetime parameters are allowed, and thus we should + /// error if we encounter attributes after the bound lifetimes. + /// + /// If `followed_by_ty_params` is Some(r), then there may be type + /// parameter bindings after the lifetimes, so we should pass + /// along the parsed attributes to be attached to the first such + /// type parmeter. + pub fn parse_lifetime_defs(&mut self, + followed_by_ty_params: Option<&mut Vec<ast::Attribute>>) + -> PResult<'a, Vec<ast::LifetimeDef>> + { + let mut res = Vec::new(); + loop { + let attrs = try!(self.parse_outer_attributes()); + match self.token { + token::Lifetime(_) => { + let lifetime = try!(self.parse_lifetime()); + let bounds = + if self.eat(&token::Colon) { + try!(self.parse_lifetimes(token::BinOp(token::Plus))) + } else { + Vec::new() + }; + res.push(ast::LifetimeDef { attrs: attrs.into(), + lifetime: lifetime, + bounds: bounds }); + } + + _ => { + if let Some(recv) = followed_by_ty_params { + assert!(recv.is_empty()); + *recv = attrs; + debug!("parse_lifetime_defs ret {:?}", res); + return Ok(res); + } else if !attrs.is_empty() { + let msg = "trailing attribute after lifetime parameters"; + return Err(self.fatal(msg)); + } + } + } + + match self.token { + token::Comma => { self.bump();} + token::Gt => { return Ok(res); } + token::BinOp(token::Shr) => { return Ok(res); } + _ => { + let this_token_str = self.this_token_to_string(); + let msg = format!("expected `,` or `>` after lifetime \ + name, found `{}`", + this_token_str); + return Err(self.fatal(&msg[..])); + } + } + } + } + + /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty + /// one too, but putting that in there messes up the grammar.... + /// + /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by + /// either a comma or `>`. Used when parsing type parameter lists, where we expect something + /// like `<'a, 'b, T>`. + pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> { + + let mut res = Vec::new(); + loop { + match self.token { + token::Lifetime(_) => { + res.push(try!(self.parse_lifetime())); + } + _ => { + return Ok(res); + } + } + + if self.token != sep { + return Ok(res); + } + + self.bump(); + } + } + + /// Parse mutability (`mut` or nothing). + pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> { + if self.eat_keyword(keywords::Mut) { + Ok(Mutability::Mutable) + } else { + Ok(Mutability::Immutable) + } + } + + pub fn parse_field_name(&mut self) -> PResult<'a, Ident> { + if let token::Literal(token::Integer(name), None) = self.token { + self.bump(); + Ok(Ident::with_empty_ctxt(name)) + } else { + self.parse_ident() + } + } + + /// Parse ident (COLON expr)? + pub fn parse_field(&mut self) -> PResult<'a, Field> { + let lo = self.span.lo; + let hi; + + // Check if a colon exists one ahead. This means we're parsing a fieldname. + let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) { + let fieldname = try!(self.parse_field_name()); + self.bump(); + hi = self.prev_span.hi; + (fieldname, try!(self.parse_expr()), false) + } else { + let fieldname = try!(self.parse_ident()); + hi = self.prev_span.hi; + + // Mimic `x: x` for the `x` field shorthand. + let path = ast::Path::from_ident(mk_sp(lo, hi), fieldname); + (fieldname, self.mk_expr(lo, hi, ExprKind::Path(None, path), ThinVec::new()), true) + }; + Ok(ast::Field { + ident: spanned(lo, hi, fieldname), + span: mk_sp(lo, expr.span.hi), + expr: expr, + is_shorthand: is_shorthand, + }) + } + + pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: ExprKind, attrs: ThinVec<Attribute>) + -> P<Expr> { + P(Expr { + id: ast::DUMMY_NODE_ID, + node: node, + span: mk_sp(lo, hi), + attrs: attrs.into(), + }) + } + + pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind { + ExprKind::Unary(unop, expr) + } + + pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind { + ExprKind::Binary(binop, lhs, rhs) + } + + pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind { + ExprKind::Call(f, args) + } + + fn mk_method_call(&mut self, + ident: ast::SpannedIdent, + tps: Vec<P<Ty>>, + args: Vec<P<Expr>>) + -> ast::ExprKind { + ExprKind::MethodCall(ident, tps, args) + } + + pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind { + ExprKind::Index(expr, idx) + } + + pub fn mk_range(&mut self, + start: Option<P<Expr>>, + end: Option<P<Expr>>, + limits: RangeLimits) + -> PResult<'a, ast::ExprKind> { + if end.is_none() && limits == RangeLimits::Closed { + Err(self.span_fatal_help(self.span, + "inclusive range with no end", + "inclusive ranges must be bounded at the end \ + (`...b` or `a...b`)")) + } else { + Ok(ExprKind::Range(start, end, limits)) + } + } + + pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind { + ExprKind::Field(expr, ident) + } + + pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind { + ExprKind::TupField(expr, idx) + } + + pub fn mk_assign_op(&mut self, binop: ast::BinOp, + lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind { + ExprKind::AssignOp(binop, lhs, rhs) + } + + pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, + m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> { + P(Expr { + id: ast::DUMMY_NODE_ID, + node: ExprKind::Mac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}), + span: mk_sp(lo, hi), + attrs: attrs, + }) + } + + pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> { + let span = &self.span; + let lv_lit = P(codemap::Spanned { + node: LitKind::Int(i as u64, ast::LitIntType::Unsigned(UintTy::U32)), + span: *span + }); + + P(Expr { + id: ast::DUMMY_NODE_ID, + node: ExprKind::Lit(lv_lit), + span: *span, + attrs: attrs, + }) + } + + fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> { + self.expected_tokens.push(TokenType::Token(token::Gt)); + match self.token { + token::OpenDelim(delim) => { + self.bump(); + Ok(delim) + }, + _ => Err(self.fatal("expected open delimiter")), + } + } + + /// At the bottom (top?) of the precedence hierarchy, + /// parse things like parenthesized exprs, + /// macros, return, etc. + /// + /// NB: This does not parse outer attributes, + /// and is private because it only works + /// correctly if called from parse_dot_or_call_expr(). + fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> { + maybe_whole_expr!(self); + + // Outer attributes are already parsed and will be + // added to the return value after the fact. + // + // Therefore, prevent sub-parser from parsing + // attributes by giving them a empty "already parsed" list. + let mut attrs = ThinVec::new(); + + let lo = self.span.lo; + let mut hi = self.span.hi; + + let ex: ExprKind; + + // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr(). + match self.token { + token::OpenDelim(token::Paren) => { + self.bump(); + + attrs.extend(try!(self.parse_inner_attributes())); + + // (e) is parenthesized e + // (e,) is a tuple with only one field, e + let mut es = vec![]; + let mut trailing_comma = false; + while self.token != token::CloseDelim(token::Paren) { + es.push(try!(self.parse_expr())); + try!(self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])); + if self.check(&token::Comma) { + trailing_comma = true; + + self.bump(); + } else { + trailing_comma = false; + break; + } + } + self.bump(); + + hi = self.prev_span.hi; + return if es.len() == 1 && !trailing_comma { + Ok(self.mk_expr(lo, hi, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs)) + } else { + Ok(self.mk_expr(lo, hi, ExprKind::Tup(es), attrs)) + } + }, + token::OpenDelim(token::Brace) => { + return self.parse_block_expr(lo, BlockCheckMode::Default, attrs); + }, + token::BinOp(token::Or) | token::OrOr => { + let lo = self.span.lo; + return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs); + }, + token::OpenDelim(token::Bracket) => { + self.bump(); + + attrs.extend(try!(self.parse_inner_attributes())); + + if self.check(&token::CloseDelim(token::Bracket)) { + // Empty vector. + self.bump(); + ex = ExprKind::Vec(Vec::new()); + } else { + // Nonempty vector. + let first_expr = try!(self.parse_expr()); + if self.check(&token::Semi) { + // Repeating array syntax: [ 0; 512 ] + self.bump(); + let count = try!(self.parse_expr()); + try!(self.expect(&token::CloseDelim(token::Bracket))); + ex = ExprKind::Repeat(first_expr, count); + } else if self.check(&token::Comma) { + // Vector with two or more elements. + self.bump(); + let remaining_exprs = try!(self.parse_seq_to_end( + &token::CloseDelim(token::Bracket), + SeqSep::trailing_allowed(token::Comma), + |p| Ok(try!(p.parse_expr())) + )); + let mut exprs = vec![first_expr]; + exprs.extend(remaining_exprs); + ex = ExprKind::Vec(exprs); + } else { + // Vector with one element. + try!(self.expect(&token::CloseDelim(token::Bracket))); + ex = ExprKind::Vec(vec![first_expr]); + } + } + hi = self.prev_span.hi; + } + _ => { + if self.eat_lt() { + let (qself, path) = + try!(self.parse_qualified_path(PathStyle::Expr)); + hi = path.span.hi; + return Ok(self.mk_expr(lo, hi, ExprKind::Path(Some(qself), path), attrs)); + } + if self.eat_keyword(keywords::Move) { + let lo = self.prev_span.lo; + return self.parse_lambda_expr(lo, CaptureBy::Value, attrs); + } + if self.eat_keyword(keywords::If) { + return self.parse_if_expr(attrs); + } + if self.eat_keyword(keywords::For) { + let lo = self.prev_span.lo; + return self.parse_for_expr(None, lo, attrs); + } + if self.eat_keyword(keywords::While) { + let lo = self.prev_span.lo; + return self.parse_while_expr(None, lo, attrs); + } + if self.token.is_lifetime() { + let label = Spanned { node: self.get_lifetime(), + span: self.span }; + let lo = self.span.lo; + self.bump(); + try!(self.expect(&token::Colon)); + if self.eat_keyword(keywords::While) { + return self.parse_while_expr(Some(label), lo, attrs) + } + if self.eat_keyword(keywords::For) { + return self.parse_for_expr(Some(label), lo, attrs) + } + if self.eat_keyword(keywords::Loop) { + return self.parse_loop_expr(Some(label), lo, attrs) + } + return Err(self.fatal("expected `while`, `for`, or `loop` after a label")) + } + if self.eat_keyword(keywords::Loop) { + let lo = self.prev_span.lo; + return self.parse_loop_expr(None, lo, attrs); + } + if self.eat_keyword(keywords::Continue) { + let ex = if self.token.is_lifetime() { + let ex = ExprKind::Continue(Some(Spanned{ + node: self.get_lifetime(), + span: self.span + })); + self.bump(); + ex + } else { + ExprKind::Continue(None) + }; + let hi = self.prev_span.hi; + return Ok(self.mk_expr(lo, hi, ex, attrs)); + } + if self.eat_keyword(keywords::Match) { + return self.parse_match_expr(attrs); + } + if self.eat_keyword(keywords::Unsafe) { + return self.parse_block_expr( + lo, + BlockCheckMode::Unsafe(ast::UserProvided), + attrs); + } + if self.eat_keyword(keywords::Return) { + if self.token.can_begin_expr() { + let e = try!(self.parse_expr()); + hi = e.span.hi; + ex = ExprKind::Ret(Some(e)); + } else { + ex = ExprKind::Ret(None); + } + } else if self.eat_keyword(keywords::Break) { + let lt = if self.token.is_lifetime() { + let spanned_lt = Spanned { + node: self.get_lifetime(), + span: self.span + }; + self.bump(); + Some(spanned_lt) + } else { + None + }; + let e = if self.token.can_begin_expr() + && !(self.token == token::OpenDelim(token::Brace) + && self.restrictions.contains( + Restrictions::restriction_no_struct_literal())) { + Some(try!(self.parse_expr())) + } else { + None + }; + ex = ExprKind::Break(lt, e); + hi = self.prev_span.hi; + } else if self.token.is_keyword(keywords::Let) { + // Catch this syntax error here, instead of in `check_strict_keywords`, so + // that we can explicitly mention that let is not to be used as an expression + let mut db = self.fatal("expected expression, found statement (`let`)"); + db.note("variable declaration using `let` is a statement"); + return Err(db); + } else if self.token.is_path_start() { + let pth = try!(self.parse_path(PathStyle::Expr)); + + // `!`, as an operator, is prefix, so we know this isn't that + if self.eat(&token::Not) { + // MACRO INVOCATION expression + let delim = try!(self.expect_open_delim()); + let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim), + SeqSep::none(), + |p| p.parse_token_tree())); + let hi = self.prev_span.hi; + return Ok(self.mk_mac_expr(lo, hi, Mac_ { path: pth, tts: tts }, attrs)); + } + if self.check(&token::OpenDelim(token::Brace)) { + // This is a struct literal, unless we're prohibited + // from parsing struct literals here. + let prohibited = self.restrictions.contains( + RESTRICTION_NO_STRUCT_LITERAL + ); + if !prohibited { + return self.parse_struct_expr(lo, pth, attrs); + } + } + + hi = pth.span.hi; + ex = ExprKind::Path(None, pth); + } else { + match self.parse_lit() { + Ok(lit) => { + hi = lit.span.hi; + ex = ExprKind::Lit(P(lit)); + } + Err(mut err) => { + self.cancel(&mut err); + let msg = format!("expected expression, found {}", + self.this_token_descr()); + return Err(self.fatal(&msg)); + } + } + } + } + } + + return Ok(self.mk_expr(lo, hi, ex, attrs)); + } + + fn parse_struct_expr(&mut self, lo: BytePos, pth: ast::Path, mut attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + self.bump(); + let mut fields = Vec::new(); + let mut base = None; + + attrs.extend(try!(self.parse_inner_attributes())); + + while self.token != token::CloseDelim(token::Brace) { + if self.eat(&token::DotDot) { + match self.parse_expr() { + Ok(e) => { + base = Some(e); + } + Err(mut e) => { + e.emit(); + self.recover_stmt(); + } + } + break; + } + + match self.parse_field() { + Ok(f) => fields.push(f), + Err(mut e) => { + e.emit(); + self.recover_stmt(); + break; + } + } + + match self.expect_one_of(&[token::Comma], + &[token::CloseDelim(token::Brace)]) { + Ok(()) => {} + Err(mut e) => { + e.emit(); + self.recover_stmt(); + break; + } + } + } + + let hi = self.span.hi; + try!(self.expect(&token::CloseDelim(token::Brace))); + return Ok(self.mk_expr(lo, hi, ExprKind::Struct(pth, fields, base), attrs)); + } + + fn parse_or_use_outer_attributes(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, ThinVec<Attribute>> { + if let Some(attrs) = already_parsed_attrs { + Ok(attrs) + } else { + self.parse_outer_attributes().map(|a| a.into()) + } + } + + /// Parse a block or unsafe block + pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode, + outer_attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + + try!(self.expect(&token::OpenDelim(token::Brace))); + + let mut attrs = outer_attrs; + attrs.extend(try!(self.parse_inner_attributes())); + + let blk = try!(self.parse_block_tail(lo, blk_mode)); + return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), attrs)); + } + + /// parse a.b or a(13) or a[4] or just a + pub fn parse_dot_or_call_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs)); + + let b = self.parse_bottom_expr(); + let (span, b) = try!(self.interpolated_or_expr_span(b)); + self.parse_dot_or_call_expr_with(b, span.lo, attrs) + } + + pub fn parse_dot_or_call_expr_with(&mut self, + e0: P<Expr>, + lo: BytePos, + mut attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + // Stitch the list of outer attributes onto the return value. + // A little bit ugly, but the best way given the current code + // structure + self.parse_dot_or_call_expr_with_(e0, lo) + .map(|expr| + expr.map(|mut expr| { + attrs.extend::<Vec<_>>(expr.attrs.into()); + expr.attrs = attrs; + match expr.node { + ExprKind::If(..) | ExprKind::IfLet(..) => { + if !expr.attrs.is_empty() { + // Just point to the first attribute in there... + let span = expr.attrs[0].span; + + self.span_err(span, + "attributes are not yet allowed on `if` \ + expressions"); + } + } + _ => {} + } + expr + }) + ) + } + + // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue + // parsing into an expression. + fn parse_dot_suffix(&mut self, + ident: Ident, + ident_span: Span, + self_value: P<Expr>, + lo: BytePos) + -> PResult<'a, P<Expr>> { + let (_, tys, bindings) = if self.eat(&token::ModSep) { + try!(self.expect_lt()); + try!(self.parse_generic_values_after_lt()) + } else { + (Vec::new(), Vec::new(), Vec::new()) + }; + + if !bindings.is_empty() { + let prev_span = self.prev_span; + self.span_err(prev_span, "type bindings are only permitted on trait paths"); + } + + Ok(match self.token { + // expr.f() method call. + token::OpenDelim(token::Paren) => { + let mut es = try!(self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| Ok(try!(p.parse_expr())) + )); + let hi = self.prev_span.hi; + + es.insert(0, self_value); + let id = spanned(ident_span.lo, ident_span.hi, ident); + let nd = self.mk_method_call(id, tys, es); + self.mk_expr(lo, hi, nd, ThinVec::new()) + } + // Field access. + _ => { + if !tys.is_empty() { + let prev_span = self.prev_span; + self.span_err(prev_span, + "field expressions may not \ + have type parameters"); + } + + let id = spanned(ident_span.lo, ident_span.hi, ident); + let field = self.mk_field(self_value, id); + self.mk_expr(lo, ident_span.hi, field, ThinVec::new()) + } + }) + } + + fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> { + let mut e = e0; + let mut hi; + loop { + // expr? + while self.eat(&token::Question) { + let hi = self.prev_span.hi; + e = self.mk_expr(lo, hi, ExprKind::Try(e), ThinVec::new()); + } + + // expr.f + if self.eat(&token::Dot) { + match self.token { + token::Ident(i) => { + let dot_pos = self.prev_span.hi; + hi = self.span.hi; + self.bump(); + + e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo)); + } + token::Literal(token::Integer(n), suf) => { + let sp = self.span; + + // A tuple index may not have a suffix + self.expect_no_suffix(sp, "tuple index", suf); + + let dot = self.prev_span.hi; + hi = self.span.hi; + self.bump(); + + let index = n.as_str().parse::<usize>().ok(); + match index { + Some(n) => { + let id = spanned(dot, hi, n); + let field = self.mk_tup_field(e, id); + e = self.mk_expr(lo, hi, field, ThinVec::new()); + } + None => { + let prev_span = self.prev_span; + self.span_err(prev_span, "invalid tuple or tuple struct index"); + } + } + } + token::Literal(token::Float(n), _suf) => { + self.bump(); + let prev_span = self.prev_span; + let fstr = n.as_str(); + let mut err = self.diagnostic().struct_span_err(prev_span, + &format!("unexpected token: `{}`", n)); + if fstr.chars().all(|x| "0123456789.".contains(x)) { + let float = match fstr.parse::<f64>().ok() { + Some(f) => f, + None => continue, + }; + err.help(&format!("try parenthesizing the first index; e.g., `(foo.{}){}`", + float.trunc() as usize, + format!(".{}", fstr.splitn(2, ".").last().unwrap()))); + } + return Err(err); + + } + _ => { + // FIXME Could factor this out into non_fatal_unexpected or something. + let actual = self.this_token_to_string(); + self.span_err(self.span, &format!("unexpected token: `{}`", actual)); + + let dot_pos = self.prev_span.hi; + e = try!(self.parse_dot_suffix(keywords::Invalid.ident(), + mk_sp(dot_pos, dot_pos), + e, lo)); + } + } + continue; + } + if self.expr_is_complete(&e) { break; } + match self.token { + // expr(...) + token::OpenDelim(token::Paren) => { + let es = try!(self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| Ok(try!(p.parse_expr())) + )); + hi = self.prev_span.hi; + + let nd = self.mk_call(e, es); + e = self.mk_expr(lo, hi, nd, ThinVec::new()); + } + + // expr[...] + // Could be either an index expression or a slicing expression. + token::OpenDelim(token::Bracket) => { + self.bump(); + let ix = try!(self.parse_expr()); + hi = self.span.hi; + try!(self.expect(&token::CloseDelim(token::Bracket))); + let index = self.mk_index(e, ix); + e = self.mk_expr(lo, hi, index, ThinVec::new()) + } + _ => return Ok(e) + } + } + return Ok(e); + } + + // Parse unquoted tokens after a `$` in a token tree + fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> { + let mut sp = self.span; + let name = match self.token { + token::Dollar => { + self.bump(); + + if self.token == token::OpenDelim(token::Paren) { + let Spanned { node: seq, span: seq_span } = try!(self.parse_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::none(), + |p| p.parse_token_tree() + )); + let (sep, repeat) = try!(self.parse_sep_and_kleene_op()); + let name_num = macro_parser::count_names(&seq); + return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi), + Rc::new(SequenceRepetition { + tts: seq, + separator: sep, + op: repeat, + num_captures: name_num + }))); + } else if self.token.is_keyword(keywords::Crate) { + let ident = match self.token { + token::Ident(id) => ast::Ident { name: Symbol::intern("$crate"), ..id }, + _ => unreachable!(), + }; + self.bump(); + return Ok(TokenTree::Token(sp, token::Ident(ident))); + } else { + sp = mk_sp(sp.lo, self.span.hi); + self.parse_ident().unwrap_or_else(|mut e| { + e.emit(); + keywords::Invalid.ident() + }) + } + } + token::SubstNt(name) => { + self.bump(); + name + } + _ => unreachable!() + }; + // continue by trying to parse the `:ident` after `$name` + if self.token == token::Colon && + self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword()) { + self.bump(); + sp = mk_sp(sp.lo, self.span.hi); + let nt_kind = try!(self.parse_ident()); + Ok(TokenTree::Token(sp, MatchNt(name, nt_kind))) + } else { + Ok(TokenTree::Token(sp, SubstNt(name))) + } + } + + pub fn check_unknown_macro_variable(&mut self) { + if self.quote_depth == 0 && !self.parsing_token_tree { + match self.token { + token::SubstNt(name) => + self.fatal(&format!("unknown macro variable `{}`", name)).emit(), + _ => {} + } + } + } + + /// Parse an optional separator followed by a Kleene-style + /// repetition token (+ or *). + pub fn parse_sep_and_kleene_op(&mut self) + -> PResult<'a, (Option<token::Token>, tokenstream::KleeneOp)> { + fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> + PResult<'a, Option<tokenstream::KleeneOp>> { + match parser.token { + token::BinOp(token::Star) => { + parser.bump(); + Ok(Some(tokenstream::KleeneOp::ZeroOrMore)) + }, + token::BinOp(token::Plus) => { + parser.bump(); + Ok(Some(tokenstream::KleeneOp::OneOrMore)) + }, + _ => Ok(None) + } + }; + + if let Some(kleene_op) = try!(parse_kleene_op(self)) { + return Ok((None, kleene_op)); + } + + let separator = self.bump_and_get(); + match try!(parse_kleene_op(self)) { + Some(zerok) => Ok((Some(separator), zerok)), + None => return Err(self.fatal("expected `*` or `+`")) + } + } + + /// parse a single token tree from the input. + pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> { + // FIXME #6994: currently, this is too eager. It + // parses token trees but also identifies TokenType::Sequence's + // and token::SubstNt's; it's too early to know yet + // whether something will be a nonterminal or a seq + // yet. + match self.token { + token::Eof => { + let mut err: DiagnosticBuilder<'a> = + self.diagnostic().struct_span_err(self.span, + "this file contains an un-closed delimiter"); + for &(_, sp) in &self.open_braces { + err.span_help(sp, "did you mean to close this delimiter?"); + } + + Err(err) + }, + token::OpenDelim(delim) => { + if self.tts.last().map(|&(_, i)| i == 1).unwrap_or(false) { + let tt = self.tts.pop().unwrap().0; + self.bump(); + return Ok(if self.allow_interpolated_tts { + // avoid needlessly reparsing token trees in recursive macro expansions + TokenTree::Token(tt.span(), token::Interpolated(Rc::new(token::NtTT(tt)))) + } else { + tt + }); + } + + let parsing_token_tree = ::std::mem::replace(&mut self.parsing_token_tree, true); + // The span for beginning of the delimited section + let pre_span = self.span; + + // Parse the open delimiter. + self.open_braces.push((delim, self.span)); + let open_span = self.span; + self.bump(); + + // Parse the token trees within the delimiters. + // We stop at any delimiter so we can try to recover if the user + // uses an incorrect delimiter. + let tts = self.parse_seq_to_before_tokens(&[&token::CloseDelim(token::Brace), + &token::CloseDelim(token::Paren), + &token::CloseDelim(token::Bracket)], + SeqSep::none(), + |p| p.parse_token_tree(), + |mut e| e.emit()); + + let close_span = self.span; + // Expand to cover the entire delimited token tree + let span = Span { hi: close_span.hi, ..pre_span }; + + match self.token { + // Correct delimiter. + token::CloseDelim(d) if d == delim => { + self.open_braces.pop().unwrap(); + + // Parse the close delimiter. + self.bump(); + } + // Incorrect delimiter. + token::CloseDelim(other) => { + let token_str = self.this_token_to_string(); + let mut err = self.diagnostic().struct_span_err(self.span, + &format!("incorrect close delimiter: `{}`", token_str)); + // This is a conservative error: only report the last unclosed delimiter. + // The previous unclosed delimiters could actually be closed! The parser + // just hasn't gotten to them yet. + if let Some(&(_, sp)) = self.open_braces.last() { + err.span_note(sp, "unclosed delimiter"); + }; + err.emit(); + + self.open_braces.pop().unwrap(); + + // If the incorrect delimiter matches an earlier opening + // delimiter, then don't consume it (it can be used to + // close the earlier one). Otherwise, consume it. + // E.g., we try to recover from: + // fn foo() { + // bar(baz( + // } // Incorrect delimiter but matches the earlier `{` + if !self.open_braces.iter().any(|&(b, _)| b == other) { + self.bump(); + } + } + token::Eof => { + // Silently recover, the EOF token will be seen again + // and an error emitted then. Thus we don't pop from + // self.open_braces here. + }, + _ => {} + } + + self.parsing_token_tree = parsing_token_tree; + Ok(TokenTree::Delimited(span, Rc::new(Delimited { + delim: delim, + open_span: open_span, + tts: tts, + close_span: close_span, + }))) + }, + token::CloseDelim(_) => { + // An unexpected closing delimiter (i.e., there is no + // matching opening delimiter). + let token_str = self.this_token_to_string(); + let err = self.diagnostic().struct_span_err(self.span, + &format!("unexpected close delimiter: `{}`", token_str)); + Err(err) + }, + /* we ought to allow different depths of unquotation */ + token::Dollar | token::SubstNt(..) if self.quote_depth > 0 => { + self.parse_unquoted() + } + _ => { + Ok(TokenTree::Token(self.span, self.bump_and_get())) + } + } + } + + // parse a stream of tokens into a list of TokenTree's, + // up to EOF. + pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> { + let mut tts = Vec::new(); + while self.token != token::Eof { + tts.push(try!(self.parse_token_tree())); + } + Ok(tts) + } + + /// Parse a prefix-unary-operator expr + pub fn parse_prefix_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs)); + let lo = self.span.lo; + let hi; + // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr() + let ex = match self.token { + token::Not => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = try!(self.interpolated_or_expr_span(e)); + hi = span.hi; + self.mk_unary(UnOp::Not, e) + } + token::BinOp(token::Minus) => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = try!(self.interpolated_or_expr_span(e)); + hi = span.hi; + self.mk_unary(UnOp::Neg, e) + } + token::BinOp(token::Star) => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = try!(self.interpolated_or_expr_span(e)); + hi = span.hi; + self.mk_unary(UnOp::Deref, e) + } + token::BinOp(token::And) | token::AndAnd => { + try!(self.expect_and()); + let m = try!(self.parse_mutability()); + let e = self.parse_prefix_expr(None); + let (span, e) = try!(self.interpolated_or_expr_span(e)); + hi = span.hi; + ExprKind::AddrOf(m, e) + } + token::Ident(..) if self.token.is_keyword(keywords::In) => { + self.bump(); + let place = try!(self.parse_expr_res( + RESTRICTION_NO_STRUCT_LITERAL, + None, + )); + let blk = try!(self.parse_block()); + let span = blk.span; + hi = span.hi; + let blk_expr = self.mk_expr(span.lo, hi, ExprKind::Block(blk), ThinVec::new()); + ExprKind::InPlace(place, blk_expr) + } + token::Ident(..) if self.token.is_keyword(keywords::Box) => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = try!(self.interpolated_or_expr_span(e)); + hi = span.hi; + ExprKind::Box(e) + } + _ => return self.parse_dot_or_call_expr(Some(attrs)) + }; + return Ok(self.mk_expr(lo, hi, ex, attrs)); + } + + /// Parse an associative expression + /// + /// This parses an expression accounting for associativity and precedence of the operators in + /// the expression. + pub fn parse_assoc_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + self.parse_assoc_expr_with(0, already_parsed_attrs.into()) + } + + /// Parse an associative expression with operators of at least `min_prec` precedence + pub fn parse_assoc_expr_with(&mut self, + min_prec: usize, + lhs: LhsExpr) + -> PResult<'a, P<Expr>> { + let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { + expr + } else { + let attrs = match lhs { + LhsExpr::AttributesParsed(attrs) => Some(attrs), + _ => None, + }; + if self.token == token::DotDot || self.token == token::DotDotDot { + return self.parse_prefix_range_expr(attrs); + } else { + try!(self.parse_prefix_expr(attrs)) + } + }; + + if self.expr_is_complete(&lhs) { + // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071 + return Ok(lhs); + } + self.expected_tokens.push(TokenType::Operator); + while let Some(op) = AssocOp::from_token(&self.token) { + + let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated { + self.prev_span + } else { + lhs.span + }; + + let cur_op_span = self.span; + let restrictions = if op.is_assign_like() { + self.restrictions & RESTRICTION_NO_STRUCT_LITERAL + } else { + self.restrictions + }; + if op.precedence() < min_prec { + break; + } + self.bump(); + if op.is_comparison() { + self.check_no_chained_comparison(&lhs, &op); + } + // Special cases: + if op == AssocOp::As { + let rhs = try!(self.parse_ty()); + let (lo, hi) = (lhs_span.lo, rhs.span.hi); + lhs = self.mk_expr(lo, hi, ExprKind::Cast(lhs, rhs), ThinVec::new()); + continue + } else if op == AssocOp::Colon { + let rhs = try!(self.parse_ty()); + let (lo, hi) = (lhs_span.lo, rhs.span.hi); + lhs = self.mk_expr(lo, hi, ExprKind::Type(lhs, rhs), ThinVec::new()); + continue + } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot { + // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to + // generalise it to the Fixity::None code. + // + // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other + // two variants are handled with `parse_prefix_range_expr` call above. + let rhs = if self.is_at_start_of_range_notation_rhs() { + Some(try!(self.parse_assoc_expr_with(op.precedence() + 1, + LhsExpr::NotYetParsed))) + } else { + None + }; + let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs { + x.span + } else { + cur_op_span + }); + let limits = if op == AssocOp::DotDot { + RangeLimits::HalfOpen + } else { + RangeLimits::Closed + }; + + let r = try!(self.mk_range(Some(lhs), rhs, limits)); + lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, ThinVec::new()); + break + } + + let rhs = try!(match op.fixity() { + Fixity::Right => self.with_res( + restrictions - RESTRICTION_STMT_EXPR, + |this| { + this.parse_assoc_expr_with(op.precedence(), + LhsExpr::NotYetParsed) + }), + Fixity::Left => self.with_res( + restrictions - RESTRICTION_STMT_EXPR, + |this| { + this.parse_assoc_expr_with(op.precedence() + 1, + LhsExpr::NotYetParsed) + }), + // We currently have no non-associative operators that are not handled above by + // the special cases. The code is here only for future convenience. + Fixity::None => self.with_res( + restrictions - RESTRICTION_STMT_EXPR, + |this| { + this.parse_assoc_expr_with(op.precedence() + 1, + LhsExpr::NotYetParsed) + }), + }); + + let (lo, hi) = (lhs_span.lo, rhs.span.hi); + lhs = match op { + AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | + AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor | + AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight | + AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual | + AssocOp::Greater | AssocOp::GreaterEqual => { + let ast_op = op.to_ast_binop().unwrap(); + let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs); + self.mk_expr(lo, hi, binary, ThinVec::new()) + } + AssocOp::Assign => + self.mk_expr(lo, hi, ExprKind::Assign(lhs, rhs), ThinVec::new()), + AssocOp::Inplace => + self.mk_expr(lo, hi, ExprKind::InPlace(lhs, rhs), ThinVec::new()), + AssocOp::AssignOp(k) => { + let aop = match k { + token::Plus => BinOpKind::Add, + token::Minus => BinOpKind::Sub, + token::Star => BinOpKind::Mul, + token::Slash => BinOpKind::Div, + token::Percent => BinOpKind::Rem, + token::Caret => BinOpKind::BitXor, + token::And => BinOpKind::BitAnd, + token::Or => BinOpKind::BitOr, + token::Shl => BinOpKind::Shl, + token::Shr => BinOpKind::Shr, + }; + let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs); + self.mk_expr(lo, hi, aopexpr, ThinVec::new()) + } + AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => { + self.bug("As, Colon, DotDot or DotDotDot branch reached") + } + }; + + if op.fixity() == Fixity::None { break } + } + Ok(lhs) + } + + /// Produce an error if comparison operators are chained (RFC #558). + /// We only need to check lhs, not rhs, because all comparison ops + /// have same precedence and are left-associative + fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) { + debug_assert!(outer_op.is_comparison()); + match lhs.node { + ExprKind::Binary(op, _, _) if op.node.is_comparison() => { + // respan to include both operators + let op_span = mk_sp(op.span.lo, self.span.hi); + let mut err = self.diagnostic().struct_span_err(op_span, + "chained comparison operators require parentheses"); + if op.node == BinOpKind::Lt && *outer_op == AssocOp::Greater { + err.help( + "use `::<...>` instead of `<...>` if you meant to specify type arguments"); + } + err.emit(); + } + _ => {} + } + } + + /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr` + fn parse_prefix_range_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot); + let tok = self.token.clone(); + let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs)); + let lo = self.span.lo; + let mut hi = self.span.hi; + self.bump(); + let opt_end = if self.is_at_start_of_range_notation_rhs() { + // RHS must be parsed with more associativity than the dots. + let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1; + Some(try!(self.parse_assoc_expr_with(next_prec, + LhsExpr::NotYetParsed) + .map(|x|{ + hi = x.span.hi; + x + }))) + } else { + None + }; + let limits = if tok == token::DotDot { + RangeLimits::HalfOpen + } else { + RangeLimits::Closed + }; + + let r = try!(self.mk_range(None, + opt_end, + limits)); + Ok(self.mk_expr(lo, hi, r, attrs)) + } + + fn is_at_start_of_range_notation_rhs(&self) -> bool { + if self.token.can_begin_expr() { + // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`. + if self.token == token::OpenDelim(token::Brace) { + return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL); + } + true + } else { + false + } + } + + /// Parse an 'if' or 'if let' expression ('if' token already eaten) + pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + if self.check_keyword(keywords::Let) { + return self.parse_if_let_expr(attrs); + } + let lo = self.prev_span.lo; + let cond = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)); + let thn = try!(self.parse_block()); + let mut els: Option<P<Expr>> = None; + let mut hi = thn.span.hi; + if self.eat_keyword(keywords::Else) { + let elexpr = try!(self.parse_else_expr()); + hi = elexpr.span.hi; + els = Some(elexpr); + } + Ok(self.mk_expr(lo, hi, ExprKind::If(cond, thn, els), attrs)) + } + + /// Parse an 'if let' expression ('if' token already eaten) + pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + let lo = self.prev_span.lo; + try!(self.expect_keyword(keywords::Let)); + let pat = try!(self.parse_pat()); + try!(self.expect(&token::Eq)); + let expr = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)); + let thn = try!(self.parse_block()); + let (hi, els) = if self.eat_keyword(keywords::Else) { + let expr = try!(self.parse_else_expr()); + (expr.span.hi, Some(expr)) + } else { + (thn.span.hi, None) + }; + Ok(self.mk_expr(lo, hi, ExprKind::IfLet(pat, expr, thn, els), attrs)) + } + + // `move |args| expr` + pub fn parse_lambda_expr(&mut self, + lo: BytePos, + capture_clause: CaptureBy, + attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> + { + let decl = try!(self.parse_fn_block_decl()); + let decl_hi = self.prev_span.hi; + let body = match decl.output { + FunctionRetTy::Default(_) => try!(self.parse_expr()), + _ => { + // If an explicit return type is given, require a + // block to appear (RFC 968). + let body_lo = self.span.lo; + try!(self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())) + } + }; + + Ok(self.mk_expr( + lo, + body.span.hi, + ExprKind::Closure(capture_clause, decl, body, mk_sp(lo, decl_hi)), + attrs)) + } + + // `else` token already eaten + pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> { + if self.eat_keyword(keywords::If) { + return self.parse_if_expr(ThinVec::new()); + } else { + let blk = try!(self.parse_block()); + return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), ThinVec::new())); + } + } + + /// Parse a 'for' .. 'in' expression ('for' token already eaten) + pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>, + span_lo: BytePos, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + // Parse: `for <src_pat> in <src_expr> <src_loop_block>` + + let pat = try!(self.parse_pat()); + try!(self.expect_keyword(keywords::In)); + let expr = try!(self.parse_expr_res(Restrictions::restriction_no_struct_literal(), None)); + let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block()); + attrs.extend(iattrs); + + let hi = self.prev_span.hi; + + Ok(self.mk_expr(span_lo, hi, + ExprKind::ForLoop(pat, expr, loop_block, opt_ident), + attrs)) + } + + /// Parse a 'while' or 'while let' expression ('while' token already eaten) + pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>, + span_lo: BytePos, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + if self.token.is_keyword(keywords::Let) { + return self.parse_while_let_expr(opt_ident, span_lo, attrs); + } + let cond = try!(self.parse_expr_res(Restrictions::restriction_no_struct_literal(), None)); + let (iattrs, body) = try!(self.parse_inner_attrs_and_block()); + attrs.extend(iattrs); + let hi = body.span.hi; + return Ok(self.mk_expr(span_lo, hi, ExprKind::While(cond, body, opt_ident), + attrs)); + } + + /// Parse a 'while let' expression ('while' token already eaten) + pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>, + span_lo: BytePos, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + try!(self.expect_keyword(keywords::Let)); + let pat = try!(self.parse_pat()); + try!(self.expect(&token::Eq)); + let expr = try!(self.parse_expr_res(Restrictions::restriction_no_struct_literal(), None)); + let (iattrs, body) = try!(self.parse_inner_attrs_and_block()); + attrs.extend(iattrs); + let hi = body.span.hi; + return Ok(self.mk_expr(span_lo, hi, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs)); + } + + // parse `loop {...}`, `loop` token already eaten + pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>, + span_lo: BytePos, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + let (iattrs, body) = try!(self.parse_inner_attrs_and_block()); + attrs.extend(iattrs); + let hi = body.span.hi; + Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs)) + } + + // `match` token already eaten + fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + let match_span = self.prev_span; + let lo = self.prev_span.lo; + let discriminant = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, + None)); + if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) { + if self.token == token::Token::Semi { + e.span_note(match_span, "did you mean to remove this `match` keyword?"); + } + return Err(e) + } + attrs.extend(try!(self.parse_inner_attributes())); + + let mut arms: Vec<Arm> = Vec::new(); + while self.token != token::CloseDelim(token::Brace) { + match self.parse_arm() { + Ok(arm) => arms.push(arm), + Err(mut e) => { + // Recover by skipping to the end of the block. + e.emit(); + self.recover_stmt(); + let hi = self.span.hi; + if self.token == token::CloseDelim(token::Brace) { + self.bump(); + } + return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs)); + } + } + } + let hi = self.span.hi; + self.bump(); + return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs)); + } + + pub fn parse_arm(&mut self) -> PResult<'a, Arm> { + maybe_whole!(self, NtArm, |x| x); + + let attrs = try!(self.parse_outer_attributes()); + let pats = try!(self.parse_pats()); + let mut guard = None; + if self.eat_keyword(keywords::If) { + guard = Some(try!(self.parse_expr())); + } + try!(self.expect(&token::FatArrow)); + let expr = try!(self.parse_expr_res(RESTRICTION_STMT_EXPR, None)); + + let require_comma = + !classify::expr_is_simple_block(&expr) + && self.token != token::CloseDelim(token::Brace); + + if require_comma { + try!(self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])); + } else { + self.eat(&token::Comma); + } + + Ok(ast::Arm { + attrs: attrs, + pats: pats, + guard: guard, + body: expr, + }) + } + + /// Parse an expression + pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> { + self.parse_expr_res(Restrictions::empty(), None) + } + + /// Evaluate the closure with restrictions in place. + /// + /// After the closure is evaluated, restrictions are reset. + pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T + where F: FnOnce(&mut Self) -> T + { + let old = self.restrictions; + self.restrictions = r; + let r = f(self); + self.restrictions = old; + return r; + + } + + /// Parse an expression, subject to the given restrictions + pub fn parse_expr_res(&mut self, r: Restrictions, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs)) + } + + /// Parse the RHS of a local variable declaration (e.g. '= 14;') + fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> { + if self.check(&token::Eq) { + self.bump(); + Ok(Some(try!(self.parse_expr()))) + } else { + Ok(None) + } + } + + /// Parse patterns, separated by '|' s + fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> { + let mut pats = Vec::new(); + loop { + pats.push(try!(self.parse_pat())); + if self.check(&token::BinOp(token::Or)) { self.bump();} + else { return Ok(pats); } + }; + } + + fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool) + -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> { + let mut fields = vec![]; + let mut ddpos = None; + + while !self.check(&token::CloseDelim(token::Paren)) { + if ddpos.is_none() && self.eat(&token::DotDot) { + ddpos = Some(fields.len()); + if self.eat(&token::Comma) { + // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed. + fields.push(try!(self.parse_pat())); + } + } else if ddpos.is_some() && self.eat(&token::DotDot) { + // Emit a friendly error, ignore `..` and continue parsing + self.span_err(self.prev_span, "`..` can only be used once per \ + tuple or tuple struct pattern"); + } else { + fields.push(try!(self.parse_pat())); + } + + if !self.check(&token::CloseDelim(token::Paren)) || + (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) { + try!(self.expect(&token::Comma)); + } + } + + Ok((fields, ddpos)) + } + + fn parse_pat_vec_elements( + &mut self, + ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> { + let mut before = Vec::new(); + let mut slice = None; + let mut after = Vec::new(); + let mut first = true; + let mut before_slice = true; + + while self.token != token::CloseDelim(token::Bracket) { + if first { + first = false; + } else { + try!(self.expect(&token::Comma)); + + if self.token == token::CloseDelim(token::Bracket) + && (before_slice || !after.is_empty()) { + break + } + } + + if before_slice { + if self.check(&token::DotDot) { + self.bump(); + + if self.check(&token::Comma) || + self.check(&token::CloseDelim(token::Bracket)) { + slice = Some(P(ast::Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Wild, + span: self.span, + })); + before_slice = false; + } + continue + } + } + + let subpat = try!(self.parse_pat()); + if before_slice && self.check(&token::DotDot) { + self.bump(); + slice = Some(subpat); + before_slice = false; + } else if before_slice { + before.push(subpat); + } else { + after.push(subpat); + } + } + + Ok((before, slice, after)) + } + + /// Parse the fields of a struct-like pattern + fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> { + let mut fields = Vec::new(); + let mut etc = false; + let mut first = true; + while self.token != token::CloseDelim(token::Brace) { + if first { + first = false; + } else { + try!(self.expect(&token::Comma)); + // accept trailing commas + if self.check(&token::CloseDelim(token::Brace)) { break } + } + + let lo = self.span.lo; + let hi; + + if self.check(&token::DotDot) { + self.bump(); + if self.token != token::CloseDelim(token::Brace) { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected `{}`, found `{}`", "}", + token_str))) + } + etc = true; + break; + } + + // Check if a colon exists one ahead. This means we're parsing a fieldname. + let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) { + // Parsing a pattern of the form "fieldname: pat" + let fieldname = try!(self.parse_field_name()); + self.bump(); + let pat = try!(self.parse_pat()); + hi = pat.span.hi; + (pat, fieldname, false) + } else { + // Parsing a pattern of the form "(box) (ref) (mut) fieldname" + let is_box = self.eat_keyword(keywords::Box); + let boxed_span_lo = self.span.lo; + let is_ref = self.eat_keyword(keywords::Ref); + let is_mut = self.eat_keyword(keywords::Mut); + let fieldname = try!(self.parse_ident()); + hi = self.prev_span.hi; + + let bind_type = match (is_ref, is_mut) { + (true, true) => BindingMode::ByRef(Mutability::Mutable), + (true, false) => BindingMode::ByRef(Mutability::Immutable), + (false, true) => BindingMode::ByValue(Mutability::Mutable), + (false, false) => BindingMode::ByValue(Mutability::Immutable), + }; + let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname}; + let fieldpat = P(ast::Pat{ + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident(bind_type, fieldpath, None), + span: mk_sp(boxed_span_lo, hi), + }); + + let subpat = if is_box { + P(ast::Pat{ + id: ast::DUMMY_NODE_ID, + node: PatKind::Box(fieldpat), + span: mk_sp(lo, hi), + }) + } else { + fieldpat + }; + (subpat, fieldname, true) + }; + + fields.push(codemap::Spanned { span: mk_sp(lo, hi), + node: ast::FieldPat { ident: fieldname, + pat: subpat, + is_shorthand: is_shorthand }}); + } + return Ok((fields, etc)); + } + + fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> { + if self.token.is_path_start() { + let lo = self.span.lo; + let (qself, path) = if self.eat_lt() { + // Parse a qualified path + let (qself, path) = + try!(self.parse_qualified_path(PathStyle::Expr)); + (Some(qself), path) + } else { + // Parse an unqualified path + (None, try!(self.parse_path(PathStyle::Expr))) + }; + let hi = self.prev_span.hi; + Ok(self.mk_expr(lo, hi, ExprKind::Path(qself, path), ThinVec::new())) + } else { + self.parse_pat_literal_maybe_minus() + } + } + + /// Parse a pattern. + pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> { + maybe_whole!(self, NtPat, |x| x); + + let lo = self.span.lo; + let pat; + match self.token { + token::Underscore => { + // Parse _ + self.bump(); + pat = PatKind::Wild; + } + token::BinOp(token::And) | token::AndAnd => { + // Parse &pat / &mut pat + try!(self.expect_and()); + let mutbl = try!(self.parse_mutability()); + if let token::Lifetime(ident) = self.token { + return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident))); + } + let subpat = try!(self.parse_pat()); + pat = PatKind::Ref(subpat, mutbl); + } + token::OpenDelim(token::Paren) => { + // Parse (pat,pat,pat,...) as tuple pattern + self.bump(); + let (fields, ddpos) = try!(self.parse_pat_tuple_elements(true)); + try!(self.expect(&token::CloseDelim(token::Paren))); + pat = PatKind::Tuple(fields, ddpos); + } + token::OpenDelim(token::Bracket) => { + // Parse [pat,pat,...] as slice pattern + self.bump(); + let (before, slice, after) = try!(self.parse_pat_vec_elements()); + try!(self.expect(&token::CloseDelim(token::Bracket))); + pat = PatKind::Slice(before, slice, after); + } + // At this point, token != _, &, &&, (, [ + _ => if self.eat_keyword(keywords::Mut) { + // Parse mut ident @ pat + pat = try!(self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))); + } else if self.eat_keyword(keywords::Ref) { + // Parse ref ident @ pat / ref mut ident @ pat + let mutbl = try!(self.parse_mutability()); + pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl))); + } else if self.eat_keyword(keywords::Box) { + // Parse box pat + let subpat = try!(self.parse_pat()); + pat = PatKind::Box(subpat); + } else if self.token.is_ident() && !self.token.is_any_keyword() && + self.look_ahead(1, |t| match *t { + token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) | + token::DotDotDot | token::ModSep | token::Not => false, + _ => true, + }) { + // Parse ident @ pat + // This can give false positives and parse nullary enums, + // they are dealt with later in resolve + let binding_mode = BindingMode::ByValue(Mutability::Immutable); + pat = try!(self.parse_pat_ident(binding_mode)); + } else if self.token.is_path_start() { + // Parse pattern starting with a path + let (qself, path) = if self.eat_lt() { + // Parse a qualified path + let (qself, path) = try!(self.parse_qualified_path(PathStyle::Expr)); + (Some(qself), path) + } else { + // Parse an unqualified path + (None, try!(self.parse_path(PathStyle::Expr))) + }; + match self.token { + token::Not if qself.is_none() => { + // Parse macro invocation + self.bump(); + let delim = try!(self.expect_open_delim()); + let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim), + SeqSep::none(), + |p| p.parse_token_tree())); + let mac = spanned(lo, self.prev_span.hi, Mac_ { path: path, tts: tts }); + pat = PatKind::Mac(mac); + } + token::DotDotDot => { + // Parse range + let hi = self.prev_span.hi; + let begin = + self.mk_expr(lo, hi, ExprKind::Path(qself, path), ThinVec::new()); + self.bump(); + let end = try!(self.parse_pat_range_end()); + pat = PatKind::Range(begin, end); + } + token::OpenDelim(token::Brace) => { + if qself.is_some() { + return Err(self.fatal("unexpected `{` after qualified path")); + } + // Parse struct pattern + self.bump(); + let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| { + e.emit(); + self.recover_stmt(); + (vec![], false) + }); + self.bump(); + pat = PatKind::Struct(path, fields, etc); + } + token::OpenDelim(token::Paren) => { + if qself.is_some() { + return Err(self.fatal("unexpected `(` after qualified path")); + } + // Parse tuple struct or enum pattern + self.bump(); + let (fields, ddpos) = try!(self.parse_pat_tuple_elements(false)); + try!(self.expect(&token::CloseDelim(token::Paren))); + pat = PatKind::TupleStruct(path, fields, ddpos) + } + _ => pat = PatKind::Path(qself, path), + } + } else { + // Try to parse everything else as literal with optional minus + match self.parse_pat_literal_maybe_minus() { + Ok(begin) => { + if self.eat(&token::DotDotDot) { + let end = try!(self.parse_pat_range_end()); + pat = PatKind::Range(begin, end); + } else { + pat = PatKind::Lit(begin); + } + } + Err(mut err) => { + self.cancel(&mut err); + let msg = format!("expected pattern, found {}", self.this_token_descr()); + return Err(self.fatal(&msg)); + } + } + } + } + + let hi = self.prev_span.hi; + Ok(P(ast::Pat { + id: ast::DUMMY_NODE_ID, + node: pat, + span: mk_sp(lo, hi), + })) + } + + /// Parse ident or ident @ pat + /// used by the copy foo and ref foo patterns to give a good + /// error message when parsing mistakes like ref foo(a,b) + fn parse_pat_ident(&mut self, + binding_mode: ast::BindingMode) + -> PResult<'a, PatKind> { + let ident = try!(self.parse_ident()); + let prev_span = self.prev_span; + let name = codemap::Spanned{span: prev_span, node: ident}; + let sub = if self.eat(&token::At) { + Some(try!(self.parse_pat())) + } else { + None + }; + + // just to be friendly, if they write something like + // ref Some(i) + // we end up here with ( as the current token. This shortly + // leads to a parse error. Note that if there is no explicit + // binding mode then we do not end up here, because the lookahead + // will direct us over to parse_enum_variant() + if self.token == token::OpenDelim(token::Paren) { + return Err(self.span_fatal( + self.prev_span, + "expected identifier, found enum pattern")) + } + + Ok(PatKind::Ident(binding_mode, name, sub)) + } + + /// Parse a local variable declaration + fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> { + let lo = self.span.lo; + let pat = try!(self.parse_pat()); + + let mut ty = None; + if self.eat(&token::Colon) { + ty = Some(try!(self.parse_ty_sum())); + } + let init = try!(self.parse_initializer()); + Ok(P(ast::Local { + ty: ty, + pat: pat, + init: init, + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, self.prev_span.hi), + attrs: attrs, + })) + } + + /// Parse a structure field + fn parse_name_and_ty(&mut self, + lo: BytePos, + vis: Visibility, + attrs: Vec<Attribute>) + -> PResult<'a, StructField> { + let name = try!(self.parse_ident()); + try!(self.expect(&token::Colon)); + let ty = try!(self.parse_ty_sum()); + Ok(StructField { + span: mk_sp(lo, self.prev_span.hi), + ident: Some(name), + vis: vis, + id: ast::DUMMY_NODE_ID, + ty: ty, + attrs: attrs, + }) + } + + /// Emit an expected item after attributes error. + fn expected_item_err(&self, attrs: &[Attribute]) { + let message = match attrs.last() { + Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment", + _ => "expected item after attributes", + }; + + self.span_err(self.prev_span, message); + } + + /// Parse a statement. This stops just before trailing semicolons on everything but items. + /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. + pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> { + Ok(self.parse_stmt_(true)) + } + + // Eat tokens until we can be relatively sure we reached the end of the + // statement. This is something of a best-effort heuristic. + // + // We terminate when we find an unmatched `}` (without consuming it). + fn recover_stmt(&mut self) { + self.recover_stmt_(SemiColonMode::Ignore) + } + // If `break_on_semi` is `Break`, then we will stop consuming tokens after + // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is + // approximate - it can mean we break too early due to macros, but that + // shoud only lead to sub-optimal recovery, not inaccurate parsing). + fn recover_stmt_(&mut self, break_on_semi: SemiColonMode) { + let mut brace_depth = 0; + let mut bracket_depth = 0; + debug!("recover_stmt_ enter loop"); + loop { + debug!("recover_stmt_ loop {:?}", self.token); + match self.token { + token::OpenDelim(token::DelimToken::Brace) => { + brace_depth += 1; + self.bump(); + } + token::OpenDelim(token::DelimToken::Bracket) => { + bracket_depth += 1; + self.bump(); + } + token::CloseDelim(token::DelimToken::Brace) => { + if brace_depth == 0 { + debug!("recover_stmt_ return - close delim {:?}", self.token); + return; + } + brace_depth -= 1; + self.bump(); + } + token::CloseDelim(token::DelimToken::Bracket) => { + bracket_depth -= 1; + if bracket_depth < 0 { + bracket_depth = 0; + } + self.bump(); + } + token::Eof => { + debug!("recover_stmt_ return - Eof"); + return; + } + token::Semi => { + self.bump(); + if break_on_semi == SemiColonMode::Break && + brace_depth == 0 && + bracket_depth == 0 { + debug!("recover_stmt_ return - Semi"); + return; + } + } + _ => { + self.bump() + } + } + } + } + + fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> { + self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| { + e.emit(); + self.recover_stmt_(SemiColonMode::Break); + None + }) + } + + fn is_union_item(&mut self) -> bool { + self.token.is_keyword(keywords::Union) && + self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword()) + } + + fn parse_stmt_without_recovery(&mut self, + macro_legacy_warnings: bool) + -> PResult<'a, Option<Stmt>> { + maybe_whole!(self, NtStmt, |x| Some(x)); + + let attrs = try!(self.parse_outer_attributes()); + let lo = self.span.lo; + + Ok(Some(if self.eat_keyword(keywords::Let) { + Stmt { + id: ast::DUMMY_NODE_ID, + node: StmtKind::Local(try!(self.parse_local(attrs.into()))), + span: mk_sp(lo, self.prev_span.hi), + } + // Starts like a simple path, but not a union item. + } else if self.token.is_path_start() && + !self.token.is_qpath_start() && + !self.is_union_item() { + let pth = try!(self.parse_path(PathStyle::Expr)); + + if !self.eat(&token::Not) { + let expr = if self.check(&token::OpenDelim(token::Brace)) { + try!(self.parse_struct_expr(lo, pth, ThinVec::new())) + } else { + let hi = self.prev_span.hi; + self.mk_expr(lo, hi, ExprKind::Path(None, pth), ThinVec::new()) + }; + + let expr = try!(self.with_res(Restrictions::restriction_stmt_expr(), |this| { + let expr = try!(this.parse_dot_or_call_expr_with(expr, lo, attrs.into())); + this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) + })); + + return Ok(Some(Stmt { + id: ast::DUMMY_NODE_ID, + node: StmtKind::Expr(expr), + span: mk_sp(lo, self.prev_span.hi), + })); + } + + // it's a macro invocation + let id = match self.token { + token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier + _ => try!(self.parse_ident()), + }; + + // check that we're pointing at delimiters (need to check + // again after the `if`, because of `parse_ident` + // consuming more tokens). + let delim = match self.token { + token::OpenDelim(delim) => delim, + _ => { + // we only expect an ident if we didn't parse one + // above. + let ident_str = if id.name == keywords::Invalid.name() { + "identifier, " + } else { + "" + }; + let tok_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`", + ident_str, + tok_str))) + }, + }; + + let tts = try!(self.parse_unspanned_seq( + &token::OpenDelim(delim), + &token::CloseDelim(delim), + SeqSep::none(), + |p| p.parse_token_tree() + )); + let hi = self.prev_span.hi; + + let style = if delim == token::Brace { + MacStmtStyle::Braces + } else { + MacStmtStyle::NoBraces + }; + + if id.name == keywords::Invalid.name() { + let mac = spanned(lo, hi, Mac_ { path: pth, tts: tts }); + let node = if delim == token::Brace || + self.token == token::Semi || self.token == token::Eof { + StmtKind::Mac(P((mac, style, attrs.into()))) + } + // We used to incorrectly stop parsing macro-expanded statements here. + // If the next token will be an error anyway but could have parsed with the + // earlier behavior, stop parsing here and emit a warning to avoid breakage. + else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token { + // These can continue an expression, so we can't stop parsing and warn. + token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | + token::BinOp(token::Minus) | token::BinOp(token::Star) | + token::BinOp(token::And) | token::BinOp(token::Or) | + token::AndAnd | token::OrOr | + token::DotDot | token::DotDotDot => false, + _ => true, + } { + self.warn_missing_semicolon(); + StmtKind::Mac(P((mac, style, attrs.into()))) + } else { + let e = self.mk_mac_expr(lo, hi, mac.node, ThinVec::new()); + let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs.into())); + let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))); + StmtKind::Expr(e) + }; + Stmt { + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, hi), + node: node, + } + } else { + // if it has a special ident, it's definitely an item + // + // Require a semicolon or braces. + if style != MacStmtStyle::Braces { + if !self.eat(&token::Semi) { + self.span_err(self.prev_span, + "macros that expand to items must \ + either be surrounded with braces or \ + followed by a semicolon"); + } + } + Stmt { + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, hi), + node: StmtKind::Item({ + self.mk_item( + lo, hi, id /*id is good here*/, + ItemKind::Mac(spanned(lo, hi, Mac_ { path: pth, tts: tts })), + Visibility::Inherited, + attrs) + }), + } + } + } else { + // FIXME: Bad copy of attrs + let old_directory_ownership = + mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); + let item = try!(self.parse_item_(attrs.clone(), false, true)); + self.directory.ownership = old_directory_ownership; + match item { + Some(i) => Stmt { + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, i.span.hi), + node: StmtKind::Item(i), + }, + None => { + let unused_attrs = |attrs: &[_], s: &mut Self| { + if attrs.len() > 0 { + if s.prev_token_kind == PrevTokenKind::DocComment { + s.span_err_help(s.prev_span, + "found a documentation comment that doesn't document anything", + "doc comments must come before what they document, maybe a \ + comment was intended with `//`?"); + } else { + s.span_err(s.span, "expected statement after outer attribute"); + } + } + }; + + // Do not attempt to parse an expression if we're done here. + if self.token == token::Semi { + unused_attrs(&attrs, self); + self.bump(); + return Ok(None); + } + + if self.token == token::CloseDelim(token::Brace) { + unused_attrs(&attrs, self); + return Ok(None); + } + + // Remainder are line-expr stmts. + let e = try!(self.parse_expr_res( + Restrictions::restriction_stmt_expr(), Some(attrs.into()))); + Stmt { + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, e.span.hi), + node: StmtKind::Expr(e), + } + } + } + })) + } + + /// Is this expression a successfully-parsed statement? + fn expr_is_complete(&mut self, e: &Expr) -> bool { + self.restrictions.contains(RESTRICTION_STMT_EXPR) && + !classify::expr_requires_semi_to_be_stmt(e) + } + + /// Parse a block. No inner attrs are allowed. + pub fn parse_block(&mut self) -> PResult<'a, P<Block>> { + maybe_whole!(self, NtBlock, |x| x); + + let lo = self.span.lo; + + if !self.eat(&token::OpenDelim(token::Brace)) { + let sp = self.span; + let tok = self.this_token_to_string(); + let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok)); + + // Check to see if the user has written something like + // + // if (cond) + // bar; + // + // Which is valid in other languages, but not Rust. + match self.parse_stmt_without_recovery(false) { + Ok(Some(stmt)) => { + let mut stmt_span = stmt.span; + // expand the span to include the semicolon, if it exists + if self.eat(&token::Semi) { + stmt_span.hi = self.prev_span.hi; + } + e.span_help(stmt_span, "try placing this code inside a block"); + } + Err(mut e) => { + self.recover_stmt_(SemiColonMode::Break); + self.cancel(&mut e); + } + _ => () + } + return Err(e); + } + + self.parse_block_tail(lo, BlockCheckMode::Default) + } + + /// Parse a block. Inner attrs are allowed. + fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> { + maybe_whole!(self, NtBlock, |x| (Vec::new(), x)); + + let lo = self.span.lo; + try!(self.expect(&token::OpenDelim(token::Brace))); + Ok((try!(self.parse_inner_attributes()), + try!(self.parse_block_tail(lo, BlockCheckMode::Default)))) + } + + /// Parse the rest of a block expression or function body + /// Precondition: already parsed the '{'. + fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> { + let mut stmts = vec![]; + + while !self.eat(&token::CloseDelim(token::Brace)) { + if let Some(stmt) = try!(self.parse_full_stmt(false)) { + stmts.push(stmt); + } else if self.token == token::Eof { + break; + } else { + // Found only `;` or `}`. + continue; + }; + } + + Ok(P(ast::Block { + stmts: stmts, + id: ast::DUMMY_NODE_ID, + rules: s, + span: mk_sp(lo, self.prev_span.hi), + })) + } + + /// Parse a statement, including the trailing semicolon. + pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> { + let mut stmt = match self.parse_stmt_(macro_legacy_warnings) { + Some(stmt) => stmt, + None => return Ok(None), + }; + + match stmt.node { + StmtKind::Expr(ref expr) if self.token != token::Eof => { + // expression without semicolon + if classify::expr_requires_semi_to_be_stmt(expr) { + // Just check for errors and recover; do not eat semicolon yet. + if let Err(mut e) = + self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)]) + { + e.emit(); + self.recover_stmt(); + } + } + } + StmtKind::Local(..) => { + // We used to incorrectly allow a macro-expanded let statement to lack a semicolon. + if macro_legacy_warnings && self.token != token::Semi { + self.warn_missing_semicolon(); + } else { + try!(self.expect_one_of(&[token::Semi], &[])); + } + } + _ => {} + } + + if self.eat(&token::Semi) { + stmt = stmt.add_trailing_semicolon(); + } + + stmt.span.hi = self.prev_span.hi; + Ok(Some(stmt)) + } + + fn warn_missing_semicolon(&self) { + self.diagnostic().struct_span_warn(self.span, { + &format!("expected `;`, found `{}`", self.this_token_to_string()) + }).note({ + "This was erroneously allowed and will become a hard error in a future release" + }).emit(); + } + + // Parses a sequence of bounds if a `:` is found, + // otherwise returns empty list. + fn parse_colon_then_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> + { + if !self.eat(&token::Colon) { + Ok(P::new()) + } else { + self.parse_ty_param_bounds() + } + } + + // matches bounds = ( boundseq )? + // where boundseq = ( polybound + boundseq ) | polybound + // and polybound = ( 'for' '<' 'region '>' )? bound + // and bound = 'region | trait_ref + fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> + { + let mut result = vec![]; + loop { + let question_span = self.span; + let ate_question = self.eat(&token::Question); + match self.token { + token::Lifetime(lifetime) => { + if ate_question { + self.span_err(question_span, + "`?` may only modify trait bounds, not lifetime bounds"); + } + result.push(RegionTyParamBound(ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: self.span, + name: lifetime.name + })); + self.bump(); + } + _ if self.token.is_path_start() || self.token.is_keyword(keywords::For) => { + let poly_trait_ref = try!(self.parse_poly_trait_ref()); + let modifier = if ate_question { + TraitBoundModifier::Maybe + } else { + TraitBoundModifier::None + }; + result.push(TraitTyParamBound(poly_trait_ref, modifier)) + } + _ => break, + } + + if !self.eat(&token::BinOp(token::Plus)) { + break; + } + } + + return Ok(P::from_vec(result)); + } + + /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )? + fn parse_ty_param(&mut self, preceding_attrs: Vec<ast::Attribute>) -> PResult<'a, TyParam> { + let span = self.span; + let ident = try!(self.parse_ident()); + + let bounds = try!(self.parse_colon_then_ty_param_bounds()); + + let default = if self.check(&token::Eq) { + self.bump(); + Some(try!(self.parse_ty_sum())) + } else { + None + }; + + Ok(TyParam { + attrs: preceding_attrs.into(), + ident: ident, + id: ast::DUMMY_NODE_ID, + bounds: bounds, + default: default, + span: span, + }) + } + + /// Parse a set of optional generic type parameter declarations. Where + /// clauses are not parsed here, and must be added later via + /// `parse_where_clause()`. + /// + /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > ) + /// | ( < lifetimes , typaramseq ( , )? > ) + /// where typaramseq = ( typaram ) | ( typaram , typaramseq ) + pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> { + maybe_whole!(self, NtGenerics, |x| x); + let span_lo = self.span.lo; + + if self.eat(&token::Lt) { + // Upon encountering attribute in generics list, we do not + // know if it is attached to lifetime or to type param. + // + // Solution: 1. eagerly parse attributes in tandem with + // lifetime defs, 2. store last set of parsed (and unused) + // attributes in `attrs`, and 3. pass in those attributes + // when parsing formal type param after lifetime defs. + let mut attrs = vec![]; + let lifetime_defs = try!(self.parse_lifetime_defs(Some(&mut attrs))); + let mut seen_default = false; + let mut post_lifetime_attrs = Some(attrs); + let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| { + try!(p.forbid_lifetime()); + // Move out of `post_lifetime_attrs` if present. O/w + // not first type param: parse attributes anew. + let attrs = match post_lifetime_attrs.as_mut() { + None => try!(p.parse_outer_attributes()), + Some(attrs) => mem::replace(attrs, vec![]), + }; + post_lifetime_attrs = None; + let ty_param = try!(p.parse_ty_param(attrs)); + if ty_param.default.is_some() { + seen_default = true; + } else if seen_default { + let prev_span = p.prev_span; + p.span_err(prev_span, + "type parameters with a default must be trailing"); + } + Ok(ty_param) + })); + if let Some(attrs) = post_lifetime_attrs { + if !attrs.is_empty() { + self.span_err(attrs[0].span, + "trailing attribute after lifetime parameters"); + } + } + Ok(ast::Generics { + lifetimes: lifetime_defs, + ty_params: ty_params, + where_clause: WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + }, + span: mk_sp(span_lo, self.prev_span.hi), + }) + } else { + Ok(ast::Generics::default()) + } + } + + fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>, + Vec<P<Ty>>, + Vec<TypeBinding>)> { + let span_lo = self.span.lo; + let lifetimes = try!(self.parse_lifetimes(token::Comma)); + + let missing_comma = !lifetimes.is_empty() && + !self.token.is_like_gt() && + self.prev_token_kind != PrevTokenKind::Comma; + + if missing_comma { + + let msg = format!("expected `,` or `>` after lifetime \ + name, found `{}`", + self.this_token_to_string()); + let mut err = self.diagnostic().struct_span_err(self.span, &msg); + + let span_hi = self.span.hi; + let span_hi = match self.parse_ty() { + Ok(..) => self.span.hi, + Err(ref mut err) => { + self.cancel(err); + span_hi + } + }; + + let msg = format!("did you mean a single argument type &'a Type, \ + or did you mean the comma-separated arguments \ + 'a, Type?"); + err.span_note(mk_sp(span_lo, span_hi), &msg); + return Err(err); + } + + // First parse types. + let (types, returned) = try!(self.parse_seq_to_gt_or_return( + Some(token::Comma), + |p| { + try!(p.forbid_lifetime()); + if p.look_ahead(1, |t| t == &token::Eq) { + Ok(None) + } else { + Ok(Some(try!(p.parse_ty_sum()))) + } + } + )); + + // If we found the `>`, don't continue. + if !returned { + return Ok((lifetimes, types.into_vec(), Vec::new())); + } + + // Then parse type bindings. + let bindings = try!(self.parse_seq_to_gt( + Some(token::Comma), + |p| { + try!(p.forbid_lifetime()); + let lo = p.span.lo; + let ident = try!(p.parse_ident()); + try!(p.expect(&token::Eq)); + let ty = try!(p.parse_ty()); + let hi = ty.span.hi; + let span = mk_sp(lo, hi); + return Ok(TypeBinding{id: ast::DUMMY_NODE_ID, + ident: ident, + ty: ty, + span: span, + }); + } + )); + Ok((lifetimes, types.into_vec(), bindings.into_vec())) + } + + fn forbid_lifetime(&mut self) -> PResult<'a, ()> { + if self.token.is_lifetime() { + let span = self.span; + return Err(self.diagnostic().struct_span_err(span, "lifetime parameters must be \ + declared prior to type parameters")) + } + Ok(()) + } + + /// Parses an optional `where` clause and places it in `generics`. + /// + /// ```ignore + /// where T : Trait<U, V> + 'b, 'a : 'b + /// ``` + pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> { + maybe_whole!(self, NtWhereClause, |x| x); + + let mut where_clause = WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + }; + + if !self.eat_keyword(keywords::Where) { + return Ok(where_clause); + } + + // This is a temporary hack. + // + // We are considering adding generics to the `where` keyword as an alternative higher-rank + // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking + // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`. + if token::Lt == self.token { + let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime()); + if ident_or_lifetime { + let gt_comma_or_colon = self.look_ahead(2, |t| { + *t == token::Gt || *t == token::Comma || *t == token::Colon + }); + if gt_comma_or_colon { + self.span_err(self.span, "syntax `where<T>` is reserved for future use"); + } + } + } + + let mut parsed_something = false; + loop { + let lo = self.span.lo; + match self.token { + token::OpenDelim(token::Brace) => { + break + } + + token::Lifetime(..) => { + let bounded_lifetime = + try!(self.parse_lifetime()); + + try!(self.expect(&token::Colon)); + + let bounds = + try!(self.parse_lifetimes(token::BinOp(token::Plus))); + + let hi = self.prev_span.hi; + let span = mk_sp(lo, hi); + + where_clause.predicates.push(ast::WherePredicate::RegionPredicate( + ast::WhereRegionPredicate { + span: span, + lifetime: bounded_lifetime, + bounds: bounds + } + )); + + parsed_something = true; + } + + _ => { + let bound_lifetimes = if self.eat_keyword(keywords::For) { + // Higher ranked constraint. + try!(self.expect(&token::Lt)); + let lifetime_defs = try!(self.parse_lifetime_defs(None)); + try!(self.expect_gt()); + lifetime_defs + } else { + vec![] + }; + + let bounded_ty = try!(self.parse_ty()); + + if self.eat(&token::Colon) { + let bounds = try!(self.parse_ty_param_bounds()); + let hi = self.prev_span.hi; + let span = mk_sp(lo, hi); + + if bounds.is_empty() { + self.span_err(span, + "each predicate in a `where` clause must have \ + at least one bound in it"); + } + + where_clause.predicates.push(ast::WherePredicate::BoundPredicate( + ast::WhereBoundPredicate { + span: span, + bound_lifetimes: bound_lifetimes, + bounded_ty: bounded_ty, + bounds: bounds, + })); + + parsed_something = true; + } else if self.eat(&token::Eq) { + // let ty = try!(self.parse_ty()); + let hi = self.prev_span.hi; + let span = mk_sp(lo, hi); + // where_clause.predicates.push( + // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { + // id: ast::DUMMY_NODE_ID, + // span: span, + // path: panic!("NYI"), //bounded_ty, + // ty: ty, + // })); + // parsed_something = true; + // // FIXME(#18433) + self.span_err(span, + "equality constraints are not yet supported \ + in where clauses (#20041)"); + } else { + let prev_span = self.prev_span; + self.span_err(prev_span, + "unexpected token in `where` clause"); + } + } + }; + + if !self.eat(&token::Comma) { + break + } + } + + if !parsed_something { + let prev_span = self.prev_span; + self.span_err(prev_span, + "a `where` clause must have at least one predicate \ + in it"); + } + + Ok(where_clause) + } + + fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool) + -> PResult<'a, (Vec<Arg> , bool)> { + let sp = self.span; + let mut variadic = false; + let args: Vec<Option<Arg>> = + try!(self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| { + if p.token == token::DotDotDot { + p.bump(); + if allow_variadic { + if p.token != token::CloseDelim(token::Paren) { + let span = p.span; + p.span_err(span, + "`...` must be last in argument list for variadic function"); + } + } else { + let span = p.span; + p.span_err(span, + "only foreign functions are allowed to be variadic"); + } + variadic = true; + Ok(None) + } else { + match p.parse_arg_general(named_args) { + Ok(arg) => Ok(Some(arg)), + Err(mut e) => { + e.emit(); + p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]); + Ok(None) + } + } + } + } + )); + + let args: Vec<_> = args.into_iter().filter_map(|x| x).collect(); + + if variadic && args.is_empty() { + self.span_err(sp, + "variadic function must be declared with at least one named argument"); + } + + Ok((args, variadic)) + } + + /// Parse the argument list and result type of a function declaration + pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> { + + let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic)); + let ret_ty = try!(self.parse_ret_ty()); + + Ok(P(FnDecl { + inputs: args, + output: ret_ty, + variadic: variadic + })) + } + + /// Returns the parsed optional self argument and whether a self shortcut was used. + fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> { + let expect_ident = |this: &mut Self| match this.token { + // Preserve hygienic context. + token::Ident(ident) => { this.bump(); codemap::respan(this.prev_span, ident) } + _ => unreachable!() + }; + let isolated_self = |this: &mut Self, n| { + this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) && + this.look_ahead(n + 1, |t| t != &token::ModSep) + }; + + // Parse optional self parameter of a method. + // Only a limited set of initial token sequences is considered self parameters, anything + // else is parsed as a normal function parameter list, so some lookahead is required. + let eself_lo = self.span.lo; + let (eself, eself_ident) = match self.token { + token::BinOp(token::And) => { + // &self + // &mut self + // &'lt self + // &'lt mut self + // ¬_self + if isolated_self(self, 1) { + self.bump(); + (SelfKind::Region(None, Mutability::Immutable), expect_ident(self)) + } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) && + isolated_self(self, 2) { + self.bump(); + self.bump(); + (SelfKind::Region(None, Mutability::Mutable), expect_ident(self)) + } else if self.look_ahead(1, |t| t.is_lifetime()) && + isolated_self(self, 2) { + self.bump(); + let lt = try!(self.parse_lifetime()); + (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self)) + } else if self.look_ahead(1, |t| t.is_lifetime()) && + self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) && + isolated_self(self, 3) { + self.bump(); + let lt = try!(self.parse_lifetime()); + self.bump(); + (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self)) + } else { + return Ok(None); + } + } + token::BinOp(token::Star) => { + // *self + // *const self + // *mut self + // *not_self + // Emit special error for `self` cases. + if isolated_self(self, 1) { + self.bump(); + self.span_err(self.span, "cannot pass `self` by raw pointer"); + (SelfKind::Value(Mutability::Immutable), expect_ident(self)) + } else if self.look_ahead(1, |t| t.is_mutability()) && + isolated_self(self, 2) { + self.bump(); + self.bump(); + self.span_err(self.span, "cannot pass `self` by raw pointer"); + (SelfKind::Value(Mutability::Immutable), expect_ident(self)) + } else { + return Ok(None); + } + } + token::Ident(..) => { + if isolated_self(self, 0) { + // self + // self: TYPE + let eself_ident = expect_ident(self); + if self.eat(&token::Colon) { + let ty = try!(self.parse_ty_sum()); + (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident) + } else { + (SelfKind::Value(Mutability::Immutable), eself_ident) + } + } else if self.token.is_keyword(keywords::Mut) && + isolated_self(self, 1) { + // mut self + // mut self: TYPE + self.bump(); + let eself_ident = expect_ident(self); + if self.eat(&token::Colon) { + let ty = try!(self.parse_ty_sum()); + (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident) + } else { + (SelfKind::Value(Mutability::Mutable), eself_ident) + } + } else { + return Ok(None); + } + } + _ => return Ok(None), + }; + + let eself = codemap::respan(mk_sp(eself_lo, self.prev_span.hi), eself); + Ok(Some(Arg::from_self(eself, eself_ident))) + } + + /// Parse the parameter list and result type of a function that may have a `self` parameter. + fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>, + { + try!(self.expect(&token::OpenDelim(token::Paren))); + + // Parse optional self argument + let self_arg = try!(self.parse_self_arg()); + + // Parse the rest of the function parameter list. + let sep = SeqSep::trailing_allowed(token::Comma); + let fn_inputs = if let Some(self_arg) = self_arg { + if self.check(&token::CloseDelim(token::Paren)) { + vec![self_arg] + } else if self.eat(&token::Comma) { + let mut fn_inputs = vec![self_arg]; + fn_inputs.append(&mut self.parse_seq_to_before_end( + &token::CloseDelim(token::Paren), sep, parse_arg_fn) + ); + fn_inputs + } else { + return self.unexpected(); + } + } else { + self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn) + }; + + // Parse closing paren and return type. + try!(self.expect(&token::CloseDelim(token::Paren))); + Ok(P(FnDecl { + inputs: fn_inputs, + output: try!(self.parse_ret_ty()), + variadic: false + })) + } + + // parse the |arg, arg| header on a lambda + fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> { + let inputs_captures = { + if self.eat(&token::OrOr) { + Vec::new() + } else { + try!(self.expect(&token::BinOp(token::Or))); + let args = self.parse_seq_to_before_end( + &token::BinOp(token::Or), + SeqSep::trailing_allowed(token::Comma), + |p| p.parse_fn_block_arg() + ); + self.bump(); + args + } + }; + let output = try!(self.parse_ret_ty()); + + Ok(P(FnDecl { + inputs: inputs_captures, + output: output, + variadic: false + })) + } + + /// Parse the name and optional generic types of a function header. + fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> { + let id = try!(self.parse_ident()); + let generics = try!(self.parse_generics()); + Ok((id, generics)) + } + + fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident, + node: ItemKind, vis: Visibility, + attrs: Vec<Attribute>) -> P<Item> { + P(Item { + ident: ident, + attrs: attrs, + id: ast::DUMMY_NODE_ID, + node: node, + vis: vis, + span: mk_sp(lo, hi) + }) + } + + /// Parse an item-position function declaration. + fn parse_item_fn(&mut self, + unsafety: Unsafety, + constness: Spanned<Constness>, + abi: abi::Abi) + -> PResult<'a, ItemInfo> { + let (ident, mut generics) = try!(self.parse_fn_header()); + let decl = try!(self.parse_fn_decl(false)); + generics.where_clause = try!(self.parse_where_clause()); + let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block()); + Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs))) + } + + /// true if we are looking at `const ID`, false for things like `const fn` etc + pub fn is_const_item(&mut self) -> bool { + self.token.is_keyword(keywords::Const) && + !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) && + !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) + } + + /// parses all the "front matter" for a `fn` declaration, up to + /// and including the `fn` keyword: + /// + /// - `const fn` + /// - `unsafe fn` + /// - `const unsafe fn` + /// - `extern fn` + /// - etc + pub fn parse_fn_front_matter(&mut self) + -> PResult<'a, (Spanned<ast::Constness>, + ast::Unsafety, + abi::Abi)> { + let is_const_fn = self.eat_keyword(keywords::Const); + let const_span = self.prev_span; + let unsafety = try!(self.parse_unsafety()); + let (constness, unsafety, abi) = if is_const_fn { + (respan(const_span, Constness::Const), unsafety, Abi::Rust) + } else { + let abi = if self.eat_keyword(keywords::Extern) { + try!(self.parse_opt_abi()).unwrap_or(Abi::C) + } else { + Abi::Rust + }; + (respan(self.prev_span, Constness::NotConst), unsafety, abi) + }; + try!(self.expect_keyword(keywords::Fn)); + Ok((constness, unsafety, abi)) + } + + /// Parse an impl item. + pub fn parse_impl_item(&mut self) -> PResult<'a, ImplItem> { + maybe_whole!(self, NtImplItem, |x| x); + + let mut attrs = try!(self.parse_outer_attributes()); + let lo = self.span.lo; + let vis = try!(self.parse_visibility(true)); + let defaultness = try!(self.parse_defaultness()); + let (name, node) = if self.eat_keyword(keywords::Type) { + let name = try!(self.parse_ident()); + try!(self.expect(&token::Eq)); + let typ = try!(self.parse_ty_sum()); + try!(self.expect(&token::Semi)); + (name, ast::ImplItemKind::Type(typ)) + } else if self.is_const_item() { + try!(self.expect_keyword(keywords::Const)); + let name = try!(self.parse_ident()); + try!(self.expect(&token::Colon)); + let typ = try!(self.parse_ty_sum()); + try!(self.expect(&token::Eq)); + let expr = try!(self.parse_expr()); + try!(self.expect(&token::Semi)); + (name, ast::ImplItemKind::Const(typ, expr)) + } else { + let (name, inner_attrs, node) = try!(self.parse_impl_method(&vis)); + attrs.extend(inner_attrs); + (name, node) + }; + + Ok(ImplItem { + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, self.prev_span.hi), + ident: name, + vis: vis, + defaultness: defaultness, + attrs: attrs, + node: node + }) + } + + fn complain_if_pub_macro(&mut self, visa: &Visibility, span: Span) { + match *visa { + Visibility::Inherited => (), + _ => { + let is_macro_rules: bool = match self.token { + token::Ident(sid) => sid.name == Symbol::intern("macro_rules"), + _ => false, + }; + if is_macro_rules { + self.diagnostic().struct_span_err(span, "can't qualify macro_rules \ + invocation with `pub`") + .help("did you mean #[macro_export]?") + .emit(); + } else { + self.diagnostic().struct_span_err(span, "can't qualify macro \ + invocation with `pub`") + .help("try adjusting the macro to put `pub` \ + inside the invocation") + .emit(); + } + } + } + } + + /// Parse a method or a macro invocation in a trait impl. + fn parse_impl_method(&mut self, vis: &Visibility) + -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> { + // code copied from parse_macro_use_or_failure... abstraction! + if self.token.is_path_start() { + // method macro. + + let prev_span = self.prev_span; + self.complain_if_pub_macro(&vis, prev_span); + + let lo = self.span.lo; + let pth = try!(self.parse_path(PathStyle::Mod)); + try!(self.expect(&token::Not)); + + // eat a matched-delimiter token tree: + let delim = try!(self.expect_open_delim()); + let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim), + SeqSep::none(), + |p| p.parse_token_tree())); + if delim != token::Brace { + try!(self.expect(&token::Semi)) + } + + let mac = spanned(lo, self.prev_span.hi, Mac_ { path: pth, tts: tts }); + Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac))) + } else { + let (constness, unsafety, abi) = try!(self.parse_fn_front_matter()); + let ident = try!(self.parse_ident()); + let mut generics = try!(self.parse_generics()); + let decl = try!(self.parse_fn_decl_with_self(|p| p.parse_arg())); + generics.where_clause = try!(self.parse_where_clause()); + let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block()); + Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig { + generics: generics, + abi: abi, + unsafety: unsafety, + constness: constness, + decl: decl + }, body))) + } + } + + /// Parse trait Foo { ... } + fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> { + let ident = try!(self.parse_ident()); + let mut tps = try!(self.parse_generics()); + + // Parse supertrait bounds. + let bounds = try!(self.parse_colon_then_ty_param_bounds()); + + tps.where_clause = try!(self.parse_where_clause()); + + let meths = try!(self.parse_trait_items()); + Ok((ident, ItemKind::Trait(unsafety, tps, bounds, meths), None)) + } + + /// Parses items implementations variants + /// impl<T> Foo { ... } + /// impl<T> ToString for &'static T { ... } + /// impl Send for .. {} + fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> { + let impl_span = self.span; + + // First, parse type parameters if necessary. + let mut generics = try!(self.parse_generics()); + + // Special case: if the next identifier that follows is '(', don't + // allow this to be parsed as a trait. + let could_be_trait = self.token != token::OpenDelim(token::Paren); + + let neg_span = self.span; + let polarity = if self.eat(&token::Not) { + ast::ImplPolarity::Negative + } else { + ast::ImplPolarity::Positive + }; + + // Parse the trait. + let mut ty = try!(self.parse_ty_sum()); + + // Parse traits, if necessary. + let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) { + // New-style trait. Reinterpret the type as a trait. + match ty.node { + TyKind::Path(None, ref path) => { + Some(TraitRef { + path: (*path).clone(), + ref_id: ty.id, + }) + } + _ => { + self.span_err(ty.span, "not a trait"); + None + } + } + } else { + match polarity { + ast::ImplPolarity::Negative => { + // This is a negated type implementation + // `impl !MyType {}`, which is not allowed. + self.span_err(neg_span, "inherent implementation can't be negated"); + }, + _ => {} + } + None + }; + + if opt_trait.is_some() && self.eat(&token::DotDot) { + if generics.is_parameterized() { + self.span_err(impl_span, "default trait implementations are not \ + allowed to have generics"); + } + + try!(self.expect(&token::OpenDelim(token::Brace))); + try!(self.expect(&token::CloseDelim(token::Brace))); + Ok((keywords::Invalid.ident(), + ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None)) + } else { + if opt_trait.is_some() { + ty = try!(self.parse_ty_sum()); + } + generics.where_clause = try!(self.parse_where_clause()); + + try!(self.expect(&token::OpenDelim(token::Brace))); + let attrs = try!(self.parse_inner_attributes()); + + let mut impl_items = vec![]; + while !self.eat(&token::CloseDelim(token::Brace)) { + impl_items.push(try!(self.parse_impl_item())); + } + + Ok((keywords::Invalid.ident(), + ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items), + Some(attrs))) + } + } + + /// Parse a::B<String,i32> + fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> { + Ok(ast::TraitRef { + path: try!(self.parse_path(PathStyle::Type)), + ref_id: ast::DUMMY_NODE_ID, + }) + } + + fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> { + if self.eat_keyword(keywords::For) { + try!(self.expect(&token::Lt)); + let lifetime_defs = try!(self.parse_lifetime_defs(None)); + try!(self.expect_gt()); + Ok(lifetime_defs) + } else { + Ok(Vec::new()) + } + } + + /// Parse for<'l> a::B<String,i32> + fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> { + let lo = self.span.lo; + let lifetime_defs = try!(self.parse_late_bound_lifetime_defs()); + + Ok(ast::PolyTraitRef { + bound_lifetimes: lifetime_defs, + trait_ref: try!(self.parse_trait_ref()), + span: mk_sp(lo, self.prev_span.hi), + }) + } + + /// Parse struct Foo { ... } + fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> { + let class_name = try!(self.parse_ident()); + let mut generics = try!(self.parse_generics()); + + // There is a special case worth noting here, as reported in issue #17904. + // If we are parsing a tuple struct it is the case that the where clause + // should follow the field list. Like so: + // + // struct Foo<T>(T) where T: Copy; + // + // If we are parsing a normal record-style struct it is the case + // that the where clause comes before the body, and after the generics. + // So if we look ahead and see a brace or a where-clause we begin + // parsing a record style struct. + // + // Otherwise if we look ahead and see a paren we parse a tuple-style + // struct. + + let vdata = if self.token.is_keyword(keywords::Where) { + generics.where_clause = try!(self.parse_where_clause()); + if self.eat(&token::Semi) { + // If we see a: `struct Foo<T> where T: Copy;` style decl. + VariantData::Unit(ast::DUMMY_NODE_ID) + } else { + // If we see: `struct Foo<T> where T: Copy { ... }` + VariantData::Struct(try!(self.parse_record_struct_body()), ast::DUMMY_NODE_ID) + } + // No `where` so: `struct Foo<T>;` + } else if self.eat(&token::Semi) { + VariantData::Unit(ast::DUMMY_NODE_ID) + // Record-style struct definition + } else if self.token == token::OpenDelim(token::Brace) { + VariantData::Struct(try!(self.parse_record_struct_body()), ast::DUMMY_NODE_ID) + // Tuple-style struct definition with optional where-clause. + } else if self.token == token::OpenDelim(token::Paren) { + let body = VariantData::Tuple(try!(self.parse_tuple_struct_body()), ast::DUMMY_NODE_ID); + generics.where_clause = try!(self.parse_where_clause()); + try!(self.expect(&token::Semi)); + body + } else { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \ + name, found `{}`", token_str))) + }; + + Ok((class_name, ItemKind::Struct(vdata, generics), None)) + } + + /// Parse union Foo { ... } + fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> { + let class_name = try!(self.parse_ident()); + let mut generics = try!(self.parse_generics()); + + let vdata = if self.token.is_keyword(keywords::Where) { + generics.where_clause = try!(self.parse_where_clause()); + VariantData::Struct(try!(self.parse_record_struct_body()), ast::DUMMY_NODE_ID) + } else if self.token == token::OpenDelim(token::Brace) { + VariantData::Struct(try!(self.parse_record_struct_body()), ast::DUMMY_NODE_ID) + } else { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected `where` or `{{` after union \ + name, found `{}`", token_str))) + }; + + Ok((class_name, ItemKind::Union(vdata, generics), None)) + } + + pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> { + let mut fields = Vec::new(); + if self.eat(&token::OpenDelim(token::Brace)) { + while self.token != token::CloseDelim(token::Brace) { + fields.push(try!(self.parse_struct_decl_field().map_err(|e| { + self.recover_stmt(); + self.eat(&token::CloseDelim(token::Brace)); + e + }))); + } + + self.bump(); + } else { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected `where`, or `{{` after struct \ + name, found `{}`", + token_str))); + } + + Ok(fields) + } + + pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> { + // This is the case where we find `struct Foo<T>(T) where T: Copy;` + // Unit like structs are handled in parse_item_struct function + let fields = try!(self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| { + let attrs = try!(p.parse_outer_attributes()); + let lo = p.span.lo; + let mut vis = try!(p.parse_visibility(false)); + let ty_is_interpolated = + p.token.is_interpolated() || p.look_ahead(1, |t| t.is_interpolated()); + let mut ty = try!(p.parse_ty_sum()); + + // Handle `pub(path) type`, in which `vis` will be `pub` and `ty` will be `(path)`. + if vis == Visibility::Public && !ty_is_interpolated && + p.token != token::Comma && p.token != token::CloseDelim(token::Paren) { + ty = if let TyKind::Paren(ref path_ty) = ty.node { + if let TyKind::Path(None, ref path) = path_ty.node { + vis = Visibility::Restricted { path: P(path.clone()), id: path_ty.id }; + Some(try!(p.parse_ty_sum())) + } else { + None + } + } else { + None + }.unwrap_or(ty); + } + Ok(StructField { + span: mk_sp(lo, p.span.hi), + vis: vis, + ident: None, + id: ast::DUMMY_NODE_ID, + ty: ty, + attrs: attrs, + }) + })); + + Ok(fields) + } + + /// Parse a structure field declaration + pub fn parse_single_struct_field(&mut self, + lo: BytePos, + vis: Visibility, + attrs: Vec<Attribute> ) + -> PResult<'a, StructField> { + let a_var = try!(self.parse_name_and_ty(lo, vis, attrs)); + match self.token { + token::Comma => { + self.bump(); + } + token::CloseDelim(token::Brace) => {} + token::DocComment(_) => return Err(self.span_fatal_help(self.span, + "found a documentation comment that doesn't document anything", + "doc comments must come before what they document, maybe a comment was \ + intended with `//`?")), + _ => return Err(self.span_fatal_help(self.span, + &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()), + "struct fields should be separated by commas")), + } + Ok(a_var) + } + + /// Parse an element of a struct definition + fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> { + let attrs = try!(self.parse_outer_attributes()); + let lo = self.span.lo; + let vis = try!(self.parse_visibility(true)); + self.parse_single_struct_field(lo, vis, attrs) + } + + // If `allow_path` is false, just parse the `pub` in `pub(path)` (but still parse `pub(crate)`) + fn parse_visibility(&mut self, allow_path: bool) -> PResult<'a, Visibility> { + let pub_crate = |this: &mut Self| { + let span = this.prev_span; + try!(this.expect(&token::CloseDelim(token::Paren))); + Ok(Visibility::Crate(span)) + }; + + if !self.eat_keyword(keywords::Pub) { + Ok(Visibility::Inherited) + } else if !allow_path { + // Look ahead to avoid eating the `(` in `pub(path)` while still parsing `pub(crate)` + if self.token == token::OpenDelim(token::Paren) && + self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) { + self.bump(); self.bump(); + pub_crate(self) + } else { + Ok(Visibility::Public) + } + } else if !self.eat(&token::OpenDelim(token::Paren)) { + Ok(Visibility::Public) + } else if self.eat_keyword(keywords::Crate) { + pub_crate(self) + } else { + let path = try!(self.parse_path(PathStyle::Mod)).default_to_global(); + try!(self.expect(&token::CloseDelim(token::Paren))); + Ok(Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }) + } + } + + /// Parse defaultness: DEFAULT or nothing + fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> { + if self.eat_contextual_keyword(keywords::Default.ident()) { + Ok(Defaultness::Default) + } else { + Ok(Defaultness::Final) + } + } + + /// Given a termination token, parse all of the items in a module + fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> { + let mut items = vec![]; + while let Some(item) = try!(self.parse_item()) { + items.push(item); + } + + if !self.eat(term) { + let token_str = self.this_token_to_string(); + return Err(self.fatal(&format!("expected item, found `{}`", token_str))); + } + + let hi = if self.span == syntax_pos::DUMMY_SP { + inner_lo + } else { + self.prev_span.hi + }; + + Ok(ast::Mod { + inner: mk_sp(inner_lo, hi), + items: items + }) + } + + fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> { + let id = try!(self.parse_ident()); + try!(self.expect(&token::Colon)); + let ty = try!(self.parse_ty_sum()); + try!(self.expect(&token::Eq)); + let e = try!(self.parse_expr()); + try!(self.expect(&token::Semi)); + let item = match m { + Some(m) => ItemKind::Static(ty, m, e), + None => ItemKind::Const(ty, e), + }; + Ok((id, item, None)) + } + + /// Parse a `mod <foo> { ... }` or `mod <foo>;` item + fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> { + let (in_cfg, outer_attrs) = { + let mut strip_unconfigured = ::config::StripUnconfigured { + sess: self.sess, + should_test: false, // irrelevant + features: None, // don't perform gated feature checking + }; + let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned()); + (strip_unconfigured.in_cfg(&outer_attrs), outer_attrs) + }; + + let id_span = self.span; + let id = try!(self.parse_ident()); + if self.check(&token::Semi) { + self.bump(); + if in_cfg { + // This mod is in an external file. Let's go get it! + let ModulePathSuccess { path, directory_ownership, warn } = + try!(self.submod_path(id, &outer_attrs, id_span)); + let (module, mut attrs) = + try!(self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)); + if warn { + let attr = ast::Attribute { + id: attr::mk_attr_id(), + style: ast::AttrStyle::Outer, + value: ast::MetaItem { + name: Symbol::intern("warn_directory_ownership"), + node: ast::MetaItemKind::Word, + span: syntax_pos::DUMMY_SP, + }, + is_sugared_doc: false, + span: syntax_pos::DUMMY_SP, + }; + attr::mark_known(&attr); + attrs.push(attr); + } + Ok((id, module, Some(attrs))) + } else { + let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() }; + Ok((id, ItemKind::Mod(placeholder), None)) + } + } else { + let old_directory = self.directory.clone(); + self.push_directory(id, &outer_attrs); + try!(self.expect(&token::OpenDelim(token::Brace))); + let mod_inner_lo = self.span.lo; + let attrs = try!(self.parse_inner_attributes()); + let module = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)); + self.directory = old_directory; + Ok((id, ItemKind::Mod(module), Some(attrs))) + } + } + + fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) { + if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") { + self.directory.path.push(&*path.as_str()); + self.directory.ownership = DirectoryOwnership::Owned; + } else { + self.directory.path.push(&*id.name.as_str()); + } + } + + pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> { + attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d.as_str())) + } + + /// Returns either a path to a module, or . + pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath + { + let mod_name = id.to_string(); + let default_path_str = format!("{}.rs", mod_name); + let secondary_path_str = format!("{}/mod.rs", mod_name); + let default_path = dir_path.join(&default_path_str); + let secondary_path = dir_path.join(&secondary_path_str); + let default_exists = codemap.file_exists(&default_path); + let secondary_exists = codemap.file_exists(&secondary_path); + + let result = match (default_exists, secondary_exists) { + (true, false) => Ok(ModulePathSuccess { + path: default_path, + directory_ownership: DirectoryOwnership::UnownedViaMod(false), + warn: false, + }), + (false, true) => Ok(ModulePathSuccess { + path: secondary_path, + directory_ownership: DirectoryOwnership::Owned, + warn: false, + }), + (false, false) => Err(ModulePathError { + err_msg: format!("file not found for module `{}`", mod_name), + help_msg: format!("name the file either {} or {} inside the directory {:?}", + default_path_str, + secondary_path_str, + dir_path.display()), + }), + (true, true) => Err(ModulePathError { + err_msg: format!("file for module `{}` found at both {} and {}", + mod_name, + default_path_str, + secondary_path_str), + help_msg: "delete or rename one of them to remove the ambiguity".to_owned(), + }), + }; + + ModulePath { + name: mod_name, + path_exists: default_exists || secondary_exists, + result: result, + } + } + + fn submod_path(&mut self, + id: ast::Ident, + outer_attrs: &[ast::Attribute], + id_sp: Span) -> PResult<'a, ModulePathSuccess> { + if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) { + return Ok(ModulePathSuccess { + directory_ownership: match path.file_name().and_then(|s| s.to_str()) { + Some("mod.rs") => DirectoryOwnership::Owned, + _ => DirectoryOwnership::UnownedViaMod(true), + }, + path: path, + warn: false, + }); + } + + let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap()); + + if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership { + let msg = + "Cannot declare a non-inline module inside a block unless it has a path attribute"; + let mut err = self.diagnostic().struct_span_err(id_sp, msg); + if paths.path_exists { + let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", + paths.name); + err.span_note(id_sp, &msg); + } + return Err(err); + } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership { + if warn { + if let Ok(result) = paths.result { + return Ok(ModulePathSuccess { warn: true, ..result }); + } + } + let mut err = self.diagnostic().struct_span_err(id_sp, + "cannot declare a new module at this location"); + let this_module = match self.directory.path.file_name() { + Some(file_name) => file_name.to_str().unwrap().to_owned(), + None => self.root_module_name.as_ref().unwrap().clone(), + }; + err.span_note(id_sp, + &format!("maybe move this module `{0}` to its own directory \ + via `{0}/mod.rs`", + this_module)); + if paths.path_exists { + err.span_note(id_sp, + &format!("... or maybe `use` the module `{}` instead \ + of possibly redeclaring it", + paths.name)); + return Err(err); + } else { + return Err(err); + }; + } + + match paths.result { + Ok(succ) => Ok(succ), + Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)), + } + } + + /// Read a module from a source file. + fn eval_src_mod(&mut self, + path: PathBuf, + directory_ownership: DirectoryOwnership, + name: String, + id_sp: Span) + -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> { + let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut(); + if let Some(i) = included_mod_stack.iter().position(|p| *p == path) { + let mut err = String::from("circular modules: "); + let len = included_mod_stack.len(); + for p in &included_mod_stack[i.. len] { + err.push_str(&p.to_string_lossy()); + err.push_str(" -> "); + } + err.push_str(&path.to_string_lossy()); + return Err(self.span_fatal(id_sp, &err[..])); + } + included_mod_stack.push(path.clone()); + drop(included_mod_stack); + + let mut p0 = + new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp); + let mod_inner_lo = p0.span.lo; + let mod_attrs = try!(p0.parse_inner_attributes()); + let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo)); + self.sess.included_mod_stack.borrow_mut().pop(); + Ok((ast::ItemKind::Mod(m0), mod_attrs)) + } + + /// Parse a function declaration from a foreign module + fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos, + attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> { + try!(self.expect_keyword(keywords::Fn)); + + let (ident, mut generics) = try!(self.parse_fn_header()); + let decl = try!(self.parse_fn_decl(true)); + generics.where_clause = try!(self.parse_where_clause()); + let hi = self.span.hi; + try!(self.expect(&token::Semi)); + Ok(ast::ForeignItem { + ident: ident, + attrs: attrs, + node: ForeignItemKind::Fn(decl, generics), + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, hi), + vis: vis + }) + } + + /// Parse a static item from a foreign module + fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos, + attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> { + try!(self.expect_keyword(keywords::Static)); + let mutbl = self.eat_keyword(keywords::Mut); + + let ident = try!(self.parse_ident()); + try!(self.expect(&token::Colon)); + let ty = try!(self.parse_ty_sum()); + let hi = self.span.hi; + try!(self.expect(&token::Semi)); + Ok(ForeignItem { + ident: ident, + attrs: attrs, + node: ForeignItemKind::Static(ty, mutbl), + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, hi), + vis: vis + }) + } + + /// Parse extern crate links + /// + /// # Examples + /// + /// extern crate foo; + /// extern crate bar as foo; + fn parse_item_extern_crate(&mut self, + lo: BytePos, + visibility: Visibility, + attrs: Vec<Attribute>) + -> PResult<'a, P<Item>> { + + let crate_name = try!(self.parse_ident()); + let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) { + (Some(crate_name.name), ident) + } else { + (None, crate_name) + }; + try!(self.expect(&token::Semi)); + + let prev_span = self.prev_span; + Ok(self.mk_item(lo, + prev_span.hi, + ident, + ItemKind::ExternCrate(maybe_path), + visibility, + attrs)) + } + + /// Parse `extern` for foreign ABIs + /// modules. + /// + /// `extern` is expected to have been + /// consumed before calling this method + /// + /// # Examples: + /// + /// extern "C" {} + /// extern {} + fn parse_item_foreign_mod(&mut self, + lo: BytePos, + opt_abi: Option<abi::Abi>, + visibility: Visibility, + mut attrs: Vec<Attribute>) + -> PResult<'a, P<Item>> { + try!(self.expect(&token::OpenDelim(token::Brace))); + + let abi = opt_abi.unwrap_or(Abi::C); + + attrs.extend(try!(self.parse_inner_attributes())); + + let mut foreign_items = vec![]; + while let Some(item) = try!(self.parse_foreign_item()) { + foreign_items.push(item); + } + try!(self.expect(&token::CloseDelim(token::Brace))); + + let prev_span = self.prev_span; + let m = ast::ForeignMod { + abi: abi, + items: foreign_items + }; + Ok(self.mk_item(lo, + prev_span.hi, + keywords::Invalid.ident(), + ItemKind::ForeignMod(m), + visibility, + attrs)) + } + + /// Parse type Foo = Bar; + fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> { + let ident = try!(self.parse_ident()); + let mut tps = try!(self.parse_generics()); + tps.where_clause = try!(self.parse_where_clause()); + try!(self.expect(&token::Eq)); + let ty = try!(self.parse_ty_sum()); + try!(self.expect(&token::Semi)); + Ok((ident, ItemKind::Ty(ty, tps), None)) + } + + /// Parse the part of an "enum" decl following the '{' + fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> { + let mut variants = Vec::new(); + let mut all_nullary = true; + let mut any_disr = None; + while self.token != token::CloseDelim(token::Brace) { + let variant_attrs = try!(self.parse_outer_attributes()); + let vlo = self.span.lo; + + let struct_def; + let mut disr_expr = None; + let ident = try!(self.parse_ident()); + if self.check(&token::OpenDelim(token::Brace)) { + // Parse a struct variant. + all_nullary = false; + struct_def = VariantData::Struct(try!(self.parse_record_struct_body()), + ast::DUMMY_NODE_ID); + } else if self.check(&token::OpenDelim(token::Paren)) { + all_nullary = false; + struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body()), + ast::DUMMY_NODE_ID); + } else if self.eat(&token::Eq) { + disr_expr = Some(try!(self.parse_expr())); + any_disr = disr_expr.as_ref().map(|expr| expr.span); + struct_def = VariantData::Unit(ast::DUMMY_NODE_ID); + } else { + struct_def = VariantData::Unit(ast::DUMMY_NODE_ID); + } + + let vr = ast::Variant_ { + name: ident, + attrs: variant_attrs, + data: struct_def, + disr_expr: disr_expr, + }; + variants.push(spanned(vlo, self.prev_span.hi, vr)); + + if !self.eat(&token::Comma) { break; } + } + try!(self.expect(&token::CloseDelim(token::Brace))); + match any_disr { + Some(disr_span) if !all_nullary => + self.span_err(disr_span, + "discriminator values can only be used with a c-like enum"), + _ => () + } + + Ok(ast::EnumDef { variants: variants }) + } + + /// Parse an "enum" declaration + fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> { + let id = try!(self.parse_ident()); + let mut generics = try!(self.parse_generics()); + generics.where_clause = try!(self.parse_where_clause()); + try!(self.expect(&token::OpenDelim(token::Brace))); + + let enum_definition = try!(self.parse_enum_def(&generics).map_err(|e| { + self.recover_stmt(); + self.eat(&token::CloseDelim(token::Brace)); + e + })); + Ok((id, ItemKind::Enum(enum_definition, generics), None)) + } + + /// Parses a string as an ABI spec on an extern type or module. Consumes + /// the `extern` keyword, if one is found. + fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> { + match self.token { + token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => { + let sp = self.span; + self.expect_no_suffix(sp, "ABI spec", suf); + self.bump(); + match abi::lookup(&s.as_str()) { + Some(abi) => Ok(Some(abi)), + None => { + let prev_span = self.prev_span; + self.span_err( + prev_span, + &format!("invalid ABI: expected one of [{}], \ + found `{}`", + abi::all_names().join(", "), + s)); + Ok(None) + } + } + } + + _ => Ok(None), + } + } + + /// Parse one of the items allowed by the flags. + /// NB: this function no longer parses the items inside an + /// extern crate. + fn parse_item_(&mut self, attrs: Vec<Attribute>, + macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> { + maybe_whole!(self, NtItem, |item| { + let mut item = item.unwrap(); + let mut attrs = attrs; + mem::swap(&mut item.attrs, &mut attrs); + item.attrs.extend(attrs); + Some(P(item)) + }); + + let lo = self.span.lo; + + let visibility = try!(self.parse_visibility(true)); + + if self.eat_keyword(keywords::Use) { + // USE ITEM + let item_ = ItemKind::Use(try!(self.parse_view_path())); + try!(self.expect(&token::Semi)); + + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + keywords::Invalid.ident(), + item_, + visibility, + attrs); + return Ok(Some(item)); + } + + if self.eat_keyword(keywords::Extern) { + if self.eat_keyword(keywords::Crate) { + return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs)))); + } + + let opt_abi = try!(self.parse_opt_abi()); + + if self.eat_keyword(keywords::Fn) { + // EXTERN FUNCTION ITEM + let fn_span = self.prev_span; + let abi = opt_abi.unwrap_or(Abi::C); + let (ident, item_, extra_attrs) = + try!(self.parse_item_fn(Unsafety::Normal, + respan(fn_span, Constness::NotConst), + abi)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } else if self.check(&token::OpenDelim(token::Brace)) { + return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)))); + } + + try!(self.unexpected()); + } + + if self.eat_keyword(keywords::Static) { + // STATIC ITEM + let m = if self.eat_keyword(keywords::Mut) { + Mutability::Mutable + } else { + Mutability::Immutable + }; + let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m))); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Const) { + let const_span = self.prev_span; + if self.check_keyword(keywords::Fn) + || (self.check_keyword(keywords::Unsafe) + && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) { + // CONST FUNCTION ITEM + let unsafety = if self.eat_keyword(keywords::Unsafe) { + Unsafety::Unsafe + } else { + Unsafety::Normal + }; + self.bump(); + let (ident, item_, extra_attrs) = + try!(self.parse_item_fn(unsafety, + respan(const_span, Constness::Const), + Abi::Rust)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + + // CONST ITEM + if self.eat_keyword(keywords::Mut) { + let prev_span = self.prev_span; + self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable") + .help("did you mean to declare a static?") + .emit(); + } + let (ident, item_, extra_attrs) = try!(self.parse_item_const(None)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) + { + // UNSAFE TRAIT ITEM + try!(self.expect_keyword(keywords::Unsafe)); + try!(self.expect_keyword(keywords::Trait)); + let (ident, item_, extra_attrs) = + try!(self.parse_item_trait(ast::Unsafety::Unsafe)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) + { + // IMPL ITEM + try!(self.expect_keyword(keywords::Unsafe)); + try!(self.expect_keyword(keywords::Impl)); + let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Fn) { + // FUNCTION ITEM + self.bump(); + let fn_span = self.prev_span; + let (ident, item_, extra_attrs) = + try!(self.parse_item_fn(Unsafety::Normal, + respan(fn_span, Constness::NotConst), + Abi::Rust)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Unsafe) + && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) { + // UNSAFE FUNCTION ITEM + self.bump(); + let abi = if self.eat_keyword(keywords::Extern) { + try!(self.parse_opt_abi()).unwrap_or(Abi::C) + } else { + Abi::Rust + }; + try!(self.expect_keyword(keywords::Fn)); + let fn_span = self.prev_span; + let (ident, item_, extra_attrs) = + try!(self.parse_item_fn(Unsafety::Unsafe, + respan(fn_span, Constness::NotConst), + abi)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Mod) { + // MODULE ITEM + let (ident, item_, extra_attrs) = + try!(self.parse_item_mod(&attrs[..])); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Type) { + // TYPE ITEM + let (ident, item_, extra_attrs) = try!(self.parse_item_type()); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Enum) { + // ENUM ITEM + let (ident, item_, extra_attrs) = try!(self.parse_item_enum()); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Trait) { + // TRAIT ITEM + let (ident, item_, extra_attrs) = + try!(self.parse_item_trait(ast::Unsafety::Normal)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Impl) { + // IMPL ITEM + let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal)); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Struct) { + // STRUCT ITEM + let (ident, item_, extra_attrs) = try!(self.parse_item_struct()); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.is_union_item() { + // UNION ITEM + self.bump(); + let (ident, item_, extra_attrs) = try!(self.parse_item_union()); + let prev_span = self.prev_span; + let item = self.mk_item(lo, + prev_span.hi, + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility) + } + + /// Parse a foreign item. + fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> { + let attrs = try!(self.parse_outer_attributes()); + let lo = self.span.lo; + let visibility = try!(self.parse_visibility(true)); + + if self.check_keyword(keywords::Static) { + // FOREIGN STATIC ITEM + return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs)))); + } + if self.check_keyword(keywords::Fn) { + // FOREIGN FUNCTION ITEM + return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs)))); + } + + // FIXME #5668: this will occur for a macro invocation: + match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) { + Some(item) => { + return Err(self.span_fatal(item.span, "macros cannot expand to foreign items")); + } + None => Ok(None) + } + } + + /// This is the fall-through for parsing items. + fn parse_macro_use_or_failure( + &mut self, + attrs: Vec<Attribute> , + macros_allowed: bool, + attributes_allowed: bool, + lo: BytePos, + visibility: Visibility + ) -> PResult<'a, Option<P<Item>>> { + if macros_allowed && self.token.is_path_start() { + // MACRO INVOCATION ITEM + + let prev_span = self.prev_span; + self.complain_if_pub_macro(&visibility, prev_span); + + let mac_lo = self.span.lo; + + // item macro. + let pth = try!(self.parse_path(PathStyle::Mod)); + try!(self.expect(&token::Not)); + + // a 'special' identifier (like what `macro_rules!` uses) + // is optional. We should eventually unify invoc syntax + // and remove this. + let id = if self.token.is_ident() { + try!(self.parse_ident()) + } else { + keywords::Invalid.ident() // no special identifier + }; + // eat a matched-delimiter token tree: + let delim = try!(self.expect_open_delim()); + let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim), + SeqSep::none(), + |p| p.parse_token_tree())); + if delim != token::Brace { + if !self.eat(&token::Semi) { + let prev_span = self.prev_span; + self.span_err(prev_span, + "macros that expand to items must either \ + be surrounded with braces or followed by \ + a semicolon"); + } + } + + let hi = self.prev_span.hi; + let mac = spanned(mac_lo, hi, Mac_ { path: pth, tts: tts }); + let item = self.mk_item(lo, hi, id, ItemKind::Mac(mac), visibility, attrs); + return Ok(Some(item)); + } + + // FAILURE TO PARSE ITEM + match visibility { + Visibility::Inherited => {} + _ => { + let prev_span = self.prev_span; + return Err(self.span_fatal(prev_span, "unmatched visibility `pub`")); + } + } + + if !attributes_allowed && !attrs.is_empty() { + self.expected_item_err(&attrs); + } + Ok(None) + } + + pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> { + let attrs = try!(self.parse_outer_attributes()); + self.parse_item_(attrs, true, false) + } + + fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> { + self.parse_unspanned_seq(&token::OpenDelim(token::Brace), + &token::CloseDelim(token::Brace), + SeqSep::trailing_allowed(token::Comma), |this| { + let lo = this.span.lo; + let ident = if this.eat_keyword(keywords::SelfValue) { + keywords::SelfValue.ident() + } else { + try!(this.parse_ident()) + }; + let rename = try!(this.parse_rename()); + let node = ast::PathListItem_ { + name: ident, + rename: rename, + id: ast::DUMMY_NODE_ID + }; + let hi = this.prev_span.hi; + Ok(spanned(lo, hi, node)) + }) + } + + /// `::{` or `::*` + fn is_import_coupler(&mut self) -> bool { + self.check(&token::ModSep) && + self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) || + *t == token::BinOp(token::Star)) + } + + /// Matches ViewPath: + /// MOD_SEP? non_global_path + /// MOD_SEP? non_global_path as IDENT + /// MOD_SEP? non_global_path MOD_SEP STAR + /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE + /// MOD_SEP? LBRACE item_seq RBRACE + fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> { + let lo = self.span.lo; + if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) || + self.is_import_coupler() { + // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`. + self.eat(&token::ModSep); + let prefix = ast::Path { + segments: vec![ast::PathSegment::crate_root()], + span: mk_sp(lo, self.span.hi), + }; + let view_path_kind = if self.eat(&token::BinOp(token::Star)) { + ViewPathGlob(prefix) + } else { + ViewPathList(prefix, try!(self.parse_path_list_items())) + }; + Ok(P(spanned(lo, self.span.hi, view_path_kind))) + } else { + let prefix = try!(self.parse_path(PathStyle::Mod)).default_to_global(); + if self.is_import_coupler() { + // `foo::bar::{a, b}` or `foo::bar::*` + self.bump(); + if self.check(&token::BinOp(token::Star)) { + self.bump(); + Ok(P(spanned(lo, self.span.hi, ViewPathGlob(prefix)))) + } else { + let items = try!(self.parse_path_list_items()); + Ok(P(spanned(lo, self.span.hi, ViewPathList(prefix, items)))) + } + } else { + // `foo::bar` or `foo::bar as baz` + let rename = try!(self.parse_rename()). + unwrap_or(prefix.segments.last().unwrap().identifier); + Ok(P(spanned(lo, self.prev_span.hi, ViewPathSimple(rename, prefix)))) + } + } + } + + fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> { + if self.eat_keyword(keywords::As) { + self.parse_ident().map(Some) + } else { + Ok(None) + } + } + + /// Parses a source module as a crate. This is the main + /// entry point for the parser. + pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> { + let lo = self.span.lo; + Ok(ast::Crate { + attrs: try!(self.parse_inner_attributes()), + module: try!(self.parse_mod_items(&token::Eof, lo)), + span: mk_sp(lo, self.span.lo), + exported_macros: Vec::new(), + }) + } + + pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> { + let ret = match self.token { + token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf), + token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf), + _ => return None + }; + self.bump(); + Some(ret) + } + + pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> { + match self.parse_optional_str() { + Some((s, style, suf)) => { + let sp = self.prev_span; + self.expect_no_suffix(sp, "string literal", suf); + Ok((s, style)) + } + _ => Err(self.fatal("expected string literal")) + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/parse/token.rs b/bash-5.1/vendor/syntex_syntax/src/parse/token.rs new file mode 100644 index 0000000..8ac39dd --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/parse/token.rs @@ -0,0 +1,334 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use self::BinOpToken::*; +pub use self::Nonterminal::*; +pub use self::DelimToken::*; +pub use self::Lit::*; +pub use self::Token::*; + +use ast::{self}; +use ptr::P; +use symbol::keywords; +use tokenstream; + +use std::fmt; +use std::rc::Rc; + +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)] +pub enum BinOpToken { + Plus, + Minus, + Star, + Slash, + Percent, + Caret, + And, + Or, + Shl, + Shr, +} + +/// A delimiter token +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)] +pub enum DelimToken { + /// A round parenthesis: `(` or `)` + Paren, + /// A square bracket: `[` or `]` + Bracket, + /// A curly brace: `{` or `}` + Brace, + /// An empty delimiter + NoDelim, +} + +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)] +pub enum Lit { + Byte(ast::Name), + Char(ast::Name), + Integer(ast::Name), + Float(ast::Name), + Str_(ast::Name), + StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */ + ByteStr(ast::Name), + ByteStrRaw(ast::Name, usize), /* raw byte str delimited by n hash symbols */ +} + +impl Lit { + pub fn short_name(&self) -> &'static str { + match *self { + Byte(_) => "byte", + Char(_) => "char", + Integer(_) => "integer", + Float(_) => "float", + Str_(_) | StrRaw(..) => "string", + ByteStr(_) | ByteStrRaw(..) => "byte string" + } + } +} + +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug)] +pub enum Token { + /* Expression-operator symbols. */ + Eq, + Lt, + Le, + EqEq, + Ne, + Ge, + Gt, + AndAnd, + OrOr, + Not, + Tilde, + BinOp(BinOpToken), + BinOpEq(BinOpToken), + + /* Structural symbols */ + At, + Dot, + DotDot, + DotDotDot, + Comma, + Semi, + Colon, + ModSep, + RArrow, + LArrow, + FatArrow, + Pound, + Dollar, + Question, + /// An opening delimiter, eg. `{` + OpenDelim(DelimToken), + /// A closing delimiter, eg. `}` + CloseDelim(DelimToken), + + /* Literals */ + Literal(Lit, Option<ast::Name>), + + /* Name components */ + Ident(ast::Ident), + Underscore, + Lifetime(ast::Ident), + + /* For interpolation */ + Interpolated(Rc<Nonterminal>), + // Can be expanded into several tokens. + /// Doc comment + DocComment(ast::Name), + // In left-hand-sides of MBE macros: + /// Parse a nonterminal (name to bind, name of NT) + MatchNt(ast::Ident, ast::Ident), + // In right-hand-sides of MBE macros: + /// A syntactic variable that will be filled in by macro expansion. + SubstNt(ast::Ident), + + // Junk. These carry no data because we don't really care about the data + // they *would* carry, and don't really want to allocate a new ident for + // them. Instead, users could extract that from the associated span. + + /// Whitespace + Whitespace, + /// Comment + Comment, + Shebang(ast::Name), + + Eof, +} + +impl Token { + /// Returns `true` if the token starts with '>'. + pub fn is_like_gt(&self) -> bool { + match *self { + BinOp(Shr) | BinOpEq(Shr) | Gt | Ge => true, + _ => false, + } + } + + /// Returns `true` if the token can appear at the start of an expression. + pub fn can_begin_expr(&self) -> bool { + match *self { + OpenDelim(..) => true, + Ident(..) => true, + Literal(..) => true, + Not => true, + BinOp(Minus) => true, + BinOp(Star) => true, + BinOp(And) => true, + BinOp(Or) => true, // in lambda syntax + OrOr => true, // in lambda syntax + AndAnd => true, // double borrow + DotDot | DotDotDot => true, // range notation + Lt | BinOp(Shl) => true, // associated path + ModSep => true, + Pound => true, // for expression attributes + Interpolated(ref nt) => match **nt { + NtExpr(..) => true, + NtIdent(..) => true, + NtBlock(..) => true, + NtPath(..) => true, + _ => false, + }, + _ => false, + } + } + + /// Returns `true` if the token is any literal + pub fn is_lit(&self) -> bool { + match *self { + Literal(..) => true, + _ => false, + } + } + + /// Returns `true` if the token is an identifier. + pub fn is_ident(&self) -> bool { + match *self { + Ident(..) => true, + _ => false, + } + } + + /// Returns `true` if the token is a documentation comment. + pub fn is_doc_comment(&self) -> bool { + match *self { + DocComment(..) => true, + _ => false, + } + } + + /// Returns `true` if the token is interpolated. + pub fn is_interpolated(&self) -> bool { + match *self { + Interpolated(..) => true, + _ => false, + } + } + + /// Returns `true` if the token is an interpolated path. + pub fn is_path(&self) -> bool { + if let Interpolated(ref nt) = *self { + if let NtPath(..) = **nt { + return true; + } + } + false + } + + /// Returns `true` if the token is a lifetime. + pub fn is_lifetime(&self) -> bool { + match *self { + Lifetime(..) => true, + _ => false, + } + } + + /// Returns `true` if the token is either the `mut` or `const` keyword. + pub fn is_mutability(&self) -> bool { + self.is_keyword(keywords::Mut) || + self.is_keyword(keywords::Const) + } + + pub fn is_qpath_start(&self) -> bool { + self == &Lt || self == &BinOp(Shl) + } + + pub fn is_path_start(&self) -> bool { + self == &ModSep || self.is_qpath_start() || self.is_path() || + self.is_path_segment_keyword() || self.is_ident() && !self.is_any_keyword() + } + + /// Returns `true` if the token is a given keyword, `kw`. + pub fn is_keyword(&self, kw: keywords::Keyword) -> bool { + match *self { + Ident(id) => id.name == kw.name(), + _ => false, + } + } + + pub fn is_path_segment_keyword(&self) -> bool { + match *self { + Ident(id) => id.name == keywords::Super.name() || + id.name == keywords::SelfValue.name() || + id.name == keywords::SelfType.name(), + _ => false, + } + } + + /// Returns `true` if the token is either a strict or reserved keyword. + pub fn is_any_keyword(&self) -> bool { + self.is_strict_keyword() || self.is_reserved_keyword() + } + + /// Returns `true` if the token is a strict keyword. + pub fn is_strict_keyword(&self) -> bool { + match *self { + Ident(id) => id.name >= keywords::As.name() && + id.name <= keywords::While.name(), + _ => false, + } + } + + /// Returns `true` if the token is a keyword reserved for possible future use. + pub fn is_reserved_keyword(&self) -> bool { + match *self { + Ident(id) => id.name >= keywords::Abstract.name() && + id.name <= keywords::Yield.name(), + _ => false, + } + } +} + +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)] +/// For interpolation during macro expansion. +pub enum Nonterminal { + NtItem(P<ast::Item>), + NtBlock(P<ast::Block>), + NtStmt(ast::Stmt), + NtPat(P<ast::Pat>), + NtExpr(P<ast::Expr>), + NtTy(P<ast::Ty>), + NtIdent(ast::SpannedIdent), + /// Stuff inside brackets for attributes + NtMeta(ast::MetaItem), + NtPath(ast::Path), + NtTT(tokenstream::TokenTree), + // These are not exposed to macros, but are used by quasiquote. + NtArm(ast::Arm), + NtImplItem(ast::ImplItem), + NtTraitItem(ast::TraitItem), + NtGenerics(ast::Generics), + NtWhereClause(ast::WhereClause), + NtArg(ast::Arg), +} + +impl fmt::Debug for Nonterminal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + NtItem(..) => f.pad("NtItem(..)"), + NtBlock(..) => f.pad("NtBlock(..)"), + NtStmt(..) => f.pad("NtStmt(..)"), + NtPat(..) => f.pad("NtPat(..)"), + NtExpr(..) => f.pad("NtExpr(..)"), + NtTy(..) => f.pad("NtTy(..)"), + NtIdent(..) => f.pad("NtIdent(..)"), + NtMeta(..) => f.pad("NtMeta(..)"), + NtPath(..) => f.pad("NtPath(..)"), + NtTT(..) => f.pad("NtTT(..)"), + NtArm(..) => f.pad("NtArm(..)"), + NtImplItem(..) => f.pad("NtImplItem(..)"), + NtTraitItem(..) => f.pad("NtTraitItem(..)"), + NtGenerics(..) => f.pad("NtGenerics(..)"), + NtWhereClause(..) => f.pad("NtWhereClause(..)"), + NtArg(..) => f.pad("NtArg(..)"), + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/print/pp.rs b/bash-5.1/vendor/syntex_syntax/src/print/pp.rs new file mode 100644 index 0000000..3f3f093 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/print/pp.rs @@ -0,0 +1,640 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! This pretty-printer is a direct reimplementation of Philip Karlton's +//! Mesa pretty-printer, as described in appendix A of +//! +//! ````ignore +//! STAN-CS-79-770: "Pretty Printing", by Derek C. Oppen. +//! Stanford Department of Computer Science, 1979. +//! ```` +//! +//! The algorithm's aim is to break a stream into as few lines as possible +//! while respecting the indentation-consistency requirements of the enclosing +//! block, and avoiding breaking at silly places on block boundaries, for +//! example, between "x" and ")" in "x)". +//! +//! I am implementing this algorithm because it comes with 20 pages of +//! documentation explaining its theory, and because it addresses the set of +//! concerns I've seen other pretty-printers fall down on. Weirdly. Even though +//! it's 32 years old. What can I say? +//! +//! Despite some redundancies and quirks in the way it's implemented in that +//! paper, I've opted to keep the implementation here as similar as I can, +//! changing only what was blatantly wrong, a typo, or sufficiently +//! non-idiomatic rust that it really stuck out. +//! +//! In particular you'll see a certain amount of churn related to INTEGER vs. +//! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two +//! somewhat readily? In any case, I've used usize for indices-in-buffers and +//! ints for character-sizes-and-indentation-offsets. This respects the need +//! for ints to "go negative" while carrying a pending-calculation balance, and +//! helps differentiate all the numbers flying around internally (slightly). +//! +//! I also inverted the indentation arithmetic used in the print stack, since +//! the Mesa implementation (somewhat randomly) stores the offset on the print +//! stack in terms of margin-col rather than col itself. I store col. +//! +//! I also implemented a small change in the String token, in that I store an +//! explicit length for the string. For most tokens this is just the length of +//! the accompanying string. But it's necessary to permit it to differ, for +//! encoding things that are supposed to "go on their own line" -- certain +//! classes of comment and blank-line -- where relying on adjacent +//! hardbreak-like Break tokens with long blankness indication doesn't actually +//! work. To see why, consider when there is a "thing that should be on its own +//! line" between two long blocks, say functions. If you put a hardbreak after +//! each function (or before each) and the breaking algorithm decides to break +//! there anyways (because the functions themselves are long) you wind up with +//! extra blank lines. If you don't put hardbreaks you can wind up with the +//! "thing which should be on its own line" not getting its own line in the +//! rare case of "really small functions" or such. This re-occurs with comments +//! and explicit blank lines. So in those cases we use a string with a payload +//! we want isolated to a line and an explicit length that's huge, surrounded +//! by two zero-length breaks. The algorithm will try its best to fit it on a +//! line (which it can't) and so naturally place the content on its own line to +//! avoid combining it with other lines and making matters even worse. + +use std::collections::VecDeque; +use std::fmt; +use std::io; + +#[derive(Clone, Copy, PartialEq)] +pub enum Breaks { + Consistent, + Inconsistent, +} + +#[derive(Clone, Copy)] +pub struct BreakToken { + offset: isize, + blank_space: isize +} + +#[derive(Clone, Copy)] +pub struct BeginToken { + offset: isize, + breaks: Breaks +} + +#[derive(Clone)] +pub enum Token { + String(String, isize), + Break(BreakToken), + Begin(BeginToken), + End, + Eof, +} + +impl Token { + pub fn is_eof(&self) -> bool { + match *self { + Token::Eof => true, + _ => false, + } + } + + pub fn is_hardbreak_tok(&self) -> bool { + match *self { + Token::Break(BreakToken { + offset: 0, + blank_space: bs + }) if bs == SIZE_INFINITY => + true, + _ => + false + } + } +} + +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Token::String(ref s, len) => write!(f, "STR({},{})", s, len), + Token::Break(_) => f.write_str("BREAK"), + Token::Begin(_) => f.write_str("BEGIN"), + Token::End => f.write_str("END"), + Token::Eof => f.write_str("EOF"), + } + } +} + +fn buf_str(buf: &[BufEntry], left: usize, right: usize, lim: usize) -> String { + let n = buf.len(); + let mut i = left; + let mut l = lim; + let mut s = String::from("["); + while i != right && l != 0 { + l -= 1; + if i != left { + s.push_str(", "); + } + s.push_str(&format!("{}={}", buf[i].size, &buf[i].token)); + i += 1; + i %= n; + } + s.push(']'); + s +} + +#[derive(Copy, Clone)] +pub enum PrintStackBreak { + Fits, + Broken(Breaks), +} + +#[derive(Copy, Clone)] +pub struct PrintStackElem { + offset: isize, + pbreak: PrintStackBreak +} + +const SIZE_INFINITY: isize = 0xffff; + +pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> { + // Yes 55, it makes the ring buffers big enough to never fall behind. + let n: usize = 55 * linewidth; + debug!("mk_printer {}", linewidth); + Printer { + out: out, + buf_len: n, + margin: linewidth as isize, + space: linewidth as isize, + left: 0, + right: 0, + buf: vec![BufEntry { token: Token::Eof, size: 0 }; n], + left_total: 0, + right_total: 0, + scan_stack: VecDeque::new(), + print_stack: Vec::new(), + pending_indentation: 0 + } +} + + +/// In case you do not have the paper, here is an explanation of what's going +/// on. +/// +/// There is a stream of input tokens flowing through this printer. +/// +/// The printer buffers up to 3N tokens inside itself, where N is linewidth. +/// Yes, linewidth is chars and tokens are multi-char, but in the worst +/// case every token worth buffering is 1 char long, so it's ok. +/// +/// Tokens are String, Break, and Begin/End to delimit blocks. +/// +/// Begin tokens can carry an offset, saying "how far to indent when you break +/// inside here", as well as a flag indicating "consistent" or "inconsistent" +/// breaking. Consistent breaking means that after the first break, no attempt +/// will be made to flow subsequent breaks together onto lines. Inconsistent +/// is the opposite. Inconsistent breaking example would be, say: +/// +/// foo(hello, there, good, friends) +/// +/// breaking inconsistently to become +/// +/// foo(hello, there +/// good, friends); +/// +/// whereas a consistent breaking would yield: +/// +/// foo(hello, +/// there +/// good, +/// friends); +/// +/// That is, in the consistent-break blocks we value vertical alignment +/// more than the ability to cram stuff onto a line. But in all cases if it +/// can make a block a one-liner, it'll do so. +/// +/// Carrying on with high-level logic: +/// +/// The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and +/// 'right' indices denote the active portion of the ring buffer as well as +/// describing hypothetical points-in-the-infinite-stream at most 3N tokens +/// apart (i.e. "not wrapped to ring-buffer boundaries"). The paper will switch +/// between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer +/// and point-in-infinite-stream senses freely. +/// +/// There is a parallel ring buffer, 'size', that holds the calculated size of +/// each token. Why calculated? Because for Begin/End pairs, the "size" +/// includes everything between the pair. That is, the "size" of Begin is +/// actually the sum of the sizes of everything between Begin and the paired +/// End that follows. Since that is arbitrarily far in the future, 'size' is +/// being rewritten regularly while the printer runs; in fact most of the +/// machinery is here to work out 'size' entries on the fly (and give up when +/// they're so obviously over-long that "infinity" is a good enough +/// approximation for purposes of line breaking). +/// +/// The "input side" of the printer is managed as an abstract process called +/// SCAN, which uses 'scan_stack', to manage calculating 'size'. SCAN is, in +/// other words, the process of calculating 'size' entries. +/// +/// The "output side" of the printer is managed by an abstract process called +/// PRINT, which uses 'print_stack', 'margin' and 'space' to figure out what to +/// do with each token/size pair it consumes as it goes. It's trying to consume +/// the entire buffered window, but can't output anything until the size is >= +/// 0 (sizes are set to negative while they're pending calculation). +/// +/// So SCAN takes input and buffers tokens and pending calculations, while +/// PRINT gobbles up completed calculations and tokens from the buffer. The +/// theory is that the two can never get more than 3N tokens apart, because +/// once there's "obviously" too much data to fit on a line, in a size +/// calculation, SCAN will write "infinity" to the size and let PRINT consume +/// it. +/// +/// In this implementation (following the paper, again) the SCAN process is +/// the method called 'pretty_print', and the 'PRINT' process is the method +/// called 'print'. +pub struct Printer<'a> { + pub out: Box<io::Write+'a>, + buf_len: usize, + /// Width of lines we're constrained to + margin: isize, + /// Number of spaces left on line + space: isize, + /// Index of left side of input stream + left: usize, + /// Index of right side of input stream + right: usize, + /// Ring-buffer of tokens and calculated sizes + buf: Vec<BufEntry>, + /// Running size of stream "...left" + left_total: isize, + /// Running size of stream "...right" + right_total: isize, + /// Pseudo-stack, really a ring too. Holds the + /// primary-ring-buffers index of the Begin that started the + /// current block, possibly with the most recent Break after that + /// Begin (if there is any) on top of it. Stuff is flushed off the + /// bottom as it becomes irrelevant due to the primary ring-buffer + /// advancing. + scan_stack: VecDeque<usize>, + /// Stack of blocks-in-progress being flushed by print + print_stack: Vec<PrintStackElem> , + /// Buffered indentation to avoid writing trailing whitespace + pending_indentation: isize, +} + +#[derive(Clone)] +struct BufEntry { + token: Token, + size: isize, +} + +impl<'a> Printer<'a> { + pub fn last_token(&mut self) -> Token { + self.buf[self.right].token.clone() + } + // be very careful with this! + pub fn replace_last_token(&mut self, t: Token) { + self.buf[self.right].token = t; + } + pub fn pretty_print(&mut self, token: Token) -> io::Result<()> { + debug!("pp Vec<{},{}>", self.left, self.right); + match token { + Token::Eof => { + if !self.scan_stack.is_empty() { + self.check_stack(0); + try!(self.advance_left()); + } + self.indent(0); + Ok(()) + } + Token::Begin(b) => { + if self.scan_stack.is_empty() { + self.left_total = 1; + self.right_total = 1; + self.left = 0; + self.right = 0; + } else { self.advance_right(); } + debug!("pp Begin({})/buffer Vec<{},{}>", + b.offset, self.left, self.right); + self.buf[self.right] = BufEntry { token: token, size: -self.right_total }; + let right = self.right; + self.scan_push(right); + Ok(()) + } + Token::End => { + if self.scan_stack.is_empty() { + debug!("pp End/print Vec<{},{}>", self.left, self.right); + self.print(token, 0) + } else { + debug!("pp End/buffer Vec<{},{}>", self.left, self.right); + self.advance_right(); + self.buf[self.right] = BufEntry { token: token, size: -1 }; + let right = self.right; + self.scan_push(right); + Ok(()) + } + } + Token::Break(b) => { + if self.scan_stack.is_empty() { + self.left_total = 1; + self.right_total = 1; + self.left = 0; + self.right = 0; + } else { self.advance_right(); } + debug!("pp Break({})/buffer Vec<{},{}>", + b.offset, self.left, self.right); + self.check_stack(0); + let right = self.right; + self.scan_push(right); + self.buf[self.right] = BufEntry { token: token, size: -self.right_total }; + self.right_total += b.blank_space; + Ok(()) + } + Token::String(s, len) => { + if self.scan_stack.is_empty() { + debug!("pp String('{}')/print Vec<{},{}>", + s, self.left, self.right); + self.print(Token::String(s, len), len) + } else { + debug!("pp String('{}')/buffer Vec<{},{}>", + s, self.left, self.right); + self.advance_right(); + self.buf[self.right] = BufEntry { token: Token::String(s, len), size: len }; + self.right_total += len; + self.check_stream() + } + } + } + } + pub fn check_stream(&mut self) -> io::Result<()> { + debug!("check_stream Vec<{}, {}> with left_total={}, right_total={}", + self.left, self.right, self.left_total, self.right_total); + if self.right_total - self.left_total > self.space { + debug!("scan window is {}, longer than space on line ({})", + self.right_total - self.left_total, self.space); + if Some(&self.left) == self.scan_stack.back() { + debug!("setting {} to infinity and popping", self.left); + let scanned = self.scan_pop_bottom(); + self.buf[scanned].size = SIZE_INFINITY; + } + try!(self.advance_left()); + if self.left != self.right { + try!(self.check_stream()); + } + } + Ok(()) + } + pub fn scan_push(&mut self, x: usize) { + debug!("scan_push {}", x); + self.scan_stack.push_front(x); + } + pub fn scan_pop(&mut self) -> usize { + self.scan_stack.pop_front().unwrap() + } + pub fn scan_top(&mut self) -> usize { + *self.scan_stack.front().unwrap() + } + pub fn scan_pop_bottom(&mut self) -> usize { + self.scan_stack.pop_back().unwrap() + } + pub fn advance_right(&mut self) { + self.right += 1; + self.right %= self.buf_len; + assert!(self.right != self.left); + } + pub fn advance_left(&mut self) -> io::Result<()> { + debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right, + self.left, self.buf[self.left].size); + + let mut left_size = self.buf[self.left].size; + + while left_size >= 0 { + let left = self.buf[self.left].token.clone(); + + let len = match left { + Token::Break(b) => b.blank_space, + Token::String(_, len) => { + assert_eq!(len, left_size); + len + } + _ => 0 + }; + + try!(self.print(left, left_size)); + + self.left_total += len; + + if self.left == self.right { + break; + } + + self.left += 1; + self.left %= self.buf_len; + + left_size = self.buf[self.left].size; + } + + Ok(()) + } + pub fn check_stack(&mut self, k: isize) { + if !self.scan_stack.is_empty() { + let x = self.scan_top(); + match self.buf[x].token { + Token::Begin(_) => { + if k > 0 { + let popped = self.scan_pop(); + self.buf[popped].size = self.buf[x].size + self.right_total; + self.check_stack(k - 1); + } + } + Token::End => { + // paper says + not =, but that makes no sense. + let popped = self.scan_pop(); + self.buf[popped].size = 1; + self.check_stack(k + 1); + } + _ => { + let popped = self.scan_pop(); + self.buf[popped].size = self.buf[x].size + self.right_total; + if k > 0 { + self.check_stack(k); + } + } + } + } + } + pub fn print_newline(&mut self, amount: isize) -> io::Result<()> { + debug!("NEWLINE {}", amount); + let ret = write!(self.out, "\n"); + self.pending_indentation = 0; + self.indent(amount); + ret + } + pub fn indent(&mut self, amount: isize) { + debug!("INDENT {}", amount); + self.pending_indentation += amount; + } + pub fn get_top(&mut self) -> PrintStackElem { + match self.print_stack.last() { + Some(el) => *el, + None => PrintStackElem { + offset: 0, + pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) + } + } + } + pub fn print_str(&mut self, s: &str) -> io::Result<()> { + while self.pending_indentation > 0 { + try!(write!(self.out, " ")); + self.pending_indentation -= 1; + } + write!(self.out, "{}", s) + } + pub fn print(&mut self, token: Token, l: isize) -> io::Result<()> { + debug!("print {} {} (remaining line space={})", token, l, + self.space); + debug!("{}", buf_str(&self.buf, + self.left, + self.right, + 6)); + match token { + Token::Begin(b) => { + if l > self.space { + let col = self.margin - self.space + b.offset; + debug!("print Begin -> push broken block at col {}", col); + self.print_stack.push(PrintStackElem { + offset: col, + pbreak: PrintStackBreak::Broken(b.breaks) + }); + } else { + debug!("print Begin -> push fitting block"); + self.print_stack.push(PrintStackElem { + offset: 0, + pbreak: PrintStackBreak::Fits + }); + } + Ok(()) + } + Token::End => { + debug!("print End -> pop End"); + let print_stack = &mut self.print_stack; + assert!(!print_stack.is_empty()); + print_stack.pop().unwrap(); + Ok(()) + } + Token::Break(b) => { + let top = self.get_top(); + match top.pbreak { + PrintStackBreak::Fits => { + debug!("print Break({}) in fitting block", b.blank_space); + self.space -= b.blank_space; + self.indent(b.blank_space); + Ok(()) + } + PrintStackBreak::Broken(Breaks::Consistent) => { + debug!("print Break({}+{}) in consistent block", + top.offset, b.offset); + let ret = self.print_newline(top.offset + b.offset); + self.space = self.margin - (top.offset + b.offset); + ret + } + PrintStackBreak::Broken(Breaks::Inconsistent) => { + if l > self.space { + debug!("print Break({}+{}) w/ newline in inconsistent", + top.offset, b.offset); + let ret = self.print_newline(top.offset + b.offset); + self.space = self.margin - (top.offset + b.offset); + ret + } else { + debug!("print Break({}) w/o newline in inconsistent", + b.blank_space); + self.indent(b.blank_space); + self.space -= b.blank_space; + Ok(()) + } + } + } + } + Token::String(ref s, len) => { + debug!("print String({})", s); + assert_eq!(l, len); + // assert!(l <= space); + self.space -= len; + self.print_str(s) + } + Token::Eof => { + // Eof should never get here. + panic!(); + } + } + } +} + +// Convenience functions to talk to the printer. +// +// "raw box" +pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::Result<()> { + p.pretty_print(Token::Begin(BeginToken { + offset: indent as isize, + breaks: b + })) +} + +pub fn ibox(p: &mut Printer, indent: usize) -> io::Result<()> { + rbox(p, indent, Breaks::Inconsistent) +} + +pub fn cbox(p: &mut Printer, indent: usize) -> io::Result<()> { + rbox(p, indent, Breaks::Consistent) +} + +pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::Result<()> { + p.pretty_print(Token::Break(BreakToken { + offset: off, + blank_space: n as isize + })) +} + +pub fn end(p: &mut Printer) -> io::Result<()> { + p.pretty_print(Token::End) +} + +pub fn eof(p: &mut Printer) -> io::Result<()> { + p.pretty_print(Token::Eof) +} + +pub fn word(p: &mut Printer, wrd: &str) -> io::Result<()> { + p.pretty_print(Token::String(wrd.to_string(), wrd.len() as isize)) +} + +pub fn huge_word(p: &mut Printer, wrd: &str) -> io::Result<()> { + p.pretty_print(Token::String(wrd.to_string(), SIZE_INFINITY)) +} + +pub fn zero_word(p: &mut Printer, wrd: &str) -> io::Result<()> { + p.pretty_print(Token::String(wrd.to_string(), 0)) +} + +pub fn spaces(p: &mut Printer, n: usize) -> io::Result<()> { + break_offset(p, n, 0) +} + +pub fn zerobreak(p: &mut Printer) -> io::Result<()> { + spaces(p, 0) +} + +pub fn space(p: &mut Printer) -> io::Result<()> { + spaces(p, 1) +} + +pub fn hardbreak(p: &mut Printer) -> io::Result<()> { + spaces(p, SIZE_INFINITY as usize) +} + +pub fn hardbreak_tok_offset(off: isize) -> Token { + Token::Break(BreakToken {offset: off, blank_space: SIZE_INFINITY}) +} + +pub fn hardbreak_tok() -> Token { + hardbreak_tok_offset(0) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/print/pprust.rs b/bash-5.1/vendor/syntex_syntax/src/print/pprust.rs new file mode 100644 index 0000000..7e74b70 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/print/pprust.rs @@ -0,0 +1,3126 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use self::AnnNode::*; + +use abi::{self, Abi}; +use ast::{self, BlockCheckMode, PatKind}; +use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; +use ast::Attribute; +use util::parser::AssocOp; +use attr; +use codemap::{self, CodeMap}; +use syntax_pos::{self, BytePos}; +use errors; +use parse::token::{self, BinOpToken, Token}; +use parse::lexer::comments; +use parse; +use print::pp::{self, break_offset, word, space, zerobreak, hardbreak}; +use print::pp::{Breaks, eof}; +use print::pp::Breaks::{Consistent, Inconsistent}; +use ptr::P; +use std_inject; +use symbol::{Symbol, keywords}; +use tokenstream::{self, TokenTree}; + +use std::ascii; +use std::io::{self, Write, Read}; +use std::iter; + +pub enum AnnNode<'a> { + NodeIdent(&'a ast::Ident), + NodeName(&'a ast::Name), + NodeBlock(&'a ast::Block), + NodeItem(&'a ast::Item), + NodeSubItem(ast::NodeId), + NodeExpr(&'a ast::Expr), + NodePat(&'a ast::Pat), +} + +pub trait PpAnn { + fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) } + fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) } +} + +#[derive(Copy, Clone)] +pub struct NoAnn; + +impl PpAnn for NoAnn {} + +#[derive(Copy, Clone)] +pub struct CurrentCommentAndLiteral { + pub cur_cmnt: usize, + pub cur_lit: usize, +} + +pub struct State<'a> { + pub s: pp::Printer<'a>, + cm: Option<&'a CodeMap>, + comments: Option<Vec<comments::Comment> >, + literals: Option<Vec<comments::Literal> >, + cur_cmnt_and_lit: CurrentCommentAndLiteral, + boxes: Vec<pp::Breaks>, + ann: &'a (PpAnn+'a), +} + +pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> { + static NO_ANN: NoAnn = NoAnn; + rust_printer_annotated(writer, &NO_ANN) +} + +pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>, + ann: &'a PpAnn) -> State<'a> { + State { + s: pp::mk_printer(writer, DEFAULT_COLUMNS), + cm: None, + comments: None, + literals: None, + cur_cmnt_and_lit: CurrentCommentAndLiteral { + cur_cmnt: 0, + cur_lit: 0 + }, + boxes: Vec::new(), + ann: ann, + } +} + +pub const INDENT_UNIT: usize = 4; + +pub const DEFAULT_COLUMNS: usize = 78; + +/// Requires you to pass an input filename and reader so that +/// it can scan the input text for comments and literals to +/// copy forward. +pub fn print_crate<'a>(cm: &'a CodeMap, + span_diagnostic: &errors::Handler, + krate: &ast::Crate, + filename: String, + input: &mut Read, + out: Box<Write+'a>, + ann: &'a PpAnn, + is_expanded: bool) -> io::Result<()> { + let mut s = State::new_from_input(cm, + span_diagnostic, + filename, + input, + out, + ann, + is_expanded); + if is_expanded && !std_inject::injected_crate_name(krate).is_none() { + // We need to print `#![no_std]` (and its feature gate) so that + // compiling pretty-printed source won't inject libstd again. + // However we don't want these attributes in the AST because + // of the feature gate, so we fake them up here. + + // #![feature(prelude_import)] + let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import")); + let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]); + let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list); + try!(s.print_attribute(&fake_attr)); + + // #![no_std] + let no_std_meta = attr::mk_word_item(Symbol::intern("no_std")); + let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta); + try!(s.print_attribute(&fake_attr)); + } + + try!(s.print_mod(&krate.module, &krate.attrs)); + try!(s.print_remaining_comments()); + eof(&mut s.s) +} + +impl<'a> State<'a> { + pub fn new_from_input(cm: &'a CodeMap, + span_diagnostic: &errors::Handler, + filename: String, + input: &mut Read, + out: Box<Write+'a>, + ann: &'a PpAnn, + is_expanded: bool) -> State<'a> { + let (cmnts, lits) = comments::gather_comments_and_literals( + span_diagnostic, + filename, + input); + + State::new( + cm, + out, + ann, + Some(cmnts), + // If the code is post expansion, don't use the table of + // literals, since it doesn't correspond with the literals + // in the AST anymore. + if is_expanded { None } else { Some(lits) }) + } + + pub fn new(cm: &'a CodeMap, + out: Box<Write+'a>, + ann: &'a PpAnn, + comments: Option<Vec<comments::Comment>>, + literals: Option<Vec<comments::Literal>>) -> State<'a> { + State { + s: pp::mk_printer(out, DEFAULT_COLUMNS), + cm: Some(cm), + comments: comments, + literals: literals, + cur_cmnt_and_lit: CurrentCommentAndLiteral { + cur_cmnt: 0, + cur_lit: 0 + }, + boxes: Vec::new(), + ann: ann, + } + } +} + +pub fn to_string<F>(f: F) -> String where + F: FnOnce(&mut State) -> io::Result<()>, +{ + let mut wr = Vec::new(); + { + let mut printer = rust_printer(Box::new(&mut wr)); + f(&mut printer).unwrap(); + eof(&mut printer.s).unwrap(); + } + String::from_utf8(wr).unwrap() +} + +pub fn binop_to_string(op: BinOpToken) -> &'static str { + match op { + token::Plus => "+", + token::Minus => "-", + token::Star => "*", + token::Slash => "/", + token::Percent => "%", + token::Caret => "^", + token::And => "&", + token::Or => "|", + token::Shl => "<<", + token::Shr => ">>", + } +} + +pub fn token_to_string(tok: &Token) -> String { + match *tok { + token::Eq => "=".to_string(), + token::Lt => "<".to_string(), + token::Le => "<=".to_string(), + token::EqEq => "==".to_string(), + token::Ne => "!=".to_string(), + token::Ge => ">=".to_string(), + token::Gt => ">".to_string(), + token::Not => "!".to_string(), + token::Tilde => "~".to_string(), + token::OrOr => "||".to_string(), + token::AndAnd => "&&".to_string(), + token::BinOp(op) => binop_to_string(op).to_string(), + token::BinOpEq(op) => format!("{}=", binop_to_string(op)), + + /* Structural symbols */ + token::At => "@".to_string(), + token::Dot => ".".to_string(), + token::DotDot => "..".to_string(), + token::DotDotDot => "...".to_string(), + token::Comma => ",".to_string(), + token::Semi => ";".to_string(), + token::Colon => ":".to_string(), + token::ModSep => "::".to_string(), + token::RArrow => "->".to_string(), + token::LArrow => "<-".to_string(), + token::FatArrow => "=>".to_string(), + token::OpenDelim(token::Paren) => "(".to_string(), + token::CloseDelim(token::Paren) => ")".to_string(), + token::OpenDelim(token::Bracket) => "[".to_string(), + token::CloseDelim(token::Bracket) => "]".to_string(), + token::OpenDelim(token::Brace) => "{".to_string(), + token::CloseDelim(token::Brace) => "}".to_string(), + token::OpenDelim(token::NoDelim) => " ".to_string(), + token::CloseDelim(token::NoDelim) => " ".to_string(), + token::Pound => "#".to_string(), + token::Dollar => "$".to_string(), + token::Question => "?".to_string(), + + /* Literals */ + token::Literal(lit, suf) => { + let mut out = match lit { + token::Byte(b) => format!("b'{}'", b), + token::Char(c) => format!("'{}'", c), + token::Float(c) => c.to_string(), + token::Integer(c) => c.to_string(), + token::Str_(s) => format!("\"{}\"", s), + token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}", + delim=repeat("#", n), + string=s), + token::ByteStr(v) => format!("b\"{}\"", v), + token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}", + delim=repeat("#", n), + string=s), + }; + + if let Some(s) = suf { + out.push_str(&s.as_str()) + } + + out + } + + /* Name components */ + token::Ident(s) => s.to_string(), + token::Lifetime(s) => s.to_string(), + token::Underscore => "_".to_string(), + + /* Other */ + token::DocComment(s) => s.to_string(), + token::SubstNt(s) => format!("${}", s), + token::MatchNt(s, t) => format!("${}:{}", s, t), + token::Eof => "<eof>".to_string(), + token::Whitespace => " ".to_string(), + token::Comment => "/* */".to_string(), + token::Shebang(s) => format!("/* shebang: {}*/", s), + + token::Interpolated(ref nt) => match **nt { + token::NtExpr(ref e) => expr_to_string(&e), + token::NtMeta(ref e) => meta_item_to_string(&e), + token::NtTy(ref e) => ty_to_string(&e), + token::NtPath(ref e) => path_to_string(&e), + token::NtItem(ref e) => item_to_string(&e), + token::NtBlock(ref e) => block_to_string(&e), + token::NtStmt(ref e) => stmt_to_string(&e), + token::NtPat(ref e) => pat_to_string(&e), + token::NtIdent(ref e) => ident_to_string(e.node), + token::NtTT(ref e) => tt_to_string(&e), + token::NtArm(ref e) => arm_to_string(&e), + token::NtImplItem(ref e) => impl_item_to_string(&e), + token::NtTraitItem(ref e) => trait_item_to_string(&e), + token::NtGenerics(ref e) => generics_to_string(&e), + token::NtWhereClause(ref e) => where_clause_to_string(&e), + token::NtArg(ref e) => arg_to_string(&e), + } + } +} + +pub fn ty_to_string(ty: &ast::Ty) -> String { + to_string(|s| s.print_type(ty)) +} + +pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String { + to_string(|s| s.print_bounds("", bounds)) +} + +pub fn pat_to_string(pat: &ast::Pat) -> String { + to_string(|s| s.print_pat(pat)) +} + +pub fn arm_to_string(arm: &ast::Arm) -> String { + to_string(|s| s.print_arm(arm)) +} + +pub fn expr_to_string(e: &ast::Expr) -> String { + to_string(|s| s.print_expr(e)) +} + +pub fn lifetime_to_string(e: &ast::Lifetime) -> String { + to_string(|s| s.print_lifetime(e)) +} + +pub fn tt_to_string(tt: &tokenstream::TokenTree) -> String { + to_string(|s| s.print_tt(tt)) +} + +pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String { + to_string(|s| s.print_tts(tts)) +} + +pub fn stmt_to_string(stmt: &ast::Stmt) -> String { + to_string(|s| s.print_stmt(stmt)) +} + +pub fn attr_to_string(attr: &ast::Attribute) -> String { + to_string(|s| s.print_attribute(attr)) +} + +pub fn item_to_string(i: &ast::Item) -> String { + to_string(|s| s.print_item(i)) +} + +pub fn impl_item_to_string(i: &ast::ImplItem) -> String { + to_string(|s| s.print_impl_item(i)) +} + +pub fn trait_item_to_string(i: &ast::TraitItem) -> String { + to_string(|s| s.print_trait_item(i)) +} + +pub fn generics_to_string(generics: &ast::Generics) -> String { + to_string(|s| s.print_generics(generics)) +} + +pub fn where_clause_to_string(i: &ast::WhereClause) -> String { + to_string(|s| s.print_where_clause(i)) +} + +pub fn fn_block_to_string(p: &ast::FnDecl) -> String { + to_string(|s| s.print_fn_block_args(p)) +} + +pub fn path_to_string(p: &ast::Path) -> String { + to_string(|s| s.print_path(p, false, 0, false)) +} + +pub fn ident_to_string(id: ast::Ident) -> String { + to_string(|s| s.print_ident(id)) +} + +pub fn fun_to_string(decl: &ast::FnDecl, + unsafety: ast::Unsafety, + constness: ast::Constness, + name: ast::Ident, + generics: &ast::Generics) + -> String { + to_string(|s| { + try!(s.head("")); + try!(s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name), + generics, &ast::Visibility::Inherited)); + try!(s.end()); // Close the head box + s.end() // Close the outer box + }) +} + +pub fn block_to_string(blk: &ast::Block) -> String { + to_string(|s| { + // containing cbox, will be closed by print-block at } + try!(s.cbox(INDENT_UNIT)); + // head-ibox, will be closed by print-block after { + try!(s.ibox(0)); + s.print_block(blk) + }) +} + +pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String { + to_string(|s| s.print_meta_list_item(li)) +} + +pub fn meta_item_to_string(mi: &ast::MetaItem) -> String { + to_string(|s| s.print_meta_item(mi)) +} + +pub fn attribute_to_string(attr: &ast::Attribute) -> String { + to_string(|s| s.print_attribute(attr)) +} + +pub fn lit_to_string(l: &ast::Lit) -> String { + to_string(|s| s.print_literal(l)) +} + +pub fn variant_to_string(var: &ast::Variant) -> String { + to_string(|s| s.print_variant(var)) +} + +pub fn arg_to_string(arg: &ast::Arg) -> String { + to_string(|s| s.print_arg(arg, false)) +} + +pub fn mac_to_string(arg: &ast::Mac) -> String { + to_string(|s| s.print_mac(arg, ::parse::token::Paren)) +} + +pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String { + match *vis { + ast::Visibility::Public => format!("pub {}", s), + ast::Visibility::Crate(_) => format!("pub(crate) {}", s), + ast::Visibility::Restricted { ref path, .. } => + format!("pub({}) {}", to_string(|s| s.print_path(path, false, 0, true)), s), + ast::Visibility::Inherited => s.to_string() + } +} + +fn needs_parentheses(expr: &ast::Expr) -> bool { + match expr.node { + ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) | + ast::ExprKind::Closure(..) | + ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) | + ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true, + _ => false, + } +} + +pub trait PrintState<'a> { + fn writer(&mut self) -> &mut pp::Printer<'a>; + fn boxes(&mut self) -> &mut Vec<pp::Breaks>; + fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>; + fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral; + fn literals(&self) -> &Option<Vec<comments::Literal>>; + + fn word_space(&mut self, w: &str) -> io::Result<()> { + try!(word(self.writer(), w)); + space(self.writer()) + } + + fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") } + + fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") } + + fn is_begin(&mut self) -> bool { + match self.writer().last_token() { + pp::Token::Begin(_) => true, + _ => false, + } + } + + fn is_end(&mut self) -> bool { + match self.writer().last_token() { + pp::Token::End => true, + _ => false, + } + } + + // is this the beginning of a line? + fn is_bol(&mut self) -> bool { + self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok() + } + + fn hardbreak_if_not_bol(&mut self) -> io::Result<()> { + if !self.is_bol() { + try!(hardbreak(self.writer())) + } + Ok(()) + } + + // "raw box" + fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> { + self.boxes().push(b); + pp::rbox(self.writer(), u, b) + } + + fn ibox(&mut self, u: usize) -> io::Result<()> { + self.boxes().push(pp::Breaks::Inconsistent); + pp::ibox(self.writer(), u) + } + + fn end(&mut self) -> io::Result<()> { + self.boxes().pop().unwrap(); + pp::end(self.writer()) + } + + fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> + where F: FnMut(&mut Self, &T) -> io::Result<()>, + { + try!(self.rbox(0, b)); + let mut first = true; + for elt in elts { + if first { first = false; } else { try!(self.word_space(",")); } + try!(op(self, elt)); + } + self.end() + } + + fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> { + let mut cur_lit = self.cur_cmnt_and_lit().cur_lit; + + let mut result = None; + + if let &Some(ref lits) = self.literals() + { + while cur_lit < lits.len() { + let ltrl = (*lits)[cur_lit].clone(); + if ltrl.pos > pos { break; } + cur_lit += 1; + if ltrl.pos == pos { + result = Some(ltrl); + break; + } + } + } + + self.cur_cmnt_and_lit().cur_lit = cur_lit; + result + } + + fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> { + while let Some(ref cmnt) = self.next_comment() { + if cmnt.pos < pos { + try!(self.print_comment(cmnt)); + self.cur_cmnt_and_lit().cur_cmnt += 1; + } else { + break + } + } + Ok(()) + } + + fn print_comment(&mut self, + cmnt: &comments::Comment) -> io::Result<()> { + match cmnt.style { + comments::Mixed => { + assert_eq!(cmnt.lines.len(), 1); + try!(zerobreak(self.writer())); + try!(word(self.writer(), &cmnt.lines[0])); + zerobreak(self.writer()) + } + comments::Isolated => { + try!(self.hardbreak_if_not_bol()); + for line in &cmnt.lines { + // Don't print empty lines because they will end up as trailing + // whitespace + if !line.is_empty() { + try!(word(self.writer(), &line[..])); + } + try!(hardbreak(self.writer())); + } + Ok(()) + } + comments::Trailing => { + if !self.is_bol() { + try!(word(self.writer(), " ")); + } + if cmnt.lines.len() == 1 { + try!(word(self.writer(), &cmnt.lines[0])); + hardbreak(self.writer()) + } else { + try!(self.ibox(0)); + for line in &cmnt.lines { + if !line.is_empty() { + try!(word(self.writer(), &line[..])); + } + try!(hardbreak(self.writer())); + } + self.end() + } + } + comments::BlankLine => { + // We need to do at least one, possibly two hardbreaks. + let is_semi = match self.writer().last_token() { + pp::Token::String(s, _) => ";" == s, + _ => false + }; + if is_semi || self.is_begin() || self.is_end() { + try!(hardbreak(self.writer())); + } + hardbreak(self.writer()) + } + } + } + + fn next_comment(&mut self) -> Option<comments::Comment> { + let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt; + match *self.comments() { + Some(ref cmnts) => { + if cur_cmnt < cmnts.len() { + Some(cmnts[cur_cmnt].clone()) + } else { + None + } + } + _ => None + } + } + + fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> { + try!(self.maybe_print_comment(lit.span.lo)); + match self.next_lit(lit.span.lo) { + Some(ref ltrl) => { + return word(self.writer(), &(*ltrl).lit); + } + _ => () + } + match lit.node { + ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style), + ast::LitKind::Byte(byte) => { + let mut res = String::from("b'"); + res.extend(ascii::escape_default(byte).map(|c| c as char)); + res.push('\''); + word(self.writer(), &res[..]) + } + ast::LitKind::Char(ch) => { + let mut res = String::from("'"); + res.extend(ch.escape_default()); + res.push('\''); + word(self.writer(), &res[..]) + } + ast::LitKind::Int(i, t) => { + match t { + ast::LitIntType::Signed(st) => { + word(self.writer(), &st.val_to_string(i as i64)) + } + ast::LitIntType::Unsigned(ut) => { + word(self.writer(), &ut.val_to_string(i)) + } + ast::LitIntType::Unsuffixed => { + word(self.writer(), &format!("{}", i)) + } + } + } + ast::LitKind::Float(ref f, t) => { + word(self.writer(), + &format!( + "{}{}", + &f, + t.ty_to_string())) + } + ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f.as_str()), + ast::LitKind::Bool(val) => { + if val { word(self.writer(), "true") } else { word(self.writer(), "false") } + } + ast::LitKind::ByteStr(ref v) => { + let mut escaped: String = String::new(); + for &ch in v.iter() { + escaped.extend(ascii::escape_default(ch) + .map(|c| c as char)); + } + word(self.writer(), &format!("b\"{}\"", escaped)) + } + } + } + + fn print_string(&mut self, st: &str, + style: ast::StrStyle) -> io::Result<()> { + let st = match style { + ast::StrStyle::Cooked => { + (format!("\"{}\"", st.chars().flat_map(char::escape_default).collect::<String>())) + } + ast::StrStyle::Raw(n) => { + (format!("r{delim}\"{string}\"{delim}", + delim=repeat("#", n), + string=st)) + } + }; + word(self.writer(), &st[..]) + } + + fn print_inner_attributes(&mut self, + attrs: &[ast::Attribute]) -> io::Result<()> { + self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true) + } + + fn print_inner_attributes_no_trailing_hardbreak(&mut self, + attrs: &[ast::Attribute]) + -> io::Result<()> { + self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false) + } + + fn print_outer_attributes(&mut self, + attrs: &[ast::Attribute]) -> io::Result<()> { + self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true) + } + + fn print_inner_attributes_inline(&mut self, + attrs: &[ast::Attribute]) -> io::Result<()> { + self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true) + } + + fn print_outer_attributes_inline(&mut self, + attrs: &[ast::Attribute]) -> io::Result<()> { + self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true) + } + + fn print_either_attributes(&mut self, + attrs: &[ast::Attribute], + kind: ast::AttrStyle, + is_inline: bool, + trailing_hardbreak: bool) -> io::Result<()> { + let mut count = 0; + for attr in attrs { + if attr.style == kind { + try!(self.print_attribute_inline(attr, is_inline)); + if is_inline { + try!(self.nbsp()); + } + count += 1; + } + } + if count > 0 && trailing_hardbreak && !is_inline { + try!(self.hardbreak_if_not_bol()); + } + Ok(()) + } + + fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> { + self.print_attribute_inline(attr, false) + } + + fn print_attribute_inline(&mut self, attr: &ast::Attribute, + is_inline: bool) -> io::Result<()> { + if !is_inline { + try!(self.hardbreak_if_not_bol()); + } + try!(self.maybe_print_comment(attr.span.lo)); + if attr.is_sugared_doc { + try!(word(self.writer(), &attr.value_str().unwrap().as_str())); + hardbreak(self.writer()) + } else { + match attr.style { + ast::AttrStyle::Inner => try!(word(self.writer(), "#![")), + ast::AttrStyle::Outer => try!(word(self.writer(), "#[")), + } + try!(self.print_meta_item(&attr.meta())); + word(self.writer(), "]") + } + } + + fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> { + match item.node { + ast::NestedMetaItemKind::MetaItem(ref mi) => { + self.print_meta_item(mi) + }, + ast::NestedMetaItemKind::Literal(ref lit) => { + self.print_literal(lit) + } + } + } + + fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> { + try!(self.ibox(INDENT_UNIT)); + match item.node { + ast::MetaItemKind::Word => { + try!(word(self.writer(), &item.name.as_str())); + } + ast::MetaItemKind::NameValue(ref value) => { + try!(self.word_space(&item.name.as_str())); + try!(self.word_space("=")); + try!(self.print_literal(value)); + } + ast::MetaItemKind::List(ref items) => { + try!(word(self.writer(), &item.name.as_str())); + try!(self.popen()); + try!(self.commasep(Consistent, + &items[..], + |s, i| s.print_meta_list_item(&i))); + try!(self.pclose()); + } + } + self.end() + } + + fn space_if_not_bol(&mut self) -> io::Result<()> { + if !self.is_bol() { try!(space(self.writer())); } + Ok(()) + } + + fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") } +} + +impl<'a> PrintState<'a> for State<'a> { + fn writer(&mut self) -> &mut pp::Printer<'a> { + &mut self.s + } + + fn boxes(&mut self) -> &mut Vec<pp::Breaks> { + &mut self.boxes + } + + fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> { + &mut self.comments + } + + fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral { + &mut self.cur_cmnt_and_lit + } + + fn literals(&self) -> &Option<Vec<comments::Literal>> { + &self.literals + } +} + +impl<'a> State<'a> { + pub fn cbox(&mut self, u: usize) -> io::Result<()> { + self.boxes.push(pp::Breaks::Consistent); + pp::cbox(&mut self.s, u) + } + + pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> { + try!(word(&mut self.s, w)); + self.nbsp() + } + + pub fn head(&mut self, w: &str) -> io::Result<()> { + // outer-box is consistent + try!(self.cbox(INDENT_UNIT)); + // head-box is inconsistent + try!(self.ibox(w.len() + 1)); + // keyword that starts the head + if !w.is_empty() { + try!(self.word_nbsp(w)); + } + Ok(()) + } + + pub fn bopen(&mut self) -> io::Result<()> { + try!(word(&mut self.s, "{")); + self.end() // close the head-box + } + + pub fn bclose_(&mut self, span: syntax_pos::Span, + indented: usize) -> io::Result<()> { + self.bclose_maybe_open(span, indented, true) + } + pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span, + indented: usize, close_box: bool) -> io::Result<()> { + try!(self.maybe_print_comment(span.hi)); + try!(self.break_offset_if_not_bol(1, -(indented as isize))); + try!(word(&mut self.s, "}")); + if close_box { + try!(self.end()); // close the outer-box + } + Ok(()) + } + pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> { + self.bclose_(span, INDENT_UNIT) + } + + pub fn in_cbox(&self) -> bool { + match self.boxes.last() { + Some(&last_box) => last_box == pp::Breaks::Consistent, + None => false + } + } + + pub fn break_offset_if_not_bol(&mut self, n: usize, + off: isize) -> io::Result<()> { + if !self.is_bol() { + break_offset(&mut self.s, n, off) + } else { + if off != 0 && self.s.last_token().is_hardbreak_tok() { + // We do something pretty sketchy here: tuck the nonzero + // offset-adjustment we were going to deposit along with the + // break into the previous hardbreak. + self.s.replace_last_token(pp::hardbreak_tok_offset(off)); + } + Ok(()) + } + } + + // Synthesizes a comment that was not textually present in the original source + // file. + pub fn synth_comment(&mut self, text: String) -> io::Result<()> { + try!(word(&mut self.s, "/*")); + try!(space(&mut self.s)); + try!(word(&mut self.s, &text[..])); + try!(space(&mut self.s)); + word(&mut self.s, "*/") + } + + + + pub fn commasep_cmnt<T, F, G>(&mut self, + b: Breaks, + elts: &[T], + mut op: F, + mut get_span: G) -> io::Result<()> where + F: FnMut(&mut State, &T) -> io::Result<()>, + G: FnMut(&T) -> syntax_pos::Span, + { + try!(self.rbox(0, b)); + let len = elts.len(); + let mut i = 0; + for elt in elts { + try!(self.maybe_print_comment(get_span(elt).hi)); + try!(op(self, elt)); + i += 1; + if i < len { + try!(word(&mut self.s, ",")); + try!(self.maybe_print_trailing_comment(get_span(elt), + Some(get_span(&elts[i]).hi))); + try!(self.space_if_not_bol()); + } + } + self.end() + } + + pub fn commasep_exprs(&mut self, b: Breaks, + exprs: &[P<ast::Expr>]) -> io::Result<()> { + self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span) + } + + pub fn print_mod(&mut self, _mod: &ast::Mod, + attrs: &[ast::Attribute]) -> io::Result<()> { + try!(self.print_inner_attributes(attrs)); + for item in &_mod.items { + try!(self.print_item(&item)); + } + Ok(()) + } + + pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, + attrs: &[ast::Attribute]) -> io::Result<()> { + try!(self.print_inner_attributes(attrs)); + for item in &nmod.items { + try!(self.print_foreign_item(item)); + } + Ok(()) + } + + pub fn print_opt_lifetime(&mut self, + lifetime: &Option<ast::Lifetime>) -> io::Result<()> { + if let Some(l) = *lifetime { + try!(self.print_lifetime(&l)); + try!(self.nbsp()); + } + Ok(()) + } + + pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> { + try!(self.maybe_print_comment(ty.span.lo)); + try!(self.ibox(0)); + match ty.node { + ast::TyKind::Slice(ref ty) => { + try!(word(&mut self.s, "[")); + try!(self.print_type(&ty)); + try!(word(&mut self.s, "]")); + } + ast::TyKind::Ptr(ref mt) => { + try!(word(&mut self.s, "*")); + match mt.mutbl { + ast::Mutability::Mutable => try!(self.word_nbsp("mut")), + ast::Mutability::Immutable => try!(self.word_nbsp("const")), + } + try!(self.print_type(&mt.ty)); + } + ast::TyKind::Rptr(ref lifetime, ref mt) => { + try!(word(&mut self.s, "&")); + try!(self.print_opt_lifetime(lifetime)); + try!(self.print_mt(mt)); + } + ast::TyKind::Never => { + try!(word(&mut self.s, "!")); + }, + ast::TyKind::Tup(ref elts) => { + try!(self.popen()); + try!(self.commasep(Inconsistent, &elts[..], + |s, ty| s.print_type(&ty))); + if elts.len() == 1 { + try!(word(&mut self.s, ",")); + } + try!(self.pclose()); + } + ast::TyKind::Paren(ref typ) => { + try!(self.popen()); + try!(self.print_type(&typ)); + try!(self.pclose()); + } + ast::TyKind::BareFn(ref f) => { + let generics = ast::Generics { + lifetimes: f.lifetimes.clone(), + ty_params: P::new(), + where_clause: ast::WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + }, + span: syntax_pos::DUMMY_SP, + }; + try!(self.print_ty_fn(f.abi, + f.unsafety, + &f.decl, + None, + &generics)); + } + ast::TyKind::Path(None, ref path) => { + try!(self.print_path(path, false, 0, false)); + } + ast::TyKind::Path(Some(ref qself), ref path) => { + try!(self.print_qpath(path, qself, false)) + } + ast::TyKind::ObjectSum(ref ty, ref bounds) => { + try!(self.print_type(&ty)); + try!(self.print_bounds("+", &bounds[..])); + } + ast::TyKind::PolyTraitRef(ref bounds) => { + try!(self.print_bounds("", &bounds[..])); + } + ast::TyKind::ImplTrait(ref bounds) => { + try!(self.print_bounds("impl ", &bounds[..])); + } + ast::TyKind::Array(ref ty, ref v) => { + try!(word(&mut self.s, "[")); + try!(self.print_type(&ty)); + try!(word(&mut self.s, "; ")); + try!(self.print_expr(&v)); + try!(word(&mut self.s, "]")); + } + ast::TyKind::Typeof(ref e) => { + try!(word(&mut self.s, "typeof(")); + try!(self.print_expr(&e)); + try!(word(&mut self.s, ")")); + } + ast::TyKind::Infer => { + try!(word(&mut self.s, "_")); + } + ast::TyKind::ImplicitSelf => { + try!(word(&mut self.s, "Self")); + } + ast::TyKind::Mac(ref m) => { + try!(self.print_mac(m, token::Paren)); + } + } + self.end() + } + + pub fn print_foreign_item(&mut self, + item: &ast::ForeignItem) -> io::Result<()> { + try!(self.hardbreak_if_not_bol()); + try!(self.maybe_print_comment(item.span.lo)); + try!(self.print_outer_attributes(&item.attrs)); + match item.node { + ast::ForeignItemKind::Fn(ref decl, ref generics) => { + try!(self.head("")); + try!(self.print_fn(decl, ast::Unsafety::Normal, + ast::Constness::NotConst, + Abi::Rust, Some(item.ident), + generics, &item.vis)); + try!(self.end()); // end head-ibox + try!(word(&mut self.s, ";")); + self.end() // end the outer fn box + } + ast::ForeignItemKind::Static(ref t, m) => { + try!(self.head(&visibility_qualified(&item.vis, "static"))); + if m { + try!(self.word_space("mut")); + } + try!(self.print_ident(item.ident)); + try!(self.word_space(":")); + try!(self.print_type(&t)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end the head-ibox + self.end() // end the outer cbox + } + } + } + + fn print_associated_const(&mut self, + ident: ast::Ident, + ty: &ast::Ty, + default: Option<&ast::Expr>, + vis: &ast::Visibility) + -> io::Result<()> + { + try!(word(&mut self.s, &visibility_qualified(vis, ""))); + try!(self.word_space("const")); + try!(self.print_ident(ident)); + try!(self.word_space(":")); + try!(self.print_type(ty)); + if let Some(expr) = default { + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_expr(expr)); + } + word(&mut self.s, ";") + } + + fn print_associated_type(&mut self, + ident: ast::Ident, + bounds: Option<&ast::TyParamBounds>, + ty: Option<&ast::Ty>) + -> io::Result<()> { + try!(self.word_space("type")); + try!(self.print_ident(ident)); + if let Some(bounds) = bounds { + try!(self.print_bounds(":", bounds)); + } + if let Some(ty) = ty { + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_type(ty)); + } + word(&mut self.s, ";") + } + + /// Pretty-print an item + pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> { + try!(self.hardbreak_if_not_bol()); + try!(self.maybe_print_comment(item.span.lo)); + try!(self.print_outer_attributes(&item.attrs)); + try!(self.ann.pre(self, NodeItem(item))); + match item.node { + ast::ItemKind::ExternCrate(ref optional_path) => { + try!(self.head(&visibility_qualified(&item.vis, "extern crate"))); + if let Some(p) = *optional_path { + let val = p.as_str(); + if val.contains("-") { + try!(self.print_string(&val, ast::StrStyle::Cooked)); + } else { + try!(self.print_name(p)); + } + try!(space(&mut self.s)); + try!(word(&mut self.s, "as")); + try!(space(&mut self.s)); + } + try!(self.print_ident(item.ident)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end inner head-block + try!(self.end()); // end outer head-block + } + ast::ItemKind::Use(ref vp) => { + try!(self.head(&visibility_qualified(&item.vis, "use"))); + try!(self.print_view_path(&vp)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end inner head-block + try!(self.end()); // end outer head-block + } + ast::ItemKind::Static(ref ty, m, ref expr) => { + try!(self.head(&visibility_qualified(&item.vis, "static"))); + if m == ast::Mutability::Mutable { + try!(self.word_space("mut")); + } + try!(self.print_ident(item.ident)); + try!(self.word_space(":")); + try!(self.print_type(&ty)); + try!(space(&mut self.s)); + try!(self.end()); // end the head-ibox + + try!(self.word_space("=")); + try!(self.print_expr(&expr)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end the outer cbox + } + ast::ItemKind::Const(ref ty, ref expr) => { + try!(self.head(&visibility_qualified(&item.vis, "const"))); + try!(self.print_ident(item.ident)); + try!(self.word_space(":")); + try!(self.print_type(&ty)); + try!(space(&mut self.s)); + try!(self.end()); // end the head-ibox + + try!(self.word_space("=")); + try!(self.print_expr(&expr)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end the outer cbox + } + ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => { + try!(self.head("")); + try!(self.print_fn( + decl, + unsafety, + constness.node, + abi, + Some(item.ident), + typarams, + &item.vis + )); + try!(word(&mut self.s, " ")); + try!(self.print_block_with_attrs(&body, &item.attrs)); + } + ast::ItemKind::Mod(ref _mod) => { + try!(self.head(&visibility_qualified(&item.vis, "mod"))); + try!(self.print_ident(item.ident)); + try!(self.nbsp()); + try!(self.bopen()); + try!(self.print_mod(_mod, &item.attrs)); + try!(self.bclose(item.span)); + } + ast::ItemKind::ForeignMod(ref nmod) => { + try!(self.head("extern")); + try!(self.word_nbsp(&nmod.abi.to_string())); + try!(self.bopen()); + try!(self.print_foreign_mod(nmod, &item.attrs)); + try!(self.bclose(item.span)); + } + ast::ItemKind::Ty(ref ty, ref params) => { + try!(self.ibox(INDENT_UNIT)); + try!(self.ibox(0)); + try!(self.word_nbsp(&visibility_qualified(&item.vis, "type"))); + try!(self.print_ident(item.ident)); + try!(self.print_generics(params)); + try!(self.end()); // end the inner ibox + + try!(self.print_where_clause(¶ms.where_clause)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_type(&ty)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end the outer ibox + } + ast::ItemKind::Enum(ref enum_definition, ref params) => { + try!(self.print_enum_def( + enum_definition, + params, + item.ident, + item.span, + &item.vis + )); + } + ast::ItemKind::Struct(ref struct_def, ref generics) => { + try!(self.head(&visibility_qualified(&item.vis, "struct"))); + try!(self.print_struct(&struct_def, generics, item.ident, item.span, true)); + } + ast::ItemKind::Union(ref struct_def, ref generics) => { + try!(self.head(&visibility_qualified(&item.vis, "union"))); + try!(self.print_struct(&struct_def, generics, item.ident, item.span, true)); + } + ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => { + try!(self.head("")); + try!(self.print_visibility(&item.vis)); + try!(self.print_unsafety(unsafety)); + try!(self.word_nbsp("impl")); + try!(self.print_trait_ref(trait_ref)); + try!(space(&mut self.s)); + try!(self.word_space("for")); + try!(self.word_space("..")); + try!(self.bopen()); + try!(self.bclose(item.span)); + } + ast::ItemKind::Impl(unsafety, + polarity, + ref generics, + ref opt_trait, + ref ty, + ref impl_items) => { + try!(self.head("")); + try!(self.print_visibility(&item.vis)); + try!(self.print_unsafety(unsafety)); + try!(self.word_nbsp("impl")); + + if generics.is_parameterized() { + try!(self.print_generics(generics)); + try!(space(&mut self.s)); + } + + match polarity { + ast::ImplPolarity::Negative => { + try!(word(&mut self.s, "!")); + }, + _ => {} + } + + if let Some(ref t) = *opt_trait { + try!(self.print_trait_ref(t)); + try!(space(&mut self.s)); + try!(self.word_space("for")); + } + + try!(self.print_type(&ty)); + try!(self.print_where_clause(&generics.where_clause)); + + try!(space(&mut self.s)); + try!(self.bopen()); + try!(self.print_inner_attributes(&item.attrs)); + for impl_item in impl_items { + try!(self.print_impl_item(impl_item)); + } + try!(self.bclose(item.span)); + } + ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => { + try!(self.head("")); + try!(self.print_visibility(&item.vis)); + try!(self.print_unsafety(unsafety)); + try!(self.word_nbsp("trait")); + try!(self.print_ident(item.ident)); + try!(self.print_generics(generics)); + let mut real_bounds = Vec::with_capacity(bounds.len()); + for b in bounds.iter() { + if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + try!(space(&mut self.s)); + try!(self.word_space("for )")); + try!(self.print_trait_ref(&ptr.trait_ref)); + } else { + real_bounds.push(b.clone()); + } + } + try!(self.print_bounds(":", &real_bounds[..])); + try!(self.print_where_clause(&generics.where_clause)); + try!(word(&mut self.s, " ")); + try!(self.bopen()); + for trait_item in trait_items { + try!(self.print_trait_item(trait_item)); + } + try!(self.bclose(item.span)); + } + ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => { + try!(self.print_visibility(&item.vis)); + try!(self.print_path(&node.path, false, 0, false)); + try!(word(&mut self.s, "! ")); + try!(self.print_ident(item.ident)); + try!(self.cbox(INDENT_UNIT)); + try!(self.popen()); + try!(self.print_tts(&node.tts[..])); + try!(self.pclose()); + try!(word(&mut self.s, ";")); + try!(self.end()); + } + } + self.ann.post(self, NodeItem(item)) + } + + fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> { + self.print_path(&t.path, false, 0, false) + } + + fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> { + if !lifetimes.is_empty() { + try!(word(&mut self.s, "for<")); + let mut comma = false; + for lifetime_def in lifetimes { + if comma { + try!(self.word_space(",")) + } + try!(self.print_outer_attributes_inline(&lifetime_def.attrs)); + try!(self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)); + comma = true; + } + try!(word(&mut self.s, ">")); + } + Ok(()) + } + + fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> { + try!(self.print_formal_lifetime_list(&t.bound_lifetimes)); + self.print_trait_ref(&t.trait_ref) + } + + pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef, + generics: &ast::Generics, ident: ast::Ident, + span: syntax_pos::Span, + visibility: &ast::Visibility) -> io::Result<()> { + try!(self.head(&visibility_qualified(visibility, "enum"))); + try!(self.print_ident(ident)); + try!(self.print_generics(generics)); + try!(self.print_where_clause(&generics.where_clause)); + try!(space(&mut self.s)); + self.print_variants(&enum_definition.variants, span) + } + + pub fn print_variants(&mut self, + variants: &[ast::Variant], + span: syntax_pos::Span) -> io::Result<()> { + try!(self.bopen()); + for v in variants { + try!(self.space_if_not_bol()); + try!(self.maybe_print_comment(v.span.lo)); + try!(self.print_outer_attributes(&v.node.attrs)); + try!(self.ibox(INDENT_UNIT)); + try!(self.print_variant(v)); + try!(word(&mut self.s, ",")); + try!(self.end()); + try!(self.maybe_print_trailing_comment(v.span, None)); + } + self.bclose(span) + } + + pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> { + match *vis { + ast::Visibility::Public => self.word_nbsp("pub"), + ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"), + ast::Visibility::Restricted { ref path, .. } => { + let path = to_string(|s| s.print_path(path, false, 0, true)); + self.word_nbsp(&format!("pub({})", path)) + } + ast::Visibility::Inherited => Ok(()) + } + } + + pub fn print_struct(&mut self, + struct_def: &ast::VariantData, + generics: &ast::Generics, + ident: ast::Ident, + span: syntax_pos::Span, + print_finalizer: bool) -> io::Result<()> { + try!(self.print_ident(ident)); + try!(self.print_generics(generics)); + if !struct_def.is_struct() { + if struct_def.is_tuple() { + try!(self.popen()); + try!(self.commasep( + Inconsistent, struct_def.fields(), + |s, field| { + try!(s.maybe_print_comment(field.span.lo)); + try!(s.print_outer_attributes(&field.attrs)); + try!(s.print_visibility(&field.vis)); + s.print_type(&field.ty) + } + )); + try!(self.pclose()); + } + try!(self.print_where_clause(&generics.where_clause)); + if print_finalizer { + try!(word(&mut self.s, ";")); + } + try!(self.end()); + self.end() // close the outer-box + } else { + try!(self.print_where_clause(&generics.where_clause)); + try!(self.nbsp()); + try!(self.bopen()); + try!(self.hardbreak_if_not_bol()); + + for field in struct_def.fields() { + try!(self.hardbreak_if_not_bol()); + try!(self.maybe_print_comment(field.span.lo)); + try!(self.print_outer_attributes(&field.attrs)); + try!(self.print_visibility(&field.vis)); + try!(self.print_ident(field.ident.unwrap())); + try!(self.word_nbsp(":")); + try!(self.print_type(&field.ty)); + try!(word(&mut self.s, ",")); + } + + self.bclose(span) + } + } + + /// This doesn't deserve to be called "pretty" printing, but it should be + /// meaning-preserving. A quick hack that might help would be to look at the + /// spans embedded in the TTs to decide where to put spaces and newlines. + /// But it'd be better to parse these according to the grammar of the + /// appropriate macro, transcribe back into the grammar we just parsed from, + /// and then pretty-print the resulting AST nodes (so, e.g., we print + /// expression arguments as expressions). It can be done! I think. + pub fn print_tt(&mut self, tt: &tokenstream::TokenTree) -> io::Result<()> { + match *tt { + TokenTree::Token(_, ref tk) => { + try!(word(&mut self.s, &token_to_string(tk))); + match *tk { + parse::token::DocComment(..) => { + hardbreak(&mut self.s) + } + _ => Ok(()) + } + } + TokenTree::Delimited(_, ref delimed) => { + try!(word(&mut self.s, &token_to_string(&delimed.open_token()))); + try!(space(&mut self.s)); + try!(self.print_tts(&delimed.tts)); + try!(space(&mut self.s)); + word(&mut self.s, &token_to_string(&delimed.close_token())) + }, + TokenTree::Sequence(_, ref seq) => { + try!(word(&mut self.s, "$(")); + for tt_elt in &seq.tts { + try!(self.print_tt(tt_elt)); + } + try!(word(&mut self.s, ")")); + if let Some(ref tk) = seq.separator { + try!(word(&mut self.s, &token_to_string(tk))); + } + match seq.op { + tokenstream::KleeneOp::ZeroOrMore => word(&mut self.s, "*"), + tokenstream::KleeneOp::OneOrMore => word(&mut self.s, "+"), + } + } + } + } + + pub fn print_tts(&mut self, tts: &[tokenstream::TokenTree]) -> io::Result<()> { + try!(self.ibox(0)); + for (i, tt) in tts.iter().enumerate() { + if i != 0 { + try!(space(&mut self.s)); + } + try!(self.print_tt(tt)); + } + self.end() + } + + pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> { + try!(self.head("")); + let generics = ast::Generics::default(); + try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)); + match v.node.disr_expr { + Some(ref d) => { + try!(space(&mut self.s)); + try!(self.word_space("=")); + self.print_expr(&d) + } + _ => Ok(()) + } + } + + pub fn print_method_sig(&mut self, + ident: ast::Ident, + m: &ast::MethodSig, + vis: &ast::Visibility) + -> io::Result<()> { + self.print_fn(&m.decl, + m.unsafety, + m.constness.node, + m.abi, + Some(ident), + &m.generics, + vis) + } + + pub fn print_trait_item(&mut self, ti: &ast::TraitItem) + -> io::Result<()> { + try!(self.ann.pre(self, NodeSubItem(ti.id))); + try!(self.hardbreak_if_not_bol()); + try!(self.maybe_print_comment(ti.span.lo)); + try!(self.print_outer_attributes(&ti.attrs)); + match ti.node { + ast::TraitItemKind::Const(ref ty, ref default) => { + try!(self.print_associated_const(ti.ident, &ty, + default.as_ref().map(|expr| &**expr), + &ast::Visibility::Inherited)); + } + ast::TraitItemKind::Method(ref sig, ref body) => { + if body.is_some() { + try!(self.head("")); + } + try!(self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)); + if let Some(ref body) = *body { + try!(self.nbsp()); + try!(self.print_block_with_attrs(body, &ti.attrs)); + } else { + try!(word(&mut self.s, ";")); + } + } + ast::TraitItemKind::Type(ref bounds, ref default) => { + try!(self.print_associated_type(ti.ident, Some(bounds), + default.as_ref().map(|ty| &**ty))); + } + ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => { + // code copied from ItemKind::Mac: + try!(self.print_path(&node.path, false, 0, false)); + try!(word(&mut self.s, "! ")); + try!(self.cbox(INDENT_UNIT)); + try!(self.popen()); + try!(self.print_tts(&node.tts[..])); + try!(self.pclose()); + try!(word(&mut self.s, ";")); + try!(self.end()) + } + } + self.ann.post(self, NodeSubItem(ti.id)) + } + + pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> { + try!(self.ann.pre(self, NodeSubItem(ii.id))); + try!(self.hardbreak_if_not_bol()); + try!(self.maybe_print_comment(ii.span.lo)); + try!(self.print_outer_attributes(&ii.attrs)); + if let ast::Defaultness::Default = ii.defaultness { + try!(self.word_nbsp("default")); + } + match ii.node { + ast::ImplItemKind::Const(ref ty, ref expr) => { + try!(self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)); + } + ast::ImplItemKind::Method(ref sig, ref body) => { + try!(self.head("")); + try!(self.print_method_sig(ii.ident, sig, &ii.vis)); + try!(self.nbsp()); + try!(self.print_block_with_attrs(body, &ii.attrs)); + } + ast::ImplItemKind::Type(ref ty) => { + try!(self.print_associated_type(ii.ident, None, Some(ty))); + } + ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => { + // code copied from ItemKind::Mac: + try!(self.print_path(&node.path, false, 0, false)); + try!(word(&mut self.s, "! ")); + try!(self.cbox(INDENT_UNIT)); + try!(self.popen()); + try!(self.print_tts(&node.tts[..])); + try!(self.pclose()); + try!(word(&mut self.s, ";")); + try!(self.end()) + } + } + self.ann.post(self, NodeSubItem(ii.id)) + } + + pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> { + try!(self.maybe_print_comment(st.span.lo)); + match st.node { + ast::StmtKind::Local(ref loc) => { + try!(self.print_outer_attributes(&loc.attrs)); + try!(self.space_if_not_bol()); + try!(self.ibox(INDENT_UNIT)); + try!(self.word_nbsp("let")); + + try!(self.ibox(INDENT_UNIT)); + try!(self.print_local_decl(&loc)); + try!(self.end()); + if let Some(ref init) = loc.init { + try!(self.nbsp()); + try!(self.word_space("=")); + try!(self.print_expr(&init)); + } + try!(word(&mut self.s, ";")); + try!(self.end()); + } + ast::StmtKind::Item(ref item) => try!(self.print_item(&item)), + ast::StmtKind::Expr(ref expr) => { + try!(self.space_if_not_bol()); + try!(self.print_expr_outer_attr_style(&expr, false)); + if parse::classify::expr_requires_semi_to_be_stmt(expr) { + try!(word(&mut self.s, ";")); + } + } + ast::StmtKind::Semi(ref expr) => { + try!(self.space_if_not_bol()); + try!(self.print_expr_outer_attr_style(&expr, false)); + try!(word(&mut self.s, ";")); + } + ast::StmtKind::Mac(ref mac) => { + let (ref mac, style, ref attrs) = **mac; + try!(self.space_if_not_bol()); + try!(self.print_outer_attributes(&attrs)); + let delim = match style { + ast::MacStmtStyle::Braces => token::Brace, + _ => token::Paren + }; + try!(self.print_mac(&mac, delim)); + if style == ast::MacStmtStyle::Semicolon { + try!(word(&mut self.s, ";")); + } + } + } + self.maybe_print_trailing_comment(st.span, None) + } + + pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> { + self.print_block_with_attrs(blk, &[]) + } + + pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> { + self.print_block_unclosed_indent(blk, INDENT_UNIT) + } + + pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block, + attrs: &[ast::Attribute]) + -> io::Result<()> { + self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false) + } + + pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block, + indented: usize) -> io::Result<()> { + self.print_block_maybe_unclosed(blk, indented, &[], false) + } + + pub fn print_block_with_attrs(&mut self, + blk: &ast::Block, + attrs: &[ast::Attribute]) -> io::Result<()> { + self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true) + } + + pub fn print_block_maybe_unclosed(&mut self, + blk: &ast::Block, + indented: usize, + attrs: &[ast::Attribute], + close_box: bool) -> io::Result<()> { + match blk.rules { + BlockCheckMode::Unsafe(..) => try!(self.word_space("unsafe")), + BlockCheckMode::Default => () + } + try!(self.maybe_print_comment(blk.span.lo)); + try!(self.ann.pre(self, NodeBlock(blk))); + try!(self.bopen()); + + try!(self.print_inner_attributes(attrs)); + + for (i, st) in blk.stmts.iter().enumerate() { + match st.node { + ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => { + try!(self.maybe_print_comment(st.span.lo)); + try!(self.space_if_not_bol()); + try!(self.print_expr_outer_attr_style(&expr, false)); + try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))); + } + _ => try!(self.print_stmt(st)), + } + } + + try!(self.bclose_maybe_open(blk.span, indented, close_box)); + self.ann.post(self, NodeBlock(blk)) + } + + fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> { + match els { + Some(_else) => { + match _else.node { + // "another else-if" + ast::ExprKind::If(ref i, ref then, ref e) => { + try!(self.cbox(INDENT_UNIT - 1)); + try!(self.ibox(0)); + try!(word(&mut self.s, " else if ")); + try!(self.print_expr(&i)); + try!(space(&mut self.s)); + try!(self.print_block(&then)); + self.print_else(e.as_ref().map(|e| &**e)) + } + // "another else-if-let" + ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => { + try!(self.cbox(INDENT_UNIT - 1)); + try!(self.ibox(0)); + try!(word(&mut self.s, " else if let ")); + try!(self.print_pat(&pat)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_expr(&expr)); + try!(space(&mut self.s)); + try!(self.print_block(&then)); + self.print_else(e.as_ref().map(|e| &**e)) + } + // "final else" + ast::ExprKind::Block(ref b) => { + try!(self.cbox(INDENT_UNIT - 1)); + try!(self.ibox(0)); + try!(word(&mut self.s, " else ")); + self.print_block(&b) + } + // BLEAH, constraints would be great here + _ => { + panic!("print_if saw if with weird alternative"); + } + } + } + _ => Ok(()) + } + } + + pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, + elseopt: Option<&ast::Expr>) -> io::Result<()> { + try!(self.head("if")); + try!(self.print_expr(test)); + try!(space(&mut self.s)); + try!(self.print_block(blk)); + self.print_else(elseopt) + } + + pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block, + elseopt: Option<&ast::Expr>) -> io::Result<()> { + try!(self.head("if let")); + try!(self.print_pat(pat)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_expr(expr)); + try!(space(&mut self.s)); + try!(self.print_block(blk)); + self.print_else(elseopt) + } + + pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken) + -> io::Result<()> { + try!(self.print_path(&m.node.path, false, 0, false)); + try!(word(&mut self.s, "!")); + match delim { + token::Paren => try!(self.popen()), + token::Bracket => try!(word(&mut self.s, "[")), + token::Brace => { + try!(self.head("")); + try!(self.bopen()); + } + token::NoDelim => {} + } + try!(self.print_tts(&m.node.tts)); + match delim { + token::Paren => self.pclose(), + token::Bracket => word(&mut self.s, "]"), + token::Brace => self.bclose(m.span), + token::NoDelim => Ok(()), + } + } + + + fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> { + try!(self.popen()); + try!(self.commasep_exprs(Inconsistent, args)); + self.pclose() + } + + pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr, + binop: ast::BinOp) -> bool { + match sub_expr.node { + ast::ExprKind::Binary(ref sub_op, _, _) => { + if AssocOp::from_ast_binop(sub_op.node).precedence() < + AssocOp::from_ast_binop(binop.node).precedence() { + true + } else { + false + } + } + _ => true + } + } + + pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> { + let needs_par = needs_parentheses(expr); + if needs_par { + try!(self.popen()); + } + try!(self.print_expr(expr)); + if needs_par { + try!(self.pclose()); + } + Ok(()) + } + + fn print_expr_in_place(&mut self, + place: &ast::Expr, + expr: &ast::Expr) -> io::Result<()> { + try!(self.print_expr_maybe_paren(place)); + try!(space(&mut self.s)); + try!(self.word_space("<-")); + self.print_expr_maybe_paren(expr) + } + + fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], + attrs: &[Attribute]) -> io::Result<()> { + try!(self.ibox(INDENT_UNIT)); + try!(word(&mut self.s, "[")); + try!(self.print_inner_attributes_inline(attrs)); + try!(self.commasep_exprs(Inconsistent, &exprs[..])); + try!(word(&mut self.s, "]")); + self.end() + } + + fn print_expr_repeat(&mut self, + element: &ast::Expr, + count: &ast::Expr, + attrs: &[Attribute]) -> io::Result<()> { + try!(self.ibox(INDENT_UNIT)); + try!(word(&mut self.s, "[")); + try!(self.print_inner_attributes_inline(attrs)); + try!(self.print_expr(element)); + try!(self.word_space(";")); + try!(self.print_expr(count)); + try!(word(&mut self.s, "]")); + self.end() + } + + fn print_expr_struct(&mut self, + path: &ast::Path, + fields: &[ast::Field], + wth: &Option<P<ast::Expr>>, + attrs: &[Attribute]) -> io::Result<()> { + try!(self.print_path(path, true, 0, false)); + try!(word(&mut self.s, "{")); + try!(self.print_inner_attributes_inline(attrs)); + try!(self.commasep_cmnt( + Consistent, + &fields[..], + |s, field| { + try!(s.ibox(INDENT_UNIT)); + if !field.is_shorthand { + try!(s.print_ident(field.ident.node)); + try!(s.word_space(":")); + } + try!(s.print_expr(&field.expr)); + s.end() + }, + |f| f.span)); + match *wth { + Some(ref expr) => { + try!(self.ibox(INDENT_UNIT)); + if !fields.is_empty() { + try!(word(&mut self.s, ",")); + try!(space(&mut self.s)); + } + try!(word(&mut self.s, "..")); + try!(self.print_expr(&expr)); + try!(self.end()); + } + _ => if !fields.is_empty() { + try!(word(&mut self.s, ",")) + } + } + try!(word(&mut self.s, "}")); + Ok(()) + } + + fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], + attrs: &[Attribute]) -> io::Result<()> { + try!(self.popen()); + try!(self.print_inner_attributes_inline(attrs)); + try!(self.commasep_exprs(Inconsistent, &exprs[..])); + if exprs.len() == 1 { + try!(word(&mut self.s, ",")); + } + self.pclose() + } + + fn print_expr_call(&mut self, + func: &ast::Expr, + args: &[P<ast::Expr>]) -> io::Result<()> { + try!(self.print_expr_maybe_paren(func)); + self.print_call_post(args) + } + + fn print_expr_method_call(&mut self, + ident: ast::SpannedIdent, + tys: &[P<ast::Ty>], + args: &[P<ast::Expr>]) -> io::Result<()> { + let base_args = &args[1..]; + try!(self.print_expr(&args[0])); + try!(word(&mut self.s, ".")); + try!(self.print_ident(ident.node)); + if !tys.is_empty() { + try!(word(&mut self.s, "::<")); + try!(self.commasep(Inconsistent, tys, + |s, ty| s.print_type(&ty))); + try!(word(&mut self.s, ">")); + } + self.print_call_post(base_args) + } + + fn print_expr_binary(&mut self, + op: ast::BinOp, + lhs: &ast::Expr, + rhs: &ast::Expr) -> io::Result<()> { + if self.check_expr_bin_needs_paren(lhs, op) { + try!(self.print_expr_maybe_paren(lhs)); + } else { + try!(self.print_expr(lhs)); + } + try!(space(&mut self.s)); + try!(self.word_space(op.node.to_string())); + if self.check_expr_bin_needs_paren(rhs, op) { + self.print_expr_maybe_paren(rhs) + } else { + self.print_expr(rhs) + } + } + + fn print_expr_unary(&mut self, + op: ast::UnOp, + expr: &ast::Expr) -> io::Result<()> { + try!(word(&mut self.s, ast::UnOp::to_string(op))); + self.print_expr_maybe_paren(expr) + } + + fn print_expr_addr_of(&mut self, + mutability: ast::Mutability, + expr: &ast::Expr) -> io::Result<()> { + try!(word(&mut self.s, "&")); + try!(self.print_mutability(mutability)); + self.print_expr_maybe_paren(expr) + } + + pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> { + self.print_expr_outer_attr_style(expr, true) + } + + fn print_expr_outer_attr_style(&mut self, + expr: &ast::Expr, + is_inline: bool) -> io::Result<()> { + try!(self.maybe_print_comment(expr.span.lo)); + + let attrs = &expr.attrs; + if is_inline { + try!(self.print_outer_attributes_inline(attrs)); + } else { + try!(self.print_outer_attributes(attrs)); + } + + try!(self.ibox(INDENT_UNIT)); + try!(self.ann.pre(self, NodeExpr(expr))); + match expr.node { + ast::ExprKind::Box(ref expr) => { + try!(self.word_space("box")); + try!(self.print_expr(expr)); + } + ast::ExprKind::InPlace(ref place, ref expr) => { + try!(self.print_expr_in_place(place, expr)); + } + ast::ExprKind::Vec(ref exprs) => { + try!(self.print_expr_vec(&exprs[..], attrs)); + } + ast::ExprKind::Repeat(ref element, ref count) => { + try!(self.print_expr_repeat(&element, &count, attrs)); + } + ast::ExprKind::Struct(ref path, ref fields, ref wth) => { + try!(self.print_expr_struct(path, &fields[..], wth, attrs)); + } + ast::ExprKind::Tup(ref exprs) => { + try!(self.print_expr_tup(&exprs[..], attrs)); + } + ast::ExprKind::Call(ref func, ref args) => { + try!(self.print_expr_call(&func, &args[..])); + } + ast::ExprKind::MethodCall(ident, ref tys, ref args) => { + try!(self.print_expr_method_call(ident, &tys[..], &args[..])); + } + ast::ExprKind::Binary(op, ref lhs, ref rhs) => { + try!(self.print_expr_binary(op, &lhs, &rhs)); + } + ast::ExprKind::Unary(op, ref expr) => { + try!(self.print_expr_unary(op, &expr)); + } + ast::ExprKind::AddrOf(m, ref expr) => { + try!(self.print_expr_addr_of(m, &expr)); + } + ast::ExprKind::Lit(ref lit) => { + try!(self.print_literal(&lit)); + } + ast::ExprKind::Cast(ref expr, ref ty) => { + if let ast::ExprKind::Cast(..) = expr.node { + try!(self.print_expr(&expr)); + } else { + try!(self.print_expr_maybe_paren(&expr)); + } + try!(space(&mut self.s)); + try!(self.word_space("as")); + try!(self.print_type(&ty)); + } + ast::ExprKind::Type(ref expr, ref ty) => { + try!(self.print_expr(&expr)); + try!(self.word_space(":")); + try!(self.print_type(&ty)); + } + ast::ExprKind::If(ref test, ref blk, ref elseopt) => { + try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))); + } + ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => { + try!(self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))); + } + ast::ExprKind::While(ref test, ref blk, opt_ident) => { + if let Some(ident) = opt_ident { + try!(self.print_ident(ident.node)); + try!(self.word_space(":")); + } + try!(self.head("while")); + try!(self.print_expr(&test)); + try!(space(&mut self.s)); + try!(self.print_block_with_attrs(&blk, attrs)); + } + ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => { + if let Some(ident) = opt_ident { + try!(self.print_ident(ident.node)); + try!(self.word_space(":")); + } + try!(self.head("while let")); + try!(self.print_pat(&pat)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_expr(&expr)); + try!(space(&mut self.s)); + try!(self.print_block_with_attrs(&blk, attrs)); + } + ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => { + if let Some(ident) = opt_ident { + try!(self.print_ident(ident.node)); + try!(self.word_space(":")); + } + try!(self.head("for")); + try!(self.print_pat(&pat)); + try!(space(&mut self.s)); + try!(self.word_space("in")); + try!(self.print_expr(&iter)); + try!(space(&mut self.s)); + try!(self.print_block_with_attrs(&blk, attrs)); + } + ast::ExprKind::Loop(ref blk, opt_ident) => { + if let Some(ident) = opt_ident { + try!(self.print_ident(ident.node)); + try!(self.word_space(":")); + } + try!(self.head("loop")); + try!(space(&mut self.s)); + try!(self.print_block_with_attrs(&blk, attrs)); + } + ast::ExprKind::Match(ref expr, ref arms) => { + try!(self.cbox(INDENT_UNIT)); + try!(self.ibox(4)); + try!(self.word_nbsp("match")); + try!(self.print_expr(&expr)); + try!(space(&mut self.s)); + try!(self.bopen()); + try!(self.print_inner_attributes_no_trailing_hardbreak(attrs)); + for arm in arms { + try!(self.print_arm(arm)); + } + try!(self.bclose_(expr.span, INDENT_UNIT)); + } + ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => { + try!(self.print_capture_clause(capture_clause)); + + try!(self.print_fn_block_args(&decl)); + try!(space(&mut self.s)); + try!(self.print_expr(body)); + try!(self.end()); // need to close a box + + // a box will be closed by print_expr, but we didn't want an overall + // wrapper so we closed the corresponding opening. so create an + // empty box to satisfy the close. + try!(self.ibox(0)); + } + ast::ExprKind::Block(ref blk) => { + // containing cbox, will be closed by print-block at } + try!(self.cbox(INDENT_UNIT)); + // head-box, will be closed by print-block after { + try!(self.ibox(0)); + try!(self.print_block_with_attrs(&blk, attrs)); + } + ast::ExprKind::Assign(ref lhs, ref rhs) => { + try!(self.print_expr(&lhs)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_expr(&rhs)); + } + ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => { + try!(self.print_expr(&lhs)); + try!(space(&mut self.s)); + try!(word(&mut self.s, op.node.to_string())); + try!(self.word_space("=")); + try!(self.print_expr(&rhs)); + } + ast::ExprKind::Field(ref expr, id) => { + try!(self.print_expr(&expr)); + try!(word(&mut self.s, ".")); + try!(self.print_ident(id.node)); + } + ast::ExprKind::TupField(ref expr, id) => { + try!(self.print_expr(&expr)); + try!(word(&mut self.s, ".")); + try!(self.print_usize(id.node)); + } + ast::ExprKind::Index(ref expr, ref index) => { + try!(self.print_expr(&expr)); + try!(word(&mut self.s, "[")); + try!(self.print_expr(&index)); + try!(word(&mut self.s, "]")); + } + ast::ExprKind::Range(ref start, ref end, limits) => { + if let &Some(ref e) = start { + try!(self.print_expr(&e)); + } + if limits == ast::RangeLimits::HalfOpen { + try!(word(&mut self.s, "..")); + } else { + try!(word(&mut self.s, "...")); + } + if let &Some(ref e) = end { + try!(self.print_expr(&e)); + } + } + ast::ExprKind::Path(None, ref path) => { + try!(self.print_path(path, true, 0, false)) + } + ast::ExprKind::Path(Some(ref qself), ref path) => { + try!(self.print_qpath(path, qself, true)) + } + ast::ExprKind::Break(opt_ident, ref opt_expr) => { + try!(word(&mut self.s, "break")); + try!(space(&mut self.s)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident.node)); + try!(space(&mut self.s)); + } + if let Some(ref expr) = *opt_expr { + try!(self.print_expr(expr)); + try!(space(&mut self.s)); + } + } + ast::ExprKind::Continue(opt_ident) => { + try!(word(&mut self.s, "continue")); + try!(space(&mut self.s)); + if let Some(ident) = opt_ident { + try!(self.print_ident(ident.node)); + try!(space(&mut self.s)) + } + } + ast::ExprKind::Ret(ref result) => { + try!(word(&mut self.s, "return")); + match *result { + Some(ref expr) => { + try!(word(&mut self.s, " ")); + try!(self.print_expr(&expr)); + } + _ => () + } + } + ast::ExprKind::InlineAsm(ref a) => { + try!(word(&mut self.s, "asm!")); + try!(self.popen()); + try!(self.print_string(&a.asm.as_str(), a.asm_str_style)); + try!(self.word_space(":")); + + try!(self.commasep(Inconsistent, &a.outputs, |s, out| { + let constraint = out.constraint.as_str(); + let mut ch = constraint.chars(); + match ch.next() { + Some('=') if out.is_rw => { + try!(s.print_string(&format!("+{}", ch.as_str()), + ast::StrStyle::Cooked)) + } + _ => try!(s.print_string(&constraint, ast::StrStyle::Cooked)) + } + try!(s.popen()); + try!(s.print_expr(&out.expr)); + try!(s.pclose()); + Ok(()) + })); + try!(space(&mut self.s)); + try!(self.word_space(":")); + + try!(self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| { + try!(s.print_string(&co.as_str(), ast::StrStyle::Cooked)); + try!(s.popen()); + try!(s.print_expr(&o)); + try!(s.pclose()); + Ok(()) + })); + try!(space(&mut self.s)); + try!(self.word_space(":")); + + try!(self.commasep(Inconsistent, &a.clobbers, + |s, co| { + try!(s.print_string(&co.as_str(), ast::StrStyle::Cooked)); + Ok(()) + })); + + let mut options = vec![]; + if a.volatile { + options.push("volatile"); + } + if a.alignstack { + options.push("alignstack"); + } + if a.dialect == ast::AsmDialect::Intel { + options.push("intel"); + } + + if !options.is_empty() { + try!(space(&mut self.s)); + try!(self.word_space(":")); + try!(self.commasep(Inconsistent, &options, + |s, &co| { + try!(s.print_string(co, ast::StrStyle::Cooked)); + Ok(()) + })); + } + + try!(self.pclose()); + } + ast::ExprKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)), + ast::ExprKind::Paren(ref e) => { + try!(self.popen()); + try!(self.print_inner_attributes_inline(attrs)); + try!(self.print_expr(&e)); + try!(self.pclose()); + }, + ast::ExprKind::Try(ref e) => { + try!(self.print_expr(e)); + try!(word(&mut self.s, "?")) + } + } + try!(self.ann.post(self, NodeExpr(expr))); + self.end() + } + + pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> { + try!(self.print_pat(&loc.pat)); + if let Some(ref ty) = loc.ty { + try!(self.word_space(":")); + try!(self.print_type(&ty)); + } + Ok(()) + } + + pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> { + try!(word(&mut self.s, &ident.name.as_str())); + self.ann.post(self, NodeIdent(&ident)) + } + + pub fn print_usize(&mut self, i: usize) -> io::Result<()> { + word(&mut self.s, &i.to_string()) + } + + pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> { + try!(word(&mut self.s, &name.as_str())); + self.ann.post(self, NodeName(&name)) + } + + pub fn print_for_decl(&mut self, loc: &ast::Local, + coll: &ast::Expr) -> io::Result<()> { + try!(self.print_local_decl(loc)); + try!(space(&mut self.s)); + try!(self.word_space("in")); + self.print_expr(coll) + } + + fn print_path(&mut self, + path: &ast::Path, + colons_before_params: bool, + depth: usize, + defaults_to_global: bool) + -> io::Result<()> + { + try!(self.maybe_print_comment(path.span.lo)); + + let mut segments = path.segments[..path.segments.len()-depth].iter(); + if defaults_to_global && path.is_global() { + segments.next(); + } + for (i, segment) in segments.enumerate() { + if i > 0 { + try!(word(&mut self.s, "::")) + } + if segment.identifier.name != keywords::CrateRoot.name() && + segment.identifier.name != "$crate" { + try!(self.print_ident(segment.identifier)); + if let Some(ref parameters) = segment.parameters { + try!(self.print_path_parameters(parameters, colons_before_params)); + } + } + } + + Ok(()) + } + + fn print_qpath(&mut self, + path: &ast::Path, + qself: &ast::QSelf, + colons_before_params: bool) + -> io::Result<()> + { + try!(word(&mut self.s, "<")); + try!(self.print_type(&qself.ty)); + if qself.position > 0 { + try!(space(&mut self.s)); + try!(self.word_space("as")); + let depth = path.segments.len() - qself.position; + try!(self.print_path(&path, false, depth, false)); + } + try!(word(&mut self.s, ">")); + try!(word(&mut self.s, "::")); + let item_segment = path.segments.last().unwrap(); + try!(self.print_ident(item_segment.identifier)); + match item_segment.parameters { + Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params), + None => Ok(()), + } + } + + fn print_path_parameters(&mut self, + parameters: &ast::PathParameters, + colons_before_params: bool) + -> io::Result<()> + { + if colons_before_params { + try!(word(&mut self.s, "::")) + } + + match *parameters { + ast::PathParameters::AngleBracketed(ref data) => { + try!(word(&mut self.s, "<")); + + let mut comma = false; + for lifetime in &data.lifetimes { + if comma { + try!(self.word_space(",")) + } + try!(self.print_lifetime(lifetime)); + comma = true; + } + + if !data.types.is_empty() { + if comma { + try!(self.word_space(",")) + } + try!(self.commasep( + Inconsistent, + &data.types, + |s, ty| s.print_type(&ty))); + comma = true; + } + + for binding in data.bindings.iter() { + if comma { + try!(self.word_space(",")) + } + try!(self.print_ident(binding.ident)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_type(&binding.ty)); + comma = true; + } + + try!(word(&mut self.s, ">")) + } + + ast::PathParameters::Parenthesized(ref data) => { + try!(word(&mut self.s, "(")); + try!(self.commasep( + Inconsistent, + &data.inputs, + |s, ty| s.print_type(&ty))); + try!(word(&mut self.s, ")")); + + if let Some(ref ty) = data.output { + try!(self.space_if_not_bol()); + try!(self.word_space("->")); + try!(self.print_type(&ty)); + } + } + } + + Ok(()) + } + + pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> { + try!(self.maybe_print_comment(pat.span.lo)); + try!(self.ann.pre(self, NodePat(pat))); + /* Pat isn't normalized, but the beauty of it + is that it doesn't matter */ + match pat.node { + PatKind::Wild => try!(word(&mut self.s, "_")), + PatKind::Ident(binding_mode, ref path1, ref sub) => { + match binding_mode { + ast::BindingMode::ByRef(mutbl) => { + try!(self.word_nbsp("ref")); + try!(self.print_mutability(mutbl)); + } + ast::BindingMode::ByValue(ast::Mutability::Immutable) => {} + ast::BindingMode::ByValue(ast::Mutability::Mutable) => { + try!(self.word_nbsp("mut")); + } + } + try!(self.print_ident(path1.node)); + if let Some(ref p) = *sub { + try!(word(&mut self.s, "@")); + try!(self.print_pat(&p)); + } + } + PatKind::TupleStruct(ref path, ref elts, ddpos) => { + try!(self.print_path(path, true, 0, false)); + try!(self.popen()); + if let Some(ddpos) = ddpos { + try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))); + if ddpos != 0 { + try!(self.word_space(",")); + } + try!(word(&mut self.s, "..")); + if ddpos != elts.len() { + try!(word(&mut self.s, ",")); + try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))); + } + } else { + try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))); + } + try!(self.pclose()); + } + PatKind::Path(None, ref path) => { + try!(self.print_path(path, true, 0, false)); + } + PatKind::Path(Some(ref qself), ref path) => { + try!(self.print_qpath(path, qself, false)); + } + PatKind::Struct(ref path, ref fields, etc) => { + try!(self.print_path(path, true, 0, false)); + try!(self.nbsp()); + try!(self.word_space("{")); + try!(self.commasep_cmnt( + Consistent, &fields[..], + |s, f| { + try!(s.cbox(INDENT_UNIT)); + if !f.node.is_shorthand { + try!(s.print_ident(f.node.ident)); + try!(s.word_nbsp(":")); + } + try!(s.print_pat(&f.node.pat)); + s.end() + }, + |f| f.node.pat.span)); + if etc { + if !fields.is_empty() { try!(self.word_space(",")); } + try!(word(&mut self.s, "..")); + } + try!(space(&mut self.s)); + try!(word(&mut self.s, "}")); + } + PatKind::Tuple(ref elts, ddpos) => { + try!(self.popen()); + if let Some(ddpos) = ddpos { + try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))); + if ddpos != 0 { + try!(self.word_space(",")); + } + try!(word(&mut self.s, "..")); + if ddpos != elts.len() { + try!(word(&mut self.s, ",")); + try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))); + } + } else { + try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))); + if elts.len() == 1 { + try!(word(&mut self.s, ",")); + } + } + try!(self.pclose()); + } + PatKind::Box(ref inner) => { + try!(word(&mut self.s, "box ")); + try!(self.print_pat(&inner)); + } + PatKind::Ref(ref inner, mutbl) => { + try!(word(&mut self.s, "&")); + if mutbl == ast::Mutability::Mutable { + try!(word(&mut self.s, "mut ")); + } + try!(self.print_pat(&inner)); + } + PatKind::Lit(ref e) => try!(self.print_expr(&**e)), + PatKind::Range(ref begin, ref end) => { + try!(self.print_expr(&begin)); + try!(space(&mut self.s)); + try!(word(&mut self.s, "...")); + try!(self.print_expr(&end)); + } + PatKind::Slice(ref before, ref slice, ref after) => { + try!(word(&mut self.s, "[")); + try!(self.commasep(Inconsistent, + &before[..], + |s, p| s.print_pat(&p))); + if let Some(ref p) = *slice { + if !before.is_empty() { try!(self.word_space(",")); } + if p.node != PatKind::Wild { + try!(self.print_pat(&p)); + } + try!(word(&mut self.s, "..")); + if !after.is_empty() { try!(self.word_space(",")); } + } + try!(self.commasep(Inconsistent, + &after[..], + |s, p| s.print_pat(&p))); + try!(word(&mut self.s, "]")); + } + PatKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)), + } + self.ann.post(self, NodePat(pat)) + } + + fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> { + // I have no idea why this check is necessary, but here it + // is :( + if arm.attrs.is_empty() { + try!(space(&mut self.s)); + } + try!(self.cbox(INDENT_UNIT)); + try!(self.ibox(0)); + try!(self.maybe_print_comment(arm.pats[0].span.lo)); + try!(self.print_outer_attributes(&arm.attrs)); + let mut first = true; + for p in &arm.pats { + if first { + first = false; + } else { + try!(space(&mut self.s)); + try!(self.word_space("|")); + } + try!(self.print_pat(&p)); + } + try!(space(&mut self.s)); + if let Some(ref e) = arm.guard { + try!(self.word_space("if")); + try!(self.print_expr(&e)); + try!(space(&mut self.s)); + } + try!(self.word_space("=>")); + + match arm.body.node { + ast::ExprKind::Block(ref blk) => { + // the block will close the pattern's ibox + try!(self.print_block_unclosed_indent(&blk, INDENT_UNIT)); + + // If it is a user-provided unsafe block, print a comma after it + if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules { + try!(word(&mut self.s, ",")); + } + } + _ => { + try!(self.end()); // close the ibox for the pattern + try!(self.print_expr(&arm.body)); + try!(word(&mut self.s, ",")); + } + } + self.end() // close enclosing cbox + } + + fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> { + match explicit_self.node { + SelfKind::Value(m) => { + try!(self.print_mutability(m)); + word(&mut self.s, "self") + } + SelfKind::Region(ref lt, m) => { + try!(word(&mut self.s, "&")); + try!(self.print_opt_lifetime(lt)); + try!(self.print_mutability(m)); + word(&mut self.s, "self") + } + SelfKind::Explicit(ref typ, m) => { + try!(self.print_mutability(m)); + try!(word(&mut self.s, "self")); + try!(self.word_space(":")); + self.print_type(&typ) + } + } + } + + pub fn print_fn(&mut self, + decl: &ast::FnDecl, + unsafety: ast::Unsafety, + constness: ast::Constness, + abi: abi::Abi, + name: Option<ast::Ident>, + generics: &ast::Generics, + vis: &ast::Visibility) -> io::Result<()> { + try!(self.print_fn_header_info(unsafety, constness, abi, vis)); + + if let Some(name) = name { + try!(self.nbsp()); + try!(self.print_ident(name)); + } + try!(self.print_generics(generics)); + try!(self.print_fn_args_and_ret(decl)); + self.print_where_clause(&generics.where_clause) + } + + pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl) + -> io::Result<()> { + try!(self.popen()); + try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))); + if decl.variadic { + try!(word(&mut self.s, ", ...")); + } + try!(self.pclose()); + + self.print_fn_output(decl) + } + + pub fn print_fn_block_args( + &mut self, + decl: &ast::FnDecl) + -> io::Result<()> { + try!(word(&mut self.s, "|")); + try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))); + try!(word(&mut self.s, "|")); + + if let ast::FunctionRetTy::Default(..) = decl.output { + return Ok(()); + } + + try!(self.space_if_not_bol()); + try!(self.word_space("->")); + match decl.output { + ast::FunctionRetTy::Ty(ref ty) => { + try!(self.print_type(&ty)); + self.maybe_print_comment(ty.span.lo) + } + ast::FunctionRetTy::Default(..) => unreachable!(), + } + } + + pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) + -> io::Result<()> { + match capture_clause { + ast::CaptureBy::Value => self.word_space("move"), + ast::CaptureBy::Ref => Ok(()), + } + } + + pub fn print_bounds(&mut self, + prefix: &str, + bounds: &[ast::TyParamBound]) + -> io::Result<()> { + if !bounds.is_empty() { + try!(word(&mut self.s, prefix)); + let mut first = true; + for bound in bounds { + try!(self.nbsp()); + if first { + first = false; + } else { + try!(self.word_space("+")); + } + + try!(match *bound { + TraitTyParamBound(ref tref, TraitBoundModifier::None) => { + self.print_poly_trait_ref(tref) + } + TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => { + try!(word(&mut self.s, "?")); + self.print_poly_trait_ref(tref) + } + RegionTyParamBound(ref lt) => { + self.print_lifetime(lt) + } + }) + } + Ok(()) + } else { + Ok(()) + } + } + + pub fn print_lifetime(&mut self, + lifetime: &ast::Lifetime) + -> io::Result<()> + { + self.print_name(lifetime.name) + } + + pub fn print_lifetime_bounds(&mut self, + lifetime: &ast::Lifetime, + bounds: &[ast::Lifetime]) + -> io::Result<()> + { + try!(self.print_lifetime(lifetime)); + if !bounds.is_empty() { + try!(word(&mut self.s, ": ")); + for (i, bound) in bounds.iter().enumerate() { + if i != 0 { + try!(word(&mut self.s, " + ")); + } + try!(self.print_lifetime(bound)); + } + } + Ok(()) + } + + pub fn print_generics(&mut self, + generics: &ast::Generics) + -> io::Result<()> + { + let total = generics.lifetimes.len() + generics.ty_params.len(); + if total == 0 { + return Ok(()); + } + + try!(word(&mut self.s, "<")); + + let mut ints = Vec::new(); + for i in 0..total { + ints.push(i); + } + + try!(self.commasep(Inconsistent, &ints[..], |s, &idx| { + if idx < generics.lifetimes.len() { + let lifetime_def = &generics.lifetimes[idx]; + try!(s.print_outer_attributes_inline(&lifetime_def.attrs)); + s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds) + } else { + let idx = idx - generics.lifetimes.len(); + let param = &generics.ty_params[idx]; + s.print_ty_param(param) + } + })); + + try!(word(&mut self.s, ">")); + Ok(()) + } + + pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> { + try!(self.print_outer_attributes_inline(¶m.attrs)); + try!(self.print_ident(param.ident)); + try!(self.print_bounds(":", ¶m.bounds)); + match param.default { + Some(ref default) => { + try!(space(&mut self.s)); + try!(self.word_space("=")); + self.print_type(&default) + } + _ => Ok(()) + } + } + + pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause) + -> io::Result<()> { + if where_clause.predicates.is_empty() { + return Ok(()) + } + + try!(space(&mut self.s)); + try!(self.word_space("where")); + + for (i, predicate) in where_clause.predicates.iter().enumerate() { + if i != 0 { + try!(self.word_space(",")); + } + + match *predicate { + ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes, + ref bounded_ty, + ref bounds, + ..}) => { + try!(self.print_formal_lifetime_list(bound_lifetimes)); + try!(self.print_type(&bounded_ty)); + try!(self.print_bounds(":", bounds)); + } + ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime, + ref bounds, + ..}) => { + try!(self.print_lifetime_bounds(lifetime, bounds)); + } + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => { + try!(self.print_path(path, false, 0, false)); + try!(space(&mut self.s)); + try!(self.word_space("=")); + try!(self.print_type(&ty)); + } + } + } + + Ok(()) + } + + pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> { + match vp.node { + ast::ViewPathSimple(ident, ref path) => { + try!(self.print_path(path, false, 0, true)); + + if path.segments.last().unwrap().identifier.name != + ident.name { + try!(space(&mut self.s)); + try!(self.word_space("as")); + try!(self.print_ident(ident)); + } + + Ok(()) + } + + ast::ViewPathGlob(ref path) => { + try!(self.print_path(path, false, 0, true)); + word(&mut self.s, "::*") + } + + ast::ViewPathList(ref path, ref idents) => { + if path.segments.is_empty() { + try!(word(&mut self.s, "{")); + } else { + try!(self.print_path(path, false, 0, true)); + try!(word(&mut self.s, "::{")); + } + try!(self.commasep(Inconsistent, &idents[..], |s, w| { + try!(s.print_ident(w.node.name)); + if let Some(ident) = w.node.rename { + try!(space(&mut s.s)); + try!(s.word_space("as")); + try!(s.print_ident(ident)); + } + Ok(()) + })); + word(&mut self.s, "}") + } + } + } + + pub fn print_mutability(&mut self, + mutbl: ast::Mutability) -> io::Result<()> { + match mutbl { + ast::Mutability::Mutable => self.word_nbsp("mut"), + ast::Mutability::Immutable => Ok(()), + } + } + + pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> { + try!(self.print_mutability(mt.mutbl)); + self.print_type(&mt.ty) + } + + pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> { + try!(self.ibox(INDENT_UNIT)); + match input.ty.node { + ast::TyKind::Infer if is_closure => try!(self.print_pat(&input.pat)), + _ => { + if let Some(eself) = input.to_self() { + try!(self.print_explicit_self(&eself)); + } else { + let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node { + ident.node.name == keywords::Invalid.name() + } else { + false + }; + if !invalid { + try!(self.print_pat(&input.pat)); + try!(word(&mut self.s, ":")); + try!(space(&mut self.s)); + } + try!(self.print_type(&input.ty)); + } + } + } + self.end() + } + + pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> { + if let ast::FunctionRetTy::Default(..) = decl.output { + return Ok(()); + } + + try!(self.space_if_not_bol()); + try!(self.ibox(INDENT_UNIT)); + try!(self.word_space("->")); + match decl.output { + ast::FunctionRetTy::Default(..) => unreachable!(), + ast::FunctionRetTy::Ty(ref ty) => + try!(self.print_type(&ty)) + } + try!(self.end()); + + match decl.output { + ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo), + _ => Ok(()) + } + } + + pub fn print_ty_fn(&mut self, + abi: abi::Abi, + unsafety: ast::Unsafety, + decl: &ast::FnDecl, + name: Option<ast::Ident>, + generics: &ast::Generics) + -> io::Result<()> { + try!(self.ibox(INDENT_UNIT)); + if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() { + try!(word(&mut self.s, "for")); + try!(self.print_generics(generics)); + } + let generics = ast::Generics { + lifetimes: Vec::new(), + ty_params: P::new(), + where_clause: ast::WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + }, + span: syntax_pos::DUMMY_SP, + }; + try!(self.print_fn(decl, + unsafety, + ast::Constness::NotConst, + abi, + name, + &generics, + &ast::Visibility::Inherited)); + self.end() + } + + pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span, + next_pos: Option<BytePos>) + -> io::Result<()> { + let cm = match self.cm { + Some(cm) => cm, + _ => return Ok(()) + }; + if let Some(ref cmnt) = self.next_comment() { + if cmnt.style != comments::Trailing { return Ok(()) } + let span_line = cm.lookup_char_pos(span.hi); + let comment_line = cm.lookup_char_pos(cmnt.pos); + let next = next_pos.unwrap_or(cmnt.pos + BytePos(1)); + if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line { + try!(self.print_comment(cmnt)); + self.cur_cmnt_and_lit.cur_cmnt += 1; + } + } + Ok(()) + } + + pub fn print_remaining_comments(&mut self) -> io::Result<()> { + // If there aren't any remaining comments, then we need to manually + // make sure there is a line break at the end. + if self.next_comment().is_none() { + try!(hardbreak(&mut self.s)); + } + loop { + match self.next_comment() { + Some(ref cmnt) => { + try!(self.print_comment(cmnt)); + self.cur_cmnt_and_lit.cur_cmnt += 1; + } + _ => break + } + } + Ok(()) + } + + pub fn print_opt_abi_and_extern_if_nondefault(&mut self, + opt_abi: Option<Abi>) + -> io::Result<()> { + match opt_abi { + Some(Abi::Rust) => Ok(()), + Some(abi) => { + try!(self.word_nbsp("extern")); + self.word_nbsp(&abi.to_string()) + } + None => Ok(()) + } + } + + pub fn print_extern_opt_abi(&mut self, + opt_abi: Option<Abi>) -> io::Result<()> { + match opt_abi { + Some(abi) => { + try!(self.word_nbsp("extern")); + self.word_nbsp(&abi.to_string()) + } + None => Ok(()) + } + } + + pub fn print_fn_header_info(&mut self, + unsafety: ast::Unsafety, + constness: ast::Constness, + abi: Abi, + vis: &ast::Visibility) -> io::Result<()> { + try!(word(&mut self.s, &visibility_qualified(vis, ""))); + + match constness { + ast::Constness::NotConst => {} + ast::Constness::Const => try!(self.word_nbsp("const")) + } + + try!(self.print_unsafety(unsafety)); + + if abi != Abi::Rust { + try!(self.word_nbsp("extern")); + try!(self.word_nbsp(&abi.to_string())); + } + + word(&mut self.s, "fn") + } + + pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> { + match s { + ast::Unsafety::Normal => Ok(()), + ast::Unsafety::Unsafe => self.word_nbsp("unsafe"), + } + } +} + +fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() } + +#[cfg(test)] +mod tests { + use super::*; + + use ast; + use codemap; + use syntax_pos; + + #[test] + fn test_fun_to_string() { + let abba_ident = ast::Ident::from_str("abba"); + + let decl = ast::FnDecl { + inputs: Vec::new(), + output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP), + variadic: false + }; + let generics = ast::Generics::default(); + assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, + ast::Constness::NotConst, + abba_ident, &generics), + "fn abba()"); + } + + #[test] + fn test_variant_to_string() { + let ident = ast::Ident::from_str("principal_skinner"); + + let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ { + name: ident, + attrs: Vec::new(), + // making this up as I go.... ? + data: ast::VariantData::Unit(ast::DUMMY_NODE_ID), + disr_expr: None, + }); + + let varstr = variant_to_string(&var); + assert_eq!(varstr, "principal_skinner"); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/ptr.rs b/bash-5.1/vendor/syntex_syntax/src/ptr.rs new file mode 100644 index 0000000..5875015 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/ptr.rs @@ -0,0 +1,217 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The AST pointer +//! +//! Provides `P<T>`, a frozen owned smart pointer, as a replacement for `@T` in +//! the AST. +//! +//! # Motivations and benefits +//! +//! * **Identity**: sharing AST nodes is problematic for the various analysis +//! passes (e.g. one may be able to bypass the borrow checker with a shared +//! `ExprKind::AddrOf` node taking a mutable borrow). The only reason `@T` in the +//! AST hasn't caused issues is because of inefficient folding passes which +//! would always deduplicate any such shared nodes. Even if the AST were to +//! switch to an arena, this would still hold, i.e. it couldn't use `&'a T`, +//! but rather a wrapper like `P<'a, T>`. +//! +//! * **Immutability**: `P<T>` disallows mutating its inner `T`, unlike `Box<T>` +//! (unless it contains an `Unsafe` interior, but that may be denied later). +//! This mainly prevents mistakes, but can also enforces a kind of "purity". +//! +//! * **Efficiency**: folding can reuse allocation space for `P<T>` and `Vec<T>`, +//! the latter even when the input and output types differ (as it would be the +//! case with arenas or a GADT AST using type parameters to toggle features). +//! +//! * **Maintainability**: `P<T>` provides a fixed interface - `Deref`, +//! `and_then` and `map` - which can remain fully functional even if the +//! implementation changes (using a special thread-local heap, for example). +//! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. + +use std::fmt::{self, Display, Debug}; +use std::iter::FromIterator; +use std::ops::Deref; +use std::{mem, ptr, slice, vec}; + +use serialize::{Encodable, Decodable, Encoder, Decoder}; + +/// An owned smart pointer. +#[derive(Hash, PartialEq, Eq, PartialOrd, Ord)] +pub struct P<T: ?Sized> { + ptr: Box<T> +} + +#[allow(non_snake_case)] +/// Construct a `P<T>` from a `T` value. +pub fn P<T: 'static>(value: T) -> P<T> { + P { + ptr: Box::new(value) + } +} + +impl<T: 'static> P<T> { + /// Move out of the pointer. + /// Intended for chaining transformations not covered by `map`. + pub fn and_then<U, F>(self, f: F) -> U where + F: FnOnce(T) -> U, + { + f(*self.ptr) + } + /// Equivalent to and_then(|x| x) + pub fn unwrap(self) -> T { + *self.ptr + } + + /// Transform the inner value, consuming `self` and producing a new `P<T>`. + pub fn map<F>(mut self, f: F) -> P<T> where + F: FnOnce(T) -> T, + { + let p: *mut T = &mut *self.ptr; + + // Leak self in case of panic. + // FIXME(eddyb) Use some sort of "free guard" that + // only deallocates, without dropping the pointee, + // in case the call the `f` below ends in a panic. + mem::forget(self); + + unsafe { + ptr::write(p, f(ptr::read(p))); + + // Recreate self from the raw pointer. + P { + ptr: Box::from_raw(p) + } + } + } +} + +impl<T: ?Sized> Deref for P<T> { + type Target = T; + + fn deref(&self) -> &T { + &self.ptr + } +} + +impl<T: 'static + Clone> Clone for P<T> { + fn clone(&self) -> P<T> { + P((**self).clone()) + } +} + +impl<T: ?Sized + Debug> Debug for P<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.ptr, f) + } +} + +impl<T: Display> Display for P<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} + +impl<T> fmt::Pointer for P<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Pointer::fmt(&self.ptr, f) + } +} + +impl<T: 'static + Decodable> Decodable for P<T> { + fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> { + Decodable::decode(d).map(P) + } +} + +impl<T: Encodable> Encodable for P<T> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl<T> P<[T]> { + pub fn new() -> P<[T]> { + P { ptr: Default::default() } + } + + #[inline(never)] + pub fn from_vec(v: Vec<T>) -> P<[T]> { + P { ptr: v.into_boxed_slice() } + } + + #[inline(never)] + pub fn into_vec(self) -> Vec<T> { + self.ptr.into_vec() + } +} + +impl<T> Default for P<[T]> { + /// Creates an empty `P<[T]>`. + fn default() -> P<[T]> { + P::new() + } +} + +impl<T: Clone> Clone for P<[T]> { + fn clone(&self) -> P<[T]> { + P::from_vec(self.to_vec()) + } +} + +impl<T> From<Vec<T>> for P<[T]> { + fn from(v: Vec<T>) -> Self { + P::from_vec(v) + } +} + +impl<T> Into<Vec<T>> for P<[T]> { + fn into(self) -> Vec<T> { + self.into_vec() + } +} + +impl<T> FromIterator<T> for P<[T]> { + fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> { + P::from_vec(iter.into_iter().collect()) + } +} + +impl<T> IntoIterator for P<[T]> { + type Item = T; + type IntoIter = vec::IntoIter<T>; + + fn into_iter(self) -> Self::IntoIter { + self.into_vec().into_iter() + } +} + +impl<'a, T> IntoIterator for &'a P<[T]> { + type Item = &'a T; + type IntoIter = slice::Iter<'a, T>; + fn into_iter(self) -> Self::IntoIter { + self.ptr.into_iter() + } +} + +impl<T: Encodable> Encodable for P<[T]> { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + Encodable::encode(&**self, s) + } +} + +impl<T: Decodable> Decodable for P<[T]> { + fn decode<D: Decoder>(d: &mut D) -> Result<P<[T]>, D::Error> { + Ok(P::from_vec(match Decodable::decode(d) { + Ok(t) => t, + Err(e) => return Err(e) + })) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/show_span.rs b/bash-5.1/vendor/syntex_syntax/src/show_span.rs new file mode 100644 index 0000000..263a4f1 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/show_span.rs @@ -0,0 +1,86 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Span debugger +//! +//! This module shows spans for all expressions in the crate +//! to help with compiler debugging. + +use std::str::FromStr; + +use ast; +use errors; +use visit; +use visit::Visitor; + +enum Mode { + Expression, + Pattern, + Type, +} + +impl FromStr for Mode { + type Err = (); + fn from_str(s: &str) -> Result<Mode, ()> { + let mode = match s { + "expr" => Mode::Expression, + "pat" => Mode::Pattern, + "ty" => Mode::Type, + _ => return Err(()) + }; + Ok(mode) + } +} + +struct ShowSpanVisitor<'a> { + span_diagnostic: &'a errors::Handler, + mode: Mode, +} + +impl<'a> Visitor<'a> for ShowSpanVisitor<'a> { + fn visit_expr(&mut self, e: &'a ast::Expr) { + if let Mode::Expression = self.mode { + self.span_diagnostic.span_warn(e.span, "expression"); + } + visit::walk_expr(self, e); + } + + fn visit_pat(&mut self, p: &'a ast::Pat) { + if let Mode::Pattern = self.mode { + self.span_diagnostic.span_warn(p.span, "pattern"); + } + visit::walk_pat(self, p); + } + + fn visit_ty(&mut self, t: &'a ast::Ty) { + if let Mode::Type = self.mode { + self.span_diagnostic.span_warn(t.span, "type"); + } + visit::walk_ty(self, t); + } + + fn visit_mac(&mut self, mac: &'a ast::Mac) { + visit::walk_mac(self, mac); + } +} + +pub fn run(span_diagnostic: &errors::Handler, + mode: &str, + krate: &ast::Crate) { + let mode = match mode.parse().ok() { + Some(mode) => mode, + None => return + }; + let mut v = ShowSpanVisitor { + span_diagnostic: span_diagnostic, + mode: mode, + }; + visit::walk_crate(&mut v, krate); +} diff --git a/bash-5.1/vendor/syntex_syntax/src/std_inject.rs b/bash-5.1/vendor/syntex_syntax/src/std_inject.rs new file mode 100644 index 0000000..68d807b --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/std_inject.rs @@ -0,0 +1,94 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast; +use attr; +use symbol::{Symbol, keywords}; +use syntax_pos::{DUMMY_SP, Span}; +use codemap::{self, ExpnInfo, NameAndSpan, MacroAttribute}; +use parse::ParseSess; +use ptr::P; + +/// Craft a span that will be ignored by the stability lint's +/// call to codemap's is_internal check. +/// The expanded code uses the unstable `#[prelude_import]` attribute. +fn ignored_span(sess: &ParseSess, sp: Span) -> Span { + let info = ExpnInfo { + call_site: DUMMY_SP, + callee: NameAndSpan { + format: MacroAttribute(Symbol::intern("std_inject")), + span: None, + allow_internal_unstable: true, + } + }; + let expn_id = sess.codemap().record_expansion(info); + let mut sp = sp; + sp.expn_id = expn_id; + return sp; +} + +pub fn injected_crate_name(krate: &ast::Crate) -> Option<&'static str> { + if attr::contains_name(&krate.attrs, "no_core") { + None + } else if attr::contains_name(&krate.attrs, "no_std") { + Some("core") + } else { + Some("std") + } +} + +pub fn maybe_inject_crates_ref(sess: &ParseSess, + mut krate: ast::Crate, + alt_std_name: Option<String>) + -> ast::Crate { + let name = match injected_crate_name(&krate) { + Some(name) => name, + None => return krate, + }; + + let crate_name = Symbol::intern(&alt_std_name.unwrap_or(name.to_string())); + + krate.module.items.insert(0, P(ast::Item { + attrs: vec![attr::mk_attr_outer(attr::mk_attr_id(), + attr::mk_word_item(Symbol::intern("macro_use")))], + vis: ast::Visibility::Inherited, + node: ast::ItemKind::ExternCrate(Some(crate_name)), + ident: ast::Ident::from_str(name), + id: ast::DUMMY_NODE_ID, + span: DUMMY_SP, + })); + + let span = ignored_span(sess, DUMMY_SP); + krate.module.items.insert(0, P(ast::Item { + attrs: vec![ast::Attribute { + style: ast::AttrStyle::Outer, + value: ast::MetaItem { + name: Symbol::intern("prelude_import"), + node: ast::MetaItemKind::Word, + span: span, + }, + id: attr::mk_attr_id(), + is_sugared_doc: false, + span: span, + }], + vis: ast::Visibility::Inherited, + node: ast::ItemKind::Use(P(codemap::dummy_spanned(ast::ViewPathGlob(ast::Path { + segments: ["{{root}}", name, "prelude", "v1"].into_iter().map(|name| { + ast::Ident::from_str(name).into() + }).collect(), + span: span, + })))), + id: ast::DUMMY_NODE_ID, + ident: keywords::Invalid.ident(), + span: span, + })); + + krate +} diff --git a/bash-5.1/vendor/syntex_syntax/src/str.rs b/bash-5.1/vendor/syntex_syntax/src/str.rs new file mode 100644 index 0000000..0955065 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/str.rs @@ -0,0 +1,24 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub fn char_at(s: &str, byte: usize) -> char { + s[byte..].chars().next().unwrap() +} + +// FIXME: This was copied from core/str/mod.rs because it is currently unstable. +#[inline] +pub fn slice_shift_char(s: &str) -> Option<(char, &str)> { + if s.is_empty() { + None + } else { + let ch = char_at(s, 0); + Some((ch, &s[ch.len_utf8()..])) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/symbol.rs b/bash-5.1/vendor/syntex_syntax/src/symbol.rs new file mode 100644 index 0000000..d37ca18 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/symbol.rs @@ -0,0 +1,312 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! An "interner" is a data structure that associates values with usize tags and +//! allows bidirectional lookup; i.e. given a value, one can easily find the +//! type, and vice versa. + +use serialize::{Decodable, Decoder, Encodable, Encoder}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::fmt; + +/// A symbol is an interned or gensymed string. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Symbol(u32); + +// FIXME syntex +// The interner in thread-local, so `Symbol` shouldn't move between threads. +// impl !Send for Symbol { } + +impl Symbol { + /// Maps a string to its interned representation. + pub fn intern(string: &str) -> Self { + with_interner(|interner| interner.intern(string)) + } + + /// gensym's a new usize, using the current interner. + pub fn gensym(string: &str) -> Self { + with_interner(|interner| interner.gensym(string)) + } + + pub fn as_str(self) -> InternedString { + with_interner(|interner| unsafe { + InternedString { + string: ::std::mem::transmute::<&str, &str>(interner.get(self)) + } + }) + } + + pub fn as_u32(self) -> u32 { + self.0 + } +} + +impl fmt::Debug for Symbol { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}({})", self, self.0) + } +} + +impl fmt::Display for Symbol { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.as_str(), f) + } +} + +impl Encodable for Symbol { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_str(&self.as_str()) + } +} + +impl Decodable for Symbol { + fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> { + Ok(Symbol::intern(&try!(d.read_str()))) + } +} + +impl<'a> PartialEq<&'a str> for Symbol { + fn eq(&self, other: &&str) -> bool { + *self.as_str() == **other + } +} + +#[derive(Default)] +pub struct Interner { + names: HashMap<Box<str>, Symbol>, + strings: Vec<Box<str>>, +} + +impl Interner { + pub fn new() -> Self { + Interner::default() + } + + fn prefill(init: &[&str]) -> Self { + let mut this = Interner::new(); + for &string in init { + this.intern(string); + } + this + } + + pub fn intern(&mut self, string: &str) -> Symbol { + if let Some(&name) = self.names.get(string) { + return name; + } + + let name = Symbol(self.strings.len() as u32); + let string = string.to_string().into_boxed_str(); + self.strings.push(string.clone()); + self.names.insert(string, name); + name + } + + fn gensym(&mut self, string: &str) -> Symbol { + let gensym = Symbol(self.strings.len() as u32); + // leave out of `names` to avoid colliding + self.strings.push(string.to_string().into_boxed_str()); + gensym + } + + pub fn get(&self, name: Symbol) -> &str { + &self.strings[name.0 as usize] + } +} + +// In this macro, there is the requirement that the name (the number) must be monotonically +// increasing by one in the special identifiers, starting at 0; the same holds for the keywords, +// except starting from the next number instead of zero. +macro_rules! declare_keywords {( + $( ($index: expr, $konst: ident, $string: expr) )* +) => { + pub mod keywords { + use ast; + use ext; + #[derive(Clone, Copy, PartialEq, Eq)] + pub struct Keyword { + ident: ast::Ident, + } + impl Keyword { + #[inline] pub fn ident(self) -> ast::Ident { self.ident } + #[inline] pub fn name(self) -> ast::Name { self.ident.name } + } + $( + #[allow(non_upper_case_globals)] + pub const $konst: Keyword = Keyword { + ident: ast::Ident { + name: ast::Name($index), + ctxt: ext::hygiene::SyntaxContext(0), + } + }; + )* + } + + impl Interner { + fn fresh() -> Self { + Interner::prefill(&[$($string,)*]) + } + } +}} + +// NB: leaving holes in the ident table is bad! a different ident will get +// interned with the id from the hole, but it will be between the min and max +// of the reserved words, and thus tagged as "reserved". +// After modifying this list adjust `is_strict_keyword`/`is_reserved_keyword`, +// this should be rarely necessary though if the keywords are kept in alphabetic order. +declare_keywords! { + // Invalid identifier + (0, Invalid, "") + + // Strict keywords used in the language. + (1, As, "as") + (2, Box, "box") + (3, Break, "break") + (4, Const, "const") + (5, Continue, "continue") + (6, Crate, "crate") + (7, Else, "else") + (8, Enum, "enum") + (9, Extern, "extern") + (10, False, "false") + (11, Fn, "fn") + (12, For, "for") + (13, If, "if") + (14, Impl, "impl") + (15, In, "in") + (16, Let, "let") + (17, Loop, "loop") + (18, Match, "match") + (19, Mod, "mod") + (20, Move, "move") + (21, Mut, "mut") + (22, Pub, "pub") + (23, Ref, "ref") + (24, Return, "return") + (25, SelfValue, "self") + (26, SelfType, "Self") + (27, Static, "static") + (28, Struct, "struct") + (29, Super, "super") + (30, Trait, "trait") + (31, True, "true") + (32, Type, "type") + (33, Unsafe, "unsafe") + (34, Use, "use") + (35, Where, "where") + (36, While, "while") + + // Keywords reserved for future use. + (37, Abstract, "abstract") + (38, Alignof, "alignof") + (39, Become, "become") + (40, Do, "do") + (41, Final, "final") + (42, Macro, "macro") + (43, Offsetof, "offsetof") + (44, Override, "override") + (45, Priv, "priv") + (46, Proc, "proc") + (47, Pure, "pure") + (48, Sizeof, "sizeof") + (49, Typeof, "typeof") + (50, Unsized, "unsized") + (51, Virtual, "virtual") + (52, Yield, "yield") + + // Weak keywords, have special meaning only in specific contexts. + (53, Default, "default") + (54, StaticLifetime, "'static") + (55, Union, "union") + + // A virtual keyword that resolves to the crate root when used in a lexical scope. + (56, CrateRoot, "{{root}}") +} + +// If an interner exists in TLS, return it. Otherwise, prepare a fresh one. +fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T { + thread_local!(static INTERNER: RefCell<Interner> = { + RefCell::new(Interner::fresh()) + }); + INTERNER.with(|interner| f(&mut *interner.borrow_mut())) +} + +/// Represents a string stored in the thread-local interner. Because the +/// interner lives for the life of the thread, this can be safely treated as an +/// immortal string, as long as it never crosses between threads. +/// +/// FIXME(pcwalton): You must be careful about what you do in the destructors +/// of objects stored in TLS, because they may run after the interner is +/// destroyed. In particular, they must not access string contents. This can +/// be fixed in the future by just leaking all strings until thread death +/// somehow. +#[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)] +pub struct InternedString { + string: &'static str, +} + +// FIXME syntex +// impl !Send for InternedString { } + +impl ::std::ops::Deref for InternedString { + type Target = str; + fn deref(&self) -> &str { self.string } +} + +impl fmt::Debug for InternedString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(self.string, f) + } +} + +impl fmt::Display for InternedString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self.string, f) + } +} + +impl Decodable for InternedString { + fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> { + Ok(Symbol::intern(&try!(d.read_str())).as_str()) + } +} + +impl Encodable for InternedString { + fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { + s.emit_str(self.string) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ast::Name; + + #[test] + fn interner_tests() { + let mut i: Interner = Interner::new(); + // first one is zero: + assert_eq!(i.intern("dog"), Name(0)); + // re-use gets the same entry: + assert_eq!(i.intern ("dog"), Name(0)); + // different string gets a different #: + assert_eq!(i.intern("cat"), Name(1)); + assert_eq!(i.intern("cat"), Name(1)); + // dog is still at zero + assert_eq!(i.intern("dog"), Name(0)); + // gensym gets 3 + assert_eq!(i.gensym("zebra"), Name(2)); + // gensym of same string gets new number : + assert_eq!(i.gensym("zebra"), Name(3)); + // gensym of *existing* string gets new number: + assert_eq!(i.gensym("dog"), Name(4)); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/test.rs b/bash-5.1/vendor/syntex_syntax/src/test.rs new file mode 100644 index 0000000..b8e0b93 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/test.rs @@ -0,0 +1,718 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Code that generates a test runner to run all the tests in a crate + +#![allow(dead_code)] +#![allow(unused_imports)] + +use self::HasTestSignature::*; + +use std::iter; +use std::slice; +use std::mem; +use std::vec; +use attr::{self, HasAttrs}; +use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, FileMap, BytePos}; +use std::rc::Rc; + +use codemap::{self, CodeMap, ExpnInfo, NameAndSpan, MacroAttribute, dummy_spanned}; +use errors; +use errors::snippet::{SnippetData}; +use config; +use entry::{self, EntryPointType}; +use ext::base::{ExtCtxt, Resolver}; +use ext::build::AstBuilder; +use ext::expand::ExpansionConfig; +use fold::Folder; +use util::move_map::MoveMap; +use fold; +use parse::{token, ParseSess}; +use print::pprust; +use ast::{self, Ident}; +use ptr::P; +use symbol::{self, Symbol, keywords}; +use util::small_vector::SmallVector; + +enum ShouldPanic { + No, + Yes(Option<Symbol>), +} + +struct Test { + span: Span, + path: Vec<Ident> , + bench: bool, + ignore: bool, + should_panic: ShouldPanic +} + +struct TestCtxt<'a> { + sess: &'a ParseSess, + span_diagnostic: &'a errors::Handler, + path: Vec<Ident>, + ext_cx: ExtCtxt<'a>, + testfns: Vec<Test>, + reexport_test_harness_main: Option<Symbol>, + is_test_crate: bool, + + // top-level re-export submodule, filled out after folding is finished + toplevel_reexport: Option<Ident>, +} + +// Traverse the crate, collecting all the test functions, eliding any +// existing main functions, and synthesizing a main test harness +pub fn modify_for_testing(sess: &ParseSess, + resolver: &mut Resolver, + should_test: bool, + krate: ast::Crate, + span_diagnostic: &errors::Handler) -> ast::Crate { + // Check for #[reexport_test_harness_main = "some_name"] which + // creates a `use some_name = __test::main;`. This needs to be + // unconditional, so that the attribute is still marked as used in + // non-test builds. + let reexport_test_harness_main = + attr::first_attr_value_str_by_name(&krate.attrs, + "reexport_test_harness_main"); + + if should_test { + generate_test_harness(sess, resolver, reexport_test_harness_main, krate, span_diagnostic) + } else { + krate + } +} + +struct TestHarnessGenerator<'a> { + cx: TestCtxt<'a>, + tests: Vec<Ident>, + + // submodule name, gensym'd identifier for re-exports + tested_submods: Vec<(Ident, Ident)>, +} + +impl<'a> fold::Folder for TestHarnessGenerator<'a> { + fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate { + let mut folded = fold::noop_fold_crate(c, self); + + // Add a special __test module to the crate that will contain code + // generated for the test harness + let (mod_, reexport) = mk_test_module(&mut self.cx); + match reexport { + Some(re) => folded.module.items.push(re), + None => {} + } + folded.module.items.push(mod_); + folded + } + + fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> { + let ident = i.ident; + if ident.name != keywords::Invalid.name() { + self.cx.path.push(ident); + } + debug!("current path: {}", path_name_i(&self.cx.path)); + + if is_test_fn(&self.cx, &i) || is_bench_fn(&self.cx, &i) { + match i.node { + ast::ItemKind::Fn(_, ast::Unsafety::Unsafe, _, _, _, _) => { + let diag = self.cx.span_diagnostic; + panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests")); + } + _ => { + debug!("this is a test function"); + let test = Test { + span: i.span, + path: self.cx.path.clone(), + bench: is_bench_fn(&self.cx, &i), + ignore: is_ignored(&i), + should_panic: should_panic(&i, &self.cx) + }; + self.cx.testfns.push(test); + self.tests.push(i.ident); + } + } + } + + let mut item = i.unwrap(); + // We don't want to recurse into anything other than mods, since + // mods or tests inside of functions will break things + if let ast::ItemKind::Mod(module) = item.node { + let tests = mem::replace(&mut self.tests, Vec::new()); + let tested_submods = mem::replace(&mut self.tested_submods, Vec::new()); + let mut mod_folded = fold::noop_fold_mod(module, self); + let tests = mem::replace(&mut self.tests, tests); + let tested_submods = mem::replace(&mut self.tested_submods, tested_submods); + + if !tests.is_empty() || !tested_submods.is_empty() { + let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods); + mod_folded.items.push(it); + + if !self.cx.path.is_empty() { + self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym)); + } else { + debug!("pushing nothing, sym: {:?}", sym); + self.cx.toplevel_reexport = Some(sym); + } + } + item.node = ast::ItemKind::Mod(mod_folded); + } + if ident.name != keywords::Invalid.name() { + self.cx.path.pop(); + } + SmallVector::one(P(item)) + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac } +} + +struct EntryPointCleaner { + // Current depth in the ast + depth: usize, +} + +impl fold::Folder for EntryPointCleaner { + fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> { + self.depth += 1; + let folded = fold::noop_fold_item(i, self).expect_one("noop did something"); + self.depth -= 1; + + // Remove any #[main] or #[start] from the AST so it doesn't + // clash with the one we're going to add, but mark it as + // #[allow(dead_code)] to avoid printing warnings. + let folded = match entry::entry_point_type(&folded, self.depth) { + EntryPointType::MainNamed | + EntryPointType::MainAttr | + EntryPointType::Start => + folded.map(|ast::Item {id, ident, attrs, node, vis, span}| { + let allow_str = Symbol::intern("allow"); + let dead_code_str = Symbol::intern("dead_code"); + let word_vec = vec![attr::mk_list_word_item(dead_code_str)]; + let allow_dead_code_item = attr::mk_list_item(allow_str, word_vec); + let allow_dead_code = attr::mk_attr_outer(attr::mk_attr_id(), + allow_dead_code_item); + + ast::Item { + id: id, + ident: ident, + attrs: attrs.into_iter() + .filter(|attr| { + !attr.check_name("main") && !attr.check_name("start") + }) + .chain(iter::once(allow_dead_code)) + .collect(), + node: node, + vis: vis, + span: span + } + }), + EntryPointType::None | + EntryPointType::OtherMain => folded, + }; + + SmallVector::one(folded) + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac } +} + +fn mk_reexport_mod(cx: &mut TestCtxt, + parent: ast::NodeId, + tests: Vec<Ident>, + tested_submods: Vec<(Ident, Ident)>) + -> (P<ast::Item>, Ident) { + let super_ = Ident::from_str("super"); + + // Generate imports with `#[allow(private_in_public)]` to work around issue #36768. + let allow_private_in_public = cx.ext_cx.attribute(DUMMY_SP, cx.ext_cx.meta_list( + DUMMY_SP, + Symbol::intern("allow"), + vec![cx.ext_cx.meta_list_item_word(DUMMY_SP, Symbol::intern("private_in_public"))], + )); + let items = tests.into_iter().map(|r| { + cx.ext_cx.item_use_simple(DUMMY_SP, ast::Visibility::Public, + cx.ext_cx.path(DUMMY_SP, vec![super_, r])) + .map_attrs(|_| vec![allow_private_in_public.clone()]) + }).chain(tested_submods.into_iter().map(|(r, sym)| { + let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]); + cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Visibility::Public, r, path) + .map_attrs(|_| vec![allow_private_in_public.clone()]) + })).collect(); + + let reexport_mod = ast::Mod { + inner: DUMMY_SP, + items: items, + }; + + let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports")); + let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent }; + cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent); + let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item { + ident: sym.clone(), + attrs: Vec::new(), + id: ast::DUMMY_NODE_ID, + node: ast::ItemKind::Mod(reexport_mod), + vis: ast::Visibility::Public, + span: DUMMY_SP, + })).pop().unwrap(); + + (it, sym) +} + +fn generate_test_harness(sess: &ParseSess, + resolver: &mut Resolver, + reexport_test_harness_main: Option<Symbol>, + krate: ast::Crate, + sd: &errors::Handler) -> ast::Crate { + // Remove the entry points + let mut cleaner = EntryPointCleaner { depth: 0 }; + let krate = cleaner.fold_crate(krate); + + let mut cx: TestCtxt = TestCtxt { + sess: sess, + span_diagnostic: sd, + ext_cx: ExtCtxt::new(sess, ExpansionConfig::default("test".to_string()), resolver), + path: Vec::new(), + testfns: Vec::new(), + reexport_test_harness_main: reexport_test_harness_main, + is_test_crate: is_test_crate(&krate), + toplevel_reexport: None, + }; + cx.ext_cx.crate_root = Some("std"); + + cx.ext_cx.bt_push(ExpnInfo { + call_site: DUMMY_SP, + callee: NameAndSpan { + format: MacroAttribute(Symbol::intern("test")), + span: None, + allow_internal_unstable: false, + } + }); + + TestHarnessGenerator { + cx: cx, + tests: Vec::new(), + tested_submods: Vec::new(), + }.fold_crate(krate) +} + +/// Craft a span that will be ignored by the stability lint's +/// call to codemap's is_internal check. +/// The expanded code calls some unstable functions in the test crate. +fn ignored_span(cx: &TestCtxt, sp: Span) -> Span { + let info = ExpnInfo { + call_site: sp, + callee: NameAndSpan { + format: MacroAttribute(Symbol::intern("test")), + span: None, + allow_internal_unstable: true, + } + }; + let expn_id = cx.sess.codemap().record_expansion(info); + let mut sp = sp; + sp.expn_id = expn_id; + return sp; +} + +#[derive(PartialEq)] +enum HasTestSignature { + Yes, + No, + NotEvenAFunction, +} + +fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { + let has_test_attr = attr::contains_name(&i.attrs, "test"); + + fn has_test_signature(i: &ast::Item) -> HasTestSignature { + match i.node { + ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => { + let no_output = match decl.output { + ast::FunctionRetTy::Default(..) => true, + ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true, + _ => false + }; + if decl.inputs.is_empty() + && no_output + && !generics.is_parameterized() { + Yes + } else { + No + } + } + _ => NotEvenAFunction, + } + } + + if has_test_attr { + let diag = cx.span_diagnostic; + match has_test_signature(i) { + Yes => {}, + No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"), + NotEvenAFunction => diag.span_err(i.span, + "only functions may be used as tests"), + } + } + + return has_test_attr && has_test_signature(i) == Yes; +} + +fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { + let has_bench_attr = attr::contains_name(&i.attrs, "bench"); + + fn has_test_signature(i: &ast::Item) -> bool { + match i.node { + ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => { + let input_cnt = decl.inputs.len(); + let no_output = match decl.output { + ast::FunctionRetTy::Default(..) => true, + ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true, + _ => false + }; + let tparm_cnt = generics.ty_params.len(); + // NB: inadequate check, but we're running + // well before resolve, can't get too deep. + input_cnt == 1 + && no_output && tparm_cnt == 0 + } + _ => false + } + } + + if has_bench_attr && !has_test_signature(i) { + let diag = cx.span_diagnostic; + diag.span_err(i.span, "functions used as benches must have signature \ + `fn(&mut Bencher) -> ()`"); + } + + return has_bench_attr && has_test_signature(i); +} + +fn is_ignored(i: &ast::Item) -> bool { + i.attrs.iter().any(|attr| attr.check_name("ignore")) +} + +fn should_panic(i: &ast::Item, cx: &TestCtxt) -> ShouldPanic { + match i.attrs.iter().find(|attr| attr.check_name("should_panic")) { + Some(attr) => { + let sd = cx.span_diagnostic; + if attr.is_value_str() { + sd.struct_span_warn( + attr.span(), + "attribute must be of the form: \ + `#[should_panic]` or \ + `#[should_panic(expected = \"error message\")]`" + ).note("Errors in this attribute were erroneously allowed \ + and will become a hard error in a future release.") + .emit(); + return ShouldPanic::Yes(None); + } + match attr.meta_item_list() { + // Handle #[should_panic] + None => ShouldPanic::Yes(None), + // Handle #[should_panic(expected = "foo")] + Some(list) => { + let msg = list.iter() + .find(|mi| mi.check_name("expected")) + .and_then(|mi| mi.meta_item()) + .and_then(|mi| mi.value_str()); + if list.len() != 1 || msg.is_none() { + sd.struct_span_warn( + attr.span(), + "argument must be of the form: \ + `expected = \"error message\"`" + ).note("Errors in this attribute were erroneously \ + allowed and will become a hard error in a \ + future release.").emit(); + ShouldPanic::Yes(None) + } else { + ShouldPanic::Yes(msg) + } + }, + } + } + None => ShouldPanic::No, + } +} + +/* + +We're going to be building a module that looks more or less like: + +mod __test { + extern crate test (name = "test", vers = "..."); + fn main() { + test::test_main_static(&::os::args()[], tests) + } + + static tests : &'static [test::TestDescAndFn] = &[ + ... the list of tests in the crate ... + ]; +} + +*/ + +fn mk_std(cx: &TestCtxt) -> P<ast::Item> { + let id_test = Ident::from_str("test"); + let sp = ignored_span(cx, DUMMY_SP); + let (vi, vis, ident) = if cx.is_test_crate { + (ast::ItemKind::Use( + P(nospan(ast::ViewPathSimple(id_test, + path_node(vec![id_test]))))), + ast::Visibility::Public, keywords::Invalid.ident()) + } else { + (ast::ItemKind::ExternCrate(None), ast::Visibility::Inherited, id_test) + }; + P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: ident, + node: vi, + attrs: vec![], + vis: vis, + span: sp + }) +} + +fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> { + // Writing this out by hand with 'ignored_span': + // pub fn main() { + // #![main] + // use std::slice::AsSlice; + // test::test_main_static(::std::os::args().as_slice(), TESTS); + // } + + let sp = ignored_span(cx, DUMMY_SP); + let ecx = &cx.ext_cx; + + // test::test_main_static + let test_main_path = + ecx.path(sp, vec![Ident::from_str("test"), Ident::from_str("test_main_static")]); + + // test::test_main_static(...) + let test_main_path_expr = ecx.expr_path(test_main_path); + let tests_ident_expr = ecx.expr_ident(sp, Ident::from_str("TESTS")); + let call_test_main = ecx.expr_call(sp, test_main_path_expr, + vec![tests_ident_expr]); + let call_test_main = ecx.stmt_expr(call_test_main); + // #![main] + let main_meta = ecx.meta_word(sp, Symbol::intern("main")); + let main_attr = ecx.attribute(sp, main_meta); + // pub fn main() { ... } + let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![])); + let main_body = ecx.block(sp, vec![call_test_main]); + let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], main_ret_ty), + ast::Unsafety::Normal, + dummy_spanned(ast::Constness::NotConst), + ::abi::Abi::Rust, ast::Generics::default(), main_body); + let main = P(ast::Item { + ident: Ident::from_str("main"), + attrs: vec![main_attr], + id: ast::DUMMY_NODE_ID, + node: main, + vis: ast::Visibility::Public, + span: sp + }); + + return main; +} + +fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) { + // Link to test crate + let import = mk_std(cx); + + // A constant vector of test descriptors. + let tests = mk_tests(cx); + + // The synthesized main function which will call the console test runner + // with our list of tests + let mainfn = mk_main(cx); + + let testmod = ast::Mod { + inner: DUMMY_SP, + items: vec![import, mainfn, tests], + }; + let item_ = ast::ItemKind::Mod(testmod); + let mod_ident = Ident::with_empty_ctxt(Symbol::gensym("__test")); + + let mut expander = cx.ext_cx.monotonic_expander(); + let item = expander.fold_item(P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: mod_ident, + attrs: vec![], + node: item_, + vis: ast::Visibility::Public, + span: DUMMY_SP, + })).pop().unwrap(); + let reexport = cx.reexport_test_harness_main.map(|s| { + // building `use <ident> = __test::main` + let reexport_ident = Ident::with_empty_ctxt(s); + + let use_path = + nospan(ast::ViewPathSimple(reexport_ident, + path_node(vec![mod_ident, Ident::from_str("main")]))); + + expander.fold_item(P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: keywords::Invalid.ident(), + attrs: vec![], + node: ast::ItemKind::Use(P(use_path)), + vis: ast::Visibility::Inherited, + span: DUMMY_SP + })).pop().unwrap() + }); + + debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); + + (item, reexport) +} + +fn nospan<T>(t: T) -> codemap::Spanned<T> { + codemap::Spanned { node: t, span: DUMMY_SP } +} + +fn path_node(ids: Vec<Ident>) -> ast::Path { + ast::Path { + span: DUMMY_SP, + segments: ids.into_iter().map(Into::into).collect(), + } +} + +fn path_name_i(idents: &[Ident]) -> String { + // FIXME: Bad copies (#2543 -- same for everything else that says "bad") + idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::") +} + +fn mk_tests(cx: &TestCtxt) -> P<ast::Item> { + // The vector of test_descs for this crate + let test_descs = mk_test_descs(cx); + + // FIXME #15962: should be using quote_item, but that stringifies + // __test_reexports, causing it to be reinterned, losing the + // gensym information. + let sp = ignored_span(cx, DUMMY_SP); + let ecx = &cx.ext_cx; + let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"), + ecx.ident_of("test"), + ecx.ident_of("TestDescAndFn")])); + let static_lt = ecx.lifetime(sp, keywords::StaticLifetime.name()); + // &'static [self::test::TestDescAndFn] + let static_type = ecx.ty_rptr(sp, + ecx.ty(sp, ast::TyKind::Slice(struct_type)), + Some(static_lt), + ast::Mutability::Immutable); + // static TESTS: $static_type = &[...]; + ecx.item_const(sp, + ecx.ident_of("TESTS"), + static_type, + test_descs) +} + +fn is_test_crate(krate: &ast::Crate) -> bool { + match attr::find_crate_name(&krate.attrs) { + Some(s) if "test" == &*s.as_str() => true, + _ => false + } +} + +fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> { + debug!("building test vector from {} tests", cx.testfns.len()); + + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::AddrOf(ast::Mutability::Immutable, + P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: ast::ExprKind::Vec(cx.testfns.iter().map(|test| { + mk_test_desc_and_fn_rec(cx, test) + }).collect()), + span: DUMMY_SP, + attrs: ast::ThinVec::new(), + })), + span: DUMMY_SP, + attrs: ast::ThinVec::new(), + }) +} + +fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> { + // FIXME #15962: should be using quote_expr, but that stringifies + // __test_reexports, causing it to be reinterned, losing the + // gensym information. + + let span = ignored_span(cx, test.span); + let path = test.path.clone(); + let ecx = &cx.ext_cx; + let self_id = ecx.ident_of("self"); + let test_id = ecx.ident_of("test"); + + // creates self::test::$name + let test_path = |name| { + ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)]) + }; + // creates $name: $expr + let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr); + + debug!("encoding {}", path_name_i(&path[..])); + + // path to the #[test] function: "foo::bar::baz" + let path_string = path_name_i(&path[..]); + let name_expr = ecx.expr_str(span, Symbol::intern(&path_string)); + + // self::test::StaticTestName($name_expr) + let name_expr = ecx.expr_call(span, + ecx.expr_path(test_path("StaticTestName")), + vec![name_expr]); + + let ignore_expr = ecx.expr_bool(span, test.ignore); + let should_panic_path = |name| { + ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldPanic"), ecx.ident_of(name)]) + }; + let fail_expr = match test.should_panic { + ShouldPanic::No => ecx.expr_path(should_panic_path("No")), + ShouldPanic::Yes(msg) => { + match msg { + Some(msg) => { + let msg = ecx.expr_str(span, msg); + let path = should_panic_path("YesWithMessage"); + ecx.expr_call(span, ecx.expr_path(path), vec![msg]) + } + None => ecx.expr_path(should_panic_path("Yes")), + } + } + }; + + // self::test::TestDesc { ... } + let desc_expr = ecx.expr_struct( + span, + test_path("TestDesc"), + vec![field("name", name_expr), + field("ignore", ignore_expr), + field("should_panic", fail_expr)]); + + + let mut visible_path = match cx.toplevel_reexport { + Some(id) => vec![id], + None => { + let diag = cx.span_diagnostic; + diag.bug("expected to find top-level re-export name, but found None"); + } + }; + visible_path.extend(path); + + let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path)); + + let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" }; + // self::test::$variant_name($fn_expr) + let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]); + + // self::test::TestDescAndFn { ... } + ecx.expr_struct(span, + test_path("TestDescAndFn"), + vec![field("desc", desc_expr), + field("testfn", testfn_expr)]) +} diff --git a/bash-5.1/vendor/syntex_syntax/src/test_snippet.rs b/bash-5.1/vendor/syntex_syntax/src/test_snippet.rs new file mode 100644 index 0000000..98e5748 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/test_snippet.rs @@ -0,0 +1,546 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use codemap::CodeMap; +use errors::Handler; +use errors::emitter::EmitterWriter; +use std::io; +use std::io::prelude::*; +use std::rc::Rc; +use std::str; +use std::sync::{Arc, Mutex}; +use syntax_pos::{BytePos, NO_EXPANSION, Span, MultiSpan}; + +/// Identify a position in the text by the Nth occurrence of a string. +struct Position { + string: &'static str, + count: usize, +} + +struct SpanLabel { + start: Position, + end: Position, + label: &'static str, +} + +struct Shared<T: Write> { + data: Arc<Mutex<T>>, +} + +impl<T: Write> Write for Shared<T> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.data.lock().unwrap().write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.data.lock().unwrap().flush() + } +} + +fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) { + let output = Arc::new(Mutex::new(Vec::new())); + + let code_map = Rc::new(CodeMap::new()); + code_map.new_filemap_and_lines("test.rs", None, &file_text); + + let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end); + let mut msp = MultiSpan::from_span(primary_span); + for span_label in span_labels { + let span = make_span(&file_text, &span_label.start, &span_label.end); + msp.push_span_label(span, span_label.label.to_string()); + println!("span: {:?} label: {:?}", span, span_label.label); + println!("text: {:?}", code_map.span_to_snippet(span)); + } + + let emitter = EmitterWriter::new(Box::new(Shared { data: output.clone() }), + Some(code_map.clone())); + let handler = Handler::with_emitter(true, false, Box::new(emitter)); + handler.span_err(msp, "foo"); + + assert!(expected_output.chars().next() == Some('\n'), + "expected output should begin with newline"); + let expected_output = &expected_output[1..]; + + let bytes = output.lock().unwrap(); + let actual_output = str::from_utf8(&bytes).unwrap(); + println!("expected output:\n------\n{}------", expected_output); + println!("actual output:\n------\n{}------", actual_output); + + assert!(expected_output == actual_output) +} + +fn make_span(file_text: &str, start: &Position, end: &Position) -> Span { + let start = make_pos(file_text, start); + let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends + assert!(start <= end); + Span { + lo: BytePos(start as u32), + hi: BytePos(end as u32), + expn_id: NO_EXPANSION, + } +} + +fn make_pos(file_text: &str, pos: &Position) -> usize { + let mut remainder = file_text; + let mut offset = 0; + for _ in 0..pos.count { + if let Some(n) = remainder.find(&pos.string) { + offset += n; + remainder = &remainder[n + 1..]; + } else { + panic!("failed to find {} instances of {:?} in {:?}", + pos.count, + pos.string, + file_text); + } + } + offset +} + +#[test] +fn ends_on_col0() { + test_harness(r#" +fn foo() { +} +"#, + vec![ + SpanLabel { + start: Position { + string: "{", + count: 1, + }, + end: Position { + string: "}", + count: 1, + }, + label: "test", + }, + ], + r#" +error: foo + --> test.rs:2:10 + | +2 | fn foo() { + | __________^ starting here... +3 | | } + | |_^ ...ending here: test + +"#); +} + +#[test] +fn ends_on_col2() { + test_harness(r#" +fn foo() { + + + } +"#, + vec![ + SpanLabel { + start: Position { + string: "{", + count: 1, + }, + end: Position { + string: "}", + count: 1, + }, + label: "test", + }, + ], + r#" +error: foo + --> test.rs:2:10 + | +2 | fn foo() { + | __________^ starting here... +3 | | +4 | | +5 | | } + | |___^ ...ending here: test + +"#); +} +#[test] +fn non_nested() { + test_harness(r#" +fn foo() { + X0 Y0 + X1 Y1 + X2 Y2 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "X0", + count: 1, + }, + end: Position { + string: "X2", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "Y2", + count: 1, + }, + label: "`Y` is a good letter too", + }, + ], + r#" +error: foo + --> test.rs:3:3 + | +3 | X0 Y0 + | ____^__- starting here... + | | ___| + | || starting here... +4 | || X1 Y1 +5 | || X2 Y2 + | ||____^__- ...ending here: `Y` is a good letter too + | |____| + | ...ending here: `X` is a good letter + +"#); +} + +#[test] +fn nested() { + test_harness(r#" +fn foo() { + X0 Y0 + Y1 X1 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "X0", + count: 1, + }, + end: Position { + string: "X1", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "Y1", + count: 1, + }, + label: "`Y` is a good letter too", + }, + ], +r#" +error: foo + --> test.rs:3:3 + | +3 | X0 Y0 + | ____^__- starting here... + | | ___| + | || starting here... +4 | || Y1 X1 + | ||____-__^ ...ending here: `X` is a good letter + | |_____| + | ...ending here: `Y` is a good letter too + +"#); +} + +#[test] +fn different_overlap() { + test_harness(r#" +fn foo() { + X0 Y0 Z0 + X1 Y1 Z1 + X2 Y2 Z2 + X3 Y3 Z3 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "X2", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Z1", + count: 1, + }, + end: Position { + string: "X3", + count: 1, + }, + label: "`Y` is a good letter too", + }, + ], + r#" +error: foo + --> test.rs:3:6 + | +3 | X0 Y0 Z0 + | ______^ starting here... +4 | | X1 Y1 Z1 + | |_________- starting here... +5 | || X2 Y2 Z2 + | ||____^ ...ending here: `X` is a good letter +6 | | X3 Y3 Z3 + | |_____- ...ending here: `Y` is a good letter too + +"#); +} + +#[test] +fn triple_overlap() { + test_harness(r#" +fn foo() { + X0 Y0 Z0 + X1 Y1 Z1 + X2 Y2 Z2 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "X0", + count: 1, + }, + end: Position { + string: "X2", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "Y2", + count: 1, + }, + label: "`Y` is a good letter too", + }, + SpanLabel { + start: Position { + string: "Z0", + count: 1, + }, + end: Position { + string: "Z2", + count: 1, + }, + label: "`Z` label", + }, + ], + r#" +error: foo + --> test.rs:3:3 + | +3 | X0 Y0 Z0 + | _____^__-__- starting here... + | | ____|__| + | || ___| starting here... + | ||| starting here... +4 | ||| X1 Y1 Z1 +5 | ||| X2 Y2 Z2 + | |||____^__-__- ...ending here: `Z` label + | ||____|__| + | |____| ...ending here: `Y` is a good letter too + | ...ending here: `X` is a good letter + +"#); +} + +#[test] +fn minimum_depth() { + test_harness(r#" +fn foo() { + X0 Y0 Z0 + X1 Y1 Z1 + X2 Y2 Z2 + X3 Y3 Z3 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "X1", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Y1", + count: 1, + }, + end: Position { + string: "Z2", + count: 1, + }, + label: "`Y` is a good letter too", + }, + SpanLabel { + start: Position { + string: "X2", + count: 1, + }, + end: Position { + string: "Y3", + count: 1, + }, + label: "`Z`", + }, + ], + r#" +error: foo + --> test.rs:3:6 + | +3 | X0 Y0 Z0 + | ______^ starting here... +4 | | X1 Y1 Z1 + | |____^_- starting here... + | ||____| + | | ...ending here: `X` is a good letter +5 | | X2 Y2 Z2 + | |____-______- ...ending here: `Y` is a good letter too + | ____| + | | starting here... +6 | | X3 Y3 Z3 + | |________- ...ending here: `Z` + +"#); +} + +#[test] +fn non_overlaping() { + test_harness(r#" +fn foo() { + X0 Y0 Z0 + X1 Y1 Z1 + X2 Y2 Z2 + X3 Y3 Z3 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "X1", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Y2", + count: 1, + }, + end: Position { + string: "Z3", + count: 1, + }, + label: "`Y` is a good letter too", + }, + ], + r#" +error: foo + --> test.rs:3:6 + | +3 | X0 Y0 Z0 + | ______^ starting here... +4 | | X1 Y1 Z1 + | |____^ ...ending here: `X` is a good letter +5 | X2 Y2 Z2 + | ______- starting here... +6 | | X3 Y3 Z3 + | |__________- ...ending here: `Y` is a good letter too + +"#); +} +#[test] +fn overlaping_start_and_end() { + test_harness(r#" +fn foo() { + X0 Y0 Z0 + X1 Y1 Z1 + X2 Y2 Z2 + X3 Y3 Z3 +} +"#, + vec![ + SpanLabel { + start: Position { + string: "Y0", + count: 1, + }, + end: Position { + string: "X1", + count: 1, + }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { + string: "Z1", + count: 1, + }, + end: Position { + string: "Z3", + count: 1, + }, + label: "`Y` is a good letter too", + }, + ], + r#" +error: foo + --> test.rs:3:6 + | +3 | X0 Y0 Z0 + | ______^ starting here... +4 | | X1 Y1 Z1 + | |____^____- starting here... + | ||____| + | | ...ending here: `X` is a good letter +5 | | X2 Y2 Z2 +6 | | X3 Y3 Z3 + | |___________- ...ending here: `Y` is a good letter too + +"#); +} diff --git a/bash-5.1/vendor/syntex_syntax/src/tokenstream.rs b/bash-5.1/vendor/syntex_syntax/src/tokenstream.rs new file mode 100644 index 0000000..e352e78 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/tokenstream.rs @@ -0,0 +1,1128 @@ +// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! # Token Streams +//! +//! TokenStreams represent syntactic objects before they are converted into ASTs. +//! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s, +//! which are themselves either a single Token, a Delimited subsequence of tokens, +//! or a SequenceRepetition specifier (for the purpose of sequence generation during macro +//! expansion). +//! +//! ## Ownership +//! TokenStreams are persistant data structures construced as ropes with reference +//! counted-children. In general, this means that calling an operation on a TokenStream +//! (such as `slice`) produces an entirely new TokenStream from the borrowed reference to +//! the original. This essentially coerces TokenStreams into 'views' of their subparts, +//! and a borrowed TokenStream is sufficient to build an owned TokenStream without taking +//! ownership of the original. + +use ast::{self, AttrStyle, LitKind}; +use syntax_pos::{Span, DUMMY_SP, NO_EXPANSION}; +use codemap::{Spanned, combine_spans}; +use ext::base; +use ext::tt::macro_parser; +use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration}; +use parse::lexer; +use parse::{self, Directory}; +use parse::token::{self, Token, Lit, Nonterminal}; +use print::pprust; +use symbol::Symbol; + +use std::fmt; +use std::iter::*; +use std::ops::{self, Index}; +use std::rc::Rc; + +/// A delimited sequence of token trees +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct Delimited { + /// The type of delimiter + pub delim: token::DelimToken, + /// The span covering the opening delimiter + pub open_span: Span, + /// The delimited sequence of token trees + pub tts: Vec<TokenTree>, + /// The span covering the closing delimiter + pub close_span: Span, +} + +impl Delimited { + /// Returns the opening delimiter as a token. + pub fn open_token(&self) -> token::Token { + token::OpenDelim(self.delim) + } + + /// Returns the closing delimiter as a token. + pub fn close_token(&self) -> token::Token { + token::CloseDelim(self.delim) + } + + /// Returns the opening delimiter as a token tree. + pub fn open_tt(&self) -> TokenTree { + TokenTree::Token(self.open_span, self.open_token()) + } + + /// Returns the closing delimiter as a token tree. + pub fn close_tt(&self) -> TokenTree { + TokenTree::Token(self.close_span, self.close_token()) + } + + /// Returns the token trees inside the delimiters. + pub fn subtrees(&self) -> &[TokenTree] { + &self.tts + } +} + +/// A sequence of token trees +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct SequenceRepetition { + /// The sequence of token trees + pub tts: Vec<TokenTree>, + /// The optional separator + pub separator: Option<token::Token>, + /// Whether the sequence can be repeated zero (*), or one or more times (+) + pub op: KleeneOp, + /// The number of `MatchNt`s that appear in the sequence (and subsequences) + pub num_captures: usize, +} + +/// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star) +/// for token sequences. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +pub enum KleeneOp { + ZeroOrMore, + OneOrMore, +} + +/// When the main rust parser encounters a syntax-extension invocation, it +/// parses the arguments to the invocation as a token-tree. This is a very +/// loose structure, such that all sorts of different AST-fragments can +/// be passed to syntax extensions using a uniform type. +/// +/// If the syntax extension is an MBE macro, it will attempt to match its +/// LHS token tree against the provided token tree, and if it finds a +/// match, will transcribe the RHS token tree, splicing in any captured +/// macro_parser::matched_nonterminals into the `SubstNt`s it finds. +/// +/// The RHS of an MBE macro is the only place `SubstNt`s are substituted. +/// Nothing special happens to misnamed or misplaced `SubstNt`s. +#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +pub enum TokenTree { + /// A single token + Token(Span, token::Token), + /// A delimited sequence of token trees + Delimited(Span, Rc<Delimited>), + + // This only makes sense in MBE macros. + /// A kleene-style repetition sequence with a span + Sequence(Span, Rc<SequenceRepetition>), +} + +impl TokenTree { + pub fn len(&self) -> usize { + match *self { + TokenTree::Token(_, token::DocComment(name)) => { + match doc_comment_style(&name.as_str()) { + AttrStyle::Outer => 2, + AttrStyle::Inner => 3, + } + } + TokenTree::Token(_, token::Interpolated(ref nt)) => { + if let Nonterminal::NtTT(..) = **nt { 1 } else { 0 } + }, + TokenTree::Token(_, token::MatchNt(..)) => 3, + TokenTree::Delimited(_, ref delimed) => delimed.tts.len() + 2, + TokenTree::Sequence(_, ref seq) => seq.tts.len(), + TokenTree::Token(..) => 0, + } + } + + pub fn get_tt(&self, index: usize) -> TokenTree { + match (self, index) { + (&TokenTree::Token(sp, token::DocComment(_)), 0) => TokenTree::Token(sp, token::Pound), + (&TokenTree::Token(sp, token::DocComment(name)), 1) + if doc_comment_style(&name.as_str()) == AttrStyle::Inner => { + TokenTree::Token(sp, token::Not) + } + (&TokenTree::Token(sp, token::DocComment(name)), _) => { + let stripped = strip_doc_comment_decoration(&name.as_str()); + + // Searches for the occurrences of `"#*` and returns the minimum number of `#`s + // required to wrap the text. + let num_of_hashes = stripped.chars() + .scan(0, |cnt, x| { + *cnt = if x == '"' { + 1 + } else if *cnt != 0 && x == '#' { + *cnt + 1 + } else { + 0 + }; + Some(*cnt) + }) + .max() + .unwrap_or(0); + + TokenTree::Delimited(sp, Rc::new(Delimited { + delim: token::Bracket, + open_span: sp, + tts: vec![TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))), + TokenTree::Token(sp, token::Eq), + TokenTree::Token(sp, token::Literal( + token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))], + close_span: sp, + })) + } + (&TokenTree::Delimited(_, ref delimed), _) => { + if index == 0 { + return delimed.open_tt(); + } + if index == delimed.tts.len() + 1 { + return delimed.close_tt(); + } + delimed.tts[index - 1].clone() + } + (&TokenTree::Token(sp, token::MatchNt(name, kind)), _) => { + let v = [TokenTree::Token(sp, token::SubstNt(name)), + TokenTree::Token(sp, token::Colon), + TokenTree::Token(sp, token::Ident(kind))]; + v[index].clone() + } + (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(), + _ => panic!("Cannot expand a token tree"), + } + } + + /// Returns the `Span` corresponding to this token tree. + pub fn get_span(&self) -> Span { + match *self { + TokenTree::Token(span, _) => span, + TokenTree::Delimited(span, _) => span, + TokenTree::Sequence(span, _) => span, + } + } + + /// Use this token tree as a matcher to parse given tts. + pub fn parse(cx: &base::ExtCtxt, + mtch: &[TokenTree], + tts: &[TokenTree]) + -> macro_parser::NamedParseResult { + let diag = &cx.parse_sess().span_diagnostic; + // `None` is because we're not interpolating + let arg_rdr = lexer::new_tt_reader(diag, None, tts.iter().cloned().collect()); + let directory = Directory { + path: cx.current_expansion.module.directory.clone(), + ownership: cx.current_expansion.directory_ownership, + }; + macro_parser::parse(cx.parse_sess(), arg_rdr, mtch, Some(directory)) + } + + /// Check if this TokenTree is equal to the other, regardless of span information. + pub fn eq_unspanned(&self, other: &TokenTree) -> bool { + match (self, other) { + (&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2, + (&TokenTree::Delimited(_, ref dl), &TokenTree::Delimited(_, ref dl2)) => { + (*dl).delim == (*dl2).delim && dl.tts.len() == dl2.tts.len() && + { + for (tt1, tt2) in dl.tts.iter().zip(dl2.tts.iter()) { + if !tt1.eq_unspanned(tt2) { + return false; + } + } + true + } + } + (_, _) => false, + } + } + + /// Retrieve the TokenTree's span. + pub fn span(&self) -> Span { + match *self { + TokenTree::Token(sp, _) | + TokenTree::Delimited(sp, _) | + TokenTree::Sequence(sp, _) => sp, + } + } + + /// Indicates if the stream is a token that is equal to the provided token. + pub fn eq_token(&self, t: Token) -> bool { + match *self { + TokenTree::Token(_, ref tk) => *tk == t, + _ => false, + } + } + + /// Indicates if the token is an identifier. + pub fn is_ident(&self) -> bool { + self.maybe_ident().is_some() + } + + /// Returns an identifier. + pub fn maybe_ident(&self) -> Option<ast::Ident> { + match *self { + TokenTree::Token(_, Token::Ident(t)) => Some(t.clone()), + TokenTree::Delimited(_, ref dl) => { + let tts = dl.subtrees(); + if tts.len() != 1 { + return None; + } + tts[0].maybe_ident() + } + _ => None, + } + } + + /// Returns a Token literal. + pub fn maybe_lit(&self) -> Option<token::Lit> { + match *self { + TokenTree::Token(_, Token::Literal(l, _)) => Some(l.clone()), + TokenTree::Delimited(_, ref dl) => { + let tts = dl.subtrees(); + if tts.len() != 1 { + return None; + } + tts[0].maybe_lit() + } + _ => None, + } + } + + /// Returns an AST string literal. + pub fn maybe_str(&self) -> Option<ast::Lit> { + match *self { + TokenTree::Token(sp, Token::Literal(Lit::Str_(s), _)) => { + let l = LitKind::Str(Symbol::intern(&parse::str_lit(&s.as_str())), + ast::StrStyle::Cooked); + Some(Spanned { + node: l, + span: sp, + }) + } + TokenTree::Token(sp, Token::Literal(Lit::StrRaw(s, n), _)) => { + let l = LitKind::Str(Symbol::intern(&parse::raw_str_lit(&s.as_str())), + ast::StrStyle::Raw(n)); + Some(Spanned { + node: l, + span: sp, + }) + } + _ => None, + } + } +} + +/// #Token Streams +/// +/// TokenStreams are a syntactic abstraction over TokenTrees. The goal is for procedural +/// macros to work over TokenStreams instead of arbitrary syntax. For now, however, we +/// are going to cut a few corners (i.e., use some of the AST structure) when we need to +/// for backwards compatibility. + +/// TokenStreams are collections of TokenTrees that represent a syntactic structure. The +/// struct itself shouldn't be directly manipulated; the internal structure is not stable, +/// and may be changed at any time in the future. The operators will not, however (except +/// for signatures, later on). +#[derive(Clone, Eq, Hash, RustcEncodable, RustcDecodable)] +pub struct TokenStream { + ts: InternalTS, +} + +// This indicates the maximum size for a leaf in the concatenation algorithm. +// If two leafs will be collectively smaller than this, they will be merged. +// If a leaf is larger than this, it will be concatenated at the top. +const LEAF_SIZE : usize = 32; + +// NB If Leaf access proves to be slow, inroducing a secondary Leaf without the bounds +// for unsliced Leafs may lead to some performance improvemenet. +#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)] +pub enum InternalTS { + Empty(Span), + Leaf { + tts: Rc<Vec<TokenTree>>, + offset: usize, + len: usize, + sp: Span, + }, + Node { + left: Rc<InternalTS>, + right: Rc<InternalTS>, + len: usize, + sp: Span, + }, +} + +impl fmt::Debug for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.ts.fmt(f) + } +} + +impl fmt::Debug for InternalTS { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + InternalTS::Empty(..) => Ok(()), + InternalTS::Leaf { ref tts, offset, len, .. } => { + for t in tts.iter().skip(offset).take(len) { + try!(write!(f, "{:?}", t)); + } + Ok(()) + } + InternalTS::Node { ref left, ref right, .. } => { + try!(left.fmt(f)); + right.fmt(f) + } + } + } +} + +/// Checks if two TokenStreams are equivalent (including spans). For unspanned +/// equality, see `eq_unspanned`. +impl PartialEq<TokenStream> for TokenStream { + fn eq(&self, other: &TokenStream) -> bool { + self.iter().eq(other.iter()) + } +} + +// NB this will disregard gaps. if we have [a|{2,5} , b|{11,13}], the resultant span +// will be at {2,13}. Without finer-grained span structures, however, this seems to be +// our only recourse. +// FIXME Do something smarter to compute the expansion id. +fn covering_span(trees: &[TokenTree]) -> Span { + // disregard any dummy spans we have + let trees = trees.iter().filter(|t| t.span() != DUMMY_SP).collect::<Vec<&TokenTree>>(); + + // if we're out of spans, stop + if trees.len() < 1 { + return DUMMY_SP; + } + + // set up the initial values + let fst_span = trees[0].span(); + + let mut lo_span = fst_span.lo; + let mut hi_span = fst_span.hi; + let mut expn_id = fst_span.expn_id; + + // compute the spans iteratively + for t in trees.iter().skip(1) { + let sp = t.span(); + if sp.lo < lo_span { + lo_span = sp.lo; + } + if hi_span < sp.hi { + hi_span = sp.hi; + } + if expn_id != sp.expn_id { + expn_id = NO_EXPANSION; + } + } + + Span { + lo: lo_span, + hi: hi_span, + expn_id: expn_id, + } +} + +impl InternalTS { + fn len(&self) -> usize { + match *self { + InternalTS::Empty(..) => 0, + InternalTS::Leaf { len, .. } => len, + InternalTS::Node { len, .. } => len, + } + } + + fn span(&self) -> Span { + match *self { + InternalTS::Empty(sp) | + InternalTS::Leaf { sp, .. } | + InternalTS::Node { sp, .. } => sp, + } + } + + fn slice(&self, range: ops::Range<usize>) -> TokenStream { + let from = range.start; + let to = range.end; + if from == to { + return TokenStream::mk_empty(); + } + if from > to { + panic!("Invalid range: {} to {}", from, to); + } + if from == 0 && to == self.len() { + return TokenStream { ts: self.clone() }; /* should be cheap */ + } + match *self { + InternalTS::Empty(..) => panic!("Invalid index"), + InternalTS::Leaf { ref tts, offset, .. } => { + let offset = offset + from; + let len = to - from; + TokenStream::mk_sub_leaf(tts.clone(), + offset, + len, + covering_span(&tts[offset..offset + len])) + } + InternalTS::Node { ref left, ref right, .. } => { + let left_len = left.len(); + if to <= left_len { + left.slice(range) + } else if from >= left_len { + right.slice(from - left_len..to - left_len) + } else { + TokenStream::concat(left.slice(from..left_len), right.slice(0..to - left_len)) + } + } + } + } + + fn to_vec(&self) -> Vec<&TokenTree> { + let mut res = Vec::with_capacity(self.len()); + fn traverse_and_append<'a>(res: &mut Vec<&'a TokenTree>, ts: &'a InternalTS) { + match *ts { + InternalTS::Empty(..) => {}, + InternalTS::Leaf { ref tts, offset, len, .. } => { + let mut to_app = tts[offset..offset + len].iter().collect(); + res.append(&mut to_app); + } + InternalTS::Node { ref left, ref right, .. } => { + traverse_and_append(res, left); + traverse_and_append(res, right); + } + } + } + traverse_and_append(&mut res, self); + res + } + + fn to_tts(&self) -> Vec<TokenTree> { + self.to_vec().into_iter().cloned().collect::<Vec<TokenTree>>() + } + + // Returns an internal node's children. + fn children(&self) -> Option<(Rc<InternalTS>, Rc<InternalTS>)> { + match *self { + InternalTS::Node { ref left, ref right, .. } => Some((left.clone(), right.clone())), + _ => None, + } + } +} + +/// TokenStream operators include basic destructuring, boolean operations, `maybe_...` +/// operations, and `maybe_..._prefix` operations. Boolean operations are straightforward, +/// indicating information about the structure of the stream. The `maybe_...` operations +/// return `Some<...>` if the tokenstream contains the appropriate item. +/// +/// Similarly, the `maybe_..._prefix` operations potentially return a +/// partially-destructured stream as a pair where the first element is the expected item +/// and the second is the remainder of the stream. As anb example, +/// +/// `maybe_path_prefix("a::b::c(a,b,c).foo()") -> (a::b::c, "(a,b,c).foo()")` +impl TokenStream { + // Construct an empty node with a dummy span. + pub fn mk_empty() -> TokenStream { + TokenStream { ts: InternalTS::Empty(DUMMY_SP) } + } + + // Construct an empty node with the provided span. + fn mk_spanned_empty(sp: Span) -> TokenStream { + TokenStream { ts: InternalTS::Empty(sp) } + } + + // Construct a leaf node with a 0 offset and length equivalent to the input. + fn mk_leaf(tts: Rc<Vec<TokenTree>>, sp: Span) -> TokenStream { + let len = tts.len(); + TokenStream { + ts: InternalTS::Leaf { + tts: tts, + offset: 0, + len: len, + sp: sp, + }, + } + } + + // Construct a leaf node with the provided values. + fn mk_sub_leaf(tts: Rc<Vec<TokenTree>>, offset: usize, len: usize, sp: Span) -> TokenStream { + TokenStream { + ts: InternalTS::Leaf { + tts: tts, + offset: offset, + len: len, + sp: sp, + }, + } + } + + // Construct an internal node with the provided values. + fn mk_int_node(left: Rc<InternalTS>, + right: Rc<InternalTS>, + len: usize, + sp: Span) + -> TokenStream { + TokenStream { + ts: InternalTS::Node { + left: left, + right: right, + len: len, + sp: sp, + }, + } + } + + /// Convert a vector of `TokenTree`s into a `TokenStream`. + pub fn from_tts(trees: Vec<TokenTree>) -> TokenStream { + let span = covering_span(&trees[..]); + TokenStream::mk_leaf(Rc::new(trees), span) + } + + /// Convert a vector of Tokens into a TokenStream. + pub fn from_tokens(tokens: Vec<Token>) -> TokenStream { + // FIXME do something nicer with the spans + TokenStream::from_tts(tokens.into_iter().map(|t| TokenTree::Token(DUMMY_SP, t)).collect()) + } + + /// Manually change a TokenStream's span. + pub fn respan(self, span: Span) -> TokenStream { + match self.ts { + InternalTS::Empty(..) => TokenStream::mk_spanned_empty(span), + InternalTS::Leaf { tts, offset, len, .. } => { + TokenStream::mk_sub_leaf(tts, offset, len, span) + } + InternalTS::Node { left, right, len, .. } => { + TokenStream::mk_int_node(left, right, len, span) + } + } + } + + /// Concatenates two TokenStreams into a new TokenStream. + pub fn concat(left: TokenStream, right: TokenStream) -> TokenStream { + // This internal procedure performs 'aggressive compacting' during concatenation as + // follows: + // - If the nodes' combined total total length is less than 32, we copy both of + // them into a new vector and build a new leaf node. + // - If one node is an internal node and the other is a 'small' leaf (length<32), + // we recur down the internal node on the appropriate side. + // - Otherwise, we construct a new internal node that points to them as left and + // right. + fn concat_internal(left: Rc<InternalTS>, right: Rc<InternalTS>) -> TokenStream { + let llen = left.len(); + let rlen = right.len(); + let len = llen + rlen; + let span = combine_spans(left.span(), right.span()); + if len <= LEAF_SIZE { + let mut new_vec = left.to_tts(); + let mut rvec = right.to_tts(); + new_vec.append(&mut rvec); + return TokenStream::mk_leaf(Rc::new(new_vec), span); + } + + match (left.children(), right.children()) { + (Some((lleft, lright)), None) => { + if rlen <= LEAF_SIZE { + let new_right = concat_internal(lright, right); + TokenStream::mk_int_node(lleft, Rc::new(new_right.ts), len, span) + } else { + TokenStream::mk_int_node(left, right, len, span) + } + } + (None, Some((rleft, rright))) => { + if rlen <= LEAF_SIZE { + let new_left = concat_internal(left, rleft); + TokenStream::mk_int_node(Rc::new(new_left.ts), rright, len, span) + } else { + TokenStream::mk_int_node(left, right, len, span) + } + } + (_, _) => TokenStream::mk_int_node(left, right, len, span), + } + } + + if left.is_empty() { + right + } else if right.is_empty() { + left + } else { + concat_internal(Rc::new(left.ts), Rc::new(right.ts)) + } + } + + /// Indicate if the TokenStream is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Return a TokenStream's length. + pub fn len(&self) -> usize { + self.ts.len() + } + + /// Convert a TokenStream into a vector of borrowed TokenTrees. + pub fn to_vec(&self) -> Vec<&TokenTree> { + self.ts.to_vec() + } + + /// Convert a TokenStream into a vector of TokenTrees (by cloning the TokenTrees). + /// (This operation is an O(n) deep copy of the underlying structure.) + pub fn to_tts(&self) -> Vec<TokenTree> { + self.ts.to_tts() + } + + /// Return the TokenStream's span. + pub fn span(&self) -> Span { + self.ts.span() + } + + /// Returns an iterator over a TokenStream (as a sequence of TokenTrees). + pub fn iter<'a>(&self) -> Iter { + Iter { vs: self, idx: 0 } + } + + /// Splits a TokenStream based on the provided `&TokenTree -> bool` predicate. + pub fn split<P>(&self, pred: P) -> Split<P> + where P: FnMut(&TokenTree) -> bool + { + Split { + vs: self, + pred: pred, + finished: false, + idx: 0, + } + } + + /// Produce a slice of the input TokenStream from the `from` index, inclusive, to the + /// `to` index, non-inclusive. + pub fn slice(&self, range: ops::Range<usize>) -> TokenStream { + self.ts.slice(range) + } + + /// Slice starting at the provided index, inclusive. + pub fn slice_from(&self, from: ops::RangeFrom<usize>) -> TokenStream { + self.slice(from.start..self.len()) + } + + /// Slice up to the provided index, non-inclusive. + pub fn slice_to(&self, to: ops::RangeTo<usize>) -> TokenStream { + self.slice(0..to.end) + } + + /// Indicates where the stream is a single, delimited expression (e.g., `(a,b,c)` or + /// `{a,b,c}`). + pub fn is_delimited(&self) -> bool { + self.maybe_delimited().is_some() + } + + /// Returns the inside of the delimited term as a new TokenStream. + pub fn maybe_delimited(&self) -> Option<TokenStream> { + if !(self.len() == 1) { + return None; + } + + // FIXME It would be nice to change Delimited to move the Rc around the TokenTree + // vector directly in order to avoid the clone here. + match self[0] { + TokenTree::Delimited(_, ref rc) => Some(TokenStream::from_tts(rc.tts.clone())), + _ => None, + } + } + + /// Indicates if the stream is exactly one identifier. + pub fn is_ident(&self) -> bool { + self.maybe_ident().is_some() + } + + /// Returns an identifier + pub fn maybe_ident(&self) -> Option<ast::Ident> { + if !(self.len() == 1) { + return None; + } + + match self[0] { + TokenTree::Token(_, Token::Ident(t)) => Some(t), + _ => None, + } + } + + /// Compares two TokenStreams, checking equality without regarding span information. + pub fn eq_unspanned(&self, other: &TokenStream) -> bool { + for (t1, t2) in self.iter().zip(other.iter()) { + if !t1.eq_unspanned(t2) { + return false; + } + } + true + } + + /// Convert a vector of TokenTrees into a parentheses-delimited TokenStream. + pub fn as_delimited_stream(tts: Vec<TokenTree>, delim: token::DelimToken) -> TokenStream { + let new_sp = covering_span(&tts); + + let new_delim = Rc::new(Delimited { + delim: delim, + open_span: DUMMY_SP, + tts: tts, + close_span: DUMMY_SP, + }); + + TokenStream::from_tts(vec![TokenTree::Delimited(new_sp, new_delim)]) + } +} + +impl fmt::Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&pprust::tts_to_string(&self.to_tts())) + } +} + +// FIXME Reimplement this iterator to hold onto a slice iterator for a leaf, getting the +// next leaf's iterator when the current one is exhausted. +pub struct Iter<'a> { + vs: &'a TokenStream, + idx: usize, +} + +impl<'a> Iterator for Iter<'a> { + type Item = &'a TokenTree; + + fn next(&mut self) -> Option<&'a TokenTree> { + if self.vs.is_empty() || self.idx >= self.vs.len() { + return None; + } + + let ret = Some(&self.vs[self.idx]); + self.idx = self.idx + 1; + ret + } +} + +pub struct Split<'a, P> + where P: FnMut(&TokenTree) -> bool +{ + vs: &'a TokenStream, + pred: P, + finished: bool, + idx: usize, +} + +impl<'a, P> Iterator for Split<'a, P> + where P: FnMut(&TokenTree) -> bool +{ + type Item = TokenStream; + + fn next(&mut self) -> Option<TokenStream> { + if self.finished { + return None; + } + if self.idx >= self.vs.len() { + self.finished = true; + return None; + } + + let mut lookup = self.vs.iter().skip(self.idx); + match lookup.position(|x| (self.pred)(&x)) { + None => { + self.finished = true; + Some(self.vs.slice_from(self.idx..)) + } + Some(edx) => { + let ret = Some(self.vs.slice(self.idx..self.idx + edx)); + self.idx += edx + 1; + ret + } + } + } +} + +impl Index<usize> for TokenStream { + type Output = TokenTree; + + fn index(&self, index: usize) -> &TokenTree { + &self.ts[index] + } +} + +impl Index<usize> for InternalTS { + type Output = TokenTree; + + fn index(&self, index: usize) -> &TokenTree { + if self.len() <= index { + panic!("Index {} too large for {:?}", index, self); + } + match *self { + InternalTS::Empty(..) => panic!("Invalid index"), + InternalTS::Leaf { ref tts, offset, .. } => tts.get(index + offset).unwrap(), + InternalTS::Node { ref left, ref right, .. } => { + let left_len = left.len(); + if index < left_len { + Index::index(&**left, index) + } else { + Index::index(&**right, index - left_len) + } + } + } + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use syntax::ast::Ident; + use syntax_pos::{Span, BytePos, NO_EXPANSION, DUMMY_SP}; + use parse::token::{self, Token}; + use util::parser_testing::string_to_tts; + use std::rc::Rc; + + fn sp(a: u32, b: u32) -> Span { + Span { + lo: BytePos(a), + hi: BytePos(b), + expn_id: NO_EXPANSION, + } + } + + fn as_paren_delimited_stream(tts: Vec<TokenTree>) -> TokenStream { + TokenStream::as_delimited_stream(tts, token::DelimToken::Paren) + } + + #[test] + fn test_concat() { + let test_res = TokenStream::from_tts(string_to_tts("foo::bar::baz".to_string())); + let test_fst = TokenStream::from_tts(string_to_tts("foo::bar".to_string())); + let test_snd = TokenStream::from_tts(string_to_tts("::baz".to_string())); + let eq_res = TokenStream::concat(test_fst, test_snd); + assert_eq!(test_res.len(), 5); + assert_eq!(eq_res.len(), 5); + assert_eq!(test_res.eq_unspanned(&eq_res), true); + } + + #[test] + fn test_from_to_bijection() { + let test_start = string_to_tts("foo::bar(baz)".to_string()); + let test_end = TokenStream::from_tts(string_to_tts("foo::bar(baz)".to_string())).to_tts(); + assert_eq!(test_start, test_end) + } + + #[test] + fn test_to_from_bijection() { + let test_start = TokenStream::from_tts(string_to_tts("foo::bar(baz)".to_string())); + let test_end = TokenStream::from_tts(test_start.clone().to_tts()); + assert_eq!(test_start, test_end) + } + + #[test] + fn test_eq_0() { + let test_res = TokenStream::from_tts(string_to_tts("foo".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("foo".to_string())); + assert_eq!(test_res, test_eqs) + } + + #[test] + fn test_eq_1() { + let test_res = TokenStream::from_tts(string_to_tts("::bar::baz".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("::bar::baz".to_string())); + assert_eq!(test_res, test_eqs) + } + + #[test] + fn test_eq_2() { + let test_res = TokenStream::from_tts(string_to_tts("foo::bar".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("foo::bar::baz".to_string())); + assert_eq!(test_res, test_eqs.slice(0..3)) + } + + #[test] + fn test_eq_3() { + let test_res = TokenStream::from_tts(string_to_tts("".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("".to_string())); + assert_eq!(test_res, test_eqs) + } + + #[test] + fn test_diseq_0() { + let test_res = TokenStream::from_tts(string_to_tts("::bar::baz".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("bar::baz".to_string())); + assert_eq!(test_res == test_eqs, false) + } + + #[test] + fn test_diseq_1() { + let test_res = TokenStream::from_tts(string_to_tts("(bar,baz)".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("bar,baz".to_string())); + assert_eq!(test_res == test_eqs, false) + } + + #[test] + fn test_slice_0() { + let test_res = TokenStream::from_tts(string_to_tts("foo::bar".to_string())); + let test_eqs = TokenStream::from_tts(string_to_tts("foo::bar::baz".to_string())); + assert_eq!(test_res, test_eqs.slice(0..3)) + } + + #[test] + fn test_slice_1() { + let test_res = TokenStream::from_tts(string_to_tts("foo::bar::baz".to_string())) + .slice(2..3); + let test_eqs = TokenStream::from_tts(vec![TokenTree::Token(sp(5,8), + token::Ident(Ident::from_str("bar")))]); + assert_eq!(test_res, test_eqs) + } + + #[test] + fn test_is_empty() { + let test0 = TokenStream::from_tts(Vec::new()); + let test1 = TokenStream::from_tts( + vec![TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a")))] + ); + + let test2 = TokenStream::from_tts(string_to_tts("foo(bar::baz)".to_string())); + + assert_eq!(test0.is_empty(), true); + assert_eq!(test1.is_empty(), false); + assert_eq!(test2.is_empty(), false); + } + + #[test] + fn test_is_delimited() { + let test0 = TokenStream::from_tts(string_to_tts("foo(bar::baz)".to_string())); + let test1 = TokenStream::from_tts(string_to_tts("(bar::baz)".to_string())); + let test2 = TokenStream::from_tts(string_to_tts("(foo,bar,baz)".to_string())); + let test3 = TokenStream::from_tts(string_to_tts("(foo,bar,baz)(zab,rab,oof)".to_string())); + let test4 = TokenStream::from_tts(string_to_tts("(foo,bar,baz)foo".to_string())); + let test5 = TokenStream::from_tts(string_to_tts("".to_string())); + + assert_eq!(test0.is_delimited(), false); + assert_eq!(test1.is_delimited(), true); + assert_eq!(test2.is_delimited(), true); + assert_eq!(test3.is_delimited(), false); + assert_eq!(test4.is_delimited(), false); + assert_eq!(test5.is_delimited(), false); + } + + #[test] + fn test_is_ident() { + let test0 = TokenStream::from_tts(string_to_tts("\"foo\"".to_string())); + let test1 = TokenStream::from_tts(string_to_tts("5".to_string())); + let test2 = TokenStream::from_tts(string_to_tts("foo".to_string())); + let test3 = TokenStream::from_tts(string_to_tts("foo::bar".to_string())); + let test4 = TokenStream::from_tts(string_to_tts("foo(bar)".to_string())); + + assert_eq!(test0.is_ident(), false); + assert_eq!(test1.is_ident(), false); + assert_eq!(test2.is_ident(), true); + assert_eq!(test3.is_ident(), false); + assert_eq!(test4.is_ident(), false); + } + + #[test] + fn test_maybe_delimited() { + let test0_input = TokenStream::from_tts(string_to_tts("foo(bar::baz)".to_string())); + let test1_input = TokenStream::from_tts(string_to_tts("(bar::baz)".to_string())); + let test2_input = TokenStream::from_tts(string_to_tts("(foo,bar,baz)".to_string())); + let test3_input = TokenStream::from_tts(string_to_tts("(foo,bar,baz)(zab,rab)" + .to_string())); + let test4_input = TokenStream::from_tts(string_to_tts("(foo,bar,baz)foo".to_string())); + let test5_input = TokenStream::from_tts(string_to_tts("".to_string())); + + let test0 = test0_input.maybe_delimited(); + let test1 = test1_input.maybe_delimited(); + let test2 = test2_input.maybe_delimited(); + let test3 = test3_input.maybe_delimited(); + let test4 = test4_input.maybe_delimited(); + let test5 = test5_input.maybe_delimited(); + + assert_eq!(test0, None); + + let test1_expected = TokenStream::from_tts(vec![TokenTree::Token(sp(1, 4), + token::Ident(Ident::from_str("bar"))), + TokenTree::Token(sp(4, 6), token::ModSep), + TokenTree::Token(sp(6, 9), + token::Ident(Ident::from_str("baz")))]); + assert_eq!(test1, Some(test1_expected)); + + let test2_expected = TokenStream::from_tts(vec![TokenTree::Token(sp(1, 4), + token::Ident(Ident::from_str("foo"))), + TokenTree::Token(sp(4, 5), token::Comma), + TokenTree::Token(sp(5, 8), + token::Ident(Ident::from_str("bar"))), + TokenTree::Token(sp(8, 9), token::Comma), + TokenTree::Token(sp(9, 12), + token::Ident(Ident::from_str("baz")))]); + assert_eq!(test2, Some(test2_expected)); + + assert_eq!(test3, None); + + assert_eq!(test4, None); + + assert_eq!(test5, None); + } + + // pub fn maybe_ident(&self) -> Option<ast::Ident> + #[test] + fn test_maybe_ident() { + let test0 = TokenStream::from_tts(string_to_tts("\"foo\"".to_string())).maybe_ident(); + let test1 = TokenStream::from_tts(string_to_tts("5".to_string())).maybe_ident(); + let test2 = TokenStream::from_tts(string_to_tts("foo".to_string())).maybe_ident(); + let test3 = TokenStream::from_tts(string_to_tts("foo::bar".to_string())).maybe_ident(); + let test4 = TokenStream::from_tts(string_to_tts("foo(bar)".to_string())).maybe_ident(); + + assert_eq!(test0, None); + assert_eq!(test1, None); + assert_eq!(test2, Some(Ident::from_str("foo"))); + assert_eq!(test3, None); + assert_eq!(test4, None); + } + + #[test] + fn test_as_delimited_stream() { + let test0 = as_paren_delimited_stream(string_to_tts("foo,bar,".to_string())); + let test1 = as_paren_delimited_stream(string_to_tts("baz(foo,bar)".to_string())); + + let test0_tts = vec![TokenTree::Token(sp(0, 3), token::Ident(Ident::from_str("foo"))), + TokenTree::Token(sp(3, 4), token::Comma), + TokenTree::Token(sp(4, 7), token::Ident(Ident::from_str("bar"))), + TokenTree::Token(sp(7, 8), token::Comma)]; + let test0_stream = TokenStream::from_tts(vec![TokenTree::Delimited(sp(0, 8), + Rc::new(Delimited { + delim: token::DelimToken::Paren, + open_span: DUMMY_SP, + tts: test0_tts, + close_span: DUMMY_SP, + }))]); + + assert_eq!(test0, test0_stream); + + + let test1_tts = vec![TokenTree::Token(sp(4, 7), token::Ident(Ident::from_str("foo"))), + TokenTree::Token(sp(7, 8), token::Comma), + TokenTree::Token(sp(8, 11), token::Ident(Ident::from_str("bar")))]; + + let test1_parse = vec![TokenTree::Token(sp(0, 3), token::Ident(Ident::from_str("baz"))), + TokenTree::Delimited(sp(3, 12), + Rc::new(Delimited { + delim: token::DelimToken::Paren, + open_span: sp(3, 4), + tts: test1_tts, + close_span: sp(11, 12), + }))]; + + let test1_stream = TokenStream::from_tts(vec![TokenTree::Delimited(sp(0, 12), + Rc::new(Delimited { + delim: token::DelimToken::Paren, + open_span: DUMMY_SP, + tts: test1_parse, + close_span: DUMMY_SP, + }))]); + + assert_eq!(test1, test1_stream); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/lev_distance.rs b/bash-5.1/vendor/syntex_syntax/src/util/lev_distance.rs new file mode 100644 index 0000000..a6fff2d --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/lev_distance.rs @@ -0,0 +1,84 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use symbol::Symbol; + +/// To find the Levenshtein distance between two strings +pub fn lev_distance(a: &str, b: &str) -> usize { + // cases which don't require further computation + if a.is_empty() { + return b.chars().count(); + } else if b.is_empty() { + return a.chars().count(); + } + + let mut dcol: Vec<_> = (0..b.len() + 1).collect(); + let mut t_last = 0; + + for (i, sc) in a.chars().enumerate() { + let mut current = i; + dcol[0] = current + 1; + + for (j, tc) in b.chars().enumerate() { + let next = dcol[j + 1]; + if sc == tc { + dcol[j + 1] = current; + } else { + dcol[j + 1] = cmp::min(current, next); + dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1; + } + current = next; + t_last = j; + } + } dcol[t_last + 1] +} + +/// To find the best match for a given string from an iterator of names +/// As a loose rule to avoid the obviously incorrect suggestions, it takes +/// an optional limit for the maximum allowable edit distance, which defaults +/// to one-third of the given word +pub fn find_best_match_for_name<'a, T>(iter_names: T, + lookup: &str, + dist: Option<usize>) -> Option<Symbol> + where T: Iterator<Item = &'a Symbol> { + let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d); + iter_names + .filter_map(|&name| { + let dist = lev_distance(lookup, &name.as_str()); + match dist <= max_dist { // filter the unwanted cases + true => Some((name, dist)), + false => None, + } + }) + .min_by_key(|&(_, val)| val) // extract the tuple containing the minimum edit distance + .map(|(s, _)| s) // and return only the string +} + +#[test] +fn test_lev_distance() { + use std::char::{from_u32, MAX}; + // Test bytelength agnosticity + for c in (0..MAX as u32) + .filter_map(|i| from_u32(i)) + .map(|i| i.to_string()) { + assert_eq!(lev_distance(&c[..], &c[..]), 0); + } + + let a = "\nMäry häd ä little lämb\n\nLittle lämb\n"; + let b = "\nMary häd ä little lämb\n\nLittle lämb\n"; + let c = "Mary häd ä little lämb\n\nLittle lämb\n"; + assert_eq!(lev_distance(a, b), 1); + assert_eq!(lev_distance(b, a), 1); + assert_eq!(lev_distance(a, c), 2); + assert_eq!(lev_distance(c, a), 2); + assert_eq!(lev_distance(b, c), 1); + assert_eq!(lev_distance(c, b), 1); +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/move_map.rs b/bash-5.1/vendor/syntex_syntax/src/util/move_map.rs new file mode 100644 index 0000000..e1078b7 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/move_map.rs @@ -0,0 +1,77 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::ptr; + +pub trait MoveMap<T>: Sized { + fn move_map<F>(self, mut f: F) -> Self where F: FnMut(T) -> T { + self.move_flat_map(|e| Some(f(e))) + } + + fn move_flat_map<F, I>(self, f: F) -> Self + where F: FnMut(T) -> I, + I: IntoIterator<Item=T>; +} + +impl<T> MoveMap<T> for Vec<T> { + fn move_flat_map<F, I>(mut self, mut f: F) -> Self + where F: FnMut(T) -> I, + I: IntoIterator<Item=T> + { + let mut read_i = 0; + let mut write_i = 0; + unsafe { + let mut old_len = self.len(); + self.set_len(0); // make sure we just leak elements in case of panic + + while read_i < old_len { + // move the read_i'th item out of the vector and map it + // to an iterator + let e = ptr::read(self.get_unchecked(read_i)); + let mut iter = f(e).into_iter(); + read_i += 1; + + while let Some(e) = iter.next() { + if write_i < read_i { + ptr::write(self.get_unchecked_mut(write_i), e); + write_i += 1; + } else { + // If this is reached we ran out of space + // in the middle of the vector. + // However, the vector is in a valid state here, + // so we just do a somewhat inefficient insert. + self.set_len(old_len); + self.insert(write_i, e); + + old_len = self.len(); + self.set_len(0); + + read_i += 1; + write_i += 1; + } + } + } + + // write_i tracks the number of actually written new items. + self.set_len(write_i); + } + + self + } +} + +impl<T> MoveMap<T> for ::ptr::P<[T]> { + fn move_flat_map<F, I>(self, f: F) -> Self + where F: FnMut(T) -> I, + I: IntoIterator<Item=T> + { + ::ptr::P::from_vec(self.into_vec().move_flat_map(f)) + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/node_count.rs b/bash-5.1/vendor/syntex_syntax/src/util/node_count.rs new file mode 100644 index 0000000..b90802d --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/node_count.rs @@ -0,0 +1,156 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Simply gives a rought count of the number of nodes in an AST. + +use visit::*; +use ast::*; +use syntax_pos::Span; + +pub struct NodeCounter { + pub count: usize, +} + +impl NodeCounter { + pub fn new() -> NodeCounter { + NodeCounter { + count: 0, + } + } +} + +impl<'ast> Visitor<'ast> for NodeCounter { + fn visit_ident(&mut self, span: Span, ident: Ident) { + self.count += 1; + walk_ident(self, span, ident); + } + fn visit_mod(&mut self, m: &Mod, _s: Span, _n: NodeId) { + self.count += 1; + walk_mod(self, m) + } + fn visit_foreign_item(&mut self, i: &ForeignItem) { + self.count += 1; + walk_foreign_item(self, i) + } + fn visit_item(&mut self, i: &Item) { + self.count += 1; + walk_item(self, i) + } + fn visit_local(&mut self, l: &Local) { + self.count += 1; + walk_local(self, l) + } + fn visit_block(&mut self, b: &Block) { + self.count += 1; + walk_block(self, b) + } + fn visit_stmt(&mut self, s: &Stmt) { + self.count += 1; + walk_stmt(self, s) + } + fn visit_arm(&mut self, a: &Arm) { + self.count += 1; + walk_arm(self, a) + } + fn visit_pat(&mut self, p: &Pat) { + self.count += 1; + walk_pat(self, p) + } + fn visit_expr(&mut self, ex: &Expr) { + self.count += 1; + walk_expr(self, ex) + } + fn visit_ty(&mut self, t: &Ty) { + self.count += 1; + walk_ty(self, t) + } + fn visit_generics(&mut self, g: &Generics) { + self.count += 1; + walk_generics(self, g) + } + fn visit_fn(&mut self, fk: FnKind, fd: &FnDecl, s: Span, _: NodeId) { + self.count += 1; + walk_fn(self, fk, fd, s) + } + fn visit_trait_item(&mut self, ti: &TraitItem) { + self.count += 1; + walk_trait_item(self, ti) + } + fn visit_impl_item(&mut self, ii: &ImplItem) { + self.count += 1; + walk_impl_item(self, ii) + } + fn visit_trait_ref(&mut self, t: &TraitRef) { + self.count += 1; + walk_trait_ref(self, t) + } + fn visit_ty_param_bound(&mut self, bounds: &TyParamBound) { + self.count += 1; + walk_ty_param_bound(self, bounds) + } + fn visit_poly_trait_ref(&mut self, t: &PolyTraitRef, m: &TraitBoundModifier) { + self.count += 1; + walk_poly_trait_ref(self, t, m) + } + fn visit_variant_data(&mut self, s: &VariantData, _: Ident, + _: &Generics, _: NodeId, _: Span) { + self.count += 1; + walk_struct_def(self, s) + } + fn visit_struct_field(&mut self, s: &StructField) { + self.count += 1; + walk_struct_field(self, s) + } + fn visit_enum_def(&mut self, enum_definition: &EnumDef, + generics: &Generics, item_id: NodeId, _: Span) { + self.count += 1; + walk_enum_def(self, enum_definition, generics, item_id) + } + fn visit_variant(&mut self, v: &Variant, g: &Generics, item_id: NodeId) { + self.count += 1; + walk_variant(self, v, g, item_id) + } + fn visit_lifetime(&mut self, lifetime: &Lifetime) { + self.count += 1; + walk_lifetime(self, lifetime) + } + fn visit_lifetime_def(&mut self, lifetime: &LifetimeDef) { + self.count += 1; + walk_lifetime_def(self, lifetime) + } + fn visit_mac(&mut self, _mac: &Mac) { + self.count += 1; + walk_mac(self, _mac) + } + fn visit_path(&mut self, path: &Path, _id: NodeId) { + self.count += 1; + walk_path(self, path) + } + fn visit_path_list_item(&mut self, prefix: &Path, item: &PathListItem) { + self.count += 1; + walk_path_list_item(self, prefix, item) + } + fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &PathParameters) { + self.count += 1; + walk_path_parameters(self, path_span, path_parameters) + } + fn visit_assoc_type_binding(&mut self, type_binding: &TypeBinding) { + self.count += 1; + walk_assoc_type_binding(self, type_binding) + } + fn visit_attribute(&mut self, _attr: &Attribute) { + self.count += 1; + } + fn visit_macro_def(&mut self, macro_def: &MacroDef) { + self.count += 1; + walk_macro_def(self, macro_def) + } + +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/parser.rs b/bash-5.1/vendor/syntex_syntax/src/util/parser.rs new file mode 100644 index 0000000..ce24fe1 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/parser.rs @@ -0,0 +1,217 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +use parse::token::{Token, BinOpToken}; +use symbol::keywords; +use ast::BinOpKind; + +/// Associative operator with precedence. +/// +/// This is the enum which specifies operator precedence and fixity to the parser. +#[derive(Debug, PartialEq, Eq)] +pub enum AssocOp { + /// `+` + Add, + /// `-` + Subtract, + /// `*` + Multiply, + /// `/` + Divide, + /// `%` + Modulus, + /// `&&` + LAnd, + /// `||` + LOr, + /// `^` + BitXor, + /// `&` + BitAnd, + /// `|` + BitOr, + /// `<<` + ShiftLeft, + /// `>>` + ShiftRight, + /// `==` + Equal, + /// `<` + Less, + /// `<=` + LessEqual, + /// `!=` + NotEqual, + /// `>` + Greater, + /// `>=` + GreaterEqual, + /// `=` + Assign, + /// `<-` + Inplace, + /// `?=` where ? is one of the BinOpToken + AssignOp(BinOpToken), + /// `as` + As, + /// `..` range + DotDot, + /// `...` range + DotDotDot, + /// `:` + Colon, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Fixity { + /// The operator is left-associative + Left, + /// The operator is right-associative + Right, + /// The operator is not associative + None +} + +impl AssocOp { + /// Create a new AssocOP from a token + pub fn from_token(t: &Token) -> Option<AssocOp> { + use self::AssocOp::*; + match *t { + Token::BinOpEq(k) => Some(AssignOp(k)), + Token::LArrow => Some(Inplace), + Token::Eq => Some(Assign), + Token::BinOp(BinOpToken::Star) => Some(Multiply), + Token::BinOp(BinOpToken::Slash) => Some(Divide), + Token::BinOp(BinOpToken::Percent) => Some(Modulus), + Token::BinOp(BinOpToken::Plus) => Some(Add), + Token::BinOp(BinOpToken::Minus) => Some(Subtract), + Token::BinOp(BinOpToken::Shl) => Some(ShiftLeft), + Token::BinOp(BinOpToken::Shr) => Some(ShiftRight), + Token::BinOp(BinOpToken::And) => Some(BitAnd), + Token::BinOp(BinOpToken::Caret) => Some(BitXor), + Token::BinOp(BinOpToken::Or) => Some(BitOr), + Token::Lt => Some(Less), + Token::Le => Some(LessEqual), + Token::Ge => Some(GreaterEqual), + Token::Gt => Some(Greater), + Token::EqEq => Some(Equal), + Token::Ne => Some(NotEqual), + Token::AndAnd => Some(LAnd), + Token::OrOr => Some(LOr), + Token::DotDot => Some(DotDot), + Token::DotDotDot => Some(DotDotDot), + Token::Colon => Some(Colon), + _ if t.is_keyword(keywords::As) => Some(As), + _ => None + } + } + + /// Create a new AssocOp from ast::BinOpKind. + pub fn from_ast_binop(op: BinOpKind) -> Self { + use self::AssocOp::*; + match op { + BinOpKind::Lt => Less, + BinOpKind::Gt => Greater, + BinOpKind::Le => LessEqual, + BinOpKind::Ge => GreaterEqual, + BinOpKind::Eq => Equal, + BinOpKind::Ne => NotEqual, + BinOpKind::Mul => Multiply, + BinOpKind::Div => Divide, + BinOpKind::Rem => Modulus, + BinOpKind::Add => Add, + BinOpKind::Sub => Subtract, + BinOpKind::Shl => ShiftLeft, + BinOpKind::Shr => ShiftRight, + BinOpKind::BitAnd => BitAnd, + BinOpKind::BitXor => BitXor, + BinOpKind::BitOr => BitOr, + BinOpKind::And => LAnd, + BinOpKind::Or => LOr + } + } + + /// Gets the precedence of this operator + pub fn precedence(&self) -> usize { + use self::AssocOp::*; + match *self { + As | Colon => 14, + Multiply | Divide | Modulus => 13, + Add | Subtract => 12, + ShiftLeft | ShiftRight => 11, + BitAnd => 10, + BitXor => 9, + BitOr => 8, + Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual => 7, + LAnd => 6, + LOr => 5, + DotDot | DotDotDot => 4, + Inplace => 3, + Assign | AssignOp(_) => 2, + } + } + + /// Gets the fixity of this operator + pub fn fixity(&self) -> Fixity { + use self::AssocOp::*; + // NOTE: it is a bug to have an operators that has same precedence but different fixities! + match *self { + Inplace | Assign | AssignOp(_) => Fixity::Right, + As | Multiply | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | + BitXor | BitOr | Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | + LAnd | LOr | Colon => Fixity::Left, + DotDot | DotDotDot => Fixity::None + } + } + + pub fn is_comparison(&self) -> bool { + use self::AssocOp::*; + match *self { + Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual => true, + Inplace | Assign | AssignOp(_) | As | Multiply | Divide | Modulus | Add | Subtract | + ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | LOr | + DotDot | DotDotDot | Colon => false + } + } + + pub fn is_assign_like(&self) -> bool { + use self::AssocOp::*; + match *self { + Assign | AssignOp(_) | Inplace => true, + Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | As | Multiply | Divide | + Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | + LOr | DotDot | DotDotDot | Colon => false + } + } + + pub fn to_ast_binop(&self) -> Option<BinOpKind> { + use self::AssocOp::*; + match *self { + Less => Some(BinOpKind::Lt), + Greater => Some(BinOpKind::Gt), + LessEqual => Some(BinOpKind::Le), + GreaterEqual => Some(BinOpKind::Ge), + Equal => Some(BinOpKind::Eq), + NotEqual => Some(BinOpKind::Ne), + Multiply => Some(BinOpKind::Mul), + Divide => Some(BinOpKind::Div), + Modulus => Some(BinOpKind::Rem), + Add => Some(BinOpKind::Add), + Subtract => Some(BinOpKind::Sub), + ShiftLeft => Some(BinOpKind::Shl), + ShiftRight => Some(BinOpKind::Shr), + BitAnd => Some(BinOpKind::BitAnd), + BitXor => Some(BinOpKind::BitXor), + BitOr => Some(BinOpKind::BitOr), + LAnd => Some(BinOpKind::And), + LOr => Some(BinOpKind::Or), + Inplace | Assign | AssignOp(_) | As | DotDot | DotDotDot | Colon => None + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/parser_testing.rs b/bash-5.1/vendor/syntex_syntax/src/util/parser_testing.rs new file mode 100644 index 0000000..82459dc --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/parser_testing.rs @@ -0,0 +1,172 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast::{self, Ident}; +use parse::{ParseSess,PResult,filemap_to_tts}; +use parse::{lexer, new_parser_from_source_str}; +use parse::parser::Parser; +use ptr::P; +use tokenstream; +use std::iter::Peekable; + +/// Map a string to tts, using a made-up filename: +pub fn string_to_tts(source_str: String) -> Vec<tokenstream::TokenTree> { + let ps = ParseSess::new(); + filemap_to_tts(&ps, ps.codemap().new_filemap("bogofile".to_string(), None, source_str)) +} + +/// Map string to parser (via tts) +pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> { + new_parser_from_source_str(ps, "bogofile".to_string(), source_str) +} + +fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where + F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>, +{ + let mut p = string_to_parser(&ps, s); + let x = panictry!(f(&mut p)); + p.abort_if_errors(); + x +} + +/// Parse a string, return a crate. +pub fn string_to_crate (source_str : String) -> ast::Crate { + let ps = ParseSess::new(); + with_error_checking_parse(source_str, &ps, |p| { + p.parse_crate_mod() + }) +} + +/// Parse a string, return an expr +pub fn string_to_expr (source_str : String) -> P<ast::Expr> { + let ps = ParseSess::new(); + with_error_checking_parse(source_str, &ps, |p| { + p.parse_expr() + }) +} + +/// Parse a string, return an item +pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> { + let ps = ParseSess::new(); + with_error_checking_parse(source_str, &ps, |p| { + p.parse_item() + }) +} + +/// Parse a string, return a stmt +pub fn string_to_stmt(source_str : String) -> Option<ast::Stmt> { + let ps = ParseSess::new(); + with_error_checking_parse(source_str, &ps, |p| { + p.parse_stmt() + }) +} + +/// Parse a string, return a pat. Uses "irrefutable"... which doesn't +/// (currently) affect parsing. +pub fn string_to_pat(source_str: String) -> P<ast::Pat> { + let ps = ParseSess::new(); + with_error_checking_parse(source_str, &ps, |p| { + p.parse_pat() + }) +} + +/// Convert a vector of strings to a vector of Ident's +pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<Ident> { + ids.iter().map(|u| Ident::from_str(*u)).collect() +} + +/// Does the given string match the pattern? whitespace in the first string +/// may be deleted or replaced with other whitespace to match the pattern. +/// This function is relatively Unicode-ignorant; fortunately, the careful design +/// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?). +pub fn matches_codepattern(a : &str, b : &str) -> bool { + let mut a_iter = a.chars().peekable(); + let mut b_iter = b.chars().peekable(); + + loop { + let (a, b) = match (a_iter.peek(), b_iter.peek()) { + (None, None) => return true, + (None, _) => return false, + (Some(&a), None) => { + if is_pattern_whitespace(a) { + break // trailing whitespace check is out of loop for borrowck + } else { + return false + } + } + (Some(&a), Some(&b)) => (a, b) + }; + + if is_pattern_whitespace(a) && is_pattern_whitespace(b) { + // skip whitespace for a and b + scan_for_non_ws_or_end(&mut a_iter); + scan_for_non_ws_or_end(&mut b_iter); + } else if is_pattern_whitespace(a) { + // skip whitespace for a + scan_for_non_ws_or_end(&mut a_iter); + } else if a == b { + a_iter.next(); + b_iter.next(); + } else { + return false + } + } + + // check if a has *only* trailing whitespace + a_iter.all(is_pattern_whitespace) +} + +/// Advances the given peekable `Iterator` until it reaches a non-whitespace character +fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) { + while lexer::is_pattern_whitespace(iter.peek().cloned()) { + iter.next(); + } +} + +pub fn is_pattern_whitespace(c: char) -> bool { + lexer::is_pattern_whitespace(Some(c)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eqmodws() { + assert_eq!(matches_codepattern("",""),true); + assert_eq!(matches_codepattern("","a"),false); + assert_eq!(matches_codepattern("a",""),false); + assert_eq!(matches_codepattern("a","a"),true); + assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); + assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true); + assert_eq!(matches_codepattern("a b","a \n\t\r b "),false); + assert_eq!(matches_codepattern("a b","a b"),true); + assert_eq!(matches_codepattern("ab","a b"),false); + assert_eq!(matches_codepattern("a b","ab"),true); + assert_eq!(matches_codepattern(" a b","ab"),true); + } + + #[test] + fn pattern_whitespace() { + assert_eq!(matches_codepattern("","\x0C"), false); + // TODO - not yet enabled + //assert_eq!(matches_codepattern("a b ","a \u{0085}\n\t\r b"),true); + assert_eq!(matches_codepattern("a b","a \u{0085}\n\t\r b "),false); + } + + #[test] + fn non_pattern_whitespace() { + // These have the property 'White_Space' but not 'Pattern_White_Space' + assert_eq!(matches_codepattern("a b","a\u{2002}b"), false); + assert_eq!(matches_codepattern("a b","a\u{2002}b"), false); + assert_eq!(matches_codepattern("\u{205F}a b","ab"), false); + assert_eq!(matches_codepattern("a \u{3000}b","ab"), false); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/small_vector.rs b/bash-5.1/vendor/syntex_syntax/src/util/small_vector.rs new file mode 100644 index 0000000..ba139b5 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/small_vector.rs @@ -0,0 +1,329 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use self::SmallVectorRepr::*; +use self::IntoIterRepr::*; + +use std::ops; +use std::iter::{IntoIterator, FromIterator}; +use std::mem; +use std::slice; +use std::vec; + +use util::move_map::MoveMap; + +/// A vector type optimized for cases where the size is almost always 0 or 1 +#[derive(Clone)] +pub struct SmallVector<T> { + repr: SmallVectorRepr<T>, +} + +#[derive(Clone)] +enum SmallVectorRepr<T> { + Zero, + One(T), + Many(Vec<T>), +} + +impl<T> Default for SmallVector<T> { + fn default() -> Self { + SmallVector { repr: Zero } + } +} + +impl<T> Into<Vec<T>> for SmallVector<T> { + fn into(self) -> Vec<T> { + match self.repr { + Zero => Vec::new(), + One(t) => vec![t], + Many(vec) => vec, + } + } +} + +impl<T> FromIterator<T> for SmallVector<T> { + fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> SmallVector<T> { + let mut v = SmallVector::zero(); + v.extend(iter); + v + } +} + +impl<T> Extend<T> for SmallVector<T> { + fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) { + for val in iter { + self.push(val); + } + } +} + +impl<T> SmallVector<T> { + pub fn new() -> SmallVector<T> { + SmallVector::zero() + } + + pub fn zero() -> SmallVector<T> { + SmallVector { repr: Zero } + } + + pub fn one(v: T) -> SmallVector<T> { + SmallVector { repr: One(v) } + } + + pub fn many(vs: Vec<T>) -> SmallVector<T> { + SmallVector { repr: Many(vs) } + } + + pub fn as_slice(&self) -> &[T] { + self + } + + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + pub fn pop(&mut self) -> Option<T> { + match self.repr { + Zero => None, + One(..) => { + let one = mem::replace(&mut self.repr, Zero); + match one { + One(v1) => Some(v1), + _ => unreachable!() + } + } + Many(ref mut vs) => vs.pop(), + } + } + + pub fn push(&mut self, v: T) { + match self.repr { + Zero => self.repr = One(v), + One(..) => { + let one = mem::replace(&mut self.repr, Zero); + match one { + One(v1) => mem::replace(&mut self.repr, Many(vec![v1, v])), + _ => unreachable!() + }; + } + Many(ref mut vs) => vs.push(v) + } + } + + pub fn push_all(&mut self, other: SmallVector<T>) { + for v in other.into_iter() { + self.push(v); + } + } + + pub fn get(&self, idx: usize) -> &T { + match self.repr { + One(ref v) if idx == 0 => v, + Many(ref vs) => &vs[idx], + _ => panic!("out of bounds access") + } + } + + pub fn expect_one(self, err: &'static str) -> T { + match self.repr { + One(v) => v, + Many(v) => { + if v.len() == 1 { + v.into_iter().next().unwrap() + } else { + panic!(err) + } + } + _ => panic!(err) + } + } + + pub fn len(&self) -> usize { + match self.repr { + Zero => 0, + One(..) => 1, + Many(ref vals) => vals.len() + } + } + + pub fn is_empty(&self) -> bool { self.len() == 0 } + + pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> SmallVector<U> { + let repr = match self.repr { + Zero => Zero, + One(t) => One(f(t)), + Many(vec) => Many(vec.into_iter().map(f).collect()), + }; + SmallVector { repr: repr } + } +} + +impl<T> ops::Deref for SmallVector<T> { + type Target = [T]; + + fn deref(&self) -> &[T] { + match self.repr { + Zero => { + let result: &[T] = &[]; + result + } + One(ref v) => { + unsafe { slice::from_raw_parts(v, 1) } + } + Many(ref vs) => vs + } + } +} + +impl<T> ops::DerefMut for SmallVector<T> { + fn deref_mut(&mut self) -> &mut [T] { + match self.repr { + Zero => { + let result: &mut [T] = &mut []; + result + } + One(ref mut v) => { + unsafe { slice::from_raw_parts_mut(v, 1) } + } + Many(ref mut vs) => vs + } + } +} + +impl<T> IntoIterator for SmallVector<T> { + type Item = T; + type IntoIter = IntoIter<T>; + fn into_iter(self) -> Self::IntoIter { + let repr = match self.repr { + Zero => ZeroIterator, + One(v) => OneIterator(v), + Many(vs) => ManyIterator(vs.into_iter()) + }; + IntoIter { repr: repr } + } +} + +pub struct IntoIter<T> { + repr: IntoIterRepr<T>, +} + +enum IntoIterRepr<T> { + ZeroIterator, + OneIterator(T), + ManyIterator(vec::IntoIter<T>), +} + +impl<T> Iterator for IntoIter<T> { + type Item = T; + + fn next(&mut self) -> Option<T> { + match self.repr { + ZeroIterator => None, + OneIterator(..) => { + let mut replacement = ZeroIterator; + mem::swap(&mut self.repr, &mut replacement); + match replacement { + OneIterator(v) => Some(v), + _ => unreachable!() + } + } + ManyIterator(ref mut inner) => inner.next() + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + match self.repr { + ZeroIterator => (0, Some(0)), + OneIterator(..) => (1, Some(1)), + ManyIterator(ref inner) => inner.size_hint() + } + } +} + +impl<T> MoveMap<T> for SmallVector<T> { + fn move_flat_map<F, I>(self, mut f: F) -> Self + where F: FnMut(T) -> I, + I: IntoIterator<Item=T> + { + match self.repr { + Zero => Self::zero(), + One(v) => f(v).into_iter().collect(), + Many(vs) => SmallVector { repr: Many(vs.move_flat_map(f)) }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_len() { + let v: SmallVector<isize> = SmallVector::new(); + assert_eq!(0, v.len()); + + assert_eq!(1, SmallVector::one(1).len()); + assert_eq!(5, SmallVector::many(vec![1, 2, 3, 4, 5]).len()); + } + + #[test] + fn test_push_get() { + let mut v = SmallVector::new(); + v.push(1); + assert_eq!(1, v.len()); + assert_eq!(1, v[0]); + v.push(2); + assert_eq!(2, v.len()); + assert_eq!(2, v[1]); + v.push(3); + assert_eq!(3, v.len()); + assert_eq!(3, v[2]); + } + + #[test] + fn test_from_iter() { + let v: SmallVector<isize> = (vec![1, 2, 3]).into_iter().collect(); + assert_eq!(3, v.len()); + assert_eq!(1, v[0]); + assert_eq!(2, v[1]); + assert_eq!(3, v[2]); + } + + #[test] + fn test_move_iter() { + let v = SmallVector::new(); + let v: Vec<isize> = v.into_iter().collect(); + assert_eq!(v, Vec::new()); + + let v = SmallVector::one(1); + assert_eq!(v.into_iter().collect::<Vec<_>>(), [1]); + + let v = SmallVector::many(vec![1, 2, 3]); + assert_eq!(v.into_iter().collect::<Vec<_>>(), [1, 2, 3]); + } + + #[test] + #[should_panic] + fn test_expect_one_zero() { + let _: isize = SmallVector::new().expect_one(""); + } + + #[test] + #[should_panic] + fn test_expect_one_many() { + SmallVector::many(vec![1, 2]).expect_one(""); + } + + #[test] + fn test_expect_one_one() { + assert_eq!(1, SmallVector::one(1).expect_one("")); + assert_eq!(1, SmallVector::many(vec![1]).expect_one("")); + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/util/thin_vec.rs b/bash-5.1/vendor/syntex_syntax/src/util/thin_vec.rs new file mode 100644 index 0000000..546686b --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/util/thin_vec.rs @@ -0,0 +1,59 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// A vector type optimized for cases where this size is usually 0 (c.f. `SmallVector`). +/// The `Option<Box<..>>` wrapping allows us to represent a zero sized vector with `None`, +/// which uses only a single (null) pointer. +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct ThinVec<T>(Option<Box<Vec<T>>>); + +impl<T> ThinVec<T> { + pub fn new() -> Self { + ThinVec(None) + } +} + +impl<T> From<Vec<T>> for ThinVec<T> { + fn from(vec: Vec<T>) -> Self { + if vec.is_empty() { + ThinVec(None) + } else { + ThinVec(Some(Box::new(vec))) + } + } +} + +impl<T> Into<Vec<T>> for ThinVec<T> { + fn into(self) -> Vec<T> { + match self { + ThinVec(None) => Vec::new(), + ThinVec(Some(vec)) => *vec, + } + } +} + +impl<T> ::std::ops::Deref for ThinVec<T> { + type Target = [T]; + fn deref(&self) -> &[T] { + match *self { + ThinVec(None) => &[], + ThinVec(Some(ref vec)) => vec, + } + } +} + +impl<T> Extend<T> for ThinVec<T> { + fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { + match *self { + ThinVec(Some(ref mut vec)) => vec.extend(iter), + ThinVec(None) => *self = iter.into_iter().collect::<Vec<_>>().into(), + } + } +} diff --git a/bash-5.1/vendor/syntex_syntax/src/visit.rs b/bash-5.1/vendor/syntex_syntax/src/visit.rs new file mode 100644 index 0000000..42fdc86 --- /dev/null +++ b/bash-5.1/vendor/syntex_syntax/src/visit.rs @@ -0,0 +1,812 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! AST walker. Each overridden visit method has full control over what +//! happens with its node, it can do its own traversal of the node's children, +//! call `visit::walk_*` to apply the default traversal algorithm, or prevent +//! deeper traversal by doing nothing. +//! +//! Note: it is an important invariant that the default visitor walks the body +//! of a function in "execution order" (more concretely, reverse post-order +//! with respect to the CFG implied by the AST), meaning that if AST node A may +//! execute before AST node B, then A is visited first. The borrow checker in +//! particular relies on this property. +//! +//! Note: walking an AST before macro expansion is probably a bad idea. For +//! instance, a walker looking for item names in a module will miss all of +//! those that are created by the expansion of a macro. + +use abi::Abi; +use ast::*; +use syntax_pos::Span; +use codemap::Spanned; + +#[derive(Copy, Clone, PartialEq, Eq)] +pub enum FnKind<'a> { + /// fn foo() or extern "Abi" fn foo() + ItemFn(Ident, &'a Generics, Unsafety, Spanned<Constness>, Abi, &'a Visibility, &'a Block), + + /// fn foo(&self) + Method(Ident, &'a MethodSig, Option<&'a Visibility>, &'a Block), + + /// |x, y| body + Closure(&'a Expr), +} + +/// Each method of the Visitor trait is a hook to be potentially +/// overridden. Each method's default implementation recursively visits +/// the substructure of the input via the corresponding `walk` method; +/// e.g. the `visit_mod` method by default calls `visit::walk_mod`. +/// +/// If you want to ensure that your code handles every variant +/// explicitly, you need to override each method. (And you also need +/// to monitor future changes to `Visitor` in case a new method with a +/// new default implementation gets introduced.) +pub trait Visitor<'ast>: Sized { + fn visit_name(&mut self, _span: Span, _name: Name) { + // Nothing to do. + } + fn visit_ident(&mut self, span: Span, ident: Ident) { + walk_ident(self, span, ident); + } + fn visit_mod(&mut self, m: &'ast Mod, _s: Span, _n: NodeId) { walk_mod(self, m) } + fn visit_foreign_item(&mut self, i: &'ast ForeignItem) { walk_foreign_item(self, i) } + fn visit_item(&mut self, i: &'ast Item) { walk_item(self, i) } + fn visit_local(&mut self, l: &'ast Local) { walk_local(self, l) } + fn visit_block(&mut self, b: &'ast Block) { walk_block(self, b) } + fn visit_stmt(&mut self, s: &'ast Stmt) { walk_stmt(self, s) } + fn visit_arm(&mut self, a: &'ast Arm) { walk_arm(self, a) } + fn visit_pat(&mut self, p: &'ast Pat) { walk_pat(self, p) } + fn visit_expr(&mut self, ex: &'ast Expr) { walk_expr(self, ex) } + fn visit_expr_post(&mut self, _ex: &'ast Expr) { } + fn visit_ty(&mut self, t: &'ast Ty) { walk_ty(self, t) } + fn visit_generics(&mut self, g: &'ast Generics) { walk_generics(self, g) } + fn visit_fn(&mut self, fk: FnKind<'ast>, fd: &'ast FnDecl, s: Span, _: NodeId) { + walk_fn(self, fk, fd, s) + } + fn visit_trait_item(&mut self, ti: &'ast TraitItem) { walk_trait_item(self, ti) } + fn visit_impl_item(&mut self, ii: &'ast ImplItem) { walk_impl_item(self, ii) } + fn visit_trait_ref(&mut self, t: &'ast TraitRef) { walk_trait_ref(self, t) } + fn visit_ty_param_bound(&mut self, bounds: &'ast TyParamBound) { + walk_ty_param_bound(self, bounds) + } + fn visit_poly_trait_ref(&mut self, t: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { + walk_poly_trait_ref(self, t, m) + } + fn visit_variant_data(&mut self, s: &'ast VariantData, _: Ident, + _: &'ast Generics, _: NodeId, _: Span) { + walk_struct_def(self, s) + } + fn visit_struct_field(&mut self, s: &'ast StructField) { walk_struct_field(self, s) } + fn visit_enum_def(&mut self, enum_definition: &'ast EnumDef, + generics: &'ast Generics, item_id: NodeId, _: Span) { + walk_enum_def(self, enum_definition, generics, item_id) + } + fn visit_variant(&mut self, v: &'ast Variant, g: &'ast Generics, item_id: NodeId) { + walk_variant(self, v, g, item_id) + } + fn visit_lifetime(&mut self, lifetime: &'ast Lifetime) { + walk_lifetime(self, lifetime) + } + fn visit_lifetime_def(&mut self, lifetime: &'ast LifetimeDef) { + walk_lifetime_def(self, lifetime) + } + fn visit_mac(&mut self, _mac: &'ast Mac) { + panic!("visit_mac disabled by default"); + // NB: see note about macros above. + // if you really want a visitor that + // works on macros, use this + // definition in your trait impl: + // visit::walk_mac(self, _mac) + } + fn visit_path(&mut self, path: &'ast Path, _id: NodeId) { + walk_path(self, path) + } + fn visit_path_list_item(&mut self, prefix: &'ast Path, item: &'ast PathListItem) { + walk_path_list_item(self, prefix, item) + } + fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) { + walk_path_segment(self, path_span, path_segment) + } + fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'ast PathParameters) { + walk_path_parameters(self, path_span, path_parameters) + } + fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { + walk_assoc_type_binding(self, type_binding) + } + fn visit_attribute(&mut self, _attr: &'ast Attribute) {} + fn visit_macro_def(&mut self, macro_def: &'ast MacroDef) { + walk_macro_def(self, macro_def) + } + fn visit_vis(&mut self, vis: &'ast Visibility) { + walk_vis(self, vis) + } + fn visit_fn_ret_ty(&mut self, ret_ty: &'ast FunctionRetTy) { + walk_fn_ret_ty(self, ret_ty) + } +} + +#[macro_export] +macro_rules! walk_list { + ($visitor: expr, $method: ident, $list: expr) => { + for elem in $list { + $visitor.$method(elem) + } + }; + ($visitor: expr, $method: ident, $list: expr, $($extra_args: expr),*) => { + for elem in $list { + $visitor.$method(elem, $($extra_args,)*) + } + } +} + +macro_rules! walk_opt { + ($visitor: expr, $method: ident, $opt: expr) => { + if let Some(ref elem) = *$opt { + $visitor.$method(elem) + } + } +} + +pub fn walk_opt_name<'a, V: Visitor<'a>>(visitor: &mut V, span: Span, opt_name: Option<Name>) { + if let Some(name) = opt_name { + visitor.visit_name(span, name); + } +} + +pub fn walk_opt_ident<'a, V: Visitor<'a>>(visitor: &mut V, span: Span, opt_ident: Option<Ident>) { + if let Some(ident) = opt_ident { + visitor.visit_ident(span, ident); + } +} + +pub fn walk_opt_sp_ident<'a, V: Visitor<'a>>(visitor: &mut V, + opt_sp_ident: &Option<Spanned<Ident>>) { + if let Some(ref sp_ident) = *opt_sp_ident { + visitor.visit_ident(sp_ident.span, sp_ident.node); + } +} + +pub fn walk_ident<'a, V: Visitor<'a>>(visitor: &mut V, span: Span, ident: Ident) { + visitor.visit_name(span, ident.name); +} + +pub fn walk_crate<'a, V: Visitor<'a>>(visitor: &mut V, krate: &'a Crate) { + visitor.visit_mod(&krate.module, krate.span, CRATE_NODE_ID); + walk_list!(visitor, visit_attribute, &krate.attrs); + walk_list!(visitor, visit_macro_def, &krate.exported_macros); +} + +pub fn walk_macro_def<'a, V: Visitor<'a>>(visitor: &mut V, macro_def: &'a MacroDef) { + visitor.visit_ident(macro_def.span, macro_def.ident); + walk_list!(visitor, visit_attribute, ¯o_def.attrs); +} + +pub fn walk_mod<'a, V: Visitor<'a>>(visitor: &mut V, module: &'a Mod) { + walk_list!(visitor, visit_item, &module.items); +} + +pub fn walk_local<'a, V: Visitor<'a>>(visitor: &mut V, local: &'a Local) { + for attr in local.attrs.iter() { + visitor.visit_attribute(attr); + } + visitor.visit_pat(&local.pat); + walk_opt!(visitor, visit_ty, &local.ty); + walk_opt!(visitor, visit_expr, &local.init); +} + +pub fn walk_lifetime<'a, V: Visitor<'a>>(visitor: &mut V, lifetime: &'a Lifetime) { + visitor.visit_name(lifetime.span, lifetime.name); +} + +pub fn walk_lifetime_def<'a, V: Visitor<'a>>(visitor: &mut V, lifetime_def: &'a LifetimeDef) { + visitor.visit_lifetime(&lifetime_def.lifetime); + walk_list!(visitor, visit_lifetime, &lifetime_def.bounds); + walk_list!(visitor, visit_attribute, &*lifetime_def.attrs); +} + +pub fn walk_poly_trait_ref<'a, V>(visitor: &mut V, + trait_ref: &'a PolyTraitRef, + _: &TraitBoundModifier) + where V: Visitor<'a>, +{ + walk_list!(visitor, visit_lifetime_def, &trait_ref.bound_lifetimes); + visitor.visit_trait_ref(&trait_ref.trait_ref); +} + +pub fn walk_trait_ref<'a, V: Visitor<'a>>(visitor: &mut V, trait_ref: &'a TraitRef) { + visitor.visit_path(&trait_ref.path, trait_ref.ref_id) +} + +pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) { + visitor.visit_vis(&item.vis); + visitor.visit_ident(item.span, item.ident); + match item.node { + ItemKind::ExternCrate(opt_name) => { + walk_opt_name(visitor, item.span, opt_name) + } + ItemKind::Use(ref vp) => { + match vp.node { + ViewPathSimple(ident, ref path) => { + visitor.visit_ident(vp.span, ident); + visitor.visit_path(path, item.id); + } + ViewPathGlob(ref path) => { + visitor.visit_path(path, item.id); + } + ViewPathList(ref prefix, ref list) => { + visitor.visit_path(prefix, item.id); + for item in list { + visitor.visit_path_list_item(prefix, item) + } + } + } + } + ItemKind::Static(ref typ, _, ref expr) | + ItemKind::Const(ref typ, ref expr) => { + visitor.visit_ty(typ); + visitor.visit_expr(expr); + } + ItemKind::Fn(ref declaration, unsafety, constness, abi, ref generics, ref body) => { + visitor.visit_fn(FnKind::ItemFn(item.ident, generics, unsafety, + constness, abi, &item.vis, body), + declaration, + item.span, + item.id) + } + ItemKind::Mod(ref module) => { + visitor.visit_mod(module, item.span, item.id) + } + ItemKind::ForeignMod(ref foreign_module) => { + walk_list!(visitor, visit_foreign_item, &foreign_module.items); + } + ItemKind::Ty(ref typ, ref type_parameters) => { + visitor.visit_ty(typ); + visitor.visit_generics(type_parameters) + } + ItemKind::Enum(ref enum_definition, ref type_parameters) => { + visitor.visit_generics(type_parameters); + visitor.visit_enum_def(enum_definition, type_parameters, item.id, item.span) + } + ItemKind::DefaultImpl(_, ref trait_ref) => { + visitor.visit_trait_ref(trait_ref) + } + ItemKind::Impl(_, _, + ref type_parameters, + ref opt_trait_reference, + ref typ, + ref impl_items) => { + visitor.visit_generics(type_parameters); + walk_opt!(visitor, visit_trait_ref, opt_trait_reference); + visitor.visit_ty(typ); + walk_list!(visitor, visit_impl_item, impl_items); + } + ItemKind::Struct(ref struct_definition, ref generics) | + ItemKind::Union(ref struct_definition, ref generics) => { + visitor.visit_generics(generics); + visitor.visit_variant_data(struct_definition, item.ident, + generics, item.id, item.span); + } + ItemKind::Trait(_, ref generics, ref bounds, ref methods) => { + visitor.visit_generics(generics); + walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_trait_item, methods); + } + ItemKind::Mac(ref mac) => visitor.visit_mac(mac), + } + walk_list!(visitor, visit_attribute, &item.attrs); +} + +pub fn walk_enum_def<'a, V: Visitor<'a>>(visitor: &mut V, + enum_definition: &'a EnumDef, + generics: &'a Generics, + item_id: NodeId) { + walk_list!(visitor, visit_variant, &enum_definition.variants, generics, item_id); +} + +pub fn walk_variant<'a, V>(visitor: &mut V, + variant: &'a Variant, + generics: &'a Generics, + item_id: NodeId) + where V: Visitor<'a>, +{ + visitor.visit_ident(variant.span, variant.node.name); + visitor.visit_variant_data(&variant.node.data, variant.node.name, + generics, item_id, variant.span); + walk_opt!(visitor, visit_expr, &variant.node.disr_expr); + walk_list!(visitor, visit_attribute, &variant.node.attrs); +} + +pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) { + match typ.node { + TyKind::Slice(ref ty) | TyKind::Paren(ref ty) => { + visitor.visit_ty(ty) + } + TyKind::Ptr(ref mutable_type) => { + visitor.visit_ty(&mutable_type.ty) + } + TyKind::Rptr(ref opt_lifetime, ref mutable_type) => { + walk_list!(visitor, visit_lifetime, opt_lifetime); + visitor.visit_ty(&mutable_type.ty) + } + TyKind::Never => {}, + TyKind::Tup(ref tuple_element_types) => { + walk_list!(visitor, visit_ty, tuple_element_types); + } + TyKind::BareFn(ref function_declaration) => { + walk_fn_decl(visitor, &function_declaration.decl); + walk_list!(visitor, visit_lifetime_def, &function_declaration.lifetimes); + } + TyKind::Path(ref maybe_qself, ref path) => { + if let Some(ref qself) = *maybe_qself { + visitor.visit_ty(&qself.ty); + } + visitor.visit_path(path, typ.id); + } + TyKind::ObjectSum(ref ty, ref bounds) => { + visitor.visit_ty(ty); + walk_list!(visitor, visit_ty_param_bound, bounds); + } + TyKind::Array(ref ty, ref expression) => { + visitor.visit_ty(ty); + visitor.visit_expr(expression) + } + TyKind::PolyTraitRef(ref bounds) => { + walk_list!(visitor, visit_ty_param_bound, bounds); + } + TyKind::ImplTrait(ref bounds) => { + walk_list!(visitor, visit_ty_param_bound, bounds); + } + TyKind::Typeof(ref expression) => { + visitor.visit_expr(expression) + } + TyKind::Infer | TyKind::ImplicitSelf => {} + TyKind::Mac(ref mac) => { + visitor.visit_mac(mac) + } + } +} + +pub fn walk_path<'a, V: Visitor<'a>>(visitor: &mut V, path: &'a Path) { + for segment in &path.segments { + visitor.visit_path_segment(path.span, segment); + } +} + +pub fn walk_path_list_item<'a, V: Visitor<'a>>(visitor: &mut V, + _prefix: &Path, + item: &'a PathListItem) { + visitor.visit_ident(item.span, item.node.name); + walk_opt_ident(visitor, item.span, item.node.rename); +} + +pub fn walk_path_segment<'a, V: Visitor<'a>>(visitor: &mut V, + path_span: Span, + segment: &'a PathSegment) { + visitor.visit_ident(path_span, segment.identifier); + if let Some(ref parameters) = segment.parameters { + visitor.visit_path_parameters(path_span, parameters); + } +} + +pub fn walk_path_parameters<'a, V>(visitor: &mut V, + _path_span: Span, + path_parameters: &'a PathParameters) + where V: Visitor<'a>, +{ + match *path_parameters { + PathParameters::AngleBracketed(ref data) => { + walk_list!(visitor, visit_ty, &data.types); + walk_list!(visitor, visit_lifetime, &data.lifetimes); + walk_list!(visitor, visit_assoc_type_binding, &data.bindings); + } + PathParameters::Parenthesized(ref data) => { + walk_list!(visitor, visit_ty, &data.inputs); + walk_opt!(visitor, visit_ty, &data.output); + } + } +} + +pub fn walk_assoc_type_binding<'a, V: Visitor<'a>>(visitor: &mut V, + type_binding: &'a TypeBinding) { + visitor.visit_ident(type_binding.span, type_binding.ident); + visitor.visit_ty(&type_binding.ty); +} + +pub fn walk_pat<'a, V: Visitor<'a>>(visitor: &mut V, pattern: &'a Pat) { + match pattern.node { + PatKind::TupleStruct(ref path, ref children, _) => { + visitor.visit_path(path, pattern.id); + walk_list!(visitor, visit_pat, children); + } + PatKind::Path(ref opt_qself, ref path) => { + if let Some(ref qself) = *opt_qself { + visitor.visit_ty(&qself.ty); + } + visitor.visit_path(path, pattern.id) + } + PatKind::Struct(ref path, ref fields, _) => { + visitor.visit_path(path, pattern.id); + for field in fields { + visitor.visit_ident(field.span, field.node.ident); + visitor.visit_pat(&field.node.pat) + } + } + PatKind::Tuple(ref tuple_elements, _) => { + walk_list!(visitor, visit_pat, tuple_elements); + } + PatKind::Box(ref subpattern) | + PatKind::Ref(ref subpattern, _) => { + visitor.visit_pat(subpattern) + } + PatKind::Ident(_, ref pth1, ref optional_subpattern) => { + visitor.visit_ident(pth1.span, pth1.node); + walk_opt!(visitor, visit_pat, optional_subpattern); + } + PatKind::Lit(ref expression) => visitor.visit_expr(expression), + PatKind::Range(ref lower_bound, ref upper_bound) => { + visitor.visit_expr(lower_bound); + visitor.visit_expr(upper_bound) + } + PatKind::Wild => (), + PatKind::Slice(ref prepatterns, ref slice_pattern, ref postpatterns) => { + walk_list!(visitor, visit_pat, prepatterns); + walk_opt!(visitor, visit_pat, slice_pattern); + walk_list!(visitor, visit_pat, postpatterns); + } + PatKind::Mac(ref mac) => visitor.visit_mac(mac), + } +} + +pub fn walk_foreign_item<'a, V: Visitor<'a>>(visitor: &mut V, foreign_item: &'a ForeignItem) { + visitor.visit_vis(&foreign_item.vis); + visitor.visit_ident(foreign_item.span, foreign_item.ident); + + match foreign_item.node { + ForeignItemKind::Fn(ref function_declaration, ref generics) => { + walk_fn_decl(visitor, function_declaration); + visitor.visit_generics(generics) + } + ForeignItemKind::Static(ref typ, _) => visitor.visit_ty(typ), + } + + walk_list!(visitor, visit_attribute, &foreign_item.attrs); +} + +pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyParamBound) { + match *bound { + TraitTyParamBound(ref typ, ref modifier) => { + visitor.visit_poly_trait_ref(typ, modifier); + } + RegionTyParamBound(ref lifetime) => { + visitor.visit_lifetime(lifetime); + } + } +} + +pub fn walk_generics<'a, V: Visitor<'a>>(visitor: &mut V, generics: &'a Generics) { + for param in &generics.ty_params { + visitor.visit_ident(param.span, param.ident); + walk_list!(visitor, visit_ty_param_bound, ¶m.bounds); + walk_list!(visitor, visit_ty, ¶m.default); + walk_list!(visitor, visit_attribute, &*param.attrs); + } + walk_list!(visitor, visit_lifetime_def, &generics.lifetimes); + for predicate in &generics.where_clause.predicates { + match *predicate { + WherePredicate::BoundPredicate(WhereBoundPredicate{ref bounded_ty, + ref bounds, + ref bound_lifetimes, + ..}) => { + visitor.visit_ty(bounded_ty); + walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_lifetime_def, bound_lifetimes); + } + WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime, + ref bounds, + ..}) => { + visitor.visit_lifetime(lifetime); + walk_list!(visitor, visit_lifetime, bounds); + } + WherePredicate::EqPredicate(WhereEqPredicate{id, + ref path, + ref ty, + ..}) => { + visitor.visit_path(path, id); + visitor.visit_ty(ty); + } + } + } +} + +pub fn walk_fn_ret_ty<'a, V: Visitor<'a>>(visitor: &mut V, ret_ty: &'a FunctionRetTy) { + if let FunctionRetTy::Ty(ref output_ty) = *ret_ty { + visitor.visit_ty(output_ty) + } +} + +pub fn walk_fn_decl<'a, V: Visitor<'a>>(visitor: &mut V, function_declaration: &'a FnDecl) { + for argument in &function_declaration.inputs { + visitor.visit_pat(&argument.pat); + visitor.visit_ty(&argument.ty) + } + visitor.visit_fn_ret_ty(&function_declaration.output) +} + +pub fn walk_fn<'a, V>(visitor: &mut V, kind: FnKind<'a>, declaration: &'a FnDecl, _span: Span) + where V: Visitor<'a>, +{ + match kind { + FnKind::ItemFn(_, generics, _, _, _, _, body) => { + visitor.visit_generics(generics); + walk_fn_decl(visitor, declaration); + visitor.visit_block(body); + } + FnKind::Method(_, ref sig, _, body) => { + visitor.visit_generics(&sig.generics); + walk_fn_decl(visitor, declaration); + visitor.visit_block(body); + } + FnKind::Closure(body) => { + walk_fn_decl(visitor, declaration); + visitor.visit_expr(body); + } + } +} + +pub fn walk_trait_item<'a, V: Visitor<'a>>(visitor: &mut V, trait_item: &'a TraitItem) { + visitor.visit_ident(trait_item.span, trait_item.ident); + walk_list!(visitor, visit_attribute, &trait_item.attrs); + match trait_item.node { + TraitItemKind::Const(ref ty, ref default) => { + visitor.visit_ty(ty); + walk_opt!(visitor, visit_expr, default); + } + TraitItemKind::Method(ref sig, None) => { + visitor.visit_generics(&sig.generics); + walk_fn_decl(visitor, &sig.decl); + } + TraitItemKind::Method(ref sig, Some(ref body)) => { + visitor.visit_fn(FnKind::Method(trait_item.ident, sig, None, body), + &sig.decl, trait_item.span, trait_item.id); + } + TraitItemKind::Type(ref bounds, ref default) => { + walk_list!(visitor, visit_ty_param_bound, bounds); + walk_opt!(visitor, visit_ty, default); + } + TraitItemKind::Macro(ref mac) => { + visitor.visit_mac(mac); + } + } +} + +pub fn walk_impl_item<'a, V: Visitor<'a>>(visitor: &mut V, impl_item: &'a ImplItem) { + visitor.visit_vis(&impl_item.vis); + visitor.visit_ident(impl_item.span, impl_item.ident); + walk_list!(visitor, visit_attribute, &impl_item.attrs); + match impl_item.node { + ImplItemKind::Const(ref ty, ref expr) => { + visitor.visit_ty(ty); + visitor.visit_expr(expr); + } + ImplItemKind::Method(ref sig, ref body) => { + visitor.visit_fn(FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis), body), + &sig.decl, impl_item.span, impl_item.id); + } + ImplItemKind::Type(ref ty) => { + visitor.visit_ty(ty); + } + ImplItemKind::Macro(ref mac) => { + visitor.visit_mac(mac); + } + } +} + +pub fn walk_struct_def<'a, V: Visitor<'a>>(visitor: &mut V, struct_definition: &'a VariantData) { + walk_list!(visitor, visit_struct_field, struct_definition.fields()); +} + +pub fn walk_struct_field<'a, V: Visitor<'a>>(visitor: &mut V, struct_field: &'a StructField) { + visitor.visit_vis(&struct_field.vis); + walk_opt_ident(visitor, struct_field.span, struct_field.ident); + visitor.visit_ty(&struct_field.ty); + walk_list!(visitor, visit_attribute, &struct_field.attrs); +} + +pub fn walk_block<'a, V: Visitor<'a>>(visitor: &mut V, block: &'a Block) { + walk_list!(visitor, visit_stmt, &block.stmts); +} + +pub fn walk_stmt<'a, V: Visitor<'a>>(visitor: &mut V, statement: &'a Stmt) { + match statement.node { + StmtKind::Local(ref local) => visitor.visit_local(local), + StmtKind::Item(ref item) => visitor.visit_item(item), + StmtKind::Expr(ref expression) | StmtKind::Semi(ref expression) => { + visitor.visit_expr(expression) + } + StmtKind::Mac(ref mac) => { + let (ref mac, _, ref attrs) = **mac; + visitor.visit_mac(mac); + for attr in attrs.iter() { + visitor.visit_attribute(attr); + } + } + } +} + +pub fn walk_mac<'a, V: Visitor<'a>>(_: &mut V, _: &Mac) { + // Empty! +} + +pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { + for attr in expression.attrs.iter() { + visitor.visit_attribute(attr); + } + match expression.node { + ExprKind::Box(ref subexpression) => { + visitor.visit_expr(subexpression) + } + ExprKind::InPlace(ref place, ref subexpression) => { + visitor.visit_expr(place); + visitor.visit_expr(subexpression) + } + ExprKind::Vec(ref subexpressions) => { + walk_list!(visitor, visit_expr, subexpressions); + } + ExprKind::Repeat(ref element, ref count) => { + visitor.visit_expr(element); + visitor.visit_expr(count) + } + ExprKind::Struct(ref path, ref fields, ref optional_base) => { + visitor.visit_path(path, expression.id); + for field in fields { + visitor.visit_ident(field.ident.span, field.ident.node); + visitor.visit_expr(&field.expr) + } + walk_opt!(visitor, visit_expr, optional_base); + } + ExprKind::Tup(ref subexpressions) => { + walk_list!(visitor, visit_expr, subexpressions); + } + ExprKind::Call(ref callee_expression, ref arguments) => { + visitor.visit_expr(callee_expression); + walk_list!(visitor, visit_expr, arguments); + } + ExprKind::MethodCall(ref ident, ref types, ref arguments) => { + visitor.visit_ident(ident.span, ident.node); + walk_list!(visitor, visit_ty, types); + walk_list!(visitor, visit_expr, arguments); + } + ExprKind::Binary(_, ref left_expression, ref right_expression) => { + visitor.visit_expr(left_expression); + visitor.visit_expr(right_expression) + } + ExprKind::AddrOf(_, ref subexpression) | ExprKind::Unary(_, ref subexpression) => { + visitor.visit_expr(subexpression) + } + ExprKind::Lit(_) => {} + ExprKind::Cast(ref subexpression, ref typ) | ExprKind::Type(ref subexpression, ref typ) => { + visitor.visit_expr(subexpression); + visitor.visit_ty(typ) + } + ExprKind::If(ref head_expression, ref if_block, ref optional_else) => { + visitor.visit_expr(head_expression); + visitor.visit_block(if_block); + walk_opt!(visitor, visit_expr, optional_else); + } + ExprKind::While(ref subexpression, ref block, ref opt_sp_ident) => { + visitor.visit_expr(subexpression); + visitor.visit_block(block); + walk_opt_sp_ident(visitor, opt_sp_ident); + } + ExprKind::IfLet(ref pattern, ref subexpression, ref if_block, ref optional_else) => { + visitor.visit_pat(pattern); + visitor.visit_expr(subexpression); + visitor.visit_block(if_block); + walk_opt!(visitor, visit_expr, optional_else); + } + ExprKind::WhileLet(ref pattern, ref subexpression, ref block, ref opt_sp_ident) => { + visitor.visit_pat(pattern); + visitor.visit_expr(subexpression); + visitor.visit_block(block); + walk_opt_sp_ident(visitor, opt_sp_ident); + } + ExprKind::ForLoop(ref pattern, ref subexpression, ref block, ref opt_sp_ident) => { + visitor.visit_pat(pattern); + visitor.visit_expr(subexpression); + visitor.visit_block(block); + walk_opt_sp_ident(visitor, opt_sp_ident); + } + ExprKind::Loop(ref block, ref opt_sp_ident) => { + visitor.visit_block(block); + walk_opt_sp_ident(visitor, opt_sp_ident); + } + ExprKind::Match(ref subexpression, ref arms) => { + visitor.visit_expr(subexpression); + walk_list!(visitor, visit_arm, arms); + } + ExprKind::Closure(_, ref function_declaration, ref body, _decl_span) => { + visitor.visit_fn(FnKind::Closure(body), + function_declaration, + expression.span, + expression.id) + } + ExprKind::Block(ref block) => visitor.visit_block(block), + ExprKind::Assign(ref left_hand_expression, ref right_hand_expression) => { + visitor.visit_expr(left_hand_expression); + visitor.visit_expr(right_hand_expression); + } + ExprKind::AssignOp(_, ref left_expression, ref right_expression) => { + visitor.visit_expr(left_expression); + visitor.visit_expr(right_expression); + } + ExprKind::Field(ref subexpression, ref ident) => { + visitor.visit_expr(subexpression); + visitor.visit_ident(ident.span, ident.node); + } + ExprKind::TupField(ref subexpression, _) => { + visitor.visit_expr(subexpression); + } + ExprKind::Index(ref main_expression, ref index_expression) => { + visitor.visit_expr(main_expression); + visitor.visit_expr(index_expression) + } + ExprKind::Range(ref start, ref end, _) => { + walk_list!(visitor, visit_expr, start); + walk_list!(visitor, visit_expr, end); + } + ExprKind::Path(ref maybe_qself, ref path) => { + if let Some(ref qself) = *maybe_qself { + visitor.visit_ty(&qself.ty); + } + visitor.visit_path(path, expression.id) + } + ExprKind::Break(ref opt_sp_ident, ref opt_expr) => { + walk_opt_sp_ident(visitor, opt_sp_ident); + walk_list!(visitor, visit_expr, opt_expr); + } + ExprKind::Continue(ref opt_sp_ident) => { + walk_opt_sp_ident(visitor, opt_sp_ident); + } + ExprKind::Ret(ref optional_expression) => { + walk_list!(visitor, visit_expr, optional_expression); + } + ExprKind::Mac(ref mac) => visitor.visit_mac(mac), + ExprKind::Paren(ref subexpression) => { + visitor.visit_expr(subexpression) + } + ExprKind::InlineAsm(ref ia) => { + for &(_, ref input) in &ia.inputs { + visitor.visit_expr(&input) + } + for output in &ia.outputs { + visitor.visit_expr(&output.expr) + } + } + ExprKind::Try(ref subexpression) => { + visitor.visit_expr(subexpression) + } + } + + visitor.visit_expr_post(expression) +} + +pub fn walk_arm<'a, V: Visitor<'a>>(visitor: &mut V, arm: &'a Arm) { + walk_list!(visitor, visit_pat, &arm.pats); + walk_opt!(visitor, visit_expr, &arm.guard); + visitor.visit_expr(&arm.body); + walk_list!(visitor, visit_attribute, &arm.attrs); +} + +pub fn walk_vis<'a, V: Visitor<'a>>(visitor: &mut V, vis: &'a Visibility) { + if let Visibility::Restricted { ref path, id } = *vis { + visitor.visit_path(path, id); + } +} diff --git a/bash-5.1/vendor/target_build_utils/.cargo-checksum.json b/bash-5.1/vendor/target_build_utils/.cargo-checksum.json new file mode 100644 index 0000000..e971094 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"91fb05f84fda62f2f1f6271f91077fc860349d17289a3056892419189f948818","README.md":"6f54aa0c069383caf076e5e3417949bc3f0d2a317927f5a0d619402af59ac16b","appveyor.yml":"97fce4e40fb26ccb8cebeb24bcb86074a2e8aa650e9fec56c08cac0838f80f31","build.rs":"5aa55162b40e43d1141a0346758b9dfbcc6b821d44dc1598e24921f6438ebf04","src/changelog.rs":"3ef2a084251ed575f6d4e350c02918a77665db988c9f41d010c29648faede01b","src/lib.rs":"627fedc2347b4cb1fc61bc97d54825f4a6be08ba4363ff579d96859c57ab7b11","src/my-great-target.json":"4be6fbe16c9c8e643972a3343687395fdb1dde5e65f741a0c5ae734e3f316347"},"package":"013d134ae4a25ee744ad6129db589018558f620ddfa44043887cdd45fa08e75c"} \ No newline at end of file diff --git a/bash-5.1/vendor/target_build_utils/Cargo.toml b/bash-5.1/vendor/target_build_utils/Cargo.toml new file mode 100644 index 0000000..8955c27 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "target_build_utils" +version = "0.3.1" +authors = ["Simonas Kazlauskas <target_build_utils@kazlauskas.me>"] +description = "DEPRECATED: Use Cargo environment variables `CARGO_CFG_TARGET_*`" +keywords = ["target", "triple", "json", "build"] +license = "ISC/Apache-2.0" +repository = "https://github.com/nagisa/target_build_utils.rs" +documentation = "https://docs.rs/target_build_utils" +build = "build.rs" + +[features] +default = ["serde_json"] + +[dependencies] +serde_json = { version = "0.9", optional = true } +phf = "0.7" + +[build-dependencies] +phf_codegen = "0.7" diff --git a/bash-5.1/vendor/target_build_utils/README.md b/bash-5.1/vendor/target_build_utils/README.md new file mode 100644 index 0000000..c3e128c --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/README.md @@ -0,0 +1,62 @@ +# DEPRECATED + +Use environment variables set by cargo from 1.14.0 onwards. + +They look like this: `CARGO_CFG_TARGET_OS`, `CARGO_CFG_TARGET_ENV`… + +--- + +[![Travis CI][tcii]][tci] [![Appveyor CI][acii]][aci] + +[tcii]: https://travis-ci.org/nagisa/target_build_utils.rs.svg?branch=master +[tci]: https://travis-ci.org/nagisa/target_build_utils.rs +[acii]: https://ci.appveyor.com/api/projects/status/jasfj7r1o085xpxo?svg=true +[aci]: https://ci.appveyor.com/project/nagisa/target-build-utils-rs + +Utility crate to handle the `TARGET` environment variable passed into build.rs scripts. + +Unlike rust’s `#[cfg(target…)]` attributes, `build.rs`-scripts do not expose a convenient way +to detect the system the code will be built for in a way which would properly support +cross-compilation. + +This crate exposes `target_arch`, `target_vendor`, `target_os` and `target_abi` very much in +the same manner as the corresponding `cfg` attributes in Rust do, thus allowing `build.rs` +script to adjust the output depending on the target the crate is being built for.. + +Custom target json files are also supported. + +# Using target_build_utils + +This crate is only useful if you’re using a build script (`build.rs`). Add dependency to this +crate to your `Cargo.toml` via: + +```toml +[package] +# ... +build = "build.rs" + +[build-dependencies] +target_build_utils = "0.1" +``` + +Then write your `build.rs` like this: + +```rust,no_run +extern crate target_build_utils; +use target_build_utils::TargetInfo; + +fn main() { + let target = TargetInfo::new().expect("could not get target info"); + if target.target_os() == "windows" { + // conditional stuff for windows + } +} +``` + +Now, when running `cargo build`, your `build.rs` should be aware of the properties of the +target system when your crate is being cross-compiled. + +# License + +llvm_build_utils is distributed under ISC (MIT-like) or Apache (version 2.0) license at your +choice. diff --git a/bash-5.1/vendor/target_build_utils/appveyor.yml b/bash-5.1/vendor/target_build_utils/appveyor.yml new file mode 100644 index 0000000..ee4ba67 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/appveyor.yml @@ -0,0 +1,20 @@ +environment: + matrix: + - TARGET: nightly-x86_64-pc-windows-msvc + - TARGET: nightly-i686-pc-windows-msvc + - TARGET: nightly-x86_64-pc-windows-gnu + - TARGET: nightly-i686-pc-windows-gnu + - TARGET: 1.12.0-x86_64-pc-windows-msvc + - TARGET: 1.12.0-i686-pc-windows-msvc + - TARGET: 1.12.0-x86_64-pc-windows-gnu + - TARGET: 1.12.0-i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust.exe" + - ps: .\rust.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null + - ps: $env:PATH="$env:PATH;C:\rust\bin" + - rustc -vV + - cargo -vV +build: off +test_script: + - cargo test + - cargo test --no-default-features diff --git a/bash-5.1/vendor/target_build_utils/build.rs b/bash-5.1/vendor/target_build_utils/build.rs new file mode 100644 index 0000000..23d2342 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/build.rs @@ -0,0 +1,111 @@ +extern crate phf_codegen; + +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::fmt::Write as FmtWrite; + +fn main(){ + let mut cmd = std::env::var_os("RUSTC") + .map(|c| Command::new(c)) + .unwrap_or(Command::new("rustc")); + let c = cmd + .args(&["--print=target-list"]) + .stdout(Stdio::piped()) + .spawn() + .expect("Could not spawn rustc!"); + let targets = c.wait_with_output().expect("could not wait for rustc to exit"); + if !targets.status.success() { + println!("rustc --print=target-list did not exit successfully"); + std::process::exit(1); + } + let output = Path::new(&::std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("builtins.rs"); + let mut file = BufWriter::new(File::create(&output).expect("builtins.rs file")); + + let stdout = String::from_utf8_lossy(&targets.stdout); + write!(&mut file, "static BUILTINS: phf::Map<&'static str, TargetInfo> = ").unwrap(); + let mut map = phf_codegen::Map::new(); + for line in stdout.lines() { + let cfg = cfg_for_target(line); + if !cfg.is_empty() { + map.entry(line, &cfg); + } + } + map.build(&mut file).unwrap(); + write!(&mut file, ";").unwrap(); +} + + +fn cfg_for_target(target: &str) -> String { + let mut cmd = std::env::var_os("RUSTC") + .map(|c| Command::new(c)) + .unwrap_or(Command::new("rustc")); + let c = cmd + .args(&["--target", target, "--print=cfg"]) + .stdout(Stdio::piped()) + .spawn().and_then(|c| c.wait_with_output()); + + if let Ok(o) = c { + if o.status.success() { + let string = String::from_utf8_lossy(&o.stdout); + let mut switches = Vec::new(); + let mut other_keys = Vec::new(); + let (mut arch, mut os, mut env, mut endian, mut ptrw) = ("", "", "", "", ""); + for (k, v) in parse(&string) { + match (k, v) { + ("target_arch", Some(v)) => arch = v, + ("target_os", Some(v)) => os = v, + ("target_env", Some(v)) => env = v, + ("target_endian", Some(v)) => endian = v, + ("target_pointer_width", Some(v)) => ptrw = v, + (_, None) => match k { + "unix" | + "windows" | + "target_thread_local" => switches.push(k), + _ => println!("Switch `{}` blacklisted", k), + }, + (k, Some(v)) => other_keys.push((k, v)), + } + } + let mut switches_fmt = String::with_capacity(1024); + let mut other_keys_fmt = String::with_capacity(4096); + switches_fmt.push_str("["); + for switch in switches { + write!(switches_fmt, "B({:?}), ", switch).expect("writes to String do not fail"); + } + switches_fmt.push_str("]"); + other_keys_fmt.push_str("["); + for (k, v) in other_keys { + write!(other_keys_fmt, "(B({:?}), B({:?})), ", k, v) + .expect("writes to String do not fail"); + } + other_keys_fmt.push_str("]"); + + format!("TargetInfo {{ \ + arch: B({:?}), \ + os: B({:?}), \ + env: B({:?}), \ + endian: B({:?}), \ + pointer_width: B({:?}), \ + switches: B(&{}), \ + other_keys: B(&{}) \ + }}", arch, os, env, endian, ptrw, switches_fmt, other_keys_fmt) + } else { + println!("rustc --print=cfg --target={} did not exit successfully", target); + String::new() + } + } else { + String::new() + } +} + +fn parse(i: &str) -> Vec<(&str, Option<&str>)> { + i.lines().map(|line| { + let mut split = line.split('='); + let key = split.next().expect("probably bug"); + let val = split.next().map(|v| v.trim().trim_matches('"')); + debug_assert!(split.next().is_none()); + (key, val) + }).collect() +} diff --git a/bash-5.1/vendor/target_build_utils/src/changelog.rs b/bash-5.1/vendor/target_build_utils/src/changelog.rs new file mode 100644 index 0000000..2b27876 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/src/changelog.rs @@ -0,0 +1,46 @@ +//! Project Changelog + +/// Release 0.3.0 (2017-02-10) +/// +/// # Breaking changes +/// +/// * The `Error` enumeration gained a new variant `CustomTargetsUnsupported` to signify the fact +/// this particular build of the crate does not support custom JSON targets. +/// +/// # Other changes +/// +/// * `serde_json` is now an enabled-by-default optional dependency. If custom target support is +/// not necessary in your project, it can be disabled with [`default-features = +/// false`](http://doc.crates.io/specifying-dependencies.html#choosing-features). +pub mod r0_3_0 {} + +/// Release 0.2.1 (2017-02-03) +/// +/// * Upgrade serde to 0.9 +pub mod r0_2_1 {} + +/// Release 0.2.0 (2017-01-18) +/// +/// # Breaking changes +/// +/// * `TargetInfo::target_vendor` changed signature to return `Option<&str>` instead of `&str`. +/// Non-nightly rustc doesn’t give the information about target vendor, so it is not available when +/// compiling with stable/beta rustc. +/// +/// # Other changes +/// +/// * Added `TargetInfo::target_cfg`. Can be used to emulate e.g. `#[cfg(unix)]` or +/// `#[cfg(windows)]`. +/// * Added `TargetInfo::target_cfg_value`. Can be used to extract more obscure target properties +/// such as `#[cfg(target_has_atomic = "64")]`. Note that many of these depend on rustc channel, +/// just like `target_vendor`. +pub mod r0_2_0 {} + +/// Release 0.1.2 (2016-10-17) +/// +/// * Now figures out target info from the rustc that is used to compile the library. This results +/// in less divergence between versions of rustc (i.e. when targets are added), but is not able to +/// provide target info for some targets on some hosts anymore. For example all `*-apple-ios` +/// targets are not available anymore on the linux host. +/// * `Error` implements `std::error::Error` trait now. +pub mod r0_1_2 {} diff --git a/bash-5.1/vendor/target_build_utils/src/lib.rs b/bash-5.1/vendor/target_build_utils/src/lib.rs new file mode 100644 index 0000000..78c7bc3 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/src/lib.rs @@ -0,0 +1,568 @@ +//! # DEPRECATED +//! Use environment variables set by cargo from 1.14.0 onwards. +//! +//! They look like this: `CARGO_CFG_TARGET_OS`, `CARGO_CFG_TARGET_ENV`… +//! +//! --- +//! +//! Utility crate to handle the `TARGET` environment variable passed into build.rs scripts. +//! +//! Unlike rust’s `#[cfg(target…)]` attributes, `build.rs`-scripts do not expose a convenient way +//! to detect the system the code will be built for in a way which would properly support +//! cross-compilation. +//! +//! This crate exposes `target_arch`, `target_vendor`, `target_os` and `target_abi` very much in +//! the same manner as the corresponding `cfg` attributes in Rust do, thus allowing `build.rs` +//! script to adjust the output depending on the target the crate is being built for.. +//! +//! Custom target json files are also supported. +//! +//! # Usage +//! +//! This crate is only useful if you’re using a build script (`build.rs`). Add dependency to this +//! crate to your `Cargo.toml` via: +//! +//! ```toml +//! [package] +//! # ... +//! build = "build.rs" +//! +//! [build-dependencies] +//! target_build_utils = "0.1" +//! ``` +//! +//! Then write your `build.rs` like this: +//! +//! ```rust,no_run +//! extern crate target_build_utils; +//! use target_build_utils::TargetInfo; +//! +//! fn main() { +//! let target = TargetInfo::new().expect("could not get target info"); +//! if target.target_os() == "windows" { +//! // conditional stuff for windows +//! } +//! } +//! ``` +//! +//! Now, when running `cargo build`, your `build.rs` should be aware of the properties of the +//! target system when your crate is being cross-compiled. +#[cfg(feature = "serde_json")] +extern crate serde_json; +extern crate phf; + +use std::env; +use std::path::{Path, PathBuf}; +use std::ffi::OsString; +use std::borrow::Cow; +use std::borrow::Cow::Borrowed as B; + +pub mod changelog; + +#[derive(Debug)] +pub enum Error { + /// The `TARGET` environment variable does not exist or is not valid utf-8 + TargetUnset, + /// Target was not found + TargetNotFound, + /// Custom target JSON was found, but was invalid + InvalidSpec, + /// IO error occured during search of JSON target files + Io(::std::io::Error), + /// Crate was built without support for custom targets JSON file + CustomTargetsUnsupported, +} + +impl ::std::fmt::Display for Error { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + Error::Io(ref e) => <::std::io::Error as ::std::fmt::Display>::fmt(e, fmt), + ref e => fmt.write_str(std::error::Error::description(e)), + } + } +} + +impl ::std::error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::TargetUnset => "TARGET environment variable is not set or is not valid utf-8", + Error::TargetNotFound => "The requested target was not found", + Error::InvalidSpec => "Custom target JSON file was not valid", + Error::Io(ref e) => e.description(), + Error::CustomTargetsUnsupported => "Support for custom target JSON file was disabled at compilation", + } + } + + fn cause(&self) -> Option<&::std::error::Error> { + match *self { + Error::Io(ref e) => Some(e), + _ => None + } + } +} + + +include!(concat!(env!("OUT_DIR"), "/builtins.rs")); + +#[derive(Clone, Debug)] +pub struct TargetInfo { + arch: Cow<'static, str>, + os: Cow<'static, str>, + env: Cow<'static, str>, + endian: Cow<'static, str>, + pointer_width: Cow<'static, str>, + // Switches such as `cfg(unix)` + switches: Cow<'static, [Cow<'static, str>]>, + // Other keys such as `target_vendor` or `target_has_atomic` + other_keys: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>, +} + +impl TargetInfo { + /// Parse the target info from `TARGET` environment variable + /// + /// `TARGET` environment variable is usually set for you in build.rs scripts, therefore this + /// function is all that’s necessary in majority of cases. + /// + /// # Example + /// + /// ```rust,no_run + /// use target_build_utils::TargetInfo; + /// let target = TargetInfo::new().expect("could not get target"); + /// ``` + pub fn new() -> Result<TargetInfo, Error> { + env::var("TARGET").map_err(|_| Error::TargetUnset).and_then(|s| TargetInfo::from_str(&s)) + } + + /// Calculate the target info from the provided target value + /// + /// String may contain a triple or path to the json file. + /// + /// # Example + /// + /// ```rust,no_run + /// use target_build_utils::TargetInfo; + /// let target = TargetInfo::from_str("x86_64-unknown-linux-gnu") + /// .expect("could not get target"); + /// ``` + pub fn from_str(s: &str) -> Result<TargetInfo, Error> { + #[cfg(feature = "serde_json")] + fn load_json(path: &Path) -> Result<TargetInfo, Error> { + use std::fs::File; + use serde_json as s; + let f = try!(File::open(path).map_err(|e| Error::Io(e))); + let json: s::Value = try!(s::from_reader(f).map_err(|_| Error::InvalidSpec)); + let req = |name: &str| + json.get(name).and_then(|a| a.as_str()).ok_or(Error::InvalidSpec); + + let vendor = json.get("vendor").and_then(|s| s.as_str()).unwrap_or("unknown").into(); + Ok(TargetInfo { + arch: Cow::Owned(try!(req("arch")).into()), + os: Cow::Owned(try!(req("os")).into()), + env: Cow::Owned(json.get("env").and_then(|s| s.as_str()).unwrap_or("").into()), + endian: Cow::Owned(try!(req("target-endian")).into()), + pointer_width: Cow::Owned(try!(req("target-pointer-width")).into()), + switches: B(&[]), + other_keys: Cow::Owned(vec![(B("target_vendor"), Cow::Owned(vendor))]), + }) + } + + #[cfg(not(feature = "serde_json"))] + fn load_json(_: &Path) -> Result<TargetInfo, Error> { + Err(Error::CustomTargetsUnsupported) + } + + if let Some(t) = TargetInfo::load_specific(s) { + return Ok(t); + } + let path = Path::new(s); + if path.is_file() { + return load_json(&path); + } + let path = { + let mut target = String::from(s); + target.push_str(".json"); + PathBuf::from(target) + }; + let target_path = env::var_os("RUST_TARGET_PATH") + .unwrap_or(OsString::new()); + for dir in env::split_paths(&target_path) { + let p = dir.join(&path); + if p.is_file() { + return load_json(&p); + } + } + Err(Error::TargetNotFound) + } + + fn load_specific(s: &str) -> Option<TargetInfo> { + BUILTINS.get(s).cloned() + } +} + +impl TargetInfo { + /// Architecture of the targeted machine + /// + /// Corresponds to the `#[cfg(target_arch = {})]` in Rust code. + pub fn target_arch(&self) -> &str { + &*self.arch + } + /// OS of the targeted machine + /// + /// Corresponds to the `#[cfg(target_os = {})]` in Rust code. + pub fn target_os(&self) -> &str { + &*self.os + } + /// Environment (ABI) of the targeted machine + /// + /// Corresponds to the `#[cfg(target_env = {})]` in Rust code. + pub fn target_env(&self) -> &str { + &*self.env + } + /// Endianess of the targeted machine + /// + /// Valid values are: `little` and `big`. + /// + /// Corresponds to the `#[cfg(target_endian = {})]` in Rust code. + pub fn target_endian(&self) -> &str { + &*self.endian + } + /// Pointer width of the targeted machine + /// + /// Corresponds to the `#[cfg(target_pointer_width = {})]` in Rust code. + pub fn target_pointer_width(&self) -> &str { + &*self.pointer_width + } + + /// Vendor of the targeted machine + /// + /// Corresponds to the `#[cfg(target_vendor = {})]` in Rust code. + /// + /// This currently returns `Some` only when when targetting nightly rustc version as well as + /// for custom JSON targets. + pub fn target_vendor(&self) -> Option<&str> { + self.target_cfg_value("target_vendor") + } + + /// Check if the configuration switch is set for target + /// + /// Corresponds to the `#[cfg({key} = {})]` in Rust code. + /// + /// This function behaves specially in regard to custom JSON targets and will always return + /// `false` for them currently. + /// + /// # Examples + /// + /// ```rust,no_run + /// use target_build_utils::TargetInfo; + /// let info = TargetInfo::new().expect("target info"); + /// let is_unix = info.target_cfg("unix"); + /// ``` + pub fn target_cfg(&self, key: &str) -> bool { + self.switches.iter().any(|x| x == key) + } + + /// Return the value of an arbitrary configuration key + /// + /// This function behaves specially in regard to custom JSON targets and will rarely return + /// any extra target information. + /// + /// # Examples + /// + /// ```rust,no_run + /// use target_build_utils::TargetInfo; + /// let info = TargetInfo::new().expect("target info"); + /// assert_eq!(info.target_cfg_value("target_os"), Some(info.target_os())); + /// assert_eq!(info.target_cfg_value("target_banana"), None); + /// ``` + pub fn target_cfg_value<'a>(&'a self, key: &str) -> Option<&'a str> { + match key { + "target_arch" => Some(self.target_arch()), + "target_os" => Some(self.target_os()), + "target_env" => Some(self.target_env()), + "target_endian" => Some(self.target_endian()), + "target_pointer_width" => Some(self.target_pointer_width()), + key => self.other_keys.iter().find(|t| t.0 == key).map(|t| &*t.1) + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn correct_archs() { + macro_rules! check_arch { + ($expected: expr, $bit: expr, $end: expr, $($str: expr),+) => { + $( + if let Ok(ti) = super::TargetInfo::from_str($str) { + assert_eq!(ti.target_arch(), $expected); + assert_eq!(ti.target_endian(), $end); + assert_eq!(ti.target_pointer_width(), $bit); + } + )+ + } + } + check_arch!("x86_64", "64", "little" + , "x86_64-unknown-linux-gnu" + , "x86_64-unknown-linux-musl" + , "x86_64-unknown-freebsd" + , "x86_64-unknown-dragonfly" + , "x86_64-unknown-bitrig" + , "x86_64-unknown-openbsd" + , "x86_64-unknown-netbsd" + , "x86_64-rumprun-netbsd" + , "x86_64-apple-darwin" + , "x86_64-apple-ios" + , "x86_64-sun-solaris" + , "x86_64-pc-windows-gnu" + , "x86_64-pc-windows-msvc"); + + check_arch!("x86", "32", "little" + , "i586-unknown-linux-gnu" + , "i686-unknown-linux-musl" + , "i686-linux-android" + , "i686-unknown-freebsd" + , "i686-unknown-dragonfly" + , "i686-apple-darwin" + , "i686-pc-windows-gnu" + , "i686-pc-windows-msvc" + , "i586-pc-windows-msvc" + , "i386-apple-ios"); + check_arch!("mips", "32", "big" + , "mips-unknown-linux-musl" + , "mips-unknown-linux-gnu"); + check_arch!("mips", "32", "little" + , "mipsel-unknown-linux-musl" + , "mipsel-unknown-linux-gnu"); + check_arch!("aarch64", "64", "little" + , "aarch64-unknown-linux-gnu" + , "aarch64-linux-android" + , "aarch64-apple-ios"); + check_arch!("arm", "32", "little" + , "arm-unknown-linux-gnueabi" + , "arm-unknown-linux-gnueabihf" + , "arm-linux-androideabi" + , "armv7-linux-androideabi" + , "armv7-apple-ios"); + check_arch!("powerpc", "32", "big", "powerpc-unknown-linux-gnu"); + check_arch!("powerpc64", "64", "big" + , "powerpc64-unknown-linux-gnu"); + check_arch!("powerpc64", "64", "little" + , "powerpc64le-unknown-linux-gnu"); + } + + #[test] + fn correct_vendors() { + macro_rules! check_vnd { + ($expected: expr, $($str: expr),+) => { + $( + if let Ok(ti) = super::TargetInfo::from_str($str) { + if let Some(vnd) = ti.target_vendor() { + assert_eq!(vnd, $expected); + } + } + )+ + } + } + check_vnd!("unknown", "x86_64-unknown-linux-gnu" + , "x86_64-unknown-linux-musl" + , "x86_64-unknown-freebsd" + , "x86_64-unknown-dragonfly" + , "x86_64-unknown-bitrig" + , "x86_64-unknown-openbsd" + , "x86_64-unknown-netbsd" + , "i686-unknown-linux-gnu" + , "i586-unknown-linux-gnu" + , "i686-unknown-linux-musl" + , "i686-unknown-freebsd" + , "i686-unknown-dragonfly" + , "mips-unknown-linux-musl" + , "mips-unknown-linux-gnu" + , "mipsel-unknown-linux-musl" + , "mipsel-unknown-linux-gnu" + , "aarch64-unknown-linux-gnu" + , "arm-unknown-linux-gnueabi" + , "arm-unknown-linux-gnueabihf" + , "armv7-unknown-linux-gnueabihf" + , "powerpc-unknown-linux-gnu" + , "powerpc64-unknown-linux-gnu" + , "powerpc64le-unknown-linux-gnu" + , "i686-linux-android" + , "aarch64-linux-android" + , "arm-linux-androideabi" + , "armv7-linux-androideabi"); + check_vnd!("apple", "x86_64-apple-darwin" + , "x86_64-apple-ios" + , "i686-apple-darwin" + , "i386-apple-ios" + , "aarch64-apple-ios" + , "armv7-apple-ios" + , "armv7s-apple-ios"); + check_vnd!("pc", "x86_64-pc-windows-gnu" + , "x86_64-pc-windows-msvc" + , "i686-pc-windows-gnu" + , "i686-pc-windows-msvc" + , "i586-pc-windows-msvc"); + check_vnd!("rumprun", "x86_64-rumprun-netbsd"); + check_vnd!("sun", "x86_64-sun-solaris"); + } + + #[test] + fn correct_os() { + macro_rules! check_os { + ($expected: expr, $($str: expr),+) => { + $( + if let Ok(ti) = super::TargetInfo::from_str($str) { + assert_eq!(ti.target_os(), $expected); + } + )+ + } + } + check_os!("linux", "x86_64-unknown-linux-gnu" + , "x86_64-unknown-linux-musl" + , "i686-unknown-linux-gnu" + , "i586-unknown-linux-gnu" + , "i686-unknown-linux-musl" + , "mips-unknown-linux-musl" + , "mips-unknown-linux-gnu" + , "mipsel-unknown-linux-musl" + , "mipsel-unknown-linux-gnu" + , "aarch64-unknown-linux-gnu" + , "arm-unknown-linux-gnueabi" + , "arm-unknown-linux-gnueabihf" + , "armv7-unknown-linux-gnueabihf" + , "powerpc-unknown-linux-gnu" + , "powerpc64-unknown-linux-gnu" + , "powerpc64le-unknown-linux-gnu"); + check_os!("android", "i686-linux-android" + , "aarch64-linux-android" + , "arm-linux-androideabi" + , "armv7-linux-androideabi"); + check_os!("windows", "x86_64-pc-windows-gnu" + , "x86_64-pc-windows-msvc" + , "i686-pc-windows-gnu" + , "i686-pc-windows-msvc" + , "i586-pc-windows-msvc"); + check_os!("freebsd", "x86_64-unknown-freebsd" + , "i686-unknown-freebsd"); + check_os!("dragonfly", "x86_64-unknown-dragonfly" + , "i686-unknown-dragonfly"); + check_os!("bitrig", "x86_64-unknown-bitrig"); + check_os!("openbsd", "x86_64-unknown-openbsd"); + check_os!("netbsd", "x86_64-unknown-netbsd" + , "x86_64-rumprun-netbsd"); + check_os!("solaris", "x86_64-sun-solaris"); + check_os!("macos", "x86_64-apple-darwin" + , "i686-apple-darwin"); + check_os!("ios", "x86_64-apple-ios" + , "i386-apple-ios" + , "aarch64-apple-ios" + , "armv7-apple-ios" + , "armv7s-apple-ios"); + } + + #[test] + fn correct_env() { + macro_rules! check_env { + ($expected: expr, $($str: expr),+) => { + $( + if let Ok(ti) = super::TargetInfo::from_str($str) { + assert_eq!(ti.target_env(), $expected); + } + )+ + } + } + check_env!("gnu", "x86_64-unknown-linux-gnu" + , "i686-unknown-linux-gnu" + , "i586-unknown-linux-gnu" + , "mips-unknown-linux-gnu" + , "mipsel-unknown-linux-gnu" + , "aarch64-unknown-linux-gnu" + , "arm-unknown-linux-gnueabi" + , "arm-unknown-linux-gnueabihf" + , "armv7-unknown-linux-gnueabihf" + , "powerpc-unknown-linux-gnu" + , "powerpc64-unknown-linux-gnu" + , "powerpc64le-unknown-linux-gnu" + , "x86_64-pc-windows-gnu" + , "i686-pc-windows-gnu"); + check_env!("musl", "x86_64-unknown-linux-musl" + , "i686-unknown-linux-musl" + , "mips-unknown-linux-musl" + , "mipsel-unknown-linux-musl"); + check_env!("msvc", "x86_64-pc-windows-msvc" + , "i686-pc-windows-msvc" + , "i586-pc-windows-msvc"); + check_env!("", "i686-linux-android" + , "aarch64-linux-android" + , "arm-linux-androideabi" + , "armv7-linux-androideabi" + , "x86_64-unknown-freebsd" + , "i686-unknown-freebsd" + , "x86_64-unknown-dragonfly" + , "i686-unknown-dragonfly" + , "x86_64-unknown-bitrig" + , "x86_64-unknown-openbsd" + , "x86_64-unknown-netbsd" + , "x86_64-rumprun-netbsd" + , "x86_64-sun-solaris" + , "x86_64-apple-darwin" + , "i686-apple-darwin" + , "x86_64-apple-ios" + , "i386-apple-ios" + , "aarch64-apple-ios" + , "armv7-apple-ios" + , "armv7s-apple-ios" + ); + } + + #[test] + #[cfg(feature = "serde_json")] + fn external_work() { + use std::env; + env::set_var("TARGET", "src/my-great-target.json"); + let target = super::TargetInfo::new().unwrap(); + external_is_correct(&target); + } + + #[test] + #[cfg(not(feature = "serde_json"))] + fn external_work() { + use std::env; + env::set_var("TARGET", "src/my-great-target.json"); + super::TargetInfo::new().err().unwrap(); + } + + #[test] + #[cfg(feature = "serde_json")] + fn external_search_work() { + use std::env; + env::set_var("RUST_TARGET_PATH", ""); + super::TargetInfo::from_str("my-great-target").err().unwrap(); + env::set_var("RUST_TARGET_PATH", env::join_paths(&["/usr/"]).unwrap()); + super::TargetInfo::from_str("my-great-target").err().unwrap(); + env::set_var("RUST_TARGET_PATH", env::join_paths(&["/usr/","src/"]).unwrap()); + let target = super::TargetInfo::from_str("my-great-target").unwrap(); + external_is_correct(&target); + } + + #[test] + #[cfg(not(feature = "serde_json"))] + fn external_search_work() { + use std::env; + env::set_var("RUST_TARGET_PATH", ""); + super::TargetInfo::from_str("my-great-target").err().unwrap(); + env::set_var("RUST_TARGET_PATH", env::join_paths(&["/usr/"]).unwrap()); + super::TargetInfo::from_str("my-great-target").err().unwrap(); + env::set_var("RUST_TARGET_PATH", env::join_paths(&["/usr/","src/"]).unwrap()); + super::TargetInfo::from_str("my-great-target").err().unwrap(); + } + + #[cfg(feature = "serde_json")] + fn external_is_correct(ti: &super::TargetInfo) { + assert_eq!(ti.target_arch(), "x86_64"); + assert_eq!(ti.target_endian(), "little"); + assert_eq!(ti.target_pointer_width(), "42"); + assert_eq!(ti.target_os(), "nux"); + assert_eq!(ti.target_vendor(), Some("unknown")); + } +} diff --git a/bash-5.1/vendor/target_build_utils/src/my-great-target.json b/bash-5.1/vendor/target_build_utils/src/my-great-target.json new file mode 100644 index 0000000..c24c8e1 --- /dev/null +++ b/bash-5.1/vendor/target_build_utils/src/my-great-target.json @@ -0,0 +1,10 @@ +{ + "pre-link-args": ["-m64"], + "data-layout": "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128", + "llvm-target": "x86_64-unknown-linux-gnu", + "target-endian": "little", + "target-pointer-width": "42", + "arch": "x86_64", + "os": "nux", + "morestack": false +} diff --git a/bash-5.1/vendor/term/.cargo-checksum.json b/bash-5.1/vendor/term/.cargo-checksum.json new file mode 100644 index 0000000..fad2ef9 --- /dev/null +++ b/bash-5.1/vendor/term/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"f88e383191ad44e3f49cb5ed1389fd1f0cca6be0e9cc5f37f11c323186cd8bf6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"f5d6df44431e0814368b2890d954ae2253efb7765925582de8be11eb16a505a6","appveyor.yml":"da991211b72fa6f231af7adb84c9fb72f5a9131d1c0a3d47b8ceffe5a82c8542","rustfmt.toml":"be851a0fa92766755e54e163ccceedee0b28ea6d527888c48f1cbc766f23733c","scripts/id_rsa.enc":"210d1476adba1c08d77329d9f71dba828c0516d8ae659c6317c9bee4683e5d50","scripts/travis-doc-upload.cfg":"2609cb89644596a2ede3cd63b7a5fb6e84ee56c2b880ff67584e9655f4a2e777","src/lib.rs":"53c4f63f2bc07326024b8663961790ecd0a136b14c38eacb4c751764da5d5f2c","src/terminfo/mod.rs":"a47021ff3bca69131cbd23b3df0143a9baebf2c1949687ec1b726b29b157ba6f","src/terminfo/parm.rs":"efde5f3ab1cb5a646f51f07bd90cd05154e7d080c96dc03ae33dc2a125c5aedd","src/terminfo/parser/compiled.rs":"8f5a87d19c0bdfbc95f9fed8deb447e07d1368abca6d147f79c14b2f164b4a11","src/terminfo/parser/names.rs":"dd32022a5f198abc40fa68566c0798725451345173a7d80c80e05a121c8cf0f8","src/terminfo/searcher.rs":"5602a32e555762e5171c1865c2c1b3b6bb092b8c233f413bc0933658bed40b67","src/win.rs":"9efbdc4bb18b317e3d98fa58e441cc8903710ac0e6f315899329660cf6d10277","tests/data/dumb":"123c85a2812a517d967db5f31660db0e6aded4a0b95ed943c5ab435368e7a25c","tests/data/linux":"9dcec472e8ec612e84b46c2b8ae17a4f47b2ccfe93bc7b16970bbaaa20fab1e9","tests/data/linux-16color":"eb0b5684a42db662ebaa0043cc4bb5e082b09a7312796ec669e0159fce6af499","tests/data/linux-basic":"1373c033c6a891911a0a478e5f9654600e84dbfe2d16f649ba2fc08802335a0c","tests/data/linux-c":"50807ab8371b45bd80ca9d563de882b733b5db88cff7646e40c344e98ef755ed","tests/data/linux-c-nc":"d88eb59f749d91be3148ce39dec7c050d95feb516702ed7f9f6cec7a58b424a7","tests/data/linux-koi8":"4b7d942f03ce95d45802029db0c87879eb93be50b43026c63c18a3552dd37c93","tests/data/linux-koi8r":"7267d93deec24396a9955e95da621c054d8d677634b465d798f792141b24e1de","tests/data/linux-lat":"b72b2ec68fa445e2e0ae96cc7bb2149a1527e11ae475d1957c8a22d9ec2c0905","tests/data/linux-m":"4a92f6fef1eeb679ec4511579d3004cfe6fc1d4dd73fed5299cde568f6cf3fbf","tests/data/linux-nic":"eac886df04c80e6ba02687087ddc93635c0f433f4f28195447499a8963989f21","tests/data/linux-vt":"2ebd4c761a492190609f6d8bcdd8f9c8c81e281b0d5e8a51b87f4ba126370bb4","tests/data/linux2.2":"c3d6e1466e9fb4111f4bf243b87a3de290d85224f1a4241947a3f51bdff08b82","tests/data/linux2.6":"52c2930ab1cad8271c280fefb1f581b12b7b3be445348d047a39f5e3448b3614","tests/data/linux2.6.26":"88f5a62b78956a21015ac887c5189a9f72900a842c2f844a1a5e197151a078d2","tests/data/linux3.0":"29b2aad27b5c291adab85e4150883fa6dc0034671c67e889d722168735ba2504","tests/data/rxvt":"9411be0058e147fc7a1962cd35145446d3d439ac3be9b6ca9d3aa2aa0c28ef5e","tests/data/rxvt-16color":"d41e75a0bad0e7c6d957c727f68dc507898685f3bbd71f0721a0a4beb14daf08","tests/data/rxvt-256color":"e6415e230d7962133d1da913cfcf23a0e2d3ed75379164a921feb9462c475a8e","tests/data/rxvt-88color":"958a81509d2b1e2cfe5a7bcf7a15e81d12575e4ccaa1dd308eda8edf7905a36a","tests/data/rxvt-basic":"3989e1c659121cb8fd8f67b8bff7f304e52c1f401cd1d09e906e11a58e0bc587","tests/data/rxvt-color":"3d2b49d48aca7fad7a3bf26d06592207b3c3cbf7afc3a5223fd0613f50a2739b","tests/data/rxvt-cygwin":"d50e434af6b3ab85b26e4f6af21c9c612d271efacaff3e64ef3da8c350a91809","tests/data/rxvt-cygwin-native":"34ee4ef070d9c366f5aba8f72a29a0e45ab552ba43b3e32265dfbe9eef157994","tests/data/rxvt-xpm":"4e8e40313ef00f0572456724249a625c36f2c5338b5014b87f236e29f612212e","tests/data/screen":"57c2888ffb9d7632381dc6191657abda998ca5f0958ad5787f848ff2206198f9","tests/data/screen-256color":"13fd658c693283ffb495d7f473bf525422e312e199bff6e64abdb70db5b22f46","tests/data/xterm":"67a59e4f0807759546dbf45c0bc2dddb30944ef553990345b1d08d7d19ddc13a","tests/data/xterm-256color":"e2525d133091a1ac38b2ad4eecd8df48eee31789c8fafac0ed99bcd6b746d8ce","tests/terminfo.rs":"e07390f101f2c109a15c2274eb31a96c602845c75f33f2775ed2a6b98ffbdf5a"},"package":"fa63644f74ce96fbeb9b794f66aff2a52d601cbd5e80f4b97123e3899f4570f1"} \ No newline at end of file diff --git a/bash-5.1/vendor/term/Cargo.toml b/bash-5.1/vendor/term/Cargo.toml new file mode 100644 index 0000000..fc1c2d7 --- /dev/null +++ b/bash-5.1/vendor/term/Cargo.toml @@ -0,0 +1,31 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "term" +version = "0.4.6" +authors = ["The Rust Project Developers", "Steven Allen"] +description = "A terminal formatting library\n" +homepage = "https://github.com/Stebalien/term" +documentation = "https://stebalien.github.io/doc/term/term/" +readme = "README.md" +categories = ["command-line-interface"] +license = "MIT/Apache-2.0" +repository = "https://github.com/Stebalien/term" + +[features] +default = [] +[target."cfg(windows)".dependencies.kernel32-sys] +version = "0.2" + +[target."cfg(windows)".dependencies.winapi] +version = "0.2" diff --git a/bash-5.1/vendor/term/LICENSE-APACHE b/bash-5.1/vendor/term/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/term/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/term/LICENSE-MIT b/bash-5.1/vendor/term/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bash-5.1/vendor/term/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/term/README.md b/bash-5.1/vendor/term/README.md new file mode 100644 index 0000000..e1b75ec --- /dev/null +++ b/bash-5.1/vendor/term/README.md @@ -0,0 +1,36 @@ +term +==== + +A Rust library for terminfo parsing and terminal colors. + +[![Build Status](https://travis-ci.org/Stebalien/term.svg?branch=master)](https://travis-ci.org/Stebalien/term) +[![Build status](https://ci.appveyor.com/api/projects/status/2duvop23k4n3owyt?svg=true)](https://ci.appveyor.com/project/Stebalien/term) + +[Documentation](https://stebalien.github.io/doc/term/term/) + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] + +term = "*" +``` + +and this to your crate root: + +```rust +extern crate term; +``` + +## Packaging and Distributing + +For all terminals but windows consoles, this library depends on a non-hashed +(for now) terminfo database being present. For example, on Debian derivitives, +you should depend on ncurses-term; on Arch Linux, you depend on ncurses; and on +MinGW, you should depend on mingw32-terminfo. + +Unfortunately, if you're using a non-windows console on Windows (e.g. MinGW, +Cygwin, Git Bash), you'll need to set the TERMINFO environment variable to +point to the directory containing the terminfo database. diff --git a/bash-5.1/vendor/term/appveyor.yml b/bash-5.1/vendor/term/appveyor.yml new file mode 100644 index 0000000..6a1b8dc --- /dev/null +++ b/bash-5.1/vendor/term/appveyor.yml @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose diff --git a/bash-5.1/vendor/term/rustfmt.toml b/bash-5.1/vendor/term/rustfmt.toml new file mode 100644 index 0000000..f86d8d1 --- /dev/null +++ b/bash-5.1/vendor/term/rustfmt.toml @@ -0,0 +1,3 @@ +wrap_match_arms = true +struct_lit_multiline_style = "ForceMulti" +wrap_comments = false diff --git a/bash-5.1/vendor/term/scripts/id_rsa.enc b/bash-5.1/vendor/term/scripts/id_rsa.enc new file mode 100644 index 0000000000000000000000000000000000000000..8fb90fa04d3600d9b6d4b6ee538f570693af471a GIT binary patch literal 1680 zcmV;B25<Q%1mY;M+5YU{b5s=&o=DR6k3^@HLK)3D{J(fu+C5rBspa+->E^ogt80r( zzme&mJUFnLimQ`9-~q!oz>PC_hwmzWVTnmMmVY3jen0*RFe3xZYY1Q}dX#qK=qMh! zyROZHe*9tN*uNwn^i&+SN~}=;ri-2}QdP!s!x-L!+t>QMj%)%k$3fYyxuPS-b$0#h zG$v8hi6tou#CDp!I_7fi#(|YQH>$%2oofOYo(l<L5fnNXADxa$JZ@lm3%np=bde71 zrh8>%`828RQ!6zP@_C<{<|~VPr$Gse{+=I^+8*}-@AGnaj61T!4980SXzu8@cy%37 zm9*#M)o6fSQrdIBC2+Xs-bXRga6pL&rOT9a;!kb+vvtm*q$cf!fHT}A?HP%XX^2SE zfADZjEKXKHY-`$a0wHh^+X!X?`6~+<*ySigp!4pW?m`GQofK)~um1dIT{<pAWVUD! z>=j>k{Me60?cKbYjD4uo=2gZ(o0frzk*&_K26t!MauBFaJn23KRmDg>vLPs%eaT!9 z`cFH8cPQ0HLihtOlp<au8q4WZEl!jp)}h*G(}=ljH4U=n7CAw4$fQ98<A+fsk=|ct zf#W`$vVQIX0X9g?Q+*%RXdS$=eQ_WhY@S4skow{3^nkfCu7*k5H@N3i36kR4`|O1C z{AS~NBlNoyrXBGG3)G0vn5&N5Y<{gKE#@WlS7d2^(e=Er2IS+4U2Gl}cuyHJmSt9D zN9Xcg03gC~k;avR?g4$6gvrkoIn0!_g^8akYHW=#wpj{{Hk|Sx=USfGU-tpW`F>nE z`y1Z{{K!qGQx~zR&S?CyX}MxXi^m(K#0%*(2&(7pQa~oax(9U!W{#$DHd1x~8!+!_ zCLo7a=-Iy!sulhZ?aMA;JaA+36W9_HI7sR}rz=4rS1TIRK}{cErSLIU1<H>(Q=C){ z7<Pg54^jL5I%qg+PYa3bHYAt(Wsg?vcuWi5iFore@v|bsw6s{+zH$2~s>5Wr9^%zU zqO9804ip}nL<Njgws_f(V0TV6v8?B&wTO)3D6MqI&Afc6GL$#+3kWI`T;{B0>fYm- zt0j3YS=rLYZs<9lKFw2r%g8FgVU>xIrdEJ)1VR0CC$ocDb>#-?sKH?$H;&R=xd-}? zX2_=MAZ+h=207wJoU730Gm%Hnrlf5bcUiSCWrXbCYm4lWJt81`G0+W<@%34v4d!@n zufn;(2N<>)SmzSm2+KZ~Ux6COao?D!oL0%y!O3vxxhVG^q-FwOAY((WZE(i0Ny7jY z?0j){v!RH6J!FT@hWmIBzFU=K{m-b~p95IJCersHlywxihTtJtsL(=_ilbkTUaQtw z@rb=;4(0tHv?9HcT5Ww?Nt<eG<$G(akoT@I#Q&1tbA{TN26e--9|n0(xRrN{3`#$% zhWLyZPfLGfG1_&l7K1JQ{};-%Wt8bq0;_CUlMXWEUgALRHLRbO2<Dj3b%dNg=nE+` z{4vE7jm2%_f+p4dS&{yjxXIdrDm;-)9UE3csmj>NgT4VGEj`3`c-zY<NUIC#UZU$Z zVCPj(dhwrgjA1_AmkQGu#EiJEQ6&n@iNY3MH3opjp`Y|LHN4RKpv%Qd1SD3%!r}Gg z%T=#}@APZUgBUuxDv>A3&|xZ%$}|uKCmuRYn342x=)=$jr@Y0<Gl-*y0bh!<zEJ$N zvr)VxADl0VX_h+UCzN*|-sa$th=-CEK0`m5`7@qF8fOtbi-TQfsf7HKQ7}>;JRakS z<647upq#(T;^2B-dY`Q7zrNUUX$?L=NPB1%Pvljm+sG%XgkX-cX#C;W#C#b=If{~N z2`DjfX9-0f$MA(pLy9My80Q!=N$;-ufPinG-B7*6%H4|Y3?pmT+dsI5z)Tw?lbt$y zQR$n|F`EK7Yc@-5`t%lLk(4;1L9njrA+adbf&J6&_o_>xH8d@VxCx_Tdr<L?<?&2q znv=8Wb2a!cx;HhM-9>sf-~(ea6u==zRT<O4>k%K5;g+y)-FUc-Gj)0N0Va235-&$C z$bw2tCem-`6t3_0DQ&DR95nN3=yNT1rzMEgp5=EL)vTn3i!VY)^$urT&_QyTM&ftj z-pTcGL9!`%Zwk2ncex(H4I#U*B(T?#bY{Jo8#SU=D5JBvDKT;w)qjKyigthTPnN6_ aPb;Ec5;j_Ue-paC$w4z$<DSUme2`p1iAbmb literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/scripts/travis-doc-upload.cfg b/bash-5.1/vendor/term/scripts/travis-doc-upload.cfg new file mode 100644 index 0000000..8abd391 --- /dev/null +++ b/bash-5.1/vendor/term/scripts/travis-doc-upload.cfg @@ -0,0 +1,3 @@ +PROJECT_NAME=term +DOCS_REPO=Stebalien/doc.git +SSH_KEY_TRAVIS_ID=b92a405b42db diff --git a/bash-5.1/vendor/term/src/lib.rs b/bash-5.1/vendor/term/src/lib.rs new file mode 100644 index 0000000..a5824d4 --- /dev/null +++ b/bash-5.1/vendor/term/src/lib.rs @@ -0,0 +1,401 @@ +// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Terminal formatting library. +//! +//! This crate provides the `Terminal` trait, which abstracts over an [ANSI +//! Terminal][ansi] to provide color printing, among other things. There are two +//! implementations, the `TerminfoTerminal`, which uses control characters from +//! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console +//! API][win]. +//! +//! # Usage +//! +//! This crate is [on crates.io](https://crates.io/crates/term) and can be +//! used by adding `term` to the dependencies in your project's `Cargo.toml`. +//! +//! ```toml +//! [dependencies] +//! +//! term = "0.4.6" +//! ``` +//! +//! and this to your crate root: +//! +//! ```rust +//! extern crate term; +//! ``` +//! +//! # Examples +//! +//! ```no_run +//! extern crate term; +//! use std::io::prelude::*; +//! +//! fn main() { +//! let mut t = term::stdout().unwrap(); +//! +//! t.fg(term::color::GREEN).unwrap(); +//! write!(t, "hello, ").unwrap(); +//! +//! t.fg(term::color::RED).unwrap(); +//! writeln!(t, "world!").unwrap(); +//! +//! t.reset().unwrap(); +//! } +//! ``` +//! +//! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code +//! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx +//! [ti]: https://en.wikipedia.org/wiki/Terminfo + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://doc.rust-lang.org/favicon.ico", + html_root_url = "https://stebalien.github.io/doc/term/term/", + test(attr(deny(warnings))))] +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] + +use std::io::prelude::*; + +pub use terminfo::TerminfoTerminal; +#[cfg(windows)] +pub use win::WinConsole; + +use std::io::{self, Stdout, Stderr}; + +pub mod terminfo; + +#[cfg(windows)] +mod win; + +/// Alias for stdout terminals. +pub type StdoutTerminal = Terminal<Output = Stdout> + Send; +/// Alias for stderr terminals. +pub type StderrTerminal = Terminal<Output = Stderr> + Send; + +#[cfg(not(windows))] +/// Return a Terminal wrapping stdout, or None if a terminal couldn't be +/// opened. +pub fn stdout() -> Option<Box<StdoutTerminal>> { + TerminfoTerminal::new(io::stdout()).map(|t| Box::new(t) as Box<StdoutTerminal>) +} + +#[cfg(windows)] +/// Return a Terminal wrapping stdout, or None if a terminal couldn't be +/// opened. +pub fn stdout() -> Option<Box<StdoutTerminal>> { + TerminfoTerminal::new(io::stdout()) + .map(|t| Box::new(t) as Box<StdoutTerminal>) + .or_else(|| WinConsole::new(io::stdout()).ok().map(|t| Box::new(t) as Box<StdoutTerminal>)) +} + +#[cfg(not(windows))] +/// Return a Terminal wrapping stderr, or None if a terminal couldn't be +/// opened. +pub fn stderr() -> Option<Box<StderrTerminal>> { + TerminfoTerminal::new(io::stderr()).map(|t| Box::new(t) as Box<StderrTerminal>) +} + +#[cfg(windows)] +/// Return a Terminal wrapping stderr, or None if a terminal couldn't be +/// opened. +pub fn stderr() -> Option<Box<StderrTerminal>> { + TerminfoTerminal::new(io::stderr()) + .map(|t| Box::new(t) as Box<StderrTerminal>) + .or_else(|| WinConsole::new(io::stderr()).ok().map(|t| Box::new(t) as Box<StderrTerminal>)) +} + + +/// Terminal color definitions +#[allow(missing_docs)] +pub mod color { + /// Number for a terminal color + pub type Color = u16; + + pub const BLACK: Color = 0; + pub const RED: Color = 1; + pub const GREEN: Color = 2; + pub const YELLOW: Color = 3; + pub const BLUE: Color = 4; + pub const MAGENTA: Color = 5; + pub const CYAN: Color = 6; + pub const WHITE: Color = 7; + + pub const BRIGHT_BLACK: Color = 8; + pub const BRIGHT_RED: Color = 9; + pub const BRIGHT_GREEN: Color = 10; + pub const BRIGHT_YELLOW: Color = 11; + pub const BRIGHT_BLUE: Color = 12; + pub const BRIGHT_MAGENTA: Color = 13; + pub const BRIGHT_CYAN: Color = 14; + pub const BRIGHT_WHITE: Color = 15; +} + +/// Terminal attributes for use with term.attr(). +/// +/// Most attributes can only be turned on and must be turned off with term.reset(). +/// The ones that can be turned off explicitly take a boolean value. +/// Color is also represented as an attribute for convenience. +#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] +pub enum Attr { + /// Bold (or possibly bright) mode + Bold, + /// Dim mode, also called faint or half-bright. Often not supported + Dim, + /// Italics mode. Often not supported + Italic(bool), + /// Underline mode + Underline(bool), + /// Blink mode + Blink, + /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold + Standout(bool), + /// Reverse mode, inverts the foreground and background colors + Reverse, + /// Secure mode, also called invis mode. Hides the printed text + Secure, + /// Convenience attribute to set the foreground color + ForegroundColor(color::Color), + /// Convenience attribute to set the background color + BackgroundColor(color::Color), +} + +/// An error arising from interacting with the terminal. +#[derive(Debug)] +pub enum Error { + /// Indicates an error from any underlying IO + Io(io::Error), + /// Indicates an error during terminfo parsing + TerminfoParsing(terminfo::Error), + /// Indicates an error expanding a parameterized string from the terminfo database + ParameterizedExpansion(terminfo::parm::Error), + /// Indicates that the terminal does not support the requested operation. + NotSupported, + /// Indicates that the `TERM` environment variable was unset, and thus we were unable to detect + /// which terminal we should be using. + TermUnset, + /// Indicates that we were unable to find a terminfo entry for the requested terminal. + TerminfoEntryNotFound, + /// Indicates that the cursor could not be moved to the requested position. + CursorDestinationInvalid, + /// Indicates that the terminal does not support displaying the requested color. + /// + /// This is like `NotSupported`, but more specific. + ColorOutOfRange, + #[doc(hidden)] + /// Please don't match against this - if you do, we can't promise we won't break your crate + /// with a semver-compliant version bump. + __Nonexhaustive, +} + +// manually implemented because std::io::Error does not implement Eq/PartialEq +impl std::cmp::PartialEq for Error { + fn eq(&self, other: &Error) -> bool { + use Error::*; + match *self { + Io(_) => false, + TerminfoParsing(ref inner1) => { + match *other { + TerminfoParsing(ref inner2) => inner1 == inner2, + _ => false, + } + } + ParameterizedExpansion(ref inner1) => { + match *other { + ParameterizedExpansion(ref inner2) => inner1 == inner2, + _ => false, + } + } + NotSupported => { + match *other { + NotSupported => true, + _ => false, + } + } + TermUnset => { + match *other { + TermUnset => true, + _ => false, + } + } + TerminfoEntryNotFound => { + match *other { + TerminfoEntryNotFound => true, + _ => false, + } + } + CursorDestinationInvalid => { + match *other { + CursorDestinationInvalid => true, + _ => false, + } + } + ColorOutOfRange => { + match *other { + ColorOutOfRange => true, + _ => false, + } + } + __Nonexhaustive => { + match *other { + __Nonexhaustive => true, + _ => false, + } + } + } + } +} + +/// The canonical `Result` type using this crate's Error type. +pub type Result<T> = std::result::Result<T, Error>; + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + use std::error::Error; + if let ::Error::Io(ref e) = *self { + write!(f, "{}", e) + } else { + f.write_str(self.description()) + } + } +} + +impl std::error::Error for Error { + fn description(&self) -> &str { + use Error::*; + match *self { + Io(ref io) => io.description(), + TerminfoParsing(ref e) => e.description(), + ParameterizedExpansion(ref e) => e.description(), + NotSupported => "operation not supported by the terminal", + TermUnset => "TERM environment variable unset, unable to detect a terminal", + TerminfoEntryNotFound => "could not find a terminfo entry for this terminal", + CursorDestinationInvalid => "could not move cursor to requested position", + ColorOutOfRange => "color not supported by the terminal", + __Nonexhaustive => "placeholder variant that shouldn't be used", + } + } + + fn cause(&self) -> Option<&std::error::Error> { + match *self { + Error::Io(ref io) => Some(io), + Error::TerminfoParsing(ref e) => Some(e), + Error::ParameterizedExpansion(ref e) => Some(e), + _ => None, + } + } +} + +impl From<Error> for io::Error { + fn from(err: Error) -> io::Error { + let kind = match err { + Error::Io(ref e) => e.kind(), + _ => io::ErrorKind::Other, + }; + io::Error::new(kind, err) + } +} + +impl std::convert::From<io::Error> for Error { + fn from(val: io::Error) -> Self { + Error::Io(val) + } +} + +impl std::convert::From<terminfo::Error> for Error { + fn from(val: terminfo::Error) -> Self { + Error::TerminfoParsing(val) + } +} + +impl std::convert::From<terminfo::parm::Error> for Error { + fn from(val: terminfo::parm::Error) -> Self { + Error::ParameterizedExpansion(val) + } +} + +/// A terminal with similar capabilities to an ANSI Terminal +/// (foreground/background colors etc). +pub trait Terminal: Write { + /// The terminal's output writer type. + type Output: Write; + + /// Sets the foreground color to the given color. + /// + /// If the color is a bright color, but the terminal only supports 8 colors, + /// the corresponding normal color will be used instead. + /// + /// Returns `Ok(())` if the color change code was sent to the terminal, or `Err(e)` if there + /// was an error. + fn fg(&mut self, color: color::Color) -> Result<()>; + + /// Sets the background color to the given color. + /// + /// If the color is a bright color, but the terminal only supports 8 colors, + /// the corresponding normal color will be used instead. + /// + /// Returns `Ok(())` if the color change code was sent to the terminal, or `Err(e)` if there + /// was an error. + fn bg(&mut self, color: color::Color) -> Result<()>; + + /// Sets the given terminal attribute, if supported. Returns `Ok(())` if the attribute is + /// supported and was sent to the terminal, or `Err(e)` if there was an error or the attribute + /// wasn't supported. + fn attr(&mut self, attr: Attr) -> Result<()>; + + /// Returns whether the given terminal attribute is supported. + fn supports_attr(&self, attr: Attr) -> bool; + + /// Resets all terminal attributes and colors to their defaults. + /// + /// Returns `Ok(())` if the reset code was printed, or `Err(e)` if there was an error. + /// + /// *Note: This does not flush.* + /// + /// That means the reset command may get buffered so, if you aren't planning on doing anything + /// else that might flush stdout's buffer (e.g. writing a line of text), you should flush after + /// calling reset. + fn reset(&mut self) -> Result<()>; + + /// Returns true if reset is supported. + fn supports_reset(&self) -> bool; + + /// Returns true if color is fully supported. + /// + /// If this function returns `true`, `bg`, `fg`, and `reset` will never + /// return `Err(Error::NotSupported)`. + fn supports_color(&self) -> bool; + + /// Moves the cursor up one line. + /// + /// Returns `Ok(())` if the cursor movement code was printed, or `Err(e)` if there was an + /// error. + fn cursor_up(&mut self) -> Result<()>; + + /// Deletes the text from the cursor location to the end of the line. + /// + /// Returns `Ok(())` if the deletion code was printed, or `Err(e)` if there was an error. + fn delete_line(&mut self) -> Result<()>; + + /// Moves the cursor to the left edge of the current line. + /// + /// Returns `Ok(true)` if the deletion code was printed, or `Err(e)` if there was an error. + fn carriage_return(&mut self) -> Result<()>; + + /// Gets an immutable reference to the stream inside + fn get_ref(&self) -> &Self::Output; + + /// Gets a mutable reference to the stream inside + fn get_mut(&mut self) -> &mut Self::Output; + + /// Returns the contained stream, destroying the `Terminal` + fn into_inner(self) -> Self::Output where Self: Sized; +} diff --git a/bash-5.1/vendor/term/src/terminfo/mod.rs b/bash-5.1/vendor/term/src/terminfo/mod.rs new file mode 100644 index 0000000..71cdd64 --- /dev/null +++ b/bash-5.1/vendor/term/src/terminfo/mod.rs @@ -0,0 +1,403 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Terminfo database interface. + +use std::collections::HashMap; +use std::env; +use std::fs::File; +use std::io::prelude::*; +use std::io; +use std::io::BufReader; +use std::path::Path; + +use Attr; +use color; +use Terminal; +use Result; +use self::searcher::get_dbpath_for_term; +use self::parser::compiled::parse; +use self::parm::{expand, Variables, Param}; +use self::Error::*; + + +/// Returns true if the named terminal supports basic ANSI escape codes. +fn is_ansi(name: &str) -> bool { + // SORTED! We binary search this. + static ANSI_TERM_PREFIX: &'static [&'static str] = &[ + "Eterm", + "ansi", + "eterm", + "iterm", + "konsole", + "linux", + "mrxvt", + "msyscon", + "rxvt", + "screen", + "tmux", + "xterm", + ]; + match ANSI_TERM_PREFIX.binary_search(&name) { + Ok(_) => true, + Err(0) => false, + Err(idx) => name.starts_with(ANSI_TERM_PREFIX[idx - 1]), + } +} + + +/// A parsed terminfo database entry. +#[derive(Debug, Clone)] +pub struct TermInfo { + /// Names for the terminal + pub names: Vec<String>, + /// Map of capability name to boolean value + pub bools: HashMap<&'static str, bool>, + /// Map of capability name to numeric value + pub numbers: HashMap<&'static str, u16>, + /// Map of capability name to raw (unexpanded) string + pub strings: HashMap<&'static str, Vec<u8>>, +} + +impl TermInfo { + /// Create a `TermInfo` based on current environment. + pub fn from_env() -> Result<TermInfo> { + let term_var = env::var("TERM").ok(); + let term_name = term_var + .as_ref() + .map(|s| &**s) + .or_else(|| env::var("MSYSCON") + .ok() + .and_then(|s| if s == "mintty.exe" { + Some("msyscon") + } else { + None + })); + if let Some(term_name) = term_name { + return TermInfo::from_name(term_name); + } else { + return Err(::Error::TermUnset); + } + } + + /// Create a `TermInfo` for the named terminal. + pub fn from_name(name: &str) -> Result<TermInfo> { + if let Some(path) = get_dbpath_for_term(name) { + match TermInfo::from_path(&path) { + Ok(term) => return Ok(term), + // Skip IO Errors (e.g., permission denied). + Err(::Error::Io(_)) => {}, + // Don't ignore malformed terminfo databases. + Err(e) => return Err(e), + } + } + // Basic ANSI fallback terminal. + if is_ansi(name) { + let mut strings = HashMap::new(); + strings.insert("sgr0", b"\x1B[0m".to_vec()); + strings.insert("bold", b"\x1B[1m".to_vec()); + strings.insert("setaf", b"\x1B[3%p1%dm".to_vec()); + strings.insert("setab", b"\x1B[4%p1%dm".to_vec()); + + let mut numbers = HashMap::new(); + numbers.insert("colors", 8u16); + + Ok(TermInfo { + names: vec![name.to_owned()], + bools: HashMap::new(), + numbers: numbers, + strings: strings, + }) + } else { + Err(::Error::TerminfoEntryNotFound) + } + } + + /// Parse the given `TermInfo`. + pub fn from_path<P: AsRef<Path>>(path: P) -> Result<TermInfo> { + Self::_from_path(path.as_ref()) + } + // Keep the metadata small + // (That is, this uses a &Path so that this function need not be instantiated + // for every type + // which implements AsRef<Path>. One day, if/when rustc is a bit smarter, it + // might do this for + // us. Alas. ) + fn _from_path(path: &Path) -> Result<TermInfo> { + let file = try!(File::open(path).map_err(::Error::Io)); + let mut reader = BufReader::new(file); + parse(&mut reader, false) + } + + /// Retrieve a capability `cmd` and expand it with `params`, writing result to `out`. + pub fn apply_cap(&self, cmd: &str, params: &[Param], out: &mut io::Write) -> Result<()> { + match self.strings.get(cmd) { + Some(cmd) => { + match expand(cmd, params, &mut Variables::new()) { + Ok(s) => { + try!(out.write_all(&s)); + Ok(()) + } + Err(e) => Err(e.into()), + } + } + None => Err(::Error::NotSupported), + } + } + + /// Write the reset string to `out`. + pub fn reset(&self, out: &mut io::Write) -> Result<()> { + // are there any terminals that have color/attrs and not sgr0? + // Try falling back to sgr, then op + let cmd = match [("sgr0", &[] as &[Param]), ("sgr", &[Param::Number(0)]), ("op", &[])] + .iter() + .filter_map(|&(cap, params)| { + self.strings.get(cap).map(|c| (c, params)) + }) + .next() { + Some((op, params)) => { + match expand(op, params, &mut Variables::new()) { + Ok(cmd) => cmd, + Err(e) => return Err(e.into()), + } + } + None => return Err(::Error::NotSupported), + }; + try!(out.write_all(&cmd)); + Ok(()) + } + +} + +#[derive(Debug, Eq, PartialEq)] +/// An error from parsing a terminfo entry +pub enum Error { + /// The "magic" number at the start of the file was wrong. + /// + /// It should be `0x11A` + BadMagic(u16), + /// The names in the file were not valid UTF-8. + /// + /// In theory these should only be ASCII, but to work with the Rust `str` type, we treat them + /// as UTF-8. This is valid, except when a terminfo file decides to be invalid. This hasn't + /// been encountered in the wild. + NotUtf8(::std::str::Utf8Error), + /// The names section of the file was empty + ShortNames, + /// More boolean parameters are present in the file than this crate knows how to interpret. + TooManyBools, + /// More number parameters are present in the file than this crate knows how to interpret. + TooManyNumbers, + /// More string parameters are present in the file than this crate knows how to interpret. + TooManyStrings, + /// The length of some field was not >= -1. + InvalidLength, + /// The names table was missing a trailing null terminator. + NamesMissingNull, + /// The strings table was missing a trailing null terminator. + StringsMissingNull, +} + +impl ::std::fmt::Display for Error { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + use std::error::Error; + match *self { + NotUtf8(e) => write!(f, "{}", e), + BadMagic(v) => write!(f, "bad magic number {:x} in terminfo header", v), + _ => f.write_str(self.description()), + } + } +} + +impl ::std::convert::From<::std::string::FromUtf8Error> for Error { + fn from(v: ::std::string::FromUtf8Error) -> Self { + NotUtf8(v.utf8_error()) + } +} + +impl ::std::error::Error for Error { + fn description(&self) -> &str { + match *self { + BadMagic(..) => "incorrect magic number at start of file", + ShortNames => "no names exposed, need at least one", + TooManyBools => "more boolean properties than libterm knows about", + TooManyNumbers => "more number properties than libterm knows about", + TooManyStrings => "more string properties than libterm knows about", + InvalidLength => "invalid length field value, must be >= -1", + NotUtf8(ref e) => e.description(), + NamesMissingNull => "names table missing NUL terminator", + StringsMissingNull => "string table missing NUL terminator", + } + } + + fn cause(&self) -> Option<&::std::error::Error> { + match *self { + NotUtf8(ref e) => Some(e), + _ => None, + } + } +} + +pub mod searcher; + +/// `TermInfo` format parsing. +pub mod parser { + //! ncurses-compatible compiled terminfo format parsing (term(5)) + pub mod compiled; + mod names; +} +pub mod parm; + + +fn cap_for_attr(attr: Attr) -> &'static str { + match attr { + Attr::Bold => "bold", + Attr::Dim => "dim", + Attr::Italic(true) => "sitm", + Attr::Italic(false) => "ritm", + Attr::Underline(true) => "smul", + Attr::Underline(false) => "rmul", + Attr::Blink => "blink", + Attr::Standout(true) => "smso", + Attr::Standout(false) => "rmso", + Attr::Reverse => "rev", + Attr::Secure => "invis", + Attr::ForegroundColor(_) => "setaf", + Attr::BackgroundColor(_) => "setab", + } +} + +/// A Terminal that knows how many colors it supports, with a reference to its +/// parsed Terminfo database record. +#[derive(Clone, Debug)] +pub struct TerminfoTerminal<T> { + num_colors: u16, + out: T, + ti: TermInfo, +} + +impl<T: Write> Terminal for TerminfoTerminal<T> { + type Output = T; + fn fg(&mut self, color: color::Color) -> Result<()> { + let color = self.dim_if_necessary(color); + if self.num_colors > color { + return self.ti.apply_cap("setaf", &[Param::Number(color as i32)], &mut self.out); + } + Err(::Error::ColorOutOfRange) + } + + fn bg(&mut self, color: color::Color) -> Result<()> { + let color = self.dim_if_necessary(color); + if self.num_colors > color { + return self.ti.apply_cap("setab", &[Param::Number(color as i32)], &mut self.out); + } + Err(::Error::ColorOutOfRange) + } + + fn attr(&mut self, attr: Attr) -> Result<()> { + match attr { + Attr::ForegroundColor(c) => self.fg(c), + Attr::BackgroundColor(c) => self.bg(c), + _ => self.ti.apply_cap(cap_for_attr(attr), &[], &mut self.out), + } + } + + fn supports_attr(&self, attr: Attr) -> bool { + match attr { + Attr::ForegroundColor(_) | Attr::BackgroundColor(_) => self.num_colors > 0, + _ => { + let cap = cap_for_attr(attr); + self.ti.strings.get(cap).is_some() + } + } + } + + fn reset(&mut self) -> Result<()> { + self.ti.reset(&mut self.out) + } + + fn supports_reset(&self) -> bool { + ["sgr0", "sgr", "op"].iter().any(|&cap| self.ti.strings.get(cap).is_some()) + } + + fn supports_color(&self) -> bool { + self.num_colors > 0 && self.supports_reset() + } + + fn cursor_up(&mut self) -> Result<()> { + self.ti.apply_cap("cuu1", &[], &mut self.out) + } + + fn delete_line(&mut self) -> Result<()> { + self.ti.apply_cap("el", &[], &mut self.out) + } + + fn carriage_return(&mut self) -> Result<()> { + self.ti.apply_cap("cr", &[], &mut self.out) + } + + fn get_ref(&self) -> &T { + &self.out + } + + fn get_mut(&mut self) -> &mut T { + &mut self.out + } + + fn into_inner(self) -> T + where Self: Sized + { + self.out + } +} + +impl<T: Write> TerminfoTerminal<T> { + /// Create a new TerminfoTerminal with the given TermInfo and Write. + pub fn new_with_terminfo(out: T, terminfo: TermInfo) -> TerminfoTerminal<T> { + let nc = if terminfo.strings.contains_key("setaf") && + terminfo.strings.contains_key("setab") { + terminfo.numbers.get("colors").map_or(0, |&n| n) + } else { + 0 + }; + + TerminfoTerminal { + out: out, + ti: terminfo, + num_colors: nc, + } + } + + /// Create a new TerminfoTerminal for the current environment with the given Write. + /// + /// Returns `None` when the terminfo cannot be found or parsed. + pub fn new(out: T) -> Option<TerminfoTerminal<T>> { + TermInfo::from_env().map(move |ti| TerminfoTerminal::new_with_terminfo(out, ti)).ok() + } + + fn dim_if_necessary(&self, color: color::Color) -> color::Color { + if color >= self.num_colors && color >= 8 && color < 16 { + color - 8 + } else { + color + } + } +} + + +impl<T: Write> Write for TerminfoTerminal<T> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.out.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.out.flush() + } +} diff --git a/bash-5.1/vendor/term/src/terminfo/parm.rs b/bash-5.1/vendor/term/src/terminfo/parm.rs new file mode 100644 index 0000000..5c9d240 --- /dev/null +++ b/bash-5.1/vendor/term/src/terminfo/parm.rs @@ -0,0 +1,698 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Parameterized string expansion + +use self::Param::*; +use self::States::*; + +use std::iter::repeat; + +#[derive(Clone, Copy, PartialEq)] +enum States { + Nothing, + Percent, + SetVar, + GetVar, + PushParam, + CharConstant, + CharClose, + IntConstant(i32), + FormatPattern(Flags, FormatState), + SeekIfElse(usize), + SeekIfElsePercent(usize), + SeekIfEnd(usize), + SeekIfEndPercent(usize), +} + +#[derive(Copy, PartialEq, Clone)] +enum FormatState { + Flags, + Width, + Precision, +} + +/// Types of parameters a capability can use +#[allow(missing_docs)] +#[derive(Clone)] +pub enum Param { + Number(i32), + Words(String), +} + +impl Default for Param { + fn default() -> Self { + Param::Number(0) + } +} + +/// An error from interpreting a parameterized string. +#[derive(Debug, Eq, PartialEq)] +pub enum Error { + /// Data was requested from the stack, but the stack didn't have enough elements. + StackUnderflow, + /// The type of the element(s) on top of the stack did not match the type that the operator + /// wanted. + TypeMismatch, + /// An unrecognized format option was used. + UnrecognizedFormatOption(char), + /// An invalid variable name was used. + InvalidVariableName(char), + /// An invalid parameter index was used. + InvalidParameterIndex(char), + /// A malformed character constant was used. + MalformedCharacterConstant, + /// An integer constant was too large (overflowed an i32) + IntegerConstantOverflow, + /// A malformed integer constant was used. + MalformedIntegerConstant, + /// A format width constant was too large (overflowed a usize) + FormatWidthOverflow, + /// A format precision constant was too large (overflowed a usize) + FormatPrecisionOverflow, +} + +impl ::std::fmt::Display for Error { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + use std::error::Error; + f.write_str(self.description()) + } +} + +impl ::std::error::Error for Error { + fn description(&self) -> &str { + use self::Error::*; + match *self { + StackUnderflow => "not enough elements on the stack", + TypeMismatch => "type mismatch", + UnrecognizedFormatOption(_) => "unrecognized format option", + InvalidVariableName(_) => "invalid variable name", + InvalidParameterIndex(_) => "invalid parameter index", + MalformedCharacterConstant => "malformed character constant", + IntegerConstantOverflow => "integer constant computation overflowed", + MalformedIntegerConstant => "malformed integer constant", + FormatWidthOverflow => "format width constant computation overflowed", + FormatPrecisionOverflow => "format precision constant computation overflowed", + } + } + + fn cause(&self) -> Option<&::std::error::Error> { + None + } +} + +/// Container for static and dynamic variable arrays +#[derive(Default)] +pub struct Variables { + /// Static variables A-Z + sta: [Param; 26], + /// Dynamic variables a-z + dyn: [Param; 26], +} + +impl Variables { + /// Return a new zero-initialized Variables + pub fn new() -> Variables { + Default::default() + } +} + +/// Expand a parameterized capability +/// +/// # Arguments +/// * `cap` - string to expand +/// * `params` - vector of params for %p1 etc +/// * `vars` - Variables struct for %Pa etc +/// +/// To be compatible with ncurses, `vars` should be the same between calls to `expand` for +/// multiple capabilities for the same terminal. +pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result<Vec<u8>, Error> { + let mut state = Nothing; + + // expanded cap will only rarely be larger than the cap itself + let mut output = Vec::with_capacity(cap.len()); + + let mut stack: Vec<Param> = Vec::new(); + + // Copy parameters into a local vector for mutability + let mut mparams = [Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), + Number(0), Number(0), Number(0)]; + for (dst, src) in mparams.iter_mut().zip(params.iter()) { + *dst = (*src).clone(); + } + + for &c in cap.iter() { + let cur = c as char; + let mut old_state = state; + match state { + Nothing => { + if cur == '%' { + state = Percent; + } else { + output.push(c); + } + } + Percent => { + match cur { + '%' => { + output.push(c); + state = Nothing + } + 'c' => { + match stack.pop() { + // if c is 0, use 0200 (128) for ncurses compatibility + Some(Number(0)) => output.push(128u8), + // Don't check bounds. ncurses just casts and truncates. + Some(Number(c)) => output.push(c as u8), + Some(_) => return Err(Error::TypeMismatch), + None => return Err(Error::StackUnderflow), + } + } + 'p' => state = PushParam, + 'P' => state = SetVar, + 'g' => state = GetVar, + '\'' => state = CharConstant, + '{' => state = IntConstant(0), + 'l' => { + match stack.pop() { + Some(Words(s)) => stack.push(Number(s.len() as i32)), + Some(_) => return Err(Error::TypeMismatch), + None => return Err(Error::StackUnderflow), + } + } + '+' | '-' | '/' | '*' | '^' | '&' | '|' | 'm' => { + match (stack.pop(), stack.pop()) { + (Some(Number(y)), Some(Number(x))) => { + stack.push(Number(match cur { + '+' => x + y, + '-' => x - y, + '*' => x * y, + '/' => x / y, + '|' => x | y, + '&' => x & y, + '^' => x ^ y, + 'm' => x % y, + _ => unreachable!("logic error"), + })) + } + (Some(_), Some(_)) => return Err(Error::TypeMismatch), + _ => return Err(Error::StackUnderflow), + } + } + '=' | '>' | '<' | 'A' | 'O' => { + match (stack.pop(), stack.pop()) { + (Some(Number(y)), Some(Number(x))) => { + stack.push(Number(if match cur { + '=' => x == y, + '<' => x < y, + '>' => x > y, + 'A' => x > 0 && y > 0, + 'O' => x > 0 || y > 0, + _ => unreachable!("logic error"), + } { + 1 + } else { + 0 + })) + } + (Some(_), Some(_)) => return Err(Error::TypeMismatch), + _ => return Err(Error::StackUnderflow), + } + } + '!' | '~' => { + match stack.pop() { + Some(Number(x)) => { + stack.push(Number(match cur { + '!' if x > 0 => 0, + '!' => 1, + '~' => !x, + _ => unreachable!("logic error"), + })) + } + Some(_) => return Err(Error::TypeMismatch), + None => return Err(Error::StackUnderflow), + } + } + 'i' => { + match (&mparams[0], &mparams[1]) { + (&Number(x), &Number(y)) => { + mparams[0] = Number(x + 1); + mparams[1] = Number(y + 1); + } + (_, _) => return Err(Error::TypeMismatch), + } + } + + // printf-style support for %doxXs + 'd' | 'o' | 'x' | 'X' | 's' => { + if let Some(arg) = stack.pop() { + let flags = Flags::default(); + let res = try!(format(arg, FormatOp::from_char(cur), flags)); + output.extend(res); + } else { + return Err(Error::StackUnderflow); + } + } + ':' | '#' | ' ' | '.' | '0'...'9' => { + let mut flags = Flags::default(); + let mut fstate = FormatState::Flags; + match cur { + ':' => (), + '#' => flags.alternate = true, + ' ' => flags.space = true, + '.' => fstate = FormatState::Precision, + '0'...'9' => { + flags.width = cur as usize - '0' as usize; + fstate = FormatState::Width; + } + _ => unreachable!("logic error"), + } + state = FormatPattern(flags, fstate); + } + + // conditionals + '?'|';' => (), + 't' => { + match stack.pop() { + Some(Number(0)) => state = SeekIfElse(0), + Some(Number(_)) => (), + Some(_) => return Err(Error::TypeMismatch), + None => return Err(Error::StackUnderflow), + } + } + 'e' => state = SeekIfEnd(0), + c => return Err(Error::UnrecognizedFormatOption(c)), + } + } + PushParam => { + // params are 1-indexed + stack.push(mparams[match cur.to_digit(10) { + Some(d) => d as usize - 1, + None => return Err(Error::InvalidParameterIndex(cur)), + }] + .clone()); + } + SetVar => { + if cur >= 'A' && cur <= 'Z' { + if let Some(arg) = stack.pop() { + let idx = (cur as u8) - b'A'; + vars.sta[idx as usize] = arg; + } else { + return Err(Error::StackUnderflow); + } + } else if cur >= 'a' && cur <= 'z' { + if let Some(arg) = stack.pop() { + let idx = (cur as u8) - b'a'; + vars.dyn[idx as usize] = arg; + } else { + return Err(Error::StackUnderflow); + } + } else { + return Err(Error::InvalidVariableName(cur)); + } + } + GetVar => { + if cur >= 'A' && cur <= 'Z' { + let idx = (cur as u8) - b'A'; + stack.push(vars.sta[idx as usize].clone()); + } else if cur >= 'a' && cur <= 'z' { + let idx = (cur as u8) - b'a'; + stack.push(vars.dyn[idx as usize].clone()); + } else { + return Err(Error::InvalidVariableName(cur)); + } + } + CharConstant => { + stack.push(Number(c as i32)); + state = CharClose; + } + CharClose => { + if cur != '\'' { + return Err(Error::MalformedCharacterConstant); + } + } + IntConstant(i) => { + if cur == '}' { + stack.push(Number(i)); + state = Nothing; + } else if let Some(digit) = cur.to_digit(10) { + match i.checked_mul(10).and_then(|i_ten| i_ten.checked_add(digit as i32)) { + Some(i) => { + state = IntConstant(i); + old_state = Nothing; + } + None => return Err(Error::IntegerConstantOverflow), + } + } else { + return Err(Error::MalformedIntegerConstant); + } + } + FormatPattern(ref mut flags, ref mut fstate) => { + old_state = Nothing; + match (*fstate, cur) { + (_, 'd') | (_, 'o') | (_, 'x') | (_, 'X') | (_, 's') => { + if let Some(arg) = stack.pop() { + let res = try!(format(arg, FormatOp::from_char(cur), *flags)); + output.extend(res); + // will cause state to go to Nothing + old_state = FormatPattern(*flags, *fstate); + } else { + return Err(Error::StackUnderflow); + } + } + (FormatState::Flags, '#') => { + flags.alternate = true; + } + (FormatState::Flags, '-') => { + flags.left = true; + } + (FormatState::Flags, '+') => { + flags.sign = true; + } + (FormatState::Flags, ' ') => { + flags.space = true; + } + (FormatState::Flags, '0'...'9') => { + flags.width = cur as usize - '0' as usize; + *fstate = FormatState::Width; + } + (FormatState::Width, '0'...'9') => { + flags.width = match flags.width.checked_mul(10).and_then(|w| { + w.checked_add(cur as usize - '0' as usize) + }) { + Some(width) => width, + None => return Err(Error::FormatWidthOverflow), + } + } + (FormatState::Width, '.')|(FormatState::Flags, '.') => { + *fstate = FormatState::Precision; + } + (FormatState::Precision, '0'...'9') => { + flags.precision = match flags.precision.checked_mul(10).and_then(|w| { + w.checked_add(cur as usize - '0' as usize) + }) { + Some(precision) => precision, + None => return Err(Error::FormatPrecisionOverflow), + } + } + _ => return Err(Error::UnrecognizedFormatOption(cur)), + } + } + SeekIfElse(level) => { + if cur == '%' { + state = SeekIfElsePercent(level); + } + old_state = Nothing; + } + SeekIfElsePercent(level) => { + if cur == ';' { + if level == 0 { + state = Nothing; + } else { + state = SeekIfElse(level - 1); + } + } else if cur == 'e' && level == 0 { + state = Nothing; + } else if cur == '?' { + state = SeekIfElse(level + 1); + } else { + state = SeekIfElse(level); + } + } + SeekIfEnd(level) => { + if cur == '%' { + state = SeekIfEndPercent(level); + } + old_state = Nothing; + } + SeekIfEndPercent(level) => { + if cur == ';' { + if level == 0 { + state = Nothing; + } else { + state = SeekIfEnd(level - 1); + } + } else if cur == '?' { + state = SeekIfEnd(level + 1); + } else { + state = SeekIfEnd(level); + } + } + } + if state == old_state { + state = Nothing; + } + } + Ok(output) +} + +#[derive(Copy, PartialEq, Clone, Default)] +struct Flags { + width: usize, + precision: usize, + alternate: bool, + left: bool, + sign: bool, + space: bool, +} + +#[derive(Copy, Clone)] +enum FormatOp { + Digit, + Octal, + Hex, + HEX, + String, +} + +impl FormatOp { + fn from_char(c: char) -> FormatOp { + use self::FormatOp::*; + match c { + 'd' => Digit, + 'o' => Octal, + 'x' => Hex, + 'X' => HEX, + 's' => String, + _ => panic!("bad FormatOp char"), + } + } +} + +fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8>, Error> { + use self::FormatOp::*; + let mut s = match val { + Number(d) => { + match op { + Digit => { + if flags.sign { + format!("{:+01$}", d, flags.precision) + } else if d < 0 { + // C doesn't take sign into account in precision calculation. + format!("{:01$}", d, flags.precision + 1) + } else if flags.space { + format!(" {:01$}", d, flags.precision) + } else { + format!("{:01$}", d, flags.precision) + } + } + Octal => { + if flags.alternate { + // Leading octal zero counts against precision. + format!("0{:01$o}", d, flags.precision.saturating_sub(1)) + } else { + format!("{:01$o}", d, flags.precision) + } + } + Hex => { + if flags.alternate && d != 0 { + format!("0x{:01$x}", d, flags.precision) + } else { + format!("{:01$x}", d, flags.precision) + } + } + HEX => { + if flags.alternate && d != 0 { + format!("0X{:01$X}", d, flags.precision) + } else { + format!("{:01$X}", d, flags.precision) + } + } + String => return Err(Error::TypeMismatch), + } + .into_bytes() + } + Words(s) => { + match op { + String => { + let mut s = s.into_bytes(); + if flags.precision > 0 && flags.precision < s.len() { + s.truncate(flags.precision); + } + s + } + _ => return Err(Error::TypeMismatch), + } + } + }; + if flags.width > s.len() { + let n = flags.width - s.len(); + if flags.left { + s.extend(repeat(b' ').take(n)); + } else { + let mut s_ = Vec::with_capacity(flags.width); + s_.extend(repeat(b' ').take(n)); + s_.extend(s.into_iter()); + s = s_; + } + } + Ok(s) +} + +#[cfg(test)] +mod test { + use super::{expand, Variables}; + use super::Param::{self, Words, Number}; + use std::result::Result::Ok; + + #[test] + fn test_basic_setabf() { + let s = b"\\E[48;5;%p1%dm"; + assert_eq!(expand(s, &[Number(1)], &mut Variables::new()).unwrap(), + "\\E[48;5;1m".bytes().collect::<Vec<_>>()); + } + + #[test] + fn test_multiple_int_constants() { + assert_eq!(expand(b"%{1}%{2}%d%d", &[], &mut Variables::new()).unwrap(), + "21".bytes().collect::<Vec<_>>()); + } + + #[test] + fn test_op_i() { + let mut vars = Variables::new(); + assert_eq!(expand(b"%p1%d%p2%d%p3%d%i%p1%d%p2%d%p3%d", + &[Number(1), Number(2), Number(3)], + &mut vars), + Ok("123233".bytes().collect::<Vec<_>>())); + assert_eq!(expand(b"%p1%d%p2%d%i%p1%d%p2%d", &[], &mut vars), + Ok("0011".bytes().collect::<Vec<_>>())); + } + + #[test] + fn test_param_stack_failure_conditions() { + let mut varstruct = Variables::new(); + let vars = &mut varstruct; + fn get_res(fmt: &str, + cap: &str, + params: &[Param], + vars: &mut Variables) + -> Result<Vec<u8>, super::Error> { + let mut u8v: Vec<_> = fmt.bytes().collect(); + u8v.extend(cap.as_bytes().iter().cloned()); + expand(&u8v, params, vars) + } + + let caps = ["%d", "%c", "%s", "%Pa", "%l", "%!", "%~"]; + for &cap in &caps { + let res = get_res("", cap, &[], vars); + assert!(res.is_err(), + "Op {} succeeded incorrectly with 0 stack entries", + cap); + let p = if cap == "%s" || cap == "%l" { + Words("foo".to_owned()) + } else { + Number(97) + }; + let res = get_res("%p1", cap, &[p], vars); + assert!(res.is_ok(), + "Op {} failed with 1 stack entry: {}", + cap, + res.err().unwrap()); + } + let caps = ["%+", "%-", "%*", "%/", "%m", "%&", "%|", "%A", "%O"]; + for &cap in &caps { + let res = expand(cap.as_bytes(), &[], vars); + assert!(res.is_err(), + "Binop {} succeeded incorrectly with 0 stack entries", + cap); + let res = get_res("%{1}", cap, &[], vars); + assert!(res.is_err(), + "Binop {} succeeded incorrectly with 1 stack entry", + cap); + let res = get_res("%{1}%{2}", cap, &[], vars); + assert!(res.is_ok(), + "Binop {} failed with 2 stack entries: {}", + cap, + res.err().unwrap()); + } + } + + #[test] + fn test_push_bad_param() { + assert!(expand(b"%pa", &[], &mut Variables::new()).is_err()); + } + + #[test] + fn test_comparison_ops() { + let v = [('<', [1u8, 0u8, 0u8]), ('=', [0u8, 1u8, 0u8]), ('>', [0u8, 0u8, 1u8])]; + for &(op, bs) in &v { + let s = format!("%{{1}}%{{2}}%{}%d", op); + let res = expand(s.as_bytes(), &[], &mut Variables::new()); + assert!(res.is_ok(), res.err().unwrap()); + assert_eq!(res.unwrap(), vec![b'0' + bs[0]]); + let s = format!("%{{1}}%{{1}}%{}%d", op); + let res = expand(s.as_bytes(), &[], &mut Variables::new()); + assert!(res.is_ok(), res.err().unwrap()); + assert_eq!(res.unwrap(), vec![b'0' + bs[1]]); + let s = format!("%{{2}}%{{1}}%{}%d", op); + let res = expand(s.as_bytes(), &[], &mut Variables::new()); + assert!(res.is_ok(), res.err().unwrap()); + assert_eq!(res.unwrap(), vec![b'0' + bs[2]]); + } + } + + #[test] + fn test_conditionals() { + let mut vars = Variables::new(); + let s = b"\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m"; + let res = expand(s, &[Number(1)], &mut vars); + assert!(res.is_ok(), res.err().unwrap()); + assert_eq!(res.unwrap(), "\\E[31m".bytes().collect::<Vec<_>>()); + let res = expand(s, &[Number(8)], &mut vars); + assert!(res.is_ok(), res.err().unwrap()); + assert_eq!(res.unwrap(), "\\E[90m".bytes().collect::<Vec<_>>()); + let res = expand(s, &[Number(42)], &mut vars); + assert!(res.is_ok(), res.err().unwrap()); + assert_eq!(res.unwrap(), "\\E[38;5;42m".bytes().collect::<Vec<_>>()); + } + + #[test] + fn test_format() { + let mut varstruct = Variables::new(); + let vars = &mut varstruct; + assert_eq!(expand(b"%p1%s%p2%2s%p3%2s%p4%.2s", + &[Words("foo".to_owned()), + Words("foo".to_owned()), + Words("f".to_owned()), + Words("foo".to_owned())], + vars), + Ok("foofoo ffo".bytes().collect::<Vec<_>>())); + assert_eq!(expand(b"%p1%:-4.2s", &[Words("foo".to_owned())], vars), + Ok("fo ".bytes().collect::<Vec<_>>())); + + assert_eq!(expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", &[Number(1)], vars), + Ok("1001 1+1".bytes().collect::<Vec<_>>())); + assert_eq!(expand(b"%p1%o%p1%#o%p2%6.4x%p2%#6.4X", + &[Number(15), Number(27)], + vars), + Ok("17017 001b0X001B".bytes().collect::<Vec<_>>())); + } +} diff --git a/bash-5.1/vendor/term/src/terminfo/parser/compiled.rs b/bash-5.1/vendor/term/src/terminfo/parser/compiled.rs new file mode 100644 index 0000000..24ddd00 --- /dev/null +++ b/bash-5.1/vendor/term/src/terminfo/parser/compiled.rs @@ -0,0 +1,199 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! ncurses-compatible compiled terminfo format parsing (term(5)) + +use std::collections::HashMap; +use std::io::prelude::*; +use std::io; + +use terminfo::Error::*; +use terminfo::TermInfo; +use Result; + +pub use terminfo::parser::names::*; + +// These are the orders ncurses uses in its compiled format (as of 5.9). Not +// sure if portable. + +fn read_le_u16(r: &mut io::Read) -> io::Result<u16> { + let mut b = [0; 2]; + let mut amt = 0; + while amt < b.len() { + match try!(r.read(&mut b[amt..])) { + 0 => return Err(io::Error::new(io::ErrorKind::Other, "end of file")), + n => amt += n, + } + } + Ok((b[0] as u16) | ((b[1] as u16) << 8)) +} + +fn read_byte(r: &mut io::Read) -> io::Result<u8> { + match r.bytes().next() { + Some(s) => s, + None => Err(io::Error::new(io::ErrorKind::Other, "end of file")), + } +} + +/// Parse a compiled terminfo entry, using long capability names if `longnames` +/// is true +pub fn parse(file: &mut io::Read, longnames: bool) -> Result<TermInfo> { + let (bnames, snames, nnames) = if longnames { + (boolfnames, stringfnames, numfnames) + } else { + (boolnames, stringnames, numnames) + }; + + // Check magic number + let magic = try!(read_le_u16(file)); + if magic != 0x011A { + return Err(BadMagic(magic).into()); + } + + // According to the spec, these fields must be >= -1 where -1 means that the + // feature is not + // supported. Using 0 instead of -1 works because we skip sections with length + // 0. + macro_rules! read_nonneg { + () => {{ + match try!(read_le_u16(file)) as i16 { + n if n >= 0 => n as usize, + -1 => 0, + _ => return Err(InvalidLength.into()), + } + }} + } + + let names_bytes = read_nonneg!(); + let bools_bytes = read_nonneg!(); + let numbers_count = read_nonneg!(); + let string_offsets_count = read_nonneg!(); + let string_table_bytes = read_nonneg!(); + + if names_bytes == 0 { + return Err(ShortNames.into()); + } + + if bools_bytes > boolnames.len() { + return Err(TooManyBools.into()); + } + + if numbers_count > numnames.len() { + return Err(TooManyNumbers.into()); + } + + if string_offsets_count > stringnames.len() { + return Err(TooManyStrings.into()); + } + + // don't read NUL + let mut bytes = Vec::new(); + try!(file.take((names_bytes - 1) as u64).read_to_end(&mut bytes)); + let names_str = match String::from_utf8(bytes) { + Ok(s) => s, + Err(e) => return Err(NotUtf8(e.utf8_error()).into()), + }; + + let term_names: Vec<String> = names_str.split('|') + .map(|s| s.to_owned()) + .collect(); + // consume NUL + if try!(read_byte(file)) != b'\0' { + return Err(NamesMissingNull.into()); + } + + let bools_map: HashMap<&str, bool> = try! { + (0..bools_bytes).filter_map(|i| match read_byte(file) { + Err(e) => Some(Err(e)), + Ok(1) => Some(Ok((bnames[i], true))), + Ok(_) => None + }).collect() + }; + + if (bools_bytes + names_bytes) % 2 == 1 { + try!(read_byte(file)); // compensate for padding + } + + let numbers_map: HashMap<&str, u16> = try! { + (0..numbers_count).filter_map(|i| match read_le_u16(file) { + Ok(0xFFFF) => None, + Ok(n) => Some(Ok((nnames[i], n))), + Err(e) => Some(Err(e)) + }).collect() + }; + + let string_map: HashMap<&str, Vec<u8>> = if string_offsets_count > 0 { + let string_offsets: Vec<u16> = try!((0..string_offsets_count) + .map(|_| read_le_u16(file)) + .collect()); + + let mut string_table = Vec::new(); + try!(file.take(string_table_bytes as u64).read_to_end(&mut string_table)); + + try!(string_offsets.into_iter() + .enumerate() + .filter(|&(_, offset)| { + // non-entry + offset != 0xFFFF + }) + .map(|(i, offset)| { + let offset = offset as usize; + + let name = if snames[i] == "_" { + stringfnames[i] + } else { + snames[i] + }; + + if offset == 0xFFFE { + // undocumented: FFFE indicates cap@, which means the capability + // is not present + // unsure if the handling for this is correct + return Ok((name, Vec::new())); + } + + // Find the offset of the NUL we want to go to + let nulpos = string_table[offset..string_table_bytes] + .iter() + .position(|&b| b == 0); + match nulpos { + Some(len) => { + Ok((name, + string_table[offset..offset + len].to_vec())) + } + None => return Err(::Error::TerminfoParsing(StringsMissingNull)), + } + }) + .collect()) + } else { + HashMap::new() + }; + + // And that's all there is to it + Ok(TermInfo { + names: term_names, + bools: bools_map, + numbers: numbers_map, + strings: string_map, + }) +} + +#[cfg(test)] +mod test { + + use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames}; + + #[test] + fn test_veclens() { + assert_eq!(boolfnames.len(), boolnames.len()); + assert_eq!(numfnames.len(), numnames.len()); + assert_eq!(stringfnames.len(), stringnames.len()); + } +} diff --git a/bash-5.1/vendor/term/src/terminfo/parser/names.rs b/bash-5.1/vendor/term/src/terminfo/parser/names.rs new file mode 100644 index 0000000..41ff6c6 --- /dev/null +++ b/bash-5.1/vendor/term/src/terminfo/parser/names.rs @@ -0,0 +1,553 @@ +#![allow(non_upper_case_globals, missing_docs)] +#![cfg_attr(rustfmt, rustfmt_skip)] + +pub static boolfnames: &'static [&'static str] = &["auto_left_margin", + "auto_right_margin", + "no_esc_ctlc", + "ceol_standout_glitch", + "eat_newline_glitch", + "erase_overstrike", + "generic_type", + "hard_copy", + "has_meta_key", + "has_status_line", + "insert_null_glitch", + "memory_above", + "memory_below", + "move_insert_mode", + "move_standout_mode", + "over_strike", + "status_line_esc_ok", + "dest_tabs_magic_smso", + "tilde_glitch", + "transparent_underline", + "xon_xoff", + "needs_xon_xoff", + "prtr_silent", + "hard_cursor", + "non_rev_rmcup", + "no_pad_char", + "non_dest_scroll_region", + "can_change", + "back_color_erase", + "hue_lightness_saturation", + "col_addr_glitch", + "cr_cancels_micro_mode", + "has_print_wheel", + "row_addr_glitch", + "semi_auto_right_margin", + "cpi_changes_res", + "lpi_changes_res", + "backspaces_with_bs", + "crt_no_scrolling", + "no_correctly_working_cr", + "gnu_has_meta_key", + "linefeed_is_newline", + "has_hardware_tabs", + "return_does_clr_eol"]; + +pub static boolnames: &'static [&'static str] = + &["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", + "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", + "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", + "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; + +pub static numfnames: &'static [&'static str] = &["columns", + "init_tabs", + "lines", + "lines_of_memory", + "magic_cookie_glitch", + "padding_baud_rate", + "virtual_terminal", + "width_status_line", + "num_labels", + "label_height", + "label_width", + "max_attributes", + "maximum_windows", + "max_colors", + "max_pairs", + "no_color_video", + "buffer_capacity", + "dot_vert_spacing", + "dot_horz_spacing", + "max_micro_address", + "max_micro_jump", + "micro_col_size", + "micro_line_size", + "number_of_pins", + "output_res_char", + "output_res_line", + "output_res_horz_inch", + "output_res_vert_inch", + "print_rate", + "wide_char_size", + "buttons", + "bit_image_entwining", + "bit_image_type", + "magic_cookie_glitch_ul", + "carriage_return_delay", + "new_line_delay", + "backspace_delay", + "horizontal_tab_delay", + "number_of_function_keys"]; + +pub static numnames: &'static [&'static str] = + &["cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", + "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", + "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", + "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; + +pub static stringfnames: &'static [&'static str] = &["back_tab", + "bell", + "carriage_return", + "change_scroll_region", + "clear_all_tabs", + "clear_screen", + "clr_eol", + "clr_eos", + "column_address", + "command_character", + "cursor_address", + "cursor_down", + "cursor_home", + "cursor_invisible", + "cursor_left", + "cursor_mem_address", + "cursor_normal", + "cursor_right", + "cursor_to_ll", + "cursor_up", + "cursor_visible", + "delete_character", + "delete_line", + "dis_status_line", + "down_half_line", + "enter_alt_charset_mode", + "enter_blink_mode", + "enter_bold_mode", + "enter_ca_mode", + "enter_delete_mode", + "enter_dim_mode", + "enter_insert_mode", + "enter_secure_mode", + "enter_protected_mode", + "enter_reverse_mode", + "enter_standout_mode", + "enter_underline_mode", + "erase_chars", + "exit_alt_charset_mode", + "exit_attribute_mode", + "exit_ca_mode", + "exit_delete_mode", + "exit_insert_mode", + "exit_standout_mode", + "exit_underline_mode", + "flash_screen", + "form_feed", + "from_status_line", + "init_1string", + "init_2string", + "init_3string", + "init_file", + "insert_character", + "insert_line", + "insert_padding", + "key_backspace", + "key_catab", + "key_clear", + "key_ctab", + "key_dc", + "key_dl", + "key_down", + "key_eic", + "key_eol", + "key_eos", + "key_f0", + "key_f1", + "key_f10", + "key_f2", + "key_f3", + "key_f4", + "key_f5", + "key_f6", + "key_f7", + "key_f8", + "key_f9", + "key_home", + "key_ic", + "key_il", + "key_left", + "key_ll", + "key_npage", + "key_ppage", + "key_right", + "key_sf", + "key_sr", + "key_stab", + "key_up", + "keypad_local", + "keypad_xmit", + "lab_f0", + "lab_f1", + "lab_f10", + "lab_f2", + "lab_f3", + "lab_f4", + "lab_f5", + "lab_f6", + "lab_f7", + "lab_f8", + "lab_f9", + "meta_off", + "meta_on", + "newline", + "pad_char", + "parm_dch", + "parm_delete_line", + "parm_down_cursor", + "parm_ich", + "parm_index", + "parm_insert_line", + "parm_left_cursor", + "parm_right_cursor", + "parm_rindex", + "parm_up_cursor", + "pkey_key", + "pkey_local", + "pkey_xmit", + "print_screen", + "prtr_off", + "prtr_on", + "repeat_char", + "reset_1string", + "reset_2string", + "reset_3string", + "reset_file", + "restore_cursor", + "row_address", + "save_cursor", + "scroll_forward", + "scroll_reverse", + "set_attributes", + "set_tab", + "set_window", + "tab", + "to_status_line", + "underline_char", + "up_half_line", + "init_prog", + "key_a1", + "key_a3", + "key_b2", + "key_c1", + "key_c3", + "prtr_non", + "char_padding", + "acs_chars", + "plab_norm", + "key_btab", + "enter_xon_mode", + "exit_xon_mode", + "enter_am_mode", + "exit_am_mode", + "xon_character", + "xoff_character", + "ena_acs", + "label_on", + "label_off", + "key_beg", + "key_cancel", + "key_close", + "key_command", + "key_copy", + "key_create", + "key_end", + "key_enter", + "key_exit", + "key_find", + "key_help", + "key_mark", + "key_message", + "key_move", + "key_next", + "key_open", + "key_options", + "key_previous", + "key_print", + "key_redo", + "key_reference", + "key_refresh", + "key_replace", + "key_restart", + "key_resume", + "key_save", + "key_suspend", + "key_undo", + "key_sbeg", + "key_scancel", + "key_scommand", + "key_scopy", + "key_screate", + "key_sdc", + "key_sdl", + "key_select", + "key_send", + "key_seol", + "key_sexit", + "key_sfind", + "key_shelp", + "key_shome", + "key_sic", + "key_sleft", + "key_smessage", + "key_smove", + "key_snext", + "key_soptions", + "key_sprevious", + "key_sprint", + "key_sredo", + "key_sreplace", + "key_sright", + "key_srsume", + "key_ssave", + "key_ssuspend", + "key_sundo", + "req_for_input", + "key_f11", + "key_f12", + "key_f13", + "key_f14", + "key_f15", + "key_f16", + "key_f17", + "key_f18", + "key_f19", + "key_f20", + "key_f21", + "key_f22", + "key_f23", + "key_f24", + "key_f25", + "key_f26", + "key_f27", + "key_f28", + "key_f29", + "key_f30", + "key_f31", + "key_f32", + "key_f33", + "key_f34", + "key_f35", + "key_f36", + "key_f37", + "key_f38", + "key_f39", + "key_f40", + "key_f41", + "key_f42", + "key_f43", + "key_f44", + "key_f45", + "key_f46", + "key_f47", + "key_f48", + "key_f49", + "key_f50", + "key_f51", + "key_f52", + "key_f53", + "key_f54", + "key_f55", + "key_f56", + "key_f57", + "key_f58", + "key_f59", + "key_f60", + "key_f61", + "key_f62", + "key_f63", + "clr_bol", + "clear_margins", + "set_left_margin", + "set_right_margin", + "label_format", + "set_clock", + "display_clock", + "remove_clock", + "create_window", + "goto_window", + "hangup", + "dial_phone", + "quick_dial", + "tone", + "pulse", + "flash_hook", + "fixed_pause", + "wait_tone", + "user0", + "user1", + "user2", + "user3", + "user4", + "user5", + "user6", + "user7", + "user8", + "user9", + "orig_pair", + "orig_colors", + "initialize_color", + "initialize_pair", + "set_color_pair", + "set_foreground", + "set_background", + "change_char_pitch", + "change_line_pitch", + "change_res_horz", + "change_res_vert", + "define_char", + "enter_doublewide_mode", + "enter_draft_quality", + "enter_italics_mode", + "enter_leftward_mode", + "enter_micro_mode", + "enter_near_letter_quality", + "enter_normal_quality", + "enter_shadow_mode", + "enter_subscript_mode", + "enter_superscript_mode", + "enter_upward_mode", + "exit_doublewide_mode", + "exit_italics_mode", + "exit_leftward_mode", + "exit_micro_mode", + "exit_shadow_mode", + "exit_subscript_mode", + "exit_superscript_mode", + "exit_upward_mode", + "micro_column_address", + "micro_down", + "micro_left", + "micro_right", + "micro_row_address", + "micro_up", + "order_of_pins", + "parm_down_micro", + "parm_left_micro", + "parm_right_micro", + "parm_up_micro", + "select_char_set", + "set_bottom_margin", + "set_bottom_margin_parm", + "set_left_margin_parm", + "set_right_margin_parm", + "set_top_margin", + "set_top_margin_parm", + "start_bit_image", + "start_char_set_def", + "stop_bit_image", + "stop_char_set_def", + "subscript_characters", + "superscript_characters", + "these_cause_cr", + "zero_motion", + "char_set_names", + "key_mouse", + "mouse_info", + "req_mouse_pos", + "get_mouse", + "set_a_foreground", + "set_a_background", + "pkey_plab", + "device_type", + "code_set_init", + "set0_des_seq", + "set1_des_seq", + "set2_des_seq", + "set3_des_seq", + "set_lr_margin", + "set_tb_margin", + "bit_image_repeat", + "bit_image_newline", + "bit_image_carriage_return", + "color_names", + "define_bit_image_region", + "end_bit_image_region", + "set_color_band", + "set_page_length", + "display_pc_char", + "enter_pc_charset_mode", + "exit_pc_charset_mode", + "enter_scancode_mode", + "exit_scancode_mode", + "pc_term_options", + "scancode_escape", + "alt_scancode_esc", + "enter_horizontal_hl_mode", + "enter_left_hl_mode", + "enter_low_hl_mode", + "enter_right_hl_mode", + "enter_top_hl_mode", + "enter_vertical_hl_mode", + "set_a_attributes", + "set_pglen_inch", + "termcap_init2", + "termcap_reset", + "linefeed_if_not_lf", + "backspace_if_not_bs", + "other_non_function_keys", + "arrow_key_map", + "acs_ulcorner", + "acs_llcorner", + "acs_urcorner", + "acs_lrcorner", + "acs_ltee", + "acs_rtee", + "acs_btee", + "acs_ttee", + "acs_hline", + "acs_vline", + "acs_plus", + "memory_lock", + "memory_unlock", + "box_chars_1"]; + +pub static stringnames: &'static [&'static str] = + &["cbt", "bel", "cr", "csr", "tbc", "clear", "el", "ed", "hpa", "cmdch", "cup", "cud1", + "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", + "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", + "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", + "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", + "kctab", "kdch1", "kdl1", "kcud1", "krmir", "kel", "ked", "kf0", "kf1", "kf10", "kf2", + "kf3", "kf4", "kf5", "kf6", "kf7", "kf8", "kf9", "khome", "kich1", "kil1", "kcub1", "kll", + "knp", "kpp", "kcuf1", "kind", "kri", "khts", "kcuu1", "rmkx", "smkx", "lf0", "lf1", "lf10", + "lf2", "lf3", "lf4", "lf5", "lf6", "lf7", "lf8", "lf9", "rmm", "smm", "nel", "pad", "dch", + "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", + "mc0", "mc4", "mc5", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", + "sgr", "hts", "wind", "ht", "tsl", "uc", "hu", "iprog", "ka1", "ka3", "kb2", "kc1", "kc3", + "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", + "enacs", "smln", "rmln", "kbeg", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "kend", "kent", + "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", + "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", + "kCMD", "kCPY", "kCRT", "kDC", "kDL", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", + "kHOM", "kIC", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", + "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "kf11", "kf12", "kf13", "kf14", "kf15", + "kf16", "kf17", "kf18", "kf19", "kf20", "kf21", "kf22", "kf23", "kf24", "kf25", "kf26", + "kf27", "kf28", "kf29", "kf30", "kf31", "kf32", "kf33", "kf34", "kf35", "kf36", "kf37", + "kf38", "kf39", "kf40", "kf41", "kf42", "kf43", "kf44", "kf45", "kf46", "kf47", "kf48", + "kf49", "kf50", "kf51", "kf52", "kf53", "kf54", "kf55", "kf56", "kf57", "kf58", "kf59", + "kf60", "kf61", "kf62", "kf63", "el1", "mgc", "smgl", "smgr", "fln", "sclk", "dclk", + "rmclk", "cwin", "wingo", "hup", "dial", "qdial", "tone", "pulse", "hook", "pause", "wait", + "u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7", "u8", "u9", "op", "oc", "initc", "initp", + "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", + "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", + "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", + "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", + "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", + "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", + "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", + "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", + "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", + "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", + "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; diff --git a/bash-5.1/vendor/term/src/terminfo/searcher.rs b/bash-5.1/vendor/term/src/terminfo/searcher.rs new file mode 100644 index 0000000..1782118 --- /dev/null +++ b/bash-5.1/vendor/term/src/terminfo/searcher.rs @@ -0,0 +1,91 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! ncurses-compatible database discovery +//! +//! Does not support hashed database, only filesystem! + +use std::env; +use std::fs; +use std::path::PathBuf; + +/// Return path to database entry for `term` +pub fn get_dbpath_for_term(term: &str) -> Option<PathBuf> { + let mut dirs_to_search = Vec::new(); + let first_char = match term.chars().next() { + Some(c) => c, + None => return None, + }; + + // Find search directory + // The terminfo manual says: + // + // > If the environment variable TERMINFO is set, it is interpreted + // > as the pathname of a directory containing the compiled description + // > you are working on. Only that directory is searched. + // + // However, the ncurses manual says: + // + // > If the environment variable TERMINFO is defined, any program using + // > curses checks for a local terminal definition before checking in + // > the standard place. + // + // Given that ncurses is the defacto standard, we follow the ncurses manual. + if let Some(dir) = env::var_os("TERMINFO") { + dirs_to_search.push(PathBuf::from(dir)); + } + + if let Ok(dirs) = env::var("TERMINFO_DIRS") { + for i in dirs.split(':') { + if i == "" { + dirs_to_search.push(PathBuf::from("/usr/share/terminfo")); + } else { + dirs_to_search.push(PathBuf::from(i)); + } + } + } else { + // Found nothing in TERMINFO_DIRS, use the default paths: + // According to /etc/terminfo/README, after looking at + // ~/.terminfo, ncurses will search /etc/terminfo, then + // /lib/terminfo, and eventually /usr/share/terminfo. + // On Haiku the database can be found at /boot/system/data/terminfo + if let Some(mut homedir) = env::home_dir() { + homedir.push(".terminfo"); + dirs_to_search.push(homedir) + } + + dirs_to_search.push(PathBuf::from("/etc/terminfo")); + dirs_to_search.push(PathBuf::from("/lib/terminfo")); + dirs_to_search.push(PathBuf::from("/usr/share/terminfo")); + dirs_to_search.push(PathBuf::from("/boot/system/data/terminfo")); + } + + // Look for the terminal in all of the search directories + for mut p in dirs_to_search { + if fs::metadata(&p).is_ok() { + p.push(&first_char.to_string()); + p.push(&term); + if fs::metadata(&p).is_ok() { + return Some(p); + } + p.pop(); + p.pop(); + + // on some installations the dir is named after the hex of the char + // (e.g. OS X) + p.push(&format!("{:x}", first_char as usize)); + p.push(term); + if fs::metadata(&p).is_ok() { + return Some(p); + } + } + } + None +} diff --git a/bash-5.1/vendor/term/src/win.rs b/bash-5.1/vendor/term/src/win.rs new file mode 100644 index 0000000..3d571d5 --- /dev/null +++ b/bash-5.1/vendor/term/src/win.rs @@ -0,0 +1,301 @@ +// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Windows console handling + +// FIXME (#13400): this is only a tiny fraction of the Windows console api + +extern crate kernel32; +extern crate winapi; + +use std::io::prelude::*; +use std::io; +use std::ptr; + +use Attr; +use Error; +use Result; +use Terminal; +use color; + +/// A Terminal implementation which uses the Win32 Console API. +pub struct WinConsole<T> { + buf: T, + def_foreground: color::Color, + def_background: color::Color, + foreground: color::Color, + background: color::Color, +} + +fn color_to_bits(color: color::Color) -> u16 { + // magic numbers from mingw-w64's wincon.h + + let bits = match color % 8 { + color::BLACK => 0, + color::BLUE => 0x1, + color::GREEN => 0x2, + color::RED => 0x4, + color::YELLOW => 0x2 | 0x4, + color::MAGENTA => 0x1 | 0x4, + color::CYAN => 0x1 | 0x2, + color::WHITE => 0x1 | 0x2 | 0x4, + _ => unreachable!(), + }; + + if color >= 8 { + bits | 0x8 + } else { + bits + } +} + +fn bits_to_color(bits: u16) -> color::Color { + let color = match bits & 0x7 { + 0 => color::BLACK, + 0x1 => color::BLUE, + 0x2 => color::GREEN, + 0x4 => color::RED, + 0x6 => color::YELLOW, + 0x5 => color::MAGENTA, + 0x3 => color::CYAN, + 0x7 => color::WHITE, + _ => unreachable!(), + }; + + color | (bits & 0x8) // copy the hi-intensity bit +} + +// Just get a handle to the current console buffer whatever it is +fn conout() -> io::Result<winapi::HANDLE> { + let name = b"CONOUT$\0"; + let handle = unsafe { + kernel32::CreateFileA(name.as_ptr() as *const i8, + winapi::GENERIC_READ | winapi::GENERIC_WRITE, + winapi::FILE_SHARE_WRITE, + ptr::null_mut(), + winapi::OPEN_EXISTING, + 0, + ptr::null_mut()) + }; + if handle == winapi::INVALID_HANDLE_VALUE { + Err(io::Error::last_os_error()) + } else { + Ok(handle) + } +} + +// This test will only pass if it is running in an actual console, probably +#[test] +fn test_conout() { + assert!(conout().is_ok()) +} + +impl<T: Write + Send> WinConsole<T> { + fn apply(&mut self) -> io::Result<()> { + let out = try!(conout()); + let _unused = self.buf.flush(); + let mut accum: winapi::WORD = 0; + accum |= color_to_bits(self.foreground); + accum |= color_to_bits(self.background) << 4; + unsafe { + kernel32::SetConsoleTextAttribute(out, accum); + } + Ok(()) + } + + /// Returns `Err` whenever the terminal cannot be created for some + /// reason. + pub fn new(out: T) -> io::Result<WinConsole<T>> { + let fg; + let bg; + let handle = try!(conout()); + unsafe { + let mut buffer_info = ::std::mem::uninitialized(); + if kernel32::GetConsoleScreenBufferInfo(handle, &mut buffer_info) != 0 { + fg = bits_to_color(buffer_info.wAttributes); + bg = bits_to_color(buffer_info.wAttributes >> 4); + } else { + return Err(io::Error::last_os_error()); + } + } + Ok(WinConsole { + buf: out, + def_foreground: fg, + def_background: bg, + foreground: fg, + background: bg, + }) + } +} + +impl<T: Write> Write for WinConsole<T> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.buf.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.buf.flush() + } +} + +impl<T: Write + Send> Terminal for WinConsole<T> { + type Output = T; + + fn fg(&mut self, color: color::Color) -> Result<()> { + self.foreground = color; + try!(self.apply()); + + Ok(()) + } + + fn bg(&mut self, color: color::Color) -> Result<()> { + self.background = color; + try!(self.apply()); + + Ok(()) + } + + fn attr(&mut self, attr: Attr) -> Result<()> { + match attr { + Attr::ForegroundColor(f) => { + self.foreground = f; + try!(self.apply()); + Ok(()) + } + Attr::BackgroundColor(b) => { + self.background = b; + try!(self.apply()); + Ok(()) + } + _ => Err(Error::NotSupported), + } + } + + fn supports_attr(&self, attr: Attr) -> bool { + // it claims support for underscore and reverse video, but I can't get + // it to do anything -cmr + match attr { + Attr::ForegroundColor(_) | Attr::BackgroundColor(_) => true, + _ => false, + } + } + + fn reset(&mut self) -> Result<()> { + self.foreground = self.def_foreground; + self.background = self.def_background; + try!(self.apply()); + + Ok(()) + } + + fn supports_reset(&self) -> bool { + true + } + + fn supports_color(&self) -> bool { + true + } + + fn cursor_up(&mut self) -> Result<()> { + let _unused = self.buf.flush(); + let handle = try!(conout()); + unsafe { + let mut buffer_info = ::std::mem::uninitialized(); + if kernel32::GetConsoleScreenBufferInfo(handle, &mut buffer_info) != 0 { + let (x, y) = (buffer_info.dwCursorPosition.X, + buffer_info.dwCursorPosition.Y); + if y == 0 { + // Even though this might want to be a CursorPositionInvalid, on Unix there + // is no checking to see if the cursor is already on the first line. + // I'm not sure what the ideal behavior is, but I think it'd be silly to have + // cursor_up fail in this case. + Ok(()) + } else { + let pos = winapi::COORD { + X: x, + Y: y - 1, + }; + if kernel32::SetConsoleCursorPosition(handle, pos) != 0 { + Ok(()) + } else { + Err(io::Error::last_os_error().into()) + } + } + } else { + Err(io::Error::last_os_error().into()) + } + } + } + + fn delete_line(&mut self) -> Result<()> { + let _unused = self.buf.flush(); + let handle = try!(conout()); + unsafe { + let mut buffer_info = ::std::mem::uninitialized(); + if kernel32::GetConsoleScreenBufferInfo(handle, &mut buffer_info) == 0 { + return Err(io::Error::last_os_error().into()); + } + let pos = buffer_info.dwCursorPosition; + let size = buffer_info.dwSize; + let num = (size.X - pos.X) as winapi::DWORD; + let mut written = 0; + if kernel32::FillConsoleOutputCharacterW(handle, 0, num, pos, &mut written) == 0 { + return Err(io::Error::last_os_error().into()); + } + if kernel32::FillConsoleOutputAttribute(handle, 0, num, pos, &mut written) == 0 { + return Err(io::Error::last_os_error().into()); + } + // Similar reasoning for not failing as in cursor_up -- it doesn't even make + // sense to + // me that these APIs could have written 0, unless the terminal is width zero. + Ok(()) + } + } + + fn carriage_return(&mut self) -> Result<()> { + let _unused = self.buf.flush(); + let handle = try!(conout()); + unsafe { + let mut buffer_info = ::std::mem::uninitialized(); + if kernel32::GetConsoleScreenBufferInfo(handle, &mut buffer_info) != 0 { + let winapi::COORD { X: x, Y: y } = buffer_info.dwCursorPosition; + if x == 0 { + Err(Error::CursorDestinationInvalid) + } else { + let pos = winapi::COORD { + X: 0, + Y: y, + }; + if kernel32::SetConsoleCursorPosition(handle, pos) != 0 { + Ok(()) + } else { + Err(io::Error::last_os_error().into()) + } + } + } else { + Err(io::Error::last_os_error().into()) + } + } + } + + fn get_ref<'a>(&'a self) -> &'a T { + &self.buf + } + + fn get_mut<'a>(&'a mut self) -> &'a mut T { + &mut self.buf + } + + fn into_inner(self) -> T + where Self: Sized + { + self.buf + } +} diff --git a/bash-5.1/vendor/term/tests/data/dumb b/bash-5.1/vendor/term/tests/data/dumb new file mode 100644 index 0000000000000000000000000000000000000000..fd4091a9946019db595d9b4ac2a6b935fe42dd20 GIT binary patch literal 308 zcmb1Qlwe?DU}R`w;9y88%}uJYFwjlT&neB#Qvh)lN=hmj7#IT>{{LqHs{4-ySTID; R6bvIS8v{E7F9R140szw?1nB?( literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux b/bash-5.1/vendor/term/tests/data/linux new file mode 100644 index 0000000000000000000000000000000000000000..b458ffaf9ee20fee8841b0a3aca29bbc46c77fa1 GIT binary patch literal 1780 zcmbtVTWm~G6y4`cL%mB7Itbz>-tIm3-p(|GQB+G?saKSVcuY$l(}z+@&4@%I5g+_W zgoH>WB9WjZd<doZ5fSm>@yUk|k>G<5ajkvsOovj@xanSd?S1y$=iGJ9^yG`tG?DTs zDV7Hkbxm#U2Q*HOH#hBSPSg+y{K52-Cg~87=jFow^yJba8ig?;NjWrz@@WbgGy@rj zim8OkXg&A_ssYwfBkiLknCBg$BXmr&6LeDh({zq5&?V}mTRQHdhxC}9X`Y$+Exkkh zKArmj|G8)U3w<Lg28y9#q!=qEh^b<_m@91Id12UmQ6!eZ^RpuD{pfdGiSbopqlk+H zSer<RBk;$2y>%)bpB3lDWpPDZ6F0;V>3PFp*(a|j8V$BiM;qkko@};~Sxq1LU#mQ? z{vYdlzn6&<vQ@Urlsqht%H#5+JR{HlXU9zE-u_}g`(Bne<!yOiK9W!6^M1bDd+z?m zM!<h#M!-(9zjs&=SP~dW!zdUt>Wmi4sE!yd%BXHd!rlQW4aQc$mBHAji%PQ8uP>#+ zNR`5(%1r>RIOY0LEg~}xz64g3&4oEv39EovRwK}5&`dFNY5^f;8XRVNja49)$)OqX zy^}zobeYn1QJ3d+6Vv7^)10>uql;kWbP#B#0E=OIIm+VDk9mo)r3}RYE5svKSYsih zGBwwfflCXRxD5UW4r3+sGWp{)smKtXRA+cGnv`b<x6&Ezq6xH$2RE&zV3;%h?o?AS z#8Pud{&pkErMn{`Bf?aHIzF|tSqIehvo5IeX#uF^(?X`;P_&c=p>+w(%9}lM&bYbb z&DUFUwqD)-b;rlrD|JumUpCxHylTAL^q@J_(!I00wR_j*-S^wB@9Elmuf22M=l!2L z-W+(5Jd^s4CL3YV5bt3$#M|Sf@ShbLYWWo+aIKrt5-P2;(mLCEPi)0Cwyw8zy~XDc zQs9(ULzq}W6Chf^CyC82j5vk(2o`NqB`ed;nsg}FO&T+e4$Cynq%qGh74mi;dFPLL zbZ5<Ny)&31=JYWC?D9FJ0Ir|`xS^)<RRsI_x5uLcpzcr_f!k&*w3tLiRa9b9)mmB? Vrec%UnAEUUQNuP1W>Z64(GTBQScU)q literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-16color b/bash-5.1/vendor/term/tests/data/linux-16color new file mode 100644 index 0000000000000000000000000000000000000000..8c2e4768b6983a96f617fbe1f63c17cb816bf124 GIT binary patch literal 1858 zcmbtVU1(HC6h1R6n%2KqtXQ{}C>^Nv@7}rh?rvCdO>Io@{}-c+Slx|g%}qAuM`PFB zA`}Gi!M+Hhpa?<{1T_lvq12yLUy6wMp!QK8d=SC<&^{DzzcY6?tEnjs4msz1-<dP# z&i!UKcZQftGpUw};!woTb@uhow_};SpYJ|sSY0OH*^~EM>-Oh*+v@BXIOckY1pZ)V zltGya5d<|9ymQoIRSI)NlE%=-G=pZ5qB+R8)JRRVf;Izhp;q`Db<hDS0tLY#I!s3m z`hkv{c#_W0IXX`Rbj|P^ben#o`vzAY{gj@8KQHHAAif%!|C9bEDaMHjVv3k1J{7aY z7h-{Mu=fOPk!TRh5P2*w$B_Noug3g3u~lS*57Z}0;xOW|VXID*`Dt-hTo4z<WpP!E zmq9QIRvooNY%0(u!?wunL)mI2qt+4fZ&wAup8r`ld|ie6vRn4clKfsCk;mk5c}kvr z&yJPO!{d*m?0Z4}B!8B-<Q;iWJ{aZN;m;l|SCMeVoXDCo`tJ^XkwRn~O{8dA<y4og zvPspYRkj-mXE$7PG`$>Q1&m|4sHqCW`eynNsb*M8dp^9Kp_-7jfms>grLcx-F2T9A zuvIYI?tu5$8KfDxZE$f$#<`5l9$Nrxi>Z|iqw9lcQ>IN_%H!vH{^yIdWi4Ec*(I=* z^c}oYg8K?)wxeyPA?Gcozh>76XUBQQP8eU$URwqm$c{^63_Nz>3r=Ju%r^Pu3|LhG z{7{qO%^0w<0=SjQa2ErhRVKP^Jw+3o2~Q_W(Kt)Z9r@i=ic5Qwag}7K0o@Qf)vOEX zg;@_!hcE_chp?U@FcfX3574@a=GM-eGJpDlPpsd+8MEWkuD^D_Y`d7dyXR5+FaG0> z>z%*mOI?F|2fGJ*w)fuZyRz@b{+s;+2VQ;qN8!oAhs9H+*J!d8mWuNkrs8}&ZVCTc zp`npqg8>`ew2@F7owd=~F=ygvu5nDgW9n_bhmZodGz($Uu}-*DjBgT~Q=fF}@e(ZB zwzaHGKWkFZo>x>~s)B7<R#7cfmPXzgA@9C3kM69w!%Yi`qUuoDQ2Ro>s1_S3Ta!A} zFzt?5<tbF*EU?M)o#*>Y5q!DE;(IrnzhJO8f3rM07N;_SCeueW4H|w%4K37UQOic! Wl%Ph7HdxfYLsR=s8|F}ZM$<oqfN#+N literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-basic b/bash-5.1/vendor/term/tests/data/linux-basic new file mode 100644 index 0000000000000000000000000000000000000000..4f23cb9ad8ba4c8a21778f399e05066932569d82 GIT binary patch literal 1664 zcmbuAUr5tY6vxlKiJ2r?RG7mkX+eLi-@k2+MbpYQQX@;j9Fn@FTbt9Srll@|2!tqt zdI*Z3UV4Zy>ZzBk7K9HK^kN0Q_)tVa*^5uEbIxy@H4C(Uc)sUz&ON_-@9+Gs`;~|i zD1{;z5wB$=6zv}@Z*S`j`G=X;`@5sP-H~Ge0{_tXN<k)sWHJx!PgfpP!b%(ikdOnb zp#(O76*gnWfNJodui-oEQ0vhe;Rweq;D;bn7sS{Pz%ZPJ^Kc2Sa(n}B!5z5AoL+ex z5*WWo<tEU-%8b8(N%#O$@Cm-cG|a#(<cNGxD3ZxlXvLybl%c0<Q_7pseBFZM<-#u9 z!i!WdnuQ;IB<rsJR6Hc&VpLoZ7sX}q5p$n^tNW6Pz9FfSR<lVL`}r$Z{Ux7Wxo?4W z+4rSmuRI_dWV39Q9Wo+ga!|(qbH?<{+5X%j=N*+-<TZIy-d^N=+3WsGd^fe`n0&OL z)e~|;E`<WH_^csok7^CLtUa1F5W|GtiQ={R_M@voBcCer%%NHDg?vnTArEyAS{2$s zv^q3Z?LxJYFlj_a5XC{nVi58AO$e$&q2e;V5y3#?GL7rpwxGr5wnaAX)D&gME*z~y ztA#VDdK_gp8gD^UDKul+mTxafHHzw>5w(KVNvbK#j3iWQC$N#24^==<$=jrdW2j35 zEy@|%3`1=iXe!RoEDYEmzoq36SSl!Ec0K?W2epxAq-VFfskG1Ku(}8}M8iaVE^8p# z%&ZMjGtrKyn&>1%#*TVn8BXnitwq~bloxMbtGsW`X}jMs)A>C(7J7O7ZTNBIUDtT@ zd3U@gaUu~*^d9Yd*8lM2lYys$4^I6!Jv}rvJUMbbK8uqyqq!aQ4&4rVJw_aVHL-`> zehnjJ?wiIf)VR+Y_gUw6qH9#6bG^>>DxEQG1)jhFHpXX<qPXpTR5IP^GMscQs69G2 zks>2Q<}srqvjjf`x%jmxqYnbwum4AYqq*3J<xq&f`D<|3>!7L$JPI^5Kw|||D{xqW PaGM6<b`?#BuwR3p!_Y@7 literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-c b/bash-5.1/vendor/term/tests/data/linux-c new file mode 100644 index 0000000000000000000000000000000000000000..aa66f83d836c5c348162b91dce1fd6d942f60435 GIT binary patch literal 2120 zcmc&#U1%It6h8O5)L1O7qEfq5*5YkxW0ILWGrL(<x{VsM*rue~Ld+7{IGaDS*^QIL ztZsHi6rmuBpbvr~*cTr}D*A5K2;zf2_)-;o>4PE)T3`Cq_?<JmscuyoeCV*}JKs6? z+;i`IcXno%>Z9GXgBt4jM0vKdT<Zx}#izn*WwBbGOu4;YZ@N1*RgF^Ba%nP3Rl?<H zadMGJ;RlneMOvX!>+4;#{*PA|9im$?Mx-f0x6>}Vn+)wo#-~9Vf<G)Xhk?gnC+IPW z$0?*4Ve=G;U!hfcj$Wi!=yi$TqIc+BdS7^Z>2tJ(_={HVOZcxh#=oKS^aEX>pXgV* zNSEj`CDc~69eckGwo~m^d*J!n+wyUAH6Fltk4me&Du5kRV=9C%cg$LD#dXzGr`1d9 zW%a815xJlLR`<(B^c$F~d9^_2#9zJgz`x`>D<8VXy3Tp+xS)^f<9bY=(o?#uBVE(Y z|JkwKxzoR}$-bxcYx)iSwmzfZ(`Pq1w{z{y#wQc;j4(0ZV*lM?CDBOSNZTk`G_z*G zHKm+cu%;9t;Y|Yy$>PIshhgknMMGC;TwkEANEN6H_yBAGHUb-lx$ZnLU=U`R`7?kF zGXbBOtUn6kIvhH=*!yJ!R?4i@<%5}IF&~ugxz9RI-$9HXf*qk}fnF1EKTNh@T@K@z zw^e+QVG!VEc*N}&%raU>xKIWzO*07?;+xvWcPZQCn-enJCcLO*cr!wdv<bJ840jO% zeZu7UBb4mtOssr~k{OnfJMz7oJeMxzGA75=g8DJ_u4H}CAkGG$Hl}G%H>O#p;83(c zH=*?qb?><MmY$uxcRJsnN=$q(b!qzdnX|KBJ@M__$K~(l&s9FJHW${OT#MEgPcD77 z{LxdNtbAJg@aaFExmdrjdcN^y^D>%@!SWeC!+eI1$8X}T2@OSliwInFvm&7tovrBX z$(eYTYdop<q~7Ic3{v0;EJ2uJx&p|jLm-=%&G}i}1dBF45^Gb>Hq1e@#4^=gr(t@` zzKMON+k|FPRE7eOt!{&$VGeMKgQ7k&5}D};VOoM3dQI0%yBE{WUdWZuOD3V!UNds- zlNP+|y#fFFZUAS;PqZf|f&(o28!Ub^@V}gHz_)t~zWRIk8xH&HTZ>1x;Mu*Iw&Oc} j2cERMXke6v92z}NC;Dm7p+_B>o3J$ZxC`@WF0}L~cK*F1 literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-c-nc b/bash-5.1/vendor/term/tests/data/linux-c-nc new file mode 100644 index 0000000000000000000000000000000000000000..da344e0deaad46bf6dc7d202e42f5579c3871263 GIT binary patch literal 1766 zcmbtVO=whC6h8M()F_pxsHlUjN}r%{^u7Dun@O0`F|BC^V~Rf!Vun!Ti)LablQ<?# z+9V@|QV>duU>Aj!LfyC!vDCd*BZv!KxbX+vxKK(38#h@QzjNM9)bR&{kDTv(=iGD8 zz4yCs@>Z!@T1|^+Tv?G^Pkv}57R2(wn9wyrfBtBH?%<l?p1~}FTz?@JWIOZS2Z<E^ zVDgkmDO75Dx|*h6`&83bT7oemO;xmvR?%9rXah1HHBu9Nv&?J(?t<;5eG+$2Kv`jZ zR1iN*WAq*UKtIzj68}zr(rG#?yu9>9nm~NDl)DChV`ls&-J*MRpB~a9nxrXuN>yrs zs=?lu!d9r&Y8^a3>q|b2Ud4?VkEysysWjLw)vf~gT*a)RQaq}P>bUw*{iIH)2gv>V zQr&+u(PJ=2^J>0Mihp(GhBxFZE5CThy2^RwIIX|bt-4+B*N1dY7xaiOzGugB=Su(m zEc+hUC-txT4}D6X(dTA4w{q>-#wrrdm=mcfvA1_v8TlwOj}}riWA#`Aj@6a428`8J zK*H??q@$VbaLq9GrJ|<iG^|h40;JMZ4g4I|0NV*`fjLee&}R^4n0Z-1f|-EFOxAA$ zacmClWazyd0wZNc>Qa6-no0S&k3TWCz2#GkZiVfjV?ehE_zWgnFb;=d%-hOrV`v08 z2_A9k1nU`%EnFxAm&Td+4B?>`@+oDTd^jO3Wx|U}hBqT*N11Rd$#54T&?ks??51cP zXF}z>D4Jjyxg($5N^$96GGQf|8c;8!?(?h%>W5h$)Pyt+>V&kODL52O(|ojUqS{59 z7ROd>UTNRmU)A~7p{efwv*&uQAHLmtA$O<mV*W~habV)eL}B9SSA&;_&VT*S@THNz zzj^ZQ<mmmeTjReKpQ1@SES2CpOeOewydwT<LPL??AOaWNj7VriXCpehawo3g8dvIF zsdxAtgA{lJyC6&^o(H7j0g%nDPkQw@1dG<Ola(1^O-7CHk6Rn9QOCCJachfZ8|2+L z<h|GC(VaDS<z}!%#+zZ`yUXt(Meuc*i*M38{>s2!{9W<rT&Vj2)!<9A99n!x4Q<q9 aQ(G(Tt)oVp_Sn?hX{h&r19Pc2F!T&a_FJj| literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-koi8 b/bash-5.1/vendor/term/tests/data/linux-koi8 new file mode 100644 index 0000000000000000000000000000000000000000..1333f2d9f7d1d5965e898e2cd2d6c0c8d3ace0ac GIT binary patch literal 1808 zcmbuA-)|IE6vxlKOWLXwS|bEmAZukJ{s3m~%yhR|!nSDLO`!z&5o$M$uG`vOc3W!M zLZR)_mLIJIOq(<YlmtS84-gZA5kfE|Jm8b@p?`x9J{Vtk@Wo{Oo;$l;EydV4={e_f z&OLMPopbN@t`|0Kq&gZC@jyP?KQz2GcQhLr)fhUFEo4IMhf?`M&tQM5&=X2$QiG{9 zywI_p0+GNUL_Z}cxk7ke4S7pGHPlQmV~j}B3R*+!=`}LwO+*}Or8w=T!{8682RciA zbdttEo;N{LbWzhReW~r&be(R}E&7fgX#X+&NI%iM=JM3P(68`+E5&|?eY!CI2mMJ> zREw3OUaS=xM1$BOwh0?+k3e>a7V$nTKW!!Jd(Y~<82><YinPdshD1?J!Okpt>q^PL zCT@st#T{{1d@o*-p0^58dFmFtS3n1}cUX2UL@Sw0>F31%ndNzz|CqP<y|RBq4#?wj zR8Goi`GuU5U&-tLvtqgOV*AZ9>)w|4<U{#bK9N7m`DMPlc<$x;uLt}$-UwJF`u7Ua zKue&SYAKjBvc`aAbVrQ=WpocBVD~~Lg2^_R-4M2=q<97W`~<y-Py!NDZXVi7Q;qLs z;F)RgyO5SjEW)vUkamb=^+CI=G$|%00~Kb{%3;!L>;PCMyJpn4P9BcZX-enCT%Om> zZ{DFybNfz=HbeH%X=u9$wF{z`qbzoPpO=_?k5wy_73L8uqIDB%Wop*Qic=dITvq-E z)^aEGGWp{)w3mS=)e&BdhCOBAQaZv_G@w`MVAp;MMmXZ{PB#U^+-k1K-)_V>wGa&( zQAP!He6%Z32k81y7pQz}1X?~eF@n+21igULaeBM%o%*fow!Laz`glcZ_S37q*D^EN zM@P=(&g3Wi&h}q8S{xYvY<zJ1*hhu)LsQ2;KQTQ#aq{x1D<k(ue<;qOL?<K`<{gZM zd2^g1{;#5gy7>woSa(h71}fcUrMqnF9kCVX*gD_V`4*o-Gy-R|8*NE8_Cv)Q`5dv> zO;M)_pTI5a+Q)qv=8lXg*Bvw7GDa-ZG{=nXhN%#@pA&bMjH5bt+}8VoDU!|t`6ri8 zAq8;%RN?k&;Cl%2_g@~5R-v~mX*KSewdlnrYU!Z3NgW62P=s1dI$%;Rr6~7_1+giY GR`eIR*<6eO literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-koi8r b/bash-5.1/vendor/term/tests/data/linux-koi8r new file mode 100644 index 0000000000000000000000000000000000000000..e3cb2a18dac7dc657aa0206bc531291732ae12cc GIT binary patch literal 1814 zcmbuAe{54#6vxlKB`|fsMwBQOQV1^*W$@m8@AXFtmI0#`HUkQA&=9O$rKQ~%UFSMS zYfMN;h=1TeBt{a*5)wi}f=(0t!zeK2A7Tvg570mL5C1SE$RGNL@%cUXwJS~_EWGTT z^Ev09ckX@X-tI0FVOmZdR1>cRN`;}(YFF`aAzD7FIW$(N<U<_jDu*(qO0GPVspLZ0 ze5Rbq!V8V$DntT*5dAcu;llI0Hpu;+Hrhl>Fh(S49z8?LXeAl61`&sPC`mi$4e(yd zK^JI{#;FGKy!YuieW2+>I;HK$be7K11)8ESwSSquqw91-b93fj={NYlH)6M8@6L?> zNq>_R3q-r<6idbPVwHG7tP{5IyeMRY=oZ^x`PtsEzW0CqD#mw-eIhGLpixm5$6-&- zdh4Txe@0A-i{g^_RD3R;lAgB+(t0{(yr)5Xw6|9tn2EMBnQ{+^|2NC?4n1Pt?Dv{} zNtR_**5xsILY|bT<Y_tim=&9qXWR30tb0*@A-|GW<u&<({Be%&&YpX&z7g=>SQD@t z^zaHB16u+MXdwmDM!^`ijDff@tc-y&0`@_uR4~0AW(S0ABPrQJKR-oJB9ww8lv{$f zvef2#d3a_Pyam$TibXlL6VeB<tU+j(l_tgH<e?%=S~*O5jr{=2WY>)Q)+xbJI!)=k zgv;}~rPUjhX|8`6qnjYT^d7WbhuRF$%TX4)zRyccZ)Md3Wkq<zifSEWtxU}tS#fHZ z!DZ!t;6m<%UM7E>hQ227q&mWj(a_rjE~O(}MFV=34eo!9f>Dn6yE8z+2)CLm^0yla zPOZcvMx0Rr9Utvh)B(DF)CDRZ!$8Z&7$X=RP0<r5ourpK)^>J1yY4yj=QrnNK6(4E zgLm?m3f~{PRs6d2)8IEl-yW_HPal~sPmdg^Tpj)Foy%ias#D{4-~D6am!mgpr|bWq z$UaCS!h4vA@b)-${AWcEb^8@Ou<o1EEmXSCO842;dtxijv30(!^DRDyXa!E`02-4H z4?!iue3Dq~Slo%>Be-e%cXDT{+>;6Ax;5iPW5O~`vu3O}Ooh1pfVgwtII45cZM`#? zBJIqOe|GsCQUF)beB5EH_$q?j``hEu`RHytEyiuL6unqM-Tjm_sed=^iBgYAubWiN OC@Q{XL2N2!75xi6bY$KD literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-lat b/bash-5.1/vendor/term/tests/data/linux-lat new file mode 100644 index 0000000000000000000000000000000000000000..9a428f96e180cc75c0dca31e8b133771bb193031 GIT binary patch literal 1822 zcmbuAU1$_n6vxlK8#I1LQEA;Ot2m(bBQtkqvK!XAMvaMI#ZQbbLD$XJ-DI++>!!xW z-BSDrih{lbN(Ds_L=Z$Nv=2U5zg|R2@j>uWANo)P^`U)`PXFi5ZnjOeG<3*0_xC^d z%(*k?-p$MrD`_q@P)V#0dAWT5z%nmYJgO;jI9JR@Aai*ua<CAPiln?^rjSn+Gm&&Q zRY;|wB8M_XB7r}czA8|WP`+Oed)HM@t7r!1h$Pj~ESf{}$)LrEIMhmQw2^j!cT)yF zN4<1}N+93=nuh3%rt>tc$8YHpU7>4qi+<4h4n3ep^t0yb$}i{_=wB<bml)rS%>PDj zNs94evY0Mri;u(tu}CZzw($KJY=vkM>oD@Qp)v;QpZ-(KZxwq)T6my-Q5HiO&yBk4 zn~J_DE{p5phPWxd6O*LxPleU4h7mOrv{S3ya_>mAmdTWPPyFv$zTf>H^G4rS)t)TK z0a=#E<!O0N4$BMj^8c(@tvq_XI>x%!<@fToyel8dpX8G<-aC5jv1%g}+_5-hSLoj> zd=gp{8c$OwoHTMqpJjB#jXq^`6%eowz_o{y8!&8y@mNV}t6`AeP7@Johb5Hj!CPsn z4^$S)OoP|JT57Qv$F{&W!z`;8-esprF*#YdD3f*$lYYhyfMv2Y<H6{75K5;hotJQV zUDsQ<LYZdcO3bc;ZKAK>?K0eIn0_2(u?#dnVsb6JRyZrlGgeIdX7<X|tdSk3HZi#D zf)|{^ozRcTFQ;L16?jn{;fK+%sR~?5N4Sax^eP?h+(zLTM}pnyqHvU3%@z6GjRdC_ z<545dsDMs@b}i}v-5}}$Re()EE5K$(Fgn^!6HvO1mNYD#zU+hLADYkh)ukqV_WOZX z*&DgX-KToacqe<0<?kOX_uc#abm88iy~UyavtQgf{NuohBX7QZJ^1|S)6#|VA1Ja1 zmWc8mCZfDOP8t7M(L>#S1qIf9Q@Vvp_gU#a+j>uI#W}Xlw{^b7=Mb&HDeXdIl1+KI zL=&GRHoH0QG~*?>X`NfRGXva{LFKw7<6~pcGEK8&G#aKt+<s5od1oBex#zat87z@> zMkqMDd=4puPtZ7g%NFpb2=>?C9?y<LcPG;{d~If<7xSp4gW62$*g-pE)N0aplX_B$ NdiGl|n|jiU{sf;*WlsPA literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-m b/bash-5.1/vendor/term/tests/data/linux-m new file mode 100644 index 0000000000000000000000000000000000000000..65d418012ae2bdea33a3e7eda450ec582870ab59 GIT binary patch literal 1770 zcmchYOK2295QeLJ#rGqMin_jWz*o#n&rEj1ifh!Epiz8c9t0noXksS2F&d4=T@eI9 zJm^Ib1w{}<5PX6j#8=ddh=>OtM?H8DK|Sa}GXB-Go7JeG2sWvzuc~XRyK8zg<HRJI zKn0W*Zpdp&ws#b^?5$)wIgv_kPk9ZKlPRE=Y9kW(gXocktSf}?_b30CqucNHM_`Uf zQXd*c<7f&QGy@Tb%BY-{(mHT8H9$8}3+<*f$oKctK{~AIC>_)G1f8a{be^uz4ej5d z2lR-ZYR)bFhTg(|myNxL{nRu6nZA+~{ls7~T#Odu#Z)m}%n>&B9)-*mrD8EGk0n_f zct7jqm|rPsL_&C=c99VWVUP5B>Uh>aCC-Qo;-a`Lu8Bd?_lH9AqoBtd30kYYYPr5A zn$Kiv_)YxBEZ^Vyhk3o9%lV#clN~Z656DCEh&(1w$}|61F;}^_J@=P&FUafiro1N~ z$|v%fewJ_8{~1OoSm#eyoDnJt^`jvat~HvBR?Dc58Li5wZ$rS|0#y;NT>`Td!Zw>! zp2r}+f(9Z~0f{TugSHaXKkypinF;VhNNGM6<=6_yGKgihK)b9oDJG{8D#E0d!=(3E z1+YwZ%~)U^5027lO6SF0Uf1=e%~hsZG!L`$A(gZb+Ri{NfavWgi`~HIE!Hk#RR(26 zc*crqUBX(Knl-ZG)M5sgRdB!|+zGu+KAeVSIp9Tggg2w1G6!5rN4Sax^ePdqTSeh0 zM}oIgPvHo+nk(|zjX0<7h((MTqXIes+WDvhbc3i1Q~?$PtpH0H!RTlO4M6E~npH4+ zc;T2iW6f6^`fR+k`OB6MjTf69Z++2x%X`^!J9$5qY3<t9)z-Cr{f>L>S9jjob+_Zn z?oWF@cD~;GJbg0LjUqLWc!b|!Ji@QX$>2XLdZ^p4;DL4Dly0HYeO9{9wtgqJ;v8G& z+dALkdx%!xme!*&wZ%!Ocro837P}<ol;9BDw7M1CnGWtrr*hr2G1KU@Ow&voMTV&m zw|^6Nei=t~?s;%e`OZ-YUz@)8E=}dH4&?jaH_!G(CkN9o8bPCR?uk@dMdc<{t)aD1 VDl=)dNzEG-HE*&YHZ>;{eFG{tUWfny literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-nic b/bash-5.1/vendor/term/tests/data/linux-nic new file mode 100644 index 0000000000000000000000000000000000000000..84458a5f466e989000261aaa75b6582a945c20c5 GIT binary patch literal 1810 zcmbtVO>7fK6n-;CkRl>}B&vWZG8K!&PnzA?UE7fX6H15$iG-k(v{sY`+r+LN$FY+p z5FCU!ph`#;mFNWykt(DLE+DE(Z~;nyOU0q5{v6vw)k_6jIC=Trteu1aRim!*-hA(y zH*aRX8E4ju4tkGPQB~{=6mrF}iPmB+by}m)cy2Ts%B8YxFe_9UE0xNbN+pvHofs~M zio?a$)L6Nasf0@9;lc92P=!d~52n95sE0y$UK4q5{F-PFtwA4=q$RYL*3%|3Xe$_p zI;o2e(lOvqC<C9PAv#G_AkRBX=jnn*7wH?_UZ!cfO4sNX-PZAadPG0b&l)$Tu6chV z{;SUYjrO0}{^#_9Y7`JnqFJmFEn=hCEVhX@tlfb{#V)ZIEr0v#tslMa51_wCd@TA! z4V_srB2Ixhw_wzTdi=GxB&Nl;;;Q&g)W8WjzhYoES_YKRQMWui%g)dByxzC)uV#5( z-+#<oIIa=*%Z$v+5jifa@|^rqekCvc&x(!83){<!tUE2Q%Nz0sc}G5wj~6+1;oOUj zTLS)w4S_9n^zRkSKsd0Bnkkqxaz@EA(lMi?jC2`<JqVWwCJ&%F2;;V%)HMhF`~)or zm4L;STY$Gx)Z|B5L}m*3Ls-Wg7iI1ctOsUUL+~y;jT9p%3m0Leox@14u@}HHIW%K_ z>l6?uou+hN+~s-Q!seaIG~0Hgx0}wu+f#6RVR|Xb;?R$IdC7h3I^nDc_gGQw+u18q zV-4AHYM6n`&fi=!tDu+28`Get0eDi)bT<H3&<qdO0P>`QeTOL+WyU{{GzBB9E*IkM z8gWh?jYW(YLj~yg(4J!*K-XtoK;^?Qpyk7MhQJUpLGPe+7j0j)V|8oG2kXq=KU*?z z^Tdn6r`a31C!hbCzgzfi=w9*R@KkALWTre*=^uSC_Wc+4$A6r-b@KVCXOn-N{-t_l zs)iz;!r~D=ws?e3#F@fBQ%I*(SBQYMTuLjaw7g2oYwM%173bJG-`4pSUp+{Hi<yQn z$#4-a9_Gu#X1B+jc5H%0>pR5COt2=C%5|&8He=E<O|xpW8KwenzlC?+$fG)IZtIi5 z6iH_m`PY@NUI1^-QoLX9^V<WP|7#=kE`_)&XeHj4cOk__>gc5|lX^d*qfzQK>4-`B O0Y&-a7R;u6O3_PhQ)r|B literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux-vt b/bash-5.1/vendor/term/tests/data/linux-vt new file mode 100644 index 0000000000000000000000000000000000000000..42df50d3b45aa49e8c5ca07306107085afb8d205 GIT binary patch literal 1702 zcmbtVOK4L;6umP_ZPltM3L3Oge4w_q@6Ah^mTIHcl4?H`t=bwYtx222e48}=SX&Wv zBZwOj1kr^X5kwS<3&D*b=*Ep}!G#NP<3a>o^m*<i@e>s+K61}J_so4WckU#aO~R(l zw1#HI8<~iu@>BH_<L5MShtjEBIx*tT=VGad`*<IO@JP-*n$Ef-+2Kqy7RnI`d|>)1 zl42-?<5ZIK$ET9^(OQfVNm@$lX%lTFgLXpkP&);vlTLsS&<HR_Nt&ivFvqz-m*}!) zSLvGeH|Q4Kp}X{u=5_p(p3w_>rFm)TxAYG2`=a&%{^R%YPxOTxS}Ll<DzQ#%6g9#S zwZcU0URbke6>aeR1d6^8{f?a&?-3`&kcfe0#f-QJf2HiL>&5t{xGnC9`{IFEa2`RM z|0VD7_vi`OXB~YNB!6F(m5RUU<=HF#F|Yi+Qd}+9$&Io`8nRYe(kJ)Iw*Q>5G;_H> zw8(jT<bXUS!!jzzWPXwFmao0o_<3=?m-6*Lt-RnYILoM-TtOpdWGo}xVq}yN&O)#w zfDTviFkB~$eK9HUgBJ2TXgQ<~m|uAlKr2L*g(!;141u@7_W#hDSnGv#lWT_w?@a<M z2F2is0({Igc$n!5`;pJ}m`V86Af5z3=`5ww{9azvo7lcbnPx*PM)$$G=seJ#0~~<q zT9n0MA?Esm2N~J{mXAlQCXLOE%G6v_22O2c;$<l8uA1ARtK^+&(p@6Fs8+ZbO}a{i zr_u_~q6r!mat$6KR}(9RqY0DC$9=|(9aIH9K()1Xb@lbTcbn$W(D3l+Xe1Ji#$spA z#N&xXGMP%H)0xcJST>u>jgRN^6BCn@Q&ZE^XV1=Y$tPicAGg`>;}&}6@YjcZ>J}+P z;CgRLZ&T@BDBTNN_sv$EW9xid=UaR*C>LL&Fp3X0rU3p%K590*xy93rgXE13_VPxj z`0F;Kyxv)3moa0Rra5ag7^Z@5|3&xwQOE4uX<K&>O9VYdwgk6A1@4q>d^^B?{zVZj q!B`coq}8|qHemZ(Xn#KiOzQ8WV@=d<(ovJ*!;0dkEtpO5kfLvP8$<;F literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux2.2 b/bash-5.1/vendor/term/tests/data/linux2.2 new file mode 100644 index 0000000000000000000000000000000000000000..8656939f5efee9a7970f87f5092a1da1d84d4bb5 GIT binary patch literal 1788 zcmbuAU2F_d6vxlKE7W%hf<+LM_-tqH%yhR|Y>R49;xnon@v$wfZa<W=w7VjaNW=p# z5+NZ?BqEWZBs_?(;zdNngO5iZJctAjJc#i>cXqqfM>Hlq=lssOXU@HI?%m$;Vj@kX zd`gKWfkb^%TT&IM4h@q*1<A?r=B8cEiCQ9oKZt%Zka30Zygc%L`{Ypxjl>v{q<%D- z#?ursXa*t<l~Fk@qxIkoR0~~CjkJ$aAkRBUhv}%M<8(sXQ*@Tj(FN+F8`{4^59kp+ z)tsIB4ZVf`E)#nX`>ALAGkql~28bbIgcu_xh^b<_C=fQ*9)`>nrD8EGKT9*#_kPtY zFuqDui?~RD+C*9$hCSBnt&<u5jOY{>#U*h?ToZ$(=M978p8Otf6lk6HHpopq(Of1| z?H}SlXL;U^f6VLsUe-^@R+*G(c}O0S$K(llT6X?t#cbu?_Iw}fUX<76O?gi~luzWd zKEB&~?!Nj)z<*;#z|PR$E6fWl3=E*56pR`5MvG<CM2r??)U+aCZ-=S~#+Je?gRspc zmFLjUub@E)RY0Q3O+Z_5%JaQCcxD{D5K@|pg*mnovK(SrjnFPDO^V5>g9<Te<uK_r zRsk%NT{GfaCjm$4G^O*RF3;;Grp;BRSvVh~C6G!w0BxtC7C`iJl*O*^^Acl=Sd~Fp zAs(^9S{Jicre=+-IJJnuW#xb1Q0|0YCV!lU<yqiKb%YnAp)w0xN=LYg2J|W(+_;*8 zVUGB_Q$xWJx0);Rw;NGT-5m)T5k>`ce6({>2k81y7pQzJ0$M&6GlJ343L1#g<uogQ z_J}!S3&xqRHuu|ddE1xmAL=gEKi=`8;a1{h<L##V&FPlzo!zb7yEg5<*LHQ!oxOLH zUHd-m|JeSz<9X_I`WuQ=L!u$x!)S=N$4TQqD|)Egui$}o-;{2l(tTFC&$iwZTXBx9 z^KG4P@i{~*a7t^?m{?I0RJ4ds5{q3Naf<N~+_a4=xid-bNxO30lrht2w@lMa8HI+a z5V!vjcYYg3b?&*XcLr0$oF4MeE}ugR;0EfCn`$cGM35hUdpz17-5o;1aodbRFD6lG d6_uM*wU*X}sm!D`CN*qP)Uefp*wheL^c`^CT6q8f literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux2.6 b/bash-5.1/vendor/term/tests/data/linux2.6 new file mode 100644 index 0000000000000000000000000000000000000000..4560270ae73401e2fb7afe9744a1f1574a712097 GIT binary patch literal 1785 zcmbtVT})g>6h1Rc0Bb3fq^a$O2x%t~6?*U7dw1Dv<3f=_1VW<{(M{9R1^L@uuu$c1 z(WYtB2iu3H2|f@LYt+Pt)~2ROV~nC`lRo&|pY*}-;)5^fLwzt_zcY82O|dl+C!BA- z^UawvbI;5&yG0GvP!;7wB9tD<o|x8+k$FRE!5XJ)Q{&mm@$?{(z#q)CJjuI4_<lM0 zk8I`COw|}8l2k%FXgAf7qIxJUwNX2D(re(a(;#q!GBiUuFyB8(r|7I<=jejz7ioz; zqEG1xT{Zr7`ihq6rs0L9@6dhtKj*bo^uMf+|4M80fd0fsl!_<CcCk~`h&|#N?7abI zi-?G$=a$I#f%i{r#rQ$dBl<)?*r=Ek^XN}+m~}qyUlfbtlK4b?CO#KJ`hE$l*h<&E zEnuC->yf?dYB7>o@-h0uQNDllKgMmGSMZO?VVRXva#p@4&&c=X1^L1M%vi|0vHx(B zc|Vqy<u!Rjel35Lw>CL<<Jz0`!=Yft)1mr2`}Yh^C>AQC3JNFHh?=m~KwM2|HE<k) zGX&@eCtpI>3FAH=)Lx`Pd<SiT)B#IqFAcO)R33Q4@T?SgE3BocHL-RG)=k@hUIt(@ zXa;u}5M^e-WoGu*N0p!%1~(1RW?Y+qgvX0{>Am~4W$k+bqs_1`dKc&{01m*+9<<GF z;PbwcFEX?N>?n`eO$K9(+A`cw1`drd@fd=ys^HHz`{OS%q`N?PQKRr?4CyKmPGuC% zVh9S93Lk!%!cD9MM>0U+DA$)WT5;P_2@ai#M^&7u26Y4K6jc}03setO2Q&g|t9XXz z#njX`HCU<Q6z-rWkh`6pt9pKW!&8mBtb0dG`metE$I#mF7b8E7-WmHQeK+%M_J{F> ziIuljj;~A}nfm_3mv1k>^WF5dncruBn_Hc~om*P?3rXI9C8B(Ki720syMX_vD59yq zh6ip6r%esDDYQ0)cFdtTnqwRj@0fU-Zy#!byE%Z$BqLcsBEt8F&56a`814sG?eHNk z%`_KfPJ3QXJ*(zy%d&E6pRzP`=P|nbNFCX^=#DuWERl5AnQiW>ZDoi;cz4S1f+&7} zU=RP|c)S$#-HMA_jn`!t-m*Gs>7#aw`d+2pCTg>&&7oH;8td0IcFcx3G?vozH+cqF Awg3PC literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux2.6.26 b/bash-5.1/vendor/term/tests/data/linux2.6.26 new file mode 100644 index 0000000000000000000000000000000000000000..7b9db46710a79b30d0ae3249bd6a58351a1a5bdd GIT binary patch literal 1789 zcmbtVU2IfE6h1TCl!6ut36XYftjZ*y(B3=u-ra7NxW!uASQ-dQENlq0+tR<?ZKVZD z+pQX-@j-ncCiS5qQG+Hv2n0exhyk=p!h_EO;eqhN124z}JP<D5nY-IfOG{{&^nCN3 zZ_b>VduFy%CElP{se*DM5lZ)E4~^>DNUe@c7+#Ya%nlExyK9cr4c2s~x`_n-V5a3s z-W9%IM*f1Wj2dVS#)u@9&|0dZ*GbVvC@wWoGquvk;Jc|C*hd*UN;xp!|D3*{uMPW_ zj+uUnrs+reg-+6G<Da7obeXOgURe4X-GqNDuiZv}XLkH9-J=Ke2;WdDUJ|RtE23Jw zDK=p5n_;$yh&Xy~iF_Y;Ph%s--xu3OyXXMx7sFx#{g?A*eV6yY7gORVaYFnmeiK6a zehIADN@u+lV6Dd6E_cnU#Ykq!MfAB*zQ6xD<L1vR_?@y>X61++lb^}2<Tvt|{NV*N z7BbK8k1sLr&+>P9MxK{{$baP3CC;6{_EP<DD46kDXk(r|JA)I7g_cn{g_EjJ4cV$I zu7<SgItan(0knjZAE0Z6ai0%rF47>rg;qdnfhDw;2HGhq3%p)<Rtmfkwza6$v$g}) zMk|3{24FL22DcXwWoE!-X7<-kt3WdhZW^G?xHbU^j~DaO>$hmjs(S~c4X|zWDbSe& zybCjX&^Eh)&-+Tg$It|@qda2Q8;mh(%Wy*(I5fh<V+g*goIl^}kH5%}wgTZrjl!ET zWLtr7Dx+`~Lr|bpc<)XM*Rv8FNf(8qTwl&;#cfL^ICLZ)RdJ>o)D5UpR9#RnP(4r` z&<Lol;u)S7QzI)?_bL^qa0@L*?q+(sV$<r)>uM{l8~aN-P9J#KbFcSQ-@pCW1}>(r zXD(&`9-JJS`DEtc%<#UEzYd)}eEG<qqi2rZANzm&_QZd=>B+}PvImxk^64d_d_L|Z z{-2_Vrv4fpxG9`AHPoii+7#L`hvI0CaZJ2p;%&Zts0Hq37b=sCWC4i?-yb$77I$N~ zA6&J)JGeBXT$FL`c{%l#8n-RW%BebKY3R-(y1Sr`>|Aum91WI8y0gqSch$BsL?Jvo z%kY9Ietuwce{nosiu%5ci@OG|OC?p~ec9Sh%@(zPM7!##$)YBQKD20{L(@Q~4RdH9 GrRfQKSz2-c literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/linux3.0 b/bash-5.1/vendor/term/tests/data/linux3.0 new file mode 100644 index 0000000000000000000000000000000000000000..c61f69626120cfd1c7552c4b22c451369117bb85 GIT binary patch literal 1788 zcmbtVTWm~082)Frsk&bhaoGsMN!)wRoO5=&S+Q=_Mk@r3vT3NcwDzLfqO@B?hzC4~ zga?rzNIamaNJNBEBpy7w#DjS8-~|snh~xX`>~^Cr(U|oA=KH_-=bt(M%yuS=AWfk$ zlo7E&vMIg0-CkgJYBCLMTB4yP-H>c068MAZmL*wN2+u1b@3*ap7SlM45lJeb@idvH zlR>kgI8;hyR6!fSH&O$ziBhzWGGLx}hz`>+%}&rM-JhXzbb+qW4eHkZZMsXn^i=cQ z(l6-^{I^-{9s2kE;~(fFeW7poh(a-3j1?2a6fr~0!rte@ED;h>^xR_E-uHgRWf)%} zR*Py;3${bFica)L2FyB{^-qg4;-a`Lu8M0yNY5*P<y&FDHw>&od#hztznYI^7XO3( zbCl<8`Nz0{^K$-H*(lSpP41Tm<xzQDo|0$(Gh;6E!2bLo^InqIWskfg@5v|f*&yc* zTzjy7FyPOa8kn7Bf6rhCB7q?^l7exg$!NBW`l!*YjQSP`_I5ydFuoF91&sS_P+6Y( z@#QoOQaLQ9+$7MdqaxpHglE=)FM}<~YbC6$fvuuZKsN=j7!-rk2naLN;4ststESPQ zDF!DAP<mYHfSAjRxyhLem1!0)!sudHB^?0TU4W%9y$5Bn>-)T~_;Q9)fEDHut3+dj zQJI=+%D|x^CN6{jRU`TH_5S#aG+C7+yr@=qGn!Q92&d8tXVC-&steYvrC<pw{*lyE zFwFJkjAqm_jTncvMZ-pvsRDI;YUfo4)b&*tRQWUnY8lZK&x;ssql|{pMwEi(G!(hZ zXzrMKW9Ls?Fv)zqrJ%NZ+t=+M8*er}-|;eWKlv*4ApLk}S99O4zLvh$&25i%-`dl= z_hEa_zR&wVb-e3*kvZ4(9Z5F9VqreLSeVbp>B9e06j9e-!2{QYQ@Vyq7h35;+xk#! z#WA*yw{^V5w-2?z-K<At;-NGk7UKKEW=En<1owlhR<njn)6PZdP_COX<`^B8X_^_M z*f14z`wzPFTOHZC=(au@ED?A5nWgWlWu}M%cz1^21)0O|4~$=u{I8D33sK(@xVYo+ px=g}LHl35Mq$Sl<W>WQfsw$yUlS*w`XHue8QDUnFvnf%h=m*c)R{sD1 literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt b/bash-5.1/vendor/term/tests/data/rxvt new file mode 100644 index 0000000000000000000000000000000000000000..4d54c32496bcca1fd0b4b63f16fac412b8e32ede GIT binary patch literal 2285 zcmbtVTWDNW6y4{Z7~86eREo6|OCr5Btyt!sduJx&v`w3rlQzkOG||{<$Rv~JJTsX* zCQX7AQK*6yMGMs*K@mT+A4NoeD(HtlDu|#T{m>6T6huM62RN?1=O#Yu125U@th4tz zd(PSW-ke?P0PUq4DW|s86qgrEs|<~$iDGspm&`OyWEV2YQoh*OJluHiOfHpQYCKV% zFHL0k5h?t^<nhVo)OVBWr!BOTDu3~8p(FG&{6rSj&<@%~w_zvyp$$<N#i@r*fDh6A zz){JN5}c-4%2P@Bn&26FgdPKXf}W)F7+;{5=_0)*vA5`b8NZ?LF#aICQuzrZsY;~= zwpG=u9V(!j)a~j{<*KM^Rh{a%>PKt{cApwi<7!H!!SiZfEn@upr>xGXN1=L3J*Qs8 z`05{4yskbG&vjOvb&J(t?Y5e%lvSxr!K%-Um9^%q1*<HcHQ>d~7%MLQZpNNBt;_Je z{U<-iuKv6W{d?Ajo2x#yu2`SR>~r9kzW?jZc%|~K^`k|)R$s5T>z#VH-lO;HpbqPU zx=qJ*pB~gF^{AfI8C}%NdR;%H&+2pfY5lBzUcaPY(U<fa`s(}nZRGO5)NQPJM}MF{ z(pU7S|8d>M`u{V2;s54W`g@;QHMKR@(hU?iWzX0J$4<rUg0WLYINT{fJaEb!!+0FV zqp!OAS6W>Vr)_Y>VXY>V!N(+I8bdqmD6E(2fT1kF0Yo71A}sJ2BJ3CNvQ!VAWiZD? zl?k+9;$_$)8Uqm`p=kzoBUL7F2&2QZB9>PdWBaWURyi>@=EcGpKg|)SdSsXGI%pfL zWdvXxo;rd)H{ubQ;|UK5Mg&^~ql_lVC~jHPfmxVcqUSOsVPi0q<1hsdfl0}GHwbS- zJiI+2JsX6RiHGwD;Uw6qoGT<Jlau1$I6fCH4&^^of-|%_!C(+|LEq2_F0|j{6q>|c z<?RLSR=W_kOEJfeF*TrGl{$98wO28ZROcRO$c|-M7PU)t_C&oMqd=UtQXsJeE5jCG zbFg_D9Ze=DC#R-nXVd9SCY#OW^7%qxZmw9IpD&db78VzmmX?>x<&~Awr&m|k*4DYA zCn?a}7T6aA<pv~pi_$Z9514eRg;|8bFr;8%CLxA#n30wm5gTcdk!~4jsgaht)uhr+ zSM+XGFTZ0v&gD2Gj7HEE^aMkK5kYymoG5b>6qHp)^hWeX^d>A((HqgbqI4y{D|)x8 zclj+b9;3sbC)$RuH#Gnn&H?bw8$KwT8;yBU{${vRuDm}y^EOyBUcKfZZaAV_=^$yP z@SmUP8uY(T?xO8<vwtTwP!rf*x`Tq`QIrl-yWE2PG)Tj^1xJxXQ!UzEM>k<r1MbUa zIsolmxJkQkUk*U`0FBW!<#0c)(1Y|aou$WdD?URPcz;|1IUPQh1b;A6jut+tlrthH zmqLLhq_;c^vtP;>Vm}`opIm}%8CHTV!iscsn1%<b)1`Drdx#+n=wrjIv#$dIpeI=M zKmbpK((yzuqCiA}hyoD>BHGRAx;b4>*C1%$u#fQc58ML}5PYDU{X_k1AW1{%F$ad! H<A#0#?#pC8 literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-16color b/bash-5.1/vendor/term/tests/data/rxvt-16color new file mode 100644 index 0000000000000000000000000000000000000000..349701aae64486d6f36c9e83d5bda049ebeca87d GIT binary patch literal 2497 zcmcImO>9(E6h8Oe7R8@JYEWbdDTHe)1e|x@n>U>dP=SI2^k-5FsbHE;JN;v3`ZJyW zF&!4f#6(?aG=_z4Of<%YvLMD_VldH#8#OT|x*$du#^^>9U8sxkJLkRDA3)vk((~Q# zob#Rg?z`u{>D!|A(gU=Srqq_k^3p<Oj~k3k7pKcB?6fRSRwi29phZG+Eyc;gXiIK# zsWMtF5h?t^<ci3e8-+<_>2}&o^&4CpQQm?KkwXo%iMG%VtYjA=2|7v{>Y_)%PtxPS zAy~bh7o4E8G))!ZHNgw?Bs~N696e7LF}_M~&?S0Xa_`e8GX6xrVEk2hz5Y8!QuTTR zY`xl`HmR7}u3FU|<*AhFP)F1Wl|}9(>@hW{M%1_}fKRJAwSe*8uVr;XJq^_h>SgsB z#<%`a@s9dZB6m7X&i&3-XPdL#$vgG>I4ry-osu)_%sa~xsR1vo<ydj~Zyrb9b*>`z z!F6%Y-Te9p`j4H@)~dd6t~uX`_bu>;DE{MGzFz;?`OP7{PT!@Q^=7?I@6@|=TnBoe zKBP0cNB8T~dPtAyqAu$teO^DIpVH6j7xhc}75%z?Q(x9s^v&1v*UZ)bsavi2P=BgF z*VpvdYjxl2zJ}H8tsSpK_j#}3yNES6-rIN^-A%DGX41^KCZ9Gl*5u0wc;kRf?2J8* z@dS*=NcG5{G%U!_9SCJ$9X3(K%Oqq1!(rG#ST{8R6D5EPNJ8KzS>Q7yIWFLrXajhO z!5$Y?G1d;pFLFdQ79wO46AT>2RK?hSj4pd+l!wJwen*m3ZrV%x>7W=*^DtChvP$nf z=pk79Ai%opx`Gk65)ql}3r`3p1=|Hvj5f|FVX5ha7jQ`QybU?nFbvyqfMWZ>WXro( z2`@t;ygVUYtAr<$2+t#gC&5zXxf1eZ@}zihJU(w+2Fm}~37(<DjmP8I7xWE{;Ej%Y zoJW(mtGv9p=`b^asia+#W@<tGkh*5ZGb`|uq3?qxOuEFfl&LhC(G4a|u?(%JSnnci z88#1_h0W2>P%bw%Ha>p#Y@tvrmP%7o)6+9Ev$N&$++3wHKfkcBxVW^mynOClwYsuW ztDWZ^Jx#H;L$L?rpxl67UZV8O+X*IJYG;;Yunc)vz$C#i0<+RmD`G1xveGRpEw$28 zFPv1`>51M8^>QEU^IWbw$Y=#UL0>Q-m=u)5<))b1xS&*7(Oc15(c3_>qPL>=MCr-= zp6I<$@9`<IKBLR8C)$R$H{S;uOaXA_Ek7ummrDDo67j*Qw%5!<rW(}DE>rbtW;ZJH ztBI1y=FqtDoT<7sv)@#FGb$d0@Pf$m#d9MMQz7StULLK#{yr$U75Cv^6)YboEqtzh zrXtjf<9=8V!mWL+pxBqvjg+lzoE2d;Ww|I+w&7K5i{n2&(R~!BukZ!IUjU7GADXBc zv8}WnUje(3^C?9K=&*bVWT~G9@Fg&WI!)_v<eTUoQSYEO+8b#*={RNS6m-KhMg@E& z%n@FUGhuVNpZJmJ<sS+;2JIY?W0aJR%K-uFl{3v=z;QV~3668a@l(^wwgjud7GPyM zI6wpabi|`V=ivlH0O(<ZcciB?L<BRv-QYm*V=O(!(ypWZpgjW-B9iSpg$NM5?-<8V RX4yb;mI}iz40ju`^apF}kS72D literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-256color b/bash-5.1/vendor/term/tests/data/rxvt-256color new file mode 100644 index 0000000000000000000000000000000000000000..355cb6e110cfb110dd03de15544d29e72bd39f59 GIT binary patch literal 2427 zcmbVOO>9(E6h8Oe5yhX9V2H>NQV3Tore)rJ@6C?`RG{Ec+D?OoREnfO(@tS#I@6iy zAMId5OiaXuMnhca#zbRWC<|hYZZOe>F%c7Dq6=bl;X*f>=t5nL-#If=MZv$9p6`D5 zobTLs-#z!v?IyL8?xS@yqppU^i}Te^8$>6H`C@s6d+oL>)|F^qI8~i)U#w1+3+)JZ zO1wg(@CTEpNt)eNH#CEE8*QZe4IWbUC+c+~heEW0HqkcBWCxT19i$ZX(WBr;=>%|8 z@-u?dbef7(6<!lOM^Di+V9(L>^dj0<=?%I_Z%gcbx+3il^b^{jh1cu9qQ%?mA=p~A zPHj+OwN>4(I+dpqs#_gUht(irM`4etlWIa`RSvwUDrz3>-#<(0oH`HH3+iR{8rrx1 zl<|)GLOgdkZO*;UW@n4D)yX*ZdKT7rPB{f<)|qpb#8U%aT#d2f(se!dyysko?}NYi zId=2sBj`VIuC8W%?p$-emfknO@0$MaSL5~ikIpX+={5RJy<TtBTl99lLq~K}@6!8p zN)PBEeO!;~DV^74y{OOXC-u|%S$#pjq+ijm>o@f!{jR?GeEt}@{4aH_oDcP<`ZIk^ ze}%kn|6^`zjQ`uFLXFJ6(D^3&ICLd+E8Rum5p&9vT$4$fk~Nt!99|ZX3Xj-cw1;8b zHdT-OP8$g+x*e_*tlI{893>&sX!gVQ!uqKV7!&|5AO?XSV}Z{QW50l3z%dVx6c}u; zsPf@BI)0u#qOlMm5==9&8$;#8yV1JbD<i#;jOlmBSmh?Yq@RrDo5MT|RiDh#I}5rG z7C#BFE_YqQCb!}dnd=J=1Y?46!33j?Fp67pdeDoqOZ2=9W3X`;mSYcvcZ122_qPa7 zLp(e^A$={vgNcX75yFFDs`6cde3^VHJ{+IV3zvfOA69}#=yoHK2-XF4Lm_yfn>Eg$ zNL*E(Uc_{pQq)wFu1PYrpnik8rsSCw^ka>_4;q+cfn^C(Z8MYWOp?MWT1(;d0&EF3 z2b+aeXmoUJY-%c-J$*Wt%jXM)nVDj-RGOVFmn)TOb#88ceqmv8acSwyndRk`m0ImA zujp|KckBy45CP=^q<M-`GjBVXR4L9Z#$XvTuqcy&VFG5Qq*laMN@S&4R!VB6q+VlC zDW@lTuc4RsSf9so-II(~&=d3p1HqV}Y%Vv!+(rZ?%ZlEL-iqEvB`SI=dQX&|jPHrw zYv?`RCDvzj`FNsiIK7!8pwSrs_Ppf}W%CkAKY=szxSy2GlPqV)AL24D+aRc!9cGz# zLCx$mw#yFh<dWVj;@>zDK7rTBPDb5bvmCFPU8d^E+svf6+^F~xt$3%&m`N|53>tI7 zp1}~jZC2C$8>G9DmO%3T>+?HshB_jAR}<Ys5&9BWKi}QAU?;cHdiXZeR@~nYBIZ+q z_RxO0!v|@IhH;0FB2UvAY}PiqTh!aAgSwj99_q#a3CExtrzy(eey<R=^hl#DTnQZS zG#_y(V4OX&0b)`sDJ@u9b|d$q?3cm^?B`P9M<UI(2&=;8VP)DoOv6KTz@uEx{(vD0 z7+^#1z(7v};Y_9b!GYk1SbB)1eFuj?2Zoyn&)|_`@BqP&9Af{`K{k*vOSy3uhPO>v F`VHi8e6|1p literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-88color b/bash-5.1/vendor/term/tests/data/rxvt-88color new file mode 100644 index 0000000000000000000000000000000000000000..91ae94737b89bcee33dc382ffb63606b5b5713c3 GIT binary patch literal 2425 zcmbVOOKe+36utAt6v`)+iYiK7RcY0MP?Xef-h2Mww&^D=ZkohVNh{NoDj(<5+Kv<3 zNt`C`qC!HVEI=UC1#FN&hy`>}Aq1Nu!2%&sqzVZZ6@mo|*nk8JU}4U^wgZKh-&5|H zGk4CNH*fA8Pd2GedVto^jJg&oRTnCq@%VT#Uo5R~r`>kNx)SY+rz_L#)yhPv&>oL> z%5a%T;SVNHlQg@lZfFMS4%$fdn>-oXyQN+yawtR_XcKM2I(9%A&>>1uA3X+sj7|ba zBt9!RO=qY`72!3(^Yj!w1NIy}PZ!a?N^j65dRxZcr>oNbKtG}VS$MtvD_T<ZdI+{w zty3FRSZ!4gs!rvpgz8oY)e$v_v172u)hRWurc@5RsLE;q?cYC3>b$xD)eGun^%~l@ z{uJ?!`a(Q+Ic?7U&Sqzev(?Eu_4*X7@tk%F&YUyvEQzNEytF#Tipw|j*z=xq1-=jd z;^(njKOaH=iF0i=>T~D1^R@K80e;u?f4@3jum9-$;*egW@7C+}M!iLE*E@7XNA)hf zU#Ikd9?~cDh@RAWUD8#3PCu!i*3aq}^-KB{{kncrU)JyHTd(JjBUk>Vt`+m4{#1Xa zuj{W6_w9d-ZO!q2+f=9#*%!LdWFLpFhHj^OC_HRVn_1UnlV;YMYzYo;3Xlp9+g`Ls zVB9uUkN!>@0V%o@t`w}>26-GMA=79M!1lrVsSOwu04^W~fgfXm&k$q3fM38N4-Xd@ zY_F*D;W#>eo;{+m5Md;kW?(m_%7=HOb-7nUcq16g?~bv`O?pW`8O=AR*$Y*ltkOFN zx*rxl1+Xr6UBM=|;t`qa3l9Wif^oqFqm3|%TVi_9i?U1fybYtUF&MUE4~2Jw$(HxG z2rolCygVU&Ey9zDhvyN(lVGXxU4eX=d?`L0pU)eYg7P1Bf@kP<BasO91$jdvc%z#+ z<iRbF1ibeq|zsU%&KWNJbE26fG>XI9XUHTphiV3GxvB}}EwOsq3W3a4l-h0}|$ zCD=S{4pyd-k<rn~$*HL`XL7lGzEGH%DHdmE=jKYKa=B8OpI=y5T&z}?md>7CUS3(L z)z0ybo}h5Y{_sN)P)<Oamnb>&wu4EQ;>=<UmLUs^G6@*QVOCOVMQkNSR<dO!rB+hv zH71pGdZPCldU=oac`nyI#b^aRL0>Qsj0s9{xe4YrA}CQ-^j7p%^foG^qPL>=MCr-= zp6I=X-s38<KBLRW6KTWg%^n4f&HzyJmOqruOC<dS&dd{jQi>;8ni_kA)3|Jdpk{WM zWv+sn*=cN-&Ftiq-fG0Z`AGOAUL%!^yt`&OUNgH)#gn(0330hm@g-X0ohEB0ym&Hb ztO+%PDY$G_!~L6tyOEYa;{6-rJ8*_NB79d9-A57n5?4Rp-M68V+h{#}n`tZV?}stw zQ-b!;0lC8mX^1ko!$%OOX$^|CjqVloHtL|RrnZNA@qfZ`=*DQ0a=72igpwX^q=hqq z<DKRsE(wgYM+zV&xsud^rKK9V7iGUBK43qm3O^EQwkoUwTY!~lUxqS6bkL(*&w+p; z3K(ER@8CdB1K~`i`@w<Whgo`<rG1BnKnF5SglF*Rad?2>M-Q|A*dQCosHNPP3&Y#S GE&T>(p?i@4 literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-basic b/bash-5.1/vendor/term/tests/data/rxvt-basic new file mode 100644 index 0000000000000000000000000000000000000000..05474636f9193deb9d38651e5a114bbf48f0b8fe GIT binary patch literal 2145 zcmbtVU1%It6h3#ZtyVEbrBpf!X>~MFsxx<Hb`zE~O_RtbO|og4Cb6+;HrXWIW_PpM z-TXCap&;r@eG!G?L;F%u5nn_U!Iy%H3L=6JKJ`g_=!5h{LDBI$XEwoF>JJWkzWbf; ze)sOZ_uOIjD3=~1O(pe>uB<NC_D^N2`RNU&jkTFdF<;6S8llZJHjOoo=1aMSmByoM z)!Iz4nMmP>kf%<z(z;A)knW-fDT;_Jx`TGn9@>Y0jPN``DQcq*N+au~Bfw*#KPz~G zPEwBY!YhI+v_a>=UZ9ugWwfu;WqO0&k-iV;6KQ{->u7%z9z{3M{)G4?&S{&vN8P7( ztB2Jis#!g)LX}bnRTOn2deneAsz%i~_(?UbX3_rrlUEhB4%hSQf_e?@rN4}LQ++PV zufX4xvb43`>an7z4-r2D){r$~9k(V#nF7AL)yIyDH)X6`wyr>X>lU5+ZvVUs|9jSl zTcbX<u3Dc-_9gJ^y8i7}e-wRZU9-Nou3I;(pRM04t#|01dY88KUj4Y<uYKLB+jX}- ztdHnXeL_#`yk5{tdR?E_FX{{W6@5`((zjpFpL?$SOW)?0xApt_BYpKhj@lgk|JqM) z`PVP>SNcx6m+WyT@02|!mvYL+$yFfubAYrxZhFxkMsRzRD@}K^1<`K80^SoLr_gjF zIuQNT01S%&50Hc*NU|YdNU|;v6lo{8TVyo7Vk_7!NP+?@Vlr@{Cp^W#GUh7SZD>8t zD)x9W9*jk|C)wqt{8W%i6zbC)gsV@M>7N5VglL%ncpj%l&@;?EF?fOSP%tUjBG}4k zTt<;)Oc$~QOXBAf$Ref?IEe#fw}HtK_iqwjfGE5$A$^;KCliI|5yF#TVX~u8_9T16 zma%a@vNW9ka0Wa>yXU$tP6Q=G4RFLst|G6=b=sYB!l|V^C&ko&1~K)VvhQplPsVuw z8ak;W+ghDkgEO<!Ns*nV9b{)#5Nn7f#3G_flatx(?Cjj!>C^M`g+j4dDlIIO%ZrPZ zO0`<6EiElCudJ-DuC1Lpv%bEuarW#vKE~r@HyyH@T~I#t3@=ei<Ua}~rD<W7WH1al zM1o1kFpV%$M<Zq<bum&RBXu-VM?aoaYUqpKkNxsLCg8a|Z-UVX`htOAD3}zC?@}vs z;|j_sBYq=(BYu;RUhy08`{MLveqa24?DzR<n1IpacM$I%UeVkTXrctb6*s(54jfPu zu2hqYFBQ>la_JgAaQx-kh7vc>{m>qwz4&@PiN1hZ=>T=&>(xhtG)!ak98F@JrtPR= z13e(_ebhux)xBNR3+D)YQ#4ESv_Mrtt;gf_@)B{`GkoD?XDzJA$s}bHvS+Z2l!>zh z>vAF?>%0fNG8v9lL=CZws8GikjSW+`PxD=!AwvQ%z=5oLpesg*=}bR35WI)2J#6iJ jW*Br}td39yhen_P!H0TSKQ_n#k~K6x<stBI(}w;44)-)| literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-color b/bash-5.1/vendor/term/tests/data/rxvt-color new file mode 100644 index 0000000000000000000000000000000000000000..8cf3cd9d92123b0d5507de4478318704892e89d7 GIT binary patch literal 2229 zcmbtVTWDNG82;x>tZmf<D#hAUN>X|>tyK2RIlG%>ZPVsbH))bx(xk>lLN?i4_nO_! zW!oeVMG({nMG+tDi=c=P+J_>dFBSB`7ZpU%ha&pmgMuh1czHN}|G%4ftrtA(|IIhw zd^0;U{|vKV`E(bxP(kf(DzB|nk4+bI#qv7S*6K_-zfef$T4(ahxpcKyZfzfHePE%G zDXzAjtyQWs`6EOMKZJY@vR!S+q*An#_EGQ`-%dISoyejl+DrTC5N2}}N|;Vlf(Ga; z_$WODoJ0gcMsS`MsYq4f8-kbU5qcc#NqUN&Mfn1~OjqbNX?u&_m-1Ws9_5e1gWzYB zq=KLcu}ih6y~<W?>TY#Rc`BwlRj)duQfM1RJg6qrw3<^{@S>`y6_kJf)zl^R7+g=Q z%j!jxul}LO>*^CxZn2uJJFNrOL95NmSV1s{sDBGq-deJjt(qtsz$@Er?6~^78Y^#F z*Py-qC!O1F{JjhRd)9~By*{?CTc1nq3*c7`{hRIfAo$Mu$s)Z&->UcMefpq2tdHuD zj_CVzmrm#*J)+O+Nj<A`x~$jqrhZsIs-Mu$=;!qF`X&8}zN+8QH=fULTdw^}-&UV@ z^auJQeO-U{ANy_f|3BrIjsN^w|IlDo(~hQ_={B;*odu`lI+?grGESxp!J7jl>~YhN z@(hB@hU@-cX}v>&c0)=aI!!o-t0ZI|MK|IUVvw4F;XJ?vL}BowZ15SPtPA*gTy=Xq z&tUq+m9slg@pG(*$H0V^@H_*{7%FEUN9l5{jPCW$n0{xJU2fcq`|(JwG0aK024t4r zCTJI;V*+4YuDXH^ZbT8A>kAJHMg=<rV~i%mD6;hFK`p|P_<0-Bh$#fN;{@5q!DPz^ zw+K%|6rP@tfi1#=iNfOu;XyD}SyxzACM(6lv3%aR1f2h{6Ffqv8w!Q6FUT7b!5iJk zaRy1^tn&0iPN!3fIMul8#F-jUzfN7J<T>l8N9%PTH0;FlY>PS7W@o0wiIbh6U1TR$ z5jDgzVhK^9$;otjc6M%VaWR|C<?{JLp;#=HmX^xpN~Ky|US3&QU0qwN)h=APcyWDw zV`Gzd^gP+^UG|X>C?_DvQ<R)}hruLE9n7K(h9QH9FbOkEBaEcfh}lSrjAYA5N{yt{ zs}Cya^u+Jg{qjG?=doOOg3$<ig1%r_Fe)gA%Z)KNAwlV7#BaoJ#BU<fDt;q=Pn@2N z?}^{5`#nA-#%FZ-dLnJOy_sRqNCAK|Z+M{`UM%j%_|EW7d2)WZ=5Mif9KH4sUO1vV zC`6y)z2q0~Cgi`F_CPy8ZFu$WL7Pu8Izip?@}+2m#_;k@qMxQ6NO3dWF789rPWLvv zJ=9MrItSkr%~BSxVuf%J#_NmW`QuU~`C`bjJ6Mrzi^>XRL%@=fL#{<wm+cC(&I`oV zN^-0rs)!XtnNE$-*a-D{l<nybGeiJG9H{jU_0$n!A~^^S1n*;OA6o}bkAM!1H4sW_ a_#6}<_;4TVqbUxMw4v;ji@?848~O#b!%Xe~ literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-cygwin b/bash-5.1/vendor/term/tests/data/rxvt-cygwin new file mode 100644 index 0000000000000000000000000000000000000000..b122aa53304a104c3ca03acd98f6a3a98b23162b GIT binary patch literal 2251 zcmbtVOKe+36utAtKwBWGfbyv$<U~A3DXIMCJ=-x>>$Lgcr1>dLN+2lY<1{~i636*L zl0`NkfshbgR0t$Cbb$~pAEAmxp^$F6pbIu_5vl}>E?_}{N(H2vbFZE7Eg$jZd*;lU zGvk@LGn(xxPWMweWz-$M+`?SGW_WRQemt|pJdhvBrN=XaslZ5jHZ_>f<^t8dfk($P z$?SaKz~W4PB)ub$%>;^Fh!lPZ`ATG?T9V=Eq)l`;75?JeM0L=KEb`Gd+D=uN*@I9* z)I<qtr32tS^aOAKQ79w@$7q7Glo!4%xJu8^^I$L1OLPR~>+}X4r}w4p6rGjwGF?IW zqwqrEXOyH01s`IwDp%W-Usb9HRE=^~RK-=J+OIm%)`NIV^{ZhuswTm+YDUeW{QGZF zt*YnXI;>t*M^PU8Lyr^cyeKzYW!61bg>|o0X(g>fVH8pP#;vq9ZOvMXqAUYH*l1(N z$=}sjIc=SR_UWH=ZoB^X8T{w0FE)C8X<f3uk=nPwD<%D>jrKy}n&s15^j3YRuFzGw zTJO@HepuJ(Cf%yLbg%B$Nj;&b^qgMOtNK~}f<CNY*01TK`c3_gKA}(QHGTd0{I=!H zzx1v5Ijb+|i~5rO`akwt@Be?wA4>muRa?H|IJfw=`fj3I$=_#>+f$C6jM-DhPUaxE zqkx3J&$OW2kKnT8dgNDH?2w=>kP?Wv38iqAgp8r6N9;wkQ5i6l1~`BS3|@o{9z%q6 z0WXbf@9#@9m=<xR{I#ffDOSW|U_wi1jDckgmGbXK>2NKF?#0fSemuf1C+5bySU6Q0 zrVg%FnWeh|x(`v?4=@f_9l;VeqKM7$gogwpg0+HCMiXQdS^6}f7G_EOybXhhAq2K# z5BYb4$(FaR6P|`BJUt<;>x2grg~t)XgJ7z%u8^!uR*HpV`MhxnIR9ZMc!anU3<j|; z$Qu&D8(qqA5=r8$^7Mjs+@1>C`IuwJm>N*8NF961wU<zj6zd*n$d0Ai7Pa$b_DH!M zBY%Q6lfPpgv51&OOe1D!=dp+0s_74YKHwXC`_R?V%VWnU&QE@rx{&@Tb2_^+wKlz$ zTbp?@|H<robEoD%UU+x$`=`Ep`m3dL%df0l!^9pZfAv29jvy$fqJt+Z*>mp$lYG@O zi!d05BqGct#4wC7l3XKZBgrz7HzUb4l3ceqs3g`EzgzUn{}_+Qa-4ofBj^fxf+4|( zpd2$N%G?A6rI!)E5x)_?2}`T^jrd)0x-z~iez)j%`Mem9(cz1V1mYeiyFkMk08YQ* zg>tyjm>1>S!#m~5N#dHf&Z=<;tAlv!i0+~wUBuJLZ{H0#31xH}v<j-k`?nKq9z|&n z)yo^$N!`?oH*f&`G~I|~m(lIwuA*w%Rq{4a3*Om-@D0%+n#B7!LpTzB#l`UaaXmWt zipa8SS&?mv$O>gcz&a#{Tnn=<+ZAG+7l=#N!LfkIBjyk}+S^OL-PGvPWJ7(3Aq;5e zK&`R8p@<L@9c|!1@Mg9)v$eIU8??Q*git!W4nhHfcQv!#)5!rcXlQcCLEztp4gCU= CQ(b5P literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-cygwin-native b/bash-5.1/vendor/term/tests/data/rxvt-cygwin-native new file mode 100644 index 0000000000000000000000000000000000000000..2350014d89e1535165ea963736152c6c57c99d02 GIT binary patch literal 2269 zcmbtVTWnNC82;zXss-aVL5a!|vn3uZLd~8zXK&d+xwN<~ZMSI)R!b^vx3o+5QnuS0 z7GikN2YK=Gz>7Yq4?IYXhVVe5Kuvhi7+(xXj3$N$eJ}x{!Dw8+|3BM$#Y;Tt|IIhw zd^0;U|4e6{>ZOfTPervRP@bEqG>y!U&E|?t#i2@WW^{q2aAmYy$Q6h3;nBi$eyCC^ zha3IoaA$A$iCi&Tnhp2PPgO<>;mK0DvMF3DhW%lP6#fwM)yPV<Cd1QBb@TvL|Kh8o z?a+xV3eZ|wM;kEPN1;S%H>IhAdcpV7e&7K_wVD+ir$bbtitwX?$LV=G0rn!jOeayk zL8oYu&PdyN`dG^A^c~6{gjcISq9j$V1`w-My;`e6szE)Xnv|=Os#&$FJ*pdRdl65n zK{cYr)C71*O{p1_fB(&^<LU*tUQw^AH&LGcLyxoSiYRwmLF++lz4egQU}ddpbqwKu zIjdkDwx+FlQH}!7uC%e^-0y0vT(mAh`|wXXx845x1pZI0t1G>}w60m-NbOtT&6<8| zrM+7H$+C2v4(j{#Ivv&<^%iY(LT}S8x?OkceR{th*5kUUEBc6jRzIgt=$G_K{hEGV zpVEu^j6SC?=-bcdw=I|crEj^<NBXk<Twl{)|HppI{r^vSqxPHMYYO<|tPTVNchNl* z8nAQrq+@4O_N1}1WeDyVARQVo?I`ykxU9Jz|CRb3(zF^<8qsW`d0ZtS<0y6^b|5+_ z2#gj04j>ML7iWXV5NBP$E8t&2XrRDg+QpR*B~bD5tcb_JgqG+y1IrjHAKHr2;aVBp z{mz(vbDUjH%1wExSiUyQcDOoZmhLgooruIBz&KoW1Z&)gA~wep9u<rWCIpj=Cc-GP z^l3pY#*+AX8-@_W2yDkT3T*|GE$>_=JPlEJdO|vu2@fU;k0XQ!!Bk~kQCXR+6br}l zdE?S>{=-i22+d9;62ZP8Z%71hbS=kOB#E=i(~H>6_GHYiq#QfN)PQ<Eb?iykUO+wW z*FDgvohq;`X;*^wXuX}HP?}azC^L(gM@%CQBc^Ec=`C+H4MwgW2n@Y_@YdM%@x?<| zCf>_`R(QYoLFw4!(&44@($v$Hi_`DUoS(fg_s;yyBR8J;YT@#+pE0ecDAc$!v?&70 ziOBF&C3o(_V3Mr_vp9oc$Rc7)q6{MlBdIlFHj*kMSu>JaBdK-$K_#uO_+8&GzhgWe z%W(!7ji4*&2}T9uf^x{5By$rHlwL;sM*K$nCMK=oH{y52>B{)7_+8)c@@X+1qr=w} z>BB9~_JGEU0Gxfp3*~T=DKE))hj+@AbHp`onKj}FHb(H$5#3J_`T`FpzkGM#90X|% zwDr`0*Kaf0JWA3w+9fYwH}z3JUcdwBr|C|lI!O15djmDnV>NFJwd0lD2j4IqqzSx^ zQ-lLC;4g;fkIRwa3nI%-up-+Qmleu}fMq0yT#K<T+ZAP<7l<pC;g~~I5HpA}?dYfe zK5BJoqGeZ<AqME;K&`c_#Yc$gOeZ)Hyp64GZ0*?H2inzNLnz%n`=9{9d)ipv+sy$o OWN2d8LEzU$4E+M};bU_E literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/rxvt-xpm b/bash-5.1/vendor/term/tests/data/rxvt-xpm new file mode 100644 index 0000000000000000000000000000000000000000..e0c77fdc0fdcaa7ac3b8fdf4ce560fc1e5e644c4 GIT binary patch literal 2227 zcmbtVTWDNG82;x>jBV8fD#hAUN>X|>tyK2RIlG%>ZPVsbH))bx(xk>lLN?i4_nO^J zvfCzkD1x9qD2n)CUj#*b&^{CqeW{=izNjFAJ`}MJeNYeu1uqZl_y4<z*LuOj{@;A_ z%{Q|%^UpB*l%ad5m2zrVQ?asIK3XYc*O|1HXN%dzTr$%(n_bBy%lTqk$9UUAi@8*O zt?f*;RG!TqCQ|qz<ZF=aYC|TKpdGZAYJc(VpcBxEENY@Xw2uyAE=QmQ=@i9ikj{XQ z(IdbqM6H$*T%aY&Q(5?i;6-|jo&<ZEo}uSazC^FmWqL!}-k}er{Fc5)`J?b!?Prvv zYPBZBPSvXRC|k9wd(~0psfg-Qed@GIpluBCu$ojeYF?$m^Qxp)QU3i`RTtG0a6PLo zsh3f{{)ZlKs?S8Z&1$jkw)R^GtadA9)oSyI`nPChtz~P)s*17!yu97Ujw`>bvGTTc z723Oh(z)&C-}~@?V12yZ>r?BRbzN#VfL}HAZ?@ZOwePH-EYi*TcD-Bg)d%z;eMARz zNI#&vbxaTIQGHHN={cRzMP1RG`ceJ3eo8;5U(he=SM+Q8ihfJqd_KQzx%w}CTYcWs zAL&o@HT}hZ?6=kb|CC=g{_|`7LxWjO%}uw`9b`{9i%!9HQc<U1oKz8lHxG!}6J`MA zX#|%I*Mq;(dWRV8f)qn^nP3K2Nyq|<9>ht+5VZh<S%3=&!{CS6;4_3-7x1&V==MaG z!3>BiV|SwBXIK%Bfe9_a1qPNeRK`Ar(&bta-Rqq({jM;(+^84zqoGV=m=kaf$}GK2 z&~8NMB*3^_bp;#Th$1%E7akN03w8=d7)^jtWa-n3T8Jg_^EM<A(+F(Gak7tr$(9do z5uS!9JUt<UTZ9J_g~t)XgJ7z%uAr<;R*HpV`Mhy4IR9ZMc!VxD5C~vjkT)cPH@cDI z6q3YQ<>>{SE~gN3%2C&eGBu!now`oJbJkH0*XurL(1~W*7IDfg&TOj_B|Ant$&Rlf zs)!ZDGNMFNQ_1Aq-2D8~QaYW<WV5+kK3^y-FBglYQn|dcvbwsqR;g60=g(ibu)e;r zvB^7nj_i(Z`)~l16A<SqO3u7PV3MUyW?=@ykV1r*1Q})!MpA0TY$QcSvSlQtMpEk4 z2bFYs;`i!)`5)u+Sgt$CXaqe$Uoa>b7L>!~Mwpv`p!720H{v(qHz8>izY)JDPEW@7 z#P8Mp9-k89GrD{|kv81k)Cg!O2f&#(yig7=67?f|XLzSPIX_(Uw^#>`UPk~g9MN4A zpwIDM@{4y1^4~(cq3x%3yn6Sc&8G+*ryhCv5;RKVc=@K#Pg65e+(LJX`yh4D{S9v~ z4N!v4!Z%HGl*X%AA{>N?`eJzgxD;`|7_#h6R%F}4vO?Jqu(;%qYa!NUyMnCq0&%tC z92G<vv5F|t$#EJVr9O|+y*)vO5MY=CwZ7rrIzo)ahrog0{cP=L>)@$T(Bbh0LP?CA Zg#rX0>1TZ`!2yyql%94G__rBDzW~efOd<dP literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/screen b/bash-5.1/vendor/term/tests/data/screen new file mode 100644 index 0000000000000000000000000000000000000000..895f0f679d490cf5c2f23eb5a8f1df3eb46caa2a GIT binary patch literal 1587 zcmchXJ4};N6vzL!5CMarBqYig6=S|A^7>w-)GBWx3Z*Ductk^a^g$n#w!F$?(8a|? z6OGZZxVktwnK(EY7Y7F?2L}fy6BFWK;^#T{D+YoS8o%`X&+nXj?mfM?UvHH-hguv) zRODQlsr1ZDa_#z1wXSK6?frw7t4GX+CaZcen$9i+<JH-jbRwDz#sMKe><FYX?S7m= z44@cCVgKPNMjL+GKp_rL%`u#SiW*s2j}{v1LN7&rjFR5K1VWgVqe-N&fE@8{+>x2P zxQB;CPq2xn<e%X=Uf`u1v+Y-T|C;=pJijIXF3-089v|=#pYR!9@D*G5L7OTPrNXw4 zkX4E*agsbgr^Ol3m}e)mTRk*(UUZ5+F-&w*ghh({%AOgwWad8U1Mx^a7MtQ5@z$O? zXZ7!tZ+7kMbYWM-Bb|FPJL~@)_qh81Q>USQ_8HyhyuUf4$$Za{E9Fwg$54brP{!4$ zn$p#2pPDk%=`<zGFiDRxeuZ2w8T(yDJvhh}WUYofPJauUV?|^XA?}3Ym#H}E0GS_U zr0xWX&eE!DmX|9Hjw~h*lPSXl%83&!vXED?SPVICSX4#dutuX)pVNE;N}z*`n;AMs zSIMrC4N^vTQ)XQENNtwtWi>R(5=jDGlxyOM>jSilKsyDkdR%FdKB8QN(oHDOi+f4% zZv%Y;C)2hKecQlG%VJv90a|)WZcx+W<PA5SLNgQ(A1$w_sjX_NNzM9n)yJq4nhqL- zmV+jt$3ctG?Vy{`P<;uW=T)<1>P)%ngVKW%)YjJ3)z>#PXxhX?Fc=Dj!;wfdIy)PS z#p8)YGC4PwO3lxw)0s>*yRfjhxU{sqyt0zZt*)-Et*>wJ>5M@++u<C)#j#;Zm8|po zVtRd+mw!s$hbgzsk(H+cx{-@e0bO3od;!~b;qO}xD4?6R1f}#ARG^Y>+~YXK9m#ls gDYTE^l7^8X3^$`&gFk~o4Y8ns*rZNoA~t2<7joni{r~^~ literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/screen-256color b/bash-5.1/vendor/term/tests/data/screen-256color new file mode 100644 index 0000000000000000000000000000000000000000..11fbb23a81590932243b2a18a47e1396772efae7 GIT binary patch literal 1912 zcmcgtOKcle6g|&WEuhj0Bm{I&2|^F3Qn&N-k10)CC)Ch*oHmKn#sVdEoY=9QxQ^5O zg9I!P5)uN$M^qJ3)g231u|i_O0<r0$i>_F(=z<jzQpJLWIroi&YNZ<rV&r@7x%b@n znd_N12UI`$u^&}+JGNMAmCN&SH<2tY)E8PCr^E5SQIqRiuC^<E6#9&^2q^OtM`BP| z?-hw7co0vbbB_zE^CqwhyIJuR4npIQsf*({PGAsc80B$+_&O#rgE^zlqlqP~k-v?1 zP3C=kh)>C`;3}@se}!-GExt2ar}KT+|3Lp^m;Xe6qsu#;o4AFa@e6L_SNw)M_>*_E zN9|Re&ZD%))dBSky<E?!7u3-%k21ZOqV|%?s$n%w_J*2OP5RXxBi=HZkBFbB&(#;| zs`{P$&W^fh_CJ_U$L?O~SWhHMc1Py!`u~pSV&VU^(%5~jbKyS6{hJ<L?5;TzyB@QO z6WD`CU=?*$Hyu44=%%ZuTTFPfgq&4;jqVIhd{0ph4@(7Yz)jToT5ybCF;Rs)3oCC@ zb>avukA1{MgWw1ZIJTdWN>?IZSW1{@!Uo@StJn}Qg))mT;2PcaS;ZY5vY8r=7T<zZ zI7O4iTt}j_v~#pkW}E~wMJHu2Z7?I~+J+lSC=4=}lt}6eyo<s~1_MsrI&OT$dKuOb zsp*%jWk`OTa0gN5#5Nh;CNi}t=ByFn)FpF+wq2)p6YN47R!UkcGunDUH<P*@I64sO zka`hyN&Sd=q^XGdq=|?oNL?K?WL!qK_v!L}9l*-rA@uhjJ{*r9Ibz$BlT%YOGqbam zO0_ySSF6?QjmG@^!a}oo=~An;xY%wlEnU96yu7lqy1KTuzP_=sxw$3XnSk};si^(F z#I9%1a7UgOFBA9~`72Fl%-+}2oBEh;d!`4vEN<ONnq0;N)Z=<um%Vh52%@S$rigC6 zJKVp=aL4W$@Ar(y13dZ<@|6DCoc?ms@A~^Z{ikmdINNTva4(<F$M6K6#<O^yU!|k) zk>R%>iyT6XVZwX`>S$pFTX+ZW;RAe(&u|4_O6O>@;}TAu$7vhq$1tA8kd09rwZW_> z;0q)Kk^(70C?;YkVklxLVn}f)9Aum;<cY(tjIoNyGGdfrAvr70y(%h^Dv>IYDv|2= Q2x?O<Y8M?E>q;*E0&l5@%m4rY literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/xterm b/bash-5.1/vendor/term/tests/data/xterm new file mode 100644 index 0000000000000000000000000000000000000000..12ad5b33aa7eac90e5ee16e01b7224d11f7569f3 GIT binary patch literal 3412 zcmb_edx)IX6+d_Gx5oG&qWB!D8_Z`O6*J#^#?NGuCY$UgyE|hxYu1cuvt~D&&CWiu zvvD_O6D^7%zVQ7PUnpWIt*9V~mbR#flu|9&5=2xiSP>MJfUoKA+;eA2s-k~5%>Dh& zIlp_)J#)YN-MMF}9Gyq==s|U$WoBw{a&*>UE1Sb({nggN(cRVlsqx9yMSZQChQ|iR zr(1jW)TRbU7ZWM-WrAUljmDRwu*-BTok8{Q`5a3t(7~Z&(Bn)x8+9z93(&Jb>!_2; zv<dd5v>mvU#%P9SO_r<aS~^HK!@ipyphv(@&>{K*Jx4FmpXoLDZ_r!xHob3p*Xv(c zo}=pZ<I(tYBKTx$*XyULvs9~Epcbj~m9O$@xmvB(scz^!Xq(h!s$UJND(sq?R#!F0 zNv;MSP`4Q6UiGLtq@GnTs#nzC)IZg`>OXeGXX=Rh8n((f86I_7=FH53%)-p#%=wvv zh}>wRjeIvZz1v{DYP{Doe{V(`{e<7j9R302=zd3g@0c<FZjSso^Lgeg<7ITcJ{OHY zCs}6ubo~o`u3n-&o!3RZR+sc9{Tn@`$Mv+nN?)gM(s$_l^<(;wen!8b|Ds>lZ|cMP zJ^i8nL?6+0J;#~nobH_CEOeGSiL=~kb2^<Kr{ZjLMx2_n*SW^I!MWYJ&w0do(&71j z`sa7f^UjOT%g$@fac?+hv>ZMD*Z=3Uy6t;nN00h(Z`kG-ZJGWVvi<mcziqj;C0p4{ zbLd3MR@`BC!gB{wcfxlECJ_jR0PWd|zYe?}joJ2E`#)0#w9|12wWAgNsESt+hUZs} zy93TDw3QM}{fHxFv@Xgn%7LR%fX7hua$$jGpS_T+JX=W<Lbgn)eHi^KZrKXQ%+M-~ zkij=2eABxa?O1S;m&+|(j$WuPTbVxrD@a2Wh_)P&PE&KRpRy(7EOB+d$KJ(g8_;?X z@ghVjUScqBu)yf&fTeb}*jNoC<~VmR@lW?sA6c2O2qjqvnYZZe$S#9~>H|}_G5B|z z-^g_sqpM+X9ury7Ft{=k>1-HWfQj(j#@N^}c<y1ekRbwW1Ak{Z@(9{TJwVxnA8r@9 zMR%g$PT`TcgIIMp%~o<8i`}Wzb5k}Wn7)`k%ur0voe11n_=)%-%t*`xX5LNl{Mu<Q zmZpuiZtd^izI|wDczEZ|k&$Y3baZTNe0*YJ*RILQT5W1-_wFmMn4X@Q*|X=$EBEf5 zo!z%@KQHxWv|_^RR!s1OOKZ@0&4QF439mdNOy(&ygXU3*7d3;tYCdm;iXYm+{2VYC zn}G@Yfl0Q69hO+mTP_IuIm_s8GTMUt(Dq9s$sI}VNODIux7~25aNcr37`aW{_bdmN zLt!tCC3h^jW62%c+-8e<Nh+MTTo6WX6Gv|0z;Y<;rGexQBzGXW1Do5d9&!ukEf<85 zTUHlI?3xINwqF`b?oe`vCO02J*poP+2H20s07a}SZ(wdgAq@+B5CpsvJ$J9S&t2wD zh3=s70^`Nj3ytSlFE(Bv-hkPTmGEcD5^zDjL9-jp%gC{?VPUh55^3CcR^U$ZWk$iO z*9oU`y?%<h^DLnpT}Ugbol0~GZJ_}gp-I|9SJMI9VD7~I<uQ7So~GyNkMs)tmHt78 z={@?8KA|J@Ew!i<)G4@|%*V}SsfyJy+)LK04eC<0RSl^zwOh@qYt;4XR&|ehsCg^l zijKh>c>->AC)25@Ba6G$d|E(@ak~mAPs>oz8d{GVRxfR)t+-)TQPm9X$FI1aZlSyA zetMW5M`gdqt?C8(6TOPs-lTugJM;m4M4zI%Z%C`TYMwe(Wl`Tk^-Gmgk-AV7QDeL6 zRArUj;(7iY0{JPgSPgb1z(3KJ$OaJhCG5BEf@s#&Sb^*&9P_-%?7LyNagfR(-Z+;7 zIi5qINGKLcgaSE0LZL_~7D|KyK3u#s6pDmmp@hk|8(vEC?dxjatVT%zA4<p~6bZ#b z2~#XtV#yLqmRPdHk|mNZk#vcqOC(*Q=0tqZVIrYOC>BbD`2PxB0-;bS5{iYAm9(;t z*5;^hBlYHK)g-N|QCp7M0_v(!PmX#9si#IGt5*dKAw$FvGbDg+ZY*}Q*v(=$i`@|0 zx>rL1LIOeqLIgr>FLgl$LIpwvLIpzY;2Ar3#txpbgJ<mE89Uc(gaU*Fga(8NgxcN5 zDiA6VDiA6VYI(yYP=Qc^P=Qc^P&ah&SRhm&R3KC!)ZQ{Tbm%QZ?=3^_Eko@sL+tly M<Z=%U`Zk~b3tuLQH2?qr literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/data/xterm-256color b/bash-5.1/vendor/term/tests/data/xterm-256color new file mode 100644 index 0000000000000000000000000000000000000000..80f0a3479a187d72df19eee95a6e0f430f8b625e GIT binary patch literal 3462 zcmb_eYiL|W6h5<aW33M=iqAz&vDeo6$lmvEukBjfv`L#}*QT+tYq7OS(=^X!Q<Ivc z6%?hu@cpXd3q>rVqJkhQz7Y}e0V+jAML|VSR0_V<@65To655JCyzG46ne)w@IXg3V z?wq7-I-O?Ged_hP@zL&)fwSEp+&I)fG%{(b^<%xGo9p4LH_kGVGCw952HD_Wtp>YD zhtdgDIlx1zvXjW7L(t+xIt8Q8r*qIUM=PiW{no&~h&BPY&>)S|q=|9`T}8X-M%Z`K zz4RdXQQAXK(R1_?y-IJR{sDbVpV3#Qb*1ua!ZTE*aySY<M}m(|>`LW0b&{%AbJRR_ zmU2~AEmBL>3e^U^9c7KWSZz?<svmY)jj5freiEyS*QlF}a<_U&?NQIF7uB2UJ@twD zLVcI?_*v~!f528LE5*HzOP!dSlbV}4BXw447d+P+Z#CYHwc0JP-ZHg!Qt#Ki)po)k zr}iF1nci-C?Q_%Tn_ABwQop2rH?@?mRA!>^b5z1?AFof=r|J3H(OI3>%XLAo(U<5R zJ*3C<PJOk$LEol#>xcCo{fvG=zoy^OAL_mOOZ~0>QSZ|gJ;R!19dDg#&9xe=$XaAI zS}j()RkAi(eOB3;u&%VOvu?HSu^zM@vv|D!{ybqlZ@p-}VZDuh9~`7_rf&au!2x{x zxB7QaoW#i2?f4&}{rgy~zEt;0UAnZEX3&w8F4?{Iuw!?{_ONSrjlkjc0GiSzcLjJQ z3UktG`9G#~Xrja5YC_4oK|fwa7>?U-s+&<+g0fhgu^X_bh|)^wc^Pmp0B{)cPR7r% z>~hU#E6Y|?1D`FEYA1T1&m~=ApXu5U!)I_!57)HL2b<@d>tr$wi_i+$rAxDiVR^BS z1W^{j(_(V=c2K&2m<7(xb+~o`$|{t0c$@&9k`o!s8q6`e8DOD_EjE_I2-(lg3;fre z*hN$(OhQ2>LdMNIo6`#+A$!jxZVdk4=09>C#%Qe?9LIRhs~Vh{@w8M8PQZA0Y-6mh z8a#F{iq8-LHiGw?jx3zXQg=~0;>B$xJ8uu?>`^S4-Hlnd<8&#*zR(_x9Xn<-fa!|q z!t}*->|xKIL_Lza4>J%mf|<2rtX~t&#MCs>`t=(&Y}(Y*)7!gcOJ84q|G>cD;Ly<U z@Yby(Bjxhw=(cT_T{bp0KE8eX<(E%POioTs?ck|ii;|Cc-trMvxUdX`=gf<FNqFYr zVKS>!bDE`+T2OQHthu}uO0J)D=5;`4Yz8Lm2PWAPNw+BBY{EHVH<K{hn}|t5uAj7v z1Bo3->_B1%N$h09#lqQybHa#i{H~L*m#{DF#G%9vC3YyW!z8xZqD~YGXA{l|BewA) zwy>A5FYLsg#P%e%C$YUGwwXP|7S1M|6Gm*AT?9$yMA%Q-#lFP$CAM#3^AUtSi4&@e z>){|Ek6Gmn%*D&aehwRHogbSmACL50x`0o!2{#C)?D_Ttj)2UR-C(=txSb8WCl99h z2UgM-^Dr0!yMvMU7w>w<p2$ww=h~y58QAVNE+;g;Tvb2Y?y|c*ETN=lHvRPO{sFo> znQ8s~>HV?O2T0?7bRO<Azol?z!aap>qE{-%nETRv%FqH@Oifgv3uzs7Q6G)acDjPD z!R_aE+<hLV$LVQ$o?fOm>0SDW_R^R1E&WLQ=r5{MN2p_PubGWoO@j*6LfmOqs#WSD zwO;k8LA6aysw>sC>SlG9y1#a#A!Kw2-sU544?LQVMILF~%VyIYIs-Q|kFvB787-rg zxSe&-T3V0WSwFHGryckg*V0XN2koW@=n-W0ByMCc&@1#7a{G`zrO)YW`ksD5c7Kvq zGu140tV$!lx#~=nQGr^Z^2o7CwWy*>uX7xC1~!D_nkg^CE_wKhtqT$d+^%ihZv9qX zO#T8I%afgmPXuq!<h@E>0WX#hK=n-b<Y@PW0-;bS67uBm@r44RP$&}e_+WBkUnmd? zg(4<5d08YSH+j{Qx3Zd&#|Ijs2n9l+P{b5Ulu)9C5+#%<p+pI!Ngz!EX%a}2pf(U6 zk{C!R5DJANA^z5(i6`U>1wx@vw3rrm(((*-uBMJGEg7LDWopb&qerb}YR^!6H?^0k zZ|M?`!Dk2<LWT&?#)ZW;7TZ{CW3dflW7|?FKuADnK!`x7O@&sdK&U{dK&U{d%{*c= zkJ!v3HuH$hJYvhT)lh(tfY5*tfl%8zSp`A`LIpwvLM^Vk5GoKV5GoKV5bCOC?hAwp lgbIWTgxXQ$f(9K$=p9AK9Yv@eMTi?*>bulIfxgkDzX5~Wl}G>p literal 0 HcmV?d00001 diff --git a/bash-5.1/vendor/term/tests/terminfo.rs b/bash-5.1/vendor/term/tests/terminfo.rs new file mode 100644 index 0000000..54be4a5 --- /dev/null +++ b/bash-5.1/vendor/term/tests/terminfo.rs @@ -0,0 +1,32 @@ +extern crate term; + +use term::terminfo::TermInfo; +use term::terminfo::TerminfoTerminal; +use term::Terminal; +use std::fs; +use std::io; + +#[test] +fn test_parse() { + for f in fs::read_dir("tests/data/").unwrap() { + let _ = TermInfo::from_path(f.unwrap().path()).unwrap(); + } +} + +#[test] +fn test_supports_color() { + fn supports_color(term: &str) -> bool { + let terminfo = TermInfo::from_path(format!("tests/data/{}", term)).unwrap(); + let term = TerminfoTerminal::new_with_terminfo(io::stdout(), terminfo); + term.supports_color() + } + assert!(supports_color("linux")); + assert!(!supports_color("dumb")); +} + + +#[test] +fn test_fallback() { + TermInfo::from_name("ansi-cargo-test").expect("failed to use fallback"); + assert!(TermInfo::from_name("really-bad-terminal").is_err()); +} diff --git a/bash-5.1/vendor/textwrap/.cargo-checksum.json b/bash-5.1/vendor/textwrap/.cargo-checksum.json new file mode 100644 index 0000000..02794aa --- /dev/null +++ b/bash-5.1/vendor/textwrap/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"a0e3c783725beb480b666d52d49da0ec69865c82e8bd5c8a76ba330158e954c1","LICENSE":"ce93600c49fbb3e14df32efe752264644f6a2f8e08a735ba981725799e5309ef","README.md":"9af1f6627e8c2e19c7383c99462ca028b235b2f8dadbb33f13e2d1663c8c20e3","benches/linear.rs":"ec084063923bafc6e80c2cd78deb0f7ad18ae19a7e66005e991e00dac1ff3ce4","examples/layout.rs":"38cf4d316d28e0b99925bef604b68aad05489c06ec77e6105575cd26ce994631","examples/termwidth.rs":"67d95b60feb52cfd59fe5b17c37c53e51fb7f2a8e5e483d75aec8d0044dbcbd7","src/indentation.rs":"04f8479286fd87f2d75b0f02ce8309a815a5ffd1e79a7323132e34dc0e107aef","src/lib.rs":"115bf6ec566b8241d52cff83977146f03df3460d6f94ad897f2221cb56100118","src/splitting.rs":"071ef8ce0ea6c3f33230889a3426fd645276a6de626f45223ae7b873394df662","tests/version-numbers.rs":"e0e9316073d6d410440a6ee33c2f3bdfd0faa48895f6f9d05a220a91b7afcc99"},"package":"d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"} \ No newline at end of file diff --git a/bash-5.1/vendor/textwrap/Cargo.toml b/bash-5.1/vendor/textwrap/Cargo.toml new file mode 100644 index 0000000..4ec570f --- /dev/null +++ b/bash-5.1/vendor/textwrap/Cargo.toml @@ -0,0 +1,56 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "textwrap" +version = "0.11.0" +authors = ["Martin Geisler <martin@geisler.net>"] +exclude = [".dir-locals.el"] +description = "Textwrap is a small library for word wrapping, indenting, and\ndedenting strings.\n\nYou can use it to format strings (such as help and error messages) for\ndisplay in commandline applications. It is designed to be efficient\nand handle Unicode characters correctly.\n" +documentation = "https://docs.rs/textwrap/" +readme = "README.md" +keywords = ["text", "formatting", "wrap", "typesetting", "hyphenation"] +categories = ["text-processing", "command-line-interface"] +license = "MIT" +repository = "https://github.com/mgeisler/textwrap" +[package.metadata.docs.rs] +all-features = true +[dependencies.hyphenation] +version = "0.7.1" +features = ["embed_all"] +optional = true + +[dependencies.term_size] +version = "0.3.0" +optional = true + +[dependencies.unicode-width] +version = "0.1.3" +[dev-dependencies.lipsum] +version = "0.6" + +[dev-dependencies.rand] +version = "0.6" + +[dev-dependencies.rand_xorshift] +version = "0.1" + +[dev-dependencies.version-sync] +version = "0.6" +[badges.appveyor] +repository = "mgeisler/textwrap" + +[badges.codecov] +repository = "mgeisler/textwrap" + +[badges.travis-ci] +repository = "mgeisler/textwrap" diff --git a/bash-5.1/vendor/textwrap/LICENSE b/bash-5.1/vendor/textwrap/LICENSE new file mode 100644 index 0000000..0d37ec3 --- /dev/null +++ b/bash-5.1/vendor/textwrap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Martin Geisler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bash-5.1/vendor/textwrap/README.md b/bash-5.1/vendor/textwrap/README.md new file mode 100644 index 0000000..23a5439 --- /dev/null +++ b/bash-5.1/vendor/textwrap/README.md @@ -0,0 +1,337 @@ +# Textwrap + +[![](https://img.shields.io/crates/v/textwrap.svg)][crates-io] +[![](https://docs.rs/textwrap/badge.svg)][api-docs] +[![](https://travis-ci.org/mgeisler/textwrap.svg?branch=master)][travis-ci] +[![](https://ci.appveyor.com/api/projects/status/github/mgeisler/textwrap?branch=master&svg=true)][appveyor] +[![](https://codecov.io/gh/mgeisler/textwrap/branch/master/graph/badge.svg)][codecov] + +Textwrap is a small Rust crate for word wrapping text. You can use it +to format strings for display in commandline applications. The crate +name and interface is inspired by +the [Python textwrap module][py-textwrap]. + +## Usage + +Add this to your `Cargo.toml`: +```toml +[dependencies] +textwrap = "0.11" +``` + +and this to your crate root: +```rust +extern crate textwrap; +``` + +If you would like to have automatic hyphenation, specify the +dependency as: +```toml +[dependencies] +textwrap = { version = "0.11", features = ["hyphenation"] } +``` + +To conveniently wrap text at the current terminal width, enable the +`term_size` feature: + +```toml +[dependencies] +textwrap = { version = "0.11", features = ["term_size"] } +``` + +## Documentation + +**[API documentation][api-docs]** + +## Getting Started + +Word wrapping single strings is easy using the `fill` function: +```rust +extern crate textwrap; +use textwrap::fill; + +fn main() { + let text = "textwrap: a small library for wrapping text."; + println!("{}", fill(text, 18)); +} +``` +The output is +``` +textwrap: a small +library for +wrapping text. +``` + +With the `hyphenation` feature, you can get automatic hyphenation +for [about 70 languages][patterns]. Your program must load and +configure the hyphenation patterns to use: +```rust +extern crate hyphenation; +extern crate textwrap; + +use hyphenation::{Language, Load, Standard}; +use textwrap::Wrapper; + +fn main() { + let hyphenator = Standard::from_embedded(Language::EnglishUS).unwrap(); + let wrapper = Wrapper::with_splitter(18, hyphenator); + let text = "textwrap: a small library for wrapping text."; + println!("{}", wrapper.fill(text)) +} +``` + +The output now looks like this: +``` +textwrap: a small +library for wrap- +ping text. +``` + +The hyphenation uses high-quality TeX hyphenation patterns. + +## Examples + +The library comes with some small example programs that shows various +features. + +### Layout Example + +The `layout` example shows how a fixed example string is wrapped at +different widths. Run the example with: + +```shell +$ cargo run --features hyphenation --example layout +``` + +The program will use the following string: + +> Memory safety without garbage collection. Concurrency without data +> races. Zero-cost abstractions. + +The string is wrapped at all widths between 15 and 60 columns. With +narrow columns the output looks like this: + +``` +.--- Width: 15 ---. +| Memory safety | +| without garbage | +| collection. | +| Concurrency | +| without data | +| races. Zero- | +| cost abstrac- | +| tions. | +.--- Width: 16 ----. +| Memory safety | +| without garbage | +| collection. Con- | +| currency without | +| data races. Ze- | +| ro-cost abstrac- | +| tions. | +``` + +Later, longer lines are used and the output now looks like this: + +``` +.-------------------- Width: 49 --------------------. +| Memory safety without garbage collection. Concur- | +| rency without data races. Zero-cost abstractions. | +.---------------------- Width: 53 ----------------------. +| Memory safety without garbage collection. Concurrency | +| without data races. Zero-cost abstractions. | +.------------------------- Width: 59 -------------------------. +| Memory safety without garbage collection. Concurrency with- | +| out data races. Zero-cost abstractions. | +``` + +Notice how words are split at hyphens (such as "zero-cost") but also +how words are hyphenated using automatic/machine hyphenation. + +### Terminal Width Example + +The `termwidth` example simply shows how the width can be set +automatically to the current terminal width. Run it with this command: + +``` +$ cargo run --example termwidth +``` + +If you run it in a narrow terminal, you'll see output like this: +``` +Formatted in within 60 columns: +---- +Memory safety without garbage collection. Concurrency +without data races. Zero-cost abstractions. +---- +``` + +If `stdout` is not connected to the terminal, the program will use a +default of 80 columns for the width: + +``` +$ cargo run --example termwidth | cat +Formatted in within 80 columns: +---- +Memory safety without garbage collection. Concurrency without data races. Zero- +cost abstractions. +---- +``` + +## Release History + +This section lists the largest changes per release. + +### Version 0.11.0 — December 9th, 2018 + +Due to our dependencies bumping their minimum supported version of +Rust, the minimum version of Rust we test against is now 1.22.0. + +* Merged [#141][issue-141]: Fix `dedent` handling of empty lines and + trailing newlines. Thanks @bbqsrc! +* Fixed [#151][issue-151]: Release of version with hyphenation 0.7. + +### Version 0.10.0 — April 28th, 2018 + +Due to our dependencies bumping their minimum supported version of +Rust, the minimum version of Rust we test against is now 1.17.0. + +* Fixed [#99][issue-99]: Word broken even though it would fit on line. +* Fixed [#107][issue-107]: Automatic hyphenation is off by one. +* Fixed [#122][issue-122]: Take newlines into account when wrapping. +* Fixed [#129][issue-129]: Panic on string with em-dash. + +### Version 0.9.0 — October 5th, 2017 + +The dependency on `term_size` is now optional, and by default this +feature is not enabled. This is a *breaking change* for users of +`Wrapper::with_termwidth`. Enable the `term_size` feature to restore +the old functionality. + +Added a regression test for the case where `width` is set to +`usize::MAX`, thanks @Fraser999! All public structs now implement +`Debug`, thanks @hcpl! + +* Fixed [#101][issue-101]: Make `term_size` an optional dependency. + +### Version 0.8.0 — September 4th, 2017 + +The `Wrapper` stuct is now generic over the type of word splitter +being used. This means less boxing and a nicer API. The +`Wrapper::word_splitter` method has been removed. This is a *breaking +API change* if you used the method to change the word splitter. + +The `Wrapper` struct has two new methods that will wrap the input text +lazily: `Wrapper::wrap_iter` and `Wrapper::into_wrap_iter`. Use those +if you will be iterating over the wrapped lines one by one. + +* Fixed [#59][issue-59]: `wrap` could return an iterator. Thanks + @hcpl! +* Fixed [#81][issue-81]: Set `html_root_url`. + +### Version 0.7.0 — July 20th, 2017 + +Version 0.7.0 changes the return type of `Wrapper::wrap` from +`Vec<String>` to `Vec<Cow<'a, str>>`. This means that the output lines +borrow data from the input string. This is a *breaking API change* if +you relied on the exact return type of `Wrapper::wrap`. Callers of the +`textwrap::fill` convenience function will see no breakage. + +The above change and other optimizations makes version 0.7.0 roughly +15-30% faster than version 0.6.0. + +The `squeeze_whitespace` option has been removed since it was +complicating the above optimization. Let us know if this option is +important for you so we can provide a work around. + +* Fixed [#58][issue-58]: Add a "fast_wrap" function. +* Fixed [#61][issue-61]: Documentation errors. + +### Version 0.6.0 — May 22nd, 2017 + +Version 0.6.0 adds builder methods to `Wrapper` for easy one-line +initialization and configuration: + +```rust +let wrapper = Wrapper::new(60).break_words(false); +``` + +It also add a new `NoHyphenation` word splitter that will never split +words, not even at existing hyphens. + +* Fixed [#28][issue-28]: Support not squeezing whitespace. + +### Version 0.5.0 — May 15th, 2017 + +Version 0.5.0 has *breaking API changes*. However, this only affects +code using the hyphenation feature. The feature is now optional, so +you will first need to enable the `hyphenation` feature as described +above. Afterwards, please change your code from +```rust +wrapper.corpus = Some(&corpus); +``` +to +```rust +wrapper.splitter = Box::new(corpus); +``` + +Other changes include optimizations, so version 0.5.0 is roughly +10-15% faster than version 0.4.0. + +* Fixed [#19][issue-19]: Add support for finding terminal size. +* Fixed [#25][issue-25]: Handle words longer than `self.width`. +* Fixed [#26][issue-26]: Support custom indentation. +* Fixed [#36][issue-36]: Support building without `hyphenation`. +* Fixed [#39][issue-39]: Respect non-breaking spaces. + +### Version 0.4.0 — January 24th, 2017 + +Documented complexities and tested these via `cargo bench`. + +* Fixed [#13][issue-13]: Immediatedly add word if it fits. +* Fixed [#14][issue-14]: Avoid splitting on initial hyphens. + +### Version 0.3.0 — January 7th, 2017 + +Added support for automatic hyphenation. + +### Version 0.2.0 — December 28th, 2016 + +Introduced `Wrapper` struct. Added support for wrapping on hyphens. + +### Version 0.1.0 — December 17th, 2016 + +First public release with support for wrapping strings on whitespace. + +## License + +Textwrap can be distributed according to the [MIT license][mit]. +Contributions will be accepted under the same license. + +[crates-io]: https://crates.io/crates/textwrap +[travis-ci]: https://travis-ci.org/mgeisler/textwrap +[appveyor]: https://ci.appveyor.com/project/mgeisler/textwrap +[codecov]: https://codecov.io/gh/mgeisler/textwrap +[py-textwrap]: https://docs.python.org/library/textwrap +[patterns]: https://github.com/tapeinosyne/hyphenation/tree/master/patterns-tex +[api-docs]: https://docs.rs/textwrap/ +[issue-13]: https://github.com/mgeisler/textwrap/issues/13 +[issue-14]: https://github.com/mgeisler/textwrap/issues/14 +[issue-19]: https://github.com/mgeisler/textwrap/issues/19 +[issue-25]: https://github.com/mgeisler/textwrap/issues/25 +[issue-26]: https://github.com/mgeisler/textwrap/issues/26 +[issue-28]: https://github.com/mgeisler/textwrap/issues/28 +[issue-36]: https://github.com/mgeisler/textwrap/issues/36 +[issue-39]: https://github.com/mgeisler/textwrap/issues/39 +[issue-58]: https://github.com/mgeisler/textwrap/issues/58 +[issue-59]: https://github.com/mgeisler/textwrap/issues/59 +[issue-61]: https://github.com/mgeisler/textwrap/issues/61 +[issue-81]: https://github.com/mgeisler/textwrap/issues/81 +[issue-99]: https://github.com/mgeisler/textwrap/issues/99 +[issue-101]: https://github.com/mgeisler/textwrap/issues/101 +[issue-107]: https://github.com/mgeisler/textwrap/issues/107 +[issue-122]: https://github.com/mgeisler/textwrap/issues/122 +[issue-129]: https://github.com/mgeisler/textwrap/issues/129 +[issue-141]: https://github.com/mgeisler/textwrap/issues/141 +[issue-151]: https://github.com/mgeisler/textwrap/issues/151 +[mit]: LICENSE diff --git a/bash-5.1/vendor/textwrap/benches/linear.rs b/bash-5.1/vendor/textwrap/benches/linear.rs new file mode 100644 index 0000000..104398a --- /dev/null +++ b/bash-5.1/vendor/textwrap/benches/linear.rs @@ -0,0 +1,122 @@ +#![feature(test)] + +// The benchmarks here verify that the complexity grows as O(*n*) +// where *n* is the number of characters in the text to be wrapped. + +#[cfg(feature = "hyphenation")] +extern crate hyphenation; +extern crate lipsum; +extern crate rand; +extern crate rand_xorshift; +extern crate test; +extern crate textwrap; + +#[cfg(feature = "hyphenation")] +use hyphenation::{Language, Load, Standard}; +use lipsum::MarkovChain; +use rand::SeedableRng; +use rand_xorshift::XorShiftRng; +use test::Bencher; +#[cfg(feature = "hyphenation")] +use textwrap::Wrapper; + +const LINE_LENGTH: usize = 60; + +/// Generate a lorem ipsum text with the given number of characters. +fn lorem_ipsum(length: usize) -> String { + // The average word length in the lorem ipsum text is somewhere + // between 6 and 7. So we conservatively divide by 5 to have a + // long enough text that we can truncate below. + let rng = XorShiftRng::seed_from_u64(0); + let mut chain = MarkovChain::new_with_rng(rng); + chain.learn(lipsum::LOREM_IPSUM); + chain.learn(lipsum::LIBER_PRIMUS); + + let mut text = chain.generate_from(length / 5, ("Lorem", "ipsum")); + text.truncate(length); + text +} + +#[bench] +fn fill_100(b: &mut Bencher) { + let text = &lorem_ipsum(100); + b.iter(|| textwrap::fill(text, LINE_LENGTH)) +} + +#[bench] +fn fill_200(b: &mut Bencher) { + let text = &lorem_ipsum(200); + b.iter(|| textwrap::fill(text, LINE_LENGTH)) +} + +#[bench] +fn fill_400(b: &mut Bencher) { + let text = &lorem_ipsum(400); + b.iter(|| textwrap::fill(text, LINE_LENGTH)) +} + +#[bench] +fn fill_800(b: &mut Bencher) { + let text = &lorem_ipsum(800); + b.iter(|| textwrap::fill(text, LINE_LENGTH)) +} + +#[bench] +fn wrap_100(b: &mut Bencher) { + let text = &lorem_ipsum(100); + b.iter(|| textwrap::wrap(text, LINE_LENGTH)) +} + +#[bench] +fn wrap_200(b: &mut Bencher) { + let text = &lorem_ipsum(200); + b.iter(|| textwrap::wrap(text, LINE_LENGTH)) +} + +#[bench] +fn wrap_400(b: &mut Bencher) { + let text = &lorem_ipsum(400); + b.iter(|| textwrap::wrap(text, LINE_LENGTH)) +} + +#[bench] +fn wrap_800(b: &mut Bencher) { + let text = &lorem_ipsum(800); + b.iter(|| textwrap::wrap(text, LINE_LENGTH)) +} + +#[bench] +#[cfg(feature = "hyphenation")] +fn hyphenation_fill_100(b: &mut Bencher) { + let text = &lorem_ipsum(100); + let dictionary = Standard::from_embedded(Language::Latin).unwrap(); + let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); + b.iter(|| wrapper.fill(text)) +} + +#[bench] +#[cfg(feature = "hyphenation")] +fn hyphenation_fill_200(b: &mut Bencher) { + let text = &lorem_ipsum(200); + let dictionary = Standard::from_embedded(Language::Latin).unwrap(); + let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); + b.iter(|| wrapper.fill(text)) +} + +#[bench] +#[cfg(feature = "hyphenation")] +fn hyphenation_fill_400(b: &mut Bencher) { + let text = &lorem_ipsum(400); + let dictionary = Standard::from_embedded(Language::Latin).unwrap(); + let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); + b.iter(|| wrapper.fill(text)) +} + +#[bench] +#[cfg(feature = "hyphenation")] +fn hyphenation_fill_800(b: &mut Bencher) { + let text = &lorem_ipsum(800); + let dictionary = Standard::from_embedded(Language::Latin).unwrap(); + let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); + b.iter(|| wrapper.fill(text)) +} diff --git a/bash-5.1/vendor/textwrap/examples/layout.rs b/bash-5.1/vendor/textwrap/examples/layout.rs new file mode 100644 index 0000000..d36cb3a --- /dev/null +++ b/bash-5.1/vendor/textwrap/examples/layout.rs @@ -0,0 +1,38 @@ +#[cfg(feature = "hyphenation")] +extern crate hyphenation; +extern crate textwrap; + +#[cfg(feature = "hyphenation")] +use hyphenation::{Language, Load}; +use textwrap::Wrapper; + +#[cfg(not(feature = "hyphenation"))] +fn new_wrapper<'a>() -> Wrapper<'a, textwrap::HyphenSplitter> { + Wrapper::new(0) +} + +#[cfg(feature = "hyphenation")] +fn new_wrapper<'a>() -> Wrapper<'a, hyphenation::Standard> { + let dictionary = hyphenation::Standard::from_embedded(Language::EnglishUS).unwrap(); + Wrapper::with_splitter(0, dictionary) +} + +fn main() { + let example = "Memory safety without garbage collection. \ + Concurrency without data races. \ + Zero-cost abstractions."; + let mut prev_lines = vec![]; + let mut wrapper = new_wrapper(); + for width in 15..60 { + wrapper.width = width; + let lines = wrapper.wrap(example); + if lines != prev_lines { + let title = format!(" Width: {} ", width); + println!(".{:-^1$}.", title, width + 2); + for line in &lines { + println!("| {:1$} |", line, width); + } + prev_lines = lines; + } + } +} diff --git a/bash-5.1/vendor/textwrap/examples/termwidth.rs b/bash-5.1/vendor/textwrap/examples/termwidth.rs new file mode 100644 index 0000000..75db3aa --- /dev/null +++ b/bash-5.1/vendor/textwrap/examples/termwidth.rs @@ -0,0 +1,41 @@ +#[cfg(feature = "hyphenation")] +extern crate hyphenation; +extern crate textwrap; + +#[cfg(feature = "hyphenation")] +use hyphenation::{Language, Load, Standard}; +#[cfg(feature = "term_size")] +use textwrap::Wrapper; + +#[cfg(not(feature = "term_size"))] +fn main() { + println!("Please enable the term_size feature to run this example."); +} + +#[cfg(feature = "term_size")] +fn main() { + #[cfg(not(feature = "hyphenation"))] + fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, textwrap::HyphenSplitter>) { + ("without hyphenation", Wrapper::with_termwidth()) + } + + #[cfg(feature = "hyphenation")] + fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, Standard>) { + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + ( + "with hyphenation", + Wrapper::with_splitter(textwrap::termwidth(), dictionary), + ) + } + + let example = "Memory safety without garbage collection. \ + Concurrency without data races. \ + Zero-cost abstractions."; + // Create a new Wrapper -- automatically set the width to the + // current terminal width. + let (msg, wrapper) = new_wrapper(); + println!("Formatted {} in {} columns:", msg, wrapper.width); + println!("----"); + println!("{}", wrapper.fill(example)); + println!("----"); +} diff --git a/bash-5.1/vendor/textwrap/src/indentation.rs b/bash-5.1/vendor/textwrap/src/indentation.rs new file mode 100644 index 0000000..276ba10 --- /dev/null +++ b/bash-5.1/vendor/textwrap/src/indentation.rs @@ -0,0 +1,294 @@ +//! Functions related to adding and removing indentation from lines of +//! text. +//! +//! The functions here can be used to uniformly indent or dedent +//! (unindent) word wrapped lines of text. + +/// Add prefix to each non-empty line. +/// +/// ``` +/// use textwrap::indent; +/// +/// assert_eq!(indent(" +/// Foo +/// Bar +/// ", " "), " +/// Foo +/// Bar +/// "); +/// ``` +/// +/// Empty lines (lines consisting only of whitespace) are not indented +/// and the whitespace is replaced by a single newline (`\n`): +/// +/// ``` +/// use textwrap::indent; +/// +/// assert_eq!(indent(" +/// Foo +/// +/// Bar +/// \t +/// Baz +/// ", "->"), " +/// ->Foo +/// +/// ->Bar +/// +/// ->Baz +/// "); +/// ``` +/// +/// Leading and trailing whitespace on non-empty lines is kept +/// unchanged: +/// +/// ``` +/// use textwrap::indent; +/// +/// assert_eq!(indent(" \t Foo ", "->"), "-> \t Foo \n"); +/// ``` +pub fn indent(s: &str, prefix: &str) -> String { + let mut result = String::new(); + for line in s.lines() { + if line.chars().any(|c| !c.is_whitespace()) { + result.push_str(prefix); + result.push_str(line); + } + result.push('\n'); + } + result +} + +/// Removes common leading whitespace from each line. +/// +/// This function will look at each non-empty line and determine the +/// maximum amount of whitespace that can be removed from all lines: +/// +/// ``` +/// use textwrap::dedent; +/// +/// assert_eq!(dedent(" +/// 1st line +/// 2nd line +/// 3rd line +/// "), " +/// 1st line +/// 2nd line +/// 3rd line +/// "); +/// ``` +pub fn dedent(s: &str) -> String { + let mut prefix = ""; + let mut lines = s.lines(); + + // We first search for a non-empty line to find a prefix. + for line in &mut lines { + let mut whitespace_idx = line.len(); + for (idx, ch) in line.char_indices() { + if !ch.is_whitespace() { + whitespace_idx = idx; + break; + } + } + + // Check if the line had anything but whitespace + if whitespace_idx < line.len() { + prefix = &line[..whitespace_idx]; + break; + } + } + + // We then continue looking through the remaining lines to + // possibly shorten the prefix. + for line in &mut lines { + let mut whitespace_idx = line.len(); + for ((idx, a), b) in line.char_indices().zip(prefix.chars()) { + if a != b { + whitespace_idx = idx; + break; + } + } + + // Check if the line had anything but whitespace and if we + // have found a shorter prefix + if whitespace_idx < line.len() && whitespace_idx < prefix.len() { + prefix = &line[..whitespace_idx]; + } + } + + // We now go over the lines a second time to build the result. + let mut result = String::new(); + for line in s.lines() { + if line.starts_with(&prefix) && line.chars().any(|c| !c.is_whitespace()) { + let (_, tail) = line.split_at(prefix.len()); + result.push_str(tail); + } + result.push('\n'); + } + + if result.ends_with('\n') && !s.ends_with('\n') { + let new_len = result.len() - 1; + result.truncate(new_len); + } + + result +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Add newlines. Ensures that the final line in the vector also + /// has a newline. + fn add_nl(lines: &[&str]) -> String { + lines.join("\n") + "\n" + } + + #[test] + fn indent_empty() { + assert_eq!(indent("\n", " "), "\n"); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn indent_nonempty() { + let x = vec![" foo", + "bar", + " baz"]; + let y = vec!["// foo", + "//bar", + "// baz"]; + assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn indent_empty_line() { + let x = vec![" foo", + "bar", + "", + " baz"]; + let y = vec!["// foo", + "//bar", + "", + "// baz"]; + assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y)); + } + + #[test] + fn dedent_empty() { + assert_eq!(dedent(""), ""); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_multi_line() { + let x = vec![" foo", + " bar", + " baz"]; + let y = vec![" foo", + "bar", + " baz"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_empty_line() { + let x = vec![" foo", + " bar", + " ", + " baz"]; + let y = vec![" foo", + "bar", + "", + " baz"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_blank_line() { + let x = vec![" foo", + "", + " bar", + " foo", + " bar", + " baz"]; + let y = vec!["foo", + "", + " bar", + " foo", + " bar", + " baz"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_whitespace_line() { + let x = vec![" foo", + " ", + " bar", + " foo", + " bar", + " baz"]; + let y = vec!["foo", + "", + " bar", + " foo", + " bar", + " baz"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_mixed_whitespace() { + let x = vec!["\tfoo", + " bar"]; + let y = vec!["\tfoo", + " bar"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_tabbed_whitespace() { + let x = vec!["\t\tfoo", + "\t\t\tbar"]; + let y = vec!["foo", + "\tbar"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_mixed_tabbed_whitespace() { + let x = vec!["\t \tfoo", + "\t \t\tbar"]; + let y = vec!["foo", + "\tbar"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_mixed_tabbed_whitespace2() { + let x = vec!["\t \tfoo", + "\t \tbar"]; + let y = vec!["\tfoo", + " \tbar"]; + assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + } + + #[test] + #[cfg_attr(rustfmt, rustfmt_skip)] + fn dedent_preserve_no_terminating_newline() { + let x = vec![" foo", + " bar"].join("\n"); + let y = vec!["foo", + " bar"].join("\n"); + assert_eq!(dedent(&x), y); + } +} diff --git a/bash-5.1/vendor/textwrap/src/lib.rs b/bash-5.1/vendor/textwrap/src/lib.rs new file mode 100644 index 0000000..2f82325 --- /dev/null +++ b/bash-5.1/vendor/textwrap/src/lib.rs @@ -0,0 +1,987 @@ +//! `textwrap` provides functions for word wrapping and filling text. +//! +//! Wrapping text can be very useful in commandline programs where you +//! want to format dynamic output nicely so it looks good in a +//! terminal. A quick example: +//! +//! ```no_run +//! extern crate textwrap; +//! use textwrap::fill; +//! +//! fn main() { +//! let text = "textwrap: a small library for wrapping text."; +//! println!("{}", fill(text, 18)); +//! } +//! ``` +//! +//! This will display the following output: +//! +//! ```text +//! textwrap: a small +//! library for +//! wrapping text. +//! ``` +//! +//! # Displayed Width vs Byte Size +//! +//! To word wrap text, one must know the width of each word so one can +//! know when to break lines. This library measures the width of text +//! using the [displayed width][unicode-width], not the size in bytes. +//! +//! This is important for non-ASCII text. ASCII characters such as `a` +//! and `!` are simple and take up one column each. This means that +//! the displayed width is equal to the string length in bytes. +//! However, non-ASCII characters and symbols take up more than one +//! byte when UTF-8 encoded: `é` is `0xc3 0xa9` (two bytes) and `⚙` is +//! `0xe2 0x9a 0x99` (three bytes) in UTF-8, respectively. +//! +//! This is why we take care to use the displayed width instead of the +//! byte count when computing line lengths. All functions in this +//! library handle Unicode characters like this. +//! +//! [unicode-width]: https://docs.rs/unicode-width/ + +#![doc(html_root_url = "https://docs.rs/textwrap/0.11.0")] +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] + +#[cfg(feature = "hyphenation")] +extern crate hyphenation; +#[cfg(feature = "term_size")] +extern crate term_size; +extern crate unicode_width; + +use std::borrow::Cow; +use std::str::CharIndices; + +use unicode_width::UnicodeWidthChar; +use unicode_width::UnicodeWidthStr; + +/// A non-breaking space. +const NBSP: char = '\u{a0}'; + +mod indentation; +pub use indentation::dedent; +pub use indentation::indent; + +mod splitting; +pub use splitting::{HyphenSplitter, NoHyphenation, WordSplitter}; + +/// A Wrapper holds settings for wrapping and filling text. Use it +/// when the convenience [`wrap_iter`], [`wrap`] and [`fill`] functions +/// are not flexible enough. +/// +/// [`wrap_iter`]: fn.wrap_iter.html +/// [`wrap`]: fn.wrap.html +/// [`fill`]: fn.fill.html +/// +/// The algorithm used by the `WrapIter` iterator (returned from the +/// `wrap_iter` method) works by doing successive partial scans over +/// words in the input string (where each single scan yields a single +/// line) so that the overall time and memory complexity is O(*n*) where +/// *n* is the length of the input string. +#[derive(Clone, Debug)] +pub struct Wrapper<'a, S: WordSplitter> { + /// The width in columns at which the text will be wrapped. + pub width: usize, + /// Indentation used for the first line of output. + pub initial_indent: &'a str, + /// Indentation used for subsequent lines of output. + pub subsequent_indent: &'a str, + /// Allow long words to be broken if they cannot fit on a line. + /// When set to `false`, some lines may be longer than + /// `self.width`. + pub break_words: bool, + /// The method for splitting words. If the `hyphenation` feature + /// is enabled, you can use a `hyphenation::Standard` dictionary + /// here to get language-aware hyphenation. + pub splitter: S, +} + +impl<'a> Wrapper<'a, HyphenSplitter> { + /// Create a new Wrapper for wrapping at the specified width. By + /// default, we allow words longer than `width` to be broken. A + /// [`HyphenSplitter`] will be used by default for splitting + /// words. See the [`WordSplitter`] trait for other options. + /// + /// [`HyphenSplitter`]: struct.HyphenSplitter.html + /// [`WordSplitter`]: trait.WordSplitter.html + pub fn new(width: usize) -> Wrapper<'a, HyphenSplitter> { + Wrapper::with_splitter(width, HyphenSplitter) + } + + /// Create a new Wrapper for wrapping text at the current terminal + /// width. If the terminal width cannot be determined (typically + /// because the standard input and output is not connected to a + /// terminal), a width of 80 characters will be used. Other + /// settings use the same defaults as `Wrapper::new`. + /// + /// Equivalent to: + /// + /// ```no_run + /// # #![allow(unused_variables)] + /// use textwrap::{Wrapper, termwidth}; + /// + /// let wrapper = Wrapper::new(termwidth()); + /// ``` + #[cfg(feature = "term_size")] + pub fn with_termwidth() -> Wrapper<'a, HyphenSplitter> { + Wrapper::new(termwidth()) + } +} + +impl<'a, S: WordSplitter> Wrapper<'a, S> { + /// Use the given [`WordSplitter`] to create a new Wrapper for + /// wrapping at the specified width. By default, we allow words + /// longer than `width` to be broken. + /// + /// [`WordSplitter`]: trait.WordSplitter.html + pub fn with_splitter(width: usize, splitter: S) -> Wrapper<'a, S> { + Wrapper { + width: width, + initial_indent: "", + subsequent_indent: "", + break_words: true, + splitter: splitter, + } + } + + /// Change [`self.initial_indent`]. The initial indentation is + /// used on the very first line of output. + /// + /// # Examples + /// + /// Classic paragraph indentation can be achieved by specifying an + /// initial indentation and wrapping each paragraph by itself: + /// + /// ```no_run + /// # #![allow(unused_variables)] + /// use textwrap::Wrapper; + /// + /// let wrapper = Wrapper::new(15).initial_indent(" "); + /// ``` + /// + /// [`self.initial_indent`]: #structfield.initial_indent + pub fn initial_indent(self, indent: &'a str) -> Wrapper<'a, S> { + Wrapper { + initial_indent: indent, + ..self + } + } + + /// Change [`self.subsequent_indent`]. The subsequent indentation + /// is used on lines following the first line of output. + /// + /// # Examples + /// + /// Combining initial and subsequent indentation lets you format a + /// single paragraph as a bullet list: + /// + /// ```no_run + /// # #![allow(unused_variables)] + /// use textwrap::Wrapper; + /// + /// let wrapper = Wrapper::new(15) + /// .initial_indent("* ") + /// .subsequent_indent(" "); + /// ``` + /// + /// [`self.subsequent_indent`]: #structfield.subsequent_indent + pub fn subsequent_indent(self, indent: &'a str) -> Wrapper<'a, S> { + Wrapper { + subsequent_indent: indent, + ..self + } + } + + /// Change [`self.break_words`]. This controls if words longer + /// than `self.width` can be broken, or if they will be left + /// sticking out into the right margin. + /// + /// [`self.break_words`]: #structfield.break_words + pub fn break_words(self, setting: bool) -> Wrapper<'a, S> { + Wrapper { + break_words: setting, + ..self + } + } + + /// Fill a line of text at `self.width` characters. Strings are + /// wrapped based on their displayed width, not their size in + /// bytes. + /// + /// The result is a string with newlines between each line. Use + /// the `wrap` method if you need access to the individual lines. + /// + /// # Complexities + /// + /// This method simply joins the lines produced by `wrap_iter`. As + /// such, it inherits the O(*n*) time and memory complexity where + /// *n* is the input string length. + /// + /// # Examples + /// + /// ``` + /// use textwrap::Wrapper; + /// + /// let wrapper = Wrapper::new(15); + /// assert_eq!(wrapper.fill("Memory safety without garbage collection."), + /// "Memory safety\nwithout garbage\ncollection."); + /// ``` + pub fn fill(&self, s: &str) -> String { + // This will avoid reallocation in simple cases (no + // indentation, no hyphenation). + let mut result = String::with_capacity(s.len()); + + for (i, line) in self.wrap_iter(s).enumerate() { + if i > 0 { + result.push('\n'); + } + result.push_str(&line); + } + + result + } + + /// Wrap a line of text at `self.width` characters. Strings are + /// wrapped based on their displayed width, not their size in + /// bytes. + /// + /// # Complexities + /// + /// This method simply collects the lines produced by `wrap_iter`. + /// As such, it inherits the O(*n*) overall time and memory + /// complexity where *n* is the input string length. + /// + /// # Examples + /// + /// ``` + /// use textwrap::Wrapper; + /// + /// let wrap15 = Wrapper::new(15); + /// assert_eq!(wrap15.wrap("Concurrency without data races."), + /// vec!["Concurrency", + /// "without data", + /// "races."]); + /// + /// let wrap20 = Wrapper::new(20); + /// assert_eq!(wrap20.wrap("Concurrency without data races."), + /// vec!["Concurrency without", + /// "data races."]); + /// ``` + /// + /// Notice that newlines in the input are preserved. This means + /// that they force a line break, regardless of how long the + /// current line is: + /// + /// ``` + /// use textwrap::Wrapper; + /// + /// let wrapper = Wrapper::new(40); + /// assert_eq!(wrapper.wrap("First line.\nSecond line."), + /// vec!["First line.", "Second line."]); + /// ``` + /// + pub fn wrap(&self, s: &'a str) -> Vec<Cow<'a, str>> { + self.wrap_iter(s).collect::<Vec<_>>() + } + + /// Lazily wrap a line of text at `self.width` characters. Strings + /// are wrapped based on their displayed width, not their size in + /// bytes. + /// + /// The [`WordSplitter`] stored in [`self.splitter`] is used + /// whenever when a word is too large to fit on the current line. + /// By changing the field, different hyphenation strategies can be + /// implemented. + /// + /// # Complexities + /// + /// This method returns a [`WrapIter`] iterator which borrows this + /// `Wrapper`. The algorithm used has a linear complexity, so + /// getting the next line from the iterator will take O(*w*) time, + /// where *w* is the wrapping width. Fully processing the iterator + /// will take O(*n*) time for an input string of length *n*. + /// + /// When no indentation is used, each line returned is a slice of + /// the input string and the memory overhead is thus constant. + /// Otherwise new memory is allocated for each line returned. + /// + /// # Examples + /// + /// ``` + /// use std::borrow::Cow; + /// use textwrap::Wrapper; + /// + /// let wrap20 = Wrapper::new(20); + /// let mut wrap20_iter = wrap20.wrap_iter("Zero-cost abstractions."); + /// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost"))); + /// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions."))); + /// assert_eq!(wrap20_iter.next(), None); + /// + /// let wrap25 = Wrapper::new(25); + /// let mut wrap25_iter = wrap25.wrap_iter("Zero-cost abstractions."); + /// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions."))); + /// assert_eq!(wrap25_iter.next(), None); + /// ``` + /// + /// [`self.splitter`]: #structfield.splitter + /// [`WordSplitter`]: trait.WordSplitter.html + /// [`WrapIter`]: struct.WrapIter.html + pub fn wrap_iter<'w>(&'w self, s: &'a str) -> WrapIter<'w, 'a, S> { + WrapIter { + wrapper: self, + inner: WrapIterImpl::new(self, s), + } + } + + /// Lazily wrap a line of text at `self.width` characters. Strings + /// are wrapped based on their displayed width, not their size in + /// bytes. + /// + /// The [`WordSplitter`] stored in [`self.splitter`] is used + /// whenever when a word is too large to fit on the current line. + /// By changing the field, different hyphenation strategies can be + /// implemented. + /// + /// # Complexities + /// + /// This method consumes the `Wrapper` and returns a + /// [`IntoWrapIter`] iterator. Fully processing the iterator has + /// the same O(*n*) time complexity as [`wrap_iter`], where *n* is + /// the length of the input string. + /// + /// # Examples + /// + /// ``` + /// use std::borrow::Cow; + /// use textwrap::Wrapper; + /// + /// let wrap20 = Wrapper::new(20); + /// let mut wrap20_iter = wrap20.into_wrap_iter("Zero-cost abstractions."); + /// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost"))); + /// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions."))); + /// assert_eq!(wrap20_iter.next(), None); + /// ``` + /// + /// [`self.splitter`]: #structfield.splitter + /// [`WordSplitter`]: trait.WordSplitter.html + /// [`IntoWrapIter`]: struct.IntoWrapIter.html + /// [`wrap_iter`]: #method.wrap_iter + pub fn into_wrap_iter(self, s: &'a str) -> IntoWrapIter<'a, S> { + let inner = WrapIterImpl::new(&self, s); + + IntoWrapIter { + wrapper: self, + inner: inner, + } + } +} + +/// An iterator over the lines of the input string which owns a +/// `Wrapper`. An instance of `IntoWrapIter` is typically obtained +/// through either [`wrap_iter`] or [`Wrapper::into_wrap_iter`]. +/// +/// Each call of `.next()` method yields a line wrapped in `Some` if the +/// input hasn't been fully processed yet. Otherwise it returns `None`. +/// +/// [`wrap_iter`]: fn.wrap_iter.html +/// [`Wrapper::into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter +#[derive(Debug)] +pub struct IntoWrapIter<'a, S: WordSplitter> { + wrapper: Wrapper<'a, S>, + inner: WrapIterImpl<'a>, +} + +impl<'a, S: WordSplitter> Iterator for IntoWrapIter<'a, S> { + type Item = Cow<'a, str>; + + fn next(&mut self) -> Option<Cow<'a, str>> { + self.inner.next(&self.wrapper) + } +} + +/// An iterator over the lines of the input string which borrows a +/// `Wrapper`. An instance of `WrapIter` is typically obtained +/// through the [`Wrapper::wrap_iter`] method. +/// +/// Each call of `.next()` method yields a line wrapped in `Some` if the +/// input hasn't been fully processed yet. Otherwise it returns `None`. +/// +/// [`Wrapper::wrap_iter`]: struct.Wrapper.html#method.wrap_iter +#[derive(Debug)] +pub struct WrapIter<'w, 'a: 'w, S: WordSplitter + 'w> { + wrapper: &'w Wrapper<'a, S>, + inner: WrapIterImpl<'a>, +} + +impl<'w, 'a: 'w, S: WordSplitter> Iterator for WrapIter<'w, 'a, S> { + type Item = Cow<'a, str>; + + fn next(&mut self) -> Option<Cow<'a, str>> { + self.inner.next(self.wrapper) + } +} + +/// Like `char::is_whitespace`, but non-breaking spaces don't count. +#[inline] +fn is_whitespace(ch: char) -> bool { + ch.is_whitespace() && ch != NBSP +} + +/// Common implementation details for `WrapIter` and `IntoWrapIter`. +#[derive(Debug)] +struct WrapIterImpl<'a> { + // String to wrap. + source: &'a str, + // CharIndices iterator over self.source. + char_indices: CharIndices<'a>, + // Byte index where the current line starts. + start: usize, + // Byte index of the last place where the string can be split. + split: usize, + // Size in bytes of the character at self.source[self.split]. + split_len: usize, + // Width of self.source[self.start..idx]. + line_width: usize, + // Width of self.source[self.start..self.split]. + line_width_at_split: usize, + // Tracking runs of whitespace characters. + in_whitespace: bool, + // Has iterator finished producing elements? + finished: bool, +} + +impl<'a> WrapIterImpl<'a> { + fn new<S: WordSplitter>(wrapper: &Wrapper<'a, S>, s: &'a str) -> WrapIterImpl<'a> { + WrapIterImpl { + source: s, + char_indices: s.char_indices(), + start: 0, + split: 0, + split_len: 0, + line_width: wrapper.initial_indent.width(), + line_width_at_split: wrapper.initial_indent.width(), + in_whitespace: false, + finished: false, + } + } + + fn create_result_line<S: WordSplitter>(&self, wrapper: &Wrapper<'a, S>) -> Cow<'a, str> { + if self.start == 0 { + Cow::from(wrapper.initial_indent) + } else { + Cow::from(wrapper.subsequent_indent) + } + } + + fn next<S: WordSplitter>(&mut self, wrapper: &Wrapper<'a, S>) -> Option<Cow<'a, str>> { + if self.finished { + return None; + } + + while let Some((idx, ch)) = self.char_indices.next() { + let char_width = ch.width().unwrap_or(0); + let char_len = ch.len_utf8(); + + if ch == '\n' { + self.split = idx; + self.split_len = char_len; + self.line_width_at_split = self.line_width; + self.in_whitespace = false; + + // If this is not the final line, return the current line. Otherwise, + // we will return the line with its line break after exiting the loop + if self.split + self.split_len < self.source.len() { + let mut line = self.create_result_line(wrapper); + line += &self.source[self.start..self.split]; + + self.start = self.split + self.split_len; + self.line_width = wrapper.subsequent_indent.width(); + + return Some(line); + } + } else if is_whitespace(ch) { + // Extend the previous split or create a new one. + if self.in_whitespace { + self.split_len += char_len; + } else { + self.split = idx; + self.split_len = char_len; + } + self.line_width_at_split = self.line_width + char_width; + self.in_whitespace = true; + } else if self.line_width + char_width > wrapper.width { + // There is no room for this character on the current + // line. Try to split the final word. + self.in_whitespace = false; + let remaining_text = &self.source[self.split + self.split_len..]; + let final_word = match remaining_text.find(is_whitespace) { + Some(i) => &remaining_text[..i], + None => remaining_text, + }; + + let mut hyphen = ""; + let splits = wrapper.splitter.split(final_word); + for &(head, hyp, _) in splits.iter().rev() { + if self.line_width_at_split + head.width() + hyp.width() <= wrapper.width { + // We can fit head into the current line. + // Advance the split point by the width of the + // whitespace and the head length. + self.split += self.split_len + head.len(); + self.split_len = 0; + hyphen = hyp; + break; + } + } + + if self.start >= self.split { + // The word is too big to fit on a single line, so we + // need to split it at the current index. + if wrapper.break_words { + // Break work at current index. + self.split = idx; + self.split_len = 0; + self.line_width_at_split = self.line_width; + } else { + // Add smallest split. + self.split = self.start + splits[0].0.len(); + self.split_len = 0; + self.line_width_at_split = self.line_width; + } + } + + if self.start < self.split { + let mut line = self.create_result_line(wrapper); + line += &self.source[self.start..self.split]; + line += hyphen; + + self.start = self.split + self.split_len; + self.line_width += wrapper.subsequent_indent.width(); + self.line_width -= self.line_width_at_split; + self.line_width += char_width; + + return Some(line); + } + } else { + self.in_whitespace = false; + } + self.line_width += char_width; + } + + self.finished = true; + + // Add final line. + if self.start < self.source.len() { + let mut line = self.create_result_line(wrapper); + line += &self.source[self.start..]; + return Some(line); + } + + None + } +} + +/// Return the current terminal width. If the terminal width cannot be +/// determined (typically because the standard output is not connected +/// to a terminal), a default width of 80 characters will be used. +/// +/// # Examples +/// +/// Create a `Wrapper` for the current terminal with a two column +/// margin: +/// +/// ```no_run +/// # #![allow(unused_variables)] +/// use textwrap::{Wrapper, NoHyphenation, termwidth}; +/// +/// let width = termwidth() - 4; // Two columns on each side. +/// let wrapper = Wrapper::with_splitter(width, NoHyphenation) +/// .initial_indent(" ") +/// .subsequent_indent(" "); +/// ``` +#[cfg(feature = "term_size")] +pub fn termwidth() -> usize { + term_size::dimensions_stdout().map_or(80, |(w, _)| w) +} + +/// Fill a line of text at `width` characters. Strings are wrapped +/// based on their displayed width, not their size in bytes. +/// +/// The result is a string with newlines between each line. Use +/// [`wrap`] if you need access to the individual lines or +/// [`wrap_iter`] for its iterator counterpart. +/// +/// ``` +/// use textwrap::fill; +/// +/// assert_eq!(fill("Memory safety without garbage collection.", 15), +/// "Memory safety\nwithout garbage\ncollection."); +/// ``` +/// +/// This function creates a Wrapper on the fly with default settings. +/// If you need to set a language corpus for automatic hyphenation, or +/// need to fill many strings, then it is suggested to create a Wrapper +/// and call its [`fill` method]. +/// +/// [`wrap`]: fn.wrap.html +/// [`wrap_iter`]: fn.wrap_iter.html +/// [`fill` method]: struct.Wrapper.html#method.fill +pub fn fill(s: &str, width: usize) -> String { + Wrapper::new(width).fill(s) +} + +/// Wrap a line of text at `width` characters. Strings are wrapped +/// based on their displayed width, not their size in bytes. +/// +/// This function creates a Wrapper on the fly with default settings. +/// If you need to set a language corpus for automatic hyphenation, or +/// need to wrap many strings, then it is suggested to create a Wrapper +/// and call its [`wrap` method]. +/// +/// The result is a vector of strings. Use [`wrap_iter`] if you need an +/// iterator version. +/// +/// # Examples +/// +/// ``` +/// use textwrap::wrap; +/// +/// assert_eq!(wrap("Concurrency without data races.", 15), +/// vec!["Concurrency", +/// "without data", +/// "races."]); +/// +/// assert_eq!(wrap("Concurrency without data races.", 20), +/// vec!["Concurrency without", +/// "data races."]); +/// ``` +/// +/// [`wrap_iter`]: fn.wrap_iter.html +/// [`wrap` method]: struct.Wrapper.html#method.wrap +pub fn wrap(s: &str, width: usize) -> Vec<Cow<str>> { + Wrapper::new(width).wrap(s) +} + +/// Lazily wrap a line of text at `width` characters. Strings are +/// wrapped based on their displayed width, not their size in bytes. +/// +/// This function creates a Wrapper on the fly with default settings. +/// It then calls the [`into_wrap_iter`] method. Hence, the return +/// value is an [`IntoWrapIter`], not a [`WrapIter`] as the function +/// name would otherwise suggest. +/// +/// If you need to set a language corpus for automatic hyphenation, or +/// need to wrap many strings, then it is suggested to create a Wrapper +/// and call its [`wrap_iter`] or [`into_wrap_iter`] methods. +/// +/// # Examples +/// +/// ``` +/// use std::borrow::Cow; +/// use textwrap::wrap_iter; +/// +/// let mut wrap20_iter = wrap_iter("Zero-cost abstractions.", 20); +/// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost"))); +/// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions."))); +/// assert_eq!(wrap20_iter.next(), None); +/// +/// let mut wrap25_iter = wrap_iter("Zero-cost abstractions.", 25); +/// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions."))); +/// assert_eq!(wrap25_iter.next(), None); +/// ``` +/// +/// [`wrap_iter`]: struct.Wrapper.html#method.wrap_iter +/// [`into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter +/// [`IntoWrapIter`]: struct.IntoWrapIter.html +/// [`WrapIter`]: struct.WrapIter.html +pub fn wrap_iter(s: &str, width: usize) -> IntoWrapIter<HyphenSplitter> { + Wrapper::new(width).into_wrap_iter(s) +} + +#[cfg(test)] +mod tests { + #[cfg(feature = "hyphenation")] + extern crate hyphenation; + + use super::*; + #[cfg(feature = "hyphenation")] + use hyphenation::{Language, Load, Standard}; + + #[test] + fn no_wrap() { + assert_eq!(wrap("foo", 10), vec!["foo"]); + } + + #[test] + fn simple() { + assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]); + } + + #[test] + fn multi_word_on_line() { + assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]); + } + + #[test] + fn long_word() { + assert_eq!(wrap("foo", 0), vec!["f", "o", "o"]); + } + + #[test] + fn long_words() { + assert_eq!(wrap("foo bar", 0), vec!["f", "o", "o", "b", "a", "r"]); + } + + #[test] + fn max_width() { + assert_eq!(wrap("foo bar", usize::max_value()), vec!["foo bar"]); + } + + #[test] + fn leading_whitespace() { + assert_eq!(wrap(" foo bar", 6), vec![" foo", "bar"]); + } + + #[test] + fn trailing_whitespace() { + assert_eq!(wrap("foo bar ", 6), vec!["foo", "bar "]); + } + + #[test] + fn interior_whitespace() { + assert_eq!(wrap("foo: bar baz", 10), vec!["foo: bar", "baz"]); + } + + #[test] + fn extra_whitespace_start_of_line() { + // Whitespace is only significant inside a line. After a line + // gets too long and is broken, the first word starts in + // column zero and is not indented. The line before might end + // up with trailing whitespace. + assert_eq!(wrap("foo bar", 5), vec!["foo", "bar"]); + } + + #[test] + fn issue_99() { + // We did not reset the in_whitespace flag correctly and did + // not handle single-character words after a line break. + assert_eq!( + wrap("aaabbbccc x yyyzzzwww", 9), + vec!["aaabbbccc", "x", "yyyzzzwww"] + ); + } + + #[test] + fn issue_129() { + // The dash is an em-dash which takes up four bytes. We used + // to panic since we tried to index into the character. + assert_eq!(wrap("x – x", 1), vec!["x", "–", "x"]); + } + + #[test] + fn wide_character_handling() { + assert_eq!(wrap("Hello, World!", 15), vec!["Hello, World!"]); + assert_eq!( + wrap("Hello, World!", 15), + vec!["Hello,", "World!"] + ); + } + + #[test] + fn empty_input_not_indented() { + let wrapper = Wrapper::new(10).initial_indent("!!!"); + assert_eq!(wrapper.fill(""), ""); + } + + #[test] + fn indent_single_line() { + let wrapper = Wrapper::new(10).initial_indent(">>>"); // No trailing space + assert_eq!(wrapper.fill("foo"), ">>>foo"); + } + + #[test] + fn indent_multiple_lines() { + let wrapper = Wrapper::new(6).initial_indent("* ").subsequent_indent(" "); + assert_eq!(wrapper.wrap("foo bar baz"), vec!["* foo", " bar", " baz"]); + } + + #[test] + fn indent_break_words() { + let wrapper = Wrapper::new(5).initial_indent("* ").subsequent_indent(" "); + assert_eq!(wrapper.wrap("foobarbaz"), vec!["* foo", " bar", " baz"]); + } + + #[test] + fn hyphens() { + assert_eq!(wrap("foo-bar", 5), vec!["foo-", "bar"]); + } + + #[test] + fn trailing_hyphen() { + let wrapper = Wrapper::new(5).break_words(false); + assert_eq!(wrapper.wrap("foobar-"), vec!["foobar-"]); + } + + #[test] + fn multiple_hyphens() { + assert_eq!(wrap("foo-bar-baz", 5), vec!["foo-", "bar-", "baz"]); + } + + #[test] + fn hyphens_flag() { + let wrapper = Wrapper::new(5).break_words(false); + assert_eq!( + wrapper.wrap("The --foo-bar flag."), + vec!["The", "--foo-", "bar", "flag."] + ); + } + + #[test] + fn repeated_hyphens() { + let wrapper = Wrapper::new(4).break_words(false); + assert_eq!(wrapper.wrap("foo--bar"), vec!["foo--bar"]); + } + + #[test] + fn hyphens_alphanumeric() { + assert_eq!(wrap("Na2-CH4", 5), vec!["Na2-", "CH4"]); + } + + #[test] + fn hyphens_non_alphanumeric() { + let wrapper = Wrapper::new(5).break_words(false); + assert_eq!(wrapper.wrap("foo(-)bar"), vec!["foo(-)bar"]); + } + + #[test] + fn multiple_splits() { + assert_eq!(wrap("foo-bar-baz", 9), vec!["foo-bar-", "baz"]); + } + + #[test] + fn forced_split() { + let wrapper = Wrapper::new(5).break_words(false); + assert_eq!(wrapper.wrap("foobar-baz"), vec!["foobar-", "baz"]); + } + + #[test] + fn no_hyphenation() { + let wrapper = Wrapper::with_splitter(8, NoHyphenation); + assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]); + } + + #[test] + #[cfg(feature = "hyphenation")] + fn auto_hyphenation() { + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let wrapper = Wrapper::new(10); + assert_eq!( + wrapper.wrap("Internationalization"), + vec!["Internatio", "nalization"] + ); + + let wrapper = Wrapper::with_splitter(10, dictionary); + assert_eq!( + wrapper.wrap("Internationalization"), + vec!["Interna-", "tionaliza-", "tion"] + ); + } + + #[test] + #[cfg(feature = "hyphenation")] + fn split_len_hyphenation() { + // Test that hyphenation takes the width of the wihtespace + // into account. + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let wrapper = Wrapper::with_splitter(15, dictionary); + assert_eq!( + wrapper.wrap("garbage collection"), + vec!["garbage col-", "lection"] + ); + } + + #[test] + #[cfg(feature = "hyphenation")] + fn borrowed_lines() { + // Lines that end with an extra hyphen are owned, the final + // line is borrowed. + use std::borrow::Cow::{Borrowed, Owned}; + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let wrapper = Wrapper::with_splitter(10, dictionary); + let lines = wrapper.wrap("Internationalization"); + if let Borrowed(s) = lines[0] { + assert!(false, "should not have been borrowed: {:?}", s); + } + if let Borrowed(s) = lines[1] { + assert!(false, "should not have been borrowed: {:?}", s); + } + if let Owned(ref s) = lines[2] { + assert!(false, "should not have been owned: {:?}", s); + } + } + + #[test] + #[cfg(feature = "hyphenation")] + fn auto_hyphenation_with_hyphen() { + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let wrapper = Wrapper::new(8).break_words(false); + assert_eq!(wrapper.wrap("over-caffinated"), vec!["over-", "caffinated"]); + + let wrapper = Wrapper::with_splitter(8, dictionary).break_words(false); + assert_eq!( + wrapper.wrap("over-caffinated"), + vec!["over-", "caffi-", "nated"] + ); + } + + #[test] + fn break_words() { + assert_eq!(wrap("foobarbaz", 3), vec!["foo", "bar", "baz"]); + } + + #[test] + fn break_words_wide_characters() { + assert_eq!(wrap("Hello", 5), vec!["He", "ll", "o"]); + } + + #[test] + fn break_words_zero_width() { + assert_eq!(wrap("foobar", 0), vec!["f", "o", "o", "b", "a", "r"]); + } + + #[test] + fn break_words_line_breaks() { + assert_eq!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl"); + assert_eq!(fill("abcdefgh\nijkl", 5), "abcde\nfgh\nijkl"); + } + + #[test] + fn preserve_line_breaks() { + assert_eq!(fill("test\n", 11), "test\n"); + assert_eq!(fill("test\n\na\n\n", 11), "test\n\na\n\n"); + assert_eq!(fill("1 3 5 7\n1 3 5 7", 7), "1 3 5 7\n1 3 5 7"); + } + + #[test] + fn wrap_preserve_line_breaks() { + assert_eq!(fill("1 3 5 7\n1 3 5 7", 5), "1 3 5\n7\n1 3 5\n7"); + } + + #[test] + fn non_breaking_space() { + let wrapper = Wrapper::new(5).break_words(false); + assert_eq!(wrapper.fill("foo bar baz"), "foo bar baz"); + } + + #[test] + fn non_breaking_hyphen() { + let wrapper = Wrapper::new(5).break_words(false); + assert_eq!(wrapper.fill("foo‑bar‑baz"), "foo‑bar‑baz"); + } + + #[test] + fn fill_simple() { + assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz"); + } +} diff --git a/bash-5.1/vendor/textwrap/src/splitting.rs b/bash-5.1/vendor/textwrap/src/splitting.rs new file mode 100644 index 0000000..f6b65af --- /dev/null +++ b/bash-5.1/vendor/textwrap/src/splitting.rs @@ -0,0 +1,139 @@ +//! Word splitting functionality. +//! +//! To wrap text into lines, long words sometimes need to be split +//! across lines. The [`WordSplitter`] trait defines this +//! functionality. [`HyphenSplitter`] is the default implementation of +//! this treat: it will simply split words on existing hyphens. + +#[cfg(feature = "hyphenation")] +use hyphenation::{Hyphenator, Standard}; + +/// An interface for splitting words. +/// +/// When the [`wrap_iter`] method will try to fit text into a line, it +/// will eventually find a word that it too large the current text +/// width. It will then call the currently configured `WordSplitter` to +/// have it attempt to split the word into smaller parts. This trait +/// describes that functionality via the [`split`] method. +/// +/// If the `textwrap` crate has been compiled with the `hyphenation` +/// feature enabled, you will find an implementation of `WordSplitter` +/// by the `hyphenation::language::Corpus` struct. Use this struct for +/// language-aware hyphenation. See the [`hyphenation` documentation] +/// for details. +/// +/// [`wrap_iter`]: ../struct.Wrapper.html#method.wrap_iter +/// [`split`]: #tymethod.split +/// [`hyphenation` documentation]: https://docs.rs/hyphenation/ +pub trait WordSplitter { + /// Return all possible splits of word. Each split is a triple + /// with a head, a hyphen, and a tail where `head + &hyphen + + /// &tail == word`. The hyphen can be empty if there is already a + /// hyphen in the head. + /// + /// The splits should go from smallest to longest and should + /// include no split at all. So the word "technology" could be + /// split into + /// + /// ```no_run + /// vec![("tech", "-", "nology"), + /// ("technol", "-", "ogy"), + /// ("technolo", "-", "gy"), + /// ("technology", "", "")]; + /// ``` + fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)>; +} + +/// Use this as a [`Wrapper.splitter`] to avoid any kind of +/// hyphenation: +/// +/// ``` +/// use textwrap::{Wrapper, NoHyphenation}; +/// +/// let wrapper = Wrapper::with_splitter(8, NoHyphenation); +/// assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]); +/// ``` +/// +/// [`Wrapper.splitter`]: ../struct.Wrapper.html#structfield.splitter +#[derive(Clone, Debug)] +pub struct NoHyphenation; + +/// `NoHyphenation` implements `WordSplitter` by not splitting the +/// word at all. +impl WordSplitter for NoHyphenation { + fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> { + vec![(word, "", "")] + } +} + +/// Simple and default way to split words: splitting on existing +/// hyphens only. +/// +/// You probably don't need to use this type since it's already used +/// by default by `Wrapper::new`. +#[derive(Clone, Debug)] +pub struct HyphenSplitter; + +/// `HyphenSplitter` is the default `WordSplitter` used by +/// `Wrapper::new`. It will split words on any existing hyphens in the +/// word. +/// +/// It will only use hyphens that are surrounded by alphanumeric +/// characters, which prevents a word like "--foo-bar" from being +/// split on the first or second hyphen. +impl WordSplitter for HyphenSplitter { + fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> { + let mut triples = Vec::new(); + // Split on hyphens, smallest split first. We only use hyphens + // that are surrounded by alphanumeric characters. This is to + // avoid splitting on repeated hyphens, such as those found in + // --foo-bar. + let mut char_indices = word.char_indices(); + // Early return if the word is empty. + let mut prev = match char_indices.next() { + None => return vec![(word, "", "")], + Some((_, ch)) => ch, + }; + + // Find current word, or return early if the word only has a + // single character. + let (mut idx, mut cur) = match char_indices.next() { + None => return vec![(word, "", "")], + Some((idx, cur)) => (idx, cur), + }; + + for (i, next) in char_indices { + if prev.is_alphanumeric() && cur == '-' && next.is_alphanumeric() { + let (head, tail) = word.split_at(idx + 1); + triples.push((head, "", tail)); + } + prev = cur; + idx = i; + cur = next; + } + + // Finally option is no split at all. + triples.push((word, "", "")); + + triples + } +} + +/// A hyphenation dictionary can be used to do language-specific +/// hyphenation using patterns from the hyphenation crate. +#[cfg(feature = "hyphenation")] +impl WordSplitter for Standard { + fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> { + // Find splits based on language dictionary. + let mut triples = Vec::new(); + for n in self.hyphenate(word).breaks { + let (head, tail) = word.split_at(n); + let hyphen = if head.ends_with('-') { "" } else { "-" }; + triples.push((head, hyphen, tail)); + } + // Finally option is no split at all. + triples.push((word, "", "")); + + triples + } +} diff --git a/bash-5.1/vendor/textwrap/tests/version-numbers.rs b/bash-5.1/vendor/textwrap/tests/version-numbers.rs new file mode 100644 index 0000000..85c52e3 --- /dev/null +++ b/bash-5.1/vendor/textwrap/tests/version-numbers.rs @@ -0,0 +1,17 @@ +#[macro_use] +extern crate version_sync; + +#[test] +fn test_readme_deps() { + assert_markdown_deps_updated!("README.md"); +} + +#[test] +fn test_readme_changelog() { + assert_contains_regex!("README.md", r"^### Version {version} — .* \d\d?.., 20\d\d$"); +} + +#[test] +fn test_html_root_url() { + assert_html_root_url_updated!("src/lib.rs"); +} diff --git a/bash-5.1/vendor/thiserror-impl/.cargo-checksum.json b/bash-5.1/vendor/thiserror-impl/.cargo-checksum.json index 002cf21..e398ffb 100644 --- a/bash-5.1/vendor/thiserror-impl/.cargo-checksum.json +++ b/bash-5.1/vendor/thiserror-impl/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"3171e8d362ab2f3958292eb1862426b9206637c2941edbc482460f5e0b04c9d0","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","src/ast.rs":"c7601e8394f5ee304365c520181f0dbeaa807ddaa71ce4a8618ea1a70f81b3b2","src/attr.rs":"d1fe75dde04cb8df6da4e1aaec5b38c2b0f634fa3432877993b3fec4cc08b6b5","src/expand.rs":"791000b41cc09250c04dbf2f7adc06f1254922986c86633471e934621ce31940","src/fmt.rs":"d63d39120c18712596f9f2a1715821148c2becd4d8bad5bc1b307210a84dbe98","src/generics.rs":"2076cde22271be355a8131a77add4b93f83ab0af4317cd2df5471fffa4f95c66","src/lib.rs":"7d023310cd3db670554ce108a6afd94e1ae3c55c83661d4b9fcebdf1865b9e4b","src/prop.rs":"6709932aee8f9d217f40cd644629c0ecb2f46d333ae8a1398e8d745534f4e028","src/valid.rs":"ac95253944fd360d3578d0643a7baabb2cfa6bf9fbced7a6ce1f7b0529a3bb98"},"package":"c251e90f708e16c49a16f4917dc2131e75222b72edfa9cb7f7c58ae56aae0c09"} \ No newline at end of file +{"files":{"Cargo.toml":"af63bbe7a8ec50e29f44aa648a65afd05486852589b467030d28bbd7e0c878f4","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","src/ast.rs":"c7601e8394f5ee304365c520181f0dbeaa807ddaa71ce4a8618ea1a70f81b3b2","src/attr.rs":"d1fe75dde04cb8df6da4e1aaec5b38c2b0f634fa3432877993b3fec4cc08b6b5","src/expand.rs":"8e2bc7ca24e8f8d9b179b792e772d3699154b750a08dcb942be298b7cc032563","src/fmt.rs":"d63d39120c18712596f9f2a1715821148c2becd4d8bad5bc1b307210a84dbe98","src/generics.rs":"2076cde22271be355a8131a77add4b93f83ab0af4317cd2df5471fffa4f95c66","src/lib.rs":"7d023310cd3db670554ce108a6afd94e1ae3c55c83661d4b9fcebdf1865b9e4b","src/prop.rs":"6709932aee8f9d217f40cd644629c0ecb2f46d333ae8a1398e8d745534f4e028","src/valid.rs":"ac95253944fd360d3578d0643a7baabb2cfa6bf9fbced7a6ce1f7b0529a3bb98"},"package":"982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"} \ No newline at end of file diff --git a/bash-5.1/vendor/thiserror-impl/Cargo.toml b/bash-5.1/vendor/thiserror-impl/Cargo.toml index c377ae0..9f83239 100644 --- a/bash-5.1/vendor/thiserror-impl/Cargo.toml +++ b/bash-5.1/vendor/thiserror-impl/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.31" name = "thiserror-impl" -version = "1.0.33" +version = "1.0.37" authors = ["David Tolnay <dtolnay@gmail.com>"] description = "Implementation detail of the `thiserror` crate" license = "MIT OR Apache-2.0" diff --git a/bash-5.1/vendor/thiserror-impl/src/expand.rs b/bash-5.1/vendor/thiserror-impl/src/expand.rs index f2f7116..4352209 100644 --- a/bash-5.1/vendor/thiserror-impl/src/expand.rs +++ b/bash-5.1/vendor/thiserror-impl/src/expand.rs @@ -67,12 +67,12 @@ fn impl_struct(input: Struct) -> TokenStream { let source_provide = if type_is_option(source_field.ty) { quote_spanned! {source.span()=> if let std::option::Option::Some(source) = &self.#source { - source.as_dyn_error().provide(#demand); + source.thiserror_provide(#demand); } } } else { quote_spanned! {source.span()=> - self.#source.as_dyn_error().provide(#demand); + self.#source.thiserror_provide(#demand); } }; let self_provide = if source == backtrace { @@ -89,7 +89,7 @@ fn impl_struct(input: Struct) -> TokenStream { }) }; quote! { - use thiserror::__private::AsDynError; + use thiserror::__private::ThiserrorProvide; #source_provide #self_provide } @@ -259,12 +259,12 @@ fn impl_enum(input: Enum) -> TokenStream { let source_provide = if type_is_option(source_field.ty) { quote_spanned! {source.span()=> if let std::option::Option::Some(source) = #varsource { - source.as_dyn_error().provide(#demand); + source.thiserror_provide(#demand); } } } else { quote_spanned! {source.span()=> - #varsource.as_dyn_error().provide(#demand); + #varsource.thiserror_provide(#demand); } }; let self_provide = if type_is_option(backtrace_field.ty) { @@ -284,7 +284,7 @@ fn impl_enum(input: Enum) -> TokenStream { #source: #varsource, .. } => { - use thiserror::__private::AsDynError; + use thiserror::__private::ThiserrorProvide; #source_provide #self_provide } @@ -298,17 +298,17 @@ fn impl_enum(input: Enum) -> TokenStream { let source_provide = if type_is_option(source_field.ty) { quote_spanned! {backtrace.span()=> if let std::option::Option::Some(source) = #varsource { - source.as_dyn_error().provide(#demand); + source.thiserror_provide(#demand); } } } else { quote_spanned! {backtrace.span()=> - #varsource.as_dyn_error().provide(#demand); + #varsource.thiserror_provide(#demand); } }; quote! { #ty::#ident {#backtrace: #varsource, ..} => { - use thiserror::__private::AsDynError; + use thiserror::__private::ThiserrorProvide; #source_provide } } diff --git a/bash-5.1/vendor/thiserror/.cargo-checksum.json b/bash-5.1/vendor/thiserror/.cargo-checksum.json index f62a313..b82148e 100644 --- a/bash-5.1/vendor/thiserror/.cargo-checksum.json +++ b/bash-5.1/vendor/thiserror/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"0de812f611be41d9b1962bdcb235479fed9d9d48eed22033fdb0c2cadbb0e602","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"f774d4cb12047fef7c65a86e00eb7299f9250e0bc1aa445d16f63162ec942551","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/aserror.rs":"3dd14cfcfe4a0ab8b1dd774e4ea0a0197989afe84e0687e73873b61cfa4347fa","src/display.rs":"63c492bfa8b8e9180ad5abcbe63c1173b4ad490c47ec33cac9a338f96c8f8e42","src/lib.rs":"62b459b2bf9b53647570511189ed4980a0aed10a9f49abec7c34cef53178a6b2","tests/compiletest.rs":"022a8e400ef813d7ea1875b944549cee5125f6a995dc33e93b48cba3e1b57bd1","tests/test_backtrace.rs":"43323a073ca464b16e213869d3f459f07a0f9601f1516ec81371c825fb1ec8f2","tests/test_display.rs":"20fdc8903f06da3a698ef4377cccca26a71138ca6de67310c5bdb8a9fcb39d83","tests/test_error.rs":"d06dca3c38f22d7ce4e27dadd6c0f78e5cefe3a2ebbc5fe44abc9ddd5ee1985f","tests/test_expr.rs":"388402702a3be4ffcd0574d66733e8932bf7d5de37544a00ecb0e4f8d8246da4","tests/test_from.rs":"de1347e62069f826d8616b9e45ce6cccc3a8a8049cb51bd22d6763efe6118b0c","tests/test_generics.rs":"4f33747e3f62550d5af94687679af230ef92fbb3247ae4b41df46792a040e4dc","tests/test_lints.rs":"c17d79d77edfcdd4b8f6dcdcd1c70ad065cfbc747e1a618ac6343315d0b59ea4","tests/test_option.rs":"3a82af1ad206444b9955e3f2fda508d70f887ad0b7f7986bafc17496f63b07ab","tests/test_path.rs":"ef5452c7e828a0179f5ace7e19f95b9762aa887caf10244adbfe36ded712c090","tests/test_source.rs":"f2f04f11bf8a709eddb1c68f113cda0c2be87e56800d6b9d991bedd545b4642f","tests/test_transparent.rs":"cd8d5be14d00d610a1782104bea6c013618501dab5c3625178ecfcf66e31f939","tests/ui/bad-field-attr.rs":"c5b567e3091969a01061843fb2d95c5e1aa3fa81edfeecdf416a84a6fba40aa8","tests/ui/bad-field-attr.stderr":"78f576d5ec66464a77f1cdf0f5bb7dcdf18f7f04f1165983a6239ec59d908ea3","tests/ui/concat-display.rs":"3995bd6b3bdd67df7bb16499775d89600c0dd20895633fe807396a64c117078d","tests/ui/concat-display.stderr":"256dfde61ee689ebe51588b135e2e030bdf95ba5adef1cb59f588c797bbdeef2","tests/ui/duplicate-enum-source.rs":"bfe28ce18042d446a76c7411aa233598211ce1157fdd3cb87bff3b3fa7c33131","tests/ui/duplicate-enum-source.stderr":"3d32fead420b27b4497be49080bc3b78f7f0ba339ead3de6c94e5dc20302c18f","tests/ui/duplicate-fmt.rs":"af53b66445bcce076a114376747f176b42c060a156563a41ccb638ae14c451fd","tests/ui/duplicate-fmt.stderr":"998bb121ce6f1595fd99529a7a1b06451b6bf476924337dce5524a83a7a5f1a1","tests/ui/duplicate-struct-source.rs":"f3d5f8e3d6fccfcdbb630db291353709583a920c6bf46f9f9de9966b67ea4c0f","tests/ui/duplicate-struct-source.stderr":"fb761d76668ac42357cf37b03c0abdbae5de0a828034990850291c9cb6ab766d","tests/ui/duplicate-transparent.rs":"41a9447e85f1a47027023442acde55c3d8610ec46d91b39bd43a42d7a004d747","tests/ui/duplicate-transparent.stderr":"4975abad43e973df158f18098d9bcb9dc39f8e75d3e733ed5d6620d1ee065c11","tests/ui/from-backtrace-backtrace.rs":"1fd51c5a1f7f6b6ee676d9fc798b6276ef2ce75def33d07f0e4b7bbde3291859","tests/ui/from-backtrace-backtrace.stderr":"f9774e9dad51374501ef4a55fa2dacece4d1c70e29ca18761394bdb80a9a74da","tests/ui/from-not-source.rs":"744a55aeffe11066830159ac023c33aaa5576e313b341fa24440ee13dfe3ac98","tests/ui/from-not-source.stderr":"525038e8b841707b927434cca4549168f73bd305faca17552a0d1fffa542ccc4","tests/ui/lifetime.rs":"e72e0391695e47fcd07edbf3819f114e468e2097086ec687781c7c8d6b4b7da7","tests/ui/lifetime.stderr":"d889a23f71324afe95dafc5f9d15337fbdbc9977cb8924f0cafe3a3becf4ced7","tests/ui/missing-fmt.rs":"bc9e2830e54c2474ff6c27a766ed3dee88d29e40f93f30e8d64d63233866c17d","tests/ui/missing-fmt.stderr":"9a20ccee9b660fe31a5b3199307b48580bb8305cb9ce33d97d3fc767a0cfc614","tests/ui/no-display.rs":"962245372272d23e9833311c15e73221b3c7da822a2ff90189613af56ffb5c2e","tests/ui/no-display.stderr":"40f47b286b770808a7dc5ec7970bc5cd501c9400f2e50049cf3258174929a9c1","tests/ui/source-enum-not-error.rs":"7c57c63b3ec37bc456738acea2e1038de5b0f32fe7e83984037d7ad1ed921737","tests/ui/source-enum-not-error.stderr":"44c974bf0b87431af78ccc7b4e18ebdc45135ca584a254960dff3f908ed862a8","tests/ui/source-struct-not-error.rs":"09fb7713637242dca9192585a6daeb8d732dc1c1d0fa522b74f1c98618e6d949","tests/ui/source-struct-not-error.stderr":"8e087a059c6b69de44e149ab3b5bffc4f4c6c3cbbb13c235c9a3c7c264be3245","tests/ui/transparent-display.rs":"b3c59583eb64b0b5a246444456d03cf52d51bcdc08885023600dbb44fd87e5f2","tests/ui/transparent-display.stderr":"16d538914e0d92026bde4b4bec75660217da9ecc6b621d12d2eb81d33ed1d1da","tests/ui/transparent-enum-many.rs":"2a40a764fb4683bff57973eec61507a6c00f7d4d7a32da6e7bd0190c2e445434","tests/ui/transparent-enum-many.stderr":"f1d78c1d6d8edbef153420db4fb9ca3dc6076fa043b5b1bc0cd291daa417a3ea","tests/ui/transparent-enum-source.rs":"18f606a98ac0a53f08dc56f5f923b9cbe75d25ed34479c777b48dac305d5968c","tests/ui/transparent-enum-source.stderr":"1b2e0ac53951034575d43ec0396c4e2b3cfb272db2aef8d6baa13a7e1632cc84","tests/ui/transparent-struct-many.rs":"72c6b6c1a44c203d3bc68989b2f1ec092531ef75b745432824c3776c290326f6","tests/ui/transparent-struct-many.stderr":"7bd0536dbb54a0ce7d4a8e66ca7624a1b132d8a1d1e4fecca642ec77494ac01c","tests/ui/transparent-struct-source.rs":"863fa691ed7d27e8767da58d9ee11fd40d6642274b36338ca1074c07964ea2b3","tests/ui/transparent-struct-source.stderr":"267dab65929e67d32347fb467a00b43af931f8205d727d7671938580217fc70e","tests/ui/unexpected-field-fmt.rs":"29fba7b4d81c642ec8e47cfe053aa515acf9080a86d65e685363a48993becfe3","tests/ui/unexpected-field-fmt.stderr":"20731c4a08af04bed3ff513903adadd690b6bc532b15604557e7f25575a8338f","tests/ui/unexpected-struct-source.rs":"c6cbe882d622635c216feb8290b1bd536ce0ec4feee16bc087667a21b3641d5c","tests/ui/unexpected-struct-source.stderr":"7c8227513478f6cc09e8a28be337c8a0e758a06ca5978d774c91bd43c4a54043","tests/ui/union.rs":"331adff27cebd8b95b03b6742cc8247331fda1f961e1590ed39c8d39f50cf1d8","tests/ui/union.stderr":"5f67ad29753d6fb14bc03aef7d4a1f660ee7796e469c037efbf8b13456934ad3"},"package":"3d0a539a918745651435ac7db7a18761589a94cd7e94cd56999f828bf73c8a57"} \ No newline at end of file +{"files":{"Cargo.toml":"1d01528e44c86dd86ee07557c6cd89bd3cf37a2456e6f3430af299d84f304035","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"959ac4d4dc43ce39235613d853db8df4a0cfd79e262fc38aba43a98331643952","build.rs":"8b8d9cbf84b9a2fd108b49ecb4bae327da688d80b818acda9ee17170c788e193","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/aserror.rs":"c93bd9191f26a7599043b397e26822564d9bafaa339a19861182a9909e8a3811","src/display.rs":"63c492bfa8b8e9180ad5abcbe63c1173b4ad490c47ec33cac9a338f96c8f8e42","src/lib.rs":"3fcc3c1ab31a64215978b92e68c1421ec8c5fcb942e57eb35adb9cc07a865730","src/provide.rs":"b2f7a33f44f44a03e94f54cc4b79ba2dcc5fcf0fdf64b07cdd9588a6544c8d8e","tests/compiletest.rs":"022a8e400ef813d7ea1875b944549cee5125f6a995dc33e93b48cba3e1b57bd1","tests/test_backtrace.rs":"fd1f326bc23e6c1611a51bc43c1d5092b32ee18a1613abe20da0818e5729c0ed","tests/test_deprecated.rs":"7b80a10f090a3982da017556d3d71398abcead59afd8278c7b9d9b1f7b66c7b3","tests/test_display.rs":"20fdc8903f06da3a698ef4377cccca26a71138ca6de67310c5bdb8a9fcb39d83","tests/test_error.rs":"d06dca3c38f22d7ce4e27dadd6c0f78e5cefe3a2ebbc5fe44abc9ddd5ee1985f","tests/test_expr.rs":"388402702a3be4ffcd0574d66733e8932bf7d5de37544a00ecb0e4f8d8246da4","tests/test_from.rs":"de1347e62069f826d8616b9e45ce6cccc3a8a8049cb51bd22d6763efe6118b0c","tests/test_generics.rs":"4f33747e3f62550d5af94687679af230ef92fbb3247ae4b41df46792a040e4dc","tests/test_lints.rs":"c17d79d77edfcdd4b8f6dcdcd1c70ad065cfbc747e1a618ac6343315d0b59ea4","tests/test_option.rs":"3a82af1ad206444b9955e3f2fda508d70f887ad0b7f7986bafc17496f63b07ab","tests/test_path.rs":"ef5452c7e828a0179f5ace7e19f95b9762aa887caf10244adbfe36ded712c090","tests/test_source.rs":"f2f04f11bf8a709eddb1c68f113cda0c2be87e56800d6b9d991bedd545b4642f","tests/test_transparent.rs":"cd8d5be14d00d610a1782104bea6c013618501dab5c3625178ecfcf66e31f939","tests/ui/bad-field-attr.rs":"c5b567e3091969a01061843fb2d95c5e1aa3fa81edfeecdf416a84a6fba40aa8","tests/ui/bad-field-attr.stderr":"78f576d5ec66464a77f1cdf0f5bb7dcdf18f7f04f1165983a6239ec59d908ea3","tests/ui/concat-display.rs":"3995bd6b3bdd67df7bb16499775d89600c0dd20895633fe807396a64c117078d","tests/ui/concat-display.stderr":"256dfde61ee689ebe51588b135e2e030bdf95ba5adef1cb59f588c797bbdeef2","tests/ui/duplicate-enum-source.rs":"bfe28ce18042d446a76c7411aa233598211ce1157fdd3cb87bff3b3fa7c33131","tests/ui/duplicate-enum-source.stderr":"3d32fead420b27b4497be49080bc3b78f7f0ba339ead3de6c94e5dc20302c18f","tests/ui/duplicate-fmt.rs":"af53b66445bcce076a114376747f176b42c060a156563a41ccb638ae14c451fd","tests/ui/duplicate-fmt.stderr":"998bb121ce6f1595fd99529a7a1b06451b6bf476924337dce5524a83a7a5f1a1","tests/ui/duplicate-struct-source.rs":"f3d5f8e3d6fccfcdbb630db291353709583a920c6bf46f9f9de9966b67ea4c0f","tests/ui/duplicate-struct-source.stderr":"fb761d76668ac42357cf37b03c0abdbae5de0a828034990850291c9cb6ab766d","tests/ui/duplicate-transparent.rs":"41a9447e85f1a47027023442acde55c3d8610ec46d91b39bd43a42d7a004d747","tests/ui/duplicate-transparent.stderr":"4975abad43e973df158f18098d9bcb9dc39f8e75d3e733ed5d6620d1ee065c11","tests/ui/from-backtrace-backtrace.rs":"1fd51c5a1f7f6b6ee676d9fc798b6276ef2ce75def33d07f0e4b7bbde3291859","tests/ui/from-backtrace-backtrace.stderr":"f9774e9dad51374501ef4a55fa2dacece4d1c70e29ca18761394bdb80a9a74da","tests/ui/from-not-source.rs":"744a55aeffe11066830159ac023c33aaa5576e313b341fa24440ee13dfe3ac98","tests/ui/from-not-source.stderr":"525038e8b841707b927434cca4549168f73bd305faca17552a0d1fffa542ccc4","tests/ui/lifetime.rs":"e72e0391695e47fcd07edbf3819f114e468e2097086ec687781c7c8d6b4b7da7","tests/ui/lifetime.stderr":"d889a23f71324afe95dafc5f9d15337fbdbc9977cb8924f0cafe3a3becf4ced7","tests/ui/missing-fmt.rs":"bc9e2830e54c2474ff6c27a766ed3dee88d29e40f93f30e8d64d63233866c17d","tests/ui/missing-fmt.stderr":"9a20ccee9b660fe31a5b3199307b48580bb8305cb9ce33d97d3fc767a0cfc614","tests/ui/no-display.rs":"962245372272d23e9833311c15e73221b3c7da822a2ff90189613af56ffb5c2e","tests/ui/no-display.stderr":"40f47b286b770808a7dc5ec7970bc5cd501c9400f2e50049cf3258174929a9c1","tests/ui/source-enum-not-error.rs":"7c57c63b3ec37bc456738acea2e1038de5b0f32fe7e83984037d7ad1ed921737","tests/ui/source-enum-not-error.stderr":"1bb601243ff11d5de08c70edf3fd89d52b4a89fcd2a5c7775d1bc11d056ced1e","tests/ui/source-struct-not-error.rs":"09fb7713637242dca9192585a6daeb8d732dc1c1d0fa522b74f1c98618e6d949","tests/ui/source-struct-not-error.stderr":"9a1a04d606309c82eea59d1745c833189f0b4f237f0741a17dd62c11ce16642d","tests/ui/transparent-display.rs":"b3c59583eb64b0b5a246444456d03cf52d51bcdc08885023600dbb44fd87e5f2","tests/ui/transparent-display.stderr":"16d538914e0d92026bde4b4bec75660217da9ecc6b621d12d2eb81d33ed1d1da","tests/ui/transparent-enum-many.rs":"2a40a764fb4683bff57973eec61507a6c00f7d4d7a32da6e7bd0190c2e445434","tests/ui/transparent-enum-many.stderr":"f1d78c1d6d8edbef153420db4fb9ca3dc6076fa043b5b1bc0cd291daa417a3ea","tests/ui/transparent-enum-source.rs":"18f606a98ac0a53f08dc56f5f923b9cbe75d25ed34479c777b48dac305d5968c","tests/ui/transparent-enum-source.stderr":"1b2e0ac53951034575d43ec0396c4e2b3cfb272db2aef8d6baa13a7e1632cc84","tests/ui/transparent-struct-many.rs":"72c6b6c1a44c203d3bc68989b2f1ec092531ef75b745432824c3776c290326f6","tests/ui/transparent-struct-many.stderr":"7bd0536dbb54a0ce7d4a8e66ca7624a1b132d8a1d1e4fecca642ec77494ac01c","tests/ui/transparent-struct-source.rs":"863fa691ed7d27e8767da58d9ee11fd40d6642274b36338ca1074c07964ea2b3","tests/ui/transparent-struct-source.stderr":"267dab65929e67d32347fb467a00b43af931f8205d727d7671938580217fc70e","tests/ui/unexpected-field-fmt.rs":"29fba7b4d81c642ec8e47cfe053aa515acf9080a86d65e685363a48993becfe3","tests/ui/unexpected-field-fmt.stderr":"20731c4a08af04bed3ff513903adadd690b6bc532b15604557e7f25575a8338f","tests/ui/unexpected-struct-source.rs":"c6cbe882d622635c216feb8290b1bd536ce0ec4feee16bc087667a21b3641d5c","tests/ui/unexpected-struct-source.stderr":"7c8227513478f6cc09e8a28be337c8a0e758a06ca5978d774c91bd43c4a54043","tests/ui/union.rs":"331adff27cebd8b95b03b6742cc8247331fda1f961e1590ed39c8d39f50cf1d8","tests/ui/union.stderr":"5f67ad29753d6fb14bc03aef7d4a1f660ee7796e469c037efbf8b13456934ad3"},"package":"10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"} \ No newline at end of file diff --git a/bash-5.1/vendor/thiserror/Cargo.toml b/bash-5.1/vendor/thiserror/Cargo.toml index 5926572..2f060d6 100644 --- a/bash-5.1/vendor/thiserror/Cargo.toml +++ b/bash-5.1/vendor/thiserror/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.31" name = "thiserror" -version = "1.0.33" +version = "1.0.37" authors = ["David Tolnay <dtolnay@gmail.com>"] description = "derive(Error)" documentation = "https://docs.rs/thiserror" @@ -31,10 +31,10 @@ repository = "https://github.com/dtolnay/thiserror" targets = ["x86_64-unknown-linux-gnu"] [dependencies.thiserror-impl] -version = "=1.0.33" +version = "=1.0.37" [dev-dependencies.anyhow] -version = "1.0" +version = "1.0.65" [dev-dependencies.ref-cast] version = "1.0" diff --git a/bash-5.1/vendor/thiserror/README.md b/bash-5.1/vendor/thiserror/README.md index 387a56e..8f6b896 100644 --- a/bash-5.1/vendor/thiserror/README.md +++ b/bash-5.1/vendor/thiserror/README.md @@ -124,8 +124,8 @@ pub enum DataStoreError { } ``` -- The Error trait's `backtrace()` method is implemented to return whichever - field has a type named `Backtrace`, if any. +- The Error trait's `provide()` method is implemented to provide whichever field + has a type named `Backtrace`, if any, as a `std::backtrace::Backtrace`. ```rust use std::backtrace::Backtrace; @@ -138,8 +138,9 @@ pub enum DataStoreError { ``` - If a field is both a source (named `source`, or has `#[source]` or `#[from]` - attribute) *and* is marked `#[backtrace]`, then the Error trait's - `backtrace()` method is forwarded to the source's backtrace. + attribute) *and* is marked `#[backtrace]`, then the Error trait's `provide()` + method is forwarded to the source's `provide` so that both layers of the error + share the same backtrace. ```rust #[derive(Error, Debug)] @@ -165,6 +166,27 @@ pub enum DataStoreError { } ``` + Another use case is hiding implementation details of an error representation + behind an opaque error type, so that the representation is able to evolve + without breaking the crate's public API. + + ```rust + // PublicError is public, but opaque and easy to keep compatible. + #[derive(Error, Debug)] + #[error(transparent)] + pub struct PublicError(#[from] ErrorRepr); + + impl PublicError { + // Accessors for anything we do want to expose publicly. + } + + // Private and free to change across minor version of the crate. + #[derive(Error, Debug)] + enum ErrorRepr { + ... + } + ``` + - See also the [`anyhow`] library for a convenient single error type to use in application code. diff --git a/bash-5.1/vendor/thiserror/build.rs b/bash-5.1/vendor/thiserror/build.rs new file mode 100644 index 0000000..004dfb0 --- /dev/null +++ b/bash-5.1/vendor/thiserror/build.rs @@ -0,0 +1,66 @@ +use std::env; +use std::fs; +use std::path::Path; +use std::process::{Command, ExitStatus, Stdio}; +use std::str; + +// This code exercises the surface area that we expect of the Provider API. If +// the current toolchain is able to compile it, then thiserror is able to use +// providers for backtrace support. +const PROBE: &str = r#" + #![feature(provide_any)] + + use std::any::{Demand, Provider}; + + fn _f<'a, P: Provider>(p: &'a P, demand: &mut Demand<'a>) { + p.provide(demand); + } +"#; + +fn main() { + match compile_probe() { + Some(status) if status.success() => println!("cargo:rustc-cfg=provide_any"), + _ => {} + } +} + +fn compile_probe() -> Option<ExitStatus> { + let rustc = env::var_os("RUSTC")?; + let out_dir = env::var_os("OUT_DIR")?; + let probefile = Path::new(&out_dir).join("probe.rs"); + fs::write(&probefile, PROBE).ok()?; + + // Make sure to pick up Cargo rustc configuration. + let mut cmd = if let Some(wrapper) = env::var_os("RUSTC_WRAPPER") { + let mut cmd = Command::new(wrapper); + // The wrapper's first argument is supposed to be the path to rustc. + cmd.arg(rustc); + cmd + } else { + Command::new(rustc) + }; + + cmd.stderr(Stdio::null()) + .arg("--edition=2018") + .arg("--crate-name=thiserror_build") + .arg("--crate-type=lib") + .arg("--emit=metadata") + .arg("--out-dir") + .arg(out_dir) + .arg(probefile); + + if let Some(target) = env::var_os("TARGET") { + cmd.arg("--target").arg(target); + } + + // If Cargo wants to set RUSTFLAGS, use that. + if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") { + if !rustflags.is_empty() { + for arg in rustflags.split('\x1f') { + cmd.arg(arg); + } + } + } + + cmd.status().ok() +} diff --git a/bash-5.1/vendor/thiserror/src/aserror.rs b/bash-5.1/vendor/thiserror/src/aserror.rs index c036b7b..5fea84e 100644 --- a/bash-5.1/vendor/thiserror/src/aserror.rs +++ b/bash-5.1/vendor/thiserror/src/aserror.rs @@ -1,7 +1,7 @@ use std::error::Error; use std::panic::UnwindSafe; -pub trait AsDynError<'a> { +pub trait AsDynError<'a>: Sealed { fn as_dyn_error(&self) -> &(dyn Error + 'a); } @@ -39,3 +39,10 @@ impl<'a> AsDynError<'a> for dyn Error + Send + Sync + UnwindSafe + 'a { self } } + +pub trait Sealed {} +impl<'a, T: Error + 'a> Sealed for T {} +impl<'a> Sealed for dyn Error + 'a {} +impl<'a> Sealed for dyn Error + Send + 'a {} +impl<'a> Sealed for dyn Error + Send + Sync + 'a {} +impl<'a> Sealed for dyn Error + Send + Sync + UnwindSafe + 'a {} diff --git a/bash-5.1/vendor/thiserror/src/lib.rs b/bash-5.1/vendor/thiserror/src/lib.rs index 247199f..aae6552 100644 --- a/bash-5.1/vendor/thiserror/src/lib.rs +++ b/bash-5.1/vendor/thiserror/src/lib.rs @@ -146,8 +146,9 @@ //! # } //! ``` //! -//! - The Error trait's `backtrace()` method is implemented to return whichever -//! field has a type named `Backtrace`, if any. +//! - The Error trait's `provide()` method is implemented to provide whichever +//! field has a type named `Backtrace`, if any, as a +//! `std::backtrace::Backtrace`. //! //! ```rust //! # const IGNORE: &str = stringify! { @@ -163,7 +164,8 @@ //! //! - If a field is both a source (named `source`, or has `#[source]` or //! `#[from]` attribute) *and* is marked `#[backtrace]`, then the Error -//! trait's `backtrace()` method is forwarded to the source's backtrace. +//! trait's `provide()` method is forwarded to the source's `provide` so that +//! both layers of the error share the same backtrace. //! //! ```rust //! # const IGNORE: &str = stringify! { @@ -196,6 +198,31 @@ //! } //! ``` //! +//! Another use case is hiding implementation details of an error +//! representation behind an opaque error type, so that the representation is +//! able to evolve without breaking the crate's public API. +//! +//! ``` +//! # use thiserror::Error; +//! # +//! // PublicError is public, but opaque and easy to keep compatible. +//! #[derive(Error, Debug)] +//! #[error(transparent)] +//! pub struct PublicError(#[from] ErrorRepr); +//! +//! impl PublicError { +//! // Accessors for anything we do want to expose publicly. +//! } +//! +//! // Private and free to change across minor version of the crate. +//! #[derive(Error, Debug)] +//! enum ErrorRepr { +//! # /* +//! ... +//! # */ +//! } +//! ``` +//! //! - See also the [`anyhow`] library for a convenient single error type to use //! in application code. //! @@ -206,10 +233,14 @@ clippy::doc_markdown, clippy::module_name_repetitions, clippy::return_self_not_must_use, + clippy::wildcard_imports, )] +#![cfg_attr(provide_any, feature(provide_any))] mod aserror; mod display; +#[cfg(provide_any)] +mod provide; pub use thiserror_impl::*; @@ -218,4 +249,6 @@ pub use thiserror_impl::*; pub mod __private { pub use crate::aserror::AsDynError; pub use crate::display::{DisplayAsDisplay, PathAsDisplay}; + #[cfg(provide_any)] + pub use crate::provide::ThiserrorProvide; } diff --git a/bash-5.1/vendor/thiserror/src/provide.rs b/bash-5.1/vendor/thiserror/src/provide.rs new file mode 100644 index 0000000..524e743 --- /dev/null +++ b/bash-5.1/vendor/thiserror/src/provide.rs @@ -0,0 +1,15 @@ +use std::any::{Demand, Provider}; + +pub trait ThiserrorProvide: Sealed { + fn thiserror_provide<'a>(&'a self, demand: &mut Demand<'a>); +} + +impl<T: Provider + ?Sized> ThiserrorProvide for T { + #[inline] + fn thiserror_provide<'a>(&'a self, demand: &mut Demand<'a>) { + self.provide(demand); + } +} + +pub trait Sealed {} +impl<T: Provider + ?Sized> Sealed for T {} diff --git a/bash-5.1/vendor/thiserror/tests/test_backtrace.rs b/bash-5.1/vendor/thiserror/tests/test_backtrace.rs index 052c6f4..43f68b8 100644 --- a/bash-5.1/vendor/thiserror/tests/test_backtrace.rs +++ b/bash-5.1/vendor/thiserror/tests/test_backtrace.rs @@ -21,6 +21,7 @@ pub mod structs { use super::{Inner, InnerBacktrace}; use std::any; use std::backtrace::Backtrace; + use std::error::Error; use std::sync::Arc; use thiserror::Error; @@ -86,6 +87,20 @@ pub mod structs { backtrace: Arc<Backtrace>, } + #[derive(Error, Debug)] + #[error("...")] + pub struct AnyhowBacktrace { + #[backtrace] + source: anyhow::Error, + } + + #[derive(Error, Debug)] + #[error("...")] + pub struct BoxDynErrorBacktrace { + #[backtrace] + source: Box<dyn Error>, + } + #[test] fn test_backtrace() { let error = PlainBacktrace { @@ -121,6 +136,37 @@ pub mod structs { let error = ArcBacktraceFrom::from(Inner); assert!(any::request_ref::<Backtrace>(&error).is_some()); + + let error = AnyhowBacktrace { + source: anyhow::Error::msg("..."), + }; + assert!(any::request_ref::<Backtrace>(&error).is_some()); + + let error = BoxDynErrorBacktrace { + source: Box::new(PlainBacktrace { + backtrace: Backtrace::capture(), + }), + }; + assert!(any::request_ref::<Backtrace>(&error).is_some()); + } + + // https://github.com/dtolnay/thiserror/issues/185 -- std::error::Error and + // std::any::Provide both have a method called 'provide', so directly + // calling it from generated code could be ambiguous. + #[test] + fn test_provide_name_collision() { + use std::any::Provider; + + #[derive(Error, Debug)] + #[error("...")] + struct MyError { + #[source] + #[backtrace] + x: std::io::Error, + } + + let _: dyn Error; + let _: dyn Provider; } } diff --git a/bash-5.1/vendor/thiserror/tests/test_deprecated.rs b/bash-5.1/vendor/thiserror/tests/test_deprecated.rs new file mode 100644 index 0000000..5524666 --- /dev/null +++ b/bash-5.1/vendor/thiserror/tests/test_deprecated.rs @@ -0,0 +1,10 @@ +#![deny(deprecated, clippy::all, clippy::pedantic)] + +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum Error { + #[deprecated] + #[error("...")] + Deprecated, +} diff --git a/bash-5.1/vendor/thiserror/tests/ui/source-enum-not-error.stderr b/bash-5.1/vendor/thiserror/tests/ui/source-enum-not-error.stderr index da10c6e..29ee546 100644 --- a/bash-5.1/vendor/thiserror/tests/ui/source-enum-not-error.stderr +++ b/bash-5.1/vendor/thiserror/tests/ui/source-enum-not-error.stderr @@ -4,7 +4,7 @@ error[E0599]: the method `as_dyn_error` exists for reference `&NotError`, but it 4 | pub struct NotError; | ------------------- | | - | doesn't satisfy `NotError: AsDynError` + | doesn't satisfy `NotError: AsDynError<'_>` | doesn't satisfy `NotError: std::error::Error` ... 10 | source: NotError, @@ -12,9 +12,9 @@ error[E0599]: the method `as_dyn_error` exists for reference `&NotError`, but it | = note: the following trait bounds were not satisfied: `NotError: std::error::Error` - which is required by `NotError: AsDynError` + which is required by `NotError: AsDynError<'_>` `&NotError: std::error::Error` - which is required by `&NotError: AsDynError` + which is required by `&NotError: AsDynError<'_>` note: the following trait must be implemented --> $RUST/core/src/error.rs | diff --git a/bash-5.1/vendor/thiserror/tests/ui/source-struct-not-error.stderr b/bash-5.1/vendor/thiserror/tests/ui/source-struct-not-error.stderr index cc0e67a..efa4028 100644 --- a/bash-5.1/vendor/thiserror/tests/ui/source-struct-not-error.stderr +++ b/bash-5.1/vendor/thiserror/tests/ui/source-struct-not-error.stderr @@ -5,7 +5,7 @@ error[E0599]: the method `as_dyn_error` exists for struct `NotError`, but its tr | --------------- | | | method `as_dyn_error` not found for this struct - | doesn't satisfy `NotError: AsDynError` + | doesn't satisfy `NotError: AsDynError<'_>` | doesn't satisfy `NotError: std::error::Error` ... 9 | source: NotError, @@ -13,7 +13,7 @@ error[E0599]: the method `as_dyn_error` exists for struct `NotError`, but its tr | = note: the following trait bounds were not satisfied: `NotError: std::error::Error` - which is required by `NotError: AsDynError` + which is required by `NotError: AsDynError<'_>` note: the following trait must be implemented --> $RUST/core/src/error.rs | diff --git a/bash-5.1/vendor/thread_local/.cargo-checksum.json b/bash-5.1/vendor/thread_local/.cargo-checksum.json new file mode 100644 index 0000000..8798696 --- /dev/null +++ b/bash-5.1/vendor/thread_local/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b4f81d513b95fff17f96d5da83768187870df83969fd5e49b030aaf6158ccd58","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"00a29378d5aeb66b7a48b77bee0d463c8b408b8a9cb0abb7674edb10d142aca0","benches/thread_local.rs":"cc8bde81ed6206525feff209598caf1e01e89a83bf21d8b7ccc0dadc8b89d815","src/lib.rs":"d7f875b0c4a8e2229f3510c88c0425342f1628fdf2f2b113c80789b6b90378b7","src/thread_id.rs":"0962c130061939557aa272115e4420fbbc63b6bd306783a456a8ffcbf304a447","src/unreachable.rs":"830d44988f86f4fc6c3c4dd7e9e4e7d0f2cb9c5b024c360b5f7ceae365983367"},"package":"c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"} \ No newline at end of file diff --git a/bash-5.1/vendor/thread_local/Cargo.toml b/bash-5.1/vendor/thread_local/Cargo.toml new file mode 100644 index 0000000..fc7b3c8 --- /dev/null +++ b/bash-5.1/vendor/thread_local/Cargo.toml @@ -0,0 +1,26 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "thread_local" +version = "0.3.6" +authors = ["Amanieu d'Antras <amanieu@gmail.com>"] +description = "Per-object thread-local storage" +documentation = "https://amanieu.github.io/thread_local-rs/thread_local/index.html" +readme = "README.md" +keywords = ["thread_local", "concurrent", "thread"] +license = "Apache-2.0/MIT" +repository = "https://github.com/Amanieu/thread_local-rs" +[dependencies.lazy_static] +version = "1.0" +[badges.travis-ci] +repository = "Amanieu/thread_local-rs" diff --git a/bash-5.1/vendor/thread_local/LICENSE-APACHE b/bash-5.1/vendor/thread_local/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/thread_local/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/thread_local/LICENSE-MIT b/bash-5.1/vendor/thread_local/LICENSE-MIT new file mode 100644 index 0000000..40b8817 --- /dev/null +++ b/bash-5.1/vendor/thread_local/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/thread_local/README.md b/bash-5.1/vendor/thread_local/README.md new file mode 100644 index 0000000..1472ed1 --- /dev/null +++ b/bash-5.1/vendor/thread_local/README.md @@ -0,0 +1,41 @@ +thread_local +============ + +[![Build Status](https://travis-ci.org/Amanieu/thread_local-rs.svg?branch=master)](https://travis-ci.org/Amanieu/thread_local-rs) [![Crates.io](https://img.shields.io/crates/v/thread_local.svg)](https://crates.io/crates/thread_local) + +This library provides the `ThreadLocal` and `CachedThreadLocal` types which +allow a separate copy of an object to be used for each thread. This allows for +per-object thread-local storage, unlike the standard library's `thread_local!` +macro which only allows static thread-local storage. + +[Documentation](https://amanieu.github.io/thread_local-rs/thread_local/index.html) + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +thread_local = "0.3" +``` + +and this to your crate root: + +```rust +extern crate thread_local; +``` + +## License + +Licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/bash-5.1/vendor/thread_local/benches/thread_local.rs b/bash-5.1/vendor/thread_local/benches/thread_local.rs new file mode 100644 index 0000000..4cfaacd --- /dev/null +++ b/bash-5.1/vendor/thread_local/benches/thread_local.rs @@ -0,0 +1,18 @@ +#![feature(test)] + +extern crate thread_local; +extern crate test; + +use thread_local::{ThreadLocal, CachedThreadLocal}; + +#[bench] +fn thread_local(b: &mut test::Bencher) { + let local = ThreadLocal::new(); + b.iter(|| { let _: &i32 = local.get_or(|| Box::new(0)); }); +} + +#[bench] +fn cached_thread_local(b: &mut test::Bencher) { + let local = CachedThreadLocal::new(); + b.iter(|| { let _: &i32 = local.get_or(|| Box::new(0)); }); +} diff --git a/bash-5.1/vendor/thread_local/src/lib.rs b/bash-5.1/vendor/thread_local/src/lib.rs new file mode 100644 index 0000000..2f8e579 --- /dev/null +++ b/bash-5.1/vendor/thread_local/src/lib.rs @@ -0,0 +1,757 @@ +// Copyright 2017 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +//! Per-object thread-local storage +//! +//! This library provides the `ThreadLocal` type which allows a separate copy of +//! an object to be used for each thread. This allows for per-object +//! thread-local storage, unlike the standard library's `thread_local!` macro +//! which only allows static thread-local storage. +//! +//! Per-thread objects are not destroyed when a thread exits. Instead, objects +//! are only destroyed when the `ThreadLocal` containing them is destroyed. +//! +//! You can also iterate over the thread-local values of all thread in a +//! `ThreadLocal` object using the `iter_mut` and `into_iter` methods. This can +//! only be done if you have mutable access to the `ThreadLocal` object, which +//! guarantees that you are the only thread currently accessing it. +//! +//! A `CachedThreadLocal` type is also provided which wraps a `ThreadLocal` but +//! also uses a special fast path for the first thread that writes into it. The +//! fast path has very low overhead (<1ns per access) while keeping the same +//! performance as `ThreadLocal` for other threads. +//! +//! Note that since thread IDs are recycled when a thread exits, it is possible +//! for one thread to retrieve the object of another thread. Since this can only +//! occur after a thread has exited this does not lead to any race conditions. +//! +//! # Examples +//! +//! Basic usage of `ThreadLocal`: +//! +//! ```rust +//! use thread_local::ThreadLocal; +//! let tls: ThreadLocal<u32> = ThreadLocal::new(); +//! assert_eq!(tls.get(), None); +//! assert_eq!(tls.get_or(|| Box::new(5)), &5); +//! assert_eq!(tls.get(), Some(&5)); +//! ``` +//! +//! Combining thread-local values into a single result: +//! +//! ```rust +//! use thread_local::ThreadLocal; +//! use std::sync::Arc; +//! use std::cell::Cell; +//! use std::thread; +//! +//! let tls = Arc::new(ThreadLocal::new()); +//! +//! // Create a bunch of threads to do stuff +//! for _ in 0..5 { +//! let tls2 = tls.clone(); +//! thread::spawn(move || { +//! // Increment a counter to count some event... +//! let cell = tls2.get_or(|| Box::new(Cell::new(0))); +//! cell.set(cell.get() + 1); +//! }).join().unwrap(); +//! } +//! +//! // Once all threads are done, collect the counter values and return the +//! // sum of all thread-local counter values. +//! let tls = Arc::try_unwrap(tls).unwrap(); +//! let total = tls.into_iter().fold(0, |x, y| x + y.get()); +//! assert_eq!(total, 5); +//! ``` + +#![warn(missing_docs)] + +#[macro_use] +extern crate lazy_static; + +mod thread_id; +mod unreachable; + +use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; +use std::sync::Mutex; +use std::marker::PhantomData; +use std::cell::UnsafeCell; +use std::fmt; +use std::iter::Chain; +use std::option::IntoIter as OptionIter; +use std::panic::UnwindSafe; +use unreachable::{UncheckedOptionExt, UncheckedResultExt}; + +/// Thread-local variable wrapper +/// +/// See the [module-level documentation](index.html) for more. +pub struct ThreadLocal<T: ?Sized + Send> { + // Pointer to the current top-level hash table + table: AtomicPtr<Table<T>>, + + // Lock used to guard against concurrent modifications. This is only taken + // while writing to the table, not when reading from it. This also guards + // the counter for the total number of values in the hash table. + lock: Mutex<usize>, + + // PhantomData to indicate that we logically own T + marker: PhantomData<T>, +} + +struct Table<T: ?Sized + Send> { + // Hash entries for the table + entries: Box<[TableEntry<T>]>, + + // Number of bits used for the hash function + hash_bits: usize, + + // Previous table, half the size of the current one + prev: Option<Box<Table<T>>>, +} + +struct TableEntry<T: ?Sized + Send> { + // Current owner of this entry, or 0 if this is an empty entry + owner: AtomicUsize, + + // The object associated with this entry. This is only ever accessed by the + // owner of the entry. + data: UnsafeCell<Option<Box<T>>>, +} + +// ThreadLocal is always Sync, even if T isn't +unsafe impl<T: ?Sized + Send> Sync for ThreadLocal<T> {} + +impl<T: ?Sized + Send> Default for ThreadLocal<T> { + fn default() -> ThreadLocal<T> { + ThreadLocal::new() + } +} + +impl<T: ?Sized + Send> Drop for ThreadLocal<T> { + fn drop(&mut self) { + unsafe { + Box::from_raw(self.table.load(Ordering::Relaxed)); + } + } +} + +// Implementation of Clone for TableEntry, needed to make vec![] work +impl<T: ?Sized + Send> Clone for TableEntry<T> { + fn clone(&self) -> TableEntry<T> { + TableEntry { + owner: AtomicUsize::new(0), + data: UnsafeCell::new(None), + } + } +} + +// Hash function for the thread id +#[cfg(target_pointer_width = "32")] +#[inline] +fn hash(id: usize, bits: usize) -> usize { + id.wrapping_mul(0x9E3779B9) >> (32 - bits) +} +#[cfg(target_pointer_width = "64")] +#[inline] +fn hash(id: usize, bits: usize) -> usize { + id.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> (64 - bits) +} + +impl<T: ?Sized + Send> ThreadLocal<T> { + /// Creates a new empty `ThreadLocal`. + pub fn new() -> ThreadLocal<T> { + let entry = TableEntry { + owner: AtomicUsize::new(0), + data: UnsafeCell::new(None), + }; + let table = Table { + entries: vec![entry; 2].into_boxed_slice(), + hash_bits: 1, + prev: None, + }; + ThreadLocal { + table: AtomicPtr::new(Box::into_raw(Box::new(table))), + lock: Mutex::new(0), + marker: PhantomData, + } + } + + /// Returns the element for the current thread, if it exists. + pub fn get(&self) -> Option<&T> { + let id = thread_id::get(); + self.get_fast(id) + } + + /// Returns the element for the current thread, or creates it if it doesn't + /// exist. + pub fn get_or<F>(&self, create: F) -> &T + where + F: FnOnce() -> Box<T>, + { + unsafe { + self.get_or_try(|| Ok::<Box<T>, ()>(create())) + .unchecked_unwrap_ok() + } + } + + /// Returns the element for the current thread, or creates it if it doesn't + /// exist. If `create` fails, that error is returned and no element is + /// added. + pub fn get_or_try<F, E>(&self, create: F) -> Result<&T, E> + where + F: FnOnce() -> Result<Box<T>, E>, + { + let id = thread_id::get(); + match self.get_fast(id) { + Some(x) => Ok(x), + None => Ok(self.insert(id, try!(create()), true)), + } + } + + // Simple hash table lookup function + fn lookup(id: usize, table: &Table<T>) -> Option<&UnsafeCell<Option<Box<T>>>> { + // Because we use a Mutex to prevent concurrent modifications (but not + // reads) of the hash table, we can avoid any memory barriers here. No + // elements between our hash bucket and our value can have been modified + // since we inserted our thread-local value into the table. + for entry in table.entries.iter().cycle().skip(hash(id, table.hash_bits)) { + let owner = entry.owner.load(Ordering::Relaxed); + if owner == id { + return Some(&entry.data); + } + if owner == 0 { + return None; + } + } + unreachable!(); + } + + // Fast path: try to find our thread in the top-level hash table + fn get_fast(&self, id: usize) -> Option<&T> { + let table = unsafe { &*self.table.load(Ordering::Relaxed) }; + match Self::lookup(id, table) { + Some(x) => unsafe { Some((*x.get()).as_ref().unchecked_unwrap()) }, + None => self.get_slow(id, table), + } + } + + // Slow path: try to find our thread in the other hash tables, and then + // move it to the top-level hash table. + #[cold] + fn get_slow(&self, id: usize, table_top: &Table<T>) -> Option<&T> { + let mut current = &table_top.prev; + while let Some(ref table) = *current { + if let Some(x) = Self::lookup(id, table) { + let data = unsafe { (*x.get()).take().unchecked_unwrap() }; + return Some(self.insert(id, data, false)); + } + current = &table.prev; + } + None + } + + #[cold] + fn insert(&self, id: usize, data: Box<T>, new: bool) -> &T { + // Lock the Mutex to ensure only a single thread is modify the hash + // table at once. + let mut count = self.lock.lock().unwrap(); + if new { + *count += 1; + } + let table_raw = self.table.load(Ordering::Relaxed); + let table = unsafe { &*table_raw }; + + // If the current top-level hash table is more than 75% full, add a new + // level with 2x the capacity. Elements will be moved up to the new top + // level table as they are accessed. + let table = if *count > table.entries.len() * 3 / 4 { + let entry = TableEntry { + owner: AtomicUsize::new(0), + data: UnsafeCell::new(None), + }; + let new_table = Box::into_raw(Box::new(Table { + entries: vec![entry; table.entries.len() * 2].into_boxed_slice(), + hash_bits: table.hash_bits + 1, + prev: unsafe { Some(Box::from_raw(table_raw)) }, + })); + self.table.store(new_table, Ordering::Release); + unsafe { &*new_table } + } else { + table + }; + + // Insert the new element into the top-level hash table + for entry in table.entries.iter().cycle().skip(hash(id, table.hash_bits)) { + let owner = entry.owner.load(Ordering::Relaxed); + if owner == 0 { + unsafe { + entry.owner.store(id, Ordering::Relaxed); + *entry.data.get() = Some(data); + return (*entry.data.get()).as_ref().unchecked_unwrap(); + } + } + if owner == id { + // This can happen if create() inserted a value into this + // ThreadLocal between our calls to get_fast() and insert(). We + // just return the existing value and drop the newly-allocated + // Box. + unsafe { + return (*entry.data.get()).as_ref().unchecked_unwrap(); + } + } + } + unreachable!(); + } + + /// Returns a mutable iterator over the local values of all threads. + /// + /// Since this call borrows the `ThreadLocal` mutably, this operation can + /// be done safely---the mutable borrow statically guarantees no other + /// threads are currently accessing their associated values. + pub fn iter_mut(&mut self) -> IterMut<T> { + let raw = RawIter { + remaining: *self.lock.lock().unwrap(), + index: 0, + table: self.table.load(Ordering::Relaxed), + }; + IterMut { + raw: raw, + marker: PhantomData, + } + } + + /// Removes all thread-specific values from the `ThreadLocal`, effectively + /// reseting it to its original state. + /// + /// Since this call borrows the `ThreadLocal` mutably, this operation can + /// be done safely---the mutable borrow statically guarantees no other + /// threads are currently accessing their associated values. + pub fn clear(&mut self) { + *self = ThreadLocal::new(); + } +} + +impl<T: ?Sized + Send> IntoIterator for ThreadLocal<T> { + type Item = Box<T>; + type IntoIter = IntoIter<T>; + + fn into_iter(self) -> IntoIter<T> { + let raw = RawIter { + remaining: *self.lock.lock().unwrap(), + index: 0, + table: self.table.load(Ordering::Relaxed), + }; + IntoIter { + raw: raw, + _thread_local: self, + } + } +} + +impl<'a, T: ?Sized + Send + 'a> IntoIterator for &'a mut ThreadLocal<T> { + type Item = &'a mut Box<T>; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +impl<T: Send + Default> ThreadLocal<T> { + /// Returns the element for the current thread, or creates a default one if + /// it doesn't exist. + pub fn get_default(&self) -> &T { + self.get_or(|| Box::new(T::default())) + } +} + +impl<T: ?Sized + Send + fmt::Debug> fmt::Debug for ThreadLocal<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ThreadLocal {{ local_data: {:?} }}", self.get()) + } +} + +impl<T: ?Sized + Send + UnwindSafe> UnwindSafe for ThreadLocal<T> {} + +struct RawIter<T: ?Sized + Send> { + remaining: usize, + index: usize, + table: *const Table<T>, +} + +impl<T: ?Sized + Send> RawIter<T> { + fn next(&mut self) -> Option<*mut Option<Box<T>>> { + if self.remaining == 0 { + return None; + } + + loop { + let entries = unsafe { &(*self.table).entries[..] }; + while self.index < entries.len() { + let val = entries[self.index].data.get(); + self.index += 1; + if unsafe { (*val).is_some() } { + self.remaining -= 1; + return Some(val); + } + } + self.index = 0; + self.table = unsafe { &**(*self.table).prev.as_ref().unchecked_unwrap() }; + } + } +} + +/// Mutable iterator over the contents of a `ThreadLocal`. +pub struct IterMut<'a, T: ?Sized + Send + 'a> { + raw: RawIter<T>, + marker: PhantomData<&'a mut ThreadLocal<T>>, +} + +impl<'a, T: ?Sized + Send + 'a> Iterator for IterMut<'a, T> { + type Item = &'a mut Box<T>; + + fn next(&mut self) -> Option<&'a mut Box<T>> { + self.raw.next().map(|x| unsafe { + (*x).as_mut().unchecked_unwrap() + }) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + (self.raw.remaining, Some(self.raw.remaining)) + } +} + +impl<'a, T: ?Sized + Send + 'a> ExactSizeIterator for IterMut<'a, T> {} + +/// An iterator that moves out of a `ThreadLocal`. +pub struct IntoIter<T: ?Sized + Send> { + raw: RawIter<T>, + _thread_local: ThreadLocal<T>, +} + +impl<T: ?Sized + Send> Iterator for IntoIter<T> { + type Item = Box<T>; + + fn next(&mut self) -> Option<Box<T>> { + self.raw.next().map( + |x| unsafe { (*x).take().unchecked_unwrap() }, + ) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + (self.raw.remaining, Some(self.raw.remaining)) + } +} + +impl<T: ?Sized + Send> ExactSizeIterator for IntoIter<T> {} + +/// Wrapper around `ThreadLocal` which adds a fast path for a single thread. +/// +/// This has the same API as `ThreadLocal`, but will register the first thread +/// that sets a value as its owner. All accesses by the owner will go through +/// a special fast path which is much faster than the normal `ThreadLocal` path. +pub struct CachedThreadLocal<T: ?Sized + Send> { + owner: AtomicUsize, + local: UnsafeCell<Option<Box<T>>>, + global: ThreadLocal<T>, +} + +// CachedThreadLocal is always Sync, even if T isn't +unsafe impl<T: ?Sized + Send> Sync for CachedThreadLocal<T> {} + +impl<T: ?Sized + Send> Default for CachedThreadLocal<T> { + fn default() -> CachedThreadLocal<T> { + CachedThreadLocal::new() + } +} + +impl<T: ?Sized + Send> CachedThreadLocal<T> { + /// Creates a new empty `CachedThreadLocal`. + pub fn new() -> CachedThreadLocal<T> { + CachedThreadLocal { + owner: AtomicUsize::new(0), + local: UnsafeCell::new(None), + global: ThreadLocal::new(), + } + } + + /// Returns the element for the current thread, if it exists. + pub fn get(&self) -> Option<&T> { + let id = thread_id::get(); + let owner = self.owner.load(Ordering::Relaxed); + if owner == id { + return unsafe { Some((*self.local.get()).as_ref().unchecked_unwrap()) }; + } + if owner == 0 { + return None; + } + self.global.get_fast(id) + } + + /// Returns the element for the current thread, or creates it if it doesn't + /// exist. + #[inline(always)] + pub fn get_or<F>(&self, create: F) -> &T + where + F: FnOnce() -> Box<T>, + { + unsafe { + self.get_or_try(|| Ok::<Box<T>, ()>(create())) + .unchecked_unwrap_ok() + } + } + + /// Returns the element for the current thread, or creates it if it doesn't + /// exist. If `create` fails, that error is returned and no element is + /// added. + pub fn get_or_try<F, E>(&self, create: F) -> Result<&T, E> + where + F: FnOnce() -> Result<Box<T>, E>, + { + let id = thread_id::get(); + let owner = self.owner.load(Ordering::Relaxed); + if owner == id { + return Ok(unsafe { (*self.local.get()).as_ref().unchecked_unwrap() }); + } + self.get_or_try_slow(id, owner, create) + } + + #[cold] + #[inline(never)] + fn get_or_try_slow<F, E>(&self, id: usize, owner: usize, create: F) -> Result<&T, E> + where + F: FnOnce() -> Result<Box<T>, E>, + { + if owner == 0 && self.owner.compare_and_swap(0, id, Ordering::Relaxed) == 0 { + unsafe { + (*self.local.get()) = Some(try!(create())); + return Ok((*self.local.get()).as_ref().unchecked_unwrap()); + } + } + match self.global.get_fast(id) { + Some(x) => Ok(x), + None => Ok(self.global.insert(id, try!(create()), true)), + } + } + + /// Returns a mutable iterator over the local values of all threads. + /// + /// Since this call borrows the `ThreadLocal` mutably, this operation can + /// be done safely---the mutable borrow statically guarantees no other + /// threads are currently accessing their associated values. + pub fn iter_mut(&mut self) -> CachedIterMut<T> { + unsafe { + (*self.local.get()).as_mut().into_iter().chain( + self.global + .iter_mut(), + ) + } + } + + /// Removes all thread-specific values from the `ThreadLocal`, effectively + /// reseting it to its original state. + /// + /// Since this call borrows the `ThreadLocal` mutably, this operation can + /// be done safely---the mutable borrow statically guarantees no other + /// threads are currently accessing their associated values. + pub fn clear(&mut self) { + *self = CachedThreadLocal::new(); + } +} + +impl<T: ?Sized + Send> IntoIterator for CachedThreadLocal<T> { + type Item = Box<T>; + type IntoIter = CachedIntoIter<T>; + + fn into_iter(self) -> CachedIntoIter<T> { + unsafe { + (*self.local.get()).take().into_iter().chain( + self.global + .into_iter(), + ) + } + } +} + +impl<'a, T: ?Sized + Send + 'a> IntoIterator for &'a mut CachedThreadLocal<T> { + type Item = &'a mut Box<T>; + type IntoIter = CachedIterMut<'a, T>; + + fn into_iter(self) -> CachedIterMut<'a, T> { + self.iter_mut() + } +} + +impl<T: Send + Default> CachedThreadLocal<T> { + /// Returns the element for the current thread, or creates a default one if + /// it doesn't exist. + pub fn get_default(&self) -> &T { + self.get_or(|| Box::new(T::default())) + } +} + +impl<T: ?Sized + Send + fmt::Debug> fmt::Debug for CachedThreadLocal<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ThreadLocal {{ local_data: {:?} }}", self.get()) + } +} + +/// Mutable iterator over the contents of a `CachedThreadLocal`. +pub type CachedIterMut<'a, T> = Chain<OptionIter<&'a mut Box<T>>, IterMut<'a, T>>; + +/// An iterator that moves out of a `CachedThreadLocal`. +pub type CachedIntoIter<T> = Chain<OptionIter<Box<T>>, IntoIter<T>>; + +impl<T: ?Sized + Send + UnwindSafe> UnwindSafe for CachedThreadLocal<T> {} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering::Relaxed; + use std::thread; + use super::{ThreadLocal, CachedThreadLocal}; + + fn make_create() -> Arc<Fn() -> Box<usize> + Send + Sync> { + let count = AtomicUsize::new(0); + Arc::new(move || Box::new(count.fetch_add(1, Relaxed))) + } + + #[test] + fn same_thread() { + let create = make_create(); + let mut tls = ThreadLocal::new(); + assert_eq!(None, tls.get()); + assert_eq!("ThreadLocal { local_data: None }", format!("{:?}", &tls)); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + assert_eq!("ThreadLocal { local_data: Some(0) }", format!("{:?}", &tls)); + tls.clear(); + assert_eq!(None, tls.get()); + } + + #[test] + fn same_thread_cached() { + let create = make_create(); + let mut tls = CachedThreadLocal::new(); + assert_eq!(None, tls.get()); + assert_eq!("ThreadLocal { local_data: None }", format!("{:?}", &tls)); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + assert_eq!("ThreadLocal { local_data: Some(0) }", format!("{:?}", &tls)); + tls.clear(); + assert_eq!(None, tls.get()); + } + + #[test] + fn different_thread() { + let create = make_create(); + let tls = Arc::new(ThreadLocal::new()); + assert_eq!(None, tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + + let tls2 = tls.clone(); + let create2 = create.clone(); + thread::spawn(move || { + assert_eq!(None, tls2.get()); + assert_eq!(1, *tls2.get_or(|| create2())); + assert_eq!(Some(&1), tls2.get()); + }).join() + .unwrap(); + + assert_eq!(Some(&0), tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + } + + #[test] + fn different_thread_cached() { + let create = make_create(); + let tls = Arc::new(CachedThreadLocal::new()); + assert_eq!(None, tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + assert_eq!(Some(&0), tls.get()); + + let tls2 = tls.clone(); + let create2 = create.clone(); + thread::spawn(move || { + assert_eq!(None, tls2.get()); + assert_eq!(1, *tls2.get_or(|| create2())); + assert_eq!(Some(&1), tls2.get()); + }).join() + .unwrap(); + + assert_eq!(Some(&0), tls.get()); + assert_eq!(0, *tls.get_or(|| create())); + } + + #[test] + fn iter() { + let tls = Arc::new(ThreadLocal::new()); + tls.get_or(|| Box::new(1)); + + let tls2 = tls.clone(); + thread::spawn(move || { + tls2.get_or(|| Box::new(2)); + let tls3 = tls2.clone(); + thread::spawn(move || { tls3.get_or(|| Box::new(3)); }) + .join() + .unwrap(); + }).join() + .unwrap(); + + let mut tls = Arc::try_unwrap(tls).unwrap(); + let mut v = tls.iter_mut().map(|x| **x).collect::<Vec<i32>>(); + v.sort(); + assert_eq!(vec![1, 2, 3], v); + let mut v = tls.into_iter().map(|x| *x).collect::<Vec<i32>>(); + v.sort(); + assert_eq!(vec![1, 2, 3], v); + } + + #[test] + fn iter_cached() { + let tls = Arc::new(CachedThreadLocal::new()); + tls.get_or(|| Box::new(1)); + + let tls2 = tls.clone(); + thread::spawn(move || { + tls2.get_or(|| Box::new(2)); + let tls3 = tls2.clone(); + thread::spawn(move || { tls3.get_or(|| Box::new(3)); }) + .join() + .unwrap(); + }).join() + .unwrap(); + + let mut tls = Arc::try_unwrap(tls).unwrap(); + let mut v = tls.iter_mut().map(|x| **x).collect::<Vec<i32>>(); + v.sort(); + assert_eq!(vec![1, 2, 3], v); + let mut v = tls.into_iter().map(|x| *x).collect::<Vec<i32>>(); + v.sort(); + assert_eq!(vec![1, 2, 3], v); + } + + #[test] + fn is_sync() { + fn foo<T: Sync>() {} + foo::<ThreadLocal<String>>(); + foo::<ThreadLocal<RefCell<String>>>(); + foo::<CachedThreadLocal<String>>(); + foo::<CachedThreadLocal<RefCell<String>>>(); + } +} diff --git a/bash-5.1/vendor/thread_local/src/thread_id.rs b/bash-5.1/vendor/thread_local/src/thread_id.rs new file mode 100644 index 0000000..e757948 --- /dev/null +++ b/bash-5.1/vendor/thread_local/src/thread_id.rs @@ -0,0 +1,61 @@ +// Copyright 2017 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use std::collections::BinaryHeap; +use std::sync::Mutex; +use std::usize; + +// Thread ID manager which allocates thread IDs. It attempts to aggressively +// reuse thread IDs where possible to avoid cases where a ThreadLocal grows +// indefinitely when it is used by many short-lived threads. +struct ThreadIdManager { + limit: usize, + free_list: BinaryHeap<usize>, +} +impl ThreadIdManager { + fn new() -> ThreadIdManager { + ThreadIdManager { + limit: usize::MAX, + free_list: BinaryHeap::new(), + } + } + fn alloc(&mut self) -> usize { + if let Some(id) = self.free_list.pop() { + id + } else { + let id = self.limit; + self.limit = self.limit.checked_sub(1).expect("Ran out of thread IDs"); + id + } + } + fn free(&mut self, id: usize) { + self.free_list.push(id); + } +} +lazy_static! { + static ref THREAD_ID_MANAGER: Mutex<ThreadIdManager> = Mutex::new(ThreadIdManager::new()); +} + +// Non-zero integer which is unique to the current thread while it is running. +// A thread ID may be reused after a thread exits. +struct ThreadId(usize); +impl ThreadId { + fn new() -> ThreadId { + ThreadId(THREAD_ID_MANAGER.lock().unwrap().alloc()) + } +} +impl Drop for ThreadId { + fn drop(&mut self) { + THREAD_ID_MANAGER.lock().unwrap().free(self.0); + } +} +thread_local!(static THREAD_ID: ThreadId = ThreadId::new()); + +/// Returns a non-zero ID for the current thread +pub fn get() -> usize { + THREAD_ID.with(|x| x.0) +} diff --git a/bash-5.1/vendor/thread_local/src/unreachable.rs b/bash-5.1/vendor/thread_local/src/unreachable.rs new file mode 100644 index 0000000..baff766 --- /dev/null +++ b/bash-5.1/vendor/thread_local/src/unreachable.rs @@ -0,0 +1,74 @@ +// Copyright 2017 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +//! # unreachable +//! inlined from https://github.com/reem/rust-unreachable/ +//! +//! An unreachable code optimization hint in stable rust, and some useful +//! extension traits for `Option` and `Result`. +//! + +/// Hint to the optimizer that any code path which calls this function is +/// statically unreachable and can be removed. +/// +/// Calling this function in reachable code invokes undefined behavior. Be +/// very, very sure this is what you want; often, a simple `panic!` is more +/// suitable. +#[inline] +pub unsafe fn unreachable() -> ! { + /// The empty type for cases which can't occur. + enum Void { } + let x: &Void = ::std::mem::transmute(1usize); + match *x {} +} + +/// An extension trait for `Option<T>` providing unchecked unwrapping methods. +pub trait UncheckedOptionExt<T> { + /// Get the value out of this Option without checking for None. + unsafe fn unchecked_unwrap(self) -> T; + + /// Assert that this Option is a None to the optimizer. + unsafe fn unchecked_unwrap_none(self); +} + +/// An extension trait for `Result<T, E>` providing unchecked unwrapping methods. +pub trait UncheckedResultExt<T, E> { + /// Get the value out of this Result without checking for Err. + unsafe fn unchecked_unwrap_ok(self) -> T; + + /// Get the error out of this Result without checking for Ok. + unsafe fn unchecked_unwrap_err(self) -> E; +} + +impl<T> UncheckedOptionExt<T> for Option<T> { + unsafe fn unchecked_unwrap(self) -> T { + match self { + Some(x) => x, + None => unreachable() + } + } + + unsafe fn unchecked_unwrap_none(self) { + if self.is_some() { unreachable() } + } +} + +impl<T, E> UncheckedResultExt<T, E> for Result<T, E> { + unsafe fn unchecked_unwrap_ok(self) -> T { + match self { + Ok(x) => x, + Err(_) => unreachable() + } + } + + unsafe fn unchecked_unwrap_err(self) -> E { + match self { + Ok(_) => unreachable(), + Err(e) => e + } + } +} \ No newline at end of file diff --git a/bash-5.1/vendor/tinystr/LICENSE b/bash-5.1/vendor/tinystr/LICENSE new file mode 100644 index 0000000..9858d01 --- /dev/null +++ b/bash-5.1/vendor/tinystr/LICENSE @@ -0,0 +1,51 @@ +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +See Terms of Use <https://www.unicode.org/copyright.html> +for definitions of Unicode Inc.’s Data Files and Software. + +NOTICE TO USER: Carefully read the following legal agreement. +BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S +DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), +YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. +IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE +THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2022 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in https://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. + +— + +Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. +ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. diff --git a/bash-5.1/vendor/tinystr/benches/common/mod.rs b/bash-5.1/vendor/tinystr/benches/common/mod.rs new file mode 100644 index 0000000..07654e1 --- /dev/null +++ b/bash-5.1/vendor/tinystr/benches/common/mod.rs @@ -0,0 +1,79 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +// This file was adapted from parts of https://github.com/zbraniecki/tinystr + +pub static STRINGS_4: &[&str] = &[ + "US", "GB", "AR", "Hans", "CN", "AT", "PL", "FR", "AT", "Cyrl", "SR", "NO", "FR", "MK", "UK", +]; + +pub static STRINGS_8: &[&str] = &[ + "Latn", "windows", "AR", "Hans", "macos", "AT", "pl", "FR", "en", "Cyrl", "SR", "NO", "419", + "und", "UK", +]; + +pub static STRINGS_16: &[&str] = &[ + "Latn", + "windows", + "AR", + "Hans", + "macos", + "AT", + "infiniband", + "FR", + "en", + "Cyrl", + "FromIntegral", + "NO", + "419", + "MacintoshOSX2019", + "UK", +]; + +#[macro_export] +macro_rules! bench_block { + ($c:expr, $name:expr, $action:ident) => { + let mut group4 = $c.benchmark_group(&format!("{}/4", $name)); + group4.bench_function("String", $action!(String, STRINGS_4)); + group4.bench_function("TinyAsciiStr<4>", $action!(TinyAsciiStr<4>, STRINGS_4)); + group4.bench_function( + "tinystr_old::TinyStr4", + $action!(tinystr_old::TinyStr4, STRINGS_4), + ); + group4.bench_function("TinyAsciiStr<8>", $action!(TinyAsciiStr<8>, STRINGS_4)); + group4.bench_function( + "tinystr_old::TinyStr8", + $action!(tinystr_old::TinyStr8, STRINGS_4), + ); + group4.bench_function("TinyAsciiStr<16>", $action!(TinyAsciiStr<16>, STRINGS_4)); + group4.bench_function( + "tinystr_old::TinyStr16", + $action!(tinystr_old::TinyStr16, STRINGS_4), + ); + group4.finish(); + + let mut group8 = $c.benchmark_group(&format!("{}/8", $name)); + group8.bench_function("String", $action!(String, STRINGS_8)); + group8.bench_function("TinyAsciiStr<8>", $action!(TinyAsciiStr<8>, STRINGS_8)); + group8.bench_function("TinyAsciiStr<16>", $action!(TinyAsciiStr<16>, STRINGS_8)); + group8.bench_function( + "tinystr_old::TinyStr8", + $action!(tinystr_old::TinyStr8, STRINGS_8), + ); + group8.bench_function( + "tinystr_old::TinyStr16", + $action!(tinystr_old::TinyStr16, STRINGS_8), + ); + group8.finish(); + + let mut group16 = $c.benchmark_group(&format!("{}/16", $name)); + group16.bench_function("String", $action!(String, STRINGS_16)); + group16.bench_function("TinyAsciiStr<16>", $action!(TinyAsciiStr<16>, STRINGS_16)); + group16.bench_function( + "tinystr_old::TinyStr16", + $action!(tinystr_old::TinyStr16, STRINGS_16), + ); + group16.finish(); + }; +} diff --git a/bash-5.1/vendor/tinystr/benches/overview.rs b/bash-5.1/vendor/tinystr/benches/overview.rs new file mode 100644 index 0000000..4911832 --- /dev/null +++ b/bash-5.1/vendor/tinystr/benches/overview.rs @@ -0,0 +1,165 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +mod common; +use common::*; + +use criterion::black_box; +use criterion::criterion_group; +use criterion::criterion_main; +use criterion::Criterion; + +use tinystr::TinyAsciiStr; +use tinystr_old::TinyStr16; +use tinystr_old::TinyStr4; +use tinystr_old::TinyStr8; + +fn overview(c: &mut Criterion) { + let mut g = c.benchmark_group("overview"); + + g.bench_function("construct/TinyAsciiStr", |b| { + b.iter(|| { + for s in STRINGS_4 { + let _: TinyAsciiStr<4> = black_box(s).parse().unwrap(); + let _: TinyAsciiStr<8> = black_box(s).parse().unwrap(); + let _: TinyAsciiStr<16> = black_box(s).parse().unwrap(); + } + for s in STRINGS_8 { + let _: TinyAsciiStr<8> = black_box(s).parse().unwrap(); + let _: TinyAsciiStr<16> = black_box(s).parse().unwrap(); + } + for s in STRINGS_16 { + let _: TinyAsciiStr<16> = black_box(s).parse().unwrap(); + } + }); + }); + + g.bench_function("construct/TinyStr", |b| { + b.iter(|| { + for s in STRINGS_4 { + let _: TinyStr4 = black_box(s).parse().unwrap(); + let _: TinyStr8 = black_box(s).parse().unwrap(); + let _: TinyStr16 = black_box(s).parse().unwrap(); + } + for s in STRINGS_8 { + let _: TinyStr8 = black_box(s).parse().unwrap(); + let _: TinyStr16 = black_box(s).parse().unwrap(); + } + for s in STRINGS_16 { + let _: TinyStr16 = black_box(s).parse().unwrap(); + } + }); + }); + + let parsed_ascii_4: Vec<TinyAsciiStr<4>> = STRINGS_4 + .iter() + .map(|s| s.parse::<TinyAsciiStr<4>>().unwrap()) + .collect(); + let parsed_ascii_8: Vec<TinyAsciiStr<8>> = STRINGS_4 + .iter() + .chain(STRINGS_8) + .map(|s| s.parse::<TinyAsciiStr<8>>().unwrap()) + .collect(); + let parsed_ascii_16: Vec<TinyAsciiStr<16>> = STRINGS_4 + .iter() + .chain(STRINGS_8) + .chain(STRINGS_16) + .map(|s| s.parse::<TinyAsciiStr<16>>().unwrap()) + .collect(); + + let parsed_tiny_4: Vec<TinyStr4> = STRINGS_4 + .iter() + .map(|s| s.parse::<TinyStr4>().unwrap()) + .collect(); + let parsed_tiny_8: Vec<TinyStr8> = STRINGS_4 + .iter() + .chain(STRINGS_8) + .map(|s| s.parse::<TinyStr8>().unwrap()) + .collect(); + let parsed_tiny_16: Vec<TinyStr16> = STRINGS_4 + .iter() + .chain(STRINGS_8) + .chain(STRINGS_16) + .map(|s| s.parse::<TinyStr16>().unwrap()) + .collect(); + + g.bench_function("read/TinyAsciiStr", |b| { + b.iter(|| { + let mut collector: usize = 0; + for t in black_box(&parsed_ascii_4) { + let s: &str = t; + collector += s.bytes().map(usize::from).sum::<usize>(); + } + for t in black_box(&parsed_ascii_8) { + let s: &str = t; + collector += s.bytes().map(usize::from).sum::<usize>(); + } + for t in black_box(&parsed_ascii_16) { + let s: &str = t; + collector += s.bytes().map(usize::from).sum::<usize>(); + } + collector + }); + }); + + g.bench_function("read/TinyStr", |b| { + b.iter(|| { + let mut collector: usize = 0; + for t in black_box(&parsed_tiny_4) { + let s: &str = t; + collector += s.bytes().map(usize::from).sum::<usize>(); + } + for t in black_box(&parsed_tiny_8) { + let s: &str = t; + collector += s.bytes().map(usize::from).sum::<usize>(); + } + for t in black_box(&parsed_tiny_16) { + let s: &str = t; + collector += s.bytes().map(usize::from).sum::<usize>(); + } + collector + }); + }); + + g.bench_function("compare/TinyAsciiStr", |b| { + b.iter(|| { + let mut collector: usize = 0; + for ts in black_box(&parsed_ascii_4).windows(2) { + let o = ts[0].cmp(&ts[1]); + collector ^= o as usize; + } + for ts in black_box(&parsed_ascii_8).windows(2) { + let o = ts[0].cmp(&ts[1]); + collector ^= o as usize; + } + for ts in black_box(&parsed_ascii_16).windows(2) { + let o = ts[0].cmp(&ts[1]); + collector ^= o as usize; + } + collector + }); + }); + + g.bench_function("compare/TinyStr", |b| { + b.iter(|| { + let mut collector: usize = 0; + for ts in black_box(&parsed_tiny_4).windows(2) { + let o = ts[0].cmp(&ts[1]); + collector ^= o as usize; + } + for ts in black_box(&parsed_tiny_8).windows(2) { + let o = ts[0].cmp(&ts[1]); + collector ^= o as usize; + } + for ts in black_box(&parsed_tiny_16).windows(2) { + let o = ts[0].cmp(&ts[1]); + collector ^= o as usize; + } + collector + }); + }); +} + +criterion_group!(benches, overview,); +criterion_main!(benches); diff --git a/bash-5.1/vendor/tinystr/benches/read.rs b/bash-5.1/vendor/tinystr/benches/read.rs new file mode 100644 index 0000000..793bb14 --- /dev/null +++ b/bash-5.1/vendor/tinystr/benches/read.rs @@ -0,0 +1,34 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +mod common; +use common::*; + +use criterion::black_box; +use criterion::criterion_group; +use criterion::criterion_main; +use criterion::Bencher; +use criterion::Criterion; + +use tinystr::TinyAsciiStr; + +fn read(c: &mut Criterion) { + macro_rules! cfs { + ($r:ty, $inputs:expr) => { + |b: &mut Bencher| { + let parsed: Vec<$r> = $inputs.iter().map(|s| s.parse().unwrap()).collect(); + b.iter(|| { + for s in &parsed { + let _: &str = black_box(&**s); + } + }) + } + }; + } + + bench_block!(c, "read", cfs); +} + +criterion_group!(benches, read,); +criterion_main!(benches); diff --git a/bash-5.1/vendor/tinystr/benches/serde.rs b/bash-5.1/vendor/tinystr/benches/serde.rs new file mode 100644 index 0000000..b034122 --- /dev/null +++ b/bash-5.1/vendor/tinystr/benches/serde.rs @@ -0,0 +1,37 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +mod common; +use common::*; + +use criterion::black_box; +use criterion::criterion_group; +use criterion::criterion_main; +use criterion::Bencher; +use criterion::Criterion; + +use tinystr::TinyAsciiStr; + +fn deserialize(c: &mut Criterion) { + macro_rules! cfs { + ($r:ty, $inputs:expr) => { + |b: &mut Bencher| { + let serialized: Vec<Vec<u8>> = $inputs + .iter() + .map(|s| postcard::to_stdvec(&s.parse::<$r>().unwrap()).unwrap()) + .collect(); + b.iter(|| { + for bytes in &serialized { + let _: Result<$r, _> = black_box(postcard::from_bytes(bytes)); + } + }) + } + }; + } + + bench_block!(c, "deserialize", cfs); +} + +criterion_group!(benches, deserialize,); +criterion_main!(benches); diff --git a/bash-5.1/vendor/tinystr/src/ascii.rs b/bash-5.1/vendor/tinystr/src/ascii.rs new file mode 100644 index 0000000..f39f39b --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/ascii.rs @@ -0,0 +1,982 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::asciibyte::AsciiByte; +use crate::int_ops::{Aligned4, Aligned8}; +use crate::TinyStrError; +use core::fmt; +use core::ops::Deref; +use core::str::{self, FromStr}; + +#[repr(transparent)] +#[derive(PartialEq, Eq, Ord, PartialOrd, Copy, Clone, Hash)] +pub struct TinyAsciiStr<const N: usize> { + bytes: [AsciiByte; N], +} + +impl<const N: usize> TinyAsciiStr<N> { + /// Creates a `TinyAsciiStr<N>` from the given byte slice. + /// `bytes` may contain at most `N` non-null ASCII bytes. + pub const fn from_bytes(bytes: &[u8]) -> Result<Self, TinyStrError> { + Self::from_bytes_inner(bytes, 0, bytes.len(), false) + } + + /// Attempts to parse a fixed-length byte array to a `TinyAsciiStr`. + /// + /// The byte array may contain trailing NUL bytes. + /// + /// # Example + /// + /// ``` + /// use tinystr::tinystr; + /// use tinystr::TinyAsciiStr; + /// + /// assert_eq!( + /// TinyAsciiStr::<3>::try_from_raw(*b"GB\0"), + /// Ok(tinystr!(3, "GB")) + /// ); + /// assert_eq!( + /// TinyAsciiStr::<3>::try_from_raw(*b"USD"), + /// Ok(tinystr!(3, "USD")) + /// ); + /// assert!(matches!(TinyAsciiStr::<3>::try_from_raw(*b"\0A\0"), Err(_))); + /// ``` + pub const fn try_from_raw(raw: [u8; N]) -> Result<Self, TinyStrError> { + Self::from_bytes_inner(&raw, 0, N, true) + } + + /// Equivalent to [`from_bytes(bytes[start..end])`](Self::from_bytes), + /// but callable in a `const` context (which range indexing is not). + pub const fn from_bytes_manual_slice( + bytes: &[u8], + start: usize, + end: usize, + ) -> Result<Self, TinyStrError> { + Self::from_bytes_inner(bytes, start, end, false) + } + + #[inline] + pub(crate) const fn from_bytes_inner( + bytes: &[u8], + start: usize, + end: usize, + allow_trailing_null: bool, + ) -> Result<Self, TinyStrError> { + let len = end - start; + if len > N { + return Err(TinyStrError::TooLarge { max: N, len }); + } + + let mut out = [0; N]; + let mut i = 0; + let mut found_null = false; + // Indexing is protected by TinyStrError::TooLarge + #[allow(clippy::indexing_slicing)] + while i < len { + let b = bytes[start + i]; + + if b == 0 { + found_null = true; + } else if b >= 0x80 { + return Err(TinyStrError::NonAscii); + } else if found_null { + // Error if there are contentful bytes after null + return Err(TinyStrError::ContainsNull); + } + out[i] = b; + + i += 1; + } + + if !allow_trailing_null && found_null { + // We found some trailing nulls, error + return Err(TinyStrError::ContainsNull); + } + + Ok(Self { + // SAFETY: `out` only contains ASCII bytes and has same size as `self.bytes` + bytes: unsafe { AsciiByte::to_ascii_byte_array(&out) }, + }) + } + + // TODO: This function shadows the FromStr trait. Rename? + #[inline] + pub const fn from_str(s: &str) -> Result<Self, TinyStrError> { + Self::from_bytes_inner(s.as_bytes(), 0, s.len(), false) + } + + #[inline] + pub const fn as_str(&self) -> &str { + // as_bytes is valid utf8 + unsafe { str::from_utf8_unchecked(self.as_bytes()) } + } + + #[inline] + #[must_use] + pub const fn len(&self) -> usize { + if N <= 4 { + Aligned4::from_ascii_bytes(&self.bytes).len() + } else if N <= 8 { + Aligned8::from_ascii_bytes(&self.bytes).len() + } else { + let mut i = 0; + #[allow(clippy::indexing_slicing)] // < N is safe + while i < N && self.bytes[i] as u8 != AsciiByte::B0 as u8 { + i += 1 + } + i + } + } + + #[inline] + #[must_use] + pub const fn is_empty(&self) -> bool { + self.bytes[0] as u8 == AsciiByte::B0 as u8 + } + + #[inline] + #[must_use] + pub const fn as_bytes(&self) -> &[u8] { + // Safe because `self.bytes.as_slice()` pointer-casts to `&[u8]`, + // and changing the length of that slice to self.len() < N is safe. + unsafe { core::mem::transmute((self.bytes.as_slice().as_ptr(), self.len())) } + } + + #[inline] + #[must_use] + pub const fn all_bytes(&self) -> &[u8; N] { + // SAFETY: `self.bytes` has same size as [u8; N] + unsafe { core::mem::transmute(&self.bytes) } + } + + #[inline] + #[must_use] + /// Resizes a TinyAsciiStr<N> to a TinyAsciiStr<M>. + /// + /// If M < len() the string gets truncated, otherwise only the + /// memory representation changes. + pub const fn resize<const M: usize>(self) -> TinyAsciiStr<M> { + let mut bytes = [0; M]; + let mut i = 0; + // Indexing is protected by the loop guard + #[allow(clippy::indexing_slicing)] + while i < M && i < N { + bytes[i] = self.bytes[i] as u8; + i += 1; + } + // `self.bytes` only contains ASCII bytes, with no null bytes between + // ASCII characters, so this also holds for `bytes`. + unsafe { TinyAsciiStr::from_bytes_unchecked(bytes) } + } + + /// # Safety + /// Must be called with a bytes array made of valid ASCII bytes, with no null bytes + /// between ASCII characters + #[must_use] + pub const unsafe fn from_bytes_unchecked(bytes: [u8; N]) -> Self { + Self { + bytes: AsciiByte::to_ascii_byte_array(&bytes), + } + } +} + +macro_rules! check_is { + ($self:ident, $check_int:ident, $check_u8:ident) => { + if N <= 4 { + Aligned4::from_ascii_bytes(&$self.bytes).$check_int() + } else if N <= 8 { + Aligned8::from_ascii_bytes(&$self.bytes).$check_int() + } else { + let mut i = 0; + // Won't panic because self.bytes has length N + #[allow(clippy::indexing_slicing)] + while i < N && $self.bytes[i] as u8 != AsciiByte::B0 as u8 { + if !($self.bytes[i] as u8).$check_u8() { + return false; + } + i += 1; + } + true + } + }; + ($self:ident, $check_int:ident, !$check_u8_0_inv:ident, !$check_u8_1_inv:ident) => { + if N <= 4 { + Aligned4::from_ascii_bytes(&$self.bytes).$check_int() + } else if N <= 8 { + Aligned8::from_ascii_bytes(&$self.bytes).$check_int() + } else { + // Won't panic because N is > 8 + if ($self.bytes[0] as u8).$check_u8_0_inv() { + return false; + } + let mut i = 1; + // Won't panic because self.bytes has length N + #[allow(clippy::indexing_slicing)] + while i < N && $self.bytes[i] as u8 != AsciiByte::B0 as u8 { + if ($self.bytes[i] as u8).$check_u8_1_inv() { + return false; + } + i += 1; + } + true + } + }; + ($self:ident, $check_int:ident, $check_u8_0_inv:ident, $check_u8_1_inv:ident) => { + if N <= 4 { + Aligned4::from_ascii_bytes(&$self.bytes).$check_int() + } else if N <= 8 { + Aligned8::from_ascii_bytes(&$self.bytes).$check_int() + } else { + // Won't panic because N is > 8 + if !($self.bytes[0] as u8).$check_u8_0_inv() { + return false; + } + let mut i = 1; + // Won't panic because self.bytes has length N + #[allow(clippy::indexing_slicing)] + while i < N && $self.bytes[i] as u8 != AsciiByte::B0 as u8 { + if !($self.bytes[i] as u8).$check_u8_1_inv() { + return false; + } + i += 1; + } + true + } + }; +} + +impl<const N: usize> TinyAsciiStr<N> { + /// Checks if the value is composed of ASCII alphabetic characters: + /// + /// * U+0041 'A' ..= U+005A 'Z', or + /// * U+0061 'a' ..= U+007A 'z'. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "Test".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "Te3t".parse().expect("Failed to parse."); + /// + /// assert!(s1.is_ascii_alphabetic()); + /// assert!(!s2.is_ascii_alphabetic()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_alphabetic(&self) -> bool { + check_is!(self, is_ascii_alphabetic, is_ascii_alphabetic) + } + + /// Checks if the value is composed of ASCII alphanumeric characters: + /// + /// * U+0041 'A' ..= U+005A 'Z', or + /// * U+0061 'a' ..= U+007A 'z', or + /// * U+0030 '0' ..= U+0039 '9'. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "A15b".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "[3@w".parse().expect("Failed to parse."); + /// + /// assert!(s1.is_ascii_alphanumeric()); + /// assert!(!s2.is_ascii_alphanumeric()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_alphanumeric(&self) -> bool { + check_is!(self, is_ascii_alphanumeric, is_ascii_alphanumeric) + } + + /// Checks if the value is composed of ASCII decimal digits: + /// + /// * U+0030 '0' ..= U+0039 '9'. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "312".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "3d".parse().expect("Failed to parse."); + /// + /// assert!(s1.is_ascii_numeric()); + /// assert!(!s2.is_ascii_numeric()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_numeric(&self) -> bool { + check_is!(self, is_ascii_numeric, is_ascii_digit) + } + + /// Checks if the value is in ASCII lower case. + /// + /// All letter characters are checked for case. Non-letter characters are ignored. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "test".parse().expect("Failed to parse."); + /// let s3: TinyAsciiStr<4> = "001z".parse().expect("Failed to parse."); + /// + /// assert!(!s1.is_ascii_lowercase()); + /// assert!(s2.is_ascii_lowercase()); + /// assert!(s3.is_ascii_lowercase()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_lowercase(&self) -> bool { + check_is!( + self, + is_ascii_lowercase, + !is_ascii_uppercase, + !is_ascii_uppercase + ) + } + + /// Checks if the value is in ASCII title case. + /// + /// This verifies that the first character is ASCII uppercase and all others ASCII lowercase. + /// Non-letter characters are ignored. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "Test".parse().expect("Failed to parse."); + /// let s3: TinyAsciiStr<4> = "001z".parse().expect("Failed to parse."); + /// + /// assert!(!s1.is_ascii_titlecase()); + /// assert!(s2.is_ascii_titlecase()); + /// assert!(s3.is_ascii_titlecase()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_titlecase(&self) -> bool { + check_is!( + self, + is_ascii_titlecase, + !is_ascii_lowercase, + !is_ascii_uppercase + ) + } + + /// Checks if the value is in ASCII upper case. + /// + /// All letter characters are checked for case. Non-letter characters are ignored. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "TEST".parse().expect("Failed to parse."); + /// let s3: TinyAsciiStr<4> = "001z".parse().expect("Failed to parse."); + /// + /// assert!(!s1.is_ascii_uppercase()); + /// assert!(s2.is_ascii_uppercase()); + /// assert!(!s3.is_ascii_uppercase()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_uppercase(&self) -> bool { + check_is!( + self, + is_ascii_uppercase, + !is_ascii_lowercase, + !is_ascii_lowercase + ) + } + + /// Checks if the value is composed of ASCII alphabetic lower case characters: + /// + /// * U+0061 'a' ..= U+007A 'z', + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "Test".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "Te3t".parse().expect("Failed to parse."); + /// let s3: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// let s4: TinyAsciiStr<4> = "test".parse().expect("Failed to parse."); + /// let s5: TinyAsciiStr<4> = "001z".parse().expect("Failed to parse."); + /// + /// assert!(!s1.is_ascii_alphabetic_lowercase()); + /// assert!(!s2.is_ascii_alphabetic_lowercase()); + /// assert!(!s3.is_ascii_alphabetic_lowercase()); + /// assert!(s4.is_ascii_alphabetic_lowercase()); + /// assert!(!s5.is_ascii_alphabetic_lowercase()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_alphabetic_lowercase(&self) -> bool { + check_is!( + self, + is_ascii_alphabetic_lowercase, + is_ascii_lowercase, + is_ascii_lowercase + ) + } + + /// Checks if the value is composed of ASCII alphabetic, with the first character being ASCII uppercase, and all others ASCII lowercase. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "Test".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "Te3t".parse().expect("Failed to parse."); + /// let s3: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// let s4: TinyAsciiStr<4> = "test".parse().expect("Failed to parse."); + /// let s5: TinyAsciiStr<4> = "001z".parse().expect("Failed to parse."); + /// + /// assert!(s1.is_ascii_alphabetic_titlecase()); + /// assert!(!s2.is_ascii_alphabetic_titlecase()); + /// assert!(!s3.is_ascii_alphabetic_titlecase()); + /// assert!(!s4.is_ascii_alphabetic_titlecase()); + /// assert!(!s5.is_ascii_alphabetic_titlecase()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_alphabetic_titlecase(&self) -> bool { + check_is!( + self, + is_ascii_alphabetic_titlecase, + is_ascii_uppercase, + is_ascii_lowercase + ) + } + + /// Checks if the value is composed of ASCII alphabetic upper case characters: + /// + /// * U+0041 'A' ..= U+005A 'Z', + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "Test".parse().expect("Failed to parse."); + /// let s2: TinyAsciiStr<4> = "Te3t".parse().expect("Failed to parse."); + /// let s3: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// let s4: TinyAsciiStr<4> = "TEST".parse().expect("Failed to parse."); + /// let s5: TinyAsciiStr<4> = "001z".parse().expect("Failed to parse."); + /// + /// assert!(!s1.is_ascii_alphabetic_uppercase()); + /// assert!(!s2.is_ascii_alphabetic_uppercase()); + /// assert!(!s3.is_ascii_alphabetic_uppercase()); + /// assert!(s4.is_ascii_alphabetic_uppercase()); + /// assert!(!s5.is_ascii_alphabetic_uppercase()); + /// ``` + #[inline] + #[must_use] + pub const fn is_ascii_alphabetic_uppercase(&self) -> bool { + check_is!( + self, + is_ascii_alphabetic_uppercase, + is_ascii_uppercase, + is_ascii_uppercase + ) + } +} + +macro_rules! to { + ($self:ident, $to:ident, $later_char_to:ident $(,$first_char_to:ident)?) => {{ + let mut i = 0; + if N <= 4 { + let aligned = Aligned4::from_ascii_bytes(&$self.bytes).$to().to_ascii_bytes(); + // Won't panic because self.bytes has length N and aligned has length >= N + #[allow(clippy::indexing_slicing)] + while i < N { + $self.bytes[i] = aligned[i]; + i += 1; + } + } else if N <= 8 { + let aligned = Aligned8::from_ascii_bytes(&$self.bytes).$to().to_ascii_bytes(); + // Won't panic because self.bytes has length N and aligned has length >= N + #[allow(clippy::indexing_slicing)] + while i < N { + $self.bytes[i] = aligned[i]; + i += 1; + } + } else { + // Won't panic because self.bytes has length N + #[allow(clippy::indexing_slicing)] + while i < N && $self.bytes[i] as u8 != AsciiByte::B0 as u8 { + // SAFETY: AsciiByte is repr(u8) and has same size as u8 + unsafe { + $self.bytes[i] = core::mem::transmute( + ($self.bytes[i] as u8).$later_char_to() + ); + } + i += 1; + } + // SAFETY: AsciiByte is repr(u8) and has same size as u8 + $( + $self.bytes[0] = unsafe { + core::mem::transmute(($self.bytes[0] as u8).$first_char_to()) + }; + )? + } + $self + }}; +} + +impl<const N: usize> TinyAsciiStr<N> { + /// Converts this type to its ASCII lower case equivalent in-place. + /// + /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', other characters are unchanged. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "TeS3".parse().expect("Failed to parse."); + /// + /// assert_eq!(&*s1.to_ascii_lowercase(), "tes3"); + /// ``` + #[inline] + #[must_use] + pub const fn to_ascii_lowercase(mut self) -> Self { + to!(self, to_ascii_lowercase, to_ascii_lowercase) + } + + /// Converts this type to its ASCII title case equivalent in-place. + /// + /// The first character is converted to ASCII uppercase; the remaining characters + /// are converted to ASCII lowercase. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "teSt".parse().expect("Failed to parse."); + /// + /// assert_eq!(&*s1.to_ascii_titlecase(), "Test"); + /// ``` + #[inline] + #[must_use] + pub const fn to_ascii_titlecase(mut self) -> Self { + to!( + self, + to_ascii_titlecase, + to_ascii_lowercase, + to_ascii_uppercase + ) + } + + /// Converts this type to its ASCII upper case equivalent in-place. + /// + /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', other characters are unchanged. + /// + /// # Examples + /// + /// ``` + /// use tinystr::TinyAsciiStr; + /// + /// let s1: TinyAsciiStr<4> = "Tes3".parse().expect("Failed to parse."); + /// + /// assert_eq!(&*s1.to_ascii_uppercase(), "TES3"); + /// ``` + #[inline] + #[must_use] + pub const fn to_ascii_uppercase(mut self) -> Self { + to!(self, to_ascii_uppercase, to_ascii_uppercase) + } +} + +impl<const N: usize> fmt::Debug for TinyAsciiStr<N> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(self.as_str(), f) + } +} + +impl<const N: usize> fmt::Display for TinyAsciiStr<N> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self.as_str(), f) + } +} + +impl<const N: usize> Deref for TinyAsciiStr<N> { + type Target = str; + #[inline] + fn deref(&self) -> &str { + self.as_str() + } +} + +impl<const N: usize> FromStr for TinyAsciiStr<N> { + type Err = TinyStrError; + #[inline] + fn from_str(s: &str) -> Result<Self, TinyStrError> { + Self::from_str(s) + } +} + +impl<const N: usize> PartialEq<str> for TinyAsciiStr<N> { + fn eq(&self, other: &str) -> bool { + self.deref() == other + } +} + +impl<const N: usize> PartialEq<&str> for TinyAsciiStr<N> { + fn eq(&self, other: &&str) -> bool { + self.deref() == *other + } +} + +#[cfg(feature = "alloc")] +impl<const N: usize> PartialEq<alloc::string::String> for TinyAsciiStr<N> { + fn eq(&self, other: &alloc::string::String) -> bool { + self.deref() == other.deref() + } +} + +#[cfg(feature = "alloc")] +impl<const N: usize> PartialEq<TinyAsciiStr<N>> for alloc::string::String { + fn eq(&self, other: &TinyAsciiStr<N>) -> bool { + self.deref() == other.deref() + } +} + +#[cfg(test)] +mod test { + use super::*; + use rand::distributions::Distribution; + use rand::distributions::Standard; + use rand::rngs::SmallRng; + use rand::seq::SliceRandom; + use rand::SeedableRng; + + const STRINGS: [&str; 26] = [ + "Latn", + "laTn", + "windows", + "AR", + "Hans", + "macos", + "AT", + "infiniband", + "FR", + "en", + "Cyrl", + "FromIntegral", + "NO", + "419", + "MacintoshOSX2019", + "a3z", + "A3z", + "A3Z", + "a3Z", + "3A", + "3Z", + "3a", + "3z", + "@@[`{", + "UK", + "E12", + ]; + + fn gen_strings(num_strings: usize, allowed_lengths: &[usize]) -> Vec<String> { + let mut rng = SmallRng::seed_from_u64(2022); + // Need to do this in 2 steps since the RNG is needed twice + let string_lengths = core::iter::repeat_with(|| *allowed_lengths.choose(&mut rng).unwrap()) + .take(num_strings) + .collect::<Vec<usize>>(); + string_lengths + .iter() + .map(|len| { + Standard + .sample_iter(&mut rng) + .filter(|b: &u8| *b > 0 && *b < 0x80) + .take(*len) + .collect::<Vec<u8>>() + }) + .map(|byte_vec| String::from_utf8(byte_vec).expect("All ASCII")) + .collect() + } + + fn check_operation<T, F1, F2, const N: usize>(reference_f: F1, tinystr_f: F2) + where + F1: Fn(&str) -> T, + F2: Fn(TinyAsciiStr<N>) -> T, + T: core::fmt::Debug + core::cmp::PartialEq, + { + for s in STRINGS + .into_iter() + .map(str::to_owned) + .chain(gen_strings(100, &[3, 4, 5, 8, 12])) + { + let t = match TinyAsciiStr::<N>::from_str(&s) { + Ok(t) => t, + Err(TinyStrError::TooLarge { .. }) => continue, + Err(e) => panic!("{}", e), + }; + let expected = reference_f(&s); + let actual = tinystr_f(t); + assert_eq!(expected, actual, "TinyAsciiStr<{}>: {:?}", N, s); + } + } + + #[test] + fn test_is_ascii_alphabetic() { + fn check<const N: usize>() { + check_operation( + |s| s.chars().all(|c| c.is_ascii_alphabetic()), + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_alphabetic(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_alphanumeric() { + fn check<const N: usize>() { + check_operation( + |s| s.chars().all(|c| c.is_ascii_alphanumeric()), + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_alphanumeric(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_numeric() { + fn check<const N: usize>() { + check_operation( + |s| s.chars().all(|c| c.is_ascii_digit()), + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_numeric(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_lowercase() { + fn check<const N: usize>() { + check_operation( + |s| { + s == TinyAsciiStr::<16>::from_str(s) + .unwrap() + .to_ascii_lowercase() + .as_str() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_lowercase(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_titlecase() { + fn check<const N: usize>() { + check_operation( + |s| { + s == TinyAsciiStr::<16>::from_str(s) + .unwrap() + .to_ascii_titlecase() + .as_str() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_titlecase(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_uppercase() { + fn check<const N: usize>() { + check_operation( + |s| { + s == TinyAsciiStr::<16>::from_str(s) + .unwrap() + .to_ascii_uppercase() + .as_str() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_uppercase(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_alphabetic_lowercase() { + fn check<const N: usize>() { + check_operation( + |s| { + // Check alphabetic + s.chars().all(|c| c.is_ascii_alphabetic()) && + // Check lowercase + s == TinyAsciiStr::<16>::from_str(s) + .unwrap() + .to_ascii_lowercase() + .as_str() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_alphabetic_lowercase(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_alphabetic_titlecase() { + fn check<const N: usize>() { + check_operation( + |s| { + // Check alphabetic + s.chars().all(|c| c.is_ascii_alphabetic()) && + // Check titlecase + s == TinyAsciiStr::<16>::from_str(s) + .unwrap() + .to_ascii_titlecase() + .as_str() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_alphabetic_titlecase(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_is_ascii_alphabetic_uppercase() { + fn check<const N: usize>() { + check_operation( + |s| { + // Check alphabetic + s.chars().all(|c| c.is_ascii_alphabetic()) && + // Check uppercase + s == TinyAsciiStr::<16>::from_str(s) + .unwrap() + .to_ascii_uppercase() + .as_str() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::is_ascii_alphabetic_uppercase(&t), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_to_ascii_lowercase() { + fn check<const N: usize>() { + check_operation( + |s| { + s.chars() + .map(|c| c.to_ascii_lowercase()) + .collect::<String>() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::to_ascii_lowercase(t).as_str().to_owned(), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_to_ascii_titlecase() { + fn check<const N: usize>() { + check_operation( + |s| { + let mut r = s + .chars() + .map(|c| c.to_ascii_lowercase()) + .collect::<String>(); + // Safe because the string is nonempty and an ASCII string + unsafe { r.as_bytes_mut()[0].make_ascii_uppercase() }; + r + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::to_ascii_titlecase(t).as_str().to_owned(), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } + + #[test] + fn test_to_ascii_uppercase() { + fn check<const N: usize>() { + check_operation( + |s| { + s.chars() + .map(|c| c.to_ascii_uppercase()) + .collect::<String>() + }, + |t: TinyAsciiStr<N>| TinyAsciiStr::to_ascii_uppercase(t).as_str().to_owned(), + ) + } + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); + check::<8>(); + check::<16>(); + } +} diff --git a/bash-5.1/vendor/tinystr/src/asciibyte.rs b/bash-5.1/vendor/tinystr/src/asciibyte.rs new file mode 100644 index 0000000..f41a033 --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/asciibyte.rs @@ -0,0 +1,145 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +#[repr(u8)] +#[allow(dead_code)] +#[derive(PartialEq, Eq, Ord, PartialOrd, Copy, Clone, Hash)] +pub enum AsciiByte { + B0 = 0, + B1 = 1, + B2 = 2, + B3 = 3, + B4 = 4, + B5 = 5, + B6 = 6, + B7 = 7, + B8 = 8, + B9 = 9, + B10 = 10, + B11 = 11, + B12 = 12, + B13 = 13, + B14 = 14, + B15 = 15, + B16 = 16, + B17 = 17, + B18 = 18, + B19 = 19, + B20 = 20, + B21 = 21, + B22 = 22, + B23 = 23, + B24 = 24, + B25 = 25, + B26 = 26, + B27 = 27, + B28 = 28, + B29 = 29, + B30 = 30, + B31 = 31, + B32 = 32, + B33 = 33, + B34 = 34, + B35 = 35, + B36 = 36, + B37 = 37, + B38 = 38, + B39 = 39, + B40 = 40, + B41 = 41, + B42 = 42, + B43 = 43, + B44 = 44, + B45 = 45, + B46 = 46, + B47 = 47, + B48 = 48, + B49 = 49, + B50 = 50, + B51 = 51, + B52 = 52, + B53 = 53, + B54 = 54, + B55 = 55, + B56 = 56, + B57 = 57, + B58 = 58, + B59 = 59, + B60 = 60, + B61 = 61, + B62 = 62, + B63 = 63, + B64 = 64, + B65 = 65, + B66 = 66, + B67 = 67, + B68 = 68, + B69 = 69, + B70 = 70, + B71 = 71, + B72 = 72, + B73 = 73, + B74 = 74, + B75 = 75, + B76 = 76, + B77 = 77, + B78 = 78, + B79 = 79, + B80 = 80, + B81 = 81, + B82 = 82, + B83 = 83, + B84 = 84, + B85 = 85, + B86 = 86, + B87 = 87, + B88 = 88, + B89 = 89, + B90 = 90, + B91 = 91, + B92 = 92, + B93 = 93, + B94 = 94, + B95 = 95, + B96 = 96, + B97 = 97, + B98 = 98, + B99 = 99, + B100 = 100, + B101 = 101, + B102 = 102, + B103 = 103, + B104 = 104, + B105 = 105, + B106 = 106, + B107 = 107, + B108 = 108, + B109 = 109, + B110 = 110, + B111 = 111, + B112 = 112, + B113 = 113, + B114 = 114, + B115 = 115, + B116 = 116, + B117 = 117, + B118 = 118, + B119 = 119, + B120 = 120, + B121 = 121, + B122 = 122, + B123 = 123, + B124 = 124, + B125 = 125, + B126 = 126, + B127 = 127, +} + +impl AsciiByte { + // Convert [u8; N] to [AsciiByte; N] + #[inline] + pub const unsafe fn to_ascii_byte_array<const N: usize>(bytes: &[u8; N]) -> [AsciiByte; N] { + *(bytes as *const [u8; N] as *const [AsciiByte; N]) + } +} diff --git a/bash-5.1/vendor/tinystr/src/databake.rs b/bash-5.1/vendor/tinystr/src/databake.rs new file mode 100644 index 0000000..e10c194 --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/databake.rs @@ -0,0 +1,21 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::TinyAsciiStr; +use databake::*; + +impl<const N: usize> Bake for TinyAsciiStr<N> { + fn bake(&self, env: &CrateEnv) -> TokenStream { + env.insert("tinystr"); + let string = self.as_str(); + quote! { + ::tinystr::tinystr!(#N, #string) + } + } +} + +#[test] +fn test() { + test_bake!(TinyAsciiStr<10>, const: crate::tinystr!(10usize, "foo"), tinystr); +} diff --git a/bash-5.1/vendor/tinystr/src/error.rs b/bash-5.1/vendor/tinystr/src/error.rs new file mode 100644 index 0000000..7910f8b --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/error.rs @@ -0,0 +1,19 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use displaydoc::Display; + +#[cfg(feature = "std")] +impl std::error::Error for TinyStrError {} + +#[derive(Display, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum TinyStrError { + #[displaydoc("found string of larger length {len} when constructing string of length {max}")] + TooLarge { max: usize, len: usize }, + #[displaydoc("tinystr types do not support strings with null bytes")] + ContainsNull, + #[displaydoc("attempted to construct TinyStrAuto from a non-ascii string")] + NonAscii, +} diff --git a/bash-5.1/vendor/tinystr/src/int_ops.rs b/bash-5.1/vendor/tinystr/src/int_ops.rs new file mode 100644 index 0000000..102b052 --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/int_ops.rs @@ -0,0 +1,315 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::asciibyte::AsciiByte; + +/// Internal helper struct that performs operations on aligned integers. +/// Supports strings up to 4 bytes long. +#[repr(transparent)] +pub struct Aligned4(u32); + +impl Aligned4 { + /// # Panics + /// Panics if N is greater than 4 + #[inline] + pub const fn from_bytes<const N: usize>(src: &[u8; N]) -> Self { + let mut bytes = [0; 4]; + let mut i = 0; + // The function documentation defines when panics may occur + #[allow(clippy::indexing_slicing)] + while i < N { + bytes[i] = src[i]; + i += 1; + } + Self(u32::from_ne_bytes(bytes)) + } + + #[inline] + pub const fn from_ascii_bytes<const N: usize>(src: &[AsciiByte; N]) -> Self { + Self::from_bytes::<N>(unsafe { core::mem::transmute(src) }) + } + + #[inline] + pub const fn to_bytes(&self) -> [u8; 4] { + self.0.to_ne_bytes() + } + + #[inline] + pub const fn to_ascii_bytes(&self) -> [AsciiByte; 4] { + unsafe { core::mem::transmute(self.to_bytes()) } + } + + pub const fn len(&self) -> usize { + let word = self.0; + #[cfg(target_endian = "little")] + let len = (4 - word.leading_zeros() / 8) as usize; + #[cfg(target_endian = "big")] + let len = (4 - word.trailing_zeros() / 8) as usize; + len + } + + pub const fn is_ascii_alphabetic(&self) -> bool { + let word = self.0; + // Each of the following bitmasks set *the high bit* (0x8) to 0 for valid and 1 for invalid. + // `mask` sets all NUL bytes to 0. + let mask = (word + 0x7f7f_7f7f) & 0x8080_8080; + // `lower` converts the string to lowercase. It may also change the value of non-alpha + // characters, but this does not matter for the alphabetic test that follows. + let lower = word | 0x2020_2020; + // `alpha` sets all alphabetic bytes to 0. We only need check for lowercase characters. + let alpha = !(lower + 0x1f1f_1f1f) | (lower + 0x0505_0505); + // The overall string is valid if every character passes at least one test. + // We performed two tests here: non-NUL (`mask`) and alphabetic (`alpha`). + (alpha & mask) == 0 + } + + pub const fn is_ascii_alphanumeric(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_alphabetic + let mask = (word + 0x7f7f_7f7f) & 0x8080_8080; + let numeric = !(word + 0x5050_5050) | (word + 0x4646_4646); + let lower = word | 0x2020_2020; + let alpha = !(lower + 0x1f1f_1f1f) | (lower + 0x0505_0505); + (alpha & numeric & mask) == 0 + } + + pub const fn is_ascii_numeric(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_alphabetic + let mask = (word + 0x7f7f_7f7f) & 0x8080_8080; + let numeric = !(word + 0x5050_5050) | (word + 0x4646_4646); + (numeric & mask) == 0 + } + + pub const fn is_ascii_lowercase(&self) -> bool { + let word = self.0; + // For efficiency, this function tests for an invalid string rather than a valid string. + // A string is ASCII lowercase iff it contains no uppercase ASCII characters. + // `invalid_case` sets all uppercase ASCII characters to 0 and all others to 1. + let invalid_case = !(word + 0x3f3f_3f3f) | (word + 0x2525_2525); + // The string is valid if it contains no invalid characters (if all high bits are 1). + (invalid_case & 0x8080_8080) == 0x8080_8080 + } + + pub const fn is_ascii_titlecase(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_lowercase + let invalid_case = if cfg!(target_endian = "little") { + !(word + 0x3f3f_3f1f) | (word + 0x2525_2505) + } else { + !(word + 0x1f3f_3f3f) | (word + 0x0525_2525) + }; + (invalid_case & 0x8080_8080) == 0x8080_8080 + } + + pub const fn is_ascii_uppercase(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_lowercase + let invalid_case = !(word + 0x1f1f_1f1f) | (word + 0x0505_0505); + (invalid_case & 0x8080_8080) == 0x8080_8080 + } + + pub const fn is_ascii_alphabetic_lowercase(&self) -> bool { + let word = self.0; + // `mask` sets all NUL bytes to 0. + let mask = (word + 0x7f7f_7f7f) & 0x8080_8080; + // `lower_alpha` sets all lowercase ASCII characters to 0 and all others to 1. + let lower_alpha = !(word + 0x1f1f_1f1f) | (word + 0x0505_0505); + // The overall string is valid if every character passes at least one test. + // We performed two tests here: non-NUL (`mask`) and lowercase ASCII character (`alpha`). + (lower_alpha & mask) == 0 + } + + pub const fn is_ascii_alphabetic_titlecase(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_alphabetic_lowercase + let mask = (word + 0x7f7f_7f7f) & 0x8080_8080; + let title_case = if cfg!(target_endian = "little") { + !(word + 0x1f1f_1f3f) | (word + 0x0505_0525) + } else { + !(word + 0x3f1f_1f1f) | (word + 0x2505_0505) + }; + (title_case & mask) == 0 + } + + pub const fn is_ascii_alphabetic_uppercase(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_alphabetic_lowercase + let mask = (word + 0x7f7f_7f7f) & 0x8080_8080; + let upper_alpha = !(word + 0x3f3f_3f3f) | (word + 0x2525_2525); + (upper_alpha & mask) == 0 + } + + pub const fn to_ascii_lowercase(&self) -> Self { + let word = self.0; + let result = word | (((word + 0x3f3f_3f3f) & !(word + 0x2525_2525) & 0x8080_8080) >> 2); + Self(result) + } + + pub const fn to_ascii_titlecase(&self) -> Self { + let word = self.0.to_le(); + let mask = ((word + 0x3f3f_3f1f) & !(word + 0x2525_2505) & 0x8080_8080) >> 2; + let result = (word | mask) & !(0x20 & mask); + Self(u32::from_le(result)) + } + + pub const fn to_ascii_uppercase(&self) -> Self { + let word = self.0; + let result = word & !(((word + 0x1f1f_1f1f) & !(word + 0x0505_0505) & 0x8080_8080) >> 2); + Self(result) + } +} + +/// Internal helper struct that performs operations on aligned integers. +/// Supports strings up to 8 bytes long. +#[repr(transparent)] +pub struct Aligned8(u64); + +impl Aligned8 { + /// # Panics + /// Panics if N is greater than 8 + #[inline] + pub const fn from_bytes<const N: usize>(src: &[u8; N]) -> Self { + let mut bytes = [0; 8]; + let mut i = 0; + // The function documentation defines when panics may occur + #[allow(clippy::indexing_slicing)] + while i < N { + bytes[i] = src[i]; + i += 1; + } + Self(u64::from_ne_bytes(bytes)) + } + + #[inline] + pub const fn from_ascii_bytes<const N: usize>(src: &[AsciiByte; N]) -> Self { + Self::from_bytes::<N>(unsafe { core::mem::transmute(src) }) + } + + #[inline] + pub const fn to_bytes(&self) -> [u8; 8] { + self.0.to_ne_bytes() + } + + #[inline] + pub const fn to_ascii_bytes(&self) -> [AsciiByte; 8] { + unsafe { core::mem::transmute(self.to_bytes()) } + } + + pub const fn len(&self) -> usize { + let word = self.0; + #[cfg(target_endian = "little")] + let len = (8 - word.leading_zeros() / 8) as usize; + #[cfg(target_endian = "big")] + let len = (8 - word.trailing_zeros() / 8) as usize; + len + } + + pub const fn is_ascii_alphabetic(&self) -> bool { + let word = self.0; + let mask = (word + 0x7f7f_7f7f_7f7f_7f7f) & 0x8080_8080_8080_8080; + let lower = word | 0x2020_2020_2020_2020; + let alpha = !(lower + 0x1f1f_1f1f_1f1f_1f1f) | (lower + 0x0505_0505_0505_0505); + (alpha & mask) == 0 + } + + pub const fn is_ascii_alphanumeric(&self) -> bool { + let word = self.0; + let mask = (word + 0x7f7f_7f7f_7f7f_7f7f) & 0x8080_8080_8080_8080; + let numeric = !(word + 0x5050_5050_5050_5050) | (word + 0x4646_4646_4646_4646); + let lower = word | 0x2020_2020_2020_2020; + let alpha = !(lower + 0x1f1f_1f1f_1f1f_1f1f) | (lower + 0x0505_0505_0505_0505); + (alpha & numeric & mask) == 0 + } + + pub const fn is_ascii_numeric(&self) -> bool { + let word = self.0; + let mask = (word + 0x7f7f_7f7f_7f7f_7f7f) & 0x8080_8080_8080_8080; + let numeric = !(word + 0x5050_5050_5050_5050) | (word + 0x4646_4646_4646_4646); + (numeric & mask) == 0 + } + + pub const fn is_ascii_lowercase(&self) -> bool { + let word = self.0; + let invalid_case = !(word + 0x3f3f_3f3f_3f3f_3f3f) | (word + 0x2525_2525_2525_2525); + (invalid_case & 0x8080_8080_8080_8080) == 0x8080_8080_8080_8080 + } + + pub const fn is_ascii_titlecase(&self) -> bool { + let word = self.0; + let invalid_case = if cfg!(target_endian = "little") { + !(word + 0x3f3f_3f3f_3f3f_3f1f) | (word + 0x2525_2525_2525_2505) + } else { + !(word + 0x1f3f_3f3f_3f3f_3f3f) | (word + 0x0525_2525_2525_2525) + }; + (invalid_case & 0x8080_8080_8080_8080) == 0x8080_8080_8080_8080 + } + + pub const fn is_ascii_uppercase(&self) -> bool { + let word = self.0; + let invalid_case = !(word + 0x1f1f_1f1f_1f1f_1f1f) | (word + 0x0505_0505_0505_0505); + (invalid_case & 0x8080_8080_8080_8080) == 0x8080_8080_8080_8080 + } + + pub const fn is_ascii_alphabetic_lowercase(&self) -> bool { + let word = self.0; + // `mask` sets all NUL bytes to 0. + let mask = (word + 0x7f7f_7f7f_7f7f_7f7f) & 0x8080_8080_8080_8080; + // `lower_alpha` sets all lowercase ASCII characters to 0 and all others to 1. + let lower_alpha = !(word + 0x1f1f_1f1f_1f1f_1f1f) | (word + 0x0505_0505_0505_0505); + // The overall string is valid if every character passes at least one test. + // We performed two tests here: non-NUL (`mask`) and lowercase ASCII character (`alpha`). + (lower_alpha & mask) == 0 + } + + pub const fn is_ascii_alphabetic_titlecase(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_alphabetic_lowercase + let mask = (word + 0x7f7f_7f7f_7f7f_7f7f) & 0x8080_8080_8080_8080; + let title_case = if cfg!(target_endian = "little") { + !(word + 0x1f1f_1f1f_1f1f_1f3f) | (word + 0x0505_0505_0505_0525) + } else { + !(word + 0x3f1f_1f1f_1f1f_1f1f) | (word + 0x2505_0505_0505_0505) + }; + (title_case & mask) == 0 + } + + pub const fn is_ascii_alphabetic_uppercase(&self) -> bool { + let word = self.0; + // See explanatory comments in is_ascii_alphabetic_lowercase + let mask = (word + 0x7f7f_7f7f_7f7f_7f7f) & 0x8080_8080_8080_8080; + let upper_alpha = !(word + 0x3f3f_3f3f_3f3f_3f3f) | (word + 0x2525_2525_2525_2525); + (upper_alpha & mask) == 0 + } + + pub const fn to_ascii_lowercase(&self) -> Self { + let word = self.0; + let result = word + | (((word + 0x3f3f_3f3f_3f3f_3f3f) + & !(word + 0x2525_2525_2525_2525) + & 0x8080_8080_8080_8080) + >> 2); + Self(result) + } + + pub const fn to_ascii_titlecase(&self) -> Self { + let word = self.0.to_le(); + let mask = ((word + 0x3f3f_3f3f_3f3f_3f1f) + & !(word + 0x2525_2525_2525_2505) + & 0x8080_8080_8080_8080) + >> 2; + let result = (word | mask) & !(0x20 & mask); + Self(u64::from_le(result)) + } + + pub const fn to_ascii_uppercase(&self) -> Self { + let word = self.0; + let result = word + & !(((word + 0x1f1f_1f1f_1f1f_1f1f) + & !(word + 0x0505_0505_0505_0505) + & 0x8080_8080_8080_8080) + >> 2); + Self(result) + } +} diff --git a/bash-5.1/vendor/tinystr/src/macros.rs b/bash-5.1/vendor/tinystr/src/macros.rs new file mode 100644 index 0000000..b001852 --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/macros.rs @@ -0,0 +1,32 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +#[macro_export] +macro_rules! tinystr { + ($n:literal, $s:literal) => {{ + // Force it into a const context; otherwise it may get evaluated at runtime instead. + const TINYSTR_MACRO_CONST: $crate::TinyAsciiStr<$n> = { + match $crate::TinyAsciiStr::from_bytes($s.as_bytes()) { + Ok(s) => s, + // We are okay with panicking here because this is in a const context + #[allow(clippy::panic)] + // Cannot format the error since formatting isn't const yet + Err(_) => panic!(concat!("Failed to construct tinystr from ", $s)), + } + }; + TINYSTR_MACRO_CONST + }}; +} + +#[cfg(test)] +mod tests { + #[test] + fn test_macro_construction() { + let s1 = tinystr!(8, "foobar"); + assert_eq!(&*s1, "foobar"); + + let s1 = tinystr!(12, "foobarbaz"); + assert_eq!(&*s1, "foobarbaz"); + } +} diff --git a/bash-5.1/vendor/tinystr/src/serde.rs b/bash-5.1/vendor/tinystr/src/serde.rs new file mode 100644 index 0000000..933491f --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/serde.rs @@ -0,0 +1,91 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::TinyAsciiStr; +use alloc::borrow::Cow; +use alloc::string::ToString; +use core::fmt; +use core::marker::PhantomData; +use core::ops::Deref; +use serde::de::{Error, SeqAccess, Visitor}; +use serde::ser::SerializeTuple; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +impl<const N: usize> Serialize for TinyAsciiStr<N> { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + self.deref().serialize(serializer) + } else { + let mut seq = serializer.serialize_tuple(N)?; + for byte in self.all_bytes() { + seq.serialize_element(byte)?; + } + seq.end() + } + } +} + +struct TinyAsciiStrVisitor<const N: usize> { + marker: PhantomData<TinyAsciiStr<N>>, +} + +impl<const N: usize> TinyAsciiStrVisitor<N> { + fn new() -> Self { + TinyAsciiStrVisitor { + marker: PhantomData, + } + } +} + +impl<'de, const N: usize> Visitor<'de> for TinyAsciiStrVisitor<N> { + type Value = TinyAsciiStr<N>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a TinyAsciiStr<{}>", N) + } + + #[inline] + fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> + where + A: SeqAccess<'de>, + { + let mut bytes = [0u8; N]; + let mut zeroes = false; + for out in &mut bytes.iter_mut().take(N) { + let byte = seq + .next_element()? + .ok_or_else(|| Error::invalid_length(N, &self))?; + if byte == 0 { + zeroes = true; + } else if zeroes { + return Err(Error::custom("TinyAsciiStr cannot contain null bytes")); + } + + if byte >= 0x80 { + return Err(Error::custom("TinyAsciiStr cannot contain non-ascii bytes")); + } + *out = byte; + } + + Ok(unsafe { TinyAsciiStr::from_bytes_unchecked(bytes) }) + } +} + +impl<'de, const N: usize> Deserialize<'de> for TinyAsciiStr<N> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + let x: Cow<'de, str> = Deserialize::deserialize(deserializer)?; + TinyAsciiStr::from_str(&x).map_err(|e| Error::custom(e.to_string())) + } else { + deserializer.deserialize_tuple(N, TinyAsciiStrVisitor::<N>::new()) + } + } +} diff --git a/bash-5.1/vendor/tinystr/src/ule.rs b/bash-5.1/vendor/tinystr/src/ule.rs new file mode 100644 index 0000000..0fa2120 --- /dev/null +++ b/bash-5.1/vendor/tinystr/src/ule.rs @@ -0,0 +1,76 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::TinyAsciiStr; +use zerovec::maps::ZeroMapKV; +use zerovec::ule::*; +use zerovec::{ZeroSlice, ZeroVec}; + +// Safety (based on the safety checklist on the ULE trait): +// 1. CharULE does not include any uninitialized or padding bytes. +// (achieved by `#[repr(transparent)]` on a type that satisfies this invariant) +// 2. CharULE is aligned to 1 byte. +// (achieved by `#[repr(transparent)]` on a type that satisfies this invariant) +// 3. The impl of validate_byte_slice() returns an error if any byte is not valid. +// 4. The impl of validate_byte_slice() returns an error if there are extra bytes. +// 5. The other ULE methods use the default impl. +// 6. CharULE byte equality is semantic equality +unsafe impl<const N: usize> ULE for TinyAsciiStr<N> { + #[inline] + fn validate_byte_slice(bytes: &[u8]) -> Result<(), ZeroVecError> { + if bytes.len() % N != 0 { + return Err(ZeroVecError::length::<Self>(bytes.len())); + } + // Validate the bytes + for chunk in bytes.chunks_exact(N) { + let _ = TinyAsciiStr::<N>::from_bytes_inner(chunk, 0, N, true) + .map_err(|_| ZeroVecError::parse::<Self>())?; + } + Ok(()) + } +} + +impl<const N: usize> AsULE for TinyAsciiStr<N> { + type ULE = Self; + + #[inline] + fn to_unaligned(self) -> Self::ULE { + self + } + + #[inline] + fn from_unaligned(unaligned: Self::ULE) -> Self { + unaligned + } +} + +impl<'a, const N: usize> ZeroMapKV<'a> for TinyAsciiStr<N> { + type Container = ZeroVec<'a, TinyAsciiStr<N>>; + type Slice = ZeroSlice<TinyAsciiStr<N>>; + type GetType = TinyAsciiStr<N>; + type OwnedType = TinyAsciiStr<N>; +} + +#[cfg(test)] +mod test { + use crate::*; + use zerovec::*; + + #[test] + fn test_zerovec() { + let mut vec = ZeroVec::<TinyAsciiStr<7>>::new(); + + vec.with_mut(|v| v.push("foobar".parse().unwrap())); + vec.with_mut(|v| v.push("baz".parse().unwrap())); + vec.with_mut(|v| v.push("quux".parse().unwrap())); + + let bytes = vec.as_bytes(); + + let vec: ZeroVec<TinyAsciiStr<7>> = ZeroVec::parse_byte_slice(bytes).unwrap(); + + assert_eq!(&*vec.get(0).unwrap(), "foobar"); + assert_eq!(&*vec.get(1).unwrap(), "baz"); + assert_eq!(&*vec.get(2).unwrap(), "quux"); + } +} diff --git a/bash-5.1/vendor/tinystr/tests/serde.rs b/bash-5.1/vendor/tinystr/tests/serde.rs new file mode 100644 index 0000000..282914e --- /dev/null +++ b/bash-5.1/vendor/tinystr/tests/serde.rs @@ -0,0 +1,39 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use tinystr::*; + +// Tests largely adapted from `tinystr` crate +// https://github.com/zbraniecki/tinystr/blob/4e4eab55dd6bded7f29a18b41452c506c461716c/tests/serde.rs + +macro_rules! test_roundtrip { + ($f:ident, $n:literal, $val:expr) => { + #[test] + fn $f() { + let tiny: TinyAsciiStr<$n> = $val.parse().unwrap(); + let json_string = serde_json::to_string(&tiny).unwrap(); + let expected_json = concat!("\"", $val, "\""); + assert_eq!(json_string, expected_json); + let recover: TinyAsciiStr<$n> = serde_json::from_str(&json_string).unwrap(); + assert_eq!(&*tiny, &*recover); + + let bin = bincode::serialize(&tiny).unwrap(); + assert_eq!(bin, &tiny.all_bytes()[..]); + let debin: TinyAsciiStr<$n> = bincode::deserialize(&bin).unwrap(); + assert_eq!(&*tiny, &*debin); + + let post = postcard::to_stdvec(&tiny).unwrap(); + assert_eq!(post, &tiny.all_bytes()[..]); + let unpost: TinyAsciiStr<$n> = postcard::from_bytes(&post).unwrap(); + assert_eq!(&*tiny, &*unpost); + } + }; +} + +test_roundtrip!(test_roundtrip4_1, 4, "en"); +test_roundtrip!(test_roundtrip4_2, 4, "Latn"); +test_roundtrip!(test_roundtrip8, 8, "calendar"); +test_roundtrip!(test_roundtrip16, 16, "verylongstring"); +test_roundtrip!(test_roundtrip10, 11, "shortstring"); +test_roundtrip!(test_roundtrip30, 24, "veryveryverylongstring"); diff --git a/bash-5.1/vendor/ucd-util/.cargo-checksum.json b/bash-5.1/vendor/ucd-util/.cargo-checksum.json new file mode 100644 index 0000000..c3f9b08 --- /dev/null +++ b/bash-5.1/vendor/ucd-util/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"2f189133664ace08a8bcc12437757bc3d18a272a14881f052a2e720d4614b791","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","LICENSE-UNICODE":"ea8df489e83b7674d5c9d50c320bec3b15d2e2eeb7a3a8879a666d91e5640c16","README.md":"ccfb24f60893d9f0911fc0a6ccd2dd42c9512d3941c8caff5d65153af75496c0","src/hangul.rs":"7e34bdcef83da5ccabd6528b9818da160769f5b309c496dcd3a0979ab6e22de7","src/ideograph.rs":"a111c67f81c5026ee1d3d1c37f634cfa5906c4f0cf3a7dfe80c66ab537519d13","src/lib.rs":"0fa7d116ae2d201e7dcd872f05ca4558d69cb1c96f74ebf9c17eb540dea8e3ef","src/name.rs":"17ece2047e181e5d1e2f341b8a9901dd0125de8189e8b61069fc4c5c800c5375","src/property.rs":"9c42b9345ea10c445870d82fa19703ad6122f39228b1437725d46d9b07577b18","src/unicode_tables/jamo_short_name.rs":"3da457f662674ec32975c090d133d43d8a12686b3f1d38e1519eaba77f2f60c1","src/unicode_tables/mod.rs":"4aad26e2df3b9611dc7906a814e3dc442b7ca3928ccdd6e2a31173d5e7dbf677","src/unicode_tables/property_names.rs":"48a51bf2efd50e0c7b529819f22a5b022451eeafc1464d0b5200603c1d641a91","src/unicode_tables/property_values.rs":"02037b1ba2178bbecffdd074060954620ced3398706f4cb822aca58fab6459df"},"package":"abd2fc5d32b590614af8b0a20d837f32eca055edd0bbead59a9cfe80858be003"} \ No newline at end of file diff --git a/bash-5.1/vendor/ucd-util/Cargo.toml b/bash-5.1/vendor/ucd-util/Cargo.toml new file mode 100644 index 0000000..71961c5 --- /dev/null +++ b/bash-5.1/vendor/ucd-util/Cargo.toml @@ -0,0 +1,30 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "ucd-util" +version = "0.1.10" +authors = ["Andrew Gallant <jamslam@gmail.com>"] +description = """ +A small utility library for working with the Unicode character database. +""" +homepage = "https://github.com/BurntSushi/ucd-generate" +documentation = "https://docs.rs/ucd-util" +readme = "README.md" +keywords = [ + "unicode", + "database", + "character", + "property", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/BurntSushi/ucd-generate" diff --git a/bash-5.1/vendor/ucd-util/LICENSE-APACHE b/bash-5.1/vendor/ucd-util/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/ucd-util/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/ucd-util/LICENSE-MIT b/bash-5.1/vendor/ucd-util/LICENSE-MIT new file mode 100644 index 0000000..3b0a5dc --- /dev/null +++ b/bash-5.1/vendor/ucd-util/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bash-5.1/vendor/ucd-util/LICENSE-UNICODE b/bash-5.1/vendor/ucd-util/LICENSE-UNICODE new file mode 100644 index 0000000..176d5ec --- /dev/null +++ b/bash-5.1/vendor/ucd-util/LICENSE-UNICODE @@ -0,0 +1,57 @@ +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +Unicode Data Files do not include PDF online code charts under the +directory http://www.unicode.org/Public/. + +Software includes any source code published in the Unicode Standard +or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +NOTICE TO USER: Carefully read the following legal agreement. +BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S +DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), +YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. +IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE +THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2018 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. \ No newline at end of file diff --git a/bash-5.1/vendor/ucd-util/README.md b/bash-5.1/vendor/ucd-util/README.md new file mode 100644 index 0000000..0a978e4 --- /dev/null +++ b/bash-5.1/vendor/ucd-util/README.md @@ -0,0 +1,27 @@ +ucd-util +======== +A library for small auxiliary Unicode functions. This includes things like +symbol or character name canonicalization, ideograph name generation and helper +functions for searching property name and value tables. + +[![Build status](https://github.com/BurntSushi/ucd-generate/workflows/ci/badge.svg)](https://github.com/BurntSushi/ucd-generate/actions) +[![crates.io](https://img.shields.io/crates/v/ucd-util.svg)](https://crates.io/crates/ucd-util) + + +### Documentation + +https://docs.rs/ucd-util + + +### License + +This project is licensed under either of + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + https://opensource.org/licenses/MIT) +at your option. + +The data in [`src/unicode_tables/`](src/unicode_tables) is licensed inder the Unicode License +Agreement ([LICENSE-UNICODE](LICENSE-UNICODE) or +https://www.unicode.org/copyright.html#License). diff --git a/bash-5.1/vendor/ucd-util/src/hangul.rs b/bash-5.1/vendor/ucd-util/src/hangul.rs new file mode 100644 index 0000000..53f61fb --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/hangul.rs @@ -0,0 +1,99 @@ +use crate::unicode_tables::jamo_short_name::JAMO_SHORT_NAME; + +// This implementation should correspond to the algorithms described in +// Unicode 3.12. + +/// A set of ranges that corresponds to the set of all Hangul syllable +/// codepoints. +/// +/// These ranges are defined in Unicode 4.8 Table 4-13. +pub const RANGE_HANGUL_SYLLABLE: &'static [(u32, u32)] = &[(0xAC00, 0xD7A3)]; + +const S_BASE: u32 = 0xAC00; +const L_BASE: u32 = 0x1100; +const V_BASE: u32 = 0x1161; +const T_BASE: u32 = 0x11A7; +const T_COUNT: u32 = 28; +const N_COUNT: u32 = 588; + +/// Return the character name of the given precomposed Hangul codepoint. +/// +/// If the given codepoint does not correspond to a precomposed Hangul +/// codepoint in the inclusive range `AC00..D7A3`, then this returns `None`. +/// +/// This implements the algorithms described in Unicode 3.12 and Unicode 4.8. +pub fn hangul_name(cp: u32) -> Option<String> { + let mut name = "HANGUL SYLLABLE ".to_string(); + let (lpart, vpart, tpart) = match hangul_full_canonical_decomposition(cp) { + None => return None, + Some(triple) => triple, + }; + + name.push_str(jamo_short_name(lpart)); + name.push_str(jamo_short_name(vpart)); + name.push_str(tpart.map_or("", jamo_short_name)); + Some(name) +} + +/// Return the full canonical decomposition of the given precomposed Hangul +/// codepoint. +/// +/// If the decomposition does not have any trailing consonant, then the third +/// part of the tuple returned is `None`. +/// +/// If the given codepoint does not correspond to a precomposed Hangul +/// codepoint in the inclusive range `AC00..D7A3`, then this returns `None`. +/// +/// This implements the algorithms described in Unicode 3.12 and Unicode 4.8. +pub fn hangul_full_canonical_decomposition( + cp: u32, +) -> Option<(u32, u32, Option<u32>)> { + if !(0xAC00 <= cp && cp <= 0xD7A3) { + return None; + } + + let s_index = cp - S_BASE; + let l_index = s_index / N_COUNT; + let v_index = (s_index % N_COUNT) / T_COUNT; + let t_index = s_index % T_COUNT; + + let l_part = L_BASE + l_index; + let v_part = V_BASE + v_index; + let t_part = if t_index == 0 { None } else { Some(T_BASE + t_index) }; + Some((l_part, v_part, t_part)) +} + +fn jamo_short_name(cp: u32) -> &'static str { + let i = JAMO_SHORT_NAME.binary_search_by_key(&cp, |p| p.0).unwrap(); + JAMO_SHORT_NAME[i].1 +} + +#[cfg(test)] +mod tests { + use super::{hangul_full_canonical_decomposition, hangul_name}; + + #[test] + fn canon_decomp() { + assert_eq!( + hangul_full_canonical_decomposition(0xD4DB), + Some((0x1111, 0x1171, Some(0x11B6))) + ); + } + + #[test] + fn name() { + assert_eq!(hangul_name(0xD4DB).unwrap(), "HANGUL SYLLABLE PWILH"); + } + + #[test] + fn all() { + for cp in 0xAC00..(0xD7A3 + 1) { + hangul_name(cp).unwrap(); + } + } + + #[test] + fn invalid() { + assert!(hangul_name(0).is_none()); + } +} diff --git a/bash-5.1/vendor/ucd-util/src/ideograph.rs b/bash-5.1/vendor/ucd-util/src/ideograph.rs new file mode 100644 index 0000000..abebbed --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/ideograph.rs @@ -0,0 +1,82 @@ +/// A set of ranges that corresponds to the set of all ideograph codepoints. +/// +/// These ranges are defined in Unicode 4.8 Table 4-13. +pub const RANGE_IDEOGRAPH: &'static [(u32, u32)] = &[ + (0x3400, 0x4DB5), + (0x4E00, 0x9FD5), + (0x4E00, 0x9FD5), + (0x20000, 0x2A6D6), + (0x2A700, 0x2B734), + (0x2B740, 0x2B81D), + (0x2B820, 0x2CEA1), + (0x17000, 0x187EC), + (0xF900, 0xFA6D), + (0xFA70, 0xFAD9), + (0x2F800, 0x2FA1D), +]; + +/// Return the character name of the given ideograph codepoint. +/// +/// This operation is only defined on ideographic codepoints. This includes +/// precisely the following inclusive ranges: +/// +/// * `3400..4DB5` +/// * `4E00..9FD5` +/// * `20000..2A6D6` +/// * `2A700..2B734` +/// * `2B740..2B81D` +/// * `2B820..2CEA1` +/// * `17000..187EC` +/// * `F900..FA6D` +/// * `FA70..FAD9` +/// * `2F800..2FA1D` +/// +/// If the given codepoint is not in any of the above ranges, then `None` is +/// returned. +/// +/// This implements the algorithm described in Unicode 4.8. +pub fn ideograph_name(cp: u32) -> Option<String> { + // This match should be in sync with the `RANGE_IDEOGRAPH` constant. + match cp { + 0x3400...0x4DB5 + | 0x4E00...0x9FD5 + | 0x20000...0x2A6D6 + | 0x2A700...0x2B734 + | 0x2B740...0x2B81D + | 0x2B820...0x2CEA1 => { + Some(format!("CJK UNIFIED IDEOGRAPH-{:04X}", cp)) + } + 0x17000...0x187EC => Some(format!("TANGUT IDEOGRAPH-{:04X}", cp)), + 0xF900...0xFA6D | 0xFA70...0xFAD9 | 0x2F800...0x2FA1D => { + Some(format!("CJK COMPATIBILITY IDEOGRAPH-{:04X}", cp)) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::ideograph_name; + + #[test] + fn name() { + assert_eq!( + ideograph_name(0x4E00).unwrap(), + "CJK UNIFIED IDEOGRAPH-4E00" + ); + assert_eq!( + ideograph_name(0x9FD5).unwrap(), + "CJK UNIFIED IDEOGRAPH-9FD5" + ); + assert_eq!(ideograph_name(0x17000).unwrap(), "TANGUT IDEOGRAPH-17000"); + assert_eq!( + ideograph_name(0xF900).unwrap(), + "CJK COMPATIBILITY IDEOGRAPH-F900" + ); + } + + #[test] + fn invalid() { + assert!(ideograph_name(0).is_none()); + } +} diff --git a/bash-5.1/vendor/ucd-util/src/lib.rs b/bash-5.1/vendor/ucd-util/src/lib.rs new file mode 100644 index 0000000..9d3356b --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/lib.rs @@ -0,0 +1,30 @@ +/*! +The `ucd-util` crate contains a smattering of utility functions that implement +various algorithms specified by Unicode. There is no specific goal for +exhaustiveness. Instead, implementations should be added on an as-needed basis. + +A *current* design constraint of this crate is that it should not bring in any +large Unicode tables. For example, to use the various property name and value +canonicalization functions, you'll need to supply your own table, which can +be generated using `ucd-generate`. +*/ + +#![deny(missing_docs)] +#![allow(unknown_lints)] +#![allow(ellipsis_inclusive_range_patterns)] + +mod hangul; +mod ideograph; +mod name; +mod property; +mod unicode_tables; + +pub use crate::hangul::{ + hangul_full_canonical_decomposition, hangul_name, RANGE_HANGUL_SYLLABLE, +}; +pub use crate::ideograph::{ideograph_name, RANGE_IDEOGRAPH}; +pub use crate::name::{character_name_normalize, symbolic_name_normalize}; +pub use crate::property::{ + canonical_property_name, canonical_property_value, property_values, + PropertyTable, PropertyValueTable, PropertyValues, +}; diff --git a/bash-5.1/vendor/ucd-util/src/name.rs b/bash-5.1/vendor/ucd-util/src/name.rs new file mode 100644 index 0000000..ad80fae --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/name.rs @@ -0,0 +1,203 @@ +/// Normalize the given character name in place according to UAX44-LM2. +/// +/// See: https://unicode.org/reports/tr44/#UAX44-LM2 +pub fn character_name_normalize(string: &mut String) { + let bytes = unsafe { + // SAFETY: `character_name_normalize_bytes` guarantees that + // `bytes[..len]` is valid UTF-8. + string.as_mut_vec() + }; + let len = character_name_normalize_bytes(bytes).len(); + bytes.truncate(len); +} + +/// Normalize the given character name in place according to UAX44-LM2. +/// +/// The slice returned is guaranteed to be valid UTF-8 for all possible values +/// of `slice`. +/// +/// See: https://unicode.org/reports/tr44/#UAX44-LM2 +fn character_name_normalize_bytes(slice: &mut [u8]) -> &mut [u8] { + // According to Unicode 4.8, character names consist only of Latin + // capital letters A to Z, ASCII digits, ASCII space or ASCII hypen. + // Therefore, we can do very simplistic case folding and operate on the + // raw bytes, since everything is ASCII. Note that we don't actually know + // whether `slice` is all ASCII or not, so we drop all non-ASCII bytes. + let mut next_write = 0; + let mut prev_letter = false; + // let mut prev_space = true; + for i in 0..slice.len() { + // SAFETY ARGUMENT: To guarantee that the resulting slice is valid + // UTF-8, we ensure that the slice contains only ASCII bytes. In + // particular, we drop every non-ASCII byte from the normalized string. + let b = slice[i]; + if b == b' ' { + // Drop spaces. + } else if b == b'_' { + // Drop the underscore. + } else if b == b'-' { + let medial = prev_letter + && slice.get(i + 1).map_or(false, |b| b.is_ascii_alphabetic()); + let mut keep_hyphen = !medial; + // We want to keep the hypen only if it isn't medial. However, + // there is one exception. We need to keep the hypen in the + // character (U+1180) named `HANGUL JUNGSEONG O-E`. So we check for + // that here. + let next_e = + slice.get(i + 1).map_or(false, |&b| b == b'E' || b == b'e'); + // More characters after the final E are fine, as long as they are + // underscores and spaces. + let rest_empty = i + 2 >= slice.len() + || slice[i + 2..].iter().all(|&b| b == b' ' || b == b'_'); + if !keep_hyphen && next_e && rest_empty { + keep_hyphen = slice[..next_write] == b"hanguljungseongo"[..]; + } + if keep_hyphen { + slice[next_write] = b; + next_write += 1; + } + } else if b'A' <= b && b <= b'Z' { + slice[next_write] = b + (b'a' - b'A'); + next_write += 1; + } else if b <= 0x7F { + slice[next_write] = b; + next_write += 1; + } + // prev_space = false; + prev_letter = b.is_ascii_alphabetic(); + } + &mut slice[..next_write] +} + +/// Normalize the given symbolic name in place according to UAX44-LM3. +/// +/// A "symbolic name" typically corresponds to property names and property +/// value aliases. Note, though, that it should not be applied to property +/// string values. +/// +/// See: https://unicode.org/reports/tr44/#UAX44-LM2 +pub fn symbolic_name_normalize(string: &mut String) { + let bytes = unsafe { + // SAFETY: `symbolic_name_normalize_bytes` guarantees that + // `bytes[..len]` is valid UTF-8. + string.as_mut_vec() + }; + let len = symbolic_name_normalize_bytes(bytes).len(); + bytes.truncate(len); +} + +/// Normalize the given symbolic name in place according to UAX44-LM3. +/// +/// A "symbolic name" typically corresponds to property names and property +/// value aliases. Note, though, that it should not be applied to property +/// string values. +/// +/// The slice returned is guaranteed to be valid UTF-8 for all possible values +/// of `slice`. +/// +/// See: https://unicode.org/reports/tr44/#UAX44-LM3 +fn symbolic_name_normalize_bytes(slice: &mut [u8]) -> &mut [u8] { + // I couldn't find a place in the standard that specified that property + // names/aliases had a particular structure (unlike character names), but + // we assume that it's ASCII only and drop anything that isn't ASCII. + let mut start = 0; + let mut starts_with_is = false; + if slice.len() > 2 { + // Ignore any "is" prefix. + starts_with_is = slice[0..2] == b"is"[..] + || slice[0..2] == b"IS"[..] + || slice[0..2] == b"iS"[..] + || slice[0..2] == b"Is"[..]; + if starts_with_is { + start = 2; + } + } + let mut next_write = 0; + for i in start..slice.len() { + // SAFETY ARGUMENT: To guarantee that the resulting slice is valid + // UTF-8, we ensure that the slice contains only ASCII bytes. In + // particular, we drop every non-ASCII byte from the normalized string. + let b = slice[i]; + if b == b' ' || b == b'_' || b == b'-' { + continue; + } else if b'A' <= b && b <= b'Z' { + slice[next_write] = b + (b'a' - b'A'); + next_write += 1; + } else if b <= 0x7F { + slice[next_write] = b; + next_write += 1; + } + } + // Special case: ISO_Comment has a 'isc' abbreviation. Since we generally + // ignore 'is' prefixes, the 'isc' abbreviation gets caught in the cross + // fire and ends up creating an alias for 'c' to 'ISO_Comment', but it + // is actually an alias for the 'Other' general category. + if starts_with_is && next_write == 1 && slice[0] == b'c' { + slice[0] = b'i'; + slice[1] = b's'; + slice[2] = b'c'; + next_write = 3; + } + &mut slice[..next_write] +} + +#[cfg(test)] +mod tests { + use super::{ + character_name_normalize, character_name_normalize_bytes, + symbolic_name_normalize, symbolic_name_normalize_bytes, + }; + + fn char_norm(s: &str) -> String { + let mut s = s.to_string(); + character_name_normalize(&mut s); + s + } + + fn sym_norm(s: &str) -> String { + let mut s = s.to_string(); + symbolic_name_normalize(&mut s); + s + } + + #[test] + fn char_normalize() { + assert_eq!(char_norm("HANGUL JUNGSEONG O-E"), "hanguljungseongo-e"); + assert_eq!(char_norm("HANGUL JUNGSEONG O-E _"), "hanguljungseongo-e"); + assert_eq!(char_norm("zero-width space"), "zerowidthspace"); + assert_eq!(char_norm("zerowidthspace"), "zerowidthspace"); + assert_eq!(char_norm("ZERO WIDTH SPACE"), "zerowidthspace"); + assert_eq!(char_norm("TIBETAN MARK TSA -PHRU"), "tibetanmarktsa-phru"); + assert_eq!(char_norm("tibetan_letter_-a"), "tibetanletter-a"); + } + + #[test] + fn sym_normalize() { + assert_eq!(sym_norm("Line_Break"), "linebreak"); + assert_eq!(sym_norm("Line-break"), "linebreak"); + assert_eq!(sym_norm("linebreak"), "linebreak"); + assert_eq!(sym_norm("BA"), "ba"); + assert_eq!(sym_norm("ba"), "ba"); + assert_eq!(sym_norm("Greek"), "greek"); + assert_eq!(sym_norm("isGreek"), "greek"); + assert_eq!(sym_norm("IS_Greek"), "greek"); + assert_eq!(sym_norm("isc"), "isc"); + assert_eq!(sym_norm("is c"), "isc"); + assert_eq!(sym_norm("is_c"), "isc"); + assert_eq!(sym_norm("IS"), "is"); + } + + #[test] + fn valid_utf8_character() { + let mut x = b"abc\xFFxyz".to_vec(); + let y = character_name_normalize_bytes(&mut x); + assert_eq!(y, b"abcxyz"); + } + + #[test] + fn valid_utf8_symbolic() { + let mut x = b"abc\xFFxyz".to_vec(); + let y = symbolic_name_normalize_bytes(&mut x); + assert_eq!(y, b"abcxyz"); + } +} diff --git a/bash-5.1/vendor/ucd-util/src/property.rs b/bash-5.1/vendor/ucd-util/src/property.rs new file mode 100644 index 0000000..1f4dfc7 --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/property.rs @@ -0,0 +1,132 @@ +/// The type of a property name table. +/// +/// A property name table is a sequence of sorted tuples, where the first +/// value in each tuple is a normalized property name and the second value of +/// each tuple is the corresponding canonical property name. +pub type PropertyTable = &'static [(&'static str, &'static str)]; + +/// Find the canonical property name for the given normalized property name. +/// +/// If no such property exists, then `None` is returned. +/// +/// The normalized property name must have been normalized according to +/// UAX44 LM3, which can be done using `symbolic_name_normalize`. +pub fn canonical_property_name( + property_table: PropertyTable, + normalized_property_name: &str, +) -> Option<&'static str> { + property_table + .binary_search_by_key(&normalized_property_name, |&(n, _)| n) + .ok() + .map(|i| property_table[i].1) +} + +/// Type of a property value table. +/// +/// A property value table maps property names to a mapping of property values, +/// where the mapping of property values is represented by a sequence of +/// tuples. The first element of each tuple is a normalized property value +/// while the second element of each tuple is the corresponding canonical +/// property value. +/// +/// Note that a property value table only includes values for properties that +/// are catalogs, enumerations or binary properties. Properties that have +/// string values (such as case or decomposition mappings), numeric values +/// or are miscellaneous are not represented in this table. +pub type PropertyValueTable = &'static [(&'static str, PropertyValues)]; + +/// A mapping of property values for a specific property. +/// +/// The first element of each tuple is a normalized property value while the +/// second element of each tuple is the corresponding canonical property +/// value. +pub type PropertyValues = &'static [(&'static str, &'static str)]; + +/// Find the set of possible property values for a given property. +/// +/// The set returned is a mapping expressed as a sorted list of tuples. +/// The first element of each tuple is a normalized property value while the +/// second element of each tuple is the corresponding canonical property +/// value. +/// +/// If no such property exists, then `None` is returned. +/// +/// The given property name must be in its canonical form, which can be +/// found using `canonical_property_name`. +pub fn property_values( + property_value_table: PropertyValueTable, + canonical_property_name: &str, +) -> Option<PropertyValues> { + property_value_table + .binary_search_by_key(&canonical_property_name, |&(n, _)| n) + .ok() + .map(|i| property_value_table[i].1) +} + +/// Find the canonical property value for the given normalized property +/// value. +/// +/// The given property values should correspond to the values for the property +/// under question, which can be found using `property_values`. +/// +/// If no such property value exists, then `None` is returned. +/// +/// The normalized property value must have been normalized according to +/// UAX44 LM3, which can be done using `symbolic_name_normalize`. +pub fn canonical_property_value( + property_values: PropertyValues, + normalized_property_value: &str, +) -> Option<&'static str> { + // This is cute. The types line up, so why not? + canonical_property_name(property_values, normalized_property_value) +} + +#[cfg(test)] +mod tests { + use crate::unicode_tables::property_names::PROPERTY_NAMES; + use crate::unicode_tables::property_values::PROPERTY_VALUES; + + use super::{ + canonical_property_name, canonical_property_value, property_values, + }; + + #[test] + fn canonical_property_name_1() { + assert_eq!( + canonical_property_name(PROPERTY_NAMES, "gc"), + Some("General_Category") + ); + assert_eq!( + canonical_property_name(PROPERTY_NAMES, "generalcategory"), + Some("General_Category") + ); + assert_eq!(canonical_property_name(PROPERTY_NAMES, "g c"), None); + } + + #[test] + fn property_values_1() { + assert_eq!( + property_values(PROPERTY_VALUES, "White_Space"), + Some( + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ][..] + ) + ); + } + + #[test] + fn canonical_property_value_1() { + let values = property_values(PROPERTY_VALUES, "White_Space").unwrap(); + assert_eq!(canonical_property_value(values, "false"), Some("No")); + assert_eq!(canonical_property_value(values, "t"), Some("Yes")); + assert_eq!(canonical_property_value(values, "F"), None); + } +} diff --git a/bash-5.1/vendor/ucd-util/src/unicode_tables/jamo_short_name.rs b/bash-5.1/vendor/ucd-util/src/unicode_tables/jamo_short_name.rs new file mode 100644 index 0000000..f434d8c --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/unicode_tables/jamo_short_name.rs @@ -0,0 +1,77 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate jamo-short-name ucd-15.0.0 +// +// Unicode version: 15.0.0. +// +// ucd-generate 0.2.13 is available on crates.io. + +pub const JAMO_SHORT_NAME: &'static [(u32, &'static str)] = &[ + (4352, "G"), + (4353, "GG"), + (4354, "N"), + (4355, "D"), + (4356, "DD"), + (4357, "R"), + (4358, "M"), + (4359, "B"), + (4360, "BB"), + (4361, "S"), + (4362, "SS"), + (4363, ""), + (4364, "J"), + (4365, "JJ"), + (4366, "C"), + (4367, "K"), + (4368, "T"), + (4369, "P"), + (4370, "H"), + (4449, "A"), + (4450, "AE"), + (4451, "YA"), + (4452, "YAE"), + (4453, "EO"), + (4454, "E"), + (4455, "YEO"), + (4456, "YE"), + (4457, "O"), + (4458, "WA"), + (4459, "WAE"), + (4460, "OE"), + (4461, "YO"), + (4462, "U"), + (4463, "WEO"), + (4464, "WE"), + (4465, "WI"), + (4466, "YU"), + (4467, "EU"), + (4468, "YI"), + (4469, "I"), + (4520, "G"), + (4521, "GG"), + (4522, "GS"), + (4523, "N"), + (4524, "NJ"), + (4525, "NH"), + (4526, "D"), + (4527, "L"), + (4528, "LG"), + (4529, "LM"), + (4530, "LB"), + (4531, "LS"), + (4532, "LT"), + (4533, "LP"), + (4534, "LH"), + (4535, "M"), + (4536, "B"), + (4537, "BS"), + (4538, "S"), + (4539, "SS"), + (4540, "NG"), + (4541, "J"), + (4542, "C"), + (4543, "K"), + (4544, "T"), + (4545, "P"), + (4546, "H"), +]; diff --git a/bash-5.1/vendor/ucd-util/src/unicode_tables/mod.rs b/bash-5.1/vendor/ucd-util/src/unicode_tables/mod.rs new file mode 100644 index 0000000..558177d --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/unicode_tables/mod.rs @@ -0,0 +1,5 @@ +pub mod jamo_short_name; +#[cfg(test)] +pub mod property_names; +#[cfg(test)] +pub mod property_values; diff --git a/bash-5.1/vendor/ucd-util/src/unicode_tables/property_names.rs b/bash-5.1/vendor/ucd-util/src/unicode_tables/property_names.rs new file mode 100644 index 0000000..40dfe76 --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/unicode_tables/property_names.rs @@ -0,0 +1,264 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-names ucd-15.0.0 +// +// Unicode version: 15.0.0. +// +// ucd-generate 0.2.13 is available on crates.io. + +pub const PROPERTY_NAMES: &'static [(&'static str, &'static str)] = &[ + ("age", "Age"), + ("ahex", "ASCII_Hex_Digit"), + ("alpha", "Alphabetic"), + ("alphabetic", "Alphabetic"), + ("asciihexdigit", "ASCII_Hex_Digit"), + ("bc", "Bidi_Class"), + ("bidic", "Bidi_Control"), + ("bidiclass", "Bidi_Class"), + ("bidicontrol", "Bidi_Control"), + ("bidim", "Bidi_Mirrored"), + ("bidimirrored", "Bidi_Mirrored"), + ("bidimirroringglyph", "Bidi_Mirroring_Glyph"), + ("bidipairedbracket", "Bidi_Paired_Bracket"), + ("bidipairedbrackettype", "Bidi_Paired_Bracket_Type"), + ("blk", "Block"), + ("block", "Block"), + ("bmg", "Bidi_Mirroring_Glyph"), + ("bpb", "Bidi_Paired_Bracket"), + ("bpt", "Bidi_Paired_Bracket_Type"), + ("canonicalcombiningclass", "Canonical_Combining_Class"), + ("cased", "Cased"), + ("casefolding", "Case_Folding"), + ("caseignorable", "Case_Ignorable"), + ("ccc", "Canonical_Combining_Class"), + ("ce", "Composition_Exclusion"), + ("cf", "Case_Folding"), + ("changeswhencasefolded", "Changes_When_Casefolded"), + ("changeswhencasemapped", "Changes_When_Casemapped"), + ("changeswhenlowercased", "Changes_When_Lowercased"), + ("changeswhennfkccasefolded", "Changes_When_NFKC_Casefolded"), + ("changeswhentitlecased", "Changes_When_Titlecased"), + ("changeswhenuppercased", "Changes_When_Uppercased"), + ("ci", "Case_Ignorable"), + ("cjkaccountingnumeric", "kAccountingNumeric"), + ("cjkcompatibilityvariant", "kCompatibilityVariant"), + ("cjkiicore", "kIICore"), + ("cjkirggsource", "kIRG_GSource"), + ("cjkirghsource", "kIRG_HSource"), + ("cjkirgjsource", "kIRG_JSource"), + ("cjkirgkpsource", "kIRG_KPSource"), + ("cjkirgksource", "kIRG_KSource"), + ("cjkirgmsource", "kIRG_MSource"), + ("cjkirgssource", "kIRG_SSource"), + ("cjkirgtsource", "kIRG_TSource"), + ("cjkirguksource", "kIRG_UKSource"), + ("cjkirgusource", "kIRG_USource"), + ("cjkirgvsource", "kIRG_VSource"), + ("cjkothernumeric", "kOtherNumeric"), + ("cjkprimarynumeric", "kPrimaryNumeric"), + ("cjkrsunicode", "kRSUnicode"), + ("compex", "Full_Composition_Exclusion"), + ("compositionexclusion", "Composition_Exclusion"), + ("cwcf", "Changes_When_Casefolded"), + ("cwcm", "Changes_When_Casemapped"), + ("cwkcf", "Changes_When_NFKC_Casefolded"), + ("cwl", "Changes_When_Lowercased"), + ("cwt", "Changes_When_Titlecased"), + ("cwu", "Changes_When_Uppercased"), + ("dash", "Dash"), + ("decompositionmapping", "Decomposition_Mapping"), + ("decompositiontype", "Decomposition_Type"), + ("defaultignorablecodepoint", "Default_Ignorable_Code_Point"), + ("dep", "Deprecated"), + ("deprecated", "Deprecated"), + ("di", "Default_Ignorable_Code_Point"), + ("dia", "Diacritic"), + ("diacritic", "Diacritic"), + ("dm", "Decomposition_Mapping"), + ("dt", "Decomposition_Type"), + ("ea", "East_Asian_Width"), + ("eastasianwidth", "East_Asian_Width"), + ("ebase", "Emoji_Modifier_Base"), + ("ecomp", "Emoji_Component"), + ("emod", "Emoji_Modifier"), + ("emoji", "Emoji"), + ("emojicomponent", "Emoji_Component"), + ("emojimodifier", "Emoji_Modifier"), + ("emojimodifierbase", "Emoji_Modifier_Base"), + ("emojipresentation", "Emoji_Presentation"), + ("epres", "Emoji_Presentation"), + ("equideo", "Equivalent_Unified_Ideograph"), + ("equivalentunifiedideograph", "Equivalent_Unified_Ideograph"), + ("expandsonnfc", "Expands_On_NFC"), + ("expandsonnfd", "Expands_On_NFD"), + ("expandsonnfkc", "Expands_On_NFKC"), + ("expandsonnfkd", "Expands_On_NFKD"), + ("ext", "Extender"), + ("extendedpictographic", "Extended_Pictographic"), + ("extender", "Extender"), + ("extpict", "Extended_Pictographic"), + ("fcnfkc", "FC_NFKC_Closure"), + ("fcnfkcclosure", "FC_NFKC_Closure"), + ("fullcompositionexclusion", "Full_Composition_Exclusion"), + ("gc", "General_Category"), + ("gcb", "Grapheme_Cluster_Break"), + ("generalcategory", "General_Category"), + ("graphemebase", "Grapheme_Base"), + ("graphemeclusterbreak", "Grapheme_Cluster_Break"), + ("graphemeextend", "Grapheme_Extend"), + ("graphemelink", "Grapheme_Link"), + ("grbase", "Grapheme_Base"), + ("grext", "Grapheme_Extend"), + ("grlink", "Grapheme_Link"), + ("hangulsyllabletype", "Hangul_Syllable_Type"), + ("hex", "Hex_Digit"), + ("hexdigit", "Hex_Digit"), + ("hst", "Hangul_Syllable_Type"), + ("hyphen", "Hyphen"), + ("idc", "ID_Continue"), + ("idcontinue", "ID_Continue"), + ("ideo", "Ideographic"), + ("ideographic", "Ideographic"), + ("ids", "ID_Start"), + ("idsb", "IDS_Binary_Operator"), + ("idsbinaryoperator", "IDS_Binary_Operator"), + ("idst", "IDS_Trinary_Operator"), + ("idstart", "ID_Start"), + ("idstrinaryoperator", "IDS_Trinary_Operator"), + ("indicpositionalcategory", "Indic_Positional_Category"), + ("indicsyllabiccategory", "Indic_Syllabic_Category"), + ("inpc", "Indic_Positional_Category"), + ("insc", "Indic_Syllabic_Category"), + ("isc", "ISO_Comment"), + ("jamoshortname", "Jamo_Short_Name"), + ("jg", "Joining_Group"), + ("joinc", "Join_Control"), + ("joincontrol", "Join_Control"), + ("joininggroup", "Joining_Group"), + ("joiningtype", "Joining_Type"), + ("jsn", "Jamo_Short_Name"), + ("jt", "Joining_Type"), + ("kaccountingnumeric", "kAccountingNumeric"), + ("kcompatibilityvariant", "kCompatibilityVariant"), + ("kiicore", "kIICore"), + ("kirggsource", "kIRG_GSource"), + ("kirghsource", "kIRG_HSource"), + ("kirgjsource", "kIRG_JSource"), + ("kirgkpsource", "kIRG_KPSource"), + ("kirgksource", "kIRG_KSource"), + ("kirgmsource", "kIRG_MSource"), + ("kirgssource", "kIRG_SSource"), + ("kirgtsource", "kIRG_TSource"), + ("kirguksource", "kIRG_UKSource"), + ("kirgusource", "kIRG_USource"), + ("kirgvsource", "kIRG_VSource"), + ("kothernumeric", "kOtherNumeric"), + ("kprimarynumeric", "kPrimaryNumeric"), + ("krsunicode", "kRSUnicode"), + ("lb", "Line_Break"), + ("lc", "Lowercase_Mapping"), + ("linebreak", "Line_Break"), + ("loe", "Logical_Order_Exception"), + ("logicalorderexception", "Logical_Order_Exception"), + ("lower", "Lowercase"), + ("lowercase", "Lowercase"), + ("lowercasemapping", "Lowercase_Mapping"), + ("math", "Math"), + ("na", "Name"), + ("na1", "Unicode_1_Name"), + ("name", "Name"), + ("namealias", "Name_Alias"), + ("nchar", "Noncharacter_Code_Point"), + ("nfcqc", "NFC_Quick_Check"), + ("nfcquickcheck", "NFC_Quick_Check"), + ("nfdqc", "NFD_Quick_Check"), + ("nfdquickcheck", "NFD_Quick_Check"), + ("nfkccasefold", "NFKC_Casefold"), + ("nfkccf", "NFKC_Casefold"), + ("nfkcqc", "NFKC_Quick_Check"), + ("nfkcquickcheck", "NFKC_Quick_Check"), + ("nfkdqc", "NFKD_Quick_Check"), + ("nfkdquickcheck", "NFKD_Quick_Check"), + ("noncharactercodepoint", "Noncharacter_Code_Point"), + ("nt", "Numeric_Type"), + ("numerictype", "Numeric_Type"), + ("numericvalue", "Numeric_Value"), + ("nv", "Numeric_Value"), + ("oalpha", "Other_Alphabetic"), + ("ocomment", "ISO_Comment"), + ("odi", "Other_Default_Ignorable_Code_Point"), + ("ogrext", "Other_Grapheme_Extend"), + ("oidc", "Other_ID_Continue"), + ("oids", "Other_ID_Start"), + ("olower", "Other_Lowercase"), + ("omath", "Other_Math"), + ("otheralphabetic", "Other_Alphabetic"), + ("otherdefaultignorablecodepoint", "Other_Default_Ignorable_Code_Point"), + ("othergraphemeextend", "Other_Grapheme_Extend"), + ("otheridcontinue", "Other_ID_Continue"), + ("otheridstart", "Other_ID_Start"), + ("otherlowercase", "Other_Lowercase"), + ("othermath", "Other_Math"), + ("otheruppercase", "Other_Uppercase"), + ("oupper", "Other_Uppercase"), + ("patsyn", "Pattern_Syntax"), + ("patternsyntax", "Pattern_Syntax"), + ("patternwhitespace", "Pattern_White_Space"), + ("patws", "Pattern_White_Space"), + ("pcm", "Prepended_Concatenation_Mark"), + ("prependedconcatenationmark", "Prepended_Concatenation_Mark"), + ("qmark", "Quotation_Mark"), + ("quotationmark", "Quotation_Mark"), + ("radical", "Radical"), + ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), + ("sb", "Sentence_Break"), + ("sc", "Script"), + ("scf", "Simple_Case_Folding"), + ("script", "Script"), + ("scriptextensions", "Script_Extensions"), + ("scx", "Script_Extensions"), + ("sd", "Soft_Dotted"), + ("sentencebreak", "Sentence_Break"), + ("sentenceterminal", "Sentence_Terminal"), + ("sfc", "Simple_Case_Folding"), + ("simplecasefolding", "Simple_Case_Folding"), + ("simplelowercasemapping", "Simple_Lowercase_Mapping"), + ("simpletitlecasemapping", "Simple_Titlecase_Mapping"), + ("simpleuppercasemapping", "Simple_Uppercase_Mapping"), + ("slc", "Simple_Lowercase_Mapping"), + ("softdotted", "Soft_Dotted"), + ("space", "White_Space"), + ("stc", "Simple_Titlecase_Mapping"), + ("sterm", "Sentence_Terminal"), + ("suc", "Simple_Uppercase_Mapping"), + ("tc", "Titlecase_Mapping"), + ("term", "Terminal_Punctuation"), + ("terminalpunctuation", "Terminal_Punctuation"), + ("titlecasemapping", "Titlecase_Mapping"), + ("uc", "Uppercase_Mapping"), + ("uideo", "Unified_Ideograph"), + ("unicode1name", "Unicode_1_Name"), + ("unicoderadicalstroke", "kRSUnicode"), + ("unifiedideograph", "Unified_Ideograph"), + ("upper", "Uppercase"), + ("uppercase", "Uppercase"), + ("uppercasemapping", "Uppercase_Mapping"), + ("urs", "kRSUnicode"), + ("variationselector", "Variation_Selector"), + ("verticalorientation", "Vertical_Orientation"), + ("vo", "Vertical_Orientation"), + ("vs", "Variation_Selector"), + ("wb", "Word_Break"), + ("whitespace", "White_Space"), + ("wordbreak", "Word_Break"), + ("wspace", "White_Space"), + ("xidc", "XID_Continue"), + ("xidcontinue", "XID_Continue"), + ("xids", "XID_Start"), + ("xidstart", "XID_Start"), + ("xonfc", "Expands_On_NFC"), + ("xonfd", "Expands_On_NFD"), + ("xonfkc", "Expands_On_NFKC"), + ("xonfkd", "Expands_On_NFKD"), +]; diff --git a/bash-5.1/vendor/ucd-util/src/unicode_tables/property_values.rs b/bash-5.1/vendor/ucd-util/src/unicode_tables/property_values.rs new file mode 100644 index 0000000..b35588b --- /dev/null +++ b/bash-5.1/vendor/ucd-util/src/unicode_tables/property_values.rs @@ -0,0 +1,3041 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-values ucd-15.0.0 +// +// Unicode version: 15.0.0. +// +// ucd-generate 0.2.13 is available on crates.io. + +pub const PROPERTY_VALUES: &'static [( + &'static str, + &'static [(&'static str, &'static str)], +)] = &[ + ( + "ASCII_Hex_Digit", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Age", + &[ + ("1.1", "V1_1"), + ("10.0", "V10_0"), + ("11.0", "V11_0"), + ("12.0", "V12_0"), + ("12.1", "V12_1"), + ("13.0", "V13_0"), + ("14.0", "V14_0"), + ("15.0", "V15_0"), + ("2.0", "V2_0"), + ("2.1", "V2_1"), + ("3.0", "V3_0"), + ("3.1", "V3_1"), + ("3.2", "V3_2"), + ("4.0", "V4_0"), + ("4.1", "V4_1"), + ("5.0", "V5_0"), + ("5.1", "V5_1"), + ("5.2", "V5_2"), + ("6.0", "V6_0"), + ("6.1", "V6_1"), + ("6.2", "V6_2"), + ("6.3", "V6_3"), + ("7.0", "V7_0"), + ("8.0", "V8_0"), + ("9.0", "V9_0"), + ("na", "Unassigned"), + ("unassigned", "Unassigned"), + ("v100", "V10_0"), + ("v11", "V1_1"), + ("v110", "V11_0"), + ("v120", "V12_0"), + ("v121", "V12_1"), + ("v130", "V13_0"), + ("v140", "V14_0"), + ("v150", "V15_0"), + ("v20", "V2_0"), + ("v21", "V2_1"), + ("v30", "V3_0"), + ("v31", "V3_1"), + ("v32", "V3_2"), + ("v40", "V4_0"), + ("v41", "V4_1"), + ("v50", "V5_0"), + ("v51", "V5_1"), + ("v52", "V5_2"), + ("v60", "V6_0"), + ("v61", "V6_1"), + ("v62", "V6_2"), + ("v63", "V6_3"), + ("v70", "V7_0"), + ("v80", "V8_0"), + ("v90", "V9_0"), + ], + ), + ( + "Alphabetic", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Bidi_Class", + &[ + ("al", "Arabic_Letter"), + ("an", "Arabic_Number"), + ("arabicletter", "Arabic_Letter"), + ("arabicnumber", "Arabic_Number"), + ("b", "Paragraph_Separator"), + ("bn", "Boundary_Neutral"), + ("boundaryneutral", "Boundary_Neutral"), + ("commonseparator", "Common_Separator"), + ("cs", "Common_Separator"), + ("en", "European_Number"), + ("es", "European_Separator"), + ("et", "European_Terminator"), + ("europeannumber", "European_Number"), + ("europeanseparator", "European_Separator"), + ("europeanterminator", "European_Terminator"), + ("firststrongisolate", "First_Strong_Isolate"), + ("fsi", "First_Strong_Isolate"), + ("l", "Left_To_Right"), + ("lefttoright", "Left_To_Right"), + ("lefttorightembedding", "Left_To_Right_Embedding"), + ("lefttorightisolate", "Left_To_Right_Isolate"), + ("lefttorightoverride", "Left_To_Right_Override"), + ("lre", "Left_To_Right_Embedding"), + ("lri", "Left_To_Right_Isolate"), + ("lro", "Left_To_Right_Override"), + ("nonspacingmark", "Nonspacing_Mark"), + ("nsm", "Nonspacing_Mark"), + ("on", "Other_Neutral"), + ("otherneutral", "Other_Neutral"), + ("paragraphseparator", "Paragraph_Separator"), + ("pdf", "Pop_Directional_Format"), + ("pdi", "Pop_Directional_Isolate"), + ("popdirectionalformat", "Pop_Directional_Format"), + ("popdirectionalisolate", "Pop_Directional_Isolate"), + ("r", "Right_To_Left"), + ("righttoleft", "Right_To_Left"), + ("righttoleftembedding", "Right_To_Left_Embedding"), + ("righttoleftisolate", "Right_To_Left_Isolate"), + ("righttoleftoverride", "Right_To_Left_Override"), + ("rle", "Right_To_Left_Embedding"), + ("rli", "Right_To_Left_Isolate"), + ("rlo", "Right_To_Left_Override"), + ("s", "Segment_Separator"), + ("segmentseparator", "Segment_Separator"), + ("whitespace", "White_Space"), + ("ws", "White_Space"), + ], + ), + ( + "Bidi_Control", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Bidi_Mirrored", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Bidi_Paired_Bracket_Type", + &[ + ("c", "Close"), + ("close", "Close"), + ("n", "None"), + ("none", "None"), + ("o", "Open"), + ("open", "Open"), + ], + ), + ( + "Block", + &[ + ("adlam", "Adlam"), + ("aegeannumbers", "Aegean_Numbers"), + ("ahom", "Ahom"), + ("alchemical", "Alchemical_Symbols"), + ("alchemicalsymbols", "Alchemical_Symbols"), + ("alphabeticpf", "Alphabetic_Presentation_Forms"), + ("alphabeticpresentationforms", "Alphabetic_Presentation_Forms"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), + ("ancientgreekmusic", "Ancient_Greek_Musical_Notation"), + ("ancientgreekmusicalnotation", "Ancient_Greek_Musical_Notation"), + ("ancientgreeknumbers", "Ancient_Greek_Numbers"), + ("ancientsymbols", "Ancient_Symbols"), + ("arabic", "Arabic"), + ("arabicexta", "Arabic_Extended_A"), + ("arabicextb", "Arabic_Extended_B"), + ("arabicextc", "Arabic_Extended_C"), + ("arabicextendeda", "Arabic_Extended_A"), + ("arabicextendedb", "Arabic_Extended_B"), + ("arabicextendedc", "Arabic_Extended_C"), + ("arabicmath", "Arabic_Mathematical_Alphabetic_Symbols"), + ( + "arabicmathematicalalphabeticsymbols", + "Arabic_Mathematical_Alphabetic_Symbols", + ), + ("arabicpfa", "Arabic_Presentation_Forms_A"), + ("arabicpfb", "Arabic_Presentation_Forms_B"), + ("arabicpresentationformsa", "Arabic_Presentation_Forms_A"), + ("arabicpresentationformsb", "Arabic_Presentation_Forms_B"), + ("arabicsup", "Arabic_Supplement"), + ("arabicsupplement", "Arabic_Supplement"), + ("armenian", "Armenian"), + ("arrows", "Arrows"), + ("ascii", "Basic_Latin"), + ("avestan", "Avestan"), + ("balinese", "Balinese"), + ("bamum", "Bamum"), + ("bamumsup", "Bamum_Supplement"), + ("bamumsupplement", "Bamum_Supplement"), + ("basiclatin", "Basic_Latin"), + ("bassavah", "Bassa_Vah"), + ("batak", "Batak"), + ("bengali", "Bengali"), + ("bhaiksuki", "Bhaiksuki"), + ("blockelements", "Block_Elements"), + ("bopomofo", "Bopomofo"), + ("bopomofoext", "Bopomofo_Extended"), + ("bopomofoextended", "Bopomofo_Extended"), + ("boxdrawing", "Box_Drawing"), + ("brahmi", "Brahmi"), + ("braille", "Braille_Patterns"), + ("braillepatterns", "Braille_Patterns"), + ("buginese", "Buginese"), + ("buhid", "Buhid"), + ("byzantinemusic", "Byzantine_Musical_Symbols"), + ("byzantinemusicalsymbols", "Byzantine_Musical_Symbols"), + ("canadiansyllabics", "Unified_Canadian_Aboriginal_Syllabics"), + ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), + ("chakma", "Chakma"), + ("cham", "Cham"), + ("cherokee", "Cherokee"), + ("cherokeesup", "Cherokee_Supplement"), + ("cherokeesupplement", "Cherokee_Supplement"), + ("chesssymbols", "Chess_Symbols"), + ("chorasmian", "Chorasmian"), + ("cjk", "CJK_Unified_Ideographs"), + ("cjkcompat", "CJK_Compatibility"), + ("cjkcompatforms", "CJK_Compatibility_Forms"), + ("cjkcompatibility", "CJK_Compatibility"), + ("cjkcompatibilityforms", "CJK_Compatibility_Forms"), + ("cjkcompatibilityideographs", "CJK_Compatibility_Ideographs"), + ( + "cjkcompatibilityideographssupplement", + "CJK_Compatibility_Ideographs_Supplement", + ), + ("cjkcompatideographs", "CJK_Compatibility_Ideographs"), + ( + "cjkcompatideographssup", + "CJK_Compatibility_Ideographs_Supplement", + ), + ("cjkexta", "CJK_Unified_Ideographs_Extension_A"), + ("cjkextb", "CJK_Unified_Ideographs_Extension_B"), + ("cjkextc", "CJK_Unified_Ideographs_Extension_C"), + ("cjkextd", "CJK_Unified_Ideographs_Extension_D"), + ("cjkexte", "CJK_Unified_Ideographs_Extension_E"), + ("cjkextf", "CJK_Unified_Ideographs_Extension_F"), + ("cjkextg", "CJK_Unified_Ideographs_Extension_G"), + ("cjkexth", "CJK_Unified_Ideographs_Extension_H"), + ("cjkradicalssup", "CJK_Radicals_Supplement"), + ("cjkradicalssupplement", "CJK_Radicals_Supplement"), + ("cjkstrokes", "CJK_Strokes"), + ("cjksymbols", "CJK_Symbols_And_Punctuation"), + ("cjksymbolsandpunctuation", "CJK_Symbols_And_Punctuation"), + ("cjkunifiedideographs", "CJK_Unified_Ideographs"), + ( + "cjkunifiedideographsextensiona", + "CJK_Unified_Ideographs_Extension_A", + ), + ( + "cjkunifiedideographsextensionb", + "CJK_Unified_Ideographs_Extension_B", + ), + ( + "cjkunifiedideographsextensionc", + "CJK_Unified_Ideographs_Extension_C", + ), + ( + "cjkunifiedideographsextensiond", + "CJK_Unified_Ideographs_Extension_D", + ), + ( + "cjkunifiedideographsextensione", + "CJK_Unified_Ideographs_Extension_E", + ), + ( + "cjkunifiedideographsextensionf", + "CJK_Unified_Ideographs_Extension_F", + ), + ( + "cjkunifiedideographsextensiong", + "CJK_Unified_Ideographs_Extension_G", + ), + ( + "cjkunifiedideographsextensionh", + "CJK_Unified_Ideographs_Extension_H", + ), + ("combiningdiacriticalmarks", "Combining_Diacritical_Marks"), + ( + "combiningdiacriticalmarksextended", + "Combining_Diacritical_Marks_Extended", + ), + ( + "combiningdiacriticalmarksforsymbols", + "Combining_Diacritical_Marks_For_Symbols", + ), + ( + "combiningdiacriticalmarkssupplement", + "Combining_Diacritical_Marks_Supplement", + ), + ("combininghalfmarks", "Combining_Half_Marks"), + ( + "combiningmarksforsymbols", + "Combining_Diacritical_Marks_For_Symbols", + ), + ("commonindicnumberforms", "Common_Indic_Number_Forms"), + ("compatjamo", "Hangul_Compatibility_Jamo"), + ("controlpictures", "Control_Pictures"), + ("coptic", "Coptic"), + ("copticepactnumbers", "Coptic_Epact_Numbers"), + ("countingrod", "Counting_Rod_Numerals"), + ("countingrodnumerals", "Counting_Rod_Numerals"), + ("cuneiform", "Cuneiform"), + ("cuneiformnumbers", "Cuneiform_Numbers_And_Punctuation"), + ( + "cuneiformnumbersandpunctuation", + "Cuneiform_Numbers_And_Punctuation", + ), + ("currencysymbols", "Currency_Symbols"), + ("cypriotsyllabary", "Cypriot_Syllabary"), + ("cyprominoan", "Cypro_Minoan"), + ("cyrillic", "Cyrillic"), + ("cyrillicexta", "Cyrillic_Extended_A"), + ("cyrillicextb", "Cyrillic_Extended_B"), + ("cyrillicextc", "Cyrillic_Extended_C"), + ("cyrillicextd", "Cyrillic_Extended_D"), + ("cyrillicextendeda", "Cyrillic_Extended_A"), + ("cyrillicextendedb", "Cyrillic_Extended_B"), + ("cyrillicextendedc", "Cyrillic_Extended_C"), + ("cyrillicextendedd", "Cyrillic_Extended_D"), + ("cyrillicsup", "Cyrillic_Supplement"), + ("cyrillicsupplement", "Cyrillic_Supplement"), + ("cyrillicsupplementary", "Cyrillic_Supplement"), + ("deseret", "Deseret"), + ("devanagari", "Devanagari"), + ("devanagariext", "Devanagari_Extended"), + ("devanagariexta", "Devanagari_Extended_A"), + ("devanagariextended", "Devanagari_Extended"), + ("devanagariextendeda", "Devanagari_Extended_A"), + ("diacriticals", "Combining_Diacritical_Marks"), + ("diacriticalsext", "Combining_Diacritical_Marks_Extended"), + ( + "diacriticalsforsymbols", + "Combining_Diacritical_Marks_For_Symbols", + ), + ("diacriticalssup", "Combining_Diacritical_Marks_Supplement"), + ("dingbats", "Dingbats"), + ("divesakuru", "Dives_Akuru"), + ("dogra", "Dogra"), + ("domino", "Domino_Tiles"), + ("dominotiles", "Domino_Tiles"), + ("duployan", "Duployan"), + ("earlydynasticcuneiform", "Early_Dynastic_Cuneiform"), + ( + "egyptianhieroglyphformatcontrols", + "Egyptian_Hieroglyph_Format_Controls", + ), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), + ("elbasan", "Elbasan"), + ("elymaic", "Elymaic"), + ("emoticons", "Emoticons"), + ("enclosedalphanum", "Enclosed_Alphanumerics"), + ("enclosedalphanumerics", "Enclosed_Alphanumerics"), + ( + "enclosedalphanumericsupplement", + "Enclosed_Alphanumeric_Supplement", + ), + ("enclosedalphanumsup", "Enclosed_Alphanumeric_Supplement"), + ("enclosedcjk", "Enclosed_CJK_Letters_And_Months"), + ("enclosedcjklettersandmonths", "Enclosed_CJK_Letters_And_Months"), + ("enclosedideographicsup", "Enclosed_Ideographic_Supplement"), + ( + "enclosedideographicsupplement", + "Enclosed_Ideographic_Supplement", + ), + ("ethiopic", "Ethiopic"), + ("ethiopicext", "Ethiopic_Extended"), + ("ethiopicexta", "Ethiopic_Extended_A"), + ("ethiopicextb", "Ethiopic_Extended_B"), + ("ethiopicextended", "Ethiopic_Extended"), + ("ethiopicextendeda", "Ethiopic_Extended_A"), + ("ethiopicextendedb", "Ethiopic_Extended_B"), + ("ethiopicsup", "Ethiopic_Supplement"), + ("ethiopicsupplement", "Ethiopic_Supplement"), + ("generalpunctuation", "General_Punctuation"), + ("geometricshapes", "Geometric_Shapes"), + ("geometricshapesext", "Geometric_Shapes_Extended"), + ("geometricshapesextended", "Geometric_Shapes_Extended"), + ("georgian", "Georgian"), + ("georgianext", "Georgian_Extended"), + ("georgianextended", "Georgian_Extended"), + ("georgiansup", "Georgian_Supplement"), + ("georgiansupplement", "Georgian_Supplement"), + ("glagolitic", "Glagolitic"), + ("glagoliticsup", "Glagolitic_Supplement"), + ("glagoliticsupplement", "Glagolitic_Supplement"), + ("gothic", "Gothic"), + ("grantha", "Grantha"), + ("greek", "Greek_And_Coptic"), + ("greekandcoptic", "Greek_And_Coptic"), + ("greekext", "Greek_Extended"), + ("greekextended", "Greek_Extended"), + ("gujarati", "Gujarati"), + ("gunjalagondi", "Gunjala_Gondi"), + ("gurmukhi", "Gurmukhi"), + ("halfandfullforms", "Halfwidth_And_Fullwidth_Forms"), + ("halfmarks", "Combining_Half_Marks"), + ("halfwidthandfullwidthforms", "Halfwidth_And_Fullwidth_Forms"), + ("hangul", "Hangul_Syllables"), + ("hangulcompatibilityjamo", "Hangul_Compatibility_Jamo"), + ("hanguljamo", "Hangul_Jamo"), + ("hanguljamoextendeda", "Hangul_Jamo_Extended_A"), + ("hanguljamoextendedb", "Hangul_Jamo_Extended_B"), + ("hangulsyllables", "Hangul_Syllables"), + ("hanifirohingya", "Hanifi_Rohingya"), + ("hanunoo", "Hanunoo"), + ("hatran", "Hatran"), + ("hebrew", "Hebrew"), + ("highprivateusesurrogates", "High_Private_Use_Surrogates"), + ("highpusurrogates", "High_Private_Use_Surrogates"), + ("highsurrogates", "High_Surrogates"), + ("hiragana", "Hiragana"), + ("idc", "Ideographic_Description_Characters"), + ( + "ideographicdescriptioncharacters", + "Ideographic_Description_Characters", + ), + ("ideographicsymbols", "Ideographic_Symbols_And_Punctuation"), + ( + "ideographicsymbolsandpunctuation", + "Ideographic_Symbols_And_Punctuation", + ), + ("imperialaramaic", "Imperial_Aramaic"), + ("indicnumberforms", "Common_Indic_Number_Forms"), + ("indicsiyaqnumbers", "Indic_Siyaq_Numbers"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), + ("ipaext", "IPA_Extensions"), + ("ipaextensions", "IPA_Extensions"), + ("jamo", "Hangul_Jamo"), + ("jamoexta", "Hangul_Jamo_Extended_A"), + ("jamoextb", "Hangul_Jamo_Extended_B"), + ("javanese", "Javanese"), + ("kaithi", "Kaithi"), + ("kaktoviknumerals", "Kaktovik_Numerals"), + ("kanaexta", "Kana_Extended_A"), + ("kanaextb", "Kana_Extended_B"), + ("kanaextendeda", "Kana_Extended_A"), + ("kanaextendedb", "Kana_Extended_B"), + ("kanasup", "Kana_Supplement"), + ("kanasupplement", "Kana_Supplement"), + ("kanbun", "Kanbun"), + ("kangxi", "Kangxi_Radicals"), + ("kangxiradicals", "Kangxi_Radicals"), + ("kannada", "Kannada"), + ("katakana", "Katakana"), + ("katakanaext", "Katakana_Phonetic_Extensions"), + ("katakanaphoneticextensions", "Katakana_Phonetic_Extensions"), + ("kawi", "Kawi"), + ("kayahli", "Kayah_Li"), + ("kharoshthi", "Kharoshthi"), + ("khitansmallscript", "Khitan_Small_Script"), + ("khmer", "Khmer"), + ("khmersymbols", "Khmer_Symbols"), + ("khojki", "Khojki"), + ("khudawadi", "Khudawadi"), + ("lao", "Lao"), + ("latin1", "Latin_1_Supplement"), + ("latin1sup", "Latin_1_Supplement"), + ("latin1supplement", "Latin_1_Supplement"), + ("latinexta", "Latin_Extended_A"), + ("latinextadditional", "Latin_Extended_Additional"), + ("latinextb", "Latin_Extended_B"), + ("latinextc", "Latin_Extended_C"), + ("latinextd", "Latin_Extended_D"), + ("latinexte", "Latin_Extended_E"), + ("latinextendeda", "Latin_Extended_A"), + ("latinextendedadditional", "Latin_Extended_Additional"), + ("latinextendedb", "Latin_Extended_B"), + ("latinextendedc", "Latin_Extended_C"), + ("latinextendedd", "Latin_Extended_D"), + ("latinextendede", "Latin_Extended_E"), + ("latinextendedf", "Latin_Extended_F"), + ("latinextendedg", "Latin_Extended_G"), + ("latinextf", "Latin_Extended_F"), + ("latinextg", "Latin_Extended_G"), + ("lepcha", "Lepcha"), + ("letterlikesymbols", "Letterlike_Symbols"), + ("limbu", "Limbu"), + ("lineara", "Linear_A"), + ("linearbideograms", "Linear_B_Ideograms"), + ("linearbsyllabary", "Linear_B_Syllabary"), + ("lisu", "Lisu"), + ("lisusup", "Lisu_Supplement"), + ("lisusupplement", "Lisu_Supplement"), + ("lowsurrogates", "Low_Surrogates"), + ("lycian", "Lycian"), + ("lydian", "Lydian"), + ("mahajani", "Mahajani"), + ("mahjong", "Mahjong_Tiles"), + ("mahjongtiles", "Mahjong_Tiles"), + ("makasar", "Makasar"), + ("malayalam", "Malayalam"), + ("mandaic", "Mandaic"), + ("manichaean", "Manichaean"), + ("marchen", "Marchen"), + ("masaramgondi", "Masaram_Gondi"), + ("mathalphanum", "Mathematical_Alphanumeric_Symbols"), + ( + "mathematicalalphanumericsymbols", + "Mathematical_Alphanumeric_Symbols", + ), + ("mathematicaloperators", "Mathematical_Operators"), + ("mathoperators", "Mathematical_Operators"), + ("mayannumerals", "Mayan_Numerals"), + ("medefaidrin", "Medefaidrin"), + ("meeteimayek", "Meetei_Mayek"), + ("meeteimayekext", "Meetei_Mayek_Extensions"), + ("meeteimayekextensions", "Meetei_Mayek_Extensions"), + ("mendekikakui", "Mende_Kikakui"), + ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), + ("miao", "Miao"), + ("miscarrows", "Miscellaneous_Symbols_And_Arrows"), + ( + "miscellaneousmathematicalsymbolsa", + "Miscellaneous_Mathematical_Symbols_A", + ), + ( + "miscellaneousmathematicalsymbolsb", + "Miscellaneous_Mathematical_Symbols_B", + ), + ("miscellaneoussymbols", "Miscellaneous_Symbols"), + ( + "miscellaneoussymbolsandarrows", + "Miscellaneous_Symbols_And_Arrows", + ), + ( + "miscellaneoussymbolsandpictographs", + "Miscellaneous_Symbols_And_Pictographs", + ), + ("miscellaneoustechnical", "Miscellaneous_Technical"), + ("miscmathsymbolsa", "Miscellaneous_Mathematical_Symbols_A"), + ("miscmathsymbolsb", "Miscellaneous_Mathematical_Symbols_B"), + ("miscpictographs", "Miscellaneous_Symbols_And_Pictographs"), + ("miscsymbols", "Miscellaneous_Symbols"), + ("misctechnical", "Miscellaneous_Technical"), + ("modi", "Modi"), + ("modifierletters", "Spacing_Modifier_Letters"), + ("modifiertoneletters", "Modifier_Tone_Letters"), + ("mongolian", "Mongolian"), + ("mongoliansup", "Mongolian_Supplement"), + ("mongoliansupplement", "Mongolian_Supplement"), + ("mro", "Mro"), + ("multani", "Multani"), + ("music", "Musical_Symbols"), + ("musicalsymbols", "Musical_Symbols"), + ("myanmar", "Myanmar"), + ("myanmarexta", "Myanmar_Extended_A"), + ("myanmarextb", "Myanmar_Extended_B"), + ("myanmarextendeda", "Myanmar_Extended_A"), + ("myanmarextendedb", "Myanmar_Extended_B"), + ("nabataean", "Nabataean"), + ("nagmundari", "Nag_Mundari"), + ("nandinagari", "Nandinagari"), + ("nb", "No_Block"), + ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), + ("nko", "NKo"), + ("noblock", "No_Block"), + ("numberforms", "Number_Forms"), + ("nushu", "Nushu"), + ("nyiakengpuachuehmong", "Nyiakeng_Puachue_Hmong"), + ("ocr", "Optical_Character_Recognition"), + ("ogham", "Ogham"), + ("olchiki", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), + ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), + ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), + ("oldsogdian", "Old_Sogdian"), + ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), + ("olduyghur", "Old_Uyghur"), + ("opticalcharacterrecognition", "Optical_Character_Recognition"), + ("oriya", "Oriya"), + ("ornamentaldingbats", "Ornamental_Dingbats"), + ("osage", "Osage"), + ("osmanya", "Osmanya"), + ("ottomansiyaqnumbers", "Ottoman_Siyaq_Numbers"), + ("pahawhhmong", "Pahawh_Hmong"), + ("palmyrene", "Palmyrene"), + ("paucinhau", "Pau_Cin_Hau"), + ("phagspa", "Phags_Pa"), + ("phaistos", "Phaistos_Disc"), + ("phaistosdisc", "Phaistos_Disc"), + ("phoenician", "Phoenician"), + ("phoneticext", "Phonetic_Extensions"), + ("phoneticextensions", "Phonetic_Extensions"), + ("phoneticextensionssupplement", "Phonetic_Extensions_Supplement"), + ("phoneticextsup", "Phonetic_Extensions_Supplement"), + ("playingcards", "Playing_Cards"), + ("privateuse", "Private_Use_Area"), + ("privateusearea", "Private_Use_Area"), + ("psalterpahlavi", "Psalter_Pahlavi"), + ("pua", "Private_Use_Area"), + ("punctuation", "General_Punctuation"), + ("rejang", "Rejang"), + ("rumi", "Rumi_Numeral_Symbols"), + ("ruminumeralsymbols", "Rumi_Numeral_Symbols"), + ("runic", "Runic"), + ("samaritan", "Samaritan"), + ("saurashtra", "Saurashtra"), + ("sharada", "Sharada"), + ("shavian", "Shavian"), + ("shorthandformatcontrols", "Shorthand_Format_Controls"), + ("siddham", "Siddham"), + ("sinhala", "Sinhala"), + ("sinhalaarchaicnumbers", "Sinhala_Archaic_Numbers"), + ("smallforms", "Small_Form_Variants"), + ("smallformvariants", "Small_Form_Variants"), + ("smallkanaext", "Small_Kana_Extension"), + ("smallkanaextension", "Small_Kana_Extension"), + ("sogdian", "Sogdian"), + ("sorasompeng", "Sora_Sompeng"), + ("soyombo", "Soyombo"), + ("spacingmodifierletters", "Spacing_Modifier_Letters"), + ("specials", "Specials"), + ("sundanese", "Sundanese"), + ("sundanesesup", "Sundanese_Supplement"), + ("sundanesesupplement", "Sundanese_Supplement"), + ("suparrowsa", "Supplemental_Arrows_A"), + ("suparrowsb", "Supplemental_Arrows_B"), + ("suparrowsc", "Supplemental_Arrows_C"), + ("superandsub", "Superscripts_And_Subscripts"), + ("superscriptsandsubscripts", "Superscripts_And_Subscripts"), + ("supmathoperators", "Supplemental_Mathematical_Operators"), + ("supplementalarrowsa", "Supplemental_Arrows_A"), + ("supplementalarrowsb", "Supplemental_Arrows_B"), + ("supplementalarrowsc", "Supplemental_Arrows_C"), + ( + "supplementalmathematicaloperators", + "Supplemental_Mathematical_Operators", + ), + ("supplementalpunctuation", "Supplemental_Punctuation"), + ( + "supplementalsymbolsandpictographs", + "Supplemental_Symbols_And_Pictographs", + ), + ( + "supplementaryprivateuseareaa", + "Supplementary_Private_Use_Area_A", + ), + ( + "supplementaryprivateuseareab", + "Supplementary_Private_Use_Area_B", + ), + ("suppuaa", "Supplementary_Private_Use_Area_A"), + ("suppuab", "Supplementary_Private_Use_Area_B"), + ("suppunctuation", "Supplemental_Punctuation"), + ( + "supsymbolsandpictographs", + "Supplemental_Symbols_And_Pictographs", + ), + ("suttonsignwriting", "Sutton_SignWriting"), + ("sylotinagri", "Syloti_Nagri"), + ( + "symbolsandpictographsexta", + "Symbols_And_Pictographs_Extended_A", + ), + ( + "symbolsandpictographsextendeda", + "Symbols_And_Pictographs_Extended_A", + ), + ("symbolsforlegacycomputing", "Symbols_For_Legacy_Computing"), + ("syriac", "Syriac"), + ("syriacsup", "Syriac_Supplement"), + ("syriacsupplement", "Syriac_Supplement"), + ("tagalog", "Tagalog"), + ("tagbanwa", "Tagbanwa"), + ("tags", "Tags"), + ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), + ("taiviet", "Tai_Viet"), + ("taixuanjing", "Tai_Xuan_Jing_Symbols"), + ("taixuanjingsymbols", "Tai_Xuan_Jing_Symbols"), + ("takri", "Takri"), + ("tamil", "Tamil"), + ("tamilsup", "Tamil_Supplement"), + ("tamilsupplement", "Tamil_Supplement"), + ("tangsa", "Tangsa"), + ("tangut", "Tangut"), + ("tangutcomponents", "Tangut_Components"), + ("tangutsup", "Tangut_Supplement"), + ("tangutsupplement", "Tangut_Supplement"), + ("telugu", "Telugu"), + ("thaana", "Thaana"), + ("thai", "Thai"), + ("tibetan", "Tibetan"), + ("tifinagh", "Tifinagh"), + ("tirhuta", "Tirhuta"), + ("toto", "Toto"), + ("transportandmap", "Transport_And_Map_Symbols"), + ("transportandmapsymbols", "Transport_And_Map_Symbols"), + ("ucas", "Unified_Canadian_Aboriginal_Syllabics"), + ("ucasext", "Unified_Canadian_Aboriginal_Syllabics_Extended"), + ("ucasexta", "Unified_Canadian_Aboriginal_Syllabics_Extended_A"), + ("ugaritic", "Ugaritic"), + ( + "unifiedcanadianaboriginalsyllabics", + "Unified_Canadian_Aboriginal_Syllabics", + ), + ( + "unifiedcanadianaboriginalsyllabicsextended", + "Unified_Canadian_Aboriginal_Syllabics_Extended", + ), + ( + "unifiedcanadianaboriginalsyllabicsextendeda", + "Unified_Canadian_Aboriginal_Syllabics_Extended_A", + ), + ("vai", "Vai"), + ("variationselectors", "Variation_Selectors"), + ("variationselectorssupplement", "Variation_Selectors_Supplement"), + ("vedicext", "Vedic_Extensions"), + ("vedicextensions", "Vedic_Extensions"), + ("verticalforms", "Vertical_Forms"), + ("vithkuqi", "Vithkuqi"), + ("vs", "Variation_Selectors"), + ("vssup", "Variation_Selectors_Supplement"), + ("wancho", "Wancho"), + ("warangciti", "Warang_Citi"), + ("yezidi", "Yezidi"), + ("yijing", "Yijing_Hexagram_Symbols"), + ("yijinghexagramsymbols", "Yijing_Hexagram_Symbols"), + ("yiradicals", "Yi_Radicals"), + ("yisyllables", "Yi_Syllables"), + ("zanabazarsquare", "Zanabazar_Square"), + ("znamennymusic", "Znamenny_Musical_Notation"), + ("znamennymusicalnotation", "Znamenny_Musical_Notation"), + ], + ), + ( + "Canonical_Combining_Class", + &[ + ("", "Iota_Subscript"), + ("0", "Not_Reordered"), + ("1", "Overlay"), + ("10", "CCC10"), + ("103", "CCC103"), + ("107", "CCC107"), + ("11", "CCC11"), + ("118", "CCC118"), + ("12", "CCC12"), + ("122", "CCC122"), + ("129", "CCC129"), + ("13", "CCC13"), + ("130", "CCC130"), + ("132", "CCC132"), + ("133", "CCC133"), + ("14", "CCC14"), + ("15", "CCC15"), + ("16", "CCC16"), + ("17", "CCC17"), + ("18", "CCC18"), + ("19", "CCC19"), + ("20", "CCC20"), + ("200", "Attached_Below_Left"), + ("202", "Attached_Below"), + ("21", "CCC21"), + ("214", "Attached_Above"), + ("216", "Attached_Above_Right"), + ("218", "Below_Left"), + ("22", "CCC22"), + ("220", "Below"), + ("222", "Below_Right"), + ("224", "Left"), + ("226", "Right"), + ("228", "Above_Left"), + ("23", "CCC23"), + ("230", "Above"), + ("232", "Above_Right"), + ("233", "Double_Below"), + ("234", "Double_Above"), + ("24", "CCC24"), + ("240", "Iota_Subscript"), + ("25", "CCC25"), + ("26", "CCC26"), + ("27", "CCC27"), + ("28", "CCC28"), + ("29", "CCC29"), + ("30", "CCC30"), + ("31", "CCC31"), + ("32", "CCC32"), + ("33", "CCC33"), + ("34", "CCC34"), + ("35", "CCC35"), + ("36", "CCC36"), + ("6", "Han_Reading"), + ("7", "Nukta"), + ("8", "Kana_Voicing"), + ("84", "CCC84"), + ("9", "Virama"), + ("91", "CCC91"), + ("a", "Above"), + ("above", "Above"), + ("aboveleft", "Above_Left"), + ("aboveright", "Above_Right"), + ("al", "Above_Left"), + ("ar", "Above_Right"), + ("ata", "Attached_Above"), + ("atar", "Attached_Above_Right"), + ("atb", "Attached_Below"), + ("atbl", "Attached_Below_Left"), + ("attachedabove", "Attached_Above"), + ("attachedaboveright", "Attached_Above_Right"), + ("attachedbelow", "Attached_Below"), + ("attachedbelowleft", "Attached_Below_Left"), + ("b", "Below"), + ("below", "Below"), + ("belowleft", "Below_Left"), + ("belowright", "Below_Right"), + ("bl", "Below_Left"), + ("br", "Below_Right"), + ("ccc10", "CCC10"), + ("ccc103", "CCC103"), + ("ccc107", "CCC107"), + ("ccc11", "CCC11"), + ("ccc118", "CCC118"), + ("ccc12", "CCC12"), + ("ccc122", "CCC122"), + ("ccc129", "CCC129"), + ("ccc13", "CCC13"), + ("ccc130", "CCC130"), + ("ccc132", "CCC132"), + ("ccc133", "CCC133"), + ("ccc14", "CCC14"), + ("ccc15", "CCC15"), + ("ccc16", "CCC16"), + ("ccc17", "CCC17"), + ("ccc18", "CCC18"), + ("ccc19", "CCC19"), + ("ccc20", "CCC20"), + ("ccc21", "CCC21"), + ("ccc22", "CCC22"), + ("ccc23", "CCC23"), + ("ccc24", "CCC24"), + ("ccc25", "CCC25"), + ("ccc26", "CCC26"), + ("ccc27", "CCC27"), + ("ccc28", "CCC28"), + ("ccc29", "CCC29"), + ("ccc30", "CCC30"), + ("ccc31", "CCC31"), + ("ccc32", "CCC32"), + ("ccc33", "CCC33"), + ("ccc34", "CCC34"), + ("ccc35", "CCC35"), + ("ccc36", "CCC36"), + ("ccc84", "CCC84"), + ("ccc91", "CCC91"), + ("da", "Double_Above"), + ("db", "Double_Below"), + ("doubleabove", "Double_Above"), + ("doublebelow", "Double_Below"), + ("hanr", "Han_Reading"), + ("hanreading", "Han_Reading"), + ("iotasubscript", "Iota_Subscript"), + ("kanavoicing", "Kana_Voicing"), + ("kv", "Kana_Voicing"), + ("l", "Left"), + ("left", "Left"), + ("nk", "Nukta"), + ("notreordered", "Not_Reordered"), + ("nr", "Not_Reordered"), + ("nukta", "Nukta"), + ("ov", "Overlay"), + ("overlay", "Overlay"), + ("r", "Right"), + ("right", "Right"), + ("virama", "Virama"), + ("vr", "Virama"), + ], + ), + ( + "Case_Ignorable", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Cased", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Changes_When_Casefolded", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Changes_When_Casemapped", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Changes_When_Lowercased", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Changes_When_NFKC_Casefolded", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Changes_When_Titlecased", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Changes_When_Uppercased", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Composition_Exclusion", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Dash", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Decomposition_Type", + &[ + ("can", "Canonical"), + ("canonical", "Canonical"), + ("circle", "Circle"), + ("com", "Compat"), + ("compat", "Compat"), + ("enc", "Circle"), + ("fin", "Final"), + ("final", "Final"), + ("font", "Font"), + ("fra", "Fraction"), + ("fraction", "Fraction"), + ("init", "Initial"), + ("initial", "Initial"), + ("med", "Medial"), + ("medial", "Medial"), + ("nar", "Narrow"), + ("narrow", "Narrow"), + ("nb", "Nobreak"), + ("nobreak", "Nobreak"), + ("none", "None"), + ("o", "Isolated"), + ("olated", "Isolated"), + ("small", "Small"), + ("sml", "Small"), + ("sqr", "Square"), + ("square", "Square"), + ("sub", "Sub"), + ("sup", "Super"), + ("super", "Super"), + ("vert", "Vertical"), + ("vertical", "Vertical"), + ("wide", "Wide"), + ], + ), + ( + "Default_Ignorable_Code_Point", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Deprecated", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Diacritic", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "East_Asian_Width", + &[ + ("a", "Ambiguous"), + ("ambiguous", "Ambiguous"), + ("f", "Fullwidth"), + ("fullwidth", "Fullwidth"), + ("h", "Halfwidth"), + ("halfwidth", "Halfwidth"), + ("n", "Neutral"), + ("na", "Narrow"), + ("narrow", "Narrow"), + ("neutral", "Neutral"), + ("w", "Wide"), + ("wide", "Wide"), + ], + ), + ( + "Emoji", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Emoji_Component", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Emoji_Modifier", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Emoji_Modifier_Base", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Emoji_Presentation", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Expands_On_NFC", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Expands_On_NFD", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Expands_On_NFKC", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Expands_On_NFKD", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Extended_Pictographic", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Extender", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Full_Composition_Exclusion", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "General_Category", + &[ + ("c", "Other"), + ("casedletter", "Cased_Letter"), + ("cc", "Control"), + ("cf", "Format"), + ("closepunctuation", "Close_Punctuation"), + ("cn", "Unassigned"), + ("cntrl", "Control"), + ("co", "Private_Use"), + ("combiningmark", "Mark"), + ("connectorpunctuation", "Connector_Punctuation"), + ("control", "Control"), + ("cs", "Surrogate"), + ("currencysymbol", "Currency_Symbol"), + ("dashpunctuation", "Dash_Punctuation"), + ("decimalnumber", "Decimal_Number"), + ("digit", "Decimal_Number"), + ("enclosingmark", "Enclosing_Mark"), + ("finalpunctuation", "Final_Punctuation"), + ("format", "Format"), + ("initialpunctuation", "Initial_Punctuation"), + ("l", "Letter"), + ("lc", "Cased_Letter"), + ("letter", "Letter"), + ("letternumber", "Letter_Number"), + ("lineseparator", "Line_Separator"), + ("ll", "Lowercase_Letter"), + ("lm", "Modifier_Letter"), + ("lo", "Other_Letter"), + ("lowercaseletter", "Lowercase_Letter"), + ("lt", "Titlecase_Letter"), + ("lu", "Uppercase_Letter"), + ("m", "Mark"), + ("mark", "Mark"), + ("mathsymbol", "Math_Symbol"), + ("mc", "Spacing_Mark"), + ("me", "Enclosing_Mark"), + ("mn", "Nonspacing_Mark"), + ("modifierletter", "Modifier_Letter"), + ("modifiersymbol", "Modifier_Symbol"), + ("n", "Number"), + ("nd", "Decimal_Number"), + ("nl", "Letter_Number"), + ("no", "Other_Number"), + ("nonspacingmark", "Nonspacing_Mark"), + ("number", "Number"), + ("openpunctuation", "Open_Punctuation"), + ("other", "Other"), + ("otherletter", "Other_Letter"), + ("othernumber", "Other_Number"), + ("otherpunctuation", "Other_Punctuation"), + ("othersymbol", "Other_Symbol"), + ("p", "Punctuation"), + ("paragraphseparator", "Paragraph_Separator"), + ("pc", "Connector_Punctuation"), + ("pd", "Dash_Punctuation"), + ("pe", "Close_Punctuation"), + ("pf", "Final_Punctuation"), + ("pi", "Initial_Punctuation"), + ("po", "Other_Punctuation"), + ("privateuse", "Private_Use"), + ("ps", "Open_Punctuation"), + ("punct", "Punctuation"), + ("punctuation", "Punctuation"), + ("s", "Symbol"), + ("sc", "Currency_Symbol"), + ("separator", "Separator"), + ("sk", "Modifier_Symbol"), + ("sm", "Math_Symbol"), + ("so", "Other_Symbol"), + ("spaceseparator", "Space_Separator"), + ("spacingmark", "Spacing_Mark"), + ("surrogate", "Surrogate"), + ("symbol", "Symbol"), + ("titlecaseletter", "Titlecase_Letter"), + ("unassigned", "Unassigned"), + ("uppercaseletter", "Uppercase_Letter"), + ("z", "Separator"), + ("zl", "Line_Separator"), + ("zp", "Paragraph_Separator"), + ("zs", "Space_Separator"), + ], + ), + ( + "Grapheme_Base", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Grapheme_Cluster_Break", + &[ + ("cn", "Control"), + ("control", "Control"), + ("cr", "CR"), + ("eb", "E_Base"), + ("ebase", "E_Base"), + ("ebasegaz", "E_Base_GAZ"), + ("ebg", "E_Base_GAZ"), + ("em", "E_Modifier"), + ("emodifier", "E_Modifier"), + ("ex", "Extend"), + ("extend", "Extend"), + ("gaz", "Glue_After_Zwj"), + ("glueafterzwj", "Glue_After_Zwj"), + ("l", "L"), + ("lf", "LF"), + ("lv", "LV"), + ("lvt", "LVT"), + ("other", "Other"), + ("pp", "Prepend"), + ("prepend", "Prepend"), + ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), + ("sm", "SpacingMark"), + ("spacingmark", "SpacingMark"), + ("t", "T"), + ("v", "V"), + ("xx", "Other"), + ("zwj", "ZWJ"), + ], + ), + ( + "Grapheme_Extend", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Grapheme_Link", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Hangul_Syllable_Type", + &[ + ("l", "Leading_Jamo"), + ("leadingjamo", "Leading_Jamo"), + ("lv", "LV_Syllable"), + ("lvsyllable", "LV_Syllable"), + ("lvt", "LVT_Syllable"), + ("lvtsyllable", "LVT_Syllable"), + ("na", "Not_Applicable"), + ("notapplicable", "Not_Applicable"), + ("t", "Trailing_Jamo"), + ("trailingjamo", "Trailing_Jamo"), + ("v", "Vowel_Jamo"), + ("voweljamo", "Vowel_Jamo"), + ], + ), + ( + "Hex_Digit", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Hyphen", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "IDS_Binary_Operator", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "IDS_Trinary_Operator", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "ID_Continue", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "ID_Start", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Ideographic", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Indic_Positional_Category", + &[ + ("bottom", "Bottom"), + ("bottomandleft", "Bottom_And_Left"), + ("bottomandright", "Bottom_And_Right"), + ("left", "Left"), + ("leftandright", "Left_And_Right"), + ("na", "NA"), + ("overstruck", "Overstruck"), + ("right", "Right"), + ("top", "Top"), + ("topandbottom", "Top_And_Bottom"), + ("topandbottomandleft", "Top_And_Bottom_And_Left"), + ("topandbottomandright", "Top_And_Bottom_And_Right"), + ("topandleft", "Top_And_Left"), + ("topandleftandright", "Top_And_Left_And_Right"), + ("topandright", "Top_And_Right"), + ("visualorderleft", "Visual_Order_Left"), + ], + ), + ( + "Indic_Syllabic_Category", + &[ + ("avagraha", "Avagraha"), + ("bindu", "Bindu"), + ("brahmijoiningnumber", "Brahmi_Joining_Number"), + ("cantillationmark", "Cantillation_Mark"), + ("consonant", "Consonant"), + ("consonantdead", "Consonant_Dead"), + ("consonantfinal", "Consonant_Final"), + ("consonantheadletter", "Consonant_Head_Letter"), + ("consonantinitialpostfixed", "Consonant_Initial_Postfixed"), + ("consonantkiller", "Consonant_Killer"), + ("consonantmedial", "Consonant_Medial"), + ("consonantplaceholder", "Consonant_Placeholder"), + ("consonantprecedingrepha", "Consonant_Preceding_Repha"), + ("consonantprefixed", "Consonant_Prefixed"), + ("consonantsubjoined", "Consonant_Subjoined"), + ("consonantsucceedingrepha", "Consonant_Succeeding_Repha"), + ("consonantwithstacker", "Consonant_With_Stacker"), + ("geminationmark", "Gemination_Mark"), + ("invisiblestacker", "Invisible_Stacker"), + ("joiner", "Joiner"), + ("modifyingletter", "Modifying_Letter"), + ("nonjoiner", "Non_Joiner"), + ("nukta", "Nukta"), + ("number", "Number"), + ("numberjoiner", "Number_Joiner"), + ("other", "Other"), + ("purekiller", "Pure_Killer"), + ("registershifter", "Register_Shifter"), + ("syllablemodifier", "Syllable_Modifier"), + ("toneletter", "Tone_Letter"), + ("tonemark", "Tone_Mark"), + ("virama", "Virama"), + ("visarga", "Visarga"), + ("vowel", "Vowel"), + ("voweldependent", "Vowel_Dependent"), + ("vowelindependent", "Vowel_Independent"), + ], + ), + ( + "Jamo_Short_Name", + &[ + ("a", "A"), + ("ae", "AE"), + ("b", "B"), + ("bb", "BB"), + ("bs", "BS"), + ("c", "C"), + ("d", "D"), + ("dd", "DD"), + ("e", "E"), + ("eo", "EO"), + ("eu", "EU"), + ("g", "G"), + ("gg", "GG"), + ("gs", "GS"), + ("h", "H"), + ("i", "I"), + ("j", "J"), + ("jj", "JJ"), + ("k", "K"), + ("l", "L"), + ("lb", "LB"), + ("lg", "LG"), + ("lh", "LH"), + ("lm", "LM"), + ("lp", "LP"), + ("ls", "LS"), + ("lt", "LT"), + ("m", "M"), + ("n", "N"), + ("ng", "NG"), + ("nh", "NH"), + ("nj", "NJ"), + ("o", "O"), + ("oe", "OE"), + ("p", "P"), + ("r", "R"), + ("s", "S"), + ("ss", "SS"), + ("t", "T"), + ("u", "U"), + ("wa", "WA"), + ("wae", "WAE"), + ("we", "WE"), + ("weo", "WEO"), + ("wi", "WI"), + ("ya", "YA"), + ("yae", "YAE"), + ("ye", "YE"), + ("yeo", "YEO"), + ("yi", "YI"), + ("yo", "YO"), + ("yu", "YU"), + ], + ), + ( + "Join_Control", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Joining_Group", + &[ + ("africanfeh", "African_Feh"), + ("africannoon", "African_Noon"), + ("africanqaf", "African_Qaf"), + ("ain", "Ain"), + ("alaph", "Alaph"), + ("alef", "Alef"), + ("beh", "Beh"), + ("beth", "Beth"), + ("burushaskiyehbarree", "Burushaski_Yeh_Barree"), + ("dal", "Dal"), + ("dalathrish", "Dalath_Rish"), + ("e", "E"), + ("farsiyeh", "Farsi_Yeh"), + ("fe", "Fe"), + ("feh", "Feh"), + ("finalsemkath", "Final_Semkath"), + ("gaf", "Gaf"), + ("gamal", "Gamal"), + ("hah", "Hah"), + ("hamzaonhehgoal", "Hamza_On_Heh_Goal"), + ("hanifirohingyakinnaya", "Hanifi_Rohingya_Kinna_Ya"), + ("hanifirohingyapa", "Hanifi_Rohingya_Pa"), + ("he", "He"), + ("heh", "Heh"), + ("hehgoal", "Heh_Goal"), + ("heth", "Heth"), + ("kaf", "Kaf"), + ("kaph", "Kaph"), + ("khaph", "Khaph"), + ("knottedheh", "Knotted_Heh"), + ("lam", "Lam"), + ("lamadh", "Lamadh"), + ("malayalambha", "Malayalam_Bha"), + ("malayalamja", "Malayalam_Ja"), + ("malayalamlla", "Malayalam_Lla"), + ("malayalamllla", "Malayalam_Llla"), + ("malayalamnga", "Malayalam_Nga"), + ("malayalamnna", "Malayalam_Nna"), + ("malayalamnnna", "Malayalam_Nnna"), + ("malayalamnya", "Malayalam_Nya"), + ("malayalamra", "Malayalam_Ra"), + ("malayalamssa", "Malayalam_Ssa"), + ("malayalamtta", "Malayalam_Tta"), + ("manichaeanaleph", "Manichaean_Aleph"), + ("manichaeanayin", "Manichaean_Ayin"), + ("manichaeanbeth", "Manichaean_Beth"), + ("manichaeandaleth", "Manichaean_Daleth"), + ("manichaeandhamedh", "Manichaean_Dhamedh"), + ("manichaeanfive", "Manichaean_Five"), + ("manichaeangimel", "Manichaean_Gimel"), + ("manichaeanheth", "Manichaean_Heth"), + ("manichaeanhundred", "Manichaean_Hundred"), + ("manichaeankaph", "Manichaean_Kaph"), + ("manichaeanlamedh", "Manichaean_Lamedh"), + ("manichaeanmem", "Manichaean_Mem"), + ("manichaeannun", "Manichaean_Nun"), + ("manichaeanone", "Manichaean_One"), + ("manichaeanpe", "Manichaean_Pe"), + ("manichaeanqoph", "Manichaean_Qoph"), + ("manichaeanresh", "Manichaean_Resh"), + ("manichaeansadhe", "Manichaean_Sadhe"), + ("manichaeansamekh", "Manichaean_Samekh"), + ("manichaeantaw", "Manichaean_Taw"), + ("manichaeanten", "Manichaean_Ten"), + ("manichaeanteth", "Manichaean_Teth"), + ("manichaeanthamedh", "Manichaean_Thamedh"), + ("manichaeantwenty", "Manichaean_Twenty"), + ("manichaeanwaw", "Manichaean_Waw"), + ("manichaeanyodh", "Manichaean_Yodh"), + ("manichaeanzayin", "Manichaean_Zayin"), + ("meem", "Meem"), + ("mim", "Mim"), + ("nojoininggroup", "No_Joining_Group"), + ("noon", "Noon"), + ("nun", "Nun"), + ("nya", "Nya"), + ("pe", "Pe"), + ("qaf", "Qaf"), + ("qaph", "Qaph"), + ("reh", "Reh"), + ("reversedpe", "Reversed_Pe"), + ("rohingyayeh", "Rohingya_Yeh"), + ("sad", "Sad"), + ("sadhe", "Sadhe"), + ("seen", "Seen"), + ("semkath", "Semkath"), + ("shin", "Shin"), + ("straightwaw", "Straight_Waw"), + ("swashkaf", "Swash_Kaf"), + ("syriacwaw", "Syriac_Waw"), + ("tah", "Tah"), + ("taw", "Taw"), + ("tehmarbuta", "Teh_Marbuta"), + ("tehmarbutagoal", "Hamza_On_Heh_Goal"), + ("teth", "Teth"), + ("thinyeh", "Thin_Yeh"), + ("verticaltail", "Vertical_Tail"), + ("waw", "Waw"), + ("yeh", "Yeh"), + ("yehbarree", "Yeh_Barree"), + ("yehwithtail", "Yeh_With_Tail"), + ("yudh", "Yudh"), + ("yudhhe", "Yudh_He"), + ("zain", "Zain"), + ("zhain", "Zhain"), + ], + ), + ( + "Joining_Type", + &[ + ("c", "Join_Causing"), + ("d", "Dual_Joining"), + ("dualjoining", "Dual_Joining"), + ("joincausing", "Join_Causing"), + ("l", "Left_Joining"), + ("leftjoining", "Left_Joining"), + ("nonjoining", "Non_Joining"), + ("r", "Right_Joining"), + ("rightjoining", "Right_Joining"), + ("t", "Transparent"), + ("transparent", "Transparent"), + ("u", "Non_Joining"), + ], + ), + ( + "Line_Break", + &[ + ("", "Infix_Numeric"), + ("ai", "Ambiguous"), + ("al", "Alphabetic"), + ("alphabetic", "Alphabetic"), + ("ambiguous", "Ambiguous"), + ("b2", "Break_Both"), + ("ba", "Break_After"), + ("bb", "Break_Before"), + ("bk", "Mandatory_Break"), + ("breakafter", "Break_After"), + ("breakbefore", "Break_Before"), + ("breakboth", "Break_Both"), + ("breaksymbols", "Break_Symbols"), + ("carriagereturn", "Carriage_Return"), + ("cb", "Contingent_Break"), + ("cj", "Conditional_Japanese_Starter"), + ("cl", "Close_Punctuation"), + ("closeparenthesis", "Close_Parenthesis"), + ("closepunctuation", "Close_Punctuation"), + ("cm", "Combining_Mark"), + ("combiningmark", "Combining_Mark"), + ("complexcontext", "Complex_Context"), + ("conditionaljapanesestarter", "Conditional_Japanese_Starter"), + ("contingentbreak", "Contingent_Break"), + ("cp", "Close_Parenthesis"), + ("cr", "Carriage_Return"), + ("eb", "E_Base"), + ("ebase", "E_Base"), + ("em", "E_Modifier"), + ("emodifier", "E_Modifier"), + ("ex", "Exclamation"), + ("exclamation", "Exclamation"), + ("gl", "Glue"), + ("glue", "Glue"), + ("h2", "H2"), + ("h3", "H3"), + ("hebrewletter", "Hebrew_Letter"), + ("hl", "Hebrew_Letter"), + ("hy", "Hyphen"), + ("hyphen", "Hyphen"), + ("id", "Ideographic"), + ("ideographic", "Ideographic"), + ("in", "Inseparable"), + ("infixnumeric", "Infix_Numeric"), + ("inseparable", "Inseparable"), + ("inseperable", "Inseparable"), + ("jl", "JL"), + ("jt", "JT"), + ("jv", "JV"), + ("lf", "Line_Feed"), + ("linefeed", "Line_Feed"), + ("mandatorybreak", "Mandatory_Break"), + ("nextline", "Next_Line"), + ("nl", "Next_Line"), + ("nonstarter", "Nonstarter"), + ("ns", "Nonstarter"), + ("nu", "Numeric"), + ("numeric", "Numeric"), + ("op", "Open_Punctuation"), + ("openpunctuation", "Open_Punctuation"), + ("po", "Postfix_Numeric"), + ("postfixnumeric", "Postfix_Numeric"), + ("pr", "Prefix_Numeric"), + ("prefixnumeric", "Prefix_Numeric"), + ("qu", "Quotation"), + ("quotation", "Quotation"), + ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), + ("sa", "Complex_Context"), + ("sg", "Surrogate"), + ("sp", "Space"), + ("space", "Space"), + ("surrogate", "Surrogate"), + ("sy", "Break_Symbols"), + ("unknown", "Unknown"), + ("wj", "Word_Joiner"), + ("wordjoiner", "Word_Joiner"), + ("xx", "Unknown"), + ("zw", "ZWSpace"), + ("zwj", "ZWJ"), + ("zwspace", "ZWSpace"), + ], + ), + ( + "Logical_Order_Exception", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Lowercase", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Math", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "NFC_Quick_Check", + &[ + ("m", "Maybe"), + ("maybe", "Maybe"), + ("n", "No"), + ("no", "No"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "NFD_Quick_Check", + &[("n", "No"), ("no", "No"), ("y", "Yes"), ("yes", "Yes")], + ), + ( + "NFKC_Quick_Check", + &[ + ("m", "Maybe"), + ("maybe", "Maybe"), + ("n", "No"), + ("no", "No"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "NFKD_Quick_Check", + &[("n", "No"), ("no", "No"), ("y", "Yes"), ("yes", "Yes")], + ), + ( + "Noncharacter_Code_Point", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Numeric_Type", + &[ + ("de", "Decimal"), + ("decimal", "Decimal"), + ("di", "Digit"), + ("digit", "Digit"), + ("none", "None"), + ("nu", "Numeric"), + ("numeric", "Numeric"), + ], + ), + ( + "Other_Alphabetic", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_Default_Ignorable_Code_Point", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_Grapheme_Extend", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_ID_Continue", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_ID_Start", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_Lowercase", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_Math", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Other_Uppercase", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Pattern_Syntax", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Pattern_White_Space", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Prepended_Concatenation_Mark", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Quotation_Mark", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Radical", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Regional_Indicator", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Script", + &[ + ("adlam", "Adlam"), + ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), + ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), + ("arab", "Arabic"), + ("arabic", "Arabic"), + ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), + ("armn", "Armenian"), + ("avestan", "Avestan"), + ("avst", "Avestan"), + ("bali", "Balinese"), + ("balinese", "Balinese"), + ("bamu", "Bamum"), + ("bamum", "Bamum"), + ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), + ("batak", "Batak"), + ("batk", "Batak"), + ("beng", "Bengali"), + ("bengali", "Bengali"), + ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), + ("bopo", "Bopomofo"), + ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), + ("brahmi", "Brahmi"), + ("brai", "Braille"), + ("braille", "Braille"), + ("bugi", "Buginese"), + ("buginese", "Buginese"), + ("buhd", "Buhid"), + ("buhid", "Buhid"), + ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), + ("cari", "Carian"), + ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), + ("chakma", "Chakma"), + ("cham", "Cham"), + ("cher", "Cherokee"), + ("cherokee", "Cherokee"), + ("chorasmian", "Chorasmian"), + ("chrs", "Chorasmian"), + ("common", "Common"), + ("copt", "Coptic"), + ("coptic", "Coptic"), + ("cpmn", "Cypro_Minoan"), + ("cprt", "Cypriot"), + ("cuneiform", "Cuneiform"), + ("cypriot", "Cypriot"), + ("cyprominoan", "Cypro_Minoan"), + ("cyrillic", "Cyrillic"), + ("cyrl", "Cyrillic"), + ("deseret", "Deseret"), + ("deva", "Devanagari"), + ("devanagari", "Devanagari"), + ("diak", "Dives_Akuru"), + ("divesakuru", "Dives_Akuru"), + ("dogr", "Dogra"), + ("dogra", "Dogra"), + ("dsrt", "Deseret"), + ("dupl", "Duployan"), + ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), + ("elba", "Elbasan"), + ("elbasan", "Elbasan"), + ("elym", "Elymaic"), + ("elymaic", "Elymaic"), + ("ethi", "Ethiopic"), + ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), + ("georgian", "Georgian"), + ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), + ("gong", "Gunjala_Gondi"), + ("gonm", "Masaram_Gondi"), + ("goth", "Gothic"), + ("gothic", "Gothic"), + ("gran", "Grantha"), + ("grantha", "Grantha"), + ("greek", "Greek"), + ("grek", "Greek"), + ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), + ("gunjalagondi", "Gunjala_Gondi"), + ("gurmukhi", "Gurmukhi"), + ("guru", "Gurmukhi"), + ("han", "Han"), + ("hang", "Hangul"), + ("hangul", "Hangul"), + ("hani", "Han"), + ("hanifirohingya", "Hanifi_Rohingya"), + ("hano", "Hanunoo"), + ("hanunoo", "Hanunoo"), + ("hatr", "Hatran"), + ("hatran", "Hatran"), + ("hebr", "Hebrew"), + ("hebrew", "Hebrew"), + ("hira", "Hiragana"), + ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), + ("hmng", "Pahawh_Hmong"), + ("hmnp", "Nyiakeng_Puachue_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), + ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), + ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), + ("ital", "Old_Italic"), + ("java", "Javanese"), + ("javanese", "Javanese"), + ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), + ("kana", "Katakana"), + ("kannada", "Kannada"), + ("katakana", "Katakana"), + ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kawi", "Kawi"), + ("kayahli", "Kayah_Li"), + ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), + ("khitansmallscript", "Khitan_Small_Script"), + ("khmer", "Khmer"), + ("khmr", "Khmer"), + ("khoj", "Khojki"), + ("khojki", "Khojki"), + ("khudawadi", "Khudawadi"), + ("kits", "Khitan_Small_Script"), + ("knda", "Kannada"), + ("kthi", "Kaithi"), + ("lana", "Tai_Tham"), + ("lao", "Lao"), + ("laoo", "Lao"), + ("latin", "Latin"), + ("latn", "Latin"), + ("lepc", "Lepcha"), + ("lepcha", "Lepcha"), + ("limb", "Limbu"), + ("limbu", "Limbu"), + ("lina", "Linear_A"), + ("linb", "Linear_B"), + ("lineara", "Linear_A"), + ("linearb", "Linear_B"), + ("lisu", "Lisu"), + ("lyci", "Lycian"), + ("lycian", "Lycian"), + ("lydi", "Lydian"), + ("lydian", "Lydian"), + ("mahajani", "Mahajani"), + ("mahj", "Mahajani"), + ("maka", "Makasar"), + ("makasar", "Makasar"), + ("malayalam", "Malayalam"), + ("mand", "Mandaic"), + ("mandaic", "Mandaic"), + ("mani", "Manichaean"), + ("manichaean", "Manichaean"), + ("marc", "Marchen"), + ("marchen", "Marchen"), + ("masaramgondi", "Masaram_Gondi"), + ("medefaidrin", "Medefaidrin"), + ("medf", "Medefaidrin"), + ("meeteimayek", "Meetei_Mayek"), + ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), + ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), + ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), + ("miao", "Miao"), + ("mlym", "Malayalam"), + ("modi", "Modi"), + ("mong", "Mongolian"), + ("mongolian", "Mongolian"), + ("mro", "Mro"), + ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), + ("mult", "Multani"), + ("multani", "Multani"), + ("myanmar", "Myanmar"), + ("mymr", "Myanmar"), + ("nabataean", "Nabataean"), + ("nagm", "Nag_Mundari"), + ("nagmundari", "Nag_Mundari"), + ("nand", "Nandinagari"), + ("nandinagari", "Nandinagari"), + ("narb", "Old_North_Arabian"), + ("nbat", "Nabataean"), + ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), + ("nko", "Nko"), + ("nkoo", "Nko"), + ("nshu", "Nushu"), + ("nushu", "Nushu"), + ("nyiakengpuachuehmong", "Nyiakeng_Puachue_Hmong"), + ("ogam", "Ogham"), + ("ogham", "Ogham"), + ("olchiki", "Ol_Chiki"), + ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), + ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), + ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), + ("oldsogdian", "Old_Sogdian"), + ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), + ("olduyghur", "Old_Uyghur"), + ("oriya", "Oriya"), + ("orkh", "Old_Turkic"), + ("orya", "Oriya"), + ("osage", "Osage"), + ("osge", "Osage"), + ("osma", "Osmanya"), + ("osmanya", "Osmanya"), + ("ougr", "Old_Uyghur"), + ("pahawhhmong", "Pahawh_Hmong"), + ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), + ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), + ("perm", "Old_Permic"), + ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), + ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), + ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), + ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), + ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), + ("qaai", "Inherited"), + ("rejang", "Rejang"), + ("rjng", "Rejang"), + ("rohg", "Hanifi_Rohingya"), + ("runic", "Runic"), + ("runr", "Runic"), + ("samaritan", "Samaritan"), + ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), + ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), + ("sgnw", "SignWriting"), + ("sharada", "Sharada"), + ("shavian", "Shavian"), + ("shaw", "Shavian"), + ("shrd", "Sharada"), + ("sidd", "Siddham"), + ("siddham", "Siddham"), + ("signwriting", "SignWriting"), + ("sind", "Khudawadi"), + ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), + ("sogd", "Sogdian"), + ("sogdian", "Sogdian"), + ("sogo", "Old_Sogdian"), + ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), + ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), + ("sund", "Sundanese"), + ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), + ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), + ("syriac", "Syriac"), + ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), + ("tagbanwa", "Tagbanwa"), + ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), + ("taiviet", "Tai_Viet"), + ("takr", "Takri"), + ("takri", "Takri"), + ("tale", "Tai_Le"), + ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), + ("taml", "Tamil"), + ("tang", "Tangut"), + ("tangsa", "Tangsa"), + ("tangut", "Tangut"), + ("tavt", "Tai_Viet"), + ("telu", "Telugu"), + ("telugu", "Telugu"), + ("tfng", "Tifinagh"), + ("tglg", "Tagalog"), + ("thaa", "Thaana"), + ("thaana", "Thaana"), + ("thai", "Thai"), + ("tibetan", "Tibetan"), + ("tibt", "Tibetan"), + ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), + ("tirhuta", "Tirhuta"), + ("tnsa", "Tangsa"), + ("toto", "Toto"), + ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), + ("unknown", "Unknown"), + ("vai", "Vai"), + ("vaii", "Vai"), + ("vith", "Vithkuqi"), + ("vithkuqi", "Vithkuqi"), + ("wancho", "Wancho"), + ("wara", "Warang_Citi"), + ("warangciti", "Warang_Citi"), + ("wcho", "Wancho"), + ("xpeo", "Old_Persian"), + ("xsux", "Cuneiform"), + ("yezi", "Yezidi"), + ("yezidi", "Yezidi"), + ("yi", "Yi"), + ("yiii", "Yi"), + ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), + ("zinh", "Inherited"), + ("zyyy", "Common"), + ("zzzz", "Unknown"), + ], + ), + ( + "Script_Extensions", + &[ + ("adlam", "Adlam"), + ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), + ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), + ("arab", "Arabic"), + ("arabic", "Arabic"), + ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), + ("armn", "Armenian"), + ("avestan", "Avestan"), + ("avst", "Avestan"), + ("bali", "Balinese"), + ("balinese", "Balinese"), + ("bamu", "Bamum"), + ("bamum", "Bamum"), + ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), + ("batak", "Batak"), + ("batk", "Batak"), + ("beng", "Bengali"), + ("bengali", "Bengali"), + ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), + ("bopo", "Bopomofo"), + ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), + ("brahmi", "Brahmi"), + ("brai", "Braille"), + ("braille", "Braille"), + ("bugi", "Buginese"), + ("buginese", "Buginese"), + ("buhd", "Buhid"), + ("buhid", "Buhid"), + ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), + ("cari", "Carian"), + ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), + ("chakma", "Chakma"), + ("cham", "Cham"), + ("cher", "Cherokee"), + ("cherokee", "Cherokee"), + ("chorasmian", "Chorasmian"), + ("chrs", "Chorasmian"), + ("common", "Common"), + ("copt", "Coptic"), + ("coptic", "Coptic"), + ("cpmn", "Cypro_Minoan"), + ("cprt", "Cypriot"), + ("cuneiform", "Cuneiform"), + ("cypriot", "Cypriot"), + ("cyprominoan", "Cypro_Minoan"), + ("cyrillic", "Cyrillic"), + ("cyrl", "Cyrillic"), + ("deseret", "Deseret"), + ("deva", "Devanagari"), + ("devanagari", "Devanagari"), + ("diak", "Dives_Akuru"), + ("divesakuru", "Dives_Akuru"), + ("dogr", "Dogra"), + ("dogra", "Dogra"), + ("dsrt", "Deseret"), + ("dupl", "Duployan"), + ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), + ("elba", "Elbasan"), + ("elbasan", "Elbasan"), + ("elym", "Elymaic"), + ("elymaic", "Elymaic"), + ("ethi", "Ethiopic"), + ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), + ("georgian", "Georgian"), + ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), + ("gong", "Gunjala_Gondi"), + ("gonm", "Masaram_Gondi"), + ("goth", "Gothic"), + ("gothic", "Gothic"), + ("gran", "Grantha"), + ("grantha", "Grantha"), + ("greek", "Greek"), + ("grek", "Greek"), + ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), + ("gunjalagondi", "Gunjala_Gondi"), + ("gurmukhi", "Gurmukhi"), + ("guru", "Gurmukhi"), + ("han", "Han"), + ("hang", "Hangul"), + ("hangul", "Hangul"), + ("hani", "Han"), + ("hanifirohingya", "Hanifi_Rohingya"), + ("hano", "Hanunoo"), + ("hanunoo", "Hanunoo"), + ("hatr", "Hatran"), + ("hatran", "Hatran"), + ("hebr", "Hebrew"), + ("hebrew", "Hebrew"), + ("hira", "Hiragana"), + ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), + ("hmng", "Pahawh_Hmong"), + ("hmnp", "Nyiakeng_Puachue_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), + ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), + ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), + ("ital", "Old_Italic"), + ("java", "Javanese"), + ("javanese", "Javanese"), + ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), + ("kana", "Katakana"), + ("kannada", "Kannada"), + ("katakana", "Katakana"), + ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kawi", "Kawi"), + ("kayahli", "Kayah_Li"), + ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), + ("khitansmallscript", "Khitan_Small_Script"), + ("khmer", "Khmer"), + ("khmr", "Khmer"), + ("khoj", "Khojki"), + ("khojki", "Khojki"), + ("khudawadi", "Khudawadi"), + ("kits", "Khitan_Small_Script"), + ("knda", "Kannada"), + ("kthi", "Kaithi"), + ("lana", "Tai_Tham"), + ("lao", "Lao"), + ("laoo", "Lao"), + ("latin", "Latin"), + ("latn", "Latin"), + ("lepc", "Lepcha"), + ("lepcha", "Lepcha"), + ("limb", "Limbu"), + ("limbu", "Limbu"), + ("lina", "Linear_A"), + ("linb", "Linear_B"), + ("lineara", "Linear_A"), + ("linearb", "Linear_B"), + ("lisu", "Lisu"), + ("lyci", "Lycian"), + ("lycian", "Lycian"), + ("lydi", "Lydian"), + ("lydian", "Lydian"), + ("mahajani", "Mahajani"), + ("mahj", "Mahajani"), + ("maka", "Makasar"), + ("makasar", "Makasar"), + ("malayalam", "Malayalam"), + ("mand", "Mandaic"), + ("mandaic", "Mandaic"), + ("mani", "Manichaean"), + ("manichaean", "Manichaean"), + ("marc", "Marchen"), + ("marchen", "Marchen"), + ("masaramgondi", "Masaram_Gondi"), + ("medefaidrin", "Medefaidrin"), + ("medf", "Medefaidrin"), + ("meeteimayek", "Meetei_Mayek"), + ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), + ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), + ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), + ("miao", "Miao"), + ("mlym", "Malayalam"), + ("modi", "Modi"), + ("mong", "Mongolian"), + ("mongolian", "Mongolian"), + ("mro", "Mro"), + ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), + ("mult", "Multani"), + ("multani", "Multani"), + ("myanmar", "Myanmar"), + ("mymr", "Myanmar"), + ("nabataean", "Nabataean"), + ("nagm", "Nag_Mundari"), + ("nagmundari", "Nag_Mundari"), + ("nand", "Nandinagari"), + ("nandinagari", "Nandinagari"), + ("narb", "Old_North_Arabian"), + ("nbat", "Nabataean"), + ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), + ("nko", "Nko"), + ("nkoo", "Nko"), + ("nshu", "Nushu"), + ("nushu", "Nushu"), + ("nyiakengpuachuehmong", "Nyiakeng_Puachue_Hmong"), + ("ogam", "Ogham"), + ("ogham", "Ogham"), + ("olchiki", "Ol_Chiki"), + ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), + ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), + ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), + ("oldsogdian", "Old_Sogdian"), + ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), + ("olduyghur", "Old_Uyghur"), + ("oriya", "Oriya"), + ("orkh", "Old_Turkic"), + ("orya", "Oriya"), + ("osage", "Osage"), + ("osge", "Osage"), + ("osma", "Osmanya"), + ("osmanya", "Osmanya"), + ("ougr", "Old_Uyghur"), + ("pahawhhmong", "Pahawh_Hmong"), + ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), + ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), + ("perm", "Old_Permic"), + ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), + ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), + ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), + ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), + ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), + ("qaai", "Inherited"), + ("rejang", "Rejang"), + ("rjng", "Rejang"), + ("rohg", "Hanifi_Rohingya"), + ("runic", "Runic"), + ("runr", "Runic"), + ("samaritan", "Samaritan"), + ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), + ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), + ("sgnw", "SignWriting"), + ("sharada", "Sharada"), + ("shavian", "Shavian"), + ("shaw", "Shavian"), + ("shrd", "Sharada"), + ("sidd", "Siddham"), + ("siddham", "Siddham"), + ("signwriting", "SignWriting"), + ("sind", "Khudawadi"), + ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), + ("sogd", "Sogdian"), + ("sogdian", "Sogdian"), + ("sogo", "Old_Sogdian"), + ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), + ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), + ("sund", "Sundanese"), + ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), + ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), + ("syriac", "Syriac"), + ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), + ("tagbanwa", "Tagbanwa"), + ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), + ("taiviet", "Tai_Viet"), + ("takr", "Takri"), + ("takri", "Takri"), + ("tale", "Tai_Le"), + ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), + ("taml", "Tamil"), + ("tang", "Tangut"), + ("tangsa", "Tangsa"), + ("tangut", "Tangut"), + ("tavt", "Tai_Viet"), + ("telu", "Telugu"), + ("telugu", "Telugu"), + ("tfng", "Tifinagh"), + ("tglg", "Tagalog"), + ("thaa", "Thaana"), + ("thaana", "Thaana"), + ("thai", "Thai"), + ("tibetan", "Tibetan"), + ("tibt", "Tibetan"), + ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), + ("tirhuta", "Tirhuta"), + ("tnsa", "Tangsa"), + ("toto", "Toto"), + ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), + ("unknown", "Unknown"), + ("vai", "Vai"), + ("vaii", "Vai"), + ("vith", "Vithkuqi"), + ("vithkuqi", "Vithkuqi"), + ("wancho", "Wancho"), + ("wara", "Warang_Citi"), + ("warangciti", "Warang_Citi"), + ("wcho", "Wancho"), + ("xpeo", "Old_Persian"), + ("xsux", "Cuneiform"), + ("yezi", "Yezidi"), + ("yezidi", "Yezidi"), + ("yi", "Yi"), + ("yiii", "Yi"), + ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), + ("zinh", "Inherited"), + ("zyyy", "Common"), + ("zzzz", "Unknown"), + ], + ), + ( + "Sentence_Break", + &[ + ("at", "ATerm"), + ("aterm", "ATerm"), + ("cl", "Close"), + ("close", "Close"), + ("cr", "CR"), + ("ex", "Extend"), + ("extend", "Extend"), + ("fo", "Format"), + ("format", "Format"), + ("le", "OLetter"), + ("lf", "LF"), + ("lo", "Lower"), + ("lower", "Lower"), + ("nu", "Numeric"), + ("numeric", "Numeric"), + ("oletter", "OLetter"), + ("other", "Other"), + ("sc", "SContinue"), + ("scontinue", "SContinue"), + ("se", "Sep"), + ("sep", "Sep"), + ("sp", "Sp"), + ("st", "STerm"), + ("sterm", "STerm"), + ("up", "Upper"), + ("upper", "Upper"), + ("xx", "Other"), + ], + ), + ( + "Sentence_Terminal", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Soft_Dotted", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Terminal_Punctuation", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Unified_Ideograph", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Uppercase", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Variation_Selector", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Vertical_Orientation", + &[ + ("r", "Rotated"), + ("rotated", "Rotated"), + ("tr", "Transformed_Rotated"), + ("transformedrotated", "Transformed_Rotated"), + ("transformedupright", "Transformed_Upright"), + ("tu", "Transformed_Upright"), + ("u", "Upright"), + ("upright", "Upright"), + ], + ), + ( + "White_Space", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "Word_Break", + &[ + ("aletter", "ALetter"), + ("cr", "CR"), + ("doublequote", "Double_Quote"), + ("dq", "Double_Quote"), + ("eb", "E_Base"), + ("ebase", "E_Base"), + ("ebasegaz", "E_Base_GAZ"), + ("ebg", "E_Base_GAZ"), + ("em", "E_Modifier"), + ("emodifier", "E_Modifier"), + ("ex", "ExtendNumLet"), + ("extend", "Extend"), + ("extendnumlet", "ExtendNumLet"), + ("fo", "Format"), + ("format", "Format"), + ("gaz", "Glue_After_Zwj"), + ("glueafterzwj", "Glue_After_Zwj"), + ("hebrewletter", "Hebrew_Letter"), + ("hl", "Hebrew_Letter"), + ("ka", "Katakana"), + ("katakana", "Katakana"), + ("le", "ALetter"), + ("lf", "LF"), + ("mb", "MidNumLet"), + ("midletter", "MidLetter"), + ("midnum", "MidNum"), + ("midnumlet", "MidNumLet"), + ("ml", "MidLetter"), + ("mn", "MidNum"), + ("newline", "Newline"), + ("nl", "Newline"), + ("nu", "Numeric"), + ("numeric", "Numeric"), + ("other", "Other"), + ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), + ("singlequote", "Single_Quote"), + ("sq", "Single_Quote"), + ("wsegspace", "WSegSpace"), + ("xx", "Other"), + ("zwj", "ZWJ"), + ], + ), + ( + "XID_Continue", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), + ( + "XID_Start", + &[ + ("f", "No"), + ("false", "No"), + ("n", "No"), + ("no", "No"), + ("t", "Yes"), + ("true", "Yes"), + ("y", "Yes"), + ("yes", "Yes"), + ], + ), +]; diff --git a/bash-5.1/vendor/unic-langid-impl/tests/canonicalize_test.rs b/bash-5.1/vendor/unic-langid-impl/tests/canonicalize_test.rs new file mode 100644 index 0000000..b019582 --- /dev/null +++ b/bash-5.1/vendor/unic-langid-impl/tests/canonicalize_test.rs @@ -0,0 +1,13 @@ +use unic_langid_impl::canonicalize; + +fn assert_canonicalize(input: &str, output: &str) { + assert_eq!(&canonicalize(input).unwrap(), output); +} + +#[test] +fn test_canonicalize() { + assert_canonicalize("Pl", "pl"); + assert_canonicalize("eN-uS", "en-US"); + assert_canonicalize("ZH_hans_hK", "zh-Hans-HK"); + assert_canonicalize("en-scouse-fonipa", "en-fonipa-scouse"); +} diff --git a/bash-5.1/vendor/unic-langid-impl/tests/fixtures.rs b/bash-5.1/vendor/unic-langid-impl/tests/fixtures.rs new file mode 100644 index 0000000..27cd29b --- /dev/null +++ b/bash-5.1/vendor/unic-langid-impl/tests/fixtures.rs @@ -0,0 +1,75 @@ +use std::convert::TryInto; +use std::error::Error; +use std::fs::File; +use std::path::Path; + +use unic_langid_impl::LanguageIdentifier; + +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +struct LangIdTestInputData { + string: String, +} + +#[derive(Serialize, Deserialize, Debug)] +struct LangIdTestOutputObject { + language: Option<String>, + script: Option<String>, + region: Option<String>, + #[serde(default)] + variants: Vec<String>, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(untagged)] +enum LangIdTestOutput { + String(String), + Object(LangIdTestOutputObject), +} + +#[derive(Serialize, Deserialize)] +struct LangIdTestSet { + input: LangIdTestInputData, + output: LangIdTestOutput, +} + +fn read_langid_testsets<P: AsRef<Path>>(path: P) -> Result<Vec<LangIdTestSet>, Box<dyn Error>> { + let file = File::open(path)?; + let sets = serde_json::from_reader(file)?; + Ok(sets) +} + +fn test_langid_fixtures(path: &str) { + let tests = read_langid_testsets(path).unwrap(); + + for test in tests { + let s = test.input.string; + + let langid: LanguageIdentifier = s.parse().expect("Parsing failed."); + + match test.output { + LangIdTestOutput::Object(o) => { + let expected = LanguageIdentifier::from_parts( + o.language.try_into().unwrap(), + o.script.as_ref().map(|s| s.parse().unwrap()), + o.region.as_ref().map(|r| r.parse().unwrap()), + o.variants + .iter() + .map(|s| s.parse().unwrap()) + .collect::<Vec<_>>() + .as_ref(), + ); + assert_eq!(langid, expected); + } + LangIdTestOutput::String(s) => { + assert_eq!(langid.to_string(), s); + } + } + } +} + +#[test] +fn parse() { + test_langid_fixtures("./tests/fixtures/parsing.json"); +} diff --git a/bash-5.1/vendor/unic-langid-impl/tests/language_identifier_test.rs b/bash-5.1/vendor/unic-langid-impl/tests/language_identifier_test.rs new file mode 100644 index 0000000..79b81fb --- /dev/null +++ b/bash-5.1/vendor/unic-langid-impl/tests/language_identifier_test.rs @@ -0,0 +1,192 @@ +use unic_langid_impl::parser::parse_language_identifier; +use unic_langid_impl::subtags; +use unic_langid_impl::CharacterDirection; +use unic_langid_impl::LanguageIdentifier; + +fn assert_language_identifier( + loc: &LanguageIdentifier, + language: Option<&str>, + script: Option<&str>, + region: Option<&str>, + variants: Option<&[&str]>, +) { + assert_eq!( + loc.language, + language.map_or(subtags::Language::default(), |l| { + subtags::Language::from_bytes(l.as_bytes()).unwrap() + }) + ); + assert_eq!(loc.script, script.map(|s| s.parse().unwrap())); + assert_eq!(loc.region, region.map(|r| r.parse().unwrap())); + let v = variants + .unwrap_or(&[]) + .iter() + .map(|v| -> subtags::Variant { v.parse().unwrap() }) + .collect::<Vec<_>>(); + assert_eq!( + loc.variants().collect::<Vec<_>>(), + v.iter().collect::<Vec<_>>(), + ); +} + +fn assert_parsed_language_identifier( + input: &str, + language: Option<&str>, + script: Option<&str>, + region: Option<&str>, + variants: Option<&[&str]>, +) { + let langid = parse_language_identifier(input.as_bytes()).unwrap(); + assert_language_identifier(&langid, language, script, region, variants); +} + +#[test] +fn test_language_identifier_parser() { + assert_parsed_language_identifier("pl", Some("pl"), None, None, None); + assert_parsed_language_identifier("und", None, None, None, None); + assert_parsed_language_identifier("en-US", Some("en"), None, Some("US"), None); + assert_parsed_language_identifier("en-Latn-US", Some("en"), Some("Latn"), Some("US"), None); + assert_parsed_language_identifier("sl-nedis", Some("sl"), None, None, Some(&["nedis"])); +} + +#[test] +fn test_language_casing() { + assert_parsed_language_identifier("Pl", Some("pl"), None, None, None); + assert_parsed_language_identifier("En-uS", Some("en"), None, Some("US"), None); + assert_parsed_language_identifier("eN-lAtN-uS", Some("en"), Some("Latn"), Some("US"), None); + assert_parsed_language_identifier("ZH_cyrl_hN", Some("zh"), Some("Cyrl"), Some("HN"), None); +} + +#[test] +fn test_serialize_langid() { + let langid: LanguageIdentifier = "en-Latn-US".parse().unwrap(); + assert_eq!(&langid.to_string(), "en-Latn-US"); +} + +#[test] +fn test_sorted_variants() { + let langid: LanguageIdentifier = "en-nedis-macos".parse().unwrap(); + assert_eq!(&langid.to_string(), "en-macos-nedis"); + + let langid = LanguageIdentifier::from_parts( + "en".parse().unwrap(), + None, + None, + &["nedis".parse().unwrap(), "macos".parse().unwrap()], + ); + assert_eq!(&langid.to_string(), "en-macos-nedis"); +} + +#[test] +fn test_from_parts_unchecked() { + let langid: LanguageIdentifier = "en-nedis-macos".parse().unwrap(); + let (lang, script, region, variants) = langid.into_parts(); + let langid = LanguageIdentifier::from_raw_parts_unchecked( + lang, + script, + region, + Some(variants.into_boxed_slice()), + ); + assert_eq!(&langid.to_string(), "en-macos-nedis"); +} + +#[test] +fn test_matches() { + let langid_en: LanguageIdentifier = "en".parse().unwrap(); + let langid_en_us: LanguageIdentifier = "en-US".parse().unwrap(); + let langid_en_us2: LanguageIdentifier = "en-US".parse().unwrap(); + let langid_pl: LanguageIdentifier = "pl".parse().unwrap(); + assert_eq!(langid_en.matches(&langid_en_us, false, false), false); + assert_eq!(langid_en_us.matches(&langid_en_us2, false, false), true); + assert_eq!(langid_en.matches(&langid_pl, false, false), false); + assert_eq!(langid_en.matches(&langid_en_us, true, false), true); +} + +#[test] +fn test_set_fields() { + let mut langid = LanguageIdentifier::default(); + assert_eq!(&langid.to_string(), "und"); + + langid.language = "pl".parse().expect("Setting language failed"); + assert_eq!(&langid.to_string(), "pl"); + + langid.language = "de".parse().expect("Setting language failed"); + assert_eq!(&langid.to_string(), "de"); + langid.region = Some("AT".parse().expect("Setting region failed")); + assert_eq!(&langid.to_string(), "de-AT"); + langid.script = Some("Latn".parse().expect("Setting script failed")); + assert_eq!(&langid.to_string(), "de-Latn-AT"); + langid.set_variants(&["macos".parse().expect("Setting variants failed")]); + assert_eq!(&langid.to_string(), "de-Latn-AT-macos"); + + assert_eq!(langid.has_variant("macos".parse().unwrap()), true); + assert_eq!(langid.has_variant("windows".parse().unwrap()), false); + + langid.language.clear(); + assert_eq!(&langid.to_string(), "und-Latn-AT-macos"); + langid.region = None; + assert_eq!(&langid.to_string(), "und-Latn-macos"); + langid.script = None; + assert_eq!(&langid.to_string(), "und-macos"); + langid.clear_variants(); + assert_eq!(&langid.to_string(), "und"); + + assert_eq!(langid.has_variant("macos".parse().unwrap()), false); +} + +#[test] +fn test_matches_as_range() { + let langid: LanguageIdentifier = "en-US".parse().unwrap(); + let langid2: LanguageIdentifier = "en-US-windows".parse().unwrap(); + assert_eq!(langid.matches(&langid2, false, false), false); + assert_eq!(langid.matches(&langid2, true, false), true); + assert_eq!(langid.matches(&langid2, false, true), false); + assert_eq!(langid.matches(&langid2, true, true), true); +} + +#[test] +fn test_character_direction() { + let langid: LanguageIdentifier = "en-US".parse().unwrap(); + let langid2: LanguageIdentifier = "ar-AF".parse().unwrap(); + assert_eq!(langid.character_direction(), CharacterDirection::LTR); + assert_eq!(langid2.character_direction(), CharacterDirection::RTL); +} + +#[test] +fn test_langid_ord() { + let input = &[ + "en-US-macos-zarab", + "en-US-macos-nedis", + "en-US-macos", + "en-GB", + "en", + "en-US", + "ar", + "fr", + "de", + ]; + + let mut langids = input + .iter() + .map(|l| -> LanguageIdentifier { l.parse().unwrap() }) + .collect::<Vec<_>>(); + + langids.sort(); + + let result = langids.iter().map(|l| l.to_string()).collect::<Vec<_>>(); + + assert_eq!( + &result, + &[ + "ar", + "de", + "en", + "en-GB", + "en-US", + "en-US-macos", + "en-US-macos-nedis", + "en-US-macos-zarab", + "fr" + ] + ); +} diff --git a/bash-5.1/vendor/unic-langid-impl/tests/likelysubtags.rs b/bash-5.1/vendor/unic-langid-impl/tests/likelysubtags.rs new file mode 100644 index 0000000..a378274 --- /dev/null +++ b/bash-5.1/vendor/unic-langid-impl/tests/likelysubtags.rs @@ -0,0 +1,113 @@ +use unic_langid_impl::likelysubtags::{maximize, minimize, CLDR_VERSION}; +use unic_langid_impl::subtags; + +static STRINGS: &[(&str, Option<&str>)] = &[ + ("en-US", Some("en-Latn-US")), + ("en-GB", Some("en-Latn-GB")), + ("es-AR", Some("es-Latn-AR")), + ("it", Some("it-Latn-IT")), + ("zh-Hans-CN", None), + ("de-AT", Some("de-Latn-AT")), + ("pl", Some("pl-Latn-PL")), + ("fr-FR", Some("fr-Latn-FR")), + ("de-AT", Some("de-Latn-AT")), + ("sr-Cyrl-SR", None), + ("nb-NO", Some("nb-Latn-NO")), + ("fr-FR", Some("fr-Latn-FR")), + ("mk", Some("mk-Cyrl-MK")), + ("uk", Some("uk-Cyrl-UA")), + ("und-PL", Some("pl-Latn-PL")), + ("und-Latn-AM", Some("ku-Latn-AM")), + ("ug-Cyrl", Some("ug-Cyrl-KZ")), + ("sr-ME", Some("sr-Latn-ME")), + ("mn-Mong", Some("mn-Mong-CN")), + ("lif-Limb", Some("lif-Limb-IN")), + ("gan", Some("gan-Hans-CN")), + ("zh-Hant", Some("zh-Hant-TW")), + ("yue-Hans", Some("yue-Hans-CN")), + ("unr", Some("unr-Beng-IN")), + ("unr-Deva", Some("unr-Deva-NP")), + ("und-Thai-CN", Some("lcp-Thai-CN")), + ("ug-Cyrl", Some("ug-Cyrl-KZ")), + ("en-Latn-DE", None), + ("pl-FR", Some("pl-Latn-FR")), + ("de-CH", Some("de-Latn-CH")), + ("tuq", Some("tuq-Latn")), + ("sr-ME", Some("sr-Latn-ME")), + ("ng", Some("ng-Latn-NA")), + ("klx", Some("klx-Latn")), + ("kk-Arab", Some("kk-Arab-CN")), + ("en-Cyrl", Some("en-Cyrl-US")), + ("und-Cyrl-UK", Some("ru-Cyrl-UK")), + ("und-Arab", Some("ar-Arab-EG")), + ("und-Arab-FO", Some("ar-Arab-FO")), + ("zh-TW", Some("zh-Hant-TW")), +]; + +fn extract_input( + s: &str, +) -> ( + subtags::Language, + Option<subtags::Script>, + Option<subtags::Region>, +) { + let chunks: Vec<&str> = s.split("-").collect(); + let lang: subtags::Language = chunks[0].parse().unwrap(); + let (script, region) = if let Some(s) = chunks.get(1) { + if let Ok(script) = s.parse() { + let region = chunks.get(2).map(|r| r.parse().unwrap()); + (Some(script), region) + } else { + let region = s.parse().unwrap(); + (None, Some(region)) + } + } else { + (None, None) + }; + (lang, script, region) +} + +fn extract_output( + s: Option<&str>, +) -> Option<( + subtags::Language, + Option<subtags::Script>, + Option<subtags::Region>, +)> { + s.map(|s| { + let chunks: Vec<&str> = s.split("-").collect(); + ( + chunks[0].parse().unwrap(), + chunks.get(1).map(|s| s.parse().unwrap()), + chunks.get(2).map(|s| s.parse().unwrap()), + ) + }) +} + +#[test] +fn maximize_test() { + for i in STRINGS { + let chunks = extract_input(i.0); + let result = maximize(chunks.0, chunks.1, chunks.2); + assert_eq!(extract_output(i.1), result); + } +} + +#[test] +fn version_works() { + assert_eq!(CLDR_VERSION, "36"); +} + +#[test] +fn minimize_test() { + let lang = "zh".parse().unwrap(); + let script = "Hant".parse().unwrap(); + let result = minimize(lang, Some(script), None); + assert_eq!(result, Some(extract_input("zh-TW"))); + + let lang = "en".parse().unwrap(); + let script = "Latn".parse().unwrap(); + let region = "US".parse().unwrap(); + let result = minimize(lang, Some(script), Some(region)); + assert_eq!(result, Some(extract_input("en"))); +} diff --git a/bash-5.1/vendor/unicode-ident/.cargo-checksum.json b/bash-5.1/vendor/unicode-ident/.cargo-checksum.json index 71995a9..1fcb95c 100644 --- a/bash-5.1/vendor/unicode-ident/.cargo-checksum.json +++ b/bash-5.1/vendor/unicode-ident/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"9f1a0934313101d94964bdcf532bb746fb5d58c696d0dc37e9cf344500a13552","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","LICENSE-UNICODE":"68f5b9f5ea36881a0942ba02f558e9e1faf76cc09cb165ad801744c61b738844","README.md":"2dca6b25b21944fa91134d6de872e74836074afab663924b06d33d168cc59e23","benches/xid.rs":"a61f61ecc7d5124c759cdeb55ab74470ab69f2f3ca37613da65f16e0e5e33487","src/lib.rs":"d0030259a628125669ad6c02d3eb791526e6d6ae35d8a858a87f90245162666c","src/tables.rs":"887457a7ce0d2fff750b40134de684e86d3999e5d191544f31ee45936b7bcb72","tests/compare.rs":"89c4dc4f745064a9f734667b1d960596a10b8cb019a8ed1c5b9512678a866ad5","tests/fst/mod.rs":"69a3aaf59acd8bca962ecc6234be56be8c0934ab79b253162f10eb881523901f","tests/fst/xid_continue.fst":"6e079a81175e445461dc330f61294c9f24bdb1681b7a591999fbb4547766ea99","tests/fst/xid_start.fst":"382fc736b472d09052a53c89cc2060bd839792350c6d22638b91e9123bf14540","tests/roaring/mod.rs":"784f65a48477fab7549620c7843c7ad6da533f69a18abca1172f6acb95045e53","tests/static_size.rs":"3974f6948c06d60b63738ddf5688478144718da87ccfdc4af6918d76a0bd9f06","tests/trie/mod.rs":"d4acbb716bcbaf80660039797f45e138ed8bbd66749fa3b19b1a971574679cc9","tests/trie/trie.rs":"6780e33f74f86131aa32f321bc3c77c4d9b526b708e82db64b198dce4c86429b"},"package":"c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf"} \ No newline at end of file +{"files":{"Cargo.toml":"4589e7f695ce2ae3c0dbb7a79647d044b8f2ef71183bf478fe01922966c54556","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","LICENSE-UNICODE":"68f5b9f5ea36881a0942ba02f558e9e1faf76cc09cb165ad801744c61b738844","README.md":"3dc1793fcaf87c77c5ed467c4a76cb696883f2f4329c011a869fbd34c4404382","benches/xid.rs":"a61f61ecc7d5124c759cdeb55ab74470ab69f2f3ca37613da65f16e0e5e33487","src/lib.rs":"d0030259a628125669ad6c02d3eb791526e6d6ae35d8a858a87f90245162666c","src/tables.rs":"4a84cc7a1a391abebe5672db993c519b9f8fe462690d7e5a8bdd43be8481c10b","tests/compare.rs":"89c4dc4f745064a9f734667b1d960596a10b8cb019a8ed1c5b9512678a866ad5","tests/fst/mod.rs":"69a3aaf59acd8bca962ecc6234be56be8c0934ab79b253162f10eb881523901f","tests/fst/xid_continue.fst":"0624500413ac318fee8424eecdad70397f911e3beae52231bfca295bb1bb9e04","tests/fst/xid_start.fst":"cc36f4f1149a4004ea7e2075cfb54756328b571946fda526be508cf5ed53dbdb","tests/roaring/mod.rs":"784f65a48477fab7549620c7843c7ad6da533f69a18abca1172f6acb95045e53","tests/static_size.rs":"6686edc08a6718cb4be03916b87a2594a2d2f2c779dbac6372fd27d5d7f7d8b6","tests/trie/mod.rs":"d4acbb716bcbaf80660039797f45e138ed8bbd66749fa3b19b1a971574679cc9","tests/trie/trie.rs":"dbd7de5fe601159643a4c6febed06793f812e8d71010b0ec78f2557353a976b2"},"package":"6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"} \ No newline at end of file diff --git a/bash-5.1/vendor/unicode-ident/Cargo.toml b/bash-5.1/vendor/unicode-ident/Cargo.toml index d946cc8..03e1871 100644 --- a/bash-5.1/vendor/unicode-ident/Cargo.toml +++ b/bash-5.1/vendor/unicode-ident/Cargo.toml @@ -13,12 +13,15 @@ edition = "2018" rust-version = "1.31" name = "unicode-ident" -version = "1.0.3" +version = "1.0.5" authors = ["David Tolnay <dtolnay@gmail.com>"] description = "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31" documentation = "https://docs.rs/unicode-ident" readme = "README.md" -keywords = ["unicode"] +keywords = [ + "unicode", + "xid", +] categories = [ "development-tools::procedural-macro-helpers", "no-std", @@ -34,7 +37,7 @@ name = "xid" harness = false [dev-dependencies.criterion] -version = "0.3" +version = "0.4" default-features = false [dev-dependencies.fst] @@ -45,11 +48,11 @@ version = "0.8" features = ["small_rng"] [dev-dependencies.roaring] -version = "0.9" +version = "0.10" [dev-dependencies.ucd-trie] version = "0.1" default-features = false [dev-dependencies.unicode-xid] -version = "0.2" +version = "0.2.4" diff --git a/bash-5.1/vendor/unicode-ident/README.md b/bash-5.1/vendor/unicode-ident/README.md index 5a63c61..6c590b0 100644 --- a/bash-5.1/vendor/unicode-ident/README.md +++ b/bash-5.1/vendor/unicode-ident/README.md @@ -41,10 +41,10 @@ different ratios of ASCII to non-ASCII codepoints in the input data. | | static storage | 0% nonascii | 1% | 10% | 100% nonascii | |---|---|---|---|---|---| -| **`unicode-ident`** | 9.75 K | 0.96 ns | 0.95 ns | 1.09 ns | 1.55 ns | -| **`unicode-xid`** | 11.34 K | 1.88 ns | 2.14 ns | 3.48 ns | 15.63 ns | -| **`ucd-trie`** | 9.95 K | 1.29 ns | 1.28 ns | 1.36 ns | 2.15 ns | -| **`fst`** | 133 K | 55.1 ns | 54.9 ns | 53.2 ns | 28.5 ns | +| **`unicode-ident`** | 10.0 K | 0.96 ns | 0.95 ns | 1.09 ns | 1.55 ns | +| **`unicode-xid`** | 11.5 K | 1.88 ns | 2.14 ns | 3.48 ns | 15.63 ns | +| **`ucd-trie`** | 10.2 K | 1.29 ns | 1.28 ns | 1.36 ns | 2.15 ns | +| **`fst`** | 138 K | 55.1 ns | 54.9 ns | 53.2 ns | 28.5 ns | | **`roaring`** | 66.1 K | 2.78 ns | 3.09 ns | 3.37 ns | 4.70 ns | Source code for the benchmark is provided in the *bench* directory of this repo diff --git a/bash-5.1/vendor/unicode-ident/src/tables.rs b/bash-5.1/vendor/unicode-ident/src/tables.rs index a697636..380c798 100644 --- a/bash-5.1/vendor/unicode-ident/src/tables.rs +++ b/bash-5.1/vendor/unicode-ident/src/tables.rs @@ -28,7 +28,7 @@ pub(crate) static ASCII_CONTINUE: Align64<[bool; 128]> = Align64([ pub(crate) const CHUNK: usize = 64; -pub(crate) static TRIE_START: Align8<[u8; 394]> = Align8([ +pub(crate) static TRIE_START: Align8<[u8; 402]> = Align8([ 0x04, 0x0B, 0x0F, 0x13, 0x17, 0x1B, 0x1F, 0x23, 0x27, 0x2D, 0x31, 0x34, 0x38, 0x3C, 0x40, 0x02, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x00, 0x4D, 0x00, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, @@ -39,21 +39,22 @@ pub(crate) static TRIE_START: Align8<[u8; 394]> = Align8([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x60, 0x64, 0x66, 0x6A, 0x6E, 0x72, 0x28, 0x76, 0x78, 0x7C, 0x80, 0x84, 0x88, 0x8C, 0x90, 0x94, 0x98, 0x9E, 0xA2, 0x05, 0x2B, 0xA6, 0x00, 0x00, 0x00, 0x00, 0x99, 0x05, 0x05, 0xA8, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x05, 0xAB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x05, 0xAE, 0x00, 0xB2, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x32, 0x05, 0x05, 0xB6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9C, 0x43, 0xB8, 0x00, 0x00, 0x00, 0x00, 0xBB, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC4, 0xC6, 0x00, 0x00, 0x00, 0xB9, - 0xBC, 0xCF, 0x00, 0xBF, 0xD3, 0x00, 0x00, 0xD7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x05, 0xAE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0xB1, 0x00, 0xB5, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x32, 0x05, 0x05, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9C, 0x43, 0xBB, 0x00, 0x00, 0x00, 0x00, 0xBE, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC8, 0x00, 0x00, 0x00, 0xAF, + 0xCE, 0xD2, 0xD6, 0xBC, 0xDA, 0x00, 0x00, 0xDE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0xD9, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x52, 0xDC, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xDF, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0xDA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xE1, 0x00, 0x00, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xDD, + 0x05, 0x05, 0x05, 0xE0, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x52, 0xE3, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xE6, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xE9, 0x00, 0x00, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xE4, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0xE7, ]); pub(crate) static TRIE_CONTINUE: Align8<[u8; 1793]> = Align8([ @@ -66,23 +67,23 @@ pub(crate) static TRIE_CONTINUE: Align8<[u8; 1793]> = Align8([ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x62, 0x64, 0x68, 0x6C, 0x70, 0x74, 0x28, 0x76, 0x7A, 0x7E, 0x82, 0x86, 0x8A, 0x8E, 0x92, 0x96, 0x9B, 0xA0, 0xA4, - 0x05, 0x2B, 0xA6, 0x00, 0x00, 0x00, 0x00, 0x99, 0x05, 0x05, 0xA8, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x05, 0xAB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x05, 0xB0, 0x00, 0xB4, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x32, 0x05, 0x05, 0xB6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9C, 0x43, 0xB8, 0x00, 0x00, 0x00, 0x00, 0xBE, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA9, 0xAC, 0xC1, 0xC4, 0xC8, 0x00, 0xCA, 0x00, 0xB9, - 0xCD, 0xD1, 0x00, 0xBF, 0xD5, 0x00, 0x00, 0xD7, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0x00, + 0x05, 0x2B, 0xA6, 0x00, 0x00, 0x00, 0x00, 0x99, 0x05, 0x05, 0xAB, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x05, 0xAE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0xB3, 0x00, 0xB7, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x32, 0x05, 0x05, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9C, 0x43, 0xBB, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA9, 0xAC, 0xC4, 0xC6, 0xCA, 0x00, 0xCC, 0x00, 0xAF, + 0xD0, 0xD4, 0xD8, 0xBC, 0xDC, 0x00, 0x00, 0xDE, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x00, 0x00, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0xD9, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x52, 0xDC, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xDF, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0xDA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xE1, 0x00, 0x00, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xDD, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x05, 0x05, 0xE0, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x52, 0xE3, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xE6, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xE9, 0x00, 0x00, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0xE4, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -169,10 +170,10 @@ pub(crate) static TRIE_CONTINUE: Align8<[u8; 1793]> = Align8([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xCB, + 0xC2, ]); -pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ +pub(crate) static LEAF: Align64<[u8; 7520]> = Align64([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -240,7 +241,7 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xF0, 0xDF, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0x27, 0x00, 0x40, 0x70, 0x80, 0x03, 0x00, 0x00, 0xFC, 0xE0, 0xFF, 0x7F, 0xFC, 0xFF, 0xFF, 0xFB, 0x2F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xDF, 0xFD, 0xFF, 0xFF, 0xFD, 0xFF, 0xF3, 0xDF, 0x3D, 0x60, 0x27, 0xCF, 0xFF, 0x00, 0x00, - 0xEF, 0xDF, 0xFD, 0xFF, 0xFF, 0xFD, 0xEF, 0xF3, 0xDF, 0x3D, 0x60, 0x60, 0xCF, 0xFF, 0x06, 0x00, + 0xEF, 0xDF, 0xFD, 0xFF, 0xFF, 0xFD, 0xEF, 0xF3, 0xDF, 0x3D, 0x60, 0x60, 0xCF, 0xFF, 0x0E, 0x00, 0xFF, 0xDF, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0x7D, 0xF0, 0x80, 0xCF, 0xFF, 0x00, 0xFC, 0xEE, 0xFF, 0x7F, 0xFC, 0xFF, 0xFF, 0xFB, 0x2F, 0x7F, 0x84, 0x5F, 0xFF, 0xC0, 0xFF, 0x0C, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x05, 0x00, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -248,7 +249,7 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0x7F, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, - 0xD6, 0xF7, 0xFF, 0xFF, 0xAF, 0xFF, 0xFF, 0x3F, 0x5F, 0x3F, 0xFF, 0xF3, 0x00, 0x00, 0x00, 0x00, + 0xD6, 0xF7, 0xFF, 0xFF, 0xAF, 0xFF, 0xFF, 0x3F, 0x5F, 0x7F, 0xFF, 0xF3, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xFF, 0x03, 0xA0, 0xC2, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0x1F, 0xFE, 0xFF, 0xDF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0x1F, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x80, 0x00, 0x00, 0x3F, 0x3C, 0x62, 0xC0, 0xE1, 0xFF, @@ -309,7 +310,7 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0x00, 0x00, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0xF0, 0x00, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00, 0x27, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -339,7 +340,7 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xFF, 0xFF, 0x00, 0x0C, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, @@ -434,7 +435,7 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0xFF, 0xFF, 0x1F, 0x80, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1B, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1B, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0x1F, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7F, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, @@ -445,11 +446,11 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x04, 0x00, 0xFF, 0xFF, 0xFF, 0x01, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x4F, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xDE, 0xFF, 0x17, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0x0F, 0x00, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xBD, 0xFF, 0xBF, 0xFF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x9F, 0xF9, 0xFF, 0xFF, 0xFD, 0xED, 0x23, 0x00, 0x00, 0x01, 0xE0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xBD, 0xFF, 0xBF, 0xFF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0x03, 0xEF, 0x9F, 0xF9, 0xFF, 0xFF, 0xFD, 0xED, 0xFB, 0x9F, 0x39, 0x81, 0xE0, 0xCF, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -499,28 +500,34 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0x7F, 0xFB, 0x01, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x07, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xF4, 0xFF, 0xFD, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7F, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xC7, 0x07, 0x00, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xE3, 0x07, 0xF8, 0xE7, 0x0F, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0x7F, 0xE0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xE0, @@ -545,26 +552,24 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x6F, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0x1F, 0xFF, 0x01, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x80, 0x3F, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0x1F, 0xFF, 0x01, 0xFF, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x6F, 0xFF, 0x7F, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0x64, 0xDE, 0xFF, 0xEB, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBF, 0xE7, 0xDF, 0xDF, 0xFF, 0xFF, 0xFF, 0x7B, 0x5F, 0xFC, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, @@ -581,10 +586,12 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0x10, 0x00, 0x00, 0xF8, 0xFE, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, - 0x7F, 0xFF, 0xFF, 0xF9, 0xDB, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x80, 0x3F, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x7F, 0xFF, 0xFF, 0xF9, 0xDB, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, + 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xFF, 0x3F, 0xFF, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -595,6 +602,14 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -617,12 +632,14 @@ pub(crate) static LEAF: Align64<[u8; 7264]> = Align64([ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, diff --git a/bash-5.1/vendor/unicode-ident/tests/fst/xid_continue.fst b/bash-5.1/vendor/unicode-ident/tests/fst/xid_continue.fst index 5359051cb82edee8fd3faa8cfad6c1663f513ec0..05e7b1aa2ff308b57fb409c70c521b4575cba311 100644 GIT binary patch delta 2238 zcmc&$drVVj6u;l46cF0pftFzky_6P8Wl$cX0u~C$8=)<wB5!R$rzo(=Dh><&VT}7@ zT+cET#-khPgpC#N78l17+-6+(V{^+!W^{|qjN8-+#6Ng@cgtfj84;F9Jm<@~-#t0! z{LVSwxnJ&RH>dw|jxCqOvBz{Sc>$qMp-1%vMR?NJBo#O)WCHXZy-j99o-NGTbFFRf zwRd!OSsCX254wB6ACWk5o<gVTqM+`4i`{%!U^lM?XL#~9ba?AG-WMGe+s$&xvKW>% zfnFABStPdp<=HA-UjHnuH0WG#O2~uI;c!dj%_xUu^Oo3{dvWUcesy{BaEjf0F}*h{ zJI8Jg(em^XLruXLSy)_hqU`5AZ<-?a-FvmKN?V=tT2!6geD@ghWNvn5dJ6pMQ0R)N zqt%Tciq>Hm#_9)bAN7HHL;>QH?J%~U2Upv5&Y@vSBAh}^bZf`UE^vL62ZKFj9Cbpx z3dT0eAo0A$Y3sHa7|2vX*d-SUlgK0`??_=%)6z3Cv$A*Q<Z86KJUx?d*j2E*u&B7C z6qHGc0>(j$1H_IG3<s9dA76OlMd9g$tzefSU!SMbYH}0jaWvLo7~o1k`mP_0aXnmF z*O=J2?J79l=?!hITVO~oM(Jz{IXIC4{?2W5+TffEMR<e8O$g&YWgvcsfK!=5_~DaY zI5e6;e|asGfDWM;y0nR4GlaWUR+x->7BB*uJW}A>5djKdC)$^k$^scCXg=G2g*;fX zY3T*joMxOD1Wou9MR1_yU^tK?g|zZ!k{3mAxr$(UP@oK~M^tVL9%9lT?DbL@`sOnv zqmT)`4fY!<xbiR`YLpSs80`U9lza$7UdYH6RE-lR3Z>HWM;o0ef)B%^3V7-7@6R;2 z!>{W}M<ZAw6ciFcy-`4G#?NvseAlntwC-Zw0scXv*ehSC_6ZS1iE2fRuZZ*xXqY%7 z>z92cYnWKz8u`+0bx-4__E*TTIi<sTFw!BjH!peKj<#+M$&TS|Ur;2+-%4;-OOj%D z+)I6&j%U?px8=w+7G0?Rm|?b{s;IVPq%^L)eeVg=#mdJ0^nr$nAFF(-XKN21A>KG{ zo_X}wpMTt?FHNQ*zr74&G*viit#pVb+UMAi`(a?6ot~V&jYFr<Z}CLSL4D_S?t&qx zclJS8)CL%;yGjuW&?WR;v}(HCj}YI*QsRo(6^~&Ho98PzPAi4A%)>te^?@^X-*u%Z z{|RDuU!{x1QT+>Ci~WCL8LZg<HO@@?oSQ#AH3|N^Mf8nd22o2n5A6Y^v+b#|*FfGW zKWM&XhMrylyjAT3cYZ$!swfwnm|?Ha0orOPLx3J?4%sk-VMjgD>X#A!fA&vDhH<Af y$MptE#KV<R_PZXttRv7A3i!z_+PAfp?}Q_abjF6Rv%e?~@)5D=u{5juP5uu_o<h|C delta 1919 zcmZ3tgXR4amJI<4n}ZaVGxGmO1_E0qE3)q2d|WAwX|kRw-)39YR7Roy|EJHGIcxTu zx%1{P`2T<5qQy%lD>5ofPFWr~QNVa}g8GuM`nwhR{C6v80lkEHMdyi!O1+Y)l)qb{ zp@h|rdYV{`)hetu0sW61E>yuTj!#rYeWs?H&TG9>hV{lbO+YFqm|I&tvvIUv=a}en z%I$8&O3zh3zW#SBbb@$8mBRBQ-$_JA#?>WUOsYuL&v=xzJlC(lyV#)YZpDMmGwVZS zSvGE1vwE_jlh)+#t5;1vJvVr=LOTni-bBX6%}eG<uutB<G>g%0a-pv3<e+7NlMi}3 zYFb!YS=-p!{kQ+`;OON1-^JC<-NVz%+sD_>KOivZe{e`>Sa?KaRCLT_sbr_g$IbXB z@9K-+ym$FOVP=614Vwe^PUo1s@M_%Th3_sh3FuE`bl=>6Tu)%~0x{W1BFd8mt_HBD zr=_L@1qMuR<Z+uk?*{+m37&Ea$||bJX%Wm;Q`gXh2~OUaTQ&JXff$p(uE~Lhe<#n* zG2HCnyMb}?0zJ;j{8zX(=iRw2IC)}#Jd=R@L`JpA{_j{P%YO)*yzJdMmjC|+)Fv{z zZSMRi#XPw#g?}^0w;62pxg38uy|}x$yLoE_N`(`|yd{GrCrZjmTg#d$9Q(9Z>7>$K zrDLBUutycfB95-t*r8>uBcTUUecb>=W*EVAo-pn;l`#M5WeE{5uraYov8lG3;$ZLW z;~MRL+2e~>qt6Y$_JDIi{-FoLk47p-cgDPmJD>0^>1+x^`ms;)nQ7Ucd3y?Ci%u8+ ze)sal^UXPb-5KS8A(fnx3JR|@SfGLEbP%DCvH9Y^z08P6XqX&xYR2RRPv@|I`TFhq z4}qWHK%FNh4~e4%+q2jh`Pl0hF*5>@Jp%)TL0yuCnUJydVC(VN`kIyD6$c?xFbuiR zO{A83knaZ&LBoH*TtG1VY3wpT>IVLHM*&7VrpXUYr%hHovCYn#fsujX7bhcmXfh*< z2$O-x<c(Y(whKuy{$y0X$YLmQe*zyf6C;BHE5m_aekKMGh!O%?0|XB(*Q^8p*OV1G diff --git a/bash-5.1/vendor/unicode-ident/tests/fst/xid_start.fst b/bash-5.1/vendor/unicode-ident/tests/fst/xid_start.fst index 5c2e43fac225796496df1a373f9334e204da6cf1..a5975b67e57e82eddf216bdb249e32fc1c58c440 100644 GIT binary patch delta 1364 zcmcIkdq|T}6#wp>`?fjfu3^Mt<$P@EES--npPS|@-;Z8aKBg^0iy-ii3ToCL6@uv3 zNrN7w6hRMY`Vmpt!yZILP?6Oi8cwXG<w%1bO58S^6a`^n=fFMp-t#->p5J|S4GSET z0-K=?u4hUhxh)^3nBcKM0Vmsvark1`=4;X|iHOuiMaR%ssy8f+qwxueNy$c2O6sz- z^o-0bx;#54H!r`Su&9`R7wEVd2?zyZvWG(ke)O=Na9D?I@c2xSipYIsK2mRqSi}mw zFr^GdSl}gOMPiA!)JH}kur~nY`?BFtpaC`?PXdDcF^K{sJOb8x-jEyK4DatA<xiZw z&vHZr16?e1%BrCKl3YaHWyb2Eqv<jx1`cKM16^fus8DO+k#_;8*!hx8H5)CfN{Wl3 zfxDOqiraD&>?(DEDnzZJbdiUE$ApGy!>4B;>g-l%9}L2z8_?@X{==PCIY(Gl8y31q zqlP_FBkLjWcR&ZWrgNC6Ib;O;4Wlc+Yi9cb(Df2%N%4b^b#q*Z226|`((^B$j$o*K zro=?aAtl^cBjg`GU&mU{vuWZBk|oj|KCGPjjrjM@b1H_FrTvzGhJZr>rTyPEEoizo zGiy+fY3f5GwQh9xVt1P#F&%j|vLQ+u^G-iC&gu`2+aG@+-jaxtb4;Stp=H{1M@C_m zF8f$cN8YJ|lSPdsLn|UyHLs~(yKDW*^8J;i{imx&H+0viYwy(Qwm661IEDu81H9v9 z5|WmcSI|mI%~jR(pkgjoS)fy5=QZ{|7j<=*=X7$Qr=Wg%8^^3cK*n3Z`AP<HwYNBu z0%mon2U*AWIb<TM)~R)x7<c<G>Lr+Y)LY?*_&2ommu2nJ-ypvrX4gN(e|A&;RkrH? z%1-N?`0|<e6TCpsK3)w(X#42`B*6Ne3!&l4ZWteJ1y!v=FhM3=e?%vrde@AgC$K1& z*cimD{`4oc;6HhP_y8qtbG=wzqY6RH1J<a>XcS<?sJxh)d;KxvmM34Q45RG3X8s2F CJB=j( delta 1094 zcmaF<n|aeq<_%`kCLeHPpKL$Pck)GM$;r#71x{8dca+!G(bdy8F#K=y-`K>|?7z8% zrIodft)0Dtqm#3X>;K8eB4Q>BFtRcU)K6qI+x&6*Ljh)i4GohSS!ZoNzv?gh<U;Pa z$#QcvCx6(of=NJsBBT4{fO+hjBe#U|Pu_5N3Ug3kz~qUO6ebJYRGZv?gdb>>oPx57 z>VI^grmmq06PrBo_yi__U6UVb{@R>zY#RUMMs9f~0r`oHrkn5Gc*Qh%e>m%A_B&B* z^_(1~oLf1ac&z!=gak#k#8su_ZqAX}A#+AX?j{6Q%fnd2(RoUmDr;2J)j_JiXoARA zZJ5rdI;-?d4aAHgd|%T*N7G7EJ@eBRBGwme*4cfr-{>gm{L3ZHE!`u_E7K>yZ<YU- zfY4y8Q0H)|NZ)9=n>n$Y<C~IRr*x%#OMmzB#q&oGH>*FkVO07b6ASWsTzmqEN(2!o zKp|=JM$U(u)1Ka80*2{?$p+j8lizNeG1=i$=VXOU2_}J`prD#4zzUTO*ev&km%aYQ z%NH;089*dCkcF9eU9VYRabT#fN3-@mH--{471Wgn`=7c-l4M#EO?~&`<*%PVHVZP} zV4VEuThio-8pe|+*d|YYxMi!hfHwmpL*RR2;ABB-5j6!7Mur=Vo+1K`%uI|73M>o< T+L)ObKw$0{FvYOrve_X3Uth<E diff --git a/bash-5.1/vendor/unicode-ident/tests/static_size.rs b/bash-5.1/vendor/unicode-ident/tests/static_size.rs index f0e04d4..df65f45 100644 --- a/bash-5.1/vendor/unicode-ident/tests/static_size.rs +++ b/bash-5.1/vendor/unicode-ident/tests/static_size.rs @@ -13,7 +13,7 @@ fn test_size() { + size_of_val(&tables::TRIE_START) + size_of_val(&tables::TRIE_CONTINUE) + size_of_val(&tables::LEAF); - assert_eq!(9752, size); + assert_eq!(10016, size); } #[test] @@ -24,7 +24,7 @@ fn test_xid_size() { mod ucd; let size = size_of_val(ucd::XID_START) + size_of_val(ucd::XID_CONTINUE); - assert_eq!(11344, size); + assert_eq!(11528, size); let _ = ucd::BY_NAME; } @@ -71,7 +71,7 @@ fn test_trieset_size() { + size_of_val(tree3_level2) + size_of_val(tree3_level3); - assert_eq!(9952, start_size + continue_size); + assert_eq!(10208, start_size + continue_size); let _ = trie::BY_NAME; } @@ -81,7 +81,7 @@ fn test_fst_size() { let xid_start_fst = include_bytes!("fst/xid_start.fst"); let xid_continue_fst = include_bytes!("fst/xid_continue.fst"); let size = xid_start_fst.len() + xid_continue_fst.len(); - assert_eq!(132897, size); + assert_eq!(137749, size); } #[test] diff --git a/bash-5.1/vendor/unicode-ident/tests/tables/mod.rs b/bash-5.1/vendor/unicode-ident/tests/tables/mod.rs new file mode 100644 index 0000000..72bfd8b --- /dev/null +++ b/bash-5.1/vendor/unicode-ident/tests/tables/mod.rs @@ -0,0 +1,7 @@ +#![allow(clippy::module_inception)] + +#[allow(clippy::redundant_static_lifetimes)] +#[rustfmt::skip] +mod tables; + +pub(crate) use self::tables::*; diff --git a/bash-5.1/vendor/unicode-ident/tests/tables/tables.rs b/bash-5.1/vendor/unicode-ident/tests/tables/tables.rs new file mode 100644 index 0000000..30aeee9 --- /dev/null +++ b/bash-5.1/vendor/unicode-ident/tests/tables/tables.rs @@ -0,0 +1,347 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-bool UCD --include XID_Start,XID_Continue +// +// Unicode version: 15.0.0. +// +// ucd-generate 0.2.13 is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(u32, u32)])] = &[ + ("XID_Continue", XID_CONTINUE), ("XID_Start", XID_START), +]; + +pub const XID_CONTINUE: &'static [(u32, u32)] = &[ + (48, 57), (65, 90), (95, 95), (97, 122), (170, 170), (181, 181), (183, 183), + (186, 186), (192, 214), (216, 246), (248, 705), (710, 721), (736, 740), + (748, 748), (750, 750), (768, 884), (886, 887), (891, 893), (895, 895), + (902, 906), (908, 908), (910, 929), (931, 1013), (1015, 1153), (1155, 1159), + (1162, 1327), (1329, 1366), (1369, 1369), (1376, 1416), (1425, 1469), + (1471, 1471), (1473, 1474), (1476, 1477), (1479, 1479), (1488, 1514), + (1519, 1522), (1552, 1562), (1568, 1641), (1646, 1747), (1749, 1756), + (1759, 1768), (1770, 1788), (1791, 1791), (1808, 1866), (1869, 1969), + (1984, 2037), (2042, 2042), (2045, 2045), (2048, 2093), (2112, 2139), + (2144, 2154), (2160, 2183), (2185, 2190), (2200, 2273), (2275, 2403), + (2406, 2415), (2417, 2435), (2437, 2444), (2447, 2448), (2451, 2472), + (2474, 2480), (2482, 2482), (2486, 2489), (2492, 2500), (2503, 2504), + (2507, 2510), (2519, 2519), (2524, 2525), (2527, 2531), (2534, 2545), + (2556, 2556), (2558, 2558), (2561, 2563), (2565, 2570), (2575, 2576), + (2579, 2600), (2602, 2608), (2610, 2611), (2613, 2614), (2616, 2617), + (2620, 2620), (2622, 2626), (2631, 2632), (2635, 2637), (2641, 2641), + (2649, 2652), (2654, 2654), (2662, 2677), (2689, 2691), (2693, 2701), + (2703, 2705), (2707, 2728), (2730, 2736), (2738, 2739), (2741, 2745), + (2748, 2757), (2759, 2761), (2763, 2765), (2768, 2768), (2784, 2787), + (2790, 2799), (2809, 2815), (2817, 2819), (2821, 2828), (2831, 2832), + (2835, 2856), (2858, 2864), (2866, 2867), (2869, 2873), (2876, 2884), + (2887, 2888), (2891, 2893), (2901, 2903), (2908, 2909), (2911, 2915), + (2918, 2927), (2929, 2929), (2946, 2947), (2949, 2954), (2958, 2960), + (2962, 2965), (2969, 2970), (2972, 2972), (2974, 2975), (2979, 2980), + (2984, 2986), (2990, 3001), (3006, 3010), (3014, 3016), (3018, 3021), + (3024, 3024), (3031, 3031), (3046, 3055), (3072, 3084), (3086, 3088), + (3090, 3112), (3114, 3129), (3132, 3140), (3142, 3144), (3146, 3149), + (3157, 3158), (3160, 3162), (3165, 3165), (3168, 3171), (3174, 3183), + (3200, 3203), (3205, 3212), (3214, 3216), (3218, 3240), (3242, 3251), + (3253, 3257), (3260, 3268), (3270, 3272), (3274, 3277), (3285, 3286), + (3293, 3294), (3296, 3299), (3302, 3311), (3313, 3315), (3328, 3340), + (3342, 3344), (3346, 3396), (3398, 3400), (3402, 3406), (3412, 3415), + (3423, 3427), (3430, 3439), (3450, 3455), (3457, 3459), (3461, 3478), + (3482, 3505), (3507, 3515), (3517, 3517), (3520, 3526), (3530, 3530), + (3535, 3540), (3542, 3542), (3544, 3551), (3558, 3567), (3570, 3571), + (3585, 3642), (3648, 3662), (3664, 3673), (3713, 3714), (3716, 3716), + (3718, 3722), (3724, 3747), (3749, 3749), (3751, 3773), (3776, 3780), + (3782, 3782), (3784, 3790), (3792, 3801), (3804, 3807), (3840, 3840), + (3864, 3865), (3872, 3881), (3893, 3893), (3895, 3895), (3897, 3897), + (3902, 3911), (3913, 3948), (3953, 3972), (3974, 3991), (3993, 4028), + (4038, 4038), (4096, 4169), (4176, 4253), (4256, 4293), (4295, 4295), + (4301, 4301), (4304, 4346), (4348, 4680), (4682, 4685), (4688, 4694), + (4696, 4696), (4698, 4701), (4704, 4744), (4746, 4749), (4752, 4784), + (4786, 4789), (4792, 4798), (4800, 4800), (4802, 4805), (4808, 4822), + (4824, 4880), (4882, 4885), (4888, 4954), (4957, 4959), (4969, 4977), + (4992, 5007), (5024, 5109), (5112, 5117), (5121, 5740), (5743, 5759), + (5761, 5786), (5792, 5866), (5870, 5880), (5888, 5909), (5919, 5940), + (5952, 5971), (5984, 5996), (5998, 6000), (6002, 6003), (6016, 6099), + (6103, 6103), (6108, 6109), (6112, 6121), (6155, 6157), (6159, 6169), + (6176, 6264), (6272, 6314), (6320, 6389), (6400, 6430), (6432, 6443), + (6448, 6459), (6470, 6509), (6512, 6516), (6528, 6571), (6576, 6601), + (6608, 6618), (6656, 6683), (6688, 6750), (6752, 6780), (6783, 6793), + (6800, 6809), (6823, 6823), (6832, 6845), (6847, 6862), (6912, 6988), + (6992, 7001), (7019, 7027), (7040, 7155), (7168, 7223), (7232, 7241), + (7245, 7293), (7296, 7304), (7312, 7354), (7357, 7359), (7376, 7378), + (7380, 7418), (7424, 7957), (7960, 7965), (7968, 8005), (8008, 8013), + (8016, 8023), (8025, 8025), (8027, 8027), (8029, 8029), (8031, 8061), + (8064, 8116), (8118, 8124), (8126, 8126), (8130, 8132), (8134, 8140), + (8144, 8147), (8150, 8155), (8160, 8172), (8178, 8180), (8182, 8188), + (8255, 8256), (8276, 8276), (8305, 8305), (8319, 8319), (8336, 8348), + (8400, 8412), (8417, 8417), (8421, 8432), (8450, 8450), (8455, 8455), + (8458, 8467), (8469, 8469), (8472, 8477), (8484, 8484), (8486, 8486), + (8488, 8488), (8490, 8505), (8508, 8511), (8517, 8521), (8526, 8526), + (8544, 8584), (11264, 11492), (11499, 11507), (11520, 11557), + (11559, 11559), (11565, 11565), (11568, 11623), (11631, 11631), + (11647, 11670), (11680, 11686), (11688, 11694), (11696, 11702), + (11704, 11710), (11712, 11718), (11720, 11726), (11728, 11734), + (11736, 11742), (11744, 11775), (12293, 12295), (12321, 12335), + (12337, 12341), (12344, 12348), (12353, 12438), (12441, 12442), + (12445, 12447), (12449, 12538), (12540, 12543), (12549, 12591), + (12593, 12686), (12704, 12735), (12784, 12799), (13312, 19903), + (19968, 42124), (42192, 42237), (42240, 42508), (42512, 42539), + (42560, 42607), (42612, 42621), (42623, 42737), (42775, 42783), + (42786, 42888), (42891, 42954), (42960, 42961), (42963, 42963), + (42965, 42969), (42994, 43047), (43052, 43052), (43072, 43123), + (43136, 43205), (43216, 43225), (43232, 43255), (43259, 43259), + (43261, 43309), (43312, 43347), (43360, 43388), (43392, 43456), + (43471, 43481), (43488, 43518), (43520, 43574), (43584, 43597), + (43600, 43609), (43616, 43638), (43642, 43714), (43739, 43741), + (43744, 43759), (43762, 43766), (43777, 43782), (43785, 43790), + (43793, 43798), (43808, 43814), (43816, 43822), (43824, 43866), + (43868, 43881), (43888, 44010), (44012, 44013), (44016, 44025), + (44032, 55203), (55216, 55238), (55243, 55291), (63744, 64109), + (64112, 64217), (64256, 64262), (64275, 64279), (64285, 64296), + (64298, 64310), (64312, 64316), (64318, 64318), (64320, 64321), + (64323, 64324), (64326, 64433), (64467, 64605), (64612, 64829), + (64848, 64911), (64914, 64967), (65008, 65017), (65024, 65039), + (65056, 65071), (65075, 65076), (65101, 65103), (65137, 65137), + (65139, 65139), (65143, 65143), (65145, 65145), (65147, 65147), + (65149, 65149), (65151, 65276), (65296, 65305), (65313, 65338), + (65343, 65343), (65345, 65370), (65382, 65470), (65474, 65479), + (65482, 65487), (65490, 65495), (65498, 65500), (65536, 65547), + (65549, 65574), (65576, 65594), (65596, 65597), (65599, 65613), + (65616, 65629), (65664, 65786), (65856, 65908), (66045, 66045), + (66176, 66204), (66208, 66256), (66272, 66272), (66304, 66335), + (66349, 66378), (66384, 66426), (66432, 66461), (66464, 66499), + (66504, 66511), (66513, 66517), (66560, 66717), (66720, 66729), + (66736, 66771), (66776, 66811), (66816, 66855), (66864, 66915), + (66928, 66938), (66940, 66954), (66956, 66962), (66964, 66965), + (66967, 66977), (66979, 66993), (66995, 67001), (67003, 67004), + (67072, 67382), (67392, 67413), (67424, 67431), (67456, 67461), + (67463, 67504), (67506, 67514), (67584, 67589), (67592, 67592), + (67594, 67637), (67639, 67640), (67644, 67644), (67647, 67669), + (67680, 67702), (67712, 67742), (67808, 67826), (67828, 67829), + (67840, 67861), (67872, 67897), (67968, 68023), (68030, 68031), + (68096, 68099), (68101, 68102), (68108, 68115), (68117, 68119), + (68121, 68149), (68152, 68154), (68159, 68159), (68192, 68220), + (68224, 68252), (68288, 68295), (68297, 68326), (68352, 68405), + (68416, 68437), (68448, 68466), (68480, 68497), (68608, 68680), + (68736, 68786), (68800, 68850), (68864, 68903), (68912, 68921), + (69248, 69289), (69291, 69292), (69296, 69297), (69373, 69404), + (69415, 69415), (69424, 69456), (69488, 69509), (69552, 69572), + (69600, 69622), (69632, 69702), (69734, 69749), (69759, 69818), + (69826, 69826), (69840, 69864), (69872, 69881), (69888, 69940), + (69942, 69951), (69956, 69959), (69968, 70003), (70006, 70006), + (70016, 70084), (70089, 70092), (70094, 70106), (70108, 70108), + (70144, 70161), (70163, 70199), (70206, 70209), (70272, 70278), + (70280, 70280), (70282, 70285), (70287, 70301), (70303, 70312), + (70320, 70378), (70384, 70393), (70400, 70403), (70405, 70412), + (70415, 70416), (70419, 70440), (70442, 70448), (70450, 70451), + (70453, 70457), (70459, 70468), (70471, 70472), (70475, 70477), + (70480, 70480), (70487, 70487), (70493, 70499), (70502, 70508), + (70512, 70516), (70656, 70730), (70736, 70745), (70750, 70753), + (70784, 70853), (70855, 70855), (70864, 70873), (71040, 71093), + (71096, 71104), (71128, 71133), (71168, 71232), (71236, 71236), + (71248, 71257), (71296, 71352), (71360, 71369), (71424, 71450), + (71453, 71467), (71472, 71481), (71488, 71494), (71680, 71738), + (71840, 71913), (71935, 71942), (71945, 71945), (71948, 71955), + (71957, 71958), (71960, 71989), (71991, 71992), (71995, 72003), + (72016, 72025), (72096, 72103), (72106, 72151), (72154, 72161), + (72163, 72164), (72192, 72254), (72263, 72263), (72272, 72345), + (72349, 72349), (72368, 72440), (72704, 72712), (72714, 72758), + (72760, 72768), (72784, 72793), (72818, 72847), (72850, 72871), + (72873, 72886), (72960, 72966), (72968, 72969), (72971, 73014), + (73018, 73018), (73020, 73021), (73023, 73031), (73040, 73049), + (73056, 73061), (73063, 73064), (73066, 73102), (73104, 73105), + (73107, 73112), (73120, 73129), (73440, 73462), (73472, 73488), + (73490, 73530), (73534, 73538), (73552, 73561), (73648, 73648), + (73728, 74649), (74752, 74862), (74880, 75075), (77712, 77808), + (77824, 78895), (78912, 78933), (82944, 83526), (92160, 92728), + (92736, 92766), (92768, 92777), (92784, 92862), (92864, 92873), + (92880, 92909), (92912, 92916), (92928, 92982), (92992, 92995), + (93008, 93017), (93027, 93047), (93053, 93071), (93760, 93823), + (93952, 94026), (94031, 94087), (94095, 94111), (94176, 94177), + (94179, 94180), (94192, 94193), (94208, 100343), (100352, 101589), + (101632, 101640), (110576, 110579), (110581, 110587), (110589, 110590), + (110592, 110882), (110898, 110898), (110928, 110930), (110933, 110933), + (110948, 110951), (110960, 111355), (113664, 113770), (113776, 113788), + (113792, 113800), (113808, 113817), (113821, 113822), (118528, 118573), + (118576, 118598), (119141, 119145), (119149, 119154), (119163, 119170), + (119173, 119179), (119210, 119213), (119362, 119364), (119808, 119892), + (119894, 119964), (119966, 119967), (119970, 119970), (119973, 119974), + (119977, 119980), (119982, 119993), (119995, 119995), (119997, 120003), + (120005, 120069), (120071, 120074), (120077, 120084), (120086, 120092), + (120094, 120121), (120123, 120126), (120128, 120132), (120134, 120134), + (120138, 120144), (120146, 120485), (120488, 120512), (120514, 120538), + (120540, 120570), (120572, 120596), (120598, 120628), (120630, 120654), + (120656, 120686), (120688, 120712), (120714, 120744), (120746, 120770), + (120772, 120779), (120782, 120831), (121344, 121398), (121403, 121452), + (121461, 121461), (121476, 121476), (121499, 121503), (121505, 121519), + (122624, 122654), (122661, 122666), (122880, 122886), (122888, 122904), + (122907, 122913), (122915, 122916), (122918, 122922), (122928, 122989), + (123023, 123023), (123136, 123180), (123184, 123197), (123200, 123209), + (123214, 123214), (123536, 123566), (123584, 123641), (124112, 124153), + (124896, 124902), (124904, 124907), (124909, 124910), (124912, 124926), + (124928, 125124), (125136, 125142), (125184, 125259), (125264, 125273), + (126464, 126467), (126469, 126495), (126497, 126498), (126500, 126500), + (126503, 126503), (126505, 126514), (126516, 126519), (126521, 126521), + (126523, 126523), (126530, 126530), (126535, 126535), (126537, 126537), + (126539, 126539), (126541, 126543), (126545, 126546), (126548, 126548), + (126551, 126551), (126553, 126553), (126555, 126555), (126557, 126557), + (126559, 126559), (126561, 126562), (126564, 126564), (126567, 126570), + (126572, 126578), (126580, 126583), (126585, 126588), (126590, 126590), + (126592, 126601), (126603, 126619), (126625, 126627), (126629, 126633), + (126635, 126651), (130032, 130041), (131072, 173791), (173824, 177977), + (177984, 178205), (178208, 183969), (183984, 191456), (194560, 195101), + (196608, 201546), (201552, 205743), (917760, 917999), +]; + +pub const XID_START: &'static [(u32, u32)] = &[ + (65, 90), (97, 122), (170, 170), (181, 181), (186, 186), (192, 214), + (216, 246), (248, 705), (710, 721), (736, 740), (748, 748), (750, 750), + (880, 884), (886, 887), (891, 893), (895, 895), (902, 902), (904, 906), + (908, 908), (910, 929), (931, 1013), (1015, 1153), (1162, 1327), + (1329, 1366), (1369, 1369), (1376, 1416), (1488, 1514), (1519, 1522), + (1568, 1610), (1646, 1647), (1649, 1747), (1749, 1749), (1765, 1766), + (1774, 1775), (1786, 1788), (1791, 1791), (1808, 1808), (1810, 1839), + (1869, 1957), (1969, 1969), (1994, 2026), (2036, 2037), (2042, 2042), + (2048, 2069), (2074, 2074), (2084, 2084), (2088, 2088), (2112, 2136), + (2144, 2154), (2160, 2183), (2185, 2190), (2208, 2249), (2308, 2361), + (2365, 2365), (2384, 2384), (2392, 2401), (2417, 2432), (2437, 2444), + (2447, 2448), (2451, 2472), (2474, 2480), (2482, 2482), (2486, 2489), + (2493, 2493), (2510, 2510), (2524, 2525), (2527, 2529), (2544, 2545), + (2556, 2556), (2565, 2570), (2575, 2576), (2579, 2600), (2602, 2608), + (2610, 2611), (2613, 2614), (2616, 2617), (2649, 2652), (2654, 2654), + (2674, 2676), (2693, 2701), (2703, 2705), (2707, 2728), (2730, 2736), + (2738, 2739), (2741, 2745), (2749, 2749), (2768, 2768), (2784, 2785), + (2809, 2809), (2821, 2828), (2831, 2832), (2835, 2856), (2858, 2864), + (2866, 2867), (2869, 2873), (2877, 2877), (2908, 2909), (2911, 2913), + (2929, 2929), (2947, 2947), (2949, 2954), (2958, 2960), (2962, 2965), + (2969, 2970), (2972, 2972), (2974, 2975), (2979, 2980), (2984, 2986), + (2990, 3001), (3024, 3024), (3077, 3084), (3086, 3088), (3090, 3112), + (3114, 3129), (3133, 3133), (3160, 3162), (3165, 3165), (3168, 3169), + (3200, 3200), (3205, 3212), (3214, 3216), (3218, 3240), (3242, 3251), + (3253, 3257), (3261, 3261), (3293, 3294), (3296, 3297), (3313, 3314), + (3332, 3340), (3342, 3344), (3346, 3386), (3389, 3389), (3406, 3406), + (3412, 3414), (3423, 3425), (3450, 3455), (3461, 3478), (3482, 3505), + (3507, 3515), (3517, 3517), (3520, 3526), (3585, 3632), (3634, 3634), + (3648, 3654), (3713, 3714), (3716, 3716), (3718, 3722), (3724, 3747), + (3749, 3749), (3751, 3760), (3762, 3762), (3773, 3773), (3776, 3780), + (3782, 3782), (3804, 3807), (3840, 3840), (3904, 3911), (3913, 3948), + (3976, 3980), (4096, 4138), (4159, 4159), (4176, 4181), (4186, 4189), + (4193, 4193), (4197, 4198), (4206, 4208), (4213, 4225), (4238, 4238), + (4256, 4293), (4295, 4295), (4301, 4301), (4304, 4346), (4348, 4680), + (4682, 4685), (4688, 4694), (4696, 4696), (4698, 4701), (4704, 4744), + (4746, 4749), (4752, 4784), (4786, 4789), (4792, 4798), (4800, 4800), + (4802, 4805), (4808, 4822), (4824, 4880), (4882, 4885), (4888, 4954), + (4992, 5007), (5024, 5109), (5112, 5117), (5121, 5740), (5743, 5759), + (5761, 5786), (5792, 5866), (5870, 5880), (5888, 5905), (5919, 5937), + (5952, 5969), (5984, 5996), (5998, 6000), (6016, 6067), (6103, 6103), + (6108, 6108), (6176, 6264), (6272, 6312), (6314, 6314), (6320, 6389), + (6400, 6430), (6480, 6509), (6512, 6516), (6528, 6571), (6576, 6601), + (6656, 6678), (6688, 6740), (6823, 6823), (6917, 6963), (6981, 6988), + (7043, 7072), (7086, 7087), (7098, 7141), (7168, 7203), (7245, 7247), + (7258, 7293), (7296, 7304), (7312, 7354), (7357, 7359), (7401, 7404), + (7406, 7411), (7413, 7414), (7418, 7418), (7424, 7615), (7680, 7957), + (7960, 7965), (7968, 8005), (8008, 8013), (8016, 8023), (8025, 8025), + (8027, 8027), (8029, 8029), (8031, 8061), (8064, 8116), (8118, 8124), + (8126, 8126), (8130, 8132), (8134, 8140), (8144, 8147), (8150, 8155), + (8160, 8172), (8178, 8180), (8182, 8188), (8305, 8305), (8319, 8319), + (8336, 8348), (8450, 8450), (8455, 8455), (8458, 8467), (8469, 8469), + (8472, 8477), (8484, 8484), (8486, 8486), (8488, 8488), (8490, 8505), + (8508, 8511), (8517, 8521), (8526, 8526), (8544, 8584), (11264, 11492), + (11499, 11502), (11506, 11507), (11520, 11557), (11559, 11559), + (11565, 11565), (11568, 11623), (11631, 11631), (11648, 11670), + (11680, 11686), (11688, 11694), (11696, 11702), (11704, 11710), + (11712, 11718), (11720, 11726), (11728, 11734), (11736, 11742), + (12293, 12295), (12321, 12329), (12337, 12341), (12344, 12348), + (12353, 12438), (12445, 12447), (12449, 12538), (12540, 12543), + (12549, 12591), (12593, 12686), (12704, 12735), (12784, 12799), + (13312, 19903), (19968, 42124), (42192, 42237), (42240, 42508), + (42512, 42527), (42538, 42539), (42560, 42606), (42623, 42653), + (42656, 42735), (42775, 42783), (42786, 42888), (42891, 42954), + (42960, 42961), (42963, 42963), (42965, 42969), (42994, 43009), + (43011, 43013), (43015, 43018), (43020, 43042), (43072, 43123), + (43138, 43187), (43250, 43255), (43259, 43259), (43261, 43262), + (43274, 43301), (43312, 43334), (43360, 43388), (43396, 43442), + (43471, 43471), (43488, 43492), (43494, 43503), (43514, 43518), + (43520, 43560), (43584, 43586), (43588, 43595), (43616, 43638), + (43642, 43642), (43646, 43695), (43697, 43697), (43701, 43702), + (43705, 43709), (43712, 43712), (43714, 43714), (43739, 43741), + (43744, 43754), (43762, 43764), (43777, 43782), (43785, 43790), + (43793, 43798), (43808, 43814), (43816, 43822), (43824, 43866), + (43868, 43881), (43888, 44002), (44032, 55203), (55216, 55238), + (55243, 55291), (63744, 64109), (64112, 64217), (64256, 64262), + (64275, 64279), (64285, 64285), (64287, 64296), (64298, 64310), + (64312, 64316), (64318, 64318), (64320, 64321), (64323, 64324), + (64326, 64433), (64467, 64605), (64612, 64829), (64848, 64911), + (64914, 64967), (65008, 65017), (65137, 65137), (65139, 65139), + (65143, 65143), (65145, 65145), (65147, 65147), (65149, 65149), + (65151, 65276), (65313, 65338), (65345, 65370), (65382, 65437), + (65440, 65470), (65474, 65479), (65482, 65487), (65490, 65495), + (65498, 65500), (65536, 65547), (65549, 65574), (65576, 65594), + (65596, 65597), (65599, 65613), (65616, 65629), (65664, 65786), + (65856, 65908), (66176, 66204), (66208, 66256), (66304, 66335), + (66349, 66378), (66384, 66421), (66432, 66461), (66464, 66499), + (66504, 66511), (66513, 66517), (66560, 66717), (66736, 66771), + (66776, 66811), (66816, 66855), (66864, 66915), (66928, 66938), + (66940, 66954), (66956, 66962), (66964, 66965), (66967, 66977), + (66979, 66993), (66995, 67001), (67003, 67004), (67072, 67382), + (67392, 67413), (67424, 67431), (67456, 67461), (67463, 67504), + (67506, 67514), (67584, 67589), (67592, 67592), (67594, 67637), + (67639, 67640), (67644, 67644), (67647, 67669), (67680, 67702), + (67712, 67742), (67808, 67826), (67828, 67829), (67840, 67861), + (67872, 67897), (67968, 68023), (68030, 68031), (68096, 68096), + (68112, 68115), (68117, 68119), (68121, 68149), (68192, 68220), + (68224, 68252), (68288, 68295), (68297, 68324), (68352, 68405), + (68416, 68437), (68448, 68466), (68480, 68497), (68608, 68680), + (68736, 68786), (68800, 68850), (68864, 68899), (69248, 69289), + (69296, 69297), (69376, 69404), (69415, 69415), (69424, 69445), + (69488, 69505), (69552, 69572), (69600, 69622), (69635, 69687), + (69745, 69746), (69749, 69749), (69763, 69807), (69840, 69864), + (69891, 69926), (69956, 69956), (69959, 69959), (69968, 70002), + (70006, 70006), (70019, 70066), (70081, 70084), (70106, 70106), + (70108, 70108), (70144, 70161), (70163, 70187), (70207, 70208), + (70272, 70278), (70280, 70280), (70282, 70285), (70287, 70301), + (70303, 70312), (70320, 70366), (70405, 70412), (70415, 70416), + (70419, 70440), (70442, 70448), (70450, 70451), (70453, 70457), + (70461, 70461), (70480, 70480), (70493, 70497), (70656, 70708), + (70727, 70730), (70751, 70753), (70784, 70831), (70852, 70853), + (70855, 70855), (71040, 71086), (71128, 71131), (71168, 71215), + (71236, 71236), (71296, 71338), (71352, 71352), (71424, 71450), + (71488, 71494), (71680, 71723), (71840, 71903), (71935, 71942), + (71945, 71945), (71948, 71955), (71957, 71958), (71960, 71983), + (71999, 71999), (72001, 72001), (72096, 72103), (72106, 72144), + (72161, 72161), (72163, 72163), (72192, 72192), (72203, 72242), + (72250, 72250), (72272, 72272), (72284, 72329), (72349, 72349), + (72368, 72440), (72704, 72712), (72714, 72750), (72768, 72768), + (72818, 72847), (72960, 72966), (72968, 72969), (72971, 73008), + (73030, 73030), (73056, 73061), (73063, 73064), (73066, 73097), + (73112, 73112), (73440, 73458), (73474, 73474), (73476, 73488), + (73490, 73523), (73648, 73648), (73728, 74649), (74752, 74862), + (74880, 75075), (77712, 77808), (77824, 78895), (78913, 78918), + (82944, 83526), (92160, 92728), (92736, 92766), (92784, 92862), + (92880, 92909), (92928, 92975), (92992, 92995), (93027, 93047), + (93053, 93071), (93760, 93823), (93952, 94026), (94032, 94032), + (94099, 94111), (94176, 94177), (94179, 94179), (94208, 100343), + (100352, 101589), (101632, 101640), (110576, 110579), (110581, 110587), + (110589, 110590), (110592, 110882), (110898, 110898), (110928, 110930), + (110933, 110933), (110948, 110951), (110960, 111355), (113664, 113770), + (113776, 113788), (113792, 113800), (113808, 113817), (119808, 119892), + (119894, 119964), (119966, 119967), (119970, 119970), (119973, 119974), + (119977, 119980), (119982, 119993), (119995, 119995), (119997, 120003), + (120005, 120069), (120071, 120074), (120077, 120084), (120086, 120092), + (120094, 120121), (120123, 120126), (120128, 120132), (120134, 120134), + (120138, 120144), (120146, 120485), (120488, 120512), (120514, 120538), + (120540, 120570), (120572, 120596), (120598, 120628), (120630, 120654), + (120656, 120686), (120688, 120712), (120714, 120744), (120746, 120770), + (120772, 120779), (122624, 122654), (122661, 122666), (122928, 122989), + (123136, 123180), (123191, 123197), (123214, 123214), (123536, 123565), + (123584, 123627), (124112, 124139), (124896, 124902), (124904, 124907), + (124909, 124910), (124912, 124926), (124928, 125124), (125184, 125251), + (125259, 125259), (126464, 126467), (126469, 126495), (126497, 126498), + (126500, 126500), (126503, 126503), (126505, 126514), (126516, 126519), + (126521, 126521), (126523, 126523), (126530, 126530), (126535, 126535), + (126537, 126537), (126539, 126539), (126541, 126543), (126545, 126546), + (126548, 126548), (126551, 126551), (126553, 126553), (126555, 126555), + (126557, 126557), (126559, 126559), (126561, 126562), (126564, 126564), + (126567, 126570), (126572, 126578), (126580, 126583), (126585, 126588), + (126590, 126590), (126592, 126601), (126603, 126619), (126625, 126627), + (126629, 126633), (126635, 126651), (131072, 173791), (173824, 177977), + (177984, 178205), (178208, 183969), (183984, 191456), (194560, 195101), + (196608, 201546), (201552, 205743), +]; diff --git a/bash-5.1/vendor/unicode-ident/tests/trie/trie.rs b/bash-5.1/vendor/unicode-ident/tests/trie/trie.rs index 7f7a14f..821e7cb 100644 --- a/bash-5.1/vendor/unicode-ident/tests/trie/trie.rs +++ b/bash-5.1/vendor/unicode-ident/tests/trie/trie.rs @@ -2,9 +2,9 @@ // // ucd-generate property-bool UCD --include XID_Start,XID_Continue --trie-set // -// Unicode version: 14.0.0. +// Unicode version: 15.0.0. // -// ucd-generate 0.2.10 is available on crates.io. +// ucd-generate 0.2.13 is available on crates.io. pub const BY_NAME: &'static [(&'static str, &'static ::ucd_trie::TrieSet)] = &[ ("XID_Continue", XID_CONTINUE), ("XID_Start", XID_START), @@ -77,10 +77,10 @@ pub const XID_CONTINUE: &'static ::ucd_trie::TrieSet = &::ucd_trie::TrieSet { 0xF3C5FDFFFFF99FEF, 0x5003FFCFB080799F, 0xD36DFDFFFFF987EE, 0x3FFFC05E023987, 0xF3EDFDFFFFFBBFEE, 0xFE00FFCF00013BBF, 0xF3EDFDFFFFF99FEE, 0x2FFCFB0E0399F, 0xC3FFC718D63DC7EC, 0xFFC000813DC7, - 0xF3FFFDFFFFFDDFFF, 0xFFCF27603DDF, 0xF3EFFDFFFFFDDFEF, 0x6FFCF60603DDF, + 0xF3FFFDFFFFFDDFFF, 0xFFCF27603DDF, 0xF3EFFDFFFFFDDFEF, 0xEFFCF60603DDF, 0xFFFFFFFFFFFDDFFF, 0xFC00FFCF80F07DDF, 0x2FFBFFFFFC7FFFEE, 0xCFFC0FF5F847F, 0x7FFFFFFFFFFFFFE, 0x3FF7FFF, 0x3FFFFFAFFFFFF7D6, - 0xF3FF3F5F, 0xC2A003FF03000001, 0xFFFE1FFFFFFFFEFF, 0x1FFFFFFFFEFFFFDF, + 0xF3FF7F5F, 0xC2A003FF03000001, 0xFFFE1FFFFFFFFEFF, 0x1FFFFFFFFEFFFFDF, 0x40, 0xFFFFFFFFFFFF03FF, 0xFFFFFFFF3FFFFFFF, 0xF7FFFFFFFFFF20BF, 0xFFFFFFFF3D7F3DFF, 0x7F3DFFFFFFFF3DFF, 0xFFFFFFFFFF7FFF3D, 0xFFFFFFFFFF3DFFFF, 0x3FE00E7FFFFFF, 0xFFFFFFFF0000FFFF, @@ -112,78 +112,80 @@ pub const XID_CONTINUE: &'static ::ucd_trie::TrieSet = &::ucd_trie::TrieSet { ], tree3_level1: &[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 5, 9, 10, 11, 12, 13, 14, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 15, 16, 17, 7, 18, 19, 7, 20, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 7, 7, 7, 15, 16, 17, 7, 18, 19, 7, 20, 21, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 21, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 22, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ], tree3_level2: &[ 0, 1, 2, 3, 4, 5, 4, 6, 4, 4, 7, 8, 9, 10, 11, 12, 2, 2, 13, 14, 15, 16, 17, 4, 2, 2, 2, 2, 18, 19, 20, 4, 21, 22, 23, 24, 25, 4, 26, 4, 27, 28, - 29, 30, 31, 32, 33, 4, 2, 34, 35, 35, 36, 4, 4, 4, 4, 4, 37, 4, 38, 39, - 40, 41, 2, 42, 3, 43, 44, 45, 2, 46, 47, 4, 48, 49, 50, 51, 4, 4, 2, 52, - 2, 53, 4, 4, 54, 55, 2, 56, 57, 58, 59, 60, 4, 4, 3, 4, 61, 62, 63, 64, - 65, 66, 67, 68, 69, 57, 4, 4, 4, 4, 70, 71, 72, 4, 73, 74, 75, 4, 4, 4, 4, - 76, 4, 4, 77, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 78, 4, 2, 79, - 2, 2, 2, 80, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 81, 82, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 79, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 29, 30, 31, 32, 33, 4, 2, 34, 35, 35, 36, 4, 4, 4, 4, 4, 37, 38, 39, 40, + 41, 42, 2, 43, 3, 44, 45, 46, 2, 47, 48, 49, 50, 51, 52, 53, 4, 4, 2, 54, + 2, 55, 4, 4, 56, 57, 2, 58, 59, 60, 61, 62, 4, 4, 3, 4, 63, 64, 65, 66, + 67, 68, 69, 70, 71, 59, 4, 4, 4, 4, 72, 73, 74, 4, 75, 76, 77, 4, 4, 4, 4, + 78, 79, 80, 81, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 82, 4, 2, 83, + 2, 2, 2, 84, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 85, 86, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 87, 88, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 60, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 62, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, - 2, 2, 2, 2, 2, 2, 2, 57, 83, 67, 84, 18, 85, 86, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 2, 4, 4, 2, 87, 88, 89, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 59, 89, 69, 90, 18, 91, 92, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 2, 4, 4, 2, 93, 94, 95, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 90, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 91, 34, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 2, 2, 2, 2, 2, 96, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 88, 34, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 92, 2, 2, 2, 2, 93, 94, 2, 2, 2, 2, 2, 95, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 97, 2, 2, 2, 2, 98, 99, 2, 2, 2, 2, 2, 100, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 2, 96, 97, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 2, 101, 102, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 98, 60, 4, 4, 4, 4, 4, 4, 4, 99, 100, 4, 4, 101, 4, 4, - 4, 4, 4, 4, 2, 102, 103, 104, 105, 106, 2, 2, 2, 2, 107, 108, 109, 110, - 111, 112, 4, 4, 4, 4, 4, 4, 4, 4, 113, 114, 115, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 23, 4, 4, 4, 116, 4, 4, 4, 117, 118, 4, 4, 4, - 4, 119, 120, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 121, - 2, 2, 2, 122, 2, 123, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 124, 125, 126, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 103, 62, 4, 4, 4, 4, 4, 4, 4, 104, 105, 4, 4, 106, 4, + 4, 4, 4, 4, 4, 2, 107, 108, 109, 110, 111, 2, 2, 2, 2, 112, 113, 114, 115, + 116, 117, 4, 4, 4, 4, 4, 4, 4, 4, 118, 119, 120, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 121, 4, 4, 4, 122, 123, 124, 4, 125, 126, 4, 4, + 4, 4, 127, 128, 4, 4, 4, 4, 4, 4, 4, 129, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 130, 2, 2, 2, 131, 2, 132, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 133, 134, 135, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 128, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 136, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 137, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 57, 2, 2, 2, 11, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 128, 2, 2, 2, + 11, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 138, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 129, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 130, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, - 2, 131, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 132, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 139, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 133, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, + 2, 2, 2, 140, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 141, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 87, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 87, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, ], tree3_level3: &[ 0xB7FFFF7FFFFFEFFF, 0x3FFF3FFF, 0xFFFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFF, 0, @@ -195,32 +197,34 @@ pub const XID_CONTINUE: &'static ::ucd_trie::TrieSet = &::ucd_trie::TrieSet { 0x37FFFF00000000, 0x3FFFFFF003FFFFF, 0xC0FFFFFFFFFFFFFF, 0x873FFFFFFEEFF06F, 0x1FFFFFFF00000000, 0x1FFFFFFF, 0x7FFFFFFEFF, 0x3FFFFFFFFFFFFF, 0x7FFFF003FFFFF, 0x3FFFF, 0x1FF, 0x7FFFFFFFFFFFF, - 0x3FF00FFFFFFFFFF, 0x31BFFFFFFFFFF, 0xFFFF00801FFFFFFF, - 0xFFFF00000001FFFF, 0xFFFF00000000003F, 0x7FFFFF0000001F, - 0x803FFFC00000007F, 0x3FF01FFFFFF0004, 0xFFDFFFFFFFFFFFFF, - 0x4FFFFFFFFF00F0, 0x17FFDE1F, 0x40FFFFFFFFFBFFFF, 0xFFFF01FFBFFFBD7F, - 0x3FF07FFFFFFFFFF, 0xFBEDFDFFFFF99FEF, 0x1F1FCFE081399F, 0x3C3FF07FF, - 0x3FF00BF, 0xFF3FFFFFFFFFFFFF, 0x3F000001, 0x3FF0011, 0x1FFFFFFFFFFFFFF, - 0x3FF, 0x3FF0FFFE7FFFFFF, 0x7F, 0xFFFFFFFF00000000, 0x800003FFFFFFFFFF, - 0xF9BFFFFFFF6FF27F, 0x3FF000F, 0xFFFFFCFF00000000, 0x1BFCFFFFFF, - 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFF0080, 0xFFFF000023FFFFFF, - 0xFF7FFFFFFFFFFDFF, 0xFFFC000003FF0001, 0x7FFEFFFFFCFFFF, - 0xB47FFFFFFFFFFB7F, 0xFFFFFDBF03FF00FF, 0x3FF01FB7FFF, 0x7FFFFF00000000, - 0x1000000000000, 0x3FFFFFF, 0x7FFFFFFFFFFF, 0xF, 0xFFFFFFFFFFFF0000, - 0x1FFFFFFFFFFFF, 0xFFFF03FF7FFFFFFF, 0x1F3FFFFFFF03FF, 0xE0FFFFF803FF000F, - 0xFFFF, 0xFFFFFFFFFFFF87FF, 0xFFFF80FF, 0x3001B00000000, 0xFFFFFFFFFFFFFF, - 0x3FFFFF, 0x6FEF000000000000, 0x7FFFFFFFF, 0xFFFF00F000070000, - 0xFFFFFFFFFFFFFFF, 0x1FFF07FFFFFFFFFF, 0x63FF01FF, 0xFFFF3FFFFFFFFFFF, - 0xF807E3E000000000, 0x3C0000000FE7, 0x1C, 0xFFFFFFFFFFDFFFFF, - 0xEBFFDE64DFFFFFFF, 0xFFFFFFFFFFFFFFEF, 0x7BFFFFFFDFDFE7BF, - 0xFFFFFFFFFFFDFC5F, 0xFFFFFF3FFFFFFFFF, 0xF7FFFFFFF7FFFFFD, - 0xFFDFFFFFFFDFFFFF, 0xFFFF7FFFFFFF7FFF, 0xFFFFFDFFFFFFFDFF, - 0xFFFFFFFFFFFFCFF7, 0xF87FFFFFFFFFFFFF, 0x201FFFFFFFFFFF, 0xFFFEF8000010, - 0x7DBF9FFFF7F, 0x3FFF1FFFFFFFFFFF, 0x43FF, 0x7FFFFFFF0000, - 0x3FFFFFFFFFFFFFF, 0x7FFF6F7F00000000, 0x7F001F, 0x3FF0FFF, - 0xAF7FE96FFFFFFEF, 0x5EF7F796AA96EA84, 0xFFFFBEE0FFFFBFF, + 0x3FF00FFFFFFFFFF, 0x31BFFFFFFFFFF, 0xE000000000000000, + 0xFFFF00801FFFFFFF, 0xFFFF00000001FFFF, 0xFFFF00000000003F, + 0x7FFFFF0000001F, 0x803FFFC00000007F, 0x3FF01FFFFFF0004, + 0xFFDFFFFFFFFFFFFF, 0x4FFFFFFFFF00F0, 0x17FFDE1F, 0xC0FFFFFFFFFBFFFF, 0x3, + 0xFFFF01FFBFFFBD7F, 0x3FF07FFFFFFFFFF, 0xFBEDFDFFFFF99FEF, + 0x1F1FCFE081399F, 0x3C3FF07FF, 0x3FF00BF, 0xFF3FFFFFFFFFFFFF, 0x3F000001, + 0x3FF0011, 0x1FFFFFFFFFFFFFF, 0x3FF, 0x3FF0FFFE7FFFFFF, 0x7F, + 0xFFFFFFFF00000000, 0x800003FFFFFFFFFF, 0xF9BFFFFFFF6FF27F, 0x3FF000F, + 0xFFFFFCFF00000000, 0x1BFCFFFFFF, 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFF0080, + 0xFFFF000023FFFFFF, 0xFF7FFFFFFFFFFDFF, 0xFFFC000003FF0001, + 0x7FFEFFFFFCFFFF, 0xB47FFFFFFFFFFB7F, 0xFFFFFDBF03FF00FF, 0x3FF01FB7FFF, + 0x7FFFFF00000000, 0xC7FFFFFFFFFDFFFF, 0x3FF0007, 0x1000000000000, + 0x3FFFFFF, 0x7FFFFFFFFFFF, 0xF, 0xFFFFFFFFFFFF0000, 0x1FFFFFFFFFFFF, + 0xFFFFFFFFFFFF, 0x3FFFFF, 0xFFFF03FF7FFFFFFF, 0x1F3FFFFFFF03FF, + 0xE0FFFFF803FF000F, 0xFFFF, 0xFFFFFFFFFFFF87FF, 0xFFFF80FF, + 0x3001B00000000, 0xFFFFFFFFFFFFFF, 0x6FEF000000000000, 0x40007FFFFFFFF, + 0xFFFF00F000270000, 0xFFFFFFFFFFFFFFF, 0x1FFF07FFFFFFFFFF, 0x63FF01FF, + 0xFFFF3FFFFFFFFFFF, 0xF807E3E000000000, 0x3C0000000FE7, 0x1C, + 0xFFFFFFFFFFDFFFFF, 0xEBFFDE64DFFFFFFF, 0xFFFFFFFFFFFFFFEF, + 0x7BFFFFFFDFDFE7BF, 0xFFFFFFFFFFFDFC5F, 0xFFFFFF3FFFFFFFFF, + 0xF7FFFFFFF7FFFFFD, 0xFFDFFFFFFFDFFFFF, 0xFFFF7FFFFFFF7FFF, + 0xFFFFFDFFFFFFFDFF, 0xFFFFFFFFFFFFCFF7, 0xF87FFFFFFFFFFFFF, + 0x201FFFFFFFFFFF, 0xFFFEF8000010, 0x7E07FFFFFFF, 0xFFFF07DBF9FFFF7F, + 0x3FFFFFFFFFFF, 0x8000, 0x3FFF1FFFFFFFFFFF, 0x43FF, 0x7FFFFFFF0000, + 0x3FFFFFFFFFFFFFF, 0x3FFFFFFFFFF0000, 0x7FFF6F7F00000000, 0x7F001F, + 0x3FF0FFF, 0xAF7FE96FFFFFFEF, 0x5EF7F796AA96EA84, 0xFFFFBEE0FFFFBFF, 0x3FF000000000000, 0xFFFFFFFF, 0xFFFF0003FFFFFFFF, 0x1FFFFFFFF, - 0x3FFFFFFF, 0x7FF, 0xFFFFFFFFFFFF, + 0x3FFFFFFF, 0xFFFFFFFFFFFF07FF, ], }; @@ -336,7 +340,7 @@ pub const XID_START: &'static ::ucd_trie::TrieSet = &::ucd_trie::TrieSet { ], tree3_level1: &[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 5, 9, 10, 5, 11, 12, 5, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 13, 14, 15, 7, 16, 17, 7, 18, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 7, 7, 13, 14, 15, 7, 16, 17, 7, 18, 19, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, @@ -345,61 +349,63 @@ pub const XID_START: &'static ::ucd_trie::TrieSet = &::ucd_trie::TrieSet { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ], tree3_level2: &[ 0, 1, 2, 3, 4, 5, 4, 4, 4, 4, 6, 7, 8, 9, 10, 11, 2, 2, 12, 13, 14, 15, 16, 4, 2, 2, 2, 2, 17, 18, 19, 4, 20, 21, 22, 23, 24, 4, 25, 4, 26, 27, 28, 29, 30, 31, 32, 4, 2, 33, 34, 34, 35, 4, 4, 4, 4, 4, 36, 4, 37, 38, - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 4, 50, 22, 51, 52, 4, 4, 5, - 53, 54, 55, 4, 4, 56, 57, 54, 58, 59, 4, 60, 61, 4, 4, 62, 4, 63, 64, 65, - 66, 67, 68, 69, 70, 71, 72, 4, 4, 4, 4, 73, 74, 75, 4, 76, 77, 78, 4, 4, - 4, 4, 79, 4, 4, 80, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 81, 4, 2, - 56, 2, 2, 2, 82, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 83, 84, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 56, 4, 4, 4, 4, 4, 4, 4, 4, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 22, 52, 53, 4, 4, 5, + 54, 55, 56, 4, 4, 57, 58, 55, 59, 60, 4, 61, 62, 4, 4, 63, 4, 64, 65, 66, + 67, 68, 69, 70, 71, 72, 73, 4, 4, 4, 4, 74, 75, 76, 4, 77, 78, 79, 4, 4, + 4, 4, 80, 81, 4, 82, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 83, 4, + 2, 57, 2, 2, 2, 84, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 85, 86, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 55, 87, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 61, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 62, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 2, 2, 2, 2, 2, 2, 2, 2, 72, 85, 86, 87, 54, 88, 75, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 2, 4, 4, 2, 89, 90, 91, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 4, 2, 2, 2, 2, 2, 2, 2, 2, 73, 88, 89, 90, 55, 91, 76, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 2, 4, 4, 2, 92, 93, 94, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 92, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 93, 33, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 2, 2, 2, 2, 2, 2, 2, 95, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 96, 33, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 94, 2, 2, 2, 2, 95, 96, 2, 2, 2, 2, 2, 97, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 97, 2, 2, 2, 2, 98, 99, 2, 2, 2, 2, 2, 100, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 2, 98, 99, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 100, 101, 102, 103, 104, 2, 2, - 2, 2, 105, 106, 107, 108, 109, 110, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 22, 4, 4, 4, 4, 4, 4, 4, 111, - 112, 4, 4, 4, 4, 87, 62, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 113, 2, 2, 2, 114, 2, 115, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 116, 117, 118, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 119, 2, 2, 2, 2, 2, 2, + 4, 4, 4, 4, 4, 4, 2, 101, 102, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 103, 104, 105, 106, 107, + 2, 2, 2, 2, 108, 109, 110, 111, 112, 113, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 114, 4, 4, 4, 115, 116, + 4, 4, 117, 118, 4, 4, 4, 4, 90, 63, 4, 4, 4, 4, 4, 4, 4, 119, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 120, 2, 2, 2, 121, 2, 122, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 123, 124, 125, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 126, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 72, 2, 2, 2, 10, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 127, 2, 2, 2, 10, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 120, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 128, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 121, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 129, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 122, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 123, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 130, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 131, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 55, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, ], tree3_level3: &[ 0xB7FFFF7FFFFFEFFF, 0x3FFF3FFF, 0xFFFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFF, 0, @@ -414,23 +420,25 @@ pub const XID_START: &'static ::ucd_trie::TrieSet = &::ucd_trie::TrieSet { 0x303FFFFFFFFFF, 0xFFFF00801FFFFFFF, 0xFFFF00000000003F, 0xFFFF000000000003, 0x7FFFFF0000001F, 0xFFFFFFFFFFFFF8, 0x26000000000000, 0xFFFFFFFFFFF8, 0x1FFFFFF0000, 0x7FFFFFFFF8, 0x47FFFFFFFF0090, - 0x7FFFFFFFFFFF8, 0x1400001E, 0xFFFFFFBFFFF, 0xFFFF01FFBFFFBD7F, + 0x7FFFFFFFFFFF8, 0x1400001E, 0x80000FFFFFFBFFFF, 0x1, 0xFFFF01FFBFFFBD7F, 0x23EDFDFFFFF99FE0, 0x3E0010000, 0x380000780, 0xFFFFFFFFFFFF, 0xB0, 0x7FFFFFFFFFFF, 0xF000000, 0x10, 0x10007FFFFFFFFFF, 0x7FFFFFF, 0x7F, 0xFFFFFFFFFFF, 0xFFFFFFFF00000000, 0x80000000FFFFFFFF, 0x8000FFFFFF6FF27F, 0x2, 0xFFFFFCFF00000000, 0xA0001FFFF, 0x407FFFFFFFFF801, 0xFFFFFFFFF0010000, 0xFFFF0000200003FF, 0x1FFFFFFFFFFFFFF, 0x7FFFFFFFFDFF, 0xFFFC000000000001, 0xFFFF, 0x1FFFFFFFFFB7F, 0xFFFFFDBF00000040, - 0x10003FF, 0x7FFFF00000000, 0x1000000000000, 0x3FFFFFF, 0xF, - 0xFFFFFFFFFFFF0000, 0x1FFFFFFFFFFFF, 0xFFFF00007FFFFFFF, + 0x10003FF, 0x7FFFF00000000, 0xFFFFFFFFDFFF4, 0x1000000000000, 0x3FFFFFF, + 0xF, 0xFFFFFFFFFFFF0000, 0x1FFFFFFFFFFFF, 0x7E, 0xFFFF00007FFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x3FFFFFFF0000, 0xE0FFFFF80000000F, 0x107FF, 0xFFF80000, 0xB00000000, 0xFFFFFFFFFFFFFF, 0x3FFFFF, 0x6FEF000000000000, - 0x7FFFFFFFF, 0xFFFF00F000070000, 0xFFFFFFFFFFFFFFF, 0x1FFF07FFFFFFFFFF, - 0x3FF01FF, 0xFFFFFFFFFFDFFFFF, 0xEBFFDE64DFFFFFFF, 0xFFFFFFFFFFFFFFEF, - 0x7BFFFFFFDFDFE7BF, 0xFFFFFFFFFFFDFC5F, 0xFFFFFF3FFFFFFFFF, - 0xF7FFFFFFF7FFFFFD, 0xFFDFFFFFFFDFFFFF, 0xFFFF7FFFFFFF7FFF, - 0xFFFFFDFFFFFFFDFF, 0xFF7, 0x3F801FFFFFFFFFFF, 0x4000, 0x7FFF6F7F00000000, - 0x1F, 0x80F, 0xAF7FE96FFFFFFEF, 0x5EF7F796AA96EA84, 0xFFFFBEE0FFFFBFF, - 0xFFFFFFFF, 0xFFFF0003FFFFFFFF, 0x1FFFFFFFF, 0x3FFFFFFF, 0x7FF, + 0x40007FFFFFFFF, 0xFFFF00F000270000, 0xFFFFFFFFFFFFFFF, + 0x1FFF07FFFFFFFFFF, 0x3FF01FF, 0xFFFFFFFFFFDFFFFF, 0xEBFFDE64DFFFFFFF, + 0xFFFFFFFFFFFFFFEF, 0x7BFFFFFFDFDFE7BF, 0xFFFFFFFFFFFDFC5F, + 0xFFFFFF3FFFFFFFFF, 0xF7FFFFFFF7FFFFFD, 0xFFDFFFFFFFDFFFFF, + 0xFFFF7FFFFFFF7FFF, 0xFFFFFDFFFFFFFDFF, 0xFF7, 0x7E07FFFFFFF, + 0xFFFF000000000000, 0x3FFFFFFFFFFF, 0x3F801FFFFFFFFFFF, 0x4000, + 0xFFFFFFF0000, 0x7FFF6F7F00000000, 0x1F, 0x80F, 0xAF7FE96FFFFFFEF, + 0x5EF7F796AA96EA84, 0xFFFFBEE0FFFFBFF, 0xFFFFFFFF, 0x3FFFFFFFFFFFFFF, + 0xFFFF0003FFFFFFFF, 0x1FFFFFFFF, 0x3FFFFFFF, 0xFFFFFFFFFFFF07FF, ], }; diff --git a/bash-5.1/vendor/unicode-width/.cargo-checksum.json b/bash-5.1/vendor/unicode-width/.cargo-checksum.json new file mode 100644 index 0000000..5c7b922 --- /dev/null +++ b/bash-5.1/vendor/unicode-width/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"23860c2a7b5d96b21569afedf033469bab9fe14a1b24a35068b8641c578ce24d","Cargo.toml":"f22e31fb3559e916864820719a09ab3adbf80301440e1702acf827210bbf76df","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"8a041a4305fb318f5c2cb284046f8480796521d0e829023b0441b5e8469490eb","scripts/unicode.py":"0c53095ef99395338399f9ad218b4481cffcf63774fd61871ed32efb242419f8","src/lib.rs":"38c44436eac069bd8d11203f31ecfef8adfe92da1fce19ba00bdd25aa3fbbe20","src/tables.rs":"c6ddb420c289517bb92973199fd2987b9608f29fc10bb33b5290f39b301ce92f","src/tests.rs":"ff9f331210861ba78040f119a0f6ccfacf5b2ca1ebee430784de0858fad01860"},"package":"c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"} \ No newline at end of file diff --git a/bash-5.1/vendor/unicode-width/COPYRIGHT b/bash-5.1/vendor/unicode-width/COPYRIGHT new file mode 100644 index 0000000..b286ec1 --- /dev/null +++ b/bash-5.1/vendor/unicode-width/COPYRIGHT @@ -0,0 +1,7 @@ +Licensed under the Apache License, Version 2.0 +<LICENSE-APACHE or +http://www.apache.org/licenses/LICENSE-2.0> or the MIT +license <LICENSE-MIT or http://opensource.org/licenses/MIT>, +at your option. All files in the project carrying such +notice may not be copied, modified, or distributed except +according to those terms. diff --git a/bash-5.1/vendor/unicode-width/Cargo.toml b/bash-5.1/vendor/unicode-width/Cargo.toml new file mode 100644 index 0000000..77aded9 --- /dev/null +++ b/bash-5.1/vendor/unicode-width/Cargo.toml @@ -0,0 +1,60 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "unicode-width" +version = "0.1.10" +authors = [ + "kwantam <kwantam@gmail.com>", + "Manish Goregaokar <manishsmail@gmail.com>", +] +exclude = [ + "target/*", + "Cargo.lock", +] +description = """ +Determine displayed width of `char` and `str` types +according to Unicode Standard Annex #11 rules. +""" +homepage = "https://github.com/unicode-rs/unicode-width" +documentation = "https://unicode-rs.github.io/unicode-width" +readme = "README.md" +keywords = [ + "text", + "width", + "unicode", +] +license = "MIT/Apache-2.0" +repository = "https://github.com/unicode-rs/unicode-width" + +[dependencies.compiler_builtins] +version = "0.1" +optional = true + +[dependencies.core] +version = "1.0" +optional = true +package = "rustc-std-workspace-core" + +[dependencies.std] +version = "1.0" +optional = true +package = "rustc-std-workspace-std" + +[features] +bench = [] +default = [] +no_std = [] +rustc-dep-of-std = [ + "std", + "core", + "compiler_builtins", +] diff --git a/bash-5.1/vendor/unicode-width/LICENSE-APACHE b/bash-5.1/vendor/unicode-width/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/unicode-width/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/unicode-width/LICENSE-MIT b/bash-5.1/vendor/unicode-width/LICENSE-MIT new file mode 100644 index 0000000..e69282e --- /dev/null +++ b/bash-5.1/vendor/unicode-width/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2015 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/unicode-width/README.md b/bash-5.1/vendor/unicode-width/README.md new file mode 100644 index 0000000..595e163 --- /dev/null +++ b/bash-5.1/vendor/unicode-width/README.md @@ -0,0 +1,58 @@ +# unicode-width + +Determine displayed width of `char` and `str` types according to +[Unicode Standard Annex #11][UAX11] rules. + +[UAX11]: http://www.unicode.org/reports/tr11/ + +[![Build Status](https://travis-ci.org/unicode-rs/unicode-width.svg)](https://travis-ci.org/unicode-rs/unicode-width) + +[Documentation](https://unicode-rs.github.io/unicode-width/unicode_width/index.html) + +```rust +extern crate unicode_width; + +use unicode_width::UnicodeWidthStr; + +fn main() { + let teststr = "Hello, world!"; + let width = UnicodeWidthStr::width(teststr); + println!("{}", teststr); + println!("The above string is {} columns wide.", width); + let width = teststr.width_cjk(); + println!("The above string is {} columns wide (CJK).", width); +} +``` + +**NOTE:** The computed width values may not match the actual rendered column +width. For example, the woman scientist emoji comprises of a woman emoji, a +zero-width joiner and a microscope emoji. + +```rust +extern crate unicode_width; +use unicode_width::UnicodeWidthStr; + +fn main() { + assert_eq!(UnicodeWidthStr::width("👩"), 2); // Woman + assert_eq!(UnicodeWidthStr::width("🔬"), 2); // Microscope + assert_eq!(UnicodeWidthStr::width("👩‍🔬"), 4); // Woman scientist +} +``` + +See [Unicode Standard Annex #11][UAX11] for precise details on what is and isn't +covered by this crate. + +## features + +unicode-width does not depend on libstd, so it can be used in crates +with the `#![no_std]` attribute. + +## crates.io + +You can use this package in your project by adding the following +to your `Cargo.toml`: + +```toml +[dependencies] +unicode-width = "0.1.7" +``` diff --git a/bash-5.1/vendor/unicode-width/scripts/unicode.py b/bash-5.1/vendor/unicode-width/scripts/unicode.py new file mode 100755 index 0000000..2efb0b6 --- /dev/null +++ b/bash-5.1/vendor/unicode-width/scripts/unicode.py @@ -0,0 +1,505 @@ +#!/usr/bin/env python3 +# +# Copyright 2011-2022 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +# This script uses the following Unicode tables: +# - EastAsianWidth.txt +# - ReadMe.txt +# - UnicodeData.txt +# +# Since this should not require frequent updates, we just store this +# out-of-line and check the generated module into git. + +import enum +import math +import os +import re +import sys + +NUM_CODEPOINTS = 0x110000 +"""An upper bound for which `range(0, NUM_CODEPOINTS)` contains Unicode's codespace.""" + +MAX_CODEPOINT_BITS = math.ceil(math.log2(NUM_CODEPOINTS - 1)) +"""The maximum number of bits required to represent a Unicode codepoint.""" + + +class OffsetType(enum.IntEnum): + """Represents the data type of a lookup table's offsets. Each variant's value represents the + number of bits required to represent that variant's type.""" + + U2 = 2 + """Offsets are 2-bit unsigned integers, packed four-per-byte.""" + U4 = 4 + """Offsets are 4-bit unsigned integers, packed two-per-byte.""" + U8 = 8 + """Each offset is a single byte (u8).""" + + +TABLE_CFGS = [ + (13, MAX_CODEPOINT_BITS, OffsetType.U8), + (6, 13, OffsetType.U8), + (0, 6, OffsetType.U2), +] +"""Represents the format of each level of the multi-level lookup table. +A level's entry is of the form `(low_bit, cap_bit, offset_type)`. +This means that every sub-table in that level is indexed by bits `low_bit..cap_bit` of the +codepoint and those tables offsets are stored according to `offset_type`. + +If this is edited, you must ensure that `emit_module` reflects your changes.""" + +MODULE_FILENAME = "tables.rs" +"""The filename of the emitted Rust module (will be created in the working directory)""" + +Codepoint = int +BitPos = int + + +def fetch_open(filename: str): + """Opens `filename` and return its corresponding file object. If `filename` isn't on disk, + fetches it from `http://www.unicode.org/Public/UNIDATA/`. Exits with code 1 on failure.""" + if not os.path.exists(os.path.basename(filename)): + os.system(f"curl -O http://www.unicode.org/Public/UNIDATA/{filename}") + try: + return open(filename, encoding="utf-8") + except OSError: + sys.stderr.write(f"cannot load {filename}") + sys.exit(1) + + +def load_unicode_version() -> "tuple[int, int, int]": + """Returns the current Unicode version by fetching and processing `ReadMe.txt`.""" + with fetch_open("ReadMe.txt") as readme: + pattern = r"for Version (\d+)\.(\d+)\.(\d+) of the Unicode" + return tuple(map(int, re.search(pattern, readme.read()).groups())) + + +class EffectiveWidth(enum.IntEnum): + """Represents the width of a Unicode character. All East Asian Width classes resolve into + either `EffectiveWidth.NARROW`, `EffectiveWidth.WIDE`, or `EffectiveWidth.AMBIGUOUS`.""" + + ZERO = 0 + """ Zero columns wide. """ + NARROW = 1 + """ One column wide. """ + WIDE = 2 + """ Two columns wide. """ + AMBIGUOUS = 3 + """ Two columns wide in a CJK context. One column wide in all other contexts. """ + + +def load_east_asian_widths() -> "list[EffectiveWidth]": + """Return a list of effective widths, indexed by codepoint. + Widths are determined by fetching and parsing `EastAsianWidth.txt`. + + `Neutral`, `Narrow`, and `Halfwidth` characters are assigned `EffectiveWidth.NARROW`. + + `Wide` and `Fullwidth` characters are assigned `EffectiveWidth.WIDE`. + + `Ambiguous` chracters are assigned `EffectiveWidth.AMBIGUOUS`.""" + with fetch_open("EastAsianWidth.txt") as eaw: + # matches a width assignment for a single codepoint, i.e. "1F336;N # ..." + single = re.compile(r"^([0-9A-F]+);(\w+) +# (\w+)") + # matches a width assignment for a range of codepoints, i.e. "3001..3003;W # ..." + multiple = re.compile(r"^([0-9A-F]+)\.\.([0-9A-F]+);(\w+) +# (\w+)") + # map between width category code and condensed width + width_codes = { + **{c: EffectiveWidth.NARROW for c in ["N", "Na", "H"]}, + **{c: EffectiveWidth.WIDE for c in ["W", "F"]}, + "A": EffectiveWidth.AMBIGUOUS, + } + + width_map = [] + current = 0 + for line in eaw.readlines(): + raw_data = None # (low, high, width) + if match := single.match(line): + raw_data = (match.group(1), match.group(1), match.group(2)) + elif match := multiple.match(line): + raw_data = (match.group(1), match.group(2), match.group(3)) + else: + continue + low = int(raw_data[0], 16) + high = int(raw_data[1], 16) + width = width_codes[raw_data[2]] + + assert current <= high + while current <= high: + # Some codepoints don't fall into any of the ranges in EastAsianWidth.txt. + # All such codepoints are implicitly given Neural width (resolves to narrow) + width_map.append(EffectiveWidth.NARROW if current < low else width) + current += 1 + + while len(width_map) < NUM_CODEPOINTS: + # Catch any leftover codepoints and assign them implicit Neutral/narrow width. + width_map.append(EffectiveWidth.NARROW) + + return width_map + + +def load_zero_widths() -> "list[bool]": + """Returns a list `l` where `l[c]` is true if codepoint `c` is considered a zero-width + character. `c` is considered a zero-width character if `c` is in general categories + `Cc`, `Cf`, `Mn`, or `Me` (determined by fetching and processing `UnicodeData.txt`).""" + with fetch_open("UnicodeData.txt") as categories: + zw_map = [] + current = 0 + for line in categories.readlines(): + if len(raw_data := line.split(";")) != 15: + continue + [codepoint, name, cat_code] = [ + int(raw_data[0], 16), + raw_data[1], + raw_data[2], + ] + zero_width = cat_code in ["Cc", "Cf", "Mn", "Me"] + + assert current <= codepoint + while current <= codepoint: + if name.endswith(", Last>") or current == codepoint: + # if name ends with Last, we backfill the width value to all codepoints since + # the previous codepoint (aka the start of the range) + zw_map.append(zero_width) + else: + # unassigned characters are implicitly given Neutral width, which is nonzero + zw_map.append(False) + current += 1 + + while len(zw_map) < NUM_CODEPOINTS: + # Catch any leftover codepoints. They must be unassigned (so nonzero width) + zw_map.append(False) + + return zw_map + + +class Bucket: + """A bucket contains a group of codepoints and an ordered width list. If one bucket's width + list overlaps with another's width list, those buckets can be merged via `try_extend`.""" + + def __init__(self): + """Creates an empty bucket.""" + self.entry_set = set() + self.widths = [] + + def append(self, codepoint: Codepoint, width: EffectiveWidth): + """Adds a codepoint/width pair to the bucket, and appends `width` to the width list.""" + self.entry_set.add((codepoint, width)) + self.widths.append(width) + + def try_extend(self, attempt: "Bucket") -> bool: + """If either `self` or `attempt`'s width list starts with the other bucket's width list, + set `self`'s width list to the longer of the two, add all of `attempt`'s codepoints + into `self`, and return `True`. Otherwise, return `False`.""" + (less, more) = (self.widths, attempt.widths) + if len(self.widths) > len(attempt.widths): + (less, more) = (attempt.widths, self.widths) + if less != more[: len(less)]: + return False + self.entry_set |= attempt.entry_set + self.widths = more + return True + + def entries(self) -> "list[tuple[Codepoint, EffectiveWidth]]": + """Return a list of the codepoint/width pairs in this bucket, sorted by codepoint.""" + result = list(self.entry_set) + result.sort() + return result + + def width(self) -> "EffectiveWidth": + """If all codepoints in this bucket have the same width, return that width; otherwise, + return `None`.""" + if len(self.widths) == 0: + return None + potential_width = self.widths[0] + for width in self.widths[1:]: + if potential_width != width: + return None + return potential_width + + +def make_buckets(entries, low_bit: BitPos, cap_bit: BitPos) -> "list[Bucket]": + """Partitions the `(Codepoint, EffectiveWidth)` tuples in `entries` into `Bucket`s. All + codepoints with identical bits from `low_bit` to `cap_bit` (exclusive) are placed in the + same bucket. Returns a list of the buckets in increasing order of those bits.""" + num_bits = cap_bit - low_bit + assert num_bits > 0 + buckets = [Bucket() for _ in range(0, 2 ** num_bits)] + mask = (1 << num_bits) - 1 + for (codepoint, width) in entries: + buckets[(codepoint >> low_bit) & mask].append(codepoint, width) + return buckets + + +class Table: + """Represents a lookup table. Each table contains a certain number of subtables; each + subtable is indexed by a contiguous bit range of the codepoint and contains a list + of `2**(number of bits in bit range)` entries. (The bit range is the same for all subtables.) + + Typically, tables contain a list of buckets of codepoints. Bucket `i`'s codepoints should + be indexed by sub-table `i` in the next-level lookup table. The entries of this table are + indexes into the bucket list (~= indexes into the sub-tables of the next-level table.) The + key to compression is that two different buckets in two different sub-tables may have the + same width list, which means that they can be merged into the same bucket. + + If no bucket contains two codepoints with different widths, calling `indices_to_widths` will + discard the buckets and convert the entries into `EffectiveWidth` values.""" + + def __init__( + self, entry_groups, low_bit: BitPos, cap_bit: BitPos, offset_type: OffsetType + ): + """Create a lookup table with a sub-table for each `(Codepoint, EffectiveWidth)` iterator + in `entry_groups`. Each sub-table is indexed by codepoint bits in `low_bit..cap_bit`, + and each table entry is represented in the format specified by `offset_type`. Asserts + that this table is actually representable with `offset_type`.""" + self.low_bit = low_bit + self.cap_bit = cap_bit + self.offset_type = offset_type + self.entries = [] + self.indexed = [] + + buckets = [] + for entries in entry_groups: + buckets.extend(make_buckets(entries, self.low_bit, self.cap_bit)) + + for bucket in buckets: + for (i, existing) in enumerate(self.indexed): + if existing.try_extend(bucket): + self.entries.append(i) + break + else: + self.entries.append(len(self.indexed)) + self.indexed.append(bucket) + + # Validate offset type + for index in self.entries: + assert index < (1 << int(self.offset_type)) + + def indices_to_widths(self): + """Destructively converts the indices in this table to the `EffectiveWidth` values of + their buckets. Assumes that no bucket contains codepoints with different widths.""" + self.entries = list(map(lambda i: int(self.indexed[i].width()), self.entries)) + del self.indexed + + def buckets(self): + """Returns an iterator over this table's buckets.""" + return self.indexed + + def to_bytes(self) -> "list[int]": + """Returns this table's entries as a list of bytes. The bytes are formatted according to + the `OffsetType` which the table was created with, converting any `EffectiveWidth` entries + to their enum variant's integer value. For example, with `OffsetType.U2`, each byte will + contain four packed 2-bit entries.""" + entries_per_byte = 8 // int(self.offset_type) + byte_array = [] + for i in range(0, len(self.entries), entries_per_byte): + byte = 0 + for j in range(0, entries_per_byte): + byte |= self.entries[i + j] << (j * int(self.offset_type)) + byte_array.append(byte) + return byte_array + + +def make_tables( + table_cfgs: "list[tuple[BitPos, BitPos, OffsetType]]", entries +) -> "list[Table]": + """Creates a table for each configuration in `table_cfgs`, with the first config corresponding + to the top-level lookup table, the second config corresponding to the second-level lookup + table, and so forth. `entries` is an iterator over the `(Codepoint, EffectiveWidth)` pairs + to include in the top-level table.""" + tables = [] + entry_groups = [entries] + for (low_bit, cap_bit, offset_type) in table_cfgs: + table = Table(entry_groups, low_bit, cap_bit, offset_type) + entry_groups = map(lambda bucket: bucket.entries(), table.buckets()) + tables.append(table) + return tables + + +def emit_module( + out_name: str, unicode_version: "tuple[int, int, int]", tables: "list[Table]" +): + """Outputs a Rust module to `out_name` using table data from `tables`. + If `TABLE_CFGS` is edited, you may need to edit the included code for `lookup_width`.""" + if os.path.exists(out_name): + os.remove(out_name) + with open(out_name, "w", newline="\n", encoding="utf-8") as module: + module.write( + """// Copyright 2012-2022 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly +""" + ) + module.write( + f""" +/// The version of [Unicode](http://www.unicode.org/) +/// that this version of unicode-width is based on. +pub const UNICODE_VERSION: (u8, u8, u8) = {unicode_version}; +""" + ) + + module.write( + """ +pub mod charwidth { + use core::option::Option::{self, None, Some}; + + /// Returns the [UAX #11](https://www.unicode.org/reports/tr11/) based width of `c` by + /// consulting a multi-level lookup table. + /// If `is_cjk == true`, ambiguous width characters are treated as double width; otherwise, + /// they're treated as single width. + /// + /// # Maintenance + /// The tables themselves are autogenerated but this function is hardcoded. You should have + /// nothing to worry about if you re-run `unicode.py` (for example, when updating Unicode.) + /// However, if you change the *actual structure* of the lookup tables (perhaps by editing the + /// `TABLE_CFGS` global in `unicode.py`) you must ensure that this code reflects those changes. + #[inline] + fn lookup_width(c: char, is_cjk: bool) -> usize { + let cp = c as usize; + + let t1_offset = TABLES_0[cp >> 13 & 0xFF]; + + // Each sub-table in TABLES_1 is 7 bits, and each stored entry is a byte, + // so each sub-table is 128 bytes in size. + // (Sub-tables are selected using the computed offset from the previous table.) + let t2_offset = TABLES_1[128 * usize::from(t1_offset) + (cp >> 6 & 0x7F)]; + + // Each sub-table in TABLES_2 is 6 bits, but each stored entry is 2 bits. + // This is accomplished by packing four stored entries into one byte. + // So each sub-table is 2**(6-2) == 16 bytes in size. + // Since this is the last table, each entry represents an encoded width. + let packed_widths = TABLES_2[16 * usize::from(t2_offset) + (cp >> 2 & 0xF)]; + + // Extract the packed width + let width = packed_widths >> (2 * (cp & 0b11)) & 0b11; + + // A width of 3 signifies that the codepoint is ambiguous width. + if width == 3 { + if is_cjk { + 2 + } else { + 1 + } + } else { + width.into() + } + } +""" + ) + + module.write( + """ + /// Returns the [UAX #11](https://www.unicode.org/reports/tr11/) based width of `c`, or + /// `None` if `c` is a control character other than `'\\x00'`. + /// If `is_cjk == true`, ambiguous width characters are treated as double width; otherwise, + /// they're treated as single width. + #[inline] + pub fn width(c: char, is_cjk: bool) -> Option<usize> { + if c < '\\u{7F}' { + if c >= '\\u{20}' { + // U+0020 to U+007F (exclusive) are single-width ASCII codepoints + Some(1) + } else if c == '\\0' { + // U+0000 *is* a control code, but it's special-cased + Some(0) + } else { + // U+0001 to U+0020 (exclusive) are control codes + None + } + } else if c >= '\\u{A0}' { + // No characters >= U+00A0 are control codes, so we can consult the lookup tables + Some(lookup_width(c, is_cjk)) + } else { + // U+007F to U+00A0 (exclusive) are control codes + None + } + } +""" + ) + + subtable_count = 1 + for (i, table) in enumerate(tables): + new_subtable_count = len(table.buckets()) + if i == len(tables) - 1: + table.indices_to_widths() # for the last table, indices == widths + byte_array = table.to_bytes() + module.write( + f""" + /// Autogenerated. {subtable_count} sub-table(s). Consult [`lookup_width`] for layout info. + static TABLES_{i}: [u8; {len(byte_array)}] = [""" + ) + for (j, byte) in enumerate(byte_array): + # Add line breaks for every 15th entry (chosen to match what rustfmt does) + if j % 15 == 0: + module.write("\n ") + module.write(f" 0x{byte:02X},") + module.write("\n ];\n") + subtable_count = new_subtable_count + module.write("}\n") + + +def main(module_filename: str): + """Obtain character data from the latest version of Unicode, transform it into a multi-level + lookup table for character width, and write a Rust module utilizing that table to + `module_filename`. + + We obey the following rules in decreasing order of importance: + - The soft hyphen (`U+00AD`) is single-width. + - Hangul Jamo medial vowels & final consonants (`U+1160..=U+11FF`) are zero-width. + - All codepoints in general categories `Cc`, `Cf`, `Mn`, and `Me` are zero-width. + - All codepoints with an East Asian Width of `Ambigous` are ambiguous-width. + - All codepoints with an East Asian Width of `Wide` or `Fullwidth` are double-width. + - All other codepoints (including unassigned codepoints and codepoints with an East Asian Width + of `Neutral`, `Narrow`, or `Halfwidth`) are single-width. + + These rules are based off of Markus Kuhn's free `wcwidth()` implementation: + http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c""" + version = load_unicode_version() + print(f"Generating module for Unicode {version[0]}.{version[1]}.{version[2]}") + + eaw_map = load_east_asian_widths() + zw_map = load_zero_widths() + + # Characters marked as zero-width in zw_map should be zero-width in the final map + width_map = list( + map(lambda x: EffectiveWidth.ZERO if x[1] else x[0], zip(eaw_map, zw_map)) + ) + + # Override for soft hyphen + width_map[0x00AD] = EffectiveWidth.NARROW + + # Override for Hangul Jamo medial vowels & final consonants + for i in range(0x1160, 0x11FF + 1): + width_map[i] = EffectiveWidth.ZERO + + tables = make_tables(TABLE_CFGS, enumerate(width_map)) + + print("------------------------") + total_size = 0 + for (i, table) in enumerate(tables): + size_bytes = len(table.to_bytes()) + print(f"Table {i} Size: {size_bytes} bytes") + total_size += size_bytes + print("------------------------") + print(f" Total Size: {total_size} bytes") + + emit_module(module_filename, version, tables) + print(f'Wrote to "{module_filename}"') + + +if __name__ == "__main__": + main(MODULE_FILENAME) diff --git a/bash-5.1/vendor/unicode-width/src/lib.rs b/bash-5.1/vendor/unicode-width/src/lib.rs new file mode 100644 index 0000000..1ee35c8 --- /dev/null +++ b/bash-5.1/vendor/unicode-width/src/lib.rs @@ -0,0 +1,131 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Determine displayed width of `char` and `str` types according to +//! [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) +//! rules. +//! +//! ```rust +//! extern crate unicode_width; +//! +//! use unicode_width::UnicodeWidthStr; +//! +//! fn main() { +//! let teststr = "Hello, world!"; +//! let width = UnicodeWidthStr::width(teststr); +//! println!("{}", teststr); +//! println!("The above string is {} columns wide.", width); +//! let width = teststr.width_cjk(); +//! println!("The above string is {} columns wide (CJK).", width); +//! } +//! ``` +//! +//! # features +//! +//! unicode-width supports a `no_std` feature. This eliminates dependence +//! on std, and instead uses equivalent functions from core. +//! +//! # crates.io +//! +//! You can use this package in your project by adding the following +//! to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! unicode-width = "0.1.5" +//! ``` + +#![deny(missing_docs, unsafe_code)] +#![doc(html_logo_url = "https://unicode-rs.github.io/unicode-rs_sm.png", + html_favicon_url = "https://unicode-rs.github.io/unicode-rs_sm.png")] + +#![cfg_attr(feature = "bench", feature(test))] +#![no_std] + +#[cfg(test)] +#[macro_use] +extern crate std; + +#[cfg(feature = "bench")] +extern crate test; + +use tables::charwidth as cw; +pub use tables::UNICODE_VERSION; + +use core::ops::Add; + +mod tables; + +#[cfg(test)] +mod tests; + +/// Methods for determining displayed width of Unicode characters. +pub trait UnicodeWidthChar { + /// Returns the character's displayed width in columns, or `None` if the + /// character is a control character other than `'\x00'`. + /// + /// This function treats characters in the Ambiguous category according + /// to [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) + /// as 1 column wide. This is consistent with the recommendations for non-CJK + /// contexts, or when the context cannot be reliably determined. + fn width(self) -> Option<usize>; + + /// Returns the character's displayed width in columns, or `None` if the + /// character is a control character other than `'\x00'`. + /// + /// This function treats characters in the Ambiguous category according + /// to [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) + /// as 2 columns wide. This is consistent with the recommendations for + /// CJK contexts. + fn width_cjk(self) -> Option<usize>; +} + +impl UnicodeWidthChar for char { + #[inline] + fn width(self) -> Option<usize> { cw::width(self, false) } + + #[inline] + fn width_cjk(self) -> Option<usize> { cw::width(self, true) } +} + +/// Methods for determining displayed width of Unicode strings. +pub trait UnicodeWidthStr { + /// Returns the string's displayed width in columns. + /// + /// Control characters are treated as having zero width. + /// + /// This function treats characters in the Ambiguous category according + /// to [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) + /// as 1 column wide. This is consistent with the recommendations for + /// non-CJK contexts, or when the context cannot be reliably determined. + fn width<'a>(&'a self) -> usize; + + /// Returns the string's displayed width in columns. + /// + /// Control characters are treated as having zero width. + /// + /// This function treats characters in the Ambiguous category according + /// to [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) + /// as 2 column wide. This is consistent with the recommendations for + /// CJK contexts. + fn width_cjk<'a>(&'a self) -> usize; +} + +impl UnicodeWidthStr for str { + #[inline] + fn width(&self) -> usize { + self.chars().map(|c| cw::width(c, false).unwrap_or(0)).fold(0, Add::add) + } + + #[inline] + fn width_cjk(&self) -> usize { + self.chars().map(|c| cw::width(c, true).unwrap_or(0)).fold(0, Add::add) + } +} diff --git a/bash-5.1/vendor/unicode-width/src/tables.rs b/bash-5.1/vendor/unicode-width/src/tables.rs new file mode 100644 index 0000000..439c69c --- /dev/null +++ b/bash-5.1/vendor/unicode-width/src/tables.rs @@ -0,0 +1,540 @@ +// Copyright 2012-2022 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly + +/// The version of [Unicode](http://www.unicode.org/) +/// that this version of unicode-width is based on. +pub const UNICODE_VERSION: (u8, u8, u8) = (15, 0, 0); + +pub mod charwidth { + use core::option::Option::{self, None, Some}; + + /// Returns the [UAX #11](https://www.unicode.org/reports/tr11/) based width of `c` by + /// consulting a multi-level lookup table. + /// If `is_cjk == true`, ambiguous width characters are treated as double width; otherwise, + /// they're treated as single width. + /// + /// # Maintenance + /// The tables themselves are autogenerated but this function is hardcoded. You should have + /// nothing to worry about if you re-run `unicode.py` (for example, when updating Unicode.) + /// However, if you change the *actual structure* of the lookup tables (perhaps by editing the + /// `TABLE_CFGS` global in `unicode.py`) you must ensure that this code reflects those changes. + #[inline] + fn lookup_width(c: char, is_cjk: bool) -> usize { + let cp = c as usize; + + let t1_offset = TABLES_0[cp >> 13 & 0xFF]; + + // Each sub-table in TABLES_1 is 7 bits, and each stored entry is a byte, + // so each sub-table is 128 bytes in size. + // (Sub-tables are selected using the computed offset from the previous table.) + let t2_offset = TABLES_1[128 * usize::from(t1_offset) + (cp >> 6 & 0x7F)]; + + // Each sub-table in TABLES_2 is 6 bits, but each stored entry is 2 bits. + // This is accomplished by packing four stored entries into one byte. + // So each sub-table is 2**(6-2) == 16 bytes in size. + // Since this is the last table, each entry represents an encoded width. + let packed_widths = TABLES_2[16 * usize::from(t2_offset) + (cp >> 2 & 0xF)]; + + // Extract the packed width + let width = packed_widths >> (2 * (cp & 0b11)) & 0b11; + + // A width of 3 signifies that the codepoint is ambiguous width. + if width == 3 { + if is_cjk { + 2 + } else { + 1 + } + } else { + width.into() + } + } + + /// Returns the [UAX #11](https://www.unicode.org/reports/tr11/) based width of `c`, or + /// `None` if `c` is a control character other than `'\x00'`. + /// If `is_cjk == true`, ambiguous width characters are treated as double width; otherwise, + /// they're treated as single width. + #[inline] + pub fn width(c: char, is_cjk: bool) -> Option<usize> { + if c < '\u{7F}' { + if c >= '\u{20}' { + // U+0020 to U+007F (exclusive) are single-width ASCII codepoints + Some(1) + } else if c == '\0' { + // U+0000 *is* a control code, but it's special-cased + Some(0) + } else { + // U+0001 to U+0020 (exclusive) are control codes + None + } + } else if c >= '\u{A0}' { + // No characters >= U+00A0 are control codes, so we can consult the lookup tables + Some(lookup_width(c, is_cjk)) + } else { + // U+007F to U+00A0 (exclusive) are control codes + None + } + } + + /// Autogenerated. 1 sub-table(s). Consult [`lookup_width`] for layout info. + static TABLES_0: [u8; 256] = [ + 0x00, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, + 0x0E, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x0F, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x0F, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x10, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x12, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, + 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, + ]; + + /// Autogenerated. 19 sub-table(s). Consult [`lookup_width`] for layout info. + static TABLES_1: [u8; 2432] = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x06, 0x08, 0x06, 0x09, 0x0A, 0x0B, 0x0C, + 0x0D, 0x0E, 0x0F, 0x10, 0x06, 0x06, 0x06, 0x11, 0x12, 0x13, 0x14, 0x06, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x22, 0x24, 0x25, + 0x26, 0x27, 0x28, 0x29, 0x2A, 0x25, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, + 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x06, 0x3B, 0x3C, 0x0A, 0x0A, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x3D, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x06, 0x43, 0x06, 0x44, 0x06, 0x06, 0x06, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x06, 0x06, 0x4E, 0x06, 0x06, 0x06, 0x0A, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, + 0x56, 0x57, 0x58, 0x59, 0x06, 0x5A, 0x06, 0x06, 0x5B, 0x06, 0x5C, 0x5D, 0x5E, 0x5D, 0x5F, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x69, 0x6A, 0x06, 0x06, 0x06, 0x06, 0x06, 0x6B, + 0x06, 0x01, 0x06, 0x6C, 0x06, 0x06, 0x6D, 0x6E, 0x3B, 0x3B, 0x3B, 0x6F, 0x70, 0x71, 0x72, + 0x3B, 0x73, 0x3B, 0x74, 0x75, 0x76, 0x77, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x06, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x78, 0x79, 0x06, 0x06, 0x06, 0x06, 0x06, 0x7A, 0x7B, 0x7C, + 0x06, 0x06, 0x06, 0x06, 0x7D, 0x06, 0x06, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, + 0x86, 0x06, 0x06, 0x06, 0x87, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x88, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x89, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x8A, 0x8B, 0x06, 0x01, 0x71, 0x8C, 0x06, 0x8D, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x8E, 0x06, 0x06, 0x06, 0x8F, 0x06, 0x90, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x91, 0x06, 0x06, 0x92, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x93, 0x06, 0x06, 0x06, 0x06, 0x06, 0x94, 0x95, 0x06, 0x96, 0x97, 0x06, + 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0x2E, 0x06, 0xA1, 0x2C, 0xA2, 0x06, + 0x06, 0xA3, 0xA4, 0xA5, 0xA6, 0x06, 0x06, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0x06, 0xAC, 0x06, + 0x06, 0x06, 0xAD, 0x06, 0x06, 0x06, 0xAE, 0xAF, 0x06, 0xB0, 0xB1, 0xB2, 0xB3, 0x06, 0x06, + 0x06, 0x06, 0x06, 0xB4, 0x06, 0xB5, 0x06, 0xB6, 0xB7, 0xB8, 0x06, 0x06, 0x06, 0x06, 0xB9, + 0xBA, 0xBB, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x47, 0xBC, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0xBD, 0xBE, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xBF, 0xC0, 0xC1, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0xC2, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0xC3, 0xC4, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xC5, 0x3B, 0x3B, 0x3B, 0x3B, 0xC6, + 0xC7, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0xC8, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0xC9, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xCA, + 0xCB, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xCC, 0xCD, 0x06, 0x06, 0xCE, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xCF, 0xD0, + 0xD1, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xD2, 0x06, 0xBF, 0x06, 0xBE, 0x06, 0x06, 0x06, + 0x06, 0x06, 0xD3, 0xD4, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xD4, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xD5, 0x06, 0xD6, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0xD7, 0x06, 0x06, 0xD8, + 0xD9, 0xDA, 0xDB, 0x06, 0xDC, 0xDD, 0x06, 0x06, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0x3B, + 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0x3B, 0xE9, 0x3B, 0xEA, 0x06, 0x06, 0x06, 0xEB, 0x06, 0x06, + 0x06, 0x06, 0xEC, 0xED, 0x3B, 0x3B, 0x06, 0xEE, 0xEF, 0xF0, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, + 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0x3B, 0xE5, 0xF1, 0x0A, 0x06, 0x06, 0x0A, 0x0A, 0x0A, + 0x0B, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, 0x5D, + 0x5D, 0xF2, + ]; + + /// Autogenerated. 243 sub-table(s). Consult [`lookup_width`] for layout info. + static TABLES_2: [u8; 3888] = [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5D, 0xD7, 0x77, 0x75, 0xFF, + 0xF7, 0x7F, 0xFF, 0x55, 0x75, 0x55, 0x55, 0x57, 0xD5, 0x57, 0xF5, 0x5F, 0x75, 0x7F, 0x5F, + 0xF7, 0xD5, 0x7F, 0x77, 0x5D, 0x55, 0x55, 0x55, 0xDD, 0x55, 0xD5, 0x55, 0x55, 0xF5, 0xD5, + 0x55, 0xFD, 0x55, 0x57, 0xD5, 0x7F, 0x57, 0xFF, 0x5D, 0xF5, 0x55, 0x55, 0x55, 0x55, 0xF5, + 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x75, 0x77, 0x77, 0x77, 0x57, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x5D, 0x55, 0x55, + 0x55, 0x5D, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xD7, 0xFD, 0x5D, 0x57, 0x55, + 0xFF, 0xDD, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0xFD, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0x5F, 0x55, 0xFD, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, + 0x5F, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x5D, + 0x55, 0x55, 0x55, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x5D, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x15, 0x00, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x41, 0x10, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x00, 0x50, 0x55, 0x55, 0x00, 0x00, 0x40, 0x54, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, + 0x55, 0x55, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x00, 0x10, 0x00, + 0x14, 0x04, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x51, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x05, 0x00, 0x00, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x05, 0x10, 0x00, 0x00, 0x01, 0x01, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x50, 0x55, 0x00, 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, + 0x54, 0x01, 0x00, 0x54, 0x51, 0x01, 0x00, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x54, 0x01, 0x54, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x45, 0x41, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x54, 0x41, 0x15, 0x14, 0x50, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x50, 0x51, 0x55, 0x55, 0x01, 0x10, 0x54, 0x51, 0x55, 0x55, 0x55, 0x55, 0x05, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x00, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x14, 0x01, 0x54, 0x55, 0x51, 0x55, 0x41, 0x55, + 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0x55, 0x55, 0x51, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0x54, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x04, 0x54, 0x05, 0x04, + 0x50, 0x55, 0x41, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, + 0x55, 0x50, 0x55, 0x55, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x50, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x54, + 0x01, 0x54, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x45, 0x55, 0x05, 0x44, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x51, 0x00, 0x40, 0x55, 0x55, 0x15, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x51, 0x00, 0x00, 0x54, 0x55, 0x55, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x50, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x11, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, 0x00, 0x00, 0x40, 0x00, 0x04, 0x55, 0x01, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x55, 0x45, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, 0x04, 0x00, 0x41, 0x41, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x50, 0x05, 0x54, 0x55, 0x55, 0x55, 0x01, 0x54, 0x55, 0x55, 0x45, 0x41, + 0x55, 0x51, 0x55, 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x10, 0x00, 0x50, 0x55, 0x45, 0x01, 0x00, 0x00, 0x55, 0x55, 0x51, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x41, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x40, 0x15, 0x54, 0x55, 0x45, 0x55, 0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, + 0x14, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x45, 0x00, 0x40, 0x44, 0x01, 0x00, 0x54, 0x15, 0x00, 0x00, 0x14, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x04, 0x40, 0x54, 0x45, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x55, 0x55, 0x55, + 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x50, 0x10, 0x50, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, 0x50, 0x11, 0x50, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, + 0x05, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x54, 0x51, + 0x55, 0x54, 0x50, 0x55, 0x55, 0x55, 0x15, 0x00, 0xD7, 0x7F, 0x5F, 0x5F, 0x7F, 0xFF, 0x05, + 0x40, 0xF7, 0x5D, 0xD5, 0x75, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x04, + 0x00, 0x00, 0x55, 0x57, 0x55, 0xD5, 0xFD, 0x57, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x57, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x54, 0x55, 0x55, 0x55, 0xD5, 0x5D, 0x5D, 0x55, 0xD5, 0x75, 0x55, + 0x55, 0x7D, 0x75, 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xD5, 0x57, + 0xD5, 0x7F, 0xFF, 0xFF, 0xFF, 0x55, 0xFF, 0xFF, 0x5F, 0x55, 0x55, 0x55, 0x5D, 0x55, 0xFF, + 0xFF, 0x5F, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x5F, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x75, 0x57, 0x55, 0x55, 0x55, 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xF7, 0xD5, 0xD7, + 0xD5, 0x5D, 0x5D, 0x75, 0xFD, 0xD7, 0xDD, 0xFF, 0x77, 0x55, 0xFF, 0x55, 0x5F, 0x55, 0x55, + 0x57, 0x57, 0x75, 0x55, 0x55, 0x55, 0x5F, 0xFF, 0xF5, 0xF5, 0x55, 0x55, 0x55, 0x55, 0xF5, + 0xF5, 0x55, 0x55, 0x55, 0x5D, 0x5D, 0x55, 0x55, 0x5D, 0x55, 0x55, 0x55, 0x55, 0x55, 0xD5, + 0x55, 0x55, 0x55, 0x55, 0x75, 0x55, 0xA5, 0x55, 0x55, 0x55, 0x69, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xA9, 0x56, 0x96, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x55, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0x55, 0x55, 0x55, 0xFF, 0xFF, 0xFF, 0xFF, 0xF5, 0x5F, 0x55, 0x55, 0xDF, + 0xFF, 0x5F, 0x55, 0xF5, 0xF5, 0x55, 0x5F, 0x5F, 0xF5, 0xD7, 0xF5, 0x5F, 0x55, 0x55, 0x55, + 0xF5, 0x5F, 0x55, 0xD5, 0x55, 0x55, 0x55, 0x69, 0x55, 0x7D, 0x5D, 0xF5, 0x55, 0x5A, 0x55, + 0x77, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x77, 0x55, 0xAA, 0xAA, 0xAA, 0x55, + 0x55, 0x55, 0xDF, 0xDF, 0x7F, 0xDF, 0x55, 0x55, 0x55, 0x95, 0x55, 0x55, 0x55, 0x55, 0x95, + 0x55, 0x55, 0xF5, 0x59, 0x55, 0xA5, 0x55, 0x55, 0x55, 0x55, 0xE9, 0x55, 0xFA, 0xFF, 0xEF, + 0xFF, 0xFE, 0xFF, 0xFF, 0xDF, 0x55, 0xEF, 0xFF, 0xAF, 0xFB, 0xEF, 0xFB, 0x55, 0x59, 0xA5, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x56, 0x55, 0x55, 0x55, 0x55, 0x5D, 0x55, 0x55, + 0x55, 0x66, 0x95, 0x9A, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xF5, 0xFF, 0xFF, 0x55, + 0x55, 0x55, 0x55, 0x55, 0xA9, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x56, 0x55, 0x55, 0x95, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x95, 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x56, 0xF9, 0x5F, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x50, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x9A, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x5A, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0x0A, 0xA0, 0xAA, 0xAA, 0xAA, 0x6A, 0xA9, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, + 0x81, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0xA9, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xA9, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xFF, 0xFF, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0x56, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0x6A, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x40, + 0x00, 0x00, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x50, 0x55, 0x55, 0x55, 0x45, 0x45, 0x15, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x41, + 0x55, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, + 0x00, 0x00, 0x00, 0x50, 0x55, 0x55, 0x15, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x05, 0x00, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x50, 0x55, 0x55, + 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x56, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x05, 0x50, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, 0x40, 0x41, 0x41, 0x55, 0x55, 0x15, 0x55, 0x55, + 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x04, 0x14, 0x54, 0x05, 0x51, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x50, 0x55, 0x45, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x51, 0x54, 0x51, 0x55, 0x55, 0x55, + 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0xAA, 0x5A, 0x55, 0x00, 0x00, 0x00, 0x00, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, 0xAA, + 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x56, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, + 0x6A, 0x55, 0x55, 0x55, 0x55, 0x01, 0x5D, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x40, 0x55, 0x01, 0x41, 0x55, 0x00, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x40, 0x15, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x41, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, + 0x55, 0x05, 0x00, 0x00, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x05, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x00, 0x00, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x14, 0x54, 0x55, 0x15, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x15, 0x40, 0x41, 0x51, 0x45, 0x55, 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x15, 0x00, 0x01, 0x00, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x15, 0x55, 0x55, 0x55, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x00, 0x40, 0x55, 0x55, 0x01, 0x14, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x50, 0x04, 0x55, 0x45, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x15, 0x15, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x00, 0x54, 0x00, 0x54, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x05, + 0x44, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x44, + 0x15, 0x04, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, + 0x50, 0x55, 0x10, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x50, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x15, 0x00, 0x40, 0x11, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x15, 0x51, 0x00, 0x10, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, + 0x05, 0x10, 0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x41, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x44, 0x15, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x00, 0x05, 0x55, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, 0x00, 0x40, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x14, 0x40, 0x55, 0x15, + 0x55, 0x55, 0x01, 0x40, 0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x05, 0x00, 0x00, 0x40, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x40, 0x00, + 0x10, 0x55, 0x55, 0x55, 0x55, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x41, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x01, + 0x40, 0x45, 0x10, 0x00, 0x10, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x50, 0x11, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x15, 0x54, 0x55, 0x55, 0x50, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x05, 0x40, 0x55, 0x44, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0x15, 0x00, 0x00, 0x00, 0x50, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x15, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0x54, 0x55, 0x55, 0x5A, 0x55, 0x55, 0x55, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x5A, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0xAA, 0xAA, 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, + 0xA9, 0xAA, 0x69, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, 0x55, 0x55, 0x55, + 0x65, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x6A, 0x59, 0x55, 0x55, 0x55, 0xAA, 0x55, + 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x41, 0x00, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x15, 0x50, 0x55, 0x15, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x05, 0x50, 0x55, 0x55, 0x55, 0x55, 0x05, 0x54, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x15, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x55, 0x51, 0x55, 0x55, 0x55, + 0x54, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x01, 0x00, 0x00, 0x00, 0x55, 0x55, 0x55, 0x55, + 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x10, 0x04, 0x40, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x95, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xFF, 0xFF, 0x7F, 0x55, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0x5F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0x5F, 0x55, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xEF, 0xAB, 0xAA, + 0xEA, 0xFF, 0xFF, 0xFF, 0xFF, 0x57, 0x55, 0x55, 0x55, 0x55, 0x6A, 0x55, 0x55, 0x55, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0xAA, 0xAA, 0x56, 0x55, + 0x5A, 0x55, 0x55, 0x55, 0xAA, 0x5A, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x56, 0x55, 0x55, 0xA9, 0xAA, 0x9A, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xA6, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0x6A, 0x95, 0xAA, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x56, 0x56, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0x6A, 0xA6, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0x96, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0x5A, 0x55, 0x55, 0x95, 0x6A, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0x55, 0x55, 0x55, 0x55, 0x65, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x69, 0x55, 0x55, 0x55, + 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x95, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0x5A, 0x55, 0x56, 0x6A, 0xA9, + 0x55, 0xAA, 0x55, 0x55, 0x95, 0x56, 0x55, 0xAA, 0xAA, 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0x55, 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x6A, 0xAA, 0xAA, 0x9A, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0x56, 0xAA, + 0xAA, 0x56, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x9A, + 0xAA, 0x5A, 0x55, 0xA5, 0xAA, 0xAA, 0xAA, 0x55, 0xAA, 0xAA, 0x56, 0x55, 0xAA, 0xAA, 0x56, + 0x55, 0x51, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0x5F, + ]; +} diff --git a/bash-5.1/vendor/unicode-width/src/tests.rs b/bash-5.1/vendor/unicode-width/src/tests.rs new file mode 100644 index 0000000..e49b1bf --- /dev/null +++ b/bash-5.1/vendor/unicode-width/src/tests.rs @@ -0,0 +1,191 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(feature = "bench")] +use std::iter; +#[cfg(feature = "bench")] +use test::{self, Bencher}; +#[cfg(feature = "bench")] +use super::{UnicodeWidthChar, UnicodeWidthStr}; + +use std::prelude::v1::*; + +#[cfg(feature = "bench")] +#[bench] +fn cargo(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.iter(|| { + for c in string.chars() { + test::black_box(UnicodeWidthChar::width(c)); + } + }); +} + +#[cfg(feature = "bench")] +#[bench] +#[allow(deprecated)] +fn stdlib(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.iter(|| { + for c in string.chars() { + test::black_box(c.width()); + } + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn simple_if(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.iter(|| { + for c in string.chars() { + test::black_box(simple_width_if(c)); + } + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn simple_match(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.iter(|| { + for c in string.chars() { + test::black_box(simple_width_match(c)); + } + }); +} + +#[cfg(feature = "bench")] +#[inline] +fn simple_width_if(c: char) -> Option<usize> { + let cu = c as u32; + if cu < 127 { + if cu > 31 { + Some(1) + } else if cu == 0 { + Some(0) + } else { + None + } + } else { + UnicodeWidthChar::width(c) + } +} + +#[cfg(feature = "bench")] +#[inline] +fn simple_width_match(c: char) -> Option<usize> { + match c as u32 { + cu if cu == 0 => Some(0), + cu if cu < 0x20 => None, + cu if cu < 0x7f => Some(1), + _ => UnicodeWidthChar::width(c) + } +} +#[cfg(all(feature = "bench", not(feature = "no_std")))] +#[bench] +fn enwik8(b: &mut Bencher) { + // To benchmark, download & unzip `enwik8` from https://data.deepai.org/enwik8.zip + let data_path = "bench_data/enwik8"; + let string = std::fs::read_to_string(data_path).unwrap_or_default(); + b.iter(|| test::black_box(UnicodeWidthStr::width(string.as_str()))); +} +#[cfg(all(feature = "bench", not(feature = "no_std")))] +#[bench] +fn jawiki(b: &mut Bencher) { + // To benchmark, download & extract `jawiki-20220501-pages-articles-multistream-index.txt` from + // https://dumps.wikimedia.org/jawiki/20220501/jawiki-20220501-pages-articles-multistream-index.txt.bz2 + let data_path = "bench_data/jawiki-20220501-pages-articles-multistream-index.txt"; + let string = std::fs::read_to_string(data_path).unwrap_or_default(); + b.iter(|| test::black_box(UnicodeWidthStr::width(string.as_str()))); +} +#[test] +fn test_str() { + use super::UnicodeWidthStr; + + assert_eq!(UnicodeWidthStr::width("hello"), 10); + assert_eq!("hello".width_cjk(), 10); + assert_eq!(UnicodeWidthStr::width("\0\0\0\x01\x01"), 0); + assert_eq!("\0\0\0\x01\x01".width_cjk(), 0); + assert_eq!(UnicodeWidthStr::width(""), 0); + assert_eq!("".width_cjk(), 0); + assert_eq!(UnicodeWidthStr::width("\u{2081}\u{2082}\u{2083}\u{2084}"), 4); + assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width_cjk(), 8); +} + +#[test] +fn test_emoji() { + // Example from the README. + use super::UnicodeWidthStr; + + assert_eq!(UnicodeWidthStr::width("👩"), 2); // Woman + assert_eq!(UnicodeWidthStr::width("🔬"), 2); // Microscope + assert_eq!(UnicodeWidthStr::width("👩‍🔬"), 4); // Woman scientist +} + +#[test] +fn test_char() { + use super::UnicodeWidthChar; + #[cfg(feature = "no_std")] + use core::option::Option::{Some, None}; + + assert_eq!(UnicodeWidthChar::width('h'), Some(2)); + assert_eq!('h'.width_cjk(), Some(2)); + assert_eq!(UnicodeWidthChar::width('\x00'), Some(0)); + assert_eq!('\x00'.width_cjk(), Some(0)); + assert_eq!(UnicodeWidthChar::width('\x01'), None); + assert_eq!('\x01'.width_cjk(), None); + assert_eq!(UnicodeWidthChar::width('\u{2081}'), Some(1)); + assert_eq!('\u{2081}'.width_cjk(), Some(2)); +} + +#[test] +fn test_char2() { + use super::UnicodeWidthChar; + #[cfg(feature = "no_std")] + use core::option::Option::{Some, None}; + + assert_eq!(UnicodeWidthChar::width('\x00'),Some(0)); + assert_eq!('\x00'.width_cjk(),Some(0)); + + assert_eq!(UnicodeWidthChar::width('\x0A'),None); + assert_eq!('\x0A'.width_cjk(),None); + + assert_eq!(UnicodeWidthChar::width('w'),Some(1)); + assert_eq!('w'.width_cjk(),Some(1)); + + assert_eq!(UnicodeWidthChar::width('h'),Some(2)); + assert_eq!('h'.width_cjk(),Some(2)); + + assert_eq!(UnicodeWidthChar::width('\u{AD}'),Some(1)); + assert_eq!('\u{AD}'.width_cjk(),Some(1)); + + assert_eq!(UnicodeWidthChar::width('\u{1160}'),Some(0)); + assert_eq!('\u{1160}'.width_cjk(),Some(0)); + + assert_eq!(UnicodeWidthChar::width('\u{a1}'),Some(1)); + assert_eq!('\u{a1}'.width_cjk(),Some(2)); + + assert_eq!(UnicodeWidthChar::width('\u{300}'),Some(0)); + assert_eq!('\u{300}'.width_cjk(),Some(0)); +} + +#[test] +fn unicode_12() { + use super::UnicodeWidthChar; + #[cfg(feature = "no_std")] + use core::option::Option::{Some, None}; + + assert_eq!(UnicodeWidthChar::width('\u{1F971}'), Some(2)); +} diff --git a/bash-5.1/vendor/unicode-xid/.cargo-checksum.json b/bash-5.1/vendor/unicode-xid/.cargo-checksum.json new file mode 100644 index 0000000..a25540c --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"23860c2a7b5d96b21569afedf033469bab9fe14a1b24a35068b8641c578ce24d","Cargo.toml":"1be08526c07c40136071faf603a382456ad1a6bafbb45d9ace01c52b50a9a55c","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"67998486b32f4fe46abbbaa411b92528750e7f0e22452dc8a5b95d87d80fde75","scripts/unicode.py":"762eea92dd51238c6bf877570bde1149932ba15cf87be1618fc21cd53e941733","src/lib.rs":"4a89fadf452ae7c53536eaa4496f951a3153f8189dd1cbc532648731d30f0b11","src/tables.rs":"0643459b6ebeeed83aecd7604f0ea29c06bea7ce6c1cd9acd4988d27ace1ec53","src/tests.rs":"35a459382e190197e7b9a78832ae79f310b48a02a5b4227bf9bbc89d46c8deac"},"package":"8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc"} \ No newline at end of file diff --git a/bash-5.1/vendor/unicode-xid/COPYRIGHT b/bash-5.1/vendor/unicode-xid/COPYRIGHT new file mode 100644 index 0000000..b286ec1 --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/COPYRIGHT @@ -0,0 +1,7 @@ +Licensed under the Apache License, Version 2.0 +<LICENSE-APACHE or +http://www.apache.org/licenses/LICENSE-2.0> or the MIT +license <LICENSE-MIT or http://opensource.org/licenses/MIT>, +at your option. All files in the project carrying such +notice may not be copied, modified, or distributed except +according to those terms. diff --git a/bash-5.1/vendor/unicode-xid/Cargo.toml b/bash-5.1/vendor/unicode-xid/Cargo.toml new file mode 100644 index 0000000..ac711a5 --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/Cargo.toml @@ -0,0 +1,26 @@ +[package] + +name = "unicode-xid" +version = "0.0.4" +authors = ["erick.tryzelaar <erick.tryzelaar@gmail.com>", + "kwantam <kwantam@gmail.com>", + ] + +homepage = "https://github.com/unicode-rs/unicode-xid" +repository = "https://github.com/unicode-rs/unicode-xid" +documentation = "https://unicode-rs.github.io/unicode-xid" +license = "MIT/Apache-2.0" +keywords = ["text", "unicode", "xid"] +readme = "README.md" +description = """ +Determine whether characters have the XID_Start +or XID_Continue properties according to +Unicode Standard Annex #31. +""" + +exclude = [ "target/*", "Cargo.lock" ] + +[features] +default = [] +no_std = [] +bench = [] diff --git a/bash-5.1/vendor/unicode-xid/LICENSE-APACHE b/bash-5.1/vendor/unicode-xid/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/unicode-xid/LICENSE-MIT b/bash-5.1/vendor/unicode-xid/LICENSE-MIT new file mode 100644 index 0000000..e69282e --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2015 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/unicode-xid/README.md b/bash-5.1/vendor/unicode-xid/README.md new file mode 100644 index 0000000..3a2be47 --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/README.md @@ -0,0 +1,34 @@ +# unicode-xid + +Determine if a `char` is a valid identifier for a parser and/or lexer according to +[Unicode Standard Annex #31](http://www.unicode.org/reports/tr31/) rules. + +[![Build Status](https://travis-ci.org/unicode-rs/unicode-xid.svg)](https://travis-ci.org/unicode-rs/unicode-xid) + +[Documentation](https://unicode-rs.github.io/unicode-xid/unicode_xid/index.html) + +```rust +extern crate unicode_xid; + +use unicode_xid::UnicodeXID; + +fn main() { + let ch = 'a'; + println!("Is {} a valid start of an identifier? {}", ch, UnicodeXID::is_xid_start(ch)); +} +``` + +# features + +unicode-xid supports a `no_std` feature. This eliminates dependence +on std, and instead uses equivalent functions from core. + +# crates.io + +You can use this package in your project by adding the following +to your `Cargo.toml`: + +```toml +[dependencies] +unicode-xid = "0.0.4" +``` diff --git a/bash-5.1/vendor/unicode-xid/scripts/unicode.py b/bash-5.1/vendor/unicode-xid/scripts/unicode.py new file mode 100755 index 0000000..a30d2f2 --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/scripts/unicode.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +# +# Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +# This script uses the following Unicode tables: +# - DerivedCoreProperties.txt +# - ReadMe.txt +# +# Since this should not require frequent updates, we just store this +# out-of-line and check the unicode.rs file into git. + +import fileinput, re, os, sys + +preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly + +#![allow(missing_docs, non_upper_case_globals, non_snake_case)] +''' + +def fetch(f): + if not os.path.exists(os.path.basename(f)): + os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s" + % f) + + if not os.path.exists(os.path.basename(f)): + sys.stderr.write("cannot load %s" % f) + exit(1) + +def group_cat(cat): + cat_out = [] + letters = sorted(set(cat)) + cur_start = letters.pop(0) + cur_end = cur_start + for letter in letters: + assert letter > cur_end, \ + "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter)) + if letter == cur_end + 1: + cur_end = letter + else: + cat_out.append((cur_start, cur_end)) + cur_start = cur_end = letter + cat_out.append((cur_start, cur_end)) + return cat_out + +def ungroup_cat(cat): + cat_out = [] + for (lo, hi) in cat: + while lo <= hi: + cat_out.append(lo) + lo += 1 + return cat_out + +def format_table_content(f, content, indent): + line = " "*indent + first = True + for chunk in content.split(","): + if len(line) + len(chunk) < 98: + if first: + line += chunk + else: + line += ", " + chunk + first = False + else: + f.write(line + ",\n") + line = " "*indent + chunk + f.write(line) + +def load_properties(f, interestingprops): + fetch(f) + props = {} + re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)") + re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)") + + for line in fileinput.input(os.path.basename(f)): + prop = None + d_lo = 0 + d_hi = 0 + m = re1.match(line) + if m: + d_lo = m.group(1) + d_hi = m.group(1) + prop = m.group(2) + else: + m = re2.match(line) + if m: + d_lo = m.group(1) + d_hi = m.group(2) + prop = m.group(3) + else: + continue + if interestingprops and prop not in interestingprops: + continue + d_lo = int(d_lo, 16) + d_hi = int(d_hi, 16) + if prop not in props: + props[prop] = [] + props[prop].append((d_lo, d_hi)) + + # optimize if possible + for prop in props: + props[prop] = group_cat(ungroup_cat(props[prop])) + + return props + +def escape_char(c): + return "'\\u{%x}'" % c + +def emit_bsearch_range_table(f): + f.write(""" +fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use core::cmp::Ordering::{Equal, Less, Greater}; + + r.binary_search_by(|&(lo,hi)| { + if lo <= c && c <= hi { Equal } + else if hi < c { Less } + else { Greater } + }).is_ok() +}\n +""") + +def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True, + pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True): + pub_string = "const" + if not is_const: + pub_string = "let" + if is_pub: + pub_string = "pub " + pub_string + f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type)) + data = "" + first = True + for dat in t_data: + if not first: + data += "," + first = False + data += pfun(dat) + format_table_content(f, data, 8) + f.write("\n ];\n\n") + +def emit_property_module(f, mod, tbl, emit): + f.write("pub mod %s {\n" % mod) + for cat in sorted(emit): + emit_table(f, "%s_table" % cat, tbl[cat]) + f.write(" pub fn %s(c: char) -> bool {\n" % cat) + f.write(" super::bsearch_range_table(c, %s_table)\n" % cat) + f.write(" }\n\n") + f.write("}\n\n") + +if __name__ == "__main__": + r = "tables.rs" + if os.path.exists(r): + os.remove(r) + with open(r, "w") as rf: + # write the file's preamble + rf.write(preamble) + + # download and parse all the data + fetch("ReadMe.txt") + with open("ReadMe.txt") as readme: + pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode" + unicode_version = re.search(pattern, readme.read()).groups() + rf.write(""" +/// The version of [Unicode](http://www.unicode.org/) +/// that this version of unicode-xid is based on. +pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s); +""" % unicode_version) + emit_bsearch_range_table(rf) + + want_derived = ["XID_Start", "XID_Continue"] + derived = load_properties("DerivedCoreProperties.txt", want_derived) + emit_property_module(rf, "derived_property", derived, want_derived) diff --git a/bash-5.1/vendor/unicode-xid/src/lib.rs b/bash-5.1/vendor/unicode-xid/src/lib.rs new file mode 100644 index 0000000..09faf97 --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/src/lib.rs @@ -0,0 +1,87 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Determine if a `char` is a valid identifier for a parser and/or lexer according to +//! [Unicode Standard Annex #31](http://www.unicode.org/reports/tr31/) rules. +//! +//! ```rust +//! extern crate unicode_xid; +//! +//! use unicode_xid::UnicodeXID; +//! +//! fn main() { +//! let ch = 'a'; +//! println!("Is {} a valid start of an identifier? {}", ch, UnicodeXID::is_xid_start(ch)); +//! } +//! ``` +//! +//! # features +//! +//! unicode-xid supports a `no_std` feature. This eliminates dependence +//! on std, and instead uses equivalent functions from core. +//! +//! # crates.io +//! +//! You can use this package in your project by adding the following +//! to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! unicode-xid = "0.0.4" +//! ``` + +#![deny(missing_docs, unsafe_code)] +#![doc(html_logo_url = "https://unicode-rs.github.io/unicode-rs_sm.png", + html_favicon_url = "https://unicode-rs.github.io/unicode-rs_sm.png")] + +#![no_std] +#![cfg_attr(feature = "bench", feature(test, unicode))] + +#[cfg(test)] +#[macro_use] +extern crate std; + +#[cfg(feature = "bench")] +extern crate test; + +use tables::derived_property; +pub use tables::UNICODE_VERSION; + +mod tables; + +#[cfg(test)] +mod tests; + +/// Methods for determining if a character is a valid identifier character. +pub trait UnicodeXID { + /// Returns whether the specified character satisfies the 'XID_Start' + /// Unicode property. + /// + /// 'XID_Start' is a Unicode Derived Property specified in + /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), + /// mostly similar to ID_Start but modified for closure under NFKx. + fn is_xid_start(self) -> bool; + + /// Returns whether the specified `char` satisfies the 'XID_Continue' + /// Unicode property. + /// + /// 'XID_Continue' is a Unicode Derived Property specified in + /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), + /// mostly similar to 'ID_Continue' but modified for closure under NFKx. + fn is_xid_continue(self) -> bool; +} + +impl UnicodeXID for char { + #[inline] + fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } + + #[inline] + fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } +} diff --git a/bash-5.1/vendor/unicode-xid/src/tables.rs b/bash-5.1/vendor/unicode-xid/src/tables.rs new file mode 100644 index 0000000..3fe0d3d --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/src/tables.rs @@ -0,0 +1,426 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly + +#![allow(missing_docs, non_upper_case_globals, non_snake_case)] + +/// The version of [Unicode](http://www.unicode.org/) +/// that this version of unicode-xid is based on. +pub const UNICODE_VERSION: (u64, u64, u64) = (9, 0, 0); + +fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use core::cmp::Ordering::{Equal, Less, Greater}; + + r.binary_search_by(|&(lo,hi)| { + if lo <= c && c <= hi { Equal } + else if hi < c { Less } + else { Greater } + }).is_ok() +} + +pub mod derived_property { + pub const XID_Continue_table: &'static [(char, char)] = &[ + ('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), ('\u{61}', '\u{7a}'), + ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{b7}', '\u{b7}'), ('\u{ba}', '\u{ba}'), + ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), + ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), ('\u{300}', + '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), ('\u{37f}', '\u{37f}'), + ('\u{386}', '\u{38a}'), ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', + '\u{3f5}'), ('\u{3f7}', '\u{481}'), ('\u{483}', '\u{487}'), ('\u{48a}', '\u{52f}'), + ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{561}', '\u{587}'), ('\u{591}', + '\u{5bd}'), ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), + ('\u{5c7}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{610}', + '\u{61a}'), ('\u{620}', '\u{669}'), ('\u{66e}', '\u{6d3}'), ('\u{6d5}', '\u{6dc}'), + ('\u{6df}', '\u{6e8}'), ('\u{6ea}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), ('\u{710}', + '\u{74a}'), ('\u{74d}', '\u{7b1}'), ('\u{7c0}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), + ('\u{800}', '\u{82d}'), ('\u{840}', '\u{85b}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', + '\u{8bd}'), ('\u{8d4}', '\u{8e1}'), ('\u{8e3}', '\u{963}'), ('\u{966}', '\u{96f}'), + ('\u{971}', '\u{983}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), ('\u{993}', + '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), + ('\u{9bc}', '\u{9c4}'), ('\u{9c7}', '\u{9c8}'), ('\u{9cb}', '\u{9ce}'), ('\u{9d7}', + '\u{9d7}'), ('\u{9dc}', '\u{9dd}'), ('\u{9df}', '\u{9e3}'), ('\u{9e6}', '\u{9f1}'), + ('\u{a01}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}', '\u{a10}'), ('\u{a13}', + '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), + ('\u{a38}', '\u{a39}'), ('\u{a3c}', '\u{a3c}'), ('\u{a3e}', '\u{a42}'), ('\u{a47}', + '\u{a48}'), ('\u{a4b}', '\u{a4d}'), ('\u{a51}', '\u{a51}'), ('\u{a59}', '\u{a5c}'), + ('\u{a5e}', '\u{a5e}'), ('\u{a66}', '\u{a75}'), ('\u{a81}', '\u{a83}'), ('\u{a85}', + '\u{a8d}'), ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), + ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), ('\u{abc}', '\u{ac5}'), ('\u{ac7}', + '\u{ac9}'), ('\u{acb}', '\u{acd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae3}'), + ('\u{ae6}', '\u{aef}'), ('\u{af9}', '\u{af9}'), ('\u{b01}', '\u{b03}'), ('\u{b05}', + '\u{b0c}'), ('\u{b0f}', '\u{b10}'), ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), + ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b44}'), ('\u{b47}', + '\u{b48}'), ('\u{b4b}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), ('\u{b5c}', '\u{b5d}'), + ('\u{b5f}', '\u{b63}'), ('\u{b66}', '\u{b6f}'), ('\u{b71}', '\u{b71}'), ('\u{b82}', + '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), ('\u{b92}', '\u{b95}'), + ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', + '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), ('\u{bbe}', '\u{bc2}'), + ('\u{bc6}', '\u{bc8}'), ('\u{bca}', '\u{bcd}'), ('\u{bd0}', '\u{bd0}'), ('\u{bd7}', + '\u{bd7}'), ('\u{be6}', '\u{bef}'), ('\u{c00}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), + ('\u{c0e}', '\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', + '\u{c44}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4d}'), ('\u{c55}', '\u{c56}'), + ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c63}'), ('\u{c66}', '\u{c6f}'), ('\u{c80}', + '\u{c83}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), ('\u{c92}', '\u{ca8}'), + ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), ('\u{cbc}', '\u{cc4}'), ('\u{cc6}', + '\u{cc8}'), ('\u{cca}', '\u{ccd}'), ('\u{cd5}', '\u{cd6}'), ('\u{cde}', '\u{cde}'), + ('\u{ce0}', '\u{ce3}'), ('\u{ce6}', '\u{cef}'), ('\u{cf1}', '\u{cf2}'), ('\u{d01}', + '\u{d03}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), + ('\u{d3d}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4e}'), ('\u{d54}', + '\u{d57}'), ('\u{d5f}', '\u{d63}'), ('\u{d66}', '\u{d6f}'), ('\u{d7a}', '\u{d7f}'), + ('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), ('\u{db3}', + '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{dca}', '\u{dca}'), + ('\u{dcf}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), ('\u{dd8}', '\u{ddf}'), ('\u{de6}', + '\u{def}'), ('\u{df2}', '\u{df3}'), ('\u{e01}', '\u{e3a}'), ('\u{e40}', '\u{e4e}'), + ('\u{e50}', '\u{e59}'), ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), ('\u{e87}', + '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), + ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', + '\u{ea7}'), ('\u{eaa}', '\u{eab}'), ('\u{ead}', '\u{eb9}'), ('\u{ebb}', '\u{ebd}'), + ('\u{ec0}', '\u{ec4}'), ('\u{ec6}', '\u{ec6}'), ('\u{ec8}', '\u{ecd}'), ('\u{ed0}', + '\u{ed9}'), ('\u{edc}', '\u{edf}'), ('\u{f00}', '\u{f00}'), ('\u{f18}', '\u{f19}'), + ('\u{f20}', '\u{f29}'), ('\u{f35}', '\u{f35}'), ('\u{f37}', '\u{f37}'), ('\u{f39}', + '\u{f39}'), ('\u{f3e}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), ('\u{f71}', '\u{f84}'), + ('\u{f86}', '\u{f97}'), ('\u{f99}', '\u{fbc}'), ('\u{fc6}', '\u{fc6}'), ('\u{1000}', + '\u{1049}'), ('\u{1050}', '\u{109d}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), + ('\u{10cd}', '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{1248}'), ('\u{124a}', + '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), + ('\u{1260}', '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', + '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), + ('\u{12c8}', '\u{12d6}'), ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', + '\u{135a}'), ('\u{135d}', '\u{135f}'), ('\u{1369}', '\u{1371}'), ('\u{1380}', '\u{138f}'), + ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', '\u{166c}'), ('\u{166f}', + '\u{167f}'), ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f8}'), + ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1714}'), ('\u{1720}', '\u{1734}'), ('\u{1740}', + '\u{1753}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1772}', '\u{1773}'), + ('\u{1780}', '\u{17d3}'), ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dd}'), ('\u{17e0}', + '\u{17e9}'), ('\u{180b}', '\u{180d}'), ('\u{1810}', '\u{1819}'), ('\u{1820}', '\u{1877}'), + ('\u{1880}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), ('\u{1900}', '\u{191e}'), ('\u{1920}', + '\u{192b}'), ('\u{1930}', '\u{193b}'), ('\u{1946}', '\u{196d}'), ('\u{1970}', '\u{1974}'), + ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{19d0}', '\u{19da}'), ('\u{1a00}', + '\u{1a1b}'), ('\u{1a20}', '\u{1a5e}'), ('\u{1a60}', '\u{1a7c}'), ('\u{1a7f}', '\u{1a89}'), + ('\u{1a90}', '\u{1a99}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1ab0}', '\u{1abd}'), ('\u{1b00}', + '\u{1b4b}'), ('\u{1b50}', '\u{1b59}'), ('\u{1b6b}', '\u{1b73}'), ('\u{1b80}', '\u{1bf3}'), + ('\u{1c00}', '\u{1c37}'), ('\u{1c40}', '\u{1c49}'), ('\u{1c4d}', '\u{1c7d}'), ('\u{1c80}', + '\u{1c88}'), ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', '\u{1cf6}'), ('\u{1cf8}', '\u{1cf9}'), + ('\u{1d00}', '\u{1df5}'), ('\u{1dfb}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', + '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), + ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', + '\u{1fb4}'), ('\u{1fb6}', '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), + ('\u{1fc6}', '\u{1fcc}'), ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', + '\u{1fec}'), ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{203f}', '\u{2040}'), + ('\u{2054}', '\u{2054}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', '\u{207f}'), ('\u{2090}', + '\u{209c}'), ('\u{20d0}', '\u{20dc}'), ('\u{20e1}', '\u{20e1}'), ('\u{20e5}', '\u{20f0}'), + ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', '\u{2113}'), ('\u{2115}', + '\u{2115}'), ('\u{2118}', '\u{211d}'), ('\u{2124}', '\u{2124}'), ('\u{2126}', '\u{2126}'), + ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{2139}'), ('\u{213c}', '\u{213f}'), ('\u{2145}', + '\u{2149}'), ('\u{214e}', '\u{214e}'), ('\u{2160}', '\u{2188}'), ('\u{2c00}', '\u{2c2e}'), + ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), ('\u{2ceb}', '\u{2cf3}'), ('\u{2d00}', + '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), ('\u{2d30}', '\u{2d67}'), + ('\u{2d6f}', '\u{2d6f}'), ('\u{2d7f}', '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', + '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), + ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{2de0}', + '\u{2dff}'), ('\u{3005}', '\u{3007}'), ('\u{3021}', '\u{302f}'), ('\u{3031}', '\u{3035}'), + ('\u{3038}', '\u{303c}'), ('\u{3041}', '\u{3096}'), ('\u{3099}', '\u{309a}'), ('\u{309d}', + '\u{309f}'), ('\u{30a1}', '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312d}'), + ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', '\u{31ff}'), ('\u{3400}', + '\u{4db5}'), ('\u{4e00}', '\u{9fd5}'), ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), + ('\u{a500}', '\u{a60c}'), ('\u{a610}', '\u{a62b}'), ('\u{a640}', '\u{a66f}'), ('\u{a674}', + '\u{a67d}'), ('\u{a67f}', '\u{a6f1}'), ('\u{a717}', '\u{a71f}'), ('\u{a722}', '\u{a788}'), + ('\u{a78b}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', '\u{a827}'), ('\u{a840}', + '\u{a873}'), ('\u{a880}', '\u{a8c5}'), ('\u{a8d0}', '\u{a8d9}'), ('\u{a8e0}', '\u{a8f7}'), + ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', '\u{a8fd}'), ('\u{a900}', '\u{a92d}'), ('\u{a930}', + '\u{a953}'), ('\u{a960}', '\u{a97c}'), ('\u{a980}', '\u{a9c0}'), ('\u{a9cf}', '\u{a9d9}'), + ('\u{a9e0}', '\u{a9fe}'), ('\u{aa00}', '\u{aa36}'), ('\u{aa40}', '\u{aa4d}'), ('\u{aa50}', + '\u{aa59}'), ('\u{aa60}', '\u{aa76}'), ('\u{aa7a}', '\u{aac2}'), ('\u{aadb}', '\u{aadd}'), + ('\u{aae0}', '\u{aaef}'), ('\u{aaf2}', '\u{aaf6}'), ('\u{ab01}', '\u{ab06}'), ('\u{ab09}', + '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}'), + ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', '\u{abea}'), ('\u{abec}', + '\u{abed}'), ('\u{abf0}', '\u{abf9}'), ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), + ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', + '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), ('\u{fb1d}', '\u{fb28}'), ('\u{fb2a}', '\u{fb36}'), + ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', + '\u{fb44}'), ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fc5d}'), ('\u{fc64}', '\u{fd3d}'), + ('\u{fd50}', '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdf9}'), ('\u{fe00}', + '\u{fe0f}'), ('\u{fe20}', '\u{fe2f}'), ('\u{fe33}', '\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), + ('\u{fe71}', '\u{fe71}'), ('\u{fe73}', '\u{fe73}'), ('\u{fe77}', '\u{fe77}'), ('\u{fe79}', + '\u{fe79}'), ('\u{fe7b}', '\u{fe7b}'), ('\u{fe7d}', '\u{fe7d}'), ('\u{fe7f}', '\u{fefc}'), + ('\u{ff10}', '\u{ff19}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff3f}', '\u{ff3f}'), ('\u{ff41}', + '\u{ff5a}'), ('\u{ff66}', '\u{ffbe}'), ('\u{ffc2}', '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), + ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), + ('\u{1000d}', '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), + ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', '\u{100fa}'), + ('\u{10140}', '\u{10174}'), ('\u{101fd}', '\u{101fd}'), ('\u{10280}', '\u{1029c}'), + ('\u{102a0}', '\u{102d0}'), ('\u{102e0}', '\u{102e0}'), ('\u{10300}', '\u{1031f}'), + ('\u{10330}', '\u{1034a}'), ('\u{10350}', '\u{1037a}'), ('\u{10380}', '\u{1039d}'), + ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', '\u{103d5}'), + ('\u{10400}', '\u{1049d}'), ('\u{104a0}', '\u{104a9}'), ('\u{104b0}', '\u{104d3}'), + ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), ('\u{10530}', '\u{10563}'), + ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', '\u{10767}'), + ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), ('\u{1080a}', '\u{10835}'), + ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{10855}'), + ('\u{10860}', '\u{10876}'), ('\u{10880}', '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), + ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), ('\u{10920}', '\u{10939}'), + ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), ('\u{10a00}', '\u{10a03}'), + ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), + ('\u{10a19}', '\u{10a33}'), ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'), + ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), ('\u{10ac0}', '\u{10ac7}'), + ('\u{10ac9}', '\u{10ae6}'), ('\u{10b00}', '\u{10b35}'), ('\u{10b40}', '\u{10b55}'), + ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), ('\u{10c00}', '\u{10c48}'), + ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), ('\u{11000}', '\u{11046}'), + ('\u{11066}', '\u{1106f}'), ('\u{1107f}', '\u{110ba}'), ('\u{110d0}', '\u{110e8}'), + ('\u{110f0}', '\u{110f9}'), ('\u{11100}', '\u{11134}'), ('\u{11136}', '\u{1113f}'), + ('\u{11150}', '\u{11173}'), ('\u{11176}', '\u{11176}'), ('\u{11180}', '\u{111c4}'), + ('\u{111ca}', '\u{111cc}'), ('\u{111d0}', '\u{111da}'), ('\u{111dc}', '\u{111dc}'), + ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{11237}'), ('\u{1123e}', '\u{1123e}'), + ('\u{11280}', '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), + ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', '\u{112ea}'), + ('\u{112f0}', '\u{112f9}'), ('\u{11300}', '\u{11303}'), ('\u{11305}', '\u{1130c}'), + ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'), + ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133c}', '\u{11344}'), + ('\u{11347}', '\u{11348}'), ('\u{1134b}', '\u{1134d}'), ('\u{11350}', '\u{11350}'), + ('\u{11357}', '\u{11357}'), ('\u{1135d}', '\u{11363}'), ('\u{11366}', '\u{1136c}'), + ('\u{11370}', '\u{11374}'), ('\u{11400}', '\u{1144a}'), ('\u{11450}', '\u{11459}'), + ('\u{11480}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{114d0}', '\u{114d9}'), + ('\u{11580}', '\u{115b5}'), ('\u{115b8}', '\u{115c0}'), ('\u{115d8}', '\u{115dd}'), + ('\u{11600}', '\u{11640}'), ('\u{11644}', '\u{11644}'), ('\u{11650}', '\u{11659}'), + ('\u{11680}', '\u{116b7}'), ('\u{116c0}', '\u{116c9}'), ('\u{11700}', '\u{11719}'), + ('\u{1171d}', '\u{1172b}'), ('\u{11730}', '\u{11739}'), ('\u{118a0}', '\u{118e9}'), + ('\u{118ff}', '\u{118ff}'), ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), + ('\u{11c0a}', '\u{11c36}'), ('\u{11c38}', '\u{11c40}'), ('\u{11c50}', '\u{11c59}'), + ('\u{11c72}', '\u{11c8f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11ca9}', '\u{11cb6}'), + ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12480}', '\u{12543}'), + ('\u{13000}', '\u{1342e}'), ('\u{14400}', '\u{14646}'), ('\u{16800}', '\u{16a38}'), + ('\u{16a40}', '\u{16a5e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16ad0}', '\u{16aed}'), + ('\u{16af0}', '\u{16af4}'), ('\u{16b00}', '\u{16b36}'), ('\u{16b40}', '\u{16b43}'), + ('\u{16b50}', '\u{16b59}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), + ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f7e}'), ('\u{16f8f}', '\u{16f9f}'), + ('\u{16fe0}', '\u{16fe0}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', '\u{18af2}'), + ('\u{1b000}', '\u{1b001}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), + ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1bc9d}', '\u{1bc9e}'), + ('\u{1d165}', '\u{1d169}'), ('\u{1d16d}', '\u{1d172}'), ('\u{1d17b}', '\u{1d182}'), + ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', '\u{1d1ad}'), ('\u{1d242}', '\u{1d244}'), + ('\u{1d400}', '\u{1d454}'), ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), + ('\u{1d4a2}', '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), + ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), + ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), + ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), + ('\u{1d540}', '\u{1d544}'), ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), + ('\u{1d552}', '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), + ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', '\u{1d734}'), + ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d76e}'), ('\u{1d770}', '\u{1d788}'), + ('\u{1d78a}', '\u{1d7a8}'), ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), + ('\u{1d7ce}', '\u{1d7ff}'), ('\u{1da00}', '\u{1da36}'), ('\u{1da3b}', '\u{1da6c}'), + ('\u{1da75}', '\u{1da75}'), ('\u{1da84}', '\u{1da84}'), ('\u{1da9b}', '\u{1da9f}'), + ('\u{1daa1}', '\u{1daaf}'), ('\u{1e000}', '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), + ('\u{1e01b}', '\u{1e021}'), ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}'), + ('\u{1e800}', '\u{1e8c4}'), ('\u{1e8d0}', '\u{1e8d6}'), ('\u{1e900}', '\u{1e94a}'), + ('\u{1e950}', '\u{1e959}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), + ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), + ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), + ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), + ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), + ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), + ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), + ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), + ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), + ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), + ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), + ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), + ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2f800}', '\u{2fa1d}'), + ('\u{e0100}', '\u{e01ef}') + ]; + + pub fn XID_Continue(c: char) -> bool { + super::bsearch_range_table(c, XID_Continue_table) + } + + pub const XID_Start_table: &'static [(char, char)] = &[ + ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), + ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), + ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', + '\u{2ee}'), ('\u{370}', '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), + ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), ('\u{38c}', + '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), ('\u{3f7}', '\u{481}'), + ('\u{48a}', '\u{52f}'), ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{561}', + '\u{587}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{620}', '\u{64a}'), + ('\u{66e}', '\u{66f}'), ('\u{671}', '\u{6d3}'), ('\u{6d5}', '\u{6d5}'), ('\u{6e5}', + '\u{6e6}'), ('\u{6ee}', '\u{6ef}'), ('\u{6fa}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), + ('\u{710}', '\u{710}'), ('\u{712}', '\u{72f}'), ('\u{74d}', '\u{7a5}'), ('\u{7b1}', + '\u{7b1}'), ('\u{7ca}', '\u{7ea}'), ('\u{7f4}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), + ('\u{800}', '\u{815}'), ('\u{81a}', '\u{81a}'), ('\u{824}', '\u{824}'), ('\u{828}', + '\u{828}'), ('\u{840}', '\u{858}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', '\u{8bd}'), + ('\u{904}', '\u{939}'), ('\u{93d}', '\u{93d}'), ('\u{950}', '\u{950}'), ('\u{958}', + '\u{961}'), ('\u{971}', '\u{980}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), + ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', + '\u{9b9}'), ('\u{9bd}', '\u{9bd}'), ('\u{9ce}', '\u{9ce}'), ('\u{9dc}', '\u{9dd}'), + ('\u{9df}', '\u{9e1}'), ('\u{9f0}', '\u{9f1}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}', + '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), + ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), ('\u{a59}', '\u{a5c}'), ('\u{a5e}', + '\u{a5e}'), ('\u{a72}', '\u{a74}'), ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), + ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', + '\u{ab9}'), ('\u{abd}', '\u{abd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae1}'), + ('\u{af9}', '\u{af9}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), ('\u{b13}', + '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), + ('\u{b3d}', '\u{b3d}'), ('\u{b5c}', '\u{b5d}'), ('\u{b5f}', '\u{b61}'), ('\u{b71}', + '\u{b71}'), ('\u{b83}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), + ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', + '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), + ('\u{bd0}', '\u{bd0}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}', '\u{c10}'), ('\u{c12}', + '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c3d}'), ('\u{c58}', '\u{c5a}'), + ('\u{c60}', '\u{c61}'), ('\u{c80}', '\u{c80}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', + '\u{c90}'), ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), + ('\u{cbd}', '\u{cbd}'), ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce1}'), ('\u{cf1}', + '\u{cf2}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), + ('\u{d3d}', '\u{d3d}'), ('\u{d4e}', '\u{d4e}'), ('\u{d54}', '\u{d56}'), ('\u{d5f}', + '\u{d61}'), ('\u{d7a}', '\u{d7f}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), + ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{e01}', + '\u{e30}'), ('\u{e32}', '\u{e32}'), ('\u{e40}', '\u{e46}'), ('\u{e81}', '\u{e82}'), + ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', + '\u{e8d}'), ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), + ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), ('\u{ead}', + '\u{eb0}'), ('\u{eb2}', '\u{eb2}'), ('\u{ebd}', '\u{ebd}'), ('\u{ec0}', '\u{ec4}'), + ('\u{ec6}', '\u{ec6}'), ('\u{edc}', '\u{edf}'), ('\u{f00}', '\u{f00}'), ('\u{f40}', + '\u{f47}'), ('\u{f49}', '\u{f6c}'), ('\u{f88}', '\u{f8c}'), ('\u{1000}', '\u{102a}'), + ('\u{103f}', '\u{103f}'), ('\u{1050}', '\u{1055}'), ('\u{105a}', '\u{105d}'), ('\u{1061}', + '\u{1061}'), ('\u{1065}', '\u{1066}'), ('\u{106e}', '\u{1070}'), ('\u{1075}', '\u{1081}'), + ('\u{108e}', '\u{108e}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', + '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{1248}'), ('\u{124a}', '\u{124d}'), + ('\u{1250}', '\u{1256}'), ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', + '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), + ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', + '\u{12d6}'), ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', '\u{135a}'), + ('\u{1380}', '\u{138f}'), ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', + '\u{166c}'), ('\u{166f}', '\u{167f}'), ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), + ('\u{16ee}', '\u{16f8}'), ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), ('\u{1720}', + '\u{1731}'), ('\u{1740}', '\u{1751}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), + ('\u{1780}', '\u{17b3}'), ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dc}'), ('\u{1820}', + '\u{1877}'), ('\u{1880}', '\u{18a8}'), ('\u{18aa}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), + ('\u{1900}', '\u{191e}'), ('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}'), ('\u{1980}', + '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{1a00}', '\u{1a16}'), ('\u{1a20}', '\u{1a54}'), + ('\u{1aa7}', '\u{1aa7}'), ('\u{1b05}', '\u{1b33}'), ('\u{1b45}', '\u{1b4b}'), ('\u{1b83}', + '\u{1ba0}'), ('\u{1bae}', '\u{1baf}'), ('\u{1bba}', '\u{1be5}'), ('\u{1c00}', '\u{1c23}'), + ('\u{1c4d}', '\u{1c4f}'), ('\u{1c5a}', '\u{1c7d}'), ('\u{1c80}', '\u{1c88}'), ('\u{1ce9}', + '\u{1cec}'), ('\u{1cee}', '\u{1cf1}'), ('\u{1cf5}', '\u{1cf6}'), ('\u{1d00}', '\u{1dbf}'), + ('\u{1e00}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', + '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), + ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', '\u{1fb4}'), ('\u{1fb6}', + '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), ('\u{1fc6}', '\u{1fcc}'), + ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', '\u{1fec}'), ('\u{1ff2}', + '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', '\u{207f}'), + ('\u{2090}', '\u{209c}'), ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', + '\u{2113}'), ('\u{2115}', '\u{2115}'), ('\u{2118}', '\u{211d}'), ('\u{2124}', '\u{2124}'), + ('\u{2126}', '\u{2126}'), ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{2139}'), ('\u{213c}', + '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', '\u{214e}'), ('\u{2160}', '\u{2188}'), + ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), ('\u{2ceb}', + '\u{2cee}'), ('\u{2cf2}', '\u{2cf3}'), ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), + ('\u{2d2d}', '\u{2d2d}'), ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d80}', + '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), + ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', + '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{3005}', '\u{3007}'), ('\u{3021}', '\u{3029}'), + ('\u{3031}', '\u{3035}'), ('\u{3038}', '\u{303c}'), ('\u{3041}', '\u{3096}'), ('\u{309d}', + '\u{309f}'), ('\u{30a1}', '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312d}'), + ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', '\u{31ff}'), ('\u{3400}', + '\u{4db5}'), ('\u{4e00}', '\u{9fd5}'), ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), + ('\u{a500}', '\u{a60c}'), ('\u{a610}', '\u{a61f}'), ('\u{a62a}', '\u{a62b}'), ('\u{a640}', + '\u{a66e}'), ('\u{a67f}', '\u{a69d}'), ('\u{a6a0}', '\u{a6ef}'), ('\u{a717}', '\u{a71f}'), + ('\u{a722}', '\u{a788}'), ('\u{a78b}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', + '\u{a801}'), ('\u{a803}', '\u{a805}'), ('\u{a807}', '\u{a80a}'), ('\u{a80c}', '\u{a822}'), + ('\u{a840}', '\u{a873}'), ('\u{a882}', '\u{a8b3}'), ('\u{a8f2}', '\u{a8f7}'), ('\u{a8fb}', + '\u{a8fb}'), ('\u{a8fd}', '\u{a8fd}'), ('\u{a90a}', '\u{a925}'), ('\u{a930}', '\u{a946}'), + ('\u{a960}', '\u{a97c}'), ('\u{a984}', '\u{a9b2}'), ('\u{a9cf}', '\u{a9cf}'), ('\u{a9e0}', + '\u{a9e4}'), ('\u{a9e6}', '\u{a9ef}'), ('\u{a9fa}', '\u{a9fe}'), ('\u{aa00}', '\u{aa28}'), + ('\u{aa40}', '\u{aa42}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa60}', '\u{aa76}'), ('\u{aa7a}', + '\u{aa7a}'), ('\u{aa7e}', '\u{aaaf}'), ('\u{aab1}', '\u{aab1}'), ('\u{aab5}', '\u{aab6}'), + ('\u{aab9}', '\u{aabd}'), ('\u{aac0}', '\u{aac0}'), ('\u{aac2}', '\u{aac2}'), ('\u{aadb}', + '\u{aadd}'), ('\u{aae0}', '\u{aaea}'), ('\u{aaf2}', '\u{aaf4}'), ('\u{ab01}', '\u{ab06}'), + ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', + '\u{ab2e}'), ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', '\u{abe2}'), + ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', + '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), + ('\u{fb1d}', '\u{fb1d}'), ('\u{fb1f}', '\u{fb28}'), ('\u{fb2a}', '\u{fb36}'), ('\u{fb38}', + '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), + ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fc5d}'), ('\u{fc64}', '\u{fd3d}'), ('\u{fd50}', + '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdf9}'), ('\u{fe71}', '\u{fe71}'), + ('\u{fe73}', '\u{fe73}'), ('\u{fe77}', '\u{fe77}'), ('\u{fe79}', '\u{fe79}'), ('\u{fe7b}', + '\u{fe7b}'), ('\u{fe7d}', '\u{fe7d}'), ('\u{fe7f}', '\u{fefc}'), ('\u{ff21}', '\u{ff3a}'), + ('\u{ff41}', '\u{ff5a}'), ('\u{ff66}', '\u{ff9d}'), ('\u{ffa0}', '\u{ffbe}'), ('\u{ffc2}', + '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}'), + ('\u{10000}', '\u{1000b}'), ('\u{1000d}', '\u{10026}'), ('\u{10028}', '\u{1003a}'), + ('\u{1003c}', '\u{1003d}'), ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), + ('\u{10080}', '\u{100fa}'), ('\u{10140}', '\u{10174}'), ('\u{10280}', '\u{1029c}'), + ('\u{102a0}', '\u{102d0}'), ('\u{10300}', '\u{1031f}'), ('\u{10330}', '\u{1034a}'), + ('\u{10350}', '\u{10375}'), ('\u{10380}', '\u{1039d}'), ('\u{103a0}', '\u{103c3}'), + ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', '\u{103d5}'), ('\u{10400}', '\u{1049d}'), + ('\u{104b0}', '\u{104d3}'), ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), + ('\u{10530}', '\u{10563}'), ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), + ('\u{10760}', '\u{10767}'), ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), + ('\u{1080a}', '\u{10835}'), ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), + ('\u{1083f}', '\u{10855}'), ('\u{10860}', '\u{10876}'), ('\u{10880}', '\u{1089e}'), + ('\u{108e0}', '\u{108f2}'), ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), + ('\u{10920}', '\u{10939}'), ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), + ('\u{10a00}', '\u{10a00}'), ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), + ('\u{10a19}', '\u{10a33}'), ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), + ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac9}', '\u{10ae4}'), ('\u{10b00}', '\u{10b35}'), + ('\u{10b40}', '\u{10b55}'), ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), + ('\u{10c00}', '\u{10c48}'), ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), + ('\u{11003}', '\u{11037}'), ('\u{11083}', '\u{110af}'), ('\u{110d0}', '\u{110e8}'), + ('\u{11103}', '\u{11126}'), ('\u{11150}', '\u{11172}'), ('\u{11176}', '\u{11176}'), + ('\u{11183}', '\u{111b2}'), ('\u{111c1}', '\u{111c4}'), ('\u{111da}', '\u{111da}'), + ('\u{111dc}', '\u{111dc}'), ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1122b}'), + ('\u{11280}', '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), + ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', '\u{112de}'), + ('\u{11305}', '\u{1130c}'), ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), + ('\u{1132a}', '\u{11330}'), ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), + ('\u{1133d}', '\u{1133d}'), ('\u{11350}', '\u{11350}'), ('\u{1135d}', '\u{11361}'), + ('\u{11400}', '\u{11434}'), ('\u{11447}', '\u{1144a}'), ('\u{11480}', '\u{114af}'), + ('\u{114c4}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{11580}', '\u{115ae}'), + ('\u{115d8}', '\u{115db}'), ('\u{11600}', '\u{1162f}'), ('\u{11644}', '\u{11644}'), + ('\u{11680}', '\u{116aa}'), ('\u{11700}', '\u{11719}'), ('\u{118a0}', '\u{118df}'), + ('\u{118ff}', '\u{118ff}'), ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), + ('\u{11c0a}', '\u{11c2e}'), ('\u{11c40}', '\u{11c40}'), ('\u{11c72}', '\u{11c8f}'), + ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12480}', '\u{12543}'), + ('\u{13000}', '\u{1342e}'), ('\u{14400}', '\u{14646}'), ('\u{16800}', '\u{16a38}'), + ('\u{16a40}', '\u{16a5e}'), ('\u{16ad0}', '\u{16aed}'), ('\u{16b00}', '\u{16b2f}'), + ('\u{16b40}', '\u{16b43}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), + ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f50}'), ('\u{16f93}', '\u{16f9f}'), + ('\u{16fe0}', '\u{16fe0}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', '\u{18af2}'), + ('\u{1b000}', '\u{1b001}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), + ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1d400}', '\u{1d454}'), + ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', '\u{1d4a2}'), + ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), ('\u{1d4ae}', '\u{1d4b9}'), + ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), + ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), + ('\u{1d51e}', '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), + ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', '\u{1d6a5}'), + ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), ('\u{1d6dc}', '\u{1d6fa}'), + ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), + ('\u{1d750}', '\u{1d76e}'), ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), + ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1e800}', '\u{1e8c4}'), + ('\u{1e900}', '\u{1e943}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), + ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), + ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), + ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), + ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), + ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), + ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), + ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), + ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), + ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), + ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), + ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), + ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2f800}', '\u{2fa1d}') + ]; + + pub fn XID_Start(c: char) -> bool { + super::bsearch_range_table(c, XID_Start_table) + } + +} + diff --git a/bash-5.1/vendor/unicode-xid/src/tests.rs b/bash-5.1/vendor/unicode-xid/src/tests.rs new file mode 100644 index 0000000..f433396 --- /dev/null +++ b/bash-5.1/vendor/unicode-xid/src/tests.rs @@ -0,0 +1,113 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(feature = "bench")] +use std::iter; +#[cfg(feature = "bench")] +use test::Bencher; +#[cfg(feature = "bench")] +use std::prelude::v1::*; + +use super::UnicodeXID; + +#[cfg(feature = "bench")] +#[bench] +fn cargo_is_xid_start(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(UnicodeXID::is_xid_start) + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn stdlib_is_xid_start(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(char::is_xid_start) + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn cargo_xid_continue(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(UnicodeXID::is_xid_continue) + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn stdlib_xid_continue(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(char::is_xid_continue) + }); +} + +#[test] +fn test_is_xid_start() { + let chars = [ + 'A', 'Z', 'a', 'z', + '\u{1000d}', '\u{10026}', + ]; + + for ch in &chars { + assert!(UnicodeXID::is_xid_start(*ch), "{}", ch); + } +} + +#[test] +fn test_is_not_xid_start() { + let chars = [ + '\x00', '\x01', + '0', '9', + ' ', '[', '<', '{', '(', + '\u{02c2}', '\u{ffff}', + ]; + + for ch in &chars { + assert!(!UnicodeXID::is_xid_start(*ch), "{}", ch); + } +} + +#[test] +fn test_is_xid_continue() { + let chars = [ + '0', '9', 'A', 'Z', 'a', 'z', '_', + '\u{1000d}', '\u{10026}', + ]; + + for ch in &chars { + assert!(UnicodeXID::is_xid_continue(*ch), "{}", ch); + } +} + +#[test] +fn test_is_not_xid_continue() { + let chars = [ + '\x00', '\x01', + ' ', '[', '<', '{', '(', + '\u{02c2}', '\u{ffff}', + ]; + + for &ch in &chars { + assert!(!UnicodeXID::is_xid_continue(ch), "{}", ch); + } +} diff --git a/bash-5.1/vendor/utf8-ranges/.cargo-checksum.json b/bash-5.1/vendor/utf8-ranges/.cargo-checksum.json new file mode 100644 index 0000000..fab5035 --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYING":"01c266bced4a434da0051174d6bee16a4c82cf634e2679b6155d40d75012390f","Cargo.toml":"768ba1eefc42ef86f4f5d2f150df9661103a25c6594f3e183ce8eb147f6ba052","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","README.md":"6aef9c8b41cff99539e983d9f06a650ffdb47a4588fde54ee78364038c4e6ba0","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","benches/bench.rs":"584fefa78c1d0041e1eae4f04a7112864ddc4f39a62ce16e4de73c6df6857d66","src/char_utf8.rs":"e8125d4809fb94ac9ebc57bdf67b2dc61c9f356d76dc154576064937095e1915","src/lib.rs":"0022a915ddd64e95266c60df07dcf5154822ce5b4b8b359a66d102dc9d72edf5"},"package":"7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba"} \ No newline at end of file diff --git a/bash-5.1/vendor/utf8-ranges/COPYING b/bash-5.1/vendor/utf8-ranges/COPYING new file mode 100644 index 0000000..bb9c20a --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/COPYING @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff --git a/bash-5.1/vendor/utf8-ranges/Cargo.toml b/bash-5.1/vendor/utf8-ranges/Cargo.toml new file mode 100644 index 0000000..5ad54f7 --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/Cargo.toml @@ -0,0 +1,41 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "utf8-ranges" +version = "1.0.5" +authors = ["Andrew Gallant <jamslam@gmail.com>"] +exclude = [ + "/ci/*", + "/.travis.yml", + "/Makefile", + "/ctags.rust", + "/session.vim", +] +description = "DEPRECATED. Use regex-syntax::utf8 submodule instead." +homepage = "https://github.com/BurntSushi/utf8-ranges" +documentation = "https://docs.rs/utf8-ranges" +readme = "README.md" +keywords = [ + "codepoint", + "utf8", + "automaton", + "range", +] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/utf8-ranges" + +[dev-dependencies.quickcheck] +version = "1" +default-features = false + +[badges.travis-ci] +repository = "BurntSushi/utf8-ranges" diff --git a/bash-5.1/vendor/utf8-ranges/LICENSE-MIT b/bash-5.1/vendor/utf8-ranges/LICENSE-MIT new file mode 100644 index 0000000..3b0a5dc --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bash-5.1/vendor/utf8-ranges/README.md b/bash-5.1/vendor/utf8-ranges/README.md new file mode 100644 index 0000000..1737dc7 --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/README.md @@ -0,0 +1,57 @@ +**DEPRECATED:** This crate has been folded into the +[`regex-syntax`](https://docs.rs/regex-syntax) and is now deprecated. + +utf8-ranges +=========== +This crate converts contiguous ranges of Unicode scalar values to UTF-8 byte +ranges. This is useful when constructing byte based automata from Unicode. +Stated differently, this lets one embed UTF-8 decoding as part of one's +automaton. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/utf8-ranges.png)](https://travis-ci.org/BurntSushi/utf8-ranges) +[![](http://meritbadge.herokuapp.com/utf8-ranges)](https://crates.io/crates/utf8-ranges) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + + +### Documentation + +https://docs.rs/utf8-ranges + + +### Example + +This shows how to convert a scalar value range (e.g., the basic multilingual +plane) to a sequence of byte based character classes. + + +```rust +extern crate utf8_ranges; + +use utf8_ranges::Utf8Sequences; + +fn main() { + for range in Utf8Sequences::new('\u{0}', '\u{FFFF}') { + println!("{:?}", range); + } +} +``` + +The output: + +```text +[0-7F] +[C2-DF][80-BF] +[E0][A0-BF][80-BF] +[E1-EC][80-BF][80-BF] +[ED][80-9F][80-BF] +[EE-EF][80-BF][80-BF] +``` + +These ranges can then be used to build an automaton. Namely: + +1. Every arbitrary sequence of bytes matches exactly one of the sequences of + ranges or none of them. +2. Every match sequence of bytes is guaranteed to be valid UTF-8. (Erroneous + encodings of surrogate codepoints in UTF-8 cannot match any of the byte + ranges above.) diff --git a/bash-5.1/vendor/utf8-ranges/UNLICENSE b/bash-5.1/vendor/utf8-ranges/UNLICENSE new file mode 100644 index 0000000..68a49da --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to <http://unlicense.org/> diff --git a/bash-5.1/vendor/utf8-ranges/benches/bench.rs b/bash-5.1/vendor/utf8-ranges/benches/bench.rs new file mode 100644 index 0000000..ccffa89 --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/benches/bench.rs @@ -0,0 +1,25 @@ +#![feature(test)] + +extern crate test; +extern crate utf8_ranges; + +use test::Bencher; +use utf8_ranges::Utf8Sequences; + +#[bench] +fn no_reuse(b: &mut Bencher) { + b.iter(|| { + let count = Utf8Sequences::new('\u{0}', '\u{10FFFF}').count(); + assert_eq!(count, 9); + }) +} + +#[bench] +fn reuse(b: &mut Bencher) { + let mut seqs = Utf8Sequences::new('\u{0}', '\u{10FFFF}'); + b.iter(|| { + seqs.reset('\u{0}', '\u{10FFFF}'); + let count = (&mut seqs).count(); + assert_eq!(count, 9); + }) +} diff --git a/bash-5.1/vendor/utf8-ranges/src/char_utf8.rs b/bash-5.1/vendor/utf8-ranges/src/char_utf8.rs new file mode 100644 index 0000000..ac6be54 --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/src/char_utf8.rs @@ -0,0 +1,36 @@ +// Pulled from std::char until encode_utf8 stabilizes. ---AG + +// UTF-8 ranges and tags for encoding characters +const TAG_CONT: u8 = 0b1000_0000; +const TAG_TWO_B: u8 = 0b1100_0000; +const TAG_THREE_B: u8 = 0b1110_0000; +const TAG_FOUR_B: u8 = 0b1111_0000; +const MAX_ONE_B: u32 = 0x80; +const MAX_TWO_B: u32 = 0x800; +const MAX_THREE_B: u32 = 0x10000; + +#[inline] +pub fn encode_utf8(character: char, dst: &mut [u8]) -> Option<usize> { + let code = character as u32; + if code < MAX_ONE_B && !dst.is_empty() { + dst[0] = code as u8; + Some(1) + } else if code < MAX_TWO_B && dst.len() >= 2 { + dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; + dst[1] = (code & 0x3F) as u8 | TAG_CONT; + Some(2) + } else if code < MAX_THREE_B && dst.len() >= 3 { + dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; + dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code & 0x3F) as u8 | TAG_CONT; + Some(3) + } else if dst.len() >= 4 { + dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; + dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[3] = (code & 0x3F) as u8 | TAG_CONT; + Some(4) + } else { + None + } +} diff --git a/bash-5.1/vendor/utf8-ranges/src/lib.rs b/bash-5.1/vendor/utf8-ranges/src/lib.rs new file mode 100644 index 0000000..aa36bc4 --- /dev/null +++ b/bash-5.1/vendor/utf8-ranges/src/lib.rs @@ -0,0 +1,532 @@ +/*! +Crate `utf8-ranges` converts ranges of Unicode scalar values to equivalent +ranges of UTF-8 bytes. This is useful for constructing byte based automatons +that need to embed UTF-8 decoding. + +See the documentation on the `Utf8Sequences` iterator for more details and +an example. + +# Wait, what is this? + +This is simplest to explain with an example. Let's say you wanted to test +whether a particular byte sequence was a Cyrillic character. One possible +scalar value range is `[0400-04FF]`. The set of allowed bytes for this +range can be expressed as a sequence of byte ranges: + +```ignore +[D0-D3][80-BF] +``` + +This is simple enough: simply encode the boundaries, `0400` encodes to +`D0 80` and `04FF` encodes to `D3 BF`, and create ranges from each +corresponding pair of bytes: `D0` to `D3` and `80` to `BF`. + +However, what if you wanted to add the Cyrillic Supplementary characters to +your range? Your range might then become `[0400-052F]`. The same procedure +as above doesn't quite work because `052F` encodes to `D4 AF`. The byte ranges +you'd get from the previous transformation would be `[D0-D4][80-AF]`. However, +this isn't quite correct because this range doesn't capture many characters, +for example, `04FF` (because its last byte, `BF` isn't in the range `80-AF`). + +Instead, you need multiple sequences of byte ranges: + +```ignore +[D0-D3][80-BF] # matches codepoints 0400-04FF +[D4][80-AF] # matches codepoints 0500-052F +``` + +This gets even more complicated if you want bigger ranges, particularly if +they naively contain surrogate codepoints. For example, the sequence of byte +ranges for the basic multilingual plane (`[0000-FFFF]`) look like this: + +```ignore +[0-7F] +[C2-DF][80-BF] +[E0][A0-BF][80-BF] +[E1-EC][80-BF][80-BF] +[ED][80-9F][80-BF] +[EE-EF][80-BF][80-BF] +``` + +Note that the byte ranges above will *not* match any erroneous encoding of +UTF-8, including encodings of surrogate codepoints. + +And, of course, for all of Unicode (`[000000-10FFFF]`): + +```ignore +[0-7F] +[C2-DF][80-BF] +[E0][A0-BF][80-BF] +[E1-EC][80-BF][80-BF] +[ED][80-9F][80-BF] +[EE-EF][80-BF][80-BF] +[F0][90-BF][80-BF][80-BF] +[F1-F3][80-BF][80-BF][80-BF] +[F4][80-8F][80-BF][80-BF] +``` + +This crate automates the process of creating these byte ranges from ranges of +Unicode scalar values. + +# Why would I ever use this? + +You probably won't ever need this. In 99% of cases, you just decode the byte +sequence into a Unicode scalar value and compare scalar values directly. +However, this explicit decoding step isn't always possible. For example, the +construction of some finite state machines may benefit from converting ranges +of scalar values into UTF-8 decoder automata (e.g., for character classes in +regular expressions). + +# Lineage + +I got the idea and general implementation strategy from Russ Cox in his +[article on regexps](https://web.archive.org/web/20160404141123/https://swtch.com/~rsc/regexp/regexp3.html) and RE2. +Russ Cox got it from Ken Thompson's `grep` (no source, folk lore?). +I also got the idea from +[Lucene](https://github.com/apache/lucene-solr/blob/ae93f4e7ac6a3908046391de35d4f50a0d3c59ca/lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.java), +which uses it for executing automata on their term index. +*/ + +#![deny(missing_docs)] + +#[cfg(test)] +extern crate quickcheck; + +use std::char; +use std::fmt; +use std::slice; + +use char_utf8::encode_utf8; + +const MAX_UTF8_BYTES: usize = 4; + +mod char_utf8; + +/// Utf8Sequence represents a sequence of byte ranges. +/// +/// To match a Utf8Sequence, a candidate byte sequence must match each +/// successive range. +/// +/// For example, if there are two ranges, `[C2-DF][80-BF]`, then the byte +/// sequence `\xDD\x61` would not match because `0x61 < 0x80`. +#[derive(Copy, Clone, Eq, PartialEq)] +pub enum Utf8Sequence { + /// One byte range. + One(Utf8Range), + /// Two successive byte ranges. + Two([Utf8Range; 2]), + /// Three successive byte ranges. + Three([Utf8Range; 3]), + /// Four successive byte ranges. + Four([Utf8Range; 4]), +} + +impl Utf8Sequence { + /// Creates a new UTF-8 sequence from the encoded bytes of a scalar value + /// range. + /// + /// This assumes that `start` and `end` have the same length. + fn from_encoded_range(start: &[u8], end: &[u8]) -> Self { + assert_eq!(start.len(), end.len()); + match start.len() { + 2 => Utf8Sequence::Two([ + Utf8Range::new(start[0], end[0]), + Utf8Range::new(start[1], end[1]), + ]), + 3 => Utf8Sequence::Three([ + Utf8Range::new(start[0], end[0]), + Utf8Range::new(start[1], end[1]), + Utf8Range::new(start[2], end[2]), + ]), + 4 => Utf8Sequence::Four([ + Utf8Range::new(start[0], end[0]), + Utf8Range::new(start[1], end[1]), + Utf8Range::new(start[2], end[2]), + Utf8Range::new(start[3], end[3]), + ]), + n => unreachable!("invalid encoded length: {}", n), + } + } + + /// Returns the underlying sequence of byte ranges as a slice. + pub fn as_slice(&self) -> &[Utf8Range] { + use self::Utf8Sequence::*; + match *self { + One(ref r) => slice::from_ref(r), + Two(ref r) => &r[..], + Three(ref r) => &r[..], + Four(ref r) => &r[..], + } + } + + /// Returns the number of byte ranges in this sequence. + /// + /// The length is guaranteed to be in the closed interval `[1, 4]`. + pub fn len(&self) -> usize { + self.as_slice().len() + } + + /// Returns true if and only if a prefix of `bytes` matches this sequence + /// of byte ranges. + pub fn matches(&self, bytes: &[u8]) -> bool { + if bytes.len() < self.len() { + return false; + } + for (&b, r) in bytes.iter().zip(self) { + if !r.matches(b) { + return false; + } + } + true + } +} + +impl<'a> IntoIterator for &'a Utf8Sequence { + type IntoIter = slice::Iter<'a, Utf8Range>; + type Item = &'a Utf8Range; + + fn into_iter(self) -> Self::IntoIter { + self.as_slice().into_iter() + } +} + +impl fmt::Debug for Utf8Sequence { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Utf8Sequence::*; + match *self { + One(ref r) => write!(f, "{:?}", r), + Two(ref r) => write!(f, "{:?}{:?}", r[0], r[1]), + Three(ref r) => write!(f, "{:?}{:?}{:?}", r[0], r[1], r[2]), + Four(ref r) => write!(f, "{:?}{:?}{:?}{:?}", + r[0], r[1], r[2], r[3]), + } + } +} + +/// A single inclusive range of UTF-8 bytes. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Utf8Range { + /// Start of byte range (inclusive). + pub start: u8, + /// End of byte range (inclusive). + pub end: u8, +} + +impl Utf8Range { + fn new(start: u8, end: u8) -> Self { + Utf8Range { start: start, end: end } + } + + /// Returns true if and only if the given byte is in this range. + pub fn matches(&self, b: u8) -> bool { + self.start <= b && b <= self.end + } +} + +impl fmt::Debug for Utf8Range { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.start == self.end { + write!(f, "[{:X}]", self.start) + } else { + write!(f, "[{:X}-{:X}]", self.start, self.end) + } + } +} + +/// An iterator over ranges of matching UTF-8 byte sequences. +/// +/// The iteration represents an alternation of comprehensive byte sequences +/// that match precisely the set of UTF-8 encoded scalar values. +/// +/// A byte sequence corresponds to one of the scalar values in the range given +/// if and only if it completely matches exactly one of the sequences of byte +/// ranges produced by this iterator. +/// +/// Each sequence of byte ranges matches a unique set of bytes. That is, no two +/// sequences will match the same bytes. +/// +/// # Example +/// +/// This shows how to match an arbitrary byte sequence against a range of +/// scalar values. +/// +/// ```rust +/// use utf8_ranges::{Utf8Sequences, Utf8Sequence}; +/// +/// fn matches(seqs: &[Utf8Sequence], bytes: &[u8]) -> bool { +/// for range in seqs { +/// if range.matches(bytes) { +/// return true; +/// } +/// } +/// false +/// } +/// +/// // Test the basic multilingual plane. +/// let seqs: Vec<_> = Utf8Sequences::new('\u{0}', '\u{FFFF}').collect(); +/// +/// // UTF-8 encoding of 'a'. +/// assert!(matches(&seqs, &[0x61])); +/// // UTF-8 encoding of '☃' (`\u{2603}`). +/// assert!(matches(&seqs, &[0xE2, 0x98, 0x83])); +/// // UTF-8 encoding of `\u{10348}` (outside the BMP). +/// assert!(!matches(&seqs, &[0xF0, 0x90, 0x8D, 0x88])); +/// // Tries to match against a UTF-8 encoding of a surrogate codepoint, +/// // which is invalid UTF-8, and therefore fails, despite the fact that +/// // the corresponding codepoint (0xD800) falls in the range given. +/// assert!(!matches(&seqs, &[0xED, 0xA0, 0x80])); +/// // And fails against plain old invalid UTF-8. +/// assert!(!matches(&seqs, &[0xFF, 0xFF])); +/// ``` +/// +/// If this example seems circuitous, that's because it is! It's meant to be +/// illustrative. In practice, you could just try to decode your byte sequence +/// and compare it with the scalar value range directly. However, this is not +/// always possible (for example, in a byte based automaton). +pub struct Utf8Sequences { + range_stack: Vec<ScalarRange>, +} + +impl Utf8Sequences { + /// Create a new iterator over UTF-8 byte ranges for the scalar value range + /// given. + pub fn new(start: char, end: char) -> Self { + let mut it = Utf8Sequences { range_stack: vec![] }; + it.push(start as u32, end as u32); + it + } + + /// reset resets the scalar value range. + /// Any existing state is cleared, but resources may be reused. + /// + /// N.B. Benchmarks say that this method is dubious. + #[doc(hidden)] + pub fn reset(&mut self, start: char, end: char) { + self.range_stack.clear(); + self.push(start as u32, end as u32); + } + + fn push(&mut self, start: u32, end: u32) { + self.range_stack.push(ScalarRange { start: start, end: end }); + } +} + +struct ScalarRange { + start: u32, + end: u32, +} + +impl fmt::Debug for ScalarRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ScalarRange({:X}, {:X})", self.start, self.end) + } +} + +impl Iterator for Utf8Sequences { + type Item = Utf8Sequence; + + fn next(&mut self) -> Option<Self::Item> { + 'TOP: + while let Some(mut r) = self.range_stack.pop() { + 'INNER: + loop { + if let Some((r1, r2)) = r.split() { + self.push(r2.start, r2.end); + r.start = r1.start; + r.end = r1.end; + continue 'INNER; + } + if !r.is_valid() { + continue 'TOP; + } + for i in 1..MAX_UTF8_BYTES { + let max = max_scalar_value(i); + if r.start <= max && max < r.end { + self.push(max + 1, r.end); + r.end = max; + continue 'INNER; + } + } + if let Some(ascii_range) = r.as_ascii() { + return Some(Utf8Sequence::One(ascii_range)); + } + for i in 1..MAX_UTF8_BYTES { + let m = (1 << (6 * i)) - 1; + if (r.start & !m) != (r.end & !m) { + if (r.start & m) != 0 { + self.push((r.start | m) + 1, r.end); + r.end = r.start | m; + continue 'INNER; + } + if (r.end & m) != m { + self.push(r.end & !m, r.end); + r.end = (r.end & !m) - 1; + continue 'INNER; + } + } + } + let mut start = [0; MAX_UTF8_BYTES]; + let mut end = [0; MAX_UTF8_BYTES]; + let n = r.encode(&mut start, &mut end); + return Some(Utf8Sequence::from_encoded_range( + &start[0..n], &end[0..n])); + } + } + None + } +} + +impl ScalarRange { + /// split splits this range if it overlaps with a surrogate codepoint. + /// + /// Either or both ranges may be invalid. + fn split(&self) -> Option<(ScalarRange, ScalarRange)> { + if self.start < 0xE000 && self.end > 0xD7FF { + Some((ScalarRange { + start: self.start, + end: 0xD7FF, + }, ScalarRange { + start: 0xE000, + end: self.end, + })) + } else { + None + } + } + + /// is_valid returns true if and only if start <= end. + fn is_valid(&self) -> bool { + self.start <= self.end + } + + /// as_ascii returns this range as a Utf8Range if and only if all scalar + /// values in this range can be encoded as a single byte. + fn as_ascii(&self) -> Option<Utf8Range> { + if self.is_ascii() { + Some(Utf8Range::new(self.start as u8, self.end as u8)) + } else { + None + } + } + + /// is_ascii returns true if the range is ASCII only (i.e., takes a single + /// byte to encode any scalar value). + fn is_ascii(&self) -> bool { + self.is_valid() && self.end <= 0x7f + } + + /// encode writes the UTF-8 encoding of the start and end of this range + /// to the corresponding destination slices. + /// + /// The slices should have room for at least `MAX_UTF8_BYTES`. + fn encode(&self, start: &mut [u8], end: &mut [u8]) -> usize { + let cs = char::from_u32(self.start).unwrap(); + let ce = char::from_u32(self.end).unwrap(); + let n = encode_utf8(cs, start).unwrap(); + let m = encode_utf8(ce, end).unwrap(); + assert_eq!(n, m); + n + } +} + +fn max_scalar_value(nbytes: usize) -> u32 { + match nbytes { + 1 => 0x007F, + 2 => 0x07FF, + 3 => 0xFFFF, + 4 => 0x10FFFF, + _ => unreachable!("invalid UTF-8 byte sequence size"), + } +} + +#[cfg(test)] +mod tests { + use std::char; + + use quickcheck::{TestResult, quickcheck}; + + use {Utf8Range, Utf8Sequences}; + + fn rutf8(s: u8, e: u8) -> Utf8Range { + Utf8Range::new(s, e) + } + + fn never_accepts_surrogate_codepoints(start: char, end: char) { + for cp in 0xD800..0xE000 { + let buf = encode_surrogate(cp); + for r in Utf8Sequences::new(start, end) { + if r.matches(&buf) { + panic!( + "Sequence ({:X}, {:X}) contains range {:?}, \ + which matches surrogate code point {:X} \ + with encoded bytes {:?}", + start as u32, end as u32, r, cp, buf, + ); + } + } + } + } + + #[test] + fn codepoints_no_surrogates() { + never_accepts_surrogate_codepoints('\u{0}', '\u{FFFF}'); + never_accepts_surrogate_codepoints('\u{0}', '\u{10FFFF}'); + never_accepts_surrogate_codepoints('\u{0}', '\u{10FFFE}'); + never_accepts_surrogate_codepoints('\u{80}', '\u{10FFFF}'); + never_accepts_surrogate_codepoints('\u{D7FF}', '\u{E000}'); + } + + #[test] + fn single_codepoint_one_sequence() { + // Tests that every range of scalar values that contains a single + // scalar value is recognized by one sequence of byte ranges. + for i in 0x0..(0x10FFFF + 1) { + let c = match char::from_u32(i) { + None => continue, + Some(c) => c, + }; + let seqs: Vec<_> = Utf8Sequences::new(c, c).collect(); + assert_eq!(seqs.len(), 1); + } + } + + #[test] + fn qc_codepoints_no_surrogate() { + fn p(s: char, e: char) -> TestResult { + if s > e { + return TestResult::discard(); + } + never_accepts_surrogate_codepoints(s, e); + TestResult::passed() + } + quickcheck(p as fn(char, char) -> TestResult); + } + + #[test] + fn bmp() { + use Utf8Sequence::*; + + let seqs = Utf8Sequences::new('\u{0}', '\u{FFFF}') + .collect::<Vec<_>>(); + assert_eq!(seqs, vec![ + One(rutf8(0x0, 0x7F)), + Two([rutf8(0xC2, 0xDF), rutf8(0x80, 0xBF)]), + Three([rutf8(0xE0, 0xE0), rutf8(0xA0, 0xBF), rutf8(0x80, 0xBF)]), + Three([rutf8(0xE1, 0xEC), rutf8(0x80, 0xBF), rutf8(0x80, 0xBF)]), + Three([rutf8(0xED, 0xED), rutf8(0x80, 0x9F), rutf8(0x80, 0xBF)]), + Three([rutf8(0xEE, 0xEF), rutf8(0x80, 0xBF), rutf8(0x80, 0xBF)]), + ]); + } + + fn encode_surrogate(cp: u32) -> [u8; 3] { + const TAG_CONT: u8 = 0b1000_0000; + const TAG_THREE_B: u8 = 0b1110_0000; + + assert!(0xD800 <= cp && cp < 0xE000); + let mut dst = [0; 3]; + dst[0] = (cp >> 12 & 0x0F) as u8 | TAG_THREE_B; + dst[1] = (cp >> 6 & 0x3F) as u8 | TAG_CONT; + dst[2] = (cp & 0x3F) as u8 | TAG_CONT; + dst + } +} diff --git a/bash-5.1/vendor/vec_map/.cargo-checksum.json b/bash-5.1/vendor/vec_map/.cargo-checksum.json new file mode 100644 index 0000000..0051c1c --- /dev/null +++ b/bash-5.1/vendor/vec_map/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"051324cbce9a044f098c6577f57e054f7122f7134f473bbee65c52ee8014e066","LICENSE-APACHE":"8173d5c29b4f956d532781d2b86e4e30f83e6b7878dce18c919451d6ba707c90","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"637a32d6be7c7f2ea9fb5d2d51c4788a44a5cb100e653f8bab71a1d33ae429b1","src/lib.rs":"660ae0d68bb09c0281c75c526c0bfb2059821dee065e14f5cb31e695b4c81c2d"},"package":"f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"} \ No newline at end of file diff --git a/bash-5.1/vendor/vec_map/Cargo.toml b/bash-5.1/vendor/vec_map/Cargo.toml new file mode 100644 index 0000000..05b0833 --- /dev/null +++ b/bash-5.1/vendor/vec_map/Cargo.toml @@ -0,0 +1,31 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "vec_map" +version = "0.8.2" +authors = ["Alex Crichton <alex@alexcrichton.com>", "Jorge Aparicio <japaricious@gmail.com>", "Alexis Beingessner <a.beingessner@gmail.com>", "Brian Anderson <>", "tbu- <>", "Manish Goregaokar <>", "Aaron Turon <aturon@mozilla.com>", "Adolfo Ochagavía <>", "Niko Matsakis <>", "Steven Fackler <>", "Chase Southwood <csouth3@illinois.edu>", "Eduard Burtescu <>", "Florian Wilkens <>", "Félix Raimundo <>", "Tibor Benke <>", "Markus Siemens <markus@m-siemens.de>", "Josh Branchaud <jbranchaud@gmail.com>", "Huon Wilson <dbau.pp@gmail.com>", "Corey Farwell <coref@rwell.org>", "Aaron Liblong <>", "Nick Cameron <nrc@ncameron.org>", "Patrick Walton <pcwalton@mimiga.net>", "Felix S Klock II <>", "Andrew Paseltiner <apaseltiner@gmail.com>", "Sean McArthur <sean.monstar@gmail.com>", "Vadim Petrochenkov <>"] +exclude = ["/.travis.yml", "/deploy-docs.sh"] +description = "A simple map based on a vector for small integer keys" +homepage = "https://github.com/contain-rs/vec-map" +documentation = "https://contain-rs.github.io/vec-map/vec_map" +readme = "README.md" +keywords = ["data-structures", "collections", "vecmap", "vec_map", "contain-rs"] +license = "MIT/Apache-2.0" +repository = "https://github.com/contain-rs/vec-map" +[dependencies.serde] +version = "1.0" +features = ["derive"] +optional = true + +[features] +eders = ["serde"] diff --git a/bash-5.1/vendor/vec_map/LICENSE-APACHE b/bash-5.1/vendor/vec_map/LICENSE-APACHE new file mode 100644 index 0000000..11069ed --- /dev/null +++ b/bash-5.1/vendor/vec_map/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bash-5.1/vendor/vec_map/LICENSE-MIT b/bash-5.1/vendor/vec_map/LICENSE-MIT new file mode 100644 index 0000000..e69282e --- /dev/null +++ b/bash-5.1/vendor/vec_map/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2015 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bash-5.1/vendor/vec_map/README.md b/bash-5.1/vendor/vec_map/README.md new file mode 100644 index 0000000..17d5c5b --- /dev/null +++ b/bash-5.1/vendor/vec_map/README.md @@ -0,0 +1,15 @@ +**WARNING: THIS PROJECT IS IN MAINTENANCE MODE, DUE TO INSUFFICIENT MAINTAINER RESOURCES** + +It works fine, but will generally no longer be improved. + +We are currently only accepting changes which: + +* keep this compiling with the latest versions of Rust or its dependencies. +* have minimal review requirements, such as documentation changes (so not totally new APIs). + +------ + + +A simple map based on a vector for small integer keys. + +Documentation is available at https://contain-rs.github.io/vec-map/vec_map. diff --git a/bash-5.1/vendor/vec_map/src/lib.rs b/bash-5.1/vendor/vec_map/src/lib.rs new file mode 100644 index 0000000..0b63833 --- /dev/null +++ b/bash-5.1/vendor/vec_map/src/lib.rs @@ -0,0 +1,1623 @@ +// Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![deny(missing_docs)] + +//! A simple map based on a vector for small integer keys. Space requirements +//! are O(highest integer key). + +// optional serde support +#[cfg(feature = "serde")] +#[macro_use] +extern crate serde; + +use self::Entry::*; + +use std::cmp::{Ordering, max}; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::iter::{Enumerate, FilterMap, FromIterator}; +use std::mem::{replace, swap}; +use std::ops::{Index, IndexMut}; +use std::slice; +use std::vec; + +/// A map optimized for small integer keys. +/// +/// # Examples +/// +/// ``` +/// use vec_map::VecMap; +/// +/// let mut months = VecMap::new(); +/// months.insert(1, "Jan"); +/// months.insert(2, "Feb"); +/// months.insert(3, "Mar"); +/// +/// if !months.contains_key(12) { +/// println!("The end is near!"); +/// } +/// +/// assert_eq!(months.get(1), Some(&"Jan")); +/// +/// if let Some(value) = months.get_mut(3) { +/// *value = "Venus"; +/// } +/// +/// assert_eq!(months.get(3), Some(&"Venus")); +/// +/// // Print out all months +/// for (key, value) in &months { +/// println!("month {} is {}", key, value); +/// } +/// +/// months.clear(); +/// assert!(months.is_empty()); +/// ``` +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct VecMap<V> { + n: usize, + v: Vec<Option<V>>, +} + +/// A view into a single entry in a map, which may either be vacant or occupied. +pub enum Entry<'a, V: 'a> { + /// A vacant Entry + Vacant(VacantEntry<'a, V>), + + /// An occupied Entry + Occupied(OccupiedEntry<'a, V>), +} + +/// A vacant Entry. +pub struct VacantEntry<'a, V: 'a> { + map: &'a mut VecMap<V>, + index: usize, +} + +/// An occupied Entry. +pub struct OccupiedEntry<'a, V: 'a> { + map: &'a mut VecMap<V>, + index: usize, +} + +impl<V> Default for VecMap<V> { + #[inline] + fn default() -> Self { Self::new() } +} + +impl<V: Hash> Hash for VecMap<V> { + fn hash<H: Hasher>(&self, state: &mut H) { + // In order to not traverse the `VecMap` twice, count the elements + // during iteration. + let mut count: usize = 0; + for elt in self { + elt.hash(state); + count += 1; + } + count.hash(state); + } +} + +impl<V> VecMap<V> { + /// Creates an empty `VecMap`. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// let mut map: VecMap<&str> = VecMap::new(); + /// ``` + pub fn new() -> Self { VecMap { n: 0, v: vec![] } } + + /// Creates an empty `VecMap` with space for at least `capacity` + /// elements before resizing. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// let mut map: VecMap<&str> = VecMap::with_capacity(10); + /// ``` + pub fn with_capacity(capacity: usize) -> Self { + VecMap { n: 0, v: Vec::with_capacity(capacity) } + } + + /// Returns the number of elements the `VecMap` can hold without + /// reallocating. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// let map: VecMap<String> = VecMap::with_capacity(10); + /// assert!(map.capacity() >= 10); + /// ``` + #[inline] + pub fn capacity(&self) -> usize { + self.v.capacity() + } + + /// Reserves capacity for the given `VecMap` to contain `len` distinct keys. + /// In the case of `VecMap` this means reallocations will not occur as long + /// as all inserted keys are less than `len`. + /// + /// The collection may reserve more space to avoid frequent reallocations. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// let mut map: VecMap<&str> = VecMap::new(); + /// map.reserve_len(10); + /// assert!(map.capacity() >= 10); + /// ``` + pub fn reserve_len(&mut self, len: usize) { + let cur_len = self.v.len(); + if len >= cur_len { + self.v.reserve(len - cur_len); + } + } + + /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys. + /// In the case of `VecMap` this means reallocations will not occur as long as all inserted + /// keys are less than `len`. + /// + /// Note that the allocator may give the collection more space than it requests. + /// Therefore capacity cannot be relied upon to be precisely minimal. Prefer + /// `reserve_len` if future insertions are expected. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// let mut map: VecMap<&str> = VecMap::new(); + /// map.reserve_len_exact(10); + /// assert!(map.capacity() >= 10); + /// ``` + pub fn reserve_len_exact(&mut self, len: usize) { + let cur_len = self.v.len(); + if len >= cur_len { + self.v.reserve_exact(len - cur_len); + } + } + + /// Trims the `VecMap` of any excess capacity. + /// + /// The collection may reserve more space to avoid frequent reallocations. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// let mut map: VecMap<&str> = VecMap::with_capacity(10); + /// map.shrink_to_fit(); + /// assert_eq!(map.capacity(), 0); + /// ``` + pub fn shrink_to_fit(&mut self) { + // strip off trailing `None`s + if let Some(idx) = self.v.iter().rposition(Option::is_some) { + self.v.truncate(idx + 1); + } else { + self.v.clear(); + } + + self.v.shrink_to_fit() + } + + /// Returns an iterator visiting all keys in ascending order of the keys. + /// The iterator's element type is `usize`. + pub fn keys(&self) -> Keys<V> { + Keys { iter: self.iter() } + } + + /// Returns an iterator visiting all values in ascending order of the keys. + /// The iterator's element type is `&'r V`. + pub fn values(&self) -> Values<V> { + Values { iter: self.iter() } + } + + /// Returns an iterator visiting all values in ascending order of the keys. + /// The iterator's element type is `&'r mut V`. + pub fn values_mut(&mut self) -> ValuesMut<V> { + ValuesMut { iter_mut: self.iter_mut() } + } + + /// Returns an iterator visiting all key-value pairs in ascending order of the keys. + /// The iterator's element type is `(usize, &'r V)`. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// map.insert(3, "c"); + /// map.insert(2, "b"); + /// + /// // Print `1: a` then `2: b` then `3: c` + /// for (key, value) in map.iter() { + /// println!("{}: {}", key, value); + /// } + /// ``` + pub fn iter(&self) -> Iter<V> { + Iter { + front: 0, + back: self.v.len(), + n: self.n, + yielded: 0, + iter: self.v.iter() + } + } + + /// Returns an iterator visiting all key-value pairs in ascending order of the keys, + /// with mutable references to the values. + /// The iterator's element type is `(usize, &'r mut V)`. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// map.insert(2, "b"); + /// map.insert(3, "c"); + /// + /// for (key, value) in map.iter_mut() { + /// *value = "x"; + /// } + /// + /// for (key, value) in &map { + /// assert_eq!(value, &"x"); + /// } + /// ``` + pub fn iter_mut(&mut self) -> IterMut<V> { + IterMut { + front: 0, + back: self.v.len(), + n: self.n, + yielded: 0, + iter: self.v.iter_mut() + } + } + + /// Moves all elements from `other` into the map while overwriting existing keys. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut a = VecMap::new(); + /// a.insert(1, "a"); + /// a.insert(2, "b"); + /// + /// let mut b = VecMap::new(); + /// b.insert(3, "c"); + /// b.insert(4, "d"); + /// + /// a.append(&mut b); + /// + /// assert_eq!(a.len(), 4); + /// assert_eq!(b.len(), 0); + /// assert_eq!(a[1], "a"); + /// assert_eq!(a[2], "b"); + /// assert_eq!(a[3], "c"); + /// assert_eq!(a[4], "d"); + /// ``` + pub fn append(&mut self, other: &mut Self) { + self.extend(other.drain()); + } + + /// Splits the collection into two at the given key. + /// + /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`, + /// and the returned `Self` contains elements `[at, max_key)`. + /// + /// Note that the capacity of `self` does not change. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut a = VecMap::new(); + /// a.insert(1, "a"); + /// a.insert(2, "b"); + /// a.insert(3, "c"); + /// a.insert(4, "d"); + /// + /// let b = a.split_off(3); + /// + /// assert_eq!(a[1], "a"); + /// assert_eq!(a[2], "b"); + /// + /// assert_eq!(b[3], "c"); + /// assert_eq!(b[4], "d"); + /// ``` + pub fn split_off(&mut self, at: usize) -> Self { + let mut other = VecMap::new(); + + if at == 0 { + // Move all elements to other + // The swap will also fix .n + swap(self, &mut other); + return other + } else if at >= self.v.len() { + // No elements to copy + return other; + } + + // Look up the index of the first non-None item + let first_index = self.v.iter().position(|el| el.is_some()); + let start_index = match first_index { + Some(index) => max(at, index), + None => { + // self has no elements + return other; + } + }; + + // Fill the new VecMap with `None`s until `start_index` + other.v.extend((0..start_index).map(|_| None)); + + // Move elements beginning with `start_index` from `self` into `other` + let mut taken = 0; + other.v.extend(self.v[start_index..].iter_mut().map(|el| { + let el = el.take(); + if el.is_some() { + taken += 1; + } + el + })); + other.n = taken; + self.n -= taken; + + other + } + + /// Returns an iterator visiting all key-value pairs in ascending order of + /// the keys, emptying (but not consuming) the original `VecMap`. + /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// map.insert(3, "c"); + /// map.insert(2, "b"); + /// + /// let vec: Vec<(usize, &str)> = map.drain().collect(); + /// + /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]); + /// ``` + pub fn drain(&mut self) -> Drain<V> { + fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> { + v.map(|v| (i, v)) + } + let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr + + self.n = 0; + Drain { iter: self.v.drain(..).enumerate().filter_map(filter) } + } + + /// Returns the number of elements in the map. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut a = VecMap::new(); + /// assert_eq!(a.len(), 0); + /// a.insert(1, "a"); + /// assert_eq!(a.len(), 1); + /// ``` + pub fn len(&self) -> usize { + self.n + } + + /// Returns true if the map contains no elements. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut a = VecMap::new(); + /// assert!(a.is_empty()); + /// a.insert(1, "a"); + /// assert!(!a.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + self.n == 0 + } + + /// Clears the map, removing all key-value pairs. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut a = VecMap::new(); + /// a.insert(1, "a"); + /// a.clear(); + /// assert!(a.is_empty()); + /// ``` + pub fn clear(&mut self) { self.n = 0; self.v.clear() } + + /// Returns a reference to the value corresponding to the key. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// assert_eq!(map.get(1), Some(&"a")); + /// assert_eq!(map.get(2), None); + /// ``` + pub fn get(&self, key: usize) -> Option<&V> { + if key < self.v.len() { + self.v[key].as_ref() + } else { + None + } + } + + /// Returns true if the map contains a value for the specified key. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// assert_eq!(map.contains_key(1), true); + /// assert_eq!(map.contains_key(2), false); + /// ``` + #[inline] + pub fn contains_key(&self, key: usize) -> bool { + self.get(key).is_some() + } + + /// Returns a mutable reference to the value corresponding to the key. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// if let Some(x) = map.get_mut(1) { + /// *x = "b"; + /// } + /// assert_eq!(map[1], "b"); + /// ``` + pub fn get_mut(&mut self, key: usize) -> Option<&mut V> { + if key < self.v.len() { + self.v[key].as_mut() + } else { + None + } + } + + /// Inserts a key-value pair into the map. If the key already had a value + /// present in the map, that value is returned. Otherwise, `None` is returned. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// assert_eq!(map.insert(37, "a"), None); + /// assert_eq!(map.is_empty(), false); + /// + /// map.insert(37, "b"); + /// assert_eq!(map.insert(37, "c"), Some("b")); + /// assert_eq!(map[37], "c"); + /// ``` + pub fn insert(&mut self, key: usize, value: V) -> Option<V> { + let len = self.v.len(); + if len <= key { + self.v.extend((0..key - len + 1).map(|_| None)); + } + let was = replace(&mut self.v[key], Some(value)); + if was.is_none() { + self.n += 1; + } + was + } + + /// Removes a key from the map, returning the value at the key if the key + /// was previously in the map. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// assert_eq!(map.remove(1), Some("a")); + /// assert_eq!(map.remove(1), None); + /// ``` + pub fn remove(&mut self, key: usize) -> Option<V> { + if key >= self.v.len() { + return None; + } + let result = &mut self.v[key]; + let was = result.take(); + if was.is_some() { + self.n -= 1; + } + was + } + + /// Gets the given key's corresponding entry in the map for in-place manipulation. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut count: VecMap<u32> = VecMap::new(); + /// + /// // count the number of occurrences of numbers in the vec + /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4] { + /// *count.entry(x).or_insert(0) += 1; + /// } + /// + /// assert_eq!(count[1], 3); + /// ``` + pub fn entry(&mut self, key: usize) -> Entry<V> { + // FIXME(Gankro): this is basically the dumbest implementation of + // entry possible, because weird non-lexical borrows issues make it + // completely insane to do any other way. That said, Entry is a border-line + // useless construct on VecMap, so it's hardly a big loss. + if self.contains_key(key) { + Occupied(OccupiedEntry { + map: self, + index: key, + }) + } else { + Vacant(VacantEntry { + map: self, + index: key, + }) + } + } + + /// Retains only the elements specified by the predicate. + /// + /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map: VecMap<usize> = (0..8).map(|x|(x, x*10)).collect(); + /// map.retain(|k, _| k % 2 == 0); + /// assert_eq!(map.len(), 4); + /// ``` + pub fn retain<F>(&mut self, mut f: F) + where F: FnMut(usize, &mut V) -> bool + { + for (i, e) in self.v.iter_mut().enumerate() { + let remove = match *e { + Some(ref mut value) => !f(i, value), + None => false, + }; + if remove { + *e = None; + self.n -= 1; + } + } + } +} + +impl<'a, V> Entry<'a, V> { + /// Ensures a value is in the entry by inserting the default if empty, and + /// returns a mutable reference to the value in the entry. + pub fn or_insert(self, default: V) -> &'a mut V { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(default), + } + } + + /// Ensures a value is in the entry by inserting the result of the default + /// function if empty, and returns a mutable reference to the value in the + /// entry. + pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(default()), + } + } +} + +impl<'a, V> VacantEntry<'a, V> { + /// Sets the value of the entry with the VacantEntry's key, + /// and returns a mutable reference to it. + pub fn insert(self, value: V) -> &'a mut V { + let index = self.index; + self.map.insert(index, value); + &mut self.map[index] + } +} + +impl<'a, V> OccupiedEntry<'a, V> { + /// Gets a reference to the value in the entry. + pub fn get(&self) -> &V { + let index = self.index; + &self.map[index] + } + + /// Gets a mutable reference to the value in the entry. + pub fn get_mut(&mut self) -> &mut V { + let index = self.index; + &mut self.map[index] + } + + /// Converts the entry into a mutable reference to its value. + pub fn into_mut(self) -> &'a mut V { + let index = self.index; + &mut self.map[index] + } + + /// Sets the value of the entry with the OccupiedEntry's key, + /// and returns the entry's old value. + pub fn insert(&mut self, value: V) -> V { + let index = self.index; + self.map.insert(index, value).unwrap() + } + + /// Takes the value of the entry out of the map, and returns it. + pub fn remove(self) -> V { + let index = self.index; + self.map.remove(index).unwrap() + } +} + +impl<V: Clone> Clone for VecMap<V> { + #[inline] + fn clone(&self) -> Self { + VecMap { n: self.n, v: self.v.clone() } + } + + #[inline] + fn clone_from(&mut self, source: &Self) { + self.v.clone_from(&source.v); + self.n = source.n; + } +} + +impl<V: PartialEq> PartialEq for VecMap<V> { + fn eq(&self, other: &Self) -> bool { + self.n == other.n && self.iter().eq(other.iter()) + } +} + +impl<V: Eq> Eq for VecMap<V> {} + +impl<V: PartialOrd> PartialOrd for VecMap<V> { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + self.iter().partial_cmp(other.iter()) + } +} + +impl<V: Ord> Ord for VecMap<V> { + #[inline] + fn cmp(&self, other: &Self) -> Ordering { + self.iter().cmp(other.iter()) + } +} + +impl<V: fmt::Debug> fmt::Debug for VecMap<V> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_map().entries(self).finish() + } +} + +impl<V> FromIterator<(usize, V)> for VecMap<V> { + fn from_iter<I: IntoIterator<Item = (usize, V)>>(iter: I) -> Self { + let mut map = Self::new(); + map.extend(iter); + map + } +} + +impl<T> IntoIterator for VecMap<T> { + type Item = (usize, T); + type IntoIter = IntoIter<T>; + + /// Returns an iterator visiting all key-value pairs in ascending order of + /// the keys, consuming the original `VecMap`. + /// The iterator's element type is `(usize, &'r V)`. + /// + /// # Examples + /// + /// ``` + /// use vec_map::VecMap; + /// + /// let mut map = VecMap::new(); + /// map.insert(1, "a"); + /// map.insert(3, "c"); + /// map.insert(2, "b"); + /// + /// let vec: Vec<(usize, &str)> = map.into_iter().collect(); + /// + /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]); + /// ``` + fn into_iter(self) -> IntoIter<T> { + IntoIter { + n: self.n, + yielded: 0, + iter: self.v.into_iter().enumerate() + } + } +} + +impl<'a, T> IntoIterator for &'a VecMap<T> { + type Item = (usize, &'a T); + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T> IntoIterator for &'a mut VecMap<T> { + type Item = (usize, &'a mut T); + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +impl<V> Extend<(usize, V)> for VecMap<V> { + fn extend<I: IntoIterator<Item = (usize, V)>>(&mut self, iter: I) { + for (k, v) in iter { + self.insert(k, v); + } + } +} + +impl<'a, V: Copy> Extend<(usize, &'a V)> for VecMap<V> { + fn extend<I: IntoIterator<Item = (usize, &'a V)>>(&mut self, iter: I) { + self.extend(iter.into_iter().map(|(key, &value)| (key, value))); + } +} + +impl<V> Index<usize> for VecMap<V> { + type Output = V; + + #[inline] + fn index(&self, i: usize) -> &V { + self.get(i).expect("key not present") + } +} + +impl<'a, V> Index<&'a usize> for VecMap<V> { + type Output = V; + + #[inline] + fn index(&self, i: &usize) -> &V { + self.get(*i).expect("key not present") + } +} + +impl<V> IndexMut<usize> for VecMap<V> { + #[inline] + fn index_mut(&mut self, i: usize) -> &mut V { + self.get_mut(i).expect("key not present") + } +} + +impl<'a, V> IndexMut<&'a usize> for VecMap<V> { + #[inline] + fn index_mut(&mut self, i: &usize) -> &mut V { + self.get_mut(*i).expect("key not present") + } +} + +macro_rules! iterator { + (impl $name:ident -> $elem:ty, $($getter:ident),+) => { + impl<'a, V> Iterator for $name<'a, V> { + type Item = $elem; + + #[inline] + fn next(&mut self) -> Option<$elem> { + while self.front < self.back { + if let Some(elem) = self.iter.next() { + if let Some(x) = elem$(. $getter ())+ { + let index = self.front; + self.front += 1; + self.yielded += 1; + return Some((index, x)); + } + } + self.front += 1; + } + None + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (self.n - self.yielded, Some(self.n - self.yielded)) + } + } + } +} + +macro_rules! double_ended_iterator { + (impl $name:ident -> $elem:ty, $($getter:ident),+) => { + impl<'a, V> DoubleEndedIterator for $name<'a, V> { + #[inline] + fn next_back(&mut self) -> Option<$elem> { + while self.front < self.back { + if let Some(elem) = self.iter.next_back() { + if let Some(x) = elem$(. $getter ())+ { + self.back -= 1; + return Some((self.back, x)); + } + } + self.back -= 1; + } + None + } + } + } +} + +/// An iterator over the key-value pairs of a map. +pub struct Iter<'a, V: 'a> { + front: usize, + back: usize, + n: usize, + yielded: usize, + iter: slice::Iter<'a, Option<V>> +} + +// FIXME(#19839) Remove in favor of `#[derive(Clone)]` +impl<'a, V> Clone for Iter<'a, V> { + fn clone(&self) -> Iter<'a, V> { + Iter { + front: self.front, + back: self.back, + n: self.n, + yielded: self.yielded, + iter: self.iter.clone() + } + } +} + +iterator! { impl Iter -> (usize, &'a V), as_ref } +impl<'a, V> ExactSizeIterator for Iter<'a, V> {} +double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref } + +/// An iterator over the key-value pairs of a map, with the +/// values being mutable. +pub struct IterMut<'a, V: 'a> { + front: usize, + back: usize, + n: usize, + yielded: usize, + iter: slice::IterMut<'a, Option<V>> +} + +iterator! { impl IterMut -> (usize, &'a mut V), as_mut } +impl<'a, V> ExactSizeIterator for IterMut<'a, V> {} +double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut } + +/// An iterator over the keys of a map. +pub struct Keys<'a, V: 'a> { + iter: Iter<'a, V>, +} + +// FIXME(#19839) Remove in favor of `#[derive(Clone)]` +impl<'a, V> Clone for Keys<'a, V> { + fn clone(&self) -> Keys<'a, V> { + Keys { + iter: self.iter.clone() + } + } +} + +/// An iterator over the values of a map. +pub struct Values<'a, V: 'a> { + iter: Iter<'a, V>, +} + +// FIXME(#19839) Remove in favor of `#[derive(Clone)]` +impl<'a, V> Clone for Values<'a, V> { + fn clone(&self) -> Values<'a, V> { + Values { + iter: self.iter.clone() + } + } +} + +/// An iterator over the values of a map. +pub struct ValuesMut<'a, V: 'a> { + iter_mut: IterMut<'a, V>, +} + +/// A consuming iterator over the key-value pairs of a map. +pub struct IntoIter<V> { + n: usize, + yielded: usize, + iter: Enumerate<vec::IntoIter<Option<V>>>, +} + +/// A draining iterator over the key-value pairs of a map. +pub struct Drain<'a, V: 'a> { + iter: FilterMap< + Enumerate<vec::Drain<'a, Option<V>>>, + fn((usize, Option<V>)) -> Option<(usize, V)>> +} + +impl<'a, V> Iterator for Drain<'a, V> { + type Item = (usize, V); + + fn next(&mut self) -> Option<(usize, V)> { self.iter.next() } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } +} + +impl<'a, V> ExactSizeIterator for Drain<'a, V> {} + +impl<'a, V> DoubleEndedIterator for Drain<'a, V> { + fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() } +} + +impl<'a, V> Iterator for Keys<'a, V> { + type Item = usize; + + fn next(&mut self) -> Option<usize> { self.iter.next().map(|e| e.0) } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } +} + +impl<'a, V> ExactSizeIterator for Keys<'a, V> {} + +impl<'a, V> DoubleEndedIterator for Keys<'a, V> { + fn next_back(&mut self) -> Option<usize> { self.iter.next_back().map(|e| e.0) } +} + +impl<'a, V> Iterator for Values<'a, V> { + type Item = &'a V; + + fn next(&mut self) -> Option<(&'a V)> { self.iter.next().map(|e| e.1) } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } +} + +impl<'a, V> ExactSizeIterator for Values<'a, V> {} + +impl<'a, V> DoubleEndedIterator for Values<'a, V> { + fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back().map(|e| e.1) } +} + +impl<'a, V> Iterator for ValuesMut<'a, V> { + type Item = &'a mut V; + + fn next(&mut self) -> Option<(&'a mut V)> { self.iter_mut.next().map(|e| e.1) } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter_mut.size_hint() } +} + +impl<'a, V> ExactSizeIterator for ValuesMut<'a, V> {} + +impl<'a, V> DoubleEndedIterator for ValuesMut<'a, V> { + fn next_back(&mut self) -> Option<&'a mut V> { self.iter_mut.next_back().map(|e| e.1) } +} + +impl<V> Iterator for IntoIter<V> { + type Item = (usize, V); + + fn next(&mut self) -> Option<(usize, V)> { + loop { + match self.iter.next() { + None => return None, + Some((i, Some(value))) => { + self.yielded += 1; + return Some((i, value)) + }, + _ => {} + } + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + (self.n - self.yielded, Some(self.n - self.yielded)) + } +} + +impl<V> ExactSizeIterator for IntoIter<V> {} + +impl<V> DoubleEndedIterator for IntoIter<V> { + fn next_back(&mut self) -> Option<(usize, V)> { + loop { + match self.iter.next_back() { + None => return None, + Some((i, Some(value))) => return Some((i, value)), + _ => {} + } + } + } +} + +#[allow(dead_code)] +fn assert_properties() { + fn vec_map_covariant<'a, T>(map: VecMap<&'static T>) -> VecMap<&'a T> { map } + + fn into_iter_covariant<'a, T>(iter: IntoIter<&'static T>) -> IntoIter<&'a T> { iter } + + fn iter_covariant<'i, 'a, T>(iter: Iter<'i, &'static T>) -> Iter<'i, &'a T> { iter } + + fn keys_covariant<'i, 'a, T>(iter: Keys<'i, &'static T>) -> Keys<'i, &'a T> { iter } + + fn values_covariant<'i, 'a, T>(iter: Values<'i, &'static T>) -> Values<'i, &'a T> { iter } +} + +#[cfg(test)] +mod test { + use super::VecMap; + use super::Entry::{Occupied, Vacant}; + use std::hash::{Hash, Hasher}; + use std::collections::hash_map::DefaultHasher; + + #[test] + fn test_get_mut() { + let mut m = VecMap::new(); + assert!(m.insert(1, 12).is_none()); + assert!(m.insert(2, 8).is_none()); + assert!(m.insert(5, 14).is_none()); + let new = 100; + match m.get_mut(5) { + None => panic!(), Some(x) => *x = new + } + assert_eq!(m.get(5), Some(&new)); + } + + #[test] + fn test_len() { + let mut map = VecMap::new(); + assert_eq!(map.len(), 0); + assert!(map.is_empty()); + assert!(map.insert(5, 20).is_none()); + assert_eq!(map.len(), 1); + assert!(!map.is_empty()); + assert!(map.insert(11, 12).is_none()); + assert_eq!(map.len(), 2); + assert!(!map.is_empty()); + assert!(map.insert(14, 22).is_none()); + assert_eq!(map.len(), 3); + assert!(!map.is_empty()); + } + + #[test] + fn test_clear() { + let mut map = VecMap::new(); + assert!(map.insert(5, 20).is_none()); + assert!(map.insert(11, 12).is_none()); + assert!(map.insert(14, 22).is_none()); + map.clear(); + assert!(map.is_empty()); + assert!(map.get(5).is_none()); + assert!(map.get(11).is_none()); + assert!(map.get(14).is_none()); + } + + #[test] + fn test_insert() { + let mut m = VecMap::new(); + assert_eq!(m.insert(1, 2), None); + assert_eq!(m.insert(1, 3), Some(2)); + assert_eq!(m.insert(1, 4), Some(3)); + } + + #[test] + fn test_remove() { + let mut m = VecMap::new(); + m.insert(1, 2); + assert_eq!(m.remove(1), Some(2)); + assert_eq!(m.remove(1), None); + } + + #[test] + fn test_keys() { + let mut map = VecMap::new(); + map.insert(1, 'a'); + map.insert(2, 'b'); + map.insert(3, 'c'); + let keys: Vec<_> = map.keys().collect(); + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); + } + + #[test] + fn test_values() { + let mut map = VecMap::new(); + map.insert(1, 'a'); + map.insert(2, 'b'); + map.insert(3, 'c'); + let values: Vec<_> = map.values().cloned().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); + } + + #[test] + fn test_iterator() { + let mut m = VecMap::new(); + + assert!(m.insert(0, 1).is_none()); + assert!(m.insert(1, 2).is_none()); + assert!(m.insert(3, 5).is_none()); + assert!(m.insert(6, 10).is_none()); + assert!(m.insert(10, 11).is_none()); + + let mut it = m.iter(); + assert_eq!(it.size_hint(), (5, Some(5))); + assert_eq!(it.next().unwrap(), (0, &1)); + assert_eq!(it.size_hint(), (4, Some(4))); + assert_eq!(it.next().unwrap(), (1, &2)); + assert_eq!(it.size_hint(), (3, Some(3))); + assert_eq!(it.next().unwrap(), (3, &5)); + assert_eq!(it.size_hint(), (2, Some(2))); + assert_eq!(it.next().unwrap(), (6, &10)); + assert_eq!(it.size_hint(), (1, Some(1))); + assert_eq!(it.next().unwrap(), (10, &11)); + assert_eq!(it.size_hint(), (0, Some(0))); + assert!(it.next().is_none()); + } + + #[test] + fn test_iterator_size_hints() { + let mut m = VecMap::new(); + + assert!(m.insert(0, 1).is_none()); + assert!(m.insert(1, 2).is_none()); + assert!(m.insert(3, 5).is_none()); + assert!(m.insert(6, 10).is_none()); + assert!(m.insert(10, 11).is_none()); + + assert_eq!(m.iter().size_hint(), (5, Some(5))); + assert_eq!(m.iter().rev().size_hint(), (5, Some(5))); + assert_eq!(m.iter_mut().size_hint(), (5, Some(5))); + assert_eq!(m.iter_mut().rev().size_hint(), (5, Some(5))); + } + + #[test] + fn test_mut_iterator() { + let mut m = VecMap::new(); + + assert!(m.insert(0, 1).is_none()); + assert!(m.insert(1, 2).is_none()); + assert!(m.insert(3, 5).is_none()); + assert!(m.insert(6, 10).is_none()); + assert!(m.insert(10, 11).is_none()); + + for (k, v) in &mut m { + *v += k as isize; + } + + let mut it = m.iter(); + assert_eq!(it.next().unwrap(), (0, &1)); + assert_eq!(it.next().unwrap(), (1, &3)); + assert_eq!(it.next().unwrap(), (3, &8)); + assert_eq!(it.next().unwrap(), (6, &16)); + assert_eq!(it.next().unwrap(), (10, &21)); + assert!(it.next().is_none()); + } + + #[test] + fn test_rev_iterator() { + let mut m = VecMap::new(); + + assert!(m.insert(0, 1).is_none()); + assert!(m.insert(1, 2).is_none()); + assert!(m.insert(3, 5).is_none()); + assert!(m.insert(6, 10).is_none()); + assert!(m.insert(10, 11).is_none()); + + let mut it = m.iter().rev(); + assert_eq!(it.next().unwrap(), (10, &11)); + assert_eq!(it.next().unwrap(), (6, &10)); + assert_eq!(it.next().unwrap(), (3, &5)); + assert_eq!(it.next().unwrap(), (1, &2)); + assert_eq!(it.next().unwrap(), (0, &1)); + assert!(it.next().is_none()); + } + + #[test] + fn test_mut_rev_iterator() { + let mut m = VecMap::new(); + + assert!(m.insert(0, 1).is_none()); + assert!(m.insert(1, 2).is_none()); + assert!(m.insert(3, 5).is_none()); + assert!(m.insert(6, 10).is_none()); + assert!(m.insert(10, 11).is_none()); + + for (k, v) in m.iter_mut().rev() { + *v += k as isize; + } + + let mut it = m.iter(); + assert_eq!(it.next().unwrap(), (0, &1)); + assert_eq!(it.next().unwrap(), (1, &3)); + assert_eq!(it.next().unwrap(), (3, &8)); + assert_eq!(it.next().unwrap(), (6, &16)); + assert_eq!(it.next().unwrap(), (10, &21)); + assert!(it.next().is_none()); + } + + #[test] + fn test_move_iter() { + let mut m: VecMap<Box<_>> = VecMap::new(); + m.insert(1, Box::new(2)); + let mut called = false; + for (k, v) in m { + assert!(!called); + called = true; + assert_eq!(k, 1); + assert_eq!(v, Box::new(2)); + } + assert!(called); + } + + #[test] + fn test_drain_iterator() { + let mut map = VecMap::new(); + map.insert(1, "a"); + map.insert(3, "c"); + map.insert(2, "b"); + + let vec: Vec<_> = map.drain().collect(); + + assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]); + assert_eq!(map.len(), 0); + } + + #[test] + fn test_append() { + let mut a = VecMap::new(); + a.insert(1, "a"); + a.insert(2, "b"); + a.insert(3, "c"); + + let mut b = VecMap::new(); + b.insert(3, "d"); // Overwrite element from a + b.insert(4, "e"); + b.insert(5, "f"); + + a.append(&mut b); + + assert_eq!(a.len(), 5); + assert_eq!(b.len(), 0); + // Capacity shouldn't change for possible reuse + assert!(b.capacity() >= 4); + + assert_eq!(a[1], "a"); + assert_eq!(a[2], "b"); + assert_eq!(a[3], "d"); + assert_eq!(a[4], "e"); + assert_eq!(a[5], "f"); + } + + #[test] + fn test_split_off() { + // Split within the key range + let mut a = VecMap::new(); + a.insert(1, "a"); + a.insert(2, "b"); + a.insert(3, "c"); + a.insert(4, "d"); + + let b = a.split_off(3); + + assert_eq!(a.len(), 2); + assert_eq!(b.len(), 2); + + assert_eq!(a[1], "a"); + assert_eq!(a[2], "b"); + + assert_eq!(b[3], "c"); + assert_eq!(b[4], "d"); + + // Split at 0 + a.clear(); + a.insert(1, "a"); + a.insert(2, "b"); + a.insert(3, "c"); + a.insert(4, "d"); + + let b = a.split_off(0); + + assert_eq!(a.len(), 0); + assert_eq!(b.len(), 4); + assert_eq!(b[1], "a"); + assert_eq!(b[2], "b"); + assert_eq!(b[3], "c"); + assert_eq!(b[4], "d"); + + // Split behind max_key + a.clear(); + a.insert(1, "a"); + a.insert(2, "b"); + a.insert(3, "c"); + a.insert(4, "d"); + + let b = a.split_off(5); + + assert_eq!(a.len(), 4); + assert_eq!(b.len(), 0); + assert_eq!(a[1], "a"); + assert_eq!(a[2], "b"); + assert_eq!(a[3], "c"); + assert_eq!(a[4], "d"); + } + + #[test] + fn test_show() { + let mut map = VecMap::new(); + let empty = VecMap::<i32>::new(); + + map.insert(1, 2); + map.insert(3, 4); + + let map_str = format!("{:?}", map); + assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); + assert_eq!(format!("{:?}", empty), "{}"); + } + + #[test] + fn test_clone() { + let mut a = VecMap::new(); + + a.insert(1, 'x'); + a.insert(4, 'y'); + a.insert(6, 'z'); + + assert_eq!(a.clone().iter().collect::<Vec<_>>(), [(1, &'x'), (4, &'y'), (6, &'z')]); + } + + #[test] + fn test_eq() { + let mut a = VecMap::new(); + let mut b = VecMap::new(); + + assert!(a == b); + assert!(a.insert(0, 5).is_none()); + assert!(a != b); + assert!(b.insert(0, 4).is_none()); + assert!(a != b); + assert!(a.insert(5, 19).is_none()); + assert!(a != b); + assert!(!b.insert(0, 5).is_none()); + assert!(a != b); + assert!(b.insert(5, 19).is_none()); + assert!(a == b); + + a = VecMap::new(); + b = VecMap::with_capacity(1); + assert!(a == b); + } + + #[test] + fn test_lt() { + let mut a = VecMap::new(); + let mut b = VecMap::new(); + + assert!(!(a < b) && !(b < a)); + assert!(b.insert(2, 5).is_none()); + assert!(a < b); + assert!(a.insert(2, 7).is_none()); + assert!(!(a < b) && b < a); + assert!(b.insert(1, 0).is_none()); + assert!(b < a); + assert!(a.insert(0, 6).is_none()); + assert!(a < b); + assert!(a.insert(6, 2).is_none()); + assert!(a < b && !(b < a)); + } + + #[test] + fn test_ord() { + let mut a = VecMap::new(); + let mut b = VecMap::new(); + + assert!(a <= b && a >= b); + assert!(a.insert(1, 1).is_none()); + assert!(a > b && a >= b); + assert!(b < a && b <= a); + assert!(b.insert(2, 2).is_none()); + assert!(b > a && b >= a); + assert!(a < b && a <= b); + } + + #[test] + fn test_hash() { + fn hash<T: Hash>(t: &T) -> u64 { + let mut s = DefaultHasher::new(); + t.hash(&mut s); + s.finish() + } + + let mut x = VecMap::new(); + let mut y = VecMap::new(); + + assert!(hash(&x) == hash(&y)); + x.insert(1, 'a'); + x.insert(2, 'b'); + x.insert(3, 'c'); + + y.insert(3, 'c'); + y.insert(2, 'b'); + y.insert(1, 'a'); + + assert!(hash(&x) == hash(&y)); + + x.insert(1000, 'd'); + x.remove(1000); + + assert!(hash(&x) == hash(&y)); + } + + #[test] + fn test_from_iter() { + let xs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]; + + let map: VecMap<_> = xs.iter().cloned().collect(); + + for &(k, v) in &xs { + assert_eq!(map.get(k), Some(&v)); + } + } + + #[test] + fn test_index() { + let mut map = VecMap::new(); + + map.insert(1, 2); + map.insert(2, 1); + map.insert(3, 4); + + assert_eq!(map[3], 4); + } + + #[test] + #[should_panic] + fn test_index_nonexistent() { + let mut map = VecMap::new(); + + map.insert(1, 2); + map.insert(2, 1); + map.insert(3, 4); + + map[4]; + } + + #[test] + fn test_entry() { + let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; + + let mut map: VecMap<_> = xs.iter().cloned().collect(); + + // Existing key (insert) + match map.entry(1) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + assert_eq!(view.get(), &10); + assert_eq!(view.insert(100), 10); + } + } + + assert_eq!(map.get(1).unwrap(), &100); + assert_eq!(map.len(), 6); + + // Existing key (update) + match map.entry(2) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + let v = view.get_mut(); + *v *= 10; + } + } + + assert_eq!(map.get(2).unwrap(), &200); + assert_eq!(map.len(), 6); + + // Existing key (take) + match map.entry(3) { + Vacant(_) => unreachable!(), + Occupied(view) => { + assert_eq!(view.remove(), 30); + } + } + + assert_eq!(map.get(3), None); + assert_eq!(map.len(), 5); + + // Inexistent key (insert) + match map.entry(10) { + Occupied(_) => unreachable!(), + Vacant(view) => { + assert_eq!(*view.insert(1000), 1000); + } + } + + assert_eq!(map.get(10).unwrap(), &1000); + assert_eq!(map.len(), 6); + } + + #[test] + fn test_extend_ref() { + let mut a = VecMap::new(); + a.insert(1, "one"); + let mut b = VecMap::new(); + b.insert(2, "two"); + b.insert(3, "three"); + + a.extend(&b); + + assert_eq!(a.len(), 3); + assert_eq!(a[&1], "one"); + assert_eq!(a[&2], "two"); + assert_eq!(a[&3], "three"); + } + + #[test] + #[cfg(feature = "serde")] + fn test_serde() { + use serde::{Serialize, Deserialize}; + fn impls_serde_traits<'de, S: Serialize + Deserialize<'de>>() {} + + impls_serde_traits::<VecMap<u32>>(); + } + + #[test] + fn test_retain() { + let mut map = VecMap::new(); + map.insert(1, "one"); + map.insert(2, "two"); + map.insert(3, "three"); + map.retain(|k, v| match k { + 1 => false, + 2 => { + *v = "two changed"; + true + }, + 3 => false, + _ => panic!(), + }); + + assert_eq!(map.len(), 1); + assert_eq!(map.get(1), None); + assert_eq!(map[2], "two changed"); + assert_eq!(map.get(3), None); + } +} diff --git a/bash-5.1/vendor/winapi-0.2.8/.cargo-checksum.json b/bash-5.1/vendor/winapi-0.2.8/.cargo-checksum.json new file mode 100644 index 0000000..8723902 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"d15a0464554e57323507a2ff34925a2c592f3dffec9beb092c7ce985440f5bda","LICENSE.md":"fd232cfaeeff018cd3b9f22e0279b1c2237742999277596638800e967f6e4a29","src/activation.rs":"0e25834dfecd59391e2ecfdaa2e01bb5ac4d181778b47d0b9f67c56a6b2bd75f","src/audioclient.rs":"8c645d4ddb171620a527bcc14fa2904ff9aeb529262e68a0a9957d2ed77118be","src/audiosessiontypes.rs":"ba8cd1950cdab112861208ac1ecc35e656cbbe36e60c31315e547cfe47707685","src/basetsd.rs":"7b879d3164d5e6ec1b94d18a6b58f74a7f4e62fc279df32126e76c4f3138239d","src/bcrypt.rs":"05fe44190a37dd744bff8fc682f25a47c5f4239d417b213d18542aaa19b08b06","src/cfg.rs":"057ace203f04f8c09b6f68fefba7d3eb6644c46f2e44ca8f1364a8bc3bdd4970","src/cfgmgr32.rs":"714289f058283fc89fc79bbd4932bdbc0e9a88edd62a1787aac82c338f2dfb45","src/combaseapi.rs":"45458b1e0d918b237afd7e9581e2714b58ee009a91bbec45827694d1159a2e8b","src/commctrl.rs":"c0173aabd50f34a85c2523876fa0191d052d1d0c157f95ed228d98508806cc7d","src/commdlg.rs":"e75f64491eea54f651884eb3cc5353588c7fe54b086b43557d6d4917abbf95cd","src/corsym.rs":"301f937c7cb394675b2127a24595beef261d269d8f7cb45d6b4ac21a063985e3","src/d2d1.rs":"e7aa08883d85e2631f5327541e644b650ad009095daadef606bb06d9ac99afd3","src/d2dbasetypes.rs":"5a26048c997a580d8bb2a3512f1cb20dba411da99ffd6b23f4b0615ab9378058","src/d3d10shader.rs":"d6edf923fa8442be35b7f4ebebcd2e4bec4c3842ed5aee4bfd05c2de11edc4e0","src/d3d11.rs":"3f2f681357730df7ea954fb78903f0f0ad0bb3b577727307e751fd9598a4e837","src/d3d11shader.rs":"29612cc75ba238e2cd691fdcc01be9c79ca12b046e207d3cbfc5af23f04c4cb9","src/d3d12.rs":"906e512385e78756fe84f9a9622c510ce5a6daeb121127cf93f11af0f2fa3763","src/d3d12sdklayers.rs":"b50edb48a1c51bc7e3bf7176733c3dad4eb45a4e9747096e3b5a723052e130c8","src/d3d12shader.rs":"ff58932ef32c108348e41864f09ac6f909d641cac4f94c3e4f6c3dc4e5916521","src/d3d9.rs":"e01614130a4d68bb6e2a23f62ffb4d5016381e9026f8477aaca64851c8dcad53","src/d3d9caps.rs":"d4bcf91b7ae307388c91c19eacdb808506faea184b03178feee5c47959211b7b","src/d3d9types.rs":"1e10aae6297bc8dc083b111da496313ff19dcb9b88450e2637f8e98c0401519c","src/d3dcommon.rs":"f841b2e4df6dfccb9eb1955add24689db7b173780ec25e99b89097140a012152","src/d3dcompiler.rs":"02269410bd7f83f49391f852320ca0d76fd8d907ed22c68a003af65b3f5ab54a","src/dbghelp.rs":"c0ea5bcd04f414a696cd876439a7c4d6ee63627f4662705d189fd6e0412622f8","src/dcommon.rs":"8889ca66e2f89f1c275e5d6b7d6b203e7f25b4e7a262689b2ec6f04b9d1b5ae8","src/devpropdef.rs":"74948513ed623d3bdf1ea3fbf1f540b3e9e46efb9c1674ecccfe7f2fae5792f2","src/docobj.rs":"43e214d9d0c436a88ed2c620b8386e58e4d549ba9c8be51bf52291caf95e225d","src/dpapi.rs":"d44a1a6c9e52b34e8e87df1079b97081c646f07d0eee51f0d0cf66ae1c6fd58a","src/dsgetdc.rs":"5911c35ef3d80a5162fdbea6902f9b07033b746ff91bff2657a0971edb07bff2","src/dsound.rs":"53a5532d645e1b7995f0b4a0f0711fc66da8a27b7f8c87ce3d9e0882cfdca07c","src/dsrole.rs":"50b27a8afb11188ce24ab49620fe69ea21658148d8fd6076b8927175db5c1a9e","src/dwmapi.rs":"e65ca961eec0db275e211e04c59a8995c8c13d36ab08dc36ce197d9a4856266f","src/dwrite.rs":"f138d36e8b93778a7866cc755893b4da19cfd6ce42427139589a0bbaa294eb44","src/dxgi.rs":"5b6fcc5c665df1c0c6ed3de5d678a7bade1bb8ab1acbe952b784ce99fc817e53","src/dxgi1_2.rs":"6ba44755d715f2493236103fc5c24d7d45dff2e1fc3690aefbd4eb6c859dbc07","src/dxgi1_3.rs":"1f86a9db5fd45199fcc3ce56423e5fcf0c58df4001e2b50c5586d38ab820b78f","src/dxgi1_4.rs":"c578e6fcb82d535b20fc10232b75a7b9512d068919cc1e3f1c7cf55f3eb46460","src/dxgiformat.rs":"2e73df34f480b6ef3b5e21de0a520dacec91b00772e42786568fd162ca5e9aa6","src/dxgitype.rs":"204b8dae38c13a1dd8cd2ce6ca68851f743b416213d6db1cd0d96808bcbf7058","src/errhandlingapi.rs":"a70f9db3dd8ab60aba0daf39f12b527e54e312ca640e0b80d80c93ffdb6913c6","src/excpt.rs":"b07cf9ff0d23dd50c0776d048d0c579e401b7d729635f78998f85d35f33f05a4","src/fileapi.rs":"d31814c612bbd9372abbf6f8455fc2af89ac236c6b1855da10d66545e485ec57","src/gl.rs":"9429708bb97aeecb2c40030460ed0c3415fc0f2335c9513c68afa6157bd9b465","src/guiddef.rs":"86618dcd39c77048c7e453e6e86dafe90358eb7f97144f9672ae09e7b9855729","src/heapapi.rs":"21e420ba7641e507e8f2801d2b0ed25dbcb98e967924d711beb5cbfa8a5785e4","src/hidclass.rs":"a93380d35dc4d45807b10bbd69ee63eb8517b75989b68391685070a2fcfbefa1","src/hidpi.rs":"0b641fc119ac35761fe8e5eaed9a0781e9018598ea269d6cd386dbf5563ab9a0","src/hidsdi.rs":"50abb938ea8d0af90ccdea7ac3de4bc10fe42e34bc6a6d6eb4da1b330727da34","src/hidusage.rs":"44adc029bc89f0d4977b1295b7e998ddabf5283de66e1e33146bda8968d1d98b","src/hstring.rs":"51b3e63e3f1ed48f54c63c3e820e0563fb857b2743529d5f947f718d43425b89","src/http.rs":"ebb8b8db9e786e2683ad8b9a9066ef418df773ae7ce4d75f166cb5321f85f5a0","src/imm.rs":"b9277502f17f4cc6bde4f80f722ec1b976913355edbf162814ccfec2b3b080fd","src/inaddr.rs":"938143669da02c83a31d207be11e2176ed5219edf0e6f8f7a5534a5c6c3ce8d1","src/inspectable.rs":"b01f1814a233a77bf9f25c264747252c0464388c7d9c7302e5bde57502b8139b","src/ksmedia.rs":"acb96b1ea0cf3b5397f9037958093c6b4dbb54c4246516e57b9fed055e8e69c1","src/lib.rs":"8a7840b030f56883f68bdf90a1a04df8be2a5e2698a9ea86c73fac59c9f09b6e","src/libloaderapi.rs":"21a5d17c9f8ac4c006b515979964a8870f30710be4482083f45c6a41a16a36ce","src/lmaccess.rs":"712661c871569513334152bdcdf56c07776c560a22cd5b892a0f38e1957e28db","src/lmcons.rs":"3449aab4399cc36e7d7db551e384d82dfa4204178c4cfb9642f90645687fbc81","src/lmdfs.rs":"c351cdb2d10bf3a7c5ce7400dcdca41a792554e21e75fa9e5378ac18d8d3e4e7","src/lmerrlog.rs":"7937928544d27575e302c5e9c5e6803e9033e1f4d715e7ca29be202276d7d7a6","src/lmjoin.rs":"362cdc71f3f50099b862eff0733b3a57dd0f95cac15943135f794424f651b916","src/lsalookup.rs":"4aef1a95033444181f2b2b9df364ea165b0fdedb396c63e5d12db6b7398a3d5f","src/macros.rs":"5dacc570f226b6f1ad31d76a03675f0d182a3d578846920000fabb7cd92fc7f8","src/memoryapi.rs":"2273b8bfd7fc36dcf654c320826952ad502e8922a84174f8c1f7ed08aa555a04","src/minschannel.rs":"139828de63a0a4476de2bee454f5bca5e8a46cc29f1680339bb2804ee2d17322","src/minwinbase.rs":"6cd387a7f79e1a708bc48b5b27eaeaa7aadf0fff7a5e0a76cda0bdf3fa871863","src/minwindef.rs":"47ba4f2ec7789109ae339170715ed76288ae60ee57a4f06d5cc50a0e6855699f","src/mmdeviceapi.rs":"c8b7f7b6b78488d23ccba2b34e8765eac60ec9f08e19c96b377d957f65b1b6d1","src/mmreg.rs":"1621fad6eaa16d1e5ca95055fd11bf066b777b1343625f9fdc74e4d313d60dea","src/mmsystem.rs":"f6a2bff3bf80af1468de2c2a5f7ff2ced2b625adaf24f08f9b303965ed5ee371","src/mscat.rs":"9226a8e30546c4142e4fcdc716f8a15cc7c8081c9e875ec72ff9e8551f86f9a1","src/mssip.rs":"d7e2b91e358ff4986e700396d04f92aa1671aafada0d4889914a413177c091e1","src/nb30.rs":"dd85d7849111f04d33895835269929dc219e04de4373e91468eb053e3e0a5c52","src/ncrypt.rs":"29f168dcddeaa2cb231a7174cec672be83cca192ffc4632cead4c4a25189fb49","src/ntdef.rs":"3be66042d16a862f0fed8f48406b08c3091fbf92885a44efb7747f4a764d7de7","src/ntsecapi.rs":"dfb2cc7e23e8b20fa5ffd30ccecdb81b62d8ffeb68fdf99f93fb141ff4155afd","src/ntstatus.rs":"de6208f4e119a6405c1726433ea5e47a8b5f46b345f5809e9f580cce88360a79","src/oaidl.rs":"640c911e39888928baf77145cca34c1a768bfd759ec9709f70649a2946cb3246","src/objbase.rs":"7c9edb6a9ea72baddb15a6aec3602b3f9e7b1ce969dd655f440eae0ede1372e2","src/objidl.rs":"2a623b989f2a216edca3bd118eceff41267632839a3fd4410df9a7c126a87b64","src/objidlbase.rs":"3415a0bcd1b5b63ff48e17138ff87dae7c31eaeb323ae81f34b6712efade1d04","src/olectl.rs":"da2014c3d5858c5abff1635e1b8c8223333e7d22d28cac614aac3305a7f04ee4","src/pdh.rs":"eb01459c2acc456ecd204c6716d26027a6c77c2b4a9b698d3c922254fe2cc319","src/playsoundapi.rs":"7efddfc8601de565946c8c93074211c83b20866a1588e36e0518bba9864d0cf0","src/processsnapshot.rs":"df99a56280e6e41c5896341ffa1abe734f6c8662f4d7ea960cb97fb34c5b85d9","src/processthreadsapi.rs":"bf8edf8984ee97bc5054e68d02ec4633b5f15720602ab19c95d78e7d420c9cc8","src/propidl.rs":"88b5f176e4624063cadd8db95db52bf07cff421d73a8cfe319f992a9c99cd315","src/propsys.rs":"05c411639479f88e77383c585117a886f48ea7453260210db9f283e2cafdffbf","src/prsht.rs":"f862538c0010a51a02e5f24b3a44b54ba5993c32400b98a3b0558741ae7473a3","src/psapi.rs":"512523c5f8334c9ad221a73776c0ed2da93d8e2353dc4d2cee951ffa6ea7c163","src/qos.rs":"9ef6183b7c03b5b412f81f38ebb06048ff6266032bc236964dd994f173b82ec4","src/reason.rs":"c92aded3bbea859f110eed73b9b0fb40df6ac4a6ed6431ca69882b46b5ad5229","src/restrictederrorinfo.rs":"b8c53f4ae149ea806028cdafe699390a20202d72028b5f62836bcbf97720d133","src/roapi.rs":"dbbefb19f402a2aece66b500739b0a9e2c4d0133a8bc94d076510d5a67def175","src/roerrorapi.rs":"84a0a71a3f9ce67a577954ee5761cbd97d892eb5e7eb2c381f6bd29d4e1d4af7","src/rpc.rs":"e2293651222edf37f3ad3076adaae9033b25b06bd7b88ed7372585a4ae46c7d9","src/rpcdce.rs":"de77ca3c9b689ffaaf395a6882d3dfc3a1cec181efa6cb6075e605e4462bc3f6","src/sapi.rs":"05dbc1166b836251538c9e52a772fa584a1d0a1ad823e4336ab5e6cfefb96d57","src/schannel.rs":"e48926896227ffae5033bd634a7c71f5359d7a08b7b8c6e94e03864d87a37f8b","src/servprov.rs":"f086b4330162c7da711ea59d7023304a8fa2a53470b54d846ea1c11567703693","src/setupapi.rs":"4959862dd39597cd711022fcefbaf5c75b61410d57d04e9dbec2ddf7a2fa6f31","src/shellapi.rs":"ce3e3e7cd8aefe8068d6c51256827c0c3d51a449e4ab73e7125ea28d44dd6b6d","src/shellscalingapi.rs":"59c162b0215ff4b71b3535b6e142cca8cd99028031f47f0a6efb960c160a8776","src/shlguid.rs":"dcb7a1ada1b1b90f405e6dea8bcf1fc6994725b49a3165b7908670b2c31490e5","src/shlobj.rs":"53ff059ec6123001bed8f007c36e40812f83e4e04bd50b371319d10b4e38c36f","src/shobjidl.rs":"953d6ef4dc2a0d175d7133dc2f41255123ab8f778b22feaebd8ca1fa77356aa7","src/shtypes.rs":"ff785004e819bcfc521ab79327e58f98debab4e40c20412bbecdcee1b2801371","src/spapidef.rs":"9abe751425b6aaac7e4a7ea49f6d8e859f8f73164abd4d69b48e3e224d7de829","src/sql.rs":"004ed353b40bb4bceab55d6e8c33063a8eac992b076e47e6ead8303dbbc5b67f","src/sqltypes.rs":"0c5fa183c9f5b9e16e292de6a9afdf73f554730e651250856148ac04718803b8","src/sspi.rs":"dbd9d544abea4396983867ef4f7fbe2588673cc953dbeb74e7edc46503b16fa0","src/strmif.rs":"168040999cf99843cc1447988e46c56481a7a343ae41ab854db40ef566fa1119","src/subauth.rs":"183dd0df6436e9f0e859d62ca78e8ed42d4c1a5dc0690dcf22d42467fd2e0700","src/synchapi.rs":"cfce677c85377a340cb9307d9ac9eb06ffe9fd5e2ce08ed4a0390729e3a7d717","src/sysinfoapi.rs":"9a5579143263ce20d8c365b9874a0ae90ef28bc3295eab26ba3782efa48b464a","src/threadpoolapi.rs":"57876ea70b86d08663f7916ce076547f17596c26b8bf4dfafbad60e78264ff95","src/timezoneapi.rs":"5ccd80e6d16a858c56e20a7f3c5570e29777dab0fdfc057b6d2fb06463d56eb3","src/tlhelp32.rs":"c96ef7416bceab473463cc4ad98f037aeaac87bb7adf45cc16c281308537e82f","src/unknwnbase.rs":"2708c19491deb7364100025f3bb88a791c219551a65af70a776f8f3c5bf18b05","src/urlhist.rs":"8c8c0d0a613e59f68bf0e8cec061ea2126baa98d1479df4d07c8df5e41b50bc1","src/urlmon.rs":"0652e602ef2f5826360e5eab68bdf4f9365827a012c2c89289c54016ea001b74","src/usb.rs":"7e682ee819b237eabe796e604cff2434c450f724f4c86d919683eb7a5167c343","src/usbspec.rs":"d19671960838eb592cda4cd7c84c6f66cd9484f0904b5a28e1d8fd91e9c2c6af","src/usp10.rs":"baa2c1ef6ca5f064bc55b24f39c0553ede45a87b9183318572916fd4f1c679c6","src/vadefs.rs":"0e2f12fd1c521a943908669b2d10fceea409bac45242ec6e87c0e69706c1b3d0","src/vsbackup.rs":"af71cb851bd7eacde9d3e46a112497baef3ecebb472aae3c76c7faff804d33f9","src/vss.rs":"a626613810a69309b8f50d0a3bd75928d9de771c2287b6242487cb8cd55394a0","src/vsserror.rs":"f06b108d66ea9f06ad15d83b981117ed6a2a9cd218bb3bf53f13b0055acd9b2e","src/vswriter.rs":"8c4f5d27fa0883d187506538136cc610074941bb952afbe0984f7cb7c3c656f7","src/werapi.rs":"a2d692514ff3a61126971c5c2c5a7298c0f822559550a7f14501f8c96d1d951a","src/winbase.rs":"e224c40d827b1f1a9c74643c000f71e87ad18f749810cc611425af325c9472b8","src/wincon.rs":"402c5ebf80aa6ab1002935b7ddca17e8a243d0c714982054395862fe0ae40a04","src/wincred.rs":"e5fa987622dd880151ae190bb45daa666ffae3ae8e2da97407210afe01dd93d6","src/wincrypt.rs":"f7f8743b6a89d3f5e8b07405e43010bb3729aa8a8cf4546cc02705f802947ebc","src/windef.rs":"89fa9f5ab2909a4840f16979ebbc0afa2134abcb1d47cb7435b581f31b227658","src/windowscodecs.rs":"7c63bc4e2d0e7ce60c7bb13b93ef5aa12213f71a46845b6e034a9c224ef3eb3c","src/windowsx.rs":"414a9a841590f88804da3eb9ba55d583372a467cc50ab1ebdd7cfc653ce5f627","src/winerror.rs":"f3882eba4e299acbdedd548feb1ff89de958fb72d665bd6ba013b6a1f7596b52","src/winevt.rs":"64ae96f475ed98da7a84704d53d16caccbac2dbd525de0ef0f65fc58a6775ed1","src/wingdi.rs":"35aa9dd14b4b4c5a227ac3df0d312c19cbaede2d1388c26ad8eb910e80efeafd","src/winhttp.rs":"37769be104a2eb9efa70ffd74c8f38a09d9639cf575a677ad75d941e8d87cd58","src/winioctl.rs":"0f0efe0a41894a325b70428d04aeddec8dd7a87a91489a4e564a248e8498861b","src/winnetwk.rs":"d492c3d14a422f611166d39b895ddc6dd749ebc64a020bf3125af452494f91dd","src/winnls.rs":"90904d6adad70081a620165223fb4a71b64d747596c64d0df7de9511cd0f75c6","src/winnt.rs":"2c51ad0a065006010f1cfe7a3335274304e4747adc63f9798e1ca1f7091154a5","src/winreg.rs":"c687a5c6433daa13793815ef9af8befaedc9635be14eea0c618ad5334952dc31","src/winscard.rs":"78ab1d3ae22e486726740c343a4cc6268ca318de43f4b7d7ba51acbdf1b93936","src/winsmcrd.rs":"62be129c3d4cdea9dd31e769b587f071a94c347c8df71a43bb1eea18d52a60cc","src/winsock2.rs":"21dc0393f37f56c15c59d49a32861fb24c8f28d43ce26b56d958a174a5040a76","src/winspool.rs":"a3bd8e04f2db6118fe529bf52cb856a773cd8b816d197fc8edc8ac942578fd74","src/winstring.rs":"dc535f972d93be2fe067a5ca64edb45b6ad8e4549ecc0ce24486bd94555d5707","src/winsvc.rs":"7999f00b341f3e0e8701ea89f71986a6600650ff8cffdb1292e9f55d47bd0a3e","src/winusb.rs":"0ac355aa879a4aae501db04f1e8859dbef5e33fda9d46a7a12ef25e5524ec396","src/winusbio.rs":"8e2d64832999b59b2ea900396184c36d34cf94c97f31e15916c299213748a3e1","src/winuser.rs":"791bd8625812feccc8ec421489194d635c94cb4c4d754287a0caa54fa8f71c19","src/ws2def.rs":"0a1c7a69e4da8edc0584b0e3fb4ad1fa4aed621510b1bc1b0d104990577c6a38","src/ws2ipdef.rs":"c6a898cf25d187ad83e110af1e2286824868691a60818ecc44e68fa0bbbd4ff6","src/ws2spi.rs":"e63da700de55a317769230319eb9e4ec85cc0ac80b2baa076399367338b7ca0f","src/ws2tcpip.rs":"698084fd5d631a2ef236fe76001e7c44afd9b8958243e4ad4c098ac4beb4b352","src/wtypes.rs":"2689e8f442ccdc0b0e1ec82160a5cc3e80abf95dca82855ec595314062774a14","src/wtypesbase.rs":"f6dc0a8b09f3f003339c5dd366bdddb9dd671894be9dcf4a42058b226d2917a8","src/xinput.rs":"e15cd46bf18977481e22d609f8e0bb5508776902d7fa64477bb5b78596c0f67d"},"package":"167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"} \ No newline at end of file diff --git a/bash-5.1/vendor/winapi-0.2.8/Cargo.toml b/bash-5.1/vendor/winapi-0.2.8/Cargo.toml new file mode 100644 index 0000000..941a659 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/Cargo.toml @@ -0,0 +1,61 @@ +[package] +name = "winapi" +version = "0.2.8" +authors = ["Peter Atashian <retep998@gmail.com>"] +description = "Types and constants for WinAPI bindings. See README for list of crates providing function bindings." +documentation = "https://retep998.github.io/doc/winapi/" +repository = "https://github.com/retep998/winapi-rs" +readme = "README.md" +keywords = ["windows", "ffi", "win32", "com", "directx"] +license = "MIT" +include = ["src/**/*", "Cargo.toml", "LICENSE.md"] + +[dev-dependencies] +advapi32-sys = { version = "0", path = "lib/advapi32" } +bcrypt-sys = { version = "0", path = "lib/bcrypt" } +comctl32-sys = { version = "0", path = "lib/comctl32" } +comdlg32-sys = { version = "0", path = "lib/comdlg32" } +credui-sys = { version = "0", path = "lib/credui" } +crypt32-sys = { version = "0", path = "lib/crypt32" } +d2d1-sys = { version = "0", path = "lib/d2d1" } +d3d11-sys = { version = "0", path = "lib/d3d11" } +d3d12-sys = { version = "0", path = "lib/d3d12" } +d3d9-sys = { version = "0", path = "lib/d3d9" } +d3dcompiler-sys = { version = "0", path = "lib/d3dcompiler" } +dbghelp-sys = { version = "0", path = "lib/dbghelp" } +dsound-sys = { version = "0", path = "lib/dsound" } +dwmapi-sys = { version = "0", path = "lib/dwmapi" } +dwrite-sys = { version = "0", path = "lib/dwrite" } +dxgi-sys = { version = "0", path = "lib/dxgi" } +dxguid-sys = { version = "0", path = "lib/dxguid" } +gdi32-sys = { version = "0", path = "lib/gdi32" } +hid-sys = { version = "0", path = "lib/hid" } +httpapi-sys = { version = "0", path = "lib/httpapi" } +kernel32-sys = { version = "0", path = "lib/kernel32" } +ktmw32-sys = { version = "0", path = "lib/ktmw32" } +mpr-sys = { version = "0", path = "lib/mpr" } +netapi32-sys = { version = "0", path = "lib/netapi32" } +odbc32-sys = { version = "0", path = "lib/odbc32" } +ole32-sys = { version = "0", path = "lib/ole32" } +oleaut32-sys = { version = "0", path = "lib/oleaut32" } +opengl32-sys = { version = "0", path = "lib/opengl32" } +pdh-sys = { version = "0", path = "lib/pdh" } +psapi-sys = { version = "0", path = "lib/psapi" } +runtimeobject-sys = { version = "0", path = "lib/runtimeobject" } +secur32-sys = { version = "0", path = "lib/secur32" } +setupapi-sys = { version = "0", path = "lib/setupapi" } +shell32-sys = { version = "0", path = "lib/shell32" } +shlwapi-sys = { version = "0", path = "lib/shlwapi" } +user32-sys = { version = "0", path = "lib/user32" } +userenv-sys = { version = "0", path = "lib/userenv" } +usp10-sys = { version = "0", path = "lib/usp10" } +uuid-sys = { version = "0", path = "lib/uuid" } +vssapi-sys = { version = "0", path = "lib/vssapi" } +wevtapi-sys = { version = "0", path = "lib/wevtapi" } +winhttp-sys = { version = "0", path = "lib/winhttp" } +winmm-sys = { version = "0", path = "lib/winmm" } +winscard-sys = { version = "0", path = "lib/winscard" } +winspool-sys = { version = "0", path = "lib/winspool" } +winusb-sys = { version = "0", path = "lib/winusb" } +ws2_32-sys = { version = "0", path = "lib/ws2_32" } +xinput-sys = { version = "0", path = "lib/xinput" } diff --git a/bash-5.1/vendor/winapi-0.2.8/LICENSE.md b/bash-5.1/vendor/winapi-0.2.8/LICENSE.md new file mode 100644 index 0000000..60d12ac --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Peter Atashian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bash-5.1/vendor/winapi-0.2.8/src/activation.rs b/bash-5.1/vendor/winapi-0.2.8/src/activation.rs new file mode 100644 index 0000000..f94f81b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/activation.rs @@ -0,0 +1,5 @@ +RIDL!( +interface IActivationFactory(IActivationFactoryVtbl): IInspectable(IInspectableVtbl) { + fn ActivateInstance(&mut self, instance: *mut *mut ::IInspectable) -> ::HRESULT +} +); \ No newline at end of file diff --git a/bash-5.1/vendor/winapi-0.2.8/src/audioclient.rs b/bash-5.1/vendor/winapi-0.2.8/src/audioclient.rs new file mode 100644 index 0000000..5a5ee6a --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/audioclient.rs @@ -0,0 +1,71 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +//1627 +pub const AUDCLNT_E_NOT_INITIALIZED: ::HRESULT = AUDCLNT_ERR!(0x001); +pub const AUDCLNT_E_ALREADY_INITIALIZED: ::HRESULT = AUDCLNT_ERR!(0x002); +pub const AUDCLNT_E_WRONG_ENDPOINT_TYPE: ::HRESULT = AUDCLNT_ERR!(0x003); +pub const AUDCLNT_E_DEVICE_INVALIDATED: ::HRESULT = AUDCLNT_ERR!(0x004); +pub const AUDCLNT_E_NOT_STOPPED: ::HRESULT = AUDCLNT_ERR!(0x005); +pub const AUDCLNT_E_BUFFER_TOO_LARGE: ::HRESULT = AUDCLNT_ERR!(0x006); +pub const AUDCLNT_E_OUT_OF_ORDER: ::HRESULT = AUDCLNT_ERR!(0x007); +pub const AUDCLNT_E_UNSUPPORTED_FORMAT: ::HRESULT = AUDCLNT_ERR!(0x008); +pub const AUDCLNT_E_INVALID_SIZE: ::HRESULT = AUDCLNT_ERR!(0x009); +pub const AUDCLNT_E_DEVICE_IN_USE: ::HRESULT = AUDCLNT_ERR!(0x00a); +pub const AUDCLNT_E_BUFFER_OPERATION_PENDING: ::HRESULT = AUDCLNT_ERR!(0x00b); +pub const AUDCLNT_E_THREAD_NOT_REGISTERED: ::HRESULT = AUDCLNT_ERR!(0x00c); +pub const AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: ::HRESULT = AUDCLNT_ERR!(0x00e); +pub const AUDCLNT_E_ENDPOINT_CREATE_FAILED: ::HRESULT = AUDCLNT_ERR!(0x00f); +pub const AUDCLNT_E_SERVICE_NOT_RUNNING: ::HRESULT = AUDCLNT_ERR!(0x010); +pub const AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: ::HRESULT = AUDCLNT_ERR!(0x011); +pub const AUDCLNT_E_EXCLUSIVE_MODE_ONLY: ::HRESULT = AUDCLNT_ERR!(0x012); +pub const AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: ::HRESULT = AUDCLNT_ERR!(0x013); +pub const AUDCLNT_E_EVENTHANDLE_NOT_SET: ::HRESULT = AUDCLNT_ERR!(0x014); +pub const AUDCLNT_E_INCORRECT_BUFFER_SIZE: ::HRESULT = AUDCLNT_ERR!(0x015); +pub const AUDCLNT_E_BUFFER_SIZE_ERROR: ::HRESULT = AUDCLNT_ERR!(0x016); +pub const AUDCLNT_E_CPUUSAGE_EXCEEDED: ::HRESULT = AUDCLNT_ERR!(0x017); +pub const AUDCLNT_E_BUFFER_ERROR: ::HRESULT = AUDCLNT_ERR!(0x018); +pub const AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: ::HRESULT = AUDCLNT_ERR!(0x019); +pub const AUDCLNT_E_INVALID_DEVICE_PERIOD: ::HRESULT = AUDCLNT_ERR!(0x020); +pub const AUDCLNT_E_INVALID_STREAM_FLAG: ::HRESULT = AUDCLNT_ERR!(0x021); +pub const AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: ::HRESULT = AUDCLNT_ERR!(0x022); +pub const AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: ::HRESULT = AUDCLNT_ERR!(0x023); +pub const AUDCLNT_E_OFFLOAD_MODE_ONLY: ::HRESULT = AUDCLNT_ERR!(0x024); +pub const AUDCLNT_E_NONOFFLOAD_MODE_ONLY: ::HRESULT = AUDCLNT_ERR!(0x025); +pub const AUDCLNT_E_RESOURCES_INVALIDATED: ::HRESULT = AUDCLNT_ERR!(0x026); +pub const AUDCLNT_E_RAW_MODE_UNSUPPORTED: ::HRESULT = AUDCLNT_ERR!(0x027); +pub const AUDCLNT_S_BUFFER_EMPTY: ::SCODE = AUDCLNT_SUCCESS!(0x001); +pub const AUDCLNT_S_THREAD_ALREADY_REGISTERED: ::SCODE = AUDCLNT_SUCCESS!(0x002); +pub const AUDCLNT_S_POSITION_STALLED: ::SCODE = AUDCLNT_SUCCESS!(0x003); +DEFINE_GUID!(IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4c32, + 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2); +DEFINE_GUID!(IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, + 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2); +RIDL!{interface IAudioClient(IAudioClientVtbl): IUnknown(IUnknownVtbl) { + fn Initialize( + &mut self, ShareMode: ::AUDCLNT_SHAREMODE, StreamFlags: ::DWORD, + hnsBufferDuration: ::REFERENCE_TIME, hnsPeriodicity: ::REFERENCE_TIME, + pFormat: *const ::WAVEFORMATEX, AudioSessionGuid: ::LPCGUID + ) -> ::HRESULT, + fn GetBufferSize(&mut self, pNumBufferFrames: *mut ::UINT32) -> ::HRESULT, + fn GetStreamLatency(&mut self, phnsLatency: *mut ::REFERENCE_TIME) -> ::HRESULT, + fn GetCurrentPadding(&mut self, pNumPaddingFrames: *mut ::UINT32) -> ::HRESULT, + fn IsFormatSupported( + &mut self, ShareMode: ::AUDCLNT_SHAREMODE, pFormat: *const ::WAVEFORMATEX, + ppClosestMatch: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetMixFormat(&mut self, ppDeviceFormat: *mut *mut ::WAVEFORMATEX) -> ::HRESULT, + fn GetDevicePeriod( + &mut self, phnsDefaultDevicePeriod: *mut ::REFERENCE_TIME, + phnsMinimumDevicePeriod: *mut ::REFERENCE_TIME + ) -> ::HRESULT, + fn Start(&mut self) -> ::HRESULT, + fn Stop(&mut self) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn SetEventHandle(&mut self, eventHandle: ::HANDLE) -> ::HRESULT, + fn GetService(&mut self, riid: ::REFIID, ppv: *mut ::LPVOID) -> ::HRESULT +}} +RIDL!{interface IAudioRenderClient(IAudioRenderClientVtbl): IUnknown(IUnknownVtbl) { + fn GetBuffer(&mut self, NumFramesRequested: ::UINT32, ppData: *mut *mut ::BYTE) -> ::HRESULT, + fn ReleaseBuffer(&mut self, NumFramesWritten: ::UINT32, dwFlags: ::DWORD) -> ::HRESULT +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/audiosessiontypes.rs b/bash-5.1/vendor/winapi-0.2.8/src/audiosessiontypes.rs new file mode 100644 index 0000000..796f17f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/audiosessiontypes.rs @@ -0,0 +1,11 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +ENUM!{enum AUDCLNT_SHAREMODE { + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_SHAREMODE_EXCLUSIVE, +}} +pub const AUDCLNT_STREAMFLAGS_CROSSPROCESS: ::DWORD = 0x00010000; +pub const AUDCLNT_STREAMFLAGS_LOOPBACK: ::DWORD = 0x00020000; +pub const AUDCLNT_STREAMFLAGS_EVENTCALLBACK: ::DWORD = 0x00040000; +pub const AUDCLNT_STREAMFLAGS_NOPERSIST: ::DWORD = 0x00080000; +pub const AUDCLNT_STREAMFLAGS_RATEADJUST: ::DWORD = 0x00100000; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/basetsd.rs b/bash-5.1/vendor/winapi-0.2.8/src/basetsd.rs new file mode 100644 index 0000000..6bf20fc --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/basetsd.rs @@ -0,0 +1,99 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Type definitions for the basic sized types. +#[cfg(target_arch = "x86")] +pub type POINTER_64_INT = ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type POINTER_64_INT = ::__uint64; +pub type INT8 = ::c_schar; +pub type PINT8 = *mut ::c_schar; +pub type INT16 = ::c_short; +pub type PINT16 = *mut ::c_short; +pub type INT32 = ::c_int; +pub type PINT32 = *mut ::c_int; +pub type INT64 = ::__int64; +pub type PINT64 = *mut ::__int64; +pub type UINT8 = ::c_uchar; +pub type PUINT8 = *mut ::c_uchar; +pub type UINT16 = ::c_ushort; +pub type PUINT16 = *mut ::c_ushort; +pub type UINT32 = ::c_uint; +pub type PUINT32 = *mut ::c_uint; +pub type UINT64 = ::__uint64; +pub type PUINT64 = *mut ::__uint64; +pub type LONG32 = ::c_int; +pub type PLONG32 = *mut ::c_int; +pub type ULONG32 = ::c_uint; +pub type PULONG32 = *mut ::c_uint; +pub type DWORD32 = ::c_uint; +pub type PDWORD32 = *mut ::c_uint; +#[cfg(target_arch = "x86")] +pub type INT_PTR = ::c_int; +#[cfg(target_arch = "x86_64")] +pub type INT_PTR = ::__int64; +#[cfg(target_arch = "x86")] +pub type PINT_PTR = *mut ::c_int; +#[cfg(target_arch = "x86_64")] +pub type PINT_PTR = *mut ::__int64; +#[cfg(target_arch = "x86")] +pub type UINT_PTR = ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type UINT_PTR = ::__uint64; +#[cfg(target_arch = "x86")] +pub type PUINT_PTR = *mut ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type PUINT_PTR = *mut ::__uint64; +#[cfg(target_arch = "x86")] +pub type LONG_PTR = ::c_long; +#[cfg(target_arch = "x86_64")] +pub type LONG_PTR = ::__int64; +#[cfg(target_arch = "x86")] +pub type PLONG_PTR = *mut ::c_long; +#[cfg(target_arch = "x86_64")] +pub type PLONG_PTR = *mut ::__int64; +#[cfg(target_arch = "x86")] +pub type ULONG_PTR = ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type ULONG_PTR = ::__uint64; +#[cfg(target_arch = "x86")] +pub type PULONG_PTR = *mut ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type PULONG_PTR = *mut ::__uint64; +#[cfg(target_arch = "x86_64")] +pub type SHANDLE_PTR = ::__int64; +#[cfg(target_arch = "x86_64")] +pub type HANDLE_PTR = ::__uint64; +#[cfg(target_arch = "x86_64")] +pub type UHALF_PTR = ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type PUHALF_PTR = *mut ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type HALF_PTR = ::c_int; +#[cfg(target_arch = "x86_64")] +pub type PHALF_PTR = *mut ::c_int; +#[cfg(target_arch = "x86")] +pub type SHANDLE_PTR = ::c_long; +#[cfg(target_arch = "x86")] +pub type HANDLE_PTR = ::c_ulong; +#[cfg(target_arch = "x86")] +pub type UHALF_PTR = ::c_ushort; +#[cfg(target_arch = "x86")] +pub type PUHALF_PTR = *mut ::c_ushort; +#[cfg(target_arch = "x86")] +pub type HALF_PTR = ::c_short; +#[cfg(target_arch = "x86")] +pub type PHALF_PTR = *mut ::c_short; +pub type SIZE_T = ULONG_PTR; +pub type PSIZE_T = *mut ULONG_PTR; +pub type SSIZE_T = LONG_PTR; +pub type PSSIZE_T = *mut LONG_PTR; +pub type DWORD_PTR = ULONG_PTR; +pub type PDWORD_PTR = *mut ULONG_PTR; +pub type LONG64 = ::__int64; +pub type PLONG64 = *mut ::__int64; +pub type ULONG64 = ::__uint64; +pub type PULONG64 = *mut ::__uint64; +pub type DWORD64 = ::__uint64; +pub type PDWORD64 = *mut ::__uint64; +pub type KAFFINITY = ULONG_PTR; +pub type PKAFFINITY = *mut KAFFINITY; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/bcrypt.rs b/bash-5.1/vendor/winapi-0.2.8/src/bcrypt.rs new file mode 100644 index 0000000..ee818a5 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/bcrypt.rs @@ -0,0 +1,356 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Cryptographic Primitive API Prototypes and Definitions +pub const KDF_HASH_ALGORITHM: ::ULONG = 0x0; +pub const KDF_SECRET_PREPEND: ::ULONG = 0x1; +pub const KDF_SECRET_APPEND: ::ULONG = 0x2; +pub const KDF_HMAC_KEY: ::ULONG = 0x3; +pub const KDF_TLS_PRF_LABEL: ::ULONG = 0x4; +pub const KDF_TLS_PRF_SEED: ::ULONG = 0x5; +pub const KDF_SECRET_HANDLE: ::ULONG = 0x6; +pub const KDF_TLS_PRF_PROTOCOL: ::ULONG = 0x7; +pub const KDF_ALGORITHMID: ::ULONG = 0x8; +pub const KDF_PARTYUINFO: ::ULONG = 0x9; +pub const KDF_PARTYVINFO: ::ULONG = 0xA; +pub const KDF_SUPPPUBINFO: ::ULONG = 0xB; +pub const KDF_SUPPPRIVINFO: ::ULONG = 0xC; +pub const KDF_LABEL: ::ULONG = 0xD; +pub const KDF_CONTEXT: ::ULONG = 0xE; +pub const KDF_SALT: ::ULONG = 0xF; +pub const KDF_ITERATION_COUNT: ::ULONG = 0x10; +pub const KDF_GENERIC_PARAMETER: ::ULONG = 0x11; +pub const KDF_KEYBITLENGTH: ::ULONG = 0x12; +pub const KDF_USE_SECRET_AS_HMAC_KEY_FLAG: ::ULONG = 0x1; +STRUCT!{struct BCRYPT_KEY_LENGTHS_STRUCT { + dwMinLength: ::ULONG, + dwMaxLength: ::ULONG, + dwIncrement: ::ULONG, +}} +pub type BCRYPT_AUTH_TAG_LENGTHS_STRUCT = BCRYPT_KEY_LENGTHS_STRUCT; +STRUCT!{struct BCRYPT_OID { + cbOID: ::ULONG, + pbOID: ::PUCHAR, +}} +STRUCT!{struct BCRYPT_OID_LIST { + dwOIDCount: ::ULONG, + pOIDs: *mut BCRYPT_OID, +}} +STRUCT!{struct BCRYPT_PKCS1_PADDING_INFO { + pszAlgId: ::LPCWSTR, +}} +STRUCT!{struct BCRYPT_PSS_PADDING_INFO { + pszAlgId: ::LPCWSTR, + cbSalt: ::ULONG, +}} +STRUCT!{struct BCRYPT_OAEP_PADDING_INFO { + pszAlgId: ::LPCWSTR, + pbLabel: ::PUCHAR, + cbLabel: ::ULONG, +}} +pub const BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION: ::ULONG = 1; +pub const BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG: ::ULONG = 0x00000001; +pub const BCRYPT_AUTH_MODE_IN_PROGRESS_FLAG: ::ULONG = 0x00000002; +STRUCT!{struct BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO { + cbSize: ::ULONG, + dwInfoVersion: ::ULONG, + pbNonce: ::PUCHAR, + cbNonce: ::ULONG, + pbAuthData: ::PUCHAR, + cbAuthData: ::ULONG, + pbTag: ::PUCHAR, + cbTag: ::ULONG, + pbMacContext: ::PUCHAR, + cbMacContext: ::ULONG, + cbAAD: ::ULONG, + cbData: ::ULONGLONG, + dwFlags: ::ULONG, +}} +pub type PBCRYPT_AUTHENTICATED_CIPHER_MODE_INFO = *mut BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO; +pub const BCRYPT_PROV_DISPATCH: ::ULONG = 0x00000001; +pub const BCRYPT_BLOCK_PADDING: ::ULONG = 0x00000001; +pub const BCRYPT_PAD_NONE: ::ULONG = 0x00000001; +pub const BCRYPT_PAD_PKCS1: ::ULONG = 0x00000002; +pub const BCRYPT_PAD_OAEP: ::ULONG = 0x00000004; +pub const BCRYPT_PAD_PSS: ::ULONG = 0x00000008; +pub const BCRYPT_PAD_PKCS1_OPTIONAL_HASH_OID: ::ULONG = 0x00000010; +pub const BCRYPTBUFFER_VERSION: ::ULONG = 0; +STRUCT!{struct BCryptBuffer { + cbBuffer: ::ULONG, + BufferType: ::ULONG, + pvBuffer: ::PVOID, +}} +pub type PBCryptBuffer = *mut BCryptBuffer; +STRUCT!{struct BCryptBufferDesc { + ulVersion: ::ULONG, + cBuffers: ::ULONG, + pBuffers: PBCryptBuffer, +}} +pub type PBCryptBufferDesc = *mut BCryptBufferDesc; +//321 +pub type BCRYPT_HANDLE = ::PVOID; +pub type BCRYPT_ALG_HANDLE = ::PVOID; +pub type BCRYPT_KEY_HANDLE = ::PVOID; +pub type BCRYPT_HASH_HANDLE = ::PVOID; +pub type BCRYPT_SECRET_HANDLE = ::PVOID; +STRUCT!{struct BCRYPT_KEY_BLOB { + Magic: ::ULONG, +}} +pub const BCRYPT_RSAPUBLIC_MAGIC: ::ULONG = 0x31415352; +pub const BCRYPT_RSAPRIVATE_MAGIC: ::ULONG = 0x32415352; +STRUCT!{struct BCRYPT_RSAKEY_BLOB { + Magic: ::ULONG, + BitLength: ::ULONG, + cbPublicExp: ::ULONG, + cbModulus: ::ULONG, + cbPrime1: ::ULONG, + cbPrime2: ::ULONG, +}} +pub const BCRYPT_RSAFULLPRIVATE_MAGIC: ::ULONG = 0x33415352; +pub const BCRYPT_ECDH_PUBLIC_P256_MAGIC: ::ULONG = 0x314B4345; +pub const BCRYPT_ECDH_PRIVATE_P256_MAGIC: ::ULONG = 0x324B4345; +pub const BCRYPT_ECDH_PUBLIC_P384_MAGIC: ::ULONG = 0x334B4345; +pub const BCRYPT_ECDH_PRIVATE_P384_MAGIC: ::ULONG = 0x344B4345; +pub const BCRYPT_ECDH_PUBLIC_P521_MAGIC: ::ULONG = 0x354B4345; +pub const BCRYPT_ECDH_PRIVATE_P521_MAGIC: ::ULONG = 0x364B4345; +pub const BCRYPT_ECDSA_PUBLIC_P256_MAGIC: ::ULONG = 0x31534345; +pub const BCRYPT_ECDSA_PRIVATE_P256_MAGIC: ::ULONG = 0x32534345; +pub const BCRYPT_ECDSA_PUBLIC_P384_MAGIC: ::ULONG = 0x33534345; +pub const BCRYPT_ECDSA_PRIVATE_P384_MAGIC: ::ULONG = 0x34534345; +pub const BCRYPT_ECDSA_PUBLIC_P521_MAGIC: ::ULONG = 0x35534345; +pub const BCRYPT_ECDSA_PRIVATE_P521_MAGIC: ::ULONG = 0x36534345; +STRUCT!{struct BCRYPT_ECCKEY_BLOB { + dwMagic: ::ULONG, + cbKey: ::ULONG, +}} +pub type PBCRYPT_ECCKEY_BLOB = *mut BCRYPT_ECCKEY_BLOB; +pub const BCRYPT_DH_PUBLIC_MAGIC: ::ULONG = 0x42504844; +pub const BCRYPT_DH_PRIVATE_MAGIC: ::ULONG = 0x56504844; +STRUCT!{struct BCRYPT_DH_KEY_BLOB { + dwMagic: ::ULONG, + cbKey: ::ULONG, +}} +pub type PBCRYPT_DH_KEY_BLOB = *mut BCRYPT_DH_KEY_BLOB; +pub const BCRYPT_DH_PARAMETERS_MAGIC: ::ULONG = 0x4d504844; +STRUCT!{struct BCRYPT_DH_PARAMETER_HEADER { + cbLength: ::ULONG, + dwMagic: ::ULONG, + cbKeyLength: ::ULONG, +}} +pub const BCRYPT_DSA_PUBLIC_MAGIC: ::ULONG = 0x42505344; +pub const BCRYPT_DSA_PRIVATE_MAGIC: ::ULONG = 0x56505344; +pub const BCRYPT_DSA_PUBLIC_MAGIC_V2: ::ULONG = 0x32425044; +pub const BCRYPT_DSA_PRIVATE_MAGIC_V2: ::ULONG = 0x32565044; +STRUCT!{struct BCRYPT_DSA_KEY_BLOB { + dwMagic: ::ULONG, + cbKey: ::ULONG, + Count: [::UCHAR; 4], + Seed: [::UCHAR; 20], + q: [::UCHAR; 20], +}} +pub type PBCRYPT_DSA_KEY_BLOB = *mut BCRYPT_DSA_KEY_BLOB; +ENUM!{enum HASHALGORITHM_ENUM { + DSA_HASH_ALGORITHM_SHA1, + DSA_HASH_ALGORITHM_SHA256, + DSA_HASH_ALGORITHM_SHA512, +}} +ENUM!{enum DSAFIPSVERSION_ENUM { + DSA_FIPS186_2, + DSA_FIPS186_3, +}} +STRUCT!{struct BCRYPT_DSA_KEY_BLOB_V2 { + dwMagic: ::ULONG, + cbKey: ::ULONG, + hashAlgorithm: HASHALGORITHM_ENUM, + standardVersion: DSAFIPSVERSION_ENUM, + cbSeedLength: ::ULONG, + cbGroupSize: ::ULONG, + Count: [::UCHAR; 4], +}} +pub type PBCRYPT_DSA_KEY_BLOB_V2 = *mut BCRYPT_DSA_KEY_BLOB_V2; +STRUCT!{struct BCRYPT_KEY_DATA_BLOB_HEADER { + dwMagic: ::ULONG, + dwVersion: ::ULONG, + cbKeyData: ::ULONG, +}} +pub type PBCRYPT_KEY_DATA_BLOB_HEADER = *mut BCRYPT_KEY_DATA_BLOB_HEADER; +pub const BCRYPT_KEY_DATA_BLOB_MAGIC: ::ULONG = 0x4d42444b; +pub const BCRYPT_KEY_DATA_BLOB_VERSION1: ::ULONG = 0x1; +pub const BCRYPT_DSA_PARAMETERS_MAGIC: ::ULONG = 0x4d505344; +pub const BCRYPT_DSA_PARAMETERS_MAGIC_V2: ::ULONG = 0x324d5044; +STRUCT!{struct BCRYPT_DSA_PARAMETER_HEADER { + cbLength: ::ULONG, + dwMagic: ::ULONG, + cbKeyLength: ::ULONG, + Count: [::UCHAR; 4], + Seed: [::UCHAR; 20], + q: [::UCHAR; 20], +}} +STRUCT!{struct BCRYPT_DSA_PARAMETER_HEADER_V2 { + cbLength: ::ULONG, + dwMagic: ::ULONG, + cbKeyLength: ::ULONG, + hashAlgorithm: HASHALGORITHM_ENUM, + standardVersion: DSAFIPSVERSION_ENUM, + cbSeedLength: ::ULONG, + cbGroupSize: ::ULONG, + Count: [::UCHAR; 4], +}} +ENUM!{enum BCRYPT_HASH_OPERATION_TYPE { + BCRYPT_HASH_OPERATION_HASH_DATA = 1, + BCRYPT_HASH_OPERATION_FINISH_HASH = 2, +}} +STRUCT!{struct BCRYPT_MULTI_HASH_OPERATION { + iHash: ::ULONG, + hashOperation: BCRYPT_HASH_OPERATION_TYPE, + pbBuffer: ::PUCHAR, + cbBuffer: ::ULONG, +}} +ENUM!{enum BCRYPT_MULTI_OPERATION_TYPE { + BCRYPT_OPERATION_TYPE_HASH = 1, +}} +STRUCT!{struct BCRYPT_MULTI_OBJECT_LENGTH_STRUCT { + cbPerObject: ::ULONG, + cbPerElement: ::ULONG, +}} +pub const BCRYPT_CIPHER_INTERFACE: ::ULONG = 0x00000001; +pub const BCRYPT_HASH_INTERFACE: ::ULONG = 0x00000002; +pub const BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE: ::ULONG = 0x00000003; +pub const BCRYPT_SECRET_AGREEMENT_INTERFACE: ::ULONG = 0x00000004; +pub const BCRYPT_SIGNATURE_INTERFACE: ::ULONG = 0x00000005; +pub const BCRYPT_RNG_INTERFACE: ::ULONG = 0x00000006; +pub const BCRYPT_KEY_DERIVATION_INTERFACE: ::ULONG = 0x00000007; +pub const BCRYPT_ALG_HANDLE_HMAC_FLAG: ::ULONG = 0x00000008; +pub const BCRYPT_CAPI_AES_FLAG: ::ULONG = 0x00000010; +pub const BCRYPT_HASH_REUSABLE_FLAG: ::ULONG = 0x00000020; +pub const BCRYPT_BUFFERS_LOCKED_FLAG: ::ULONG = 0x00000040; +pub const BCRYPT_EXTENDED_KEYSIZE: ::ULONG = 0x00000080; +pub const BCRYPT_CIPHER_OPERATION: ::ULONG = 0x00000001; +pub const BCRYPT_HASH_OPERATION: ::ULONG = 0x00000002; +pub const BCRYPT_ASYMMETRIC_ENCRYPTION_OPERATION: ::ULONG = 0x00000004; +pub const BCRYPT_SECRET_AGREEMENT_OPERATION: ::ULONG = 0x00000008; +pub const BCRYPT_SIGNATURE_OPERATION: ::ULONG = 0x00000010; +pub const BCRYPT_RNG_OPERATION: ::ULONG = 0x00000020; +pub const BCRYPT_KEY_DERIVATION_OPERATION: ::ULONG = 0x00000040; +STRUCT!{struct BCRYPT_ALGORITHM_IDENTIFIER { + pszName: ::LPWSTR, + dwClass: ::ULONG, + dwFlags: ::ULONG, +}} +STRUCT!{struct BCRYPT_PROVIDER_NAME { + pszProviderName: ::LPWSTR, +}} +pub const BCRYPT_PUBLIC_KEY_FLAG: ::ULONG = 0x00000001; +pub const BCRYPT_PRIVATE_KEY_FLAG: ::ULONG = 0x00000002; +pub const BCRYPT_RNG_USE_ENTROPY_IN_BUFFER: ::ULONG = 0x00000001; +pub const BCRYPT_USE_SYSTEM_PREFERRED_RNG: ::ULONG = 0x00000002; +STRUCT!{struct BCRYPT_INTERFACE_VERSION { + MajorVersion: ::USHORT, + MinorVersion: ::USHORT, +}} +pub type PBCRYPT_INTERFACE_VERSION = *mut BCRYPT_INTERFACE_VERSION; +pub const BCRYPT_CIPHER_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_HASH_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_HASH_INTERFACE_MAJORVERSION_2: ::USHORT = 2; +pub const BCRYPT_HASH_INTERFACE_VERSION_2: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(BCRYPT_HASH_INTERFACE_MAJORVERSION_2, 0); +pub const BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_SECRET_AGREEMENT_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_SIGNATURE_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_RNG_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const CRYPT_MIN_DEPENDENCIES: ::ULONG = 0x00000001; +pub const CRYPT_PROCESS_ISOLATE: ::ULONG = 0x00010000; +pub const CRYPT_UM: ::ULONG = 0x00000001; +pub const CRYPT_KM: ::ULONG = 0x00000002; +pub const CRYPT_MM: ::ULONG = 0x00000003; +pub const CRYPT_ANY: ::ULONG = 0x00000004; +pub const CRYPT_OVERWRITE: ::ULONG = 0x00000001; +pub const CRYPT_LOCAL: ::ULONG = 0x00000001; +pub const CRYPT_DOMAIN: ::ULONG = 0x00000002; +pub const CRYPT_EXCLUSIVE: ::ULONG = 0x00000001; +pub const CRYPT_OVERRIDE: ::ULONG = 0x00010000; +pub const CRYPT_ALL_FUNCTIONS: ::ULONG = 0x00000001; +pub const CRYPT_ALL_PROVIDERS: ::ULONG = 0x00000002; +pub const CRYPT_PRIORITY_TOP: ::ULONG = 0x00000000; +pub const CRYPT_PRIORITY_BOTTOM: ::ULONG = 0xFFFFFFFF; +STRUCT!{struct CRYPT_INTERFACE_REG { + dwInterface: ::ULONG, + dwFlags: ::ULONG, + cFunctions: ::ULONG, + rgpszFunctions: *mut ::PWSTR, +}} +pub type PCRYPT_INTERFACE_REG = *mut CRYPT_INTERFACE_REG; +STRUCT!{struct CRYPT_IMAGE_REG { + pszImage: ::PWSTR, + cInterfaces: ::ULONG, + rgpInterfaces: *mut PCRYPT_INTERFACE_REG, +}} +pub type PCRYPT_IMAGE_REG = *mut CRYPT_IMAGE_REG; +STRUCT!{struct CRYPT_PROVIDER_REG { + cAliases: ::ULONG, + rgpszAliases: *mut ::PWSTR, + pUM: PCRYPT_IMAGE_REG, + pKM: PCRYPT_IMAGE_REG, +}} +pub type PCRYPT_PROVIDER_REG = *mut CRYPT_PROVIDER_REG; +STRUCT!{struct CRYPT_PROVIDERS { + cProviders: ::ULONG, + rgpszProviders: *mut ::PWSTR, +}} +pub type PCRYPT_PROVIDERS = *mut CRYPT_PROVIDERS; +STRUCT!{struct CRYPT_CONTEXT_CONFIG { + dwFlags: ::ULONG, + dwReserved: ::ULONG, +}} +pub type PCRYPT_CONTEXT_CONFIG = *mut CRYPT_CONTEXT_CONFIG; +STRUCT!{struct CRYPT_CONTEXT_FUNCTION_CONFIG { + dwFlags: ::ULONG, + dwReserved: ::ULONG, +}} +pub type PCRYPT_CONTEXT_FUNCTION_CONFIG = *mut CRYPT_CONTEXT_FUNCTION_CONFIG; +STRUCT!{struct CRYPT_CONTEXTS { + cContexts: ::ULONG, + rgpszContexts: *mut ::PWSTR, +}} +pub type PCRYPT_CONTEXTS = *mut CRYPT_CONTEXTS; +STRUCT!{struct CRYPT_CONTEXT_FUNCTIONS { + cFunctions: ::ULONG, + rgpszFunctions: *mut ::PWSTR, +}} +pub type PCRYPT_CONTEXT_FUNCTIONS = *mut CRYPT_CONTEXT_FUNCTIONS; +STRUCT!{struct CRYPT_CONTEXT_FUNCTION_PROVIDERS { + cProviders: ::ULONG, + rgpszProviders: *mut ::PWSTR, +}} +pub type PCRYPT_CONTEXT_FUNCTION_PROVIDERS = *mut CRYPT_CONTEXT_FUNCTION_PROVIDERS; +STRUCT!{struct CRYPT_PROPERTY_REF { + pszProperty: ::PWSTR, + cbValue: ::ULONG, + pbValue: ::PUCHAR, +}} +pub type PCRYPT_PROPERTY_REF = *mut CRYPT_PROPERTY_REF; +STRUCT!{struct CRYPT_IMAGE_REF { + pszImage: ::PWSTR, + dwFlags: ::ULONG, +}} +pub type PCRYPT_IMAGE_REF = *mut CRYPT_IMAGE_REF; +STRUCT!{struct CRYPT_PROVIDER_REF { + dwInterface: ::ULONG, + pszFunction: ::PWSTR, + pszProvider: ::PWSTR, + cProperties: ::ULONG, + rgpProperties: *mut PCRYPT_PROPERTY_REF, + pUM: PCRYPT_IMAGE_REF, + pKM: PCRYPT_IMAGE_REF, +}} +pub type PCRYPT_PROVIDER_REF = *mut CRYPT_PROVIDER_REF; +STRUCT!{struct CRYPT_PROVIDER_REFS { + cProviders: ::ULONG, + rgpProviders: *mut PCRYPT_PROVIDER_REF, +}} +pub type PCRYPT_PROVIDER_REFS = *mut CRYPT_PROVIDER_REFS; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/cfg.rs b/bash-5.1/vendor/winapi-0.2.8/src/cfg.rs new file mode 100644 index 0000000..0720d32 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/cfg.rs @@ -0,0 +1,134 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! common Configuration Manager definitions for both user mode and kernel mode code +ENUM!{enum PNP_VETO_TYPE { + PNP_VetoTypeUnknown, + PNP_VetoLegacyDevice, + PNP_VetoPendingClose, + PNP_VetoWindowsApp, + PNP_VetoWindowsService, + PNP_VetoOutstandingOpen, + PNP_VetoDevice, + PNP_VetoDriver, + PNP_VetoIllegalDeviceRequest, + PNP_VetoInsufficientPower, + PNP_VetoNonDisableable, + PNP_VetoLegacyDriver, + PNP_VetoInsufficientRights, +}} +pub type PPNP_VETO_TYPE = *mut PNP_VETO_TYPE; +pub const CM_PROB_NOT_CONFIGURED: ::CONFIGRET = 0x00000001; +pub const CM_PROB_DEVLOADER_FAILED: ::CONFIGRET = 0x00000002; +pub const CM_PROB_OUT_OF_MEMORY: ::CONFIGRET = 0x00000003; +pub const CM_PROB_ENTRY_IS_WRONG_TYPE: ::CONFIGRET = 0x00000004; +pub const CM_PROB_LACKED_ARBITRATOR: ::CONFIGRET = 0x00000005; +pub const CM_PROB_BOOT_CONFIG_CONFLICT: ::CONFIGRET = 0x00000006; +pub const CM_PROB_FAILED_FILTER: ::CONFIGRET = 0x00000007; +pub const CM_PROB_DEVLOADER_NOT_FOUND: ::CONFIGRET = 0x00000008; +pub const CM_PROB_INVALID_DATA: ::CONFIGRET = 0x00000009; +pub const CM_PROB_FAILED_START: ::CONFIGRET = 0x0000000A; +pub const CM_PROB_LIAR: ::CONFIGRET = 0x0000000B; +pub const CM_PROB_NORMAL_CONFLICT: ::CONFIGRET = 0x0000000C; +pub const CM_PROB_NOT_VERIFIED: ::CONFIGRET = 0x0000000D; +pub const CM_PROB_NEED_RESTART: ::CONFIGRET = 0x0000000E; +pub const CM_PROB_REENUMERATION: ::CONFIGRET = 0x0000000F; +pub const CM_PROB_PARTIAL_LOG_CONF: ::CONFIGRET = 0x00000010; +pub const CM_PROB_UNKNOWN_RESOURCE: ::CONFIGRET = 0x00000011; +pub const CM_PROB_REINSTALL: ::CONFIGRET = 0x00000012; +pub const CM_PROB_REGISTRY: ::CONFIGRET = 0x00000013; +pub const CM_PROB_VXDLDR: ::CONFIGRET = 0x00000014; +pub const CM_PROB_WILL_BE_REMOVED: ::CONFIGRET = 0x00000015; +pub const CM_PROB_DISABLED: ::CONFIGRET = 0x00000016; +pub const CM_PROB_DEVLOADER_NOT_READY: ::CONFIGRET = 0x00000017; +pub const CM_PROB_DEVICE_NOT_THERE: ::CONFIGRET = 0x00000018; +pub const CM_PROB_MOVED: ::CONFIGRET = 0x00000019; +pub const CM_PROB_TOO_EARLY: ::CONFIGRET = 0x0000001A; +pub const CM_PROB_NO_VALID_LOG_CONF: ::CONFIGRET = 0x0000001B; +pub const CM_PROB_FAILED_INSTALL: ::CONFIGRET = 0x0000001C; +pub const CM_PROB_HARDWARE_DISABLED: ::CONFIGRET = 0x0000001D; +pub const CM_PROB_CANT_SHARE_IRQ: ::CONFIGRET = 0x0000001E; +pub const CM_PROB_FAILED_ADD: ::CONFIGRET = 0x0000001F; +pub const CM_PROB_DISABLED_SERVICE: ::CONFIGRET = 0x00000020; +pub const CM_PROB_TRANSLATION_FAILED: ::CONFIGRET = 0x00000021; +pub const CM_PROB_NO_SOFTCONFIG: ::CONFIGRET = 0x00000022; +pub const CM_PROB_BIOS_TABLE: ::CONFIGRET = 0x00000023; +pub const CM_PROB_IRQ_TRANSLATION_FAILED: ::CONFIGRET = 0x00000024; +pub const CM_PROB_FAILED_DRIVER_ENTRY: ::CONFIGRET = 0x00000025; +pub const CM_PROB_DRIVER_FAILED_PRIOR_UNLOAD: ::CONFIGRET = 0x00000026; +pub const CM_PROB_DRIVER_FAILED_LOAD: ::CONFIGRET = 0x00000027; +pub const CM_PROB_DRIVER_SERVICE_KEY_INVALID: ::CONFIGRET = 0x00000028; +pub const CM_PROB_LEGACY_SERVICE_NO_DEVICES: ::CONFIGRET = 0x00000029; +pub const CM_PROB_DUPLICATE_DEVICE: ::CONFIGRET = 0x0000002A; +pub const CM_PROB_FAILED_POST_START: ::CONFIGRET = 0x0000002B; +pub const CM_PROB_HALTED: ::CONFIGRET = 0x0000002C; +pub const CM_PROB_PHANTOM: ::CONFIGRET = 0x0000002D; +pub const CM_PROB_SYSTEM_SHUTDOWN: ::CONFIGRET = 0x0000002E; +pub const CM_PROB_HELD_FOR_EJECT: ::CONFIGRET = 0x0000002F; +pub const CM_PROB_DRIVER_BLOCKED: ::CONFIGRET = 0x00000030; +pub const CM_PROB_REGISTRY_TOO_LARGE: ::CONFIGRET = 0x00000031; +pub const CM_PROB_SETPROPERTIES_FAILED: ::CONFIGRET = 0x00000032; +pub const CM_PROB_WAITING_ON_DEPENDENCY: ::CONFIGRET = 0x00000033; +pub const CM_PROB_UNSIGNED_DRIVER: ::CONFIGRET = 0x00000034; +pub const CM_PROB_USED_BY_DEBUGGER: ::CONFIGRET = 0x00000035; +pub const NUM_CM_PROB_V1: ::CONFIGRET = 0x00000025; +pub const NUM_CM_PROB_V2: ::CONFIGRET = 0x00000032; +pub const NUM_CM_PROB_V3: ::CONFIGRET = 0x00000033; +pub const NUM_CM_PROB_V4: ::CONFIGRET = 0x00000034; +pub const NUM_CM_PROB_V5: ::CONFIGRET = 0x00000035; +pub const NUM_CM_PROB_V6: ::CONFIGRET = 0x00000036; +pub const DN_ROOT_ENUMERATED: ::CONFIGRET = 0x00000001; +pub const DN_DRIVER_LOADED: ::CONFIGRET = 0x00000002; +pub const DN_ENUM_LOADED: ::CONFIGRET = 0x00000004; +pub const DN_STARTED: ::CONFIGRET = 0x00000008; +pub const DN_MANUAL: ::CONFIGRET = 0x00000010; +pub const DN_NEED_TO_ENUM: ::CONFIGRET = 0x00000020; +pub const DN_NOT_FIRST_TIME: ::CONFIGRET = 0x00000040; +pub const DN_HARDWARE_ENUM: ::CONFIGRET = 0x00000080; +pub const DN_LIAR: ::CONFIGRET = 0x00000100; +pub const DN_HAS_MARK: ::CONFIGRET = 0x00000200; +pub const DN_HAS_PROBLEM: ::CONFIGRET = 0x00000400; +pub const DN_FILTERED: ::CONFIGRET = 0x00000800; +pub const DN_MOVED: ::CONFIGRET = 0x00001000; +pub const DN_DISABLEABLE: ::CONFIGRET = 0x00002000; +pub const DN_REMOVABLE: ::CONFIGRET = 0x00004000; +pub const DN_PRIVATE_PROBLEM: ::CONFIGRET = 0x00008000; +pub const DN_MF_PARENT: ::CONFIGRET = 0x00010000; +pub const DN_MF_CHILD: ::CONFIGRET = 0x00020000; +pub const DN_WILL_BE_REMOVED: ::CONFIGRET = 0x00040000; +pub const DN_NOT_FIRST_TIMEE: ::CONFIGRET = 0x00080000; +pub const DN_STOP_FREE_RES: ::CONFIGRET = 0x00100000; +pub const DN_REBAL_CANDIDATE: ::CONFIGRET = 0x00200000; +pub const DN_BAD_PARTIAL: ::CONFIGRET = 0x00400000; +pub const DN_NT_ENUMERATOR: ::CONFIGRET = 0x00800000; +pub const DN_NT_DRIVER: ::CONFIGRET = 0x01000000; +pub const DN_NEEDS_LOCKING: ::CONFIGRET = 0x02000000; +pub const DN_ARM_WAKEUP: ::CONFIGRET = 0x04000000; +pub const DN_APM_ENUMERATOR: ::CONFIGRET = 0x08000000; +pub const DN_APM_DRIVER: ::CONFIGRET = 0x10000000; +pub const DN_SILENT_INSTALL: ::CONFIGRET = 0x20000000; +pub const DN_NO_SHOW_IN_DM: ::CONFIGRET = 0x40000000; +pub const DN_BOOT_LOG_PROB: ::CONFIGRET = 0x80000000; +pub const DN_NEED_RESTART: ::CONFIGRET = DN_LIAR; +pub const DN_DRIVER_BLOCKED: ::CONFIGRET = DN_NOT_FIRST_TIME; +pub const DN_LEGACY_DRIVER: ::CONFIGRET = DN_MOVED; +pub const DN_CHILD_WITH_INVALID_ID: ::CONFIGRET = DN_HAS_MARK; +pub const DN_DEVICE_DISCONNECTED: ::CONFIGRET = DN_NEEDS_LOCKING; +pub const DN_CHANGEABLE_FLAGS: ::CONFIGRET = DN_NOT_FIRST_TIME + DN_HARDWARE_ENUM + DN_HAS_MARK + + DN_DISABLEABLE + DN_REMOVABLE + DN_MF_CHILD + DN_MF_PARENT + DN_NOT_FIRST_TIMEE + + DN_STOP_FREE_RES + DN_REBAL_CANDIDATE + DN_NT_ENUMERATOR + DN_NT_DRIVER + DN_SILENT_INSTALL + + DN_NO_SHOW_IN_DM; +pub const LCPRI_FORCECONFIG: ::PRIORITY = 0x00000000; +pub const LCPRI_BOOTCONFIG: ::PRIORITY = 0x00000001; +pub const LCPRI_DESIRED: ::PRIORITY = 0x00002000; +pub const LCPRI_NORMAL: ::PRIORITY = 0x00003000; +pub const LCPRI_LASTBESTCONFIG: ::PRIORITY = 0x00003FFF; +pub const LCPRI_SUBOPTIMAL: ::PRIORITY = 0x00005000; +pub const LCPRI_LASTSOFTCONFIG: ::PRIORITY = 0x00007FFF; +pub const LCPRI_RESTART: ::PRIORITY = 0x00008000; +pub const LCPRI_REBOOT: ::PRIORITY = 0x00009000; +pub const LCPRI_POWEROFF: ::PRIORITY = 0x0000A000; +pub const LCPRI_HARDRECONFIG: ::PRIORITY = 0x0000C000; +pub const LCPRI_HARDWIRED: ::PRIORITY = 0x0000E000; +pub const LCPRI_IMPOSSIBLE: ::PRIORITY = 0x0000F000; +pub const LCPRI_DISABLED: ::PRIORITY = 0x0000FFFF; +pub const MAX_LCPRI: ::PRIORITY = 0x0000FFFF; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/cfgmgr32.rs b/bash-5.1/vendor/winapi-0.2.8/src/cfgmgr32.rs new file mode 100644 index 0000000..0305f1b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/cfgmgr32.rs @@ -0,0 +1,758 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! user APIs for the Configuration Manager +pub type PCVOID = *const ::VOID; +pub const MAX_DEVICE_ID_LEN: usize = 200; +pub const MAX_DEVNODE_ID_LEN: usize = MAX_DEVICE_ID_LEN; +pub const MAX_GUID_STRING_LEN: usize = 39; +pub const MAX_CLASS_NAME_LEN: usize = 32; +pub const MAX_PROFILE_LEN: usize = 80; +pub const MAX_CONFIG_VALUE: ::DWORD = 9999; +pub const MAX_INSTANCE_VALUE: ::DWORD = 9999; +pub const MAX_MEM_REGISTERS: ::DWORD = 9; +pub const MAX_IO_PORTS: ::DWORD = 20; +pub const MAX_IRQS: ::DWORD = 7; +pub const MAX_DMA_CHANNELS: ::DWORD = 7; +pub const DWORD_MAX: ::DWORD = 0xffffffff; +pub const DWORDLONG_MAX: ::DWORDLONG = 0xffffffffffffffff; +pub const CONFIGMG_VERSION: ::DWORD = 0x0400; +pub type RETURN_TYPE = ::DWORD; +pub type CONFIGRET = RETURN_TYPE; +pub type DEVNODE = ::DWORD; +pub type DEVINST = ::DWORD; +pub type PDEVNODE = *mut DEVNODE; +pub type PDEVINST = *mut DEVNODE; +pub type DEVNODEID_A = *mut ::CHAR; +pub type DEVINSTID_A = *mut ::CHAR; +pub type DEVNODEID_W = *mut ::WCHAR; +pub type DEVINSTID_W = *mut ::WCHAR; +pub type LOG_CONF = ::DWORD_PTR; +pub type PLOG_CONF = *mut LOG_CONF; +pub type RES_DES = ::DWORD_PTR; +pub type PRES_DES = *mut RES_DES; +pub type RESOURCEID = ::ULONG; +pub type PRESOURCEID = *mut RESOURCEID; +pub type PRIORITY = ::ULONG; +pub type PPRIORITY = *mut PRIORITY; +pub type RANGE_LIST = ::DWORD_PTR; +pub type PRANGE_LIST = *mut RANGE_LIST; +pub type RANGE_ELEMENT = ::DWORD_PTR; +pub type PRANGE_ELEMENT = *mut RANGE_ELEMENT; +pub type HMACHINE = ::HANDLE; +pub type PHMACHINE = *mut HMACHINE; +pub type CONFLICT_LIST = ::ULONG_PTR; +pub type PCONFLICT_LIST = *mut CONFLICT_LIST; +STRUCT!{nodebug struct CONFLICT_DETAILS_A { + CD_ulSize: ::ULONG, + CD_ulMask: ::ULONG, + CD_dnDevInst: DEVINST, + CD_rdResDes: RES_DES, + CD_ulFlags: ::ULONG, + CD_szDescription: [::CHAR; ::MAX_PATH], +}} +pub type PCONFLICT_DETAILS_A = *mut CONFLICT_DETAILS_A; +STRUCT!{nodebug struct CONFLICT_DETAILS_W { + CD_ulSize: ::ULONG, + CD_ulMask: ::ULONG, + CD_dnDevInst: DEVINST, + CD_rdResDes: RES_DES, + CD_ulFlags: ::ULONG, + CD_szDescription: [::WCHAR; ::MAX_PATH], +}} +pub type PCONFLICT_DETAILS_W = *mut CONFLICT_DETAILS_W; +pub const CM_CDMASK_DEVINST: ::ULONG = 0x00000001; +pub const CM_CDMASK_RESDES: ::ULONG = 0x00000002; +pub const CM_CDMASK_FLAGS: ::ULONG = 0x00000004; +pub const CM_CDMASK_DESCRIPTION: ::ULONG = 0x00000008; +pub const CM_CDMASK_VALID: ::ULONG = 0x0000000F; +pub const CM_CDFLAGS_DRIVER: ::ULONG = 0x00000001; +pub const CM_CDFLAGS_ROOT_OWNED: ::ULONG = 0x00000002; +pub const CM_CDFLAGS_RESERVED: ::ULONG = 0x00000004; +pub type REGDISPOSITION = ::ULONG; +pub const mMD_MemoryType: ::DWORD = 0x1; +pub const fMD_MemoryType: ::DWORD = mMD_MemoryType; +pub const fMD_ROM: ::DWORD = 0x0; +pub const fMD_RAM: ::DWORD = 0x1; +pub const mMD_32_24: ::DWORD = 0x2; +pub const fMD_32_24: ::DWORD = mMD_32_24; +pub const fMD_24: ::DWORD = 0x0; +pub const fMD_32: ::DWORD = 0x2; +pub const mMD_Prefetchable: ::DWORD = 0x4; +pub const fMD_Prefetchable: ::DWORD = mMD_Prefetchable; +pub const fMD_Pref: ::DWORD = mMD_Prefetchable; +pub const fMD_PrefetchDisallowed: ::DWORD = 0x0; +pub const fMD_PrefetchAllowed: ::DWORD = 0x4; +pub const mMD_Readable: ::DWORD = 0x8; +pub const fMD_Readable: ::DWORD = mMD_Readable; +pub const fMD_ReadAllowed: ::DWORD = 0x0; +pub const fMD_ReadDisallowed: ::DWORD = 0x8; +pub const mMD_CombinedWrite: ::DWORD = 0x10; +pub const fMD_CombinedWrite: ::DWORD = mMD_CombinedWrite; +pub const fMD_CombinedWriteDisallowed: ::DWORD = 0x0; +pub const fMD_CombinedWriteAllowed: ::DWORD = 0x10; +pub const mMD_Cacheable: ::DWORD = 0x20; +pub const fMD_NonCacheable: ::DWORD = 0x0; +pub const fMD_Cacheable: ::DWORD = 0x20; +pub const fMD_WINDOW_DECODE: ::DWORD = 0x40; +pub const fMD_MEMORY_BAR: ::DWORD = 0x80; +STRUCT!{struct MEM_RANGE { + MR_Align: ::DWORDLONG, + MR_nBytes: ::ULONG, + MR_Min: ::DWORDLONG, + MR_Max: ::DWORDLONG, + MR_Flags: ::DWORD, + MR_Reserved: ::DWORD, +}} +pub type PMEM_RANGE = *mut MEM_RANGE; +STRUCT!{struct MEM_DES { + MD_Count: ::DWORD, + MD_Type: ::DWORD, + MD_Alloc_Base: ::DWORDLONG, + MD_Alloc_End: ::DWORDLONG, + MD_Flags: ::DWORD, + MD_Reserved: ::DWORD, +}} +pub type PMEM_DES = *mut MEM_DES; +STRUCT!{struct MEM_RESOURCE { + MEM_Header: MEM_DES, + MEM_Data: [MEM_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PMEM_RESOURCE = *mut MEM_RESOURCE; +STRUCT!{struct MEM_LARGE_RANGE { + MLR_Align: ::DWORDLONG, + MLR_nBytes: ::ULONGLONG, + MLR_Min: ::DWORDLONG, + MLR_Max: ::DWORDLONG, + MLR_Flags: ::DWORD, + MLR_Reserved: ::DWORD, +}} +pub type PMEM_LARGE_RANGE = *mut MEM_LARGE_RANGE; +STRUCT!{struct MEM_LARGE_DES { + MLD_Count: ::DWORD, + MLD_Type: ::DWORD, + MLD_Alloc_Base: ::DWORDLONG, + MLD_Alloc_End: ::DWORDLONG, + MLD_Flags: ::DWORD, + MLD_Reserved: ::DWORD, +}} +pub type PMEM_LARGE_DES = *mut MEM_LARGE_DES; +STRUCT!{struct MEM_LARGE_RESOURCE { + MEM_LARGE_Header: MEM_LARGE_DES, + MEM_LARGE_Data: [MEM_LARGE_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PMEM_LARGE_RESOURCE = *mut MEM_LARGE_RESOURCE; +pub const fIOD_PortType: ::DWORD = 0x1; +pub const fIOD_Memory: ::DWORD = 0x0; +pub const fIOD_IO: ::DWORD = 0x1; +pub const fIOD_DECODE: ::DWORD = 0x00fc; +pub const fIOD_10_BIT_DECODE: ::DWORD = 0x0004; +pub const fIOD_12_BIT_DECODE: ::DWORD = 0x0008; +pub const fIOD_16_BIT_DECODE: ::DWORD = 0x0010; +pub const fIOD_POSITIVE_DECODE: ::DWORD = 0x0020; +pub const fIOD_PASSIVE_DECODE: ::DWORD = 0x0040; +pub const fIOD_WINDOW_DECODE: ::DWORD = 0x0080; +pub const fIOD_PORT_BAR: ::DWORD = 0x0100; +pub const IO_ALIAS_10_BIT_DECODE: ::DWORDLONG = 0x00000004; +pub const IO_ALIAS_12_BIT_DECODE: ::DWORDLONG = 0x00000010; +pub const IO_ALIAS_16_BIT_DECODE: ::DWORDLONG = 0x00000000; +pub const IO_ALIAS_POSITIVE_DECODE: ::DWORDLONG = 0x000000FF; +STRUCT!{struct IO_RANGE { + IOR_Align: ::DWORDLONG, + IOR_nPorts: ::DWORD, + IOR_Min: ::DWORDLONG, + IOR_Max: ::DWORDLONG, + IOR_RangeFlags: ::DWORD, + IOR_Alias: ::DWORDLONG, +}} +pub type PIO_RANGE = *mut IO_RANGE; +STRUCT!{struct IO_DES { + IOD_Count: ::DWORD, + IOD_Type: ::DWORD, + IOD_Alloc_Base: ::DWORDLONG, + IOD_Alloc_End: ::DWORDLONG, + IOD_DesFlags: ::DWORD, +}} +pub type PIO_DES = *mut IO_DES; +STRUCT!{struct IO_RESOURCE { + IO_Header: IO_DES, + IO_Data: [IO_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PIO_RESOURCE = *mut IO_RESOURCE; +pub const mDD_Width: ::ULONG = 0x3; +pub const fDD_BYTE: ::ULONG = 0x0; +pub const fDD_WORD: ::ULONG = 0x1; +pub const fDD_DWORD: ::ULONG = 0x2; +pub const fDD_BYTE_AND_WORD: ::ULONG = 0x3; +pub const mDD_BusMaster: ::ULONG = 0x4; +pub const fDD_NoBusMaster: ::ULONG = 0x0; +pub const fDD_BusMaster: ::ULONG = 0x4; +pub const mDD_Type: ::ULONG = 0x18; +pub const fDD_TypeStandard: ::ULONG = 0x00; +pub const fDD_TypeA: ::ULONG = 0x08; +pub const fDD_TypeB: ::ULONG = 0x10; +pub const fDD_TypeF: ::ULONG = 0x18; +STRUCT!{struct DMA_RANGE { + DR_Min: ::ULONG, + DR_Max: ::ULONG, + DR_Flags: ::ULONG, +}} +pub type PDMA_RANGE = *mut DMA_RANGE; +STRUCT!{struct DMA_DES { + DD_Count: ::DWORD, + DD_Type: ::DWORD, + DD_Flags: ::DWORD, + DD_Alloc_Chan: ::ULONG, +}} +pub type PDMA_DES = *mut DMA_DES; +STRUCT!{struct DMA_RESOURCE { + DMA_Header: DMA_DES, + DMA_Data: [DMA_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PDMA_RESOURCE = *mut DMA_RESOURCE; +pub const mIRQD_Share: ::ULONG = 0x1; +pub const fIRQD_Exclusive: ::ULONG = 0x0; +pub const fIRQD_Share: ::ULONG = 0x1; +pub const fIRQD_Share_Bit: ::ULONG = 0; +pub const fIRQD_Level_Bit: ::ULONG = 1; +pub const mIRQD_Edge_Level: ::ULONG = 0x2; +pub const fIRQD_Level: ::ULONG = 0x0; +pub const fIRQD_Edge: ::ULONG = 0x2; +STRUCT!{struct IRQ_RANGE { + IRQR_Min: ::ULONG, + IRQR_Max: ::ULONG, + IRQR_Flags: ::ULONG, +}} +pub type PIRQ_RANGE = *mut IRQ_RANGE; +STRUCT!{struct IRQ_DES_32 { + IRQD_Count: ::DWORD, + IRQD_Type: ::DWORD, + IRQD_Flags: ::DWORD, + IRQD_Alloc_Num: ::ULONG, + IRQD_Affinity: ::ULONG32, +}} +pub type PIRQ_DES_32 = *mut IRQ_DES_32; +STRUCT!{struct IRQ_DES_64 { + IRQD_Count: ::DWORD, + IRQD_Type: ::DWORD, + IRQD_Flags: ::DWORD, + IRQD_Alloc_Num: ::ULONG, + IRQD_Affinity: ::ULONG64, +}} +pub type PIRQ_DES_64 = *mut IRQ_DES_64; +STRUCT!{struct IRQ_RESOURCE_32 { + IRQ_Header: IRQ_DES_32, + IRQ_Data: [IRQ_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PIRQ_RESOURCE_32 = *mut IRQ_RESOURCE_32; +STRUCT!{struct IRQ_RESOURCE_64 { + IRQ_Header: IRQ_DES_64, + IRQ_Data: [IRQ_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PIRQ_RESOURCE_64 = *mut IRQ_RESOURCE_64; +STRUCT!{struct DEVPRIVATE_RANGE { + PR_Data1: ::DWORD, + PR_Data2: ::DWORD, + PR_Data3: ::DWORD, +}} +pub type PDEVPRIVATE_RANGE = *mut DEVPRIVATE_RANGE; +STRUCT!{struct DEVPRIVATE_DES { + PD_Count: ::DWORD, + PD_Type: ::DWORD, + PD_Data1: ::DWORD, + PD_Data2: ::DWORD, + PD_Data3: ::DWORD, + PD_Flags: ::DWORD, +}} +pub type PDEVPRIVATE_DES = *mut DEVPRIVATE_DES; +STRUCT!{struct DEVPRIVATE_RESOURCE { + PRV_Header: DEVPRIVATE_DES, + PRV_Data: [DEVPRIVATE_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PDEVPRIVATE_RESOURCE = *mut DEVPRIVATE_RESOURCE; +STRUCT!{struct CS_DES { + CSD_SignatureLength: ::DWORD, + CSD_LegacyDataOffset: ::DWORD, + CSD_LegacyDataSize: ::DWORD, + CSD_Flags: ::DWORD, + CSD_ClassGuid: ::GUID, + CSD_Signature: [::BYTE; ::ANYSIZE_ARRAY], +}} +pub type PCS_DES = *mut CS_DES; +STRUCT!{struct CS_RESOURCE { + CS_Header: CS_DES, +}} +pub type PCS_RESOURCE = *mut CS_RESOURCE; +pub const mPCD_IO_8_16: ::DWORD = 0x1; +pub const fPCD_IO_8: ::DWORD = 0x0; +pub const fPCD_IO_16: ::DWORD = 0x1; +pub const mPCD_MEM_8_16: ::DWORD = 0x2; +pub const fPCD_MEM_8: ::DWORD = 0x0; +pub const fPCD_MEM_16: ::DWORD = 0x2; +pub const mPCD_MEM_A_C: ::DWORD = 0xC; +pub const fPCD_MEM1_A: ::DWORD = 0x4; +pub const fPCD_MEM2_A: ::DWORD = 0x8; +pub const fPCD_IO_ZW_8: ::DWORD = 0x10; +pub const fPCD_IO_SRC_16: ::DWORD = 0x20; +pub const fPCD_IO_WS_16: ::DWORD = 0x40; +pub const mPCD_MEM_WS: ::DWORD = 0x300; +pub const fPCD_MEM_WS_ONE: ::DWORD = 0x100; +pub const fPCD_MEM_WS_TWO: ::DWORD = 0x200; +pub const fPCD_MEM_WS_THREE: ::DWORD = 0x300; +pub const fPCD_MEM_A: ::DWORD = 0x4; +pub const fPCD_ATTRIBUTES_PER_WINDOW: ::DWORD = 0x8000; +pub const fPCD_IO1_16: ::DWORD = 0x00010000; +pub const fPCD_IO1_ZW_8: ::DWORD = 0x00020000; +pub const fPCD_IO1_SRC_16: ::DWORD = 0x00040000; +pub const fPCD_IO1_WS_16: ::DWORD = 0x00080000; +pub const fPCD_IO2_16: ::DWORD = 0x00100000; +pub const fPCD_IO2_ZW_8: ::DWORD = 0x00200000; +pub const fPCD_IO2_SRC_16: ::DWORD = 0x00400000; +pub const fPCD_IO2_WS_16: ::DWORD = 0x00800000; +pub const mPCD_MEM1_WS: ::DWORD = 0x03000000; +pub const fPCD_MEM1_WS_TWO: ::DWORD = 0x02000000; +pub const fPCD_MEM1_WS_THREE: ::DWORD = 0x03000000; +pub const fPCD_MEM1_16: ::DWORD = 0x04000000; +pub const mPCD_MEM2_WS: ::DWORD = 0x30000000; +pub const fPCD_MEM2_WS_ONE: ::DWORD = 0x10000000; +pub const fPCD_MEM2_WS_TWO: ::DWORD = 0x20000000; +pub const fPCD_MEM2_WS_THREE: ::DWORD = 0x30000000; +pub const fPCD_MEM2_16: ::DWORD = 0x40000000; +pub const PCD_MAX_MEMORY: usize = 2; +pub const PCD_MAX_IO: usize = 2; +STRUCT!{struct PCCARD_DES { + PCD_Count: ::DWORD, + PCD_Type: ::DWORD, + PCD_Flags: ::DWORD, + PCD_ConfigIndex: ::BYTE, + PCD_Reserved: [::BYTE; 3], + PCD_MemoryCardBase1: ::DWORD, + PCD_MemoryCardBase2: ::DWORD, + PCD_MemoryCardBase: [::DWORD; PCD_MAX_MEMORY], + PCD_MemoryFlags: [::WORD; PCD_MAX_MEMORY], + PCD_IoFlags: [::BYTE; PCD_MAX_IO], +}} +pub type PPCCARD_DES = *mut PCCARD_DES; +STRUCT!{struct PCCARD_RESOURCE { + PcCard_Header: PCCARD_DES, +}} +pub type PPCCARD_RESOURCE = *mut PCCARD_RESOURCE; +pub const mPMF_AUDIO_ENABLE: ::DWORD = 0x8; +pub const fPMF_AUDIO_ENABLE: ::DWORD = 0x8; +STRUCT!{struct MFCARD_DES { + PMF_Count: ::DWORD, + PMF_Type: ::DWORD, + PMF_Flags: ::DWORD, + PMF_ConfigOptions: ::BYTE, + PMF_IoResourceIndex: ::BYTE, + PMF_Reserved: [::BYTE; 2], + PMF_ConfigRegisterBase: ::DWORD, +}} +pub type PMFCARD_DES = *mut MFCARD_DES; +STRUCT!{struct MFCARD_RESOURCE { + MfCard_Header: MFCARD_DES, +}} +pub type PMFCARD_RESOURCE = *mut MFCARD_RESOURCE; +STRUCT!{struct BUSNUMBER_RANGE { + BUSR_Min: ::ULONG, + BUSR_Max: ::ULONG, + BUSR_nBusNumbers: ::ULONG, + BUSR_Flags: ::ULONG, +}} +pub type PBUSNUMBER_RANGE = *mut BUSNUMBER_RANGE; +STRUCT!{struct BUSNUMBER_DES { + BUSD_Count: ::DWORD, + BUSD_Type: ::DWORD, + BUSD_Flags: ::DWORD, + BUSD_Alloc_Base: ::ULONG, + BUSD_Alloc_End: ::ULONG, +}} +pub type PBUSNUMBER_DES = *mut BUSNUMBER_DES; +STRUCT!{struct BUSNUMBER_RESOURCE { + BusNumber_Header: BUSNUMBER_DES, + BusNumber_Data: [BUSNUMBER_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PBUSNUMBER_RESOURCE = *mut BUSNUMBER_RESOURCE; +STRUCT!{struct CONNECTION_DES { + COND_Type: ::DWORD, + COND_Flags: ::DWORD, + COND_Class: ::BYTE, + COND_ClassType: ::BYTE, + COND_Reserved1: ::BYTE, + COND_Reserved2: ::BYTE, + COND_Id: ::LARGE_INTEGER, +}} +pub type PCONNECTION_DES = *mut CONNECTION_DES; +STRUCT!{struct CONNECTION_RESOURCE { + Connection_Header: CONNECTION_DES, +}} +pub type PCONNECTION_RESOURCE = *mut CONNECTION_RESOURCE; +pub const CM_HWPI_NOT_DOCKABLE: ::DWORD = 0x00000000; +pub const CM_HWPI_UNDOCKED: ::DWORD = 0x00000001; +pub const CM_HWPI_DOCKED: ::DWORD = 0x00000002; +STRUCT!{nodebug struct HWPROFILEINFO_A { + HWPI_ulHWProfile: ::ULONG, + HWPI_szFriendlyName: [::CHAR; MAX_PROFILE_LEN], + HWPI_dwFlags: ::DWORD, +}} +pub type PHWPROFILEINFO_A = *mut HWPROFILEINFO_A; +STRUCT!{nodebug struct HWPROFILEINFO_W { + HWPI_ulHWProfile: ::ULONG, + HWPI_szFriendlyName: [::WCHAR; MAX_PROFILE_LEN], + HWPI_dwFlags: ::DWORD, +}} +pub type PHWPROFILEINFO_W = *mut HWPROFILEINFO_W; +pub const ResType_All: RESOURCEID = 0x00000000; +pub const ResType_None: RESOURCEID = 0x00000000; +pub const ResType_Mem: RESOURCEID = 0x00000001; +pub const ResType_IO: RESOURCEID = 0x00000002; +pub const ResType_DMA: RESOURCEID = 0x00000003; +pub const ResType_IRQ: RESOURCEID = 0x00000004; +pub const ResType_DoNotUse: RESOURCEID = 0x00000005; +pub const ResType_BusNumber: RESOURCEID = 0x00000006; +pub const ResType_MemLarge: RESOURCEID = 0x00000007; +pub const ResType_MAX: RESOURCEID = 0x00000007; +pub const ResType_Ignored_Bit: RESOURCEID = 0x00008000; +pub const ResType_ClassSpecific: RESOURCEID = 0x0000FFFF; +pub const ResType_Reserved: RESOURCEID = 0x00008000; +pub const ResType_DevicePrivate: RESOURCEID = 0x00008001; +pub const ResType_PcCardConfig: RESOURCEID = 0x00008002; +pub const ResType_MfCardConfig: RESOURCEID = 0x00008003; +pub const ResType_Connection: RESOURCEID = 0x00008004; +pub const CM_ADD_RANGE_ADDIFCONFLICT: ::ULONG = 0x00000000; +pub const CM_ADD_RANGE_DONOTADDIFCONFLICT: ::ULONG = 0x00000001; +pub const CM_ADD_RANGE_BITS: ::ULONG = 0x00000001; +pub const BASIC_LOG_CONF: ::ULONG = 0x00000000; +pub const FILTERED_LOG_CONF: ::ULONG = 0x00000001; +pub const ALLOC_LOG_CONF: ::ULONG = 0x00000002; +pub const BOOT_LOG_CONF: ::ULONG = 0x00000003; +pub const FORCED_LOG_CONF: ::ULONG = 0x00000004; +pub const OVERRIDE_LOG_CONF: ::ULONG = 0x00000005; +pub const NUM_LOG_CONF: ::ULONG = 0x00000006; +pub const LOG_CONF_BITS: ::ULONG = 0x00000007; +pub const PRIORITY_EQUAL_FIRST: ::ULONG = 0x00000008; +pub const PRIORITY_EQUAL_LAST: ::ULONG = 0x00000000; +pub const PRIORITY_BIT: ::ULONG = 0x00000008; +pub const RegDisposition_OpenAlways: REGDISPOSITION = 0x00000000; +pub const RegDisposition_OpenExisting: REGDISPOSITION = 0x00000001; +pub const RegDisposition_Bits: REGDISPOSITION = 0x00000001; +pub const CM_ADD_ID_HARDWARE: ::ULONG = 0x00000000; +pub const CM_ADD_ID_COMPATIBLE: ::ULONG = 0x00000001; +pub const CM_ADD_ID_BITS: ::ULONG = 0x00000001; +pub const CM_CREATE_DEVNODE_NORMAL: ::ULONG = 0x00000000; +pub const CM_CREATE_DEVNODE_NO_WAIT_INSTALL: ::ULONG = 0x00000001; +pub const CM_CREATE_DEVNODE_PHANTOM: ::ULONG = 0x00000002; +pub const CM_CREATE_DEVNODE_GENERATE_ID: ::ULONG = 0x00000004; +pub const CM_CREATE_DEVNODE_DO_NOT_INSTALL: ::ULONG = 0x00000008; +pub const CM_CREATE_DEVNODE_BITS: ::ULONG = 0x0000000F; +pub const CM_CREATE_DEVINST_NORMAL: ::ULONG = CM_CREATE_DEVNODE_NORMAL; +pub const CM_CREATE_DEVINST_NO_WAIT_INSTALL: ::ULONG = CM_CREATE_DEVNODE_NO_WAIT_INSTALL; +pub const CM_CREATE_DEVINST_PHANTOM: ::ULONG = CM_CREATE_DEVNODE_PHANTOM; +pub const CM_CREATE_DEVINST_GENERATE_ID: ::ULONG = CM_CREATE_DEVNODE_GENERATE_ID; +pub const CM_CREATE_DEVINST_DO_NOT_INSTALL: ::ULONG = CM_CREATE_DEVNODE_DO_NOT_INSTALL; +pub const CM_CREATE_DEVINST_BITS: ::ULONG = CM_CREATE_DEVNODE_BITS; +pub const CM_DELETE_CLASS_ONLY: ::ULONG = 0x00000000; +pub const CM_DELETE_CLASS_SUBKEYS: ::ULONG = 0x00000001; +pub const CM_DELETE_CLASS_INTERFACE: ::ULONG = 0x00000002; +pub const CM_DELETE_CLASS_BITS: ::ULONG = 0x00000003; +pub const CM_ENUMERATE_CLASSES_INSTALLER: ::ULONG = 0x00000000; +pub const CM_ENUMERATE_CLASSES_INTERFACE: ::ULONG = 0x00000001; +pub const CM_ENUMERATE_CLASSES_BITS: ::ULONG = 0x00000001; +pub const CM_DETECT_NEW_PROFILE: ::ULONG = 0x00000001; +pub const CM_DETECT_CRASHED: ::ULONG = 0x00000002; +pub const CM_DETECT_HWPROF_FIRST_BOOT: ::ULONG = 0x00000004; +pub const CM_DETECT_RUN: ::ULONG = 0x80000000; +pub const CM_DETECT_BITS: ::ULONG = 0x80000007; +pub const CM_DISABLE_POLITE: ::ULONG = 0x00000000; +pub const CM_DISABLE_ABSOLUTE: ::ULONG = 0x00000001; +pub const CM_DISABLE_HARDWARE: ::ULONG = 0x00000002; +pub const CM_DISABLE_UI_NOT_OK: ::ULONG = 0x00000004; +pub const CM_DISABLE_BITS: ::ULONG = 0x00000007; +pub const CM_GETIDLIST_FILTER_NONE: ::ULONG = 0x00000000; +pub const CM_GETIDLIST_FILTER_ENUMERATOR: ::ULONG = 0x00000001; +pub const CM_GETIDLIST_FILTER_SERVICE: ::ULONG = 0x00000002; +pub const CM_GETIDLIST_FILTER_EJECTRELATIONS: ::ULONG = 0x00000004; +pub const CM_GETIDLIST_FILTER_REMOVALRELATIONS: ::ULONG = 0x00000008; +pub const CM_GETIDLIST_FILTER_POWERRELATIONS: ::ULONG = 0x00000010; +pub const CM_GETIDLIST_FILTER_BUSRELATIONS: ::ULONG = 0x00000020; +pub const CM_GETIDLIST_DONOTGENERATE: ::ULONG = 0x10000040; +pub const CM_GETIDLIST_FILTER_TRANSPORTRELATIONS: ::ULONG = 0x00000080; +pub const CM_GETIDLIST_FILTER_PRESENT: ::ULONG = 0x00000100; +pub const CM_GETIDLIST_FILTER_CLASS: ::ULONG = 0x00000200; +pub const CM_GETIDLIST_FILTER_BITS: ::ULONG = 0x100003FF; +pub const CM_GET_DEVICE_INTERFACE_LIST_PRESENT: ::ULONG = 0x00000000; +pub const CM_GET_DEVICE_INTERFACE_LIST_ALL_DEVICES: ::ULONG = 0x00000001; +pub const CM_GET_DEVICE_INTERFACE_LIST_BITS: ::ULONG = 0x00000001; +pub const CM_DRP_DEVICEDESC: ::ULONG = 0x00000001; +pub const CM_DRP_HARDWAREID: ::ULONG = 0x00000002; +pub const CM_DRP_COMPATIBLEIDS: ::ULONG = 0x00000003; +pub const CM_DRP_UNUSED0: ::ULONG = 0x00000004; +pub const CM_DRP_SERVICE: ::ULONG = 0x00000005; +pub const CM_DRP_UNUSED1: ::ULONG = 0x00000006; +pub const CM_DRP_UNUSED2: ::ULONG = 0x00000007; +pub const CM_DRP_CLASS: ::ULONG = 0x00000008; +pub const CM_DRP_CLASSGUID: ::ULONG = 0x00000009; +pub const CM_DRP_DRIVER: ::ULONG = 0x0000000A; +pub const CM_DRP_CONFIGFLAGS: ::ULONG = 0x0000000B; +pub const CM_DRP_MFG: ::ULONG = 0x0000000C; +pub const CM_DRP_FRIENDLYNAME: ::ULONG = 0x0000000D; +pub const CM_DRP_LOCATION_INFORMATION: ::ULONG = 0x0000000E; +pub const CM_DRP_PHYSICAL_DEVICE_OBJECT_NAME: ::ULONG = 0x0000000F; +pub const CM_DRP_CAPABILITIES: ::ULONG = 0x00000010; +pub const CM_DRP_UI_NUMBER: ::ULONG = 0x00000011; +pub const CM_DRP_UPPERFILTERS: ::ULONG = 0x00000012; +pub const CM_CRP_UPPERFILTERS: ::ULONG = CM_DRP_UPPERFILTERS; +pub const CM_DRP_LOWERFILTERS: ::ULONG = 0x00000013; +pub const CM_CRP_LOWERFILTERS: ::ULONG = CM_DRP_LOWERFILTERS; +pub const CM_DRP_BUSTYPEGUID: ::ULONG = 0x00000014; +pub const CM_DRP_LEGACYBUSTYPE: ::ULONG = 0x00000015; +pub const CM_DRP_BUSNUMBER: ::ULONG = 0x00000016; +pub const CM_DRP_ENUMERATOR_NAME: ::ULONG = 0x00000017; +pub const CM_DRP_SECURITY: ::ULONG = 0x00000018; +pub const CM_CRP_SECURITY: ::ULONG = CM_DRP_SECURITY; +pub const CM_DRP_SECURITY_SDS: ::ULONG = 0x00000019; +pub const CM_CRP_SECURITY_SDS: ::ULONG = CM_DRP_SECURITY_SDS; +pub const CM_DRP_DEVTYPE: ::ULONG = 0x0000001A; +pub const CM_CRP_DEVTYPE: ::ULONG = CM_DRP_DEVTYPE; +pub const CM_DRP_EXCLUSIVE: ::ULONG = 0x0000001B; +pub const CM_CRP_EXCLUSIVE: ::ULONG = CM_DRP_EXCLUSIVE; +pub const CM_DRP_CHARACTERISTICS: ::ULONG = 0x0000001C; +pub const CM_CRP_CHARACTERISTICS: ::ULONG = CM_DRP_CHARACTERISTICS; +pub const CM_DRP_ADDRESS: ::ULONG = 0x0000001D; +pub const CM_DRP_UI_NUMBER_DESC_FORMAT: ::ULONG = 0x0000001E; +pub const CM_DRP_DEVICE_POWER_DATA: ::ULONG = 0x0000001F; +pub const CM_DRP_REMOVAL_POLICY: ::ULONG = 0x00000020; +pub const CM_DRP_REMOVAL_POLICY_HW_DEFAULT: ::ULONG = 0x00000021; +pub const CM_DRP_REMOVAL_POLICY_OVERRIDE: ::ULONG = 0x00000022; +pub const CM_DRP_INSTALL_STATE: ::ULONG = 0x00000023; +pub const CM_DRP_LOCATION_PATHS: ::ULONG = 0x00000024; +pub const CM_DRP_BASE_CONTAINERID: ::ULONG = 0x00000025; +pub const CM_DRP_MIN: ::ULONG = 0x00000001; +pub const CM_CRP_MIN: ::ULONG = CM_DRP_MIN; +pub const CM_DRP_MAX: ::ULONG = 0x00000025; +pub const CM_CRP_MAX: ::ULONG = CM_DRP_MAX; +pub const CM_DEVCAP_LOCKSUPPORTED: ::ULONG = 0x00000001; +pub const CM_DEVCAP_EJECTSUPPORTED: ::ULONG = 0x00000002; +pub const CM_DEVCAP_REMOVABLE: ::ULONG = 0x00000004; +pub const CM_DEVCAP_DOCKDEVICE: ::ULONG = 0x00000008; +pub const CM_DEVCAP_UNIQUEID: ::ULONG = 0x00000010; +pub const CM_DEVCAP_SILENTINSTALL: ::ULONG = 0x00000020; +pub const CM_DEVCAP_RAWDEVICEOK: ::ULONG = 0x00000040; +pub const CM_DEVCAP_SURPRISEREMOVALOK: ::ULONG = 0x00000080; +pub const CM_DEVCAP_HARDWAREDISABLED: ::ULONG = 0x00000100; +pub const CM_DEVCAP_NONDYNAMIC: ::ULONG = 0x00000200; +pub const CM_REMOVAL_POLICY_EXPECT_NO_REMOVAL: ::ULONG = 1; +pub const CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL: ::ULONG = 2; +pub const CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL: ::ULONG = 3; +pub const CM_INSTALL_STATE_INSTALLED: ::ULONG = 0; +pub const CM_INSTALL_STATE_NEEDS_REINSTALL: ::ULONG = 1; +pub const CM_INSTALL_STATE_FAILED_INSTALL: ::ULONG = 2; +pub const CM_INSTALL_STATE_FINISH_INSTALL: ::ULONG = 3; +pub const CM_LOCATE_DEVNODE_NORMAL: ::ULONG = 0x00000000; +pub const CM_LOCATE_DEVNODE_PHANTOM: ::ULONG = 0x00000001; +pub const CM_LOCATE_DEVNODE_CANCELREMOVE: ::ULONG = 0x00000002; +pub const CM_LOCATE_DEVNODE_NOVALIDATION: ::ULONG = 0x00000004; +pub const CM_LOCATE_DEVNODE_BITS: ::ULONG = 0x00000007; +pub const CM_LOCATE_DEVINST_NORMAL: ::ULONG = CM_LOCATE_DEVNODE_NORMAL; +pub const CM_LOCATE_DEVINST_PHANTOM: ::ULONG = CM_LOCATE_DEVNODE_PHANTOM; +pub const CM_LOCATE_DEVINST_CANCELREMOVE: ::ULONG = CM_LOCATE_DEVNODE_CANCELREMOVE; +pub const CM_LOCATE_DEVINST_NOVALIDATION: ::ULONG = CM_LOCATE_DEVNODE_NOVALIDATION; +pub const CM_LOCATE_DEVINST_BITS: ::ULONG = CM_LOCATE_DEVNODE_BITS; +pub const CM_OPEN_CLASS_KEY_INSTALLER: ::ULONG = 0x00000000; +pub const CM_OPEN_CLASS_KEY_INTERFACE: ::ULONG = 0x00000001; +pub const CM_OPEN_CLASS_KEY_BITS: ::ULONG = 0x00000001; +pub const CM_REMOVE_UI_OK: ::ULONG = 0x00000000; +pub const CM_REMOVE_UI_NOT_OK: ::ULONG = 0x00000001; +pub const CM_REMOVE_NO_RESTART: ::ULONG = 0x00000002; +pub const CM_REMOVE_BITS: ::ULONG = 0x00000003; +pub const CM_QUERY_REMOVE_UI_OK: ::ULONG = CM_REMOVE_UI_OK; +pub const CM_QUERY_REMOVE_UI_NOT_OK: ::ULONG = CM_REMOVE_UI_NOT_OK; +pub const CM_QUERY_REMOVE_BITS: ::ULONG = CM_QUERY_REMOVE_UI_OK | CM_QUERY_REMOVE_UI_NOT_OK; +pub const CM_REENUMERATE_NORMAL: ::ULONG = 0x00000000; +pub const CM_REENUMERATE_SYNCHRONOUS: ::ULONG = 0x00000001; +pub const CM_REENUMERATE_RETRY_INSTALLATION: ::ULONG = 0x00000002; +pub const CM_REENUMERATE_ASYNCHRONOUS: ::ULONG = 0x00000004; +pub const CM_REENUMERATE_BITS: ::ULONG = 0x00000007; +pub const CM_REGISTER_DEVICE_DRIVER_STATIC: ::ULONG = 0x00000000; +pub const CM_REGISTER_DEVICE_DRIVER_DISABLEABLE: ::ULONG = 0x00000001; +pub const CM_REGISTER_DEVICE_DRIVER_REMOVABLE: ::ULONG = 0x00000002; +pub const CM_REGISTER_DEVICE_DRIVER_BITS: ::ULONG = 0x00000003; +pub const CM_REGISTRY_HARDWARE: ::ULONG = 0x00000000; +pub const CM_REGISTRY_SOFTWARE: ::ULONG = 0x00000001; +pub const CM_REGISTRY_USER: ::ULONG = 0x00000100; +pub const CM_REGISTRY_CONFIG: ::ULONG = 0x00000200; +pub const CM_REGISTRY_BITS: ::ULONG = 0x00000301; +pub const CM_SET_DEVNODE_PROBLEM_NORMAL: ::ULONG = 0x00000000; +pub const CM_SET_DEVNODE_PROBLEM_OVERRIDE: ::ULONG = 0x00000001; +pub const CM_SET_DEVNODE_PROBLEM_BITS: ::ULONG = 0x00000001; +pub const CM_SET_DEVINST_PROBLEM_NORMAL: ::ULONG = CM_SET_DEVNODE_PROBLEM_NORMAL; +pub const CM_SET_DEVINST_PROBLEM_OVERRIDE: ::ULONG = CM_SET_DEVNODE_PROBLEM_OVERRIDE; +pub const CM_SET_DEVINST_PROBLEM_BITS: ::ULONG = CM_SET_DEVNODE_PROBLEM_BITS; +pub const CM_SET_HW_PROF_FLAGS_UI_NOT_OK: ::ULONG = 0x00000001; +pub const CM_SET_HW_PROF_FLAGS_BITS: ::ULONG = 0x00000001; +pub const CM_SETUP_DEVNODE_READY: ::ULONG = 0x00000000; +pub const CM_SETUP_DEVINST_READY: ::ULONG = CM_SETUP_DEVNODE_READY; +pub const CM_SETUP_DOWNLOAD: ::ULONG = 0x00000001; +pub const CM_SETUP_WRITE_LOG_CONFS: ::ULONG = 0x00000002; +pub const CM_SETUP_PROP_CHANGE: ::ULONG = 0x00000003; +pub const CM_SETUP_DEVNODE_RESET: ::ULONG = 0x00000004; +pub const CM_SETUP_DEVINST_RESET: ::ULONG = CM_SETUP_DEVNODE_RESET; +pub const CM_SETUP_DEVNODE_CONFIG: ::ULONG = 0x00000005; +pub const CM_SETUP_DEVINST_CONFIG: ::ULONG = CM_SETUP_DEVNODE_CONFIG; +pub const CM_SETUP_DEVNODE_CONFIG_CLASS: ::ULONG = 0x00000006; +pub const CM_SETUP_DEVINST_CONFIG_CLASS: ::ULONG = CM_SETUP_DEVNODE_CONFIG_CLASS; +pub const CM_SETUP_DEVNODE_CONFIG_EXTENSIONS: ::ULONG = 0x00000007; +pub const CM_SETUP_DEVINST_CONFIG_EXTENSIONS: ::ULONG = CM_SETUP_DEVNODE_CONFIG_EXTENSIONS; +pub const CM_SETUP_BITS: ::ULONG = 0x00000007; +pub const CM_QUERY_ARBITRATOR_RAW: ::ULONG = 0x00000000; +pub const CM_QUERY_ARBITRATOR_TRANSLATED: ::ULONG = 0x00000001; +pub const CM_QUERY_ARBITRATOR_BITS: ::ULONG = 0x00000001; +pub const CM_CUSTOMDEVPROP_MERGE_MULTISZ: ::ULONG = 0x00000001; +pub const CM_CUSTOMDEVPROP_BITS: ::ULONG = 0x00000001; +pub const CM_NAME_ATTRIBUTE_NAME_RETRIEVED_FROM_DEVICE: ::ULONG = 0x1; +pub const CM_NAME_ATTRIBUTE_USER_ASSIGNED_NAME: ::ULONG = 0x2; +pub const CM_CLASS_PROPERTY_INSTALLER: ::ULONG = 0x00000000; +pub const CM_CLASS_PROPERTY_INTERFACE: ::ULONG = 0x00000001; +pub const CM_CLASS_PROPERTY_BITS: ::ULONG = 0x00000001; +DECLARE_HANDLE!(HCMNOTIFICATION, HCMNOTIFICATION__); +pub type PHCMNOTIFICATION = *mut HCMNOTIFICATION; +pub const CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES: ::ULONG = 0x00000001; +pub const CM_NOTIFY_FILTER_FLAG_ALL_DEVICE_INSTANCES: ::ULONG = 0x00000002; +pub const CM_NOTIFY_FILTER_VALID_FLAGS: ::ULONG = CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES + | CM_NOTIFY_FILTER_FLAG_ALL_DEVICE_INSTANCES; +ENUM!{enum CM_NOTIFY_FILTER_TYPE { + CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE = 0, + CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE, + CM_NOTIFY_FILTER_TYPE_DEVICEINSTANCE, + CM_NOTIFY_FILTER_TYPE_MAX, +}} +pub type PCM_NOTIFY_FILTER_TYPE = *mut CM_NOTIFY_FILTER_TYPE; +STRUCT!{struct CM_NOTIFY_FILTER_DeviceInterface { + ClassGuid: ::GUID, +}} +STRUCT!{struct CM_NOTIFY_FILTER_DeviceHandle { + hTarget: ::HANDLE, +}} +STRUCT!{nodebug struct CM_NOTIFY_FILTER_DeviceInstance { + InstanceId: [::WCHAR; MAX_DEVICE_ID_LEN], +}} +STRUCT!{nodebug struct CM_NOTIFY_FILTER { + cbSize: ::DWORD, + Flags: ::DWORD, + FilterType: CM_NOTIFY_FILTER_TYPE, + Reserved: ::DWORD, + u: [::BYTE; 400], +}} +UNION!(CM_NOTIFY_FILTER, u, DeviceInterface, DeviceInterface_mut, CM_NOTIFY_FILTER_DeviceInterface); +UNION!(CM_NOTIFY_FILTER, u, DeviceHandle, DeviceHandle_mut, CM_NOTIFY_FILTER_DeviceHandle); +UNION!(CM_NOTIFY_FILTER, u, DeviceInstance, DeviceInstance_mut, CM_NOTIFY_FILTER_DeviceInstance); +pub type PCM_NOTIFY_FILTER = *mut CM_NOTIFY_FILTER; +ENUM!{enum CM_NOTIFY_ACTION { + CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL = 0, + CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL, + CM_NOTIFY_ACTION_DEVICEQUERYREMOVE, + CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED, + CM_NOTIFY_ACTION_DEVICEREMOVEPENDING, + CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE, + CM_NOTIFY_ACTION_DEVICECUSTOMEVENT, + CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED, + CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED, + CM_NOTIFY_ACTION_DEVICEINSTANCEREMOVED, + CM_NOTIFY_ACTION_MAX, +}} +pub type PCM_NOTIFY_ACTION = *mut CM_NOTIFY_ACTION; +STRUCT!{struct CM_NOTIFY_EVENT_DATA_DeviceInterface { + ClassGuid: ::GUID, + SymbolicLink: [::WCHAR; ::ANYSIZE_ARRAY], +}} +STRUCT!{struct CM_NOTIFY_EVENT_DATA_DeviceHandle { + EventGuid: ::GUID, + NameOffset: ::LONG, + DataSize: ::DWORD, + Data: [::BYTE; ::ANYSIZE_ARRAY], +}} +STRUCT!{struct CM_NOTIFY_EVENT_DATA_DeviceInstance { + InstanceId: [::WCHAR; ::ANYSIZE_ARRAY], +}} +STRUCT!{struct CM_NOTIFY_EVENT_DATA { + FilterType: CM_NOTIFY_FILTER_TYPE, + Reserved: ::DWORD, + u: [::BYTE; 25], +}} +UNION!( + CM_NOTIFY_EVENT_DATA, u, DeviceInterface, DeviceInterface_mut, + CM_NOTIFY_EVENT_DATA_DeviceInterface +); +UNION!(CM_NOTIFY_EVENT_DATA, u, DeviceHandle, DeviceHandle_mut, CM_NOTIFY_EVENT_DATA_DeviceHandle); +UNION!( + CM_NOTIFY_EVENT_DATA, u, DeviceInstance, DeviceInstance_mut, CM_NOTIFY_EVENT_DATA_DeviceInstance +); +pub type PCM_NOTIFY_EVENT_DATA = *mut CM_NOTIFY_EVENT_DATA; +pub type PCM_NOTIFY_CALLBACK = Option<unsafe extern "system" fn( + hNotify: HCMNOTIFICATION, Context: ::PVOID, Action: CM_NOTIFY_ACTION, + EventData: PCM_NOTIFY_EVENT_DATA, EventDataSize: ::DWORD, +) -> ::DWORD>; +pub const CR_SUCCESS: CONFIGRET = 0x00000000; +pub const CR_DEFAULT: CONFIGRET = 0x00000001; +pub const CR_OUT_OF_MEMORY: CONFIGRET = 0x00000002; +pub const CR_INVALID_POINTER: CONFIGRET = 0x00000003; +pub const CR_INVALID_FLAG: CONFIGRET = 0x00000004; +pub const CR_INVALID_DEVNODE: CONFIGRET = 0x00000005; +pub const CR_INVALID_DEVINST: CONFIGRET = CR_INVALID_DEVNODE; +pub const CR_INVALID_RES_DES: CONFIGRET = 0x00000006; +pub const CR_INVALID_LOG_CONF: CONFIGRET = 0x00000007; +pub const CR_INVALID_ARBITRATOR: CONFIGRET = 0x00000008; +pub const CR_INVALID_NODELIST: CONFIGRET = 0x00000009; +pub const CR_DEVNODE_HAS_REQS: CONFIGRET = 0x0000000A; +pub const CR_DEVINST_HAS_REQS: CONFIGRET = CR_DEVNODE_HAS_REQS; +pub const CR_INVALID_RESOURCEID: CONFIGRET = 0x0000000B; +pub const CR_DLVXD_NOT_FOUND: CONFIGRET = 0x0000000C; +pub const CR_NO_SUCH_DEVNODE: CONFIGRET = 0x0000000D; +pub const CR_NO_SUCH_DEVINST: CONFIGRET = CR_NO_SUCH_DEVNODE; +pub const CR_NO_MORE_LOG_CONF: CONFIGRET = 0x0000000E; +pub const CR_NO_MORE_RES_DES: CONFIGRET = 0x0000000F; +pub const CR_ALREADY_SUCH_DEVNODE: CONFIGRET = 0x00000010; +pub const CR_ALREADY_SUCH_DEVINST: CONFIGRET = CR_ALREADY_SUCH_DEVNODE; +pub const CR_INVALID_RANGE_LIST: CONFIGRET = 0x00000011; +pub const CR_INVALID_RANGE: CONFIGRET = 0x00000012; +pub const CR_FAILURE: CONFIGRET = 0x00000013; +pub const CR_NO_SUCH_LOGICAL_DEV: CONFIGRET = 0x00000014; +pub const CR_CREATE_BLOCKED: CONFIGRET = 0x00000015; +pub const CR_NOT_SYSTEM_VM: CONFIGRET = 0x00000016; +pub const CR_REMOVE_VETOED: CONFIGRET = 0x00000017; +pub const CR_APM_VETOED: CONFIGRET = 0x00000018; +pub const CR_INVALID_LOAD_TYPE: CONFIGRET = 0x00000019; +pub const CR_BUFFER_SMALL: CONFIGRET = 0x0000001A; +pub const CR_NO_ARBITRATOR: CONFIGRET = 0x0000001B; +pub const CR_NO_REGISTRY_HANDLE: CONFIGRET = 0x0000001C; +pub const CR_REGISTRY_ERROR: CONFIGRET = 0x0000001D; +pub const CR_INVALID_DEVICE_ID: CONFIGRET = 0x0000001E; +pub const CR_INVALID_DATA: CONFIGRET = 0x0000001F; +pub const CR_INVALID_API: CONFIGRET = 0x00000020; +pub const CR_DEVLOADER_NOT_READY: CONFIGRET = 0x00000021; +pub const CR_NEED_RESTART: CONFIGRET = 0x00000022; +pub const CR_NO_MORE_HW_PROFILES: CONFIGRET = 0x00000023; +pub const CR_DEVICE_NOT_THERE: CONFIGRET = 0x00000024; +pub const CR_NO_SUCH_VALUE: CONFIGRET = 0x00000025; +pub const CR_WRONG_TYPE: CONFIGRET = 0x00000026; +pub const CR_INVALID_PRIORITY: CONFIGRET = 0x00000027; +pub const CR_NOT_DISABLEABLE: CONFIGRET = 0x00000028; +pub const CR_FREE_RESOURCES: CONFIGRET = 0x00000029; +pub const CR_QUERY_VETOED: CONFIGRET = 0x0000002A; +pub const CR_CANT_SHARE_IRQ: CONFIGRET = 0x0000002B; +pub const CR_NO_DEPENDENT: CONFIGRET = 0x0000002C; +pub const CR_SAME_RESOURCES: CONFIGRET = 0x0000002D; +pub const CR_NO_SUCH_REGISTRY_KEY: CONFIGRET = 0x0000002E; +pub const CR_INVALID_MACHINENAME: CONFIGRET = 0x0000002F; +pub const CR_REMOTE_COMM_FAILURE: CONFIGRET = 0x00000030; +pub const CR_MACHINE_UNAVAILABLE: CONFIGRET = 0x00000031; +pub const CR_NO_CM_SERVICES: CONFIGRET = 0x00000032; +pub const CR_ACCESS_DENIED: CONFIGRET = 0x00000033; +pub const CR_CALL_NOT_IMPLEMENTED: CONFIGRET = 0x00000034; +pub const CR_INVALID_PROPERTY: CONFIGRET = 0x00000035; +pub const CR_DEVICE_INTERFACE_ACTIVE: CONFIGRET = 0x00000036; +pub const CR_NO_SUCH_DEVICE_INTERFACE: CONFIGRET = 0x00000037; +pub const CR_INVALID_REFERENCE_STRING: CONFIGRET = 0x00000038; +pub const CR_INVALID_CONFLICT_LIST: CONFIGRET = 0x00000039; +pub const CR_INVALID_INDEX: CONFIGRET = 0x0000003A; +pub const CR_INVALID_STRUCTURE_SIZE: CONFIGRET = 0x0000003B; +pub const NUM_CR_RESULTS: CONFIGRET = 0x0000003C; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/combaseapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/combaseapi.rs new file mode 100644 index 0000000..9233bc5 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/combaseapi.rs @@ -0,0 +1,17 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub const CLSCTX_INPROC_SERVER: DWORD = 0x1; +pub const CLSCTX_INPROC_HANDLER: DWORD = 0x2; +pub const CLSCTX_LOCAL_SERVER: DWORD = 0x4; +pub const CLSCTX_REMOTE_SERVER: DWORD = 0x10; +pub const CLSCTX_SERVER: DWORD = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | + CLSCTX_REMOTE_SERVER; +pub const CLSCTX_ALL: DWORD = CLSCTX_INPROC_HANDLER | CLSCTX_SERVER; +STRUCT!{struct ServerInformation { + dwServerPid: DWORD, + dwServerTid: DWORD, + ui64ServerAddress: UINT64, +}} +pub type PServerInformation = *mut ServerInformation; +DECLARE_HANDLE!(CO_MTA_USAGE_COOKIE, CO_MTA_USAGE_COOKIE__); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/commctrl.rs b/bash-5.1/vendor/winapi-0.2.8/src/commctrl.rs new file mode 100644 index 0000000..88513e1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/commctrl.rs @@ -0,0 +1,3578 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//138 +STRUCT!{struct INITCOMMONCONTROLSEX { + dwSize: ::DWORD, + dwICC: ::DWORD, +}} +pub type LPINITCOMMONCONTROLSEX = *mut INITCOMMONCONTROLSEX; +pub const ICC_LISTVIEW_CLASSES: ::DWORD = 0x1; +pub const ICC_TREEVIEW_CLASSES: ::DWORD = 0x2; +pub const ICC_BAR_CLASSES: ::DWORD = 0x4; +pub const ICC_TAB_CLASSES: ::DWORD = 0x8; +pub const ICC_UPDOWN_CLASS: ::DWORD = 0x10; +pub const ICC_PROGRESS_CLASS: ::DWORD = 0x20; +pub const ICC_HOTKEY_CLASS: ::DWORD = 0x40; +pub const ICC_ANIMATE_CLASS: ::DWORD = 0x80; +pub const ICC_WIN95_CLASSES: ::DWORD = 0xFF; +pub const ICC_DATE_CLASSES: ::DWORD = 0x100; +pub const ICC_USEREX_CLASSES: ::DWORD = 0x200; +pub const ICC_COOL_CLASSES: ::DWORD = 0x400; +pub const ICC_INTERNET_CLASSES: ::DWORD = 0x800; +pub const ICC_PAGESCROLLER_CLASS: ::DWORD = 0x1000; +pub const ICC_NATIVEFNTCTL_CLASS: ::DWORD = 0x2000; +pub const ICC_STANDARD_CLASSES: ::DWORD = 0x4000; +pub const ICC_LINK_CLASS: ::DWORD = 0x8000; +pub const ODT_HEADER: ::UINT = 100; +pub const ODT_TAB: ::UINT = 101; +pub const ODT_LISTVIEW: ::UINT = 102; +pub const LVM_FIRST: ::UINT = 0x1000; +pub const TV_FIRST: ::UINT = 0x1100; +pub const HDM_FIRST: ::UINT = 0x1200; +pub const TCM_FIRST: ::UINT = 0x1300; +pub const PGM_FIRST: ::UINT = 0x1400; +pub const ECM_FIRST: ::UINT = 0x1500; +pub const BCM_FIRST: ::UINT = 0x1600; +pub const CBM_FIRST: ::UINT = 0x1700; +pub const CCM_FIRST: ::UINT = 0x2000; +pub const CCM_LAST: ::UINT = CCM_FIRST + 0x200; +pub const CCM_SETBKCOLOR: ::UINT = CCM_FIRST + 1; +STRUCT!{struct COLORSCHEME { + dwSize: ::DWORD, + clrBtnHighlight: ::COLORREF, + clrBtnShadow: ::COLORREF, +}} +pub type LPCOLORSCHEME = *mut COLORSCHEME; +pub const CCM_SETCOLORSCHEME: ::UINT = CCM_FIRST + 2; +pub const CCM_GETCOLORSCHEME: ::UINT = CCM_FIRST + 3; +pub const CCM_GETDROPTARGET: ::UINT = CCM_FIRST + 4; +pub const CCM_SETUNICODEFORMAT: ::UINT = CCM_FIRST + 5; +pub const CCM_GETUNICODEFORMAT: ::UINT = CCM_FIRST + 6; +pub const CCM_SETVERSION: ::UINT = CCM_FIRST + 7; +pub const CCM_GETVERSION: ::UINT = CCM_FIRST + 8; +pub const CCM_SETNOTIFYWINDOW: ::UINT = CCM_FIRST + 9; +pub const CCM_SETWINDOWTHEME: ::UINT = CCM_FIRST + 0xb; +pub const CCM_DPISCALE: ::UINT = CCM_FIRST + 0xc; +pub const INFOTIPSIZE: ::c_int = 1024; +pub const NM_OUTOFMEMORY: ::UINT = (NM_FIRST as ::INT - 1) as ::UINT; +pub const NM_CLICK: ::UINT = (NM_FIRST as ::INT - 2) as ::UINT; +pub const NM_DBLCLK: ::UINT = (NM_FIRST as ::INT - 3) as ::UINT; +pub const NM_RETURN: ::UINT = (NM_FIRST as ::INT - 4) as ::UINT; +pub const NM_RCLICK: ::UINT = (NM_FIRST as ::INT - 5) as ::UINT; +pub const NM_RDBLCLK: ::UINT = (NM_FIRST as ::INT - 6) as ::UINT; +pub const NM_SETFOCUS: ::UINT = (NM_FIRST as ::INT - 7) as ::UINT; +pub const NM_KILLFOCUS: ::UINT = (NM_FIRST as ::INT - 8) as ::UINT; +pub const NM_CUSTOMDRAW: ::UINT = (NM_FIRST as ::INT - 12) as ::UINT; +pub const NM_HOVER: ::UINT = (NM_FIRST as ::INT - 13) as ::UINT; +pub const NM_NCHITTEST: ::UINT = (NM_FIRST as ::INT - 14) as ::UINT; +pub const NM_KEYDOWN: ::UINT = (NM_FIRST as ::INT - 15) as ::UINT; +pub const NM_RELEASEDCAPTURE: ::UINT = (NM_FIRST as ::INT - 16) as ::UINT; +pub const NM_SETCURSOR: ::UINT = (NM_FIRST as ::INT - 17) as ::UINT; +pub const NM_CHAR: ::UINT = (NM_FIRST as ::INT - 18) as ::UINT; +pub const NM_TOOLTIPSCREATED: ::UINT = (NM_FIRST as ::INT - 19) as ::UINT; +pub const NM_LDOWN: ::UINT = (NM_FIRST as ::INT - 20) as ::UINT; +pub const NM_RDOWN: ::UINT = (NM_FIRST as ::INT - 21) as ::UINT; +pub const NM_THEMECHANGED: ::UINT = (NM_FIRST as ::INT - 22) as ::UINT; +pub const NM_FONTCHANGED: ::UINT = (NM_FIRST as ::INT - 23) as ::UINT; +pub const NM_CUSTOMTEXT: ::UINT = (NM_FIRST as ::INT - 24) as ::UINT; +pub const NM_TVSTATEIMAGECHANGING: ::UINT = (NM_FIRST as ::INT - 24) as ::UINT; +STRUCT!{struct NMTOOLTIPSCREATED { + hdr: ::NMHDR, + hwndToolTips: ::HWND, +}} +pub type LPNMTOOLTIPSCREATED = *mut NMTOOLTIPSCREATED; +STRUCT!{struct NMMOUSE { + hdr : ::NMHDR, + dwItemSpec: ::DWORD_PTR, + dwItemData: ::DWORD_PTR, + pt: ::POINT, + dwHitInfo: ::LPARAM, +}} +pub type LPNMMOUSE = *mut NMMOUSE; +pub type NMCLICK = NMMOUSE; +pub type LPNMCLICK = LPNMMOUSE; +STRUCT!{struct NMOBJECTNOTIFY { + hdr: ::NMHDR, + iItem: ::c_int, + piid: *const ::IID, + pObject: *mut ::c_void, + hResult: ::HRESULT, + dwFlags: ::DWORD, +}} +pub type LPNMOBJECTNOTIFY = *mut NMOBJECTNOTIFY; +STRUCT!{struct NMKEY { + hdr: ::NMHDR, + nVKey: ::UINT, + uFlags: ::UINT, +}} +pub type LPNMKEY = *mut NMKEY; +STRUCT!{struct NMCHAR { + hdr: ::NMHDR, + ch: ::UINT, + dwItemPrev: ::DWORD, + dwItemNext: ::DWORD, +}} +pub type LPNMCHAR = *mut NMCHAR; +STRUCT!{struct NMCUSTOMTEXT { + hdr: ::NMHDR, + hDC: ::HDC, + lpString: ::LPCWSTR, + nCount: ::c_int, + lpRect: ::LPRECT, + uFormat: ::UINT, + fLink: ::BOOL, +}} +pub type LPNMCUSTOMTEXT = *mut NMCUSTOMTEXT; +pub const NM_FIRST: ::UINT = 0; +pub const NM_LAST: ::UINT = -99i32 as ::UINT; +pub const LVN_FIRST: ::UINT = -100i32 as ::UINT; +pub const LVN_LAST: ::UINT = -199i32 as ::UINT; +pub const HDN_FIRST: ::UINT = -300i32 as ::UINT; +pub const HDN_LAST: ::UINT = -399i32 as ::UINT; +pub const TVN_FIRST: ::UINT = -400i32 as ::UINT; +pub const TVN_LAST: ::UINT = -499i32 as ::UINT; +pub const TTN_FIRST: ::UINT = -520i32 as ::UINT; +pub const TTN_LAST: ::UINT = -549i32 as ::UINT; +pub const TCN_FIRST: ::UINT = -550i32 as ::UINT; +pub const TCN_LAST: ::UINT = -580i32 as ::UINT; +// pub const CDN_FIRST: ::UINT = 0 - 601; +// pub const CDN_LAST: ::UINT = 0 - 699; +pub const TBN_FIRST: ::UINT = -700i32 as ::UINT; +pub const TBN_LAST: ::UINT = -720i32 as ::UINT; +pub const UDN_FIRST: ::UINT = -721i32 as ::UINT; +pub const UDN_LAST: ::UINT = -729i32 as ::UINT; +pub const DTN_FIRST: ::UINT = -740i32 as ::UINT; +pub const DTN_LAST: ::UINT = -745i32 as ::UINT; +pub const MCN_FIRST: ::UINT = -746i32 as ::UINT; +pub const MCN_LAST: ::UINT = -752i32 as ::UINT; +pub const DTN_FIRST2: ::UINT = -753i32 as ::UINT; +pub const DTN_LAST2: ::UINT = -799i32 as ::UINT; +pub const CBEN_FIRST: ::UINT = -800i32 as ::UINT; +pub const CBEN_LAST: ::UINT = -830i32 as ::UINT; +pub const RBN_FIRST: ::UINT = -831i32 as ::UINT; +pub const RBN_LAST: ::UINT = -859i32 as ::UINT; +pub const IPN_FIRST: ::UINT = -860i32 as ::UINT; +pub const IPN_LAST: ::UINT = -879i32 as ::UINT; +pub const SBN_FIRST: ::UINT = -880i32 as ::UINT; +pub const SBN_LAST: ::UINT = -899i32 as ::UINT; +pub const PGN_FIRST: ::UINT = -900i32 as ::UINT; +pub const PGN_LAST: ::UINT = -950i32 as ::UINT; +pub const WMN_FIRST: ::UINT = -1000i32 as ::UINT; +pub const WMN_LAST: ::UINT = -1200i32 as ::UINT; +pub const BCN_FIRST: ::UINT = -1250i32 as ::UINT; +pub const BCN_LAST: ::UINT = -1350i32 as ::UINT; +pub const TRBN_FIRST: ::UINT = -1501i32 as ::UINT; +pub const TRBN_LAST: ::UINT = -1519i32 as ::UINT; +pub const CDRF_DODEFAULT: ::LRESULT = 0x00000000; +pub const CDRF_NEWFONT: ::LRESULT = 0x00000002; +pub const CDRF_SKIPDEFAULT: ::LRESULT = 0x00000004; +pub const CDRF_DOERASE: ::LRESULT = 0x00000008; +pub const CDRF_SKIPPOSTPAINT: ::LRESULT = 0x00000100; +pub const CDRF_NOTIFYPOSTPAINT: ::LRESULT = 0x00000010; +pub const CDRF_NOTIFYITEMDRAW: ::LRESULT = 0x00000020; +pub const CDRF_NOTIFYSUBITEMDRAW: ::LRESULT = 0x00000020; +pub const CDRF_NOTIFYPOSTERASE: ::LRESULT = 0x00000040; +pub const CDDS_PREPAINT: ::DWORD = 0x00000001; +pub const CDDS_POSTPAINT: ::DWORD = 0x00000002; +pub const CDDS_PREERASE: ::DWORD = 0x00000003; +pub const CDDS_POSTERASE: ::DWORD = 0x00000004; +pub const CDDS_ITEM: ::DWORD = 0x00010000; +pub const CDDS_ITEMPREPAINT: ::DWORD = CDDS_ITEM | CDDS_PREPAINT; +pub const CDDS_ITEMPOSTPAINT: ::DWORD = CDDS_ITEM | CDDS_POSTPAINT; +pub const CDDS_ITEMPREERASE: ::DWORD = CDDS_ITEM | CDDS_PREERASE; +pub const CDDS_ITEMPOSTERASE: ::DWORD = CDDS_ITEM | CDDS_POSTERASE; +pub const CDDS_SUBITEM: ::DWORD = 0x00020000; +pub const CDIS_SELECTED: ::UINT = 0x0001; +pub const CDIS_GRAYED: ::UINT = 0x0002; +pub const CDIS_DISABLED: ::UINT = 0x0004; +pub const CDIS_CHECKED: ::UINT = 0x0008; +pub const CDIS_FOCUS: ::UINT = 0x0010; +pub const CDIS_DEFAULT: ::UINT = 0x0020; +pub const CDIS_HOT: ::UINT = 0x0040; +pub const CDIS_MARKED: ::UINT = 0x0080; +pub const CDIS_INDETERMINATE: ::UINT = 0x0100; +pub const CDIS_SHOWKEYBOARDCUES: ::UINT = 0x0200; +pub const CDIS_NEARHOT: ::UINT = 0x0400; +pub const CDIS_OTHERSIDEHOT: ::UINT = 0x0800; +pub const CDIS_DROPHILITED: ::UINT = 0x1000; +STRUCT!{struct NMCUSTOMDRAW { + hdr: ::NMHDR, + dwDrawStage: ::DWORD, + hdc: ::HDC, + rc: ::RECT, + dwItemSpec: ::DWORD_PTR, + uItemState: ::UINT, + lItemlParam: ::LPARAM, +}} +pub type LPNMCUSTOMDRAW = *mut NMCUSTOMDRAW; +STRUCT!{struct NMTTCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + uDrawFlags: ::UINT, +}} +pub type LPNMTTCUSTOMDRAW = *mut NMTTCUSTOMDRAW; +STRUCT!{struct NMCUSTOMSPLITRECTINFO { + hdr: ::NMHDR, + rcClient: ::RECT, + rcButton: ::RECT, + rcSplit: ::RECT, +}} +pub type LPNMCUSTOMSPLITRECTINFO = *mut NMCUSTOMSPLITRECTINFO; +pub const NM_GETCUSTOMSPLITRECT: ::UINT = BCN_FIRST + 0x0003; +pub const CLR_NONE: ::DWORD = 0xFFFFFFFF; +pub const CLR_DEFAULT: ::DWORD = 0xFF000000; +pub enum IMAGELIST {} +pub type HIMAGELIST = *mut IMAGELIST; +STRUCT!{struct IMAGELISTDRAWPARAMS { + cbSize: ::DWORD, + himl: HIMAGELIST, + i: ::c_int, + hdcDst: ::HDC, + x: ::c_int, + y: ::c_int, + cx: ::c_int, + cy: ::c_int, + xBitmap: ::c_int, + yBitmap: ::c_int, + rgbBk: ::COLORREF, + rgbFg: ::COLORREF, + fStyle: ::UINT, + dwRop: ::DWORD, + fState: ::DWORD, + Frame: ::DWORD, + crEffect: ::COLORREF, +}} +pub type LPIMAGELISTDRAWPARAMS = *mut IMAGELISTDRAWPARAMS; +pub const ILC_MASK: ::UINT = 0x00000001; +pub const ILC_COLOR: ::UINT = 0x00000000; +pub const ILC_COLORDDB: ::UINT = 0x000000FE; +pub const ILC_COLOR4: ::UINT = 0x00000004; +pub const ILC_COLOR8: ::UINT = 0x00000008; +pub const ILC_COLOR16: ::UINT = 0x00000010; +pub const ILC_COLOR24: ::UINT = 0x00000018; +pub const ILC_COLOR32: ::UINT = 0x00000020; +pub const ILC_PALETTE: ::UINT = 0x00000800; +pub const ILC_MIRROR: ::UINT = 0x00002000; +pub const ILC_PERITEMMIRROR: ::UINT = 0x00008000; +pub const ILC_ORIGINALSIZE: ::UINT = 0x00010000; +pub const ILC_HIGHQUALITYSCALE: ::UINT = 0x00020000; +pub const ILD_NORMAL: ::UINT = 0x00000000; +pub const ILD_TRANSPARENT: ::UINT = 0x00000001; +pub const ILD_MASK: ::UINT = 0x00000010; +pub const ILD_IMAGE: ::UINT = 0x00000020; +pub const ILD_ROP: ::UINT = 0x00000040; +pub const ILD_BLEND25: ::UINT = 0x00000002; +pub const ILD_BLEND50: ::UINT = 0x00000004; +pub const ILD_OVERLAYMASK: ::UINT = 0x00000F00; +#[inline] #[allow(dead_code)] +pub fn INDEXTOOVERLAYMASK(i: ::UINT) -> ::UINT { i << 8 } +pub const ILD_PRESERVEALPHA: ::UINT = 0x00001000; +pub const ILD_SCALE: ::UINT = 0x00002000; +pub const ILD_DPISCALE: ::UINT = 0x00004000; +pub const ILD_ASYNC: ::UINT = 0x00008000; +pub const ILD_SELECTED: ::UINT = ILD_BLEND50; +pub const ILD_FOCUS: ::UINT = ILD_BLEND25; +pub const ILD_BLEND: ::UINT = ILD_BLEND50; +pub const CLR_HILIGHT: ::DWORD = CLR_DEFAULT; +pub const ILS_NORMAL: ::DWORD = 0x00000000; +pub const ILS_GLOW: ::DWORD = 0x00000001; +pub const ILS_SHADOW: ::DWORD = 0x00000002; +pub const ILS_SATURATE: ::DWORD = 0x00000004; +pub const ILS_ALPHA: ::DWORD = 0x00000008; +pub const HBITMAP_CALLBACK: ::HBITMAP = (0-1) as ::HBITMAP; +pub const ILCF_MOVE: ::UINT = 0x00000000; +pub const ILCF_SWAP: ::UINT = 0x00000001; +STRUCT!{struct IMAGEINFO { + hbmImage: ::HBITMAP, + hbmMask: ::HBITMAP, + Unused1: ::c_int, + Unused2: ::c_int, + rcImage: ::RECT, +}} +pub type LPIMAGEINFO = *mut IMAGEINFO; +pub const HDS_HORZ: ::DWORD = 0x0000; +pub const HDS_BUTTONS: ::DWORD = 0x0002; +pub const HDS_HOTTRACK: ::DWORD = 0x0004; +pub const HDS_HIDDEN: ::DWORD = 0x0008; +pub const HDS_DRAGDROP: ::DWORD = 0x0040; +pub const HDS_FULLDRAG: ::DWORD = 0x0080; +pub const HDS_FILTERBAR: ::DWORD = 0x0100; +pub const HDS_FLAT: ::DWORD = 0x0200; +pub const HDS_CHECKBOXES: ::DWORD = 0x0400; +pub const HDS_NOSIZING: ::DWORD = 0x0800; +pub const HDS_OVERFLOW: ::DWORD = 0x1000; +pub const HDFT_ISSTRING: ::UINT = 0x0000; +pub const HDFT_ISNUMBER: ::UINT = 0x0001; +pub const HDFT_ISDATE: ::UINT = 0x0002; +pub const HDFT_HASNOVALUE: ::UINT = 0x8000; +STRUCT!{struct HD_TEXTFILTERA { + pszText: ::LPSTR, + cchTextMax: ::INT, +}} +pub type LPHD_TEXTFILTERA = *mut HD_TEXTFILTERA; +STRUCT!{struct HD_TEXTFILTERW { + pszText: ::LPWSTR, + cchTextMax: ::INT, +}} +pub type LPHD_TEXTFILTERW = *mut HD_TEXTFILTERW; +STRUCT!{struct HDITEMA { + mask: ::UINT, + cxy: ::c_int, + pszText: ::LPSTR, + hbm: ::HBITMAP, + cchTextMax: ::c_int, + fmt: ::c_int, + lParam: ::LPARAM, + iImage: ::c_int, + iOrder: ::c_int, + _type: ::UINT, + pvFilter: *mut ::c_void, + state: ::UINT, +}} +pub type LPHDITEMA = *mut HDITEMA; +STRUCT!{struct HDITEMW { + mask: ::UINT, + cxy: ::c_int, + pszText: ::LPWSTR, + hbm: ::HBITMAP, + cchTextMax: ::c_int, + fmt: ::c_int, + lParam: ::LPARAM, + iImage: ::c_int, + iOrder: ::c_int, + _type: ::UINT, + pvFilter: *mut ::c_void, + state: ::UINT, +}} +pub type LPHDITEMW = *mut HDITEMW; +pub const HDI_WIDTH: ::UINT = 0x0001; +pub const HDI_HEIGHT: ::UINT = HDI_WIDTH; +pub const HDI_TEXT: ::UINT = 0x0002; +pub const HDI_FORMAT: ::UINT = 0x0004; +pub const HDI_LPARAM: ::UINT = 0x0008; +pub const HDI_BITMAP: ::UINT = 0x0010; +pub const HDI_IMAGE: ::UINT = 0x0020; +pub const HDI_DI_SETITEM: ::UINT = 0x0040; +pub const HDI_ORDER: ::UINT = 0x0080; +pub const HDI_FILTER: ::UINT = 0x0100; +pub const HDI_STATE: ::UINT = 0x0200; +pub const HDF_LEFT: ::c_int = 0x0000; +pub const HDF_RIGHT: ::c_int = 0x0001; +pub const HDF_CENTER: ::c_int = 0x0002; +pub const HDF_JUSTIFYMASK: ::c_int = 0x0003; +pub const HDF_RTLREADING: ::c_int = 0x0004; +pub const HDF_BITMAP: ::c_int = 0x2000; +pub const HDF_STRING: ::c_int = 0x4000; +pub const HDF_OWNERDRAW: ::c_int = 0x8000; +pub const HDF_IMAGE: ::c_int = 0x0800; +pub const HDF_BITMAP_ON_RIGHT: ::c_int = 0x1000; +pub const HDF_SORTUP: ::c_int = 0x0400; +pub const HDF_SORTDOWN: ::c_int = 0x0200; +pub const HDF_CHECKBOX: ::c_int = 0x0040; +pub const HDF_CHECKED: ::c_int = 0x0080; +pub const HDF_FIXEDWIDTH: ::c_int = 0x0100; +pub const HDF_SPLITBUTTON: ::c_int = 0x1000000; +pub const HDIS_FOCUSED: ::UINT = 0x00000001; +pub const HDM_GETITEMCOUNT: ::UINT = HDM_FIRST + 0; +pub const HDM_INSERTITEMA: ::UINT = HDM_FIRST + 1; +pub const HDM_INSERTITEMW: ::UINT = HDM_FIRST + 10; +pub const HDM_DELETEITEM: ::UINT = HDM_FIRST + 2; +pub const HDM_GETITEMA: ::UINT = HDM_FIRST + 3; +pub const HDM_GETITEMW: ::UINT = HDM_FIRST + 11; +pub const HDM_SETITEMA: ::UINT = HDM_FIRST + 4; +pub const HDM_SETITEMW: ::UINT = HDM_FIRST + 12; +STRUCT!{struct HDLAYOUT { + prc: *mut ::RECT, + pwpos: *mut ::WINDOWPOS, +}} +pub type LPHDLAYOUT = *mut HDLAYOUT; +pub const HDM_LAYOUT: ::UINT = HDM_FIRST + 5; +pub const HHT_NOWHERE: ::UINT = 0x0001; +pub const HHT_ONHEADER: ::UINT = 0x0002; +pub const HHT_ONDIVIDER: ::UINT = 0x0004; +pub const HHT_ONDIVOPEN: ::UINT = 0x0008; +pub const HHT_ONFILTER: ::UINT = 0x0010; +pub const HHT_ONFILTERBUTTON: ::UINT = 0x0020; +pub const HHT_ABOVE: ::UINT = 0x0100; +pub const HHT_BELOW: ::UINT = 0x0200; +pub const HHT_TORIGHT: ::UINT = 0x0400; +pub const HHT_TOLEFT: ::UINT = 0x0800; +pub const HHT_ONITEMSTATEICON: ::UINT = 0x1000; +pub const HHT_ONDROPDOWN: ::UINT = 0x2000; +pub const HHT_ONOVERFLOW: ::UINT = 0x4000; +STRUCT!{struct HDHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + iItem: ::c_int, +}} +pub type LPHDHITTESTINFO = *mut HDHITTESTINFO; +pub const HDSIL_NORMAL: ::WPARAM = 0; +pub const HDSIL_STATE: ::WPARAM = 1; +pub const HDM_HITTEST: ::UINT = HDM_FIRST + 6; +pub const HDM_GETITEMRECT: ::UINT = HDM_FIRST + 7; +pub const HDM_SETIMAGELIST: ::UINT = HDM_FIRST + 8; +pub const HDM_GETIMAGELIST: ::UINT = HDM_FIRST + 9; +pub const HDM_ORDERTOINDEX: ::UINT = HDM_FIRST + 15; +pub const HDM_CREATEDRAGIMAGE: ::UINT = HDM_FIRST + 16; +pub const HDM_GETORDERARRAY: ::UINT = HDM_FIRST + 17; +pub const HDM_SETORDERARRAY: ::UINT = HDM_FIRST + 18; +pub const HDM_SETHOTDIVIDER: ::UINT = HDM_FIRST + 19; +pub const HDM_SETBITMAPMARGIN: ::UINT = HDM_FIRST + 20; +pub const HDM_GETBITMAPMARGIN: ::UINT = HDM_FIRST + 21; +pub const HDM_SETFILTERCHANGETIMEOUT: ::UINT = HDM_FIRST + 22; +pub const HDM_EDITFILTER: ::UINT = HDM_FIRST + 23; +pub const HDM_CLEARFILTER: ::UINT = HDM_FIRST + 24; +pub const HDM_GETITEMDROPDOWNRECT: ::UINT = HDM_FIRST + 25; +pub const HDM_GETOVERFLOWRECT: ::UINT = HDM_FIRST + 26; +pub const HDM_GETFOCUSEDITEM: ::UINT = HDM_FIRST + 27; +pub const HDM_SETFOCUSEDITEM: ::UINT = HDM_FIRST + 28; +pub const HDN_ITEMCHANGINGA: ::UINT = HDN_FIRST-0; +pub const HDN_ITEMCHANGINGW: ::UINT = HDN_FIRST-20; +pub const HDN_ITEMCHANGEDA: ::UINT = HDN_FIRST-1; +pub const HDN_ITEMCHANGEDW: ::UINT = HDN_FIRST-21; +pub const HDN_ITEMCLICKA: ::UINT = HDN_FIRST-2; +pub const HDN_ITEMCLICKW: ::UINT = HDN_FIRST-22; +pub const HDN_ITEMDBLCLICKA: ::UINT = HDN_FIRST-3; +pub const HDN_ITEMDBLCLICKW: ::UINT = HDN_FIRST-23; +pub const HDN_DIVIDERDBLCLICKA: ::UINT = HDN_FIRST-5; +pub const HDN_DIVIDERDBLCLICKW: ::UINT = HDN_FIRST-25; +pub const HDN_BEGINTRACKA: ::UINT = HDN_FIRST-6; +pub const HDN_BEGINTRACKW: ::UINT = HDN_FIRST-26; +pub const HDN_ENDTRACKA: ::UINT = HDN_FIRST-7; +pub const HDN_ENDTRACKW: ::UINT = HDN_FIRST-27; +pub const HDN_TRACKA: ::UINT = HDN_FIRST-8; +pub const HDN_TRACKW: ::UINT = HDN_FIRST-28; +pub const HDN_GETDISPINFOA: ::UINT = HDN_FIRST-9; +pub const HDN_GETDISPINFOW: ::UINT = HDN_FIRST-29; +pub const HDN_BEGINDRAG: ::UINT = HDN_FIRST-10; +pub const HDN_ENDDRAG: ::UINT = HDN_FIRST-11; +pub const HDN_FILTERCHANGE: ::UINT = HDN_FIRST-12; +pub const HDN_FILTERBTNCLICK: ::UINT = HDN_FIRST-13; +pub const HDN_BEGINFILTEREDIT: ::UINT = HDN_FIRST-14; +pub const HDN_ENDFILTEREDIT: ::UINT = HDN_FIRST-15; +pub const HDN_ITEMSTATEICONCLICK: ::UINT = HDN_FIRST-16; +pub const HDN_ITEMKEYDOWN: ::UINT = HDN_FIRST-17; +pub const HDN_DROPDOWN: ::UINT = HDN_FIRST-18; +pub const HDN_OVERFLOWCLICK: ::UINT = HDN_FIRST-19; +STRUCT!{struct NMHEADERA { + hdr: ::NMHDR, + iItem: ::c_int, + iButton: ::c_int, + pitem: *mut HDITEMA, +}} +pub type LPNMHEADERA = *mut NMHEADERA; +STRUCT!{struct NMHEADERW { + hdr: ::NMHDR, + iItem: ::c_int, + iButton: ::c_int, + pitem: *mut HDITEMW, +}} +pub type LPNMHEADERW = *mut NMHEADERW; +STRUCT!{struct NMHDDISPINFOW { + hdr: ::NMHDR, + iItem: ::c_int, + mask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMHDDISPINFOW = *mut NMHDDISPINFOW; +STRUCT!{struct NMHDDISPINFOA { + hdr: ::NMHDR, + iItem: ::c_int, + mask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMHDDISPINFOA = *mut NMHDDISPINFOA; +STRUCT!{struct NMHDFILTERBTNCLICK { + hdr: ::NMHDR, + iItem: ::INT, + rc: ::RECT, +}} +pub type LPNMHDFILTERBTNCLICK = *mut NMHDFILTERBTNCLICK; +#[cfg(target_arch="x86")] +STRUCT!{struct TBBUTTON { + iBitmap: ::c_int, + idCommand: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + bReserved: [::BYTE; 2], + dwData: ::DWORD_PTR, + iString: ::INT_PTR, +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct TBBUTTON { + iBitmap: ::c_int, + idCommand: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + bReserved: [::BYTE; 6], + dwData: ::DWORD_PTR, + iString: ::INT_PTR, +}} +pub type PTBBUTTON = *mut TBBUTTON; +pub type LPTBBUTTON = *mut TBBUTTON; +pub type LPCTBBUTTON = *const TBBUTTON; +STRUCT!{struct COLORMAP { + from: ::COLORREF, + to: ::COLORREF, +}} +pub type LPCOLORMAP = *mut COLORMAP; +pub const CMB_MASKED: ::UINT = 0x02; +pub const TBSTATE_CHECKED: ::BYTE = 0x01; +pub const TBSTATE_PRESSED: ::BYTE = 0x02; +pub const TBSTATE_ENABLED: ::BYTE = 0x04; +pub const TBSTATE_HIDDEN: ::BYTE = 0x08; +pub const TBSTATE_INDETERMINATE: ::BYTE = 0x10; +pub const TBSTATE_WRAP: ::BYTE = 0x20; +pub const TBSTATE_ELLIPSES: ::BYTE = 0x40; +pub const TBSTATE_MARKED: ::BYTE = 0x80; +pub const TBSTYLE_BUTTON: ::DWORD = 0x0000; +pub const TBSTYLE_SEP: ::DWORD = 0x0001; +pub const TBSTYLE_CHECK: ::DWORD = 0x0002; +pub const TBSTYLE_GROUP: ::DWORD = 0x0004; +pub const TBSTYLE_CHECKGROUP: ::DWORD = TBSTYLE_GROUP | TBSTYLE_CHECK; +pub const TBSTYLE_DROPDOWN: ::DWORD = 0x0008; +pub const TBSTYLE_AUTOSIZE: ::DWORD = 0x0010; +pub const TBSTYLE_NOPREFIX: ::DWORD = 0x0020; +pub const TBSTYLE_TOOLTIPS: ::DWORD = 0x0100; +pub const TBSTYLE_WRAPABLE: ::DWORD = 0x0200; +pub const TBSTYLE_ALTDRAG: ::DWORD = 0x0400; +pub const TBSTYLE_FLAT: ::DWORD = 0x0800; +pub const TBSTYLE_LIST: ::DWORD = 0x1000; +pub const TBSTYLE_CUSTOMERASE: ::DWORD = 0x2000; +pub const TBSTYLE_REGISTERDROP: ::DWORD = 0x4000; +pub const TBSTYLE_TRANSPARENT: ::DWORD = 0x8000; +pub const TBSTYLE_EX_DRAWDDARROWS: ::DWORD = 0x00000001; +pub const BTNS_BUTTON: ::DWORD = TBSTYLE_BUTTON; +pub const BTNS_SEP: ::DWORD = TBSTYLE_SEP; +pub const BTNS_CHECK: ::DWORD = TBSTYLE_CHECK; +pub const BTNS_GROUP: ::DWORD = TBSTYLE_GROUP; +pub const BTNS_CHECKGROUP: ::DWORD = TBSTYLE_CHECKGROUP; +pub const BTNS_DROPDOWN: ::DWORD = TBSTYLE_DROPDOWN; +pub const BTNS_AUTOSIZE: ::DWORD = TBSTYLE_AUTOSIZE; +pub const BTNS_NOPREFIX: ::DWORD = TBSTYLE_NOPREFIX; +pub const BTNS_SHOWTEXT: ::DWORD = 0x0040; +pub const BTNS_WHOLEDROPDOWN: ::DWORD = 0x0080; +pub const TBSTYLE_EX_MIXEDBUTTONS: ::DWORD = 0x00000008; +pub const TBSTYLE_EX_HIDECLIPPEDBUTTONS: ::DWORD = 0x00000010; +pub const TBSTYLE_EX_MULTICOLUMN: ::DWORD = 0x00000002; +pub const TBSTYLE_EX_VERTICAL: ::DWORD = 0x00000004; +pub const TBSTYLE_EX_DOUBLEBUFFER: ::DWORD = 0x00000080; +STRUCT!{struct NMTBCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + hbrMonoDither: ::HBRUSH, + hbrLines: ::HBRUSH, + hpenLines: ::HPEN, + clrText: ::COLORREF, + clrMark: ::COLORREF, + clrTextHighlight: ::COLORREF, + clrBtnFace: ::COLORREF, + clrBtnHighlight: ::COLORREF, + clrHighlightHotTrack: ::COLORREF, + rcText: ::RECT, + nStringBkMode: ::c_int, + nHLStringBkMode: ::c_int, + iListGap: ::c_int, +}} +pub type LPNMTBCUSTOMDRAW = *mut NMTBCUSTOMDRAW; +pub const TBCDRF_NOEDGES: ::LRESULT = 0x00010000; +pub const TBCDRF_HILITEHOTTRACK: ::LRESULT = 0x00020000; +pub const TBCDRF_NOOFFSET: ::LRESULT = 0x00040000; +pub const TBCDRF_NOMARK: ::LRESULT = 0x00080000; +pub const TBCDRF_NOETCHEDEFFECT: ::LRESULT = 0x00100000; +pub const TBCDRF_BLENDICON: ::LRESULT = 0x00200000; +pub const TBCDRF_NOBACKGROUND: ::LRESULT = 0x00400000; +pub const TBCDRF_USECDCOLORS: ::LRESULT = 0x00800000; +pub const TB_ENABLEBUTTON: ::UINT = ::WM_USER + 1; +pub const TB_CHECKBUTTON: ::UINT = ::WM_USER + 2; +pub const TB_PRESSBUTTON: ::UINT = ::WM_USER + 3; +pub const TB_HIDEBUTTON: ::UINT = ::WM_USER + 4; +pub const TB_INDETERMINATE: ::UINT = ::WM_USER + 5; +pub const TB_MARKBUTTON: ::UINT = ::WM_USER + 6; +pub const TB_ISBUTTONENABLED: ::UINT = ::WM_USER + 9; +pub const TB_ISBUTTONCHECKED: ::UINT = ::WM_USER + 10; +pub const TB_ISBUTTONPRESSED: ::UINT = ::WM_USER + 11; +pub const TB_ISBUTTONHIDDEN: ::UINT = ::WM_USER + 12; +pub const TB_ISBUTTONINDETERMINATE : ::UINT = ::WM_USER + 13; +pub const TB_ISBUTTONHIGHLIGHTED: ::UINT = ::WM_USER + 14; +pub const TB_SETSTATE: ::UINT = ::WM_USER + 17; +pub const TB_GETSTATE: ::UINT = ::WM_USER + 18; +pub const TB_ADDBITMAP: ::UINT = ::WM_USER + 19; +STRUCT!{struct TBADDBITMAP { + hInst: ::HINSTANCE, + nID: ::UINT_PTR, +}} +pub type LPTBADDBITMAP = *mut TBADDBITMAP; +pub const HINST_COMMCTRL: ::HINSTANCE = (0 - 1) as ::HINSTANCE; +pub const IDB_STD_SMALL_COLOR: ::WPARAM = 0; +pub const IDB_STD_LARGE_COLOR: ::WPARAM = 1; +pub const IDB_VIEW_SMALL_COLOR: ::WPARAM = 4; +pub const IDB_VIEW_LARGE_COLOR: ::WPARAM = 5; +pub const IDB_HIST_SMALL_COLOR: ::WPARAM = 8; +pub const IDB_HIST_LARGE_COLOR: ::WPARAM = 9; +pub const IDB_HIST_NORMAL: ::WPARAM = 12; +pub const IDB_HIST_HOT: ::WPARAM = 13; +pub const IDB_HIST_DISABLED: ::WPARAM = 14; +pub const IDB_HIST_PRESSED: ::WPARAM = 15; +pub const STD_CUT: ::c_int = 0; +pub const STD_COPY: ::c_int = 1; +pub const STD_PASTE: ::c_int = 2; +pub const STD_UNDO: ::c_int = 3; +pub const STD_REDOW: ::c_int = 4; +pub const STD_DELETE: ::c_int = 5; +pub const STD_FILENEW: ::c_int = 6; +pub const STD_FILEOPEN: ::c_int = 7; +pub const STD_FILESAVE: ::c_int = 8; +pub const STD_PRINTPRE: ::c_int = 9; +pub const STD_PROPERTIES: ::c_int = 10; +pub const STD_HELP: ::c_int = 11; +pub const STD_FIND: ::c_int = 12; +pub const STD_REPLACE: ::c_int = 13; +pub const STD_PRINT: ::c_int = 14; +pub const VIEW_LARGEICONS: ::c_int = 0; +pub const VIEW_SMALLICONS: ::c_int = 1; +pub const VIEW_LIST: ::c_int = 2; +pub const VIEW_DETAILS: ::c_int = 3; +pub const VIEW_SORTNAME: ::c_int = 4; +pub const VIEW_SORTSIZE: ::c_int = 5; +pub const VIEW_SORTDATE: ::c_int = 6; +pub const VIEW_SORTTYPE: ::c_int = 7; +pub const VIEW_PARENTFOLDER: ::c_int = 8; +pub const VIEW_NETCONNECT: ::c_int = 9; +pub const VIEW_NETDISCONNECT: ::c_int = 10; +pub const VIEW_NEWFOLDER: ::c_int = 11; +pub const VIEW_VIEWMENU: ::c_int = 12; +pub const HIST_BACK: ::c_int = 0; +pub const HIST_FORWARD: ::c_int = 1; +pub const HIST_FAVORITES: ::c_int = 2; +pub const HIST_ADDTOFAVORITES: ::c_int = 3; +pub const HIST_VIEWTREE: ::c_int = 4; +pub const TB_ADDBUTTONSA: ::UINT = ::WM_USER + 20; +pub const TB_INSERTBUTTONA: ::UINT = ::WM_USER + 21; +pub const TB_DELETEBUTTON: ::UINT = ::WM_USER + 22; +pub const TB_GETBUTTON: ::UINT = ::WM_USER + 23; +pub const TB_BUTTONCOUNT: ::UINT = ::WM_USER + 24; +pub const TB_COMMANDTOINDEX: ::UINT = ::WM_USER + 25; +STRUCT!{struct TBSAVEPARAMSA { + hkr: ::HKEY, + pszSubKey: ::LPCSTR, + pszValueName: ::LPCSTR, +}} +pub type LPTBSAVEPARAMSA = *mut TBSAVEPARAMSA; +STRUCT!{struct TBSAVEPARAMSW { + hkr: ::HKEY, + pszSubKey: ::LPCWSTR, + pszValueName: ::LPCWSTR, +}} +pub type LPTBSAVEPARAMSW = *mut TBSAVEPARAMSW; +pub const TB_SAVERESTOREA: ::UINT = ::WM_USER + 26; +pub const TB_SAVERESTOREW: ::UINT = ::WM_USER + 76; +pub const TB_CUSTOMIZE: ::UINT = ::WM_USER + 27; +pub const TB_ADDSTRINGA: ::UINT = ::WM_USER + 28; +pub const TB_ADDSTRINGW: ::UINT = ::WM_USER + 77; +pub const TB_GETITEMRECT: ::UINT = ::WM_USER + 29; +pub const TB_BUTTONSTRUCTSIZE: ::UINT = ::WM_USER + 30; +pub const TB_SETBUTTONSIZE: ::UINT = ::WM_USER + 31; +pub const TB_SETBITMAPSIZE: ::UINT = ::WM_USER + 32; +pub const TB_AUTOSIZE: ::UINT = ::WM_USER + 33; +pub const TB_GETTOOLTIPS: ::UINT = ::WM_USER + 35; +pub const TB_SETTOOLTIPS: ::UINT = ::WM_USER + 36; +pub const TB_SETPARENT: ::UINT = ::WM_USER + 37; +pub const TB_SETROWS: ::UINT = ::WM_USER + 39; +pub const TB_GETROWS: ::UINT = ::WM_USER + 40; +pub const TB_SETCMDID: ::UINT = ::WM_USER + 42; +pub const TB_CHANGEBITMAP: ::UINT = ::WM_USER + 43; +pub const TB_GETBITMAP: ::UINT = ::WM_USER + 44; +pub const TB_GETBUTTONTEXTA: ::UINT = ::WM_USER + 45; +pub const TB_GETBUTTONTEXTW: ::UINT = ::WM_USER + 75; +pub const TB_REPLACEBITMAP: ::UINT = ::WM_USER + 46; +pub const TB_SETINDENT: ::UINT = ::WM_USER + 47; +pub const TB_SETIMAGELIST: ::UINT = ::WM_USER + 48; +pub const TB_GETIMAGELIST: ::UINT = ::WM_USER + 49; +pub const TB_LOADIMAGES: ::UINT = ::WM_USER + 50; +pub const TB_GETRECT: ::UINT = ::WM_USER + 51; +pub const TB_SETHOTIMAGELIST: ::UINT = ::WM_USER + 52; +pub const TB_GETHOTIMAGELIST: ::UINT = ::WM_USER + 53; +pub const TB_SETDISABLEDIMAGELIST: ::UINT = ::WM_USER + 54; +pub const TB_GETDISABLEDIMAGELIST: ::UINT = ::WM_USER + 55; +pub const TB_SETSTYLE: ::UINT = ::WM_USER + 56; +pub const TB_GETSTYLE: ::UINT = ::WM_USER + 57; +pub const TB_GETBUTTONSIZE: ::UINT = ::WM_USER + 58; +pub const TB_SETBUTTONWIDTH: ::UINT = ::WM_USER + 59; +pub const TB_SETMAXTEXTROWS: ::UINT = ::WM_USER + 60; +pub const TB_GETTEXTROWS: ::UINT = ::WM_USER + 61; +pub const TB_GETOBJECT: ::UINT = ::WM_USER + 62; +pub const TB_GETHOTITEM: ::UINT = ::WM_USER + 71; +pub const TB_SETHOTITEM: ::UINT = ::WM_USER + 72; +pub const TB_SETANCHORHIGHLIGHT: ::UINT = ::WM_USER + 73; +pub const TB_GETANCHORHIGHLIGHT: ::UINT = ::WM_USER + 74; +pub const TB_MAPACCELERATORA: ::UINT = ::WM_USER + 78; +STRUCT!{struct TBINSERTMARK { + iButton: ::c_int, + dwFlags: ::DWORD, +}} +pub type LPTBINSERTMARK = *mut TBINSERTMARK; +pub const TBIMHT_AFTER: ::DWORD = 0x00000001; +pub const TBIMHT_BACKGROUND: ::DWORD = 0x00000002; +pub const TB_GETINSERTMARK: ::UINT = ::WM_USER + 79; +pub const TB_SETINSERTMARK: ::UINT = ::WM_USER + 80; +pub const TB_INSERTMARKHITTEST: ::UINT = ::WM_USER + 81; +pub const TB_MOVEBUTTON: ::UINT = ::WM_USER + 82; +pub const TB_GETMAXSIZE: ::UINT = ::WM_USER + 83; +pub const TB_SETEXTENDEDSTYLE: ::UINT = ::WM_USER + 84; +pub const TB_GETEXTENDEDSTYLE: ::UINT = ::WM_USER + 85; +pub const TB_GETPADDING: ::UINT = ::WM_USER + 86; +pub const TB_SETPADDING: ::UINT = ::WM_USER + 87; +pub const TB_SETINSERTMARKCOLOR: ::UINT = ::WM_USER + 88; +pub const TB_GETINSERTMARKCOLOR: ::UINT = ::WM_USER + 89; +pub const TB_SETCOLORSCHEME: ::UINT = CCM_SETCOLORSCHEME; +pub const TB_GETCOLORSCHEME: ::UINT = CCM_GETCOLORSCHEME; +pub const TB_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TB_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TB_MAPACCELERATORW: ::UINT = ::WM_USER + 90; +STRUCT!{struct TBREPLACEBITMAP { + hInstOld: ::HINSTANCE, + nIDOld: ::UINT_PTR, + hInstNew: ::HINSTANCE, + nIDNew: ::UINT_PTR, + nButtons: ::c_int, +}} +pub type LPTBREPLACEBITMAP = *mut TBREPLACEBITMAP; +pub const TBBF_LARGE: ::DWORD = 0x0001; +pub const TB_GETBITMAPFLAGS: ::UINT = ::WM_USER + 41; +pub const TBIF_IMAGE: ::DWORD = 0x00000001; +pub const TBIF_TEXT: ::DWORD = 0x00000002; +pub const TBIF_STATE: ::DWORD = 0x00000004; +pub const TBIF_STYLE: ::DWORD = 0x00000008; +pub const TBIF_LPARAM: ::DWORD = 0x00000010; +pub const TBIF_COMMAND: ::DWORD = 0x00000020; +pub const TBIF_SIZE: ::DWORD = 0x00000040; +pub const TBIF_BYINDEX: ::DWORD = 0x80000000; +STRUCT!{struct TBBUTTONINFOA { + cbSize: ::UINT, + dwMask: ::DWORD, + idCommand: ::c_int, + iImage: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + cx: ::WORD, + lParam: ::DWORD_PTR, + pszText: ::LPSTR, + cchText: ::c_int, +}} +pub type LPTBBUTTONINFOA = *mut TBBUTTONINFOA; +STRUCT!{struct TBBUTTONINFOW { + cbSize: ::UINT, + dwMask: ::DWORD, + idCommand: ::c_int, + iImage: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + cx: ::WORD, + lParam: ::DWORD_PTR, + pszText: ::LPWSTR, + cchText: ::c_int, +}} +pub type LPTBBUTTONINFOW = *mut TBBUTTONINFOW; +pub const TB_GETBUTTONINFOW: ::UINT = ::WM_USER + 63; +pub const TB_SETBUTTONINFOW: ::UINT = ::WM_USER + 64; +pub const TB_GETBUTTONINFOA: ::UINT = ::WM_USER + 65; +pub const TB_SETBUTTONINFOA: ::UINT = ::WM_USER + 66; +pub const TB_INSERTBUTTONW: ::UINT = ::WM_USER + 67; +pub const TB_ADDBUTTONSW: ::UINT = ::WM_USER + 68; +pub const TB_HITTEST: ::UINT = ::WM_USER + 69; +pub const TB_SETDRAWTEXTFLAGS: ::UINT = ::WM_USER + 70; +pub const TB_GETSTRINGW: ::UINT = ::WM_USER + 91; +pub const TB_GETSTRINGA: ::UINT = ::WM_USER + 92; +pub const TB_SETBOUNDINGSIZE: ::UINT = ::WM_USER + 93; +pub const TB_SETHOTITEM2: ::UINT = ::WM_USER + 94; +pub const TB_HASACCELERATOR: ::UINT = ::WM_USER + 95; +pub const TB_SETLISTGAP: ::UINT = ::WM_USER + 96; +pub const TB_GETIMAGELISTCOUNT: ::UINT = ::WM_USER + 98; +pub const TB_GETIDEALSIZE: ::UINT = ::WM_USER + 99; +pub const TBMF_PAD: ::DWORD = 0x00000001; +pub const TBMF_BARPAD: ::DWORD = 0x00000002; +pub const TBMF_BUTTONSPACING: ::DWORD = 0x00000004; +STRUCT!{struct TBMETRICS { + cbSize: ::UINT, + dwMask: ::DWORD, + cxPad: ::c_int, + cyPad: ::c_int, + cxBarPad: ::c_int, + cyBarPad: ::c_int, + cxButtonSpacing: ::c_int, + cyButtonSpacing: ::c_int, +}} +pub type LPTBMETRICS = *mut TBMETRICS; +pub const TB_GETMETRICS: ::UINT = ::WM_USER + 101; +pub const TB_SETMETRICS: ::UINT = ::WM_USER + 102; +pub const TB_GETITEMDROPDOWNRECT: ::UINT = ::WM_USER + 103; +pub const TB_SETPRESSEDIMAGELIST: ::UINT = ::WM_USER + 104; +pub const TB_GETPRESSEDIMAGELIST: ::UINT = ::WM_USER + 105; +pub const TB_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub const TBN_GETBUTTONINFOA: ::UINT = TBN_FIRST - 0; +pub const TBN_BEGINDRAG: ::UINT = TBN_FIRST - 1; +pub const TBN_ENDDRAG: ::UINT = TBN_FIRST - 2; +pub const TBN_BEGINADJUST: ::UINT = TBN_FIRST - 3; +pub const TBN_ENDADJUST: ::UINT = TBN_FIRST - 4; +pub const TBN_RESET: ::UINT = TBN_FIRST - 5; +pub const TBN_QUERYINSERT: ::UINT = TBN_FIRST - 6; +pub const TBN_QUERYDELETE: ::UINT = TBN_FIRST - 7; +pub const TBN_TOOLBARCHANGE: ::UINT = TBN_FIRST - 8; +pub const TBN_CUSTHELP: ::UINT = TBN_FIRST - 9; +pub const TBN_DROPDOWN: ::UINT = TBN_FIRST - 10; +pub const TBN_GETOBJECT: ::UINT = TBN_FIRST - 12; +STRUCT!{struct NMTBHOTITEM { + hdr: ::NMHDR, + idOld: ::c_int, + idNew: ::c_int, + dwFlags: ::DWORD, +}} +pub type LPNMTBHOTITEM = *mut NMTBHOTITEM; +pub const HICF_OTHER: ::DWORD = 0x00000000; +pub const HICF_MOUSE: ::DWORD = 0x00000001; +pub const HICF_ARROWKEYS: ::DWORD = 0x00000002; +pub const HICF_ACCELERATOR: ::DWORD = 0x00000004; +pub const HICF_DUPACCEL: ::DWORD = 0x00000008; +pub const HICF_ENTERING: ::DWORD = 0x00000010; +pub const HICF_LEAVING: ::DWORD = 0x00000020; +pub const HICF_RESELECT: ::DWORD = 0x00000040; +pub const HICF_LMOUSE: ::DWORD = 0x00000080; +pub const HICF_TOGGLEDROPDOWN: ::DWORD = 0x00000100; +pub const TBN_HOTITEMCHANGE: ::UINT = TBN_FIRST - 13; +pub const TBN_DRAGOUT: ::UINT = TBN_FIRST - 14; +pub const TBN_DELETINGBUTTON: ::UINT = TBN_FIRST - 15; +pub const TBN_GETDISPINFOA: ::UINT = TBN_FIRST - 16; +pub const TBN_GETDISPINFOW: ::UINT = TBN_FIRST - 17; +pub const TBN_GETINFOTIPA: ::UINT = TBN_FIRST - 18; +pub const TBN_GETINFOTIPW: ::UINT = TBN_FIRST - 19; +pub const TBN_GETBUTTONINFOW: ::UINT = TBN_FIRST - 20; +pub const TBN_RESTORE: ::UINT = TBN_FIRST - 21; +pub const TBN_SAVE: ::UINT = TBN_FIRST - 22; +pub const TBN_INITCUSTOMIZE: ::UINT = TBN_FIRST - 23; +pub const TBN_WRAPHOTITEM: ::UINT = TBN_FIRST - 24; +pub const TBN_DUPACCELERATOR: ::UINT = TBN_FIRST - 25; +pub const TBN_WRAPACCELERATOR: ::UINT = TBN_FIRST - 26; +pub const TBN_DRAGOVER: ::UINT = TBN_FIRST - 27; +pub const TBN_MAPACCELERATOR: ::UINT = TBN_FIRST - 28; +pub const TBNRF_HIDEHELP: ::LRESULT = 0x00000001; +pub const TBNRF_ENDCUSTOMIZE: ::LRESULT = 0x00000002; +STRUCT!{struct NMTBSAVE { + hdr: ::NMHDR, + pData: *mut ::DWORD, + pCurrent: *mut ::DWORD, + cbData: ::UINT, + iItem: ::c_int, + cButtons: ::c_int, + tbButton: TBBUTTON, +}} +pub type LPNMTBSAVE = *mut NMTBSAVE; +STRUCT!{struct NMTBRESTORE { + hdr: ::NMHDR, + pData: *mut ::DWORD, + pCurrent: *mut ::DWORD, + cbData: ::UINT, + iItem: ::c_int, + cButtons: ::c_int, + cbBytesPerRecord: ::c_int, + tbButton: TBBUTTON, +}} +pub type LPNMTBRESTORE = *mut NMTBRESTORE; +STRUCT!{struct NMTBGETINFOTIPA { + hdr: ::NMHDR, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + lParal: ::LPARAM, +}} +pub type LPNMTBGETINFOTIPA = *mut NMTBGETINFOTIPA; +STRUCT!{struct NMTBGETINFOTIPW { + hdr: ::NMHDR, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + lParal: ::LPARAM, +}} +pub type LPNMTBGETINFOTIPW = *mut NMTBGETINFOTIPW; +pub const TBNF_IMAGE: ::DWORD = 0x00000001; +pub const TBNF_TEXT: ::DWORD = 0x00000002; +pub const TBNF_DI_SETITEM: ::DWORD = 0x10000000; +STRUCT!{struct NMTBDISPINFOA { + hdr: ::NMHDR, + dwMask: ::DWORD, + idCommand: ::c_int, + lParam: ::DWORD_PTR, + iImage: ::c_int, + pszText: ::LPSTR, + cchText: ::c_int, +}} +pub type LPNMTBDISPINFOA = *mut NMTBDISPINFOA; +STRUCT!{struct NMTBDISPINFOW { + hdr: ::NMHDR, + dwMask: ::DWORD, + idCommand: ::c_int, + lParam: ::DWORD_PTR, + iImage: ::c_int, + pszText: ::LPWSTR, + cchText: ::c_int, +}} +pub type LPNMTBDISPINFOW = *mut NMTBDISPINFOW; +pub const TBDDRET_DEFAULT: ::LRESULT = 0; +pub const TBDDRET_NODEFAULT: ::LRESULT = 1; +pub const TBDDRET_TREATPRESSED: ::LRESULT = 2; +pub type TBNOTIFYA = NMTOOLBARA; +pub type TBNOTIFYW = NMTOOLBARW; +pub type LPTBNOTIFYA = LPNMTOOLBARA; +pub type LPTBNOTIFYW = LPNMTOOLBARW; +STRUCT!{struct NMTOOLBARA { + hdr: ::NMHDR, + iItem: ::c_int, + tbButton: TBBUTTON, + cchText: ::c_int, + pszText: ::LPSTR, + rcButton: ::RECT, +}} +pub type LPNMTOOLBARA = *mut NMTOOLBARA; +STRUCT!{struct NMTOOLBARW { + hdr: ::NMHDR, + iItem: ::c_int, + tbButton: TBBUTTON, + cchText: ::c_int, + pszText: ::LPWSTR, + rcButton: ::RECT, +}} +pub type LPNMTOOLBARW = *mut NMTOOLBARW; +pub const RBIM_IMAGELIST: ::UINT = 0x00000001; +pub const RBS_TOOLTIPS: ::DWORD = 0x00000100; +pub const RBS_VARHEIGHT: ::DWORD = 0x00000200; +pub const RBS_BANDBORDERS: ::DWORD = 0x00000400; +pub const RBS_FIXEDORDER: ::DWORD = 0x00000800; +pub const RBS_REGISTERDROP: ::DWORD = 0x00001000; +pub const RBS_AUTOSIZE: ::DWORD = 0x00002000; +pub const RBS_VERTICALGRIPPER: ::DWORD = 0x00004000; +pub const RBS_DBLCLKTOGGLE: ::DWORD = 0x00008000; +STRUCT!{struct REBARINFO { + cbSize: ::UINT, + fMask: ::UINT, + himl: HIMAGELIST, +}} +pub type LPREBARINFO = *mut REBARINFO; +pub const RBBS_BREAK: ::UINT = 0x00000001; +pub const RBBS_FIXEDSIZE: ::UINT = 0x00000002; +pub const RBBS_CHILDEDGE: ::UINT = 0x00000004; +pub const RBBS_HIDDEN: ::UINT = 0x00000008; +pub const RBBS_NOVERT: ::UINT = 0x00000010; +pub const RBBS_FIXEDBMP: ::UINT = 0x00000020; +pub const RBBS_VARIABLEHEIGHT: ::UINT = 0x00000040; +pub const RBBS_GRIPPERALWAYS: ::UINT = 0x00000080; +pub const RBBS_NOGRIPPER: ::UINT = 0x00000100; +pub const RBBS_USECHEVRON: ::UINT = 0x00000200; +pub const RBBS_HIDETITLE: ::UINT = 0x00000400; +pub const RBBS_TOPALIGN: ::UINT = 0x00000800; +pub const RBBIM_STYLE: ::UINT = 0x00000001; +pub const RBBIM_COLORS: ::UINT = 0x00000002; +pub const RBBIM_TEXT: ::UINT = 0x00000004; +pub const RBBIM_IMAGE: ::UINT = 0x00000008; +pub const RBBIM_CHILD: ::UINT = 0x00000010; +pub const RBBIM_CHILDSIZE: ::UINT = 0x00000020; +pub const RBBIM_SIZE: ::UINT = 0x00000040; +pub const RBBIM_BACKGROUND: ::UINT = 0x00000080; +pub const RBBIM_ID: ::UINT = 0x00000100; +pub const RBBIM_IDEALSIZE: ::UINT = 0x00000200; +pub const RBBIM_LPARAM: ::UINT = 0x00000400; +pub const RBBIM_HEADERSIZE: ::UINT = 0x00000800; +pub const RBBIM_CHEVRONLOCATION: ::UINT = 0x00001000; +pub const RBBIM_CHEVRONSTATE: ::UINT = 0x00002000; +STRUCT!{struct REBARBANDINFOA { + cbSize: ::UINT, + fMask: ::UINT, + fStyle: ::UINT, + clrFore: ::COLORREF, + clrBack: ::COLORREF, + lpText: ::LPSTR, + cch: ::UINT, + iImage: ::c_int, + hwndChild: ::HWND, + cxMinChild: ::UINT, + cyMinChild: ::UINT, + cx: ::UINT, + hbmBack: ::HBITMAP, + wID: ::UINT, + cyChild: ::UINT, + cyMaxChild: ::UINT, + cyIntegral: ::UINT, + cxIdeal: ::UINT, + lParam: ::LPARAM, + cxHeader: ::UINT, + rcChevronLocation: ::RECT, + uChevronState: ::UINT, +}} +pub type LPREBARBANDINFOA = *mut REBARBANDINFOA; +pub type LPCREBARBANDINFOA = *const REBARBANDINFOA; +STRUCT!{struct REBARBANDINFOW { + cbSize: ::UINT, + fMask: ::UINT, + fStyle: ::UINT, + clrFore: ::COLORREF, + clrBack: ::COLORREF, + lpText: ::LPWSTR, + cch: ::UINT, + iImage: ::c_int, + hwndChild: ::HWND, + cxMinChild: ::UINT, + cyMinChild: ::UINT, + cx: ::UINT, + hbmBack: ::HBITMAP, + wID: ::UINT, + cyChild: ::UINT, + cyMaxChild: ::UINT, + cyIntegral: ::UINT, + cxIdeal: ::UINT, + lParam: ::LPARAM, + cxHeader: ::UINT, + rcChevronLocation: ::RECT, + uChevronState: ::UINT, +}} +pub type LPREBARBANDINFOW = *mut REBARBANDINFOW; +pub type LPCREBARBANDINFOW = *const REBARBANDINFOW; +pub const RB_INSERTBANDA: ::UINT = ::WM_USER + 1; +pub const RB_DELETEBAND: ::UINT = ::WM_USER + 2; +pub const RB_GETBARINFO: ::UINT = ::WM_USER + 3; +pub const RB_SETBARINFO: ::UINT = ::WM_USER + 4; +pub const RB_SETBANDINFOA: ::UINT = ::WM_USER + 6; +pub const RB_SETPARENT: ::UINT = ::WM_USER + 7; +pub const RB_HITTEST: ::UINT = ::WM_USER + 8; +pub const RB_GETRECT: ::UINT = ::WM_USER + 9; +pub const RB_INSERTBANDW: ::UINT = ::WM_USER + 10; +pub const RB_SETBANDINFOW: ::UINT = ::WM_USER + 11; +pub const RB_GETBANDCOUNT: ::UINT = ::WM_USER + 12; +pub const RB_GETROWCOUNT: ::UINT = ::WM_USER + 13; +pub const RB_GETROWHEIGHT: ::UINT = ::WM_USER + 14; +pub const RB_IDTOINDEX: ::UINT = ::WM_USER + 16; +pub const RB_GETTOOLTIPS: ::UINT = ::WM_USER + 17; +pub const RB_SETTOOLTIPS: ::UINT = ::WM_USER + 18; +pub const RB_SETBKCOLOR: ::UINT = ::WM_USER + 19; +pub const RB_GETBKCOLOR: ::UINT = ::WM_USER + 20; +pub const RB_SETTEXTCOLOR: ::UINT = ::WM_USER + 21; +pub const RB_GETTEXTCOLOR: ::UINT = ::WM_USER + 22; +pub const RBSTR_CHANGERECT: ::WPARAM = 0x0001; +pub const RB_SIZETORECT: ::UINT = ::WM_USER + 23; +pub const RB_SETCOLORSCHEME: ::UINT = CCM_SETCOLORSCHEME; +pub const RB_GETCOLORSCHEME: ::UINT = CCM_GETCOLORSCHEME; +pub const RB_BEGINDRAG: ::UINT = ::WM_USER + 24; +pub const RB_ENDDRAG: ::UINT = ::WM_USER + 25; +pub const RB_DRAGMOVE: ::UINT = ::WM_USER + 26; +pub const RB_GETBARHEIGHT: ::UINT = ::WM_USER + 27; +pub const RB_GETBANDINFOW: ::UINT = ::WM_USER + 28; +pub const RB_GETBANDINFOA: ::UINT = ::WM_USER + 29; +pub const RB_MINIMIZEBAND: ::UINT = ::WM_USER + 30; +pub const RB_MAXIMIZEBAND: ::UINT = ::WM_USER + 31; +pub const RB_GETDROPTARGET: ::UINT = CCM_GETDROPTARGET; +pub const RB_GETBANDBORDERS: ::UINT = ::WM_USER + 34; +pub const RB_SHOWBAND: ::UINT = ::WM_USER + 35; +pub const RB_SETPALETTE: ::UINT = ::WM_USER + 37; +pub const RB_GETPALETTE: ::UINT = ::WM_USER + 38; +pub const RB_MOVEBAND: ::UINT = ::WM_USER + 39; +pub const RB_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const RB_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const RB_GETBANDMARGINS: ::UINT = ::WM_USER + 40; +pub const RB_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub const RB_SETEXTENDEDSTYLE: ::UINT = ::WM_USER + 41; +pub const RB_GETEXTENDEDSTYLE: ::UINT = ::WM_USER + 42; +pub const RB_PUSHCHEVRON: ::UINT = ::WM_USER + 43; +pub const RB_SETBANDWIDTH: ::UINT = ::WM_USER + 44; +pub const RBN_HEIGHTCHANGE: ::UINT = RBN_FIRST - 0; +pub const RBN_GETOBJECT: ::UINT = RBN_FIRST - 1; +pub const RBN_LAYOUTCHANGED: ::UINT = RBN_FIRST - 2; +pub const RBN_AUTOSIZE: ::UINT = RBN_FIRST - 3; +pub const RBN_BEGINDRAG: ::UINT = RBN_FIRST - 4; +pub const RBN_ENDDRAG: ::UINT = RBN_FIRST - 5; +pub const RBN_DELETINGBAND: ::UINT = RBN_FIRST - 6; +pub const RBN_DELETEDBAND: ::UINT = RBN_FIRST - 7; +pub const RBN_CHILDSIZE: ::UINT = RBN_FIRST - 8; +pub const RBN_CHEVRONPUSHED: ::UINT = RBN_FIRST - 10; +pub const RBN_SPLITTERDRAG: ::UINT = RBN_FIRST - 11; +pub const RBN_MINMAX: ::UINT = RBN_FIRST - 21; +pub const RBN_AUTOBREAK: ::UINT = RBN_FIRST - 22; +STRUCT!{struct NMREBARCHILDSIZE { + hdr: ::NMHDR, + uBand: ::UINT, + wID: ::UINT, + rcChild: ::RECT, + rcBand: ::RECT, +}} +pub type LPNMREBARCHILDSIZE = *mut NMREBARCHILDSIZE; +STRUCT!{struct NMREBAR { + hdr: ::NMHDR, + dwMask: ::DWORD, + uBand: ::UINT, + fStyle: ::UINT, + wID: ::UINT, + lParam: ::LPARAM, +}} +pub type LPNMREBAR = *mut NMREBAR; +pub const RBNM_ID: ::DWORD = 0x00000001; +pub const RBNM_STYLE: ::DWORD = 0x00000002; +pub const RBNM_LPARAM: ::DWORD = 0x00000004; +STRUCT!{struct NMRBAUTOSIZE { + hdr: ::NMHDR, + fChanged: ::BOOL, + rcTarget: ::RECT, + rcActual: ::RECT, +}} +pub type LPNMRBAUTOSIZE = *mut NMRBAUTOSIZE; +STRUCT!{struct NMREBARCHEVRON { + hdr: ::NMHDR, + uBand: ::UINT, + wID: ::UINT, + lParam: ::LPARAM, + rc: ::RECT, + lParamNM: ::LPARAM, +}} +pub type LPNMREBARCHEVRON = *mut NMREBARCHEVRON; +STRUCT!{struct NMREBARSPLITTER { + hdr: ::NMHDR, + rcSizing: ::RECT, +}} +pub type LPNMREBARSPLITTER = *mut NMREBARSPLITTER; +pub const RBAB_AUTOSIZE: ::UINT = 0x0001; +pub const RBAB_ADDBAND: ::UINT = 0x0002; +STRUCT!{struct NMREBARAUTOBREAK { + hdr: ::NMHDR, + uBand: ::UINT, + wID: ::UINT, + lParam: ::LPARAM, + uMsg: ::UINT, + fStyleCurrent: ::UINT, + fAutoBreak: ::UINT, +}} +pub type LPNMREBARAUTOBREAK = *mut NMREBARAUTOBREAK; +pub const RBHT_NOWHERE: ::UINT = 0x0001; +pub const RBHT_CAPTION: ::UINT = 0x0002; +pub const RBHT_CLIENT: ::UINT = 0x0003; +pub const RBHT_GRABBER: ::UINT = 0x0004; +pub const RBHT_CHEVRON: ::UINT = 0x0008; +pub const RBHT_SPLITTER: ::UINT = 0x0010; +STRUCT!{struct RBHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + iBand: ::c_int, +}} +pub type LPRBHITTESTINFO = *mut RBHITTESTINFO; +pub type LPTOOLINFOA = LPTTTOOLINFOA; +pub type LPTOOLINFOW = LPTTTOOLINFOW; +pub type TOOLINFOA = TTTOOLINFOA; +pub type TOOLINFOW = TTTOOLINFOW; +STRUCT!{struct TTTOOLINFOA { + cbSize: ::UINT, + uFlags: ::UINT, + hwnd: ::HWND, + uId: ::UINT_PTR, + rect: ::RECT, + hinst: ::HINSTANCE, + lpszText: ::LPSTR, + lParam: ::LPARAM, + lpReserved: *mut ::c_void, +}} +pub type PTTTOOLINFOA = *mut TTTOOLINFOA; +pub type LPTTTOOLINFOA = *mut TTTOOLINFOA; +STRUCT!{struct TTTOOLINFOW { + cbSize: ::UINT, + uFlags: ::UINT, + hwnd: ::HWND, + uId: ::UINT_PTR, + rect: ::RECT, + hinst: ::HINSTANCE, + lpszText: ::LPSTR, + lParam: ::LPARAM, + lpReserved: *mut ::c_void, +}} +pub type PTTTOOLINFOW = *mut TTTOOLINFOW; +pub type LPTTTOOLINFOW = *mut TTTOOLINFOW; +pub const TTS_ALWAYSTIP: ::DWORD = 0x01; +pub const TTS_NOPREFIX: ::DWORD = 0x02; +pub const TTS_NOANIMATE: ::DWORD = 0x10; +pub const TTS_NOFADE: ::DWORD = 0x20; +pub const TTS_BALLOON: ::DWORD = 0x40; +pub const TTS_CLOSE: ::DWORD = 0x80; +pub const TTS_USEVISUALSTYLE: ::DWORD = 0x100; +pub const TTF_IDISHWND: ::UINT = 0x0001; +pub const TTF_CENTERTIP: ::UINT = 0x0002; +pub const TTF_RTLREADING: ::UINT = 0x0004; +pub const TTF_SUBCLASS: ::UINT = 0x0010; +pub const TTF_TRACK: ::UINT = 0x0020; +pub const TTF_ABSOLUTE: ::UINT = 0x0080; +pub const TTF_TRANSPARENT: ::UINT = 0x0100; +pub const TTF_PARSELINKS: ::UINT = 0x1000; +pub const TTF_DI_SETITEM: ::UINT = 0x8000; +pub const TTDT_AUTOMATIC: ::WPARAM = 0; +pub const TTDT_RESHOW: ::WPARAM = 1; +pub const TTDT_AUTOPOP: ::WPARAM = 2; +pub const TTDT_INITIAL: ::WPARAM = 3; +pub const TTI_NONE: ::WPARAM = 0; +pub const TTI_INFO: ::WPARAM = 1; +pub const TTI_WARNING: ::WPARAM = 2; +pub const TTI_ERROR: ::WPARAM = 3; +pub const TTI_INFO_LARGE: ::WPARAM = 4; +pub const TTI_WARNING_LARGE: ::WPARAM = 5; +pub const TTI_ERROR_LARGE: ::WPARAM = 6; +pub const TTM_ACTIVATE: ::UINT = ::WM_USER + 1; +pub const TTM_SETDELAYTIME: ::UINT = ::WM_USER + 3; +pub const TTM_ADDTOOLA: ::UINT = ::WM_USER + 4; +pub const TTM_ADDTOOLW: ::UINT = ::WM_USER + 50; +pub const TTM_DELTOOLA: ::UINT = ::WM_USER + 5; +pub const TTM_DELTOOLW: ::UINT = ::WM_USER + 51; +pub const TTM_NEWTOOLRECTA: ::UINT = ::WM_USER + 6; +pub const TTM_NEWTOOLRECTW: ::UINT = ::WM_USER + 52; +pub const TTM_RELAYEVENT: ::UINT = ::WM_USER + 7; +pub const TTM_GETTOOLINFOA: ::UINT = ::WM_USER + 8; +pub const TTM_GETTOOLINFOW: ::UINT = ::WM_USER + 53; +pub const TTM_SETTOOLINFOA: ::UINT = ::WM_USER + 9; +pub const TTM_SETTOOLINFOW: ::UINT = ::WM_USER + 54; +pub const TTM_HITTESTA: ::UINT = ::WM_USER + 10; +pub const TTM_HITTESTW: ::UINT = ::WM_USER + 55; +pub const TTM_GETTEXTA: ::UINT = ::WM_USER + 11; +pub const TTM_GETTEXTW: ::UINT = ::WM_USER + 56; +pub const TTM_UPDATETIPTEXTA: ::UINT = ::WM_USER + 12; +pub const TTM_UPDATETIPTEXTW: ::UINT = ::WM_USER + 57; +pub const TTM_GETTOOLCOUNT: ::UINT = ::WM_USER + 13; +pub const TTM_ENUMTOOLSA: ::UINT = ::WM_USER + 14; +pub const TTM_ENUMTOOLSW: ::UINT = ::WM_USER + 58; +pub const TTM_GETCURRENTTOOLA: ::UINT = ::WM_USER + 15; +pub const TTM_GETCURRENTTOOLW: ::UINT = ::WM_USER + 59; +pub const TTM_WINDOWFROMPOINT: ::UINT = ::WM_USER + 16; +pub const TTM_TRACKACTIVATE: ::UINT = ::WM_USER + 17; +pub const TTM_TRACKPOSITION: ::UINT = ::WM_USER + 18; +pub const TTM_SETTIPBKCOLOR: ::UINT = ::WM_USER + 19; +pub const TTM_SETTIPTEXTCOLOR: ::UINT = ::WM_USER + 20; +pub const TTM_GETDELAYTIME: ::UINT = ::WM_USER + 21; +pub const TTM_GETTIPBKCOLOR: ::UINT = ::WM_USER + 22; +pub const TTM_GETTIPTEXTCOLOR: ::UINT = ::WM_USER + 23; +pub const TTM_SETMAXTIPWIDTH: ::UINT = ::WM_USER + 24; +pub const TTM_GETMAXTIPWIDTH: ::UINT = ::WM_USER + 25; +pub const TTM_SETMARGIN: ::UINT = ::WM_USER + 26; +pub const TTM_GETMARGIN: ::UINT = ::WM_USER + 27; +pub const TTM_POP: ::UINT = ::WM_USER + 28; +pub const TTM_UPDATE: ::UINT = ::WM_USER + 29; +pub const TTM_GETBUBBLESIZE: ::UINT = ::WM_USER + 30; +pub const TTM_ADJUSTRECT: ::UINT = ::WM_USER + 31; +pub const TTM_SETTITLEA: ::UINT = ::WM_USER + 32; +pub const TTM_SETTITLEW: ::UINT = ::WM_USER + 33; +pub const TTM_POPUP: ::UINT = ::WM_USER + 34; +pub const TTM_GETTITLE: ::UINT = ::WM_USER + 35; +STRUCT!{struct TTGETTITLE { + dwSize: ::DWORD, + uTitleBitmap: ::UINT, + cch: ::UINT, + pszTitle: *mut ::WCHAR, +}} +pub type LPTTGETTITLE = *mut TTGETTITLE; +pub const TTM_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub type LPHITTESTINFOW = LPTTHITTESTINFOW; +pub type LPHITTESTINFOA = LPTTHITTESTINFOA; +STRUCT!{struct TTHITTESTINFOA { + hwnd: ::HWND, + pt: ::POINT, + ti: TTTOOLINFOA, +}} +pub type LPTTHITTESTINFOA = *mut TTHITTESTINFOA; +STRUCT!{struct TTHITTESTINFOW { + hwnd: ::HWND, + pt: ::POINT, + ti: TTTOOLINFOW, +}} +pub type LPTTHITTESTINFOW = *mut TTHITTESTINFOW; +pub const TTN_GETDISPINFOA: ::UINT = TTN_FIRST - 0; +pub const TTN_GETDISPINFOW: ::UINT = TTN_FIRST - 10; +pub const TTN_SHOW: ::UINT = TTN_FIRST - 1; +pub const TTN_POP: ::UINT = TTN_FIRST - 2; +pub const TTN_LINKCLICK: ::UINT = TTN_FIRST - 3; +pub const TTN_NEEDTEXTA: ::UINT = TTN_GETDISPINFOA; +pub const TTN_NEEDTEXTW: ::UINT = TTN_GETDISPINFOW; +pub type TOOLTIPTEXTW = NMTTDISPINFOW; +pub type TOOLTIPTEXTA = NMTTDISPINFOA; +pub type LPTOOLTIPTEXTA = LPNMTTDISPINFOA; +pub type LPTOOLTIPTEXTW = LPNMTTDISPINFOW; +STRUCT!{nodebug struct NMTTDISPINFOA { + hdr: ::NMHDR, + lpszText: ::LPSTR, + szText: [::c_char; 80], + hinst: ::HINSTANCE, + uFlags: ::UINT, + lParam: ::LPARAM, +}} +pub type LPNMTTDISPINFOA = *mut NMTTDISPINFOA; +STRUCT!{nodebug struct NMTTDISPINFOW { + hdr: ::NMHDR, + lpszText: ::LPWSTR, + szText: [::WCHAR; 80], + hinst: ::HINSTANCE, + uFlags: ::UINT, + lParam: ::LPARAM, +}} +pub type LPNMTTDISPINFOW = *mut NMTTDISPINFOW; +pub const SBARS_SIZEGRIP: ::DWORD = 0x0100; +pub const SBARS_TOOLTIPS: ::DWORD = 0x0800; +pub const SBT_TOOLTIPS: ::DWORD = 0x0800; +pub const SB_SETTEXTA: ::UINT = ::WM_USER + 1; +pub const SB_SETTEXTW: ::UINT = ::WM_USER + 11; +pub const SB_GETTEXTA: ::UINT = ::WM_USER + 2; +pub const SB_GETTEXTW: ::UINT = ::WM_USER + 13; +pub const SB_GETTEXTLENGTHA: ::UINT = ::WM_USER + 3; +pub const SB_GETTEXTLENGTHW: ::UINT = ::WM_USER + 12; +pub const SB_SETPARTS: ::UINT = ::WM_USER + 4; +pub const SB_GETPARTS: ::UINT = ::WM_USER + 6; +pub const SB_GETBORDERS: ::UINT = ::WM_USER + 7; +pub const SB_SETMINHEIGHT: ::UINT = ::WM_USER + 8; +pub const SB_SIMPLE: ::UINT = ::WM_USER + 9; +pub const SB_GETRECT: ::UINT = ::WM_USER + 10; +pub const SB_ISSIMPLE: ::UINT = ::WM_USER + 14; +pub const SB_SETICON: ::UINT = ::WM_USER + 15; +pub const SB_SETTIPTEXTA: ::UINT = ::WM_USER + 16; +pub const SB_SETTIPTEXTW: ::UINT = ::WM_USER + 17; +pub const SB_GETTIPTEXTA: ::UINT = ::WM_USER + 18; +pub const SB_GETTIPTEXTW: ::UINT = ::WM_USER + 19; +pub const SB_GETICON: ::UINT = ::WM_USER + 20; +pub const SB_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const SB_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const SBT_OWNERDRAW: ::WPARAM = 0x1000; +pub const SBT_NOBORDERS: ::WPARAM = 0x0100; +pub const SBT_POPOUT: ::WPARAM = 0x0200; +pub const SBT_RTLREADING: ::WPARAM = 0x0400; +pub const SBT_NOTABPARSING: ::WPARAM = 0x0800; +pub const SB_SETBKCOLOR: ::UINT = CCM_SETBKCOLOR; +pub const SBN_SIMPLEMODECHANGE: ::UINT = SBN_FIRST - 0; +pub const SB_SIMPLEID: ::WPARAM = 0x00ff; +pub const TBS_AUTOTICKS: ::DWORD = 0x0001; +pub const TBS_VERT: ::DWORD = 0x0002; +pub const TBS_HORZ: ::DWORD = 0x0000; +pub const TBS_TOP: ::DWORD = 0x0004; +pub const TBS_BOTTOM: ::DWORD = 0x0000; +pub const TBS_LEFT: ::DWORD = 0x0004; +pub const TBS_RIGHT: ::DWORD = 0x0000; +pub const TBS_BOTH: ::DWORD = 0x0008; +pub const TBS_NOTICKS: ::DWORD = 0x0010; +pub const TBS_ENABLESELRANGE: ::DWORD = 0x0020; +pub const TBS_FIXEDLENGTH: ::DWORD = 0x0040; +pub const TBS_NOTHUMB: ::DWORD = 0x0080; +pub const TBS_TOOLTIPS: ::DWORD = 0x0100; +pub const TBS_REVERSED: ::DWORD = 0x0200; +pub const TBS_DOWNISLEFT: ::DWORD = 0x0400; +pub const TBS_NOTIFYBEFOREMOVE: ::DWORD = 0x0800; +pub const TBS_TRANSPARENTBKGND: ::DWORD = 0x1000; +pub const TBM_GETPOS: ::UINT = ::WM_USER; +pub const TBM_GETRANGEMIN: ::UINT = ::WM_USER + 1; +pub const TBM_GETRANGEMAX: ::UINT = ::WM_USER + 2; +pub const TBM_GETTIC: ::UINT = ::WM_USER + 3; +pub const TBM_SETTIC: ::UINT = ::WM_USER + 4; +pub const TBM_SETPOS: ::UINT = ::WM_USER + 5; +pub const TBM_SETRANGE: ::UINT = ::WM_USER + 6; +pub const TBM_SETRANGEMIN: ::UINT = ::WM_USER + 7; +pub const TBM_SETRANGEMAX: ::UINT = ::WM_USER + 8; +pub const TBM_CLEARTICS: ::UINT = ::WM_USER + 9; +pub const TBM_SETSEL: ::UINT = ::WM_USER + 10; +pub const TBM_SETSELSTART: ::UINT = ::WM_USER + 11; +pub const TBM_SETSELEND: ::UINT = ::WM_USER + 12; +pub const TBM_GETPTICS: ::UINT = ::WM_USER + 14; +pub const TBM_GETTICPOS: ::UINT = ::WM_USER + 15; +pub const TBM_GETNUMTICS: ::UINT = ::WM_USER + 16; +pub const TBM_GETSELSTART: ::UINT = ::WM_USER + 17; +pub const TBM_GETSELEND: ::UINT = ::WM_USER + 18; +pub const TBM_CLEARSEL: ::UINT = ::WM_USER + 19; +pub const TBM_SETTICFREQ: ::UINT = ::WM_USER + 20; +pub const TBM_SETPAGESIZE: ::UINT = ::WM_USER + 21; +pub const TBM_GETPAGESIZE: ::UINT = ::WM_USER + 22; +pub const TBM_SETLINESIZE: ::UINT = ::WM_USER + 23; +pub const TBM_GETLINESIZE: ::UINT = ::WM_USER + 24; +pub const TBM_GETTHUMBRECT: ::UINT = ::WM_USER + 25; +pub const TBM_GETCHANNELRECT: ::UINT = ::WM_USER + 26; +pub const TBM_SETTHUMBLENGTH: ::UINT = ::WM_USER + 27; +pub const TBM_GETTHUMBLENGTH: ::UINT = ::WM_USER + 28; +pub const TBM_SETTOOLTIPS: ::UINT = ::WM_USER + 29; +pub const TBM_GETTOOLTIPS: ::UINT = ::WM_USER + 30; +pub const TBM_SETTIPSIDE: ::UINT = ::WM_USER + 31; +pub const TBTS_TOP: ::WPARAM = 0; +pub const TBTS_LEFT: ::WPARAM = 1; +pub const TBTS_BOTTOM: ::WPARAM = 2; +pub const TBTS_RIGHT: ::WPARAM = 3; +pub const TBM_SETBUDDY: ::UINT = ::WM_USER + 32; +pub const TBM_GETBUDDY: ::UINT = ::WM_USER + 33; +pub const TBM_SETPOSNOTIFY: ::UINT = ::WM_USER + 34; +pub const TBM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TBM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TBCD_TICS: ::DWORD_PTR = 0x0001; +pub const TBCD_THUMB: ::DWORD_PTR = 0x0001; +pub const TBCD_CHANNEL: ::DWORD_PTR = 0x0001; +pub const TB_LINEUP: ::WPARAM = 0; +pub const TB_LINEDOWN: ::WPARAM = 1; +pub const TB_PAGEUP: ::WPARAM = 2; +pub const TB_PAGEDOWN: ::WPARAM = 3; +pub const TB_THUMBPOSITION: ::WPARAM = 4; +pub const TB_THUMBTRACK: ::WPARAM = 5; +pub const TB_TOP: ::WPARAM = 6; +pub const TB_BOTTOM: ::WPARAM = 7; +pub const TB_ENDTRACK: ::WPARAM = 8; +pub const TRBN_THUMBPOSCHANGING: ::UINT = TRBN_FIRST - 1; +STRUCT!{struct NMTRBTHUMBPOSCHANGING { + hdr: ::NMHDR, + dwPos: ::DWORD, + nReason: ::c_int, +}} +STRUCT!{struct DRAGLISTINFO { + uNotification: ::UINT, + hWnd: ::HWND, + ptCursor: ::POINT, +}} +pub type LPDRAGLISTINFO = *mut DRAGLISTINFO; +pub const DL_BEGINDRAG: ::UINT = ::WM_USER + 133; +pub const DL_DRAGGING: ::UINT = ::WM_USER + 134; +pub const DL_DROPPED: ::UINT = ::WM_USER + 135; +pub const DL_CANCELDRAG: ::UINT = ::WM_USER + 136; +pub const DL_CURSORSET: ::UINT = 0; +pub const DL_STOPCURSOR: ::UINT = 1; +pub const DL_COPYCURSOR: ::UINT = 2; +pub const DL_MOVECURSOR: ::UINT = 3; +STRUCT!{struct UDACCEL { + nSec: ::UINT, + nInc: ::UINT, +}} +pub type LPUDACCEL = *mut UDACCEL; +pub const UD_MAXVAL: ::c_short = 0x7fff; +pub const UD_MINVAL: ::c_short = 0 - UD_MAXVAL; +pub const UDS_WRAP: ::DWORD = 0x0001; +pub const UDS_SETBUDDYINT: ::DWORD = 0x0002; +pub const UDS_ALIGNRIGHT: ::DWORD = 0x0004; +pub const UDS_ALIGNLEFT: ::DWORD = 0x0008; +pub const UDS_AUTOBUDDY: ::DWORD = 0x0010; +pub const UDS_ARROWKEYS: ::DWORD = 0x0020; +pub const UDS_HORZ: ::DWORD = 0x0040; +pub const UDS_NOTHOUSANDS: ::DWORD = 0x0080; +pub const UDS_HOTTRACK: ::DWORD = 0x0100; +pub const UDM_SETRANGE: ::UINT = ::WM_USER + 101; +pub const UDM_GETRANGE: ::UINT = ::WM_USER + 102; +pub const UDM_SETPOS: ::UINT = ::WM_USER + 103; +pub const UDM_GETPOS: ::UINT = ::WM_USER + 104; +pub const UDM_SETBUDDY: ::UINT = ::WM_USER + 105; +pub const UDM_GETBUDDY: ::UINT = ::WM_USER + 106; +pub const UDM_SETACCEL: ::UINT = ::WM_USER + 107; +pub const UDM_GETACCEL: ::UINT = ::WM_USER + 108; +pub const UDM_SETBASE: ::UINT = ::WM_USER + 109; +pub const UDM_GETBASE: ::UINT = ::WM_USER + 110; +pub const UDM_SETRANGE32: ::UINT = ::WM_USER + 111; +pub const UDM_GETRANGE32: ::UINT = ::WM_USER + 112; +pub const UDM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const UDM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const UDM_SETPOS32: ::UINT = ::WM_USER + 113; +pub const UDM_GETPOS32: ::UINT = ::WM_USER + 114; +pub type NM_UPDOWN = NMUPDOWN; +pub type LPNM_UPDOWN = LPNMUPDOWN; +STRUCT!{struct NMUPDOWN { + hdr: ::NMHDR, + iPos: ::c_int, + iDelta: ::c_int, +}} +pub type LPNMUPDOWN = *mut NMUPDOWN; +pub const UDN_DELTAPOS: ::UINT = UDN_FIRST - 1; +pub const PBS_SMOOTH: ::DWORD = 0x01; +pub const PBS_VERTICAL: ::DWORD = 0x04; +pub const PBM_SETRANGE: ::UINT = ::WM_USER + 1; +pub const PBM_SETPOS: ::UINT = ::WM_USER + 2; +pub const PBM_DELTAPOS: ::UINT = ::WM_USER + 3; +pub const PBM_SETSTEP: ::UINT = ::WM_USER + 4; +pub const PBM_STEPIT: ::UINT = ::WM_USER + 5; +pub const PBM_SETRANGE32: ::UINT = ::WM_USER + 6; +STRUCT!{struct PBRANGE { + iLow: ::c_int, + iHigh: ::c_int, +}} +pub type LPPBRANGE = *mut PBRANGE; +pub const PBM_GETRANGE: ::UINT = ::WM_USER + 7; +pub const PBM_GETPOS: ::UINT = ::WM_USER + 8; +pub const PBM_SETBARCOLOR: ::UINT = ::WM_USER + 9; +pub const PBM_SETBKCOLOR: ::UINT = CCM_SETBKCOLOR; +pub const PBM_SETMARQUEE: ::UINT = ::WM_USER + 10; +pub const PBS_MARQUEE: ::DWORD = 0x08; +pub const PBS_SMOOTHREVERSE: ::DWORD = 0x10; +pub const PBM_GETSTEP: ::UINT = ::WM_USER + 13; +pub const PBM_GETBKCOLOR: ::UINT = ::WM_USER + 14; +pub const PBM_GETBARCOLOR: ::UINT = ::WM_USER + 15; +pub const PBM_SETSTATE: ::UINT = ::WM_USER + 16; +pub const PBM_GETSTATE: ::UINT = ::WM_USER + 17; +pub const PBST_NORMAL: ::c_int = 0x0001; +pub const PBST_ERROR: ::c_int = 0x0002; +pub const PBST_PAUSED: ::c_int = 0x0003; +pub const HOTKEYF_SHIFT: ::BYTE = 0x01; +pub const HOTKEYF_CONTROL: ::BYTE = 0x02; +pub const HOTKEYF_ALT: ::BYTE = 0x04; +pub const HOTKEYF_EXT: ::BYTE = 0x08; +pub const HKCOMB_NONE: ::WPARAM = 0x0001; +pub const HKCOMB_S: ::WPARAM = 0x0002; +pub const HKCOMB_C: ::WPARAM = 0x0004; +pub const HKCOMB_A: ::WPARAM = 0x0008; +pub const HKCOMB_SC: ::WPARAM = 0x0010; +pub const HKCOMB_SA: ::WPARAM = 0x0020; +pub const HKCOMB_CA: ::WPARAM = 0x0040; +pub const HKCOMB_SCA: ::WPARAM = 0x0080; +pub const HKM_SETHOTKEY: ::UINT = ::WM_USER + 1; +pub const HKM_GETHOTKEY: ::UINT = ::WM_USER + 2; +pub const HKM_SETRULES: ::UINT = ::WM_USER + 3; +pub const CCS_TOP: ::DWORD = 0x00000001; +pub const CCS_NOMOVEY: ::DWORD = 0x00000002; +pub const CCS_BOTTOM: ::DWORD = 0x00000003; +pub const CCS_NORESIZE: ::DWORD = 0x00000004; +pub const CCS_NOPARENTALIGN: ::DWORD = 0x00000008; +pub const CCS_ADJUSTABLE: ::DWORD = 0x00000020; +pub const CCS_NODIVIDER: ::DWORD = 0x00000040; +pub const CCS_VERT: ::DWORD = 0x00000080; +pub const CCS_LEFT: ::DWORD = CCS_VERT | CCS_TOP; +pub const CCS_RIGHT: ::DWORD = CCS_VERT | CCS_BOTTOM; +pub const CCS_NOMOVEX: ::DWORD = CCS_VERT | CCS_NOMOVEY; +pub const MAX_LINKID_TEXT: usize = 48; +pub const L_MAX_URL_LENGTH: usize = 2048 + 32 + 4; +pub const LWS_TRANSPARENT: ::DWORD = 0x0001; +pub const LWS_IGNORERETURN: ::DWORD = 0x0002; +pub const LWS_NOPREFIX: ::DWORD = 0x0004; +pub const LWS_USEVISUALSTYLE: ::DWORD = 0x0008; +pub const LWS_USECUSTOMTEXT: ::DWORD = 0x0010; +pub const LWS_RIGHT: ::DWORD = 0x0020; +pub const LIF_ITEMINDEX: ::UINT = 0x00000001; +pub const LIF_STATE: ::UINT = 0x00000002; +pub const LIF_ITEMID: ::UINT = 0x00000004; +pub const LIF_URL: ::UINT = 0x00000008; +pub const LIS_FOCUSED: ::UINT = 0x00000001; +pub const LIS_ENABLED: ::UINT = 0x00000002; +pub const LIS_VISITED: ::UINT = 0x00000004; +pub const LIS_HOTTRACK: ::UINT = 0x00000008; +pub const LIS_DEFAULTCOLORS: ::UINT = 0x00000010; +STRUCT!{nodebug struct LITEM { + mask: ::UINT, + iLink: ::c_int, + state: ::UINT, + stateMask: ::UINT, + szID: [::WCHAR; MAX_LINKID_TEXT], + szUrl: [::WCHAR; L_MAX_URL_LENGTH], +}} +pub type PLITEM = *mut LITEM; +STRUCT!{nodebug struct LHITTESTINFO { + pt: ::POINT, + item: LITEM, +}} +pub type PLHITTESTINFO = *mut LHITTESTINFO; +STRUCT!{nodebug struct NMLINK { + hdr: ::NMHDR, + item: LITEM, +}} +pub type PNMLINK = *mut NMLINK; +pub const LM_HITTEST: ::UINT = ::WM_USER + 0x300; +pub const LM_GETIDEALHEIGHT: ::UINT = ::WM_USER + 0x301; +pub const LM_SETITEM: ::UINT = ::WM_USER + 0x302; +pub const LM_GETITEM: ::UINT = ::WM_USER + 0x303; +pub const LM_GETIDEALSIZE: ::UINT = LM_GETIDEALHEIGHT; +pub const LVS_ICON: ::DWORD = 0x0000; +pub const LVS_REPORT: ::DWORD = 0x0001; +pub const LVS_SMALLICON: ::DWORD = 0x0002; +pub const LVS_LIST: ::DWORD = 0x0003; +pub const LVS_TYPEMASK: ::DWORD = 0x0003; +pub const LVS_SINGLESEL: ::DWORD = 0x0004; +pub const LVS_SHOWSELALWAYS: ::DWORD = 0x0008; +pub const LVS_SORTASCENDING: ::DWORD = 0x0010; +pub const LVS_SORTDESCENDING: ::DWORD = 0x0020; +pub const LVS_SHAREIMAGELISTS: ::DWORD = 0x0040; +pub const LVS_NOLABELWRAP: ::DWORD = 0x0080; +pub const LVS_AUTOARRANGE: ::DWORD = 0x0100; +pub const LVS_EDITLABELS: ::DWORD = 0x0200; +pub const LVS_OWNERDATA: ::DWORD = 0x1000; +pub const LVS_NOSCROLL: ::DWORD = 0x2000; +pub const LVS_TYPESTYLEMASK: ::DWORD = 0xfc00; +pub const LVS_ALIGNTOP: ::DWORD = 0x0000; +pub const LVS_ALIGNLEFT: ::DWORD = 0x0800; +pub const LVS_ALIGNMASK: ::DWORD = 0x0c00; +pub const LVS_OWNERDRAWFIXED: ::DWORD = 0x0400; +pub const LVS_NOCOLUMNHEADER: ::DWORD = 0x4000; +pub const LVS_NOSORTHEADER: ::DWORD = 0x8000; +pub const LVM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const LVM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const LVM_GETBKCOLOR: ::UINT = LVM_FIRST + 0; +pub const LVM_SETBKCOLOR: ::UINT = LVM_FIRST + 1; +pub const LVM_GETIMAGELIST: ::UINT = LVM_FIRST + 2; +pub const LVM_SETIMAGELIST: ::UINT = LVM_FIRST + 3; +pub const LVM_GETITEMCOUNT: ::UINT = LVM_FIRST + 4; +pub const LVSIL_NORMAL: ::c_int = 0; +pub const LVSIL_SMALL: ::c_int = 1; +pub const LVSIL_STATE: ::c_int = 2; +pub const LVSIL_GROUPHEADER: ::c_int = 3; +pub const LVIF_TEXT: ::UINT = 0x00000001; +pub const LVIF_IMAGE: ::UINT = 0x00000002; +pub const LVIF_PARAM: ::UINT = 0x00000004; +pub const LVIF_STATE: ::UINT = 0x00000008; +pub const LVIF_INDENT: ::UINT = 0x00000010; +pub const LVIF_NORECOMPUTE: ::UINT = 0x00000800; +pub const LVIF_GROUPID: ::UINT = 0x00000100; +pub const LVIF_COLUMNS: ::UINT = 0x00000200; +pub const LVIF_COLFMT: ::UINT = 0x00010000; +pub const LVIS_FOCUSED: ::UINT = 0x0001; +pub const LVIS_SELECTED: ::UINT = 0x0002; +pub const LVIS_CUT: ::UINT = 0x0004; +pub const LVIS_DROPHILITED: ::UINT = 0x0008; +pub const LVIS_GLOW: ::UINT = 0x0010; +pub const LVIS_ACTIVATING: ::UINT = 0x0020; +pub const LVIS_OVERLAYMASK: ::UINT = 0x0F00; +pub const LVIS_STATEIMAGEMASK: ::UINT = 0xF000; +#[inline] #[allow(dead_code)] +pub fn INDEXTOSTATEIMAGEMASK(i: ::UINT) -> ::UINT { i << 12 } +pub const I_INDENTCALLBACK: ::c_int = -1; +pub type LV_ITEMA = LVITEMA; +pub type LV_ITEMW = LVITEMW; +pub const I_GROUPIDCALLBACK: ::c_int = -1; +pub const I_GROUPIDNONE: ::c_int = -2; +STRUCT!{struct LVITEMA { + mask: ::UINT, + iItem: ::c_int, + iSubItem: ::c_int, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, + iIndent: ::c_int, + iGroupId: ::c_int, + cColumns: ::UINT, + puColumns: ::PUINT, + piColFmt: *mut ::c_int, + iGroup: ::c_int, +}} +pub type LPLVITEMA = *mut LVITEMA; +STRUCT!{struct LVITEMW { + mask: ::UINT, + iItem: ::c_int, + iSubItem: ::c_int, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, + iIndent: ::c_int, + iGroupId: ::c_int, + cColumns: ::UINT, + puColumns: ::PUINT, + piColFmt: *mut ::c_int, + iGroup: ::c_int, +}} +pub type LPLVITEMW = *mut LVITEMW; +pub const LPSTR_TEXTCALLBACKW: ::LPWSTR = (0 - 1) as ::LPWSTR; +pub const LPSTR_TEXTCALLBACKA: ::LPSTR = (0 - 1) as ::LPSTR; +pub const I_IMAGECALLBACK: ::c_int = -1; +pub const I_IMAGENONE: ::c_int = -2; +pub const I_COLUMNSCALLBACK: ::UINT = -1i32 as ::UINT; +pub const LVM_GETITEMA: ::UINT = LVM_FIRST + 5; +pub const LVM_GETITEMW: ::UINT = LVM_FIRST + 75; +pub const LVM_SETITEMA: ::UINT = LVM_FIRST + 6; +pub const LVM_SETITEMW: ::UINT = LVM_FIRST + 76; +pub const LVM_INSERTITEMA: ::UINT = LVM_FIRST + 7; +pub const LVM_INSERTITEMW: ::UINT = LVM_FIRST + 77; +pub const LVM_DELETEITEM: ::UINT = LVM_FIRST + 8; +pub const LVM_DELETEALLITEMS: ::UINT = LVM_FIRST + 9; +pub const LVM_GETCALLBACKMASK: ::UINT = LVM_FIRST + 10; +pub const LVM_SETCALLBACKMASK: ::UINT = LVM_FIRST + 11; +pub const LVM_GETNEXTITEM: ::UINT = LVM_FIRST + 12; +pub const LVNI_ALL: ::LPARAM = 0x0000; +pub const LVNI_FOCUSED: ::LPARAM = 0x0001; +pub const LVNI_SELECTED: ::LPARAM = 0x0002; +pub const LVNI_CUT: ::LPARAM = 0x0004; +pub const LVNI_DROPHILITED: ::LPARAM = 0x0008; +pub const LVNI_STATEMASK: ::LPARAM = LVNI_FOCUSED | LVNI_SELECTED | LVNI_CUT | LVNI_DROPHILITED; +pub const LVNI_VISIBLEORDER: ::LPARAM = 0x0010; +pub const LVNI_PREVIOUS: ::LPARAM = 0x0020; +pub const LVNI_VISIBLEONLY: ::LPARAM = 0x0040; +pub const LVNI_SAMEGROUPONLY: ::LPARAM = 0x0080; +pub const LVNI_ABOVE: ::LPARAM = 0x0100; +pub const LVNI_BELOW: ::LPARAM = 0x0200; +pub const LVNI_TOLEFT: ::LPARAM = 0x0400; +pub const LVNI_TORIGHT: ::LPARAM = 0x0800; +pub const LVNI_DIRECTIONMASK: ::LPARAM = LVNI_ABOVE | LVNI_BELOW | LVNI_TOLEFT | LVNI_TORIGHT; +pub const LVFI_PARAM: ::UINT = 0x0001; +pub const LVFI_STRING: ::UINT = 0x0002; +pub const LVFI_SUBSTRING: ::UINT = 0x0004; +pub const LVFI_PARTIAL: ::UINT = 0x0008; +pub const LVFI_WRAP: ::UINT = 0x0020; +pub const LVFI_NEARESTXY: ::UINT = 0x0040; +pub type LV_FINDINFOA = LVFINDINFOA; +pub type LV_FINDINFOW = LVFINDINFOW; +STRUCT!{struct LVFINDINFOA { + flags: ::UINT, + psz: ::LPCSTR, + lParam: ::LPARAM, + pt: ::POINT, + vkDirection: ::UINT, +}} +pub type LPLVFINDINFOA = *mut LVFINDINFOA; +STRUCT!{struct LVFINDINFOW { + flags: ::UINT, + psz: ::LPCWSTR, + lParam: ::LPARAM, + pt: ::POINT, + vkDirection: ::UINT, +}} +pub type LPLVFINDINFOW = *mut LVFINDINFOW; +pub const LVM_FINDITEMA: ::UINT = LVM_FIRST + 13; +pub const LVM_FINDITEMW: ::UINT = LVM_FIRST + 83; +pub const LVIR_BOUNDS: ::c_int = 0; +pub const LVIR_ICON: ::c_int = 1; +pub const LVIR_LABEL: ::c_int = 2; +pub const LVIR_SELECTBOUNDS: ::c_int = 3; +pub const LVM_GETITEMRECT: ::UINT = LVM_FIRST + 14; +pub const LVM_SETITEMPOSITION: ::UINT = LVM_FIRST + 15; +pub const LVM_GETITEMPOSITION: ::UINT = LVM_FIRST + 16; +pub const LVM_GETSTRINGWIDTHA: ::UINT = LVM_FIRST + 17; +pub const LVM_GETSTRINGWIDTHW: ::UINT = LVM_FIRST + 87; +pub const LVHT_NOWHERE: ::UINT = 0x00000001; +pub const LVHT_ONITEMICON: ::UINT = 0x00000002; +pub const LVHT_ONITEMLABEL: ::UINT = 0x00000004; +pub const LVHT_ONITEMSTATEICON: ::UINT = 0x00000008; +pub const LVHT_ONITEM: ::UINT = LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON; +pub const LVHT_ABOVE: ::UINT = 0x00000008; +pub const LVHT_BELOW: ::UINT = 0x00000010; +pub const LVHT_TORIGHT: ::UINT = 0x00000020; +pub const LVHT_TOLEFT: ::UINT = 0x00000040; +pub const LVHT_EX_GROUP_HEADER: ::UINT = 0x10000000; +pub const LVHT_EX_GROUP_FOOTER: ::UINT = 0x20000000; +pub const LVHT_EX_GROUP_COLLAPSE: ::UINT = 0x40000000; +pub const LVHT_EX_GROUP_BACKGROUND: ::UINT = 0x80000000; +pub const LVHT_EX_GROUP_STATEICON: ::UINT = 0x01000000; +pub const LVHT_EX_GROUP_SUBSETLINK: ::UINT = 0x02000000; +pub const LVHT_EX_GROUP: ::UINT = LVHT_EX_GROUP_BACKGROUND | LVHT_EX_GROUP_COLLAPSE + | LVHT_EX_GROUP_FOOTER | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON + | LVHT_EX_GROUP_SUBSETLINK; +pub const LVHT_EX_ONCONTENTS: ::UINT = 0x04000000; +pub const LVHT_EX_FOOTER: ::UINT = 0x08000000; +pub type LV_HITTESTINFO = LVHITTESTINFO; +STRUCT!{struct LVHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + iItem: ::c_int, + iSubItem: ::c_int, + iGroup: ::c_int, +}} +pub type LPLVHITTESTINFO = *mut LVHITTESTINFO; +pub const LVM_HITTEST: ::UINT = LVM_FIRST + 18; +pub const LVM_ENSUREVISIBLE: ::UINT = LVM_FIRST + 19; +pub const LVM_SCROLL: ::UINT = LVM_FIRST + 20; +pub const LVM_REDRAWITEMS: ::UINT = LVM_FIRST + 21; +pub const LVA_DEFAULT: ::WPARAM = 0x0000; +pub const LVA_ALIGNLEFT: ::WPARAM = 0x0001; +pub const LVA_ALIGNTOP: ::WPARAM = 0x0002; +pub const LVA_SNAPTOGRID: ::WPARAM = 0x0005; +pub const LVM_ARRANGE: ::UINT = LVM_FIRST + 22; +pub const LVM_EDITLABELA: ::UINT = LVM_FIRST + 23; +pub const LVM_EDITLABELW: ::UINT = LVM_FIRST + 118; +pub const LVM_GETEDITCONTROL: ::UINT = LVM_FIRST + 24; +pub type LV_COLUMNA = LVCOLUMNA; +pub type LV_COLUMNW = LVCOLUMNW; +STRUCT!{struct LVCOLUMNA { + mask: ::UINT, + fmt: ::c_int, + cx: ::c_int, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iSubItem: ::c_int, + iImage: ::c_int, + iOrder: ::c_int, + cxMin: ::c_int, + cxDefault: ::c_int, + cxIdeal: ::c_int, +}} +pub type LPLVCOLUMNA = *mut LVCOLUMNA; +STRUCT!{struct LVCOLUMNW { + mask: ::UINT, + fmt: ::c_int, + cx: ::c_int, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iSubItem: ::c_int, + iImage: ::c_int, + iOrder: ::c_int, + cxMin: ::c_int, + cxDefault: ::c_int, + cxIdeal: ::c_int, +}} +pub type LPLVCOLUMNW = *mut LVCOLUMNW; +pub const LVCF_FMT: ::UINT = 0x0001; +pub const LVCF_WIDTH: ::UINT = 0x0002; +pub const LVCF_TEXT: ::UINT = 0x0004; +pub const LVCF_SUBITEM: ::UINT = 0x0008; +pub const LVCF_IMAGE: ::UINT = 0x0010; +pub const LVCF_ORDER: ::UINT = 0x0020; +pub const LVCF_MINWIDTH: ::UINT = 0x0040; +pub const LVCF_DEFAULTWIDTH: ::UINT = 0x0080; +pub const LVCF_IDEALWIDTH: ::UINT = 0x0100; +pub const LVCFMT_LEFT: ::c_int = 0x0000; +pub const LVCFMT_RIGHT: ::c_int = 0x0001; +pub const LVCFMT_CENTER: ::c_int = 0x0002; +pub const LVCFMT_JUSTIFYMASK: ::c_int = 0x0003; +pub const LVCFMT_IMAGE: ::c_int = 0x0800; +pub const LVCFMT_BITMAP_ON_RIGHT: ::c_int = 0x1000; +pub const LVCFMT_COL_HAS_IMAGES: ::c_int = 0x8000; +pub const LVCFMT_FIXED_WIDTH: ::c_int = 0x00100; +pub const LVCFMT_NO_DPI_SCALE: ::c_int = 0x40000; +pub const LVCFMT_FIXED_RATIO: ::c_int = 0x80000; +pub const LVCFMT_LINE_BREAK: ::c_int = 0x100000; +pub const LVCFMT_FILL: ::c_int = 0x200000; +pub const LVCFMT_WRAP: ::c_int = 0x400000; +pub const LVCFMT_NO_TITLE: ::c_int = 0x800000; +pub const LVCFMT_TILE_PLACEMENTMASK: ::c_int = LVCFMT_LINE_BREAK | LVCFMT_FILL; +pub const LVCFMT_SPLITBUTTON: ::c_int = 0x1000000; +pub const LVM_GETCOLUMNA: ::UINT = LVM_FIRST + 25; +pub const LVM_GETCOLUMNW: ::UINT = LVM_FIRST + 95; +pub const LVM_SETCOLUMNA: ::UINT = LVM_FIRST + 26; +pub const LVM_SETCOLUMNW: ::UINT = LVM_FIRST + 96; +pub const LVM_INSERTCOLUMNA: ::UINT = LVM_FIRST + 27; +pub const LVM_INSERTCOLUMNW: ::UINT = LVM_FIRST + 97; +pub const LVM_DELETECOLUMN: ::UINT = LVM_FIRST + 28; +pub const LVM_GETCOLUMNWIDTH: ::UINT = LVM_FIRST + 29; +pub const LVM_SETCOLUMNWIDTH: ::UINT = LVM_FIRST + 30; +pub const LVM_GETHEADER: ::UINT = LVM_FIRST + 31; +pub const LVM_CREATEDRAGIMAGE: ::UINT = LVM_FIRST + 33; +pub const LVM_GETVIEWRECT: ::UINT = LVM_FIRST + 34; +pub const LVM_GETTEXTCOLOR: ::UINT = LVM_FIRST + 35; +pub const LVM_SETTEXTCOLOR: ::UINT = LVM_FIRST + 36; +pub const LVM_GETTEXTBKCOLOR: ::UINT = LVM_FIRST + 37; +pub const LVM_SETTEXTBKCOLOR: ::UINT = LVM_FIRST + 38; +pub const LVM_GETTOPINDEX: ::UINT = LVM_FIRST + 39; +pub const LVM_GETCOUNTPERPAGE: ::UINT = LVM_FIRST + 40; +pub const LVM_GETORIGIN: ::UINT = LVM_FIRST + 41; +pub const LVM_UPDATE: ::UINT = LVM_FIRST + 42; +pub const LVM_SETITEMSTATE: ::UINT = LVM_FIRST + 43; +pub const LVM_GETITEMSTATE: ::UINT = LVM_FIRST + 44; +pub const LVM_GETITEMTEXTA: ::UINT = LVM_FIRST + 45; +pub const LVM_GETITEMTEXTW: ::UINT = LVM_FIRST + 115; +pub const LVM_SETITEMTEXTA: ::UINT = LVM_FIRST + 46; +pub const LVM_SETITEMTEXTW: ::UINT = LVM_FIRST + 116; +pub const LVM_SETITEMCOUNT: ::UINT = LVM_FIRST + 47; +pub const LVM_SORTITEMS: ::UINT = LVM_FIRST + 48; +pub const LVM_SETITEMPOSITION32: ::UINT = LVM_FIRST + 49; +pub const LVM_GETSELECTEDCOUNT: ::UINT = LVM_FIRST + 50; +pub const LVM_GETITEMSPACING: ::UINT = LVM_FIRST + 51; +pub const LVM_GETISEARCHSTRINGA: ::UINT = LVM_FIRST + 52; +pub const LVM_GETISEARCHSTRINGW: ::UINT = LVM_FIRST + 117; +pub const LVM_SETICONSPACING: ::UINT = LVM_FIRST + 53; +pub const LVM_SETEXTENDEDLISTVIEWSTYLE: ::UINT = LVM_FIRST + 54; +pub const LVM_GETEXTENDEDLISTVIEWSTYLE: ::UINT = LVM_FIRST + 55; +pub const LVSICF_NOINVALIDATEALL: ::LPARAM = 0x00000001; +pub const LVSICF_NOSCROLL: ::LPARAM = 0x00000002; +pub const LVS_EX_GRIDLINES: ::DWORD = 0x00000001; +pub const LVS_EX_SUBITEMIMAGES: ::DWORD = 0x00000002; +pub const LVS_EX_CHECKBOXES: ::DWORD = 0x00000004; +pub const LVS_EX_TRACKSELECT: ::DWORD = 0x00000008; +pub const LVS_EX_HEADERDRAGDROP: ::DWORD = 0x00000010; +pub const LVS_EX_FULLROWSELECT: ::DWORD = 0x00000020; +pub const LVS_EX_ONECLICKACTIVATE: ::DWORD = 0x00000040; +pub const LVS_EX_TWOCLICKACTIVATE: ::DWORD = 0x00000080; +pub const LVS_EX_FLATSB: ::DWORD = 0x00000100; +pub const LVS_EX_REGIONAL: ::DWORD = 0x00000200; +pub const LVS_EX_INFOTIP: ::DWORD = 0x00000400; +pub const LVS_EX_UNDERLINEHOT: ::DWORD = 0x00000800; +pub const LVS_EX_UNDERLINECOLD: ::DWORD = 0x00001000; +pub const LVS_EX_MULTIWORKAREAS: ::DWORD = 0x00002000; +pub const LVS_EX_LABELTIP: ::DWORD = 0x00004000; +pub const LVS_EX_BORDERSELECT: ::DWORD = 0x00008000; +pub const LVS_EX_DOUBLEBUFFER: ::DWORD = 0x00010000; +pub const LVS_EX_HIDELABELS: ::DWORD = 0x00020000; +pub const LVS_EX_SINGLEROW: ::DWORD = 0x00040000; +pub const LVS_EX_SNAPTOGRID: ::DWORD = 0x00080000; +pub const LVS_EX_SIMPLESELECT: ::DWORD = 0x00100000; +pub const LVS_EX_JUSTIFYCOLUMNS: ::DWORD = 0x00200000; +pub const LVS_EX_TRANSPARENTBKGND: ::DWORD = 0x00400000; +pub const LVS_EX_TRANSPARENTSHADOWTEXT: ::DWORD = 0x00800000; +pub const LVS_EX_AUTOAUTOARRANGE: ::DWORD = 0x01000000; +pub const LVS_EX_HEADERINALLVIEWS: ::DWORD = 0x02000000; +pub const LVS_EX_AUTOCHECKSELECT: ::DWORD = 0x08000000; +pub const LVS_EX_AUTOSIZECOLUMNS: ::DWORD = 0x10000000; +pub const LVS_EX_COLUMNSNAPPOINTS: ::DWORD = 0x40000000; +pub const LVS_EX_COLUMNOVERFLOW: ::DWORD = 0x80000000; +pub const LVM_GETSUBITEMRECT: ::UINT = LVM_FIRST + 56; +pub const LVM_SUBITEMHITTEST: ::UINT = LVM_FIRST + 57; +pub const LVM_SETCOLUMNORDERARRAY: ::UINT = LVM_FIRST + 58; +pub const LVM_GETCOLUMNORDERARRAY: ::UINT = LVM_FIRST + 59; +pub const LVM_SETHOTITEM: ::UINT = LVM_FIRST + 60; +pub const LVM_GETHOTITEM: ::UINT = LVM_FIRST + 61; +pub const LVM_SETHOTCURSOR: ::UINT = LVM_FIRST + 62; +pub const LVM_GETHOTCURSOR: ::UINT = LVM_FIRST + 63; +pub const LVM_APPROXIMATEVIEWRECT: ::UINT = LVM_FIRST + 64; +pub const LV_MAX_WORKAREAS: ::WPARAM = 16; +pub const LVM_SETWORKAREAS: ::UINT = LVM_FIRST + 65; +pub const LVM_GETWORKAREAS: ::UINT = LVM_FIRST + 70; +pub const LVM_GETNUMBEROFWORKAREAS: ::UINT = LVM_FIRST + 73; +pub const LVM_GETSELECTIONMARK: ::UINT = LVM_FIRST + 66; +pub const LVM_SETSELECTIONMARK: ::UINT = LVM_FIRST + 67; +pub const LVM_SETHOVERTIME: ::UINT = LVM_FIRST + 71; +pub const LVM_GETHOVERTIME: ::UINT = LVM_FIRST + 72; +pub const LVM_SETTOOLTIPS: ::UINT = LVM_FIRST + 74; +pub const LVM_GETTOOLTIPS: ::UINT = LVM_FIRST + 78; +pub const LVM_SORTITEMSEX: ::UINT = LVM_FIRST + 81; +STRUCT!{struct LVBKIMAGEA { + ulFlags: ::ULONG, + hbm: ::HBITMAP, + pszImage: ::LPSTR, + cchImageMax: ::UINT, + xOffsetPercent: ::c_int, + yOffsetPercent: ::c_int, +}} +pub type LPLVBKIMAGEA = *mut LVBKIMAGEA; +STRUCT!{struct LVBKIMAGEW { + ulFlags: ::ULONG, + hbm: ::HBITMAP, + pszImage: ::LPWSTR, + cchImageMax: ::UINT, + xOffsetPercent: ::c_int, + yOffsetPercent: ::c_int, +}} +pub type LPLVBKIMAGEW = *mut LVBKIMAGEW; +pub const LVBKIF_SOURCE_NONE: ::ULONG = 0x00000000; +pub const LVBKIF_SOURCE_HBITMAP: ::ULONG = 0x00000001; +pub const LVBKIF_SOURCE_URL: ::ULONG = 0x00000002; +pub const LVBKIF_SOURCE_MASK: ::ULONG = 0x00000003; +pub const LVBKIF_STYLE_NORMAL: ::ULONG = 0x00000000; +pub const LVBKIF_STYLE_TILE: ::ULONG = 0x00000010; +pub const LVBKIF_STYLE_MASK: ::ULONG = 0x00000010; +pub const LVBKIF_FLAG_TILEOFFSET: ::ULONG = 0x00000100; +pub const LVBKIF_TYPE_WATERMARK: ::ULONG = 0x10000000; +pub const LVBKIF_FLAG_ALPHABLEND: ::ULONG = 0x20000000; +pub const LVM_SETBKIMAGEA: ::UINT = LVM_FIRST + 68; +pub const LVM_SETBKIMAGEW: ::UINT = LVM_FIRST + 138; +pub const LVM_GETBKIMAGEA: ::UINT = LVM_FIRST + 69; +pub const LVM_GETBKIMAGEW: ::UINT = LVM_FIRST + 139; +pub const LVM_SETSELECTEDCOLUMN: ::UINT = LVM_FIRST + 140; +pub const LV_VIEW_ICON: ::DWORD = 0x0000; +pub const LV_VIEW_DETAILS: ::DWORD = 0x0001; +pub const LV_VIEW_SMALLICON: ::DWORD = 0x0002; +pub const LV_VIEW_LIST: ::DWORD = 0x0003; +pub const LV_VIEW_TILE: ::DWORD = 0x0004; +pub const LV_VIEW_MAX: ::DWORD = 0x0004; +pub const LVM_SETVIEW: ::UINT = LVM_FIRST + 142; +pub const LVM_GETVIEW: ::UINT = LVM_FIRST + 143; +pub const LVGF_NONE: ::UINT = 0x00000000; +pub const LVGF_HEADER: ::UINT = 0x00000001; +pub const LVGF_FOOTER: ::UINT = 0x00000002; +pub const LVGF_STATE: ::UINT = 0x00000004; +pub const LVGF_ALIGN: ::UINT = 0x00000008; +pub const LVGF_GROUPID: ::UINT = 0x00000010; +pub const LVGF_SUBTITLE: ::UINT = 0x00000100; +pub const LVGF_TASK: ::UINT = 0x00000200; +pub const LVGF_DESCRIPTIONTOP: ::UINT = 0x00000400; +pub const LVGF_DESCRIPTIONBOTTOM: ::UINT = 0x00000800; +pub const LVGF_TITLEIMAGE: ::UINT = 0x00001000; +pub const LVGF_EXTENDEDIMAGE: ::UINT = 0x00002000; +pub const LVGF_ITEMS: ::UINT = 0x00004000; +pub const LVGF_SUBSET: ::UINT = 0x00008000; +pub const LVGF_SUBSETITEMS: ::UINT = 0x00010000; +pub const LVGS_NORMAL: ::UINT = 0x00000000; +pub const LVGS_COLLAPSED: ::UINT = 0x00000001; +pub const LVGS_HIDDEN: ::UINT = 0x00000002; +pub const LVGS_NOHEADER: ::UINT = 0x00000004; +pub const LVGS_COLLAPSIBLE: ::UINT = 0x00000008; +pub const LVGS_FOCUSED: ::UINT = 0x00000010; +pub const LVGS_SELECTED: ::UINT = 0x00000020; +pub const LVGS_SUBSETED: ::UINT = 0x00000040; +pub const LVGS_SUBSETLINKFOCUSED: ::UINT = 0x00000080; +pub const LVGA_HEADER_LEFT: ::UINT = 0x00000001; +pub const LVGA_HEADER_CENTER: ::UINT = 0x00000002; +pub const LVGA_HEADER_RIGHT: ::UINT = 0x00000004; +pub const LVGA_FOOTER_LEFT: ::UINT = 0x00000008; +pub const LVGA_FOOTER_CENTER: ::UINT = 0x00000010; +pub const LVGA_FOOTER_RIGHT: ::UINT = 0x00000020; +STRUCT!{struct LVGROUP { + cbSize: ::UINT, + mask: ::UINT, + pszHeader: ::LPWSTR, + cchHeader: ::c_int, + pszFooter: ::LPWSTR, + cchFooter: ::c_int, + iGroupId: ::c_int, + stateMask: ::UINT, + state: ::UINT, + uAlign: ::UINT, + pszSubtitle: ::LPWSTR, + cchSubtitle: ::UINT, + pszTask: ::LPWSTR, + cchTask: ::UINT, + pszDescriptionTop: ::LPWSTR, + cchDescriptionTop: ::UINT, + pszDescriptionBottom: ::LPWSTR, + cchDescriptionBottom: ::UINT, + iTitleImage: ::c_int, + iExtendedImage: ::c_int, + iFirstItem: ::c_int, + cItems: ::UINT, + pszSubsetTitle: ::LPWSTR, + cchSubsetTitle: ::UINT, +}} +pub type PLVGROUP = *mut LVGROUP; +pub const LVM_INSERTGROUP: ::UINT = LVM_FIRST + 145; +pub const LVM_SETGROUPINFO: ::UINT = LVM_FIRST + 147; +pub const LVM_GETGROUPINFO: ::UINT = LVM_FIRST + 149; +pub const LVM_REMOVEGROUP: ::UINT = LVM_FIRST + 150; +pub const LVM_MOVEGROUP: ::UINT = LVM_FIRST + 151; +pub const LVM_GETGROUPCOUNT: ::UINT = LVM_FIRST + 152; +pub const LVM_GETGROUPINFOBYINDEX: ::UINT = LVM_FIRST + 153; +pub const LVM_MOVEITEMTOGROUP: ::UINT = LVM_FIRST + 154; +pub const LVM_GETGROUPRECT: ::UINT = LVM_FIRST + 98; +pub const LVGGR_GROUP: ::LPARAM = 0; +pub const LVGGR_HEADER: ::LPARAM = 1; +pub const LVGGR_LABEL: ::LPARAM = 2; +pub const LVGGR_SUBSETLINK: ::LPARAM = 3; +pub const LVGMF_NONE: ::UINT = 0x00000000; +pub const LVGMF_BORDERSIZE: ::UINT = 0x00000001; +pub const LVGMF_BORDERCOLOR: ::UINT = 0x00000002; +pub const LVGMF_TEXTCOLOR: ::UINT = 0x00000004; +STRUCT!{struct LVGROUPMETRICS { + cbSize: ::UINT, + mask: ::UINT, + Left: ::UINT, + Top: ::UINT, + Right: ::UINT, + Bottom: ::UINT, + crLeft: ::COLORREF, + crTop: ::COLORREF, + crRight: ::COLORREF, + crBottom: ::COLORREF, + crHeader: ::COLORREF, + crFooter: ::COLORREF, +}} +pub type PLVGROUPMETRICS = *mut LVGROUPMETRICS; +pub const LVM_SETGROUPMETRICS: ::UINT = LVM_FIRST + 155; +pub const LVM_GETGROUPMETRICS: ::UINT = LVM_FIRST + 156; +pub const LVM_ENABLEGROUPVIEW: ::UINT = LVM_FIRST + 157; +pub const LVM_SORTGROUPS: ::UINT = LVM_FIRST + 158; +pub type PFNLVGROUPCOMPARE = Option<unsafe extern "system" fn( + ::c_int, ::c_int, *mut ::c_void, +) -> ::c_int>; +STRUCT!{nodebug struct LVINSERTGROUPSORTED { + pfnGroupCompare: PFNLVGROUPCOMPARE, + pvData: *mut ::c_void, + lvGroup: LVGROUP, +}} +pub type PLVINSERTGROUPSORTED = *mut LVINSERTGROUPSORTED; +pub const LVM_INSERTGROUPSORTED: ::UINT = LVM_FIRST + 159; +pub const LVM_REMOVEALLGROUPS: ::UINT = LVM_FIRST + 160; +pub const LVM_HASGROUP: ::UINT = LVM_FIRST + 161; +pub const LVM_GETGROUPSTATE: ::UINT = LVM_FIRST + 92; +pub const LVM_GETFOCUSEDGROUP: ::UINT = LVM_FIRST + 93; +pub const LVTVIF_AUTOSIZE: ::DWORD = 0x00000000; +pub const LVTVIF_FIXEDWIDTH: ::DWORD = 0x00000001; +pub const LVTVIF_FIXEDHEIGHT: ::DWORD = 0x00000002; +pub const LVTVIF_FIXEDSIZE: ::DWORD = 0x00000003; +pub const LVTVIF_EXTENDED: ::DWORD = 0x00000004; +pub const LVTVIM_TILESIZE: ::DWORD = 0x00000001; +pub const LVTVIM_COLUMNS: ::DWORD = 0x00000002; +pub const LVTVIM_LABELMARGIN: ::DWORD = 0x00000004; +STRUCT!{struct LVTILEVIEWINFO { + cbSize: ::UINT, + dwMask: ::DWORD, + dwFlags: ::DWORD, + sizeTile: ::SIZE, + cLines: ::c_int, + rcLabelMargin: ::RECT, +}} +pub type PLVTILEVIEWINFO = *mut LVTILEVIEWINFO; +STRUCT!{struct LVTILEINFO { + cbSize: ::UINT, + iItem: ::c_int, + cColumns: ::UINT, + puColumns: ::PUINT, + piColFmt: *mut ::c_int, +}} +pub type PLVTILEINFO = *mut LVTILEINFO; +pub const LVM_SETTILEVIEWINFO: ::UINT = LVM_FIRST + 162; +pub const LVM_GETTILEVIEWINFO: ::UINT = LVM_FIRST + 163; +pub const LVM_SETTILEINFO: ::UINT = LVM_FIRST + 164; +pub const LVM_GETTILEINFO: ::UINT = LVM_FIRST + 165; +STRUCT!{struct LVINSERTMARK { + cbSize: ::UINT, + dwFlags: ::DWORD, + iItem: ::c_int, + dwReserved: ::DWORD, +}} +pub type LPLVINSERTMARK = *mut LVINSERTMARK; +pub const LVIM_AFTER: ::DWORD = 0x00000001; +pub const LVM_SETINSERTMARK: ::UINT = LVM_FIRST + 166; +pub const LVM_GETINSERTMARK: ::UINT = LVM_FIRST + 167; +pub const LVM_INSERTMARKHITTEST: ::UINT = LVM_FIRST + 168; +pub const LVM_GETINSERTMARKRECT: ::UINT = LVM_FIRST + 169; +pub const LVM_SETINSERTMARKCOLOR: ::UINT = LVM_FIRST + 170; +pub const LVM_GETINSERTMARKCOLOR: ::UINT = LVM_FIRST + 171; +STRUCT!{struct LVSETINFOTIP { + cbSize: ::UINT, + dwFlags: ::DWORD, + pszText: ::LPWSTR, + iItem: ::c_int, + iSubItem: ::c_int, +}} +pub type PLVSETINFOTIP = *mut LVSETINFOTIP; +pub const LVM_SETINFOTIP: ::UINT = LVM_FIRST + 173; +pub const LVM_GETSELECTEDCOLUMN: ::UINT = LVM_FIRST + 174; +pub const LVM_ISGROUPVIEWENABLED: ::UINT = LVM_FIRST + 175; +pub const LVM_GETOUTLINECOLOR: ::UINT = LVM_FIRST + 176; +pub const LVM_SETOUTLINECOLOR: ::UINT = LVM_FIRST + 177; +pub const LVM_CANCELEDITLABEL: ::UINT = LVM_FIRST + 179; +pub const LVM_MAPINDEXTOID: ::UINT = LVM_FIRST + 180; +pub const LVM_MAPIDTOINDEX: ::UINT = LVM_FIRST + 181; +pub const LVM_ISITEMVISIBLE: ::UINT = LVM_FIRST + 182; +pub const LVM_GETEMPTYTEXT: ::UINT = LVM_FIRST + 204; +pub const LVM_GETFOOTERRECT: ::UINT = LVM_FIRST + 205; +pub const LVFF_ITEMCOUNT: ::UINT = 0x00000001; +STRUCT!{struct LVFOOTERINFO { + mask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + cItems: ::UINT, +}} +pub type LPLVFOOTERINFO = *mut LVFOOTERINFO; +pub const LVM_GETFOOTERINFO: ::UINT = LVM_FIRST + 206; +pub const LVM_GETFOOTERITEMRECT: ::UINT = LVM_FIRST + 207; +pub const LVFIF_TEXT: ::UINT = 0x00000001; +pub const LVFIF_STATE: ::UINT = 0x00000002; +pub const LVFIS_FOCUSED: ::UINT = 0x0001; +STRUCT!{struct LVFOOTERITEM { + mask: ::UINT, + iItem: ::c_int, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + state: ::UINT, + stateMask: ::UINT, +}} +pub type LPLVFOOTERITEM = *mut LVFOOTERITEM; +pub const LVM_GETFOOTERITEM: ::UINT = LVM_FIRST + 208; +STRUCT!{struct LVITEMINDEX { + iItem: ::c_int, + iGroup: ::c_int, +}} +pub type PLVITEMINDEX = *mut LVITEMINDEX; +pub const LVM_GETITEMINDEXRECT: ::UINT = LVM_FIRST + 209; +pub const LVM_SETITEMINDEXSTATE: ::UINT = LVM_FIRST + 210; +pub const LVM_GETNEXTITEMINDEX: ::UINT = LVM_FIRST + 211; +pub type LPNM_LISTVIEW = LPNMLISTVIEW; +pub type NM_LISTVIEW = NMLISTVIEW; +STRUCT!{struct NMLISTVIEW { + hdr: ::NMHDR, + iItem: ::c_int, + iSubItem: ::c_int, + uNewState: ::UINT, + uOldState: ::UINT, + uChanged: ::UINT, + ptAction: ::POINT, + lParam: ::LPARAM, +}} +pub type LPNMLISTVIEW = *mut NMLISTVIEW; +STRUCT!{struct NMITEMACTIVATE { + hdr: ::NMHDR, + iItem: ::c_int, + iSubItem: ::c_int, + uNewState: ::UINT, + uOldState: ::UINT, + uChanged: ::UINT, + ptAction: ::POINT, + lParam: ::LPARAM, + uKeyFlags: ::UINT, +}} +pub type LPNMITEMACTIVATE = *mut NMITEMACTIVATE; +pub const LVKF_ALT: ::UINT = 0x0001; +pub const LVKF_CONTROL: ::UINT = 0x0002; +pub const LVKF_SHIFT: ::UINT = 0x0004; +STRUCT!{struct NMLVCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + clrText: ::COLORREF, + clrTextBk: ::COLORREF, + iSubItem: ::c_int, + dwItemType: ::DWORD, + clrFace: ::COLORREF, + iIconEffect: ::c_int, + iIconPhase: ::c_int, + iPartId: ::c_int, + iStateId: ::c_int, + rcText: ::RECT, + uAlign: ::UINT, +}} +pub type LPNMLVCUSTOMDRAW = *mut NMLVCUSTOMDRAW; +pub const LVCDI_ITEM: ::DWORD = 0x00000000; +pub const LVCDI_GROUP: ::DWORD = 0x00000001; +pub const LVCDI_ITEMSLIST: ::DWORD = 0x00000002; +pub const LVCDRF_NOSELECT: ::LRESULT = 0x00010000; +pub const LVCDRF_NOGROUPFRAME: ::LRESULT = 0x00020000; +STRUCT!{struct NMLVCACHEHINT { + hdr: ::NMHDR, + iFrom: ::c_int, + iTo: ::c_int, +}} +pub type LPNMLVCACHEHINT = *mut NMLVCACHEHINT; +pub type LPNM_CACHEHINT = LPNMLVCACHEHINT; +pub type PNM_CACHEHINT = LPNMLVCACHEHINT; +pub type NM_CACHEHINT = NMLVCACHEHINT; +STRUCT!{struct NMLVFINDITEMA { + hdr: ::NMHDR, + iStart: ::c_int, + lvfi: LVFINDINFOA, +}} +pub type LPNMLVFINDITEMA = *mut NMLVFINDITEMA; +STRUCT!{struct NMLVFINDITEMW { + hdr: ::NMHDR, + iStart: ::c_int, + lvfi: LVFINDINFOW, +}} +pub type LPNMLVFINDITEMW = *mut NMLVFINDITEMW; +pub type PNM_FINDITEMA = LPNMLVFINDITEMA; +pub type LPNM_FINDITEMA = LPNMLVFINDITEMA; +pub type NM_FINDITEMA = NMLVFINDITEMA; +pub type PNM_FINDITEMW = LPNMLVFINDITEMW; +pub type LPNM_FINDITEMW = LPNMLVFINDITEMW; +pub type NM_FINDITEMW = NMLVFINDITEMW; +STRUCT!{struct NMLVODSTATECHANGE { + hdr: ::NMHDR, + iFrom: ::c_int, + iTo: ::c_int, + uNewState: ::UINT, + uOldState: ::UINT, +}} +pub type LPNMLVODSTATECHANGE = *mut NMLVODSTATECHANGE; +pub type PNM_ODSTATECHANGE = LPNMLVODSTATECHANGE; +pub type LPNM_ODSTATECHANGE = LPNMLVODSTATECHANGE; +pub type NM_ODSTATECHANGE = NMLVODSTATECHANGE; +pub const LVN_ITEMCHANGING: ::UINT = LVN_FIRST - 0; +pub const LVN_ITEMCHANGED: ::UINT = LVN_FIRST - 1; +pub const LVN_INSERTITEM: ::UINT = LVN_FIRST - 2; +pub const LVN_DELETEITEM: ::UINT = LVN_FIRST - 3; +pub const LVN_DELETEALLITEMS: ::UINT = LVN_FIRST - 4; +pub const LVN_BEGINLABELEDITA: ::UINT = LVN_FIRST - 5; +pub const LVN_BEGINLABELEDITW: ::UINT = LVN_FIRST - 75; +pub const LVN_ENDLABELEDITA: ::UINT = LVN_FIRST - 6; +pub const LVN_ENDLABELEDITW: ::UINT = LVN_FIRST - 76; +pub const LVN_COLUMNCLICK: ::UINT = LVN_FIRST - 8; +pub const LVN_BEGINDRAG: ::UINT = LVN_FIRST - 9; +pub const LVN_BEGINRDRAG: ::UINT = LVN_FIRST - 11; +pub const LVN_ODCACHEHINT: ::UINT = LVN_FIRST - 13; +pub const LVN_ODFINDITEMA: ::UINT = LVN_FIRST - 52; +pub const LVN_ODFINDITEMW: ::UINT = LVN_FIRST - 79; +pub const LVN_ITEMACTIVATE: ::UINT = LVN_FIRST - 14; +pub const LVN_ODSTATECHANGED: ::UINT = LVN_FIRST - 15; +pub const LVN_HOTTRACK: ::UINT = LVN_FIRST - 21; +pub const LVN_GETDISPINFOA: ::UINT = LVN_FIRST - 50; +pub const LVN_GETDISPINFOW: ::UINT = LVN_FIRST - 77; +pub const LVN_SETDISPINFOA: ::UINT = LVN_FIRST - 51; +pub const LVN_SETDISPINFOW: ::UINT = LVN_FIRST - 78; +pub const LVIF_DI_SETITEM: ::UINT = 0x1000; +pub type LV_DISPINFOA = NMLVDISPINFOA; +pub type LV_DISPINFOW = NMLVDISPINFOW; +STRUCT!{struct NMLVDISPINFOA { + hdr: ::NMHDR, + item: LVITEMA, +}} +pub type LPNMLVDISPINFOA = *mut NMLVDISPINFOA; +STRUCT!{struct NMLVDISPINFOW { + hdr: ::NMHDR, + item: LVITEMW, +}} +pub type LPNMLVDISPINFOW = *mut NMLVDISPINFOW; +pub const LVN_KEYDOWN: ::UINT = LVN_FIRST - 55; +pub type LV_KEYDOWN = NMLVKEYDOWN; +STRUCT!{struct NMLVKEYDOWN { + hdr: ::NMHDR, + wVKey: ::WORD, + flags: ::UINT, +}} +pub type LPNMLVKEYDOWN = *mut NMLVKEYDOWN; +pub const LVN_MARQUEEBEGIN: ::UINT = LVN_FIRST - 56; +STRUCT!{nodebug struct NMLVLINK { + hdr: ::NMHDR, + link: LITEM, + iItem: ::c_int, + iSubItem: ::c_int, +}} +pub type PNMLVLINK = *mut NMLVLINK; +STRUCT!{struct NMLVGETINFOTIPA { + hdr: ::NMHDR, + dwFlags: ::DWORD, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + iSubItem: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMLVGETINFOTIPA = *mut NMLVGETINFOTIPA; +STRUCT!{struct NMLVGETINFOTIPW { + hdr: ::NMHDR, + dwFlags: ::DWORD, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + iSubItem: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMLVGETINFOTIPW = *mut NMLVGETINFOTIPW; +pub const LVGIT_UNFOLDED: ::DWORD = 0x0001; +pub const LVN_GETINFOTIPA: ::UINT = LVN_FIRST - 57; +pub const LVN_GETINFOTIPW: ::UINT = LVN_FIRST - 58; +pub const LVNSCH_DEFAULT: ::LPARAM = -1; +pub const LVNSCH_ERROR: ::LPARAM = -2; +pub const LVNSCH_IGNORE: ::LPARAM = -3; +pub const LVN_INCREMENTALSEARCHA: ::UINT = LVN_FIRST - 62; +pub const LVN_INCREMENTALSEARCHW: ::UINT = LVN_FIRST - 63; +pub const LVN_COLUMNDROPDOWN: ::UINT = LVN_FIRST - 64; +pub const LVN_COLUMNOVERFLOWCLICK: ::UINT = LVN_FIRST - 66; +STRUCT!{struct NMLVSCROLL { + hdr: ::NMHDR, + dx: ::c_int, + dy: ::c_int, +}} +pub type LPNMLVSCROLL = *mut NMLVSCROLL; +pub const LVN_BEGINSCROLL: ::UINT = LVN_FIRST - 80; +pub const LVN_ENDSCROLL: ::UINT = LVN_FIRST - 81; +pub const LVN_LINKCLICK: ::UINT = LVN_FIRST - 84; +pub const EMF_CENTERED: ::DWORD = 0x00000001; +STRUCT!{nodebug struct NMLVEMPTYMARKUP { + hdr: ::NMHDR, + dwFlags: ::DWORD, + szMarkup: [::WCHAR; L_MAX_URL_LENGTH], +}} +pub const LVN_GETEMPTYMARKUP: ::UINT = LVN_FIRST - 87; +pub const TVS_HASBUTTONS: ::DWORD = 0x0001; +pub const TVS_HASLINES: ::DWORD = 0x0002; +pub const TVS_LINESATROOT: ::DWORD = 0x0004; +pub const TVS_EDITLABELS: ::DWORD = 0x0008; +pub const TVS_DISABLEDRAGDROP: ::DWORD = 0x0010; +pub const TVS_SHOWSELALWAYS: ::DWORD = 0x0020; +pub const TVS_RTLREADING: ::DWORD = 0x0040; +pub const TVS_NOTOOLTIPS: ::DWORD = 0x0080; +pub const TVS_CHECKBOXES: ::DWORD = 0x0100; +pub const TVS_TRACKSELECT: ::DWORD = 0x0200; +pub const TVS_SINGLEEXPAND: ::DWORD = 0x0400; +pub const TVS_INFOTIP: ::DWORD = 0x0800; +pub const TVS_FULLROWSELECT: ::DWORD = 0x1000; +pub const TVS_NOSCROLL: ::DWORD = 0x2000; +pub const TVS_NONEVENHEIGHT: ::DWORD = 0x4000; +pub const TVS_NOHSCROLL: ::DWORD = 0x8000; +pub const TVS_EX_NOSINGLECOLLAPSE: ::DWORD = 0x0001; +pub const TVS_EX_MULTISELECT: ::DWORD = 0x0002; +pub const TVS_EX_DOUBLEBUFFER: ::DWORD = 0x0004; +pub const TVS_EX_NOINDENTSTATE: ::DWORD = 0x0008; +pub const TVS_EX_RICHTOOLTIP: ::DWORD = 0x0010; +pub const TVS_EX_AUTOHSCROLL: ::DWORD = 0x0020; +pub const TVS_EX_FADEINOUTEXPANDOS: ::DWORD = 0x0040; +pub const TVS_EX_PARTIALCHECKBOXES: ::DWORD = 0x0080; +pub const TVS_EX_EXCLUSIONCHECKBOXES: ::DWORD = 0x0100; +pub const TVS_EX_DIMMEDCHECKBOXES: ::DWORD = 0x0200; +pub const TVS_EX_DRAWIMAGEASYNC: ::DWORD = 0x0400; +pub enum TREEITEM {} +pub type HTREEITEM = *mut TREEITEM; +pub const TVIF_TEXT: ::UINT = 0x0001; +pub const TVIF_IMAGE: ::UINT = 0x0002; +pub const TVIF_PARAM: ::UINT = 0x0004; +pub const TVIF_STATE: ::UINT = 0x0008; +pub const TVIF_HANDLE: ::UINT = 0x0010; +pub const TVIF_SELECTEDIMAGE: ::UINT = 0x0020; +pub const TVIF_CHILDREN: ::UINT = 0x0040; +pub const TVIF_INTEGRAL: ::UINT = 0x0080; +pub const TVIF_STATEEX: ::UINT = 0x0100; +pub const TVIF_EXPANDEDIMAGE: ::UINT = 0x0200; +pub const TVIS_SELECTED: ::UINT = 0x0002; +pub const TVIS_CUT: ::UINT = 0x0004; +pub const TVIS_DROPHILITED: ::UINT = 0x0008; +pub const TVIS_BOLD: ::UINT = 0x0010; +pub const TVIS_EXPANDED: ::UINT = 0x0020; +pub const TVIS_EXPANDEDONCE: ::UINT = 0x0040; +pub const TVIS_EXPANDPARTIAL: ::UINT = 0x0080; +pub const TVIS_OVERLAYMASK: ::UINT = 0x0F00; +pub const TVIS_STATEIMAGEMASK: ::UINT = 0xF000; +pub const TVIS_USERMASK: ::UINT = 0xF000; +pub const TVIS_EX_FLAT: ::UINT = 0x0001; +pub const TVIS_EX_DISABLED: ::UINT = 0x0002; +pub const TVIS_EX_ALL: ::UINT = 0x0002; +STRUCT!{struct NMTVSTATEIMAGECHANGING { + hdr: ::NMHDR, + hti: HTREEITEM, + iOldStateImageIndex: ::c_int, + iNewStateImageIndex: ::c_int, +}} +pub type LPNMTVSTATEIMAGECHANGING = *mut NMTVSTATEIMAGECHANGING; +pub const I_CHILDRENCALLBACK: ::c_int = -1; +pub const I_CHILDRENAUTO: ::c_int = -2; +pub type LPTV_ITEMW = LPTVITEMW; +pub type LPTV_ITEMA = LPTVITEMA; +pub type TV_ITEMW = TVITEMW; +pub type TV_ITEMA = TVITEMA; +STRUCT!{struct TVITEMA { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTVITEMA = *mut TVITEMA; +STRUCT!{struct TVITEMW { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTVITEMW = *mut TVITEMW; +STRUCT!{struct TVITEMEXA { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, + iIntegral: ::c_int, + uStateEx: ::UINT, + hwnd: ::HWND, + iExpandedImage: ::c_int, + iReserved: ::c_int, +}} +pub type LPTVITEMEXA = *mut TVITEMEXA; +STRUCT!{struct TVITEMEXW { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, + iIntegral: ::c_int, + uStateEx: ::UINT, + hwnd: ::HWND, + iExpandedImage: ::c_int, + iReserved: ::c_int, +}} +pub type LPTVITEMEXW = *mut TVITEMEXW; +pub const TVI_ROOT: HTREEITEM = (0 - 0x10000) as HTREEITEM; +pub const TVI_FIRST: HTREEITEM = (0 - 0x0FFFF) as HTREEITEM; +pub const TVI_LAST: HTREEITEM = (0 - 0x0FFFE) as HTREEITEM; +pub const TVI_SORT: HTREEITEM = (0 - 0x0FFFD) as HTREEITEM; +pub type LPTV_INSERTSTRUCTA = LPTVINSERTSTRUCTA; +pub type LPTV_INSERTSTRUCTW = LPTVINSERTSTRUCTW; +pub type TV_INSERTSTRUCTA = TVINSERTSTRUCTA; +pub type TV_INSERTSTRUCTW = TVINSERTSTRUCTW; +STRUCT!{struct TVINSERTSTRUCTA { + hParent: HTREEITEM, + hInsertAfter: HTREEITEM, + itemex: TVITEMEXA, +}} +UNION!(TVINSERTSTRUCTA, itemex, item, item_mut, TV_ITEMA); +pub type LPTVINSERTSTRUCTA = *mut TVINSERTSTRUCTA; +STRUCT!{struct TVINSERTSTRUCTW { + hParent: HTREEITEM, + hInsertAfter: HTREEITEM, + itemex: TVITEMEXW, +}} +UNION!(TVINSERTSTRUCTW, itemex, item, item_mut, TV_ITEMW); +pub type LPTVINSERTSTRUCTW = *mut TVINSERTSTRUCTW; +pub const TVM_INSERTITEMA: ::UINT = TV_FIRST + 0; +pub const TVM_INSERTITEMW: ::UINT = TV_FIRST + 50; +pub const TVM_DELETEITEM: ::UINT = TV_FIRST + 1; +pub const TVM_EXPAND: ::UINT = TV_FIRST + 2; +pub const TVM_GETITEMRECT: ::UINT = TV_FIRST + 4; +pub const TVE_COLLAPSE: ::WPARAM = 0x0001; +pub const TVE_EXPAND: ::WPARAM = 0x0002; +pub const TVE_TOGGLE: ::WPARAM = 0x0003; +pub const TVE_EXPANDPARTIAL: ::WPARAM = 0x4000; +pub const TVE_COLLAPSERESET: ::WPARAM = 0x8000; +pub const TVM_GETCOUNT: ::UINT = TV_FIRST + 5; +pub const TVM_GETINDENT: ::UINT = TV_FIRST + 6; +pub const TVM_SETINDENT: ::UINT = TV_FIRST + 7; +pub const TVM_GETIMAGELIST: ::UINT = TV_FIRST + 8; +pub const TVM_SETIMAGELIST: ::UINT = TV_FIRST + 9; +pub const TVM_GETNEXTITEM: ::UINT = TV_FIRST + 10; +pub const TVSIL_NORMAL: ::WPARAM = 0; +pub const TVSIL_STATE: ::WPARAM = 2; +pub const TVGN_ROOT: ::WPARAM = 0x0000; +pub const TVGN_NEXT: ::WPARAM = 0x0001; +pub const TVGN_PREVIOUS: ::WPARAM = 0x0002; +pub const TVGN_PARENT: ::WPARAM = 0x0003; +pub const TVGN_CHILD: ::WPARAM = 0x0004; +pub const TVGN_FIRSTVISIBLE: ::WPARAM = 0x0005; +pub const TVGN_NEXTVISIBLE: ::WPARAM = 0x0006; +pub const TVGN_PREVIOUSVISIBLE: ::WPARAM = 0x0007; +pub const TVGN_DROPHILITE: ::WPARAM = 0x0008; +pub const TVGN_CARET: ::WPARAM = 0x0009; +pub const TVGN_LASTVISIBLE: ::WPARAM = 0x000A; +pub const TVGN_NEXTSELECTED: ::WPARAM = 0x000B; +pub const TVSI_NOSINGLEEXPAND: ::WPARAM = 0x8000; +pub const TVM_SELECTITEM: ::UINT = TV_FIRST + 11; +pub const TVM_GETITEMA: ::UINT = TV_FIRST + 12; +pub const TVM_GETITEMW: ::UINT = TV_FIRST + 62; +pub const TVM_SETITEMA: ::UINT = TV_FIRST + 13; +pub const TVM_SETITEMW: ::UINT = TV_FIRST + 63; +pub const TVM_EDITLABELA: ::UINT = TV_FIRST + 14; +pub const TVM_EDITLABELW: ::UINT = TV_FIRST + 65; +pub const TVM_GETEDITCONTROL: ::UINT = TV_FIRST + 15; +pub const TVM_GETVISIBLECOUNT: ::UINT = TV_FIRST + 16; +pub const TVM_HITTEST: ::UINT = TV_FIRST + 17; +pub type LPTV_HITTESTINFO = LPTVHITTESTINFO; +pub type TV_HITTESTINFO = TVHITTESTINFO; +STRUCT!{struct TVHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + hItem: HTREEITEM, +}} +pub type LPTVHITTESTINFO = *mut TVHITTESTINFO; +pub const TVHT_NOWHERE: ::UINT = 0x0001; +pub const TVHT_ONITEMICON: ::UINT = 0x0002; +pub const TVHT_ONITEMLABEL: ::UINT = 0x0004; +pub const TVHT_ONITEM: ::UINT = TVHT_ONITEMICON | TVHT_ONITEMLABEL | TVHT_ONITEMSTATEICON; +pub const TVHT_ONITEMINDENT: ::UINT = 0x0008; +pub const TVHT_ONITEMBUTTON: ::UINT = 0x0010; +pub const TVHT_ONITEMRIGHT: ::UINT = 0x0020; +pub const TVHT_ONITEMSTATEICON: ::UINT = 0x0040; +pub const TVHT_ABOVE: ::UINT = 0x0100; +pub const TVHT_BELOW: ::UINT = 0x0200; +pub const TVHT_TORIGHT: ::UINT = 0x0400; +pub const TVHT_TOLEFT: ::UINT = 0x0800; +pub const TVM_CREATEDRAGIMAGE: ::UINT = TV_FIRST + 18; +pub const TVM_SORTCHILDREN: ::UINT = TV_FIRST + 19; +pub const TVM_ENSUREVISIBLE: ::UINT = TV_FIRST + 20; +pub const TVM_SORTCHILDRENCB: ::UINT = TV_FIRST + 21; +pub const TVM_ENDEDITLABELNOW: ::UINT = TV_FIRST + 22; +pub const TVM_GETISEARCHSTRINGA: ::UINT = TV_FIRST + 23; +pub const TVM_GETISEARCHSTRINGW: ::UINT = TV_FIRST + 64; +pub const TVM_SETTOOLTIPS: ::UINT = TV_FIRST + 24; +pub const TVM_GETTOOLTIPS: ::UINT = TV_FIRST + 25; +pub const TVM_SETINSERTMARK: ::UINT = TV_FIRST + 26; +pub const TVM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TVM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TVM_SETITEMHEIGHT: ::UINT = TV_FIRST + 27; +pub const TVM_GETITEMHEIGHT: ::UINT = TV_FIRST + 28; +pub const TVM_SETBKCOLOR: ::UINT = TV_FIRST + 29; +pub const TVM_SETTEXTCOLOR: ::UINT = TV_FIRST + 30; +pub const TVM_GETBKCOLOR: ::UINT = TV_FIRST + 31; +pub const TVM_GETTEXTCOLOR: ::UINT = TV_FIRST + 32; +pub const TVM_SETSCROLLTIME: ::UINT = TV_FIRST + 33; +pub const TVM_GETSCROLLTIME: ::UINT = TV_FIRST + 34; +pub const TVM_SETINSERTMARKCOLOR: ::UINT = TV_FIRST + 37; +pub const TVM_GETINSERTMARKCOLOR: ::UINT = TV_FIRST + 38; +pub const TVM_SETBORDER: ::UINT = TV_FIRST + 35; +pub const TVSBF_XBORDER: ::WPARAM = 0x00000001; +pub const TVSBF_YBORDER: ::WPARAM = 0x00000002; +pub const TVM_GETITEMSTATE: ::UINT = TV_FIRST + 39; +pub const TVM_SETLINECOLOR: ::UINT = TV_FIRST + 40; +pub const TVM_GETLINECOLOR: ::UINT = TV_FIRST + 41; +pub const TVM_MAPACCIDTOHTREEITEM: ::UINT = TV_FIRST + 42; +pub const TVM_MAPHTREEITEMTOACCID: ::UINT = TV_FIRST + 43; +pub const TVM_SETEXTENDEDSTYLE: ::UINT = TV_FIRST + 44; +pub const TVM_GETEXTENDEDSTYLE: ::UINT = TV_FIRST + 45; +pub const TVM_SETAUTOSCROLLINFO: ::UINT = TV_FIRST + 59; +pub const TVM_SETHOT: ::UINT = TV_FIRST + 58; +pub const TVM_GETSELECTEDCOUNT: ::UINT = TV_FIRST + 70; +pub const TVM_SHOWINFOTIP: ::UINT = TV_FIRST + 71; +ENUM!{enum TVITEMPART { + TVGIPR_BUTTON = 0x0001, +}} +STRUCT!{struct TVGETITEMPARTRECTINFO { + hti: HTREEITEM, + prc: *mut ::RECT, + partID: TVITEMPART, +}} +pub const TVM_GETITEMPARTRECT: ::UINT = TV_FIRST + 72; +pub type PFNTVCOMPARE = Option<unsafe extern "system" fn( + lParam1: ::LPARAM, lParam2: ::LPARAM, lParamSort: ::LPARAM, +) -> ::c_int>; +pub type LPTV_SORTCB = LPTVSORTCB; +pub type TV_SORTCB = TVSORTCB; +STRUCT!{nodebug struct TVSORTCB { + hParent: HTREEITEM, + lpfnCompare: PFNTVCOMPARE, + lParam: ::LPARAM, +}} +pub type LPTVSORTCB = *mut TVSORTCB; +pub type LPNM_TREEVIEWA = LPNMTREEVIEWA; +pub type LPNM_TREEVIEWW = LPNMTREEVIEWW; +pub type NM_TREEVIEWA = NMTREEVIEWA; +pub type NM_TREEVIEWW = NMTREEVIEWW; +STRUCT!{struct NMTREEVIEWA { + hdr: ::NMHDR, + action: ::UINT, + itemOld: TVITEMA, + itemNew: TVITEMA, + ptDrag: ::POINT, +}} +pub type LPNMTREEVIEWA = *mut NMTREEVIEWA; +STRUCT!{struct NMTREEVIEWW { + hdr: ::NMHDR, + action: ::UINT, + itemOld: TVITEMW, + itemNew: TVITEMW, + ptDrag: ::POINT, +}} +pub type LPNMTREEVIEWW = *mut NMTREEVIEWW; +pub const TVN_SELCHANGINGA: ::UINT = TVN_FIRST - 1; +pub const TVN_SELCHANGINGW: ::UINT = TVN_FIRST - 50; +pub const TVN_SELCHANGEDA: ::UINT = TVN_FIRST - 2; +pub const TVN_SELCHANGEDW: ::UINT = TVN_FIRST - 51; +pub const TVN_GETDISPINFOA: ::UINT = TVN_FIRST - 3; +pub const TVN_GETDISPINFOW: ::UINT = TVN_FIRST - 52; +pub const TVN_SETDISPINFOA: ::UINT = TVN_FIRST - 4; +pub const TVN_SETDISPINFOW: ::UINT = TVN_FIRST - 53; +pub const TVC_UNKNOWN: ::LPARAM = 0x0000; +pub const TVC_BYMOUSE: ::LPARAM = 0x0001; +pub const TVC_BYKEYBOARD: ::LPARAM = 0x0002; +pub const TVIF_DI_SETITEM: ::UINT = 0x1000; +pub type TV_DISPINFOA = NMTVDISPINFOA; +pub type TV_DISPINFOW = NMTVDISPINFOW; +STRUCT!{struct NMTVDISPINFOA { + hdr: ::NMHDR, + item: TVITEMA, +}} +pub type LPNMTVDISPINFOA = *mut NMTVDISPINFOA; +STRUCT!{struct NMTVDISPINFOW { + hdr: ::NMHDR, + item: TVITEMW, +}} +pub type LPNMTVDISPINFOW = *mut NMTVDISPINFOW; +STRUCT!{struct NMTVDISPINFOEXA { + hdr: ::NMHDR, + item: TVITEMEXA, +}} +pub type LPNMTVDISPINFOEXA = *mut NMTVDISPINFOEXA; +STRUCT!{struct NMTVDISPINFOEXW { + hdr: ::NMHDR, + item: TVITEMEXW, +}} +pub type LPNMTVDISPINFOEXW = *mut NMTVDISPINFOEXW; +pub type TV_DISPINFOEXA = NMTVDISPINFOEXA; +pub type TV_DISPINFOEXW = NMTVDISPINFOEXW; +pub const TVN_ITEMEXPANDINGA: ::UINT = TVN_FIRST - 5; +pub const TVN_ITEMEXPANDINGW: ::UINT = TVN_FIRST - 54; +pub const TVN_ITEMEXPANDEDA: ::UINT = TVN_FIRST - 6; +pub const TVN_ITEMEXPANDEDW: ::UINT = TVN_FIRST - 55; +pub const TVN_BEGINDRAGA: ::UINT = TVN_FIRST - 7; +pub const TVN_BEGINDRAGW: ::UINT = TVN_FIRST - 56; +pub const TVN_BEGINRDRAGA: ::UINT = TVN_FIRST - 8; +pub const TVN_BEGINRDRAGW: ::UINT = TVN_FIRST - 57; +pub const TVN_DELETEITEMA: ::UINT = TVN_FIRST - 9; +pub const TVN_DELETEITEMW: ::UINT = TVN_FIRST - 58; +pub const TVN_BEGINLABELEDITA: ::UINT = TVN_FIRST - 10; +pub const TVN_BEGINLABELEDITW: ::UINT = TVN_FIRST - 59; +pub const TVN_ENDLABELEDITA: ::UINT = TVN_FIRST - 11; +pub const TVN_ENDLABELEDITW: ::UINT = TVN_FIRST - 60; +pub const TVN_KEYDOWN: ::UINT = TVN_FIRST - 12; +pub const TVN_GETINFOTIPA: ::UINT = TVN_FIRST - 13; +pub const TVN_GETINFOTIPW: ::UINT = TVN_FIRST - 14; +pub const TVN_SINGLEEXPAND: ::UINT = TVN_FIRST - 15; +pub const TVN_ITEMCHANGINGA: ::UINT = TVN_FIRST - 16; +pub const TVN_ITEMCHANGINGW: ::UINT = TVN_FIRST - 17; +pub const TVN_ITEMCHANGEDA: ::UINT = TVN_FIRST - 18; +pub const TVN_ITEMCHANGEDW: ::UINT = TVN_FIRST - 19; +pub const TVN_ASYNCDRAW: ::UINT = TVN_FIRST - 20; +pub const TVNRET_DEFAULT: ::LRESULT = 0; +pub const TVNRET_SKIPOLD: ::LRESULT = 1; +pub const TVNRET_SKIPNEW: ::LRESULT = 2; +pub type TV_KEYDOWN = NMTVKEYDOWN; +STRUCT!{struct NMTVKEYDOWN { + hdr: ::NMHDR, + wVKey: ::WORD, + flags: ::UINT, +}} +pub type LPNMTVKEYDOWN = *mut NMTVKEYDOWN; +STRUCT!{struct NMTVCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + clrText: ::COLORREF, + clrTextBk: ::COLORREF, + iLevel: ::c_int, +}} +pub type LPNMTVCUSTOMDRAW = *mut NMTVCUSTOMDRAW; +STRUCT!{struct NMTVGETINFOTIPA { + hdr: ::NMHDR, + pszText: ::LPSTR, + cchTextMax: ::c_int, + hItem: HTREEITEM, + lParam: ::LPARAM, +}} +pub type LPNMTVGETINFOTIPA = *mut NMTVGETINFOTIPA; +STRUCT!{struct NMTVGETINFOTIPW { + hdr: ::NMHDR, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + hItem: HTREEITEM, + lParam: ::LPARAM, +}} +pub type LPNMTVGETINFOTIPW = *mut NMTVGETINFOTIPW; +pub const TVCDRF_NOIMAGES: ::LRESULT = 0x00010000; +STRUCT!{struct NMTVITEMCHANGE { + hdr: ::NMHDR, + uChanged: ::UINT, + hItem: HTREEITEM, + uStateNew: ::UINT, + uStateOld: ::UINT, + lParam: ::LPARAM, +}} +STRUCT!{struct NMTVASYNCDRAW { + hdr: ::NMHDR, + pimldp: *mut IMAGELISTDRAWPARAMS, + hr: ::HRESULT, + hItem: HTREEITEM, + lParam: ::LPARAM, + dwRetFlags: ::DWORD, + iRetImageIndex: ::c_int, +}} +pub const CBEIF_TEXT: ::UINT = 0x00000001; +pub const CBEIF_IMAGE: ::UINT = 0x00000002; +pub const CBEIF_SELECTEDIMAGE: ::UINT = 0x00000004; +pub const CBEIF_OVERLAY: ::UINT = 0x00000008; +pub const CBEIF_INDENT: ::UINT = 0x00000010; +pub const CBEIF_LPARAM: ::UINT = 0x00000020; +pub const CBEIF_DI_SETITEM: ::UINT = 0x10000000; +STRUCT!{struct COMBOBOXEXITEMA { + mask: ::UINT, + iItem: ::INT_PTR, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + iOverlay: ::c_int, + iIndent: ::c_int, + lParam: ::LPARAM, +}} +pub type PCOMBOBOXEXITEMA = *mut COMBOBOXEXITEMA; +pub type PCCOMBOBOXEXITEMA = *const COMBOBOXEXITEMA; +STRUCT!{struct COMBOBOXEXITEMW { + mask: ::UINT, + iItem: ::INT_PTR, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + iOverlay: ::c_int, + iIndent: ::c_int, + lParam: ::LPARAM, +}} +pub type PCOMBOBOXEXITEMW = *mut COMBOBOXEXITEMW; +pub type PCCOMBOBOXEXITEMW = *const COMBOBOXEXITEMW; +pub const CBEM_INSERTITEMA: ::UINT = ::WM_USER + 1; +pub const CBEM_SETIMAGELIST: ::UINT = ::WM_USER + 2; +pub const CBEM_GETIMAGELIST: ::UINT = ::WM_USER + 3; +pub const CBEM_GETITEMA: ::UINT = ::WM_USER + 4; +pub const CBEM_SETITEMA: ::UINT = ::WM_USER + 5; +pub const CBEM_DELETEITEM: ::UINT = ::CB_DELETESTRING; +pub const CBEM_GETCOMBOCONTROL: ::UINT = ::WM_USER + 6; +pub const CBEM_GETEDITCONTROL: ::UINT = ::WM_USER + 7; +pub const CBEM_SETEXSTYLE: ::UINT = ::WM_USER + 8; +pub const CBEM_SETEXTENDEDSTYLE: ::UINT = ::WM_USER + 14; +pub const CBEM_GETEXSTYLE: ::UINT = ::WM_USER + 9; +pub const CBEM_GETEXTENDEDSTYLE: ::UINT = ::WM_USER + 9; +pub const CBEM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const CBEM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const CBEM_HASEDITCHANGED: ::UINT = ::WM_USER + 10; +pub const CBEM_INSERTITEMW: ::UINT = ::WM_USER + 11; +pub const CBEM_SETITEMW: ::UINT = ::WM_USER + 12; +pub const CBEM_GETITEMW: ::UINT = ::WM_USER + 13; +pub const CBEM_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub const CBES_EX_NOEDITIMAGE: ::DWORD = 0x00000001; +pub const CBES_EX_NOEDITIMAGEINDENT: ::DWORD = 0x00000002; +pub const CBES_EX_PATHWORDBREAKPROC: ::DWORD = 0x00000004; +pub const CBES_EX_NOSIZELIMIT: ::DWORD = 0x00000008; +pub const CBES_EX_CASESENSITIVE: ::DWORD = 0x00000010; +pub const CBES_EX_TEXTENDELLIPSIS: ::DWORD = 0x00000020; +STRUCT!{struct NMCOMBOBOXEXA { + hdr: ::NMHDR, + ceItem: COMBOBOXEXITEMA, +}} +pub type PNMCOMBOBOXEXA = *mut NMCOMBOBOXEXA; +STRUCT!{struct NMCOMBOBOXEXW { + hdr: ::NMHDR, + ceItem: COMBOBOXEXITEMW, +}} +pub type PNMCOMBOBOXEXW = *mut NMCOMBOBOXEXW; +pub const CBEN_GETDISPINFOA: ::UINT = CBEN_FIRST - 0; +pub const CBEN_INSERTITEM: ::UINT = CBEN_FIRST - 1; +pub const CBEN_DELETEITEM: ::UINT = CBEN_FIRST - 2; +pub const CBEN_BEGINEDIT: ::UINT = CBEN_FIRST - 4; +pub const CBEN_ENDEDITA: ::UINT = CBEN_FIRST - 5; +pub const CBEN_ENDEDITW: ::UINT = CBEN_FIRST - 6; +pub const CBEN_GETDISPINFOW: ::UINT = CBEN_FIRST - 7; +pub const CBEN_DRAGBEGINA: ::UINT = CBEN_FIRST - 8; +pub const CBEN_DRAGBEGINW: ::UINT = CBEN_FIRST - 9; +pub const CBENF_KILLFOCUS: ::c_int = 1; +pub const CBENF_RETURN: ::c_int = 2; +pub const CBENF_ESCAPE: ::c_int = 3; +pub const CBENF_DROPDOWN: ::c_int = 4; +pub const CBEMAXSTRLEN: usize = 260; +STRUCT!{nodebug struct NMCBEDRAGBEGINW { + hdr: ::NMHDR, + iItemid: ::c_int, + szText: [::WCHAR; CBEMAXSTRLEN], +}} +pub type PNMCBEDRAGBEGINW = *mut NMCBEDRAGBEGINW; +pub type LPNMCBEDRAGBEGINW = *mut NMCBEDRAGBEGINW; +STRUCT!{nodebug struct NMCBEDRAGBEGINA { + hdr: ::NMHDR, + iItemid: ::c_int, + szText: [::c_char; CBEMAXSTRLEN], +}} +pub type PNMCBEDRAGBEGINA = *mut NMCBEDRAGBEGINA; +pub type LPNMCBEDRAGBEGINA = *mut NMCBEDRAGBEGINA; +STRUCT!{nodebug struct NMCBEENDEDITW { + hdr: ::NMHDR, + fChanged: ::BOOL, + iNewSelection: ::c_int, + szText: [::WCHAR; CBEMAXSTRLEN], + iWhy: ::c_int, +}} +pub type PNMCBEENDEDITW = *mut NMCBEENDEDITW; +pub type LPNMCBEENDEDITW = *mut NMCBEENDEDITW; +STRUCT!{nodebug struct NMCBEENDEDITA { + hdr: ::NMHDR, + fChanged: ::BOOL, + iNewSelection: ::c_int, + szText: [::c_char; CBEMAXSTRLEN], + iWhy: ::c_int, +}} +pub type PNMCBEENDEDITA = *mut NMCBEENDEDITA; +pub type LPNMCBEENDEDITA = *mut NMCBEENDEDITA; +pub const TCS_SCROLLOPPOSITE: ::DWORD = 0x0001; +pub const TCS_BOTTOM: ::DWORD = 0x0002; +pub const TCS_RIGHT: ::DWORD = 0x0002; +pub const TCS_MULTISELECT: ::DWORD = 0x0004; +pub const TCS_FLATBUTTONS: ::DWORD = 0x0008; +pub const TCS_FORCEICONLEFT: ::DWORD = 0x0010; +pub const TCS_FORCELABELLEFT: ::DWORD = 0x0020; +pub const TCS_HOTTRACK: ::DWORD = 0x0040; +pub const TCS_VERTICAL: ::DWORD = 0x0080; +pub const TCS_TABS: ::DWORD = 0x0000; +pub const TCS_BUTTONS: ::DWORD = 0x0100; +pub const TCS_SINGLELINE: ::DWORD = 0x0000; +pub const TCS_MULTILINE: ::DWORD = 0x0200; +pub const TCS_RIGHTJUSTIFY: ::DWORD = 0x0000; +pub const TCS_FIXEDWIDTH: ::DWORD = 0x0400; +pub const TCS_RAGGEDRIGHT: ::DWORD = 0x0800; +pub const TCS_FOCUSONBUTTONDOWN: ::DWORD = 0x1000; +pub const TCS_OWNERDRAWFIXED: ::DWORD = 0x2000; +pub const TCS_TOOLTIPS: ::DWORD = 0x4000; +pub const TCS_FOCUSNEVER: ::DWORD = 0x8000; +pub const TCS_EX_FLATSEPARATORS: ::DWORD = 0x00000001; +pub const TCS_EX_REGISTERDROP: ::DWORD = 0x00000002; +pub const TCM_GETIMAGELIST: ::UINT = TCM_FIRST + 2; +pub const TCM_SETIMAGELIST: ::UINT = TCM_FIRST + 3; +pub const TCM_GETITEMCOUNT: ::UINT = TCM_FIRST + 4; +pub const TCIF_TEXT: ::UINT = 0x0001; +pub const TCIF_IMAGE: ::UINT = 0x0002; +pub const TCIF_RTLREADING: ::UINT = 0x0004; +pub const TCIF_PARAM: ::UINT = 0x0008; +pub const TCIF_STATE: ::UINT = 0x0010; +pub const TCIS_BUTTONPRESSED: ::DWORD = 0x0001; +pub const TCIS_HIGHLIGHTED: ::DWORD = 0x0002; +pub type TC_ITEMHEADERA = TCITEMHEADERA; +pub type TC_ITEMHEADERW = TCITEMHEADERW; +STRUCT!{struct TCITEMHEADERA { + mask: ::UINT, + lpReserved1: ::UINT, + lpReserved2: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, +}} +pub type LPTCITEMHEADERA = *mut TCITEMHEADERA; +STRUCT!{struct TCITEMHEADERW { + mask: ::UINT, + lpReserved1: ::UINT, + lpReserved2: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, +}} +pub type LPTCITEMHEADERW = *mut TCITEMHEADERW; +pub type TC_ITEMA = TCITEMA; +pub type TC_ITEMW = TCITEMW; +STRUCT!{struct TCITEMA { + mask: ::UINT, + dwState: ::DWORD, + dwStateMask: ::DWORD, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTCITEMA = *mut TCITEMA; +STRUCT!{struct TCITEMW { + mask: ::UINT, + dwState: ::DWORD, + dwStateMask: ::DWORD, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTCITEMW = *mut TCITEMW; +pub const TCM_GETITEMA: ::UINT = TCM_FIRST + 5; +pub const TCM_GETITEMW: ::UINT = TCM_FIRST + 60; +pub const TCM_SETITEMA: ::UINT = TCM_FIRST + 6; +pub const TCM_SETITEMW: ::UINT = TCM_FIRST + 61; +pub const TCM_INSERTITEMA: ::UINT = TCM_FIRST + 7; +pub const TCM_INSERTITEMW: ::UINT = TCM_FIRST + 62; +pub const TCM_DELETEITEM: ::UINT = TCM_FIRST + 8; +pub const TCM_DELETEALLITEMS: ::UINT = TCM_FIRST + 9; +pub const TCM_GETITEMRECT: ::UINT = TCM_FIRST + 10; +pub const TCM_GETCURSEL: ::UINT = TCM_FIRST + 11; +pub const TCM_SETCURSEL: ::UINT = TCM_FIRST + 12; +pub const TCHT_NOWHERE: ::UINT = 0x0001; +pub const TCHT_ONITEMICON: ::UINT = 0x0002; +pub const TCHT_ONITEMLABEL: ::UINT = 0x0004; +pub const TCHT_ONITEM: ::UINT = TCHT_ONITEMICON | TCHT_ONITEMLABEL; +pub type LPTC_HITTESTINFO = LPTCHITTESTINFO; +pub type TC_HITTESTINFO = TCHITTESTINFO; +STRUCT!{struct TCHITTESTINFO { + pt: ::POINT, + flags: ::UINT, +}} +pub type LPTCHITTESTINFO = *mut TCHITTESTINFO; +pub const TCM_HITTEST: ::UINT = TCM_FIRST + 13; +pub const TCM_SETITEMEXTRA: ::UINT = TCM_FIRST + 14; +pub const TCM_ADJUSTRECT: ::UINT = TCM_FIRST + 40; +pub const TCM_SETITEMSIZE: ::UINT = TCM_FIRST + 41; +pub const TCM_REMOVEIMAGE: ::UINT = TCM_FIRST + 42; +pub const TCM_SETPADDING: ::UINT = TCM_FIRST + 43; +pub const TCM_GETROWCOUNT: ::UINT = TCM_FIRST + 44; +pub const TCM_GETTOOLTIPS: ::UINT = TCM_FIRST + 45; +pub const TCM_SETTOOLTIPS: ::UINT = TCM_FIRST + 46; +pub const TCM_GETCURFOCUS: ::UINT = TCM_FIRST + 47; +pub const TCM_SETCURFOCUS: ::UINT = TCM_FIRST + 48; +pub const TCM_SETMINTABWIDTH: ::UINT = TCM_FIRST + 49; +pub const TCM_DESELECTALL: ::UINT = TCM_FIRST + 50; +pub const TCM_HIGHLIGHTITEM: ::UINT = TCM_FIRST + 51; +pub const TCM_SETEXTENDEDSTYLE: ::UINT = TCM_FIRST + 52; +pub const TCM_GETEXTENDEDSTYLE: ::UINT = TCM_FIRST + 53; +pub const TCM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TCM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TCN_KEYDOWN: ::UINT = TCN_FIRST - 0; +pub type TC_KEYDOWN = NMTCKEYDOWN; +STRUCT!{struct NMTCKEYDOWN { + hdr: ::NMHDR, + wVKey: ::WORD, + flags: ::UINT, +}} +pub const TCN_SELCHANGE: ::UINT = TCN_FIRST - 1; +pub const TCN_SELCHANGING: ::UINT = TCN_FIRST - 2; +pub const TCN_GETOBJECT: ::UINT = TCN_FIRST - 3; +pub const TCN_FOCUSCHANGE: ::UINT = TCN_FIRST - 4; +pub const ACS_CENTER: ::DWORD = 0x0001; +pub const ACS_TRANSPARENT: ::DWORD = 0x0002; +pub const ACS_AUTOPLAY: ::DWORD = 0x0004; +pub const ACS_TIMER: ::DWORD = 0x0008; +pub const ACM_OPENA: ::UINT = ::WM_USER + 100; +pub const ACM_OPENW: ::UINT = ::WM_USER + 103; +pub const ACM_PLAY: ::UINT = ::WM_USER + 101; +pub const ACM_STOP: ::UINT = ::WM_USER + 102; +pub const ACM_ISPLAYING: ::UINT = ::WM_USER + 104; +pub const ACN_START: ::WPARAM = 1; +pub const ACN_STOP: ::WPARAM = 2; +pub type MONTHDAYSTATE = ::DWORD; +pub type LPMONTHDAYSTATE = *mut ::DWORD; +pub const MCM_FIRST: ::UINT = 0x1000; +pub const MCM_GETCURSEL: ::UINT = MCM_FIRST + 1; +pub const MCM_SETCURSEL: ::UINT = MCM_FIRST + 2; +pub const MCM_GETMAXSELCOUNT: ::UINT = MCM_FIRST + 3; +pub const MCM_SETMAXSELCOUNT: ::UINT = MCM_FIRST + 4; +pub const MCM_GETSELRANGE: ::UINT = MCM_FIRST + 5; +pub const MCM_SETSELRANGE: ::UINT = MCM_FIRST + 6; +pub const MCM_GETMONTHRANGE: ::UINT = MCM_FIRST + 7; +pub const MCM_SETDAYSTATE: ::UINT = MCM_FIRST + 8; +pub const MCM_GETMINREQRECT: ::UINT = MCM_FIRST + 9; +pub const MCM_SETCOLOR: ::UINT = MCM_FIRST + 10; +pub const MCM_GETCOLOR: ::UINT = MCM_FIRST + 11; +pub const MCM_SETTODAY: ::UINT = MCM_FIRST + 12; +pub const MCM_GETTODAY: ::UINT = MCM_FIRST + 13; +pub const MCM_HITTEST: ::UINT = MCM_FIRST + 14; +pub const MCSC_BACKGROUND: ::WPARAM = 0; +pub const MCSC_TEXT: ::WPARAM = 1; +pub const MCSC_TITLEBK: ::WPARAM = 2; +pub const MCSC_TITLETEXT: ::WPARAM = 3; +pub const MCSC_MONTHBK: ::WPARAM = 4; +pub const MCSC_TRAILINGTEXT: ::WPARAM = 5; +STRUCT!{struct MCHITTESTINFO { + cbSize: ::UINT, + pt: ::POINT, + uHit: ::UINT, + st: ::SYSTEMTIME, + rc: ::RECT, + iOffset: ::c_int, + iRow: ::c_int, + iCol: ::c_int, +}} +pub type PMCHITTESTINFO = *mut MCHITTESTINFO; +pub const MCHT_TITLE: ::UINT = 0x00010000; +pub const MCHT_CALENDAR: ::UINT = 0x00020000; +pub const MCHT_TODAYLINK: ::UINT = 0x00030000; +pub const MCHT_CALENDARCONTROL: ::UINT = 0x00100000; +pub const MCHT_NEXT: ::UINT = 0x01000000; +pub const MCHT_PREV: ::UINT = 0x02000000; +pub const MCHT_NOWHERE: ::UINT = 0x00000000; +pub const MCHT_TITLEBK: ::UINT = MCHT_TITLE; +pub const MCHT_TITLEMONTH: ::UINT = MCHT_TITLE | 0x0001; +pub const MCHT_TITLEYEAR: ::UINT = MCHT_TITLE | 0x0002; +pub const MCHT_TITLEBTNNEXT: ::UINT = MCHT_TITLE | MCHT_NEXT | 0x0003; +pub const MCHT_TITLEBTNPREV: ::UINT = MCHT_TITLE | MCHT_PREV | 0x0003; +pub const MCHT_CALENDARBK: ::UINT = MCHT_CALENDAR; +pub const MCHT_CALENDARDATE: ::UINT = MCHT_CALENDAR | 0x0001; +pub const MCHT_CALENDARDATENEXT: ::UINT = MCHT_CALENDARDATE | MCHT_NEXT; +pub const MCHT_CALENDARDATEPREV: ::UINT = MCHT_CALENDARDATE | MCHT_PREV; +pub const MCHT_CALENDARDAY: ::UINT = MCHT_CALENDAR | 0x0002; +pub const MCHT_CALENDARWEEKNUM: ::UINT = MCHT_CALENDAR | 0x0003; +pub const MCHT_CALENDARDATEMIN: ::UINT = MCHT_CALENDAR | 0x0004; +pub const MCHT_CALENDARDATEMAX: ::UINT = MCHT_CALENDAR | 0x0005; +pub const MCM_SETFIRSTDAYOFWEEK: ::UINT = MCM_FIRST + 15; +pub const MCM_GETFIRSTDAYOFWEEK: ::UINT = MCM_FIRST + 16; +pub const MCM_GETRANGE: ::UINT = MCM_FIRST + 17; +pub const MCM_SETRANGE: ::UINT = MCM_FIRST + 18; +pub const MCM_GETMONTHDELTA: ::UINT = MCM_FIRST + 19; +pub const MCM_SETMONTHDELTA: ::UINT = MCM_FIRST + 20; +pub const MCM_GETMAXTODAYWIDTH: ::UINT = MCM_FIRST + 21; +pub const MCM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const MCM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const MCM_GETCURRENTVIEW: ::UINT = MCM_FIRST + 22; +pub const MCM_GETCALENDARCOUNT: ::UINT = MCM_FIRST + 23; +pub const MCMV_MONTH: ::DWORD = 0; +pub const MCMV_YEAR: ::DWORD = 1; +pub const MCMV_DECADE: ::DWORD = 2; +pub const MCMV_CENTURY: ::DWORD = 3; +pub const MCMV_MAX: ::DWORD = MCMV_CENTURY; +pub const MCGIP_CALENDARCONTROL: ::DWORD = 0; +pub const MCGIP_NEXT: ::DWORD = 1; +pub const MCGIP_PREV: ::DWORD = 2; +pub const MCGIP_FOOTER: ::DWORD = 3; +pub const MCGIP_CALENDAR: ::DWORD = 4; +pub const MCGIP_CALENDARHEADER: ::DWORD = 5; +pub const MCGIP_CALENDARBODY: ::DWORD = 6; +pub const MCGIP_CALENDARROW: ::DWORD = 7; +pub const MCGIP_CALENDARCELL: ::DWORD = 8; +pub const MCGIF_DATE: ::DWORD = 0x00000001; +pub const MCGIF_RECT: ::DWORD = 0x00000002; +pub const MCGIF_NAME: ::DWORD = 0x00000004; +STRUCT!{struct MCGRIDINFO { + cbSize: ::UINT, + dwPart: ::DWORD, + dwFlags: ::DWORD, + iCalendar: ::c_int, + iRow: ::c_int, + iCol: ::c_int, + bSelected: ::BOOL, + stStart: ::SYSTEMTIME, + stEnd: ::SYSTEMTIME, + rc: ::RECT, + pszName: ::PWSTR, + cchName: ::size_t, +}} +pub type PMCGRIDINFO = *mut MCGRIDINFO; +pub const MCM_GETCALENDARGRIDINFO: ::UINT = MCM_FIRST + 24; +pub const MCM_GETCALID: ::UINT = MCM_FIRST + 27; +pub const MCM_SETCALID: ::UINT = MCM_FIRST + 28; +pub const MCM_SIZERECTTOMIN: ::UINT = MCM_FIRST + 29; +pub const MCM_SETCALENDARBORDER: ::UINT = MCM_FIRST + 30; +pub const MCM_GETCALENDARBORDER: ::UINT = MCM_FIRST + 31; +pub const MCM_SETCURRENTVIEW: ::UINT = MCM_FIRST + 32; +STRUCT!{struct NMSELCHANGE { + nmhdr: ::NMHDR, + stSelStart: ::SYSTEMTIME, + stSelEnd: ::SYSTEMTIME, +}} +pub type LPNMSELCHANGE = *mut NMSELCHANGE; +pub const MCN_SELCHANGE: ::UINT = MCN_FIRST - 3; +STRUCT!{struct NMDAYSTATE { + nmhdr: ::NMHDR, + stStart: ::SYSTEMTIME, + cDayState: ::c_int, + prgDayState: LPMONTHDAYSTATE, +}} +pub type LPNMDAYSTATE = *mut NMDAYSTATE; +pub const MCN_GETDAYSTATE: ::UINT = MCN_FIRST - 1; +pub type NMSELECT = NMSELCHANGE; +pub type LPNMSELECT = *mut NMSELCHANGE; +pub const MCN_SELECT: ::UINT = MCN_FIRST; +STRUCT!{struct NMVIEWCHANGE { + nmhdr: ::NMHDR, + dwOldView: ::DWORD, + dwNewView: ::DWORD, +}} +pub type LPNMVIEWCHANGE = *mut NMVIEWCHANGE; +pub const MCN_VIEWCHANGE: ::UINT = MCN_FIRST - 4; +pub const MCS_DAYSTATE: ::DWORD = 0x0001; +pub const MCS_MULTISELECT: ::DWORD = 0x0002; +pub const MCS_WEEKNUMBERS: ::DWORD = 0x0004; +pub const MCS_NOTODAYCIRCLE: ::DWORD = 0x0008; +pub const MCS_NOTODAY: ::DWORD = 0x0010; +pub const MCS_NOTRAILINGDATES: ::DWORD = 0x0040; +pub const MCS_SHORTDAYSOFWEEK: ::DWORD = 0x0080; +pub const MCS_NOSELCHANGEONNAV: ::DWORD = 0x0100; +pub const GMR_VISIBLE: ::DWORD = 0; +pub const GMR_DAYSTATE: ::DWORD = 1; +STRUCT!{struct DATETIMEPICKERINFO { + cbSize: ::UINT, + rcCheck: ::RECT, + stateCheck: ::DWORD, + rcButton: ::RECT, + stateButton: ::DWORD, + hwndEdit: ::HWND, + hwndUD: ::HWND, + hwndDropDown: ::HWND, +}} +pub type LPDATETIMEPICKERINFO = *mut DATETIMEPICKERINFO; +pub const DTM_FIRST: ::UINT = 0x1000; +pub const DTM_GETSYSTEMTIME: ::UINT = DTM_FIRST + 1; +pub const DTM_SETSYSTEMTIME: ::UINT = DTM_FIRST + 2; +pub const DTM_GETRANGE: ::UINT = DTM_FIRST + 3; +pub const DTM_SETRANGE: ::UINT = DTM_FIRST + 4; +pub const DTM_SETFORMATA: ::UINT = DTM_FIRST + 5; +pub const DTM_SETFORMATW: ::UINT = DTM_FIRST + 50; +pub const DTM_SETMCCOLOR: ::UINT = DTM_FIRST + 6; +pub const DTM_GETMCCOLOR: ::UINT = DTM_FIRST + 7; +pub const DTM_GETMONTHCAL: ::UINT = DTM_FIRST + 8; +pub const DTM_SETMCFONT: ::UINT = DTM_FIRST + 9; +pub const DTM_GETMCFONT: ::UINT = DTM_FIRST + 10; +pub const DTM_SETMCSTYLE: ::UINT = DTM_FIRST + 11; +pub const DTM_GETMCSTYLE: ::UINT = DTM_FIRST + 12; +pub const DTM_CLOSEMONTHCAL: ::UINT = DTM_FIRST + 13; +pub const DTM_GETDATETIMEPICKERINFO: ::UINT = DTM_FIRST + 14; +pub const DTM_GETIDEALSIZE: ::UINT = DTM_FIRST + 15; +pub const DTS_UPDOWN: ::DWORD = 0x0001; +pub const DTS_SHOWNONE: ::DWORD = 0x0002; +pub const DTS_SHORTDATEFORMAT: ::DWORD = 0x0000; +pub const DTS_LONGDATEFORMAT: ::DWORD = 0x0004; +pub const DTS_SHORTDATECENTURYFORMAT: ::DWORD = 0x000C; +pub const DTS_TIMEFORMAT: ::DWORD = 0x0009; +pub const DTS_APPCANPARSE: ::DWORD = 0x0010; +pub const DTS_RIGHTALIGN: ::DWORD = 0x0020; +pub const DTN_DATETIMECHANGE: ::UINT = DTN_FIRST2 - 6; +STRUCT!{struct NMDATETIMECHANGE { + nmhdr: ::NMHDR, + dwFlags: ::DWORD, + st: ::SYSTEMTIME, +}} +pub type LPNMDATETIMECHANGE = *mut NMDATETIMECHANGE; +pub const DTN_USERSTRINGA: ::UINT = DTN_FIRST2 - 5; +pub const DTN_USERSTRINGW: ::UINT = DTN_FIRST - 5; +STRUCT!{struct NMDATETIMESTRINGA { + nmhdr: ::NMHDR, + pszUserString: ::LPCSTR, + st: ::SYSTEMTIME, + dwFlags: ::DWORD, +}} +pub type LPNMDATETIMESTRINGA = *mut NMDATETIMESTRINGA; +STRUCT!{struct NMDATETIMESTRINGW { + nmhdr: ::NMHDR, + pszUserString: ::LPCWSTR, + st: ::SYSTEMTIME, + dwFlags: ::DWORD, +}} +pub type LPNMDATETIMESTRINGW = *mut NMDATETIMESTRINGW; +pub const DTN_WMKEYDOWNA: ::UINT = DTN_FIRST2 - 4; +pub const DTN_WMKEYDOWNW: ::UINT = DTN_FIRST - 4; +STRUCT!{struct NMDATETIMEWMKEYDOWNA { + nmhdr: ::NMHDR, + nVirtKey: ::c_int, + pszFormat: ::LPCSTR, + st: ::SYSTEMTIME, +}} +pub type LPNMDATETIMEWMKEYDOWNA = *mut NMDATETIMEWMKEYDOWNA; +STRUCT!{struct NMDATETIMEWMKEYDOWNW { + nmhdr: ::NMHDR, + nVirtKey: ::c_int, + pszFormat: ::LPCWSTR, + st: ::SYSTEMTIME, +}} +pub type LPNMDATETIMEWMKEYDOWNW = *mut NMDATETIMEWMKEYDOWNW; +pub const DTN_FORMATA: ::UINT = DTN_FIRST2 - 3; +pub const DTN_FORMATW: ::UINT = DTN_FIRST - 3; +STRUCT!{nodebug struct NMDATETIMEFORMATA { + nmhdr: ::NMHDR, + pszFormat: ::LPCSTR, + st: ::SYSTEMTIME, + pszDisplay: ::LPCSTR, + szDisplay: [::CHAR; 64], +}} +pub type LPNMDATETIMEFORMATA = *mut NMDATETIMEFORMATA; +STRUCT!{nodebug struct NMDATETIMEFORMATW { + nmhdr: ::NMHDR, + pszFormat: ::LPCWSTR, + st: ::SYSTEMTIME, + pszDisplay: ::LPCWSTR, + szDisplay: [::WCHAR; 64], +}} +pub type LPNMDATETIMEFORMATW = *mut NMDATETIMEFORMATW; +pub const DTN_FORMATQUERYA: ::UINT = DTN_FIRST2 - 2; +pub const DTN_FORMATQUERYW: ::UINT = DTN_FIRST - 2; +STRUCT!{struct NMDATETIMEFORMATQUERYA { + nmhdr: ::NMHDR, + pszFormat: ::LPCSTR, + szMax: ::SIZE, +}} +pub type LPNMDATETIMEFORMATQUERYA = *mut NMDATETIMEFORMATQUERYA; +STRUCT!{struct NMDATETIMEFORMATQUERYW { + nmhdr: ::NMHDR, + pszFormat: ::LPCWSTR, + szMax: ::SIZE, +}} +pub type LPNMDATETIMEFORMATQUERYW = *mut NMDATETIMEFORMATQUERYW; +pub const DTN_DROPDOWN: ::UINT = DTN_FIRST2 - 1; +pub const DTN_CLOSEUP: ::UINT = DTN_FIRST2; +pub const GDTR_MIN: ::WPARAM = 0x0001; +pub const GDTR_MAX: ::WPARAM = 0x0002; +pub const GDT_ERROR: ::LRESULT = -1; +pub const GDT_VALID: ::LRESULT = 0; +pub const GDT_NONE: ::LRESULT = 1; +pub const IPM_CLEARADDRESS: ::UINT = ::WM_USER + 100; +pub const IPM_SETADDRESS: ::UINT = ::WM_USER + 101; +pub const IPM_GETADDRESS: ::UINT = ::WM_USER + 102; +pub const IPM_SETRANGE: ::UINT = ::WM_USER + 103; +pub const IPM_SETFOCUS: ::UINT = ::WM_USER + 104; +pub const IPM_ISBLANK: ::UINT = ::WM_USER + 105; +pub const IPN_FIELDCHANGED: ::UINT = IPN_FIRST - 0; +STRUCT!{struct NMIPADDRESS { + hdr: ::NMHDR, + iField: ::c_int, + iValue: ::c_int, +}} +pub type LPNMIPADDRESS = *mut NMIPADDRESS; +#[inline] #[allow(dead_code)] +pub fn MAKEIPRANGE(low: ::BYTE, high: ::BYTE) -> ::LPARAM { + (high << 8 + low) as ::LPARAM +} +#[inline] #[allow(dead_code)] +pub fn MAKEIPADDRESS(b1: ::DWORD, b2: ::DWORD, b3: ::DWORD, b4: ::DWORD) -> ::LPARAM { + ((b1 << 24) + (b2 << 16) + (b3 << 8) + b4) as ::LPARAM +} +pub const PGS_VERT: ::DWORD = 0x00000000; +pub const PGS_HORZ: ::DWORD = 0x00000001; +pub const PGS_AUTOSCROLL: ::DWORD = 0x00000002; +pub const PGS_DRAGNDROP: ::DWORD = 0x00000004; +pub const PGF_INVISIBLE: ::DWORD = 0; +pub const PGF_NORMAL: ::DWORD = 1; +pub const PGF_GRAYED: ::DWORD = 2; +pub const PGF_DEPRESSED: ::DWORD = 4; +pub const PGF_HOT: ::DWORD = 8; +pub const PGB_TOPORLEFT: ::c_int = 0; +pub const PGB_BOTTOMORRIGHT: ::c_int = 1; +pub const PGM_SETCHILD: ::UINT = PGM_FIRST + 1; +pub const PGM_RECALCSIZE: ::UINT = PGM_FIRST + 2; +pub const PGM_FORWARDMOUSE: ::UINT = PGM_FIRST + 3; +pub const PGM_SETBKCOLOR: ::UINT = PGM_FIRST + 4; +pub const PGM_GETBKCOLOR: ::UINT = PGM_FIRST + 5; +pub const PGM_SETBORDER: ::UINT = PGM_FIRST + 6; +pub const PGM_GETBORDER: ::UINT = PGM_FIRST + 7; +pub const PGM_SETPOS: ::UINT = PGM_FIRST + 8; +pub const PGM_GETPOS: ::UINT = PGM_FIRST + 9; +pub const PGM_SETBUTTONSIZE: ::UINT = PGM_FIRST + 10; +pub const PGM_GETBUTTONSIZE: ::UINT = PGM_FIRST + 11; +pub const PGM_GETBUTTONSTATE: ::UINT = PGM_FIRST + 12; +pub const PGM_GETDROPTARGET: ::UINT = CCM_GETDROPTARGET; +pub const PGM_SETSCROLLINFO: ::UINT = PGM_FIRST + 13; +pub const PGN_SCROLL: ::UINT = PGN_FIRST - 1; +pub const PGF_SCROLLUP: ::c_int = 1; +pub const PGF_SCROLLDOWN: ::c_int = 2; +pub const PGF_SCROLLLEFT: ::c_int = 4; +pub const PGF_SCROLLRIGHT: ::c_int = 8; +pub const PGK_SHIFT: ::BOOL = 1; +pub const PGK_CONTROL: ::BOOL = 2; +pub const PGK_MENU: ::BOOL = 4; +STRUCT!{struct NMPGSCROLL { + hdr: ::NMHDR, + fwKeys: ::BOOL, + rcParent: ::RECT, + iDir: ::c_int, + iXpos: ::c_int, + iYpos: ::c_int, + iScroll: ::c_int, +}} +pub type LPNMPGSCROLL = *mut NMPGSCROLL; +pub const PGN_CALCSIZE: ::UINT = PGN_FIRST - 2; +pub const PGF_CALCWIDTH: ::DWORD = 1; +pub const PGF_CALCHEIGHT: ::DWORD = 2; +STRUCT!{struct NMPGCALCSIZE { + hdr: ::NMHDR, + dwFlag: ::DWORD, + iWidth: ::c_int, + iHeight: ::c_int, +}} +pub type LPNMPGCALCSIZE = *mut NMPGCALCSIZE; +pub const PGN_HOTITEMCHANGE: ::UINT = PGN_FIRST - 3; +STRUCT!{struct NMPGHOTITEM { + hdr: ::NMHDR, + idOld: ::c_int, + idNew: ::c_int, + dwFlags: ::DWORD, +}} +pub type LPNMPGHOTITEM = *mut NMPGHOTITEM; +pub const NFS_EDIT: ::DWORD = 0x0001; +pub const NFS_STATIC: ::DWORD = 0x0002; +pub const NFS_LISTCOMBO: ::DWORD = 0x0004; +pub const NFS_BUTTON: ::DWORD = 0x0008; +pub const NFS_ALL: ::DWORD = 0x0010; +pub const NFS_USEFONTASSOC: ::DWORD = 0x0020; +pub const BUTTON_IMAGELIST_ALIGN_LEFT: ::UINT = 0; +pub const BUTTON_IMAGELIST_ALIGN_RIGHT: ::UINT = 1; +pub const BUTTON_IMAGELIST_ALIGN_TOP: ::UINT = 2; +pub const BUTTON_IMAGELIST_ALIGN_BOTTOM: ::UINT = 3; +pub const BUTTON_IMAGELIST_ALIGN_CENTER: ::UINT = 4; +STRUCT!{struct BUTTON_IMAGELIST { + himl: HIMAGELIST, + margin: ::RECT, + uAlign: ::UINT, +}} +pub type PBUTTON_IMAGELIST = *mut BUTTON_IMAGELIST; +pub const BCM_GETIDEALSIZE: ::UINT = BCM_FIRST + 0x0001; +pub const BCM_SETIMAGELIST: ::UINT = BCM_FIRST + 0x0002; +pub const BCM_GETIMAGELIST: ::UINT = BCM_FIRST + 0x0003; +pub const BCM_SETTEXTMARGIN: ::UINT = BCM_FIRST + 0x0004; +pub const BCM_GETTEXTMARGIN: ::UINT = BCM_FIRST + 0x0005; +STRUCT!{struct NMBCHOTITEM { + hdr: ::NMHDR, + dwFlags: ::DWORD, +}} +pub type LPNMBCHOTITEM = *mut NMBCHOTITEM; +pub const BCN_HOTITEMCHANGE: ::UINT = BCN_FIRST + 0x0001; +pub const BS_SPLITBUTTON: ::UINT = 0x0000000C; +pub const BS_DEFSPLITBUTTON: ::UINT = 0x0000000D; +pub const BS_COMMANDLINK: ::UINT = 0x0000000E; +pub const BS_DEFCOMMANDLINK: ::UINT = 0x0000000F; +pub const BCSIF_GLYPH: ::UINT = 0x0001; +pub const BCSIF_IMAGE: ::UINT = 0x0002; +pub const BCSIF_STYLE: ::UINT = 0x0004; +pub const BCSIF_SIZE: ::UINT = 0x0008; +pub const BCSS_NOSPLIT: ::UINT = 0x0001; +pub const BCSS_STRETCH: ::UINT = 0x0002; +pub const BCSS_ALIGNLEFT: ::UINT = 0x0004; +pub const BCSS_IMAGE: ::UINT = 0x0008; +STRUCT!{struct BUTTON_SPLITINFO { + mask: ::UINT, + himlGlyph: HIMAGELIST, + uSplitStyle: ::UINT, + size: ::SIZE, +}} +pub type PBUTTON_SPLITINFO = *mut BUTTON_SPLITINFO; +pub const BCM_SETDROPDOWNSTATE: ::UINT = BCM_FIRST + 0x0006; +pub const BCM_SETSPLITINFO: ::UINT = BCM_FIRST + 0x0007; +pub const BCM_GETSPLITINFO: ::UINT = BCM_FIRST + 0x0008; +pub const BCM_SETNOTE: ::UINT = BCM_FIRST + 0x0009; +pub const BCM_GETNOTE: ::UINT = BCM_FIRST + 0x000A; +pub const BCM_GETNOTELENGTH: ::UINT = BCM_FIRST + 0x000B; +pub const BCM_SETSHIELD: ::UINT = BCM_FIRST + 0x000C; +pub const BCCL_NOGLYPH: HIMAGELIST = (0 - 1) as HIMAGELIST; +STRUCT!{struct NMBCDROPDOWN { + hdr: ::NMHDR, + rcButton: ::RECT, +}} +pub type LPNMBCDROPDOWN = *mut NMBCDROPDOWN; +pub const BCN_DROPDOWN: ::UINT = BCN_FIRST + 0x0002; +pub const EM_SETCUEBANNER: ::UINT = ECM_FIRST + 1; +pub const EM_GETCUEBANNER: ::UINT = ECM_FIRST + 2; +pub const EM_SHOWBALLOONTIP: ::UINT = ECM_FIRST + 3; +pub const EM_HIDEBALLOONTIP: ::UINT = ECM_FIRST + 4; +pub const EM_SETHILITE: ::UINT = ECM_FIRST + 5; +pub const EM_GETHILITE: ::UINT = ECM_FIRST + 6; +pub const EM_NOSETFOCUS: ::UINT = ECM_FIRST + 7; +pub const EM_TAKEFOCUS: ::UINT = ECM_FIRST + 8; +STRUCT!{struct EDITBALLOONTIP { + cbStruct: ::DWORD, + pszTitle: ::LPCWSTR, + pszText: ::LPCWSTR, + ttiIcon: ::INT, +}} +pub type PEDITBALLOONTIP = *mut EDITBALLOONTIP; +pub const CB_SETMINVISIBLE: ::UINT = CBM_FIRST + 1; +pub const CB_GETMINVISIBLE: ::UINT = CBM_FIRST + 2; +pub const CB_SETCUEBANNER: ::UINT = CBM_FIRST + 3; +pub const CB_GETCUEBANNER: ::UINT = CBM_FIRST + 4; +pub type PFTASKDIALOGCALLBACK = Option<unsafe extern "system" fn( + hwnd: ::HWND, msg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM, lpRefData: ::LONG_PTR, +) -> ::HRESULT>; +FLAGS!{enum TASKDIALOG_FLAGS { + TDF_ENABLE_HYPERLINKS = 0x0001, + TDF_USE_HICON_MAIN = 0x0002, + TDF_USE_HICON_FOOTER = 0x0004, + TDF_ALLOW_DIALOG_CANCELLATION = 0x0008, + TDF_USE_COMMAND_LINKS = 0x0010, + TDF_USE_COMMAND_LINKS_NO_ICON = 0x0020, + TDF_EXPAND_FOOTER_AREA = 0x0040, + TDF_EXPANDED_BY_DEFAULT = 0x0080, + TDF_VERIFICATION_FLAG_CHECKED = 0x0100, + TDF_SHOW_PROGRESS_BAR = 0x0200, + TDF_SHOW_MARQUEE_PROGRESS_BAR = 0x0400, + TDF_CALLBACK_TIMER = 0x0800, + TDF_POSITION_RELATIVE_TO_WINDOW = 0x1000, + TDF_RTL_LAYOUT = 0x2000, + TDF_NO_DEFAULT_RADIO_BUTTON = 0x4000, + TDF_CAN_BE_MINIMIZED = 0x8000, + TDF_NO_SET_FOREGROUND = 0x00010000, + TDF_SIZE_TO_CONTENT = 0x01000000, +}} +ENUM!{enum TASKDIALOG_MESSAGES { + TDM_NAVIGATE_PAGE = ::WM_USER + 101, + TDM_CLICK_BUTTON = ::WM_USER + 102, + TDM_SET_MARQUEE_PROGRESS_BAR = ::WM_USER + 103, + TDM_SET_PROGRESS_BAR_STATE = ::WM_USER + 104, + TDM_SET_PROGRESS_BAR_RANGE = ::WM_USER + 105, + TDM_SET_PROGRESS_BAR_POS = ::WM_USER + 106, + TDM_SET_PROGRESS_BAR_MARQUEE = ::WM_USER + 107, + TDM_SET_ELEMENT_TEXT = ::WM_USER + 108, + TDM_CLICK_RADIO_BUTTON = ::WM_USER + 110, + TDM_ENABLE_BUTTON = ::WM_USER + 111, + TDM_ENABLE_RADIO_BUTTON = ::WM_USER + 112, + TDM_CLICK_VERIFICATION = ::WM_USER + 113, + TDM_UPDATE_ELEMENT_TEXT = ::WM_USER + 114, + TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = ::WM_USER + 115, + TDM_UPDATE_ICON = ::WM_USER + 116, +}} +ENUM!{enum TASKDIALOG_NOTIFICATIONS { + TDN_CREATED = 0, + TDN_NAVIGATED = 1, + TDN_BUTTON_CLICKED = 2, + TDN_HYPERLINK_CLICKED = 3, + TDN_TIMER = 4, + TDN_DESTROYED = 5, + TDN_RADIO_BUTTON_CLICKED = 6, + TDN_DIALOG_CONSTRUCTED = 7, + TDN_VERIFICATION_CLICKED = 8, + TDN_HELP = 9, + TDN_EXPANDO_BUTTON_CLICKED = 10, +}} +STRUCT!{struct TASKDIALOG_BUTTON { + nButtonID: ::c_int, + pszButtonText: ::PCWSTR, +}} +ENUM!{enum TASKDIALOG_ELEMENTS { + TDE_CONTENT, + TDE_EXPANDED_INFORMATION, + TDE_FOOTER, + TDE_MAIN_INSTRUCTION, +}} +ENUM!{enum TASKDIALOG_ICON_ELEMENTS { + TDIE_ICON_MAIN, + TDIE_ICON_FOOTER, +}} +FLAGS!{enum TASKDIALOG_COMMON_BUTTON_FLAGS { + TDCBF_OK_BUTTON = 0x0001, + TDCBF_YES_BUTTON = 0x0002, + TDCBF_NO_BUTTON = 0x0004, + TDCBF_CANCEL_BUTTON = 0x0008, + TDCBF_RETRY_BUTTON = 0x0010, + TDCBF_CLOSE_BUTTON = 0x0020, +}} +STRUCT!{nodebug struct TASKDIALOGCONFIG { + cbSize: ::UINT, + hwndParent: ::HWND, + hInstance: ::HINSTANCE, + dwFlags: TASKDIALOG_FLAGS, + dwCommonButtons: TASKDIALOG_COMMON_BUTTON_FLAGS, + pszWindowTitle: ::PCWSTR, + hMainIcon: ::HICON, + pszMainInstruction: ::PCWSTR, + pszContent: ::PCWSTR, + cButtons: ::UINT, + pButtons: *const TASKDIALOG_BUTTON, + nDefaultButton: ::c_int, + cRadioButtons: ::UINT, + pRadioButtons: *const TASKDIALOG_BUTTON, + nDefaultRadioButton: ::c_int, + pszVerificationText: ::PCWSTR, + pszExpandedInformation: ::PCWSTR, + pszExpandedControlText: ::PCWSTR, + pszCollapsedControlText: ::PCWSTR, + hFooterIcon: ::HICON, + pszFooter: ::PCWSTR, + pfCallback: PFTASKDIALOGCALLBACK, + lpCallbackData: ::LONG_PTR, + cxWidth: ::UINT, +}} +UNION!(TASKDIALOGCONFIG, hMainIcon, pszMainIcon, pszMainIcon_mut, ::PCWSTR); +UNION!(TASKDIALOGCONFIG, hFooterIcon, pszFooterIcon, pszFooterIcon_mut, ::PCWSTR); +pub const DA_LAST: ::c_int = 0x7FFFFFFF; +pub const DA_ERR: ::c_int = -1; +pub type PFNDAENUMCALLBACK = Option<unsafe extern "system" fn( + p: *mut ::c_void, pData: *mut ::c_void, +) -> ::c_int>; +pub type PFNDAENUMCALLBACKCONST = Option<unsafe extern "system" fn( + p: *const ::c_void, pData: *mut ::c_void, +) -> ::c_int>; +pub type PFNDACOMPARE = Option<unsafe extern "system" fn( + p1: *mut ::c_void, p2: *mut ::c_void, lParam: ::LPARAM, +) -> ::c_int>; +pub type PFNDACOMPARECONST = Option<unsafe extern "system" fn( + p1: *const ::c_void, p2: *const ::c_void, lParam: ::LPARAM, +) -> ::c_int>; +pub enum DSA {} +pub type HDSA = *mut DSA; +pub const DSA_APPEND: ::c_int = DA_LAST; +pub const DSA_ERR: ::c_int = DA_ERR; +pub type PFNDSAENUMCALLBACK = PFNDAENUMCALLBACK; +pub type PFNDSAENUMCALLBACKCONST = PFNDAENUMCALLBACKCONST; +pub type PFNDSACOMPARE = PFNDACOMPARE; +pub type PFNDSACOMPARECONST = PFNDACOMPARECONST; +pub enum DPA {} +pub type HDPA = *mut DPA; +STRUCT!{struct DPASTREAMINFO { + iPos: ::c_int, + pvItem: *mut ::c_void, +}} +pub type PFNDPASTREAM = Option<unsafe extern "system" fn( + pinfo: *mut DPASTREAMINFO, pstream: *mut ::IStream, pvInstData: *mut ::c_void, +) -> ::HRESULT>; +pub const DPAM_SORTED: ::DWORD = 0x00000001; +pub const DPAM_NORMAL: ::DWORD = 0x00000002; +pub const DPAM_UNION: ::DWORD = 0x00000004; +pub const DPAM_INTERSECT: ::DWORD = 0x00000008; +pub type PFNDPAMERGE = Option<unsafe extern "system" fn( + uMsg: ::UINT, pvDest: *mut ::c_void, pvSrc: *mut ::c_void, lParam: ::LPARAM, +) -> *mut ::c_void>; +pub type PFNDPAMERGECONST = Option<unsafe extern "system" fn( + uMsg: ::UINT, pvDest: *const ::c_void, pvSrc: *const ::c_void, lParam: ::LPARAM, +) -> *const ::c_void>; +pub const DPAMM_MERGE: ::UINT = 1; +pub const DPAMM_DELETE: ::UINT = 2; +pub const DPAMM_INSERT: ::UINT = 3; +pub const DPAS_SORTED: ::UINT = 0x0001; +pub const DPAS_INSERTBEFORE: ::UINT = 0x0002; +pub const DPAS_INSERTAFTER: ::UINT = 0x0004; +pub const DPA_APPEND: ::c_int = DA_LAST; +pub const DPA_ERR: ::c_int = DA_ERR; +pub type PFNDPAENUMCALLBACK = PFNDAENUMCALLBACK; +pub type PFNDPAENUMCALLBACKCONST = PFNDAENUMCALLBACKCONST; +pub type PFNDPACOMPARE = PFNDACOMPARE; +pub type PFNDPACOMPARECONST = PFNDACOMPARECONST; +pub const WSB_PROP_CYVSCROLL: ::UINT = 0x00000001; +pub const WSB_PROP_CXHSCROLL: ::UINT = 0x00000002; +pub const WSB_PROP_CYHSCROLL: ::UINT = 0x00000004; +pub const WSB_PROP_CXVSCROLL: ::UINT = 0x00000008; +pub const WSB_PROP_CXHTHUMB: ::UINT = 0x00000010; +pub const WSB_PROP_CYVTHUMB: ::UINT = 0x00000020; +pub const WSB_PROP_VBKGCOLOR: ::UINT = 0x00000040; +pub const WSB_PROP_HBKGCOLOR: ::UINT = 0x00000080; +pub const WSB_PROP_VSTYLE: ::UINT = 0x00000100; +pub const WSB_PROP_HSTYLE: ::UINT = 0x00000200; +pub const WSB_PROP_WINSTYLE: ::UINT = 0x00000400; +pub const WSB_PROP_PALETTE: ::UINT = 0x00000800; +pub const WSB_PROP_MASK: ::UINT = 0x00000FFF; +pub const FSB_FLAT_MODE: ::INT_PTR = 2; +pub const FSB_ENCARTA_MODE: ::INT_PTR = 1; +pub const FSB_REGULAR_MODE: ::INT_PTR = 0; +pub type SUBCLASSPROC = Option<unsafe extern "system" fn( + hWnd: ::HWND, uMsg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM, uIdSubclass: ::UINT_PTR, + dwRefData: ::DWORD_PTR, +) -> ::LRESULT>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/commdlg.rs b/bash-5.1/vendor/winapi-0.2.8/src/commdlg.rs new file mode 100644 index 0000000..0eb3fd8 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/commdlg.rs @@ -0,0 +1,583 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! 32-Bit Common Dialog APIs +pub type LPOFNHOOKPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +STRUCT!{nodebug struct OPENFILENAME_NT4A { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCSTR, + lpstrCustomFilter: ::LPSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCSTR, + lpstrTitle: ::LPCSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCSTR, +}} +pub type LPOPENFILENAME_NT4A = *mut OPENFILENAME_NT4A; +STRUCT!{nodebug struct OPENFILENAME_NT4W { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCWSTR, + lpstrCustomFilter: ::LPWSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPWSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPWSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCWSTR, + lpstrTitle: ::LPCWSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCWSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCWSTR, +}} +pub type LPOPENFILENAME_NT4W = *mut OPENFILENAME_NT4W; +STRUCT!{nodebug struct OPENFILENAMEA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCSTR, + lpstrCustomFilter: ::LPSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCSTR, + lpstrTitle: ::LPCSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCSTR, + pvReserved: *mut ::c_void, + dwReserved: ::DWORD, + FlagsEx: ::DWORD, +}} +pub type LPOPENFILENAMEA = *mut OPENFILENAMEA; +STRUCT!{nodebug struct OPENFILENAMEW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCWSTR, + lpstrCustomFilter: ::LPWSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPWSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPWSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCWSTR, + lpstrTitle: ::LPCWSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCWSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCWSTR, + pvReserved: *mut ::c_void, + dwReserved: ::DWORD, + FlagsEx: ::DWORD, +}} +pub type LPOPENFILENAMEW = *mut OPENFILENAMEW; +pub const OFN_READONLY: ::DWORD = 0x00000001; +pub const OFN_OVERWRITEPROMPT: ::DWORD = 0x00000002; +pub const OFN_HIDEREADONLY: ::DWORD = 0x00000004; +pub const OFN_NOCHANGEDIR: ::DWORD = 0x00000008; +pub const OFN_SHOWHELP: ::DWORD = 0x00000010; +pub const OFN_ENABLEHOOK: ::DWORD = 0x00000020; +pub const OFN_ENABLETEMPLATE: ::DWORD = 0x00000040; +pub const OFN_ENABLETEMPLATEHANDLE: ::DWORD = 0x00000080; +pub const OFN_NOVALIDATE: ::DWORD = 0x00000100; +pub const OFN_ALLOWMULTISELECT: ::DWORD = 0x00000200; +pub const OFN_EXTENSIONDIFFERENT: ::DWORD = 0x00000400; +pub const OFN_PATHMUSTEXIST: ::DWORD = 0x00000800; +pub const OFN_FILEMUSTEXIST: ::DWORD = 0x00001000; +pub const OFN_CREATEPROMPT: ::DWORD = 0x00002000; +pub const OFN_SHAREAWARE: ::DWORD = 0x00004000; +pub const OFN_NOREADONLYRETURN: ::DWORD = 0x00008000; +pub const OFN_NOTESTFILECREATE: ::DWORD = 0x00010000; +pub const OFN_NONETWORKBUTTON: ::DWORD = 0x00020000; +pub const OFN_NOLONGNAMES: ::DWORD = 0x00040000; +pub const OFN_EXPLORER: ::DWORD = 0x00080000; +pub const OFN_NODEREFERENCELINKS: ::DWORD = 0x00100000; +pub const OFN_LONGNAMES: ::DWORD = 0x00200000; +pub const OFN_ENABLEINCLUDENOTIFY: ::DWORD = 0x00400000; +pub const OFN_ENABLESIZING: ::DWORD = 0x00800000; +pub const OFN_DONTADDTORECENT: ::DWORD = 0x02000000; +pub const OFN_FORCESHOWHIDDEN: ::DWORD = 0x10000000; +pub const OFN_EX_NOPLACESBAR: ::DWORD = 0x00000001; +pub const OFN_SHAREFALLTHROUGH: ::UINT_PTR = 2; +pub const OFN_SHARENOWARN: ::UINT_PTR = 1; +pub const OFN_SHAREWARN: ::UINT_PTR = 0; +pub type LPCCHOOKPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +STRUCT!{struct OFNOTIFYA { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEA, + pszFile: ::LPSTR, +}} +pub type LPOFNOTIFYA = *mut OFNOTIFYA; +STRUCT!{struct OFNOTIFYW { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEW, + pszFile: ::LPWSTR, +}} +pub type LPOFNOTIFYW = *mut OFNOTIFYW; +STRUCT!{struct OFNOTIFYEXA { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEA, + psf: ::LPVOID, + pidl: ::LPVOID, +}} +pub type LPOFNOTIFYEXA = *mut OFNOTIFYEXA; +STRUCT!{struct OFNOTIFYEXW { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEW, + psf: ::LPVOID, + pidl: ::LPVOID, +}} +pub type LPOFNOTIFYEXW = *mut OFNOTIFYEXW; +pub const CDN_FIRST: ::UINT = -601i32 as ::UINT; +pub const CDN_LAST: ::UINT = -699i32 as ::UINT; +pub const CDN_INITDONE: ::UINT = CDN_FIRST - 0x0000; +pub const CDN_SELCHANGE: ::UINT = CDN_FIRST - 0x0001; +pub const CDN_FOLDERCHANGE: ::UINT = CDN_FIRST - 0x0002; +pub const CDN_SHAREVIOLATION: ::UINT = CDN_FIRST - 0x0003; +pub const CDN_HELP: ::UINT = CDN_FIRST - 0x0004; +pub const CDN_FILEOK: ::UINT = CDN_FIRST - 0x0005; +pub const CDN_TYPECHANGE: ::UINT = CDN_FIRST - 0x0006; +pub const CDN_INCLUDEITEM: ::UINT = CDN_FIRST - 0x0007; +pub const CDM_FIRST: ::UINT = ::WM_USER + 100; +pub const CDM_LAST: ::UINT = ::WM_USER + 200; +pub const CDM_GETSPEC: ::UINT = CDM_FIRST + 0x0000; +pub const CDM_GETFILEPATH: ::UINT = CDM_FIRST + 0x0001; +pub const CDM_GETFOLDERPATH: ::UINT = CDM_FIRST + 0x0002; +pub const CDM_GETFOLDERIDLIST: ::UINT = CDM_FIRST + 0x0003; +pub const CDM_SETCONTROLTEXT: ::UINT = CDM_FIRST + 0x0004; +pub const CDM_HIDECONTROL: ::UINT = CDM_FIRST + 0x0005; +pub const CDM_SETDEFEXT: ::UINT = CDM_FIRST + 0x0006; +STRUCT!{nodebug struct CHOOSECOLORA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HWND, + rgbResult: ::COLORREF, + lpCustColors: *mut ::COLORREF, + Flags: ::DWORD, + lCustData: ::LPARAM, + lpfnHook: LPCCHOOKPROC, + lpTemplateName: ::LPCSTR, +}} +pub type LPCHOOSECOLORA = *mut CHOOSECOLORA; +STRUCT!{nodebug struct CHOOSECOLORW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HWND, + rgbResult: ::COLORREF, + lpCustColors: *mut ::COLORREF, + Flags: ::DWORD, + lCustData: ::LPARAM, + lpfnHook: LPCCHOOKPROC, + lpTemplateName: ::LPCWSTR, +}} +pub type LPCHOOSECOLORW = *mut CHOOSECOLORW; +pub const CC_RGBINIT: ::DWORD = 0x00000001; +pub const CC_FULLOPEN: ::DWORD = 0x00000002; +pub const CC_PREVENTFULLOPEN: ::DWORD = 0x00000004; +pub const CC_SHOWHELP: ::DWORD = 0x00000008; +pub const CC_ENABLEHOOK: ::DWORD = 0x00000010; +pub const CC_ENABLETEMPLATE: ::DWORD = 0x00000020; +pub const CC_ENABLETEMPLATEHANDLE: ::DWORD = 0x00000040; +pub const CC_SOLIDCOLOR: ::DWORD = 0x00000080; +pub const CC_ANYCOLOR: ::DWORD = 0x00000100; +pub type LPFRHOOKPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +STRUCT!{nodebug struct FINDREPLACEA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + Flags: ::DWORD, + lpstrFindWhat: ::LPSTR, + lpstrReplaceWith: ::LPSTR, + wFindWhatLen: ::WORD, + wReplaceWithLen: ::WORD, + lCustData: ::LPARAM, + lpfnHook: LPFRHOOKPROC, + lpTemplateName: ::LPCSTR, +}} +pub type LPFINDREPLACEA = *mut FINDREPLACEA; +STRUCT!{nodebug struct FINDREPLACEW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + Flags: ::DWORD, + lpstrFindWhat: ::LPWSTR, + lpstrReplaceWith: ::LPWSTR, + wFindWhatLen: ::WORD, + wReplaceWithLen: ::WORD, + lCustData: ::LPARAM, + lpfnHook: LPFRHOOKPROC, + lpTemplateName: ::LPCWSTR, +}} +pub type LPFINDREPLACEW = *mut FINDREPLACEW; +pub const FR_DOWN: ::DWORD = 0x00000001; +pub const FR_WHOLEWORD: ::DWORD = 0x00000002; +pub const FR_MATCHCASE: ::DWORD = 0x00000004; +pub const FR_FINDNEXT: ::DWORD = 0x00000008; +pub const FR_REPLACE: ::DWORD = 0x00000010; +pub const FR_REPLACEALL: ::DWORD = 0x00000020; +pub const FR_DIALOGTERM: ::DWORD = 0x00000040; +pub const FR_SHOWHELP: ::DWORD = 0x00000080; +pub const FR_ENABLEHOOK: ::DWORD = 0x00000100; +pub const FR_ENABLETEMPLATE: ::DWORD = 0x00000200; +pub const FR_NOUPDOWN: ::DWORD = 0x00000400; +pub const FR_NOMATCHCASE: ::DWORD = 0x00000800; +pub const FR_NOWHOLEWORD: ::DWORD = 0x00001000; +pub const FR_ENABLETEMPLATEHANDLE: ::DWORD = 0x00002000; +pub const FR_HIDEUPDOWN: ::DWORD = 0x00004000; +pub const FR_HIDEMATCHCASE: ::DWORD = 0x00008000; +pub const FR_HIDEWHOLEWORD: ::DWORD = 0x00010000; +pub const FR_RAW: ::DWORD = 0x00020000; +pub const FR_MATCHDIAC: ::DWORD = 0x20000000; +pub const FR_MATCHKASHIDA: ::DWORD = 0x40000000; +pub const FR_MATCHALEFHAMZA: ::DWORD = 0x80000000; +pub type LPCFHOOKPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +STRUCT!{nodebug struct CHOOSEFONTA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDC: ::HDC, + lpLogFont: ::LPLOGFONTA, + iPointSize: ::INT, + Flags: ::DWORD, + rgbColors: ::COLORREF, + lCustData: ::LPARAM, + lpfnHook: LPCFHOOKPROC, + lpTemplateName: ::LPCSTR, + hInstance: ::HINSTANCE, + lpszStyle: ::LPSTR, + nFontType: ::WORD, + ___MISSING_ALIGNMENT__: ::WORD, + nSizeMin: ::INT, + nSizeMax: ::INT, +}} +pub type LPCHOOSEFONTA = *mut CHOOSEFONTA; +STRUCT!{nodebug struct CHOOSEFONTW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDC: ::HDC, + lpLogFont: ::LPLOGFONTW, + iPointSize: ::INT, + Flags: ::DWORD, + rgbColors: ::COLORREF, + lCustData: ::LPARAM, + lpfnHook: LPCFHOOKPROC, + lpTemplateName: ::LPCWSTR, + hInstance: ::HINSTANCE, + lpszStyle: ::LPWSTR, + nFontType: ::WORD, + ___MISSING_ALIGNMENT__: ::WORD, + nSizeMin: ::INT, + nSizeMax: ::INT, +}} +pub type LPCHOOSEFONTW = *mut CHOOSEFONTW; +pub const CF_SCREENFONTS: ::DWORD = 0x00000001; +pub const CF_PRINTERFONTS: ::DWORD = 0x00000002; +pub const CF_BOTH: ::DWORD = CF_SCREENFONTS | CF_PRINTERFONTS; +pub const CF_SHOWHELP: ::DWORD = 0x00000004; +pub const CF_ENABLEHOOK: ::DWORD = 0x00000008; +pub const CF_ENABLETEMPLATE: ::DWORD = 0x00000010; +pub const CF_ENABLETEMPLATEHANDLE: ::DWORD = 0x00000020; +pub const CF_INITTOLOGFONTSTRUCT: ::DWORD = 0x00000040; +pub const CF_USESTYLE: ::DWORD = 0x00000080; +pub const CF_EFFECTS: ::DWORD = 0x00000100; +pub const CF_APPLY: ::DWORD = 0x00000200; +pub const CF_ANSIONLY: ::DWORD = 0x00000400; +pub const CF_SCRIPTSONLY: ::DWORD = CF_ANSIONLY; +pub const CF_NOVECTORFONTS: ::DWORD = 0x00000800; +pub const CF_NOOEMFONTS: ::DWORD = CF_NOVECTORFONTS; +pub const CF_NOSIMULATIONS: ::DWORD = 0x00001000; +pub const CF_LIMITSIZE: ::DWORD = 0x00002000; +pub const CF_FIXEDPITCHONLY: ::DWORD = 0x00004000; +pub const CF_WYSIWYG: ::DWORD = 0x00008000; +pub const CF_FORCEFONTEXIST: ::DWORD = 0x00010000; +pub const CF_SCALABLEONLY: ::DWORD = 0x00020000; +pub const CF_TTONLY: ::DWORD = 0x00040000; +pub const CF_NOFACESEL: ::DWORD = 0x00080000; +pub const CF_NOSTYLESEL: ::DWORD = 0x00100000; +pub const CF_NOSIZESEL: ::DWORD = 0x00200000; +pub const CF_SELECTSCRIPT: ::DWORD = 0x00400000; +pub const CF_NOSCRIPTSEL: ::DWORD = 0x00800000; +pub const CF_NOVERTFONTS: ::DWORD = 0x01000000; +pub const CF_INACTIVEFONTS: ::DWORD = 0x02000000; +pub const SIMULATED_FONTTYPE: ::WORD = 0x8000; +pub const PRINTER_FONTTYPE: ::WORD = 0x4000; +pub const SCREEN_FONTTYPE: ::WORD = 0x2000; +pub const BOLD_FONTTYPE: ::WORD = 0x0100; +pub const ITALIC_FONTTYPE: ::WORD = 0x0200; +pub const REGULAR_FONTTYPE: ::WORD = 0x0400; +pub const PS_OPENTYPE_FONTTYPE: ::DWORD = 0x10000; +pub const TT_OPENTYPE_FONTTYPE: ::DWORD = 0x20000; +pub const TYPE1_FONTTYPE: ::DWORD = 0x40000; +pub const SYMBOL_FONTTYPE: ::DWORD = 0x80000; +pub const WM_CHOOSEFONT_GETLOGFONT: ::UINT = ::WM_USER + 1; +pub const WM_CHOOSEFONT_SETLOGFONT: ::UINT = ::WM_USER + 101; +pub const WM_CHOOSEFONT_SETFLAGS: ::UINT = ::WM_USER + 102; +pub const CD_LBSELNOITEMS: ::WORD = -1i16 as ::WORD; +pub const CD_LBSELCHANGE: ::WORD = 0; +pub const CD_LBSELSUB: ::WORD = 1; +pub const CD_LBSELADD: ::WORD = 2; +pub type LPPRINTHOOKPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +pub type LPSETUPHOOKPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +STRUCT!{nodebug struct PRINTDLGA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + nFromPage: ::WORD, + nToPage: ::WORD, + nMinPage: ::WORD, + nMaxPage: ::WORD, + nCopies: ::WORD, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPrintHook: LPPRINTHOOKPROC, + lpfnSetupHook: LPSETUPHOOKPROC, + lpPrintTemplateName: ::LPCSTR, + lpSetupTemplateName: ::LPCSTR, + hPrintTemplate: ::HGLOBAL, + hSetupTemplate: ::HGLOBAL, +}} +pub type LPPRINTDLGA = *mut PRINTDLGA; +STRUCT!{nodebug struct PRINTDLGW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + nFromPage: ::WORD, + nToPage: ::WORD, + nMinPage: ::WORD, + nMaxPage: ::WORD, + nCopies: ::WORD, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPrintHook: LPPRINTHOOKPROC, + lpfnSetupHook: LPSETUPHOOKPROC, + lpPrintTemplateName: ::LPCWSTR, + lpSetupTemplateName: ::LPCWSTR, + hPrintTemplate: ::HGLOBAL, + hSetupTemplate: ::HGLOBAL, +}} +pub type LPPRINTDLGW = *mut PRINTDLGW; +RIDL!( +interface IPrintDialogCallback(IPrintDialogCallbackVtbl) : IUnknown(IUnknownVtbl) { + fn InitDone(&mut self) -> ::HRESULT, + fn SelectionChange(&mut self) -> ::HRESULT, + fn HandleMessage( + &mut self, hDlg: ::HWND, uMsg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM, + pResult: *mut ::LRESULT + ) -> ::HRESULT +} +); +RIDL!( +interface IPrintDialogServices(IPrintDialogServicesVtbl) : IUnknown(IUnknownVtbl) { + fn GetCurrentDevMode(&mut self, pDevMode: ::LPDEVMODEW, pcbSize: *mut ::UINT) -> ::HRESULT, + fn GetCurrentPrinterName(&mut self, pPrinterName: ::LPWSTR, pcchSize: *mut ::UINT) -> ::HRESULT, + fn GetCurrentPortName(&mut self, pPortName: ::LPWSTR, pcchSize: *mut ::UINT) -> ::HRESULT +} +); +STRUCT!{struct PRINTPAGERANGE { + nFromPage: ::DWORD, + nToPage: ::DWORD, +}} +pub type LPPRINTPAGERANGE = *mut PRINTPAGERANGE; +pub type PCPRINTPAGERANGE = *const PRINTPAGERANGE; +STRUCT!{struct PRINTDLGEXA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + Flags2: ::DWORD, + ExclusionFlags: ::DWORD, + nPageRanges: ::DWORD, + nMaxPageRanges: ::DWORD, + lpPageRanges: LPPRINTPAGERANGE, + nMinPage: ::DWORD, + nMaxPage: ::DWORD, + nCopies: ::DWORD, + hInstance: ::HINSTANCE, + lpPrintTemplateName: ::LPCSTR, + lpCallback: ::LPUNKNOWN, + nPropertyPages: ::DWORD, + lphPropertyPages: *mut ::HPROPSHEETPAGE, + nStartPage: ::DWORD, + dwResultAction: ::DWORD, +}} +pub type LPPRINTDLGEXA = *mut PRINTDLGEXA; +STRUCT!{struct PRINTDLGEXW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + Flags2: ::DWORD, + ExclusionFlags: ::DWORD, + nPageRanges: ::DWORD, + nMaxPageRanges: ::DWORD, + lpPageRanges: LPPRINTPAGERANGE, + nMinPage: ::DWORD, + nMaxPage: ::DWORD, + nCopies: ::DWORD, + hInstance: ::HINSTANCE, + lpPrintTemplateName: ::LPCWSTR, + lpCallback: ::LPUNKNOWN, + nPropertyPages: ::DWORD, + lphPropertyPages: *mut ::HPROPSHEETPAGE, + nStartPage: ::DWORD, + dwResultAction: ::DWORD, +}} +pub type LPPRINTDLGEXW = *mut PRINTDLGEXW; +pub const PD_ALLPAGES: ::DWORD = 0x00000000; +pub const PD_SELECTION: ::DWORD = 0x00000001; +pub const PD_PAGENUMS: ::DWORD = 0x00000002; +pub const PD_NOSELECTION: ::DWORD = 0x00000004; +pub const PD_NOPAGENUMS: ::DWORD = 0x00000008; +pub const PD_COLLATE: ::DWORD = 0x00000010; +pub const PD_PRINTTOFILE: ::DWORD = 0x00000020; +pub const PD_PRINTSETUP: ::DWORD = 0x00000040; +pub const PD_NOWARNING: ::DWORD = 0x00000080; +pub const PD_RETURNDC: ::DWORD = 0x00000100; +pub const PD_RETURNIC: ::DWORD = 0x00000200; +pub const PD_RETURNDEFAULT: ::DWORD = 0x00000400; +pub const PD_SHOWHELP: ::DWORD = 0x00000800; +pub const PD_ENABLEPRINTHOOK: ::DWORD = 0x00001000; +pub const PD_ENABLESETUPHOOK: ::DWORD = 0x00002000; +pub const PD_ENABLEPRINTTEMPLATE: ::DWORD = 0x00004000; +pub const PD_ENABLESETUPTEMPLATE: ::DWORD = 0x00008000; +pub const PD_ENABLEPRINTTEMPLATEHANDLE: ::DWORD = 0x00010000; +pub const PD_ENABLESETUPTEMPLATEHANDLE: ::DWORD = 0x00020000; +pub const PD_USEDEVMODECOPIES: ::DWORD = 0x00040000; +pub const PD_USEDEVMODECOPIESANDCOLLATE: ::DWORD = 0x00040000; +pub const PD_DISABLEPRINTTOFILE: ::DWORD = 0x00080000; +pub const PD_HIDEPRINTTOFILE: ::DWORD = 0x00100000; +pub const PD_NONETWORKBUTTON: ::DWORD = 0x00200000; +pub const PD_CURRENTPAGE: ::DWORD = 0x00400000; +pub const PD_NOCURRENTPAGE: ::DWORD = 0x00800000; +pub const PD_EXCLUSIONFLAGS: ::DWORD = 0x01000000; +pub const PD_USELARGETEMPLATE: ::DWORD = 0x10000000; +pub const PD_EXCL_COPIESANDCOLLATE: ::DWORD = ::DM_COPIES | ::DM_COLLATE; +pub const START_PAGE_GENERAL: ::DWORD = 0xffffffff; +pub const PD_RESULT_CANCEL: ::DWORD = 0; +pub const PD_RESULT_PRINT: ::DWORD = 1; +pub const PD_RESULT_APPLY: ::DWORD = 2; +STRUCT!{struct DEVNAMES { + wDriverOffset: ::WORD, + wDeviceOffset: ::WORD, + wOutputOffset: ::WORD, + wDefault: ::WORD, +}} +pub type LPDEVNAMES = *mut DEVNAMES; +pub type PCDEVNAMES = *const DEVNAMES; +pub const DN_DEFAULTPRN: ::WORD = 0x0001; +pub const WM_PSD_PAGESETUPDLG: ::UINT = ::WM_USER; +pub const WM_PSD_FULLPAGERECT: ::UINT = ::WM_USER + 1; +pub const WM_PSD_MINMARGINRECT: ::UINT = ::WM_USER + 2; +pub const WM_PSD_MARGINRECT: ::UINT = ::WM_USER + 3; +pub const WM_PSD_GREEKTEXTRECT: ::UINT = ::WM_USER + 4; +pub const WM_PSD_ENVSTAMPRECT: ::UINT = ::WM_USER + 5; +pub const WM_PSD_YAFULLPAGERECT: ::UINT = ::WM_USER + 6; +pub type LPPAGEPAINTHOOK = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +pub type LPPAGESETUPHOOK = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::UINT_PTR>; +STRUCT!{nodebug struct PAGESETUPDLGA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + Flags: ::DWORD, + ptPaperSize: ::POINT, + rtMinMargin: ::RECT, + rtMargin: ::RECT, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPageSetupHook: LPPAGESETUPHOOK, + lpfnPagePaintHook: LPPAGEPAINTHOOK, + lpPageSetupTemplateName: ::LPCSTR, + hPageSetupTemplate: ::HGLOBAL, +}} +pub type LPPAGESETUPDLGA = *mut PAGESETUPDLGA; +STRUCT!{nodebug struct PAGESETUPDLGW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + Flags: ::DWORD, + ptPaperSize: ::POINT, + rtMinMargin: ::RECT, + rtMargin: ::RECT, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPageSetupHook: LPPAGESETUPHOOK, + lpfnPagePaintHook: LPPAGEPAINTHOOK, + lpPageSetupTemplateName: ::LPCWSTR, + hPageSetupTemplate: ::HGLOBAL, +}} +pub type LPPAGESETUPDLGW = *mut PAGESETUPDLGW; +pub const PSD_DEFAULTMINMARGINS: ::DWORD = 0x00000000; +pub const PSD_INWININIINTLMEASURE: ::DWORD = 0x00000000; +pub const PSD_MINMARGINS: ::DWORD = 0x00000001; +pub const PSD_MARGINS: ::DWORD = 0x00000002; +pub const PSD_INTHOUSANDTHSOFINCHES: ::DWORD = 0x00000004; +pub const PSD_INHUNDREDTHSOFMILLIMETERS: ::DWORD = 0x00000008; +pub const PSD_DISABLEMARGINS: ::DWORD = 0x00000010; +pub const PSD_DISABLEPRINTER: ::DWORD = 0x00000020; +pub const PSD_NOWARNING: ::DWORD = 0x00000080; +pub const PSD_DISABLEORIENTATION: ::DWORD = 0x00000100; +pub const PSD_RETURNDEFAULT: ::DWORD = 0x00000400; +pub const PSD_DISABLEPAPER: ::DWORD = 0x00000200; +pub const PSD_SHOWHELP: ::DWORD = 0x00000800; +pub const PSD_ENABLEPAGESETUPHOOK: ::DWORD = 0x00002000; +pub const PSD_ENABLEPAGESETUPTEMPLATE: ::DWORD = 0x00008000; +pub const PSD_ENABLEPAGESETUPTEMPLATEHANDLE: ::DWORD = 0x00020000; +pub const PSD_ENABLEPAGEPAINTHOOK: ::DWORD = 0x00040000; +pub const PSD_DISABLEPAGEPAINTING: ::DWORD = 0x00080000; +pub const PSD_NONETWORKBUTTON: ::DWORD = 0x00200000; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/corsym.rs b/bash-5.1/vendor/winapi-0.2.8/src/corsym.rs new file mode 100644 index 0000000..d036f07 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/corsym.rs @@ -0,0 +1,79 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Common Language Runtime Debugging Symbol Reader/Writer/Binder Interfaces +DEFINE_GUID!(CorSym_LanguageType_C, 0x63a08714, 0xfc37, 0x11d2, + 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_LanguageType_CPlusPlus, 0x3a12d0b7, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_CSharp, 0x3f5162f8, 0x07c6, 0x11d3, + 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_LanguageType_Basic, 0x3a12d0b8, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_Java, 0x3a12d0b4, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_Cobol, 0xaf046cd1, 0xd0e1, 0x11d2, + 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc); +DEFINE_GUID!(CorSym_LanguageType_Pascal, 0xaf046cd2, 0xd0e1, 0x11d2, + 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc); +DEFINE_GUID!(CorSym_LanguageType_ILAssembly, 0xaf046cd3, 0xd0e1, 0x11d2, + 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc); +DEFINE_GUID!(CorSym_LanguageType_JScript, 0x3a12d0b6, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x00, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_SMC, 0xd9b9f7b, 0x6611, 0x11d3, + 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd); +DEFINE_GUID!(CorSym_LanguageType_MCPlusPlus, 0x4b35fde8, 0x07c6, 0x11d3, + 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_LanguageVendor_Microsoft, 0x994b45c4, 0xe6e9, 0x11d2, + 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_DocumentType_Text, 0x5a869d0b, 0x6611, 0x11d3, + 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd); +DEFINE_GUID!(CorSym_DocumentType_MC, 0xeb40cb65, 0x3c1f, 0x4352, + 0x9d, 0x7b, 0xba, 0xf, 0xc4, 0x7a, 0x9d, 0x77); +DEFINE_GUID!(CorSym_SourceHash_MD5, 0x406ea660, 0x64cf, 0x4c82, + 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99); +DEFINE_GUID!(CorSym_SourceHash_SHA1, 0xff1816ec, 0xaa5e, 0x4d10, + 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60); +ENUM!{enum CorSymAddrKind { + ADDR_IL_OFFSET = 1, + ADDR_NATIVE_RVA = 2, + ADDR_NATIVE_REGISTER = 3, + ADDR_NATIVE_REGREL = 4, + ADDR_NATIVE_OFFSET = 5, + ADDR_NATIVE_REGREG = 6, + ADDR_NATIVE_REGSTK = 7, + ADDR_NATIVE_STKREG = 8, + ADDR_BITFIELD = 9, + ADDR_NATIVE_ISECTOFFSET = 10, +}} +FLAGS!{enum CorSymVarFlag { + VAR_IS_COMP_GEN = 1, +}} +RIDL!( +interface ISymUnmanagedBinder(ISymUnmanagedBinderVtbl): IUnknown(IUnknownVtbl) { + fn GetReaderForFile( + &mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR, + pRetVal: *mut *mut ISymUnmanagedReader + ) -> ::HRESULT, + fn GetReaderFromStream( + &mut self, importer: *mut ::IUnknown, pstream: *mut ::IStream, + pRetVal: *mut *mut ISymUnmanagedReader + ) -> ::HRESULT +} +); +FLAGS!{enum CorSymSearchPolicyAttributes { + AllowRegistryAccess = 0x1, + AllowSymbolServerAccess = 0x2, + AllowOriginalPathAccess = 0x4, + AllowReferencePathAccess = 0x8, +}} +RIDL!( +interface ISymUnmanagedBinder2(ISymUnmanagedBinder2Vtbl): + ISymUnmanagedBinder(ISymUnmanagedBinderVtbl) { + fn GetReaderForFile2( + &mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR, + searchPolicy: ::ULONG32, pRetVal: *mut *mut ISymUnmanagedReader + ) -> ::HRESULT +} +); +#[derive(Clone, Copy)] +pub struct ISymUnmanagedReader; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d2d1.rs b/bash-5.1/vendor/winapi-0.2.8/src/d2d1.rs new file mode 100644 index 0000000..1b1b039 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d2d1.rs @@ -0,0 +1,734 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of d2d1.h +// Types confirmed affected by the ABI issue: +// D2D1_SIZE_F, D2D1_SIZE_U, D2D1_COLOR_F, D2D1_PIXEL_FORMAT, +// D2D1_POINT_2F +pub const D2D1_DEFAULT_FLATTENING_TOLERANCE: ::FLOAT = 0.25; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_NEAREST_NEIGHBOR: ::DWORD = 0; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_LINEAR: ::DWORD = 1; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_CUBIC: ::DWORD = 2; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_MULTI_SAMPLE_LINEAR: ::DWORD = 3; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_ANISOTROPIC: ::DWORD = 4; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_HIGH_QUALITY_CUBIC: ::DWORD = 5; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_FANT: ::DWORD = 6; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_MIPMAP_LINEAR: ::DWORD = 7; +ENUM!{enum D2D1_GAMMA { + D2D1_GAMMA_2_2 = 0, + D2D1_GAMMA_1_0 = 1, +}} +ENUM!{enum D2D1_OPACITY_MASK_CONTENT { + D2D1_OPACITY_MASK_CONTENT_GRAPHICS = 0, + D2D1_OPACITY_MASK_CONTENT_TEXT_NATURAL = 1, + D2D1_OPACITY_MASK_CONTENT_TEXT_GDI_COMPATIBLE = 2, +}} +ENUM!{enum D2D1_EXTEND_MODE { + D2D1_EXTEND_MODE_CLAMP = 0, + D2D1_EXTEND_MODE_WRAP = 1, + D2D1_EXTEND_MODE_MIRROR = 2, +}} +ENUM!{enum D2D1_ANTIALIAS_MODE { + D2D1_ANTIALIAS_MODE_PER_PRIMITIVE = 0, + D2D1_ANTIALIAS_MODE_ALIASED = 1, +}} +ENUM!{enum D2D1_TEXT_ANTIALIAS_MODE { + D2D1_TEXT_ANTIALIAS_MODE_DEFAULT = 0, + D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE = 1, + D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE = 2, + D2D1_TEXT_ANTIALIAS_MODE_ALIASED = 3, +}} +ENUM!{enum D2D1_BITMAP_INTERPOLATION_MODE { + D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR = + D2D1_INTERPOLATION_MODE_DEFINITION_NEAREST_NEIGHBOR, + D2D1_BITMAP_INTERPOLATION_MODE_LINEAR = + D2D1_INTERPOLATION_MODE_DEFINITION_LINEAR, +}} +FLAGS!{enum D2D1_DRAW_TEXT_OPTIONS { + D2D1_DRAW_TEXT_OPTIONS_NO_SNAP = 0x00000001, + D2D1_DRAW_TEXT_OPTIONS_CLIP = 0x00000002, + D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT = 0x00000004, + D2D1_DRAW_TEXT_OPTIONS_NONE = 0x00000000, +}} +pub type D2D1_POINT_2U = ::D2D_POINT_2U; +pub type D2D1_POINT_2F = ::D2D_POINT_2F; +pub type D2D1_RECT_F = ::D2D_RECT_F; +pub type D2D1_RECT_U = ::D2D_RECT_U; +pub type D2D1_SIZE_F = ::D2D_SIZE_F; +pub type D2D1_SIZE_U = ::D2D_SIZE_U; +pub type D2D1_COLOR_F = ::D2D_COLOR_F; +pub type D2D1_MATRIX_3X2_F = ::D2D_MATRIX_3X2_F; +pub type D2D1_TAG = ::UINT64; +STRUCT!{struct D2D1_BITMAP_PROPERTIES { + pixelFormat: ::D2D1_PIXEL_FORMAT, + dpiX: ::FLOAT, + dpiY: ::FLOAT, +}} +STRUCT!{struct D2D1_GRADIENT_STOP { + position: ::FLOAT, + color: D2D1_COLOR_F, +}} +STRUCT!{struct D2D1_BRUSH_PROPERTIES { + opacity: ::FLOAT, + transform: D2D1_MATRIX_3X2_F, +}} +STRUCT!{struct D2D1_BITMAP_BRUSH_PROPERTIES { + extendModeX: D2D1_EXTEND_MODE, + extendModeY: D2D1_EXTEND_MODE, + interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE, +}} +STRUCT!{struct D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES { + startPoint: ::D2D1_POINT_2F, + endPoint: ::D2D1_POINT_2F, +}} +STRUCT!{struct D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES { + center: ::D2D1_POINT_2F, + gradientOriginOffset: ::D2D1_POINT_2F, + radiusX: ::FLOAT, + radiusY: ::FLOAT, +}} +ENUM!{enum D2D1_ARC_SIZE { + D2D1_ARC_SIZE_SMALL = 0, + D2D1_ARC_SIZE_LARGE = 1, +}} +ENUM!{enum D2D1_CAP_STYLE { + D2D1_CAP_STYLE_FLAT = 0, + D2D1_CAP_STYLE_SQUARE = 1, + D2D1_CAP_STYLE_ROUND = 2, + D2D1_CAP_STYLE_TRIANGLE = 3, +}} +ENUM!{enum D2D1_DASH_STYLE { + D2D1_DASH_STYLE_SOLID = 0, + D2D1_DASH_STYLE_DASH = 1, + D2D1_DASH_STYLE_DOT = 2, + D2D1_DASH_STYLE_DASH_DOT = 3, + D2D1_DASH_STYLE_DASH_DOT_DOT = 4, + D2D1_DASH_STYLE_CUSTOM = 5, +}} +ENUM!{enum D2D1_LINE_JOIN { + D2D1_LINE_JOIN_MITER = 0, + D2D1_LINE_JOIN_BEVEL = 1, + D2D1_LINE_JOIN_ROUND = 2, + D2D1_LINE_JOIN_MITER_OR_BEVEL = 3, +}} +ENUM!{enum D2D1_COMBINE_MODE { + D2D1_COMBINE_MODE_UNION = 0, + D2D1_COMBINE_MODE_INTERSECT = 1, + D2D1_COMBINE_MODE_XOR = 2, + D2D1_COMBINE_MODE_EXCLUDE = 3, +}} +ENUM!{enum D2D1_GEOMETRY_RELATION { + D2D1_GEOMETRY_RELATION_UNKNOWN = 0, + D2D1_GEOMETRY_RELATION_DISJOINT = 1, + D2D1_GEOMETRY_RELATION_IS_CONTAINED = 2, + D2D1_GEOMETRY_RELATION_CONTAINS = 3, + D2D1_GEOMETRY_RELATION_OVERLAP = 4, +}} +ENUM!{enum D2D1_GEOMETRY_SIMPLIFICATION_OPTION { + D2D1_GEOMETRY_SIMPLIFICATION_OPTION_CUBICS_AND_LINES = 0, + D2D1_GEOMETRY_SIMPLIFICATION_OPTION_LINES = 1, +}} +ENUM!{enum D2D1_FIGURE_BEGIN { + D2D1_FIGURE_BEGIN_FILLED = 0, + D2D1_FIGURE_BEGIN_HOLLOW = 1, +}} +ENUM!{enum D2D1_FIGURE_END { + D2D1_FIGURE_END_OPEN = 0, + D2D1_FIGURE_END_CLOSED = 1, +}} +STRUCT!{struct D2D1_BEZIER_SEGMENT { + point1: ::D2D1_POINT_2F, + point2: ::D2D1_POINT_2F, + point3: ::D2D1_POINT_2F, +}} +STRUCT!{struct D2D1_TRIANGLE { + point1: ::D2D1_POINT_2F, + point2: ::D2D1_POINT_2F, + point3: ::D2D1_POINT_2F, +}} +FLAGS!{enum D2D1_PATH_SEGMENT { + D2D1_PATH_SEGMENT_NONE = 0x00000000, + D2D1_PATH_SEGMENT_FORCE_UNSTROKED = 0x00000001, + D2D1_PATH_SEGMENT_FORCE_ROUND_LINE_JOIN = 0x00000002, +}} +ENUM!{enum D2D1_SWEEP_DIRECTION { + D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE = 0, + D2D1_SWEEP_DIRECTION_CLOCKWISE = 1, +}} +ENUM!{enum D2D1_FILL_MODE { + D2D1_FILL_MODE_ALTERNATE = 0, + D2D1_FILL_MODE_WINDING = 1, +}} +STRUCT!{struct D2D1_ARC_SEGMENT { + point: ::D2D1_POINT_2F, + size: D2D1_SIZE_F, + rotationAngle: ::FLOAT, + sweepDirection: D2D1_SWEEP_DIRECTION, + arcSize: D2D1_ARC_SIZE, +}} +STRUCT!{struct D2D1_QUADRATIC_BEZIER_SEGMENT { + point1: ::D2D1_POINT_2F, + point2: ::D2D1_POINT_2F, +}} +STRUCT!{struct D2D1_ELLIPSE { + point: ::D2D1_POINT_2F, + radiusX: ::FLOAT, + radiusY: ::FLOAT, +}} +STRUCT!{struct D2D1_ROUNDED_RECT { + rect: ::D2D1_RECT_F, + radiusX: ::FLOAT, + radiusY: ::FLOAT, +}} +STRUCT!{struct D2D1_STROKE_STYLE_PROPERTIES { + startCap: D2D1_CAP_STYLE, + endCap: D2D1_CAP_STYLE, + dashCap: D2D1_CAP_STYLE, + lineJoin: D2D1_LINE_JOIN, + miterLimit: ::FLOAT, + dashStyle: D2D1_DASH_STYLE, + dashOffset: ::FLOAT, +}} +FLAGS!{enum D2D1_LAYER_OPTIONS { + D2D1_LAYER_OPTIONS_NONE = 0x00000000, + D2D1_LAYER_OPTIONS_INITIALIZE_FOR_CLEARTYPE = 0x00000001, +}} +STRUCT!{struct D2D1_LAYER_PARAMETERS { + contentBounds: ::D2D1_RECT_F, + geometricMask: *mut ID2D1Geometry, + maskAntialiasMode: D2D1_ANTIALIAS_MODE, + maskTransform: D2D1_MATRIX_3X2_F, + opacity: ::FLOAT, + opacityBrush: *mut ID2D1Brush, + layerOptions: D2D1_LAYER_OPTIONS, +}} +ENUM!{enum D2D1_WINDOW_STATE { + D2D1_WINDOW_STATE_NONE = 0x0000000, + D2D1_WINDOW_STATE_OCCLUDED = 0x0000001, +}} +ENUM!{enum D2D1_RENDER_TARGET_TYPE { + D2D1_RENDER_TARGET_TYPE_DEFAULT = 0, + D2D1_RENDER_TARGET_TYPE_SOFTWARE = 1, + D2D1_RENDER_TARGET_TYPE_HARDWARE = 2, +}} +ENUM!{enum D2D1_FEATURE_LEVEL { + D2D1_FEATURE_LEVEL_DEFAULT = 0, + D2D1_FEATURE_LEVEL_9 = ::D3D_FEATURE_LEVEL_9_1.0, + D2D1_FEATURE_LEVEL_10 = ::D3D_FEATURE_LEVEL_10_0.0, +}} +FLAGS!{enum D2D1_RENDER_TARGET_USAGE { + D2D1_RENDER_TARGET_USAGE_NONE = 0x00000000, + D2D1_RENDER_TARGET_USAGE_FORCE_BITMAP_REMOTING = 0x00000001, + D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE = 0x00000002, +}} +FLAGS!{enum D2D1_PRESENT_OPTIONS { + D2D1_PRESENT_OPTIONS_NONE = 0x00000000, + D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS = 0x00000001, + D2D1_PRESENT_OPTIONS_IMMEDIATELY = 0x00000002, +}} +STRUCT!{struct D2D1_RENDER_TARGET_PROPERTIES { + _type: D2D1_RENDER_TARGET_TYPE, + pixelFormat: ::D2D1_PIXEL_FORMAT, + dpiX: ::FLOAT, + dpiY: ::FLOAT, + usage: D2D1_RENDER_TARGET_USAGE, + minLevel: D2D1_FEATURE_LEVEL, +}} +STRUCT!{struct D2D1_HWND_RENDER_TARGET_PROPERTIES { + hwnd: ::HWND, + pixelSize: D2D1_SIZE_U, + presentOptions: D2D1_PRESENT_OPTIONS, +}} +FLAGS!{enum D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS { + D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE = 0x00000000, + D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_GDI_COMPATIBLE = 0x00000001, +}} +STRUCT!{struct D2D1_DRAWING_STATE_DESCRIPTION { + antialiasMode: D2D1_ANTIALIAS_MODE, + textAntialiasMode: D2D1_TEXT_ANTIALIAS_MODE, + tag1: D2D1_TAG, + tag2: D2D1_TAG, + transform: D2D1_MATRIX_3X2_F, +}} +ENUM!{enum D2D1_DC_INITIALIZE_MODE { + D2D1_DC_INITIALIZE_MODE_COPY = 0, + D2D1_DC_INITIALIZE_MODE_CLEAR = 1, +}} +ENUM!{enum D2D1_DEBUG_LEVEL { + D2D1_DEBUG_LEVEL_NONE = 0, + D2D1_DEBUG_LEVEL_ERROR = 1, + D2D1_DEBUG_LEVEL_WARNING = 2, + D2D1_DEBUG_LEVEL_INFORMATION = 3, +}} +ENUM!{enum D2D1_FACTORY_TYPE { + D2D1_FACTORY_TYPE_SINGLE_THREADED = 0, + D2D1_FACTORY_TYPE_MULTI_THREADED = 1, +}} +STRUCT!{struct D2D1_FACTORY_OPTIONS { + debugLevel: D2D1_DEBUG_LEVEL, +}} +RIDL!( +interface ID2D1Resource(ID2D1ResourceVtbl): IUnknown(IUnknownVtbl) { + fn GetFactory(&mut self, factory: *mut *mut ID2D1Factory) -> () +}); +RIDL!( +interface ID2D1Image(ID2D1ImageVtbl): ID2D1Resource(ID2D1ResourceVtbl) { +}); +RIDL!( +interface ID2D1Bitmap(ID2D1BitmapVtbl): ID2D1Image(ID2D1ImageVtbl) { + fn GetSize(&mut self, ret: *mut D2D1_SIZE_F) -> *mut D2D1_SIZE_F, // FIXME: ABI issue + fn GetPixelSize(&mut self, ret: *mut D2D1_SIZE_U) -> *mut D2D1_SIZE_U, // FIXME: ABI issue + fn GetPixelFormat( + &mut self, ret: *mut ::D2D1_PIXEL_FORMAT + ) -> *mut ::D2D1_PIXEL_FORMAT, // FIXME: ABI issue + fn GetDpi(&mut self, dpiX: *mut ::FLOAT, dpiY: *mut ::FLOAT) -> (), + fn CopyFromBitmap( + &mut self, destPoint: *const ::D2D1_POINT_2U, bitmap: *mut ID2D1Bitmap, + srcRect: *const ::D2D1_RECT_U + ) -> ::HRESULT, + fn CopyFromRenderTarget( + &mut self, destPoint: *const ::D2D1_POINT_2U, renderTarget: *mut ID2D1RenderTarget, + srcRect: *const ::D2D1_RECT_U + ) -> ::HRESULT, + fn CopyFromMemory( + &mut self, dstRect: *const ::D2D1_RECT_U, srcData: *const ::c_void, pitch: ::UINT32 + ) -> ::HRESULT +}); +RIDL!( +interface ID2D1GradientStopCollection(ID2D1GradientStopCollectionVtbl) + : ID2D1Resource(ID2D1ResourceVtbl) { + fn GetGradientStopCount(&mut self) -> ::UINT32, + fn GetGradientStops( + &mut self, gradientStops: *mut D2D1_GRADIENT_STOP, gradientStopsCount: ::UINT32 + ) -> (), + fn GetColorInterpolationGamma(&mut self) -> D2D1_GAMMA, + fn GetExtendMode(&mut self) -> D2D1_EXTEND_MODE +}); +RIDL!( +interface ID2D1Brush(ID2D1BrushVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn SetOpacity(&mut self, opacity: ::FLOAT) -> (), + fn SetTransform(&mut self, transform: *const D2D1_MATRIX_3X2_F) -> (), + fn GetOpacity(&mut self) -> ::FLOAT, + fn GetTransform(&mut self, transform: *mut D2D1_MATRIX_3X2_F) -> () +}); +RIDL!( +interface ID2D1BitmapBrush(ID2D1BitmapBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetExtendModeX(&mut self, extendModeX: D2D1_EXTEND_MODE) -> (), + fn SetExtendModeY(&mut self, extendModeY: D2D1_EXTEND_MODE) -> (), + fn SetInterpolationMode(&mut self, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE) -> (), + fn SetBitmap(&mut self, bitmap: *mut ID2D1Bitmap) -> (), + fn GetExtendModeX(&mut self) -> D2D1_EXTEND_MODE, + fn GetExtendModeY(&mut self) -> D2D1_EXTEND_MODE, + fn GetInterpolationMode(&mut self) -> D2D1_BITMAP_INTERPOLATION_MODE, + fn GetBitmap(&mut self, bitmap: *mut *mut ID2D1Bitmap) -> () +}); +RIDL!( +interface ID2D1SolidColorBrush(ID2D1SolidColorBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetColor(&mut self, color: *const D2D1_COLOR_F) -> (), + fn GetColor(&mut self, color: *mut D2D1_COLOR_F) -> *mut D2D1_COLOR_F +}); +RIDL!( +interface ID2D1LinearGradientBrush(ID2D1LinearGradientBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetStartPoint(&mut self, startPoint: ::D2D1_POINT_2F) -> (), + fn SetEndPoint(&mut self, endPoint: ::D2D1_POINT_2F) -> (), + fn GetStartPoint(&mut self, ret: *mut D2D1_POINT_2F) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetEndPoint(&mut self, ret: *mut D2D1_POINT_2F) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetGradientStopCollection( + &mut self, gradientStopCollection: *mut *mut ID2D1GradientStopCollection + ) -> () +}); +RIDL!( +interface ID2D1RadialGradientBrush(ID2D1RadialGradientBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetCenter(&mut self, center: ::D2D1_POINT_2F) -> (), + fn SetGradientOriginOffset(&mut self, gradientOriginOffset: ::D2D1_POINT_2F) -> (), + fn SetRadiusX(&mut self, radiusX: ::FLOAT) -> (), + fn SetRadiusY(&mut self, radiusY: ::FLOAT) -> (), + fn GetCenter(&mut self, ret: *mut D2D1_POINT_2F) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetGradientOriginOffset( + &mut self, ret: *mut D2D1_POINT_2F + ) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetRadiusX(&mut self) -> ::FLOAT, + fn GetRadiusY(&mut self) -> ::FLOAT, + fn GetGradientStopCollection( + &mut self, gradientStopCollection: *mut *mut ID2D1GradientStopCollection + ) -> () +}); +RIDL!( +interface ID2D1StrokeStyle(ID2D1StrokeStyleVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetStartCap(&mut self) -> D2D1_CAP_STYLE, + fn GetEndCap(&mut self) -> D2D1_CAP_STYLE, + fn GetDashCap(&mut self) -> D2D1_CAP_STYLE, + fn GetMiterLimit(&mut self) -> ::FLOAT, + fn GetLineJoin(&mut self) -> D2D1_LINE_JOIN, + fn GetDashOffset(&mut self) -> ::FLOAT, + fn GetDashStyle(&mut self) -> D2D1_DASH_STYLE, + fn GetDashesCount(&mut self) -> ::UINT32, + fn GetDashes(&mut self, dashes: *mut ::FLOAT, dashesCount: ::UINT32) -> () +}); +RIDL!( +interface ID2D1Geometry(ID2D1GeometryVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetBounds( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, bounds: *mut ::D2D1_RECT_F + ) -> ::HRESULT, + fn GetWidenedBounds( + &mut self, strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + bounds: *mut ::D2D1_RECT_F + ) -> ::HRESULT, + fn StrokeContainsPoint( + &mut self, point: ::D2D1_POINT_2F, strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + contains: *mut ::BOOL + ) -> ::HRESULT, + fn FillContainsPoint( + &mut self, point: ::D2D1_POINT_2F, worldTransform: *const D2D1_MATRIX_3X2_F, + flatteningTolerance: ::FLOAT, contains: *mut ::BOOL + ) -> ::HRESULT, + fn CompareWithGeometry( + &mut self, inputGeometry: *mut ID2D1Geometry, + inputGeometryTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + relation: *mut D2D1_GEOMETRY_RELATION + ) -> ::HRESULT, + fn Simplify( + &mut self, simplificationOption: D2D1_GEOMETRY_SIMPLIFICATION_OPTION, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT, + fn Tessellate( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + tessellationSink: *mut ID2D1TessellationSink + ) -> ::HRESULT, + fn CombineWithGeometry( + &mut self, inputGeometry: *mut ID2D1Geometry, combineMode: D2D1_COMBINE_MODE, + inputGeometryTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT, + fn Outline( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT, + fn ComputeArea( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + area: *mut ::FLOAT + ) -> ::HRESULT, + fn ComputeLength( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + length: *mut ::FLOAT + ) -> ::HRESULT, + fn ComputePointAtLength( + &mut self, length: ::FLOAT, worldTransform: *const D2D1_MATRIX_3X2_F, + flatteningTolerance: ::FLOAT, point: *mut ::D2D1_POINT_2F, + unitTangentVector: *mut ::D2D1_POINT_2F + ) -> ::HRESULT, + fn Widen( + &mut self, strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT +}); +RIDL!( +interface ID2D1RectangleGeometry(ID2D1RectangleGeometryVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetRect(&mut self, rect: *mut ::D2D1_RECT_F) -> () +}); +RIDL!( +interface ID2D1RoundedRectangleGeometry(ID2D1RoundedRectangleGeometryVtbl) + : ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetRoundedRect(&mut self, roundedRect: *mut D2D1_ROUNDED_RECT) -> () +}); +RIDL!( +interface ID2D1EllipseGeometry(ID2D1EllipseGeometryVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetEllipse(&mut self, ellipse: *mut D2D1_ELLIPSE) -> () +}); +RIDL!( +interface ID2D1GeometryGroup(ID2D1GeometryGroupVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetFillMode(&mut self) -> D2D1_FILL_MODE, + fn GetSourceGeometryCount(&mut self) -> ::UINT32, + fn GetSourceGeometries( + &mut self, geometries: *mut *mut ID2D1Geometry, geometriesCount: ::UINT32 + ) -> () +}); +RIDL!( +interface ID2D1TransformedGeometry(ID2D1TransformedGeometryVtbl) + : ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetSourceGeometry(&mut self, sourceGeometry: *mut *mut ID2D1Geometry) -> (), + fn GetTransform(&mut self, transform: *mut D2D1_MATRIX_3X2_F) -> () +}); +RIDL!( +interface ID2D1SimplifiedGeometrySink(ID2D1SimplifiedGeometrySinkVtbl): IUnknown(IUnknownVtbl) { + fn SetFillMode(&mut self, fillMode: D2D1_FILL_MODE) -> (), + fn SetSegmentFlags(&mut self, vertexFlags: D2D1_PATH_SEGMENT) -> (), + fn BeginFigure(&mut self, startPoint: ::D2D1_POINT_2F, figureBegin: D2D1_FIGURE_BEGIN) -> (), + fn AddLines(&mut self, points: *const ::D2D1_POINT_2F, pointsCount: ::UINT32) -> (), + fn AddBeziers(&mut self, beziers: *const D2D1_BEZIER_SEGMENT, beziersCount: ::UINT32) -> (), + fn EndFigure(&mut self, figureEnd: D2D1_FIGURE_END) -> (), + fn Close(&mut self) -> ::HRESULT +}); +RIDL!( +interface ID2D1GeometrySink(ID2D1GeometrySinkVtbl) + : ID2D1SimplifiedGeometrySink(ID2D1SimplifiedGeometrySinkVtbl) { + fn AddLine(&mut self, point: ::D2D1_POINT_2F) -> (), + fn AddBezier(&mut self, bezier: *const D2D1_BEZIER_SEGMENT) -> (), + fn AddQuadraticBezier(&mut self, bezier: *const D2D1_QUADRATIC_BEZIER_SEGMENT) -> (), + fn AddQuadraticBeziers( + &mut self, beziers: *const D2D1_QUADRATIC_BEZIER_SEGMENT, beziersCount: ::UINT32 + ) -> (), + fn AddArc(&mut self, arc: *const D2D1_ARC_SEGMENT) -> () +}); +RIDL!( +interface ID2D1TessellationSink(ID2D1TessellationSinkVtbl): IUnknown(IUnknownVtbl) { + fn AddTriangles(&mut self, triangles: *const D2D1_TRIANGLE, triangleCount: ::UINT32) -> (), + fn Close(&mut self) -> ::HRESULT +}); +RIDL!( +interface ID2D1PathGeometry(ID2D1PathGeometryVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn Open(&mut self, geometrySink: *mut *mut ID2D1GeometrySink) -> ::HRESULT, + fn Stream(&mut self, geometrySink: *mut ID2D1GeometrySink) -> ::HRESULT, + fn GetSegmentCount(&mut self, count: *mut ::UINT32) -> ::HRESULT, + fn GetFigureCount(&mut self, count: *mut ::UINT32) -> ::HRESULT +}); +RIDL!( +interface ID2D1Mesh(ID2D1MeshVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn Open(&mut self, tessellationSink: *mut *mut ID2D1TessellationSink) -> ::HRESULT +}); +RIDL!( +interface ID2D1Layer(ID2D1LayerVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetSize(&mut self, ret: *mut D2D1_SIZE_F) -> *mut D2D1_SIZE_F // FIXME: ABI issue +}); +RIDL!( +interface ID2D1DrawingStateBlock(ID2D1DrawingStateBlockVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetDescription(&mut self, stateDescription: *mut D2D1_DRAWING_STATE_DESCRIPTION) -> (), + fn SetDescription(&mut self, stateDescription: *const D2D1_DRAWING_STATE_DESCRIPTION) -> (), + fn SetTextRenderingParams( + &mut self, textRenderingParams: *mut ::IDWriteRenderingParams + ) -> (), + fn GetTextRenderingParams( + &mut self, textRenderingParams: *mut *mut ::IDWriteRenderingParams + ) -> () +}); +RIDL!( +interface ID2D1RenderTarget(ID2D1RenderTargetVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn CreateBitmap( + &mut self, size: D2D1_SIZE_U, srcData: *const ::c_void, pitch: ::UINT32, + bitmapProperties: *const D2D1_BITMAP_PROPERTIES, bitmap: *mut *mut ID2D1Bitmap + ) -> ::HRESULT, + fn CreateBitmapFromWicBitmap( + &mut self, wicBitmapSource: *mut ::IWICBitmapSource, + bitmapProperties: *const D2D1_BITMAP_PROPERTIES, bitmap: *mut *mut ID2D1Bitmap + ) -> ::HRESULT, + fn CreateSharedBitmap( + &mut self, riid: ::REFIID, data: *const ::c_void, + bitmapProperties: *const D2D1_BITMAP_PROPERTIES, bitmap: *mut *mut ID2D1Bitmap + ) -> ::HRESULT, + fn CreateBitmapBrush( + &mut self, bitmap: *mut ID2D1Bitmap, + bitmapBrushProperties: *const D2D1_BITMAP_BRUSH_PROPERTIES, + brushProperties: *const D2D1_BRUSH_PROPERTIES, bitmapBrush: *mut *mut ID2D1BitmapBrush + ) -> ::HRESULT, + fn CreateSolidColorBrush( + &mut self, color: *const D2D1_COLOR_F, brushProperties: *const D2D1_BRUSH_PROPERTIES, + solidColorBrush: *mut *mut ID2D1SolidColorBrush + ) -> ::HRESULT, + fn CreateGradientStopCollection( + &mut self, gradientStops: *const D2D1_GRADIENT_STOP, gradientStopsCount: ::UINT32, + colorInterpolationGamma: D2D1_GAMMA, extendMode: D2D1_EXTEND_MODE, + gradientStopCollection: *mut *mut ID2D1GradientStopCollection + ) -> ::HRESULT, + fn CreateLinearGradientBrush( + &mut self, linearGradientBrushProperties: *const D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES, + brushProperties: *const D2D1_BRUSH_PROPERTIES, + gradientStopCollection: *mut ID2D1GradientStopCollection, + linearGradientBrush: *mut *mut ID2D1LinearGradientBrush + ) -> ::HRESULT, + fn CreateRadialGradientBrush( + &mut self, radialGradientBrushProperties: *const D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES, + brushProperties: *const D2D1_BRUSH_PROPERTIES, + gradientStopCollection: *mut ID2D1GradientStopCollection, + radialGradientBrush: *mut *mut ID2D1RadialGradientBrush + ) -> ::HRESULT, + fn CreateCompatibleRenderTarget( + &mut self, desiredSize: *const D2D1_SIZE_F, desiredPixelSize: *const D2D1_SIZE_U, + desiredFormat: *const ::D2D1_PIXEL_FORMAT, options: D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS, + bitmapRenderTarget: *mut *mut ID2D1BitmapRenderTarget + ) -> ::HRESULT, + fn CreateLayer(&mut self, size: *const D2D1_SIZE_F, layer: *mut *mut ID2D1Layer) -> ::HRESULT, + fn CreateMesh(&mut self, mesh: *mut *mut ID2D1Mesh) -> ::HRESULT, + fn DrawLine( + &mut self, point0: ::D2D1_POINT_2F, point1: ::D2D1_POINT_2F, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStype: *mut ID2D1StrokeStyle + ) -> (), + fn DrawRectangle( + &mut self, rect: *const ::D2D1_RECT_F, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillRectangle( + &mut self, rect: *const ::D2D1_RECT_F, brush: *mut ID2D1Brush + ) -> (), + fn DrawRoundedRectangle( + &mut self, roundedRect: *const D2D1_ROUNDED_RECT, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillRoundedRectangle( + &mut self, roundedRect: *const D2D1_ROUNDED_RECT, brush: *mut ID2D1Brush + ) -> (), + fn DrawEllipse( + &mut self, ellipse: *const D2D1_ELLIPSE, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillEllipse( + &mut self, ellipse: *const D2D1_ELLIPSE, brush: *mut ID2D1Brush + ) -> (), + fn DrawGeometry( + &mut self, geometry: *mut ID2D1Geometry, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillGeometry( + &mut self, geometry: *mut ID2D1Geometry, brush: *mut ID2D1Brush, + opacityBrush: *mut ID2D1Brush + ) -> (), + fn FillMesh( + &mut self, mesh: *mut ID2D1Mesh, brush: *const ID2D1Brush + ) -> (), + fn FillOpacityMask( + &mut self, opacityMask: *mut ID2D1Bitmap, brush: *mut ID2D1Brush, + content: D2D1_OPACITY_MASK_CONTENT, destinationRectangle: *const ::D2D1_RECT_F, + sourceRectangle: *const ::D2D1_RECT_F + ) -> (), + fn DrawBitmap( + &mut self, bitmap: *mut ID2D1Bitmap, destinationRectangle: *const ::D2D1_RECT_F, + opacity: ::FLOAT, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE, + sourceRectangle: *const ::D2D1_RECT_F + ) -> (), + fn DrawText( + &mut self, string: *const ::WCHAR, stringLength: ::UINT32, + textFormat: *mut ::IDWriteTextFormat, layoutRect: *const ::D2D1_RECT_F, + defaultForegroundBrush: *mut ID2D1Brush, options: D2D1_DRAW_TEXT_OPTIONS, + measuringMode: ::DWRITE_MEASURING_MODE + ) -> (), + fn DrawTextLayout( + &mut self, origin: ::D2D1_POINT_2F, textLayout: *mut ::IDWriteTextLayout, + defaultForegroundBrush: *mut ID2D1Brush, options: D2D1_DRAW_TEXT_OPTIONS + ) -> (), + fn DrawGlyphRun( + &mut self, baselineOrigin: ::D2D1_POINT_2F, glyphRun: *const ::DWRITE_GLYPH_RUN, + foregroundBrush: *mut ID2D1Brush, measuringMode: ::DWRITE_MEASURING_MODE + ) -> (), + fn SetTransform(&mut self, transform: *const D2D1_MATRIX_3X2_F) -> (), + fn GetTransform(&mut self, transform: *mut D2D1_MATRIX_3X2_F) -> (), + fn SetAntialiasMode(&mut self, antialiasMode: D2D1_ANTIALIAS_MODE) -> (), + fn GetAntialiasMode(&mut self) -> D2D1_ANTIALIAS_MODE, + fn SetTextAntialiasMode(&mut self, textAntialiasMode: D2D1_TEXT_ANTIALIAS_MODE) -> (), + fn GetTextAntialiasMode(&mut self) -> D2D1_TEXT_ANTIALIAS_MODE, + fn SetTextRenderingParams( + &mut self, textRenderingParams: *mut ::IDWriteRenderingParams + ) -> (), + fn GetTextRenderingParams( + &mut self, textRenderingParams: *mut *mut ::IDWriteRenderingParams + ) -> (), + fn SetTags(&mut self, tag1: D2D1_TAG, tag2: D2D1_TAG) -> (), + fn GetTags(&mut self, tag1: *mut D2D1_TAG, tag2: *mut D2D1_TAG) -> (), + fn PushLayer( + &mut self, layerParameters: *const D2D1_LAYER_PARAMETERS, layer: *mut ID2D1Layer + ) -> (), + fn PopLayer(&mut self) -> (), + fn Flush(&mut self, tag1: *mut D2D1_TAG, tag2: *mut D2D1_TAG) -> ::HRESULT, + fn SaveDrawingState(&mut self, drawingStateBlock: *mut ID2D1DrawingStateBlock) -> (), + fn RestoreDrawingState(&mut self, drawingStateBlock: *mut ID2D1DrawingStateBlock) -> (), + fn PushAxisAlignedClip( + &mut self, clipRect: *const ::D2D1_RECT_F, antialiasMode: D2D1_ANTIALIAS_MODE + ) -> (), + fn PopAxisAlignedClip(&mut self) -> (), + fn Clear(&mut self, clearColor: *const D2D1_COLOR_F) -> (), + fn BeginDraw(&mut self) -> (), + fn EndDraw(&mut self, tag1: *mut D2D1_TAG, tag2: *mut D2D1_TAG) -> ::HRESULT, + fn GetPixelFormat( + &mut self, ret: *mut ::D2D1_PIXEL_FORMAT + ) -> *mut ::D2D1_PIXEL_FORMAT, // FIXME: ABI issue + fn SetDpi(&mut self, dpiX: ::FLOAT, dpiY: ::FLOAT) -> (), + fn GetDpi(&mut self, dpiX: *mut ::FLOAT, dpiY: *mut ::FLOAT) -> (), + fn GetSize(&mut self, ret: *mut D2D1_SIZE_F) -> *mut D2D1_SIZE_F, // FIXME: ABI issue + fn GetPixelSize(&mut self, ret: *mut D2D1_SIZE_U) -> *mut D2D1_SIZE_U, // FIXME: ABI issue + fn GetMaximumBitmapSize(&mut self) -> ::UINT32, + fn IsSupported( + &mut self, renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES + ) -> ::BOOL +}); +RIDL!( +interface ID2D1BitmapRenderTarget(ID2D1BitmapRenderTargetVtbl) + : ID2D1RenderTarget(ID2D1RenderTargetVtbl) { + fn GetBitmap(&mut self, bitmap: *mut *mut ID2D1Bitmap) -> ::HRESULT +}); +RIDL!( +interface ID2D1HwndRenderTarget(ID2D1HwndRenderTargetVtbl) + : ID2D1RenderTarget(ID2D1RenderTargetVtbl) { + fn CheckWindowState(&mut self) -> D2D1_WINDOW_STATE, + fn Resize(&mut self, pixelSize: *const D2D1_SIZE_U) -> ::HRESULT, + fn GetHwnd(&mut self) -> ::HWND +}); +RIDL!( +interface ID2D1GdiInteropRenderTarget(ID2D1GdiInteropRenderTargetVtbl): IUnknown(IUnknownVtbl) { + fn GetDC(&mut self, mode: D2D1_DC_INITIALIZE_MODE, hdc: *mut ::HDC) -> ::HRESULT, + fn ReleaseDC(&mut self, update: *const ::RECT) -> ::HRESULT +}); +RIDL!( +interface ID2D1DCRenderTarget(ID2D1DCRenderTargetVtbl): ID2D1RenderTarget(ID2D1RenderTargetVtbl) { + fn BindDC(&mut self, hDC: ::HDC, pSubRect: *const ::RECT) -> ::HRESULT +}); +RIDL!( +interface ID2D1Factory(ID2D1FactoryVtbl): IUnknown(IUnknownVtbl) { + fn ReloadSystemMetrics(&mut self) -> ::HRESULT, + fn GetDesktopDpi(&mut self, dpiX: *mut ::FLOAT, dpiY: *mut ::FLOAT) -> (), + fn CreateRectangleGeometry( + &mut self, rectangle: *const ::D2D1_RECT_F, + rectangleGeometry: *mut *mut ID2D1RectangleGeometry + ) -> ::HRESULT, + fn CreateRoundedRectangleGeometry( + &mut self, roundedRectangle: *const D2D1_ROUNDED_RECT, + roundedRectangleGeometry: *mut *mut ID2D1RoundedRectangleGeometry + ) -> ::HRESULT, + fn CreateEllipseGeometry( + &mut self, ellipse: *const D2D1_ELLIPSE, + ellipseGeometry: *mut *mut ID2D1EllipseGeometry + ) -> ::HRESULT, + fn CreateGeometryGroup( + &mut self, fillMode: D2D1_FILL_MODE, geometries: *mut *mut ID2D1Geometry, + geometriesCount: ::UINT32, geometryGroup: *mut *mut ID2D1GeometryGroup + ) -> ::HRESULT, + fn CreateTransformedGeometry( + &mut self, sourceGeometry: *mut ID2D1Geometry, transform: *const D2D1_MATRIX_3X2_F, + transformedGeometry: *mut *mut ID2D1TransformedGeometry + ) -> ::HRESULT, + fn CreatePathGeometry( + &mut self, pathGeometry: *mut *mut ID2D1PathGeometry + ) -> ::HRESULT, + fn CreateStrokeStyle( + &mut self, strokeStyleProperties: *const D2D1_STROKE_STYLE_PROPERTIES, + dashes: *const ::FLOAT, dashesCount: ::UINT32, strokeStyle: *mut *mut ID2D1StrokeStyle + ) -> ::HRESULT, + fn CreateDrawingStateBlock( + &mut self, drawingStateDescription: *const D2D1_DRAWING_STATE_DESCRIPTION, + textRenderingParams: *mut ::IDWriteRenderingParams, + drawingStateBlock: *mut *mut ID2D1DrawingStateBlock + ) -> ::HRESULT, + fn CreateWicBitmapRenderTarget( + &mut self, target: *mut ::IWICBitmap, + renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + renderTarget: *mut *mut ID2D1RenderTarget + ) -> ::HRESULT, + fn CreateHwndRenderTarget( + &mut self, renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + hwndRenderTargetProperties: *const D2D1_HWND_RENDER_TARGET_PROPERTIES, + hwndRenderTarget: *mut *mut ID2D1HwndRenderTarget + ) -> ::HRESULT, + fn CreateDxgiSurfaceRenderTarget( + &mut self, dxgiSurface: *mut ::IDXGISurface, + renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + renderTarget: *mut *mut ID2D1RenderTarget + ) -> ::HRESULT, + fn CreateDCRenderTarget( + &mut self, renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + dcRenderTarget: *mut *mut ID2D1DCRenderTarget + ) -> ::HRESULT +}); +DEFINE_GUID!( + UuidOfID2D1Factory, + 0x06152247, 0x6f50, 0x465a, 0x92, 0x45, 0x11, 0x8b, 0xfd, 0x3b, 0x60, 0x07 +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d2dbasetypes.rs b/bash-5.1/vendor/winapi-0.2.8/src/d2dbasetypes.rs new file mode 100644 index 0000000..45a5a14 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d2dbasetypes.rs @@ -0,0 +1,61 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of d2dbasetypes.h +STRUCT!{struct D2D_POINT_2U { + x: ::UINT32, + y: ::UINT32, +}} +STRUCT!{struct D2D_POINT_2F { + x: ::FLOAT, + y: ::FLOAT, +}} +pub type D2D_POINT_2L = ::POINT; +STRUCT!{struct D2D_VECTOR_2F { + x: ::FLOAT, + y: ::FLOAT, +}} +STRUCT!{struct D2D_VECTOR_3F { + x: ::FLOAT, + y: ::FLOAT, + z: ::FLOAT, +}} +STRUCT!{struct D2D_VECTOR_4F { + x: ::FLOAT, + y: ::FLOAT, + z: ::FLOAT, + w: ::FLOAT, +}} +STRUCT!{struct D2D_RECT_F { + left: ::FLOAT, + top: ::FLOAT, + right: ::FLOAT, + bottom: ::FLOAT, +}} +STRUCT!{struct D2D_RECT_U { + left: ::UINT32, + top: ::UINT32, + right: ::UINT32, + bottom: ::UINT32, +}} +pub type D2D_RECT_L = ::RECT; +STRUCT!{struct D2D_SIZE_F { + width: ::FLOAT, + height: ::FLOAT, +}} +STRUCT!{struct D2D_SIZE_U { + width: ::UINT32, + height: ::UINT32, +}} +pub type D2D_COLOR_F = ::D3DCOLORVALUE; +STRUCT!{struct D2D_MATRIX_3X2_F { + matrix: [[::FLOAT; 2]; 3], +}} +STRUCT!{struct D2D_MATRIX_4X3_F { + matrix: [[::FLOAT; 3]; 4], +}} +STRUCT!{struct D2D_MATRIX_4X4_F { + matrix: [[::FLOAT; 4]; 4], +}} +STRUCT!{struct D2D_MATRIX_5X4_F { + matrix: [[::FLOAT; 4]; 5], +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d10shader.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d10shader.rs new file mode 100644 index 0000000..4f64c5f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d10shader.rs @@ -0,0 +1,110 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub type D3D10_RESOURCE_RETURN_TYPE = D3D_RESOURCE_RETURN_TYPE; +pub type D3D10_CBUFFER_TYPE = D3D_CBUFFER_TYPE; +STRUCT!{struct D3D10_SHADER_DESC { + Version: UINT, + Creator: LPCSTR, + Flags: UINT, + ConstantBuffers: UINT, + BoundResources: UINT, + InputParameters: UINT, + OutputParameters: UINT, + InstructionCount: UINT, + TempRegisterCount: UINT, + TempArrayCount: UINT, + DefCount: UINT, + DclCount: UINT, + TextureNormalInstructions: UINT, + TextureLoadInstructions: UINT, + TextureCompInstructions: UINT, + TextureBiasInstructions: UINT, + TextureGradientInstructions: UINT, + FloatInstructionCount: UINT, + IntInstructionCount: UINT, + UintInstructionCount: UINT, + StaticFlowControlCount: UINT, + DynamicFlowControlCount: UINT, + MacroInstructionCount: UINT, + ArrayInstructionCount: UINT, + CutInstructionCount: UINT, + EmitInstructionCount: UINT, + GSOutputTopology: D3D_PRIMITIVE_TOPOLOGY, + GSMaxOutputVertexCount: UINT, +}} +STRUCT!{struct D3D10_SHADER_BUFFER_DESC { + Name: LPCSTR, + Type: D3D10_CBUFFER_TYPE, + Variables: UINT, + Size: UINT, + uFlags: UINT, +}} +STRUCT!{struct D3D10_SHADER_VARIABLE_DESC { + Name: LPCSTR, + StartOffset: UINT, + Size: UINT, + uFlags: UINT, + DefaultValue: LPVOID, +}} +STRUCT!{struct D3D10_SHADER_TYPE_DESC { + Class: D3D_SHADER_VARIABLE_CLASS, + Type: D3D_SHADER_VARIABLE_TYPE, + Rows: UINT, + Columns: UINT, + Elements: UINT, + Members: UINT, + Offset: UINT, +}} +STRUCT!{struct D3D10_SHADER_INPUT_BIND_DESC { + Name: LPCSTR, + Type: D3D_SHADER_INPUT_TYPE, + BindPoint: UINT, + BindCount: UINT, + uFlags: UINT, + ReturnType: D3D_RESOURCE_RETURN_TYPE, + Dimension: D3D_SRV_DIMENSION, + NumSamples: UINT, +}} +STRUCT!{struct D3D10_SIGNATURE_PARAMETER_DESC { + SemanticName: LPCSTR, + SemanticIndex: UINT, + Register: UINT, + SystemValueType: D3D_NAME, + ComponentType: D3D_REGISTER_COMPONENT_TYPE, + Mask: BYTE, + ReadWriteMask: BYTE, +}} +RIDL!{interface ID3D10ShaderReflectionType(ID3D10ShaderReflectionTypeVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_TYPE_DESC) -> HRESULT, + fn GetMemberTypeByIndex(&mut self, Index: UINT) -> *mut ID3D10ShaderReflectionType, + fn GetMemberTypeByName(&mut self, Name: LPCSTR) -> *mut ID3D10ShaderReflectionType, + fn GetMemberTypeName(&mut self, Index: UINT) -> LPCSTR +}} +RIDL!{interface ID3D10ShaderReflectionVariable(ID3D10ShaderReflectionVariableVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_VARIABLE_DESC) -> HRESULT, + fn GetType(&mut self) -> *mut ID3D10ShaderReflectionType +}} +RIDL!{interface ID3D10ShaderReflectionConstantBuffer(ID3D10ShaderReflectionConstantBufferVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_BUFFER_DESC) -> HRESULT, + fn GetVariableByIndex(&mut self, Index: UINT) -> *mut ID3D10ShaderReflectionVariable, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D10ShaderReflectionVariable +}} +RIDL!{interface ID3D10ShaderReflection(ID3D10ShaderReflectionVtbl): IUnknown(IUnknownVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_DESC) -> HRESULT, + fn GetConstantBufferByIndex( + &mut self, Index: UINT + ) -> *mut ID3D10ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: LPCSTR + ) -> *mut ID3D10ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: UINT, pDesc: *mut D3D10_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetInputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D10_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetOutputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D10_SIGNATURE_PARAMETER_DESC + ) -> HRESULT +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d11.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d11.rs new file mode 100644 index 0000000..4fed70c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d11.rs @@ -0,0 +1,2665 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub const D3D11_16BIT_INDEX_STRIP_CUT_VALUE: DWORD = 0xffff; +pub const D3D11_32BIT_INDEX_STRIP_CUT_VALUE: DWORD = 0xffffffff; +pub const D3D11_8BIT_INDEX_STRIP_CUT_VALUE: DWORD = 0xff; +pub const D3D11_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT: DWORD = 9; +pub const D3D11_CLIP_OR_CULL_DISTANCE_COUNT: DWORD = 8; +pub const D3D11_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT: DWORD = 2; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT: DWORD = 14; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT: DWORD = 15; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT: DWORD = 16; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT: DWORD = 15; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT: DWORD = 64; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT: DWORD = 1; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT: DWORD = 128; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT: DWORD = 128; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_COUNT: DWORD = 16; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT: DWORD = 16; +pub const D3D11_COMMONSHADER_SUBROUTINE_NESTING_LIMIT: DWORD = 32; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_COUNT: DWORD = 4096; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_READS_PER_INST: DWORD = 3; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_READ_PORTS: DWORD = 3; +pub const D3D11_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX: DWORD = 10; +pub const D3D11_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN: c_long = -10; +pub const D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE: c_long = -8; +pub const D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE: DWORD = 7; +pub const D3D11_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 256; +pub const D3D11_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP: DWORD = 64; +pub const D3D11_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 240; +pub const D3D11_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP: DWORD = 68; +pub const D3D11_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 224; +pub const D3D11_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP: DWORD = 72; +pub const D3D11_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 208; +pub const D3D11_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP: DWORD = 76; +pub const D3D11_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 192; +pub const D3D11_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP: DWORD = 84; +pub const D3D11_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 176; +pub const D3D11_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP: DWORD = 92; +pub const D3D11_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 160; +pub const D3D11_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP: DWORD = 100; +pub const D3D11_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 144; +pub const D3D11_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP: DWORD = 112; +pub const D3D11_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 128; +pub const D3D11_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP: DWORD = 128; +pub const D3D11_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 112; +pub const D3D11_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP: DWORD = 144; +pub const D3D11_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 96; +pub const D3D11_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP: DWORD = 168; +pub const D3D11_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 80; +pub const D3D11_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP: DWORD = 204; +pub const D3D11_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 64; +pub const D3D11_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP: DWORD = 256; +pub const D3D11_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 48; +pub const D3D11_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP: DWORD = 340; +pub const D3D11_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 32; +pub const D3D11_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP: DWORD = 512; +pub const D3D11_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 16; +pub const D3D11_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP: DWORD = 768; +pub const D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION: DWORD = 1; +pub const D3D11_CS_4_X_RAW_UAV_BYTE_ALIGNMENT: DWORD = 256; +pub const D3D11_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP: DWORD = 768; +pub const D3D11_CS_4_X_THREAD_GROUP_MAX_X: DWORD = 768; +pub const D3D11_CS_4_X_THREAD_GROUP_MAX_Y: DWORD = 768; +pub const D3D11_CS_4_X_UAV_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION: DWORD = 65535; +pub const D3D11_CS_TGSM_REGISTER_COUNT: DWORD = 8192; +pub const D3D11_CS_TGSM_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_CS_TGSM_RESOURCE_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_CS_TGSM_RESOURCE_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_CS_THREADGROUPID_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_CS_THREADGROUPID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREADIDINGROUP_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_CS_THREADIDINGROUP_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREADID_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_CS_THREADID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP: DWORD = 1024; +pub const D3D11_CS_THREAD_GROUP_MAX_X: DWORD = 1024; +pub const D3D11_CS_THREAD_GROUP_MAX_Y: DWORD = 1024; +pub const D3D11_CS_THREAD_GROUP_MAX_Z: DWORD = 64; +pub const D3D11_CS_THREAD_GROUP_MIN_X: DWORD = 1; +pub const D3D11_CS_THREAD_GROUP_MIN_Y: DWORD = 1; +pub const D3D11_CS_THREAD_GROUP_MIN_Z: DWORD = 1; +pub const D3D11_CS_THREAD_LOCAL_TEMP_REGISTER_POOL: DWORD = 16384; +pub const D3D11_DEFAULT_BLEND_FACTOR_ALPHA: FLOAT = 1.0; +pub const D3D11_DEFAULT_BLEND_FACTOR_BLUE: FLOAT = 1.0; +pub const D3D11_DEFAULT_BLEND_FACTOR_GREEN: FLOAT = 1.0; +pub const D3D11_DEFAULT_BLEND_FACTOR_RED: FLOAT = 1.0; +pub const D3D11_DEFAULT_BORDER_COLOR_COMPONENT: FLOAT = 0.0; +pub const D3D11_DEFAULT_DEPTH_BIAS: DWORD = 0; +pub const D3D11_DEFAULT_DEPTH_BIAS_CLAMP: FLOAT = 0.0; +pub const D3D11_DEFAULT_MAX_ANISOTROPY: DWORD = 16; +pub const D3D11_DEFAULT_MIP_LOD_BIAS: FLOAT = 0.0; +pub const D3D11_DEFAULT_RENDER_TARGET_ARRAY_INDEX: DWORD = 0; +pub const D3D11_DEFAULT_SAMPLE_MASK: DWORD = 0xffffffff; +pub const D3D11_DEFAULT_SCISSOR_ENDX: DWORD = 0; +pub const D3D11_DEFAULT_SCISSOR_ENDY: DWORD = 0; +pub const D3D11_DEFAULT_SCISSOR_STARTX: DWORD = 0; +pub const D3D11_DEFAULT_SCISSOR_STARTY: DWORD = 0; +pub const D3D11_DEFAULT_SLOPE_SCALED_DEPTH_BIAS: FLOAT = 0.0; +pub const D3D11_DEFAULT_STENCIL_READ_MASK: DWORD = 0xff; +pub const D3D11_DEFAULT_STENCIL_REFERENCE: DWORD = 0; +pub const D3D11_DEFAULT_STENCIL_WRITE_MASK: DWORD = 0xff; +pub const D3D11_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_HEIGHT: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_MAX_DEPTH: FLOAT = 0.0; +pub const D3D11_DEFAULT_VIEWPORT_MIN_DEPTH: FLOAT = 0.0; +pub const D3D11_DEFAULT_VIEWPORT_TOPLEFTX: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_TOPLEFTY: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_WIDTH: DWORD = 0; +pub const D3D11_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: DWORD = 3968; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT: DWORD = 1; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_FLOAT16_FUSED_TOLERANCE_IN_ULP: FLOAT = 0.6; +pub const D3D11_FLOAT32_MAX: FLOAT = 3.402823466E+38; +pub const D3D11_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP: FLOAT = 0.6; +pub const D3D11_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR: FLOAT = 2.4; +pub const D3D11_FLOAT_TO_SRGB_EXPONENT_NUMERATOR: FLOAT = 1.0; +pub const D3D11_FLOAT_TO_SRGB_OFFSET: FLOAT = 0.055; +pub const D3D11_FLOAT_TO_SRGB_SCALE_1: FLOAT = 12.92; +pub const D3D11_FLOAT_TO_SRGB_SCALE_2: FLOAT = 1.055; +pub const D3D11_FLOAT_TO_SRGB_THRESHOLD: FLOAT = 0.0031308; +pub const D3D11_FTOI_INSTRUCTION_MAX_INPUT: FLOAT = 2147483647.999; +pub const D3D11_FTOI_INSTRUCTION_MIN_INPUT: FLOAT = -2147483648.999; +pub const D3D11_FTOU_INSTRUCTION_MAX_INPUT: FLOAT = 4294967295.999; +pub const D3D11_FTOU_INSTRUCTION_MIN_INPUT: FLOAT = 0.0; +pub const D3D11_GS_INPUT_INSTANCE_ID_READS_PER_INST: DWORD = 2; +pub const D3D11_GS_INPUT_INSTANCE_ID_READ_PORTS: DWORD = 1; +pub const D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_COUNT: DWORD = 1; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_GS_INPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_GS_INPUT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_GS_INPUT_REGISTER_VERTICES: DWORD = 32; +pub const D3D11_GS_MAX_INSTANCE_COUNT: DWORD = 32; +pub const D3D11_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES: DWORD = 1024; +pub const D3D11_GS_OUTPUT_ELEMENTS: DWORD = 32; +pub const D3D11_GS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_CONTROL_POINT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND: DWORD = 0xffffffff; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND: DWORD = 0xffffffff; +pub const D3D11_HS_MAXTESSFACTOR_LOWER_BOUND: FLOAT = 1.0; +pub const D3D11_HS_MAXTESSFACTOR_UPPER_BOUND: FLOAT = 64.0; +pub const D3D11_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: DWORD = 3968; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS: DWORD = 128; +pub const D3D11_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES: DWORD = 0; +pub const D3D11_IA_DEFAULT_PRIMITIVE_TOPOLOGY: DWORD = 0; +pub const D3D11_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES: DWORD = 0; +pub const D3D11_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT: DWORD = 1; +pub const D3D11_IA_INSTANCE_ID_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_INTEGER_ARITHMETIC_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_PATCH_MAX_CONTROL_POINT_COUNT: DWORD = 32; +pub const D3D11_IA_PRIMITIVE_ID_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_VERTEX_ID_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT: DWORD = 32; +pub const D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS: DWORD = 128; +pub const D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT: DWORD = 32; +pub const D3D11_INTEGER_DIVIDE_BY_ZERO_QUOTIENT: DWORD = 0xffffffff; +pub const D3D11_INTEGER_DIVIDE_BY_ZERO_REMAINDER: DWORD = 0xffffffff; +pub const D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL: DWORD = 0xffffffff; +pub const D3D11_KEEP_UNORDERED_ACCESS_VIEWS: DWORD = 0xffffffff; +pub const D3D11_LINEAR_GAMMA: FLOAT = 1.0; +pub const D3D11_MAJOR_VERSION: DWORD = 11; +pub const D3D11_MAX_BORDER_COLOR_COMPONENT: FLOAT = 1.0; +pub const D3D11_MAX_DEPTH: FLOAT = 1.0; +pub const D3D11_MAX_MAXANISOTROPY: DWORD = 16; +pub const D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT: DWORD = 32; +pub const D3D11_MAX_POSITION_VALUE: FLOAT = 3.402823466E+34; +pub const D3D11_MAX_TEXTURE_DIMENSION_2_TO_EXP: DWORD = 17; +pub const D3D11_MINOR_VERSION: DWORD = 0; +pub const D3D11_MIN_BORDER_COLOR_COMPONENT: FLOAT = 0.0; +pub const D3D11_MIN_DEPTH: FLOAT = 0.0; +pub const D3D11_MIN_MAXANISOTROPY: DWORD = 0; +pub const D3D11_MIP_LOD_BIAS_MAX: FLOAT = 15.99; +pub const D3D11_MIP_LOD_BIAS_MIN: FLOAT = -16.0; +pub const D3D11_MIP_LOD_FRACTIONAL_BIT_COUNT: DWORD = 8; +pub const D3D11_MIP_LOD_RANGE_BIT_COUNT: DWORD = 8; +pub const D3D11_MULTISAMPLE_ANTIALIAS_LINE_WIDTH: FLOAT = 1.4; +pub const D3D11_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT: DWORD = 0; +pub const D3D11_PIXEL_ADDRESS_RANGE_BIT_COUNT: DWORD = 15; +pub const D3D11_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT: DWORD = 16; +pub const D3D11_PS_CS_UAV_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_PS_CS_UAV_REGISTER_COUNT: DWORD = 8; +pub const D3D11_PS_CS_UAV_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_PS_CS_UAV_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_PS_FRONTFACING_DEFAULT_VALUE: DWORD = 0xffffffff; +pub const D3D11_PS_FRONTFACING_FALSE_VALUE: DWORD = 0; +pub const D3D11_PS_FRONTFACING_TRUE_VALUE: DWORD = 0xffffffff; +pub const D3D11_PS_INPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_PS_INPUT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_PS_INPUT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT: FLOAT = 0.0; +pub const D3D11_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_OUTPUT_DEPTH_REGISTER_COUNT: DWORD = 1; +pub const D3D11_PS_OUTPUT_MASK_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_OUTPUT_MASK_REGISTER_COUNT: DWORD = 1; +pub const D3D11_PS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_OUTPUT_REGISTER_COUNT: DWORD = 8; +pub const D3D11_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT: FLOAT = 0.5; +pub const D3D11_RAW_UAV_SRV_BYTE_ALIGNMENT: DWORD = 16; +pub const D3D11_REQ_BLEND_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP: DWORD = 27; +pub const D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT: DWORD = 4096; +pub const D3D11_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: DWORD = 32; +pub const D3D11_REQ_DRAW_VERTEX_COUNT_2_TO_EXP: DWORD = 32; +pub const D3D11_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION: DWORD = 16384; +pub const D3D11_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT: DWORD = 1024; +pub const D3D11_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT: DWORD = 4096; +pub const D3D11_REQ_MAXANISOTROPY: DWORD = 16; +pub const D3D11_REQ_MIP_LEVELS: DWORD = 15; +pub const D3D11_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES: DWORD = 2048; +pub const D3D11_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH: DWORD = 16384; +pub const D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM: DWORD = 128; +pub const D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM: FLOAT = 0.25; +pub const D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM: DWORD = 2048; +pub const D3D11_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP: DWORD = 20; +pub const D3D11_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION: DWORD = 2048; +pub const D3D11_REQ_TEXTURE1D_U_DIMENSION: DWORD = 16384; +pub const D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION: DWORD = 2048; +pub const D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION: DWORD = 16384; +pub const D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION: DWORD = 2048; +pub const D3D11_REQ_TEXTURECUBE_DIMENSION: DWORD = 16384; +pub const D3D11_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL: DWORD = 0; +pub const D3D11_SHADER_MAJOR_VERSION: DWORD = 5; +pub const D3D11_SHADER_MAX_INSTANCES: DWORD = 65535; +pub const D3D11_SHADER_MAX_INTERFACES: DWORD = 253; +pub const D3D11_SHADER_MAX_INTERFACE_CALL_SITES: DWORD = 4096; +pub const D3D11_SHADER_MAX_TYPES: DWORD = 65535; +pub const D3D11_SHADER_MINOR_VERSION: DWORD = 0; +pub const D3D11_SHIFT_INSTRUCTION_PAD_VALUE: DWORD = 0; +pub const D3D11_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT: DWORD = 5; +pub const D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT: DWORD = 8; +pub const D3D11_SO_BUFFER_MAX_STRIDE_IN_BYTES: DWORD = 2048; +pub const D3D11_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES: DWORD = 512; +pub const D3D11_SO_BUFFER_SLOT_COUNT: DWORD = 4; +pub const D3D11_SO_DDI_REGISTER_INDEX_DENOTING_GAP: DWORD = 0xffffffff; +pub const D3D11_SO_NO_RASTERIZED_STREAM: DWORD = 0xffffffff; +pub const D3D11_SO_OUTPUT_COMPONENT_COUNT: DWORD = 128; +pub const D3D11_SO_STREAM_COUNT: DWORD = 4; +pub const D3D11_SPEC_DATE_DAY: DWORD = 16; +pub const D3D11_SPEC_DATE_MONTH: DWORD = 05; +pub const D3D11_SPEC_DATE_YEAR: DWORD = 2011; +pub const D3D11_SPEC_VERSION: FLOAT = 1.07; +pub const D3D11_SRGB_GAMMA: FLOAT = 2.2; +pub const D3D11_SRGB_TO_FLOAT_DENOMINATOR_1: FLOAT = 12.92; +pub const D3D11_SRGB_TO_FLOAT_DENOMINATOR_2: FLOAT = 1.055; +pub const D3D11_SRGB_TO_FLOAT_EXPONENT: FLOAT = 2.4; +pub const D3D11_SRGB_TO_FLOAT_OFFSET: FLOAT = 0.055; +pub const D3D11_SRGB_TO_FLOAT_THRESHOLD: FLOAT = 0.04045; +pub const D3D11_SRGB_TO_FLOAT_TOLERANCE_IN_ULP: FLOAT = 0.5; +pub const D3D11_STANDARD_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_STANDARD_COMPONENT_BIT_COUNT_DOUBLED: DWORD = 64; +pub const D3D11_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE: DWORD = 4; +pub const D3D11_STANDARD_PIXEL_COMPONENT_COUNT: DWORD = 128; +pub const D3D11_STANDARD_PIXEL_ELEMENT_COUNT: DWORD = 32; +pub const D3D11_STANDARD_VECTOR_SIZE: DWORD = 4; +pub const D3D11_STANDARD_VERTEX_ELEMENT_COUNT: DWORD = 32; +pub const D3D11_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT: DWORD = 64; +pub const D3D11_SUBPIXEL_FRACTIONAL_BIT_COUNT: DWORD = 8; +pub const D3D11_SUBTEXEL_FRACTIONAL_BIT_COUNT: DWORD = 8; +pub const D3D11_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR: DWORD = 64; +pub const D3D11_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR: DWORD = 64; +pub const D3D11_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR: DWORD = 63; +pub const D3D11_TESSELLATOR_MAX_TESSELLATION_FACTOR: DWORD = 64; +pub const D3D11_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR: DWORD = 2; +pub const D3D11_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR: DWORD = 1; +pub const D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR: DWORD = 1; +pub const D3D11_TEXEL_ADDRESS_RANGE_BIT_COUNT: DWORD = 16; +pub const D3D11_UNBOUND_MEMORY_ACCESS_RESULT: DWORD = 0; +pub const D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX: DWORD = 15; +pub const D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE: DWORD = 16; +pub const D3D11_VIEWPORT_BOUNDS_MAX: DWORD = 32767; +pub const D3D11_VIEWPORT_BOUNDS_MIN: c_long = -32768; +pub const D3D11_VS_INPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_VS_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_VS_INPUT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_VS_INPUT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_VS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_VS_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT: DWORD = 10; +pub const D3D11_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: DWORD = 25; +pub const D3D11_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP: DWORD = 25; +pub const D3D11_1_UAV_SLOT_COUNT: DWORD = 64; +pub const D3D11_2_TILED_RESOURCE_TILE_SIZE_IN_BYTES: DWORD = 65536; +ENUM!{enum D3D11_INPUT_CLASSIFICATION { + D3D11_INPUT_PER_VERTEX_DATA = 0, + D3D11_INPUT_PER_INSTANCE_DATA = 1, +}} +pub const D3D11_APPEND_ALIGNED_ELEMENT: DWORD = 0xffffffff; +STRUCT!{struct D3D11_INPUT_ELEMENT_DESC { + SemanticName: LPCSTR, + SemanticIndex: UINT, + Format: DXGI_FORMAT, + InputSlot: UINT, + AlignedByteOffset: UINT, + InputSlotClass: D3D11_INPUT_CLASSIFICATION, + InstanceDataStepRate: UINT, +}} +ENUM!{enum D3D11_FILL_MODE { + D3D11_FILL_WIREFRAME = 2, + D3D11_FILL_SOLID = 3, +}} +pub type D3D11_PRIMITIVE_TOPOLOGY = D3D_PRIMITIVE_TOPOLOGY; +pub type D3D11_PRIMITIVE = D3D_PRIMITIVE; +ENUM!{enum D3D11_CULL_MODE { + D3D11_CULL_NONE = 1, + D3D11_CULL_FRONT = 2, + D3D11_CULL_BACK = 3, +}} +STRUCT!{struct D3D11_SO_DECLARATION_ENTRY { + Stream: UINT, + SemanticName: LPCSTR, + SemanticIndex: UINT, + StartComponent: BYTE, + ComponentCount: BYTE, + OutputSlot: BYTE, +}} +STRUCT!{struct D3D11_VIEWPORT { + TopLeftX: FLOAT, + TopLeftY: FLOAT, + Width: FLOAT, + Height: FLOAT, + MinDepth: FLOAT, + MaxDepth: FLOAT, +}} +STRUCT!{struct D3D11_DRAW_INSTANCED_INDIRECT_ARGS { + VertexCountPerInstance: UINT, + InstanceCount: UINT, + StartVertexLocation: UINT, + StartInstanceLocation: UINT, +}} +STRUCT!{struct D3D11_DRAW_INDEXED_INSTANCED_INDIRECT_ARGS { + IndexCountPerInstance: UINT, + InstanceCount: UINT, + StartIndexLocation: UINT, + BaseVertexLocation: INT, + StartInstanceLocation: UINT, +}} +ENUM!{enum D3D11_RESOURCE_DIMENSION { + D3D11_RESOURCE_DIMENSION_UNKNOWN = 0, + D3D11_RESOURCE_DIMENSION_BUFFER = 1, + D3D11_RESOURCE_DIMENSION_TEXTURE1D = 2, + D3D11_RESOURCE_DIMENSION_TEXTURE2D = 3, + D3D11_RESOURCE_DIMENSION_TEXTURE3D = 4, +}} +pub type D3D11_SRV_DIMENSION = D3D_SRV_DIMENSION; +ENUM!{enum D3D11_DSV_DIMENSION { + D3D11_DSV_DIMENSION_UNKNOWN = 0, + D3D11_DSV_DIMENSION_TEXTURE1D = 1, + D3D11_DSV_DIMENSION_TEXTURE1DARRAY = 2, + D3D11_DSV_DIMENSION_TEXTURE2D = 3, + D3D11_DSV_DIMENSION_TEXTURE2DARRAY = 4, + D3D11_DSV_DIMENSION_TEXTURE2DMS = 5, + D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY = 6, +}} +ENUM!{enum D3D11_RTV_DIMENSION { + D3D11_RTV_DIMENSION_UNKNOWN = 0, + D3D11_RTV_DIMENSION_BUFFER = 1, + D3D11_RTV_DIMENSION_TEXTURE1D = 2, + D3D11_RTV_DIMENSION_TEXTURE1DARRAY = 3, + D3D11_RTV_DIMENSION_TEXTURE2D = 4, + D3D11_RTV_DIMENSION_TEXTURE2DARRAY = 5, + D3D11_RTV_DIMENSION_TEXTURE2DMS = 6, + D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D11_RTV_DIMENSION_TEXTURE3D = 8, +}} +ENUM!{enum D3D11_UAV_DIMENSION { + D3D11_UAV_DIMENSION_UNKNOWN = 0, + D3D11_UAV_DIMENSION_BUFFER = 1, + D3D11_UAV_DIMENSION_TEXTURE1D = 2, + D3D11_UAV_DIMENSION_TEXTURE1DARRAY = 3, + D3D11_UAV_DIMENSION_TEXTURE2D = 4, + D3D11_UAV_DIMENSION_TEXTURE2DARRAY = 5, + D3D11_UAV_DIMENSION_TEXTURE3D = 8, +}} +ENUM!{enum D3D11_USAGE { + D3D11_USAGE_DEFAULT = 0, + D3D11_USAGE_IMMUTABLE = 1, + D3D11_USAGE_DYNAMIC = 2, + D3D11_USAGE_STAGING = 3, +}} +FLAGS!{enum D3D11_BIND_FLAG { + D3D11_BIND_VERTEX_BUFFER = 0x1, + D3D11_BIND_INDEX_BUFFER = 0x2, + D3D11_BIND_CONSTANT_BUFFER = 0x4, + D3D11_BIND_SHADER_RESOURCE = 0x8, + D3D11_BIND_STREAM_OUTPUT = 0x10, + D3D11_BIND_RENDER_TARGET = 0x20, + D3D11_BIND_DEPTH_STENCIL = 0x40, + D3D11_BIND_UNORDERED_ACCESS = 0x80, + D3D11_BIND_DECODER = 0x200, + D3D11_BIND_VIDEO_ENCODER = 0x400, +}} +FLAGS!{enum D3D11_CPU_ACCESS_FLAG { + D3D11_CPU_ACCESS_WRITE = 0x10000, + D3D11_CPU_ACCESS_READ = 0x20000, +}} +FLAGS!{enum D3D11_RESOURCE_MISC_FLAG { + D3D11_RESOURCE_MISC_GENERATE_MIPS = 0x1, + D3D11_RESOURCE_MISC_SHARED = 0x2, + D3D11_RESOURCE_MISC_TEXTURECUBE = 0x4, + D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS = 0x10, + D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS = 0x20, + D3D11_RESOURCE_MISC_BUFFER_STRUCTURED = 0x40, + D3D11_RESOURCE_MISC_RESOURCE_CLAMP = 0x80, + D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX = 0x100, + D3D11_RESOURCE_MISC_GDI_COMPATIBLE = 0x200, + D3D11_RESOURCE_MISC_SHARED_NTHANDLE = 0x800, + D3D11_RESOURCE_MISC_RESTRICTED_CONTENT = 0x1000, + D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE = 0x2000, + D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE_DRIVER = 0x4000, + D3D11_RESOURCE_MISC_GUARDED = 0x8000, + D3D11_RESOURCE_MISC_TILE_POOL = 0x20000, + D3D11_RESOURCE_MISC_TILED = 0x40000, + D3D11_RESOURCE_MISC_HW_PROTECTED = 0x80000, +}} +ENUM!{enum D3D11_MAP { + D3D11_MAP_READ = 1, + D3D11_MAP_WRITE = 2, + D3D11_MAP_READ_WRITE = 3, + D3D11_MAP_WRITE_DISCARD = 4, + D3D11_MAP_WRITE_NO_OVERWRITE = 5, +}} +FLAGS!{enum D3D11_MAP_FLAG { + D3D11_MAP_FLAG_DO_NOT_WAIT = 0x100000, +}} +FLAGS!{enum D3D11_RAISE_FLAG { + D3D11_RAISE_FLAG_DRIVER_INTERNAL_ERROR = 0x1, +}} +FLAGS!{enum D3D11_CLEAR_FLAG { + D3D11_CLEAR_DEPTH = 0x1, + D3D11_CLEAR_STENCIL = 0x2, +}} +pub type D3D11_RECT = RECT; +STRUCT!{struct D3D11_BOX { + left: UINT, + top: UINT, + front: UINT, + right: UINT, + bottom: UINT, + back: UINT, +}} +RIDL!{interface ID3D11DeviceChild(ID3D11DeviceChildVtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut ID3D11Device) -> (), + fn GetPrivateData( + &mut self, guid: REFGUID, pDataSize: *mut UINT, pData: *mut c_void + ) -> HRESULT, + fn SetPrivateData( + &mut self, guid: REFGUID, DataSize: UINT, pData: *const c_void + ) -> HRESULT, + fn SetPrivateDataInterface(&mut self, guid: REFGUID, pData: *const IUnknown) -> HRESULT +}} +ENUM!{enum D3D11_COMPARISON_FUNC { + D3D11_COMPARISON_NEVER = 1, + D3D11_COMPARISON_LESS = 2, + D3D11_COMPARISON_EQUAL = 3, + D3D11_COMPARISON_LESS_EQUAL = 4, + D3D11_COMPARISON_GREATER = 5, + D3D11_COMPARISON_NOT_EQUAL = 6, + D3D11_COMPARISON_GREATER_EQUAL = 7, + D3D11_COMPARISON_ALWAYS = 8, +}} +ENUM!{enum D3D11_DEPTH_WRITE_MASK { + D3D11_DEPTH_WRITE_MASK_ZERO = 0, + D3D11_DEPTH_WRITE_MASK_ALL = 1, +}} +ENUM!{enum D3D11_STENCIL_OP { + D3D11_STENCIL_OP_KEEP = 1, + D3D11_STENCIL_OP_ZERO = 2, + D3D11_STENCIL_OP_REPLACE = 3, + D3D11_STENCIL_OP_INCR_SAT = 4, + D3D11_STENCIL_OP_DECR_SAT = 5, + D3D11_STENCIL_OP_INVERT = 6, + D3D11_STENCIL_OP_INCR = 7, + D3D11_STENCIL_OP_DECR = 8, +}} +STRUCT!{struct D3D11_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D11_STENCIL_OP, + StencilDepthFailOp: D3D11_STENCIL_OP, + StencilPassOp: D3D11_STENCIL_OP, + StencilFunc: D3D11_COMPARISON_FUNC, +}} +STRUCT!{struct D3D11_DEPTH_STENCIL_DESC { + DepthEnable: BOOL, + DepthWriteMask: D3D11_DEPTH_WRITE_MASK, + DepthFunc: D3D11_COMPARISON_FUNC, + StencilEnable: BOOL, + StencilReadMask: UINT8, + StencilWriteMask: UINT8, + FrontFace: D3D11_DEPTH_STENCILOP_DESC, + BackFace: D3D11_DEPTH_STENCILOP_DESC, +}} +RIDL!{interface ID3D11DepthStencilState(ID3D11DepthStencilStateVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_DEPTH_STENCIL_DESC) -> () +}} +ENUM!{enum D3D11_BLEND { + D3D11_BLEND_ZERO = 1, + D3D11_BLEND_ONE = 2, + D3D11_BLEND_SRC_COLOR = 3, + D3D11_BLEND_INV_SRC_COLOR = 4, + D3D11_BLEND_SRC_ALPHA = 5, + D3D11_BLEND_INV_SRC_ALPHA = 6, + D3D11_BLEND_DEST_ALPHA = 7, + D3D11_BLEND_INV_DEST_ALPHA = 8, + D3D11_BLEND_DEST_COLOR = 9, + D3D11_BLEND_INV_DEST_COLOR = 10, + D3D11_BLEND_SRC_ALPHA_SAT = 11, + D3D11_BLEND_BLEND_FACTOR = 14, + D3D11_BLEND_INV_BLEND_FACTOR = 15, + D3D11_BLEND_SRC1_COLOR = 16, + D3D11_BLEND_INV_SRC1_COLOR = 17, + D3D11_BLEND_SRC1_ALPHA = 18, + D3D11_BLEND_INV_SRC1_ALPHA = 19, +}} +ENUM!{enum D3D11_BLEND_OP { + D3D11_BLEND_OP_ADD = 1, + D3D11_BLEND_OP_SUBTRACT = 2, + D3D11_BLEND_OP_REV_SUBTRACT = 3, + D3D11_BLEND_OP_MIN = 4, + D3D11_BLEND_OP_MAX = 5, +}} +FLAGS!{enum D3D11_COLOR_WRITE_ENABLE { + D3D11_COLOR_WRITE_ENABLE_RED = 1, + D3D11_COLOR_WRITE_ENABLE_GREEN = 2, + D3D11_COLOR_WRITE_ENABLE_BLUE = 4, + D3D11_COLOR_WRITE_ENABLE_ALPHA = 8, + D3D11_COLOR_WRITE_ENABLE_ALL = D3D11_COLOR_WRITE_ENABLE_RED.0 | D3D11_COLOR_WRITE_ENABLE_GREEN.0 | + D3D11_COLOR_WRITE_ENABLE_BLUE.0 | D3D11_COLOR_WRITE_ENABLE_ALPHA.0, +}} +STRUCT!{struct D3D11_RENDER_TARGET_BLEND_DESC { + BlendEnable: BOOL, + SrcBlend: D3D11_BLEND, + DestBlend: D3D11_BLEND, + BlendOp: D3D11_BLEND_OP, + SrcBlendAlpha: D3D11_BLEND, + DestBlendAlpha: D3D11_BLEND, + BlendOpAlpha: D3D11_BLEND_OP, + RenderTargetWriteMask: UINT8, +}} +STRUCT!{struct D3D11_BLEND_DESC { + AlphaToCoverageEnable: BOOL, + IndependentBlendEnable: BOOL, + RenderTarget: [D3D11_RENDER_TARGET_BLEND_DESC; 8], +}} +RIDL!{interface ID3D11BlendState(ID3D11BlendStateVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_BLEND_DESC) -> () +}} +STRUCT!{struct D3D11_RASTERIZER_DESC { + FillMode: D3D11_FILL_MODE, + CullMode: D3D11_CULL_MODE, + FrontCounterClockwise: BOOL, + DepthBias: INT, + DepthBiasClamp: FLOAT, + SlopeScaledDepthBias: FLOAT, + DepthClipEnable: BOOL, + ScissorEnable: BOOL, + MultisampleEnable: BOOL, + AntialiasedLineEnable: BOOL, +}} +RIDL!{interface ID3D11RasterizerState(ID3D11RasterizerStateVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_RASTERIZER_DESC) -> () +}} +STRUCT!{struct D3D11_SUBRESOURCE_DATA { + pSysMem: *const c_void, + SysMemPitch: UINT, + SysMemSlicePitch: UINT, +}} +STRUCT!{struct D3D11_MAPPED_SUBRESOURCE { + pData: *mut c_void, + RowPitch: UINT, + DepthPitch: UINT, +}} +RIDL!{interface ID3D11Resource(ID3D11ResourceVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetType(&mut self, pResourceDimension: *mut D3D11_RESOURCE_DIMENSION) -> (), + fn SetEvictionPriority(&mut self, EvictionPriority: UINT) -> (), + fn GetEvictionPriority(&mut self) -> UINT +}} +STRUCT!{struct D3D11_BUFFER_DESC { + ByteWidth: UINT, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, + StructureByteStride: UINT, +}} +RIDL!{interface ID3D11Buffer(ID3D11BufferVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_BUFFER_DESC) -> () +}} +STRUCT!{struct D3D11_TEXTURE1D_DESC { + Width: UINT, + MipLevels: UINT, + ArraySize: UINT, + Format: DXGI_FORMAT, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Texture1D(ID3D11Texture1DVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_TEXTURE1D_DESC) -> () +}} +STRUCT!{struct D3D11_TEXTURE2D_DESC { + Width: UINT, + Height: UINT, + MipLevels: UINT, + ArraySize: UINT, + Format: DXGI_FORMAT, + SampleDesc: DXGI_SAMPLE_DESC, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Texture2D(ID3D11Texture2DVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_TEXTURE2D_DESC) -> () +}} +STRUCT!{struct D3D11_TEXTURE3D_DESC { + Width: UINT, + Height: UINT, + Depth: UINT, + MipLevels: UINT, + Format: DXGI_FORMAT, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Texture3D(ID3D11Texture3DVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_TEXTURE3D_DESC) -> () +}} +ENUM!{enum D3D11_TEXTURECUBE_FACE { + D3D11_TEXTURECUBE_FACE_POSITIVE_X = 0, + D3D11_TEXTURECUBE_FACE_NEGATIVE_X = 1, + D3D11_TEXTURECUBE_FACE_POSITIVE_Y = 2, + D3D11_TEXTURECUBE_FACE_NEGATIVE_Y = 3, + D3D11_TEXTURECUBE_FACE_POSITIVE_Z = 4, + D3D11_TEXTURECUBE_FACE_NEGATIVE_Z = 5, +}} +RIDL!{interface ID3D11View(ID3D11ViewVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetResource(&mut self, ppResource: *mut *mut ID3D11Resource) -> () +}} +STRUCT!{struct D3D11_BUFFER_SRV { + u1: UINT, + u2: UINT, +}} +UNION!{D3D11_BUFFER_SRV, u1, FirstElement, FirstElement_mut, UINT} +UNION!{D3D11_BUFFER_SRV, u1, ElementOffset, ElementOffset_mut, UINT} +UNION!{D3D11_BUFFER_SRV, u2, NumElements, NumElements_mut, UINT} +UNION!{D3D11_BUFFER_SRV, u2, ElementWidth, ElementWidth_mut, UINT} +FLAGS!{enum D3D11_BUFFEREX_SRV_FLAG { + D3D11_BUFFEREX_SRV_FLAG_RAW = 0x1, +}} +STRUCT!{struct D3D11_BUFFEREX_SRV { + FirstElement: UINT, + NumElements: UINT, + Flags: UINT, +}} +STRUCT!{struct D3D11_TEX1D_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX3D_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEXCUBE_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEXCUBE_ARRAY_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, + First2DArrayFace: UINT, + NumCubes: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_SRV { + UnusedField_NothingToDefine: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_ARRAY_SRV { + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_SRV_DIMENSION, + u: [UINT; 4], +}} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Buffer, Buffer_mut, D3D11_BUFFER_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, D3D11_TEX2DMS_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + D3D11_TEX2DMS_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture3D, Texture3D_mut, D3D11_TEX3D_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, TextureCube, TextureCube_mut, D3D11_TEXCUBE_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, TextureCubeArray, TextureCubeArray_mut, + D3D11_TEXCUBE_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, BufferEx, BufferEx_mut, D3D11_BUFFEREX_SRV} +RIDL!{interface ID3D11ShaderResourceView(ID3D11ShaderResourceViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_RESOURCE_VIEW_DESC) -> () +}} +STRUCT!{struct D3D11_BUFFER_RTV { + u1: UINT, + u2: UINT, +}} +UNION!{D3D11_BUFFER_RTV, u1, FirstElement, FirstElement_mut, UINT} +UNION!{D3D11_BUFFER_RTV, u1, ElementOffset, ElementOffset_mut, UINT} +UNION!{D3D11_BUFFER_RTV, u2, NumElements, NumElements_mut, UINT} +UNION!{D3D11_BUFFER_RTV, u2, ElementWidth, ElementWidth_mut, UINT} +STRUCT!{struct D3D11_TEX1D_RTV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_RTV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_RTV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_RTV { + UnusedField_NothingToDefine: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_RTV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_ARRAY_RTV { + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX3D_RTV { + MipSlice: UINT, + FirstWSlice: UINT, + WSize: UINT, +}} +STRUCT!{struct D3D11_RENDER_TARGET_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_RTV_DIMENSION, + u: [UINT; 3], +}} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Buffer, Buffer_mut, D3D11_BUFFER_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, D3D11_TEX2DMS_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2DMSArray,Texture2DMSArray_mut, + D3D11_TEX2DMS_ARRAY_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture3D, Texture3D_mut, D3D11_TEX3D_RTV} +RIDL!{interface ID3D11RenderTargetView(ID3D11RenderTargetViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_RENDER_TARGET_VIEW_DESC) -> () +}} +STRUCT!{struct D3D11_TEX1D_DSV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_DSV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_DSV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_DSV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_DSV { + UnusedField_NothingToDefine: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_ARRAY_DSV { + FirstArraySlice: UINT, + ArraySize: UINT, +}} +FLAGS!{enum D3D11_DSV_FLAG{ + D3D11_DSV_READ_ONLY_DEPTH = 0x1, + D3D11_DSV_READ_ONLY_STENCIL = 0x2, +}} +STRUCT!{struct D3D11_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_DSV_DIMENSION, + Flags: UINT, + u: [UINT; 3], +}} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, D3D11_TEX2DMS_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + D3D11_TEX2DMS_ARRAY_DSV} +RIDL!{interface ID3D11DepthStencilView(ID3D11DepthStencilViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_DEPTH_STENCIL_VIEW_DESC) -> () +}} +FLAGS!{enum D3D11_BUFFER_UAV_FLAG { + D3D11_BUFFER_UAV_FLAG_RAW = 0x1, + D3D11_BUFFER_UAV_FLAG_APPEND = 0x2, + D3D11_BUFFER_UAV_FLAG_COUNTER = 0x4, +}} +STRUCT!{struct D3D11_BUFFER_UAV { + FirstElement: UINT, + NumElements: UINT, + Flags: UINT, +}} +STRUCT!{struct D3D11_TEX1D_UAV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_UAV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_UAV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_UAV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX3D_UAV { + MipSlice: UINT, + FirstWSlice: UINT, + WSize: UINT, +}} +STRUCT!{struct D3D11_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_UAV_DIMENSION, + u: [UINT; 3], +}} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Buffer, Buffer_mut, D3D11_BUFFER_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture3D, Texture3D_mut, D3D11_TEX3D_UAV} +RIDL!{interface ID3D11UnorderedAccessView(ID3D11UnorderedAccessViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_UNORDERED_ACCESS_VIEW_DESC) -> () +}} +RIDL!{interface ID3D11VertexShader(ID3D11VertexShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11HullShader(ID3D11HullShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11DomainShader(ID3D11DomainShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11GeometryShader(ID3D11GeometryShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11PixelShader(ID3D11PixelShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11ComputeShader(ID3D11ComputeShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11InputLayout(ID3D11InputLayoutVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +ENUM!{enum D3D11_FILTER { + D3D11_FILTER_MIN_MAG_MIP_POINT = 0, + D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1, + D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, + D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5, + D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10, + D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, + D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14, + D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15, + D3D11_FILTER_ANISOTROPIC = 0x55, + D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80, + D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, + D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, + D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, + D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, + D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, + D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, + D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, + D3D11_FILTER_COMPARISON_ANISOTROPIC = 0xd5, + D3D11_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100, + D3D11_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, + D3D11_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, + D3D11_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, + D3D11_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, + D3D11_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, + D3D11_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, + D3D11_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, + D3D11_FILTER_MINIMUM_ANISOTROPIC = 0x155, + D3D11_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180, + D3D11_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, + D3D11_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, + D3D11_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, + D3D11_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, + D3D11_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, + D3D11_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, + D3D11_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, + D3D11_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5, +}} +ENUM!{enum D3D11_FILTER_TYPE { + D3D11_FILTER_TYPE_POINT = 0, + D3D11_FILTER_TYPE_LINEAR = 1, +}} +ENUM!{enum D3D11_FILTER_REDUCTION_TYPE { + D3D11_FILTER_REDUCTION_TYPE_STANDARD = 0, + D3D11_FILTER_REDUCTION_TYPE_COMPARISON = 1, + D3D11_FILTER_REDUCTION_TYPE_MINIMUM = 2, + D3D11_FILTER_REDUCTION_TYPE_MAXIMUM = 3, +}} +pub const D3D11_FILTER_REDUCTION_TYPE_MASK: DWORD = 0x3; +pub const D3D11_FILTER_REDUCTION_TYPE_SHIFT: DWORD = 7; +pub const D3D11_FILTER_TYPE_MASK: DWORD = 0x3; +pub const D3D11_MIN_FILTER_SHIFT: DWORD = 4; +pub const D3D11_MAG_FILTER_SHIFT: DWORD = 2; +pub const D3D11_MIP_FILTER_SHIFT: DWORD = 0; +pub const D3D11_COMPARISON_FILTERING_BIT: DWORD = 0x80; +pub const D3D11_ANISOTROPIC_FILTERING_BIT: DWORD = 0x40; +ENUM!{enum D3D11_TEXTURE_ADDRESS_MODE { + D3D11_TEXTURE_ADDRESS_WRAP = 1, + D3D11_TEXTURE_ADDRESS_MIRROR = 2, + D3D11_TEXTURE_ADDRESS_CLAMP = 3, + D3D11_TEXTURE_ADDRESS_BORDER = 4, + D3D11_TEXTURE_ADDRESS_MIRROR_ONCE = 5, +}} +STRUCT!{struct D3D11_SAMPLER_DESC { + Filter: D3D11_FILTER, + AddressU: D3D11_TEXTURE_ADDRESS_MODE, + AddressV: D3D11_TEXTURE_ADDRESS_MODE, + AddressW: D3D11_TEXTURE_ADDRESS_MODE, + MipLODBias: FLOAT, + MaxAnisotropy: UINT, + ComparisonFunc: D3D11_COMPARISON_FUNC, + BorderColor: [FLOAT; 4], + MinLOD: FLOAT, + MaxLOD: FLOAT, +}} +RIDL!{interface ID3D11SamplerState(ID3D11SamplerStateVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SAMPLER_DESC) -> () +}} +FLAGS!{enum D3D11_FORMAT_SUPPORT { + D3D11_FORMAT_SUPPORT_BUFFER = 0x1, + D3D11_FORMAT_SUPPORT_IA_VERTEX_BUFFER = 0x2, + D3D11_FORMAT_SUPPORT_IA_INDEX_BUFFER = 0x4, + D3D11_FORMAT_SUPPORT_SO_BUFFER = 0x8, + D3D11_FORMAT_SUPPORT_TEXTURE1D = 0x10, + D3D11_FORMAT_SUPPORT_TEXTURE2D = 0x20, + D3D11_FORMAT_SUPPORT_TEXTURE3D = 0x40, + D3D11_FORMAT_SUPPORT_TEXTURECUBE = 0x80, + D3D11_FORMAT_SUPPORT_SHADER_LOAD = 0x100, + D3D11_FORMAT_SUPPORT_SHADER_SAMPLE = 0x200, + D3D11_FORMAT_SUPPORT_SHADER_SAMPLE_COMPARISON = 0x400, + D3D11_FORMAT_SUPPORT_SHADER_SAMPLE_MONO_TEXT = 0x800, + D3D11_FORMAT_SUPPORT_MIP = 0x1000, + D3D11_FORMAT_SUPPORT_MIP_AUTOGEN = 0x2000, + D3D11_FORMAT_SUPPORT_RENDER_TARGET = 0x4000, + D3D11_FORMAT_SUPPORT_BLENDABLE = 0x8000, + D3D11_FORMAT_SUPPORT_DEPTH_STENCIL = 0x10000, + D3D11_FORMAT_SUPPORT_CPU_LOCKABLE = 0x20000, + D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE = 0x40000, + D3D11_FORMAT_SUPPORT_DISPLAY = 0x80000, + D3D11_FORMAT_SUPPORT_CAST_WITHIN_BIT_LAYOUT = 0x100000, + D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET = 0x200000, + D3D11_FORMAT_SUPPORT_MULTISAMPLE_LOAD = 0x400000, + D3D11_FORMAT_SUPPORT_SHADER_GATHER = 0x800000, + D3D11_FORMAT_SUPPORT_BACK_BUFFER_CAST = 0x1000000, + D3D11_FORMAT_SUPPORT_TYPED_UNORDERED_ACCESS_VIEW = 0x2000000, + D3D11_FORMAT_SUPPORT_SHADER_GATHER_COMPARISON = 0x4000000, + D3D11_FORMAT_SUPPORT_DECODER_OUTPUT = 0x8000000, + D3D11_FORMAT_SUPPORT_VIDEO_PROCESSOR_OUTPUT = 0x10000000, + D3D11_FORMAT_SUPPORT_VIDEO_PROCESSOR_INPUT = 0x20000000, + D3D11_FORMAT_SUPPORT_VIDEO_ENCODER = 0x40000000, +}} +FLAGS!{enum D3D11_FORMAT_SUPPORT2 { + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_ADD = 0x1, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS = 0x2, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE = 0x4, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_EXCHANGE = 0x8, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX = 0x10, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX = 0x20, + D3D11_FORMAT_SUPPORT2_UAV_TYPED_LOAD = 0x40, + D3D11_FORMAT_SUPPORT2_UAV_TYPED_STORE = 0x80, + D3D11_FORMAT_SUPPORT2_OUTPUT_MERGER_LOGIC_OP = 0x100, + D3D11_FORMAT_SUPPORT2_TILED = 0x200, + D3D11_FORMAT_SUPPORT2_SHAREABLE = 0x400, + D3D11_FORMAT_SUPPORT2_MULTIPLANE_OVERLAY = 0x4000, +}} +RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDataSize(&mut self) -> UINT +}} +FLAGS!{enum D3D11_ASYNC_GETDATA_FLAG { + D3D11_ASYNC_GETDATA_DONOTFLUSH = 0x1, +}} +ENUM!{enum D3D11_QUERY { + D3D11_QUERY_EVENT = 0, + D3D11_QUERY_OCCLUSION = D3D11_QUERY_EVENT.0 + 1, + D3D11_QUERY_TIMESTAMP = D3D11_QUERY_OCCLUSION.0 + 1, + D3D11_QUERY_TIMESTAMP_DISJOINT = D3D11_QUERY_TIMESTAMP.0 + 1, + D3D11_QUERY_PIPELINE_STATISTICS = D3D11_QUERY_TIMESTAMP_DISJOINT.0 + 1, + D3D11_QUERY_OCCLUSION_PREDICATE = D3D11_QUERY_PIPELINE_STATISTICS.0 + 1, + D3D11_QUERY_SO_STATISTICS = D3D11_QUERY_OCCLUSION_PREDICATE.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE = D3D11_QUERY_SO_STATISTICS.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM0 = D3D11_QUERY_SO_OVERFLOW_PREDICATE.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM0 = D3D11_QUERY_SO_STATISTICS_STREAM0.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM1 = D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM0.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM1 = D3D11_QUERY_SO_STATISTICS_STREAM1.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM2 = D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM1.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM2 = D3D11_QUERY_SO_STATISTICS_STREAM2.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM3 = D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM2.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM3 = D3D11_QUERY_SO_STATISTICS_STREAM3.0 + 1, +}} +FLAGS!{enum D3D11_QUERY_MISC_FLAG { + D3D11_QUERY_MISC_PREDICATEHINT = 0x1, +}} +STRUCT!{struct D3D11_QUERY_DESC { + Query: D3D11_QUERY, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Query(ID3D11QueryVtbl): ID3D11Asynchronous(ID3D11AsynchronousVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_QUERY_DESC) -> () +}} +RIDL!{interface ID3D11Predicate(ID3D11PredicateVtbl): ID3D11Query(ID3D11QueryVtbl) {}} +STRUCT!{struct D3D11_QUERY_DATA_TIMESTAMP_DISJOINT { + Frequency: UINT64, + Disjoint: BOOL, +}} +STRUCT!{struct D3D11_QUERY_DATA_PIPELINE_STATISTICS { + IAVertices: UINT64, + IAPrimitives: UINT64, + VSInvocations: UINT64, + GSInvocations: UINT64, + GSPrimitives: UINT64, + CInvocations: UINT64, + CPrimitives: UINT64, + PSInvocations: UINT64, + HSInvocations: UINT64, + DSInvocations: UINT64, + CSInvocations: UINT64, +}} +STRUCT!{struct D3D11_QUERY_DATA_SO_STATISTICS { + NumPrimitivesWritten: UINT64, + PrimitivesStorageNeeded: UINT64, +}} +FLAGS!{enum D3D11_COUNTER { + D3D11_COUNTER_DEVICE_DEPENDENT_0 = 0x40000000, +}} +ENUM!{enum D3D11_COUNTER_TYPE { + D3D11_COUNTER_TYPE_FLOAT32 = 0, + D3D11_COUNTER_TYPE_UINT16 = D3D11_COUNTER_TYPE_FLOAT32.0 + 1, + D3D11_COUNTER_TYPE_UINT32 = D3D11_COUNTER_TYPE_UINT16.0 + 1, + D3D11_COUNTER_TYPE_UINT64 = D3D11_COUNTER_TYPE_UINT32.0 + 1, +}} +STRUCT!{struct D3D11_COUNTER_DESC { + Counter: D3D11_COUNTER, + MiscFlags: UINT, +}} +STRUCT!{struct D3D11_COUNTER_INFO { + LastDeviceDependentCounter: D3D11_COUNTER, + NumSimultaneousCounters: UINT, + NumDetectableParallelUnits: UINT8, +}} +RIDL!{interface ID3D11Counter(ID3D11CounterVtbl): ID3D11Asynchronous(ID3D11AsynchronousVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_COUNTER_DESC) -> () +}} +ENUM!{enum D3D11_STANDARD_MULTISAMPLE_QUALITY_LEVELS { + D3D11_STANDARD_MULTISAMPLE_PATTERN = 0xffffffff, + D3D11_CENTER_MULTISAMPLE_PATTERN = 0xfffffffe, +}} +ENUM!{enum D3D11_DEVICE_CONTEXT_TYPE { + D3D11_DEVICE_CONTEXT_IMMEDIATE = 0, + D3D11_DEVICE_CONTEXT_DEFERRED = D3D11_DEVICE_CONTEXT_IMMEDIATE.0 + 1, +}} +STRUCT!{struct D3D11_CLASS_INSTANCE_DESC { + InstanceId: UINT, + InstanceIndex: UINT, + TypeId: UINT, + ConstantBuffer: UINT, + BaseConstantBufferOffset: UINT, + BaseTexture: UINT, + BaseSampler: UINT, + Created: BOOL, +}} +RIDL!{interface ID3D11ClassInstance(ID3D11ClassInstanceVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetClassLinkage(&mut self, ppLinkage: *mut *mut ID3D11ClassLinkage) -> (), + fn GetDesc(&mut self, pDesc: *mut D3D11_CLASS_INSTANCE_DESC) -> (), + fn GetInstanceName(&mut self, pInstanceName: LPSTR, pBufferLength: *mut SIZE_T) -> (), + fn GetTypeName(&mut self, pTypeName: LPSTR, pBufferLength: *mut SIZE_T) -> () +}} +RIDL!{interface ID3D11ClassLinkage(ID3D11ClassLinkageVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetClassInstance( + &mut self, GetClassInstance: LPCSTR, InstanceIndex: UINT, + ppInstance: *mut *mut ID3D11ClassInstance + ) -> HRESULT, + fn CreateClassInstance( + &mut self, pClassTypeName: LPCSTR, ConstantBufferOffset: UINT, ConstantVectorOffset: UINT, TextureOffset: UINT, SamplerOffset: UINT, ppInstance: *mut *mut ID3D11ClassInstance + ) -> HRESULT +}} +RIDL!{interface ID3D11CommandList(ID3D11CommandListVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetContextFlags(&mut self) -> UINT +}} +ENUM!{enum D3D11_FEATURE { + D3D11_FEATURE_THREADING = 0, + D3D11_FEATURE_DOUBLES = D3D11_FEATURE_THREADING.0 + 1, + D3D11_FEATURE_FORMAT_SUPPORT = D3D11_FEATURE_DOUBLES.0 + 1, + D3D11_FEATURE_FORMAT_SUPPORT2 = D3D11_FEATURE_FORMAT_SUPPORT.0 + 1, + D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS = D3D11_FEATURE_FORMAT_SUPPORT2.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS = D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS.0 + 1, + D3D11_FEATURE_ARCHITECTURE_INFO = D3D11_FEATURE_D3D11_OPTIONS.0 + 1, + D3D11_FEATURE_D3D9_OPTIONS = D3D11_FEATURE_ARCHITECTURE_INFO.0 + 1, + D3D11_FEATURE_SHADER_MIN_PRECISION_SUPPORT = D3D11_FEATURE_D3D9_OPTIONS.0 + 1, + D3D11_FEATURE_D3D9_SHADOW_SUPPORT = D3D11_FEATURE_SHADER_MIN_PRECISION_SUPPORT.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS1 = D3D11_FEATURE_D3D9_SHADOW_SUPPORT.0 + 1, + D3D11_FEATURE_D3D9_SIMPLE_INSTANCING_SUPPORT = D3D11_FEATURE_D3D11_OPTIONS1.0 + 1, + D3D11_FEATURE_MARKER_SUPPORT = D3D11_FEATURE_D3D9_SIMPLE_INSTANCING_SUPPORT.0 + 1, + D3D11_FEATURE_D3D9_OPTIONS1 = D3D11_FEATURE_MARKER_SUPPORT.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS2 = D3D11_FEATURE_D3D9_OPTIONS1.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS3 = D3D11_FEATURE_D3D11_OPTIONS2.0 + 1, + D3D11_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = D3D11_FEATURE_D3D11_OPTIONS3.0 + 1, +}} +STRUCT!{struct D3D11_FEATURE_DATA_THREADING { + DriverConcurrentCreates: BOOL, + DriverCommandLists: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_DOUBLES { + DoublePrecisionFloatShaderOps: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_FORMAT_SUPPORT { + InFormat: DXGI_FORMAT, + OutFormatSupport: UINT, +}} +STRUCT!{struct D3D11_FEATURE_DATA_FORMAT_SUPPORT2 { + InFormat: DXGI_FORMAT, + OutFormatSupport2: UINT, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS { + ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS { + OutputMergerLogicOp: BOOL, + UAVOnlyRenderingForcedSampleCount: BOOL, + DiscardAPIsSeenByDriver: BOOL, + FlagsForUpdateAndCopySeenByDriver: BOOL, + ClearView: BOOL, + CopyWithOverlap: BOOL, + ConstantBufferPartialUpdate: BOOL, + ConstantBufferOffsetting: BOOL, + MapNoOverwriteOnDynamicConstantBuffer: BOOL, + MapNoOverwriteOnDynamicBufferSRV: BOOL, + MultisampleRTVWithForcedSampleCountOne: BOOL, + SAD4ShaderInstructions: BOOL, + ExtendedDoublesShaderInstructions: BOOL, + ExtendedResourceSharing: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_ARCHITECTURE_INFO { + TileBasedDeferredRenderer: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_OPTIONS { + FullNonPow2TextureSupport: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_SHADOW_SUPPORT { + SupportsDepthAsTextureWithLessEqualComparisonFilter: BOOL, +}} +FLAGS!{enum D3D11_SHADER_MIN_PRECISION_SUPPORT { + D3D11_SHADER_MIN_PRECISION_10_BIT = 0x1, + D3D11_SHADER_MIN_PRECISION_16_BIT = 0x2, +}} +STRUCT!{struct D3D11_FEATURE_DATA_SHADER_MIN_PRECISION_SUPPORT { + PixelShaderMinPrecision: UINT, + AllOtherShaderStagesMinPrecision: UINT, +}} +ENUM!{enum D3D11_TILED_RESOURCES_TIER { + D3D11_TILED_RESOURCES_NOT_SUPPORTED = 0, + D3D11_TILED_RESOURCES_TIER_1 = 1, + D3D11_TILED_RESOURCES_TIER_2 = 2, + D3D11_TILED_RESOURCES_TIER_3 = 3, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS1 { + TiledResourcesTier: D3D11_TILED_RESOURCES_TIER, + MinMaxFiltering: BOOL, + ClearViewAlsoSupportsDepthOnlyFormats: BOOL, + MapOnDefaultBuffers: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_SIMPLE_INSTANCING_SUPPORT { + SimpleInstancingSupported: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_MARKER_SUPPORT { + Profile: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_OPTIONS1 { + FullNonPow2TextureSupported: BOOL, + DepthAsTextureWithLessEqualComparisonFilterSupported: BOOL, + SimpleInstancingSupported: BOOL, + TextureCubeFaceRenderTargetWithNonCubeDepthStencilSupported: BOOL, +}} +ENUM!{enum D3D11_CONSERVATIVE_RASTERIZATION_TIER { + D3D11_CONSERVATIVE_RASTERIZATION_NOT_SUPPORTED = 0, + D3D11_CONSERVATIVE_RASTERIZATION_TIER_1 = 1, + D3D11_CONSERVATIVE_RASTERIZATION_TIER_2 = 2, + D3D11_CONSERVATIVE_RASTERIZATION_TIER_3 = 3, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS2 { + PSSpecifiedStencilRefSupported: BOOL, + TypedUAVLoadAdditionalFormats: BOOL, + ROVsSupported: BOOL, + ConservativeRasterizationTier: D3D11_CONSERVATIVE_RASTERIZATION_TIER, + TiledResourcesTier: D3D11_TILED_RESOURCES_TIER, + MapOnDefaultTextures: BOOL, + StandardSwizzle: BOOL, + UnifiedMemoryArchitecture: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS3 { + VPAndRTArrayIndexFromAnyShaderFeedingRasterizer: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT { + MaxGPUVirtualAddressBitsPerResource: UINT, + MaxGPUVirtualAddressBitsPerProcess: UINT, +}} +RIDL!{interface ID3D11DeviceContext(ID3D11DeviceContextVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn VSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn PSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn PSSetShader( + &mut self, pPixelShader: *mut ID3D11PixelShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn PSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn VSSetShader( + &mut self, pVertexShader: *mut ID3D11VertexShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn DrawIndexed( + &mut self, IndexCount: UINT, StartIndexLocation: UINT, BaseVertexLocation: INT + ) -> (), + fn Draw(&mut self, VertexCount: UINT, StartVertexLocation: UINT) -> (), + fn Map( + &mut self, pResource: *mut ID3D11Resource, Subresource: UINT, MapType: D3D11_MAP, + MapFlags: UINT, pMappedResource: *mut D3D11_MAPPED_SUBRESOURCE + ) -> HRESULT, + fn Unmap(&mut self, pResource: *mut ID3D11Resource, Subresource: UINT) -> (), + fn PSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn IASetInputLayout(&mut self, pInputLayout: *mut ID3D11InputLayout) -> (), + fn IASetVertexBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppVertexBuffers: *const *mut ID3D11Buffer, + pStrides: *const UINT, pOffsets: *const UINT + ) -> (), + fn IASetIndexBuffer( + &mut self, pIndexBuffer: *mut ID3D11Buffer, Format: DXGI_FORMAT, Offset: UINT + ) -> (), + fn DrawIndexedInstanced( + &mut self, IndexCountPerInstance: UINT, InstanceCount: UINT, StartIndexLocation: UINT, + BaseVertexLocation: INT, StartInstanceLocation: UINT + ) -> (), + fn DrawInstanced( + &mut self, VertexCountPerInstance: UINT, InstanceCount: UINT, StartVertexLocation: UINT, + StartInstanceLocation: UINT + ) -> (), + fn GSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn GSSetShader( + &mut self, pShader: *mut ID3D11GeometryShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn IASetPrimitiveTopology(&mut self, Topology: D3D11_PRIMITIVE_TOPOLOGY) -> (), + fn VSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn VSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn Begin(&mut self, pAsync: *mut ID3D11Asynchronous) -> (), + fn End(&mut self, pAsync: *mut ID3D11Asynchronous) -> (), + fn GetData( + &mut self, pAsync: *mut ID3D11Asynchronous, pData: *mut c_void, DataSize: UINT, + GetDataFlags: UINT + ) -> HRESULT, + fn SetPredication( + &mut self, pPredicate: *mut ID3D11Predicate, PredicateValue: BOOL + ) -> (), + fn GSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn GSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn OMSetRenderTargets( + &mut self, NumViews: UINT, ppRenderTargetViews: *const *mut ID3D11RenderTargetView, + pDepthStencilView: *mut ID3D11DepthStencilView + ) -> (), + fn OMSetRenderTargetsAndUnorderedAccessViews( + &mut self, NumRTVs: UINT, ppRenderTargetViews: *const *mut ID3D11RenderTargetView, + pDepthStencilView: *mut ID3D11DepthStencilView, UAVStartSlot: UINT, NumUAVs: UINT, + ppUnorderedAccessViews: *const *mut ID3D11UnorderedAccessView, + pUAVInitialCounts: *const UINT + ) -> (), + fn OMSetBlendState( + &mut self, pBlendState: *mut ID3D11BlendState, BlendFactor: &[FLOAT; 4], SampleMask: UINT + ) -> (), + fn OMSetDepthStencilState( + &mut self, pDepthStencilState: *mut ID3D11DepthStencilState, StencilRef: UINT + ) -> (), + fn SOSetTargets( + &mut self, NumBuffers: UINT, ppSOTargets: *const *mut ID3D11Buffer, pOffsets: *const UINT + ) -> (), + fn DrawAuto(&mut self) -> (), + fn DrawIndexedInstancedIndirect( + &mut self, pBufferForArgs: *mut ID3D11Buffer, AlignedByteOffsetForArgs: UINT + ) -> (), + fn DrawInstancedIndirect( + &mut self, pBufferForArgs: *mut ID3D11Buffer, AlignedByteOffsetForArgs: UINT + ) -> (), + fn Dispatch( + &mut self, ThreadGroupCountX: UINT, ThreadGroupCountY: UINT, ThreadGroupCountZ: UINT + ) -> (), + fn DispatchIndirect( + &mut self, pBufferForArgs: *mut ID3D11Buffer, AlignedByteOffsetForArgs: UINT + ) -> (), + fn RSSetState(&mut self, pRasterizerState: *mut ID3D11RasterizerState) -> (), + fn RSSetViewports(&mut self, NumViewports: UINT, pViewports: *const D3D11_VIEWPORT) -> (), + fn RSSetScissorRects(&mut self, NumRects: UINT, pRects: *const D3D11_RECT) -> (), + fn CopySubresourceRegion( + &mut self, pDstResource: *mut ID3D11Resource, DstSubresource: UINT, DstX: UINT, DstY: UINT, + DstZ: UINT, pSrcResource: *mut ID3D11Resource, SrcSubresource: UINT, + pSrcBox: *const D3D11_BOX + ) -> (), + fn CopyResource( + &mut self, pDstResource: *mut ID3D11Resource, pSrcResource: *mut ID3D11Resource + ) -> (), + fn UpdateSubresource( + &mut self, pDstResource: *mut ID3D11Resource, DstSubresource: UINT, + pDstBox: *const D3D11_BOX, pSrcData: *const c_void, SrcRowPitch: UINT, SrcDepthPitch: UINT + ) -> (), + fn CopyStructureCount( + &mut self, pDstBuffer: *mut ID3D11Buffer, DstAlignedByteOffset: UINT, + pSrcView: *mut ID3D11UnorderedAccessView + ) -> (), + fn ClearRenderTargetView( + &mut self, pRenderTargetView: *mut ID3D11RenderTargetView, ColorRGBA: &[FLOAT; 4] + ) -> (), + fn ClearUnorderedAccessViewUint( + &mut self, pUnorderedAccessView: *mut ID3D11UnorderedAccessView, Values: &[UINT; 4] + ) -> (), + fn ClearUnorderedAccessViewFloat( + &mut self, pUnorderedAccessView: *mut ID3D11UnorderedAccessView, Values: &[FLOAT; 4] + ) -> (), + fn ClearDepthStencilView( + &mut self, pDepthStencilView: *mut ID3D11DepthStencilView, ClearFlags: UINT, Depth: FLOAT, + Stencil: UINT8 + ) -> (), + fn GenerateMips(&mut self, pShaderResourceView: *mut ID3D11ShaderResourceView) -> (), + fn SetResourceMinLOD(&mut self, pResource: *mut ID3D11Resource, MinLOD: FLOAT) -> (), + fn GetResourceMinLOD(&mut self, pResource: *mut ID3D11Resource) -> FLOAT, + fn ResolveSubresource( + &mut self, pDstResource: *mut ID3D11Resource, DstSubresource: UINT, + pSrcResource: *mut ID3D11Resource, SrcSubresource: UINT, Format: DXGI_FORMAT + ) -> (), + fn ExecuteCommandList( + &mut self, pCommandList: *mut ID3D11CommandList, + RestoreContextState: BOOL + ) -> (), + fn HSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn HSSetShader( + &mut self, pHullShader: *mut ID3D11HullShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn HSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn HSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn DSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn DSSetShader( + &mut self, pDomainShader: *mut ID3D11DomainShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn DSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn DSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn CSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn CSSetUnorderedAccessViews( + &mut self, StartSlot: UINT, NumUAVs: UINT, + ppUnorderedAccessViews: *const *mut ID3D11UnorderedAccessView + ) -> (), + fn CSSetShader( + &mut self, pComputeShader: *mut ID3D11ComputeShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn CSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn CSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn VSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn PSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn PSGetShader( + &mut self, ppPixelShader: *mut *mut ID3D11PixelShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn PSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn VSGetShader( + &mut self, ppVertexShader: *mut *mut ID3D11VertexShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn PSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn IAGetInputLayout(&mut self, ppInputLayout: *mut *mut ID3D11InputLayout) -> (), + fn IAGetVertexBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppVertexBuffers: *mut *mut ID3D11Buffer, + pStrides: *mut UINT, pOffsets: *mut UINT + ) -> (), + fn IAGetIndexBuffer( + &mut self, pIndexBuffer: *mut *mut ID3D11Buffer, Format: *mut DXGI_FORMAT, + Offset: *mut UINT + ) -> (), + fn GSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn GSGetShader( + &mut self, ppGeometryShader: *mut *mut ID3D11GeometryShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn IAGetPrimitiveTopology(&mut self, pTopology: *mut D3D11_PRIMITIVE_TOPOLOGY) -> (), + fn VSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn VSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn GetPredication( + &mut self, ppPredicate: *mut *mut ID3D11Predicate, pPredicateValue: *mut BOOL + ) -> (), + fn GSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn GSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn OMGetRenderTargets( + &mut self, NumViews: UINT, ppRenderTargetViews: *mut *mut ID3D11RenderTargetView, + ppDepthStencilView: *mut *mut ID3D11DepthStencilView + ) -> (), + fn OMGetRenderTargetsAndUnorderedAccessViews( + &mut self, NumRTVs: UINT, ppRenderTargetViews: *mut *mut ID3D11RenderTargetView, + ppDepthStencilView: *mut *mut ID3D11DepthStencilView, UAVStartSlot: UINT, + ppUnorderedAccessViews: *mut *mut ID3D11UnorderedAccessView + ) -> (), + fn OMGetBlendState( + &mut self, ppBlendState: *mut *mut ID3D11BlendState, BlendFactor: &mut [FLOAT; 4], + pSampleMask: *mut UINT + ) -> (), + fn OMGetDepthStencilState( + &mut self, ppDepthStencilState: *mut *mut ID3D11DepthStencilState, pStencilRef: *mut UINT + ) -> (), + fn SOGetTargets(&mut self, NumBuffers: UINT, ppSOTargets: *mut *mut ID3D11Buffer) -> (), + fn RSGetState(&mut self, ppRasterizerState: *mut *mut ID3D11RasterizerState) -> (), + fn RSGetViewports(&mut self, pNumViewports: *mut UINT, pViewports: *mut D3D11_VIEWPORT) -> (), + fn RSGetScissorRects(&mut self, pNumRects: *mut UINT, pRects: *mut D3D11_RECT) -> (), + fn HSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn HSGetShader( + &mut self, ppHullShader: *mut *mut ID3D11HullShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn HSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn HSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn DSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn DSGetShader( + &mut self, ppDomainShader: *mut *mut ID3D11DomainShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn DSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn DSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn CSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn CSGetUnorderedAccessViews( + &mut self, StartSlot: UINT, NumUAVs: UINT, + ppUnorderedAccessViews: *mut *mut ID3D11UnorderedAccessView + ) -> (), + fn CSGetShader( + &mut self, ppComputeShader: *mut *mut ID3D11ComputeShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn CSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn CSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn ClearState(&mut self) -> (), + fn Flush(&mut self) -> (), + fn GetType(&mut self) -> D3D11_DEVICE_CONTEXT_TYPE, + fn GetContextFlags(&mut self) -> UINT, + fn FinishCommandList( + &mut self, RestoreDeferredContextState: BOOL, ppCommandList: *mut *mut ID3D11CommandList + ) -> HRESULT +}} +STRUCT!{struct D3D11_VIDEO_DECODER_DESC { + Guid: GUID, + SampleWidth: UINT, + SampleHeight: UINT, + OutputFormat: DXGI_FORMAT, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_CONFIG { + guidConfigBitstreamEncryption: GUID, + guidConfigMBcontrolEncryption: GUID, + guidConfigResidDiffEncryption: GUID, + ConfigBitstreamRaw: UINT, + ConfigMBcontrolRasterOrder: UINT, + ConfigResidDiffHost: UINT, + ConfigSpatialResid8: UINT, + ConfigResid8Subtraction: UINT, + ConfigSpatialHost8or9Clipping: UINT, + ConfigSpatialResidInterleaved: UINT, + ConfigIntraResidUnsigned: UINT, + ConfigResidDiffAccelerator: UINT, + ConfigHostInverseScan: UINT, + ConfigSpecificIDCT: UINT, + Config4GroupedCoefs: UINT, + ConfigMinRenderTargetBuffCount: USHORT, + ConfigDecoderSpecific: USHORT, +}} +ENUM!{enum D3D11_VIDEO_DECODER_BUFFER_TYPE { + D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS = 0, + D3D11_VIDEO_DECODER_BUFFER_MACROBLOCK_CONTROL = 1, + D3D11_VIDEO_DECODER_BUFFER_RESIDUAL_DIFFERENCE = 2, + D3D11_VIDEO_DECODER_BUFFER_DEBLOCKING_CONTROL = 3, + D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX = 4, + D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL = 5, + D3D11_VIDEO_DECODER_BUFFER_BITSTREAM = 6, + D3D11_VIDEO_DECODER_BUFFER_MOTION_VECTOR = 7, + D3D11_VIDEO_DECODER_BUFFER_FILM_GRAIN = 8, +}} +STRUCT!{struct D3D11_AES_CTR_IV { + IV: UINT64, + Count: UINT64, +}} +STRUCT!{struct D3D11_ENCRYPTED_BLOCK_INFO { + NumEncryptedBytesAtBeginning: UINT, + NumBytesInSkipPattern: UINT, + NumBytesInEncryptPattern: UINT, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_BUFFER_DESC { + BufferType: D3D11_VIDEO_DECODER_BUFFER_TYPE, + BufferIndex: UINT, + DataOffset: UINT, + DataSize: UINT, + FirstMBaddress: UINT, + NumMBsInBuffer: UINT, + Width: UINT, + Height: UINT, + Stride: UINT, + ReservedBits: UINT, + pIV: *mut c_void, + IVSize: UINT, + PartialEncryption: BOOL, + EncryptedBlockInfo: D3D11_ENCRYPTED_BLOCK_INFO, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_EXTENSION { + Function: UINT, + pPrivateInputData: *mut c_void, + PrivateInputDataSize: UINT, + pPrivateOutputData: *mut c_void, + PrivateOutputDataSize: UINT, + ResourceCount: UINT, + ppResourceList: *mut *mut ID3D11Resource, +}} +RIDL!{interface ID3D11VideoDecoder(ID3D11VideoDecoderVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetCreationParameters( + &mut self, pVideoDesc: *mut D3D11_VIDEO_DECODER_DESC, + pConfig: *mut D3D11_VIDEO_DECODER_CONFIG + ) -> HRESULT, + fn GetDriverHandle(&mut self, pDriverHandle: *mut HANDLE) -> HRESULT +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT { + D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_INPUT = 0x1, + D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_OUTPUT = 0x2, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_DEVICE_CAPS { + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_LINEAR_SPACE = 0x1, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_xvYCC = 0x2, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_RGB_RANGE_CONVERSION = 0x4, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_YCbCr_MATRIX_CONVERSION = 0x8, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_NOMINAL_RANGE = 0x10, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FEATURE_CAPS { + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ALPHA_FILL = 0x1, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_CONSTRICTION = 0x2, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_LUMA_KEY = 0x4, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ALPHA_PALETTE = 0x8, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_LEGACY = 0x10, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_STEREO = 0x20, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ROTATION = 0x40, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ALPHA_STREAM = 0x80, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_PIXEL_ASPECT_RATIO = 0x100, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_MIRROR = 0x200, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_SHADER_USAGE = 0x400, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FILTER_CAPS { + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_BRIGHTNESS = 0x1, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_CONTRAST = 0x2, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_HUE = 0x4, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_SATURATION = 0x8, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_NOISE_REDUCTION = 0x10, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_EDGE_ENHANCEMENT = 0x20, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_ANAMORPHIC_SCALING = 0x40, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_STEREO_ADJUSTMENT = 0x80, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FORMAT_CAPS { + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_RGB_INTERLACED = 0x1, + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_RGB_PROCAMP = 0x2, + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_RGB_LUMA_KEY = 0x4, + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_PALETTE_INTERLACED = 0x8, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS { + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_DENOISE = 0x1, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_DERINGING = 0x2, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_EDGE_ENHANCEMENT = 0x4, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_COLOR_CORRECTION = 0x8, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_FLESH_TONE_MAPPING = 0x10, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_IMAGE_STABILIZATION = 0x20, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_SUPER_RESOLUTION = 0x40, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_ANAMORPHIC_SCALING = 0x80, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_STEREO_CAPS { + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_MONO_OFFSET = 0x1, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_ROW_INTERLEAVED = 0x2, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_COLUMN_INTERLEAVED = 0x4, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_CHECKERBOARD = 0x8, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_FLIP_MODE = 0x10, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_CAPS { + DeviceCaps: UINT, + FeatureCaps: UINT, + FilterCaps: UINT, + InputFormatCaps: UINT, + AutoStreamCaps: UINT, + StereoCaps: UINT, + RateConversionCapsCount: UINT, + MaxInputStreams: UINT, + MaxStreamStates: UINT, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS { + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_BLEND = 0x1, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_BOB = 0x2, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_ADAPTIVE = 0x4, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_MOTION_COMPENSATION = 0x8, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_INVERSE_TELECINE = 0x10, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_FRAME_RATE_CONVERSION = 0x20, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS { + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_32 = 0x1, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_22 = 0x2, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_2224 = 0x4, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_2332 = 0x8, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_32322 = 0x10, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_55 = 0x20, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_64 = 0x40, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_87 = 0x80, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_222222222223 = 0x100, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_OTHER = 0x80000000, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS { + PastFrames: UINT, + FutureFrames: UINT, + ProcessorCaps: UINT, + ITelecineCaps: UINT, + CustomRateCount: UINT, +}} +FLAGS!{enum D3D11_CONTENT_PROTECTION_CAPS { + D3D11_CONTENT_PROTECTION_CAPS_SOFTWARE = 0x1, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE = 0x2, + D3D11_CONTENT_PROTECTION_CAPS_PROTECTION_ALWAYS_ON = 0x4, + D3D11_CONTENT_PROTECTION_CAPS_PARTIAL_DECRYPTION = 0x8, + D3D11_CONTENT_PROTECTION_CAPS_CONTENT_KEY = 0x10, + D3D11_CONTENT_PROTECTION_CAPS_FRESHEN_SESSION_KEY = 0x20, + D3D11_CONTENT_PROTECTION_CAPS_ENCRYPTED_READ_BACK = 0x40, + D3D11_CONTENT_PROTECTION_CAPS_ENCRYPTED_READ_BACK_KEY = 0x80, + D3D11_CONTENT_PROTECTION_CAPS_SEQUENTIAL_CTR_IV = 0x100, + D3D11_CONTENT_PROTECTION_CAPS_ENCRYPT_SLICEDATA_ONLY = 0x200, + D3D11_CONTENT_PROTECTION_CAPS_DECRYPTION_BLT = 0x400, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_PROTECT_UNCOMPRESSED = 0x800, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_PROTECTED_MEMORY_PAGEABLE = 0x1000, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_TEARDOWN = 0x2000, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_DRM_COMMUNICATION = 0x4000, +}} +STRUCT!{struct D3D11_VIDEO_CONTENT_PROTECTION_CAPS { + Caps: UINT, + KeyExchangeTypeCount: UINT, + BlockAlignmentSize: UINT, + ProtectedMemorySize: ULONGLONG, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_CUSTOM_RATE { + CustomRate: DXGI_RATIONAL, + OutputFrames: UINT, + InputInterlaced: BOOL, + InputFramesOrFields: UINT, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_FILTER { + D3D11_VIDEO_PROCESSOR_FILTER_BRIGHTNESS = 0, + D3D11_VIDEO_PROCESSOR_FILTER_CONTRAST = 1, + D3D11_VIDEO_PROCESSOR_FILTER_HUE = 2, + D3D11_VIDEO_PROCESSOR_FILTER_SATURATION = 3, + D3D11_VIDEO_PROCESSOR_FILTER_NOISE_REDUCTION = 4, + D3D11_VIDEO_PROCESSOR_FILTER_EDGE_ENHANCEMENT = 5, + D3D11_VIDEO_PROCESSOR_FILTER_ANAMORPHIC_SCALING = 6, + D3D11_VIDEO_PROCESSOR_FILTER_STEREO_ADJUSTMENT = 7, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_FILTER_RANGE { + Minimum: c_int, + Maximum: c_int, + Default: c_int, + Multiplier: c_float, +}} +ENUM!{enum D3D11_VIDEO_FRAME_FORMAT { + D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE = 0, + D3D11_VIDEO_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST = 1, + D3D11_VIDEO_FRAME_FORMAT_INTERLACED_BOTTOM_FIELD_FIRST = 2, +}} +ENUM!{enum D3D11_VIDEO_USAGE { + D3D11_VIDEO_USAGE_PLAYBACK_NORMAL = 0, + D3D11_VIDEO_USAGE_OPTIMAL_SPEED = 1, + D3D11_VIDEO_USAGE_OPTIMAL_QUALITY = 2, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_CONTENT_DESC { + InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT, + InputFrameRate: DXGI_RATIONAL, + InputWidth: UINT, + InputHeight: UINT, + OutputFrameRate: DXGI_RATIONAL, + OutputWidth: UINT, + OutputHeight: UINT, + Usage: D3D11_VIDEO_USAGE, +}} +RIDL!{interface ID3D11VideoProcessorEnumerator(ID3D11VideoProcessorEnumeratorVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetVideoProcessorContentDesc( + &mut self, pContentDesc: *mut D3D11_VIDEO_PROCESSOR_CONTENT_DESC + ) -> HRESULT, + fn CheckVideoProcessorFormat(&mut self, Format: DXGI_FORMAT, pFlags: *mut UINT) -> HRESULT, + fn GetVideoProcessorCaps(&mut self, pCaps: *mut D3D11_VIDEO_PROCESSOR_CAPS) -> HRESULT, + fn GetVideoProcessorRateConversionCaps( + &mut self, TypeIndex: UINT, pCaps: *mut D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS + ) -> HRESULT, + fn GetVideoProcessorCustomRate( + &mut self, TypeIndex: UINT, CustomRateIndex: UINT, + pRate: *mut D3D11_VIDEO_PROCESSOR_CUSTOM_RATE + ) -> HRESULT, + fn GetVideoProcessorFilterRange( + &mut self, Filter: D3D11_VIDEO_PROCESSOR_FILTER, + Range: *mut D3D11_VIDEO_PROCESSOR_FILTER_RANGE + ) -> HRESULT +}} +STRUCT!{struct D3D11_VIDEO_COLOR_RGBA { + R: c_float, + G: c_float, + B: c_float, + A: c_float, +}} +STRUCT!{struct D3D11_VIDEO_COLOR_YCbCrA { + Y: c_float, + Cb: c_float, + Cr: c_float, + A: c_float, +}} +STRUCT!{struct D3D11_VIDEO_COLOR { + u: [c_float; 4], +}} +UNION!{D3D11_VIDEO_COLOR, u, YCbCr, YCbCr_mut, D3D11_VIDEO_COLOR_YCbCrA} +UNION!{D3D11_VIDEO_COLOR, u, RGBA, RGBA_mut, D3D11_VIDEO_COLOR_RGBA} +ENUM!{enum D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE { + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_UNDEFINED = 0, + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_16_235 = 1, + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_0_255 = 2, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_COLOR_SPACE { + bitfield: UINT, +}} +BITFIELD!{D3D11_VIDEO_PROCESSOR_COLOR_SPACE bitfield: UINT [ + Usage set_Usage[0..1], + RGB_Range set_RGB_Range[1..2], + YCbCr_Matrix set_YCbCr_Matrix[2..3], + YCbCr_xvYCC set_YCbCr_xvYCC[3..4], + Nominal_Range set_Nominal_Range[4..6], +]} +ENUM!{enum D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE { + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_OPAQUE = 0, + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_BACKGROUND = 1, + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_DESTINATION = 2, + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_SOURCE_STREAM = 3, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_OUTPUT_RATE { + D3D11_VIDEO_PROCESSOR_OUTPUT_RATE_NORMAL = 0, + D3D11_VIDEO_PROCESSOR_OUTPUT_RATE_HALF = 1, + D3D11_VIDEO_PROCESSOR_OUTPUT_RATE_CUSTOM = 2, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_STEREO_FORMAT { + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_MONO = 0, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_HORIZONTAL = 1, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_VERTICAL = 2, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_SEPARATE = 3, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_MONO_OFFSET = 4, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_ROW_INTERLEAVED = 5, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_COLUMN_INTERLEAVED = 6, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_CHECKERBOARD = 7, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_STEREO_FLIP_MODE { + D3D11_VIDEO_PROCESSOR_STEREO_FLIP_NONE = 0, + D3D11_VIDEO_PROCESSOR_STEREO_FLIP_FRAME0 = 1, + D3D11_VIDEO_PROCESSOR_STEREO_FLIP_FRAME1 = 2, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_ROTATION { + D3D11_VIDEO_PROCESSOR_ROTATION_IDENTITY = 0, + D3D11_VIDEO_PROCESSOR_ROTATION_90 = 1, + D3D11_VIDEO_PROCESSOR_ROTATION_180 = 2, + D3D11_VIDEO_PROCESSOR_ROTATION_270 = 3, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_STREAM { + Enable: BOOL, + OutputIndex: UINT, + InputFrameOrField: UINT, + PastFrames: UINT, + FutureFrames: UINT, + ppPastSurfaces: *mut *mut ID3D11VideoProcessorInputView, + pInputSurface: *mut ID3D11VideoProcessorInputView, + ppFutureSurfaces: *mut *mut ID3D11VideoProcessorInputView, + ppPastSurfacesRight: *mut *mut ID3D11VideoProcessorInputView, + pInputSurfaceRight: *mut ID3D11VideoProcessorInputView, + ppFutureSurfacesRight: *mut *mut ID3D11VideoProcessorInputView, +}} +RIDL!{interface ID3D11VideoProcessor(ID3D11VideoProcessorVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetContentDesc(&mut self, pDesc: *mut D3D11_VIDEO_PROCESSOR_CONTENT_DESC) -> (), + fn GetRateConversionCaps( + &mut self, pCaps: *mut D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS + ) -> () +}} +STRUCT!{struct D3D11_OMAC { + Omac: [BYTE; 16], +}} +ENUM!{enum D3D11_AUTHENTICATED_CHANNEL_TYPE { + D3D11_AUTHENTICATED_CHANNEL_D3D11 = 1, + D3D11_AUTHENTICATED_CHANNEL_DRIVER_SOFTWARE = 2, + D3D11_AUTHENTICATED_CHANNEL_DRIVER_HARDWARE = 3, +}} +RIDL!{interface ID3D11AuthenticatedChannel(ID3D11AuthenticatedChannelVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetCertificateSize(&mut self, pCertificateSize: *mut UINT) -> HRESULT, + fn GetCertificate(&mut self, CertificateSize: UINT, pCertificate: *mut BYTE) -> HRESULT, + fn GetChannelHandle(&mut self, pChannelHandle: *mut HANDLE) -> () +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_INPUT { + QueryType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT { + omac: D3D11_OMAC, + QueryType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, + ReturnCode: HRESULT, +}} +//FIXME bitfield +STRUCT!{struct D3D11_AUTHENTICATED_PROTECTION_FLAGS { + u: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_PROTECTION_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + ProtectionFlags: D3D11_AUTHENTICATED_PROTECTION_FLAGS, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CHANNEL_TYPE_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + ChannelType: D3D11_AUTHENTICATED_CHANNEL_TYPE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_DEVICE_HANDLE_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DeviceHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CRYPTO_SESSION_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + DecoderHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CRYPTO_SESSION_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DecoderHandle: HANDLE, + CryptoSessionHandle: HANDLE, + DeviceHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_RESTRICTED_SHARED_RESOURCE_PROCESS_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + RestrictedSharedResourceProcessCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_RESTRICTED_SHARED_RESOURCE_PROCESS_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + ProcessIndex: UINT, +}} +ENUM!{enum D3D11_AUTHENTICATED_PROCESS_IDENTIFIER_TYPE { + DD3D11_PROCESSIDTYPE_UNKNOWN = 0, + DD3D11_PROCESSIDTYPE_DWM = 1, + DD3D11_PROCESSIDTYPE_HANDLE = 2, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_RESTRICTED_SHARED_RESOURCE_PROCESS_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + ProcessIndex: UINT, + ProcessIdentifier: D3D11_AUTHENTICATED_PROCESS_IDENTIFIER_TYPE, + ProcessHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_UNRESTRICTED_PROTECTED_SHARED_RESOURCE_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + UnrestrictedProtectedSharedResourceCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_COUNT_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, + OutputIDCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, + OutputIDIndex: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, + OutputIDIndex: UINT, + OutputID: UINT64, +}} +ENUM!{enum D3D11_BUS_TYPE { + D3D11_BUS_TYPE_OTHER = 0, + D3D11_BUS_TYPE_PCI = 0x1, + D3D11_BUS_TYPE_PCIX = 0x2, + D3D11_BUS_TYPE_PCIEXPRESS = 0x3, + D3D11_BUS_TYPE_AGP = 0x4, + D3D11_BUS_IMPL_MODIFIER_INSIDE_OF_CHIPSET = 0x10000, + D3D11_BUS_IMPL_MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_CHIP = 0x20000, + D3D11_BUS_IMPL_MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_SOCKET = 0x30000, + D3D11_BUS_IMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR = 0x40000, + D3D11_BUS_IMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR_INSIDE_OF_NUAE = 0x50000, + D3D11_BUS_IMPL_MODIFIER_NON_STANDARD = 0x80000000, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACESSIBILITY_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + BusType: D3D11_BUS_TYPE, + AccessibleInContiguousBlocks: BOOL, + AccessibleInNonContiguousBlocks: BOOL, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + EncryptionGuidCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + EncryptionGuidIndex: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + EncryptionGuidIndex: UINT, + EncryptionGuid: GUID, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CURRENT_ACCESSIBILITY_ENCRYPTION_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + EncryptionGuid: GUID, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_INPUT { + omac: D3D11_OMAC, + ConfigureType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_OUTPUT { + omac: D3D11_OMAC, + ConfigureType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, + ReturnCode: HRESULT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_INITIALIZE_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + StartSequenceQuery: UINT, + StartSequenceConfigure: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_PROTECTION_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + Protections: D3D11_AUTHENTICATED_PROTECTION_FLAGS, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_CRYPTO_SESSION_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + DecoderHandle: HANDLE, + CryptoSessionHandle: HANDLE, + DeviceHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_SHARED_RESOURCE_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + ProcessType: D3D11_AUTHENTICATED_PROCESS_IDENTIFIER_TYPE, + ProcessHandle: HANDLE, + AllowAccess: BOOL, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_ACCESSIBLE_ENCRYPTION_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + EncryptionGuid: GUID, +}} +RIDL!{interface ID3D11CryptoSession(ID3D11CryptoSessionVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetCryptoType(&mut self, pCryptoType: *mut GUID) -> (), + fn GetDecoderProfile(&mut self, pDecoderProfile: *mut GUID) -> (), + fn GetCertificateSize(&mut self, pCertificateSize: *mut UINT) -> HRESULT, + fn GetCertificate(&mut self, CertificateSize: UINT, pCertificate: *mut BYTE) -> HRESULT, + fn GetCryptoSessionHandle(&mut self, pCertificate: *mut HANDLE) -> () +}} +ENUM!{enum D3D11_VDOV_DIMENSION { + D3D11_VDOV_DIMENSION_UNKNOWN = 0, + D3D11_VDOV_DIMENSION_TEXTURE2D = 1, +}} +STRUCT!{struct D3D11_TEX2D_VDOV { + ArraySlice: UINT, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC { + DecodeProfile: GUID, + ViewDimension: D3D11_VDOV_DIMENSION, + Texture2D: D3D11_TEX2D_VDOV, +}} +RIDL!{interface ID3D11VideoDecoderOutputView(ID3D11VideoDecoderOutputViewVtbl) + : ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC) -> () +}} +ENUM!{enum D3D11_VPIV_DIMENSION { + D3D11_VPIV_DIMENSION_UNKNOWN = 0, + D3D11_VPIV_DIMENSION_TEXTURE2D = 1, +}} +STRUCT!{struct D3D11_TEX2D_VPIV { + MipSlice: UINT, + ArraySlice: UINT, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC { + FourCC: UINT, + ViewDimension: D3D11_VPIV_DIMENSION, + Texture2D: D3D11_TEX2D_VPIV, +}} +RIDL!{interface ID3D11VideoProcessorInputView(ID3D11VideoProcessorInputViewVtbl) + : ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC) -> () +}} +ENUM!{enum D3D11_VPOV_DIMENSION { + D3D11_VPOV_DIMENSION_UNKNOWN = 0, + D3D11_VPOV_DIMENSION_TEXTURE2D = 1, + D3D11_VPOV_DIMENSION_TEXTURE2DARRAY = 2, +}} +STRUCT!{struct D3D11_TEX2D_VPOV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_VPOV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { + ViewDimension: D3D11_VPOV_DIMENSION, + u: [UINT; 3], +}} +UNION!{D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_VPOV} +UNION!{D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_VPOV} +RIDL!{interface ID3D11VideoProcessorOutputView(ID3D11VideoProcessorOutputViewVtbl) + : ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC) -> () +}} +RIDL!{interface ID3D11VideoContext(ID3D11VideoContextVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDecoderBuffer( + &mut self, pDecoder: *mut ID3D11VideoDecoder, Type: D3D11_VIDEO_DECODER_BUFFER_TYPE, + pBufferSize: *mut UINT, ppBuffer: *mut *mut c_void + ) -> HRESULT, + fn ReleaseDecoderBuffer( + &mut self, pDecoder: *mut ID3D11VideoDecoder, Type: D3D11_VIDEO_DECODER_BUFFER_TYPE + ) -> HRESULT, + fn DecoderBeginFrame( + &mut self, pDecoder: *mut ID3D11VideoDecoder, pView: *mut ID3D11VideoDecoderOutputView, + ContentKeySize: UINT, pContentKey: *const c_void + ) -> HRESULT, + fn DecoderEndFrame(&mut self, pDecoder: *mut ID3D11VideoDecoder) -> HRESULT, + fn SubmitDecoderBuffers( + &mut self, pDecoder: *mut ID3D11VideoDecoder, NumBuffers: UINT, + pBufferDesc: *const D3D11_VIDEO_DECODER_BUFFER_DESC + ) -> HRESULT, + fn DecoderExtension( + &mut self, pDecoder: *mut ID3D11VideoDecoder, + pExtensionData: *const D3D11_VIDEO_DECODER_EXTENSION + ) -> HRESULT, + fn VideoProcessorSetOutputTargetRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enable: BOOL, pRect: *const RECT + ) -> (), + fn VideoProcessorSetOutputBackgroundColor( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, YCbCr: BOOL, pRect: *const RECT + ) -> (), + fn VideoProcessorSetOutputColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pColorSpace: *const D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> HRESULT, + fn VideoProcessorSetOutputAlphaFillMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + AlphaFillMode: D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE, StreamIndex: UINT + ) -> (), + fn VideoProcessorSetOutputConstriction( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enable: BOOL, Size: SIZE + ) -> (), + fn VideoProcessorSetOutputStereoMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enable: BOOL + ) -> (), + fn VideoProcessorSetOutputExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pExtensionGuid: *const GUID, + DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorGetOutputTargetRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enabled: *mut BOOL, pRect: *mut RECT + ) -> (), + fn VideoProcessorGetOutputBackgroundColor( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pYCbCr: *mut BOOL, + pColor: *mut D3D11_VIDEO_COLOR + ) -> (), + fn VideoProcessorGetOutputColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pColorSpace: *mut D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> (), + fn VideoProcessorGetOutputAlphaFillMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pAlphaFillMode: *mut D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE, pStreamIndex: *mut UINT + ) -> (), + fn VideoProcessorGetOutputConstriction( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pEnabled: *mut BOOL, + pSize: *mut SIZE + ) -> (), + fn VideoProcessorGetOutputStereoMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pEnabled: *mut BOOL + ) -> (), + fn VideoProcessorGetOutputExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pExtensionGuid: *const GUID, + DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorSetStreamFrameFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + FrameFormat: D3D11_VIDEO_FRAME_FORMAT + ) -> (), + fn VideoProcessorSetStreamColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pColorSpace: *const D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> (), + fn VideoProcessorSetStreamOutputRate( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + OutputRate: D3D11_VIDEO_PROCESSOR_OUTPUT_RATE, RepeatFrame: BOOL, + pCustomRate: *const DXGI_RATIONAL + ) -> (), + fn VideoProcessorSetStreamSourceRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + pRect: *const RECT + ) -> (), + fn VideoProcessorSetStreamDestRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + pRect: *const RECT + ) -> (), + fn VideoProcessorSetStreamAlpha( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Alpha: FLOAT + ) -> (), + fn VideoProcessorSetStreamPalette( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Count: UINT, + pEntries: *const UINT + ) -> (), + fn VideoProcessorSetStreamPixelAspectRatio( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + pSourceAspectRatio: *const DXGI_RATIONAL, pDestinationAspectRatio: *const DXGI_RATIONAL + ) -> (), + fn VideoProcessorSetStreamLumaKey( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Lower: FLOAT, Upper: FLOAT + ) -> (), + fn VideoProcessorSetStreamStereoFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Format: D3D11_VIDEO_PROCESSOR_STEREO_FORMAT, LeftViewFrame0: BOOL, BaseViewFrame0: BOOL, + FlipMode: D3D11_VIDEO_PROCESSOR_STEREO_FLIP_MODE + ) -> (), + fn VideoProcessorSetStreamAutoProcessingMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL + ) -> (), + fn VideoProcessorSetStreamFilter( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + Filter: D3D11_VIDEO_PROCESSOR_FILTER, Enable: BOOL, Level: c_int + ) -> (), + fn VideoProcessorSetStreamExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pExtensionGuid: *const GUID, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorGetStreamFrameFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pFrameFormat: *mut D3D11_VIDEO_FRAME_FORMAT + ) -> (), + fn VideoProcessorGetStreamColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pColorSpace: *mut D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> (), + fn VideoProcessorGetStreamOutputRate( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pOutputRate: *mut D3D11_VIDEO_PROCESSOR_OUTPUT_RATE, pRepeatFrame: *mut BOOL, + pCustomRate: *mut DXGI_RATIONAL + ) -> (), + fn VideoProcessorGetStreamSourceRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pRect: *mut RECT + ) -> (), + fn VideoProcessorGetStreamDestRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pRect: *mut RECT + ) -> (), + fn VideoProcessorGetStreamAlpha( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pAlpha: *mut FLOAT + ) -> (), + fn VideoProcessorGetStreamPalette( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Count: UINT, + pEntries: *mut UINT + ) -> (), + fn VideoProcessorGetStreamPixelAspectRatio( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pSourceAspectRatio: *mut DXGI_RATIONAL, + pDestinationAspectRatio: *mut DXGI_RATIONAL + ) -> (), + fn VideoProcessorGetStreamLumaKey( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pLower: *mut FLOAT, pUpper: *mut FLOAT + ) -> (), + fn VideoProcessorGetStreamStereoFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pFormat: *mut D3D11_VIDEO_PROCESSOR_STEREO_FORMAT, + pLeftViewFrame0: *mut BOOL, pBaseViewFrame0: *mut BOOL, + pFlipMode: *mut D3D11_VIDEO_PROCESSOR_STEREO_FLIP_MODE, MonoOffset: *mut c_int + ) -> (), + fn VideoProcessorGetStreamAutoProcessingMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL + ) -> (), + fn VideoProcessorGetStreamFilter( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + Filter: D3D11_VIDEO_PROCESSOR_FILTER, pEnabled: *mut BOOL, pLevel: *mut c_int + ) -> (), + fn VideoProcessorGetStreamExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pExtensionGuid: *const GUID, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorBlt( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pView: *mut ID3D11VideoProcessorOutputView, OutputFrame: UINT, StreamCount: UINT, + pStreams: *const D3D11_VIDEO_PROCESSOR_STREAM + ) -> HRESULT, + fn NegotiateCryptoSessionKeyExchange( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn EncryptionBlt( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, pSrcSurface: *mut ID3D11Texture2D, + pDstSurface: *mut ID3D11Texture2D, IVSize: UINT, pIV: *mut c_void + ) -> HRESULT, + fn DecryptionBlt( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, pSrcSurface: *mut ID3D11Texture2D, + pDstSurface: *mut ID3D11Texture2D, pEncryptedBlockInfo: *mut D3D11_ENCRYPTED_BLOCK_INFO, + ContentKeySize: UINT, pContentKey: *const c_void, IVSize: UINT, pIV: *mut c_void + ) -> HRESULT, + fn StartSessionKeyRefresh( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, RandomNumberSize: UINT, + pRandomNumber: *mut c_void + ) -> HRESULT, + fn FinishSessionKeyRefresh(&mut self, pCryptoSession: *mut ID3D11CryptoSession) -> HRESULT, + fn GetEncryptionBltKey( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, KeySize: UINT, + pReadbackKey: *mut c_void + ) -> HRESULT, + fn NegotiateAuthenticatedChannelKeyExchange( + &mut self, pChannel: *mut ID3D11AuthenticatedChannel, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn QueryAuthenticatedChannel( + &mut self, pChannel: *mut ID3D11AuthenticatedChannel, InputSize: UINT, + pInput: *const c_void, OutputSize: UINT, pOutput: *mut c_void + ) -> HRESULT, + fn ConfigureAuthenticatedChannel( + &mut self, pChannel: *mut ID3D11AuthenticatedChannel, InputSize: UINT, + pInput: *const c_void, pOutput: *mut D3D11_AUTHENTICATED_CONFIGURE_OUTPUT + ) -> HRESULT, + fn VideoProcessorSetStreamRotation( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Rotation: D3D11_VIDEO_PROCESSOR_ROTATION + ) -> HRESULT, + fn VideoProcessorGetStreamRotation( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnable: *mut BOOL, pRotation: *mut D3D11_VIDEO_PROCESSOR_ROTATION + ) -> HRESULT +}} +RIDL!{interface ID3D11VideoDevice(ID3D11VideoDeviceVtbl): IUnknown(IUnknownVtbl) { + fn CreateVideoDecoder( + &mut self, pVideoDesc: *const D3D11_VIDEO_DECODER_DESC, + pConfig: *const D3D11_VIDEO_DECODER_CONFIG, ppDecoder: *mut *mut ID3D11VideoDecoder + ) -> HRESULT, + fn CreateVideoProcessor( + &mut self, pEnum: *mut ID3D11VideoProcessorEnumerator, RateConversionIndex: UINT, + ppVideoProcessor: *mut *mut ID3D11VideoProcessor + ) -> HRESULT, + fn CreateAuthenticatedChannel( + &mut self, ChannelType: D3D11_AUTHENTICATED_CHANNEL_TYPE, + ppAuthenticatedChannel: *mut *mut ID3D11AuthenticatedChannel + ) -> HRESULT, + fn CreateCryptoSession( + &mut self, pCryptoType: *const GUID, pDecoderProfile: *const GUID, + pKeyExchangeType: *const GUID, ppCryptoSession: *mut *mut ID3D11CryptoSession + ) -> HRESULT, + fn CreateVideoDecoderOutputView( + &mut self, pResource: *mut ID3D11Resource, + pDesc: *const D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC, + ppVDOVView: *mut *mut ID3D11VideoDecoderOutputView + ) -> HRESULT, + fn CreateVideoProcessorInputView( + &mut self, pResource: *mut ID3D11Resource, pEnum: *mut ID3D11VideoProcessorEnumerator, + pDesc: *const D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, + ppVPIView: *mut *mut ID3D11VideoProcessorInputView + ) -> HRESULT, + fn CreateVideoProcessorOutputView( + &mut self, pResource: *mut ID3D11Resource, pEnum: *mut ID3D11VideoProcessorEnumerator, + pDesc: *const D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, + ppVPOView: *mut *mut ID3D11VideoProcessorOutputView + ) -> HRESULT, + fn CreateVideoProcessorEnumerator( + &mut self, pDesc: *const D3D11_VIDEO_PROCESSOR_CONTENT_DESC, + ppEnum: *mut *mut ID3D11VideoProcessorEnumerator + ) -> HRESULT, + fn GetVideoDecoderProfileCount(&mut self) -> UINT, + fn GetVideoDecoderProfile(&mut self, Index: UINT, pDecoderProfile: *mut GUID) -> HRESULT, + fn CheckVideoDecoderFormat( + &mut self, pDecoderProfile: *const GUID, Format: DXGI_FORMAT, pSupported: *mut BOOL + ) -> HRESULT, + fn GetVideoDecoderConfigCount( + &mut self, pDesc: *const D3D11_VIDEO_DECODER_DESC, pCount: *mut UINT + ) -> HRESULT, + fn GetVideoDecoderConfig( + &mut self, pDesc: *const D3D11_VIDEO_DECODER_DESC, Index: UINT, + pConfig: *mut D3D11_VIDEO_DECODER_CONFIG + ) -> HRESULT, + fn GetContentProtectionCaps( + &mut self, pCryptoType: *const GUID, pDecoderProfile: *const GUID, + pCaps: *mut D3D11_VIDEO_CONTENT_PROTECTION_CAPS + ) -> HRESULT, + fn CheckCryptoKeyExchange( + &mut self, pCryptoType: *const GUID, pDecoderProfile: *const GUID, Index: UINT, + pKeyExchangeType: *mut GUID + ) -> HRESULT, + fn SetPrivateData( &mut self, guid: REFGUID, DataSize: UINT, pData: *const c_void) -> HRESULT, + fn SetPrivateDataInterface(&mut self, guid: REFGUID, pData: *const IUnknown) -> HRESULT +}} +RIDL!{interface ID3D11Device(ID3D11DeviceVtbl): IUnknown(IUnknownVtbl) { + fn CreateBuffer( + &mut self, pDesc: *const D3D11_BUFFER_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppBuffer: *mut *mut ID3D11Buffer + ) -> HRESULT, + fn CreateTexture1D( + &mut self, pDesc: *const D3D11_TEXTURE1D_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppTexture1D: *mut *mut ID3D11Texture1D + ) -> HRESULT, + fn CreateTexture2D( + &mut self, pDesc: *const D3D11_TEXTURE2D_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppTexture2D: *mut *mut ID3D11Texture2D + ) -> HRESULT, + fn CreateTexture3D( + &mut self, pDesc: *const D3D11_TEXTURE3D_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppTexture3D: *mut *mut ID3D11Texture3D + ) -> HRESULT, + fn CreateShaderResourceView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_SHADER_RESOURCE_VIEW_DESC, + ppSRView: *mut *mut ID3D11ShaderResourceView + ) -> HRESULT, + fn CreateUnorderedAccessView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_UNORDERED_ACCESS_VIEW_DESC, + ppUAView: *mut *mut ID3D11UnorderedAccessView + ) -> HRESULT, + fn CreateRenderTargetView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_RENDER_TARGET_VIEW_DESC, + ppRTView: *mut *mut ID3D11RenderTargetView + ) -> HRESULT, + fn CreateDepthStencilView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_DEPTH_STENCIL_VIEW_DESC, + ppDepthStencilView: *mut *mut ID3D11DepthStencilView + ) -> HRESULT, + fn CreateInputLayout( + &mut self, pInputElementDescs: *const D3D11_INPUT_ELEMENT_DESC, NumElements: UINT, + pShaderBytecodeWithInputSignature: *const c_void, BytecodeLength: SIZE_T, + ppInputLayout: *mut *mut ID3D11InputLayout + ) -> HRESULT, + fn CreateVertexShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppVertexShader: *mut *mut ID3D11VertexShader + ) -> HRESULT, + fn CreateGeometryShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppGeometryShader: *mut *mut ID3D11GeometryShader + ) -> HRESULT, + fn CreateGeometryShaderWithStreamOutput( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pSODeclaration: *const D3D11_SO_DECLARATION_ENTRY, NumEntries: UINT, + pBufferStrides: *const UINT, NumStrides: UINT, RasterizedStream: UINT, + pClassLinkage: *mut ID3D11ClassLinkage, ppGeometryShader: *mut *mut ID3D11GeometryShader + ) -> HRESULT, + fn CreatePixelShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppPixelShader: *mut *mut ID3D11PixelShader + ) -> HRESULT, + fn CreateHullShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppHullShader: *mut *mut ID3D11HullShader + ) -> HRESULT, + fn CreateDomainShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppDomainShader: *mut *mut ID3D11DomainShader + ) -> HRESULT, + fn CreateComputeShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppComputeShader: *mut *mut ID3D11ComputeShader + ) -> HRESULT, + fn CreateClassLinkage(&mut self, ppLinkage: *mut *mut ID3D11ClassLinkage) -> HRESULT, + fn CreateBlendState( + &mut self, pBlendStateDesc: *const D3D11_BLEND_DESC, + ppBlendState: *mut *mut ID3D11BlendState + ) -> HRESULT, + fn CreateDepthStencilState( + &mut self, pDepthStencilDesc: *const D3D11_DEPTH_STENCIL_DESC, + ppDepthStencilState: *mut *mut ID3D11DepthStencilState + ) -> HRESULT, + fn CreateRasterizerState( + &mut self, pRasterizerDesc: *const D3D11_RASTERIZER_DESC, + ppRasterizerState: *mut *mut ID3D11RasterizerState + ) -> HRESULT, + fn CreateSamplerState( + &mut self, pSamplerDesc: *const D3D11_SAMPLER_DESC, + ppSamplerState: *mut *mut ID3D11SamplerState + ) -> HRESULT, + fn CreateQuery( + &mut self, pQueryDesc: *const D3D11_QUERY_DESC, ppQuery: *mut *mut ID3D11Query + ) -> HRESULT, + fn CreatePredicate( + &mut self, pPredicateDesc: *const D3D11_QUERY_DESC, ppPredicate: *mut *mut ID3D11Predicate + ) -> HRESULT, + fn CreateCounter( + &mut self, pCounterDesc: *const D3D11_COUNTER_DESC, ppCounter: *mut *mut ID3D11Counter + ) -> HRESULT, + fn CreateDeferredContext( + &mut self, ContextFlags: UINT, ppDeferredContext: *mut *mut ID3D11DeviceContext + ) -> HRESULT, + fn OpenSharedResource( + &mut self, hResource: HANDLE, ReturnedInterface: REFIID, ppResource: *mut *mut c_void + ) -> HRESULT, + fn CheckFormatSupport( + &mut self, Format: DXGI_FORMAT, pFormatSupport: *mut UINT + ) -> HRESULT, + fn CheckMultisampleQualityLevels( + &mut self, Format: DXGI_FORMAT, SampleCount: UINT, pNumQualityLevels: *mut UINT + ) -> HRESULT, + fn CheckCounterInfo(&mut self, pCounterInfo: *mut D3D11_COUNTER_INFO) -> (), + fn CheckCounter( + &mut self, pDesc: *const D3D11_COUNTER_DESC, pType: *mut D3D11_COUNTER_TYPE, + pActiveCounters: *mut UINT, szName: LPSTR, pNameLength: *mut UINT, szUnits: LPSTR, + pUnitsLength: *mut UINT, szDescription: LPSTR, pDescriptionLength: *mut UINT + ) -> HRESULT, + fn CheckFeatureSupport( + &mut self, Feature: D3D11_FEATURE, pFeatureSupportData: *mut c_void, + FeatureSupportDataSize: UINT + ) -> HRESULT, + fn GetPrivateData( + &mut self, guid: REFGUID, pDataSize: *mut UINT, pData: *mut c_void + ) -> HRESULT, + fn SetPrivateData( + &mut self, guid: REFGUID, DataSize: UINT, pData: *const c_void + ) -> HRESULT, + fn SetPrivateDataInterface(&mut self, guid: REFGUID, pData: *const IUnknown) -> HRESULT, + fn GetFeatureLevel(&mut self) -> D3D_FEATURE_LEVEL, + fn GetCreationFlags(&mut self) -> UINT, + fn GetDeviceRemovedReason(&mut self) -> HRESULT, + fn GetImmediateContext(&mut self, ppImmediateContext: *mut *mut ID3D11DeviceContext) -> (), + fn SetExceptionMode(&mut self, RaiseFlags: UINT) -> HRESULT, + fn GetExceptionMode(&mut self) -> UINT +}} +FLAGS!{enum D3D11_CREATE_DEVICE_FLAG { + D3D11_CREATE_DEVICE_SINGLETHREADED = 0x1, + D3D11_CREATE_DEVICE_DEBUG = 0x2, + D3D11_CREATE_DEVICE_SWITCH_TO_REF = 0x4, + D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS = 0x8, + D3D11_CREATE_DEVICE_BGRA_SUPPORT = 0x20, + D3D11_CREATE_DEVICE_DEBUGGABLE = 0x40, + D3D11_CREATE_DEVICE_PREVENT_ALTERING_LAYER_SETTINGS_FROM_REGISTRY = 0x80, + D3D11_CREATE_DEVICE_DISABLE_GPU_TIMEOUT = 0x100, + D3D11_CREATE_DEVICE_VIDEO_SUPPORT = 0x800, +}} +pub const D3D11_SDK_VERSION: DWORD = 7; + +pub fn D3D11CalcSubresource(MipSlice: ::UINT, ArraySlice: ::UINT, MipLevels: ::UINT) -> ::UINT { + MipSlice + ArraySlice * MipLevels +} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d11shader.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d11shader.rs new file mode 100644 index 0000000..8328abe --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d11shader.rs @@ -0,0 +1,320 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +ENUM!{enum D3D11_SHADER_VERSION_TYPE { + D3D11_SHVER_PIXEL_SHADER = 0, + D3D11_SHVER_VERTEX_SHADER = 1, + D3D11_SHVER_GEOMETRY_SHADER = 2, + D3D11_SHVER_HULL_SHADER = 3, + D3D11_SHVER_DOMAIN_SHADER = 4, + D3D11_SHVER_COMPUTE_SHADER = 5, + D3D11_SHVER_RESERVED0 = 0xFFF0, +}} +pub const D3D_RETURN_PARAMETER_INDEX: c_int = -1; +pub type D3D11_RESOURCE_RETURN_TYPE = D3D_RESOURCE_RETURN_TYPE; +pub type D3D11_CBUFFER_TYPE = D3D_CBUFFER_TYPE; +STRUCT!{struct D3D11_SIGNATURE_PARAMETER_DESC { + SemanticName: LPCSTR, + SemanticIndex: UINT, + Register: UINT, + SystemValueType: D3D_NAME, + ComponentType: D3D_REGISTER_COMPONENT_TYPE, + Mask: BYTE, + ReadWriteMask: BYTE, + Stream: UINT, + MinPrecision: D3D_MIN_PRECISION, +}} +STRUCT!{struct D3D11_SHADER_BUFFER_DESC { + Name: LPCSTR, + Type: D3D_CBUFFER_TYPE, + Variables: UINT, + Size: UINT, + uFlags: UINT, +}} +STRUCT!{struct D3D11_SHADER_VARIABLE_DESC { + Name: LPCSTR, + StartOffset: UINT, + Size: UINT, + uFlags: UINT, + DefaultValue: LPVOID, + StartTexture: UINT, + TextureSize: UINT, + StartSampler: UINT, + SamplerSize: UINT, +}} +STRUCT!{struct D3D11_SHADER_TYPE_DESC { + Class: D3D_SHADER_VARIABLE_CLASS, + Type: D3D_SHADER_VARIABLE_TYPE, + Rows: UINT, + Columns: UINT, + Elements: UINT, + Members: UINT, + Offset: UINT, + Name: LPCSTR, +}} +pub type D3D11_TESSELLATOR_DOMAIN = D3D_TESSELLATOR_DOMAIN; +pub type D3D11_TESSELLATOR_PARTITIONING = D3D_TESSELLATOR_PARTITIONING; +pub type D3D11_TESSELLATOR_OUTPUT_PRIMITIVE = D3D_TESSELLATOR_OUTPUT_PRIMITIVE; +STRUCT!{struct D3D11_SHADER_DESC { + Version: UINT, + Creator: LPCSTR, + Flags: UINT, + ConstantBuffers: UINT, + BoundResources: UINT, + InputParameters: UINT, + OutputParameters: UINT, + InstructionCount: UINT, + TempRegisterCount: UINT, + TempArrayCount: UINT, + DefCount: UINT, + DclCount: UINT, + TextureNormalInstructions: UINT, + TextureLoadInstructions: UINT, + TextureCompInstructions: UINT, + TextureBiasInstructions: UINT, + TextureGradientInstructions: UINT, + FloatInstructionCount: UINT, + IntInstructionCount: UINT, + UintInstructionCount: UINT, + StaticFlowControlCount: UINT, + DynamicFlowControlCount: UINT, + MacroInstructionCount: UINT, + ArrayInstructionCount: UINT, + CutInstructionCount: UINT, + EmitInstructionCount: UINT, + GSOutputTopology: D3D_PRIMITIVE_TOPOLOGY, + GSMaxOutputVertexCount: UINT, + InputPrimitive: D3D_PRIMITIVE, + PatchConstantParameters: UINT, + cGSInstanceCount: UINT, + cControlPoints: UINT, + HSOutputPrimitive: D3D_TESSELLATOR_OUTPUT_PRIMITIVE, + HSPartitioning: D3D_TESSELLATOR_PARTITIONING, + TessellatorDomain: D3D_TESSELLATOR_DOMAIN, + cBarrierInstructions: UINT, + cInterlockedInstructions: UINT, + cTextureStoreInstructions: UINT, +}} +STRUCT!{struct D3D11_SHADER_INPUT_BIND_DESC { + Name: LPCSTR, + Type: D3D_SHADER_INPUT_TYPE, + BindPoint: UINT, + BindCount: UINT, + uFlags: UINT, + ReturnType: D3D_RESOURCE_RETURN_TYPE, + Dimension: D3D_SRV_DIMENSION, + NumSamples: UINT, +}} +pub const D3D_SHADER_REQUIRES_DOUBLES: UINT64 = 0x00000001; +pub const D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL: UINT64 = 0x00000002; +pub const D3D_SHADER_REQUIRES_UAVS_AT_EVERY_STAGE: UINT64 = 0x00000004; +pub const D3D_SHADER_REQUIRES_64_UAVS: UINT64 = 0x00000008; +pub const D3D_SHADER_REQUIRES_MINIMUM_PRECISION: UINT64 = 0x00000010; +pub const D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS: UINT64 = 0x00000020; +pub const D3D_SHADER_REQUIRES_11_1_SHADER_EXTENSIONS: UINT64 = 0x00000040; +pub const D3D_SHADER_REQUIRES_LEVEL_9_COMPARISON_FILTERING: UINT64 = 0x00000080; +pub const D3D_SHADER_REQUIRES_TILED_RESOURCES: UINT64 = 0x00000100; +STRUCT!{struct D3D11_LIBRARY_DESC { + Creator: LPCSTR, + Flags: UINT, + FunctionCount: UINT, +}} +STRUCT!{struct D3D11_FUNCTION_DESC { + Version: UINT, + Creator: LPCSTR, + Flags: UINT, + ConstantBuffers: UINT, + BoundResources: UINT, + InstructionCount: UINT, + TempRegisterCount: UINT, + TempArrayCount: UINT, + DefCount: UINT, + DclCount: UINT, + TextureNormalInstructions: UINT, + TextureLoadInstructions: UINT, + TextureCompInstructions: UINT, + TextureBiasInstructions: UINT, + TextureGradientInstructions: UINT, + FloatInstructionCount: UINT, + IntInstructionCount: UINT, + UintInstructionCount: UINT, + StaticFlowControlCount: UINT, + DynamicFlowControlCount: UINT, + MacroInstructionCount: UINT, + ArrayInstructionCount: UINT, + MovInstructionCount: UINT, + MovcInstructionCount: UINT, + ConversionInstructionCount: UINT, + BitwiseInstructionCount: UINT, + MinFeatureLevel: D3D_FEATURE_LEVEL, + RequiredFeatureFlags: UINT64, + Name: LPCSTR, + FunctionParameterCount: INT, + HasReturn: BOOL, + Has10Level9VertexShader: BOOL, + Has10Level9PixelShader: BOOL, +}} +STRUCT!{struct D3D11_PARAMETER_DESC { + Name: LPCSTR, + SemanticName: LPCSTR, + Type: D3D_SHADER_VARIABLE_TYPE, + Class: D3D_SHADER_VARIABLE_CLASS, + Rows: UINT, + Columns: UINT, + InterpolationMode: D3D_INTERPOLATION_MODE, + Flags: D3D_PARAMETER_FLAGS, + FirstInRegister: UINT, + FirstInComponent: UINT, + FirstOutRegister: UINT, + FirstOutComponent: UINT, +}} +RIDL!{interface ID3D11ShaderReflectionType(ID3D11ShaderReflectionTypeVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_TYPE_DESC) -> HRESULT, + fn GetMemberTypeByIndex(&mut self, Index: UINT) -> *mut ID3D11ShaderReflectionType, + fn GetMemberTypeByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionType, + fn GetMemberTypeName(&mut self, Index: UINT) -> LPCSTR, + fn IsEqual(&mut self, pType: *mut ID3D11ShaderReflectionType) -> HRESULT, + fn GetSubType(&mut self) -> *mut ID3D11ShaderReflectionType, + fn GetBaseClass(&mut self) -> *mut ID3D11ShaderReflectionType, + fn GetNumInterfaces(&mut self) -> UINT, + fn GetInterfaceByIndex(&mut self, uIndex: UINT) -> *mut ID3D11ShaderReflectionType, + fn IsOfType(&mut self, pType: *mut ID3D11ShaderReflectionType) -> HRESULT, + fn ImplementsInterface(&mut self, pBase: *mut ID3D11ShaderReflectionType) -> HRESULT +}} +RIDL!{interface ID3D11ShaderReflectionVariable(ID3D11ShaderReflectionVariableVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_VARIABLE_DESC) -> HRESULT, + fn GetType(&mut self) -> *mut ID3D11ShaderReflectionType, + fn GetBuffer(&mut self) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetInterfaceSlot(&mut self, uArrayIndex: UINT) -> UINT +}} +RIDL!{interface ID3D11ShaderReflectionConstantBuffer(ID3D11ShaderReflectionConstantBufferVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_BUFFER_DESC) -> HRESULT, + fn GetVariableByIndex(&mut self, Index: UINT) -> *mut ID3D11ShaderReflectionVariable, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionVariable +}} +RIDL!{interface ID3D11ShaderReflection(ID3D11ShaderReflectionVtbl): IUnknown(IUnknownVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_DESC) -> HRESULT, + fn GetConstantBufferByIndex( + &mut self, Index: UINT + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: LPCSTR + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: UINT, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetInputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D11_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetOutputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D11_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetPatchConstantParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D11_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: LPCSTR, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetMovInstructionCount(&mut self) -> UINT, + fn GetMovcInstructionCount(&mut self) -> UINT, + fn GetConversionInstructionCount(&mut self) -> UINT, + fn GetBitwiseInstructionCount(&mut self) -> UINT, + fn GetGSInputPrimitive(&mut self) -> D3D_PRIMITIVE, + fn IsSampleFrequencyShader(&mut self) -> BOOL, + fn GetNumInterfaceSlots(&mut self) -> UINT, + fn GetMinFeatureLevel(&mut self, pLevel: *mut D3D_FEATURE_LEVEL) -> HRESULT, + fn GetThreadGroupSize( + &mut self, pSizeX: *mut UINT, pSizeY: *mut UINT, pSizeZ: *mut UINT + ) -> UINT, + fn GetRequiresFlags(&mut self) -> UINT64 +}} +RIDL!{interface ID3D11LibraryReflection(ID3D11LibraryReflectionVtbl): IUnknown(IUnknownVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_LIBRARY_DESC) -> HRESULT, + fn GetFunctionByIndex(&mut self, FunctionIndex: INT) -> *mut ID3D11FunctionReflection +}} +RIDL!{interface ID3D11FunctionReflection(ID3D11FunctionReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_FUNCTION_DESC) -> HRESULT, + fn GetConstantBufferByIndex( + &mut self, BufferIndex: UINT + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: LPCSTR + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: UINT, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: LPCSTR, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetFunctionParameter( + &mut self, ParameterIndex: INT + ) -> *mut ID3D11FunctionParameterReflection +}} +RIDL!{interface ID3D11FunctionParameterReflection(ID3D11FunctionParameterReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_PARAMETER_DESC) -> HRESULT +}} +RIDL!{interface ID3D11Module(ID3D11ModuleVtbl): IUnknown(IUnknownVtbl) { + fn CreateInstance( + &mut self, pNamespace: LPCSTR, ppModuleInstance: *mut *mut ID3D11ModuleInstance + ) -> HRESULT +}} +RIDL!{interface ID3D11ModuleInstance(ID3D11ModuleInstanceVtbl): IUnknown(IUnknownVtbl) { + fn BindConstantBuffer(&mut self, uSrcSlot: UINT, uDstSlot: UINT, cbDstOffset: UINT) -> HRESULT, + fn BindConstantBufferByName( + &mut self, pName: LPCSTR, uDstSlot: UINT, cbDstOffset: UINT + ) -> HRESULT, + fn BindResource(&mut self, uSrcSlot: UINT, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindResourceByName(&mut self, pName: LPCSTR, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindSampler(&mut self, uSrcSlot: UINT, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindSamplerByName(&mut self, pName: LPCSTR, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindUnorderedAccessView(&mut self, uSrcSlot: UINT, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindUnorderedAccessViewByName( + &mut self, pName: LPCSTR, uDstSlot: UINT, uCount: UINT + ) -> HRESULT, + fn BindResourceAsUnorderedAccessView( + &mut self, uSrcSrvSlot: UINT, uDstUavSlot: UINT, uCount: UINT + ) -> HRESULT, + fn BindResourceAsUnorderedAccessViewByName( + &mut self, pSrvName: LPCSTR, uDstUavSlot: UINT, uCount: UINT + ) -> HRESULT +}} +RIDL!{interface ID3D11Linker(ID3D11LinkerVtbl): IUnknown(IUnknownVtbl) { + fn Link( + &mut self, pEntry: *mut ID3D11ModuleInstance, pEntryName: LPCSTR, pTargetName: LPCSTR, + uFlags: UINT, ppShaderBlob: *mut *mut ID3DBlob, ppErrorBuffer: *mut *mut ID3DBlob + ) -> HRESULT, + fn UseLibrary(&mut self, pLibraryMI: *mut ID3D11ModuleInstance) -> HRESULT, + fn AddClipPlaneFromCBuffer(&mut self, uCBufferSlot: UINT, uCBufferEntry: UINT) -> HRESULT +}} +RIDL!{interface ID3D11LinkingNode(ID3D11LinkingNodeVtbl): IUnknown(IUnknownVtbl) {}} +RIDL!{interface ID3D11FunctionLinkingGraph(ID3D11FunctionLinkingGraphVtbl): IUnknown(IUnknownVtbl) { + fn CreateModuleInstance( + &mut self, ppModuleInstance: *mut *mut ID3D11ModuleInstance, + ppErrorBuffer: *mut *mut ID3DBlob + ) -> HRESULT, + fn SetInputSignature( + &mut self, pInputParameters: *const D3D11_PARAMETER_DESC, cInputParameters: UINT, + ppInputNode: *mut *mut ID3D11LinkingNode + ) -> HRESULT, + fn SetOutputSignature( + &mut self, pOutputParameters: *const D3D11_PARAMETER_DESC, cOutputParameters: UINT, + ppOutputNode: *mut *mut ID3D11LinkingNode + ) -> HRESULT, + fn CallFunction( + &mut self, pModuleInstanceNamespace: LPCSTR, + pModuleWithFunctionPrototype: *mut ID3D11Module, pFunctionName: LPCSTR, + ppCallNode: *mut *mut ID3D11LinkingNode + ) -> HRESULT, + fn PassValue( + &mut self, pSrcNode: *mut ID3D11LinkingNode, SrcParameterIndex: INT, + pDstNode: *mut ID3D11LinkingNode, DstParameterIndex: INT + ) -> HRESULT, + fn PassValueWithSwizzle( + &mut self, pSrcNode: *mut ID3D11LinkingNode, SrcParameterIndex: INT, pSrcSwizzle: LPCSTR, + pDstNode: *mut ID3D11LinkingNode, DstParameterIndex: INT, pDstSwizzle: LPCSTR + ) -> HRESULT, + fn GetLastError(&mut self, ppErrorBuffer: *mut *mut ID3DBlob) -> HRESULT, + fn GenerateHlsl(&mut self, uFlags: UINT, ppBuffer: *mut *mut ID3DBlob) -> HRESULT +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d12.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d12.rs new file mode 100644 index 0000000..ac6ae3b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d12.rs @@ -0,0 +1,2324 @@ +// Copyright © 2015, Dmitry Roschin +// Licensed under the MIT License <LICENSE.md> +pub const D3D12_16BIT_INDEX_STRIP_CUT_VALUE: ::UINT = 0xffff; +pub const D3D12_32BIT_INDEX_STRIP_CUT_VALUE: ::UINT = 0xffffffff; +pub const D3D12_8BIT_INDEX_STRIP_CUT_VALUE: ::UINT = 0xff; +pub const D3D12_ANISOTROPIC_FILTERING_BIT: ::UINT = 0x40; +pub const D3D12_APPEND_ALIGNED_ELEMENT: ::UINT = 0xffffffff; +pub const D3D12_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT: ::UINT = 9; +pub const D3D12_CLIP_OR_CULL_DISTANCE_COUNT: ::UINT = 8; +pub const D3D12_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT: ::UINT = 2; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT: ::UINT = 14; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT: ::UINT = 15; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT: ::UINT = 16; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT: ::UINT = 15; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT: ::UINT = 64; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT: ::UINT = 128; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT: ::UINT = 128; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_COUNT: ::UINT = 16; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_SAMPLER_SLOT_COUNT: ::UINT = 16; +pub const D3D12_COMMONSHADER_SUBROUTINE_NESTING_LIMIT: ::UINT = 32; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_COUNT: ::UINT = 4096; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_READS_PER_INST: ::UINT = 3; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_READ_PORTS: ::UINT = 3; +pub const D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX: ::UINT = 10; +pub const D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN: ::INT = -10; +pub const D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE: ::INT = -8; +pub const D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE: ::UINT = 7; +pub const D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT: ::UINT = 256; +pub const D3D12_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 256; +pub const D3D12_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP: ::UINT = 64; +pub const D3D12_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 240; +pub const D3D12_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP: ::UINT = 68; +pub const D3D12_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 224; +pub const D3D12_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP: ::UINT = 72; +pub const D3D12_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 208; +pub const D3D12_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP: ::UINT = 76; +pub const D3D12_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 192; +pub const D3D12_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP: ::UINT = 84; +pub const D3D12_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 176; +pub const D3D12_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP: ::UINT = 92; +pub const D3D12_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 160; +pub const D3D12_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP: ::UINT = 100; +pub const D3D12_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 144; +pub const D3D12_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP: ::UINT = 112; +pub const D3D12_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 128; +pub const D3D12_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP: ::UINT = 128; +pub const D3D12_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 112; +pub const D3D12_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP: ::UINT = 144; +pub const D3D12_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 96; +pub const D3D12_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP: ::UINT = 168; +pub const D3D12_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 80; +pub const D3D12_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP: ::UINT = 204; +pub const D3D12_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 64; +pub const D3D12_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP: ::UINT = 256; +pub const D3D12_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 48; +pub const D3D12_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP: ::UINT = 340; +pub const D3D12_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 32; +pub const D3D12_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP: ::UINT = 512; +pub const D3D12_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 16; +pub const D3D12_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP: ::UINT = 768; +pub const D3D12_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION: ::UINT = 1; +pub const D3D12_CS_4_X_RAW_UAV_BYTE_ALIGNMENT: ::UINT = 256; +pub const D3D12_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP: ::UINT = 768; +pub const D3D12_CS_4_X_THREAD_GROUP_MAX_X: ::UINT = 768; +pub const D3D12_CS_4_X_THREAD_GROUP_MAX_Y: ::UINT = 768; +pub const D3D12_CS_4_X_UAV_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION: ::UINT = 65535; +pub const D3D12_CS_TGSM_REGISTER_COUNT: ::UINT = 8192; +pub const D3D12_CS_TGSM_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_CS_TGSM_RESOURCE_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_CS_TGSM_RESOURCE_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_CS_THREADGROUPID_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_CS_THREADGROUPID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREADIDINGROUP_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_CS_THREADIDINGROUP_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREADID_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_CS_THREADID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP: ::UINT = 1024; +pub const D3D12_CS_THREAD_GROUP_MAX_X: ::UINT = 1024; +pub const D3D12_CS_THREAD_GROUP_MAX_Y: ::UINT = 1024; +pub const D3D12_CS_THREAD_GROUP_MAX_Z: ::UINT = 64; +pub const D3D12_CS_THREAD_GROUP_MIN_X: ::UINT = 1; +pub const D3D12_CS_THREAD_GROUP_MIN_Y: ::UINT = 1; +pub const D3D12_CS_THREAD_GROUP_MIN_Z: ::UINT = 1; +pub const D3D12_CS_THREAD_LOCAL_TEMP_REGISTER_POOL: ::UINT = 16384; +pub const D3D12_DEFAULT_BLEND_FACTOR_ALPHA: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BLEND_FACTOR_BLUE: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BLEND_FACTOR_GREEN: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BLEND_FACTOR_RED: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BORDER_COLOR_COMPONENT: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_DEPTH_BIAS: ::UINT = 0; +pub const D3D12_DEFAULT_DEPTH_BIAS_CLAMP: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_MAX_ANISOTROPY: ::UINT = 16; +pub const D3D12_DEFAULT_MIP_LOD_BIAS: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 4194304; +pub const D3D12_DEFAULT_RENDER_TARGET_ARRAY_INDEX: ::UINT = 0; +pub const D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 65536; +pub const D3D12_DEFAULT_SAMPLE_MASK: ::UINT = 0xffffffff; +pub const D3D12_DEFAULT_SCISSOR_ENDX: ::UINT = 0; +pub const D3D12_DEFAULT_SCISSOR_ENDY: ::UINT = 0; +pub const D3D12_DEFAULT_SCISSOR_STARTX: ::UINT = 0; +pub const D3D12_DEFAULT_SCISSOR_STARTY: ::UINT = 0; +pub const D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_STENCIL_READ_MASK: ::UINT = 0xff; +pub const D3D12_DEFAULT_STENCIL_REFERENCE: ::UINT = 0; +pub const D3D12_DEFAULT_STENCIL_WRITE_MASK: ::UINT = 0xff; +pub const D3D12_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_HEIGHT: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_MAX_DEPTH: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_VIEWPORT_MIN_DEPTH: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_VIEWPORT_TOPLEFTX: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_TOPLEFTY: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_WIDTH: ::UINT = 0; +pub const D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND: ::UINT = 0xffffffff; +pub const D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_END: ::UINT = 0xfffffff7; +pub const D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_START: ::UINT = 0xfffffff0; +pub const D3D12_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: ::UINT = 3968; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_FILTER_REDUCTION_TYPE_MASK: ::UINT = 0x3; +pub const D3D12_FILTER_REDUCTION_TYPE_SHIFT: ::UINT = 7; +pub const D3D12_FILTER_TYPE_MASK: ::UINT = 0x3; +pub const D3D12_FLOAT16_FUSED_TOLERANCE_IN_ULP: ::DOUBLE = 0.6; +pub const D3D12_FLOAT32_MAX: ::FLOAT = 3.402823466e+38; +pub const D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP: ::FLOAT = 0.6; +pub const D3D12_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR: ::FLOAT = 2.4; +pub const D3D12_FLOAT_TO_SRGB_EXPONENT_NUMERATOR: ::FLOAT = 1.0; +pub const D3D12_FLOAT_TO_SRGB_OFFSET: ::FLOAT = 0.055; +pub const D3D12_FLOAT_TO_SRGB_SCALE_1: ::FLOAT = 12.92; +pub const D3D12_FLOAT_TO_SRGB_SCALE_2: ::FLOAT = 1.055; +pub const D3D12_FLOAT_TO_SRGB_THRESHOLD: ::FLOAT = 0.0031308; +pub const D3D12_FTOI_INSTRUCTION_MAX_INPUT: ::FLOAT = 2147483647.999; +pub const D3D12_FTOI_INSTRUCTION_MIN_INPUT: ::FLOAT = -2147483648.999; +pub const D3D12_FTOU_INSTRUCTION_MAX_INPUT: ::FLOAT = 4294967295.999; +pub const D3D12_FTOU_INSTRUCTION_MIN_INPUT: ::FLOAT = 0.0; +pub const D3D12_GS_INPUT_INSTANCE_ID_READS_PER_INST: ::UINT = 2; +pub const D3D12_GS_INPUT_INSTANCE_ID_READ_PORTS: ::UINT = 1; +pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_GS_INPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_GS_INPUT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_GS_INPUT_REGISTER_VERTICES: ::UINT = 32; +pub const D3D12_GS_MAX_INSTANCE_COUNT: ::UINT = 32; +pub const D3D12_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES: ::UINT = 1024; +pub const D3D12_GS_OUTPUT_ELEMENTS: ::UINT = 32; +pub const D3D12_GS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_CONTROL_POINT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND: ::UINT = 0xffffffff; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND: ::UINT = 0xffffffff; +pub const D3D12_HS_MAXTESSFACTOR_LOWER_BOUND: ::FLOAT = 1.0; +pub const D3D12_HS_MAXTESSFACTOR_UPPER_BOUND: ::FLOAT = 64.0; +pub const D3D12_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: ::UINT = 3968; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS: ::UINT = 128; +pub const D3D12_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES: ::UINT = 0; +pub const D3D12_IA_DEFAULT_PRIMITIVE_TOPOLOGY: ::UINT = 0; +pub const D3D12_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES: ::UINT = 0; +pub const D3D12_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT: ::UINT = 1; +pub const D3D12_IA_INSTANCE_ID_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_INTEGER_ARITHMETIC_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_PATCH_MAX_CONTROL_POINT_COUNT: ::UINT = 32; +pub const D3D12_IA_PRIMITIVE_ID_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_VERTEX_ID_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT: ::UINT = 32; +pub const D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS: ::UINT = 128; +pub const D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT: ::UINT = 32; +pub const D3D12_INTEGER_DIVIDE_BY_ZERO_QUOTIENT: ::UINT = 0xffffffff; +pub const D3D12_INTEGER_DIVIDE_BY_ZERO_REMAINDER: ::UINT = 0xffffffff; +pub const D3D12_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL: ::UINT = 0xffffffff; +pub const D3D12_KEEP_UNORDERED_ACCESS_VIEWS: ::UINT = 0xffffffff; +pub const D3D12_LINEAR_GAMMA: ::FLOAT = 1.0; +pub const D3D12_MAG_FILTER_SHIFT: ::UINT = 2; +pub const D3D12_MAJOR_VERSION: ::UINT = 12; +pub const D3D12_MAX_BORDER_COLOR_COMPONENT: ::FLOAT = 1.0; +pub const D3D12_MAX_DEPTH: ::FLOAT = 1.0; +pub const D3D12_MAX_LIVE_STATIC_SAMPLERS: ::UINT = 2032; +pub const D3D12_MAX_MAXANISOTROPY: ::UINT = 16; +pub const D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT: ::UINT = 32; +pub const D3D12_MAX_POSITION_VALUE: ::FLOAT = 3.402823466e+34; +pub const D3D12_MAX_ROOT_COST: ::UINT = 64; +pub const D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1: ::UINT = 1000000; +pub const D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2: ::UINT = 1000000; +pub const D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE: ::UINT = 2048; +pub const D3D12_MAX_TEXTURE_DIMENSION_2_TO_EXP: ::UINT = 17; +pub const D3D12_MINOR_VERSION: ::UINT = 0; +pub const D3D12_MIN_BORDER_COLOR_COMPONENT: ::FLOAT = 0.0; +pub const D3D12_MIN_DEPTH: ::FLOAT = 0.0; +pub const D3D12_MIN_FILTER_SHIFT: ::UINT = 4; +pub const D3D12_MIN_MAXANISOTROPY: ::UINT = 0; +pub const D3D12_MIP_FILTER_SHIFT: ::UINT = 0; +pub const D3D12_MIP_LOD_BIAS_MAX: ::FLOAT = 15.99; +pub const D3D12_MIP_LOD_BIAS_MIN: ::FLOAT = -16.0; +pub const D3D12_MIP_LOD_FRACTIONAL_BIT_COUNT: ::UINT = 8; +pub const D3D12_MIP_LOD_RANGE_BIT_COUNT: ::UINT = 8; +pub const D3D12_MULTISAMPLE_ANTIALIAS_LINE_WIDTH: ::FLOAT = 1.4; +pub const D3D12_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT: ::UINT = 0; +pub const D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_END: ::UINT = 0xffffffff; +pub const D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_START: ::UINT = 0xfffffff8; +pub const D3D12_PACKED_TILE: ::UINT = 0xffffffff; +pub const D3D12_PIXEL_ADDRESS_RANGE_BIT_COUNT: ::UINT = 15; +pub const D3D12_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT: ::UINT = 16; +pub const D3D12_PS_CS_UAV_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_PS_CS_UAV_REGISTER_COUNT: ::UINT = 8; +pub const D3D12_PS_CS_UAV_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_PS_CS_UAV_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_PS_FRONTFACING_DEFAULT_VALUE: ::UINT = 0xffffffff; +pub const D3D12_PS_FRONTFACING_FALSE_VALUE: ::UINT = 0; +pub const D3D12_PS_FRONTFACING_TRUE_VALUE: ::UINT = 0xffffffff; +pub const D3D12_PS_INPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_PS_INPUT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_PS_INPUT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT: ::FLOAT = 0.0; +pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_OUTPUT_MASK_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_PS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_OUTPUT_REGISTER_COUNT: ::UINT = 8; +pub const D3D12_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT: ::FLOAT = 0.5; +pub const D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT: ::UINT = 16; +pub const D3D12_REQ_BLEND_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP: ::UINT = 27; +pub const D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT: ::UINT = 4096; +pub const D3D12_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: ::UINT = 32; +pub const D3D12_REQ_DRAW_VERTEX_COUNT_2_TO_EXP: ::UINT = 32; +pub const D3D12_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION: ::UINT = 16384; +pub const D3D12_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT: ::UINT = 1024; +pub const D3D12_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT: ::UINT = 4096; +pub const D3D12_REQ_MAXANISOTROPY: ::UINT = 16; +pub const D3D12_REQ_MIP_LEVELS: ::UINT = 15; +pub const D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES: ::UINT = 2048; +pub const D3D12_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH: ::UINT = 16384; +pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM: ::UINT = 128; +pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM: ::FLOAT = 0.25; +pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM: ::UINT = 2048; +pub const D3D12_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP: ::UINT = 20; +pub const D3D12_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_SUBRESOURCES: ::UINT = 30720; +pub const D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION: ::UINT = 2048; +pub const D3D12_REQ_TEXTURE1D_U_DIMENSION: ::UINT = 16384; +pub const D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION: ::UINT = 2048; +pub const D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION: ::UINT = 16384; +pub const D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION: ::UINT = 2048; +pub const D3D12_REQ_TEXTURECUBE_DIMENSION: ::UINT = 16384; +pub const D3D12_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL: ::UINT = 0; +pub const D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES: ::UINT = 0xffffffff; +pub const D3D12_SHADER_COMPONENT_MAPPING_MASK: ::UINT = 0x7; +pub const D3D12_SHADER_COMPONENT_MAPPING_SHIFT: ::UINT = 3; +pub const D3D12_SHADER_MAJOR_VERSION: ::UINT = 5; +pub const D3D12_SHADER_MAX_INSTANCES: ::UINT = 65535; +pub const D3D12_SHADER_MAX_INTERFACES: ::UINT = 253; +pub const D3D12_SHADER_MAX_INTERFACE_CALL_SITES: ::UINT = 4096; +pub const D3D12_SHADER_MAX_TYPES: ::UINT = 65535; +pub const D3D12_SHADER_MINOR_VERSION: ::UINT = 1; +pub const D3D12_SHIFT_INSTRUCTION_PAD_VALUE: ::UINT = 0; +pub const D3D12_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT: ::UINT = 5; +pub const D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT: ::UINT = 8; +pub const D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 65536; +pub const D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 4096; +pub const D3D12_SO_BUFFER_MAX_STRIDE_IN_BYTES: ::UINT = 2048; +pub const D3D12_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES: ::UINT = 512; +pub const D3D12_SO_BUFFER_SLOT_COUNT: ::UINT = 4; +pub const D3D12_SO_DDI_REGISTER_INDEX_DENOTING_GAP: ::UINT = 0xffffffff; +pub const D3D12_SO_NO_RASTERIZED_STREAM: ::UINT = 0xffffffff; +pub const D3D12_SO_OUTPUT_COMPONENT_COUNT: ::UINT = 128; +pub const D3D12_SO_STREAM_COUNT: ::UINT = 4; +pub const D3D12_SPEC_DATE_DAY: ::UINT = 14; +pub const D3D12_SPEC_DATE_MONTH: ::UINT = 11; +pub const D3D12_SPEC_DATE_YEAR: ::UINT = 2014; +pub const D3D12_SPEC_VERSION: ::DOUBLE = 1.16; +pub const D3D12_SRGB_GAMMA: ::FLOAT = 2.2; +pub const D3D12_SRGB_TO_FLOAT_DENOMINATOR_1: ::FLOAT = 12.92; +pub const D3D12_SRGB_TO_FLOAT_DENOMINATOR_2: ::FLOAT = 1.055; +pub const D3D12_SRGB_TO_FLOAT_EXPONENT: ::FLOAT = 2.4; +pub const D3D12_SRGB_TO_FLOAT_OFFSET: ::FLOAT = 0.055; +pub const D3D12_SRGB_TO_FLOAT_THRESHOLD: ::FLOAT = 0.04045; +pub const D3D12_SRGB_TO_FLOAT_TOLERANCE_IN_ULP: ::FLOAT = 0.5; +pub const D3D12_STANDARD_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_STANDARD_COMPONENT_BIT_COUNT_DOUBLED: ::UINT = 64; +pub const D3D12_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE: ::UINT = 4; +pub const D3D12_STANDARD_PIXEL_COMPONENT_COUNT: ::UINT = 128; +pub const D3D12_STANDARD_PIXEL_ELEMENT_COUNT: ::UINT = 32; +pub const D3D12_STANDARD_VECTOR_SIZE: ::UINT = 4; +pub const D3D12_STANDARD_VERTEX_ELEMENT_COUNT: ::UINT = 32; +pub const D3D12_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT: ::UINT = 64; +pub const D3D12_SUBPIXEL_FRACTIONAL_BIT_COUNT: ::UINT = 8; +pub const D3D12_SUBTEXEL_FRACTIONAL_BIT_COUNT: ::UINT = 8; +pub const D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_END: ::UINT = 0xffffffff; +pub const D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_START: ::UINT = 0xfffffff0; +pub const D3D12_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR: ::UINT = 64; +pub const D3D12_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR: ::UINT = 64; +pub const D3D12_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR: ::UINT = 63; +pub const D3D12_TESSELLATOR_MAX_TESSELLATION_FACTOR: ::UINT = 64; +pub const D3D12_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR: ::UINT = 2; +pub const D3D12_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR: ::UINT = 1; +pub const D3D12_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR: ::UINT = 1; +pub const D3D12_TEXEL_ADDRESS_RANGE_BIT_COUNT: ::UINT = 16; +pub const D3D12_TEXTURE_DATA_PITCH_ALIGNMENT: ::UINT = 256; +pub const D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT: ::UINT = 512; +pub const D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES: ::UINT = 65536; +pub const D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT: ::UINT = 4096; +pub const D3D12_UAV_SLOT_COUNT: ::UINT = 64; +pub const D3D12_UNBOUND_MEMORY_ACCESS_RESULT: ::UINT = 0; +pub const D3D12_VIEWPORT_AND_SCISSORRECT_MAX_INDEX: ::UINT = 15; +pub const D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE: ::UINT = 16; +pub const D3D12_VIEWPORT_BOUNDS_MAX: ::UINT = 32767; +pub const D3D12_VIEWPORT_BOUNDS_MIN: ::INT = -32768; +pub const D3D12_VS_INPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_VS_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_VS_INPUT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_VS_INPUT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_VS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_VS_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT: ::UINT = 10; +pub const D3D12_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: ::UINT = 25; +pub const D3D12_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP: ::UINT = 25; +pub type D3D12_GPU_VIRTUAL_ADDRESS = ::UINT64; +ENUM!{enum D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE_DIRECT = 0, + D3D12_COMMAND_LIST_TYPE_BUNDLE = 1, + D3D12_COMMAND_LIST_TYPE_COMPUTE = 2, + D3D12_COMMAND_LIST_TYPE_COPY = 3, +}} +FLAGS!{enum D3D12_COMMAND_QUEUE_FLAGS { + D3D12_COMMAND_QUEUE_FLAG_NONE = 0x0, + D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT = 0x1, +}} +ENUM!{enum D3D12_COMMAND_QUEUE_PRIORITY { + D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0, + D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100, +}} +STRUCT!{struct D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE, + Priority: ::INT, + Flags: D3D12_COMMAND_QUEUE_FLAGS, + NodeMask: ::UINT, +}} +ENUM!{enum D3D12_PRIMITIVE_TOPOLOGY_TYPE { + D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED = 0, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT = 1, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE = 2, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE = 3, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH = 4, +}} +ENUM!{enum D3D12_INPUT_CLASSIFICATION { + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0, + D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1, +}} +STRUCT!{struct D3D12_INPUT_ELEMENT_DESC { + SemanticName: ::LPCSTR, + SemanticIndex: ::UINT, + Format: ::DXGI_FORMAT, + InputSlot: ::UINT, + AlignedByteOffset: ::UINT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION, + InstanceDataStepRate: ::UINT, +}} +ENUM!{enum D3D12_FILL_MODE { + D3D12_FILL_MODE_WIREFRAME = 2, + D3D12_FILL_MODE_SOLID = 3, +}} +pub type D3D12_PRIMITIVE_TOPOLOGY = ::D3D_PRIMITIVE_TOPOLOGY; +pub type D3D12_PRIMITIVE = ::D3D_PRIMITIVE; +ENUM!{enum D3D12_CULL_MODE { + D3D12_CULL_MODE_NONE = 1, + D3D12_CULL_MODE_FRONT = 2, + D3D12_CULL_MODE_BACK = 3, +}} +STRUCT!{struct D3D12_SO_DECLARATION_ENTRY { + Stream: ::UINT, + SemanticName: ::LPCSTR, + SemanticIndex: ::UINT, + StartComponent: ::BYTE, + ComponentCount: ::BYTE, + OutputSlot: ::BYTE, +}} +STRUCT!{struct D3D12_VIEWPORT { + TopLeftX: ::FLOAT, + TopLeftY: ::FLOAT, + Width: ::FLOAT, + Height: ::FLOAT, + MinDepth: ::FLOAT, + MaxDepth: ::FLOAT, +}} +pub type D3D12_RECT = ::RECT; +STRUCT!{struct D3D12_BOX { + left: ::UINT, + top: ::UINT, + front: ::UINT, + right: ::UINT, + bottom: ::UINT, + back: ::UINT, +}} +ENUM!{enum D3D12_COMPARISON_FUNC { + D3D12_COMPARISON_FUNC_NEVER = 1, + D3D12_COMPARISON_FUNC_LESS = 2, + D3D12_COMPARISON_FUNC_EQUAL = 3, + D3D12_COMPARISON_FUNC_LESS_EQUAL = 4, + D3D12_COMPARISON_FUNC_GREATER = 5, + D3D12_COMPARISON_FUNC_NOT_EQUAL = 6, + D3D12_COMPARISON_FUNC_GREATER_EQUAL = 7, + D3D12_COMPARISON_FUNC_ALWAYS = 8, +}} +ENUM!{enum D3D12_DEPTH_WRITE_MASK { + D3D12_DEPTH_WRITE_MASK_ZERO = 0, + D3D12_DEPTH_WRITE_MASK_ALL = 1, +}} +ENUM!{enum D3D12_STENCIL_OP { + D3D12_STENCIL_OP_KEEP = 1, + D3D12_STENCIL_OP_ZERO = 2, + D3D12_STENCIL_OP_REPLACE = 3, + D3D12_STENCIL_OP_INCR_SAT = 4, + D3D12_STENCIL_OP_DECR_SAT = 5, + D3D12_STENCIL_OP_INVERT = 6, + D3D12_STENCIL_OP_INCR = 7, + D3D12_STENCIL_OP_DECR = 8, +}} +STRUCT!{struct D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP, + StencilDepthFailOp: D3D12_STENCIL_OP, + StencilPassOp: D3D12_STENCIL_OP, + StencilFunc: D3D12_COMPARISON_FUNC, +}} +STRUCT!{struct D3D12_DEPTH_STENCIL_DESC { + DepthEnable: ::BOOL, + DepthWriteMask: D3D12_DEPTH_WRITE_MASK, + DepthFunc: D3D12_COMPARISON_FUNC, + StencilEnable: ::BOOL, + StencilReadMask: ::UINT8, + StencilWriteMask: ::UINT8, + FrontFace: D3D12_DEPTH_STENCILOP_DESC, + BackFace: D3D12_DEPTH_STENCILOP_DESC, +}} +ENUM!{enum D3D12_BLEND { + D3D12_BLEND_ZERO = 1, + D3D12_BLEND_ONE = 2, + D3D12_BLEND_SRC_COLOR = 3, + D3D12_BLEND_INV_SRC_COLOR = 4, + D3D12_BLEND_SRC_ALPHA = 5, + D3D12_BLEND_INV_SRC_ALPHA = 6, + D3D12_BLEND_DEST_ALPHA = 7, + D3D12_BLEND_INV_DEST_ALPHA = 8, + D3D12_BLEND_DEST_COLOR = 9, + D3D12_BLEND_INV_DEST_COLOR = 10, + D3D12_BLEND_SRC_ALPHA_SAT = 11, + D3D12_BLEND_BLEND_FACTOR = 14, + D3D12_BLEND_INV_BLEND_FACTOR = 15, + D3D12_BLEND_SRC1_COLOR = 16, + D3D12_BLEND_INV_SRC1_COLOR = 17, + D3D12_BLEND_SRC1_ALPHA = 18, + D3D12_BLEND_INV_SRC1_ALPHA = 19, +}} +ENUM!{enum D3D12_BLEND_OP { + D3D12_BLEND_OP_ADD = 1, + D3D12_BLEND_OP_SUBTRACT = 2, + D3D12_BLEND_OP_REV_SUBTRACT = 3, + D3D12_BLEND_OP_MIN = 4, + D3D12_BLEND_OP_MAX = 5, +}} +FLAGS!{enum D3D12_COLOR_WRITE_ENABLE { + D3D12_COLOR_WRITE_ENABLE_RED = 0x1, + D3D12_COLOR_WRITE_ENABLE_GREEN = 0x2, + D3D12_COLOR_WRITE_ENABLE_BLUE = 0x4, + D3D12_COLOR_WRITE_ENABLE_ALPHA = 0x8, + D3D12_COLOR_WRITE_ENABLE_ALL = 0xF, +}} +ENUM!{enum D3D12_LOGIC_OP { + D3D12_LOGIC_OP_CLEAR = 0, + D3D12_LOGIC_OP_SET = 1, + D3D12_LOGIC_OP_COPY = 2, + D3D12_LOGIC_OP_COPY_INVERTED = 3, + D3D12_LOGIC_OP_NOOP = 4, + D3D12_LOGIC_OP_INVERT = 5, + D3D12_LOGIC_OP_AND = 6, + D3D12_LOGIC_OP_NAND = 7, + D3D12_LOGIC_OP_OR = 8, + D3D12_LOGIC_OP_NOR = 9, + D3D12_LOGIC_OP_XOR = 10, + D3D12_LOGIC_OP_EQUIV = 11, + D3D12_LOGIC_OP_AND_REVERSE = 12, + D3D12_LOGIC_OP_AND_INVERTED = 13, + D3D12_LOGIC_OP_OR_REVERSE = 14, + D3D12_LOGIC_OP_OR_INVERTED = 15, +}} +STRUCT!{struct D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: ::BOOL, + LogicOpEnable: ::BOOL, + SrcBlend: D3D12_BLEND, + DestBlend: D3D12_BLEND, + BlendOp: D3D12_BLEND_OP, + SrcBlendAlpha: D3D12_BLEND, + DestBlendAlpha: D3D12_BLEND, + BlendOpAlpha: D3D12_BLEND_OP, + LogicOp: D3D12_LOGIC_OP, + RenderTargetWriteMask: ::UINT8, +}} +STRUCT!{struct D3D12_BLEND_DESC { + AlphaToCoverageEnable: ::BOOL, + IndependentBlendEnable: ::BOOL, + RenderTarget: [D3D12_RENDER_TARGET_BLEND_DESC; 8], +}} +ENUM!{enum D3D12_CONSERVATIVE_RASTERIZATION_MODE { + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = 0, + D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = 1, +}} +STRUCT!{struct D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE, + CullMode: D3D12_CULL_MODE, + FrontCounterClockwise: ::BOOL, + DepthBias: ::INT, + DepthBiasClamp: ::FLOAT, + SlopeScaledDepthBias: ::FLOAT, + DepthClipEnable: ::BOOL, + MultisampleEnable: ::BOOL, + AntialiasedLineEnable: ::BOOL, + ForcedSampleCount: ::UINT, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE, +}} +RIDL!{interface ID3D12Object(ID3D12ObjectVtbl): IUnknown(IUnknownVtbl) { + fn GetPrivateData( + &mut self, guid: ::REFGUID, pDataSize: *mut ::UINT, pData: *mut ::c_void + ) -> ::HRESULT, + fn SetPrivateData( + &mut self, guid: ::REFGUID, DataSize: ::UINT, pData: *const ::c_void + ) -> ::HRESULT, + fn SetPrivateDataInterface( + &mut self, guid: ::REFGUID, pData: *const ::IUnknown + ) -> ::HRESULT, + fn SetName(&mut self, Name: ::LPCWSTR) -> ::HRESULT +}} +RIDL!{interface ID3D12DeviceChild(ID3D12DeviceChildVtbl): ID3D12Object(ID3D12ObjectVtbl) { + fn GetDevice( + &mut self, riid: ::REFGUID, ppvDevice: *mut *mut ::c_void + ) -> ::HRESULT +}} +RIDL!{interface ID3D12RootSignature(ID3D12RootSignatureVtbl): + ID3D12DeviceChild(ID3D12DeviceChildVtbl) { +}} +STRUCT!{struct D3D12_SHADER_BYTECODE { + pShaderBytecode: *const ::c_void, + BytecodeLength: ::SIZE_T, +}} +STRUCT!{struct D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: *const D3D12_SO_DECLARATION_ENTRY, + NumEntries: ::UINT, + pBufferStrides: *const ::UINT, + NumStrides: ::UINT, + RasterizedStream: ::UINT, +}} +STRUCT!{struct D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: *const D3D12_INPUT_ELEMENT_DESC, + NumElements: ::UINT, +}} +ENUM!{enum D3D12_INDEX_BUFFER_STRIP_CUT_VALUE { + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED = 0, + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF = 1, + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF = 2, +}} +STRUCT!{struct D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: *const ::c_void, + CachedBlobSizeInBytes: ::SIZE_T, +}} +FLAGS!{enum D3D12_PIPELINE_STATE_FLAGS { + D3D12_PIPELINE_STATE_FLAG_NONE = 0x0, + D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG = 0x1, +}} +STRUCT!{struct D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: *mut ID3D12RootSignature, + VS: D3D12_SHADER_BYTECODE, + PS: D3D12_SHADER_BYTECODE, + DS: D3D12_SHADER_BYTECODE, + HS: D3D12_SHADER_BYTECODE, + GS: D3D12_SHADER_BYTECODE, + StreamOutput: D3D12_STREAM_OUTPUT_DESC, + BlendState: D3D12_BLEND_DESC, + SampleMask: ::UINT, + RasterizerState: D3D12_RASTERIZER_DESC, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC, + InputLayout: D3D12_INPUT_LAYOUT_DESC, + IBStripCutValue: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE, + NumRenderTargets: ::UINT, + RTVFormats: [::DXGI_FORMAT; 8], + DSVFormat: ::DXGI_FORMAT, + SampleDesc: ::DXGI_SAMPLE_DESC, + NodeMask: ::UINT, + CachedPSO: D3D12_CACHED_PIPELINE_STATE, + Flags: D3D12_PIPELINE_STATE_FLAGS, +}} +STRUCT!{struct D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: *mut ID3D12RootSignature, + CS: D3D12_SHADER_BYTECODE, + NodeMask: ::UINT, + CachedPSO: D3D12_CACHED_PIPELINE_STATE, + Flags: D3D12_PIPELINE_STATE_FLAGS, +}} +ENUM!{enum D3D12_FEATURE { + D3D12_FEATURE_D3D12_OPTIONS = 0, + D3D12_FEATURE_ARCHITECTURE = 1, + D3D12_FEATURE_FEATURE_LEVELS = 2, + D3D12_FEATURE_FORMAT_SUPPORT = 3, + D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = 4, + D3D12_FEATURE_FORMAT_INFO = 5, + D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = 6, +}} +FLAGS!{enum D3D12_SHADER_MIN_PRECISION_SUPPORT { + D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE = 0, + D3D12_SHADER_MIN_PRECISION_SUPPORT_10_BIT = 0x1, + D3D12_SHADER_MIN_PRECISION_SUPPORT_16_BIT = 0x2, +}} +ENUM!{enum D3D12_TILED_RESOURCES_TIER { + D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED = 0, + D3D12_TILED_RESOURCES_TIER_1 = 1, + D3D12_TILED_RESOURCES_TIER_2 = 2, + D3D12_TILED_RESOURCES_TIER_3 = 3, +}} +ENUM!{enum D3D12_RESOURCE_BINDING_TIER { + D3D12_RESOURCE_BINDING_TIER_1 = 1, + D3D12_RESOURCE_BINDING_TIER_2 = 2, + D3D12_RESOURCE_BINDING_TIER_3 = 3, +}} +ENUM!{enum D3D12_CONSERVATIVE_RASTERIZATION_TIER { + D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED = 0, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 = 1, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_2 = 2, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 = 3, +}} +FLAGS!{enum D3D12_FORMAT_SUPPORT1 { + D3D12_FORMAT_SUPPORT1_NONE = 0x0, + D3D12_FORMAT_SUPPORT1_BUFFER = 0x1, + D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER = 0x2, + D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER = 0x4, + D3D12_FORMAT_SUPPORT1_SO_BUFFER = 0x8, + D3D12_FORMAT_SUPPORT1_TEXTURE1D = 0x10, + D3D12_FORMAT_SUPPORT1_TEXTURE2D = 0x20, + D3D12_FORMAT_SUPPORT1_TEXTURE3D = 0x40, + D3D12_FORMAT_SUPPORT1_TEXTURECUBE = 0x80, + D3D12_FORMAT_SUPPORT1_SHADER_LOAD = 0x100, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE = 0x200, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON = 0x400, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_MONO_TEXT = 0x800, + D3D12_FORMAT_SUPPORT1_MIP = 0x1000, + D3D12_FORMAT_SUPPORT1_RENDER_TARGET = 0x4000, + D3D12_FORMAT_SUPPORT1_BLENDABLE = 0x8000, + D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL = 0x10000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE = 0x40000, + D3D12_FORMAT_SUPPORT1_DISPLAY = 0x80000, + D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT = 0x100000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET = 0x200000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD = 0x400000, + D3D12_FORMAT_SUPPORT1_SHADER_GATHER = 0x800000, + D3D12_FORMAT_SUPPORT1_BACK_BUFFER_CAST = 0x1000000, + D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW = 0x2000000, + D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON = 0x4000000, + D3D12_FORMAT_SUPPORT1_DECODER_OUTPUT = 0x8000000, + D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_OUTPUT = 0x10000000, + D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_INPUT = 0x20000000, + D3D12_FORMAT_SUPPORT1_VIDEO_ENCODER = 0x40000000, +}} +FLAGS!{enum D3D12_FORMAT_SUPPORT2 { + D3D12_FORMAT_SUPPORT2_NONE = 0x0, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD = 0x1, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS = 0x2, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE = 0x4, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_EXCHANGE = 0x8, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX = 0x10, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX = 0x20, + D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD = 0x40, + D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE = 0x80, + D3D12_FORMAT_SUPPORT2_OUTPUT_MERGER_LOGIC_OP = 0x100, + D3D12_FORMAT_SUPPORT2_TILED = 0x200, + D3D12_FORMAT_SUPPORT2_MULTIPLANE_OVERLAY = 0x4000, +}} +FLAGS!{enum D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS { + D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE = 0x0, + D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE = 0x1, +}} +ENUM!{enum D3D12_CROSS_NODE_SHARING_TIER { + D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED = 0, + D3D12_CROSS_NODE_SHARING_TIER_1_EMULATED = 1, + D3D12_CROSS_NODE_SHARING_TIER_1 = 2, + D3D12_CROSS_NODE_SHARING_TIER_2 = 3, +}} +ENUM!{enum D3D12_RESOURCE_HEAP_TIER { + D3D12_RESOURCE_HEAP_TIER_1 = 1, + D3D12_RESOURCE_HEAP_TIER_2 = 2, +}} +STRUCT!{struct D3D12_FEATURE_DATA_D3D12_OPTIONS { + DoublePrecisionFloatShaderOps: ::BOOL, + OutputMergerLogicOp: ::BOOL, + MinPrecisionSupport: D3D12_SHADER_MIN_PRECISION_SUPPORT, + TiledResourcesTier: D3D12_TILED_RESOURCES_TIER, + ResourceBindingTier: D3D12_RESOURCE_BINDING_TIER, + PSSpecifiedStencilRefSupported: ::BOOL, + TypedUAVLoadAdditionalFormats: ::BOOL, + ROVsSupported: ::BOOL, + ConservativeRasterizationTier: D3D12_CONSERVATIVE_RASTERIZATION_TIER, + MaxGPUVirtualAddressBitsPerResource: ::UINT, + StandardSwizzle64KBSupported: ::BOOL, + CrossNodeSharingTier: D3D12_CROSS_NODE_SHARING_TIER, + CrossAdapterRowMajorTextureSupported: ::BOOL, + VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation: ::BOOL, + ResourceHeapTier: D3D12_RESOURCE_HEAP_TIER, +}} + + + + + + + + + +FLAGS!{ enum D3D12_BUFFER_SRV_FLAGS { + D3D12_BUFFER_SRV_FLAG_NONE = 0x0, + D3D12_BUFFER_SRV_FLAG_RAW = 0x1, +}} + +FLAGS!{ enum D3D12_BUFFER_UAV_FLAGS { + D3D12_BUFFER_UAV_FLAG_NONE = 0x0, + D3D12_BUFFER_UAV_FLAG_RAW = 0x1, +}} + +FLAGS!{ enum D3D12_CLEAR_FLAGS { + D3D12_CLEAR_FLAG_DEPTH = 0x1, + D3D12_CLEAR_FLAG_STENCIL = 0x2, +}} + + +ENUM!{ enum D3D12_CPU_PAGE_PROPERTY { + D3D12_CPU_PAGE_PROPERTY_UNKNOWN = 0, + D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE = 1, + D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE = 2, + D3D12_CPU_PAGE_PROPERTY_WRITE_BACK = 3, +}} + + +FLAGS!{ enum D3D12_DESCRIPTOR_HEAP_FLAGS { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE = 0x0, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE = 0x1, +}} + +ENUM!{ enum D3D12_DESCRIPTOR_HEAP_TYPE { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV = 0, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER = 1, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV = 2, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV = 3, + D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES = 4, +}} + +ENUM!{ enum D3D12_DESCRIPTOR_RANGE_TYPE { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0, + D3D12_DESCRIPTOR_RANGE_TYPE_UAV = 1, + D3D12_DESCRIPTOR_RANGE_TYPE_CBV = 2, + D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = 3, +}} + +ENUM!{ enum D3D12_DSV_DIMENSION { + D3D12_DSV_DIMENSION_UNKNOWN = 0, + D3D12_DSV_DIMENSION_TEXTURE1D = 1, + D3D12_DSV_DIMENSION_TEXTURE1DARRAY = 2, + D3D12_DSV_DIMENSION_TEXTURE2D = 3, + D3D12_DSV_DIMENSION_TEXTURE2DARRAY = 4, + D3D12_DSV_DIMENSION_TEXTURE2DMS = 5, + D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY = 6, +}} + +FLAGS!{ enum D3D12_DSV_FLAGS { + D3D12_DSV_FLAG_NONE = 0x0, + D3D12_DSV_FLAG_READ_ONLY_DEPTH = 0x1, + D3D12_DSV_FLAG_READ_ONLY_STENCIL = 0x2, +}} + + + +FLAGS!{ enum D3D12_FENCE_FLAGS { + D3D12_FENCE_FLAG_NONE = 0x0, + D3D12_FENCE_FLAG_SHARED = 0x1, + D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER = 0x2, +}} + + + +ENUM!{ enum D3D12_FILTER { + D3D12_FILTER_MIN_MAG_MIP_POINT = 0, + D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR = 1, + D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 4, + D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR = 5, + D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT = 16, + D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 17, + D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT = 20, + D3D12_FILTER_MIN_MAG_MIP_LINEAR = 21, + D3D12_FILTER_ANISOTROPIC = 85, + D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 128, + D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 129, + D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 132, + D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 133, + D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 144, + D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 145, + D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 148, + D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 149, + D3D12_FILTER_COMPARISON_ANISOTROPIC = 213, + D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 256, + D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 257, + D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 260, + D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 261, + D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 272, + D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 273, + D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 276, + D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 277, + D3D12_FILTER_MINIMUM_ANISOTROPIC = 341, + D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 384, + D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 385, + D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 388, + D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 389, + D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 400, + D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 401, + D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 404, + D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 405, + D3D12_FILTER_MAXIMUM_ANISOTROPIC = 469, +}} + +ENUM!{ enum D3D12_FILTER_REDUCTION_TYPE { + D3D12_FILTER_REDUCTION_TYPE_STANDARD = 0, + D3D12_FILTER_REDUCTION_TYPE_COMPARISON = 1, + D3D12_FILTER_REDUCTION_TYPE_MINIMUM = 2, + D3D12_FILTER_REDUCTION_TYPE_MAXIMUM = 3, +}} + +ENUM!{ enum D3D12_FILTER_TYPE { + D3D12_FILTER_TYPE_POINT = 0, + D3D12_FILTER_TYPE_LINEAR = 1, +}} + + + +FLAGS!{ enum D3D12_HEAP_FLAGS { + D3D12_HEAP_FLAG_NONE = 0x0, + D3D12_HEAP_FLAG_SHARED = 0x1, + D3D12_HEAP_FLAG_DENY_BUFFERS = 0x4, + D3D12_HEAP_FLAG_ALLOW_DISPLAY = 0x8, + D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER = 0x20, + D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES = 0x40, + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES = 0x80, + D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES = 0x0, + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS = 0xC0, + D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44, + D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES = 0x84, +}} + +ENUM!{ enum D3D12_HEAP_TYPE { + D3D12_HEAP_TYPE_DEFAULT = 1, + D3D12_HEAP_TYPE_UPLOAD = 2, + D3D12_HEAP_TYPE_READBACK = 3, + D3D12_HEAP_TYPE_CUSTOM = 4, +}} + + + +ENUM!{ enum D3D12_INDIRECT_ARGUMENT_TYPE { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW = 0, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED = 1, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH = 2, + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW = 3, + D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW = 4, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT = 5, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW = 6, + D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW = 7, + D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW = 8, +}} + + + + + +ENUM!{ enum D3D12_MEMORY_POOL { + D3D12_MEMORY_POOL_UNKNOWN = 0, + D3D12_MEMORY_POOL_L0 = 1, + D3D12_MEMORY_POOL_L1 = 2, +}} + + + + +ENUM!{ enum D3D12_PREDICATION_OP { + D3D12_PREDICATION_OP_EQUAL_ZERO = 0, + D3D12_PREDICATION_OP_NOT_EQUAL_ZERO = 1, +}} + + + +ENUM!{ enum D3D12_QUERY_HEAP_TYPE { + D3D12_QUERY_HEAP_TYPE_OCCLUSION = 0, + D3D12_QUERY_HEAP_TYPE_TIMESTAMP = 1, + D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS = 2, + D3D12_QUERY_HEAP_TYPE_SO_STATISTICS = 3, +}} + +ENUM!{ enum D3D12_QUERY_TYPE { + D3D12_QUERY_TYPE_OCCLUSION = 0, + D3D12_QUERY_TYPE_BINARY_OCCLUSION = 1, + D3D12_QUERY_TYPE_TIMESTAMP = 2, + D3D12_QUERY_TYPE_PIPELINE_STATISTICS = 3, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 = 4, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1 = 5, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2 = 6, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3 = 7, +}} + +FLAGS!{ enum D3D12_RESOURCE_BARRIER_FLAGS { + D3D12_RESOURCE_BARRIER_FLAG_NONE = 0x0, + D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY = 0x1, + D3D12_RESOURCE_BARRIER_FLAG_END_ONLY = 0x2, +}} + +ENUM!{ enum D3D12_RESOURCE_BARRIER_TYPE { + D3D12_RESOURCE_BARRIER_TYPE_TRANSITION = 0, + D3D12_RESOURCE_BARRIER_TYPE_ALIASING = 1, + D3D12_RESOURCE_BARRIER_TYPE_UAV = 2, +}} + + +ENUM!{ enum D3D12_RESOURCE_DIMENSION { + D3D12_RESOURCE_DIMENSION_UNKNOWN = 0, + D3D12_RESOURCE_DIMENSION_BUFFER = 1, + D3D12_RESOURCE_DIMENSION_TEXTURE1D = 2, + D3D12_RESOURCE_DIMENSION_TEXTURE2D = 3, + D3D12_RESOURCE_DIMENSION_TEXTURE3D = 4, +}} + +FLAGS!{ enum D3D12_RESOURCE_FLAGS { + D3D12_RESOURCE_FLAG_NONE = 0x0, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET = 0x1, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL = 0x2, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS = 0x4, + D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE = 0x8, + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER = 0x10, + D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS = 0x20, +}} + + +FLAGS!{ enum D3D12_RESOURCE_STATES { + D3D12_RESOURCE_STATE_COMMON = 0x0, + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER = 0x1, + D3D12_RESOURCE_STATE_INDEX_BUFFER = 0x2, + D3D12_RESOURCE_STATE_RENDER_TARGET = 0x4, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS = 0x8, + D3D12_RESOURCE_STATE_DEPTH_WRITE = 0x10, + D3D12_RESOURCE_STATE_DEPTH_READ = 0x20, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE = 0x40, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE = 0x80, + D3D12_RESOURCE_STATE_STREAM_OUT = 0x100, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT = 0x200, + D3D12_RESOURCE_STATE_COPY_DEST = 0x400, + D3D12_RESOURCE_STATE_COPY_SOURCE = 0x800, + D3D12_RESOURCE_STATE_RESOLVE_DEST = 0x1000, + D3D12_RESOURCE_STATE_RESOLVE_SOURCE = 0x2000, + D3D12_RESOURCE_STATE_GENERIC_READ = 0xAC3, + D3D12_RESOURCE_STATE_PRESENT = 0x0, + D3D12_RESOURCE_STATE_PREDICATION = 0x200, +}} + +ENUM!{ enum D3D12_ROOT_PARAMETER_TYPE { + D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0, + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS = 1, + D3D12_ROOT_PARAMETER_TYPE_CBV = 2, + D3D12_ROOT_PARAMETER_TYPE_SRV = 3, + D3D12_ROOT_PARAMETER_TYPE_UAV = 4, +}} + +FLAGS!{ enum D3D12_ROOT_SIGNATURE_FLAGS { + D3D12_ROOT_SIGNATURE_FLAG_NONE = 0x0, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1, + D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2, + D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS = 0x4, + D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8, + D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10, + D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT = 0x40, +}} + +ENUM!{ enum D3D12_RTV_DIMENSION { + D3D12_RTV_DIMENSION_UNKNOWN = 0, + D3D12_RTV_DIMENSION_BUFFER = 1, + D3D12_RTV_DIMENSION_TEXTURE1D = 2, + D3D12_RTV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_RTV_DIMENSION_TEXTURE2D = 4, + D3D12_RTV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_RTV_DIMENSION_TEXTURE2DMS = 6, + D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D12_RTV_DIMENSION_TEXTURE3D = 8, +}} + +ENUM!{ enum D3D12_SHADER_COMPONENT_MAPPING { + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_0 = 0, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1 = 1, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_2 = 2, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_3 = 3, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 = 4, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1 = 5, +}} + + +ENUM!{ enum D3D12_SHADER_VISIBILITY { + D3D12_SHADER_VISIBILITY_ALL = 0, + D3D12_SHADER_VISIBILITY_VERTEX = 1, + D3D12_SHADER_VISIBILITY_HULL = 2, + D3D12_SHADER_VISIBILITY_DOMAIN = 3, + D3D12_SHADER_VISIBILITY_GEOMETRY = 4, + D3D12_SHADER_VISIBILITY_PIXEL = 5, +}} + +ENUM!{ enum D3D12_SRV_DIMENSION { + D3D12_SRV_DIMENSION_UNKNOWN = 0, + D3D12_SRV_DIMENSION_BUFFER = 1, + D3D12_SRV_DIMENSION_TEXTURE1D = 2, + D3D12_SRV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_SRV_DIMENSION_TEXTURE2D = 4, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_SRV_DIMENSION_TEXTURE2DMS = 6, + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D12_SRV_DIMENSION_TEXTURE3D = 8, + D3D12_SRV_DIMENSION_TEXTURECUBE = 9, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY = 10, +}} + +ENUM!{ enum D3D12_STATIC_BORDER_COLOR { + D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK = 0, + D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK = 1, + D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE = 2, +}} + + + +ENUM!{ enum D3D12_TEXTURE_ADDRESS_MODE { + D3D12_TEXTURE_ADDRESS_MODE_WRAP = 1, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR = 2, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP = 3, + D3D12_TEXTURE_ADDRESS_MODE_BORDER = 4, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE = 5, +}} + +ENUM!{ enum D3D12_TEXTURE_COPY_TYPE { + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX = 0, + D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT = 1, +}} + +ENUM!{ enum D3D12_TEXTURE_LAYOUT { + D3D12_TEXTURE_LAYOUT_UNKNOWN = 0, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR = 1, + D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2, + D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3, +}} + + +FLAGS!{ enum D3D12_TILE_COPY_FLAGS { + D3D12_TILE_COPY_FLAG_NONE = 0x0, + D3D12_TILE_COPY_FLAG_NO_HAZARD = 0x1, + D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2, + D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4, +}} + +FLAGS!{ enum D3D12_TILE_MAPPING_FLAGS { + D3D12_TILE_MAPPING_FLAG_NONE = 0x0, + D3D12_TILE_MAPPING_FLAG_NO_HAZARD = 0x1, +}} + +FLAGS!{ enum D3D12_TILE_RANGE_FLAGS { + D3D12_TILE_RANGE_FLAG_NONE = 0x0, + D3D12_TILE_RANGE_FLAG_NULL = 0x1, + D3D12_TILE_RANGE_FLAG_SKIP = 0x2, + D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE = 0x4, +}} + +ENUM!{ enum D3D12_UAV_DIMENSION { + D3D12_UAV_DIMENSION_UNKNOWN = 0, + D3D12_UAV_DIMENSION_BUFFER = 1, + D3D12_UAV_DIMENSION_TEXTURE1D = 2, + D3D12_UAV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_UAV_DIMENSION_TEXTURE2D = 4, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_UAV_DIMENSION_TEXTURE3D = 8, +}} + +ENUM!{ enum D3D_ROOT_SIGNATURE_VERSION { + D3D_ROOT_SIGNATURE_VERSION_1 = 1, +}} + + + + + +STRUCT!{struct D3D12_BUFFER_RTV { + FirstElement: ::UINT64, + NumElements: ::UINT, +}} + +STRUCT!{struct D3D12_BUFFER_SRV { + FirstElement: ::UINT64, + NumElements: ::UINT, + StructureByteStride: ::UINT, + Flags: ::D3D12_BUFFER_SRV_FLAGS, +}} + +STRUCT!{struct D3D12_BUFFER_UAV { + FirstElement: ::UINT64, + NumElements: ::UINT, + StructureByteStride: ::UINT, + CounterOffsetInBytes: ::UINT64, + Flags: ::D3D12_BUFFER_UAV_FLAGS, +}} + + + +STRUCT!{struct D3D12_CLEAR_VALUE { + Format: ::DXGI_FORMAT, + u: [::FLOAT; 4], +}} + +UNION!(D3D12_CLEAR_VALUE, u, DepthStencil, DepthStencil_mut, ::D3D12_DEPTH_STENCIL_VALUE); +UNION!(D3D12_CLEAR_VALUE, u, Color, Color_mut, [::FLOAT; 4]); + + + +STRUCT!{struct D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: ::UINT, + NumArgumentDescs: ::UINT, + pArgumentDescs: *const ::D3D12_INDIRECT_ARGUMENT_DESC, + NodeMask: ::UINT, +}} + + + +STRUCT!{struct D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT, +}} + +STRUCT!{struct D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: ::SIZE_T, +}} + + + +STRUCT!{struct D3D12_DEPTH_STENCIL_VALUE { + Depth: ::FLOAT, + Stencil: ::UINT8, +}} + +STRUCT!{struct D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_DSV_DIMENSION, + Flags: ::D3D12_DSV_FLAGS, + u: ::D3D12_TEX1D_ARRAY_DSV, +}} + +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + ::D3D12_TEX2DMS_ARRAY_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, ::D3D12_TEX2DMS_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_DSV); + +STRUCT!{struct D3D12_DESCRIPTOR_HEAP_DESC { + Type: ::D3D12_DESCRIPTOR_HEAP_TYPE, + NumDescriptors: ::UINT, + Flags: ::D3D12_DESCRIPTOR_HEAP_FLAGS, + NodeMask: ::UINT, +}} + +STRUCT!{struct D3D12_DESCRIPTOR_RANGE { + RangeType: ::D3D12_DESCRIPTOR_RANGE_TYPE, + NumDescriptors: ::UINT, + BaseShaderRegister: ::UINT, + RegisterSpace: ::UINT, + OffsetInDescriptorsFromTableStart: ::UINT, +}} + +STRUCT!{struct D3D12_DISCARD_REGION { + NumRects: ::UINT, + pRects: *const ::D3D12_RECT, + FirstSubresource: ::UINT, + NumSubresources: ::UINT, +}} + +STRUCT!{struct D3D12_DISPATCH_ARGUMENTS { + ThreadGroupCountX: ::UINT, + ThreadGroupCountY: ::UINT, + ThreadGroupCountZ: ::UINT, +}} + +STRUCT!{struct D3D12_DRAW_ARGUMENTS { + VertexCountPerInstance: ::UINT, + InstanceCount: ::UINT, + StartVertexLocation: ::UINT, + StartInstanceLocation: ::UINT, +}} + +STRUCT!{struct D3D12_DRAW_INDEXED_ARGUMENTS { + IndexCountPerInstance: ::UINT, + InstanceCount: ::UINT, + StartIndexLocation: ::UINT, + BaseVertexLocation: ::INT, + StartInstanceLocation: ::UINT, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_ARCHITECTURE { + NodeIndex: ::UINT, + TileBasedRenderer: ::BOOL, + UMA: ::BOOL, + CacheCoherentUMA: ::BOOL, +}} + + +STRUCT!{struct D3D12_FEATURE_DATA_FEATURE_LEVELS { + NumFeatureLevels: ::UINT, + pFeatureLevelsRequested: *const ::D3D_FEATURE_LEVEL, + MaxSupportedFeatureLevel: ::D3D_FEATURE_LEVEL, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_FORMAT_INFO { + Format: ::DXGI_FORMAT, + PlaneCount: ::UINT8, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: ::DXGI_FORMAT, + Support1: ::D3D12_FORMAT_SUPPORT1, + Support2: ::D3D12_FORMAT_SUPPORT2, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT { + MaxGPUVirtualAddressBitsPerResource: ::UINT, + MaxGPUVirtualAddressBitsPerProcess: ::UINT, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS { + Format: ::DXGI_FORMAT, + SampleCount: ::UINT, + Flags: ::D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS, + NumQualityLevels: ::UINT, +}} + +STRUCT!{struct D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: ::UINT64, +}} + + + +STRUCT!{struct D3D12_HEAP_DESC { + SizeInBytes: ::UINT64, + Properties: ::D3D12_HEAP_PROPERTIES, + Alignment: ::UINT64, + Flags: ::D3D12_HEAP_FLAGS, +}} + +STRUCT!{struct D3D12_HEAP_PROPERTIES { + Type: ::D3D12_HEAP_TYPE, + CPUPageProperty: ::D3D12_CPU_PAGE_PROPERTY, + MemoryPoolPreference: ::D3D12_MEMORY_POOL, + CreationNodeMask: ::UINT, + VisibleNodeMask: ::UINT, +}} + +STRUCT!{struct D3D12_INDEX_BUFFER_VIEW { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT, + Format: ::DXGI_FORMAT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer { + Slot: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_Constant { + RootParameterIndex: ::UINT, + DestOffsetIn32BitValues: ::UINT, + Num32BitValuesToSet: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_ConstantBufferView { + RootParameterIndex: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_ShaderResourceView { + RootParameterIndex: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_UnorderedAccessView { + RootParameterIndex: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC { + Type: ::D3D12_INDIRECT_ARGUMENT_TYPE, + u: ::D3D12_INDIRECT_ARGUMENT_DESC_Constant, +}} + +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, UnorderedAccessView, UnorderedAccessView_mut, + D3D12_INDIRECT_ARGUMENT_DESC_UnorderedAccessView); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, ShaderResourceView, ShaderResourceView_mut, + D3D12_INDIRECT_ARGUMENT_DESC_ShaderResourceView); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, ConstantBufferView, ConstantBufferView_mut, + D3D12_INDIRECT_ARGUMENT_DESC_ConstantBufferView); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, Constant, Constant_mut, + D3D12_INDIRECT_ARGUMENT_DESC_Constant); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, VertexBuffer, VertexBuffer_mut, + D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer); + + + + +STRUCT!{struct D3D12_MEMCPY_DEST { + pData: *mut ::c_void, + RowPitch: ::SIZE_T, + SlicePitch: ::SIZE_T, +}} + +STRUCT!{struct D3D12_PACKED_MIP_INFO { + NumStandardMips: ::UINT8, + NumPackedMips: ::UINT8, + NumTilesForPackedMips: ::UINT, + StartTileIndexInOverallResource: ::UINT, +}} + +STRUCT!{struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: ::UINT64, + Footprint: ::D3D12_SUBRESOURCE_FOOTPRINT, +}} + +STRUCT!{struct D3D12_QUERY_DATA_PIPELINE_STATISTICS { + IAVertices: ::UINT64, + IAPrimitives: ::UINT64, + VSInvocations: ::UINT64, + GSInvocations: ::UINT64, + GSPrimitives: ::UINT64, + CInvocations: ::UINT64, + CPrimitives: ::UINT64, + PSInvocations: ::UINT64, + HSInvocations: ::UINT64, + DSInvocations: ::UINT64, + CSInvocations: ::UINT64, +}} + +STRUCT!{struct D3D12_QUERY_DATA_SO_STATISTICS { + NumPrimitivesWritten: ::UINT64, + PrimitivesStorageNeeded: ::UINT64, +}} + +STRUCT!{struct D3D12_QUERY_HEAP_DESC { + Type: ::D3D12_QUERY_HEAP_TYPE, + Count: ::UINT, + NodeMask: ::UINT, +}} + +STRUCT!{struct D3D12_RANGE { + Begin: ::SIZE_T, + End: ::SIZE_T, +}} + + + +STRUCT!{struct D3D12_RENDER_TARGET_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_RTV_DIMENSION, + u: ::D3D12_BUFFER_RTV, +}} + +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture3D, Texture3D_mut, ::D3D12_TEX3D_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + ::D3D12_TEX2DMS_ARRAY_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, ::D3D12_TEX2DMS_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Buffer, Buffer_mut, ::D3D12_BUFFER_RTV); + +STRUCT!{struct D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: *mut ::ID3D12Resource, + pResourceAfter: *mut ::ID3D12Resource, +}} + +STRUCT!{struct D3D12_RESOURCE_ALLOCATION_INFO { + SizeInBytes: ::UINT64, + Alignment: ::UINT64, +}} + +STRUCT!{struct D3D12_RESOURCE_BARRIER { + Type: ::D3D12_RESOURCE_BARRIER_TYPE, + Flags: ::D3D12_RESOURCE_BARRIER_FLAGS, + u: ::D3D12_RESOURCE_TRANSITION_BARRIER, +}} + +UNION!(D3D12_RESOURCE_BARRIER, u, UAV, UAV_mut, ::D3D12_RESOURCE_UAV_BARRIER); +UNION!(D3D12_RESOURCE_BARRIER, u, Aliasing, Aliasing_mut, ::D3D12_RESOURCE_ALIASING_BARRIER); +UNION!(D3D12_RESOURCE_BARRIER, u, Transition, Transition_mut, ::D3D12_RESOURCE_TRANSITION_BARRIER); + +STRUCT!{struct D3D12_RESOURCE_DESC { + Dimension: ::D3D12_RESOURCE_DIMENSION, + Alignment: ::UINT64, + Width: ::UINT64, + Height: ::UINT, + DepthOrArraySize: ::UINT16, + MipLevels: ::UINT16, + Format: ::DXGI_FORMAT, + SampleDesc: ::DXGI_SAMPLE_DESC, + Layout: ::D3D12_TEXTURE_LAYOUT, + Flags: ::D3D12_RESOURCE_FLAGS, +}} + +STRUCT!{struct D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: *mut ::ID3D12Resource, + Subresource: ::UINT, + StateBefore: ::D3D12_RESOURCE_STATES, + StateAfter: ::D3D12_RESOURCE_STATES, +}} + +STRUCT!{struct D3D12_RESOURCE_UAV_BARRIER { + pResource: *mut ::ID3D12Resource, +}} + +STRUCT!{struct D3D12_ROOT_CONSTANTS { + ShaderRegister: ::UINT, + RegisterSpace: ::UINT, + Num32BitValues: ::UINT, +}} + +STRUCT!{struct D3D12_ROOT_DESCRIPTOR { + ShaderRegister: ::UINT, + RegisterSpace: ::UINT, +}} + +STRUCT!{struct D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: ::UINT, + pDescriptorRanges: *const ::D3D12_DESCRIPTOR_RANGE, +}} + +#[cfg(target_pointer_width = "64")] +STRUCT!{struct D3D12_ROOT_PARAMETER { + ParameterType: ::D3D12_ROOT_PARAMETER_TYPE, + u: ::D3D12_ROOT_DESCRIPTOR_TABLE, + ShaderVisibility: ::D3D12_SHADER_VISIBILITY, +}} + +#[cfg(target_pointer_width = "32")] +STRUCT!{struct D3D12_ROOT_PARAMETER { + ParameterType: ::D3D12_ROOT_PARAMETER_TYPE, + u: ::D3D12_ROOT_CONSTANTS, + ShaderVisibility: ::D3D12_SHADER_VISIBILITY, +}} + +UNION!(D3D12_ROOT_PARAMETER, u, Descriptor, Descriptor_mut, ::D3D12_ROOT_DESCRIPTOR); +UNION!(D3D12_ROOT_PARAMETER, u, Constants, Constants_mut, ::D3D12_ROOT_CONSTANTS); +UNION!(D3D12_ROOT_PARAMETER, u, DescriptorTable, DescriptorTable_mut, + ::D3D12_ROOT_DESCRIPTOR_TABLE); + +STRUCT!{struct D3D12_ROOT_SIGNATURE_DESC { + NumParameters: ::UINT, + pParameters: *const ::D3D12_ROOT_PARAMETER, + NumStaticSamplers: ::UINT, + pStaticSamplers: *const ::D3D12_STATIC_SAMPLER_DESC, + Flags: ::D3D12_ROOT_SIGNATURE_FLAGS, +}} + +STRUCT!{struct D3D12_SAMPLER_DESC { + Filter: ::D3D12_FILTER, + AddressU: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressV: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressW: ::D3D12_TEXTURE_ADDRESS_MODE, + MipLODBias: ::FLOAT, + MaxAnisotropy: ::UINT, + ComparisonFunc: ::D3D12_COMPARISON_FUNC, + BorderColor: [::FLOAT; 4], + MinLOD: ::FLOAT, + MaxLOD: ::FLOAT, +}} + + + +STRUCT!{struct D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_SRV_DIMENSION, + Shader4ComponentMapping: ::UINT, + u: ::D3D12_BUFFER_SRV, +}} + +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, TextureCubeArray, TextureCubeArray_mut, + ::D3D12_TEXCUBE_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, TextureCube, TextureCube_mut, ::D3D12_TEXCUBE_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture3D, Texture3D_mut, ::D3D12_TEX3D_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + ::D3D12_TEX2DMS_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, ::D3D12_TEX2DMS_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Buffer, Buffer_mut, ::D3D12_BUFFER_SRV); + + + +STRUCT!{struct D3D12_STATIC_SAMPLER_DESC { + Filter: ::D3D12_FILTER, + AddressU: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressV: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressW: ::D3D12_TEXTURE_ADDRESS_MODE, + MipLODBias: ::FLOAT, + MaxAnisotropy: ::UINT, + ComparisonFunc: ::D3D12_COMPARISON_FUNC, + BorderColor: ::D3D12_STATIC_BORDER_COLOR, + MinLOD: ::FLOAT, + MaxLOD: ::FLOAT, + ShaderRegister: ::UINT, + RegisterSpace: ::UINT, + ShaderVisibility: ::D3D12_SHADER_VISIBILITY, +}} + +STRUCT!{struct D3D12_STREAM_OUTPUT_BUFFER_VIEW { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT64, + BufferFilledSizeLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, +}} + + + +STRUCT!{struct D3D12_SUBRESOURCE_DATA { + pData: *const ::c_void, + RowPitch: ::LONG_PTR, + SlicePitch: ::LONG_PTR, +}} + +STRUCT!{struct D3D12_SUBRESOURCE_FOOTPRINT { + Format: ::DXGI_FORMAT, + Width: ::UINT, + Height: ::UINT, + Depth: ::UINT, + RowPitch: ::UINT, +}} + +STRUCT!{struct D3D12_SUBRESOURCE_INFO { + Offset: ::UINT64, + RowPitch: ::UINT, + DepthPitch: ::UINT, +}} + +STRUCT!{struct D3D12_SUBRESOURCE_TILING { + WidthInTiles: ::UINT, + HeightInTiles: ::UINT16, + DepthInTiles: ::UINT16, + StartTileIndexInOverallResource: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_DSV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_RTV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_UAV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_DSV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_RTV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX1D_UAV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_ARRAY_DSV { + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_ARRAY_RTV { + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_ARRAY_SRV { + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_DSV { + UnusedField_NothingToDefine: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_RTV { + UnusedField_NothingToDefine: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_SRV { + UnusedField_NothingToDefine: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_DSV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_RTV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + PlaneSlice: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_UAV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_DSV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_RTV { + MipSlice: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + PlaneSlice: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX2D_UAV { + MipSlice: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX3D_RTV { + MipSlice: ::UINT, + FirstWSlice: ::UINT, + WSize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX3D_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX3D_UAV { + MipSlice: ::UINT, + FirstWSlice: ::UINT, + WSize: ::UINT, +}} + +STRUCT!{struct D3D12_TEXCUBE_ARRAY_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + First2DArrayFace: ::UINT, + NumCubes: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEXCUBE_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEXTURE_COPY_LOCATION { + pResource: *mut ::ID3D12Resource, + Type: ::D3D12_TEXTURE_COPY_TYPE, + u: ::D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +}} + +UNION!(D3D12_TEXTURE_COPY_LOCATION, u, SubresourceIndex, SubresourceIndex_mut, ::UINT); +UNION!(D3D12_TEXTURE_COPY_LOCATION, u, PlacedFootprint, PlacedFootprint_mut, + ::D3D12_PLACED_SUBRESOURCE_FOOTPRINT); + +STRUCT!{struct D3D12_TILED_RESOURCE_COORDINATE { + X: ::UINT, + Y: ::UINT, + Z: ::UINT, + Subresource: ::UINT, +}} + +STRUCT!{struct D3D12_TILE_REGION_SIZE { + NumTiles: ::UINT, + UseBox: ::BOOL, + Width: ::UINT, + Height: ::UINT16, + Depth: ::UINT16, +}} + +STRUCT!{struct D3D12_TILE_SHAPE { + WidthInTexels: ::UINT, + HeightInTexels: ::UINT, + DepthInTexels: ::UINT, +}} + +STRUCT!{struct D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_UAV_DIMENSION, + u: ::D3D12_BUFFER_UAV, +}} + +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture3D, Texture3D_mut, ::D3D12_TEX3D_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Buffer, Buffer_mut, ::D3D12_BUFFER_UAV); + +STRUCT!{struct D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT, + StrideInBytes: ::UINT, +}} + + + +RIDL!( +interface ID3D12CommandAllocator(ID3D12CommandAllocatorVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn Reset(&mut self) -> ::HRESULT +}); + +RIDL!( +interface ID3D12CommandList(ID3D12CommandListVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) { + fn GetType(&mut self) -> ::D3D12_COMMAND_LIST_TYPE +}); + +RIDL!( +interface ID3D12CommandQueue(ID3D12CommandQueueVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn UpdateTileMappings( + &mut self, pResource: *mut ::ID3D12Resource, NumResourceRegions: ::UINT, + pResourceRegionStartCoordinates: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pResourceRegionSizes: *const ::D3D12_TILE_REGION_SIZE, pHeap: *mut ::ID3D12Heap, + NumRanges: ::UINT, pRangeFlags: *const ::D3D12_TILE_RANGE_FLAGS, + pHeapRangeStartOffsets: *const ::UINT, pRangeTileCounts: *const ::UINT, + Flags: ::D3D12_TILE_MAPPING_FLAGS + ) -> (), + fn CopyTileMappings( + &mut self, pDstResource: *mut ::ID3D12Resource, + pDstRegionStartCoordinate: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pSrcResource: *mut ::ID3D12Resource, + pSrcRegionStartCoordinate: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pRegionSize: *const ::D3D12_TILE_REGION_SIZE, Flags: ::D3D12_TILE_MAPPING_FLAGS + ) -> (), + fn ExecuteCommandLists( + &mut self, NumCommandLists: ::UINT, ppCommandLists: *mut *mut ::ID3D12CommandList + ) -> (), + fn SetMarker( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn BeginEvent( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn EndEvent(&mut self) -> (), + fn Signal( + &mut self, pFence: *mut ::ID3D12Fence, Value: ::UINT64 + ) -> ::HRESULT, + fn Wait( + &mut self, pFence: *mut ::ID3D12Fence, Value: ::UINT64 + ) -> ::HRESULT, + fn GetTimestampFrequency(&mut self, pFrequency: *mut ::UINT64) -> ::HRESULT, + fn GetClockCalibration( + &mut self, pGpuTimestamp: *mut ::UINT64, pCpuTimestamp: *mut ::UINT64 + ) -> ::HRESULT, + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_COMMAND_QUEUE_DESC + ) -> *mut ::D3D12_COMMAND_QUEUE_DESC +}); + +RIDL!( +interface ID3D12CommandSignature(ID3D12CommandSignatureVtbl): ID3D12Pageable(ID3D12PageableVtbl) { +}); + +RIDL!( +interface ID3D12DescriptorHeap(ID3D12DescriptorHeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_DESCRIPTOR_HEAP_DESC + ) -> *mut ::D3D12_DESCRIPTOR_HEAP_DESC, + fn GetCPUDescriptorHandleForHeapStart( + &mut self, __ret_val: *mut ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> *mut ::D3D12_CPU_DESCRIPTOR_HANDLE, + fn GetGPUDescriptorHandleForHeapStart( + &mut self, __ret_val: *mut ::D3D12_GPU_DESCRIPTOR_HANDLE + ) -> *mut ::D3D12_GPU_DESCRIPTOR_HANDLE +}); + + + +RIDL!( +interface ID3D12Device(ID3D12DeviceVtbl): ID3D12Object(ID3D12ObjectVtbl) { + fn GetNodeCount(&mut self) -> ::UINT, + fn CreateCommandQueue( + &mut self, pDesc: *const ::D3D12_COMMAND_QUEUE_DESC, riid: ::REFGUID, + ppCommandQueue: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateCommandAllocator( + &mut self, type_: ::D3D12_COMMAND_LIST_TYPE, riid: ::REFGUID, + ppCommandAllocator: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateGraphicsPipelineState( + &mut self, pDesc: *const ::D3D12_GRAPHICS_PIPELINE_STATE_DESC, riid: ::REFGUID, + ppPipelineState: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateComputePipelineState( + &mut self, pDesc: *const ::D3D12_COMPUTE_PIPELINE_STATE_DESC, riid: ::REFGUID, + ppPipelineState: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateCommandList( + &mut self, nodeMask: ::UINT, type_: ::D3D12_COMMAND_LIST_TYPE, + pCommandAllocator: *mut ::ID3D12CommandAllocator, + pInitialState: *mut ::ID3D12PipelineState, riid: ::REFGUID, + ppCommandList: *mut *mut ::c_void + ) -> ::HRESULT, + fn CheckFeatureSupport( + &mut self, Feature: ::D3D12_FEATURE, pFeatureSupportData: *mut ::c_void, + FeatureSupportDataSize: ::UINT + ) -> ::HRESULT, + fn CreateDescriptorHeap( + &mut self, pDescriptorHeapDesc: *const ::D3D12_DESCRIPTOR_HEAP_DESC, riid: ::REFGUID, + ppvHeap: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetDescriptorHandleIncrementSize( + &mut self, DescriptorHeapType: ::D3D12_DESCRIPTOR_HEAP_TYPE + ) -> ::UINT, + fn CreateRootSignature( + &mut self, nodeMask: ::UINT, pBlobWithRootSignature: *const ::c_void, + blobLengthInBytes: ::SIZE_T, riid: ::REFGUID, ppvRootSignature: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateConstantBufferView( + &mut self, pDesc: *const ::D3D12_CONSTANT_BUFFER_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateShaderResourceView( + &mut self, pResource: *mut ::ID3D12Resource, + pDesc: *const ::D3D12_SHADER_RESOURCE_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateUnorderedAccessView( + &mut self, pResource: *mut ::ID3D12Resource, pCounterResource: *mut ::ID3D12Resource, + pDesc: *const ::D3D12_UNORDERED_ACCESS_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateRenderTargetView( + &mut self, pResource: *mut ::ID3D12Resource, pDesc: *const ::D3D12_RENDER_TARGET_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateDepthStencilView( + &mut self, pResource: *mut ::ID3D12Resource, pDesc: *const ::D3D12_DEPTH_STENCIL_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateSampler( + &mut self, pDesc: *const ::D3D12_SAMPLER_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CopyDescriptors( + &mut self, NumDestDescriptorRanges: ::UINT, + pDestDescriptorRangeStarts: *const ::D3D12_CPU_DESCRIPTOR_HANDLE, + pDestDescriptorRangeSizes: *const ::UINT, NumSrcDescriptorRanges: ::UINT, + pSrcDescriptorRangeStarts: *const ::D3D12_CPU_DESCRIPTOR_HANDLE, + pSrcDescriptorRangeSizes: *const ::UINT, DescriptorHeapsType: ::D3D12_DESCRIPTOR_HEAP_TYPE + ) -> (), + fn CopyDescriptorsSimple( + &mut self, NumDescriptors: ::UINT, DestDescriptorRangeStart: ::D3D12_CPU_DESCRIPTOR_HANDLE, + SrcDescriptorRangeStart: ::D3D12_CPU_DESCRIPTOR_HANDLE, + DescriptorHeapsType: ::D3D12_DESCRIPTOR_HEAP_TYPE + ) -> (), + fn GetResourceAllocationInfo( + &mut self, visibleMask: ::UINT, numResourceDescs: ::UINT, + pResourceDescs: *const ::D3D12_RESOURCE_DESC, + __ret_val: *mut ::D3D12_RESOURCE_ALLOCATION_INFO + ) -> *mut ::D3D12_RESOURCE_ALLOCATION_INFO, + fn GetCustomHeapProperties( + &mut self, nodeMask: ::UINT, heapType: ::D3D12_HEAP_TYPE, + __ret_val: *mut ::D3D12_HEAP_PROPERTIES + ) -> *mut ::D3D12_HEAP_PROPERTIES, + fn CreateCommittedResource( + &mut self, pHeapProperties: *const ::D3D12_HEAP_PROPERTIES, HeapFlags: ::D3D12_HEAP_FLAGS, + pResourceDesc: *const ::D3D12_RESOURCE_DESC, InitialResourceState: ::D3D12_RESOURCE_STATES, + pOptimizedClearValue: *const ::D3D12_CLEAR_VALUE, riidResource: ::REFGUID, + ppvResource: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateHeap( + &mut self, pDesc: *const ::D3D12_HEAP_DESC, riid: ::REFGUID, ppvHeap: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreatePlacedResource( + &mut self, pHeap: *mut ::ID3D12Heap, HeapOffset: ::UINT64, + pDesc: *const ::D3D12_RESOURCE_DESC, InitialState: ::D3D12_RESOURCE_STATES, + pOptimizedClearValue: *const ::D3D12_CLEAR_VALUE, riid: ::REFGUID, + ppvResource: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateReservedResource( + &mut self, pDesc: *const ::D3D12_RESOURCE_DESC, InitialState: ::D3D12_RESOURCE_STATES, + pOptimizedClearValue: *const ::D3D12_CLEAR_VALUE, riid: ::REFGUID, + ppvResource: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateSharedHandle( + &mut self, pObject: *mut ::ID3D12DeviceChild, pAttributes: *const ::SECURITY_ATTRIBUTES, + Access: ::DWORD, Name: ::LPCWSTR, pHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn OpenSharedHandle( + &mut self, NTHandle: ::HANDLE, riid: ::REFGUID, ppvObj: *mut *mut ::c_void + ) -> ::HRESULT, + fn OpenSharedHandleByName( + &mut self, Name: ::LPCWSTR, Access: ::DWORD, pNTHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn MakeResident( + &mut self, NumObjects: ::UINT, ppObjects: *mut *mut ::ID3D12Pageable + ) -> ::HRESULT, + fn Evict( + &mut self, NumObjects: ::UINT, ppObjects: *mut *mut ::ID3D12Pageable + ) -> ::HRESULT, + fn CreateFence( + &mut self, InitialValue: ::UINT64, Flags: ::D3D12_FENCE_FLAGS, riid: ::REFGUID, + ppFence: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetDeviceRemovedReason(&mut self) -> ::HRESULT, + fn GetCopyableFootprints( + &mut self, pResourceDesc: *const ::D3D12_RESOURCE_DESC, FirstSubresource: ::UINT, + NumSubresources: ::UINT, BaseOffset: ::UINT64, + pLayouts: *mut ::D3D12_PLACED_SUBRESOURCE_FOOTPRINT, pNumRows: *mut ::UINT, + pRowSizeInBytes: *mut ::UINT64, pTotalBytes: *mut ::UINT64 + ) -> (), + fn CreateQueryHeap( + &mut self, pDesc: *const ::D3D12_QUERY_HEAP_DESC, riid: ::REFGUID, + ppvHeap: *mut *mut ::c_void + ) -> ::HRESULT, + fn SetStablePowerState(&mut self, Enable: ::BOOL) -> ::HRESULT, + fn CreateCommandSignature( + &mut self, pDesc: *const ::D3D12_COMMAND_SIGNATURE_DESC, + pRootSignature: *mut ::ID3D12RootSignature, riid: ::REFGUID, + ppvCommandSignature: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetResourceTiling( + &mut self, pTiledResource: *mut ::ID3D12Resource, pNumTilesForEntireResource: *mut ::UINT, + pPackedMipDesc: *mut ::D3D12_PACKED_MIP_INFO, + pStandardTileShapeForNonPackedMips: *mut ::D3D12_TILE_SHAPE, + pNumSubresourceTilings: *mut ::UINT, FirstSubresourceTilingToGet: ::UINT, + pSubresourceTilingsForNonPackedMips: *mut ::D3D12_SUBRESOURCE_TILING + ) -> (), + fn GetAdapterLuid(&mut self, __ret_val: *mut ::LUID) -> *mut ::LUID +}); + +RIDL!( +interface ID3D12Fence(ID3D12FenceVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetCompletedValue(&mut self) -> ::UINT64, + fn SetEventOnCompletion( + &mut self, Value: ::UINT64, hEvent: ::HANDLE + ) -> ::HRESULT, + fn Signal(&mut self, Value: ::UINT64) -> ::HRESULT +}); + +RIDL!( +interface ID3D12GraphicsCommandList(ID3D12GraphicsCommandListVtbl): ID3D12CommandList(ID3D12CommandListVtbl) { + fn Close(&mut self) -> ::HRESULT, + fn Reset( + &mut self, pAllocator: *mut ::ID3D12CommandAllocator, + pInitialState: *mut ::ID3D12PipelineState + ) -> ::HRESULT, + fn ClearState(&mut self, pPipelineState: *mut ::ID3D12PipelineState) -> (), + fn DrawInstanced( + &mut self, VertexCountPerInstance: ::UINT, InstanceCount: ::UINT, + StartVertexLocation: ::UINT, StartInstanceLocation: ::UINT + ) -> (), + fn DrawIndexedInstanced( + &mut self, IndexCountPerInstance: ::UINT, InstanceCount: ::UINT, + StartIndexLocation: ::UINT, BaseVertexLocation: ::INT, StartInstanceLocation: ::UINT + ) -> (), + fn Dispatch( + &mut self, ThreadGroupCountX: ::UINT, ThreadGroupCountY: ::UINT, ThreadGroupCountZ: ::UINT + ) -> (), + fn CopyBufferRegion( + &mut self, pDstBuffer: *mut ::ID3D12Resource, DstOffset: ::UINT64, + pSrcBuffer: *mut ::ID3D12Resource, SrcOffset: ::UINT64, NumBytes: ::UINT64 + ) -> (), + fn CopyTextureRegion( + &mut self, pDst: *const ::D3D12_TEXTURE_COPY_LOCATION, DstX: ::UINT, DstY: ::UINT, + DstZ: ::UINT, pSrc: *const ::D3D12_TEXTURE_COPY_LOCATION, pSrcBox: *const ::D3D12_BOX + ) -> (), + fn CopyResource( + &mut self, pDstResource: *mut ::ID3D12Resource, pSrcResource: *mut ::ID3D12Resource + ) -> (), + fn CopyTiles( + &mut self, pTiledResource: *mut ::ID3D12Resource, + pTileRegionStartCoordinate: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pTileRegionSize: *const ::D3D12_TILE_REGION_SIZE, pBuffer: *mut ::ID3D12Resource, + BufferStartOffsetInBytes: ::UINT64, Flags: ::D3D12_TILE_COPY_FLAGS + ) -> (), + fn ResolveSubresource( + &mut self, pDstResource: *mut ::ID3D12Resource, DstSubresource: ::UINT, + pSrcResource: *mut ::ID3D12Resource, SrcSubresource: ::UINT, Format: ::DXGI_FORMAT + ) -> (), + fn IASetPrimitiveTopology( + &mut self, PrimitiveTopology: ::D3D12_PRIMITIVE_TOPOLOGY + ) -> (), + fn RSSetViewports( + &mut self, NumViewports: ::UINT, pViewports: *const ::D3D12_VIEWPORT + ) -> (), + fn RSSetScissorRects( + &mut self, NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn OMSetBlendFactor(&mut self, BlendFactor: *const [::FLOAT; 4]) -> (), + fn OMSetStencilRef(&mut self, StencilRef: ::UINT) -> (), + fn SetPipelineState( + &mut self, pPipelineState: *mut ::ID3D12PipelineState + ) -> (), + fn ResourceBarrier( + &mut self, NumBarriers: ::UINT, pBarriers: *const ::D3D12_RESOURCE_BARRIER + ) -> (), + fn ExecuteBundle( + &mut self, pCommandList: *mut ::ID3D12GraphicsCommandList + ) -> (), + fn SetDescriptorHeaps( + &mut self, NumDescriptorHeaps: ::UINT, ppDescriptorHeaps: *mut *mut ::ID3D12DescriptorHeap + ) -> (), + fn SetComputeRootSignature( + &mut self, pRootSignature: *mut ::ID3D12RootSignature + ) -> (), + fn SetGraphicsRootSignature( + &mut self, pRootSignature: *mut ::ID3D12RootSignature + ) -> (), + fn SetComputeRootDescriptorTable( + &mut self, RootParameterIndex: ::UINT, BaseDescriptor: ::D3D12_GPU_DESCRIPTOR_HANDLE + ) -> (), + fn SetGraphicsRootDescriptorTable( + &mut self, RootParameterIndex: ::UINT, BaseDescriptor: ::D3D12_GPU_DESCRIPTOR_HANDLE + ) -> (), + fn SetComputeRoot32BitConstant( + &mut self, RootParameterIndex: ::UINT, SrcData: ::UINT, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetGraphicsRoot32BitConstant( + &mut self, RootParameterIndex: ::UINT, SrcData: ::UINT, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetComputeRoot32BitConstants( + &mut self, RootParameterIndex: ::UINT, Num32BitValuesToSet: ::UINT, + pSrcData: *const ::c_void, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetGraphicsRoot32BitConstants( + &mut self, RootParameterIndex: ::UINT, Num32BitValuesToSet: ::UINT, + pSrcData: *const ::c_void, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetComputeRootConstantBufferView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetGraphicsRootConstantBufferView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetComputeRootShaderResourceView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetGraphicsRootShaderResourceView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetComputeRootUnorderedAccessView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetGraphicsRootUnorderedAccessView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn IASetIndexBuffer( + &mut self, pView: *const ::D3D12_INDEX_BUFFER_VIEW + ) -> (), + fn IASetVertexBuffers( + &mut self, StartSlot: ::UINT, NumViews: ::UINT, pViews: *const ::D3D12_VERTEX_BUFFER_VIEW + ) -> (), + fn SOSetTargets( + &mut self, StartSlot: ::UINT, NumViews: ::UINT, + pViews: *const ::D3D12_STREAM_OUTPUT_BUFFER_VIEW + ) -> (), + fn OMSetRenderTargets( + &mut self, NumRenderTargetDescriptors: ::UINT, + pRenderTargetDescriptors: *const ::D3D12_CPU_DESCRIPTOR_HANDLE, + RTsSingleHandleToDescriptorRange: ::BOOL, + pDepthStencilDescriptor: *const ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn ClearDepthStencilView( + &mut self, DepthStencilView: ::D3D12_CPU_DESCRIPTOR_HANDLE, + ClearFlags: ::D3D12_CLEAR_FLAGS, Depth: ::FLOAT, Stencil: ::UINT8, NumRects: ::UINT, + pRects: *const ::D3D12_RECT + ) -> (), + fn ClearRenderTargetView( + &mut self, RenderTargetView: ::D3D12_CPU_DESCRIPTOR_HANDLE, ColorRGBA: *const [::FLOAT; 4], + NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn ClearUnorderedAccessViewUint( + &mut self, ViewGPUHandleInCurrentHeap: ::D3D12_GPU_DESCRIPTOR_HANDLE, + ViewCPUHandle: ::D3D12_CPU_DESCRIPTOR_HANDLE, pResource: *mut ::ID3D12Resource, + Values: *const [::UINT; 4], NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn ClearUnorderedAccessViewFloat( + &mut self, ViewGPUHandleInCurrentHeap: ::D3D12_GPU_DESCRIPTOR_HANDLE, + ViewCPUHandle: ::D3D12_CPU_DESCRIPTOR_HANDLE, pResource: *mut ::ID3D12Resource, + Values: *const [::FLOAT; 4], NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn DiscardResource( + &mut self, pResource: *mut ::ID3D12Resource, pRegion: *const ::D3D12_DISCARD_REGION + ) -> (), + fn BeginQuery( + &mut self, pQueryHeap: *mut ::ID3D12QueryHeap, Type: ::D3D12_QUERY_TYPE, Index: ::UINT + ) -> (), + fn EndQuery( + &mut self, pQueryHeap: *mut ::ID3D12QueryHeap, Type: ::D3D12_QUERY_TYPE, Index: ::UINT + ) -> (), + fn ResolveQueryData( + &mut self, pQueryHeap: *mut ::ID3D12QueryHeap, Type: ::D3D12_QUERY_TYPE, + StartIndex: ::UINT, NumQueries: ::UINT, pDestinationBuffer: *mut ::ID3D12Resource, + AlignedDestinationBufferOffset: ::UINT64 + ) -> (), + fn SetPredication( + &mut self, pBuffer: *mut ::ID3D12Resource, AlignedBufferOffset: ::UINT64, + Operation: ::D3D12_PREDICATION_OP + ) -> (), + fn SetMarker( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn BeginEvent( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn EndEvent(&mut self) -> (), + fn ExecuteIndirect( + &mut self, pCommandSignature: *mut ::ID3D12CommandSignature, MaxCommandCount: ::UINT, + pArgumentBuffer: *mut ::ID3D12Resource, ArgumentBufferOffset: ::UINT64, + pCountBuffer: *mut ::ID3D12Resource, CountBufferOffset: ::UINT64 + ) -> () +}); + +RIDL!( +interface ID3D12Heap(ID3D12HeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_HEAP_DESC + ) -> *mut ::D3D12_HEAP_DESC +}); + + + +RIDL!( +interface ID3D12Pageable(ID3D12PageableVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) { +}); + +RIDL!( +interface ID3D12PipelineState(ID3D12PipelineStateVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetCachedBlob(&mut self, ppBlob: *mut *mut ::ID3DBlob) -> ::HRESULT +}); + +RIDL!( +interface ID3D12QueryHeap(ID3D12QueryHeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) { +}); + +RIDL!( +interface ID3D12Resource(ID3D12ResourceVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn Map( + &mut self, Subresource: ::UINT, pReadRange: *const ::D3D12_RANGE, + ppData: *mut *mut ::c_void + ) -> ::HRESULT, + fn Unmap( + &mut self, Subresource: ::UINT, pWrittenRange: *const ::D3D12_RANGE + ) -> (), + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_RESOURCE_DESC + ) -> *mut ::D3D12_RESOURCE_DESC, + fn GetGPUVirtualAddress(&mut self) -> ::D3D12_GPU_VIRTUAL_ADDRESS, + fn WriteToSubresource( + &mut self, DstSubresource: ::UINT, pDstBox: *const ::D3D12_BOX, pSrcData: *const ::c_void, + SrcRowPitch: ::UINT, SrcDepthPitch: ::UINT + ) -> ::HRESULT, + fn ReadFromSubresource( + &mut self, pDstData: *mut ::c_void, DstRowPitch: ::UINT, DstDepthPitch: ::UINT, + SrcSubresource: ::UINT, pSrcBox: *const ::D3D12_BOX + ) -> ::HRESULT, + fn GetHeapProperties( + &mut self, pHeapProperties: *mut ::D3D12_HEAP_PROPERTIES, + pHeapFlags: *mut ::D3D12_HEAP_FLAGS + ) -> ::HRESULT +}); + +RIDL!( +interface ID3D12RootSignatureDeserializer(ID3D12RootSignatureDeserializerVtbl): IUnknown(IUnknownVtbl) { + fn GetRootSignatureDesc(&mut self) -> *const ::D3D12_ROOT_SIGNATURE_DESC +}); + + + +pub type PFN_D3D12_CREATE_DEVICE = extern "system" fn (_ : *mut ::IUnknown, _ : ::D3D_FEATURE_LEVEL, _ : ::REFGUID, _ : *mut *mut ::c_void) -> ::HRESULT; +pub type PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER = extern "system" fn (pSrcData: ::LPCVOID, SrcDataSizeInBytes: ::SIZE_T, pRootSignatureDeserializerInterface: ::REFGUID, ppRootSignatureDeserializer: *mut *mut ::c_void) -> ::HRESULT; +pub type PFN_D3D12_GET_DEBUG_INTERFACE = extern "system" fn (_ : ::REFGUID, _ : *mut *mut ::c_void) -> ::HRESULT; +pub type PFN_D3D12_SERIALIZE_ROOT_SIGNATURE = extern "system" fn (pRootSignature: *const ::D3D12_ROOT_SIGNATURE_DESC, Version: ::D3D_ROOT_SIGNATURE_VERSION, ppBlob: *mut *mut ::ID3DBlob, ppErrorBlob: *mut *mut ::ID3DBlob) -> ::HRESULT; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d12sdklayers.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d12sdklayers.rs new file mode 100644 index 0000000..f159886 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d12sdklayers.rs @@ -0,0 +1,1063 @@ +// Copyright © 2015, Dmitry Roschin +// Licensed under the MIT License <LICENSE.md> +RIDL!{interface ID3D12Debug(ID3D12DebugVtbl): IUnknown(IUnknownVtbl) { + fn EnableDebugLayer(&mut self) -> () +}} +FLAGS!{enum D3D12_DEBUG_FEATURE { + D3D12_DEBUG_FEATURE_NONE = 0, + D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DRAW = 0x1, + D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DISPATCH = 0x2, +}} +FLAGS!{enum D3D12_RLDO_FLAGS { + D3D12_RLDO_NONE = 0x0, + D3D12_RLDO_SUMMARY = 0x1, + D3D12_RLDO_DETAIL = 0x2, + D3D12_RLDO_IGNORE_INTERNAL = 0x4, +}} +RIDL!{interface ID3D12DebugDevice(ID3D12DebugDeviceVtbl): IUnknown(IUnknownVtbl) { + fn SetFeatureMask(&mut self, Mask: ::D3D12_DEBUG_FEATURE) -> ::HRESULT, + fn GetFeatureMask(&mut self) -> ::D3D12_DEBUG_FEATURE, + fn ReportLiveDeviceObjects(&mut self, Flags: ::D3D12_RLDO_FLAGS) -> ::HRESULT +}} +RIDL!{interface ID3D12DebugCommandQueue(ID3D12DebugCommandQueueVtbl): IUnknown(IUnknownVtbl) { + fn AssertResourceState( + &mut self, pResource: *mut ::ID3D12Resource, Subresource: ::UINT, State: ::UINT + ) -> ::BOOL +}} +RIDL!{interface ID3D12DebugCommandList(ID3D12DebugCommandListVtbl): IUnknown(IUnknownVtbl) { + fn AssertResourceState( + &mut self, pResource: *mut ::ID3D12Resource, Subresource: ::UINT, State: ::UINT + ) -> ::BOOL, + fn SetFeatureMask(&mut self, Mask: ::D3D12_DEBUG_FEATURE) -> ::HRESULT, + fn GetFeatureMask(&mut self) -> ::D3D12_DEBUG_FEATURE +}} +ENUM!{enum D3D12_MESSAGE_CATEGORY { + D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED = 0, + D3D12_MESSAGE_CATEGORY_MISCELLANEOUS = 1, + D3D12_MESSAGE_CATEGORY_INITIALIZATION = 2, + D3D12_MESSAGE_CATEGORY_CLEANUP = 3, + D3D12_MESSAGE_CATEGORY_COMPILATION = 4, + D3D12_MESSAGE_CATEGORY_STATE_CREATION = 5, + D3D12_MESSAGE_CATEGORY_STATE_SETTING = 6, + D3D12_MESSAGE_CATEGORY_STATE_GETTING = 7, + D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION = 8, + D3D12_MESSAGE_CATEGORY_EXECUTION = 9, + D3D12_MESSAGE_CATEGORY_SHADER = 10, +}} +ENUM!{enum D3D12_MESSAGE_SEVERITY { + D3D12_MESSAGE_SEVERITY_CORRUPTION = 0, + D3D12_MESSAGE_SEVERITY_ERROR = 1, + D3D12_MESSAGE_SEVERITY_WARNING = 2, + D3D12_MESSAGE_SEVERITY_INFO = 3, + D3D12_MESSAGE_SEVERITY_MESSAGE = 4, +}} +ENUM!{enum D3D12_MESSAGE_ID { + D3D12_MESSAGE_ID_UNKNOWN = 0, + D3D12_MESSAGE_ID_STRING_FROM_APPLICATION = 1, + D3D12_MESSAGE_ID_CORRUPTED_THIS = 2, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER1 = 3, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER2 = 4, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER3 = 5, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER4 = 6, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER5 = 7, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER6 = 8, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER7 = 9, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER8 = 10, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER9 = 11, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER10 = 12, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER11 = 13, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER12 = 14, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER13 = 15, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER14 = 16, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER15 = 17, + D3D12_MESSAGE_ID_CORRUPTED_MULTITHREADING = 18, + D3D12_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY = 19, + D3D12_MESSAGE_ID_GETPRIVATEDATA_MOREDATA = 20, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA = 21, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN = 22, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS = 23, + D3D12_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS = 24, + D3D12_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY = 25, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT = 26, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC = 27, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT = 28, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDVIDEOPLANESLICE = 29, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDPLANESLICE = 30, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS = 31, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE = 32, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN = 33, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN = 34, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT = 35, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT = 36, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC = 37, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT = 38, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDVIDEOPLANESLICE = 39, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDPLANESLICE = 40, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS = 41, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE = 42, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN = 43, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN = 44, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT = 45, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC = 46, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT = 47, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS = 48, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE = 49, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN = 50, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN = 51, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY = 52, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS = 53, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT = 54, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT = 55, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT = 56, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS = 57, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH = 58, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE = 59, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE = 60, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT = 61, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC = 62, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE = 63, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC = 64, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT = 65, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY = 66, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE = 67, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE = 68, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY = 69, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE = 70, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE = 71, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY = 72, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE = 73, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE = 74, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES = 75, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED = 76, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL = 77, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL = 78, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED = 79, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT = 80, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT = 81, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT = 82, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT = 83, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION = 84, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT = 85, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE = 86, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC = 87, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH = 88, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS = 89, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX = 90, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE = 91, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY = 92, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE = 93, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE = 94, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE = 95, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE = 96, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP = 97, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS = 98, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC = 99, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK = 100, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC = 101, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP = 102, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP = 103, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP = 104, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC = 105, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP = 106, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP = 107, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP = 108, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC = 109, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC = 110, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND = 111, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND = 112, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP = 113, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA = 114, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA = 115, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA = 116, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK = 117, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC = 118, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER = 119, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU = 120, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV = 121, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW = 122, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS = 123, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY = 124, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC = 125, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD = 126, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD = 127, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC = 128, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED = 129, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED = 130, + D3D12_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT = 131, + D3D12_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR = 132, + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH = 133, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH = 134, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID = 135, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE = 136, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE = 137, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE = 138, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE = 139, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX = 140, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE = 141, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID = 142, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID = 143, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID = 144, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID = 145, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID = 146, + D3D12_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE = 147, + D3D12_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS = 148, + D3D12_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED = 149, + D3D12_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN = 150, + D3D12_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED = 151, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE = 152, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE = 153, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS = 154, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED = 155, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN = 156, + D3D12_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE = 157, + D3D12_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED = 158, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE = 159, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE = 160, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS = 161, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED = 162, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN = 163, + D3D12_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE = 164, + D3D12_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED = 165, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE = 166, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE = 167, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS = 168, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED = 169, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN = 170, + D3D12_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE = 171, + D3D12_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED = 172, + D3D12_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED = 173, + D3D12_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED = 174, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS = 175, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN = 176, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN = 177, + D3D12_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE = 178, + D3D12_MESSAGE_ID_REF_THREADING_MODE = 179, + D3D12_MESSAGE_ID_REF_UMDRIVER_EXCEPTION = 180, + D3D12_MESSAGE_ID_REF_KMDRIVER_EXCEPTION = 181, + D3D12_MESSAGE_ID_REF_HARDWARE_EXCEPTION = 182, + D3D12_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE = 183, + D3D12_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER = 184, + D3D12_MESSAGE_ID_REF_OUT_OF_MEMORY = 185, + D3D12_MESSAGE_ID_REF_INFO = 186, + D3D12_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW = 187, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW = 188, + D3D12_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW = 189, + D3D12_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW = 190, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW = 191, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW = 192, + D3D12_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET = 193, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND = 194, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX = 195, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE = 196, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK = 197, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE = 198, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS = 199, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ROOT_SIGNATURE_NOT_SET = 200, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ROOT_SIGNATURE_MISMATCH = 201, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_NOT_SET = 202, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INPUTLAYOUT_NOT_SET = 203, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_CONSTANT_BUFFER_NOT_SET = 204, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_CONSTANT_BUFFER_TOO_SMALL = 205, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SAMPLER_NOT_SET = 206, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SHADERRESOURCEVIEW_NOT_SET = 207, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VIEW_DIMENSION_MISMATCH = 208, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL = 209, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_TOO_SMALL = 210, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_NOT_SET = 211, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_FORMAT_INVALID = 212, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_TOO_SMALL = 213, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_GS_INPUT_PRIMITIVE_MISMATCH = 214, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_RETURN_TYPE_MISMATCH = 215, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_POSITION_NOT_PRESENT = 216, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OUTPUT_STREAM_NOT_SET = 217, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_BOUND_RESOURCE_MAPPED = 218, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INVALID_PRIMITIVETOPOLOGY = 219, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_OFFSET_UNALIGNED = 220, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_STRIDE_UNALIGNED = 221, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_OFFSET_UNALIGNED = 222, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED = 223, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED = 224, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED = 225, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED = 226, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED = 227, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE = 228, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SO_STRIDE_LARGER_THAN_BUFFER = 229, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING = 230, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0 = 231, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT = 232, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT = 233, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT = 234, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN = 235, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN = 236, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN = 237, + D3D12_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET = 238, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC = 239, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC = 240, + D3D12_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH = 241, + D3D12_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW = 242, + D3D12_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS = 243, + D3D12_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH = 244, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH = 245, + D3D12_MESSAGE_ID_BLENDSTATE_GETDESC_LEGACY = 246, + D3D12_MESSAGE_ID_SHADERRESOURCEVIEW_GETDESC_LEGACY = 247, + D3D12_MESSAGE_ID_DEVICE_DRAW_PS_OUTPUT_TYPE_MISMATCH = 248, + D3D12_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_GATHER_UNSUPPORTED = 249, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN = 250, + D3D12_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_STRIDE_TOO_LARGE = 251, + D3D12_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_INVALIDRANGE = 252, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_EMPTY_LAYOUT = 253, + D3D12_MESSAGE_ID_DEVICE_DRAW_RESOURCE_SAMPLE_COUNT_MISMATCH = 254, + D3D12_MESSAGE_ID_LIVE_OBJECT_SUMMARY = 255, + D3D12_MESSAGE_ID_LIVE_BUFFER = 256, + D3D12_MESSAGE_ID_LIVE_TEXTURE1D = 257, + D3D12_MESSAGE_ID_LIVE_TEXTURE2D = 258, + D3D12_MESSAGE_ID_LIVE_TEXTURE3D = 259, + D3D12_MESSAGE_ID_LIVE_SHADERRESOURCEVIEW = 260, + D3D12_MESSAGE_ID_LIVE_RENDERTARGETVIEW = 261, + D3D12_MESSAGE_ID_LIVE_DEPTHSTENCILVIEW = 262, + D3D12_MESSAGE_ID_LIVE_VERTEXSHADER = 263, + D3D12_MESSAGE_ID_LIVE_GEOMETRYSHADER = 264, + D3D12_MESSAGE_ID_LIVE_PIXELSHADER = 265, + D3D12_MESSAGE_ID_LIVE_INPUTLAYOUT = 266, + D3D12_MESSAGE_ID_LIVE_SAMPLER = 267, + D3D12_MESSAGE_ID_LIVE_BLENDSTATE = 268, + D3D12_MESSAGE_ID_LIVE_DEPTHSTENCILSTATE = 269, + D3D12_MESSAGE_ID_LIVE_RASTERIZERSTATE = 270, + D3D12_MESSAGE_ID_LIVE_QUERY = 271, + D3D12_MESSAGE_ID_LIVE_PREDICATE = 272, + D3D12_MESSAGE_ID_LIVE_COUNTER = 273, + D3D12_MESSAGE_ID_LIVE_DEVICE = 274, + D3D12_MESSAGE_ID_LIVE_SWAPCHAIN = 275, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFLAGS = 276, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDCLASSLINKAGE = 277, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDCLASSLINKAGE = 278, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMSTREAMS = 279, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTREAMTORASTERIZER = 280, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDSTREAMS = 281, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCLASSLINKAGE = 282, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDCLASSLINKAGE = 283, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTREAM = 284, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDENTRIES = 285, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDSTRIDES = 286, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMSTRIDES = 287, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDCALL = 288, + D3D12_MESSAGE_ID_CREATEHULLSHADER_OUTOFMEMORY = 289, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDSHADERBYTECODE = 290, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDSHADERTYPE = 291, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDCLASSLINKAGE = 292, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDCALL = 293, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_OUTOFMEMORY = 294, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDSHADERBYTECODE = 295, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDSHADERTYPE = 296, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDCLASSLINKAGE = 297, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_XOR_DS_MISMATCH = 298, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_INVALID_ARG_BUFFER = 299, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_OFFSET_UNALIGNED = 300, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_OFFSET_OVERFLOW = 301, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDMAPTYPE = 302, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDSUBRESOURCE = 303, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDFLAGS = 304, + D3D12_MESSAGE_ID_RESOURCE_MAP_ALREADYMAPPED = 305, + D3D12_MESSAGE_ID_RESOURCE_MAP_DEVICEREMOVED_RETURN = 306, + D3D12_MESSAGE_ID_RESOURCE_MAP_OUTOFMEMORY_RETURN = 307, + D3D12_MESSAGE_ID_RESOURCE_MAP_WITHOUT_INITIAL_DISCARD = 308, + D3D12_MESSAGE_ID_RESOURCE_UNMAP_INVALIDSUBRESOURCE = 309, + D3D12_MESSAGE_ID_RESOURCE_UNMAP_NOTMAPPED = 310, + D3D12_MESSAGE_ID_DEVICE_DRAW_RASTERIZING_CONTROL_POINTS = 311, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNSUPPORTED = 312, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_SIGNATURE_MISMATCH = 313, + D3D12_MESSAGE_ID_DEVICE_DRAW_HULL_SHADER_INPUT_TOPOLOGY_MISMATCH = 314, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_CONTROL_POINT_COUNT_MISMATCH = 315, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_TESSELLATOR_DOMAIN_MISMATCH = 316, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_UNRECOGNIZED_FEATURE = 317, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_MISMATCHED_DATA_SIZE = 318, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_INVALIDARG_RETURN = 319, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDCALL = 320, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_OUTOFMEMORY = 321, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDSHADERBYTECODE = 322, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDCLASSLINKAGE = 323, + D3D12_MESSAGE_ID_DEVICE_CSSETSHADERRESOURCES_VIEWS_EMPTY = 324, + D3D12_MESSAGE_ID_CSSETCONSTANTBUFFERS_INVALIDBUFFER = 325, + D3D12_MESSAGE_ID_DEVICE_CSSETCONSTANTBUFFERS_BUFFERS_EMPTY = 326, + D3D12_MESSAGE_ID_DEVICE_CSSETSAMPLERS_SAMPLERS_EMPTY = 327, + D3D12_MESSAGE_ID_DEVICE_CSGETSHADERRESOURCES_VIEWS_EMPTY = 328, + D3D12_MESSAGE_ID_DEVICE_CSGETCONSTANTBUFFERS_BUFFERS_EMPTY = 329, + D3D12_MESSAGE_ID_DEVICE_CSGETSAMPLERS_SAMPLERS_EMPTY = 330, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 331, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 332, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 333, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 334, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DOUBLEFLOATOPSNOTSUPPORTED = 335, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 336, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_DOUBLEFLOATOPSNOTSUPPORTED = 337, + D3D12_MESSAGE_ID_CREATEBUFFER_INVALIDSTRUCTURESTRIDE = 338, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFLAGS = 339, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDRESOURCE = 340, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDESC = 341, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDFORMAT = 342, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDVIDEOPLANESLICE = 343, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDPLANESLICE = 344, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDIMENSIONS = 345, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_UNRECOGNIZEDFORMAT = 346, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_OVERLAPPING_OLD_SLOTS = 347, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_NO_OP = 348, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDARG_RETURN = 349, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_OUTOFMEMORY_RETURN = 350, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEW_DENORMFLUSH = 351, + D3D12_MESSAGE_ID_DEVICE_CSSETUNORDEREDACCESSS_VIEWS_EMPTY = 352, + D3D12_MESSAGE_ID_DEVICE_CSGETUNORDEREDACCESSS_VIEWS_EMPTY = 353, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDFLAGS = 354, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_INVALID_ARG_BUFFER = 355, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_OFFSET_UNALIGNED = 356, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_OFFSET_OVERFLOW = 357, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DEPTH_READONLY = 358, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_STENCIL_READONLY = 359, + D3D12_MESSAGE_ID_CHECKFEATURESUPPORT_FORMAT_DEPRECATED = 360, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_RETURN_TYPE_MISMATCH = 361, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_NOT_SET = 362, + D3D12_MESSAGE_ID_DEVICE_DRAW_UNORDEREDACCESSVIEW_RENDERTARGETVIEW_OVERLAP = 363, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_DIMENSION_MISMATCH = 364, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_APPEND_UNSUPPORTED = 365, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMICS_UNSUPPORTED = 366, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_STRUCTURE_STRIDE_MISMATCH = 367, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_BUFFER_TYPE_MISMATCH = 368, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_RAW_UNSUPPORTED = 369, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_FORMAT_LD_UNSUPPORTED = 370, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_FORMAT_STORE_UNSUPPORTED = 371, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_ADD_UNSUPPORTED = 372, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_BITWISE_OPS_UNSUPPORTED = 373, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_CMPSTORE_CMPEXCHANGE_UNSUPPORTED = 374, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_EXCHANGE_UNSUPPORTED = 375, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_SIGNED_MINMAX_UNSUPPORTED = 376, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_UNSIGNED_MINMAX_UNSUPPORTED = 377, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_BOUND_RESOURCE_MAPPED = 378, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_THREADGROUPCOUNT_OVERFLOW = 379, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_THREADGROUPCOUNT_ZERO = 380, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_STRUCTURE_STRIDE_MISMATCH = 381, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_BUFFER_TYPE_MISMATCH = 382, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_RAW_UNSUPPORTED = 383, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_UNSUPPORTED = 384, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_UNSUPPORTED = 385, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDOFFSET = 386, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_LARGEOFFSET = 387, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDDESTINATIONSTATE = 388, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDSOURCESTATE = 389, + D3D12_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_NOT_SUPPORTED = 390, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEWFLOAT_INVALIDFORMAT = 391, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_COUNTER_UNSUPPORTED = 392, + D3D12_MESSAGE_ID_DEVICE_DRAW_PIXEL_SHADER_WITHOUT_RTV_OR_DSV = 393, + D3D12_MESSAGE_ID_SHADER_ABORT = 394, + D3D12_MESSAGE_ID_SHADER_MESSAGE = 395, + D3D12_MESSAGE_ID_SHADER_ERROR = 396, + D3D12_MESSAGE_ID_OFFERRESOURCES_INVALIDRESOURCE = 397, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_INVALIDARG_RETURN = 398, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_OUTOFMEMORY_RETURN = 399, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_ACCESSDENIED_RETURN = 400, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFORCEDSAMPLECOUNT = 401, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_FORCED_SAMPLE_COUNT = 402, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDLOGICOPS = 403, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDARRAYWITHDECODER = 404, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDARRAYWITHDECODER = 405, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDARRAYWITHDECODER = 406, + D3D12_MESSAGE_ID_DEVICE_LOCKEDOUT_INTERFACE = 407, + D3D12_MESSAGE_ID_OFFERRESOURCES_INVALIDPRIORITY = 408, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDVIEW = 409, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 410, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_SHADEREXTENSIONSNOTSUPPORTED = 411, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 412, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_SHADEREXTENSIONSNOTSUPPORTED = 413, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 414, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_SHADEREXTENSIONSNOTSUPPORTED = 415, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 416, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_SHADEREXTENSIONSNOTSUPPORTED = 417, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DOUBLEEXTENSIONSNOTSUPPORTED = 418, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_SHADEREXTENSIONSNOTSUPPORTED = 419, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 420, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_SHADEREXTENSIONSNOTSUPPORTED = 421, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 422, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_SHADEREXTENSIONSNOTSUPPORTED = 423, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_MINPRECISION = 424, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_UAVSNOTSUPPORTED = 425, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_UAVSNOTSUPPORTED = 426, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_UAVSNOTSUPPORTED = 427, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_UAVSNOTSUPPORTED = 428, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UAVSNOTSUPPORTED = 429, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_UAVSNOTSUPPORTED = 430, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_UAVSNOTSUPPORTED = 431, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_INVALIDOFFSET = 432, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_TOOMANYVIEWS = 433, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_NOTSUPPORTED = 434, + D3D12_MESSAGE_ID_SWAPDEVICECONTEXTSTATE_NOTSUPPORTED = 435, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_PREFERUPDATESUBRESOURCE1 = 436, + D3D12_MESSAGE_ID_GETDC_INACCESSIBLE = 437, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDRECT = 438, + D3D12_MESSAGE_ID_DEVICE_DRAW_SAMPLE_MASK_IGNORED_ON_FL9 = 439, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE1_NOT_SUPPORTED = 440, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BY_NAME_NOT_SUPPORTED = 441, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_NOT_SUPPORTED = 442, + D3D12_MESSAGE_ID_OFFERRELEASE_NOT_SUPPORTED = 443, + D3D12_MESSAGE_ID_OFFERRESOURCES_INACCESSIBLE = 444, + D3D12_MESSAGE_ID_CREATEVIDEOPROCESSORINPUTVIEW_INVALIDMSAA = 445, + D3D12_MESSAGE_ID_CREATEVIDEOPROCESSOROUTPUTVIEW_INVALIDMSAA = 446, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDSOURCERECT = 447, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_EMPTYRECT = 448, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_EMPTYDESTBOX = 449, + D3D12_MESSAGE_ID_COPYSUBRESOURCEREGION_EMPTYSOURCEBOX = 450, + D3D12_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_LOGIC_OPS = 451, + D3D12_MESSAGE_ID_DEVICE_DRAW_DEPTHSTENCILVIEW_NOT_SET = 452, + D3D12_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET = 453, + D3D12_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET_DUE_TO_FLIP_PRESENT = 454, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_NOT_SET_DUE_TO_FLIP_PRESENT = 455, + D3D12_MESSAGE_ID_GETDATAFORNEWHARDWAREKEY_NULLPARAM = 456, + D3D12_MESSAGE_ID_CHECKCRYPTOSESSIONSTATUS_NULLPARAM = 457, + D3D12_MESSAGE_ID_SETEVENTONHARDWARECONTENTPROTECTIONTILT_NULLPARAM = 458, + D3D12_MESSAGE_ID_GETVIDEODECODERCAPS_NULLPARAM = 459, + D3D12_MESSAGE_ID_GETVIDEODECODERCAPS_ZEROWIDTHHEIGHT = 460, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_NULLPARAM = 461, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_INVALIDCOLORSPACE = 462, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_ZEROWIDTHHEIGHT = 463, + D3D12_MESSAGE_ID_VIDEODECODERENABLEDOWNSAMPLING_NULLPARAM = 464, + D3D12_MESSAGE_ID_VIDEODECODERENABLEDOWNSAMPLING_UNSUPPORTED = 465, + D3D12_MESSAGE_ID_VIDEODECODERUPDATEDOWNSAMPLING_NULLPARAM = 466, + D3D12_MESSAGE_ID_VIDEODECODERUPDATEDOWNSAMPLING_UNSUPPORTED = 467, + D3D12_MESSAGE_ID_CHECKVIDEOPROCESSORFORMATCONVERSION_NULLPARAM = 468, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETOUTPUTCOLORSPACE1_NULLPARAM = 469, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETOUTPUTCOLORSPACE1_NULLPARAM = 470, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMCOLORSPACE1_NULLPARAM = 471, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMCOLORSPACE1_INVALIDSTREAM = 472, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_NULLPARAM = 473, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_INVALIDSTREAM = 474, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_UNSUPPORTED = 475, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETSTREAMCOLORSPACE1_NULLPARAM = 476, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETSTREAMMIRROR_NULLPARAM = 477, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_NULLPARAM = 478, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_INVALIDCOLORSPACE = 479, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_ZEROWIDTHHEIGHT = 480, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETOUTPUTSHADERUSAGE_NULLPARAM = 481, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETOUTPUTSHADERUSAGE_NULLPARAM = 482, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_NULLPARAM = 483, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDSTREAMCOUNT = 484, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_TARGETRECT = 485, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDSOURCERECT = 486, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDDESTRECT = 487, + D3D12_MESSAGE_ID_CREATEBUFFER_INVALIDUSAGE = 488, + D3D12_MESSAGE_ID_CREATETEXTURE1D_INVALIDUSAGE = 489, + D3D12_MESSAGE_ID_CREATETEXTURE2D_INVALIDUSAGE = 490, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_LEVEL9_STEPRATE_NOT_1 = 491, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_LEVEL9_INSTANCING_NOT_SUPPORTED = 492, + D3D12_MESSAGE_ID_UPDATETILEMAPPINGS_INVALID_PARAMETER = 493, + D3D12_MESSAGE_ID_COPYTILEMAPPINGS_INVALID_PARAMETER = 494, + D3D12_MESSAGE_ID_COPYTILES_INVALID_PARAMETER = 495, + D3D12_MESSAGE_ID_NULL_TILE_MAPPING_ACCESS_WARNING = 496, + D3D12_MESSAGE_ID_NULL_TILE_MAPPING_ACCESS_ERROR = 497, + D3D12_MESSAGE_ID_DIRTY_TILE_MAPPING_ACCESS = 498, + D3D12_MESSAGE_ID_DUPLICATE_TILE_MAPPINGS_IN_COVERED_AREA = 499, + D3D12_MESSAGE_ID_TILE_MAPPINGS_IN_COVERED_AREA_DUPLICATED_OUTSIDE = 500, + D3D12_MESSAGE_ID_TILE_MAPPINGS_SHARED_BETWEEN_INCOMPATIBLE_RESOURCES = 501, + D3D12_MESSAGE_ID_TILE_MAPPINGS_SHARED_BETWEEN_INPUT_AND_OUTPUT = 502, + D3D12_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_INVALIDFLAGS = 503, + D3D12_MESSAGE_ID_GETRESOURCETILING_NONTILED_RESOURCE = 504, + D3D12_MESSAGE_ID_NEED_TO_CALL_TILEDRESOURCEBARRIER = 505, + D3D12_MESSAGE_ID_CREATEDEVICE_INVALIDARGS = 506, + D3D12_MESSAGE_ID_CREATEDEVICE_WARNING = 507, + D3D12_MESSAGE_ID_TILED_RESOURCE_TIER_1_BUFFER_TEXTURE_MISMATCH = 508, + D3D12_MESSAGE_ID_CREATE_CRYPTOSESSION = 509, + D3D12_MESSAGE_ID_CREATE_AUTHENTICATEDCHANNEL = 510, + D3D12_MESSAGE_ID_LIVE_CRYPTOSESSION = 511, + D3D12_MESSAGE_ID_LIVE_AUTHENTICATEDCHANNEL = 512, + D3D12_MESSAGE_ID_DESTROY_CRYPTOSESSION = 513, + D3D12_MESSAGE_ID_DESTROY_AUTHENTICATEDCHANNEL = 514, + D3D12_MESSAGE_ID_MAP_INVALID_SUBRESOURCE = 515, + D3D12_MESSAGE_ID_MAP_INVALID_TYPE = 516, + D3D12_MESSAGE_ID_MAP_UNSUPPORTED_TYPE = 517, + D3D12_MESSAGE_ID_UNMAP_INVALID_SUBRESOURCE = 518, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_TYPE = 519, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_NULL_POINTER = 520, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_SUBRESOURCE = 521, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_RESERVED_BITS = 522, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISSING_BIND_FLAGS = 523, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_MISC_FLAGS = 524, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MATCHING_STATES = 525, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMBINATION = 526, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH = 527, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_RESOURCE = 528, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_SAMPLE_COUNT = 529, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAGS = 530, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMBINED_FLAGS = 531, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAGS_FOR_FORMAT = 532, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_SPLIT_BARRIER = 533, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_UNMATCHED_END = 534, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_UNMATCHED_BEGIN = 535, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAG = 536, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMMAND_LIST_TYPE = 537, + D3D12_MESSAGE_ID_INVALID_SUBRESOURCE_STATE = 538, + D3D12_MESSAGE_ID_INEFFICIENT_PRESENT = 539, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_CONTENTION = 540, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_RESET = 541, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_RESET_BUNDLE = 542, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_CANNOT_RESET = 543, + D3D12_MESSAGE_ID_COMMAND_LIST_OPEN = 544, + D3D12_MESSAGE_ID_QUERY_STATE_MISMATCH = 545, + D3D12_MESSAGE_ID_INVALID_BUNDLE_API = 546, + D3D12_MESSAGE_ID_COMMAND_LIST_CLOSED = 547, + D3D12_MESSAGE_ID_COMMAND_LIST_CLOSED_WITH_INVALID_RESOURCE = 548, + D3D12_MESSAGE_ID_WRONG_COMMAND_ALLOCATOR_TYPE = 549, + D3D12_MESSAGE_ID_INVALID_INDIRECT_ARGUMENT_BUFFER = 550, + D3D12_MESSAGE_ID_COMPUTE_AND_GRAPHICS_PIPELINE = 551, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_SYNC = 552, + D3D12_MESSAGE_ID_COMMAND_LIST_SYNC = 553, + D3D12_MESSAGE_ID_SET_DESCRIPTOR_HEAP_INVALID = 554, + D3D12_MESSAGE_ID_CREATE_QUEUE_IMAGE_NOT_SUPPORTED = 555, + D3D12_MESSAGE_ID_CREATE_COMMAND_ALLOCATOR_IMAGE_NOT_SUPPORTED = 556, + D3D12_MESSAGE_ID_CREATE_COMMANDQUEUE = 557, + D3D12_MESSAGE_ID_CREATE_COMMANDALLOCATOR = 558, + D3D12_MESSAGE_ID_CREATE_PIPELINESTATE = 559, + D3D12_MESSAGE_ID_CREATE_COMMANDLIST12 = 560, + D3D12_MESSAGE_ID_CREATE_IMAGECOMMANDLIST = 561, + D3D12_MESSAGE_ID_CREATE_RESOURCE = 562, + D3D12_MESSAGE_ID_CREATE_DESCRIPTORHEAP = 563, + D3D12_MESSAGE_ID_CREATE_ROOTSIGNATURE = 564, + D3D12_MESSAGE_ID_CREATE_LIBRARY = 565, + D3D12_MESSAGE_ID_CREATE_HEAP = 566, + D3D12_MESSAGE_ID_CREATE_MONITOREDFENCE = 567, + D3D12_MESSAGE_ID_CREATE_QUERYHEAP = 568, + D3D12_MESSAGE_ID_CREATE_COMMANDSIGNATURE = 569, + D3D12_MESSAGE_ID_LIVE_COMMANDQUEUE = 570, + D3D12_MESSAGE_ID_LIVE_COMMANDALLOCATOR = 571, + D3D12_MESSAGE_ID_LIVE_PIPELINESTATE = 572, + D3D12_MESSAGE_ID_LIVE_COMMANDLIST12 = 573, + D3D12_MESSAGE_ID_LIVE_IMAGECOMMANDLIST = 574, + D3D12_MESSAGE_ID_LIVE_RESOURCE = 575, + D3D12_MESSAGE_ID_LIVE_DESCRIPTORHEAP = 576, + D3D12_MESSAGE_ID_LIVE_ROOTSIGNATURE = 577, + D3D12_MESSAGE_ID_LIVE_LIBRARY = 578, + D3D12_MESSAGE_ID_LIVE_HEAP = 579, + D3D12_MESSAGE_ID_LIVE_MONITOREDFENCE = 580, + D3D12_MESSAGE_ID_LIVE_QUERYHEAP = 581, + D3D12_MESSAGE_ID_LIVE_COMMANDSIGNATURE = 582, + D3D12_MESSAGE_ID_DESTROY_COMMANDQUEUE = 583, + D3D12_MESSAGE_ID_DESTROY_COMMANDALLOCATOR = 584, + D3D12_MESSAGE_ID_DESTROY_PIPELINESTATE = 585, + D3D12_MESSAGE_ID_DESTROY_COMMANDLIST12 = 586, + D3D12_MESSAGE_ID_DESTROY_IMAGECOMMANDLIST = 587, + D3D12_MESSAGE_ID_DESTROY_RESOURCE = 588, + D3D12_MESSAGE_ID_DESTROY_DESCRIPTORHEAP = 589, + D3D12_MESSAGE_ID_DESTROY_ROOTSIGNATURE = 590, + D3D12_MESSAGE_ID_DESTROY_LIBRARY = 591, + D3D12_MESSAGE_ID_DESTROY_HEAP = 592, + D3D12_MESSAGE_ID_DESTROY_MONITOREDFENCE = 593, + D3D12_MESSAGE_ID_DESTROY_QUERYHEAP = 594, + D3D12_MESSAGE_ID_DESTROY_COMMANDSIGNATURE = 595, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDHEAPTYPE = 596, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDIMENSIONS = 597, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDMISCFLAGS = 598, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDMISCFLAGS = 599, + D3D12_MESSAGE_ID_CREATERESOURCE_LARGEALLOCATION = 600, + D3D12_MESSAGE_ID_CREATERESOURCE_SMALLALLOCATION = 601, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDARG_RETURN = 602, + D3D12_MESSAGE_ID_CREATERESOURCE_OUTOFMEMORY_RETURN = 603, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDESC = 604, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDINITIALSTATE = 605, + D3D12_MESSAGE_ID_RESOURCE_HAS_PENDING_INITIAL_DATA = 606, + D3D12_MESSAGE_ID_POSSIBLY_INVALID_SUBRESOURCE_STATE = 607, + D3D12_MESSAGE_ID_INVALID_USE_OF_NON_RESIDENT_RESOURCE = 608, + D3D12_MESSAGE_ID_POSSIBLE_INVALID_USE_OF_NON_RESIDENT_RESOURCE = 609, + D3D12_MESSAGE_ID_BUNDLE_PIPELINE_STATE_MISMATCH = 610, + D3D12_MESSAGE_ID_PRIMITIVE_TOPOLOGY_MISMATCH_PIPELINE_STATE = 611, + D3D12_MESSAGE_ID_RENDER_TARGET_NUMBER_MISMATCH_PIPELINE_STATE = 612, + D3D12_MESSAGE_ID_RENDER_TARGET_FORMAT_MISMATCH_PIPELINE_STATE = 613, + D3D12_MESSAGE_ID_RENDER_TARGET_SAMPLE_DESC_MISMATCH_PIPELINE_STATE = 614, + D3D12_MESSAGE_ID_DEPTH_STENCIL_FORMAT_MISMATCH_PIPELINE_STATE = 615, + D3D12_MESSAGE_ID_DEPTH_STENCIL_SAMPLE_DESC_MISMATCH_PIPELINE_STATE = 616, + D3D12_MESSAGE_ID_RENDER_TARGET_NUMBER_MISMATCH_BUNDLE_PIPELINE_STATE = 617, + D3D12_MESSAGE_ID_RENDER_TARGET_FORMAT_MISMATCH_BUNDLE_PIPELINE_STATE = 618, + D3D12_MESSAGE_ID_RENDER_TARGET_SAMPLE_DESC_MISMATCH_BUNDLE_PIPELINE_STATE = 619, + D3D12_MESSAGE_ID_DEPTH_STENCIL_FORMAT_MISMATCH_BUNDLE_PIPELINE_STATE = 620, + D3D12_MESSAGE_ID_DEPTH_STENCIL_SAMPLE_DESC_MISMATCH_BUNDLE_PIPELINE_STATE = 621, + D3D12_MESSAGE_ID_CREATESHADER_INVALIDBYTECODE = 622, + D3D12_MESSAGE_ID_CREATEHEAP_NULLDESC = 623, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDSIZE = 624, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDHEAPTYPE = 625, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDCPUPAGEPROPERTIES = 626, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDMEMORYPOOL = 627, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDPROPERTIES = 628, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDALIGNMENT = 629, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDMISCFLAGS = 630, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDMISCFLAGS = 631, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDARG_RETURN = 632, + D3D12_MESSAGE_ID_CREATEHEAP_OUTOFMEMORY_RETURN = 633, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLHEAPPROPERTIES = 634, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDHEAPTYPE = 635, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDCPUPAGEPROPERTIES = 636, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDMEMORYPOOL = 637, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPPROPERTIES = 638, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDHEAPMISCFLAGS = 639, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPMISCFLAGS = 640, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDARG_RETURN = 641, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_OUTOFMEMORY_RETURN = 642, + D3D12_MESSAGE_ID_GETCUSTOMHEAPPROPERTIES_UNRECOGNIZEDHEAPTYPE = 643, + D3D12_MESSAGE_ID_GETCUSTOMHEAPPROPERTIES_INVALIDHEAPTYPE = 644, + D3D12_MESSAGE_ID_CREATE_DESCRIPTOR_HEAP_INVALID_DESC = 645, + D3D12_MESSAGE_ID_INVALID_DESCRIPTOR_HANDLE = 646, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALID_CONSERVATIVERASTERMODE = 647, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_SYSTEMVALUE = 648, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_INVALID_RESOURCE = 649, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_INVALID_DESC = 650, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_LARGE_OFFSET = 651, + D3D12_MESSAGE_ID_CREATE_UNORDEREDACCESS_VIEW_INVALID_COUNTER_USAGE = 652, + D3D12_MESSAGE_ID_COPY_DESCRIPTORS_INVALID_RANGES = 653, + D3D12_MESSAGE_ID_COPY_DESCRIPTORS_WRITE_ONLY_DESCRIPTOR = 654, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RTV_FORMAT_NOT_UNKNOWN = 655, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_RENDER_TARGET_COUNT = 656, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VERTEX_SHADER_NOT_SET = 657, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INPUTLAYOUT_NOT_SET = 658, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_HS_DS_SIGNATURE_MISMATCH = 659, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_REGISTERINDEX = 660, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_COMPONENTTYPE = 661, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_REGISTERMASK = 662, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_SYSTEMVALUE = 663, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS = 664, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_MINPRECISION = 665, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND = 666, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_XOR_DS_MISMATCH = 667, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HULL_SHADER_INPUT_TOPOLOGY_MISMATCH = 668, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_DS_CONTROL_POINT_COUNT_MISMATCH = 669, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_DS_TESSELLATOR_DOMAIN_MISMATCH = 670, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN = 671, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_USE_OF_FORCED_SAMPLE_COUNT = 672, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_PRIMITIVETOPOLOGY = 673, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_SYSTEMVALUE = 674, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0 = 675, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING = 676, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_OUTPUT_TYPE_MISMATCH = 677, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_RENDER_TARGET_DOES_NOT_SUPPORT_LOGIC_OPS = 678, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RENDERTARGETVIEW_NOT_SET = 679, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_DEPTHSTENCILVIEW_NOT_SET = 680, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_GS_INPUT_PRIMITIVE_MISMATCH = 681, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_POSITION_NOT_PRESENT = 682, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MISSING_ROOT_SIGNATURE_FLAGS = 683, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_INDEX_BUFFER_PROPERTIES = 684, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_SAMPLE_DESC = 685, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_ROOT_SIGNATURE_MISMATCH = 686, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_DS_ROOT_SIGNATURE_MISMATCH = 687, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VS_ROOT_SIGNATURE_MISMATCH = 688, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_GS_ROOT_SIGNATURE_MISMATCH = 689, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_ROOT_SIGNATURE_MISMATCH = 690, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MISSING_ROOT_SIGNATURE = 691, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_OPEN_BUNDLE = 692, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_DESCRIPTOR_HEAP_MISMATCH = 693, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_TYPE = 694, + D3D12_MESSAGE_ID_DRAW_EMPTY_SCISSOR_RECTANGLE = 695, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_BLOB_NOT_FOUND = 696, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_DESERIALIZE_FAILED = 697, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_INVALID_CONFIGURATION = 698, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_NOT_SUPPORTED_ON_DEVICE = 699, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLRESOURCEPROPERTIES = 700, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLHEAP = 701, + D3D12_MESSAGE_ID_GETRESOURCEALLOCATIONINFO_INVALIDRDESCS = 702, + D3D12_MESSAGE_ID_MAKERESIDENT_NULLOBJECTARRAY = 703, + D3D12_MESSAGE_ID_MAKERESIDENT_INVALIDOBJECT = 704, + D3D12_MESSAGE_ID_EVICT_NULLOBJECTARRAY = 705, + D3D12_MESSAGE_ID_EVICT_INVALIDOBJECT = 706, + D3D12_MESSAGE_ID_HEAPS_UNSUPPORTED = 707, + D3D12_MESSAGE_ID_SET_DESCRIPTOR_TABLE_INVALID = 708, + D3D12_MESSAGE_ID_SET_ROOT_CONSTANT_INVALID = 709, + D3D12_MESSAGE_ID_SET_ROOT_CONSTANT_BUFFER_VIEW_INVALID = 710, + D3D12_MESSAGE_ID_SET_ROOT_SHADER_RESOURCE_VIEW_INVALID = 711, + D3D12_MESSAGE_ID_SET_ROOT_UNORDERED_ACCESS_VIEW_INVALID = 712, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_INVALID_DESC = 713, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_LARGE_OFFSET = 714, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_INVALID_DESC = 715, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_LARGE_OFFSET = 716, + D3D12_MESSAGE_ID_SET_STREAM_OUTPUT_BUFFERS_INVALID_DESC = 717, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDDIMENSIONALITY = 718, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDLAYOUT = 719, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDIMENSIONALITY = 720, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDALIGNMENT = 721, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDMIPLEVELS = 722, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDSAMPLEDESC = 723, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDLAYOUT = 724, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_INVALID = 725, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_INVALID = 726, + D3D12_MESSAGE_ID_SET_STREAM_OUTPUT_BUFFERS_INVALID = 727, + D3D12_MESSAGE_ID_SET_RENDER_TARGETS_INVALID = 728, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_INVALID_PARAMETERS = 729, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_JPEG_NOT_SUPPORTED = 730, + D3D12_MESSAGE_ID_BEGIN_END_QUERY_INVALID_PARAMETERS = 731, + D3D12_MESSAGE_ID_CLOSE_COMMAND_LIST_OPEN_QUERY = 732, + D3D12_MESSAGE_ID_RESOLVE_QUERY_DATA_INVALID_PARAMETERS = 733, + D3D12_MESSAGE_ID_SET_PREDICATION_INVALID_PARAMETERS = 734, + D3D12_MESSAGE_ID_TIMESTAMPS_NOT_SUPPORTED = 735, + D3D12_MESSAGE_ID_UNSTABLE_POWER_STATE = 736, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDFORMAT = 737, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDFORMAT = 738, + D3D12_MESSAGE_ID_GETCOPYABLELAYOUT_INVALIDSUBRESOURCERANGE = 739, + D3D12_MESSAGE_ID_GETCOPYABLELAYOUT_INVALIDBASEOFFSET = 740, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_HEAP = 741, + D3D12_MESSAGE_ID_CREATE_SAMPLER_INVALID = 742, + D3D12_MESSAGE_ID_CREATECOMMANDSIGNATURE_INVALID = 743, + D3D12_MESSAGE_ID_EXECUTE_INDIRECT_INVALID_PARAMETERS = 744, + D3D12_MESSAGE_ID_GETGPUVIRTUALADDRESS_INVALID_RESOURCE_DIMENSION = 745, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDCONTEXTTYPE = 746, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_DECODENOTSUPPORTED = 747, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_ENCODENOTSUPPORTED = 748, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDPLANEINDEX = 749, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDVIDEOPLANEINDEX = 750, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_AMBIGUOUSVIDEOPLANEINDEX = 751, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDPLANEINDEX = 752, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDVIDEOPLANEINDEX = 753, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_AMBIGUOUSVIDEOPLANEINDEX = 754, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDPLANEINDEX = 755, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDVIDEOPLANEINDEX = 756, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_AMBIGUOUSVIDEOPLANEINDEX = 757, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSCANDATAOFFSET = 758, + D3D12_MESSAGE_ID_JPEGDECODE_NOTSUPPORTED = 759, + D3D12_MESSAGE_ID_JPEGDECODE_DIMENSIONSTOOLARGE = 760, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDCOMPONENTS = 761, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDCOMPONENTS = 762, + D3D12_MESSAGE_ID_JPEGDECODE_DESTINATIONNOT2D = 763, + D3D12_MESSAGE_ID_JPEGDECODE_TILEDRESOURCESUNSUPPORTED = 764, + D3D12_MESSAGE_ID_JPEGDECODE_GUARDRECTSUNSUPPORTED = 765, + D3D12_MESSAGE_ID_JPEGDECODE_FORMATUNSUPPORTED = 766, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSUBRESOURCE = 767, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDMIPLEVEL = 768, + D3D12_MESSAGE_ID_JPEGDECODE_EMPTYDESTBOX = 769, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXNOT2D = 770, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXNOTSUB = 771, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXESINTERSECT = 772, + D3D12_MESSAGE_ID_JPEGDECODE_XSUBSAMPLEMISMATCH = 773, + D3D12_MESSAGE_ID_JPEGDECODE_YSUBSAMPLEMISMATCH = 774, + D3D12_MESSAGE_ID_JPEGDECODE_XSUBSAMPLEODD = 775, + D3D12_MESSAGE_ID_JPEGDECODE_YSUBSAMPLEODD = 776, + D3D12_MESSAGE_ID_JPEGDECODE_UPSCALEUNSUPPORTED = 777, + D3D12_MESSAGE_ID_JPEGDECODE_TIER4DOWNSCALETOLARGE = 778, + D3D12_MESSAGE_ID_JPEGDECODE_TIER3DOWNSCALEUNSUPPORTED = 779, + D3D12_MESSAGE_ID_JPEGDECODE_CHROMASIZEMISMATCH = 780, + D3D12_MESSAGE_ID_JPEGDECODE_LUMACHROMASIZEMISMATCH = 781, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDNUMDESTINATIONS = 782, + D3D12_MESSAGE_ID_JPEGDECODE_SUBBOXUNSUPPORTED = 783, + D3D12_MESSAGE_ID_JPEGDECODE_1DESTUNSUPPORTEDFORMAT = 784, + D3D12_MESSAGE_ID_JPEGDECODE_3DESTUNSUPPORTEDFORMAT = 785, + D3D12_MESSAGE_ID_JPEGDECODE_SCALEUNSUPPORTED = 786, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSOURCESIZE = 787, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDCOPYFLAGS = 788, + D3D12_MESSAGE_ID_JPEGDECODE_HAZARD = 789, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDSRCBUFFERUSAGE = 790, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDSRCBUFFERMISCFLAGS = 791, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDDSTTEXTUREUSAGE = 792, + D3D12_MESSAGE_ID_JPEGDECODE_BACKBUFFERNOTSUPPORTED = 793, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPRTEDCOPYFLAGS = 794, + D3D12_MESSAGE_ID_JPEGENCODE_NOTSUPPORTED = 795, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDSCANDATAOFFSET = 796, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDCOMPONENTS = 797, + D3D12_MESSAGE_ID_JPEGENCODE_SOURCENOT2D = 798, + D3D12_MESSAGE_ID_JPEGENCODE_TILEDRESOURCESUNSUPPORTED = 799, + D3D12_MESSAGE_ID_JPEGENCODE_GUARDRECTSUNSUPPORTED = 800, + D3D12_MESSAGE_ID_JPEGENCODE_XSUBSAMPLEMISMATCH = 801, + D3D12_MESSAGE_ID_JPEGENCODE_YSUBSAMPLEMISMATCH = 802, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDCOMPONENTS = 803, + D3D12_MESSAGE_ID_JPEGENCODE_FORMATUNSUPPORTED = 804, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDSUBRESOURCE = 805, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDMIPLEVEL = 806, + D3D12_MESSAGE_ID_JPEGENCODE_DIMENSIONSTOOLARGE = 807, + D3D12_MESSAGE_ID_JPEGENCODE_HAZARD = 808, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDDSTBUFFERUSAGE = 809, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDDSTBUFFERMISCFLAGS = 810, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDSRCTEXTUREUSAGE = 811, + D3D12_MESSAGE_ID_JPEGENCODE_BACKBUFFERNOTSUPPORTED = 812, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_UNSUPPORTEDCONTEXTTTYPEFORQUERY = 813, + D3D12_MESSAGE_ID_FLUSH1_INVALIDCONTEXTTYPE = 814, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDCLEARVALUE = 815, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDCLEARVALUEFORMAT = 816, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDCLEARVALUEFORMAT = 817, + D3D12_MESSAGE_ID_CREATERESOURCE_CLEARVALUEDENORMFLUSH = 818, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALIDDEPTH = 819, + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE = 820, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE = 821, + D3D12_MESSAGE_ID_MAP_INVALIDHEAP = 822, + D3D12_MESSAGE_ID_UNMAP_INVALIDHEAP = 823, + D3D12_MESSAGE_ID_MAP_INVALIDRESOURCE = 824, + D3D12_MESSAGE_ID_UNMAP_INVALIDRESOURCE = 825, + D3D12_MESSAGE_ID_MAP_INVALIDSUBRESOURCE = 826, + D3D12_MESSAGE_ID_UNMAP_INVALIDSUBRESOURCE = 827, + D3D12_MESSAGE_ID_MAP_INVALIDRANGE = 828, + D3D12_MESSAGE_ID_UNMAP_INVALIDRANGE = 829, + D3D12_MESSAGE_ID_MAP_NULLRANGE = 830, + D3D12_MESSAGE_ID_UNMAP_NULLRANGE = 831, + D3D12_MESSAGE_ID_MAP_INVALIDDATAPOINTER = 832, + D3D12_MESSAGE_ID_MAP_INVALIDARG_RETURN = 833, + D3D12_MESSAGE_ID_MAP_OUTOFMEMORY_RETURN = 834, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_BUNDLENOTSUPPORTED = 835, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_COMMANDLISTMISMATCH = 836, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_OPENCOMMANDLIST = 837, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_FAILEDCOMMANDLIST = 838, + D3D12_MESSAGE_ID_COPYBUFFERREGION_NULLDST = 839, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDDSTRESOURCEDIMENSION = 840, + D3D12_MESSAGE_ID_COPYBUFFERREGION_DSTRANGEOUTOFBOUNDS = 841, + D3D12_MESSAGE_ID_COPYBUFFERREGION_NULLSRC = 842, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDSRCRESOURCEDIMENSION = 843, + D3D12_MESSAGE_ID_COPYBUFFERREGION_SRCRANGEOUTOFBOUNDS = 844, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDCOPYFLAGS = 845, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_NULLDST = 846, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDDSTTYPE = 847, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCEDIMENSION = 848, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCE = 849, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTSUBRESOURCE = 850, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTOFFSET = 851, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDDSTFORMAT = 852, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTFORMAT = 853, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTDIMENSIONS = 854, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTROWPITCH = 855, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTPLACEMENT = 856, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTDSPLACEDFOOTPRINTFORMAT = 857, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_DSTREGIONOUTOFBOUNDS = 858, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_NULLSRC = 859, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDSRCTYPE = 860, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCRESOURCEDIMENSION = 861, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCRESOURCE = 862, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCSUBRESOURCE = 863, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCOFFSET = 864, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDSRCFORMAT = 865, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCFORMAT = 866, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCDIMENSIONS = 867, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCROWPITCH = 868, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCPLACEMENT = 869, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCDSPLACEDFOOTPRINTFORMAT = 870, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_SRCREGIONOUTOFBOUNDS = 871, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTCOORDINATES = 872, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCBOX = 873, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_FORMATMISMATCH = 874, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_EMPTYBOX = 875, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDCOPYFLAGS = 876, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_SUBRESOURCE_INDEX = 877, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_FORMAT = 878, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_RESOURCE_MISMATCH = 879, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_SAMPLE_COUNT = 880, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_INVALID_SHADER = 881, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_CS_ROOT_SIGNATURE_MISMATCH = 882, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_MISSING_ROOT_SIGNATURE = 883, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALIDCACHEDBLOB = 884, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBADAPTERMISMATCH = 885, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBDRIVERVERSIONMISMATCH = 886, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBDESCMISMATCH = 887, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBIGNORED = 888, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDHEAP = 889, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDRESOURCE = 890, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDBOX = 891, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDSUBRESOURCE = 892, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_EMPTYBOX = 893, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDHEAP = 894, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDRESOURCE = 895, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDBOX = 896, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDSUBRESOURCE = 897, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_EMPTYBOX = 898, + D3D12_MESSAGE_ID_TOO_MANY_NODES_SPECIFIED = 899, + D3D12_MESSAGE_ID_INVALID_NODE_INDEX = 900, + D3D12_MESSAGE_ID_GETHEAPPROPERTIES_INVALIDRESOURCE = 901, + D3D12_MESSAGE_ID_NODE_MASK_MISMATCH = 902, + D3D12_MESSAGE_ID_COMMAND_LIST_OUTOFMEMORY = 903, + D3D12_MESSAGE_ID_COMMAND_LIST_MULTIPLE_SWAPCHAIN_BUFFER_REFERENCES = 904, + D3D12_MESSAGE_ID_COMMAND_LIST_TOO_MANY_SWAPCHAIN_REFERENCES = 905, + D3D12_MESSAGE_ID_COMMAND_QUEUE_TOO_MANY_SWAPCHAIN_REFERENCES = 906, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_WRONGSWAPCHAINBUFFERREFERENCE = 907, + D3D12_MESSAGE_ID_COMMAND_LIST_SETRENDERTARGETS_INVALIDNUMRENDERTARGETS = 908, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_TYPE = 909, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_FLAGS = 910, + D3D12_MESSAGE_ID_CREATESHAREDRESOURCE_INVALIDFLAGS = 911, + D3D12_MESSAGE_ID_CREATESHAREDRESOURCE_INVALIDFORMAT = 912, + D3D12_MESSAGE_ID_CREATESHAREDHEAP_INVALIDFLAGS = 913, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_UNRECOGNIZEDPROPERTIES = 914, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_INVALIDSIZE = 915, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_INVALIDOBJECT = 916, + D3D12_MESSAGE_ID_KEYEDMUTEX_INVALIDOBJECT = 917, + D3D12_MESSAGE_ID_KEYEDMUTEX_INVALIDKEY = 918, + D3D12_MESSAGE_ID_KEYEDMUTEX_WRONGSTATE = 919, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_PRIORITY = 920, + D3D12_MESSAGE_ID_OBJECT_DELETED_WHILE_STILL_IN_USE = 921, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALID_FLAGS = 922, + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_HAS_NO_RESOURCE = 923, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RENDER_TARGET_DELETED = 924, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_ALL_RENDER_TARGETS_HAVE_UNKNOWN_FORMAT = 925, + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_INTERSECTS_MULTIPLE_BUFFERS = 926, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_GPU_WRITTEN_READBACK_RESOURCE_MAPPED = 927, + D3D12_MESSAGE_ID_UNMAP_RANGE_NOT_NEEDED = 928, + D3D12_MESSAGE_ID_UNMAP_RANGE_NOT_EMPTY = 929, + D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE = 930, + D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE = 931, + D3D12_MESSAGE_ID_NO_GRAPHICS_API_SUPPORT = 932, + D3D12_MESSAGE_ID_NO_COMPUTE_API_SUPPORT = 933, + D3D12_MESSAGE_ID_D3D12_MESSAGES_END = 934, +}} +STRUCT!{struct D3D12_MESSAGE { + Category: D3D12_MESSAGE_CATEGORY, + Severity: D3D12_MESSAGE_SEVERITY, + ID: D3D12_MESSAGE_ID, + pDescription: *const ::c_char, + DescriptionByteLength: ::SIZE_T, +}} +STRUCT!{struct D3D12_INFO_QUEUE_FILTER_DESC { + NumCategories: ::UINT, + pCategoryList: *mut D3D12_MESSAGE_CATEGORY, + NumSeverities: ::UINT, + pSeverityList: *mut D3D12_MESSAGE_SEVERITY, + NumIDs: ::UINT, + pIDList: *mut D3D12_MESSAGE_ID, +}} +STRUCT!{struct D3D12_INFO_QUEUE_FILTER { + AllowList: D3D12_INFO_QUEUE_FILTER_DESC, + DenyList: D3D12_INFO_QUEUE_FILTER_DESC, +}} +pub const D3D12_INFO_QUEUE_DEFAULT_MESSAGE_COUNT_LIMIT: ::UINT = 1024; +RIDL!{interface ID3D12InfoQueue(ID3D12InfoQueueVtbl): IUnknown(IUnknownVtbl) { + fn SetMessageCountLimit(&mut self, MessageCountLimit: ::UINT64) -> ::HRESULT, + fn ClearStoredMessages(&mut self) -> (), + fn GetMessage( + &mut self, MessageIndex: ::UINT64, pMessage: *mut ::D3D12_MESSAGE, + pMessageByteLength: *mut ::SIZE_T + ) -> ::HRESULT, + fn GetNumMessagesAllowedByStorageFilter(&mut self) -> ::UINT64, + fn GetNumMessagesDeniedByStorageFilter(&mut self) -> ::UINT64, + fn GetNumStoredMessages(&mut self) -> ::UINT64, + fn GetNumStoredMessagesAllowedByRetrievalFilter(&mut self) -> ::UINT64, + fn GetNumMessagesDiscardedByMessageCountLimit(&mut self) -> ::UINT64, + fn GetMessageCountLimit(&mut self) -> ::UINT64, + fn AddStorageFilterEntries(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn GetStorageFilter( + &mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER, pFilterByteLength: *mut ::SIZE_T + ) -> ::HRESULT, + fn ClearStorageFilter(&mut self) -> (), + fn PushEmptyStorageFilter(&mut self) -> ::HRESULT, + fn PushCopyOfStorageFilter(&mut self) -> ::HRESULT, + fn PushStorageFilter(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn PopStorageFilter(&mut self) -> (), + fn GetStorageFilterStackSize(&mut self) -> ::UINT, + fn AddRetrievalFilterEntries(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn GetRetrievalFilter( + &mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER, pFilterByteLength: *mut ::SIZE_T + ) -> ::HRESULT, + fn ClearRetrievalFilter(&mut self) -> (), + fn PushEmptyRetrievalFilter(&mut self) -> ::HRESULT, + fn PushCopyOfRetrievalFilter(&mut self) -> ::HRESULT, + fn PushRetrievalFilter(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn PopRetrievalFilter(&mut self) -> (), + fn GetRetrievalFilterStackSize(&mut self) -> ::UINT, + fn AddMessage( + &mut self, Category: ::D3D12_MESSAGE_CATEGORY, Severity: ::D3D12_MESSAGE_SEVERITY, + ID: ::D3D12_MESSAGE_ID, pDescription: ::LPCSTR + ) -> ::HRESULT, + fn AddApplicationMessage( + &mut self, Severity: ::D3D12_MESSAGE_SEVERITY, pDescription: ::LPCSTR + ) -> ::HRESULT, + fn SetBreakOnCategory( + &mut self, Category: ::D3D12_MESSAGE_CATEGORY, bEnable: ::BOOL + ) -> ::HRESULT, + fn SetBreakOnSeverity( + &mut self, Severity: ::D3D12_MESSAGE_SEVERITY, bEnable: ::BOOL + ) -> ::HRESULT, + fn SetBreakOnID(&mut self, ID: ::D3D12_MESSAGE_ID, bEnable: ::BOOL) -> ::HRESULT, + fn GetBreakOnCategory(&mut self, Category: ::D3D12_MESSAGE_CATEGORY) -> ::BOOL, + fn GetBreakOnSeverity(&mut self, Severity: ::D3D12_MESSAGE_SEVERITY) -> ::BOOL, + fn GetBreakOnID(&mut self, ID: ::D3D12_MESSAGE_ID) -> ::BOOL, + fn SetMuteDebugOutput(&mut self, bMute: ::BOOL) -> (), + fn GetMuteDebugOutput(&mut self) -> ::BOOL +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d12shader.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d12shader.rs new file mode 100644 index 0000000..bd210b2 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d12shader.rs @@ -0,0 +1,320 @@ +// Copyright © 2016; Dmitry Roschin +// Licensed under the MIT License <LICENSE.md> +FLAGS!{ enum D3D12_SHADER_VERSION_TYPE { + D3D12_SHVER_PIXEL_SHADER = 0x0, + D3D12_SHVER_VERTEX_SHADER = 0x1, + D3D12_SHVER_GEOMETRY_SHADER = 0x2, + D3D12_SHVER_HULL_SHADER = 0x3, + D3D12_SHVER_DOMAIN_SHADER = 0x4, + D3D12_SHVER_COMPUTE_SHADER = 0x5, + D3D12_SHVER_RESERVED0 = 0xFFF0, +}} + +STRUCT!{struct D3D12_FUNCTION_DESC { + Version: ::UINT, + Creator: ::LPCSTR, + Flags: ::UINT, + ConstantBuffers: ::UINT, + BoundResources: ::UINT, + InstructionCount: ::UINT, + TempRegisterCount: ::UINT, + TempArrayCount: ::UINT, + DefCount: ::UINT, + DclCount: ::UINT, + TextureNormalInstructions: ::UINT, + TextureLoadInstructions: ::UINT, + TextureCompInstructions: ::UINT, + TextureBiasInstructions: ::UINT, + TextureGradientInstructions: ::UINT, + FloatInstructionCount: ::UINT, + IntInstructionCount: ::UINT, + UintInstructionCount: ::UINT, + StaticFlowControlCount: ::UINT, + DynamicFlowControlCount: ::UINT, + MacroInstructionCount: ::UINT, + ArrayInstructionCount: ::UINT, + MovInstructionCount: ::UINT, + MovcInstructionCount: ::UINT, + ConversionInstructionCount: ::UINT, + BitwiseInstructionCount: ::UINT, + MinFeatureLevel: ::D3D_FEATURE_LEVEL, + RequiredFeatureFlags: ::UINT64, + Name: ::LPCSTR, + FunctionParameterCount: ::INT, + HasReturn: ::BOOL, + Has10Level9VertexShader: ::BOOL, + Has10Level9PixelShader: ::BOOL, +}} + +STRUCT!{struct D3D12_LIBRARY_DESC { + Creator: ::LPCSTR, + Flags: ::UINT, + FunctionCount: ::UINT, +}} + +STRUCT!{struct D3D12_PARAMETER_DESC { + Name: ::LPCSTR, + SemanticName: ::LPCSTR, + Type: ::D3D_SHADER_VARIABLE_TYPE, + Class: ::D3D_SHADER_VARIABLE_CLASS, + Rows: ::UINT, + Columns: ::UINT, + InterpolationMode: ::D3D_INTERPOLATION_MODE, + Flags: ::D3D_PARAMETER_FLAGS, + FirstInRegister: ::UINT, + FirstInComponent: ::UINT, + FirstOutRegister: ::UINT, + FirstOutComponent: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_BUFFER_DESC { + Name: ::LPCSTR, + Type: ::D3D_CBUFFER_TYPE, + Variables: ::UINT, + Size: ::UINT, + uFlags: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_DESC { + Version: ::UINT, + Creator: ::LPCSTR, + Flags: ::UINT, + ConstantBuffers: ::UINT, + BoundResources: ::UINT, + InputParameters: ::UINT, + OutputParameters: ::UINT, + InstructionCount: ::UINT, + TempRegisterCount: ::UINT, + TempArrayCount: ::UINT, + DefCount: ::UINT, + DclCount: ::UINT, + TextureNormalInstructions: ::UINT, + TextureLoadInstructions: ::UINT, + TextureCompInstructions: ::UINT, + TextureBiasInstructions: ::UINT, + TextureGradientInstructions: ::UINT, + FloatInstructionCount: ::UINT, + IntInstructionCount: ::UINT, + UintInstructionCount: ::UINT, + StaticFlowControlCount: ::UINT, + DynamicFlowControlCount: ::UINT, + MacroInstructionCount: ::UINT, + ArrayInstructionCount: ::UINT, + CutInstructionCount: ::UINT, + EmitInstructionCount: ::UINT, + GSOutputTopology: ::D3D_PRIMITIVE_TOPOLOGY, + GSMaxOutputVertexCount: ::UINT, + InputPrimitive: ::D3D_PRIMITIVE, + PatchConstantParameters: ::UINT, + cGSInstanceCount: ::UINT, + cControlPoints: ::UINT, + HSOutputPrimitive: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE, + HSPartitioning: ::D3D_TESSELLATOR_PARTITIONING, + TessellatorDomain: ::D3D_TESSELLATOR_DOMAIN, + cBarrierInstructions: ::UINT, + cInterlockedInstructions: ::UINT, + cTextureStoreInstructions: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_INPUT_BIND_DESC { + Name: ::LPCSTR, + Type: ::D3D_SHADER_INPUT_TYPE, + BindPoint: ::UINT, + BindCount: ::UINT, + uFlags: ::UINT, + ReturnType: ::D3D_RESOURCE_RETURN_TYPE, + Dimension: ::D3D_SRV_DIMENSION, + NumSamples: ::UINT, + Space: ::UINT, + uID: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_TYPE_DESC { + Class: ::D3D_SHADER_VARIABLE_CLASS, + Type: ::D3D_SHADER_VARIABLE_TYPE, + Rows: ::UINT, + Columns: ::UINT, + Elements: ::UINT, + Members: ::UINT, + Offset: ::UINT, + Name: ::LPCSTR, +}} + +STRUCT!{struct D3D12_SHADER_VARIABLE_DESC { + Name: ::LPCSTR, + StartOffset: ::UINT, + Size: ::UINT, + uFlags: ::UINT, + DefaultValue: ::LPVOID, + StartTexture: ::UINT, + TextureSize: ::UINT, + StartSampler: ::UINT, + SamplerSize: ::UINT, +}} + +STRUCT!{struct D3D12_SIGNATURE_PARAMETER_DESC { + SemanticName: ::LPCSTR, + SemanticIndex: ::UINT, + Register: ::UINT, + SystemValueType: ::D3D_NAME, + ComponentType: ::D3D_REGISTER_COMPONENT_TYPE, + Mask: ::BYTE, + ReadWriteMask: ::BYTE, + Stream: ::UINT, + MinPrecision: ::D3D_MIN_PRECISION, +}} + +RIDL!( +interface ID3D12FunctionParameterReflection(ID3D12FunctionParameterReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_PARAMETER_DESC) -> ::HRESULT +}); + +RIDL!( +interface ID3D12FunctionReflection(ID3D12FunctionReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_FUNCTION_DESC) -> ::HRESULT, + fn GetConstantBufferByIndex( + &mut self, BufferIndex: ::UINT + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: ::UINT, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetVariableByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: ::LPCSTR, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetFunctionParameter( + &mut self, ParameterIndex: ::INT + ) -> *mut ::ID3D12FunctionParameterReflection +}); + +RIDL!( +interface ID3D12LibraryReflection(ID3D12LibraryReflectionVtbl): IUnknown(IUnknownVtbl) { + fn QueryInterface( + &mut self, iid: *const ::IID, ppv: *mut ::LPVOID + ) -> ::HRESULT, + fn AddRef(&mut self) -> ::ULONG, + fn Release(&mut self) -> ::ULONG, + fn GetDesc(&mut self, pDesc: *mut ::D3D12_LIBRARY_DESC) -> ::HRESULT, + fn GetFunctionByIndex( + &mut self, FunctionIndex: ::INT + ) -> *mut ::ID3D12FunctionReflection +}); + +RIDL!( +interface ID3D12ShaderReflectionConstantBuffer(ID3D12ShaderReflectionConstantBufferVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_SHADER_BUFFER_DESC) -> ::HRESULT, + fn GetVariableByIndex( + &mut self, Index: ::UINT + ) -> *mut ::ID3D12ShaderReflectionVariable, + fn GetVariableByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionVariable +}); + +RIDL!( +interface ID3D12ShaderReflectionType(ID3D12ShaderReflectionTypeVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_SHADER_TYPE_DESC) -> ::HRESULT, + fn GetMemberTypeByIndex( + &mut self, Index: ::UINT + ) -> *mut ::ID3D12ShaderReflectionType, + fn GetMemberTypeByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionType, + fn GetMemberTypeName(&mut self, Index: ::UINT) -> ::LPCSTR, + fn IsEqual( + &mut self, pType: *mut ::ID3D12ShaderReflectionType + ) -> ::HRESULT, + fn GetSubType(&mut self) -> *mut ::ID3D12ShaderReflectionType, + fn GetBaseClass(&mut self) -> *mut ::ID3D12ShaderReflectionType, + fn GetNumInterfaces(&mut self) -> ::UINT, + fn GetInterfaceByIndex( + &mut self, uIndex: ::UINT + ) -> *mut ::ID3D12ShaderReflectionType, + fn IsOfType( + &mut self, pType: *mut ::ID3D12ShaderReflectionType + ) -> ::HRESULT, + fn ImplementsInterface( + &mut self, pBase: *mut ::ID3D12ShaderReflectionType + ) -> ::HRESULT +}); + +RIDL!( +interface ID3D12ShaderReflectionVariable(ID3D12ShaderReflectionVariableVtbl) { + fn GetDesc( + &mut self, pDesc: *mut ::D3D12_SHADER_VARIABLE_DESC + ) -> ::HRESULT, + fn GetType(&mut self) -> *mut ::ID3D12ShaderReflectionType, + fn GetBuffer(&mut self) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetInterfaceSlot(&mut self, uArrayIndex: ::UINT) -> ::UINT +}); + +RIDL!( +interface ID3D12ShaderReflection(ID3D12ShaderReflectionVtbl): IUnknown(IUnknownVtbl) { + fn QueryInterface( + &mut self, iid: *const ::IID, ppv: *mut ::LPVOID + ) -> ::HRESULT, + fn AddRef(&mut self) -> ::ULONG, + fn Release(&mut self) -> ::ULONG, + fn GetDesc(&mut self, pDesc: *mut ::D3D12_SHADER_DESC) -> ::HRESULT, + fn GetConstantBufferByIndex( + &mut self, Index: ::UINT + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: ::UINT, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetInputParameterDesc( + &mut self, ParameterIndex: ::UINT, pDesc: *mut ::D3D12_SIGNATURE_PARAMETER_DESC + ) -> ::HRESULT, + fn GetOutputParameterDesc( + &mut self, ParameterIndex: ::UINT, pDesc: *mut ::D3D12_SIGNATURE_PARAMETER_DESC + ) -> ::HRESULT, + fn GetPatchConstantParameterDesc( + &mut self, ParameterIndex: ::UINT, pDesc: *mut ::D3D12_SIGNATURE_PARAMETER_DESC + ) -> ::HRESULT, + fn GetVariableByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: ::LPCSTR, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetMovInstructionCount(&mut self) -> ::UINT, + fn GetMovcInstructionCount(&mut self) -> ::UINT, + fn GetConversionInstructionCount(&mut self) -> ::UINT, + fn GetBitwiseInstructionCount(&mut self) -> ::UINT, + fn GetGSInputPrimitive(&mut self) -> ::D3D_PRIMITIVE, + fn IsSampleFrequencyShader(&mut self) -> ::BOOL, + fn GetNumInterfaceSlots(&mut self) -> ::UINT, + fn GetMinFeatureLevel( + &mut self, pLevel: *mut ::D3D_FEATURE_LEVEL + ) -> ::HRESULT, + fn GetThreadGroupSize( + &mut self, pSizeX: *mut ::UINT, pSizeY: *mut ::UINT, pSizeZ: *mut ::UINT + ) -> ::UINT, + fn GetRequiresFlags(&mut self) -> ::UINT64 +}); + +pub type D3D12_CBUFFER_TYPE = ::D3D_CBUFFER_TYPE; +pub type D3D12_RESOURCE_RETURN_TYPE = ::D3D_RESOURCE_RETURN_TYPE; +pub type D3D12_TESSELLATOR_DOMAIN = ::D3D_TESSELLATOR_DOMAIN; +pub type D3D12_TESSELLATOR_OUTPUT_PRIMITIVE = ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE; +pub type D3D12_TESSELLATOR_PARTITIONING = ::D3D_TESSELLATOR_PARTITIONING; +pub type LPD3D12FUNCTIONPARAMETERREFLECTION = *mut ::ID3D12FunctionParameterReflection; +pub type LPD3D12FUNCTIONREFLECTION = *mut ::ID3D12FunctionReflection; +pub type LPD3D12LIBRARYREFLECTION = *mut ::ID3D12LibraryReflection; +pub type LPD3D12SHADERREFLECTION = *mut ::ID3D12ShaderReflection; +pub type LPD3D12SHADERREFLECTIONCONSTANTBUFFER = *mut ::ID3D12ShaderReflectionConstantBuffer; +pub type LPD3D12SHADERREFLECTIONTYPE = *mut ::ID3D12ShaderReflectionType; +pub type LPD3D12SHADERREFLECTIONVARIABLE = *mut ::ID3D12ShaderReflectionVariable; +pub const D3D_SHADER_REQUIRES_INNER_COVERAGE: ::UINT64 = 0x00000400; +pub const D3D_SHADER_REQUIRES_ROVS: ::UINT64 = 0x00001000; +pub const D3D_SHADER_REQUIRES_STENCIL_REF: ::UINT64 = 0x00000200; +pub const D3D_SHADER_REQUIRES_TYPED_UAV_LOAD_ADDITIONAL_FORMATS: ::UINT64 = 0x00000800; +pub const D3D_SHADER_REQUIRES_VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER: ::UINT64 = 0x00002000; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d9.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d9.rs new file mode 100644 index 0000000..26f9031 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d9.rs @@ -0,0 +1,713 @@ +// Copyright © 2015, Corey Richardson +// Licensed under the MIT License <LICENSE.md> +//! Direct3D include file +pub const D3D_SDK_VERSION: ::DWORD = 32; +pub const D3D9b_SDK_VERSION: ::DWORD = 31; +RIDL!( +interface IDirect3D9(IDirect3D9Vtbl): IUnknown(IUnknownVtbl) { + fn RegisterSoftwareDevice(&mut self, pInitializeFunction: *mut ::VOID) -> ::HRESULT, + fn GetAdapterCount(&mut self) -> ::UINT, + fn GetAdapterIdentifier( + &mut self, Adapter: ::UINT, Flags: ::DWORD, pIdentifier: *mut ::D3DADAPTER_IDENTIFIER9 + ) -> ::HRESULT, + fn GetAdapterModeCount(&mut self, Adapter: ::UINT, Format: ::D3DFORMAT) -> ::UINT, + fn EnumAdapterModes( + &mut self, Adapter: ::UINT, Format: ::D3DFORMAT, Mode: ::UINT, pMode: *mut ::D3DDISPLAYMODE + ) -> ::HRESULT, + fn GetAdapterDisplayMode( + &mut self, Adapter: ::UINT, pMode: *mut ::D3DDISPLAYMODE + ) -> ::HRESULT, + fn CheckDeviceType( + &mut self, Adapter: ::UINT, DevType: ::D3DDEVTYPE, AdapterFormat: ::D3DFORMAT, + BackBufferFormat: ::D3DFORMAT, bWindowed: ::BOOL + ) -> ::HRESULT, + fn CheckDeviceFormat( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, AdapterFormat: ::D3DFORMAT, + Usage: ::DWORD, RType: ::D3DRESOURCETYPE, CheckFormat: ::D3DFORMAT + ) -> ::HRESULT, + fn CheckDeviceMultiSampleType( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, SurfaceFormat: ::D3DFORMAT, + Windowed: ::BOOL, MultiSampleType: ::D3DMULTISAMPLE_TYPE, pQualityLevels: *mut ::DWORD + ) -> ::HRESULT, + fn CheckDepthStencilMatch( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, AdapterFormat: ::D3DFORMAT, + RenderTargetFormat: ::D3DFORMAT, DepthStencilFormat: ::D3DFORMAT + ) -> ::HRESULT, + fn CheckDeviceFormatConversion( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, SourceFormat: ::D3DFORMAT, + TargetFormat: ::D3DFORMAT + ) -> ::HRESULT, + fn GetDeviceCaps( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, pCaps: *mut ::D3DCAPS9 + ) -> ::HRESULT, + fn GetAdapterMonitor(&mut self, Adapter: ::UINT) -> ::HMONITOR, + fn CreateDevice( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, hFocusWindow: ::HWND, + BehaviorFlags: ::DWORD, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + ppReturnedDeviceInterface: *mut *mut IDirect3DDevice9 + ) -> ::HRESULT +} +); +pub type LPDIRECT3D9 = *mut IDirect3D9; +pub type PDIRECT3D9 = *mut IDirect3D9; +RIDL!( +interface IDirect3DDevice9(IDirect3DDevice9Vtbl): IUnknown(IUnknownVtbl) { + fn TestCooperativeLevel(&mut self) -> ::HRESULT, + fn GetAvailableTextureMem(&mut self) -> ::UINT, + fn EvictManagedResources(&mut self) -> ::HRESULT, + fn GetDirect3D(&mut self, ppD3D9: *mut *mut IDirect3D9) -> ::HRESULT, + fn GetDeviceCaps(&mut self, pCaps: *mut ::D3DCAPS9) -> ::HRESULT, + fn GetDisplayMode(&mut self, iSwapChain: ::UINT, pMode: *mut ::D3DDISPLAYMODE) -> ::HRESULT, + fn GetCreationParameters( + &mut self, pParameters: *mut ::D3DDEVICE_CREATION_PARAMETERS + ) -> ::HRESULT, + fn SetCursorProperties( + &mut self, XHotSpot: ::UINT, YHotSpot: ::UINT, pCursorBitmap: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn SetCursorPosition(&mut self, X: ::INT, Y: ::INT, Flags: ::DWORD) -> (), + fn ShowCursor(&mut self, bShow: ::BOOL) -> ::BOOL, + fn CreateAdditionalSwapChain( + &mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + pSwapChain: *mut *mut IDirect3DSwapChain9 + ) -> ::HRESULT, + fn GetSwapChain( + &mut self, iSwapChain: ::UINT, pSwapChain: *mut *mut IDirect3DSwapChain9 + ) -> ::HRESULT, + fn GetNumberOfSwapChains(&mut self) -> ::UINT, + fn Reset(&mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS) -> ::HRESULT, + fn Present( + &mut self, pSourceRect: *const ::RECT, pDestRect: *const ::RECT, + hDestWindowOverride: ::HWND, pDirtyRegion: *const ::RGNDATA + ) -> ::HRESULT, + fn GetBackBuffer( + &mut self, iSwapChain: ::UINT, iBackBuffer: ::UINT, Type: ::D3DBACKBUFFER_TYPE, + ppBackBuffer: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetRasterStatus( + &mut self, iSwapChain: ::UINT, pRasterStatus: *mut ::D3DRASTER_STATUS + ) -> ::HRESULT, + fn SetDialogBoxMode(&mut self, bEnableDialogs: ::BOOL) -> ::HRESULT, + fn SetGammaRamp( + &mut self, iSwapChain: ::UINT, Flags: ::DWORD, pRamp: *const ::D3DGAMMARAMP + ) -> (), + fn GetGammaRamp(&mut self, iSwapChain: ::UINT, pRamp: *mut ::D3DGAMMARAMP) -> (), + fn CreateTexture( + &mut self, Width: ::UINT, Height: ::UINT, Levels: ::UINT, Usage: ::DWORD, + Format: ::D3DFORMAT, Pool: ::D3DPOOL, ppTexture: *mut *mut IDirect3DTexture9, + pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateVolumeTexture( + &mut self, Width: ::UINT, Height: ::UINT, Depth: ::UINT, Levels: ::UINT, Usage: ::DWORD, + Format: ::D3DFORMAT, Pool: ::D3DPOOL, ppVolumeTexture: *mut *mut IDirect3DVolumeTexture9, + pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateCubeTexture( + &mut self, EdgeLength: ::UINT, Levels: ::UINT, Usage: ::DWORD, Format: ::D3DFORMAT, + Pool: ::D3DPOOL, ppCubeTexture: *mut *mut IDirect3DCubeTexture9, + pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateVertexBuffer( + &mut self, Length: ::UINT, Usage: ::DWORD, FVF: ::DWORD, Pool: ::D3DPOOL, + ppVertexBuffer: *mut *mut IDirect3DVertexBuffer9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateIndexBuffer( + &mut self, Length: ::UINT, Usage: ::DWORD, Format: ::D3DFORMAT, Pool: ::D3DPOOL, + ppIndexBuffer: *mut *mut IDirect3DIndexBuffer9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateRenderTarget( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Lockable: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateDepthStencilSurface( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Discard: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn UpdateSurface( + &mut self, pSourceSurface: *mut IDirect3DSurface9, pSourceRect: *const ::RECT, + pDestinationSurface: *mut IDirect3DSurface9, pDestPoint: *const ::POINT + ) -> ::HRESULT, + fn UpdateTexture( + &mut self, pSourceTexture: *mut IDirect3DBaseTexture9, + pDestinationTexture: *mut IDirect3DBaseTexture9 + ) -> ::HRESULT, + fn GetRenderTargetData( + &mut self, pRenderTarget: *mut IDirect3DSurface9, pDestSurface: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetFrontBufferData( + &mut self, iSwapChain: ::UINT, pDestSurface: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn StretchRect( + &mut self, pSourceSurface: *mut IDirect3DSurface9, pSourceRect: *const ::RECT, + pDestSurface: *mut IDirect3DSurface9, pDestRect: *const ::RECT, + Filter: ::D3DTEXTUREFILTERTYPE + ) -> ::HRESULT, + fn ColorFill( + &mut self, pSurface: *mut IDirect3DSurface9, pRect: *const ::RECT, color: ::D3DCOLOR + ) -> ::HRESULT, + fn CreateOffscreenPlainSurface( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, Pool: ::D3DPOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn SetRenderTarget( + &mut self, RenderTargetIndex: ::DWORD, pRenderTarget: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetRenderTarget( + &mut self, RenderTargetIndex: ::DWORD, ppRenderTarget: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn SetDepthStencilSurface(&mut self, pNewZStencil: *mut IDirect3DSurface9) -> ::HRESULT, + fn GetDepthStencilSurface( + &mut self, ppZStencilSurface: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn BeginScene(&mut self) -> ::HRESULT, + fn EndScene(&mut self) -> ::HRESULT, + fn Clear( + &mut self, Count: ::DWORD, pRects: *const ::D3DRECT, Flags: ::DWORD, Color: ::D3DCOLOR, + Z: ::FLOAT, Stencil: ::DWORD + ) -> ::HRESULT, + fn SetTransform( + &mut self, State: ::D3DTRANSFORMSTATETYPE, pMatrix: *const ::D3DMATRIX + ) -> ::HRESULT, + fn GetTransform( + &mut self, State: ::D3DTRANSFORMSTATETYPE, pMatrix: *mut ::D3DMATRIX + ) -> ::HRESULT, + fn MultiplyTransform( + &mut self, arg1: ::D3DTRANSFORMSTATETYPE, arg2: *const ::D3DMATRIX + ) -> ::HRESULT, + fn SetViewport(&mut self, pViewport: *const ::D3DVIEWPORT9) -> ::HRESULT, + fn GetViewport(&mut self, pViewport: *mut ::D3DVIEWPORT9) -> ::HRESULT, + fn SetMaterial(&mut self, pMaterial: *const ::D3DMATERIAL9) -> ::HRESULT, + fn GetMaterial(&mut self, pMaterial: *mut ::D3DMATERIAL9) -> ::HRESULT, + fn SetLight(&mut self, Index: ::DWORD, arg1: *const ::D3DLIGHT9) -> ::HRESULT, + fn GetLight(&mut self, Index: ::DWORD, arg1: *mut ::D3DLIGHT9) -> ::HRESULT, + fn LightEnable(&mut self, Index: ::DWORD, Enable: ::BOOL) -> ::HRESULT, + fn GetLightEnable(&mut self, Index: ::DWORD, pEnable: *mut ::BOOL) -> ::HRESULT, + fn SetClipPlane(&mut self, Index: ::DWORD, pPlane: *const ::FLOAT) -> ::HRESULT, + fn GetClipPlane(&mut self, Index: ::DWORD, pPlane: *mut ::FLOAT) -> ::HRESULT, + fn SetRenderState(&mut self, State: ::D3DRENDERSTATETYPE, Value: ::DWORD) -> ::HRESULT, + fn GetRenderState(&mut self, State: ::D3DRENDERSTATETYPE, pValue: *mut ::DWORD) -> ::HRESULT, + fn CreateStateBlock( + &mut self, Type: ::D3DSTATEBLOCKTYPE, ppSB: *mut *mut IDirect3DStateBlock9 + ) -> ::HRESULT, + fn BeginStateBlock(&mut self) -> ::HRESULT, + fn EndStateBlock(&mut self, ppSB: *mut *mut IDirect3DStateBlock9) -> ::HRESULT, + fn SetClipStatus(&mut self, pClipStatus: *const ::D3DCLIPSTATUS9) -> ::HRESULT, + fn GetClipStatus(&mut self, pClipStatus: *mut ::D3DCLIPSTATUS9) -> ::HRESULT, + fn GetTexture( + &mut self, Stage: ::DWORD, ppTexture: *mut *mut IDirect3DBaseTexture9 + ) -> ::HRESULT, + fn SetTexture(&mut self, Stage: ::DWORD, pTexture: *mut IDirect3DBaseTexture9) -> ::HRESULT, + fn GetTextureStageState( + &mut self, Stage: ::DWORD, Type: ::D3DTEXTURESTAGESTATETYPE, pValue: *mut ::DWORD + ) -> ::HRESULT, + fn SetTextureStageState( + &mut self, Stage: ::DWORD, Type: ::D3DTEXTURESTAGESTATETYPE, Value: ::DWORD + ) -> ::HRESULT, + fn GetSamplerState( + &mut self, Sampler: ::DWORD, Type: ::D3DSAMPLERSTATETYPE, pValue: *mut ::DWORD + ) -> ::HRESULT, + fn SetSamplerState( + &mut self, Sampler: ::DWORD, Type: ::D3DSAMPLERSTATETYPE, Value: ::DWORD + ) -> ::HRESULT, + fn ValidateDevice(&mut self, pNumPasses: *mut ::DWORD) -> ::HRESULT, + fn SetPaletteEntries( + &mut self, PaletteNumber: ::UINT, pEntries: *const ::PALETTEENTRY + ) -> ::HRESULT, + fn GetPaletteEntries( + &mut self, PaletteNumber: ::UINT, pEntries: *mut ::PALETTEENTRY + ) -> ::HRESULT, + fn SetCurrentTexturePalette(&mut self, PaletteNumber: ::UINT) -> ::HRESULT, + fn GetCurrentTexturePalette(&mut self, PaletteNumber: *mut ::UINT) -> ::HRESULT, + fn SetScissorRect(&mut self, pRect: *const ::RECT) -> ::HRESULT, + fn GetScissorRect(&mut self, pRect: *mut ::RECT) -> ::HRESULT, + fn SetSoftwareVertexProcessing(&mut self, bSoftware: ::BOOL) -> ::HRESULT, + fn GetSoftwareVertexProcessing(&mut self) -> ::BOOL, + fn SetNPatchMode(&mut self, nSegments: ::FLOAT) -> ::HRESULT, + fn GetNPatchMode(&mut self) -> ::FLOAT, + fn DrawPrimitive( + &mut self, PrimitiveType: ::D3DPRIMITIVETYPE, StartVertex: ::UINT, PrimitiveCount: ::UINT + ) -> ::HRESULT, + fn DrawIndexedPrimitive( + &mut self, arg1: ::D3DPRIMITIVETYPE, BaseVertexIndex: ::INT, MinVertexIndex: ::UINT, + NumVertices: ::UINT, startIndex: ::UINT, primCount: ::UINT + ) -> ::HRESULT, + fn DrawPrimitiveUP( + &mut self, PrimitiveType: ::D3DPRIMITIVETYPE, PrimitiveCount: ::UINT, + pVertexStreamZeroData: *const ::VOID, VertexStreamZeroStride: ::UINT + ) -> ::HRESULT, + fn DrawIndexedPrimitiveUP( + &mut self, PrimitiveType: ::D3DPRIMITIVETYPE, MinVertexIndex: ::UINT, NumVertices: ::UINT, + PrimitiveCount: ::UINT, pIndexData: *const ::VOID, IndexDataFormat: ::D3DFORMAT, + pVertexStreamZeroData: *const ::VOID, VertexStreamZeroStride: ::UINT + ) -> ::HRESULT, + fn ProcessVertices( + &mut self, SrcStartIndex: ::UINT, DestIndex: ::UINT, VertexCount: ::UINT, + pDestBuffer: *mut IDirect3DVertexBuffer9, pVertexDecl: *mut IDirect3DVertexDeclaration9, + Flags: ::DWORD + ) -> ::HRESULT, + fn CreateVertexDeclaration( + &mut self, pVertexElements: *const ::D3DVERTEXELEMENT9, + ppDecl: *mut *mut IDirect3DVertexDeclaration9 + ) -> ::HRESULT, + fn SetVertexDeclaration(&mut self, pDecl: *mut IDirect3DVertexDeclaration9) -> ::HRESULT, + fn GetVertexDeclaration(&mut self, ppDecl: *mut *mut IDirect3DVertexDeclaration9) -> ::HRESULT, + fn SetFVF(&mut self, FVF: ::DWORD) -> ::HRESULT, + fn GetFVF(&mut self, pFVF: *mut ::DWORD) -> ::HRESULT, + fn CreateVertexShader( + &mut self, pFunction: *const ::DWORD, ppShader: *mut *mut IDirect3DVertexShader9 + ) -> ::HRESULT, + fn SetVertexShader(&mut self, pShader: *mut IDirect3DVertexShader9) -> ::HRESULT, + fn GetVertexShader(&mut self, ppShader: *mut *mut IDirect3DVertexShader9) -> ::HRESULT, + fn SetVertexShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *const ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn GetVertexShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn SetVertexShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *const ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn GetVertexShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn SetVertexShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *const ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn GetVertexShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn SetStreamSource( + &mut self, StreamNumber: ::UINT, pStreamData: *mut IDirect3DVertexBuffer9, + OffsetInBytes: ::UINT, Stride: ::UINT + ) -> ::HRESULT, + fn GetStreamSource( + &mut self, StreamNumber: ::UINT, ppStreamData: *mut *mut IDirect3DVertexBuffer9, + pOffsetInBytes: *mut ::UINT, pStride: *mut ::UINT + ) -> ::HRESULT, + fn SetStreamSourceFreq(&mut self, StreamNumber: ::UINT, Setting: ::UINT) -> ::HRESULT, + fn GetStreamSourceFreq(&mut self, StreamNumber: ::UINT, pSetting: *mut ::UINT) -> ::HRESULT, + fn SetIndices(&mut self, pIndexData: *mut IDirect3DIndexBuffer9) -> ::HRESULT, + fn GetIndices(&mut self, ppIndexData: *mut *mut IDirect3DIndexBuffer9) -> ::HRESULT, + fn CreatePixelShader( + &mut self, pFunction: *const ::DWORD, ppShader: *mut *mut IDirect3DPixelShader9 + ) -> ::HRESULT, + fn SetPixelShader(&mut self, pShader: *mut IDirect3DPixelShader9) -> ::HRESULT, + fn GetPixelShader(&mut self, ppShader: *mut *mut IDirect3DPixelShader9) -> ::HRESULT, + fn SetPixelShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *const ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn GetPixelShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn SetPixelShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *const ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn GetPixelShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn SetPixelShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *const ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn GetPixelShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn DrawRectPatch( + &mut self, Handle: ::UINT, pNumSegs: *const ::FLOAT, + pRectPatchInfo: *const ::D3DRECTPATCH_INFO + ) -> ::HRESULT, + fn DrawTriPatch( + &mut self, Handle: ::UINT, pNumSegs: *const ::FLOAT, + pTriPatchInfo: *const ::D3DTRIPATCH_INFO + ) -> ::HRESULT, + fn DeletePatch(&mut self, Handle: ::UINT) -> ::HRESULT, + fn CreateQuery( + &mut self, Type: ::D3DQUERYTYPE, ppQuery: *mut *mut IDirect3DQuery9 + ) -> ::HRESULT +} +); +pub type LPDIRECT3DDEVICE9 = *mut IDirect3DDevice9; +pub type PDIRECT3DDEVICE9 = *mut IDirect3DDevice9; +RIDL!( +interface IDirect3DStateBlock9(IDirect3DStateBlock9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn Capture(&mut self) -> ::HRESULT, + fn Apply(&mut self) -> ::HRESULT +} +); +pub type LPDIRECT3DSTATEBLOCK9 = *mut IDirect3DStateBlock9; +pub type PDIRECT3DSTATEBLOCK9 = *mut IDirect3DStateBlock9; +RIDL!( +interface IDirect3DSwapChain9(IDirect3DSwapChain9Vtbl): IUnknown(IUnknownVtbl) { + fn Present( + &mut self, pSourceRect: *const ::RECT, pDestRect: *const ::RECT, + hDestWindowOverride: ::HWND, pDirtyRegion: *const ::RGNDATA, dwFlags: ::DWORD + ) -> ::HRESULT, + fn GetFrontBufferData(&mut self, pDestSurface: *mut IDirect3DSurface9) -> ::HRESULT, + fn GetBackBuffer( + &mut self, iBackBuffer: ::UINT, Type: ::D3DBACKBUFFER_TYPE, + ppBackBuffer: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetRasterStatus(&mut self, pRasterStatus: *mut ::D3DRASTER_STATUS) -> ::HRESULT, + fn GetDisplayMode(&mut self, pMode: *mut ::D3DDISPLAYMODE) -> ::HRESULT, + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetPresentParameters( + &mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS + ) -> ::HRESULT +} +); +pub type LPDIRECT3DSWAPCHAIN9 = *mut IDirect3DSwapChain9; +pub type PDIRECT3DSWAPCHAIN9 = *mut IDirect3DSwapChain9; +RIDL!( +interface IDirect3DResource9(IDirect3DResource9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn SetPrivateData( + &mut self, refguid: *const ::GUID, pData: *const ::VOID, SizeOfData: ::DWORD, + Flags: ::DWORD + ) -> ::HRESULT, + fn GetPrivateData( + &mut self, refguid: *const ::GUID, pData: *mut ::VOID, pSizeOfData: *mut ::DWORD + ) -> ::HRESULT, + fn FreePrivateData(&mut self, refguid: *const ::GUID) -> ::HRESULT, + fn SetPriority(&mut self, PriorityNew: ::DWORD) -> ::DWORD, + fn GetPriority(&mut self) -> ::DWORD, + fn PreLoad(&mut self) -> (), + fn GetType(&mut self) -> ::D3DRESOURCETYPE +} +); +pub type LPDIRECT3DRESOURCE9 = *mut IDirect3DResource9; +pub type PDIRECT3DRESOURCE9 = *mut IDirect3DResource9; +RIDL!( +interface IDirect3DVertexDeclaration9(IDirect3DVertexDeclaration9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetDeclaration( + &mut self, pElement: *mut ::D3DVERTEXELEMENT9, pNumElements: *mut ::UINT + ) -> ::HRESULT +} +); +pub type LPDIRECT3DVERTEXDECLARATION9 = *mut IDirect3DVertexDeclaration9; +pub type PDIRECT3DVERTEXDECLARATION9 = *mut IDirect3DVertexDeclaration9; +RIDL!( +interface IDirect3DVertexShader9(IDirect3DVertexShader9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetFunction(&mut self, arg1: *mut ::VOID, pSizeOfData: *mut ::UINT) -> ::HRESULT +} +); +pub type LPDIRECT3DVERTEXSHADER9 = *mut IDirect3DVertexShader9; +pub type PDIRECT3DVERTEXSHADER9 = *mut IDirect3DVertexShader9; +RIDL!( +interface IDirect3DPixelShader9(IDirect3DPixelShader9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetFunction(&mut self, arg1: *mut ::VOID, pSizeOfData: *mut ::UINT) -> ::HRESULT +} +); +pub type LPDIRECT3DPIXELSHADER9 = *mut IDirect3DPixelShader9; +pub type PDIRECT3DPIXELSHADER9 = *mut IDirect3DPixelShader9; +RIDL!( +interface IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn SetLOD(&mut self, LODNew: ::DWORD) -> ::DWORD, + fn GetLOD(&mut self) -> ::DWORD, + fn GetLevelCount(&mut self) -> ::DWORD, + fn SetAutoGenFilterType(&mut self, FilterType: ::D3DTEXTUREFILTERTYPE) -> ::HRESULT, + fn GetAutoGenFilterType(&mut self) -> ::D3DTEXTUREFILTERTYPE, + fn GenerateMipSubLevels(&mut self) -> () +} +); +pub type LPDIRECT3DBASETEXTURE9 = *mut IDirect3DBaseTexture9; +pub type PDIRECT3DBASETEXTURE9 = *mut IDirect3DBaseTexture9; +RIDL!( +interface IDirect3DTexture9(IDirect3DTexture9Vtbl): IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl) { + fn GetLevelDesc(&mut self, Level: ::UINT, pDesc: *mut ::D3DSURFACE_DESC) -> ::HRESULT, + fn GetSurfaceLevel( + &mut self, Level: ::UINT, ppSurfaceLevel: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn LockRect( + &mut self, Level: ::UINT, pLockedRect: *mut ::D3DLOCKED_RECT, pRect: *const ::RECT, + Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockRect(&mut self, Level: ::UINT) -> ::HRESULT, + fn AddDirtyRect(&mut self, pDirtyRect: *const ::RECT) -> ::HRESULT +} +); +pub type LPDIRECT3DTEXTURE9 = *mut IDirect3DTexture9; +pub type PDIRECT3DTEXTURE9 = *mut IDirect3DTexture9; +RIDL!( +interface IDirect3DVolumeTexture9(IDirect3DVolumeTexture9Vtbl): IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl) { + fn GetLevelDesc(&mut self, Level: ::UINT, pDesc: *mut ::D3DVOLUME_DESC) -> ::HRESULT, + fn GetVolumeLevel( + &mut self, Level: ::UINT, ppVolumeLevel: *mut *mut IDirect3DVolume9 + ) -> ::HRESULT, + fn LockBox( + &mut self, Level: ::UINT, pLockedVolume: *mut ::D3DLOCKED_BOX, pBox: *const ::D3DBOX, + Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockBox(&mut self, Level: ::UINT) -> ::HRESULT, + fn AddDirtyBox(&mut self, pDirtyBox: *const ::D3DBOX) -> ::HRESULT +} +); +pub type LPDIRECT3DVOLUMETEXTURE9 = *mut IDirect3DVolumeTexture9; +pub type PDIRECT3DVOLUMETEXTURE9 = *mut IDirect3DVolumeTexture9; +RIDL!( +interface IDirect3DCubeTexture9(IDirect3DCubeTexture9Vtbl): IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl) { + fn GetLevelDesc(&mut self, Level: ::UINT, pDesc: *mut ::D3DSURFACE_DESC) -> ::HRESULT, + fn GetCubeMapSurface( + &mut self, FaceType: ::D3DCUBEMAP_FACES, Level: ::UINT, + ppCubeMapSurface: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn LockRect( + &mut self, FaceType: ::D3DCUBEMAP_FACES, Level: ::UINT, pLockedRect: *mut ::D3DLOCKED_RECT, + pRect: *const ::RECT, Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockRect(&mut self, FaceType: ::D3DCUBEMAP_FACES, Level: ::UINT) -> ::HRESULT, + fn AddDirtyRect( + &mut self, FaceType: ::D3DCUBEMAP_FACES, pDirtyRect: *const ::RECT + ) -> ::HRESULT +} +); +pub type LPDIRECT3DCUBETEXTURE9 = *mut IDirect3DCubeTexture9; +pub type PDIRECT3DCUBETEXTURE9 = *mut IDirect3DCubeTexture9; +RIDL!( +interface IDirect3DVertexBuffer9(IDirect3DVertexBuffer9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn Lock( + &mut self, OffsetToLock: ::UINT, SizeToLock: ::UINT, ppbData: *mut *mut ::VOID, + Flags: ::DWORD + ) -> ::HRESULT, + fn Unlock(&mut self) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DVERTEXBUFFER_DESC) -> ::HRESULT +} +); +pub type LPDIRECT3DVERTEXBUFFER9 = *mut IDirect3DVertexBuffer9; +pub type PDIRECT3DVERTEXBUFFER9 = *mut IDirect3DVertexBuffer9; +RIDL!( +interface IDirect3DIndexBuffer9(IDirect3DIndexBuffer9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn Lock( + &mut self, OffsetToLock: ::UINT, SizeToLock: ::UINT, ppbData: *mut *mut ::VOID, + Flags: ::DWORD + ) -> ::HRESULT, + fn Unlock(&mut self) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DINDEXBUFFER_DESC) -> ::HRESULT +} +); +pub type LPDIRECT3DINDEXBUFFER9 = *mut IDirect3DIndexBuffer9; +pub type PDIRECT3DINDEXBUFFER9 = *mut IDirect3DIndexBuffer9; +RIDL!( +interface IDirect3DSurface9(IDirect3DSurface9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn GetContainer(&mut self, riid: *const ::IID, ppContainer: *mut *mut ::VOID) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DSURFACE_DESC) -> ::HRESULT, + fn LockRect( + &mut self, pLockedRect: *mut ::D3DLOCKED_RECT, pRect: *const ::RECT, Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockRect(&mut self) -> ::HRESULT, + fn GetDC(&mut self, phdc: *mut ::HDC) -> ::HRESULT, + fn ReleaseDC(&mut self, hdc: ::HDC) -> ::HRESULT +} +); +pub type LPDIRECT3DSURFACE9 = *mut IDirect3DSurface9; +pub type PDIRECT3DSURFACE9 = *mut IDirect3DSurface9; +RIDL!( +interface IDirect3DVolume9(IDirect3DVolume9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn SetPrivateData( + &mut self, refguid: *const ::GUID, pData: *const ::VOID, SizeOfData: ::DWORD, + Flags: ::DWORD + ) -> ::HRESULT, + fn GetPrivateData( + &mut self, refguid: *const ::GUID, pData: *mut ::VOID, pSizeOfData: *mut ::DWORD + ) -> ::HRESULT, + fn FreePrivateData(&mut self, refguid: *const ::GUID) -> ::HRESULT, + fn GetContainer(&mut self, riid: *const ::IID, ppContainer: *mut *mut ::VOID) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DVOLUME_DESC) -> ::HRESULT, + fn LockBox( + &mut self, pLockedVolume: *mut ::D3DLOCKED_BOX, pBox: *const ::D3DBOX, Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockBox(&mut self) -> ::HRESULT +} +); +pub type LPDIRECT3DVOLUME9 = *mut IDirect3DVolume9; +pub type PDIRECT3DVOLUME9 = *mut IDirect3DVolume9; +RIDL!( +interface IDirect3DQuery9(IDirect3DQuery9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetType(&mut self) -> ::D3DRESOURCETYPE, + fn GetDataSize(&mut self) -> ::DWORD, + fn Issue(&mut self, dwIssueFlags: ::DWORD) -> ::HRESULT, + fn GetData( + &mut self, pData: *mut ::VOID, dwSize: ::DWORD, dwGetDataFlags: ::DWORD + ) -> ::HRESULT +} +); +pub type LPDIRECT3DQUERY9 = *mut IDirect3DQuery9; +pub type PDIRECT3DQUERY9 = *mut IDirect3DQuery9; +pub const D3DCREATE_FPU_PRESERVE: ::DWORD = 0x2; +pub const D3DCREATE_MULTITHREADED: ::DWORD = 0x4; +pub const D3DCREATE_PUREDEVICE: ::DWORD = 0x10; +pub const D3DCREATE_SOFTWARE_VERTEXPROCESSING: ::DWORD = 0x20; +pub const D3DCREATE_HARDWARE_VERTEXPROCESSING: ::DWORD = 0x40; +pub const D3DCREATE_MIXED_VERTEXPROCESSING: ::DWORD = 0x80; +pub const D3DCREATE_DISABLE_DRIVER_MANAGEMENT: ::DWORD = 0x100; +pub const D3DCREATE_ADAPTERGROUP_DEVICE: ::DWORD = 0x200; +pub const D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX: ::DWORD = 0x400; +pub const D3DCREATE_NOWINDOWCHANGES: ::DWORD = 0x800; +pub const D3DCREATE_DISABLE_PSGP_THREADING: ::DWORD = 0x2000; +pub const D3DCREATE_ENABLE_PRESENTSTATS: ::DWORD = 0x4000; +pub const D3DCREATE_DISABLE_PRESENTSTATS: ::DWORD = 0x8000; +pub const D3DCREATE_SCREENSAVER: ::DWORD = 0x10000000; +pub const D3DADAPTER_DEFAULT: ::DWORD = 0; +RIDL!( +interface IDirect3D9Ex(IDirect3D9ExVtbl): IDirect3D9(IDirect3D9Vtbl) { + fn GetAdapterModeCountEx( + &mut self, Adapter: ::UINT, pFilter: *const ::D3DDISPLAYMODEFILTER + ) -> ::UINT, + fn EnumAdapterModesEx( + &mut self, Adapter: ::UINT, pFilter: *const ::D3DDISPLAYMODEFILTER, Mode: ::UINT, + pMode: *mut ::D3DDISPLAYMODEEX + ) -> ::HRESULT, + fn GetAdapterDisplayModeEx( + &mut self, Adapter: ::UINT, pMode: *mut ::D3DDISPLAYMODEEX, + pRotation: *mut ::D3DDISPLAYROTATION + ) -> ::HRESULT, + fn CreateDeviceEx( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, hFocusWindow: ::HWND, + BehaviorFlags: ::DWORD, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + pFullscreenDisplayMode: *mut ::D3DDISPLAYMODEEX, + ppReturnedDeviceInterface: *mut *mut IDirect3DDevice9Ex + ) -> ::HRESULT, + fn GetAdapterLUID(&mut self, Adapter: ::UINT, pLUID: *mut ::LUID) -> ::HRESULT +} +); +pub type LPDIRECT3D9EX = *mut IDirect3D9Ex; +pub type PDIRECT3D9EX = *mut IDirect3D9Ex; +RIDL!( +interface IDirect3DDevice9Ex(IDirect3DDevice9ExVtbl): IDirect3DDevice9(IDirect3DDevice9Vtbl) { + fn SetConvolutionMonoKernel( + &mut self, width: ::UINT, height: ::UINT, rows: *mut ::FLOAT, columns: *mut ::FLOAT + ) -> ::HRESULT, + fn ComposeRects( + &mut self, pSrc: *mut IDirect3DSurface9, pDst: *mut IDirect3DSurface9, + pSrcRectDescs: *mut IDirect3DVertexBuffer9, NumRects: ::UINT, + pDstRectDescs: *mut IDirect3DVertexBuffer9, Operation: ::D3DCOMPOSERECTSOP, Xoffset: ::INT, + Yoffset: ::INT + ) -> ::HRESULT, + fn PresentEx( + &mut self, pSourceRect: *const ::RECT, pDestRect: *const ::RECT, + hDestWindowOverride: ::HWND, pDirtyRegion: *const ::RGNDATA, dwFlags: ::DWORD + ) -> ::HRESULT, + fn GetGPUThreadPriority(&mut self, pPriority: *mut ::INT) -> ::HRESULT, + fn SetGPUThreadPriority(&mut self, Priority: ::INT) -> ::HRESULT, + fn WaitForVBlank(&mut self, iSwapChain: ::UINT) -> ::HRESULT, + fn CheckResourceResidency( + &mut self, pResourceArray: *mut *mut IDirect3DResource9, NumResources: ::UINT32 + ) -> ::HRESULT, + fn SetMaximumFrameLatency(&mut self, MaxLatency: ::UINT) -> ::HRESULT, + fn GetMaximumFrameLatency(&mut self, pMaxLatency: *mut ::UINT) -> ::HRESULT, + fn CheckDeviceState(&mut self, hDestinationWindow: ::HWND) -> ::HRESULT, + fn CreateRenderTargetEx( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Lockable: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE, Usage: ::DWORD + ) -> ::HRESULT, + fn CreateOffscreenPlainSurfaceEx( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, Pool: ::D3DPOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE, Usage: ::DWORD + ) -> ::HRESULT, + fn CreateDepthStencilSurfaceEx( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Discard: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE, Usage: ::DWORD + ) -> ::HRESULT, + fn ResetEx( + &mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + pFullscreenDisplayMode: *mut ::D3DDISPLAYMODEEX + ) -> ::HRESULT, + fn GetDisplayModeEx( + &mut self, iSwapChain: ::UINT, pMode: *mut ::D3DDISPLAYMODEEX, + pRotation: *mut ::D3DDISPLAYROTATION + ) -> ::HRESULT +} +); +pub type LPDIRECT3DDEVICE9EX = *mut IDirect3DDevice9Ex; +pub type PDIRECT3DDEVICE9EX = *mut IDirect3DDevice9Ex; +RIDL!( +interface IDirect3DSwapChain9Ex(IDirect3DSwapChain9ExVtbl): IDirect3DSwapChain9(IDirect3DSwapChain9Vtbl) { + fn GetLastPresentCount(&mut self, pLastPresentCount: *mut ::UINT) -> ::HRESULT, + fn GetPresentStats(&mut self, pPresentationStatistics: *mut ::D3DPRESENTSTATS) -> ::HRESULT, + fn GetDisplayModeEx( + &mut self, pMode: *mut ::D3DDISPLAYMODEEX, pRotation: *mut ::D3DDISPLAYROTATION + ) -> ::HRESULT +} +); +pub type LPDIRECT3DSWAPCHAIN9EX = *mut IDirect3DSwapChain9Ex; +pub type PDIRECT3DSWAPCHAIN9EX = *mut IDirect3DSwapChain9Ex; +RIDL!( +interface IDirect3D9ExOverlayExtension(IDirect3D9ExOverlayExtensionVtbl): IUnknown(IUnknownVtbl) { + fn CheckDeviceOverlayType( + &mut self, Adapter: ::UINT, DevType: ::D3DDEVTYPE, OverlayWidth: ::UINT, + OverlayHeight: ::UINT, OverlayFormat: ::D3DFORMAT, pDisplayMode: *mut ::D3DDISPLAYMODEEX, + DisplayRotation: ::D3DDISPLAYROTATION, pOverlayCaps: *mut ::D3DOVERLAYCAPS + ) -> ::HRESULT +} +); +pub type LPDIRECT3D9EXOVERLAYEXTENSION = *mut IDirect3D9ExOverlayExtension; +pub type PDIRECT3D9EXOVERLAYEXTENSION = *mut IDirect3D9ExOverlayExtension; +RIDL!( +interface IDirect3DDevice9Video(IDirect3DDevice9VideoVtbl): IUnknown(IUnknownVtbl) { + fn GetContentProtectionCaps( + &mut self, pCryptoType: *const ::GUID, pDecodeProfile: *const ::GUID, + pCaps: *mut ::D3DCONTENTPROTECTIONCAPS + ) -> ::HRESULT, + fn CreateAuthenticatedChannel( + &mut self, ChannelType: ::D3DAUTHENTICATEDCHANNELTYPE, + ppAuthenticatedChannel: *mut *mut IDirect3DAuthenticatedChannel9, + pChannelHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateCryptoSession( + &mut self, pCryptoType: *const ::GUID, pDecodeProfile: *const ::GUID, + ppCryptoSession: *mut *mut IDirect3DCryptoSession9, pCryptoHandle: *mut ::HANDLE + ) -> ::HRESULT +} +); +pub type LPDIRECT3DDEVICE9VIDEO = *mut IDirect3DDevice9Video; +pub type PDIRECT3DDEVICE9VIDEO = *mut IDirect3DDevice9Video; +RIDL!( +interface IDirect3DAuthenticatedChannel9(IDirect3DAuthenticatedChannel9Vtbl): IUnknown(IUnknownVtbl) { + fn GetCertificateSize(&mut self, pCertificateSize: *mut ::UINT) -> ::HRESULT, + fn GetCertificate(&mut self, CertifacteSize: ::UINT, ppCertificate: *mut ::BYTE) -> ::HRESULT, + fn NegotiateKeyExchange(&mut self, DataSize: ::UINT, pData: *mut ::VOID) -> ::HRESULT, + fn Query( + &mut self, InputSize: ::UINT, pInput: *const ::VOID, OutputSize: ::UINT, + pOutput: *mut ::VOID + ) -> ::HRESULT, + fn Configure( + &mut self, InputSize: ::UINT, pInput: *const ::VOID, + pOutput: *mut ::D3DAUTHENTICATEDCHANNEL_CONFIGURE_OUTPUT + ) -> ::HRESULT +} +); +pub type LPDIRECT3DAUTHENTICATEDCHANNEL9 = *mut IDirect3DAuthenticatedChannel9; +pub type PDIRECT3DAUTHENTICATEDCHANNEL9 = *mut IDirect3DAuthenticatedChannel9; +RIDL!( +interface IDirect3DCryptoSession9(IDirect3DCryptoSession9Vtbl): IUnknown(IUnknownVtbl) { + fn GetCertificateSize(&mut self, pCertificateSize: *mut ::UINT) -> ::HRESULT, + fn GetCertificate(&mut self, CertifacteSize: ::UINT, ppCertificate: *mut ::BYTE) -> ::HRESULT, + fn NegotiateKeyExchange(&mut self, DataSize: ::UINT, pData: *mut ::VOID) -> ::HRESULT, + fn EncryptionBlt( + &mut self, pSrcSurface: *mut IDirect3DSurface9, pDstSurface: *mut IDirect3DSurface9, + DstSurfaceSize: ::UINT, pIV: *mut ::VOID + ) -> ::HRESULT, + fn DecryptionBlt( + &mut self, pSrcSurface: *mut IDirect3DSurface9, pDstSurface: *mut IDirect3DSurface9, + SrcSurfaceSize: ::UINT, pEncryptedBlockInfo: *mut ::D3DENCRYPTED_BLOCK_INFO, + pContentKey: *mut ::VOID, pIV: *mut ::VOID + ) -> ::HRESULT, + fn GetSurfacePitch( + &mut self, pSrcSurface: *mut IDirect3DSurface9, pSurfacePitch: *mut ::UINT + ) -> ::HRESULT, + fn StartSessionKeyRefresh( + &mut self, pRandomNumber: *mut ::VOID, RandomNumberSize: ::UINT + ) -> ::HRESULT, + fn FinishSessionKeyRefresh(&mut self) -> ::HRESULT, + fn GetEncryptionBltKey(&mut self, pReadbackKey: *mut ::VOID, KeySize: ::UINT) -> ::HRESULT +} +); +pub type LPDIRECT3DCRYPTOSESSION9 = *mut IDirect3DCryptoSession9; +pub type PDIRECT3DCRYPTOSESSION9 = *mut IDirect3DCryptoSession9; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d9caps.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d9caps.rs new file mode 100644 index 0000000..74c877d --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d9caps.rs @@ -0,0 +1,349 @@ +// Copyright © 2015, Corey Richardson +// Licensed under the MIT License <LICENSE.md> +//! Direct3D capabilities include file +STRUCT!{struct D3DVSHADERCAPS2_0 { + Caps: ::DWORD, + DynamicFlowControlDepth: ::INT, + NumTemps: ::INT, + StaticFlowControlDepth: ::INT, +}} +pub const D3DVS20CAPS_PREDICATION: ::DWORD = 1 << 0; +pub const D3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 24; +pub const D3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 0; +pub const D3DVS20_MAX_NUMTEMPS: ::DWORD = 32; +pub const D3DVS20_MIN_NUMTEMPS: ::DWORD = 12; +pub const D3DVS20_MAX_STATICFLOWCONTROLDEPTH: ::DWORD = 4; +pub const D3DVS20_MIN_STATICFLOWCONTROLDEPTH: ::DWORD = 1; +STRUCT!{struct D3DPSHADERCAPS2_0 { + Caps: ::DWORD, + DynamicFlowControlDepth: ::INT, + NumTemps: ::INT, + StaticFlowControlDepth: ::INT, + NumInstructionSlots: ::INT, +}} +pub const D3DPS20CAPS_ARBITRARYSWIZZLE: ::DWORD = 1 << 0; +pub const D3DPS20CAPS_GRADIENTINSTRUCTIONS: ::DWORD = 1 << 1; +pub const D3DPS20CAPS_PREDICATION: ::DWORD = 1 << 2; +pub const D3DPS20CAPS_NODEPENDENTREADLIMIT: ::DWORD = 1 << 3; +pub const D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT: ::DWORD = 1 << 4; +pub const D3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 24; +pub const D3DPS20_MIN_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 0; +pub const D3DPS20_MAX_NUMTEMPS: ::DWORD = 32; +pub const D3DPS20_MIN_NUMTEMPS: ::DWORD = 12; +pub const D3DPS20_MAX_STATICFLOWCONTROLDEPTH: ::DWORD = 4; +pub const D3DPS20_MIN_STATICFLOWCONTROLDEPTH: ::DWORD = 0; +pub const D3DPS20_MAX_NUMINSTRUCTIONSLOTS: ::DWORD = 512; +pub const D3DPS20_MIN_NUMINSTRUCTIONSLOTS: ::DWORD = 96; +pub const D3DMIN30SHADERINSTRUCTIONS: ::DWORD = 512; +pub const D3DMAX30SHADERINSTRUCTIONS: ::DWORD = 32768; +STRUCT!{struct D3DOVERLAYCAPS { + Caps: ::UINT, + MaxOverlayDisplayWidth: ::UINT, + MaxOverlayDisplayHeight: ::UINT, +}} +pub const D3DOVERLAYCAPS_FULLRANGERGB: ::DWORD = 0x00000001; +pub const D3DOVERLAYCAPS_LIMITEDRANGERGB: ::DWORD = 0x00000002; +pub const D3DOVERLAYCAPS_YCbCr_BT601: ::DWORD = 0x00000004; +pub const D3DOVERLAYCAPS_YCbCr_BT709: ::DWORD = 0x00000008; +pub const D3DOVERLAYCAPS_YCbCr_BT601_xvYCC: ::DWORD = 0x00000010; +pub const D3DOVERLAYCAPS_YCbCr_BT709_xvYCC: ::DWORD = 0x00000020; +pub const D3DOVERLAYCAPS_STRETCHX: ::DWORD = 0x00000040; +pub const D3DOVERLAYCAPS_STRETCHY: ::DWORD = 0x00000080; +STRUCT!{struct D3DCONTENTPROTECTIONCAPS { + Caps: ::DWORD, + KeyExchangeType: ::GUID, + BufferAlignmentStart: ::UINT, + BlockAlignmentSize: ::UINT, + ProtectedMemorySize: ::ULONGLONG, +}} +pub const D3DCPCAPS_SOFTWARE: ::DWORD = 0x00000001; +pub const D3DCPCAPS_HARDWARE: ::DWORD = 0x00000002; +pub const D3DCPCAPS_PROTECTIONALWAYSON: ::DWORD = 0x00000004; +pub const D3DCPCAPS_PARTIALDECRYPTION: ::DWORD = 0x00000008; +pub const D3DCPCAPS_CONTENTKEY: ::DWORD = 0x00000010; +pub const D3DCPCAPS_FRESHENSESSIONKEY: ::DWORD = 0x00000020; +pub const D3DCPCAPS_ENCRYPTEDREADBACK: ::DWORD = 0x00000040; +pub const D3DCPCAPS_ENCRYPTEDREADBACKKEY: ::DWORD = 0x00000080; +pub const D3DCPCAPS_SEQUENTIAL_CTR_IV: ::DWORD = 0x00000100; +pub const D3DCPCAPS_ENCRYPTSLICEDATAONLY: ::DWORD = 0x00000200; +STRUCT!{struct D3DCAPS9 { + DeviceType: ::D3DDEVTYPE, + AdapterOrdinal: ::UINT, + Caps: ::DWORD, + Caps2: ::DWORD, + Caps3: ::DWORD, + PresentationIntervals: ::DWORD, + CursorCaps: ::DWORD, + DevCaps: ::DWORD, + PrimitiveMiscCaps: ::DWORD, + RasterCaps: ::DWORD, + ZCmpCaps: ::DWORD, + SrcBlendCaps: ::DWORD, + DestBlendCaps: ::DWORD, + AlphaCmpCaps: ::DWORD, + ShadeCaps: ::DWORD, + TextureCaps: ::DWORD, + TextureFilterCaps: ::DWORD, + CubeTextureFilterCaps: ::DWORD, + VolumeTextureFilterCaps: ::DWORD, + TextureAddressCaps: ::DWORD, + VolumeTextureAddressCaps: ::DWORD, + LineCaps: ::DWORD, + MaxTextureWidth: ::DWORD, + MaxTextureHeight: ::DWORD, + MaxVolumeExtent: ::DWORD, + MaxTextureRepeat: ::DWORD, + MaxTextureAspectRatio: ::DWORD, + MaxAnisotropy: ::DWORD, + MaxVertexW: ::c_float, + GuardBandLeft: ::c_float, + GuardBandTop: ::c_float, + GuardBandRight: ::c_float, + GuardBandBottom: ::c_float, + ExtentsAdjust: ::c_float, + StencilCaps: ::DWORD, + FVFCaps: ::DWORD, + TextureOpCaps: ::DWORD, + MaxTextureBlendStages: ::DWORD, + MaxSimultaneousTextures: ::DWORD, + VertexProcessingCaps: ::DWORD, + MaxActiveLights: ::DWORD, + MaxUserClipPlanes: ::DWORD, + MaxVertexBlendMatrices: ::DWORD, + MaxVertexBlendMatrixIndex: ::DWORD, + MaxPointSize: ::c_float, + MaxPrimitiveCount: ::DWORD, + MaxVertexIndex: ::DWORD, + MaxStreams: ::DWORD, + MaxStreamStride: ::DWORD, + VertexShaderVersion: ::DWORD, + MaxVertexShaderConst: ::DWORD, + PixelShaderVersion: ::DWORD, + PixelShader1xMaxValue: ::c_float, + DevCaps2: ::DWORD, + MaxNpatchTessellationLevel: ::c_float, + Reserved5: ::DWORD, + MasterAdapterOrdinal: ::UINT, + AdapterOrdinalInGroup: ::UINT, + NumberOfAdaptersInGroup: ::UINT, + DeclTypes: ::DWORD, + NumSimultaneousRTs: ::DWORD, + StretchRectFilterCaps: ::DWORD, + VS20Caps: ::D3DVSHADERCAPS2_0, + PS20Caps: ::D3DPSHADERCAPS2_0, + VertexTextureFilterCaps: ::DWORD, + MaxVShaderInstructionsExecuted: ::DWORD, + MaxPShaderInstructionsExecuted: ::DWORD, + MaxVertexShader30InstructionSlots: ::DWORD, + MaxPixelShader30InstructionSlots: ::DWORD, +}} +pub const D3DCAPS_OVERLAY: ::DWORD = 0x00000800; +pub const D3DCAPS_READ_SCANLINE: ::DWORD = 0x00020000; +pub const D3DCAPS2_FULLSCREENGAMMA: ::DWORD = 0x00020000; +pub const D3DCAPS2_CANCALIBRATEGAMMA: ::DWORD = 0x00100000; +pub const D3DCAPS2_RESERVED: ::DWORD = 0x02000000; +pub const D3DCAPS2_CANMANAGERESOURCE: ::DWORD = 0x10000000; +pub const D3DCAPS2_DYNAMICTEXTURES: ::DWORD = 0x20000000; +pub const D3DCAPS2_CANAUTOGENMIPMAP: ::DWORD = 0x40000000; +pub const D3DCAPS2_CANSHARERESOURCE: ::DWORD = 0x80000000; +pub const D3DCAPS3_RESERVED: ::DWORD = 0x8000001f; +pub const D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD: ::DWORD = 0x00000020; +pub const D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION: ::DWORD = 0x00000080; +pub const D3DCAPS3_COPY_TO_VIDMEM: ::DWORD = 0x00000100; +pub const D3DCAPS3_COPY_TO_SYSTEMMEM: ::DWORD = 0x00000200; +pub const D3DCAPS3_DXVAHD: ::DWORD = 0x00000400; +pub const D3DCAPS3_DXVAHD_LIMITED: ::DWORD = 0x00000800; +pub const D3DPRESENT_INTERVAL_DEFAULT: ::DWORD = 0x00000000; +pub const D3DPRESENT_INTERVAL_ONE: ::DWORD = 0x00000001; +pub const D3DPRESENT_INTERVAL_TWO: ::DWORD = 0x00000002; +pub const D3DPRESENT_INTERVAL_THREE: ::DWORD = 0x00000004; +pub const D3DPRESENT_INTERVAL_FOUR: ::DWORD = 0x00000008; +pub const D3DPRESENT_INTERVAL_IMMEDIATE: ::DWORD = 0x80000000; +pub const D3DCURSORCAPS_COLOR: ::DWORD = 0x00000001; +pub const D3DCURSORCAPS_LOWRES: ::DWORD = 0x00000002; +pub const D3DDEVCAPS_EXECUTESYSTEMMEMORY: ::DWORD = 0x00000010; +pub const D3DDEVCAPS_EXECUTEVIDEOMEMORY: ::DWORD = 0x00000020; +pub const D3DDEVCAPS_TLVERTEXSYSTEMMEMORY: ::DWORD = 0x00000040; +pub const D3DDEVCAPS_TLVERTEXVIDEOMEMORY: ::DWORD = 0x00000080; +pub const D3DDEVCAPS_TEXTURESYSTEMMEMORY: ::DWORD = 0x00000100; +pub const D3DDEVCAPS_TEXTUREVIDEOMEMORY: ::DWORD = 0x00000200; +pub const D3DDEVCAPS_DRAWPRIMTLVERTEX: ::DWORD = 0x00000400; +pub const D3DDEVCAPS_CANRENDERAFTERFLIP: ::DWORD = 0x00000800; +pub const D3DDEVCAPS_TEXTURENONLOCALVIDMEM: ::DWORD = 0x00001000; +pub const D3DDEVCAPS_DRAWPRIMITIVES2: ::DWORD = 0x00002000; +pub const D3DDEVCAPS_SEPARATETEXTUREMEMORIES: ::DWORD = 0x00004000; +pub const D3DDEVCAPS_DRAWPRIMITIVES2EX: ::DWORD = 0x00008000; +pub const D3DDEVCAPS_HWTRANSFORMANDLIGHT: ::DWORD = 0x00010000; +pub const D3DDEVCAPS_CANBLTSYSTONONLOCAL: ::DWORD = 0x00020000; +pub const D3DDEVCAPS_HWRASTERIZATION: ::DWORD = 0x00080000; +pub const D3DDEVCAPS_PUREDEVICE: ::DWORD = 0x00100000; +pub const D3DDEVCAPS_QUINTICRTPATCHES: ::DWORD = 0x00200000; +pub const D3DDEVCAPS_RTPATCHES: ::DWORD = 0x00400000; +pub const D3DDEVCAPS_RTPATCHHANDLEZERO: ::DWORD = 0x00800000; +pub const D3DDEVCAPS_NPATCHES: ::DWORD = 0x01000000; +pub const D3DPMISCCAPS_MASKZ: ::DWORD = 0x00000002; +pub const D3DPMISCCAPS_CULLNONE: ::DWORD = 0x00000010; +pub const D3DPMISCCAPS_CULLCW: ::DWORD = 0x00000020; +pub const D3DPMISCCAPS_CULLCCW: ::DWORD = 0x00000040; +pub const D3DPMISCCAPS_COLORWRITEENABLE: ::DWORD = 0x00000080; +pub const D3DPMISCCAPS_CLIPPLANESCALEDPOINTS: ::DWORD = 0x00000100; +pub const D3DPMISCCAPS_CLIPTLVERTS: ::DWORD = 0x00000200; +pub const D3DPMISCCAPS_TSSARGTEMP: ::DWORD = 0x00000400; +pub const D3DPMISCCAPS_BLENDOP: ::DWORD = 0x00000800; +pub const D3DPMISCCAPS_NULLREFERENCE: ::DWORD = 0x00001000; +pub const D3DPMISCCAPS_INDEPENDENTWRITEMASKS: ::DWORD = 0x00004000; +pub const D3DPMISCCAPS_PERSTAGECONSTANT: ::DWORD = 0x00008000; +pub const D3DPMISCCAPS_FOGANDSPECULARALPHA: ::DWORD = 0x00010000; +pub const D3DPMISCCAPS_SEPARATEALPHABLEND: ::DWORD = 0x00020000; +pub const D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS: ::DWORD = 0x00040000; +pub const D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING: ::DWORD = 0x00080000; +pub const D3DPMISCCAPS_FOGVERTEXCLAMPED: ::DWORD = 0x00100000; +pub const D3DPMISCCAPS_POSTBLENDSRGBCONVERT: ::DWORD = 0x00200000; +pub const D3DLINECAPS_TEXTURE: ::DWORD = 0x00000001; +pub const D3DLINECAPS_ZTEST: ::DWORD = 0x00000002; +pub const D3DLINECAPS_BLEND: ::DWORD = 0x00000004; +pub const D3DLINECAPS_ALPHACMP: ::DWORD = 0x00000008; +pub const D3DLINECAPS_FOG: ::DWORD = 0x00000010; +pub const D3DLINECAPS_ANTIALIAS: ::DWORD = 0x00000020; +pub const D3DPRASTERCAPS_DITHER: ::DWORD = 0x00000001; +pub const D3DPRASTERCAPS_ZTEST: ::DWORD = 0x00000010; +pub const D3DPRASTERCAPS_FOGVERTEX: ::DWORD = 0x00000080; +pub const D3DPRASTERCAPS_FOGTABLE: ::DWORD = 0x00000100; +pub const D3DPRASTERCAPS_MIPMAPLODBIAS: ::DWORD = 0x00002000; +pub const D3DPRASTERCAPS_ZBUFFERLESSHSR: ::DWORD = 0x00008000; +pub const D3DPRASTERCAPS_FOGRANGE: ::DWORD = 0x00010000; +pub const D3DPRASTERCAPS_ANISOTROPY: ::DWORD = 0x00020000; +pub const D3DPRASTERCAPS_WBUFFER: ::DWORD = 0x00040000; +pub const D3DPRASTERCAPS_WFOG: ::DWORD = 0x00100000; +pub const D3DPRASTERCAPS_ZFOG: ::DWORD = 0x00200000; +pub const D3DPRASTERCAPS_COLORPERSPECTIVE: ::DWORD = 0x00400000; +pub const D3DPRASTERCAPS_SCISSORTEST: ::DWORD = 0x01000000; +pub const D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS: ::DWORD = 0x02000000; +pub const D3DPRASTERCAPS_DEPTHBIAS: ::DWORD = 0x04000000; +pub const D3DPRASTERCAPS_MULTISAMPLE_TOGGLE: ::DWORD = 0x08000000; +pub const D3DPCMPCAPS_NEVER: ::DWORD = 0x00000001; +pub const D3DPCMPCAPS_LESS: ::DWORD = 0x00000002; +pub const D3DPCMPCAPS_EQUAL: ::DWORD = 0x00000004; +pub const D3DPCMPCAPS_LESSEQUAL: ::DWORD = 0x00000008; +pub const D3DPCMPCAPS_GREATER: ::DWORD = 0x00000010; +pub const D3DPCMPCAPS_NOTEQUAL: ::DWORD = 0x00000020; +pub const D3DPCMPCAPS_GREATEREQUAL: ::DWORD = 0x00000040; +pub const D3DPCMPCAPS_ALWAYS: ::DWORD = 0x00000080; +pub const D3DPBLENDCAPS_ZERO: ::DWORD = 0x00000001; +pub const D3DPBLENDCAPS_ONE: ::DWORD = 0x00000002; +pub const D3DPBLENDCAPS_SRCCOLOR: ::DWORD = 0x00000004; +pub const D3DPBLENDCAPS_INVSRCCOLOR: ::DWORD = 0x00000008; +pub const D3DPBLENDCAPS_SRCALPHA: ::DWORD = 0x00000010; +pub const D3DPBLENDCAPS_INVSRCALPHA: ::DWORD = 0x00000020; +pub const D3DPBLENDCAPS_DESTALPHA: ::DWORD = 0x00000040; +pub const D3DPBLENDCAPS_INVDESTALPHA: ::DWORD = 0x00000080; +pub const D3DPBLENDCAPS_DESTCOLOR: ::DWORD = 0x00000100; +pub const D3DPBLENDCAPS_INVDESTCOLOR: ::DWORD = 0x00000200; +pub const D3DPBLENDCAPS_SRCALPHASAT: ::DWORD = 0x00000400; +pub const D3DPBLENDCAPS_BOTHSRCALPHA: ::DWORD = 0x00000800; +pub const D3DPBLENDCAPS_BOTHINVSRCALPHA: ::DWORD = 0x00001000; +pub const D3DPBLENDCAPS_BLENDFACTOR: ::DWORD = 0x00002000; +pub const D3DPBLENDCAPS_SRCCOLOR2: ::DWORD = 0x00004000; +pub const D3DPBLENDCAPS_INVSRCCOLOR2: ::DWORD = 0x00008000; +pub const D3DPSHADECAPS_COLORGOURAUDRGB: ::DWORD = 0x00000008; +pub const D3DPSHADECAPS_SPECULARGOURAUDRGB: ::DWORD = 0x00000200; +pub const D3DPSHADECAPS_ALPHAGOURAUDBLEND: ::DWORD = 0x00004000; +pub const D3DPSHADECAPS_FOGGOURAUD: ::DWORD = 0x00080000; +pub const D3DPTEXTURECAPS_PERSPECTIVE: ::DWORD = 0x00000001; +pub const D3DPTEXTURECAPS_POW2: ::DWORD = 0x00000002; +pub const D3DPTEXTURECAPS_ALPHA: ::DWORD = 0x00000004; +pub const D3DPTEXTURECAPS_SQUAREONLY: ::DWORD = 0x00000020; +pub const D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE: ::DWORD = 0x00000040; +pub const D3DPTEXTURECAPS_ALPHAPALETTE: ::DWORD = 0x00000080; +pub const D3DPTEXTURECAPS_NONPOW2CONDITIONAL: ::DWORD = 0x00000100; +pub const D3DPTEXTURECAPS_PROJECTED: ::DWORD = 0x00000400; +pub const D3DPTEXTURECAPS_CUBEMAP: ::DWORD = 0x00000800; +pub const D3DPTEXTURECAPS_VOLUMEMAP: ::DWORD = 0x00002000; +pub const D3DPTEXTURECAPS_MIPMAP: ::DWORD = 0x00004000; +pub const D3DPTEXTURECAPS_MIPVOLUMEMAP: ::DWORD = 0x00008000; +pub const D3DPTEXTURECAPS_MIPCUBEMAP: ::DWORD = 0x00010000; +pub const D3DPTEXTURECAPS_CUBEMAP_POW2: ::DWORD = 0x00020000; +pub const D3DPTEXTURECAPS_VOLUMEMAP_POW2: ::DWORD = 0x00040000; +pub const D3DPTEXTURECAPS_NOPROJECTEDBUMPENV: ::DWORD = 0x00200000; +pub const D3DPTFILTERCAPS_MINFPOINT: ::DWORD = 0x00000100; +pub const D3DPTFILTERCAPS_MINFLINEAR: ::DWORD = 0x00000200; +pub const D3DPTFILTERCAPS_MINFANISOTROPIC: ::DWORD = 0x00000400; +pub const D3DPTFILTERCAPS_MINFPYRAMIDALQUAD: ::DWORD = 0x00000800; +pub const D3DPTFILTERCAPS_MINFGAUSSIANQUAD: ::DWORD = 0x00001000; +pub const D3DPTFILTERCAPS_MIPFPOINT: ::DWORD = 0x00010000; +pub const D3DPTFILTERCAPS_MIPFLINEAR: ::DWORD = 0x00020000; +pub const D3DPTFILTERCAPS_CONVOLUTIONMONO: ::DWORD = 0x00040000; +pub const D3DPTFILTERCAPS_MAGFPOINT: ::DWORD = 0x01000000; +pub const D3DPTFILTERCAPS_MAGFLINEAR: ::DWORD = 0x02000000; +pub const D3DPTFILTERCAPS_MAGFANISOTROPIC: ::DWORD = 0x04000000; +pub const D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD: ::DWORD = 0x08000000; +pub const D3DPTFILTERCAPS_MAGFGAUSSIANQUAD: ::DWORD = 0x10000000; +pub const D3DPTADDRESSCAPS_WRAP: ::DWORD = 0x00000001; +pub const D3DPTADDRESSCAPS_MIRROR: ::DWORD = 0x00000002; +pub const D3DPTADDRESSCAPS_CLAMP: ::DWORD = 0x00000004; +pub const D3DPTADDRESSCAPS_BORDER: ::DWORD = 0x00000008; +pub const D3DPTADDRESSCAPS_INDEPENDENTUV: ::DWORD = 0x00000010; +pub const D3DPTADDRESSCAPS_MIRRORONCE: ::DWORD = 0x00000020; +pub const D3DSTENCILCAPS_KEEP: ::DWORD = 0x00000001; +pub const D3DSTENCILCAPS_ZERO: ::DWORD = 0x00000002; +pub const D3DSTENCILCAPS_REPLACE: ::DWORD = 0x00000004; +pub const D3DSTENCILCAPS_INCRSAT: ::DWORD = 0x00000008; +pub const D3DSTENCILCAPS_DECRSAT: ::DWORD = 0x00000010; +pub const D3DSTENCILCAPS_INVERT: ::DWORD = 0x00000020; +pub const D3DSTENCILCAPS_INCR: ::DWORD = 0x00000040; +pub const D3DSTENCILCAPS_DECR: ::DWORD = 0x00000080; +pub const D3DSTENCILCAPS_TWOSIDED: ::DWORD = 0x00000100; +pub const D3DTEXOPCAPS_DISABLE: ::DWORD = 0x00000001; +pub const D3DTEXOPCAPS_SELECTARG1: ::DWORD = 0x00000002; +pub const D3DTEXOPCAPS_SELECTARG2: ::DWORD = 0x00000004; +pub const D3DTEXOPCAPS_MODULATE: ::DWORD = 0x00000008; +pub const D3DTEXOPCAPS_MODULATE2X: ::DWORD = 0x00000010; +pub const D3DTEXOPCAPS_MODULATE4X: ::DWORD = 0x00000020; +pub const D3DTEXOPCAPS_ADD: ::DWORD = 0x00000040; +pub const D3DTEXOPCAPS_ADDSIGNED: ::DWORD = 0x00000080; +pub const D3DTEXOPCAPS_ADDSIGNED2X: ::DWORD = 0x00000100; +pub const D3DTEXOPCAPS_SUBTRACT: ::DWORD = 0x00000200; +pub const D3DTEXOPCAPS_ADDSMOOTH: ::DWORD = 0x00000400; +pub const D3DTEXOPCAPS_BLENDDIFFUSEALPHA: ::DWORD = 0x00000800; +pub const D3DTEXOPCAPS_BLENDTEXTUREALPHA: ::DWORD = 0x00001000; +pub const D3DTEXOPCAPS_BLENDFACTORALPHA: ::DWORD = 0x00002000; +pub const D3DTEXOPCAPS_BLENDTEXTUREALPHAPM: ::DWORD = 0x00004000; +pub const D3DTEXOPCAPS_BLENDCURRENTALPHA: ::DWORD = 0x00008000; +pub const D3DTEXOPCAPS_PREMODULATE: ::DWORD = 0x00010000; +pub const D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR: ::DWORD = 0x00020000; +pub const D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA: ::DWORD = 0x00040000; +pub const D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR: ::DWORD = 0x00080000; +pub const D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA: ::DWORD = 0x00100000; +pub const D3DTEXOPCAPS_BUMPENVMAP: ::DWORD = 0x00200000; +pub const D3DTEXOPCAPS_BUMPENVMAPLUMINANCE: ::DWORD = 0x00400000; +pub const D3DTEXOPCAPS_DOTPRODUCT3: ::DWORD = 0x00800000; +pub const D3DTEXOPCAPS_MULTIPLYADD: ::DWORD = 0x01000000; +pub const D3DTEXOPCAPS_LERP: ::DWORD = 0x02000000; +pub const D3DFVFCAPS_TEXCOORDCOUNTMASK: ::DWORD = 0x0000ffff; +pub const D3DFVFCAPS_DONOTSTRIPELEMENTS: ::DWORD = 0x00080000; +pub const D3DFVFCAPS_PSIZE: ::DWORD = 0x00100000; +pub const D3DVTXPCAPS_TEXGEN: ::DWORD = 0x00000001; +pub const D3DVTXPCAPS_MATERIALSOURCE7: ::DWORD = 0x00000002; +pub const D3DVTXPCAPS_DIRECTIONALLIGHTS: ::DWORD = 0x00000008; +pub const D3DVTXPCAPS_POSITIONALLIGHTS: ::DWORD = 0x00000010; +pub const D3DVTXPCAPS_LOCALVIEWER: ::DWORD = 0x00000020; +pub const D3DVTXPCAPS_TWEENING: ::DWORD = 0x00000040; +pub const D3DVTXPCAPS_TEXGEN_SPHEREMAP: ::DWORD = 0x00000100; +pub const D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER: ::DWORD = 0x00000200; +pub const D3DDEVCAPS2_STREAMOFFSET: ::DWORD = 0x00000001; +pub const D3DDEVCAPS2_DMAPNPATCH: ::DWORD = 0x00000002; +pub const D3DDEVCAPS2_ADAPTIVETESSRTPATCH: ::DWORD = 0x00000004; +pub const D3DDEVCAPS2_ADAPTIVETESSNPATCH: ::DWORD = 0x00000008; +pub const D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES: ::DWORD = 0x00000010; +pub const D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH: ::DWORD = 0x00000020; +pub const D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET: ::DWORD = 0x00000040; +pub const D3DDTCAPS_UBYTE4: ::DWORD = 0x00000001; +pub const D3DDTCAPS_UBYTE4N: ::DWORD = 0x00000002; +pub const D3DDTCAPS_SHORT2N: ::DWORD = 0x00000004; +pub const D3DDTCAPS_SHORT4N: ::DWORD = 0x00000008; +pub const D3DDTCAPS_USHORT2N: ::DWORD = 0x00000010; +pub const D3DDTCAPS_USHORT4N: ::DWORD = 0x00000020; +pub const D3DDTCAPS_UDEC3: ::DWORD = 0x00000040; +pub const D3DDTCAPS_DEC3N: ::DWORD = 0x00000080; +pub const D3DDTCAPS_FLOAT16_2: ::DWORD = 0x00000100; +pub const D3DDTCAPS_FLOAT16_4: ::DWORD = 0x00000200; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3d9types.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3d9types.rs new file mode 100644 index 0000000..28d0bed --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3d9types.rs @@ -0,0 +1,1397 @@ +// Copyright © 2015, Corey Richardson +// Licensed under the MIT License <LICENSE.md> +//! Direct3D capabilities include file +pub type D3DCOLOR = ::DWORD; +STRUCT!{struct D3DVECTOR { + x: ::c_float, + y: ::c_float, + z: ::c_float, +}} +STRUCT!{struct D3DCOLORVALUE { + r: ::c_float, + g: ::c_float, + b: ::c_float, + a: ::c_float, +}} +STRUCT!{struct D3DRECT { + x1: ::LONG, + y1: ::LONG, + x2: ::LONG, + y2: ::LONG, +}} +STRUCT!{struct D3DMATRIX { + m: [[::c_float; 4]; 4], +}} +STRUCT!{struct D3DVIEWPORT9 { + X: ::DWORD, + Y: ::DWORD, + Width: ::DWORD, + Height: ::DWORD, + MinZ: ::c_float, + MaxZ: ::c_float, +}} +pub const D3DMAXUSERCLIPPLANES: ::DWORD = 32; +pub const D3DCLIPPLANE0: ::DWORD = (1 << 0); +pub const D3DCLIPPLANE1: ::DWORD = (1 << 1); +pub const D3DCLIPPLANE2: ::DWORD = (1 << 2); +pub const D3DCLIPPLANE3: ::DWORD = (1 << 3); +pub const D3DCLIPPLANE4: ::DWORD = (1 << 4); +pub const D3DCLIPPLANE5: ::DWORD = (1 << 5); +pub const D3DCS_LEFT: ::DWORD = 0x00000001; +pub const D3DCS_RIGHT: ::DWORD = 0x00000002; +pub const D3DCS_TOP: ::DWORD = 0x00000004; +pub const D3DCS_BOTTOM: ::DWORD = 0x00000008; +pub const D3DCS_FRONT: ::DWORD = 0x00000010; +pub const D3DCS_BACK: ::DWORD = 0x00000020; +pub const D3DCS_PLANE0: ::DWORD = 0x00000040; +pub const D3DCS_PLANE1: ::DWORD = 0x00000080; +pub const D3DCS_PLANE2: ::DWORD = 0x00000100; +pub const D3DCS_PLANE3: ::DWORD = 0x00000200; +pub const D3DCS_PLANE4: ::DWORD = 0x00000400; +pub const D3DCS_PLANE5: ::DWORD = 0x00000800; +pub const D3DCS_ALL: ::DWORD = D3DCS_LEFT | D3DCS_RIGHT | D3DCS_TOP | D3DCS_BOTTOM | D3DCS_FRONT + | D3DCS_BACK | D3DCS_PLANE0 | D3DCS_PLANE1 | D3DCS_PLANE2 | D3DCS_PLANE3 | D3DCS_PLANE4 + | D3DCS_PLANE5; +STRUCT!{struct D3DCLIPSTATUS9 { + ClipUnion: ::DWORD, + ClipIntersection: ::DWORD, +}} +STRUCT!{struct D3DMATERIAL9 { + Diffuse: D3DCOLORVALUE, + Ambient: D3DCOLORVALUE, + Specular: D3DCOLORVALUE, + Emissive: D3DCOLORVALUE, + Power: ::c_float, +}} +ENUM!{enum D3DLIGHTTYPE { + D3DLIGHT_POINT = 1, + D3DLIGHT_SPOT = 2, + D3DLIGHT_DIRECTIONAL = 3, +}} +STRUCT!{struct D3DLIGHT9 { + Type: D3DLIGHTTYPE, + Diffuse: D3DCOLORVALUE, + Specular: D3DCOLORVALUE, + Ambient: D3DCOLORVALUE, + Position: D3DVECTOR, + Direction: D3DVECTOR, + Range: ::c_float, + Falloff: ::c_float, + Attenuation0: ::c_float, + Attenuation1: ::c_float, + Attenuation2: ::c_float, + Theta: ::c_float, + Phi: ::c_float, +}} +pub const D3DCLEAR_TARGET: ::DWORD = 0x1; +pub const D3DCLEAR_ZBUFFER: ::DWORD = 0x2; +pub const D3DCLEAR_STENCIL: ::DWORD = 0x4; +ENUM!{enum D3DSHADEMODE { + D3DSHADE_FLAT = 1, + D3DSHADE_GOURAUD = 2, + D3DSHADE_PHONG = 3, +}} +ENUM!{enum D3DFILLMODE { + D3DFILL_POINT = 1, + D3DFILL_WIREFRAME = 2, + D3DFILL_SOLID = 3, +}} +ENUM!{enum D3DBLEND { + D3DBLEND_ZERO = 1, + D3DBLEND_ONE = 2, + D3DBLEND_SRCCOLOR = 3, + D3DBLEND_INVSRCCOLOR = 4, + D3DBLEND_SRCALPHA = 5, + D3DBLEND_INVSRCALPHA = 6, + D3DBLEND_DESTALPHA = 7, + D3DBLEND_INVDESTALPHA = 8, + D3DBLEND_DESTCOLOR = 9, + D3DBLEND_INVDESTCOLOR = 10, + D3DBLEND_SRCALPHASAT = 11, + D3DBLEND_BOTHSRCALPHA = 12, + D3DBLEND_BOTHINVSRCALPHA = 13, + D3DBLEND_BLENDFACTOR = 14, + D3DBLEND_INVBLENDFACTOR = 15, +}} +ENUM!{enum D3DBLENDOP { + D3DBLENDOP_ADD = 1, + D3DBLENDOP_SUBTRACT = 2, + D3DBLENDOP_REVSUBTRACT = 3, + D3DBLENDOP_MIN = 4, + D3DBLENDOP_MAX = 5, +}} +ENUM!{enum D3DTEXTUREADDRESS { + D3DTADDRESS_WRAP = 1, + D3DTADDRESS_MIRROR = 2, + D3DTADDRESS_CLAMP = 3, + D3DTADDRESS_BORDER = 4, + D3DTADDRESS_MIRRORONCE = 5, +}} +ENUM!{enum D3DCULL { + D3DCULL_NONE = 1, + D3DCULL_CW = 2, + D3DCULL_CCW = 3, +}} +ENUM!{enum D3DCMPFUNC { + D3DCMP_NEVER = 1, + D3DCMP_LESS = 2, + D3DCMP_EQUAL = 3, + D3DCMP_LESSEQUAL = 4, + D3DCMP_GREATER = 5, + D3DCMP_NOTEQUAL = 6, + D3DCMP_GREATEREQUAL = 7, + D3DCMP_ALWAYS = 8, +}} +ENUM!{enum D3DSTENCILOP { + D3DSTENCILOP_KEEP = 1, + D3DSTENCILOP_ZERO = 2, + D3DSTENCILOP_REPLACE = 3, + D3DSTENCILOP_INCRSAT = 4, + D3DSTENCILOP_DECRSAT = 5, + D3DSTENCILOP_INVERT = 6, + D3DSTENCILOP_INCR = 7, + D3DSTENCILOP_DECR = 8, +}} +ENUM!{enum D3DFOGMODE { + D3DFOG_NONE = 0, + D3DFOG_EXP = 1, + D3DFOG_EXP2 = 2, + D3DFOG_LINEAR = 3, +}} +ENUM!{enum D3DZBUFFERTYPE { + D3DZB_FALSE = 0, + D3DZB_TRUE = 1, + D3DZB_USEW = 2, +}} +ENUM!{enum D3DPRIMITIVETYPE { + D3DPT_POINTLIST = 1, + D3DPT_LINELIST = 2, + D3DPT_LINESTRIP = 3, + D3DPT_TRIANGLELIST = 4, + D3DPT_TRIANGLESTRIP = 5, + D3DPT_TRIANGLEFAN = 6, +}} +ENUM!{enum D3DTRANSFORMSTATETYPE { + D3DTS_VIEW = 2, + D3DTS_PROJECTION = 3, + D3DTS_TEXTURE0 = 16, + D3DTS_TEXTURE1 = 17, + D3DTS_TEXTURE2 = 18, + D3DTS_TEXTURE3 = 19, + D3DTS_TEXTURE4 = 20, + D3DTS_TEXTURE5 = 21, + D3DTS_TEXTURE6 = 22, + D3DTS_TEXTURE7 = 23, +}} +ENUM!{enum D3DRENDERSTATETYPE { + D3DRS_ZENABLE = 7, + D3DRS_FILLMODE = 8, + D3DRS_SHADEMODE = 9, + D3DRS_ZWRITEENABLE = 14, + D3DRS_ALPHATESTENABLE = 15, + D3DRS_LASTPIXEL = 16, + D3DRS_SRCBLEND = 19, + D3DRS_DESTBLEND = 20, + D3DRS_CULLMODE = 22, + D3DRS_ZFUNC = 23, + D3DRS_ALPHAREF = 24, + D3DRS_ALPHAFUNC = 25, + D3DRS_DITHERENABLE = 26, + D3DRS_ALPHABLENDENABLE = 27, + D3DRS_FOGENABLE = 28, + D3DRS_SPECULARENABLE = 29, + D3DRS_FOGCOLOR = 34, + D3DRS_FOGTABLEMODE = 35, + D3DRS_FOGSTART = 36, + D3DRS_FOGEND = 37, + D3DRS_FOGDENSITY = 38, + D3DRS_RANGEFOGENABLE = 48, + D3DRS_STENCILENABLE = 52, + D3DRS_STENCILFAIL = 53, + D3DRS_STENCILZFAIL = 54, + D3DRS_STENCILPASS = 55, + D3DRS_STENCILFUNC = 56, + D3DRS_STENCILREF = 57, + D3DRS_STENCILMASK = 58, + D3DRS_STENCILWRITEMASK = 59, + D3DRS_TEXTUREFACTOR = 60, + D3DRS_WRAP0 = 128, + D3DRS_WRAP1 = 129, + D3DRS_WRAP2 = 130, + D3DRS_WRAP3 = 131, + D3DRS_WRAP4 = 132, + D3DRS_WRAP5 = 133, + D3DRS_WRAP6 = 134, + D3DRS_WRAP7 = 135, + D3DRS_CLIPPING = 136, + D3DRS_LIGHTING = 137, + D3DRS_AMBIENT = 139, + D3DRS_FOGVERTEXMODE = 140, + D3DRS_COLORVERTEX = 141, + D3DRS_LOCALVIEWER = 142, + D3DRS_NORMALIZENORMALS = 143, + D3DRS_DIFFUSEMATERIALSOURCE = 145, + D3DRS_SPECULARMATERIALSOURCE = 146, + D3DRS_AMBIENTMATERIALSOURCE = 147, + D3DRS_EMISSIVEMATERIALSOURCE = 148, + D3DRS_VERTEXBLEND = 151, + D3DRS_CLIPPLANEENABLE = 152, + D3DRS_POINTSIZE = 154, + D3DRS_POINTSIZE_MIN = 155, + D3DRS_POINTSPRITEENABLE = 156, + D3DRS_POINTSCALEENABLE = 157, + D3DRS_POINTSCALE_A = 158, + D3DRS_POINTSCALE_B = 159, + D3DRS_POINTSCALE_C = 160, + D3DRS_MULTISAMPLEANTIALIAS = 161, + D3DRS_MULTISAMPLEMASK = 162, + D3DRS_PATCHEDGESTYLE = 163, + D3DRS_DEBUGMONITORTOKEN = 165, + D3DRS_POINTSIZE_MAX = 166, + D3DRS_INDEXEDVERTEXBLENDENABLE = 167, + D3DRS_COLORWRITEENABLE = 168, + D3DRS_TWEENFACTOR = 170, + D3DRS_BLENDOP = 171, + D3DRS_POSITIONDEGREE = 172, + D3DRS_NORMALDEGREE = 173, + D3DRS_SCISSORTESTENABLE = 174, + D3DRS_SLOPESCALEDEPTHBIAS = 175, + D3DRS_ANTIALIASEDLINEENABLE = 176, + D3DRS_MINTESSELLATIONLEVEL = 178, + D3DRS_MAXTESSELLATIONLEVEL = 179, + D3DRS_ADAPTIVETESS_X = 180, + D3DRS_ADAPTIVETESS_Y = 181, + D3DRS_ADAPTIVETESS_Z = 182, + D3DRS_ADAPTIVETESS_W = 183, + D3DRS_ENABLEADAPTIVETESSELLATION = 184, + D3DRS_TWOSIDEDSTENCILMODE = 185, + D3DRS_CCW_STENCILFAIL = 186, + D3DRS_CCW_STENCILZFAIL = 187, + D3DRS_CCW_STENCILPASS = 188, + D3DRS_CCW_STENCILFUNC = 189, + D3DRS_COLORWRITEENABLE1 = 190, + D3DRS_COLORWRITEENABLE2 = 191, + D3DRS_COLORWRITEENABLE3 = 192, + D3DRS_BLENDFACTOR = 193, + D3DRS_SRGBWRITEENABLE = 194, + D3DRS_DEPTHBIAS = 195, + D3DRS_WRAP8 = 198, + D3DRS_WRAP9 = 199, + D3DRS_WRAP10 = 200, + D3DRS_WRAP11 = 201, + D3DRS_WRAP12 = 202, + D3DRS_WRAP13 = 203, + D3DRS_WRAP14 = 204, + D3DRS_WRAP15 = 205, + D3DRS_SEPARATEALPHABLENDENABLE = 206, + D3DRS_SRCBLENDALPHA = 207, + D3DRS_DESTBLENDALPHA = 208, + D3DRS_BLENDOPALPHA = 209, +}} +pub const D3D_MAX_SIMULTANEOUS_RENDERTARGETS: ::DWORD = 4; +ENUM!{enum D3DMATERIALCOLORSOURCE { + D3DMCS_MATERIAL = 0, + D3DMCS_COLOR1 = 1, + D3DMCS_COLOR2 = 2, +}} +pub const D3DRENDERSTATE_WRAPBIAS: ::DWORD = 128; +pub const D3DWRAP_U: ::DWORD = 0x00000001; +pub const D3DWRAP_V: ::DWORD = 0x00000002; +pub const D3DWRAP_W: ::DWORD = 0x00000004; +pub const D3DWRAPCOORD_0: ::DWORD = 0x00000001; +pub const D3DWRAPCOORD_1: ::DWORD = 0x00000002; +pub const D3DWRAPCOORD_2: ::DWORD = 0x00000004; +pub const D3DWRAPCOORD_3: ::DWORD = 0x00000008; +pub const D3DCOLORWRITEENABLE_RED: ::DWORD = 1 << 0; +pub const D3DCOLORWRITEENABLE_GREEN: ::DWORD = 1 << 1; +pub const D3DCOLORWRITEENABLE_BLUE: ::DWORD = 1 << 2; +pub const D3DCOLORWRITEENABLE_ALPHA: ::DWORD = 1 << 3; +ENUM!{enum D3DTEXTURESTAGESTATETYPE { + D3DTSS_COLOROP = 1, + D3DTSS_COLORARG1 = 2, + D3DTSS_COLORARG2 = 3, + D3DTSS_ALPHAOP = 4, + D3DTSS_ALPHAARG1 = 5, + D3DTSS_ALPHAARG2 = 6, + D3DTSS_BUMPENVMAT00 = 7, + D3DTSS_BUMPENVMAT01 = 8, + D3DTSS_BUMPENVMAT10 = 9, + D3DTSS_BUMPENVMAT11 = 10, + D3DTSS_TEXCOORDINDEX = 11, + D3DTSS_BUMPENVLSCALE = 22, + D3DTSS_BUMPENVLOFFSET = 23, + D3DTSS_TEXTURETRANSFORMFLAGS = 24, + D3DTSS_COLORARG0 = 26, + D3DTSS_ALPHAARG0 = 27, + D3DTSS_RESULTARG = 28, + D3DTSS_CONSTANT = 32, +}} +ENUM!{enum D3DSAMPLERSTATETYPE { + D3DSAMP_ADDRESSU = 1, + D3DSAMP_ADDRESSV = 2, + D3DSAMP_ADDRESSW = 3, + D3DSAMP_BORDERCOLOR = 4, + D3DSAMP_MAGFILTER = 5, + D3DSAMP_MINFILTER = 6, + D3DSAMP_MIPFILTER = 7, + D3DSAMP_MIPMAPLODBIAS = 8, + D3DSAMP_MAXMIPLEVEL = 9, + D3DSAMP_MAXANISOTROPY = 10, + D3DSAMP_SRGBTEXTURE = 11, + D3DSAMP_ELEMENTINDEX = 12, + D3DSAMP_DMAPOFFSET = 13, +}} +pub const D3DDMAPSAMPLER: ::DWORD = 256; +pub const D3DVERTEXTEXTURESAMPLER0: ::DWORD = D3DDMAPSAMPLER + 1; +pub const D3DVERTEXTEXTURESAMPLER1: ::DWORD = D3DDMAPSAMPLER + 2; +pub const D3DVERTEXTEXTURESAMPLER2: ::DWORD = D3DDMAPSAMPLER + 3; +pub const D3DVERTEXTEXTURESAMPLER3: ::DWORD = D3DDMAPSAMPLER + 4; +pub const D3DTSS_TCI_PASSTHRU: ::DWORD = 0x00000000; +pub const D3DTSS_TCI_CAMERASPACENORMAL: ::DWORD = 0x00010000; +pub const D3DTSS_TCI_CAMERASPACEPOSITION: ::DWORD = 0x00020000; +pub const D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR: ::DWORD = 0x00030000; +pub const D3DTSS_TCI_SPHEREMAP: ::DWORD = 0x00040000; +ENUM!{enum D3DTEXTUREOP { + D3DTOP_DISABLE = 1, + D3DTOP_SELECTARG1 = 2, + D3DTOP_SELECTARG2 = 3, + D3DTOP_MODULATE = 4, + D3DTOP_MODULATE2X = 5, + D3DTOP_MODULATE4X = 6, + D3DTOP_ADD = 7, + D3DTOP_ADDSIGNED = 8, + D3DTOP_ADDSIGNED2X = 9, + D3DTOP_SUBTRACT = 10, + D3DTOP_ADDSMOOTH = 11, + D3DTOP_BLENDDIFFUSEALPHA = 12, + D3DTOP_BLENDTEXTUREALPHA = 13, + D3DTOP_BLENDFACTORALPHA = 14, + D3DTOP_BLENDTEXTUREALPHAPM = 15, + D3DTOP_BLENDCURRENTALPHA = 16, + D3DTOP_PREMODULATE = 17, + D3DTOP_MODULATEALPHA_ADDCOLOR = 18, + D3DTOP_MODULATECOLOR_ADDALPHA = 19, + D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20, + D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21, + D3DTOP_BUMPENVMAP = 22, + D3DTOP_BUMPENVMAPLUMINANCE = 23, + D3DTOP_DOTPRODUCT3 = 24, + D3DTOP_MULTIPLYADD = 25, + D3DTOP_LERP = 26, +}} +pub const D3DTA_SELECTMASK: ::DWORD = 0x0000000f; +pub const D3DTA_DIFFUSE: ::DWORD = 0x00000000; +pub const D3DTA_CURRENT: ::DWORD = 0x00000001; +pub const D3DTA_TEXTURE: ::DWORD = 0x00000002; +pub const D3DTA_TFACTOR: ::DWORD = 0x00000003; +pub const D3DTA_SPECULAR: ::DWORD = 0x00000004; +pub const D3DTA_TEMP: ::DWORD = 0x00000005; +pub const D3DTA_CONSTANT: ::DWORD = 0x00000006; +pub const D3DTA_COMPLEMENT: ::DWORD = 0x00000010; +pub const D3DTA_ALPHAREPLICATE: ::DWORD = 0x00000020; +ENUM!{enum D3DTEXTUREFILTERTYPE { + D3DTEXF_NONE = 0, + D3DTEXF_POINT = 1, + D3DTEXF_LINEAR = 2, + D3DTEXF_ANISOTROPIC = 3, + D3DTEXF_PYRAMIDALQUAD = 6, + D3DTEXF_GAUSSIANQUAD = 7, + D3DTEXF_CONVOLUTIONMONO = 8, +}} +pub const D3DPV_DONOTCOPYDATA: ::DWORD = 1 << 0; +pub const D3DFVF_RESERVED0: ::DWORD = 0x001; +pub const D3DFVF_POSITION_MASK: ::DWORD = 0x400E; +pub const D3DFVF_XYZ: ::DWORD = 0x002; +pub const D3DFVF_XYZRHW: ::DWORD = 0x004; +pub const D3DFVF_XYZB1: ::DWORD = 0x006; +pub const D3DFVF_XYZB2: ::DWORD = 0x008; +pub const D3DFVF_XYZB3: ::DWORD = 0x00a; +pub const D3DFVF_XYZB4: ::DWORD = 0x00c; +pub const D3DFVF_XYZB5: ::DWORD = 0x00e; +pub const D3DFVF_XYZW: ::DWORD = 0x4002; +pub const D3DFVF_NORMAL: ::DWORD = 0x010; +pub const D3DFVF_PSIZE: ::DWORD = 0x020; +pub const D3DFVF_DIFFUSE: ::DWORD = 0x040; +pub const D3DFVF_SPECULAR: ::DWORD = 0x080; +pub const D3DFVF_TEXCOUNT_MASK: ::DWORD = 0xf00; +pub const D3DFVF_TEXCOUNT_SHIFT: ::DWORD = 8; +pub const D3DFVF_TEX0: ::DWORD = 0x000; +pub const D3DFVF_TEX1: ::DWORD = 0x100; +pub const D3DFVF_TEX2: ::DWORD = 0x200; +pub const D3DFVF_TEX3: ::DWORD = 0x300; +pub const D3DFVF_TEX4: ::DWORD = 0x400; +pub const D3DFVF_TEX5: ::DWORD = 0x500; +pub const D3DFVF_TEX6: ::DWORD = 0x600; +pub const D3DFVF_TEX7: ::DWORD = 0x700; +pub const D3DFVF_TEX8: ::DWORD = 0x800; +pub const D3DFVF_LASTBETA_UBYTE4: ::DWORD = 0x1000; +pub const D3DFVF_LASTBETA_D3DCOLOR: ::DWORD = 0x8000; +pub const D3DFVF_RESERVED2: ::DWORD = 0x6000; +ENUM!{enum D3DDECLUSAGE { + D3DDECLUSAGE_POSITION = 0, + D3DDECLUSAGE_BLENDWEIGHT, + D3DDECLUSAGE_BLENDINDICES, + D3DDECLUSAGE_NORMAL, + D3DDECLUSAGE_PSIZE, + D3DDECLUSAGE_TEXCOORD, + D3DDECLUSAGE_TANGENT, + D3DDECLUSAGE_BINORMAL, + D3DDECLUSAGE_TESSFACTOR, + D3DDECLUSAGE_POSITIONT, + D3DDECLUSAGE_COLOR, + D3DDECLUSAGE_FOG, + D3DDECLUSAGE_DEPTH, + D3DDECLUSAGE_SAMPLE, +}} +pub const MAXD3DDECLUSAGE: D3DDECLUSAGE = D3DDECLUSAGE_SAMPLE; +pub const MAXD3DDECLUSAGEINDEX: ::DWORD = 15; +pub const MAXD3DDECLLENGTH: ::DWORD = 64; +ENUM!{enum D3DDECLMETHOD { + D3DDECLMETHOD_DEFAULT = 0, + D3DDECLMETHOD_PARTIALU, + D3DDECLMETHOD_PARTIALV, + D3DDECLMETHOD_CROSSUV, + D3DDECLMETHOD_UV, + D3DDECLMETHOD_LOOKUP, + D3DDECLMETHOD_LOOKUPPRESAMPLED, +}} +pub const MAXD3DDECLMETHOD: D3DDECLMETHOD = D3DDECLMETHOD_LOOKUPPRESAMPLED; +ENUM!{enum D3DDECLTYPE { + D3DDECLTYPE_FLOAT1 = 0, + D3DDECLTYPE_FLOAT2 = 1, + D3DDECLTYPE_FLOAT3 = 2, + D3DDECLTYPE_FLOAT4 = 3, + D3DDECLTYPE_D3DCOLOR = 4, + D3DDECLTYPE_UBYTE4 = 5, + D3DDECLTYPE_SHORT2 = 6, + D3DDECLTYPE_SHORT4 = 7, + D3DDECLTYPE_UBYTE4N = 8, + D3DDECLTYPE_SHORT2N = 9, + D3DDECLTYPE_SHORT4N = 10, + D3DDECLTYPE_USHORT2N = 11, + D3DDECLTYPE_USHORT4N = 12, + D3DDECLTYPE_UDEC3 = 13, + D3DDECLTYPE_DEC3N = 14, + D3DDECLTYPE_FLOAT16_2 = 15, + D3DDECLTYPE_FLOAT16_4 = 16, + D3DDECLTYPE_UNUSED = 17, +}} +pub const MAXD3DDECLTYPE: D3DDECLTYPE = D3DDECLTYPE_UNUSED; +STRUCT!{struct D3DVERTEXELEMENT9 { + Stream: ::WORD, + Offset: ::WORD, + Type: ::BYTE, + Method: ::BYTE, + Usage: ::BYTE, + UsageIndex: ::BYTE, +}} +pub type LPD3DVERTEXELEMENT9 = *mut D3DVERTEXELEMENT9; +pub const D3DDECL_END: D3DVERTEXELEMENT9 = D3DVERTEXELEMENT9 { + Stream: 0xFF, + Offset: 0, + Type: D3DDECLTYPE_UNUSED.0 as ::BYTE, + Method: 0, + Usage: 0, + UsageIndex: 0, +}; +pub const D3DDP_MAXTEXCOORD: ::DWORD = 8; +pub const D3DSTREAMSOURCE_INDEXEDDATA: ::DWORD = 1 << 30; +pub const D3DSTREAMSOURCE_INSTANCEDATA: ::DWORD = 2 << 30; +pub const D3DSI_OPCODE_MASK: ::DWORD = 0x0000FFFF; +pub const D3DSI_INSTLENGTH_MASK: ::DWORD = 0x0F000000; +pub const D3DSI_INSTLENGTH_SHIFT: ::DWORD = 24; +ENUM!{enum D3DSHADER_INSTRUCTION_OPCODE_TYPE { + D3DSIO_NOP = 0, + D3DSIO_MOV = 1, + D3DSIO_ADD = 2, + D3DSIO_SUB = 3, + D3DSIO_MAD = 4, + D3DSIO_MUL = 5, + D3DSIO_RCP = 6, + D3DSIO_RSQ = 7, + D3DSIO_DP3 = 8, + D3DSIO_DP4 = 9, + D3DSIO_MIN = 10, + D3DSIO_MAX = 11, + D3DSIO_SLT = 12, + D3DSIO_SGE = 13, + D3DSIO_EXP = 14, + D3DSIO_LOG = 15, + D3DSIO_LIT = 16, + D3DSIO_DST = 17, + D3DSIO_LRP = 18, + D3DSIO_FRC = 18, + D3DSIO_M4x4 = 20, + D3DSIO_M4x3 = 21, + D3DSIO_M3x4 = 22, + D3DSIO_M3x3 = 23, + D3DSIO_M3x2 = 24, + D3DSIO_CALL = 25, + D3DSIO_CALLNZ = 26, + D3DSIO_LOOP = 27, + D3DSIO_RET = 28, + D3DSIO_ENDLOOP = 29, + D3DSIO_LABEL = 30, + D3DSIO_DCL = 31, + D3DSIO_POW = 32, + D3DSIO_CRS = 33, + D3DSIO_SGN = 34, + D3DSIO_ABS = 35, + D3DSIO_NRM = 36, + D3DSIO_SINCOS = 37, + D3DSIO_REP = 38, + D3DSIO_ENDREP = 39, + D3DSIO_IF = 40, + D3DSIO_IFC = 41, + D3DSIO_ELSE = 42, + D3DSIO_ENDIF = 43, + D3DSIO_BREAK = 44, + D3DSIO_BREAKC = 45, + D3DSIO_MOVA = 46, + D3DSIO_DEFB = 47, + D3DSIO_DEFI = 48, + D3DSIO_TEXCOORD = 64, + D3DSIO_TEXKILL = 65, + D3DSIO_TEX = 66, + D3DSIO_TEXBEM = 67, + D3DSIO_TEXBEML = 68, + D3DSIO_TEXREG2AR = 69, + D3DSIO_TEXREG2GB = 70, + D3DSIO_TEXM3x2PAD = 71, + D3DSIO_TEXM3x2TEX = 72, + D3DSIO_TEXM3x3PAD = 73, + D3DSIO_TEXM3x3TEX = 74, + D3DSIO_RESERVED0 = 75, + D3DSIO_TEXM3x3SPEC = 76, + D3DSIO_TEXM3x3VSPEC = 77, + D3DSIO_EXPP = 78, + D3DSIO_LOGP = 79, + D3DSIO_CND = 80, + D3DSIO_DEF = 81, + D3DSIO_TEXREG2RGB = 82, + D3DSIO_TEXDP3TEX = 83, + D3DSIO_TEXM3x2DEPTH = 84, + D3DSIO_TEXDP3 = 85, + D3DSIO_TEXM3x3 = 86, + D3DSIO_TEXDEPTH = 87, + D3DSIO_CMP = 88, + D3DSIO_BEM = 89, + D3DSIO_DP2ADD = 90, + D3DSIO_DSX = 91, + D3DSIO_DSY = 92, + D3DSIO_TEXLDD = 93, + D3DSIO_SETP = 94, + D3DSIO_TEXLDL = 95, + D3DSIO_BREAKP = 96, + D3DSIO_PHASE = 0xFFFD, + D3DSIO_COMMENT = 0xFFFE, + D3DSIO_END = 0xFFFF, +}} +pub const D3DSI_COISSUE: ::DWORD = 0x40000000; +pub const D3DSP_OPCODESPECIFICCONTROL_MASK: ::DWORD = 0x00ff0000; +pub const D3DSP_OPCODESPECIFICCONTROL_SHIFT: ::DWORD = 16; +pub const D3DSI_TEXLD_PROJECT: ::DWORD = 0x01 << D3DSP_OPCODESPECIFICCONTROL_SHIFT; +pub const D3DSI_TEXLD_BIAS: ::DWORD = 0x02 << D3DSP_OPCODESPECIFICCONTROL_SHIFT; +ENUM!{enum D3DSHADER_COMPARISON { + D3DSPC_RESERVED0 = 0, + D3DSPC_GT = 1, + D3DSPC_EQ = 2, + D3DSPC_GE = 3, + D3DSPC_LT = 4, + D3DSPC_NE = 5, + D3DSPC_LE = 6, + D3DSPC_RESERVED1 = 7, +}} +pub const D3DSHADER_COMPARISON_SHIFT: ::DWORD = D3DSP_OPCODESPECIFICCONTROL_SHIFT; +pub const D3DSHADER_COMPARISON_MASK: ::DWORD = 0x7 << D3DSHADER_COMPARISON_SHIFT; +pub const D3DSHADER_INSTRUCTION_PREDICATED: ::DWORD = 0x1 << 28; +pub const D3DSP_DCL_USAGE_SHIFT: ::DWORD = 0; +pub const D3DSP_DCL_USAGE_MASK: ::DWORD = 0x0000000f; +pub const D3DSP_DCL_USAGEINDEX_SHIFT: ::DWORD = 16; +pub const D3DSP_DCL_USAGEINDEX_MASK: ::DWORD = 0x000f0000; +pub const D3DSP_TEXTURETYPE_SHIFT: ::DWORD = 27; +pub const D3DSP_TEXTURETYPE_MASK: ::DWORD = 0x78000000; +ENUM!{enum D3DSAMPLER_TEXTURE_TYPE { + D3DSTT_UNKNOWN = 0 << D3DSP_TEXTURETYPE_SHIFT, + D3DSTT_2D = 2 << D3DSP_TEXTURETYPE_SHIFT, + D3DSTT_CUBE = 3 << D3DSP_TEXTURETYPE_SHIFT, + D3DSTT_VOLUME = 4 << D3DSP_TEXTURETYPE_SHIFT, +}} +pub const D3DSP_REGNUM_MASK: ::DWORD = 0x000007FF; +pub const D3DSP_WRITEMASK_0: ::DWORD = 0x00010000; +pub const D3DSP_WRITEMASK_1: ::DWORD = 0x00020000; +pub const D3DSP_WRITEMASK_2: ::DWORD = 0x00040000; +pub const D3DSP_WRITEMASK_3: ::DWORD = 0x00080000; +pub const D3DSP_WRITEMASK_ALL: ::DWORD = 0x000F0000; +pub const D3DSP_DSTMOD_SHIFT: ::DWORD = 20; +pub const D3DSP_DSTMOD_MASK: ::DWORD = 0x00F00000; +pub const D3DSPDM_NONE: ::DWORD = 0 << D3DSP_DSTMOD_SHIFT; +pub const D3DSPDM_SATURATE: ::DWORD = 1 << D3DSP_DSTMOD_SHIFT; +pub const D3DSPDM_PARTIALPRECISION: ::DWORD = 2 << D3DSP_DSTMOD_SHIFT; +pub const D3DSPDM_MSAMPCENTROID: ::DWORD = 4 << D3DSP_DSTMOD_SHIFT; +pub const D3DSP_DSTSHIFT_SHIFT: ::DWORD = 24; +pub const D3DSP_DSTSHIFT_MASK: ::DWORD = 0x0F000000; +pub const D3DSP_REGTYPE_SHIFT: ::DWORD = 28; +pub const D3DSP_REGTYPE_SHIFT2: ::DWORD = 8; +pub const D3DSP_REGTYPE_MASK: ::DWORD = 0x70000000; +pub const D3DSP_REGTYPE_MASK2: ::DWORD = 0x00001800; +ENUM!{enum D3DSHADER_PARAM_REGISTER_TYPE { + D3DSPR_TEMP = 0, + D3DSPR_INPUT = 1, + D3DSPR_CONST = 2, + D3DSPR_ADDR = 3, + D3DSPR_TEXTURE = 3, + D3DSPR_RASTOUT = 4, + D3DSPR_ATTROUT = 5, + D3DSPR_TEXCRDOUT = 6, + D3DSPR_OUTPUT = 6, + D3DSPR_CONSTINT = 7, + D3DSPR_COLOROUT = 8, + D3DSPR_DEPTHOUT = 9, + D3DSPR_SAMPLER = 10, + D3DSPR_CONST2 = 11, + D3DSPR_CONST3 = 12, + D3DSPR_CONST4 = 13, + D3DSPR_CONSTBOOL = 14, + D3DSPR_LOOP = 15, + D3DSPR_TEMPFLOAT16 = 16, + D3DSPR_MISCTYPE = 17, + D3DSPR_LABEL = 18, + D3DSPR_PREDICATE = 19, +}} +ENUM!{enum D3DSHADER_MISCTYPE_OFFSETS { + D3DSMO_POSITION = 0, + D3DSMO_FACE = 1, +}} +ENUM!{enum D3DVS_RASTOUT_OFFSETS { + D3DSRO_POSITION = 0, + D3DSRO_FOG, + D3DSRO_POINT_SIZE, +}} +pub const D3DVS_ADDRESSMODE_SHIFT: ::DWORD = 13; +pub const D3DVS_ADDRESSMODE_MASK: ::DWORD = 1 << D3DVS_ADDRESSMODE_SHIFT; +ENUM!{enum D3DVS_ADDRESSMODE_TYPE { + D3DVS_ADDRMODE_ABSOLUTE = 0 << D3DVS_ADDRESSMODE_SHIFT, + D3DVS_ADDRMODE_RELATIVE = 1 << D3DVS_ADDRESSMODE_SHIFT, +}} +pub const D3DSHADER_ADDRESSMODE_SHIFT: ::DWORD = 13; +pub const D3DSHADER_ADDRESSMODE_MASK: ::DWORD = 1 << D3DSHADER_ADDRESSMODE_SHIFT; +ENUM!{enum D3DSHADER_ADDRESSMODE_TYPE { + D3DSHADER_ADDRMODE_ABSOLUTE = 0 << D3DSHADER_ADDRESSMODE_SHIFT, + D3DSHADER_ADDRMODE_RELATIVE = 1 << D3DSHADER_ADDRESSMODE_SHIFT, +}} +pub const D3DVS_SWIZZLE_SHIFT: ::DWORD = 16; +pub const D3DVS_SWIZZLE_MASK: ::DWORD = 0x00FF0000; +pub const D3DVS_X_X: ::DWORD = 0 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_X_Y: ::DWORD = 1 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_X_Z: ::DWORD = 2 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_X_W: ::DWORD = 3 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_Y_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Y_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Y_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Y_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Z_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_Z_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_Z_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_Z_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_W_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_W_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_W_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_W_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_NOSWIZZLE: ::DWORD = D3DVS_X_X | D3DVS_Y_Y | D3DVS_Z_Z | D3DVS_W_W; +pub const D3DSP_SWIZZLE_SHIFT: ::DWORD = 16; +pub const D3DSP_SWIZZLE_MASK: ::DWORD = 0x00FF0000; +pub const D3DSP_NOSWIZZLE: ::DWORD = (0 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | (2 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (3 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATERED: ::DWORD = (0 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (0 << (D3DSP_SWIZZLE_SHIFT + 2)) | (0 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (0 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATEGREEN: ::DWORD = (1 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | (1 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (1 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATEBLUE: ::DWORD = (2 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (2 << (D3DSP_SWIZZLE_SHIFT + 2)) | (2 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (2 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATEALPHA: ::DWORD = (3 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (3 << (D3DSP_SWIZZLE_SHIFT + 2)) | (3 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (3 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_SRCMOD_SHIFT: ::DWORD = 24; +pub const D3DSP_SRCMOD_MASK: ::DWORD = 0x0F000000; +ENUM!{enum D3DSHADER_PARAM_SRCMOD_TYPE { + D3DSPSM_NONE = 0 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_NEG = 1 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_BIAS = 2 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_BIASNEG = 3 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_SIGN = 4 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_SIGNNEG = 5 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_COMP = 6 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_X2 = 7 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_X2NEG = 8 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_DZ = 9 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_DW = 10 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_ABS = 11 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_ABSNEG = 12 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_NOT = 13 << D3DSP_SRCMOD_SHIFT, +}} +pub const D3DSP_MIN_PRECISION_SHIFT: ::DWORD = 14; +pub const D3DSP_MIN_PRECISION_MASK: ::DWORD = 0x0000C000; +ENUM!{enum D3DSHADER_MIN_PRECISION { + D3DMP_DEFAULT = 0, + D3DMP_16 = 1, + D3DMP_2_8 = 2, +}} +pub const D3DSI_COMMENTSIZE_SHIFT: ::DWORD = 16; +pub const D3DSI_COMMENTSIZE_MASK: ::DWORD = 0x7FFF0000; +pub const D3DPS_END: ::DWORD = 0x0000FFFF; +pub const D3DVS_END: ::DWORD = 0x0000FFFF; +ENUM!{enum D3DBASISTYPE { + D3DBASIS_BEZIER = 0, + D3DBASIS_BSPLINE = 1, + D3DBASIS_CATMULL_ROM = 2, +}} +ENUM!{enum D3DDEGREETYPE { + D3DDEGREE_LINEAR = 1, + D3DDEGREE_QUADRATIC = 2, + D3DDEGREE_CUBIC = 3, + D3DDEGREE_QUINTIC = 5, +}} +ENUM!{enum D3DPATCHEDGESTYLE { + D3DPATCHEDGE_DISCRETE = 0, + D3DPATCHEDGE_CONTINUOUS = 1, +}} +ENUM!{enum D3DSTATEBLOCKTYPE { + D3DSBT_ALL = 1, + D3DSBT_PIXELSTATE = 2, + D3DSBT_VERTEXSTATE = 3, +}} +FLAGS!{enum D3DVERTEXBLENDFLAGS { + D3DVBF_DISABLE = 0, + D3DVBF_1WEIGHTS = 1, + D3DVBF_2WEIGHTS = 2, + D3DVBF_3WEIGHTS = 3, + D3DVBF_TWEENING = 255, + D3DVBF_0WEIGHTS = 256, +}} +ENUM!{enum D3DTEXTURETRANSFORMFLAGS { + D3DTTFF_DISABLE = 0, + D3DTTFF_COUNT1 = 1, + D3DTTFF_COUNT2 = 2, + D3DTTFF_COUNT3 = 3, + D3DTTFF_COUNT4 = 4, + D3DTTFF_PROJECTED = 256, +}} +pub const D3DFVF_TEXTUREFORMAT2: ::DWORD = 0; +pub const D3DFVF_TEXTUREFORMAT1: ::DWORD = 3; +pub const D3DFVF_TEXTUREFORMAT3: ::DWORD = 1; +pub const D3DFVF_TEXTUREFORMAT4: ::DWORD = 2; +ENUM!{enum D3DDEVTYPE { + D3DDEVTYPE_HAL = 1, + D3DDEVTYPE_REF = 2, + D3DDEVTYPE_SW = 3, + D3DDEVTYPE_NULLREF = 4, +}} +ENUM!{enum D3DMULTISAMPLE_TYPE { + D3DMULTISAMPLE_NONE = 0, + D3DMULTISAMPLE_NONMASKABLE = 1, + D3DMULTISAMPLE_2_SAMPLES = 2, + D3DMULTISAMPLE_3_SAMPLES = 3, + D3DMULTISAMPLE_4_SAMPLES = 4, + D3DMULTISAMPLE_5_SAMPLES = 5, + D3DMULTISAMPLE_6_SAMPLES = 6, + D3DMULTISAMPLE_7_SAMPLES = 7, + D3DMULTISAMPLE_8_SAMPLES = 8, + D3DMULTISAMPLE_9_SAMPLES = 9, + D3DMULTISAMPLE_10_SAMPLES = 10, + D3DMULTISAMPLE_11_SAMPLES = 11, + D3DMULTISAMPLE_12_SAMPLES = 12, + D3DMULTISAMPLE_13_SAMPLES = 13, + D3DMULTISAMPLE_14_SAMPLES = 14, + D3DMULTISAMPLE_15_SAMPLES = 15, + D3DMULTISAMPLE_16_SAMPLES = 16, +}} +ENUM!{enum D3DFORMAT { + D3DFMT_UNKNOWN = 0, + D3DFMT_R8G8B8 = 20, + D3DFMT_A8R8G8B8 = 21, + D3DFMT_X8R8G8B8 = 22, + D3DFMT_R5G6B5 = 23, + D3DFMT_X1R5G5B5 = 24, + D3DFMT_A1R5G5B5 = 25, + D3DFMT_A4R4G4B4 = 26, + D3DFMT_R3G3B2 = 27, + D3DFMT_A8 = 28, + D3DFMT_A8R3G3B2 = 29, + D3DFMT_X4R4G4B4 = 30, + D3DFMT_A2B10G10R10 = 31, + D3DFMT_A8B8G8R8 = 32, + D3DFMT_X8B8G8R8 = 33, + D3DFMT_G16R16 = 34, + D3DFMT_A2R10G10B10 = 35, + D3DFMT_A16B16G16R16 = 36, + D3DFMT_A8P8 = 40, + D3DFMT_P8 = 41, + D3DFMT_L8 = 50, + D3DFMT_A8L8 = 51, + D3DFMT_A4L4 = 52, + D3DFMT_V8U8 = 60, + D3DFMT_L6V5U5 = 61, + D3DFMT_X8L8V8U8 = 62, + D3DFMT_Q8W8V8U8 = 63, + D3DFMT_V16U16 = 64, + D3DFMT_A2W10V10U10 = 67, + D3DFMT_UYVY = MAKEFOURCC!(b'U', b'Y', b'V', b'Y') as u32, + D3DFMT_R8G8_B8G8 = MAKEFOURCC!(b'R', b'G', b'B', b'G') as u32, + D3DFMT_YUY2 = MAKEFOURCC!(b'Y', b'U', b'Y', b'2') as u32, + D3DFMT_G8R8_G8B8 = MAKEFOURCC!(b'G', b'R', b'G', b'B') as u32, + D3DFMT_DXT1 = MAKEFOURCC!(b'D', b'X', b'T', b'1') as u32, + D3DFMT_DXT2 = MAKEFOURCC!(b'D', b'X', b'T', b'2') as u32, + D3DFMT_DXT3 = MAKEFOURCC!(b'D', b'X', b'T', b'3') as u32, + D3DFMT_DXT4 = MAKEFOURCC!(b'D', b'X', b'T', b'4') as u32, + D3DFMT_DXT5 = MAKEFOURCC!(b'D', b'X', b'T', b'5') as u32, + D3DFMT_D16_LOCKABLE = 70, + D3DFMT_D32 = 71, + D3DFMT_D15S1 = 73, + D3DFMT_D24S8 = 75, + D3DFMT_D24X8 = 77, + D3DFMT_D24X4S4 = 79, + D3DFMT_D16 = 80, + D3DFMT_D32F_LOCKABLE = 82, + D3DFMT_D24FS8 = 83, + D3DFMT_D32_LOCKABLE = 84, + D3DFMT_S8_LOCKABLE = 85, + D3DFMT_L16 = 81, + D3DFMT_VERTEXDATA = 100, + D3DFMT_INDEX16 = 101, + D3DFMT_INDEX32 = 102, + D3DFMT_Q16W16V16U16 = 110, + D3DFMT_MULTI2_ARGB8 = MAKEFOURCC!(b'M', b'E', b'T', b'1') as u32, + D3DFMT_R16F = 111, + D3DFMT_G16R16F = 112, + D3DFMT_A16B16G16R16F = 113, + D3DFMT_R32F = 114, + D3DFMT_G32R32F = 115, + D3DFMT_A32B32G32R32F = 116, + D3DFMT_CxV8U8 = 117, + D3DFMT_A1 = 118, + D3DFMT_A2B10G10R10_XR_BIAS = 119, + D3DFMT_BINARYBUFFER = 199, +}} +STRUCT!{struct D3DDISPLAYMODE { + Width: ::UINT, + Height: ::UINT, + RefreshRate: ::UINT, + Format: D3DFORMAT, +}} +STRUCT!{struct D3DDEVICE_CREATION_PARAMETERS { + AdapterOrdinal: ::UINT, + DeviceType: D3DDEVTYPE, + hFocusWindow: ::HWND, + BehaviorFlags: ::DWORD, +}} +ENUM!{enum D3DSWAPEFFECT { + D3DSWAPEFFECT_DISCARD = 1, + D3DSWAPEFFECT_FLIP = 2, + D3DSWAPEFFECT_COPY = 3, + D3DSWAPEFFECT_OVERLAY = 4, + D3DSWAPEFFECT_FLIPEX = 5, +}} +ENUM!{enum D3DPOOL { + D3DPOOL_DEFAULT = 0, + D3DPOOL_MANAGED = 1, + D3DPOOL_SYSTEMMEM = 2, + D3DPOOL_SCRATCH = 3, +}} +pub const D3DPRESENT_RATE_DEFAULT: ::DWORD = 0x00000000; +STRUCT!{struct D3DPRESENT_PARAMETERS { + BackBufferWidth: ::UINT, + BackBufferHeight: ::UINT, + BackBufferFormat: D3DFORMAT, + BackBufferCount: ::UINT, + MultiSampleType: D3DMULTISAMPLE_TYPE, + MultiSampleQuality: ::DWORD, + SwapEffect: D3DSWAPEFFECT, + hDeviceWindow: ::HWND, + Windowed: ::BOOL, + EnableAutoDepthStencil: ::BOOL, + AutoDepthStencilFormat: D3DFORMAT, + Flags: ::DWORD, + FullScreen_RefreshRateInHz: ::UINT, + PresentationInterval: ::UINT, +}} +pub const D3DPRESENTFLAG_LOCKABLE_BACKBUFFER: ::DWORD = 0x00000001; +pub const D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL: ::DWORD = 0x00000002; +pub const D3DPRESENTFLAG_DEVICECLIP: ::DWORD = 0x00000004; +pub const D3DPRESENTFLAG_VIDEO: ::DWORD = 0x00000010; +pub const D3DPRESENTFLAG_NOAUTOROTATE: ::DWORD = 0x00000020; +pub const D3DPRESENTFLAG_UNPRUNEDMODE: ::DWORD = 0x00000040; +pub const D3DPRESENTFLAG_OVERLAY_LIMITEDRGB: ::DWORD = 0x00000080; +pub const D3DPRESENTFLAG_OVERLAY_YCbCr_BT709: ::DWORD = 0x00000100; +pub const D3DPRESENTFLAG_OVERLAY_YCbCr_xvYCC: ::DWORD = 0x00000200; +pub const D3DPRESENTFLAG_RESTRICTED_CONTENT: ::DWORD = 0x00000400; +pub const D3DPRESENTFLAG_RESTRICT_SHARED_RESOURCE_DRIVER: ::DWORD = 0x00000800; +STRUCT!{nodebug struct D3DGAMMARAMP { + red: [::WORD; 256], + green: [::WORD; 256], + blue: [::WORD; 256], +}} +ENUM!{enum D3DBACKBUFFER_TYPE { + D3DBACKBUFFER_TYPE_MONO = 0, + D3DBACKBUFFER_TYPE_LEFT = 1, + D3DBACKBUFFER_TYPE_RIGHT = 2, +}} +ENUM!{enum D3DRESOURCETYPE { + D3DRTYPE_SURFACE = 1, + D3DRTYPE_VOLUME = 2, + D3DRTYPE_TEXTURE = 3, + D3DRTYPE_VOLUMETEXTURE = 4, + D3DRTYPE_CUBETEXTURE = 5, + D3DRTYPE_VERTEXBUFFER = 6, + D3DRTYPE_INDEXBUFFER = 7, +}} +pub const D3DUSAGE_RENDERTARGET: ::DWORD = 0x00000001; +pub const D3DUSAGE_DEPTHSTENCIL: ::DWORD = 0x00000002; +pub const D3DUSAGE_DYNAMIC: ::DWORD = 0x00000200; +pub const D3DUSAGE_NONSECURE: ::DWORD = 0x00800000; +pub const D3DUSAGE_AUTOGENMIPMAP: ::DWORD = 0x00000400; +pub const D3DUSAGE_DMAP: ::DWORD = 0x00004000; +pub const D3DUSAGE_QUERY_LEGACYBUMPMAP: ::DWORD = 0x00008000; +pub const D3DUSAGE_QUERY_SRGBREAD: ::DWORD = 0x00010000; +pub const D3DUSAGE_QUERY_FILTER: ::DWORD = 0x00020000; +pub const D3DUSAGE_QUERY_SRGBWRITE: ::DWORD = 0x00040000; +pub const D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING: ::DWORD = 0x00080000; +pub const D3DUSAGE_QUERY_VERTEXTEXTURE: ::DWORD = 0x00100000; +pub const D3DUSAGE_QUERY_WRAPANDMIP: ::DWORD = 0x00200000; +pub const D3DUSAGE_WRITEONLY: ::DWORD = 0x00000008; +pub const D3DUSAGE_SOFTWAREPROCESSING: ::DWORD = 0x00000010; +pub const D3DUSAGE_DONOTCLIP: ::DWORD = 0x00000020; +pub const D3DUSAGE_POINTS: ::DWORD = 0x00000040; +pub const D3DUSAGE_RTPATCHES: ::DWORD = 0x00000080; +pub const D3DUSAGE_NPATCHES: ::DWORD = 0x00000100; +pub const D3DUSAGE_TEXTAPI: ::DWORD = 0x10000000; +pub const D3DUSAGE_RESTRICTED_CONTENT: ::DWORD = 0x00000800; +pub const D3DUSAGE_RESTRICT_SHARED_RESOURCE: ::DWORD = 0x00002000; +pub const D3DUSAGE_RESTRICT_SHARED_RESOURCE_DRIVER: ::DWORD = 0x00001000; +ENUM!{enum D3DCUBEMAP_FACES { + D3DCUBEMAP_FACE_POSITIVE_X = 0, + D3DCUBEMAP_FACE_NEGATIVE_X = 1, + D3DCUBEMAP_FACE_POSITIVE_Y = 2, + D3DCUBEMAP_FACE_NEGATIVE_Y = 3, + D3DCUBEMAP_FACE_POSITIVE_Z = 4, + D3DCUBEMAP_FACE_NEGATIVE_Z = 5, +}} +pub const D3DLOCK_READONLY: ::DWORD = 0x00000010; +pub const D3DLOCK_DISCARD: ::DWORD = 0x00002000; +pub const D3DLOCK_NOOVERWRITE: ::DWORD = 0x00001000; +pub const D3DLOCK_NOSYSLOCK: ::DWORD = 0x00000800; +pub const D3DLOCK_DONOTWAIT: ::DWORD = 0x00004000; +pub const D3DLOCK_NO_DIRTY_UPDATE: ::DWORD = 0x00008000; +STRUCT!{struct D3DVERTEXBUFFER_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + Size: ::UINT, + FVF: ::DWORD, +}} +STRUCT!{struct D3DINDEXBUFFER_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + Size: ::UINT, +}} +STRUCT!{struct D3DSURFACE_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + MultiSampleType: D3DMULTISAMPLE_TYPE, + MultiSampleQuality: ::DWORD, + Width: ::UINT, + Height: ::UINT, +}} +STRUCT!{struct D3DVOLUME_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + Width: ::UINT, + Height: ::UINT, + Depth: ::UINT, +}} +STRUCT!{struct D3DLOCKED_RECT { + Pitch: ::INT, + pBits: *mut ::c_void, +}} +STRUCT!{struct D3DBOX { + Left: ::UINT, + Top: ::UINT, + Right: ::UINT, + Bottom: ::UINT, + Front: ::UINT, + Back: ::UINT, +}} +STRUCT!{struct D3DLOCKED_BOX { + RowPitch: ::INT, + SlicePitch: ::INT, + pBits: *mut ::c_void, +}} +STRUCT!{struct D3DRANGE { + Offset: ::UINT, + Size: ::UINT, +}} +STRUCT!{struct D3DRECTPATCH_INFO { + StartVertexOffsetWidth: ::UINT, + StartVertexOffsetHeight: ::UINT, + Width: ::UINT, + Height: ::UINT, + Stride: ::UINT, + Basis: D3DBASISTYPE, + Degree: D3DDEGREETYPE, +}} +STRUCT!{struct D3DTRIPATCH_INFO { + StartVertexOffset: ::UINT, + NumVertices: ::UINT, + Basis: D3DBASISTYPE, + Degree: D3DDEGREETYPE, +}} +pub const MAX_DEVICE_IDENTIFIER_STRING: usize = 512; +STRUCT!{nodebug struct D3DADAPTER_IDENTIFIER9 { + Driver: [::c_char; MAX_DEVICE_IDENTIFIER_STRING], + Description: [::c_char; MAX_DEVICE_IDENTIFIER_STRING], + DeviceName: [::c_char; 32], + DriverVersion: ::LARGE_INTEGER, + VendorId: ::DWORD, + DeviceId: ::DWORD, + SubSysId: ::DWORD, + Revision: ::DWORD, + DeviceIdentifier: ::GUID, + WHQLLevel: ::DWORD, +}} +STRUCT!{struct D3DRASTER_STATUS { + InVBlank: ::BOOL, + ScanLine: ::UINT, +}} +ENUM!{enum D3DDEBUGMONITORTOKENS { + D3DDMT_ENABLE = 0, + D3DDMT_DISABLE = 1, +}} +ENUM!{enum D3DQUERYTYPE { + D3DQUERYTYPE_VCACHE = 4, + D3DQUERYTYPE_RESOURCEMANAGER = 5, + D3DQUERYTYPE_VERTEXSTATS = 6, + D3DQUERYTYPE_EVENT = 8, + D3DQUERYTYPE_OCCLUSION = 9, + D3DQUERYTYPE_TIMESTAMP = 10, + D3DQUERYTYPE_TIMESTAMPDISJOINT = 11, + D3DQUERYTYPE_TIMESTAMPFREQ = 12, + D3DQUERYTYPE_PIPELINETIMINGS = 13, + D3DQUERYTYPE_INTERFACETIMINGS = 14, + D3DQUERYTYPE_VERTEXTIMINGS = 15, + D3DQUERYTYPE_PIXELTIMINGS = 16, + D3DQUERYTYPE_BANDWIDTHTIMINGS = 17, + D3DQUERYTYPE_CACHEUTILIZATION = 18, + D3DQUERYTYPE_MEMORYPRESSURE = 19, +}} +pub const D3DISSUE_END: ::DWORD = 1 << 0; +pub const D3DISSUE_BEGIN: ::DWORD = 1 << 1; +pub const D3DGETDATA_FLUSH: ::DWORD = 1 << 0; +STRUCT!{struct D3DRESOURCESTATS { + bThrashing: ::BOOL, + ApproxBytesDownloaded: ::DWORD, + NumEvicts: ::DWORD, + NumVidCreates: ::DWORD, + LastPri: ::DWORD, + NumUsed: ::DWORD, + NumUsedInVidMem: ::DWORD, + WorkingSet: ::DWORD, + WorkingSetBytes: ::DWORD, + TotalManaged: ::DWORD, + TotalBytes: ::DWORD, +}} +pub const D3DRTYPECOUNT: usize = 8; +STRUCT!{struct D3DDEVINFO_RESOURCEMANAGER { + stats: [D3DRESOURCESTATS; 8 /*D3DRTYPECOUNT, rust bug?*/], +}} +pub type LPD3DDEVINFO_RESOURCEMANAGER = *mut D3DDEVINFO_RESOURCEMANAGER; +STRUCT!{struct D3DDEVINFO_D3DVERTEXSTATS { + NumRenderedTriangles: ::DWORD, + NumExtraClippingTriangles: ::DWORD, +}} +pub type LPD3DDEVINFO_D3DVERTEXSTATS = *mut D3DDEVINFO_D3DVERTEXSTATS; +STRUCT!{struct D3DDEVINFO_VCACHE { + Pattern: ::DWORD, + OptMethod: ::DWORD, + CacheSize: ::DWORD, + MagicNumber: ::DWORD, +}} +pub type LPD3DDEVINFO_VCACHE = *mut D3DDEVINFO_VCACHE; +STRUCT!{struct D3DDEVINFO_D3D9PIPELINETIMINGS { + VertexProcessingTimePercent: ::FLOAT, + PixelProcessingTimePercent: ::FLOAT, + OtherGPUProcessingTimePercent: ::FLOAT, + GPUIdleTimePercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9INTERFACETIMINGS { + WaitingForGPUToUseApplicationResourceTimePercent: ::FLOAT, + WaitingForGPUToAcceptMoreCommandsTimePercent: ::FLOAT, + WaitingForGPUToStayWithinLatencyTimePercent: ::FLOAT, + WaitingForGPUExclusiveResourceTimePercent: ::FLOAT, + WaitingForGPUOtherTimePercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9STAGETIMINGS { + MemoryProcessingPercent: ::FLOAT, + ComputationProcessingPercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9BANDWIDTHTIMINGS { + MaxBandwidthUtilized: ::FLOAT, + FrontEndUploadMemoryUtilizedPercent: ::FLOAT, + VertexRateUtilizedPercent: ::FLOAT, + TriangleSetupRateUtilizedPercent: ::FLOAT, + FillRateUtilizedPercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9CACHEUTILIZATION { + TextureCacheHitRate: ::FLOAT, + PostTransformVertexCacheHitRate: ::FLOAT, +}} +STRUCT!{struct D3DMEMORYPRESSURE { + BytesEvictedFromProcess: ::UINT64, + SizeOfInefficientAllocation: ::UINT64, + LevelOfEfficiency: ::DWORD, +}} +ENUM!{enum D3DCOMPOSERECTSOP { + D3DCOMPOSERECTS_COPY = 1, + D3DCOMPOSERECTS_OR = 2, + D3DCOMPOSERECTS_AND = 3, + D3DCOMPOSERECTS_NEG = 4, +}} +STRUCT!{struct D3DCOMPOSERECTDESC { + X: ::USHORT, + Y: ::USHORT, + Width: ::USHORT, + Height: ::USHORT, +}} +STRUCT!{struct D3DCOMPOSERECTDESTINATION { + SrcRectIndex: ::USHORT, + Reserved: ::USHORT, + X: ::SHORT, + Y: ::SHORT, +}} +pub const D3DCOMPOSERECTS_MAXNUMRECTS: ::DWORD = 0xFFFF; +pub const D3DCONVOLUTIONMONO_MAXWIDTH: ::DWORD = 7; +pub const D3DCONVOLUTIONMONO_MAXHEIGHT: ::DWORD = D3DCONVOLUTIONMONO_MAXWIDTH; +pub const D3DFMT_A1_SURFACE_MAXWIDTH: ::DWORD = 8192; +pub const D3DFMT_A1_SURFACE_MAXHEIGHT: ::DWORD = 2048; +STRUCT!{struct D3DPRESENTSTATS { + PresentCount: ::UINT, + PresentRefreshCount: ::UINT, + SyncRefreshCount: ::UINT, + SyncQPCTime: ::LARGE_INTEGER, + SyncGPUTime: ::LARGE_INTEGER, +}} +ENUM!{enum D3DSCANLINEORDERING { + D3DSCANLINEORDERING_UNKNOWN = 0, + D3DSCANLINEORDERING_PROGRESSIVE = 1, + D3DSCANLINEORDERING_INTERLACED = 2, +}} +STRUCT!{struct D3DDISPLAYMODEEX { + Size: ::UINT, + Width: ::UINT, + Height: ::UINT, + RefreshRate: ::UINT, + Format: D3DFORMAT, + ScanLineOrdering: D3DSCANLINEORDERING, +}} +STRUCT!{struct D3DDISPLAYMODEFILTER { + Size: ::UINT, + Format: D3DFORMAT, + ScanLineOrdering: D3DSCANLINEORDERING, +}} +ENUM!{enum D3DDISPLAYROTATION { + D3DDISPLAYROTATION_IDENTITY = 1, + D3DDISPLAYROTATION_90 = 2, + D3DDISPLAYROTATION_180 = 3, + D3DDISPLAYROTATION_270 = 4, +}} +pub const D3D9_RESOURCE_PRIORITY_MINIMUM: ::DWORD = 0x28000000; +pub const D3D9_RESOURCE_PRIORITY_LOW: ::DWORD = 0x50000000; +pub const D3D9_RESOURCE_PRIORITY_NORMAL: ::DWORD = 0x78000000; +pub const D3D9_RESOURCE_PRIORITY_HIGH: ::DWORD = 0xa0000000; +pub const D3D9_RESOURCE_PRIORITY_MAXIMUM: ::DWORD = 0xc8000000; +pub const D3D_OMAC_SIZE: usize = 16; +STRUCT!{struct D3D_OMAC { + Omac: [::BYTE; D3D_OMAC_SIZE], +}} +ENUM!{enum D3DAUTHENTICATEDCHANNELTYPE { + D3DAUTHENTICATEDCHANNEL_D3D9 = 1, + D3DAUTHENTICATEDCHANNEL_DRIVER_SOFTWARE = 2, + D3DAUTHENTICATEDCHANNEL_DRIVER_HARDWARE = 3, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERY_INPUT { + QueryType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT { + omac: D3D_OMAC, + QueryType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, + ReturnCode: ::HRESULT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS { + Value: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYPROTECTION_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + ProtectionFlags: D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYCHANNELTYPE_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + ChannelType: D3DAUTHENTICATEDCHANNELTYPE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYDEVICEHANDLE_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DeviceHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYCRYPTOSESSION_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + DXVA2DecodeHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYCRYPTOSESSION_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DXVA2DecodeHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + DeviceHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESSCOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + NumRestrictedSharedResourceProcesses: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESS_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + ProcessIndex: ::UINT, +}} +ENUM!{enum D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE { + PROCESSIDTYPE_UNKNOWN = 0, + PROCESSIDTYPE_DWM = 1, + PROCESSIDTYPE_HANDLE = 2, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESS_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + ProcessIndex: ::UINT, + ProcessIdentifer: D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE, + ProcessHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYUNRESTRICTEDPROTECTEDSHAREDRESOURCECOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + NumUnrestrictedProtectedSharedResources: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + NumOutputIDs: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTID_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + OutputIDIndex: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTID_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + OutputIDIndex: ::UINT, + OutputID: ::UINT64, +}} +FLAGS!{enum D3DBUSTYPE { + D3DBUSTYPE_OTHER = 0x00000000, + D3DBUSTYPE_PCI = 0x00000001, + D3DBUSTYPE_PCIX = 0x00000002, + D3DBUSTYPE_PCIEXPRESS = 0x00000003, + D3DBUSTYPE_AGP = 0x00000004, + D3DBUSIMPL_MODIFIER_INSIDE_OF_CHIPSET = 0x00010000, + MD3DBUSIMPL_ODIFIER_TRACKS_ON_MOTHER_BOARD_TO_CHIP = 0x00020000, + D3DBUSIMPL_MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_SOCKET = 0x00030000, + D3DBUSIMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR = 0x00040000, + D3DBUSIMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR_INSIDE_OF_NUAE = 0x00050000, + D3DBUSIMPL_MODIFIER_NON_STANDARD = 0x80000000, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYINFOBUSTYPE_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + BusType: D3DBUSTYPE, + bAccessibleInContiguousBlocks: ::BOOL, + bAccessibleInNonContiguousBlocks: ::BOOL, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUIDCOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + NumEncryptionGuids: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUID_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + EncryptionGuidIndex: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUID_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + EncryptionGuidIndex: ::UINT, + EncryptionGuid: ::GUID, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYUNCOMPRESSEDENCRYPTIONLEVEL_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + EncryptionGuid: ::GUID, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT { + omac: D3D_OMAC, + ConfigureType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURE_OUTPUT { + omac: D3D_OMAC, + ConfigureType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, + ReturnCode: ::HRESULT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGUREINITIALIZE { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + StartSequenceQuery: ::UINT, + StartSequenceConfigure: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGUREPROTECTION { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + Protections: D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURECRYPTOSESSION { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + DXVA2DecodeHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + DeviceHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURESHAREDRESOURCE { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + ProcessIdentiferType: D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE, + ProcessHandle: ::HANDLE, + AllowAccess: ::BOOL, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGUREUNCOMPRESSEDENCRYPTION { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + EncryptionGuid: ::GUID, +}} +STRUCT!{struct D3DENCRYPTED_BLOCK_INFO { + NumEncryptedBytesAtBeginning: ::UINT, + NumBytesInSkipPattern: ::UINT, + NumBytesInEncryptPattern: ::UINT, +}} +STRUCT!{struct D3DAES_CTR_IV { + IV: ::UINT64, + Count: ::UINT64, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3dcommon.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3dcommon.rs new file mode 100644 index 0000000..51a1b4e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3dcommon.rs @@ -0,0 +1,753 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of d3dcommon.h +ENUM!{enum D3D_DRIVER_TYPE { + D3D_DRIVER_TYPE_UNKNOWN, + D3D_DRIVER_TYPE_HARDWARE, + D3D_DRIVER_TYPE_REFERENCE, + D3D_DRIVER_TYPE_NULL, + D3D_DRIVER_TYPE_SOFTWARE, + D3D_DRIVER_TYPE_WARP, +}} +ENUM!{enum D3D_FEATURE_LEVEL { + D3D_FEATURE_LEVEL_9_1 = 0x9100, + D3D_FEATURE_LEVEL_9_2 = 0x9200, + D3D_FEATURE_LEVEL_9_3 = 0x9300, + D3D_FEATURE_LEVEL_10_0 = 0xa000, + D3D_FEATURE_LEVEL_10_1 = 0xa100, + D3D_FEATURE_LEVEL_11_0 = 0xb000, + D3D_FEATURE_LEVEL_11_1 = 0xb100, + D3D_FEATURE_LEVEL_12_0 = 0xc000, + D3D_FEATURE_LEVEL_12_1 = 0xc100, +}} +ENUM!{enum D3D_PRIMITIVE_TOPOLOGY { + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0, + D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1, + D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5, + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13, + D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33, + D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34, + D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35, + D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36, + D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37, + D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38, + D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39, + D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40, + D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41, + D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42, + D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43, + D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44, + D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45, + D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46, + D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47, + D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48, + D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49, + D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50, + D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51, + D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52, + D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53, + D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54, + D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55, + D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56, + D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57, + D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58, + D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59, + D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60, + D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61, + D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62, + D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63, + D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64, +}} +pub const D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; +pub const D3D10_PRIMITIVE_TOPOLOGY_POINTLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_POINTLIST; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; +pub const D3D11_PRIMITIVE_TOPOLOGY_POINTLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_POINTLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST; +ENUM!{enum D3D_PRIMITIVE { + D3D_PRIMITIVE_UNDEFINED = 0, + D3D_PRIMITIVE_POINT = 1, + D3D_PRIMITIVE_LINE = 2, + D3D_PRIMITIVE_TRIANGLE = 3, + D3D_PRIMITIVE_LINE_ADJ = 6, + D3D_PRIMITIVE_TRIANGLE_ADJ = 7, + D3D_PRIMITIVE_1_CONTROL_POINT_PATCH = 8, + D3D_PRIMITIVE_2_CONTROL_POINT_PATCH = 9, + D3D_PRIMITIVE_3_CONTROL_POINT_PATCH = 10, + D3D_PRIMITIVE_4_CONTROL_POINT_PATCH = 11, + D3D_PRIMITIVE_5_CONTROL_POINT_PATCH = 12, + D3D_PRIMITIVE_6_CONTROL_POINT_PATCH = 13, + D3D_PRIMITIVE_7_CONTROL_POINT_PATCH = 14, + D3D_PRIMITIVE_8_CONTROL_POINT_PATCH = 15, + D3D_PRIMITIVE_9_CONTROL_POINT_PATCH = 16, + D3D_PRIMITIVE_10_CONTROL_POINT_PATCH = 17, + D3D_PRIMITIVE_11_CONTROL_POINT_PATCH = 18, + D3D_PRIMITIVE_12_CONTROL_POINT_PATCH = 19, + D3D_PRIMITIVE_13_CONTROL_POINT_PATCH = 20, + D3D_PRIMITIVE_14_CONTROL_POINT_PATCH = 21, + D3D_PRIMITIVE_15_CONTROL_POINT_PATCH = 22, + D3D_PRIMITIVE_16_CONTROL_POINT_PATCH = 23, + D3D_PRIMITIVE_17_CONTROL_POINT_PATCH = 24, + D3D_PRIMITIVE_18_CONTROL_POINT_PATCH = 25, + D3D_PRIMITIVE_19_CONTROL_POINT_PATCH = 26, + D3D_PRIMITIVE_20_CONTROL_POINT_PATCH = 28, + D3D_PRIMITIVE_21_CONTROL_POINT_PATCH = 29, + D3D_PRIMITIVE_22_CONTROL_POINT_PATCH = 30, + D3D_PRIMITIVE_23_CONTROL_POINT_PATCH = 31, + D3D_PRIMITIVE_24_CONTROL_POINT_PATCH = 32, + D3D_PRIMITIVE_25_CONTROL_POINT_PATCH = 33, + D3D_PRIMITIVE_26_CONTROL_POINT_PATCH = 34, + D3D_PRIMITIVE_27_CONTROL_POINT_PATCH = 35, + D3D_PRIMITIVE_28_CONTROL_POINT_PATCH = 36, + D3D_PRIMITIVE_29_CONTROL_POINT_PATCH = 37, + D3D_PRIMITIVE_30_CONTROL_POINT_PATCH = 38, + D3D_PRIMITIVE_31_CONTROL_POINT_PATCH = 39, + D3D_PRIMITIVE_32_CONTROL_POINT_PATCH = 40, +}} +pub const D3D10_PRIMITIVE_UNDEFINED: ::D3D_PRIMITIVE = D3D_PRIMITIVE_UNDEFINED; +pub const D3D10_PRIMITIVE_POINT: ::D3D_PRIMITIVE = D3D_PRIMITIVE_POINT; +pub const D3D10_PRIMITIVE_LINE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE; +pub const D3D10_PRIMITIVE_TRIANGLE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE; +pub const D3D10_PRIMITIVE_LINE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE_ADJ; +pub const D3D10_PRIMITIVE_TRIANGLE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE_ADJ; +pub const D3D11_PRIMITIVE_UNDEFINED: ::D3D_PRIMITIVE = D3D_PRIMITIVE_UNDEFINED; +pub const D3D11_PRIMITIVE_POINT: ::D3D_PRIMITIVE = D3D_PRIMITIVE_POINT; +pub const D3D11_PRIMITIVE_LINE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE; +pub const D3D11_PRIMITIVE_TRIANGLE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE; +pub const D3D11_PRIMITIVE_LINE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE_ADJ; +pub const D3D11_PRIMITIVE_TRIANGLE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE_ADJ; +pub const D3D11_PRIMITIVE_1_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_1_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_2_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_2_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_3_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_3_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_4_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_4_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_5_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_5_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_6_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_6_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_7_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_7_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_8_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_8_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_9_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_9_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_10_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_10_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_11_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_11_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_12_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_12_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_13_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_13_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_14_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_14_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_15_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_15_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_16_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_16_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_17_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_17_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_18_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_18_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_19_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_19_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_20_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_20_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_21_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_21_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_22_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_22_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_23_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_23_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_24_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_24_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_25_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_25_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_26_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_26_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_27_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_27_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_28_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_28_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_29_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_29_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_30_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_30_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_31_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_31_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_32_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_32_CONTROL_POINT_PATCH; +ENUM!{enum D3D_SRV_DIMENSION { + D3D_SRV_DIMENSION_UNKNOWN = 0, + D3D_SRV_DIMENSION_BUFFER = 1, + D3D_SRV_DIMENSION_TEXTURE1D = 2, + D3D_SRV_DIMENSION_TEXTURE1DARRAY = 3, + D3D_SRV_DIMENSION_TEXTURE2D = 4, + D3D_SRV_DIMENSION_TEXTURE2DARRAY = 5, + D3D_SRV_DIMENSION_TEXTURE2DMS = 6, + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D_SRV_DIMENSION_TEXTURE3D = 8, + D3D_SRV_DIMENSION_TEXTURECUBE = 9, + D3D_SRV_DIMENSION_TEXTURECUBEARRAY = 10, + D3D_SRV_DIMENSION_BUFFEREX = 11, +}} +pub const D3D10_SRV_DIMENSION_UNKNOWN: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_UNKNOWN; +pub const D3D10_SRV_DIMENSION_BUFFER: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFER; +pub const D3D10_SRV_DIMENSION_TEXTURE1D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1D; +pub const D3D10_SRV_DIMENSION_TEXTURE1DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1DARRAY; +pub const D3D10_SRV_DIMENSION_TEXTURE2D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2D; +pub const D3D10_SRV_DIMENSION_TEXTURE2DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DARRAY; +pub const D3D10_SRV_DIMENSION_TEXTURE2DMS: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMS; +pub const D3D10_SRV_DIMENSION_TEXTURE2DMSARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY; +pub const D3D10_SRV_DIMENSION_TEXTURE3D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE3D; +pub const D3D10_SRV_DIMENSION_TEXTURECUBE: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBE; +pub const D3D10_1_SRV_DIMENSION_UNKNOWN: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_UNKNOWN; +pub const D3D10_1_SRV_DIMENSION_BUFFER: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFER; +pub const D3D10_1_SRV_DIMENSION_TEXTURE1D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1D; +pub const D3D10_1_SRV_DIMENSION_TEXTURE1DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1DARRAY; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2D; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DARRAY; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2DMS: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMS; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2DMSARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY; +pub const D3D10_1_SRV_DIMENSION_TEXTURE3D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE3D; +pub const D3D10_1_SRV_DIMENSION_TEXTURECUBE: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBE; +pub const D3D10_1_SRV_DIMENSION_TEXTURECUBEARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBEARRAY; +pub const D3D11_SRV_DIMENSION_UNKNOWN: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_UNKNOWN; +pub const D3D11_SRV_DIMENSION_BUFFER: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFER; +pub const D3D11_SRV_DIMENSION_TEXTURE1D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1D; +pub const D3D11_SRV_DIMENSION_TEXTURE1DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1DARRAY; +pub const D3D11_SRV_DIMENSION_TEXTURE2D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2D; +pub const D3D11_SRV_DIMENSION_TEXTURE2DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DARRAY; +pub const D3D11_SRV_DIMENSION_TEXTURE2DMS: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMS; +pub const D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY; +pub const D3D11_SRV_DIMENSION_TEXTURE3D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE3D; +pub const D3D11_SRV_DIMENSION_TEXTURECUBE: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBE; +pub const D3D11_SRV_DIMENSION_TEXTURECUBEARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBEARRAY; +pub const D3D11_SRV_DIMENSION_BUFFEREX: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFEREX; +STRUCT!{struct D3D_SHADER_MACRO { + Name: ::LPCSTR, + Definition: ::LPCSTR, +}} +pub type LPD3D_SHADER_MACRO = *mut D3D_SHADER_MACRO; +RIDL!( +interface ID3D10Blob(ID3D10BlobVtbl): IUnknown(IUnknownVtbl) { + fn GetBufferPointer(&mut self) -> ::LPVOID, + fn GetBufferSize(&mut self) -> ::SIZE_T +} +); +pub type LPD3D10BLOB = *mut ID3D10Blob; +pub type ID3DBlob = ID3D10Blob; +pub type LPD3DBLOB = *mut ID3DBlob; +ENUM!{enum D3D_INCLUDE_TYPE { + D3D_INCLUDE_LOCAL = 0, + D3D_INCLUDE_SYSTEM, +}} +pub const D3D10_INCLUDE_LOCAL: ::D3D_INCLUDE_TYPE = D3D_INCLUDE_LOCAL; +pub const D3D10_INCLUDE_SYSTEM: ::D3D_INCLUDE_TYPE = D3D_INCLUDE_SYSTEM; +RIDL!( +interface ID3DInclude(ID3DIncludeVtbl) { + fn Open( + &mut self, IncludeType: D3D_INCLUDE_TYPE, pFileName: ::LPCSTR, pParentData: ::LPCVOID, + ppData: *mut ::LPCVOID, pBytes: *mut ::UINT + ) -> ::HRESULT, + fn Close(&mut self, pData: ::LPCVOID) -> ::HRESULT +} +); +pub type LPD3DINCLUDE = *mut ID3DInclude; +ENUM!{enum D3D_SHADER_VARIABLE_CLASS { + D3D_SVC_SCALAR = 0, + D3D_SVC_VECTOR, + D3D_SVC_MATRIX_ROWS, + D3D_SVC_MATRIX_COLUMNS, + D3D_SVC_OBJECT, + D3D_SVC_STRUCT, + D3D_SVC_INTERFACE_CLASS, + D3D_SVC_INTERFACE_POINTER, +}} +pub const D3D10_SVC_SCALAR: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_SCALAR; +pub const D3D10_SVC_VECTOR: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_VECTOR; +pub const D3D10_SVC_MATRIX_ROWS: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_MATRIX_ROWS; +pub const D3D10_SVC_MATRIX_COLUMNS: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_MATRIX_COLUMNS; +pub const D3D10_SVC_OBJECT: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_OBJECT; +pub const D3D10_SVC_STRUCT: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_STRUCT; +pub const D3D11_SVC_INTERFACE_CLASS: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_INTERFACE_CLASS; +pub const D3D11_SVC_INTERFACE_POINTER: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_INTERFACE_POINTER; +FLAGS!{enum D3D_SHADER_VARIABLE_FLAGS { + D3D_SVF_USERPACKED = 1, + D3D_SVF_USED = 2, + D3D_SVF_INTERFACE_POINTER = 4, + D3D_SVF_INTERFACE_PARAMETER = 8, +}} +pub const D3D10_SVF_USERPACKED: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_USERPACKED; +pub const D3D10_SVF_USED: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_USED; +pub const D3D11_SVF_INTERFACE_POINTER: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_INTERFACE_POINTER; +pub const D3D11_SVF_INTERFACE_PARAMETER: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_INTERFACE_PARAMETER; +ENUM!{enum D3D_SHADER_VARIABLE_TYPE { + D3D_SVT_VOID = 0, + D3D_SVT_BOOL = 1, + D3D_SVT_INT = 2, + D3D_SVT_FLOAT = 3, + D3D_SVT_STRING = 4, + D3D_SVT_TEXTURE = 5, + D3D_SVT_TEXTURE1D = 6, + D3D_SVT_TEXTURE2D = 7, + D3D_SVT_TEXTURE3D = 8, + D3D_SVT_TEXTURECUBE = 9, + D3D_SVT_SAMPLER = 10, + D3D_SVT_SAMPLER1D = 11, + D3D_SVT_SAMPLER2D = 12, + D3D_SVT_SAMPLER3D = 13, + D3D_SVT_SAMPLERCUBE = 14, + D3D_SVT_PIXELSHADER = 15, + D3D_SVT_VERTEXSHADER = 16, + D3D_SVT_PIXELFRAGMENT = 17, + D3D_SVT_VERTEXFRAGMENT = 18, + D3D_SVT_UINT = 19, + D3D_SVT_UINT8 = 20, + D3D_SVT_GEOMETRYSHADER = 21, + D3D_SVT_RASTERIZER = 22, + D3D_SVT_DEPTHSTENCIL = 23, + D3D_SVT_BLEND = 24, + D3D_SVT_BUFFER = 25, + D3D_SVT_CBUFFER = 26, + D3D_SVT_TBUFFER = 27, + D3D_SVT_TEXTURE1DARRAY = 28, + D3D_SVT_TEXTURE2DARRAY = 29, + D3D_SVT_RENDERTARGETVIEW = 30, + D3D_SVT_DEPTHSTENCILVIEW = 31, + D3D_SVT_TEXTURE2DMS = 32, + D3D_SVT_TEXTURE2DMSARRAY = 33, + D3D_SVT_TEXTURECUBEARRAY = 34, + D3D_SVT_HULLSHADER = 35, + D3D_SVT_DOMAINSHADER = 36, + D3D_SVT_INTERFACE_POINTER = 37, + D3D_SVT_COMPUTESHADER = 38, + D3D_SVT_DOUBLE = 39, + D3D_SVT_RWTEXTURE1D = 40, + D3D_SVT_RWTEXTURE1DARRAY = 41, + D3D_SVT_RWTEXTURE2D = 42, + D3D_SVT_RWTEXTURE2DARRAY = 43, + D3D_SVT_RWTEXTURE3D = 44, + D3D_SVT_RWBUFFER = 45, + D3D_SVT_BYTEADDRESS_BUFFER = 46, + D3D_SVT_RWBYTEADDRESS_BUFFER = 47, + D3D_SVT_STRUCTURED_BUFFER = 48, + D3D_SVT_RWSTRUCTURED_BUFFER = 49, + D3D_SVT_APPEND_STRUCTURED_BUFFER = 50, + D3D_SVT_CONSUME_STRUCTURED_BUFFER = 51, + D3D_SVT_MIN8FLOAT = 52, + D3D_SVT_MIN10FLOAT = 53, + D3D_SVT_MIN16FLOAT = 54, + D3D_SVT_MIN12INT = 55, + D3D_SVT_MIN16INT = 56, + D3D_SVT_MIN16UINT = 57, +}} +pub const D3D10_SVT_VOID: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_VOID; +pub const D3D10_SVT_BOOL: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BOOL; +pub const D3D10_SVT_INT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_INT; +pub const D3D10_SVT_FLOAT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_FLOAT; +pub const D3D10_SVT_STRING: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_STRING; +pub const D3D10_SVT_TEXTURE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE; +pub const D3D10_SVT_TEXTURE1D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE1D; +pub const D3D10_SVT_TEXTURE2D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2D; +pub const D3D10_SVT_TEXTURE3D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE3D; +pub const D3D10_SVT_TEXTURECUBE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURECUBE; +pub const D3D10_SVT_SAMPLER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER; +pub const D3D10_SVT_SAMPLER1D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER1D; +pub const D3D10_SVT_SAMPLER2D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER2D; +pub const D3D10_SVT_SAMPLER3D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER3D; +pub const D3D10_SVT_SAMPLERCUBE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLERCUBE; +pub const D3D10_SVT_PIXELSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_PIXELSHADER; +pub const D3D10_SVT_VERTEXSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_VERTEXSHADER; +pub const D3D10_SVT_PIXELFRAGMENT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_PIXELFRAGMENT; +pub const D3D10_SVT_VERTEXFRAGMENT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_VERTEXFRAGMENT; +pub const D3D10_SVT_UINT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_UINT; +pub const D3D10_SVT_UINT8: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_UINT8; +pub const D3D10_SVT_GEOMETRYSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_GEOMETRYSHADER; +pub const D3D10_SVT_RASTERIZER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RASTERIZER; +pub const D3D10_SVT_DEPTHSTENCIL: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DEPTHSTENCIL; +pub const D3D10_SVT_BLEND: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BLEND; +pub const D3D10_SVT_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BUFFER; +pub const D3D10_SVT_CBUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_CBUFFER; +pub const D3D10_SVT_TBUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TBUFFER; +pub const D3D10_SVT_TEXTURE1DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE1DARRAY; +pub const D3D10_SVT_TEXTURE2DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2DARRAY; +pub const D3D10_SVT_RENDERTARGETVIEW: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RENDERTARGETVIEW; +pub const D3D10_SVT_DEPTHSTENCILVIEW: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DEPTHSTENCILVIEW; +pub const D3D10_SVT_TEXTURE2DMS: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2DMS; +pub const D3D10_SVT_TEXTURE2DMSARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2DMSARRAY; +pub const D3D10_SVT_TEXTURECUBEARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURECUBEARRAY; +pub const D3D11_SVT_HULLSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_HULLSHADER; +pub const D3D11_SVT_DOMAINSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DOMAINSHADER; +pub const D3D11_SVT_INTERFACE_POINTER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_INTERFACE_POINTER; +pub const D3D11_SVT_COMPUTESHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_COMPUTESHADER; +pub const D3D11_SVT_DOUBLE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DOUBLE; +pub const D3D11_SVT_RWTEXTURE1D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE1D; +pub const D3D11_SVT_RWTEXTURE1DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE1DARRAY; +pub const D3D11_SVT_RWTEXTURE2D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE2D; +pub const D3D11_SVT_RWTEXTURE2DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE2DARRAY; +pub const D3D11_SVT_RWTEXTURE3D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE3D; +pub const D3D11_SVT_RWBUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWBUFFER; +pub const D3D11_SVT_BYTEADDRESS_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BYTEADDRESS_BUFFER; +pub const D3D11_SVT_RWBYTEADDRESS_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_RWBYTEADDRESS_BUFFER; +pub const D3D11_SVT_STRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_STRUCTURED_BUFFER; +pub const D3D11_SVT_RWSTRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_RWSTRUCTURED_BUFFER; +pub const D3D11_SVT_APPEND_STRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_APPEND_STRUCTURED_BUFFER; +pub const D3D11_SVT_CONSUME_STRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_CONSUME_STRUCTURED_BUFFER; +FLAGS!{enum D3D_SHADER_INPUT_FLAGS { + D3D_SIF_USERPACKED = 0x1, + D3D_SIF_COMPARISON_SAMPLER = 0x2, + D3D_SIF_TEXTURE_COMPONENT_0 = 0x4, + D3D_SIF_TEXTURE_COMPONENT_1 = 0x8, + D3D_SIF_TEXTURE_COMPONENTS = 0xc, + D3D_SIF_UNUSED = 0x10, +}} +pub const D3D10_SIF_USERPACKED: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_USERPACKED; +pub const D3D10_SIF_COMPARISON_SAMPLER: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_COMPARISON_SAMPLER; +pub const D3D10_SIF_TEXTURE_COMPONENT_0: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_TEXTURE_COMPONENT_0; +pub const D3D10_SIF_TEXTURE_COMPONENT_1: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_TEXTURE_COMPONENT_1; +pub const D3D10_SIF_TEXTURE_COMPONENTS: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_TEXTURE_COMPONENTS; +ENUM!{enum D3D_SHADER_INPUT_TYPE { + D3D_SIT_CBUFFER, + D3D_SIT_TBUFFER, + D3D_SIT_TEXTURE, + D3D_SIT_SAMPLER, + D3D_SIT_UAV_RWTYPED, + D3D_SIT_STRUCTURED, + D3D_SIT_UAV_RWSTRUCTURED, + D3D_SIT_BYTEADDRESS, + D3D_SIT_UAV_RWBYTEADDRESS, + D3D_SIT_UAV_APPEND_STRUCTURED, + D3D_SIT_UAV_CONSUME_STRUCTURED, + D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER, +}} +pub const D3D10_SIT_CBUFFER: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_CBUFFER; +pub const D3D10_SIT_TBUFFER: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_TBUFFER; +pub const D3D10_SIT_TEXTURE: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_TEXTURE; +pub const D3D10_SIT_SAMPLER: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_SAMPLER; +pub const D3D11_SIT_UAV_RWTYPED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_RWTYPED; +pub const D3D11_SIT_STRUCTURED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_STRUCTURED; +pub const D3D11_SIT_UAV_RWSTRUCTURED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_RWSTRUCTURED; +pub const D3D11_SIT_BYTEADDRESS: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_BYTEADDRESS; +pub const D3D11_SIT_UAV_RWBYTEADDRESS: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_RWBYTEADDRESS; +pub const D3D11_SIT_UAV_APPEND_STRUCTURED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_APPEND_STRUCTURED; +pub const D3D11_SIT_UAV_CONSUME_STRUCTURED: ::D3D_SHADER_INPUT_TYPE = + D3D_SIT_UAV_CONSUME_STRUCTURED; +pub const D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: ::D3D_SHADER_INPUT_TYPE = + D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER; +FLAGS!{enum D3D_SHADER_CBUFFER_FLAGS { + D3D_CBF_USERPACKED = 1, +}} +pub const D3D10_CBF_USERPACKED: ::D3D_SHADER_CBUFFER_FLAGS = D3D_CBF_USERPACKED; +ENUM!{enum D3D_CBUFFER_TYPE { + D3D_CT_CBUFFER, + D3D_CT_TBUFFER, + D3D_CT_INTERFACE_POINTERS, + D3D_CT_RESOURCE_BIND_INFO, +}} +pub const D3D10_CT_CBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_CBUFFER; +pub const D3D10_CT_TBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_TBUFFER; +pub const D3D11_CT_CBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_CBUFFER; +pub const D3D11_CT_TBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_TBUFFER; +pub const D3D11_CT_INTERFACE_POINTERS: ::D3D_CBUFFER_TYPE = D3D_CT_INTERFACE_POINTERS; +pub const D3D11_CT_RESOURCE_BIND_INFO: ::D3D_CBUFFER_TYPE = D3D_CT_RESOURCE_BIND_INFO; +ENUM!{enum D3D_NAME { + D3D_NAME_UNDEFINED = 0, + D3D_NAME_POSITION = 1, + D3D_NAME_CLIP_DISTANCE = 2, + D3D_NAME_CULL_DISTANCE = 3, + D3D_NAME_RENDER_TARGET_ARRAY_INDEX = 4, + D3D_NAME_VIEWPORT_ARRAY_INDEX = 5, + D3D_NAME_VERTEX_ID = 6, + D3D_NAME_PRIMITIVE_ID = 7, + D3D_NAME_INSTANCE_ID = 8, + D3D_NAME_IS_FRONT_FACE = 9, + D3D_NAME_SAMPLE_INDEX = 10, + D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR = 11, + D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR = 12, + D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR = 13, + D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR = 14, + D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR = 15, + D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR = 16, + D3D_NAME_TARGET = 64, + D3D_NAME_DEPTH = 65, + D3D_NAME_COVERAGE = 66, + D3D_NAME_DEPTH_GREATER_EQUAL = 67, + D3D_NAME_DEPTH_LESS_EQUAL = 68, +}} +pub const D3D10_NAME_UNDEFINED: D3D_NAME = D3D_NAME_UNDEFINED; +pub const D3D10_NAME_POSITION: D3D_NAME = D3D_NAME_POSITION; +pub const D3D10_NAME_CLIP_DISTANCE: D3D_NAME = D3D_NAME_CLIP_DISTANCE; +pub const D3D10_NAME_CULL_DISTANCE: D3D_NAME = D3D_NAME_CULL_DISTANCE; +pub const D3D10_NAME_RENDER_TARGET_ARRAY_INDEX: D3D_NAME = D3D_NAME_RENDER_TARGET_ARRAY_INDEX; +pub const D3D10_NAME_VIEWPORT_ARRAY_INDEX: D3D_NAME = D3D_NAME_VIEWPORT_ARRAY_INDEX; +pub const D3D10_NAME_VERTEX_ID: D3D_NAME = D3D_NAME_VERTEX_ID; +pub const D3D10_NAME_PRIMITIVE_ID: D3D_NAME = D3D_NAME_PRIMITIVE_ID; +pub const D3D10_NAME_INSTANCE_ID: D3D_NAME = D3D_NAME_INSTANCE_ID; +pub const D3D10_NAME_IS_FRONT_FACE: D3D_NAME = D3D_NAME_IS_FRONT_FACE; +pub const D3D10_NAME_SAMPLE_INDEX: D3D_NAME = D3D_NAME_SAMPLE_INDEX; +pub const D3D10_NAME_TARGET: D3D_NAME = D3D_NAME_TARGET; +pub const D3D10_NAME_DEPTH: D3D_NAME = D3D_NAME_DEPTH; +pub const D3D10_NAME_COVERAGE: D3D_NAME = D3D_NAME_COVERAGE; +pub const D3D11_NAME_FINAL_QUAD_EDGE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR; +pub const D3D11_NAME_FINAL_QUAD_INSIDE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR; +pub const D3D11_NAME_FINAL_TRI_EDGE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR; +pub const D3D11_NAME_FINAL_TRI_INSIDE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR; +pub const D3D11_NAME_FINAL_LINE_DETAIL_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR; +pub const D3D11_NAME_FINAL_LINE_DENSITY_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR; +pub const D3D11_NAME_DEPTH_GREATER_EQUAL: D3D_NAME = D3D_NAME_DEPTH_GREATER_EQUAL; +pub const D3D11_NAME_DEPTH_LESS_EQUAL: D3D_NAME = D3D_NAME_DEPTH_LESS_EQUAL; +ENUM!{enum D3D_RESOURCE_RETURN_TYPE { + D3D_RETURN_TYPE_UNORM = 1, + D3D_RETURN_TYPE_SNORM = 2, + D3D_RETURN_TYPE_SINT = 3, + D3D_RETURN_TYPE_UINT = 4, + D3D_RETURN_TYPE_FLOAT = 5, + D3D_RETURN_TYPE_MIXED = 6, + D3D_RETURN_TYPE_DOUBLE = 7, + D3D_RETURN_TYPE_CONTINUED = 8, +}} +pub const D3D10_RETURN_TYPE_UNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UNORM; +pub const D3D10_RETURN_TYPE_SNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SNORM; +pub const D3D10_RETURN_TYPE_SINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SINT; +pub const D3D10_RETURN_TYPE_UINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UINT; +pub const D3D10_RETURN_TYPE_FLOAT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_FLOAT; +pub const D3D10_RETURN_TYPE_MIXED: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_MIXED; +pub const D3D11_RETURN_TYPE_UNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UNORM; +pub const D3D11_RETURN_TYPE_SNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SNORM; +pub const D3D11_RETURN_TYPE_SINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SINT; +pub const D3D11_RETURN_TYPE_UINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UINT; +pub const D3D11_RETURN_TYPE_FLOAT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_FLOAT; +pub const D3D11_RETURN_TYPE_MIXED: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_MIXED; +pub const D3D11_RETURN_TYPE_DOUBLE: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_DOUBLE; +pub const D3D11_RETURN_TYPE_CONTINUED: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_CONTINUED; +ENUM!{enum D3D_REGISTER_COMPONENT_TYPE { + D3D_REGISTER_COMPONENT_UNKNOWN = 0, + D3D_REGISTER_COMPONENT_UINT32 = 1, + D3D_REGISTER_COMPONENT_SINT32 = 2, + D3D_REGISTER_COMPONENT_FLOAT32 = 3, +}} +pub const D3D10_REGISTER_COMPONENT_UNKNOWN: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_UNKNOWN; +pub const D3D10_REGISTER_COMPONENT_UINT32: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_UINT32; +pub const D3D10_REGISTER_COMPONENT_SINT32: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_SINT32; +pub const D3D10_REGISTER_COMPONENT_FLOAT32: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_FLOAT32; +ENUM!{enum D3D_TESSELLATOR_DOMAIN { + D3D_TESSELLATOR_DOMAIN_UNDEFINED, + D3D_TESSELLATOR_DOMAIN_ISOLINE, + D3D_TESSELLATOR_DOMAIN_TRI, + D3D_TESSELLATOR_DOMAIN_QUAD, +}} +pub const D3D11_TESSELLATOR_DOMAIN_UNDEFINED: ::D3D_TESSELLATOR_DOMAIN = + D3D_TESSELLATOR_DOMAIN_UNDEFINED; +pub const D3D11_TESSELLATOR_DOMAIN_ISOLINE: ::D3D_TESSELLATOR_DOMAIN = + D3D_TESSELLATOR_DOMAIN_ISOLINE; +pub const D3D11_TESSELLATOR_DOMAIN_TRI: ::D3D_TESSELLATOR_DOMAIN = D3D_TESSELLATOR_DOMAIN_TRI; +pub const D3D11_TESSELLATOR_DOMAIN_QUAD: ::D3D_TESSELLATOR_DOMAIN = D3D_TESSELLATOR_DOMAIN_QUAD; +ENUM!{enum D3D_TESSELLATOR_PARTITIONING { + D3D_TESSELLATOR_PARTITIONING_UNDEFINED, + D3D_TESSELLATOR_PARTITIONING_INTEGER, + D3D_TESSELLATOR_PARTITIONING_POW2, + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD, + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN, +}} +pub const D3D11_TESSELLATOR_PARTITIONING_UNDEFINED: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_UNDEFINED; +pub const D3D11_TESSELLATOR_PARTITIONING_INTEGER: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_INTEGER; +pub const D3D11_TESSELLATOR_PARTITIONING_POW2: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_POW2; +pub const D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD; +pub const D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN; +ENUM!{enum D3D_TESSELLATOR_OUTPUT_PRIMITIVE { + D3D_TESSELLATOR_OUTPUT_UNDEFINED, + D3D_TESSELLATOR_OUTPUT_POINT, + D3D_TESSELLATOR_OUTPUT_LINE, + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW, + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW, +}} +pub const D3D11_TESSELLATOR_OUTPUT_UNDEFINED: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_UNDEFINED; +pub const D3D11_TESSELLATOR_OUTPUT_POINT: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_POINT; +pub const D3D11_TESSELLATOR_OUTPUT_LINE: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_LINE; +pub const D3D11_TESSELLATOR_OUTPUT_TRIANGLE_CW: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW; +pub const D3D11_TESSELLATOR_OUTPUT_TRIANGLE_CCW: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW; +ENUM!{enum D3D_MIN_PRECISION { + D3D_MIN_PRECISION_DEFAULT, + D3D_MIN_PRECISION_FLOAT_16, + D3D_MIN_PRECISION_FLOAT_2_8, + D3D_MIN_PRECISION_RESERVED, + D3D_MIN_PRECISION_SINT_16, + D3D_MIN_PRECISION_UINT_16, + D3D_MIN_PRECISION_ANY_16 = 0xf0, + D3D_MIN_PRECISION_ANY_10 = 0xf1, +}} +ENUM!{enum D3D_INTERPOLATION_MODE { + D3D_INTERPOLATION_UNDEFINED, + D3D_INTERPOLATION_CONSTANT, + D3D_INTERPOLATION_LINEAR, + D3D_INTERPOLATION_LINEAR_CENTROID, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE_CENTROID, + D3D_INTERPOLATION_LINEAR_SAMPLE, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE_SAMPLE, +}} +FLAGS!{enum D3D_PARAMETER_FLAGS { + D3D_PF_NONE = 0, + D3D_PF_IN = 0x1, + D3D_PF_OUT = 0x2, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/d3dcompiler.rs b/bash-5.1/vendor/winapi-0.2.8/src/d3dcompiler.rs new file mode 100644 index 0000000..6918888 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/d3dcompiler.rs @@ -0,0 +1,74 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub const D3DCOMPILER_DLL: &'static str = "d3dcompiler_47.dll"; +pub const D3D_COMPILER_VERSION: DWORD = 47; +pub const D3DCOMPILE_DEBUG: DWORD = 1 << 0; +pub const D3DCOMPILE_SKIP_VALIDATION: DWORD = 1 << 1; +pub const D3DCOMPILE_SKIP_OPTIMIZATION: DWORD = 1 << 2; +pub const D3DCOMPILE_PACK_MATRIX_ROW_MAJOR: DWORD = 1 << 3; +pub const D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR: DWORD = 1 << 4; +pub const D3DCOMPILE_PARTIAL_PRECISION: DWORD = 1 << 5; +pub const D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT: DWORD = 1 << 6; +pub const D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT: DWORD = 1 << 7; +pub const D3DCOMPILE_NO_PRESHADER: DWORD = 1 << 8; +pub const D3DCOMPILE_AVOID_FLOW_CONTROL: DWORD = 1 << 9; +pub const D3DCOMPILE_PREFER_FLOW_CONTROL: DWORD = 1 << 10; +pub const D3DCOMPILE_ENABLE_STRICTNESS: DWORD = 1 << 11; +pub const D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY: DWORD = 1 << 12; +pub const D3DCOMPILE_IEEE_STRICTNESS: DWORD = 1 << 13; +pub const D3DCOMPILE_OPTIMIZATION_LEVEL0: DWORD = 1 << 14; +pub const D3DCOMPILE_OPTIMIZATION_LEVEL1: DWORD = 0; +pub const D3DCOMPILE_OPTIMIZATION_LEVEL2: DWORD = (1 << 14) | (1 << 15); +pub const D3DCOMPILE_OPTIMIZATION_LEVEL3: DWORD = 1 << 15; +pub const D3DCOMPILE_RESERVED16: DWORD = 1 << 16; +pub const D3DCOMPILE_RESERVED17: DWORD = 1 << 17; +pub const D3DCOMPILE_WARNINGS_ARE_ERRORS: DWORD = 1 << 18; +pub const D3DCOMPILE_RESOURCES_MAY_ALIAS: DWORD = 1 << 19; +pub const D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES: DWORD = 1 << 20; +pub const D3DCOMPILE_ALL_RESOURCES_BOUND: DWORD = 1 << 21; +pub const D3DCOMPILE_EFFECT_CHILD_EFFECT: DWORD = 1 << 0; +pub const D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS: DWORD = 1 << 1; +pub const D3D_COMPILE_STANDARD_FILE_INCLUDE: *mut ID3DInclude = 1 as *mut ID3DInclude; +pub const D3DCOMPILE_SECDATA_MERGE_UAV_SLOTS: DWORD = 0x00000001; +pub const D3DCOMPILE_SECDATA_PRESERVE_TEMPLATE_SLOTS: DWORD = 0x00000002; +pub const D3DCOMPILE_SECDATA_REQUIRE_TEMPLATE_MATCH: DWORD = 0x00000004; +pub const D3D_DISASM_ENABLE_COLOR_CODE: DWORD = 0x00000001; +pub const D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS: DWORD = 0x00000002; +pub const D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING: DWORD = 0x00000004; +pub const D3D_DISASM_ENABLE_INSTRUCTION_CYCLE: DWORD = 0x00000008; +pub const D3D_DISASM_DISABLE_DEBUG_INFO: DWORD = 0x00000010; +pub const D3D_DISASM_ENABLE_INSTRUCTION_OFFSET: DWORD = 0x00000020; +pub const D3D_DISASM_INSTRUCTION_ONLY: DWORD = 0x00000040; +pub const D3D_DISASM_PRINT_HEX_LITERALS: DWORD = 0x00000080; +pub const D3D_GET_INST_OFFSETS_INCLUDE_NON_EXECUTABLE: DWORD = 0x00000001; +FLAGS!{enum D3DCOMPILER_STRIP_FLAGS { + D3DCOMPILER_STRIP_REFLECTION_DATA = 0x00000001, + D3DCOMPILER_STRIP_DEBUG_INFO = 0x00000002, + D3DCOMPILER_STRIP_TEST_BLOBS = 0x00000004, + D3DCOMPILER_STRIP_PRIVATE_DATA = 0x00000008, + D3DCOMPILER_STRIP_ROOT_SIGNATURE = 0x00000010, + D3DCOMPILER_STRIP_FORCE_DWORD = 0x7fffffff, +}} +ENUM!{enum D3D_BLOB_PART { + D3D_BLOB_INPUT_SIGNATURE_BLOB, + D3D_BLOB_OUTPUT_SIGNATURE_BLOB, + D3D_BLOB_INPUT_AND_OUTPUT_SIGNATURE_BLOB, + D3D_BLOB_PATCH_CONSTANT_SIGNATURE_BLOB, + D3D_BLOB_ALL_SIGNATURE_BLOB, + D3D_BLOB_DEBUG_INFO, + D3D_BLOB_LEGACY_SHADER, + D3D_BLOB_XNA_PREPASS_SHADER, + D3D_BLOB_XNA_SHADER, + D3D_BLOB_PDB, + D3D_BLOB_PRIVATE_DATA, + D3D_BLOB_ROOT_SIGNATURE, + D3D_BLOB_TEST_ALTERNATE_SHADER = 0x8000, + D3D_BLOB_TEST_COMPILE_DETAILS, + D3D_BLOB_TEST_COMPILE_PERF, + D3D_BLOB_TEST_COMPILE_REPORT, +}} +STRUCT!{struct D3D_SHADER_DATA { + pBytecode: LPCVOID, + BytecodeLength: SIZE_T, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dbghelp.rs b/bash-5.1/vendor/winapi-0.2.8/src/dbghelp.rs new file mode 100644 index 0000000..8c20d72 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dbghelp.rs @@ -0,0 +1,340 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! DbgHelp include file +#[cfg(target_arch = "x86_64")] +STRUCT!{struct LOADED_IMAGE { + ModuleName: ::PSTR, + hFile: ::HANDLE, + MappedAddress: ::PUCHAR, + FileHeader: ::PIMAGE_NT_HEADERS64, + LastRvaSection: ::PIMAGE_SECTION_HEADER, + NumberOfSections: ::ULONG, + Sections: ::PIMAGE_SECTION_HEADER, + Characteristics: ::ULONG, + fSystemImage: ::BOOLEAN, + fDOSImage: ::BOOLEAN, + fReadOnly: ::BOOLEAN, + Version: ::UCHAR, + Links: ::LIST_ENTRY, + SizeOfImage: ::ULONG, +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct LOADED_IMAGE { + ModuleName: ::PSTR, + hFile: ::HANDLE, + MappedAddress: ::PUCHAR, + FileHeader: ::PIMAGE_NT_HEADERS32, + LastRvaSection: ::PIMAGE_SECTION_HEADER, + NumberOfSections: ::ULONG, + Sections: ::PIMAGE_SECTION_HEADER, + Characteristics: ::ULONG, + fSystemImage: ::BOOLEAN, + fDOSImage: ::BOOLEAN, + fReadOnly: ::BOOLEAN, + Version: ::UCHAR, + Links: ::LIST_ENTRY, + SizeOfImage: ::ULONG, +}} +pub const MAX_SYM_NAME: usize = 2000; +pub const ERROR_IMAGE_NOT_STRIPPED: ::DWORD = 0x8800; +pub const ERROR_NO_DBG_POINTER: ::DWORD = 0x8801; +pub const ERROR_NO_PDB_POINTER: ::DWORD = 0x8802; +pub type PFIND_DEBUG_FILE_CALLBACK = Option<unsafe extern "system" fn( + FileHandle: ::HANDLE, FileName: ::PCSTR, CallerData: ::PVOID, +) -> ::BOOL>; +pub type PFIND_DEBUG_FILE_CALLBACKW = Option<unsafe extern "system" fn( + FileHandle: ::HANDLE, FileName: ::PCWSTR, CallerData: ::PVOID, +) -> ::BOOL>; +pub type PFINDFILEINPATHCALLBACK = Option<unsafe extern "system" fn( + filename: ::PCSTR, context: ::PVOID, +) -> ::BOOL>; +pub type PFINDFILEINPATHCALLBACKW = Option<unsafe extern "system" fn( + filename: ::PCWSTR, context: ::PVOID, +) -> ::BOOL>; +pub type PFIND_EXE_FILE_CALLBACK = Option<unsafe extern "system" fn( + FileHandle: ::HANDLE, FileName: ::PCSTR, CallerData: ::PVOID, +) -> ::BOOL>; +pub type PFIND_EXE_FILE_CALLBACKW = Option<unsafe extern "system" fn( + FileHandle: ::HANDLE, FileName: ::PCWSTR, CallerData: ::PVOID, +) -> ::BOOL>; +#[cfg(target_arch = "x86")] +STRUCT!{struct IMAGE_DEBUG_INFORMATION { + List: ::LIST_ENTRY, + ReservedSize: ::DWORD, + ReservedMappedBase: ::PVOID, + ReservedMachine: ::USHORT, + ReservedCharacteristics: ::USHORT, + ReservedCheckSum: ::DWORD, + ImageBase: ::DWORD, + SizeOfImage: ::DWORD, + ReservedNumberOfSections: ::DWORD, + ReservedSections: ::PIMAGE_SECTION_HEADER, + ReservedExportedNamesSize: ::DWORD, + ReservedExportedNames: ::PSTR, + ReservedNumberOfFunctionTableEntries: ::DWORD, + ReservedFunctionTableEntries: ::PIMAGE_FUNCTION_ENTRY, + ReservedLowestFunctionStartingAddress: ::DWORD, + ReservedHighestFunctionEndingAddress: ::DWORD, + ReservedNumberOfFpoTableEntries: ::DWORD, + ReservedFpoTableEntries: ::PFPO_DATA, + SizeOfCoffSymbols: ::DWORD, + CoffSymbols: ::PIMAGE_COFF_SYMBOLS_HEADER, + ReservedSizeOfCodeViewSymbols: ::DWORD, + ReservedCodeViewSymbols: ::PVOID, + ImageFilePath: ::PSTR, + ImageFileName: ::PSTR, + ReservedDebugFilePath: ::PSTR, + ReservedTimeDateStamp: ::DWORD, + ReservedRomImage: ::BOOL, + ReservedDebugDirectory: ::PIMAGE_DEBUG_DIRECTORY, + ReservedNumberOfDebugDirectories: ::DWORD, + ReservedOriginalFunctionTableBaseAddress: ::DWORD, + Reserved: [::DWORD; 2], +}} +#[cfg(target_arch = "x86")] +pub type PIMAGE_DEBUG_INFORMATION = *mut IMAGE_DEBUG_INFORMATION; +pub type PENUMDIRTREE_CALLBACK = Option<unsafe extern "system" fn( + FilePath: ::PCSTR, CallerData: ::PVOID, +) -> ::BOOL>; +pub type PENUMDIRTREE_CALLBACKW = Option<unsafe extern "system" fn( + FilePath: ::PCWSTR, CallerData: ::PVOID, +) -> ::BOOL>; +pub const UNDNAME_COMPLETE: ::DWORD = 0x0000; +pub const UNDNAME_NO_LEADING_UNDERSCORES: ::DWORD = 0x0001; +pub const UNDNAME_NO_MS_KEYWORDS: ::DWORD = 0x0002; +pub const UNDNAME_NO_FUNCTION_RETURNS: ::DWORD = 0x0004; +pub const UNDNAME_NO_ALLOCATION_MODEL: ::DWORD = 0x0008; +pub const UNDNAME_NO_ALLOCATION_LANGUAGE: ::DWORD = 0x0010; +pub const UNDNAME_NO_MS_THISTYPE: ::DWORD = 0x0020; +pub const UNDNAME_NO_CV_THISTYPE: ::DWORD = 0x0040; +pub const UNDNAME_NO_THISTYPE: ::DWORD = 0x0060; +pub const UNDNAME_NO_ACCESS_SPECIFIERS: ::DWORD = 0x0080; +pub const UNDNAME_NO_THROW_SIGNATURES: ::DWORD = 0x0100; +pub const UNDNAME_NO_MEMBER_TYPE: ::DWORD = 0x0200; +pub const UNDNAME_NO_RETURN_UDT_MODEL: ::DWORD = 0x0400; +pub const UNDNAME_32_BIT_DECODE: ::DWORD = 0x0800; +pub const UNDNAME_NAME_ONLY: ::DWORD = 0x1000; +pub const UNDNAME_NO_ARGUMENTS: ::DWORD = 0x2000; +pub const UNDNAME_NO_SPECIAL_SYMS: ::DWORD = 0x4000; +pub const DBHHEADER_DEBUGDIRS: ::DWORD = 0x1; +pub const DBHHEADER_CVMISC: ::DWORD = 0x2; +pub const DBHHEADER_PDBGUID: ::DWORD = 0x3; +STRUCT!{struct MODLOAD_DATA { + ssize: ::DWORD, + ssig: ::DWORD, + data: ::PVOID, + size: ::DWORD, + flags: ::DWORD, +}} +pub type PMODLOAD_DATA = *mut MODLOAD_DATA; +STRUCT!{struct MODLOAD_CVMISC { + oCV: ::DWORD, + cCV: ::size_t, + oMisc: ::DWORD, + cMisc: ::size_t, + dtImage: ::DWORD, + cImage: ::DWORD, +}} +pub type PMODLOAD_CVMISC = *mut MODLOAD_CVMISC; +STRUCT!{struct MODLOAD_PDBGUID_PDBAGE { + PdbGuid: ::GUID, + PdbAge: ::DWORD, +}} +pub type PMODLOAD_PDBGUID_PDBAGE = *mut MODLOAD_PDBGUID_PDBAGE; +ENUM!{enum ADDRESS_MODE { + AddrMode1616, + AddrMode1632, + AddrModeReal, + AddrModeFlat, +}} +STRUCT!{struct ADDRESS64 { + Offset: ::DWORD64, + Segment: ::WORD, + Mode: ::ADDRESS_MODE, +}} +pub type LPADDRESS64 = *mut ADDRESS64; +#[cfg(target_arch = "x86_64")] +pub type ADDRESS = ADDRESS64; +#[cfg(target_arch = "x86_64")] +pub type LPADDRESS = LPADDRESS64; +#[cfg(target_arch = "x86")] +STRUCT!{struct ADDRESS { + Offset: ::DWORD, + Segment: ::WORD, + Mode: ::ADDRESS_MODE, +}} +#[cfg(target_arch = "x86")] +pub type LPADDRESS = *mut ADDRESS; +STRUCT!{struct KDHELP64 { + Thread: ::DWORD64, + ThCallbackStack: ::DWORD, + ThCallbackBStore: ::DWORD, + NextCallback: ::DWORD, + FramePointer: ::DWORD, + KiCallUserMode: ::DWORD64, + KeUserCallbackDispatcher: ::DWORD64, + SystemRangeStart: ::DWORD64, + KiUserExceptionDispatcher: ::DWORD64, + StackBase: ::DWORD64, + StackLimit: ::DWORD64, + BuildVersion: ::DWORD, + Reserved0: ::DWORD, + Reserved1: [::DWORD64; 4], +}} +pub type PKDHELP64 = *mut KDHELP64; +#[cfg(target_arch = "x86_64")] +pub type KDHELP = KDHELP64; +#[cfg(target_arch = "x86_64")] +pub type PKDHELP = PKDHELP64; +#[cfg(target_arch = "x86")] +STRUCT!{struct KDHELP { + Thread: ::DWORD, + ThCallbackStack: ::DWORD, + NextCallback: ::DWORD, + FramePointer: ::DWORD, + KiCallUserMode: ::DWORD, + KeUserCallbackDispatcher: ::DWORD, + SystemRangeStart: ::DWORD, + ThCallbackBStore: ::DWORD, + KiUserExceptionDispatcher: ::DWORD, + StackBase: ::DWORD, + StackLimit: ::DWORD, + Reserved: [::DWORD; 5], +}} +#[cfg(target_arch = "x86")] +pub type PKDHELP = *mut KDHELP; +STRUCT!{struct STACKFRAME64 { + AddrPC: ::ADDRESS64, + AddrReturn: ::ADDRESS64, + AddrFrame: ::ADDRESS64, + AddrStack: ::ADDRESS64, + AddrBStore: ::ADDRESS64, + FuncTableEntry: ::PVOID, + Params: [::DWORD64; 4], + Far: ::BOOL, + Virtual: ::BOOL, + Reserved: [::DWORD64; 3], + KdHelp: ::KDHELP64, +}} +pub type LPSTACKFRAME64 = *mut STACKFRAME64; +pub const INLINE_FRAME_CONTEXT_INIT: ::DWORD = 0; +pub const INLINE_FRAME_CONTEXT_IGNORE: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct STACKFRAME_EX { + AddrPC: ::ADDRESS64, + AddrReturn: ::ADDRESS64, + AddrFrame: ::ADDRESS64, + AddrStack: ::ADDRESS64, + AddrBStore: ::ADDRESS64, + FuncTableEntry: ::PVOID, + Params: [::DWORD64; 4], + Far: ::BOOL, + Virtual: ::BOOL, + Reserved: [::DWORD64; 3], + KdHelp: ::KDHELP64, + StackFrameSize: ::DWORD, + InlineFrameContext: ::DWORD, +}} +pub type LPSTACKFRAME_EX = *mut STACKFRAME_EX; +#[cfg(target_arch = "x86_64")] +pub type STACKFRAME = STACKFRAME64; +#[cfg(target_arch = "x86_64")] +pub type LPSTACKFRAME = LPSTACKFRAME64; +#[cfg(target_arch = "x86")] +STRUCT!{struct STACKFRAME { + AddrPC: ::ADDRESS, + AddrReturn: ::ADDRESS, + AddrFrame: ::ADDRESS, + AddrStack: ::ADDRESS, + FuncTableEntry: ::PVOID, + Params: [::DWORD; 4], + Far: ::BOOL, + Virtual: ::BOOL, + Reserved: [::DWORD; 3], + KdHelp: ::KDHELP, + AddrBStore: ::ADDRESS, +}} +#[cfg(target_arch = "x86")] +pub type LPSTACKFRAME = *mut STACKFRAME; +pub type PREAD_PROCESS_MEMORY_ROUTINE64 = Option<unsafe extern "system" fn( + hProcess: ::HANDLE, qwBaseAddress: ::DWORD64, lpBuffer: ::PVOID, nSize: ::DWORD, + lpNumberOfBytesRead: ::LPDWORD, +) -> ::BOOL>; +pub type PFUNCTION_TABLE_ACCESS_ROUTINE64 = Option<unsafe extern "system" fn( + ahProcess: ::HANDLE, AddrBase: ::DWORD64, +) -> ::PVOID>; +pub type PGET_MODULE_BASE_ROUTINE64 = Option<unsafe extern "system" fn( + hProcess: ::HANDLE, Address: ::DWORD64, +) -> ::DWORD64>; +pub type PTRANSLATE_ADDRESS_ROUTINE64 = Option<unsafe extern "system" fn( + hProcess: ::HANDLE, hThread: ::HANDLE, lpaddr: LPADDRESS64, +) -> ::DWORD64>; +pub const SYM_STKWALK_DEFAULT: ::DWORD = 0x00000000; +pub const SYM_STKWALK_FORCE_FRAMEPTR: ::DWORD = 0x00000001; +#[cfg(target_arch = "x86_64")] +pub type PREAD_PROCESS_MEMORY_ROUTINE = PREAD_PROCESS_MEMORY_ROUTINE64; +#[cfg(target_arch = "x86_64")] +pub type PFUNCTION_TABLE_ACCESS_ROUTINE = PFUNCTION_TABLE_ACCESS_ROUTINE64; +#[cfg(target_arch = "x86_64")] +pub type PGET_MODULE_BASE_ROUTINE = PGET_MODULE_BASE_ROUTINE64; +#[cfg(target_arch = "x86_64")] +pub type PTRANSLATE_ADDRESS_ROUTINE = PTRANSLATE_ADDRESS_ROUTINE64; +#[cfg(target_arch = "x86")] +pub type PREAD_PROCESS_MEMORY_ROUTINE = Option<unsafe extern "system" fn( + hProcess: ::HANDLE, qwBaseAddress: ::DWORD, lpBuffer: ::PVOID, nSize: ::DWORD, + lpNumberOfBytesRead: ::PDWORD, +) -> ::BOOL>; +#[cfg(target_arch = "x86")] +pub type PFUNCTION_TABLE_ACCESS_ROUTINE = Option<unsafe extern "system" fn( + ahProcess: ::HANDLE, AddrBase: ::DWORD, +) -> ::PVOID>; +#[cfg(target_arch = "x86")] +pub type PGET_MODULE_BASE_ROUTINE = Option<unsafe extern "system" fn( + hProcess: ::HANDLE, Address: ::DWORD, +) -> ::DWORD>; +#[cfg(target_arch = "x86")] +pub type PTRANSLATE_ADDRESS_ROUTINE = Option<unsafe extern "system" fn( + hProcess: ::HANDLE, hThread: ::HANDLE, lpaddr: LPADDRESS, +) -> ::DWORD>; +pub const API_VERSION_NUMBER: ::USHORT = 12; +STRUCT!{struct API_VERSION { + MajorVersion: ::USHORT, + MinorVersion: ::USHORT, + Revision: ::USHORT, + Reserved: ::USHORT, +}} +pub type LPAPI_VERSION = *mut API_VERSION; +STRUCT!{struct SYMBOL_INFOW { + SizeOfStruct: ::ULONG, + TypeIndex: ::ULONG, + Reserved: [::ULONG64; 2], + Index: ::ULONG, + Size: ::ULONG, + ModBase: ::ULONG64, + Flags: ::ULONG, + Value: ::ULONG64, + Address: ::ULONG64, + Register: ::ULONG, + Scope: ::ULONG, + Tag: ::ULONG, + NameLen: ::ULONG, + MaxNameLen: ::ULONG, + Name: [::WCHAR; 1], +}} +pub type PSYMBOL_INFOW = *mut SYMBOL_INFOW; +STRUCT!{struct IMAGEHLP_SYMBOL64 { + SizeOfStruct: ::DWORD, + Address: ::DWORD64, + Size: ::DWORD, + Flags: ::DWORD, + MaxNameLength: ::DWORD, + Name: [::CHAR; 1], +}} +pub type PIMAGEHLP_SYMBOL64 = *mut IMAGEHLP_SYMBOL64; +STRUCT!{struct IMAGEHLP_LINEW64 { + SizeOfStruct: ::DWORD, + Key: ::PVOID, + LineNumber: ::DWORD, + FileName: ::PWSTR, + Address: ::DWORD64, +}} +pub type PIMAGEHLP_LINEW64 = *mut IMAGEHLP_LINEW64; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dcommon.rs b/bash-5.1/vendor/winapi-0.2.8/src/dcommon.rs new file mode 100644 index 0000000..2c220e3 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dcommon.rs @@ -0,0 +1,18 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dcommon.h +ENUM!{enum DWRITE_MEASURING_MODE { + DWRITE_MEASURING_MODE_NATURAL = 0, + DWRITE_MEASURING_MODE_GDI_CLASSIC = 1, + DWRITE_MEASURING_MODE_GDI_NATURAL = 2, +}} +ENUM!{enum D2D1_ALPHA_MODE { + D2D1_ALPHA_MODE_UNKNOWN = 0, + D2D1_ALPHA_MODE_PREMULTIPLIED = 1, + D2D1_ALPHA_MODE_STRAIGHT = 2, + D2D1_ALPHA_MODE_IGNORE = 3, +}} +STRUCT!{struct D2D1_PIXEL_FORMAT { + format: ::DXGI_FORMAT, + alphaMode: D2D1_ALPHA_MODE, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/devpropdef.rs b/bash-5.1/vendor/winapi-0.2.8/src/devpropdef.rs new file mode 100644 index 0000000..3deca43 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/devpropdef.rs @@ -0,0 +1,71 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Defines property types and keys for the Plug and Play Device Property API +pub type DEVPROPTYPE = ::ULONG; +pub type PDEVPROPTYPE = *mut ::ULONG; +pub const DEVPROP_TYPEMOD_ARRAY: DEVPROPTYPE = 0x00001000; +pub const DEVPROP_TYPEMOD_LIST: DEVPROPTYPE = 0x00002000; +pub const DEVPROP_TYPE_EMPTY: DEVPROPTYPE = 0x00000000; +pub const DEVPROP_TYPE_NULL: DEVPROPTYPE = 0x00000001; +pub const DEVPROP_TYPE_SBYTE: DEVPROPTYPE = 0x00000002; +pub const DEVPROP_TYPE_BYTE: DEVPROPTYPE = 0x00000003; +pub const DEVPROP_TYPE_INT16: DEVPROPTYPE = 0x00000004; +pub const DEVPROP_TYPE_UINT16: DEVPROPTYPE = 0x00000005; +pub const DEVPROP_TYPE_INT32: DEVPROPTYPE = 0x00000006; +pub const DEVPROP_TYPE_UINT32: DEVPROPTYPE = 0x00000007; +pub const DEVPROP_TYPE_INT64: DEVPROPTYPE = 0x00000008; +pub const DEVPROP_TYPE_UINT64: DEVPROPTYPE = 0x00000009; +pub const DEVPROP_TYPE_FLOAT: DEVPROPTYPE = 0x0000000A; +pub const DEVPROP_TYPE_DOUBLE: DEVPROPTYPE = 0x0000000B; +pub const DEVPROP_TYPE_DECIMAL: DEVPROPTYPE = 0x0000000C; +pub const DEVPROP_TYPE_GUID: DEVPROPTYPE = 0x0000000D; +pub const DEVPROP_TYPE_CURRENCY: DEVPROPTYPE = 0x0000000E; +pub const DEVPROP_TYPE_DATE: DEVPROPTYPE = 0x0000000F; +pub const DEVPROP_TYPE_FILETIME: DEVPROPTYPE = 0x00000010; +pub const DEVPROP_TYPE_BOOLEAN: DEVPROPTYPE = 0x00000011; +pub const DEVPROP_TYPE_STRING: DEVPROPTYPE = 0x00000012; +pub const DEVPROP_TYPE_STRING_LIST: DEVPROPTYPE = DEVPROP_TYPE_STRING | DEVPROP_TYPEMOD_LIST; +pub const DEVPROP_TYPE_SECURITY_DESCRIPTOR: DEVPROPTYPE = 0x00000013; +pub const DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING: DEVPROPTYPE = 0x00000014; +pub const DEVPROP_TYPE_DEVPROPKEY: DEVPROPTYPE = 0x00000015; +pub const DEVPROP_TYPE_DEVPROPTYPE: DEVPROPTYPE = 0x00000016; +pub const DEVPROP_TYPE_BINARY: DEVPROPTYPE = DEVPROP_TYPE_BYTE | DEVPROP_TYPEMOD_ARRAY; +pub const DEVPROP_TYPE_ERROR: DEVPROPTYPE = 0x00000017; +pub const DEVPROP_TYPE_NTSTATUS: DEVPROPTYPE = 0x00000018; +pub const DEVPROP_TYPE_STRING_INDIRECT: DEVPROPTYPE = 0x00000019; +pub const MAX_DEVPROP_TYPE: DEVPROPTYPE = 0x00000019; +pub const MAX_DEVPROP_TYPEMOD: DEVPROPTYPE = 0x00002000; +pub const DEVPROP_MASK_TYPE: DEVPROPTYPE = 0x00000FFF; +pub const DEVPROP_MASK_TYPEMOD: DEVPROPTYPE = 0x0000F000; +pub type DEVPROP_BOOLEAN = ::CHAR; +pub type PDEVPROP_BOOLEAN = *mut ::CHAR; +pub const DEVPROP_TRUE: DEVPROP_BOOLEAN = -1; +pub const DEVPROP_FALSE: DEVPROP_BOOLEAN = 0; +pub type DEVPROPGUID = ::GUID; +pub type PDEVPROPGUID = *mut ::GUID; +pub type DEVPROPID = ::ULONG; +pub type PDEVPROPID = *mut ::ULONG; +STRUCT!{struct DEVPROPKEY { + fmtid: DEVPROPGUID, + pid: DEVPROPID, +}} +pub type PDEVPROPKEY = *mut DEVPROPKEY; +ENUM!{enum DEVPROPSTORE { + DEVPROP_STORE_SYSTEM, + DEVPROP_STORE_USER, +}} +pub type PDEVPROPSTORE = *mut DEVPROPSTORE; +STRUCT!{struct DEVPROPCOMPKEY { + Key: DEVPROPKEY, + Store: DEVPROPSTORE, + LocaleName: ::PCWSTR, +}} +pub type PDEVPROPCOMPKEY = *mut DEVPROPCOMPKEY; +STRUCT!{struct DEVPROPERTY { + CompKey: DEVPROPCOMPKEY, + Type: DEVPROPTYPE, + BufferSize: ::ULONG, + Buffer: ::PVOID, +}} +pub type PDEVPROPERTY = *mut DEVPROPERTY; +pub const DEVPROPID_FIRST_USABLE: DEVPROPID = 2; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/docobj.rs b/bash-5.1/vendor/winapi-0.2.8/src/docobj.rs new file mode 100644 index 0000000..3d5f904 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/docobj.rs @@ -0,0 +1,22 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +STRUCT!{struct OLECMD { + cmdID: ::ULONG, + cmdf: ::DWORD, +}} +STRUCT!{struct OLECMDTEXT { + cmdtextf: ::DWORD, + cwActual: ::ULONG, + cwBuf: ::ULONG, + rgwz: [::wchar_t; 0], +}} +RIDL!{interface IOleCommandTarget(IOleCommandTargetVtbl): IUnknown(IUnknownVtbl) { + fn QueryStatus( + &mut self, pguidCmdGroup: *const ::GUID, cCmds: ::ULONG, prgCmds: *mut OLECMD, + pCmdText: *mut OLECMDTEXT + ) -> ::HRESULT, + fn Exec( + &mut self, pguidCmdGroup: *const :: GUID, nCmdID: ::DWORD, nCmdexecopt: ::DWORD, + pvaIn: *mut ::VARIANT, pvaOut: *mut ::VARIANT + ) -> ::HRESULT +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dpapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/dpapi.rs new file mode 100644 index 0000000..c62e56f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dpapi.rs @@ -0,0 +1,11 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Data Protection API Prototypes and Definitions +pub const szFORCE_KEY_PROTECTION: &'static str = "ForceKeyProtection"; +STRUCT!{struct CRYPTPROTECT_PROMPTSTRUCT { + cbSize: ::DWORD, + dwPromptFlags: ::DWORD, + hwndApp: ::HWND, + szPrompt: ::LPCWSTR, +}} +pub type PCRYPTPROTECT_PROMPTSTRUCT = *mut CRYPTPROTECT_PROMPTSTRUCT; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dsgetdc.rs b/bash-5.1/vendor/winapi-0.2.8/src/dsgetdc.rs new file mode 100644 index 0000000..09c81c0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dsgetdc.rs @@ -0,0 +1,113 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! This file contains structures, function prototypes, and definitions for the DsGetDcName API. +pub const DS_FORCE_REDISCOVERY: ::ULONG = 0x00000001; +pub const DS_DIRECTORY_SERVICE_REQUIRED: ::ULONG = 0x00000010; +pub const DS_DIRECTORY_SERVICE_PREFERRED: ::ULONG = 0x00000020; +pub const DS_GC_SERVER_REQUIRED: ::ULONG = 0x00000040; +pub const DS_PDC_REQUIRED: ::ULONG = 0x00000080; +pub const DS_BACKGROUND_ONLY: ::ULONG = 0x00000100; +pub const DS_IP_REQUIRED: ::ULONG = 0x00000200; +pub const DS_KDC_REQUIRED: ::ULONG = 0x00000400; +pub const DS_TIMESERV_REQUIRED: ::ULONG = 0x00000800; +pub const DS_WRITABLE_REQUIRED: ::ULONG = 0x00001000; +pub const DS_GOOD_TIMESERV_PREFERRED: ::ULONG = 0x00002000; +pub const DS_AVOID_SELF: ::ULONG = 0x00004000; +pub const DS_ONLY_LDAP_NEEDED: ::ULONG = 0x00008000; +pub const DS_IS_FLAT_NAME: ::ULONG = 0x00010000; +pub const DS_IS_DNS_NAME: ::ULONG = 0x00020000; +pub const DS_TRY_NEXTCLOSEST_SITE: ::ULONG = 0x00040000; +pub const DS_DIRECTORY_SERVICE_6_REQUIRED: ::ULONG = 0x00080000; +pub const DS_WEB_SERVICE_REQUIRED: ::ULONG = 0x00100000; +pub const DS_DIRECTORY_SERVICE_8_REQUIRED: ::ULONG = 0x00200000; +pub const DS_DIRECTORY_SERVICE_9_REQUIRED: ::ULONG = 0x00400000; +pub const DS_RETURN_DNS_NAME: ::ULONG = 0x40000000; +pub const DS_RETURN_FLAT_NAME: ::ULONG = 0x80000000; +pub const DSGETDC_VALID_FLAGS: ::ULONG = DS_FORCE_REDISCOVERY | DS_DIRECTORY_SERVICE_REQUIRED + | DS_DIRECTORY_SERVICE_PREFERRED | DS_GC_SERVER_REQUIRED | DS_PDC_REQUIRED | DS_BACKGROUND_ONLY + | DS_IP_REQUIRED | DS_KDC_REQUIRED | DS_TIMESERV_REQUIRED | DS_WRITABLE_REQUIRED + | DS_GOOD_TIMESERV_PREFERRED | DS_AVOID_SELF | DS_ONLY_LDAP_NEEDED | DS_IS_FLAT_NAME + | DS_IS_DNS_NAME | DS_TRY_NEXTCLOSEST_SITE | DS_DIRECTORY_SERVICE_6_REQUIRED + | DS_DIRECTORY_SERVICE_8_REQUIRED | DS_DIRECTORY_SERVICE_9_REQUIRED | DS_WEB_SERVICE_REQUIRED + | DS_RETURN_FLAT_NAME | DS_RETURN_DNS_NAME; +STRUCT!{struct DOMAIN_CONTROLLER_INFOA { + DomainControllerName: ::LPSTR, + DomainControllerAddress: ::LPSTR, + DomainControllerAddressType: ::ULONG, + DomainGuid: ::GUID, + DomainName: ::LPSTR, + DnsForestName: ::LPSTR, + Flags: ::ULONG, + DcSiteName: ::LPSTR, + ClientSiteName: ::LPSTR, +}} +pub type PDOMAIN_CONTROLLER_INFOA = *mut DOMAIN_CONTROLLER_INFOA; +STRUCT!{struct DOMAIN_CONTROLLER_INFOW { + DomainControllerName: ::LPWSTR, + DomainControllerAddress: ::LPWSTR, + DomainControllerAddressType: ::ULONG, + DomainGuid: ::GUID, + DomainName: ::LPWSTR, + DnsForestName: ::LPWSTR, + Flags: ::ULONG, + DcSiteName: ::LPWSTR, + ClientSiteName: ::LPWSTR, +}} +pub type PDOMAIN_CONTROLLER_INFOW = *mut DOMAIN_CONTROLLER_INFOW; +pub const DS_INET_ADDRESS: ::ULONG = 1; +pub const DS_NETBIOS_ADDRESS: ::ULONG = 2; +pub const DS_PDC_FLAG: ::ULONG = 0x00000001; +pub const DS_GC_FLAG: ::ULONG = 0x00000004; +pub const DS_LDAP_FLAG: ::ULONG = 0x00000008; +pub const DS_DS_FLAG: ::ULONG = 0x00000010; +pub const DS_KDC_FLAG: ::ULONG = 0x00000020; +pub const DS_TIMESERV_FLAG: ::ULONG = 0x00000040; +pub const DS_CLOSEST_FLAG: ::ULONG = 0x00000080; +pub const DS_WRITABLE_FLAG: ::ULONG = 0x00000100; +pub const DS_GOOD_TIMESERV_FLAG: ::ULONG = 0x00000200; +pub const DS_NDNC_FLAG: ::ULONG = 0x00000400; +pub const DS_SELECT_SECRET_DOMAIN_6_FLAG: ::ULONG = 0x00000800; +pub const DS_FULL_SECRET_DOMAIN_6_FLAG: ::ULONG = 0x00001000; +pub const DS_WS_FLAG: ::ULONG = 0x00002000; +pub const DS_DS_8_FLAG: ::ULONG = 0x00004000; +pub const DS_DS_9_FLAG: ::ULONG = 0x00008000; +pub const DS_PING_FLAGS: ::ULONG = 0x000FFFFF; +pub const DS_DNS_CONTROLLER_FLAG: ::ULONG = 0x20000000; +pub const DS_DNS_DOMAIN_FLAG: ::ULONG = 0x40000000; +pub const DS_DNS_FOREST_FLAG: ::ULONG = 0x80000000; +pub const DS_DOMAIN_IN_FOREST: ::ULONG = 0x0001; +pub const DS_DOMAIN_DIRECT_OUTBOUND: ::ULONG = 0x0002; +pub const DS_DOMAIN_TREE_ROOT: ::ULONG = 0x0004; +pub const DS_DOMAIN_PRIMARY: ::ULONG = 0x0008; +pub const DS_DOMAIN_NATIVE_MODE: ::ULONG = 0x0010; +pub const DS_DOMAIN_DIRECT_INBOUND: ::ULONG = 0x0020; +pub const DS_DOMAIN_VALID_FLAGS: ::ULONG = DS_DOMAIN_IN_FOREST | DS_DOMAIN_DIRECT_OUTBOUND + | DS_DOMAIN_TREE_ROOT | DS_DOMAIN_PRIMARY | DS_DOMAIN_NATIVE_MODE | DS_DOMAIN_DIRECT_INBOUND; +STRUCT!{struct DS_DOMAIN_TRUSTSW { + NetbiosDomainName: ::LPWSTR, + DnsDomainName: ::LPWSTR, + Flags: ::ULONG, + ParentIndex: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, + DomainSid: ::PSID, + DomainGuid: ::GUID, +}} +pub type PDS_DOMAIN_TRUSTSW = *mut DS_DOMAIN_TRUSTSW; +STRUCT!{struct DS_DOMAIN_TRUSTSA { + NetbiosDomainName: ::LPSTR, + DnsDomainName: ::LPSTR, + Flags: ::ULONG, + ParentIndex: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, + DomainSid: ::PSID, + DomainGuid: ::GUID, +}} +pub type PDS_DOMAIN_TRUSTSA = *mut DS_DOMAIN_TRUSTSA; +pub const DS_ONLY_DO_SITE_NAME: ::ULONG = 0x01; +pub const DS_NOTIFY_AFTER_SITE_RECORDS: ::ULONG = 0x02; +pub const DS_OPEN_VALID_OPTION_FLAGS: ::ULONG = DS_ONLY_DO_SITE_NAME + | DS_NOTIFY_AFTER_SITE_RECORDS; +pub const DS_OPEN_VALID_FLAGS: ::ULONG = DS_FORCE_REDISCOVERY | DS_ONLY_LDAP_NEEDED + | DS_KDC_REQUIRED | DS_PDC_REQUIRED | DS_GC_SERVER_REQUIRED | DS_WRITABLE_REQUIRED; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dsound.rs b/bash-5.1/vendor/winapi-0.2.8/src/dsound.rs new file mode 100644 index 0000000..e8f167f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dsound.rs @@ -0,0 +1,132 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! DSound procedure declarations, constant definitions and macros +STRUCT!{struct DSCAPS { + dwSize: ::DWORD, + dwFlags: ::DWORD, + dwMinSecondarySampleRate: ::DWORD, + dwMaxSecondarySampleRate: ::DWORD, + dwPrimaryBuffers: ::DWORD, + dwMaxHwMixingAllBuffers: ::DWORD, + dwMaxHwMixingStaticBuffers: ::DWORD, + dwMaxHwMixingStreamingBuffers: ::DWORD, + dwFreeHwMixingAllBuffers: ::DWORD, + dwFreeHwMixingStaticBuffers: ::DWORD, + dwFreeHwMixingStreamingBuffers: ::DWORD, + dwMaxHw3DAllBuffers: ::DWORD, + dwMaxHw3DStaticBuffers: ::DWORD, + dwMaxHw3DStreamingBuffers: ::DWORD, + dwFreeHw3DAllBuffers: ::DWORD, + dwFreeHw3DStaticBuffers: ::DWORD, + dwFreeHw3DStreamingBuffers: ::DWORD, + dwTotalHwMemBytes: ::DWORD, + dwFreeHwMemBytes: ::DWORD, + dwMaxContigFreeHwMemBytes: ::DWORD, + dwUnlockTransferRateHwBuffers: ::DWORD, + dwPlayCpuOverheadSwBuffers: ::DWORD, + dwReserved1: ::DWORD, + dwReserved2: ::DWORD, +}} +pub type LPDSCAPS = *mut DSCAPS; +STRUCT!{struct DSBCAPS { + dwSize: ::DWORD, + dwFlags: ::DWORD, + dwBufferBytes: ::DWORD, + dwUnlockTransferRate: ::DWORD, + dwPlayCpuOverhead: ::DWORD, +}} +pub type LPDSBCAPS = *mut DSBCAPS; +STRUCT!{struct DSBUFFERDESC { + dwSize: ::DWORD, + dwFlags: ::DWORD, + dwBufferBytes: ::DWORD, + dwReserved: ::DWORD, + lpwfxFormat: ::LPWAVEFORMATEX, + guid3DAlgorithm: ::GUID, +}} +pub type LPCDSBUFFERDESC = *const DSBUFFERDESC; +RIDL!( +interface IDirectSoundBuffer(IDirectSoundBufferVtbl): IUnknown(IUnknownVtbl) { + fn GetCaps(&mut self, pDSBufferCaps: ::LPDSBCAPS) -> ::HRESULT, + fn GetCurrentPosition( + &mut self, pdwCurrentPlayCursor: ::LPDWORD, pdwCurrentWriteCursor: ::LPDWORD + ) -> ::HRESULT, + fn GetFormat( + &mut self, pwfxFormat: ::LPWAVEFORMATEX, dwSizeAllocated: ::DWORD, + pdwSizeWritten: ::LPDWORD + ) -> ::HRESULT, + fn GetVolume(&mut self, plVolume: ::LPLONG) -> ::HRESULT, + fn GetPan(&mut self, plPan: ::LPLONG) -> ::HRESULT, + fn GetFrequency(&mut self, pdwFrequency: ::LPDWORD) -> ::HRESULT, + fn GetStatus(&mut self, pdwStatus: ::LPDWORD) -> ::HRESULT, + fn Initialize( + &mut self, pDirectSound: ::LPDIRECTSOUND, pcDSBufferDesc: ::LPCDSBUFFERDESC + ) -> ::HRESULT, + fn Lock( + &mut self, dwOffset: ::DWORD, dwBytes: ::DWORD, ppvAudioPtr1: *mut ::LPVOID, + pdwAudioBytes1: ::LPDWORD, ppvAudioPtr2: *mut ::LPVOID, pdwAudioBytes2: ::LPDWORD, + dwFlags: ::DWORD + ) -> ::HRESULT, + fn Play(&mut self, dwReserved1: ::DWORD, dwPriority: ::DWORD, dwFlags: ::DWORD) -> ::HRESULT, + fn SetCurrentPosition(&mut self, dwNewPosition: ::DWORD) -> ::HRESULT, + fn SetFormat(&mut self, pcfxFormat: ::LPCWAVEFORMATEX) -> ::HRESULT, + fn SetVolume(&mut self, lVolume: ::LONG) -> ::HRESULT, + fn SetPan(&mut self, lPan: ::LONG) -> ::HRESULT, + fn SetFrequency(&mut self, dwFrequency: ::DWORD) -> ::HRESULT, + fn Stop(&mut self) -> ::HRESULT, + fn Unlock( + &mut self, pvAudioPtr1: ::LPVOID, dwAudioBytes1: ::DWORD, pvAudioPtr2: ::LPVOID, + dwAudioBytes2: ::DWORD + ) -> ::HRESULT, + fn Restore(&mut self) -> ::HRESULT +} +); +pub type LPDIRECTSOUNDBUFFER = *mut IDirectSoundBuffer; +RIDL!( +interface IDirectSound(IDirectSoundVtbl): IUnknown(IUnknownVtbl) +{ + fn CreateSoundBuffer( + &mut self, pcDSBufferDesc: ::LPCDSBUFFERDESC, ppDSBuffer: *mut ::LPDIRECTSOUNDBUFFER, + pUnkOuter: ::LPUNKNOWN + ) -> ::HRESULT, + fn GetCaps(&mut self, pDSCaps: ::LPDSCAPS) -> ::HRESULT, + fn DuplicateSoundBuffer( + &mut self, pDSBufferOriginal: LPDIRECTSOUNDBUFFER, + ppDSBufferDuplicate: *mut ::LPDIRECTSOUNDBUFFER + ) -> ::HRESULT, + fn SetCooperativeLevel(&mut self, hWnd: ::HWND, dwLevel: ::DWORD) -> ::HRESULT, + fn Compact(&mut self) -> ::HRESULT, + fn GetSpeakerConfig(&mut self, pdwSpeakerConfig: ::LPDWORD) -> ::HRESULT, + fn SetSpeakerConfig(&mut self, dwSpeakerConfig: ::DWORD) -> ::HRESULT, + fn Initialize(&mut self, pcGuidDevice: ::LPCGUID) -> ::HRESULT +} +); +pub type LPDIRECTSOUND = *mut IDirectSound; +pub const DS_OK: ::HRESULT = ::S_OK; +pub const DSERR_GENERIC: ::HRESULT = ::E_FAIL; +pub const DSSCL_NORMAL: ::DWORD = 0x00000001; +pub const DSSCL_PRIORITY: ::DWORD = 0x00000002; +pub const DSSCL_EXCLUSIVE: ::DWORD = 0x00000003; +pub const DSSCL_WRITEPRIMARY: ::DWORD = 0x00000004; +pub const DSBCAPS_PRIMARYBUFFER: ::DWORD = 0x00000001; +pub const DSBCAPS_STATIC: ::DWORD = 0x00000002; +pub const DSBCAPS_LOCHARDWARE: ::DWORD = 0x00000004; +pub const DSBCAPS_LOCSOFTWARE: ::DWORD = 0x00000008; +pub const DSBCAPS_CTRL3D: ::DWORD = 0x00000010; +pub const DSBCAPS_CTRLFREQUENCY: ::DWORD = 0x00000020; +pub const DSBCAPS_CTRLPAN: ::DWORD = 0x00000040; +pub const DSBCAPS_CTRLVOLUME: ::DWORD = 0x00000080; +pub const DSBCAPS_CTRLPOSITIONNOTIFY: ::DWORD = 0x00000100; +pub const DSBCAPS_CTRLFX: ::DWORD = 0x00000200; +pub const DSBCAPS_STICKYFOCUS: ::DWORD = 0x00004000; +pub const DSBCAPS_GLOBALFOCUS: ::DWORD = 0x00008000; +pub const DSBCAPS_GETCURRENTPOSITION2: ::DWORD = 0x00010000; +pub const DSBCAPS_MUTE3DATMAXDISTANCE: ::DWORD = 0x00020000; +pub const DSBCAPS_LOCDEFER: ::DWORD = 0x00040000; +pub const DSBCAPS_TRUEPLAYPOSITION: ::DWORD = 0x00080000; +pub const DSBPLAY_LOOPING: ::DWORD = 0x00000001; +pub const DSBPLAY_LOCHARDWARE: ::DWORD = 0x00000002; +pub const DSBPLAY_LOCSOFTWARE: ::DWORD = 0x00000004; +pub const DSBPLAY_TERMINATEBY_TIME: ::DWORD = 0x00000008; +pub const DSBPLAY_TERMINATEBY_DISTANCE: ::DWORD = 0x000000010; +pub const DSBPLAY_TERMINATEBY_PRIORITY: ::DWORD = 0x000000020; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dsrole.rs b/bash-5.1/vendor/winapi-0.2.8/src/dsrole.rs new file mode 100644 index 0000000..f9cf81c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dsrole.rs @@ -0,0 +1,50 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Contains public interfaces to query the network roles of workstations, servers, and DCs +ENUM!{enum DSROLE_MACHINE_ROLE { + DsRole_RoleStandaloneWorkstation, + DsRole_RoleMemberWorkstation, + DsRole_RoleStandaloneServer, + DsRole_RoleMemberServer, + DsRole_RoleBackupDomainController, + DsRole_RolePrimaryDomainController, +}} +ENUM!{enum DSROLE_SERVER_STATE { + DsRoleServerUnknown = 0, + DsRoleServerPrimary, + DsRoleServerBackup, +}} +pub type PDSROLE_SERVER_STATE = *mut DSROLE_SERVER_STATE; +ENUM!{enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL { + DsRolePrimaryDomainInfoBasic = 1, + DsRoleUpgradeStatus, + DsRoleOperationState, +}} +pub const DSROLE_PRIMARY_DS_RUNNING: ::ULONG = 0x00000001; +pub const DSROLE_PRIMARY_DS_MIXED_MODE: ::ULONG = 0x00000002; +pub const DSROLE_UPGRADE_IN_PROGRESS: ::ULONG = 0x00000004; +pub const DSROLE_PRIMARY_DS_READONLY: ::ULONG = 0x00000008; +pub const DSROLE_PRIMARY_DOMAIN_GUID_PRESENT: ::ULONG = 0x01000000; +STRUCT!{struct DSROLE_PRIMARY_DOMAIN_INFO_BASIC { + MachineRole: DSROLE_MACHINE_ROLE, + Flags: ::ULONG, + DomainNameFlat: ::LPWSTR, + DomainNameDns: ::LPWSTR, + DomainForestName: ::LPWSTR, + DomainGuid: ::GUID, +}} +pub type PDSROLE_PRIMARY_DOMAIN_INFO_BASIC = *mut DSROLE_PRIMARY_DOMAIN_INFO_BASIC; +STRUCT!{struct DSROLE_UPGRADE_STATUS_INFO { + OperationState: ::ULONG, + PreviousServerState: DSROLE_SERVER_STATE, +}} +pub type PDSROLE_UPGRADE_STATUS_INFO = *mut DSROLE_UPGRADE_STATUS_INFO; +ENUM!{enum DSROLE_OPERATION_STATE { + DsRoleOperationIdle = 0, + DsRoleOperationActive, + DsRoleOperationNeedReboot, +}} +STRUCT!{struct DSROLE_OPERATION_STATE_INFO { + OperationState: DSROLE_OPERATION_STATE, +}} +pub type PDSROLE_OPERATION_STATE_INFO = *mut DSROLE_OPERATION_STATE_INFO; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dwmapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/dwmapi.rs new file mode 100644 index 0000000..f95e8f1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dwmapi.rs @@ -0,0 +1,9 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Procedure declarations, constant definitions, and macros for the NLS component. +STRUCT!{struct DWM_BLURBEHIND { + dwFlags: ::DWORD, + fEnable: ::BOOL, + hRgnBlur: ::HRGN, + fTransitionOnMaximized: ::BOOL, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dwrite.rs b/bash-5.1/vendor/winapi-0.2.8/src/dwrite.rs new file mode 100644 index 0000000..09bbf0d --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dwrite.rs @@ -0,0 +1,1038 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! DirectX Typography Services public API definitions. +ENUM!{enum DWRITE_FONT_FILE_TYPE { + DWRITE_FONT_FILE_TYPE_UNKNOWN, + DWRITE_FONT_FILE_TYPE_CFF, + DWRITE_FONT_FILE_TYPE_TRUETYPE, + DWRITE_FONT_FILE_TYPE_TRUETYPE_COLLECTION, + DWRITE_FONT_FILE_TYPE_TYPE1_PFM, + DWRITE_FONT_FILE_TYPE_TYPE1_PFB, + DWRITE_FONT_FILE_TYPE_VECTOR, + DWRITE_FONT_FILE_TYPE_BITMAP, +}} +ENUM!{enum DWRITE_FONT_FACE_TYPE { + DWRITE_FONT_FACE_TYPE_CFF, + DWRITE_FONT_FACE_TYPE_TRUETYPE, + DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION, + DWRITE_FONT_FACE_TYPE_TYPE1, + DWRITE_FONT_FACE_TYPE_VECTOR, + DWRITE_FONT_FACE_TYPE_BITMAP, + DWRITE_FONT_FACE_TYPE_UNKNOWN, + DWRITE_FONT_FACE_TYPE_RAW_CFF, +}} +FLAGS!{enum DWRITE_FONT_SIMULATIONS { + DWRITE_FONT_SIMULATIONS_NONE = 0x0000, + DWRITE_FONT_SIMULATIONS_BOLD = 0x0001, + DWRITE_FONT_SIMULATIONS_OBLIQUE = 0x0002, +}} +ENUM!{enum DWRITE_FONT_WEIGHT { + DWRITE_FONT_WEIGHT_THIN = 100, + DWRITE_FONT_WEIGHT_EXTRA_LIGHT = 200, + DWRITE_FONT_WEIGHT_ULTRA_LIGHT = 200, + DWRITE_FONT_WEIGHT_LIGHT = 300, + DWRITE_FONT_WEIGHT_SEMI_LIGHT = 350, + DWRITE_FONT_WEIGHT_NORMAL = 400, + DWRITE_FONT_WEIGHT_REGULAR = 400, + DWRITE_FONT_WEIGHT_MEDIUM = 500, + DWRITE_FONT_WEIGHT_DEMI_BOLD = 600, + DWRITE_FONT_WEIGHT_SEMI_BOLD = 600, + DWRITE_FONT_WEIGHT_BOLD = 700, + DWRITE_FONT_WEIGHT_EXTRA_BOLD = 800, + DWRITE_FONT_WEIGHT_ULTRA_BOLD = 800, + DWRITE_FONT_WEIGHT_BLACK = 900, + DWRITE_FONT_WEIGHT_HEAVY = 900, + DWRITE_FONT_WEIGHT_EXTRA_BLACK = 950, + DWRITE_FONT_WEIGHT_ULTRA_BLACK = 950, +}} +ENUM!{enum DWRITE_FONT_STRETCH { + DWRITE_FONT_STRETCH_UNDEFINED = 0, + DWRITE_FONT_STRETCH_ULTRA_CONDENSED = 1, + DWRITE_FONT_STRETCH_EXTRA_CONDENSED = 2, + DWRITE_FONT_STRETCH_CONDENSED = 3, + DWRITE_FONT_STRETCH_SEMI_CONDENSED = 4, + DWRITE_FONT_STRETCH_NORMAL = 5, + DWRITE_FONT_STRETCH_MEDIUM = 5, + DWRITE_FONT_STRETCH_SEMI_EXPANDED = 6, + DWRITE_FONT_STRETCH_EXPANDED = 7, + DWRITE_FONT_STRETCH_EXTRA_EXPANDED = 8, + DWRITE_FONT_STRETCH_ULTRA_EXPANDED = 9, +}} +ENUM!{enum DWRITE_FONT_STYLE { + DWRITE_FONT_STYLE_NORMAL, + DWRITE_FONT_STYLE_OBLIQUE, + DWRITE_FONT_STYLE_ITALIC, +}} +ENUM!{enum DWRITE_INFORMATIONAL_STRING_ID { + DWRITE_INFORMATIONAL_STRING_NONE, + DWRITE_INFORMATIONAL_STRING_COPYRIGHT_NOTICE, + DWRITE_INFORMATIONAL_STRING_VERSION_STRINGS, + DWRITE_INFORMATIONAL_STRING_TRADEMARK, + DWRITE_INFORMATIONAL_STRING_MANUFACTURER, + DWRITE_INFORMATIONAL_STRING_DESIGNER, + DWRITE_INFORMATIONAL_STRING_DESIGNER_URL, + DWRITE_INFORMATIONAL_STRING_DESCRIPTION, + DWRITE_INFORMATIONAL_STRING_FONT_VENDOR_URL, + DWRITE_INFORMATIONAL_STRING_LICENSE_DESCRIPTION, + DWRITE_INFORMATIONAL_STRING_LICENSE_INFO_URL, + DWRITE_INFORMATIONAL_STRING_WIN32_FAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_WIN32_SUBFAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_PREFERRED_FAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_PREFERRED_SUBFAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_SAMPLE_TEXT, + DWRITE_INFORMATIONAL_STRING_FULL_NAME, + DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME, + DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_CID_NAME, + DWRITE_INFORMATIONAL_STRING_WWS_FAMILY_NAME, + DWRITE_INFORMATIONAL_STRING_DESIGN_SCRIPT_LANGUAGE_TAG, + DWRITE_INFORMATIONAL_STRING_SUPPORTED_SCRIPT_LANGUAGE_TAG, +}} +STRUCT!{struct DWRITE_FONT_METRICS { + designUnitsPerEm: ::UINT16, + ascent: ::UINT16, + descent: ::UINT16, + lineGap: ::INT16, + capHeight: ::UINT16, + xHeight: ::UINT16, + underlinePosition: ::INT16, + underlineThickness: ::UINT16, + strikethroughPosition: ::INT16, + strikethroughThickness: ::UINT16, +}} +STRUCT!{struct DWRITE_GLYPH_METRICS { + leftSideBearing: ::INT32, + advanceWidth: ::UINT32, + rightSideBearing: ::INT32, + topSideBearing: ::INT32, + advanceHeight: ::UINT32, + bottomSideBearing: ::INT32, + verticalOriginY: ::INT32, +}} +STRUCT!{struct DWRITE_GLYPH_OFFSET { + advanceOffset: ::FLOAT, + ascenderOffset: ::FLOAT, +}} +ENUM!{enum DWRITE_FACTORY_TYPE { + DWRITE_FACTORY_TYPE_SHARED, + DWRITE_FACTORY_TYPE_ISOLATED, +}} +#[inline] +pub fn DWRITE_MAKE_OPENTYPE_TAG(a: u8, b: u8, c: u8, d: u8) -> u32 { + ((d as u32) << 24) | ((c as u32) << 16) | ((b as u32) << 8) | (a as u32) +} +RIDL!{interface IDWriteFontFileLoader(IDWriteFontFileLoaderVtbl): IUnknown(IUnknownVtbl) { + fn CreateStreamFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + fontFileStream: *mut *mut IDWriteFontFileStream + ) -> ::HRESULT +}} +RIDL!{interface IDWriteLocalFontFileLoader(IDWriteLocalFontFileLoaderVtbl): + IDWriteFontFileLoader(IDWriteFontFileLoaderVtbl) { + fn GetFilePathLengthFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + filePathLength: *mut ::UINT32 + ) -> ::HRESULT, + fn GetFilePathFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + filePath: *mut ::WCHAR, + filePathSize: ::UINT32 + ) -> ::HRESULT, + fn GetLastWriteTimeFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + lastWriteTime: *mut ::FILETIME + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFileStream(IDWriteFontFileStreamVtbl): IUnknown(IUnknownVtbl) { + fn ReadFileFragment( + &mut self, fragmentStart: *mut *const ::c_void, fileOffset: ::UINT64, + fragmentSize: ::UINT64, fragmentContext: *mut *mut ::c_void + ) -> ::HRESULT, + fn ReleaseFileFragment(&mut self, fragmentContext: *mut ::c_void) -> (), + fn GetFileSize(&mut self, fileSize: *mut ::UINT64) -> ::HRESULT, + fn GetLastWriteTime(&mut self, lastWriteTime: *mut ::UINT64) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFile(IDWriteFontFileVtbl): IUnknown(IUnknownVtbl) { + fn GetReferenceKey( + &mut self, fontFileReferenceKey: *mut *const ::c_void, + fontFileReferenceKeySize: *mut ::UINT32 + ) -> ::HRESULT, + fn GetLoader(&mut self, fontFileLoader: *mut *mut IDWriteFontFileLoader) -> ::HRESULT, + fn Analyze( + &mut self, isSupportedFontType: *mut ::BOOL, fontFileType: *mut DWRITE_FONT_FILE_TYPE, + fontFaceType: *mut DWRITE_FONT_FACE_TYPE, numberOfFaces: *mut ::UINT32 + ) -> ::HRESULT +}} +ENUM!{enum DWRITE_PIXEL_GEOMETRY { + DWRITE_PIXEL_GEOMETRY_FLAT, + DWRITE_PIXEL_GEOMETRY_RGB, + DWRITE_PIXEL_GEOMETRY_BGR, +}} +ENUM!{enum DWRITE_RENDERING_MODE { + DWRITE_RENDERING_MODE_DEFAULT, + DWRITE_RENDERING_MODE_ALIASED, + DWRITE_RENDERING_MODE_GDI_CLASSIC, + DWRITE_RENDERING_MODE_GDI_NATURAL, + DWRITE_RENDERING_MODE_NATURAL, + DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC, + DWRITE_RENDERING_MODE_OUTLINE, + DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC = DWRITE_RENDERING_MODE_GDI_CLASSIC.0, + DWRITE_RENDERING_MODE_CLEARTYPE_GDI_NATURAL = DWRITE_RENDERING_MODE_GDI_NATURAL.0, + DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL = DWRITE_RENDERING_MODE_NATURAL.0, + DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC = DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC.0, +}} +STRUCT!{struct DWRITE_MATRIX { + m11: ::FLOAT, + m12: ::FLOAT, + m21: ::FLOAT, + m22: ::FLOAT, + dx: ::FLOAT, + dy: ::FLOAT, +}} +RIDL!{interface IDWriteRenderingParams(IDWriteRenderingParamsVtbl): IUnknown(IUnknownVtbl) { + fn GetGamma(&mut self) -> ::FLOAT, + fn GetEnhancedContrast(&mut self) -> ::FLOAT, + fn GetClearTypeLevel(&mut self) -> ::FLOAT, + fn GetPixelGeometry(&mut self) -> DWRITE_PIXEL_GEOMETRY, + fn GetRenderingMode(&mut self) -> DWRITE_RENDERING_MODE +}} +pub type IDWriteGeometrySink = ::ID2D1SimplifiedGeometrySink; +RIDL!{interface IDWriteFontFace(IDWriteFontFaceVtbl): IUnknown(IUnknownVtbl) { + fn GetType(&mut self) -> DWRITE_FONT_FACE_TYPE, + fn GetFiles( + &mut self, numberOfFiles: *mut ::UINT32, fontFiles: *mut *mut IDWriteFontFile + ) -> ::HRESULT, + fn GetIndex(&mut self) -> ::UINT32, + fn GetSimulations(&mut self) -> DWRITE_FONT_SIMULATIONS, + fn IsSymbolFont(&mut self) -> ::BOOL, + fn GetMetrics(&mut self, fontFaceMetrics: *mut DWRITE_FONT_METRICS) -> (), + fn GetGlyphCount(&mut self) -> ::UINT16, + fn GetDesignGlyphMetrics( + &mut self, glyphIndices: *const ::UINT16, glyphCount: ::UINT32, + glyphMetrics: *mut DWRITE_GLYPH_METRICS, isSideways: ::BOOL + ) -> ::HRESULT, + fn GetGlyphIndices( + &mut self, codePoints: *const ::UINT32, codePointCount: ::UINT32, + glyphIndices: *mut ::UINT16 + ) -> ::HRESULT, + fn TryGetFontTable( + &mut self, openTypeTableTag: ::UINT32, tableData: *mut *const ::c_void, + tableSize: *mut ::UINT32, tableContext: *mut *mut ::c_void, exists: *mut ::BOOL + ) -> ::HRESULT, + fn ReleaseFontTable( + &mut self, tableContext: *mut ::c_void + ) -> ::HRESULT, + fn GetGlyphRunOutline( + &mut self, emSize: ::FLOAT, glyphIndices: *const ::UINT16, glyphAdvances: *const ::FLOAT, + glyphOffsets: *const DWRITE_GLYPH_OFFSET, glyphCount: ::UINT32, isSideways: ::BOOL, + isRightToLeft: ::BOOL, geometrySink: *mut IDWriteGeometrySink + ) -> ::HRESULT, + fn GetRecommendedRenderingMode( + &mut self, emSize: ::FLOAT, pixelsPerDip: ::FLOAT, measuringMode: ::DWRITE_MEASURING_MODE, + renderingParams: *mut IDWriteRenderingParams, renderingMode: *mut DWRITE_RENDERING_MODE + ) -> ::HRESULT, + fn GetGdiCompatibleMetrics( + &mut self, emSize: ::FLOAT, pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, + fontFaceMetrics: *mut DWRITE_FONT_METRICS + ) -> ::HRESULT, + fn GetGdiCompatibleGlyphMetrics( + &mut self, enSize: ::FLOAT, pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, + useGdiNatrual: ::BOOL, glyphIndices: *const ::UINT16, glyphCount: ::UINT32, + glyphMetrics: *mut DWRITE_GLYPH_METRICS, isSideways: ::BOOL + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontCollectionLoader(IDWriteFontCollectionLoaderVtbl): + IUnknown(IUnknownVtbl) { + fn CreateEnumeratorFromKey( + &mut self, factory: *mut IDWriteFactory, collectionKey: *const ::c_void, + collectionKeySize: ::UINT32, fontFileEnumerator: *mut *mut IDWriteFontFileEnumerator + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFileEnumerator(IDWriteFontFileEnumeratorVtbl): IUnknown(IUnknownVtbl) { + fn MoveNext(&mut self, hasCurrentFile: *mut ::BOOL) -> ::HRESULT, + fn GetCurrentFontFile(&mut self, fontFile: *mut *mut IDWriteFontFile) -> ::HRESULT +}} +RIDL!{interface IDWriteLocalizedStrings(IDWriteLocalizedStringsVtbl): IUnknown(IUnknownVtbl) { + fn GetCount(&mut self) -> ::UINT32, + fn FindLocaleName( + &mut self, localeName: *const ::WCHAR, index: *mut ::UINT32, exists: *mut ::BOOL + ) -> ::HRESULT, + fn GetLocaleNameLength(&mut self, index: ::UINT32, length: *mut ::UINT32) -> ::HRESULT, + fn GetLocaleName( + &mut self, index: ::UINT32, localeName: *mut ::WCHAR, size: ::UINT32 + ) -> ::HRESULT, + fn GetStringLength(&mut self, index: ::UINT32, length: *mut ::UINT32) -> ::HRESULT, + fn GetString( + &mut self, index: ::UINT32, stringBuffer: *mut ::WCHAR, size: ::UINT32 + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontCollection(IDWriteFontCollectionVtbl): IUnknown(IUnknownVtbl) { + fn GetFontFamilyCount(&mut self) -> ::UINT32, + fn GetFontFamily( + &mut self, index: ::UINT32, fontFamily: *mut *mut IDWriteFontFamily + ) -> ::HRESULT, + fn FindFamilyName( + &mut self, familyName: *const ::WCHAR, index: *mut ::UINT32, exists: *mut ::BOOL + ) -> ::HRESULT, + fn GetFontFromFontFace( + &mut self, fontFace: *mut IDWriteFontFace, font: *mut *mut IDWriteFont + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontList(IDWriteFontListVtbl): IUnknown(IUnknownVtbl) { + fn GetFontCollection(&mut self, fontCollection: *mut *mut IDWriteFontCollection) -> ::HRESULT, + fn GetFontCount(&mut self) -> ::UINT32, + fn GetFont(&mut self, index: ::UINT32, font: *mut *mut IDWriteFont) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFamily(IDWriteFontFamilyVtbl): IDWriteFontList(IDWriteFontListVtbl) { + fn GetFamilyNames(&mut self, names: *mut *mut IDWriteLocalizedStrings) -> ::HRESULT, + fn GetFirstMatchingFont( + &mut self, weight: DWRITE_FONT_WEIGHT, stretch: DWRITE_FONT_STRETCH, + style: DWRITE_FONT_STYLE, matchingFont: *mut *mut IDWriteFont + ) -> ::HRESULT, + fn GetMatchingFonts( + &mut self, weight: DWRITE_FONT_WEIGHT, stretch: DWRITE_FONT_STRETCH, + style: DWRITE_FONT_STYLE, matchingFonts: *mut *mut IDWriteFontList + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFont(IDWriteFontVtbl): IUnknown(IUnknownVtbl) { + fn GetFontFamily(&mut self, fontFamily: *mut *mut IDWriteFontFamily) -> ::HRESULT, + fn GetWeight(&mut self) -> DWRITE_FONT_WEIGHT, + fn GetStretch(&mut self) -> DWRITE_FONT_STRETCH, + fn GetStyle(&mut self) -> DWRITE_FONT_STYLE, + fn IsSymbolFont(&mut self) -> ::BOOL, + fn GetFaceNames(&mut self, names: *mut *mut IDWriteLocalizedStrings) -> ::HRESULT, + fn GetInformationalStrings( + &mut self, informationalStringId: DWRITE_INFORMATIONAL_STRING_ID, + informationalStrings: *mut *mut IDWriteLocalizedStrings, exists: *mut ::BOOL + ) -> ::HRESULT, + fn GetSimulations(&mut self) -> DWRITE_FONT_SIMULATIONS, + fn GetMetrics(&mut self, fontMetrics: *mut DWRITE_FONT_METRICS) -> (), + fn HasCharacter(&mut self, unicodeValue: ::UINT32, exists: *mut ::BOOL) -> ::HRESULT, + fn CreateFontFace(&mut self, fontFace: *mut *mut IDWriteFontFace) -> ::HRESULT +}} +ENUM!{enum DWRITE_READING_DIRECTION { + DWRITE_READING_DIRECTION_LEFT_TO_RIGHT = 0, + DWRITE_READING_DIRECTION_RIGHT_TO_LEFT = 1, + DWRITE_READING_DIRECTION_TOP_TO_BOTTOM = 2, + DWRITE_READING_DIRECTION_BOTTOM_TO_TOP = 3, +}} +ENUM!{enum DWRITE_FLOW_DIRECTION { + DWRITE_FLOW_DIRECTION_TOP_TO_BOTTOM = 0, + DWRITE_FLOW_DIRECTION_BOTTOM_TO_TOP = 1, + DWRITE_FLOW_DIRECTION_LEFT_TO_RIGHT = 2, + DWRITE_FLOW_DIRECTION_RIGHT_TO_LEFT = 3, +}} +ENUM!{enum DWRITE_TEXT_ALIGNMENT { + DWRITE_TEXT_ALIGNMENT_LEADING, + DWRITE_TEXT_ALIGNMENT_TRAILING, + DWRITE_TEXT_ALIGNMENT_CENTER, + DWRITE_TEXT_ALIGNMENT_JUSTIFIED, +}} +ENUM!{enum DWRITE_PARAGRAPH_ALIGNMENT { + DWRITE_PARAGRAPH_ALIGNMENT_NEAR, + DWRITE_PARAGRAPH_ALIGNMENT_FAR, + DWRITE_PARAGRAPH_ALIGNMENT_CENTER, +}} +ENUM!{enum DWRITE_WORD_WRAPPING { + DWRITE_WORD_WRAPPING_WRAP = 0, + DWRITE_WORD_WRAPPING_NO_WRAP = 1, + DWRITE_WORD_WRAPPING_EMERGENCY_BREAK = 2, + DWRITE_WORD_WRAPPING_WHOLE_WORD = 3, + DWRITE_WORD_WRAPPING_CHARACTER = 4, +}} +ENUM!{enum DWRITE_LINE_SPACING_METHOD { + DWRITE_LINE_SPACING_METHOD_DEFAULT, + DWRITE_LINE_SPACING_METHOD_UNIFORM, + DWRITE_LINE_SPACING_METHOD_PROPORTIONAL, +}} +ENUM!{enum DWRITE_TRIMMING_GRANULARITY { + DWRITE_TRIMMING_GRANULARITY_NONE, + DWRITE_TRIMMING_GRANULARITY_CHARACTER, + DWRITE_TRIMMING_GRANULARITY_WORD, +}} +ENUM!{enum DWRITE_FONT_FEATURE_TAG { + DWRITE_FONT_FEATURE_TAG_ALTERNATIVE_FRACTIONS = 0x63726661, // 'afrc' + DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS_FROM_CAPITALS = 0x63703263, // 'c2pc' + DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS_FROM_CAPITALS = 0x63733263, // 'c2sc' + DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_ALTERNATES = 0x746c6163, // 'calt' + DWRITE_FONT_FEATURE_TAG_CASE_SENSITIVE_FORMS = 0x65736163, // 'case' + DWRITE_FONT_FEATURE_TAG_GLYPH_COMPOSITION_DECOMPOSITION = 0x706d6363, // 'ccmp' + DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_LIGATURES = 0x67696c63, // 'clig' + DWRITE_FONT_FEATURE_TAG_CAPITAL_SPACING = 0x70737063, // 'cpsp' + DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_SWASH = 0x68777363, // 'cswh' + DWRITE_FONT_FEATURE_TAG_CURSIVE_POSITIONING = 0x73727563, // 'curs' + DWRITE_FONT_FEATURE_TAG_DEFAULT = 0x746c6664, // 'dflt' + DWRITE_FONT_FEATURE_TAG_DISCRETIONARY_LIGATURES = 0x67696c64, // 'dlig' + DWRITE_FONT_FEATURE_TAG_EXPERT_FORMS = 0x74707865, // 'expt' + DWRITE_FONT_FEATURE_TAG_FRACTIONS = 0x63617266, // 'frac' + DWRITE_FONT_FEATURE_TAG_FULL_WIDTH = 0x64697766, // 'fwid' + DWRITE_FONT_FEATURE_TAG_HALF_FORMS = 0x666c6168, // 'half' + DWRITE_FONT_FEATURE_TAG_HALANT_FORMS = 0x6e6c6168, // 'haln' + DWRITE_FONT_FEATURE_TAG_ALTERNATE_HALF_WIDTH = 0x746c6168, // 'halt' + DWRITE_FONT_FEATURE_TAG_HISTORICAL_FORMS = 0x74736968, // 'hist' + DWRITE_FONT_FEATURE_TAG_HORIZONTAL_KANA_ALTERNATES = 0x616e6b68, // 'hkna' + DWRITE_FONT_FEATURE_TAG_HISTORICAL_LIGATURES = 0x67696c68, // 'hlig' + DWRITE_FONT_FEATURE_TAG_HALF_WIDTH = 0x64697768, // 'hwid' + DWRITE_FONT_FEATURE_TAG_HOJO_KANJI_FORMS = 0x6f6a6f68, // 'hojo' + DWRITE_FONT_FEATURE_TAG_JIS04_FORMS = 0x3430706a, // 'jp04' + DWRITE_FONT_FEATURE_TAG_JIS78_FORMS = 0x3837706a, // 'jp78' + DWRITE_FONT_FEATURE_TAG_JIS83_FORMS = 0x3338706a, // 'jp83' + DWRITE_FONT_FEATURE_TAG_JIS90_FORMS = 0x3039706a, // 'jp90' + DWRITE_FONT_FEATURE_TAG_KERNING = 0x6e72656b, // 'kern' + DWRITE_FONT_FEATURE_TAG_STANDARD_LIGATURES = 0x6167696c, // 'liga' + DWRITE_FONT_FEATURE_TAG_LINING_FIGURES = 0x6d756e6c, // 'lnum' + DWRITE_FONT_FEATURE_TAG_LOCALIZED_FORMS = 0x6c636f6c, // 'locl' + DWRITE_FONT_FEATURE_TAG_MARK_POSITIONING = 0x6b72616d, // 'mark' + DWRITE_FONT_FEATURE_TAG_MATHEMATICAL_GREEK = 0x6b72676d, // 'mgrk' + DWRITE_FONT_FEATURE_TAG_MARK_TO_MARK_POSITIONING = 0x6b6d6b6d, // 'mkmk' + DWRITE_FONT_FEATURE_TAG_ALTERNATE_ANNOTATION_FORMS = 0x746c616e, // 'nalt' + DWRITE_FONT_FEATURE_TAG_NLC_KANJI_FORMS = 0x6b636c6e, // 'nlck' + DWRITE_FONT_FEATURE_TAG_OLD_STYLE_FIGURES = 0x6d756e6f, // 'onum' + DWRITE_FONT_FEATURE_TAG_ORDINALS = 0x6e64726f, // 'ordn' + DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_ALTERNATE_WIDTH = 0x746c6170, // 'palt' + DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS = 0x70616370, // 'pcap' + DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_FIGURES = 0x6d756e70, // 'pnum' + DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_WIDTHS = 0x64697770, // 'pwid' + DWRITE_FONT_FEATURE_TAG_QUARTER_WIDTHS = 0x64697771, // 'qwid' + DWRITE_FONT_FEATURE_TAG_REQUIRED_LIGATURES = 0x67696c72, // 'rlig' + DWRITE_FONT_FEATURE_TAG_RUBY_NOTATION_FORMS = 0x79627572, // 'ruby' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_ALTERNATES = 0x746c6173, // 'salt' + DWRITE_FONT_FEATURE_TAG_SCIENTIFIC_INFERIORS = 0x666e6973, // 'sinf' + DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS = 0x70636d73, // 'smcp' + DWRITE_FONT_FEATURE_TAG_SIMPLIFIED_FORMS = 0x6c706d73, // 'smpl' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_1 = 0x31307373, // 'ss01' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_2 = 0x32307373, // 'ss02' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_3 = 0x33307373, // 'ss03' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_4 = 0x34307373, // 'ss04' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_5 = 0x35307373, // 'ss05' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_6 = 0x36307373, // 'ss06' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_7 = 0x37307373, // 'ss07' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_8 = 0x38307373, // 'ss08' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_9 = 0x39307373, // 'ss09' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_10 = 0x30317373, // 'ss10' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_11 = 0x31317373, // 'ss11' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_12 = 0x32317373, // 'ss12' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_13 = 0x33317373, // 'ss13' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_14 = 0x34317373, // 'ss14' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_15 = 0x35317373, // 'ss15' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_16 = 0x36317373, // 'ss16' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_17 = 0x37317373, // 'ss17' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_18 = 0x38317373, // 'ss18' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_19 = 0x39317373, // 'ss19' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_20 = 0x30327373, // 'ss20' + DWRITE_FONT_FEATURE_TAG_SUBSCRIPT = 0x73627573, // 'subs' + DWRITE_FONT_FEATURE_TAG_SUPERSCRIPT = 0x73707573, // 'sups' + DWRITE_FONT_FEATURE_TAG_SWASH = 0x68737773, // 'swsh' + DWRITE_FONT_FEATURE_TAG_TITLING = 0x6c746974, // 'titl' + DWRITE_FONT_FEATURE_TAG_TRADITIONAL_NAME_FORMS = 0x6d616e74, // 'tnam' + DWRITE_FONT_FEATURE_TAG_TABULAR_FIGURES = 0x6d756e74, // 'tnum' + DWRITE_FONT_FEATURE_TAG_TRADITIONAL_FORMS = 0x64617274, // 'trad' + DWRITE_FONT_FEATURE_TAG_THIRD_WIDTHS = 0x64697774, // 'twid' + DWRITE_FONT_FEATURE_TAG_UNICASE = 0x63696e75, // 'unic' + DWRITE_FONT_FEATURE_TAG_VERTICAL_WRITING = 0x74726576, // 'vert' + DWRITE_FONT_FEATURE_TAG_VERTICAL_ALTERNATES_AND_ROTATION = 0x32747276, // 'vrt2' + DWRITE_FONT_FEATURE_TAG_SLASHED_ZERO = 0x6f72657a, // 'zero' +}} +STRUCT!{struct DWRITE_TEXT_RANGE { + startPosition: ::UINT32, + length: ::UINT32, +}} +STRUCT!{struct DWRITE_FONT_FEATURE { + nameTag: DWRITE_FONT_FEATURE_TAG, + parameter: ::UINT32, +}} +STRUCT!{struct DWRITE_TYPOGRAPHIC_FEATURES { + features: *mut DWRITE_FONT_FEATURE, + featureCount: ::UINT32, +}} +STRUCT!{struct DWRITE_TRIMMING { + granularity: DWRITE_TRIMMING_GRANULARITY, + delimiter: ::UINT32, + delimiterCount: ::UINT32, +}} +RIDL!{interface IDWriteTextFormat(IDWriteTextFormatVtbl): IUnknown(IUnknownVtbl) { + fn SetTextAlignment(&mut self, textAlignment: DWRITE_TEXT_ALIGNMENT) -> ::HRESULT, + fn SetParagraphAlignment( + &mut self, paragraphAlignment: DWRITE_PARAGRAPH_ALIGNMENT + ) -> ::HRESULT, + fn SetWordWrapping(&mut self, wordWrapping: DWRITE_WORD_WRAPPING) -> ::HRESULT, + fn SetReadingDirection(&mut self, readingDirection: DWRITE_READING_DIRECTION) -> ::HRESULT, + fn SetFlowDirection(&mut self, flowDirection: DWRITE_FLOW_DIRECTION) -> ::HRESULT, + fn SetIncrementalTabStop(&mut self, incrementalTabStop: ::FLOAT) -> ::HRESULT, + fn SetTrimming( + &mut self, trimmingOptions: *const DWRITE_TRIMMING, trimmingSign: *mut IDWriteInlineObject + ) -> ::HRESULT, + fn SetLineSpacing( + &mut self, lineSpacingMethod: DWRITE_LINE_SPACING_METHOD, lineSpacing: ::FLOAT, + baseLine: ::FLOAT + ) -> ::HRESULT, + fn GetTextAlignment(&mut self) -> DWRITE_TEXT_ALIGNMENT, + fn GetParagraphAlignment(&mut self) -> DWRITE_PARAGRAPH_ALIGNMENT, + fn GetWordWrapping(&mut self) -> DWRITE_WORD_WRAPPING, + fn GetReadingDirection(&mut self) -> DWRITE_READING_DIRECTION, + fn GetFlowDirection(&mut self) -> DWRITE_FLOW_DIRECTION, + fn GetIncrementalTabStop(&mut self) -> ::FLOAT, + fn GetTrimming( + &mut self, trimmingOptions: *mut DWRITE_TRIMMING, + trimmingSign: *mut *mut IDWriteInlineObject + ) -> ::HRESULT, + fn GetLineSpacing( + &mut self, lineSpacingMethod: *mut DWRITE_LINE_SPACING_METHOD, lineSpacing: *mut ::FLOAT, + baseline: *mut ::FLOAT + ) -> ::HRESULT, + fn GetFontCollection(&mut self, fontCollection: *mut *mut IDWriteFontCollection) -> ::HRESULT, + fn GetFontFamilyNameLength(&mut self) -> ::UINT32, + fn GetFontFamilyName(&mut self, fontFamilyName: *mut ::WCHAR, nameSize: ::UINT32) -> ::HRESULT, + fn GetFontWeight(&mut self) -> DWRITE_FONT_WEIGHT, + fn GetFontStyle(&mut self) -> DWRITE_FONT_STYLE, + fn GetFontStretch(&mut self) -> DWRITE_FONT_STRETCH, + fn GetFontSize(&mut self) -> ::FLOAT, + fn GetLocaleNameLength(&mut self) -> ::UINT32, + fn GetLocaleName(&mut self, localeName: *mut ::WCHAR, nameSize: ::UINT32) -> ::HRESULT +}} +RIDL!{interface IDWriteTypography(IDWriteTypographyVtbl): IUnknown(IUnknownVtbl) { + fn AddFontFeature(&mut self, fontFeature: DWRITE_FONT_FEATURE) -> ::HRESULT, + fn GetFontFeatureCount(&mut self) -> ::UINT32, + fn GetFontFeature( + &mut self, fontFeatureIndex: ::UINT32, fontFeature: *mut DWRITE_FONT_FEATURE + ) -> ::HRESULT +}} +FLAGS!{enum DWRITE_SCRIPT_SHAPES { + DWRITE_SCRIPT_SHAPES_DEFAULT = 0, + DWRITE_SCRIPT_SHAPES_NO_VISUAL = 1, +}} +STRUCT!{struct DWRITE_SCRIPT_ANALYSIS { + script: ::UINT16, + shapes: DWRITE_SCRIPT_SHAPES, +}} +ENUM!{enum DWRITE_BREAK_CONDITION { + DWRITE_BREAK_CONDITION_NEUTRAL, + DWRITE_BREAK_CONDITION_CAN_BREAK, + DWRITE_BREAK_CONDITION_MAY_NOT_BREAK, + DWRITE_BREAK_CONDITION_MUST_BREAK, +}} +STRUCT!{struct DWRITE_LINE_BREAKPOINT { + bit_fields: ::UINT8, +}} +BITFIELD!{DWRITE_LINE_BREAKPOINT bit_fields: ::UINT8 [ + breakConditionBefore set_breakConditionBefore[0..2], + breakConditionAfter set_breakConditionAfter[2..4], + isWhitespace set_isWhitespace[4..5], + isSoftHyphen set_isSoftHyphen[5..6], + padding set_padding[6..8], +]} +ENUM!{enum DWRITE_NUMBER_SUBSTITUTION_METHOD { + DWRITE_NUMBER_SUBSTITUTION_METHOD_FROM_CULTURE, + DWRITE_NUMBER_SUBSTITUTION_METHOD_CONTEXTUAL, + DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE, + DWRITE_NUMBER_SUBSTITUTION_METHOD_NATIONAL, + DWRITE_NUMBER_SUBSTITUTION_METHOD_TRADITIONAL, +}} +RIDL!{interface IDWriteNumberSubstitution(IDWriteNumberSubstitutionVtbl): IUnknown(IUnknownVtbl) { +}} +STRUCT!{struct DWRITE_SHAPING_TEXT_PROPERTIES { + bit_fields: ::UINT16, +}} +BITFIELD!{DWRITE_SHAPING_TEXT_PROPERTIES bit_fields: ::UINT16 [ + isShapedAlone set_isShapedAlone[0..1], + reserved set_reserved[1..16], +]} +STRUCT!{struct DWRITE_SHAPING_GLYPH_PROPERTIES { + bit_fields: ::UINT16, +}} +BITFIELD!{DWRITE_SHAPING_GLYPH_PROPERTIES bit_fields: ::UINT16 [ + justification set_justification[0..4], + isClusterStart set_isClusterStart[4..5], + isDiacritic set_isDiacritic[5..6], + isZeroWidthSpace set_isZeroWidthSpace[6..7], + reserved set_reserved[7..16], +]} +RIDL!{interface IDWriteTextAnalysisSource(IDWriteTextAnalysisSourceVtbl): IUnknown(IUnknownVtbl) { + fn GetTextAtPosition( + &mut self, textPosition: ::UINT32, textString: *mut *const ::WCHAR, + textLength: *mut ::UINT32 + ) -> ::HRESULT, + fn GetTextBeforePosition( + &mut self, textPosition: ::UINT32, textString: *mut *const ::WCHAR, + textLength: *mut ::UINT32 + ) -> ::HRESULT, + fn GetParagraphReadingDirection(&mut self) -> DWRITE_READING_DIRECTION, + fn GetLocaleName( + &mut self, textPosition: ::UINT32, textLength: *mut ::UINT32, + localeName: *mut *const ::WCHAR + ) -> ::HRESULT, + fn GetNumberSubstitution( + &mut self, textPosition: ::UINT32, textLength: *mut ::UINT32, + numberSubstitution: *mut *mut IDWriteNumberSubstitution + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextAnalysisSink(IDWriteTextAnalysisSinkVtbl): IUnknown(IUnknownVtbl) { + fn SetScriptAnalysis( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, + scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS + ) -> ::HRESULT, + fn SetLineBreakpoints( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, + lineBreakpoints: *const DWRITE_LINE_BREAKPOINT + ) -> ::HRESULT, + fn SetBidiLevel( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, explicitLevel: ::UINT8, + resolvedLevel: ::UINT8 + ) -> ::HRESULT, + fn SetNumberSubstitution( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, + numberSubstitution: *mut IDWriteNumberSubstitution + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextAnalyzer(IDWriteTextAnalyzerVtbl): IUnknown(IUnknownVtbl) { + fn AnalyzeScript( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn AnalyzeBidi( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn AnalyzeNumberSubstitution( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn AnalyzeLineBreakpoints( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn GetGlyphs( + &mut self, textString: *const ::WCHAR, textLength: ::UINT32, + fontFace: *mut IDWriteFontFace, isSideways: ::BOOL, isRightToLeft: ::BOOL, + scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS, localeName: *const ::WCHAR, + numberSubstitution: *mut IDWriteNumberSubstitution, + features: *mut *const DWRITE_TYPOGRAPHIC_FEATURES, featureRangeLengths: *const ::UINT32, + featureRanges: ::UINT32, maxGlyphCount: ::UINT32, clusterMap: *mut ::UINT16, + textProps: *mut DWRITE_SHAPING_TEXT_PROPERTIES, glyphIndices: *mut ::UINT16, + glyphProps: *mut DWRITE_SHAPING_GLYPH_PROPERTIES, actualGlyphCount: *mut ::UINT32 + ) -> ::HRESULT, + fn GetGlyphPlacements( + &mut self, textString: *const ::WCHAR, clusterMap: *const ::UINT16, + textProps: *mut DWRITE_SHAPING_TEXT_PROPERTIES, textLength: ::UINT32, + glyphIndices: *const ::UINT16, glyphProps: *const DWRITE_SHAPING_GLYPH_PROPERTIES, + glyphCount: ::UINT32, fontFace: *mut IDWriteFontFace, fontEmSize: ::FLOAT, + isSideways: ::BOOL, isRightToLeft: ::BOOL, scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS, + localeName: *const ::WCHAR, features: *mut *const DWRITE_TYPOGRAPHIC_FEATURES, + featureRangeLengths: *const ::UINT32, featureRanges: ::UINT32, glyphAdvances: *mut ::FLOAT, + glyphOffsets: *mut DWRITE_GLYPH_OFFSET + ) -> ::HRESULT, + fn GetGdiCompatibleGlyphPlacements( + &mut self, textString: *const ::WCHAR, clusterMap: *const ::UINT16, + textProps: *mut DWRITE_SHAPING_TEXT_PROPERTIES, textLength: ::UINT32, + glyphIndices: *const ::UINT16, glyphProps: *const DWRITE_SHAPING_GLYPH_PROPERTIES, + glyphCount: ::UINT32, fontFace: *mut IDWriteFontFace, fontEmSize: ::FLOAT, + pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, useGdiNatrual: ::BOOL, + isSideways: ::BOOL, isRightToLeft: ::BOOL, scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS, + localeName: *const ::WCHAR, features: *mut *const DWRITE_TYPOGRAPHIC_FEATURES, + featureRangeLengths: *const ::UINT32, featureRanges: ::UINT32, glyphAdvances: *mut ::FLOAT, + glyphOffsets: *mut DWRITE_GLYPH_OFFSET + ) -> ::HRESULT +}} +STRUCT!{struct DWRITE_GLYPH_RUN { + fontFace: *mut IDWriteFontFace, + fontEmSize: ::FLOAT, + glyphCount: ::UINT32, + glyphIndices: *const ::UINT16, + glyphAdvances: *const ::FLOAT, + glyphOffsets: *const DWRITE_GLYPH_OFFSET, + isSideways: ::BOOL, + bidiLevel: ::UINT32, +}} +STRUCT!{struct DWRITE_GLYPH_RUN_DESCRIPTION { + localeName: *const ::WCHAR, + string: *const ::WCHAR, + stringLength: ::UINT32, + clusterMap: *const ::UINT16, + textPosition: ::UINT32, +}} +STRUCT!{struct DWRITE_UNDERLINE { + width: ::FLOAT, + thickness: ::FLOAT, + offset: ::FLOAT, + runHeight: ::FLOAT, + readingDirection: DWRITE_READING_DIRECTION, + flowDirection: DWRITE_FLOW_DIRECTION, + localeName: *const ::WCHAR, + measuringMode: ::DWRITE_MEASURING_MODE, +}} +STRUCT!{struct DWRITE_STRIKETHROUGH { + width: ::FLOAT, + thickness: ::FLOAT, + offset: ::FLOAT, + readingDirection: DWRITE_READING_DIRECTION, + flowDirection: DWRITE_FLOW_DIRECTION, + localeName: *const ::WCHAR, + measuringMode: ::DWRITE_MEASURING_MODE, +}} +STRUCT!{struct DWRITE_LINE_METRICS { + length: ::UINT32, + trailingWhitespaceLength: ::UINT32, + newlineLength: ::UINT32, + height: ::FLOAT, + baseline: ::FLOAT, + isTrimmed: ::BOOL, +}} +STRUCT!{struct DWRITE_CLUSTER_METRICS { + width: ::FLOAT, + length: ::UINT16, + bit_fields: ::UINT16, +}} +BITFIELD!{DWRITE_CLUSTER_METRICS bit_fields: ::UINT16 [ + canWrapLineAfter set_canWrapLineAfter[0..1], + isWhitespace set_isWhitespace[1..2], + isNewline set_isNewline[2..3], + isSoftHyphen set_isSoftHyphen[3..4], + isRightToLeft set_isRightToLeft[4..5], + padding set_padding[5..16], +]} +STRUCT!{struct DWRITE_TEXT_METRICS { + left: ::FLOAT, + top: ::FLOAT, + width: ::FLOAT, + widthIncludingTrailingWhitespace: ::FLOAT, + height: ::FLOAT, + layoutWidth: ::FLOAT, + layoutHeight: ::FLOAT, + maxBidiReorderingDepth: ::UINT32, + lineCount: ::UINT32, +}} +STRUCT!{struct DWRITE_INLINE_OBJECT_METRICS { + width: ::FLOAT, + height: ::FLOAT, + baseline: ::FLOAT, + supportsSideways: ::BOOL, +}} +STRUCT!{struct DWRITE_OVERHANG_METRICS { + left: ::FLOAT, + top: ::FLOAT, + right: ::FLOAT, + bottom: ::FLOAT, +}} +STRUCT!{struct DWRITE_HIT_TEST_METRICS { + textPosition: ::UINT32, + length: ::UINT32, + left: ::FLOAT, + top: ::FLOAT, + width: ::FLOAT, + height: ::FLOAT, + bidiLevel: ::UINT32, + isText: ::BOOL, + isTrimmed: ::BOOL, +}} +RIDL!{interface IDWriteInlineObject(IDWriteInlineObjectVtbl): IUnknown(IUnknownVtbl) { + fn Draw( + &mut self, clientDrawingContext: *mut ::c_void, renderer: *mut IDWriteTextRenderer, + originX: ::FLOAT, originY: ::FLOAT, isSideways: ::BOOL, isRightToLeft: ::BOOL, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn GetMetrics(&mut self, metrics: *mut DWRITE_INLINE_OBJECT_METRICS) -> ::HRESULT, + fn GetOverhangMetrics(&mut self, overhangs: *mut DWRITE_OVERHANG_METRICS) -> ::HRESULT, + fn GetBreakConditions( + &mut self, breakConditionBefore: *mut DWRITE_BREAK_CONDITION, + breakConditionAfter: *mut DWRITE_BREAK_CONDITION + ) -> ::HRESULT +}} +RIDL!{interface IDWritePixelSnapping(IDWritePixelSnappingVtbl): IUnknown(IUnknownVtbl) { + fn IsPixelSnappingDisabled( + &mut self, clientDrawingContext: *mut ::c_void, isDisabled: *mut ::BOOL + ) -> ::HRESULT, + fn GetCurrentTransform( + &mut self, clientDrawingContext: *mut ::c_void, transform: *mut DWRITE_MATRIX + ) -> ::HRESULT, + fn GetPixelsPerDip( + &mut self, clientDrawingContext: *mut ::c_void, pixelsPerDip: *mut ::FLOAT + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextRenderer(IDWriteTextRendererVtbl): + IDWritePixelSnapping(IDWritePixelSnappingVtbl) { + fn DrawGlyphRun( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, measuringMode: ::DWRITE_MEASURING_MODE, + glyphRun: *const DWRITE_GLYPH_RUN, + glyphRunDescription: *const DWRITE_GLYPH_RUN_DESCRIPTION, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn DrawUnderline( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, underline: *const DWRITE_UNDERLINE, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn DrawStrikethrough( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, strikethrough: *const DWRITE_STRIKETHROUGH, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn DrawInlineObject( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, inlineObject: *mut IDWriteInlineObject, + isSideways: ::BOOL, isRightToLeft: ::BOOL, clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextLayout(IDWriteTextLayoutVtbl): + IDWriteTextFormat(IDWriteTextFormatVtbl) { + fn SetMaxWidth(&mut self, maxWidth: ::FLOAT) -> ::HRESULT, + fn SetMaxHeight(&mut self, maxHeight: ::FLOAT) -> ::HRESULT, + fn SetFontCollection( + &mut self, fontCollection: *mut IDWriteFontCollection, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontFamilyName( + &mut self, fontFamilyName: *const ::WCHAR, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontWeight( + &mut self, fontWeight: DWRITE_FONT_WEIGHT, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontStyle( + &mut self, fontStyle: DWRITE_FONT_STYLE, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontStretch( + &mut self, fontStretch: DWRITE_FONT_STRETCH, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontSize(&mut self, fontSize: ::FLOAT, textRange: DWRITE_TEXT_RANGE) -> ::HRESULT, + fn SetUnderline(&mut self, hasUnderline: ::BOOL, textRange: DWRITE_TEXT_RANGE) -> ::HRESULT, + fn SetStrikethrough( + &mut self, hasStrikethrough: ::BOOL, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetDrawingEffect( + &mut self, drawingEffect: *mut ::IUnknown, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetInlineObject( + &mut self, inlineObject: *mut IDWriteInlineObject, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetTypography( + &mut self, typography: *mut IDWriteTypography, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetLocaleName( + &mut self, localeName: *const ::WCHAR, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetMaxWidth(&mut self) -> ::FLOAT, + fn GetMaxHeight(&mut self) -> ::FLOAT, + fn GetFontCollection( + &mut self, currentPosition: ::UINT32, fontCollection: *mut *mut IDWriteFontCollection, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontFamilyNameLength( + &mut self, currentPosition: ::UINT32, nameLength: *mut ::UINT32, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontFamilyName( + &mut self, currentPosition: ::UINT32, fontFamilyName: *mut ::WCHAR, + nameSize: ::UINT32, textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontWeight( + &mut self, currentPosition: ::UINT32, fontWeight: *mut DWRITE_FONT_WEIGHT, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontStyle( + &mut self, currentPosition: ::UINT32, fontStyle: *mut DWRITE_FONT_STYLE, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontStretch( + &mut self, currentPosition: ::UINT32, fontStretch: *mut DWRITE_FONT_STRETCH, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontSize( + &mut self, currentPosition: ::UINT32, fontSize: *mut ::FLOAT, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetUnderline( + &mut self, currentPosition: ::UINT32, hasUnderline: *mut ::BOOL, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetStrikethrough( + &mut self, currentPosition: ::UINT32, hasStrikethrough: *mut ::BOOL, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetDrawingEffect( + &mut self, currentPosition: ::UINT32, drawingEffect: *mut *mut ::IUnknown, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetInlineObject( + &mut self, currentPosition: ::UINT32, inlineObject: *mut *mut IDWriteInlineObject, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetTypography( + &mut self, currentPosition: ::UINT32, typography: *mut *mut IDWriteTypography, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetLocaleNameLength( + &mut self, currentPosition: ::UINT32, nameLength: *mut ::UINT32, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetLocaleName( + &mut self, currentPosition: ::UINT32, localeName: *mut ::WCHAR, nameSize: ::UINT32, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn Draw( + &mut self, clientDrawingContext: *mut ::c_void, renderer: *mut IDWriteTextRenderer, + originX: ::FLOAT, originY: ::FLOAT + ) -> ::HRESULT, + fn GetLineMetrics( + &mut self, lineMetrics: *mut DWRITE_LINE_METRICS, maxLineCount: ::UINT32, + actualLineCount: *mut ::UINT32 + ) -> ::HRESULT, + fn GetMetrics(&mut self, textMetrics: *mut DWRITE_TEXT_METRICS) -> ::HRESULT, + fn GetOverhangMetrics(&mut self, overhangs: *mut DWRITE_OVERHANG_METRICS) -> ::HRESULT, + fn GetClusterMetrics( + &mut self, clusterMetrics: *mut DWRITE_CLUSTER_METRICS, maxClusterCount: ::UINT32, + actualClusterCount: *mut ::UINT32 + ) -> ::HRESULT, + fn DetermineMinWidth(&mut self, minWidth: *mut ::FLOAT) -> ::HRESULT, + fn HitTestPoint( + &mut self, pointX: ::FLOAT, pointY: ::FLOAT, isTrailingHit: *mut ::BOOL, + isInside: *mut ::BOOL, hitTestMetrics: *mut DWRITE_HIT_TEST_METRICS + ) -> ::HRESULT, + fn HitTestTextPosition( + &mut self, textPosition: ::UINT32, isTrailingHit: ::BOOL, pointX: *mut ::FLOAT, + pointY: *mut ::FLOAT, hitTestMetrics: *mut DWRITE_HIT_TEST_METRICS + ) -> ::HRESULT, + fn HitTestTextRange( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, originX: ::FLOAT, + originY: ::FLOAT, hitTestMetrics: *mut DWRITE_HIT_TEST_METRICS, + maxHitTestMetricsCount: ::UINT32, actualHitTestMetricsCount: *mut ::UINT32 + ) -> ::HRESULT +}} +RIDL!{interface IDWriteBitmapRenderTarget(IDWriteBitmapRenderTargetVtbl): IUnknown(IUnknownVtbl) { + fn DrawGlyphRun( + &mut self, baselineOriginX: ::FLOAT, baselineOriginY: ::FLOAT, + measuringMode: ::DWRITE_MEASURING_MODE, glyphRun: *const ::DWRITE_GLYPH_RUN, + renderingParams: *mut IDWriteRenderingParams, textColor: ::COLORREF, + blackBoxRect: *mut ::RECT + ) -> ::HRESULT, + fn GetMemoryDC(&mut self) -> ::HDC, + fn GetPixelsPerDip(&mut self) -> ::FLOAT, + fn SetPixelsPerDip(&mut self, pixelsPerDip: ::FLOAT) -> ::HRESULT, + fn GetCurrentTransform(&mut self, transform: *mut DWRITE_MATRIX) -> ::HRESULT, + fn SetCurrentTransform(&mut self, transform: *const DWRITE_MATRIX) -> ::HRESULT, + fn GetSize(&mut self, size: *mut ::SIZE) -> ::HRESULT, + fn Resize(&mut self, width: ::UINT32, height: ::UINT32) -> ::HRESULT +}} +RIDL!{interface IDWriteGdiInterop(IDWriteGdiInteropVtbl): IUnknown(IUnknownVtbl) { + fn CreateFontFromLOGFONT( + &mut self, logFont: *const ::LOGFONTW, font: *mut *mut IDWriteFont + ) -> ::HRESULT, + fn ConvertFontToLOGFONT( + &mut self, font: *mut IDWriteFont, logFont: *mut ::LOGFONTW, isSystemFont: *mut ::BOOL + ) -> ::HRESULT, + fn ConvertFontFaceToLOGFONT( + &mut self, font: *mut IDWriteFontFace, logFont: *mut ::LOGFONTW + ) -> ::HRESULT, + fn CreateFontFaceFromHdc( + &mut self, hdc: ::HDC, fontFace: *mut *mut IDWriteFontFace + ) -> ::HRESULT, + fn CreateBitmapRenderTarget( + &mut self, hdc: ::HDC, width: ::UINT32, height: ::UINT32, + renderTarget: *mut *mut IDWriteBitmapRenderTarget + ) -> ::HRESULT +}} +ENUM!{enum DWRITE_TEXTURE_TYPE { + DWRITE_TEXTURE_ALIASED_1x1 = 0, + DWRITE_TEXTURE_CLEARTYPE_3x1 = 1, +}} +pub const DWRITE_ALPHA_MAX: ::BYTE = 255; +RIDL!{interface IDWriteGlyphRunAnalysis(IDWriteGlyphRunAnalysisVtbl): IUnknown(IUnknownVtbl) { + fn GetAlphaTextureBounds( + &mut self, textureType: DWRITE_TEXTURE_TYPE, textureBounds: *mut ::RECT + ) -> ::HRESULT, + fn CreateAlphaTexture( + &mut self, textureType: DWRITE_TEXTURE_TYPE, textureBounds: *const ::RECT, + alphaValues: *mut ::BYTE, bufferSize: ::UINT32 + ) -> ::HRESULT, + fn GetAlphaBlendParams( + &mut self, renderingParams: *mut IDWriteRenderingParams, blendGamma: *mut ::FLOAT, + blendEnhancedContrast: *mut ::FLOAT, blendClearTypeLevel: *mut ::FLOAT + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFactory(IDWriteFactoryVtbl): IUnknown(IUnknownVtbl) { + fn GetSystemFontCollection( + &mut self, fontCollection: *mut *mut IDWriteFontCollection, checkForUpdates: ::BOOL + ) -> ::HRESULT, + fn CreateCustomFontCollection( + &mut self, collectionLoader: *mut IDWriteFontCollectionLoader, + collectionKey: *const ::c_void, collectionKeySize: ::UINT32, + fontCollection: *mut *mut IDWriteFontCollection + ) -> ::HRESULT, + fn RegisterFontCollectionLoader( + &mut self, fontCollectionLoader: *mut IDWriteFontCollectionLoader + ) -> ::HRESULT, + fn UnregisterFontCollectionLoader( + &mut self, fontCollectionLoader: *mut IDWriteFontCollectionLoader + ) -> ::HRESULT, + fn CreateFontFileReference( + &mut self, filePath: *const ::WCHAR, lastWriteTime: *const ::FILETIME, + fontFile: *mut *mut IDWriteFontFile + ) -> ::HRESULT, + fn CreateCustomFontFileReference( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + fontFileLoader: *mut IDWriteFontFileLoader, fontFile: *mut *mut IDWriteFontFile + ) -> ::HRESULT, + fn CreateFontFace( + &mut self, fontFaceType: DWRITE_FONT_FACE_TYPE, numberOfFiles: ::UINT32, + fontFiles: *const *mut IDWriteFontFile, faceIndex: ::UINT32, + fontFaceSimulationFlags: DWRITE_FONT_SIMULATIONS, fontFace: *mut *mut IDWriteFontFace + ) -> ::HRESULT, + fn CreateRenderingParams( + &mut self, renderingParams: *mut *mut IDWriteRenderingParams + ) -> ::HRESULT, + fn CreateMonitorRenderingParams( + &mut self, monitor: ::HMONITOR, renderingParams: *mut *mut IDWriteRenderingParams + ) -> ::HRESULT, + fn CreateCustomRenderingParams( + &mut self, gamma: ::FLOAT, enhancedContrast: ::FLOAT, clearTypeLevel: ::FLOAT, + pixelGeometry: DWRITE_PIXEL_GEOMETRY, renderingMode: DWRITE_RENDERING_MODE, + renderingParams: *mut *mut IDWriteRenderingParams + ) -> ::HRESULT, + fn RegisterFontFileLoader( + &mut self, fontFileLoader: *mut IDWriteFontFileLoader + ) -> ::HRESULT, + fn UnregisterFontFileLoader( + &mut self, fontFileLoader: *mut IDWriteFontFileLoader + ) -> ::HRESULT, + fn CreateTextFormat( + &mut self, fontFamilyName: *const ::WCHAR, fontCollection: *mut IDWriteFontCollection, + fontWeight: DWRITE_FONT_WEIGHT, fontStyle: DWRITE_FONT_STYLE, + fontStretch: DWRITE_FONT_STRETCH, fontSize: ::FLOAT, localeName: *const ::WCHAR, + textFormat: *mut *mut IDWriteTextFormat + ) -> ::HRESULT, + fn CreateTypography(&mut self, typography: *mut *mut IDWriteTypography) -> ::HRESULT, + fn GetGdiInterop(&mut self, gdiInterop: *mut *mut IDWriteGdiInterop) -> ::HRESULT, + fn CreateTextLayout( + &mut self, string: *const ::WCHAR, stringLength: ::UINT32, + textFormat: *mut IDWriteTextFormat, maxWidth: ::FLOAT, maxHeight: ::FLOAT, + textLayout: *mut *mut IDWriteTextLayout + ) -> ::HRESULT, + fn CreateGdiCompatibleTextLayout( + &mut self, string: *const ::WCHAR, stringLength: ::UINT32, + textFormat: *mut IDWriteTextFormat, layoutWidth: ::FLOAT, layoutHeight: ::FLOAT, + pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, useGdiNatrual: ::BOOL, + textLayout: *mut *mut IDWriteTextLayout + ) -> ::HRESULT, + fn CreateEllipsisTrimmingSign( + &mut self, textFormat: *mut IDWriteTextFormat, trimmingSign: *mut *mut IDWriteInlineObject + ) -> ::HRESULT, + fn CreateTextAnalyzer(&mut self, textAnalyzer: *mut *mut IDWriteTextAnalyzer) -> ::HRESULT, + fn CreateNumberSubstitution( + &mut self, substitutionMethod: DWRITE_NUMBER_SUBSTITUTION_METHOD, + localeName: *const ::WCHAR, ignoreUserOverride: ::BOOL, + numberSubstitution: *mut *mut IDWriteNumberSubstitution + ) -> ::HRESULT, + fn CreateGlyphRunAnalysis( + &mut self, glyphRun: *const DWRITE_GLYPH_RUN, pixelsPerDip: ::FLOAT, + transform: *const DWRITE_MATRIX, renderingMode: DWRITE_RENDERING_MODE, + measuringMode: ::DWRITE_MEASURING_MODE, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, glyphRunAnalysis: *mut *mut IDWriteGlyphRunAnalysis + ) -> ::HRESULT +}} +pub const FACILITY_DWRITE: ::HRESULT = 0x898; +pub const DWRITE_ERR_BASE: ::HRESULT = 0x5000; +#[inline] +pub fn MAKE_DWRITE_HR(severity: ::HRESULT, code: ::HRESULT) -> ::HRESULT { + ::MAKE_HRESULT(severity, FACILITY_DWRITE, DWRITE_ERR_BASE + code) +} +#[inline] +pub fn MAKE_DWRITE_HR_ERR(code: ::HRESULT) -> ::HRESULT { + MAKE_DWRITE_HR(::SEVERITY_ERROR, code) +} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dxgi.rs b/bash-5.1/vendor/winapi-0.2.8/src/dxgi.rs new file mode 100644 index 0000000..c818215 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dxgi.rs @@ -0,0 +1,240 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dxgi.h +STRUCT!{struct DXGI_FRAME_STATISTICS { + PresentCount: ::UINT, + PresentRefreshCount: ::UINT, + SyncRefreshCount: ::UINT, + SyncQPCTime: ::LARGE_INTEGER, + SyncGPUTime: ::LARGE_INTEGER, +}} +STRUCT!{struct DXGI_MAPPED_RECT { + Pitch: ::INT, + pBits: *mut ::BYTE, +}} +STRUCT!{nodebug struct DXGI_ADAPTER_DESC { + Description: [::WCHAR; 128], + VectorId: ::UINT, + DeviceId: ::UINT, + SubSysId: ::UINT, + Revision: ::UINT, + DedicatedVideoMemory: ::SIZE_T, + DedicatedSystemMemory: ::SIZE_T, + SharedSystemMemory: ::SIZE_T, + AdapterLuid: ::LUID, +}} +STRUCT!{nodebug struct DXGI_OUTPUT_DESC { + DeviceName: [::WCHAR; 32], + DesktopCoordinates: ::RECT, + AttachedToDesktop: ::BOOL, + Rotation: ::DXGI_MODE_ROTATION, + Monitor: ::HMONITOR, +}} +STRUCT!{struct DXGI_SHARED_RESOURCE { + Handle: ::HANDLE, +}} +pub const DXGI_RESOURCE_PRIORITY_MINIMUM: ::DWORD = 0x28000000; +pub const DXGI_RESOURCE_PRIORITY_LOW: ::DWORD = 0x50000000; +pub const DXGI_RESOURCE_PRIORITY_NORMAL: ::DWORD = 0x78000000; +pub const DXGI_RESOURCE_PRIORITY_HIGH: ::DWORD = 0xa0000000; +pub const DXGI_RESOURCE_PRIORITY_MAXIMUM: ::DWORD = 0xc8000000; +ENUM!{enum DXGI_RESIDENCY { + DXGI_RESIDENCY_FULLY_RESIDENT = 1, + DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = 2, + DXGI_RESIDENCY_EVICTED_TO_DISK = 3, +}} +STRUCT!{struct DXGI_SURFACE_DESC { + Width: ::UINT, + Height: ::UINT, + Format: ::DXGI_FORMAT, + SampleDesc: ::DXGI_SAMPLE_DESC, +}} +ENUM!{enum DXGI_SWAP_EFFECT { + DXGI_SWAP_EFFECT_DISCARD = 0, + DXGI_SWAP_EFFECT_SEQUENTIAL = 1, + DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = 3, +}} +FLAGS!{enum DXGI_SWAP_CHAIN_FLAG { + DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = 1, + DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = 2, + DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE = 4, + DXGI_SWAP_CHAIN_FLAG_RESTRICTED_CONTENT = 8, + DXGI_SWAP_CHAIN_FLAG_RESTRICT_SHARED_RESOURCE_DRIVER = 16, + DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY = 32, + DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT = 64, + DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER = 128, + DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO = 256, + DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO = 512, +}} +STRUCT!{struct DXGI_SWAP_CHAIN_DESC { + BufferDesc: ::DXGI_MODE_DESC, + SampleDesc: ::DXGI_SAMPLE_DESC, + BufferUsage: ::DXGI_USAGE, + BufferCount: ::UINT, + OutputWindow: ::HWND, + Windowed: ::BOOL, + SwapEffect: DXGI_SWAP_EFFECT, + Flags: ::UINT, +}} +RIDL!( +interface IDXGIObject(IDXGIObjectVtbl): IUnknown(IUnknownVtbl) { + fn SetPrivateData( + &mut self, Name: ::REFGUID, DataSize: ::UINT, pData: *const ::c_void + ) -> ::HRESULT, + fn SetPrivateDataInterface(&mut self, Name: ::REFGUID, pUnknown: *const ::IUnknown) -> ::HRESULT, + fn GetPrivateData( + &mut self, Name: ::REFGUID, pDataSize: *mut ::UINT, pData: *mut ::c_void + ) -> ::HRESULT, + fn GetParent( + &mut self, riid: ::REFIID, ppParent: *mut *mut ::c_void + ) -> ::HRESULT +}); +RIDL!( +interface IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetDevice(&mut self, riid: ::REFIID, ppDevice: *mut *mut ::c_void) -> ::HRESULT +}); +RIDL!( +interface IDXGIResource(IDXGIResourceVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn GetSharedHandle(&mut self, pSharedHandle: *mut ::HANDLE) -> ::HRESULT, + fn GetUsage(&mut self, pUsage: *mut ::DXGI_USAGE) -> ::HRESULT, + fn SetEvictionPriority(&mut self, EvictionPriority: ::UINT) -> ::HRESULT, + fn GetEvictionPriority(&mut self, pEvictionPriority: *mut ::UINT) -> ::HRESULT +}); +RIDL!( +interface IDXGIKeyedMutex(IDXGIKeyedMutexVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn AcquireSync(&mut self, Key: ::UINT64, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn ReleaseSync(&mut self, Key: ::UINT64) -> ::HRESULT +}); +RIDL!( +interface IDXGISurface(IDXGISurfaceVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn GetDesc(&mut self, pDesc: *mut DXGI_SURFACE_DESC) -> ::HRESULT, + fn Map(&mut self, pLockedRect: *mut DXGI_MAPPED_RECT, MapFlags: ::UINT) -> ::HRESULT, + fn Unmap(&mut self) -> ::HRESULT +}); +RIDL!( +interface IDXGISurface1(IDXGISurface1Vtbl): IDXGISurface(IDXGISurfaceVtbl) { + fn GetDC(&mut self, Discard: ::BOOL, phdc: *mut ::HDC) -> ::HRESULT, + fn ReleaseDC(&mut self, pDirtyRect: *mut ::RECT) -> ::HRESULT +}); +RIDL!( +interface IDXGIAdapter(IDXGIAdapterVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn EnumOutputs(&mut self, Output: ::UINT, ppOutput: *mut *mut IDXGIOutput) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut DXGI_ADAPTER_DESC) -> ::HRESULT, + fn CheckInterfaceSupport( + &mut self, InterfaceName: ::REFGUID, pUMDVersion: *mut ::LARGE_INTEGER + ) -> ::HRESULT +}); +RIDL!( +interface IDXGIOutput(IDXGIOutputVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetDesc(&mut self, pDesc: *mut DXGI_OUTPUT_DESC) -> ::HRESULT, + fn GetDisplayModeList( + &mut self, EnumFormat: ::DXGI_FORMAT, Flags: ::UINT, pNumModes: *mut ::UINT, + pDesc: *mut ::DXGI_MODE_DESC + ) -> ::HRESULT, + fn FindClosestMatchingMode( + &mut self, pModeToMatch: *const ::DXGI_MODE_DESC, pClosestMatch: *mut ::DXGI_MODE_DESC, + pConcernedDevice: *mut ::IUnknown + ) -> ::HRESULT, + fn WaitForVBlank(&mut self) -> ::HRESULT, + fn TakeOwnership(&mut self, pDevice: *mut ::IUnknown, Exclusive: ::BOOL) -> ::HRESULT, + fn ReleaseOwnership(&mut self) -> (), + fn GetGammaControlCapabilities( + &mut self, pGammaCaps: *mut ::DXGI_GAMMA_CONTROL_CAPABILITIES + ) -> ::HRESULT, + fn SetGammaControl(&mut self, pArray: *const ::DXGI_GAMMA_CONTROL) -> ::HRESULT, + fn GetGammaControl(&mut self, pArray: *mut ::DXGI_GAMMA_CONTROL) -> ::HRESULT, + fn SetDisplaySurface(&mut self, pScanoutSurface: *mut IDXGISurface) -> ::HRESULT, + fn GetDisplaySurfaceData(&mut self, pDestination: *mut IDXGISurface) -> ::HRESULT, + fn GetFrameStatistics(&mut self, pStats: *mut DXGI_FRAME_STATISTICS) -> ::HRESULT +}); +pub const DXGI_MAX_SWAP_CHAIN_BUFFERS: ::DWORD = 16; +pub const DXGI_PRESENT_TEST: ::DWORD = 0x00000001; +pub const DXGI_PRESENT_DO_NOT_SEQUENCE: ::DWORD = 0x00000002; +pub const DXGI_PRESENT_RESTART: ::DWORD = 0x00000004; +pub const DXGI_PRESENT_DO_NOT_WAIT: ::DWORD = 0x00000008; +pub const DXGI_PRESENT_STEREO_PREFER_RIGHT: ::DWORD = 0x00000010; +pub const DXGI_PRESENT_STEREO_TEMPORARY_MONO: ::DWORD = 0x00000020; +pub const DXGI_PRESENT_RESTRICT_TO_OUTPUT: ::DWORD = 0x00000040; +pub const DXGI_PRESENT_USE_DURATION: ::DWORD = 0x00000100; +RIDL!( +interface IDXGISwapChain(IDXGISwapChainVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn Present(&mut self, SyncInterval: ::UINT, Flags: ::UINT) -> ::HRESULT, + fn GetBuffer( + &mut self, Buffer: ::UINT, riid: ::REFIID, ppSurface: *mut *mut ::c_void + ) -> ::HRESULT, + fn SetFullscreenState(&mut self, Fullscreen: ::BOOL, pTarget: *mut IDXGIOutput) -> ::HRESULT, + fn GetFullscreenState( + &mut self, pFullscreen: *mut ::BOOL, ppTarget: *mut *mut IDXGIOutput + ) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut DXGI_SWAP_CHAIN_DESC) -> ::HRESULT, + fn ResizeBuffers( + &mut self, BufferCount: ::UINT, Width: ::UINT, Height: ::UINT, NewFormat: ::DXGI_FORMAT, + SwapChainFlags: ::UINT + ) -> ::HRESULT, + fn ResizeTarget(&mut self, pNewTargetParameters: *const ::DXGI_MODE_DESC) -> ::HRESULT, + fn GetContainingOutput(&mut self, ppOutput: *mut *mut IDXGIOutput) -> ::HRESULT, + fn GetFrameStatistics(&mut self, pStats: *mut DXGI_FRAME_STATISTICS) -> ::HRESULT, + fn GetLastPresentCount(&mut self, pLastPresentCount: *mut ::UINT) -> ::HRESULT +}); +RIDL!( +interface IDXGIFactory(IDXGIFactoryVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn EnumAdapters(&mut self, Adapter: ::UINT, ppAdapter: *mut *mut IDXGIAdapter) -> ::HRESULT, + fn MakeWindowAssociation(&mut self, WindowHandle: ::HWND, Flags: ::UINT) -> ::HRESULT, + fn GetWindowAssociation(&mut self, pWindowHandle: *mut ::HWND) -> ::HRESULT, + fn CreateSwapChain( + &mut self, pDevice: *mut ::IUnknown, pDesc: *mut DXGI_SWAP_CHAIN_DESC, + ppSwapChain: *mut *mut IDXGISwapChain + ) -> ::HRESULT, + fn CreateSoftwareAdapter( + &mut self, Module: ::HMODULE, ppAdapter: *mut *mut IDXGIAdapter + ) -> ::HRESULT +}); +RIDL!( +interface IDXGIDevice(IDXGIDeviceVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetAdapter(&mut self, pAdapter: *mut *mut IDXGIAdapter) -> ::HRESULT, + fn CreateSurface( + &mut self, pDesc: *const DXGI_SURFACE_DESC, NumSurfaces: ::UINT, Usage: ::DXGI_USAGE, + pSharedResource: *const DXGI_SHARED_RESOURCE, ppSurface: *mut *mut IDXGISurface + ) -> ::HRESULT, + fn QueryResourceResidency( + &mut self, ppResources: *const *mut ::IUnknown, pResidencyStatus: *mut DXGI_RESIDENCY, + NumResources: ::UINT + ) -> ::HRESULT, + fn SetGPUThreadPriority(&mut self, Priority: ::INT) -> ::HRESULT, + fn GetGPUThreadPriority(&mut self, pPriority: *mut ::INT) -> ::HRESULT +}); +ENUM!{enum DXGI_ADAPTER_FLAG { + DXGI_ADAPTER_FLAG_NONE, + DXGI_ADAPTER_FLAG_REMOTE, + DXGI_ADAPTER_FLAG_SOFTWARE, +}} +STRUCT!{nodebug struct DXGI_ADAPTER_DESC1 { + Description: [::WCHAR; 128], + VendorId: ::UINT, + DeviceId: ::UINT, + SubSysId: ::UINT, + Revision: ::UINT, + DedicatedVideoMemory: ::SIZE_T, + DedicatedSystemMemory: ::SIZE_T, + SharedSystemMemory: ::SIZE_T, + AdapterLuid: ::LUID, + Flags: ::UINT, +}} +STRUCT!{struct DXGI_DISPLAY_COLOR_SPACE { + PrimaryCoordinates: [[::FLOAT; 2]; 8], + WhitePoints: [[::FLOAT; 2]; 16], +}} +RIDL!( +interface IDXGIFactory1(IDXGIFactory1Vtbl): IDXGIFactory(IDXGIFactoryVtbl) { + fn EnumAdapters1(&mut self, Adapter: ::UINT, ppAdapter: *mut *mut IDXGIAdapter1) -> ::HRESULT, + fn IsCurrent(&mut self) -> ::BOOL +}); +RIDL!( +interface IDXGIAdapter1(IDXGIAdapter1Vtbl): IDXGIAdapter(IDXGIAdapterVtbl) { + fn GetDesc1(&mut self, pDesc: *mut DXGI_ADAPTER_DESC1) -> ::HRESULT +}); +RIDL!( +interface IDXGIDevice1(IDXGIDevice1Vtbl): IDXGIDevice(IDXGIDeviceVtbl) { + fn SetMaximumFrameLatency(&mut self, MaxLatency: ::UINT) -> ::HRESULT, + fn GetMaximumFrameLatency(&mut self, pMaxLatency: *mut ::UINT) -> ::HRESULT +}); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_2.rs b/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_2.rs new file mode 100644 index 0000000..4208274 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_2.rs @@ -0,0 +1,288 @@ +// Copyright © 2015; Dmitry Roschin +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dxgi1_2.h + +ENUM!{ enum DXGI_ALPHA_MODE { + DXGI_ALPHA_MODE_UNSPECIFIED = 0, + DXGI_ALPHA_MODE_PREMULTIPLIED = 1, + DXGI_ALPHA_MODE_STRAIGHT = 2, + DXGI_ALPHA_MODE_IGNORE = 3, + DXGI_ALPHA_MODE_FORCE_DWORD = 0xFFFFFFFF, +}} + +ENUM!{ enum DXGI_COMPUTE_PREEMPTION_GRANULARITY { + DXGI_COMPUTE_PREEMPTION_DMA_BUFFER_BOUNDARY = 0, + DXGI_COMPUTE_PREEMPTION_DISPATCH_BOUNDARY = 1, + DXGI_COMPUTE_PREEMPTION_THREAD_GROUP_BOUNDARY = 2, + DXGI_COMPUTE_PREEMPTION_THREAD_BOUNDARY = 3, + DXGI_COMPUTE_PREEMPTION_INSTRUCTION_BOUNDARY = 4, +}} + +ENUM!{ enum DXGI_GRAPHICS_PREEMPTION_GRANULARITY { + DXGI_GRAPHICS_PREEMPTION_DMA_BUFFER_BOUNDARY = 0, + DXGI_GRAPHICS_PREEMPTION_PRIMITIVE_BOUNDARY = 1, + DXGI_GRAPHICS_PREEMPTION_TRIANGLE_BOUNDARY = 2, + DXGI_GRAPHICS_PREEMPTION_PIXEL_BOUNDARY = 3, + DXGI_GRAPHICS_PREEMPTION_INSTRUCTION_BOUNDARY = 4, +}} + +ENUM!{ enum DXGI_OUTDUPL_POINTER_SHAPE_TYPE { + DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME = 1, + DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR = 2, + DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MASKED_COLOR = 4, +}} + +ENUM!{ enum DXGI_SCALING { + DXGI_SCALING_STRETCH = 0, + DXGI_SCALING_NONE = 1, + DXGI_SCALING_ASPECT_RATIO_STRETCH = 2, +}} + +ENUM!{ enum _DXGI_OFFER_RESOURCE_PRIORITY { + DXGI_OFFER_RESOURCE_PRIORITY_LOW = 1, + DXGI_OFFER_RESOURCE_PRIORITY_NORMAL = 2, + DXGI_OFFER_RESOURCE_PRIORITY_HIGH = 3, +}} + +STRUCT!{nodebug struct DXGI_ADAPTER_DESC2 { + Description: [::WCHAR; 128], + VendorId: ::UINT, + DeviceId: ::UINT, + SubSysId: ::UINT, + Revision: ::UINT, + DedicatedVideoMemory: ::SIZE_T, + DedicatedSystemMemory: ::SIZE_T, + SharedSystemMemory: ::SIZE_T, + AdapterLuid: ::LUID, + Flags: ::UINT, + GraphicsPreemptionGranularity: ::DXGI_GRAPHICS_PREEMPTION_GRANULARITY, + ComputePreemptionGranularity: ::DXGI_COMPUTE_PREEMPTION_GRANULARITY, +}} + +STRUCT!{struct DXGI_MODE_DESC1 { + Width: ::UINT, + Height: ::UINT, + RefreshRate: ::DXGI_RATIONAL, + Format: ::DXGI_FORMAT, + ScanlineOrdering: ::DXGI_MODE_SCANLINE_ORDER, + Scaling: ::DXGI_MODE_SCALING, + Stereo: ::BOOL, +}} + +STRUCT!{struct DXGI_OUTDUPL_DESC { + ModeDesc: ::DXGI_MODE_DESC, + Rotation: ::DXGI_MODE_ROTATION, + DesktopImageInSystemMemory: ::BOOL, +}} + +STRUCT!{struct DXGI_OUTDUPL_FRAME_INFO { + LastPresentTime: ::LARGE_INTEGER, + LastMouseUpdateTime: ::LARGE_INTEGER, + AccumulatedFrames: ::UINT, + RectsCoalesced: ::BOOL, + ProtectedContentMaskedOut: ::BOOL, + PointerPosition: ::DXGI_OUTDUPL_POINTER_POSITION, + TotalMetadataBufferSize: ::UINT, + PointerShapeBufferSize: ::UINT, +}} + +STRUCT!{struct DXGI_OUTDUPL_MOVE_RECT { + SourcePoint: ::POINT, + DestinationRect: ::RECT, +}} + +STRUCT!{struct DXGI_OUTDUPL_POINTER_POSITION { + Position: ::POINT, + Visible: ::BOOL, +}} + +STRUCT!{struct DXGI_OUTDUPL_POINTER_SHAPE_INFO { + Type: ::UINT, + Width: ::UINT, + Height: ::UINT, + Pitch: ::UINT, + HotSpot: ::POINT, +}} + +STRUCT!{struct DXGI_PRESENT_PARAMETERS { + DirtyRectsCount: ::UINT, + pDirtyRects: *mut ::RECT, + pScrollRect: *mut ::RECT, + pScrollOffset: *mut ::POINT, +}} + +STRUCT!{struct DXGI_SWAP_CHAIN_DESC1 { + Width: ::UINT, + Height: ::UINT, + Format: ::DXGI_FORMAT, + Stereo: ::BOOL, + SampleDesc: ::DXGI_SAMPLE_DESC, + BufferUsage: ::DXGI_USAGE, + BufferCount: ::UINT, + Scaling: ::DXGI_SCALING, + SwapEffect: ::DXGI_SWAP_EFFECT, + AlphaMode: ::DXGI_ALPHA_MODE, + Flags: ::UINT, +}} + +STRUCT!{struct DXGI_SWAP_CHAIN_FULLSCREEN_DESC { + RefreshRate: ::DXGI_RATIONAL, + ScanlineOrdering: ::DXGI_MODE_SCANLINE_ORDER, + Scaling: ::DXGI_MODE_SCALING, + Windowed: ::BOOL, +}} + +RIDL!( +interface IDXGIAdapter2(IDXGIAdapter2Vtbl): IDXGIAdapter1(IDXGIAdapter1Vtbl) { + fn GetDesc2(&mut self, pDesc: *mut ::DXGI_ADAPTER_DESC2) -> ::HRESULT +}); + +RIDL!( +interface IDXGIDevice2(IDXGIDevice2Vtbl): IDXGIDevice1(IDXGIDevice1Vtbl) { + fn OfferResources( + &mut self, NumResources: ::UINT, ppResources: *mut *mut ::IDXGIResource, + Priority: ::DXGI_OFFER_RESOURCE_PRIORITY + ) -> ::HRESULT, + fn ReclaimResources( + &mut self, NumResources: ::UINT, ppResources: *mut *mut ::IDXGIResource, + pDiscarded: *mut ::BOOL + ) -> ::HRESULT, + fn EnqueueSetEvent(&mut self, hEvent: ::HANDLE) -> ::HRESULT +}); + +RIDL!( +interface IDXGIDisplayControl(IDXGIDisplayControlVtbl): IUnknown(IUnknownVtbl) { + fn IsStereoEnabled(&mut self) -> ::BOOL, + fn SetStereoEnabled(&mut self, enabled: ::BOOL) -> () +}); + +RIDL!( +interface IDXGIFactory2(IDXGIFactory2Vtbl): IDXGIFactory1(IDXGIFactory1Vtbl) { + fn IsWindowedStereoEnabled(&mut self) -> ::BOOL, + fn CreateSwapChainForHwnd( + &mut self, pDevice: *mut ::IUnknown, hWnd: ::HWND, pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, + pFullscreenDesc: *const ::DXGI_SWAP_CHAIN_FULLSCREEN_DESC, + pRestrictToOutput: *mut ::IDXGIOutput, ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT, + fn CreateSwapChainForCoreWindow( + &mut self, pDevice: *mut ::IUnknown, pWindow: *mut ::IUnknown, + pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: *mut ::IDXGIOutput, + ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT, + fn GetSharedResourceAdapterLuid( + &mut self, hResource: ::HANDLE, pLuid: *mut ::LUID + ) -> ::HRESULT, + fn RegisterStereoStatusWindow( + &mut self, WindowHandle: ::HWND, wMsg: ::UINT, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn RegisterStereoStatusEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterStereoStatus(&mut self, dwCookie: ::DWORD) -> (), + fn RegisterOcclusionStatusWindow( + &mut self, WindowHandle: ::HWND, wMsg: ::UINT, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn RegisterOcclusionStatusEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterOcclusionStatus(&mut self, dwCookie: ::DWORD) -> (), + fn CreateSwapChainForComposition( + &mut self, pDevice: *mut ::IUnknown, pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, + pRestrictToOutput: *mut ::IDXGIOutput, ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutput1(IDXGIOutput1Vtbl): IDXGIOutput(IDXGIOutputVtbl) { + fn GetDisplayModeList1( + &mut self, EnumFormat: ::DXGI_FORMAT, Flags: ::UINT, pNumModes: *mut ::UINT, + pDesc: *mut ::DXGI_MODE_DESC1 + ) -> ::HRESULT, + fn FindClosestMatchingMode1( + &mut self, pModeToMatch: *const ::DXGI_MODE_DESC1, pClosestMatch: *mut ::DXGI_MODE_DESC1, + pConcernedDevice: *mut ::IUnknown + ) -> ::HRESULT, + fn GetDisplaySurfaceData1( + &mut self, pDestination: *mut ::IDXGIResource + ) -> ::HRESULT, + fn DuplicateOutput( + &mut self, pDevice: *mut ::IUnknown, + ppOutputDuplication: *mut *mut ::IDXGIOutputDuplication + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutputDuplication(IDXGIOutputDuplicationVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::DXGI_OUTDUPL_DESC) -> (), + fn AcquireNextFrame( + &mut self, TimeoutInMilliseconds: ::UINT, pFrameInfo: *mut ::DXGI_OUTDUPL_FRAME_INFO, + ppDesktopResource: *mut *mut ::IDXGIResource + ) -> ::HRESULT, + fn GetFrameDirtyRects( + &mut self, DirtyRectsBufferSize: ::UINT, pDirtyRectsBuffer: *mut ::RECT, + pDirtyRectsBufferSizeRequired: *mut ::UINT + ) -> ::HRESULT, + fn GetFrameMoveRects( + &mut self, MoveRectsBufferSize: ::UINT, pMoveRectBuffer: *mut ::DXGI_OUTDUPL_MOVE_RECT, + pMoveRectsBufferSizeRequired: *mut ::UINT + ) -> ::HRESULT, + fn GetFramePointerShape( + &mut self, PointerShapeBufferSize: ::UINT, pPointerShapeBuffer: *mut ::c_void, + pPointerShapeBufferSizeRequired: *mut ::UINT, + pPointerShapeInfo: *mut ::DXGI_OUTDUPL_POINTER_SHAPE_INFO + ) -> ::HRESULT, + fn MapDesktopSurface( + &mut self, pLockedRect: *mut ::DXGI_MAPPED_RECT + ) -> ::HRESULT, + fn UnMapDesktopSurface(&mut self) -> ::HRESULT, + fn ReleaseFrame(&mut self) -> ::HRESULT +}); + +RIDL!( +interface IDXGIResource1(IDXGIResource1Vtbl): IDXGIResource(IDXGIResourceVtbl) { + fn CreateSubresourceSurface( + &mut self, index: ::UINT, ppSurface: *mut *mut ::IDXGISurface2 + ) -> ::HRESULT, + fn CreateSharedHandle( + &mut self, pAttributes: *const ::SECURITY_ATTRIBUTES, dwAccess: ::DWORD, lpName: ::LPCWSTR, + pHandle: *mut ::HANDLE + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISurface2(IDXGISurface2Vtbl): IDXGISurface1(IDXGISurface1Vtbl) { + fn GetResource( + &mut self, riid: ::REFGUID, ppParentResource: *mut *mut ::c_void, + pSubresourceIndex: *mut ::UINT + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChain1(IDXGISwapChain1Vtbl): IDXGISwapChain(IDXGISwapChainVtbl) { + fn GetDesc1(&mut self, pDesc: *mut ::DXGI_SWAP_CHAIN_DESC1) -> ::HRESULT, + fn GetFullscreenDesc( + &mut self, pDesc: *mut ::DXGI_SWAP_CHAIN_FULLSCREEN_DESC + ) -> ::HRESULT, + fn GetHwnd(&mut self, pHwnd: *mut ::HWND) -> ::HRESULT, + fn GetCoreWindow( + &mut self, refiid: ::REFGUID, ppUnk: *mut *mut ::c_void + ) -> ::HRESULT, + fn Present1( + &mut self, SyncInterval: ::UINT, PresentFlags: ::UINT, + pPresentParameters: *const ::DXGI_PRESENT_PARAMETERS + ) -> ::HRESULT, + fn IsTemporaryMonoSupported(&mut self) -> ::BOOL, + fn GetRestrictToOutput( + &mut self, ppRestrictToOutput: *mut *mut ::IDXGIOutput + ) -> ::HRESULT, + fn SetBackgroundColor(&mut self, pColor: *const ::DXGI_RGBA) -> ::HRESULT, + fn GetBackgroundColor(&mut self, pColor: *mut ::DXGI_RGBA) -> ::HRESULT, + fn SetRotation(&mut self, Rotation: ::DXGI_MODE_ROTATION) -> ::HRESULT, + fn GetRotation(&mut self, pRotation: *mut ::DXGI_MODE_ROTATION) -> ::HRESULT +}); + +pub type DXGI_OFFER_RESOURCE_PRIORITY = ::_DXGI_OFFER_RESOURCE_PRIORITY; +pub const DXGI_ENUM_MODES_DISABLED_STEREO: ::UINT = 8; +pub const DXGI_ENUM_MODES_STEREO: ::UINT = 4; +pub const DXGI_SHARED_RESOURCE_READ: ::UINT = 0x80000000; +pub const DXGI_SHARED_RESOURCE_WRITE: ::UINT = 1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_3.rs b/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_3.rs new file mode 100644 index 0000000..71acf98 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_3.rs @@ -0,0 +1,131 @@ +// Copyright © 2015; Dmitry Roschin +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dxgi1_3.h + +ENUM!{ enum DXGI_FRAME_PRESENTATION_MODE { + DXGI_FRAME_PRESENTATION_MODE_COMPOSED = 0, + DXGI_FRAME_PRESENTATION_MODE_OVERLAY = 1, + DXGI_FRAME_PRESENTATION_MODE_NONE = 2, + DXGI_FRAME_PRESENTATION_MODE_COMPOSITION_FAILURE = 3, +}} + +FLAGS!{ enum DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS { + DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_NOMINAL_RANGE = 0x1, + DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_BT709 = 0x2, + DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_xvYCC = 0x4, +}} + +FLAGS!{ enum DXGI_OVERLAY_SUPPORT_FLAG { + DXGI_OVERLAY_SUPPORT_FLAG_DIRECT = 0x1, + DXGI_OVERLAY_SUPPORT_FLAG_SCALING = 0x2, +}} + +STRUCT!{struct DXGI_DECODE_SWAP_CHAIN_DESC { + Flags: ::UINT, +}} + +STRUCT!{struct DXGI_FRAME_STATISTICS_MEDIA { + PresentCount: ::UINT, + PresentRefreshCount: ::UINT, + SyncRefreshCount: ::UINT, + SyncQPCTime: ::LARGE_INTEGER, + SyncGPUTime: ::LARGE_INTEGER, + CompositionMode: ::DXGI_FRAME_PRESENTATION_MODE, + ApprovedPresentDuration: ::UINT, +}} + +STRUCT!{struct DXGI_MATRIX_3X2_F { + _11: ::FLOAT, + _12: ::FLOAT, + _21: ::FLOAT, + _22: ::FLOAT, + _31: ::FLOAT, + _32: ::FLOAT, +}} + +RIDL!( +interface IDXGIDecodeSwapChain(IDXGIDecodeSwapChainVtbl): IUnknown(IUnknownVtbl) { + fn PresentBuffer( + &mut self, BufferToPresent: ::UINT, SyncInterval: ::UINT, Flags: ::UINT + ) -> ::HRESULT, + fn SetSourceRect(&mut self, pRect: *const ::RECT) -> ::HRESULT, + fn SetTargetRect(&mut self, pRect: *const ::RECT) -> ::HRESULT, + fn SetDestSize(&mut self, Width: ::UINT, Height: ::UINT) -> ::HRESULT, + fn GetSourceRect(&mut self, pRect: *mut ::RECT) -> ::HRESULT, + fn GetTargetRect(&mut self, pRect: *mut ::RECT) -> ::HRESULT, + fn GetDestSize( + &mut self, pWidth: *mut ::UINT, pHeight: *mut ::UINT + ) -> ::HRESULT, + fn SetColorSpace( + &mut self, ColorSpace: ::DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS + ) -> ::HRESULT, + fn GetColorSpace(&mut self) -> ::DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS +}); + +RIDL!( +interface IDXGIDevice3(IDXGIDevice3Vtbl): IDXGIDevice2(IDXGIDevice2Vtbl) { + fn Trim(&mut self) -> () +}); + +RIDL!( +interface IDXGIFactory3(IDXGIFactory3Vtbl): IDXGIFactory2(IDXGIFactory2Vtbl) { + fn GetCreationFlags(&mut self) -> ::UINT +}); + +RIDL!( +interface IDXGIFactoryMedia(IDXGIFactoryMediaVtbl): IUnknown(IUnknownVtbl) { + fn CreateSwapChainForCompositionSurfaceHandle( + &mut self, pDevice: *mut ::IUnknown, hSurface: ::HANDLE, + pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: *mut ::IDXGIOutput, + ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT, + fn CreateDecodeSwapChainForCompositionSurfaceHandle( + &mut self, pDevice: *mut ::IUnknown, hSurface: ::HANDLE, + pDesc: *mut ::DXGI_DECODE_SWAP_CHAIN_DESC, pYuvDecodeBuffers: *mut ::IDXGIResource, + pRestrictToOutput: *mut ::IDXGIOutput, ppSwapChain: *mut *mut ::IDXGIDecodeSwapChain + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutput2(IDXGIOutput2Vtbl): IDXGIOutput1(IDXGIOutput1Vtbl) { + fn SupportsOverlays(&mut self) -> ::BOOL +}); + +RIDL!( +interface IDXGIOutput3(IDXGIOutput3Vtbl): IDXGIOutput2(IDXGIOutput2Vtbl) { + fn CheckOverlaySupport( + &mut self, EnumFormat: ::DXGI_FORMAT, pConcernedDevice: *mut ::IUnknown, + pFlags: *mut ::UINT + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChain2(IDXGISwapChain2Vtbl): IDXGISwapChain1(IDXGISwapChain1Vtbl) { + fn SetSourceSize(&mut self, Width: ::UINT, Height: ::UINT) -> ::HRESULT, + fn GetSourceSize( + &mut self, pWidth: *mut ::UINT, pHeight: *mut ::UINT + ) -> ::HRESULT, + fn SetMaximumFrameLatency(&mut self, MaxLatency: ::UINT) -> ::HRESULT, + fn GetMaximumFrameLatency(&mut self, pMaxLatency: *mut ::UINT) -> ::HRESULT, + fn GetFrameLatencyWaitableObject(&mut self) -> ::HANDLE, + fn SetMatrixTransform( + &mut self, pMatrix: *const ::DXGI_MATRIX_3X2_F + ) -> ::HRESULT, + fn GetMatrixTransform( + &mut self, pMatrix: *mut ::DXGI_MATRIX_3X2_F + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChainMedia(IDXGISwapChainMediaVtbl): IUnknown(IUnknownVtbl) { + fn GetFrameStatisticsMedia( + &mut self, pStats: *mut ::DXGI_FRAME_STATISTICS_MEDIA + ) -> ::HRESULT, + fn SetPresentDuration(&mut self, Duration: ::UINT) -> ::HRESULT, + fn CheckPresentDurationSupport( + &mut self, DesiredPresentDuration: ::UINT, pClosestSmallerPresentDuration: *mut ::UINT, + pClosestLargerPresentDuration: *mut ::UINT + ) -> ::HRESULT +}); + +pub const DXGI_CREATE_FACTORY_DEBUG: ::UINT = 0x1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_4.rs b/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_4.rs new file mode 100644 index 0000000..cbca18f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dxgi1_4.rs @@ -0,0 +1,82 @@ +// Copyright © 2015; Dmitry Roschin +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dxgi1_4.h + +ENUM!{ enum DXGI_MEMORY_SEGMENT_GROUP { + DXGI_MEMORY_SEGMENT_GROUP_LOCAL = 0, + DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL = 1, +}} + +FLAGS!{ enum DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG { + DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG_PRESENT = 0x1, +}} + +FLAGS!{ enum DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG { + DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT = 0x1, + DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_OVERLAY_PRESENT = 0x2, +}} + +STRUCT!{struct DXGI_QUERY_VIDEO_MEMORY_INFO { + Budget: ::UINT64, + CurrentUsage: ::UINT64, + AvailableForReservation: ::UINT64, + CurrentReservation: ::UINT64, +}} + +RIDL!( +interface IDXGIAdapter3(IDXGIAdapter3Vtbl): IDXGIAdapter2(IDXGIAdapter2Vtbl) { + fn RegisterHardwareContentProtectionTeardownStatusEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterHardwareContentProtectionTeardownStatus( + &mut self, dwCookie: ::DWORD + ) -> (), + fn QueryVideoMemoryInfo( + &mut self, NodeIndex: ::UINT, MemorySegmentGroup: ::DXGI_MEMORY_SEGMENT_GROUP, + pVideoMemoryInfo: *mut ::DXGI_QUERY_VIDEO_MEMORY_INFO + ) -> ::HRESULT, + fn SetVideoMemoryReservation( + &mut self, NodeIndex: ::UINT, MemorySegmentGroup: ::DXGI_MEMORY_SEGMENT_GROUP, + Reservation: ::UINT64 + ) -> ::HRESULT, + fn RegisterVideoMemoryBudgetChangeNotificationEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterVideoMemoryBudgetChangeNotification( + &mut self, dwCookie: ::DWORD + ) -> () +}); + +RIDL!( +interface IDXGIFactory4(IDXGIFactory4Vtbl): IDXGIFactory3(IDXGIFactory3Vtbl) { + fn EnumAdapterByLuid( + &mut self, AdapterLuid: ::LUID, riid: ::REFGUID, ppvAdapter: *mut *mut ::c_void + ) -> ::HRESULT, + fn EnumWarpAdapter( + &mut self, riid: ::REFGUID, ppvAdapter: *mut *mut ::c_void + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutput4(IDXGIOutput4Vtbl): IDXGIOutput3(IDXGIOutput3Vtbl) { + fn CheckOverlayColorSpaceSupport( + &mut self, Format: ::DXGI_FORMAT, ColorSpace: ::DXGI_COLOR_SPACE_TYPE, + pConcernedDevice: *mut ::IUnknown, pFlags: *mut ::UINT + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChain3(IDXGISwapChain3Vtbl): IDXGISwapChain2(IDXGISwapChain2Vtbl) { + fn GetCurrentBackBufferIndex(&mut self) -> ::UINT, + fn CheckColorSpaceSupport( + &mut self, ColorSpace: ::DXGI_COLOR_SPACE_TYPE, pColorSpaceSupport: *mut ::UINT + ) -> ::HRESULT, + fn SetColorSpace1( + &mut self, ColorSpace: ::DXGI_COLOR_SPACE_TYPE + ) -> ::HRESULT, + fn ResizeBuffers1( + &mut self, BufferCount: ::UINT, Width: ::UINT, Height: ::UINT, Format: ::DXGI_FORMAT, + SwapChainFlags: ::UINT, pCreationNodeMask: *const ::UINT, + ppPresentQueue: *mut *mut ::IUnknown + ) -> ::HRESULT +}); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dxgiformat.rs b/bash-5.1/vendor/winapi-0.2.8/src/dxgiformat.rs new file mode 100644 index 0000000..3e46fc2 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dxgiformat.rs @@ -0,0 +1,124 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dxgiformat.h +ENUM!{enum DXGI_FORMAT { + DXGI_FORMAT_UNKNOWN = 0, + DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, + DXGI_FORMAT_R32G32B32A32_FLOAT = 2, + DXGI_FORMAT_R32G32B32A32_UINT = 3, + DXGI_FORMAT_R32G32B32A32_SINT = 4, + DXGI_FORMAT_R32G32B32_TYPELESS = 5, + DXGI_FORMAT_R32G32B32_FLOAT = 6, + DXGI_FORMAT_R32G32B32_UINT = 7, + DXGI_FORMAT_R32G32B32_SINT = 8, + DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, + DXGI_FORMAT_R16G16B16A16_FLOAT = 10, + DXGI_FORMAT_R16G16B16A16_UNORM = 11, + DXGI_FORMAT_R16G16B16A16_UINT = 12, + DXGI_FORMAT_R16G16B16A16_SNORM = 13, + DXGI_FORMAT_R16G16B16A16_SINT = 14, + DXGI_FORMAT_R32G32_TYPELESS = 15, + DXGI_FORMAT_R32G32_FLOAT = 16, + DXGI_FORMAT_R32G32_UINT = 17, + DXGI_FORMAT_R32G32_SINT = 18, + DXGI_FORMAT_R32G8X24_TYPELESS = 19, + DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, + DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, + DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, + DXGI_FORMAT_R10G10B10A2_UNORM = 24, + DXGI_FORMAT_R10G10B10A2_UINT = 25, + DXGI_FORMAT_R11G11B10_FLOAT = 26, + DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, + DXGI_FORMAT_R8G8B8A8_UNORM = 28, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, + DXGI_FORMAT_R8G8B8A8_UINT = 30, + DXGI_FORMAT_R8G8B8A8_SNORM = 31, + DXGI_FORMAT_R8G8B8A8_SINT = 32, + DXGI_FORMAT_R16G16_TYPELESS = 33, + DXGI_FORMAT_R16G16_FLOAT = 34, + DXGI_FORMAT_R16G16_UNORM = 35, + DXGI_FORMAT_R16G16_UINT = 36, + DXGI_FORMAT_R16G16_SNORM = 37, + DXGI_FORMAT_R16G16_SINT = 38, + DXGI_FORMAT_R32_TYPELESS = 39, + DXGI_FORMAT_D32_FLOAT = 40, + DXGI_FORMAT_R32_FLOAT = 41, + DXGI_FORMAT_R32_UINT = 42, + DXGI_FORMAT_R32_SINT = 43, + DXGI_FORMAT_R24G8_TYPELESS = 44, + DXGI_FORMAT_D24_UNORM_S8_UINT = 45, + DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, + DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, + DXGI_FORMAT_R8G8_TYPELESS = 48, + DXGI_FORMAT_R8G8_UNORM = 49, + DXGI_FORMAT_R8G8_UINT = 50, + DXGI_FORMAT_R8G8_SNORM = 51, + DXGI_FORMAT_R8G8_SINT = 52, + DXGI_FORMAT_R16_TYPELESS = 53, + DXGI_FORMAT_R16_FLOAT = 54, + DXGI_FORMAT_D16_UNORM = 55, + DXGI_FORMAT_R16_UNORM = 56, + DXGI_FORMAT_R16_UINT = 57, + DXGI_FORMAT_R16_SNORM = 58, + DXGI_FORMAT_R16_SINT = 59, + DXGI_FORMAT_R8_TYPELESS = 60, + DXGI_FORMAT_R8_UNORM = 61, + DXGI_FORMAT_R8_UINT = 62, + DXGI_FORMAT_R8_SNORM = 63, + DXGI_FORMAT_R8_SINT = 64, + DXGI_FORMAT_A8_UNORM = 65, + DXGI_FORMAT_R1_UNORM = 66, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, + DXGI_FORMAT_R8G8_B8G8_UNORM = 68, + DXGI_FORMAT_G8R8_G8B8_UNORM = 69, + DXGI_FORMAT_BC1_TYPELESS = 70, + DXGI_FORMAT_BC1_UNORM = 71, + DXGI_FORMAT_BC1_UNORM_SRGB = 72, + DXGI_FORMAT_BC2_TYPELESS = 73, + DXGI_FORMAT_BC2_UNORM = 74, + DXGI_FORMAT_BC2_UNORM_SRGB = 75, + DXGI_FORMAT_BC3_TYPELESS = 76, + DXGI_FORMAT_BC3_UNORM = 77, + DXGI_FORMAT_BC3_UNORM_SRGB = 78, + DXGI_FORMAT_BC4_TYPELESS = 79, + DXGI_FORMAT_BC4_UNORM = 80, + DXGI_FORMAT_BC4_SNORM = 81, + DXGI_FORMAT_BC5_TYPELESS = 82, + DXGI_FORMAT_BC5_UNORM = 83, + DXGI_FORMAT_BC5_SNORM = 84, + DXGI_FORMAT_B5G6R5_UNORM = 85, + DXGI_FORMAT_B5G5R5A1_UNORM = 86, + DXGI_FORMAT_B8G8R8A8_UNORM = 87, + DXGI_FORMAT_B8G8R8X8_UNORM = 88, + DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, + DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, + DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, + DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, + DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, + DXGI_FORMAT_BC6H_TYPELESS = 94, + DXGI_FORMAT_BC6H_UF16 = 95, + DXGI_FORMAT_BC6H_SF16 = 96, + DXGI_FORMAT_BC7_TYPELESS = 97, + DXGI_FORMAT_BC7_UNORM = 98, + DXGI_FORMAT_BC7_UNORM_SRGB = 99, + DXGI_FORMAT_AYUV = 100, + DXGI_FORMAT_Y410 = 101, + DXGI_FORMAT_Y416 = 102, + DXGI_FORMAT_NV12 = 103, + DXGI_FORMAT_P010 = 104, + DXGI_FORMAT_P016 = 105, + DXGI_FORMAT_420_OPAQUE = 106, + DXGI_FORMAT_YUY2 = 107, + DXGI_FORMAT_Y210 = 108, + DXGI_FORMAT_Y216 = 109, + DXGI_FORMAT_NV11 = 110, + DXGI_FORMAT_AI44 = 111, + DXGI_FORMAT_IA44 = 112, + DXGI_FORMAT_P8 = 113, + DXGI_FORMAT_A8P8 = 114, + DXGI_FORMAT_B4G4R4A4_UNORM = 115, + DXGI_FORMAT_P208 = 130, + DXGI_FORMAT_V208 = 131, + DXGI_FORMAT_V408 = 132, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/dxgitype.rs b/bash-5.1/vendor/winapi-0.2.8/src/dxgitype.rs new file mode 100644 index 0000000..6c9a2f5 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/dxgitype.rs @@ -0,0 +1,86 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of dxgitype.h +pub const DXGI_CPU_ACCESS_NONE: ::DWORD = 0; +pub const DXGI_CPU_ACCESS_DYNAMIC: ::DWORD = 1; +pub const DXGI_CPU_ACCESS_READ_WRITE: ::DWORD = 2; +pub const DXGI_CPU_ACCESS_SCRATCH: ::DWORD = 3; +pub const DXGI_CPU_ACCESS_FIELD: ::DWORD = 15; +FLAGS!{enum DXGI_USAGE { + DXGI_USAGE_SHADER_INPUT = 1 << (0 + 4), + DXGI_USAGE_RENDER_TARGET_OUTPUT = 1 << (1 + 4), + DXGI_USAGE_BACK_BUFFER = 1 << (2 + 4), + DXGI_USAGE_SHARED = 1 << (3 + 4), + DXGI_USAGE_READ_ONLY = 1 << (4 + 4), + DXGI_USAGE_DISCARD_ON_PRESENT = 1 << (5 + 4), + DXGI_USAGE_UNORDERED_ACCESS = 1 << (6 + 4), +}} +STRUCT!{struct DXGI_RGB { + Red: f32, + Green: f32, + Blue: f32, +}} +pub type DXGI_RGBA = ::D3DCOLORVALUE; +STRUCT!{nodebug struct DXGI_GAMMA_CONTROL { + Scale: DXGI_RGB, + Offset: DXGI_RGB, + GammaCurve: [DXGI_RGB; 1025], +}} +STRUCT!{nodebug struct DXGI_GAMMA_CONTROL_CAPABILITIES { + ScaleAndOffsetSupported: ::BOOL, + MaxConvertedValue: f32, + MinConvertedValue: f32, + NumGammaControlPoints: ::UINT, + ControlPointPositions: [f32; 1025], +}} +STRUCT!{struct DXGI_RATIONAL { + Numerator: ::UINT, + Denominator: ::UINT, +}} +ENUM!{enum DXGI_MODE_SCANLINE_ORDER { + DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED, + DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE, + DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST, + DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST, +}} +ENUM!{enum DXGI_MODE_SCALING { + DXGI_MODE_SCALING_UNSPECIFIED, + DXGI_MODE_SCALING_CENTERED, + DXGI_MODE_SCALING_STRETCHED, +}} +ENUM!{enum DXGI_MODE_ROTATION { + DXGI_MODE_ROTATION_UNSPECIFIED, + DXGI_MODE_ROTATION_IDENTITY, + DXGI_MODE_ROTATION_ROTATE90, + DXGI_MODE_ROTATION_ROTATE180, + DXGI_MODE_ROTATION_ROTATE270, +}} +STRUCT!{struct DXGI_MODE_DESC { + Width: ::UINT, + Height: ::UINT, + RefreshRate: DXGI_RATIONAL, + Format: ::DXGI_FORMAT, + ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER, + Scaling: DXGI_MODE_SCALING, +}} +STRUCT!{struct DXGI_SAMPLE_DESC { + Count: ::UINT, + Quality: ::UINT, +}} +ENUM!{enum DXGI_COLOR_SPACE_TYPE { + DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 = 0x0, + DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 = 0x1, + DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709 = 0x2, + DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P2020 = 0x3, + DXGI_COLOR_SPACE_RESERVED = 0x4, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 = 0x5, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 = 0x6, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601 = 0x7, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 = 0x8, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709 = 0x9, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 = 0xA, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 = 0xB, + DXGI_COLOR_SPACE_CUSTOM = 0xFFFFFFFF, +}} +pub const DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN: ::UINT = 0xfffffffe; +pub const DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN: ::UINT = 0xffffffff; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/errhandlingapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/errhandlingapi.rs new file mode 100644 index 0000000..fbdde40 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/errhandlingapi.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-errorhandling-l1 +pub type PTOP_LEVEL_EXCEPTION_FILTER = Option<unsafe extern "system" fn( + ExceptionInfo: *mut ::EXCEPTION_POINTERS, +) -> ::LONG>; +pub type LPTOP_LEVEL_EXCEPTION_FILTER = PTOP_LEVEL_EXCEPTION_FILTER; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/excpt.rs b/bash-5.1/vendor/winapi-0.2.8/src/excpt.rs new file mode 100644 index 0000000..53ea3ff --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/excpt.rs @@ -0,0 +1,14 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +ENUM!{enum EXCEPTION_DISPOSITION { + ExceptionContinueExecution = 0, + ExceptionContinueSearch = 1, + ExceptionNestedException = 2, + ExceptionCollidedUnwind = 3, +}} +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct _EXCEPTION_RECORD; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct _CONTEXT; +#[cfg(target_arch = "x86_64")] #[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct _DISPATCHER_CONTEXT; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/fileapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/fileapi.rs new file mode 100644 index 0000000..764a7f6 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/fileapi.rs @@ -0,0 +1,152 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-file-l1 +pub const CREATE_NEW: ::DWORD = 1; +pub const CREATE_ALWAYS: ::DWORD = 2; +pub const OPEN_EXISTING: ::DWORD = 3; +pub const OPEN_ALWAYS: ::DWORD = 4; +pub const TRUNCATE_EXISTING: ::DWORD = 5; +pub const INVALID_FILE_SIZE: ::DWORD = 0xFFFFFFFF; +pub const INVALID_SET_FILE_POINTER: ::DWORD = 0xFFFFFFFF; +pub const INVALID_FILE_ATTRIBUTES: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct WIN32_FILE_ATTRIBUTE_DATA { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, +}} +pub type LPWIN32_FILE_ATTRIBUTE_DATA = *mut WIN32_FILE_ATTRIBUTE_DATA; +STRUCT!{struct BY_HANDLE_FILE_INFORMATION { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + dwVolumeSerialNumber: ::DWORD, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, + nNumberOfLinks: ::DWORD, + nFileIndexHigh: ::DWORD, + nFileIndexLow: ::DWORD, +}} +pub type PBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; +pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; +STRUCT!{struct CREATEFILE2_EXTENDED_PARAMETERS { + dwSize: ::DWORD, + dwFileAttributes: ::DWORD, + dwFileFlags: ::DWORD, + dwSecurityQosFlags: ::DWORD, + lpSecurityAttributes: ::LPSECURITY_ATTRIBUTES, + hTemplateFile: ::HANDLE, +}} +pub type PCREATEFILE2_EXTENDED_PARAMETERS = *mut CREATEFILE2_EXTENDED_PARAMETERS; +pub type LPCREATEFILE2_EXTENDED_PARAMETERS = *mut CREATEFILE2_EXTENDED_PARAMETERS; +ENUM!{enum PRIORITY_HINT { + IoPriorityHintVeryLow = 0, + IoPriorityHintLow = 1, + IoPriorityHintNormal = 2, + MaximumIoPriorityHintType = 3, +}} +STRUCT!{struct FILE_BASIC_INFO { + CreationTime: ::LARGE_INTEGER, + LastAccessTime: ::LARGE_INTEGER, + LastWriteTime: ::LARGE_INTEGER, + ChangeTime: ::LARGE_INTEGER, + FileAttributes: ::DWORD, +}} +STRUCT!{struct FILE_STANDARD_INFO { + AllocationSize: ::LARGE_INTEGER, + EndOfFile: ::LARGE_INTEGER, + NumberOfLinks: ::DWORD, + DeletePending: ::BOOLEAN, + Directory: ::BOOLEAN, +}} +STRUCT!{struct FILE_NAME_INFO { + FileNameLength: ::DWORD, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_RENAME_INFO { + ReplaceIfExists: ::BOOL, + RootDirectory: ::HANDLE, + FileNameLength: ::DWORD, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_DISPOSITION_INFO { + DeleteFile: ::BOOL, +}} +STRUCT!{struct FILE_ALLOCATION_INFO { + AllocationSize: ::LARGE_INTEGER, +}} +STRUCT!{struct FILE_END_OF_FILE_INFO { + EndOfFile: ::LARGE_INTEGER, +}} +STRUCT!{struct FILE_STREAM_INFO { + NextEntryOffset: ::DWORD, + StreamNameLength: ::DWORD, + StreamSize: ::DWORD, + StreamAllocationSize: ::DWORD, + StreamName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_COMPRESSION_INFO { + CompressedFileSize: ::LARGE_INTEGER, + CompressionFormat: ::WORD, + CompressionUnitShift: ::UCHAR, + ChunkShift: ::UCHAR, + ClusterShift: ::UCHAR, + Reserved: [::UCHAR; 3], +}} +STRUCT!{struct FILE_ATTRIBUTE_TAG_INFO { + NextEntryOffset: ::DWORD, + ReparseTag: ::DWORD, +}} +STRUCT!{struct FILE_ID_BOTH_DIR_INFO { + NextEntryOffset: ::DWORD, + FileIndex: ::DWORD, + CreationTime: ::LARGE_INTEGER, + LastAccessTime: ::LARGE_INTEGER, + LastWriteTime: ::LARGE_INTEGER, + ChangeTime: ::LARGE_INTEGER, + EndOfFile: ::LARGE_INTEGER, + AllocationSize: ::LARGE_INTEGER, + FileAttributes: ::DWORD, + FileNameLength: ::DWORD, + EaSize: ::DWORD, + ShortNameLength: ::CCHAR, + ShortName: [::WCHAR; 12], + FileId: ::LARGE_INTEGER, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_IO_PRIORITY_HINT_INFO { + PriorityHint: ::PRIORITY_HINT, +}} +STRUCT!{struct FILE_FULL_DIR_INFO { + NextEntryOffset: ::ULONG, + FileIndex: ::ULONG, + CreationTime: ::LARGE_INTEGER, + LastAccessTime: ::LARGE_INTEGER, + LastWriteTime: ::LARGE_INTEGER, + ChangeTime: ::LARGE_INTEGER, + EndOfFile: ::LARGE_INTEGER, + AllocationSize: ::LARGE_INTEGER, + FileAttributes: ::ULONG, + FileNameLength: ::ULONG, + EaSize: ::ULONG, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_STORAGE_INFO { + LogicalBytesPerSector: ::ULONG, + PhysicalBytesPerSectorForAtomicity: ::ULONG, + PhysicalBytesPerSectorForPerformance: ::ULONG, + FileSystemEffectivePhysicalBytesPerSectorForAtomicity: ::ULONG, + Flags: ::ULONG, + ByteOffsetForSectorAlignment: ::ULONG, + ByteOffsetForPartitionAlignment: ::ULONG, +}} +STRUCT!{struct FILE_ALIGNMENT_INFO { + AlignmentRequirement: ::ULONG, +}} +STRUCT!{struct FILE_ID_INFO { + VolumeSerialNumber: ::ULONGLONG, + FileId: ::FILE_ID_128, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/gl.rs b/bash-5.1/vendor/winapi-0.2.8/src/gl.rs new file mode 100644 index 0000000..006c37e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/gl.rs @@ -0,0 +1,35 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//48 +pub type GLenum = ::c_uint; +pub type GLboolean = ::c_uchar; +pub type GLbitfield = ::c_uint; +pub type GLbyte = ::c_schar; +pub type GLshort = ::c_short; +pub type GLint = ::c_int; +pub type GLsizei = ::c_int; +pub type GLubyte = ::c_uchar; +pub type GLushort = ::c_ushort; +pub type GLuint = ::c_uint; +pub type GLfloat = ::c_float; +pub type GLclampf = ::c_float; +pub type GLdouble = ::c_double; +pub type GLclampd = ::c_double; +pub type GLvoid = ::c_void; +//63 +//68 +//AccumOp +pub const GL_ACCUM: GLenum = 0x0100; +pub const GL_LOAD: GLenum = 0x0101; +pub const GL_RETURN: GLenum = 0x0102; +pub const GL_MULT: GLenum = 0x0103; +pub const GL_ADD: GLenum = 0x0104; +//AlphaFunction +pub const GL_NEVER: GLenum = 0x0200; +pub const GL_LESS: GLenum = 0x0201; +pub const GL_EQUAL: GLenum = 0x0202; +pub const GL_LEQUAL: GLenum = 0x0203; +pub const GL_GREATER: GLenum = 0x0204; +pub const GL_NOTEQUAL: GLenum = 0x0205; +pub const GL_GEQUAL: GLenum = 0x0206; +pub const GL_ALWAYS: GLenum = 0x0207; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/guiddef.rs b/bash-5.1/vendor/winapi-0.2.8/src/guiddef.rs new file mode 100644 index 0000000..8b436cd --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/guiddef.rs @@ -0,0 +1,20 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +STRUCT!{struct GUID { + Data1: ::c_ulong, + Data2: ::c_ushort, + Data3: ::c_ushort, + Data4: [::c_uchar; 8], +}} +pub type LPGUID = *mut GUID; +pub type LPCGUID = *const GUID; +pub type IID = GUID; +pub type LPIID = *mut IID; +pub type CLSID = GUID; +pub type LPCLSID = *mut CLSID; +pub type FMTID = GUID; +pub type LPFMTID = *mut FMTID; +pub type REFGUID = *const GUID; +pub type REFIID = *const IID; +pub type REFCLSID = *const IID; +pub type REFFMTID = *const IID; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/heapapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/heapapi.rs new file mode 100644 index 0000000..6f631c5 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/heapapi.rs @@ -0,0 +1,12 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-heap-l1 +STRUCT!{struct HEAP_SUMMARY { + cb: ::DWORD, + cbAllocated: ::SIZE_T, + cbCommitted: ::SIZE_T, + cbReserved: ::SIZE_T, + cbMaxReserve: ::SIZE_T, +}} +pub type PHEAP_SUMMARY = *mut HEAP_SUMMARY; +pub type LPHEAP_SUMMARY = PHEAP_SUMMARY; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/hidclass.rs b/bash-5.1/vendor/winapi-0.2.8/src/hidclass.rs new file mode 100644 index 0000000..0851d5f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/hidclass.rs @@ -0,0 +1,56 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License <LICENSE.md> +DEFINE_GUID!{GUID_DEVINTERFACE_HID, 0x4D1E55B2, 0xF16F, 0x11CF, + 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} +pub const GUID_CLASS_INPUT: ::GUID = GUID_DEVINTERFACE_HID; +DEFINE_GUID!{GUID_HID_INTERFACE_NOTIFY, 0x2c4e2e88, 0x25e6, 0x4c33, 0x88, 0x2f, 0x3d, 0x82, 0xe6, 0x07, 0x36, 0x81} +DEFINE_GUID!{GUID_HID_INTERFACE_HIDPARSE, 0xf5c315a5, 0x69ac, 0x4bc2, 0x92, 0x79, 0xd0, 0xb6, 0x45, 0x76, 0xf4, 0x4b} +// FIXME devpropkey stuff +pub const HID_REVISION: ::DWORD = 0x00000001; +pub const IOCTL_HID_GET_DRIVER_CONFIG: ::DWORD = HID_BUFFER_CTL_CODE!(100); +pub const IOCTL_HID_SET_DRIVER_CONFIG: ::DWORD = HID_BUFFER_CTL_CODE!(101); +pub const IOCTL_HID_GET_POLL_FREQUENCY_MSEC: ::DWORD = HID_BUFFER_CTL_CODE!(102); +pub const IOCTL_HID_SET_POLL_FREQUENCY_MSEC: ::DWORD = HID_BUFFER_CTL_CODE!(103); +pub const IOCTL_GET_NUM_DEVICE_INPUT_BUFFERS: ::DWORD = HID_BUFFER_CTL_CODE!(104); +pub const IOCTL_SET_NUM_DEVICE_INPUT_BUFFERS: ::DWORD = HID_BUFFER_CTL_CODE!(105); +pub const IOCTL_HID_GET_COLLECTION_INFORMATION: ::DWORD = HID_BUFFER_CTL_CODE!(106); +pub const IOCTL_HID_ENABLE_WAKE_ON_SX: ::DWORD = HID_BUFFER_CTL_CODE!(107); +pub const IOCTL_HID_SET_S0_IDLE_TIMEOUT: ::DWORD = HID_BUFFER_CTL_CODE!(108); +pub const IOCTL_HID_GET_COLLECTION_DESCRIPTOR: ::DWORD = HID_CTL_CODE!(100); +pub const IOCTL_HID_FLUSH_QUEUE: ::DWORD = HID_CTL_CODE!(101); +pub const IOCTL_HID_SET_FEATURE: ::DWORD = HID_IN_CTL_CODE!(100); +pub const IOCTL_HID_SET_OUTPUT_REPORT: ::DWORD = HID_IN_CTL_CODE!(101); +pub const IOCTL_HID_GET_FEATURE: ::DWORD = HID_OUT_CTL_CODE!(100); +pub const IOCTL_GET_PHYSICAL_DESCRIPTOR: ::DWORD = HID_OUT_CTL_CODE!(102); +pub const IOCTL_HID_GET_HARDWARE_ID: ::DWORD = HID_OUT_CTL_CODE!(103); +pub const IOCTL_HID_GET_INPUT_REPORT: ::DWORD = HID_OUT_CTL_CODE!(104); +pub const IOCTL_HID_GET_OUTPUT_REPORT: ::DWORD = HID_OUT_CTL_CODE!(105); +pub const IOCTL_HID_GET_MANUFACTURER_STRING: ::DWORD = HID_OUT_CTL_CODE!(110); +pub const IOCTL_HID_GET_PRODUCT_STRING: ::DWORD = HID_OUT_CTL_CODE!(111); +pub const IOCTL_HID_GET_SERIALNUMBER_STRING: ::DWORD = HID_OUT_CTL_CODE!(112); +pub const IOCTL_HID_GET_INDEXED_STRING: ::DWORD = HID_OUT_CTL_CODE!(120); +pub const IOCTL_HID_GET_MS_GENRE_DESCRIPTOR: ::DWORD = HID_OUT_CTL_CODE!(121); +pub const IOCTL_HID_ENABLE_SECURE_READ: ::DWORD = HID_CTL_CODE!(130); +pub const IOCTL_HID_DISABLE_SECURE_READ: ::DWORD = HID_CTL_CODE!(131); +pub const IOCTL_HID_DEVICERESET_NOTIFICATION: ::DWORD = HID_CTL_CODE!(140); +STRUCT!{struct HID_XFER_PACKET { + reportBuffer: ::PUCHAR, + reportBufferLen: ::ULONG, + reportId: ::UCHAR, +}} +pub type PHID_XFER_PACKET = *mut HID_XFER_PACKET; +//FIXME Stuff for NT_INCLUDED +STRUCT!{struct HID_COLLECTION_INFORMATION { + DescriptorSize: ::ULONG, + Polled: ::BOOLEAN, + Reserved1: [::UCHAR; 1], + VendorID: ::USHORT, + ProductID: ::USHORT, + VersionNumber: ::USHORT, +}} +pub type PHID_COLLECTION_INFORMATION = *mut HID_COLLECTION_INFORMATION; +STRUCT!{struct HID_DRIVER_CONFIG { + Size: ::ULONG, + RingBufferSize: ::ULONG, +}} +pub type PHID_DRIVER_CONFIG = *mut HID_DRIVER_CONFIG; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/hidpi.rs b/bash-5.1/vendor/winapi-0.2.8/src/hidpi.rs new file mode 100644 index 0000000..b2321ea --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/hidpi.rs @@ -0,0 +1,182 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License <LICENSE.md> +pub const HIDP_LINK_COLLECTION_ROOT: ::USHORT = -1i16 as u16; +pub const HIDP_LINK_COLLECTION_UNSPECIFIED: ::USHORT = 0; +ENUM!{enum HIDP_REPORT_TYPE { + HidP_Input, + HidP_Output, + HidP_Feature, +}} +STRUCT!{struct USAGE_AND_PAGE { + Usage: ::USAGE, + UsagePage: ::USAGE, +}} +pub type PUSAGE_AND_PAGE = *mut USAGE_AND_PAGE; +STRUCT!{struct HIDP_BUTTON_CAPS { + UsagePage: ::USAGE, + ReportID: ::UCHAR, + IsAlias: ::BOOLEAN, + BitField: ::USHORT, + LinkCollection: ::USHORT, + LinkUsage: ::USAGE, + LinkUsagePage: ::USAGE, + IsRange: ::BOOLEAN, + IsStringRange: ::BOOLEAN, + IsDesignatorRange: ::BOOLEAN, + IsAbsolute: ::BOOLEAN, + Reserved: [::ULONG; 10], + S_un: [u16; 8], +}} +UNION!{HIDP_BUTTON_CAPS, S_un, Range, Range_mut, HIDP_RANGE_STRUCT} +UNION!{HIDP_BUTTON_CAPS, S_un, NotRange, NotRange_mut, HIDP_NOTRANGE_STRUCT} +pub type PHIDP_BUTTON_CAPS = *mut HIDP_BUTTON_CAPS; +STRUCT!{struct HIDP_RANGE_STRUCT { + UsageMin: ::USAGE, + UsageMax: ::USAGE, + StringMin: ::USHORT, + StringMax: ::USHORT, + DesignatorMin: ::USHORT, + DesignatorMax: ::USHORT, + DataIndexMin: ::USHORT, + DataIndexMax: ::USHORT, +}} +STRUCT!{struct HIDP_NOTRANGE_STRUCT { + Usage: ::USAGE, + Reserved1: ::USAGE, + StringIndex: ::USHORT, + Reserved2: ::USHORT, + DesignatorIndex: ::USHORT, + Reserved3: ::USHORT, + DataIndex: ::USHORT, + Reserved4: ::USHORT, +}} +STRUCT!{struct HIDP_VALUE_CAPS { + UsagePage: ::USAGE, + ReportID: ::UCHAR, + IsAlias: ::BOOLEAN, + BitField: ::USHORT, + LinkCollection: ::USHORT, + LinkUsage: ::USAGE, + LinkUsagePage: ::USAGE, + IsRange: ::BOOLEAN, + IsStringRange: ::BOOLEAN, + IsDesignatorRange: ::BOOLEAN, + IsAbsolute: ::BOOLEAN, + HasNull: ::BOOLEAN, + Reserved: ::UCHAR, + BitSize: ::USHORT, + ReportCount: ::USHORT, + Reserved2: [::USHORT; 5], + UnitsExp: ::ULONG, + Units: ::ULONG, + LogicalMin: ::LONG, + LogicalMax: ::LONG, + PhysicalMin: ::LONG, + PhysicalMax: ::LONG, + S_un: [u16; 8], +}} +UNION!{HIDP_VALUE_CAPS, S_un, Range, Range_mut, HIDP_RANGE_STRUCT} +UNION!{HIDP_VALUE_CAPS, S_un, NotRange, NotRange_mut, HIDP_NOTRANGE_STRUCT} +pub type PHIDP_VALUE_CAPS = *mut HIDP_VALUE_CAPS; +STRUCT!{struct HIDP_LINK_COLLECTION_NODE { + LinkUsage: ::USAGE, + LinkUsagePage: ::USAGE, + Parent: ::USHORT, + NumberOfChildren: ::USHORT, + NextSibling: ::USHORT, + FirstChild: ::USHORT, + bit_fields: ::ULONG, + UserContext: ::PVOID, +}} +BITFIELD!{HIDP_LINK_COLLECTION_NODE bit_fields: ::ULONG [ + CollectionType set_CollectionType[0..8], + IsAlias set_IsAlias[8..9], +]} +pub type PHIDP_LINK_COLLECTION_NODE = *mut HIDP_LINK_COLLECTION_NODE; +pub type PHIDP_REPORT_DESCRIPTOR = ::PUCHAR; +pub enum HIDP_PREPARSED_DATA{} +pub type PHIDP_PREPARSED_DATA = *mut HIDP_PREPARSED_DATA; +STRUCT!{struct HIDP_CAPS { + Usage: ::USAGE, + UsagePage: ::USAGE, + InputReportByteLength: ::USHORT, + OutputReportByteLength: ::USHORT, + FeatureReportByteLength: ::USHORT, + Reserved: [::USHORT; 17], + NumberLinkCollectionNodes: ::USHORT, + NumberInputButtonCaps: ::USHORT, + NumberInputValueCaps: ::USHORT, + NumberInputDataIndices: ::USHORT, + NumberOutputButtonCaps: ::USHORT, + NumberOutputValueCaps: ::USHORT, + NumberOutputDataIndices: ::USHORT, + NumberFeatureButtonCaps: ::USHORT, + NumberFeatureValueCaps: ::USHORT, + NumberFeatureDataIndices: ::USHORT, +}} +pub type PHIDP_CAPS = *mut HIDP_CAPS; +STRUCT!{struct HIDP_DATA { + DataIndex: ::USHORT, + Reserved: ::USHORT, + S_un: [u32; 1], +}} +UNION!{HIDP_DATA, S_un, RawValue, RawValue_mut, ::ULONG} +UNION!{HIDP_DATA, S_un, On, On_mut, ::BOOLEAN} +pub type PHIDP_DATA = *mut HIDP_DATA; +STRUCT!{struct HIDP_UNKNOWN_TOKEN { + Token: ::UCHAR, + Reserved: [::UCHAR; 3], + BitField: ::ULONG, +}} +pub type PHIDP_UNKNOWN_TOKEN = *mut HIDP_UNKNOWN_TOKEN; +STRUCT!{struct HIDP_EXTENDED_ATTRIBUTES { + NumGlobalUnknowns: ::UCHAR, + Reserved: [::UCHAR; 3], + GlobalUnknowns: PHIDP_UNKNOWN_TOKEN, + Data: [::ULONG; 1], +}} +pub type PHIDP_EXTENDED_ATTRIBUTES = *mut HIDP_EXTENDED_ATTRIBUTES; +ENUM!{enum HIDP_KEYBOARD_DIRECTION { + HidP_Keyboard_Break, + HidP_Keyboard_Make, +}} +STRUCT!{struct HIDP_KEYBOARD_MODIFIER_STATE { + ul: ::ULONG, +}} +BITFIELD!{HIDP_KEYBOARD_MODIFIER_STATE ul: ::ULONG [ + LeftControl set_LeftControl[0..1], + LeftShift set_LeftShift[1..2], + LeftAlt set_LeftAlt[2..3], + LeftGUI set_LeftGUI[3..4], + RightControl set_RightControl[4..5], + RightShift set_RightShift[5..6], + RightAlt set_RightAlt[6..7], + RigthGUI set_RigthGUI[7..8], + CapsLock set_CapsLock[8..9], + ScollLock set_ScollLock[9..10], + NumLock set_NumLock[10..11], +]} +pub type PHIDP_KEYBOARD_MODIFIER_STATE = *mut HIDP_KEYBOARD_MODIFIER_STATE; +pub type PHIDP_INSERT_SCANCODES = Option<unsafe extern "C" fn( + Context: ::PVOID, NewScanCodes: ::PCHAR, Length: ::ULONG, +) -> ::BOOLEAN>; +pub const HIDP_STATUS_SUCCESS: ::NTSTATUS = HIDP_ERROR_CODES!(0x0, 0); +pub const HIDP_STATUS_NULL: ::NTSTATUS = HIDP_ERROR_CODES!(0x8, 1); +pub const HIDP_STATUS_INVALID_PREPARSED_DATA: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 1); +pub const HIDP_STATUS_INVALID_REPORT_TYPE: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 2); +pub const HIDP_STATUS_INVALID_REPORT_LENGTH: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 3); +pub const HIDP_STATUS_USAGE_NOT_FOUND: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 4); +pub const HIDP_STATUS_VALUE_OUT_OF_RANGE: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 5); +pub const HIDP_STATUS_BAD_LOG_PHY_VALUES: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 6); +pub const HIDP_STATUS_BUFFER_TOO_SMALL: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 7); +pub const HIDP_STATUS_INTERNAL_ERROR: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 8); +pub const HIDP_STATUS_I8042_TRANS_UNKNOWN: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 9); +pub const HIDP_STATUS_INCOMPATIBLE_REPORT_ID: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xA); +pub const HIDP_STATUS_NOT_VALUE_ARRAY: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xB); +pub const HIDP_STATUS_IS_VALUE_ARRAY: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xC); +pub const HIDP_STATUS_DATA_INDEX_NOT_FOUND: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xD); +pub const HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xE); +pub const HIDP_STATUS_BUTTON_NOT_PRESSED: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xF); +pub const HIDP_STATUS_REPORT_DOES_NOT_EXIST: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0x10); +pub const HIDP_STATUS_NOT_IMPLEMENTED: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0x20); +pub const HIDP_STATUS_I8242_TRANS_UNKNOWN: ::NTSTATUS = HIDP_STATUS_I8042_TRANS_UNKNOWN; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/hidsdi.rs b/bash-5.1/vendor/winapi-0.2.8/src/hidsdi.rs new file mode 100644 index 0000000..1b421f0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/hidsdi.rs @@ -0,0 +1,15 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License <LICENSE.md> +STRUCT!{struct HIDD_CONFIGURATION { + cookie: ::PVOID, + size: ::ULONG, + RingBufferSize: ::ULONG, +}} +pub type PHIDD_CONFIGURATION = *mut HIDD_CONFIGURATION; +STRUCT!{struct HIDD_ATTRIBUTES { + Size: ::ULONG, + VendorID: ::USHORT, + ProductID: ::USHORT, + VersionNumber: ::USHORT, +}} +pub type PHIDD_ATTRIBUTES = *mut HIDD_ATTRIBUTES; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/hidusage.rs b/bash-5.1/vendor/winapi-0.2.8/src/hidusage.rs new file mode 100644 index 0000000..4d76509 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/hidusage.rs @@ -0,0 +1,270 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License <LICENSE.md> +pub type USAGE = ::USHORT; +pub type PUSAGE = *mut USAGE; +pub const HID_USAGE_PAGE_UNDEFINED: ::USAGE = 0x00; +pub const HID_USAGE_PAGE_GENERIC: ::USAGE = 0x01; +pub const HID_USAGE_PAGE_SIMULATION: ::USAGE = 0x02; +pub const HID_USAGE_PAGE_VR: ::USAGE = 0x03; +pub const HID_USAGE_PAGE_SPORT: ::USAGE = 0x04; +pub const HID_USAGE_PAGE_GAME: ::USAGE = 0x05; +pub const HID_USAGE_PAGE_KEYBOARD: ::USAGE = 0x07; +pub const HID_USAGE_PAGE_LED: ::USAGE = 0x08; +pub const HID_USAGE_PAGE_BUTTON: ::USAGE = 0x09; +pub const HID_USAGE_PAGE_ORDINAL: ::USAGE = 0x0A; +pub const HID_USAGE_PAGE_TELEPHONY: ::USAGE = 0x0B; +pub const HID_USAGE_PAGE_CONSUMER: ::USAGE = 0x0C; +pub const HID_USAGE_PAGE_DIGITIZER: ::USAGE = 0x0D; +pub const HID_USAGE_PAGE_UNICODE: ::USAGE = 0x10; +pub const HID_USAGE_PAGE_ALPHANUMERIC: ::USAGE = 0x14; +pub const HID_USAGE_PAGE_SENSOR: ::USAGE = 0x20; +pub const HID_USAGE_PAGE_BARCODE_SCANNER: ::USAGE = 0x8C; +pub const HID_USAGE_PAGE_WEIGHING_DEVICE: ::USAGE = 0x8D; +pub const HID_USAGE_PAGE_MAGNETIC_STRIPE_READER: ::USAGE = 0x8E; +pub const HID_USAGE_PAGE_CAMERA_CONTROL: ::USAGE = 0x90; +pub const HID_USAGE_PAGE_MICROSOFT_BLUETOOTH_HANDSFREE: ::USAGE = 0xFFF3; +pub const HID_USAGE_PAGE_VENDOR_DEFINED_BEGIN: ::USAGE = 0xFF00; +pub const HID_USAGE_PAGE_VENDOR_DEFINED_END: ::USAGE = 0xFFFF; +pub const HID_USAGE_GENERIC_POINTER: ::USAGE = 0x01; +pub const HID_USAGE_GENERIC_MOUSE: ::USAGE = 0x02; +pub const HID_USAGE_GENERIC_JOYSTICK: ::USAGE = 0x04; +pub const HID_USAGE_GENERIC_GAMEPAD: ::USAGE = 0x05; +pub const HID_USAGE_GENERIC_KEYBOARD: ::USAGE = 0x06; +pub const HID_USAGE_GENERIC_KEYPAD: ::USAGE = 0x07; +pub const HID_USAGE_GENERIC_PORTABLE_DEVICE_CONTROL: ::USAGE = 0x0D; +pub const HID_USAGE_GENERIC_SYSTEM_CTL: ::USAGE = 0x80; +pub const HID_USAGE_GENERIC_X: ::USAGE = 0x30; +pub const HID_USAGE_GENERIC_Y: ::USAGE = 0x31; +pub const HID_USAGE_GENERIC_Z: ::USAGE = 0x32; +pub const HID_USAGE_GENERIC_RX: ::USAGE = 0x33; +pub const HID_USAGE_GENERIC_RY: ::USAGE = 0x34; +pub const HID_USAGE_GENERIC_RZ: ::USAGE = 0x35; +pub const HID_USAGE_GENERIC_SLIDER: ::USAGE = 0x36; +pub const HID_USAGE_GENERIC_DIAL: ::USAGE = 0x37; +pub const HID_USAGE_GENERIC_WHEEL: ::USAGE = 0x38; +pub const HID_USAGE_GENERIC_HATSWITCH: ::USAGE = 0x39; +pub const HID_USAGE_GENERIC_COUNTED_BUFFER: ::USAGE = 0x3A; +pub const HID_USAGE_GENERIC_BYTE_COUNT: ::USAGE = 0x3B; +pub const HID_USAGE_GENERIC_MOTION_WAKEUP: ::USAGE = 0x3C; +pub const HID_USAGE_GENERIC_VX: ::USAGE = 0x40; +pub const HID_USAGE_GENERIC_VY: ::USAGE = 0x41; +pub const HID_USAGE_GENERIC_VZ: ::USAGE = 0x42; +pub const HID_USAGE_GENERIC_VBRX: ::USAGE = 0x43; +pub const HID_USAGE_GENERIC_VBRY: ::USAGE = 0x44; +pub const HID_USAGE_GENERIC_VBRZ: ::USAGE = 0x45; +pub const HID_USAGE_GENERIC_VNO: ::USAGE = 0x46; +pub const HID_USAGE_GENERIC_RESOLUTION_MULTIPLIER: ::USAGE = 0x48; +pub const HID_USAGE_GENERIC_SYSCTL_POWER: ::USAGE = 0x81; +pub const HID_USAGE_GENERIC_SYSCTL_SLEEP: ::USAGE = 0x82; +pub const HID_USAGE_GENERIC_SYSCTL_WAKE: ::USAGE = 0x83; +pub const HID_USAGE_GENERIC_SYSCTL_CONTEXT_MENU: ::USAGE = 0x84; +pub const HID_USAGE_GENERIC_SYSCTL_MAIN_MENU: ::USAGE = 0x85; +pub const HID_USAGE_GENERIC_SYSCTL_APP_MENU: ::USAGE = 0x86; +pub const HID_USAGE_GENERIC_SYSCTL_HELP_MENU: ::USAGE = 0x87; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_EXIT: ::USAGE = 0x88; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_SELECT: ::USAGE = 0x89; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_RIGHT: ::USAGE = 0x8A; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_LEFT: ::USAGE = 0x8B; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_UP: ::USAGE = 0x8C; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_DOWN: ::USAGE = 0x8D; +pub const HID_USAGE_GENERIC_SYSTEM_DISPLAY_ROTATION_LOCK_BUTTON: ::USAGE = 0xC9; +pub const HID_USAGE_GENERIC_SYSTEM_DISPLAY_ROTATION_LOCK_SLIDER_SWITCH: ::USAGE = 0xCA; +pub const HID_USAGE_GENERIC_CONTROL_ENABLE: ::USAGE = 0xCB; +pub const HID_USAGE_SIMULATION_RUDDER: ::USAGE = 0xBA; +pub const HID_USAGE_SIMULATION_THROTTLE: ::USAGE = 0xBB; +pub const HID_USAGE_KEYBOARD_NOEVENT: ::USAGE = 0x00; +pub const HID_USAGE_KEYBOARD_ROLLOVER: ::USAGE = 0x01; +pub const HID_USAGE_KEYBOARD_POSTFAIL: ::USAGE = 0x02; +pub const HID_USAGE_KEYBOARD_UNDEFINED: ::USAGE = 0x03; +pub const HID_USAGE_KEYBOARD_aA: ::USAGE = 0x04; +pub const HID_USAGE_KEYBOARD_zZ: ::USAGE = 0x1D; +pub const HID_USAGE_KEYBOARD_ONE: ::USAGE = 0x1E; +pub const HID_USAGE_KEYBOARD_ZERO: ::USAGE = 0x27; +pub const HID_USAGE_KEYBOARD_LCTRL: ::USAGE = 0xE0; +pub const HID_USAGE_KEYBOARD_LSHFT: ::USAGE = 0xE1; +pub const HID_USAGE_KEYBOARD_LALT: ::USAGE = 0xE2; +pub const HID_USAGE_KEYBOARD_LGUI: ::USAGE = 0xE3; +pub const HID_USAGE_KEYBOARD_RCTRL: ::USAGE = 0xE4; +pub const HID_USAGE_KEYBOARD_RSHFT: ::USAGE = 0xE5; +pub const HID_USAGE_KEYBOARD_RALT: ::USAGE = 0xE6; +pub const HID_USAGE_KEYBOARD_RGUI: ::USAGE = 0xE7; +pub const HID_USAGE_KEYBOARD_SCROLL_LOCK: ::USAGE = 0x47; +pub const HID_USAGE_KEYBOARD_NUM_LOCK: ::USAGE = 0x53; +pub const HID_USAGE_KEYBOARD_CAPS_LOCK: ::USAGE = 0x39; +pub const HID_USAGE_KEYBOARD_F1: ::USAGE = 0x3A; +pub const HID_USAGE_KEYBOARD_F2: ::USAGE = 0x3B; +pub const HID_USAGE_KEYBOARD_F3: ::USAGE = 0x3C; +pub const HID_USAGE_KEYBOARD_F4: ::USAGE = 0x3D; +pub const HID_USAGE_KEYBOARD_F5: ::USAGE = 0x3E; +pub const HID_USAGE_KEYBOARD_F6: ::USAGE = 0x3F; +pub const HID_USAGE_KEYBOARD_F7: ::USAGE = 0x40; +pub const HID_USAGE_KEYBOARD_F8: ::USAGE = 0x41; +pub const HID_USAGE_KEYBOARD_F9: ::USAGE = 0x42; +pub const HID_USAGE_KEYBOARD_F10: ::USAGE = 0x43; +pub const HID_USAGE_KEYBOARD_F11: ::USAGE = 0x44; +pub const HID_USAGE_KEYBOARD_F12: ::USAGE = 0x45; +pub const HID_USAGE_KEYBOARD_F13: ::USAGE = 0x68; +pub const HID_USAGE_KEYBOARD_F14: ::USAGE = 0x69; +pub const HID_USAGE_KEYBOARD_F15: ::USAGE = 0x6A; +pub const HID_USAGE_KEYBOARD_F16: ::USAGE = 0x6B; +pub const HID_USAGE_KEYBOARD_F17: ::USAGE = 0x6C; +pub const HID_USAGE_KEYBOARD_F18: ::USAGE = 0x6D; +pub const HID_USAGE_KEYBOARD_F19: ::USAGE = 0x6E; +pub const HID_USAGE_KEYBOARD_F20: ::USAGE = 0x6F; +pub const HID_USAGE_KEYBOARD_F21: ::USAGE = 0x70; +pub const HID_USAGE_KEYBOARD_F22: ::USAGE = 0x71; +pub const HID_USAGE_KEYBOARD_F23: ::USAGE = 0x72; +pub const HID_USAGE_KEYBOARD_F24: ::USAGE = 0x73; +pub const HID_USAGE_KEYBOARD_RETURN: ::USAGE = 0x28; +pub const HID_USAGE_KEYBOARD_ESCAPE: ::USAGE = 0x29; +pub const HID_USAGE_KEYBOARD_DELETE: ::USAGE = 0x2A; +pub const HID_USAGE_KEYBOARD_PRINT_SCREEN: ::USAGE = 0x46; +pub const HID_USAGE_KEYBOARD_DELETE_FORWARD: ::USAGE = 0x4C; +pub const HID_USAGE_LED_NUM_LOCK: ::USAGE = 0x01; +pub const HID_USAGE_LED_CAPS_LOCK: ::USAGE = 0x02; +pub const HID_USAGE_LED_SCROLL_LOCK: ::USAGE = 0x03; +pub const HID_USAGE_LED_COMPOSE: ::USAGE = 0x04; +pub const HID_USAGE_LED_KANA: ::USAGE = 0x05; +pub const HID_USAGE_LED_POWER: ::USAGE = 0x06; +pub const HID_USAGE_LED_SHIFT: ::USAGE = 0x07; +pub const HID_USAGE_LED_DO_NOT_DISTURB: ::USAGE = 0x08; +pub const HID_USAGE_LED_MUTE: ::USAGE = 0x09; +pub const HID_USAGE_LED_TONE_ENABLE: ::USAGE = 0x0A; +pub const HID_USAGE_LED_HIGH_CUT_FILTER: ::USAGE = 0x0B; +pub const HID_USAGE_LED_LOW_CUT_FILTER: ::USAGE = 0x0C; +pub const HID_USAGE_LED_EQUALIZER_ENABLE: ::USAGE = 0x0D; +pub const HID_USAGE_LED_SOUND_FIELD_ON: ::USAGE = 0x0E; +pub const HID_USAGE_LED_SURROUND_FIELD_ON: ::USAGE = 0x0F; +pub const HID_USAGE_LED_REPEAT: ::USAGE = 0x10; +pub const HID_USAGE_LED_STEREO: ::USAGE = 0x11; +pub const HID_USAGE_LED_SAMPLING_RATE_DETECT: ::USAGE = 0x12; +pub const HID_USAGE_LED_SPINNING: ::USAGE = 0x13; +pub const HID_USAGE_LED_CAV: ::USAGE = 0x14; +pub const HID_USAGE_LED_CLV: ::USAGE = 0x15; +pub const HID_USAGE_LED_RECORDING_FORMAT_DET: ::USAGE = 0x16; +pub const HID_USAGE_LED_OFF_HOOK: ::USAGE = 0x17; +pub const HID_USAGE_LED_RING: ::USAGE = 0x18; +pub const HID_USAGE_LED_MESSAGE_WAITING: ::USAGE = 0x19; +pub const HID_USAGE_LED_DATA_MODE: ::USAGE = 0x1A; +pub const HID_USAGE_LED_BATTERY_OPERATION: ::USAGE = 0x1B; +pub const HID_USAGE_LED_BATTERY_OK: ::USAGE = 0x1C; +pub const HID_USAGE_LED_BATTERY_LOW: ::USAGE = 0x1D; +pub const HID_USAGE_LED_SPEAKER: ::USAGE = 0x1E; +pub const HID_USAGE_LED_HEAD_SET: ::USAGE = 0x1F; +pub const HID_USAGE_LED_HOLD: ::USAGE = 0x20; +pub const HID_USAGE_LED_MICROPHONE: ::USAGE = 0x21; +pub const HID_USAGE_LED_COVERAGE: ::USAGE = 0x22; +pub const HID_USAGE_LED_NIGHT_MODE: ::USAGE = 0x23; +pub const HID_USAGE_LED_SEND_CALLS: ::USAGE = 0x24; +pub const HID_USAGE_LED_CALL_PICKUP: ::USAGE = 0x25; +pub const HID_USAGE_LED_CONFERENCE: ::USAGE = 0x26; +pub const HID_USAGE_LED_STAND_BY: ::USAGE = 0x27; +pub const HID_USAGE_LED_CAMERA_ON: ::USAGE = 0x28; +pub const HID_USAGE_LED_CAMERA_OFF: ::USAGE = 0x29; +pub const HID_USAGE_LED_ON_LINE: ::USAGE = 0x2A; +pub const HID_USAGE_LED_OFF_LINE: ::USAGE = 0x2B; +pub const HID_USAGE_LED_BUSY: ::USAGE = 0x2C; +pub const HID_USAGE_LED_READY: ::USAGE = 0x2D; +pub const HID_USAGE_LED_PAPER_OUT: ::USAGE = 0x2E; +pub const HID_USAGE_LED_PAPER_JAM: ::USAGE = 0x2F; +pub const HID_USAGE_LED_REMOTE: ::USAGE = 0x30; +pub const HID_USAGE_LED_FORWARD: ::USAGE = 0x31; +pub const HID_USAGE_LED_REVERSE: ::USAGE = 0x32; +pub const HID_USAGE_LED_STOP: ::USAGE = 0x33; +pub const HID_USAGE_LED_REWIND: ::USAGE = 0x34; +pub const HID_USAGE_LED_FAST_FORWARD: ::USAGE = 0x35; +pub const HID_USAGE_LED_PLAY: ::USAGE = 0x36; +pub const HID_USAGE_LED_PAUSE: ::USAGE = 0x37; +pub const HID_USAGE_LED_RECORD: ::USAGE = 0x38; +pub const HID_USAGE_LED_ERROR: ::USAGE = 0x39; +pub const HID_USAGE_LED_SELECTED_INDICATOR: ::USAGE = 0x3A; +pub const HID_USAGE_LED_IN_USE_INDICATOR: ::USAGE = 0x3B; +pub const HID_USAGE_LED_MULTI_MODE_INDICATOR: ::USAGE = 0x3C; +pub const HID_USAGE_LED_INDICATOR_ON: ::USAGE = 0x3D; +pub const HID_USAGE_LED_INDICATOR_FLASH: ::USAGE = 0x3E; +pub const HID_USAGE_LED_INDICATOR_SLOW_BLINK: ::USAGE = 0x3F; +pub const HID_USAGE_LED_INDICATOR_FAST_BLINK: ::USAGE = 0x40; +pub const HID_USAGE_LED_INDICATOR_OFF: ::USAGE = 0x41; +pub const HID_USAGE_LED_FLASH_ON_TIME: ::USAGE = 0x42; +pub const HID_USAGE_LED_SLOW_BLINK_ON_TIME: ::USAGE = 0x43; +pub const HID_USAGE_LED_SLOW_BLINK_OFF_TIME: ::USAGE = 0x44; +pub const HID_USAGE_LED_FAST_BLINK_ON_TIME: ::USAGE = 0x45; +pub const HID_USAGE_LED_FAST_BLINK_OFF_TIME: ::USAGE = 0x46; +pub const HID_USAGE_LED_INDICATOR_COLOR: ::USAGE = 0x47; +pub const HID_USAGE_LED_RED: ::USAGE = 0x48; +pub const HID_USAGE_LED_GREEN: ::USAGE = 0x49; +pub const HID_USAGE_LED_AMBER: ::USAGE = 0x4A; +pub const HID_USAGE_LED_GENERIC_INDICATOR: ::USAGE = 0x4B; +pub const HID_USAGE_TELEPHONY_PHONE: ::USAGE = 0x01; +pub const HID_USAGE_TELEPHONY_ANSWERING_MACHINE: ::USAGE = 0x02; +pub const HID_USAGE_TELEPHONY_MESSAGE_CONTROLS: ::USAGE = 0x03; +pub const HID_USAGE_TELEPHONY_HANDSET: ::USAGE = 0x04; +pub const HID_USAGE_TELEPHONY_HEADSET: ::USAGE = 0x05; +pub const HID_USAGE_TELEPHONY_KEYPAD: ::USAGE = 0x06; +pub const HID_USAGE_TELEPHONY_PROGRAMMABLE_BUTTON: ::USAGE = 0x07; +pub const HID_USAGE_TELEPHONY_REDIAL: ::USAGE = 0x24; +pub const HID_USAGE_TELEPHONY_TRANSFER: ::USAGE = 0x25; +pub const HID_USAGE_TELEPHONY_DROP: ::USAGE = 0x26; +pub const HID_USAGE_TELEPHONY_LINE: ::USAGE = 0x2A; +pub const HID_USAGE_TELEPHONY_RING_ENABLE: ::USAGE = 0x2D; +pub const HID_USAGE_TELEPHONY_SEND: ::USAGE = 0x31; +pub const HID_USAGE_TELEPHONY_KEYPAD_0: ::USAGE = 0xB0; +pub const HID_USAGE_TELEPHONY_KEYPAD_D: ::USAGE = 0xBF; +pub const HID_USAGE_TELEPHONY_HOST_AVAILABLE: ::USAGE = 0xF1; +pub const HID_USAGE_CONSUMERCTRL: ::USAGE = 0x01; +pub const HID_USAGE_CONSUMER_CHANNEL_INCREMENT: ::USAGE = 0x9C; +pub const HID_USAGE_CONSUMER_CHANNEL_DECREMENT: ::USAGE = 0x9D; +pub const HID_USAGE_CONSUMER_PLAY: ::USAGE = 0xB0; +pub const HID_USAGE_CONSUMER_PAUSE: ::USAGE = 0xB1; +pub const HID_USAGE_CONSUMER_RECORD: ::USAGE = 0xB2; +pub const HID_USAGE_CONSUMER_FAST_FORWARD: ::USAGE = 0xB3; +pub const HID_USAGE_CONSUMER_REWIND: ::USAGE = 0xB4; +pub const HID_USAGE_CONSUMER_SCAN_NEXT_TRACK: ::USAGE = 0xB5; +pub const HID_USAGE_CONSUMER_SCAN_PREV_TRACK: ::USAGE = 0xB6; +pub const HID_USAGE_CONSUMER_STOP: ::USAGE = 0xB7; +pub const HID_USAGE_CONSUMER_PLAY_PAUSE: ::USAGE = 0xCD; +pub const HID_USAGE_CONSUMER_VOLUME: ::USAGE = 0xE0; +pub const HID_USAGE_CONSUMER_BALANCE: ::USAGE = 0xE1; +pub const HID_USAGE_CONSUMER_MUTE: ::USAGE = 0xE2; +pub const HID_USAGE_CONSUMER_BASS: ::USAGE = 0xE3; +pub const HID_USAGE_CONSUMER_TREBLE: ::USAGE = 0xE4; +pub const HID_USAGE_CONSUMER_BASS_BOOST: ::USAGE = 0xE5; +pub const HID_USAGE_CONSUMER_SURROUND_MODE: ::USAGE = 0xE6; +pub const HID_USAGE_CONSUMER_LOUDNESS: ::USAGE = 0xE7; +pub const HID_USAGE_CONSUMER_MPX: ::USAGE = 0xE8; +pub const HID_USAGE_CONSUMER_VOLUME_INCREMENT: ::USAGE = 0xE9; +pub const HID_USAGE_CONSUMER_VOLUME_DECREMENT: ::USAGE = 0xEA; +pub const HID_USAGE_CONSUMER_BASS_INCREMENT: ::USAGE = 0x152; +pub const HID_USAGE_CONSUMER_BASS_DECREMENT: ::USAGE = 0x153; +pub const HID_USAGE_CONSUMER_TREBLE_INCREMENT: ::USAGE = 0x154; +pub const HID_USAGE_CONSUMER_TREBLE_DECREMENT: ::USAGE = 0x155; +pub const HID_USAGE_CONSUMER_AL_CONFIGURATION: ::USAGE = 0x183; +pub const HID_USAGE_CONSUMER_AL_EMAIL: ::USAGE = 0x18A; +pub const HID_USAGE_CONSUMER_AL_CALCULATOR: ::USAGE = 0x192; +pub const HID_USAGE_CONSUMER_AL_BROWSER: ::USAGE = 0x194; +pub const HID_USAGE_CONSUMER_AC_SEARCH: ::USAGE = 0x221; +pub const HID_USAGE_CONSUMER_AC_GOTO: ::USAGE = 0x222; +pub const HID_USAGE_CONSUMER_AC_HOME: ::USAGE = 0x223; +pub const HID_USAGE_CONSUMER_AC_BACK: ::USAGE = 0x224; +pub const HID_USAGE_CONSUMER_AC_FORWARD: ::USAGE = 0x225; +pub const HID_USAGE_CONSUMER_AC_STOP: ::USAGE = 0x226; +pub const HID_USAGE_CONSUMER_AC_REFRESH: ::USAGE = 0x227; +pub const HID_USAGE_CONSUMER_AC_PREVIOUS: ::USAGE = 0x228; +pub const HID_USAGE_CONSUMER_AC_NEXT: ::USAGE = 0x229; +pub const HID_USAGE_CONSUMER_AC_BOOKMARKS: ::USAGE = 0x22A; +pub const HID_USAGE_CONSUMER_AC_PAN: ::USAGE = 0x238; +pub const HID_USAGE_CONSUMER_EXTENDED_KEYBOARD_ATTRIBUTES_COLLECTION: ::USAGE = 0x2C0; +pub const HID_USAGE_CONSUMER_KEYBOARD_FORM_FACTOR: ::USAGE = 0x2C1; +pub const HID_USAGE_CONSUMER_KEYBOARD_KEY_TYPE: ::USAGE = 0x2C2; +pub const HID_USAGE_CONSUMER_KEYBOARD_PHYSICAL_LAYOUT: ::USAGE = 0x2C3; +pub const HID_USAGE_CONSUMER_VENDOR_SPECIFIC_KEYBOARD_PHYSICAL_LAYOUT: ::USAGE = 0x2C4; +pub const HID_USAGE_CONSUMER_KEYBOARD_IETF_LANGUAGE_TAG_INDEX: ::USAGE = 0x2C5; +pub const HID_USAGE_CONSUMER_IMPLEMENTED_KEYBOARD_INPUT_ASSIST_CONTROLS: ::USAGE = 0x2C6; +pub const HID_USAGE_DIGITIZER_PEN: ::USAGE = 0x02; +pub const HID_USAGE_DIGITIZER_IN_RANGE: ::USAGE = 0x32; +pub const HID_USAGE_DIGITIZER_TIP_SWITCH: ::USAGE = 0x42; +pub const HID_USAGE_DIGITIZER_BARREL_SWITCH: ::USAGE = 0x44; +pub const HID_USAGE_CAMERA_AUTO_FOCUS: ::USAGE = 0x20; +pub const HID_USAGE_CAMERA_SHUTTER: ::USAGE = 0x21; +pub const HID_USAGE_MS_BTH_HF_DIALNUMBER: ::USAGE = 0x21; +pub const HID_USAGE_MS_BTH_HF_DIALMEMORY: ::USAGE = 0x22; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/hstring.rs b/bash-5.1/vendor/winapi-0.2.8/src/hstring.rs new file mode 100644 index 0000000..01cfc6d --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/hstring.rs @@ -0,0 +1,16 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This interface definition contains typedefs for Windows Runtime data types. +DECLARE_HANDLE!(HSTRING, HSTRING__); +#[cfg(target_arch = "x86_64")] +STRUCT!{struct HSTRING_HEADER { + Reserved: [::PVOID; 0], // For alignment + Reserved2: [::c_char; 24], +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct HSTRING_HEADER { + Reserved: [::PVOID; 0], // For alignment + Reserved2: [::c_char; 20], +}} +UNION!(HSTRING_HEADER, Reserved2, Reserved1, Reserved1_mut, ::PVOID); +DECLARE_HANDLE!(HSTRING_BUFFER, HSTRING_BUFFER__); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/http.rs b/bash-5.1/vendor/winapi-0.2.8/src/http.rs new file mode 100644 index 0000000..b0020f9 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/http.rs @@ -0,0 +1,828 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! HTTP API specification +pub const HTTP_INITIALIZE_SERVER: ::ULONG = 0x00000001; +pub const HTTP_INITIALIZE_CONFIG: ::ULONG = 0x00000002; +pub const HTTP_DEMAND_CBT: ::ULONG = 0x00000004; +ENUM!{enum HTTP_SERVER_PROPERTY { + HttpServerAuthenticationProperty, + HttpServerLoggingProperty, + HttpServerQosProperty, + HttpServerTimeoutsProperty, + HttpServerQueueLengthProperty, + HttpServerStateProperty, + HttpServer503VerbosityProperty, + HttpServerBindingProperty, + HttpServerExtendedAuthenticationProperty, + HttpServerListenEndpointProperty, + HttpServerChannelBindProperty, + HttpServerProtectionLevelProperty, +}} +pub type PHTTP_SERVER_PROPERTY = *mut HTTP_SERVER_PROPERTY; +STRUCT!{struct HTTP_PROPERTY_FLAGS { + BitFields: ::ULONG, +}} +BITFIELD!(HTTP_PROPERTY_FLAGS BitFields: ::ULONG [ + Present set_Present[0..1], +]); +pub type PHTTP_PROPERTY_FLAGS = *mut HTTP_PROPERTY_FLAGS; +ENUM!{enum HTTP_ENABLED_STATE { + HttpEnabledStateActive, + HttpEnabledStateInactive, +}} +pub type PHTTP_ENABLED_STATE = *mut HTTP_ENABLED_STATE; +STRUCT!{struct HTTP_STATE_INFO { + Flags: HTTP_PROPERTY_FLAGS, + State: HTTP_ENABLED_STATE, +}} +pub type PHTTP_STATE_INFO = *mut HTTP_STATE_INFO; +ENUM!{enum HTTP_503_RESPONSE_VERBOSITY { + Http503ResponseVerbosityBasic, + Http503ResponseVerbosityLimited, + Http503ResponseVerbosityFull, +}} +pub type PHTTP_503_RESPONSE_VERBOSITY = *mut HTTP_503_RESPONSE_VERBOSITY; +ENUM!{enum HTTP_QOS_SETTING_TYPE { + HttpQosSettingTypeBandwidth, + HttpQosSettingTypeConnectionLimit, + HttpQosSettingTypeFlowRate, +}} +pub type PHTTP_QOS_SETTING_TYPE = *mut HTTP_QOS_SETTING_TYPE; +STRUCT!{struct HTTP_QOS_SETTING_INFO { + QosType: HTTP_QOS_SETTING_TYPE, + QosSetting: ::PVOID, +}} +pub type PHTTP_QOS_SETTING_INFO = *mut HTTP_QOS_SETTING_INFO; +STRUCT!{struct HTTP_CONNECTION_LIMIT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + MaxConnections: ::ULONG, +}} +pub type PHTTP_CONNECTION_LIMIT_INFO = *mut HTTP_CONNECTION_LIMIT_INFO; +STRUCT!{struct HTTP_BANDWIDTH_LIMIT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + MaxBandwidth: ::ULONG, +}} +pub type PHTTP_BANDWIDTH_LIMIT_INFO = *mut HTTP_BANDWIDTH_LIMIT_INFO; +STRUCT!{struct HTTP_FLOWRATE_INFO { + Flags: HTTP_PROPERTY_FLAGS, + MaxBandwidth: ::ULONG, + MaxPeakBandwidth: ::ULONG, + BurstSize: ::ULONG, +}} +pub type PHTTP_FLOWRATE_INFO = *mut HTTP_FLOWRATE_INFO; +pub const HTTP_MIN_ALLOWED_BANDWIDTH_THROTTLING_RATE: ::ULONG = 1024; +pub const HTTP_LIMIT_INFINITE: ::ULONG = !0; +ENUM!{enum HTTP_SERVICE_CONFIG_TIMEOUT_KEY { + IdleConnectionTimeout = 0, + HeaderWaitTimeout, +}} +pub type PHTTP_SERVICE_CONFIG_TIMEOUT_KEY = *mut HTTP_SERVICE_CONFIG_TIMEOUT_KEY; +pub type HTTP_SERVICE_CONFIG_TIMEOUT_PARAM = ::USHORT; +pub type PHTTP_SERVICE_CONFIG_TIMEOUT_PARAM = *mut ::USHORT; +STRUCT!{struct HTTP_SERVICE_CONFIG_TIMEOUT_SET { + KeyDesc: HTTP_SERVICE_CONFIG_TIMEOUT_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_TIMEOUT_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_TIMEOUT_SET = *mut HTTP_SERVICE_CONFIG_TIMEOUT_SET; +STRUCT!{struct HTTP_TIMEOUT_LIMIT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + EntityBody: ::USHORT, + DrainEntityBody: ::USHORT, + RequestQueue: ::USHORT, + IdleConnection: ::USHORT, + HeaderWait: ::USHORT, + MinSendRate: ::ULONG, +}} +pub type PHTTP_TIMEOUT_LIMIT_INFO = *mut HTTP_TIMEOUT_LIMIT_INFO; +STRUCT!{struct HTTP_LISTEN_ENDPOINT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + EnableSharing: ::BOOLEAN, +}} +pub type PHTTP_LISTEN_ENDPOINT_INFO = *mut HTTP_LISTEN_ENDPOINT_INFO; +STRUCT!{struct HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS { + DomainNameLength: ::USHORT, + DomainName: ::PWSTR, + RealmLength: ::USHORT, + Realm: ::PWSTR, +}} +pub type PHTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS = *mut HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS; +STRUCT!{struct HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS { + RealmLength: ::USHORT, + Realm: ::PWSTR, +}} +pub type PHTTP_SERVER_AUTHENTICATION_BASIC_PARAMS = *mut HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS; +pub const HTTP_AUTH_ENABLE_BASIC: ::ULONG = 0x00000001; +pub const HTTP_AUTH_ENABLE_DIGEST: ::ULONG = 0x00000002; +pub const HTTP_AUTH_ENABLE_NTLM: ::ULONG = 0x00000004; +pub const HTTP_AUTH_ENABLE_NEGOTIATE: ::ULONG = 0x00000008; +pub const HTTP_AUTH_ENABLE_KERBEROS: ::ULONG = 0x00000010; +pub const HTTP_AUTH_ENABLE_ALL: ::ULONG = HTTP_AUTH_ENABLE_BASIC | HTTP_AUTH_ENABLE_DIGEST | + HTTP_AUTH_ENABLE_NTLM | HTTP_AUTH_ENABLE_NEGOTIATE | HTTP_AUTH_ENABLE_KERBEROS; +pub const HTTP_AUTH_EX_FLAG_ENABLE_KERBEROS_CREDENTIAL_CACHING: ::UCHAR = 0x01; +pub const HTTP_AUTH_EX_FLAG_CAPTURE_CREDENTIAL: ::UCHAR = 0x02; +STRUCT!{struct HTTP_SERVER_AUTHENTICATION_INFO { + Flags: HTTP_PROPERTY_FLAGS, + AuthSchemes: ::ULONG, + ReceiveMutualAuth: ::BOOLEAN, + ReceiveContextHandle: ::BOOLEAN, + DisableNTLMCredentialCaching: ::BOOLEAN, + ExFlags: ::UCHAR, + DigestParams: HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS, + BasicParams: HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS, +}} +pub type PHTTP_SERVER_AUTHENTICATION_INFO = *mut HTTP_SERVER_AUTHENTICATION_INFO; +ENUM!{enum HTTP_SERVICE_BINDING_TYPE { + HttpServiceBindingTypeNone = 0, + HttpServiceBindingTypeW, + HttpServiceBindingTypeA, +}} +STRUCT!{struct HTTP_SERVICE_BINDING_BASE { + Type: HTTP_SERVICE_BINDING_TYPE, +}} +pub type PHTTP_SERVICE_BINDING_BASE = *mut HTTP_SERVICE_BINDING_BASE; +STRUCT!{struct HTTP_SERVICE_BINDING_A { + Base: HTTP_SERVICE_BINDING_BASE, + Buffer: ::PCHAR, + BufferSize: ::ULONG, +}} +pub type PHTTP_SERVICE_BINDING_A = *mut HTTP_SERVICE_BINDING_A; +STRUCT!{struct HTTP_SERVICE_BINDING_W { + Base: HTTP_SERVICE_BINDING_BASE, + Buffer: ::PWCHAR, + BufferSize: ::ULONG, +}} +pub type PHTTP_SERVICE_BINDING_W = *mut HTTP_SERVICE_BINDING_W; +ENUM!{enum HTTP_AUTHENTICATION_HARDENING_LEVELS { + HttpAuthenticationHardeningLegacy = 0, + HttpAuthenticationHardeningMedium, + HttpAuthenticationHardeningStrict, +}} +pub const HTTP_CHANNEL_BIND_PROXY: ::ULONG = 0x1; +pub const HTTP_CHANNEL_BIND_PROXY_COHOSTING: ::ULONG = 0x20; +pub const HTTP_CHANNEL_BIND_NO_SERVICE_NAME_CHECK: ::ULONG = 0x2; +pub const HTTP_CHANNEL_BIND_DOTLESS_SERVICE: ::ULONG = 0x4; +pub const HTTP_CHANNEL_BIND_SECURE_CHANNEL_TOKEN: ::ULONG = 0x8; +pub const HTTP_CHANNEL_BIND_CLIENT_SERVICE: ::ULONG = 0x10; +STRUCT!{struct HTTP_CHANNEL_BIND_INFO { + Hardening: HTTP_AUTHENTICATION_HARDENING_LEVELS, + Flags: ::ULONG, + ServiceNames: *mut PHTTP_SERVICE_BINDING_BASE, + NumberOfServiceNames: ::ULONG, +}} +pub type PHTTP_CHANNEL_BIND_INFO = *mut HTTP_CHANNEL_BIND_INFO; +STRUCT!{struct HTTP_REQUEST_CHANNEL_BIND_STATUS { + ServiceName: PHTTP_SERVICE_BINDING_BASE, + ChannelToken: ::PUCHAR, + ChannelTokenSize: ::ULONG, + Flags: ::ULONG, +}} +pub type PHTTP_REQUEST_CHANNEL_BIND_STATUS = *mut HTTP_REQUEST_CHANNEL_BIND_STATUS; +pub const HTTP_LOG_FIELD_DATE: ::ULONG = 0x00000001; +pub const HTTP_LOG_FIELD_TIME: ::ULONG = 0x00000002; +pub const HTTP_LOG_FIELD_CLIENT_IP: ::ULONG = 0x00000004; +pub const HTTP_LOG_FIELD_USER_NAME: ::ULONG = 0x00000008; +pub const HTTP_LOG_FIELD_SITE_NAME: ::ULONG = 0x00000010; +pub const HTTP_LOG_FIELD_COMPUTER_NAME: ::ULONG = 0x00000020; +pub const HTTP_LOG_FIELD_SERVER_IP: ::ULONG = 0x00000040; +pub const HTTP_LOG_FIELD_METHOD: ::ULONG = 0x00000080; +pub const HTTP_LOG_FIELD_URI_STEM: ::ULONG = 0x00000100; +pub const HTTP_LOG_FIELD_URI_QUERY: ::ULONG = 0x00000200; +pub const HTTP_LOG_FIELD_STATUS: ::ULONG = 0x00000400; +pub const HTTP_LOG_FIELD_WIN32_STATUS: ::ULONG = 0x00000800; +pub const HTTP_LOG_FIELD_BYTES_SENT: ::ULONG = 0x00001000; +pub const HTTP_LOG_FIELD_BYTES_RECV: ::ULONG = 0x00002000; +pub const HTTP_LOG_FIELD_TIME_TAKEN: ::ULONG = 0x00004000; +pub const HTTP_LOG_FIELD_SERVER_PORT: ::ULONG = 0x00008000; +pub const HTTP_LOG_FIELD_USER_AGENT: ::ULONG = 0x00010000; +pub const HTTP_LOG_FIELD_COOKIE: ::ULONG = 0x00020000; +pub const HTTP_LOG_FIELD_REFERER: ::ULONG = 0x00040000; +pub const HTTP_LOG_FIELD_VERSION: ::ULONG = 0x00080000; +pub const HTTP_LOG_FIELD_HOST: ::ULONG = 0x00100000; +pub const HTTP_LOG_FIELD_SUB_STATUS: ::ULONG = 0x00200000; +pub const HTTP_LOG_FIELD_CLIENT_PORT: ::ULONG = 0x00400000; +pub const HTTP_LOG_FIELD_URI: ::ULONG = 0x00800000; +pub const HTTP_LOG_FIELD_SITE_ID: ::ULONG = 0x01000000; +pub const HTTP_LOG_FIELD_REASON: ::ULONG = 0x02000000; +pub const HTTP_LOG_FIELD_QUEUE_NAME: ::ULONG = 0x04000000; +ENUM!{enum HTTP_LOGGING_TYPE { + HttpLoggingTypeW3C, + HttpLoggingTypeIIS, + HttpLoggingTypeNCSA, + HttpLoggingTypeRaw, +}} +ENUM!{enum HTTP_LOGGING_ROLLOVER_TYPE { + HttpLoggingRolloverSize, + HttpLoggingRolloverDaily, + HttpLoggingRolloverWeekly, + HttpLoggingRolloverMonthly, + HttpLoggingRolloverHourly, +}} +pub const HTTP_MIN_ALLOWED_LOG_FILE_ROLLOVER_SIZE: ::ULONG = (1 * 1024 * 1024) as ::ULONG; +pub const HTTP_LOGGING_FLAG_LOCAL_TIME_ROLLOVER: ::ULONG = 0x00000001; +pub const HTTP_LOGGING_FLAG_USE_UTF8_CONVERSION: ::ULONG = 0x00000002; +pub const HTTP_LOGGING_FLAG_LOG_ERRORS_ONLY: ::ULONG = 0x00000004; +pub const HTTP_LOGGING_FLAG_LOG_SUCCESS_ONLY: ::ULONG = 0x00000008; +STRUCT!{struct HTTP_LOGGING_INFO { + Flags: HTTP_PROPERTY_FLAGS, + LoggingFlags: ::ULONG, + SoftwareName: ::PCWSTR, + SoftwareNameLength: ::USHORT, + DirectoryNameLength: ::USHORT, + DirectoryName: ::PCWSTR, + Format: HTTP_LOGGING_TYPE, + Fields: ::ULONG, + pExtFields: ::PVOID, + NumOfExtFields: ::USHORT, + MaxRecordSize: ::USHORT, + RolloverType: HTTP_LOGGING_ROLLOVER_TYPE, + RolloverSize: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, +}} +pub type PHTTP_LOGGING_INFO = *mut HTTP_LOGGING_INFO; +STRUCT!{struct HTTP_BINDING_INFO { + Flags: HTTP_PROPERTY_FLAGS, + RequestQueueHandle: ::HANDLE, +}} +pub type PHTTP_BINDING_INFO = *mut HTTP_BINDING_INFO; +ENUM!{enum HTTP_PROTECTION_LEVEL_TYPE { + HttpProtectionLevelUnrestricted, + HttpProtectionLevelEdgeRestricted, + HttpProtectionLevelRestricted, +}} +pub type PHTTP_PROTECTION_LEVEL_TYPE = *mut HTTP_PROTECTION_LEVEL_TYPE; +STRUCT!{struct HTTP_PROTECTION_LEVEL_INFO { + Flags: HTTP_PROPERTY_FLAGS, + Level: HTTP_PROTECTION_LEVEL_TYPE, +}} +pub type PHTTP_PROTECTION_LEVEL_INFO = *mut HTTP_PROTECTION_LEVEL_INFO; +pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING: ::ULONG = 0x00000001; +pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_CONTROLLER: ::ULONG = 0x00000002; +pub const HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY: ::ULONG = 0x00000001; +pub const HTTP_RECEIVE_REQUEST_FLAG_FLUSH_BODY: ::ULONG = 0x00000002; +pub const HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER: ::ULONG = 0x00000001; +pub const HTTP_SEND_RESPONSE_FLAG_DISCONNECT: ::ULONG = 0x00000001; +pub const HTTP_SEND_RESPONSE_FLAG_MORE_DATA: ::ULONG = 0x00000002; +pub const HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA: ::ULONG = 0x00000004; +pub const HTTP_SEND_RESPONSE_FLAG_ENABLE_NAGLING: ::ULONG = 0x00000008; +pub const HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES: ::ULONG = 0x00000020; +pub const HTTP_SEND_RESPONSE_FLAG_OPAQUE: ::ULONG = 0x00000040; +pub const HTTP_FLUSH_RESPONSE_FLAG_RECURSIVE: ::ULONG = 0x00000001; +pub type HTTP_OPAQUE_ID = ::ULONGLONG; +pub type PHTTP_OPAQUE_ID = *mut ::ULONGLONG; +pub type HTTP_REQUEST_ID = HTTP_OPAQUE_ID; +pub type PHTTP_REQUEST_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_CONNECTION_ID = HTTP_OPAQUE_ID; +pub type PHTTP_CONNECTION_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_RAW_CONNECTION_ID = HTTP_OPAQUE_ID; +pub type PHTTP_RAW_CONNECTION_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_URL_GROUP_ID = HTTP_OPAQUE_ID; +pub type PHTTP_URL_GROUP_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_SERVER_SESSION_ID = HTTP_OPAQUE_ID; +pub type PHTTP_SERVER_SESSION_ID = *mut HTTP_OPAQUE_ID; +pub const HTTP_BYTE_RANGE_TO_EOF: ::ULONGLONG = !0; +STRUCT!{struct HTTP_BYTE_RANGE { + StartingOffset: ::ULARGE_INTEGER, + Length: ::ULARGE_INTEGER, +}} +pub type PHTTP_BYTE_RANGE = *mut HTTP_BYTE_RANGE; +STRUCT!{struct HTTP_VERSION { + MajorVersion: ::USHORT, + MinorVersion: ::USHORT, +}} +pub type PHTTP_VERSION = *mut HTTP_VERSION; +pub const HTTP_VERSION_UNKNOWN: HTTP_VERSION = HTTP_VERSION { MajorVersion: 0, MinorVersion: 0 }; +pub const HTTP_VERSION_0_9: HTTP_VERSION = HTTP_VERSION { MajorVersion: 0, MinorVersion: 9 }; +pub const HTTP_VERSION_1_0: HTTP_VERSION = HTTP_VERSION { MajorVersion: 1, MinorVersion: 0 }; +pub const HTTP_VERSION_1_1: HTTP_VERSION = HTTP_VERSION { MajorVersion: 1, MinorVersion: 1 }; +#[inline] #[allow(dead_code)] +pub fn HTTP_SET_VERSION(mut version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) { + version.MajorVersion = major; + version.MinorVersion = minor; +} +#[inline] #[allow(dead_code)] +pub fn HTTP_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.MajorVersion == major && version.MinorVersion == minor +} +#[inline] #[allow(dead_code)] +pub fn HTTP_GREATER_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.MajorVersion > major || (version.MajorVersion == major && version.MinorVersion > minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_LESS_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.MajorVersion < major || (version.MajorVersion == major && version.MinorVersion < minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_NOT_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + !HTTP_EQUAL_VERSION(version, major, minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_GREATER_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + !HTTP_LESS_VERSION(version, major, minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_LESS_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + !HTTP_GREATER_VERSION(version, major, minor) +} +ENUM!{enum HTTP_VERB { + HttpVerbUnparsed, + HttpVerbUnknown, + HttpVerbInvalid, + HttpVerbOPTIONS, + HttpVerbGET, + HttpVerbHEAD, + HttpVerbPOST, + HttpVerbPUT, + HttpVerbDELETE, + HttpVerbTRACE, + HttpVerbCONNECT, + HttpVerbTRACK, + HttpVerbMOVE, + HttpVerbCOPY, + HttpVerbPROPFIND, + HttpVerbPROPPATCH, + HttpVerbMKCOL, + HttpVerbLOCK, + HttpVerbUNLOCK, + HttpVerbSEARCH, + HttpVerbMaximum, +}} +pub type PHTTP_VERB = *mut HTTP_VERB; +ENUM!{enum HTTP_HEADER_ID { + HttpHeaderCacheControl = 0, + HttpHeaderConnection = 1, + HttpHeaderDate = 2, + HttpHeaderKeepAlive = 3, + HttpHeaderPragma = 4, + HttpHeaderTrailer = 5, + HttpHeaderTransferEncoding = 6, + HttpHeaderUpgrade = 7, + HttpHeaderVia = 8, + HttpHeaderWarning = 9, + HttpHeaderAllow = 10, + HttpHeaderContentLength = 11, + HttpHeaderContentType = 12, + HttpHeaderContentEncoding = 13, + HttpHeaderContentLanguage = 14, + HttpHeaderContentLocation = 15, + HttpHeaderContentMd5 = 16, + HttpHeaderContentRange = 17, + HttpHeaderExpires = 18, + HttpHeaderLastModified = 19, + HttpHeaderAccept = 20, + HttpHeaderAcceptCharset = 21, + HttpHeaderAcceptEncoding = 22, + HttpHeaderAcceptLanguage = 23, + HttpHeaderAuthorization = 24, + HttpHeaderCookie = 25, + HttpHeaderExpect = 26, + HttpHeaderFrom = 27, + HttpHeaderHost = 28, + HttpHeaderIfMatch = 29, + HttpHeaderIfModifiedSince = 30, + HttpHeaderIfNoneMatch = 31, + HttpHeaderIfRange = 32, + HttpHeaderIfUnmodifiedSince = 33, + HttpHeaderMaxForwards = 34, + HttpHeaderProxyAuthorization = 35, + HttpHeaderReferer = 36, + HttpHeaderRange = 37, + HttpHeaderTe = 38, + HttpHeaderTranslate = 39, + HttpHeaderUserAgent = 40, + HttpHeaderRequestMaximum = 41, + HttpHeaderAcceptRanges = 20, + HttpHeaderAge = 21, + HttpHeaderEtag = 22, + HttpHeaderLocation = 23, + HttpHeaderProxyAuthenticate = 24, + HttpHeaderRetryAfter = 25, + HttpHeaderServer = 26, + HttpHeaderSetCookie = 27, + HttpHeaderVary = 28, + HttpHeaderWwwAuthenticate = 29, + HttpHeaderResponseMaximum = 30, + HttpHeaderMaximum = 41, +}} +pub type PHTTP_HEADER_ID = *mut HTTP_HEADER_ID; +STRUCT!{struct HTTP_KNOWN_HEADER { + RawValueLength: ::USHORT, + pRawValue: ::PCSTR, +}} +pub type PHTTP_KNOWN_HEADER = *mut HTTP_KNOWN_HEADER; +STRUCT!{struct HTTP_UNKNOWN_HEADER { + NameLength: ::USHORT, + RawValueLength: ::USHORT, + pName: ::PCSTR, + pRawValue: ::PCSTR, +}} +pub type PHTTP_UNKNOWN_HEADER = *mut HTTP_UNKNOWN_HEADER; +ENUM!{enum HTTP_LOG_DATA_TYPE { + HttpLogDataTypeFields = 0, +}} +pub type PHTTP_LOG_DATA_TYPE = *mut HTTP_LOG_DATA_TYPE; +STRUCT!{struct HTTP_LOG_DATA { + Type: HTTP_LOG_DATA_TYPE, +}} +pub type PHTTP_LOG_DATA = *mut HTTP_LOG_DATA; +STRUCT!{struct HTTP_LOG_FIELDS_DATA { + Base: HTTP_LOG_DATA, + UserNameLength: ::USHORT, + UriStemLength: ::USHORT, + ClientIpLength: ::USHORT, + ServerNameLength: ::USHORT, + ServiceNameLength: ::USHORT, + ServerIpLength: ::USHORT, + MethodLength: ::USHORT, + UriQueryLength: ::USHORT, + HostLength: ::USHORT, + UserAgentLength: ::USHORT, + CookieLength: ::USHORT, + ReferrerLength: ::USHORT, + UserName: ::PWCHAR, + UriStem: ::PWCHAR, + ClientIp: ::PCHAR, + ServerName: ::PCHAR, + ServiceName: ::PCHAR, + ServerIp: ::PCHAR, + Method: ::PCHAR, + UriQuery: ::PCHAR, + Host: ::PCHAR, + UserAgent: ::PCHAR, + Cookie: ::PCHAR, + Referrer: ::PCHAR, + ServerPort: ::USHORT, + ProtocolStatus: ::USHORT, + Win32Status: ::ULONG, + MethodNum: HTTP_VERB, + SubStatus: ::USHORT, +}} +pub type PHTTP_LOG_FIELDS_DATA = *mut HTTP_LOG_FIELDS_DATA; +ENUM!{enum HTTP_DATA_CHUNK_TYPE { + HttpDataChunkFromMemory, + HttpDataChunkFromFileHandle, + HttpDataChunkFromFragmentCache, + HttpDataChunkFromFragmentCacheEx, + HttpDataChunkMaximum, +}} +pub type PHTTP_DATA_CHUNK_TYPE = *mut HTTP_DATA_CHUNK_TYPE; +STRUCT!{struct HTTP_DATA_CHUNK_FromMemory { + pBuffer: ::PVOID, + BufferLength: ::ULONG, +}} +STRUCT!{struct HTTP_DATA_CHUNK_FromFileHandle { + ByteRange: HTTP_BYTE_RANGE, + FileHandle: ::HANDLE, +}} +STRUCT!{struct HTTP_DATA_CHUNK_FromFragmentCache { + FragmentNameLength: ::USHORT, + pFragmentName: ::PCWSTR, +}} +STRUCT!{struct HTTP_DATA_CHUNK_FromFragmentCacheEx { + ByteRange: HTTP_BYTE_RANGE, + pFragmentName: ::PCWSTR, +}} +STRUCT!{struct HTTP_DATA_CHUNK { + DataChunkType: HTTP_DATA_CHUNK_TYPE, + FromFileHandle: HTTP_DATA_CHUNK_FromFileHandle, +}} +UNION!(HTTP_DATA_CHUNK, FromFileHandle, FromMemory, FromMemory_mut, HTTP_DATA_CHUNK_FromMemory); +UNION!( + HTTP_DATA_CHUNK, FromFileHandle, FromFragmentCache, FromFragmentCache_mut, + HTTP_DATA_CHUNK_FromFragmentCache +); +UNION!( + HTTP_DATA_CHUNK, FromFileHandle, FromFragmentCacheEx, FromFragmentCacheEx_mut, + HTTP_DATA_CHUNK_FromFragmentCacheEx +); +pub type PHTTP_DATA_CHUNK = *mut HTTP_DATA_CHUNK; +STRUCT!{nodebug struct HTTP_REQUEST_HEADERS { + UnknownHeaderCount: ::USHORT, + pUnknownHeaders: PHTTP_UNKNOWN_HEADER, + TrailerCount: ::USHORT, + pTrailers: PHTTP_UNKNOWN_HEADER, + KnownHeaders: [HTTP_KNOWN_HEADER; 41], // FIXME HttpHeaderRequestMaximum +}} +pub type PHTTP_REQUEST_HEADERS = *mut HTTP_REQUEST_HEADERS; +STRUCT!{nodebug struct HTTP_RESPONSE_HEADERS { + UnknownHeaderCount: ::USHORT, + pUnknownHeaders: PHTTP_UNKNOWN_HEADER, + TrailerCount: ::USHORT, + pTrailers: PHTTP_UNKNOWN_HEADER, + KnownHeaders: [HTTP_KNOWN_HEADER; 30], // FIXME HttpHeaderResponseMaximum +}} +pub type PHTTP_RESPONSE_HEADERS = *mut HTTP_RESPONSE_HEADERS; +STRUCT!{struct HTTP_TRANSPORT_ADDRESS { + pRemoteAddress: ::PSOCKADDR, + pLocalAddress: ::PSOCKADDR, +}} +pub type PHTTP_TRANSPORT_ADDRESS = *mut HTTP_TRANSPORT_ADDRESS; +STRUCT!{struct HTTP_COOKED_URL { + FullUrlLength: ::USHORT, + HostLength: ::USHORT, + AbsPathLength: ::USHORT, + QueryStringLength: ::USHORT, + pFullUrl: ::PCWSTR, + pHost: ::PCWSTR, + pAbsPath: ::PCWSTR, + pQueryString: ::PCWSTR, +}} +pub type PHTTP_COOKED_URL = *mut HTTP_COOKED_URL; +pub type HTTP_URL_CONTEXT = ::ULONGLONG; +pub const HTTP_URL_FLAG_REMOVE_ALL: ::ULONG = 0x00000001; +ENUM!{enum HTTP_AUTH_STATUS { + HttpAuthStatusSuccess, + HttpAuthStatusNotAuthenticated, + HttpAuthStatusFailure, +}} +pub type PHTTP_AUTH_STATUS = *mut HTTP_AUTH_STATUS; +ENUM!{enum HTTP_REQUEST_AUTH_TYPE { + HttpRequestAuthTypeNone = 0, + HttpRequestAuthTypeBasic, + HttpRequestAuthTypeDigest, + HttpRequestAuthTypeNTLM, + HttpRequestAuthTypeNegotiate, + HttpRequestAuthTypeKerberos, +}} +pub type PHTTP_REQUEST_AUTH_TYPE = *mut HTTP_REQUEST_AUTH_TYPE; +STRUCT!{struct HTTP_SSL_CLIENT_CERT_INFO { + CertFlags: ::ULONG, + CertEncodedSize: ::ULONG, + pCertEncoded: ::PUCHAR, + Token: ::HANDLE, + CertDeniedByMapper: ::BOOLEAN, +}} +pub type PHTTP_SSL_CLIENT_CERT_INFO = *mut HTTP_SSL_CLIENT_CERT_INFO; +pub const HTTP_RECEIVE_SECURE_CHANNEL_TOKEN: ::ULONG = 0x1; +STRUCT!{struct HTTP_SSL_INFO { + ServerCertKeySize: ::USHORT, + ConnectionKeySize: ::USHORT, + ServerCertIssuerSize: ::ULONG, + ServerCertSubjectSize: ::ULONG, + pServerCertIssuer: ::PCSTR, + pServerCertSubject: ::PCSTR, + pClientCertInfo: PHTTP_SSL_CLIENT_CERT_INFO, + SslClientCertNegotiated: ::ULONG, +}} +pub type PHTTP_SSL_INFO = *mut HTTP_SSL_INFO; +ENUM!{enum HTTP_REQUEST_INFO_TYPE { + HttpRequestInfoTypeAuth, + HttpRequestInfoTypeChannelBind, +}} +STRUCT!{struct HTTP_REQUEST_INFO { + InfoType: HTTP_REQUEST_INFO_TYPE, + InfoLength: ::ULONG, + pInfo: ::PVOID, +}} +pub type PHTTP_REQUEST_INFO = *mut HTTP_REQUEST_INFO; +pub const HTTP_REQUEST_AUTH_FLAG_TOKEN_FOR_CACHED_CRED: ::ULONG = 0x00000001; +STRUCT!{struct HTTP_REQUEST_AUTH_INFO { + AuthStatus: HTTP_AUTH_STATUS, + SecStatus: ::SECURITY_STATUS, + Flags: ::ULONG, + AuthType: HTTP_REQUEST_AUTH_TYPE, + AccessToken: ::HANDLE, + ContextAttributes: ::ULONG, + PackedContextLength: ::ULONG, + PackedContextType: ::ULONG, + PackedContext: ::PVOID, + MutualAuthDataLength: ::ULONG, + pMutualAuthData: ::PCHAR, + PackageNameLength: ::USHORT, + pPackageName: ::PWSTR, +}} +pub type PHTTP_REQUEST_AUTH_INFO = *mut HTTP_REQUEST_AUTH_INFO; +STRUCT!{nodebug struct HTTP_REQUEST_V1 { + Flags: ::ULONG, + ConnectionId: HTTP_CONNECTION_ID, + RequestId: HTTP_REQUEST_ID, + UrlContext: HTTP_URL_CONTEXT, + Version: HTTP_VERSION, + Verb: HTTP_VERB, + UnknownVerbLength: ::USHORT, + RawUrlLength: ::USHORT, + pUnknownVerb: ::PCSTR, + pRawUrl: ::PCSTR, + CookedUrl: HTTP_COOKED_URL, + Address: HTTP_TRANSPORT_ADDRESS, + Headers: HTTP_REQUEST_HEADERS, + BytesReceived: ::ULONGLONG, + EntityChunkCount: ::USHORT, + pEntityChunks: PHTTP_DATA_CHUNK, + RawConnectionId: HTTP_RAW_CONNECTION_ID, + pSslInfo: PHTTP_SSL_INFO, +}} +pub type PHTTP_REQUEST_V1 = *mut HTTP_REQUEST_V1; +STRUCT!{nodebug struct HTTP_REQUEST_V2 { + Base: HTTP_REQUEST_V1, + RequestInfoCount: ::USHORT, + pRequestInfo: PHTTP_REQUEST_INFO, +}} +pub type PHTTP_REQUEST_V2 = *mut HTTP_REQUEST_V2; +pub type HTTP_REQUEST = HTTP_REQUEST_V2; +pub type PHTTP_REQUEST = *mut HTTP_REQUEST; +pub const HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS: ::ULONG = 0x00000001; +pub const HTTP_REQUEST_FLAG_IP_ROUTED: ::ULONG = 0x00000002; +STRUCT!{nodebug struct HTTP_RESPONSE_V1 { + Flags: ::ULONG, + Version: HTTP_VERSION, + StatusCode: ::USHORT, + ReasonLength: ::USHORT, + pReason: ::PCSTR, + Headers: HTTP_RESPONSE_HEADERS, + EntityChunkCount: ::USHORT, + pEntityChunks: PHTTP_DATA_CHUNK, +}} +pub type PHTTP_RESPONSE_V1 = *mut HTTP_RESPONSE_V1; +pub const HTTP_RESPONSE_FLAG_MULTIPLE_ENCODINGS_AVAILABLE: ::ULONG = 0x00000001; +ENUM!{enum HTTP_RESPONSE_INFO_TYPE { + HttpResponseInfoTypeMultipleKnownHeaders, + HttpResponseInfoTypeAuthenticationProperty, + HttpResponseInfoTypeQoSProperty, + HttpResponseInfoTypeChannelBind, +}} +pub type PHTTP_RESPONSE_INFO_TYPE = *mut HTTP_RESPONSE_INFO_TYPE; +STRUCT!{struct HTTP_RESPONSE_INFO { + Type: HTTP_RESPONSE_INFO_TYPE, + Length: ::ULONG, + pInfo: ::PVOID, +}} +pub type PHTTP_RESPONSE_INFO = *mut HTTP_RESPONSE_INFO; +pub const HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER: ::ULONG = 0x00000001; +STRUCT!{struct HTTP_MULTIPLE_KNOWN_HEADERS { + HeaderId: HTTP_HEADER_ID, + Flags: ::ULONG, + KnownHeaderCount: ::USHORT, + KnownHeaders: PHTTP_KNOWN_HEADER, +}} +pub type PHTTP_MULTIPLE_KNOWN_HEADERS = *mut HTTP_MULTIPLE_KNOWN_HEADERS; +STRUCT!{nodebug struct HTTP_RESPONSE_V2 { + Base: HTTP_RESPONSE_V1, + ResponseInfoCount: ::USHORT, + pResponseInfo: PHTTP_RESPONSE_INFO, +}} +pub type PHTTP_RESPONSE_V2 = *mut HTTP_RESPONSE_V2; +pub type HTTP_RESPONSE = HTTP_RESPONSE_V2; +pub type PHTTP_RESPONSE = *mut HTTP_RESPONSE; +STRUCT!{struct HTTPAPI_VERSION { + HttpApiMajorVersion: ::USHORT, + HttpApiMinorVersion: ::USHORT, +}} +pub type PHTTPAPI_VERSION = *mut HTTPAPI_VERSION; +pub const HTTPAPI_VERSION_2: HTTPAPI_VERSION = HTTPAPI_VERSION { + HttpApiMajorVersion: 2, HttpApiMinorVersion: 0, +}; +pub const HTTPAPI_VERSION_1: HTTPAPI_VERSION = HTTPAPI_VERSION { + HttpApiMajorVersion: 1, HttpApiMinorVersion: 0, +}; +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_EQUAL_VERSION(version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.HttpApiMajorVersion == major && version.HttpApiMinorVersion == minor +} +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_GREATER_VERSION(version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.HttpApiMajorVersion > major || + (version.HttpApiMajorVersion == major && version.HttpApiMinorVersion > minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_LESS_VERSION(version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.HttpApiMajorVersion < major || + (version.HttpApiMajorVersion == major && version.HttpApiMinorVersion < minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_VERSION_GREATER_OR_EQUAL( + version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT +) -> bool { + !HTTPAPI_LESS_VERSION(version, major, minor) +} +ENUM!{enum HTTP_CACHE_POLICY_TYPE { + HttpCachePolicyNocache, + HttpCachePolicyUserInvalidates, + HttpCachePolicyTimeToLive, + HttpCachePolicyMaximum, +}} +pub type PHTTP_CACHE_POLICY_TYPE = *mut HTTP_CACHE_POLICY_TYPE; +STRUCT!{struct HTTP_CACHE_POLICY { + Policy: HTTP_CACHE_POLICY_TYPE, + SecondsToLive: ::ULONG, +}} +pub type PHTTP_CACHE_POLICY = *mut HTTP_CACHE_POLICY; +ENUM!{enum HTTP_SERVICE_CONFIG_ID { + HttpServiceConfigIPListenList, + HttpServiceConfigSSLCertInfo, + HttpServiceConfigUrlAclInfo, + HttpServiceConfigTimeout, + HttpServiceConfigCache, + HttpServiceConfigSslSniCertInfo, + HttpServiceConfigSslCcsCertInfo, + HttpServiceConfigMax, +}} +pub type PHTTP_SERVICE_CONFIG_ID = *mut HTTP_SERVICE_CONFIG_ID; +ENUM!{enum HTTP_SERVICE_CONFIG_QUERY_TYPE { + HttpServiceConfigQueryExact, + HttpServiceConfigQueryNext, + HttpServiceConfigQueryMax, +}} +pub type PHTTP_SERVICE_CONFIG_QUERY_TYPE = *mut HTTP_SERVICE_CONFIG_QUERY_TYPE; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_KEY { + pIpPort: ::PSOCKADDR, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_KEY = *mut HTTP_SERVICE_CONFIG_SSL_KEY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_SNI_KEY { + IpPort: ::SOCKADDR_STORAGE, + Host: ::PWSTR, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SNI_KEY = *mut HTTP_SERVICE_CONFIG_SSL_SNI_KEY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_CCS_KEY { + LocalAddress: ::SOCKADDR_STORAGE, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_CCS_KEY = *mut HTTP_SERVICE_CONFIG_SSL_CCS_KEY; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_PARAM { + SslHashLength: ::ULONG, + pSslHash: ::PVOID, + AppId: ::GUID, + pSslCertStoreName: ::PWSTR, + DefaultCertCheckMode: ::DWORD, + DefaultRevocationFreshnessTime: ::DWORD, + DefaultRevocationUrlRetrievalTimeout: ::DWORD, + pDefaultSslCtlIdentifier: ::PWSTR, + pDefaultSslCtlStoreName: ::PWSTR, + DefaultFlags: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_PARAM = *mut HTTP_SERVICE_CONFIG_SSL_PARAM; +pub const HTTP_SERVICE_CONFIG_SSL_FLAG_USE_DS_MAPPER: ::DWORD = 0x00000001; +pub const HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT: ::DWORD = 0x00000002; +pub const HTTP_SERVICE_CONFIG_SSL_FLAG_NO_RAW_FILTER: ::DWORD = 0x00000004; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_SET { + KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SET = *mut HTTP_SERVICE_CONFIG_SSL_SET; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_SNI_SET { + KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SNI_SET = *mut HTTP_SERVICE_CONFIG_SSL_SNI_SET; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_CCS_SET { + KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_CCS_SET = *mut HTTP_SERVICE_CONFIG_SSL_CCS_SET; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_QUERY = *mut HTTP_SERVICE_CONFIG_SSL_QUERY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_SNI_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SNI_QUERY = *mut HTTP_SERVICE_CONFIG_SSL_SNI_QUERY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_CCS_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_CCS_QUERY = *mut HTTP_SERVICE_CONFIG_SSL_CCS_QUERY; +STRUCT!{struct HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM { + AddrLength: ::USHORT, + pAddress: ::PSOCKADDR, +}} +pub type PHTTP_SERVICE_CONFIG_IP_LISTEN_PARAM = *mut HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY { + AddrCount: ::ULONG, + AddrList: [::SOCKADDR_STORAGE; ::ANYSIZE_ARRAY], +}} +pub type PHTTP_SERVICE_CONFIG_IP_LISTEN_QUERY = *mut HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_KEY { + pUrlPrefix: ::PWSTR, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_KEY = *mut HTTP_SERVICE_CONFIG_URLACL_KEY; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_PARAM { + pStringSecurityDescriptor: ::PWSTR, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_PARAM = *mut HTTP_SERVICE_CONFIG_URLACL_PARAM; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_SET { + KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_URLACL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_SET = *mut HTTP_SERVICE_CONFIG_URLACL_SET; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_QUERY = *mut HTTP_SERVICE_CONFIG_URLACL_QUERY; +ENUM!{enum HTTP_SERVICE_CONFIG_CACHE_KEY { + MaxCacheResponseSize = 0, + CacheRangeChunkSize, +}} +pub type PHTTP_SERVICE_CONFIG_CACHE_KEY = *mut HTTP_SERVICE_CONFIG_CACHE_KEY; +pub type HTTP_SERVICE_CONFIG_CACHE_PARAM = ::ULONG; +pub type PHTTP_SERVICE_CONFIG_CACHE_PARAM = *mut ::ULONG; +STRUCT!{struct HTTP_SERVICE_CONFIG_CACHE_SET { + KeyDesc: HTTP_SERVICE_CONFIG_CACHE_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_CACHE_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_CACHE_SET = *mut HTTP_SERVICE_CONFIG_CACHE_SET; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/imm.rs b/bash-5.1/vendor/winapi-0.2.8/src/imm.rs new file mode 100644 index 0000000..cadf6cf --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/imm.rs @@ -0,0 +1,3 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub type LPUINT = *mut ::c_uint; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/inaddr.rs b/bash-5.1/vendor/winapi-0.2.8/src/inaddr.rs new file mode 100644 index 0000000..f89e9ba --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/inaddr.rs @@ -0,0 +1,22 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! IPv4 Internet address +STRUCT!{struct in_addr_S_un_b { + s_b1: ::UCHAR, + s_b2: ::UCHAR, + s_b3: ::UCHAR, + s_b4: ::UCHAR, +}} +STRUCT!{struct in_addr_S_un_w { + s_w1: ::USHORT, + s_w2: ::USHORT, +}} +STRUCT!{struct in_addr { + S_un: ::ULONG, +}} +UNION!(in_addr, S_un, S_un_b, S_un_b_mut, in_addr_S_un_b); +UNION!(in_addr, S_un, S_un_w, S_un_w_mut, in_addr_S_un_w); +UNION!(in_addr, S_un, S_addr, S_addr_mut, ::ULONG); +pub type IN_ADDR = in_addr; +pub type PIN_ADDR = *mut in_addr; +pub type LPIN_ADDR = *mut in_addr; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/inspectable.rs b/bash-5.1/vendor/winapi-0.2.8/src/inspectable.rs new file mode 100644 index 0000000..36575e1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/inspectable.rs @@ -0,0 +1,15 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub type LPINSPECTABLE = *mut IInspectable; +ENUM!{enum TrustLevel { + BaseTrust = 0, + PartialTrust, + FullTrust, +}} +RIDL!( +interface IInspectable(IInspectableVtbl): IUnknown(IUnknownVtbl) { + fn GetIids(&mut self, iidCount: *mut ::ULONG, iids: *mut *mut ::IID) -> ::HRESULT, + fn GetRuntimeClassName(&mut self, className: *mut ::HSTRING) -> ::HRESULT, + fn GetTrustLevel(&mut self, trustLevel: *mut TrustLevel) -> ::HRESULT +} +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ksmedia.rs b/bash-5.1/vendor/winapi-0.2.8/src/ksmedia.rs new file mode 100644 index 0000000..8ef2700 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ksmedia.rs @@ -0,0 +1,18 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_ANALOG, 0x6DBA3190, 0x67BD, 0x11CF, + 0xA0, 0xF7, 0x00, 0x20, 0xAF, 0xD1, 0x56, 0xE4); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_DRM, 0x00000009, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_ALAW, 0x00000006, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_MULAW, 0x00000007, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_ADPCM, 0x00000002, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_MPEG, 0x00000050, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lib.rs b/bash-5.1/vendor/winapi-0.2.8/src/lib.rs new file mode 100644 index 0000000..0e99f81 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lib.rs @@ -0,0 +1,368 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Types and constants for WinAPI bindings. +#![allow(bad_style)] +#![warn(trivial_casts, trivial_numeric_casts)] +#![warn(unused_qualifications, unused)] +#![cfg(windows)] +//------------------------------------------------------------------------------------------------- +// Imports +//------------------------------------------------------------------------------------------------- +pub use std::os::raw::{ + c_void, + c_char, + c_schar, + c_uchar, + c_short, + c_ushort, + c_int, + c_uint, + c_long, + c_ulong, + c_longlong, + c_ulonglong, + c_float, + c_double, +}; +pub use activation::*; +pub use audioclient::*; +pub use audiosessiontypes::*; +pub use basetsd::*; +pub use bcrypt::*; +pub use cfg::*; +pub use cfgmgr32::*; +pub use combaseapi::*; +pub use commctrl::*; +pub use commdlg::*; +pub use corsym::*; +pub use d2d1::*; +pub use d2dbasetypes::*; +pub use d3d9::*; +pub use d3d9caps::*; +pub use d3d9types::*; +pub use d3d11::*; +pub use d3d10shader::*; +pub use d3d11shader::*; +pub use d3d12::*; +pub use d3d12sdklayers::*; +pub use d3d12shader::*; +pub use d3dcommon::*; +pub use d3dcompiler::*; +pub use dbghelp::*; +pub use dcommon::*; +pub use devpropdef::*; +pub use docobj::*; +pub use dpapi::*; +pub use dsgetdc::*; +pub use dsound::*; +pub use dsrole::*; +pub use dwmapi::*; +pub use dwrite::*; +pub use dxgi::*; +pub use dxgi1_2::*; +pub use dxgi1_3::*; +pub use dxgi1_4::*; +pub use dxgiformat::*; +pub use dxgitype::*; +pub use errhandlingapi::*; +pub use excpt::*; +pub use fileapi::*; +pub use gl::*; +pub use guiddef::*; +pub use heapapi::*; +pub use hidclass::*; +pub use hidpi::*; +pub use hidsdi::*; +pub use hidusage::*; +pub use hstring::*; +pub use http::*; +pub use imm::*; +pub use inaddr::*; +pub use inspectable::*; +pub use ksmedia::*; +pub use libloaderapi::*; +pub use lmaccess::*; +pub use lmcons::*; +pub use lmdfs::*; +pub use lmerrlog::*; +pub use lmjoin::*; +pub use lsalookup::*; +pub use memoryapi::*; +pub use minschannel::*; +pub use minwinbase::*; +pub use minwindef::*; +pub use mmdeviceapi::*; +pub use mmreg::*; +pub use mmsystem::*; +pub use mscat::*; +pub use mssip::*; +pub use nb30::*; +pub use ncrypt::*; +pub use ntdef::*; +pub use ntsecapi::*; +pub use ntstatus::*; +pub use oaidl::*; +pub use objbase::*; +pub use objidl::*; +pub use objidlbase::*; +pub use olectl::*; +pub use pdh::*; +pub use playsoundapi::*; +pub use processsnapshot::*; +pub use processthreadsapi::*; +pub use propidl::*; +pub use propsys::*; +pub use prsht::*; +pub use psapi::*; +pub use qos::*; +pub use reason::*; +pub use restrictederrorinfo::*; +pub use roapi::*; +pub use roerrorapi::*; +pub use rpc::*; +pub use rpcdce::*; +pub use sapi::*; +pub use schannel::*; +pub use servprov::*; +pub use setupapi::*; +pub use shellapi::*; +pub use shellscalingapi::*; +pub use shlguid::*; +pub use shlobj::*; +pub use shobjidl::*; +pub use shtypes::*; +pub use spapidef::*; +pub use sqltypes::*; +pub use sspi::*; +pub use strmif::*; +pub use subauth::*; +pub use synchapi::*; +pub use sysinfoapi::*; +pub use threadpoolapi::*; +pub use timezoneapi::*; +pub use tlhelp32::*; +pub use unknwnbase::*; +pub use urlhist::*; +pub use urlmon::*; +pub use usb::*; +pub use usbspec::*; +pub use usp10::*; +pub use vadefs::*; +pub use vsbackup::*; +pub use vss::*; +pub use vsserror::*; +pub use vswriter::*; +pub use werapi::*; +pub use winbase::*; +pub use wincon::*; +pub use wincred::*; +pub use wincrypt::*; +pub use windowsx::*; +pub use windef::*; +pub use windowscodecs::*; +pub use winerror::*; +pub use winevt::*; +pub use wingdi::*; +pub use winhttp::*; +pub use winioctl::*; +pub use winnetwk::*; +pub use winnls::*; +pub use winnt::*; +pub use winreg::*; +pub use winscard::*; +pub use winsmcrd::*; +pub use winsock2::*; +pub use winspool::*; +pub use winstring::*; +pub use winsvc::*; +pub use winusb::*; +pub use winusbio::*; +pub use winuser::*; +pub use ws2def::*; +pub use ws2ipdef::*; +pub use ws2spi::*; +pub use ws2tcpip::*; +pub use wtypes::*; +pub use wtypesbase::*; +pub use xinput::*; +//------------------------------------------------------------------------------------------------- +// Modules +//------------------------------------------------------------------------------------------------- +#[macro_use] mod macros; +pub mod activation; +pub mod audioclient; +pub mod audiosessiontypes; +pub mod basetsd; +pub mod bcrypt; +pub mod cfg; +pub mod cfgmgr32; +pub mod combaseapi; +pub mod commctrl; +pub mod commdlg; +pub mod corsym; +pub mod d2d1; +pub mod d2dbasetypes; +pub mod d3d9; +pub mod d3d9caps; +pub mod d3d9types; +pub mod d3d11; +pub mod d3d10shader; +pub mod d3d11shader; +pub mod d3d12; +pub mod d3d12sdklayers; +pub mod d3d12shader; +pub mod d3dcommon; +pub mod d3dcompiler; +pub mod dbghelp; +pub mod dcommon; +pub mod devpropdef; +pub mod docobj; +pub mod dpapi; +pub mod dsgetdc; +pub mod dsound; +pub mod dsrole; +pub mod dwmapi; +pub mod dwrite; +pub mod dxgi; +pub mod dxgi1_2; +pub mod dxgi1_3; +pub mod dxgi1_4; +pub mod dxgiformat; +pub mod dxgitype; +pub mod errhandlingapi; +pub mod excpt; +pub mod fileapi; +pub mod gl; +pub mod guiddef; +pub mod heapapi; +pub mod hidclass; +pub mod hidpi; +pub mod hidsdi; +pub mod hidusage; +pub mod hstring; +pub mod http; +pub mod imm; +pub mod inaddr; +pub mod inspectable; +pub mod ksmedia; +pub mod libloaderapi; +pub mod lmaccess; +pub mod lmcons; +pub mod lmdfs; +pub mod lmerrlog; +pub mod lmjoin; +pub mod lsalookup; +pub mod memoryapi; +pub mod minschannel; +pub mod minwinbase; +pub mod minwindef; +pub mod mmdeviceapi; +pub mod mmreg; +pub mod mmsystem; +pub mod mscat; +pub mod mssip; +pub mod nb30; +pub mod ncrypt; +pub mod ntdef; +pub mod ntsecapi; +pub mod ntstatus; +pub mod oaidl; +pub mod objbase; +pub mod objidl; +pub mod objidlbase; +pub mod olectl; +pub mod pdh; +pub mod playsoundapi; +pub mod processsnapshot; +pub mod processthreadsapi; +pub mod propidl; +pub mod propsys; +pub mod prsht; +pub mod psapi; +pub mod qos; +pub mod reason; +pub mod restrictederrorinfo; +pub mod roapi; +pub mod roerrorapi; +pub mod rpc; +pub mod rpcdce; +pub mod sapi; +pub mod schannel; +pub mod servprov; +pub mod setupapi; +pub mod shellapi; +pub mod shellscalingapi; +pub mod shlguid; +pub mod shlobj; +pub mod shobjidl; +pub mod shtypes; +pub mod spapidef; +pub mod sqltypes; +pub mod sspi; +pub mod strmif; +pub mod subauth; +pub mod synchapi; +pub mod sysinfoapi; +pub mod threadpoolapi; +pub mod timezoneapi; +pub mod tlhelp32; +pub mod unknwnbase; +pub mod urlhist; +pub mod urlmon; +pub mod usb; +pub mod usbspec; +pub mod usp10; +pub mod vadefs; +pub mod vsbackup; +pub mod vss; +pub mod vsserror; +pub mod vswriter; +pub mod werapi; +pub mod winbase; +pub mod wincon; +pub mod wincred; +pub mod wincrypt; +pub mod windef; +pub mod windowscodecs; +pub mod windowsx; +pub mod winerror; +pub mod winevt; +pub mod wingdi; +pub mod winhttp; +pub mod winioctl; +pub mod winnetwk; +pub mod winnls; +pub mod winnt; +pub mod winreg; +pub mod winscard; +pub mod winsmcrd; +pub mod winsock2; +pub mod winspool; +pub mod winstring; +pub mod winsvc; +pub mod winusb; +pub mod winusbio; +pub mod winuser; +pub mod ws2def; +pub mod ws2ipdef; +pub mod ws2spi; +pub mod ws2tcpip; +pub mod wtypes; +pub mod wtypesbase; +pub mod xinput; +//------------------------------------------------------------------------------------------------- +// Primitive types not provided by std +//------------------------------------------------------------------------------------------------- +pub type __int8 = i8; +pub type __uint8 = u8; +pub type __int16 = i16; +pub type __uint16 = u16; +pub type __int32 = i32; +pub type __uint32 = u32; +pub type __int64 = i64; +pub type __uint64 = u64; +pub type wchar_t = c_ushort; +#[cfg(target_arch = "x86")] +pub type size_t = c_uint; +#[cfg(target_arch = "x86_64")] +pub type size_t = __uint64; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/libloaderapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/libloaderapi.rs new file mode 100644 index 0000000..9b47b0a --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/libloaderapi.rs @@ -0,0 +1,23 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-libraryloader-l1 +pub type DLL_DIRECTORY_COOKIE = ::PVOID; +pub type PDLL_DIRECTORY_COOKIE = *mut ::PVOID; +pub type ENUMRESLANGPROCA = Option<unsafe extern "system" fn( + hModule: ::HMODULE, lpType: ::LPCSTR, lpName: ::LPCSTR, wLanguage: ::WORD, lParam: ::LONG_PTR, +) -> ::BOOL>; +pub type ENUMRESLANGPROCW = Option<unsafe extern "system" fn( + hModule: ::HMODULE, lpType: ::LPCWSTR, lpName: ::LPCWSTR, wLanguage: ::WORD, lParam: ::LONG_PTR, +) -> ::BOOL>; +pub type ENUMRESNAMEPROCA = Option<unsafe extern "system" fn( + hModule: ::HMODULE, lpType: ::LPCSTR, lpName: ::LPSTR, lParam: ::LONG_PTR, +) -> ::BOOL>; +pub type ENUMRESNAMEPROCW = Option<unsafe extern "system" fn( + hModule: ::HMODULE, lpType: ::LPCWSTR, lpName: ::LPWSTR, lParam: ::LONG_PTR, +) -> ::BOOL>; +pub type ENUMRESTYPEPROCA = Option<unsafe extern "system" fn( + hModule: ::HMODULE, lpType: ::LPSTR, lParam: ::LONG_PTR, +) -> ::BOOL>; +pub type ENUMRESTYPEPROCW = Option<unsafe extern "system" fn( + hModule: ::HMODULE, lpType: ::LPWSTR, lParam: ::LONG_PTR, +) -> ::BOOL>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lmaccess.rs b/bash-5.1/vendor/winapi-0.2.8/src/lmaccess.rs new file mode 100644 index 0000000..2768f8c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lmaccess.rs @@ -0,0 +1,853 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +// This file contains structures, function prototypes, and definitions +// for the NetUser, NetUserModals, NetGroup, NetAccess, and NetLogon API. +STRUCT!{struct USER_INFO_0 { + usri0_name: ::LPWSTR, +}} +pub type PUSER_INFO_0 = *mut USER_INFO_0; +pub type LPUSER_INFO_0 = *mut USER_INFO_0; +STRUCT!{struct USER_INFO_1 { + usri1_name: ::LPWSTR, + usri1_password: ::LPWSTR, + usri1_password_age: ::DWORD, + usri1_priv: ::DWORD, + usri1_home_dir: ::LPWSTR, + usri1_comment: ::LPWSTR, + usri1_flags: ::DWORD, + usri1_script_path: ::LPWSTR, +}} +pub type PUSER_INFO_1 = *mut USER_INFO_1; +pub type LPUSER_INFO_1 = *mut USER_INFO_1; +STRUCT!{struct USER_INFO_2 { + usri2_name: ::LPWSTR, + usri2_password: ::LPWSTR, + usri2_password_age: ::DWORD, + usri2_priv: ::DWORD, + usri2_home_dir: ::LPWSTR, + usri2_comment: ::LPWSTR, + usri2_flags: ::DWORD, + usri2_script_path: ::LPWSTR, + usri2_auth_flags: ::DWORD, + usri2_full_name: ::LPWSTR, + usri2_usr_comment: ::LPWSTR, + usri2_parms: ::LPWSTR, + usri2_workstations: ::LPWSTR, + usri2_last_logon: ::DWORD, + usri2_last_logoff: ::DWORD, + usri2_acct_expires: ::DWORD, + usri2_max_storage: ::DWORD, + usri2_units_per_week: ::DWORD, + usri2_logon_hours: ::PBYTE, + usri2_bad_pw_count: ::DWORD, + usri2_num_logons: ::DWORD, + usri2_logon_server: ::LPWSTR, + usri2_country_code: ::DWORD, + usri2_code_page: ::DWORD, +}} +pub type PUSER_INFO_2 = *mut USER_INFO_2; +pub type LPUSER_INFO_2 = *mut USER_INFO_2; +STRUCT!{struct USER_INFO_3 { + usri3_name: ::LPWSTR, + usri3_password: ::LPWSTR, + usri3_password_age: ::DWORD, + usri3_priv: ::DWORD, + usri3_home_dir: ::LPWSTR, + usri3_comment: ::LPWSTR, + usri3_flags: ::DWORD, + usri3_script_path: ::LPWSTR, + usri3_auth_flags: ::DWORD, + usri3_full_name: ::LPWSTR, + usri3_usr_comment: ::LPWSTR, + usri3_parms: ::LPWSTR, + usri3_workstations: ::LPWSTR, + usri3_last_logon: ::DWORD, + usri3_last_logoff: ::DWORD, + usri3_acct_expires: ::DWORD, + usri3_max_storage: ::DWORD, + usri3_units_per_week: ::DWORD, + usri3_logon_hours: ::PBYTE, + usri3_bad_pw_count: ::DWORD, + usri3_num_logons: ::DWORD, + usri3_logon_server: ::LPWSTR, + usri3_country_code: ::DWORD, + usri3_code_page: ::DWORD, + usri3_user_id: ::DWORD, + usri3_primary_group_id: ::DWORD, + usri3_profile: ::LPWSTR, + usri3_home_dir_drive: ::LPWSTR, + usri3_password_expired: ::DWORD, +}} +pub type PUSER_INFO_3 = *mut USER_INFO_3; +pub type LPUSER_INFO_3 = *mut USER_INFO_3; +STRUCT!{struct USER_INFO_4 { + usri4_name: ::LPWSTR, + usri4_password: ::LPWSTR, + usri4_password_age: ::DWORD, + usri4_priv: ::DWORD, + usri4_home_dir: ::LPWSTR, + usri4_comment: ::LPWSTR, + usri4_flags: ::DWORD, + usri4_script_path: ::LPWSTR, + usri4_auth_flags: ::DWORD, + usri4_full_name: ::LPWSTR, + usri4_usr_comment: ::LPWSTR, + usri4_parms: ::LPWSTR, + usri4_workstations: ::LPWSTR, + usri4_last_logon: ::DWORD, + usri4_last_logoff: ::DWORD, + usri4_acct_expires: ::DWORD, + usri4_max_storage: ::DWORD, + usri4_units_per_week: ::DWORD, + usri4_logon_hours: ::PBYTE, + usri4_bad_pw_count: ::DWORD, + usri4_num_logons: ::DWORD, + usri4_logon_server: ::LPWSTR, + usri4_country_code: ::DWORD, + usri4_code_page: ::DWORD, + usri4_user_sid: ::PSID, + usri4_primary_group_id: ::DWORD, + usri4_profile: ::LPWSTR, + usri4_home_dir_drive: ::LPWSTR, + usri4_password_expired: ::DWORD, +}} +pub type PUSER_INFO_4 = *mut USER_INFO_4; +pub type LPUSER_INFO_4 = *mut USER_INFO_4; +STRUCT!{struct USER_INFO_10 { + usri10_name: ::LPWSTR, + usri10_comment: ::LPWSTR, + usri10_usr_comment: ::LPWSTR, + usri10_full_name: ::LPWSTR, +}} +pub type PUSER_INFO_10 = *mut USER_INFO_10; +pub type LPUSER_INFO_10 = *mut USER_INFO_10; +STRUCT!{struct USER_INFO_11 { + usri11_name: ::LPWSTR, + usri11_comment: ::LPWSTR, + usri11_usr_comment: ::LPWSTR, + usri11_full_name: ::LPWSTR, + usri11_priv: ::DWORD, + usri11_auth_flags: ::DWORD, + usri11_password_age: ::DWORD, + usri11_home_dir: ::LPWSTR, + usri11_parms: ::LPWSTR, + usri11_last_logon: ::DWORD, + usri11_last_logoff: ::DWORD, + usri11_bad_pw_count: ::DWORD, + usri11_num_logons: ::DWORD, + usri11_logon_server: ::LPWSTR, + usri11_country_code: ::DWORD, + usri11_workstations: ::LPWSTR, + usri11_max_storage: ::DWORD, + usri11_units_per_week: ::DWORD, + usri11_logon_hours: ::PBYTE, + usri11_code_page: ::DWORD, +}} +pub type PUSER_INFO_11 = *mut USER_INFO_11; +pub type LPUSER_INFO_11 = *mut USER_INFO_11; +STRUCT!{struct USER_INFO_20 { + usri20_name: ::LPWSTR, + usri20_full_name: ::LPWSTR, + usri20_comment: ::LPWSTR, + usri20_flags: ::DWORD, + usri20_user_id: ::DWORD, +}} +pub type PUSER_INFO_20 = *mut USER_INFO_20; +pub type LPUSER_INFO_20 = *mut USER_INFO_20; +STRUCT!{struct USER_INFO_21 { + usri21_password: [::BYTE; ::ENCRYPTED_PWLEN], +}} +pub type PUSER_INFO_21 = *mut USER_INFO_21; +pub type LPUSER_INFO_21 = *mut USER_INFO_21; +STRUCT!{struct USER_INFO_22 { + usri22_name: ::LPWSTR, + usri22_password: [::BYTE; ::ENCRYPTED_PWLEN], + usri22_password_age: ::DWORD, + usri22_priv: ::DWORD, + usri22_home_dir: ::LPWSTR, + usri22_comment: ::LPWSTR, + usri22_flags: ::DWORD, + usri22_script_path: ::LPWSTR, + usri22_auth_flags: ::DWORD, + usri22_full_name: ::LPWSTR, + usri22_usr_comment: ::LPWSTR, + usri22_parms: ::LPWSTR, + usri22_workstations: ::LPWSTR, + usri22_last_logon: ::DWORD, + usri22_last_logoff: ::DWORD, + usri22_acct_expires: ::DWORD, + usri22_max_storage: ::DWORD, + usri22_units_per_week: ::DWORD, + usri22_logon_hours: ::PBYTE, + usri22_bad_pw_count: ::DWORD, + usri22_num_logons: ::DWORD, + usri22_logon_server: ::LPWSTR, + usri22_country_code: ::DWORD, + usri22_code_page: ::DWORD, +}} +pub type PUSER_INFO_22 = *mut USER_INFO_22; +pub type LPUSER_INFO_22 = *mut USER_INFO_22; +STRUCT!{struct USER_INFO_23 { + usri23_name: ::LPWSTR, + usri23_full_name: ::LPWSTR, + usri23_comment: ::LPWSTR, + usri23_flags: ::DWORD, + usri23_user_sid: ::PSID, +}} +pub type PUSER_INFO_23 = *mut USER_INFO_23; +pub type LPUSER_INFO_23 = *mut USER_INFO_23; +STRUCT!{struct USER_INFO_24 { + usri24_internet_identity: ::BOOL, + usri24_flags: ::DWORD, + usri24_internet_provider_name: ::LPWSTR, + usri24_internet_principal_name: ::LPWSTR, + usri24_user_sid: ::PSID, +}} +pub type PUSER_INFO_24 = *mut USER_INFO_24; +pub type LPUSER_INFO_24 = *mut USER_INFO_24; +STRUCT!{struct USER_INFO_1003 { + usri1003_password: ::LPWSTR, +}} +pub type PUSER_INFO_1003 = *mut USER_INFO_1003; +pub type LPUSER_INFO_1003 = *mut USER_INFO_1003; +STRUCT!{struct USER_INFO_1005 { + usri1005_priv: ::DWORD, +}} +pub type PUSER_INFO_1005 = *mut USER_INFO_1005; +pub type LPUSER_INFO_1005 = *mut USER_INFO_1005; +STRUCT!{struct USER_INFO_1006 { + usri1006_home_dir: ::LPWSTR, +}} +pub type PUSER_INFO_1006 = *mut USER_INFO_1006; +pub type LPUSER_INFO_1006 = *mut USER_INFO_1006; +STRUCT!{struct USER_INFO_1007 { + usri1007_comment: ::LPWSTR, +}} +pub type PUSER_INFO_1007 = *mut USER_INFO_1007; +pub type LPUSER_INFO_1007 = *mut USER_INFO_1007; +STRUCT!{struct USER_INFO_1008 { + usri1008_flags: ::DWORD, +}} +pub type PUSER_INFO_1008 = *mut USER_INFO_1008; +pub type LPUSER_INFO_1008 = *mut USER_INFO_1008; +STRUCT!{struct USER_INFO_1009 { + usri1009_script_path: ::LPWSTR, +}} +pub type PUSER_INFO_1009 = *mut USER_INFO_1009; +pub type LPUSER_INFO_1009 = *mut USER_INFO_1009; +STRUCT!{struct USER_INFO_1010 { + usri1010_auth_flags: ::DWORD, +}} +pub type PUSER_INFO_1010 = *mut USER_INFO_1010; +pub type LPUSER_INFO_1010 = *mut USER_INFO_1010; +STRUCT!{struct USER_INFO_1011 { + usri1011_full_name: ::LPWSTR, +}} +pub type PUSER_INFO_1011 = *mut USER_INFO_1011; +pub type LPUSER_INFO_1011 = *mut USER_INFO_1011; +STRUCT!{struct USER_INFO_1012 { + usri1012_usr_comment: ::LPWSTR, +}} +pub type PUSER_INFO_1012 = *mut USER_INFO_1012; +pub type LPUSER_INFO_1012 = *mut USER_INFO_1012; +STRUCT!{struct USER_INFO_1013 { + usri1013_parms: ::LPWSTR, +}} +pub type PUSER_INFO_1013 = *mut USER_INFO_1013; +pub type LPUSER_INFO_1013 = *mut USER_INFO_1013; +STRUCT!{struct USER_INFO_1014 { + usri1014_workstations: ::LPWSTR, +}} +pub type PUSER_INFO_1014 = *mut USER_INFO_1014; +pub type LPUSER_INFO_1014 = *mut USER_INFO_1014; +STRUCT!{struct USER_INFO_1017 { + usri1017_acct_expires: ::DWORD, +}} +pub type PUSER_INFO_1017 = *mut USER_INFO_1017; +pub type LPUSER_INFO_1017 = *mut USER_INFO_1017; +STRUCT!{struct USER_INFO_1018 { + usri1018_max_storage: ::DWORD, +}} +pub type PUSER_INFO_1018 = *mut USER_INFO_1018; +pub type LPUSER_INFO_1018 = *mut USER_INFO_1018; +STRUCT!{struct USER_INFO_1020 { + usri1020_units_per_week: ::DWORD, + usri1020_logon_hours: ::LPBYTE, +}} +pub type PUSER_INFO_1020 = *mut USER_INFO_1020; +pub type LPUSER_INFO_1020 = *mut USER_INFO_1020; +STRUCT!{struct USER_INFO_1023 { + usri1023_logon_server: ::LPWSTR, +}} +pub type PUSER_INFO_1023 = *mut USER_INFO_1023; +pub type LPUSER_INFO_1023 = *mut USER_INFO_1023; +STRUCT!{struct USER_INFO_1024 { + usri1024_country_code: ::DWORD, +}} +pub type PUSER_INFO_1024 = *mut USER_INFO_1024; +pub type LPUSER_INFO_1024 = *mut USER_INFO_1024; +STRUCT!{struct USER_INFO_1025 { + usri1025_code_page: ::DWORD, +}} +pub type PUSER_INFO_1025 = *mut USER_INFO_1025; +pub type LPUSER_INFO_1025 = *mut USER_INFO_1025; +STRUCT!{struct USER_INFO_1051 { + usri1051_primary_group_id: ::DWORD, +}} +pub type PUSER_INFO_1051 = *mut USER_INFO_1051; +pub type LPUSER_INFO_1051 = *mut USER_INFO_1051; +STRUCT!{struct USER_INFO_1052 { + usri1052_profile: ::LPWSTR, +}} +pub type PUSER_INFO_1052 = *mut USER_INFO_1052; +pub type LPUSER_INFO_1052 = *mut USER_INFO_1052; +STRUCT!{struct USER_INFO_1053 { + usri1053_home_dir_drive: ::LPWSTR, +}} +pub type PUSER_INFO_1053 = *mut USER_INFO_1053; +pub type LPUSER_INFO_1053 = *mut USER_INFO_1053; +STRUCT!{struct USER_MODALS_INFO_0 { + usrmod0_min_passwd_len: ::DWORD, + usrmod0_max_passwd_age: ::DWORD, + usrmod0_min_passwd_age: ::DWORD, + usrmod0_force_logoff: ::DWORD, + usrmod0_password_hist_len: ::DWORD, +}} +pub type PUSER_MODALS_INFO_0 = *mut USER_MODALS_INFO_0; +pub type LPUSER_MODALS_INFO_0 = *mut USER_MODALS_INFO_0; +STRUCT!{struct USER_MODALS_INFO_1 { + usrmod1_role: ::DWORD, + usrmod1_primary: ::LPWSTR, +}} +pub type PUSER_MODALS_INFO_1 = *mut USER_MODALS_INFO_1; +pub type LPUSER_MODALS_INFO_1 = *mut USER_MODALS_INFO_1; +STRUCT!{struct USER_MODALS_INFO_2 { + usrmod2_domain_name: ::LPWSTR, + usrmod2_domain_id: ::PSID, +}} +pub type PUSER_MODALS_INFO_2 = *mut USER_MODALS_INFO_2; +pub type LPUSER_MODALS_INFO_2 = *mut USER_MODALS_INFO_2; +STRUCT!{struct USER_MODALS_INFO_3 { + usrmod3_lockout_duration: ::DWORD, + usrmod3_lockout_observation_window: ::DWORD, + usrmod3_lockout_threshold: ::DWORD, +}} +pub type PUSER_MODALS_INFO_3 = *mut USER_MODALS_INFO_3; +pub type LPUSER_MODALS_INFO_3 = *mut USER_MODALS_INFO_3; +STRUCT!{struct USER_MODALS_INFO_1001 { + usrmod1001_min_passwd_len: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1001 = *mut USER_MODALS_INFO_1001; +pub type LPUSER_MODALS_INFO_1001 = *mut USER_MODALS_INFO_1001; +STRUCT!{struct USER_MODALS_INFO_1002 { + usrmod1002_max_passwd_age: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1002 = *mut USER_MODALS_INFO_1002; +pub type LPUSER_MODALS_INFO_1002 = *mut USER_MODALS_INFO_1002; +STRUCT!{struct USER_MODALS_INFO_1003 { + usrmod1003_min_passwd_age: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1003 = *mut USER_MODALS_INFO_1003; +pub type LPUSER_MODALS_INFO_1003 = *mut USER_MODALS_INFO_1003; +STRUCT!{struct USER_MODALS_INFO_1004 { + usrmod1004_force_logoff: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1004 = *mut USER_MODALS_INFO_1004; +pub type LPUSER_MODALS_INFO_1004 = *mut USER_MODALS_INFO_1004; +STRUCT!{struct USER_MODALS_INFO_1005 { + usrmod1005_password_hist_len: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1005 = *mut USER_MODALS_INFO_1005; +pub type LPUSER_MODALS_INFO_1005 = *mut USER_MODALS_INFO_1005; +STRUCT!{struct USER_MODALS_INFO_1006 { + usrmod1006_role: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1006 = *mut USER_MODALS_INFO_1006; +pub type LPUSER_MODALS_INFO_1006 = *mut USER_MODALS_INFO_1006; +STRUCT!{struct USER_MODALS_INFO_1007 { + usrmod1007_primary: ::LPWSTR, +}} +pub type PUSER_MODALS_INFO_1007 = *mut USER_MODALS_INFO_1007; +pub type LPUSER_MODALS_INFO_1007 = *mut USER_MODALS_INFO_1007; +pub const UF_SCRIPT: ::DWORD = 0x0001; +pub const UF_ACCOUNTDISABLE: ::DWORD = 0x0002; +pub const UF_HOMEDIR_REQUIRED: ::DWORD = 0x0008; +pub const UF_LOCKOUT: ::DWORD = 0x0010; +pub const UF_PASSWD_NOTREQD: ::DWORD = 0x0020; +pub const UF_PASSWD_CANT_CHANGE: ::DWORD = 0x0040; +pub const UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: ::DWORD = 0x0080; +pub const UF_TEMP_DUPLICATE_ACCOUNT: ::DWORD = 0x0100; +pub const UF_NORMAL_ACCOUNT: ::DWORD = 0x0200; +pub const UF_INTERDOMAIN_TRUST_ACCOUNT: ::DWORD = 0x0800; +pub const UF_WORKSTATION_TRUST_ACCOUNT: ::DWORD = 0x1000; +pub const UF_SERVER_TRUST_ACCOUNT: ::DWORD = 0x2000; +pub const UF_MACHINE_ACCOUNT_MASK: ::DWORD = UF_INTERDOMAIN_TRUST_ACCOUNT + | UF_WORKSTATION_TRUST_ACCOUNT | UF_SERVER_TRUST_ACCOUNT; +pub const UF_ACCOUNT_TYPE_MASK: ::DWORD = UF_TEMP_DUPLICATE_ACCOUNT | UF_NORMAL_ACCOUNT + | UF_INTERDOMAIN_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT | UF_SERVER_TRUST_ACCOUNT; +pub const UF_DONT_EXPIRE_PASSWD: ::DWORD = 0x10000; +pub const UF_MNS_LOGON_ACCOUNT: ::DWORD = 0x20000; +pub const UF_SMARTCARD_REQUIRED: ::DWORD = 0x40000; +pub const UF_TRUSTED_FOR_DELEGATION: ::DWORD = 0x80000; +pub const UF_NOT_DELEGATED: ::DWORD = 0x100000; +pub const UF_USE_DES_KEY_ONLY: ::DWORD = 0x200000; +pub const UF_DONT_REQUIRE_PREAUTH: ::DWORD = 0x400000; +pub const UF_PASSWORD_EXPIRED: ::DWORD = 0x800000; +pub const UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: ::DWORD = 0x1000000; +pub const UF_NO_AUTH_DATA_REQUIRED: ::DWORD = 0x2000000; +pub const UF_PARTIAL_SECRETS_ACCOUNT: ::DWORD = 0x4000000; +pub const UF_USE_AES_KEYS: ::DWORD = 0x8000000; +pub const UF_SETTABLE_BITS: ::DWORD = UF_SCRIPT | UF_ACCOUNTDISABLE | UF_LOCKOUT + | UF_HOMEDIR_REQUIRED | UF_PASSWD_NOTREQD | UF_PASSWD_CANT_CHANGE | UF_ACCOUNT_TYPE_MASK + | UF_DONT_EXPIRE_PASSWD | UF_MNS_LOGON_ACCOUNT | UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED + | UF_SMARTCARD_REQUIRED | UF_TRUSTED_FOR_DELEGATION | UF_NOT_DELEGATED | UF_USE_DES_KEY_ONLY + | UF_DONT_REQUIRE_PREAUTH | UF_PASSWORD_EXPIRED | UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION + | UF_NO_AUTH_DATA_REQUIRED | UF_USE_AES_KEYS | UF_PARTIAL_SECRETS_ACCOUNT; +pub const FILTER_TEMP_DUPLICATE_ACCOUNT: ::DWORD = 0x0001; +pub const FILTER_NORMAL_ACCOUNT: ::DWORD = 0x0002; +pub const FILTER_INTERDOMAIN_TRUST_ACCOUNT: ::DWORD = 0x0008; +pub const FILTER_WORKSTATION_TRUST_ACCOUNT: ::DWORD = 0x0010; +pub const FILTER_SERVER_TRUST_ACCOUNT: ::DWORD = 0x0020; +pub const LG_INCLUDE_INDIRECT: ::DWORD = 0x0001; +pub const AF_OP_PRINT: ::DWORD = 0x1; +pub const AF_OP_COMM: ::DWORD = 0x2; +pub const AF_OP_SERVER: ::DWORD = 0x4; +pub const AF_OP_ACCOUNTS: ::DWORD = 0x8; +pub const AF_SETTABLE_BITS: ::DWORD = AF_OP_PRINT | AF_OP_COMM | AF_OP_SERVER | AF_OP_ACCOUNTS; +pub const UAS_ROLE_STANDALONE: ::DWORD = 0; +pub const UAS_ROLE_MEMBER: ::DWORD = 1; +pub const UAS_ROLE_BACKUP: ::DWORD = 2; +pub const UAS_ROLE_PRIMARY: ::DWORD = 3; +pub const USER_NAME_PARMNUM: ::DWORD = 1; +pub const USER_PASSWORD_PARMNUM: ::DWORD = 3; +pub const USER_PASSWORD_AGE_PARMNUM: ::DWORD = 4; +pub const USER_PRIV_PARMNUM: ::DWORD = 5; +pub const USER_HOME_DIR_PARMNUM: ::DWORD = 6; +pub const USER_COMMENT_PARMNUM: ::DWORD = 7; +pub const USER_FLAGS_PARMNUM: ::DWORD = 8; +pub const USER_SCRIPT_PATH_PARMNUM: ::DWORD = 9; +pub const USER_AUTH_FLAGS_PARMNUM: ::DWORD = 10; +pub const USER_FULL_NAME_PARMNUM: ::DWORD = 11; +pub const USER_USR_COMMENT_PARMNUM: ::DWORD = 12; +pub const USER_PARMS_PARMNUM: ::DWORD = 13; +pub const USER_WORKSTATIONS_PARMNUM: ::DWORD = 14; +pub const USER_LAST_LOGON_PARMNUM: ::DWORD = 15; +pub const USER_LAST_LOGOFF_PARMNUM: ::DWORD = 16; +pub const USER_ACCT_EXPIRES_PARMNUM: ::DWORD = 17; +pub const USER_MAX_STORAGE_PARMNUM: ::DWORD = 18; +pub const USER_UNITS_PER_WEEK_PARMNUM: ::DWORD = 19; +pub const USER_LOGON_HOURS_PARMNUM: ::DWORD = 20; +pub const USER_PAD_PW_COUNT_PARMNUM: ::DWORD = 21; +pub const USER_NUM_LOGONS_PARMNUM: ::DWORD = 22; +pub const USER_LOGON_SERVER_PARMNUM: ::DWORD = 23; +pub const USER_COUNTRY_CODE_PARMNUM: ::DWORD = 24; +pub const USER_CODE_PAGE_PARMNUM: ::DWORD = 25; +pub const USER_PRIMARY_GROUP_PARMNUM: ::DWORD = 51; +pub const USER_PROFILE: ::DWORD = 52; +pub const USER_PROFILE_PARMNUM: ::DWORD = 52; +pub const USER_HOME_DIR_DRIVE_PARMNUM: ::DWORD = 53; +pub const USER_NAME_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_NAME_PARMNUM; +pub const USER_PASSWORD_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_PASSWORD_PARMNUM; +pub const USER_PASSWORD_AGE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_PASSWORD_AGE_PARMNUM; +pub const USER_PRIV_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_PRIV_PARMNUM; +pub const USER_HOME_DIR_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_HOME_DIR_PARMNUM; +pub const USER_COMMENT_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_COMMENT_PARMNUM; +pub const USER_FLAGS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_FLAGS_PARMNUM; +pub const USER_SCRIPT_PATH_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_SCRIPT_PATH_PARMNUM; +pub const USER_AUTH_FLAGS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_AUTH_FLAGS_PARMNUM; +pub const USER_FULL_NAME_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_FULL_NAME_PARMNUM; +pub const USER_USR_COMMENT_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_USR_COMMENT_PARMNUM; +pub const USER_PARMS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_PARMS_PARMNUM; +pub const USER_WORKSTATIONS_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_WORKSTATIONS_PARMNUM; +pub const USER_LAST_LOGON_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_LAST_LOGON_PARMNUM; +pub const USER_LAST_LOGOFF_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_LAST_LOGOFF_PARMNUM; +pub const USER_ACCT_EXPIRES_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_ACCT_EXPIRES_PARMNUM; +pub const USER_MAX_STORAGE_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_MAX_STORAGE_PARMNUM; +pub const USER_UNITS_PER_WEEK_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_UNITS_PER_WEEK_PARMNUM; +pub const USER_LOGON_HOURS_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_LOGON_HOURS_PARMNUM; +pub const USER_PAD_PW_COUNT_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_PAD_PW_COUNT_PARMNUM; +pub const USER_NUM_LOGONS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_NUM_LOGONS_PARMNUM; +pub const USER_LOGON_SERVER_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_LOGON_SERVER_PARMNUM; +pub const USER_COUNTRY_CODE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_COUNTRY_CODE_PARMNUM; +pub const USER_CODE_PAGE_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_CODE_PAGE_PARMNUM; +pub const USER_PRIMARY_GROUP_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_PRIMARY_GROUP_PARMNUM; +pub const USER_HOME_DIR_DRIVE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_HOME_DIR_DRIVE_PARMNUM; +pub const TIMEQ_FOREVER: ::DWORD = -1i32 as ::DWORD; +pub const USER_MAXSTORAGE_UNLIMITED: ::DWORD = -1i32 as ::DWORD; +pub const USER_NO_LOGOFF: ::DWORD = -1i32 as ::DWORD; +pub const UNITS_PER_DAY: ::DWORD = 24; +pub const UNITS_PER_WEEK: ::DWORD = UNITS_PER_DAY * 7; +pub const USER_PRIV_MASK: ::DWORD = 0x3; +pub const USER_PRIV_GUEST: ::DWORD = 0; +pub const USER_PRIV_USER: ::DWORD = 1; +pub const USER_PRIV_ADMIN: ::DWORD = 2; +pub const MAX_PASSWD_LEN: ::DWORD = ::PWLEN; +pub const DEF_MIN_PWLEN: ::DWORD = 6; +pub const DEF_PWUNIQUENESS: ::DWORD = 5; +pub const DEF_MAX_PWHIST: ::DWORD = 8; +pub const DEF_MAX_PWAGE: ::DWORD = TIMEQ_FOREVER; +pub const DEF_MIN_PWAGE: ::DWORD = 0; +pub const DEF_FORCE_LOGOFF: ::DWORD = 0xffffffff; +pub const DEF_MAX_BADPW: ::DWORD = 0; +pub const ONE_DAY: ::DWORD = 1 * 24 * 3600; +pub const VALIDATED_LOGON: ::DWORD = 0; +pub const PASSWORD_EXPIRED: ::DWORD = 2; +pub const NON_VALIDATED_LOGON: ::DWORD = 3; +pub const VALID_LOGOFF: ::DWORD = 1; +pub const MODALS_MIN_PASSWD_LEN_PARMNUM: ::DWORD = 1; +pub const MODALS_MAX_PASSWD_AGE_PARMNUM: ::DWORD = 2; +pub const MODALS_MIN_PASSWD_AGE_PARMNUM: ::DWORD = 3; +pub const MODALS_FORCE_LOGOFF_PARMNUM: ::DWORD = 4; +pub const MODALS_PASSWD_HIST_LEN_PARMNUM: ::DWORD = 5; +pub const MODALS_ROLE_PARMNUM: ::DWORD = 6; +pub const MODALS_PRIMARY_PARMNUM: ::DWORD = 7; +pub const MODALS_DOMAIN_NAME_PARMNUM: ::DWORD = 8; +pub const MODALS_DOMAIN_ID_PARMNUM: ::DWORD = 9; +pub const MODALS_LOCKOUT_DURATION_PARMNUM: ::DWORD = 10; +pub const MODALS_LOCKOUT_OBSERVATION_WINDOW_PARMNUM: ::DWORD = 11; +pub const MODALS_LOCKOUT_THRESHOLD_PARMNUM: ::DWORD = 12; +pub const MODALS_MIN_PASSWD_LEN_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_MIN_PASSWD_LEN_PARMNUM; +pub const MODALS_MAX_PASSWD_AGE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_MAX_PASSWD_AGE_PARMNUM; +pub const MODALS_MIN_PASSWD_AGE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_MIN_PASSWD_AGE_PARMNUM; +pub const MODALS_FORCE_LOGOFF_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_FORCE_LOGOFF_PARMNUM; +pub const MODALS_PASSWD_HIST_LEN_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_PASSWD_HIST_LEN_PARMNUM; +pub const MODALS_ROLE_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + MODALS_ROLE_PARMNUM; +pub const MODALS_PRIMARY_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + MODALS_PRIMARY_PARMNUM; +pub const MODALS_DOMAIN_NAME_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_DOMAIN_NAME_PARMNUM; +pub const MODALS_DOMAIN_ID_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + MODALS_DOMAIN_ID_PARMNUM; +STRUCT!{struct GROUP_INFO_0 { + grpi0_name: ::LPWSTR, +}} +pub type PGROUP_INFO_0 = *mut GROUP_INFO_0; +pub type LPGROUP_INFO_0 = *mut GROUP_INFO_0; +STRUCT!{struct GROUP_INFO_1 { + grpi1_name: ::LPWSTR, + grpi1_comment: ::LPWSTR, +}} +pub type PGROUP_INFO_1 = *mut GROUP_INFO_1; +pub type LPGROUP_INFO_1 = *mut GROUP_INFO_1; +STRUCT!{struct GROUP_INFO_2 { + grpi2_name: ::LPWSTR, + grpi2_comment: ::LPWSTR, + grpi2_group_id: ::DWORD, + grpi2_attributes: ::DWORD, +}} +pub type PGROUP_INFO_2 = *mut GROUP_INFO_2; +STRUCT!{struct GROUP_INFO_3 { + grpi3_name: ::LPWSTR, + grpi3_comment: ::LPWSTR, + grpi3_group_sid: ::PSID, + grpi3_attributes: ::DWORD, +}} +pub type PGROUP_INFO_3 = *mut GROUP_INFO_3; +STRUCT!{struct GROUP_INFO_1002 { + grpi1002_comment: ::LPWSTR, +}} +pub type PGROUP_INFO_1002 = *mut GROUP_INFO_1002; +pub type LPGROUP_INFO_1002 = *mut GROUP_INFO_1002; +STRUCT!{struct GROUP_INFO_1005 { + grpi1005_attributes: ::DWORD, +}} +pub type PGROUP_INFO_1005 = *mut GROUP_INFO_1005; +pub type LPGROUP_INFO_1005 = *mut GROUP_INFO_1005; +STRUCT!{struct GROUP_USERS_INFO_0 { + grui0_name: ::LPWSTR, +}} +pub type PGROUP_USERS_INFO_0 = *mut GROUP_USERS_INFO_0; +pub type LPGROUP_USERS_INFO_0 = *mut GROUP_USERS_INFO_0; +STRUCT!{struct GROUP_USERS_INFO_1 { + grui1_name: ::LPWSTR, + grui1_attributes: ::DWORD, +}} +pub type PGROUP_USERS_INFO_1 = *mut GROUP_USERS_INFO_1; +pub type LPGROUP_USERS_INFO_1 = *mut GROUP_USERS_INFO_1; +pub const GROUPIDMASK: ::DWORD = 0x8000; +pub const GROUP_SPECIALGRP_USERS: &'static str = "USERS"; +pub const GROUP_SPECIALGRP_ADMINS: &'static str = "ADMINS"; +pub const GROUP_SPECIALGRP_GUESTS: &'static str = "GUESTS"; +pub const GROUP_SPECIALGRP_LOCAL: &'static str = "LOCAL"; +pub const GROUP_ALL_PARMNUM: ::DWORD = 0; +pub const GROUP_NAME_PARMNUM: ::DWORD = 1; +pub const GROUP_COMMENT_PARMNUM: ::DWORD = 2; +pub const GROUP_ATTRIBUTES_PARMNUM: ::DWORD = 3; +pub const GROUP_ALL_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_ALL_PARMNUM; +pub const GROUP_NAME_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_NAME_PARMNUM; +pub const GROUP_COMMENT_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_COMMENT_PARMNUM; +pub const GROUP_ATTRIBUTES_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_ATTRIBUTES_PARMNUM; +STRUCT!{struct LOCALGROUP_INFO_0 { + lgrpi0_name: ::LPWSTR, +}} +pub type PLOCALGROUP_INFO_0 = *mut LOCALGROUP_INFO_0; +pub type LPLOCALGROUP_INFO_0 = *mut LOCALGROUP_INFO_0; +STRUCT!{struct LOCALGROUP_INFO_1 { + lgrpi1_name: ::LPWSTR, + lgrpi1_comment: ::LPWSTR, +}} +pub type PLOCALGROUP_INFO_1 = *mut LOCALGROUP_INFO_1; +pub type LPLOCALGROUP_INFO_1 = *mut LOCALGROUP_INFO_1; +STRUCT!{struct LOCALGROUP_INFO_1002 { + lgrpi1002_comment: ::LPWSTR, +}} +pub type PLOCALGROUP_INFO_1002 = *mut LOCALGROUP_INFO_1002; +pub type LPLOCALGROUP_INFO_1002 = *mut LOCALGROUP_INFO_1002; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_0 { + lgrmi0_sid: ::PSID, +}} +pub type PLOCALGROUP_MEMBERS_INFO_0 = *mut LOCALGROUP_MEMBERS_INFO_0; +pub type LPLOCALGROUP_MEMBERS_INFO_0 = *mut LOCALGROUP_MEMBERS_INFO_0; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_1 { + lgrmi1_sid: ::PSID, + lgrmi1_sidusage: ::SID_NAME_USE, + lgrmi1_name: ::LPWSTR, +}} +pub type PLOCALGROUP_MEMBERS_INFO_1 = *mut LOCALGROUP_MEMBERS_INFO_1; +pub type LPLOCALGROUP_MEMBERS_INFO_1 = *mut LOCALGROUP_MEMBERS_INFO_1; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_2 { + lgrmi2_sid: ::PSID, + lgrmi2_sidusage: ::SID_NAME_USE, + lgrmi2_domainandname: ::LPWSTR, +}} +pub type PLOCALGROUP_MEMBERS_INFO_2 = *mut LOCALGROUP_MEMBERS_INFO_2; +pub type LPLOCALGROUP_MEMBERS_INFO_2 = *mut LOCALGROUP_MEMBERS_INFO_2; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_3 { + lgrmi3_domainandname: ::LPWSTR, +}} +pub type PLOCALGROUP_MEMBERS_INFO_3 = *mut LOCALGROUP_MEMBERS_INFO_3; +pub type LPLOCALGROUP_MEMBERS_INFO_3 = *mut LOCALGROUP_MEMBERS_INFO_3; +STRUCT!{struct LOCALGROUP_USERS_INFO_0 { + lgrui0_name: ::LPWSTR, +}} +pub type PLOCALGROUP_USERS_INFO_0 = *mut LOCALGROUP_USERS_INFO_0; +pub type LPLOCALGROUP_USERS_INFO_0 = *mut LOCALGROUP_USERS_INFO_0; +pub const LOCALGROUP_NAME_PARMNUM: ::DWORD = 1; +pub const LOCALGROUP_COMMENT_PARMNUM: ::DWORD = 2; +STRUCT!{struct NET_DISPLAY_USER { + usri1_name: ::LPWSTR, + usri1_comment: ::LPWSTR, + usri1_flags: ::DWORD, + usri1_full_name: ::LPWSTR, + usri1_user_id: ::DWORD, + usri1_next_index: ::DWORD, +}} +pub type PNET_DISPLAY_USER = *mut NET_DISPLAY_USER; +STRUCT!{struct NET_DISPLAY_MACHINE { + usri2_name: ::LPWSTR, + usri2_comment: ::LPWSTR, + usri2_flags: ::DWORD, + usri2_user_id: ::DWORD, + usri2_next_index: ::DWORD, +}} +pub type PNET_DISPLAY_MACHINE = *mut NET_DISPLAY_MACHINE; +STRUCT!{struct NET_DISPLAY_GROUP { + usri3_name: ::LPWSTR, + usri3_comment: ::LPWSTR, + grpi3_group_id: ::DWORD, + grpi3_attributes: ::DWORD, + grpi3_next_index: ::DWORD, +}} +pub type PNET_DISPLAY_GROUP = *mut NET_DISPLAY_GROUP; +STRUCT!{struct ACCESS_INFO_0 { + acc0_resource_name: ::LPWSTR, +}} +pub type PACCESS_INFO_0 = *mut ACCESS_INFO_0; +pub type LPACCESS_INFO_0 = *mut ACCESS_INFO_0; +STRUCT!{struct ACCESS_INFO_1 { + acc1_resource_name: ::LPWSTR, + acc1_attr: ::DWORD, + acc1_count: ::DWORD, +}} +pub type PACCESS_INFO_1 = *mut ACCESS_INFO_1; +pub type LPACCESS_INFO_1 = *mut ACCESS_INFO_1; +STRUCT!{struct ACCESS_INFO_1002 { + acc1002_attr: ::DWORD, +}} +pub type PACCESS_INFO_1002 = *mut ACCESS_INFO_1002; +pub type LPACCESS_INFO_1002 = *mut ACCESS_INFO_1002; +STRUCT!{struct ACCESS_LIST { + acl_ugname: ::LPWSTR, + acl_access: ::DWORD, +}} +pub type PACCESS_LIST = *mut ACCESS_LIST; +pub type LPACCESS_LIST = *mut ACCESS_LIST; +pub const ACCESS_NONE: ::DWORD = 0; +pub const ACCESS_ALL: ::DWORD = ACCESS_READ | ACCESS_WRITE | ACCESS_CREATE | ACCESS_EXEC + | ACCESS_DELETE | ACCESS_ATRIB | ACCESS_PERM; +pub const ACCESS_READ: ::DWORD = 0x01; +pub const ACCESS_WRITE: ::DWORD = 0x02; +pub const ACCESS_CREATE: ::DWORD = 0x04; +pub const ACCESS_EXEC: ::DWORD = 0x08; +pub const ACCESS_DELETE: ::DWORD = 0x10; +pub const ACCESS_ATRIB: ::DWORD = 0x20; +pub const ACCESS_PERM: ::DWORD = 0x40; +pub const ACCESS_GROUP: ::DWORD = 0x8000; +pub const ACCESS_AUDIT: ::DWORD = 0x1; +pub const ACCESS_SUCCESS_OPEN: ::DWORD = 0x10; +pub const ACCESS_SUCCESS_WRITE: ::DWORD = 0x20; +pub const ACCESS_SUCCESS_DELETE: ::DWORD = 0x40; +pub const ACCESS_SUCCESS_ACL: ::DWORD = 0x80; +pub const ACCESS_SUCCESS_MASK: ::DWORD = 0xF0; +pub const ACCESS_FAIL_OPEN: ::DWORD = 0x100; +pub const ACCESS_FAIL_WRITE: ::DWORD = 0x200; +pub const ACCESS_FAIL_DELETE: ::DWORD = 0x400; +pub const ACCESS_FAIL_ACL: ::DWORD = 0x800; +pub const ACCESS_FAIL_MASK: ::DWORD = 0xF00; +pub const ACCESS_FAIL_SHIFT: ::DWORD = 4; +pub const ACCESS_RESOURCE_NAME_PARMNUM: ::DWORD = 1; +pub const ACCESS_ATTR_PARMNUM: ::DWORD = 2; +pub const ACCESS_COUNT_PARMNUM: ::DWORD = 3; +pub const ACCESS_ACCESS_LIST_PARMNUM: ::DWORD = 4; +pub const ACCESS_RESOURCE_NAME_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + ACCESS_RESOURCE_NAME_PARMNUM; +pub const ACCESS_ATTR_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + ACCESS_ATTR_PARMNUM; +pub const ACCESS_COUNT_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + ACCESS_COUNT_PARMNUM; +pub const ACCESS_ACCESS_LIST_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + ACCESS_ACCESS_LIST_PARMNUM; +ENUM!{enum NET_VALIDATE_PASSWORD_TYPE { + NetValidateAuthentication = 1, + NetValidatePasswordChange, + NetValidatePasswordReset, +}} +pub type PNET_VALIDATE_PASSWORD_TYPE = *mut NET_VALIDATE_PASSWORD_TYPE; +STRUCT!{struct NET_VALIDATE_PASSWORD_HASH { + Length: ::ULONG, + Hash: ::LPBYTE, +}} +pub type PNET_VALIDATE_PASSWORD_HASH = *mut NET_VALIDATE_PASSWORD_HASH; +pub const NET_VALIDATE_PASSWORD_LAST_SET: ::ULONG = 0x00000001; +pub const NET_VALIDATE_BAD_PASSWORD_TIME: ::ULONG = 0x00000002; +pub const NET_VALIDATE_LOCKOUT_TIME: ::ULONG = 0x00000004; +pub const NET_VALIDATE_BAD_PASSWORD_COUNT: ::ULONG = 0x00000008; +pub const NET_VALIDATE_PASSWORD_HISTORY_LENGTH: ::ULONG = 0x00000010; +pub const NET_VALIDATE_PASSWORD_HISTORY: ::ULONG = 0x00000020; +STRUCT!{struct NET_VALIDATE_PERSISTED_FIELDS { + PresentFields: ::ULONG, + PasswordLastSet: ::FILETIME, + BadPasswordTime: ::FILETIME, + LockoutTime: ::FILETIME, + BadPasswordCount: ::ULONG, + PasswordHistoryLength: ::ULONG, + PasswordHistory: PNET_VALIDATE_PASSWORD_HASH, +}} +pub type PNET_VALIDATE_PERSISTED_FIELDS = *mut NET_VALIDATE_PERSISTED_FIELDS; +STRUCT!{struct NET_VALIDATE_OUTPUT_ARG { + ChangedPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + ValidationStatus: ::NET_API_STATUS, +}} +pub type PNET_VALIDATE_OUTPUT_ARG = *mut NET_VALIDATE_OUTPUT_ARG; +STRUCT!{struct NET_VALIDATE_AUTHENTICATION_INPUT_ARG { + InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + PasswordMatched: ::BOOLEAN, +}} +pub type PNET_VALIDATE_AUTHENTICATION_INPUT_ARG = *mut NET_VALIDATE_AUTHENTICATION_INPUT_ARG; +STRUCT!{struct NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG { + InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + ClearPassword: ::LPWSTR, + UserAccountName: ::LPWSTR, + HashedPassword: NET_VALIDATE_PASSWORD_HASH, + PasswordMatch: ::BOOLEAN, +}} +pub type PNET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG = *mut NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG; +STRUCT!{struct NET_VALIDATE_PASSWORD_RESET_INPUT_ARG { + InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + ClearPassword: ::LPWSTR, + UserAccountName: ::LPWSTR, + HashedPassword: NET_VALIDATE_PASSWORD_HASH, + PasswordMustChangeAtNextLogon: ::BOOLEAN, + ClearLockout: ::BOOLEAN, +}} +pub type PNET_VALIDATE_PASSWORD_RESET_INPUT_ARG = *mut NET_VALIDATE_PASSWORD_RESET_INPUT_ARG; +pub const NETLOGON_CONTROL_QUERY: ::DWORD = 1; +pub const NETLOGON_CONTROL_REPLICATE: ::DWORD = 2; +pub const NETLOGON_CONTROL_SYNCHRONIZE: ::DWORD = 3; +pub const NETLOGON_CONTROL_PDC_REPLICATE: ::DWORD = 4; +pub const NETLOGON_CONTROL_REDISCOVER: ::DWORD = 5; +pub const NETLOGON_CONTROL_TC_QUERY: ::DWORD = 6; +pub const NETLOGON_CONTROL_TRANSPORT_NOTIFY: ::DWORD = 7; +pub const NETLOGON_CONTROL_FIND_USER: ::DWORD = 8; +pub const NETLOGON_CONTROL_CHANGE_PASSWORD: ::DWORD = 9; +pub const NETLOGON_CONTROL_TC_VERIFY: ::DWORD = 10; +pub const NETLOGON_CONTROL_FORCE_DNS_REG: ::DWORD = 11; +pub const NETLOGON_CONTROL_QUERY_DNS_REG: ::DWORD = 12; +pub const NETLOGON_CONTROL_UNLOAD_NETLOGON_DLL: ::DWORD = 0xFFFB; +pub const NETLOGON_CONTROL_BACKUP_CHANGE_LOG: ::DWORD = 0xFFFC; +pub const NETLOGON_CONTROL_TRUNCATE_LOG: ::DWORD = 0xFFFD; +pub const NETLOGON_CONTROL_SET_DBFLAG: ::DWORD = 0xFFFE; +pub const NETLOGON_CONTROL_BREAKPOINT: ::DWORD = 0xFFFF; +STRUCT!{struct NETLOGON_INFO_1 { + netlog1_flags: ::DWORD, + netlog1_pdc_connection_status: ::NET_API_STATUS, +}} +pub type PNETLOGON_INFO_1 = *mut NETLOGON_INFO_1; +STRUCT!{struct NETLOGON_INFO_2 { + netlog2_flags: ::DWORD, + netlog2_pdc_connection_status: ::NET_API_STATUS, + netlog2_trusted_dc_name: ::LPWSTR, + netlog2_tc_connection_status: ::NET_API_STATUS, +}} +pub type PNETLOGON_INFO_2 = *mut NETLOGON_INFO_2; +STRUCT!{struct NETLOGON_INFO_3 { + netlog3_flags: ::DWORD, + netlog3_logon_attempts: ::DWORD, + netlog3_reserved1: ::DWORD, + netlog3_reserved2: ::DWORD, + netlog3_reserved3: ::DWORD, + netlog3_reserved4: ::DWORD, + netlog3_reserved5: ::DWORD, +}} +pub type PNETLOGON_INFO_3 = *mut NETLOGON_INFO_3; +STRUCT!{struct NETLOGON_INFO_4 { + netlog4_trusted_dc_name: ::LPWSTR, + netlog4_trusted_domain_name: ::LPWSTR, +}} +pub type PNETLOGON_INFO_4 = *mut NETLOGON_INFO_4; +pub const NETLOGON_REPLICATION_NEEDED: ::DWORD = 0x01; +pub const NETLOGON_REPLICATION_IN_PROGRESS: ::DWORD = 0x02; +pub const NETLOGON_FULL_SYNC_REPLICATION: ::DWORD = 0x04; +pub const NETLOGON_REDO_NEEDED: ::DWORD = 0x08; +pub const NETLOGON_HAS_IP: ::DWORD = 0x10; +pub const NETLOGON_HAS_TIMESERV: ::DWORD = 0x20; +pub const NETLOGON_DNS_UPDATE_FAILURE: ::DWORD = 0x40; +pub const NETLOGON_VERIFY_STATUS_RETURNED: ::DWORD = 0x80; +DEFINE_GUID!(ServiceAccountPasswordGUID, 0x262E99C9, 0x6160, 0x4871, + 0xAC, 0xEC, 0x4E, 0x61, 0x73, 0x6B, 0x6F, 0x21); +pub const SERVICE_ACCOUNT_FLAG_LINK_TO_HOST_ONLY: ::DWORD = 0x00000001; +pub const SERVICE_ACCOUNT_FLAG_ADD_AGAINST_RODC: ::DWORD = 0x00000002; +pub const SERVICE_ACCOUNT_FLAG_UNLINK_FROM_HOST_ONLY: ::DWORD = 0x00000001; +pub const SERVICE_ACCOUNT_FLAG_REMOVE_OFFLINE: ::DWORD = 0x00000002; +ENUM!{enum MSA_INFO_LEVEL { + MsaInfoLevel0 = 0, + MsaInfoLevelMax, +}} +pub type PMSA_INFO_LEVEL = *mut MSA_INFO_LEVEL; +ENUM!{enum MSA_INFO_STATE { + MsaInfoNotExist = 1, + MsaInfoNotService, + MsaInfoCannotInstall, + MsaInfoCanInstall, + MsaInfoInstalled, +}} +pub type PMSA_INFO_STATE = *mut MSA_INFO_STATE; +STRUCT!{struct MSA_INFO_0 { + State: MSA_INFO_STATE, +}} +pub type PMSA_INFO_0 = *mut MSA_INFO_0; +pub type LPMSA_INFO_0 = *mut MSA_INFO_0; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lmcons.rs b/bash-5.1/vendor/winapi-0.2.8/src/lmcons.rs new file mode 100644 index 0000000..267db8b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lmcons.rs @@ -0,0 +1,55 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This file contains constants used throughout the LAN Manager API header files. +pub const CNLEN: ::DWORD = 15; +pub const LM20_CNLEN: ::DWORD = 15; +pub const DNLEN: ::DWORD = CNLEN; +pub const LM20_DNLEN: ::DWORD = LM20_CNLEN; +pub const UNCLEN: ::DWORD = CNLEN + 2; +pub const LM20_UNCLEN: ::DWORD = LM20_CNLEN + 2; +pub const NNLEN: ::DWORD = 80; +pub const LM20_NNLEN: ::DWORD = 12; +pub const RMLEN: ::DWORD = UNCLEN + 1 + NNLEN; +pub const LM20_RMLEN: ::DWORD = LM20_UNCLEN + 1 + LM20_NNLEN; +pub const SNLEN: ::DWORD = 80; +pub const LM20_SNLEN: ::DWORD = 15; +pub const STXTLEN: ::DWORD = 256; +pub const LM20_STXTLEN: ::DWORD = 63; +pub const PATHLEN: ::DWORD = 256; +pub const LM20_PATHLEN: ::DWORD = 256; +pub const DEVLEN: ::DWORD = 80; +pub const LM20_DEVLEN: ::DWORD = 8; +pub const EVLEN: ::DWORD = 16; +pub const UNLEN: ::DWORD = 256; +pub const LM20_UNLEN: ::DWORD = 20; +pub const GNLEN: ::DWORD = UNLEN; +pub const LM20_GNLEN: ::DWORD = LM20_UNLEN; +pub const PWLEN: ::DWORD = 256; +pub const LM20_PWLEN: ::DWORD = 14; +pub const SHPWLEN: ::DWORD = 8; +pub const CLTYPE_LEN: ::DWORD = 12; +pub const MAXCOMMENTSZ: ::DWORD = 256; +pub const LM20_MAXCOMMENTSZ: ::DWORD = 48; +pub const QNLEN: ::DWORD = NNLEN; +pub const LM20_QNLEN: ::DWORD = LM20_NNLEN; +pub const ALERTSZ: ::DWORD = 128; +pub const MAXDEVENTRIES: ::DWORD = 4 * 8; // FIXME: sizeof(int) instead of 4 +pub const NETBIOS_NAME_LEN: ::DWORD = 16; +pub const MAX_PREFERRED_LENGTH: ::DWORD = -1i32 as ::DWORD; +pub const CRYPT_KEY_LEN: ::DWORD = 7; +pub const CRYPT_TXT_LEN: ::DWORD = 8; +pub const ENCRYPTED_PWLEN: usize = 16; +pub const SESSION_PWLEN: ::DWORD = 24; +pub const SESSION_CRYPT_KLEN: ::DWORD = 21; +pub const PARM_ERROR_UNKNOWN: ::DWORD = -1i32 as ::DWORD; +pub const PARM_ERROR_NONE: ::DWORD = 0; +pub const PARMNUM_BASE_INFOLEVEL: ::DWORD = 1000; +pub type LMSTR = ::LPWSTR; +pub type LMCSTR = ::LPCWSTR; +pub type NET_API_STATUS = ::DWORD; +pub type API_RET_TYPE = NET_API_STATUS; +pub const PLATFORM_ID_DOS: ::DWORD = 300; +pub const PLATFORM_ID_OS2: ::DWORD = 400; +pub const PLATFORM_ID_NT: ::DWORD = 500; +pub const PLATFORM_ID_OSF: ::DWORD = 600; +pub const PLATFORM_ID_VMS: ::DWORD = 700; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lmdfs.rs b/bash-5.1/vendor/winapi-0.2.8/src/lmdfs.rs new file mode 100644 index 0000000..b74c647 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lmdfs.rs @@ -0,0 +1,311 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +// This file contains structures, function prototypes, and definitions for the NetDfs API +pub const DFS_VOLUME_STATES: ::DWORD = 0xF; +pub const DFS_VOLUME_STATE_OK: ::DWORD = 1; +pub const DFS_VOLUME_STATE_INCONSISTENT: ::DWORD = 2; +pub const DFS_VOLUME_STATE_OFFLINE: ::DWORD = 3; +pub const DFS_VOLUME_STATE_ONLINE: ::DWORD = 4; +pub const DFS_VOLUME_STATE_RESYNCHRONIZE: ::DWORD = 0x10; +pub const DFS_VOLUME_STATE_STANDBY: ::DWORD = 0x20; +pub const DFS_VOLUME_STATE_FORCE_SYNC: ::DWORD = 0x40; +pub const DFS_VOLUME_FLAVORS: ::DWORD = 0x0300; +pub const DFS_VOLUME_FLAVOR_UNUSED1: ::DWORD = 0x0000; +pub const DFS_VOLUME_FLAVOR_STANDALONE: ::DWORD = 0x0100; +pub const DFS_VOLUME_FLAVOR_AD_BLOB: ::DWORD = 0x0200; +pub const DFS_STORAGE_FLAVOR_UNUSED2: ::DWORD = 0x0300; +pub const DFS_STORAGE_STATES: ::ULONG = 0xF; +pub const DFS_STORAGE_STATE_OFFLINE: ::ULONG = 1; +pub const DFS_STORAGE_STATE_ONLINE: ::ULONG = 2; +pub const DFS_STORAGE_STATE_ACTIVE: ::ULONG = 4; +ENUM!{enum DFS_TARGET_PRIORITY_CLASS { + DfsInvalidPriorityClass = -1i32 as u32, + DfsSiteCostNormalPriorityClass = 0, + DfsGlobalHighPriorityClass, + DfsSiteCostHighPriorityClass, + DfsSiteCostLowPriorityClass, + DfsGlobalLowPriorityClass, +}} +STRUCT!{struct DFS_TARGET_PRIORITY { + TargetPriorityClass: DFS_TARGET_PRIORITY_CLASS, + TargetPriorityRank: ::USHORT, + Reserved: ::USHORT, +}} +pub type PDFS_TARGET_PRIORITY = *mut DFS_TARGET_PRIORITY; +STRUCT!{struct DFS_INFO_1 { + EntryPath: ::LPWSTR, +}} +pub type PDFS_INFO_1 = *mut DFS_INFO_1; +pub type LPDFS_INFO_1 = *mut DFS_INFO_1; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_1_32 { + EntryPath: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_1_32 = *mut DFS_INFO_1_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_1_32 = *mut DFS_INFO_1_32; +STRUCT!{struct DFS_INFO_2 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + NumberOfStorages: ::DWORD, +}} +pub type PDFS_INFO_2 = *mut DFS_INFO_2; +pub type LPDFS_INFO_2 = *mut DFS_INFO_2; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_2_32 { + EntryPath: ::ULONG, + Comment: ::ULONG, + State: ::DWORD, + NumberOfStorages: ::DWORD, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_2_32 = *mut DFS_INFO_2_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_2_32 = *mut DFS_INFO_2_32; +STRUCT!{struct DFS_STORAGE_INFO { + State: ::ULONG, + ServerName: ::LPWSTR, + ShareName: ::LPWSTR, +}} +pub type PDFS_STORAGE_INFO = *mut DFS_STORAGE_INFO; +pub type LPDFS_STORAGE_INFO = *mut DFS_STORAGE_INFO; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_STORAGE_INFO_0_32 { + State: ::ULONG, + ServerName: ::ULONG, + ShareName: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_STORAGE_INFO_0_32 = *mut DFS_STORAGE_INFO_0_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_STORAGE_INFO_0_32 = *mut DFS_STORAGE_INFO_0_32; +STRUCT!{struct DFS_STORAGE_INFO_1 { + State: ::ULONG, + ServerName: ::LPWSTR, + ShareName: ::LPWSTR, + TargetPriority: DFS_TARGET_PRIORITY, +}} +pub type PDFS_STORAGE_INFO_1 = *mut DFS_STORAGE_INFO_1; +pub type LPDFS_STORAGE_INFO_1 = *mut DFS_STORAGE_INFO_1; +STRUCT!{struct DFS_INFO_3 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_3 = *mut DFS_INFO_3; +pub type LPDFS_INFO_3 = *mut DFS_INFO_3; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_3_32 { + EntryPath: ::ULONG, + Comment: ::ULONG, + State: ::DWORD, + NumberOfStorages: ::DWORD, + Storage: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_3_32 = *mut DFS_INFO_3_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_3_32 = *mut DFS_INFO_3_32; +STRUCT!{struct DFS_INFO_4 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_4 = *mut DFS_INFO_4; +pub type LPDFS_INFO_4 = *mut DFS_INFO_4; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_4_32 { + EntryPath: ::ULONG, + Comment: ::ULONG, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + NumberOfStorages: ::DWORD, + Storage: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_4_32 = *mut DFS_INFO_4_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_4_32 = *mut DFS_INFO_4_32; +STRUCT!{struct DFS_INFO_5 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + NumberOfStorages: ::DWORD, +}} +pub type PDFS_INFO_5 = *mut DFS_INFO_5; +pub type LPDFS_INFO_5 = *mut DFS_INFO_5; +STRUCT!{struct DFS_INFO_6 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_6 = *mut DFS_INFO_6; +pub type LPDFS_INFO_6 = *mut DFS_INFO_6; +STRUCT!{struct DFS_INFO_7 { + GenerationGuid: ::GUID, +}} +pub type PDFS_INFO_7 = *mut DFS_INFO_7; +pub type LPDFS_INFO_7 = *mut DFS_INFO_7; +STRUCT!{struct DFS_INFO_8 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, + NumberOfStorages: ::DWORD, +}} +pub type PDFS_INFO_8 = *mut DFS_INFO_8; +pub type LPDFS_INFO_8 = *mut DFS_INFO_8; +STRUCT!{struct DFS_INFO_9 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_9 = *mut DFS_INFO_9; +pub type LPDFS_INFO_9 = *mut DFS_INFO_9; +pub const DFS_PROPERTY_FLAG_INSITE_REFERRALS: ::ULONG = 0x00000001; +pub const DFS_PROPERTY_FLAG_ROOT_SCALABILITY: ::ULONG = 0x00000002; +pub const DFS_PROPERTY_FLAG_SITE_COSTING: ::ULONG = 0x00000004; +pub const DFS_PROPERTY_FLAG_TARGET_FAILBACK: ::ULONG = 0x00000008; +pub const DFS_PROPERTY_FLAG_CLUSTER_ENABLED: ::ULONG = 0x00000010; +pub const DFS_PROPERTY_FLAG_ABDE: ::ULONG = 0x00000020; +pub const DFS_VALID_PROPERTY_FLAGS: ::ULONG = DFS_PROPERTY_FLAG_INSITE_REFERRALS + | DFS_PROPERTY_FLAG_ROOT_SCALABILITY | DFS_PROPERTY_FLAG_SITE_COSTING + | DFS_PROPERTY_FLAG_TARGET_FAILBACK | DFS_PROPERTY_FLAG_CLUSTER_ENABLED + | DFS_PROPERTY_FLAG_ABDE; +STRUCT!{struct DFS_INFO_50 { + NamespaceMajorVersion: ::ULONG, + NamespaceMinorVersion: ::ULONG, + NamespaceCapabilities: ::ULONGLONG, +}} +pub type PDFS_INFO_50 = *mut DFS_INFO_50; +pub type LPDFS_INFO_50 = *mut DFS_INFO_50; +STRUCT!{struct DFS_INFO_100 { + Comment: ::LPWSTR, +}} +pub type PDFS_INFO_100 = *mut DFS_INFO_100; +pub type LPDFS_INFO_100 = *mut DFS_INFO_100; +STRUCT!{struct DFS_INFO_101 { + State: ::DWORD, +}} +pub type PDFS_INFO_101 = *mut DFS_INFO_101; +pub type LPDFS_INFO_101 = *mut DFS_INFO_101; +STRUCT!{struct DFS_INFO_102 { + Timeout: ::ULONG, +}} +pub type PDFS_INFO_102 = *mut DFS_INFO_102; +pub type LPDFS_INFO_102 = *mut DFS_INFO_102; +STRUCT!{struct DFS_INFO_103 { + PropertyFlagMask: ::ULONG, + PropertyFlags: ::ULONG, +}} +pub type PDFS_INFO_103 = *mut DFS_INFO_103; +pub type LPDFS_INFO_103 = *mut DFS_INFO_103; +STRUCT!{struct DFS_INFO_104 { + TargetPriority: DFS_TARGET_PRIORITY, +}} +pub type PDFS_INFO_104 = *mut DFS_INFO_104; +pub type LPDFS_INFO_104 = *mut DFS_INFO_104; +STRUCT!{struct DFS_INFO_105 { + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + PropertyFlagMask: ::ULONG, + PropertyFlags: ::ULONG, +}} +pub type PDFS_INFO_105 = *mut DFS_INFO_105; +pub type LPDFS_INFO_105 = *mut DFS_INFO_105; +STRUCT!{struct DFS_INFO_106 { + State: ::DWORD, + TargetPriority: DFS_TARGET_PRIORITY, +}} +pub type PDFS_INFO_106 = *mut DFS_INFO_106; +pub type LPDFS_INFO_106 = *mut DFS_INFO_106; +STRUCT!{struct DFS_INFO_107 { + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + PropertyFlagMask: ::ULONG, + PropertyFlags: ::ULONG, + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, +}} +pub type PDFS_INFO_107 = *mut DFS_INFO_107; +pub type LPDFS_INFO_107 = *mut DFS_INFO_107; +STRUCT!{struct DFS_INFO_150 { + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, +}} +pub type PDFS_INFO_150 = *mut DFS_INFO_150; +pub type LPDFS_INFO_150 = *mut DFS_INFO_150; +STRUCT!{struct DFS_INFO_200 { + FtDfsName: ::LPWSTR, +}} +pub type PDFS_INFO_200 = *mut DFS_INFO_200; +pub type LPDFS_INFO_200 = *mut DFS_INFO_200; +STRUCT!{struct DFS_INFO_300 { + Flags: ::DWORD, + DfsName: ::LPWSTR, +}} +pub type PDFS_INFO_300 = *mut DFS_INFO_300; +pub type LPDFS_INFO_300 = *mut DFS_INFO_300; +pub const DFS_ADD_VOLUME: ::DWORD = 1; +pub const DFS_RESTORE_VOLUME: ::DWORD = 2; +pub const NET_DFS_SETDC_FLAGS: ::DWORD = 0x00000000; +pub const NET_DFS_SETDC_TIMEOUT: ::DWORD = 0x00000001; +pub const NET_DFS_SETDC_INITPKT: ::DWORD = 0x00000002; +STRUCT!{struct DFS_SITENAME_INFO { + SiteFlags: ::ULONG, + SiteName: ::LPWSTR, +}} +pub type PDFS_SITENAME_INFO = *mut DFS_SITENAME_INFO; +pub type LPDFS_SITENAME_INFO = *mut DFS_SITENAME_INFO; +pub const DFS_SITE_PRIMARY: ::ULONG = 0x1; +STRUCT!{struct DFS_SITELIST_INFO { + cSites: ::ULONG, + Site: [DFS_SITENAME_INFO; 1], +}} +pub type PDFS_SITELIST_INFO = *mut DFS_SITELIST_INFO; +pub type LPDFS_SITELIST_INFO = *mut DFS_SITELIST_INFO; +ENUM!{enum DFS_NAMESPACE_VERSION_ORIGIN { + DFS_NAMESPACE_VERSION_ORIGIN_COMBINED = 0, + DFS_NAMESPACE_VERSION_ORIGIN_SERVER, + DFS_NAMESPACE_VERSION_ORIGIN_DOMAIN, +}} +pub type PDFS_NAMESPACE_VERSION_ORIGIN = *mut DFS_NAMESPACE_VERSION_ORIGIN; +pub const DFS_NAMESPACE_CAPABILITY_ABDE: ::ULONGLONG = 0x0000000000000001; +STRUCT!{struct DFS_SUPPORTED_NAMESPACE_VERSION_INFO { + DomainDfsMajorVersion: ::ULONG, + DomainDfsMinorVersion: ::ULONG, + DomainDfsCapabilities: ::ULONGLONG, + StandaloneDfsMajorVersion: ::ULONG, + StandaloneDfsMinorVersion: ::ULONG, + StandaloneDfsCapabilities: ::ULONGLONG, +}} +pub type PDFS_SUPPORTED_NAMESPACE_VERSION_INFO = *mut DFS_SUPPORTED_NAMESPACE_VERSION_INFO; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lmerrlog.rs b/bash-5.1/vendor/winapi-0.2.8/src/lmerrlog.rs new file mode 100644 index 0000000..ebbe3b0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lmerrlog.rs @@ -0,0 +1,263 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +STRUCT!{struct ERROR_LOG { + el_len: ::DWORD, + el_reserved: ::DWORD, + el_time: ::DWORD, + el_error: ::DWORD, + el_name: ::LPWSTR, + el_text: ::LPWSTR, + el_data: ::LPBYTE, + el_data_size: ::DWORD, + el_nstrings: ::DWORD, +}} +pub type PERROR_LOG = *mut ERROR_LOG; +pub type LPERROR_LOG = *mut ERROR_LOG; +STRUCT!{struct HLOG { + time: ::DWORD, + last_flags: ::DWORD, + offset: ::DWORD, + rec_offset: ::DWORD, +}} +pub type PHLOG = *mut HLOG; +pub type LPHLOG = *mut HLOG; +pub const LOGFLAGS_FORWARD: ::DWORD = 0; +pub const LOGFLAGS_BACKWARD: ::DWORD = 0x1; +pub const LOGFLAGS_SEEK: ::DWORD = 0x2; +pub const ERRLOG_BASE: ::DWORD = 3100; +pub const NELOG_Internal_Error: ::DWORD = ERRLOG_BASE + 0; +pub const NELOG_Resource_Shortage: ::DWORD = ERRLOG_BASE + 1; +pub const NELOG_Unable_To_Lock_Segment: ::DWORD = ERRLOG_BASE + 2; +pub const NELOG_Unable_To_Unlock_Segment: ::DWORD = ERRLOG_BASE + 3; +pub const NELOG_Uninstall_Service: ::DWORD = ERRLOG_BASE + 4; +pub const NELOG_Init_Exec_Fail: ::DWORD = ERRLOG_BASE + 5; +pub const NELOG_Ncb_Error: ::DWORD = ERRLOG_BASE + 6; +pub const NELOG_Net_Not_Started: ::DWORD = ERRLOG_BASE + 7; +pub const NELOG_Ioctl_Error: ::DWORD = ERRLOG_BASE + 8; +pub const NELOG_System_Semaphore: ::DWORD = ERRLOG_BASE + 9; +pub const NELOG_Init_OpenCreate_Err: ::DWORD = ERRLOG_BASE + 10; +pub const NELOG_NetBios: ::DWORD = ERRLOG_BASE + 11; +pub const NELOG_SMB_Illegal: ::DWORD = ERRLOG_BASE + 12; +pub const NELOG_Service_Fail: ::DWORD = ERRLOG_BASE + 13; +pub const NELOG_Entries_Lost: ::DWORD = ERRLOG_BASE + 14; +pub const NELOG_Init_Seg_Overflow: ::DWORD = ERRLOG_BASE + 20; +pub const NELOG_Srv_No_Mem_Grow: ::DWORD = ERRLOG_BASE + 21; +pub const NELOG_Access_File_Bad: ::DWORD = ERRLOG_BASE + 22; +pub const NELOG_Srvnet_Not_Started: ::DWORD = ERRLOG_BASE + 23; +pub const NELOG_Init_Chardev_Err: ::DWORD = ERRLOG_BASE + 24; +pub const NELOG_Remote_API: ::DWORD = ERRLOG_BASE + 25; +pub const NELOG_Ncb_TooManyErr: ::DWORD = ERRLOG_BASE + 26; +pub const NELOG_Mailslot_err: ::DWORD = ERRLOG_BASE + 27; +pub const NELOG_ReleaseMem_Alert: ::DWORD = ERRLOG_BASE + 28; +pub const NELOG_AT_cannot_write: ::DWORD = ERRLOG_BASE + 29; +pub const NELOG_Cant_Make_Msg_File: ::DWORD = ERRLOG_BASE + 30; +pub const NELOG_Exec_Netservr_NoMem: ::DWORD = ERRLOG_BASE + 31; +pub const NELOG_Server_Lock_Failure: ::DWORD = ERRLOG_BASE + 32; +pub const NELOG_Msg_Shutdown: ::DWORD = ERRLOG_BASE + 40; +pub const NELOG_Msg_Sem_Shutdown: ::DWORD = ERRLOG_BASE + 41; +pub const NELOG_Msg_Log_Err: ::DWORD = ERRLOG_BASE + 50; +pub const NELOG_VIO_POPUP_ERR: ::DWORD = ERRLOG_BASE + 51; +pub const NELOG_Msg_Unexpected_SMB_Type: ::DWORD = ERRLOG_BASE + 52; +pub const NELOG_Wksta_Infoseg: ::DWORD = ERRLOG_BASE + 60; +pub const NELOG_Wksta_Compname: ::DWORD = ERRLOG_BASE + 61; +pub const NELOG_Wksta_BiosThreadFailure: ::DWORD = ERRLOG_BASE + 62; +pub const NELOG_Wksta_IniSeg: ::DWORD = ERRLOG_BASE + 63; +pub const NELOG_Wksta_HostTab_Full: ::DWORD = ERRLOG_BASE + 64; +pub const NELOG_Wksta_Bad_Mailslot_SMB: ::DWORD = ERRLOG_BASE + 65; +pub const NELOG_Wksta_UASInit: ::DWORD = ERRLOG_BASE + 66; +pub const NELOG_Wksta_SSIRelogon: ::DWORD = ERRLOG_BASE + 67; +pub const NELOG_Build_Name: ::DWORD = ERRLOG_BASE + 70; +pub const NELOG_Name_Expansion: ::DWORD = ERRLOG_BASE + 71; +pub const NELOG_Message_Send: ::DWORD = ERRLOG_BASE + 72; +pub const NELOG_Mail_Slt_Err: ::DWORD = ERRLOG_BASE + 73; +pub const NELOG_AT_cannot_read: ::DWORD = ERRLOG_BASE + 74; +pub const NELOG_AT_sched_err: ::DWORD = ERRLOG_BASE + 75; +pub const NELOG_AT_schedule_file_created: ::DWORD = ERRLOG_BASE + 76; +pub const NELOG_Srvnet_NB_Open: ::DWORD = ERRLOG_BASE + 77; +pub const NELOG_AT_Exec_Err: ::DWORD = ERRLOG_BASE + 78; +pub const NELOG_Lazy_Write_Err: ::DWORD = ERRLOG_BASE + 80; +pub const NELOG_HotFix: ::DWORD = ERRLOG_BASE + 81; +pub const NELOG_HardErr_From_Server: ::DWORD = ERRLOG_BASE + 82; +pub const NELOG_LocalSecFail1: ::DWORD = ERRLOG_BASE + 83; +pub const NELOG_LocalSecFail2: ::DWORD = ERRLOG_BASE + 84; +pub const NELOG_LocalSecFail3: ::DWORD = ERRLOG_BASE + 85; +pub const NELOG_LocalSecGeneralFail: ::DWORD = ERRLOG_BASE + 86; +pub const NELOG_NetWkSta_Internal_Error: ::DWORD = ERRLOG_BASE + 90; +pub const NELOG_NetWkSta_No_Resource: ::DWORD = ERRLOG_BASE + 91; +pub const NELOG_NetWkSta_SMB_Err: ::DWORD = ERRLOG_BASE + 92; +pub const NELOG_NetWkSta_VC_Err: ::DWORD = ERRLOG_BASE + 93; +pub const NELOG_NetWkSta_Stuck_VC_Err: ::DWORD = ERRLOG_BASE + 94; +pub const NELOG_NetWkSta_NCB_Err: ::DWORD = ERRLOG_BASE + 95; +pub const NELOG_NetWkSta_Write_Behind_Err: ::DWORD = ERRLOG_BASE + 96; +pub const NELOG_NetWkSta_Reset_Err: ::DWORD = ERRLOG_BASE + 97; +pub const NELOG_NetWkSta_Too_Many: ::DWORD = ERRLOG_BASE + 98; +pub const NELOG_Srv_Thread_Failure: ::DWORD = ERRLOG_BASE + 104; +pub const NELOG_Srv_Close_Failure: ::DWORD = ERRLOG_BASE + 105; +pub const NELOG_ReplUserCurDir: ::DWORD = ERRLOG_BASE + 106; +pub const NELOG_ReplCannotMasterDir: ::DWORD = ERRLOG_BASE + 107; +pub const NELOG_ReplUpdateError: ::DWORD = ERRLOG_BASE + 108; +pub const NELOG_ReplLostMaster: ::DWORD = ERRLOG_BASE + 109; +pub const NELOG_NetlogonAuthDCFail: ::DWORD = ERRLOG_BASE + 110; +pub const NELOG_ReplLogonFailed: ::DWORD = ERRLOG_BASE + 111; +pub const NELOG_ReplNetErr: ::DWORD = ERRLOG_BASE + 112; +pub const NELOG_ReplMaxFiles: ::DWORD = ERRLOG_BASE + 113; +pub const NELOG_ReplMaxTreeDepth: ::DWORD = ERRLOG_BASE + 114; +pub const NELOG_ReplBadMsg: ::DWORD = ERRLOG_BASE + 115; +pub const NELOG_ReplSysErr: ::DWORD = ERRLOG_BASE + 116; +pub const NELOG_ReplUserLoged: ::DWORD = ERRLOG_BASE + 117; +pub const NELOG_ReplBadImport: ::DWORD = ERRLOG_BASE + 118; +pub const NELOG_ReplBadExport: ::DWORD = ERRLOG_BASE + 119; +pub const NELOG_ReplSignalFileErr: ::DWORD = ERRLOG_BASE + 120; +pub const NELOG_DiskFT: ::DWORD = ERRLOG_BASE + 121; +pub const NELOG_ReplAccessDenied: ::DWORD = ERRLOG_BASE + 122; +pub const NELOG_NetlogonFailedPrimary: ::DWORD = ERRLOG_BASE + 123; +pub const NELOG_NetlogonPasswdSetFailed: ::DWORD = ERRLOG_BASE + 124; +pub const NELOG_NetlogonTrackingError: ::DWORD = ERRLOG_BASE + 125; +pub const NELOG_NetlogonSyncError: ::DWORD = ERRLOG_BASE + 126; +pub const NELOG_NetlogonRequireSignOrSealError: ::DWORD = ERRLOG_BASE + 127; +pub const NELOG_UPS_PowerOut: ::DWORD = ERRLOG_BASE + 130; +pub const NELOG_UPS_Shutdown: ::DWORD = ERRLOG_BASE + 131; +pub const NELOG_UPS_CmdFileError: ::DWORD = ERRLOG_BASE + 132; +pub const NELOG_UPS_CannotOpenDriver: ::DWORD = ERRLOG_BASE+133; +pub const NELOG_UPS_PowerBack: ::DWORD = ERRLOG_BASE + 134; +pub const NELOG_UPS_CmdFileConfig: ::DWORD = ERRLOG_BASE + 135; +pub const NELOG_UPS_CmdFileExec: ::DWORD = ERRLOG_BASE + 136; +pub const NELOG_Missing_Parameter: ::DWORD = ERRLOG_BASE + 150; +pub const NELOG_Invalid_Config_Line: ::DWORD = ERRLOG_BASE + 151; +pub const NELOG_Invalid_Config_File: ::DWORD = ERRLOG_BASE + 152; +pub const NELOG_File_Changed: ::DWORD = ERRLOG_BASE + 153; +pub const NELOG_Files_Dont_Fit: ::DWORD = ERRLOG_BASE + 154; +pub const NELOG_Wrong_DLL_Version: ::DWORD = ERRLOG_BASE + 155; +pub const NELOG_Error_in_DLL: ::DWORD = ERRLOG_BASE + 156; +pub const NELOG_System_Error: ::DWORD = ERRLOG_BASE + 157; +pub const NELOG_FT_ErrLog_Too_Large: ::DWORD = ERRLOG_BASE + 158; +pub const NELOG_FT_Update_In_Progress: ::DWORD = ERRLOG_BASE + 159; +pub const NELOG_Joined_Domain: ::DWORD = ERRLOG_BASE + 160; +pub const NELOG_Joined_Workgroup: ::DWORD = ERRLOG_BASE + 161; +pub const NELOG_OEM_Code: ::DWORD = ERRLOG_BASE + 199; +pub const ERRLOG2_BASE: ::DWORD = 5700; +pub const NELOG_NetlogonSSIInitError: ::DWORD = ERRLOG2_BASE + 0; +pub const NELOG_NetlogonFailedToUpdateTrustList: ::DWORD = ERRLOG2_BASE + 1; +pub const NELOG_NetlogonFailedToAddRpcInterface: ::DWORD = ERRLOG2_BASE + 2; +pub const NELOG_NetlogonFailedToReadMailslot: ::DWORD = ERRLOG2_BASE + 3; +pub const NELOG_NetlogonFailedToRegisterSC: ::DWORD = ERRLOG2_BASE + 4; +pub const NELOG_NetlogonChangeLogCorrupt: ::DWORD = ERRLOG2_BASE + 5; +pub const NELOG_NetlogonFailedToCreateShare: ::DWORD = ERRLOG2_BASE + 6; +pub const NELOG_NetlogonDownLevelLogonFailed: ::DWORD = ERRLOG2_BASE + 7; +pub const NELOG_NetlogonDownLevelLogoffFailed: ::DWORD = ERRLOG2_BASE + 8; +pub const NELOG_NetlogonNTLogonFailed: ::DWORD = ERRLOG2_BASE + 9; +pub const NELOG_NetlogonNTLogoffFailed: ::DWORD = ERRLOG2_BASE + 10; +pub const NELOG_NetlogonPartialSyncCallSuccess: ::DWORD = ERRLOG2_BASE + 11; +pub const NELOG_NetlogonPartialSyncCallFailed: ::DWORD = ERRLOG2_BASE + 12; +pub const NELOG_NetlogonFullSyncCallSuccess: ::DWORD = ERRLOG2_BASE + 13; +pub const NELOG_NetlogonFullSyncCallFailed: ::DWORD = ERRLOG2_BASE + 14; +pub const NELOG_NetlogonPartialSyncSuccess: ::DWORD = ERRLOG2_BASE + 15; +pub const NELOG_NetlogonPartialSyncFailed: ::DWORD = ERRLOG2_BASE + 16; +pub const NELOG_NetlogonFullSyncSuccess: ::DWORD = ERRLOG2_BASE + 17; +pub const NELOG_NetlogonFullSyncFailed: ::DWORD = ERRLOG2_BASE + 18; +pub const NELOG_NetlogonAuthNoDomainController: ::DWORD = ERRLOG2_BASE + 19; +pub const NELOG_NetlogonAuthNoTrustLsaSecret: ::DWORD = ERRLOG2_BASE + 20; +pub const NELOG_NetlogonAuthNoTrustSamAccount: ::DWORD = ERRLOG2_BASE + 21; +pub const NELOG_NetlogonServerAuthFailed: ::DWORD = ERRLOG2_BASE + 22; +pub const NELOG_NetlogonServerAuthNoTrustSamAccount: ::DWORD = ERRLOG2_BASE + 23; +pub const NELOG_FailedToRegisterSC: ::DWORD = ERRLOG2_BASE + 24; +pub const NELOG_FailedToSetServiceStatus: ::DWORD = ERRLOG2_BASE + 25; +pub const NELOG_FailedToGetComputerName: ::DWORD = ERRLOG2_BASE + 26; +pub const NELOG_DriverNotLoaded: ::DWORD = ERRLOG2_BASE + 27; +pub const NELOG_NoTranportLoaded: ::DWORD = ERRLOG2_BASE + 28; +pub const NELOG_NetlogonFailedDomainDelta: ::DWORD = ERRLOG2_BASE + 29; +pub const NELOG_NetlogonFailedGlobalGroupDelta: ::DWORD = ERRLOG2_BASE + 30; +pub const NELOG_NetlogonFailedLocalGroupDelta: ::DWORD = ERRLOG2_BASE + 31; +pub const NELOG_NetlogonFailedUserDelta: ::DWORD = ERRLOG2_BASE + 32; +pub const NELOG_NetlogonFailedPolicyDelta: ::DWORD = ERRLOG2_BASE + 33; +pub const NELOG_NetlogonFailedTrustedDomainDelta: ::DWORD = ERRLOG2_BASE + 34; +pub const NELOG_NetlogonFailedAccountDelta: ::DWORD = ERRLOG2_BASE + 35; +pub const NELOG_NetlogonFailedSecretDelta: ::DWORD = ERRLOG2_BASE + 36; +pub const NELOG_NetlogonSystemError: ::DWORD = ERRLOG2_BASE + 37; +pub const NELOG_NetlogonDuplicateMachineAccounts: ::DWORD = ERRLOG2_BASE + 38; +pub const NELOG_NetlogonTooManyGlobalGroups: ::DWORD = ERRLOG2_BASE + 39; +pub const NELOG_NetlogonBrowserDriver: ::DWORD = ERRLOG2_BASE + 40; +pub const NELOG_NetlogonAddNameFailure: ::DWORD = ERRLOG2_BASE + 41; +pub const NELOG_RplMessages: ::DWORD = ERRLOG2_BASE + 42; +pub const NELOG_RplXnsBoot: ::DWORD = ERRLOG2_BASE + 43; +pub const NELOG_RplSystem: ::DWORD = ERRLOG2_BASE + 44; +pub const NELOG_RplWkstaTimeout: ::DWORD = ERRLOG2_BASE + 45; +pub const NELOG_RplWkstaFileOpen: ::DWORD = ERRLOG2_BASE + 46; +pub const NELOG_RplWkstaFileRead: ::DWORD = ERRLOG2_BASE + 47; +pub const NELOG_RplWkstaMemory: ::DWORD = ERRLOG2_BASE + 48; +pub const NELOG_RplWkstaFileChecksum: ::DWORD = ERRLOG2_BASE + 49; +pub const NELOG_RplWkstaFileLineCount: ::DWORD = ERRLOG2_BASE + 50; +pub const NELOG_RplWkstaBbcFile: ::DWORD = ERRLOG2_BASE + 51; +pub const NELOG_RplWkstaFileSize: ::DWORD = ERRLOG2_BASE + 52; +pub const NELOG_RplWkstaInternal: ::DWORD = ERRLOG2_BASE + 53; +pub const NELOG_RplWkstaWrongVersion: ::DWORD = ERRLOG2_BASE + 54; +pub const NELOG_RplWkstaNetwork: ::DWORD = ERRLOG2_BASE + 55; +pub const NELOG_RplAdapterResource: ::DWORD = ERRLOG2_BASE + 56; +pub const NELOG_RplFileCopy: ::DWORD = ERRLOG2_BASE + 57; +pub const NELOG_RplFileDelete: ::DWORD = ERRLOG2_BASE + 58; +pub const NELOG_RplFilePerms: ::DWORD = ERRLOG2_BASE + 59; +pub const NELOG_RplCheckConfigs: ::DWORD = ERRLOG2_BASE + 60; +pub const NELOG_RplCreateProfiles: ::DWORD = ERRLOG2_BASE + 61; +pub const NELOG_RplRegistry: ::DWORD = ERRLOG2_BASE + 62; +pub const NELOG_RplReplaceRPLDISK: ::DWORD = ERRLOG2_BASE + 63; +pub const NELOG_RplCheckSecurity: ::DWORD = ERRLOG2_BASE + 64; +pub const NELOG_RplBackupDatabase: ::DWORD = ERRLOG2_BASE + 65; +pub const NELOG_RplInitDatabase: ::DWORD = ERRLOG2_BASE + 66; +pub const NELOG_RplRestoreDatabaseFailure: ::DWORD = ERRLOG2_BASE + 67; +pub const NELOG_RplRestoreDatabaseSuccess: ::DWORD = ERRLOG2_BASE + 68; +pub const NELOG_RplInitRestoredDatabase: ::DWORD = ERRLOG2_BASE + 69; +pub const NELOG_NetlogonSessionTypeWrong: ::DWORD = ERRLOG2_BASE + 70; +pub const NELOG_RplUpgradeDBTo40: ::DWORD = ERRLOG2_BASE + 71; +pub const NELOG_NetlogonLanmanBdcsNotAllowed: ::DWORD = ERRLOG2_BASE + 72; +pub const NELOG_NetlogonNoDynamicDns: ::DWORD = ERRLOG2_BASE + 73; +pub const NELOG_NetlogonDynamicDnsRegisterFailure: ::DWORD = ERRLOG2_BASE + 74; +pub const NELOG_NetlogonDynamicDnsDeregisterFailure: ::DWORD = ERRLOG2_BASE + 75; +pub const NELOG_NetlogonFailedFileCreate: ::DWORD = ERRLOG2_BASE + 76; +pub const NELOG_NetlogonGetSubnetToSite: ::DWORD = ERRLOG2_BASE + 77; +pub const NELOG_NetlogonNoSiteForClient: ::DWORD = ERRLOG2_BASE + 78; +pub const NELOG_NetlogonBadSiteName: ::DWORD = ERRLOG2_BASE + 79; +pub const NELOG_NetlogonBadSubnetName: ::DWORD = ERRLOG2_BASE + 80; +pub const NELOG_NetlogonDynamicDnsServerFailure: ::DWORD = ERRLOG2_BASE + 81; +pub const NELOG_NetlogonDynamicDnsFailure: ::DWORD = ERRLOG2_BASE + 82; +pub const NELOG_NetlogonRpcCallCancelled: ::DWORD = ERRLOG2_BASE + 83; +pub const NELOG_NetlogonDcSiteCovered: ::DWORD = ERRLOG2_BASE + 84; +pub const NELOG_NetlogonDcSiteNotCovered: ::DWORD = ERRLOG2_BASE + 85; +pub const NELOG_NetlogonGcSiteCovered: ::DWORD = ERRLOG2_BASE + 86; +pub const NELOG_NetlogonGcSiteNotCovered: ::DWORD = ERRLOG2_BASE + 87; +pub const NELOG_NetlogonFailedSpnUpdate: ::DWORD = ERRLOG2_BASE + 88; +pub const NELOG_NetlogonFailedDnsHostNameUpdate: ::DWORD = ERRLOG2_BASE + 89; +pub const NELOG_NetlogonAuthNoUplevelDomainController: ::DWORD = ERRLOG2_BASE + 90; +pub const NELOG_NetlogonAuthDomainDowngraded: ::DWORD = ERRLOG2_BASE + 91; +pub const NELOG_NetlogonNdncSiteCovered: ::DWORD = ERRLOG2_BASE + 92; +pub const NELOG_NetlogonNdncSiteNotCovered: ::DWORD = ERRLOG2_BASE + 93; +pub const NELOG_NetlogonDcOldSiteCovered: ::DWORD = ERRLOG2_BASE + 94; +pub const NELOG_NetlogonDcSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 95; +pub const NELOG_NetlogonGcOldSiteCovered: ::DWORD = ERRLOG2_BASE + 96; +pub const NELOG_NetlogonGcSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 97; +pub const NELOG_NetlogonNdncOldSiteCovered: ::DWORD = ERRLOG2_BASE + 98; +pub const NELOG_NetlogonNdncSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 99; +pub const NELOG_NetlogonSpnMultipleSamAccountNames: ::DWORD = ERRLOG2_BASE + 100; +pub const NELOG_NetlogonSpnCrackNamesFailure: ::DWORD = ERRLOG2_BASE + 101; +pub const NELOG_NetlogonNoAddressToSiteMapping: ::DWORD = ERRLOG2_BASE + 102; +pub const NELOG_NetlogonInvalidGenericParameterValue: ::DWORD = ERRLOG2_BASE + 103; +pub const NELOG_NetlogonInvalidDwordParameterValue: ::DWORD = ERRLOG2_BASE + 104; +pub const NELOG_NetlogonServerAuthFailedNoAccount: ::DWORD = ERRLOG2_BASE + 105; +pub const NELOG_NetlogonNoDynamicDnsManual: ::DWORD = ERRLOG2_BASE + 106; +pub const NELOG_NetlogonNoSiteForClients: ::DWORD = ERRLOG2_BASE + 107; +pub const NELOG_NetlogonDnsDeregAborted: ::DWORD = ERRLOG2_BASE + 108; +pub const NELOG_NetlogonRpcPortRequestFailure: ::DWORD = ERRLOG2_BASE + 109; +pub const NELOG_NetlogonPartialSiteMappingForClients: ::DWORD = ERRLOG2_BASE + 110; +pub const NELOG_NetlogonRemoteDynamicDnsRegisterFailure: ::DWORD = ERRLOG2_BASE + 111; +pub const NELOG_NetlogonRemoteDynamicDnsDeregisterFailure: ::DWORD = ERRLOG2_BASE + 112; +pub const NELOG_NetlogonRejectedRemoteDynamicDnsRegister: ::DWORD = ERRLOG2_BASE + 113; +pub const NELOG_NetlogonRejectedRemoteDynamicDnsDeregister: ::DWORD = ERRLOG2_BASE + 114; +pub const NELOG_NetlogonRemoteDynamicDnsUpdateRequestFailure: ::DWORD = ERRLOG2_BASE + 115; +pub const NELOG_NetlogonUserValidationReqInitialTimeOut: ::DWORD = ERRLOG2_BASE + 116; +pub const NELOG_NetlogonUserValidationReqRecurringTimeOut: ::DWORD = ERRLOG2_BASE + 117; +pub const NELOG_NetlogonUserValidationReqWaitInitialWarning: ::DWORD = ERRLOG2_BASE + 118; +pub const NELOG_NetlogonUserValidationReqWaitRecurringWarning: ::DWORD = ERRLOG2_BASE + 119; +pub const NELOG_NetlogonFailedToAddAuthzRpcInterface: ::DWORD = ERRLOG2_BASE + 120; +pub const NELOG_NetLogonFailedToInitializeAuthzRm: ::DWORD = ERRLOG2_BASE + 121; +pub const NELOG_NetLogonFailedToInitializeRPCSD: ::DWORD = ERRLOG2_BASE + 122; +pub const NELOG_NetlogonMachinePasswdSetSucceeded: ::DWORD = ERRLOG2_BASE + 123; +pub const NELOG_NetlogonMsaPasswdSetSucceeded: ::DWORD = ERRLOG2_BASE + 124; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lmjoin.rs b/bash-5.1/vendor/winapi-0.2.8/src/lmjoin.rs new file mode 100644 index 0000000..12b8a10 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lmjoin.rs @@ -0,0 +1,80 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +// Definitions and prototypes for the Net setup apis +ENUM!{enum NETSETUP_NAME_TYPE { + NetSetupUnknown = 0, + NetSetupMachine, + NetSetupWorkgroup, + NetSetupDomain, + NetSetupNonExistentDomain, + NetSetupDnsMachine, +}} +pub type PNETSETUP_NAME_TYPE = *mut NETSETUP_NAME_TYPE; +ENUM!{enum NETSETUP_JOIN_STATUS { + NetSetupUnknownStatus = 0, + NetSetupUnjoined, + NetSetupWorkgroupName, + NetSetupDomainName, +}} +pub type PNETSETUP_JOIN_STATUS = *mut NETSETUP_JOIN_STATUS; +pub const NETSETUP_JOIN_DOMAIN: ::DWORD = 0x00000001; +pub const NETSETUP_ACCT_CREATE: ::DWORD = 0x00000002; +pub const NETSETUP_ACCT_DELETE: ::DWORD = 0x00000004; +pub const NETSETUP_WIN9X_UPGRADE: ::DWORD = 0x00000010; +pub const NETSETUP_DOMAIN_JOIN_IF_JOINED: ::DWORD = 0x00000020; +pub const NETSETUP_JOIN_UNSECURE: ::DWORD = 0x00000040; +pub const NETSETUP_MACHINE_PWD_PASSED: ::DWORD = 0x00000080; +pub const NETSETUP_DEFER_SPN_SET: ::DWORD = 0x00000100; +pub const NETSETUP_JOIN_DC_ACCOUNT: ::DWORD = 0x00000200; +pub const NETSETUP_JOIN_WITH_NEW_NAME: ::DWORD = 0x00000400; +pub const NETSETUP_JOIN_READONLY: ::DWORD = 0x00000800; +pub const NETSETUP_DNS_NAME_CHANGES_ONLY: ::DWORD = 0x00001000; +pub const NETSETUP_INSTALL_INVOCATION: ::DWORD = 0x00040000; +pub const NETSETUP_AMBIGUOUS_DC: ::DWORD = 0x00001000; +pub const NETSETUP_NO_NETLOGON_CACHE: ::DWORD = 0x00002000; +pub const NETSETUP_DONT_CONTROL_SERVICES: ::DWORD = 0x00004000; +pub const NETSETUP_SET_MACHINE_NAME: ::DWORD = 0x00008000; +pub const NETSETUP_FORCE_SPN_SET: ::DWORD = 0x00010000; +pub const NETSETUP_NO_ACCT_REUSE: ::DWORD = 0x00020000; +pub const NETSETUP_ALT_SAMACCOUNTNAME: ::DWORD = 0x00020000; +pub const NETSETUP_IGNORE_UNSUPPORTED_FLAGS: ::DWORD = 0x10000000; +pub const NETSETUP_VALID_UNJOIN_FLAGS: ::DWORD = NETSETUP_ACCT_DELETE + | NETSETUP_IGNORE_UNSUPPORTED_FLAGS | NETSETUP_JOIN_DC_ACCOUNT; +pub const NETSETUP_PROCESS_OFFLINE_FLAGS: ::DWORD = NETSETUP_JOIN_DOMAIN + | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_WITH_NEW_NAME | NETSETUP_DONT_CONTROL_SERVICES + | NETSETUP_MACHINE_PWD_PASSED; +pub const NETSETUP_PROVISION_DOWNLEVEL_PRIV_SUPPORT: ::DWORD = 0x00000001; +pub const NETSETUP_PROVISION_REUSE_ACCOUNT: ::DWORD = 0x00000002; +pub const NETSETUP_PROVISION_USE_DEFAULT_PASSWORD: ::DWORD = 0x00000004; +pub const NETSETUP_PROVISION_SKIP_ACCOUNT_SEARCH: ::DWORD = 0x00000008; +pub const NETSETUP_PROVISION_ROOT_CA_CERTS: ::DWORD = 0x00000010; +pub const NETSETUP_PROVISION_PERSISTENTSITE: ::DWORD = 0x00000020; +pub const NETSETUP_PROVISION_ONLINE_CALLER: ::DWORD = 0x40000000; +pub const NETSETUP_PROVISION_CHECK_PWD_ONLY: ::DWORD = 0x80000000; +pub const NETSETUP_PROVISIONING_PARAMS_WIN8_VERSION: ::DWORD = 0x00000001; +pub const NETSETUP_PROVISIONING_PARAMS_CURRENT_VERSION: ::DWORD = 0x00000002; +STRUCT!{struct NETSETUP_PROVISIONING_PARAMS { + dwVersion: ::DWORD, + lpDomain: ::LPCWSTR, + lpHostName: ::LPCWSTR, + lpMachineAccountOU: ::LPCWSTR, + lpDcName: ::LPCWSTR, + dwProvisionOptions: ::DWORD, + aCertTemplateNames: *mut ::LPCWSTR, + cCertTemplateNames: ::DWORD, + aMachinePolicyNames: *mut ::LPCWSTR, + cMachinePolicyNames: ::DWORD, + aMachinePolicyPaths: *mut ::LPCWSTR, + cMachinePolicyPaths: ::DWORD, + lpNetbiosName: ::LPWSTR, + lpSiteName: ::LPWSTR, + lpPrimaryDNSDomain: ::LPWSTR, +}} +pub type PNETSETUP_PROVISIONING_PARAMS = *mut NETSETUP_PROVISIONING_PARAMS; +ENUM!{enum NET_COMPUTER_NAME_TYPE { + NetPrimaryComputerName, + NetAlternateComputerNames, + NetAllComputerNames, + NetComputerNameTypeMax, +}} +pub type PNET_COMPUTER_NAME_TYPE = *mut NET_COMPUTER_NAME_TYPE; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/lsalookup.rs b/bash-5.1/vendor/winapi-0.2.8/src/lsalookup.rs new file mode 100644 index 0000000..039d72a --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/lsalookup.rs @@ -0,0 +1,69 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! LSA Policy Lookup API +STRUCT!{struct LSA_UNICODE_STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PWSTR, +}} +pub type PLSA_UNICODE_STRING = *mut LSA_UNICODE_STRING; +STRUCT!{struct LSA_STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PCHAR, +}} +pub type PLSA_STRING = *mut LSA_STRING; +STRUCT!{struct LSA_OBJECT_ATTRIBUTES { + Length: ::ULONG, + RootDirectory: ::HANDLE, + ObjectName: PLSA_UNICODE_STRING, + Attributes: ::ULONG, + SecurityDescriptor: ::PVOID, + SecurityQualityOfService: ::PVOID, +}} +pub type PLSA_OBJECT_ATTRIBUTES = *mut LSA_OBJECT_ATTRIBUTES; +STRUCT!{struct LSA_TRUST_INFORMATION { + Name: LSA_UNICODE_STRING, + Sid: ::PSID, +}} +pub type PLSA_TRUST_INFORMATION = *mut LSA_TRUST_INFORMATION; +STRUCT!{struct LSA_REFERENCED_DOMAIN_LIST { + Entries: ::ULONG, + Domains: PLSA_TRUST_INFORMATION, +}} +pub type PLSA_REFERENCED_DOMAIN_LIST = *mut LSA_REFERENCED_DOMAIN_LIST; +STRUCT!{struct LSA_TRANSLATED_SID2 { + Use: ::SID_NAME_USE, + Sid: ::PSID, + DomainIndex: ::LONG, + Flags: ::ULONG, +}} +pub type PLSA_TRANSLATED_SID2 = *mut LSA_TRANSLATED_SID2; +STRUCT!{struct LSA_TRANSLATED_NAME { + Use: ::SID_NAME_USE, + Name: LSA_UNICODE_STRING, + DomainIndex: ::LONG, +}} +pub type PLSA_TRANSLATED_NAME = *mut LSA_TRANSLATED_NAME; +STRUCT!{struct POLICY_ACCOUNT_DOMAIN_INFO { + DomainName: LSA_UNICODE_STRING, + DomainSid: ::PSID, +}} +pub type PPOLICY_ACCOUNT_DOMAIN_INFO = *mut POLICY_ACCOUNT_DOMAIN_INFO; +STRUCT!{struct POLICY_DNS_DOMAIN_INFO { + Name: LSA_UNICODE_STRING, + DnsDomainName: LSA_UNICODE_STRING, + DnsForestName: LSA_UNICODE_STRING, + DomainGuid: ::GUID, + Sid: ::PSID, +}} +pub type PPOLICY_DNS_DOMAIN_INFO = *mut POLICY_DNS_DOMAIN_INFO; +pub const LOOKUP_VIEW_LOCAL_INFORMATION: ::ACCESS_MASK = 0x00000001; +pub const LOOKUP_TRANSLATE_NAMES: ::ACCESS_MASK = 0x00000800; +ENUM!{enum LSA_LOOKUP_DOMAIN_INFO_CLASS { + AccountDomainInformation = 5, + DnsDomainInformation = 12, +}} +pub type PLSA_LOOKUP_DOMAIN_INFO_CLASS = *mut LSA_LOOKUP_DOMAIN_INFO_CLASS; +pub type LSA_LOOKUP_HANDLE = ::PVOID; +pub type PLSA_LOOKUP_HANDLE = *mut ::PVOID; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/macros.rs b/bash-5.1/vendor/winapi-0.2.8/src/macros.rs new file mode 100644 index 0000000..0bbd6aa --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/macros.rs @@ -0,0 +1,270 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Macros to make things easier to define +macro_rules! DECLARE_HANDLE { + ($name:ident, $inner:ident) => { + #[allow(missing_copy_implementations)] pub enum $inner { } + pub type $name = *mut $inner; + }; +} +macro_rules! MAKE_HRESULT { + ($sev:expr, $fac:expr, $code:expr) => { + ($sev << 31) | ($fac << 16) | $code + } +} +macro_rules! MAKE_SCODE { + ($sev:expr, $fac:expr, $code:expr) => { + ($sev << 31) | ($fac << 16) | $code + } +} +macro_rules! HIDP_ERROR_CODES { + ($sev:expr, $code:expr) => { + ($sev << 28) | (::FACILITY_HID_ERROR_CODE << 16) | $code + } +} +macro_rules! MAKEFOURCC { + ($a:expr, $b:expr, $c:expr, $d:expr) => { + ($a as i32) | (($b as i32) << 8) | (($c as i32) << 16) | (($d as i32) << 24) + } +} +#[macro_export] +macro_rules! DEFINE_GUID { + ( + $name:ident, $l:expr, $w1:expr, $w2:expr, $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, + $b6:expr, $b7:expr, $b8:expr + ) => { + pub const $name: $crate::GUID = $crate::GUID { + Data1: $l, + Data2: $w1, + Data3: $w2, + Data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], + }; + } +} +macro_rules! CTL_CODE { + ($DeviceType:expr, $Function:expr, $Method:expr, $Access:expr) => { + ($DeviceType << 16) | ($Access << 14) | ($Function << 2) | $Method + } +} +macro_rules! HID_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_NEITHER, ::FILE_ANY_ACCESS) + } +} +macro_rules! HID_BUFFER_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_BUFFERED, ::FILE_ANY_ACCESS) + } +} +macro_rules! HID_IN_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_IN_DIRECT, ::FILE_ANY_ACCESS) + } +} +macro_rules! HID_OUT_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_OUT_DIRECT, ::FILE_ANY_ACCESS) + } +} +macro_rules! AUDCLNT_ERR { + ($n:expr) => { + MAKE_HRESULT!(::SEVERITY_ERROR, ::FACILITY_AUDCLNT, $n) + }; +} +macro_rules! AUDCLNT_SUCCESS { + ($n:expr) => { + MAKE_SCODE!(::SEVERITY_SUCCESS, ::FACILITY_AUDCLNT, $n) + }; +} +macro_rules! BCRYPT_MAKE_INTERFACE_VERSION { + ($major:expr, $minor:expr) => { + ::BCRYPT_INTERFACE_VERSION { MajorVersion: $major, MinorVersion: $minor } + } +} +#[macro_export] +macro_rules! RIDL { + (interface $interface:ident ($vtbl:ident) + {$( + fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty + ),+} + ) => { + #[repr(C)] #[allow(missing_copy_implementations)] + pub struct $vtbl { + $(pub $method: unsafe extern "system" fn( + This: *mut $interface + $(,$p: $t)* + ) -> $rtr),+ + } + #[repr(C)] #[derive(Debug)] #[allow(missing_copy_implementations)] + pub struct $interface { + pub lpVtbl: *const $vtbl + } + impl $interface { + #[inline] + $(pub unsafe fn $method(&mut self $(,$p: $t)*) -> $rtr { + ((*self.lpVtbl).$method)(self $(,$p)*) + })+ + } + }; + (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) { + }) => { + #[repr(C)] #[allow(missing_copy_implementations)] + pub struct $vtbl { + pub parent: $crate::$pvtbl + } + #[repr(C)] #[derive(Debug)] #[allow(missing_copy_implementations)] + pub struct $interface { + pub lpVtbl: *const $vtbl + } + impl ::std::ops::Deref for $interface { + type Target = $crate::$pinterface; + #[inline] + fn deref(&self) -> &$crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + impl ::std::ops::DerefMut for $interface { + #[inline] + fn deref_mut(&mut self) -> &mut $crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + }; + (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) + {$( + fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty + ),+} + ) => { + #[repr(C)] #[allow(missing_copy_implementations)] + pub struct $vtbl { + pub parent: $crate::$pvtbl + $(,pub $method: unsafe extern "system" fn( + This: *mut $interface + $(,$p: $t)* + ) -> $rtr)+ + } + #[repr(C)] #[derive(Debug)] #[allow(missing_copy_implementations)] + pub struct $interface { + pub lpVtbl: *const $vtbl + } + impl $interface { + #[inline] + $(pub unsafe fn $method(&mut self $(,$p: $t)*) -> $rtr { + ((*self.lpVtbl).$method)(self $(,$p)*) + })+ + } + impl ::std::ops::Deref for $interface { + type Target = $crate::$pinterface; + #[inline] + fn deref(&self) -> &$crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + impl ::std::ops::DerefMut for $interface { + #[inline] + fn deref_mut(&mut self) -> &mut $crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + }; +} +macro_rules! UNION { + ($base:ident, $field:ident, $variant:ident, $variantmut:ident, $fieldtype:ty) => { + impl $base { + #[inline] + pub unsafe fn $variant(&self) -> &$fieldtype { + ::std::mem::transmute(&self.$field) + } + #[inline] + pub unsafe fn $variantmut(&mut self) -> &mut $fieldtype { + ::std::mem::transmute(&mut self.$field) + } + } + } +} +macro_rules! BITFIELD { + ($base:ident $field:ident: $fieldtype:ty [ + $($thing:ident $set_thing:ident[$r:expr],)+ + ]) => { + impl $base {$( + #[inline] + pub fn $thing(&self) -> $fieldtype { + let size = ::std::mem::size_of::<$fieldtype>() * 8; + self.$field << (size - $r.end) >> (size - $r.end + $r.start) + } + #[inline] + pub fn $set_thing(&mut self, val: $fieldtype) { + let mask = ((1 << ($r.end - $r.start)) - 1) << $r.start; + self.$field &= !mask; + self.$field |= (val << $r.start) & mask; + } + )+} + } +} +#[macro_export] +macro_rules! ENUM { + {enum $name:ident { $($variant:ident = $value:expr,)+ }} => { + #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + pub struct $name(pub u32); + $(pub const $variant: $name = $name($value);)+ + }; + {enum $name:ident { $variant:ident = $value:expr, $($rest:tt)* }} => { + #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + pub struct $name(pub u32); + pub const $variant: $name = $name($value); + ENUM!{@gen $name, $variant, $($rest)*} + }; + {enum $name:ident { $variant:ident, $($rest:tt)* }} => { + ENUM!{enum $name { $variant = 0, $($rest)* }} + }; + {@gen $name:ident, $base:ident,} => {}; + {@gen $name:ident, $base:ident, $variant:ident = $value:expr, $($rest:tt)*} => { + pub const $variant: $name = $name($value); + ENUM!{@gen $name, $variant, $($rest)*} + }; + {@gen $name:ident, $base:ident, $variant:ident, $($rest:tt)*} => { + pub const $variant: $name = $name($base.0 + 1u32); + ENUM!{@gen $name, $variant, $($rest)*} + }; +} +macro_rules! FLAGS { + {enum $name:ident { $($variant:ident = $value:expr,)+ }} => { + #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + pub struct $name(pub u32); + $(pub const $variant: $name = $name($value);)+ + impl ::std::ops::BitAnd<$name> for $name { + type Output = $name; + fn bitand(self, o: $name) -> $name { $name(self.0 & o.0) } + } + impl ::std::ops::BitOr<$name> for $name { + type Output = $name; + fn bitor(self, o: $name) -> $name { $name(self.0 | o.0) } + } + impl ::std::ops::BitXor<$name> for $name { + type Output = $name; + fn bitxor(self, o: $name) -> $name { $name(self.0 ^ o.0) } + } + impl ::std::ops::Not for $name { + type Output = $name; + fn not(self) -> $name { $name(!self.0) } + } + } +} +macro_rules! STRUCT { + {$(#[$attrs:meta])* nodebug struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { + #[repr(C)] $(#[$attrs])* + pub struct $name { + $(pub $field: $ftype,)+ + } + impl Copy for $name {} + impl Clone for $name { fn clone(&self) -> $name { *self } } + }; + {$(#[$attrs:meta])* struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { + #[repr(C)] #[derive(Debug)] $(#[$attrs])* + pub struct $name { + $(pub $field: $ftype,)+ + } + impl Copy for $name {} + impl Clone for $name { fn clone(&self) -> $name { *self } } + }; +} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/memoryapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/memoryapi.rs new file mode 100644 index 0000000..30cefea --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/memoryapi.rs @@ -0,0 +1,19 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-memory-l1-1-0 +pub const FILE_MAP_WRITE: ::DWORD = ::SECTION_MAP_WRITE; +pub const FILE_MAP_READ: ::DWORD = ::SECTION_MAP_READ; +pub const FILE_MAP_ALL_ACCESS: ::DWORD = ::SECTION_ALL_ACCESS; +pub const FILE_MAP_EXECUTE: ::DWORD = ::SECTION_MAP_EXECUTE_EXPLICIT; +pub const FILE_MAP_COPY: ::DWORD = 0x00000001; +pub const FILE_MAP_RESERVE: ::DWORD = 0x80000000; +ENUM!{enum MEMORY_RESOURCE_NOTIFICATION_TYPE { + LowMemoryResourceNotification, + HighMemoryResourceNotification, +}} +STRUCT!{struct WIN32_MEMORY_RANGE_ENTRY { + VirtualAddress: ::PVOID, + NumberOfBytes: ::SIZE_T, +}} +pub type PWIN32_MEMORY_RANGE_ENTRY = *mut WIN32_MEMORY_RANGE_ENTRY; +pub type PBAD_MEMORY_CALLBACK_ROUTINE = Option<unsafe extern "system" fn()>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/minschannel.rs b/bash-5.1/vendor/winapi-0.2.8/src/minschannel.rs new file mode 100644 index 0000000..828f1be --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/minschannel.rs @@ -0,0 +1,56 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Public Definitions for MIN SCHANNEL Security Provider + +pub const SECPKG_ATTR_ISSUER_LIST: ::DWORD = 0x50; +pub const SECPKG_ATTR_REMOTE_CRED: ::DWORD = 0x51; +pub const SECPKG_ATTR_LOCAL_CRED: ::DWORD = 0x52; +pub const SECPKG_ATTR_REMOTE_CERT_CONTEXT: ::DWORD = 0x53; +pub const SECPKG_ATTR_LOCAL_CERT_CONTEXT: ::DWORD = 0x54; +pub const SECPKG_ATTR_ROOT_STORE: ::DWORD = 0x55; +pub const SECPKG_ATTR_SUPPORTED_ALGS: ::DWORD = 0x56; +pub const SECPKG_ATTR_CIPHER_STRENGTHS: ::DWORD = 0x57; +pub const SECPKG_ATTR_SUPPORTED_PROTOCOLS: ::DWORD = 0x58; +pub const SECPKG_ATTR_ISSUER_LIST_EX: ::DWORD = 0x59; +pub const SECPKG_ATTR_CONNECTION_INFO: ::DWORD = 0x5a; +pub const SECPKG_ATTR_EAP_KEY_BLOCK: ::DWORD = 0x5b; +pub const SECPKG_ATTR_MAPPED_CRED_ATTR: ::DWORD = 0x5c; +pub const SECPKG_ATTR_SESSION_INFO: ::DWORD = 0x5d; +pub const SECPKG_ATTR_APP_DATA: ::DWORD = 0x5e; +pub const SECPKG_ATTR_REMOTE_CERTIFICATES: ::DWORD = 0x5F; +pub const SECPKG_ATTR_CLIENT_CERT_POLICY: ::DWORD = 0x60; +pub const SECPKG_ATTR_CC_POLICY_RESULT: ::DWORD = 0x61; +pub const SECPKG_ATTR_USE_NCRYPT: ::DWORD = 0x62; +pub const SECPKG_ATTR_LOCAL_CERT_INFO: ::DWORD = 0x63; +pub const SECPKG_ATTR_CIPHER_INFO: ::DWORD = 0x64; +pub const SECPKG_ATTR_EAP_PRF_INFO: ::DWORD = 0x65; +pub const SECPKG_ATTR_SUPPORTED_SIGNATURES: ::DWORD = 0x66; +pub const SECPKG_ATTR_REMOTE_CERT_CHAIN: ::DWORD = 0x67; +pub const SECPKG_ATTR_UI_INFO: ::DWORD = 0x68; +pub const SECPKG_ATTR_EARLY_START: ::DWORD = 0x69; + +STRUCT!{struct SecPkgCred_SupportedAlgs { + cSupportedAlgs: ::DWORD, + palgSupportedAlgs: ::ALG_ID, +}} + +STRUCT!{struct SecPkgCred_CipherStrengths { + dwMinimumCipherStrength: ::DWORD, + dwMaximumCipherStrength: ::DWORD, +}} + +STRUCT!{struct SecPkgCred_SupportedProtocols { + grbitProtocol: ::DWORD, +}} + +STRUCT!{struct SecPkgCred_ClientCertPolicy { + dwFlags: ::DWORD, + guidPolicyId: ::GUID, + dwCertFlags: ::DWORD, + dwUrlRetrievalTimeout: ::DWORD, + fCheckRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, + fOmitUsageCheck: ::BOOL, + pwszSslCtlStoreName: ::LPWSTR, + pwszSslCtlIdentifier: ::LPWSTR, +}} \ No newline at end of file diff --git a/bash-5.1/vendor/winapi-0.2.8/src/minwinbase.rs b/bash-5.1/vendor/winapi-0.2.8/src/minwinbase.rs new file mode 100644 index 0000000..f6317fa --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/minwinbase.rs @@ -0,0 +1,253 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This module defines the 32-Bit Windows Base APIs +STRUCT!{struct SECURITY_ATTRIBUTES { + nLength: ::DWORD, + lpSecurityDescriptor: ::LPVOID, + bInheritHandle: ::BOOL, +}} +pub type PSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; +pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; +STRUCT!{struct OVERLAPPED { + Internal: ::ULONG_PTR, + InternalHigh: ::ULONG_PTR, + Offset: ::DWORD, + OffsetHigh: ::DWORD, + hEvent: ::HANDLE, +}} +UNION!(OVERLAPPED, Offset, Pointer, Pointer_mut, ::PVOID); +pub type LPOVERLAPPED = *mut OVERLAPPED; +STRUCT!{struct OVERLAPPED_ENTRY { + lpCompletionKey: ::ULONG_PTR, + lpOverlapped: LPOVERLAPPED, + Internal: ::ULONG_PTR, + dwNumberOfBytesTransferred: ::DWORD, +}} +pub type LPOVERLAPPED_ENTRY = *mut OVERLAPPED_ENTRY; +STRUCT!{struct SYSTEMTIME { + wYear: ::WORD, + wMonth: ::WORD, + wDayOfWeek: ::WORD, + wDay: ::WORD, + wHour: ::WORD, + wMinute: ::WORD, + wSecond: ::WORD, + wMilliseconds: ::WORD, +}} +pub type PSYSTEMTIME = *mut SYSTEMTIME; +pub type LPSYSTEMTIME = *mut SYSTEMTIME; +STRUCT!{nodebug struct WIN32_FIND_DATAA { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, + dwReserved0: ::DWORD, + dwReserved1: ::DWORD, + cFileName: [::CHAR; ::MAX_PATH], + cAlternateFileName: [::CHAR; 14], +}} +pub type PWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA; +pub type LPWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA; +STRUCT!{nodebug struct WIN32_FIND_DATAW { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, + dwReserved0: ::DWORD, + dwReserved1: ::DWORD, + cFileName: [::WCHAR; ::MAX_PATH], + cAlternateFileName: [::WCHAR; 14], +}} +pub type PWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; +pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; +ENUM!{enum FINDEX_INFO_LEVELS { + FindExInfoStandard, + FindExInfoBasic, + FindExInfoMaxInfoLevel, +}} +pub const FIND_FIRST_EX_CASE_SENSITIVE: ::DWORD = 0x00000001; +pub const FIND_FIRST_EX_LARGE_FETCH: ::DWORD = 0x00000002; +ENUM!{enum FINDEX_SEARCH_OPS { + FindExSearchNameMatch, + FindExSearchLimitToDirectories, + FindExSearchLimitToDevices, + FindExSearchMaxSearchOp, +}} +ENUM!{enum GET_FILEEX_INFO_LEVELS { + GetFileExInfoStandard, + GetFileExMaxInfoLevel, +}} +ENUM!{enum FILE_INFO_BY_HANDLE_CLASS { + FileBasicInfo, + FileStandardInfo, + FileNameInfo, + FileRenameInfo, + FileDispositionInfo, + FileAllocationInfo, + FileEndOfFileInfo, + FileStreamInfo, + FileCompressionInfo, + FileAttributeTagInfo, + FileIdBothDirectoryInfo, + FileIdBothDirectoryRestartInfo, + FileIoPriorityHintInfo, + FileRemoteProtocolInfo, + FileFullDirectoryInfo, + FileFullDirectoryRestartInfo, + FileStorageInfo, + FileAlignmentInfo, + FileIdInfo, + FileIdExtdDirectoryInfo, + FileIdExtdDirectoryRestartInfo, + MaximumFileInfoByHandleClass, +}} +pub type PFILE_INFO_BY_HANDLE_CLASS = *mut FILE_INFO_BY_HANDLE_CLASS; +pub type CRITICAL_SECTION = ::RTL_CRITICAL_SECTION; +pub type PCRITICAL_SECTION = ::PRTL_CRITICAL_SECTION; +pub type LPCRITICAL_SECTION = ::PRTL_CRITICAL_SECTION; +pub type CRITICAL_SECTION_DEBUG = ::RTL_CRITICAL_SECTION_DEBUG; +pub type PCRITICAL_SECTION_DEBUG = ::PRTL_CRITICAL_SECTION_DEBUG; +pub type LPCRITICAL_SECTION_DEBUG = ::PRTL_CRITICAL_SECTION_DEBUG; +pub type LPOVERLAPPED_COMPLETION_ROUTINE = Option<unsafe extern "system" fn( + dwErrorCode: ::DWORD, dwNumberOfBytesTransfered: ::DWORD, lpOverlapped: LPOVERLAPPED, +)>; +pub const LOCKFILE_FAIL_IMMEDIATELY: ::DWORD = 0x00000001; +pub const LOCKFILE_EXCLUSIVE_LOCK: ::DWORD = 0x00000002; +STRUCT!{struct PROCESS_HEAP_ENTRY_Block { + hMem: ::HANDLE, + dwReserved: [::DWORD; 3], +}} +STRUCT!{struct PROCESS_HEAP_ENTRY_Region { + dwCommittedSize: ::DWORD, + dwUnCommittedSize: ::DWORD, + lpFirstBlock: ::LPVOID, + lpLastBlock: ::LPVOID, +}} +STRUCT!{struct PROCESS_HEAP_ENTRY { + lpData: ::PVOID, + cbData: ::DWORD, + cbOverhead: ::BYTE, + iRegionIndex: ::BYTE, + wFlags: ::WORD, + Region: PROCESS_HEAP_ENTRY_Region, +}} +UNION!(PROCESS_HEAP_ENTRY, Region, Block, Block_mut, PROCESS_HEAP_ENTRY_Block); +pub type LPPROCESS_HEAP_ENTRY = *mut PROCESS_HEAP_ENTRY; +pub type PPROCESS_HEAP_ENTRY = *mut PROCESS_HEAP_ENTRY; +pub const PROCESS_HEAP_REGION: ::WORD = 0x0001; +pub const PROCESS_HEAP_UNCOMMITTED_RANGE: ::WORD = 0x0002; +pub const PROCESS_HEAP_ENTRY_BUSY: ::WORD = 0x0004; +pub const PROCESS_HEAP_SEG_ALLOC: ::WORD = 0x0008; +pub const PROCESS_HEAP_ENTRY_MOVEABLE: ::WORD = 0x0010; +pub const PROCESS_HEAP_ENTRY_DDESHARE: ::WORD = 0x0020; +pub type PTHREAD_START_ROUTINE = Option<unsafe extern "system" fn( + lpThreadParameter: ::LPVOID, +) -> ::DWORD>; +pub type LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE; +pub type LPCONTEXT = ::PCONTEXT; +STRUCT!{struct REASON_CONTEXT_Detailed { + LocalizedReasonModule: ::HMODULE, + LocalizedReasonId: ::ULONG, + ReasonStringCount: ::ULONG, + ReasonStrings: *mut ::LPWSTR, +}} +STRUCT!{struct REASON_CONTEXT { + Version: ::ULONG, + Flags: ::DWORD, + Reason: REASON_CONTEXT_Detailed, +}} +UNION!(REASON_CONTEXT, Reason, SimpleReasonString, SimpleReasonString_mut, ::LPWSTR); +pub type PREASON_CONTEXT = *mut REASON_CONTEXT; +pub const EXCEPTION_DEBUG_EVENT: ::DWORD = 1; +pub const CREATE_THREAD_DEBUG_EVENT: ::DWORD = 2; +pub const CREATE_PROCESS_DEBUG_EVENT: ::DWORD = 3; +pub const EXIT_THREAD_DEBUG_EVENT: ::DWORD = 4; +pub const EXIT_PROCESS_DEBUG_EVENT: ::DWORD = 5; +pub const LOAD_DLL_DEBUG_EVENT: ::DWORD = 6; +pub const UNLOAD_DLL_DEBUG_EVENT: ::DWORD = 7; +pub const OUTPUT_DEBUG_STRING_EVENT: ::DWORD = 8; +pub const RIP_EVENT: ::DWORD = 9; +STRUCT!{struct EXCEPTION_DEBUG_INFO { + ExceptionRecord: ::EXCEPTION_RECORD, + dwFirstChance: ::DWORD, +}} +pub type LPEXCEPTION_DEBUG_INFO = *mut EXCEPTION_DEBUG_INFO; +STRUCT!{nodebug struct CREATE_THREAD_DEBUG_INFO { + hThread: ::HANDLE, + lpThreadLocalBase: ::LPVOID, + lpStartAddress: LPTHREAD_START_ROUTINE, +}} +pub type LPCREATE_THREAD_DEBUG_INFO = *mut CREATE_THREAD_DEBUG_INFO; +STRUCT!{nodebug struct CREATE_PROCESS_DEBUG_INFO { + hFile: ::HANDLE, + hProcess: ::HANDLE, + hThread: ::HANDLE, + lpBaseOfImage: ::LPVOID, + dwDebugInfoFileOffset: ::DWORD, + nDebugInfoSize: ::DWORD, + lpThreadLocalBase: ::LPVOID, + lpStartAddress: LPTHREAD_START_ROUTINE, + lpImageName: ::LPVOID, + fUnicode: ::WORD, +}} +pub type LPCREATE_PROCESS_DEBUG_INFO = *mut CREATE_PROCESS_DEBUG_INFO; +STRUCT!{struct EXIT_THREAD_DEBUG_INFO { + dwExitCode: ::DWORD, +}} +pub type LPEXIT_THREAD_DEBUG_INFO = *mut EXIT_THREAD_DEBUG_INFO; +STRUCT!{struct EXIT_PROCESS_DEBUG_INFO { + dwExitCode: ::DWORD, +}} +pub type LPEXIT_PROCESS_DEBUG_INFO = *mut EXIT_PROCESS_DEBUG_INFO; +STRUCT!{struct LOAD_DLL_DEBUG_INFO { + hFile: ::HANDLE, + lpBaseOfDll: ::LPVOID, + dwDebugInfoFileOffset: ::DWORD, + nDebugInfoSize: ::DWORD, + lpImageName: ::LPVOID, + fUnicode: ::WORD, +}} +pub type LPLOAD_DLL_DEBUG_INFO = *mut LOAD_DLL_DEBUG_INFO; +STRUCT!{struct UNLOAD_DLL_DEBUG_INFO { + lpBaseOfDll: ::LPVOID, +}} +pub type LPUNLOAD_DLL_DEBUG_INFO = *mut UNLOAD_DLL_DEBUG_INFO; +STRUCT!{struct OUTPUT_DEBUG_STRING_INFO { + lpDebugStringData: ::LPSTR, + fUnicode: ::WORD, + nDebugStringLength: ::WORD, +}} +pub type LPOUTPUT_DEBUG_STRING_INFO = *mut OUTPUT_DEBUG_STRING_INFO; +STRUCT!{struct RIP_INFO { + dwError: ::DWORD, + dwType: ::DWORD, +}} +pub type LPRIP_INFO = *mut RIP_INFO; +#[cfg(target_arch="x86_64")] +STRUCT!{nodebug struct DEBUG_EVENT { + dwDebugEventCode: ::DWORD, + dwProcessId: ::DWORD, + dwThreadId: ::DWORD, + u: [u8; 160], +}} +#[cfg(target_arch="x86")] +STRUCT!{nodebug struct DEBUG_EVENT { + dwDebugEventCode: ::DWORD, + dwProcessId: ::DWORD, + dwThreadId: ::DWORD, + u: [u8; 84], +}} +UNION!(DEBUG_EVENT, u, Exception, Exception_mut, EXCEPTION_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, CreateThread, CreateThread_mut, CREATE_THREAD_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, CreateProcessInfo, CreateProcessInfo_mut, CREATE_PROCESS_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, ExitThread, ExitThread_mut, EXIT_THREAD_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, ExitProcess, ExitProcess_mut, EXIT_PROCESS_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, LoadDll, LoadDll_mut, LOAD_DLL_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, UnloadDll, UnloadDll_mut, UNLOAD_DLL_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, DebugString, DebugString_mut, OUTPUT_DEBUG_STRING_INFO); +UNION!(DEBUG_EVENT, u, RipInfo, RipInfo_mut, RIP_INFO); +pub type LPDEBUG_EVENT = *mut DEBUG_EVENT; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/minwindef.rs b/bash-5.1/vendor/winapi-0.2.8/src/minwindef.rs new file mode 100644 index 0000000..a5ed017 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/minwindef.rs @@ -0,0 +1,89 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Basic Windows Type Definitions for minwin partition +pub type ULONG = ::c_ulong; +pub type PULONG = *mut ULONG; +pub type USHORT = ::c_ushort; +pub type PUSHORT = *mut USHORT; +pub type UCHAR = ::c_uchar; +pub type PUCHAR = *mut UCHAR; +pub type PSZ = *mut ::c_char; +pub const MAX_PATH: usize = 260; +pub const FALSE: BOOL = 0; +pub const TRUE: BOOL = 1; +pub type DWORD = ::c_ulong; +pub type BOOL = ::c_int; +pub type BYTE = ::c_uchar; +pub type WORD = ::c_ushort; +pub type FLOAT = ::c_float; +pub type PFLOAT = *mut FLOAT; +pub type PBOOL = *mut BOOL; +pub type LPBOOL = *mut BOOL; +pub type PBYTE = *mut BYTE; +pub type LPBYTE = *mut BYTE; +pub type PINT = *mut ::c_int; +pub type LPINT = *mut ::c_int; +pub type PWORD = *mut WORD; +pub type LPWORD = *mut WORD; +pub type LPLONG = *mut ::c_long; +pub type PDWORD = *mut DWORD; +pub type LPDWORD = *mut DWORD; +pub type LPVOID = *mut ::c_void; +pub type LPCVOID = *const ::c_void; +pub type INT = ::c_int; +pub type UINT = ::c_uint; +pub type PUINT = *mut ::c_uint; +pub type WPARAM = ::UINT_PTR; +pub type LPARAM = ::LONG_PTR; +pub type LRESULT = ::LONG_PTR; +pub fn MAKEWORD(a: BYTE, b: BYTE) -> WORD { + (a as WORD) | ((b as WORD) << 8) +} +pub fn MAKELONG(a: WORD, b: WORD) -> ::LONG { + ((a as DWORD) | ((b as DWORD) << 16)) as ::LONG +} +pub fn LOWORD(l: DWORD) -> WORD { + (l & 0xffff) as WORD +} +pub fn HIWORD(l: DWORD) -> WORD { + ((l >> 16) & 0xffff) as WORD +} +pub fn LOBYTE(l: WORD) -> BYTE { + (l & 0xff) as BYTE +} +pub fn HIBYTE(l: WORD) -> BYTE { + ((l >> 8) & 0xff) as BYTE +} +pub type SPHANDLE = *mut ::HANDLE; +pub type LPHANDLE = *mut ::HANDLE; +pub type HGLOBAL = ::HANDLE; +pub type HLOCAL = ::HANDLE; +pub type GLOBALHANDLE = ::HANDLE; +pub type LOCALHANDLE = ::HANDLE; +/// Pointer to probably a function with unknown type signature. +pub type FARPROC = *const ::c_void; +/// Pointer to probably a function with unknown type signature. +pub type NEARPROC = *const ::c_void; +/// Pointer to probably a function with unknown type signature. +pub type PROC = *const ::c_void; +pub type ATOM = WORD; +DECLARE_HANDLE!(HKEY, HKEY__); +pub type PHKEY = *mut HKEY; +DECLARE_HANDLE!(HMETAFILE, HMETAFILE__); +DECLARE_HANDLE!(HINSTANCE, HINSTANCE__); +pub type HMODULE = HINSTANCE; +DECLARE_HANDLE!(HRGN, HRGN__); +DECLARE_HANDLE!(HRSRC, HRSRC__); +DECLARE_HANDLE!(HSPRITE, HSPRITE__); +DECLARE_HANDLE!(HLSURF, HLSURF__); +DECLARE_HANDLE!(HSTR, HSTR__); +DECLARE_HANDLE!(HTASK, HTASK__); +DECLARE_HANDLE!(HWINSTA, HWINSTA__); +DECLARE_HANDLE!(HKL, HKL__); +pub type HFILE = ::c_int; +STRUCT!{struct FILETIME { + dwLowDateTime: DWORD, + dwHighDateTime: DWORD, +}} +pub type PFILETIME = *mut FILETIME; +pub type LPFILETIME = *mut FILETIME; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/mmdeviceapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/mmdeviceapi.rs new file mode 100644 index 0000000..9fc85a7 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/mmdeviceapi.rs @@ -0,0 +1,63 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +pub const DEVICE_STATE_ACTIVE: ::DWORD = 0x00000001; +pub const DEVICE_STATE_DISABLED: ::DWORD = 0x00000002; +pub const DEVICE_STATE_NOTPRESENT: ::DWORD = 0x00000004; +pub const DEVICE_STATE_UNPLUGGED: ::DWORD = 0x00000008; +pub const DEVICE_STATEMASK_ALL: ::DWORD = 0x0000000F; +ENUM!{enum EDataFlow { + eRender, + eCapture, + eAll, + EDataFlow_enum_count, +}} +ENUM!{enum ERole { + eConsole, + eMultimedia, + eCommunications, + ERole_enum_count, +}} +DEFINE_GUID!(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, + 0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E); +DEFINE_GUID!(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, + 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6); +RIDL!( +interface IMMDevice(IMMDeviceVtbl): IUnknown(IUnknownVtbl) { + fn Activate( + &mut self, iid: ::REFIID, dwClsCtx: ::DWORD, pActivationParams: *mut ::PROPVARIANT, + ppInterface: *mut ::LPVOID + ) -> ::HRESULT, + fn OpenPropertyStore( + &mut self, stgmAccess: ::DWORD, ppProperties: *mut *mut ::IPropertyStore + ) -> ::HRESULT, + fn GetId(&mut self, ppstrId: *mut ::LPWSTR) -> ::HRESULT, + fn GetState(&mut self, pdwState: *mut ::DWORD) -> ::HRESULT +} +); +RIDL!( +interface IMMDeviceEnumerator(IMMDeviceEnumeratorVtbl): IUnknown(IUnknownVtbl) { + fn EnumAudioEndpoints( + &mut self, dataFlow: EDataFlow, dwStateMask: ::DWORD, + ppDevices: *mut *mut IMMDeviceCollection + ) -> ::HRESULT, + fn GetDefaultAudioEndpoint( + &mut self, dataFlow: EDataFlow, role: ERole, ppEndpoint: *mut *mut IMMDevice + ) -> ::HRESULT, + fn GetDevice(&mut self, pwstrId: ::LPCWSTR, ppDevices: *mut *mut IMMDevice) -> ::HRESULT, + fn RegisterEndpointNotificationCallback( + &mut self, pClient: *mut IMMNotificationClient + ) -> ::HRESULT, + fn UnregisterEndpointNotificationCallback( + &mut self, pClient: *mut IMMNotificationClient + ) -> ::HRESULT +} +); +RIDL!( +interface IMMDeviceCollection(IMMDeviceCollectionVtbl): IUnknown(IUnknownVtbl) { + fn GetCount(&mut self, pcDevices: *const ::UINT) -> ::HRESULT, + fn Item(&mut self, nDevice: ::UINT, ppDevice: *mut *mut IMMDevice) -> ::HRESULT +} +); +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMMNotificationClient; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/mmreg.rs b/bash-5.1/vendor/winapi-0.2.8/src/mmreg.rs new file mode 100644 index 0000000..826d96d --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/mmreg.rs @@ -0,0 +1,304 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub const WAVE_FORMAT_UNKNOWN: ::WORD = 0x0000; +pub const WAVE_FORMAT_PCM: ::WORD = 0x0001; +pub const WAVE_FORMAT_ADPCM: ::WORD = 0x0002; +pub const WAVE_FORMAT_IEEE_FLOAT: ::WORD = 0x0003; +pub const WAVE_FORMAT_VSELP: ::WORD = 0x0004; +pub const WAVE_FORMAT_IBM_CVSD: ::WORD = 0x0005; +pub const WAVE_FORMAT_ALAW: ::WORD = 0x0006; +pub const WAVE_FORMAT_MULAW: ::WORD = 0x0007; +pub const WAVE_FORMAT_DTS: ::WORD = 0x0008; +pub const WAVE_FORMAT_DRM: ::WORD = 0x0009; +pub const WAVE_FORMAT_WMAVOICE9: ::WORD = 0x000A; +pub const WAVE_FORMAT_WMAVOICE10: ::WORD = 0x000B; +pub const WAVE_FORMAT_OKI_ADPCM: ::WORD = 0x0010; +pub const WAVE_FORMAT_DVI_ADPCM: ::WORD = 0x0011; +pub const WAVE_FORMAT_IMA_ADPCM: ::WORD = WAVE_FORMAT_DVI_ADPCM; +pub const WAVE_FORMAT_MEDIASPACE_ADPCM: ::WORD = 0x0012; +pub const WAVE_FORMAT_SIERRA_ADPCM: ::WORD = 0x0013; +pub const WAVE_FORMAT_G723_ADPCM: ::WORD = 0x0014; +pub const WAVE_FORMAT_DIGISTD: ::WORD = 0x0015; +pub const WAVE_FORMAT_DIGIFIX: ::WORD = 0x0016; +pub const WAVE_FORMAT_DIALOGIC_OKI_ADPCM: ::WORD = 0x0017; +pub const WAVE_FORMAT_MEDIAVISION_ADPCM: ::WORD = 0x0018; +pub const WAVE_FORMAT_CU_CODEC: ::WORD = 0x0019; +pub const WAVE_FORMAT_HP_DYN_VOICE: ::WORD = 0x001A; +pub const WAVE_FORMAT_YAMAHA_ADPCM: ::WORD = 0x0020; +pub const WAVE_FORMAT_SONARC: ::WORD = 0x0021; +pub const WAVE_FORMAT_DSPGROUP_TRUESPEECH: ::WORD = 0x0022; +pub const WAVE_FORMAT_ECHOSC1: ::WORD = 0x0023; +pub const WAVE_FORMAT_AUDIOFILE_AF36: ::WORD = 0x0024; +pub const WAVE_FORMAT_APTX: ::WORD = 0x0025; +pub const WAVE_FORMAT_AUDIOFILE_AF10: ::WORD = 0x0026; +pub const WAVE_FORMAT_PROSODY_1612: ::WORD = 0x0027; +pub const WAVE_FORMAT_LRC: ::WORD = 0x0028; +pub const WAVE_FORMAT_DOLBY_AC2: ::WORD = 0x0030; +pub const WAVE_FORMAT_GSM610: ::WORD = 0x0031; +pub const WAVE_FORMAT_MSNAUDIO: ::WORD = 0x0032; +pub const WAVE_FORMAT_ANTEX_ADPCME: ::WORD = 0x0033; +pub const WAVE_FORMAT_CONTROL_RES_VQLPC: ::WORD = 0x0034; +pub const WAVE_FORMAT_DIGIREAL: ::WORD = 0x0035; +pub const WAVE_FORMAT_DIGIADPCM: ::WORD = 0x0036; +pub const WAVE_FORMAT_CONTROL_RES_CR10: ::WORD = 0x0037; +pub const WAVE_FORMAT_NMS_VBXADPCM: ::WORD = 0x0038; +pub const WAVE_FORMAT_CS_IMAADPCM: ::WORD = 0x0039; +pub const WAVE_FORMAT_ECHOSC3: ::WORD = 0x003A; +pub const WAVE_FORMAT_ROCKWELL_ADPCM: ::WORD = 0x003B; +pub const WAVE_FORMAT_ROCKWELL_DIGITALK: ::WORD = 0x003C; +pub const WAVE_FORMAT_XEBEC: ::WORD = 0x003D; +pub const WAVE_FORMAT_G721_ADPCM: ::WORD = 0x0040; +pub const WAVE_FORMAT_G728_CELP: ::WORD = 0x0041; +pub const WAVE_FORMAT_MSG723: ::WORD = 0x0042; +pub const WAVE_FORMAT_INTEL_G723_1: ::WORD = 0x0043; +pub const WAVE_FORMAT_INTEL_G729: ::WORD = 0x0044; +pub const WAVE_FORMAT_SHARP_G726: ::WORD = 0x0045; +pub const WAVE_FORMAT_MPEG: ::WORD = 0x0050; +pub const WAVE_FORMAT_RT24: ::WORD = 0x0052; +pub const WAVE_FORMAT_PAC: ::WORD = 0x0053; +pub const WAVE_FORMAT_MPEGLAYER3: ::WORD = 0x0055; +pub const WAVE_FORMAT_LUCENT_G723: ::WORD = 0x0059; +pub const WAVE_FORMAT_CIRRUS: ::WORD = 0x0060; +pub const WAVE_FORMAT_ESPCM: ::WORD = 0x0061; +pub const WAVE_FORMAT_VOXWARE: ::WORD = 0x0062; +pub const WAVE_FORMAT_CANOPUS_ATRAC: ::WORD = 0x0063; +pub const WAVE_FORMAT_G726_ADPCM: ::WORD = 0x0064; +pub const WAVE_FORMAT_G722_ADPCM: ::WORD = 0x0065; +pub const WAVE_FORMAT_DSAT: ::WORD = 0x0066; +pub const WAVE_FORMAT_DSAT_DISPLAY: ::WORD = 0x0067; +pub const WAVE_FORMAT_VOXWARE_BYTE_ALIGNED: ::WORD = 0x0069; +pub const WAVE_FORMAT_VOXWARE_AC8: ::WORD = 0x0070; +pub const WAVE_FORMAT_VOXWARE_AC10: ::WORD = 0x0071; +pub const WAVE_FORMAT_VOXWARE_AC16: ::WORD = 0x0072; +pub const WAVE_FORMAT_VOXWARE_AC20: ::WORD = 0x0073; +pub const WAVE_FORMAT_VOXWARE_RT24: ::WORD = 0x0074; +pub const WAVE_FORMAT_VOXWARE_RT29: ::WORD = 0x0075; +pub const WAVE_FORMAT_VOXWARE_RT29HW: ::WORD = 0x0076; +pub const WAVE_FORMAT_VOXWARE_VR12: ::WORD = 0x0077; +pub const WAVE_FORMAT_VOXWARE_VR18: ::WORD = 0x0078; +pub const WAVE_FORMAT_VOXWARE_TQ40: ::WORD = 0x0079; +pub const WAVE_FORMAT_VOXWARE_SC3: ::WORD = 0x007A; +pub const WAVE_FORMAT_VOXWARE_SC3_1: ::WORD = 0x007B; +pub const WAVE_FORMAT_SOFTSOUND: ::WORD = 0x0080; +pub const WAVE_FORMAT_VOXWARE_TQ60: ::WORD = 0x0081; +pub const WAVE_FORMAT_MSRT24: ::WORD = 0x0082; +pub const WAVE_FORMAT_G729A: ::WORD = 0x0083; +pub const WAVE_FORMAT_MVI_MVI2: ::WORD = 0x0084; +pub const WAVE_FORMAT_DF_G726: ::WORD = 0x0085; +pub const WAVE_FORMAT_DF_GSM610: ::WORD = 0x0086; +pub const WAVE_FORMAT_ISIAUDIO: ::WORD = 0x0088; +pub const WAVE_FORMAT_ONLIVE: ::WORD = 0x0089; +pub const WAVE_FORMAT_MULTITUDE_FT_SX20: ::WORD = 0x008A; +pub const WAVE_FORMAT_INFOCOM_ITS_G721_ADPCM: ::WORD = 0x008B; +pub const WAVE_FORMAT_CONVEDIA_G729: ::WORD = 0x008C; +pub const WAVE_FORMAT_CONGRUENCY: ::WORD = 0x008D; +pub const WAVE_FORMAT_SBC24: ::WORD = 0x0091; +pub const WAVE_FORMAT_DOLBY_AC3_SPDIF: ::WORD = 0x0092; +pub const WAVE_FORMAT_MEDIASONIC_G723: ::WORD = 0x0093; +pub const WAVE_FORMAT_PROSODY_8KBPS: ::WORD = 0x0094; +pub const WAVE_FORMAT_ZYXEL_ADPCM: ::WORD = 0x0097; +pub const WAVE_FORMAT_PHILIPS_LPCBB: ::WORD = 0x0098; +pub const WAVE_FORMAT_PACKED: ::WORD = 0x0099; +pub const WAVE_FORMAT_MALDEN_PHONYTALK: ::WORD = 0x00A0; +pub const WAVE_FORMAT_RACAL_RECORDER_GSM: ::WORD = 0x00A1; +pub const WAVE_FORMAT_RACAL_RECORDER_G720_A: ::WORD = 0x00A2; +pub const WAVE_FORMAT_RACAL_RECORDER_G723_1: ::WORD = 0x00A3; +pub const WAVE_FORMAT_RACAL_RECORDER_TETRA_ACELP: ::WORD = 0x00A4; +pub const WAVE_FORMAT_NEC_AAC: ::WORD = 0x00B0; +pub const WAVE_FORMAT_RAW_AAC1: ::WORD = 0x00FF; +pub const WAVE_FORMAT_RHETOREX_ADPCM: ::WORD = 0x0100; +pub const WAVE_FORMAT_IRAT: ::WORD = 0x0101; +pub const WAVE_FORMAT_VIVO_G723: ::WORD = 0x0111; +pub const WAVE_FORMAT_VIVO_SIREN: ::WORD = 0x0112; +pub const WAVE_FORMAT_PHILIPS_CELP: ::WORD = 0x0120; +pub const WAVE_FORMAT_PHILIPS_GRUNDIG: ::WORD = 0x0121; +pub const WAVE_FORMAT_DIGITAL_G723: ::WORD = 0x0123; +pub const WAVE_FORMAT_SANYO_LD_ADPCM: ::WORD = 0x0125; +pub const WAVE_FORMAT_SIPROLAB_ACEPLNET: ::WORD = 0x0130; +pub const WAVE_FORMAT_SIPROLAB_ACELP4800: ::WORD = 0x0131; +pub const WAVE_FORMAT_SIPROLAB_ACELP8V3: ::WORD = 0x0132; +pub const WAVE_FORMAT_SIPROLAB_G729: ::WORD = 0x0133; +pub const WAVE_FORMAT_SIPROLAB_G729A: ::WORD = 0x0134; +pub const WAVE_FORMAT_SIPROLAB_KELVIN: ::WORD = 0x0135; +pub const WAVE_FORMAT_VOICEAGE_AMR: ::WORD = 0x0136; +pub const WAVE_FORMAT_G726ADPCM: ::WORD = 0x0140; +pub const WAVE_FORMAT_DICTAPHONE_CELP68: ::WORD = 0x0141; +pub const WAVE_FORMAT_DICTAPHONE_CELP54: ::WORD = 0x0142; +pub const WAVE_FORMAT_QUALCOMM_PUREVOICE: ::WORD = 0x0150; +pub const WAVE_FORMAT_QUALCOMM_HALFRATE: ::WORD = 0x0151; +pub const WAVE_FORMAT_TUBGSM: ::WORD = 0x0155; +pub const WAVE_FORMAT_MSAUDIO1: ::WORD = 0x0160; +pub const WAVE_FORMAT_WMAUDIO2: ::WORD = 0x0161; +pub const WAVE_FORMAT_WMAUDIO3: ::WORD = 0x0162; +pub const WAVE_FORMAT_WMAUDIO_LOSSLESS: ::WORD = 0x0163; +pub const WAVE_FORMAT_WMASPDIF: ::WORD = 0x0164; +pub const WAVE_FORMAT_UNISYS_NAP_ADPCM: ::WORD = 0x0170; +pub const WAVE_FORMAT_UNISYS_NAP_ULAW: ::WORD = 0x0171; +pub const WAVE_FORMAT_UNISYS_NAP_ALAW: ::WORD = 0x0172; +pub const WAVE_FORMAT_UNISYS_NAP_16K: ::WORD = 0x0173; +pub const WAVE_FORMAT_SYCOM_ACM_SYC008: ::WORD = 0x0174; +pub const WAVE_FORMAT_SYCOM_ACM_SYC701_G726L: ::WORD = 0x0175; +pub const WAVE_FORMAT_SYCOM_ACM_SYC701_CELP54: ::WORD = 0x0176; +pub const WAVE_FORMAT_SYCOM_ACM_SYC701_CELP68: ::WORD = 0x0177; +pub const WAVE_FORMAT_KNOWLEDGE_ADVENTURE_ADPCM: ::WORD = 0x0178; +pub const WAVE_FORMAT_FRAUNHOFER_IIS_MPEG2_AAC: ::WORD = 0x0180; +pub const WAVE_FORMAT_DTS_DS: ::WORD = 0x0190; +pub const WAVE_FORMAT_CREATIVE_ADPCM: ::WORD = 0x0200; +pub const WAVE_FORMAT_CREATIVE_FASTSPEECH8: ::WORD = 0x0202; +pub const WAVE_FORMAT_CREATIVE_FASTSPEECH10: ::WORD = 0x0203; +pub const WAVE_FORMAT_UHER_ADPCM: ::WORD = 0x0210; +pub const WAVE_FORMAT_ULEAD_DV_AUDIO: ::WORD = 0x0215; +pub const WAVE_FORMAT_ULEAD_DV_AUDIO_1: ::WORD = 0x0216; +pub const WAVE_FORMAT_QUARTERDECK: ::WORD = 0x0220; +pub const WAVE_FORMAT_ILINK_VC: ::WORD = 0x0230; +pub const WAVE_FORMAT_RAW_SPORT: ::WORD = 0x0240; +pub const WAVE_FORMAT_ESST_AC3: ::WORD = 0x0241; +pub const WAVE_FORMAT_GENERIC_PASSTHRU: ::WORD = 0x0249; +pub const WAVE_FORMAT_IPI_HSX: ::WORD = 0x0250; +pub const WAVE_FORMAT_IPI_RPELP: ::WORD = 0x0251; +pub const WAVE_FORMAT_CS2: ::WORD = 0x0260; +pub const WAVE_FORMAT_SONY_SCX: ::WORD = 0x0270; +pub const WAVE_FORMAT_SONY_SCY: ::WORD = 0x0271; +pub const WAVE_FORMAT_SONY_ATRAC3: ::WORD = 0x0272; +pub const WAVE_FORMAT_SONY_SPC: ::WORD = 0x0273; +pub const WAVE_FORMAT_TELUM_AUDIO: ::WORD = 0x0280; +pub const WAVE_FORMAT_TELUM_IA_AUDIO: ::WORD = 0x0281; +pub const WAVE_FORMAT_NORCOM_VOICE_SYSTEMS_ADPCM: ::WORD = 0x0285; +pub const WAVE_FORMAT_FM_TOWNS_SND: ::WORD = 0x0300; +pub const WAVE_FORMAT_MICRONAS: ::WORD = 0x0350; +pub const WAVE_FORMAT_MICRONAS_CELP833: ::WORD = 0x0351; +pub const WAVE_FORMAT_BTV_DIGITAL: ::WORD = 0x0400; +pub const WAVE_FORMAT_INTEL_MUSIC_CODER: ::WORD = 0x0401; +pub const WAVE_FORMAT_INDEO_AUDIO: ::WORD = 0x0402; +pub const WAVE_FORMAT_QDESIGN_MUSIC: ::WORD = 0x0450; +pub const WAVE_FORMAT_ON2_VP7_AUDIO: ::WORD = 0x0500; +pub const WAVE_FORMAT_ON2_VP6_AUDIO: ::WORD = 0x0501; +pub const WAVE_FORMAT_VME_VMPCM: ::WORD = 0x0680; +pub const WAVE_FORMAT_TPC: ::WORD = 0x0681; +pub const WAVE_FORMAT_LIGHTWAVE_LOSSLESS: ::WORD = 0x08AE; +pub const WAVE_FORMAT_OLIGSM: ::WORD = 0x1000; +pub const WAVE_FORMAT_OLIADPCM: ::WORD = 0x1001; +pub const WAVE_FORMAT_OLICELP: ::WORD = 0x1002; +pub const WAVE_FORMAT_OLISBC: ::WORD = 0x1003; +pub const WAVE_FORMAT_OLIOPR: ::WORD = 0x1004; +pub const WAVE_FORMAT_LH_CODEC: ::WORD = 0x1100; +pub const WAVE_FORMAT_LH_CODEC_CELP: ::WORD = 0x1101; +pub const WAVE_FORMAT_LH_CODEC_SBC8: ::WORD = 0x1102; +pub const WAVE_FORMAT_LH_CODEC_SBC12: ::WORD = 0x1103; +pub const WAVE_FORMAT_LH_CODEC_SBC16: ::WORD = 0x1104; +pub const WAVE_FORMAT_NORRIS: ::WORD = 0x1400; +pub const WAVE_FORMAT_ISIAUDIO_2: ::WORD = 0x1401; +pub const WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS: ::WORD = 0x1500; +pub const WAVE_FORMAT_MPEG_ADTS_AAC: ::WORD = 0x1600; +pub const WAVE_FORMAT_MPEG_RAW_AAC: ::WORD = 0x1601; +pub const WAVE_FORMAT_MPEG_LOAS: ::WORD = 0x1602; +pub const WAVE_FORMAT_NOKIA_MPEG_ADTS_AAC: ::WORD = 0x1608; +pub const WAVE_FORMAT_NOKIA_MPEG_RAW_AAC: ::WORD = 0x1609; +pub const WAVE_FORMAT_VODAFONE_MPEG_ADTS_AAC: ::WORD = 0x160A; +pub const WAVE_FORMAT_VODAFONE_MPEG_RAW_AAC: ::WORD = 0x160B; +pub const WAVE_FORMAT_MPEG_HEAAC: ::WORD = 0x1610; +pub const WAVE_FORMAT_VOXWARE_RT24_SPEECH: ::WORD = 0x181C; +pub const WAVE_FORMAT_SONICFOUNDRY_LOSSLESS: ::WORD = 0x1971; +pub const WAVE_FORMAT_INNINGS_TELECOM_ADPCM: ::WORD = 0x1979; +pub const WAVE_FORMAT_LUCENT_SX8300P: ::WORD = 0x1C07; +pub const WAVE_FORMAT_LUCENT_SX5363S: ::WORD = 0x1C0C; +pub const WAVE_FORMAT_CUSEEME: ::WORD = 0x1F03; +pub const WAVE_FORMAT_NTCSOFT_ALF2CM_ACM: ::WORD = 0x1FC4; +pub const WAVE_FORMAT_DVM: ::WORD = 0x2000; +pub const WAVE_FORMAT_DTS2: ::WORD = 0x2001; +pub const WAVE_FORMAT_MAKEAVIS: ::WORD = 0x3313; +pub const WAVE_FORMAT_DIVIO_MPEG4_AAC: ::WORD = 0x4143; +pub const WAVE_FORMAT_NOKIA_ADAPTIVE_MULTIRATE: ::WORD = 0x4201; +pub const WAVE_FORMAT_DIVIO_G726: ::WORD = 0x4243; +pub const WAVE_FORMAT_LEAD_SPEECH: ::WORD = 0x434C; +pub const WAVE_FORMAT_LEAD_VORBIS: ::WORD = 0x564C; +pub const WAVE_FORMAT_WAVPACK_AUDIO: ::WORD = 0x5756; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_1: ::WORD = 0x674F; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_2: ::WORD = 0x6750; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_3: ::WORD = 0x6751; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_1_PLUS: ::WORD = 0x676F; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_2_PLUS: ::WORD = 0x6770; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_3_PLUS: ::WORD = 0x6771; +pub const WAVE_FORMAT_3COM_NBX: ::WORD = 0x7000; +pub const WAVE_FORMAT_FAAD_AAC: ::WORD = 0x706D; +pub const WAVE_FORMAT_AMR_NB: ::WORD = 0x7361; +pub const WAVE_FORMAT_AMR_WB: ::WORD = 0x7362; +pub const WAVE_FORMAT_AMR_WP: ::WORD = 0x7363; +pub const WAVE_FORMAT_GSM_AMR_CBR: ::WORD = 0x7A21; +pub const WAVE_FORMAT_GSM_AMR_VBR_SID: ::WORD = 0x7A22; +pub const WAVE_FORMAT_COMVERSE_INFOSYS_G723_1: ::WORD = 0xA100; +pub const WAVE_FORMAT_COMVERSE_INFOSYS_AVQSBC: ::WORD = 0xA101; +pub const WAVE_FORMAT_COMVERSE_INFOSYS_SBC: ::WORD = 0xA102; +pub const WAVE_FORMAT_SYMBOL_G729_A: ::WORD = 0xA103; +pub const WAVE_FORMAT_VOICEAGE_AMR_WB: ::WORD = 0xA104; +pub const WAVE_FORMAT_INGENIENT_G726: ::WORD = 0xA105; +pub const WAVE_FORMAT_MPEG4_AAC: ::WORD = 0xA106; +pub const WAVE_FORMAT_ENCORE_G726: ::WORD = 0xA107; +pub const WAVE_FORMAT_ZOLL_ASAO: ::WORD = 0xA108; +pub const WAVE_FORMAT_SPEEX_VOICE: ::WORD = 0xA109; +pub const WAVE_FORMAT_VIANIX_MASC: ::WORD = 0xA10A; +pub const WAVE_FORMAT_WM9_SPECTRUM_ANALYZER: ::WORD = 0xA10B; +pub const WAVE_FORMAT_WMF_SPECTRUM_ANAYZER: ::WORD = 0xA10C; +pub const WAVE_FORMAT_GSM_610: ::WORD = 0xA10D; +pub const WAVE_FORMAT_GSM_620: ::WORD = 0xA10E; +pub const WAVE_FORMAT_GSM_660: ::WORD = 0xA10F; +pub const WAVE_FORMAT_GSM_690: ::WORD = 0xA110; +pub const WAVE_FORMAT_GSM_ADAPTIVE_MULTIRATE_WB: ::WORD = 0xA111; +pub const WAVE_FORMAT_POLYCOM_G722: ::WORD = 0xA112; +pub const WAVE_FORMAT_POLYCOM_G728: ::WORD = 0xA113; +pub const WAVE_FORMAT_POLYCOM_G729_A: ::WORD = 0xA114; +pub const WAVE_FORMAT_POLYCOM_SIREN: ::WORD = 0xA115; +pub const WAVE_FORMAT_GLOBAL_IP_ILBC: ::WORD = 0xA116; +pub const WAVE_FORMAT_RADIOTIME_TIME_SHIFT_RADIO: ::WORD = 0xA117; +pub const WAVE_FORMAT_NICE_ACA: ::WORD = 0xA118; +pub const WAVE_FORMAT_NICE_ADPCM: ::WORD = 0xA119; +pub const WAVE_FORMAT_VOCORD_G721: ::WORD = 0xA11A; +pub const WAVE_FORMAT_VOCORD_G726: ::WORD = 0xA11B; +pub const WAVE_FORMAT_VOCORD_G722_1: ::WORD = 0xA11C; +pub const WAVE_FORMAT_VOCORD_G728: ::WORD = 0xA11D; +pub const WAVE_FORMAT_VOCORD_G729: ::WORD = 0xA11E; +pub const WAVE_FORMAT_VOCORD_G729_A: ::WORD = 0xA11F; +pub const WAVE_FORMAT_VOCORD_G723_1: ::WORD = 0xA120; +pub const WAVE_FORMAT_VOCORD_LBC: ::WORD = 0xA121; +pub const WAVE_FORMAT_NICE_G728: ::WORD = 0xA122; +pub const WAVE_FORMAT_FRACE_TELECOM_G729: ::WORD = 0xA123; +pub const WAVE_FORMAT_CODIAN: ::WORD = 0xA124; +pub const WAVE_FORMAT_FLAC: ::WORD = 0xF1AC; +pub const WAVE_FORMAT_EXTENSIBLE: ::WORD = 0xFFFE; +pub const WAVE_FORMAT_DEVELOPMENT: ::WORD = 0xFFFF; +//2557 +pub const SPEAKER_FRONT_LEFT: ::DWORD = 0x1; +pub const SPEAKER_FRONT_RIGHT: ::DWORD = 0x2; +pub const SPEAKER_FRONT_CENTER: ::DWORD = 0x4; +pub const SPEAKER_LOW_FREQUENCY: ::DWORD = 0x8; +pub const SPEAKER_BACK_LEFT: ::DWORD = 0x10; +pub const SPEAKER_BACK_RIGHT: ::DWORD = 0x20; +pub const SPEAKER_FRONT_LEFT_OF_CENTER: ::DWORD = 0x40; +pub const SPEAKER_FRONT_RIGHT_OF_CENTER: ::DWORD = 0x80; +pub const SPEAKER_BACK_CENTER: ::DWORD = 0x100; +pub const SPEAKER_SIDE_LEFT: ::DWORD = 0x200; +pub const SPEAKER_SIDE_RIGHT: ::DWORD = 0x400; +pub const SPEAKER_TOP_CENTER: ::DWORD = 0x800; +pub const SPEAKER_TOP_FRONT_LEFT: ::DWORD = 0x1000; +pub const SPEAKER_TOP_FRONT_CENTER: ::DWORD = 0x2000; +pub const SPEAKER_TOP_FRONT_RIGHT: ::DWORD = 0x4000; +pub const SPEAKER_TOP_BACK_LEFT: ::DWORD = 0x8000; +pub const SPEAKER_TOP_BACK_CENTER: ::DWORD = 0x10000; +pub const SPEAKER_TOP_BACK_RIGHT: ::DWORD = 0x20000; +pub const SPEAKER_RESERVED: ::DWORD = 0x7FFC0000; +pub const SPEAKER_ALL: ::DWORD = 0x80000000; +STRUCT!{#[repr(packed)] struct WAVEFORMATEX { + wFormatTag: ::WORD, + nChannels: ::WORD, + nSamplesPerSec: ::DWORD, + nAvgBytesPerSec: ::DWORD, + nBlockAlign: ::WORD, + wBitsPerSample: ::WORD, + cbSize: ::WORD, +}} +STRUCT!{#[repr(packed)] struct WAVEFORMATEXTENSIBLE { + Format: ::WAVEFORMATEX, + Samples: ::WORD, + dwChannelMask: ::DWORD, + SubFormat: ::GUID, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/mmsystem.rs b/bash-5.1/vendor/winapi-0.2.8/src/mmsystem.rs new file mode 100644 index 0000000..c579eda --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/mmsystem.rs @@ -0,0 +1,259 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! MM procedure declarations, constant definitions and macros +//109 (Win 7 SDK) +pub type MMVERSION = ::UINT; +pub type MMRESULT = ::UINT; +STRUCT!{struct MMTIME { + wType: ::UINT, + u: MMTIME_u, +}} +pub type PMMTIME = *mut MMTIME; +pub type NPMMTIME = *mut MMTIME; +pub type LPMMTIME = *mut MMTIME; +STRUCT!{struct MMTIME_u { + data: [u8; 8], +}} +UNION!(MMTIME_u, data, ms, ms_mut, ::DWORD); +UNION!(MMTIME_u, data, sample, sample_mut, ::DWORD); +UNION!(MMTIME_u, data, cb, cb_mut, ::DWORD); +UNION!(MMTIME_u, data, ticks, ticks_mut, ::DWORD); +UNION!(MMTIME_u, data, smpte, smpte_mut, MMTIME_smpte); +UNION!(MMTIME_u, data, midi, midi_mut, MMTIME_midi); +STRUCT!{struct MMTIME_smpte { + hour: ::BYTE, + min: ::BYTE, + sec: ::BYTE, + frame: ::BYTE, + fps: ::BYTE, + dummy: ::BYTE, + pad: [::BYTE; 2], +}} +STRUCT!{struct MMTIME_midi { + songptrpos: ::DWORD, +}} +pub const TIME_MS: ::UINT = 0x0001; +pub const TIME_SAMPLES: ::UINT = 0x0002; +pub const TIME_BYTES: ::UINT = 0x0004; +pub const TIME_SMPTE: ::UINT = 0x0008; +pub const TIME_MIDI: ::UINT = 0x0010; +pub const TIME_TICKS: ::UINT = 0x0020; +pub const MM_JOY1MOVE: ::UINT = 0x3A0; +pub const MM_JOY2MOVE: ::UINT = 0x3A1; +pub const MM_JOY1ZMOVE: ::UINT = 0x3A2; +pub const MM_JOY2ZMOVE: ::UINT = 0x3A3; +pub const MM_JOY1BUTTONDOWN: ::UINT = 0x3B5; +pub const MM_JOY2BUTTONDOWN: ::UINT = 0x3B6; +pub const MM_JOY1BUTTONUP: ::UINT = 0x3B7; +pub const MM_JOY2BUTTONUP: ::UINT = 0x3B8; +pub const MM_MCINOTIFY: ::UINT = 0x3B9; +pub const MM_WOM_OPEN: ::UINT = 0x3BB; +pub const MM_WOM_CLOSE: ::UINT = 0x3BC; +pub const MM_WOM_DONE: ::UINT = 0x3BD; +pub const MM_WIM_OPEN: ::UINT = 0x3BE; +pub const MM_WIM_CLOSE: ::UINT = 0x3BF; +pub const MM_WIM_DATA: ::UINT = 0x3C0; +pub const MM_MIM_OPEN: ::UINT = 0x3C1; +pub const MM_MIM_CLOSE: ::UINT = 0x3C2; +pub const MM_MIM_DATA: ::UINT = 0x3C3; +pub const MM_MIM_LONGDATA: ::UINT = 0x3C4; +pub const MM_MIM_ERROR: ::UINT = 0x3C5; +pub const MM_MIM_LONGERROR: ::UINT = 0x3C6; +pub const MM_MOM_OPEN: ::UINT = 0x3C7; +pub const MM_MOM_CLOSE: ::UINT = 0x3C8; +pub const MM_MOM_DONE: ::UINT = 0x3C9; +pub const MMSYSERR_BASE: MMRESULT = 0; +pub const WAVERR_BASE: MMRESULT = 32; +pub const MIDIERR_BASE: MMRESULT = 64; +pub const TIMERR_BASE: MMRESULT = 96; +pub const JOYERR_BASE: MMRESULT = 160; +pub const MCIERR_BASE: MMRESULT = 256; +pub const MIXERR_BASE: MMRESULT = 1024; +pub const MMSYSERR_NOERROR: MMRESULT = 0; +pub const MMSYSERR_ERROR: MMRESULT = MMSYSERR_BASE + 1; +pub const MMSYSERR_BADDEVICEID: MMRESULT = MMSYSERR_BASE + 2; +pub const MMSYSERR_NOTENABLED: MMRESULT = MMSYSERR_BASE + 3; +pub const MMSYSERR_ALLOCATED: MMRESULT = MMSYSERR_BASE + 4; +pub const MMSYSERR_INVALHANDLE: MMRESULT = MMSYSERR_BASE + 5; +pub const MMSYSERR_NODRIVER: MMRESULT = MMSYSERR_BASE + 6; +pub const MMSYSERR_NOMEM: MMRESULT = MMSYSERR_BASE + 7; +pub const MMSYSERR_NOTSUPPORTED: MMRESULT = MMSYSERR_BASE + 8; +pub const MMSYSERR_BADERRNUM: MMRESULT = MMSYSERR_BASE + 9; +pub const MMSYSERR_INVALFLAG: MMRESULT = MMSYSERR_BASE + 10; +pub const MMSYSERR_INVALPARAM: MMRESULT = MMSYSERR_BASE + 11; +pub const MMSYSERR_HANDLEBUSY: MMRESULT = MMSYSERR_BASE + 12; +pub const MMSYSERR_INVALIDALIAS: MMRESULT = MMSYSERR_BASE + 13; +pub const MMSYSERR_BADDB: MMRESULT = MMSYSERR_BASE + 14; +pub const MMSYSERR_KEYNOTFOUND: MMRESULT = MMSYSERR_BASE + 15; +pub const MMSYSERR_READERROR: MMRESULT = MMSYSERR_BASE + 16; +pub const MMSYSERR_WRITEERROR: MMRESULT = MMSYSERR_BASE + 17; +pub const MMSYSERR_DELETEERROR: MMRESULT = MMSYSERR_BASE + 18; +pub const MMSYSERR_VALNOTFOUND: MMRESULT = MMSYSERR_BASE + 19; +pub const MMSYSERR_NODRIVERCB: MMRESULT = MMSYSERR_BASE + 20; +pub const MMSYSERR_MOREDATA: MMRESULT = MMSYSERR_BASE + 21; +pub const MMSYSERR_LASTERROR: MMRESULT = MMSYSERR_BASE + 21; +pub const MIDIERR_UNPREPARED: MMRESULT = MIDIERR_BASE + 0; +pub const MIDIERR_STILLPLAYING: MMRESULT = MIDIERR_BASE + 1; +pub const MIDIERR_NOMAP: MMRESULT = MIDIERR_BASE + 2; +pub const MIDIERR_NOTREADY: MMRESULT = MIDIERR_BASE + 3; +pub const MIDIERR_NODEVICE: MMRESULT = MIDIERR_BASE + 4; +pub const MIDIERR_INVALIDSETUP: MMRESULT = MIDIERR_BASE + 5; +pub const MIDIERR_BADOPENMODE: MMRESULT = MIDIERR_BASE + 6; +pub const MIDIERR_DONT_CONTINUE: MMRESULT = MIDIERR_BASE + 7; +pub const MIDIERR_LASTERROR: MMRESULT = MIDIERR_BASE + 7; +pub const CALLBACK_TYPEMASK: ::DWORD = 0x00070000; +pub const CALLBACK_NULL: ::DWORD = 0x00000000; +pub const CALLBACK_WINDOW: ::DWORD = 0x00010000; +pub const CALLBACK_TASK: ::DWORD = 0x00020000; +pub const CALLBACK_FUNCTION: ::DWORD = 0x00030000; +pub const CALLBACK_THREAD: ::DWORD = CALLBACK_TASK; +pub const CALLBACK_EVENT: ::DWORD = 0x00050000; +//497 (Win 7 SDK) +pub const WAVERR_BADFORMAT: MMRESULT = WAVERR_BASE + 0; +pub const WAVERR_STILLPLAYING: MMRESULT = WAVERR_BASE + 1; +pub const WAVERR_UNPREPARED: MMRESULT = WAVERR_BASE + 2; +pub const WAVERR_SYNC: MMRESULT = WAVERR_BASE + 3; +pub const WAVERR_LASTERROR: MMRESULT = WAVERR_BASE + 3; +DECLARE_HANDLE!(HWAVEIN, HWAVEIN__); +DECLARE_HANDLE!(HWAVEOUT, HWAVEOUT__); +pub type LPHWAVEIN = *mut HWAVEIN; +pub type LPHWAVEOUT = *mut HWAVEOUT; +pub const WOM_OPEN: ::UINT = MM_WOM_OPEN; +pub const WOM_CLOSE: ::UINT = MM_WOM_CLOSE; +pub const WOM_DONE: ::UINT = MM_WOM_DONE; +pub const WIM_OPEN: ::UINT = MM_WIM_OPEN; +pub const WIM_CLOSE: ::UINT = MM_WIM_CLOSE; +pub const WIM_DATA: ::UINT = MM_WIM_DATA; +pub const WAVE_MAPPER: ::UINT = 0xFFFFFFFF; +pub const WAVE_FORMAT_QUERY: ::DWORD = 0x0001; +pub const WAVE_ALLOWSYNC: ::DWORD = 0x0002; +pub const WAVE_MAPPED: ::DWORD = 0x0004; +pub const WAVE_FORMAT_DIRECT: ::DWORD = 0x0008; +pub const WAVE_FORMAT_DIRECT_QUERY: ::DWORD = WAVE_FORMAT_QUERY | WAVE_FORMAT_DIRECT; +pub const WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE: ::DWORD = 0x0010; +STRUCT!{struct WAVEHDR { + lpData: ::LPSTR, + dwBufferLength: ::DWORD, + dwBytesRecorded: ::DWORD, + dwUser: ::DWORD_PTR, + dwFlags: ::DWORD, + dwLoops: ::DWORD, + lpNext: *mut WAVEHDR, + reserved: ::DWORD_PTR, +}} +pub type PWAVEHDR = *mut WAVEHDR; +pub type NPWAVEHDR = *mut WAVEHDR; +pub type LPWAVEHDR = *mut WAVEHDR; +STRUCT!{struct WAVEOUTCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: MMVERSION, + szPname: [::WCHAR; 32], + dwFormats: ::DWORD, + wChannels: ::WORD, + wReserved1: ::WORD, + dwSupport: ::DWORD, +}} +pub type PWAVEOUTCAPSW = *mut WAVEOUTCAPSW; +pub type NPWAVEOUTCAPSW = *mut WAVEOUTCAPSW; +pub type LPWAVEOUTCAPSW = *mut WAVEOUTCAPSW; +STRUCT!{struct WAVEINCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: MMVERSION, + szPname: [::WCHAR; 32], + dwFormats: ::DWORD, + wChannels: ::WORD, + wReserved1: ::WORD, +}} +pub type PWAVEINCAPSW = *mut WAVEINCAPSW; +pub type NPWAVEINCAPSW = *mut WAVEINCAPSW; +pub type LPWAVEINCAPSW = *mut WAVEINCAPSW; +pub const WAVE_INVALIDFORMAT: ::DWORD = 0x00000000; +pub const WAVE_FORMAT_1M08: ::DWORD = 0x00000001; +pub const WAVE_FORMAT_1S08: ::DWORD = 0x00000002; +pub const WAVE_FORMAT_1M16: ::DWORD = 0x00000004; +pub const WAVE_FORMAT_1S16: ::DWORD = 0x00000008; +pub const WAVE_FORMAT_2M08: ::DWORD = 0x00000010; +pub const WAVE_FORMAT_2S08: ::DWORD = 0x00000020; +pub const WAVE_FORMAT_2M16: ::DWORD = 0x00000040; +pub const WAVE_FORMAT_2S16: ::DWORD = 0x00000080; +pub const WAVE_FORMAT_4M08: ::DWORD = 0x00000100; +pub const WAVE_FORMAT_4S08: ::DWORD = 0x00000200; +pub const WAVE_FORMAT_4M16: ::DWORD = 0x00000400; +pub const WAVE_FORMAT_4S16: ::DWORD = 0x00000800; +pub const WAVE_FORMAT_44M08: ::DWORD = 0x00000100; +pub const WAVE_FORMAT_44S08: ::DWORD = 0x00000200; +pub const WAVE_FORMAT_44M16: ::DWORD = 0x00000400; +pub const WAVE_FORMAT_44S16: ::DWORD = 0x00000800; +pub const WAVE_FORMAT_48M08: ::DWORD = 0x00001000; +pub const WAVE_FORMAT_48S08: ::DWORD = 0x00002000; +pub const WAVE_FORMAT_48M16: ::DWORD = 0x00004000; +pub const WAVE_FORMAT_48S16: ::DWORD = 0x00008000; +pub const WAVE_FORMAT_96M08: ::DWORD = 0x00010000; +pub const WAVE_FORMAT_96S08: ::DWORD = 0x00020000; +pub const WAVE_FORMAT_96M16: ::DWORD = 0x00040000; +pub const WAVE_FORMAT_96S16: ::DWORD = 0x00080000; +//782 (Win 7 SDK) +pub type PWAVEFORMATEX = *mut ::WAVEFORMATEX; +pub type NPWAVEFORMATEX = *mut ::WAVEFORMATEX; +pub type LPWAVEFORMATEX = *mut ::WAVEFORMATEX; +pub type LPCWAVEFORMATEX = *const ::WAVEFORMATEX; +//2170 (Win 7 SDK) +pub const TIMERR_NOERROR: ::MMRESULT = 0; +pub const TIMERR_NOCANDO: ::MMRESULT = TIMERR_BASE + 1; +pub const TIMERR_STRUCT: ::MMRESULT = TIMERR_BASE + 33; +//2198 (Win 7 SDK) +STRUCT!{struct TIMECAPS { + wPeriodMin: ::UINT, + wPeriodMax: ::UINT, +}} +pub type PTIMECAPS = *mut TIMECAPS; +pub type NPTIMECAPS = *mut TIMECAPS; +pub type LPTIMECAPS = *mut TIMECAPS; +STRUCT!{struct MIDIHDR { + lpData: ::LPSTR, + dwBufferLength: ::DWORD, + dwBytesRecorded: ::DWORD, + dwUser: ::DWORD_PTR, + dwFlags: ::DWORD, + lpNext: *mut MIDIHDR, + reserved: ::DWORD_PTR, + dwOffset: ::DWORD, + dwReserved: [::DWORD_PTR; 4], +}} +pub type PMIDIHDR = *mut MIDIHDR; +pub type NPMIDIHDR = *mut MIDIHDR; +pub type LPMIDIHDR = *mut MIDIHDR; +STRUCT!{struct MIDIINCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: MMVERSION, + szPname: [::WCHAR; 32], + dwSupport: ::DWORD, +}} +pub type PMIDIINCAPSW = *mut MIDIINCAPSW; +pub type NPMIDIINCAPSW = *mut MIDIINCAPSW; +pub type LPMIDIINCAPSW = *mut MIDIINCAPSW; +STRUCT!{struct MIDIOUTCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: ::MMVERSION, + szPname: [::WCHAR; 32], + wTechnology: ::WORD, + wVoices: ::WORD, + wNotes: ::WORD, + wChannelMask: ::WORD, + dwSupport: ::DWORD, +}} +pub type PMIDIOUTCAPSW = *mut MIDIOUTCAPSW; +pub type NPMIDIOUTCAPSW = *mut MIDIOUTCAPSW; +pub type LPMIDIOUTCAPSW = *mut MIDIOUTCAPSW; +DECLARE_HANDLE!(HMIDIIN, HMIDIIN__); +DECLARE_HANDLE!(HMIDIOUT, HMIDIOUT__); +pub type LPHMIDIIN = *mut HMIDIIN; +pub type LPHMIDIOUT = *mut HMIDIOUT; +DECLARE_HANDLE!(HMIDISTRM, HMIDISTRM__); +DECLARE_HANDLE!(HMIDI, HMIDI__); +pub type LPHMIDISTRM = *mut HMIDISTRM; +pub type LPHMIDI = *mut HMIDI; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/mscat.rs b/bash-5.1/vendor/winapi-0.2.8/src/mscat.rs new file mode 100644 index 0000000..cc159de --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/mscat.rs @@ -0,0 +1,28 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Microsoft Internet Security Catalog API Prototypes and Definitions +STRUCT!{struct CRYPTCATSTORE { + cbStruct: ::DWORD, + dwPublicVersion: ::DWORD, + pwszP7File: ::LPWSTR, + hProv: ::HCRYPTPROV, + dwEncodingType: ::DWORD, + fdwStoreFlags: ::DWORD, + hReserved: ::HANDLE, + hAttrs: ::HANDLE, + hCryptMsg: ::HCRYPTMSG, + hSorted: ::HANDLE, +}} +STRUCT!{struct CRYPTCATMEMBER { + cbStruct: ::DWORD, + pwszReferenceTag: ::LPWSTR, + pwszFileName: ::LPWSTR, + gSubjectType: ::GUID, + fdwMemberFlags: ::DWORD, + pIndirectData: *mut ::SIP_INDIRECT_DATA, + dwCertVersion: ::DWORD, + dwReserved: ::DWORD, + hReserved: ::HANDLE, + sEncodedIndirectData: ::CRYPT_ATTR_BLOB, + sEncodedMemberInfo: ::CRYPT_ATTR_BLOB, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/mssip.rs b/bash-5.1/vendor/winapi-0.2.8/src/mssip.rs new file mode 100644 index 0000000..5eeaa7e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/mssip.rs @@ -0,0 +1,103 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Microsoft SIP Provider Prototypes and Definitions +STRUCT!{struct SIP_SUBJECTINFO { + cbSize: ::DWORD, + pgSubjectType: *mut ::GUID, + hFile: ::HANDLE, + pwsFileName: ::LPCWSTR, + pwsDisplayName: ::LPCWSTR, + dwReserved1: ::DWORD, + dwIntVersion: ::DWORD, + hProv: ::HCRYPTPROV, + DigestAlgorithm: ::CRYPT_ALGORITHM_IDENTIFIER, + dwFlags: ::DWORD, + dwEncodingType: ::DWORD, + dwReserved2: ::DWORD, + fdwCAPISettings: ::DWORD, + fdwSecuritySettings: ::DWORD, + dwIndex: ::DWORD, + dwUnionChoice: ::DWORD, + psFlat: *mut MS_ADDINFO_FLAT, + pClientData: ::LPVOID, +}} +UNION!(SIP_SUBJECTINFO, psFlat, psCatMember, psCatMember_mut, *mut MS_ADDINFO_CATALOGMEMBER); +UNION!(SIP_SUBJECTINFO, psFlat, psBlob, psBlob_mut, *mut MS_ADDINFO_BLOB); +pub type LPSIP_SUBJECTINFO = *mut SIP_SUBJECTINFO; +STRUCT!{struct MS_ADDINFO_FLAT { + cbStruct: ::DWORD, + pIndirectData: *mut SIP_INDIRECT_DATA, +}} +pub type PMS_ADDINFO_FLAT = *mut MS_ADDINFO_FLAT; +STRUCT!{struct MS_ADDINFO_CATALOGMEMBER { + cbStruct: ::DWORD, + pStore: *mut ::CRYPTCATSTORE, + pMember: *mut ::CRYPTCATMEMBER, +}} +pub type PMS_ADDINFO_CATALOGMEMBER = *mut MS_ADDINFO_CATALOGMEMBER; +STRUCT!{struct MS_ADDINFO_BLOB { + cbStruct: ::DWORD, + cbMemObject: ::DWORD, + pbMemObject: *mut ::BYTE, + cbMemSignedMsg: ::DWORD, + pbMemSignedMsg: *mut ::BYTE, +}} +pub type PMS_ADDINFO_BLOB = *mut MS_ADDINFO_BLOB; +STRUCT!{struct SIP_INDIRECT_DATA { + Data: ::CRYPT_ATTRIBUTE_TYPE_VALUE, + DigestAlgorithm: ::CRYPT_ALGORITHM_IDENTIFIER, + Digest: ::CRYPT_HASH_BLOB, +}} +pub type PSIP_INDIRECT_DATA = *mut SIP_INDIRECT_DATA; +STRUCT!{struct SIP_ADD_NEWPROVIDER { + cbStruct: ::DWORD, + pgSubject: *mut ::GUID, + pwszDLLFileName: *mut ::WCHAR, + pwszMagicNumber: *mut ::WCHAR, + pwszIsFunctionName: *mut ::WCHAR, + pwszGetFuncName: *mut ::WCHAR, + pwszPutFuncName: *mut ::WCHAR, + pwszCreateFuncName: *mut ::WCHAR, + pwszVerifyFuncName: *mut ::WCHAR, + pwszRemoveFuncName: *mut ::WCHAR, + pwszIsFunctionNameFmt2: *mut ::WCHAR, + pwszGetCapFuncName: ::PWSTR, +}} +pub type PSIP_ADD_NEWPROVIDER = *mut SIP_ADD_NEWPROVIDER; +STRUCT!{struct SIP_CAP_SET_V3 { + cbSize: ::DWORD, + dwVersion: ::DWORD, + isMultiSign: ::BOOL, + dwFlags: ::DWORD, +}} +UNION!(SIP_CAP_SET_V3, dwFlags, dwReserved, dwReserved_mut, ::DWORD); +pub type PSIP_CAP_SET_V3 = *mut SIP_CAP_SET_V3; +pub type SIP_CAP_SET = PSIP_CAP_SET_V3; +pub type pCryptSIPGetSignedDataMsg = Option<unsafe extern "system" fn( + pSubjectInfo: *mut SIP_SUBJECTINFO, pdwEncodingType: *mut ::DWORD, dwIndex: ::DWORD, + pcbSignedDataMsg: *mut ::DWORD, pbSignedDataMsg: *mut ::BYTE, +) -> ::BOOL>; +pub type pCryptSIPPutSignedDataMsg = Option<unsafe extern "system" fn( + pSubjectInfo: *mut SIP_SUBJECTINFO, dwEncodingType: ::DWORD, pdwIndex: *mut ::DWORD, + cbSignedDataMsg: ::DWORD, pbSignedDataMsg: *mut ::BYTE, +) -> ::BOOL>; +pub type pCryptSIPCreateIndirectData = Option<unsafe extern "system" fn( + pSubjectInfo: *mut SIP_SUBJECTINFO, pcbIndirectData: *mut ::DWORD, + pIndirectData: *mut SIP_INDIRECT_DATA, +) -> ::BOOL>; +pub type pCryptSIPVerifyIndirectData = Option<unsafe extern "system" fn( + pSubjectInfo: *mut SIP_SUBJECTINFO, pIndirectData: *mut SIP_INDIRECT_DATA, +) -> ::BOOL>; +pub type pCryptSIPRemoveSignedDataMsg = Option<unsafe extern "system" fn( + pSubjectInfo: *mut SIP_SUBJECTINFO, dwIndex: ::DWORD, +) -> ::BOOL>; +STRUCT!{nodebug struct SIP_DISPATCH_INFO { + cbSize: ::DWORD, + hSIP: ::HANDLE, + pfGet: pCryptSIPGetSignedDataMsg, + pfPut: pCryptSIPPutSignedDataMsg, + pfCreate: pCryptSIPCreateIndirectData, + pfVerify: pCryptSIPVerifyIndirectData, + pfRemove: pCryptSIPRemoveSignedDataMsg, +}} +pub type LPSIP_DISPATCH_INFO = *mut SIP_DISPATCH_INFO; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/nb30.rs b/bash-5.1/vendor/winapi-0.2.8/src/nb30.rs new file mode 100644 index 0000000..26e9dea --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/nb30.rs @@ -0,0 +1,200 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +// This module contains the definitions for portable NetBIOS 3.0 support. +pub const NCBNAMSZ: usize = 16; +pub const MAX_LANA: usize = 254; +pub type PFPOST = Option<unsafe extern "system" fn(*mut NCB)>; +#[cfg(target_arch="x86_64")] +STRUCT!{nodebug struct NCB { + ncb_command: ::UCHAR, + ncb_retcode: ::UCHAR, + ncb_lsn: ::UCHAR, + ncb_num: ::UCHAR, + ncb_buffer: ::PUCHAR, + ncb_length: ::WORD, + ncb_callname: [::UCHAR; NCBNAMSZ], + ncb_name: [::UCHAR; NCBNAMSZ], + ncb_rto: ::UCHAR, + ncb_sto: ::UCHAR, + ncb_post: PFPOST, + ncb_lana_num: ::UCHAR, + ncb_cmd_cplt: ::UCHAR, + ncb_reserve: [::UCHAR; 18], + ncb_event: ::HANDLE, +}} +#[cfg(target_arch="x86")] +STRUCT!{nodebug struct NCB { + ncb_command: ::UCHAR, + ncb_retcode: ::UCHAR, + ncb_lsn: ::UCHAR, + ncb_num: ::UCHAR, + ncb_buffer: ::PUCHAR, + ncb_length: ::WORD, + ncb_callname: [::UCHAR; NCBNAMSZ], + ncb_name: [::UCHAR; NCBNAMSZ], + ncb_rto: ::UCHAR, + ncb_sto: ::UCHAR, + ncb_post: PFPOST, + ncb_lana_num: ::UCHAR, + ncb_cmd_cplt: ::UCHAR, + ncb_reserve: [::UCHAR; 10], + ncb_event: ::HANDLE, +}} +pub type PNCB = *mut NCB; +STRUCT!{struct ADAPTER_STATUS { + adapter_address: [::UCHAR; 6], + rev_major: ::UCHAR, + reserved0: ::UCHAR, + adapter_type: ::UCHAR, + rev_minor: ::UCHAR, + duration: ::WORD, + frmr_recv: ::WORD, + frmr_xmit: ::WORD, + iframe_recv_err: ::WORD, + xmit_aborts: ::WORD, + xmit_success: ::DWORD, + recv_success: ::DWORD, + iframe_xmit_err: ::WORD, + recv_buff_unavail: ::WORD, + t1_timeouts: ::WORD, + ti_timeouts: ::WORD, + reserved1: ::DWORD, + free_ncbs: ::WORD, + max_cfg_ncbs: ::WORD, + max_ncbs: ::WORD, + xmit_buf_unavail: ::WORD, + max_dgram_size: ::WORD, + pending_sess: ::WORD, + max_cfg_sess: ::WORD, + max_sess: ::WORD, + max_sess_pkt_size: ::WORD, + name_count: ::WORD, +}} +pub type PADAPTER_STATUS = *mut ADAPTER_STATUS; +STRUCT!{struct NAME_BUFFER { + name: [::UCHAR; NCBNAMSZ], + name_num: ::UCHAR, + name_flags: ::UCHAR, +}} +pub type PNAME_BUFFER = *mut NAME_BUFFER; +pub const NAME_FLAGS_MASK: ::UCHAR = 0x87; +pub const GROUP_NAME: ::UCHAR = 0x80; +pub const UNIQUE_NAME: ::UCHAR = 0x00; +pub const REGISTERING: ::UCHAR = 0x00; +pub const REGISTERED: ::UCHAR = 0x04; +pub const DEREGISTERED: ::UCHAR = 0x05; +pub const DUPLICATE: ::UCHAR = 0x06; +pub const DUPLICATE_DEREG: ::UCHAR = 0x07; +STRUCT!{struct SESSION_HEADER { + sess_name: ::UCHAR, + num_sess: ::UCHAR, + rcv_dg_outstanding: ::UCHAR, + rcv_any_outstanding: ::UCHAR, +}} +pub type PSESSION_HEADER = *mut SESSION_HEADER; +STRUCT!{struct SESSION_BUFFER { + lsn: ::UCHAR, + state: ::UCHAR, + local_name: [::UCHAR; NCBNAMSZ], + remote_name: [::UCHAR; NCBNAMSZ], + rcvs_outstanding: ::UCHAR, + sends_outstanding: ::UCHAR, +}} +pub type PSESSION_BUFFER = *mut SESSION_BUFFER; +pub const LISTEN_OUTSTANDING: ::UCHAR = 0x01; +pub const CALL_PENDING: ::UCHAR = 0x02; +pub const SESSION_ESTABLISHED: ::UCHAR = 0x03; +pub const HANGUP_PENDING: ::UCHAR = 0x04; +pub const HANGUP_COMPLETE: ::UCHAR = 0x05; +pub const SESSION_ABORTED: ::UCHAR = 0x06; +STRUCT!{nodebug struct LANA_ENUM { + length: ::UCHAR, + lana: [::UCHAR; MAX_LANA + 1], +}} +pub type PLANA_ENUM = *mut LANA_ENUM; +STRUCT!{struct FIND_NAME_HEADER { + node_count: ::WORD, + reserved: ::UCHAR, + unique_group: ::UCHAR, +}} +pub type PFIND_NAME_HEADER = *mut FIND_NAME_HEADER; +STRUCT!{struct FIND_NAME_BUFFER { + length: ::UCHAR, + access_control: ::UCHAR, + frame_control: ::UCHAR, + destination_addr: [::UCHAR; 6], + source_addr: [::UCHAR; 6], + routing_info: [::UCHAR; 18], +}} +pub type PFIND_NAME_BUFFER = *mut FIND_NAME_BUFFER; +STRUCT!{struct ACTION_HEADER { + transport_id: ::ULONG, + action_code: ::USHORT, + reserved: ::USHORT, +}} +pub type PACTION_HEADER = *mut ACTION_HEADER; +pub const NCBCALL: ::UCHAR = 0x10; +pub const NCBLISTEN: ::UCHAR = 0x11; +pub const NCBHANGUP: ::UCHAR = 0x12; +pub const NCBSEND: ::UCHAR = 0x14; +pub const NCBRECV: ::UCHAR = 0x15; +pub const NCBRECVANY: ::UCHAR = 0x16; +pub const NCBCHAINSEND: ::UCHAR = 0x17; +pub const NCBDGSEND: ::UCHAR = 0x20; +pub const NCBDGRECV: ::UCHAR = 0x21; +pub const NCBDGSENDBC: ::UCHAR = 0x22; +pub const NCBADDNAME: ::UCHAR = 0x30; +pub const NCBDELNAME: ::UCHAR = 0x31; +pub const NCBRESET: ::UCHAR = 0x32; +pub const NCBASTAT: ::UCHAR = 0x33; +pub const NCBSSTAT: ::UCHAR = 0x34; +pub const NCBCANCEL: ::UCHAR = 0x35; +pub const NCBADDGRNAME: ::UCHAR = 0x36; +pub const NCBENUM: ::UCHAR = 0x37; +pub const NCBUNLINK: ::UCHAR = 0x70; +pub const NCBSENDNA: ::UCHAR = 0x71; +pub const NCBCHAINSENDNA: ::UCHAR = 0x72; +pub const NCBLANSTALERT: ::UCHAR = 0x73; +pub const NCBACTION: ::UCHAR = 0x77; +pub const NCBFINDNAME: ::UCHAR = 0x78; +pub const NCBTRACE: ::UCHAR = 0x79; +pub const ASYNCH: ::UCHAR = 0x80; +pub const NRC_GOODRET: ::UCHAR = 0x00; +pub const NRC_BUFLEN: ::UCHAR = 0x01; +pub const NRC_ILLCMD: ::UCHAR = 0x03; +pub const NRC_CMDTMO: ::UCHAR = 0x05; +pub const NRC_INCOMP: ::UCHAR = 0x06; +pub const NRC_BADDR: ::UCHAR = 0x07; +pub const NRC_SNUMOUT: ::UCHAR = 0x08; +pub const NRC_NORES: ::UCHAR = 0x09; +pub const NRC_SCLOSED: ::UCHAR = 0x0a; +pub const NRC_CMDCAN: ::UCHAR = 0x0b; +pub const NRC_DUPNAME: ::UCHAR = 0x0d; +pub const NRC_NAMTFUL: ::UCHAR = 0x0e; +pub const NRC_ACTSES: ::UCHAR = 0x0f; +pub const NRC_LOCTFUL: ::UCHAR = 0x11; +pub const NRC_REMTFUL: ::UCHAR = 0x12; +pub const NRC_ILLNN: ::UCHAR = 0x13; +pub const NRC_NOCALL: ::UCHAR = 0x14; +pub const NRC_NOWILD: ::UCHAR = 0x15; +pub const NRC_INUSE: ::UCHAR = 0x16; +pub const NRC_NAMERR: ::UCHAR = 0x17; +pub const NRC_SABORT: ::UCHAR = 0x18; +pub const NRC_NAMCONF: ::UCHAR = 0x19; +pub const NRC_IFBUSY: ::UCHAR = 0x21; +pub const NRC_TOOMANY: ::UCHAR = 0x22; +pub const NRC_BRIDGE: ::UCHAR = 0x23; +pub const NRC_CANOCCR: ::UCHAR = 0x24; +pub const NRC_CANCEL: ::UCHAR = 0x26; +pub const NRC_DUPENV: ::UCHAR = 0x30; +pub const NRC_ENVNOTDEF: ::UCHAR = 0x34; +pub const NRC_OSRESNOTAV: ::UCHAR = 0x35; +pub const NRC_MAXAPPS: ::UCHAR = 0x36; +pub const NRC_NOSAPS: ::UCHAR = 0x37; +pub const NRC_NORESOURCES: ::UCHAR = 0x38; +pub const NRC_INVADDRESS: ::UCHAR = 0x39; +pub const NRC_INVDDID: ::UCHAR = 0x3B; +pub const NRC_LOCKFAIL: ::UCHAR = 0x3C; +pub const NRC_OPENERR: ::UCHAR = 0x3f; +pub const NRC_SYSTEM: ::UCHAR = 0x40; +pub const NRC_PENDING: ::UCHAR = 0xff; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ncrypt.rs b/bash-5.1/vendor/winapi-0.2.8/src/ncrypt.rs new file mode 100644 index 0000000..e730141 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ncrypt.rs @@ -0,0 +1,9 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Cryptographic API Prototypes and Definitions +//191 +pub type NCRYPT_HANDLE = ::ULONG_PTR; +pub type NCRYPT_PROV_HANDLE = ::ULONG_PTR; +pub type NCRYPT_KEY_HANDLE = ::ULONG_PTR; +pub type NCRYPT_HASH_HANDLE = ::ULONG_PTR; +pub type NCRYPT_SECRET_HANDLE = ::ULONG_PTR; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ntdef.rs b/bash-5.1/vendor/winapi-0.2.8/src/ntdef.rs new file mode 100644 index 0000000..2e6f14b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ntdef.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Type definitions for the basic types. +//909 +pub type NTSTATUS = ::LONG; +pub type PNTSTATUS = *mut NTSTATUS; +pub type PCNTSTATUS = *const NTSTATUS; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ntsecapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/ntsecapi.rs new file mode 100644 index 0000000..893ea9e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ntsecapi.rs @@ -0,0 +1,1589 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! This module defines the Local Security Authority APIs. +DEFINE_GUID!(Audit_System_SecurityStateChange, 0x0cce9210, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_SecuritySubsystemExtension, 0x0cce9211, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_Integrity, 0x0cce9212, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_IPSecDriverEvents, 0x0cce9213, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_Others, 0x0cce9214, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Logon, 0x0cce9215, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Logoff, 0x0cce9216, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_AccountLockout, 0x0cce9217, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_IPSecMainMode, 0x0cce9218, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_IPSecQuickMode, 0x0cce9219, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_IPSecUserMode, 0x0cce921a, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_SpecialLogon, 0x0cce921b, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Others, 0x0cce921c, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_FileSystem, 0x0cce921d, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Registry, 0x0cce921e, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Kernel, 0x0cce921f, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Sam, 0x0cce9220, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_CertificationServices, 0x0cce9221, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_ApplicationGenerated, 0x0cce9222, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Handle, 0x0cce9223, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Share, 0x0cce9224, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_FirewallPacketDrops, 0x0cce9225, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_FirewallConnection, 0x0cce9226, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Other, 0x0cce9227, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse_Sensitive, 0x0cce9228, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse_NonSensitive, 0x0cce9229, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse_Others, 0x0cce922a, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_ProcessCreation, 0x0cce922b, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_ProcessTermination, 0x0cce922c, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_DpapiActivity, 0x0cce922d, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_RpcCall, 0x0cce922e, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_AuditPolicy, 0x0cce922f, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_AuthenticationPolicy, 0x0cce9230, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_AuthorizationPolicy, 0x0cce9231, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_MpsscvRulePolicy, 0x0cce9232, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_WfpIPSecPolicy, 0x0cce9233, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_Others, 0x0cce9234, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_UserAccount, 0x0cce9235, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_ComputerAccount, 0x0cce9236, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_SecurityGroup, 0x0cce9237, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_DistributionGroup, 0x0cce9238, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_ApplicationGroup, 0x0cce9239, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_Others, 0x0cce923a, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DSAccess_DSAccess, 0x0cce923b, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DsAccess_AdAuditChanges, 0x0cce923c, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Ds_Replication, 0x0cce923d, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Ds_DetailedReplication, 0x0cce923e, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_CredentialValidation, 0x0cce923f, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_Kerberos, 0x0cce9240, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_Others, 0x0cce9241, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_KerbCredentialValidation, 0x0cce9242, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_NPS, 0x0cce9243, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_DetailedFileShare, 0x0cce9244, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_RemovableStorage, 0x0cce9245, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_CbacStaging, 0x0cce9246, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Claims, 0x0cce9247, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System, 0x69979848, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon, 0x69979849, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess, 0x6997984a, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse, 0x6997984b, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking, 0x6997984c, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange, 0x6997984d, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement, 0x6997984e, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DirectoryServiceAccess, 0x6997984f, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon, 0x69979850, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +ENUM!{enum POLICY_AUDIT_EVENT_TYPE { + AuditCategorySystem = 0, + AuditCategoryLogon, + AuditCategoryObjectAccess, + AuditCategoryPrivilegeUse, + AuditCategoryDetailedTracking, + AuditCategoryPolicyChange, + AuditCategoryAccountManagement, + AuditCategoryDirectoryServiceAccess, + AuditCategoryAccountLogon, +}} +pub type PPOLICY_AUDIT_EVENT_TYPE = *mut POLICY_AUDIT_EVENT_TYPE; +pub const POLICY_AUDIT_EVENT_UNCHANGED: POLICY_AUDIT_EVENT_OPTIONS = 0x00000000; +pub const POLICY_AUDIT_EVENT_SUCCESS: POLICY_AUDIT_EVENT_OPTIONS = 0x00000001; +pub const POLICY_AUDIT_EVENT_FAILURE: POLICY_AUDIT_EVENT_OPTIONS = 0x00000002; +pub const POLICY_AUDIT_EVENT_NONE: POLICY_AUDIT_EVENT_OPTIONS = 0x00000004; +pub const POLICY_AUDIT_EVENT_MASK: POLICY_AUDIT_EVENT_OPTIONS = POLICY_AUDIT_EVENT_SUCCESS + | POLICY_AUDIT_EVENT_FAILURE | POLICY_AUDIT_EVENT_UNCHANGED | POLICY_AUDIT_EVENT_NONE; +pub const POLICY_VIEW_LOCAL_INFORMATION: ::ACCESS_MASK = 0x00000001; +pub const POLICY_VIEW_AUDIT_INFORMATION: ::ACCESS_MASK = 0x00000002; +pub const POLICY_GET_PRIVATE_INFORMATION: ::ACCESS_MASK = 0x00000004; +pub const POLICY_TRUST_ADMIN: ::ACCESS_MASK = 0x00000008; +pub const POLICY_CREATE_ACCOUNT: ::ACCESS_MASK = 0x00000010; +pub const POLICY_CREATE_SECRET: ::ACCESS_MASK = 0x00000020; +pub const POLICY_CREATE_PRIVILEGE: ::ACCESS_MASK = 0x00000040; +pub const POLICY_SET_DEFAULT_QUOTA_LIMITS: ::ACCESS_MASK = 0x00000080; +pub const POLICY_SET_AUDIT_REQUIREMENTS: ::ACCESS_MASK = 0x00000100; +pub const POLICY_AUDIT_LOG_ADMIN: ::ACCESS_MASK = 0x00000200; +pub const POLICY_SERVER_ADMIN: ::ACCESS_MASK = 0x00000400; +pub const POLICY_LOOKUP_NAMES: ::ACCESS_MASK = 0x00000800; +pub const POLICY_NOTIFICATION: ::ACCESS_MASK = 0x00001000; +pub const POLICY_ALL_ACCESS: ::ACCESS_MASK = ::STANDARD_RIGHTS_REQUIRED + | POLICY_VIEW_LOCAL_INFORMATION | POLICY_VIEW_AUDIT_INFORMATION + | POLICY_GET_PRIVATE_INFORMATION | POLICY_TRUST_ADMIN | POLICY_CREATE_ACCOUNT + | POLICY_CREATE_SECRET | POLICY_CREATE_PRIVILEGE | POLICY_SET_DEFAULT_QUOTA_LIMITS + | POLICY_SET_AUDIT_REQUIREMENTS | POLICY_AUDIT_LOG_ADMIN | POLICY_SERVER_ADMIN + | POLICY_LOOKUP_NAMES; +pub const POLICY_READ: ::ACCESS_MASK = ::STANDARD_RIGHTS_READ | POLICY_VIEW_AUDIT_INFORMATION + | POLICY_GET_PRIVATE_INFORMATION; +pub const POLICY_WRITE: ::ACCESS_MASK = ::STANDARD_RIGHTS_WRITE | POLICY_TRUST_ADMIN + | POLICY_CREATE_ACCOUNT | POLICY_CREATE_SECRET | POLICY_CREATE_PRIVILEGE + | POLICY_SET_DEFAULT_QUOTA_LIMITS | POLICY_SET_AUDIT_REQUIREMENTS | POLICY_AUDIT_LOG_ADMIN + | POLICY_SERVER_ADMIN; +pub const POLICY_EXECUTE: ::ACCESS_MASK = ::STANDARD_RIGHTS_EXECUTE + | POLICY_VIEW_LOCAL_INFORMATION | POLICY_LOOKUP_NAMES; +STRUCT!{struct LSA_TRANSLATED_SID { + Use: ::SID_NAME_USE, + RelativeId: ::ULONG, + DomainIndex: ::LONG, +}} +pub type PLSA_TRANSLATED_SID = *mut LSA_TRANSLATED_SID; +ENUM!{enum POLICY_LSA_SERVER_ROLE { + PolicyServerRoleBackup = 2, + PolicyServerRolePrimary, +}} +pub type PPOLICY_LSA_SERVER_ROLE = *mut POLICY_LSA_SERVER_ROLE; +pub type POLICY_AUDIT_EVENT_OPTIONS = ::ULONG; +pub type PPOLICY_AUDIT_EVENT_OPTIONS = *mut ::ULONG; +ENUM!{enum POLICY_INFORMATION_CLASS { + PolicyAuditLogInformation = 1, + PolicyAuditEventsInformation, + PolicyPrimaryDomainInformation, + PolicyPdAccountInformation, + PolicyAccountDomainInformation, + PolicyLsaServerRoleInformation, + PolicyReplicaSourceInformation, + PolicyDefaultQuotaInformation, + PolicyModificationInformation, + PolicyAuditFullSetInformation, + PolicyAuditFullQueryInformation, + PolicyDnsDomainInformation, + PolicyDnsDomainInformationInt, + PolicyLocalAccountDomainInformation, + PolicyLastEntry, +}} +pub type PPOLICY_INFORMATION_CLASS = *mut POLICY_INFORMATION_CLASS; +STRUCT!{struct POLICY_AUDIT_LOG_INFO { + AuditLogPercentFull: ::ULONG, + MaximumLogSize: ::ULONG, + AuditRetentionPeriod: ::LARGE_INTEGER, + AuditLogFullShutdownInProgress: ::BOOLEAN, + TimeToShutdown: ::LARGE_INTEGER, + NextAuditRecordId: ::ULONG, +}} +pub type PPOLICY_AUDIT_LOG_INFO = *mut POLICY_AUDIT_LOG_INFO; +STRUCT!{struct POLICY_AUDIT_EVENTS_INFO { + AuditingMode: ::BOOLEAN, + EventAuditingOptions: PPOLICY_AUDIT_EVENT_OPTIONS, + MaximumAuditEventCount: ::ULONG, +}} +pub type PPOLICY_AUDIT_EVENTS_INFO = *mut POLICY_AUDIT_EVENTS_INFO; +STRUCT!{struct POLICY_AUDIT_SUBCATEGORIES_INFO { + MaximumSubCategoryCount: ::ULONG, + EventAuditingOptions: PPOLICY_AUDIT_EVENT_OPTIONS, +}} +pub type PPOLICY_AUDIT_SUBCATEGORIES_INFO = *mut POLICY_AUDIT_SUBCATEGORIES_INFO; +STRUCT!{struct POLICY_AUDIT_CATEGORIES_INFO { + MaximumSubCategoryCount: ::ULONG, + SubCategoriesInfo: PPOLICY_AUDIT_SUBCATEGORIES_INFO, +}} +pub type PPOLICY_AUDIT_CATEGORIES_INFO = *mut POLICY_AUDIT_CATEGORIES_INFO; +pub const PER_USER_POLICY_UNCHANGED: ::ULONG = 0x00; +pub const PER_USER_AUDIT_SUCCESS_INCLUDE: ::ULONG = 0x01; +pub const PER_USER_AUDIT_SUCCESS_EXCLUDE: ::ULONG = 0x02; +pub const PER_USER_AUDIT_FAILURE_INCLUDE: ::ULONG = 0x04; +pub const PER_USER_AUDIT_FAILURE_EXCLUDE: ::ULONG = 0x08; +pub const PER_USER_AUDIT_NONE: ::ULONG = 0x10; +pub const VALID_PER_USER_AUDIT_POLICY_FLAG: ::ULONG = PER_USER_AUDIT_SUCCESS_INCLUDE + | PER_USER_AUDIT_SUCCESS_EXCLUDE | PER_USER_AUDIT_FAILURE_INCLUDE + | PER_USER_AUDIT_FAILURE_EXCLUDE | PER_USER_AUDIT_NONE; +STRUCT!{struct POLICY_PRIMARY_DOMAIN_INFO { + Name: ::LSA_UNICODE_STRING, + Sid: ::PSID, +}} +pub type PPOLICY_PRIMARY_DOMAIN_INFO = *mut POLICY_PRIMARY_DOMAIN_INFO; +STRUCT!{struct POLICY_PD_ACCOUNT_INFO { + Name: ::LSA_UNICODE_STRING, +}} +pub type PPOLICY_PD_ACCOUNT_INFO = *mut POLICY_PD_ACCOUNT_INFO; +STRUCT!{struct POLICY_LSA_SERVER_ROLE_INFO { + LsaServerRole: POLICY_LSA_SERVER_ROLE, +}} +pub type PPOLICY_LSA_SERVER_ROLE_INFO = *mut POLICY_LSA_SERVER_ROLE_INFO; +STRUCT!{struct POLICY_REPLICA_SOURCE_INFO { + ReplicaSource: ::LSA_UNICODE_STRING, + ReplicaAccountName: ::LSA_UNICODE_STRING, +}} +pub type PPOLICY_REPLICA_SOURCE_INFO = *mut POLICY_REPLICA_SOURCE_INFO; +STRUCT!{struct POLICY_DEFAULT_QUOTA_INFO { + QuotaLimits: ::QUOTA_LIMITS, +}} +pub type PPOLICY_DEFAULT_QUOTA_INFO = *mut POLICY_DEFAULT_QUOTA_INFO; +STRUCT!{struct POLICY_MODIFICATION_INFO { + ModifiedId: ::LARGE_INTEGER, + DatabaseCreationTime: ::LARGE_INTEGER, +}} +pub type PPOLICY_MODIFICATION_INFO = *mut POLICY_MODIFICATION_INFO; +STRUCT!{struct POLICY_AUDIT_FULL_SET_INFO { + ShutDownOnFull: ::BOOLEAN, +}} +pub type PPOLICY_AUDIT_FULL_SET_INFO = *mut POLICY_AUDIT_FULL_SET_INFO; +STRUCT!{struct POLICY_AUDIT_FULL_QUERY_INFO { + ShutDownOnFull: ::BOOLEAN, + LogIsFull: ::BOOLEAN, +}} +pub type PPOLICY_AUDIT_FULL_QUERY_INFO = *mut POLICY_AUDIT_FULL_QUERY_INFO; +ENUM!{enum POLICY_DOMAIN_INFORMATION_CLASS { + PolicyDomainEfsInformation = 2, + PolicyDomainKerberosTicketInformation, +}} +pub type PPOLICY_DOMAIN_INFORMATION_CLASS = *mut POLICY_DOMAIN_INFORMATION_CLASS; +STRUCT!{struct POLICY_DOMAIN_EFS_INFO { + InfoLength: ::ULONG, + EfsBlob: ::PUCHAR, +}} +pub type PPOLICY_DOMAIN_EFS_INFO = *mut POLICY_DOMAIN_EFS_INFO; +STRUCT!{struct POLICY_DOMAIN_KERBEROS_TICKET_INFO { + AuthenticationOptions: ::ULONG, + MaxServiceTicketAge: ::LARGE_INTEGER, + MaxTicketAge: ::LARGE_INTEGER, + MaxRenewAge: ::LARGE_INTEGER, + MaxClockSkew: ::LARGE_INTEGER, + Reserved: ::LARGE_INTEGER, +}} +pub type PPOLICY_DOMAIN_KERBEROS_TICKET_INFO = *mut POLICY_DOMAIN_KERBEROS_TICKET_INFO; +ENUM!{enum POLICY_NOTIFICATION_INFORMATION_CLASS { + PolicyNotifyAuditEventsInformation = 1, + PolicyNotifyAccountDomainInformation, + PolicyNotifyServerRoleInformation, + PolicyNotifyDnsDomainInformation, + PolicyNotifyDomainEfsInformation, + PolicyNotifyDomainKerberosTicketInformation, + PolicyNotifyMachineAccountPasswordInformation, + PolicyNotifyGlobalSaclInformation, + PolicyNotifyMax, +}} +pub type PPOLICY_NOTIFICATION_INFORMATION_CLASS = *mut POLICY_NOTIFICATION_INFORMATION_CLASS; +pub type LSA_HANDLE = ::PVOID; +pub type PLSA_HANDLE = *mut ::PVOID; +ENUM!{enum TRUSTED_INFORMATION_CLASS { + TrustedDomainNameInformation = 1, + TrustedControllersInformation, + TrustedPosixOffsetInformation, + TrustedPasswordInformation, + TrustedDomainInformationBasic, + TrustedDomainInformationEx, + TrustedDomainAuthInformation, + TrustedDomainFullInformation, + TrustedDomainAuthInformationInternal, + TrustedDomainFullInformationInternal, + TrustedDomainInformationEx2Internal, + TrustedDomainFullInformation2Internal, + TrustedDomainSupportedEncryptionTypes, +}} +pub type PTRUSTED_INFORMATION_CLASS = *mut TRUSTED_INFORMATION_CLASS; +STRUCT!{struct TRUSTED_DOMAIN_NAME_INFO { + Name: ::LSA_UNICODE_STRING, +}} +pub type PTRUSTED_DOMAIN_NAME_INFO = *mut TRUSTED_DOMAIN_NAME_INFO; +STRUCT!{struct TRUSTED_CONTROLLERS_INFO { + Entries: ::ULONG, + Names: ::PLSA_UNICODE_STRING, +}} +pub type PTRUSTED_CONTROLLERS_INFO = *mut TRUSTED_CONTROLLERS_INFO; +STRUCT!{struct TRUSTED_POSIX_OFFSET_INFO { + Offset: ::ULONG, +}} +pub type PTRUSTED_POSIX_OFFSET_INFO = *mut TRUSTED_POSIX_OFFSET_INFO; +STRUCT!{struct TRUSTED_PASSWORD_INFO { + Password: ::LSA_UNICODE_STRING, + OldPassword: ::LSA_UNICODE_STRING, +}} +pub type PTRUSTED_PASSWORD_INFO = *mut TRUSTED_PASSWORD_INFO; +pub type TRUSTED_DOMAIN_INFORMATION_BASIC = ::LSA_TRUST_INFORMATION; +pub type PTRUSTED_DOMAIN_INFORMATION_BASIC = ::PLSA_TRUST_INFORMATION; +pub const TRUST_DIRECTION_DISABLED: ::ULONG = 0x00000000; +pub const TRUST_DIRECTION_INBOUND: ::ULONG = 0x00000001; +pub const TRUST_DIRECTION_OUTBOUND: ::ULONG = 0x00000002; +pub const TRUST_DIRECTION_BIDIRECTIONAL: ::ULONG = TRUST_DIRECTION_INBOUND + | TRUST_DIRECTION_OUTBOUND; +pub const TRUST_TYPE_DOWNLEVEL: ::ULONG = 0x00000001; +pub const TRUST_TYPE_UPLEVEL: ::ULONG = 0x00000002; +pub const TRUST_TYPE_MIT: ::ULONG = 0x00000003; +pub const TRUST_ATTRIBUTE_NON_TRANSITIVE: ::ULONG = 0x00000001; +pub const TRUST_ATTRIBUTE_UPLEVEL_ONLY: ::ULONG = 0x00000002; +pub const TRUST_ATTRIBUTE_QUARANTINED_DOMAIN: ::ULONG = 0x00000004; +pub const TRUST_ATTRIBUTE_FOREST_TRANSITIVE: ::ULONG = 0x00000008; +pub const TRUST_ATTRIBUTE_CROSS_ORGANIZATION: ::ULONG = 0x00000010; +pub const TRUST_ATTRIBUTE_WITHIN_FOREST: ::ULONG = 0x00000020; +pub const TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL: ::ULONG = 0x00000040; +pub const TRUST_ATTRIBUTE_TRUST_USES_RC4_ENCRYPTION: ::ULONG = 0x00000080; +pub const TRUST_ATTRIBUTE_TRUST_USES_AES_KEYS: ::ULONG = 0x00000100; +pub const TRUST_ATTRIBUTE_CROSS_ORGANIZATION_NO_TGT_DELEGATION: ::ULONG = 0x00000200; +pub const TRUST_ATTRIBUTES_VALID: ::ULONG = 0xFF03FFFF; +pub const TRUST_ATTRIBUTES_USER: ::ULONG = 0xFF000000; +STRUCT!{struct TRUSTED_DOMAIN_INFORMATION_EX { + Name: ::LSA_UNICODE_STRING, + FlatName: ::LSA_UNICODE_STRING, + Sid: ::PSID, + TrustDirection: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, +}} +pub type PTRUSTED_DOMAIN_INFORMATION_EX = *mut TRUSTED_DOMAIN_INFORMATION_EX; +STRUCT!{struct TRUSTED_DOMAIN_INFORMATION_EX2 { + Name: ::LSA_UNICODE_STRING, + FlatName: ::LSA_UNICODE_STRING, + Sid: ::PSID, + TrustDirection: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, + ForestTrustLength: ::ULONG, + ForestTrustInfo: ::PUCHAR, +}} +pub type PTRUSTED_DOMAIN_INFORMATION_EX2 = *mut TRUSTED_DOMAIN_INFORMATION_EX2; +pub const TRUST_AUTH_TYPE_NONE: ::ULONG = 0; +pub const TRUST_AUTH_TYPE_NT4OWF: ::ULONG = 1; +pub const TRUST_AUTH_TYPE_CLEAR: ::ULONG = 2; +pub const TRUST_AUTH_TYPE_VERSION: ::ULONG = 3; +STRUCT!{struct LSA_AUTH_INFORMATION { + LastUpdateTime: ::LARGE_INTEGER, + AuthType: ::ULONG, + AuthInfoLength: ::ULONG, + AuthInfo: ::PUCHAR, +}} +pub type PLSA_AUTH_INFORMATION = *mut LSA_AUTH_INFORMATION; +STRUCT!{struct TRUSTED_DOMAIN_AUTH_INFORMATION { + IncomingAuthInfos: ::ULONG, + IncomingAuthenticationInformation: PLSA_AUTH_INFORMATION, + IncomingPreviousAuthenticationInformation: PLSA_AUTH_INFORMATION, + OutgoingAuthInfos: ::ULONG, + OutgoingAuthenticationInformation: PLSA_AUTH_INFORMATION, + OutgoingPreviousAuthenticationInformation: PLSA_AUTH_INFORMATION, +}} +pub type PTRUSTED_DOMAIN_AUTH_INFORMATION = *mut TRUSTED_DOMAIN_AUTH_INFORMATION; +STRUCT!{struct TRUSTED_DOMAIN_FULL_INFORMATION { + Information: TRUSTED_DOMAIN_INFORMATION_EX, + PosixOffset: TRUSTED_POSIX_OFFSET_INFO, + AuthInformation: TRUSTED_DOMAIN_AUTH_INFORMATION, +}} +pub type PTRUSTED_DOMAIN_FULL_INFORMATION = *mut TRUSTED_DOMAIN_FULL_INFORMATION; +STRUCT!{struct TRUSTED_DOMAIN_FULL_INFORMATION2 { + Information: TRUSTED_DOMAIN_INFORMATION_EX2, + PosixOffset: TRUSTED_POSIX_OFFSET_INFO, + AuthInformation: TRUSTED_DOMAIN_AUTH_INFORMATION, +}} +pub type PTRUSTED_DOMAIN_FULL_INFORMATION2 = *mut TRUSTED_DOMAIN_FULL_INFORMATION2; +STRUCT!{struct TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES { + SupportedEncryptionTypes: ::ULONG, +}} +pub type PTRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES = + *mut TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES; +ENUM!{enum LSA_FOREST_TRUST_RECORD_TYPE { + ForestTrustTopLevelName, + ForestTrustTopLevelNameEx, + ForestTrustDomainInfo, + ForestTrustRecordTypeLast, // = ForestTrustDomainInfo, +}} +pub const LSA_FTRECORD_DISABLED_REASONS: ::ULONG = 0x0000FFFF; +pub const LSA_TLN_DISABLED_NEW: ::ULONG = 0x00000001; +pub const LSA_TLN_DISABLED_ADMIN: ::ULONG = 0x00000002; +pub const LSA_TLN_DISABLED_CONFLICT: ::ULONG = 0x00000004; +pub const LSA_SID_DISABLED_ADMIN: ::ULONG = 0x00000001; +pub const LSA_SID_DISABLED_CONFLICT: ::ULONG = 0x00000002; +pub const LSA_NB_DISABLED_ADMIN: ::ULONG = 0x00000004; +pub const LSA_NB_DISABLED_CONFLICT: ::ULONG = 0x00000008; +STRUCT!{struct LSA_FOREST_TRUST_DOMAIN_INFO { + Sid: ::PSID, + DnsName: ::LSA_UNICODE_STRING, + NetbiosName: ::LSA_UNICODE_STRING, +}} +pub type PLSA_FOREST_TRUST_DOMAIN_INFO = *mut LSA_FOREST_TRUST_DOMAIN_INFO; +pub const MAX_FOREST_TRUST_BINARY_DATA_SIZE: ::ULONG = 128 * 1024; +STRUCT!{struct LSA_FOREST_TRUST_BINARY_DATA { + Length: ::ULONG, + Buffer: ::PUCHAR, +}} +pub type PLSA_FOREST_TRUST_BINARY_DATA = *mut LSA_FOREST_TRUST_BINARY_DATA; +STRUCT!{struct LSA_FOREST_TRUST_RECORD_ForestTrustData { + DomainInfo: LSA_FOREST_TRUST_DOMAIN_INFO, +}} +UNION!( + LSA_FOREST_TRUST_RECORD_ForestTrustData, DomainInfo, TopLevelName, TopLevelName_mut, + ::LSA_UNICODE_STRING +); +UNION!( + LSA_FOREST_TRUST_RECORD_ForestTrustData, DomainInfo, Data, Data_mut, + LSA_FOREST_TRUST_BINARY_DATA +); +STRUCT!{struct LSA_FOREST_TRUST_RECORD { + Flags: ::ULONG, + ForestTrustType: LSA_FOREST_TRUST_RECORD_TYPE, + Time: ::LARGE_INTEGER, + ForestTrustData: LSA_FOREST_TRUST_RECORD_ForestTrustData, +}} +pub type PLSA_FOREST_TRUST_RECORD = *mut LSA_FOREST_TRUST_RECORD; +pub const MAX_RECORDS_IN_FOREST_TRUST_INFO: ::ULONG = 4000; +STRUCT!{struct LSA_FOREST_TRUST_INFORMATION { + RecordCount: ::ULONG, + Entries: *mut PLSA_FOREST_TRUST_RECORD, +}} +pub type PLSA_FOREST_TRUST_INFORMATION = *mut LSA_FOREST_TRUST_INFORMATION; +ENUM!{enum LSA_FOREST_TRUST_COLLISION_RECORD_TYPE { + CollisionTdo, + CollisionXref, + CollisionOther, +}} +STRUCT!{struct LSA_FOREST_TRUST_COLLISION_RECORD { + Index: ::ULONG, + Type: LSA_FOREST_TRUST_COLLISION_RECORD_TYPE, + Flags: ::ULONG, + Name: ::LSA_UNICODE_STRING, +}} +pub type PLSA_FOREST_TRUST_COLLISION_RECORD = *mut LSA_FOREST_TRUST_COLLISION_RECORD; +STRUCT!{struct LSA_FOREST_TRUST_COLLISION_INFORMATION { + RecordCount: ::ULONG, + Entries: *mut PLSA_FOREST_TRUST_COLLISION_RECORD, +}} +pub type PLSA_FOREST_TRUST_COLLISION_INFORMATION = *mut LSA_FOREST_TRUST_COLLISION_INFORMATION; +pub type LSA_ENUMERATION_HANDLE = ::ULONG; +pub type PLSA_ENUMERATION_HANDLE = *mut ::ULONG; +STRUCT!{struct LSA_ENUMERATION_INFORMATION { + Sid: ::PSID, +}} +pub type PLSA_ENUMERATION_INFORMATION = *mut LSA_ENUMERATION_INFORMATION; +STRUCT!{struct LSA_LAST_INTER_LOGON_INFO { + LastSuccessfulLogon: ::LARGE_INTEGER, + LastFailedLogon: ::LARGE_INTEGER, + FailedAttemptCountSinceLastSuccessfulLogon: ::ULONG, +}} +pub type PLSA_LAST_INTER_LOGON_INFO = *mut LSA_LAST_INTER_LOGON_INFO; +STRUCT!{struct SECURITY_LOGON_SESSION_DATA { + Size: ::ULONG, + LogonId: ::LUID, + UserName: ::LSA_UNICODE_STRING, + LogonDomain: ::LSA_UNICODE_STRING, + AuthenticationPackage: ::LSA_UNICODE_STRING, + LogonType: ::ULONG, + Session: ::ULONG, + Sid: ::PSID, + LogonTime: ::LARGE_INTEGER, + LogonServer: ::LSA_UNICODE_STRING, + DnsDomainName: ::LSA_UNICODE_STRING, + Upn: ::LSA_UNICODE_STRING, + UserFlags: ::ULONG, + LastLogonInfo: LSA_LAST_INTER_LOGON_INFO, + LogonScript: ::LSA_UNICODE_STRING, + ProfilePath: ::LSA_UNICODE_STRING, + HomeDirectory: ::LSA_UNICODE_STRING, + HomeDirectoryDrive: ::LSA_UNICODE_STRING, + LogoffTime: ::LARGE_INTEGER, + KickOffTime: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, +}} +pub type PSECURITY_LOGON_SESSION_DATA = *mut SECURITY_LOGON_SESSION_DATA; +pub const CENTRAL_ACCESS_POLICY_OWNER_RIGHTS_PRESENT_FLAG: ::ULONG = 0x00000001; +pub const CENTRAL_ACCESS_POLICY_STAGED_OWNER_RIGHTS_PRESENT_FLAG: ::ULONG = 0x00000100; +pub const CENTRAL_ACCESS_POLICY_STAGED_FLAG: ::ULONG = 0x00010000; +pub const CENTRAL_ACCESS_POLICY_VALID_FLAG_MASK: ::ULONG = + CENTRAL_ACCESS_POLICY_OWNER_RIGHTS_PRESENT_FLAG + | CENTRAL_ACCESS_POLICY_STAGED_OWNER_RIGHTS_PRESENT_FLAG | CENTRAL_ACCESS_POLICY_STAGED_FLAG; +pub const LSASETCAPS_RELOAD_FLAG: ::ULONG = 0x00000001; +pub const LSASETCAPS_VALID_FLAG_MASK: ::ULONG = LSASETCAPS_RELOAD_FLAG; +STRUCT!{struct CENTRAL_ACCESS_POLICY_ENTRY { + Name: ::LSA_UNICODE_STRING, + Description: ::LSA_UNICODE_STRING, + ChangeId: ::LSA_UNICODE_STRING, + LengthAppliesTo: ::ULONG, + AppliesTo: ::PUCHAR, + LengthSD: ::ULONG, + SD: ::PSECURITY_DESCRIPTOR, + LengthStagedSD: ::ULONG, + StagedSD: ::PSECURITY_DESCRIPTOR, + Flags: ::ULONG, +}} +pub type PCENTRAL_ACCESS_POLICY_ENTRY = *mut CENTRAL_ACCESS_POLICY_ENTRY; +pub type PCCENTRAL_ACCESS_POLICY_ENTRY = *const CENTRAL_ACCESS_POLICY_ENTRY; +STRUCT!{struct CENTRAL_ACCESS_POLICY { + CAPID: ::PSID, + Name: ::LSA_UNICODE_STRING, + Description: ::LSA_UNICODE_STRING, + ChangeId: ::LSA_UNICODE_STRING, + Flags: ::ULONG, + CAPECount: ::ULONG, + CAPEs: *mut PCENTRAL_ACCESS_POLICY_ENTRY, +}} +pub type PCENTRAL_ACCESS_POLICY = *mut CENTRAL_ACCESS_POLICY; +pub type PCCENTRAL_ACCESS_POLICY = *const CENTRAL_ACCESS_POLICY; +ENUM!{enum NEGOTIATE_MESSAGES { + NegEnumPackagePrefixes = 0, + NegGetCallerName = 1, + NegTransferCredentials = 2, + NegCallPackageMax, +}} +pub const NEGOTIATE_MAX_PREFIX: usize = 32; +STRUCT!{struct NEGOTIATE_PACKAGE_PREFIX { + PackageId: ::ULONG_PTR, + PackageDataA: ::PVOID, + PackageDataW: ::PVOID, + PrefixLen: ::ULONG_PTR, + Prefix: [::UCHAR; NEGOTIATE_MAX_PREFIX], +}} +pub type PNEGOTIATE_PACKAGE_PREFIX = *mut NEGOTIATE_PACKAGE_PREFIX; +STRUCT!{struct NEGOTIATE_PACKAGE_PREFIXES { + MessageType: ::ULONG, + PrefixCount: ::ULONG, + Offset: ::ULONG, + Pad: ::ULONG, +}} +pub type PNEGOTIATE_PACKAGE_PREFIXES = *mut NEGOTIATE_PACKAGE_PREFIXES; +STRUCT!{struct NEGOTIATE_CALLER_NAME_REQUEST { + MessageType: ::ULONG, + LogonId: ::LUID, +}} +pub type PNEGOTIATE_CALLER_NAME_REQUEST = *mut NEGOTIATE_CALLER_NAME_REQUEST; +STRUCT!{struct NEGOTIATE_CALLER_NAME_RESPONSE { + MessageType: ::ULONG, + CallerName: ::PWSTR, +}} +pub type PNEGOTIATE_CALLER_NAME_RESPONSE = *mut NEGOTIATE_CALLER_NAME_RESPONSE; +STRUCT!{struct DOMAIN_PASSWORD_INFORMATION { + MinPasswordLength: ::USHORT, + PasswordHistoryLength: ::USHORT, + PasswordProperties: ::ULONG, + MaxPasswordAge: ::LARGE_INTEGER, + MinPasswordAge: ::LARGE_INTEGER, +}} +pub type PDOMAIN_PASSWORD_INFORMATION = *mut DOMAIN_PASSWORD_INFORMATION; +pub const DOMAIN_PASSWORD_COMPLEX: ::ULONG = 0x00000001; +pub const DOMAIN_PASSWORD_NO_ANON_CHANGE: ::ULONG = 0x00000002; +pub const DOMAIN_PASSWORD_NO_CLEAR_CHANGE: ::ULONG = 0x00000004; +pub const DOMAIN_LOCKOUT_ADMINS: ::ULONG = 0x00000008; +pub const DOMAIN_PASSWORD_STORE_CLEARTEXT: ::ULONG = 0x00000010; +pub const DOMAIN_REFUSE_PASSWORD_CHANGE: ::ULONG = 0x00000020; +pub const DOMAIN_NO_LM_OWF_CHANGE: ::ULONG = 0x00000040; +pub type PSAM_PASSWORD_NOTIFICATION_ROUTINE = Option<unsafe extern "system" fn( + UserName: ::PUNICODE_STRING, RelativeId: ::ULONG, NewPassword: ::PUNICODE_STRING, +) -> ::NTSTATUS>; +pub type PSAM_INIT_NOTIFICATION_ROUTINE = Option<unsafe extern "system" fn() -> ::BOOLEAN>; +pub type PSAM_PASSWORD_FILTER_ROUTINE = Option<unsafe extern "system" fn( + AccountName: ::PUNICODE_STRING, FullName: ::PUNICODE_STRING, Password: ::PUNICODE_STRING, + SetOperation: ::BOOLEAN, +) -> ::BOOLEAN>; +ENUM!{enum MSV1_0_LOGON_SUBMIT_TYPE { + MsV1_0InteractiveLogon = 2, + MsV1_0Lm20Logon, + MsV1_0NetworkLogon, + MsV1_0SubAuthLogon, + MsV1_0WorkstationUnlockLogon = 7, + MsV1_0S4ULogon = 12, + MsV1_0VirtualLogon = 82, + MsV1_0NoElevationLogon = 83, + MsV1_0LuidLogon = 84, +}} +pub type PMSV1_0_LOGON_SUBMIT_TYPE = *mut MSV1_0_LOGON_SUBMIT_TYPE; +ENUM!{enum MSV1_0_PROFILE_BUFFER_TYPE { + MsV1_0InteractiveProfile = 2, + MsV1_0Lm20LogonProfile, + MsV1_0SmartCardProfile, +}} +pub type PMSV1_0_PROFILE_BUFFER_TYPE = *mut MSV1_0_PROFILE_BUFFER_TYPE; +STRUCT!{struct MSV1_0_INTERACTIVE_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, +}} +pub type PMSV1_0_INTERACTIVE_LOGON = *mut MSV1_0_INTERACTIVE_LOGON; +STRUCT!{struct MSV1_0_INTERACTIVE_PROFILE { + MessageType: MSV1_0_PROFILE_BUFFER_TYPE, + LogonCount: ::USHORT, + BadPasswordCount: ::USHORT, + LogonTime: ::LARGE_INTEGER, + LogoffTime: ::LARGE_INTEGER, + KickOffTime: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, + LogonScript: ::UNICODE_STRING, + HomeDirectory: ::UNICODE_STRING, + FullName: ::UNICODE_STRING, + ProfilePath: ::UNICODE_STRING, + HomeDirectoryDrive: ::UNICODE_STRING, + LogonServer: ::UNICODE_STRING, + UserFlags: ::ULONG, +}} +pub type PMSV1_0_INTERACTIVE_PROFILE = *mut MSV1_0_INTERACTIVE_PROFILE; +pub const MSV1_0_CHALLENGE_LENGTH: usize = 8; +pub const MSV1_0_USER_SESSION_KEY_LENGTH: usize = 16; +pub const MSV1_0_LANMAN_SESSION_KEY_LENGTH: usize = 8; +pub const MSV1_0_CLEARTEXT_PASSWORD_ALLOWED: ::ULONG = 0x02; +pub const MSV1_0_UPDATE_LOGON_STATISTICS: ::ULONG = 0x04; +pub const MSV1_0_RETURN_USER_PARAMETERS: ::ULONG = 0x08; +pub const MSV1_0_DONT_TRY_GUEST_ACCOUNT: ::ULONG = 0x10; +pub const MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT: ::ULONG = 0x20; +pub const MSV1_0_RETURN_PASSWORD_EXPIRY: ::ULONG = 0x40; +pub const MSV1_0_USE_CLIENT_CHALLENGE: ::ULONG = 0x80; +pub const MSV1_0_TRY_GUEST_ACCOUNT_ONLY: ::ULONG = 0x100; +pub const MSV1_0_RETURN_PROFILE_PATH: ::ULONG = 0x200; +pub const MSV1_0_TRY_SPECIFIED_DOMAIN_ONLY: ::ULONG = 0x400; +pub const MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT: ::ULONG = 0x800; +pub const MSV1_0_DISABLE_PERSONAL_FALLBACK: ::ULONG = 0x00001000; +pub const MSV1_0_ALLOW_FORCE_GUEST: ::ULONG = 0x00002000; +pub const MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED: ::ULONG = 0x00004000; +pub const MSV1_0_USE_DOMAIN_FOR_ROUTING_ONLY: ::ULONG = 0x00008000; +pub const MSV1_0_SUBAUTHENTICATION_DLL_EX: ::ULONG = 0x00100000; +pub const MSV1_0_ALLOW_MSVCHAPV2: ::ULONG = 0x00010000; +pub const MSV1_0_S4U2SELF: ::ULONG = 0x00020000; +pub const MSV1_0_CHECK_LOGONHOURS_FOR_S4U: ::ULONG = 0x00040000; +pub const MSV1_0_INTERNET_DOMAIN: ::ULONG = 0x00080000; +pub const MSV1_0_SUBAUTHENTICATION_DLL: ::ULONG = 0xFF000000; +pub const MSV1_0_SUBAUTHENTICATION_DLL_SHIFT: ::ULONG = 24; +pub const MSV1_0_MNS_LOGON: ::ULONG = 0x01000000; +pub const MSV1_0_SUBAUTHENTICATION_DLL_RAS: ::ULONG = 2; +pub const MSV1_0_SUBAUTHENTICATION_DLL_IIS: ::ULONG = 132; +STRUCT!{struct MSV1_0_LM20_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Workstation: ::UNICODE_STRING, + ChallengeToClient: [::UCHAR; MSV1_0_CHALLENGE_LENGTH], + CaseSensitiveChallengeResponse: ::STRING, + CaseInsensitiveChallengeResponse: ::STRING, + ParameterControl: ::ULONG, +}} +pub type PMSV1_0_LM20_LOGON = *mut MSV1_0_LM20_LOGON; +STRUCT!{struct MSV1_0_SUBAUTH_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Workstation: ::UNICODE_STRING, + ChallengeToClient: [::UCHAR; MSV1_0_CHALLENGE_LENGTH], + AuthenticationInfo1: ::STRING, + AuthenticationInfo2: ::STRING, + ParameterControl: ::ULONG, + SubAuthPackageId: ::ULONG, +}} +pub type PMSV1_0_SUBAUTH_LOGON = *mut MSV1_0_SUBAUTH_LOGON; +STRUCT!{struct MSV1_0_S4U_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + MSV1_0_LOGON_SUBMIT_TYPE: ::ULONG, + UserPrincipalName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, +}} +pub type PMSV1_0_S4U_LOGON = *mut MSV1_0_S4U_LOGON; +pub const LOGON_GUEST: ::ULONG = 0x01; +pub const LOGON_NOENCRYPTION: ::ULONG = 0x02; +pub const LOGON_CACHED_ACCOUNT: ::ULONG = 0x04; +pub const LOGON_USED_LM_PASSWORD: ::ULONG = 0x08; +pub const LOGON_EXTRA_SIDS: ::ULONG = 0x20; +pub const LOGON_SUBAUTH_SESSION_KEY: ::ULONG = 0x40; +pub const LOGON_SERVER_TRUST_ACCOUNT: ::ULONG = 0x80; +pub const LOGON_NTLMV2_ENABLED: ::ULONG = 0x100; +pub const LOGON_RESOURCE_GROUPS: ::ULONG = 0x200; +pub const LOGON_PROFILE_PATH_RETURNED: ::ULONG = 0x400; +pub const LOGON_NT_V2: ::ULONG = 0x800; +pub const LOGON_LM_V2: ::ULONG = 0x1000; +pub const LOGON_NTLM_V2: ::ULONG = 0x2000; +pub const LOGON_OPTIMIZED: ::ULONG = 0x4000; +pub const LOGON_WINLOGON: ::ULONG = 0x8000; +pub const LOGON_PKINIT: ::ULONG = 0x10000; +pub const LOGON_NO_OPTIMIZED: ::ULONG = 0x20000; +pub const LOGON_NO_ELEVATION: ::ULONG = 0x40000; +pub const LOGON_MANAGED_SERVICE: ::ULONG = 0x80000; +pub const LOGON_GRACE_LOGON: ::ULONG = 0x01000000; +STRUCT!{struct MSV1_0_LM20_LOGON_PROFILE { + MessageType: MSV1_0_PROFILE_BUFFER_TYPE, + KickOffTime: ::LARGE_INTEGER, + LogoffTime: ::LARGE_INTEGER, + UserFlags: ::ULONG, + UserSessionKey: [::UCHAR; MSV1_0_USER_SESSION_KEY_LENGTH], + LogonDomainName: ::UNICODE_STRING, + LanmanSessionKey: [::UCHAR; MSV1_0_LANMAN_SESSION_KEY_LENGTH], + LogonServer: ::UNICODE_STRING, + UserParameters: ::UNICODE_STRING, +}} +pub type PMSV1_0_LM20_LOGON_PROFILE = *mut MSV1_0_LM20_LOGON_PROFILE; +pub const MSV1_0_OWF_PASSWORD_LENGTH: usize = 16; +STRUCT!{struct MSV1_0_SUPPLEMENTAL_CREDENTIAL { + Version: ::ULONG, + Flags: ::ULONG, + LmPassword: [::UCHAR; MSV1_0_OWF_PASSWORD_LENGTH], + NtPassword: [::UCHAR; MSV1_0_OWF_PASSWORD_LENGTH], +}} +pub type PMSV1_0_SUPPLEMENTAL_CREDENTIAL = *mut MSV1_0_SUPPLEMENTAL_CREDENTIAL; +pub const MSV1_0_NTLM3_RESPONSE_LENGTH: usize = 16; +pub const MSV1_0_NTLM3_OWF_LENGTH: usize = 16; +STRUCT!{struct MSV1_0_NTLM3_RESPONSE { + Response: [::UCHAR; MSV1_0_NTLM3_RESPONSE_LENGTH], + RespType: ::UCHAR, + HiRespType: ::UCHAR, + Flags: ::USHORT, + MsgWord: ::ULONG, + TimeStamp: ::ULONGLONG, + ChallengeFromClient: [::UCHAR; MSV1_0_CHALLENGE_LENGTH], + AvPairsOff: ::ULONG, + Buffer: [::UCHAR; 1], +}} +pub type PMSV1_0_NTLM3_RESPONSE = *mut MSV1_0_NTLM3_RESPONSE; +ENUM!{enum MSV1_0_AVID { + MsvAvEOL, + MsvAvNbComputerName, + MsvAvNbDomainName, + MsvAvDnsComputerName, + MsvAvDnsDomainName, + MsvAvDnsTreeName, + MsvAvFlags, + MsvAvTimestamp, + MsvAvRestrictions, + MsvAvTargetName, + MsvAvChannelBindings, +}} +STRUCT!{struct MSV1_0_AV_PAIR { + AvId: ::USHORT, + AvLen: ::USHORT, +}} +pub type PMSV1_0_AV_PAIR = *mut MSV1_0_AV_PAIR; +ENUM!{enum MSV1_0_PROTOCOL_MESSAGE_TYPE { + MsV1_0Lm20ChallengeRequest = 0, + MsV1_0Lm20GetChallengeResponse, + MsV1_0EnumerateUsers, + MsV1_0GetUserInfo, + MsV1_0ReLogonUsers, + MsV1_0ChangePassword, + MsV1_0ChangeCachedPassword, + MsV1_0GenericPassthrough, + MsV1_0CacheLogon, + MsV1_0SubAuth, + MsV1_0DeriveCredential, + MsV1_0CacheLookup, + MsV1_0SetProcessOption, + MsV1_0ConfigLocalAliases, + MsV1_0ClearCachedCredentials, + MsV1_0LookupToken, + MsV1_0ValidateAuth, + MsV1_0CacheLookupEx, + MsV1_0GetCredentialKey, + MsV1_0SetThreadOption, +}} +pub type PMSV1_0_PROTOCOL_MESSAGE_TYPE = *mut MSV1_0_PROTOCOL_MESSAGE_TYPE; +STRUCT!{struct MSV1_0_CHANGEPASSWORD_REQUEST { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + DomainName: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + OldPassword: ::UNICODE_STRING, + NewPassword: ::UNICODE_STRING, + Impersonating: ::BOOLEAN, +}} +pub type PMSV1_0_CHANGEPASSWORD_REQUEST = *mut MSV1_0_CHANGEPASSWORD_REQUEST; +STRUCT!{struct MSV1_0_CHANGEPASSWORD_RESPONSE { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + PasswordInfoValid: ::BOOLEAN, + DomainPasswordInfo: DOMAIN_PASSWORD_INFORMATION, +}} +pub type PMSV1_0_CHANGEPASSWORD_RESPONSE = *mut MSV1_0_CHANGEPASSWORD_RESPONSE; +STRUCT!{struct MSV1_0_PASSTHROUGH_REQUEST { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + DomainName: ::UNICODE_STRING, + PackageName: ::UNICODE_STRING, + DataLength: ::ULONG, + LogonData: ::PUCHAR, + Pad: ::ULONG, +}} +pub type PMSV1_0_PASSTHROUGH_REQUEST = *mut MSV1_0_PASSTHROUGH_REQUEST; +STRUCT!{struct MSV1_0_PASSTHROUGH_RESPONSE { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + Pad: ::ULONG, + DataLength: ::ULONG, + ValidationData: ::PUCHAR, +}} +pub type PMSV1_0_PASSTHROUGH_RESPONSE = *mut MSV1_0_PASSTHROUGH_RESPONSE; +STRUCT!{struct MSV1_0_SUBAUTH_REQUEST { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + SubAuthPackageId: ::ULONG, + SubAuthInfoLength: ::ULONG, + SubAuthSubmitBuffer: ::PUCHAR, +}} +pub type PMSV1_0_SUBAUTH_REQUEST = *mut MSV1_0_SUBAUTH_REQUEST; +STRUCT!{struct MSV1_0_SUBAUTH_RESPONSE { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + SubAuthInfoLength: ::ULONG, + SubAuthReturnBuffer: ::PUCHAR, +}} +pub type PMSV1_0_SUBAUTH_RESPONSE = *mut MSV1_0_SUBAUTH_RESPONSE; +pub const RTL_ENCRYPT_MEMORY_SIZE: ::ULONG = 8; +pub const RTL_ENCRYPT_OPTION_CROSS_PROCESS: ::ULONG = 0x01; +pub const RTL_ENCRYPT_OPTION_SAME_LOGON: ::ULONG = 0x02; +pub const KERB_ETYPE_NULL: ::LONG = 0; +pub const KERB_ETYPE_DES_CBC_CRC: ::LONG = 1; +pub const KERB_ETYPE_DES_CBC_MD4: ::LONG = 2; +pub const KERB_ETYPE_DES_CBC_MD5: ::LONG = 3; +pub const KERB_ETYPE_AES128_CTS_HMAC_SHA1_96: ::LONG = 17; +pub const KERB_ETYPE_AES256_CTS_HMAC_SHA1_96: ::LONG = 18; +pub const KERB_ETYPE_RC4_MD4: ::LONG = -128; +pub const KERB_ETYPE_RC4_PLAIN2: ::LONG = -129; +pub const KERB_ETYPE_RC4_LM: ::LONG = -130; +pub const KERB_ETYPE_RC4_SHA: ::LONG = -131; +pub const KERB_ETYPE_DES_PLAIN: ::LONG = -132; +pub const KERB_ETYPE_RC4_HMAC_OLD: ::LONG = -133; +pub const KERB_ETYPE_RC4_PLAIN_OLD: ::LONG = -134; +pub const KERB_ETYPE_RC4_HMAC_OLD_EXP: ::LONG = -135; +pub const KERB_ETYPE_RC4_PLAIN_OLD_EXP: ::LONG = -136; +pub const KERB_ETYPE_RC4_PLAIN: ::LONG = -140; +pub const KERB_ETYPE_RC4_PLAIN_EXP: ::LONG = -141; +pub const KERB_ETYPE_AES128_CTS_HMAC_SHA1_96_PLAIN: ::LONG = -148; +pub const KERB_ETYPE_AES256_CTS_HMAC_SHA1_96_PLAIN: ::LONG = -149; +pub const KERB_ETYPE_DSA_SHA1_CMS: ::LONG = 9; +pub const KERB_ETYPE_RSA_MD5_CMS: ::LONG = 10; +pub const KERB_ETYPE_RSA_SHA1_CMS: ::LONG = 11; +pub const KERB_ETYPE_RC2_CBC_ENV: ::LONG = 12; +pub const KERB_ETYPE_RSA_ENV: ::LONG = 13; +pub const KERB_ETYPE_RSA_ES_OEAP_ENV: ::LONG = 14; +pub const KERB_ETYPE_DES_EDE3_CBC_ENV: ::LONG = 15; +pub const KERB_ETYPE_DSA_SIGN: ::LONG = 8; +pub const KERB_ETYPE_RSA_PRIV: ::LONG = 9; +pub const KERB_ETYPE_RSA_PUB: ::LONG = 10; +pub const KERB_ETYPE_RSA_PUB_MD5: ::LONG = 11; +pub const KERB_ETYPE_RSA_PUB_SHA1: ::LONG = 12; +pub const KERB_ETYPE_PKCS7_PUB: ::LONG = 13; +pub const KERB_ETYPE_DES3_CBC_MD5: ::LONG = 5; +pub const KERB_ETYPE_DES3_CBC_SHA1: ::LONG = 7; +pub const KERB_ETYPE_DES3_CBC_SHA1_KD: ::LONG = 16; +pub const KERB_ETYPE_DES_CBC_MD5_NT: ::LONG = 20; +pub const KERB_ETYPE_RC4_HMAC_NT: ::LONG = 23; +pub const KERB_ETYPE_RC4_HMAC_NT_EXP: ::LONG = 24; +pub const KERB_CHECKSUM_NONE: ::LONG = 0; +pub const KERB_CHECKSUM_CRC32: ::LONG = 1; +pub const KERB_CHECKSUM_MD4: ::LONG = 2; +pub const KERB_CHECKSUM_KRB_DES_MAC: ::LONG = 4; +pub const KERB_CHECKSUM_KRB_DES_MAC_K: ::LONG = 5; +pub const KERB_CHECKSUM_MD5: ::LONG = 7; +pub const KERB_CHECKSUM_MD5_DES: ::LONG = 8; +pub const KERB_CHECKSUM_SHA1_NEW: ::LONG = 14; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES128: ::LONG = 15; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES256: ::LONG = 16; +pub const KERB_CHECKSUM_LM: ::LONG = -130; +pub const KERB_CHECKSUM_SHA1: ::LONG = -131; +pub const KERB_CHECKSUM_REAL_CRC32: ::LONG = -132; +pub const KERB_CHECKSUM_DES_MAC: ::LONG = -133; +pub const KERB_CHECKSUM_DES_MAC_MD5: ::LONG = -134; +pub const KERB_CHECKSUM_MD25: ::LONG = -135; +pub const KERB_CHECKSUM_RC4_MD5: ::LONG = -136; +pub const KERB_CHECKSUM_MD5_HMAC: ::LONG = -137; +pub const KERB_CHECKSUM_HMAC_MD5: ::LONG = -138; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES128_Ki: ::LONG = -150; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES256_Ki: ::LONG = -151; +pub const KERB_TICKET_FLAGS_reserved: ::ULONG = 0x80000000; +pub const KERB_TICKET_FLAGS_forwardable: ::ULONG = 0x40000000; +pub const KERB_TICKET_FLAGS_forwarded: ::ULONG = 0x20000000; +pub const KERB_TICKET_FLAGS_proxiable: ::ULONG = 0x10000000; +pub const KERB_TICKET_FLAGS_proxy: ::ULONG = 0x08000000; +pub const KERB_TICKET_FLAGS_may_postdate: ::ULONG = 0x04000000; +pub const KERB_TICKET_FLAGS_postdated: ::ULONG = 0x02000000; +pub const KERB_TICKET_FLAGS_invalid: ::ULONG = 0x01000000; +pub const KERB_TICKET_FLAGS_renewable: ::ULONG = 0x00800000; +pub const KERB_TICKET_FLAGS_initial: ::ULONG = 0x00400000; +pub const KERB_TICKET_FLAGS_pre_authent: ::ULONG = 0x00200000; +pub const KERB_TICKET_FLAGS_hw_authent: ::ULONG = 0x00100000; +pub const KERB_TICKET_FLAGS_ok_as_delegate: ::ULONG = 0x00040000; +pub const KERB_TICKET_FLAGS_name_canonicalize: ::ULONG = 0x00010000; +pub const KERB_TICKET_FLAGS_cname_in_pa_data: ::ULONG = 0x00040000; +pub const KERB_TICKET_FLAGS_enc_pa_rep: ::ULONG = 0x00010000; +pub const KERB_TICKET_FLAGS_reserved1: ::ULONG = 0x00000001; +pub const KRB_NT_UNKNOWN: ::LONG = 0; +pub const KRB_NT_PRINCIPAL: ::LONG = 1; +pub const KRB_NT_PRINCIPAL_AND_ID: ::LONG = -131; +pub const KRB_NT_SRV_INST: ::LONG = 2; +pub const KRB_NT_SRV_INST_AND_ID: ::LONG = -132; +pub const KRB_NT_SRV_HST: ::LONG = 3; +pub const KRB_NT_SRV_XHST: ::LONG = 4; +pub const KRB_NT_UID: ::LONG = 5; +pub const KRB_NT_ENTERPRISE_PRINCIPAL: ::LONG = 10; +pub const KRB_NT_WELLKNOWN: ::LONG = 11; +pub const KRB_NT_ENT_PRINCIPAL_AND_ID: ::LONG = -130; +pub const KRB_NT_MS_PRINCIPAL: ::LONG = -128; +pub const KRB_NT_MS_PRINCIPAL_AND_ID: ::LONG = -129; +pub const KRB_NT_MS_BRANCH_ID: ::LONG = -133; +pub const KRB_NT_X500_PRINCIPAL: ::LONG = 6; +pub const KERB_WRAP_NO_ENCRYPT: ::ULONG = 0x80000001; +ENUM!{enum KERB_LOGON_SUBMIT_TYPE { + KerbInteractiveLogon = 2, + KerbSmartCardLogon = 6, + KerbWorkstationUnlockLogon = 7, + KerbSmartCardUnlockLogon = 8, + KerbProxyLogon = 9, + KerbTicketLogon = 10, + KerbTicketUnlockLogon = 11, + KerbS4ULogon = 12, + KerbCertificateLogon = 13, + KerbCertificateS4ULogon = 14, + KerbCertificateUnlockLogon = 15, + KerbNoElevationLogon = 83, + KerbLuidLogon = 84, +}} +pub type PKERB_LOGON_SUBMIT_TYPE = *mut KERB_LOGON_SUBMIT_TYPE; +STRUCT!{struct KERB_INTERACTIVE_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, +}} +pub type PKERB_INTERACTIVE_LOGON = *mut KERB_INTERACTIVE_LOGON; +STRUCT!{struct KERB_INTERACTIVE_UNLOCK_LOGON { + Logon: KERB_INTERACTIVE_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_INTERACTIVE_UNLOCK_LOGON = *mut KERB_INTERACTIVE_UNLOCK_LOGON; +STRUCT!{struct KERB_SMART_CARD_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Pin: ::UNICODE_STRING, + CspDataLength: ::ULONG, + CspData: ::PUCHAR, +}} +pub type PKERB_SMART_CARD_LOGON = *mut KERB_SMART_CARD_LOGON; +STRUCT!{struct KERB_SMART_CARD_UNLOCK_LOGON { + Logon: KERB_SMART_CARD_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_SMART_CARD_UNLOCK_LOGON = *mut KERB_SMART_CARD_UNLOCK_LOGON; +pub const KERB_CERTIFICATE_LOGON_FLAG_CHECK_DUPLICATES: ::ULONG = 0x1; +pub const KERB_CERTIFICATE_LOGON_FLAG_USE_CERTIFICATE_INFO: ::ULONG = 0x2; +STRUCT!{struct KERB_CERTIFICATE_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + DomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Pin: ::UNICODE_STRING, + Flags: ::ULONG, + CspDataLength: ::ULONG, + CspData: ::PUCHAR, +}} +pub type PKERB_CERTIFICATE_LOGON = *mut KERB_CERTIFICATE_LOGON; +STRUCT!{struct KERB_CERTIFICATE_UNLOCK_LOGON { + Logon: KERB_CERTIFICATE_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_CERTIFICATE_UNLOCK_LOGON = *mut KERB_CERTIFICATE_UNLOCK_LOGON; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_DUPLICATES: ::ULONG = 0x1; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS: ::ULONG = 0x2; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_FAIL_IF_NT_AUTH_POLICY_REQUIRED: ::ULONG = 0x4; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_IDENTIFY: ::ULONG = 0x8; +STRUCT!{struct KERB_CERTIFICATE_S4U_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + UserPrincipalName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + CertificateLength: ::ULONG, + Certificate: ::PUCHAR, +}} +pub type PKERB_CERTIFICATE_S4U_LOGON = *mut KERB_CERTIFICATE_S4U_LOGON; +STRUCT!{struct KERB_TICKET_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + ServiceTicketLength: ::ULONG, + TicketGrantingTicketLength: ::ULONG, + ServiceTicket: ::PUCHAR, + TicketGrantingTicket: ::PUCHAR, +}} +pub type PKERB_TICKET_LOGON = *mut KERB_TICKET_LOGON; +STRUCT!{struct KERB_TICKET_UNLOCK_LOGON { + Logon: KERB_TICKET_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_TICKET_UNLOCK_LOGON = *mut KERB_TICKET_UNLOCK_LOGON; +pub const KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS: ::ULONG = 0x2; +pub const KERB_S4U_LOGON_FLAG_IDENTIFY: ::ULONG = 0x8; +STRUCT!{struct KERB_S4U_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + ClientUpn: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, +}} +pub type PKERB_S4U_LOGON = *mut KERB_S4U_LOGON; +ENUM!{enum KERB_PROFILE_BUFFER_TYPE { + KerbInteractiveProfile = 2, + KerbSmartCardProfile = 4, + KerbTicketProfile = 6, +}} +pub type PKERB_PROFILE_BUFFER_TYPE = *mut KERB_PROFILE_BUFFER_TYPE; +STRUCT!{struct KERB_INTERACTIVE_PROFILE { + MessageType: KERB_PROFILE_BUFFER_TYPE, + LogonCount: ::USHORT, + BadPasswordCount: ::USHORT, + LogonTime: ::LARGE_INTEGER, + LogoffTime: ::LARGE_INTEGER, + KickOffTime: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, + LogonScript: ::UNICODE_STRING, + HomeDirectory: ::UNICODE_STRING, + FullName: ::UNICODE_STRING, + ProfilePath: ::UNICODE_STRING, + HomeDirectoryDrive: ::UNICODE_STRING, + LogonServer: ::UNICODE_STRING, + UserFlags: ::ULONG, +}} +pub type PKERB_INTERACTIVE_PROFILE = *mut KERB_INTERACTIVE_PROFILE; +STRUCT!{struct KERB_SMART_CARD_PROFILE { + Profile: KERB_INTERACTIVE_PROFILE, + CertificateSize: ::ULONG, + CertificateData: ::PUCHAR, +}} +pub type PKERB_SMART_CARD_PROFILE = *mut KERB_SMART_CARD_PROFILE; +STRUCT!{struct KERB_CRYPTO_KEY { + KeyType: ::LONG, + Length: ::ULONG, + Value: ::PUCHAR, +}} +pub type PKERB_CRYPTO_KEY = *mut KERB_CRYPTO_KEY; +STRUCT!{struct KERB_CRYPTO_KEY32 { + KeyType: ::LONG, + Length: ::ULONG, + Offset: ::ULONG, +}} +pub type PKERB_CRYPTO_KEY32 = *mut KERB_CRYPTO_KEY32; +STRUCT!{struct KERB_TICKET_PROFILE { + Profile: KERB_INTERACTIVE_PROFILE, + SessionKey: KERB_CRYPTO_KEY, +}} +pub type PKERB_TICKET_PROFILE = *mut KERB_TICKET_PROFILE; +ENUM!{enum KERB_PROTOCOL_MESSAGE_TYPE { + KerbDebugRequestMessage = 0, + KerbQueryTicketCacheMessage, + KerbChangeMachinePasswordMessage, + KerbVerifyPacMessage, + KerbRetrieveTicketMessage, + KerbUpdateAddressesMessage, + KerbPurgeTicketCacheMessage, + KerbChangePasswordMessage, + KerbRetrieveEncodedTicketMessage, + KerbDecryptDataMessage, + KerbAddBindingCacheEntryMessage, + KerbSetPasswordMessage, + KerbSetPasswordExMessage, + KerbVerifyCredentialsMessage, + KerbQueryTicketCacheExMessage, + KerbPurgeTicketCacheExMessage, + KerbRefreshSmartcardCredentialsMessage, + KerbAddExtraCredentialsMessage, + KerbQuerySupplementalCredentialsMessage, + KerbTransferCredentialsMessage, + KerbQueryTicketCacheEx2Message, + KerbSubmitTicketMessage, + KerbAddExtraCredentialsExMessage, + KerbQueryKdcProxyCacheMessage, + KerbPurgeKdcProxyCacheMessage, + KerbQueryTicketCacheEx3Message, + KerbCleanupMachinePkinitCredsMessage, + KerbAddBindingCacheEntryExMessage, + KerbQueryBindingCacheMessage, + KerbPurgeBindingCacheMessage, + KerbPinKdcMessage, + KerbUnpinAllKdcsMessage, + KerbQueryDomainExtendedPoliciesMessage, + KerbQueryS4U2ProxyCacheMessage, +}} +pub type PKERB_PROTOCOL_MESSAGE_TYPE = *mut KERB_PROTOCOL_MESSAGE_TYPE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, +}} +pub type PKERB_QUERY_TKT_CACHE_REQUEST = *mut KERB_QUERY_TKT_CACHE_REQUEST; +STRUCT!{struct KERB_TICKET_CACHE_INFO { + ServerName: ::UNICODE_STRING, + RealmName: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, +}} +pub type PKERB_TICKET_CACHE_INFO = *mut KERB_TICKET_CACHE_INFO; +STRUCT!{struct KERB_TICKET_CACHE_INFO_EX { + ClientName: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ServerName: ::UNICODE_STRING, + ServerRealm: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, +}} +pub type PKERB_TICKET_CACHE_INFO_EX = *mut KERB_TICKET_CACHE_INFO_EX; +STRUCT!{struct KERB_TICKET_CACHE_INFO_EX2 { + ClientName: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ServerName: ::UNICODE_STRING, + ServerRealm: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, + SessionKeyType: ::ULONG, + BranchId: ::ULONG, +}} +pub type PKERB_TICKET_CACHE_INFO_EX2 = *mut KERB_TICKET_CACHE_INFO_EX2; +STRUCT!{struct KERB_TICKET_CACHE_INFO_EX3 { + ClientName: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ServerName: ::UNICODE_STRING, + ServerRealm: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, + SessionKeyType: ::ULONG, + BranchId: ::ULONG, + CacheFlags: ::ULONG, + KdcCalled: ::UNICODE_STRING, +}} +pub type PKERB_TICKET_CACHE_INFO_EX3 = *mut KERB_TICKET_CACHE_INFO_EX3; +STRUCT!{struct KERB_QUERY_TKT_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_RESPONSE = *mut KERB_QUERY_TKT_CACHE_RESPONSE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_EX_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO_EX; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_EX_RESPONSE = *mut KERB_QUERY_TKT_CACHE_EX_RESPONSE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_EX2_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO_EX2; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_EX2_RESPONSE = *mut KERB_QUERY_TKT_CACHE_EX2_RESPONSE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_EX3_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO_EX3; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_EX3_RESPONSE = *mut KERB_QUERY_TKT_CACHE_EX3_RESPONSE; +pub const KERB_USE_DEFAULT_TICKET_FLAGS: ::ULONG = 0x0; +pub const KERB_RETRIEVE_TICKET_DEFAULT: ::ULONG = 0x0; +pub const KERB_RETRIEVE_TICKET_DONT_USE_CACHE: ::ULONG = 0x1; +pub const KERB_RETRIEVE_TICKET_USE_CACHE_ONLY: ::ULONG = 0x2; +pub const KERB_RETRIEVE_TICKET_USE_CREDHANDLE: ::ULONG = 0x4; +pub const KERB_RETRIEVE_TICKET_AS_KERB_CRED: ::ULONG = 0x8; +pub const KERB_RETRIEVE_TICKET_WITH_SEC_CRED: ::ULONG = 0x10; +pub const KERB_RETRIEVE_TICKET_CACHE_TICKET: ::ULONG = 0x20; +pub const KERB_RETRIEVE_TICKET_MAX_LIFETIME: ::ULONG = 0x40; +STRUCT!{struct KERB_AUTH_DATA { + Type: ::ULONG, + Length: ::ULONG, + Data: ::PUCHAR, +}} +pub type PKERB_AUTH_DATA = *mut KERB_AUTH_DATA; +STRUCT!{struct KERB_NET_ADDRESS { + Family: ::ULONG, + Length: ::ULONG, + Address: ::PUCHAR, +}} +pub type PKERB_NET_ADDRESS = *mut KERB_NET_ADDRESS; +STRUCT!{struct KERB_NET_ADDRESSES { + Number: ::ULONG, + Addresses: [KERB_NET_ADDRESS; ::ANYSIZE_ARRAY], +}} +pub type PKERB_NET_ADDRESSES = *mut KERB_NET_ADDRESSES; +STRUCT!{struct KERB_EXTERNAL_NAME { + NameType: ::SHORT, + NameCount: ::USHORT, + Names: [::UNICODE_STRING; ::ANYSIZE_ARRAY], +}} +pub type PKERB_EXTERNAL_NAME = *mut KERB_EXTERNAL_NAME; +STRUCT!{struct KERB_EXTERNAL_TICKET { + ServiceName: PKERB_EXTERNAL_NAME, + TargetName: PKERB_EXTERNAL_NAME, + ClientName: PKERB_EXTERNAL_NAME, + DomainName: ::UNICODE_STRING, + TargetDomainName: ::UNICODE_STRING, + AltTargetDomainName: ::UNICODE_STRING, + SessionKey: KERB_CRYPTO_KEY, + TicketFlags: ::ULONG, + Flags: ::ULONG, + KeyExpirationTime: ::LARGE_INTEGER, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewUntil: ::LARGE_INTEGER, + TimeSkew: ::LARGE_INTEGER, + EncodedTicketSize: ::ULONG, + EncodedTicket: ::PUCHAR, +}} +pub type PKERB_EXTERNAL_TICKET = *mut KERB_EXTERNAL_TICKET; +STRUCT!{struct KERB_RETRIEVE_TKT_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + TargetName: ::UNICODE_STRING, + TicketFlags: ::ULONG, + CacheOptions: ::ULONG, + EncryptionType: ::LONG, + CredentialsHandle: ::SecHandle, +}} +pub type PKERB_RETRIEVE_TKT_REQUEST = *mut KERB_RETRIEVE_TKT_REQUEST; +STRUCT!{struct KERB_RETRIEVE_TKT_RESPONSE { + Ticket: KERB_EXTERNAL_TICKET, +}} +pub type PKERB_RETRIEVE_TKT_RESPONSE = *mut KERB_RETRIEVE_TKT_RESPONSE; +STRUCT!{struct KERB_PURGE_TKT_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + ServerName: ::UNICODE_STRING, + RealmName: ::UNICODE_STRING, +}} +pub type PKERB_PURGE_TKT_CACHE_REQUEST = *mut KERB_PURGE_TKT_CACHE_REQUEST; +pub const KERB_PURGE_ALL_TICKETS: ::ULONG = 1; +STRUCT!{struct KERB_PURGE_TKT_CACHE_EX_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + Flags: ::ULONG, + TicketTemplate: KERB_TICKET_CACHE_INFO_EX, +}} +pub type PKERB_PURGE_TKT_CACHE_EX_REQUEST = *mut KERB_PURGE_TKT_CACHE_EX_REQUEST; +STRUCT!{struct KERB_SUBMIT_TKT_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + Flags: ::ULONG, + Key: KERB_CRYPTO_KEY32, + KerbCredSize: ::ULONG, + KerbCredOffset: ::ULONG, +}} +pub type PKERB_SUBMIT_TKT_REQUEST = *mut KERB_SUBMIT_TKT_REQUEST; +STRUCT!{struct KERB_QUERY_KDC_PROXY_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + LogonId: ::LUID, +}} +pub type PKERB_QUERY_KDC_PROXY_CACHE_REQUEST = *mut KERB_QUERY_KDC_PROXY_CACHE_REQUEST; +STRUCT!{struct KDC_PROXY_CACHE_ENTRY_DATA { + SinceLastUsed: ::ULONG64, + DomainName: ::UNICODE_STRING, + ProxyServerName: ::UNICODE_STRING, + ProxyServerVdir: ::UNICODE_STRING, + ProxyServerPort: ::USHORT, + LogonId: ::LUID, + CredUserName: ::UNICODE_STRING, + CredDomainName: ::UNICODE_STRING, + GlobalCache: ::BOOLEAN, +}} +pub type PKDC_PROXY_CACHE_ENTRY_DATA = *mut KDC_PROXY_CACHE_ENTRY_DATA; +STRUCT!{struct KERB_QUERY_KDC_PROXY_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfEntries: ::ULONG, + Entries: PKDC_PROXY_CACHE_ENTRY_DATA, +}} +pub type PKERB_QUERY_KDC_PROXY_CACHE_RESPONSE = *mut KERB_QUERY_KDC_PROXY_CACHE_RESPONSE; +STRUCT!{struct KERB_PURGE_KDC_PROXY_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + LogonId: ::LUID, +}} +pub type PKERB_PURGE_KDC_PROXY_CACHE_REQUEST = *mut KERB_PURGE_KDC_PROXY_CACHE_REQUEST; +STRUCT!{struct KERB_PURGE_KDC_PROXY_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfPurged: ::ULONG, +}} +pub type PKERB_PURGE_KDC_PROXY_CACHE_RESPONSE = *mut KERB_PURGE_KDC_PROXY_CACHE_RESPONSE; +pub const KERB_S4U2PROXY_CACHE_ENTRY_INFO_FLAG_NEGATIVE: ::ULONG = 0x1; +STRUCT!{struct KERB_S4U2PROXY_CACHE_ENTRY_INFO { + ServerName: ::UNICODE_STRING, + Flags: ::ULONG, + LastStatus: ::NTSTATUS, + Expiry: ::LARGE_INTEGER, +}} +pub type PKERB_S4U2PROXY_CACHE_ENTRY_INFO = *mut KERB_S4U2PROXY_CACHE_ENTRY_INFO; +pub const KERB_S4U2PROXY_CRED_FLAG_NEGATIVE: ::ULONG = 0x1; +STRUCT!{struct KERB_S4U2PROXY_CRED { + UserName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + Flags: ::ULONG, + LastStatus: ::NTSTATUS, + Expiry: ::LARGE_INTEGER, + CountOfEntries: ::ULONG, + Entries: PKERB_S4U2PROXY_CACHE_ENTRY_INFO, +}} +pub type PKERB_S4U2PROXY_CRED = *mut KERB_S4U2PROXY_CRED; +STRUCT!{struct KERB_QUERY_S4U2PROXY_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + LogonId: ::LUID, +}} +pub type PKERB_QUERY_S4U2PROXY_CACHE_REQUEST = *mut KERB_QUERY_S4U2PROXY_CACHE_REQUEST; +STRUCT!{struct KERB_QUERY_S4U2PROXY_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfCreds: ::ULONG, + Creds: PKERB_S4U2PROXY_CRED, +}} +pub type PKERB_QUERY_S4U2PROXY_CACHE_RESPONSE = *mut KERB_QUERY_S4U2PROXY_CACHE_RESPONSE; +STRUCT!{struct KERB_CHANGEPASSWORD_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + DomainName: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + OldPassword: ::UNICODE_STRING, + NewPassword: ::UNICODE_STRING, + Impersonating: ::BOOLEAN, +}} +pub type PKERB_CHANGEPASSWORD_REQUEST = *mut KERB_CHANGEPASSWORD_REQUEST; +STRUCT!{struct KERB_SETPASSWORD_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + CredentialsHandle: ::SecHandle, + Flags: ::ULONG, + DomainName: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, +}} +pub type PKERB_SETPASSWORD_REQUEST = *mut KERB_SETPASSWORD_REQUEST; +STRUCT!{struct KERB_SETPASSWORD_EX_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + CredentialsHandle: ::SecHandle, + Flags: ::ULONG, + AccountRealm: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ClientName: ::UNICODE_STRING, + Impersonating: ::BOOLEAN, + KdcAddress: ::UNICODE_STRING, + KdcAddressType: ::ULONG, +}} +pub type PKERB_SETPASSWORD_EX_REQUEST = *mut KERB_SETPASSWORD_EX_REQUEST; +pub const DS_UNKNOWN_ADDRESS_TYPE: ::ULONG = 0; +pub const KERB_SETPASS_USE_LOGONID: ::ULONG = 1; +pub const KERB_SETPASS_USE_CREDHANDLE: ::ULONG = 2; +STRUCT!{struct KERB_DECRYPT_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + Flags: ::ULONG, + CryptoType: ::LONG, + KeyUsage: ::LONG, + Key: KERB_CRYPTO_KEY, + EncryptedDataSize: ::ULONG, + InitialVectorSize: ::ULONG, + InitialVector: ::PUCHAR, + EncryptedData: ::PUCHAR, +}} +pub type PKERB_DECRYPT_REQUEST = *mut KERB_DECRYPT_REQUEST; +pub const KERB_DECRYPT_FLAG_DEFAULT_KEY: ::ULONG = 0x00000001; +STRUCT!{struct KERB_DECRYPT_RESPONSE { + DecryptedData: [::UCHAR; ::ANYSIZE_ARRAY], +}} +pub type PKERB_DECRYPT_RESPONSE = *mut KERB_DECRYPT_RESPONSE; +STRUCT!{struct KERB_ADD_BINDING_CACHE_ENTRY_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + RealmName: ::UNICODE_STRING, + KdcAddress: ::UNICODE_STRING, + AddressType: ::ULONG, +}} +pub type PKERB_ADD_BINDING_CACHE_ENTRY_REQUEST = *mut KERB_ADD_BINDING_CACHE_ENTRY_REQUEST; +STRUCT!{struct KERB_REFRESH_SCCRED_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CredentialBlob: ::UNICODE_STRING, + LogonId: ::LUID, + Flags: ::ULONG, +}} +pub type PKERB_REFRESH_SCCRED_REQUEST = *mut KERB_REFRESH_SCCRED_REQUEST; +pub const KERB_REFRESH_SCCRED_RELEASE: ::ULONG = 0x0; +pub const KERB_REFRESH_SCCRED_GETTGT: ::ULONG = 0x1; +STRUCT!{struct KERB_ADD_CREDENTIALS_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + UserName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, + LogonId: ::LUID, + Flags: ::ULONG, +}} +pub type PKERB_ADD_CREDENTIALS_REQUEST = *mut KERB_ADD_CREDENTIALS_REQUEST; +pub const KERB_REQUEST_ADD_CREDENTIAL: ::ULONG = 1; +pub const KERB_REQUEST_REPLACE_CREDENTIAL: ::ULONG = 2; +pub const KERB_REQUEST_REMOVE_CREDENTIAL: ::ULONG = 4; +STRUCT!{struct KERB_ADD_CREDENTIALS_REQUEST_EX { + Credentials: KERB_ADD_CREDENTIALS_REQUEST, + PrincipalNameCount: ::ULONG, + PrincipalNames: [::UNICODE_STRING; ::ANYSIZE_ARRAY], +}} +pub type PKERB_ADD_CREDENTIALS_REQUEST_EX = *mut KERB_ADD_CREDENTIALS_REQUEST_EX; +STRUCT!{struct KERB_TRANSFER_CRED_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + OriginLogonId: ::LUID, + DestinationLogonId: ::LUID, + Flags: ::ULONG, +}} +pub type PKERB_TRANSFER_CRED_REQUEST = *mut KERB_TRANSFER_CRED_REQUEST; +pub const KERB_TRANSFER_CRED_WITH_TICKETS: ::ULONG = 0x1; +pub const KERB_TRANSFER_CRED_CLEANUP_CREDENTIALS: ::ULONG = 0x2; +STRUCT!{struct KERB_CLEANUP_MACHINE_PKINIT_CREDS_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, +}} +pub type PKERB_CLEANUP_MACHINE_PKINIT_CREDS_REQUEST = + *mut KERB_CLEANUP_MACHINE_PKINIT_CREDS_REQUEST; +STRUCT!{struct KERB_BINDING_CACHE_ENTRY_DATA { + DiscoveryTime: ::ULONG64, + RealmName: ::UNICODE_STRING, + KdcAddress: ::UNICODE_STRING, + AddressType: ::ULONG, + Flags: ::ULONG, + DcFlags: ::ULONG, + CacheFlags: ::ULONG, + KdcName: ::UNICODE_STRING, +}} +pub type PKERB_BINDING_CACHE_ENTRY_DATA = *mut KERB_BINDING_CACHE_ENTRY_DATA; +STRUCT!{struct KERB_QUERY_BINDING_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfEntries: ::ULONG, + Entries: PKERB_BINDING_CACHE_ENTRY_DATA, +}} +pub type PKERB_QUERY_BINDING_CACHE_RESPONSE = *mut KERB_QUERY_BINDING_CACHE_RESPONSE; +STRUCT!{struct KERB_ADD_BINDING_CACHE_ENTRY_EX_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + RealmName: ::UNICODE_STRING, + KdcAddress: ::UNICODE_STRING, + AddressType: ::ULONG, + DcFlags: ::ULONG, +}} +pub type PKERB_ADD_BINDING_CACHE_ENTRY_EX_REQUEST = *mut KERB_ADD_BINDING_CACHE_ENTRY_EX_REQUEST; +STRUCT!{struct KERB_QUERY_BINDING_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, +}} +pub type PKERB_QUERY_BINDING_CACHE_REQUEST = *mut KERB_QUERY_BINDING_CACHE_REQUEST; +STRUCT!{struct KERB_PURGE_BINDING_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, +}} +pub type PKERB_PURGE_BINDING_CACHE_REQUEST = *mut KERB_PURGE_BINDING_CACHE_REQUEST; +STRUCT!{struct KERB_QUERY_DOMAIN_EXTENDED_POLICIES_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + DomainName: ::UNICODE_STRING, +}} +pub type PKERB_QUERY_DOMAIN_EXTENDED_POLICIES_REQUEST = + *mut KERB_QUERY_DOMAIN_EXTENDED_POLICIES_REQUEST; +STRUCT!{struct KERB_QUERY_DOMAIN_EXTENDED_POLICIES_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + ExtendedPolicies: ::ULONG, + DsFlags: ::ULONG, +}} +pub type PKERB_QUERY_DOMAIN_EXTENDED_POLICIES_RESPONSE = + *mut KERB_QUERY_DOMAIN_EXTENDED_POLICIES_RESPONSE; +ENUM!{enum KERB_CERTIFICATE_INFO_TYPE { + CertHashInfo = 1, +}} +pub type PKERB_CERTIFICATE_INFO_TYPE = *mut KERB_CERTIFICATE_INFO_TYPE; +STRUCT!{struct KERB_CERTIFICATE_HASHINFO { + StoreNameLength: ::USHORT, + HashLength: ::USHORT, +}} +pub type PKERB_CERTIFICATE_HASHINFO = *mut KERB_CERTIFICATE_HASHINFO; +STRUCT!{struct KERB_CERTIFICATE_INFO { + CertInfoSize: ::ULONG, + InfoType: ::ULONG, +}} +pub type PKERB_CERTIFICATE_INFO = *mut KERB_CERTIFICATE_INFO; +STRUCT!{struct POLICY_AUDIT_SID_ARRAY { + UsersCount: ::ULONG, + UserSidArray: *mut ::PSID, +}} +pub type PPOLICY_AUDIT_SID_ARRAY = *mut POLICY_AUDIT_SID_ARRAY; +STRUCT!{struct AUDIT_POLICY_INFORMATION { + AuditSubCategoryGuid: ::GUID, + AuditingInformation: ::ULONG, + AuditCategoryGuid: ::GUID, +}} +pub type PAUDIT_POLICY_INFORMATION = *mut AUDIT_POLICY_INFORMATION; +pub type LPAUDIT_POLICY_INFORMATION = PAUDIT_POLICY_INFORMATION; +pub type PCAUDIT_POLICY_INFORMATION = *const AUDIT_POLICY_INFORMATION; +pub const AUDIT_SET_SYSTEM_POLICY: ::ULONG = 0x0001; +pub const AUDIT_QUERY_SYSTEM_POLICY: ::ULONG = 0x0002; +pub const AUDIT_SET_USER_POLICY: ::ULONG = 0x0004; +pub const AUDIT_QUERY_USER_POLICY: ::ULONG = 0x0008; +pub const AUDIT_ENUMERATE_USERS: ::ULONG = 0x0010; +pub const AUDIT_SET_MISC_POLICY: ::ULONG = 0x0020; +pub const AUDIT_QUERY_MISC_POLICY: ::ULONG = 0x0040; +pub const AUDIT_GENERIC_ALL: ::ULONG = ::STANDARD_RIGHTS_REQUIRED | AUDIT_SET_SYSTEM_POLICY + | AUDIT_QUERY_SYSTEM_POLICY | AUDIT_SET_USER_POLICY | AUDIT_QUERY_USER_POLICY + | AUDIT_ENUMERATE_USERS | AUDIT_SET_MISC_POLICY | AUDIT_QUERY_MISC_POLICY; +pub const AUDIT_GENERIC_READ: ::ULONG = ::STANDARD_RIGHTS_READ | AUDIT_QUERY_SYSTEM_POLICY + | AUDIT_QUERY_USER_POLICY | AUDIT_ENUMERATE_USERS | AUDIT_QUERY_MISC_POLICY; +pub const AUDIT_GENERIC_WRITE: ::ULONG = ::STANDARD_RIGHTS_WRITE | AUDIT_SET_USER_POLICY + | AUDIT_SET_MISC_POLICY | AUDIT_SET_SYSTEM_POLICY; +pub const AUDIT_GENERIC_EXECUTE: ::ULONG = ::STANDARD_RIGHTS_EXECUTE; +STRUCT!{struct PKU2U_CERT_BLOB { + CertOffset: ::ULONG, + CertLength: ::USHORT, +}} +pub type PPKU2U_CERT_BLOB = *mut PKU2U_CERT_BLOB; +pub const PKU2U_CREDUI_CONTEXT_VERSION: ::ULONG64 = 0x4154414454524543; +STRUCT!{struct PKU2U_CREDUI_CONTEXT { + Version: ::ULONG64, + cbHeaderLength: ::USHORT, + cbStructureLength: ::ULONG, + CertArrayCount: ::USHORT, + CertArrayOffset: ::ULONG, +}} +pub type PPKU2U_CREDUI_CONTEXT = *mut PKU2U_CREDUI_CONTEXT; +ENUM!{enum PKU2U_LOGON_SUBMIT_TYPE { + Pku2uCertificateS4ULogon = 14, +}} +pub type PPKU2U_LOGON_SUBMIT_TYPE = *mut PKU2U_LOGON_SUBMIT_TYPE; +STRUCT!{struct PKU2U_CERTIFICATE_S4U_LOGON { + MessageType: PKU2U_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + UserPrincipalName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + CertificateLength: ::ULONG, + Certificate: ::PUCHAR, +}} +pub type PPKU2U_CERTIFICATE_S4U_LOGON = *mut PKU2U_CERTIFICATE_S4U_LOGON; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ntstatus.rs b/bash-5.1/vendor/winapi-0.2.8/src/ntstatus.rs new file mode 100644 index 0000000..4662235 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ntstatus.rs @@ -0,0 +1,2474 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Constant definitions for the NTSTATUS values. +pub const STATUS_WAIT_0: ::NTSTATUS = 0x00000000; +pub const FACILITY_VSM: ::NTSTATUS = 0x45; +pub const FACILITY_VOLSNAP: ::NTSTATUS = 0x50; +pub const FACILITY_VOLMGR: ::NTSTATUS = 0x38; +pub const FACILITY_VIRTUALIZATION: ::NTSTATUS = 0x37; +pub const FACILITY_VIDEO: ::NTSTATUS = 0x1B; +pub const FACILITY_USB_ERROR_CODE: ::NTSTATUS = 0x10; +pub const FACILITY_TRANSACTION: ::NTSTATUS = 0x19; +pub const FACILITY_TPM: ::NTSTATUS = 0x29; +pub const FACILITY_TERMINAL_SERVER: ::NTSTATUS = 0xA; +pub const FACILITY_SXS_ERROR_CODE: ::NTSTATUS = 0x15; +pub const FACILITY_NTSSPI: ::NTSTATUS = 0x9; +pub const FACILITY_SPACES: ::NTSTATUS = 0xE7; +pub const FACILITY_SMB: ::NTSTATUS = 0x5D; +pub const FACILITY_SYSTEM_INTEGRITY: ::NTSTATUS = 0xE9; +pub const FACILITY_SHARED_VHDX: ::NTSTATUS = 0x5C; +pub const FACILITY_SECUREBOOT: ::NTSTATUS = 0x43; +pub const FACILITY_SECURITY_CORE: ::NTSTATUS = 0xE8; +pub const FACILITY_SDBUS: ::NTSTATUS = 0x51; +pub const FACILITY_RTPM: ::NTSTATUS = 0x2A; +pub const FACILITY_RPC_STUBS: ::NTSTATUS = 0x3; +pub const FACILITY_RPC_RUNTIME: ::NTSTATUS = 0x2; +pub const FACILITY_RESUME_KEY_FILTER: ::NTSTATUS = 0x40; +pub const FACILITY_RDBSS: ::NTSTATUS = 0x41; +pub const FACILITY_NTWIN32: ::NTSTATUS = 0x7; +pub const FACILITY_WIN32K_NTUSER: ::NTSTATUS = 0x3E; +pub const FACILITY_WIN32K_NTGDI: ::NTSTATUS = 0x3F; +pub const FACILITY_NDIS_ERROR_CODE: ::NTSTATUS = 0x23; +pub const FACILTIY_MUI_ERROR_CODE: ::NTSTATUS = 0xB; +pub const FACILITY_MONITOR: ::NTSTATUS = 0x1D; +pub const FACILITY_MAXIMUM_VALUE: ::NTSTATUS = 0xEB; +pub const FACILITY_LICENSING: ::NTSTATUS = 0xEA; +pub const FACILITY_IPSEC: ::NTSTATUS = 0x36; +pub const FACILITY_IO_ERROR_CODE: ::NTSTATUS = 0x4; +pub const FACILITY_INTERIX: ::NTSTATUS = 0x99; +pub const FACILITY_HYPERVISOR: ::NTSTATUS = 0x35; +pub const FACILITY_HID_ERROR_CODE: ::NTSTATUS = 0x11; +pub const FACILITY_GRAPHICS_KERNEL: ::NTSTATUS = 0x1E; +pub const FACILITY_FWP_ERROR_CODE: ::NTSTATUS = 0x22; +pub const FACILITY_FVE_ERROR_CODE: ::NTSTATUS = 0x21; +pub const FACILITY_FIREWIRE_ERROR_CODE: ::NTSTATUS = 0x12; +pub const FACILITY_FILTER_MANAGER: ::NTSTATUS = 0x1C; +pub const FACILITY_DRIVER_FRAMEWORK: ::NTSTATUS = 0x20; +pub const FACILITY_DEBUGGER: ::NTSTATUS = 0x1; +pub const FACILITY_COMMONLOG: ::NTSTATUS = 0x1A; +pub const FACILITY_CODCLASS_ERROR_CODE: ::NTSTATUS = 0x6; +pub const FACILITY_CLUSTER_ERROR_CODE: ::NTSTATUS = 0x13; +pub const FACILITY_NTCERT: ::NTSTATUS = 0x8; +pub const FACILITY_BTH_ATT: ::NTSTATUS = 0x42; +pub const FACILITY_BCD_ERROR_CODE: ::NTSTATUS = 0x39; +pub const FACILITY_AUDIO_KERNEL: ::NTSTATUS = 0x44; +pub const FACILITY_ACPI_ERROR_CODE: ::NTSTATUS = 0x14; +pub const STATUS_SEVERITY_WARNING: ::NTSTATUS = 0x2; +pub const STATUS_SEVERITY_SUCCESS: ::NTSTATUS = 0x0; +pub const STATUS_SEVERITY_INFORMATIONAL: ::NTSTATUS = 0x1; +pub const STATUS_SEVERITY_ERROR: ::NTSTATUS = 0x3; +pub const STATUS_SUCCESS: ::NTSTATUS = 0x00000000; +pub const STATUS_WAIT_1: ::NTSTATUS = 0x00000001; +pub const STATUS_WAIT_2: ::NTSTATUS = 0x00000002; +pub const STATUS_WAIT_3: ::NTSTATUS = 0x00000003; +pub const STATUS_WAIT_63: ::NTSTATUS = 0x0000003F; +pub const STATUS_ABANDONED: ::NTSTATUS = 0x00000080; +pub const STATUS_ABANDONED_WAIT_0: ::NTSTATUS = 0x00000080; +pub const STATUS_ABANDONED_WAIT_63: ::NTSTATUS = 0x000000BF; +pub const STATUS_USER_APC: ::NTSTATUS = 0x000000C0; +pub const STATUS_KERNEL_APC: ::NTSTATUS = 0x00000100; +pub const STATUS_ALERTED: ::NTSTATUS = 0x00000101; +pub const STATUS_TIMEOUT: ::NTSTATUS = 0x00000102; +pub const STATUS_PENDING: ::NTSTATUS = 0x00000103; +pub const STATUS_REPARSE: ::NTSTATUS = 0x00000104; +pub const STATUS_MORE_ENTRIES: ::NTSTATUS = 0x00000105; +pub const STATUS_NOT_ALL_ASSIGNED: ::NTSTATUS = 0x00000106; +pub const STATUS_SOME_NOT_MAPPED: ::NTSTATUS = 0x00000107; +pub const STATUS_OPLOCK_BREAK_IN_PROGRESS: ::NTSTATUS = 0x00000108; +pub const STATUS_VOLUME_MOUNTED: ::NTSTATUS = 0x00000109; +pub const STATUS_RXACT_COMMITTED: ::NTSTATUS = 0x0000010A; +pub const STATUS_NOTIFY_CLEANUP: ::NTSTATUS = 0x0000010B; +pub const STATUS_NOTIFY_ENUM_DIR: ::NTSTATUS = 0x0000010C; +pub const STATUS_NO_QUOTAS_FOR_ACCOUNT: ::NTSTATUS = 0x0000010D; +pub const STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED: ::NTSTATUS = 0x0000010E; +pub const STATUS_PAGE_FAULT_TRANSITION: ::NTSTATUS = 0x00000110; +pub const STATUS_PAGE_FAULT_DEMAND_ZERO: ::NTSTATUS = 0x00000111; +pub const STATUS_PAGE_FAULT_COPY_ON_WRITE: ::NTSTATUS = 0x00000112; +pub const STATUS_PAGE_FAULT_GUARD_PAGE: ::NTSTATUS = 0x00000113; +pub const STATUS_PAGE_FAULT_PAGING_FILE: ::NTSTATUS = 0x00000114; +pub const STATUS_CACHE_PAGE_LOCKED: ::NTSTATUS = 0x00000115; +pub const STATUS_CRASH_DUMP: ::NTSTATUS = 0x00000116; +pub const STATUS_BUFFER_ALL_ZEROS: ::NTSTATUS = 0x00000117; +pub const STATUS_REPARSE_OBJECT: ::NTSTATUS = 0x00000118; +pub const STATUS_RESOURCE_REQUIREMENTS_CHANGED: ::NTSTATUS = 0x00000119; +pub const STATUS_TRANSLATION_COMPLETE: ::NTSTATUS = 0x00000120; +pub const STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY: ::NTSTATUS = 0x00000121; +pub const STATUS_NOTHING_TO_TERMINATE: ::NTSTATUS = 0x00000122; +pub const STATUS_PROCESS_NOT_IN_JOB: ::NTSTATUS = 0x00000123; +pub const STATUS_PROCESS_IN_JOB: ::NTSTATUS = 0x00000124; +pub const STATUS_VOLSNAP_HIBERNATE_READY: ::NTSTATUS = 0x00000125; +pub const STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY: ::NTSTATUS = 0x00000126; +pub const STATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED: ::NTSTATUS = 0x00000127; +pub const STATUS_INTERRUPT_STILL_CONNECTED: ::NTSTATUS = 0x00000128; +pub const STATUS_PROCESS_CLONED: ::NTSTATUS = 0x00000129; +pub const STATUS_FILE_LOCKED_WITH_ONLY_READERS: ::NTSTATUS = 0x0000012A; +pub const STATUS_FILE_LOCKED_WITH_WRITERS: ::NTSTATUS = 0x0000012B; +pub const STATUS_VALID_IMAGE_HASH: ::NTSTATUS = 0x0000012C; +pub const STATUS_VALID_CATALOG_HASH: ::NTSTATUS = 0x0000012D; +pub const STATUS_VALID_STRONG_CODE_HASH: ::NTSTATUS = 0x0000012E; +pub const STATUS_RESOURCEMANAGER_READ_ONLY: ::NTSTATUS = 0x00000202; +pub const STATUS_RING_PREVIOUSLY_EMPTY: ::NTSTATUS = 0x00000210; +pub const STATUS_RING_PREVIOUSLY_FULL: ::NTSTATUS = 0x00000211; +pub const STATUS_RING_PREVIOUSLY_ABOVE_QUOTA: ::NTSTATUS = 0x00000212; +pub const STATUS_RING_NEWLY_EMPTY: ::NTSTATUS = 0x00000213; +pub const STATUS_RING_SIGNAL_OPPOSITE_ENDPOINT: ::NTSTATUS = 0x00000214; +pub const STATUS_OPLOCK_SWITCHED_TO_NEW_HANDLE: ::NTSTATUS = 0x00000215; +pub const STATUS_OPLOCK_HANDLE_CLOSED: ::NTSTATUS = 0x00000216; +pub const STATUS_WAIT_FOR_OPLOCK: ::NTSTATUS = 0x00000367; +pub const DBG_EXCEPTION_HANDLED: ::NTSTATUS = 0x00010001; +pub const DBG_CONTINUE: ::NTSTATUS = 0x00010002; +pub const STATUS_FLT_IO_COMPLETE: ::NTSTATUS = 0x001C0001; +pub const STATUS_OBJECT_NAME_EXISTS: ::NTSTATUS = 0x40000000; +pub const STATUS_THREAD_WAS_SUSPENDED: ::NTSTATUS = 0x40000001; +pub const STATUS_WORKING_SET_LIMIT_RANGE: ::NTSTATUS = 0x40000002; +pub const STATUS_IMAGE_NOT_AT_BASE: ::NTSTATUS = 0x40000003; +pub const STATUS_RXACT_STATE_CREATED: ::NTSTATUS = 0x40000004; +pub const STATUS_SEGMENT_NOTIFICATION: ::NTSTATUS = 0x40000005; +pub const STATUS_LOCAL_USER_SESSION_KEY: ::NTSTATUS = 0x40000006; +pub const STATUS_BAD_CURRENT_DIRECTORY: ::NTSTATUS = 0x40000007; +pub const STATUS_SERIAL_MORE_WRITES: ::NTSTATUS = 0x40000008; +pub const STATUS_REGISTRY_RECOVERED: ::NTSTATUS = 0x40000009; +pub const STATUS_FT_READ_RECOVERY_FROM_BACKUP: ::NTSTATUS = 0x4000000A; +pub const STATUS_FT_WRITE_RECOVERY: ::NTSTATUS = 0x4000000B; +pub const STATUS_SERIAL_COUNTER_TIMEOUT: ::NTSTATUS = 0x4000000C; +pub const STATUS_NULL_LM_PASSWORD: ::NTSTATUS = 0x4000000D; +pub const STATUS_IMAGE_MACHINE_TYPE_MISMATCH: ::NTSTATUS = 0x4000000E; +pub const STATUS_RECEIVE_PARTIAL: ::NTSTATUS = 0x4000000F; +pub const STATUS_RECEIVE_EXPEDITED: ::NTSTATUS = 0x40000010; +pub const STATUS_RECEIVE_PARTIAL_EXPEDITED: ::NTSTATUS = 0x40000011; +pub const STATUS_EVENT_DONE: ::NTSTATUS = 0x40000012; +pub const STATUS_EVENT_PENDING: ::NTSTATUS = 0x40000013; +pub const STATUS_CHECKING_FILE_SYSTEM: ::NTSTATUS = 0x40000014; +pub const STATUS_FATAL_APP_EXIT: ::NTSTATUS = 0x40000015; +pub const STATUS_PREDEFINED_HANDLE: ::NTSTATUS = 0x40000016; +pub const STATUS_WAS_UNLOCKED: ::NTSTATUS = 0x40000017; +pub const STATUS_SERVICE_NOTIFICATION: ::NTSTATUS = 0x40000018; +pub const STATUS_WAS_LOCKED: ::NTSTATUS = 0x40000019; +pub const STATUS_LOG_HARD_ERROR: ::NTSTATUS = 0x4000001A; +pub const STATUS_ALREADY_WIN32: ::NTSTATUS = 0x4000001B; +pub const STATUS_WX86_UNSIMULATE: ::NTSTATUS = 0x4000001C; +pub const STATUS_WX86_CONTINUE: ::NTSTATUS = 0x4000001D; +pub const STATUS_WX86_SINGLE_STEP: ::NTSTATUS = 0x4000001E; +pub const STATUS_WX86_BREAKPOINT: ::NTSTATUS = 0x4000001F; +pub const STATUS_WX86_EXCEPTION_CONTINUE: ::NTSTATUS = 0x40000020; +pub const STATUS_WX86_EXCEPTION_LASTCHANCE: ::NTSTATUS = 0x40000021; +pub const STATUS_WX86_EXCEPTION_CHAIN: ::NTSTATUS = 0x40000022; +pub const STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE: ::NTSTATUS = 0x40000023; +pub const STATUS_NO_YIELD_PERFORMED: ::NTSTATUS = 0x40000024; +pub const STATUS_TIMER_RESUME_IGNORED: ::NTSTATUS = 0x40000025; +pub const STATUS_ARBITRATION_UNHANDLED: ::NTSTATUS = 0x40000026; +pub const STATUS_CARDBUS_NOT_SUPPORTED: ::NTSTATUS = 0x40000027; +pub const STATUS_WX86_CREATEWX86TIB: ::NTSTATUS = 0x40000028; +pub const STATUS_MP_PROCESSOR_MISMATCH: ::NTSTATUS = 0x40000029; +pub const STATUS_HIBERNATED: ::NTSTATUS = 0x4000002A; +pub const STATUS_RESUME_HIBERNATION: ::NTSTATUS = 0x4000002B; +pub const STATUS_FIRMWARE_UPDATED: ::NTSTATUS = 0x4000002C; +pub const STATUS_DRIVERS_LEAKING_LOCKED_PAGES: ::NTSTATUS = 0x4000002D; +pub const STATUS_MESSAGE_RETRIEVED: ::NTSTATUS = 0x4000002E; +pub const STATUS_SYSTEM_POWERSTATE_TRANSITION: ::NTSTATUS = 0x4000002F; +pub const STATUS_ALPC_CHECK_COMPLETION_LIST: ::NTSTATUS = 0x40000030; +pub const STATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION: ::NTSTATUS = 0x40000031; +pub const STATUS_ACCESS_AUDIT_BY_POLICY: ::NTSTATUS = 0x40000032; +pub const STATUS_ABANDON_HIBERFILE: ::NTSTATUS = 0x40000033; +pub const STATUS_BIZRULES_NOT_ENABLED: ::NTSTATUS = 0x40000034; +pub const STATUS_FT_READ_FROM_COPY: ::NTSTATUS = 0x40000035; +pub const STATUS_IMAGE_AT_DIFFERENT_BASE: ::NTSTATUS = 0x40000036; +pub const DBG_REPLY_LATER: ::NTSTATUS = 0x40010001; +pub const DBG_UNABLE_TO_PROVIDE_HANDLE: ::NTSTATUS = 0x40010002; +pub const DBG_TERMINATE_THREAD: ::NTSTATUS = 0x40010003; +pub const DBG_TERMINATE_PROCESS: ::NTSTATUS = 0x40010004; +pub const DBG_CONTROL_C: ::NTSTATUS = 0x40010005; +pub const DBG_PRINTEXCEPTION_C: ::NTSTATUS = 0x40010006; +pub const DBG_RIPEXCEPTION: ::NTSTATUS = 0x40010007; +pub const DBG_CONTROL_BREAK: ::NTSTATUS = 0x40010008; +pub const DBG_COMMAND_EXCEPTION: ::NTSTATUS = 0x40010009; +pub const DBG_PRINTEXCEPTION_WIDE_C: ::NTSTATUS = 0x4001000A; +pub const STATUS_HEURISTIC_DAMAGE_POSSIBLE: ::NTSTATUS = 0x40190001; +pub const STATUS_GUARD_PAGE_VIOLATION: ::NTSTATUS = 0x80000001u32 as i32; +pub const STATUS_DATATYPE_MISALIGNMENT: ::NTSTATUS = 0x80000002u32 as i32; +pub const STATUS_BREAKPOINT: ::NTSTATUS = 0x80000003u32 as i32; +pub const STATUS_SINGLE_STEP: ::NTSTATUS = 0x80000004u32 as i32; +pub const STATUS_BUFFER_OVERFLOW: ::NTSTATUS = 0x80000005u32 as i32; +pub const STATUS_NO_MORE_FILES: ::NTSTATUS = 0x80000006u32 as i32; +pub const STATUS_WAKE_SYSTEM_DEBUGGER: ::NTSTATUS = 0x80000007u32 as i32; +pub const STATUS_HANDLES_CLOSED: ::NTSTATUS = 0x8000000Au32 as i32; +pub const STATUS_NO_INHERITANCE: ::NTSTATUS = 0x8000000Bu32 as i32; +pub const STATUS_GUID_SUBSTITUTION_MADE: ::NTSTATUS = 0x8000000Cu32 as i32; +pub const STATUS_PARTIAL_COPY: ::NTSTATUS = 0x8000000Du32 as i32; +pub const STATUS_DEVICE_PAPER_EMPTY: ::NTSTATUS = 0x8000000Eu32 as i32; +pub const STATUS_DEVICE_POWERED_OFF: ::NTSTATUS = 0x8000000Fu32 as i32; +pub const STATUS_DEVICE_OFF_LINE: ::NTSTATUS = 0x80000010u32 as i32; +pub const STATUS_DEVICE_BUSY: ::NTSTATUS = 0x80000011u32 as i32; +pub const STATUS_NO_MORE_EAS: ::NTSTATUS = 0x80000012u32 as i32; +pub const STATUS_INVALID_EA_NAME: ::NTSTATUS = 0x80000013u32 as i32; +pub const STATUS_EA_LIST_INCONSISTENT: ::NTSTATUS = 0x80000014u32 as i32; +pub const STATUS_INVALID_EA_FLAG: ::NTSTATUS = 0x80000015u32 as i32; +pub const STATUS_VERIFY_REQUIRED: ::NTSTATUS = 0x80000016u32 as i32; +pub const STATUS_EXTRANEOUS_INFORMATION: ::NTSTATUS = 0x80000017u32 as i32; +pub const STATUS_RXACT_COMMIT_NECESSARY: ::NTSTATUS = 0x80000018u32 as i32; +pub const STATUS_NO_MORE_ENTRIES: ::NTSTATUS = 0x8000001Au32 as i32; +pub const STATUS_FILEMARK_DETECTED: ::NTSTATUS = 0x8000001Bu32 as i32; +pub const STATUS_MEDIA_CHANGED: ::NTSTATUS = 0x8000001Cu32 as i32; +pub const STATUS_BUS_RESET: ::NTSTATUS = 0x8000001Du32 as i32; +pub const STATUS_END_OF_MEDIA: ::NTSTATUS = 0x8000001Eu32 as i32; +pub const STATUS_BEGINNING_OF_MEDIA: ::NTSTATUS = 0x8000001Fu32 as i32; +pub const STATUS_MEDIA_CHECK: ::NTSTATUS = 0x80000020u32 as i32; +pub const STATUS_SETMARK_DETECTED: ::NTSTATUS = 0x80000021u32 as i32; +pub const STATUS_NO_DATA_DETECTED: ::NTSTATUS = 0x80000022u32 as i32; +pub const STATUS_REDIRECTOR_HAS_OPEN_HANDLES: ::NTSTATUS = 0x80000023u32 as i32; +pub const STATUS_SERVER_HAS_OPEN_HANDLES: ::NTSTATUS = 0x80000024u32 as i32; +pub const STATUS_ALREADY_DISCONNECTED: ::NTSTATUS = 0x80000025u32 as i32; +pub const STATUS_LONGJUMP: ::NTSTATUS = 0x80000026u32 as i32; +pub const STATUS_CLEANER_CARTRIDGE_INSTALLED: ::NTSTATUS = 0x80000027u32 as i32; +pub const STATUS_PLUGPLAY_QUERY_VETOED: ::NTSTATUS = 0x80000028u32 as i32; +pub const STATUS_UNWIND_CONSOLIDATE: ::NTSTATUS = 0x80000029u32 as i32; +pub const STATUS_REGISTRY_HIVE_RECOVERED: ::NTSTATUS = 0x8000002Au32 as i32; +pub const STATUS_DLL_MIGHT_BE_INSECURE: ::NTSTATUS = 0x8000002Bu32 as i32; +pub const STATUS_DLL_MIGHT_BE_INCOMPATIBLE: ::NTSTATUS = 0x8000002Cu32 as i32; +pub const STATUS_STOPPED_ON_SYMLINK: ::NTSTATUS = 0x8000002Du32 as i32; +pub const STATUS_CANNOT_GRANT_REQUESTED_OPLOCK: ::NTSTATUS = 0x8000002Eu32 as i32; +pub const STATUS_NO_ACE_CONDITION: ::NTSTATUS = 0x8000002Fu32 as i32; +pub const STATUS_DEVICE_SUPPORT_IN_PROGRESS: ::NTSTATUS = 0x80000030u32 as i32; +pub const STATUS_DEVICE_POWER_CYCLE_REQUIRED: ::NTSTATUS = 0x80000031u32 as i32; +pub const DBG_EXCEPTION_NOT_HANDLED: ::NTSTATUS = 0x80010001u32 as i32; +pub const STATUS_CLUSTER_NODE_ALREADY_UP: ::NTSTATUS = 0x80130001u32 as i32; +pub const STATUS_CLUSTER_NODE_ALREADY_DOWN: ::NTSTATUS = 0x80130002u32 as i32; +pub const STATUS_CLUSTER_NETWORK_ALREADY_ONLINE: ::NTSTATUS = 0x80130003u32 as i32; +pub const STATUS_CLUSTER_NETWORK_ALREADY_OFFLINE: ::NTSTATUS = 0x80130004u32 as i32; +pub const STATUS_CLUSTER_NODE_ALREADY_MEMBER: ::NTSTATUS = 0x80130005u32 as i32; +pub const STATUS_FLT_BUFFER_TOO_SMALL: ::NTSTATUS = 0x801C0001u32 as i32; +pub const STATUS_FVE_PARTIAL_METADATA: ::NTSTATUS = 0x80210001u32 as i32; +pub const STATUS_FVE_TRANSIENT_STATE: ::NTSTATUS = 0x80210002u32 as i32; +pub const STATUS_UNSUCCESSFUL: ::NTSTATUS = 0xC0000001u32 as i32; +pub const STATUS_NOT_IMPLEMENTED: ::NTSTATUS = 0xC0000002u32 as i32; +pub const STATUS_INVALID_INFO_CLASS: ::NTSTATUS = 0xC0000003u32 as i32; +pub const STATUS_INFO_LENGTH_MISMATCH: ::NTSTATUS = 0xC0000004u32 as i32; +pub const STATUS_ACCESS_VIOLATION: ::NTSTATUS = 0xC0000005u32 as i32; +pub const STATUS_IN_PAGE_ERROR: ::NTSTATUS = 0xC0000006u32 as i32; +pub const STATUS_PAGEFILE_QUOTA: ::NTSTATUS = 0xC0000007u32 as i32; +pub const STATUS_INVALID_HANDLE: ::NTSTATUS = 0xC0000008u32 as i32; +pub const STATUS_BAD_INITIAL_STACK: ::NTSTATUS = 0xC0000009u32 as i32; +pub const STATUS_BAD_INITIAL_PC: ::NTSTATUS = 0xC000000Au32 as i32; +pub const STATUS_INVALID_CID: ::NTSTATUS = 0xC000000Bu32 as i32; +pub const STATUS_TIMER_NOT_CANCELED: ::NTSTATUS = 0xC000000Cu32 as i32; +pub const STATUS_INVALID_PARAMETER: ::NTSTATUS = 0xC000000Du32 as i32; +pub const STATUS_NO_SUCH_DEVICE: ::NTSTATUS = 0xC000000Eu32 as i32; +pub const STATUS_NO_SUCH_FILE: ::NTSTATUS = 0xC000000Fu32 as i32; +pub const STATUS_INVALID_DEVICE_REQUEST: ::NTSTATUS = 0xC0000010u32 as i32; +pub const STATUS_END_OF_FILE: ::NTSTATUS = 0xC0000011u32 as i32; +pub const STATUS_WRONG_VOLUME: ::NTSTATUS = 0xC0000012u32 as i32; +pub const STATUS_NO_MEDIA_IN_DEVICE: ::NTSTATUS = 0xC0000013u32 as i32; +pub const STATUS_UNRECOGNIZED_MEDIA: ::NTSTATUS = 0xC0000014u32 as i32; +pub const STATUS_NONEXISTENT_SECTOR: ::NTSTATUS = 0xC0000015u32 as i32; +pub const STATUS_MORE_PROCESSING_REQUIRED: ::NTSTATUS = 0xC0000016u32 as i32; +pub const STATUS_NO_MEMORY: ::NTSTATUS = 0xC0000017u32 as i32; +pub const STATUS_CONFLICTING_ADDRESSES: ::NTSTATUS = 0xC0000018u32 as i32; +pub const STATUS_NOT_MAPPED_VIEW: ::NTSTATUS = 0xC0000019u32 as i32; +pub const STATUS_UNABLE_TO_FREE_VM: ::NTSTATUS = 0xC000001Au32 as i32; +pub const STATUS_UNABLE_TO_DELETE_SECTION: ::NTSTATUS = 0xC000001Bu32 as i32; +pub const STATUS_INVALID_SYSTEM_SERVICE: ::NTSTATUS = 0xC000001Cu32 as i32; +pub const STATUS_ILLEGAL_INSTRUCTION: ::NTSTATUS = 0xC000001Du32 as i32; +pub const STATUS_INVALID_LOCK_SEQUENCE: ::NTSTATUS = 0xC000001Eu32 as i32; +pub const STATUS_INVALID_VIEW_SIZE: ::NTSTATUS = 0xC000001Fu32 as i32; +pub const STATUS_INVALID_FILE_FOR_SECTION: ::NTSTATUS = 0xC0000020u32 as i32; +pub const STATUS_ALREADY_COMMITTED: ::NTSTATUS = 0xC0000021u32 as i32; +pub const STATUS_ACCESS_DENIED: ::NTSTATUS = 0xC0000022u32 as i32; +pub const STATUS_BUFFER_TOO_SMALL: ::NTSTATUS = 0xC0000023u32 as i32; +pub const STATUS_OBJECT_TYPE_MISMATCH: ::NTSTATUS = 0xC0000024u32 as i32; +pub const STATUS_NONCONTINUABLE_EXCEPTION: ::NTSTATUS = 0xC0000025u32 as i32; +pub const STATUS_INVALID_DISPOSITION: ::NTSTATUS = 0xC0000026u32 as i32; +pub const STATUS_UNWIND: ::NTSTATUS = 0xC0000027u32 as i32; +pub const STATUS_BAD_STACK: ::NTSTATUS = 0xC0000028u32 as i32; +pub const STATUS_INVALID_UNWIND_TARGET: ::NTSTATUS = 0xC0000029u32 as i32; +pub const STATUS_NOT_LOCKED: ::NTSTATUS = 0xC000002Au32 as i32; +pub const STATUS_PARITY_ERROR: ::NTSTATUS = 0xC000002Bu32 as i32; +pub const STATUS_UNABLE_TO_DECOMMIT_VM: ::NTSTATUS = 0xC000002Cu32 as i32; +pub const STATUS_NOT_COMMITTED: ::NTSTATUS = 0xC000002Du32 as i32; +pub const STATUS_INVALID_PORT_ATTRIBUTES: ::NTSTATUS = 0xC000002Eu32 as i32; +pub const STATUS_PORT_MESSAGE_TOO_LONG: ::NTSTATUS = 0xC000002Fu32 as i32; +pub const STATUS_INVALID_PARAMETER_MIX: ::NTSTATUS = 0xC0000030u32 as i32; +pub const STATUS_INVALID_QUOTA_LOWER: ::NTSTATUS = 0xC0000031u32 as i32; +pub const STATUS_DISK_CORRUPT_ERROR: ::NTSTATUS = 0xC0000032u32 as i32; +pub const STATUS_OBJECT_NAME_INVALID: ::NTSTATUS = 0xC0000033u32 as i32; +pub const STATUS_OBJECT_NAME_NOT_FOUND: ::NTSTATUS = 0xC0000034u32 as i32; +pub const STATUS_OBJECT_NAME_COLLISION: ::NTSTATUS = 0xC0000035u32 as i32; +pub const STATUS_PORT_DO_NOT_DISTURB: ::NTSTATUS = 0xC0000036u32 as i32; +pub const STATUS_PORT_DISCONNECTED: ::NTSTATUS = 0xC0000037u32 as i32; +pub const STATUS_DEVICE_ALREADY_ATTACHED: ::NTSTATUS = 0xC0000038u32 as i32; +pub const STATUS_OBJECT_PATH_INVALID: ::NTSTATUS = 0xC0000039u32 as i32; +pub const STATUS_OBJECT_PATH_NOT_FOUND: ::NTSTATUS = 0xC000003Au32 as i32; +pub const STATUS_OBJECT_PATH_SYNTAX_BAD: ::NTSTATUS = 0xC000003Bu32 as i32; +pub const STATUS_DATA_OVERRUN: ::NTSTATUS = 0xC000003Cu32 as i32; +pub const STATUS_DATA_LATE_ERROR: ::NTSTATUS = 0xC000003Du32 as i32; +pub const STATUS_DATA_ERROR: ::NTSTATUS = 0xC000003Eu32 as i32; +pub const STATUS_CRC_ERROR: ::NTSTATUS = 0xC000003Fu32 as i32; +pub const STATUS_SECTION_TOO_BIG: ::NTSTATUS = 0xC0000040u32 as i32; +pub const STATUS_PORT_CONNECTION_REFUSED: ::NTSTATUS = 0xC0000041u32 as i32; +pub const STATUS_INVALID_PORT_HANDLE: ::NTSTATUS = 0xC0000042u32 as i32; +pub const STATUS_SHARING_VIOLATION: ::NTSTATUS = 0xC0000043u32 as i32; +pub const STATUS_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000044u32 as i32; +pub const STATUS_INVALID_PAGE_PROTECTION: ::NTSTATUS = 0xC0000045u32 as i32; +pub const STATUS_MUTANT_NOT_OWNED: ::NTSTATUS = 0xC0000046u32 as i32; +pub const STATUS_SEMAPHORE_LIMIT_EXCEEDED: ::NTSTATUS = 0xC0000047u32 as i32; +pub const STATUS_PORT_ALREADY_SET: ::NTSTATUS = 0xC0000048u32 as i32; +pub const STATUS_SECTION_NOT_IMAGE: ::NTSTATUS = 0xC0000049u32 as i32; +pub const STATUS_SUSPEND_COUNT_EXCEEDED: ::NTSTATUS = 0xC000004Au32 as i32; +pub const STATUS_THREAD_IS_TERMINATING: ::NTSTATUS = 0xC000004Bu32 as i32; +pub const STATUS_BAD_WORKING_SET_LIMIT: ::NTSTATUS = 0xC000004Cu32 as i32; +pub const STATUS_INCOMPATIBLE_FILE_MAP: ::NTSTATUS = 0xC000004Du32 as i32; +pub const STATUS_SECTION_PROTECTION: ::NTSTATUS = 0xC000004Eu32 as i32; +pub const STATUS_EAS_NOT_SUPPORTED: ::NTSTATUS = 0xC000004Fu32 as i32; +pub const STATUS_EA_TOO_LARGE: ::NTSTATUS = 0xC0000050u32 as i32; +pub const STATUS_NONEXISTENT_EA_ENTRY: ::NTSTATUS = 0xC0000051u32 as i32; +pub const STATUS_NO_EAS_ON_FILE: ::NTSTATUS = 0xC0000052u32 as i32; +pub const STATUS_EA_CORRUPT_ERROR: ::NTSTATUS = 0xC0000053u32 as i32; +pub const STATUS_FILE_LOCK_CONFLICT: ::NTSTATUS = 0xC0000054u32 as i32; +pub const STATUS_LOCK_NOT_GRANTED: ::NTSTATUS = 0xC0000055u32 as i32; +pub const STATUS_DELETE_PENDING: ::NTSTATUS = 0xC0000056u32 as i32; +pub const STATUS_CTL_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC0000057u32 as i32; +pub const STATUS_UNKNOWN_REVISION: ::NTSTATUS = 0xC0000058u32 as i32; +pub const STATUS_REVISION_MISMATCH: ::NTSTATUS = 0xC0000059u32 as i32; +pub const STATUS_INVALID_OWNER: ::NTSTATUS = 0xC000005Au32 as i32; +pub const STATUS_INVALID_PRIMARY_GROUP: ::NTSTATUS = 0xC000005Bu32 as i32; +pub const STATUS_NO_IMPERSONATION_TOKEN: ::NTSTATUS = 0xC000005Cu32 as i32; +pub const STATUS_CANT_DISABLE_MANDATORY: ::NTSTATUS = 0xC000005Du32 as i32; +pub const STATUS_NO_LOGON_SERVERS: ::NTSTATUS = 0xC000005Eu32 as i32; +pub const STATUS_NO_SUCH_LOGON_SESSION: ::NTSTATUS = 0xC000005Fu32 as i32; +pub const STATUS_NO_SUCH_PRIVILEGE: ::NTSTATUS = 0xC0000060u32 as i32; +pub const STATUS_PRIVILEGE_NOT_HELD: ::NTSTATUS = 0xC0000061u32 as i32; +pub const STATUS_INVALID_ACCOUNT_NAME: ::NTSTATUS = 0xC0000062u32 as i32; +pub const STATUS_USER_EXISTS: ::NTSTATUS = 0xC0000063u32 as i32; +pub const STATUS_NO_SUCH_USER: ::NTSTATUS = 0xC0000064u32 as i32; +pub const STATUS_GROUP_EXISTS: ::NTSTATUS = 0xC0000065u32 as i32; +pub const STATUS_NO_SUCH_GROUP: ::NTSTATUS = 0xC0000066u32 as i32; +pub const STATUS_MEMBER_IN_GROUP: ::NTSTATUS = 0xC0000067u32 as i32; +pub const STATUS_MEMBER_NOT_IN_GROUP: ::NTSTATUS = 0xC0000068u32 as i32; +pub const STATUS_LAST_ADMIN: ::NTSTATUS = 0xC0000069u32 as i32; +pub const STATUS_WRONG_PASSWORD: ::NTSTATUS = 0xC000006Au32 as i32; +pub const STATUS_ILL_FORMED_PASSWORD: ::NTSTATUS = 0xC000006Bu32 as i32; +pub const STATUS_PASSWORD_RESTRICTION: ::NTSTATUS = 0xC000006Cu32 as i32; +pub const STATUS_LOGON_FAILURE: ::NTSTATUS = 0xC000006Du32 as i32; +pub const STATUS_ACCOUNT_RESTRICTION: ::NTSTATUS = 0xC000006Eu32 as i32; +pub const STATUS_INVALID_LOGON_HOURS: ::NTSTATUS = 0xC000006Fu32 as i32; +pub const STATUS_INVALID_WORKSTATION: ::NTSTATUS = 0xC0000070u32 as i32; +pub const STATUS_PASSWORD_EXPIRED: ::NTSTATUS = 0xC0000071u32 as i32; +pub const STATUS_ACCOUNT_DISABLED: ::NTSTATUS = 0xC0000072u32 as i32; +pub const STATUS_NONE_MAPPED: ::NTSTATUS = 0xC0000073u32 as i32; +pub const STATUS_TOO_MANY_LUIDS_REQUESTED: ::NTSTATUS = 0xC0000074u32 as i32; +pub const STATUS_LUIDS_EXHAUSTED: ::NTSTATUS = 0xC0000075u32 as i32; +pub const STATUS_INVALID_SUB_AUTHORITY: ::NTSTATUS = 0xC0000076u32 as i32; +pub const STATUS_INVALID_ACL: ::NTSTATUS = 0xC0000077u32 as i32; +pub const STATUS_INVALID_SID: ::NTSTATUS = 0xC0000078u32 as i32; +pub const STATUS_INVALID_SECURITY_DESCR: ::NTSTATUS = 0xC0000079u32 as i32; +pub const STATUS_PROCEDURE_NOT_FOUND: ::NTSTATUS = 0xC000007Au32 as i32; +pub const STATUS_INVALID_IMAGE_FORMAT: ::NTSTATUS = 0xC000007Bu32 as i32; +pub const STATUS_NO_TOKEN: ::NTSTATUS = 0xC000007Cu32 as i32; +pub const STATUS_BAD_INHERITANCE_ACL: ::NTSTATUS = 0xC000007Du32 as i32; +pub const STATUS_RANGE_NOT_LOCKED: ::NTSTATUS = 0xC000007Eu32 as i32; +pub const STATUS_DISK_FULL: ::NTSTATUS = 0xC000007Fu32 as i32; +pub const STATUS_SERVER_DISABLED: ::NTSTATUS = 0xC0000080u32 as i32; +pub const STATUS_SERVER_NOT_DISABLED: ::NTSTATUS = 0xC0000081u32 as i32; +pub const STATUS_TOO_MANY_GUIDS_REQUESTED: ::NTSTATUS = 0xC0000082u32 as i32; +pub const STATUS_GUIDS_EXHAUSTED: ::NTSTATUS = 0xC0000083u32 as i32; +pub const STATUS_INVALID_ID_AUTHORITY: ::NTSTATUS = 0xC0000084u32 as i32; +pub const STATUS_AGENTS_EXHAUSTED: ::NTSTATUS = 0xC0000085u32 as i32; +pub const STATUS_INVALID_VOLUME_LABEL: ::NTSTATUS = 0xC0000086u32 as i32; +pub const STATUS_SECTION_NOT_EXTENDED: ::NTSTATUS = 0xC0000087u32 as i32; +pub const STATUS_NOT_MAPPED_DATA: ::NTSTATUS = 0xC0000088u32 as i32; +pub const STATUS_RESOURCE_DATA_NOT_FOUND: ::NTSTATUS = 0xC0000089u32 as i32; +pub const STATUS_RESOURCE_TYPE_NOT_FOUND: ::NTSTATUS = 0xC000008Au32 as i32; +pub const STATUS_RESOURCE_NAME_NOT_FOUND: ::NTSTATUS = 0xC000008Bu32 as i32; +pub const STATUS_ARRAY_BOUNDS_EXCEEDED: ::NTSTATUS = 0xC000008Cu32 as i32; +pub const STATUS_FLOAT_DENORMAL_OPERAND: ::NTSTATUS = 0xC000008Du32 as i32; +pub const STATUS_FLOAT_DIVIDE_BY_ZERO: ::NTSTATUS = 0xC000008Eu32 as i32; +pub const STATUS_FLOAT_INEXACT_RESULT: ::NTSTATUS = 0xC000008Fu32 as i32; +pub const STATUS_FLOAT_INVALID_OPERATION: ::NTSTATUS = 0xC0000090u32 as i32; +pub const STATUS_FLOAT_OVERFLOW: ::NTSTATUS = 0xC0000091u32 as i32; +pub const STATUS_FLOAT_STACK_CHECK: ::NTSTATUS = 0xC0000092u32 as i32; +pub const STATUS_FLOAT_UNDERFLOW: ::NTSTATUS = 0xC0000093u32 as i32; +pub const STATUS_INTEGER_DIVIDE_BY_ZERO: ::NTSTATUS = 0xC0000094u32 as i32; +pub const STATUS_INTEGER_OVERFLOW: ::NTSTATUS = 0xC0000095u32 as i32; +pub const STATUS_PRIVILEGED_INSTRUCTION: ::NTSTATUS = 0xC0000096u32 as i32; +pub const STATUS_TOO_MANY_PAGING_FILES: ::NTSTATUS = 0xC0000097u32 as i32; +pub const STATUS_FILE_INVALID: ::NTSTATUS = 0xC0000098u32 as i32; +pub const STATUS_ALLOTTED_SPACE_EXCEEDED: ::NTSTATUS = 0xC0000099u32 as i32; +pub const STATUS_INSUFFICIENT_RESOURCES: ::NTSTATUS = 0xC000009Au32 as i32; +pub const STATUS_DFS_EXIT_PATH_FOUND: ::NTSTATUS = 0xC000009Bu32 as i32; +pub const STATUS_DEVICE_DATA_ERROR: ::NTSTATUS = 0xC000009Cu32 as i32; +pub const STATUS_DEVICE_NOT_CONNECTED: ::NTSTATUS = 0xC000009Du32 as i32; +pub const STATUS_DEVICE_POWER_FAILURE: ::NTSTATUS = 0xC000009Eu32 as i32; +pub const STATUS_FREE_VM_NOT_AT_BASE: ::NTSTATUS = 0xC000009Fu32 as i32; +pub const STATUS_MEMORY_NOT_ALLOCATED: ::NTSTATUS = 0xC00000A0u32 as i32; +pub const STATUS_WORKING_SET_QUOTA: ::NTSTATUS = 0xC00000A1u32 as i32; +pub const STATUS_MEDIA_WRITE_PROTECTED: ::NTSTATUS = 0xC00000A2u32 as i32; +pub const STATUS_DEVICE_NOT_READY: ::NTSTATUS = 0xC00000A3u32 as i32; +pub const STATUS_INVALID_GROUP_ATTRIBUTES: ::NTSTATUS = 0xC00000A4u32 as i32; +pub const STATUS_BAD_IMPERSONATION_LEVEL: ::NTSTATUS = 0xC00000A5u32 as i32; +pub const STATUS_CANT_OPEN_ANONYMOUS: ::NTSTATUS = 0xC00000A6u32 as i32; +pub const STATUS_BAD_VALIDATION_CLASS: ::NTSTATUS = 0xC00000A7u32 as i32; +pub const STATUS_BAD_TOKEN_TYPE: ::NTSTATUS = 0xC00000A8u32 as i32; +pub const STATUS_BAD_MASTER_BOOT_RECORD: ::NTSTATUS = 0xC00000A9u32 as i32; +pub const STATUS_INSTRUCTION_MISALIGNMENT: ::NTSTATUS = 0xC00000AAu32 as i32; +pub const STATUS_INSTANCE_NOT_AVAILABLE: ::NTSTATUS = 0xC00000ABu32 as i32; +pub const STATUS_PIPE_NOT_AVAILABLE: ::NTSTATUS = 0xC00000ACu32 as i32; +pub const STATUS_INVALID_PIPE_STATE: ::NTSTATUS = 0xC00000ADu32 as i32; +pub const STATUS_PIPE_BUSY: ::NTSTATUS = 0xC00000AEu32 as i32; +pub const STATUS_ILLEGAL_FUNCTION: ::NTSTATUS = 0xC00000AFu32 as i32; +pub const STATUS_PIPE_DISCONNECTED: ::NTSTATUS = 0xC00000B0u32 as i32; +pub const STATUS_PIPE_CLOSING: ::NTSTATUS = 0xC00000B1u32 as i32; +pub const STATUS_PIPE_CONNECTED: ::NTSTATUS = 0xC00000B2u32 as i32; +pub const STATUS_PIPE_LISTENING: ::NTSTATUS = 0xC00000B3u32 as i32; +pub const STATUS_INVALID_READ_MODE: ::NTSTATUS = 0xC00000B4u32 as i32; +pub const STATUS_IO_TIMEOUT: ::NTSTATUS = 0xC00000B5u32 as i32; +pub const STATUS_FILE_FORCED_CLOSED: ::NTSTATUS = 0xC00000B6u32 as i32; +pub const STATUS_PROFILING_NOT_STARTED: ::NTSTATUS = 0xC00000B7u32 as i32; +pub const STATUS_PROFILING_NOT_STOPPED: ::NTSTATUS = 0xC00000B8u32 as i32; +pub const STATUS_COULD_NOT_INTERPRET: ::NTSTATUS = 0xC00000B9u32 as i32; +pub const STATUS_FILE_IS_A_DIRECTORY: ::NTSTATUS = 0xC00000BAu32 as i32; +pub const STATUS_NOT_SUPPORTED: ::NTSTATUS = 0xC00000BBu32 as i32; +pub const STATUS_REMOTE_NOT_LISTENING: ::NTSTATUS = 0xC00000BCu32 as i32; +pub const STATUS_DUPLICATE_NAME: ::NTSTATUS = 0xC00000BDu32 as i32; +pub const STATUS_BAD_NETWORK_PATH: ::NTSTATUS = 0xC00000BEu32 as i32; +pub const STATUS_NETWORK_BUSY: ::NTSTATUS = 0xC00000BFu32 as i32; +pub const STATUS_DEVICE_DOES_NOT_EXIST: ::NTSTATUS = 0xC00000C0u32 as i32; +pub const STATUS_TOO_MANY_COMMANDS: ::NTSTATUS = 0xC00000C1u32 as i32; +pub const STATUS_ADAPTER_HARDWARE_ERROR: ::NTSTATUS = 0xC00000C2u32 as i32; +pub const STATUS_INVALID_NETWORK_RESPONSE: ::NTSTATUS = 0xC00000C3u32 as i32; +pub const STATUS_UNEXPECTED_NETWORK_ERROR: ::NTSTATUS = 0xC00000C4u32 as i32; +pub const STATUS_BAD_REMOTE_ADAPTER: ::NTSTATUS = 0xC00000C5u32 as i32; +pub const STATUS_PRINT_QUEUE_FULL: ::NTSTATUS = 0xC00000C6u32 as i32; +pub const STATUS_NO_SPOOL_SPACE: ::NTSTATUS = 0xC00000C7u32 as i32; +pub const STATUS_PRINT_CANCELLED: ::NTSTATUS = 0xC00000C8u32 as i32; +pub const STATUS_NETWORK_NAME_DELETED: ::NTSTATUS = 0xC00000C9u32 as i32; +pub const STATUS_NETWORK_ACCESS_DENIED: ::NTSTATUS = 0xC00000CAu32 as i32; +pub const STATUS_BAD_DEVICE_TYPE: ::NTSTATUS = 0xC00000CBu32 as i32; +pub const STATUS_BAD_NETWORK_NAME: ::NTSTATUS = 0xC00000CCu32 as i32; +pub const STATUS_TOO_MANY_NAMES: ::NTSTATUS = 0xC00000CDu32 as i32; +pub const STATUS_TOO_MANY_SESSIONS: ::NTSTATUS = 0xC00000CEu32 as i32; +pub const STATUS_SHARING_PAUSED: ::NTSTATUS = 0xC00000CFu32 as i32; +pub const STATUS_REQUEST_NOT_ACCEPTED: ::NTSTATUS = 0xC00000D0u32 as i32; +pub const STATUS_REDIRECTOR_PAUSED: ::NTSTATUS = 0xC00000D1u32 as i32; +pub const STATUS_NET_WRITE_FAULT: ::NTSTATUS = 0xC00000D2u32 as i32; +pub const STATUS_PROFILING_AT_LIMIT: ::NTSTATUS = 0xC00000D3u32 as i32; +pub const STATUS_NOT_SAME_DEVICE: ::NTSTATUS = 0xC00000D4u32 as i32; +pub const STATUS_FILE_RENAMED: ::NTSTATUS = 0xC00000D5u32 as i32; +pub const STATUS_VIRTUAL_CIRCUIT_CLOSED: ::NTSTATUS = 0xC00000D6u32 as i32; +pub const STATUS_NO_SECURITY_ON_OBJECT: ::NTSTATUS = 0xC00000D7u32 as i32; +pub const STATUS_CANT_WAIT: ::NTSTATUS = 0xC00000D8u32 as i32; +pub const STATUS_PIPE_EMPTY: ::NTSTATUS = 0xC00000D9u32 as i32; +pub const STATUS_CANT_ACCESS_DOMAIN_INFO: ::NTSTATUS = 0xC00000DAu32 as i32; +pub const STATUS_CANT_TERMINATE_SELF: ::NTSTATUS = 0xC00000DBu32 as i32; +pub const STATUS_INVALID_SERVER_STATE: ::NTSTATUS = 0xC00000DCu32 as i32; +pub const STATUS_INVALID_DOMAIN_STATE: ::NTSTATUS = 0xC00000DDu32 as i32; +pub const STATUS_INVALID_DOMAIN_ROLE: ::NTSTATUS = 0xC00000DEu32 as i32; +pub const STATUS_NO_SUCH_DOMAIN: ::NTSTATUS = 0xC00000DFu32 as i32; +pub const STATUS_DOMAIN_EXISTS: ::NTSTATUS = 0xC00000E0u32 as i32; +pub const STATUS_DOMAIN_LIMIT_EXCEEDED: ::NTSTATUS = 0xC00000E1u32 as i32; +pub const STATUS_OPLOCK_NOT_GRANTED: ::NTSTATUS = 0xC00000E2u32 as i32; +pub const STATUS_INVALID_OPLOCK_PROTOCOL: ::NTSTATUS = 0xC00000E3u32 as i32; +pub const STATUS_INTERNAL_DB_CORRUPTION: ::NTSTATUS = 0xC00000E4u32 as i32; +pub const STATUS_INTERNAL_ERROR: ::NTSTATUS = 0xC00000E5u32 as i32; +pub const STATUS_GENERIC_NOT_MAPPED: ::NTSTATUS = 0xC00000E6u32 as i32; +pub const STATUS_BAD_DESCRIPTOR_FORMAT: ::NTSTATUS = 0xC00000E7u32 as i32; +pub const STATUS_INVALID_USER_BUFFER: ::NTSTATUS = 0xC00000E8u32 as i32; +pub const STATUS_UNEXPECTED_IO_ERROR: ::NTSTATUS = 0xC00000E9u32 as i32; +pub const STATUS_UNEXPECTED_MM_CREATE_ERR: ::NTSTATUS = 0xC00000EAu32 as i32; +pub const STATUS_UNEXPECTED_MM_MAP_ERROR: ::NTSTATUS = 0xC00000EBu32 as i32; +pub const STATUS_UNEXPECTED_MM_EXTEND_ERR: ::NTSTATUS = 0xC00000ECu32 as i32; +pub const STATUS_NOT_LOGON_PROCESS: ::NTSTATUS = 0xC00000EDu32 as i32; +pub const STATUS_LOGON_SESSION_EXISTS: ::NTSTATUS = 0xC00000EEu32 as i32; +pub const STATUS_INVALID_PARAMETER_1: ::NTSTATUS = 0xC00000EFu32 as i32; +pub const STATUS_INVALID_PARAMETER_2: ::NTSTATUS = 0xC00000F0u32 as i32; +pub const STATUS_INVALID_PARAMETER_3: ::NTSTATUS = 0xC00000F1u32 as i32; +pub const STATUS_INVALID_PARAMETER_4: ::NTSTATUS = 0xC00000F2u32 as i32; +pub const STATUS_INVALID_PARAMETER_5: ::NTSTATUS = 0xC00000F3u32 as i32; +pub const STATUS_INVALID_PARAMETER_6: ::NTSTATUS = 0xC00000F4u32 as i32; +pub const STATUS_INVALID_PARAMETER_7: ::NTSTATUS = 0xC00000F5u32 as i32; +pub const STATUS_INVALID_PARAMETER_8: ::NTSTATUS = 0xC00000F6u32 as i32; +pub const STATUS_INVALID_PARAMETER_9: ::NTSTATUS = 0xC00000F7u32 as i32; +pub const STATUS_INVALID_PARAMETER_10: ::NTSTATUS = 0xC00000F8u32 as i32; +pub const STATUS_INVALID_PARAMETER_11: ::NTSTATUS = 0xC00000F9u32 as i32; +pub const STATUS_INVALID_PARAMETER_12: ::NTSTATUS = 0xC00000FAu32 as i32; +pub const STATUS_REDIRECTOR_NOT_STARTED: ::NTSTATUS = 0xC00000FBu32 as i32; +pub const STATUS_REDIRECTOR_STARTED: ::NTSTATUS = 0xC00000FCu32 as i32; +pub const STATUS_STACK_OVERFLOW: ::NTSTATUS = 0xC00000FDu32 as i32; +pub const STATUS_NO_SUCH_PACKAGE: ::NTSTATUS = 0xC00000FEu32 as i32; +pub const STATUS_BAD_FUNCTION_TABLE: ::NTSTATUS = 0xC00000FFu32 as i32; +pub const STATUS_VARIABLE_NOT_FOUND: ::NTSTATUS = 0xC0000100u32 as i32; +pub const STATUS_DIRECTORY_NOT_EMPTY: ::NTSTATUS = 0xC0000101u32 as i32; +pub const STATUS_FILE_CORRUPT_ERROR: ::NTSTATUS = 0xC0000102u32 as i32; +pub const STATUS_NOT_A_DIRECTORY: ::NTSTATUS = 0xC0000103u32 as i32; +pub const STATUS_BAD_LOGON_SESSION_STATE: ::NTSTATUS = 0xC0000104u32 as i32; +pub const STATUS_LOGON_SESSION_COLLISION: ::NTSTATUS = 0xC0000105u32 as i32; +pub const STATUS_NAME_TOO_LONG: ::NTSTATUS = 0xC0000106u32 as i32; +pub const STATUS_FILES_OPEN: ::NTSTATUS = 0xC0000107u32 as i32; +pub const STATUS_CONNECTION_IN_USE: ::NTSTATUS = 0xC0000108u32 as i32; +pub const STATUS_MESSAGE_NOT_FOUND: ::NTSTATUS = 0xC0000109u32 as i32; +pub const STATUS_PROCESS_IS_TERMINATING: ::NTSTATUS = 0xC000010Au32 as i32; +pub const STATUS_INVALID_LOGON_TYPE: ::NTSTATUS = 0xC000010Bu32 as i32; +pub const STATUS_NO_GUID_TRANSLATION: ::NTSTATUS = 0xC000010Cu32 as i32; +pub const STATUS_CANNOT_IMPERSONATE: ::NTSTATUS = 0xC000010Du32 as i32; +pub const STATUS_IMAGE_ALREADY_LOADED: ::NTSTATUS = 0xC000010Eu32 as i32; +pub const STATUS_ABIOS_NOT_PRESENT: ::NTSTATUS = 0xC000010Fu32 as i32; +pub const STATUS_ABIOS_LID_NOT_EXIST: ::NTSTATUS = 0xC0000110u32 as i32; +pub const STATUS_ABIOS_LID_ALREADY_OWNED: ::NTSTATUS = 0xC0000111u32 as i32; +pub const STATUS_ABIOS_NOT_LID_OWNER: ::NTSTATUS = 0xC0000112u32 as i32; +pub const STATUS_ABIOS_INVALID_COMMAND: ::NTSTATUS = 0xC0000113u32 as i32; +pub const STATUS_ABIOS_INVALID_LID: ::NTSTATUS = 0xC0000114u32 as i32; +pub const STATUS_ABIOS_SELECTOR_NOT_AVAILABLE: ::NTSTATUS = 0xC0000115u32 as i32; +pub const STATUS_ABIOS_INVALID_SELECTOR: ::NTSTATUS = 0xC0000116u32 as i32; +pub const STATUS_NO_LDT: ::NTSTATUS = 0xC0000117u32 as i32; +pub const STATUS_INVALID_LDT_SIZE: ::NTSTATUS = 0xC0000118u32 as i32; +pub const STATUS_INVALID_LDT_OFFSET: ::NTSTATUS = 0xC0000119u32 as i32; +pub const STATUS_INVALID_LDT_DESCRIPTOR: ::NTSTATUS = 0xC000011Au32 as i32; +pub const STATUS_INVALID_IMAGE_NE_FORMAT: ::NTSTATUS = 0xC000011Bu32 as i32; +pub const STATUS_RXACT_INVALID_STATE: ::NTSTATUS = 0xC000011Cu32 as i32; +pub const STATUS_RXACT_COMMIT_FAILURE: ::NTSTATUS = 0xC000011Du32 as i32; +pub const STATUS_MAPPED_FILE_SIZE_ZERO: ::NTSTATUS = 0xC000011Eu32 as i32; +pub const STATUS_TOO_MANY_OPENED_FILES: ::NTSTATUS = 0xC000011Fu32 as i32; +pub const STATUS_CANCELLED: ::NTSTATUS = 0xC0000120u32 as i32; +pub const STATUS_CANNOT_DELETE: ::NTSTATUS = 0xC0000121u32 as i32; +pub const STATUS_INVALID_COMPUTER_NAME: ::NTSTATUS = 0xC0000122u32 as i32; +pub const STATUS_FILE_DELETED: ::NTSTATUS = 0xC0000123u32 as i32; +pub const STATUS_SPECIAL_ACCOUNT: ::NTSTATUS = 0xC0000124u32 as i32; +pub const STATUS_SPECIAL_GROUP: ::NTSTATUS = 0xC0000125u32 as i32; +pub const STATUS_SPECIAL_USER: ::NTSTATUS = 0xC0000126u32 as i32; +pub const STATUS_MEMBERS_PRIMARY_GROUP: ::NTSTATUS = 0xC0000127u32 as i32; +pub const STATUS_FILE_CLOSED: ::NTSTATUS = 0xC0000128u32 as i32; +pub const STATUS_TOO_MANY_THREADS: ::NTSTATUS = 0xC0000129u32 as i32; +pub const STATUS_THREAD_NOT_IN_PROCESS: ::NTSTATUS = 0xC000012Au32 as i32; +pub const STATUS_TOKEN_ALREADY_IN_USE: ::NTSTATUS = 0xC000012Bu32 as i32; +pub const STATUS_PAGEFILE_QUOTA_EXCEEDED: ::NTSTATUS = 0xC000012Cu32 as i32; +pub const STATUS_COMMITMENT_LIMIT: ::NTSTATUS = 0xC000012Du32 as i32; +pub const STATUS_INVALID_IMAGE_LE_FORMAT: ::NTSTATUS = 0xC000012Eu32 as i32; +pub const STATUS_INVALID_IMAGE_NOT_MZ: ::NTSTATUS = 0xC000012Fu32 as i32; +pub const STATUS_INVALID_IMAGE_PROTECT: ::NTSTATUS = 0xC0000130u32 as i32; +pub const STATUS_INVALID_IMAGE_WIN_16: ::NTSTATUS = 0xC0000131u32 as i32; +pub const STATUS_LOGON_SERVER_CONFLICT: ::NTSTATUS = 0xC0000132u32 as i32; +pub const STATUS_TIME_DIFFERENCE_AT_DC: ::NTSTATUS = 0xC0000133u32 as i32; +pub const STATUS_SYNCHRONIZATION_REQUIRED: ::NTSTATUS = 0xC0000134u32 as i32; +pub const STATUS_DLL_NOT_FOUND: ::NTSTATUS = 0xC0000135u32 as i32; +pub const STATUS_OPEN_FAILED: ::NTSTATUS = 0xC0000136u32 as i32; +pub const STATUS_IO_PRIVILEGE_FAILED: ::NTSTATUS = 0xC0000137u32 as i32; +pub const STATUS_ORDINAL_NOT_FOUND: ::NTSTATUS = 0xC0000138u32 as i32; +pub const STATUS_ENTRYPOINT_NOT_FOUND: ::NTSTATUS = 0xC0000139u32 as i32; +pub const STATUS_CONTROL_C_EXIT: ::NTSTATUS = 0xC000013Au32 as i32; +pub const STATUS_LOCAL_DISCONNECT: ::NTSTATUS = 0xC000013Bu32 as i32; +pub const STATUS_REMOTE_DISCONNECT: ::NTSTATUS = 0xC000013Cu32 as i32; +pub const STATUS_REMOTE_RESOURCES: ::NTSTATUS = 0xC000013Du32 as i32; +pub const STATUS_LINK_FAILED: ::NTSTATUS = 0xC000013Eu32 as i32; +pub const STATUS_LINK_TIMEOUT: ::NTSTATUS = 0xC000013Fu32 as i32; +pub const STATUS_INVALID_CONNECTION: ::NTSTATUS = 0xC0000140u32 as i32; +pub const STATUS_INVALID_ADDRESS: ::NTSTATUS = 0xC0000141u32 as i32; +pub const STATUS_DLL_INIT_FAILED: ::NTSTATUS = 0xC0000142u32 as i32; +pub const STATUS_MISSING_SYSTEMFILE: ::NTSTATUS = 0xC0000143u32 as i32; +pub const STATUS_UNHANDLED_EXCEPTION: ::NTSTATUS = 0xC0000144u32 as i32; +pub const STATUS_APP_INIT_FAILURE: ::NTSTATUS = 0xC0000145u32 as i32; +pub const STATUS_PAGEFILE_CREATE_FAILED: ::NTSTATUS = 0xC0000146u32 as i32; +pub const STATUS_NO_PAGEFILE: ::NTSTATUS = 0xC0000147u32 as i32; +pub const STATUS_INVALID_LEVEL: ::NTSTATUS = 0xC0000148u32 as i32; +pub const STATUS_WRONG_PASSWORD_CORE: ::NTSTATUS = 0xC0000149u32 as i32; +pub const STATUS_ILLEGAL_FLOAT_CONTEXT: ::NTSTATUS = 0xC000014Au32 as i32; +pub const STATUS_PIPE_BROKEN: ::NTSTATUS = 0xC000014Bu32 as i32; +pub const STATUS_REGISTRY_CORRUPT: ::NTSTATUS = 0xC000014Cu32 as i32; +pub const STATUS_REGISTRY_IO_FAILED: ::NTSTATUS = 0xC000014Du32 as i32; +pub const STATUS_NO_EVENT_PAIR: ::NTSTATUS = 0xC000014Eu32 as i32; +pub const STATUS_UNRECOGNIZED_VOLUME: ::NTSTATUS = 0xC000014Fu32 as i32; +pub const STATUS_SERIAL_NO_DEVICE_INITED: ::NTSTATUS = 0xC0000150u32 as i32; +pub const STATUS_NO_SUCH_ALIAS: ::NTSTATUS = 0xC0000151u32 as i32; +pub const STATUS_MEMBER_NOT_IN_ALIAS: ::NTSTATUS = 0xC0000152u32 as i32; +pub const STATUS_MEMBER_IN_ALIAS: ::NTSTATUS = 0xC0000153u32 as i32; +pub const STATUS_ALIAS_EXISTS: ::NTSTATUS = 0xC0000154u32 as i32; +pub const STATUS_LOGON_NOT_GRANTED: ::NTSTATUS = 0xC0000155u32 as i32; +pub const STATUS_TOO_MANY_SECRETS: ::NTSTATUS = 0xC0000156u32 as i32; +pub const STATUS_SECRET_TOO_LONG: ::NTSTATUS = 0xC0000157u32 as i32; +pub const STATUS_INTERNAL_DB_ERROR: ::NTSTATUS = 0xC0000158u32 as i32; +pub const STATUS_FULLSCREEN_MODE: ::NTSTATUS = 0xC0000159u32 as i32; +pub const STATUS_TOO_MANY_CONTEXT_IDS: ::NTSTATUS = 0xC000015Au32 as i32; +pub const STATUS_LOGON_TYPE_NOT_GRANTED: ::NTSTATUS = 0xC000015Bu32 as i32; +pub const STATUS_NOT_REGISTRY_FILE: ::NTSTATUS = 0xC000015Cu32 as i32; +pub const STATUS_NT_CROSS_ENCRYPTION_REQUIRED: ::NTSTATUS = 0xC000015Du32 as i32; +pub const STATUS_DOMAIN_CTRLR_CONFIG_ERROR: ::NTSTATUS = 0xC000015Eu32 as i32; +pub const STATUS_FT_MISSING_MEMBER: ::NTSTATUS = 0xC000015Fu32 as i32; +pub const STATUS_ILL_FORMED_SERVICE_ENTRY: ::NTSTATUS = 0xC0000160u32 as i32; +pub const STATUS_ILLEGAL_CHARACTER: ::NTSTATUS = 0xC0000161u32 as i32; +pub const STATUS_UNMAPPABLE_CHARACTER: ::NTSTATUS = 0xC0000162u32 as i32; +pub const STATUS_UNDEFINED_CHARACTER: ::NTSTATUS = 0xC0000163u32 as i32; +pub const STATUS_FLOPPY_VOLUME: ::NTSTATUS = 0xC0000164u32 as i32; +pub const STATUS_FLOPPY_ID_MARK_NOT_FOUND: ::NTSTATUS = 0xC0000165u32 as i32; +pub const STATUS_FLOPPY_WRONG_CYLINDER: ::NTSTATUS = 0xC0000166u32 as i32; +pub const STATUS_FLOPPY_UNKNOWN_ERROR: ::NTSTATUS = 0xC0000167u32 as i32; +pub const STATUS_FLOPPY_BAD_REGISTERS: ::NTSTATUS = 0xC0000168u32 as i32; +pub const STATUS_DISK_RECALIBRATE_FAILED: ::NTSTATUS = 0xC0000169u32 as i32; +pub const STATUS_DISK_OPERATION_FAILED: ::NTSTATUS = 0xC000016Au32 as i32; +pub const STATUS_DISK_RESET_FAILED: ::NTSTATUS = 0xC000016Bu32 as i32; +pub const STATUS_SHARED_IRQ_BUSY: ::NTSTATUS = 0xC000016Cu32 as i32; +pub const STATUS_FT_ORPHANING: ::NTSTATUS = 0xC000016Du32 as i32; +pub const STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT: ::NTSTATUS = 0xC000016Eu32 as i32; +pub const STATUS_PARTITION_FAILURE: ::NTSTATUS = 0xC0000172u32 as i32; +pub const STATUS_INVALID_BLOCK_LENGTH: ::NTSTATUS = 0xC0000173u32 as i32; +pub const STATUS_DEVICE_NOT_PARTITIONED: ::NTSTATUS = 0xC0000174u32 as i32; +pub const STATUS_UNABLE_TO_LOCK_MEDIA: ::NTSTATUS = 0xC0000175u32 as i32; +pub const STATUS_UNABLE_TO_UNLOAD_MEDIA: ::NTSTATUS = 0xC0000176u32 as i32; +pub const STATUS_EOM_OVERFLOW: ::NTSTATUS = 0xC0000177u32 as i32; +pub const STATUS_NO_MEDIA: ::NTSTATUS = 0xC0000178u32 as i32; +pub const STATUS_NO_SUCH_MEMBER: ::NTSTATUS = 0xC000017Au32 as i32; +pub const STATUS_INVALID_MEMBER: ::NTSTATUS = 0xC000017Bu32 as i32; +pub const STATUS_KEY_DELETED: ::NTSTATUS = 0xC000017Cu32 as i32; +pub const STATUS_NO_LOG_SPACE: ::NTSTATUS = 0xC000017Du32 as i32; +pub const STATUS_TOO_MANY_SIDS: ::NTSTATUS = 0xC000017Eu32 as i32; +pub const STATUS_LM_CROSS_ENCRYPTION_REQUIRED: ::NTSTATUS = 0xC000017Fu32 as i32; +pub const STATUS_KEY_HAS_CHILDREN: ::NTSTATUS = 0xC0000180u32 as i32; +pub const STATUS_CHILD_MUST_BE_VOLATILE: ::NTSTATUS = 0xC0000181u32 as i32; +pub const STATUS_DEVICE_CONFIGURATION_ERROR: ::NTSTATUS = 0xC0000182u32 as i32; +pub const STATUS_DRIVER_INTERNAL_ERROR: ::NTSTATUS = 0xC0000183u32 as i32; +pub const STATUS_INVALID_DEVICE_STATE: ::NTSTATUS = 0xC0000184u32 as i32; +pub const STATUS_IO_DEVICE_ERROR: ::NTSTATUS = 0xC0000185u32 as i32; +pub const STATUS_DEVICE_PROTOCOL_ERROR: ::NTSTATUS = 0xC0000186u32 as i32; +pub const STATUS_BACKUP_CONTROLLER: ::NTSTATUS = 0xC0000187u32 as i32; +pub const STATUS_LOG_FILE_FULL: ::NTSTATUS = 0xC0000188u32 as i32; +pub const STATUS_TOO_LATE: ::NTSTATUS = 0xC0000189u32 as i32; +pub const STATUS_NO_TRUST_LSA_SECRET: ::NTSTATUS = 0xC000018Au32 as i32; +pub const STATUS_NO_TRUST_SAM_ACCOUNT: ::NTSTATUS = 0xC000018Bu32 as i32; +pub const STATUS_TRUSTED_DOMAIN_FAILURE: ::NTSTATUS = 0xC000018Cu32 as i32; +pub const STATUS_TRUSTED_RELATIONSHIP_FAILURE: ::NTSTATUS = 0xC000018Du32 as i32; +pub const STATUS_EVENTLOG_FILE_CORRUPT: ::NTSTATUS = 0xC000018Eu32 as i32; +pub const STATUS_EVENTLOG_CANT_START: ::NTSTATUS = 0xC000018Fu32 as i32; +pub const STATUS_TRUST_FAILURE: ::NTSTATUS = 0xC0000190u32 as i32; +pub const STATUS_MUTANT_LIMIT_EXCEEDED: ::NTSTATUS = 0xC0000191u32 as i32; +pub const STATUS_NETLOGON_NOT_STARTED: ::NTSTATUS = 0xC0000192u32 as i32; +pub const STATUS_ACCOUNT_EXPIRED: ::NTSTATUS = 0xC0000193u32 as i32; +pub const STATUS_POSSIBLE_DEADLOCK: ::NTSTATUS = 0xC0000194u32 as i32; +pub const STATUS_NETWORK_CREDENTIAL_CONFLICT: ::NTSTATUS = 0xC0000195u32 as i32; +pub const STATUS_REMOTE_SESSION_LIMIT: ::NTSTATUS = 0xC0000196u32 as i32; +pub const STATUS_EVENTLOG_FILE_CHANGED: ::NTSTATUS = 0xC0000197u32 as i32; +pub const STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: ::NTSTATUS = 0xC0000198u32 as i32; +pub const STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT: ::NTSTATUS = 0xC0000199u32 as i32; +pub const STATUS_NOLOGON_SERVER_TRUST_ACCOUNT: ::NTSTATUS = 0xC000019Au32 as i32; +pub const STATUS_DOMAIN_TRUST_INCONSISTENT: ::NTSTATUS = 0xC000019Bu32 as i32; +pub const STATUS_FS_DRIVER_REQUIRED: ::NTSTATUS = 0xC000019Cu32 as i32; +pub const STATUS_IMAGE_ALREADY_LOADED_AS_DLL: ::NTSTATUS = 0xC000019Du32 as i32; +pub const STATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING: ::NTSTATUS = 0xC000019Eu32 as i32; +pub const STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME: ::NTSTATUS = 0xC000019Fu32 as i32; +pub const STATUS_SECURITY_STREAM_IS_INCONSISTENT: ::NTSTATUS = 0xC00001A0u32 as i32; +pub const STATUS_INVALID_LOCK_RANGE: ::NTSTATUS = 0xC00001A1u32 as i32; +pub const STATUS_INVALID_ACE_CONDITION: ::NTSTATUS = 0xC00001A2u32 as i32; +pub const STATUS_IMAGE_SUBSYSTEM_NOT_PRESENT: ::NTSTATUS = 0xC00001A3u32 as i32; +pub const STATUS_NOTIFICATION_GUID_ALREADY_DEFINED: ::NTSTATUS = 0xC00001A4u32 as i32; +pub const STATUS_INVALID_EXCEPTION_HANDLER: ::NTSTATUS = 0xC00001A5u32 as i32; +pub const STATUS_DUPLICATE_PRIVILEGES: ::NTSTATUS = 0xC00001A6u32 as i32; +pub const STATUS_NOT_ALLOWED_ON_SYSTEM_FILE: ::NTSTATUS = 0xC00001A7u32 as i32; +pub const STATUS_REPAIR_NEEDED: ::NTSTATUS = 0xC00001A8u32 as i32; +pub const STATUS_QUOTA_NOT_ENABLED: ::NTSTATUS = 0xC00001A9u32 as i32; +pub const STATUS_NO_APPLICATION_PACKAGE: ::NTSTATUS = 0xC00001AAu32 as i32; +pub const STATUS_FILE_METADATA_OPTIMIZATION_IN_PROGRESS: ::NTSTATUS = 0xC00001ABu32 as i32; +pub const STATUS_NOT_SAME_OBJECT: ::NTSTATUS = 0xC00001ACu32 as i32; +pub const STATUS_FATAL_MEMORY_EXHAUSTION: ::NTSTATUS = 0xC00001ADu32 as i32; +pub const STATUS_ERROR_PROCESS_NOT_IN_JOB: ::NTSTATUS = 0xC00001AEu32 as i32; +pub const STATUS_NETWORK_OPEN_RESTRICTION: ::NTSTATUS = 0xC0000201u32 as i32; +pub const STATUS_NO_USER_SESSION_KEY: ::NTSTATUS = 0xC0000202u32 as i32; +pub const STATUS_USER_SESSION_DELETED: ::NTSTATUS = 0xC0000203u32 as i32; +pub const STATUS_RESOURCE_LANG_NOT_FOUND: ::NTSTATUS = 0xC0000204u32 as i32; +pub const STATUS_INSUFF_SERVER_RESOURCES: ::NTSTATUS = 0xC0000205u32 as i32; +pub const STATUS_INVALID_BUFFER_SIZE: ::NTSTATUS = 0xC0000206u32 as i32; +pub const STATUS_INVALID_ADDRESS_COMPONENT: ::NTSTATUS = 0xC0000207u32 as i32; +pub const STATUS_INVALID_ADDRESS_WILDCARD: ::NTSTATUS = 0xC0000208u32 as i32; +pub const STATUS_TOO_MANY_ADDRESSES: ::NTSTATUS = 0xC0000209u32 as i32; +pub const STATUS_ADDRESS_ALREADY_EXISTS: ::NTSTATUS = 0xC000020Au32 as i32; +pub const STATUS_ADDRESS_CLOSED: ::NTSTATUS = 0xC000020Bu32 as i32; +pub const STATUS_CONNECTION_DISCONNECTED: ::NTSTATUS = 0xC000020Cu32 as i32; +pub const STATUS_CONNECTION_RESET: ::NTSTATUS = 0xC000020Du32 as i32; +pub const STATUS_TOO_MANY_NODES: ::NTSTATUS = 0xC000020Eu32 as i32; +pub const STATUS_TRANSACTION_ABORTED: ::NTSTATUS = 0xC000020Fu32 as i32; +pub const STATUS_TRANSACTION_TIMED_OUT: ::NTSTATUS = 0xC0000210u32 as i32; +pub const STATUS_TRANSACTION_NO_RELEASE: ::NTSTATUS = 0xC0000211u32 as i32; +pub const STATUS_TRANSACTION_NO_MATCH: ::NTSTATUS = 0xC0000212u32 as i32; +pub const STATUS_TRANSACTION_RESPONDED: ::NTSTATUS = 0xC0000213u32 as i32; +pub const STATUS_TRANSACTION_INVALID_ID: ::NTSTATUS = 0xC0000214u32 as i32; +pub const STATUS_TRANSACTION_INVALID_TYPE: ::NTSTATUS = 0xC0000215u32 as i32; +pub const STATUS_NOT_SERVER_SESSION: ::NTSTATUS = 0xC0000216u32 as i32; +pub const STATUS_NOT_CLIENT_SESSION: ::NTSTATUS = 0xC0000217u32 as i32; +pub const STATUS_CANNOT_LOAD_REGISTRY_FILE: ::NTSTATUS = 0xC0000218u32 as i32; +pub const STATUS_DEBUG_ATTACH_FAILED: ::NTSTATUS = 0xC0000219u32 as i32; +pub const STATUS_SYSTEM_PROCESS_TERMINATED: ::NTSTATUS = 0xC000021Au32 as i32; +pub const STATUS_DATA_NOT_ACCEPTED: ::NTSTATUS = 0xC000021Bu32 as i32; +pub const STATUS_NO_BROWSER_SERVERS_FOUND: ::NTSTATUS = 0xC000021Cu32 as i32; +pub const STATUS_VDM_HARD_ERROR: ::NTSTATUS = 0xC000021Du32 as i32; +pub const STATUS_DRIVER_CANCEL_TIMEOUT: ::NTSTATUS = 0xC000021Eu32 as i32; +pub const STATUS_REPLY_MESSAGE_MISMATCH: ::NTSTATUS = 0xC000021Fu32 as i32; +pub const STATUS_MAPPED_ALIGNMENT: ::NTSTATUS = 0xC0000220u32 as i32; +pub const STATUS_IMAGE_CHECKSUM_MISMATCH: ::NTSTATUS = 0xC0000221u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA: ::NTSTATUS = 0xC0000222u32 as i32; +pub const STATUS_CLIENT_SERVER_PARAMETERS_INVALID: ::NTSTATUS = 0xC0000223u32 as i32; +pub const STATUS_PASSWORD_MUST_CHANGE: ::NTSTATUS = 0xC0000224u32 as i32; +pub const STATUS_NOT_FOUND: ::NTSTATUS = 0xC0000225u32 as i32; +pub const STATUS_NOT_TINY_STREAM: ::NTSTATUS = 0xC0000226u32 as i32; +pub const STATUS_RECOVERY_FAILURE: ::NTSTATUS = 0xC0000227u32 as i32; +pub const STATUS_STACK_OVERFLOW_READ: ::NTSTATUS = 0xC0000228u32 as i32; +pub const STATUS_FAIL_CHECK: ::NTSTATUS = 0xC0000229u32 as i32; +pub const STATUS_DUPLICATE_OBJECTID: ::NTSTATUS = 0xC000022Au32 as i32; +pub const STATUS_OBJECTID_EXISTS: ::NTSTATUS = 0xC000022Bu32 as i32; +pub const STATUS_CONVERT_TO_LARGE: ::NTSTATUS = 0xC000022Cu32 as i32; +pub const STATUS_RETRY: ::NTSTATUS = 0xC000022Du32 as i32; +pub const STATUS_FOUND_OUT_OF_SCOPE: ::NTSTATUS = 0xC000022Eu32 as i32; +pub const STATUS_ALLOCATE_BUCKET: ::NTSTATUS = 0xC000022Fu32 as i32; +pub const STATUS_PROPSET_NOT_FOUND: ::NTSTATUS = 0xC0000230u32 as i32; +pub const STATUS_MARSHALL_OVERFLOW: ::NTSTATUS = 0xC0000231u32 as i32; +pub const STATUS_INVALID_VARIANT: ::NTSTATUS = 0xC0000232u32 as i32; +pub const STATUS_DOMAIN_CONTROLLER_NOT_FOUND: ::NTSTATUS = 0xC0000233u32 as i32; +pub const STATUS_ACCOUNT_LOCKED_OUT: ::NTSTATUS = 0xC0000234u32 as i32; +pub const STATUS_HANDLE_NOT_CLOSABLE: ::NTSTATUS = 0xC0000235u32 as i32; +pub const STATUS_CONNECTION_REFUSED: ::NTSTATUS = 0xC0000236u32 as i32; +pub const STATUS_GRACEFUL_DISCONNECT: ::NTSTATUS = 0xC0000237u32 as i32; +pub const STATUS_ADDRESS_ALREADY_ASSOCIATED: ::NTSTATUS = 0xC0000238u32 as i32; +pub const STATUS_ADDRESS_NOT_ASSOCIATED: ::NTSTATUS = 0xC0000239u32 as i32; +pub const STATUS_CONNECTION_INVALID: ::NTSTATUS = 0xC000023Au32 as i32; +pub const STATUS_CONNECTION_ACTIVE: ::NTSTATUS = 0xC000023Bu32 as i32; +pub const STATUS_NETWORK_UNREACHABLE: ::NTSTATUS = 0xC000023Cu32 as i32; +pub const STATUS_HOST_UNREACHABLE: ::NTSTATUS = 0xC000023Du32 as i32; +pub const STATUS_PROTOCOL_UNREACHABLE: ::NTSTATUS = 0xC000023Eu32 as i32; +pub const STATUS_PORT_UNREACHABLE: ::NTSTATUS = 0xC000023Fu32 as i32; +pub const STATUS_REQUEST_ABORTED: ::NTSTATUS = 0xC0000240u32 as i32; +pub const STATUS_CONNECTION_ABORTED: ::NTSTATUS = 0xC0000241u32 as i32; +pub const STATUS_BAD_COMPRESSION_BUFFER: ::NTSTATUS = 0xC0000242u32 as i32; +pub const STATUS_USER_MAPPED_FILE: ::NTSTATUS = 0xC0000243u32 as i32; +pub const STATUS_AUDIT_FAILED: ::NTSTATUS = 0xC0000244u32 as i32; +pub const STATUS_TIMER_RESOLUTION_NOT_SET: ::NTSTATUS = 0xC0000245u32 as i32; +pub const STATUS_CONNECTION_COUNT_LIMIT: ::NTSTATUS = 0xC0000246u32 as i32; +pub const STATUS_LOGIN_TIME_RESTRICTION: ::NTSTATUS = 0xC0000247u32 as i32; +pub const STATUS_LOGIN_WKSTA_RESTRICTION: ::NTSTATUS = 0xC0000248u32 as i32; +pub const STATUS_IMAGE_MP_UP_MISMATCH: ::NTSTATUS = 0xC0000249u32 as i32; +pub const STATUS_INSUFFICIENT_LOGON_INFO: ::NTSTATUS = 0xC0000250u32 as i32; +pub const STATUS_BAD_DLL_ENTRYPOINT: ::NTSTATUS = 0xC0000251u32 as i32; +pub const STATUS_BAD_SERVICE_ENTRYPOINT: ::NTSTATUS = 0xC0000252u32 as i32; +pub const STATUS_LPC_REPLY_LOST: ::NTSTATUS = 0xC0000253u32 as i32; +pub const STATUS_IP_ADDRESS_CONFLICT1: ::NTSTATUS = 0xC0000254u32 as i32; +pub const STATUS_IP_ADDRESS_CONFLICT2: ::NTSTATUS = 0xC0000255u32 as i32; +pub const STATUS_REGISTRY_QUOTA_LIMIT: ::NTSTATUS = 0xC0000256u32 as i32; +pub const STATUS_PATH_NOT_COVERED: ::NTSTATUS = 0xC0000257u32 as i32; +pub const STATUS_NO_CALLBACK_ACTIVE: ::NTSTATUS = 0xC0000258u32 as i32; +pub const STATUS_LICENSE_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000259u32 as i32; +pub const STATUS_PWD_TOO_SHORT: ::NTSTATUS = 0xC000025Au32 as i32; +pub const STATUS_PWD_TOO_RECENT: ::NTSTATUS = 0xC000025Bu32 as i32; +pub const STATUS_PWD_HISTORY_CONFLICT: ::NTSTATUS = 0xC000025Cu32 as i32; +pub const STATUS_PLUGPLAY_NO_DEVICE: ::NTSTATUS = 0xC000025Eu32 as i32; +pub const STATUS_UNSUPPORTED_COMPRESSION: ::NTSTATUS = 0xC000025Fu32 as i32; +pub const STATUS_INVALID_HW_PROFILE: ::NTSTATUS = 0xC0000260u32 as i32; +pub const STATUS_INVALID_PLUGPLAY_DEVICE_PATH: ::NTSTATUS = 0xC0000261u32 as i32; +pub const STATUS_DRIVER_ORDINAL_NOT_FOUND: ::NTSTATUS = 0xC0000262u32 as i32; +pub const STATUS_DRIVER_ENTRYPOINT_NOT_FOUND: ::NTSTATUS = 0xC0000263u32 as i32; +pub const STATUS_RESOURCE_NOT_OWNED: ::NTSTATUS = 0xC0000264u32 as i32; +pub const STATUS_TOO_MANY_LINKS: ::NTSTATUS = 0xC0000265u32 as i32; +pub const STATUS_QUOTA_LIST_INCONSISTENT: ::NTSTATUS = 0xC0000266u32 as i32; +pub const STATUS_FILE_IS_OFFLINE: ::NTSTATUS = 0xC0000267u32 as i32; +pub const STATUS_EVALUATION_EXPIRATION: ::NTSTATUS = 0xC0000268u32 as i32; +pub const STATUS_ILLEGAL_DLL_RELOCATION: ::NTSTATUS = 0xC0000269u32 as i32; +pub const STATUS_LICENSE_VIOLATION: ::NTSTATUS = 0xC000026Au32 as i32; +pub const STATUS_DLL_INIT_FAILED_LOGOFF: ::NTSTATUS = 0xC000026Bu32 as i32; +pub const STATUS_DRIVER_UNABLE_TO_LOAD: ::NTSTATUS = 0xC000026Cu32 as i32; +pub const STATUS_DFS_UNAVAILABLE: ::NTSTATUS = 0xC000026Du32 as i32; +pub const STATUS_VOLUME_DISMOUNTED: ::NTSTATUS = 0xC000026Eu32 as i32; +pub const STATUS_WX86_INTERNAL_ERROR: ::NTSTATUS = 0xC000026Fu32 as i32; +pub const STATUS_WX86_FLOAT_STACK_CHECK: ::NTSTATUS = 0xC0000270u32 as i32; +pub const STATUS_VALIDATE_CONTINUE: ::NTSTATUS = 0xC0000271u32 as i32; +pub const STATUS_NO_MATCH: ::NTSTATUS = 0xC0000272u32 as i32; +pub const STATUS_NO_MORE_MATCHES: ::NTSTATUS = 0xC0000273u32 as i32; +pub const STATUS_NOT_A_REPARSE_POINT: ::NTSTATUS = 0xC0000275u32 as i32; +pub const STATUS_IO_REPARSE_TAG_INVALID: ::NTSTATUS = 0xC0000276u32 as i32; +pub const STATUS_IO_REPARSE_TAG_MISMATCH: ::NTSTATUS = 0xC0000277u32 as i32; +pub const STATUS_IO_REPARSE_DATA_INVALID: ::NTSTATUS = 0xC0000278u32 as i32; +pub const STATUS_IO_REPARSE_TAG_NOT_HANDLED: ::NTSTATUS = 0xC0000279u32 as i32; +pub const STATUS_PWD_TOO_LONG: ::NTSTATUS = 0xC000027Au32 as i32; +pub const STATUS_STOWED_EXCEPTION: ::NTSTATUS = 0xC000027Bu32 as i32; +pub const STATUS_REPARSE_POINT_NOT_RESOLVED: ::NTSTATUS = 0xC0000280u32 as i32; +pub const STATUS_DIRECTORY_IS_A_REPARSE_POINT: ::NTSTATUS = 0xC0000281u32 as i32; +pub const STATUS_RANGE_LIST_CONFLICT: ::NTSTATUS = 0xC0000282u32 as i32; +pub const STATUS_SOURCE_ELEMENT_EMPTY: ::NTSTATUS = 0xC0000283u32 as i32; +pub const STATUS_DESTINATION_ELEMENT_FULL: ::NTSTATUS = 0xC0000284u32 as i32; +pub const STATUS_ILLEGAL_ELEMENT_ADDRESS: ::NTSTATUS = 0xC0000285u32 as i32; +pub const STATUS_MAGAZINE_NOT_PRESENT: ::NTSTATUS = 0xC0000286u32 as i32; +pub const STATUS_REINITIALIZATION_NEEDED: ::NTSTATUS = 0xC0000287u32 as i32; +pub const STATUS_DEVICE_REQUIRES_CLEANING: ::NTSTATUS = 0x80000288u32 as i32; +pub const STATUS_DEVICE_DOOR_OPEN: ::NTSTATUS = 0x80000289u32 as i32; +pub const STATUS_ENCRYPTION_FAILED: ::NTSTATUS = 0xC000028Au32 as i32; +pub const STATUS_DECRYPTION_FAILED: ::NTSTATUS = 0xC000028Bu32 as i32; +pub const STATUS_RANGE_NOT_FOUND: ::NTSTATUS = 0xC000028Cu32 as i32; +pub const STATUS_NO_RECOVERY_POLICY: ::NTSTATUS = 0xC000028Du32 as i32; +pub const STATUS_NO_EFS: ::NTSTATUS = 0xC000028Eu32 as i32; +pub const STATUS_WRONG_EFS: ::NTSTATUS = 0xC000028Fu32 as i32; +pub const STATUS_NO_USER_KEYS: ::NTSTATUS = 0xC0000290u32 as i32; +pub const STATUS_FILE_NOT_ENCRYPTED: ::NTSTATUS = 0xC0000291u32 as i32; +pub const STATUS_NOT_EXPORT_FORMAT: ::NTSTATUS = 0xC0000292u32 as i32; +pub const STATUS_FILE_ENCRYPTED: ::NTSTATUS = 0xC0000293u32 as i32; +pub const STATUS_WAKE_SYSTEM: ::NTSTATUS = 0x40000294; +pub const STATUS_WMI_GUID_NOT_FOUND: ::NTSTATUS = 0xC0000295u32 as i32; +pub const STATUS_WMI_INSTANCE_NOT_FOUND: ::NTSTATUS = 0xC0000296u32 as i32; +pub const STATUS_WMI_ITEMID_NOT_FOUND: ::NTSTATUS = 0xC0000297u32 as i32; +pub const STATUS_WMI_TRY_AGAIN: ::NTSTATUS = 0xC0000298u32 as i32; +pub const STATUS_SHARED_POLICY: ::NTSTATUS = 0xC0000299u32 as i32; +pub const STATUS_POLICY_OBJECT_NOT_FOUND: ::NTSTATUS = 0xC000029Au32 as i32; +pub const STATUS_POLICY_ONLY_IN_DS: ::NTSTATUS = 0xC000029Bu32 as i32; +pub const STATUS_VOLUME_NOT_UPGRADED: ::NTSTATUS = 0xC000029Cu32 as i32; +pub const STATUS_REMOTE_STORAGE_NOT_ACTIVE: ::NTSTATUS = 0xC000029Du32 as i32; +pub const STATUS_REMOTE_STORAGE_MEDIA_ERROR: ::NTSTATUS = 0xC000029Eu32 as i32; +pub const STATUS_NO_TRACKING_SERVICE: ::NTSTATUS = 0xC000029Fu32 as i32; +pub const STATUS_SERVER_SID_MISMATCH: ::NTSTATUS = 0xC00002A0u32 as i32; +pub const STATUS_DS_NO_ATTRIBUTE_OR_VALUE: ::NTSTATUS = 0xC00002A1u32 as i32; +pub const STATUS_DS_INVALID_ATTRIBUTE_SYNTAX: ::NTSTATUS = 0xC00002A2u32 as i32; +pub const STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED: ::NTSTATUS = 0xC00002A3u32 as i32; +pub const STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS: ::NTSTATUS = 0xC00002A4u32 as i32; +pub const STATUS_DS_BUSY: ::NTSTATUS = 0xC00002A5u32 as i32; +pub const STATUS_DS_UNAVAILABLE: ::NTSTATUS = 0xC00002A6u32 as i32; +pub const STATUS_DS_NO_RIDS_ALLOCATED: ::NTSTATUS = 0xC00002A7u32 as i32; +pub const STATUS_DS_NO_MORE_RIDS: ::NTSTATUS = 0xC00002A8u32 as i32; +pub const STATUS_DS_INCORRECT_ROLE_OWNER: ::NTSTATUS = 0xC00002A9u32 as i32; +pub const STATUS_DS_RIDMGR_INIT_ERROR: ::NTSTATUS = 0xC00002AAu32 as i32; +pub const STATUS_DS_OBJ_CLASS_VIOLATION: ::NTSTATUS = 0xC00002ABu32 as i32; +pub const STATUS_DS_CANT_ON_NON_LEAF: ::NTSTATUS = 0xC00002ACu32 as i32; +pub const STATUS_DS_CANT_ON_RDN: ::NTSTATUS = 0xC00002ADu32 as i32; +pub const STATUS_DS_CANT_MOD_OBJ_CLASS: ::NTSTATUS = 0xC00002AEu32 as i32; +pub const STATUS_DS_CROSS_DOM_MOVE_FAILED: ::NTSTATUS = 0xC00002AFu32 as i32; +pub const STATUS_DS_GC_NOT_AVAILABLE: ::NTSTATUS = 0xC00002B0u32 as i32; +pub const STATUS_DIRECTORY_SERVICE_REQUIRED: ::NTSTATUS = 0xC00002B1u32 as i32; +pub const STATUS_REPARSE_ATTRIBUTE_CONFLICT: ::NTSTATUS = 0xC00002B2u32 as i32; +pub const STATUS_CANT_ENABLE_DENY_ONLY: ::NTSTATUS = 0xC00002B3u32 as i32; +pub const STATUS_FLOAT_MULTIPLE_FAULTS: ::NTSTATUS = 0xC00002B4u32 as i32; +pub const STATUS_FLOAT_MULTIPLE_TRAPS: ::NTSTATUS = 0xC00002B5u32 as i32; +pub const STATUS_DEVICE_REMOVED: ::NTSTATUS = 0xC00002B6u32 as i32; +pub const STATUS_JOURNAL_DELETE_IN_PROGRESS: ::NTSTATUS = 0xC00002B7u32 as i32; +pub const STATUS_JOURNAL_NOT_ACTIVE: ::NTSTATUS = 0xC00002B8u32 as i32; +pub const STATUS_NOINTERFACE: ::NTSTATUS = 0xC00002B9u32 as i32; +pub const STATUS_DS_RIDMGR_DISABLED: ::NTSTATUS = 0xC00002BAu32 as i32; +pub const STATUS_DS_ADMIN_LIMIT_EXCEEDED: ::NTSTATUS = 0xC00002C1u32 as i32; +pub const STATUS_DRIVER_FAILED_SLEEP: ::NTSTATUS = 0xC00002C2u32 as i32; +pub const STATUS_MUTUAL_AUTHENTICATION_FAILED: ::NTSTATUS = 0xC00002C3u32 as i32; +pub const STATUS_CORRUPT_SYSTEM_FILE: ::NTSTATUS = 0xC00002C4u32 as i32; +pub const STATUS_DATATYPE_MISALIGNMENT_ERROR: ::NTSTATUS = 0xC00002C5u32 as i32; +pub const STATUS_WMI_READ_ONLY: ::NTSTATUS = 0xC00002C6u32 as i32; +pub const STATUS_WMI_SET_FAILURE: ::NTSTATUS = 0xC00002C7u32 as i32; +pub const STATUS_COMMITMENT_MINIMUM: ::NTSTATUS = 0xC00002C8u32 as i32; +pub const STATUS_REG_NAT_CONSUMPTION: ::NTSTATUS = 0xC00002C9u32 as i32; +pub const STATUS_TRANSPORT_FULL: ::NTSTATUS = 0xC00002CAu32 as i32; +pub const STATUS_DS_SAM_INIT_FAILURE: ::NTSTATUS = 0xC00002CBu32 as i32; +pub const STATUS_ONLY_IF_CONNECTED: ::NTSTATUS = 0xC00002CCu32 as i32; +pub const STATUS_DS_SENSITIVE_GROUP_VIOLATION: ::NTSTATUS = 0xC00002CDu32 as i32; +pub const STATUS_PNP_RESTART_ENUMERATION: ::NTSTATUS = 0xC00002CEu32 as i32; +pub const STATUS_JOURNAL_ENTRY_DELETED: ::NTSTATUS = 0xC00002CFu32 as i32; +pub const STATUS_DS_CANT_MOD_PRIMARYGROUPID: ::NTSTATUS = 0xC00002D0u32 as i32; +pub const STATUS_SYSTEM_IMAGE_BAD_SIGNATURE: ::NTSTATUS = 0xC00002D1u32 as i32; +pub const STATUS_PNP_REBOOT_REQUIRED: ::NTSTATUS = 0xC00002D2u32 as i32; +pub const STATUS_POWER_STATE_INVALID: ::NTSTATUS = 0xC00002D3u32 as i32; +pub const STATUS_DS_INVALID_GROUP_TYPE: ::NTSTATUS = 0xC00002D4u32 as i32; +pub const STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: ::NTSTATUS = 0xC00002D5u32 as i32; +pub const STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: ::NTSTATUS = 0xC00002D6u32 as i32; +pub const STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: ::NTSTATUS = 0xC00002D7u32 as i32; +pub const STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: ::NTSTATUS = 0xC00002D8u32 as i32; +pub const STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: ::NTSTATUS = 0xC00002D9u32 as i32; +pub const STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: ::NTSTATUS = 0xC00002DAu32 as i32; +pub const STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: ::NTSTATUS = 0xC00002DBu32 as i32; +pub const STATUS_DS_HAVE_PRIMARY_MEMBERS: ::NTSTATUS = 0xC00002DCu32 as i32; +pub const STATUS_WMI_NOT_SUPPORTED: ::NTSTATUS = 0xC00002DDu32 as i32; +pub const STATUS_INSUFFICIENT_POWER: ::NTSTATUS = 0xC00002DEu32 as i32; +pub const STATUS_SAM_NEED_BOOTKEY_PASSWORD: ::NTSTATUS = 0xC00002DFu32 as i32; +pub const STATUS_SAM_NEED_BOOTKEY_FLOPPY: ::NTSTATUS = 0xC00002E0u32 as i32; +pub const STATUS_DS_CANT_START: ::NTSTATUS = 0xC00002E1u32 as i32; +pub const STATUS_DS_INIT_FAILURE: ::NTSTATUS = 0xC00002E2u32 as i32; +pub const STATUS_SAM_INIT_FAILURE: ::NTSTATUS = 0xC00002E3u32 as i32; +pub const STATUS_DS_GC_REQUIRED: ::NTSTATUS = 0xC00002E4u32 as i32; +pub const STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: ::NTSTATUS = 0xC00002E5u32 as i32; +pub const STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS: ::NTSTATUS = 0xC00002E6u32 as i32; +pub const STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: ::NTSTATUS = 0xC00002E7u32 as i32; +pub const STATUS_MULTIPLE_FAULT_VIOLATION: ::NTSTATUS = 0xC00002E8u32 as i32; +pub const STATUS_CURRENT_DOMAIN_NOT_ALLOWED: ::NTSTATUS = 0xC00002E9u32 as i32; +pub const STATUS_CANNOT_MAKE: ::NTSTATUS = 0xC00002EAu32 as i32; +pub const STATUS_SYSTEM_SHUTDOWN: ::NTSTATUS = 0xC00002EBu32 as i32; +pub const STATUS_DS_INIT_FAILURE_CONSOLE: ::NTSTATUS = 0xC00002ECu32 as i32; +pub const STATUS_DS_SAM_INIT_FAILURE_CONSOLE: ::NTSTATUS = 0xC00002EDu32 as i32; +pub const STATUS_UNFINISHED_CONTEXT_DELETED: ::NTSTATUS = 0xC00002EEu32 as i32; +pub const STATUS_NO_TGT_REPLY: ::NTSTATUS = 0xC00002EFu32 as i32; +pub const STATUS_OBJECTID_NOT_FOUND: ::NTSTATUS = 0xC00002F0u32 as i32; +pub const STATUS_NO_IP_ADDRESSES: ::NTSTATUS = 0xC00002F1u32 as i32; +pub const STATUS_WRONG_CREDENTIAL_HANDLE: ::NTSTATUS = 0xC00002F2u32 as i32; +pub const STATUS_CRYPTO_SYSTEM_INVALID: ::NTSTATUS = 0xC00002F3u32 as i32; +pub const STATUS_MAX_REFERRALS_EXCEEDED: ::NTSTATUS = 0xC00002F4u32 as i32; +pub const STATUS_MUST_BE_KDC: ::NTSTATUS = 0xC00002F5u32 as i32; +pub const STATUS_STRONG_CRYPTO_NOT_SUPPORTED: ::NTSTATUS = 0xC00002F6u32 as i32; +pub const STATUS_TOO_MANY_PRINCIPALS: ::NTSTATUS = 0xC00002F7u32 as i32; +pub const STATUS_NO_PA_DATA: ::NTSTATUS = 0xC00002F8u32 as i32; +pub const STATUS_PKINIT_NAME_MISMATCH: ::NTSTATUS = 0xC00002F9u32 as i32; +pub const STATUS_SMARTCARD_LOGON_REQUIRED: ::NTSTATUS = 0xC00002FAu32 as i32; +pub const STATUS_KDC_INVALID_REQUEST: ::NTSTATUS = 0xC00002FBu32 as i32; +pub const STATUS_KDC_UNABLE_TO_REFER: ::NTSTATUS = 0xC00002FCu32 as i32; +pub const STATUS_KDC_UNKNOWN_ETYPE: ::NTSTATUS = 0xC00002FDu32 as i32; +pub const STATUS_SHUTDOWN_IN_PROGRESS: ::NTSTATUS = 0xC00002FEu32 as i32; +pub const STATUS_SERVER_SHUTDOWN_IN_PROGRESS: ::NTSTATUS = 0xC00002FFu32 as i32; +pub const STATUS_NOT_SUPPORTED_ON_SBS: ::NTSTATUS = 0xC0000300u32 as i32; +pub const STATUS_WMI_GUID_DISCONNECTED: ::NTSTATUS = 0xC0000301u32 as i32; +pub const STATUS_WMI_ALREADY_DISABLED: ::NTSTATUS = 0xC0000302u32 as i32; +pub const STATUS_WMI_ALREADY_ENABLED: ::NTSTATUS = 0xC0000303u32 as i32; +pub const STATUS_MFT_TOO_FRAGMENTED: ::NTSTATUS = 0xC0000304u32 as i32; +pub const STATUS_COPY_PROTECTION_FAILURE: ::NTSTATUS = 0xC0000305u32 as i32; +pub const STATUS_CSS_AUTHENTICATION_FAILURE: ::NTSTATUS = 0xC0000306u32 as i32; +pub const STATUS_CSS_KEY_NOT_PRESENT: ::NTSTATUS = 0xC0000307u32 as i32; +pub const STATUS_CSS_KEY_NOT_ESTABLISHED: ::NTSTATUS = 0xC0000308u32 as i32; +pub const STATUS_CSS_SCRAMBLED_SECTOR: ::NTSTATUS = 0xC0000309u32 as i32; +pub const STATUS_CSS_REGION_MISMATCH: ::NTSTATUS = 0xC000030Au32 as i32; +pub const STATUS_CSS_RESETS_EXHAUSTED: ::NTSTATUS = 0xC000030Bu32 as i32; +pub const STATUS_PASSWORD_CHANGE_REQUIRED: ::NTSTATUS = 0xC000030Cu32 as i32; +pub const STATUS_PKINIT_FAILURE: ::NTSTATUS = 0xC0000320u32 as i32; +pub const STATUS_SMARTCARD_SUBSYSTEM_FAILURE: ::NTSTATUS = 0xC0000321u32 as i32; +pub const STATUS_NO_KERB_KEY: ::NTSTATUS = 0xC0000322u32 as i32; +pub const STATUS_HOST_DOWN: ::NTSTATUS = 0xC0000350u32 as i32; +pub const STATUS_UNSUPPORTED_PREAUTH: ::NTSTATUS = 0xC0000351u32 as i32; +pub const STATUS_EFS_ALG_BLOB_TOO_BIG: ::NTSTATUS = 0xC0000352u32 as i32; +pub const STATUS_PORT_NOT_SET: ::NTSTATUS = 0xC0000353u32 as i32; +pub const STATUS_DEBUGGER_INACTIVE: ::NTSTATUS = 0xC0000354u32 as i32; +pub const STATUS_DS_VERSION_CHECK_FAILURE: ::NTSTATUS = 0xC0000355u32 as i32; +pub const STATUS_AUDITING_DISABLED: ::NTSTATUS = 0xC0000356u32 as i32; +pub const STATUS_PRENT4_MACHINE_ACCOUNT: ::NTSTATUS = 0xC0000357u32 as i32; +pub const STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: ::NTSTATUS = 0xC0000358u32 as i32; +pub const STATUS_INVALID_IMAGE_WIN_32: ::NTSTATUS = 0xC0000359u32 as i32; +pub const STATUS_INVALID_IMAGE_WIN_64: ::NTSTATUS = 0xC000035Au32 as i32; +pub const STATUS_BAD_BINDINGS: ::NTSTATUS = 0xC000035Bu32 as i32; +pub const STATUS_NETWORK_SESSION_EXPIRED: ::NTSTATUS = 0xC000035Cu32 as i32; +pub const STATUS_APPHELP_BLOCK: ::NTSTATUS = 0xC000035Du32 as i32; +pub const STATUS_ALL_SIDS_FILTERED: ::NTSTATUS = 0xC000035Eu32 as i32; +pub const STATUS_NOT_SAFE_MODE_DRIVER: ::NTSTATUS = 0xC000035Fu32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT: ::NTSTATUS = 0xC0000361u32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_PATH: ::NTSTATUS = 0xC0000362u32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER: ::NTSTATUS = 0xC0000363u32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_OTHER: ::NTSTATUS = 0xC0000364u32 as i32; +pub const STATUS_FAILED_DRIVER_ENTRY: ::NTSTATUS = 0xC0000365u32 as i32; +pub const STATUS_DEVICE_ENUMERATION_ERROR: ::NTSTATUS = 0xC0000366u32 as i32; +pub const STATUS_MOUNT_POINT_NOT_RESOLVED: ::NTSTATUS = 0xC0000368u32 as i32; +pub const STATUS_INVALID_DEVICE_OBJECT_PARAMETER: ::NTSTATUS = 0xC0000369u32 as i32; +pub const STATUS_MCA_OCCURED: ::NTSTATUS = 0xC000036Au32 as i32; +pub const STATUS_DRIVER_BLOCKED_CRITICAL: ::NTSTATUS = 0xC000036Bu32 as i32; +pub const STATUS_DRIVER_BLOCKED: ::NTSTATUS = 0xC000036Cu32 as i32; +pub const STATUS_DRIVER_DATABASE_ERROR: ::NTSTATUS = 0xC000036Du32 as i32; +pub const STATUS_SYSTEM_HIVE_TOO_LARGE: ::NTSTATUS = 0xC000036Eu32 as i32; +pub const STATUS_INVALID_IMPORT_OF_NON_DLL: ::NTSTATUS = 0xC000036Fu32 as i32; +pub const STATUS_DS_SHUTTING_DOWN: ::NTSTATUS = 0x40000370; +pub const STATUS_NO_SECRETS: ::NTSTATUS = 0xC0000371u32 as i32; +pub const STATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY: ::NTSTATUS = 0xC0000372u32 as i32; +pub const STATUS_FAILED_STACK_SWITCH: ::NTSTATUS = 0xC0000373u32 as i32; +pub const STATUS_HEAP_CORRUPTION: ::NTSTATUS = 0xC0000374u32 as i32; +pub const STATUS_SMARTCARD_WRONG_PIN: ::NTSTATUS = 0xC0000380u32 as i32; +pub const STATUS_SMARTCARD_CARD_BLOCKED: ::NTSTATUS = 0xC0000381u32 as i32; +pub const STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED: ::NTSTATUS = 0xC0000382u32 as i32; +pub const STATUS_SMARTCARD_NO_CARD: ::NTSTATUS = 0xC0000383u32 as i32; +pub const STATUS_SMARTCARD_NO_KEY_CONTAINER: ::NTSTATUS = 0xC0000384u32 as i32; +pub const STATUS_SMARTCARD_NO_CERTIFICATE: ::NTSTATUS = 0xC0000385u32 as i32; +pub const STATUS_SMARTCARD_NO_KEYSET: ::NTSTATUS = 0xC0000386u32 as i32; +pub const STATUS_SMARTCARD_IO_ERROR: ::NTSTATUS = 0xC0000387u32 as i32; +pub const STATUS_DOWNGRADE_DETECTED: ::NTSTATUS = 0xC0000388u32 as i32; +pub const STATUS_SMARTCARD_CERT_REVOKED: ::NTSTATUS = 0xC0000389u32 as i32; +pub const STATUS_ISSUING_CA_UNTRUSTED: ::NTSTATUS = 0xC000038Au32 as i32; +pub const STATUS_REVOCATION_OFFLINE_C: ::NTSTATUS = 0xC000038Bu32 as i32; +pub const STATUS_PKINIT_CLIENT_FAILURE: ::NTSTATUS = 0xC000038Cu32 as i32; +pub const STATUS_SMARTCARD_CERT_EXPIRED: ::NTSTATUS = 0xC000038Du32 as i32; +pub const STATUS_DRIVER_FAILED_PRIOR_UNLOAD: ::NTSTATUS = 0xC000038Eu32 as i32; +pub const STATUS_SMARTCARD_SILENT_CONTEXT: ::NTSTATUS = 0xC000038Fu32 as i32; +pub const STATUS_PER_USER_TRUST_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000401u32 as i32; +pub const STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000402u32 as i32; +pub const STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000403u32 as i32; +pub const STATUS_DS_NAME_NOT_UNIQUE: ::NTSTATUS = 0xC0000404u32 as i32; +pub const STATUS_DS_DUPLICATE_ID_FOUND: ::NTSTATUS = 0xC0000405u32 as i32; +pub const STATUS_DS_GROUP_CONVERSION_ERROR: ::NTSTATUS = 0xC0000406u32 as i32; +pub const STATUS_VOLSNAP_PREPARE_HIBERNATE: ::NTSTATUS = 0xC0000407u32 as i32; +pub const STATUS_USER2USER_REQUIRED: ::NTSTATUS = 0xC0000408u32 as i32; +pub const STATUS_STACK_BUFFER_OVERRUN: ::NTSTATUS = 0xC0000409u32 as i32; +pub const STATUS_NO_S4U_PROT_SUPPORT: ::NTSTATUS = 0xC000040Au32 as i32; +pub const STATUS_CROSSREALM_DELEGATION_FAILURE: ::NTSTATUS = 0xC000040Bu32 as i32; +pub const STATUS_REVOCATION_OFFLINE_KDC: ::NTSTATUS = 0xC000040Cu32 as i32; +pub const STATUS_ISSUING_CA_UNTRUSTED_KDC: ::NTSTATUS = 0xC000040Du32 as i32; +pub const STATUS_KDC_CERT_EXPIRED: ::NTSTATUS = 0xC000040Eu32 as i32; +pub const STATUS_KDC_CERT_REVOKED: ::NTSTATUS = 0xC000040Fu32 as i32; +pub const STATUS_PARAMETER_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000410u32 as i32; +pub const STATUS_HIBERNATION_FAILURE: ::NTSTATUS = 0xC0000411u32 as i32; +pub const STATUS_DELAY_LOAD_FAILED: ::NTSTATUS = 0xC0000412u32 as i32; +pub const STATUS_AUTHENTICATION_FIREWALL_FAILED: ::NTSTATUS = 0xC0000413u32 as i32; +pub const STATUS_VDM_DISALLOWED: ::NTSTATUS = 0xC0000414u32 as i32; +pub const STATUS_HUNG_DISPLAY_DRIVER_THREAD: ::NTSTATUS = 0xC0000415u32 as i32; +pub const STATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE: ::NTSTATUS = 0xC0000416u32 as i32; +pub const STATUS_INVALID_CRUNTIME_PARAMETER: ::NTSTATUS = 0xC0000417u32 as i32; +pub const STATUS_NTLM_BLOCKED: ::NTSTATUS = 0xC0000418u32 as i32; +pub const STATUS_DS_SRC_SID_EXISTS_IN_FOREST: ::NTSTATUS = 0xC0000419u32 as i32; +pub const STATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST: ::NTSTATUS = 0xC000041Au32 as i32; +pub const STATUS_DS_FLAT_NAME_EXISTS_IN_FOREST: ::NTSTATUS = 0xC000041Bu32 as i32; +pub const STATUS_INVALID_USER_PRINCIPAL_NAME: ::NTSTATUS = 0xC000041Cu32 as i32; +pub const STATUS_FATAL_USER_CALLBACK_EXCEPTION: ::NTSTATUS = 0xC000041Du32 as i32; +pub const STATUS_ASSERTION_FAILURE: ::NTSTATUS = 0xC0000420u32 as i32; +pub const STATUS_VERIFIER_STOP: ::NTSTATUS = 0xC0000421u32 as i32; +pub const STATUS_CALLBACK_POP_STACK: ::NTSTATUS = 0xC0000423u32 as i32; +pub const STATUS_INCOMPATIBLE_DRIVER_BLOCKED: ::NTSTATUS = 0xC0000424u32 as i32; +pub const STATUS_HIVE_UNLOADED: ::NTSTATUS = 0xC0000425u32 as i32; +pub const STATUS_COMPRESSION_DISABLED: ::NTSTATUS = 0xC0000426u32 as i32; +pub const STATUS_FILE_SYSTEM_LIMITATION: ::NTSTATUS = 0xC0000427u32 as i32; +pub const STATUS_INVALID_IMAGE_HASH: ::NTSTATUS = 0xC0000428u32 as i32; +pub const STATUS_NOT_CAPABLE: ::NTSTATUS = 0xC0000429u32 as i32; +pub const STATUS_REQUEST_OUT_OF_SEQUENCE: ::NTSTATUS = 0xC000042Au32 as i32; +pub const STATUS_IMPLEMENTATION_LIMIT: ::NTSTATUS = 0xC000042Bu32 as i32; +pub const STATUS_ELEVATION_REQUIRED: ::NTSTATUS = 0xC000042Cu32 as i32; +pub const STATUS_NO_SECURITY_CONTEXT: ::NTSTATUS = 0xC000042Du32 as i32; +pub const STATUS_PKU2U_CERT_FAILURE: ::NTSTATUS = 0xC000042Fu32 as i32; +pub const STATUS_BEYOND_VDL: ::NTSTATUS = 0xC0000432u32 as i32; +pub const STATUS_ENCOUNTERED_WRITE_IN_PROGRESS: ::NTSTATUS = 0xC0000433u32 as i32; +pub const STATUS_PTE_CHANGED: ::NTSTATUS = 0xC0000434u32 as i32; +pub const STATUS_PURGE_FAILED: ::NTSTATUS = 0xC0000435u32 as i32; +pub const STATUS_CRED_REQUIRES_CONFIRMATION: ::NTSTATUS = 0xC0000440u32 as i32; +pub const STATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE: ::NTSTATUS = 0xC0000441u32 as i32; +pub const STATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER: ::NTSTATUS = 0xC0000442u32 as i32; +pub const STATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE: ::NTSTATUS = 0xC0000443u32 as i32; +pub const STATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE: ::NTSTATUS = 0xC0000444u32 as i32; +pub const STATUS_CS_ENCRYPTION_FILE_NOT_CSE: ::NTSTATUS = 0xC0000445u32 as i32; +pub const STATUS_INVALID_LABEL: ::NTSTATUS = 0xC0000446u32 as i32; +pub const STATUS_DRIVER_PROCESS_TERMINATED: ::NTSTATUS = 0xC0000450u32 as i32; +pub const STATUS_AMBIGUOUS_SYSTEM_DEVICE: ::NTSTATUS = 0xC0000451u32 as i32; +pub const STATUS_SYSTEM_DEVICE_NOT_FOUND: ::NTSTATUS = 0xC0000452u32 as i32; +pub const STATUS_RESTART_BOOT_APPLICATION: ::NTSTATUS = 0xC0000453u32 as i32; +pub const STATUS_INSUFFICIENT_NVRAM_RESOURCES: ::NTSTATUS = 0xC0000454u32 as i32; +pub const STATUS_INVALID_SESSION: ::NTSTATUS = 0xC0000455u32 as i32; +pub const STATUS_THREAD_ALREADY_IN_SESSION: ::NTSTATUS = 0xC0000456u32 as i32; +pub const STATUS_THREAD_NOT_IN_SESSION: ::NTSTATUS = 0xC0000457u32 as i32; +pub const STATUS_INVALID_WEIGHT: ::NTSTATUS = 0xC0000458u32 as i32; +pub const STATUS_REQUEST_PAUSED: ::NTSTATUS = 0xC0000459u32 as i32; +pub const STATUS_NO_RANGES_PROCESSED: ::NTSTATUS = 0xC0000460u32 as i32; +pub const STATUS_DISK_RESOURCES_EXHAUSTED: ::NTSTATUS = 0xC0000461u32 as i32; +pub const STATUS_NEEDS_REMEDIATION: ::NTSTATUS = 0xC0000462u32 as i32; +pub const STATUS_DEVICE_FEATURE_NOT_SUPPORTED: ::NTSTATUS = 0xC0000463u32 as i32; +pub const STATUS_DEVICE_UNREACHABLE: ::NTSTATUS = 0xC0000464u32 as i32; +pub const STATUS_INVALID_TOKEN: ::NTSTATUS = 0xC0000465u32 as i32; +pub const STATUS_SERVER_UNAVAILABLE: ::NTSTATUS = 0xC0000466u32 as i32; +pub const STATUS_FILE_NOT_AVAILABLE: ::NTSTATUS = 0xC0000467u32 as i32; +pub const STATUS_DEVICE_INSUFFICIENT_RESOURCES: ::NTSTATUS = 0xC0000468u32 as i32; +pub const STATUS_PACKAGE_UPDATING: ::NTSTATUS = 0xC0000469u32 as i32; +pub const STATUS_NOT_READ_FROM_COPY: ::NTSTATUS = 0xC000046Au32 as i32; +pub const STATUS_FT_WRITE_FAILURE: ::NTSTATUS = 0xC000046Bu32 as i32; +pub const STATUS_FT_DI_SCAN_REQUIRED: ::NTSTATUS = 0xC000046Cu32 as i32; +pub const STATUS_OBJECT_NOT_EXTERNALLY_BACKED: ::NTSTATUS = 0xC000046Du32 as i32; +pub const STATUS_EXTERNAL_BACKING_PROVIDER_UNKNOWN: ::NTSTATUS = 0xC000046Eu32 as i32; +pub const STATUS_COMPRESSION_NOT_BENEFICIAL: ::NTSTATUS = 0xC000046Fu32 as i32; +pub const STATUS_DATA_CHECKSUM_ERROR: ::NTSTATUS = 0xC0000470u32 as i32; +pub const STATUS_INTERMIXED_KERNEL_EA_OPERATION: ::NTSTATUS = 0xC0000471u32 as i32; +pub const STATUS_TRIM_READ_ZERO_NOT_SUPPORTED: ::NTSTATUS = 0xC0000472u32 as i32; +pub const STATUS_TOO_MANY_SEGMENT_DESCRIPTORS: ::NTSTATUS = 0xC0000473u32 as i32; +pub const STATUS_INVALID_OFFSET_ALIGNMENT: ::NTSTATUS = 0xC0000474u32 as i32; +pub const STATUS_INVALID_FIELD_IN_PARAMETER_LIST: ::NTSTATUS = 0xC0000475u32 as i32; +pub const STATUS_OPERATION_IN_PROGRESS: ::NTSTATUS = 0xC0000476u32 as i32; +pub const STATUS_INVALID_INITIATOR_TARGET_PATH: ::NTSTATUS = 0xC0000477u32 as i32; +pub const STATUS_SCRUB_DATA_DISABLED: ::NTSTATUS = 0xC0000478u32 as i32; +pub const STATUS_NOT_REDUNDANT_STORAGE: ::NTSTATUS = 0xC0000479u32 as i32; +pub const STATUS_RESIDENT_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000047Au32 as i32; +pub const STATUS_COMPRESSED_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000047Bu32 as i32; +pub const STATUS_DIRECTORY_NOT_SUPPORTED: ::NTSTATUS = 0xC000047Cu32 as i32; +pub const STATUS_IO_OPERATION_TIMEOUT: ::NTSTATUS = 0xC000047Du32 as i32; +pub const STATUS_SYSTEM_NEEDS_REMEDIATION: ::NTSTATUS = 0xC000047Eu32 as i32; +pub const STATUS_APPX_INTEGRITY_FAILURE_CLR_NGEN: ::NTSTATUS = 0xC000047Fu32 as i32; +pub const STATUS_SHARE_UNAVAILABLE: ::NTSTATUS = 0xC0000480u32 as i32; +pub const STATUS_APISET_NOT_HOSTED: ::NTSTATUS = 0xC0000481u32 as i32; +pub const STATUS_APISET_NOT_PRESENT: ::NTSTATUS = 0xC0000482u32 as i32; +pub const STATUS_DEVICE_HARDWARE_ERROR: ::NTSTATUS = 0xC0000483u32 as i32; +pub const STATUS_FIRMWARE_SLOT_INVALID: ::NTSTATUS = 0xC0000484u32 as i32; +pub const STATUS_FIRMWARE_IMAGE_INVALID: ::NTSTATUS = 0xC0000485u32 as i32; +pub const STATUS_STORAGE_TOPOLOGY_ID_MISMATCH: ::NTSTATUS = 0xC0000486u32 as i32; +pub const STATUS_WIM_NOT_BOOTABLE: ::NTSTATUS = 0xC0000487u32 as i32; +pub const STATUS_BLOCKED_BY_PARENTAL_CONTROLS: ::NTSTATUS = 0xC0000488u32 as i32; +pub const STATUS_NEEDS_REGISTRATION: ::NTSTATUS = 0xC0000489u32 as i32; +pub const STATUS_QUOTA_ACTIVITY: ::NTSTATUS = 0xC000048Au32 as i32; +pub const STATUS_INVALID_TASK_NAME: ::NTSTATUS = 0xC0000500u32 as i32; +pub const STATUS_INVALID_TASK_INDEX: ::NTSTATUS = 0xC0000501u32 as i32; +pub const STATUS_THREAD_ALREADY_IN_TASK: ::NTSTATUS = 0xC0000502u32 as i32; +pub const STATUS_CALLBACK_BYPASS: ::NTSTATUS = 0xC0000503u32 as i32; +pub const STATUS_UNDEFINED_SCOPE: ::NTSTATUS = 0xC0000504u32 as i32; +pub const STATUS_INVALID_CAP: ::NTSTATUS = 0xC0000505u32 as i32; +pub const STATUS_NOT_GUI_PROCESS: ::NTSTATUS = 0xC0000506u32 as i32; +pub const STATUS_DEVICE_HUNG: ::NTSTATUS = 0xC0000507u32 as i32; +pub const STATUS_FAIL_FAST_EXCEPTION: ::NTSTATUS = 0xC0000602u32 as i32; +pub const STATUS_IMAGE_CERT_REVOKED: ::NTSTATUS = 0xC0000603u32 as i32; +pub const STATUS_DYNAMIC_CODE_BLOCKED: ::NTSTATUS = 0xC0000604u32 as i32; +pub const STATUS_IMAGE_CERT_EXPIRED: ::NTSTATUS = 0xC0000605u32 as i32; +pub const STATUS_PORT_CLOSED: ::NTSTATUS = 0xC0000700u32 as i32; +pub const STATUS_MESSAGE_LOST: ::NTSTATUS = 0xC0000701u32 as i32; +pub const STATUS_INVALID_MESSAGE: ::NTSTATUS = 0xC0000702u32 as i32; +pub const STATUS_REQUEST_CANCELED: ::NTSTATUS = 0xC0000703u32 as i32; +pub const STATUS_RECURSIVE_DISPATCH: ::NTSTATUS = 0xC0000704u32 as i32; +pub const STATUS_LPC_RECEIVE_BUFFER_EXPECTED: ::NTSTATUS = 0xC0000705u32 as i32; +pub const STATUS_LPC_INVALID_CONNECTION_USAGE: ::NTSTATUS = 0xC0000706u32 as i32; +pub const STATUS_LPC_REQUESTS_NOT_ALLOWED: ::NTSTATUS = 0xC0000707u32 as i32; +pub const STATUS_RESOURCE_IN_USE: ::NTSTATUS = 0xC0000708u32 as i32; +pub const STATUS_HARDWARE_MEMORY_ERROR: ::NTSTATUS = 0xC0000709u32 as i32; +pub const STATUS_THREADPOOL_HANDLE_EXCEPTION: ::NTSTATUS = 0xC000070Au32 as i32; +pub const STATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Bu32 as i32; +pub const STATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Cu32 as i32; +pub const STATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Du32 as i32; +pub const STATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Eu32 as i32; +pub const STATUS_THREADPOOL_RELEASED_DURING_OPERATION: ::NTSTATUS = 0xC000070Fu32 as i32; +pub const STATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING: ::NTSTATUS = 0xC0000710u32 as i32; +pub const STATUS_APC_RETURNED_WHILE_IMPERSONATING: ::NTSTATUS = 0xC0000711u32 as i32; +pub const STATUS_PROCESS_IS_PROTECTED: ::NTSTATUS = 0xC0000712u32 as i32; +pub const STATUS_MCA_EXCEPTION: ::NTSTATUS = 0xC0000713u32 as i32; +pub const STATUS_CERTIFICATE_MAPPING_NOT_UNIQUE: ::NTSTATUS = 0xC0000714u32 as i32; +pub const STATUS_SYMLINK_CLASS_DISABLED: ::NTSTATUS = 0xC0000715u32 as i32; +pub const STATUS_INVALID_IDN_NORMALIZATION: ::NTSTATUS = 0xC0000716u32 as i32; +pub const STATUS_NO_UNICODE_TRANSLATION: ::NTSTATUS = 0xC0000717u32 as i32; +pub const STATUS_ALREADY_REGISTERED: ::NTSTATUS = 0xC0000718u32 as i32; +pub const STATUS_CONTEXT_MISMATCH: ::NTSTATUS = 0xC0000719u32 as i32; +pub const STATUS_PORT_ALREADY_HAS_COMPLETION_LIST: ::NTSTATUS = 0xC000071Au32 as i32; +pub const STATUS_CALLBACK_RETURNED_THREAD_PRIORITY: ::NTSTATUS = 0xC000071Bu32 as i32; +pub const STATUS_INVALID_THREAD: ::NTSTATUS = 0xC000071Cu32 as i32; +pub const STATUS_CALLBACK_RETURNED_TRANSACTION: ::NTSTATUS = 0xC000071Du32 as i32; +pub const STATUS_CALLBACK_RETURNED_LDR_LOCK: ::NTSTATUS = 0xC000071Eu32 as i32; +pub const STATUS_CALLBACK_RETURNED_LANG: ::NTSTATUS = 0xC000071Fu32 as i32; +pub const STATUS_CALLBACK_RETURNED_PRI_BACK: ::NTSTATUS = 0xC0000720u32 as i32; +pub const STATUS_CALLBACK_RETURNED_THREAD_AFFINITY: ::NTSTATUS = 0xC0000721u32 as i32; +pub const STATUS_DISK_REPAIR_DISABLED: ::NTSTATUS = 0xC0000800u32 as i32; +pub const STATUS_DS_DOMAIN_RENAME_IN_PROGRESS: ::NTSTATUS = 0xC0000801u32 as i32; +pub const STATUS_DISK_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000802u32 as i32; +pub const STATUS_DATA_LOST_REPAIR: ::NTSTATUS = 0x80000803u32 as i32; +pub const STATUS_CONTENT_BLOCKED: ::NTSTATUS = 0xC0000804u32 as i32; +pub const STATUS_BAD_CLUSTERS: ::NTSTATUS = 0xC0000805u32 as i32; +pub const STATUS_VOLUME_DIRTY: ::NTSTATUS = 0xC0000806u32 as i32; +pub const STATUS_DISK_REPAIR_REDIRECTED: ::NTSTATUS = 0x40000807; +pub const STATUS_DISK_REPAIR_UNSUCCESSFUL: ::NTSTATUS = 0xC0000808u32 as i32; +pub const STATUS_CORRUPT_LOG_OVERFULL: ::NTSTATUS = 0xC0000809u32 as i32; +pub const STATUS_CORRUPT_LOG_CORRUPTED: ::NTSTATUS = 0xC000080Au32 as i32; +pub const STATUS_CORRUPT_LOG_UNAVAILABLE: ::NTSTATUS = 0xC000080Bu32 as i32; +pub const STATUS_CORRUPT_LOG_DELETED_FULL: ::NTSTATUS = 0xC000080Cu32 as i32; +pub const STATUS_CORRUPT_LOG_CLEARED: ::NTSTATUS = 0xC000080Du32 as i32; +pub const STATUS_ORPHAN_NAME_EXHAUSTED: ::NTSTATUS = 0xC000080Eu32 as i32; +pub const STATUS_PROACTIVE_SCAN_IN_PROGRESS: ::NTSTATUS = 0xC000080Fu32 as i32; +pub const STATUS_ENCRYPTED_IO_NOT_POSSIBLE: ::NTSTATUS = 0xC0000810u32 as i32; +pub const STATUS_CORRUPT_LOG_UPLEVEL_RECORDS: ::NTSTATUS = 0xC0000811u32 as i32; +pub const STATUS_FILE_CHECKED_OUT: ::NTSTATUS = 0xC0000901u32 as i32; +pub const STATUS_CHECKOUT_REQUIRED: ::NTSTATUS = 0xC0000902u32 as i32; +pub const STATUS_BAD_FILE_TYPE: ::NTSTATUS = 0xC0000903u32 as i32; +pub const STATUS_FILE_TOO_LARGE: ::NTSTATUS = 0xC0000904u32 as i32; +pub const STATUS_FORMS_AUTH_REQUIRED: ::NTSTATUS = 0xC0000905u32 as i32; +pub const STATUS_VIRUS_INFECTED: ::NTSTATUS = 0xC0000906u32 as i32; +pub const STATUS_VIRUS_DELETED: ::NTSTATUS = 0xC0000907u32 as i32; +pub const STATUS_BAD_MCFG_TABLE: ::NTSTATUS = 0xC0000908u32 as i32; +pub const STATUS_CANNOT_BREAK_OPLOCK: ::NTSTATUS = 0xC0000909u32 as i32; +pub const STATUS_BAD_KEY: ::NTSTATUS = 0xC000090Au32 as i32; +pub const STATUS_BAD_DATA: ::NTSTATUS = 0xC000090Bu32 as i32; +pub const STATUS_NO_KEY: ::NTSTATUS = 0xC000090Cu32 as i32; +pub const STATUS_FILE_HANDLE_REVOKED: ::NTSTATUS = 0xC0000910u32 as i32; +pub const STATUS_WOW_ASSERTION: ::NTSTATUS = 0xC0009898u32 as i32; +pub const STATUS_INVALID_SIGNATURE: ::NTSTATUS = 0xC000A000u32 as i32; +pub const STATUS_HMAC_NOT_SUPPORTED: ::NTSTATUS = 0xC000A001u32 as i32; +pub const STATUS_AUTH_TAG_MISMATCH: ::NTSTATUS = 0xC000A002u32 as i32; +pub const STATUS_INVALID_STATE_TRANSITION: ::NTSTATUS = 0xC000A003u32 as i32; +pub const STATUS_INVALID_KERNEL_INFO_VERSION: ::NTSTATUS = 0xC000A004u32 as i32; +pub const STATUS_INVALID_PEP_INFO_VERSION: ::NTSTATUS = 0xC000A005u32 as i32; +pub const STATUS_HANDLE_REVOKED: ::NTSTATUS = 0xC000A006u32 as i32; +pub const STATUS_IPSEC_QUEUE_OVERFLOW: ::NTSTATUS = 0xC000A010u32 as i32; +pub const STATUS_ND_QUEUE_OVERFLOW: ::NTSTATUS = 0xC000A011u32 as i32; +pub const STATUS_HOPLIMIT_EXCEEDED: ::NTSTATUS = 0xC000A012u32 as i32; +pub const STATUS_PROTOCOL_NOT_SUPPORTED: ::NTSTATUS = 0xC000A013u32 as i32; +pub const STATUS_FASTPATH_REJECTED: ::NTSTATUS = 0xC000A014u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED: ::NTSTATUS = 0xC000A080u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR: ::NTSTATUS = 0xC000A081u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR: ::NTSTATUS = 0xC000A082u32 as i32; +pub const STATUS_XML_PARSE_ERROR: ::NTSTATUS = 0xC000A083u32 as i32; +pub const STATUS_XMLDSIG_ERROR: ::NTSTATUS = 0xC000A084u32 as i32; +pub const STATUS_WRONG_COMPARTMENT: ::NTSTATUS = 0xC000A085u32 as i32; +pub const STATUS_AUTHIP_FAILURE: ::NTSTATUS = 0xC000A086u32 as i32; +pub const STATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS: ::NTSTATUS = 0xC000A087u32 as i32; +pub const STATUS_DS_OID_NOT_FOUND: ::NTSTATUS = 0xC000A088u32 as i32; +pub const STATUS_INCORRECT_ACCOUNT_TYPE: ::NTSTATUS = 0xC000A089u32 as i32; +pub const STATUS_HASH_NOT_SUPPORTED: ::NTSTATUS = 0xC000A100u32 as i32; +pub const STATUS_HASH_NOT_PRESENT: ::NTSTATUS = 0xC000A101u32 as i32; +pub const STATUS_SECONDARY_IC_PROVIDER_NOT_REGISTERED: ::NTSTATUS = 0xC000A121u32 as i32; +pub const STATUS_GPIO_CLIENT_INFORMATION_INVALID: ::NTSTATUS = 0xC000A122u32 as i32; +pub const STATUS_GPIO_VERSION_NOT_SUPPORTED: ::NTSTATUS = 0xC000A123u32 as i32; +pub const STATUS_GPIO_INVALID_REGISTRATION_PACKET: ::NTSTATUS = 0xC000A124u32 as i32; +pub const STATUS_GPIO_OPERATION_DENIED: ::NTSTATUS = 0xC000A125u32 as i32; +pub const STATUS_GPIO_INCOMPATIBLE_CONNECT_MODE: ::NTSTATUS = 0xC000A126u32 as i32; +pub const STATUS_GPIO_INTERRUPT_ALREADY_UNMASKED: ::NTSTATUS = 0x8000A127u32 as i32; +pub const STATUS_CANNOT_SWITCH_RUNLEVEL: ::NTSTATUS = 0xC000A141u32 as i32; +pub const STATUS_INVALID_RUNLEVEL_SETTING: ::NTSTATUS = 0xC000A142u32 as i32; +pub const STATUS_RUNLEVEL_SWITCH_TIMEOUT: ::NTSTATUS = 0xC000A143u32 as i32; +pub const STATUS_SERVICES_FAILED_AUTOSTART: ::NTSTATUS = 0x4000A144; +pub const STATUS_RUNLEVEL_SWITCH_AGENT_TIMEOUT: ::NTSTATUS = 0xC000A145u32 as i32; +pub const STATUS_RUNLEVEL_SWITCH_IN_PROGRESS: ::NTSTATUS = 0xC000A146u32 as i32; +pub const STATUS_NOT_APPCONTAINER: ::NTSTATUS = 0xC000A200u32 as i32; +pub const STATUS_NOT_SUPPORTED_IN_APPCONTAINER: ::NTSTATUS = 0xC000A201u32 as i32; +pub const STATUS_INVALID_PACKAGE_SID_LENGTH: ::NTSTATUS = 0xC000A202u32 as i32; +pub const STATUS_APP_DATA_NOT_FOUND: ::NTSTATUS = 0xC000A281u32 as i32; +pub const STATUS_APP_DATA_EXPIRED: ::NTSTATUS = 0xC000A282u32 as i32; +pub const STATUS_APP_DATA_CORRUPT: ::NTSTATUS = 0xC000A283u32 as i32; +pub const STATUS_APP_DATA_LIMIT_EXCEEDED: ::NTSTATUS = 0xC000A284u32 as i32; +pub const STATUS_APP_DATA_REBOOT_REQUIRED: ::NTSTATUS = 0xC000A285u32 as i32; +pub const STATUS_OFFLOAD_READ_FLT_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A1u32 as i32; +pub const STATUS_OFFLOAD_WRITE_FLT_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A2u32 as i32; +pub const STATUS_OFFLOAD_READ_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A3u32 as i32; +pub const STATUS_OFFLOAD_WRITE_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A4u32 as i32; +pub const DBG_NO_STATE_CHANGE: ::NTSTATUS = 0xC0010001u32 as i32; +pub const DBG_APP_NOT_IDLE: ::NTSTATUS = 0xC0010002u32 as i32; +pub const RPC_NT_INVALID_STRING_BINDING: ::NTSTATUS = 0xC0020001u32 as i32; +pub const RPC_NT_WRONG_KIND_OF_BINDING: ::NTSTATUS = 0xC0020002u32 as i32; +pub const RPC_NT_INVALID_BINDING: ::NTSTATUS = 0xC0020003u32 as i32; +pub const RPC_NT_PROTSEQ_NOT_SUPPORTED: ::NTSTATUS = 0xC0020004u32 as i32; +pub const RPC_NT_INVALID_RPC_PROTSEQ: ::NTSTATUS = 0xC0020005u32 as i32; +pub const RPC_NT_INVALID_STRING_UUID: ::NTSTATUS = 0xC0020006u32 as i32; +pub const RPC_NT_INVALID_ENDPOINT_FORMAT: ::NTSTATUS = 0xC0020007u32 as i32; +pub const RPC_NT_INVALID_NET_ADDR: ::NTSTATUS = 0xC0020008u32 as i32; +pub const RPC_NT_NO_ENDPOINT_FOUND: ::NTSTATUS = 0xC0020009u32 as i32; +pub const RPC_NT_INVALID_TIMEOUT: ::NTSTATUS = 0xC002000Au32 as i32; +pub const RPC_NT_OBJECT_NOT_FOUND: ::NTSTATUS = 0xC002000Bu32 as i32; +pub const RPC_NT_ALREADY_REGISTERED: ::NTSTATUS = 0xC002000Cu32 as i32; +pub const RPC_NT_TYPE_ALREADY_REGISTERED: ::NTSTATUS = 0xC002000Du32 as i32; +pub const RPC_NT_ALREADY_LISTENING: ::NTSTATUS = 0xC002000Eu32 as i32; +pub const RPC_NT_NO_PROTSEQS_REGISTERED: ::NTSTATUS = 0xC002000Fu32 as i32; +pub const RPC_NT_NOT_LISTENING: ::NTSTATUS = 0xC0020010u32 as i32; +pub const RPC_NT_UNKNOWN_MGR_TYPE: ::NTSTATUS = 0xC0020011u32 as i32; +pub const RPC_NT_UNKNOWN_IF: ::NTSTATUS = 0xC0020012u32 as i32; +pub const RPC_NT_NO_BINDINGS: ::NTSTATUS = 0xC0020013u32 as i32; +pub const RPC_NT_NO_PROTSEQS: ::NTSTATUS = 0xC0020014u32 as i32; +pub const RPC_NT_CANT_CREATE_ENDPOINT: ::NTSTATUS = 0xC0020015u32 as i32; +pub const RPC_NT_OUT_OF_RESOURCES: ::NTSTATUS = 0xC0020016u32 as i32; +pub const RPC_NT_SERVER_UNAVAILABLE: ::NTSTATUS = 0xC0020017u32 as i32; +pub const RPC_NT_SERVER_TOO_BUSY: ::NTSTATUS = 0xC0020018u32 as i32; +pub const RPC_NT_INVALID_NETWORK_OPTIONS: ::NTSTATUS = 0xC0020019u32 as i32; +pub const RPC_NT_NO_CALL_ACTIVE: ::NTSTATUS = 0xC002001Au32 as i32; +pub const RPC_NT_CALL_FAILED: ::NTSTATUS = 0xC002001Bu32 as i32; +pub const RPC_NT_CALL_FAILED_DNE: ::NTSTATUS = 0xC002001Cu32 as i32; +pub const RPC_NT_PROTOCOL_ERROR: ::NTSTATUS = 0xC002001Du32 as i32; +pub const RPC_NT_UNSUPPORTED_TRANS_SYN: ::NTSTATUS = 0xC002001Fu32 as i32; +pub const RPC_NT_UNSUPPORTED_TYPE: ::NTSTATUS = 0xC0020021u32 as i32; +pub const RPC_NT_INVALID_TAG: ::NTSTATUS = 0xC0020022u32 as i32; +pub const RPC_NT_INVALID_BOUND: ::NTSTATUS = 0xC0020023u32 as i32; +pub const RPC_NT_NO_ENTRY_NAME: ::NTSTATUS = 0xC0020024u32 as i32; +pub const RPC_NT_INVALID_NAME_SYNTAX: ::NTSTATUS = 0xC0020025u32 as i32; +pub const RPC_NT_UNSUPPORTED_NAME_SYNTAX: ::NTSTATUS = 0xC0020026u32 as i32; +pub const RPC_NT_UUID_NO_ADDRESS: ::NTSTATUS = 0xC0020028u32 as i32; +pub const RPC_NT_DUPLICATE_ENDPOINT: ::NTSTATUS = 0xC0020029u32 as i32; +pub const RPC_NT_UNKNOWN_AUTHN_TYPE: ::NTSTATUS = 0xC002002Au32 as i32; +pub const RPC_NT_MAX_CALLS_TOO_SMALL: ::NTSTATUS = 0xC002002Bu32 as i32; +pub const RPC_NT_STRING_TOO_LONG: ::NTSTATUS = 0xC002002Cu32 as i32; +pub const RPC_NT_PROTSEQ_NOT_FOUND: ::NTSTATUS = 0xC002002Du32 as i32; +pub const RPC_NT_PROCNUM_OUT_OF_RANGE: ::NTSTATUS = 0xC002002Eu32 as i32; +pub const RPC_NT_BINDING_HAS_NO_AUTH: ::NTSTATUS = 0xC002002Fu32 as i32; +pub const RPC_NT_UNKNOWN_AUTHN_SERVICE: ::NTSTATUS = 0xC0020030u32 as i32; +pub const RPC_NT_UNKNOWN_AUTHN_LEVEL: ::NTSTATUS = 0xC0020031u32 as i32; +pub const RPC_NT_INVALID_AUTH_IDENTITY: ::NTSTATUS = 0xC0020032u32 as i32; +pub const RPC_NT_UNKNOWN_AUTHZ_SERVICE: ::NTSTATUS = 0xC0020033u32 as i32; +pub const EPT_NT_INVALID_ENTRY: ::NTSTATUS = 0xC0020034u32 as i32; +pub const EPT_NT_CANT_PERFORM_OP: ::NTSTATUS = 0xC0020035u32 as i32; +pub const EPT_NT_NOT_REGISTERED: ::NTSTATUS = 0xC0020036u32 as i32; +pub const RPC_NT_NOTHING_TO_EXPORT: ::NTSTATUS = 0xC0020037u32 as i32; +pub const RPC_NT_INCOMPLETE_NAME: ::NTSTATUS = 0xC0020038u32 as i32; +pub const RPC_NT_INVALID_VERS_OPTION: ::NTSTATUS = 0xC0020039u32 as i32; +pub const RPC_NT_NO_MORE_MEMBERS: ::NTSTATUS = 0xC002003Au32 as i32; +pub const RPC_NT_NOT_ALL_OBJS_UNEXPORTED: ::NTSTATUS = 0xC002003Bu32 as i32; +pub const RPC_NT_INTERFACE_NOT_FOUND: ::NTSTATUS = 0xC002003Cu32 as i32; +pub const RPC_NT_ENTRY_ALREADY_EXISTS: ::NTSTATUS = 0xC002003Du32 as i32; +pub const RPC_NT_ENTRY_NOT_FOUND: ::NTSTATUS = 0xC002003Eu32 as i32; +pub const RPC_NT_NAME_SERVICE_UNAVAILABLE: ::NTSTATUS = 0xC002003Fu32 as i32; +pub const RPC_NT_INVALID_NAF_ID: ::NTSTATUS = 0xC0020040u32 as i32; +pub const RPC_NT_CANNOT_SUPPORT: ::NTSTATUS = 0xC0020041u32 as i32; +pub const RPC_NT_NO_CONTEXT_AVAILABLE: ::NTSTATUS = 0xC0020042u32 as i32; +pub const RPC_NT_INTERNAL_ERROR: ::NTSTATUS = 0xC0020043u32 as i32; +pub const RPC_NT_ZERO_DIVIDE: ::NTSTATUS = 0xC0020044u32 as i32; +pub const RPC_NT_ADDRESS_ERROR: ::NTSTATUS = 0xC0020045u32 as i32; +pub const RPC_NT_FP_DIV_ZERO: ::NTSTATUS = 0xC0020046u32 as i32; +pub const RPC_NT_FP_UNDERFLOW: ::NTSTATUS = 0xC0020047u32 as i32; +pub const RPC_NT_FP_OVERFLOW: ::NTSTATUS = 0xC0020048u32 as i32; +pub const RPC_NT_NO_MORE_ENTRIES: ::NTSTATUS = 0xC0030001u32 as i32; +pub const RPC_NT_SS_CHAR_TRANS_OPEN_FAIL: ::NTSTATUS = 0xC0030002u32 as i32; +pub const RPC_NT_SS_CHAR_TRANS_SHORT_FILE: ::NTSTATUS = 0xC0030003u32 as i32; +pub const RPC_NT_SS_IN_NULL_CONTEXT: ::NTSTATUS = 0xC0030004u32 as i32; +pub const RPC_NT_SS_CONTEXT_MISMATCH: ::NTSTATUS = 0xC0030005u32 as i32; +pub const RPC_NT_SS_CONTEXT_DAMAGED: ::NTSTATUS = 0xC0030006u32 as i32; +pub const RPC_NT_SS_HANDLES_MISMATCH: ::NTSTATUS = 0xC0030007u32 as i32; +pub const RPC_NT_SS_CANNOT_GET_CALL_HANDLE: ::NTSTATUS = 0xC0030008u32 as i32; +pub const RPC_NT_NULL_REF_POINTER: ::NTSTATUS = 0xC0030009u32 as i32; +pub const RPC_NT_ENUM_VALUE_OUT_OF_RANGE: ::NTSTATUS = 0xC003000Au32 as i32; +pub const RPC_NT_BYTE_COUNT_TOO_SMALL: ::NTSTATUS = 0xC003000Bu32 as i32; +pub const RPC_NT_BAD_STUB_DATA: ::NTSTATUS = 0xC003000Cu32 as i32; +pub const RPC_NT_CALL_IN_PROGRESS: ::NTSTATUS = 0xC0020049u32 as i32; +pub const RPC_NT_NO_MORE_BINDINGS: ::NTSTATUS = 0xC002004Au32 as i32; +pub const RPC_NT_GROUP_MEMBER_NOT_FOUND: ::NTSTATUS = 0xC002004Bu32 as i32; +pub const EPT_NT_CANT_CREATE: ::NTSTATUS = 0xC002004Cu32 as i32; +pub const RPC_NT_INVALID_OBJECT: ::NTSTATUS = 0xC002004Du32 as i32; +pub const RPC_NT_NO_INTERFACES: ::NTSTATUS = 0xC002004Fu32 as i32; +pub const RPC_NT_CALL_CANCELLED: ::NTSTATUS = 0xC0020050u32 as i32; +pub const RPC_NT_BINDING_INCOMPLETE: ::NTSTATUS = 0xC0020051u32 as i32; +pub const RPC_NT_COMM_FAILURE: ::NTSTATUS = 0xC0020052u32 as i32; +pub const RPC_NT_UNSUPPORTED_AUTHN_LEVEL: ::NTSTATUS = 0xC0020053u32 as i32; +pub const RPC_NT_NO_PRINC_NAME: ::NTSTATUS = 0xC0020054u32 as i32; +pub const RPC_NT_NOT_RPC_ERROR: ::NTSTATUS = 0xC0020055u32 as i32; +pub const RPC_NT_UUID_LOCAL_ONLY: ::NTSTATUS = 0x40020056; +pub const RPC_NT_SEC_PKG_ERROR: ::NTSTATUS = 0xC0020057u32 as i32; +pub const RPC_NT_NOT_CANCELLED: ::NTSTATUS = 0xC0020058u32 as i32; +pub const RPC_NT_INVALID_ES_ACTION: ::NTSTATUS = 0xC0030059u32 as i32; +pub const RPC_NT_WRONG_ES_VERSION: ::NTSTATUS = 0xC003005Au32 as i32; +pub const RPC_NT_WRONG_STUB_VERSION: ::NTSTATUS = 0xC003005Bu32 as i32; +pub const RPC_NT_INVALID_PIPE_OBJECT: ::NTSTATUS = 0xC003005Cu32 as i32; +pub const RPC_NT_INVALID_PIPE_OPERATION: ::NTSTATUS = 0xC003005Du32 as i32; +pub const RPC_NT_WRONG_PIPE_VERSION: ::NTSTATUS = 0xC003005Eu32 as i32; +pub const RPC_NT_PIPE_CLOSED: ::NTSTATUS = 0xC003005Fu32 as i32; +pub const RPC_NT_PIPE_DISCIPLINE_ERROR: ::NTSTATUS = 0xC0030060u32 as i32; +pub const RPC_NT_PIPE_EMPTY: ::NTSTATUS = 0xC0030061u32 as i32; +pub const RPC_NT_INVALID_ASYNC_HANDLE: ::NTSTATUS = 0xC0020062u32 as i32; +pub const RPC_NT_INVALID_ASYNC_CALL: ::NTSTATUS = 0xC0020063u32 as i32; +pub const RPC_NT_PROXY_ACCESS_DENIED: ::NTSTATUS = 0xC0020064u32 as i32; +pub const RPC_NT_COOKIE_AUTH_FAILED: ::NTSTATUS = 0xC0020065u32 as i32; +pub const RPC_NT_SEND_INCOMPLETE: ::NTSTATUS = 0x400200AF; +pub const STATUS_ACPI_INVALID_OPCODE: ::NTSTATUS = 0xC0140001u32 as i32; +pub const STATUS_ACPI_STACK_OVERFLOW: ::NTSTATUS = 0xC0140002u32 as i32; +pub const STATUS_ACPI_ASSERT_FAILED: ::NTSTATUS = 0xC0140003u32 as i32; +pub const STATUS_ACPI_INVALID_INDEX: ::NTSTATUS = 0xC0140004u32 as i32; +pub const STATUS_ACPI_INVALID_ARGUMENT: ::NTSTATUS = 0xC0140005u32 as i32; +pub const STATUS_ACPI_FATAL: ::NTSTATUS = 0xC0140006u32 as i32; +pub const STATUS_ACPI_INVALID_SUPERNAME: ::NTSTATUS = 0xC0140007u32 as i32; +pub const STATUS_ACPI_INVALID_ARGTYPE: ::NTSTATUS = 0xC0140008u32 as i32; +pub const STATUS_ACPI_INVALID_OBJTYPE: ::NTSTATUS = 0xC0140009u32 as i32; +pub const STATUS_ACPI_INVALID_TARGETTYPE: ::NTSTATUS = 0xC014000Au32 as i32; +pub const STATUS_ACPI_INCORRECT_ARGUMENT_COUNT: ::NTSTATUS = 0xC014000Bu32 as i32; +pub const STATUS_ACPI_ADDRESS_NOT_MAPPED: ::NTSTATUS = 0xC014000Cu32 as i32; +pub const STATUS_ACPI_INVALID_EVENTTYPE: ::NTSTATUS = 0xC014000Du32 as i32; +pub const STATUS_ACPI_HANDLER_COLLISION: ::NTSTATUS = 0xC014000Eu32 as i32; +pub const STATUS_ACPI_INVALID_DATA: ::NTSTATUS = 0xC014000Fu32 as i32; +pub const STATUS_ACPI_INVALID_REGION: ::NTSTATUS = 0xC0140010u32 as i32; +pub const STATUS_ACPI_INVALID_ACCESS_SIZE: ::NTSTATUS = 0xC0140011u32 as i32; +pub const STATUS_ACPI_ACQUIRE_GLOBAL_LOCK: ::NTSTATUS = 0xC0140012u32 as i32; +pub const STATUS_ACPI_ALREADY_INITIALIZED: ::NTSTATUS = 0xC0140013u32 as i32; +pub const STATUS_ACPI_NOT_INITIALIZED: ::NTSTATUS = 0xC0140014u32 as i32; +pub const STATUS_ACPI_INVALID_MUTEX_LEVEL: ::NTSTATUS = 0xC0140015u32 as i32; +pub const STATUS_ACPI_MUTEX_NOT_OWNED: ::NTSTATUS = 0xC0140016u32 as i32; +pub const STATUS_ACPI_MUTEX_NOT_OWNER: ::NTSTATUS = 0xC0140017u32 as i32; +pub const STATUS_ACPI_RS_ACCESS: ::NTSTATUS = 0xC0140018u32 as i32; +pub const STATUS_ACPI_INVALID_TABLE: ::NTSTATUS = 0xC0140019u32 as i32; +pub const STATUS_ACPI_REG_HANDLER_FAILED: ::NTSTATUS = 0xC0140020u32 as i32; +pub const STATUS_ACPI_POWER_REQUEST_FAILED: ::NTSTATUS = 0xC0140021u32 as i32; +pub const STATUS_CTX_WINSTATION_NAME_INVALID: ::NTSTATUS = 0xC00A0001u32 as i32; +pub const STATUS_CTX_INVALID_PD: ::NTSTATUS = 0xC00A0002u32 as i32; +pub const STATUS_CTX_PD_NOT_FOUND: ::NTSTATUS = 0xC00A0003u32 as i32; +pub const STATUS_CTX_CDM_CONNECT: ::NTSTATUS = 0x400A0004; +pub const STATUS_CTX_CDM_DISCONNECT: ::NTSTATUS = 0x400A0005; +pub const STATUS_CTX_CLOSE_PENDING: ::NTSTATUS = 0xC00A0006u32 as i32; +pub const STATUS_CTX_NO_OUTBUF: ::NTSTATUS = 0xC00A0007u32 as i32; +pub const STATUS_CTX_MODEM_INF_NOT_FOUND: ::NTSTATUS = 0xC00A0008u32 as i32; +pub const STATUS_CTX_INVALID_MODEMNAME: ::NTSTATUS = 0xC00A0009u32 as i32; +pub const STATUS_CTX_RESPONSE_ERROR: ::NTSTATUS = 0xC00A000Au32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_TIMEOUT: ::NTSTATUS = 0xC00A000Bu32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_NO_CARRIER: ::NTSTATUS = 0xC00A000Cu32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_NO_DIALTONE: ::NTSTATUS = 0xC00A000Du32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_BUSY: ::NTSTATUS = 0xC00A000Eu32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_VOICE: ::NTSTATUS = 0xC00A000Fu32 as i32; +pub const STATUS_CTX_TD_ERROR: ::NTSTATUS = 0xC00A0010u32 as i32; +pub const STATUS_CTX_LICENSE_CLIENT_INVALID: ::NTSTATUS = 0xC00A0012u32 as i32; +pub const STATUS_CTX_LICENSE_NOT_AVAILABLE: ::NTSTATUS = 0xC00A0013u32 as i32; +pub const STATUS_CTX_LICENSE_EXPIRED: ::NTSTATUS = 0xC00A0014u32 as i32; +pub const STATUS_CTX_WINSTATION_NOT_FOUND: ::NTSTATUS = 0xC00A0015u32 as i32; +pub const STATUS_CTX_WINSTATION_NAME_COLLISION: ::NTSTATUS = 0xC00A0016u32 as i32; +pub const STATUS_CTX_WINSTATION_BUSY: ::NTSTATUS = 0xC00A0017u32 as i32; +pub const STATUS_CTX_BAD_VIDEO_MODE: ::NTSTATUS = 0xC00A0018u32 as i32; +pub const STATUS_CTX_GRAPHICS_INVALID: ::NTSTATUS = 0xC00A0022u32 as i32; +pub const STATUS_CTX_NOT_CONSOLE: ::NTSTATUS = 0xC00A0024u32 as i32; +pub const STATUS_CTX_CLIENT_QUERY_TIMEOUT: ::NTSTATUS = 0xC00A0026u32 as i32; +pub const STATUS_CTX_CONSOLE_DISCONNECT: ::NTSTATUS = 0xC00A0027u32 as i32; +pub const STATUS_CTX_CONSOLE_CONNECT: ::NTSTATUS = 0xC00A0028u32 as i32; +pub const STATUS_CTX_SHADOW_DENIED: ::NTSTATUS = 0xC00A002Au32 as i32; +pub const STATUS_CTX_WINSTATION_ACCESS_DENIED: ::NTSTATUS = 0xC00A002Bu32 as i32; +pub const STATUS_CTX_INVALID_WD: ::NTSTATUS = 0xC00A002Eu32 as i32; +pub const STATUS_CTX_WD_NOT_FOUND: ::NTSTATUS = 0xC00A002Fu32 as i32; +pub const STATUS_CTX_SHADOW_INVALID: ::NTSTATUS = 0xC00A0030u32 as i32; +pub const STATUS_CTX_SHADOW_DISABLED: ::NTSTATUS = 0xC00A0031u32 as i32; +pub const STATUS_RDP_PROTOCOL_ERROR: ::NTSTATUS = 0xC00A0032u32 as i32; +pub const STATUS_CTX_CLIENT_LICENSE_NOT_SET: ::NTSTATUS = 0xC00A0033u32 as i32; +pub const STATUS_CTX_CLIENT_LICENSE_IN_USE: ::NTSTATUS = 0xC00A0034u32 as i32; +pub const STATUS_CTX_SHADOW_ENDED_BY_MODE_CHANGE: ::NTSTATUS = 0xC00A0035u32 as i32; +pub const STATUS_CTX_SHADOW_NOT_RUNNING: ::NTSTATUS = 0xC00A0036u32 as i32; +pub const STATUS_CTX_LOGON_DISABLED: ::NTSTATUS = 0xC00A0037u32 as i32; +pub const STATUS_CTX_SECURITY_LAYER_ERROR: ::NTSTATUS = 0xC00A0038u32 as i32; +pub const STATUS_TS_INCOMPATIBLE_SESSIONS: ::NTSTATUS = 0xC00A0039u32 as i32; +pub const STATUS_TS_VIDEO_SUBSYSTEM_ERROR: ::NTSTATUS = 0xC00A003Au32 as i32; +pub const STATUS_PNP_BAD_MPS_TABLE: ::NTSTATUS = 0xC0040035u32 as i32; +pub const STATUS_PNP_TRANSLATION_FAILED: ::NTSTATUS = 0xC0040036u32 as i32; +pub const STATUS_PNP_IRQ_TRANSLATION_FAILED: ::NTSTATUS = 0xC0040037u32 as i32; +pub const STATUS_PNP_INVALID_ID: ::NTSTATUS = 0xC0040038u32 as i32; +pub const STATUS_IO_REISSUE_AS_CACHED: ::NTSTATUS = 0xC0040039u32 as i32; +pub const STATUS_MUI_FILE_NOT_FOUND: ::NTSTATUS = 0xC00B0001u32 as i32; +pub const STATUS_MUI_INVALID_FILE: ::NTSTATUS = 0xC00B0002u32 as i32; +pub const STATUS_MUI_INVALID_RC_CONFIG: ::NTSTATUS = 0xC00B0003u32 as i32; +pub const STATUS_MUI_INVALID_LOCALE_NAME: ::NTSTATUS = 0xC00B0004u32 as i32; +pub const STATUS_MUI_INVALID_ULTIMATEFALLBACK_NAME: ::NTSTATUS = 0xC00B0005u32 as i32; +pub const STATUS_MUI_FILE_NOT_LOADED: ::NTSTATUS = 0xC00B0006u32 as i32; +pub const STATUS_RESOURCE_ENUM_USER_STOP: ::NTSTATUS = 0xC00B0007u32 as i32; +pub const STATUS_FLT_NO_HANDLER_DEFINED: ::NTSTATUS = 0xC01C0001u32 as i32; +pub const STATUS_FLT_CONTEXT_ALREADY_DEFINED: ::NTSTATUS = 0xC01C0002u32 as i32; +pub const STATUS_FLT_INVALID_ASYNCHRONOUS_REQUEST: ::NTSTATUS = 0xC01C0003u32 as i32; +pub const STATUS_FLT_DISALLOW_FAST_IO: ::NTSTATUS = 0xC01C0004u32 as i32; +pub const STATUS_FLT_INVALID_NAME_REQUEST: ::NTSTATUS = 0xC01C0005u32 as i32; +pub const STATUS_FLT_NOT_SAFE_TO_POST_OPERATION: ::NTSTATUS = 0xC01C0006u32 as i32; +pub const STATUS_FLT_NOT_INITIALIZED: ::NTSTATUS = 0xC01C0007u32 as i32; +pub const STATUS_FLT_FILTER_NOT_READY: ::NTSTATUS = 0xC01C0008u32 as i32; +pub const STATUS_FLT_POST_OPERATION_CLEANUP: ::NTSTATUS = 0xC01C0009u32 as i32; +pub const STATUS_FLT_INTERNAL_ERROR: ::NTSTATUS = 0xC01C000Au32 as i32; +pub const STATUS_FLT_DELETING_OBJECT: ::NTSTATUS = 0xC01C000Bu32 as i32; +pub const STATUS_FLT_MUST_BE_NONPAGED_POOL: ::NTSTATUS = 0xC01C000Cu32 as i32; +pub const STATUS_FLT_DUPLICATE_ENTRY: ::NTSTATUS = 0xC01C000Du32 as i32; +pub const STATUS_FLT_CBDQ_DISABLED: ::NTSTATUS = 0xC01C000Eu32 as i32; +pub const STATUS_FLT_DO_NOT_ATTACH: ::NTSTATUS = 0xC01C000Fu32 as i32; +pub const STATUS_FLT_DO_NOT_DETACH: ::NTSTATUS = 0xC01C0010u32 as i32; +pub const STATUS_FLT_INSTANCE_ALTITUDE_COLLISION: ::NTSTATUS = 0xC01C0011u32 as i32; +pub const STATUS_FLT_INSTANCE_NAME_COLLISION: ::NTSTATUS = 0xC01C0012u32 as i32; +pub const STATUS_FLT_FILTER_NOT_FOUND: ::NTSTATUS = 0xC01C0013u32 as i32; +pub const STATUS_FLT_VOLUME_NOT_FOUND: ::NTSTATUS = 0xC01C0014u32 as i32; +pub const STATUS_FLT_INSTANCE_NOT_FOUND: ::NTSTATUS = 0xC01C0015u32 as i32; +pub const STATUS_FLT_CONTEXT_ALLOCATION_NOT_FOUND: ::NTSTATUS = 0xC01C0016u32 as i32; +pub const STATUS_FLT_INVALID_CONTEXT_REGISTRATION: ::NTSTATUS = 0xC01C0017u32 as i32; +pub const STATUS_FLT_NAME_CACHE_MISS: ::NTSTATUS = 0xC01C0018u32 as i32; +pub const STATUS_FLT_NO_DEVICE_OBJECT: ::NTSTATUS = 0xC01C0019u32 as i32; +pub const STATUS_FLT_VOLUME_ALREADY_MOUNTED: ::NTSTATUS = 0xC01C001Au32 as i32; +pub const STATUS_FLT_ALREADY_ENLISTED: ::NTSTATUS = 0xC01C001Bu32 as i32; +pub const STATUS_FLT_CONTEXT_ALREADY_LINKED: ::NTSTATUS = 0xC01C001Cu32 as i32; +pub const STATUS_FLT_NO_WAITER_FOR_REPLY: ::NTSTATUS = 0xC01C0020u32 as i32; +pub const STATUS_FLT_REGISTRATION_BUSY: ::NTSTATUS = 0xC01C0023u32 as i32; +pub const STATUS_SXS_SECTION_NOT_FOUND: ::NTSTATUS = 0xC0150001u32 as i32; +pub const STATUS_SXS_CANT_GEN_ACTCTX: ::NTSTATUS = 0xC0150002u32 as i32; +pub const STATUS_SXS_INVALID_ACTCTXDATA_FORMAT: ::NTSTATUS = 0xC0150003u32 as i32; +pub const STATUS_SXS_ASSEMBLY_NOT_FOUND: ::NTSTATUS = 0xC0150004u32 as i32; +pub const STATUS_SXS_MANIFEST_FORMAT_ERROR: ::NTSTATUS = 0xC0150005u32 as i32; +pub const STATUS_SXS_MANIFEST_PARSE_ERROR: ::NTSTATUS = 0xC0150006u32 as i32; +pub const STATUS_SXS_ACTIVATION_CONTEXT_DISABLED: ::NTSTATUS = 0xC0150007u32 as i32; +pub const STATUS_SXS_KEY_NOT_FOUND: ::NTSTATUS = 0xC0150008u32 as i32; +pub const STATUS_SXS_VERSION_CONFLICT: ::NTSTATUS = 0xC0150009u32 as i32; +pub const STATUS_SXS_WRONG_SECTION_TYPE: ::NTSTATUS = 0xC015000Au32 as i32; +pub const STATUS_SXS_THREAD_QUERIES_DISABLED: ::NTSTATUS = 0xC015000Bu32 as i32; +pub const STATUS_SXS_ASSEMBLY_MISSING: ::NTSTATUS = 0xC015000Cu32 as i32; +pub const STATUS_SXS_RELEASE_ACTIVATION_CONTEXT: ::NTSTATUS = 0x4015000D; +pub const STATUS_SXS_PROCESS_DEFAULT_ALREADY_SET: ::NTSTATUS = 0xC015000Eu32 as i32; +pub const STATUS_SXS_EARLY_DEACTIVATION: ::NTSTATUS = 0xC015000Fu32 as i32; +pub const STATUS_SXS_INVALID_DEACTIVATION: ::NTSTATUS = 0xC0150010u32 as i32; +pub const STATUS_SXS_MULTIPLE_DEACTIVATION: ::NTSTATUS = 0xC0150011u32 as i32; +pub const STATUS_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: ::NTSTATUS = 0xC0150012u32 as i32; +pub const STATUS_SXS_PROCESS_TERMINATION_REQUESTED: ::NTSTATUS = 0xC0150013u32 as i32; +pub const STATUS_SXS_CORRUPT_ACTIVATION_STACK: ::NTSTATUS = 0xC0150014u32 as i32; +pub const STATUS_SXS_CORRUPTION: ::NTSTATUS = 0xC0150015u32 as i32; +pub const STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: ::NTSTATUS = 0xC0150016u32 as i32; +pub const STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: ::NTSTATUS = 0xC0150017u32 as i32; +pub const STATUS_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: ::NTSTATUS = 0xC0150018u32 as i32; +pub const STATUS_SXS_IDENTITY_PARSE_ERROR: ::NTSTATUS = 0xC0150019u32 as i32; +pub const STATUS_SXS_COMPONENT_STORE_CORRUPT: ::NTSTATUS = 0xC015001Au32 as i32; +pub const STATUS_SXS_FILE_HASH_MISMATCH: ::NTSTATUS = 0xC015001Bu32 as i32; +pub const STATUS_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: ::NTSTATUS = 0xC015001Cu32 as i32; +pub const STATUS_SXS_IDENTITIES_DIFFERENT: ::NTSTATUS = 0xC015001Du32 as i32; +pub const STATUS_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: ::NTSTATUS = 0xC015001Eu32 as i32; +pub const STATUS_SXS_FILE_NOT_PART_OF_ASSEMBLY: ::NTSTATUS = 0xC015001Fu32 as i32; +pub const STATUS_ADVANCED_INSTALLER_FAILED: ::NTSTATUS = 0xC0150020u32 as i32; +pub const STATUS_XML_ENCODING_MISMATCH: ::NTSTATUS = 0xC0150021u32 as i32; +pub const STATUS_SXS_MANIFEST_TOO_BIG: ::NTSTATUS = 0xC0150022u32 as i32; +pub const STATUS_SXS_SETTING_NOT_REGISTERED: ::NTSTATUS = 0xC0150023u32 as i32; +pub const STATUS_SXS_TRANSACTION_CLOSURE_INCOMPLETE: ::NTSTATUS = 0xC0150024u32 as i32; +pub const STATUS_SMI_PRIMITIVE_INSTALLER_FAILED: ::NTSTATUS = 0xC0150025u32 as i32; +pub const STATUS_GENERIC_COMMAND_FAILED: ::NTSTATUS = 0xC0150026u32 as i32; +pub const STATUS_SXS_FILE_HASH_MISSING: ::NTSTATUS = 0xC0150027u32 as i32; +pub const STATUS_CLUSTER_INVALID_NODE: ::NTSTATUS = 0xC0130001u32 as i32; +pub const STATUS_CLUSTER_NODE_EXISTS: ::NTSTATUS = 0xC0130002u32 as i32; +pub const STATUS_CLUSTER_JOIN_IN_PROGRESS: ::NTSTATUS = 0xC0130003u32 as i32; +pub const STATUS_CLUSTER_NODE_NOT_FOUND: ::NTSTATUS = 0xC0130004u32 as i32; +pub const STATUS_CLUSTER_LOCAL_NODE_NOT_FOUND: ::NTSTATUS = 0xC0130005u32 as i32; +pub const STATUS_CLUSTER_NETWORK_EXISTS: ::NTSTATUS = 0xC0130006u32 as i32; +pub const STATUS_CLUSTER_NETWORK_NOT_FOUND: ::NTSTATUS = 0xC0130007u32 as i32; +pub const STATUS_CLUSTER_NETINTERFACE_EXISTS: ::NTSTATUS = 0xC0130008u32 as i32; +pub const STATUS_CLUSTER_NETINTERFACE_NOT_FOUND: ::NTSTATUS = 0xC0130009u32 as i32; +pub const STATUS_CLUSTER_INVALID_REQUEST: ::NTSTATUS = 0xC013000Au32 as i32; +pub const STATUS_CLUSTER_INVALID_NETWORK_PROVIDER: ::NTSTATUS = 0xC013000Bu32 as i32; +pub const STATUS_CLUSTER_NODE_DOWN: ::NTSTATUS = 0xC013000Cu32 as i32; +pub const STATUS_CLUSTER_NODE_UNREACHABLE: ::NTSTATUS = 0xC013000Du32 as i32; +pub const STATUS_CLUSTER_NODE_NOT_MEMBER: ::NTSTATUS = 0xC013000Eu32 as i32; +pub const STATUS_CLUSTER_JOIN_NOT_IN_PROGRESS: ::NTSTATUS = 0xC013000Fu32 as i32; +pub const STATUS_CLUSTER_INVALID_NETWORK: ::NTSTATUS = 0xC0130010u32 as i32; +pub const STATUS_CLUSTER_NO_NET_ADAPTERS: ::NTSTATUS = 0xC0130011u32 as i32; +pub const STATUS_CLUSTER_NODE_UP: ::NTSTATUS = 0xC0130012u32 as i32; +pub const STATUS_CLUSTER_NODE_PAUSED: ::NTSTATUS = 0xC0130013u32 as i32; +pub const STATUS_CLUSTER_NODE_NOT_PAUSED: ::NTSTATUS = 0xC0130014u32 as i32; +pub const STATUS_CLUSTER_NO_SECURITY_CONTEXT: ::NTSTATUS = 0xC0130015u32 as i32; +pub const STATUS_CLUSTER_NETWORK_NOT_INTERNAL: ::NTSTATUS = 0xC0130016u32 as i32; +pub const STATUS_CLUSTER_POISONED: ::NTSTATUS = 0xC0130017u32 as i32; +pub const STATUS_CLUSTER_NON_CSV_PATH: ::NTSTATUS = 0xC0130018u32 as i32; +pub const STATUS_CLUSTER_CSV_VOLUME_NOT_LOCAL: ::NTSTATUS = 0xC0130019u32 as i32; +pub const STATUS_CLUSTER_CSV_READ_OPLOCK_BREAK_IN_PROGRESS: ::NTSTATUS = 0xC0130020u32 as i32; +pub const STATUS_CLUSTER_CSV_AUTO_PAUSE_ERROR: ::NTSTATUS = 0xC0130021u32 as i32; +pub const STATUS_CLUSTER_CSV_REDIRECTED: ::NTSTATUS = 0xC0130022u32 as i32; +pub const STATUS_CLUSTER_CSV_NOT_REDIRECTED: ::NTSTATUS = 0xC0130023u32 as i32; +pub const STATUS_CLUSTER_CSV_VOLUME_DRAINING: ::NTSTATUS = 0xC0130024u32 as i32; +pub const STATUS_CLUSTER_CSV_SNAPSHOT_CREATION_IN_PROGRESS: ::NTSTATUS = 0xC0130025u32 as i32; +pub const STATUS_CLUSTER_CSV_VOLUME_DRAINING_SUCCEEDED_DOWNLEVEL: ::NTSTATUS = 0xC0130026u32 as i32; +pub const STATUS_CLUSTER_CSV_NO_SNAPSHOTS: ::NTSTATUS = 0xC0130027u32 as i32; +pub const STATUS_CSV_IO_PAUSE_TIMEOUT: ::NTSTATUS = 0xC0130028u32 as i32; +pub const STATUS_TRANSACTIONAL_CONFLICT: ::NTSTATUS = 0xC0190001u32 as i32; +pub const STATUS_INVALID_TRANSACTION: ::NTSTATUS = 0xC0190002u32 as i32; +pub const STATUS_TRANSACTION_NOT_ACTIVE: ::NTSTATUS = 0xC0190003u32 as i32; +pub const STATUS_TM_INITIALIZATION_FAILED: ::NTSTATUS = 0xC0190004u32 as i32; +pub const STATUS_RM_NOT_ACTIVE: ::NTSTATUS = 0xC0190005u32 as i32; +pub const STATUS_RM_METADATA_CORRUPT: ::NTSTATUS = 0xC0190006u32 as i32; +pub const STATUS_TRANSACTION_NOT_JOINED: ::NTSTATUS = 0xC0190007u32 as i32; +pub const STATUS_DIRECTORY_NOT_RM: ::NTSTATUS = 0xC0190008u32 as i32; +pub const STATUS_COULD_NOT_RESIZE_LOG: ::NTSTATUS = 0x80190009u32 as i32; +pub const STATUS_TRANSACTIONS_UNSUPPORTED_REMOTE: ::NTSTATUS = 0xC019000Au32 as i32; +pub const STATUS_LOG_RESIZE_INVALID_SIZE: ::NTSTATUS = 0xC019000Bu32 as i32; +pub const STATUS_REMOTE_FILE_VERSION_MISMATCH: ::NTSTATUS = 0xC019000Cu32 as i32; +pub const STATUS_CRM_PROTOCOL_ALREADY_EXISTS: ::NTSTATUS = 0xC019000Fu32 as i32; +pub const STATUS_TRANSACTION_PROPAGATION_FAILED: ::NTSTATUS = 0xC0190010u32 as i32; +pub const STATUS_CRM_PROTOCOL_NOT_FOUND: ::NTSTATUS = 0xC0190011u32 as i32; +pub const STATUS_TRANSACTION_SUPERIOR_EXISTS: ::NTSTATUS = 0xC0190012u32 as i32; +pub const STATUS_TRANSACTION_REQUEST_NOT_VALID: ::NTSTATUS = 0xC0190013u32 as i32; +pub const STATUS_TRANSACTION_NOT_REQUESTED: ::NTSTATUS = 0xC0190014u32 as i32; +pub const STATUS_TRANSACTION_ALREADY_ABORTED: ::NTSTATUS = 0xC0190015u32 as i32; +pub const STATUS_TRANSACTION_ALREADY_COMMITTED: ::NTSTATUS = 0xC0190016u32 as i32; +pub const STATUS_TRANSACTION_INVALID_MARSHALL_BUFFER: ::NTSTATUS = 0xC0190017u32 as i32; +pub const STATUS_CURRENT_TRANSACTION_NOT_VALID: ::NTSTATUS = 0xC0190018u32 as i32; +pub const STATUS_LOG_GROWTH_FAILED: ::NTSTATUS = 0xC0190019u32 as i32; +pub const STATUS_OBJECT_NO_LONGER_EXISTS: ::NTSTATUS = 0xC0190021u32 as i32; +pub const STATUS_STREAM_MINIVERSION_NOT_FOUND: ::NTSTATUS = 0xC0190022u32 as i32; +pub const STATUS_STREAM_MINIVERSION_NOT_VALID: ::NTSTATUS = 0xC0190023u32 as i32; +pub const STATUS_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION: ::NTSTATUS = 0xC0190024u32 as i32; +pub const STATUS_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT: ::NTSTATUS = 0xC0190025u32 as i32; +pub const STATUS_CANT_CREATE_MORE_STREAM_MINIVERSIONS: ::NTSTATUS = 0xC0190026u32 as i32; +pub const STATUS_HANDLE_NO_LONGER_VALID: ::NTSTATUS = 0xC0190028u32 as i32; +pub const STATUS_NO_TXF_METADATA: ::NTSTATUS = 0x80190029u32 as i32; +pub const STATUS_LOG_CORRUPTION_DETECTED: ::NTSTATUS = 0xC0190030u32 as i32; +pub const STATUS_CANT_RECOVER_WITH_HANDLE_OPEN: ::NTSTATUS = 0x80190031u32 as i32; +pub const STATUS_RM_DISCONNECTED: ::NTSTATUS = 0xC0190032u32 as i32; +pub const STATUS_ENLISTMENT_NOT_SUPERIOR: ::NTSTATUS = 0xC0190033u32 as i32; +pub const STATUS_RECOVERY_NOT_NEEDED: ::NTSTATUS = 0x40190034; +pub const STATUS_RM_ALREADY_STARTED: ::NTSTATUS = 0x40190035; +pub const STATUS_FILE_IDENTITY_NOT_PERSISTENT: ::NTSTATUS = 0xC0190036u32 as i32; +pub const STATUS_CANT_BREAK_TRANSACTIONAL_DEPENDENCY: ::NTSTATUS = 0xC0190037u32 as i32; +pub const STATUS_CANT_CROSS_RM_BOUNDARY: ::NTSTATUS = 0xC0190038u32 as i32; +pub const STATUS_TXF_DIR_NOT_EMPTY: ::NTSTATUS = 0xC0190039u32 as i32; +pub const STATUS_INDOUBT_TRANSACTIONS_EXIST: ::NTSTATUS = 0xC019003Au32 as i32; +pub const STATUS_TM_VOLATILE: ::NTSTATUS = 0xC019003Bu32 as i32; +pub const STATUS_ROLLBACK_TIMER_EXPIRED: ::NTSTATUS = 0xC019003Cu32 as i32; +pub const STATUS_TXF_ATTRIBUTE_CORRUPT: ::NTSTATUS = 0xC019003Du32 as i32; +pub const STATUS_EFS_NOT_ALLOWED_IN_TRANSACTION: ::NTSTATUS = 0xC019003Eu32 as i32; +pub const STATUS_TRANSACTIONAL_OPEN_NOT_ALLOWED: ::NTSTATUS = 0xC019003Fu32 as i32; +pub const STATUS_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE: ::NTSTATUS = 0xC0190040u32 as i32; +pub const STATUS_TXF_METADATA_ALREADY_PRESENT: ::NTSTATUS = 0x80190041u32 as i32; +pub const STATUS_TRANSACTION_SCOPE_CALLBACKS_NOT_SET: ::NTSTATUS = 0x80190042u32 as i32; +pub const STATUS_TRANSACTION_REQUIRED_PROMOTION: ::NTSTATUS = 0xC0190043u32 as i32; +pub const STATUS_CANNOT_EXECUTE_FILE_IN_TRANSACTION: ::NTSTATUS = 0xC0190044u32 as i32; +pub const STATUS_TRANSACTIONS_NOT_FROZEN: ::NTSTATUS = 0xC0190045u32 as i32; +pub const STATUS_TRANSACTION_FREEZE_IN_PROGRESS: ::NTSTATUS = 0xC0190046u32 as i32; +pub const STATUS_NOT_SNAPSHOT_VOLUME: ::NTSTATUS = 0xC0190047u32 as i32; +pub const STATUS_NO_SAVEPOINT_WITH_OPEN_FILES: ::NTSTATUS = 0xC0190048u32 as i32; +pub const STATUS_SPARSE_NOT_ALLOWED_IN_TRANSACTION: ::NTSTATUS = 0xC0190049u32 as i32; +pub const STATUS_TM_IDENTITY_MISMATCH: ::NTSTATUS = 0xC019004Au32 as i32; +pub const STATUS_FLOATED_SECTION: ::NTSTATUS = 0xC019004Bu32 as i32; +pub const STATUS_CANNOT_ACCEPT_TRANSACTED_WORK: ::NTSTATUS = 0xC019004Cu32 as i32; +pub const STATUS_CANNOT_ABORT_TRANSACTIONS: ::NTSTATUS = 0xC019004Du32 as i32; +pub const STATUS_TRANSACTION_NOT_FOUND: ::NTSTATUS = 0xC019004Eu32 as i32; +pub const STATUS_RESOURCEMANAGER_NOT_FOUND: ::NTSTATUS = 0xC019004Fu32 as i32; +pub const STATUS_ENLISTMENT_NOT_FOUND: ::NTSTATUS = 0xC0190050u32 as i32; +pub const STATUS_TRANSACTIONMANAGER_NOT_FOUND: ::NTSTATUS = 0xC0190051u32 as i32; +pub const STATUS_TRANSACTIONMANAGER_NOT_ONLINE: ::NTSTATUS = 0xC0190052u32 as i32; +pub const STATUS_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION: ::NTSTATUS = 0xC0190053u32 as i32; +pub const STATUS_TRANSACTION_NOT_ROOT: ::NTSTATUS = 0xC0190054u32 as i32; +pub const STATUS_TRANSACTION_OBJECT_EXPIRED: ::NTSTATUS = 0xC0190055u32 as i32; +pub const STATUS_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION: ::NTSTATUS = 0xC0190056u32 as i32; +pub const STATUS_TRANSACTION_RESPONSE_NOT_ENLISTED: ::NTSTATUS = 0xC0190057u32 as i32; +pub const STATUS_TRANSACTION_RECORD_TOO_LONG: ::NTSTATUS = 0xC0190058u32 as i32; +pub const STATUS_NO_LINK_TRACKING_IN_TRANSACTION: ::NTSTATUS = 0xC0190059u32 as i32; +pub const STATUS_OPERATION_NOT_SUPPORTED_IN_TRANSACTION: ::NTSTATUS = 0xC019005Au32 as i32; +pub const STATUS_TRANSACTION_INTEGRITY_VIOLATED: ::NTSTATUS = 0xC019005Bu32 as i32; +pub const STATUS_TRANSACTIONMANAGER_IDENTITY_MISMATCH: ::NTSTATUS = 0xC019005Cu32 as i32; +pub const STATUS_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT: ::NTSTATUS = 0xC019005Du32 as i32; +pub const STATUS_TRANSACTION_MUST_WRITETHROUGH: ::NTSTATUS = 0xC019005Eu32 as i32; +pub const STATUS_TRANSACTION_NO_SUPERIOR: ::NTSTATUS = 0xC019005Fu32 as i32; +pub const STATUS_EXPIRED_HANDLE: ::NTSTATUS = 0xC0190060u32 as i32; +pub const STATUS_TRANSACTION_NOT_ENLISTED: ::NTSTATUS = 0xC0190061u32 as i32; +pub const STATUS_LOG_SECTOR_INVALID: ::NTSTATUS = 0xC01A0001u32 as i32; +pub const STATUS_LOG_SECTOR_PARITY_INVALID: ::NTSTATUS = 0xC01A0002u32 as i32; +pub const STATUS_LOG_SECTOR_REMAPPED: ::NTSTATUS = 0xC01A0003u32 as i32; +pub const STATUS_LOG_BLOCK_INCOMPLETE: ::NTSTATUS = 0xC01A0004u32 as i32; +pub const STATUS_LOG_INVALID_RANGE: ::NTSTATUS = 0xC01A0005u32 as i32; +pub const STATUS_LOG_BLOCKS_EXHAUSTED: ::NTSTATUS = 0xC01A0006u32 as i32; +pub const STATUS_LOG_READ_CONTEXT_INVALID: ::NTSTATUS = 0xC01A0007u32 as i32; +pub const STATUS_LOG_RESTART_INVALID: ::NTSTATUS = 0xC01A0008u32 as i32; +pub const STATUS_LOG_BLOCK_VERSION: ::NTSTATUS = 0xC01A0009u32 as i32; +pub const STATUS_LOG_BLOCK_INVALID: ::NTSTATUS = 0xC01A000Au32 as i32; +pub const STATUS_LOG_READ_MODE_INVALID: ::NTSTATUS = 0xC01A000Bu32 as i32; +pub const STATUS_LOG_NO_RESTART: ::NTSTATUS = 0x401A000C; +pub const STATUS_LOG_METADATA_CORRUPT: ::NTSTATUS = 0xC01A000Du32 as i32; +pub const STATUS_LOG_METADATA_INVALID: ::NTSTATUS = 0xC01A000Eu32 as i32; +pub const STATUS_LOG_METADATA_INCONSISTENT: ::NTSTATUS = 0xC01A000Fu32 as i32; +pub const STATUS_LOG_RESERVATION_INVALID: ::NTSTATUS = 0xC01A0010u32 as i32; +pub const STATUS_LOG_CANT_DELETE: ::NTSTATUS = 0xC01A0011u32 as i32; +pub const STATUS_LOG_CONTAINER_LIMIT_EXCEEDED: ::NTSTATUS = 0xC01A0012u32 as i32; +pub const STATUS_LOG_START_OF_LOG: ::NTSTATUS = 0xC01A0013u32 as i32; +pub const STATUS_LOG_POLICY_ALREADY_INSTALLED: ::NTSTATUS = 0xC01A0014u32 as i32; +pub const STATUS_LOG_POLICY_NOT_INSTALLED: ::NTSTATUS = 0xC01A0015u32 as i32; +pub const STATUS_LOG_POLICY_INVALID: ::NTSTATUS = 0xC01A0016u32 as i32; +pub const STATUS_LOG_POLICY_CONFLICT: ::NTSTATUS = 0xC01A0017u32 as i32; +pub const STATUS_LOG_PINNED_ARCHIVE_TAIL: ::NTSTATUS = 0xC01A0018u32 as i32; +pub const STATUS_LOG_RECORD_NONEXISTENT: ::NTSTATUS = 0xC01A0019u32 as i32; +pub const STATUS_LOG_RECORDS_RESERVED_INVALID: ::NTSTATUS = 0xC01A001Au32 as i32; +pub const STATUS_LOG_SPACE_RESERVED_INVALID: ::NTSTATUS = 0xC01A001Bu32 as i32; +pub const STATUS_LOG_TAIL_INVALID: ::NTSTATUS = 0xC01A001Cu32 as i32; +pub const STATUS_LOG_FULL: ::NTSTATUS = 0xC01A001Du32 as i32; +pub const STATUS_LOG_MULTIPLEXED: ::NTSTATUS = 0xC01A001Eu32 as i32; +pub const STATUS_LOG_DEDICATED: ::NTSTATUS = 0xC01A001Fu32 as i32; +pub const STATUS_LOG_ARCHIVE_NOT_IN_PROGRESS: ::NTSTATUS = 0xC01A0020u32 as i32; +pub const STATUS_LOG_ARCHIVE_IN_PROGRESS: ::NTSTATUS = 0xC01A0021u32 as i32; +pub const STATUS_LOG_EPHEMERAL: ::NTSTATUS = 0xC01A0022u32 as i32; +pub const STATUS_LOG_NOT_ENOUGH_CONTAINERS: ::NTSTATUS = 0xC01A0023u32 as i32; +pub const STATUS_LOG_CLIENT_ALREADY_REGISTERED: ::NTSTATUS = 0xC01A0024u32 as i32; +pub const STATUS_LOG_CLIENT_NOT_REGISTERED: ::NTSTATUS = 0xC01A0025u32 as i32; +pub const STATUS_LOG_FULL_HANDLER_IN_PROGRESS: ::NTSTATUS = 0xC01A0026u32 as i32; +pub const STATUS_LOG_CONTAINER_READ_FAILED: ::NTSTATUS = 0xC01A0027u32 as i32; +pub const STATUS_LOG_CONTAINER_WRITE_FAILED: ::NTSTATUS = 0xC01A0028u32 as i32; +pub const STATUS_LOG_CONTAINER_OPEN_FAILED: ::NTSTATUS = 0xC01A0029u32 as i32; +pub const STATUS_LOG_CONTAINER_STATE_INVALID: ::NTSTATUS = 0xC01A002Au32 as i32; +pub const STATUS_LOG_STATE_INVALID: ::NTSTATUS = 0xC01A002Bu32 as i32; +pub const STATUS_LOG_PINNED: ::NTSTATUS = 0xC01A002Cu32 as i32; +pub const STATUS_LOG_METADATA_FLUSH_FAILED: ::NTSTATUS = 0xC01A002Du32 as i32; +pub const STATUS_LOG_INCONSISTENT_SECURITY: ::NTSTATUS = 0xC01A002Eu32 as i32; +pub const STATUS_LOG_APPENDED_FLUSH_FAILED: ::NTSTATUS = 0xC01A002Fu32 as i32; +pub const STATUS_LOG_PINNED_RESERVATION: ::NTSTATUS = 0xC01A0030u32 as i32; +pub const STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD: ::NTSTATUS = 0xC01B00EAu32 as i32; +pub const STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD_RECOVERED: ::NTSTATUS = 0x801B00EBu32 as i32; +pub const STATUS_VIDEO_DRIVER_DEBUG_REPORT_REQUEST: ::NTSTATUS = 0x401B00EC; +pub const STATUS_MONITOR_NO_DESCRIPTOR: ::NTSTATUS = 0xC01D0001u32 as i32; +pub const STATUS_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT: ::NTSTATUS = 0xC01D0002u32 as i32; +pub const STATUS_MONITOR_INVALID_DESCRIPTOR_CHECKSUM: ::NTSTATUS = 0xC01D0003u32 as i32; +pub const STATUS_MONITOR_INVALID_STANDARD_TIMING_BLOCK: ::NTSTATUS = 0xC01D0004u32 as i32; +pub const STATUS_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED: ::NTSTATUS = 0xC01D0005u32 as i32; +pub const STATUS_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK: ::NTSTATUS = 0xC01D0006u32 as i32; +pub const STATUS_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK: ::NTSTATUS = 0xC01D0007u32 as i32; +pub const STATUS_MONITOR_NO_MORE_DESCRIPTOR_DATA: ::NTSTATUS = 0xC01D0008u32 as i32; +pub const STATUS_MONITOR_INVALID_DETAILED_TIMING_BLOCK: ::NTSTATUS = 0xC01D0009u32 as i32; +pub const STATUS_MONITOR_INVALID_MANUFACTURE_DATE: ::NTSTATUS = 0xC01D000Au32 as i32; +pub const STATUS_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER: ::NTSTATUS = 0xC01E0000u32 as i32; +pub const STATUS_GRAPHICS_INSUFFICIENT_DMA_BUFFER: ::NTSTATUS = 0xC01E0001u32 as i32; +pub const STATUS_GRAPHICS_INVALID_DISPLAY_ADAPTER: ::NTSTATUS = 0xC01E0002u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_WAS_RESET: ::NTSTATUS = 0xC01E0003u32 as i32; +pub const STATUS_GRAPHICS_INVALID_DRIVER_MODEL: ::NTSTATUS = 0xC01E0004u32 as i32; +pub const STATUS_GRAPHICS_PRESENT_MODE_CHANGED: ::NTSTATUS = 0xC01E0005u32 as i32; +pub const STATUS_GRAPHICS_PRESENT_OCCLUDED: ::NTSTATUS = 0xC01E0006u32 as i32; +pub const STATUS_GRAPHICS_PRESENT_DENIED: ::NTSTATUS = 0xC01E0007u32 as i32; +pub const STATUS_GRAPHICS_CANNOTCOLORCONVERT: ::NTSTATUS = 0xC01E0008u32 as i32; +pub const STATUS_GRAPHICS_DRIVER_MISMATCH: ::NTSTATUS = 0xC01E0009u32 as i32; +pub const STATUS_GRAPHICS_PARTIAL_DATA_POPULATED: ::NTSTATUS = 0x401E000A; +pub const STATUS_GRAPHICS_PRESENT_REDIRECTION_DISABLED: ::NTSTATUS = 0xC01E000Bu32 as i32; +pub const STATUS_GRAPHICS_PRESENT_UNOCCLUDED: ::NTSTATUS = 0xC01E000Cu32 as i32; +pub const STATUS_GRAPHICS_WINDOWDC_NOT_AVAILABLE: ::NTSTATUS = 0xC01E000Du32 as i32; +pub const STATUS_GRAPHICS_WINDOWLESS_PRESENT_DISABLED: ::NTSTATUS = 0xC01E000Eu32 as i32; +pub const STATUS_GRAPHICS_NO_VIDEO_MEMORY: ::NTSTATUS = 0xC01E0100u32 as i32; +pub const STATUS_GRAPHICS_CANT_LOCK_MEMORY: ::NTSTATUS = 0xC01E0101u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_BUSY: ::NTSTATUS = 0xC01E0102u32 as i32; +pub const STATUS_GRAPHICS_TOO_MANY_REFERENCES: ::NTSTATUS = 0xC01E0103u32 as i32; +pub const STATUS_GRAPHICS_TRY_AGAIN_LATER: ::NTSTATUS = 0xC01E0104u32 as i32; +pub const STATUS_GRAPHICS_TRY_AGAIN_NOW: ::NTSTATUS = 0xC01E0105u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_INVALID: ::NTSTATUS = 0xC01E0106u32 as i32; +pub const STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE: ::NTSTATUS = 0xC01E0107u32 as i32; +pub const STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED: ::NTSTATUS = 0xC01E0108u32 as i32; +pub const STATUS_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION: ::NTSTATUS = 0xC01E0109u32 as i32; +pub const STATUS_GRAPHICS_INVALID_ALLOCATION_USAGE: ::NTSTATUS = 0xC01E0110u32 as i32; +pub const STATUS_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION: ::NTSTATUS = 0xC01E0111u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_CLOSED: ::NTSTATUS = 0xC01E0112u32 as i32; +pub const STATUS_GRAPHICS_INVALID_ALLOCATION_INSTANCE: ::NTSTATUS = 0xC01E0113u32 as i32; +pub const STATUS_GRAPHICS_INVALID_ALLOCATION_HANDLE: ::NTSTATUS = 0xC01E0114u32 as i32; +pub const STATUS_GRAPHICS_WRONG_ALLOCATION_DEVICE: ::NTSTATUS = 0xC01E0115u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_CONTENT_LOST: ::NTSTATUS = 0xC01E0116u32 as i32; +pub const STATUS_GRAPHICS_GPU_EXCEPTION_ON_DEVICE: ::NTSTATUS = 0xC01E0200u32 as i32; +pub const STATUS_GRAPHICS_SKIP_ALLOCATION_PREPARATION: ::NTSTATUS = 0x401E0201; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY: ::NTSTATUS = 0xC01E0300u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0301u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0302u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN: ::NTSTATUS = 0xC01E0303u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE: ::NTSTATUS = 0xC01E0304u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET: ::NTSTATUS = 0xC01E0305u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0306u32 as i32; +pub const STATUS_GRAPHICS_MODE_NOT_PINNED: ::NTSTATUS = 0x401E0307; +pub const STATUS_GRAPHICS_INVALID_VIDPN_SOURCEMODESET: ::NTSTATUS = 0xC01E0308u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TARGETMODESET: ::NTSTATUS = 0xC01E0309u32 as i32; +pub const STATUS_GRAPHICS_INVALID_FREQUENCY: ::NTSTATUS = 0xC01E030Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_ACTIVE_REGION: ::NTSTATUS = 0xC01E030Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_TOTAL_REGION: ::NTSTATUS = 0xC01E030Cu32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE: ::NTSTATUS = 0xC01E0310u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE: ::NTSTATUS = 0xC01E0311u32 as i32; +pub const STATUS_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET: ::NTSTATUS = 0xC01E0312u32 as i32; +pub const STATUS_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0313u32 as i32; +pub const STATUS_GRAPHICS_MODE_ALREADY_IN_MODESET: ::NTSTATUS = 0xC01E0314u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET: ::NTSTATUS = 0xC01E0315u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET: ::NTSTATUS = 0xC01E0316u32 as i32; +pub const STATUS_GRAPHICS_SOURCE_ALREADY_IN_SET: ::NTSTATUS = 0xC01E0317u32 as i32; +pub const STATUS_GRAPHICS_TARGET_ALREADY_IN_SET: ::NTSTATUS = 0xC01E0318u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN_PRESENT_PATH: ::NTSTATUS = 0xC01E0319u32 as i32; +pub const STATUS_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY: ::NTSTATUS = 0xC01E031Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET: ::NTSTATUS = 0xC01E031Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE: ::NTSTATUS = 0xC01E031Cu32 as i32; +pub const STATUS_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET: ::NTSTATUS = 0xC01E031Du32 as i32; +pub const STATUS_GRAPHICS_NO_PREFERRED_MODE: ::NTSTATUS = 0x401E031E; +pub const STATUS_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET: ::NTSTATUS = 0xC01E031Fu32 as i32; +pub const STATUS_GRAPHICS_STALE_MODESET: ::NTSTATUS = 0xC01E0320u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_SOURCEMODESET: ::NTSTATUS = 0xC01E0321u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_SOURCE_MODE: ::NTSTATUS = 0xC01E0322u32 as i32; +pub const STATUS_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN: ::NTSTATUS = 0xC01E0323u32 as i32; +pub const STATUS_GRAPHICS_MODE_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E0324u32 as i32; +pub const STATUS_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION: ::NTSTATUS = 0xC01E0325u32 as i32; +pub const STATUS_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES: ::NTSTATUS = 0xC01E0326u32 as i32; +pub const STATUS_GRAPHICS_PATH_NOT_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0327u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE: ::NTSTATUS = 0xC01E0328u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET: ::NTSTATUS = 0xC01E0329u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITORDESCRIPTORSET: ::NTSTATUS = 0xC01E032Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITORDESCRIPTOR: ::NTSTATUS = 0xC01E032Bu32 as i32; +pub const STATUS_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET: ::NTSTATUS = 0xC01E032Cu32 as i32; +pub const STATUS_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET: ::NTSTATUS = 0xC01E032Du32 as i32; +pub const STATUS_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E032Eu32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE: ::NTSTATUS = 0xC01E032Fu32 as i32; +pub const STATUS_GRAPHICS_RESOURCES_NOT_RELATED: ::NTSTATUS = 0xC01E0330u32 as i32; +pub const STATUS_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E0331u32 as i32; +pub const STATUS_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E0332u32 as i32; +pub const STATUS_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET: ::NTSTATUS = 0xC01E0333u32 as i32; +pub const STATUS_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER: ::NTSTATUS = 0xC01E0334u32 as i32; +pub const STATUS_GRAPHICS_NO_VIDPNMGR: ::NTSTATUS = 0xC01E0335u32 as i32; +pub const STATUS_GRAPHICS_NO_ACTIVE_VIDPN: ::NTSTATUS = 0xC01E0336u32 as i32; +pub const STATUS_GRAPHICS_STALE_VIDPN_TOPOLOGY: ::NTSTATUS = 0xC01E0337u32 as i32; +pub const STATUS_GRAPHICS_MONITOR_NOT_CONNECTED: ::NTSTATUS = 0xC01E0338u32 as i32; +pub const STATUS_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0339u32 as i32; +pub const STATUS_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE: ::NTSTATUS = 0xC01E033Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_VISIBLEREGION_SIZE: ::NTSTATUS = 0xC01E033Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_STRIDE: ::NTSTATUS = 0xC01E033Cu32 as i32; +pub const STATUS_GRAPHICS_INVALID_PIXELFORMAT: ::NTSTATUS = 0xC01E033Du32 as i32; +pub const STATUS_GRAPHICS_INVALID_COLORBASIS: ::NTSTATUS = 0xC01E033Eu32 as i32; +pub const STATUS_GRAPHICS_INVALID_PIXELVALUEACCESSMODE: ::NTSTATUS = 0xC01E033Fu32 as i32; +pub const STATUS_GRAPHICS_TARGET_NOT_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0340u32 as i32; +pub const STATUS_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT: ::NTSTATUS = 0xC01E0341u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: ::NTSTATUS = 0xC01E0342u32 as i32; +pub const STATUS_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN: ::NTSTATUS = 0xC01E0343u32 as i32; +pub const STATUS_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL: ::NTSTATUS = 0xC01E0344u32 as i32; +pub const STATUS_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION: ::NTSTATUS = 0xC01E0345u32 as i32; +pub const STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0346u32 as i32; +pub const STATUS_GRAPHICS_INVALID_GAMMA_RAMP: ::NTSTATUS = 0xC01E0347u32 as i32; +pub const STATUS_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0348u32 as i32; +pub const STATUS_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0349u32 as i32; +pub const STATUS_GRAPHICS_MODE_NOT_IN_MODESET: ::NTSTATUS = 0xC01E034Au32 as i32; +pub const STATUS_GRAPHICS_DATASET_IS_EMPTY: ::NTSTATUS = 0x401E034B; +pub const STATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET: ::NTSTATUS = 0x401E034C; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON: ::NTSTATUS = 0xC01E034Du32 as i32; +pub const STATUS_GRAPHICS_INVALID_PATH_CONTENT_TYPE: ::NTSTATUS = 0xC01E034Eu32 as i32; +pub const STATUS_GRAPHICS_INVALID_COPYPROTECTION_TYPE: ::NTSTATUS = 0xC01E034Fu32 as i32; +pub const STATUS_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS: ::NTSTATUS = 0xC01E0350u32 as i32; +pub const STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED: ::NTSTATUS = 0x401E0351; +pub const STATUS_GRAPHICS_INVALID_SCANLINE_ORDERING: ::NTSTATUS = 0xC01E0352u32 as i32; +pub const STATUS_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED: ::NTSTATUS = 0xC01E0353u32 as i32; +pub const STATUS_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS: ::NTSTATUS = 0xC01E0354u32 as i32; +pub const STATUS_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT: ::NTSTATUS = 0xC01E0355u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM: ::NTSTATUS = 0xC01E0356u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN: ::NTSTATUS = 0xC01E0357u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT: ::NTSTATUS = 0xC01E0358u32 as i32; +pub const STATUS_GRAPHICS_MAX_NUM_PATHS_REACHED: ::NTSTATUS = 0xC01E0359u32 as i32; +pub const STATUS_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION: ::NTSTATUS = 0xC01E035Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_CLIENT_TYPE: ::NTSTATUS = 0xC01E035Bu32 as i32; +pub const STATUS_GRAPHICS_CLIENTVIDPN_NOT_SET: ::NTSTATUS = 0xC01E035Cu32 as i32; +pub const STATUS_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED: ::NTSTATUS = 0xC01E0400u32 as i32; +pub const STATUS_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0401u32 as i32; +pub const STATUS_GRAPHICS_UNKNOWN_CHILD_STATUS: ::NTSTATUS = 0x401E042F; +pub const STATUS_GRAPHICS_NOT_A_LINKED_ADAPTER: ::NTSTATUS = 0xC01E0430u32 as i32; +pub const STATUS_GRAPHICS_LEADLINK_NOT_ENUMERATED: ::NTSTATUS = 0xC01E0431u32 as i32; +pub const STATUS_GRAPHICS_CHAINLINKS_NOT_ENUMERATED: ::NTSTATUS = 0xC01E0432u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_CHAIN_NOT_READY: ::NTSTATUS = 0xC01E0433u32 as i32; +pub const STATUS_GRAPHICS_CHAINLINKS_NOT_STARTED: ::NTSTATUS = 0xC01E0434u32 as i32; +pub const STATUS_GRAPHICS_CHAINLINKS_NOT_POWERED_ON: ::NTSTATUS = 0xC01E0435u32 as i32; +pub const STATUS_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE: ::NTSTATUS = 0xC01E0436u32 as i32; +pub const STATUS_GRAPHICS_LEADLINK_START_DEFERRED: ::NTSTATUS = 0x401E0437; +pub const STATUS_GRAPHICS_NOT_POST_DEVICE_DRIVER: ::NTSTATUS = 0xC01E0438u32 as i32; +pub const STATUS_GRAPHICS_POLLING_TOO_FREQUENTLY: ::NTSTATUS = 0x401E0439; +pub const STATUS_GRAPHICS_START_DEFERRED: ::NTSTATUS = 0x401E043A; +pub const STATUS_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED: ::NTSTATUS = 0xC01E043Bu32 as i32; +pub const STATUS_GRAPHICS_DEPENDABLE_CHILD_STATUS: ::NTSTATUS = 0x401E043C; +pub const STATUS_GRAPHICS_OPM_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0500u32 as i32; +pub const STATUS_GRAPHICS_COPP_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0501u32 as i32; +pub const STATUS_GRAPHICS_UAB_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0502u32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS: ::NTSTATUS = 0xC01E0503u32 as i32; +pub const STATUS_GRAPHICS_OPM_NO_PROTECTED_OUTPUTS_EXIST: ::NTSTATUS = 0xC01E0505u32 as i32; +pub const STATUS_GRAPHICS_OPM_INTERNAL_ERROR: ::NTSTATUS = 0xC01E050Bu32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_HANDLE: ::NTSTATUS = 0xC01E050Cu32 as i32; +pub const STATUS_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH: ::NTSTATUS = 0xC01E050Eu32 as i32; +pub const STATUS_GRAPHICS_OPM_SPANNING_MODE_ENABLED: ::NTSTATUS = 0xC01E050Fu32 as i32; +pub const STATUS_GRAPHICS_OPM_THEATER_MODE_ENABLED: ::NTSTATUS = 0xC01E0510u32 as i32; +pub const STATUS_GRAPHICS_PVP_HFS_FAILED: ::NTSTATUS = 0xC01E0511u32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_SRM: ::NTSTATUS = 0xC01E0512u32 as i32; +pub const STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP: ::NTSTATUS = 0xC01E0513u32 as i32; +pub const STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP: ::NTSTATUS = 0xC01E0514u32 as i32; +pub const STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA: ::NTSTATUS = 0xC01E0515u32 as i32; +pub const STATUS_GRAPHICS_OPM_HDCP_SRM_NEVER_SET: ::NTSTATUS = 0xC01E0516u32 as i32; +pub const STATUS_GRAPHICS_OPM_RESOLUTION_TOO_HIGH: ::NTSTATUS = 0xC01E0517u32 as i32; +pub const STATUS_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE: ::NTSTATUS = 0xC01E0518u32 as i32; +pub const STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_NO_LONGER_EXISTS: ::NTSTATUS = 0xC01E051Au32 as i32; +pub const STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS: ::NTSTATUS = 0xC01E051Cu32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST: ::NTSTATUS = 0xC01E051Du32 as i32; +pub const STATUS_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR: ::NTSTATUS = 0xC01E051Eu32 as i32; +pub const STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS: ::NTSTATUS = 0xC01E051Fu32 as i32; +pub const STATUS_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0520u32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST: ::NTSTATUS = 0xC01E0521u32 as i32; +pub const STATUS_GRAPHICS_I2C_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0580u32 as i32; +pub const STATUS_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST: ::NTSTATUS = 0xC01E0581u32 as i32; +pub const STATUS_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA: ::NTSTATUS = 0xC01E0582u32 as i32; +pub const STATUS_GRAPHICS_I2C_ERROR_RECEIVING_DATA: ::NTSTATUS = 0xC01E0583u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0584u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_DATA: ::NTSTATUS = 0xC01E0585u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE: ::NTSTATUS = 0xC01E0586u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_CAPABILITIES_STRING: ::NTSTATUS = 0xC01E0587u32 as i32; +pub const STATUS_GRAPHICS_MCA_INTERNAL_ERROR: ::NTSTATUS = 0xC01E0588u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND: ::NTSTATUS = 0xC01E0589u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH: ::NTSTATUS = 0xC01E058Au32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM: ::NTSTATUS = 0xC01E058Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE: ::NTSTATUS = 0xC01E058Cu32 as i32; +pub const STATUS_GRAPHICS_MONITOR_NO_LONGER_EXISTS: ::NTSTATUS = 0xC01E058Du32 as i32; +pub const STATUS_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED: ::NTSTATUS = 0xC01E05E0u32 as i32; +pub const STATUS_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME: ::NTSTATUS = 0xC01E05E1u32 as i32; +pub const STATUS_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP: ::NTSTATUS = 0xC01E05E2u32 as i32; +pub const STATUS_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED: ::NTSTATUS = 0xC01E05E3u32 as i32; +pub const STATUS_GRAPHICS_INVALID_POINTER: ::NTSTATUS = 0xC01E05E4u32 as i32; +pub const STATUS_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE: ::NTSTATUS = 0xC01E05E5u32 as i32; +pub const STATUS_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL: ::NTSTATUS = 0xC01E05E6u32 as i32; +pub const STATUS_GRAPHICS_INTERNAL_ERROR: ::NTSTATUS = 0xC01E05E7u32 as i32; +pub const STATUS_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS: ::NTSTATUS = 0xC01E05E8u32 as i32; +pub const STATUS_FVE_LOCKED_VOLUME: ::NTSTATUS = 0xC0210000u32 as i32; +pub const STATUS_FVE_NOT_ENCRYPTED: ::NTSTATUS = 0xC0210001u32 as i32; +pub const STATUS_FVE_BAD_INFORMATION: ::NTSTATUS = 0xC0210002u32 as i32; +pub const STATUS_FVE_TOO_SMALL: ::NTSTATUS = 0xC0210003u32 as i32; +pub const STATUS_FVE_FAILED_WRONG_FS: ::NTSTATUS = 0xC0210004u32 as i32; +pub const STATUS_FVE_BAD_PARTITION_SIZE: ::NTSTATUS = 0xC0210005u32 as i32; +pub const STATUS_FVE_FS_NOT_EXTENDED: ::NTSTATUS = 0xC0210006u32 as i32; +pub const STATUS_FVE_FS_MOUNTED: ::NTSTATUS = 0xC0210007u32 as i32; +pub const STATUS_FVE_NO_LICENSE: ::NTSTATUS = 0xC0210008u32 as i32; +pub const STATUS_FVE_ACTION_NOT_ALLOWED: ::NTSTATUS = 0xC0210009u32 as i32; +pub const STATUS_FVE_BAD_DATA: ::NTSTATUS = 0xC021000Au32 as i32; +pub const STATUS_FVE_VOLUME_NOT_BOUND: ::NTSTATUS = 0xC021000Bu32 as i32; +pub const STATUS_FVE_NOT_DATA_VOLUME: ::NTSTATUS = 0xC021000Cu32 as i32; +pub const STATUS_FVE_CONV_READ_ERROR: ::NTSTATUS = 0xC021000Du32 as i32; +pub const STATUS_FVE_CONV_WRITE_ERROR: ::NTSTATUS = 0xC021000Eu32 as i32; +pub const STATUS_FVE_OVERLAPPED_UPDATE: ::NTSTATUS = 0xC021000Fu32 as i32; +pub const STATUS_FVE_FAILED_SECTOR_SIZE: ::NTSTATUS = 0xC0210010u32 as i32; +pub const STATUS_FVE_FAILED_AUTHENTICATION: ::NTSTATUS = 0xC0210011u32 as i32; +pub const STATUS_FVE_NOT_OS_VOLUME: ::NTSTATUS = 0xC0210012u32 as i32; +pub const STATUS_FVE_KEYFILE_NOT_FOUND: ::NTSTATUS = 0xC0210013u32 as i32; +pub const STATUS_FVE_KEYFILE_INVALID: ::NTSTATUS = 0xC0210014u32 as i32; +pub const STATUS_FVE_KEYFILE_NO_VMK: ::NTSTATUS = 0xC0210015u32 as i32; +pub const STATUS_FVE_TPM_DISABLED: ::NTSTATUS = 0xC0210016u32 as i32; +pub const STATUS_FVE_TPM_SRK_AUTH_NOT_ZERO: ::NTSTATUS = 0xC0210017u32 as i32; +pub const STATUS_FVE_TPM_INVALID_PCR: ::NTSTATUS = 0xC0210018u32 as i32; +pub const STATUS_FVE_TPM_NO_VMK: ::NTSTATUS = 0xC0210019u32 as i32; +pub const STATUS_FVE_PIN_INVALID: ::NTSTATUS = 0xC021001Au32 as i32; +pub const STATUS_FVE_AUTH_INVALID_APPLICATION: ::NTSTATUS = 0xC021001Bu32 as i32; +pub const STATUS_FVE_AUTH_INVALID_CONFIG: ::NTSTATUS = 0xC021001Cu32 as i32; +pub const STATUS_FVE_DEBUGGER_ENABLED: ::NTSTATUS = 0xC021001Du32 as i32; +pub const STATUS_FVE_DRY_RUN_FAILED: ::NTSTATUS = 0xC021001Eu32 as i32; +pub const STATUS_FVE_BAD_METADATA_POINTER: ::NTSTATUS = 0xC021001Fu32 as i32; +pub const STATUS_FVE_OLD_METADATA_COPY: ::NTSTATUS = 0xC0210020u32 as i32; +pub const STATUS_FVE_REBOOT_REQUIRED: ::NTSTATUS = 0xC0210021u32 as i32; +pub const STATUS_FVE_RAW_ACCESS: ::NTSTATUS = 0xC0210022u32 as i32; +pub const STATUS_FVE_RAW_BLOCKED: ::NTSTATUS = 0xC0210023u32 as i32; +pub const STATUS_FVE_NO_AUTOUNLOCK_MASTER_KEY: ::NTSTATUS = 0xC0210024u32 as i32; +pub const STATUS_FVE_MOR_FAILED: ::NTSTATUS = 0xC0210025u32 as i32; +pub const STATUS_FVE_NO_FEATURE_LICENSE: ::NTSTATUS = 0xC0210026u32 as i32; +pub const STATUS_FVE_POLICY_USER_DISABLE_RDV_NOT_ALLOWED: ::NTSTATUS = 0xC0210027u32 as i32; +pub const STATUS_FVE_CONV_RECOVERY_FAILED: ::NTSTATUS = 0xC0210028u32 as i32; +pub const STATUS_FVE_VIRTUALIZED_SPACE_TOO_BIG: ::NTSTATUS = 0xC0210029u32 as i32; +pub const STATUS_FVE_INVALID_DATUM_TYPE: ::NTSTATUS = 0xC021002Au32 as i32; +pub const STATUS_FVE_VOLUME_TOO_SMALL: ::NTSTATUS = 0xC0210030u32 as i32; +pub const STATUS_FVE_ENH_PIN_INVALID: ::NTSTATUS = 0xC0210031u32 as i32; +pub const STATUS_FVE_FULL_ENCRYPTION_NOT_ALLOWED_ON_TP_STORAGE: ::NTSTATUS = 0xC0210032u32 as i32; +pub const STATUS_FVE_WIPE_NOT_ALLOWED_ON_TP_STORAGE: ::NTSTATUS = 0xC0210033u32 as i32; +pub const STATUS_FVE_NOT_ALLOWED_ON_CSV_STACK: ::NTSTATUS = 0xC0210034u32 as i32; +pub const STATUS_FVE_NOT_ALLOWED_ON_CLUSTER: ::NTSTATUS = 0xC0210035u32 as i32; +pub const STATUS_FVE_NOT_ALLOWED_TO_UPGRADE_WHILE_CONVERTING: ::NTSTATUS = 0xC0210036u32 as i32; +pub const STATUS_FVE_WIPE_CANCEL_NOT_APPLICABLE: ::NTSTATUS = 0xC0210037u32 as i32; +pub const STATUS_FVE_EDRIVE_DRY_RUN_FAILED: ::NTSTATUS = 0xC0210038u32 as i32; +pub const STATUS_FVE_SECUREBOOT_DISABLED: ::NTSTATUS = 0xC0210039u32 as i32; +pub const STATUS_FVE_SECUREBOOT_CONFIG_CHANGE: ::NTSTATUS = 0xC021003Au32 as i32; +pub const STATUS_FVE_DEVICE_LOCKEDOUT: ::NTSTATUS = 0xC021003Bu32 as i32; +pub const STATUS_FVE_VOLUME_EXTEND_PREVENTS_EOW_DECRYPT: ::NTSTATUS = 0xC021003Cu32 as i32; +pub const STATUS_FVE_NOT_DE_VOLUME: ::NTSTATUS = 0xC021003Du32 as i32; +pub const STATUS_FVE_PROTECTION_DISABLED: ::NTSTATUS = 0xC021003Eu32 as i32; +pub const STATUS_FVE_PROTECTION_CANNOT_BE_DISABLED: ::NTSTATUS = 0xC021003Fu32 as i32; +pub const STATUS_FWP_CALLOUT_NOT_FOUND: ::NTSTATUS = 0xC0220001u32 as i32; +pub const STATUS_FWP_CONDITION_NOT_FOUND: ::NTSTATUS = 0xC0220002u32 as i32; +pub const STATUS_FWP_FILTER_NOT_FOUND: ::NTSTATUS = 0xC0220003u32 as i32; +pub const STATUS_FWP_LAYER_NOT_FOUND: ::NTSTATUS = 0xC0220004u32 as i32; +pub const STATUS_FWP_PROVIDER_NOT_FOUND: ::NTSTATUS = 0xC0220005u32 as i32; +pub const STATUS_FWP_PROVIDER_CONTEXT_NOT_FOUND: ::NTSTATUS = 0xC0220006u32 as i32; +pub const STATUS_FWP_SUBLAYER_NOT_FOUND: ::NTSTATUS = 0xC0220007u32 as i32; +pub const STATUS_FWP_NOT_FOUND: ::NTSTATUS = 0xC0220008u32 as i32; +pub const STATUS_FWP_ALREADY_EXISTS: ::NTSTATUS = 0xC0220009u32 as i32; +pub const STATUS_FWP_IN_USE: ::NTSTATUS = 0xC022000Au32 as i32; +pub const STATUS_FWP_DYNAMIC_SESSION_IN_PROGRESS: ::NTSTATUS = 0xC022000Bu32 as i32; +pub const STATUS_FWP_WRONG_SESSION: ::NTSTATUS = 0xC022000Cu32 as i32; +pub const STATUS_FWP_NO_TXN_IN_PROGRESS: ::NTSTATUS = 0xC022000Du32 as i32; +pub const STATUS_FWP_TXN_IN_PROGRESS: ::NTSTATUS = 0xC022000Eu32 as i32; +pub const STATUS_FWP_TXN_ABORTED: ::NTSTATUS = 0xC022000Fu32 as i32; +pub const STATUS_FWP_SESSION_ABORTED: ::NTSTATUS = 0xC0220010u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_TXN: ::NTSTATUS = 0xC0220011u32 as i32; +pub const STATUS_FWP_TIMEOUT: ::NTSTATUS = 0xC0220012u32 as i32; +pub const STATUS_FWP_NET_EVENTS_DISABLED: ::NTSTATUS = 0xC0220013u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_LAYER: ::NTSTATUS = 0xC0220014u32 as i32; +pub const STATUS_FWP_KM_CLIENTS_ONLY: ::NTSTATUS = 0xC0220015u32 as i32; +pub const STATUS_FWP_LIFETIME_MISMATCH: ::NTSTATUS = 0xC0220016u32 as i32; +pub const STATUS_FWP_BUILTIN_OBJECT: ::NTSTATUS = 0xC0220017u32 as i32; +pub const STATUS_FWP_TOO_MANY_CALLOUTS: ::NTSTATUS = 0xC0220018u32 as i32; +pub const STATUS_FWP_NOTIFICATION_DROPPED: ::NTSTATUS = 0xC0220019u32 as i32; +pub const STATUS_FWP_TRAFFIC_MISMATCH: ::NTSTATUS = 0xC022001Au32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_SA_STATE: ::NTSTATUS = 0xC022001Bu32 as i32; +pub const STATUS_FWP_NULL_POINTER: ::NTSTATUS = 0xC022001Cu32 as i32; +pub const STATUS_FWP_INVALID_ENUMERATOR: ::NTSTATUS = 0xC022001Du32 as i32; +pub const STATUS_FWP_INVALID_FLAGS: ::NTSTATUS = 0xC022001Eu32 as i32; +pub const STATUS_FWP_INVALID_NET_MASK: ::NTSTATUS = 0xC022001Fu32 as i32; +pub const STATUS_FWP_INVALID_RANGE: ::NTSTATUS = 0xC0220020u32 as i32; +pub const STATUS_FWP_INVALID_INTERVAL: ::NTSTATUS = 0xC0220021u32 as i32; +pub const STATUS_FWP_ZERO_LENGTH_ARRAY: ::NTSTATUS = 0xC0220022u32 as i32; +pub const STATUS_FWP_NULL_DISPLAY_NAME: ::NTSTATUS = 0xC0220023u32 as i32; +pub const STATUS_FWP_INVALID_ACTION_TYPE: ::NTSTATUS = 0xC0220024u32 as i32; +pub const STATUS_FWP_INVALID_WEIGHT: ::NTSTATUS = 0xC0220025u32 as i32; +pub const STATUS_FWP_MATCH_TYPE_MISMATCH: ::NTSTATUS = 0xC0220026u32 as i32; +pub const STATUS_FWP_TYPE_MISMATCH: ::NTSTATUS = 0xC0220027u32 as i32; +pub const STATUS_FWP_OUT_OF_BOUNDS: ::NTSTATUS = 0xC0220028u32 as i32; +pub const STATUS_FWP_RESERVED: ::NTSTATUS = 0xC0220029u32 as i32; +pub const STATUS_FWP_DUPLICATE_CONDITION: ::NTSTATUS = 0xC022002Au32 as i32; +pub const STATUS_FWP_DUPLICATE_KEYMOD: ::NTSTATUS = 0xC022002Bu32 as i32; +pub const STATUS_FWP_ACTION_INCOMPATIBLE_WITH_LAYER: ::NTSTATUS = 0xC022002Cu32 as i32; +pub const STATUS_FWP_ACTION_INCOMPATIBLE_WITH_SUBLAYER: ::NTSTATUS = 0xC022002Du32 as i32; +pub const STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_LAYER: ::NTSTATUS = 0xC022002Eu32 as i32; +pub const STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_CALLOUT: ::NTSTATUS = 0xC022002Fu32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_AUTH_METHOD: ::NTSTATUS = 0xC0220030u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_DH_GROUP: ::NTSTATUS = 0xC0220031u32 as i32; +pub const STATUS_FWP_EM_NOT_SUPPORTED: ::NTSTATUS = 0xC0220032u32 as i32; +pub const STATUS_FWP_NEVER_MATCH: ::NTSTATUS = 0xC0220033u32 as i32; +pub const STATUS_FWP_PROVIDER_CONTEXT_MISMATCH: ::NTSTATUS = 0xC0220034u32 as i32; +pub const STATUS_FWP_INVALID_PARAMETER: ::NTSTATUS = 0xC0220035u32 as i32; +pub const STATUS_FWP_TOO_MANY_SUBLAYERS: ::NTSTATUS = 0xC0220036u32 as i32; +pub const STATUS_FWP_CALLOUT_NOTIFICATION_FAILED: ::NTSTATUS = 0xC0220037u32 as i32; +pub const STATUS_FWP_INVALID_AUTH_TRANSFORM: ::NTSTATUS = 0xC0220038u32 as i32; +pub const STATUS_FWP_INVALID_CIPHER_TRANSFORM: ::NTSTATUS = 0xC0220039u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_CIPHER_TRANSFORM: ::NTSTATUS = 0xC022003Au32 as i32; +pub const STATUS_FWP_INVALID_TRANSFORM_COMBINATION: ::NTSTATUS = 0xC022003Bu32 as i32; +pub const STATUS_FWP_DUPLICATE_AUTH_METHOD: ::NTSTATUS = 0xC022003Cu32 as i32; +pub const STATUS_FWP_INVALID_TUNNEL_ENDPOINT: ::NTSTATUS = 0xC022003Du32 as i32; +pub const STATUS_FWP_L2_DRIVER_NOT_READY: ::NTSTATUS = 0xC022003Eu32 as i32; +pub const STATUS_FWP_KEY_DICTATOR_ALREADY_REGISTERED: ::NTSTATUS = 0xC022003Fu32 as i32; +pub const STATUS_FWP_KEY_DICTATION_INVALID_KEYING_MATERIAL: ::NTSTATUS = 0xC0220040u32 as i32; +pub const STATUS_FWP_CONNECTIONS_DISABLED: ::NTSTATUS = 0xC0220041u32 as i32; +pub const STATUS_FWP_INVALID_DNS_NAME: ::NTSTATUS = 0xC0220042u32 as i32; +pub const STATUS_FWP_STILL_ON: ::NTSTATUS = 0xC0220043u32 as i32; +pub const STATUS_FWP_IKEEXT_NOT_RUNNING: ::NTSTATUS = 0xC0220044u32 as i32; +pub const STATUS_FWP_TCPIP_NOT_READY: ::NTSTATUS = 0xC0220100u32 as i32; +pub const STATUS_FWP_INJECT_HANDLE_CLOSING: ::NTSTATUS = 0xC0220101u32 as i32; +pub const STATUS_FWP_INJECT_HANDLE_STALE: ::NTSTATUS = 0xC0220102u32 as i32; +pub const STATUS_FWP_CANNOT_PEND: ::NTSTATUS = 0xC0220103u32 as i32; +pub const STATUS_FWP_DROP_NOICMP: ::NTSTATUS = 0xC0220104u32 as i32; +pub const STATUS_NDIS_CLOSING: ::NTSTATUS = 0xC0230002u32 as i32; +pub const STATUS_NDIS_BAD_VERSION: ::NTSTATUS = 0xC0230004u32 as i32; +pub const STATUS_NDIS_BAD_CHARACTERISTICS: ::NTSTATUS = 0xC0230005u32 as i32; +pub const STATUS_NDIS_ADAPTER_NOT_FOUND: ::NTSTATUS = 0xC0230006u32 as i32; +pub const STATUS_NDIS_OPEN_FAILED: ::NTSTATUS = 0xC0230007u32 as i32; +pub const STATUS_NDIS_DEVICE_FAILED: ::NTSTATUS = 0xC0230008u32 as i32; +pub const STATUS_NDIS_MULTICAST_FULL: ::NTSTATUS = 0xC0230009u32 as i32; +pub const STATUS_NDIS_MULTICAST_EXISTS: ::NTSTATUS = 0xC023000Au32 as i32; +pub const STATUS_NDIS_MULTICAST_NOT_FOUND: ::NTSTATUS = 0xC023000Bu32 as i32; +pub const STATUS_NDIS_REQUEST_ABORTED: ::NTSTATUS = 0xC023000Cu32 as i32; +pub const STATUS_NDIS_RESET_IN_PROGRESS: ::NTSTATUS = 0xC023000Du32 as i32; +pub const STATUS_NDIS_NOT_SUPPORTED: ::NTSTATUS = 0xC02300BBu32 as i32; +pub const STATUS_NDIS_INVALID_PACKET: ::NTSTATUS = 0xC023000Fu32 as i32; +pub const STATUS_NDIS_ADAPTER_NOT_READY: ::NTSTATUS = 0xC0230011u32 as i32; +pub const STATUS_NDIS_INVALID_LENGTH: ::NTSTATUS = 0xC0230014u32 as i32; +pub const STATUS_NDIS_INVALID_DATA: ::NTSTATUS = 0xC0230015u32 as i32; +pub const STATUS_NDIS_BUFFER_TOO_SHORT: ::NTSTATUS = 0xC0230016u32 as i32; +pub const STATUS_NDIS_INVALID_OID: ::NTSTATUS = 0xC0230017u32 as i32; +pub const STATUS_NDIS_ADAPTER_REMOVED: ::NTSTATUS = 0xC0230018u32 as i32; +pub const STATUS_NDIS_UNSUPPORTED_MEDIA: ::NTSTATUS = 0xC0230019u32 as i32; +pub const STATUS_NDIS_GROUP_ADDRESS_IN_USE: ::NTSTATUS = 0xC023001Au32 as i32; +pub const STATUS_NDIS_FILE_NOT_FOUND: ::NTSTATUS = 0xC023001Bu32 as i32; +pub const STATUS_NDIS_ERROR_READING_FILE: ::NTSTATUS = 0xC023001Cu32 as i32; +pub const STATUS_NDIS_ALREADY_MAPPED: ::NTSTATUS = 0xC023001Du32 as i32; +pub const STATUS_NDIS_RESOURCE_CONFLICT: ::NTSTATUS = 0xC023001Eu32 as i32; +pub const STATUS_NDIS_MEDIA_DISCONNECTED: ::NTSTATUS = 0xC023001Fu32 as i32; +pub const STATUS_NDIS_INVALID_ADDRESS: ::NTSTATUS = 0xC0230022u32 as i32; +pub const STATUS_NDIS_INVALID_DEVICE_REQUEST: ::NTSTATUS = 0xC0230010u32 as i32; +pub const STATUS_NDIS_PAUSED: ::NTSTATUS = 0xC023002Au32 as i32; +pub const STATUS_NDIS_INTERFACE_NOT_FOUND: ::NTSTATUS = 0xC023002Bu32 as i32; +pub const STATUS_NDIS_UNSUPPORTED_REVISION: ::NTSTATUS = 0xC023002Cu32 as i32; +pub const STATUS_NDIS_INVALID_PORT: ::NTSTATUS = 0xC023002Du32 as i32; +pub const STATUS_NDIS_INVALID_PORT_STATE: ::NTSTATUS = 0xC023002Eu32 as i32; +pub const STATUS_NDIS_LOW_POWER_STATE: ::NTSTATUS = 0xC023002Fu32 as i32; +pub const STATUS_NDIS_REINIT_REQUIRED: ::NTSTATUS = 0xC0230030u32 as i32; +pub const STATUS_NDIS_DOT11_AUTO_CONFIG_ENABLED: ::NTSTATUS = 0xC0232000u32 as i32; +pub const STATUS_NDIS_DOT11_MEDIA_IN_USE: ::NTSTATUS = 0xC0232001u32 as i32; +pub const STATUS_NDIS_DOT11_POWER_STATE_INVALID: ::NTSTATUS = 0xC0232002u32 as i32; +pub const STATUS_NDIS_PM_WOL_PATTERN_LIST_FULL: ::NTSTATUS = 0xC0232003u32 as i32; +pub const STATUS_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL: ::NTSTATUS = 0xC0232004u32 as i32; +pub const STATUS_NDIS_INDICATION_REQUIRED: ::NTSTATUS = 0x40230001; +pub const STATUS_NDIS_OFFLOAD_POLICY: ::NTSTATUS = 0xC023100Fu32 as i32; +pub const STATUS_NDIS_OFFLOAD_CONNECTION_REJECTED: ::NTSTATUS = 0xC0231012u32 as i32; +pub const STATUS_NDIS_OFFLOAD_PATH_REJECTED: ::NTSTATUS = 0xC0231013u32 as i32; +pub const STATUS_TPM_ERROR_MASK: ::NTSTATUS = 0xC0290000u32 as i32; +pub const STATUS_TPM_AUTHFAIL: ::NTSTATUS = 0xC0290001u32 as i32; +pub const STATUS_TPM_BADINDEX: ::NTSTATUS = 0xC0290002u32 as i32; +pub const STATUS_TPM_BAD_PARAMETER: ::NTSTATUS = 0xC0290003u32 as i32; +pub const STATUS_TPM_AUDITFAILURE: ::NTSTATUS = 0xC0290004u32 as i32; +pub const STATUS_TPM_CLEAR_DISABLED: ::NTSTATUS = 0xC0290005u32 as i32; +pub const STATUS_TPM_DEACTIVATED: ::NTSTATUS = 0xC0290006u32 as i32; +pub const STATUS_TPM_DISABLED: ::NTSTATUS = 0xC0290007u32 as i32; +pub const STATUS_TPM_DISABLED_CMD: ::NTSTATUS = 0xC0290008u32 as i32; +pub const STATUS_TPM_FAIL: ::NTSTATUS = 0xC0290009u32 as i32; +pub const STATUS_TPM_BAD_ORDINAL: ::NTSTATUS = 0xC029000Au32 as i32; +pub const STATUS_TPM_INSTALL_DISABLED: ::NTSTATUS = 0xC029000Bu32 as i32; +pub const STATUS_TPM_INVALID_KEYHANDLE: ::NTSTATUS = 0xC029000Cu32 as i32; +pub const STATUS_TPM_KEYNOTFOUND: ::NTSTATUS = 0xC029000Du32 as i32; +pub const STATUS_TPM_INAPPROPRIATE_ENC: ::NTSTATUS = 0xC029000Eu32 as i32; +pub const STATUS_TPM_MIGRATEFAIL: ::NTSTATUS = 0xC029000Fu32 as i32; +pub const STATUS_TPM_INVALID_PCR_INFO: ::NTSTATUS = 0xC0290010u32 as i32; +pub const STATUS_TPM_NOSPACE: ::NTSTATUS = 0xC0290011u32 as i32; +pub const STATUS_TPM_NOSRK: ::NTSTATUS = 0xC0290012u32 as i32; +pub const STATUS_TPM_NOTSEALED_BLOB: ::NTSTATUS = 0xC0290013u32 as i32; +pub const STATUS_TPM_OWNER_SET: ::NTSTATUS = 0xC0290014u32 as i32; +pub const STATUS_TPM_RESOURCES: ::NTSTATUS = 0xC0290015u32 as i32; +pub const STATUS_TPM_SHORTRANDOM: ::NTSTATUS = 0xC0290016u32 as i32; +pub const STATUS_TPM_SIZE: ::NTSTATUS = 0xC0290017u32 as i32; +pub const STATUS_TPM_WRONGPCRVAL: ::NTSTATUS = 0xC0290018u32 as i32; +pub const STATUS_TPM_BAD_PARAM_SIZE: ::NTSTATUS = 0xC0290019u32 as i32; +pub const STATUS_TPM_SHA_THREAD: ::NTSTATUS = 0xC029001Au32 as i32; +pub const STATUS_TPM_SHA_ERROR: ::NTSTATUS = 0xC029001Bu32 as i32; +pub const STATUS_TPM_FAILEDSELFTEST: ::NTSTATUS = 0xC029001Cu32 as i32; +pub const STATUS_TPM_AUTH2FAIL: ::NTSTATUS = 0xC029001Du32 as i32; +pub const STATUS_TPM_BADTAG: ::NTSTATUS = 0xC029001Eu32 as i32; +pub const STATUS_TPM_IOERROR: ::NTSTATUS = 0xC029001Fu32 as i32; +pub const STATUS_TPM_ENCRYPT_ERROR: ::NTSTATUS = 0xC0290020u32 as i32; +pub const STATUS_TPM_DECRYPT_ERROR: ::NTSTATUS = 0xC0290021u32 as i32; +pub const STATUS_TPM_INVALID_AUTHHANDLE: ::NTSTATUS = 0xC0290022u32 as i32; +pub const STATUS_TPM_NO_ENDORSEMENT: ::NTSTATUS = 0xC0290023u32 as i32; +pub const STATUS_TPM_INVALID_KEYUSAGE: ::NTSTATUS = 0xC0290024u32 as i32; +pub const STATUS_TPM_WRONG_ENTITYTYPE: ::NTSTATUS = 0xC0290025u32 as i32; +pub const STATUS_TPM_INVALID_POSTINIT: ::NTSTATUS = 0xC0290026u32 as i32; +pub const STATUS_TPM_INAPPROPRIATE_SIG: ::NTSTATUS = 0xC0290027u32 as i32; +pub const STATUS_TPM_BAD_KEY_PROPERTY: ::NTSTATUS = 0xC0290028u32 as i32; +pub const STATUS_TPM_BAD_MIGRATION: ::NTSTATUS = 0xC0290029u32 as i32; +pub const STATUS_TPM_BAD_SCHEME: ::NTSTATUS = 0xC029002Au32 as i32; +pub const STATUS_TPM_BAD_DATASIZE: ::NTSTATUS = 0xC029002Bu32 as i32; +pub const STATUS_TPM_BAD_MODE: ::NTSTATUS = 0xC029002Cu32 as i32; +pub const STATUS_TPM_BAD_PRESENCE: ::NTSTATUS = 0xC029002Du32 as i32; +pub const STATUS_TPM_BAD_VERSION: ::NTSTATUS = 0xC029002Eu32 as i32; +pub const STATUS_TPM_NO_WRAP_TRANSPORT: ::NTSTATUS = 0xC029002Fu32 as i32; +pub const STATUS_TPM_AUDITFAIL_UNSUCCESSFUL: ::NTSTATUS = 0xC0290030u32 as i32; +pub const STATUS_TPM_AUDITFAIL_SUCCESSFUL: ::NTSTATUS = 0xC0290031u32 as i32; +pub const STATUS_TPM_NOTRESETABLE: ::NTSTATUS = 0xC0290032u32 as i32; +pub const STATUS_TPM_NOTLOCAL: ::NTSTATUS = 0xC0290033u32 as i32; +pub const STATUS_TPM_BAD_TYPE: ::NTSTATUS = 0xC0290034u32 as i32; +pub const STATUS_TPM_INVALID_RESOURCE: ::NTSTATUS = 0xC0290035u32 as i32; +pub const STATUS_TPM_NOTFIPS: ::NTSTATUS = 0xC0290036u32 as i32; +pub const STATUS_TPM_INVALID_FAMILY: ::NTSTATUS = 0xC0290037u32 as i32; +pub const STATUS_TPM_NO_NV_PERMISSION: ::NTSTATUS = 0xC0290038u32 as i32; +pub const STATUS_TPM_REQUIRES_SIGN: ::NTSTATUS = 0xC0290039u32 as i32; +pub const STATUS_TPM_KEY_NOTSUPPORTED: ::NTSTATUS = 0xC029003Au32 as i32; +pub const STATUS_TPM_AUTH_CONFLICT: ::NTSTATUS = 0xC029003Bu32 as i32; +pub const STATUS_TPM_AREA_LOCKED: ::NTSTATUS = 0xC029003Cu32 as i32; +pub const STATUS_TPM_BAD_LOCALITY: ::NTSTATUS = 0xC029003Du32 as i32; +pub const STATUS_TPM_READ_ONLY: ::NTSTATUS = 0xC029003Eu32 as i32; +pub const STATUS_TPM_PER_NOWRITE: ::NTSTATUS = 0xC029003Fu32 as i32; +pub const STATUS_TPM_FAMILYCOUNT: ::NTSTATUS = 0xC0290040u32 as i32; +pub const STATUS_TPM_WRITE_LOCKED: ::NTSTATUS = 0xC0290041u32 as i32; +pub const STATUS_TPM_BAD_ATTRIBUTES: ::NTSTATUS = 0xC0290042u32 as i32; +pub const STATUS_TPM_INVALID_STRUCTURE: ::NTSTATUS = 0xC0290043u32 as i32; +pub const STATUS_TPM_KEY_OWNER_CONTROL: ::NTSTATUS = 0xC0290044u32 as i32; +pub const STATUS_TPM_BAD_COUNTER: ::NTSTATUS = 0xC0290045u32 as i32; +pub const STATUS_TPM_NOT_FULLWRITE: ::NTSTATUS = 0xC0290046u32 as i32; +pub const STATUS_TPM_CONTEXT_GAP: ::NTSTATUS = 0xC0290047u32 as i32; +pub const STATUS_TPM_MAXNVWRITES: ::NTSTATUS = 0xC0290048u32 as i32; +pub const STATUS_TPM_NOOPERATOR: ::NTSTATUS = 0xC0290049u32 as i32; +pub const STATUS_TPM_RESOURCEMISSING: ::NTSTATUS = 0xC029004Au32 as i32; +pub const STATUS_TPM_DELEGATE_LOCK: ::NTSTATUS = 0xC029004Bu32 as i32; +pub const STATUS_TPM_DELEGATE_FAMILY: ::NTSTATUS = 0xC029004Cu32 as i32; +pub const STATUS_TPM_DELEGATE_ADMIN: ::NTSTATUS = 0xC029004Du32 as i32; +pub const STATUS_TPM_TRANSPORT_NOTEXCLUSIVE: ::NTSTATUS = 0xC029004Eu32 as i32; +pub const STATUS_TPM_OWNER_CONTROL: ::NTSTATUS = 0xC029004Fu32 as i32; +pub const STATUS_TPM_DAA_RESOURCES: ::NTSTATUS = 0xC0290050u32 as i32; +pub const STATUS_TPM_DAA_INPUT_DATA0: ::NTSTATUS = 0xC0290051u32 as i32; +pub const STATUS_TPM_DAA_INPUT_DATA1: ::NTSTATUS = 0xC0290052u32 as i32; +pub const STATUS_TPM_DAA_ISSUER_SETTINGS: ::NTSTATUS = 0xC0290053u32 as i32; +pub const STATUS_TPM_DAA_TPM_SETTINGS: ::NTSTATUS = 0xC0290054u32 as i32; +pub const STATUS_TPM_DAA_STAGE: ::NTSTATUS = 0xC0290055u32 as i32; +pub const STATUS_TPM_DAA_ISSUER_VALIDITY: ::NTSTATUS = 0xC0290056u32 as i32; +pub const STATUS_TPM_DAA_WRONG_W: ::NTSTATUS = 0xC0290057u32 as i32; +pub const STATUS_TPM_BAD_HANDLE: ::NTSTATUS = 0xC0290058u32 as i32; +pub const STATUS_TPM_BAD_DELEGATE: ::NTSTATUS = 0xC0290059u32 as i32; +pub const STATUS_TPM_BADCONTEXT: ::NTSTATUS = 0xC029005Au32 as i32; +pub const STATUS_TPM_TOOMANYCONTEXTS: ::NTSTATUS = 0xC029005Bu32 as i32; +pub const STATUS_TPM_MA_TICKET_SIGNATURE: ::NTSTATUS = 0xC029005Cu32 as i32; +pub const STATUS_TPM_MA_DESTINATION: ::NTSTATUS = 0xC029005Du32 as i32; +pub const STATUS_TPM_MA_SOURCE: ::NTSTATUS = 0xC029005Eu32 as i32; +pub const STATUS_TPM_MA_AUTHORITY: ::NTSTATUS = 0xC029005Fu32 as i32; +pub const STATUS_TPM_PERMANENTEK: ::NTSTATUS = 0xC0290061u32 as i32; +pub const STATUS_TPM_BAD_SIGNATURE: ::NTSTATUS = 0xC0290062u32 as i32; +pub const STATUS_TPM_NOCONTEXTSPACE: ::NTSTATUS = 0xC0290063u32 as i32; +pub const STATUS_TPM_COMMAND_BLOCKED: ::NTSTATUS = 0xC0290400u32 as i32; +pub const STATUS_TPM_INVALID_HANDLE: ::NTSTATUS = 0xC0290401u32 as i32; +pub const STATUS_TPM_DUPLICATE_VHANDLE: ::NTSTATUS = 0xC0290402u32 as i32; +pub const STATUS_TPM_EMBEDDED_COMMAND_BLOCKED: ::NTSTATUS = 0xC0290403u32 as i32; +pub const STATUS_TPM_EMBEDDED_COMMAND_UNSUPPORTED: ::NTSTATUS = 0xC0290404u32 as i32; +pub const STATUS_TPM_RETRY: ::NTSTATUS = 0xC0290800u32 as i32; +pub const STATUS_TPM_NEEDS_SELFTEST: ::NTSTATUS = 0xC0290801u32 as i32; +pub const STATUS_TPM_DOING_SELFTEST: ::NTSTATUS = 0xC0290802u32 as i32; +pub const STATUS_TPM_DEFEND_LOCK_RUNNING: ::NTSTATUS = 0xC0290803u32 as i32; +pub const STATUS_TPM_COMMAND_CANCELED: ::NTSTATUS = 0xC0291001u32 as i32; +pub const STATUS_TPM_TOO_MANY_CONTEXTS: ::NTSTATUS = 0xC0291002u32 as i32; +pub const STATUS_TPM_NOT_FOUND: ::NTSTATUS = 0xC0291003u32 as i32; +pub const STATUS_TPM_ACCESS_DENIED: ::NTSTATUS = 0xC0291004u32 as i32; +pub const STATUS_TPM_INSUFFICIENT_BUFFER: ::NTSTATUS = 0xC0291005u32 as i32; +pub const STATUS_TPM_PPI_FUNCTION_UNSUPPORTED: ::NTSTATUS = 0xC0291006u32 as i32; +pub const STATUS_PCP_ERROR_MASK: ::NTSTATUS = 0xC0292000u32 as i32; +pub const STATUS_PCP_DEVICE_NOT_READY: ::NTSTATUS = 0xC0292001u32 as i32; +pub const STATUS_PCP_INVALID_HANDLE: ::NTSTATUS = 0xC0292002u32 as i32; +pub const STATUS_PCP_INVALID_PARAMETER: ::NTSTATUS = 0xC0292003u32 as i32; +pub const STATUS_PCP_FLAG_NOT_SUPPORTED: ::NTSTATUS = 0xC0292004u32 as i32; +pub const STATUS_PCP_NOT_SUPPORTED: ::NTSTATUS = 0xC0292005u32 as i32; +pub const STATUS_PCP_BUFFER_TOO_SMALL: ::NTSTATUS = 0xC0292006u32 as i32; +pub const STATUS_PCP_INTERNAL_ERROR: ::NTSTATUS = 0xC0292007u32 as i32; +pub const STATUS_PCP_AUTHENTICATION_FAILED: ::NTSTATUS = 0xC0292008u32 as i32; +pub const STATUS_PCP_AUTHENTICATION_IGNORED: ::NTSTATUS = 0xC0292009u32 as i32; +pub const STATUS_PCP_POLICY_NOT_FOUND: ::NTSTATUS = 0xC029200Au32 as i32; +pub const STATUS_PCP_PROFILE_NOT_FOUND: ::NTSTATUS = 0xC029200Bu32 as i32; +pub const STATUS_PCP_VALIDATION_FAILED: ::NTSTATUS = 0xC029200Cu32 as i32; +pub const STATUS_PCP_DEVICE_NOT_FOUND: ::NTSTATUS = 0xC029200Du32 as i32; +pub const STATUS_RTPM_CONTEXT_CONTINUE: ::NTSTATUS = 0x00293000; +pub const STATUS_RTPM_CONTEXT_COMPLETE: ::NTSTATUS = 0x00293001; +pub const STATUS_RTPM_NO_RESULT: ::NTSTATUS = 0xC0293002u32 as i32; +pub const STATUS_RTPM_PCR_READ_INCOMPLETE: ::NTSTATUS = 0xC0293003u32 as i32; +pub const STATUS_RTPM_INVALID_CONTEXT: ::NTSTATUS = 0xC0293004u32 as i32; +pub const STATUS_RTPM_UNSUPPORTED_CMD: ::NTSTATUS = 0xC0293005u32 as i32; +pub const STATUS_HV_INVALID_HYPERCALL_CODE: ::NTSTATUS = 0xC0350002u32 as i32; +pub const STATUS_HV_INVALID_HYPERCALL_INPUT: ::NTSTATUS = 0xC0350003u32 as i32; +pub const STATUS_HV_INVALID_ALIGNMENT: ::NTSTATUS = 0xC0350004u32 as i32; +pub const STATUS_HV_INVALID_PARAMETER: ::NTSTATUS = 0xC0350005u32 as i32; +pub const STATUS_HV_ACCESS_DENIED: ::NTSTATUS = 0xC0350006u32 as i32; +pub const STATUS_HV_INVALID_PARTITION_STATE: ::NTSTATUS = 0xC0350007u32 as i32; +pub const STATUS_HV_OPERATION_DENIED: ::NTSTATUS = 0xC0350008u32 as i32; +pub const STATUS_HV_UNKNOWN_PROPERTY: ::NTSTATUS = 0xC0350009u32 as i32; +pub const STATUS_HV_PROPERTY_VALUE_OUT_OF_RANGE: ::NTSTATUS = 0xC035000Au32 as i32; +pub const STATUS_HV_INSUFFICIENT_MEMORY: ::NTSTATUS = 0xC035000Bu32 as i32; +pub const STATUS_HV_PARTITION_TOO_DEEP: ::NTSTATUS = 0xC035000Cu32 as i32; +pub const STATUS_HV_INVALID_PARTITION_ID: ::NTSTATUS = 0xC035000Du32 as i32; +pub const STATUS_HV_INVALID_VP_INDEX: ::NTSTATUS = 0xC035000Eu32 as i32; +pub const STATUS_HV_INVALID_PORT_ID: ::NTSTATUS = 0xC0350011u32 as i32; +pub const STATUS_HV_INVALID_CONNECTION_ID: ::NTSTATUS = 0xC0350012u32 as i32; +pub const STATUS_HV_INSUFFICIENT_BUFFERS: ::NTSTATUS = 0xC0350013u32 as i32; +pub const STATUS_HV_NOT_ACKNOWLEDGED: ::NTSTATUS = 0xC0350014u32 as i32; +pub const STATUS_HV_ACKNOWLEDGED: ::NTSTATUS = 0xC0350016u32 as i32; +pub const STATUS_HV_INVALID_SAVE_RESTORE_STATE: ::NTSTATUS = 0xC0350017u32 as i32; +pub const STATUS_HV_INVALID_SYNIC_STATE: ::NTSTATUS = 0xC0350018u32 as i32; +pub const STATUS_HV_OBJECT_IN_USE: ::NTSTATUS = 0xC0350019u32 as i32; +pub const STATUS_HV_INVALID_PROXIMITY_DOMAIN_INFO: ::NTSTATUS = 0xC035001Au32 as i32; +pub const STATUS_HV_NO_DATA: ::NTSTATUS = 0xC035001Bu32 as i32; +pub const STATUS_HV_INACTIVE: ::NTSTATUS = 0xC035001Cu32 as i32; +pub const STATUS_HV_NO_RESOURCES: ::NTSTATUS = 0xC035001Du32 as i32; +pub const STATUS_HV_FEATURE_UNAVAILABLE: ::NTSTATUS = 0xC035001Eu32 as i32; +pub const STATUS_HV_INSUFFICIENT_BUFFER: ::NTSTATUS = 0xC0350033u32 as i32; +pub const STATUS_HV_INSUFFICIENT_DEVICE_DOMAINS: ::NTSTATUS = 0xC0350038u32 as i32; +pub const STATUS_HV_CPUID_FEATURE_VALIDATION_ERROR: ::NTSTATUS = 0xC035003Cu32 as i32; +pub const STATUS_HV_CPUID_XSAVE_FEATURE_VALIDATION_ERROR: ::NTSTATUS = 0xC035003Du32 as i32; +pub const STATUS_HV_PROCESSOR_STARTUP_TIMEOUT: ::NTSTATUS = 0xC035003Eu32 as i32; +pub const STATUS_HV_SMX_ENABLED: ::NTSTATUS = 0xC035003Fu32 as i32; +pub const STATUS_HV_INVALID_LP_INDEX: ::NTSTATUS = 0xC0350041u32 as i32; +pub const STATUS_HV_INVALID_REGISTER_VALUE: ::NTSTATUS = 0xC0350050u32 as i32; +pub const STATUS_HV_INVALID_VTL_STATE: ::NTSTATUS = 0xC0350051u32 as i32; +pub const STATUS_HV_NX_NOT_DETECTED: ::NTSTATUS = 0xC0350055u32 as i32; +pub const STATUS_HV_INVALID_DEVICE_ID: ::NTSTATUS = 0xC0350057u32 as i32; +pub const STATUS_HV_INVALID_DEVICE_STATE: ::NTSTATUS = 0xC0350058u32 as i32; +pub const STATUS_HV_PENDING_PAGE_REQUESTS: ::NTSTATUS = 0x00350059; +pub const STATUS_HV_PAGE_REQUEST_INVALID: ::NTSTATUS = 0xC0350060u32 as i32; +pub const STATUS_HV_NOT_PRESENT: ::NTSTATUS = 0xC0351000u32 as i32; +pub const STATUS_VID_DUPLICATE_HANDLER: ::NTSTATUS = 0xC0370001u32 as i32; +pub const STATUS_VID_TOO_MANY_HANDLERS: ::NTSTATUS = 0xC0370002u32 as i32; +pub const STATUS_VID_QUEUE_FULL: ::NTSTATUS = 0xC0370003u32 as i32; +pub const STATUS_VID_HANDLER_NOT_PRESENT: ::NTSTATUS = 0xC0370004u32 as i32; +pub const STATUS_VID_INVALID_OBJECT_NAME: ::NTSTATUS = 0xC0370005u32 as i32; +pub const STATUS_VID_PARTITION_NAME_TOO_LONG: ::NTSTATUS = 0xC0370006u32 as i32; +pub const STATUS_VID_MESSAGE_QUEUE_NAME_TOO_LONG: ::NTSTATUS = 0xC0370007u32 as i32; +pub const STATUS_VID_PARTITION_ALREADY_EXISTS: ::NTSTATUS = 0xC0370008u32 as i32; +pub const STATUS_VID_PARTITION_DOES_NOT_EXIST: ::NTSTATUS = 0xC0370009u32 as i32; +pub const STATUS_VID_PARTITION_NAME_NOT_FOUND: ::NTSTATUS = 0xC037000Au32 as i32; +pub const STATUS_VID_MESSAGE_QUEUE_ALREADY_EXISTS: ::NTSTATUS = 0xC037000Bu32 as i32; +pub const STATUS_VID_EXCEEDED_MBP_ENTRY_MAP_LIMIT: ::NTSTATUS = 0xC037000Cu32 as i32; +pub const STATUS_VID_MB_STILL_REFERENCED: ::NTSTATUS = 0xC037000Du32 as i32; +pub const STATUS_VID_CHILD_GPA_PAGE_SET_CORRUPTED: ::NTSTATUS = 0xC037000Eu32 as i32; +pub const STATUS_VID_INVALID_NUMA_SETTINGS: ::NTSTATUS = 0xC037000Fu32 as i32; +pub const STATUS_VID_INVALID_NUMA_NODE_INDEX: ::NTSTATUS = 0xC0370010u32 as i32; +pub const STATUS_VID_NOTIFICATION_QUEUE_ALREADY_ASSOCIATED: ::NTSTATUS = 0xC0370011u32 as i32; +pub const STATUS_VID_INVALID_MEMORY_BLOCK_HANDLE: ::NTSTATUS = 0xC0370012u32 as i32; +pub const STATUS_VID_PAGE_RANGE_OVERFLOW: ::NTSTATUS = 0xC0370013u32 as i32; +pub const STATUS_VID_INVALID_MESSAGE_QUEUE_HANDLE: ::NTSTATUS = 0xC0370014u32 as i32; +pub const STATUS_VID_INVALID_GPA_RANGE_HANDLE: ::NTSTATUS = 0xC0370015u32 as i32; +pub const STATUS_VID_NO_MEMORY_BLOCK_NOTIFICATION_QUEUE: ::NTSTATUS = 0xC0370016u32 as i32; +pub const STATUS_VID_MEMORY_BLOCK_LOCK_COUNT_EXCEEDED: ::NTSTATUS = 0xC0370017u32 as i32; +pub const STATUS_VID_INVALID_PPM_HANDLE: ::NTSTATUS = 0xC0370018u32 as i32; +pub const STATUS_VID_MBPS_ARE_LOCKED: ::NTSTATUS = 0xC0370019u32 as i32; +pub const STATUS_VID_MESSAGE_QUEUE_CLOSED: ::NTSTATUS = 0xC037001Au32 as i32; +pub const STATUS_VID_VIRTUAL_PROCESSOR_LIMIT_EXCEEDED: ::NTSTATUS = 0xC037001Bu32 as i32; +pub const STATUS_VID_STOP_PENDING: ::NTSTATUS = 0xC037001Cu32 as i32; +pub const STATUS_VID_INVALID_PROCESSOR_STATE: ::NTSTATUS = 0xC037001Du32 as i32; +pub const STATUS_VID_EXCEEDED_KM_CONTEXT_COUNT_LIMIT: ::NTSTATUS = 0xC037001Eu32 as i32; +pub const STATUS_VID_KM_INTERFACE_ALREADY_INITIALIZED: ::NTSTATUS = 0xC037001Fu32 as i32; +pub const STATUS_VID_MB_PROPERTY_ALREADY_SET_RESET: ::NTSTATUS = 0xC0370020u32 as i32; +pub const STATUS_VID_MMIO_RANGE_DESTROYED: ::NTSTATUS = 0xC0370021u32 as i32; +pub const STATUS_VID_INVALID_CHILD_GPA_PAGE_SET: ::NTSTATUS = 0xC0370022u32 as i32; +pub const STATUS_VID_RESERVE_PAGE_SET_IS_BEING_USED: ::NTSTATUS = 0xC0370023u32 as i32; +pub const STATUS_VID_RESERVE_PAGE_SET_TOO_SMALL: ::NTSTATUS = 0xC0370024u32 as i32; +pub const STATUS_VID_MBP_ALREADY_LOCKED_USING_RESERVED_PAGE: ::NTSTATUS = 0xC0370025u32 as i32; +pub const STATUS_VID_MBP_COUNT_EXCEEDED_LIMIT: ::NTSTATUS = 0xC0370026u32 as i32; +pub const STATUS_VID_SAVED_STATE_CORRUPT: ::NTSTATUS = 0xC0370027u32 as i32; +pub const STATUS_VID_SAVED_STATE_UNRECOGNIZED_ITEM: ::NTSTATUS = 0xC0370028u32 as i32; +pub const STATUS_VID_SAVED_STATE_INCOMPATIBLE: ::NTSTATUS = 0xC0370029u32 as i32; +pub const STATUS_VID_REMOTE_NODE_PARENT_GPA_PAGES_USED: ::NTSTATUS = 0x80370001u32 as i32; +pub const STATUS_IPSEC_BAD_SPI: ::NTSTATUS = 0xC0360001u32 as i32; +pub const STATUS_IPSEC_SA_LIFETIME_EXPIRED: ::NTSTATUS = 0xC0360002u32 as i32; +pub const STATUS_IPSEC_WRONG_SA: ::NTSTATUS = 0xC0360003u32 as i32; +pub const STATUS_IPSEC_REPLAY_CHECK_FAILED: ::NTSTATUS = 0xC0360004u32 as i32; +pub const STATUS_IPSEC_INVALID_PACKET: ::NTSTATUS = 0xC0360005u32 as i32; +pub const STATUS_IPSEC_INTEGRITY_CHECK_FAILED: ::NTSTATUS = 0xC0360006u32 as i32; +pub const STATUS_IPSEC_CLEAR_TEXT_DROP: ::NTSTATUS = 0xC0360007u32 as i32; +pub const STATUS_IPSEC_AUTH_FIREWALL_DROP: ::NTSTATUS = 0xC0360008u32 as i32; +pub const STATUS_IPSEC_THROTTLE_DROP: ::NTSTATUS = 0xC0360009u32 as i32; +pub const STATUS_IPSEC_DOSP_BLOCK: ::NTSTATUS = 0xC0368000u32 as i32; +pub const STATUS_IPSEC_DOSP_RECEIVED_MULTICAST: ::NTSTATUS = 0xC0368001u32 as i32; +pub const STATUS_IPSEC_DOSP_INVALID_PACKET: ::NTSTATUS = 0xC0368002u32 as i32; +pub const STATUS_IPSEC_DOSP_STATE_LOOKUP_FAILED: ::NTSTATUS = 0xC0368003u32 as i32; +pub const STATUS_IPSEC_DOSP_MAX_ENTRIES: ::NTSTATUS = 0xC0368004u32 as i32; +pub const STATUS_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: ::NTSTATUS = 0xC0368005u32 as i32; +pub const STATUS_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: ::NTSTATUS = 0xC0368006u32 as i32; +pub const STATUS_VOLMGR_INCOMPLETE_REGENERATION: ::NTSTATUS = 0x80380001u32 as i32; +pub const STATUS_VOLMGR_INCOMPLETE_DISK_MIGRATION: ::NTSTATUS = 0x80380002u32 as i32; +pub const STATUS_VOLMGR_DATABASE_FULL: ::NTSTATUS = 0xC0380001u32 as i32; +pub const STATUS_VOLMGR_DISK_CONFIGURATION_CORRUPTED: ::NTSTATUS = 0xC0380002u32 as i32; +pub const STATUS_VOLMGR_DISK_CONFIGURATION_NOT_IN_SYNC: ::NTSTATUS = 0xC0380003u32 as i32; +pub const STATUS_VOLMGR_PACK_CONFIG_UPDATE_FAILED: ::NTSTATUS = 0xC0380004u32 as i32; +pub const STATUS_VOLMGR_DISK_CONTAINS_NON_SIMPLE_VOLUME: ::NTSTATUS = 0xC0380005u32 as i32; +pub const STATUS_VOLMGR_DISK_DUPLICATE: ::NTSTATUS = 0xC0380006u32 as i32; +pub const STATUS_VOLMGR_DISK_DYNAMIC: ::NTSTATUS = 0xC0380007u32 as i32; +pub const STATUS_VOLMGR_DISK_ID_INVALID: ::NTSTATUS = 0xC0380008u32 as i32; +pub const STATUS_VOLMGR_DISK_INVALID: ::NTSTATUS = 0xC0380009u32 as i32; +pub const STATUS_VOLMGR_DISK_LAST_VOTER: ::NTSTATUS = 0xC038000Au32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_INVALID: ::NTSTATUS = 0xC038000Bu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_NON_BASIC_BETWEEN_BASIC_PARTITIONS: ::NTSTATUS = 0xC038000Cu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_NOT_CYLINDER_ALIGNED: ::NTSTATUS = 0xC038000Du32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_PARTITIONS_TOO_SMALL: ::NTSTATUS = 0xC038000Eu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_PRIMARY_BETWEEN_LOGICAL_PARTITIONS: ::NTSTATUS = 0xC038000Fu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_TOO_MANY_PARTITIONS: ::NTSTATUS = 0xC0380010u32 as i32; +pub const STATUS_VOLMGR_DISK_MISSING: ::NTSTATUS = 0xC0380011u32 as i32; +pub const STATUS_VOLMGR_DISK_NOT_EMPTY: ::NTSTATUS = 0xC0380012u32 as i32; +pub const STATUS_VOLMGR_DISK_NOT_ENOUGH_SPACE: ::NTSTATUS = 0xC0380013u32 as i32; +pub const STATUS_VOLMGR_DISK_REVECTORING_FAILED: ::NTSTATUS = 0xC0380014u32 as i32; +pub const STATUS_VOLMGR_DISK_SECTOR_SIZE_INVALID: ::NTSTATUS = 0xC0380015u32 as i32; +pub const STATUS_VOLMGR_DISK_SET_NOT_CONTAINED: ::NTSTATUS = 0xC0380016u32 as i32; +pub const STATUS_VOLMGR_DISK_USED_BY_MULTIPLE_MEMBERS: ::NTSTATUS = 0xC0380017u32 as i32; +pub const STATUS_VOLMGR_DISK_USED_BY_MULTIPLE_PLEXES: ::NTSTATUS = 0xC0380018u32 as i32; +pub const STATUS_VOLMGR_DYNAMIC_DISK_NOT_SUPPORTED: ::NTSTATUS = 0xC0380019u32 as i32; +pub const STATUS_VOLMGR_EXTENT_ALREADY_USED: ::NTSTATUS = 0xC038001Au32 as i32; +pub const STATUS_VOLMGR_EXTENT_NOT_CONTIGUOUS: ::NTSTATUS = 0xC038001Bu32 as i32; +pub const STATUS_VOLMGR_EXTENT_NOT_IN_PUBLIC_REGION: ::NTSTATUS = 0xC038001Cu32 as i32; +pub const STATUS_VOLMGR_EXTENT_NOT_SECTOR_ALIGNED: ::NTSTATUS = 0xC038001Du32 as i32; +pub const STATUS_VOLMGR_EXTENT_OVERLAPS_EBR_PARTITION: ::NTSTATUS = 0xC038001Eu32 as i32; +pub const STATUS_VOLMGR_EXTENT_VOLUME_LENGTHS_DO_NOT_MATCH: ::NTSTATUS = 0xC038001Fu32 as i32; +pub const STATUS_VOLMGR_FAULT_TOLERANT_NOT_SUPPORTED: ::NTSTATUS = 0xC0380020u32 as i32; +pub const STATUS_VOLMGR_INTERLEAVE_LENGTH_INVALID: ::NTSTATUS = 0xC0380021u32 as i32; +pub const STATUS_VOLMGR_MAXIMUM_REGISTERED_USERS: ::NTSTATUS = 0xC0380022u32 as i32; +pub const STATUS_VOLMGR_MEMBER_IN_SYNC: ::NTSTATUS = 0xC0380023u32 as i32; +pub const STATUS_VOLMGR_MEMBER_INDEX_DUPLICATE: ::NTSTATUS = 0xC0380024u32 as i32; +pub const STATUS_VOLMGR_MEMBER_INDEX_INVALID: ::NTSTATUS = 0xC0380025u32 as i32; +pub const STATUS_VOLMGR_MEMBER_MISSING: ::NTSTATUS = 0xC0380026u32 as i32; +pub const STATUS_VOLMGR_MEMBER_NOT_DETACHED: ::NTSTATUS = 0xC0380027u32 as i32; +pub const STATUS_VOLMGR_MEMBER_REGENERATING: ::NTSTATUS = 0xC0380028u32 as i32; +pub const STATUS_VOLMGR_ALL_DISKS_FAILED: ::NTSTATUS = 0xC0380029u32 as i32; +pub const STATUS_VOLMGR_NO_REGISTERED_USERS: ::NTSTATUS = 0xC038002Au32 as i32; +pub const STATUS_VOLMGR_NO_SUCH_USER: ::NTSTATUS = 0xC038002Bu32 as i32; +pub const STATUS_VOLMGR_NOTIFICATION_RESET: ::NTSTATUS = 0xC038002Cu32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_MEMBERS_INVALID: ::NTSTATUS = 0xC038002Du32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_PLEXES_INVALID: ::NTSTATUS = 0xC038002Eu32 as i32; +pub const STATUS_VOLMGR_PACK_DUPLICATE: ::NTSTATUS = 0xC038002Fu32 as i32; +pub const STATUS_VOLMGR_PACK_ID_INVALID: ::NTSTATUS = 0xC0380030u32 as i32; +pub const STATUS_VOLMGR_PACK_INVALID: ::NTSTATUS = 0xC0380031u32 as i32; +pub const STATUS_VOLMGR_PACK_NAME_INVALID: ::NTSTATUS = 0xC0380032u32 as i32; +pub const STATUS_VOLMGR_PACK_OFFLINE: ::NTSTATUS = 0xC0380033u32 as i32; +pub const STATUS_VOLMGR_PACK_HAS_QUORUM: ::NTSTATUS = 0xC0380034u32 as i32; +pub const STATUS_VOLMGR_PACK_WITHOUT_QUORUM: ::NTSTATUS = 0xC0380035u32 as i32; +pub const STATUS_VOLMGR_PARTITION_STYLE_INVALID: ::NTSTATUS = 0xC0380036u32 as i32; +pub const STATUS_VOLMGR_PARTITION_UPDATE_FAILED: ::NTSTATUS = 0xC0380037u32 as i32; +pub const STATUS_VOLMGR_PLEX_IN_SYNC: ::NTSTATUS = 0xC0380038u32 as i32; +pub const STATUS_VOLMGR_PLEX_INDEX_DUPLICATE: ::NTSTATUS = 0xC0380039u32 as i32; +pub const STATUS_VOLMGR_PLEX_INDEX_INVALID: ::NTSTATUS = 0xC038003Au32 as i32; +pub const STATUS_VOLMGR_PLEX_LAST_ACTIVE: ::NTSTATUS = 0xC038003Bu32 as i32; +pub const STATUS_VOLMGR_PLEX_MISSING: ::NTSTATUS = 0xC038003Cu32 as i32; +pub const STATUS_VOLMGR_PLEX_REGENERATING: ::NTSTATUS = 0xC038003Du32 as i32; +pub const STATUS_VOLMGR_PLEX_TYPE_INVALID: ::NTSTATUS = 0xC038003Eu32 as i32; +pub const STATUS_VOLMGR_PLEX_NOT_RAID5: ::NTSTATUS = 0xC038003Fu32 as i32; +pub const STATUS_VOLMGR_PLEX_NOT_SIMPLE: ::NTSTATUS = 0xC0380040u32 as i32; +pub const STATUS_VOLMGR_STRUCTURE_SIZE_INVALID: ::NTSTATUS = 0xC0380041u32 as i32; +pub const STATUS_VOLMGR_TOO_MANY_NOTIFICATION_REQUESTS: ::NTSTATUS = 0xC0380042u32 as i32; +pub const STATUS_VOLMGR_TRANSACTION_IN_PROGRESS: ::NTSTATUS = 0xC0380043u32 as i32; +pub const STATUS_VOLMGR_UNEXPECTED_DISK_LAYOUT_CHANGE: ::NTSTATUS = 0xC0380044u32 as i32; +pub const STATUS_VOLMGR_VOLUME_CONTAINS_MISSING_DISK: ::NTSTATUS = 0xC0380045u32 as i32; +pub const STATUS_VOLMGR_VOLUME_ID_INVALID: ::NTSTATUS = 0xC0380046u32 as i32; +pub const STATUS_VOLMGR_VOLUME_LENGTH_INVALID: ::NTSTATUS = 0xC0380047u32 as i32; +pub const STATUS_VOLMGR_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: ::NTSTATUS = 0xC0380048u32 as i32; +pub const STATUS_VOLMGR_VOLUME_NOT_MIRRORED: ::NTSTATUS = 0xC0380049u32 as i32; +pub const STATUS_VOLMGR_VOLUME_NOT_RETAINED: ::NTSTATUS = 0xC038004Au32 as i32; +pub const STATUS_VOLMGR_VOLUME_OFFLINE: ::NTSTATUS = 0xC038004Bu32 as i32; +pub const STATUS_VOLMGR_VOLUME_RETAINED: ::NTSTATUS = 0xC038004Cu32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_EXTENTS_INVALID: ::NTSTATUS = 0xC038004Du32 as i32; +pub const STATUS_VOLMGR_DIFFERENT_SECTOR_SIZE: ::NTSTATUS = 0xC038004Eu32 as i32; +pub const STATUS_VOLMGR_BAD_BOOT_DISK: ::NTSTATUS = 0xC038004Fu32 as i32; +pub const STATUS_VOLMGR_PACK_CONFIG_OFFLINE: ::NTSTATUS = 0xC0380050u32 as i32; +pub const STATUS_VOLMGR_PACK_CONFIG_ONLINE: ::NTSTATUS = 0xC0380051u32 as i32; +pub const STATUS_VOLMGR_NOT_PRIMARY_PACK: ::NTSTATUS = 0xC0380052u32 as i32; +pub const STATUS_VOLMGR_PACK_LOG_UPDATE_FAILED: ::NTSTATUS = 0xC0380053u32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_DISKS_IN_PLEX_INVALID: ::NTSTATUS = 0xC0380054u32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_DISKS_IN_MEMBER_INVALID: ::NTSTATUS = 0xC0380055u32 as i32; +pub const STATUS_VOLMGR_VOLUME_MIRRORED: ::NTSTATUS = 0xC0380056u32 as i32; +pub const STATUS_VOLMGR_PLEX_NOT_SIMPLE_SPANNED: ::NTSTATUS = 0xC0380057u32 as i32; +pub const STATUS_VOLMGR_NO_VALID_LOG_COPIES: ::NTSTATUS = 0xC0380058u32 as i32; +pub const STATUS_VOLMGR_PRIMARY_PACK_PRESENT: ::NTSTATUS = 0xC0380059u32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_DISKS_INVALID: ::NTSTATUS = 0xC038005Au32 as i32; +pub const STATUS_VOLMGR_MIRROR_NOT_SUPPORTED: ::NTSTATUS = 0xC038005Bu32 as i32; +pub const STATUS_VOLMGR_RAID5_NOT_SUPPORTED: ::NTSTATUS = 0xC038005Cu32 as i32; +pub const STATUS_BCD_NOT_ALL_ENTRIES_IMPORTED: ::NTSTATUS = 0x80390001u32 as i32; +pub const STATUS_BCD_TOO_MANY_ELEMENTS: ::NTSTATUS = 0xC0390002u32 as i32; +pub const STATUS_BCD_NOT_ALL_ENTRIES_SYNCHRONIZED: ::NTSTATUS = 0x80390003u32 as i32; +pub const STATUS_VHD_DRIVE_FOOTER_MISSING: ::NTSTATUS = 0xC03A0001u32 as i32; +pub const STATUS_VHD_DRIVE_FOOTER_CHECKSUM_MISMATCH: ::NTSTATUS = 0xC03A0002u32 as i32; +pub const STATUS_VHD_DRIVE_FOOTER_CORRUPT: ::NTSTATUS = 0xC03A0003u32 as i32; +pub const STATUS_VHD_FORMAT_UNKNOWN: ::NTSTATUS = 0xC03A0004u32 as i32; +pub const STATUS_VHD_FORMAT_UNSUPPORTED_VERSION: ::NTSTATUS = 0xC03A0005u32 as i32; +pub const STATUS_VHD_SPARSE_HEADER_CHECKSUM_MISMATCH: ::NTSTATUS = 0xC03A0006u32 as i32; +pub const STATUS_VHD_SPARSE_HEADER_UNSUPPORTED_VERSION: ::NTSTATUS = 0xC03A0007u32 as i32; +pub const STATUS_VHD_SPARSE_HEADER_CORRUPT: ::NTSTATUS = 0xC03A0008u32 as i32; +pub const STATUS_VHD_BLOCK_ALLOCATION_FAILURE: ::NTSTATUS = 0xC03A0009u32 as i32; +pub const STATUS_VHD_BLOCK_ALLOCATION_TABLE_CORRUPT: ::NTSTATUS = 0xC03A000Au32 as i32; +pub const STATUS_VHD_INVALID_BLOCK_SIZE: ::NTSTATUS = 0xC03A000Bu32 as i32; +pub const STATUS_VHD_BITMAP_MISMATCH: ::NTSTATUS = 0xC03A000Cu32 as i32; +pub const STATUS_VHD_PARENT_VHD_NOT_FOUND: ::NTSTATUS = 0xC03A000Du32 as i32; +pub const STATUS_VHD_CHILD_PARENT_ID_MISMATCH: ::NTSTATUS = 0xC03A000Eu32 as i32; +pub const STATUS_VHD_CHILD_PARENT_TIMESTAMP_MISMATCH: ::NTSTATUS = 0xC03A000Fu32 as i32; +pub const STATUS_VHD_METADATA_READ_FAILURE: ::NTSTATUS = 0xC03A0010u32 as i32; +pub const STATUS_VHD_METADATA_WRITE_FAILURE: ::NTSTATUS = 0xC03A0011u32 as i32; +pub const STATUS_VHD_INVALID_SIZE: ::NTSTATUS = 0xC03A0012u32 as i32; +pub const STATUS_VHD_INVALID_FILE_SIZE: ::NTSTATUS = 0xC03A0013u32 as i32; +pub const STATUS_VIRTDISK_PROVIDER_NOT_FOUND: ::NTSTATUS = 0xC03A0014u32 as i32; +pub const STATUS_VIRTDISK_NOT_VIRTUAL_DISK: ::NTSTATUS = 0xC03A0015u32 as i32; +pub const STATUS_VHD_PARENT_VHD_ACCESS_DENIED: ::NTSTATUS = 0xC03A0016u32 as i32; +pub const STATUS_VHD_CHILD_PARENT_SIZE_MISMATCH: ::NTSTATUS = 0xC03A0017u32 as i32; +pub const STATUS_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED: ::NTSTATUS = 0xC03A0018u32 as i32; +pub const STATUS_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT: ::NTSTATUS = 0xC03A0019u32 as i32; +pub const STATUS_VIRTUAL_DISK_LIMITATION: ::NTSTATUS = 0xC03A001Au32 as i32; +pub const STATUS_VHD_INVALID_TYPE: ::NTSTATUS = 0xC03A001Bu32 as i32; +pub const STATUS_VHD_INVALID_STATE: ::NTSTATUS = 0xC03A001Cu32 as i32; +pub const STATUS_VIRTDISK_UNSUPPORTED_DISK_SECTOR_SIZE: ::NTSTATUS = 0xC03A001Du32 as i32; +pub const STATUS_VIRTDISK_DISK_ALREADY_OWNED: ::NTSTATUS = 0xC03A001Eu32 as i32; +pub const STATUS_VIRTDISK_DISK_ONLINE_AND_WRITABLE: ::NTSTATUS = 0xC03A001Fu32 as i32; +pub const STATUS_CTLOG_TRACKING_NOT_INITIALIZED: ::NTSTATUS = 0xC03A0020u32 as i32; +pub const STATUS_CTLOG_LOGFILE_SIZE_EXCEEDED_MAXSIZE: ::NTSTATUS = 0xC03A0021u32 as i32; +pub const STATUS_CTLOG_VHD_CHANGED_OFFLINE: ::NTSTATUS = 0xC03A0022u32 as i32; +pub const STATUS_CTLOG_INVALID_TRACKING_STATE: ::NTSTATUS = 0xC03A0023u32 as i32; +pub const STATUS_CTLOG_INCONSISTENT_TRACKING_FILE: ::NTSTATUS = 0xC03A0024u32 as i32; +pub const STATUS_VHD_METADATA_FULL: ::NTSTATUS = 0xC03A0028u32 as i32; +pub const STATUS_VHD_INVALID_CHANGE_TRACKING_ID: ::NTSTATUS = 0xC03A0029u32 as i32; +pub const STATUS_VHD_CHANGE_TRACKING_DISABLED: ::NTSTATUS = 0xC03A002Au32 as i32; +pub const STATUS_VHD_MISSING_CHANGE_TRACKING_INFORMATION: ::NTSTATUS = 0xC03A0030u32 as i32; +pub const STATUS_VHD_RESIZE_WOULD_TRUNCATE_DATA: ::NTSTATUS = 0xC03A0031u32 as i32; +pub const STATUS_VHD_COULD_NOT_COMPUTE_MINIMUM_VIRTUAL_SIZE: ::NTSTATUS = 0xC03A0032u32 as i32; +pub const STATUS_VHD_ALREADY_AT_OR_BELOW_MINIMUM_VIRTUAL_SIZE: ::NTSTATUS = 0xC03A0033u32 as i32; +pub const STATUS_QUERY_STORAGE_ERROR: ::NTSTATUS = 0x803A0001u32 as i32; +pub const STATUS_RKF_KEY_NOT_FOUND: ::NTSTATUS = 0xC0400001u32 as i32; +pub const STATUS_RKF_DUPLICATE_KEY: ::NTSTATUS = 0xC0400002u32 as i32; +pub const STATUS_RKF_BLOB_FULL: ::NTSTATUS = 0xC0400003u32 as i32; +pub const STATUS_RKF_STORE_FULL: ::NTSTATUS = 0xC0400004u32 as i32; +pub const STATUS_RKF_FILE_BLOCKED: ::NTSTATUS = 0xC0400005u32 as i32; +pub const STATUS_RKF_ACTIVE_KEY: ::NTSTATUS = 0xC0400006u32 as i32; +pub const STATUS_RDBSS_RESTART_OPERATION: ::NTSTATUS = 0xC0410001u32 as i32; +pub const STATUS_RDBSS_CONTINUE_OPERATION: ::NTSTATUS = 0xC0410002u32 as i32; +pub const STATUS_RDBSS_POST_OPERATION: ::NTSTATUS = 0xC0410003u32 as i32; +pub const STATUS_BTH_ATT_INVALID_HANDLE: ::NTSTATUS = 0xC0420001u32 as i32; +pub const STATUS_BTH_ATT_READ_NOT_PERMITTED: ::NTSTATUS = 0xC0420002u32 as i32; +pub const STATUS_BTH_ATT_WRITE_NOT_PERMITTED: ::NTSTATUS = 0xC0420003u32 as i32; +pub const STATUS_BTH_ATT_INVALID_PDU: ::NTSTATUS = 0xC0420004u32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_AUTHENTICATION: ::NTSTATUS = 0xC0420005u32 as i32; +pub const STATUS_BTH_ATT_REQUEST_NOT_SUPPORTED: ::NTSTATUS = 0xC0420006u32 as i32; +pub const STATUS_BTH_ATT_INVALID_OFFSET: ::NTSTATUS = 0xC0420007u32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_AUTHORIZATION: ::NTSTATUS = 0xC0420008u32 as i32; +pub const STATUS_BTH_ATT_PREPARE_QUEUE_FULL: ::NTSTATUS = 0xC0420009u32 as i32; +pub const STATUS_BTH_ATT_ATTRIBUTE_NOT_FOUND: ::NTSTATUS = 0xC042000Au32 as i32; +pub const STATUS_BTH_ATT_ATTRIBUTE_NOT_LONG: ::NTSTATUS = 0xC042000Bu32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_ENCRYPTION_KEY_SIZE: ::NTSTATUS = 0xC042000Cu32 as i32; +pub const STATUS_BTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH: ::NTSTATUS = 0xC042000Du32 as i32; +pub const STATUS_BTH_ATT_UNLIKELY: ::NTSTATUS = 0xC042000Eu32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_ENCRYPTION: ::NTSTATUS = 0xC042000Fu32 as i32; +pub const STATUS_BTH_ATT_UNSUPPORTED_GROUP_TYPE: ::NTSTATUS = 0xC0420010u32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_RESOURCES: ::NTSTATUS = 0xC0420011u32 as i32; +pub const STATUS_BTH_ATT_UNKNOWN_ERROR: ::NTSTATUS = 0xC0421000u32 as i32; +pub const STATUS_SECUREBOOT_ROLLBACK_DETECTED: ::NTSTATUS = 0xC0430001u32 as i32; +pub const STATUS_SECUREBOOT_POLICY_VIOLATION: ::NTSTATUS = 0xC0430002u32 as i32; +pub const STATUS_SECUREBOOT_INVALID_POLICY: ::NTSTATUS = 0xC0430003u32 as i32; +pub const STATUS_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND: ::NTSTATUS = 0xC0430004u32 as i32; +pub const STATUS_SECUREBOOT_POLICY_NOT_SIGNED: ::NTSTATUS = 0xC0430005u32 as i32; +pub const STATUS_SECUREBOOT_NOT_ENABLED: ::NTSTATUS = 0x80430006u32 as i32; +pub const STATUS_SECUREBOOT_FILE_REPLACED: ::NTSTATUS = 0xC0430007u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_ROLLBACK_DETECTED: ::NTSTATUS = 0xC0E90001u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION: ::NTSTATUS = 0xC0E90002u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_INVALID_POLICY: ::NTSTATUS = 0xC0E90003u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_POLICY_NOT_SIGNED: ::NTSTATUS = 0xC0E90004u32 as i32; +pub const STATUS_NO_APPLICABLE_APP_LICENSES_FOUND: ::NTSTATUS = 0xC0EA0001u32 as i32; +pub const STATUS_AUDIO_ENGINE_NODE_NOT_FOUND: ::NTSTATUS = 0xC0440001u32 as i32; +pub const STATUS_HDAUDIO_EMPTY_CONNECTION_LIST: ::NTSTATUS = 0xC0440002u32 as i32; +pub const STATUS_HDAUDIO_CONNECTION_LIST_NOT_SUPPORTED: ::NTSTATUS = 0xC0440003u32 as i32; +pub const STATUS_HDAUDIO_NO_LOGICAL_DEVICES_CREATED: ::NTSTATUS = 0xC0440004u32 as i32; +pub const STATUS_HDAUDIO_NULL_LINKED_LIST_ENTRY: ::NTSTATUS = 0xC0440005u32 as i32; +pub const STATUS_SPACES_RESILIENCY_TYPE_INVALID: ::NTSTATUS = 0xC0E70003u32 as i32; +pub const STATUS_SPACES_DRIVE_SECTOR_SIZE_INVALID: ::NTSTATUS = 0xC0E70004u32 as i32; +pub const STATUS_SPACES_DRIVE_REDUNDANCY_INVALID: ::NTSTATUS = 0xC0E70006u32 as i32; +pub const STATUS_SPACES_NUMBER_OF_DATA_COPIES_INVALID: ::NTSTATUS = 0xC0E70007u32 as i32; +pub const STATUS_SPACES_INTERLEAVE_LENGTH_INVALID: ::NTSTATUS = 0xC0E70009u32 as i32; +pub const STATUS_SPACES_NUMBER_OF_COLUMNS_INVALID: ::NTSTATUS = 0xC0E7000Au32 as i32; +pub const STATUS_SPACES_NOT_ENOUGH_DRIVES: ::NTSTATUS = 0xC0E7000Bu32 as i32; +pub const STATUS_SPACES_EXTENDED_ERROR: ::NTSTATUS = 0xC0E7000Cu32 as i32; +pub const STATUS_SPACES_PROVISIONING_TYPE_INVALID: ::NTSTATUS = 0xC0E7000Du32 as i32; +pub const STATUS_SPACES_ALLOCATION_SIZE_INVALID: ::NTSTATUS = 0xC0E7000Eu32 as i32; +pub const STATUS_SPACES_ENCLOSURE_AWARE_INVALID: ::NTSTATUS = 0xC0E7000Fu32 as i32; +pub const STATUS_SPACES_WRITE_CACHE_SIZE_INVALID: ::NTSTATUS = 0xC0E70010u32 as i32; +pub const STATUS_SPACES_NUMBER_OF_GROUPS_INVALID: ::NTSTATUS = 0xC0E70011u32 as i32; +pub const STATUS_SPACES_DRIVE_OPERATIONAL_STATE_INVALID: ::NTSTATUS = 0xC0E70012u32 as i32; +pub const STATUS_SPACES_UPDATE_COLUMN_STATE: ::NTSTATUS = 0xC0E70013u32 as i32; +pub const STATUS_SPACES_MAP_REQUIRED: ::NTSTATUS = 0xC0E70014u32 as i32; +pub const STATUS_SPACES_UNSUPPORTED_VERSION: ::NTSTATUS = 0xC0E70015u32 as i32; +pub const STATUS_SPACES_CORRUPT_METADATA: ::NTSTATUS = 0xC0E70016u32 as i32; +pub const STATUS_SPACES_DRT_FULL: ::NTSTATUS = 0xC0E70017u32 as i32; +pub const STATUS_SPACES_INCONSISTENCY: ::NTSTATUS = 0xC0E70018u32 as i32; +pub const STATUS_SPACES_LOG_NOT_READY: ::NTSTATUS = 0xC0E70019u32 as i32; +pub const STATUS_SPACES_NO_REDUNDANCY: ::NTSTATUS = 0xC0E7001Au32 as i32; +pub const STATUS_SPACES_DRIVE_NOT_READY: ::NTSTATUS = 0xC0E7001Bu32 as i32; +pub const STATUS_SPACES_REPAIRED: ::NTSTATUS = 0x00E7001C; +pub const STATUS_SPACES_PAUSE: ::NTSTATUS = 0x00E7001D; +pub const STATUS_SPACES_COMPLETE: ::NTSTATUS = 0x00E7001E; +pub const STATUS_VOLSNAP_BOOTFILE_NOT_VALID: ::NTSTATUS = 0xC0500003u32 as i32; +pub const STATUS_IO_PREEMPTED: ::NTSTATUS = 0xC0510001u32 as i32; +pub const STATUS_SVHDX_ERROR_STORED: ::NTSTATUS = 0xC05C0000u32 as i32; +pub const STATUS_SVHDX_ERROR_NOT_AVAILABLE: ::NTSTATUS = 0xC05CFF00u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_AVAILABLE: ::NTSTATUS = 0xC05CFF01u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_CAPACITY_DATA_CHANGED: ::NTSTATUS = 0xC05CFF02u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_RESERVATIONS_PREEMPTED: ::NTSTATUS = 0xC05CFF03u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_RESERVATIONS_RELEASED: ::NTSTATUS = 0xC05CFF04u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_REGISTRATIONS_PREEMPTED: ::NTSTATUS = 0xC05CFF05u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_OPERATING_DEFINITION_CHANGED: ::NTSTATUS = 0xC05CFF06u32 as i32; +pub const STATUS_SVHDX_RESERVATION_CONFLICT: ::NTSTATUS = 0xC05CFF07u32 as i32; +pub const STATUS_SVHDX_WRONG_FILE_TYPE: ::NTSTATUS = 0xC05CFF08u32 as i32; +pub const STATUS_SVHDX_VERSION_MISMATCH: ::NTSTATUS = 0xC05CFF09u32 as i32; +pub const STATUS_VHD_SHARED: ::NTSTATUS = 0xC05CFF0Au32 as i32; +pub const STATUS_SVHDX_NO_INITIATOR: ::NTSTATUS = 0xC05CFF0Bu32 as i32; +pub const STATUS_VHDSET_BACKING_STORAGE_NOT_FOUND: ::NTSTATUS = 0xC05CFF0Cu32 as i32; +pub const STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP: ::NTSTATUS = 0xC05D0000u32 as i32; +pub const STATUS_SMB_BAD_CLUSTER_DIALECT: ::NTSTATUS = 0xC05D0001u32 as i32; +pub const STATUS_SMB_GUEST_LOGON_BLOCKED: ::NTSTATUS = 0xC05D0002u32 as i32; +pub const STATUS_SECCORE_INVALID_COMMAND: ::NTSTATUS = 0xC0E80000u32 as i32; +pub const STATUS_VSM_NOT_INITIALIZED: ::NTSTATUS = 0xC0450000u32 as i32; +pub const STATUS_VSM_DMA_PROTECTION_NOT_IN_USE: ::NTSTATUS = 0xC0450001u32 as i32; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/oaidl.rs b/bash-5.1/vendor/winapi-0.2.8/src/oaidl.rs new file mode 100644 index 0000000..c705060 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/oaidl.rs @@ -0,0 +1,590 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of OAIdl.h +pub type wireBRECORD = *mut _wireBRECORD; +pub type wireVARIANT = *mut _wireVARIANT; +STRUCT!{struct SAFEARRAYBOUND { + cElements: ::ULONG, + lLbound: ::LONG, +}} +STRUCT!{struct SAFEARR_BSTR { + Size: ::ULONG, + aBstr: *mut ::wireBSTR, +}} +STRUCT!{struct SAFEARR_UNKNOWN { + Size: ::ULONG, + apUnknown: *mut *mut ::IUnknown, +}} +STRUCT!{struct SAFEARR_DISPATCH { + Size: ::ULONG, + apDispatch: *mut *mut IDispatch, +}} +STRUCT!{struct SAFEARR_VARIANT { + Size: ::ULONG, + aVariant: *mut wireVARIANT, +}} +STRUCT!{struct SAFEARR_BRECORD { + Size: ::ULONG, + aRecord: *mut wireBRECORD, +}} +STRUCT!{struct SAFEARR_HAVEIID { + Size: ::ULONG, + apUnknown: *mut *mut ::IUnknown, + iid: ::IID, +}} +ENUM!{enum SF_TYPE { + SF_ERROR = ::VT_ERROR.0, + SF_I1 = ::VT_I1.0, + SF_I2 = ::VT_I2.0, + SF_I4 = ::VT_I4.0, + SF_I8 = ::VT_I8.0, + SF_BSTR = ::VT_BSTR.0, + SF_UNKNOWN = ::VT_UNKNOWN.0, + SF_DISPATCH = ::VT_DISPATCH.0, + SF_VARIANT = ::VT_VARIANT.0, + SF_RECORD = ::VT_RECORD.0, + SF_HAVEIID = ::VT_UNKNOWN.0 | ::VT_RESERVED.0, +}} +STRUCT!{struct SAFEARRAYUNION { + sfType: ::ULONG, + u: __MIDL_IOleAutomationTypes_0001, +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{struct __MIDL_IOleAutomationTypes_0001 { + data0: u32, + data1: [u32; 6], +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct __MIDL_IOleAutomationTypes_0001 { + data0: u32, + data1: [u32; 5], +}} +UNION!(__MIDL_IOleAutomationTypes_0001, data0, BstrStr, BstrStr_mut, SAFEARR_BSTR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, UnknownStr, UnknownStr_mut, SAFEARR_UNKNOWN); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, DispatchStr, DispatchStr_mut, SAFEARR_DISPATCH); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, VariantStr, VariantStr_mut, SAFEARR_VARIANT); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, RecordStr, RecordStr_mut, SAFEARR_BRECORD); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, HaveIidStr, HaveIidStr_mut, SAFEARR_HAVEIID); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, ByteStr, ByteStr_mut, ::BYTE_SIZEDARR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, WordStr, WordStr_mut, ::WORD_SIZEDARR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, LongStr, LongStr_mut, ::DWORD_SIZEDARR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, HyperStr, HyperStr_mut, ::HYPER_SIZEDARR); +STRUCT!{struct _wireSAFEARRAY { + cDims: ::USHORT, + fFeatures: ::USHORT, + cbElements: ::ULONG, + cLocks: ::ULONG, + uArrayStructs: SAFEARRAYUNION, + rgsaBound: [SAFEARRAYBOUND; 1], +}} +pub type wireSAFEARRAY = *mut _wireSAFEARRAY; +pub type wirePSAFEARRAY = *mut wireSAFEARRAY; +STRUCT!{struct SAFEARRAY { + cDims: ::USHORT, + fFeatures: ::USHORT, + cbElements: ::ULONG, + cLocks: ::ULONG, + pvData: ::PVOID, + rgsabound: [SAFEARRAYBOUND; 1], +}} +pub type LPSAFEARRAY = *mut SAFEARRAY; +pub const FADF_AUTO: ::DWORD = 0x1; +pub const FADF_STATIC: ::DWORD = 0x2; +pub const FADF_EMBEDDED: ::DWORD = 0x4; +pub const FADF_FIXEDSIZE: ::DWORD = 0x10; +pub const FADF_RECORD: ::DWORD = 0x20; +pub const FADF_HAVEIID: ::DWORD = 0x40; +pub const FADF_HAVEVARTYPE: ::DWORD = 0x80; +pub const FADF_BSTR: ::DWORD = 0x100; +pub const FADF_UNKNOWN: ::DWORD = 0x200; +pub const FADF_DISPATCH: ::DWORD = 0x400; +pub const FADF_VARIANT: ::DWORD = 0x800; +pub const FADF_RESERVED: ::DWORD = 0xf008; +#[cfg(target_arch = "x86_64")] +STRUCT!{struct VARIANT { + data0: u64, + data1: u64, + data2: u64, +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct VARIANT { + data0: u64, + data1: u32, + data2: u32, +}} +UNION!(VARIANT, data0, vt, vt_mut, ::VARTYPE); +UNION!(VARIANT, data1, llVal, llVal_mut, ::LONGLONG); +UNION!(VARIANT, data1, lVal, lVal_mut, ::LONG); +UNION!(VARIANT, data1, bVal, bVal_mut, ::BYTE); +UNION!(VARIANT, data1, iVal, iVal_mut, ::SHORT); +UNION!(VARIANT, data1, fltVal, fltVal_mut, ::FLOAT); +UNION!(VARIANT, data1, dblVal, dblVal_mut, ::DOUBLE); +UNION!(VARIANT, data1, boolVal, boolVal_mut, ::VARIANT_BOOL); +UNION!(VARIANT, data1, scode, scode_mut, ::SCODE); +UNION!(VARIANT, data1, cyVal, cyVal_mut, ::CY); +UNION!(VARIANT, data1, date, date_mut, ::DATE); +UNION!(VARIANT, data1, bstrVal, bstrVal_mut, ::BSTR); +UNION!(VARIANT, data1, punkVal, punkVal_mut, *mut ::IUnknown); +UNION!(VARIANT, data1, pdispVal, pdispVal_mut, *mut IDispatch); +UNION!(VARIANT, data1, parray, parray_mut, *mut SAFEARRAY); +UNION!(VARIANT, data1, pllVal, pllVal_mut, *mut ::LONGLONG); +UNION!(VARIANT, data1, plVal, plVal_mut, *mut ::LONG); +UNION!(VARIANT, data1, pbVal, pbVal_mut, *mut ::BYTE); +UNION!(VARIANT, data1, piVal, piVal_mut, *mut ::SHORT); +UNION!(VARIANT, data1, pfltVal, pfltVal_mut, *mut ::FLOAT); +UNION!(VARIANT, data1, pdblVal, pdblVal_mut, *mut ::DOUBLE); +UNION!(VARIANT, data1, pboolVal, pboolVal_mut, *mut ::VARIANT_BOOL); +UNION!(VARIANT, data1, pscode, pscode_mut, *mut ::SCODE); +UNION!(VARIANT, data1, pcyVal, pcyVal_mut, *mut ::CY); +UNION!(VARIANT, data1, pdate, pdate_mut, *mut ::DATE); +UNION!(VARIANT, data1, pbstrVal, pbstrVal_mut, *mut ::BSTR); +UNION!(VARIANT, data1, ppunkVal, ppunkVal_mut, *mut *mut ::IUnknown); +UNION!(VARIANT, data1, ppdispVal, ppdispVal_mut, *mut *mut IDispatch); +UNION!(VARIANT, data1, pparray, pparray_mut, *mut *mut SAFEARRAY); +UNION!(VARIANT, data1, pvarVal, pvarVal_mut, *mut VARIANT); +UNION!(VARIANT, data1, byref, byref_mut, ::PVOID); +UNION!(VARIANT, data1, cVal, cVal_mut, ::CHAR); +UNION!(VARIANT, data1, uiVal, uiVal_mut, ::USHORT); +UNION!(VARIANT, data1, ulVal, ulVal_mut, ::ULONG); +UNION!(VARIANT, data1, ullVal, ullVal_mut, ::ULONGLONG); +UNION!(VARIANT, data1, intVal, intVal_mut, ::INT); +UNION!(VARIANT, data1, uintVal, uintVal_mut, ::UINT); +UNION!(VARIANT, data1, pdecVal, pdecVal_mut, *mut ::DECIMAL); +UNION!(VARIANT, data1, pcVal, pcVal_mut, *mut ::CHAR); +UNION!(VARIANT, data1, puiVal, puiVal_mut, *mut ::USHORT); +UNION!(VARIANT, data1, pulVal, pulVal_mut, *mut ::ULONG); +UNION!(VARIANT, data1, pullVal, pullVal_mut, *mut ::ULONGLONG); +UNION!(VARIANT, data1, pintVal, pintVal_mut, *mut ::INT); +UNION!(VARIANT, data1, puintVal, puintVal_mut, *mut ::UINT); +UNION!(VARIANT, data1, pvRecord, pvRecord_mut, ::PVOID); +UNION!(VARIANT, data2, pRecInfo, pRecInfo_mut, *mut IRecordInfo); +UNION!(VARIANT, data0, decVal, decVal_mut, ::DECIMAL); +pub type LPVARIANT = *mut VARIANT; +pub type VARIANTARG = VARIANT; +pub type LPVARIANTARG = *mut VARIANT; +pub type REFVARIANT = *const VARIANT; +STRUCT!{struct _wireBRECORD { + fFlags: ::ULONG, + clSize: ::ULONG, + pRecInfo: *mut IRecordInfo, + pRecord: *mut ::BYTE, +}} +STRUCT!{struct _wireVARIANT { + clSize: ::DWORD, + rpcReserved: ::DWORD, + vt: ::USHORT, + wReserved1: ::USHORT, + wReserved2: ::USHORT, + wReserved3: ::USHORT, + data0: u64, + data1: u64, +}} +UNION!(_wireVARIANT, data0, llVal, llVal_mut, ::LONGLONG); +UNION!(_wireVARIANT, data0, lVal, lVal_mut, ::LONG); +UNION!(_wireVARIANT, data0, bVal, bVal_mut, ::BYTE); +UNION!(_wireVARIANT, data0, iVal, iVal_mut, ::SHORT); +UNION!(_wireVARIANT, data0, fltVal, fltVal_mut, ::FLOAT); +UNION!(_wireVARIANT, data0, dblVal, dblVal_mut, ::DOUBLE); +UNION!(_wireVARIANT, data0, boolVal, boolVal_mut, ::VARIANT_BOOL); +UNION!(_wireVARIANT, data0, scode, scode_mut, ::SCODE); +UNION!(_wireVARIANT, data0, cyVal, cyVal_mut, ::CY); +UNION!(_wireVARIANT, data0, date, date_mut, ::DATE); +UNION!(_wireVARIANT, data0, bstrVal, bstrVal_mut, ::wireBSTR); +UNION!(_wireVARIANT, data0, punkVal, punkVal_mut, *mut ::IUnknown); +UNION!(_wireVARIANT, data0, pdispVal, pdispVal_mut, *mut IDispatch); +UNION!(_wireVARIANT, data0, parray, parray_mut, wirePSAFEARRAY); +UNION!(_wireVARIANT, data0, brecVal, brecVal_mut, wireBRECORD); +UNION!(_wireVARIANT, data0, pllVal, pllVal_mut, *mut ::LONGLONG); +UNION!(_wireVARIANT, data0, plVal, plVal_mut, *mut ::LONG); +UNION!(_wireVARIANT, data0, pbVal, pbVal_mut, *mut ::BYTE); +UNION!(_wireVARIANT, data0, piVal, piVal_mut, *mut ::SHORT); +UNION!(_wireVARIANT, data0, pfltVal, pfltVal_mut, *mut ::FLOAT); +UNION!(_wireVARIANT, data0, pdblVal, pdblVal_mut, *mut ::DOUBLE); +UNION!(_wireVARIANT, data0, pboolVal, pboolVal_mut, *mut ::VARIANT_BOOL); +UNION!(_wireVARIANT, data0, pscode, pscode_mut, *mut ::SCODE); +UNION!(_wireVARIANT, data0, pcyVal, pcyVal_mut, *mut ::CY); +UNION!(_wireVARIANT, data0, pdate, pdate_mut, *mut ::DATE); +UNION!(_wireVARIANT, data0, pbstrVal, pbstrVal_mut, *mut ::wireBSTR); +UNION!(_wireVARIANT, data0, ppunkVal, ppunkVal_mut, *mut *mut ::IUnknown); +UNION!(_wireVARIANT, data0, ppdispVal, ppdispVal_mut, *mut *mut IDispatch); +UNION!(_wireVARIANT, data0, pparray, pparray_mut, *mut wirePSAFEARRAY); +UNION!(_wireVARIANT, data0, pvarVal, pvarVal_mut, *mut wireVARIANT); +UNION!(_wireVARIANT, data0, cVal, cVal_mut, ::CHAR); +UNION!(_wireVARIANT, data0, uiVal, uiVal_mut, ::USHORT); +UNION!(_wireVARIANT, data0, ulVal, ulVal_mut, ::ULONG); +UNION!(_wireVARIANT, data0, ullVal, ullVal_mut, ::ULONGLONG); +UNION!(_wireVARIANT, data0, intVal, intVal_mut, ::INT); +UNION!(_wireVARIANT, data0, uintVal, uintVal_mut, ::UINT); +UNION!(_wireVARIANT, data0, decVal, decVal_mut, ::DECIMAL); +UNION!(_wireVARIANT, data0, pcVal, pcVal_mut, *mut ::CHAR); +UNION!(_wireVARIANT, data0, puiVal, puiVal_mut, *mut ::USHORT); +UNION!(_wireVARIANT, data0, pulVal, pulVal_mut, *mut ::ULONG); +UNION!(_wireVARIANT, data0, pullVal, pullVal_mut, *mut ::ULONGLONG); +UNION!(_wireVARIANT, data0, pintVal, pintVal_mut, *mut ::INT); +UNION!(_wireVARIANT, data0, puintVal, puintVal_mut, *mut ::UINT); +UNION!(_wireVARIANT, data0, pdecVal, pdecVal_mut, *mut ::DECIMAL); +pub type DISPID = ::LONG; +pub type MEMBERID = DISPID; +pub type HREFTYPE = ::DWORD; +ENUM!{enum TYPEKIND { + TKIND_ENUM = 0, + TKIND_RECORD, + TKIND_MODULE, + TKIND_INTERFACE, + TKIND_DISPATCH, + TKIND_COCLASS, + TKIND_ALIAS, + TKIND_UNION, + TKIND_MAX, +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{struct TYPEDESC { + data: u64, + vt: ::VARTYPE, +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct TYPEDESC { + data: u32, + vt: ::VARTYPE, +}} +UNION!(TYPEDESC, data, lptdesc, lptdesc_mut, *mut TYPEDESC); +UNION!(TYPEDESC, data, lpadesc, lpadesc_mut, *mut ARRAYDESC); +UNION!(TYPEDESC, data, hreftype, hreftype_mut, HREFTYPE); +STRUCT!{struct ARRAYDESC { + tdescElem: TYPEDESC, + cDims: ::USHORT, + rgbounds: [SAFEARRAYBOUND; 1], +}} +STRUCT!{struct PARAMDESCEX { + cBytes: ::ULONG, + varDefaultValue: VARIANTARG, +}} +pub type LPPARAMDESCEX = *mut PARAMDESCEX; +STRUCT!{struct PARAMDESC { + pparamdescex: LPPARAMDESCEX, + wParamFlags: ::USHORT, +}} +pub type LPPARAMDESC = *mut PARAMDESC; +pub const PARAMFLAG_NONE: ::DWORD = 0; +pub const PARAMFLAG_FIN: ::DWORD = 0x1; +pub const PARAMFLAG_FOUT: ::DWORD = 0x2; +pub const PARAMFLAG_FLCID: ::DWORD = 0x4; +pub const PARAMFLAG_FRETVAL: ::DWORD = 0x8; +pub const PARAMFLAG_FOPT: ::DWORD = 0x10; +pub const PARAMFLAG_FHASDEFAULT: ::DWORD = 0x20; +pub const PARAMFLAG_FHASCUSTDATA: ::DWORD = 0x40; +STRUCT!{struct IDLDESC { + dwReserved: ::ULONG_PTR, + wIDLFlags: ::USHORT, +}} +pub type LPIDLDESC = *mut IDLDESC; +pub const IDLFLAG_NONE: ::DWORD = PARAMFLAG_NONE; +pub const IDLFLAG_FIN: ::DWORD = PARAMFLAG_FIN; +pub const IDLFLAG_FOUT: ::DWORD = PARAMFLAG_FOUT; +pub const IDLFLAG_FLCID: ::DWORD = PARAMFLAG_FLCID; +pub const IDLFLAG_FRETVAL: ::DWORD = PARAMFLAG_FRETVAL; +STRUCT!{struct ELEMDESC { + tdesc: TYPEDESC, + idldesc: IDLDESC, +}} +UNION!(ELEMDESC, idldesc, paramdesc, paramdesc_mut, PARAMDESC); +pub type LPELEMDESC = *mut ELEMDESC; +STRUCT!{struct TYPEATTR { + guid: ::GUID, + lcid: ::LCID, + dwReserved: ::DWORD, + memidConstructor: ::MEMBERID, + memidDestructor: ::MEMBERID, + lpstrSchema: ::LPOLESTR, + cbSizeInstance: ::ULONG, + typekind: ::TYPEKIND, + cFuncs: ::WORD, + cVars: ::WORD, + cImplTypes: ::WORD, + cbSizeVft: ::WORD, + cbAlignment: ::WORD, + wTypeFlags: ::WORD, + wMajorVerNum: ::WORD, + wMinorVerNum: ::WORD, + tdescAlias: ::TYPEDESC, + idldescType: ::IDLDESC, +}} +pub type LPTYPEATTR = *mut TYPEATTR; +STRUCT!{struct DISPPARAMS { + rgvarg: *mut VARIANTARG, + rgdispidNamedArgs: *mut DISPID, + cArgs: ::UINT, + cNamedArgs: ::UINT, +}} +STRUCT!{nodebug struct EXCEPINFO { + wCode: ::WORD, + wReserved: ::WORD, + bstrSource: ::BSTR, + bstrDescription: ::BSTR, + bstrHelpFile: ::BSTR, + dwHelpContext: ::DWORD, + pvReserved: ::PVOID, + pfnDeferredFillIn: Option<unsafe extern "system" fn(einfo: *mut EXCEPINFO) -> ::HRESULT>, + scode: ::SCODE, +}} +ENUM!{enum CALLCONV { + CC_FASTCALL = 0, + CC_CDECL = 1, + CC_MSCPASCAL, + CC_PASCAL, + CC_MACPASCAL, + CC_STDCALL, + CC_FPFASTCALL, + CC_SYSCALL, + CC_MPWCDECL, + CC_MPWPASCAL, + CC_MAX, +}} +ENUM!{enum FUNCKIND { + FUNC_VIRTUAL = 0, + FUNC_PUREVIRTUAL, + FUNC_NONVIRTUAL, + FUNC_STATIC, + FUNC_DISPATCH, +}} +FLAGS!{enum INVOKEKIND { + INVOKE_FUNC = 1, + INVOKE_PROPERTYGET = 2, + INVOKE_PROPERTYPUT = 4, + INVOKE_PROPERTYPUTREF = 8, +}} +STRUCT!{struct FUNCDESC { + memid: ::MEMBERID, + lprgscode: *mut ::SCODE, + lprgelemdescParam: *mut ::ELEMDESC, + funckind: ::FUNCKIND, + invkind: ::INVOKEKIND, + callconv: ::CALLCONV, + cParams: ::SHORT, + cParamsOpt: ::SHORT, + oVft: ::SHORT, + cScodes: ::SHORT, + elemdescFunc: ::ELEMDESC, + wFuncFlags: ::WORD, +}} +pub type LPFUNCDESC = *mut FUNCDESC; +ENUM!{enum VARKIND { + VAR_PERINSTANCE = 0, + VAR_STATIC, + VAR_CONST, + VAR_DISPATCH, +}} +pub const IMPLTYPEFLAG_FDEFAULT: ::DWORD = 0x1; +pub const IMPLTYPEFLAG_FSOURCE: ::DWORD = 0x2; +pub const IMPLTYPEFLAG_FRESTRICTED: ::DWORD = 0x4; +pub const IMPLTYPEFLAG_FDEFAULTVTABLE: ::DWORD = 0x8; +STRUCT!{struct VARDESC { + memid: MEMBERID, + lpstrSchema: ::LPOLESTR, + lpvarValue: *mut VARIANT, + elemdescVar: ::ELEMDESC, + wVarFlags: ::WORD, + varkind: VARKIND, +}} +UNION!(VARDESC, lpvarValue, oInst, oInst_mut, ::ULONG); +pub type LPVARDESC = *mut VARDESC; +FLAGS!{enum TYPEFLAGS { + TYPEFLAG_FAPPOBJECT = 0x1, + TYPEFLAG_FCANCREATE = 0x2, + TYPEFLAG_FLICENSED = 0x4, + TYPEFLAG_FPREDECLID = 0x8, + TYPEFLAG_FHIDDEN = 0x10, + TYPEFLAG_FCONTROL = 0x20, + TYPEFLAG_FDUAL = 0x40, + TYPEFLAG_FNONEXTENSIBLE = 0x80, + TYPEFLAG_FOLEAUTOMATION = 0x100, + TYPEFLAG_FRESTRICTED = 0x200, + TYPEFLAG_FAGGREGATABLE = 0x400, + TYPEFLAG_FREPLACEABLE = 0x800, + TYPEFLAG_FDISPATCHABLE = 0x1000, + TYPEFLAG_FREVERSEBIND = 0x2000, + TYPEFLAG_FPROXY = 0x4000, +}} +FLAGS!{enum FUNCFLAGS { + FUNCFLAG_FRESTRICTED = 0x1, + FUNCFLAG_FSOURCE = 0x2, + FUNCFLAG_FBINDABLE = 0x4, + FUNCFLAG_FREQUESTEDIT = 0x8, + FUNCFLAG_FDISPLAYBIND = 0x10, + FUNCFLAG_FDEFAULTBIND = 0x20, + FUNCFLAG_FHIDDEN = 0x40, + FUNCFLAG_FUSESGETLASTERROR = 0x80, + FUNCFLAG_FDEFAULTCOLLELEM = 0x100, + FUNCFLAG_FUIDEFAULT = 0x200, + FUNCFLAG_FNONBROWSABLE = 0x400, + FUNCFLAG_FREPLACEABLE = 0x800, + FUNCFLAG_FIMMEDIATEBIND = 0x1000, +}} +FLAGS!{enum VARFLAGS { + VARFLAG_FREADONLY = 0x1, + VARFLAG_FSOURCE = 0x2, + VARFLAG_FBINDABLE = 0x4, + VARFLAG_FREQUESTEDIT = 0x8, + VARFLAG_FDISPLAYBIND = 0x10, + VARFLAG_FDEFAULTBIND = 0x20, + VARFLAG_FHIDDEN = 0x40, + VARFLAG_FRESTRICTED = 0x80, + VARFLAG_FDEFAULTCOLLELEM = 0x100, + VARFLAG_FUIDEFAULT = 0x200, + VARFLAG_FNONBROWSABLE = 0x400, + VARFLAG_FREPLACEABLE = 0x800, + VARFLAG_FIMMEDIATEBIND = 0x1000, +}} +STRUCT!{struct CLEANLOCALSTORAGE { + pInterface: *mut ::IUnknown, + pStorage: ::PVOID, + flags: ::DWORD, +}} +STRUCT!{struct CUSTDATAITEM { + guid: ::GUID, + varValue: VARIANTARG, +}} +pub type LPCUSTDATAITEM = *mut CUSTDATAITEM; +STRUCT!{struct CUSTDATA { + cCustData: ::DWORD, + prgCustData: LPCUSTDATAITEM, +}} +pub type LPCUSTDATA = *mut CUSTDATA; +pub type LPCREATETYPEINFO = *mut ICreateTypeInfo; +RIDL!( +interface ICreateTypeInfo(ICreateTypeInfoVtbl): IUnknown(IUnknownVtbl) { + fn SetGuid(&mut self, guid: ::REFGUID) -> ::HRESULT, + fn SetTypeFlags(&mut self, uTypeFlags: ::UINT) -> ::HRESULT, + fn SetDocString(&mut self, pStrDoc: ::LPOLESTR) -> ::HRESULT, + fn SetHelpContext(&mut self, dwHelpContext: ::DWORD) -> ::HRESULT, + fn SetVersion(&mut self, wMajorVerNum: ::WORD, wMinorVerNum: ::WORD) -> ::HRESULT, + fn AddRefTypeInfo(&mut self, pTInfo: *mut ITypeInfo) -> ::HRESULT, + fn AddFuncDesc(&mut self, index: ::UINT, pFuncDesc: *mut FUNCDESC) -> ::HRESULT, + fn SetImplTypeFlags(&mut self, index: ::UINT, implTypeFlags: ::INT) -> ::HRESULT, + fn SetAlignment(&mut self, cbAlignment: ::WORD) -> ::HRESULT, + fn SetSchema(&mut self, pStrSchema: ::LPOLESTR) -> ::HRESULT, + fn AddVarDesc(&mut self, index: ::UINT, pVarDesc: *mut VARDESC) -> ::HRESULT, + fn SetFuncAndParamNames( + &mut self, index: ::UINT, rgszNames: *mut ::LPOLESTR, cNames: ::UINT + ) -> ::HRESULT, + fn SetVarName(&mut self, index: ::UINT, szName: ::LPOLESTR) -> ::HRESULT, + fn SetTypeDescAlias(&mut self, pTDescAlias: *mut TYPEDESC) -> ::HRESULT, + fn DefineFuncAsDllEntry( + &mut self, index: ::UINT, szDllName: ::LPOLESTR, szProcName: ::LPOLESTR + ) -> ::HRESULT, + fn SetFuncDocString(&mut self, index: ::UINT, szDocString: ::LPOLESTR) -> ::HRESULT, + fn SetVarDocString(&mut self, index: ::UINT, szDocString: ::LPOLESTR) -> ::HRESULT, + fn SetFuncHelpContext(&mut self, index: ::UINT, dwHelpContext: ::DWORD) -> ::HRESULT, + fn SetVarHelpContext(&mut self, index: ::UINT, dwHelpContext: ::DWORD) -> ::HRESULT, + fn SetMops(&mut self, index: ::UINT, bstrMops: ::BSTR) -> ::HRESULT, + fn SetTypeIdldesc(&mut self, pIdlDesc: *mut IDLDESC) -> ::HRESULT, + fn LayOut(&mut self) -> ::HRESULT +} +); +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateTypeInfo2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateTypeLib; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateTypeLib2; +pub type LPDISPATCH = *mut IDispatch; +pub const DISPID_UNKNOWN: ::INT = -1; +pub const DISPID_VALUE: ::INT = 0; +pub const DISPID_PROPERTYPUT: ::INT = -3; +pub const DISPID_NEWENUM: ::INT = -4; +pub const DISPID_EVALUATE: ::INT = -5; +pub const DISPID_CONSTRUCTOR: ::INT = -6; +pub const DISPID_DESTRUCTOR: ::INT = -7; +pub const DISPID_COLLECT: ::INT = -8; +RIDL!( +interface IDispatch(IDispatchVtbl): IUnknown(IUnknownVtbl) { + fn GetTypeInfoCount(&mut self, pctinfo: *mut ::UINT) -> ::HRESULT, + fn GetTypeInfo( + &mut self, iTInfo: ::UINT, lcid: ::LCID, ppTInfo: *mut *mut ITypeInfo + ) -> ::HRESULT, + fn GetIDsOfNames( + &mut self, riid: ::REFIID, rgszNames: *mut ::LPOLESTR, cNames: ::UINT, lcid: ::LCID, + rgDispId: *mut ::DISPID + ) -> ::HRESULT, + fn Invoke( + &mut self, dispIdMember: ::DISPID, riid: ::REFIID, lcid: ::LCID, wFlags: ::WORD, + pDispParams: *mut ::DISPPARAMS, pVarResult: *mut VARIANT, pExcepInfo: *mut ::EXCEPINFO, + puArgErr: *mut ::UINT + ) -> ::HRESULT +} +); +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumVARIANT; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeComp; +RIDL!( +interface ITypeInfo(ITypeInfoVtbl): IUnknown(IUnknownVtbl) { + fn GetTypeAttr(&mut self, ppTypeAttr: *mut *mut TYPEATTR) -> ::HRESULT, + fn GetTypeComp(&mut self, ppTComp: *mut *mut ITypeComp) -> ::HRESULT, + fn GetFuncDesc(&mut self, index: ::UINT, ppFunDesc: *mut *mut FUNCDESC) -> ::HRESULT, + fn GetVarDesc(&mut self, index: ::UINT, pPVarDesc: *mut *mut VARDESC) -> ::HRESULT, + fn GetNames( + &mut self, memid: MEMBERID, rgBstrNames: *mut ::BSTR, cMaxNames: ::UINT, + pcNames: *mut ::UINT + ) -> ::HRESULT, + fn GetRefTypeOfImplType(&mut self, index: ::UINT, pRefType: *mut HREFTYPE) -> ::HRESULT, + fn GetImplTypeFlags(&mut self, index: ::UINT, pImplTypeFlags: *mut ::INT) -> ::HRESULT, + fn GetIDsOfNames( + &mut self, rgszNames: *mut ::LPOLESTR, cNames: ::UINT, pMemId: *mut MEMBERID + ) -> ::HRESULT, + fn Invoke( + &mut self, pvInstance: ::PVOID, memid: MEMBERID, wFlags: ::WORD, + pDispParams: *mut DISPPARAMS, pVarResult: *mut VARIANT, pExcepInfo: *mut EXCEPINFO, + puArgErr: *mut ::UINT + ) -> ::HRESULT, + fn GetDocumentation( + &mut self, memid: MEMBERID, pBstrName: *mut ::BSTR, pBstrDocString: *mut ::BSTR, + pdwHelpContext: *mut ::DWORD, pBstrHelpFile: *mut ::BSTR + ) -> ::HRESULT, + fn GetDllEntry( + &mut self, memid: MEMBERID, invKind: ::INVOKEKIND, pBstrDllName: *mut ::BSTR, + pBstrName: *mut ::BSTR, pwOrdinal: *mut ::WORD + ) -> ::HRESULT, + fn GetRefTypeInfo(&mut self, hRefType: HREFTYPE, ppTInfo: *mut *mut ITypeInfo) -> ::HRESULT, + fn AddressOfMember( + &mut self, memid: MEMBERID, invKind: ::INVOKEKIND, ppv: *mut ::PVOID + ) -> ::HRESULT, + fn CreateInstance( + &mut self, pUnkOuter: *mut ::IUnknown, riid: ::REFIID, ppvObj: *mut ::PVOID + ) -> ::HRESULT, + fn GetMops(&mut self, memid: MEMBERID, pBstrMops: *mut ::BSTR) -> ::HRESULT, + fn GetContainingTypeLib( + &mut self, ppTLib: *mut *mut ITypeLib, pIndex: *mut ::UINT + ) -> ::HRESULT, + fn ReleaseTypeAttr(&mut self, pTypeAttr: *mut TYPEATTR) -> (), + fn ReleaseFuncDesc(&mut self, pFuncDesc: *mut FUNCDESC) -> (), + fn ReleaseVarDesc(&mut self, pVarDesc: *mut VARDESC) -> () +} +); +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeInfo2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeLib; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeLib2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeChangeEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IErrorInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateErrorInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISupportErrorInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeMarshal; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRecordInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IErrorLog; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPropertyBag; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/objbase.rs b/bash-5.1/vendor/winapi-0.2.8/src/objbase.rs new file mode 100644 index 0000000..cfd2b79 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/objbase.rs @@ -0,0 +1,5 @@ +//! Component object model defintions +pub const COINIT_APARTMENTTHREADED: ::DWORD = 0x2; +pub const COINIT_MULTITHREADED: ::DWORD = 0x0; +pub const COINIT_DISABLE_OLE1DDE: ::DWORD = 0x4; +pub const COINIT_SPEED_OVER_MEMORY: ::DWORD = 0x8; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/objidl.rs b/bash-5.1/vendor/winapi-0.2.8/src/objidl.rs new file mode 100644 index 0000000..ac49010 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/objidl.rs @@ -0,0 +1,100 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +//8402 +STRUCT!{struct BIND_OPTS { + cbStruct: ::DWORD, + grfFlags: ::DWORD, + grfMode: ::DWORD, + dwTickCountDeadline: ::DWORD, +}} +pub type LPBIND_OPTS = *mut BIND_OPTS; +//8479 +RIDL!( +interface IBindCtx(IBindCtxVtbl): IUnknown(IUnknownVtbl) { + fn RegisterObjectBound(&mut self, punk: *mut ::IUnknown) -> ::HRESULT, + fn RevokeObjectBound(&mut self, punk: *mut ::IUnknown) -> ::HRESULT, + fn ReleaseBoundObjects(&mut self) -> ::HRESULT, + fn SetBindOptions(&mut self, pbindopts: *mut BIND_OPTS) -> ::HRESULT, + fn GetBindOptions(&mut self, pbindopts: *mut BIND_OPTS) -> ::HRESULT, + fn GetRunningObjectTable(&mut self, pprot: *mut *mut IRunningObjectTable) -> ::HRESULT, + fn RegisterObjectParam(&mut self, pszKey: ::LPOLESTR, punk: *mut ::IUnknown) -> ::HRESULT, + fn GetObjectParam(&mut self, pszKey: ::LPOLESTR, ppunk: *mut *mut ::IUnknown) -> ::HRESULT, + fn EnumObjectParam(&mut self, ppenum: *mut *mut ::IEnumString) -> ::HRESULT, + fn RevokeObjectParam(&mut self, pszKey: ::LPOLESTR) -> ::HRESULT +} +); +//8681 +pub type IEnumMoniker = ::IUnknown; // TODO +//8958 +RIDL!( +interface IRunningObjectTable(IRunningObjectTableVtbl): IUnknown(IUnknownVtbl) { + fn Register( + &mut self, grfFlags: ::DWORD, punkObject: *mut ::IUnknown, pmkObjectName: *mut IMoniker, + pdwRegister: *mut ::DWORD + ) -> ::HRESULT, + fn Revoke(&mut self, dwRegister: ::DWORD) -> ::HRESULT, + fn IsRunning(&mut self, pmkObjectName: *mut IMoniker) -> ::HRESULT, + fn GetObject( + &mut self, pmkObjectName: *mut IMoniker, ppunkObject: *mut *mut ::IUnknown + ) -> ::HRESULT, + fn NoteChangeTime(&mut self, dwRegister: ::DWORD, pfiletime: *mut ::FILETIME) -> ::HRESULT, + fn GetTimeOfLastChange( + &mut self, pmkObjectName: *mut IMoniker, pfiletime: *mut ::FILETIME + ) -> ::HRESULT, + fn EnumRunning(&mut self, ppenumMoniker: *mut *mut IEnumMoniker) -> ::HRESULT +} +); +//9350 +pub type IMoniker = ::IUnknown; // TODO +pub type EOLE_AUTHENTICATION_CAPABILITIES = ::DWORD; +pub const EOAC_NONE: ::DWORD = 0; +pub const EOAC_MUTUAL_AUTH: ::DWORD = 0x1; +pub const EOAC_STATIC_CLOAKING: ::DWORD = 0x20; +pub const EOAC_DYNAMIC_CLOAKING: ::DWORD = 0x40; +pub const EOAC_ANY_AUTHORITY: ::DWORD = 0x80; +pub const EOAC_MAKE_FULLSIC: ::DWORD = 0x100; +pub const EOAC_DEFAULT: ::DWORD = 0x800; +pub const EOAC_SECURE_REFS: ::DWORD = 0x2; +pub const EOAC_ACCESS_CONTROL: ::DWORD = 0x4; +pub const EOAC_APPID: ::DWORD = 0x8; +pub const EOAC_DYNAMIC: ::DWORD = 0x10; +pub const EOAC_REQUIRE_FULLSIC: ::DWORD = 0x200; +pub const EOAC_AUTO_IMPERSONATE: ::DWORD = 0x400; +pub const EOAC_NO_CUSTOM_MARSHAL: ::DWORD = 0x2000; +pub const EOAC_DISABLE_AAA: ::DWORD = 0x1000; +STRUCT!{struct SOLE_AUTHENTICATION_SERVICE { + dwAuthnSvc: ::DWORD, + dwAuthzSvc: ::DWORD, + pPrincipalName: *mut ::OLECHAR, + hr: ::HRESULT, +}} + +RIDL!( +interface IApartmentShutdown(IApartmentShutdownVtbl): IUnknown(IUnknownVtbl) { + fn OnUninitialize(&mut self, ui64ApartmentIdentifier: ::UINT64) -> ::VOID +} +); + +RIDL!( +interface IMarshal(IMarshalVtbl): IUnknown(IUnknownVtbl) { + fn GetUnmarshalClass( + &mut self, riid: ::REFIID, pv: *const ::VOID, dwDestContext: ::DWORD, + pvDestContext: *const ::VOID, mshlflags: ::DWORD, pCid: *mut ::CLSID + ) -> ::HRESULT, + fn GetMarshalSizeMax( + &mut self, riid: ::REFIID, pv: *const ::VOID, dwDestContext: ::DWORD, + pvDestContext: *const ::VOID, mshlflags: ::DWORD, pSize: *mut ::DWORD + ) -> ::HRESULT, + fn MarshalInterface( + &mut self, pStm: *const ::IStream, riid: ::REFIID, pv: *const ::VOID, + dwDestContext: ::DWORD, pvDestContext: *const ::VOID, + mshlflags: ::DWORD + ) -> ::HRESULT, + fn UnmarshalInterface( + &mut self, pStm: *const ::IStream, riid: ::REFIID, ppv: *mut *mut ::VOID + ) -> ::HRESULT, + fn ReleaseMarshalData(&mut self, pStm: *const ::IStream) -> ::HRESULT, + fn DisconnectObject(&mut self, dwReserved: ::DWORD) -> ::HRESULT +} +); \ No newline at end of file diff --git a/bash-5.1/vendor/winapi-0.2.8/src/objidlbase.rs b/bash-5.1/vendor/winapi-0.2.8/src/objidlbase.rs new file mode 100644 index 0000000..f49353f --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/objidlbase.rs @@ -0,0 +1,93 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +RIDL!( +interface IMalloc(IMallocVtbl): IUnknown(IUnknownVtbl) { + fn Alloc(&mut self, cb: ::SIZE_T) -> *mut ::c_void, + fn Realloc(&mut self, pv: *mut ::c_void, cb: ::SIZE_T) -> *mut ::c_void, + fn Free(&mut self, pv: *mut ::c_void) -> (), + fn GetSize(&mut self, pv: *mut ::c_void) -> ::SIZE_T, + fn DidAlloc(&mut self, pv: *mut ::c_void) -> ::c_int, + fn HeapMinimize(&mut self) -> () +} +); +pub type LPMALLOC = *mut IMalloc; +STRUCT!{struct STATSTG { + pwcsName: ::LPOLESTR, + type_: ::DWORD, + cbSize: ::ULARGE_INTEGER, + mtime: ::FILETIME, + ctime: ::FILETIME, + atime: ::FILETIME, + grfMode: ::DWORD, + grfLocksSupported: ::DWORD, + clsid: ::CLSID, + grfStateBits: ::DWORD, + reserved: ::DWORD, +}} +//1945 +pub type IEnumString = ::IUnknown; // TODO +//2075 +RIDL!( +interface ISequentialStream(ISequentialStreamVtbl): IUnknown(IUnknownVtbl) { + fn Read(&mut self, pv: *mut ::c_void, cb: ::ULONG, pcbRead: *mut ::ULONG) -> ::HRESULT, + fn Write(&mut self, pv: *const ::c_void, cb: ::ULONG, pcbWritten: *mut ::ULONG) -> ::HRESULT +} +); +ENUM!{enum STGTY { + STGTY_STORAGE = 1, + STGTY_STREAM = 2, + STGTY_LOCKBYTES = 3, + STGTY_PROPERTY = 4, +}} +ENUM!{enum STREAM_SEEK { + STREAM_SEEK_SET = 0, + STREAM_SEEK_CUR = 1, + STREAM_SEEK_END = 2, +}} +ENUM!{enum LOCKTYPE { + LOCK_WRITE = 1, + LOCK_EXCLUSIVE = 2, + LOCK_ONLYONCE = 4, +}} +//2255 +RIDL!( +interface IStream(IStreamVtbl): ISequentialStream(ISequentialStreamVtbl) { + fn Seek( + &mut self, dlibMove: ::LARGE_INTEGER, dwOrigin: ::DWORD, + plibNewPosition: *mut ::ULARGE_INTEGER + ) -> ::HRESULT, + fn SetSize(&mut self, libNewSize: ::ULARGE_INTEGER) -> ::HRESULT, + fn CopyTo( + &mut self, pstm: *mut IStream, cb: ::ULARGE_INTEGER, pcbRead: *mut ::ULARGE_INTEGER, + pcbWritten: *mut ::ULARGE_INTEGER + ) -> ::HRESULT, + fn Commit(&mut self, grfCommitFlags: ::DWORD) -> ::HRESULT, + fn Revert(&mut self) -> ::HRESULT, + fn LockRegion( + &mut self, libOffset: ::ULARGE_INTEGER, cb: ::ULARGE_INTEGER, dwLockType: ::DWORD + ) -> ::HRESULT, + fn UnlockRegion( + &mut self, libOffset: ::ULARGE_INTEGER, cb: ::ULARGE_INTEGER, dwLockType: ::DWORD + ) -> ::HRESULT, + fn Stat(&mut self, pstatstg: *mut STATSTG, grfStatFlag: ::DWORD) -> ::HRESULT, + fn Clone(&mut self, ppstm: *mut *mut IStream) -> ::HRESULT +} +); +pub type LPSTREAM = *mut IStream; +ENUM!{enum APTTYPEQUALIFIER { + APTTYPEQUALIFIER_NONE = 0, + APTTYPEQUALIFIER_IMPLICIT_MTA = 1, + APTTYPEQUALIFIER_NA_ON_MTA = 2, + APTTYPEQUALIFIER_NA_ON_STA = 3, + APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA = 4, + APTTYPEQUALIFIER_NA_ON_MAINSTA = 5, + APTTYPEQUALIFIER_APPLICATION_STA= 6, +}} +ENUM!{enum APTTYPE { + APTTYPE_CURRENT = -1i32 as u32, + APTTYPE_STA = 0, + APTTYPE_MTA = 1, + APTTYPE_NA = 2, + APTTYPE_MAINSTA = 3, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/olectl.rs b/bash-5.1/vendor/winapi-0.2.8/src/olectl.rs new file mode 100644 index 0000000..b557621 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/olectl.rs @@ -0,0 +1,10 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! OLE Control interfaces +//299 +pub const SELFREG_E_FIRST: ::HRESULT = MAKE_SCODE!(::SEVERITY_ERROR, ::FACILITY_ITF, 0x0200); +pub const SELFREG_E_LAST: ::HRESULT = MAKE_SCODE!(::SEVERITY_ERROR, ::FACILITY_ITF, 0x020F); +pub const SELFREG_S_FIRST: ::HRESULT = MAKE_SCODE!(::SEVERITY_SUCCESS, ::FACILITY_ITF, 0x0200); +pub const SELFREG_S_LAST: ::HRESULT = MAKE_SCODE!(::SEVERITY_SUCCESS, ::FACILITY_ITF, 0x020F); +pub const SELFREG_E_TYPELIB: ::HRESULT = SELFREG_E_FIRST + 0; +pub const SELFREG_E_CLASS: ::HRESULT = SELFREG_E_FIRST + 1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/pdh.rs b/bash-5.1/vendor/winapi-0.2.8/src/pdh.rs new file mode 100644 index 0000000..165fe1e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/pdh.rs @@ -0,0 +1,52 @@ +// Copyright © 2016, Klavs Madsen +// Licensed under the MIT License <LICENSE.md> +//! Common Performance Data Helper definitions +pub const PDH_FMT_RAW: ::DWORD = 0x00000010; +pub const PDH_FMT_ANSI: ::DWORD = 0x00000020; +pub const PDH_FMT_UNICODE: ::DWORD = 0x00000040; +pub const PDH_FMT_LONG: ::DWORD = 0x00000100; +pub const PDH_FMT_DOUBLE: ::DWORD = 0x00000200; +pub const PDH_FMT_LARGE: ::DWORD = 0x00000400; +pub const PDH_FMT_NOSCALE: ::DWORD = 0x00001000; +pub const PDH_FMT_1000: ::DWORD = 0x00002000; +pub const PDH_FMT_NODATA: ::DWORD = 0x00004000; +pub const PDH_FMT_NOCAP100: ::DWORD = 0x00008000; +pub const PERF_DETAIL_COSTLY: ::DWORD = 0x00010000; +pub const PERF_DETAIL_STANDARD: ::DWORD = 0x0000FFFF; + +pub type PDH_STATUS = ::LONG; +pub type PDH_HQUERY = ::HANDLE; +pub type HQUERY = PDH_HQUERY; +pub type PDH_HCOUNTER = ::HANDLE; +pub type HCOUNTER = PDH_HCOUNTER; + +STRUCT!{struct PDH_FMT_COUNTERVALUE { + CStatus: ::DWORD, + largeValue: ::LONGLONG, +}} +UNION!(PDH_FMT_COUNTERVALUE, largeValue, largeValue, largeValue_mut, ::LONGLONG); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, longValue, longValue_mut, ::LONG); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, doubleValue, doubleValue_mut, ::DOUBLE); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, AnsiStringValue, AnsiStringValue_mut, ::LPCSTR); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, WideStringValue, WideStringValue_mut, ::LPCWSTR); +pub type PPDH_FMT_COUNTERVALUE = *mut PDH_FMT_COUNTERVALUE; + +STRUCT!{struct PDH_COUNTER_PATH_ELEMENTS_A { + szMachineName: ::LPSTR, + szObjectName: ::LPSTR, + szInstanceName: ::LPSTR, + szParentInstance: ::LPSTR, + dwInstanceIndex: ::DWORD, + szCounterName: ::LPSTR, +}} +pub type PPDH_COUNTER_PATH_ELEMENTS_A = *mut PDH_COUNTER_PATH_ELEMENTS_A; + +STRUCT!{struct PDH_COUNTER_PATH_ELEMENTS_W { + szMachineName: ::LPWSTR, + szObjectName: ::LPWSTR, + szInstanceName: ::LPWSTR, + szParentInstance: ::LPWSTR, + dwInstanceIndex: ::DWORD, + szCounterName: ::LPWSTR, +}} +pub type PPDH_COUNTER_PATH_ELEMENTS_W = *mut PDH_COUNTER_PATH_ELEMENTS_W; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/playsoundapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/playsoundapi.rs new file mode 100644 index 0000000..99f4501 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/playsoundapi.rs @@ -0,0 +1,19 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub const SND_SYNC: DWORD = 0x0000; +pub const SND_ASYNC: DWORD = 0x0001; +pub const SND_NODEFAULT: DWORD = 0x0002; +pub const SND_MEMORY: DWORD = 0x0004; +pub const SND_LOOP: DWORD = 0x0008; +pub const SND_NOSTOP: DWORD = 0x0010; +pub const SND_NOWAIT: DWORD = 0x00002000; +pub const SND_ALIAS: DWORD = 0x00010000; +pub const SND_ALIAS_ID: DWORD = 0x00110000; +pub const SND_FILENAME: DWORD = 0x00020000; +pub const SND_RESOURCE: DWORD = 0x00040004; +pub const SND_PURGE: DWORD = 0x0040; +pub const SND_APPLICATION: DWORD = 0x0080; +pub const SND_SENTRY: DWORD = 0x00080000; +pub const SND_RING: DWORD = 0x00100000; +pub const SND_SYSTEM: DWORD = 0x00200000; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/processsnapshot.rs b/bash-5.1/vendor/winapi-0.2.8/src/processsnapshot.rs new file mode 100644 index 0000000..73ea679 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/processsnapshot.rs @@ -0,0 +1,58 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Defines the process snapshot API +FLAGS!{enum PSS_CAPTURE_FLAGS { + PSS_CAPTURE_NONE = 0x00000000, + PSS_CAPTURE_VA_CLONE = 0x00000001, + PSS_CAPTURE_RESERVED_00000002 = 0x00000002, + PSS_CAPTURE_HANDLES = 0x00000004, + PSS_CAPTURE_HANDLE_NAME_INFORMATION = 0x00000008, + PSS_CAPTURE_HANDLE_BASIC_INFORMATION = 0x00000010, + PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION = 0x00000020, + PSS_CAPTURE_HANDLE_TRACE = 0x00000040, + PSS_CAPTURE_THREADS = 0x00000080, + PSS_CAPTURE_THREAD_CONTEXT = 0x00000100, + PSS_CAPTURE_THREAD_CONTEXT_EXTENDED = 0x00000200, + PSS_CAPTURE_RESERVED_00000400 = 0x00000400, + PSS_CAPTURE_VA_SPACE = 0x00000800, + PSS_CAPTURE_VA_SPACE_SECTION_INFORMATION = 0x00001000, + PSS_CREATE_BREAKAWAY_OPTIONAL = 0x04000000, + PSS_CREATE_BREAKAWAY = 0x08000000, + PSS_CREATE_FORCE_BREAKAWAY = 0x10000000, + PSS_CREATE_USE_VM_ALLOCATIONS = 0x20000000, + PSS_CREATE_MEASURE_PERFORMANCE = 0x40000000, + PSS_CREATE_RELEASE_SECTION = -2147483648i32 as u32, +}} +ENUM!{enum PSS_QUERY_INFORMATION_CLASS { + PSS_QUERY_PROCESS_INFORMATION = 0, + PSS_QUERY_VA_CLONE_INFORMATION = 1, + PSS_QUERY_AUXILIARY_PAGES_INFORMATION = 2, + PSS_QUERY_VA_SPACE_INFORMATION = 3, + PSS_QUERY_HANDLE_INFORMATION = 4, + PSS_QUERY_THREAD_INFORMATION = 5, + PSS_QUERY_HANDLE_TRACE_INFORMATION = 6, + PSS_QUERY_PERFORMANCE_COUNTERS = 7, +}} +ENUM!{enum PSS_WALK_INFORMATION_CLASS { + PSS_WALK_AUXILIARY_PAGES = 0, + PSS_WALK_VA_SPACE = 1, + PSS_WALK_HANDLES = 2, + PSS_WALK_THREADS = 3, +}} +FLAGS!{enum PSS_DUPLICATE_FLAGS { + PSS_DUPLICATE_NONE = 0x00, + PSS_DUPLICATE_CLOSE_SOURCE = 0x01, +}} +DECLARE_HANDLE!(HPSS, HPSS__); +DECLARE_HANDLE!(HPSSWALK, HPSSWALK__); +pub type pAllocRoutine = Option<unsafe extern "system" fn( + Context: *mut ::c_void, Size: ::DWORD, +) -> *mut ::c_void>; +pub type pFreeRoutine = Option<unsafe extern "system" fn( + Context: *mut ::c_void, Address: *mut ::c_void, +)>; +STRUCT!{nodebug struct PSS_ALLOCATOR { + Context: *mut ::c_void, + AllocRoutine: pAllocRoutine, + FreeRoutine: pFreeRoutine, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/processthreadsapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/processthreadsapi.rs new file mode 100644 index 0000000..fad58c7 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/processthreadsapi.rs @@ -0,0 +1,62 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +STRUCT!{struct PROCESS_INFORMATION { + hProcess: ::HANDLE, + hThread: ::HANDLE, + dwProcessId: ::DWORD, + dwThreadId: ::DWORD, +}} +pub type PPROCESS_INFORMATION = *mut PROCESS_INFORMATION; +pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; +STRUCT!{struct STARTUPINFOA { + cb: ::DWORD, + lpReserved: ::LPSTR, + lpDesktop: ::LPSTR, + lpTitle: ::LPSTR, + dwX: ::DWORD, + dwY: ::DWORD, + dwXSize: ::DWORD, + dwYSize: ::DWORD, + dwXCountChars: ::DWORD, + dwYCountChars: ::DWORD, + dwFillAttribute: ::DWORD, + dwFlags: ::DWORD, + wShowWindow: ::WORD, + cbReserved2: ::WORD, + lpReserved2: ::LPBYTE, + hStdInput: ::HANDLE, + hStdOutput: ::HANDLE, + hStdError: ::HANDLE, +}} +pub type LPSTARTUPINFOA = *mut STARTUPINFOA; +STRUCT!{struct STARTUPINFOW { + cb: ::DWORD, + lpReserved: ::LPWSTR, + lpDesktop: ::LPWSTR, + lpTitle: ::LPWSTR, + dwX: ::DWORD, + dwY: ::DWORD, + dwXSize: ::DWORD, + dwYSize: ::DWORD, + dwXCountChars: ::DWORD, + dwYCountChars: ::DWORD, + dwFillAttribute: ::DWORD, + dwFlags: ::DWORD, + wShowWindow: ::WORD, + cbReserved2: ::WORD, + lpReserved2: ::LPBYTE, + hStdInput: ::HANDLE, + hStdOutput: ::HANDLE, + hStdError: ::HANDLE, +}} +pub type LPSTARTUPINFOW = *mut STARTUPINFOW; +STRUCT!{struct PROC_THREAD_ATTRIBUTE_LIST { + dummy: *mut ::c_void, +}} +pub type PPROC_THREAD_ATTRIBUTE_LIST = *mut PROC_THREAD_ATTRIBUTE_LIST; +pub type LPPROC_THREAD_ATTRIBUTE_LIST = *mut PROC_THREAD_ATTRIBUTE_LIST; +ENUM!{enum THREAD_INFORMATION_CLASS { + ThreadMemoryPriority, + ThreadAbsoluteCpuPriority, + ThreadInformationClassMax, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/propidl.rs b/bash-5.1/vendor/winapi-0.2.8/src/propidl.rs new file mode 100644 index 0000000..802bd18 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/propidl.rs @@ -0,0 +1,10 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +STRUCT!{struct PROPVARIANT { + vt: VARTYPE, + wReserved1: WORD, + wReserved2: WORD, + wReserved3: WORD, + data: [u8; 16], +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/propsys.rs b/bash-5.1/vendor/winapi-0.2.8/src/propsys.rs new file mode 100644 index 0000000..0666fbd --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/propsys.rs @@ -0,0 +1,4 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub type IPropertyDescriptionList = ::IUnknown; // TODO +pub type IPropertyStore = ::IUnknown; // TODO diff --git a/bash-5.1/vendor/winapi-0.2.8/src/prsht.rs b/bash-5.1/vendor/winapi-0.2.8/src/prsht.rs new file mode 100644 index 0000000..e1795a1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/prsht.rs @@ -0,0 +1,262 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Interface for the Windows Property Sheet Pages +pub enum PSP {} +pub type HPROPSHEETPAGE = *mut PSP; +pub type LPFNPSPCALLBACKA = Option<unsafe extern "system" fn( + hwnd: ::HWND, uMsg: ::UINT, ppsp: *mut PROPSHEETPAGEA, +) -> ::UINT>; +pub type LPFNPSPCALLBACKW = Option<unsafe extern "system" fn( + hwnd: ::HWND, uMsg: ::UINT, ppsp: *mut PROPSHEETPAGEW, +) -> ::UINT>; +pub const PSP_DEFAULT: ::DWORD = 0x00000000; +pub const PSP_DLGINDIRECT: ::DWORD = 0x00000001; +pub const PSP_USEHICON: ::DWORD = 0x00000002; +pub const PSP_USEICONID: ::DWORD = 0x00000004; +pub const PSP_USETITLE: ::DWORD = 0x00000008; +pub const PSP_RTLREADING: ::DWORD = 0x00000010; +pub const PSP_HASHELP: ::DWORD = 0x00000020; +pub const PSP_USEREFPARENT: ::DWORD = 0x00000040; +pub const PSP_USECALLBACK: ::DWORD = 0x00000080; +pub const PSP_PREMATURE: ::DWORD = 0x00000400; +pub const PSP_HIDEHEADER: ::DWORD = 0x00000800; +pub const PSP_USEHEADERTITLE: ::DWORD = 0x00001000; +pub const PSP_USEHEADERSUBTITLE: ::DWORD = 0x00002000; +pub const PSP_USEFUSIONCONTEXT: ::DWORD = 0x00004000; +pub const PSPCB_ADDREF: ::UINT = 0; +pub const PSPCB_RELEASE: ::UINT = 1; +pub const PSPCB_CREATE: ::UINT = 2; +pub type PROPSHEETPAGE_RESOURCE = ::LPCDLGTEMPLATEA; +STRUCT!{nodebug struct PROPSHEETPAGEA_V4 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hInstance: ::HINSTANCE, + pszTemplate: ::LPCSTR, + hIcon: ::HICON, + pszTitle: ::LPCSTR, + pfnDlgProc: ::DLGPROC, + lParam: ::LPARAM, + pfnCallback: LPFNPSPCALLBACKA, + pcRefParent: *mut ::UINT, + pszHeaderTitle: ::LPCSTR, + pszHeaderSubTitle: ::LPCSTR, + hActCtx: ::HANDLE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETPAGEA_V4, pszTemplate, pResource, pResource_mut, PROPSHEETPAGE_RESOURCE); +UNION!(PROPSHEETPAGEA_V4, hIcon, pszIcon, pszIcon_mut, ::LPCSTR); +UNION!(PROPSHEETPAGEA_V4, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCSTR); +pub type LPPROPSHEETPAGEA_V4 = *mut PROPSHEETPAGEA_V4; +pub type LPCPROPSHEETPAGEA_V4 = *const PROPSHEETPAGEA_V4; +STRUCT!{nodebug struct PROPSHEETPAGEW_V4 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hInstance: ::HINSTANCE, + pszTemplate: ::LPCWSTR, + hIcon: ::HICON, + pszTitle: ::LPCWSTR, + pfnDlgProc: ::DLGPROC, + lParam: ::LPARAM, + pfnCallback: LPFNPSPCALLBACKW, + pcRefParent: *mut ::UINT, + pszHeaderTitle: ::LPCWSTR, + pszHeaderSubTitle: ::LPCWSTR, + hActCtx: ::HANDLE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETPAGEW_V4, pszTemplate, pResource, pResource_mut, PROPSHEETPAGE_RESOURCE); +UNION!(PROPSHEETPAGEW_V4, hIcon, pszIcon, pszIcon_mut, ::LPCWSTR); +UNION!(PROPSHEETPAGEW_V4, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCWSTR); +pub type LPPROPSHEETPAGEW_V4 = *mut PROPSHEETPAGEW_V4; +pub type LPCPROPSHEETPAGEW_V4 = *const PROPSHEETPAGEW_V4; +pub type PROPSHEETPAGEA_LATEST = PROPSHEETPAGEA_V4; +pub type PROPSHEETPAGEW_LATEST = PROPSHEETPAGEW_V4; +pub type LPPROPSHEETPAGEA_LATEST = LPPROPSHEETPAGEA_V4; +pub type LPPROPSHEETPAGEW_LATEST = LPPROPSHEETPAGEW_V4; +pub type LPCPROPSHEETPAGEA_LATEST = LPCPROPSHEETPAGEA_V4; +pub type LPCPROPSHEETPAGEW_LATEST = LPCPROPSHEETPAGEW_V4; +pub type PROPSHEETPAGEA = PROPSHEETPAGEA_V4; +pub type PROPSHEETPAGEW = PROPSHEETPAGEW_V4; +pub type LPPROPSHEETPAGEA = LPPROPSHEETPAGEA_V4; +pub type LPPROPSHEETPAGEW = LPPROPSHEETPAGEW_V4; +pub type LPCPROPSHEETPAGEA = LPCPROPSHEETPAGEA_V4; +pub type LPCPROPSHEETPAGEW = LPCPROPSHEETPAGEW_V4; +pub const PSH_DEFAULT: ::DWORD = 0x00000000; +pub const PSH_PROPTITLE: ::DWORD = 0x00000001; +pub const PSH_USEHICON: ::DWORD = 0x00000002; +pub const PSH_USEICONID: ::DWORD = 0x00000004; +pub const PSH_PROPSHEETPAGE: ::DWORD = 0x00000008; +pub const PSH_WIZARDHASFINISH: ::DWORD = 0x00000010; +pub const PSH_WIZARD: ::DWORD = 0x00000020; +pub const PSH_USEPSTARTPAGE: ::DWORD = 0x00000040; +pub const PSH_NOAPPLYNOW: ::DWORD = 0x00000080; +pub const PSH_USECALLBACK: ::DWORD = 0x00000100; +pub const PSH_HASHELP: ::DWORD = 0x00000200; +pub const PSH_MODELESS: ::DWORD = 0x00000400; +pub const PSH_RTLREADING: ::DWORD = 0x00000800; +pub const PSH_WIZARDCONTEXTHELP: ::DWORD = 0x00001000; +pub const PSH_WIZARD97: ::DWORD = 0x01000000; +pub const PSH_WATERMARK: ::DWORD = 0x00008000; +pub const PSH_USEHBMWATERMARK: ::DWORD = 0x00010000; +pub const PSH_USEHPLWATERMARK: ::DWORD = 0x00020000; +pub const PSH_STRETCHWATERMARK: ::DWORD = 0x00040000; +pub const PSH_HEADER: ::DWORD = 0x00080000; +pub const PSH_USEHBMHEADER: ::DWORD = 0x00100000; +pub const PSH_USEPAGELANG: ::DWORD = 0x00200000; +pub const PSH_WIZARD_LITE: ::DWORD = 0x00400000; +pub const PSH_NOCONTEXTHELP: ::DWORD = 0x02000000; +pub const PSH_AEROWIZARD: ::DWORD = 0x00004000; +pub const PSH_RESIZABLE: ::DWORD = 0x04000000; +pub const PSH_HEADERBITMAP: ::DWORD = 0x08000000; +pub const PSH_NOMARGIN: ::DWORD = 0x10000000; +pub type PFNPROPSHEETCALLBACK = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::LPARAM, +) -> ::c_int>; +STRUCT!{nodebug struct PROPSHEETHEADERA_V2 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hwndParent: ::HWND, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + pszCaption: ::LPCSTR, + nPages: ::UINT, + pStartPage: ::LPCSTR, + ppsp: LPCPROPSHEETPAGEA, + pfnCallback: PFNPROPSHEETCALLBACK, + hbmWatermark: ::HBITMAP, + hplWatermark: ::HPALETTE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETHEADERA_V2, hIcon, pszIcon, pszIcon_mut, ::LPCSTR); +UNION!(PROPSHEETHEADERA_V2, pStartPage, nStartPage, nStartPage_mut, ::UINT); +UNION!(PROPSHEETHEADERA_V2, ppsp, phpage, phpage_mut, *mut HPROPSHEETPAGE); +UNION!(PROPSHEETHEADERA_V2, hbmWatermark, pszbmWatermark, pszbmWatermark_mut, ::LPCSTR); +UNION!(PROPSHEETHEADERA_V2, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCSTR); +pub type LPPROPSHEETHEADERA_V2 = *mut PROPSHEETHEADERA_V2; +pub type LPCPROPSHEETHEADERA_V2 = *const PROPSHEETHEADERA_V2; +STRUCT!{nodebug struct PROPSHEETHEADERW_V2 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hwndParent: ::HWND, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + pszCaption: ::LPCWSTR, + nPages: ::UINT, + pStartPage: ::LPCWSTR, + ppsp: LPCPROPSHEETPAGEW, + pfnCallback: PFNPROPSHEETCALLBACK, + hbmWatermark: ::HBITMAP, + hplWatermark: ::HPALETTE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETHEADERW_V2, hIcon, pszIcon, pszIcon_mut, ::LPCWSTR); +UNION!(PROPSHEETHEADERW_V2, pStartPage, nStartPage, nStartPage_mut, ::UINT); +UNION!(PROPSHEETHEADERW_V2, ppsp, phpage, phpage_mut, *mut HPROPSHEETPAGE); +UNION!(PROPSHEETHEADERW_V2, hbmWatermark, pszbmWatermark, pszbmWatermark_mut, ::LPCWSTR); +UNION!(PROPSHEETHEADERW_V2, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCWSTR); +pub type LPPROPSHEETHEADERW_V2 = *mut PROPSHEETHEADERW_V2; +pub type LPCPROPSHEETHEADERW_V2 = *const PROPSHEETHEADERW_V2; +pub type PROPSHEETHEADERA = PROPSHEETHEADERA_V2; +pub type PROPSHEETHEADERW = PROPSHEETHEADERW_V2; +pub type LPPROPSHEETHEADERA = LPPROPSHEETHEADERA_V2; +pub type LPPROPSHEETHEADERW = LPPROPSHEETHEADERW_V2; +pub type LPCPROPSHEETHEADERA = LPCPROPSHEETHEADERA_V2; +pub type LPCPROPSHEETHEADERW = LPCPROPSHEETHEADERW_V2; +pub const PSCB_INITIALIZED: ::UINT = 1; +pub const PSCB_PRECREATE: ::UINT = 2; +pub const PSCB_BUTTONPRESSED: ::UINT = 3; +pub type LPFNADDPROPSHEETPAGE = Option<unsafe extern "system" fn( + HPROPSHEETPAGE, ::LPARAM, +) -> ::BOOL>; +pub type LPFNADDPROPSHEETPAGES = Option<unsafe extern "system" fn( + ::LPVOID, LPFNADDPROPSHEETPAGE, ::LPARAM, +) -> ::BOOL>; +STRUCT!{struct PSHNOTIFY { + hdr: ::NMHDR, + lParam: ::LPARAM, +}} +pub type LPPSHNOTIFY = *mut PSHNOTIFY; +pub const PSN_FIRST: ::UINT = -200i32 as ::UINT; +pub const PSN_LAST: ::UINT = -299i32 as ::UINT; +pub const PSN_SETACTIVE: ::UINT = PSN_FIRST - 0; +pub const PSN_KILLACTIVE: ::UINT = PSN_FIRST - 1; +pub const PSN_APPLY: ::UINT = PSN_FIRST - 2; +pub const PSN_RESET: ::UINT = PSN_FIRST - 3; +pub const PSN_HELP: ::UINT = PSN_FIRST - 5; +pub const PSN_WIZBACK: ::UINT = PSN_FIRST - 6; +pub const PSN_WIZNEXT: ::UINT = PSN_FIRST - 7; +pub const PSN_WIZFINISH: ::UINT = PSN_FIRST - 8; +pub const PSN_QUERYCANCEL: ::UINT = PSN_FIRST - 9; +pub const PSN_GETOBJECT: ::UINT = PSN_FIRST - 10; +pub const PSN_TRANSLATEACCELERATOR: ::UINT = PSN_FIRST - 12; +pub const PSN_QUERYINITIALFOCUS: ::UINT = PSN_FIRST - 13; +pub const PSNRET_NOERROR: ::LRESULT = 0; +pub const PSNRET_INVALID: ::LRESULT = 1; +pub const PSNRET_INVALID_NOCHANGEPAGE: ::LRESULT = 2; +pub const PSNRET_MESSAGEHANDLED: ::LRESULT = 3; +pub const PSM_SETCURSEL: ::UINT = ::WM_USER + 101; +pub const PSM_REMOVEPAGE: ::UINT = ::WM_USER + 102; +pub const PSM_ADDPAGE: ::UINT = ::WM_USER + 103; +pub const PSM_CHANGED: ::UINT = ::WM_USER + 104; +pub const PSM_RESTARTWINDOWS: ::UINT = ::WM_USER + 105; +pub const PSM_REBOOTSYSTEM: ::UINT = ::WM_USER + 106; +pub const PSM_CANCELTOCLOSE: ::UINT = ::WM_USER + 107; +pub const PSM_QUERYSIBLINGS: ::UINT = ::WM_USER + 108; +pub const PSM_UNCHANGED: ::UINT = ::WM_USER + 109; +pub const PSM_APPLY: ::UINT = ::WM_USER + 110; +pub const PSM_SETTITLEA: ::UINT = ::WM_USER + 111; +pub const PSM_SETTITLEW: ::UINT = ::WM_USER + 120; +pub const PSM_SETWIZBUTTONS: ::UINT = ::WM_USER + 112; +pub const PSWIZB_BACK: ::DWORD = 0x00000001; +pub const PSWIZB_NEXT: ::DWORD = 0x00000002; +pub const PSWIZB_FINISH: ::DWORD = 0x00000004; +pub const PSWIZB_DISABLEDFINISH: ::DWORD = 0x00000008; +pub const PSWIZB_CANCEL: ::DWORD = 0x00000008; +pub const PSWIZBF_ELEVATIONREQUIRED: ::WPARAM = 0x00000001; +pub const PSBTN_BACK: ::c_int = 0; +pub const PSBTN_NEXT: ::c_int = 1; +pub const PSBTN_FINISH: ::c_int = 2; +pub const PSBTN_OK: ::c_int = 3; +pub const PSBTN_APPLYNOW: ::c_int = 4; +pub const PSBTN_CANCEL: ::c_int = 5; +pub const PSBTN_HELP: ::c_int = 6; +pub const PSBTN_MAX: ::c_int = 6; +pub const PSM_PRESSBUTTON: ::UINT = ::WM_USER + 113; +pub const PSM_SETCURSELID: ::UINT = ::WM_USER + 114; +pub const PSM_SETFINISHTEXTA: ::UINT = ::WM_USER + 115; +pub const PSM_SETFINISHTEXTW: ::UINT = ::WM_USER + 121; +pub const PSM_GETTABCONTROL: ::UINT = ::WM_USER + 116; +pub const PSM_ISDIALOGMESSAGE: ::UINT = ::WM_USER + 117; +pub const PSM_GETCURRENTPAGEHWND: ::UINT = ::WM_USER + 118; +pub const PSM_INSERTPAGE: ::UINT = ::WM_USER + 119; +pub const PSM_SETHEADERTITLEA: ::UINT = ::WM_USER + 125; +pub const PSM_SETHEADERTITLEW: ::UINT = ::WM_USER + 126; +pub const PSWIZF_SETCOLOR: ::UINT = (0 - 1) as ::UINT; +pub const PSM_SETHEADERSUBTITLEA: ::UINT = ::WM_USER + 127; +pub const PSM_SETHEADERSUBTITLEW: ::UINT = ::WM_USER + 128; +pub const PSM_HWNDTOINDEX: ::UINT = ::WM_USER + 129; +pub const PSM_INDEXTOHWND: ::UINT = ::WM_USER + 130; +pub const PSM_PAGETOINDEX: ::UINT = ::WM_USER + 131; +pub const PSM_INDEXTOPAGE: ::UINT = ::WM_USER + 132; +pub const PSM_IDTOINDEX: ::UINT = ::WM_USER + 133; +pub const PSM_INDEXTOID: ::UINT = ::WM_USER + 134; +pub const PSM_GETRESULT: ::UINT = ::WM_USER + 135; +pub const PSM_RECALCPAGESIZES: ::UINT = ::WM_USER + 136; +pub const PSM_SETNEXTTEXTW: ::UINT = ::WM_USER + 137; +pub const PSM_SHOWWIZBUTTONS: ::UINT = ::WM_USER + 138; +pub const PSM_ENABLEWIZBUTTONS: ::UINT = ::WM_USER + 139; +pub const PSM_SETBUTTONTEXTW: ::UINT = ::WM_USER + 140; +pub const PSM_SETBUTTONTEXT: ::UINT = PSM_SETBUTTONTEXTW; +pub const ID_PSRESTARTWINDOWS: ::INT_PTR = 0x2; +pub const ID_PSREBOOTSYSTEM: ::INT_PTR = ID_PSRESTARTWINDOWS | 0x1; +pub const WIZ_CXDLG: ::DWORD = 276; +pub const WIZ_CYDLG: ::DWORD = 140; +pub const WIZ_CXBMP: ::DWORD = 80; +pub const WIZ_BODYX: ::DWORD = 92; +pub const WIZ_BODYCX: ::DWORD = 184; +pub const PROP_SM_CXDLG: ::c_short = 212; +pub const PROP_SM_CYDLG: ::c_short = 188; +pub const PROP_MED_CXDLG: ::c_short = 227; +pub const PROP_MED_CYDLG: ::c_short = 215; +pub const PROP_LG_CXDLG: ::c_short = 252; +pub const PROP_LG_CYDLG: ::c_short = 218; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/psapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/psapi.rs new file mode 100644 index 0000000..801d35c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/psapi.rs @@ -0,0 +1,166 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! API Prototypes and Definitions for PSAPI.DLL +pub const LIST_MODULES_DEFAULT: ::DWORD = 0x0; +pub const LIST_MODULES_32BIT: ::DWORD = 0x01; +pub const LIST_MODULES_64BIT: ::DWORD = 0x02; +pub const LIST_MODULES_ALL: ::DWORD = LIST_MODULES_32BIT | LIST_MODULES_64BIT; +STRUCT!{struct MODULEINFO { + lpBaseOfDll: ::LPVOID, + SizeOfImage: ::DWORD, + EntryPoint: ::LPVOID, +}} +pub type LPMODULEINFO = *mut MODULEINFO; +STRUCT!{struct PSAPI_WORKING_SET_BLOCK { + Flags: ::ULONG_PTR, + BitFields: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +BITFIELD!(PSAPI_WORKING_SET_BLOCK BitFields: ::ULONG_PTR [ + Protection set_Protection[0..5], + ShareCount set_ShareCount[5..8], + Shared set_Shared[8..9], + Reserved set_Reserved[9..12], + VirtualPage set_VirtualPage[12..32], +]); +#[cfg(target_arch="x86_64")] +BITFIELD!(PSAPI_WORKING_SET_BLOCK BitFields: ::ULONG_PTR [ + Protection set_Protection[0..5], + ShareCount set_ShareCount[5..8], + Shared set_Shared[8..9], + Reserved set_Reserved[9..12], + VirtualPage set_VirtualPage[12..64], +]); +pub type PPSAPI_WORKING_SET_BLOCK = *mut PSAPI_WORKING_SET_BLOCK; +STRUCT!{struct PSAPI_WORKING_SET_INFORMATION { + NumberOfEntries: ::ULONG_PTR, + WorkingSetInfo: [PSAPI_WORKING_SET_BLOCK; 1], +}} +pub type PPSAPI_WORKING_SET_INFORMATION = *mut PSAPI_WORKING_SET_INFORMATION; +STRUCT!{struct PSAPI_WORKING_SET_EX_BLOCK_Invalid { + BitFields: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK_Invalid BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + Reserved0 set_Reserved0[1..15], + Shared set_Shared[15..16], + Reserved1 set_Reserved1[16..31], + Bad set_Bad[31..32], +]); +#[cfg(target_arch="x86_64")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK_Invalid BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + Reserved0 set_Reserved0[1..15], + Shared set_Shared[15..16], + Reserved1 set_Reserved1[16..31], + Bad set_Bad[31..32], + ReservedUlong set_ReservedUlong[32..64], +]); +STRUCT!{struct PSAPI_WORKING_SET_EX_BLOCK { + Flags: ::ULONG_PTR, + BitFields: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + ShareCount set_ShareCount[1..4], + Win32Protection set_Win32Protection[4..15], + Shared set_Shared[15..16], + Node set_Node[16..22], + Locked set_Locked[22..23], + LargePage set_LargePage[23..24], + Reserved set_Reserved[24..31], + Bad set_Bad[31..32], +]); +#[cfg(target_arch="x86_64")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + ShareCount set_ShareCount[1..4], + Win32Protection set_Win32Protection[4..15], + Shared set_Shared[15..16], + Node set_Node[16..22], + Locked set_Locked[22..23], + LargePage set_LargePage[23..24], + Reserved set_Reserved[24..31], + Bad set_Bad[31..32], + ReservedUlong set_ReservedUlong[32..64], +]); +UNION!( + PSAPI_WORKING_SET_EX_BLOCK, BitFields, Invalid, Invalid_mut, PSAPI_WORKING_SET_EX_BLOCK_Invalid +); +pub type PPSAPI_WORKING_SET_EX_BLOCK = *mut PSAPI_WORKING_SET_EX_BLOCK; +STRUCT!{struct PSAPI_WORKING_SET_EX_INFORMATION { + VirtualAddress: ::PVOID, + VirtualAttributes: PSAPI_WORKING_SET_EX_BLOCK, +}} +pub type PPSAPI_WORKING_SET_EX_INFORMATION = *mut PSAPI_WORKING_SET_EX_INFORMATION; +STRUCT!{struct PSAPI_WS_WATCH_INFORMATION { + FaultingPc: ::LPVOID, + FaultingVa: ::LPVOID, +}} +pub type PPSAPI_WS_WATCH_INFORMATION = *mut PSAPI_WS_WATCH_INFORMATION; +STRUCT!{struct PSAPI_WS_WATCH_INFORMATION_EX { + BasicInfo: PSAPI_WS_WATCH_INFORMATION, + FaultingThreadId: ::ULONG_PTR, + Flags: ::ULONG_PTR, +}} +pub type PPSAPI_WS_WATCH_INFORMATION_EX = *mut PSAPI_WS_WATCH_INFORMATION_EX; +STRUCT!{struct PROCESS_MEMORY_COUNTERS { + cb: ::DWORD, + PageFaultCount: ::DWORD, + PeakWorkingSetSize: ::SIZE_T, + WorkingSetSize: ::SIZE_T, + QuotaPeakPagedPoolUsage: ::SIZE_T, + QuotaPagedPoolUsage: ::SIZE_T, + QuotaPeakNonPagedPoolUsage: ::SIZE_T, + QuotaNonPagedPoolUsage: ::SIZE_T, + PagefileUsage: ::SIZE_T, + PeakPagefileUsage: ::SIZE_T, +}} +pub type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS; +STRUCT!{struct PROCESS_MEMORY_COUNTERS_EX { + cb: ::DWORD, + PageFaultCount: ::DWORD, + PeakWorkingSetSize: ::SIZE_T, + WorkingSetSize: ::SIZE_T, + QuotaPeakPagedPoolUsage: ::SIZE_T, + QuotaPagedPoolUsage: ::SIZE_T, + QuotaPeakNonPagedPoolUsage: ::SIZE_T, + QuotaNonPagedPoolUsage: ::SIZE_T, + PagefileUsage: ::SIZE_T, + PeakPagefileUsage: ::SIZE_T, + PrivateUsage: ::SIZE_T, +}} +pub type PPROCESS_MEMORY_COUNTERS_EX = *mut PROCESS_MEMORY_COUNTERS_EX; +STRUCT!{struct PERFORMANCE_INFORMATION { + cb: ::DWORD, + CommitTotal: ::SIZE_T, + CommitLimit: ::SIZE_T, + CommitPeak: ::SIZE_T, + PhysicalTotal: ::SIZE_T, + PhysicalAvailable: ::SIZE_T, + SystemCache: ::SIZE_T, + KernelTotal: ::SIZE_T, + KernelPaged: ::SIZE_T, + KernelNonpaged: ::SIZE_T, + PageSize: ::SIZE_T, + HandleCount: ::DWORD, + ProcessCount: ::DWORD, + ThreadCount: ::DWORD, +}} +pub type PPERFORMANCE_INFORMATION = *mut PERFORMANCE_INFORMATION; +STRUCT!{struct ENUM_PAGE_FILE_INFORMATION { + cb: ::DWORD, + Reserved: ::DWORD, + TotalSize: ::SIZE_T, + TotalInUse: ::SIZE_T, + PeakUsage: ::SIZE_T, +}} +pub type PENUM_PAGE_FILE_INFORMATION = *mut ENUM_PAGE_FILE_INFORMATION; +pub type PENUM_PAGE_FILE_CALLBACKA = Option<unsafe extern "system" fn( + pContext: ::LPVOID, pPageFileInfo: PENUM_PAGE_FILE_INFORMATION, lpFilename: ::LPCSTR, +) -> ::BOOL>; +pub type PENUM_PAGE_FILE_CALLBACKW = Option<unsafe extern "system" fn( + pContext: ::LPVOID, pPageFileInfo: PENUM_PAGE_FILE_INFORMATION, lpFilename: ::LPCWSTR, +) -> ::BOOL>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/qos.rs b/bash-5.1/vendor/winapi-0.2.8/src/qos.rs new file mode 100644 index 0000000..91026b3 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/qos.rs @@ -0,0 +1,16 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! QoS definitions for NDIS components. +pub type SERVICETYPE = ::ULONG; +STRUCT!{struct FLOWSPEC { + TokenRate: ::ULONG, + TokenBucketSize: ::ULONG, + PeakBandwidth: ::ULONG, + Latency: ::ULONG, + DelayVariation: ::ULONG, + ServiceType: SERVICETYPE, + MaxSduSize: ::ULONG, + MinimumPolicedSize: ::ULONG, +}} +pub type PFLOWSPEC = *mut FLOWSPEC; +pub type LPFLOWSPEC = *mut FLOWSPEC; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/reason.rs b/bash-5.1/vendor/winapi-0.2.8/src/reason.rs new file mode 100644 index 0000000..66b3ed3 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/reason.rs @@ -0,0 +1,63 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +// Flags used by the various UIs +pub const SHTDN_REASON_FLAG_COMMENT_REQUIRED: ::DWORD = 0x01000000; +pub const SHTDN_REASON_FLAG_DIRTY_PROBLEM_ID_REQUIRED: ::DWORD = 0x02000000; +pub const SHTDN_REASON_FLAG_CLEAN_UI: ::DWORD = 0x04000000; +pub const SHTDN_REASON_FLAG_DIRTY_UI: ::DWORD = 0x08000000; +// Flags that end up in the event log code. +pub const SHTDN_REASON_FLAG_USER_DEFINED: ::DWORD = 0x40000000; +pub const SHTDN_REASON_FLAG_PLANNED: ::DWORD = 0x80000000; +// Microsoft major reasons. +pub const SHTDN_REASON_MAJOR_OTHER: ::DWORD = 0x00000000; +pub const SHTDN_REASON_MAJOR_NONE: ::DWORD = 0x00000000; +pub const SHTDN_REASON_MAJOR_HARDWARE: ::DWORD = 0x00010000; +pub const SHTDN_REASON_MAJOR_OPERATINGSYSTEM: ::DWORD = 0x00020000; +pub const SHTDN_REASON_MAJOR_SOFTWARE: ::DWORD = 0x00030000; +pub const SHTDN_REASON_MAJOR_APPLICATION: ::DWORD = 0x00040000; +pub const SHTDN_REASON_MAJOR_SYSTEM: ::DWORD = 0x00050000; +pub const SHTDN_REASON_MAJOR_POWER: ::DWORD = 0x00060000; +pub const SHTDN_REASON_MAJOR_LEGACY_API: ::DWORD = 0x00070000; +// Microsoft minor reasons. +pub const SHTDN_REASON_MINOR_OTHER: ::DWORD = 0x00000000; +pub const SHTDN_REASON_MINOR_NONE: ::DWORD = 0x000000ff; +pub const SHTDN_REASON_MINOR_MAINTENANCE: ::DWORD = 0x00000001; +pub const SHTDN_REASON_MINOR_INSTALLATION: ::DWORD = 0x00000002; +pub const SHTDN_REASON_MINOR_UPGRADE: ::DWORD = 0x00000003; +pub const SHTDN_REASON_MINOR_RECONFIG: ::DWORD = 0x00000004; +pub const SHTDN_REASON_MINOR_HUNG: ::DWORD = 0x00000005; +pub const SHTDN_REASON_MINOR_UNSTABLE: ::DWORD = 0x00000006; +pub const SHTDN_REASON_MINOR_DISK: ::DWORD = 0x00000007; +pub const SHTDN_REASON_MINOR_PROCESSOR: ::DWORD = 0x00000008; +pub const SHTDN_REASON_MINOR_NETWORKCARD: ::DWORD = 0x00000009; +pub const SHTDN_REASON_MINOR_POWER_SUPPLY: ::DWORD = 0x0000000a; +pub const SHTDN_REASON_MINOR_CORDUNPLUGGED: ::DWORD = 0x0000000b; +pub const SHTDN_REASON_MINOR_ENVIRONMENT: ::DWORD = 0x0000000c; +pub const SHTDN_REASON_MINOR_HARDWARE_DRIVER: ::DWORD = 0x0000000d; +pub const SHTDN_REASON_MINOR_OTHERDRIVER: ::DWORD = 0x0000000e; +pub const SHTDN_REASON_MINOR_BLUESCREEN: ::DWORD = 0x0000000F; +pub const SHTDN_REASON_MINOR_SERVICEPACK: ::DWORD = 0x00000010; +pub const SHTDN_REASON_MINOR_HOTFIX: ::DWORD = 0x00000011; +pub const SHTDN_REASON_MINOR_SECURITYFIX: ::DWORD = 0x00000012; +pub const SHTDN_REASON_MINOR_SECURITY: ::DWORD = 0x00000013; +pub const SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY: ::DWORD = 0x00000014; +pub const SHTDN_REASON_MINOR_WMI: ::DWORD = 0x00000015; +pub const SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL: ::DWORD = 0x00000016; +pub const SHTDN_REASON_MINOR_HOTFIX_UNINSTALL: ::DWORD = 0x00000017; +pub const SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL: ::DWORD = 0x00000018; +pub const SHTDN_REASON_MINOR_MMC: ::DWORD = 0x00000019; +pub const SHTDN_REASON_MINOR_SYSTEMRESTORE: ::DWORD = 0x0000001a; +pub const SHTDN_REASON_MINOR_TERMSRV: ::DWORD = 0x00000020; +pub const SHTDN_REASON_MINOR_DC_PROMOTION: ::DWORD = 0x00000021; +pub const SHTDN_REASON_MINOR_DC_DEMOTION: ::DWORD = 0x00000022; +pub const SHTDN_REASON_UNKNOWN: ::DWORD = SHTDN_REASON_MINOR_NONE; +pub const SHTDN_REASON_LEGACY_API: ::DWORD = + (SHTDN_REASON_MAJOR_LEGACY_API | SHTDN_REASON_FLAG_PLANNED); +// This mask cuts out UI flags. +pub const SHTDN_REASON_VALID_BIT_MASK: ::DWORD = 0xc0ffffff; +// Convenience flags. +pub const PCLEANUI: ::DWORD = (SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_FLAG_CLEAN_UI); +pub const UCLEANUI: ::DWORD = (SHTDN_REASON_FLAG_CLEAN_UI); +pub const PDIRTYUI: ::DWORD = (SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_FLAG_DIRTY_UI); +pub const UDIRTYUI: ::DWORD = (SHTDN_REASON_FLAG_DIRTY_UI); +//89 diff --git a/bash-5.1/vendor/winapi-0.2.8/src/restrictederrorinfo.rs b/bash-5.1/vendor/winapi-0.2.8/src/restrictederrorinfo.rs new file mode 100644 index 0000000..94fbb77 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/restrictederrorinfo.rs @@ -0,0 +1,9 @@ +RIDL!( +interface IRestrictedErrorInfo(IRestrictedErrorInfoVtbl): IUnknown(IUnknownVtbl) { + fn GetErrorDetails( + &mut self, description: *mut ::BSTR, error: *mut ::HRESULT, + restrictedDescription: *mut ::BSTR, capabilitySid: *mut ::BSTR + ) -> ::HRESULT, + fn GetReference(&mut self, reference: *mut ::BSTR) -> ::HRESULT +} +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/roapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/roapi.rs new file mode 100644 index 0000000..db8d5df --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/roapi.rs @@ -0,0 +1,13 @@ +ENUM!{enum RO_INIT_TYPE { + RO_INIT_SINGLETHREADED = 0, + RO_INIT_MULTITHREADED = 1, +}} + +pub enum RO_REGISTRATION_COOKIE__{} +pub type RO_REGISTRATION_COOKIE = *mut RO_REGISTRATION_COOKIE__; + +pub type PFNGETACTIVATIONFACTORY = Option<unsafe extern "system" fn( + ::HSTRING, *mut *mut ::IActivationFactory, +) -> ::HRESULT>; + +DECLARE_HANDLE!(APARTMENT_SHUTDOWN_REGISTRATION_COOKIE, APARTMENT_SHUTDOWN_REGISTRATION_COOKIE__); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/roerrorapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/roerrorapi.rs new file mode 100644 index 0000000..9a0cbcc --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/roerrorapi.rs @@ -0,0 +1,11 @@ +FLAGS!{enum RO_ERROR_REPORTING_FLAGS { + RO_ERROR_REPORTING_NONE = 0x00000000, + RO_ERROR_REPORTING_SUPPRESSEXCEPTIONS = 0x00000001, + RO_ERROR_REPORTING_FORCEEXCEPTIONS = 0x00000002, + RO_ERROR_REPORTING_USESETERRORINFO = 0x00000004, + RO_ERROR_REPORTING_SUPPRESSSETERRORINFO = 0x00000008, +}} + +pub type PINSPECT_MEMORY_CALLBACK = Option<unsafe extern "system" fn( + *const ::VOID, ::UINT_PTR, ::UINT32, *mut ::BYTE, +) -> ::HRESULT>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/rpc.rs b/bash-5.1/vendor/winapi-0.2.8/src/rpc.rs new file mode 100644 index 0000000..0b013d3 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/rpc.rs @@ -0,0 +1,5 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +// Master include file for RPC applications. +pub type I_RPC_HANDLE = *mut ::c_void; +pub type RPC_STATUS = ::c_long; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/rpcdce.rs b/bash-5.1/vendor/winapi-0.2.8/src/rpcdce.rs new file mode 100644 index 0000000..68d88c7 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/rpcdce.rs @@ -0,0 +1,535 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License <LICENSE.md> +// This module contains the DCE RPC runtime APIs. +pub type RPC_CSTR = *mut ::c_uchar; +pub type RPC_WSTR = *mut ::wchar_t; +pub type RPC_CWSTR = *const ::wchar_t; +pub type RPC_BINDING_HANDLE = ::I_RPC_HANDLE; +pub type handle_t = RPC_BINDING_HANDLE; +pub type rpc_binding_handle_t = RPC_BINDING_HANDLE; +pub type UUID = ::GUID; +pub type uuid_t = UUID; +STRUCT!{struct RPC_BINDING_VECTOR { + Count: ::c_ulong, + BindingH: [RPC_BINDING_HANDLE; 1], +}} +pub type rpc_binding_vector_t = RPC_BINDING_VECTOR; +STRUCT!{struct UUID_VECTOR { + Count: ::c_ulong, + Uuid: [*mut UUID; 1], +}} +pub type uuid_vector_t = UUID_VECTOR; +pub type RPC_IF_HANDLE = *mut ::c_void; +STRUCT!{struct RPC_IF_ID { + Uuid: UUID, + VersMajor: ::c_ushort, + VersMinor: ::c_ushort, +}} +pub const RPC_C_BINDING_INFINITE_TIMEOUT: ::DWORD = 10; +pub const RPC_C_BINDING_MIN_TIMEOUT: ::DWORD = 0; +pub const RPC_C_BINDING_DEFAULT_TIMEOUT: ::DWORD = 5; +pub const RPC_C_BINDING_MAX_TIMEOUT: ::DWORD = 9; +pub const RPC_C_CANCEL_INFINITE_TIMEOUT: ::c_int = -1; +pub const RPC_C_LISTEN_MAX_CALLS_DEFAULT: ::DWORD = 1234; +pub const RPC_C_PROTSEQ_MAX_REQS_DEFAULT: ::DWORD = 10; +pub const RPC_C_BIND_TO_ALL_NICS: ::DWORD = 1; +pub const RPC_C_USE_INTERNET_PORT: ::DWORD = 0x1; +pub const RPC_C_USE_INTRANET_PORT: ::DWORD = 0x2; +pub const RPC_C_DONT_FAIL: ::DWORD = 0x4; +pub const RPC_C_RPCHTTP_USE_LOAD_BALANCE: ::DWORD = 0x8; +pub const RPC_C_MQ_TEMPORARY: ::DWORD = 0x0000; +pub const RPC_C_MQ_PERMANENT: ::DWORD = 0x0001; +pub const RPC_C_MQ_CLEAR_ON_OPEN: ::DWORD = 0x0002; +pub const RPC_C_MQ_USE_EXISTING_SECURITY: ::DWORD = 0x0004; +pub const RPC_C_MQ_AUTHN_LEVEL_NONE: ::DWORD = 0x0000; +pub const RPC_C_MQ_AUTHN_LEVEL_PKT_INTEGRITY: ::DWORD = 0x0008; +pub const RPC_C_MQ_AUTHN_LEVEL_PKT_PRIVACY: ::DWORD = 0x0010; +pub const RPC_C_OPT_MQ_DELIVERY: ::DWORD = 1; +pub const RPC_C_OPT_MQ_PRIORITY: ::DWORD = 2; +pub const RPC_C_OPT_MQ_JOURNAL: ::DWORD = 3; +pub const RPC_C_OPT_MQ_ACKNOWLEDGE: ::DWORD = 4; +pub const RPC_C_OPT_MQ_AUTHN_SERVICE: ::DWORD = 5; +pub const RPC_C_OPT_MQ_AUTHN_LEVEL: ::DWORD = 6; +pub const RPC_C_OPT_MQ_TIME_TO_REACH_QUEUE: ::DWORD = 7; +pub const RPC_C_OPT_MQ_TIME_TO_BE_RECEIVED: ::DWORD = 8; +pub const RPC_C_OPT_BINDING_NONCAUSAL: ::DWORD = 9; +pub const RPC_C_OPT_SECURITY_CALLBACK: ::DWORD = 10; +pub const RPC_C_OPT_UNIQUE_BINDING: ::DWORD = 11; +pub const RPC_C_OPT_CALL_TIMEOUT: ::DWORD = 12; +pub const RPC_C_OPT_DONT_LINGER: ::DWORD = 13; +pub const RPC_C_OPT_TRUST_PEER: ::DWORD = 14; +pub const RPC_C_OPT_ASYNC_BLOCK: ::DWORD = 15; +pub const RPC_C_OPT_OPTIMIZE_TIME: ::DWORD = 16; +pub const RPC_C_OPT_MAX_OPTIONS: ::DWORD = 17; +pub const RPC_C_MQ_EXPRESS: ::DWORD = 0; +pub const RPC_C_MQ_RECOVERABLE: ::DWORD = 1; +pub const RPC_C_MQ_JOURNAL_NONE: ::DWORD = 0; +pub const RPC_C_MQ_JOURNAL_DEADLETTER: ::DWORD = 1; +pub const RPC_C_MQ_JOURNAL_ALWAYS: ::DWORD = 2; +pub const RPC_C_FULL_CERT_CHAIN: ::DWORD = 0x0001; +STRUCT!{struct RPC_PROTSEQ_VECTORA { + Count: ::c_uint, + Protseq: [*mut ::c_uchar; 1], +}} +STRUCT!{struct RPC_PROTSEQ_VECTORW { + Count: ::c_uint, + Protseq: [*mut ::c_ushort; 1], +}} +STRUCT!{struct RPC_POLICY { + Length: ::c_uint, + EndpointFlags: ::c_ulong, + NICFlags: ::c_ulong, +}} +pub type PRPC_POLICY = *mut RPC_POLICY; +pub type RPC_OBJECT_INQ_FN = Option<unsafe extern "system" fn( + ObjectUuid: *mut UUID, TypeUuid: *mut UUID, Status: *mut ::RPC_STATUS, +)>; +pub type RPC_IF_CALLBACK_FN = Option<unsafe extern "system" fn( + InterfaceUuid: RPC_IF_HANDLE, Context: *mut ::c_void, +) -> ::RPC_STATUS>; +pub type RPC_SECURITY_CALLBACK_FN = Option<unsafe extern "system" fn(Context: *mut ::c_void)>; +pub type RPC_MGR_EPV = ::c_void; +STRUCT!{struct RPC_STATS_VECTOR { + Count: ::c_uint, + Stats: [::c_ulong; 1], +}} +pub const RPC_C_STATS_CALLS_IN: ::c_ulong = 0; +pub const RPC_C_STATS_CALLS_OUT: ::c_ulong = 1; +pub const RPC_C_STATS_PKTS_IN: ::c_ulong = 2; +pub const RPC_C_STATS_PKTS_OUT: ::c_ulong = 3; +STRUCT!{struct RPC_IF_ID_VECTOR { + Count: ::c_ulong, + IfId: [*mut RPC_IF_ID; 1], +}} +pub type RPC_AUTH_IDENTITY_HANDLE = *mut ::c_void; +pub type RPC_AUTHZ_HANDLE = *mut ::c_void; +pub const RPC_C_AUTHN_LEVEL_DEFAULT: ::DWORD = 0; +pub const RPC_C_AUTHN_LEVEL_NONE: ::DWORD = 1; +pub const RPC_C_AUTHN_LEVEL_CONNECT: ::DWORD = 2; +pub const RPC_C_AUTHN_LEVEL_CALL: ::DWORD = 3; +pub const RPC_C_AUTHN_LEVEL_PKT: ::DWORD = 4; +pub const RPC_C_AUTHN_LEVEL_PKT_INTEGRITY: ::DWORD = 5; +pub const RPC_C_AUTHN_LEVEL_PKT_PRIVACY: ::DWORD = 6; +pub const RPC_C_IMP_LEVEL_DEFAULT: ::DWORD = 0; +pub const RPC_C_IMP_LEVEL_ANONYMOUS: ::DWORD = 1; +pub const RPC_C_IMP_LEVEL_IDENTIFY: ::DWORD = 2; +pub const RPC_C_IMP_LEVEL_IMPERSONATE: ::DWORD = 3; +pub const RPC_C_IMP_LEVEL_DELEGATE: ::DWORD = 4; +pub const RPC_C_QOS_IDENTITY_STATIC: ::DWORD = 0; +pub const RPC_C_QOS_IDENTITY_DYNAMIC: ::DWORD = 1; +pub const RPC_C_QOS_CAPABILITIES_DEFAULT: ::DWORD = 0x0; +pub const RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH: ::DWORD = 0x1; +pub const RPC_C_QOS_CAPABILITIES_MAKE_FULLSIC: ::DWORD = 0x2; +pub const RPC_C_QOS_CAPABILITIES_ANY_AUTHORITY: ::DWORD = 0x4; +pub const RPC_C_QOS_CAPABILITIES_IGNORE_DELEGATE_FAILURE: ::DWORD = 0x8; +pub const RPC_C_QOS_CAPABILITIES_LOCAL_MA_HINT: ::DWORD = 0x10; +pub const RPC_C_QOS_CAPABILITIES_SCHANNEL_FULL_AUTH_IDENTITY: ::DWORD = 0x20; +pub const RPC_C_PROTECT_LEVEL_DEFAULT: ::DWORD = RPC_C_AUTHN_LEVEL_DEFAULT; +pub const RPC_C_PROTECT_LEVEL_NONE: ::DWORD = RPC_C_AUTHN_LEVEL_NONE; +pub const RPC_C_PROTECT_LEVEL_CONNECT: ::DWORD = RPC_C_AUTHN_LEVEL_CONNECT; +pub const RPC_C_PROTECT_LEVEL_CALL: ::DWORD = RPC_C_AUTHN_LEVEL_CALL; +pub const RPC_C_PROTECT_LEVEL_PKT: ::DWORD = RPC_C_AUTHN_LEVEL_PKT; +pub const RPC_C_PROTECT_LEVEL_PKT_INTEGRITY: ::DWORD = RPC_C_AUTHN_LEVEL_PKT_INTEGRITY; +pub const RPC_C_PROTECT_LEVEL_PKT_PRIVACY: ::DWORD = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; +pub const RPC_C_AUTHN_NONE: ::DWORD = 0; +pub const RPC_C_AUTHN_DCE_PRIVATE: ::DWORD = 1; +pub const RPC_C_AUTHN_DCE_PUBLIC: ::DWORD = 2; +pub const RPC_C_AUTHN_DEC_PUBLIC: ::DWORD = 4; +pub const RPC_C_AUTHN_GSS_NEGOTIATE: ::DWORD = 9; +pub const RPC_C_AUTHN_WINNT: ::DWORD = 10; +pub const RPC_C_AUTHN_GSS_SCHANNEL: ::DWORD = 14; +pub const RPC_C_AUTHN_GSS_KERBEROS: ::DWORD = 16; +pub const RPC_C_AUTHN_DPA: ::DWORD = 17; +pub const RPC_C_AUTHN_MSN: ::DWORD = 18; +pub const RPC_C_AUTHN_DIGEST: ::DWORD = 21; +pub const RPC_C_AUTHN_KERNEL: ::DWORD = 20; +pub const RPC_C_AUTHN_NEGO_EXTENDER: ::DWORD = 30; +pub const RPC_C_AUTHN_PKU2U: ::DWORD = 31; +pub const RPC_C_AUTHN_LIVE_SSP: ::DWORD = 32; +pub const RPC_C_AUTHN_LIVEXP_SSP: ::DWORD = 35; +pub const RPC_C_AUTHN_MSONLINE: ::DWORD = 82; +pub const RPC_C_AUTHN_MQ: ::DWORD = 100; +pub const RPC_C_AUTHN_DEFAULT: ::DWORD = 0xFFFFFFFF; +pub const RPC_C_NO_CREDENTIALS: ::DWORD = 0xFFFFFFFF; +pub const RPC_C_SECURITY_QOS_VERSION: ::DWORD = 1; +pub const RPC_C_SECURITY_QOS_VERSION_1: ::DWORD = 1; +STRUCT!{struct RPC_SECURITY_QOS { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, +}} +pub type PRPC_SECURITY_QOS = *mut RPC_SECURITY_QOS; +STRUCT!{struct SEC_WINNT_AUTH_IDENTITY_W { + User: *mut ::c_ushort, + UserLength: ::c_ulong, + Domain: *mut ::c_ushort, + DomainLength: ::c_ulong, + Password: *mut ::c_ushort, + PasswordLength: ::c_ulong, + Flags: ::c_ulong, +}} +pub type PSEC_WINNT_AUTH_IDENTITY_W = *mut SEC_WINNT_AUTH_IDENTITY_W; +STRUCT!{struct SEC_WINNT_AUTH_IDENTITY_A { + User: *mut ::c_uchar, + UserLength: ::c_ulong, + Domain: *mut ::c_uchar, + DomainLength: ::c_ulong, + Password: *mut ::c_uchar, + PasswordLength: ::c_ulong, + Flags: ::c_ulong, +}} +pub type PSEC_WINNT_AUTH_IDENTITY_A = *mut SEC_WINNT_AUTH_IDENTITY_A; +pub const RPC_C_AUTHN_INFO_TYPE_HTTP: ::c_ulong = 1; +pub const RPC_C_HTTP_AUTHN_TARGET_SERVER: ::c_ulong = 1; +pub const RPC_C_HTTP_AUTHN_TARGET_PROXY: ::c_ulong = 2; +pub const RPC_C_HTTP_AUTHN_SCHEME_BASIC: ::c_ulong = 0x00000001; +pub const RPC_C_HTTP_AUTHN_SCHEME_NTLM: ::c_ulong = 0x00000002; +pub const RPC_C_HTTP_AUTHN_SCHEME_PASSPORT: ::c_ulong = 0x00000004; +pub const RPC_C_HTTP_AUTHN_SCHEME_DIGEST: ::c_ulong = 0x00000008; +pub const RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE: ::c_ulong = 0x00000010; +pub const RPC_C_HTTP_AUTHN_SCHEME_CERT: ::c_ulong = 0x00010000; +pub const RPC_C_HTTP_FLAG_USE_SSL: ::c_ulong = 1; +pub const RPC_C_HTTP_FLAG_USE_FIRST_AUTH_SCHEME: ::c_ulong = 2; +pub const RPC_C_HTTP_FLAG_IGNORE_CERT_CN_INVALID: ::c_ulong = 8; +pub const RPC_C_HTTP_FLAG_ENABLE_CERT_REVOCATION_CHECK: ::c_ulong = 16; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_W { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_W, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_ushort, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_W = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_A { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_A, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_uchar, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_A = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V2_W { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_W, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_ushort, + ProxyCredentials: *mut SEC_WINNT_AUTH_IDENTITY_W, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V2_W = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V2_W; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V2_A { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_A, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_uchar, + ProxyCredentials: *mut SEC_WINNT_AUTH_IDENTITY_A, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V2_A = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V2_A; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V3_W { + TransportCredentials: RPC_AUTH_IDENTITY_HANDLE, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_ushort, + ProxyCredentials: *mut RPC_AUTH_IDENTITY_HANDLE, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V3_W = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V3_W; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V3_A { + TransportCredentials: RPC_AUTH_IDENTITY_HANDLE, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_uchar, + ProxyCredentials: *mut RPC_AUTH_IDENTITY_HANDLE, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V3_A = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V3_A; +STRUCT!{struct RPC_SECURITY_QOS_V2_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V2_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V2_W_union, +}} +pub type PRPC_SECURITY_QOS_V2_W = *mut RPC_SECURITY_QOS_V2_W; +STRUCT!{struct RPC_SECURITY_QOS_V2_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V2_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V2_A_union, +}} +pub type PRPC_SECURITY_QOS_V2_A = *mut RPC_SECURITY_QOS_V2_A; +STRUCT!{struct RPC_SECURITY_QOS_V3_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V3_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V3_W_union, + Sid: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V3_W = *mut RPC_SECURITY_QOS_V3_W; +STRUCT!{struct RPC_SECURITY_QOS_V3_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V3_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V3_A_union, + Sid: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V3_A = *mut RPC_SECURITY_QOS_V3_A; +STRUCT!{struct RPC_SECURITY_QOS_V4_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V4_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V4_W_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, +}} +pub type PRPC_SECURITY_QOS_V4_W = *mut RPC_SECURITY_QOS_V4_W; +STRUCT!{struct RPC_SECURITY_QOS_V4_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V4_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V4_A_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, +}} +pub type PRPC_SECURITY_QOS_V4_A = *mut RPC_SECURITY_QOS_V4_A; +STRUCT!{struct RPC_SECURITY_QOS_V5_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V5_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V5_W_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, + ServerSecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V5_W = *mut RPC_SECURITY_QOS_V5_W; +STRUCT!{struct RPC_SECURITY_QOS_V5_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V5_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V5_A_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, + ServerSecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V5_A = *mut RPC_SECURITY_QOS_V5_A; +pub const RPC_PROTSEQ_TCP: ::c_ulong = 0x1; +pub const RPC_PROTSEQ_NMP: ::c_ulong = 0x2; +pub const RPC_PROTSEQ_LRPC: ::c_ulong = 0x3; +pub const RPC_PROTSEQ_HTTP: ::c_ulong = 0x4; +pub const RPC_BHT_OBJECT_UUID_VALID: ::c_ulong = 0x1; +pub const RPC_BHO_NONCAUSAL: ::c_ulong = 0x1; +pub const RPC_BHO_DONTLINGER: ::c_ulong = 0x2; +pub const RPC_BHO_EXCLUSIVE_AND_GUARANTEED: ::c_ulong = 0x4; +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_W_union { + Reserved: *mut ::c_ushort, +}} +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_W { + Version: ::c_ulong, + Flags: ::c_ulong, + ProtocolSequence: ::c_ulong, + NetworkAddress: *mut ::c_ushort, + StringEndpoint: *mut ::c_ushort, + u1: RPC_BINDING_HANDLE_TEMPLATE_V1_W_union, + ObjectUuid: UUID, +}} +pub type PRPC_BINDING_HANDLE_TEMPLATE_V1_W = *mut RPC_BINDING_HANDLE_TEMPLATE_V1_W; +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_A_union { + Reserved: *mut ::c_uchar, +}} +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_A { + Version: ::c_ulong, + Flags: ::c_ulong, + ProtocolSequence: ::c_ulong, + NetworkAddress: *mut ::c_uchar, + StringEndpoint: *mut ::c_uchar, + u1: RPC_BINDING_HANDLE_TEMPLATE_V1_A_union, + ObjectUuid: UUID, +}} +pub type PRPC_BINDING_HANDLE_TEMPLATE_V1_A = *mut RPC_BINDING_HANDLE_TEMPLATE_V1_A; +STRUCT!{struct RPC_BINDING_HANDLE_SECURITY_V1_W { + Version: ::c_ulong, + ServerPrincName: *mut ::c_ushort, + AuthnLevel: ::c_ulong, + AuthnSvc: ::c_ulong, + AuthIdentity: *mut SEC_WINNT_AUTH_IDENTITY_W, + SecurityQos: *mut RPC_SECURITY_QOS, +}} +pub type PRPC_BINDING_HANDLE_SECURITY_V1_W = *mut RPC_BINDING_HANDLE_SECURITY_V1_W; +STRUCT!{struct RPC_BINDING_HANDLE_SECURITY_V1_A { + Version: ::c_ulong, + ServerPrincName: *mut ::c_uchar, + AuthnLevel: ::c_ulong, + AuthnSvc: ::c_ulong, + AuthIdentity: *mut SEC_WINNT_AUTH_IDENTITY_A, + SecurityQos: *mut RPC_SECURITY_QOS, +}} +pub type PRPC_BINDING_HANDLE_SECURITY_V1_A = *mut RPC_BINDING_HANDLE_SECURITY_V1_A; +STRUCT!{struct RPC_BINDING_HANDLE_OPTIONS_V1 { + Version: ::c_ulong, + Flags: ::c_ulong, + ComTimeout: ::c_ulong, + CallTimeout: ::c_ulong, +}} +pub type PRPC_BINDING_HANDLE_OPTIONS_V1 = *mut RPC_BINDING_HANDLE_OPTIONS_V1; +ENUM!{enum RPC_HTTP_REDIRECTOR_STAGE { + RPCHTTP_RS_REDIRECT = 1, + RPCHTTP_RS_ACCESS_1, + RPCHTTP_RS_SESSION, + RPCHTTP_RS_ACCESS_2, + RPCHTTP_RS_INTERFACE, +}} +pub type RPC_NEW_HTTP_PROXY_CHANNEL = Option<unsafe extern "system" fn( + RedirectorStage: RPC_HTTP_REDIRECTOR_STAGE, ServerName: RPC_WSTR, ServerPort: RPC_WSTR, + RemoteUser: RPC_WSTR, AuthType: RPC_WSTR, ResourceUuid: *mut ::c_void, + SessionId: *mut ::c_void, Interface: *mut ::c_void, Reserved: *mut ::c_void, Flags: ::c_ulong, + NewServerName: *mut RPC_WSTR, NewServerPort: *mut RPC_WSTR, +) -> ::RPC_STATUS>; +pub type RPC_HTTP_PROXY_FREE_STRING = Option<unsafe extern "system" fn(String: RPC_WSTR)>; +pub const RPC_C_AUTHZ_NONE: ::DWORD = 0; +pub const RPC_C_AUTHZ_NAME: ::DWORD = 1; +pub const RPC_C_AUTHZ_DCE: ::DWORD = 2; +pub const RPC_C_AUTHZ_DEFAULT: ::DWORD = 0xffffffff; +pub type RPC_AUTH_KEY_RETRIEVAL_FN = Option<unsafe extern "system" fn( + Arg: *mut ::c_void, ServerPrincName: RPC_WSTR, KeyVer: ::c_ulong, Key: *mut *mut ::c_void, + Status: *mut ::RPC_STATUS, +)>; +STRUCT!{struct RPC_CLIENT_INFORMATION1 { + UserName: *mut ::c_uchar, + ComputerName: *mut ::c_uchar, + Privilege: ::c_ushort, + AuthFlags: ::c_ulong, +}} +pub type PRPC_CLIENT_INFORMATION1 = *mut RPC_CLIENT_INFORMATION1; +pub type RPC_EP_INQ_HANDLE = *mut ::I_RPC_HANDLE; +pub const RPC_C_EP_ALL_ELTS: ::c_ulong = 0; +pub const RPC_C_EP_MATCH_BY_IF: ::c_ulong = 1; +pub const RPC_C_EP_MATCH_BY_OBJ: ::c_ulong = 2; +pub const RPC_C_EP_MATCH_BY_BOTH: ::c_ulong = 3; +pub const RPC_C_VERS_ALL: ::c_ulong = 1; +pub const RPC_C_VERS_COMPATIBLE: ::c_ulong = 2; +pub const RPC_C_VERS_EXACT: ::c_ulong = 3; +pub const RPC_C_VERS_MAJOR_ONLY: ::c_ulong = 4; +pub const RPC_C_VERS_UPTO: ::c_ulong = 5; +pub type RPC_MGMT_AUTHORIZATION_FN = Option<unsafe extern "system" fn( + ClientBinding: RPC_BINDING_HANDLE, RequestedMgmtOperation: ::c_ulong, + Status: *mut ::RPC_STATUS, +) -> ::c_int>; +pub const RPC_C_MGMT_INQ_IF_IDS: ::c_ulong = 0; +pub const RPC_C_MGMT_INQ_PRINC_NAME: ::c_ulong = 1; +pub const RPC_C_MGMT_INQ_STATS: ::c_ulong = 2; +pub const RPC_C_MGMT_IS_SERVER_LISTEN: ::c_ulong = 3; +pub const RPC_C_MGMT_STOP_SERVER_LISTEN: ::c_ulong = 4; +pub const RPC_IF_AUTOLISTEN: ::c_uint = 0x0001; +pub const RPC_IF_OLE: ::c_uint = 0x0002; +pub const RPC_IF_ALLOW_UNKNOWN_AUTHORITY: ::c_uint = 0x0004; +pub const RPC_IF_ALLOW_SECURE_ONLY: ::c_uint = 0x0008; +pub const RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH: ::c_uint = 0x0010; +pub const RPC_IF_ALLOW_LOCAL_ONLY: ::c_uint = 0x0020; +pub const RPC_IF_SEC_NO_CACHE: ::c_uint = 0x0040; +pub const RPC_IF_SEC_CACHE_PER_PROC: ::c_uint = 0x0080; +pub const RPC_IF_ASYNC_CALLBACK: ::c_uint = 0x0100; +pub const RPC_FW_IF_FLAG_DCOM: ::c_uint = 0x0001; +pub type RPC_INTERFACE_GROUP = *mut ::c_void; +pub type PRPC_INTERFACE_GROUP = *mut *mut ::c_void; +STRUCT!{struct RPC_ENDPOINT_TEMPLATEW { + Version: ::c_ulong, + ProtSeq: RPC_WSTR, + Endpoint: RPC_WSTR, + SecurityDescriptor: *mut ::c_void, + Backlog: ::c_ulong, +}} +pub type PRPC_ENDPOINT_TEMPLATEW = *mut RPC_ENDPOINT_TEMPLATEW; +STRUCT!{struct RPC_ENDPOINT_TEMPLATEA { + Version: ::c_ulong, + ProtSeq: RPC_CSTR, + Endpoint: RPC_CSTR, + SecurityDescriptor: *mut ::c_void, + Backlog: ::c_ulong, +}} +pub type PRPC_ENDPOINT_TEMPLATEA = *mut RPC_ENDPOINT_TEMPLATEA; +STRUCT!{struct RPC_INTERFACE_TEMPLATEA { + Version: ::c_ulong, + IfSpec: RPC_IF_HANDLE, + MgrTypeUuid: *mut UUID, + MgrEpv: *mut RPC_MGR_EPV, + Flags: ::c_uint, + MaxCalls: ::c_uint, + MaxRpcSize: ::c_uint, + IfCallback: *mut RPC_IF_CALLBACK_FN, + UuidVector: *mut UUID_VECTOR, + Annotation: RPC_CSTR, + SecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_INTERFACE_TEMPLATEA = *mut RPC_INTERFACE_TEMPLATEA; +STRUCT!{struct RPC_INTERFACE_TEMPLATEW { + Version: ::c_ulong, + IfSpec: RPC_IF_HANDLE, + MgrTypeUuid: *mut UUID, + MgrEpv: *mut RPC_MGR_EPV, + Flags: ::c_uint, + MaxCalls: ::c_uint, + MaxRpcSize: ::c_uint, + IfCallback: *mut RPC_IF_CALLBACK_FN, + UuidVector: *mut UUID_VECTOR, + Annotation: RPC_WSTR, + SecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_INTERFACE_TEMPLATEW = *mut RPC_INTERFACE_TEMPLATEW; +pub type RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN = Option<unsafe extern "system" fn( + IfGroup: RPC_INTERFACE_GROUP, IdleCallbackContext: *mut ::c_void, IsGroupIdle: ::c_ulong, +)>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/sapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/sapi.rs new file mode 100644 index 0000000..ac6ca11 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/sapi.rs @@ -0,0 +1,2431 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of sapi.h +ENUM!{enum SPDATAKEYLOCATION { + SPDKL_DefaultLocation = 0, + SPDKL_CurrentUser = 1, + SPDKL_LocalMachine = 2, + SPDKL_CurrentConfig = 5, +}} +pub const SPDUI_EngineProperties: &'static str = "EngineProperties"; +pub const SPDUI_AddRemoveWord: &'static str = "AddRemoveWord"; +pub const SPDUI_UserTraining: &'static str = "UserTraining"; +pub const SPDUI_MicTraining: &'static str = "MicTraining"; +pub const SPDUI_RecoProfileProperties: &'static str = "RecoProfileProperties"; +pub const SPDUI_AudioProperties: &'static str = "AudioProperties"; +pub const SPDUI_AudioVolume: &'static str = "AudioVolume"; +pub const SPDUI_UserEnrollment: &'static str = "UserEnrollment"; +pub const SPDUI_ShareData: &'static str = "ShareData"; +pub const SPDUI_Tutorial: &'static str = "Tutorial"; +ENUM!{enum SPSTREAMFORMAT { + SPSF_Default = -1i32 as u32, + SPSF_NoAssignedFormat = 0, + SPSF_Text = 1, + SPSF_NonStandardFormat = 2, + SPSF_ExtendedAudioFormat = 3, + SPSF_8kHz8BitMono = 4, + SPSF_8kHz8BitStereo = 5, + SPSF_8kHz16BitMono = 6, + SPSF_8kHz16BitStereo = 7, + SPSF_11kHz8BitMono = 8, + SPSF_11kHz8BitStereo = 9, + SPSF_11kHz16BitMono = 10, + SPSF_11kHz16BitStereo = 11, + SPSF_12kHz8BitMono = 12, + SPSF_12kHz8BitStereo = 13, + SPSF_12kHz16BitMono = 14, + SPSF_12kHz16BitStereo = 15, + SPSF_16kHz8BitMono = 16, + SPSF_16kHz8BitStereo = 17, + SPSF_16kHz16BitMono = 18, + SPSF_16kHz16BitStereo = 19, + SPSF_22kHz8BitMono = 20, + SPSF_22kHz8BitStereo = 21, + SPSF_22kHz16BitMono = 22, + SPSF_22kHz16BitStereo = 23, + SPSF_24kHz8BitMono = 24, + SPSF_24kHz8BitStereo = 25, + SPSF_24kHz16BitMono = 26, + SPSF_24kHz16BitStereo = 27, + SPSF_32kHz8BitMono = 28, + SPSF_32kHz8BitStereo = 29, + SPSF_32kHz16BitMono = 30, + SPSF_32kHz16BitStereo = 31, + SPSF_44kHz8BitMono = 32, + SPSF_44kHz8BitStereo = 33, + SPSF_44kHz16BitMono = 34, + SPSF_44kHz16BitStereo = 35, + SPSF_48kHz8BitMono = 36, + SPSF_48kHz8BitStereo = 37, + SPSF_48kHz16BitMono = 38, + SPSF_48kHz16BitStereo = 39, + SPSF_TrueSpeech_8kHz1BitMono = 40, + SPSF_CCITT_ALaw_8kHzMono = 41, + SPSF_CCITT_ALaw_8kHzStereo = 42, + SPSF_CCITT_ALaw_11kHzMono = 43, + SPSF_CCITT_ALaw_11kHzStereo = 44, + SPSF_CCITT_ALaw_22kHzMono = 45, + SPSF_CCITT_ALaw_22kHzStereo = 46, + SPSF_CCITT_ALaw_44kHzMono = 47, + SPSF_CCITT_ALaw_44kHzStereo = 48, + SPSF_CCITT_uLaw_8kHzMono = 49, + SPSF_CCITT_uLaw_8kHzStereo = 50, + SPSF_CCITT_uLaw_11kHzMono = 51, + SPSF_CCITT_uLaw_11kHzStereo = 52, + SPSF_CCITT_uLaw_22kHzMono = 53, + SPSF_CCITT_uLaw_22kHzStereo = 54, + SPSF_CCITT_uLaw_44kHzMono = 55, + SPSF_CCITT_uLaw_44kHzStereo = 56, + SPSF_ADPCM_8kHzMono = 57, + SPSF_ADPCM_8kHzStereo = 58, + SPSF_ADPCM_11kHzMono = 59, + SPSF_ADPCM_11kHzStereo = 60, + SPSF_ADPCM_22kHzMono = 61, + SPSF_ADPCM_22kHzStereo = 62, + SPSF_ADPCM_44kHzMono = 63, + SPSF_ADPCM_44kHzStereo = 64, + SPSF_GSM610_8kHzMono = 65, + SPSF_GSM610_11kHzMono = 66, + SPSF_GSM610_22kHzMono = 67, + SPSF_GSM610_44kHzMono = 68, + SPSF_NUM_FORMATS = 69, +}} +pub const SPREG_USER_ROOT: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech"; +pub const SPREG_LOCAL_MACHINE_ROOT: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech"; +pub const SPCAT_AUDIOOUT: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioOutput"; +pub const SPCAT_AUDIOIN: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioInput"; +pub const SPCAT_VOICES: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices"; +pub const SPCAT_RECOGNIZERS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Recognizers"; +pub const SPCAT_APPLEXICONS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AppLexicons"; +pub const SPCAT_PHONECONVERTERS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\PhoneConverters"; +pub const SPCAT_TEXTNORMALIZERS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\TextNormalizers"; +pub const SPCAT_RECOPROFILES: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech\\RecoProfiles"; +pub const SPMMSYS_AUDIO_IN_TOKEN_ID: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioInput\\TokenEnums\\MMAudioIn\\"; +pub const SPMMSYS_AUDIO_OUT_TOKEN_ID: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioOutput\\TokenEnums\\MMAudioOut\\"; +pub const SPCURRENT_USER_LEXICON_TOKEN_ID: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech\\CurrentUserLexicon"; +pub const SPCURRENT_USER_SHORTCUT_TOKEN_ID: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech\\CurrentUserShortcut"; +pub const SPTOKENVALUE_CLSID: &'static str = "CLSID"; +pub const SPTOKENKEY_FILES: &'static str = "Files"; +pub const SPTOKENKEY_UI: &'static str = "UI"; +pub const SPTOKENKEY_ATTRIBUTES: &'static str = "Attributes"; +pub const SPTOKENKEY_RETAINEDAUDIO: &'static str = "SecondsPerRetainedAudioEvent"; +pub const SPTOKENKEY_AUDIO_LATENCY_WARNING: &'static str = "LatencyWarningThreshold"; +pub const SPTOKENKEY_AUDIO_LATENCY_TRUNCATE: &'static str = "LatencyTruncateThreshold"; +pub const SPTOKENKEY_AUDIO_LATENCY_UPDATE_INTERVAL: &'static str = "LatencyUpdateInterval"; +pub const SPVOICECATEGORY_TTSRATE: &'static str = "DefaultTTSRate"; +pub const SPPROP_RESOURCE_USAGE: &'static str = "ResourceUsage"; +pub const SPPROP_HIGH_CONFIDENCE_THRESHOLD: &'static str = "HighConfidenceThreshold"; +pub const SPPROP_NORMAL_CONFIDENCE_THRESHOLD: &'static str = "NormalConfidenceThreshold"; +pub const SPPROP_LOW_CONFIDENCE_THRESHOLD: &'static str = "LowConfidenceThreshold"; +pub const SPPROP_RESPONSE_SPEED: &'static str = "ResponseSpeed"; +pub const SPPROP_COMPLEX_RESPONSE_SPEED: &'static str = "ComplexResponseSpeed"; +pub const SPPROP_ADAPTATION_ON: &'static str = "AdaptationOn"; +pub const SPPROP_PERSISTED_BACKGROUND_ADAPTATION: &'static str = "PersistedBackgroundAdaptation"; +pub const SPPROP_PERSISTED_LANGUAGE_MODEL_ADAPTATION: &'static str = "PersistedLanguageModelAdaptation"; +pub const SPPROP_UX_IS_LISTENING: &'static str = "UXIsListening"; +pub const SPTOPIC_SPELLING: &'static str = "Spelling"; +pub const SPWILDCARD: &'static str = "..."; +pub const SPDICTATION: &'static str = "*"; +pub const SPINFDICTATION: &'static str = "*+"; +pub const SPREG_SAFE_USER_TOKENS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\UserTokens"; +pub const SP_LOW_CONFIDENCE: i32 = -1; +pub const SP_NORMAL_CONFIDENCE: i32 = 0; +pub const SP_HIGH_CONFIDENCE: i32 = 1; +pub const DEFAULT_WEIGHT: i32 = 1; +pub const SP_MAX_WORD_LENGTH: i32 = 128; +pub const SP_MAX_PRON_LENGTH: i32 = 384; +pub const SP_EMULATE_RESULT: i32 = 0x40000000; +RIDL!( +interface ISpNotifyCallback(ISpNotifyCallbackVtbl) { + fn NotifyCallback(&mut self, wParam: ::WPARAM, lParam: ::LPARAM) -> ::HRESULT +} +); +pub type SPNOTIFYCALLBACK = unsafe extern "system" fn(wParam: ::WPARAM, lParam: ::LPARAM); +RIDL!( +interface ISpNotifySource(ISpNotifySourceVtbl): IUnknown(IUnknownVtbl) { + fn SetNotifySink(&mut self, pNotifySink: *mut ISpNotifySink) -> ::HRESULT, + fn SetNotifyWindowMessage( + &mut self, hWnd: ::HWND, Msg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn SetNotifyCallbackFunction( + &mut self, pfnCallback: SPNOTIFYCALLBACK, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn SetNotifyCallbackInterface( + &mut self, pSpCallback: *mut ISpNotifyCallback, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn SetNotifyWin32Event(&mut self) -> ::HRESULT, + fn WaitForNotifyEvent(&mut self, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn GetNotifyEventHandle(&mut self) -> ::HANDLE +} +); +RIDL!( +interface ISpNotifySink(ISpNotifySinkVtbl): IUnknown(IUnknownVtbl) { + fn Notify(&mut self) -> ::HRESULT +} +); +RIDL!( +interface ISpNotifyTranslator(ISpNotifyTranslatorVtbl): ISpNotifySink(ISpNotifySinkVtbl) { + fn InitWindowMessage( + &mut self, hWnd: ::HWND, Msg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn InitCallback( + &mut self, pfnCallback: SPNOTIFYCALLBACK, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn InitSpNotifyCallback( + &mut self, pSpCallback: *mut ISpNotifyCallback, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn InitWin32Event(&mut self, hEvent: ::HANDLE, fCloseHandleOnRelease: ::BOOL) -> ::HRESULT, + fn Wait(&mut self, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn GetEventHandle(&mut self) -> ::HANDLE +} +); +RIDL!( +interface ISpDataKey(ISpDataKeyVtbl): IUnknown(IUnknownVtbl) { + fn SetData( + &mut self, pszValueName: ::LPCWSTR, cbData: ::ULONG, pData: *const ::BYTE + ) -> ::HRESULT, + fn GetData( + &mut self, pszValueName: ::LPCWSTR, pcbData: *mut ::ULONG, pData: *mut ::BYTE + ) -> ::HRESULT, + fn SetStringValue(&mut self, pszValueName: ::LPCWSTR, pszValue: ::LPCWSTR) -> ::HRESULT, + fn GetStringValue(&mut self, pszValueName: ::LPCWSTR, ppszValue: *mut ::LPWSTR) -> ::HRESULT, + fn SetDWORD(&mut self, pszValueName: ::LPCWSTR, dwValue: ::DWORD) -> ::HRESULT, + fn GetDWORD(&mut self, pszValueName: ::LPCWSTR, pdwValue: *mut ::DWORD) -> ::HRESULT, + fn OpenKey(&mut self, pszSubKeyName: ::LPCWSTR, ppSubKey: *mut *mut ISpDataKey) -> ::HRESULT, + fn CreateKey(&mut self, pszSubKey: ::LPCWSTR, ppSubKey: *mut *mut ISpDataKey) -> ::HRESULT, + fn DeleteKey(&mut self, pszSubKey: ::LPCWSTR) -> ::HRESULT, + fn DeleteValue(&mut self, pszValueName: ::LPCWSTR) -> ::HRESULT, + fn EnumKeys(&mut self, Index: ::ULONG, ppszSubKeyName: *mut ::LPWSTR) -> ::HRESULT, + fn EnumValues(&mut self, Index: ::ULONG, ppszValueName: *mut ::LPWSTR) -> ::HRESULT +} +); +RIDL!( +interface ISpRegDataKey(ISpRegDataKeyVtbl): ISpDataKey(ISpDataKeyVtbl) { + fn SetKey(&mut self, hkey: ::HKEY, fReadOnly: ::BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectTokenCategory(ISpObjectTokenCategoryVtbl): ISpDataKey(ISpDataKeyVtbl) { + fn SetId(&mut self, pszCategoryId: ::LPCWSTR, fCreateIfNotExist: ::BOOL) -> ::HRESULT, + fn GetId(&mut self, ppszCoMemCategoryId: *mut ::LPWSTR) -> ::HRESULT, + fn GetDataKey( + &mut self, spdkl: SPDATAKEYLOCATION, pppDataKey: *mut *mut ISpDataKey + ) -> ::HRESULT, + fn EnumTokens( + &mut self, pzsReqAttribs: ::LPCWSTR, pszOptAttribs: ::LPCWSTR, + ppEnum: *mut *mut IEnumSpObjectTokens + ) -> ::HRESULT, + fn SetDefaultTokenId(&mut self, pszTokenId: ::LPCWSTR) -> ::HRESULT, + fn GetDefaultTokenId(&mut self, ppszCoMemTokenId: *mut ::LPWSTR) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectToken(ISpObjectTokenVtbl): ISpDataKey(ISpDataKeyVtbl) { + fn SetId( + &mut self, pszCategoryId: ::LPCWSTR, pszTokenId: ::LPCWSTR, fCreateIfNotExist: ::BOOL + ) -> ::HRESULT, + fn GetId(&mut self, ppszCoMemTokenId: *mut ::LPWSTR) -> ::HRESULT, + fn GetCategory(&mut self, ppTokenCategory: *mut *mut ISpObjectTokenCategory) -> ::HRESULT, + fn CreateInstance( + &mut self, pUnkOuter: *mut ::IUnknown, dwClsContext: ::DWORD, riid: ::REFIID, + ppvObject: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetStorageFileName( + &mut self, clsidCaller: ::REFCLSID, pszValueName: ::LPCWSTR, + pszFileNameSpecifier: ::LPCWSTR, nFolder: ::ULONG, ppszFilePath: *mut ::LPWSTR + ) -> ::HRESULT, + fn RemoveStorageFileName(&mut self, pszKeyName: ::LPCWSTR, fDeleteFile: ::BOOL) -> ::HRESULT, + fn Remove(&mut self, pclsidCaller: *const ::CLSID) -> ::HRESULT, + fn IsUISupported( + &mut self, pszTypeOfUI: ::LPCWSTR, pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, + punkObject: *mut ::IUnknown, pfSupported: *mut ::BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hwndParent: ::HWND, pszTitle: ::LPCWSTR, pszTypeOfUI: ::LPCWSTR, + pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, punkObject: *mut ::IUnknown + ) -> ::HRESULT, + fn MatchesAttributes(&mut self, pszAttributes: ::LPCWSTR, pfMatches: *mut ::BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectTokenInit(ISpObjectTokenInitVtbl): ISpObjectToken(ISpObjectTokenVtbl) { + fn InitFromDataKey( + &mut self, pszCategoryId: ::LPCWSTR, pszTokenId: ::LPCWSTR, pDataKey: *mut ISpDataKey + ) -> ::HRESULT +} +); +RIDL!( +interface IEnumSpObjectTokens(IEnumSpObjectTokensVtbl): IUnknown(IUnknownVtbl) { + fn Next( + &mut self, celt: ::ULONG, pelt: *mut *mut ISpObjectToken, pceltFetched: *mut ::ULONG + ) -> ::HRESULT, + fn Skip(&mut self, celt: ::ULONG) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn Clone(&mut self, ppEnum: *mut *mut IEnumSpObjectTokens) -> ::HRESULT, + fn Item(&mut self, Index: ::ULONG, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn GetCount(&mut self, pCount: *mut ::ULONG) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectWithToken(ISpObjectWithTokenVtbl): IUnknown(IUnknownVtbl) { + fn SetObjectToken(&mut self, pToken: *mut ISpObjectToken) -> ::HRESULT, + fn GetObjectToken(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT +} +); +RIDL!( +interface ISpResourceManager(ISpResourceManagerVtbl): IServiceProvider(IServiceProviderVtbl) { + fn SetObject(&mut self, guidServiceId: ::REFGUID, pUnkObject: *mut ::IUnknown) -> ::HRESULT, + fn GetObject( + &mut self, guidServiceId: ::REFGUID, ObjectCLSID: ::REFCLSID, ObjectIID: ::REFIID, + fReleaseWhenLastExternalRefReleased: ::BOOL, ppObject: *mut *mut ::c_void + ) -> ::HRESULT +} +); +ENUM!{enum SPEVENTLPARAMTYPE { + SPET_LPARAM_IS_UNDEFINED = 0, + SPET_LPARAM_IS_TOKEN, + SPET_LPARAM_IS_OBJECT, + SPET_LPARAM_IS_POINTER, + SPET_LPARAM_IS_STRING, +}} +ENUM!{enum SPEVENTENUM { + SPEI_UNDEFINED = 0, + SPEI_START_INPUT_STREAM = 1, + SPEI_END_INPUT_STREAM = 2, + SPEI_VOICE_CHANGE = 3, + SPEI_TTS_BOOKMARK = 4, + SPEI_WORD_BOUNDARY = 5, + SPEI_PHONEME = 6, + SPEI_SENTENCE_BOUNDARY = 7, + SPEI_VISEME = 8, + SPEI_TTS_AUDIO_LEVEL = 9, + SPEI_TTS_PRIVATE = 15, + SPEI_END_SR_STREAM = 34, + SPEI_SOUND_START = 35, + SPEI_SOUND_END = 36, + SPEI_PHRASE_START = 37, + SPEI_RECOGNITION = 38, + SPEI_HYPOTHESIS = 39, + SPEI_SR_BOOKMARK = 40, + SPEI_PROPERTY_NUM_CHANGE = 41, + SPEI_PROPERTY_STRING_CHANGE = 42, + SPEI_FALSE_RECOGNITION = 43, + SPEI_INTERFERENCE = 44, + SPEI_REQUEST_UI = 45, + SPEI_RECO_STATE_CHANGE = 46, + SPEI_ADAPTATION = 47, + SPEI_START_SR_STREAM = 48, + SPEI_RECO_OTHER_CONTEXT = 49, + SPEI_SR_AUDIO_LEVEL = 50, + SPEI_SR_RETAINEDAUDIO = 51, + SPEI_SR_PRIVATE = 52, + SPEI_ACTIVE_CATEGORY_CHANGED = 53, + SPEI_RESERVED5 = 54, + SPEI_RESERVED6 = 55, + SPEI_RESERVED1 = 30, + SPEI_RESERVED2 = 33, + SPEI_RESERVED3 = 63, +}} +pub const SPEI_MIN_TTS: SPEVENTENUM = SPEI_START_INPUT_STREAM; +pub const SPEI_MAX_TTS: SPEVENTENUM = SPEI_TTS_PRIVATE; +pub const SPEI_MIN_SR: SPEVENTENUM = SPEI_END_SR_STREAM; +pub const SPEI_MAX_SR: SPEVENTENUM = SPEI_RESERVED6; +pub const SPFEI_FLAGCHECK: u64 = (1 << SPEI_RESERVED1.0 as u64) | (1 << SPEI_RESERVED2.0 as u64); +pub const SPFEI_ALL_TTS_EVENTS: u64 = 0x000000000000FFFE | SPFEI_FLAGCHECK; +pub const SPFEI_ALL_SR_EVENTS: u64 = 0x003FFFFC00000000 | SPFEI_FLAGCHECK; +pub const SPFEI_ALL_EVENTS: u64 = 0xEFFFFFFFFFFFFFFF; +#[inline] +pub fn SPFEI(SPEI_ord: u64) -> u64 { + (1 << SPEI_ord) | SPFEI_FLAGCHECK +} +STRUCT!{struct SPEVENT { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + wParam: ::WPARAM, + lParam: ::LPARAM, +}} +STRUCT!{struct SPSERIALIZEDEVENT { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + SerializedwParam: ::ULONG, + SerializedlParam: ::LONG, +}} +STRUCT!{struct SPSERIALIZEDEVENT64 { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + SerializedwParam: ::ULONGLONG, + SerializedlParam: ::LONGLONG, +}} +STRUCT!{struct SPEVENTEX { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + wParam: ::WPARAM, + lParam: ::LPARAM, + ullAudioTimeOffset: ::ULONGLONG, +}} +ENUM!{enum SPINTERFERENCE { + SPINTERFERENCE_NONE = 0, + SPINTERFERENCE_NOISE = 1, + SPINTERFERENCE_NOSIGNAL = 2, + SPINTERFERENCE_TOOLOUD = 3, + SPINTERFERENCE_TOOQUIET = 4, + SPINTERFERENCE_TOOFAST = 5, + SPINTERFERENCE_TOOSLOW = 6, + SPINTERFERENCE_LATENCY_WARNING = 7, + SPINTERFERENCE_LATENCY_TRUNCATE_BEGIN = 8, + SPINTERFERENCE_LATENCY_TRUNCATE_END = 9, +}} +FLAGS!{enum SPENDSRSTREAMFLAGS { + SPESF_NONE = 0, + SPESF_STREAM_RELEASED = 1 << 0, + SPESF_EMULATED = 1 << 1, +}} +FLAGS!{enum SPVFEATURE { + SPVFEATURE_STRESSED = 1 << 0, + SPVFEATURE_EMPHASIS = 1 << 1, +}} +ENUM!{enum SPVISEMES { + SP_VISEME_0 = 0, + SP_VISEME_1, + SP_VISEME_2, + SP_VISEME_3, + SP_VISEME_4, + SP_VISEME_5, + SP_VISEME_6, + SP_VISEME_7, + SP_VISEME_8, + SP_VISEME_9, + SP_VISEME_10, + SP_VISEME_11, + SP_VISEME_12, + SP_VISEME_13, + SP_VISEME_14, + SP_VISEME_15, + SP_VISEME_16, + SP_VISEME_17, + SP_VISEME_18, + SP_VISEME_19, + SP_VISEME_20, + SP_VISEME_21, +}} +STRUCT!{struct SPEVENTSOURCEINFO { + ullEventInterest: ::ULONGLONG, + ullQueuedInterest: ::ULONGLONG, + ulCount: ::ULONG, +}} +RIDL!( +interface ISpEventSource(ISpEventSourceVtbl): ISpNotifySource(ISpNotifySourceVtbl) { + fn SetInterest( + &mut self, ullEventInterest: ::ULONGLONG, ullQueuedInterest: ::ULONGLONG + ) -> ::HRESULT, + fn GetEvents( + &mut self, ulCount: ::ULONG, pEventArray: *mut SPEVENT, pulFetched: *mut ::ULONG + ) -> ::HRESULT, + fn GetInfo(&mut self, pInfo: *mut SPEVENTSOURCEINFO) -> ::HRESULT +} +); +RIDL!( +interface ISpEventSource2(ISpEventSource2Vtbl): ISpEventSource(ISpEventSourceVtbl) { + fn GetEventsEx( + &mut self, ulCount: ::ULONG, pEventArray: *mut SPEVENTEX, pulFetched: *mut ::ULONG + ) -> ::HRESULT +} +); +RIDL!( +interface ISpEventSink(ISpEventSinkVtbl): IUnknown(IUnknownVtbl) { + fn AddEvents(&mut self, pEventArray: *const SPEVENT, ulCount: ::ULONG) -> ::HRESULT, + fn GetEventInterest(&mut self, pullEventInterest: *mut ::ULONGLONG) -> ::HRESULT +} +); +RIDL!( +interface ISpStreamFormat(ISpStreamFormatVtbl): IStream(IStreamVtbl) { + fn GetFormat( + &mut self, pguidFormatId: *mut ::GUID, ppCoMemWaveFormatEx: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT +} +); +ENUM!{enum SPFILEMODE { + SPFM_OPEN_READONLY = 0, + SPFM_OPEN_READWRITE = 1, + SPFM_CREATE = 2, + SPFM_CREATE_ALWAYS = 3, + SPFM_NUM_MODES = 4, +}} +RIDL!( +interface ISpStream(ISpStreamVtbl): ISpStreamFormat(ISpStreamFormatVtbl) { + fn SetBaseStream( + &mut self, pStream: *mut ::IStream, rguidFormat: ::REFGUID, + pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetBaseStream(&mut self, ppStream: *mut *mut ::IStream) -> ::HRESULT, + fn BindToFile( + &mut self, pszFileName: ::LPCWSTR, eMode: SPFILEMODE, pFormatId: *const ::GUID, + pWaveFormatEx: *const ::WAVEFORMATEX, ullEventInterest: ::ULONGLONG + ) -> ::HRESULT, + fn Close(&mut self) -> ::HRESULT +} +); +RIDL!( +interface ISpStreamFormatConverter(ISpStreamFormatConverterVtbl) + : ISpStreamFormat(ISpStreamFormatVtbl) { + fn SetBaseStream( + &mut self, pStream: *mut ISpStreamFormat, fSetFormatToBaseStreamFormat: ::BOOL, + fWriteToBaseStream: ::BOOL + ) -> ::HRESULT, + fn GetBaseStream(&mut self, ppStream: *mut *mut ISpStreamFormat) -> ::HRESULT, + fn SetFormat( + &mut self, rguidFormatIdOfConvertedStream: ::REFGUID, + pWaveFormatExOfConvertedStream: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn ResetSeekPosition(&mut self) -> ::HRESULT, + fn ScaleConvertedToBaseOffset( + &mut self, ullOffsetConvertedStream: ::ULONGLONG, pullOffsetBaseStream: *mut ::ULONGLONG + ) -> ::HRESULT, + fn ScaleBaseToConvertedOffset( + &mut self, ullOffsetBaseStream: ::ULONGLONG, pullOffsetConvertedStream: *mut ::ULONGLONG + ) -> ::HRESULT +} +); +ENUM!{enum SPAUDIOSTATE { + SPAS_CLOSED = 0, + SPAS_STOP = 1, + SPAS_PAUSE = 2, + SPAS_RUN = 3, +}} +STRUCT!{struct SPAUDIOSTATUS { + cbFreeBuffSpace: ::LONG, + cbNonBlockingIO: ::ULONG, + State: SPAUDIOSTATE, + CurSeekPos: ::ULONGLONG, + CurDevicePos: ::ULONGLONG, + dwAudioLevel: ::DWORD, + dwReserved2: ::DWORD, +}} +STRUCT!{struct SPAUDIOBUFFERINFO { + ulMsMinNotification: ::ULONG, + ulMsBufferSize: ::ULONG, + ulMsEventBias: ::ULONG, +}} +RIDL!( +interface ISpAudio(ISpAudioVtbl): ISpStreamFormat(ISpStreamFormatVtbl) { + fn SetState(&mut self, NewState: SPAUDIOSTATE, ullReserved: ::ULONGLONG) -> ::HRESULT, + fn SetFormat( + &mut self, rguidFmtId: ::REFGUID, pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetStatus(&mut self, pStatus: *mut SPAUDIOSTATUS) -> ::HRESULT, + fn SetBufferInfo(&mut self, pBuffInfo: *const SPAUDIOBUFFERINFO) -> ::HRESULT, + fn GetBufferInfo(&mut self, pBuffInfo: *mut SPAUDIOBUFFERINFO) -> ::HRESULT, + fn GetDefaultFormat( + &mut self, pFormatId: *mut ::GUID, ppCoMemWaveFormatEx: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn EventHandle(&mut self) -> ::HANDLE, + fn GetVolumeLevel(&mut self, pLevel: *mut ::ULONG) -> ::HRESULT, + fn SetVolumeLevel(&mut self, Level: ::ULONG) -> ::HRESULT, + fn GetBufferNotifySize(&mut self, pcbSize: *mut ::ULONG) -> ::HRESULT, + fn SetBufferNotifySize(&mut self, cbSize: ::ULONG) -> ::HRESULT +} +); +RIDL!( +interface ISpMMSysAudio(ISpMMSysAudioVtbl): ISpAudio(ISpAudioVtbl) { + fn GetDeviceId(&mut self, puDeviceId: *mut ::UINT) -> ::HRESULT, + fn SetDeviceId(&mut self, uDeviceId: ::UINT) -> ::HRESULT, + fn GetMMHandle(&mut self, pHandle: *mut *mut ::c_void) -> ::HRESULT, + fn GetLineId(&mut self, puLineId: *mut ::UINT) -> ::HRESULT, + fn SetLineId(&mut self, uLineId: ::UINT) -> ::HRESULT +} +); +RIDL!( +interface ISpTranscript(ISpTranscriptVtbl): IUnknown(IUnknownVtbl) { + fn GetTranscript(&mut self, ppszTranscript: *mut ::LPWSTR) -> ::HRESULT, + fn AppendTranscript(&mut self, pszTranscript: ::LPCWSTR) -> ::HRESULT +} +); +FLAGS!{enum SPDISPLYATTRIBUTES { + SPAF_ONE_TRAILING_SPACE = 0x2, + SPAF_TWO_TRAILING_SPACES = 0x4, + SPAF_CONSUME_LEADING_SPACES = 0x8, + SPAF_BUFFER_POSITION = 0x10, + SPAF_ALL = 0x1f, + SPAF_USER_SPECIFIED = 0x80, +}} +pub type SPPHONEID = ::WCHAR; +pub type PSPPHONEID = ::LPWSTR; +pub type PCSPPHONEID = ::LPCWSTR; +STRUCT!{struct SPPHRASEELEMENT { + ulAudioTimeOffset: ::ULONG, + ulAudioSizeTime: ::ULONG, + ulAudioStreamOffset: ::ULONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedStreamOffset: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + pszDisplayText: ::LPCWSTR, + pszLexicalForm: ::LPCWSTR, + pszPronunciation: *const SPPHONEID, + bDisplayAttributes: ::BYTE, + RequiredConfidence: ::c_char, + ActualConfidence: ::c_char, + Reserved: ::BYTE, + SREngineConfidence: ::c_float, +}} +STRUCT!{struct SPPHRASERULE { + pszName: ::LPCWSTR, + ulId: ::ULONG, + ulFirstElement: ::ULONG, + ulCountOfElements: ::ULONG, + pNextSibling: *const SPPHRASERULE, + pFirstChild: *const SPPHRASERULE, + SREngineConfidence: ::c_float, + Confidence: ::c_char, +}} +ENUM!{enum SPPHRASEPROPERTYUNIONTYPE { + SPPPUT_UNUSED = 0, + SPPPUT_ARRAY_INDEX, +}} +STRUCT!{struct SPPHRASEPROPERTY { + pszName: ::LPCWSTR, + bType: ::BYTE, + bReserved: ::BYTE, + usArrayIndex: u16, + pszValue: ::LPCWSTR, + vValue: ::VARIANT, + ulFirstElement: ::ULONG, + ulCountOfElements: ::ULONG, + pNextSibling: *const SPPHRASEPROPERTY, + pFirstChild: *const SPPHRASEPROPERTY, + SREngineConfidence: ::c_float, + Confidence: ::c_char, +}} +UNION!(SPPHRASEPROPERTY, bType, ulId, ulId_mut, ::ULONG); +STRUCT!{struct SPPHRASEREPLACEMENT { + bDisplayAttributes: ::BYTE, + pszReplacementText: ::LPCWSTR, + ulFirstElement: ::ULONG, + ulCountOfElements: ::ULONG, +}} +STRUCT!{struct SPSEMANTICERRORINFO { + ulLineNumber: ::ULONG, + pszScriptLine: ::LPWSTR, + pszSource: ::LPWSTR, + pszDescription: ::LPWSTR, + hrResultCode: ::HRESULT, +}} +ENUM!{enum SPSEMANTICFORMAT { + SPSMF_SAPI_PROPERTIES = 0, + SPSMF_SRGS_SEMANTICINTERPRETATION_MS = 1, + SPSMF_SRGS_SAPIPROPERTIES = 2, + SPSMF_UPS = 4, + SPSMF_SRGS_SEMANTICINTERPRETATION_W3C = 8, +}} +STRUCT!{struct SPPHRASE_50 { + cbSize: ::ULONG, + LangID: ::WORD, + wHomophoneGroupId: ::WORD, + ullGrammarID: ::ULONGLONG, + ftStartTime: ::ULONGLONG, + ullAudioStreamPosition: ::ULONGLONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + ulAudioSizeTime: ::ULONG, + Rule: ::SPPHRASERULE, + pProperties: *const ::SPPHRASEPROPERTY, + pElements: *const ::SPPHRASEELEMENT, + cReplacements: ::ULONG, + pReplacements: *const ::SPPHRASEREPLACEMENT, + SREngineID: ::GUID, + ulSREnginePrivateDataSize: ::ULONG, + pSREnginePrivateData: *const ::BYTE, +}} +STRUCT!{struct SPPHRASE_53 { + cbSize: ::ULONG, + LangID: ::WORD, + wHomophoneGroupId: ::WORD, + ullGrammarID: ::ULONGLONG, + ftStartTime: ::ULONGLONG, + ullAudioStreamPosition: ::ULONGLONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + ulAudioSizeTime: ::ULONG, + Rule: ::SPPHRASERULE, + pProperties: *const ::SPPHRASEPROPERTY, + pElements: *const ::SPPHRASEELEMENT, + cReplacements: ::ULONG, + pReplacements: *const ::SPPHRASEREPLACEMENT, + SREngineID: ::GUID, + ulSREnginePrivateDataSize: ::ULONG, + pSREnginePrivateData: *const ::BYTE, + pSML: ::LPWSTR, + pSemanticErrorInfo: *mut SPSEMANTICERRORINFO, +}} +STRUCT!{struct SPPHRASE { + cbSize: ::ULONG, + LangID: ::WORD, + wHomophoneGroupId: ::WORD, + ullGrammarID: ::ULONGLONG, + ftStartTime: ::ULONGLONG, + ullAudioStreamPosition: ::ULONGLONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + ulAudioSizeTime: ::ULONG, + Rule: ::SPPHRASERULE, + pProperties: *const ::SPPHRASEPROPERTY, + pElements: *const ::SPPHRASEELEMENT, + cReplacements: ::ULONG, + pReplacements: *const ::SPPHRASEREPLACEMENT, + SREngineID: ::GUID, + ulSREnginePrivateDataSize: ::ULONG, + pSREnginePrivateData: *const ::BYTE, + pSML: ::LPWSTR, + pSemanticErrorInfo: *mut SPSEMANTICERRORINFO, + SemanticTagFormat: SPSEMANTICFORMAT, +}} +STRUCT!{struct SPSERIALIZEDPHRASE { + ulSerializedSize: ::ULONG, +}} +STRUCT!{struct SPRULE { + pszRuleName: ::LPCWSTR, + ulRuleId: ::ULONG, + dwAttributes: ::DWORD, +}} +FLAGS!{enum SPVALUETYPE { + SPDF_PROPERTY = 0x1, + SPDF_REPLACEMENT = 0x2, + SPDF_RULE = 0x4, + SPDF_DISPLAYTEXT = 0x8, + SPDF_LEXICALFORM = 0x10, + SPDF_PRONUNCIATION = 0x20, + SPDF_AUDIO = 0x40, + SPDF_ALTERNATES = 0x80, + SPDF_ALL = 0xff, +}} +STRUCT!{struct SPBINARYGRAMMAR { + ulTotalSerializedSize: ::ULONG, +}} +ENUM!{enum SPPHRASERNG { + SPPR_ALL_ELEMENTS = -1i32 as u32, +}} +pub const SP_GETWHOLEPHRASE: SPPHRASERNG = SPPR_ALL_ELEMENTS; +pub const SPRR_ALL_ELEMENTS: SPPHRASERNG = SPPR_ALL_ELEMENTS; +DECLARE_HANDLE!(SPSTATEHANDLE, SPSTATEHANDLE__); +FLAGS!{enum SPRECOEVENTFLAGS { + SPREF_AutoPause = 1 << 0, + SPREF_Emulated = 1 << 1, + SPREF_SMLTimeout = 1 << 2, + SPREF_ExtendableParse = 1 << 3, + SPREF_ReSent = 1 << 4, + SPREF_Hypothesis = 1 << 5, + SPREF_FalseRecognition = 1 << 6, +}} +ENUM!{enum SPPARTOFSPEECH { + SPPS_NotOverriden = -1i32 as u32, + SPPS_Unknown = 0, + SPPS_Noun = 0x1000, + SPPS_Verb = 0x2000, + SPPS_Modifier = 0x3000, + SPPS_Function = 0x4000, + SPPS_Interjection = 0x5000, + SPPS_Noncontent = 0x6000, + SPPS_LMA = 0x7000, + SPPS_SuppressWord = 0xf000, +}} +FLAGS!{enum SPLEXICONTYPE { + eLEXTYPE_USER = 1 << 0, + eLEXTYPE_APP = 1 << 1, + eLEXTYPE_VENDORLEXICON = 1 << 2, + eLEXTYPE_LETTERTOSOUND = 1 << 3, + eLEXTYPE_MORPHOLOGY = 1 << 4, + eLEXTYPE_RESERVED4 = 1 << 5, + eLEXTYPE_USER_SHORTCUT = 1 << 6, + eLEXTYPE_RESERVED6 = 1 << 7, + eLEXTYPE_RESERVED7 = 1 << 8, + eLEXTYPE_RESERVED8 = 1 << 9, + eLEXTYPE_RESERVED9 = 1 << 10, + eLEXTYPE_RESERVED10 = 1 << 11, + eLEXTYPE_PRIVATE1 = 1 << 12, + eLEXTYPE_PRIVATE2 = 1 << 13, + eLEXTYPE_PRIVATE3 = 1 << 14, + eLEXTYPE_PRIVATE4 = 1 << 15, + eLEXTYPE_PRIVATE5 = 1 << 16, + eLEXTYPE_PRIVATE6 = 1 << 17, + eLEXTYPE_PRIVATE7 = 1 << 18, + eLEXTYPE_PRIVATE8 = 1 << 19, + eLEXTYPE_PRIVATE9 = 1 << 20, + eLEXTYPE_PRIVATE10 = 1 << 21, + eLEXTYPE_PRIVATE11 = 1 << 22, + eLEXTYPE_PRIVATE12 = 1 << 23, + eLEXTYPE_PRIVATE13 = 1 << 24, + eLEXTYPE_PRIVATE14 = 1 << 25, + eLEXTYPE_PRIVATE15 = 1 << 26, + eLEXTYPE_PRIVATE16 = 1 << 27, + eLEXTYPE_PRIVATE17 = 1 << 28, + eLEXTYPE_PRIVATE18 = 1 << 29, + eLEXTYPE_PRIVATE19 = 1 << 30, + eLEXTYPE_PRIVATE20 = 1 << 31, +}} +FLAGS!{enum SPWORDTYPE { + eWORDTYPE_ADDED = 1 << 0, + eWORDTYPE_DELETED = 1 << 1, +}} +FLAGS!{enum SPPRONUNCIATIONFLAGS { + ePRONFLAG_USED = 1 << 0, +}} +STRUCT!{struct SPWORDPRONUNCIATION { + pNextWordPronunciation: *mut SPWORDPRONUNCIATION, + eLexiconType: SPLEXICONTYPE, + LangID: ::WORD, + wPronunciationFlags: ::WORD, + ePartOfSpeech: SPPARTOFSPEECH, + szPronunciation: [SPPHONEID; 1], +}} +STRUCT!{struct SPWORDPRONUNCIATIONLIST { + ulSize: ::ULONG, + pvBuffer: *mut ::BYTE, + pFirstWordPronunciation: *mut SPWORDPRONUNCIATION, +}} +STRUCT!{struct SPWORD { + pNextWord: *mut SPWORD, + LangID: ::WORD, + wReserved: ::WORD, + eWordType: SPWORDTYPE, + pszWord: ::LPWSTR, + pFirstWordPronunciation: *mut SPWORDPRONUNCIATION, +}} +STRUCT!{struct SPWORDLIST { + ulSize: ::ULONG, + pvBuffer: *mut ::BYTE, + pFirstWord: *mut SPWORD, +}} +RIDL!( +interface ISpLexicon(ISpLexiconVtbl): IUnknown(IUnknownVtbl) { + fn GetPronunciations( + &mut self, pszWord: ::LPCWSTR, LangID: ::WORD, dwFlags: ::DWORD, + pWordPronunciationList: *mut SPWORDPRONUNCIATIONLIST + ) -> ::HRESULT, + fn AddPronunciation( + &mut self, pszWord: ::LPCWSTR, LangID: ::WORD, ePartOfSpeech: SPPARTOFSPEECH, + pszPronunciation: PCSPPHONEID + ) -> ::HRESULT, + fn RemovePronunciation( + &mut self, pszWord: ::LPCWSTR, LangID: ::WORD, ePartOfSpeech: SPPARTOFSPEECH, + pszPronunciation: PCSPPHONEID + ) -> ::HRESULT, + fn GetGeneration(&mut self, pdwGeneration: *mut ::DWORD) -> ::HRESULT, + fn GetGenerationChange( + &mut self, dwFlags: ::DWORD, pdwGeneration: *mut ::DWORD, pWordList: *mut SPWORDLIST + ) -> ::HRESULT, + fn GetWords( + &mut self, dwFlags: ::DWORD, pdwGeneration: *mut ::DWORD, pdwCookie: *mut ::DWORD, + pWordList: *mut SPWORDLIST + ) -> ::HRESULT +} +); +RIDL!( +interface ISpContainerLexicon(ISpContainerLexiconVtbl): ISpLexicon(ISpLexiconVtbl) { + fn AddLexicon(&mut self, pAddLexicon: *mut ISpLexicon, dwFlags: ::DWORD) -> ::HRESULT +} +); +ENUM!{enum SPSHORTCUTTYPE { + SPSHT_NotOverriden = -1i32 as u32, + SPSHT_Unknown = 0, + SPSHT_EMAIL = 0x1000, + SPSHT_OTHER = 0x2000, + SPPS_RESERVED1 = 0x3000, + SPPS_RESERVED2 = 0x4000, + SPPS_RESERVED3 = 0x5000, + SPPS_RESERVED4 = 0xf000, +}} +STRUCT!{struct SPSHORTCUTPAIR { + pNextSHORTCUTPAIR: *mut SPSHORTCUTPAIR, + LangID: ::WORD, + shType: SPSHORTCUTTYPE, + pszDisplay: ::LPWSTR, + pszSpoken: ::LPWSTR, +}} +STRUCT!{struct SPSHORTCUTPAIRLIST { + ulSize: ::ULONG, + pvBuffer: *mut ::BYTE, + pFirstShortcutPair: *mut SPSHORTCUTPAIR, +}} +RIDL!( +interface ISpShortcut(ISpShortcutVtbl): IUnknown(IUnknownVtbl) { + fn AddShortcut( + &mut self, pszDisplay: ::LPCWSTR, LangID: ::WORD, pszSpoken: ::LPCWSTR, + shType: SPSHORTCUTTYPE + ) -> ::HRESULT, + fn RemoveShortcut( + &mut self, pszDisplay: ::LPCWSTR, LangID: ::WORD, pszSpoken: ::LPCWSTR, + shType: SPSHORTCUTTYPE + ) -> ::HRESULT, + fn GetShortcuts( + &mut self, LangId: ::WORD, pShortcutpairList: *mut SPSHORTCUTPAIRLIST + ) -> ::HRESULT, + fn GetGeneration(&mut self, pdwGeneration: *mut ::DWORD) -> ::HRESULT, + fn GetWordsFromGenerationChange( + &mut self, pdwGeneration: *mut ::DWORD, pWordList: *mut SPWORDLIST + ) -> ::HRESULT, + fn GetWords( + &mut self, pdwGeneration: *mut ::DWORD, pdwCookie: *mut ::DWORD, pWordList: *mut SPWORDLIST + ) -> ::HRESULT, + fn GetShortcutsForGeneration( + &mut self, pdwGeneration: *mut ::DWORD, pdwCookie: *mut ::DWORD, + pShortcutpairList: *mut SPSHORTCUTPAIRLIST + ) -> ::HRESULT, + fn GetGenerationChange( + &mut self, pdwGeneration: *mut ::DWORD, pShortcutpairList: *mut SPSHORTCUTPAIRLIST + ) -> ::HRESULT +} +); +RIDL!( +interface ISpPhoneConverter(ISpPhoneConverterVtbl): ISpObjectWithToken(ISpObjectWithTokenVtbl) { + fn PhoneToId(&mut self, pszPhone: ::LPCWSTR, pId: *mut SPPHONEID) -> ::HRESULT, + fn IdToPhone(&mut self, pId: PCSPPHONEID, pszPhone: *mut ::WCHAR) -> ::HRESULT +} +); +RIDL!( +interface ISpPhoneticAlphabetConverter(ISpPhoneticAlphabetConverterVtbl): IUnknown(IUnknownVtbl) { + fn GetLangId(&mut self, pLangID: *mut ::WORD) -> ::HRESULT, + fn SetLangId(&mut self, LangID: *mut ::WORD) -> ::HRESULT, + fn SAPI2UPS( + &mut self, pszSAPIId: *const SPPHONEID, pszUPSId: *mut SPPHONEID, cMaxLength: ::DWORD + ) -> ::HRESULT, + fn UPS2SAPI( + &mut self, pszUPSId: *const SPPHONEID, pszSAPIId: *mut SPPHONEID, cMaxLength: ::DWORD + ) -> ::HRESULT, + fn GetMaxConvertLength( + &mut self, cSrcLength: ::DWORD, bSAPI2UPS: ::BOOL, pcMaxDestLength: *mut ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface ISpPhoneticAlphabetSelection(ISpPhoneticAlphabetSelectionVtbl): IUnknown(IUnknownVtbl) { + fn IsAlphabetUPS(&mut self, pfIsUPS: *mut ::BOOL) -> ::HRESULT, + fn SetAlphabetToUPS(&mut self, fForceUPS: ::BOOL) -> ::HRESULT +} +); +STRUCT!{struct SPVPITCH { + MiddleAdj: ::c_long, + RangeAdj: ::c_long, +}} +ENUM!{enum SPVACTIONS { + SPVA_Speak = 0, + SPVA_Silence, + SPVA_Pronounce, + SPVA_Bookmark, + SPVA_SpellOut, + SPVA_Section, + SPVA_ParseUnknownTag, +}} +STRUCT!{struct SPVCONTEXT { + pCategory: ::LPCWSTR, + pBefore: ::LPCWSTR, + pAfter: ::LPCWSTR, +}} +STRUCT!{struct SPVSTATE { + eAction: SPVACTIONS, + LangID: ::WORD, + wReserved: ::WORD, + EmphAdj: ::c_long, + RateAdj: ::c_long, + Volume: ::ULONG, + PitchAdj: SPVPITCH, + SilenceMSecs: ::ULONG, + pPhoneIds: *mut SPPHONEID, + ePartOfSpeech: SPPARTOFSPEECH, + Context: SPVCONTEXT, +}} +ENUM!{enum SPRUNSTATE { + SPRS_DONE = 1 << 0, + SPRS_IS_SPEAKING = 1 << 1, +}} +ENUM!{enum SPVLIMITS { + SPMIN_VOLUME = 0, + SPMAX_VOLUME = 100, + SPMIN_RATE = -10i32 as u32, + SPMAX_RATE = 10, +}} +ENUM!{enum SPVPRIORITY { + SPVPRI_NORMAL = 0, + SPVPRI_ALERT = 1 << 0, + SPVPRI_OVER = 1 << 1, +}} +STRUCT!{struct SPVOICESTATUS { + ulCurrentStream: ::ULONG, + ulLastStreamQueued: ::ULONG, + hrLastResult: ::HRESULT, + dwRunningState: ::DWORD, + ulInputWordPos: ::ULONG, + ulInputWordLen: ::ULONG, + ulInputSentPos: ::ULONG, + ulInputSentLen: ::ULONG, + lBookmarkId: ::LONG, + PhonemeId: SPPHONEID, + VisemeId: SPVISEMES, + dwReserved1: ::DWORD, + dwReserved2: ::DWORD, +}} +FLAGS!{enum SPEAKFLAGS { + SPF_DEFAULT = 0, + SPF_ASYNC = 1 << 0, + SPF_PURGEBEFORESPEAK = 1 << 1, + SPF_IS_FILENAME = 1 << 2, + SPF_IS_XML = 1 << 3, + SPF_IS_NOT_XML = 1 << 4, + SPF_PERSIST_XML = 1 << 5, + SPF_NLP_SPEAK_PUNC = 1 << 6, + SPF_PARSE_SAPI = 1 << 7, + SPF_PARSE_SSML = 1 << 8, +}} +pub const SPF_PARSE_AUTODETECT: SPEAKFLAGS = SPF_DEFAULT; +pub const SPF_NLP_MASK: SPEAKFLAGS = SPF_NLP_SPEAK_PUNC; +pub const SPF_PARSE_MASK: i32 = SPF_PARSE_SAPI.0 as i32 | SPF_PARSE_SSML.0 as i32; +pub const SPF_VOICE_MASK: i32 = + SPF_ASYNC.0 as i32 | SPF_PURGEBEFORESPEAK.0 as i32 | SPF_IS_FILENAME.0 as i32 | SPF_IS_XML.0 as i32 | + SPF_IS_NOT_XML.0 as i32 | SPF_NLP_MASK.0 as i32 | SPF_PERSIST_XML.0 as i32 | SPF_PARSE_MASK; +pub const SPF_UNUSED_FLAGS: i32 = !SPF_VOICE_MASK; +RIDL!( +interface ISpVoice(ISpVoiceVtbl): ISpEventSource(ISpEventSourceVtbl) { + fn SetOutput(&mut self, pUnkOutput: *mut ::IUnknown, fAllowFormatChanges: ::BOOL) -> ::HRESULT, + fn GetOutputObjectToken(&mut self, ppObjectToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn GetOutputStream(&mut self, ppStream: *mut *mut ISpStreamFormat) -> ::HRESULT, + fn Pause(&mut self) -> ::HRESULT, + fn Resume(&mut self) -> ::HRESULT, + fn SetVoice(&mut self, pToken: *mut ISpObjectToken) -> ::HRESULT, + fn GetVoice(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn Speak( + &mut self, pwcs: ::LPCWSTR, dwFlags: ::DWORD, pulStreamNumber: *mut ::ULONG + ) -> ::HRESULT, + fn SpeakStream( + &mut self, pStream: *mut ::IStream, dwFlags: ::DWORD, pulStreamNumber: *mut ::ULONG + ) -> ::HRESULT, + fn GetStatus( + &mut self, pStatus: *mut SPVOICESTATUS, ppszLastBookmark: *mut ::LPWSTR + ) -> ::HRESULT, + fn Skip( + &mut self, pItemType: ::LPCWSTR, lNumItems: ::c_long, pulNumSkipped: *mut ::ULONG + ) -> ::HRESULT, + fn SetPriority(&mut self, ePriority: SPVPRIORITY) -> ::HRESULT, + fn GetPriority(&mut self, pePriority: *mut SPVPRIORITY) -> ::HRESULT, + fn SetAlertBoundary(&mut self, eBoundary: SPEVENTENUM) -> ::HRESULT, + fn GetAlertBoundary(&mut self, peBoundary: *mut SPEVENTENUM) -> ::HRESULT, + fn SetRate(&mut self, RateAdjust: ::c_long) -> ::HRESULT, + fn GetRate(&mut self, pRateAdjust: *mut ::c_long) -> ::HRESULT, + fn SetVolume(&mut self, usVolume: ::USHORT) -> ::HRESULT, + fn GetVolume(&mut self, pusVolume: *mut ::USHORT) -> ::HRESULT, + fn WaitUntilDone(&mut self, msTimeout: ::ULONG) -> ::HRESULT, + fn SetSyncSpeakTimeout(&mut self, msTimeout: ::ULONG) -> ::HRESULT, + fn GetSyncSpeakTimeout(&mut self, pmsTimeout: *mut ::ULONG) -> ::HRESULT, + fn SpeakCompleteEvent(&mut self) -> ::HANDLE, + fn IsUISupported( + &mut self, pszTypeOfUI: ::LPCWSTR, pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, + pfSupported: *mut ::BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hwndParent: ::HWND, pszTitle: ::LPCWSTR, pszTypeOfUI: ::LPCWSTR, + pvExtraData: *mut ::c_void, cbExtraData: ::ULONG + ) -> ::HRESULT +} +); +DEFINE_GUID!( + UuidOfISpVoice, + 0x6C44DF74, 0x72B9, 0x4992, 0xA1, 0xEC, 0xEF, 0x99, 0x6E, 0x04, 0x22, 0xD4 +); +RIDL!( +interface ISpPhrase(ISpPhraseVtbl): IUnknown(IUnknownVtbl) { + fn GetPhrase(&mut self, ppCoMemPhrase: *mut *mut SPPHRASE) -> ::HRESULT, + fn GetSerializedPhrase(&mut self, ppCoMemPhrase: *mut *mut SPSERIALIZEDPHRASE) -> ::HRESULT, + fn GetText( + &mut self, ulStart: ::ULONG, ulCount: ::ULONG, fUseTextReplacements: ::BOOL, + ppszCoMemText: *mut ::LPWSTR, pbDisplayAttributes: *mut ::BYTE + ) -> ::HRESULT, + fn Discard(&mut self, dwValueTypes: ::DWORD) -> ::HRESULT +} +); +RIDL!( +interface ISpPhraseAlt(ISpPhraseAltVtbl): ISpPhrase(ISpPhraseVtbl) { + fn GetAltInfo( + &mut self, pParent: *mut *mut ISpPhrase, pulStartElementInParent: *mut ::ULONG, + pcElementsInParent: *mut ::ULONG, pcElementsInAlt: *mut ::ULONG + ) -> ::HRESULT, + fn Commit(&mut self) -> ::HRESULT +} +); +ENUM!{enum SPXMLRESULTOPTIONS { + SPXRO_SML = 0, + SPXRO_Alternates_SML = 1, +}} +RIDL!( +interface ISpPhrase2(ISpPhrase2Vtbl): ISpPhrase(ISpPhraseVtbl) { + fn GetXMLResult( + &mut self, ppszCoMemXMLResult: *mut ::LPWSTR, Options: SPXMLRESULTOPTIONS + ) -> ::HRESULT, + fn GetXMLErrorInfo(&mut self, pSemanticErrorInfo: *mut SPSEMANTICERRORINFO) -> ::HRESULT, + fn GetAudio( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, ppStream: *mut *mut ISpStreamFormat + ) -> ::HRESULT +} +); +STRUCT!{struct SPRECORESULTTIMES { + ftStreamTime: ::FILETIME, + ullLength: ::ULONGLONG, + dwTickCount: ::DWORD, + ullStart: ::ULONGLONG, +}} +STRUCT!{struct SPSERIALIZEDRESULT { + ulSerializedSize: ::ULONG, +}} +RIDL!( +interface ISpRecoResult(ISpRecoResultVtbl): ISpPhrase(ISpPhraseVtbl) { + fn GetResultTimes(&mut self, pTimes: *mut SPRECORESULTTIMES) -> ::HRESULT, + fn GetAlternates( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, ulRequestCount: ::ULONG, + ppPhrases: *mut *mut ISpPhraseAlt, pcPhrasesReturned: *mut ::ULONG + ) -> ::HRESULT, + fn GetAudio( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, ppStream: *mut *mut ISpStreamFormat + ) -> ::HRESULT, + fn SpeakAudio( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, dwFlags: ::DWORD, + pulStreamNumber: *mut ::ULONG + ) -> ::HRESULT, + fn Serialize(&mut self, ppCoMemSerializedResult: *mut *mut SPSERIALIZEDRESULT) -> ::HRESULT, + fn ScaleAudio( + &mut self, pAudioFormatId: *const ::GUID, pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetRecoContext(&mut self, ppRecoContext: *mut *mut ISpRecoContext) -> ::HRESULT +} +); +FLAGS!{enum SPCOMMITFLAGS { + SPCF_NONE = 0, + SPCF_ADD_TO_USER_LEXICON = 1 << 0, + SPCF_DEFINITE_CORRECTION = 1 << 1, +}} +RIDL!( +interface ISpRecoResult2(ISpRecoResult2Vtbl): ISpRecoResult(ISpRecoResultVtbl) { + fn CommitAlternate( + &mut self, pPhraseAlt: *mut ISpPhraseAlt, ppNewResult: *mut *mut ISpRecoResult + ) -> ::HRESULT, + fn CommitText( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, pszCorrectedData: ::LPCWSTR, + eCommitFlags: ::DWORD + ) -> ::HRESULT, + fn SetTextFeedback(&mut self, pszFeedback: ::LPCWSTR, fSuccessful: ::BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpXMLRecoResult(ISpXMLRecoResultVtbl): ISpRecoResult(ISpRecoResultVtbl) { + fn GetXMLResult( + &mut self, ppszCoMemXMLResult: *mut ::LPWSTR, Options: SPXMLRESULTOPTIONS + ) -> ::HRESULT, + fn GetXMLErrorInfo(&mut self, pSemanticErrorInfo: *mut SPSEMANTICERRORINFO) -> ::HRESULT +} +); +STRUCT!{struct SPTEXTSELECTIONINFO { + ulStartActiveOffset: ::ULONG, + cchActiveChars: ::ULONG, + ulStartSelection: ::ULONG, + cchSelection: ::ULONG, +}} +ENUM!{enum SPWORDPRONOUNCEABLE { + SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE = 0, + SPWP_UNKNOWN_WORD_PRONOUNCEABLE = 1, + SPWP_KNOWN_WORD_PRONOUNCEABLE = 2, +}} +ENUM!{enum SPGRAMMARSTATE { + SPGS_DISABLED = 0, + SPGS_ENABLED = 1, + SPGS_EXCLUSIVE = 3, +}} +ENUM!{enum SPCONTEXTSTATE { + SPCS_DISABLED = 0, + SPCS_ENABLED = 1, +}} +ENUM!{enum SPRULESTATE { + SPRS_INACTIVE = 0, + SPRS_ACTIVE = 1, + SPRS_ACTIVE_WITH_AUTO_PAUSE = 3, + SPRS_ACTIVE_USER_DELIMITED = 4, +}} +pub const SP_STREAMPOS_ASAP: ::INT = 0; +pub const SP_STREAMPOS_REALTIME: ::INT = -1; +pub const SPRULETRANS_TEXTBUFFER: SPSTATEHANDLE = -1isize as SPSTATEHANDLE; +pub const SPRULETRANS_WILDCARD: SPSTATEHANDLE = -2isize as SPSTATEHANDLE; +pub const SPRULETRANS_DICTATION: SPSTATEHANDLE = -3isize as SPSTATEHANDLE; +ENUM!{enum SPGRAMMARWORDTYPE { + SPWT_DISPLAY = 0, + SPWT_LEXICAL = 1, + SPWT_PRONUNCIATION = 2, + SPWT_LEXICAL_NO_SPECIAL_CHARS = 3, +}} +STRUCT!{struct SPPROPERTYINFO { + pszName: ::LPCWSTR, + ulId: ::ULONG, + pszValue: ::LPCWSTR, + vValue: ::VARIANT, +}} +FLAGS!{enum SPCFGRULEATTRIBUTES { + SPRAF_TopLevel = 1 << 0, + SPRAF_Active = 1 << 1, + SPRAF_Export = 1 << 2, + SPRAF_Import = 1 << 3, + SPRAF_Interpreter = 1 << 4, + SPRAF_Dynamic = 1 << 5, + SPRAF_Root = 1 << 6, + SPRAF_AutoPause = 1 << 16, + SPRAF_UserDelimited = 1 << 17, +}} +RIDL!( +interface ISpGrammarBuilder(ISpGrammarBuilderVtbl): IUnknown(IUnknownVtbl) { + fn ResetGrammar(&mut self, NewLanguage: ::WORD) -> ::HRESULT, + fn GetRule( + &mut self, pszRuleName: ::LPCWSTR, dwRuleId: ::DWORD, dwAttributes: ::DWORD, + fCreateIfNotExist: ::BOOL, phInitialState: *mut SPSTATEHANDLE + ) -> ::HRESULT, + fn ClearRule(&mut self, hState: SPSTATEHANDLE) -> ::HRESULT, + fn CreateNewState(&mut self, hState: SPSTATEHANDLE, phState: *mut SPSTATEHANDLE) -> ::HRESULT, + fn AddWordTransition( + &mut self, hFromState: SPSTATEHANDLE, hToState: SPSTATEHANDLE, psz: ::LPCWSTR, + pszSeparators: ::LPCWSTR, eWordType: SPGRAMMARWORDTYPE, Weight: ::c_float, + pPropInfo: *const SPPROPERTYINFO + ) -> ::HRESULT, + fn AddRuleTransition( + &mut self, hFromState: SPSTATEHANDLE, hToState: SPSTATEHANDLE, hRule: SPSTATEHANDLE, + Weight: ::c_float, pPropInfo: *const SPPROPERTYINFO + ) -> ::HRESULT, + fn AddResource( + &mut self, hRuleState: SPSTATEHANDLE, pszResourceName: ::LPCWSTR, + pszResourceValue: ::LPCWSTR + ) -> ::HRESULT, + fn Commit(&mut self, dwReserved: ::DWORD) -> ::HRESULT +} +); +ENUM!{enum SPLOADOPTIONS { + SPLO_STATIC = 0, + SPLO_DYNAMIC = 1, +}} +RIDL!( +interface ISpRecoGrammar(ISpRecoGrammarVtbl): ISpGrammarBuilder(ISpGrammarBuilderVtbl) { + fn GetGrammarId(&mut self, pullGrammarId: *mut ::ULONGLONG) -> ::HRESULT, + fn GetRecoContext(&mut self, ppRecoCtxt: *mut *mut ISpRecoContext) -> ::HRESULT, + fn LoadCmdFromFile(&mut self, pszFileName: ::LPCWSTR, Options: SPLOADOPTIONS) -> ::HRESULT, + fn LoadCmdFromObject( + &mut self, rcid: ::REFCLSID, pszGrammarName: ::LPCWSTR, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn LoadCmdFromResource( + &mut self, hModule: ::HMODULE, pszResourceName: ::LPCWSTR, pszResourceType: ::LPCWSTR, + wLanguage: ::WORD, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn LoadCmdFromMemory( + &mut self, pGrammar: *const SPBINARYGRAMMAR, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn LoadCmdFromProprietaryGrammar( + &mut self, rguidParam: ::REFGUID, pszStringParam: ::LPCWSTR, pvDataPrarm: *const ::c_void, + cbDataSize: ::ULONG, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn SetRuleState( + &mut self, pszName: ::LPCWSTR, pReserved: *mut ::c_void, NewState: SPRULESTATE + ) -> ::HRESULT, + fn SetRuleIdState(&mut self, ulRuleId: ::ULONG, NewState: SPRULESTATE) -> ::HRESULT, + fn LoadDictation(&mut self, pszTopicName: ::LPCWSTR, Options: SPLOADOPTIONS) -> ::HRESULT, + fn UnloadDictation(&mut self) -> ::HRESULT, + fn SetDictationState(&mut self, NewState: SPRULESTATE) -> ::HRESULT, + fn SetWordSequenceData( + &mut self, pText: *const ::WCHAR, cchText: ::ULONG, pInfo: *const SPTEXTSELECTIONINFO + ) -> ::HRESULT, + fn SetTextSelection(&mut self, pInfo: *const SPTEXTSELECTIONINFO) -> ::HRESULT, + fn IsPronounceable( + &mut self, pszWord: ::LPCWSTR, pWordPronounceable: *mut SPWORDPRONOUNCEABLE + ) -> ::HRESULT, + fn SetGrammarState(&mut self, eGrammarState: SPGRAMMARSTATE) -> ::HRESULT, + fn SaveCmd(&mut self, pStream: *mut ::IStream, ppszCoMemErrorText: *mut ::LPWSTR) -> ::HRESULT, + fn GetGrammarState(&mut self, peGrammarState: *mut SPGRAMMARSTATE) -> ::HRESULT +} +); +ENUM!{enum SPMATCHINGMODE { + AllWords = 0, + Subsequence = 1, + OrderedSubset = 3, + SubsequenceContentRequired = 5, + OrderedSubsetContentRequired = 7, +}} +ENUM!{enum PHONETICALPHABET { + PA_Ipa = 0, + PA_Ups = 1, + PA_Sapi = 2, +}} +RIDL!( +interface ISpGrammarBuilder2(ISpGrammarBuilder2Vtbl): IUnknown(IUnknownVtbl) { + fn AddTextSubset( + &mut self, hFromState: SPSTATEHANDLE, hToState: SPSTATEHANDLE, psz: ::LPCWSTR, + eMatchMode: SPMATCHINGMODE + ) -> ::HRESULT, + fn SetPhoneticAlphabet(&mut self, phoneticALphabet: PHONETICALPHABET) -> ::HRESULT +} +); +RIDL!( +interface ISpRecoGrammar2(ISpRecoGrammar2Vtbl): IUnknown(IUnknownVtbl) { + fn GetRules(&mut self, ppCoMemRules: *mut *mut SPRULE, puNumRules: *mut ::UINT) -> ::HRESULT, + fn LoadCmdFromFile2( + &mut self, pszFileName: ::LPCWSTR, Options: SPLOADOPTIONS, pszSharingUri: ::LPCWSTR, + pszBaseUri: ::LPCWSTR + ) -> ::HRESULT, + fn LoadCmdFromMemory2( + &mut self, pGrammar: *const SPBINARYGRAMMAR, Options: SPLOADOPTIONS, + pszSharingUri: ::LPCWSTR, pszBaseUri: ::LPCWSTR + ) -> ::HRESULT, + fn SetRulePriority( + &mut self, pszRuleName: ::LPCWSTR, ulRuleId: ::ULONG, nRulePriority: ::c_int + ) -> ::HRESULT, + fn SetRuleWeight( + &mut self, pszRuleName: ::LPCWSTR, ulRuleId: ::ULONG, flWeight: ::c_float + ) -> ::HRESULT, + fn SetDictationWeight(&mut self, flWeight: ::c_float) -> ::HRESULT, + fn SetGrammarLoader(&mut self, pLoader: *mut ISpeechResourceLoader) -> ::HRESULT, + fn SetSMLSecurityManager( + &mut self, pSMLSecurityManager: *mut ::IInternetSecurityManager + ) -> ::HRESULT +} +); +RIDL!( +interface ISpeechResourceLoader(ISpeechResourceLoaderVtbl): IDispatch(IDispatchVtbl) { + fn LoadResource( + &mut self, bstrResourceUri: ::BSTR, fAlwaysReload: ::VARIANT_BOOL, + pStream: *mut *mut ::IUnknown, pbstrMIMEType: *mut ::BSTR, pfModified: *mut ::VARIANT_BOOL, + pbstrRedirectUrl: *mut ::BSTR + ) -> ::HRESULT, + fn GetLocalCopy( + &mut self, bstrResourceUri: ::BSTR, pbstrLocalPath: *mut ::BSTR, + pbstrMIMEType: *mut ::BSTR, pbstrRedirectUrl: *mut ::BSTR + ) -> ::HRESULT, + fn ReleaseLocalCopy(&mut self, pbstrLocalPath: ::BSTR) -> ::HRESULT +} +); +STRUCT!{nodebug struct SPRECOCONTEXTSTATUS { + eInterference: SPINTERFERENCE, + szRequestTypeOfUI: [::WCHAR; 255], + dwReserved1: ::DWORD, + dwReserved2: ::DWORD, +}} +FLAGS!{enum SPBOOKMARKOPTIONS { + SPBO_NONE = 0, + SPBO_PAUSE = 1 << 0, + SPBO_AHEAD = 1 << 1, + SPBO_TIME_UNITS = 1 << 2, +}} +FLAGS!{enum SPAUDIOOPTIONS { + SPAO_NONE = 0, + SPAO_RETAIN_AUDIO = 1 << 0, +}} +RIDL!( +interface ISpRecoContext(ISpRecoContextVtbl): ISpEventSource(ISpEventSourceVtbl) { + fn GetRecognizer(&mut self, ppRecognizer: *mut *mut ISpRecognizer) -> ::HRESULT, + fn CreateGrammer( + &mut self, ullGrammarId: ::ULONGLONG, ppGrammar: *mut *mut ISpRecoGrammar + ) -> ::HRESULT, + fn GetStatus(&mut self, pState: *mut SPRECOCONTEXTSTATUS) -> ::HRESULT, + fn GetMaxAlternates(&mut self, pcAlternates: *mut ::ULONG) -> ::HRESULT, + fn SetMaxAlternates(&mut self, cAlternates: ::ULONG) -> ::HRESULT, + fn SetAudioOptions( + &mut self, Options: SPAUDIOOPTIONS, pAudioFormatId: *const ::GUID, + pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetAudioOptions( + &mut self, pOptions: *mut SPAUDIOOPTIONS, pAudioFormatId: *mut ::GUID, + ppCoMemWFEX: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn DeserializeResult( + &mut self, pSerializedResult: *const SPSERIALIZEDRESULT, ppResult: *mut *mut ISpRecoResult + ) -> ::HRESULT, + fn Bookmark( + &mut self, Options: SPBOOKMARKOPTIONS, ullStreamPosition: ::ULONGLONG, + lparamEvent: ::LPARAM + ) -> ::HRESULT, + fn SetAdaptionData(&mut self, pAdaptionData: ::LPCWSTR, cch: ::ULONG) -> ::HRESULT, + fn Pause(&mut self, dwReserved: ::DWORD) -> ::HRESULT, + fn Resume(&mut self, dwReserved: ::DWORD) -> ::HRESULT, + fn SetVoice(&mut self, pVoice: *mut ISpVoice, fAllowFormatChanges: ::BOOL) -> ::HRESULT, + fn GetVoice(&mut self, ppVoice: *mut *mut ISpVoice) -> ::HRESULT, + fn SetVoicePurgeEvent(&mut self, ullEventIntereset: ::ULONGLONG) -> ::HRESULT, + fn GetVoicePurgeEvent(&mut self, pullEventIntereset: *mut ::ULONGLONG) -> ::HRESULT, + fn SetContextState(&mut self, eContextState: SPCONTEXTSTATE) -> ::HRESULT, + fn GetContextState(&mut self, peContextState: *mut SPCONTEXTSTATE) -> ::HRESULT +} +); +FLAGS!{enum SPGRAMMAROPTIONS { + SPGO_SAPI = 0x1, + SPGO_SRGS = 0x2, + SPGO_UPS = 0x4, + SPGO_SRGS_MS_SCRIPT = 0x8, + SPGO_SRGS_W3C_SCRIPT = 0x100, + SPGO_SRGS_STG_SCRIPT = 0x200, + SPGO_SRGS_SCRIPT = + SPGO_SRGS.0 | SPGO_SRGS_MS_SCRIPT.0 | SPGO_SRGS_W3C_SCRIPT.0 | + SPGO_SRGS_STG_SCRIPT.0, + SPGO_FILE = 0x10, + SPGO_HTTP = 0x20, + SPGO_RES = 0x40, + SPGO_OBJECT = 0x80, + SPGO_DEFAULT = 0x3fb, + SPGO_ALL = 0x3ff, +}} +FLAGS!{enum SPADAPTATIONSETTINGS { + SPADS_Default = 0, + SPADS_CurrentRecognizer = 0x1, + SPADS_RecoProfile = 0x2, + SPADS_Immediate = 0x4, + SPADS_Reset = 0x8, + SPADS_HighVolumeDataSource = 0x10, +}} +ENUM!{enum SPADAPTATIONRELEVANCE { + SPAR_Unknown = 0, + SPAR_Low = 1, + SPAR_Medium = 2, + SPAR_High = 3, +}} +RIDL!( +interface ISpRecoContext2(ISpRecoContext2Vtbl): IUnknown(IUnknownVtbl) { + fn SetGrammarOptions(&mut self, eGrammarOptions: ::DWORD) -> ::HRESULT, + fn GetGrammarOptions(&mut self, peGrammarOptions: *mut ::DWORD) -> ::HRESULT, + fn SetAdaptationData2( + &mut self, pAdaptationData: ::LPCWSTR, cch: ::ULONG, pTopicName: ::LPCWSTR, + eAdaptationSettings: ::DWORD, eRelevance: SPADAPTATIONRELEVANCE + ) -> ::HRESULT +} +); +RIDL!( +interface ISpProperties(ISpPropertiesVtbl): IUnknown(IUnknownVtbl) { + fn SetPropertyNum(&mut self, pName: ::LPCWSTR, lValue: ::LONG) -> ::HRESULT, + fn GetPropertyNum(&mut self, pName: ::LPCWSTR, plValue: *mut ::LONG) -> ::HRESULT, + fn SetPropertyString(&mut self, pName: ::LPCWSTR, pValue: ::LPCWSTR) -> ::HRESULT, + fn GetPropertyString(&mut self, pName: ::LPCWSTR, ppCoMemValue: *mut ::LPWSTR) -> ::HRESULT +} +); +STRUCT!{struct SPRECOGNIZERSTATUS { + AudioStatus: SPAUDIOSTATUS, + ullRecognitionStreamPos: ::ULONGLONG, + ulStreamNumber: ::ULONG, + ulNumActive: ::ULONG, + clsidEngine: ::CLSID, + cLangIDs: ::ULONG, + aLangID: [::WORD; 20], + ullRecognitionStreamTime: ::ULONGLONG, +}} +ENUM!{enum SPWAVEFORMATTYPE { + SPWF_INPUT = 0, + SPWF_SRENGINE = 1, +}} +pub type SPSTREAMFORMATTYPE = SPWAVEFORMATTYPE; +ENUM!{enum SPRECOSTATE { + SPRST_INACTIVE = 0, + SPRST_ACTIVE = 1, + SPRST_ACTIVE_ALWAYS = 2, + SPRST_INACTIVE_WITH_PURGE = 3, + SPRST_NUM_STATES = 4, +}} +RIDL!( +interface ISpRecognizer(ISpRecognizerVtbl): ISpProperties(ISpPropertiesVtbl) { + fn SetRecognizer(&mut self, pRecognizer: *mut ISpObjectToken) -> ::HRESULT, + fn GetRecognizer(&mut self, ppRecognizer: *mut *mut ISpObjectToken) -> ::HRESULT, + fn SetInput(&mut self, pUnkInput: *mut ::IUnknown, fAllowFormatChanges: ::BOOL) -> ::HRESULT, + fn GetInputObjectToken(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn GetInputStream(&mut self, ppStream: *mut *mut ISpStreamFormat) -> ::HRESULT, + fn CreateRecoContext(&mut self, ppNewCtxt: *mut *mut ISpRecoContext) -> ::HRESULT, + fn GetRecoProfile(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn SetRecoProfile(&mut self, pToken: *mut ISpObjectToken) -> ::HRESULT, + fn IsSharedInstance(&mut self) -> ::HRESULT, + fn GetRecoState(&mut self, pState: *mut SPRECOSTATE) -> ::HRESULT, + fn SetRecoState(&mut self, NewState: SPRECOSTATE) -> ::HRESULT, + fn GetStatus(&mut self, pStatus: *mut SPRECOGNIZERSTATUS) -> ::HRESULT, + fn GetFormat( + &mut self, WaveFormatType: SPSTREAMFORMATTYPE, pFormatId: *mut ::GUID, + ppCoMemWFEX: *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn IsUISupported( + &mut self, pszTypeOfUI: ::LPCWSTR, pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, + pfSupported: *mut ::BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hwndParent: ::HWND, pszTitle: ::LPCWSTR, pszTypeOfUI: ::LPCWSTR, + pvExtraData: *mut ::c_void, cbExtraData: ::ULONG + ) -> ::HRESULT, + fn EmulateRecognition(&mut self, pPhrase: *mut ISpPhrase) -> ::HRESULT +} +); +RIDL!( +interface ISpSerializeState(ISpSerializeStateVtbl): IUnknown(IUnknownVtbl) { + fn GetSerializedState( + &mut self, ppbData: *mut *mut ::BYTE, pulSize: *mut ::ULONG, dwReserved: ::DWORD + ) -> ::HRESULT, + fn SetSerializedState( + &mut self, pbData: *mut ::BYTE, ulSize: ::ULONG, dwReserved: ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface ISpRecognizer2(ISpRecognizer2Vtbl): IUnknown(IUnknownVtbl) { + fn EmulateRecognitionEx( + &mut self, pPhrase: *mut ISpPhrase, dwCompareFlags: ::DWORD + ) -> ::HRESULT, + fn SetTrainingState( + &mut self, fDoingTraining: ::BOOL, fAdaptFromTrainingData: ::BOOL + ) -> ::HRESULT, + fn ResetAcousticModelAdaptation(&mut self) -> ::HRESULT +} +); +ENUM!{enum SPCATEGORYTYPE { + SPCT_COMMAND = 0, + SPCT_DICTATION, + SPCT_SLEEP, + SPCT_SUB_COMMAND, + SPCT_SUB_DICTATION, +}} +RIDL!( +interface ISpRecoCategory(ISpRecoCategoryVtbl): IUnknown(IUnknownVtbl) { + fn GetType(&mut self, peCategoryType: *mut SPCATEGORYTYPE) -> ::HRESULT +} +); +RIDL!( +interface ISpRecognizer3(ISpRecognizer3Vtbl): IUnknown(IUnknownVtbl) { + fn GetCategory( + &mut self, categoryType: SPCATEGORYTYPE, ppCategory: *mut *mut ISpRecoCategory + ) -> ::HRESULT, + fn SetActiveCategory(&mut self, pCategory: *mut ISpRecoCategory) -> ::HRESULT, + fn GetActiveCategory(&mut self, ppCategory: *mut *mut ISpRecoCategory) -> ::HRESULT +} +); +STRUCT!{struct SPNORMALIZATIONLIST { + ulSize: ::ULONG, + ppszzNormalizedList: *mut *mut ::WCHAR, +}} +RIDL!( +interface ISpEnginePronunciation(ISpEnginePronunciationVtbl): IUnknown(IUnknownVtbl) { + fn Normalize( + &mut self, pszWord: ::LPCWSTR, pszLeftContext: ::LPCWSTR, pszRightContext: ::LPCWSTR, + LangID: ::WORD, pNormalizationList: *mut SPNORMALIZATIONLIST + ) -> ::HRESULT, + fn GetPronunciations( + &mut self, pszWord: ::LPCWSTR, pszLeftContext: ::LPCWSTR, pszRightContext: ::LPCWSTR, + LangID: ::WORD, pEnginePronunciationList: *mut SPWORDPRONUNCIATIONLIST + ) -> ::HRESULT +} +); +STRUCT!{struct SPDISPLAYTOKEN { + pszLexical: *const ::WCHAR, + pszDisplay: *const ::WCHAR, + bDisplayAttributes: ::BYTE, +}} +STRUCT!{struct SPDISPLAYPHRASE { + ulNumTokens: ::ULONG, + pTokens: *mut SPDISPLAYTOKEN, +}} +RIDL!( +interface ISpDisplayAlternates(ISpDisplayAlternatesVtbl): IUnknown(IUnknownVtbl) { + fn GetDisplayAlternates( + &mut self, pPhrase: *const SPDISPLAYPHRASE, cRequestCount: ::ULONG, + ppCoMemPhrases: *mut *mut SPDISPLAYPHRASE, pcPhrasesReturned: *mut ::ULONG + ) -> ::HRESULT, + fn SetFullStopTrailSpace(&mut self, ulTrailSpace: ::ULONG) -> ::HRESULT +} +); +pub type SpeechLanguageId = ::c_long; +ENUM!{enum DISPID_SpeechDataKey { + DISPID_SDKSetBinaryValue = 1, + DISPID_SDKGetBinaryValue, + DISPID_SDKSetStringValue, + DISPID_SDKGetStringValue, + DISPID_SDKSetLongValue, + DISPID_SDKGetlongValue, + DISPID_SDKOpenKey, + DISPID_SDKCreateKey, + DISPID_SDKDeleteKey, + DISPID_SDKDeleteValue, + DISPID_SDKEnumKeys, + DISPID_SDKEnumValues, +}} +ENUM!{enum DISPID_SpeechObjectToken { + DISPID_SOTId = 1, + DISPID_SOTDataKey, + DISPID_SOTCategory, + DISPID_SOTGetDescription, + DISPID_SOTSetId, + DISPID_SOTGetAttribute, + DISPID_SOTCreateInstance, + DISPID_SOTRemove, + DISPID_SOTGetStorageFileName, + DISPID_SOTRemoveStorageFileName, + DISPID_SOTIsUISupported, + DISPID_SOTDisplayUI, + DISPID_SOTMatchesAttributes, +}} +ENUM!{enum SpeechDataKeyLocation { + SDKLDefaultLocation = SPDKL_DefaultLocation.0, + SDKLCurrentUser = SPDKL_CurrentUser.0, + SDKLLocalMachine = SPDKL_LocalMachine.0, + SDKLCurrentConfig = SPDKL_CurrentConfig.0, +}} +ENUM!{enum SpeechTokenContext { + STCInprocServer = ::CLSCTX_INPROC_SERVER, + STCInprocHandler = ::CLSCTX_INPROC_HANDLER, + STCLocalServer = ::CLSCTX_LOCAL_SERVER, + STCRemoteServer = ::CLSCTX_REMOTE_SERVER, + STCAll = ::CLSCTX_INPROC_SERVER | ::CLSCTX_INPROC_HANDLER | + ::CLSCTX_LOCAL_SERVER | ::CLSCTX_REMOTE_SERVER, +}} +ENUM!{enum SpeechTokenShellFolder { + STSF_AppData = 0x1a, + STSF_LocalAppData = 0x1c, + STSF_CommonAppData = 0x23, + STSF_FlagCreate = 0x8000, +}} +ENUM!{enum DISPID_SpeechObjectTokens { + DISPID_SOTsCount = 1, + DISPID_SOTsItem = ::DISPID_VALUE as u32, + DISPID_SOTs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechObjectTokenCategory { + DISPID_SOTCId = 1, + DISPID_SOTCDefault, + DISPID_SOTCSetId, + DISPID_SOTCGetDataKey, + DISPID_SOTCEnumerateTokens, +}} +ENUM!{enum SpeechAudioFormatType { + SAFTDefault = -1i32 as u32, + SAFTNoAssignedFormat = 0, + SAFTText = 1, + SAFTNonStandardFormat = 2, + SAFTExtendedAudioFormat = 3, + SAFT8kHz8BitMono = 4, + SAFT8kHz8BitStereo = 5, + SAFT8kHz16BitMono = 6, + SAFT8kHz16BitStereo = 7, + SAFT11kHz8BitMono = 8, + SAFT11kHz8BitStereo = 9, + SAFT11kHz16BitMono = 10, + SAFT11kHz16BitStereo = 11, + SAFT12kHz8BitMono = 12, + SAFT12kHz8BitStereo = 13, + SAFT12kHz16BitMono = 14, + SAFT12kHz16BitStereo = 15, + SAFT16kHz8BitMono = 16, + SAFT16kHz8BitStereo = 17, + SAFT16kHz16BitMono = 18, + SAFT16kHz16BitStereo = 19, + SAFT22kHz8BitMono = 20, + SAFT22kHz8BitStereo = 21, + SAFT22kHz16BitMono = 22, + SAFT22kHz16BitStereo = 23, + SAFT24kHz8BitMono = 24, + SAFT24kHz8BitStereo = 25, + SAFT24kHz16BitMono = 26, + SAFT24kHz16BitStereo = 27, + SAFT32kHz8BitMono = 28, + SAFT32kHz8BitStereo = 29, + SAFT32kHz16BitMono = 30, + SAFT32kHz16BitStereo = 31, + SAFT44kHz8BitMono = 32, + SAFT44kHz8BitStereo = 33, + SAFT44kHz16BitMono = 34, + SAFT44kHz16BitStereo = 35, + SAFT48kHz8BitMono = 36, + SAFT48kHz8BitStereo = 37, + SAFT48kHz16BitMono = 38, + SAFT48kHz16BitStereo = 39, + SAFTTrueSpeech_8kHz1BitMono = 40, + SAFTCCITT_ALaw_8kHzMono = 41, + SAFTCCITT_ALaw_8kHzStereo = 42, + SAFTCCITT_ALaw_11kHzMono = 43, + SAFTCCITT_ALaw_11kHzStereo = 44, + SAFTCCITT_ALaw_22kHzMono = 45, + SAFTCCITT_ALaw_22kHzStereo = 46, + SAFTCCITT_ALaw_44kHzMono = 47, + SAFTCCITT_ALaw_44kHzStereo = 48, + SAFTCCITT_uLaw_8kHzMono = 49, + SAFTCCITT_uLaw_8kHzStereo = 50, + SAFTCCITT_uLaw_11kHzMono = 51, + SAFTCCITT_uLaw_11kHzStereo = 52, + SAFTCCITT_uLaw_22kHzMono = 53, + SAFTCCITT_uLaw_22kHzStereo = 54, + SAFTCCITT_uLaw_44kHzMono = 55, + SAFTCCITT_uLaw_44kHzStereo = 56, + SAFTADPCM_8kHzMono = 57, + SAFTADPCM_8kHzStereo = 58, + SAFTADPCM_11kHzMono = 59, + SAFTADPCM_11kHzStereo = 60, + SAFTADPCM_22kHzMono = 61, + SAFTADPCM_22kHzStereo = 62, + SAFTADPCM_44kHzMono = 63, + SAFTADPCM_44kHzStereo = 64, + SAFTGSM610_8kHzMono = 65, + SAFTGSM610_11kHzMono = 66, + SAFTGSM610_22kHzMono = 67, + SAFTGSM610_44kHzMono = 68, +}} +ENUM!{enum DISPID_SpeechAudioFormat { + DISPID_SAFType = 1, + DISPID_SAFGuid, + DISPID_SAFGetWaveFormatEx, + DISPID_SAFSetWaveFormatEx, +}} +ENUM!{enum DISPID_SpeechBaseStream { + DISPID_SBSFormat = 1, + DISPID_SBSRead, + DISPID_SBSWrite, + DISPID_SBSSeek, +}} +ENUM!{enum SpeechStreamSeekPositionType { + SSSPTRelativeToStart = ::STREAM_SEEK_SET.0, + SSSPTRelativeToCurrentPosition = ::STREAM_SEEK_CUR.0, + SSSPTRelativeToEnd = ::STREAM_SEEK_END.0, +}} +ENUM!{enum DISPID_SpeechAudio { + DISPID_SAStatus = 200, + DISPID_SABufferInfo, + DISPID_SADefaultFormat, + DISPID_SAVolume, + DISPID_SABufferNotifySize, + DISPID_SAEventHandle, + DISPID_SASetState, +}} +ENUM!{enum SpeechAudioState { + SASClosed = SPAS_CLOSED.0, + SASStop = SPAS_STOP.0, + SASPause = SPAS_PAUSE.0, + SASRun = SPAS_RUN.0, +}} +ENUM!{enum DISPID_SpeechMMSysAudio { + DISPID_SMSADeviceId = 300, + DISPID_SMSALineId, + DISPID_SMSAMMHandle, +}} +ENUM!{enum DISPID_SpeechFileStream { + DISPID_SFSOpen = 100, + DISPID_SFSClose, +}} +ENUM!{enum SpeechStreamFileMode { + SSFMOpenForRead = SPFM_OPEN_READONLY.0, + SSFMOpenReadWrite = SPFM_OPEN_READWRITE.0, + SSFMCreate = SPFM_CREATE.0, + SSFMCreateForWrite = SPFM_CREATE_ALWAYS.0, +}} +ENUM!{enum DISPID_SpeechCustomStream { + DISPID_SCSBaseStream = 100, +}} +ENUM!{enum DISPID_SpeechMemoryStream { + DISPID_SMSSetData = 100, + DISPID_SMSGetData, +}} +ENUM!{enum DISPID_SpeechAudioStatus { + DISPID_SASFreeBufferSpace = 1, + DISPID_SASNonBlockingIO, + DISPID_SASState, + DISPID_SASCurrentSeekPosition, + DISPID_SASCurrentDevicePosition, +}} +ENUM!{enum DISPID_SpeechAudioBufferInfo { + DISPID_SABIMinNotification = 1, + DISPID_SABIBufferSize, + DISPID_SABIEventBias, +}} +ENUM!{enum DISPID_SpeechWaveFormatEx { + DISPID_SWFEFormatTag = 1, + DISPID_SWFEChannels, + DISPID_SWFESamplesPerSec, + DISPID_SWFEAvgBytesPerSec, + DISPID_SWFEBlockAlign, + DISPID_SWFEBitsPerSample, + DISPID_SWFEExtraData, +}} +ENUM!{enum DISPID_SpeechVoice { + DISPID_SVStatus = 1, + DISPID_SVVoice, + DISPID_SVAudioOutput, + DISPID_SVAudioOutputStream, + DISPID_SVRate, + DISPID_SVVolume, + DISPID_SVAllowAudioOuputFormatChangesOnNextSet, + DISPID_SVEventInterests, + DISPID_SVPriority, + DISPID_SVAlertBoundary, + DISPID_SVSyncronousSpeakTimeout, + DISPID_SVSpeak, + DISPID_SVSpeakStream, + DISPID_SVPause, + DISPID_SVResume, + DISPID_SVSkip, + DISPID_SVGetVoices, + DISPID_SVGetAudioOutputs, + DISPID_SVWaitUntilDone, + DISPID_SVSpeakCompleteEvent, + DISPID_SVIsUISupported, + DISPID_SVDisplayUI, +}} +ENUM!{enum SpeechVoicePriority { + SVPNormal = SPVPRI_NORMAL.0, + SVPAlert = SPVPRI_ALERT.0, + SVPOver = SPVPRI_OVER.0, +}} +FLAGS!{enum SpeechVoiceSpeakFlags { + SVSFDefault = SPF_DEFAULT.0, + SVSFlagsAsync = SPF_ASYNC.0, + SVSFPurgeBeforeSpeak = SPF_PURGEBEFORESPEAK.0, + SVSFIsFilename = SPF_IS_FILENAME.0, + SVSFIsXML = SPF_IS_XML.0, + SVSFIsNotXML = SPF_IS_NOT_XML.0, + SVSFPersistXML = SPF_PERSIST_XML.0, + SVSFNLPSpeakPunc = SPF_NLP_SPEAK_PUNC.0, + SVSFParseSapi = SPF_PARSE_SAPI.0, + SVSFParseSsml = SPF_PARSE_SSML.0, + SVSFParseMask = SPF_PARSE_MASK as u32, + SVSFVoiceMask = SPF_VOICE_MASK as u32, + SVSFUnusedFlags = SPF_UNUSED_FLAGS as u32, +}} +pub const SVSFParseAutodetect: SpeechVoiceSpeakFlags = SVSFDefault; +pub const SVSFNLPMask: SpeechVoiceSpeakFlags = SVSFNLPSpeakPunc; +FLAGS!{enum SpeechVoiceEvents { + SVEStartInputStream = 1 << 1, + SVEEndInputStream = 1 << 2, + SVEVoiceChange = 1 << 3, + SVEBookmark = 1 << 4, + SVEWordBoundary = 1 << 5, + SVEPhoneme = 1 << 6, + SVESentenceBoundary = 1 << 7, + SVEViseme = 1 << 8, + SVEAudioLevel = 1 << 9, + SVEPrivate = 1 << 15, + SVEAllEvents = 0x83fe, +}} +ENUM!{enum DISPID_SpeechVoiceStatus { + DISPID_SVSCurrentStreamNumber = 1, + DISPID_SVSLastStreamNumberQueued, + DISPID_SVSLastResult, + DISPID_SVSRunningState, + DISPID_SVSInputWordPosition, + DISPID_SVSInputWordLength, + DISPID_SVSInputSentencePosition, + DISPID_SVSInputSentenceLength, + DISPID_SVSLastBookmark, + DISPID_SVSLastBookmarkId, + DISPID_SVSPhonemeId, + DISPID_SVSVisemeId, +}} +ENUM!{enum SpeechRunState { + SRSEDone = SPRS_DONE.0, + SRSEIsSpeaking = SPRS_IS_SPEAKING.0, +}} +ENUM!{enum SpeechVisemeType { + SVP_0 = 0, + SVP_1, + SVP_2, + SVP_3, + SVP_4, + SVP_5, + SVP_6, + SVP_7, + SVP_8, + SVP_9, + SVP_10, + SVP_11, + SVP_12, + SVP_13, + SVP_14, + SVP_15, + SVP_16, + SVP_17, + SVP_18, + SVP_19, + SVP_20, + SVP_21, +}} +ENUM!{enum SpeechVisemeFeature { + SVF_None = 0, + SVF_Stressed = SPVFEATURE_STRESSED.0, + SVF_Emphasis = SPVFEATURE_EMPHASIS.0, +}} +ENUM!{enum DISPID_SpeechVoiceEvent { + DISPID_SVEStreamStart = 1, + DISPID_SVEStreamEnd, + DISPID_SVEVoiceChange, + DISPID_SVEBookmark, + DISPID_SVEWord, + DISPID_SVEPhoneme, + DISPID_SVESentenceBoundary, + DISPID_SVEViseme, + DISPID_SVEAudioLevel, + DISPID_SVEEnginePrivate, +}} +ENUM!{enum DISPID_SpeechRecognizer { + DISPID_SRRecognizer = 1, + DISPID_SRAllowAudioInputFormatChangesOnNextSet, + DISPID_SRAudioInput, + DISPID_SRAudioInputStream, + DISPID_SRIsShared, + DISPID_SRState, + DISPID_SRStatus, + DISPID_SRProfile, + DISPID_SREmulateRecognition, + DISPID_SRCreateRecoContext, + DISPID_SRGetFormat, + DISPID_SRSetPropertyNumber, + DISPID_SRGetPropertyNumber, + DISPID_SRSetPropertyString, + DISPID_SRGetPropertyString, + DISPID_SRIsUISupported, + DISPID_SRDisplayUI, + DISPID_SRGetRecognizers, + DISPID_SVGetAudioInputs, + DISPID_SVGetProfiles, +}} +ENUM!{enum SpeechRecognizerState { + SRSInactive = SPRST_INACTIVE.0, + SRSActive = SPRST_ACTIVE.0, + SRSActiveAlways = SPRST_ACTIVE_ALWAYS.0, + SRSInactiveWithPurge = SPRST_INACTIVE_WITH_PURGE.0, +}} +ENUM!{enum SpeechDisplayAttributes { + SDA_No_Trailing_Space = 0, + SDA_One_Trailing_Space = SPAF_ONE_TRAILING_SPACE.0, + SDA_Two_Trailing_Spaces = SPAF_TWO_TRAILING_SPACES.0, + SDA_Consume_Leading_Spaces = SPAF_CONSUME_LEADING_SPACES.0, +}} +ENUM!{enum SpeechFormatType { + SFTInput = SPWF_INPUT.0, + SFTSREngine = SPWF_SRENGINE.0, +}} +FLAGS!{enum SpeechEmulationCompareFlags { + SECFIgnoreCase = 0x1, + SECFIgnoreKanaType = 0x10000, + SECFIgnoreWidth = 0x20000, + SECFNoSpecialChars = 0x20000000, + SECFEmulateResult = 0x40000000, + SECFDefault = SECFIgnoreCase.0 | SECFIgnoreKanaType.0 | SECFIgnoreWidth.0, +}} +ENUM!{enum DISPID_SpeechRecognizerStatus { + DISPID_SRSAudioStatus = 1, + DISPID_SRSCurrentStreamPosition, + DISPID_SRSCurrentStreamNumber, + DISPID_SRSNumberOfActiveRules, + DISPID_SRSClsidEngine, + DISPID_SRSSupportedLanguages, +}} +ENUM!{enum DISPID_SpeechRecoContext { + DISPID_SRCRecognizer = 1, + DISPID_SRCAudioInInterferenceStatus, + DISPID_SRCRequestedUIType, + DISPID_SRCVoice, + DISPID_SRAllowVoiceFormatMatchingOnNextSet, + DISPID_SRCVoicePurgeEvent, + DISPID_SRCEventInterests, + DISPID_SRCCmdMaxAlternates, + DISPID_SRCState, + DISPID_SRCRetainedAudio, + DISPID_SRCRetainedAudioFormat, + DISPID_SRCPause, + DISPID_SRCResume, + DISPID_SRCCreateGrammar, + DISPID_SRCCreateResultFromMemory, + DISPID_SRCBookmark, + DISPID_SRCSetAdaptationData, +}} +ENUM!{enum SpeechRetainedAudioOptions { + SRAONone = SPAO_NONE.0, + SRAORetainAudio = SPAO_RETAIN_AUDIO.0, +}} +ENUM!{enum SpeechBookmarkOptions { + SBONone = SPBO_NONE.0, + SBOPause = SPBO_PAUSE.0, +}} +ENUM!{enum SpeechInterference { + SINone = SPINTERFERENCE_NONE.0, + SINoise = SPINTERFERENCE_NOISE.0, + SINoSignal = SPINTERFERENCE_NOSIGNAL.0, + SITooLoud = SPINTERFERENCE_TOOLOUD.0, + SITooQuiet = SPINTERFERENCE_TOOQUIET.0, + SITooFast = SPINTERFERENCE_TOOFAST.0, + SITooSlow = SPINTERFERENCE_TOOSLOW.0, +}} +FLAGS!{enum SpeechRecoEvents { + SREStreamEnd = 1 << 0, + SRESoundStart = 1 << 1, + SRESoundEnd = 1 << 2, + SREPhraseStart = 1 << 3, + SRERecognition = 1 << 4, + SREHypothesis = 1 << 5, + SREBookmark = 1 << 6, + SREPropertyNumChange = 1 << 7, + SREPropertyStringChange = 1 << 8, + SREFalseRecognition = 1 << 9, + SREInterference = 1 << 10, + SRERequestUI = 1 << 11, + SREStateChange = 1 << 12, + SREAdaptation = 1 << 13, + SREStreamStart = 1 << 14, + SRERecoOtherContext = 1 << 15, + SREAudioLevel = 1 << 16, + SREPrivate = 1 << 18, + SREAllEvents = 0x5ffff, +}} +ENUM!{enum SpeechRecoContextState { + SRCS_Disabled = SPCS_DISABLED.0, + SRCS_Enabled = SPCS_ENABLED.0, +}} +ENUM!{enum DISPIDSPRG { + DISPID_SRGId = 1, + DISPID_SRGRecoContext, + DISPID_SRGState, + DISPID_SRGRules, + DISPID_SRGReset, + DISPID_SRGCommit, + DISPID_SRGCmdLoadFromFile, + DISPID_SRGCmdLoadFromObject, + DISPID_SRGCmdLoadFromResource, + DISPID_SRGCmdLoadFromMemory, + DISPID_SRGCmdLoadFromProprietaryGrammar, + DISPID_SRGCmdSetRuleState, + DISPID_SRGCmdSetRuleIdState, + DISPID_SRGDictationLoad, + DISPID_SRGDictationUnload, + DISPID_SRGDictationSetState, + DISPID_SRGSetWordSequenceData, + DISPID_SRGSetTextSelection, + DISPID_SRGIsPronounceable, +}} +ENUM!{enum SpeechLoadOption { + SLOStatic = SPLO_STATIC.0, + SLODynamic = SPLO_DYNAMIC.0, +}} +ENUM!{enum SpeechWordPronounceable { + SWPUnknownWordUnpronounceable = SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE.0, + SWPUnknownWordPronounceable = SPWP_UNKNOWN_WORD_PRONOUNCEABLE.0, + SWPKnownWordPronounceable = SPWP_KNOWN_WORD_PRONOUNCEABLE.0, +}} +ENUM!{enum SpeechGrammarState { + SGSEnabled = SPGS_ENABLED.0, + SGSDisabled = SPGS_DISABLED.0, + SGSExclusive = SPGS_EXCLUSIVE.0, +}} +ENUM!{enum SpeechRuleState { + SGDSInactive = SPRS_INACTIVE.0, + SGDSActive = SPRS_ACTIVE.0, + SGDSActiveWithAutoPause = SPRS_ACTIVE_WITH_AUTO_PAUSE.0, + SGDSActiveUserDelimited = SPRS_ACTIVE_USER_DELIMITED.0, +}} +ENUM!{enum SpeechRuleAttributes { + SRATopLevel = SPRAF_TopLevel.0, + SRADefaultToActive = SPRAF_Active.0, + SRAExport = SPRAF_Export.0, + SRAImport = SPRAF_Import.0, + SRAInterpreter = SPRAF_Interpreter.0, + SRADynamic = SPRAF_Dynamic.0, + SRARoot = SPRAF_Root.0, +}} +ENUM!{enum SpeechGrammarWordType { + SGDisplay = SPWT_DISPLAY.0, + SGLexical = SPWT_LEXICAL.0, + SGPronounciation = SPWT_PRONUNCIATION.0, + SGLexicalNoSpecialChars = SPWT_LEXICAL_NO_SPECIAL_CHARS.0, +}} +ENUM!{enum DISPID_SpeechRecoContextEvents { + DISPID_SRCEStartStream = 1, + DISPID_SRCEEndStream, + DISPID_SRCEBookmark, + DISPID_SRCESoundStart, + DISPID_SRCESoundEnd, + DISPID_SRCEPhraseStart, + DISPID_SRCERecognition, + DISPID_SRCEHypothesis, + DISPID_SRCEPropertyNumberChange, + DISPID_SRCEPropertyStringChange, + DISPID_SRCEFalseRecognition, + DISPID_SRCEInterference, + DISPID_SRCERequestUI, + DISPID_SRCERecognizerStateChange, + DISPID_SRCEAdaptation, + DISPID_SRCERecognitionForOtherContext, + DISPID_SRCEAudioLevel, + DISPID_SRCEEnginePrivate, +}} +ENUM!{enum SpeechRecognitionType { + SRTStandard = 0, + SRTAutopause = SPREF_AutoPause.0, + SRTEmulated = SPREF_Emulated.0, + SRTSMLTimeout = SPREF_SMLTimeout.0, + SRTExtendableParse = SPREF_ExtendableParse.0, + SRTReSent = SPREF_ReSent.0, +}} +ENUM!{enum DISPID_SpeechGrammarRule { + DISPID_SGRAttributes = 1, + DISPID_SGRInitialState, + DISPID_SGRName, + DISPID_SGRId, + DISPID_SGRClear, + DISPID_SGRAddResource, + DISPID_SGRAddState, +}} +ENUM!{enum DISPID_SpeechGrammarRules { + DISPID_SGRsCount = 1, + DISPID_SGRsDynamic, + DISPID_SGRsAdd, + DISPID_SGRsCommit, + DISPID_SGRsCommitAndSave, + DISPID_SGRsFindRule, + DISPID_SGRsItem = ::DISPID_VALUE as u32, + DISPID_SGRs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechGrammarRuleState { + DISPID_SGRSRule = 1, + DISPID_SGRSTransitions, + DISPID_SGRSAddWordTransition, + DISPID_SGRSAddRuleTransition, + DISPID_SGRSAddSpecialTransition, +}} +ENUM!{enum SpeechSpecialTransitionType { + SSTTWildcard = 1, + SSTTDictation, + SSTTTextBuffer, +}} +ENUM!{enum DISPID_SpeechGrammarRuleStateTransitions { + DISPID_SGRSTsCount = 1, + DISPID_SGRSTsItem = ::DISPID_VALUE as u32, + DISPID_SGRSTs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechGrammarRuleStateTransition { + DISPID_SGRSTType = 1, + DISPID_SGRSTText, + DISPID_SGRSTRule, + DISPID_SGRSTWeight, + DISPID_SGRSTPropertyName, + DISPID_SGRSTPropertyId, + DISPID_SGRSTPropertyValue, + DISPID_SGRSTNextState, +}} +ENUM!{enum SpeechGrammarRuleStateTransitionType { + SGRSTTEpsilon = 0, + SGRSTTWord, + SGRSTTRule, + SGRSTTDictation, + SGRSTTWildcard, + SGRSTTTextBuffer, +}} +ENUM!{enum DISPIDSPTSI { + DISPIDSPTSI_ActiveOffset = 1, + DISPIDSPTSI_ActiveLength, + DISPIDSPTSI_SelectionOffset, + DISPIDSPTSI_SelectionLength, +}} +ENUM!{enum DISPID_SpeechRecoResult { + DISPID_SRRRecoContext = 1, + DISPID_SRRTimes, + DISPID_SRRAudioFormat, + DISPID_SRRPhraseInfo, + DISPID_SRRAlternates, + DISPID_SRRAudio, + DISPID_SRRSpeakAudio, + DISPID_SRRSaveToMemory, + DISPID_SRRDiscardResultInfo, +}} +ENUM!{enum SpeechDiscardType { + SDTProperty = SPDF_PROPERTY.0, + SDTReplacement = SPDF_REPLACEMENT.0, + SDTRule = SPDF_RULE.0, + SDTDisplayText = SPDF_DISPLAYTEXT.0, + SDTLexicalForm = SPDF_LEXICALFORM.0, + SDTPronunciation = SPDF_PRONUNCIATION.0, + SDTAudio = SPDF_AUDIO.0, + SDTAlternates = SPDF_ALTERNATES.0, + SDTAll = SPDF_ALL.0, +}} +ENUM!{enum DISPID_SpeechXMLRecoResult { + DISPID_SRRGetXMLResult, + DISPID_SRRGetXMLErrorInfo, +}} +ENUM!{enum DISPID_SpeechRecoResult2 { + DISPID_SRRSetTextFeedback, +}} +ENUM!{enum DISPID_SpeechPhraseBuilder { + DISPID_SPPBRestorePhraseFromMemory = 1, +}} +ENUM!{enum DISPID_SpeechRecoResultTimes { + DISPID_SRRTStreamTime = 1, + DISPID_SRRTLength, + DISPID_SRRTTickCount, + DISPID_SRRTOffsetFromStart, +}} +ENUM!{enum DISPID_SpeechPhraseAlternate { + DISPID_SPARecoResult = 1, + DISPID_SPAStartElementInResult, + DISPID_SPANumberOfElementsInResult, + DISPID_SPAPhraseInfo, + DISPID_SPACommit, +}} +ENUM!{enum DISPID_SpeechPhraseAlternates { + DISPID_SPAsCount = 1, + DISPID_SPAsItem = ::DISPID_VALUE as u32, + DISPID_SPAs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseInfo { + DISPID_SPILanguageId = 1, + DISPID_SPIGrammarId, + DISPID_SPIStartTime, + DISPID_SPIAudioStreamPosition, + DISPID_SPIAudioSizeBytes, + DISPID_SPIRetainedSizeBytes, + DISPID_SPIAudioSizeTime, + DISPID_SPIRule, + DISPID_SPIProperties, + DISPID_SPIElements, + DISPID_SPIReplacements, + DISPID_SPIEngineId, + DISPID_SPIEnginePrivateData, + DISPID_SPISaveToMemory, + DISPID_SPIGetText, + DISPID_SPIGetDisplayAttributes, +}} +ENUM!{enum DISPID_SpeechPhraseElement { + DISPID_SPEAudioTimeOffset = 1, + DISPID_SPEAudioSizeTime, + DISPID_SPEAudioStreamOffset, + DISPID_SPEAudioSizeBytes, + DISPID_SPERetainedStreamOffset, + DISPID_SPERetainedSizeBytes, + DISPID_SPEDisplayText, + DISPID_SPELexicalForm, + DISPID_SPEPronunciation, + DISPID_SPEDisplayAttributes, + DISPID_SPERequiredConfidence, + DISPID_SPEActualConfidence, + DISPID_SPEEngineConfidence, +}} +ENUM!{enum SpeechEngineConfidence { + SECLowConfidence = -1i32 as u32, + SECNormalConfidence = 0, + SECHighConfidence = 1, +}} +ENUM!{enum DISPID_SpeechPhraseElements { + DISPID_SPEsCount = 1, + DISPID_SPEsItem = ::DISPID_VALUE as u32, + DISPID_SPEs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseReplacement { + DISPID_SPRDisplayAttributes = 1, + DISPID_SPRText, + DISPID_SPRFirstElement, + DISPID_SPRNumberOfElements, +}} +ENUM!{enum DISPID_SpeechPhraseReplacements { + DISPID_SPRsCount = 1, + DISPID_SPRsItem = ::DISPID_VALUE as u32, + DISPID_SPRs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseProperty { + DISPID_SPPName = 1, + DISPID_SPPId, + DISPID_SPPValue, + DISPID_SPPFirstElement, + DISPID_SPPNumberOfElements, + DISPID_SPPEngineConfidence, + DISPID_SPPConfidence, + DISPID_SPPParent, + DISPID_SPPChildren, +}} +ENUM!{enum DISPID_SpeechPhraseProperties { + DISPID_SPPsCount = 1, + DISPID_SPPsItem = ::DISPID_VALUE as u32, + DISPID_SPPs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseRule { + DISPID_SPRuleName = 1, + DISPID_SPRuleId, + DISPID_SPRuleFirstElement, + DISPID_SPRuleNumberOfElements, + DISPID_SPRuleParent, + DISPID_SPRuleChildren, + DISPID_SPRuleConfidence, + DISPID_SPRuleEngineConfidence, +}} +ENUM!{enum DISPID_SpeechPhraseRules { + DISPID_SPRulesCount = 1, + DISPID_SPRulesItem = ::DISPID_VALUE as u32, + DISPID_SPRules_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechLexicon { + DISPID_SLGenerationId = 1, + DISPID_SLGetWords, + DISPID_SLAddPronunciation, + DISPID_SLAddPronunciationByPhoneIds, + DISPID_SLRemovePronunciation, + DISPID_SLRemovePronunciationByPhoneIds, + DISPID_SLGetPronunciations, + DISPID_SLGetGenerationChange, +}} +ENUM!{enum SpeechLexiconType { + SLTUser = eLEXTYPE_USER.0, + SLTApp = eLEXTYPE_APP.0, +}} +ENUM!{enum SpeechPartOfSpeech { + SPSNotOverriden = SPPS_NotOverriden.0, + SPSUnknown = SPPS_Unknown.0, + SPSNoun = SPPS_Noun.0, + SPSVerb = SPPS_Verb.0, + SPSModifier = SPPS_Modifier.0, + SPSFunction = SPPS_Function.0, + SPSInterjection = SPPS_Interjection.0, + SPSLMA = SPPS_LMA.0, + SPSSuppressWord = SPPS_SuppressWord.0, +}} +ENUM!{enum DISPID_SpeechLexiconWords { + DISPID_SLWsCount = 1, + DISPID_SLWsItem = ::DISPID_VALUE as u32, + DISPID_SLWs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum SpeechWordType { + SWTAdded = eWORDTYPE_ADDED.0, + SWTDeleted = eWORDTYPE_DELETED.0, +}} +ENUM!{enum DISPID_SpeechLexiconWord { + DISPID_SLWLangId = 1, + DISPID_SLWType, + DISPID_SLWWord, + DISPID_SLWPronunciations, +}} +ENUM!{enum DISPID_SpeechLexiconProns { + DISPID_SLPsCount = 1, + DISPID_SLPsItem = ::DISPID_VALUE as u32, + DISPID_SLPs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechLexiconPronunciation { + DISPID_SLPType = 1, + DISPID_SLPLangId, + DISPID_SLPPartOfSpeech, + DISPID_SLPPhoneIds, + DISPID_SLPSymbolic, +}} +ENUM!{enum DISPID_SpeechPhoneConverter { + DISPID_SPCLangId = 1, + DISPID_SPCPhoneToId, + DISPID_SPCIdToPhone, +}} +RIDL!( +interface ISpeechDataKey(ISpeechDataKeyVtbl): IDispatch(IDispatchVtbl) { + fn SetBinaryValue(&mut self, ValueName: ::BSTR, Value: ::VARIANT) -> ::HRESULT, + fn GetBinaryValue(&mut self, ValueName: ::BSTR, Value: *mut ::VARIANT) -> ::HRESULT, + fn SetStringValue(&mut self, ValueName: ::BSTR, Value: ::BSTR) -> ::HRESULT, + fn GetStringValue(&mut self, ValueName: ::BSTR, Value: *mut ::BSTR) -> ::HRESULT, + fn SetLongValue(&mut self, ValueName: ::BSTR, Value: ::c_long) -> ::HRESULT, + fn GetLongValue(&mut self, ValueName: ::BSTR, Value: *mut ::c_long) -> ::HRESULT, + fn OpenKey(&mut self, SubKeyName: ::BSTR, SubKey: *mut *mut ISpeechDataKey) -> ::HRESULT, + fn CreateKey(&mut self, SubKeyName: ::BSTR, SubKey: *mut *mut ISpeechDataKey) -> ::HRESULT, + fn DeleteKey(&mut self, SubKeyName: ::BSTR) -> ::HRESULT, + fn DeleteValue(&mut self, ValueName: ::BSTR) -> ::HRESULT, + fn EnumKeys(&mut self, Index: ::c_long, SubKeyName: *mut ::BSTR) -> ::HRESULT, + fn EnumValues(&mut self, Index: ::c_long, ValueName: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface ISpeechObjectToken(ISpeechObjectTokenVtbl): IDispatch(IDispatchVtbl) { + fn get_Id(&mut self, ObjectId: *mut ::BSTR) -> ::HRESULT, + fn get_DataKey(&mut self, DataKey: *mut *mut ISpeechDataKey) -> ::HRESULT, + fn get_Category(&mut self, Category: *mut *mut ISpeechObjectTokenCategory) -> ::HRESULT, + fn GetDescription(&mut self, Locale: ::c_long, Description: *mut ::BSTR) -> ::HRESULT, + fn SetId( + &mut self, Id: ::BSTR, CategoryId: ::BSTR, CreateIfNotExist: ::VARIANT_BOOL + ) -> ::HRESULT, + fn GetAttribute(&mut self, AttributeName: ::BSTR, AttributeValue: *mut ::BSTR) -> ::HRESULT, + fn CreateInstance( + &mut self, pUnkOuter: *mut ::IUnknown, ClsContext: SpeechTokenContext, + Object: *mut *mut ::IUnknown + ) -> ::HRESULT, + fn Remove(&mut self, ObjectStorageCLSID: ::BSTR) -> ::HRESULT, + fn GetStorageFileName( + &mut self, ObjectStorageCLSID: ::BSTR, KeyName: ::BSTR, FileName: ::BSTR, Folder: ::BSTR, + FilePath: *mut ::BSTR + ) -> ::HRESULT, + fn RemoveStorageFileName( + &mut self, ObjectStorageCLSID: ::BSTR, KeyName: ::BSTR, DeleteFile: ::VARIANT_BOOL + ) -> ::HRESULT, + fn IsUISupported( + &mut self, TypeOfUI: ::BSTR, ExtraData: *const ::VARIANT, Object: *mut ::IUnknown, + Supported: *mut ::VARIANT_BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hWnd: ::c_long, Title: ::BSTR, TypeOfUI: ::BSTR, ExtraData: *const ::VARIANT, + Object: *mut ::IUnknown + ) -> ::HRESULT, + fn MatchesAttributes(&mut self, Attributes: ::BSTR, Matches: *mut ::VARIANT_BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpeechObjectTokens(ISpeechObjectTokensVtbl): IDispatch(IDispatchVtbl) { + fn get_Count(&mut self, Count: *mut ::c_long) -> ::HRESULT, + fn Item(&mut self, Index: ::c_long, Token: *mut *mut ISpeechObjectToken) -> ::HRESULT, + fn get__NewEnum(&mut self, ppEnumVARIANT: *mut *mut ::IUnknown) -> ::HRESULT +} +); +RIDL!( +interface ISpeechObjectTokenCategory(ISpeechObjectTokenCategoryVtbl): IDispatch(IDispatchVtbl) { + fn get_Id(&mut self, Id: *mut ::BSTR) -> ::HRESULT, + fn put_Default(&mut self, TokenId: ::BSTR) -> ::HRESULT, + fn get_Default(&mut self, TokenId: *mut ::BSTR) -> ::HRESULT, + fn SetId(&mut self, Id: ::BSTR, CreateIfNotExist: ::VARIANT_BOOL) -> ::HRESULT, + fn GetDataKey( + &mut self, Location: SpeechDataKeyLocation, DataKey: *mut *mut ISpeechDataKey + ) -> ::HRESULT, + fn EnumerateTokens( + &mut self, RequiredAttributes: ::BSTR, OptionalAttributes: ::BSTR, + Tokens: *mut *mut ISpeechObjectTokens + ) -> ::HRESULT +} +); +RIDL!( +interface ISpeechAudioBufferInfo(ISpeechAudioBufferInfoVtbl): IDispatch(IDispatchVtbl) { + fn get_MinNotification(&mut self, MinNotification: *mut ::c_long) -> ::HRESULT, + fn put_MinNotification(&mut self, MinNotification: ::c_long) -> ::HRESULT, + fn get_BufferSize(&mut self, BufferSize: *mut ::c_long) -> ::HRESULT, + fn put_BufferSize(&mut self, BufferSize: ::c_long) -> ::HRESULT, + fn get_EventBias(&mut self, EventBias: *mut ::c_long) -> ::HRESULT, + fn put_EventBias(&mut self, EventBias: ::c_long) -> ::HRESULT +} +); +RIDL!( +interface ISpeechAudioStatus(ISpeechAudioStatusVtbl): IDispatch(IDispatchVtbl) { + fn get_FreeBufferSpace(&mut self, FreeBufferSpace: *mut ::c_long) -> ::HRESULT, + fn get_NonBlockingIO(&mut self, NonBlockingIO: *mut ::c_long) -> ::HRESULT, + fn get_State(&mut self, State: *mut SpeechAudioState) -> ::HRESULT, + fn get_CurrentSeekPosition(&mut self, CurrentSeekPosition: *mut ::VARIANT) -> ::HRESULT, + fn get_CurrentDevicePosition(&mut self, CurrentDevicePosition: *mut ::VARIANT) -> ::HRESULT +} +); +RIDL!( +interface ISpeechAudioFormat(ISpeechAudioFormatVtbl): IDispatch(IDispatchVtbl) { + fn get_Type(&mut self, AudioFormat: *mut SpeechAudioFormatType) -> ::HRESULT, + fn put_Type(&mut self, AudioFormat: SpeechAudioFormatType) -> ::HRESULT, + fn get_Guid(&mut self, Guid: *mut ::BSTR) -> ::HRESULT, + fn put_Guid(&mut self, Guid: ::BSTR) -> ::HRESULT, + fn GetWaveFormatEx(&mut self, SpeechWaveFormatEx: *mut *mut ISpeechWaveFormatEx) -> ::HRESULT, + fn SetWaveFormatEx(&mut self, SpeechWaveFormatEx: *mut ISpeechWaveFormatEx) -> ::HRESULT +} +); +RIDL!( +interface ISpeechWaveFormatEx(ISpeechWaveFormatExVtbl): IDispatch(IDispatchVtbl) { + fn get_FormatTag(&mut self, FormatTag: *mut ::c_short) -> ::HRESULT, + fn put_FormatTag(&mut self, FormatTag: ::c_short) -> ::HRESULT, + fn get_Channels(&mut self, Channels: *mut ::c_short) -> ::HRESULT, + fn put_Channels(&mut self, Channels: ::c_short) -> ::HRESULT, + fn get_SamplesPerSec(&mut self, SamplesPerSec: *mut ::c_long) -> ::HRESULT, + fn put_SamplesPerSec(&mut self, SamplesPerSec: ::c_long) -> ::HRESULT, + fn get_AvgBytesPerSec(&mut self, AvgBytesPerSec: *mut ::c_long) -> ::HRESULT, + fn put_AvgBytesPerSec(&mut self, AvgBytesPerSec: ::c_long) -> ::HRESULT, + fn get_BlockAlign(&mut self, BlockAlign: *mut ::c_short) -> ::HRESULT, + fn put_BlockAlign(&mut self, BlockAlign: ::c_short) -> ::HRESULT, + fn get_BitsPerSample(&mut self, BitsPerSample: *mut ::c_short) -> ::HRESULT, + fn put_BitsPerSample(&mut self, BitsPerSample: ::c_short) -> ::HRESULT, + fn get_ExtraData(&mut self, ExtraData: *mut ::VARIANT) -> ::HRESULT, + fn put_ExtraData(&mut self, ExtraData: ::VARIANT) -> ::HRESULT +} +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/schannel.rs b/bash-5.1/vendor/winapi-0.2.8/src/schannel.rs new file mode 100644 index 0000000..d57aec8 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/schannel.rs @@ -0,0 +1,333 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Public Definitions for SCHANNEL Security Provider +pub const UNISP_NAME: &'static str = "Microsoft Unified Security Protocol Provider"; +pub const SSL2SP_NAME: &'static str = "Microsoft SSL 2.0"; +pub const SSL3SP_NAME: &'static str = "Microsoft SSL 3.0"; +pub const TLS1SP_NAME: &'static str = "Microsoft TLS 1.0"; +pub const PCT1SP_NAME: &'static str = "Microsoft PCT 1.0"; +pub const SCHANNEL_NAME: &'static str = "Schannel"; +ENUM!{enum eTlsSignatureAlgorithm { + TlsSignatureAlgorithm_Anonymous = 0, + TlsSignatureAlgorithm_Rsa = 1, + TlsSignatureAlgorithm_Dsa = 2, + TlsSignatureAlgorithm_Ecdsa = 3, +}} +ENUM!{enum eTlsHashAlgorithm { + TlsHashAlgorithm_None = 0, + TlsHashAlgorithm_Md5 = 1, + TlsHashAlgorithm_Sha1 = 2, + TlsHashAlgorithm_Sha224 = 3, + TlsHashAlgorithm_Sha256 = 4, + TlsHashAlgorithm_Sha384 = 5, + TlsHashAlgorithm_Sha512 = 6, +}} +pub const UNISP_RPC_ID: ::DWORD = 14; +STRUCT!{struct SecPkgContext_RemoteCredentialInfo { + cbCertificateChain: ::DWORD, + pbCertificateChain: ::PBYTE, + cCertificates: ::DWORD, + fFlags: ::DWORD, + dwBits: ::DWORD, +}} +pub type PSecPkgContext_RemoteCredentialInfo = *mut SecPkgContext_RemoteCredentialInfo; +pub type SecPkgContext_RemoteCredenitalInfo = SecPkgContext_RemoteCredentialInfo; +pub type PSecPkgContext_RemoteCredenitalInfo = *mut SecPkgContext_RemoteCredentialInfo; +pub const RCRED_STATUS_NOCRED: ::DWORD = 0x00000000; +pub const RCRED_CRED_EXISTS: ::DWORD = 0x00000001; +pub const RCRED_STATUS_UNKNOWN_ISSUER: ::DWORD = 0x00000002; +STRUCT!{struct SecPkgContext_LocalCredentialInfo { + cbCertificateChain: ::DWORD, + pbCertificateChain: ::PBYTE, + cCertificates: ::DWORD, + fFlags: ::DWORD, + dwBits: ::DWORD, +}} +pub type PSecPkgContext_LocalCredentialInfo = *mut SecPkgContext_LocalCredentialInfo; +pub type SecPkgContext_LocalCredenitalInfo = SecPkgContext_LocalCredentialInfo; +pub type PSecPkgContext_LocalCredenitalInfo = *mut SecPkgContext_LocalCredentialInfo; +pub const LCRED_STATUS_NOCRED: ::DWORD = 0x00000000; +pub const LCRED_CRED_EXISTS: ::DWORD = 0x00000001; +pub const LCRED_STATUS_UNKNOWN_ISSUER: ::DWORD = 0x00000002; +STRUCT!{struct SecPkgContext_ClientCertPolicyResult { + dwPolicyResult: ::HRESULT, + guidPolicyId: ::GUID, +}} +pub type PSecPkgContext_ClientCertPolicyResult = *mut SecPkgContext_ClientCertPolicyResult; +STRUCT!{struct SecPkgContext_IssuerListInfoEx { + aIssuers: ::PCERT_NAME_BLOB, + cIssuers: ::DWORD, +}} +pub type PSecPkgContext_IssuerListInfoEx = *mut SecPkgContext_IssuerListInfoEx; +STRUCT!{struct SecPkgContext_ConnectionInfo { + dwProtocol: ::DWORD, + aiCipher: ::ALG_ID, + dwCipherStrength: ::DWORD, + aiHash: ::ALG_ID, + dwHashStrength: ::DWORD, + aiExch: ::ALG_ID, + dwExchStrength: ::DWORD, +}} +pub type PSecPkgContext_ConnectionInfo = *mut SecPkgContext_ConnectionInfo; +pub const SZ_ALG_MAX_SIZE: usize = 64; +pub const SECPKGCONTEXT_CIPHERINFO_V1: ::DWORD = 1; +STRUCT!{nodebug struct SecPkgContext_CipherInfo { + dwVersion: ::DWORD, + dwProtocol: ::DWORD, + dwCipherSuite: ::DWORD, + dwBaseCipherSuite: ::DWORD, + szCipherSuite: [::WCHAR; SZ_ALG_MAX_SIZE], + szCipher: [::WCHAR; SZ_ALG_MAX_SIZE], + dwCipherLen: ::DWORD, + dwCipherBlockLen: ::DWORD, + szHash: [::WCHAR; SZ_ALG_MAX_SIZE], + dwHashLen: ::DWORD, + szExchange: [::WCHAR; SZ_ALG_MAX_SIZE], + dwMinExchangeLen: ::DWORD, + dwMaxExchangeLen: ::DWORD, + szCertificate: [::WCHAR; SZ_ALG_MAX_SIZE], + dwKeyType: ::DWORD, +}} +pub type PSecPkgContext_CipherInfo = *mut SecPkgContext_CipherInfo; +STRUCT!{nodebug struct SecPkgContext_EapKeyBlock { + rgbKeys: [::BYTE; 128], + rgbIVs: [::BYTE; 64], +}} +pub type PSecPkgContext_EapKeyBlock = *mut SecPkgContext_EapKeyBlock; +STRUCT!{struct SecPkgContext_MappedCredAttr { + dwAttribute: ::DWORD, + pvBuffer: ::PVOID, +}} +pub type PSecPkgContext_MappedCredAttr = *mut SecPkgContext_MappedCredAttr; +pub const SSL_SESSION_RECONNECT: ::DWORD = 1; +STRUCT!{struct SecPkgContext_SessionInfo { + dwFlags: ::DWORD, + cbSessionId: ::DWORD, + rgbSessionId: [::BYTE; 32], +}} +pub type PSecPkgContext_SessionInfo = *mut SecPkgContext_SessionInfo; +STRUCT!{struct SecPkgContext_SessionAppData { + dwFlags: ::DWORD, + cbAppData: ::DWORD, + pbAppData: ::PBYTE, +}} +pub type PSecPkgContext_SessionAppData = *mut SecPkgContext_SessionAppData; +STRUCT!{struct SecPkgContext_EapPrfInfo { + dwVersion: ::DWORD, + cbPrfData: ::DWORD, + pbPrfData: ::PBYTE, +}} +pub type PSecPkgContext_EapPrfInfo = *mut SecPkgContext_EapPrfInfo; +STRUCT!{struct SecPkgContext_SupportedSignatures { + cSignatureAndHashAlgorithms: ::WORD, + pSignatureAndHashAlgorithms: *mut ::WORD, +}} +pub type PSecPkgContext_SupportedSignatures = *mut SecPkgContext_SupportedSignatures; +STRUCT!{struct SecPkgContext_Certificates { + cCertificates: ::DWORD, + cbCertificateChain: ::DWORD, + pbCertificateChain: ::PBYTE, +}} +pub type PSecPkgContext_Certificates = *mut SecPkgContext_Certificates; +STRUCT!{struct SecPkgContext_CertInfo { + dwVersion: ::DWORD, + cbSubjectName: ::DWORD, + pwszSubjectName: ::LPWSTR, + cbIssuerName: ::DWORD, + pwszIssuerName: ::LPWSTR, + dwKeySize: ::DWORD, +}} +pub type PSecPkgContext_CertInfo = *mut SecPkgContext_CertInfo; +pub const KERN_CONTEXT_CERT_INFO_V1: ::DWORD = 0x00000000; +STRUCT!{struct SecPkgContext_UiInfo { + hParentWindow: ::HWND, +}} +pub type PSecPkgContext_UiInfo = *mut SecPkgContext_UiInfo; +STRUCT!{struct SecPkgContext_EarlyStart { + dwEarlyStartFlags: ::DWORD, +}} +pub type PSecPkgContext_EarlyStart = *mut SecPkgContext_EarlyStart; +pub const ENABLE_TLS_CLIENT_EARLY_START: ::DWORD = 0x00000001; +pub const SCH_CRED_V1: ::DWORD = 0x00000001; +pub const SCH_CRED_V2: ::DWORD = 0x00000002; +pub const SCH_CRED_VERSION: ::DWORD = 0x00000002; +pub const SCH_CRED_V3: ::DWORD = 0x00000003; +pub const SCHANNEL_CRED_VERSION: ::DWORD = 0x00000004; +pub enum _HMAPPER {} +STRUCT!{struct SCHANNEL_CRED { + dwVersion: ::DWORD, + cCreds: ::DWORD, + paCred: *mut ::PCCERT_CONTEXT, + hRootStore: ::HCERTSTORE, + cMappers: ::DWORD, + aphMappers: *mut *mut _HMAPPER, + cSupportedAlgs: ::DWORD, + palgSupportedAlgs: *mut ::ALG_ID, + grbitEnabledProtocols: ::DWORD, + dwMinimumCipherStrength: ::DWORD, + dwMaximumCipherStrength: ::DWORD, + dwSessionLifespan: ::DWORD, + dwFlags: ::DWORD, + dwCredFormat: ::DWORD, +}} +pub type PSCHANNEL_CRED = *mut SCHANNEL_CRED; +pub const SCH_CRED_FORMAT_CERT_CONTEXT: ::DWORD = 0x00000000; +pub const SCH_CRED_FORMAT_CERT_HASH: ::DWORD = 0x00000001; +pub const SCH_CRED_FORMAT_CERT_HASH_STORE: ::DWORD = 0x00000002; +pub const SCH_CRED_MAX_STORE_NAME_SIZE: usize = 128; +pub const SCH_CRED_MAX_SUPPORTED_ALGS: ::DWORD = 256; +pub const SCH_CRED_MAX_SUPPORTED_CERTS: ::DWORD = 100; +STRUCT!{struct SCHANNEL_CERT_HASH { + dwLength: ::DWORD, + dwFlags: ::DWORD, + hProv: ::HCRYPTPROV, + ShaHash: [::BYTE; 20], +}} +pub type PSCHANNEL_CERT_HASH = *mut SCHANNEL_CERT_HASH; +STRUCT!{nodebug struct SCHANNEL_CERT_HASH_STORE { + dwLength: ::DWORD, + dwFlags: ::DWORD, + hProv: ::HCRYPTPROV, + ShaHash: [::BYTE; 20], + pwszStoreName: [::WCHAR; SCH_CRED_MAX_STORE_NAME_SIZE], +}} +pub type PSCHANNEL_CERT_HASH_STORE = *mut SCHANNEL_CERT_HASH_STORE; +pub const SCH_MACHINE_CERT_HASH: ::DWORD = 0x00000001; +pub const SCH_CRED_NO_SYSTEM_MAPPER: ::DWORD = 0x00000002; +pub const SCH_CRED_NO_SERVERNAME_CHECK: ::DWORD = 0x00000004; +pub const SCH_CRED_MANUAL_CRED_VALIDATION: ::DWORD = 0x00000008; +pub const SCH_CRED_NO_DEFAULT_CREDS: ::DWORD = 0x00000010; +pub const SCH_CRED_AUTO_CRED_VALIDATION: ::DWORD = 0x00000020; +pub const SCH_CRED_USE_DEFAULT_CREDS: ::DWORD = 0x00000040; +pub const SCH_CRED_DISABLE_RECONNECTS: ::DWORD = 0x00000080; +pub const SCH_CRED_REVOCATION_CHECK_END_CERT: ::DWORD = 0x00000100; +pub const SCH_CRED_REVOCATION_CHECK_CHAIN: ::DWORD = 0x00000200; +pub const SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT: ::DWORD = 0x00000400; +pub const SCH_CRED_IGNORE_NO_REVOCATION_CHECK: ::DWORD = 0x00000800; +pub const SCH_CRED_IGNORE_REVOCATION_OFFLINE: ::DWORD = 0x00001000; +pub const SCH_CRED_RESTRICTED_ROOTS: ::DWORD = 0x00002000; +pub const SCH_CRED_REVOCATION_CHECK_CACHE_ONLY: ::DWORD = 0x00004000; +pub const SCH_CRED_CACHE_ONLY_URL_RETRIEVAL: ::DWORD = 0x00008000; +pub const SCH_CRED_MEMORY_STORE_CERT: ::DWORD = 0x00010000; +pub const SCH_CRED_CACHE_ONLY_URL_RETRIEVAL_ON_CREATE: ::DWORD = 0x00020000; +pub const SCH_SEND_ROOT_CERT: ::DWORD = 0x00040000; +pub const SCH_CRED_SNI_CREDENTIAL: ::DWORD = 0x00080000; +pub const SCH_CRED_SNI_ENABLE_OCSP: ::DWORD = 0x00100000; +pub const SCH_SEND_AUX_RECORD: ::DWORD = 0x00200000; +pub const SCH_USE_STRONG_CRYPTO: ::DWORD = 0x00400000; +pub const SCHANNEL_RENEGOTIATE: ::DWORD = 0; +pub const SCHANNEL_SHUTDOWN: ::DWORD = 1; +pub const SCHANNEL_ALERT: ::DWORD = 2; +pub const SCHANNEL_SESSION: ::DWORD = 3; +STRUCT!{struct SCHANNEL_ALERT_TOKEN { + dwTokenType: ::DWORD, + dwAlertType: ::DWORD, + dwAlertNumber: ::DWORD, +}} +pub const TLS1_ALERT_WARNING: ::DWORD = 1; +pub const TLS1_ALERT_FATAL: ::DWORD = 2; +pub const TLS1_ALERT_CLOSE_NOTIFY: ::DWORD = 0; +pub const TLS1_ALERT_UNEXPECTED_MESSAGE: ::DWORD = 10; +pub const TLS1_ALERT_BAD_RECORD_MAC: ::DWORD = 20; +pub const TLS1_ALERT_DECRYPTION_FAILED: ::DWORD = 21; +pub const TLS1_ALERT_RECORD_OVERFLOW: ::DWORD = 22; +pub const TLS1_ALERT_DECOMPRESSION_FAIL: ::DWORD = 30; +pub const TLS1_ALERT_HANDSHAKE_FAILURE: ::DWORD = 40; +pub const TLS1_ALERT_BAD_CERTIFICATE: ::DWORD = 42; +pub const TLS1_ALERT_UNSUPPORTED_CERT: ::DWORD = 43; +pub const TLS1_ALERT_CERTIFICATE_REVOKED: ::DWORD = 44; +pub const TLS1_ALERT_CERTIFICATE_EXPIRED: ::DWORD = 45; +pub const TLS1_ALERT_CERTIFICATE_UNKNOWN: ::DWORD = 46; +pub const TLS1_ALERT_ILLEGAL_PARAMETER: ::DWORD = 47; +pub const TLS1_ALERT_UNKNOWN_CA: ::DWORD = 48; +pub const TLS1_ALERT_ACCESS_DENIED: ::DWORD = 49; +pub const TLS1_ALERT_DECODE_ERROR: ::DWORD = 50; +pub const TLS1_ALERT_DECRYPT_ERROR: ::DWORD = 51; +pub const TLS1_ALERT_EXPORT_RESTRICTION: ::DWORD = 60; +pub const TLS1_ALERT_PROTOCOL_VERSION: ::DWORD = 70; +pub const TLS1_ALERT_INSUFFIENT_SECURITY: ::DWORD = 71; +pub const TLS1_ALERT_INTERNAL_ERROR: ::DWORD = 80; +pub const TLS1_ALERT_USER_CANCELED: ::DWORD = 90; +pub const TLS1_ALERT_NO_RENEGOTIATION: ::DWORD = 100; +pub const TLS1_ALERT_UNSUPPORTED_EXT: ::DWORD = 110; +pub const TLS1_ALERT_NO_APP_PROTOCOL: ::DWORD = 120; +pub const SSL_SESSION_ENABLE_RECONNECTS: ::DWORD = 1; +pub const SSL_SESSION_DISABLE_RECONNECTS: ::DWORD = 2; +STRUCT!{struct SCHANNEL_SESSION_TOKEN { + dwTokenType: ::DWORD, + dwFlags: ::DWORD, +}} +STRUCT!{nodebug struct SCHANNEL_CLIENT_SIGNATURE { + cbLength: ::DWORD, + aiHash: ::ALG_ID, + cbHash: ::DWORD, + HashValue: [::BYTE; 36], + CertThumbprint: [::BYTE; 20], +}} +pub type PSCHANNEL_CLIENT_SIGNATURE = *mut SCHANNEL_CLIENT_SIGNATURE; +pub const SP_PROT_PCT1_SERVER: ::DWORD = 0x00000001; +pub const SP_PROT_PCT1_CLIENT: ::DWORD = 0x00000002; +pub const SP_PROT_PCT1: ::DWORD = SP_PROT_PCT1_SERVER | SP_PROT_PCT1_CLIENT; +pub const SP_PROT_SSL2_SERVER: ::DWORD = 0x00000004; +pub const SP_PROT_SSL2_CLIENT: ::DWORD = 0x00000008; +pub const SP_PROT_SSL2: ::DWORD = SP_PROT_SSL2_SERVER | SP_PROT_SSL2_CLIENT; +pub const SP_PROT_SSL3_SERVER: ::DWORD = 0x00000010; +pub const SP_PROT_SSL3_CLIENT: ::DWORD = 0x00000020; +pub const SP_PROT_SSL3: ::DWORD = SP_PROT_SSL3_SERVER | SP_PROT_SSL3_CLIENT; +pub const SP_PROT_TLS1_SERVER: ::DWORD = 0x00000040; +pub const SP_PROT_TLS1_CLIENT: ::DWORD = 0x00000080; +pub const SP_PROT_TLS1: ::DWORD = SP_PROT_TLS1_SERVER | SP_PROT_TLS1_CLIENT; +pub const SP_PROT_SSL3TLS1_CLIENTS: ::DWORD = SP_PROT_TLS1_CLIENT | SP_PROT_SSL3_CLIENT; +pub const SP_PROT_SSL3TLS1_SERVERS: ::DWORD = SP_PROT_TLS1_SERVER | SP_PROT_SSL3_SERVER; +pub const SP_PROT_SSL3TLS1: ::DWORD = SP_PROT_SSL3 | SP_PROT_TLS1; +pub const SP_PROT_UNI_SERVER: ::DWORD = 0x40000000; +pub const SP_PROT_UNI_CLIENT: ::DWORD = 0x80000000; +pub const SP_PROT_UNI: ::DWORD = SP_PROT_UNI_SERVER | SP_PROT_UNI_CLIENT; +pub const SP_PROT_ALL: ::DWORD = 0xffffffff; +pub const SP_PROT_NONE: ::DWORD = 0; +pub const SP_PROT_CLIENTS: ::DWORD = SP_PROT_PCT1_CLIENT | SP_PROT_SSL2_CLIENT + | SP_PROT_SSL3_CLIENT | SP_PROT_UNI_CLIENT | SP_PROT_TLS1_CLIENT; +pub const SP_PROT_SERVERS: ::DWORD = SP_PROT_PCT1_SERVER | SP_PROT_SSL2_SERVER + | SP_PROT_SSL3_SERVER | SP_PROT_UNI_SERVER | SP_PROT_TLS1_SERVER; +pub const SP_PROT_TLS1_0_SERVER: ::DWORD = SP_PROT_TLS1_SERVER; +pub const SP_PROT_TLS1_0_CLIENT: ::DWORD = SP_PROT_TLS1_CLIENT; +pub const SP_PROT_TLS1_0: ::DWORD = SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_0_CLIENT; +pub const SP_PROT_TLS1_1_SERVER: ::DWORD = 0x00000100; +pub const SP_PROT_TLS1_1_CLIENT: ::DWORD = 0x00000200; +pub const SP_PROT_TLS1_1: ::DWORD = SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_1_CLIENT; +pub const SP_PROT_TLS1_2_SERVER: ::DWORD = 0x00000400; +pub const SP_PROT_TLS1_2_CLIENT: ::DWORD = 0x00000800; +pub const SP_PROT_TLS1_2: ::DWORD = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_2_CLIENT; +pub const SP_PROT_DTLS_SERVER: ::DWORD = 0x00010000; +pub const SP_PROT_DTLS_CLIENT: ::DWORD = 0x00020000; +pub const SP_PROT_DTLS: ::DWORD = SP_PROT_DTLS_SERVER | SP_PROT_DTLS_CLIENT; +pub const SP_PROT_DTLS1_0_SERVER: ::DWORD = SP_PROT_DTLS_SERVER; +pub const SP_PROT_DTLS1_0_CLIENT: ::DWORD = SP_PROT_DTLS_CLIENT; +pub const SP_PROT_DTLS1_0: ::DWORD = SP_PROT_DTLS1_0_SERVER | SP_PROT_DTLS1_0_CLIENT; +pub const SP_PROT_DTLS1_X_SERVER: ::DWORD = SP_PROT_DTLS1_0_SERVER; +pub const SP_PROT_DTLS1_X_CLIENT: ::DWORD = SP_PROT_DTLS1_0_CLIENT; +pub const SP_PROT_DTLS1_X: ::DWORD = SP_PROT_DTLS1_X_SERVER | SP_PROT_DTLS1_X_CLIENT; +pub const SP_PROT_TLS1_1PLUS_SERVER: ::DWORD = SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_2_SERVER; +pub const SP_PROT_TLS1_1PLUS_CLIENT: ::DWORD = SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT; +pub const SP_PROT_TLS1_1PLUS: ::DWORD = SP_PROT_TLS1_1PLUS_SERVER | SP_PROT_TLS1_1PLUS_CLIENT; +pub const SP_PROT_TLS1_X_SERVER: ::DWORD = SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_1_SERVER + | SP_PROT_TLS1_2_SERVER; +pub const SP_PROT_TLS1_X_CLIENT: ::DWORD = SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT + | SP_PROT_TLS1_2_CLIENT; +pub const SP_PROT_TLS1_X: ::DWORD = SP_PROT_TLS1_X_SERVER | SP_PROT_TLS1_X_CLIENT; +pub const SP_PROT_SSL3TLS1_X_CLIENTS: ::DWORD = SP_PROT_TLS1_X_CLIENT | SP_PROT_SSL3_CLIENT; +pub const SP_PROT_SSL3TLS1_X_SERVERS: ::DWORD = SP_PROT_TLS1_X_SERVER | SP_PROT_SSL3_SERVER; +pub const SP_PROT_SSL3TLS1_X: ::DWORD = SP_PROT_SSL3 | SP_PROT_TLS1_X; +pub const SP_PROT_X_CLIENTS: ::DWORD = SP_PROT_CLIENTS | SP_PROT_TLS1_X_CLIENT + | SP_PROT_DTLS1_X_CLIENT; +pub const SP_PROT_X_SERVERS: ::DWORD = SP_PROT_SERVERS | SP_PROT_TLS1_X_SERVER + | SP_PROT_DTLS1_X_SERVER; +//716 +pub const SCHANNEL_SECRET_TYPE_CAPI: ::DWORD = 0x00000001; +pub const SCHANNEL_SECRET_PRIVKEY: ::DWORD = 0x00000002; +pub const SCH_CRED_X509_CERTCHAIN: ::DWORD = 0x00000001; +pub const SCH_CRED_X509_CAPI: ::DWORD = 0x00000002; +pub const SCH_CRED_CERT_CONTEXT: ::DWORD = 0x00000003; +//838 +pub const SSL_CRACK_CERTIFICATE_NAME: &'static str = "SslCrackCertificate"; +pub const SSL_FREE_CERTIFICATE_NAME: &'static str = "SslFreeCertificate"; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/servprov.rs b/bash-5.1/vendor/winapi-0.2.8/src/servprov.rs new file mode 100644 index 0000000..8b37ba8 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/servprov.rs @@ -0,0 +1,11 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of servprov.h +pub type LPSERVICEPROVIDER = *mut IServiceProvider; +RIDL!( +interface IServiceProvider(IServiceProviderVtbl): IUnknown(IUnknownVtbl) { + fn QueryService( + &mut self, guidService: ::REFGUID, riid: ::REFIID, ppvObject: *mut *mut ::c_void + ) -> ::HRESULT +} +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/setupapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/setupapi.rs new file mode 100644 index 0000000..cf3149d --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/setupapi.rs @@ -0,0 +1,1301 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Windows NT Setup and Device Installer services +pub const LINE_LEN: usize = 256; +pub const MAX_INF_STRING_LENGTH: usize = 4096; +pub const MAX_INF_SECTION_NAME_LENGTH: usize = 255; +pub const MAX_TITLE_LEN: usize = 60; +pub const MAX_INSTRUCTION_LEN: usize = 256; +pub const MAX_LABEL_LEN: usize = 30; +pub const MAX_SERVICE_NAME_LEN: usize = 256; +pub const MAX_SUBTITLE_LEN: usize = 256; +pub const SP_MAX_MACHINENAME_LENGTH: usize = ::MAX_PATH + 3; +pub type HINF = ::PVOID; +STRUCT!{struct INFCONTEXT { + Inf: ::PVOID, + CurrentInf: ::PVOID, + Section: ::UINT, + Line: ::UINT, +}} +pub type PINFCONTEXT = *mut INFCONTEXT; +STRUCT!{struct SP_INF_INFORMATION { + InfStyle: ::DWORD, + InfCount: ::DWORD, + VersionData: [::BYTE; ::ANYSIZE_ARRAY], +}} +pub type PSP_INF_INFORMATION = *mut SP_INF_INFORMATION; +STRUCT!{struct SP_ALTPLATFORM_INFO_V2 { + cbSize: ::DWORD, + Platform: ::DWORD, + MajorVersion: ::DWORD, + MinorVersion: ::DWORD, + ProcessorArchitecture: ::WORD, + Reserved: ::WORD, + FirstValidatedMajorVersion: ::DWORD, + FirstValidatedMinorVersion: ::DWORD, +}} +UNION!(SP_ALTPLATFORM_INFO_V2, Reserved, Flags, Flags_mut, ::WORD); +pub type PSP_ALTPLATFORM_INFO_V2 = *mut SP_ALTPLATFORM_INFO_V2; +STRUCT!{struct SP_ALTPLATFORM_INFO_V1 { + cbSize: ::DWORD, + Platform: ::DWORD, + MajorVersion: ::DWORD, + MinorVersion: ::DWORD, + ProcessorArchitecture: ::WORD, + Reserved: ::WORD, +}} +pub type PSP_ALTPLATFORM_INFO_V1 = *mut SP_ALTPLATFORM_INFO_V1; +pub type SP_ALTPLATFORM_INFO = SP_ALTPLATFORM_INFO_V2; +pub type PSP_ALTPLATFORM_INFO = PSP_ALTPLATFORM_INFO_V2; +pub const SP_ALTPLATFORM_FLAGS_VERSION_RANGE: ::WORD = 0x0001; +STRUCT!{nodebug struct SP_ORIGINAL_FILE_INFO_A { + cbSize: ::DWORD, + OriginalInfName: [::CHAR; ::MAX_PATH], + OriginalCatalogName: [::CHAR; ::MAX_PATH], +}} +pub type PSP_ORIGINAL_FILE_INFO_A = *mut SP_ORIGINAL_FILE_INFO_A; +STRUCT!{nodebug struct SP_ORIGINAL_FILE_INFO_W { + cbSize: ::DWORD, + OriginalInfName: [::WCHAR; ::MAX_PATH], + OriginalCatalogName: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_ORIGINAL_FILE_INFO_W = *mut SP_ORIGINAL_FILE_INFO_W; +pub const INF_STYLE_NONE: ::DWORD = 0x00000000; +pub const INF_STYLE_OLDNT: ::DWORD = 0x00000001; +pub const INF_STYLE_WIN4: ::DWORD = 0x00000002; +pub const INF_STYLE_CACHE_ENABLE: ::DWORD = 0x00000010; +pub const INF_STYLE_CACHE_DISABLE: ::DWORD = 0x00000020; +pub const INF_STYLE_CACHE_IGNORE: ::DWORD = 0x00000040; +pub const DIRID_ABSOLUTE: ::DWORD = -1i32 as ::DWORD; +pub const DIRID_ABSOLUTE_16BIT: ::DWORD = 0xffff; +pub const DIRID_NULL: ::DWORD = 0; +pub const DIRID_SRCPATH: ::DWORD = 1; +pub const DIRID_WINDOWS: ::DWORD = 10; +pub const DIRID_SYSTEM: ::DWORD = 11; +pub const DIRID_DRIVERS: ::DWORD = 12; +pub const DIRID_IOSUBSYS: ::DWORD = DIRID_DRIVERS; +pub const DIRID_DRIVER_STORE: ::DWORD = 13; +pub const DIRID_INF: ::DWORD = 17; +pub const DIRID_HELP: ::DWORD = 18; +pub const DIRID_FONTS: ::DWORD = 20; +pub const DIRID_VIEWERS: ::DWORD = 21; +pub const DIRID_COLOR: ::DWORD = 23; +pub const DIRID_APPS: ::DWORD = 24; +pub const DIRID_SHARED: ::DWORD = 25; +pub const DIRID_BOOT: ::DWORD = 30; +pub const DIRID_SYSTEM16: ::DWORD = 50; +pub const DIRID_SPOOL: ::DWORD = 51; +pub const DIRID_SPOOLDRIVERS: ::DWORD = 52; +pub const DIRID_USERPROFILE: ::DWORD = 53; +pub const DIRID_LOADER: ::DWORD = 54; +pub const DIRID_PRINTPROCESSOR: ::DWORD = 55; +pub const DIRID_DEFAULT: ::DWORD = DIRID_SYSTEM; +pub const DIRID_COMMON_STARTMENU: ::DWORD = 16406; +pub const DIRID_COMMON_PROGRAMS: ::DWORD = 16407; +pub const DIRID_COMMON_STARTUP: ::DWORD = 16408; +pub const DIRID_COMMON_DESKTOPDIRECTORY: ::DWORD = 16409; +pub const DIRID_COMMON_FAVORITES: ::DWORD = 16415; +pub const DIRID_COMMON_APPDATA: ::DWORD = 16419; +pub const DIRID_PROGRAM_FILES: ::DWORD = 16422; +pub const DIRID_SYSTEM_X86: ::DWORD = 16425; +pub const DIRID_PROGRAM_FILES_X86: ::DWORD = 16426; +pub const DIRID_PROGRAM_FILES_COMMON: ::DWORD = 16427; +pub const DIRID_PROGRAM_FILES_COMMONX86: ::DWORD = 16428; +pub const DIRID_COMMON_TEMPLATES: ::DWORD = 16429; +pub const DIRID_COMMON_DOCUMENTS: ::DWORD = 16430; +pub const DIRID_USER: ::DWORD = 0x8000; +pub type PSP_FILE_CALLBACK_A = Option<unsafe extern "system" fn( + Context: ::PVOID, Notification: ::UINT, Param1: ::UINT_PTR, Param2: ::UINT_PTR, +) -> ::UINT>; +pub type PSP_FILE_CALLBACK_W = Option<unsafe extern "system" fn( + Context: ::PVOID, Notification: ::UINT, Param1: ::UINT_PTR, Param2: ::UINT_PTR, +) -> ::UINT>; +pub const SPFILENOTIFY_STARTQUEUE: ::UINT = 0x00000001; +pub const SPFILENOTIFY_ENDQUEUE: ::UINT = 0x00000002; +pub const SPFILENOTIFY_STARTSUBQUEUE: ::UINT = 0x00000003; +pub const SPFILENOTIFY_ENDSUBQUEUE: ::UINT = 0x00000004; +pub const SPFILENOTIFY_STARTDELETE: ::UINT = 0x00000005; +pub const SPFILENOTIFY_ENDDELETE: ::UINT = 0x00000006; +pub const SPFILENOTIFY_DELETEERROR: ::UINT = 0x00000007; +pub const SPFILENOTIFY_STARTRENAME: ::UINT = 0x00000008; +pub const SPFILENOTIFY_ENDRENAME: ::UINT = 0x00000009; +pub const SPFILENOTIFY_RENAMEERROR: ::UINT = 0x0000000a; +pub const SPFILENOTIFY_STARTCOPY: ::UINT = 0x0000000b; +pub const SPFILENOTIFY_ENDCOPY: ::UINT = 0x0000000c; +pub const SPFILENOTIFY_COPYERROR: ::UINT = 0x0000000d; +pub const SPFILENOTIFY_NEEDMEDIA: ::UINT = 0x0000000e; +pub const SPFILENOTIFY_QUEUESCAN: ::UINT = 0x0000000f; +pub const SPFILENOTIFY_CABINETINFO: ::UINT = 0x00000010; +pub const SPFILENOTIFY_FILEINCABINET: ::UINT = 0x00000011; +pub const SPFILENOTIFY_NEEDNEWCABINET: ::UINT = 0x00000012; +pub const SPFILENOTIFY_FILEEXTRACTED: ::UINT = 0x00000013; +pub const SPFILENOTIFY_FILEOPDELAYED: ::UINT = 0x00000014; +pub const SPFILENOTIFY_STARTBACKUP: ::UINT = 0x00000015; +pub const SPFILENOTIFY_BACKUPERROR: ::UINT = 0x00000016; +pub const SPFILENOTIFY_ENDBACKUP: ::UINT = 0x00000017; +pub const SPFILENOTIFY_QUEUESCAN_EX: ::UINT = 0x00000018; +pub const SPFILENOTIFY_STARTREGISTRATION: ::UINT = 0x00000019; +pub const SPFILENOTIFY_ENDREGISTRATION: ::UINT = 0x00000020; +pub const SPFILENOTIFY_QUEUESCAN_SIGNERINFO: ::UINT = 0x00000040; +pub const SPFILENOTIFY_LANGMISMATCH: ::UINT = 0x00010000; +pub const SPFILENOTIFY_TARGETEXISTS: ::UINT = 0x00020000; +pub const SPFILENOTIFY_TARGETNEWER: ::UINT = 0x00040000; +pub const FILEOP_COPY: ::UINT = 0; +pub const FILEOP_RENAME: ::UINT = 1; +pub const FILEOP_DELETE: ::UINT = 2; +pub const FILEOP_BACKUP: ::UINT = 3; +pub const FILEOP_ABORT: ::UINT = 0; +pub const FILEOP_DOIT: ::UINT = 1; +pub const FILEOP_SKIP: ::UINT = 2; +pub const FILEOP_RETRY: ::UINT = FILEOP_DOIT; +pub const FILEOP_NEWPATH: ::UINT = 4; +pub const COPYFLG_WARN_IF_SKIP: ::UINT = 0x00000001; +pub const COPYFLG_NOSKIP: ::UINT = 0x00000002; +pub const COPYFLG_NOVERSIONCHECK: ::UINT = 0x00000004; +pub const COPYFLG_FORCE_FILE_IN_USE: ::UINT = 0x00000008; +pub const COPYFLG_NO_OVERWRITE: ::UINT = 0x00000010; +pub const COPYFLG_NO_VERSION_DIALOG: ::UINT = 0x00000020; +pub const COPYFLG_OVERWRITE_OLDER_ONLY: ::UINT = 0x00000040; +pub const COPYFLG_PROTECTED_WINDOWS_DRIVER_FILE: ::UINT = 0x00000100; +pub const COPYFLG_REPLACEONLY: ::UINT = 0x00000400; +pub const COPYFLG_NODECOMP: ::UINT = 0x00000800; +pub const COPYFLG_REPLACE_BOOT_FILE: ::UINT = 0x00001000; +pub const COPYFLG_NOPRUNE: ::UINT = 0x00002000; +pub const COPYFLG_IN_USE_TRY_RENAME: ::UINT = 0x00004000; +pub const DELFLG_IN_USE: ::UINT = 0x00000001; +pub const DELFLG_IN_USE1: ::UINT = 0x00010000; +STRUCT!{struct FILEPATHS_A { + Target: ::PCSTR, + Source: ::PCSTR, + Win32Error: ::UINT, + Flags: ::DWORD, +}} +pub type PFILEPATHS_A = *mut FILEPATHS_A; +STRUCT!{struct FILEPATHS_W { + Target: ::PCWSTR, + Source: ::PCWSTR, + Win32Error: ::UINT, + Flags: ::DWORD, +}} +pub type PFILEPATHS_W = *mut FILEPATHS_W; +STRUCT!{struct FILEPATHS_SIGNERINFO_A { + Target: ::PCSTR, + Source: ::PCSTR, + Win32Error: ::UINT, + Flags: ::DWORD, + DigitalSigner: ::PCSTR, + Version: ::PCSTR, + CatalogFile: ::PCSTR, +}} +pub type PFILEPATHS_SIGNERINFO_A = *mut FILEPATHS_SIGNERINFO_A; +STRUCT!{struct FILEPATHS_SIGNERINFO_W { + Target: ::PCWSTR, + Source: ::PCWSTR, + Win32Error: ::UINT, + Flags: ::DWORD, + DigitalSigner: ::PCWSTR, + Version: ::PCWSTR, + CatalogFile: ::PCWSTR, +}} +pub type PFILEPATHS_SIGNERINFO_W = *mut FILEPATHS_SIGNERINFO_W; +STRUCT!{struct SOURCE_MEDIA_A { + Reserved: ::PCSTR, + Tagfile: ::PCSTR, + Description: ::PCSTR, + SourcePath: ::PCSTR, + SourceFile: ::PCSTR, + Flags: ::DWORD, +}} +pub type PSOURCE_MEDIA_A = *mut SOURCE_MEDIA_A; +STRUCT!{struct SOURCE_MEDIA_W { + Reserved: ::PCWSTR, + Tagfile: ::PCWSTR, + Description: ::PCWSTR, + SourcePath: ::PCWSTR, + SourceFile: ::PCWSTR, + Flags: ::DWORD, +}} +pub type PSOURCE_MEDIA_W = *mut SOURCE_MEDIA_W; +STRUCT!{struct CABINET_INFO_A { + CabinetPath: ::PCSTR, + CabinetFile: ::PCSTR, + DiskName: ::PCSTR, + SetId: ::USHORT, + CabinetNumber: ::USHORT, +}} +pub type PCABINET_INFO_A = *mut CABINET_INFO_A; +STRUCT!{struct CABINET_INFO_W { + CabinetPath: ::PCWSTR, + CabinetFile: ::PCWSTR, + DiskName: ::PCWSTR, + SetId: ::USHORT, + CabinetNumber: ::USHORT, +}} +pub type PCABINET_INFO_W = *mut CABINET_INFO_W; +STRUCT!{nodebug struct FILE_IN_CABINET_INFO_A { + NameInCabinet: ::PCSTR, + FileSize: ::DWORD, + Win32Error: ::DWORD, + DosDate: ::WORD, + DosTime: ::WORD, + DosAttribs: ::WORD, + FullTargetName: [::CHAR; ::MAX_PATH], +}} +pub type PFILE_IN_CABINET_INFO_A = *mut FILE_IN_CABINET_INFO_A; +STRUCT!{nodebug struct FILE_IN_CABINET_INFO_W { + NameInCabinet: ::PCWSTR, + FileSize: ::DWORD, + Win32Error: ::DWORD, + DosDate: ::WORD, + DosTime: ::WORD, + DosAttribs: ::WORD, + FullTargetName: [::WCHAR; ::MAX_PATH], +}} +pub type PFILE_IN_CABINET_INFO_W = *mut FILE_IN_CABINET_INFO_W; +STRUCT!{struct SP_REGISTER_CONTROL_STATUSA { + cbSize: ::DWORD, + FileName: ::PCSTR, + Win32Error: ::DWORD, + FailureCode: ::DWORD, +}} +pub type PSP_REGISTER_CONTROL_STATUSA = *mut SP_REGISTER_CONTROL_STATUSA; +STRUCT!{struct SP_REGISTER_CONTROL_STATUSW { + cbSize: ::DWORD, + FileName: ::PCWSTR, + Win32Error: ::DWORD, + FailureCode: ::DWORD, +}} +pub type PSP_REGISTER_CONTROL_STATUSW = *mut SP_REGISTER_CONTROL_STATUSW; +pub const SPREG_SUCCESS: ::DWORD = 0x00000000; +pub const SPREG_LOADLIBRARY: ::DWORD = 0x00000001; +pub const SPREG_GETPROCADDR: ::DWORD = 0x00000002; +pub const SPREG_REGSVR: ::DWORD = 0x00000003; +pub const SPREG_DLLINSTALL: ::DWORD = 0x00000004; +pub const SPREG_TIMEOUT: ::DWORD = 0x00000005; +pub const SPREG_UNKNOWN: ::DWORD = 0xFFFFFFFF; +pub type HSPFILEQ = ::PVOID; +STRUCT!{struct SP_FILE_COPY_PARAMS_A { + cbSize: ::DWORD, + QueueHandle: HSPFILEQ, + SourceRootPath: ::PCSTR, + SourcePath: ::PCSTR, + SourceFilename: ::PCSTR, + SourceDescription: ::PCSTR, + SourceTagfile: ::PCSTR, + TargetDirectory: ::PCSTR, + TargetFilename: ::PCSTR, + CopyStyle: ::DWORD, + LayoutInf: HINF, + SecurityDescriptor: ::PCSTR, +}} +pub type PSP_FILE_COPY_PARAMS_A = *mut SP_FILE_COPY_PARAMS_A; +STRUCT!{struct SP_FILE_COPY_PARAMS_W { + cbSize: ::DWORD, + QueueHandle: HSPFILEQ, + SourceRootPath: ::PCWSTR, + SourcePath: ::PCWSTR, + SourceFilename: ::PCWSTR, + SourceDescription: ::PCWSTR, + SourceTagfile: ::PCWSTR, + TargetDirectory: ::PCWSTR, + TargetFilename: ::PCWSTR, + CopyStyle: ::DWORD, + LayoutInf: HINF, + SecurityDescriptor: ::PCWSTR, +}} +pub type PSP_FILE_COPY_PARAMS_W = *mut SP_FILE_COPY_PARAMS_W; +pub type HDSKSPC = ::PVOID; +pub type HDEVINFO = ::PVOID; +STRUCT!{struct SP_DEVINFO_DATA { + cbSize: ::DWORD, + ClassGuid: ::GUID, + DevInst: ::DWORD, + Reserved: ::ULONG_PTR, +}} +pub type PSP_DEVINFO_DATA = *mut SP_DEVINFO_DATA; +STRUCT!{struct SP_DEVICE_INTERFACE_DATA { + cbSize: ::DWORD, + InterfaceClassGuid: ::GUID, + Flags: ::DWORD, + Reserved: ::ULONG_PTR, +}} +pub type PSP_DEVICE_INTERFACE_DATA = *mut SP_DEVICE_INTERFACE_DATA; +pub const SPINT_ACTIVE: ::DWORD = 0x00000001; +pub const SPINT_DEFAULT: ::DWORD = 0x00000002; +pub const SPINT_REMOVED: ::DWORD = 0x00000004; +pub type SP_INTERFACE_DEVICE_DATA = SP_DEVICE_INTERFACE_DATA; +pub type PSP_INTERFACE_DEVICE_DATA = PSP_DEVICE_INTERFACE_DATA; +pub const SPID_ACTIVE: ::DWORD = SPINT_ACTIVE; +pub const SPID_DEFAULT: ::DWORD = SPINT_DEFAULT; +pub const SPID_REMOVED: ::DWORD = SPINT_REMOVED; +STRUCT!{struct SP_DEVICE_INTERFACE_DETAIL_DATA_A { + cbSize: ::DWORD, + DevicePath: [::CHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DEVICE_INTERFACE_DETAIL_DATA_A = *mut SP_DEVICE_INTERFACE_DETAIL_DATA_A; +STRUCT!{struct SP_DEVICE_INTERFACE_DETAIL_DATA_W { + cbSize: ::DWORD, + DevicePath: [::WCHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DEVICE_INTERFACE_DETAIL_DATA_W = *mut SP_DEVICE_INTERFACE_DETAIL_DATA_W; +STRUCT!{nodebug struct SP_DEVINFO_LIST_DETAIL_DATA_A { + cbSize: ::DWORD, + ClassGuid: ::GUID, + RemoteMachineHandle: ::HANDLE, + RemoteMachineName: [::CHAR; SP_MAX_MACHINENAME_LENGTH], +}} +pub type PSP_DEVINFO_LIST_DETAIL_DATA_A = *mut SP_DEVINFO_LIST_DETAIL_DATA_A; +STRUCT!{nodebug struct SP_DEVINFO_LIST_DETAIL_DATA_W { + cbSize: ::DWORD, + ClassGuid: ::GUID, + RemoteMachineHandle: ::HANDLE, + RemoteMachineName: [::WCHAR; SP_MAX_MACHINENAME_LENGTH], +}} +pub type PSP_DEVINFO_LIST_DETAIL_DATA_W = *mut SP_DEVINFO_LIST_DETAIL_DATA_W; +pub const DIF_SELECTDEVICE: DI_FUNCTION = 0x00000001; +pub const DIF_INSTALLDEVICE: DI_FUNCTION = 0x00000002; +pub const DIF_ASSIGNRESOURCES: DI_FUNCTION = 0x00000003; +pub const DIF_PROPERTIES: DI_FUNCTION = 0x00000004; +pub const DIF_REMOVE: DI_FUNCTION = 0x00000005; +pub const DIF_FIRSTTIMESETUP: DI_FUNCTION = 0x00000006; +pub const DIF_FOUNDDEVICE: DI_FUNCTION = 0x00000007; +pub const DIF_SELECTCLASSDRIVERS: DI_FUNCTION = 0x00000008; +pub const DIF_VALIDATECLASSDRIVERS: DI_FUNCTION = 0x00000009; +pub const DIF_INSTALLCLASSDRIVERS: DI_FUNCTION = 0x0000000A; +pub const DIF_CALCDISKSPACE: DI_FUNCTION = 0x0000000B; +pub const DIF_DESTROYPRIVATEDATA: DI_FUNCTION = 0x0000000C; +pub const DIF_VALIDATEDRIVER: DI_FUNCTION = 0x0000000D; +pub const DIF_DETECT: DI_FUNCTION = 0x0000000F; +pub const DIF_INSTALLWIZARD: DI_FUNCTION = 0x00000010; +pub const DIF_DESTROYWIZARDDATA: DI_FUNCTION = 0x00000011; +pub const DIF_PROPERTYCHANGE: DI_FUNCTION = 0x00000012; +pub const DIF_ENABLECLASS: DI_FUNCTION = 0x00000013; +pub const DIF_DETECTVERIFY: DI_FUNCTION = 0x00000014; +pub const DIF_INSTALLDEVICEFILES: DI_FUNCTION = 0x00000015; +pub const DIF_UNREMOVE: DI_FUNCTION = 0x00000016; +pub const DIF_SELECTBESTCOMPATDRV: DI_FUNCTION = 0x00000017; +pub const DIF_ALLOW_INSTALL: DI_FUNCTION = 0x00000018; +pub const DIF_REGISTERDEVICE: DI_FUNCTION = 0x00000019; +pub const DIF_NEWDEVICEWIZARD_PRESELECT: DI_FUNCTION = 0x0000001A; +pub const DIF_NEWDEVICEWIZARD_SELECT: DI_FUNCTION = 0x0000001B; +pub const DIF_NEWDEVICEWIZARD_PREANALYZE: DI_FUNCTION = 0x0000001C; +pub const DIF_NEWDEVICEWIZARD_POSTANALYZE: DI_FUNCTION = 0x0000001D; +pub const DIF_NEWDEVICEWIZARD_FINISHINSTALL: DI_FUNCTION = 0x0000001E; +pub const DIF_UNUSED1: DI_FUNCTION = 0x0000001F; +pub const DIF_INSTALLINTERFACES: DI_FUNCTION = 0x00000020; +pub const DIF_DETECTCANCEL: DI_FUNCTION = 0x00000021; +pub const DIF_REGISTER_COINSTALLERS: DI_FUNCTION = 0x00000022; +pub const DIF_ADDPROPERTYPAGE_ADVANCED: DI_FUNCTION = 0x00000023; +pub const DIF_ADDPROPERTYPAGE_BASIC: DI_FUNCTION = 0x00000024; +pub const DIF_RESERVED1: DI_FUNCTION = 0x00000025; +pub const DIF_TROUBLESHOOTER: DI_FUNCTION = 0x00000026; +pub const DIF_POWERMESSAGEWAKE: DI_FUNCTION = 0x00000027; +pub const DIF_ADDREMOTEPROPERTYPAGE_ADVANCED: DI_FUNCTION = 0x00000028; +pub const DIF_UPDATEDRIVER_UI: DI_FUNCTION = 0x00000029; +pub const DIF_FINISHINSTALL_ACTION: DI_FUNCTION = 0x0000002A; +pub const DIF_RESERVED2: DI_FUNCTION = 0x00000030; +pub const DIF_MOVEDEVICE: DI_FUNCTION = 0x0000000E; +pub type DI_FUNCTION = ::UINT; +STRUCT!{nodebug struct SP_DEVINSTALL_PARAMS_A { + cbSize: ::DWORD, + Flags: ::DWORD, + FlagsEx: ::DWORD, + hwndParent: ::HWND, + InstallMsgHandler: PSP_FILE_CALLBACK_A, + InstallMsgHandlerContext: ::PVOID, + FileQueue: HSPFILEQ, + ClassInstallReserved: ::ULONG_PTR, + Reserved: ::DWORD, + DriverPath: [::CHAR; ::MAX_PATH], +}} +pub type PSP_DEVINSTALL_PARAMS_A = *mut SP_DEVINSTALL_PARAMS_A; +STRUCT!{nodebug struct SP_DEVINSTALL_PARAMS_W { + cbSize: ::DWORD, + Flags: ::DWORD, + FlagsEx: ::DWORD, + hwndParent: ::HWND, + InstallMsgHandler: PSP_FILE_CALLBACK_W, + InstallMsgHandlerContext: ::PVOID, + FileQueue: HSPFILEQ, + ClassInstallReserved: ::ULONG_PTR, + Reserved: ::DWORD, + DriverPath: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_DEVINSTALL_PARAMS_W = *mut SP_DEVINSTALL_PARAMS_W; +pub const DI_SHOWOEM: ::DWORD = 0x00000001; +pub const DI_SHOWCOMPAT: ::DWORD = 0x00000002; +pub const DI_SHOWCLASS: ::DWORD = 0x00000004; +pub const DI_SHOWALL: ::DWORD = 0x00000007; +pub const DI_NOVCP: ::DWORD = 0x00000008; +pub const DI_DIDCOMPAT: ::DWORD = 0x00000010; +pub const DI_DIDCLASS: ::DWORD = 0x00000020; +pub const DI_AUTOASSIGNRES: ::DWORD = 0x00000040; +pub const DI_NEEDRESTART: ::DWORD = 0x00000080; +pub const DI_NEEDREBOOT: ::DWORD = 0x00000100; +pub const DI_NOBROWSE: ::DWORD = 0x00000200; +pub const DI_MULTMFGS: ::DWORD = 0x00000400; +pub const DI_DISABLED: ::DWORD = 0x00000800; +pub const DI_GENERALPAGE_ADDED: ::DWORD = 0x00001000; +pub const DI_RESOURCEPAGE_ADDED: ::DWORD = 0x00002000; +pub const DI_PROPERTIES_CHANGE: ::DWORD = 0x00004000; +pub const DI_INF_IS_SORTED: ::DWORD = 0x00008000; +pub const DI_ENUMSINGLEINF: ::DWORD = 0x00010000; +pub const DI_DONOTCALLCONFIGMG: ::DWORD = 0x00020000; +pub const DI_INSTALLDISABLED: ::DWORD = 0x00040000; +pub const DI_COMPAT_FROM_CLASS: ::DWORD = 0x00080000; +pub const DI_CLASSINSTALLPARAMS: ::DWORD = 0x00100000; +pub const DI_NODI_DEFAULTACTION: ::DWORD = 0x00200000; +pub const DI_QUIETINSTALL: ::DWORD = 0x00800000; +pub const DI_NOFILECOPY: ::DWORD = 0x01000000; +pub const DI_FORCECOPY: ::DWORD = 0x02000000; +pub const DI_DRIVERPAGE_ADDED: ::DWORD = 0x04000000; +pub const DI_USECI_SELECTSTRINGS: ::DWORD = 0x08000000; +pub const DI_OVERRIDE_INFFLAGS: ::DWORD = 0x10000000; +pub const DI_PROPS_NOCHANGEUSAGE: ::DWORD = 0x20000000; +pub const DI_NOSELECTICONS: ::DWORD = 0x40000000; +pub const DI_NOWRITE_IDS: ::DWORD = 0x80000000; +pub const DI_FLAGSEX_RESERVED2: ::DWORD = 0x00000001; +pub const DI_FLAGSEX_RESERVED3: ::DWORD = 0x00000002; +pub const DI_FLAGSEX_CI_FAILED: ::DWORD = 0x00000004; +pub const DI_FLAGSEX_FINISHINSTALL_ACTION: ::DWORD = 0x00000008; +pub const DI_FLAGSEX_DIDINFOLIST: ::DWORD = 0x00000010; +pub const DI_FLAGSEX_DIDCOMPATINFO: ::DWORD = 0x00000020; +pub const DI_FLAGSEX_FILTERCLASSES: ::DWORD = 0x00000040; +pub const DI_FLAGSEX_SETFAILEDINSTALL: ::DWORD = 0x00000080; +pub const DI_FLAGSEX_DEVICECHANGE: ::DWORD = 0x00000100; +pub const DI_FLAGSEX_ALWAYSWRITEIDS: ::DWORD = 0x00000200; +pub const DI_FLAGSEX_PROPCHANGE_PENDING: ::DWORD = 0x00000400; +pub const DI_FLAGSEX_ALLOWEXCLUDEDDRVS: ::DWORD = 0x00000800; +pub const DI_FLAGSEX_NOUIONQUERYREMOVE: ::DWORD = 0x00001000; +pub const DI_FLAGSEX_USECLASSFORCOMPAT: ::DWORD = 0x00002000; +pub const DI_FLAGSEX_RESERVED4: ::DWORD = 0x00004000; +pub const DI_FLAGSEX_NO_DRVREG_MODIFY: ::DWORD = 0x00008000; +pub const DI_FLAGSEX_IN_SYSTEM_SETUP: ::DWORD = 0x00010000; +pub const DI_FLAGSEX_INET_DRIVER: ::DWORD = 0x00020000; +pub const DI_FLAGSEX_APPENDDRIVERLIST: ::DWORD = 0x00040000; +pub const DI_FLAGSEX_PREINSTALLBACKUP: ::DWORD = 0x00080000; +pub const DI_FLAGSEX_BACKUPONREPLACE: ::DWORD = 0x00100000; +pub const DI_FLAGSEX_DRIVERLIST_FROM_URL: ::DWORD = 0x00200000; +pub const DI_FLAGSEX_RESERVED1: ::DWORD = 0x00400000; +pub const DI_FLAGSEX_EXCLUDE_OLD_INET_DRIVERS: ::DWORD = 0x00800000; +pub const DI_FLAGSEX_POWERPAGE_ADDED: ::DWORD = 0x01000000; +pub const DI_FLAGSEX_FILTERSIMILARDRIVERS: ::DWORD = 0x02000000; +pub const DI_FLAGSEX_INSTALLEDDRIVER: ::DWORD = 0x04000000; +pub const DI_FLAGSEX_NO_CLASSLIST_NODE_MERGE: ::DWORD = 0x08000000; +pub const DI_FLAGSEX_ALTPLATFORM_DRVSEARCH: ::DWORD = 0x10000000; +pub const DI_FLAGSEX_RESTART_DEVICE_ONLY: ::DWORD = 0x20000000; +pub const DI_FLAGSEX_RECURSIVESEARCH: ::DWORD = 0x40000000; +pub const DI_FLAGSEX_SEARCH_PUBLISHED_INFS: ::DWORD = 0x80000000; +STRUCT!{struct SP_CLASSINSTALL_HEADER { + cbSize: ::DWORD, + InstallFunction: DI_FUNCTION, +}} +pub type PSP_CLASSINSTALL_HEADER = *mut SP_CLASSINSTALL_HEADER; +STRUCT!{struct SP_ENABLECLASS_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + ClassGuid: ::GUID, + EnableMessage: ::DWORD, +}} +pub type PSP_ENABLECLASS_PARAMS = *mut SP_ENABLECLASS_PARAMS; +pub const ENABLECLASS_QUERY: ::DWORD = 0; +pub const ENABLECLASS_SUCCESS: ::DWORD = 1; +pub const ENABLECLASS_FAILURE: ::DWORD = 2; +pub const DICS_ENABLE: ::DWORD = 0x00000001; +pub const DICS_DISABLE: ::DWORD = 0x00000002; +pub const DICS_PROPCHANGE: ::DWORD = 0x00000003; +pub const DICS_START: ::DWORD = 0x00000004; +pub const DICS_STOP: ::DWORD = 0x00000005; +pub const DICS_FLAG_GLOBAL: ::DWORD = 0x00000001; +pub const DICS_FLAG_CONFIGSPECIFIC: ::DWORD = 0x00000002; +pub const DICS_FLAG_CONFIGGENERAL: ::DWORD = 0x00000004; +STRUCT!{struct SP_PROPCHANGE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + StateChange: ::DWORD, + Scope: ::DWORD, + HwProfile: ::DWORD, +}} +pub type PSP_PROPCHANGE_PARAMS = *mut SP_PROPCHANGE_PARAMS; +STRUCT!{struct SP_REMOVEDEVICE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Scope: ::DWORD, + HwProfile: ::DWORD, +}} +pub type PSP_REMOVEDEVICE_PARAMS = *mut SP_REMOVEDEVICE_PARAMS; +pub const DI_REMOVEDEVICE_GLOBAL: ::DWORD = 0x00000001; +pub const DI_REMOVEDEVICE_CONFIGSPECIFIC: ::DWORD = 0x00000002; +STRUCT!{struct SP_UNREMOVEDEVICE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Scope: ::DWORD, + HwProfile: ::DWORD, +}} +pub type PSP_UNREMOVEDEVICE_PARAMS = *mut SP_UNREMOVEDEVICE_PARAMS; +pub const DI_UNREMOVEDEVICE_CONFIGSPECIFIC: ::DWORD = 0x00000002; +STRUCT!{nodebug struct SP_SELECTDEVICE_PARAMS_A { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Title: [::CHAR; MAX_TITLE_LEN], + Instructions: [::CHAR; MAX_INSTRUCTION_LEN], + ListLabel: [::CHAR; MAX_LABEL_LEN], + SubTitle: [::CHAR; MAX_SUBTITLE_LEN], + Reserved: [::BYTE; 2], +}} +pub type PSP_SELECTDEVICE_PARAMS_A = *mut SP_SELECTDEVICE_PARAMS_A; +STRUCT!{nodebug struct SP_SELECTDEVICE_PARAMS_W { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Title: [::WCHAR; MAX_TITLE_LEN], + Instructions: [::WCHAR; MAX_INSTRUCTION_LEN], + ListLabel: [::WCHAR; MAX_LABEL_LEN], + SubTitle: [::WCHAR; MAX_SUBTITLE_LEN], +}} +pub type PSP_SELECTDEVICE_PARAMS_W = *mut SP_SELECTDEVICE_PARAMS_W; +pub type PDETECT_PROGRESS_NOTIFY = Option<unsafe extern "system" fn( + ProgressNotifyParam: ::PVOID, DetectComplete: ::DWORD, +) -> ::BOOL>; +STRUCT!{nodebug struct SP_DETECTDEVICE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + DetectProgressNotify: PDETECT_PROGRESS_NOTIFY, + ProgressNotifyParam: ::PVOID, +}} +pub type PSP_DETECTDEVICE_PARAMS = *mut SP_DETECTDEVICE_PARAMS; +pub const MAX_INSTALLWIZARD_DYNAPAGES: usize = 20; +STRUCT!{struct SP_INSTALLWIZARD_DATA { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Flags: ::DWORD, + DynamicPages: [::HPROPSHEETPAGE; MAX_INSTALLWIZARD_DYNAPAGES], + NumDynamicPages: ::DWORD, + DynamicPageFlags: ::DWORD, + PrivateFlags: ::DWORD, + PrivateData: ::LPARAM, + hwndWizardDlg: ::HWND, +}} +pub type PSP_INSTALLWIZARD_DATA = *mut SP_INSTALLWIZARD_DATA; +pub const NDW_INSTALLFLAG_DIDFACTDEFS: ::DWORD = 0x00000001; +pub const NDW_INSTALLFLAG_HARDWAREALLREADYIN: ::DWORD = 0x00000002; +pub const NDW_INSTALLFLAG_NEEDRESTART: ::DWORD = DI_NEEDRESTART; +pub const NDW_INSTALLFLAG_NEEDREBOOT: ::DWORD = DI_NEEDREBOOT; +pub const NDW_INSTALLFLAG_NEEDSHUTDOWN: ::DWORD = 0x00000200; +pub const NDW_INSTALLFLAG_EXPRESSINTRO: ::DWORD = 0x00000400; +pub const NDW_INSTALLFLAG_SKIPISDEVINSTALLED: ::DWORD = 0x00000800; +pub const NDW_INSTALLFLAG_NODETECTEDDEVS: ::DWORD = 0x00001000; +pub const NDW_INSTALLFLAG_INSTALLSPECIFIC: ::DWORD = 0x00002000; +pub const NDW_INSTALLFLAG_SKIPCLASSLIST: ::DWORD = 0x00004000; +pub const NDW_INSTALLFLAG_CI_PICKED_OEM: ::DWORD = 0x00008000; +pub const NDW_INSTALLFLAG_PCMCIAMODE: ::DWORD = 0x00010000; +pub const NDW_INSTALLFLAG_PCMCIADEVICE: ::DWORD = 0x00020000; +pub const NDW_INSTALLFLAG_USERCANCEL: ::DWORD = 0x00040000; +pub const NDW_INSTALLFLAG_KNOWNCLASS: ::DWORD = 0x00080000; +pub const DYNAWIZ_FLAG_PAGESADDED: ::DWORD = 0x00000001; +pub const DYNAWIZ_FLAG_ANALYZE_HANDLECONFLICT: ::DWORD = 0x00000008; +pub const DYNAWIZ_FLAG_INSTALLDET_NEXT: ::DWORD = 0x00000002; +pub const DYNAWIZ_FLAG_INSTALLDET_PREV: ::DWORD = 0x00000004; +pub const MIN_IDD_DYNAWIZ_RESOURCE_ID: ::c_int = 10000; +pub const MAX_IDD_DYNAWIZ_RESOURCE_ID: ::c_int = 11000; +pub const IDD_DYNAWIZ_FIRSTPAGE: ::c_int = 10000; +pub const IDD_DYNAWIZ_SELECT_PREVPAGE: ::c_int = 10001; +pub const IDD_DYNAWIZ_SELECT_NEXTPAGE: ::c_int = 10002; +pub const IDD_DYNAWIZ_ANALYZE_PREVPAGE: ::c_int = 10003; +pub const IDD_DYNAWIZ_ANALYZE_NEXTPAGE: ::c_int = 10004; +pub const IDD_DYNAWIZ_SELECTDEV_PAGE: ::c_int = 10009; +pub const IDD_DYNAWIZ_ANALYZEDEV_PAGE: ::c_int = 10010; +pub const IDD_DYNAWIZ_INSTALLDETECTEDDEVS_PAGE: ::c_int = 10011; +pub const IDD_DYNAWIZ_SELECTCLASS_PAGE: ::c_int = 10012; +pub const IDD_DYNAWIZ_INSTALLDETECTED_PREVPAGE: ::c_int = 10006; +pub const IDD_DYNAWIZ_INSTALLDETECTED_NEXTPAGE: ::c_int = 10007; +pub const IDD_DYNAWIZ_INSTALLDETECTED_NODEVS: ::c_int = 10008; +STRUCT!{struct SP_NEWDEVICEWIZARD_DATA { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Flags: ::DWORD, + DynamicPages: [::HPROPSHEETPAGE; MAX_INSTALLWIZARD_DYNAPAGES], + NumDynamicPages: ::DWORD, + hwndWizardDlg: ::HWND, +}} +pub type PSP_NEWDEVICEWIZARD_DATA = *mut SP_NEWDEVICEWIZARD_DATA; +pub type SP_ADDPROPERTYPAGE_DATA = SP_NEWDEVICEWIZARD_DATA; +pub type PSP_ADDPROPERTYPAGE_DATA = PSP_NEWDEVICEWIZARD_DATA; +STRUCT!{nodebug struct SP_TROUBLESHOOTER_PARAMS_A { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + ChmFile: [::CHAR; ::MAX_PATH], + HtmlTroubleShooter: [::CHAR; ::MAX_PATH], +}} +pub type PSP_TROUBLESHOOTER_PARAMS_A = *mut SP_TROUBLESHOOTER_PARAMS_A; +STRUCT!{nodebug struct SP_TROUBLESHOOTER_PARAMS_W { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + ChmFile: [::WCHAR; ::MAX_PATH], + HtmlTroubleShooter: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_TROUBLESHOOTER_PARAMS_W = *mut SP_TROUBLESHOOTER_PARAMS_W; +STRUCT!{nodebug struct SP_POWERMESSAGEWAKE_PARAMS_A { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + PowerMessageWake: [::CHAR; LINE_LEN * 2], +}} +pub type PSP_POWERMESSAGEWAKE_PARAMS_A = *mut SP_POWERMESSAGEWAKE_PARAMS_A; +STRUCT!{nodebug struct SP_POWERMESSAGEWAKE_PARAMS_W { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + PowerMessageWake: [::WCHAR; LINE_LEN * 2], +}} +pub type PSP_POWERMESSAGEWAKE_PARAMS_W = *mut SP_POWERMESSAGEWAKE_PARAMS_W; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V2_A { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::CHAR; LINE_LEN], + MfgName: [::CHAR; LINE_LEN], + ProviderName: [::CHAR; LINE_LEN], + DriverDate: ::FILETIME, + DriverVersion: ::DWORDLONG, +}} +pub type PSP_DRVINFO_DATA_V2_A = *mut SP_DRVINFO_DATA_V2_A; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V2_W { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::WCHAR; LINE_LEN], + MfgName: [::WCHAR; LINE_LEN], + ProviderName: [::WCHAR; LINE_LEN], + DriverDate: ::FILETIME, + DriverVersion: ::DWORDLONG, +}} +pub type PSP_DRVINFO_DATA_V2_W = *mut SP_DRVINFO_DATA_V2_W; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V1_A { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::CHAR; LINE_LEN], + MfgName: [::CHAR; LINE_LEN], + ProviderName: [::CHAR; LINE_LEN], +}} +pub type PSP_DRVINFO_DATA_V1_A = *mut SP_DRVINFO_DATA_V1_A; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V1_W { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::WCHAR; LINE_LEN], + MfgName: [::WCHAR; LINE_LEN], + ProviderName: [::WCHAR; LINE_LEN], +}} +pub type PSP_DRVINFO_DATA_V1_W = *mut SP_DRVINFO_DATA_V1_W; +pub type SP_DRVINFO_DATA_A = SP_DRVINFO_DATA_V2_A; +pub type PSP_DRVINFO_DATA_A = PSP_DRVINFO_DATA_V2_A; +pub type SP_DRVINFO_DATA_W = SP_DRVINFO_DATA_V2_W; +pub type PSP_DRVINFO_DATA_W = PSP_DRVINFO_DATA_V2_W; +STRUCT!{nodebug struct SP_DRVINFO_DETAIL_DATA_A { + cbSize: ::DWORD, + InfDate: ::FILETIME, + CompatIDsOffset: ::DWORD, + CompatIDsLength: ::DWORD, + Reserved: ::ULONG_PTR, + SectionName: [::CHAR; LINE_LEN], + InfFileName: [::CHAR; ::MAX_PATH], + DrvDescription: [::CHAR; LINE_LEN], + HardwareID: [::CHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DRVINFO_DETAIL_DATA_A = *mut SP_DRVINFO_DETAIL_DATA_A; +STRUCT!{nodebug struct SP_DRVINFO_DETAIL_DATA_W { + cbSize: ::DWORD, + InfDate: ::FILETIME, + CompatIDsOffset: ::DWORD, + CompatIDsLength: ::DWORD, + Reserved: ::ULONG_PTR, + SectionName: [::WCHAR; LINE_LEN], + InfFileName: [::WCHAR; ::MAX_PATH], + DrvDescription: [::WCHAR; LINE_LEN], + HardwareID: [::WCHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DRVINFO_DETAIL_DATA_W = *mut SP_DRVINFO_DETAIL_DATA_W; +STRUCT!{struct SP_DRVINSTALL_PARAMS { + cbSize: ::DWORD, + Rank: ::DWORD, + Flags: ::DWORD, + PrivateData: ::DWORD_PTR, + Reserved: ::DWORD, +}} +pub type PSP_DRVINSTALL_PARAMS = *mut SP_DRVINSTALL_PARAMS; +pub const DNF_DUPDESC: ::DWORD = 0x00000001; +pub const DNF_OLDDRIVER: ::DWORD = 0x00000002; +pub const DNF_EXCLUDEFROMLIST: ::DWORD = 0x00000004; +pub const DNF_NODRIVER: ::DWORD = 0x00000008; +pub const DNF_LEGACYINF: ::DWORD = 0x00000010; +pub const DNF_CLASS_DRIVER: ::DWORD = 0x00000020; +pub const DNF_COMPATIBLE_DRIVER: ::DWORD = 0x00000040; +pub const DNF_INET_DRIVER: ::DWORD = 0x00000080; +pub const DNF_UNUSED1: ::DWORD = 0x00000100; +pub const DNF_UNUSED2: ::DWORD = 0x00000200; +pub const DNF_OLD_INET_DRIVER: ::DWORD = 0x00000400; +pub const DNF_BAD_DRIVER: ::DWORD = 0x00000800; +pub const DNF_DUPPROVIDER: ::DWORD = 0x00001000; +pub const DNF_INF_IS_SIGNED: ::DWORD = 0x00002000; +pub const DNF_OEM_F6_INF: ::DWORD = 0x00004000; +pub const DNF_DUPDRIVERVER: ::DWORD = 0x00008000; +pub const DNF_BASIC_DRIVER: ::DWORD = 0x00010000; +pub const DNF_AUTHENTICODE_SIGNED: ::DWORD = 0x00020000; +pub const DNF_INSTALLEDDRIVER: ::DWORD = 0x00040000; +pub const DNF_ALWAYSEXCLUDEFROMLIST: ::DWORD = 0x00080000; +pub const DNF_INBOX_DRIVER: ::DWORD = 0x00100000; +pub const DNF_REQUESTADDITIONALSOFTWARE: ::DWORD = 0x00200000; +pub const DNF_UNUSED_22: ::DWORD = 0x00400000; +pub const DNF_UNUSED_23: ::DWORD = 0x00800000; +pub const DNF_UNUSED_24: ::DWORD = 0x01000000; +pub const DNF_UNUSED_25: ::DWORD = 0x02000000; +pub const DNF_UNUSED_26: ::DWORD = 0x04000000; +pub const DNF_UNUSED_27: ::DWORD = 0x08000000; +pub const DNF_UNUSED_28: ::DWORD = 0x10000000; +pub const DNF_UNUSED_29: ::DWORD = 0x20000000; +pub const DNF_UNUSED_30: ::DWORD = 0x40000000; +pub const DNF_UNUSED_31: ::DWORD = 0x80000000; +pub type PSP_DETSIG_CMPPROC = Option<unsafe extern "system" fn( + DeviceInfoSet: HDEVINFO, NewDeviceData: PSP_DEVINFO_DATA, ExistingDeviceData: PSP_DEVINFO_DATA, + CompareContext: ::PVOID, +) -> ::DWORD>; +STRUCT!{struct COINSTALLER_CONTEXT_DATA { + PostProcessing: ::BOOL, + InstallResult: ::DWORD, + PrivateData: ::PVOID, +}} +pub type PCOINSTALLER_CONTEXT_DATA = *mut COINSTALLER_CONTEXT_DATA; +STRUCT!{struct SP_CLASSIMAGELIST_DATA { + cbSize: ::DWORD, + ImageList: ::HIMAGELIST, + Reserved: ::ULONG_PTR, +}} +pub type PSP_CLASSIMAGELIST_DATA = *mut SP_CLASSIMAGELIST_DATA; +STRUCT!{struct SP_PROPSHEETPAGE_REQUEST { + cbSize: ::DWORD, + PageRequested: ::DWORD, + DeviceInfoSet: HDEVINFO, + DeviceInfoData: PSP_DEVINFO_DATA, +}} +pub type PSP_PROPSHEETPAGE_REQUEST = *mut SP_PROPSHEETPAGE_REQUEST; +pub const SPPSR_SELECT_DEVICE_RESOURCES: ::DWORD = 1; +pub const SPPSR_ENUM_BASIC_DEVICE_PROPERTIES: ::DWORD = 2; +pub const SPPSR_ENUM_ADV_DEVICE_PROPERTIES: ::DWORD = 3; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V2_A { + cbSize: ::DWORD, + FullInfPath: [::CHAR; ::MAX_PATH], + FilenameOffset: ::INT, + ReinstallInstance: [::CHAR; ::MAX_PATH], +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V2_A = *mut SP_BACKUP_QUEUE_PARAMS_V2_A; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V2_W { + cbSize: ::DWORD, + FullInfPath: [::WCHAR; ::MAX_PATH], + FilenameOffset: ::INT, + ReinstallInstance: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V2_W = *mut SP_BACKUP_QUEUE_PARAMS_V2_W; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V1_A { + cbSize: ::DWORD, + FullInfPath: [::CHAR; ::MAX_PATH], + FilenameOffset: ::INT, +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V1_A = *mut SP_BACKUP_QUEUE_PARAMS_V1_A; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V1_W { + cbSize: ::DWORD, + FullInfPath: [::WCHAR; ::MAX_PATH], + FilenameOffset: ::INT, +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V1_W = *mut SP_BACKUP_QUEUE_PARAMS_V1_W; +pub type SP_BACKUP_QUEUE_PARAMS_A = SP_BACKUP_QUEUE_PARAMS_V2_A; +pub type PSP_BACKUP_QUEUE_PARAMS_A = PSP_BACKUP_QUEUE_PARAMS_V2_A; +pub type SP_BACKUP_QUEUE_PARAMS_W = SP_BACKUP_QUEUE_PARAMS_V2_W; +pub type PSP_BACKUP_QUEUE_PARAMS_W = PSP_BACKUP_QUEUE_PARAMS_V2_W; +pub const ERROR_EXPECTED_SECTION_NAME: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0; +pub const ERROR_BAD_SECTION_NAME_LINE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 1; +pub const ERROR_SECTION_NAME_TOO_LONG: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 2; +pub const ERROR_GENERAL_SYNTAX: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 3; +pub const ERROR_WRONG_INF_STYLE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x100; +pub const ERROR_SECTION_NOT_FOUND: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x101; +pub const ERROR_LINE_NOT_FOUND: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x102; +pub const ERROR_NO_BACKUP: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x103; +pub const ERROR_NO_ASSOCIATED_CLASS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x200; +pub const ERROR_CLASS_MISMATCH: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x201; +pub const ERROR_DUPLICATE_FOUND: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x202; +pub const ERROR_NO_DRIVER_SELECTED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x203; +pub const ERROR_KEY_DOES_NOT_EXIST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x204; +pub const ERROR_INVALID_DEVINST_NAME: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x205; +pub const ERROR_INVALID_CLASS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x206; +pub const ERROR_DEVINST_ALREADY_EXISTS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x207; +pub const ERROR_DEVINFO_NOT_REGISTERED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x208; +pub const ERROR_INVALID_REG_PROPERTY: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x209; +pub const ERROR_NO_INF: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x20A; +pub const ERROR_NO_SUCH_DEVINST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x20B; +pub const ERROR_CANT_LOAD_CLASS_ICON: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x20C; +pub const ERROR_INVALID_CLASS_INSTALLER: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x20D; +pub const ERROR_DI_DO_DEFAULT: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x20E; +pub const ERROR_DI_NOFILECOPY: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x20F; +pub const ERROR_INVALID_HWPROFILE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x210; +pub const ERROR_NO_DEVICE_SELECTED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x211; +pub const ERROR_DEVINFO_LIST_LOCKED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x212; +pub const ERROR_DEVINFO_DATA_LOCKED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x213; +pub const ERROR_DI_BAD_PATH: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x214; +pub const ERROR_NO_CLASSINSTALL_PARAMS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x215; +pub const ERROR_FILEQUEUE_LOCKED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x216; +pub const ERROR_BAD_SERVICE_INSTALLSECT: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x217; +pub const ERROR_NO_CLASS_DRIVER_LIST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x218; +pub const ERROR_NO_ASSOCIATED_SERVICE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x219; +pub const ERROR_NO_DEFAULT_DEVICE_INTERFACE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21A; +pub const ERROR_DEVICE_INTERFACE_ACTIVE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21B; +pub const ERROR_DEVICE_INTERFACE_REMOVED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21C; +pub const ERROR_BAD_INTERFACE_INSTALLSECT: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21D; +pub const ERROR_NO_SUCH_INTERFACE_CLASS: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21E; +pub const ERROR_INVALID_REFERENCE_STRING: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21F; +pub const ERROR_INVALID_MACHINENAME: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x220; +pub const ERROR_REMOTE_COMM_FAILURE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x221; +pub const ERROR_MACHINE_UNAVAILABLE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x222; +pub const ERROR_NO_CONFIGMGR_SERVICES: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x223; +pub const ERROR_INVALID_PROPPAGE_PROVIDER: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x224; +pub const ERROR_NO_SUCH_DEVICE_INTERFACE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x225; +pub const ERROR_DI_POSTPROCESSING_REQUIRED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x226; +pub const ERROR_INVALID_COINSTALLER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x227; +pub const ERROR_NO_COMPAT_DRIVERS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x228; +pub const ERROR_NO_DEVICE_ICON: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x229; +pub const ERROR_INVALID_INF_LOGCONFIG: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22A; +pub const ERROR_DI_DONT_INSTALL: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22B; +pub const ERROR_INVALID_FILTER_DRIVER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22C; +pub const ERROR_NON_WINDOWS_NT_DRIVER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22D; +pub const ERROR_NON_WINDOWS_DRIVER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22E; +pub const ERROR_NO_CATALOG_FOR_OEM_INF: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22F; +pub const ERROR_DEVINSTALL_QUEUE_NONNATIVE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x230; +pub const ERROR_NOT_DISABLEABLE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x231; +pub const ERROR_CANT_REMOVE_DEVINST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x232; +pub const ERROR_INVALID_TARGET: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x233; +pub const ERROR_DRIVER_NONNATIVE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x234; +pub const ERROR_IN_WOW64: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x235; +pub const ERROR_SET_SYSTEM_RESTORE_POINT: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x236; +pub const ERROR_SCE_DISABLED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x238; +pub const ERROR_UNKNOWN_EXCEPTION: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x239; +pub const ERROR_PNP_REGISTRY_ERROR: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x23A; +pub const ERROR_REMOTE_REQUEST_UNSUPPORTED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x23B; +pub const ERROR_NOT_AN_INSTALLED_OEM_INF: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x23C; +pub const ERROR_INF_IN_USE_BY_DEVICES: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x23D; +pub const ERROR_DI_FUNCTION_OBSOLETE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x23E; +pub const ERROR_NO_AUTHENTICODE_CATALOG: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x23F; +pub const ERROR_AUTHENTICODE_DISALLOWED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x240; +pub const ERROR_AUTHENTICODE_TRUSTED_PUBLISHER: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x241; +pub const ERROR_AUTHENTICODE_TRUST_NOT_ESTABLISHED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x242; +pub const ERROR_AUTHENTICODE_PUBLISHER_NOT_TRUSTED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x243; +pub const ERROR_SIGNATURE_OSATTRIBUTE_MISMATCH: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x244; +pub const ERROR_ONLY_VALIDATE_VIA_AUTHENTICODE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x245; +pub const ERROR_DEVICE_INSTALLER_NOT_READY: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x246; +pub const ERROR_DRIVER_STORE_ADD_FAILED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x247; +pub const ERROR_DEVICE_INSTALL_BLOCKED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x248; +pub const ERROR_DRIVER_INSTALL_BLOCKED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x249; +pub const ERROR_WRONG_INF_TYPE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x24A; +pub const ERROR_FILE_HASH_NOT_IN_CATALOG: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x24B; +pub const ERROR_DRIVER_STORE_DELETE_FAILED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x24C; +pub const ERROR_UNRECOVERABLE_STACK_OVERFLOW: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x300; +pub const EXCEPTION_SPAPI_UNRECOVERABLE_STACK_OVERFLOW: ::DWORD = + ERROR_UNRECOVERABLE_STACK_OVERFLOW; +pub const ERROR_NO_DEFAULT_INTERFACE_DEVICE: ::DWORD = ERROR_NO_DEFAULT_DEVICE_INTERFACE; +pub const ERROR_INTERFACE_DEVICE_ACTIVE: ::DWORD = ERROR_DEVICE_INTERFACE_ACTIVE; +pub const ERROR_INTERFACE_DEVICE_REMOVED: ::DWORD = ERROR_DEVICE_INTERFACE_REMOVED; +pub const ERROR_NO_SUCH_INTERFACE_DEVICE: ::DWORD = ERROR_NO_SUCH_DEVICE_INTERFACE; +pub const ERROR_NOT_INSTALLED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x1000; +pub const INFINFO_INF_SPEC_IS_HINF: ::DWORD = 1; +pub const INFINFO_INF_NAME_IS_ABSOLUTE: ::DWORD = 2; +pub const INFINFO_DEFAULT_SEARCH: ::DWORD = 3; +pub const INFINFO_REVERSE_DEFAULT_SEARCH: ::DWORD = 4; +pub const INFINFO_INF_PATH_LIST_SEARCH: ::DWORD = 5; +pub const FILE_COMPRESSION_NONE: ::UINT = 0; +pub const FILE_COMPRESSION_WINLZA: ::UINT = 1; +pub const FILE_COMPRESSION_MSZIP: ::UINT = 2; +pub const FILE_COMPRESSION_NTCAB: ::UINT = 3; +pub const SRCLIST_TEMPORARY: ::DWORD = 0x00000001; +pub const SRCLIST_NOBROWSE: ::DWORD = 0x00000002; +pub const SRCLIST_SYSTEM: ::DWORD = 0x00000010; +pub const SRCLIST_USER: ::DWORD = 0x00000020; +pub const SRCLIST_SYSIFADMIN: ::DWORD = 0x00000040; +pub const SRCLIST_SUBDIRS: ::DWORD = 0x00000100; +pub const SRCLIST_APPEND: ::DWORD = 0x00000200; +pub const SRCLIST_NOSTRIPPLATFORM: ::DWORD = 0x00000400; +pub const IDF_NOBROWSE: ::DWORD = 0x00000001; +pub const IDF_NOSKIP: ::DWORD = 0x00000002; +pub const IDF_NODETAILS: ::DWORD = 0x00000004; +pub const IDF_NOCOMPRESSED: ::DWORD = 0x00000008; +pub const IDF_CHECKFIRST: ::DWORD = 0x00000100; +pub const IDF_NOBEEP: ::DWORD = 0x00000200; +pub const IDF_NOFOREGROUND: ::DWORD = 0x00000400; +pub const IDF_WARNIFSKIP: ::DWORD = 0x00000800; +pub const IDF_NOREMOVABLEMEDIAPROMPT: ::DWORD = 0x00001000; +pub const IDF_USEDISKNAMEASPROMPT: ::DWORD = 0x00002000; +pub const IDF_OEMDISK: ::DWORD = 0x80000000; +pub const DPROMPT_SUCCESS: ::UINT = 0; +pub const DPROMPT_CANCEL: ::UINT = 1; +pub const DPROMPT_SKIPFILE: ::UINT = 2; +pub const DPROMPT_BUFFERTOOSMALL: ::UINT = 3; +pub const DPROMPT_OUTOFMEMORY: ::UINT = 4; +pub const SETDIRID_NOT_FULL_PATH: ::DWORD = 0x00000001; +pub const SRCINFO_PATH: ::UINT = 1; +pub const SRCINFO_TAGFILE: ::UINT = 2; +pub const SRCINFO_DESCRIPTION: ::UINT = 3; +pub const SRCINFO_FLAGS: ::UINT = 4; +pub const SRCINFO_TAGFILE2: ::UINT = 4; +pub const SRC_FLAGS_CABFILE: ::UINT = 0x0010; +pub const SP_COPY_DELETESOURCE: ::DWORD = 0x0000001; +pub const SP_COPY_REPLACEONLY: ::DWORD = 0x0000002; +pub const SP_COPY_NEWER: ::DWORD = 0x0000004; +pub const SP_COPY_NEWER_OR_SAME: ::DWORD = SP_COPY_NEWER; +pub const SP_COPY_NOOVERWRITE: ::DWORD = 0x0000008; +pub const SP_COPY_NODECOMP: ::DWORD = 0x0000010; +pub const SP_COPY_LANGUAGEAWARE: ::DWORD = 0x0000020; +pub const SP_COPY_SOURCE_ABSOLUTE: ::DWORD = 0x0000040; +pub const SP_COPY_SOURCEPATH_ABSOLUTE: ::DWORD = 0x0000080; +pub const SP_COPY_IN_USE_NEEDS_REBOOT: ::DWORD = 0x0000100; +pub const SP_COPY_FORCE_IN_USE: ::DWORD = 0x0000200; +pub const SP_COPY_NOSKIP: ::DWORD = 0x0000400; +pub const SP_FLAG_CABINETCONTINUATION: ::DWORD = 0x0000800; +pub const SP_COPY_FORCE_NOOVERWRITE: ::DWORD = 0x0001000; +pub const SP_COPY_FORCE_NEWER: ::DWORD = 0x0002000; +pub const SP_COPY_WARNIFSKIP: ::DWORD = 0x0004000; +pub const SP_COPY_NOBROWSE: ::DWORD = 0x0008000; +pub const SP_COPY_NEWER_ONLY: ::DWORD = 0x0010000; +pub const SP_COPY_RESERVED: ::DWORD = 0x0020000; +pub const SP_COPY_OEMINF_CATALOG_ONLY: ::DWORD = 0x0040000; +pub const SP_COPY_REPLACE_BOOT_FILE: ::DWORD = 0x0080000; +pub const SP_COPY_NOPRUNE: ::DWORD = 0x0100000; +pub const SP_COPY_OEM_F6_INF: ::DWORD = 0x0200000; +pub const SP_COPY_ALREADYDECOMP: ::DWORD = 0x0400000; +pub const SP_COPY_WINDOWS_SIGNED: ::DWORD = 0x1000000; +pub const SP_COPY_PNPLOCKED: ::DWORD = 0x2000000; +pub const SP_COPY_IN_USE_TRY_RENAME: ::DWORD = 0x4000000; +pub const SP_COPY_INBOX_INF: ::DWORD = 0x8000000; +pub const SP_COPY_HARDLINK: ::DWORD = 0x10000000; +pub const SP_BACKUP_BACKUPPASS: ::DWORD = 0x00000001; +pub const SP_BACKUP_DEMANDPASS: ::DWORD = 0x00000002; +pub const SP_BACKUP_SPECIAL: ::DWORD = 0x00000004; +pub const SP_BACKUP_BOOTFILE: ::DWORD = 0x00000008; +pub const SPQ_SCAN_FILE_PRESENCE: ::DWORD = 0x00000001; +pub const SPQ_SCAN_FILE_VALIDITY: ::DWORD = 0x00000002; +pub const SPQ_SCAN_USE_CALLBACK: ::DWORD = 0x00000004; +pub const SPQ_SCAN_USE_CALLBACKEX: ::DWORD = 0x00000008; +pub const SPQ_SCAN_INFORM_USER: ::DWORD = 0x00000010; +pub const SPQ_SCAN_PRUNE_COPY_QUEUE: ::DWORD = 0x00000020; +pub const SPQ_SCAN_USE_CALLBACK_SIGNERINFO: ::DWORD = 0x00000040; +pub const SPQ_SCAN_PRUNE_DELREN: ::DWORD = 0x00000080; +pub const SPQ_SCAN_FILE_PRESENCE_WITHOUT_SOURCE: ::DWORD = 0x00000100; +pub const SPQ_SCAN_FILE_COMPARISON: ::DWORD = 0x00000200; +pub const SPQ_SCAN_ACTIVATE_DRP: ::DWORD = 0x00000400; +pub const SPQ_DELAYED_COPY: ::DWORD = 0x00000001; +pub const SPQ_FLAG_BACKUP_AWARE: ::DWORD = 0x00000001; +pub const SPQ_FLAG_ABORT_IF_UNSIGNED: ::DWORD = 0x00000002; +pub const SPQ_FLAG_FILES_MODIFIED: ::DWORD = 0x00000004; +pub const SPQ_FLAG_DO_SHUFFLEMOVE: ::DWORD = 0x00000008; +pub const SPQ_FLAG_VALID: ::DWORD = 0x0000000F; +pub const SPOST_NONE: ::DWORD = 0; +pub const SPOST_PATH: ::DWORD = 1; +pub const SPOST_URL: ::DWORD = 2; +pub const SPOST_MAX: ::DWORD = 3; +pub const SUOI_FORCEDELETE: ::DWORD = 0x00000001; +pub const SUOI_INTERNAL1: ::DWORD = 0x00000002; +pub const SPDSL_IGNORE_DISK: ::UINT = 0x00000001; +pub const SPDSL_DISALLOW_NEGATIVE_ADJUST: ::UINT = 0x00000002; +pub const SPFILEQ_FILE_IN_USE: ::INT = 0x00000001; +pub const SPFILEQ_REBOOT_RECOMMENDED: ::INT = 0x00000002; +pub const SPFILEQ_REBOOT_IN_PROGRESS: ::INT = 0x00000004; +pub const FLG_ADDREG_DELREG_BIT: ::DWORD = 0x00008000; +pub const FLG_ADDREG_BINVALUETYPE: ::DWORD = 0x00000001; +pub const FLG_ADDREG_NOCLOBBER: ::DWORD = 0x00000002; +pub const FLG_ADDREG_DELVAL: ::DWORD = 0x00000004; +pub const FLG_ADDREG_APPEND: ::DWORD = 0x00000008; +pub const FLG_ADDREG_KEYONLY: ::DWORD = 0x00000010; +pub const FLG_ADDREG_OVERWRITEONLY: ::DWORD = 0x00000020; +pub const FLG_ADDREG_64BITKEY: ::DWORD = 0x00001000; +pub const FLG_ADDREG_KEYONLY_COMMON: ::DWORD = 0x00002000; +pub const FLG_ADDREG_32BITKEY: ::DWORD = 0x00004000; +pub const FLG_ADDREG_TYPE_MASK: ::DWORD = 0xFFFF0000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_ADDREG_TYPE_SZ: ::DWORD = 0x00000000; +pub const FLG_ADDREG_TYPE_MULTI_SZ: ::DWORD = 0x00010000; +pub const FLG_ADDREG_TYPE_EXPAND_SZ: ::DWORD = 0x00020000; +pub const FLG_ADDREG_TYPE_BINARY: ::DWORD = 0x00000000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_ADDREG_TYPE_DWORD: ::DWORD = 0x00010000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_ADDREG_TYPE_NONE: ::DWORD = 0x00020000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_DELREG_VALUE: ::DWORD = 0x00000000; +pub const FLG_DELREG_TYPE_MASK: ::DWORD = FLG_ADDREG_TYPE_MASK; +pub const FLG_DELREG_TYPE_SZ: ::DWORD = FLG_ADDREG_TYPE_SZ; +pub const FLG_DELREG_TYPE_MULTI_SZ: ::DWORD = FLG_ADDREG_TYPE_MULTI_SZ; +pub const FLG_DELREG_TYPE_EXPAND_SZ: ::DWORD = FLG_ADDREG_TYPE_EXPAND_SZ; +pub const FLG_DELREG_TYPE_BINARY: ::DWORD = FLG_ADDREG_TYPE_BINARY; +pub const FLG_DELREG_TYPE_DWORD: ::DWORD = FLG_ADDREG_TYPE_DWORD; +pub const FLG_DELREG_TYPE_NONE: ::DWORD = FLG_ADDREG_TYPE_NONE; +pub const FLG_DELREG_64BITKEY: ::DWORD = FLG_ADDREG_64BITKEY; +pub const FLG_DELREG_KEYONLY_COMMON: ::DWORD = FLG_ADDREG_KEYONLY_COMMON; +pub const FLG_DELREG_32BITKEY: ::DWORD = FLG_ADDREG_32BITKEY; +pub const FLG_DELREG_OPERATION_MASK: ::DWORD = 0x000000FE; +pub const FLG_DELREG_MULTI_SZ_DELSTRING: ::DWORD = FLG_DELREG_TYPE_MULTI_SZ | FLG_ADDREG_DELREG_BIT + | 0x00000002; +pub const FLG_BITREG_CLEARBITS: ::DWORD = 0x00000000; +pub const FLG_BITREG_SETBITS: ::DWORD = 0x00000001; +pub const FLG_BITREG_64BITKEY: ::DWORD = 0x00001000; +pub const FLG_BITREG_32BITKEY: ::DWORD = 0x00004000; +pub const FLG_INI2REG_64BITKEY: ::DWORD = 0x00001000; +pub const FLG_INI2REG_32BITKEY: ::DWORD = 0x00004000; +pub const FLG_REGSVR_DLLREGISTER: ::DWORD = 0x00000001; +pub const FLG_REGSVR_DLLINSTALL: ::DWORD = 0x00000002; +pub const FLG_PROFITEM_CURRENTUSER: ::DWORD = 0x00000001; +pub const FLG_PROFITEM_DELETE: ::DWORD = 0x00000002; +pub const FLG_PROFITEM_GROUP: ::DWORD = 0x00000004; +pub const FLG_PROFITEM_CSIDL: ::DWORD = 0x00000008; +pub const FLG_ADDPROPERTY_NOCLOBBER: ::DWORD = 0x00000001; +pub const FLG_ADDPROPERTY_OVERWRITEONLY: ::DWORD = 0x00000002; +pub const FLG_ADDPROPERTY_APPEND: ::DWORD = 0x00000004; +pub const FLG_ADDPROPERTY_OR: ::DWORD = 0x00000008; +pub const FLG_ADDPROPERTY_AND: ::DWORD = 0x00000010; +pub const FLG_DELPROPERTY_MULTI_SZ_DELSTRING: ::DWORD = 0x00000001; +pub const SPINST_LOGCONFIG: ::UINT = 0x00000001; +pub const SPINST_INIFILES: ::UINT = 0x00000002; +pub const SPINST_REGISTRY: ::UINT = 0x00000004; +pub const SPINST_INI2REG: ::UINT = 0x00000008; +pub const SPINST_FILES: ::UINT = 0x00000010; +pub const SPINST_BITREG: ::UINT = 0x00000020; +pub const SPINST_REGSVR: ::UINT = 0x00000040; +pub const SPINST_UNREGSVR: ::UINT = 0x00000080; +pub const SPINST_PROFILEITEMS: ::UINT = 0x00000100; +pub const SPINST_COPYINF: ::UINT = 0x00000200; +pub const SPINST_PROPERTIES: ::UINT = 0x00000400; +pub const SPINST_ALL: ::UINT = 0x000007ff; +pub const SPINST_SINGLESECTION: ::UINT = 0x00010000; +pub const SPINST_LOGCONFIG_IS_FORCED: ::UINT = 0x00020000; +pub const SPINST_LOGCONFIGS_ARE_OVERRIDES: ::UINT = 0x00040000; +pub const SPINST_REGISTERCALLBACKAWARE: ::UINT = 0x00080000; +pub const SPINST_DEVICEINSTALL: ::UINT = 0x00100000; +pub const SPSVCINST_TAGTOFRONT: ::DWORD = 0x00000001; +pub const SPSVCINST_ASSOCSERVICE: ::DWORD = 0x00000002; +pub const SPSVCINST_DELETEEVENTLOGENTRY: ::DWORD = 0x00000004; +pub const SPSVCINST_NOCLOBBER_DISPLAYNAME: ::DWORD = 0x00000008; +pub const SPSVCINST_NOCLOBBER_STARTTYPE: ::DWORD = 0x00000010; +pub const SPSVCINST_NOCLOBBER_ERRORCONTROL: ::DWORD = 0x00000020; +pub const SPSVCINST_NOCLOBBER_LOADORDERGROUP: ::DWORD = 0x00000040; +pub const SPSVCINST_NOCLOBBER_DEPENDENCIES: ::DWORD = 0x00000080; +pub const SPSVCINST_NOCLOBBER_DESCRIPTION: ::DWORD = 0x00000100; +pub const SPSVCINST_STOPSERVICE: ::DWORD = 0x00000200; +pub const SPSVCINST_CLOBBER_SECURITY: ::DWORD = 0x00000400; +pub const SPSVCINST_STARTSERVICE: ::DWORD = 0x00000800; +pub const SPSVCINST_NOCLOBBER_REQUIREDPRIVILEGES: ::DWORD = 0x00001000; +pub type HSPFILELOG = ::PVOID; +pub const SPFILELOG_SYSTEMLOG: ::DWORD = 0x00000001; +pub const SPFILELOG_FORCENEW: ::DWORD = 0x00000002; +pub const SPFILELOG_QUERYONLY: ::DWORD = 0x00000004; +pub const SPFILELOG_OEMFILE: ::DWORD = 0x00000001; +ENUM!{enum SetupFileLogInfo { + SetupFileLogSourceFilename, + SetupFileLogChecksum, + SetupFileLogDiskTagfile, + SetupFileLogDiskDescription, + SetupFileLogOtherInfo, + SetupFileLogMax, +}} +pub type LogSeverity = ::DWORD; +pub const LogSevInformation: LogSeverity = 0x00000000; +pub const LogSevWarning: LogSeverity = 0x00000001; +pub const LogSevError: LogSeverity = 0x00000002; +pub const LogSevFatalError: LogSeverity = 0x00000003; +pub const LogSevMaximum: LogSeverity = 0x00000004; +pub const DICD_GENERATE_ID: ::DWORD = 0x00000001; +pub const DICD_INHERIT_CLASSDRVS: ::DWORD = 0x00000002; +pub const DIOD_INHERIT_CLASSDRVS: ::DWORD = 0x00000002; +pub const DIOD_CANCEL_REMOVE: ::DWORD = 0x00000004; +pub const DIODI_NO_ADD: ::DWORD = 0x00000001; +pub const SPRDI_FIND_DUPS: ::DWORD = 0x00000001; +pub const SPDIT_NODRIVER: ::DWORD = 0x00000000; +pub const SPDIT_CLASSDRIVER: ::DWORD = 0x00000001; +pub const SPDIT_COMPATDRIVER: ::DWORD = 0x00000002; +pub const DIGCF_DEFAULT: ::DWORD = 0x00000001; +pub const DIGCF_PRESENT: ::DWORD = 0x00000002; +pub const DIGCF_ALLCLASSES: ::DWORD = 0x00000004; +pub const DIGCF_PROFILE: ::DWORD = 0x00000008; +pub const DIGCF_DEVICEINTERFACE: ::DWORD = 0x00000010; +pub const DIBCI_NOINSTALLCLASS: ::DWORD = 0x00000001; +pub const DIBCI_NODISPLAYCLASS: ::DWORD = 0x00000002; +pub const DIOCR_INSTALLER: ::DWORD = 0x00000001; +pub const DIOCR_INTERFACE: ::DWORD = 0x00000002; +pub const DIREG_DEV: ::DWORD = 0x00000001; +pub const DIREG_DRV: ::DWORD = 0x00000002; +pub const DIREG_BOTH: ::DWORD = 0x00000004; +pub const DICLASSPROP_INSTALLER: ::DWORD = 0x00000001; +pub const DICLASSPROP_INTERFACE: ::DWORD = 0x00000002; +pub const SPDRP_DEVICEDESC: ::DWORD = 0x00000000; +pub const SPDRP_HARDWAREID: ::DWORD = 0x00000001; +pub const SPDRP_COMPATIBLEIDS: ::DWORD = 0x00000002; +pub const SPDRP_UNUSED0: ::DWORD = 0x00000003; +pub const SPDRP_SERVICE: ::DWORD = 0x00000004; +pub const SPDRP_UNUSED1: ::DWORD = 0x00000005; +pub const SPDRP_UNUSED2: ::DWORD = 0x00000006; +pub const SPDRP_CLASS: ::DWORD = 0x00000007; +pub const SPDRP_CLASSGUID: ::DWORD = 0x00000008; +pub const SPDRP_DRIVER: ::DWORD = 0x00000009; +pub const SPDRP_CONFIGFLAGS: ::DWORD = 0x0000000A; +pub const SPDRP_MFG: ::DWORD = 0x0000000B; +pub const SPDRP_FRIENDLYNAME: ::DWORD = 0x0000000C; +pub const SPDRP_LOCATION_INFORMATION: ::DWORD = 0x0000000D; +pub const SPDRP_PHYSICAL_DEVICE_OBJECT_NAME: ::DWORD = 0x0000000E; +pub const SPDRP_CAPABILITIES: ::DWORD = 0x0000000F; +pub const SPDRP_UI_NUMBER: ::DWORD = 0x00000010; +pub const SPDRP_UPPERFILTERS: ::DWORD = 0x00000011; +pub const SPDRP_LOWERFILTERS: ::DWORD = 0x00000012; +pub const SPDRP_BUSTYPEGUID: ::DWORD = 0x00000013; +pub const SPDRP_LEGACYBUSTYPE: ::DWORD = 0x00000014; +pub const SPDRP_BUSNUMBER: ::DWORD = 0x00000015; +pub const SPDRP_ENUMERATOR_NAME: ::DWORD = 0x00000016; +pub const SPDRP_SECURITY: ::DWORD = 0x00000017; +pub const SPDRP_SECURITY_SDS: ::DWORD = 0x00000018; +pub const SPDRP_DEVTYPE: ::DWORD = 0x00000019; +pub const SPDRP_EXCLUSIVE: ::DWORD = 0x0000001A; +pub const SPDRP_CHARACTERISTICS: ::DWORD = 0x0000001B; +pub const SPDRP_ADDRESS: ::DWORD = 0x0000001C; +pub const SPDRP_UI_NUMBER_DESC_FORMAT: ::DWORD = 0x0000001D; +pub const SPDRP_DEVICE_POWER_DATA: ::DWORD = 0x0000001E; +pub const SPDRP_REMOVAL_POLICY: ::DWORD = 0x0000001F; +pub const SPDRP_REMOVAL_POLICY_HW_DEFAULT: ::DWORD = 0x00000020; +pub const SPDRP_REMOVAL_POLICY_OVERRIDE: ::DWORD = 0x00000021; +pub const SPDRP_INSTALL_STATE: ::DWORD = 0x00000022; +pub const SPDRP_LOCATION_PATHS: ::DWORD = 0x00000023; +pub const SPDRP_BASE_CONTAINERID: ::DWORD = 0x00000024; +pub const SPDRP_MAXIMUM_PROPERTY: ::DWORD = 0x00000025; +pub const SPCRP_UPPERFILTERS: ::DWORD = 0x00000011; +pub const SPCRP_LOWERFILTERS: ::DWORD = 0x00000012; +pub const SPCRP_SECURITY: ::DWORD = 0x00000017; +pub const SPCRP_SECURITY_SDS: ::DWORD = 0x00000018; +pub const SPCRP_DEVTYPE: ::DWORD = 0x00000019; +pub const SPCRP_EXCLUSIVE: ::DWORD = 0x0000001A; +pub const SPCRP_CHARACTERISTICS: ::DWORD = 0x0000001B; +pub const SPCRP_MAXIMUM_PROPERTY: ::DWORD = 0x0000001C; +pub const DMI_MASK: ::DWORD = 0x00000001; +pub const DMI_BKCOLOR: ::DWORD = 0x00000002; +pub const DMI_USERECT: ::DWORD = 0x00000004; +pub const DIGCDP_FLAG_BASIC: ::DWORD = 0x00000001; +pub const DIGCDP_FLAG_ADVANCED: ::DWORD = 0x00000002; +pub const DIGCDP_FLAG_REMOTE_BASIC: ::DWORD = 0x00000003; +pub const DIGCDP_FLAG_REMOTE_ADVANCED: ::DWORD = 0x00000004; +pub const IDI_RESOURCEFIRST: ::c_int = 159; +pub const IDI_RESOURCE: ::c_int = 159; +pub const IDI_RESOURCELAST: ::c_int = 161; +pub const IDI_RESOURCEOVERLAYFIRST: ::c_int = 161; +pub const IDI_RESOURCEOVERLAYLAST: ::c_int = 161; +pub const IDI_CONFLICT: ::c_int = 161; +pub const IDI_CLASSICON_OVERLAYFIRST: ::c_int = 500; +pub const IDI_CLASSICON_OVERLAYLAST: ::c_int = 502; +pub const IDI_PROBLEM_OVL: ::c_int = 500; +pub const IDI_DISABLED_OVL: ::c_int = 501; +pub const IDI_FORCED_OVL: ::c_int = 502; +pub const SPWPT_SELECTDEVICE: ::DWORD = 0x00000001; +pub const SPWP_USE_DEVINFO_DATA: ::DWORD = 0x00000001; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V1_A { + cbSize: ::DWORD, + CatalogFile: [::CHAR; ::MAX_PATH], + DigitalSigner: [::CHAR; ::MAX_PATH], + DigitalSignerVersion: [::CHAR; ::MAX_PATH], +}} +pub type PSP_INF_SIGNER_INFO_V1_A = *mut SP_INF_SIGNER_INFO_V1_A; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V1_W { + cbSize: ::DWORD, + CatalogFile: [::WCHAR; ::MAX_PATH], + DigitalSigner: [::WCHAR; ::MAX_PATH], + DigitalSignerVersion: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_INF_SIGNER_INFO_V1_W = *mut SP_INF_SIGNER_INFO_V1_W; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V2_A { + cbSize: ::DWORD, + CatalogFile: [::CHAR; ::MAX_PATH], + DigitalSigner: [::CHAR; ::MAX_PATH], + DigitalSignerVersion: [::CHAR; ::MAX_PATH], + SignerScore: ::DWORD, +}} +pub type PSP_INF_SIGNER_INFO_V2_A = *mut SP_INF_SIGNER_INFO_V2_A; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V2_W { + cbSize: ::DWORD, + CatalogFile: [::WCHAR; ::MAX_PATH], + DigitalSigner: [::WCHAR; ::MAX_PATH], + DigitalSignerVersion: [::WCHAR; ::MAX_PATH], + SignerScore: ::DWORD, +}} +pub type PSP_INF_SIGNER_INFO_V2_W = *mut SP_INF_SIGNER_INFO_V2_W; +pub type SP_INF_SIGNER_INFO_A = SP_INF_SIGNER_INFO_V2_A; +pub type PSP_INF_SIGNER_INFO_A = PSP_INF_SIGNER_INFO_V2_A; +pub type SP_INF_SIGNER_INFO_W = SP_INF_SIGNER_INFO_V2_W; +pub type PSP_INF_SIGNER_INFO_W = PSP_INF_SIGNER_INFO_V2_W; +pub const SIGNERSCORE_UNKNOWN: ::DWORD = 0xFF000000; +pub const SIGNERSCORE_W9X_SUSPECT: ::DWORD = 0xC0000000; +pub const SIGNERSCORE_UNSIGNED: ::DWORD = 0x80000000; +pub const SIGNERSCORE_AUTHENTICODE: ::DWORD = 0x0F000000; +pub const SIGNERSCORE_WHQL: ::DWORD = 0x0D000005; +pub const SIGNERSCORE_UNCLASSIFIED: ::DWORD = 0x0D000004; +pub const SIGNERSCORE_INBOX: ::DWORD = 0x0D000003; +pub const SIGNERSCORE_LOGO_STANDARD: ::DWORD = 0x0D000002; +pub const SIGNERSCORE_LOGO_PREMIUM: ::DWORD = 0x0D000001; +pub const SIGNERSCORE_MASK: ::DWORD = 0xFF000000; +pub const SIGNERSCORE_SIGNED_MASK: ::DWORD = 0xF0000000; +pub const DICUSTOMDEVPROP_MERGE_MULTISZ: ::DWORD = 0x00000001; +pub const SCWMI_CLOBBER_SECURITY: ::DWORD = 0x00000001; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/shellapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/shellapi.rs new file mode 100644 index 0000000..6f253cf --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/shellapi.rs @@ -0,0 +1,62 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +// STUB +DECLARE_HANDLE!(HDROP, HDROP__); + +pub const NIM_ADD: ::DWORD = 0x00000000; +pub const NIM_MODIFY: ::DWORD = 0x00000001; +pub const NIM_DELETE: ::DWORD = 0x00000002; +pub const NIM_SETFOCUS: ::DWORD = 0x00000003; +pub const NIM_SETVERSION: ::DWORD = 0x00000004; +pub const NIF_MESSAGE: ::UINT = 0x00000001; +pub const NIF_ICON: ::UINT = 0x00000002; +pub const NIF_TIP: ::UINT = 0x00000004; +pub const NIF_STATE: ::UINT = 0x00000008; +pub const NIF_INFO: ::UINT = 0x00000010; +pub const NIF_GUID: ::UINT = 0x00000020; +pub const NIF_REALTIME: ::UINT = 0x00000040; +pub const NIF_SHOWTIP: ::UINT = 0x00000080; +pub const NOTIFYICON_VERSION: ::UINT = 3; +pub const NOTIFYICON_VERSION_4: ::UINT = 4; + +STRUCT!{nodebug struct NOTIFYICONDATAA { + cbSize: ::DWORD, + hWnd: ::HWND, + uID: ::UINT, + uFlags: ::UINT, + uCallbackMessage: ::UINT, + hIcon: ::HICON, + szTip: [::CHAR; 128], + dwState: ::DWORD, + dwStateMask: ::DWORD, + szInfo: [::CHAR; 256], + uTimeout: ::UINT, + szInfoTitle: [::CHAR; 64], + dwInfoFlags: ::DWORD, + guidItem: ::GUID, + hBalloonIcon: ::HICON, +}} +UNION!(NOTIFYICONDATAA, uTimeout, uTimeout, uTimeout_mut, ::UINT); +UNION!(NOTIFYICONDATAA, uTimeout, uVersion, uVersion_mut, ::UINT); +pub type PNOTIFYICONDATAA = *mut NOTIFYICONDATAA; + +STRUCT!{nodebug struct NOTIFYICONDATAW { + cbSize: ::DWORD, + hWnd: ::HWND, + uID: ::UINT, + uFlags: ::UINT, + uCallbackMessage: ::UINT, + hIcon: ::HICON, + szTip: [::WCHAR; 128], + dwState: ::DWORD, + dwStateMask: ::DWORD, + szInfo: [::WCHAR; 256], + uTimeout: ::UINT, + szInfoTitle: [::WCHAR; 64], + dwInfoFlags: ::DWORD, + guidItem: ::GUID, + hBalloonIcon: ::HICON, +}} +UNION!(NOTIFYICONDATAW, uTimeout, uTimeout, uTimeout_mut, ::UINT); +UNION!(NOTIFYICONDATAW, uTimeout, uVersion, uVersion_mut, ::UINT); // used with NIM_SETVERSION, values 0, 3 and 4 +pub type PNOTIFYICONDATAW = *mut NOTIFYICONDATAW; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/shellscalingapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/shellscalingapi.rs new file mode 100644 index 0000000..d313dde --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/shellscalingapi.rs @@ -0,0 +1,19 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +// ShellScalingApi.h +ENUM!{enum PROCESS_DPI_AWARENESS { + Process_DPI_Unaware = 0, + Process_System_DPI_Aware = 1, + Process_Per_Monitor_DPI_Aware = 2, +}} +ENUM!{enum SHELL_UI_COMPONENT { + SHELL_UI_COMPONENT_TASKBARS = 0, + SHELL_UI_COMPONENT_NOTIFICATIONAREA = 1, + SHELL_UI_COMPONENT_DESKBAND = 2, +}} +ENUM!{enum MONITOR_DPI_TYPE { + MDT_EFFECTIVE_DPI = 0, + MDT_ANGULAR_DPI = 1, + MDT_RAW_DPI = 2, +}} +pub const MDT_DEFAULT: MONITOR_DPI_TYPE = MDT_EFFECTIVE_DPI; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/shlguid.rs b/bash-5.1/vendor/winapi-0.2.8/src/shlguid.rs new file mode 100644 index 0000000..f01b4e4 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/shlguid.rs @@ -0,0 +1,2 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> diff --git a/bash-5.1/vendor/winapi-0.2.8/src/shlobj.rs b/bash-5.1/vendor/winapi-0.2.8/src/shlobj.rs new file mode 100644 index 0000000..d551f92 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/shlobj.rs @@ -0,0 +1,94 @@ +// Copyright © 2015, Peter Atashian, skdltmxn +// Licensed under the MIT License <LICENSE.md> +pub const INVALID_HANDLE_VALUE: ::HANDLE = -1isize as ::HANDLE; +pub type GPFIDL_FLAGS = ::c_int; +ENUM!{enum KNOWN_FOLDER_FLAG { + KF_FLAG_DEFAULT = 0x00000000, + KF_FLAG_NO_APPCONTAINER_REDIRECTION = 0x00010000, + KF_FLAG_CREATE = 0x00008000, + KF_FLAG_DONT_VERIFY = 0x00004000, + KF_FLAG_DONT_UNEXPAND = 0x00002000, + KF_FLAG_NO_ALIAS = 0x00001000, + KF_FLAG_INIT = 0x00000800, + KF_FLAG_DEFAULT_PATH = 0x00000400, + KF_FLAG_NOT_PARENT_RELATIVE = 0x00000200, + KF_FLAG_SIMPLE_IDLIST = 0x00000100, + KF_FLAG_ALIAS_ONLY = 0x80000000, +}} +pub const IDO_SHGIOI_SHARE: ::c_int = 0x0FFFFFFF; +pub const IDO_SHGIOI_LINK: ::c_int = 0x0FFFFFFE; +// Yes, these values are supposed to overflow. Blame Microsoft. +pub const IDO_SHGIOI_SLOWFILE: ::c_int = 0xFFFFFFFDu32 as ::c_int; +pub const IDO_SHGIOI_DEFAULT: ::c_int = 0xFFFFFFFCu32 as ::c_int; +pub const GPFIDL_DEFAULT: GPFIDL_FLAGS = 0x0000; +pub const GPFIDL_ALTNAME: GPFIDL_FLAGS = 0x0001; +pub const GPFIDL_UNCPRINTER: GPFIDL_FLAGS = 0x0002; +pub const OFASI_EDIT: ::DWORD = 0x0001; +pub const OFASI_OPENDESKTOP: ::DWORD = 0x0002; +// 1204 +pub const CSIDL_DESKTOP: ::c_int = 0x0000; +pub const CSIDL_INTERNET: ::c_int = 0x0001; +pub const CSIDL_PROGRAMS: ::c_int = 0x0002; +pub const CSIDL_CONTROLS: ::c_int = 0x0003; +pub const CSIDL_PRINTERS: ::c_int = 0x0004; +pub const CSIDL_PERSONAL: ::c_int = 0x0005; +pub const CSIDL_FAVORITES: ::c_int = 0x0006; +pub const CSIDL_STARTUP: ::c_int = 0x0007; +pub const CSIDL_RECENT: ::c_int = 0x0008; +pub const CSIDL_SENDTO: ::c_int = 0x0009; +pub const CSIDL_BITBUCKET: ::c_int = 0x000a; +pub const CSIDL_STARTMENU: ::c_int = 0x000b; +pub const CSIDL_MYDOCUMENTS: ::c_int = CSIDL_PERSONAL; +pub const CSIDL_MYMUSIC: ::c_int = 0x000d; +pub const CSIDL_MYVIDEO: ::c_int = 0x000e; +pub const CSIDL_DESKTOPDIRECTORY: ::c_int = 0x0010; +pub const CSIDL_DRIVES: ::c_int = 0x0011; +pub const CSIDL_NETWORK: ::c_int = 0x0012; +pub const CSIDL_NETHOOD: ::c_int = 0x0013; +pub const CSIDL_FONTS: ::c_int = 0x0014; +pub const CSIDL_TEMPLATES: ::c_int = 0x0015; +pub const CSIDL_COMMON_STARTMENU: ::c_int = 0x0016; +pub const CSIDL_COMMON_PROGRAMS: ::c_int = 0x0017; +pub const CSIDL_COMMON_STARTUP: ::c_int = 0x0018; +pub const CSIDL_COMMON_DESKTOPDIRECTORY: ::c_int = 0x0019; +pub const CSIDL_APPDATA: ::c_int = 0x001a; +pub const CSIDL_PRINTHOOD: ::c_int = 0x001b; +pub const CSIDL_LOCAL_APPDATA: ::c_int = 0x001c; +pub const CSIDL_ALTSTARTUP: ::c_int = 0x001d; +pub const CSIDL_COMMON_ALTSTARTUP: ::c_int = 0x001e; +pub const CSIDL_COMMON_FAVORITES: ::c_int = 0x001f; +pub const CSIDL_INTERNET_CACHE: ::c_int = 0x0020; +pub const CSIDL_COOKIES: ::c_int = 0x0021; +pub const CSIDL_HISTORY: ::c_int = 0x0022; +pub const CSIDL_COMMON_APPDATA: ::c_int = 0x0023; +pub const CSIDL_WINDOWS: ::c_int = 0x0024; +pub const CSIDL_SYSTEM: ::c_int = 0x0025; +pub const CSIDL_PROGRAM_FILES: ::c_int = 0x0026; +pub const CSIDL_MYPICTURES: ::c_int = 0x0027; +pub const CSIDL_PROFILE: ::c_int = 0x0028; +pub const CSIDL_SYSTEMX86: ::c_int = 0x0029; +pub const CSIDL_PROGRAM_FILESX86: ::c_int = 0x002a; +pub const CSIDL_PROGRAM_FILES_COMMON: ::c_int = 0x002b; +pub const CSIDL_PROGRAM_FILES_COMMONX86: ::c_int = 0x002c; +pub const CSIDL_COMMON_TEMPLATES: ::c_int = 0x002d; +pub const CSIDL_COMMON_DOCUMENTS: ::c_int = 0x002e; +pub const CSIDL_COMMON_ADMINTOOLS: ::c_int = 0x002f; +pub const CSIDL_ADMINTOOLS: ::c_int = 0x0030; +pub const CSIDL_CONNECTIONS: ::c_int = 0x0031; +pub const CSIDL_COMMON_MUSIC: ::c_int = 0x0035; +pub const CSIDL_COMMON_PICTURES: ::c_int = 0x0036; +pub const CSIDL_COMMON_VIDEO: ::c_int = 0x0037; +pub const CSIDL_RESOURCES: ::c_int = 0x0038; +pub const CSIDL_RESOURCES_LOCALIZED: ::c_int = 0x0039; +pub const CSIDL_COMMON_OEM_LINKS: ::c_int = 0x003a; +pub const CSIDL_CDBURN_AREA: ::c_int = 0x003b; +pub const CSIDL_COMPUTERSNEARME: ::c_int = 0x003d; +pub const CSIDL_FLAG_CREATE: ::c_int = 0x8000; +pub const CSIDL_FLAG_DONT_VERIFY: ::c_int = 0x4000; +pub const CSIDL_FLAG_DONT_UNEXPAND: ::c_int = 0x2000; +pub const CSIDL_FLAG_NO_ALIAS: ::c_int = 0x1000; +pub const CSIDL_FLAG_PER_USER_INIT: ::c_int = 0x0800; +pub const CSIDL_FLAG_MASK: ::c_int = 0xff00; +//1312 +pub const SHGFP_TYPE_CURRENT: ::DWORD = 0; +pub const SHGFP_TYPE_DEFAULT: ::DWORD = 1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/shobjidl.rs b/bash-5.1/vendor/winapi-0.2.8/src/shobjidl.rs new file mode 100644 index 0000000..ef7caa1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/shobjidl.rs @@ -0,0 +1,652 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +//Terrible forward declarations that need to be filled in +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenu; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenu2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenu3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExecuteCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRunnableTask; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellTaskScheduler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IQueryCodePage; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistFolder2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistFolder3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumFullIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileSyncMergeHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithFolderEnumMode; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IParseAndCreateItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumExtraSearch; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellFolder2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderViewOptions; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellView; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellView2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellView3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderView; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISearchBoxInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderView2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderViewSettings; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewHandlerVisuals; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IVisualProperties; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICommDlgBrowser; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICommDlgBrowser2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICommDlgBrowser3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IColumnManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderFilterSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderFilter; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInputObjectSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInputObject; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInputObject2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellIcon; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellBrowser; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IProfferService; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellItem2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellItemImageFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserAccountChangeCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumShellItems; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferAdviseSink; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferSource; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumResources; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellItemResources; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferDestination; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IStreamAsync; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IStreamUnbufferedInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithSelection; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithBackReferences; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPropertyUI; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICategoryProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICategorizer; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDropTargetHelper; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDragSourceHelper; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDragSourceHelper2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLinkA; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLinkW; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLinkDataList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IResolveShellLink; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IActionProgressDialog; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHWEventHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHWEventHandler2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IQueryCancelAutoPlay; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDynamicHWHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IActionProgress; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellExtInit; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellPropSheetExt; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRemoteComputer; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IQueryContinue; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithCancelEvent; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserNotification; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserNotificationCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserNotification2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IItemNameLimits; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISearchFolderItemFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExtractImage; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExtractImage2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IThumbnailHandlerFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IParentAndItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDockingWindow; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBandInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBand2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList4; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IStartMenuPinnedList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICDBurn; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IWizardSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IWizardExtension; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IWebWizardExtension; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPublishingWizard; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderViewHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerBrowserEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerBrowser; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAccessibleObject; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IResultsFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumObjects; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IOperationsProgressDialog; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IIOCancelInformation; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileOperation; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INamespaceWalkCB; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INamespaceWalkCB2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INamespaceWalk; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAutoCompleteDropDown; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IBandSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICDBurnExt; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenuSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumReadyCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumerableView; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInsertItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMenuBand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderBandPriv; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRegTreeItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IImageRecompress; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBar; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMenuPopup; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileIsInUse; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationAssociationRegistration; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationAssociationRegistrationUI; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDelegateFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IBrowserFrameOptions; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INewWindowManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAttachmentExecute; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellMenuCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellMenu; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellRunDll; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IKnownFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IKnownFolderManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISharingConfigurationManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviousVersionsInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRelatedItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IIdentityName; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDelegateItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICurrentItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferMediumItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUseToBrowseItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDisplayItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IViewStateIdentityItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDestinationStreamFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INewMenuClient; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithBindCtx; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControl; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControl2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlDropHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeAccessible; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlCustomDraw; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlFolderCapabilities; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewHandlerFrame; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITrayDeskBand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IBandHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerPaneVisibility; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenuCB; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDefaultExtractIconInit; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerCommandState; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumExplorerCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerCommandProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMarkupCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IControlMarkup; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeNetworkFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IOpenControlPanel; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IComputerInfoChangeNotify; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileSystemBindData; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileSystemBindData2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICustomDestinationList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDestinations; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDocumentLists; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithAppUserModelID; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithProgID; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUpdateIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDesktopGadget; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDesktopWallpaper; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHomeGroup; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithPropertyStore; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IOpenSearchSource; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLibrary; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDefaultFolderMenuInitialize; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationActivationManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAssocHandlerInvoker; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAssocHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumAssocHandlers; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDataObjectProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDataTransferManagerInterop; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFrameworkInputPaneHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFrameworkInputPane; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAccessibilityDockingServiceCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAccessibilityDockingService; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAppVisibilityEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAppVisibility; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPackageExecutionStateChangeNotification; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPackageDebugSettings; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISuspensionDependencyManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExecuteCommandApplicationHostEnvironment; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExecuteCommandHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDesignModeSettings; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDesignModeSettings2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchTargetMonitor; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchSourceViewSizePreference; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchTargetViewSizePreference; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchSourceAppUserModelId; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithWindow; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHandlerInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHandlerActivationHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContactManagerInterop; +//4498 +pub type SFGAOF = ::ULONG; +//9466 +ENUM!{enum SIGDN { + SIGDN_NORMALDISPLAY = 0, + SIGDN_PARENTRELATIVEPARSING = 0x80018001, + SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000, + SIGDN_PARENTRELATIVEEDITING = 0x80031001, + SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000, + SIGDN_FILESYSPATH = 0x80058000, + SIGDN_URL = 0x80068000, + SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001, + SIGDN_PARENTRELATIVE = 0x80080001, + SIGDN_PARENTRELATIVEFORUI = 0x80094001, +}} +ENUM!{enum SICHINTF { + SICHINT_DISPLAY = 0, + SICHINT_ALLFIELDS = 0x80000000, + SICHINT_CANONICAL = 0x10000000, + SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000, +}} +//9498 +RIDL!( +interface IShellItem(IShellItemVtbl): IUnknown(IUnknownVtbl) { + fn BindToHandler( + &mut self, pbc: *mut ::IBindCtx, bhid: ::REFGUID, riid: ::REFIID, ppv: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetParent(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn GetDisplayName(&mut self, sigdnName: SIGDN, ppszName: *mut ::LPWSTR) -> ::HRESULT, + fn GetAttributes(&mut self, sfgaoMask: SFGAOF, psfgaoAttribs: *mut SFGAOF) -> ::HRESULT, + fn Compare(&mut self, psi: *mut IShellItem, hint: SICHINTF, piOrder: *mut ::c_int) -> ::HRESULT +} +); +//11963 +pub type IFileOperationProgressSink = ::IUnknown; // TODO +pub type IShellItemArray = ::IUnknown; // TODO +//20869 +RIDL!( +interface IModalWindow(IModalWindowVtbl): IUnknown(IUnknownVtbl) { + fn Show(&mut self, hwndOwner: ::HWND) -> ::HRESULT +} +); +//22307 +ENUM!{enum FDE_OVERWRITE_RESPONSE { + FDEOR_DEFAULT = 0, + FDEOR_ACCEPT = 1, + FDEOR_REFUSE = 2, +}} +ENUM!{enum FDE_SHAREVIOLATION_RESPONSE { + FDESVR_DEFAULT = 0, + FDESVR_ACCEPT = 1, + FDESVR_REFUSE = 2, +}} +ENUM!{enum FDAP { + FDAP_BOTTOM = 0, + FDAP_TOP = 1, +}} +RIDL!( +interface IFileDialogEvents(IFileDialogEventsVtbl): IUnknown(IUnknownVtbl) { + fn OnFileOk(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnFolderChanging(&mut self, pfd: *mut IFileDialog, psiFolder: *mut IShellItem) -> ::HRESULT, + fn OnFolderChange(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnSelectionChange(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnShareViolation( + &mut self, pfd: *mut IFileDialog, psi: *mut IShellItem, + pResponse: *mut FDE_SHAREVIOLATION_RESPONSE + ) -> ::HRESULT, + fn OnTypeChange(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnOverwrite( + &mut self, pfd: *mut IFileDialog, psi: *mut IShellItem, + pResponse: *mut FDE_OVERWRITE_RESPONSE + ) -> ::HRESULT +} +); +FLAGS!{enum FILEOPENDIALOGOPTIONS { + FOS_OVERWRITEPROMPT = 0x2, + FOS_STRICTFILETYPES = 0x4, + FOS_NOCHANGEDIR = 0x8, + FOS_PICKFOLDERS = 0x20, + FOS_FORCEFILESYSTEM = 0x40, + FOS_ALLNONSTORAGEITEMS = 0x80, + FOS_NOVALIDATE = 0x100, + FOS_ALLOWMULTISELECT = 0x200, + FOS_PATHMUSTEXIST = 0x800, + FOS_FILEMUSTEXIST = 0x1000, + FOS_CREATEPROMPT = 0x2000, + FOS_SHAREAWARE = 0x4000, + FOS_NOREADONLYRETURN = 0x8000, + FOS_NOTESTFILECREATE = 0x10000, + FOS_HIDEMRUPLACES = 0x20000, + FOS_HIDEPINNEDPLACES = 0x40000, + FOS_NODEREFERENCELINKS = 0x100000, + FOS_DONTADDTORECENT = 0x2000000, + FOS_FORCESHOWHIDDEN = 0x10000000, + FOS_DEFAULTNOMINIMODE = 0x20000000, + FOS_FORCEPREVIEWPANEON = 0x40000000, + FOS_SUPPORTSTREAMABLEITEMS = 0x80000000, +}} +RIDL!( +interface IFileDialog(IFileDialogVtbl): IModalWindow(IModalWindowVtbl) { + fn SetFileTypes( + &mut self, cFileTypes: ::UINT, rgFilterSpec: *const ::COMDLG_FILTERSPEC + ) -> ::HRESULT, + fn SetFileTypeIndex(&mut self, iFileType: ::UINT) -> ::HRESULT, + fn GetFileTypeIndex(&mut self, piFileType: *mut ::UINT) -> ::HRESULT, + fn Advise(&mut self, pfde: *mut IFileDialogEvents, pdwCookie: *mut ::DWORD) -> ::HRESULT, + fn Unadvise(&mut self, dwCookie: ::DWORD) -> ::HRESULT, + fn SetOptions(&mut self, fos: FILEOPENDIALOGOPTIONS) -> ::HRESULT, + fn GetOptions(&mut self, pfos: *mut FILEOPENDIALOGOPTIONS) -> ::HRESULT, + fn SetDefaultFolder(&mut self, psi: *mut IShellItem) -> ::HRESULT, + fn SetFolder(&mut self, psi: *mut IShellItem) -> ::HRESULT, + fn GetFolder(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn GetCurrentSelection(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn SetFileName(&mut self, pszName: ::LPCWSTR) -> ::HRESULT, + fn GetFileName(&mut self, pszName: *mut ::LPWSTR) -> ::HRESULT, + fn SetTitle(&mut self, pszTitle: ::LPCWSTR) -> ::HRESULT, + fn SetOkButtonLabel(&mut self, pszText: ::LPCWSTR) -> ::HRESULT, + fn SetFileNameLabel(&mut self, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn GetResult(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn AddPlace(&mut self, psi: *mut IShellItem, fdap: FDAP) -> ::HRESULT, + fn SetDefaultExtension(&mut self, pszDefaultExtension: ::LPCWSTR) -> ::HRESULT, + fn Close(&mut self, hr: ::HRESULT) -> ::HRESULT, + fn SetClientGuid(&mut self, guid: ::REFGUID) -> ::HRESULT, + fn ClearClientData(&mut self) -> ::HRESULT, + fn SetFilter(&mut self, pFilter: *mut IShellItemFilter) -> ::HRESULT +} +); +RIDL!( +interface IFileSaveDialog(IFileSaveDialogVtbl): IFileDialog(IFileDialogVtbl) { + fn SetSaveAsItem(&mut self, psi: *mut IShellItem) -> ::HRESULT, + fn SetProperties(&mut self, pStore: *mut ::IPropertyStore) -> ::HRESULT, + fn SetCollectedProperties( + &mut self, pList: *mut ::IPropertyDescriptionList, fAppendDefault: ::BOOL + ) -> ::HRESULT, + fn GetProperties(&mut self, ppStore: *mut *mut ::IPropertyStore) -> ::HRESULT, + fn ApplyProperties( + &mut self, psi: *mut IShellItem, pStore: *mut ::IPropertyStore, hwnd: ::HWND, + pSink: *mut IFileOperationProgressSink + ) -> ::HRESULT +} +); +RIDL!( +interface IFileOpenDialog(IFileOpenDialogVtbl): IFileDialog(IFileDialogVtbl) { + fn GetResults(&mut self, ppenum: *mut *mut IShellItemArray) -> ::HRESULT, + fn GetSelectedItems(&mut self, ppsai: *mut *mut IShellItemArray) -> ::HRESULT +} +); +ENUM!{enum CDCONTROLSTATE { + CDCS_INACTIVE = 0x00000000, + CDCS_ENABLED = 0x00000001, + CDCS_VISIBLE = 0x00000002, + CDCS_ENABLEDVISIBLE = 0x00000003, +}} +RIDL!( +interface IFileDialogCustomize(IFileDialogCustomizeVtbl): IUnknown(IUnknownVtbl) { + fn EnableOpenDropDown(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddMenu(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn AddPushButton(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn AddComboBox(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddRadioButtonList(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddCheckButton( + &mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR, bChecked: ::BOOL + ) -> ::HRESULT, + fn AddEditBox(&mut self, dwIDCtl: ::DWORD, pszText: ::LPCWSTR) -> ::HRESULT, + fn AddSeparator(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddText(&mut self, dwIDCtl: ::DWORD, pszText: ::LPCWSTR) -> ::HRESULT, + fn SetControlLabel(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn GetControlState(&mut self, dwIDCtl: ::DWORD, pdwState: *mut CDCONTROLSTATE) -> ::HRESULT, + fn SetControlState(&mut self, dwIDCtl: ::DWORD, dwState: CDCONTROLSTATE) -> ::HRESULT, + fn GetEditBoxText(&mut self, dwIDCtl: ::DWORD, ppszText: *mut *mut ::WCHAR) -> ::HRESULT, + fn SetEditBoxText(&mut self, dwIDCtl: ::DWORD, pszText: ::LPCWSTR) -> ::HRESULT, + fn GetCheckButtonState(&mut self, dwIDCtl: ::DWORD, pbChecked: *mut ::BOOL) -> ::HRESULT, + fn SetCheckButtonState(&mut self, dwIDCtl: ::DWORD, bChecked: ::BOOL) -> ::HRESULT, + fn AddControlItem( + &mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, pszLabel: ::LPCWSTR + ) -> ::HRESULT, + fn RemoveControlItem(&mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD) -> ::HRESULT, + fn RemoveAllControlItems(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn GetControlItemState( + &mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, pdwState: *mut CDCONTROLSTATE + ) -> ::HRESULT, + fn SetControlItemState( + &mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, dwState: CDCONTROLSTATE + ) -> ::HRESULT, + fn GetSelectedControlItem(&mut self, dwIDCtl: ::DWORD, pdwIDItem: *mut ::DWORD) -> ::HRESULT, + fn SetSelectedControlItem(&mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD) -> ::HRESULT, + fn StartVisualGroup(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn EndVisualGroup(&mut self) -> ::HRESULT, + fn MakeProminent(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn SetControlItemText(&mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT +} +); +RIDL!( +interface IFileDialogControlEvents(IFileDialogControlEventsVtbl): IUnknown(IUnknownVtbl) { + fn OnItemSelected( + &mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD, dwIDItem: ::DWORD + ) -> ::HRESULT, + fn OnButtonClicked(&mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD) -> ::HRESULT, + fn OnCheckButtonToggled( + &mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD, bChecked: ::BOOL + ) -> ::HRESULT, + fn OnControlActivating( + &mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface IFileDialog2(IFileDialog2Vtbl): IFileDialog(IFileDialogVtbl) { + fn SetCancelButtonLabel(&mut self, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn SetNavigationRoot(&mut self, psi: IShellItem) -> ::HRESULT +} +); +//27457 +pub type IShellItemFilter = ::IUnknown; // TODO diff --git a/bash-5.1/vendor/winapi-0.2.8/src/shtypes.rs b/bash-5.1/vendor/winapi-0.2.8/src/shtypes.rs new file mode 100644 index 0000000..0bea4b1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/shtypes.rs @@ -0,0 +1,40 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +#[repr(C)] #[allow(missing_copy_implementations)] +pub struct SHITEMID { + pub cb: ::USHORT, + pub abID: [::BYTE; 0], +} +pub type LPSHITEMID = *mut SHITEMID; +pub type LPCSHITEMID = *const SHITEMID; +#[repr(C)] +pub struct ITEMIDLIST { + pub mkid: SHITEMID, +} +pub type ITEMIDLIST_RELATIVE = ITEMIDLIST; +pub type ITEMID_CHILD = ITEMIDLIST; +pub type ITEMIDLIST_ABSOLUTE = ITEMIDLIST; +pub type LPITEMIDLIST = *mut ITEMIDLIST; +pub type LPCITEMIDLIST = *const ITEMIDLIST; +pub type PIDLIST_ABSOLUTE = *mut ITEMIDLIST_ABSOLUTE; +pub type PCIDLIST_ABSOLUTE = *const ITEMIDLIST_ABSOLUTE; +pub type PCUIDLIST_ABSOLUTE = *const ITEMIDLIST_ABSOLUTE; +pub type PIDLIST_RELATIVE = *mut ITEMIDLIST_RELATIVE; +pub type PCIDLIST_RELATIVE = *const ITEMIDLIST_RELATIVE; +pub type PUIDLIST_RELATIVE = *mut ITEMIDLIST_RELATIVE; +pub type PCUIDLIST_RELATIVE = *const ITEMIDLIST_RELATIVE; +pub type PITEMID_CHILD = *mut ITEMID_CHILD; +pub type PCITEMID_CHILD = *const ITEMID_CHILD; +pub type PUITEMID_CHILD = *mut ITEMID_CHILD; +pub type PCUITEMID_CHILD = *const ITEMID_CHILD; +pub type PCUITEMID_CHILD_ARRAY = *const PCUITEMID_CHILD; +pub type PCUIDLIST_RELATIVE_ARRAY = *const PCUIDLIST_RELATIVE; +pub type PCIDLIST_ABSOLUTE_ARRAY = *const PCIDLIST_ABSOLUTE; +pub type PCUIDLIST_ABSOLUTE_ARRAY = *const PCUIDLIST_ABSOLUTE; +STRUCT!{struct COMDLG_FILTERSPEC { + pszName: ::LPCWSTR, + pszSpec: ::LPCWSTR, +}} +pub type KNOWNFOLDERID = ::GUID; +pub type REFKNOWNFOLDERID = *const KNOWNFOLDERID; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/spapidef.rs b/bash-5.1/vendor/winapi-0.2.8/src/spapidef.rs new file mode 100644 index 0000000..05861dd --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/spapidef.rs @@ -0,0 +1,48 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Windows NT Setup and Device Installer services +pub type SP_LOG_TOKEN = ::DWORDLONG; +pub type PSP_LOG_TOKEN = *mut ::DWORDLONG; +pub const LOGTOKEN_TYPE_MASK: SP_LOG_TOKEN = 3; +pub const LOGTOKEN_UNSPECIFIED: SP_LOG_TOKEN = 0; +pub const LOGTOKEN_NO_LOG: SP_LOG_TOKEN = 1; +pub const LOGTOKEN_SETUPAPI_APPLOG: SP_LOG_TOKEN = 2; +pub const LOGTOKEN_SETUPAPI_DEVLOG: SP_LOG_TOKEN = 3; +pub const TXTLOG_SETUPAPI_DEVLOG: ::DWORD = 0x00000001; +pub const TXTLOG_SETUPAPI_CMDLINE: ::DWORD = 0x00000002; +pub const TXTLOG_SETUPAPI_BITS: ::DWORD = 0x00000003; +pub const TXTLOG_ERROR: ::DWORD = 0x1; +pub const TXTLOG_WARNING: ::DWORD = 0x2; +pub const TXTLOG_SYSTEM_STATE_CHANGE: ::DWORD = 0x3; +pub const TXTLOG_SUMMARY: ::DWORD = 0x4; +pub const TXTLOG_DETAILS: ::DWORD = 0x5; +pub const TXTLOG_VERBOSE: ::DWORD = 0x6; +pub const TXTLOG_VERY_VERBOSE: ::DWORD = 0x7; +pub const TXTLOG_RESERVED_FLAGS: ::DWORD = 0x0000FFF0; +pub const TXTLOG_TIMESTAMP: ::DWORD = 0x00010000; +pub const TXTLOG_DEPTH_INCR: ::DWORD = 0x00020000; +pub const TXTLOG_DEPTH_DECR: ::DWORD = 0x00040000; +pub const TXTLOG_TAB_1: ::DWORD = 0x00080000; +pub const TXTLOG_FLUSH_FILE: ::DWORD = 0x00100000; +#[inline] #[allow(dead_code)] +pub fn TXTLOG_LEVEL(flags: ::DWORD) -> ::DWORD { + return flags & 0xf; +} +pub const TXTLOG_DEVINST: ::DWORD = 0x00000001; +pub const TXTLOG_INF: ::DWORD = 0x00000002; +pub const TXTLOG_FILEQ: ::DWORD = 0x00000004; +pub const TXTLOG_COPYFILES: ::DWORD = 0x00000008; +pub const TXTLOG_SIGVERIF: ::DWORD = 0x00000020; +pub const TXTLOG_BACKUP: ::DWORD = 0x00000080; +pub const TXTLOG_UI: ::DWORD = 0x00000100; +pub const TXTLOG_UTIL: ::DWORD = 0x00000200; +pub const TXTLOG_INFDB: ::DWORD = 0x00000400; +pub const TXTLOG_POLICY: ::DWORD = 0x00800000; +pub const TXTLOG_NEWDEV: ::DWORD = 0x01000000; +pub const TXTLOG_UMPNPMGR: ::DWORD = 0x02000000; +pub const TXTLOG_DRIVER_STORE: ::DWORD = 0x04000000; +pub const TXTLOG_SETUP: ::DWORD = 0x08000000; +pub const TXTLOG_CMI: ::DWORD = 0x10000000; +pub const TXTLOG_DEVMGR: ::DWORD = 0x20000000; +pub const TXTLOG_INSTALLER: ::DWORD = 0x40000000; +pub const TXTLOG_VENDOR: ::DWORD = 0x80000000; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/sql.rs b/bash-5.1/vendor/winapi-0.2.8/src/sql.rs new file mode 100644 index 0000000..503fa81 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/sql.rs @@ -0,0 +1,179 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub const SQL_NULL_DATA: SQLLEN = -1; +pub const SQL_DATA_AT_EXEC: SQLLEN = -2; +pub const SQL_SUCCESS: SQLRETURN = 0; +pub const SQL_SUCCESS_WITH_INFO: SQLRETURN = 1; +pub const SQL_NO_DATA: SQLRETURN = 100; +pub const SQL_PARAM_DATA_AVAILABLE: SQLRETURN = 101; +pub const SQL_ERROR: SQLRETURN = -1; +pub const SQL_INVALID_HANDLE: SQLRETURN = -2; +pub const SQL_STILL_EXECUTING: SQLRETURN = 2; +pub const SQL_NEED_DATA: SQLRETURN = 99; +pub const SQL_NTS: SQLSMALLINT = -3; +pub const SQL_MAX_MESSAGE_LENGTH: usize = 512; +pub const SQL_DATE_LEN: usize = 10; +pub const SQL_TIME_LEN: usize = 8; +pub const SQL_TIMESTAMP_LEN: usize = 19; +pub const SQL_HANDLE_ENV: SQLSMALLINT = 1; +pub const SQL_HANDLE_DBC: SQLSMALLINT = 2; +pub const SQL_HANDLE_STMT: SQLSMALLINT = 3; +pub const SQL_HANDLE_DESC: SQLSMALLINT = 4; +pub const SQL_ATTR_OUTPUT_NTS: SQLINTEGER = 10001; +pub const SQL_ATTR_AUTO_IPD: SQLINTEGER = 10001; +pub const SQL_ATTR_METADATA_ID: SQLINTEGER = 10014; +pub const SQL_ATTR_APP_ROW_DESC: SQLINTEGER = 10010; +pub const SQL_ATTR_APP_PARAM_DESC: SQLINTEGER = 10011; +pub const SQL_ATTR_IMP_ROW_DESC: SQLINTEGER = 10012; +pub const SQL_ATTR_IMP_PARAM_DESC: SQLINTEGER = 10013; +pub const SQL_ATTR_CURSOR_SCROLLABLE: SQLINTEGER = -1; +pub const SQL_ATTR_CURSOR_SENSITIVITY: SQLINTEGER = -2; + +//Null handle used in place of parent handle when allocating HENV +pub const SQL_NULL_HANDLE: SQLHANDLE = 0 as SQLHANDLE; + +//Special length/indicator values + +//Return values from functions + + +//Values of NULLABLE field in descriptor +pub const SQL_NO_NULLS: SQLSMALLINT = 0; +pub const SQL_NULLABLE: SQLSMALLINT = 1; +pub const SQL_NULLABLE_UNKNOWN: SQLSMALLINT = 2; + +//Env attribute +pub const SQL_ATTR_ODBC_VERSION: SQLINTEGER = 200; +pub const SQL_ATTR_CONNECTION_POOLING: SQLINTEGER = 201; +pub const SQL_ATTR_CP_MATCH: SQLINTEGER = 202; + +//Values for SQL_ATTR_ODBC_VERSION +pub const SQL_OV_ODBC2: SQLINTEGER = 2; +pub const SQL_OV_ODBC3: SQLINTEGER = 3; +pub const SQL_OV_ODBC3_80: SQLINTEGER = 380; + +//Connection attributes +pub const SQL_ACCESS_MODE: SQLINTEGER = 101; +pub const SQL_AUTOCOMMIT: SQLINTEGER = 102; +pub const SQL_LOGIN_TIMEOUT: SQLINTEGER = 103; +pub const SQL_OPT_TRACE: SQLINTEGER = 104; +pub const SQL_OPT_TRACEFILE: SQLINTEGER = 105; +pub const SQL_TRANSLATE_DLL: SQLINTEGER = 106; +pub const SQL_TRANSLATE_OPTION: SQLINTEGER = 107; +pub const SQL_TXN_ISOLATION: SQLINTEGER = 108; +pub const SQL_CURRENT_QUALIFIER: SQLINTEGER = 109; +pub const SQL_ODBC_CURSORS: SQLINTEGER = 110; +pub const SQL_QUIET_MODE: SQLINTEGER = 111; +pub const SQL_PACKET_SIZE: SQLINTEGER = 112; + +//Connection attributes with new names +pub const SQL_ATTR_ACCESS_MODE: SQLINTEGER = SQL_ACCESS_MODE; +pub const SQL_ATTR_AUTOCOMMIT: SQLINTEGER = SQL_AUTOCOMMIT; +pub const SQL_ATTR_CONNECTION_TIMEOUT: SQLINTEGER = 113; +pub const SQL_ATTR_CURRENT_CATALOG: SQLINTEGER = SQL_CURRENT_QUALIFIER; +pub const SQL_ATTR_DISCONNECT_BEHAVIOR: SQLINTEGER = 114; +pub const SQL_ATTR_ENLIST_IN_DTC: SQLINTEGER = 1207; +pub const SQL_ATTR_ENLIST_IN_XA: SQLINTEGER = 1208; +pub const SQL_ATTR_LOGIN_TIMEOUT: SQLINTEGER = SQL_LOGIN_TIMEOUT; +pub const SQL_ATTR_ODBC_CURSORS: SQLINTEGER = SQL_ODBC_CURSORS; +pub const SQL_ATTR_PACKET_SIZE: SQLINTEGER = SQL_PACKET_SIZE; +pub const SQL_ATTR_QUIET_MODE: SQLINTEGER = SQL_QUIET_MODE; +pub const SQL_ATTR_TRACE: SQLINTEGER = SQL_OPT_TRACE; +pub const SQL_ATTR_TRACEFILE: SQLINTEGER = SQL_OPT_TRACEFILE; +pub const SQL_ATTR_TRANSLATE_LIB: SQLINTEGER = SQL_TRANSLATE_DLL; +pub const SQL_ATTR_TRANSLATE_OPTION: SQLINTEGER = SQL_TRANSLATE_OPTION; +pub const SQL_ATTR_TXN_ISOLATION: SQLINTEGER = SQL_TXN_ISOLATION; +pub const SQL_ATTR_CONNECTION_DEAD: SQLINTEGER = 1209; + +//Flags for null-terminated string +pub const SQL_NTS: SQLSMALLINT = -3; + +//Options for SQLDriverConnect +pub const SQL_DRIVER_NOPROMPT: SQLUSMALLINT = 0; +pub const SQL_DRIVER_COMPLETE: SQLUSMALLINT = 1; +pub const SQL_DRIVER_PROMPT: SQLUSMALLINT = 2; +pub const SQL_DRIVER_COMPLETE_REQUIRED: SQLUSMALLINT = 3; + +//Whether an attribute is a pointer or not +pub const SQL_IS_POINTER: SQLINTEGER = -4; +pub const SQL_IS_UINTEGER: SQLINTEGER = -5; +pub const SQL_IS_INTEGER: SQLINTEGER = -6; +pub const SQL_IS_USMALLINT: SQLINTEGER = -7; +pub const SQL_IS_SMALLINT: SQLINTEGER = -8; + +//FreeStmt options +pub const SQL_CLOSE: SQLUSMALLINT = 0; +pub const SQL_DROP: SQLUSMALLINT = 1; +pub const SQL_UNBIND: SQLUSMALLINT = 2; +pub const SQL_RESET_PARAMS: SQLUSMALLINT = 3; + +//C datatype to SQL datatype mapping +pub const SQL_UNKNOWN_TYPE: SQLSMALLINT = 0; +pub const SQL_CHAR: SQLSMALLINT = 1; +pub const SQL_NUMERIC: SQLSMALLINT = 2; +pub const SQL_DECIMAL: SQLSMALLINT = 3; +pub const SQL_INTEGER: SQLSMALLINT = 4; +pub const SQL_SMALLINT: SQLSMALLINT = 5; +pub const SQL_FLOAT: SQLSMALLINT = 6; +pub const SQL_REAL: SQLSMALLINT = 7; +pub const SQL_DOUBLE: SQLSMALLINT = 8; +pub const SQL_DATETIME: SQLSMALLINT = 9; +pub const SQL_VARCHAR: SQLSMALLINT = 12; + +pub const SQL_TYPE_DATE: SQLSMALLINT = 91; +pub const SQL_TYPE_TIME: SQLSMALLINT = 92; +pub const SQL_TYPE_TIMESTAMP: SQLSMALLINT = 93; + +pub const SQL_DATE: SQLSMALLINT = 9; +pub const SQL_INTERVAL: SQLSMALLINT = 10; +pub const SQL_TIME: SQLSMALLINT = 10; +pub const SQL_TIMESTAMP: SQLSMALLINT = 11; +pub const SQL_LONGVARCHAR: SQLSMALLINT = -1; +pub const SQL_BINARY: SQLSMALLINT = -2; +pub const SQL_VARBINARY: SQLSMALLINT = -3; +pub const SQL_LONGVARBINARY: SQLSMALLINT = -4; +pub const SQL_BIGINT: SQLSMALLINT = -5; +pub const SQL_TINYINT: SQLSMALLINT = -6; +pub const SQL_BIT: SQLSMALLINT = -7; +pub const SQL_GUID: SQLSMALLINT = -11; + +pub const SQL_C_CHAR: SQLSMALLINT = SQL_CHAR; +pub const SQL_C_LONG: SQLSMALLINT = SQL_INTEGER; +pub const SQL_C_SHORT: SQLSMALLINT = SQL_SMALLINT; +pub const SQL_C_FLOAT: SQLSMALLINT = SQL_REAL; +pub const SQL_C_DOUBLE: SQLSMALLINT = SQL_DOUBLE; +pub const SQL_C_NUMERIC: SQLSMALLINT = SQL_NUMERIC; +pub const SQL_C_DEFAULT: SQLSMALLINT = 99; + +pub const SQL_SIGNED_OFFSET: SQLSMALLINT = -20; +pub const SQL_UNSIGNED_OFFSET: SQLSMALLINT = -22; + +pub const SQL_C_DATE: SQLSMALLINT = SQL_DATE; +pub const SQL_C_TIME: SQLSMALLINT = SQL_TIME; +pub const SQL_C_TIMESTAMP: SQLSMALLINT = SQL_TIMESTAMP; + +pub const SQL_C_TYPE_DATE: SQLSMALLINT = SQL_TYPE_DATE; +pub const SQL_C_TYPE_TIME: SQLSMALLINT = SQL_TYPE_TIME; +pub const SQL_C_TYPE_TIMESTAMP: SQLSMALLINT = SQL_TYPE_TIMESTAMP; + +pub const SQL_C_BINARY: SQLSMALLINT = SQL_BINARY; +pub const SQL_C_BIT: SQLSMALLINT = SQL_BIT; +pub const SQL_C_SBIGINT: SQLSMALLINT = SQL_BIGINT + SQL_SIGNED_OFFSET; +pub const SQL_C_UBIGINT: SQLSMALLINT = SQL_BIGINT + SQL_UNSIGNED_OFFSET; +pub const SQL_C_TINYINT: SQLSMALLINT = SQL_TINYINT; +pub const SQL_C_SLONG: SQLSMALLINT = SQL_C_LONG + SQL_SIGNED_OFFSET; +pub const SQL_C_SSHORT: SQLSMALLINT = SQL_C_SHORT + SQL_SIGNED_OFFSET; +pub const SQL_C_STINYINT: SQLSMALLINT = SQL_TINYINT + SQL_SIGNED_OFFSET; +pub const SQL_C_ULONG: SQLSMALLINT = SQL_C_LONG + SQL_UNSIGNED_OFFSET; +pub const SQL_C_USHORT: SQLSMALLINT = SQL_C_SHORT + SQL_UNSIGNED_OFFSET; +pub const SQL_C_UTINYINT: SQLSMALLINT = SQL_TINYINT + SQL_UNSIGNED_OFFSET; + +pub const SQL_C_GUID: SQLSMALLINT = SQL_GUID; + +pub const SQL_WCHAR: SQLSMALLINT = -8; +pub const SQL_WVARCHAR: SQLSMALLINT = -9; +pub const SQL_WLONGVARCHAR: SQLSMALLINT = -10; +pub const SQL_C_WCHAR: SQLSMALLINT = SQL_WCHAR; + +pub const SQL_TYPE_NULL: SQLSMALLINT = 0; + diff --git a/bash-5.1/vendor/winapi-0.2.8/src/sqltypes.rs b/bash-5.1/vendor/winapi-0.2.8/src/sqltypes.rs new file mode 100644 index 0000000..a5ded3a --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/sqltypes.rs @@ -0,0 +1,130 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub type SQLCHAR = ::c_uchar; +pub type SQLSCHAR = ::c_schar; +pub type SQLDATE = ::c_uchar; +pub type SQLDECIMAL = ::c_uchar; +pub type SQLDOUBLE = ::c_double; +pub type SQLFLOAT = ::c_double; +pub type SQLINTEGER = ::c_long; +pub type SQLUINTEGER = ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type SQLLEN = ::INT64; +#[cfg(target_arch = "x86_64")] +pub type SQLULEN = ::UINT64; +#[cfg(target_arch = "x86_64")] +pub type SQLSETPOSIROW = ::UINT64; +#[cfg(target_arch = "x86")] +pub type SQLLEN = SQLINTEGER; +#[cfg(target_arch = "x86")] +pub type SQLULEN = SQLUINTEGER; +#[cfg(target_arch = "x86")] +pub type SQLSETPOSIROW = SQLUSMALLINT; +pub type SQLROWCOUNT = SQLULEN; +pub type SQLROWSETSIZE = SQLULEN; +pub type SQLTRANSID = SQLULEN; +pub type SQLROWOFFSET = SQLLEN; +pub type SQLNUMERIC = ::c_uchar; +pub type SQLPOINTER = *mut ::c_void; +pub type SQLREAL = ::c_float; +pub type SQLSMALLINT = ::c_short; +pub type SQLUSMALLINT = ::c_ushort; +pub type SQLTIME = ::c_uchar; +pub type SQLTIMESTAMP = ::c_uchar; +pub type SQLVARCHAR = ::c_uchar; +pub type SQLRETURN = SQLSMALLINT; +pub type SQLHANDLE = *mut ::c_void; +pub type SQLHENV = SQLHANDLE; +pub type SQLHDBC = SQLHANDLE; +pub type SQLHSTMT = SQLHANDLE; +pub type SQLHDESC = SQLHANDLE; +//pub type UCHAR = ::c_uchar; +pub type SCHAR = ::c_schar; +//pub type SQLSCHAR = SCHAR; +pub type SDWORD = ::c_long; +pub type SWORD = ::c_short; +pub type UDWORD = ::c_ulong; +//pub type UWORD = ::c_ushort; +//#[cfg(target_arch = "x86")] +//pub type SQLUINTEGER = ::UDWORD; +pub type SLONG = ::c_long; +pub type SSHORT = ::c_short; +//pub type ULONG = ::c_ulong; +//pub type USHORT = ::c_ushort; +pub type SDOUBLE = ::c_double; +pub type LDOUBLE = ::c_double; +pub type SFLOAT = ::c_float; +pub type PTR = *mut ::c_void; +pub type HENV = *mut ::c_void; +pub type HDBC = *mut ::c_void; +pub type HSTMT = *mut ::c_void; +pub type RETCODE = ::c_short; +pub type SQLHWND = ::HWND; +STRUCT!{struct DATE_STRUCT { + year: SQLSMALLINT, + month: SQLUSMALLINT, + day: SQLUSMALLINT, +}} +pub type SQL_DATE_STRUCT = DATE_STRUCT; +STRUCT!{struct TIME_STRUCT { + hour: SQLUSMALLINT, + minute: SQLUSMALLINT, + second: SQLUSMALLINT, +}} +pub type SQL_TIME_STRUCT = TIME_STRUCT; +STRUCT!{struct TIMESTAMP_STRUCT { + year: SQLSMALLINT, + month: SQLUSMALLINT, + day: SQLUSMALLINT, + hour: SQLUSMALLINT, + minute: SQLUSMALLINT, + second: SQLUSMALLINT, + fraction: SQLUINTEGER, +}} +pub type SQL_TIMESTAMP_STRUCT = TIMESTAMP_STRUCT; +ENUM!{enum SQLINTERVAL { + SQL_IS_YEAR = 1, + SQL_IS_MONTH = 2, + SQL_IS_DAY = 3, + SQL_IS_HOUR = 4, + SQL_IS_MINUTE = 5, + SQL_IS_SECOND = 6, + SQL_IS_YEAR_TO_MONTH = 7, + SQL_IS_DAY_TO_HOUR = 8, + SQL_IS_DAY_TO_MINUTE = 9, + SQL_IS_DAY_TO_SECOND = 10, + SQL_IS_HOUR_TO_MINUTE = 11, + SQL_IS_HOUR_TO_SECOND = 12, + SQL_IS_MINUTE_TO_SECOND = 13, +}} +STRUCT!{struct SQL_YEAR_MONTH_STRUCT { + year: SQLUINTEGER, + month: SQLUINTEGER, +}} +STRUCT!{struct SQL_DAY_SECOND_STRUCT { + day: SQLUINTEGER, + hour: SQLUINTEGER, + minute: SQLUINTEGER, + second: SQLUINTEGER, + fraction: SQLUINTEGER, +}} +STRUCT!{struct SQL_INTERVAL_STRUCT { + interval_type: SQLINTERVAL, + interval_sign: SQLSMALLINT, + intval: [u32; 5], +}} +UNION!{SQL_INTERVAL_STRUCT, intval, year_month, year_month_mut, SQL_YEAR_MONTH_STRUCT} +UNION!{SQL_INTERVAL_STRUCT, intval, day_second, day_second_mut, SQL_DAY_SECOND_STRUCT} +pub type ODBCINT64 = ::__int64; +pub type SQLBIGINT = ODBCINT64; +pub type SQLUBIGINT = ::__uint64; +pub const SQL_MAX_NUMERIC_LEN: usize = 16; +STRUCT!{struct SQL_NUMERIC_STRUCT { + precision: SQLCHAR, + scale: SQLSCHAR, + sign: SQLCHAR, + val: [SQLCHAR; SQL_MAX_NUMERIC_LEN], +}} +pub type SQLGUID = ::GUID; +pub type BOOKMARK = SQLULEN; +pub type SQLWCHAR = ::wchar_t; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/sspi.rs b/bash-5.1/vendor/winapi-0.2.8/src/sspi.rs new file mode 100644 index 0000000..688fe70 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/sspi.rs @@ -0,0 +1,657 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Security Support Provider Interface Prototypes and structure definitions +pub type SEC_WCHAR = ::WCHAR; +pub type SEC_CHAR = ::CHAR; +pub type SECURITY_STATUS = ::LONG; +STRUCT!{struct SecHandle { + dwLower: ::ULONG_PTR, + dwUpper: ::ULONG_PTR, +}} +pub type PSecHandle = *mut SecHandle; +pub const SEC_DELETED_HANDLE: ::ULONG_PTR = 2; +pub type CredHandle = SecHandle; +pub type PCredHandle = PSecHandle; +pub type CtxtHandle = SecHandle; +pub type PCtxtHandle = PSecHandle; +pub type SECURITY_INTEGER = ::LARGE_INTEGER; +pub type PSECURITY_INTEGER = *mut ::LARGE_INTEGER; +pub type TimeStamp = SECURITY_INTEGER; +pub type PTimeStamp = *mut SECURITY_INTEGER; +STRUCT!{struct SECURITY_STRING { + Length: ::c_ushort, + MaximumLength: ::c_ushort, + Buffer: *mut ::c_ushort, +}} +pub type PSECURITY_STRING = *mut SECURITY_STRING; +STRUCT!{struct SecPkgInfoW { + fCapabilities: ::c_ulong, + wVersion: ::c_ushort, + wRPCID: ::c_ushort, + cbMaxToken: ::c_ulong, + Name: *mut SEC_WCHAR, + Comment: *mut SEC_WCHAR, +}} +pub type PSecPkgInfoW = *mut SecPkgInfoW; +STRUCT!{struct SecPkgInfoA { + fCapabilities: ::c_ulong, + wVersion: ::c_ushort, + wRPCID: ::c_ushort, + cbMaxToken: ::c_ulong, + Name: *mut SEC_CHAR, + Comment: *mut SEC_CHAR, +}} +pub type PSecPkgInfoA = *mut SecPkgInfoA; +pub const SECPKG_FLAG_INTEGRITY: ::c_ulong = 0x00000001; +pub const SECPKG_FLAG_PRIVACY: ::c_ulong = 0x00000002; +pub const SECPKG_FLAG_TOKEN_ONLY: ::c_ulong = 0x00000004; +pub const SECPKG_FLAG_DATAGRAM: ::c_ulong = 0x00000008; +pub const SECPKG_FLAG_CONNECTION: ::c_ulong = 0x00000010; +pub const SECPKG_FLAG_MULTI_REQUIRED: ::c_ulong = 0x00000020; +pub const SECPKG_FLAG_CLIENT_ONLY: ::c_ulong = 0x00000040; +pub const SECPKG_FLAG_EXTENDED_ERROR: ::c_ulong = 0x00000080; +pub const SECPKG_FLAG_IMPERSONATION: ::c_ulong = 0x00000100; +pub const SECPKG_FLAG_ACCEPT_WIN32_NAME: ::c_ulong = 0x00000200; +pub const SECPKG_FLAG_STREAM: ::c_ulong = 0x00000400; +pub const SECPKG_FLAG_NEGOTIABLE: ::c_ulong = 0x00000800; +pub const SECPKG_FLAG_GSS_COMPATIBLE: ::c_ulong = 0x00001000; +pub const SECPKG_FLAG_LOGON: ::c_ulong = 0x00002000; +pub const SECPKG_FLAG_ASCII_BUFFERS: ::c_ulong = 0x00004000; +pub const SECPKG_FLAG_FRAGMENT: ::c_ulong = 0x00008000; +pub const SECPKG_FLAG_MUTUAL_AUTH: ::c_ulong = 0x00010000; +pub const SECPKG_FLAG_DELEGATION: ::c_ulong = 0x00020000; +pub const SECPKG_FLAG_READONLY_WITH_CHECKSUM: ::c_ulong = 0x00040000; +pub const SECPKG_FLAG_RESTRICTED_TOKENS: ::c_ulong = 0x00080000; +pub const SECPKG_FLAG_NEGO_EXTENDER: ::c_ulong = 0x00100000; +pub const SECPKG_FLAG_NEGOTIABLE2: ::c_ulong = 0x00200000; +pub const SECPKG_FLAG_APPCONTAINER_PASSTHROUGH: ::c_ulong = 0x00400000; +pub const SECPKG_FLAG_APPCONTAINER_CHECKS: ::c_ulong = 0x00800000; +pub const SECPKG_ID_NONE: ::c_ulong = 0xFFFF; +pub const SECPKG_CALLFLAGS_APPCONTAINER: ::c_ulong = 0x00000001; +pub const SECPKG_CALLFLAGS_APPCONTAINER_AUTHCAPABLE: ::c_ulong = 0x00000002; +pub const SECPKG_CALLFLAGS_FORCE_SUPPLIED: ::c_ulong = 0x00000004; +STRUCT!{struct SecBuffer { + cbBuffer: ::c_ulong, + BufferType: ::c_ulong, + pvBuffer: *mut ::c_void, +}} +pub type PSecBuffer = *mut SecBuffer; +STRUCT!{struct SecBufferDesc { + ulVersion: ::c_ulong, + cBuffers: ::c_ulong, + pBuffers: PSecBuffer, +}} +pub type PSecBufferDesc = *mut SecBufferDesc; +pub const SECBUFFER_VERSION: ::c_ulong = 0; +pub const SECBUFFER_EMPTY: ::c_ulong = 0; +pub const SECBUFFER_DATA: ::c_ulong = 1; +pub const SECBUFFER_TOKEN: ::c_ulong = 2; +pub const SECBUFFER_PKG_PARAMS: ::c_ulong = 3; +pub const SECBUFFER_MISSING: ::c_ulong = 4; +pub const SECBUFFER_EXTRA: ::c_ulong = 5; +pub const SECBUFFER_STREAM_TRAILER: ::c_ulong = 6; +pub const SECBUFFER_STREAM_HEADER: ::c_ulong = 7; +pub const SECBUFFER_NEGOTIATION_INFO: ::c_ulong = 8; +pub const SECBUFFER_PADDING: ::c_ulong = 9; +pub const SECBUFFER_STREAM: ::c_ulong = 10; +pub const SECBUFFER_MECHLIST: ::c_ulong = 11; +pub const SECBUFFER_MECHLIST_SIGNATURE: ::c_ulong = 12; +pub const SECBUFFER_TARGET: ::c_ulong = 13; +pub const SECBUFFER_CHANNEL_BINDINGS: ::c_ulong = 14; +pub const SECBUFFER_CHANGE_PASS_RESPONSE: ::c_ulong = 15; +pub const SECBUFFER_TARGET_HOST: ::c_ulong = 16; +pub const SECBUFFER_ALERT: ::c_ulong = 17; +pub const SECBUFFER_APPLICATION_PROTOCOLS: ::c_ulong = 18; +pub const SECBUFFER_ATTRMASK: ::c_ulong = 0xF0000000; +pub const SECBUFFER_READONLY: ::c_ulong = 0x80000000; +pub const SECBUFFER_READONLY_WITH_CHECKSUM: ::c_ulong = 0x10000000; +pub const SECBUFFER_RESERVED: ::c_ulong = 0x60000000; +STRUCT!{struct SEC_NEGOTIATION_INFO { + Size: ::c_ulong, + NameLength: ::c_ulong, + Name: *mut SEC_WCHAR, + Reserved: *mut ::c_void, +}} +pub type PSEC_NEGOTIATION_INFO = *mut SEC_NEGOTIATION_INFO; +STRUCT!{struct SEC_CHANNEL_BINDINGS { + dwInitiatorAddrType: ::c_ulong, + cbInitiatorLength: ::c_ulong, + dwInitiatorOffset: ::c_ulong, + dwAcceptorAddrType: ::c_ulong, + cbAcceptorLength: ::c_ulong, + dwAcceptorOffset: ::c_ulong, + cbApplicationDataLength: ::c_ulong, + dwApplicationDataOffset: ::c_ulong, +}} +pub type PSEC_CHANNEL_BINDINGS = *mut SEC_CHANNEL_BINDINGS; +ENUM!{enum SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT { + SecApplicationProtocolNegotiationExt_None, + SecApplicationProtocolNegotiationExt_NPN, + SecApplicationProtocolNegotiationExt_ALPN, +}} +pub type PSEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT = *mut SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT; +STRUCT!{struct SEC_APPLICATION_PROTOCOL_LIST { + ProtoNegoExt: ::SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT, + ProtocolListSize: ::c_ushort, + ProtocolList: [::c_uchar; 0], +}} +STRUCT!{struct SEC_APPLICATION_PROTOCOLS { + ProtocolListsSize: ::c_ulong, + ProtocolLists: [SEC_APPLICATION_PROTOCOL_LIST; 0], +}} +pub type PSEC_APPLICATION_PROTOCOLS = *mut SEC_APPLICATION_PROTOCOLS; +pub const SECURITY_NATIVE_DREP: ::c_ulong = 0x00000010; +pub const SECURITY_NETWORK_DREP: ::c_ulong = 0x00000000; +pub const SECPKG_CRED_INBOUND: ::c_ulong = 0x00000001; +pub const SECPKG_CRED_OUTBOUND: ::c_ulong = 0x00000002; +pub const SECPKG_CRED_BOTH: ::c_ulong = 0x00000003; +pub const SECPKG_CRED_DEFAULT: ::c_ulong = 0x00000004; +pub const SECPKG_CRED_RESERVED: ::c_ulong = 0xF0000000; +pub const SECPKG_CRED_AUTOLOGON_RESTRICTED: ::c_ulong = 0x00000010; +pub const SECPKG_CRED_PROCESS_POLICY_ONLY: ::c_ulong = 0x00000020; +pub const ISC_REQ_DELEGATE: ::c_ulong = 0x00000001; +pub const ISC_REQ_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ISC_REQ_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ISC_REQ_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ISC_REQ_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ISC_REQ_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ISC_REQ_PROMPT_FOR_CREDS: ::c_ulong = 0x00000040; +pub const ISC_REQ_USE_SUPPLIED_CREDS: ::c_ulong = 0x00000080; +pub const ISC_REQ_ALLOCATE_MEMORY: ::c_ulong = 0x00000100; +pub const ISC_REQ_USE_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ISC_REQ_DATAGRAM: ::c_ulong = 0x00000400; +pub const ISC_REQ_CONNECTION: ::c_ulong = 0x00000800; +pub const ISC_REQ_CALL_LEVEL: ::c_ulong = 0x00001000; +pub const ISC_REQ_FRAGMENT_SUPPLIED: ::c_ulong = 0x00002000; +pub const ISC_REQ_EXTENDED_ERROR: ::c_ulong = 0x00004000; +pub const ISC_REQ_STREAM: ::c_ulong = 0x00008000; +pub const ISC_REQ_INTEGRITY: ::c_ulong = 0x00010000; +pub const ISC_REQ_IDENTIFY: ::c_ulong = 0x00020000; +pub const ISC_REQ_NULL_SESSION: ::c_ulong = 0x00040000; +pub const ISC_REQ_MANUAL_CRED_VALIDATION: ::c_ulong = 0x00080000; +pub const ISC_REQ_RESERVED1: ::c_ulong = 0x00100000; +pub const ISC_REQ_FRAGMENT_TO_FIT: ::c_ulong = 0x00200000; +pub const ISC_REQ_FORWARD_CREDENTIALS: ::c_ulong = 0x00400000; +pub const ISC_REQ_NO_INTEGRITY: ::c_ulong = 0x00800000; +pub const ISC_REQ_USE_HTTP_STYLE: ::c_ulong = 0x01000000; +pub const ISC_REQ_UNVERIFIED_TARGET_NAME: ::c_ulong = 0x20000000; +pub const ISC_REQ_CONFIDENTIALITY_ONLY: ::c_ulong = 0x40000000; +pub const ISC_RET_DELEGATE: ::c_ulong = 0x00000001; +pub const ISC_RET_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ISC_RET_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ISC_RET_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ISC_RET_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ISC_RET_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ISC_RET_USED_COLLECTED_CREDS: ::c_ulong = 0x00000040; +pub const ISC_RET_USED_SUPPLIED_CREDS: ::c_ulong = 0x00000080; +pub const ISC_RET_ALLOCATED_MEMORY: ::c_ulong = 0x00000100; +pub const ISC_RET_USED_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ISC_RET_DATAGRAM: ::c_ulong = 0x00000400; +pub const ISC_RET_CONNECTION: ::c_ulong = 0x00000800; +pub const ISC_RET_INTERMEDIATE_RETURN: ::c_ulong = 0x00001000; +pub const ISC_RET_CALL_LEVEL: ::c_ulong = 0x00002000; +pub const ISC_RET_EXTENDED_ERROR: ::c_ulong = 0x00004000; +pub const ISC_RET_STREAM: ::c_ulong = 0x00008000; +pub const ISC_RET_INTEGRITY: ::c_ulong = 0x00010000; +pub const ISC_RET_IDENTIFY: ::c_ulong = 0x00020000; +pub const ISC_RET_NULL_SESSION: ::c_ulong = 0x00040000; +pub const ISC_RET_MANUAL_CRED_VALIDATION: ::c_ulong = 0x00080000; +pub const ISC_RET_RESERVED1: ::c_ulong = 0x00100000; +pub const ISC_RET_FRAGMENT_ONLY: ::c_ulong = 0x00200000; +pub const ISC_RET_FORWARD_CREDENTIALS: ::c_ulong = 0x00400000; +pub const ISC_RET_USED_HTTP_STYLE: ::c_ulong = 0x01000000; +pub const ISC_RET_NO_ADDITIONAL_TOKEN: ::c_ulong = 0x02000000; +pub const ISC_RET_REAUTHENTICATION: ::c_ulong = 0x08000000; +pub const ISC_RET_CONFIDENTIALITY_ONLY: ::c_ulong = 0x40000000; +pub const ASC_REQ_DELEGATE: ::c_ulong = 0x00000001; +pub const ASC_REQ_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ASC_REQ_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ASC_REQ_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ASC_REQ_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ASC_REQ_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ASC_REQ_SESSION_TICKET: ::c_ulong = 0x00000040; +pub const ASC_REQ_ALLOCATE_MEMORY: ::c_ulong = 0x00000100; +pub const ASC_REQ_USE_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ASC_REQ_DATAGRAM: ::c_ulong = 0x00000400; +pub const ASC_REQ_CONNECTION: ::c_ulong = 0x00000800; +pub const ASC_REQ_CALL_LEVEL: ::c_ulong = 0x00001000; +pub const ASC_REQ_EXTENDED_ERROR: ::c_ulong = 0x00008000; +pub const ASC_REQ_STREAM: ::c_ulong = 0x00010000; +pub const ASC_REQ_INTEGRITY: ::c_ulong = 0x00020000; +pub const ASC_REQ_LICENSING: ::c_ulong = 0x00040000; +pub const ASC_REQ_IDENTIFY: ::c_ulong = 0x00080000; +pub const ASC_REQ_ALLOW_NULL_SESSION: ::c_ulong = 0x00100000; +pub const ASC_REQ_ALLOW_NON_USER_LOGONS: ::c_ulong = 0x00200000; +pub const ASC_REQ_ALLOW_CONTEXT_REPLAY: ::c_ulong = 0x00400000; +pub const ASC_REQ_FRAGMENT_TO_FIT: ::c_ulong = 0x00800000; +pub const ASC_REQ_FRAGMENT_SUPPLIED: ::c_ulong = 0x00002000; +pub const ASC_REQ_NO_TOKEN: ::c_ulong = 0x01000000; +pub const ASC_REQ_PROXY_BINDINGS: ::c_ulong = 0x04000000; +pub const ASC_REQ_ALLOW_MISSING_BINDINGS: ::c_ulong = 0x10000000; +pub const ASC_RET_DELEGATE: ::c_ulong = 0x00000001; +pub const ASC_RET_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ASC_RET_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ASC_RET_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ASC_RET_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ASC_RET_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ASC_RET_SESSION_TICKET: ::c_ulong = 0x00000040; +pub const ASC_RET_ALLOCATED_MEMORY: ::c_ulong = 0x00000100; +pub const ASC_RET_USED_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ASC_RET_DATAGRAM: ::c_ulong = 0x00000400; +pub const ASC_RET_CONNECTION: ::c_ulong = 0x00000800; +pub const ASC_RET_CALL_LEVEL: ::c_ulong = 0x00002000; +pub const ASC_RET_THIRD_LEG_FAILED: ::c_ulong = 0x00004000; +pub const ASC_RET_EXTENDED_ERROR: ::c_ulong = 0x00008000; +pub const ASC_RET_STREAM: ::c_ulong = 0x00010000; +pub const ASC_RET_INTEGRITY: ::c_ulong = 0x00020000; +pub const ASC_RET_LICENSING: ::c_ulong = 0x00040000; +pub const ASC_RET_IDENTIFY: ::c_ulong = 0x00080000; +pub const ASC_RET_NULL_SESSION: ::c_ulong = 0x00100000; +pub const ASC_RET_ALLOW_NON_USER_LOGONS: ::c_ulong = 0x00200000; +pub const ASC_RET_ALLOW_CONTEXT_REPLAY: ::c_ulong = 0x00400000; +pub const ASC_RET_FRAGMENT_ONLY: ::c_ulong = 0x00800000; +pub const ASC_RET_NO_TOKEN: ::c_ulong = 0x01000000; +pub const ASC_RET_NO_ADDITIONAL_TOKEN: ::c_ulong = 0x02000000; +pub const SECPKG_CRED_ATTR_NAMES: ::c_ulong = 1; +pub const SECPKG_CRED_ATTR_SSI_PROVIDER: ::c_ulong = 2; +pub const SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS: ::c_ulong = 3; +pub const SECPKG_CRED_ATTR_CERT: ::c_ulong = 4; +STRUCT!{struct SecPkgCredentials_NamesW { + sUserName: *mut SEC_WCHAR, +}} +pub type PSecPkgCredentials_NamesW = *mut SecPkgCredentials_NamesW; +STRUCT!{struct SecPkgCredentials_NamesA { + sUserName: *mut SEC_CHAR, +}} +pub type PSecPkgCredentials_NamesA = *mut SecPkgCredentials_NamesA; +STRUCT!{struct SecPkgCredentials_SSIProviderW { + sProviderName: *mut SEC_WCHAR, + ProviderInfoLength: ::c_ulong, + ProviderInfo: *mut ::c_char, +}} +pub type PSecPkgCredentials_SSIProviderW = *mut SecPkgCredentials_SSIProviderW; +STRUCT!{struct SecPkgCredentials_SSIProviderA { + sProviderName: *mut SEC_CHAR, + ProviderInfoLength: ::c_ulong, + ProviderInfo: *mut ::c_char, +}} +pub type PSecPkgCredentials_SSIProviderA = *mut SecPkgCredentials_SSIProviderA; +pub const KDC_PROXY_SETTINGS_V1: ::ULONG = 1; +pub const KDC_PROXY_SETTINGS_FLAGS_FORCEPROXY: ::ULONG = 0x1; +STRUCT!{struct SecPkgCredentials_KdcProxySettingsW { + Version: ::ULONG, + Flags: ::ULONG, + ProxyServerOffset: ::USHORT, + ProxyServerLength: ::USHORT, + ClientTlsCredOffset: ::USHORT, + ClientTlsCredLength: ::USHORT, +}} +pub type PSecPkgCredentials_KdcProxySettingsW = *mut SecPkgCredentials_KdcProxySettingsW; +STRUCT!{struct SecPkgCredentials_Cert { + EncodedCertSize: ::c_ulong, + EncodedCert: *mut ::c_uchar, +}} +pub type PSecPkgCredentials_Cert = *mut SecPkgCredentials_Cert; +pub const SECPKG_ATTR_SIZES: ::c_ulong = 0; +pub const SECPKG_ATTR_NAMES: ::c_ulong = 1; +pub const SECPKG_ATTR_LIFESPAN: ::c_ulong = 2; +pub const SECPKG_ATTR_DCE_INFO: ::c_ulong = 3; +pub const SECPKG_ATTR_STREAM_SIZES: ::c_ulong = 4; +pub const SECPKG_ATTR_KEY_INFO: ::c_ulong = 5; +pub const SECPKG_ATTR_AUTHORITY: ::c_ulong = 6; +pub const SECPKG_ATTR_PROTO_INFO: ::c_ulong = 7; +pub const SECPKG_ATTR_PASSWORD_EXPIRY: ::c_ulong = 8; +pub const SECPKG_ATTR_SESSION_KEY: ::c_ulong = 9; +pub const SECPKG_ATTR_PACKAGE_INFO: ::c_ulong = 10; +pub const SECPKG_ATTR_USER_FLAGS: ::c_ulong = 11; +pub const SECPKG_ATTR_NEGOTIATION_INFO: ::c_ulong = 12; +pub const SECPKG_ATTR_NATIVE_NAMES: ::c_ulong = 13; +pub const SECPKG_ATTR_FLAGS: ::c_ulong = 14; +pub const SECPKG_ATTR_USE_VALIDATED: ::c_ulong = 15; +pub const SECPKG_ATTR_CREDENTIAL_NAME: ::c_ulong = 16; +pub const SECPKG_ATTR_TARGET_INFORMATION: ::c_ulong = 17; +pub const SECPKG_ATTR_ACCESS_TOKEN: ::c_ulong = 18; +pub const SECPKG_ATTR_TARGET: ::c_ulong = 19; +pub const SECPKG_ATTR_AUTHENTICATION_ID: ::c_ulong = 20; +pub const SECPKG_ATTR_LOGOFF_TIME: ::c_ulong = 21; +pub const SECPKG_ATTR_NEGO_KEYS: ::c_ulong = 22; +pub const SECPKG_ATTR_PROMPTING_NEEDED: ::c_ulong = 24; +pub const SECPKG_ATTR_UNIQUE_BINDINGS: ::c_ulong = 25; +pub const SECPKG_ATTR_ENDPOINT_BINDINGS: ::c_ulong = 26; +pub const SECPKG_ATTR_CLIENT_SPECIFIED_TARGET: ::c_ulong = 27; +pub const SECPKG_ATTR_LAST_CLIENT_TOKEN_STATUS: ::c_ulong = 30; +pub const SECPKG_ATTR_NEGO_PKG_INFO: ::c_ulong = 31; +pub const SECPKG_ATTR_NEGO_STATUS: ::c_ulong = 32; +pub const SECPKG_ATTR_CONTEXT_DELETED: ::c_ulong = 33; +pub const SECPKG_ATTR_DTLS_MTU: ::c_ulong = 34; +pub const SECPKG_ATTR_DATAGRAM_SIZES: ::c_ulong = SECPKG_ATTR_STREAM_SIZES; +pub const SECPKG_ATTR_SUBJECT_SECURITY_ATTRIBUTES: ::c_ulong = 128; +pub const SECPKG_ATTR_APPLICATION_PROTOCOL: ::c_ulong = 35; +STRUCT!{struct SecPkgContext_SubjectAttributes { + AttributeInfo: *mut ::c_void, +}} +pub type PSecPkgContext_SubjectAttributes = *mut SecPkgContext_SubjectAttributes; +pub const SECPKG_ATTR_NEGO_INFO_FLAG_NO_KERBEROS: ::c_ulong = 0x1; +pub const SECPKG_ATTR_NEGO_INFO_FLAG_NO_NTLM: ::c_ulong = 0x2; +ENUM!{enum SECPKG_CRED_CLASS { + SecPkgCredClass_None = 0, + SecPkgCredClass_Ephemeral = 10, + SecPkgCredClass_PersistedGeneric = 20, + SecPkgCredClass_PersistedSpecific = 30, + SecPkgCredClass_Explicit = 40, +}} +pub type PSECPKG_CRED_CLASS = *mut SECPKG_CRED_CLASS; +STRUCT!{struct SecPkgContext_CredInfo { + CredClass: SECPKG_CRED_CLASS, + IsPromptingNeeded: ::c_ulong, +}} +pub type PSecPkgContext_CredInfo = *mut SecPkgContext_CredInfo; +STRUCT!{struct SecPkgContext_NegoPackageInfo { + PackageMask: ::c_ulong, +}} +pub type PSecPkgContext_NegoPackageInfo = *mut SecPkgContext_NegoPackageInfo; +STRUCT!{struct SecPkgContext_NegoStatus { + LastStatus: ::c_ulong, +}} +pub type PSecPkgContext_NegoStatus = *mut SecPkgContext_NegoStatus; +STRUCT!{struct SecPkgContext_Sizes { + cbMaxToken: ::c_ulong, + cbMaxSignature: ::c_ulong, + cbBlockSize: ::c_ulong, + cbSecurityTrailer: ::c_ulong, +}} +pub type PSecPkgContext_Sizes = *mut SecPkgContext_Sizes; +STRUCT!{struct SecPkgContext_StreamSizes { + cbHeader: ::c_ulong, + cbTrailer: ::c_ulong, + cbMaximumMessage: ::c_ulong, + cBuffers: ::c_ulong, + cbBlockSize: ::c_ulong, +}} +pub type PSecPkgContext_StreamSizes = *mut SecPkgContext_StreamSizes; +pub type SecPkgContext_DatagramSizes = SecPkgContext_StreamSizes; +pub type PSecPkgContext_DatagramSizes = PSecPkgContext_StreamSizes; +STRUCT!{struct SecPkgContext_NamesW { + sUserName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_NamesW = *mut SecPkgContext_NamesW; +ENUM!{enum SECPKG_ATTR_LCT_STATUS { + SecPkgAttrLastClientTokenYes, + SecPkgAttrLastClientTokenNo, + SecPkgAttrLastClientTokenMaybe, +}} +pub type PSECPKG_ATTR_LCT_STATUS = *mut SECPKG_ATTR_LCT_STATUS; +STRUCT!{struct SecPkgContext_LastClientTokenStatus { + LastClientTokenStatus: SECPKG_ATTR_LCT_STATUS, +}} +pub type PSecPkgContext_LastClientTokenStatus = *mut SecPkgContext_LastClientTokenStatus; +STRUCT!{struct SecPkgContext_NamesA { + sUserName: *mut SEC_CHAR, +}} +pub type PSecPkgContext_NamesA = *mut SecPkgContext_NamesA; +STRUCT!{struct SecPkgContext_Lifespan { + tsStart: TimeStamp, + tsExpiry: TimeStamp, +}} +pub type PSecPkgContext_Lifespan = *mut SecPkgContext_Lifespan; +STRUCT!{struct SecPkgContext_DceInfo { + AuthzSvc: ::c_ulong, + pPac: *mut ::c_void, +}} +pub type PSecPkgContext_DceInfo = *mut SecPkgContext_DceInfo; +STRUCT!{struct SecPkgContext_KeyInfoA { + sSignatureAlgorithmName: *mut ::SEC_CHAR, + sEncryptAlgorithmName: *mut ::SEC_CHAR, + KeySize: ::c_ulong, + SignatureAlgorithm: ::c_ulong, + EncryptAlgorithm: ::c_ulong, +}} +pub type PSecPkgContext_KeyInfoA = *mut SecPkgContext_KeyInfoA; +STRUCT!{struct SecPkgContext_KeyInfoW { + sSignatureAlgorithmName: *mut ::SEC_WCHAR, + sEncryptAlgorithmName: *mut ::SEC_WCHAR, + KeySize: ::c_ulong, + SignatureAlgorithm: ::c_ulong, + EncryptAlgorithm: ::c_ulong, +}} +pub type PSecPkgContext_KeyInfoW = *mut SecPkgContext_KeyInfoW; +STRUCT!{struct SecPkgContext_AuthorityA { + sAuthorityName: *mut SEC_CHAR, +}} +pub type PSecPkgContext_AuthorityA = *mut SecPkgContext_AuthorityA; +STRUCT!{struct SecPkgContext_AuthorityW { + sAuthorityName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_AuthorityW = *mut SecPkgContext_AuthorityW; +STRUCT!{struct SecPkgContext_ProtoInfoA { + sProtocolName: *mut SEC_CHAR, + majorVersion: ::c_ulong, + minorVersion: ::c_ulong, +}} +pub type PSecPkgContext_ProtoInfoA = *mut SecPkgContext_ProtoInfoA; +STRUCT!{struct SecPkgContext_ProtoInfoW { + sProtocolName: *mut SEC_WCHAR, + majorVersion: ::c_ulong, + minorVersion: ::c_ulong, +}} +pub type PSecPkgContext_ProtoInfoW = *mut SecPkgContext_ProtoInfoW; +STRUCT!{struct SecPkgContext_PasswordExpiry { + tsPasswordExpires: TimeStamp, +}} +pub type PSecPkgContext_PasswordExpiry = *mut SecPkgContext_PasswordExpiry; +STRUCT!{struct SecPkgContext_LogoffTime { + tsLogoffTime: TimeStamp, +}} +pub type PSecPkgContext_LogoffTime = *mut SecPkgContext_LogoffTime; +STRUCT!{struct SecPkgContext_SessionKey { + SessionKeyLength: ::c_ulong, + SessionKey: *mut ::c_uchar, +}} +pub type PSecPkgContext_SessionKey = *mut SecPkgContext_SessionKey; +STRUCT!{struct SecPkgContext_NegoKeys { + KeyType: ::c_ulong, + KeyLength: ::c_ushort, + KeyValue: *mut ::c_uchar, + VerifyKeyType: ::c_ulong, + VerifyKeyLength: ::c_ushort, + VerifyKeyValue: *mut ::c_uchar, +}} +pub type PSecPkgContext_NegoKeys = *mut SecPkgContext_NegoKeys; +STRUCT!{struct SecPkgContext_PackageInfoW { + PackageInfo: PSecPkgInfoW, +}} +pub type PSecPkgContext_PackageInfoW = *mut SecPkgContext_PackageInfoW; +STRUCT!{struct SecPkgContext_PackageInfoA { + PackageInfo: PSecPkgInfoA, +}} +pub type PSecPkgContext_PackageInfoA = *mut SecPkgContext_PackageInfoA; +STRUCT!{struct SecPkgContext_UserFlags { + UserFlags: ::c_ulong, +}} +pub type PSecPkgContext_UserFlags = *mut SecPkgContext_UserFlags; +STRUCT!{struct SecPkgContext_Flags { + Flags: ::c_ulong, +}} +pub type PSecPkgContext_Flags = *mut SecPkgContext_Flags; +STRUCT!{struct SecPkgContext_NegotiationInfoA { + PackageInfo: PSecPkgInfoA, + NegotiationState: ::c_ulong, +}} +pub type PSecPkgContext_NegotiationInfoA = *mut SecPkgContext_NegotiationInfoA; +STRUCT!{struct SecPkgContext_NegotiationInfoW { + PackageInfo: PSecPkgInfoW, + NegotiationState: ::c_ulong, +}} +pub type PSecPkgContext_NegotiationInfoW = *mut SecPkgContext_NegotiationInfoW; +pub const SECPKG_NEGOTIATION_COMPLETE: ::c_ulong = 0; +pub const SECPKG_NEGOTIATION_OPTIMISTIC: ::c_ulong = 1; +pub const SECPKG_NEGOTIATION_IN_PROGRESS: ::c_ulong = 2; +pub const SECPKG_NEGOTIATION_DIRECT: ::c_ulong = 3; +pub const SECPKG_NEGOTIATION_TRY_MULTICRED: ::c_ulong = 4; +STRUCT!{struct SecPkgContext_NativeNamesW { + sClientName: SEC_WCHAR, + sServerName: SEC_WCHAR, +}} +pub type PSecPkgContext_NativeNamesW = *mut SecPkgContext_NativeNamesW; +STRUCT!{struct SecPkgContext_NativeNamesA { + sClientName: SEC_CHAR, + sServerName: SEC_CHAR, +}} +pub type PSecPkgContext_NativeNamesA = *mut SecPkgContext_NativeNamesA; +STRUCT!{struct SecPkgContext_CredentialNameW { + CredentialType: ::c_ulong, + sCredentialName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_CredentialNameW = *mut SecPkgContext_CredentialNameW; +STRUCT!{struct SecPkgContext_CredentialNameA { + CredentialType: ::c_ulong, + sCredentialName: *mut SEC_CHAR, +}} +pub type PSecPkgContext_CredentialNameA = *mut SecPkgContext_CredentialNameA; +STRUCT!{struct SecPkgContext_AccessToken { + AccessToken: *mut ::c_void, +}} +pub type PSecPkgContext_AccessToken = *mut SecPkgContext_AccessToken; +STRUCT!{struct SecPkgContext_TargetInformation { + MarshalledTargetInfoLength: ::c_ulong, + MarshalledTargetInfo: *mut ::c_uchar, +}} +pub type PSecPkgContext_TargetInformation = *mut SecPkgContext_TargetInformation; +STRUCT!{struct SecPkgContext_AuthzID { + AuthzIDLength: ::c_ulong, + AuthzID: *mut ::c_char, +}} +pub type PSecPkgContext_AuthzID = *mut SecPkgContext_AuthzID; +STRUCT!{struct SecPkgContext_Target { + TargetLength: ::c_ulong, + Target: *mut ::c_char, +}} +pub type PSecPkgContext_Target = *mut SecPkgContext_Target; +STRUCT!{struct SecPkgContext_ClientSpecifiedTarget { + sTargetName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_ClientSpecifiedTarget = *mut SecPkgContext_ClientSpecifiedTarget; +STRUCT!{struct SecPkgContext_Bindings { + BindingsLength: ::c_ulong, + Bindings: *mut SEC_CHANNEL_BINDINGS, +}} +pub type PSecPkgContext_Bindings = *mut SecPkgContext_Bindings; +ENUM!{enum SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS { + SecApplicationProtocolNegotiationStatus_None, + SecApplicationProtocolNegotiationStatus_Success, + SecApplicationProtocolNegotiationStatus_SelectedClientOnly, +}} +pub type PSEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS = + *mut SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS; +pub const MAX_PROTOCOL_ID_SIZE: usize = 0xff; +STRUCT!{nodebug struct SecPkgContext_ApplicationProtocol { + ProtoNegoStatus: SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS, + ProtoNegoExt: SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT, + ProtocolIdSize: ::c_uchar, + ProtocolId: [::c_uchar; MAX_PROTOCOL_ID_SIZE], +}} +pub type PSecPkgContext_ApplicationProtocol = *mut SecPkgContext_ApplicationProtocol; +pub type SEC_GET_KEY_FN = Option<unsafe extern "system" fn( + Arg: *mut ::c_void, Principal: *mut ::c_void, KeyVer: ::c_ulong, Key: *mut *mut ::c_void, + Status: *mut SECURITY_STATUS, +)>; +pub const SECPKG_CONTEXT_EXPORT_RESET_NEW: ::c_ulong = 0x00000001; +pub const SECPKG_CONTEXT_EXPORT_DELETE_OLD: ::c_ulong = 0x00000002; +pub const SECPKG_CONTEXT_EXPORT_TO_KERNEL: ::c_ulong = 0x00000004; +pub type ACQUIRE_CREDENTIALS_HANDLE_FN_W = Option<unsafe extern "system" fn( + *mut SEC_WCHAR, *mut SEC_WCHAR, ::c_ulong, *mut ::c_void, *mut ::c_void, SEC_GET_KEY_FN, + *mut ::c_void, PCredHandle, PTimeStamp, +) -> SECURITY_STATUS>; +pub type ACQUIRE_CREDENTIALS_HANDLE_FN_A = Option<unsafe extern "system" fn( + *mut SEC_CHAR, *mut SEC_CHAR, ::c_ulong, *mut ::c_void, *mut ::c_void, SEC_GET_KEY_FN, + *mut ::c_void, PCredHandle, PTimeStamp, +) -> SECURITY_STATUS>; +pub type FREE_CREDENTIALS_HANDLE_FN = Option<unsafe extern "system" fn( + PCredHandle, +) -> SECURITY_STATUS>; +pub type ADD_CREDENTIALS_FN_W = Option<unsafe extern "system" fn( + PCredHandle, *mut SEC_WCHAR, *mut SEC_WCHAR, ::c_ulong, *mut ::c_void, SEC_GET_KEY_FN, + *mut ::c_void, PTimeStamp, +) -> SECURITY_STATUS>; +pub type ADD_CREDENTIALS_FN_A = Option<unsafe extern "system" fn( + PCredHandle, *mut SEC_CHAR, *mut SEC_CHAR, ::c_ulong, *mut ::c_void, SEC_GET_KEY_FN, + *mut ::c_void, PTimeStamp, +) -> SECURITY_STATUS>; +pub type CHANGE_PASSWORD_FN_W = Option<unsafe extern "system" fn( + *mut SEC_WCHAR, *mut SEC_WCHAR, *mut SEC_WCHAR, *mut SEC_WCHAR, *mut SEC_WCHAR, ::BOOLEAN, + ::c_ulong, PSecBufferDesc, +) -> SECURITY_STATUS>; +pub type CHANGE_PASSWORD_FN_A = Option<unsafe extern "system" fn( + *mut SEC_CHAR, *mut SEC_CHAR, *mut SEC_CHAR, *mut SEC_CHAR, *mut SEC_CHAR, ::BOOLEAN, + ::c_ulong, PSecBufferDesc, +) -> SECURITY_STATUS>; +//1844 +ENUM!{enum SecDelegationType { + SecFull, + SecService, + SecTree, + SecDirectory, + SecObject, +}} +pub type PSecDelegationType = *mut SecDelegationType; +STRUCT!{struct SEC_WINNT_AUTH_BYTE_VECTOR { + ByteArrayOffset: ::c_ulong, + ByteArrayLength: ::c_ushort, +}} +pub type PSEC_WINNT_AUTH_BYTE_VECTOR = *mut SEC_WINNT_AUTH_BYTE_VECTOR; +STRUCT!{struct SEC_WINNT_AUTH_DATA { + CredType: ::GUID, + CredData: SEC_WINNT_AUTH_BYTE_VECTOR, +}} +pub type PSEC_WINNT_AUTH_DATA = *mut SEC_WINNT_AUTH_DATA; +STRUCT!{struct SEC_WINNT_AUTH_PACKED_CREDENTIALS { + cbHeaderLength: ::c_ushort, + cbStructureLength: ::c_ushort, + AuthData: SEC_WINNT_AUTH_DATA, +}} +pub type PSEC_WINNT_AUTH_PACKED_CREDENTIALS = *mut SEC_WINNT_AUTH_PACKED_CREDENTIALS; +DEFINE_GUID!(SEC_WINNT_AUTH_DATA_TYPE_PASSWORD, 0x28bfc32f, 0x10f6, 0x4738, + 0x98, 0xd1, 0x1a, 0xc0, 0x61, 0xdf, 0x71, 0x6a); +DEFINE_GUID!(SEC_WINNT_AUTH_DATA_TYPE_CERT, 0x235f69ad, 0x73fb, 0x4dbc, + 0x82, 0x3, 0x6, 0x29, 0xe7, 0x39, 0x33, 0x9b); +STRUCT!{struct SEC_WINNT_AUTH_DATA_PASSWORD { + UnicodePassword: SEC_WINNT_AUTH_BYTE_VECTOR, +}} +pub type PSEC_WINNT_AUTH_DATA_PASSWORD = *mut SEC_WINNT_AUTH_DATA_PASSWORD; +DEFINE_GUID!(SEC_WINNT_AUTH_DATA_TYPE_CSP_DATA, 0x68fd9879, 0x79c, 0x4dfe, + 0x82, 0x81, 0x57, 0x8a, 0xad, 0xc1, 0xc1, 0x0); +STRUCT!{struct SEC_WINNT_AUTH_CERTIFICATE_DATA { + cbHeaderLength: ::c_ushort, + cbStructureLength: ::c_ushort, + Certificate: SEC_WINNT_AUTH_BYTE_VECTOR, +}} +pub type PSEC_WINNT_AUTH_CERTIFICATE_DATA = *mut SEC_WINNT_AUTH_CERTIFICATE_DATA; +STRUCT!{struct SEC_WINNT_CREDUI_CONTEXT_VECTOR { + CredUIContextArrayOffset: ::ULONG, + CredUIContextCount: ::USHORT, +}} +pub type PSEC_WINNT_CREDUI_CONTEXT_VECTOR = *mut SEC_WINNT_CREDUI_CONTEXT_VECTOR; +STRUCT!{struct SEC_WINNT_AUTH_SHORT_VECTOR { + ShortArrayOffset: ::ULONG, + ShortArrayCount: ::USHORT, +}} +pub type PSEC_WINNT_AUTH_SHORT_VECTOR = *mut SEC_WINNT_AUTH_SHORT_VECTOR; +STRUCT!{struct CREDUIWIN_MARSHALED_CONTEXT { + StructureType: ::GUID, + cbHeaderLength: ::USHORT, + LogonId: ::LUID, + MarshaledDataType: ::GUID, + MarshaledDataOffset: ::ULONG, + MarshaledDataLength: ::USHORT, +}} +pub type PCREDUIWIN_MARSHALED_CONTEXT = *mut CREDUIWIN_MARSHALED_CONTEXT; +STRUCT!{struct SEC_WINNT_CREDUI_CONTEXT { + cbHeaderLength: ::USHORT, + CredUIContextHandle: ::HANDLE, + UIInfo: ::PCREDUI_INFOW, + dwAuthError: ::ULONG, + pInputAuthIdentity: PSEC_WINNT_AUTH_IDENTITY_OPAQUE, + TargetName: ::PUNICODE_STRING, +}} +pub type PSEC_WINNT_CREDUI_CONTEXT = *mut SEC_WINNT_CREDUI_CONTEXT; +pub type PSEC_WINNT_AUTH_IDENTITY_OPAQUE = ::PVOID; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/strmif.rs b/bash-5.1/vendor/winapi-0.2.8/src/strmif.rs new file mode 100644 index 0000000..0edfe72 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/strmif.rs @@ -0,0 +1,4 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub type REFERENCE_TIME = LONGLONG; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/subauth.rs b/bash-5.1/vendor/winapi-0.2.8/src/subauth.rs new file mode 100644 index 0000000..d84dc8c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/subauth.rs @@ -0,0 +1,198 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Types and macros for Subauthentication Packages. +STRUCT!{struct UNICODE_STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PWSTR, +}} +pub type PUNICODE_STRING = *mut UNICODE_STRING; +STRUCT!{struct STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PCHAR, +}} +pub type PSTRING = *mut STRING; +STRUCT!{struct OLD_LARGE_INTEGER { + LowPart: ::ULONG, + HighPart: ::LONG, +}} +pub type POLD_LARGE_INTEGER = *mut OLD_LARGE_INTEGER; +pub type SAM_HANDLE = ::PVOID; +pub type PSAM_HANDLE = *mut ::PVOID; +pub const USER_ACCOUNT_DISABLED: ::ULONG = 0x00000001; +pub const USER_HOME_DIRECTORY_REQUIRED: ::ULONG = 0x00000002; +pub const USER_PASSWORD_NOT_REQUIRED: ::ULONG = 0x00000004; +pub const USER_TEMP_DUPLICATE_ACCOUNT: ::ULONG = 0x00000008; +pub const USER_NORMAL_ACCOUNT: ::ULONG = 0x00000010; +pub const USER_MNS_LOGON_ACCOUNT: ::ULONG = 0x00000020; +pub const USER_INTERDOMAIN_TRUST_ACCOUNT: ::ULONG = 0x00000040; +pub const USER_WORKSTATION_TRUST_ACCOUNT: ::ULONG = 0x00000080; +pub const USER_SERVER_TRUST_ACCOUNT: ::ULONG = 0x00000100; +pub const USER_DONT_EXPIRE_PASSWORD: ::ULONG = 0x00000200; +pub const USER_ACCOUNT_AUTO_LOCKED: ::ULONG = 0x00000400; +pub const USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED: ::ULONG = 0x00000800; +pub const USER_SMARTCARD_REQUIRED: ::ULONG = 0x00001000; +pub const USER_TRUSTED_FOR_DELEGATION: ::ULONG = 0x00002000; +pub const USER_NOT_DELEGATED: ::ULONG = 0x00004000; +pub const USER_USE_DES_KEY_ONLY: ::ULONG = 0x00008000; +pub const USER_DONT_REQUIRE_PREAUTH: ::ULONG = 0x00010000; +pub const USER_PASSWORD_EXPIRED: ::ULONG = 0x00020000; +pub const USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: ::ULONG = 0x00040000; +pub const USER_NO_AUTH_DATA_REQUIRED: ::ULONG = 0x00080000; +pub const USER_PARTIAL_SECRETS_ACCOUNT: ::ULONG = 0x00100000; +pub const USER_USE_AES_KEYS: ::ULONG = 0x00200000; +pub const NEXT_FREE_ACCOUNT_CONTROL_BIT: ::ULONG = USER_USE_AES_KEYS << 1; +pub const USER_MACHINE_ACCOUNT_MASK: ::ULONG = USER_INTERDOMAIN_TRUST_ACCOUNT + | USER_WORKSTATION_TRUST_ACCOUNT | USER_SERVER_TRUST_ACCOUNT; +pub const USER_ACCOUNT_TYPE_MASK: ::ULONG = USER_TEMP_DUPLICATE_ACCOUNT | USER_NORMAL_ACCOUNT + | USER_MACHINE_ACCOUNT_MASK; +pub const USER_COMPUTED_ACCOUNT_CONTROL_BITS: ::ULONG = USER_ACCOUNT_AUTO_LOCKED +| USER_PASSWORD_EXPIRED; +pub const SAM_DAYS_PER_WEEK: ::USHORT = 7; +pub const SAM_HOURS_PER_WEEK: ::USHORT = 24 * SAM_DAYS_PER_WEEK; +pub const SAM_MINUTES_PER_WEEK: ::USHORT = 60 * SAM_HOURS_PER_WEEK; +STRUCT!{struct LOGON_HOURS { + UnitsPerWeek: ::USHORT, + LogonHours: ::PUCHAR, +}} +pub type PLOGON_HOURS = *mut LOGON_HOURS; +STRUCT!{struct SR_SECURITY_DESCRIPTOR { + Length: ::ULONG, + SecurityDescriptor: ::PUCHAR, +}} +pub type PSR_SECURITY_DESCRIPTOR = *mut SR_SECURITY_DESCRIPTOR; +STRUCT!{struct USER_ALL_INFORMATION { + LastLogon: ::LARGE_INTEGER, + LastLogoff: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + AccountExpires: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, + UserName: UNICODE_STRING, + FullName: UNICODE_STRING, + HomeDirectory: UNICODE_STRING, + HomeDirectoryDrive: UNICODE_STRING, + ScriptPath: UNICODE_STRING, + ProfilePath: UNICODE_STRING, + AdminComment: UNICODE_STRING, + WorkStations: UNICODE_STRING, + UserComment: UNICODE_STRING, + Parameters: UNICODE_STRING, + LmPassword: UNICODE_STRING, + NtPassword: UNICODE_STRING, + PrivateData: UNICODE_STRING, + SecurityDescriptor: SR_SECURITY_DESCRIPTOR, + UserId: ::ULONG, + PrimaryGroupId: ::ULONG, + UserAccountControl: ::ULONG, + WhichFields: ::ULONG, + LogonHours: LOGON_HOURS, + BadPasswordCount: ::USHORT, + LogonCount: ::USHORT, + CountryCode: ::USHORT, + CodePage: ::USHORT, + LmPasswordPresent: ::BOOLEAN, + NtPasswordPresent: ::BOOLEAN, + PasswordExpired: ::BOOLEAN, + PrivateDataSensitive: ::BOOLEAN, +}} +pub type PUSER_ALL_INFORMATION = *mut USER_ALL_INFORMATION; +pub const USER_ALL_PARAMETERS: ::ULONG = 0x00200000; +pub const CLEAR_BLOCK_LENGTH: usize = 8; +STRUCT!{struct CLEAR_BLOCK { + data: [::CHAR; CLEAR_BLOCK_LENGTH], +}} +pub type PCLEAR_BLOCK = *mut CLEAR_BLOCK; +pub const CYPHER_BLOCK_LENGTH: usize = 8; +STRUCT!{struct CYPHER_BLOCK { + data: [::CHAR; CYPHER_BLOCK_LENGTH], +}} +pub type PCYPHER_BLOCK = *mut CYPHER_BLOCK; +STRUCT!{struct LM_OWF_PASSWORD { + data: [CYPHER_BLOCK; 2], +}} +pub type PLM_OWF_PASSWORD = *mut LM_OWF_PASSWORD; +pub type LM_CHALLENGE = CLEAR_BLOCK; +pub type PLM_CHALLENGE = *mut LM_CHALLENGE; +pub type NT_OWF_PASSWORD = LM_OWF_PASSWORD; +pub type PNT_OWF_PASSWORD = *mut NT_OWF_PASSWORD; +pub type NT_CHALLENGE = LM_CHALLENGE; +pub type PNT_CHALLENGE = *mut NT_CHALLENGE; +pub const USER_SESSION_KEY_LENGTH: usize = CYPHER_BLOCK_LENGTH * 2; +STRUCT!{struct USER_SESSION_KEY { + data: [CYPHER_BLOCK; 2], +}} +pub type PUSER_SESSION_KEY = *mut USER_SESSION_KEY; +ENUM!{enum NETLOGON_LOGON_INFO_CLASS { + NetlogonInteractiveInformation = 1, + NetlogonNetworkInformation, + NetlogonServiceInformation, + NetlogonGenericInformation, + NetlogonInteractiveTransitiveInformation, + NetlogonNetworkTransitiveInformation, + NetlogonServiceTransitiveInformation, +}} +STRUCT!{struct NETLOGON_LOGON_IDENTITY_INFO { + LogonDomainName: UNICODE_STRING, + ParameterControl: ::ULONG, + LogonId: OLD_LARGE_INTEGER, + UserName: UNICODE_STRING, + Workstation: UNICODE_STRING, +}} +pub type PNETLOGON_LOGON_IDENTITY_INFO = *mut NETLOGON_LOGON_IDENTITY_INFO; +STRUCT!{struct NETLOGON_INTERACTIVE_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + LmOwfPassword: LM_OWF_PASSWORD, + NtOwfPassword: NT_OWF_PASSWORD, +}} +pub type PNETLOGON_INTERACTIVE_INFO = *mut NETLOGON_INTERACTIVE_INFO; +STRUCT!{struct NETLOGON_SERVICE_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + LmOwfPassword: LM_OWF_PASSWORD, + NtOwfPassword: NT_OWF_PASSWORD, +}} +pub type PNETLOGON_SERVICE_INFO = *mut NETLOGON_SERVICE_INFO; +STRUCT!{struct NETLOGON_NETWORK_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + LmChallenge: LM_CHALLENGE, + NtChallengeResponse: STRING, + LmChallengeResponse: STRING, +}} +pub type PNETLOGON_NETWORK_INFO = *mut NETLOGON_NETWORK_INFO; +STRUCT!{struct NETLOGON_GENERIC_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + PackageName: UNICODE_STRING, + DataLength: ::ULONG, + LogonData: ::PUCHAR, +}} +pub type PNETLOGON_GENERIC_INFO = *mut NETLOGON_GENERIC_INFO; +pub const MSV1_0_PASSTHRU: ::ULONG = 0x01; +pub const MSV1_0_GUEST_LOGON: ::ULONG = 0x02; +STRUCT!{struct MSV1_0_VALIDATION_INFO { + LogoffTime: ::LARGE_INTEGER, + KickoffTime: ::LARGE_INTEGER, + LogonServer: UNICODE_STRING, + LogonDomainName: UNICODE_STRING, + SessionKey: USER_SESSION_KEY, + Authoritative: ::BOOLEAN, + UserFlags: ::ULONG, + WhichFields: ::ULONG, + UserId: ::ULONG, +}} +pub type PMSV1_0_VALIDATION_INFO = *mut MSV1_0_VALIDATION_INFO; +pub const MSV1_0_VALIDATION_LOGOFF_TIME: ::ULONG = 0x00000001; +pub const MSV1_0_VALIDATION_KICKOFF_TIME: ::ULONG = 0x00000002; +pub const MSV1_0_VALIDATION_LOGON_SERVER: ::ULONG = 0x00000004; +pub const MSV1_0_VALIDATION_LOGON_DOMAIN: ::ULONG = 0x00000008; +pub const MSV1_0_VALIDATION_SESSION_KEY: ::ULONG = 0x00000010; +pub const MSV1_0_VALIDATION_USER_FLAGS: ::ULONG = 0x00000020; +pub const MSV1_0_VALIDATION_USER_ID: ::ULONG = 0x00000040; +pub const MSV1_0_SUBAUTH_ACCOUNT_DISABLED: ::ULONG = 0x00000001; +pub const MSV1_0_SUBAUTH_PASSWORD: ::ULONG = 0x00000002; +pub const MSV1_0_SUBAUTH_WORKSTATIONS: ::ULONG = 0x00000004; +pub const MSV1_0_SUBAUTH_LOGON_HOURS: ::ULONG = 0x00000008; +pub const MSV1_0_SUBAUTH_ACCOUNT_EXPIRY: ::ULONG = 0x00000010; +pub const MSV1_0_SUBAUTH_PASSWORD_EXPIRY: ::ULONG = 0x00000020; +pub const MSV1_0_SUBAUTH_ACCOUNT_TYPE: ::ULONG = 0x00000040; +pub const MSV1_0_SUBAUTH_LOCKOUT: ::ULONG = 0x00000080; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/synchapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/synchapi.rs new file mode 100644 index 0000000..2eb9d1a --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/synchapi.rs @@ -0,0 +1,14 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-synch-l1 +pub type SRWLOCK = ::RTL_SRWLOCK; +pub type PSRWLOCK = *mut ::RTL_SRWLOCK; +pub type SYNCHRONIZATION_BARRIER = ::RTL_BARRIER; +pub type PSYNCHRONIZATION_BARRIER = ::PRTL_BARRIER; +pub type LPSYNCHRONIZATION_BARRIER = ::PRTL_BARRIER; +pub type PINIT_ONCE_FN = Option<unsafe extern "system" fn( + InitOnce: ::PINIT_ONCE, Parameter: ::PVOID, Context: *mut ::PVOID, +) -> ::BOOL>; +pub type PTIMERAPCROUTINE = Option<unsafe extern "system" fn( + lpArgToCompletionRoutine: ::LPVOID, dwTimerLowValue: ::DWORD, dwTimerHighValue: ::DWORD, +)>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/sysinfoapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/sysinfoapi.rs new file mode 100644 index 0000000..95c38c6 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/sysinfoapi.rs @@ -0,0 +1,46 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-sysinfo-l1. +STRUCT!{struct SYSTEM_INFO { + wProcessorArchitecture: ::WORD, + wReserved: ::WORD, + dwPageSize: ::DWORD, + lpMinimumApplicationAddress: ::LPVOID, + lpMaximumApplicationAddress: ::LPVOID, + dwActiveProcessorMask: ::DWORD_PTR, + dwNumberOfProcessors: ::DWORD, + dwProcessorType: ::DWORD, + dwAllocationGranularity: ::DWORD, + wProcessorLevel: ::WORD, + wProcessorRevision: ::WORD, +}} +UNION!(SYSTEM_INFO, wProcessorArchitecture, dwOemId, dwOemId_mut, ::DWORD); +pub type LPSYSTEM_INFO = *mut SYSTEM_INFO; +STRUCT!{struct MEMORYSTATUSEX { + dwLength: ::DWORD, + dwMemoryLoad: ::DWORD, + ullTotalPhys: ::DWORDLONG, + ullAvailPhys: ::DWORDLONG, + ullTotalPageFile: ::DWORDLONG, + ullAvailPageFile: ::DWORDLONG, + ullTotalVirtual: ::DWORDLONG, + ullAvailVirtual: ::DWORDLONG, + ullAvailExtendedVirtual: ::DWORDLONG, +}} +pub type LPMEMORYSTATUSEX = *mut MEMORYSTATUSEX; +ENUM!{enum COMPUTER_NAME_FORMAT { + ComputerNameNetBIOS, + ComputerNameDnsHostname, + ComputerNameDnsDomain, + ComputerNameDnsFullyQualified, + ComputerNamePhysicalNetBIOS, + ComputerNamePhysicalDnsHostname, + ComputerNamePhysicalDnsDomain, + ComputerNamePhysicalDnsFullyQualified, + ComputerNameMax, +}} +pub type INIT_ONCE = ::RTL_RUN_ONCE; +pub type PINIT_ONCE = ::PRTL_RUN_ONCE; +pub type LPINIT_ONCE = ::PRTL_RUN_ONCE; +pub type CONDITION_VARIABLE = ::RTL_CONDITION_VARIABLE; +pub type PCONDITION_VARIABLE = *mut CONDITION_VARIABLE; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/threadpoolapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/threadpoolapi.rs new file mode 100644 index 0000000..ec21aa0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/threadpoolapi.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-threadpool-l1. +pub type PTP_WIN32_IO_CALLBACK = Option<unsafe extern "system" fn( + Instance: ::PTP_CALLBACK_INSTANCE, Context: ::PVOID, Overlapped: ::PVOID, IoResult: ::ULONG, + NumberOfBytesTransferred: ::ULONG_PTR, Io: ::PTP_IO, +)>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/timezoneapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/timezoneapi.rs new file mode 100644 index 0000000..3c84b20 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/timezoneapi.rs @@ -0,0 +1,27 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! ApiSet Contract for api-ms-win-core-timezone-l1 +pub const TIME_ZONE_ID_INVALID: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct TIME_ZONE_INFORMATION { + Bias: ::LONG, + StandardName: [::WCHAR; 32], + StandardDate: ::SYSTEMTIME, + StandardBias: ::LONG, + DaylightName: [::WCHAR; 32], + DaylightDate: ::SYSTEMTIME, + DaylightBias: ::LONG, +}} +pub type PTIME_ZONE_INFORMATION = *mut TIME_ZONE_INFORMATION; +pub type LPTIME_ZONE_INFORMATION = *mut TIME_ZONE_INFORMATION; +STRUCT!{nodebug struct DYNAMIC_TIME_ZONE_INFORMATION { + Bias: ::LONG, + StandardName: [::WCHAR; 32], + StandardDate: ::SYSTEMTIME, + StandardBias: ::LONG, + DaylightName: [::WCHAR; 32], + DaylightDate: ::SYSTEMTIME, + DaylightBias: ::LONG, + TimeZoneKeyName: [::WCHAR; 128], + DynamicDaylightTimeDisabled: ::BOOLEAN, +}} +pub type PDYNAMIC_TIME_ZONE_INFORMATION = *mut DYNAMIC_TIME_ZONE_INFORMATION; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/tlhelp32.rs b/bash-5.1/vendor/winapi-0.2.8/src/tlhelp32.rs new file mode 100644 index 0000000..2e809b2 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/tlhelp32.rs @@ -0,0 +1,104 @@ +// Copyright © 2015, Gigih Aji Ibrahim +// Licensed under the MIT License <LICENSE.md> +pub const MAX_MODULE_NAME32: usize = 255; +pub const TH32CS_SNAPHEAPLIST: ::DWORD = 0x00000001; +pub const TH32CS_SNAPPROCESS: ::DWORD = 0x00000002; +pub const TH32CS_SNAPTHREAD: ::DWORD = 0x00000004; +pub const TH32CS_SNAPMODULE: ::DWORD = 0x00000008; +pub const TH32CS_SNAPMODULE32: ::DWORD = 0x00000010; +pub const TH32CS_SNAPALL: ::DWORD = + (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE); +pub const TH32CS_INHERIT: ::DWORD = 0x80000000; +STRUCT!{struct HEAPLIST32 { + dwSize: ::SIZE_T, + th32ProcessID: ::DWORD, + th32HeapID: :: ULONG_PTR, + dwFlags: ::DWORD, +}} +pub type PHEAPLIST32 = *mut HEAPLIST32; +pub type LPHEAPLIST32 = *mut HEAPLIST32; +pub const HF32_DEFAULT: ::DWORD = 1; +pub const HF32_SHARED: ::DWORD = 2; +STRUCT!{struct HEAPENTRY32 { + dwSize: ::SIZE_T, + hHandle: ::HANDLE, + dwAddress: ::ULONG_PTR, + dwBlockSize: ::SIZE_T, + dwFlags: ::DWORD, + dwLockCount: ::DWORD, + dwResvd: ::DWORD, + th32ProcessID: ::DWORD, + th32HeapID: ::ULONG_PTR, +}} +pub type PHEAPENTRY32 = *mut HEAPENTRY32; +pub type LPHEAPENTRY32 = *mut HEAPENTRY32; +pub const LF32_FIXED: ::DWORD = 0x00000001; +pub const LF32_FREE: ::DWORD = 0x00000002; +pub const LF32_MOVEABLE: ::DWORD = 0x00000004; +STRUCT!{nodebug struct PROCESSENTRY32W { + dwSize: ::DWORD, + cntUsage: ::DWORD, + th32ProcessID: ::DWORD, + th32DefaultHeapID: ::ULONG_PTR, + th32ModuleID: ::DWORD, + cntThreads: ::DWORD, + th32ParentProcessID: ::DWORD, + pcPriClassBase: ::LONG, + dwFlags: ::DWORD, + szExeFile: [::WCHAR; ::MAX_PATH], +}} +pub type PPROCESSENTRY32W = *mut PROCESSENTRY32W; +pub type LPPROCESSENTRY32W = *mut PROCESSENTRY32W; +STRUCT!{nodebug struct PROCESSENTRY32 { + dwSize: ::DWORD, + cntUsage: ::DWORD, + th32ProcessID: ::DWORD, + th32DefaultHeapID: ::ULONG_PTR, + th32ModuleID: ::DWORD, + cntThreads: ::DWORD, + th32ParentProcessID: ::DWORD, + pcPriClassBase: ::LONG, + dwFlags: ::DWORD, + szExeFile: [::CHAR; ::MAX_PATH], +}} +pub type PPROCESSENTRY32 = *mut PROCESSENTRY32; +pub type LPPROCESSENTRY32 = *mut PROCESSENTRY32; +STRUCT!{struct THREADENTRY32 { + dwSize: ::DWORD, + cntUsage: ::DWORD, + th32ThreadID: ::DWORD, + th32OwnerProcessID: ::DWORD, + tpBasePri: ::LONG, + tpDeltaPri: ::LONG, + dwFlags: ::DWORD, +}} +pub type PTHREADENTRY32 = *mut THREADENTRY32; +pub type LPTHREADENTRY32 = *mut THREADENTRY32; +STRUCT!{nodebug struct MODULEENTRY32W { + dwSize: ::DWORD, + th32ModuleID: ::DWORD, + th32ProcessID: ::DWORD, + GlblcntUsage: ::DWORD, + ProccntUsage: ::DWORD, + modBaseAddr: *mut ::BYTE, + modBaseSize: ::DWORD, + hModule: ::HMODULE, + szModule: [::WCHAR; ::MAX_MODULE_NAME32 + 1], + szExePath: [::WCHAR; ::MAX_PATH], +}} +pub type PMODULEENTRY32W = *mut MODULEENTRY32W; +pub type LPMODULEENTRY32W = *mut MODULEENTRY32W; +STRUCT!{nodebug struct MODULEENTRY32 { + dwSize: ::DWORD, + th32ModuleID: ::DWORD, + th32ProcessID: ::DWORD, + GlblcntUsage: ::DWORD, + ProccntUsage: ::DWORD, + modBaseAddr: *mut ::BYTE, + modBaseSize: ::DWORD, + hModule: ::HMODULE, + szModule: [::CHAR; ::MAX_MODULE_NAME32 + 1], + szExePath: [::CHAR; ::MAX_PATH], +}} +pub type PMODULEENTRY32 = *mut MODULEENTRY32; +pub type LPMODULEENTRY32 = *mut MODULEENTRY32; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/unknwnbase.rs b/bash-5.1/vendor/winapi-0.2.8/src/unknwnbase.rs new file mode 100644 index 0000000..2112561 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/unknwnbase.rs @@ -0,0 +1,29 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! this ALWAYS GENERATED file contains the definitions for the interfaces +RIDL!( +interface IUnknown(IUnknownVtbl) { + fn QueryInterface(&mut self, riid: ::REFIID, ppvObject: *mut *mut ::c_void) -> ::HRESULT, + fn AddRef(&mut self) -> ::ULONG, + fn Release(&mut self) -> ::ULONG +} +); +pub type LPUNKNOWN = *mut IUnknown; +RIDL!( +interface AsyncIUnknown(AsyncIUnknownVtbl): IUnknown(IUnknownVtbl) { + fn Begin_QueryInterface(&mut self, riid: ::REFIID) -> ::HRESULT, + fn Finish_QueryInterface(&mut self, ppvObject: *mut *mut ::c_void) -> ::HRESULT, + fn Begin_AddRef(&mut self) -> ::HRESULT, + fn Finish_AddRef(&mut self) -> ::ULONG, + fn Begin_Release(&mut self) -> ::HRESULT, + fn Finish_Release(&mut self) -> ::ULONG +} +); +RIDL!( +interface IClassFactory(IClassFactoryVtbl): IUnknown(IUnknownVtbl) { + fn CreateInstance( + &mut self, pUnkOuter: *mut IUnknown, riid: ::REFIID, ppvObject: *mut *mut ::c_void + ) -> ::HRESULT, + fn LockServer(&mut self, fLock: ::BOOL) -> ::HRESULT +} +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/urlhist.rs b/bash-5.1/vendor/winapi-0.2.8/src/urlhist.rs new file mode 100644 index 0000000..b6fc2db --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/urlhist.rs @@ -0,0 +1,56 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Url History Interfaces +pub const STATURL_QUERYFLAG_ISCACHED: ::DWORD = 0x00010000; +pub const STATURL_QUERYFLAG_NOURL: ::DWORD = 0x00020000; +pub const STATURL_QUERYFLAG_NOTITLE: ::DWORD = 0x00040000; +pub const STATURL_QUERYFLAG_TOPLEVEL: ::DWORD = 0x00080000; +pub const STATURLFLAG_ISCACHED: ::DWORD = 0x00000001; +pub const STATURLFLAG_ISTOPLEVEL: ::DWORD = 0x00000002; +ENUM!{enum ADDURL_FLAG { + ADDURL_FIRST = 0, + ADDURL_ADDTOHISTORYANDCACHE = 0, + ADDURL_ADDTOCACHE = 1, + ADDURL_Max = 2147483647, +}} +pub type LPENUMSTATURL = *mut IEnumSTATURL; +STRUCT!{struct STATURL { + cbSize: ::DWORD, + pwcsUrl: ::LPWSTR, + pwcsTitle: ::LPWSTR, + ftLastVisited: ::FILETIME, + ftLastUpdated: ::FILETIME, + ftExpires: ::FILETIME, + dwFlags: ::DWORD, +}} +pub type LPSTATURL = *mut STATURL; +RIDL!{interface IEnumSTATURL(IEnumSTATURLVtbl): IUnknown(IUnknownVtbl) { + fn Next(&mut self, celt: ::ULONG, rgelt: LPSTATURL, pceltFetched: *mut ::ULONG) -> ::HRESULT, + fn Skip(&mut self, celt: ::ULONG) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn Clone(&mut self, ppenum: *mut *mut ::IEnumSTATURL) -> ::HRESULT, + fn SetFilter(&mut self, poszFilter: ::LPCOLESTR, dwFlags: ::DWORD) -> ::HRESULT +}} +pub type LPURLHISTORYSTG = *mut IUrlHistoryStg; +RIDL!{interface IUrlHistoryStg(IUrlHistoryStgVtbl): IUnknown(IUnknownVtbl) { + fn AddUrl(&mut self, pocsUrl: ::LPCOLESTR) -> ::HRESULT, + fn DeleteUrl(&mut self, pocsUrl: ::LPCOLESTR, dwFlags: ::DWORD) -> ::HRESULT, + fn QueryUrl( + &mut self, pocsUrl: ::LPCOLESTR, dwFlags: ::DWORD, lpSTATURL: LPSTATURL + ) -> ::HRESULT, + fn BindToObject( + &mut self, pocsUrl: ::LPCOLESTR, riid: ::REFIID, ppvOut: *mut *mut ::c_void + ) -> ::HRESULT, + fn EnumUrls(&mut self, ppEnum: *mut *mut ::IEnumSTATURL) -> ::HRESULT +}} +pub type LPURLHISTORYSTG2 = *mut IUrlHistoryStg2; +RIDL!{interface IUrlHistoryStg2(IUrlHistoryStg2Vtbl): IUrlHistoryStg(IUrlHistoryStgVtbl) { + fn AddUrlAndNotify( + &mut self, pocsUrl: ::LPCOLESTR, pocsTitle: ::LPCOLESTR, dwFlags: ::DWORD, + fWriteHistory: ::BOOL, poctNotify: *mut ::IOleCommandTarget, punkISFolder: *mut ::IUnknown + ) -> ::HRESULT, + fn ClearHistory(&mut self) -> ::HRESULT +}} +pub type LPURLHISTORYNOTIFY = *mut IUrlHistoryNotify; +RIDL!{interface IUrlHistoryNotify(IUrlHistoryNotifyVtbl): + IOleCommandTarget(IOleCommandTargetVtbl) {}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/urlmon.rs b/bash-5.1/vendor/winapi-0.2.8/src/urlmon.rs new file mode 100644 index 0000000..e0a5e93 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/urlmon.rs @@ -0,0 +1,6 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of Urlmon.h +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInternetSecurityManager; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/usb.rs b/bash-5.1/vendor/winapi-0.2.8/src/usb.rs new file mode 100644 index 0000000..5a5904e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/usb.rs @@ -0,0 +1,18 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License <LICENSE.md> +//! USB Definitions. +ENUM!{enum USBD_PIPE_TYPE { + UsbdPipeTypeControl, + UsbdPipeTypeIsochronous, + UsbdPipeTypeBulk, + UsbdPipeTypeInterrupt, +}} + +pub type USBD_STATUS = ::LONG; + +STRUCT!{struct USBD_ISO_PACKET_DESCRIPTOR { + Offset: ::ULONG, + Length: ::ULONG, + Status: ::USBD_STATUS, +}} +pub type PUSBD_ISO_PACKET_DESCRIPTOR = *mut USBD_ISO_PACKET_DESCRIPTOR; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/usbspec.rs b/bash-5.1/vendor/winapi-0.2.8/src/usbspec.rs new file mode 100644 index 0000000..6b9605b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/usbspec.rs @@ -0,0 +1,41 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License <LICENSE.md> +//! USB Spec Definitions. +ENUM!{enum USB_DEVICE_SPEED { + UsbLowSpeed = 0, + UsbFullSpeed, + UsbHighSpeed, + UsbSuperSpeed, +}} +ENUM!{enum USB_DEVICE_TYPE { + Usb11Device = 0, + Usb20Device, +}} +STRUCT!{struct BM_REQUEST_TYPE { + _BM: ::UCHAR, + B: ::UCHAR, +}} +BITFIELD!{BM_REQUEST_TYPE _BM: ::UINT8 [ + Recipient set_Recipient[0..2], + Reserved set_Reserved[2..5], + Type set_Type[5..7], + Dir set_Dir[7..8], +]} +pub type PBM_REQUEST_TYPE = *mut BM_REQUEST_TYPE; + +STRUCT!{#[repr(packed)] struct USB_CONFIGURATION_DESCRIPTOR { + bLength: ::UCHAR, + bDescriptorType: ::UCHAR, + wTotalLength: ::USHORT, + bNumInterfaces: ::UCHAR, + bConfigurationValue: ::UCHAR, + iConfiguration: ::UCHAR, + bmAttributes: ::UCHAR, + MaxPower: ::UCHAR, +}} +pub type PUSB_CONFIGURATION_DESCRIPTOR = *mut USB_CONFIGURATION_DESCRIPTOR; +#[test] +fn test_USB_CONFIGURATION_DESCRIPTOR_size() { + use std::mem::size_of; + assert_eq!(size_of::<USB_CONFIGURATION_DESCRIPTOR>(), 9) +} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/usp10.rs b/bash-5.1/vendor/winapi-0.2.8/src/usp10.rs new file mode 100644 index 0000000..6c7b42b --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/usp10.rs @@ -0,0 +1,201 @@ +// Copyright © 2015, Jordan Miner +// Licensed under the MIT License <LICENSE.md> +//! Uniscribe structure declarations and constant definitions +pub const SCRIPT_UNDEFINED: ::WORD = 0; +pub const USP_E_SCRIPT_NOT_IN_FONT: ::HRESULT = MAKE_HRESULT!( + ::SEVERITY_ERROR, ::FACILITY_ITF, 0x200 +); +DECLARE_HANDLE!(SCRIPT_CACHE, SCRIPT_CACHE__); +STRUCT!{struct SCRIPT_CONTROL { + bit_fields: ::DWORD, +}} +BITFIELD!(SCRIPT_CONTROL bit_fields: ::DWORD [ + uDefaultLanguage set_uDefaultLanguage[0..16], + fContextDigits set_fContextDigits[16..17], + fInvertPreBoundDir set_fInvertPreBoundDir[17..18], + fInvertPostBoundDir set_fInvertPostBoundDir[18..19], + fLinkStringBefore set_fLinkStringBefore[19..20], + fLinkStringAfter set_fLinkStringAfter[20..21], + fNeutralOverride set_fNeutralOverride[21..22], + fNumericOverride set_fNumericOverride[22..23], + fLegacyBidiClass set_fLegacyBidiClass[23..24], + fMergeNeutralItems set_fMergeNeutralItems[24..25], + fReserved set_fReserved[25..32], +]); +STRUCT!{struct SCRIPT_STATE { + bit_fields: ::WORD, +}} +BITFIELD!(SCRIPT_STATE bit_fields: ::WORD [ + uBidiLevel set_uBidiLevel[0..5], + fOverrideDirection set_fOverrideDirection[5..6], + fInhibitSymSwap set_fInhibitSymSwap[6..7], + fCharShape set_fCharShape[7..8], + fDigitSubstitute set_fDigitSubstitute[8..9], + fInhibitLigate set_fInhibitLigate[9..10], + fDisplayZWG set_fDisplayZWG[10..11], + fArabicNumContext set_fArabicNumContext[11..12], + fGcpClusters set_fGcpClusters[12..13], + fReserved set_fReserved[13..14], + fEngineReserved set_fEngineReserved[14..16], +]); +STRUCT!{struct SCRIPT_ANALYSIS { + bit_fields: ::WORD, + s: SCRIPT_STATE, +}} +BITFIELD!(SCRIPT_ANALYSIS bit_fields: ::WORD [ + eScript set_eScript[0..10], + fRTL set_fRTL[10..11], + fLayoutRTL set_fLayoutRTL[11..12], + fLinkBefore set_fLinkBefore[12..13], + fLinkAfter set_fLinkAfter[13..14], + fLogicalOrder set_fLogicalOrder[14..15], + fNoGlyphIndex set_fNoGlyphIndex[15..16], +]); +STRUCT!{struct SCRIPT_ITEM { + iCharPos: ::c_int, + a: SCRIPT_ANALYSIS, +}} +//490 +pub const SCRIPT_JUSTIFY_NONE: ::WORD = 0; +pub const SCRIPT_JUSTIFY_ARABIC_BLANK: ::WORD = 1; +pub const SCRIPT_JUSTIFY_CHARACTER: ::WORD = 2; +pub const SCRIPT_JUSTIFY_RESERVED1: ::WORD = 3; +pub const SCRIPT_JUSTIFY_BLANK: ::WORD = 4; +pub const SCRIPT_JUSTIFY_RESERVED2: ::WORD = 5; +pub const SCRIPT_JUSTIFY_RESERVED3: ::WORD = 6; +pub const SCRIPT_JUSTIFY_ARABIC_NORMAL: ::WORD = 7; +pub const SCRIPT_JUSTIFY_ARABIC_KASHIDA: ::WORD = 8; +pub const SCRIPT_JUSTIFY_ARABIC_ALEF: ::WORD = 9; +pub const SCRIPT_JUSTIFY_ARABIC_HA: ::WORD = 10; +pub const SCRIPT_JUSTIFY_ARABIC_RA: ::WORD = 11; +pub const SCRIPT_JUSTIFY_ARABIC_BA: ::WORD = 12; +pub const SCRIPT_JUSTIFY_ARABIC_BARA: ::WORD = 13; +pub const SCRIPT_JUSTIFY_ARABIC_SEEN: ::WORD = 14; +pub const SCRIPT_JUSTIFY_ARABIC_SEEN_M: ::WORD = 15; +STRUCT!{struct SCRIPT_VISATTR { + bit_fields: ::WORD, +}} +BITFIELD!(SCRIPT_VISATTR bit_fields: ::WORD [ + uJustification set_uJustification[0..4], + fClusterStart set_fClusterStart[4..5], + fDiacritic set_fDiacritic[5..6], + fZeroWidth set_fZeroWidth[6..7], + fReserved set_fReserved[7..8], + fShapeReserved set_fShapeReserved[8..16], +]); +STRUCT!{struct GOFFSET { + du: ::LONG, + dv: ::LONG, +}} +STRUCT!{struct SCRIPT_LOGATTR { + bit_fields: ::BYTE, +}} +BITFIELD!(SCRIPT_LOGATTR bit_fields: ::BYTE [ + fSoftBreak set_fSoftBreak[0..1], + fWhiteSpace set_fWhiteSpace[1..2], + fCharStop set_fCharStop[2..3], + fWordStop set_fWordStop[3..4], + fInvalid set_fInvalid[4..5], + fReserved set_fReserved[5..8], +]); +pub const SGCM_RTL: ::DWORD = 0x00000001; +STRUCT!{struct SCRIPT_PROPERTIES { + bit_fields1: ::DWORD, + bit_fields2: ::DWORD, +}} +BITFIELD!(SCRIPT_PROPERTIES bit_fields1: ::DWORD [ + langid set_langid[0..16], + fNumeric set_fNumeric[16..17], + fComplex set_fComplex[17..18], + fNeedsWordBreaking set_fNeedsWordBreaking[18..19], + fNeedsCaretInfo set_fNeedsCaretInfo[19..20], + bCharSet set_bCharSet[20..28], + fControl set_fControl[28..29], + fPrivateUseArea set_fPrivateUseArea[29..30], + fNeedsCharacterJustify set_fNeedsCharacterJustify[30..31], + fInvalidGlyph set_fInvalidGlyph[31..32], +]); +BITFIELD!(SCRIPT_PROPERTIES bit_fields2: ::DWORD [ + fInvalidLogAttr set_fInvalidLogAttr[0..1], + fCDM set_fCDM[1..2], + fAmbiguousCharSet set_fAmbiguousCharSet[2..3], + fClusterSizeVaries set_fClusterSizeVaries[3..4], + fRejectInvalid set_fRejectInvalid[4..5], +]); +STRUCT!{struct SCRIPT_FONTPROPERTIES { + cBytes: ::c_int, + wgBlank: ::WORD, + wgDefault: ::WORD, + wgInvalid: ::WORD, + wgKashida: ::WORD, + iKashidaWidth: ::c_int, +}} +//1440 +pub const SSA_PASSWORD: ::DWORD = 0x00000001; +pub const SSA_TAB: ::DWORD = 0x00000002; +pub const SSA_CLIP: ::DWORD = 0x00000004; +pub const SSA_FIT: ::DWORD = 0x00000008; +pub const SSA_DZWG: ::DWORD = 0x00000010; +pub const SSA_FALLBACK: ::DWORD = 0x00000020; +pub const SSA_BREAK: ::DWORD = 0x00000040; +pub const SSA_GLYPHS: ::DWORD = 0x00000080; +pub const SSA_RTL: ::DWORD = 0x00000100; +pub const SSA_GCP: ::DWORD = 0x00000200; +pub const SSA_HOTKEY: ::DWORD = 0x00000400; +pub const SSA_METAFILE: ::DWORD = 0x00000800; +pub const SSA_LINK: ::DWORD = 0x00001000; +pub const SSA_HIDEHOTKEY: ::DWORD = 0x00002000; +pub const SSA_HOTKEYONLY: ::DWORD = 0x00002400; +pub const SSA_FULLMEASURE: ::DWORD = 0x04000000; +pub const SSA_LPKANSIFALLBACK: ::DWORD = 0x08000000; +pub const SSA_PIDX: ::DWORD = 0x10000000; +pub const SSA_LAYOUTRTL: ::DWORD = 0x20000000; +pub const SSA_DONTGLYPH: ::DWORD = 0x40000000; +pub const SSA_NOKASHIDA: ::DWORD = 0x80000000; +STRUCT!{struct SCRIPT_TABDEF { + cTabStops: ::c_int, + iScale: ::c_int, + pTabStops: *mut ::c_int, + iTabOrigin: ::c_int, +}} +DECLARE_HANDLE!(SCRIPT_STRING_ANALYSIS, SCRIPT_STRING_ANALYSIS__); +pub const SIC_COMPLEX: ::DWORD = 1; +pub const SIC_ASCIIDIGIT: ::DWORD = 2; +pub const SIC_NEUTRAL: ::DWORD = 4; +STRUCT!{struct SCRIPT_DIGITSUBSTITUTE { + bit_fields1: ::DWORD, + bit_fields2: ::DWORD, + dwReserved: ::DWORD, +}} +BITFIELD!(SCRIPT_DIGITSUBSTITUTE bit_fields1: ::DWORD [ + NationalDigitLanguage set_NationalDigitLanguage[0..16], + TraditionalDigitLanguage set_TraditionalDigitLanguage[16..32], +]); +BITFIELD!(SCRIPT_DIGITSUBSTITUTE bit_fields2: ::DWORD [ + DigitSubstitute set_DigitSubstitute[0..8], +]); +pub const SCRIPT_DIGITSUBSTITUTE_CONTEXT: ::BYTE = 0; +pub const SCRIPT_DIGITSUBSTITUTE_NONE: ::BYTE = 1; +pub const SCRIPT_DIGITSUBSTITUTE_NATIONAL: ::BYTE = 2; +pub const SCRIPT_DIGITSUBSTITUTE_TRADITIONAL: ::BYTE = 3; +pub type OPENTYPE_TAG = ::ULONG; +pub const SCRIPT_TAG_UNKNOWN: OPENTYPE_TAG = 0x00000000; +STRUCT!{struct OPENTYPE_FEATURE_RECORD { + tagFeature: OPENTYPE_TAG, + lParameter: ::LONG, +}} +STRUCT!{struct TEXTRANGE_PROPERTIES { + potfRecords: *mut OPENTYPE_FEATURE_RECORD, + cotfRecords: ::c_int, +}} +STRUCT!{struct SCRIPT_CHARPROP { + bit_fields: ::WORD, +}} +BITFIELD!(SCRIPT_CHARPROP bit_fields: ::WORD [ + fCanGlyphAlone set_fCanGlyphAlone[0..1], + reserved set_reserved[1..16], +]); +STRUCT!{struct SCRIPT_GLYPHPROP { + sva: SCRIPT_VISATTR, + reserved: ::WORD, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/vadefs.rs b/bash-5.1/vendor/winapi-0.2.8/src/vadefs.rs new file mode 100644 index 0000000..c482026 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/vadefs.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Definitions of macro helpers used by <stdarg.h>. This is the topmost header in the CRT header +//! lattice, and is always the first CRT header to be included, explicitly or implicitly. +//! Therefore, this header also has several definitions that are used throughout the CRT. +//39 +pub type va_list = *mut ::c_char; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/vsbackup.rs b/bash-5.1/vendor/winapi-0.2.8/src/vsbackup.rs new file mode 100644 index 0000000..5f6036a --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/vsbackup.rs @@ -0,0 +1,303 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License <LICENSE.md> +//! VSS backup interfaces +DEFINE_GUID!(IID_IVssExamineWriterMetadata, 0x902fcf7f, 0xb7fd, 0x42f8, + 0x81, 0xf1, 0xb2, 0xe4, 0x00, 0xb1, 0xe5, 0xbd); +DEFINE_GUID!(IID_IVssExamineWriterMetadataEx, 0x0c0e5ec0, 0xca44, 0x472b, + 0xb7, 0x02, 0xe6, 0x52, 0xdb, 0x1c, 0x04, 0x51); +DEFINE_GUID!(IID_IVssBackupComponents, 0x665c1d5f, 0xc218, 0x414d, + 0xa0, 0x5d, 0x7f, 0xef, 0x5f, 0x9d, 0x5c, 0x86); +DEFINE_GUID!(IID_IVssBackupComponentsEx, 0x963f03ad, 0x9e4c, 0x4a34, + 0xac, 0x15, 0xe4, 0xb6, 0x17, 0x4e, 0x50, 0x36); +STRUCT!{struct VSS_COMPONENTINFO { + type_: ::VSS_COMPONENT_TYPE, // type is a keyword in rust + bstrLogicalPath: ::BSTR, + bstrComponentName: ::BSTR, + bstrCaption: ::BSTR, + pbIcon: *mut ::BYTE, + cbIcon: ::UINT, + bRestoreMetadata: bool, + bNotifyOnBackupComplete: bool, + bSelectable: bool, + bSelectableForRestore: bool, + dwComponentFlags: ::DWORD, + cFileCount: ::UINT, + cDatabases: ::UINT, + cLogFiles: ::UINT, + cDependencies: ::UINT, +}} +pub type PVSSCOMPONENTINFO = *const ::VSS_COMPONENTINFO; +RIDL!( +interface IVssWMComponent(IVssWMComponentVtbl): IUnknown(IUnknownVtbl) { + fn GetComponentInfo(&mut self, ppInfo: *mut ::PVSSCOMPONENTINFO) -> ::HRESULT, + fn FreeComponentInfo(&mut self, pInfo: ::PVSSCOMPONENTINFO) -> ::HRESULT, + fn GetFile(&mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc) -> ::HRESULT, + fn GetDatabaseFile( + &mut self, iDBFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetDatabaseLogFile( + &mut self, iDbLogFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetDependency( + &mut self, iDependency: ::UINT, ppDependency: *mut *mut ::IVssWMDependency + ) -> ::HRESULT +} +); +RIDL!( +interface IVssExamineWriterMetadata(IVssExamineWriterMetadataVtbl): IUnknown(IUnknownVtbl) { + fn GetIdentity( + &mut self, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriterName: *mut ::BSTR, pUsage: *mut ::VSS_USAGE_TYPE, + pSource: *mut ::VSS_SOURCE_TYPE + ) -> ::HRESULT, + fn GetFileCounts(&mut self, pcIncludeFiles: *mut ::UINT, pcExcludeFiles: *mut ::UINT, + pcComponents: *mut ::UINT + ) -> ::HRESULT, + fn GetIncludeFile( + &mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetExcludeFile( + &mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetComponent( + &mut self, iComponent: ::UINT, ppComponent: *mut *mut ::IVssWMComponent + ) -> ::HRESULT, + fn GetRestoreMethod( + &mut self, pMethod: *mut ::VSS_RESTOREMETHOD_ENUM, pbstrService: *mut ::BSTR, + pbstrUserProcedure: *mut ::BSTR, pwriterRestore: *mut ::VSS_WRITERRESTORE_ENUM, + pbRebootRequired: *mut bool, pcMappings: *mut ::UINT + ) -> ::HRESULT, + fn GetAlternateLocationMapping( + &mut self, iMapping: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetBackupSchema(&mut self, pdwSchemaMask: *mut ::DWORD) -> ::HRESULT, + fn GetDocument(&mut self, pDoc: *mut ::c_void) -> ::HRESULT, //TODO IXMLDOMDocument + fn SaveAsXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT, + fn LoadFromXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface IVssExamineWriterMetadataEx(IVssExamineWriterMetadataExVtbl): + IVssExamineWriterMetadata(IVssExamineWriterMetadataVtbl) { + fn GetIdentityEx( + &mut self, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriterName: *mut ::BSTR, pbstrInstanceName: *mut ::BSTR, + pUsage: *mut ::VSS_USAGE_TYPE, pSource: *mut ::VSS_SOURCE_TYPE + ) -> ::HRESULT +} +); +RIDL!( +interface IVssExamineWriterMetadataEx2(IVssExamineWriterMetadataEx2Vtbl): + IVssExamineWriterMetadataEx(IVssExamineWriterMetadataExVtbl) { + fn GetVersion( + &mut self, pdwMajorVersion: *mut ::DWORD, pdwMinorVersion: *mut ::DWORD + ) -> ::HRESULT, + fn GetExcludeFromSnapshotCount(&mut self, pcExcludedFromSnapshot: *mut ::UINT) -> ::HRESULT, + fn GetExcludeFromSnapshotFile( + &mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT +} +); +#[repr(C)] +pub struct IVssWriterComponentsExt { + pub lpVtbl: *const IVssWriterComponentsExtVtbl, +} +#[repr(C)] +pub struct IVssWriterComponentsExtVtbl { + pub parent1: ::IVssWriterComponentsVtbl, + pub parent2: ::IUnknownVtbl, +} +RIDL!( +interface IVssBackupComponents(IVssBackupComponentsVtbl): IUnknown(IUnknownVtbl) { + fn GetWriterComponentsCount(&mut self, pcComponents: *mut ::UINT) -> ::HRESULT, + fn GetWriterComponents( + &mut self, iWriter: ::UINT, ppWriter: *mut *mut IVssWriterComponentsExt + ) -> ::HRESULT, + fn InitializeForBackup(&mut self, bstrXML: ::BSTR) -> ::HRESULT, + fn SetBackupState( + &mut self, bSelectComponents: bool, bBackupBootableSystemState: bool, + backupType: ::VSS_BACKUP_TYPE, bPartialFileSupport: bool + ) -> ::HRESULT, + fn InitializeForRestore(&mut self, bstrXML: ::BSTR) -> ::HRESULT, + fn SetRestoreState(&mut self, restoreType: ::VSS_RESTORE_TYPE) -> ::HRESULT, + fn GatherWriterMetadata(&mut self, pAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn GetWriterMetadataCount(&mut self, pcWriters: *mut ::UINT) -> ::HRESULT, + fn GetWriterMetadata( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, + ppMetadata: *mut *mut IVssExamineWriterMetadata + ) -> ::HRESULT, + fn FreeWriterMetadata(&mut self) -> ::HRESULT, + fn AddComponent( + &mut self, instanceId: ::VSS_ID, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, + wszLogicalPath: ::LPCWSTR, wszComponentName: ::LPCWSTR + ) -> ::HRESULT, + fn PrepareForBackup(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn AbortBackup(&mut self) -> ::HRESULT, + fn GatherWriterStatus(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn GetWriterStatusCount(&mut self, pcWriters: *mut ::UINT) -> ::HRESULT, + fn FreeWriterStatus(&mut self) -> ::HRESULT, + fn GetWriterStatus( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriter: *mut ::BSTR, pnStatus: *mut ::VSS_WRITER_STATE, + phResultFailure: *mut ::HRESULT + ) -> ::HRESULT, + fn SetBackupSucceeded( + &mut self, instanceId: ::VSS_ID, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, + wszLogicalPath: ::LPCWSTR, wszComponentName: ::LPCWSTR, bSucceded: bool + ) -> ::HRESULT, + fn SetBackupOptions( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszBackupOptions: ::LPCWSTR + ) -> ::HRESULT, + fn SetSelectedForRestore( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bSelectedForRestore: bool + ) -> ::HRESULT, + fn SetRestoreOptions( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszRestoreOptions: ::LPCWSTR + ) -> ::HRESULT, + fn SetAdditionalRestores( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bAdditionalRestores: bool + ) -> ::HRESULT, + fn SetPreviousBackupStamp( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszPreviousBackupStamp: ::LPCWSTR + ) -> ::HRESULT, + fn SaveAsXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT, + fn BackupComplete(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn AddAlternativeLocationMapping( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool, + wszDestination: ::LPCWSTR + ) -> ::HRESULT, + fn AddRestoreSubcomponent( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszSubComponentLogicalPath: ::LPCWSTR, + wszSubComponentName: ::LPCWSTR, bRepair: bool + ) -> ::HRESULT, + fn SetFileRestoreStatus( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, status: ::VSS_FILE_RESTORE_STATUS + ) -> ::HRESULT, + fn AddNewTarget( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszPath: ::LPCWSTR, wszFileName: ::LPCWSTR, bRecursive: bool, + wszAlternatePath: ::LPCWSTR + ) -> ::HRESULT, + fn SetRangesFilePath( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, iPartialFile: ::UINT, wszRangesFile: ::LPCWSTR + ) -> ::HRESULT, + fn PreRestore(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn PostRestore(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn SetContext(&mut self, lContext: ::LONG) -> ::HRESULT, + fn StartSnapshotSet(&mut self, pSnapshotSetId: *mut ::VSS_ID) -> ::HRESULT, + fn AddToSnapshotSet( + &mut self, pwszVolumeName: ::VSS_PWSZ, ProviderId: ::VSS_ID, pidSnapshot: *mut ::VSS_ID + ) -> ::HRESULT, + fn DoSnapshotSet(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn DeleteSnapshots( + &mut self, SourceObjectId: ::VSS_ID, eSourceObjectType: ::VSS_OBJECT_TYPE, + bForceDelete: ::BOOL, plDeletedSnapshots: *mut ::LONG, pNondeletedSnapshotID: *mut ::VSS_ID + ) -> ::HRESULT, + fn ImportSnapshots(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn BreakSnapshotSet(&mut self, SnapshotSetId: ::VSS_ID) -> ::HRESULT, + fn GetSnapshotProperties( + &mut self, SnapshotId: ::VSS_ID, + pProp: *mut ::VSS_SNAPSHOT_PROP + ) -> ::HRESULT, + fn Query(&mut self, QueriedObjectId: ::VSS_ID, eQueriedObjectType: ::VSS_OBJECT_TYPE, + eReturnedObjectsType: ::VSS_OBJECT_TYPE, ppEnum: *mut *mut ::IVssEnumObject) -> ::HRESULT, + fn IsVolumeSupported( + &mut self, ProviderId: ::VSS_ID, pwszVolumeName: ::VSS_PWSZ, + pbSupportedByThisProvider: *mut ::BOOL + ) -> ::HRESULT, + fn DisableWriterClasses( + &mut self, rgWriterClassId: *const ::VSS_ID, cClassId: ::UINT + ) -> ::HRESULT, + fn EnableWriterClasses( + &mut self, rgWriterClassId: *const ::VSS_ID, cClassId: ::UINT + ) -> ::HRESULT, + fn DisableWriterInstances( + &mut self, rgWriterInstanceId: *const ::VSS_ID, cInstanceId: ::UINT + ) -> ::HRESULT, + fn ExposeSnapshot(&mut self, SnapshotId: ::VSS_ID, wszPathFromRoot: ::VSS_PWSZ, + lAttributes: ::LONG, wszExpose: ::VSS_PWSZ, pwszExposed: ::VSS_PWSZ + ) -> ::HRESULT, + fn RevertToSnapshot(&mut self, SnapshotId: ::VSS_ID, bForceDismount: ::BOOL) -> ::HRESULT, + fn QueryRevertStatus( + &mut self, pwszVolume: ::VSS_PWSZ, ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx(IVssBackupComponentsExVtbl): + IVssBackupComponents(IVssBackupComponentsVtbl) { + fn GetWriterMetadataEx( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, + ppMetadata: *mut *mut ::IVssExamineWriterMetadataEx + ) -> ::HRESULT, + fn SetSelectedForRestoreEx( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bSelectedForRestore: bool, instanceId: ::VSS_ID + ) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx2(IVssBackupComponentsEx2Vtbl): + IVssBackupComponentsEx(IVssBackupComponentsExVtbl) { + fn UnexposeSnapshot(&mut self, snapshotId: ::VSS_ID) -> ::HRESULT, + fn SetAuthoritativeRestore( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bAuth: bool + ) -> ::HRESULT, + fn SetRollForward( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, rollType: ::VSS_ROLLFORWARD_TYPE, + wszRollForwardPoint: ::LPCWSTR + ) -> ::HRESULT, + fn SetRestoreName( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszRestoreName: ::LPCWSTR + ) -> ::HRESULT, + fn BreakSnapshotSetEx( + &mut self, SnapshotSetID: ::VSS_ID, dwBreakFlags: ::DWORD, ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT, + fn PreFastRecovery( + &mut self, SnapshotSetID: ::VSS_ID, dwPreFastRecoveryFlags: ::DWORD, + ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT, + fn FastRecovery( + &mut self, SnapshotSetID: ::VSS_ID, dwFastRecoveryFlags: ::DWORD, + ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx3(IVssBackupComponentsEx3Vtbl): + IVssBackupComponentsEx2(IVssBackupComponentsEx2Vtbl) { + fn GetWriterStatusEx( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriter: *mut ::BSTR, pnStatus: *mut ::VSS_WRITER_STATE, + phrFailureWriter: *mut ::HRESULT, phrApplication: *mut ::HRESULT, + pbstrApplicationMessage: *mut ::BSTR + ) -> ::HRESULT, + fn AddSnapshotToRecoverySet( + &mut self, snapshotId: ::VSS_ID, dwFlags: ::DWORD, pwszDestinationVolume: ::VSS_PWSZ + ) -> ::HRESULT, + fn RecoverSet(&mut self, dwFlags: ::DWORD, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn GetSessionId(&mut self, idSession: *mut ::VSS_ID) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx4(IVssBackupComponentsEx4Vtbl): + IVssBackupComponentsEx3(IVssBackupComponentsEx3Vtbl) { + fn GetRootAndLogicalPrefixPaths( + &mut self, pwszFilePath: ::VSS_PWSZ, ppwszRootPath: *mut ::VSS_PWSZ, + ppwszLogicalPrefix: *mut ::VSS_PWSZ, bNormalizeFQDNforRootPath: ::BOOL + ) -> ::HRESULT +} +); +pub const VSS_SW_BOOTABLE_STATE: ::DWORD = 1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/vss.rs b/bash-5.1/vendor/winapi-0.2.8/src/vss.rs new file mode 100644 index 0000000..259f181 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/vss.rs @@ -0,0 +1,256 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License <LICENSE.md> +//! VSS header file +ENUM!{enum VSS_OBJECT_TYPE { + VSS_OBJECT_UNKNOWN = 0, + VSS_OBJECT_NONE = 1, + VSS_OBJECT_SNAPSHOT_SET = 2, + VSS_OBJECT_SNAPSHOT = 3, + VSS_OBJECT_PROVIDER = 4, + VSS_OBJECT_TYPE_COUNT = 5, +}} +pub type PVSS_OBJECT_TYPE = *mut VSS_OBJECT_TYPE; +ENUM!{enum VSS_SNAPSHOT_STATE { + VSS_SS_UNKNOWN = 0x00, + VSS_SS_PREPARING = 0x01, + VSS_SS_PROCESSING_PREPARE = 0x02, + VSS_SS_PREPARED = 0x03, + VSS_SS_PROCESSING_PRECOMMIT = 0x04, + VSS_SS_PRECOMMITTED = 0x05, + VSS_SS_PROCESSING_COMMIT = 0x06, + VSS_SS_COMMITTED = 0x07, + VSS_SS_PROCESSING_POSTCOMMIT = 0x08, + VSS_SS_PROCESSING_PREFINALCOMMIT = 0x09, + VSS_SS_PREFINALCOMMITTED = 0x0a, + VSS_SS_PROCESSING_POSTFINALCOMMIT = 0x0b, + VSS_SS_CREATED = 0x0c, + VSS_SS_ABORTED = 0x0d, + VSS_SS_DELETED = 0x0e, + VSS_SS_POSTCOMMITTED = 0x0f, + VSS_SS_COUNT = 0x10, +}} +pub type PVSS_SNAPSHOT_STATE = *mut VSS_SNAPSHOT_STATE; +pub type VSS_VOLUME_SNAPSHOT_ATTRIBUTES = ::LONG; +pub const VSS_VOLSNAP_ATTR_PERSISTENT: ::LONG = 0x00000001; +pub const VSS_VOLSNAP_ATTR_NO_AUTORECOVERY: ::LONG = 0x00000002; +pub const VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE: ::LONG = 0x00000004; +pub const VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE: ::LONG = 0x00000008; +pub const VSS_VOLSNAP_ATTR_NO_WRITERS: ::LONG = 0x00000010; +pub const VSS_VOLSNAP_ATTR_TRANSPORTABLE: ::LONG = 0x00000020; +pub const VSS_VOLSNAP_ATTR_NOT_SURFACED: ::LONG = 0x00000040; +pub const VSS_VOLSNAP_ATTR_NOT_TRANSACTED: ::LONG = 0x00000080; +pub const VSS_VOLSNAP_ATTR_HARDWARE_ASSISTED: ::LONG = 0x00010000; +pub const VSS_VOLSNAP_ATTR_DIFFERENTIAL: ::LONG = 0x00020000; +pub const VSS_VOLSNAP_ATTR_PLEX: ::LONG = 0x00040000; +pub const VSS_VOLSNAP_ATTR_IMPORTED: ::LONG = 0x00080000; +pub const VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY: ::LONG = 0x00100000; +pub const VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY: ::LONG = 0x00200000; +pub const VSS_VOLSNAP_ATTR_AUTORECOVER: ::LONG = 0x00400000; +pub const VSS_VOLSNAP_ATTR_ROLLBACK_RECOVERY: ::LONG = 0x00800000; +pub const VSS_VOLSNAP_ATTR_DELAYED_POSTSNAPSHOT: ::LONG = 0x01000000; +pub const VSS_VOLSNAP_ATTR_TXF_RECOVERY: ::LONG = 0x02000000; +pub const VSS_VOLSNAP_ATTR_FILE_SHARE: ::LONG = 0x04000000; +pub type PVSS_VOLUME_SNAPSHOT_ATTRIBUTES = *mut VSS_VOLUME_SNAPSHOT_ATTRIBUTES; +pub type VSS_SNAPSHOT_CONTEXT = ::LONG; +pub type PVSS_SNAPSHOT_CONTEXT = *mut VSS_SNAPSHOT_CONTEXT; +pub const VSS_CTX_BACKUP: ::LONG = 0; +pub const VSS_CTX_FILE_SHARE_BACKUP: ::LONG = VSS_VOLSNAP_ATTR_NO_WRITERS; +pub const VSS_CTX_NAS_ROLLBACK: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE | VSS_VOLSNAP_ATTR_NO_WRITERS; +pub const VSS_CTX_APP_ROLLBACK: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE; +pub const VSS_CTX_CLIENT_ACCESSIBLE: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE + | VSS_VOLSNAP_ATTR_NO_WRITERS; +pub const VSS_CTX_CLIENT_ACCESSIBLE_WRITERS: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE; +pub const VSS_CTX_ALL: ::LONG = 0xffffffffu32 as ::LONG; +pub type VSS_PROVIDER_CAPABILITIES = ::DWORD; +pub type PVSS_PROVIDER_CAPABILITIES = *mut VSS_PROVIDER_CAPABILITIES; +pub const VSS_PRV_CAPABILITY_LEGACY: ::DWORD = 0x1; +pub const VSS_PRV_CAPABILITY_COMPLIANT: ::DWORD = 0x2; +pub const VSS_PRV_CAPABILITY_LUN_REPOINT: ::DWORD = 0x4; +pub const VSS_PRV_CAPABILITY_LUN_RESYNC: ::DWORD = 0x8; +pub const VSS_PRV_CAPABILITY_OFFLINE_CREATION: ::DWORD = 0x10; +pub const VSS_PRV_CAPABILITY_MULTIPLE_IMPORT: ::DWORD = 0x20; +pub const VSS_PRV_CAPABILITY_RECYCLING: ::DWORD = 0x40; +pub const VSS_PRV_CAPABILITY_PLEX: ::DWORD = 0x80; +pub const VSS_PRV_CAPABILITY_DIFFERENTIAL: ::DWORD = 0x100; +pub const VSS_PRV_CAPABILITY_CLUSTERED: ::DWORD = 0x200; +pub type VSS_HARDWARE_OPTIONS = ::DWORD; +pub type PVSS_HARDWARE_OPTIONS = *mut VSS_HARDWARE_OPTIONS; +pub const VSS_BREAKEX_FLAG_MASK_LUNS: ::DWORD = 0x1; +pub const VSS_BREAKEX_FLAG_MAKE_READ_WRITE: ::DWORD = 0x2; +pub const VSS_BREAKEX_FLAG_REVERT_IDENTITY_ALL: ::DWORD = 0x4; +pub const VSS_BREAKEX_FLAG_REVERT_IDENTITY_NONE: ::DWORD = 0x8; +pub const VSS_ONLUNSTATECHANGE_NOTIFY_READ_WRITE: ::DWORD = 0x100; +pub const VSS_ONLUNSTATECHANGE_NOTIFY_LUN_PRE_RECOVERY: ::DWORD = 0x200; +pub const VSS_ONLUNSTATECHANGE_NOTIFY_LUN_POST_RECOVERY: ::DWORD = 0x400; +pub const VSS_ONLUNSTATECHANGE_DO_MASK_LUNS: ::DWORD = 0x800; +pub type VSS_RECOVERY_OPTIONS = ::DWORD; +pub type PVSS_RECOVERY_OPTIONS = *mut VSS_RECOVERY_OPTIONS; +pub const VSS_RECOVERY_REVERT_IDENTITY_ALL: ::DWORD = 0x00000100; +pub const VSS_RECOVERY_NO_VOLUME_CHECK: ::DWORD = 0x00000200; +ENUM!{enum VSS_WRITER_STATE { + VSS_WS_UNKNOWN = 0, + VSS_WS_STABLE = 1, + VSS_WS_WAITING_FOR_FREEZE = 2, + VSS_WS_WAITING_FOR_THAW = 3, + VSS_WS_WAITING_FOR_POST_SNAPSHOT = 4, + VSS_WS_WAITING_FOR_BACKUP_COMPLETE = 5, + VSS_WS_FAILED_AT_IDENTIFY = 6, + VSS_WS_FAILED_AT_PREPARE_BACKUP = 7, + VSS_WS_FAILED_AT_PREPARE_SNAPSHOT = 8, + VSS_WS_FAILED_AT_FREEZE = 9, + VSS_WS_FAILED_AT_THAW = 10, + VSS_WS_FAILED_AT_POST_SNAPSHOT = 11, + VSS_WS_FAILED_AT_BACKUP_COMPLETE = 12, + VSS_WS_FAILED_AT_PRE_RESTORE = 13, + VSS_WS_FAILED_AT_POST_RESTORE = 14, + VSS_WS_FAILED_AT_BACKUPSHUTDOWN = 15, + VSS_WS_COUNT = 16, +}} +pub type PVSS_WRITER_STATE = *mut VSS_WRITER_STATE; +ENUM!{enum VSS_BACKUP_TYPE { + VSS_BT_UNDEFINED = 0, + VSS_BT_FULL = 1, + VSS_BT_INCREMENTAL = 2, + VSS_BT_DIFFERENTIAL = 3, + VSS_BT_LOG = 4, + VSS_BT_COPY = 5, + VSS_BT_OTHER = 6, +}} +pub type PVSS_BACKUP_TYPE = *mut VSS_BACKUP_TYPE; +ENUM!{enum VSS_RESTORE_TYPE { + VSS_RTYPE_UNDEFINED = 0, + VSS_RTYPE_BY_COPY = 1, + VSS_RTYPE_IMPORT = 2, + VSS_RTYPE_OTHER = 3, +}} +pub type PVSS_RESTORE_TYPE = *mut VSS_RESTORE_TYPE; +ENUM!{enum VSS_ROLLFORWARD_TYPE { + VSS_RF_UNDEFINED = 0, + VSS_RF_NONE = 1, + VSS_RF_ALL = 2, + VSS_RF_PARTIAL = 3, +}} +pub type PVSS_ROLLFORWARD_TYPE = *mut VSS_ROLLFORWARD_TYPE; +ENUM!{enum VSS_PROVIDER_TYPE { + VSS_PROV_UNKNOWN = 0, + VSS_PROV_SYSTEM = 1, + VSS_PROV_SOFTWARE = 2, + VSS_PROV_HARDWARE = 3, + VSS_PROV_FILESHARE = 4, +}} +pub type PVSS_PROVIDER_TYPE = *mut VSS_PROVIDER_TYPE; +ENUM!{enum VSS_APPLICATION_LEVEL { + VSS_APP_UNKNOWN = 0, + VSS_APP_SYSTEM = 1, + VSS_APP_BACK_END = 2, + VSS_APP_FRONT_END = 3, + VSS_APP_SYSTEM_RM = 4, + VSS_APP_AUTO = -1i32 as u32, +}} +pub type PVSS_APPLICATION_LEVEL = *mut VSS_APPLICATION_LEVEL; +ENUM!{enum VSS_SNAPSHOT_PROPERTY_ID { + VSS_SPROPID_UNKNOWN = 0, + VSS_SPROPID_SNAPSHOT_ID = 0x1, + VSS_SPROPID_SNAPSHOT_SET_ID = 0x2, + VSS_SPROPID_SNAPSHOTS_COUNT = 0x3, + VSS_SPROPID_SNAPSHOT_DEVICE = 0x4, + VSS_SPROPID_ORIGINAL_VOLUME = 0x5, + VSS_SPROPID_ORIGINATING_MACHINE = 0x6, + VSS_SPROPID_SERVICE_MACHINE = 0x7, + VSS_SPROPID_EXPOSED_NAME = 0x8, + VSS_SPROPID_EXPOSED_PATH = 0x9, + VSS_SPROPID_PROVIDER_ID = 0xa, + VSS_SPROPID_SNAPSHOT_ATTRIBUTES = 0xb, + VSS_SPROPID_CREATION_TIMESTAMP = 0xc, + VSS_SPROPID_STATUS = 0xd, +}} +pub type PVSS_SNAPSHOT_PROPERTY_ID = *mut VSS_SNAPSHOT_PROPERTY_ID; +pub type VSS_FILE_SPEC_BACKUP_TYPE = ::DWORD; +pub type PVSS_FILE_SPEC_BACKUP_TYPE = *mut VSS_FILE_SPEC_BACKUP_TYPE; +pub const VSS_FSBT_FULL_BACKUP_REQUIRED: ::DWORD = 0x1; +pub const VSS_FSBT_DIFFERENTIAL_BACKUP_REQUIRED: ::DWORD = 0x2; +pub const VSS_FSBT_INCREMENTAL_BACKUP_REQUIRED: ::DWORD = 0x4; +pub const VSS_FSBT_LOG_BACKUP_REQUIRED: ::DWORD = 0x8; +pub const VSS_FSBT_FULL_SNAPSHOT_REQUIRED: ::DWORD = 0x100; +pub const VSS_FSBT_DIFFERENTIAL_SNAPSHOT_REQUIRED: ::DWORD = 0x200; +pub const VSS_FSBT_INCREMENTAL_SNAPSHOT_REQUIRED: ::DWORD = 0x400; +pub const VSS_FSBT_LOG_SNAPSHOT_REQUIRED: ::DWORD = 0x800; +pub const VSS_FSBT_CREATED_DURING_BACKUP: ::DWORD = 0x10000; +pub const VSS_FSBT_ALL_BACKUP_REQUIRED: ::DWORD = 0xf; +pub const VSS_FSBT_ALL_SNAPSHOT_REQUIRED: ::DWORD = 0xf00; +pub type VSS_BACKUP_SCHEMA = ::DWORD; +pub type PVSS_BACKUP_SCHEMA = *mut VSS_BACKUP_SCHEMA; +pub const VSS_BS_UNDEFINED: ::DWORD = 0; +pub const VSS_BS_DIFFERENTIAL: ::DWORD = 0x1; +pub const VSS_BS_INCREMENTAL: ::DWORD = 0x2; +pub const VSS_BS_EXCLUSIVE_INCREMENTAL_DIFFERENTIAL: ::DWORD = 0x4; +pub const VSS_BS_LOG: ::DWORD = 0x8; +pub const VSS_BS_COPY: ::DWORD = 0x10; +pub const VSS_BS_TIMESTAMPED: ::DWORD = 0x20; +pub const VSS_BS_LAST_MODIFY: ::DWORD = 0x40; +pub const VSS_BS_LSN: ::DWORD = 0x80; +pub const VSS_BS_WRITER_SUPPORTS_NEW_TARGET: ::DWORD = 0x100; +pub const VSS_BS_WRITER_SUPPORTS_RESTORE_WITH_MOVE: ::DWORD = 0x200; +pub const VSS_BS_INDEPENDENT_SYSTEM_STATE: ::DWORD = 0x400; +pub const VSS_BS_ROLLFORWARD_RESTORE: ::DWORD = 0x1000; +pub const VSS_BS_RESTORE_RENAME: ::DWORD = 0x2000; +pub const VSS_BS_AUTHORITATIVE_RESTORE: ::DWORD = 0x4000; +pub const VSS_BS_WRITER_SUPPORTS_PARALLEL_RESTORES: ::DWORD = 0x8000; +pub type VSS_ID = ::GUID; +pub type VSS_PWSZ = *mut ::WCHAR; +pub type VSS_TIMESTAMP = ::LONGLONG; +STRUCT!{struct VSS_SNAPSHOT_PROP { + m_SnapshotId: ::VSS_ID, + m_SnapshotSetId: ::VSS_ID, + m_lSnapshotsCount: ::LONG, + m_pwszSnapshotDeviceObject: ::VSS_PWSZ, + m_pwszOriginalVolumeName: ::VSS_PWSZ, + m_pwszOriginatingMachine: ::VSS_PWSZ, + m_pwszServiceMachine: ::VSS_PWSZ, + m_pwszExposedName: ::VSS_PWSZ, + m_pwszExposedPath: ::VSS_PWSZ, + m_ProviderId: ::VSS_ID, + m_lSnapshotAttributes: ::LONG, + m_tsCreationTimestamp: ::VSS_TIMESTAMP, + m_eStatus: ::VSS_SNAPSHOT_STATE, +}} +type PVSS_SNAPSHOT_PROP = *mut VSS_SNAPSHOT_PROP; +STRUCT!{struct VSS_PROVIDER_PROP { + m_ProviderId: ::VSS_ID, + m_pwszProviderName: ::VSS_PWSZ, + m_eProviderType: ::VSS_PROVIDER_TYPE, + m_pwszProviderVersion: ::VSS_PWSZ, + m_ProviderVersionId: ::VSS_ID, + m_ClassId: ::CLSID, +}} +type PVSS_PROVIDER_PROP = *mut VSS_PROVIDER_PROP; +STRUCT!{struct VSS_OBJECT_UNION { + Snap: ::VSS_SNAPSHOT_PROP, +}} +UNION!(VSS_OBJECT_UNION, Snap, Prov, Prov_mut, VSS_PROVIDER_PROP); +STRUCT!{struct VSS_OBJECT_PROP { + Type: ::VSS_OBJECT_TYPE, + Obj: ::VSS_OBJECT_UNION, +}} +type PVSS_OBJECT_PROP = *mut VSS_OBJECT_PROP; +RIDL!( +interface IVssEnumObject(IVssEnumObjectVtbl): IUnknown(IUnknownVtbl) { + fn Next( + &mut self, celt: ::ULONG, rgelt: *mut ::VSS_OBJECT_PROP, pceltFetched: *mut ::ULONG + ) -> ::HRESULT, + fn Skip(&mut self, celt: ::ULONG) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn Clone(&mut self, ppenum: *mut *mut ::IVssEnumObject) -> ::HRESULT +} +); +RIDL!( +interface IVssAsync(IVssAsyncVtbl): IUnknown(IUnknownVtbl) { + fn Cancel(&mut self) -> ::HRESULT, + fn Wait(&mut self, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn QueryStatus(&mut self, pHrResult: *mut ::HRESULT, pReserved: *mut ::INT) -> ::HRESULT +} +); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/vsserror.rs b/bash-5.1/vendor/winapi-0.2.8/src/vsserror.rs new file mode 100644 index 0000000..ef84af0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/vsserror.rs @@ -0,0 +1,85 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License <LICENSE.md> +//! VSS Error header file +pub const VSS_E_BAD_STATE: ::HRESULT = 0x80042301u32 as i32; +pub const VSS_E_UNEXPECTED: ::HRESULT = 0x80042302u32 as i32; +pub const VSS_E_PROVIDER_ALREADY_REGISTERED: ::HRESULT = 0x80042303u32 as i32; +pub const VSS_E_PROVIDER_NOT_REGISTERED: ::HRESULT = 0x80042304u32 as i32; +pub const VSS_E_PROVIDER_VETO: ::HRESULT = 0x80042306u32 as i32; +pub const VSS_E_PROVIDER_IN_USE: ::HRESULT = 0x80042307u32 as i32; +pub const VSS_E_OBJECT_NOT_FOUND: ::HRESULT = 0x80042308u32 as i32; +pub const VSS_S_ASYNC_PENDING: ::HRESULT = 0x00042309u32 as i32; +pub const VSS_S_ASYNC_FINISHED: ::HRESULT = 0x0004230Au32 as i32; +pub const VSS_S_ASYNC_CANCELLED: ::HRESULT = 0x0004230Bu32 as i32; +pub const VSS_E_VOLUME_NOT_SUPPORTED: ::HRESULT = 0x8004230Cu32 as i32; +pub const VSS_E_VOLUME_NOT_SUPPORTED_BY_PROVIDER: ::HRESULT = 0x8004230Eu32 as i32; +pub const VSS_E_OBJECT_ALREADY_EXISTS: ::HRESULT = 0x8004230Du32 as i32; +pub const VSS_E_UNEXPECTED_PROVIDER_ERROR: ::HRESULT = 0x8004230Fu32 as i32; +pub const VSS_E_CORRUPT_XML_DOCUMENT: ::HRESULT = 0x80042310u32 as i32; +pub const VSS_E_INVALID_XML_DOCUMENT: ::HRESULT = 0x80042311u32 as i32; +pub const VSS_E_MAXIMUM_NUMBER_OF_VOLUMES_REACHED: ::HRESULT = 0x80042312u32 as i32; +pub const VSS_E_FLUSH_WRITES_TIMEOUT: ::HRESULT = 0x80042313u32 as i32; +pub const VSS_E_HOLD_WRITES_TIMEOUT: ::HRESULT = 0x80042314u32 as i32; +pub const VSS_E_UNEXPECTED_WRITER_ERROR: ::HRESULT = 0x80042315u32 as i32; +pub const VSS_E_SNAPSHOT_SET_IN_PROGRESS: ::HRESULT = 0x80042316u32 as i32; +pub const VSS_E_MAXIMUM_NUMBER_OF_SNAPSHOTS_REACHED: ::HRESULT = 0x80042317u32 as i32; +pub const VSS_E_WRITER_INFRASTRUCTURE: ::HRESULT = 0x80042318u32 as i32; +pub const VSS_E_WRITER_NOT_RESPONDING: ::HRESULT = 0x80042319u32 as i32; +pub const VSS_E_WRITER_ALREADY_SUBSCRIBED: ::HRESULT = 0x8004231Au32 as i32; +pub const VSS_E_UNSUPPORTED_CONTEXT: ::HRESULT = 0x8004231Bu32 as i32; +pub const VSS_E_VOLUME_IN_USE: ::HRESULT = 0x8004231Du32 as i32; +pub const VSS_E_MAXIMUM_DIFFAREA_ASSOCIATIONS_REACHED: ::HRESULT = 0x8004231Eu32 as i32; +pub const VSS_E_INSUFFICIENT_STORAGE: ::HRESULT = 0x8004231Fu32 as i32; +pub const VSS_E_NO_SNAPSHOTS_IMPORTED: ::HRESULT = 0x80042320u32 as i32; +pub const VSS_S_SOME_SNAPSHOTS_NOT_IMPORTED: ::HRESULT = 0x00042321u32 as i32; +pub const VSS_E_SOME_SNAPSHOTS_NOT_IMPORTED: ::HRESULT = 0x80042321u32 as i32; +pub const VSS_E_MAXIMUM_NUMBER_OF_REMOTE_MACHINES_REACHED: ::HRESULT = 0x80042322u32 as i32; +pub const VSS_E_REMOTE_SERVER_UNAVAILABLE: ::HRESULT = 0x80042323u32 as i32; +pub const VSS_E_REMOTE_SERVER_UNSUPPORTED: ::HRESULT = 0x80042324u32 as i32; +pub const VSS_E_REVERT_IN_PROGRESS: ::HRESULT = 0x80042325u32 as i32; +pub const VSS_E_REVERT_VOLUME_LOST: ::HRESULT = 0x80042326u32 as i32; +pub const VSS_E_REBOOT_REQUIRED: ::HRESULT = 0x80042327u32 as i32; +pub const VSS_E_TRANSACTION_FREEZE_TIMEOUT: ::HRESULT = 0x80042328u32 as i32; +pub const VSS_E_TRANSACTION_THAW_TIMEOUT: ::HRESULT = 0x80042329u32 as i32; +pub const VSS_E_VOLUME_NOT_LOCAL: ::HRESULT = 0x8004232Du32 as i32; +pub const VSS_E_CLUSTER_TIMEOUT: ::HRESULT = 0x8004232Eu32 as i32; +pub const VSS_E_WRITERERROR_INCONSISTENTSNAPSHOT: ::HRESULT = 0x800423F0u32 as i32; +pub const VSS_E_WRITERERROR_OUTOFRESOURCES: ::HRESULT = 0x800423F1u32 as i32; +pub const VSS_E_WRITERERROR_TIMEOUT: ::HRESULT = 0x800423F2u32 as i32; +pub const VSS_E_WRITERERROR_RETRYABLE: ::HRESULT = 0x800423F3u32 as i32; +pub const VSS_E_WRITERERROR_NONRETRYABLE: ::HRESULT = 0x800423F4u32 as i32; +pub const VSS_E_WRITERERROR_RECOVERY_FAILED: ::HRESULT = 0x800423F5u32 as i32; +pub const VSS_E_BREAK_REVERT_ID_FAILED: ::HRESULT = 0x800423F6u32 as i32; +pub const VSS_E_LEGACY_PROVIDER: ::HRESULT = 0x800423F7u32 as i32; +pub const VSS_E_MISSING_DISK: ::HRESULT = 0x800423F8u32 as i32; +pub const VSS_E_MISSING_HIDDEN_VOLUME: ::HRESULT = 0x800423F9u32 as i32; +pub const VSS_E_MISSING_VOLUME: ::HRESULT = 0x800423FAu32 as i32; +pub const VSS_E_AUTORECOVERY_FAILED: ::HRESULT = 0x800423FBu32 as i32; +pub const VSS_E_DYNAMIC_DISK_ERROR: ::HRESULT = 0x800423FCu32 as i32; +pub const VSS_E_NONTRANSPORTABLE_BCD: ::HRESULT = 0x800423FDu32 as i32; +pub const VSS_E_CANNOT_REVERT_DISKID: ::HRESULT = 0x800423FEu32 as i32; +pub const VSS_E_RESYNC_IN_PROGRESS: ::HRESULT = 0x800423FFu32 as i32; +pub const VSS_E_CLUSTER_ERROR: ::HRESULT = 0x80042400u32 as i32; +pub const VSS_E_UNSELECTED_VOLUME: ::HRESULT = 0x8004232Au32 as i32; +pub const VSS_E_SNAPSHOT_NOT_IN_SET: ::HRESULT = 0x8004232Bu32 as i32; +pub const VSS_E_NESTED_VOLUME_LIMIT: ::HRESULT = 0x8004232Cu32 as i32; +pub const VSS_E_NOT_SUPPORTED: ::HRESULT = 0x8004232Fu32 as i32; +pub const VSS_E_WRITERERROR_PARTIAL_FAILURE: ::HRESULT = 0x80042336u32 as i32; +pub const VSS_E_ASRERROR_DISK_ASSIGNMENT_FAILED: ::HRESULT = 0x80042401u32 as i32; +pub const VSS_E_ASRERROR_DISK_RECREATION_FAILED: ::HRESULT = 0x80042402u32 as i32; +pub const VSS_E_ASRERROR_NO_ARCPATH: ::HRESULT = 0x80042403u32 as i32; +pub const VSS_E_ASRERROR_MISSING_DYNDISK: ::HRESULT = 0x80042404u32 as i32; +pub const VSS_E_ASRERROR_SHARED_CRIDISK: ::HRESULT = 0x80042405u32 as i32; +pub const VSS_E_ASRERROR_DATADISK_RDISK0: ::HRESULT = 0x80042406u32 as i32; +pub const VSS_E_ASRERROR_RDISK0_TOOSMALL: ::HRESULT = 0x80042407u32 as i32; +pub const VSS_E_ASRERROR_CRITICAL_DISKS_TOO_SMALL: ::HRESULT = 0x80042408u32 as i32; +pub const VSS_E_WRITER_STATUS_NOT_AVAILABLE: ::HRESULT = 0x80042409u32 as i32; +pub const VSS_E_ASRERROR_DYNAMIC_VHD_NOT_SUPPORTED: ::HRESULT = 0x8004240Au32 as i32; +pub const VSS_E_CRITICAL_VOLUME_ON_INVALID_DISK: ::HRESULT = 0x80042411u32 as i32; +pub const VSS_E_ASRERROR_RDISK_FOR_SYSTEM_DISK_NOT_FOUND: ::HRESULT = 0x80042412u32 as i32; +pub const VSS_E_ASRERROR_NO_PHYSICAL_DISK_AVAILABLE: ::HRESULT = 0x80042413u32 as i32; +pub const VSS_E_ASRERROR_FIXED_PHYSICAL_DISK_AVAILABLE_AFTER_DISK_EXCLUSION: ::HRESULT = + 0x80042414u32 as i32; +pub const VSS_E_ASRERROR_CRITICAL_DISK_CANNOT_BE_EXCLUDED: ::HRESULT = 0x80042415u32 as i32; +pub const VSS_E_ASRERROR_SYSTEM_PARTITION_HIDDEN: ::HRESULT = 0x80042416u32 as i32; +pub const VSS_E_FSS_TIMEOUT: ::HRESULT = 0x80042417u32 as i32; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/vswriter.rs b/bash-5.1/vendor/winapi-0.2.8/src/vswriter.rs new file mode 100644 index 0000000..fd1509c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/vswriter.rs @@ -0,0 +1,241 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License <LICENSE.md> +//! VSS Writer header file +ENUM!{enum VSS_USAGE_TYPE { + VSS_UT_UNDEFINED = 0, + VSS_UT_BOOTABLESYSTEMSTATE = 1, + VSS_UT_SYSTEMSERVICE = 2, + VSS_UT_USERDATA = 3, + VSS_UT_OTHER = 4, +}} +ENUM!{enum VSS_SOURCE_TYPE { + VSS_ST_UNDEFINED = 0, + VSS_ST_TRANSACTEDDB = 1, + VSS_ST_NONTRANSACTEDDB = 2, + VSS_ST_OTHER = 3, +}} +ENUM!{enum VSS_RESTOREMETHOD_ENUM { + VSS_RME_UNDEFINED = 0, + VSS_RME_RESTORE_IF_NOT_THERE = 1, + VSS_RME_RESTORE_IF_CAN_REPLACE = 2, + VSS_RME_STOP_RESTORE_START = 3, + VSS_RME_RESTORE_TO_ALTERNATE_LOCATION = 4, + VSS_RME_RESTORE_AT_REBOOT = 5, + VSS_RME_RESTORE_AT_REBOOT_IF_CANNOT_REPLACE = 6, + VSS_RME_CUSTOM = 7, + VSS_RME_RESTORE_STOP_START = 8, +}} +ENUM!{enum VSS_WRITERRESTORE_ENUM { + VSS_WRE_UNDEFINED = 0, + VSS_WRE_NEVER = 1, + VSS_WRE_IF_REPLACE_FAILS = 2, + VSS_WRE_ALWAYS = 3, +}} +ENUM!{enum VSS_COMPONENT_TYPE { + VSS_CT_UNDEFINED = 0, + VSS_CT_DATABASE = 1, + VSS_CT_FILEGROUP = 2, +}} +ENUM!{enum VSS_ALTERNATE_WRITER_STATE { + VSS_AWS_UNDEFINED = 0, + VSS_AWS_NO_ALTERNATE_WRITER = 1, + VSS_AWS_ALTERNATE_WRITER_EXISTS = 2, + VSS_AWS_THIS_IS_ALTERNATE_WRITER = 3, +}} +pub type VSS_SUBSCRIBE_MASK = ::DWORD; +pub const VSS_SM_POST_SNAPSHOT_FLAG: ::DWORD = 0x00000001; +pub const VSS_SM_BACKUP_EVENTS_FLAG: ::DWORD = 0x00000002; +pub const VSS_SM_RESTORE_EVENTS_FLAG: ::DWORD = 0x00000004; +pub const VSS_SM_IO_THROTTLING_FLAG: ::DWORD = 0x00000008; +pub const VSS_SM_ALL_FLAGS: ::DWORD = 0xffffffff; +ENUM!{enum VSS_RESTORE_TARGET { + VSS_RT_UNDEFINED = 0, + VSS_RT_ORIGINAL = 1, + VSS_RT_ALTERNATE = 2, + VSS_RT_DIRECTED = 3, + VSS_RT_ORIGINAL_LOCATION = 4, +}} +ENUM!{enum VSS_FILE_RESTORE_STATUS { + VSS_RS_UNDEFINED = 0, + VSS_RS_NONE = 1, + VSS_RS_ALL = 2, + VSS_RS_FAILED = 3, +}} +pub type VSS_COMPONENT_FLAGS = ::DWORD; +pub const VSS_CF_BACKUP_RECOVERY: ::DWORD = 0x00000001; +pub const VSS_CF_APP_ROLLBACK_RECOVERY: ::DWORD = 0x00000002; +pub const VSS_CF_NOT_SYSTEM_STATE: ::DWORD = 0x00000004; +RIDL!( +interface IVssWMFiledesc(IVssWMFiledescVtbl): IUnknown(IUnknownVtbl) { + fn GetPath(&mut self, pbstrPath: *mut ::BSTR) -> ::HRESULT, + fn GetFilespec(&mut self, pbstrFilespec: *mut ::BSTR) -> ::HRESULT, + fn GetRecursive(&mut self, pbRecursive: *mut bool) -> ::HRESULT, + fn GetAlternateLocation(&mut self, pbstrAlternateLocation: *mut ::BSTR) -> ::HRESULT, + fn GetBackupTypeMask(&mut self, pdwTypeMask: *mut ::DWORD) -> ::HRESULT +} +); +RIDL!( +interface IVssWMDependency(IVssWMDependencyVtbl): IUnknown(IUnknownVtbl) { + fn GetWriterId(&mut self, pWriterId: *mut ::VSS_ID) -> ::HRESULT, + fn GetLogicalPath(&mut self, pbstrLogicalPath: *mut ::BSTR) -> ::HRESULT, + fn GetComponentName(&mut self, pbstrComponentName: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface IVssComponent(IVssComponentVtbl): IUnknown(IUnknownVtbl) { + fn GetLogicalPath(&mut self, pbstrPath: *mut ::BSTR) -> ::HRESULT, + fn GetComponentType(&mut self, pct: *mut ::VSS_COMPONENT_TYPE) -> ::HRESULT, + fn GetComponentName(&mut self, pbstrName: *mut ::BSTR) -> ::HRESULT, + fn GetBackupSucceeded(&mut self, pbSucceeded: *mut bool) -> ::HRESULT, + fn GetAlternateLocationMappingCount(&mut self, pcMappings: *mut ::UINT) -> ::HRESULT, + fn GetAlternateLocationMapping( + &mut self, iMapping: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn SetBackupMetadata(&mut self, wszData: ::LPCWSTR) -> ::HRESULT, + fn GetBackupMetadata(&mut self, pbstrData: *mut ::BSTR) -> ::HRESULT, + fn AddPartialFile( + &mut self, wszPath: ::LPCWSTR, wszFilename: ::LPCWSTR, wszRanges: ::LPCWSTR, + wszMetadata: ::LPCWSTR + ) -> ::HRESULT, + fn GetPartialFileCount(&mut self, pcPartialFiles: *mut ::UINT) -> ::HRESULT, + fn GetPartialFile( + &mut self, iPartialFile: ::UINT, pbstrPath: *mut ::BSTR, pbstrFilename: *mut ::BSTR, + pbstrRange: *mut ::BSTR, pbstrMetadata: *mut ::BSTR + ) -> ::HRESULT, + fn IsSelectedForRestore(&mut self, pbSelectedForRestore: *mut bool) -> ::HRESULT, + fn GetAdditionalRestores(&mut self, pbAdditionalRestores: *mut bool) -> ::HRESULT, + fn GetNewTargetCount(&mut self, pcNewTarget: *mut ::UINT) -> ::HRESULT, + fn GetNewTarget( + &mut self, iNewTarget: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn AddDirectedTarget( + &mut self, wszSourcePath: ::LPCWSTR, wszSourceFilename: ::LPCWSTR, + wszSourceRangeList: ::LPCWSTR, wszDestinationPath: ::LPCWSTR, + wszDestinationFilename: ::LPCWSTR, wszDestinationRangeList: ::LPCWSTR + ) -> ::HRESULT, + fn GetDirectedTargetCount(&mut self, pcDirectedTarget: *mut ::UINT) -> ::HRESULT, + fn GetDirectedTarget( + &mut self, iDirectedTarget: ::UINT, pbstrSourcePath: *mut ::BSTR, + pbstrSourceFileName: *mut ::BSTR, pbstrSourceRangeList: *mut ::BSTR, + pbstrDestinationPath: *mut ::BSTR, pbstrDestinationFilename: *mut ::BSTR, + pbstrDestinationRangeList: *mut ::BSTR + ) -> ::HRESULT, + fn SetRestoreMetadata(&mut self, wszRestoreMetadata: ::LPCWSTR) -> ::HRESULT, + fn GetRestoreMetadata(&mut self, pbstrRestoreMetadata: *mut ::BSTR) -> ::HRESULT, + fn SetRestoreTarget(&mut self, target: ::VSS_RESTORE_TARGET) -> ::HRESULT, + fn GetRestoreTarget(&mut self, pTarget: *mut ::VSS_RESTORE_TARGET) -> ::HRESULT, + fn SetPreRestoreFailureMsg(&mut self, wszPreRestoreFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn GetPreRestoreFailureMsg(&mut self, pbstrPreRestoreFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn SetPostRestoreFailureMsg(&mut self, wszPostRestoreFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn GetPostRestoreFailureMsg(&mut self, pbstrPostRestoreFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn SetBackupStamp(&mut self, wszBackupStamp: ::LPCWSTR) -> ::HRESULT, + fn GetBackupStamp(&mut self, pbstrBackupStamp: *mut ::BSTR) -> ::HRESULT, + fn GetPreviousBackupStamp(&mut self, pbstrBackupStamp: *mut ::BSTR) -> ::HRESULT, + fn GetBackupOptions(&mut self, pbstrBackupOptions: *mut ::BSTR) -> ::HRESULT, + fn GetRestoreOptions(&mut self, pbstrRestoreOptions: *mut ::BSTR) -> ::HRESULT, + fn GetRestoreSubcomponentCount(&mut self, pcRestoreSubcomponent: *mut ::UINT) -> ::HRESULT, + fn GetRestoreSubcomponent( + &mut self, iComponent: ::UINT, pbstrLogicalPath: *mut ::BSTR, + pbstrComponentName: *mut ::BSTR, pbRepair: *mut bool + ) -> ::HRESULT, + fn GetFileRestoreStatus(&mut self, pStatus: *mut VSS_FILE_RESTORE_STATUS) -> ::HRESULT, + fn AddDifferencedFilesByLastModifyTime( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: ::BOOL, + ftLastModifyTime: ::FILETIME + ) -> ::HRESULT, + fn AddDifferencedFilesByLastModifyLSN( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: ::BOOL, + bstrLsnString: ::BSTR + ) -> ::HRESULT, + fn GetDifferencedFilesCount(&mut self, pcDifferencedFiles: *mut ::UINT) -> ::HRESULT, + fn GetDifferencedFile( + &mut self, iDifferencedFile: ::UINT, pbstrPath: *mut ::BSTR, pbstrFilespec: *mut ::BSTR, + pbRecursive: *mut ::BOOL, pbstrLsnString: *mut ::BSTR, pftLastModifyTime: *mut ::FILETIME + ) -> ::HRESULT +} +); +RIDL!( +interface IVssWriterComponents(IVssWriterComponentsVtbl) { + fn GetComponentCount(&mut self, pcComponents: *mut ::UINT) -> ::HRESULT, + fn GetWriterInfo( + &mut self, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID + ) -> ::HRESULT, + fn GetComponent( + &mut self, iComponent: ::UINT, ppComponent: *mut *mut ::IVssComponent + ) -> ::HRESULT +} +); +RIDL!( +interface IVssComponentEx(IVssComponentExVtbl): IVssComponent(IVssComponentVtbl) { + fn SetPrepareForBackupFailureMsg(&mut self, wszFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn SetPostSnapshotFailureMsg(&mut self, wszFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn GetPrepareForBackupFailureMsg(&mut self, pbstrFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn GetPostSnapshotFailureMsg(&mut self, pbstrFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn GetAuthoritativeRestore(&mut self, pbAuth: *mut bool) -> ::HRESULT, + fn GetRollForward( + &mut self, pRollType: *mut ::VSS_ROLLFORWARD_TYPE, pbstrPoint: *mut ::BSTR + ) -> ::HRESULT, + fn GetRestoreName(&mut self, pbstrName: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface IVssComponentEx2(IVssComponentEx2Vtbl): IVssComponentEx(IVssComponentExVtbl) { + fn SetFailure( + &mut self, hr: ::HRESULT, hrApplication: ::HRESULT, wszApplicationMessage: ::LPCWSTR, + dwReserved: ::DWORD + ) -> ::HRESULT, + fn GetFailure( + &mut self, phr: *mut ::HRESULT, phrApplication: *mut ::HRESULT, + pbstrApplicationMessage: *mut ::BSTR, pdwReserved: *mut ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface IVssCreateWriterMetadata(IVssCreateWriterMetadataVtbl) { + fn AddIncludeFiles( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool, + wszAlternateLocation: ::LPCWSTR + ) -> ::HRESULT, + fn AddExcludeFiles( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool + ) -> ::HRESULT, + fn AddComponent( + &mut self, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszCaption: ::LPCWSTR, pbIcon: *const ::BYTE, cbIcon: ::UINT, + bRestoreMetadata: bool, bNotifyOnBackupComplete: bool, bSelectableForRestore: bool, + dwComponentFlags: ::DWORD + ) -> ::HRESULT, + fn AddDatabaseFiles( + &mut self, wszLogicalPath: ::LPCWSTR, wszDatabaseName: ::LPCWSTR, wszPath: ::LPCWSTR, + wszFilespec: ::LPCWSTR, dwBackupTypeMask: ::DWORD + ) -> ::HRESULT, + fn AddDatabaseLogFiles(&mut self, wszLogicalPath: ::LPCWSTR, wszDatabaseName: ::LPCWSTR, + wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, dwBackupTypeMask: ::DWORD + ) -> ::HRESULT, + fn AddFilesToFileGroup(&mut self, wszLogicalPath: ::LPCWSTR, wszGroupName: ::LPCWSTR, + wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool, + wszAlternateLocation: ::LPCWSTR, dwBackupTypeMask: ::DWORD + ) -> ::HRESULT, + fn SetRestoreMethod(&mut self, method: ::VSS_RESTOREMETHOD_ENUM, wszService: ::LPCWSTR, + wszUserProcedure: ::LPCWSTR, writerRestore: ::VSS_WRITERRESTORE_ENUM, + bRebootRequired: bool + ) -> ::HRESULT, + fn AddAlternateLocationMapping(&mut self, wszSourcePath: ::LPCWSTR, + wszSourceFilespec: ::LPCWSTR, bRecursive: bool, wszDestination: ::LPCWSTR + ) -> ::HRESULT, + fn AddComponentDependency(&mut self, wszForLogicalPath: ::LPCWSTR, + wszForComponentName: ::LPCWSTR, onWriterId: ::VSS_ID, wszOnLogicalPath: ::LPCWSTR, + wszOnComponentName: ::LPCWSTR + ) -> ::HRESULT, + fn SetBackupSchema(&mut self, dwSchemaMask: ::DWORD) -> ::HRESULT, + fn GetDocument(&mut self, pDoc: *mut *mut ::VOID) -> ::HRESULT, //TODO IXMLDOMDocument + fn SaveAsXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT +} +); +//IVssCreateWriterMetadataEx +//IVssWriterImpl +//IVssCreateExpressWriterMetadata +//IVssExpressWriter +//CVssWriter +//CVssWriterEx +//CVssWriterEx2 diff --git a/bash-5.1/vendor/winapi-0.2.8/src/werapi.rs b/bash-5.1/vendor/winapi-0.2.8/src/werapi.rs new file mode 100644 index 0000000..33a5a50 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/werapi.rs @@ -0,0 +1,8 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Function prototypes for Windows Error Reporting (WER) +ENUM!{enum WER_REGISTER_FILE_TYPE { + WerRegFileTypeUserDocument = 1, + WerRegFileTypeOther = 2, + WerRegFileTypeMax, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winbase.rs b/bash-5.1/vendor/winapi-0.2.8/src/winbase.rs new file mode 100644 index 0000000..59e3988 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winbase.rs @@ -0,0 +1,552 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This module defines the 32-Bit Windows Base APIs +pub const FILE_BEGIN: ::DWORD = 0; +pub const FILE_CURRENT: ::DWORD = 1; +pub const FILE_END: ::DWORD = 2; +pub const WAIT_FAILED: ::DWORD = 0xFFFFFFFF; +pub const WAIT_OBJECT_0: ::DWORD = ::STATUS_WAIT_0 as ::DWORD; +pub const WAIT_ABANDONED: ::DWORD = ::STATUS_ABANDONED_WAIT_0 as ::DWORD; +pub const WAIT_ABANDONED_0: ::DWORD = ::STATUS_ABANDONED_WAIT_0 as ::DWORD; +pub const WAIT_IO_COMPLETION: ::DWORD = ::STATUS_USER_APC as ::DWORD; +pub const FILE_FLAG_WRITE_THROUGH: ::DWORD = 0x80000000; +pub const FILE_FLAG_OVERLAPPED: ::DWORD = 0x40000000; +pub const FILE_FLAG_NO_BUFFERING: ::DWORD = 0x20000000; +pub const FILE_FLAG_RANDOM_ACCESS: ::DWORD = 0x10000000; +pub const FILE_FLAG_SEQUENTIAL_SCAN: ::DWORD = 0x08000000; +pub const FILE_FLAG_DELETE_ON_CLOSE: ::DWORD = 0x04000000; +pub const FILE_FLAG_BACKUP_SEMANTICS: ::DWORD = 0x02000000; +pub const FILE_FLAG_POSIX_SEMANTICS: ::DWORD = 0x01000000; +pub const FILE_FLAG_SESSION_AWARE: ::DWORD = 0x00800000; +pub const FILE_FLAG_OPEN_REPARSE_POINT: ::DWORD = 0x00200000; +pub const FILE_FLAG_OPEN_NO_RECALL: ::DWORD = 0x00100000; +pub const FILE_FLAG_FIRST_PIPE_INSTANCE: ::DWORD = 0x00080000; +pub const FILE_FLAG_OPEN_REQUIRING_OPLOCK: ::DWORD = 0x00040000; +pub const PROGRESS_CONTINUE: ::DWORD = 0; +pub const PROGRESS_CANCEL: ::DWORD = 1; +pub const PROGRESS_STOP: ::DWORD = 2; +pub const PROGRESS_QUIET: ::DWORD = 3; +pub const CALLBACK_CHUNK_FINISHED: ::DWORD = 0x00000000; +pub const CALLBACK_STREAM_SWITCH: ::DWORD = 0x00000001; +pub const COPY_FILE_FAIL_IF_EXISTS: ::DWORD = 0x00000001; +pub const COPY_FILE_RESTARTABLE: ::DWORD = 0x00000002; +pub const COPY_FILE_OPEN_SOURCE_FOR_WRITE: ::DWORD = 0x00000004; +pub const COPY_FILE_ALLOW_DECRYPTED_DESTINATION: ::DWORD = 0x00000008; +pub const COPY_FILE_COPY_SYMLINK: ::DWORD = 0x00000800; +pub const COPY_FILE_NO_BUFFERING: ::DWORD = 0x00001000; +pub const COPY_FILE_REQUEST_SECURITY_PRIVILEGES: ::DWORD = 0x00002000; +pub const COPY_FILE_RESUME_FROM_PAUSE: ::DWORD = 0x00004000; +pub const COPY_FILE_NO_OFFLOAD: ::DWORD = 0x00040000; +pub const REPLACEFILE_WRITE_THROUGH: ::DWORD = 0x00000001; +pub const REPLACEFILE_IGNORE_MERGE_ERRORS: ::DWORD = 0x00000002; +pub const REPLACEFILE_IGNORE_ACL_ERRORS: ::DWORD = 0x00000004; +pub const PIPE_ACCESS_INBOUND: ::DWORD = 0x00000001; +pub const PIPE_ACCESS_OUTBOUND: ::DWORD = 0x00000002; +pub const PIPE_ACCESS_DUPLEX: ::DWORD = 0x00000003; +pub const PIPE_CLIENT_END: ::DWORD = 0x00000000; +pub const PIPE_SERVER_END: ::DWORD = 0x00000001; +pub const PIPE_WAIT: ::DWORD = 0x00000000; +pub const PIPE_NOWAIT: ::DWORD = 0x00000001; +pub const PIPE_READMODE_BYTE: ::DWORD = 0x00000000; +pub const PIPE_READMODE_MESSAGE: ::DWORD = 0x00000002; +pub const PIPE_TYPE_BYTE: ::DWORD = 0x00000000; +pub const PIPE_TYPE_MESSAGE: ::DWORD = 0x00000004; +pub const PIPE_ACCEPT_REMOTE_CLIENTS: ::DWORD = 0x00000000; +pub const PIPE_REJECT_REMOTE_CLIENTS: ::DWORD = 0x00000008; +pub const PIPE_UNLIMITED_INSTANCES: ::DWORD = 255; +//270 +pub const SECURITY_CONTEXT_TRACKING: ::DWORD = 0x00040000; +pub const SECURITY_EFFECTIVE_ONLY: ::DWORD = 0x00080000; +pub const SECURITY_SQOS_PRESENT: ::DWORD = 0x00100000; +pub const SECURITY_VALID_SQOS_FLAGS: ::DWORD = 0x001F0000; +//282 +pub type PFIBER_START_ROUTINE = Option<unsafe extern "system" fn(lpFiberParameter: ::LPVOID)>; +pub type LPFIBER_START_ROUTINE = PFIBER_START_ROUTINE; +pub type PFIBER_CALLOUT_ROUTINE = Option<unsafe extern "system" fn( + lpParameter: ::LPVOID, +) -> ::LPVOID>; +//299 +pub type LPLDT_ENTRY = ::LPVOID; // TODO - fix this for 32-bit +//405 +STRUCT!{struct COMMPROP { + wPacketLength: ::WORD, + wPacketVersion: ::WORD, + dwServiceMask: ::DWORD, + dwReserved1: ::DWORD, + dwMaxTxQueue: ::DWORD, + dwMaxRxQueue: ::DWORD, + dwMaxBaud: ::DWORD, + dwProvSubType: ::DWORD, + dwProvCapabilities: ::DWORD, + dwSettableParams: ::DWORD, + dwSettableBaud: ::DWORD, + wSettableData: ::WORD, + wSettableStopParity: ::WORD, + dwCurrentTxQueue: ::DWORD, + dwCurrentRxQueue: ::DWORD, + dwProvSpec1: ::DWORD, + dwProvSpec2: ::DWORD, + wcProvChar: [::WCHAR; 1], +}} +pub type LPCOMMPROP = *mut COMMPROP; +//432 +STRUCT!{struct COMSTAT { + BitFields: ::DWORD, + cbInQue: ::DWORD, + cbOutQue : ::DWORD, +}} +BITFIELD!(COMSTAT BitFields: ::DWORD [ + fCtsHold set_fCtsHold[0..1], + fDsrHold set_fDsrHold[1..2], + fRlsdHold set_fRlsdHold[2..3], + fXoffHold set_fXoffHold[3..4], + fXoffSent set_fXoffSent[4..5], + fEof set_fEof[5..6], + fTxim set_fTxim[6..7], + fReserved set_fReserved[7..32], +]); +pub type LPCOMSTAT = *mut COMSTAT; +//460 +STRUCT!{struct DCB { + DCBlength: ::DWORD, + BaudRate: ::DWORD, + BitFields: ::DWORD, + wReserved: ::WORD, + XonLim: ::WORD, + XoffLim: ::WORD, + ByteSize: ::BYTE, + Parity: ::BYTE, + StopBits: ::BYTE, + XonChar: ::c_char, + XoffChar: ::c_char, + ErrorChar: ::c_char, + EofChar: ::c_char, + EvtChar: ::c_char, + wReserved1: ::WORD, +}} +BITFIELD!(DCB BitFields: ::DWORD [ + fBinary set_fBinary[0..1], + fParity set_fParity[1..2], + fOutxCtsFlow set_fOutxCtsFlow[2..3], + fOutxDsrFlow set_fOutxDsrFlow[3..4], + fDtrControl set_fDtrControl[4..6], + fDsrSensitivity set_fDsrSensitivity[6..7], + fTXContinueOnXoff set_fTXContinueOnXoff[7..8], + fOutX set_fOutX[8..9], + fInX set_fInX[9..10], + fErrorChar set_fErrorChar[10..11], + fNull set_fNull[11..12], + fRtsControl set_fRtsControl[12..14], + fAbortOnError set_fAbortOnError[14..15], + fDummy2 set_fDummy2[15..32], +]); +pub type LPDCB = *mut DCB; +STRUCT!{struct COMMTIMEOUTS { + ReadIntervalTimeout: ::DWORD, + ReadTotalTimeoutMultiplier: ::DWORD, + ReadTotalTimeoutConstant: ::DWORD, + WriteTotalTimeoutMultiplier: ::DWORD, + WriteTotalTimeoutConstant: ::DWORD, +}} +pub type LPCOMMTIMEOUTS = *mut COMMTIMEOUTS; +STRUCT!{struct COMMCONFIG { + dwSize: ::DWORD, + wVersion: ::WORD, + wReserved: ::WORD, + dcb: DCB, + dwProviderSubType: ::DWORD, + dwProviderOffset: ::DWORD, + dwProviderSize: ::DWORD, + wcProviderData: [::WCHAR; 1], +}} +pub type LPCOMMCONFIG = *mut COMMCONFIG; +//547 +STRUCT!{struct MEMORYSTATUS { + dwLength: ::DWORD, + dwMemoryLoad: ::DWORD, + dwTotalPhys: ::SIZE_T, + dwAvailPhys: ::SIZE_T, + dwTotalPageFile: ::SIZE_T, + dwAvailPageFile: ::SIZE_T, + dwTotalVirtual: ::SIZE_T, + dwAvailVirtual: ::SIZE_T, +}} +pub type LPMEMORYSTATUS = *mut MEMORYSTATUS; +//568 +pub const DEBUG_PROCESS: ::DWORD = 0x00000001; +pub const DEBUG_ONLY_THIS_PROCESS: ::DWORD = 0x00000002; +pub const CREATE_SUSPENDED: ::DWORD = 0x00000004; +pub const DETACHED_PROCESS: ::DWORD = 0x00000008; +pub const CREATE_NEW_CONSOLE: ::DWORD = 0x00000010; +pub const NORMAL_PRIORITY_CLASS: ::DWORD = 0x00000020; +pub const IDLE_PRIORITY_CLASS: ::DWORD = 0x00000040; +pub const HIGH_PRIORITY_CLASS: ::DWORD = 0x00000080; +pub const REALTIME_PRIORITY_CLASS: ::DWORD = 0x00000100; +pub const CREATE_NEW_PROCESS_GROUP: ::DWORD = 0x00000200; +pub const CREATE_UNICODE_ENVIRONMENT: ::DWORD = 0x00000400; +pub const CREATE_SEPARATE_WOW_VDM: ::DWORD = 0x00000800; +pub const CREATE_SHARED_WOW_VDM: ::DWORD = 0x00001000; +pub const CREATE_FORCEDOS: ::DWORD = 0x00002000; +pub const BELOW_NORMAL_PRIORITY_CLASS: ::DWORD = 0x00004000; +pub const ABOVE_NORMAL_PRIORITY_CLASS: ::DWORD = 0x00008000; +pub const INHERIT_PARENT_AFFINITY: ::DWORD = 0x00010000; +pub const INHERIT_CALLER_PRIORITY: ::DWORD = 0x00020000; +pub const CREATE_PROTECTED_PROCESS: ::DWORD = 0x00040000; +pub const EXTENDED_STARTUPINFO_PRESENT: ::DWORD = 0x00080000; +pub const PROCESS_MODE_BACKGROUND_BEGIN: ::DWORD = 0x00100000; +pub const PROCESS_MODE_BACKGROUND_END: ::DWORD = 0x00200000; +pub const CREATE_BREAKAWAY_FROM_JOB: ::DWORD = 0x01000000; +pub const CREATE_PRESERVE_CODE_AUTHZ_LEVEL: ::DWORD = 0x02000000; +pub const CREATE_DEFAULT_ERROR_MODE: ::DWORD = 0x04000000; +pub const CREATE_NO_WINDOW: ::DWORD = 0x08000000; +pub const PROFILE_USER: ::DWORD = 0x10000000; +pub const PROFILE_KERNEL: ::DWORD = 0x20000000; +pub const PROFILE_SERVER: ::DWORD = 0x40000000; +pub const CREATE_IGNORE_SYSTEM_DEFAULT: ::DWORD = 0x80000000; +//618 +pub const THREAD_PRIORITY_LOWEST: ::DWORD = ::THREAD_BASE_PRIORITY_MIN; +pub const THREAD_PRIORITY_BELOW_NORMAL: ::DWORD = THREAD_PRIORITY_LOWEST + 1; +pub const THREAD_PRIORITY_NORMAL: ::DWORD = 0; +pub const THREAD_PRIORITY_HIGHEST: ::DWORD = ::THREAD_BASE_PRIORITY_MAX; +pub const THREAD_PRIORITY_ABOVE_NORMAL: ::DWORD = THREAD_PRIORITY_HIGHEST - 1; +pub const THREAD_PRIORITY_ERROR_RETURN: ::DWORD = ::MAXLONG as ::DWORD; +pub const THREAD_PRIORITY_TIME_CRITICAL: ::DWORD = ::THREAD_BASE_PRIORITY_LOWRT; +pub const THREAD_PRIORITY_IDLE: ::DWORD = ::THREAD_BASE_PRIORITY_IDLE; +pub const THREAD_MODE_BACKGROUND_BEGIN: ::DWORD = 0x00010000; +pub const THREAD_MODE_BACKGROUND_END: ::DWORD = 0x00020000; +//666 +pub const DRIVE_UNKNOWN: ::DWORD = 0; +pub const DRIVE_NO_ROOT_DIR: ::DWORD = 1; +pub const DRIVE_REMOVABLE: ::DWORD = 2; +pub const DRIVE_FIXED: ::DWORD = 3; +pub const DRIVE_REMOTE: ::DWORD = 4; +pub const DRIVE_CDROM: ::DWORD = 5; +pub const DRIVE_RAMDISK: ::DWORD = 6; +pub const FILE_TYPE_UNKNOWN: ::DWORD = 0x0000; +pub const FILE_TYPE_DISK: ::DWORD = 0x0001; +pub const FILE_TYPE_CHAR: ::DWORD = 0x0002; +pub const FILE_TYPE_PIPE: ::DWORD = 0x0003; +pub const FILE_TYPE_REMOTE: ::DWORD = 0x8000; +pub const STD_INPUT_HANDLE: ::DWORD = 0xFFFFFFF6; +pub const STD_OUTPUT_HANDLE: ::DWORD = 0xFFFFFFF5; +pub const STD_ERROR_HANDLE: ::DWORD = 0xFFFFFFF4; +pub const NOPARITY: ::DWORD = 0; +pub const ODDPARITY: ::DWORD = 1; +pub const EVENPARITY: ::DWORD = 2; +pub const MARKPARITY: ::DWORD = 3; +pub const SPACEPARITY: ::DWORD = 4; +pub const ONESTOPBIT: ::DWORD = 0; +pub const ONE5STOPBITS: ::DWORD = 1; +pub const TWOSTOPBITS: ::DWORD = 2; +pub const IGNORE: ::DWORD = 0; +pub const INFINITE: ::DWORD = 0xFFFFFFFF; +//1729 +pub const SEM_FAILCRITICALERRORS: ::UINT = 0x0001; +pub const SEM_NOGPFAULTERRORBOX: ::UINT = 0x0002; +pub const SEM_NOALIGNMENTFAULTEXCEPT: ::UINT = 0x0004; +pub const SEM_NOOPENFILEERRORBOX: ::UINT = 0x8000; +//2320 +pub const FORMAT_MESSAGE_IGNORE_INSERTS: ::DWORD = 0x00000200; +pub const FORMAT_MESSAGE_FROM_STRING: ::DWORD = 0x00000400; +pub const FORMAT_MESSAGE_FROM_HMODULE: ::DWORD = 0x00000800; +pub const FORMAT_MESSAGE_FROM_SYSTEM: ::DWORD = 0x00001000; +pub const FORMAT_MESSAGE_ARGUMENT_ARRAY: ::DWORD = 0x00002000; +pub const FORMAT_MESSAGE_MAX_WIDTH_MASK: ::DWORD = 0x000000FF; +pub const FORMAT_MESSAGE_ALLOCATE_BUFFER: ::DWORD = 0x00000100; +//2873 +pub const STARTF_USESHOWWINDOW: ::DWORD = 0x00000001; +pub const STARTF_USESIZE: ::DWORD = 0x00000002; +pub const STARTF_USEPOSITION: ::DWORD = 0x00000004; +pub const STARTF_USECOUNTCHARS: ::DWORD = 0x00000008; +pub const STARTF_USEFILLATTRIBUTE: ::DWORD = 0x00000010; +pub const STARTF_RUNFULLSCREEN: ::DWORD = 0x00000020; +pub const STARTF_FORCEONFEEDBACK: ::DWORD = 0x00000040; +pub const STARTF_FORCEOFFFEEDBACK: ::DWORD = 0x00000080; +pub const STARTF_USESTDHANDLES: ::DWORD = 0x00000100; +pub const STARTF_USEHOTKEY: ::DWORD = 0x00000200; +pub const STARTF_TITLEISLINKNAME: ::DWORD = 0x00000800; +pub const STARTF_TITLEISAPPID: ::DWORD = 0x00001000; +pub const STARTF_PREVENTPINNING: ::DWORD = 0x00002000; +pub const STARTF_UNTRUSTEDSOURCE: ::DWORD = 0x00008000; +//5002 +pub type LPPROGRESS_ROUTINE = Option<unsafe extern "system" fn( + TotalFileSize: ::LARGE_INTEGER, TotalBytesTransferred: ::LARGE_INTEGER, + StreamSize: ::LARGE_INTEGER, StreamBytesTransferred: ::LARGE_INTEGER, dwStreamNumber: ::DWORD, + dwCallbackReason: ::DWORD, hSourceFile: ::HANDLE, hDestinationFile: ::HANDLE, lpData: ::LPVOID, +) -> ::DWORD>; +//5095 +ENUM!{enum COPYFILE2_MESSAGE_TYPE { + COPYFILE2_CALLBACK_NONE = 0, + COPYFILE2_CALLBACK_CHUNK_STARTED, + COPYFILE2_CALLBACK_CHUNK_FINISHED, + COPYFILE2_CALLBACK_STREAM_STARTED, + COPYFILE2_CALLBACK_STREAM_FINISHED, + COPYFILE2_CALLBACK_POLL_CONTINUE, + COPYFILE2_CALLBACK_ERROR, + COPYFILE2_CALLBACK_MAX, +}} +ENUM!{enum COPYFILE2_MESSAGE_ACTION { + COPYFILE2_PROGRESS_CONTINUE = 0, + COPYFILE2_PROGRESS_CANCEL, + COPYFILE2_PROGRESS_STOP, + COPYFILE2_PROGRESS_QUIET, + COPYFILE2_PROGRESS_PAUSE, +}} +ENUM!{enum COPYFILE2_COPY_PHASE { + COPYFILE2_PHASE_NONE = 0, + COPYFILE2_PHASE_PREPARE_SOURCE, + COPYFILE2_PHASE_PREPARE_DEST, + COPYFILE2_PHASE_READ_SOURCE, + COPYFILE2_PHASE_WRITE_DESTINATION, + COPYFILE2_PHASE_SERVER_COPY, + COPYFILE2_PHASE_NAMEGRAFT_COPY, + COPYFILE2_PHASE_MAX, +}} +//5129 +STRUCT!{struct COPYFILE2_MESSAGE_ChunkStarted { + dwStreamNumber: ::DWORD, + dwReserved: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliChunkNumber: ::ULARGE_INTEGER, + uliChunkSize: ::ULARGE_INTEGER, + uliStreamSize: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_ChunkFinished { + dwStreamNumber: ::DWORD, + dwFlags: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliChunkNumber: ::ULARGE_INTEGER, + uliChunkSize: ::ULARGE_INTEGER, + uliStreamSize: ::ULARGE_INTEGER, + uliStreamBytesTransferred: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, + uliTotalBytesTransferred: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_StreamStarted { + dwStreamNumber: ::DWORD, + dwReserved: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliStreamSize: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_StreamFinished { + dwStreamNumber: ::DWORD, + dwReserved: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliStreamSize: ::ULARGE_INTEGER, + uliStreamBytesTransferred: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, + uliTotalBytesTransferred: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_PollContinue { + dwReserved: ::DWORD, +}} +STRUCT!{struct COPYFILE2_MESSAGE_Error { + CopyPhase: COPYFILE2_COPY_PHASE, + dwStreamNumber: ::DWORD, + hrFailure: ::HRESULT, + dwReserved: ::DWORD, + uliChunkNumber: ::ULARGE_INTEGER, + uliStreamSize: ::ULARGE_INTEGER, + uliStreamBytesTransferred: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, + uliTotalBytesTransferred: ::ULARGE_INTEGER, +}} +#[cfg(target_arch="x86")] +STRUCT!{struct COPYFILE2_MESSAGE { + Type: COPYFILE2_MESSAGE_TYPE, + dwPadding: ::DWORD, + Info: [u64; 8], +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct COPYFILE2_MESSAGE { + Type: COPYFILE2_MESSAGE_TYPE, + dwPadding: ::DWORD, + Info: [u64; 9], +}} +UNION!{COPYFILE2_MESSAGE, Info, ChunkStarted, ChunkStarted_mut, COPYFILE2_MESSAGE_ChunkStarted} +UNION!{COPYFILE2_MESSAGE, Info, ChunkFinished, ChunkFinished_mut, COPYFILE2_MESSAGE_ChunkFinished} +UNION!{COPYFILE2_MESSAGE, Info, StreamStarted, StreamStarted_mut, COPYFILE2_MESSAGE_StreamStarted} +UNION!{COPYFILE2_MESSAGE, Info, StreamFinished, StreamFinished_mut, + COPYFILE2_MESSAGE_StreamFinished} +UNION!{COPYFILE2_MESSAGE, Info, PollContinue, PollContinue_mut, COPYFILE2_MESSAGE_PollContinue} +UNION!{COPYFILE2_MESSAGE, Info, Error, Error_mut, COPYFILE2_MESSAGE_Error} +pub type PCOPYFILE2_PROGRESS_ROUTINE = Option<unsafe extern "system" fn( + pMessage: *const COPYFILE2_MESSAGE, pvCallbackContext: ::PVOID, +) -> COPYFILE2_MESSAGE_ACTION>; +STRUCT!{nodebug struct COPYFILE2_EXTENDED_PARAMETERS { + dwSize: ::DWORD, + dwCopyFlags: ::DWORD, + pfCancel: *mut ::BOOL, + pProgressRoutine: PCOPYFILE2_PROGRESS_ROUTINE, + pvCallbackContext: ::PVOID, +}} +//5377 +pub const MOVEFILE_REPLACE_EXISTING: ::DWORD = 0x00000001; +pub const MOVEFILE_COPY_ALLOWED: ::DWORD = 0x00000002; +pub const MOVEFILE_DELAY_UNTIL_REBOOT: ::DWORD = 0x00000004; +pub const MOVEFILE_WRITE_THROUGH: ::DWORD = 0x00000008; +pub const MOVEFILE_CREATE_HARDLINK: ::DWORD = 0x00000010; +pub const MOVEFILE_FAIL_IF_NOT_TRACKABLE: ::DWORD = 0x00000020; +//7176 +pub const HW_PROFILE_GUIDLEN: usize = 39; +//pub const MAX_PROFILE_LEN: usize = 80; +pub const DOCKINFO_UNDOCKED: ::DWORD = 0x1; +pub const DOCKINFO_DOCKED: ::DWORD = 0x2; +pub const DOCKINFO_USER_SUPPLIED: ::DWORD = 0x4; +pub const DOCKINFO_USER_UNDOCKED: ::DWORD = DOCKINFO_USER_SUPPLIED | DOCKINFO_UNDOCKED; +pub const DOCKINFO_USER_DOCKED: ::DWORD = DOCKINFO_USER_SUPPLIED | DOCKINFO_DOCKED; +STRUCT!{nodebug struct HW_PROFILE_INFOA { + dwDockInfo: ::DWORD, + szHwProfileGuid: [::CHAR; HW_PROFILE_GUIDLEN], + szHwProfileName: [::CHAR; ::MAX_PROFILE_LEN], +}} +pub type LPHW_PROFILE_INFOA = *mut HW_PROFILE_INFOA; +STRUCT!{nodebug struct HW_PROFILE_INFOW { + dwDockInfo: ::DWORD, + szHwProfileGuid: [::WCHAR; HW_PROFILE_GUIDLEN], + szHwProfileName: [::WCHAR; ::MAX_PROFILE_LEN], +}} +pub type LPHW_PROFILE_INFOW = *mut HW_PROFILE_INFOW; +//7574 +STRUCT!{struct ACTCTXA { + cbSize: ::ULONG, + dwFlags: ::DWORD, + lpSource: ::LPCSTR, + wProcessorArchitecture: ::USHORT, + wLangId: ::LANGID, + lpAssemblyDirectory: ::LPCSTR, + lpResourceName: ::LPCSTR, + lpApplicationName: ::LPCSTR, + hModule: ::HMODULE, +}} +pub type PACTCTXA = *mut ACTCTXA; +STRUCT!{struct ACTCTXW { + cbSize: ::ULONG, + dwFlags: ::DWORD, + lpSource: ::LPCWSTR, + wProcessorArchitecture: ::USHORT, + wLangId: ::LANGID, + lpAssemblyDirectory: ::LPCWSTR, + lpResourceName: ::LPCWSTR, + lpApplicationName: ::LPCWSTR, + hModule: ::HMODULE, +}} +pub type PACTCTXW = *mut ACTCTXW; +pub type PCACTCTXA = *const ACTCTXA; +pub type PCACTCTXW = *const ACTCTXW; +// +pub type PUMS_CONTEXT = *mut ::c_void; +pub type PUMS_COMPLETION_LIST = *mut ::c_void; +pub type UMS_THREAD_INFO_CLASS = ::RTL_UMS_THREAD_INFO_CLASS; +pub type PUMS_THREAD_INFO_CLASS = *mut UMS_THREAD_INFO_CLASS; +pub type PUMS_SCHEDULER_ENTRY_POINT = ::PRTL_UMS_SCHEDULER_ENTRY_POINT; +STRUCT!{nodebug struct UMS_SCHEDULER_STARTUP_INFO { + UmsVersion: ::ULONG, + CompletionList: PUMS_COMPLETION_LIST, + SchedulerProc: PUMS_SCHEDULER_ENTRY_POINT, + SchedulerParam: ::PVOID, +}} +pub type PUMS_SCHEDULER_STARTUP_INFO = *mut UMS_SCHEDULER_STARTUP_INFO; +STRUCT!{struct UMS_SYSTEM_THREAD_INFORMATION { + UmsVersion: ::ULONG, + BitFields: ::ULONG, +}} +BITFIELD!(UMS_SYSTEM_THREAD_INFORMATION BitFields: ::ULONG [ + IsUmsSchedulerThread set_IsUmsSchedulerThread[0..1], + IsUmsWorkerThread set_IsUmsWorkerThread[1..2], +]); +UNION!( + UMS_SYSTEM_THREAD_INFORMATION, BitFields, ThreadUmsFlags, ThreadUmsFlags_mut, + ::ULONG +); +pub type PUMS_SYSTEM_THREAD_INFORMATION = *mut UMS_SYSTEM_THREAD_INFORMATION; +STRUCT!{struct ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA { + lpInformation: ::PVOID, + lpSectionBase: ::PVOID, + ulSectionLength: ::ULONG, + lpSectionGlobalDataBase: ::PVOID, + ulSectionGlobalDataLength: ::ULONG, +}} +pub type PACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA = + *mut ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA; +pub type PCACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA = + *const ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA; +STRUCT!{struct ACTCTX_SECTION_KEYED_DATA { + cbSize: ::ULONG, + ulDataFormatVersion: ::ULONG, + lpData: ::PVOID, + ulLength: ::ULONG, + lpSectionGlobalData: ::PVOID, + ulSectionGlobalDataLength: ::ULONG, + lpSectionBase: ::PVOID, + ulSectionTotalLength: ::ULONG, + hActCtx: ::HANDLE, + ulAssemblyRosterIndex: ::ULONG, + ulFlags: ::ULONG, + AssemblyMetadata: ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA, +}} +pub type PACTCTX_SECTION_KEYED_DATA = *mut ACTCTX_SECTION_KEYED_DATA; +pub type PCACTCTX_SECTION_KEYED_DATA = *const ACTCTX_SECTION_KEYED_DATA; +ENUM!{enum STREAM_INFO_LEVELS { + FindStreamInfoStandard, + FindStreamInfoMaxInfoLevel, +}} +ENUM!{enum PROCESS_INFORMATION_CLASS { + ProcessMemoryPriority, + ProcessInformationClassMax, +}} +ENUM!{enum DEP_SYSTEM_POLICY_TYPE { + DEPPolicyAlwaysOff = 0, + DEPPolicyAlwaysOn, + DEPPolicyOptIn, + DEPPolicyOptOut, + DEPTotalPolicyCount, +}} +ENUM!{enum PIPE_ATTRIBUTE_TYPE { + PipeAttribute, + PipeConnectionAttribute, + PipeHandleAttribute, +}} +pub type APPLICATION_RECOVERY_CALLBACK = Option<unsafe extern "system" fn( + pvParameter: ::PVOID +) -> ::DWORD>; +STRUCT!{struct SYSTEM_POWER_STATUS { + ACLineStatus: ::BYTE, + BatteryFlag: ::BYTE, + BatteryLifePercent: ::BYTE, + Reserved1: ::BYTE, + BatteryLifeTime: ::DWORD, + BatteryFullLifeTime: ::DWORD, +}} +pub type LPSYSTEM_POWER_STATUS = *mut SYSTEM_POWER_STATUS; +pub const OFS_MAXPATHNAME: usize = 128; +STRUCT!{nodebug struct OFSTRUCT { + cBytes: ::BYTE, + fFixedDisk: ::BYTE, + nErrCode: ::WORD, + Reserved1: ::WORD, + Reserved2: ::WORD, + szPathName: [::CHAR; OFS_MAXPATHNAME], +}} +pub type POFSTRUCT = *mut OFSTRUCT; +pub type LPOFSTRUCT = *mut OFSTRUCT; +ENUM!{enum FILE_ID_TYPE { + FileIdType, + ObjectIdType, + ExtendedFileIdType, + MaximumFileIdType, +}} +STRUCT!{struct FILE_ID_DESCRIPTOR { + dwSize: ::DWORD, + Type: FILE_ID_TYPE, + ObjectId: ::GUID, +}} +UNION!(FILE_ID_DESCRIPTOR, ObjectId, FileId, FileId_mut, ::LARGE_INTEGER); +UNION!(FILE_ID_DESCRIPTOR, ObjectId, ExtendedFileId, ExtendedFileId_mut, ::FILE_ID_128); +pub type LPFILE_ID_DESCRIPTOR = *mut FILE_ID_DESCRIPTOR; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/wincon.rs b/bash-5.1/vendor/winapi-0.2.8/src/wincon.rs new file mode 100644 index 0000000..23c2e74 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/wincon.rs @@ -0,0 +1,198 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This module contains the public data structures, data types, and procedures exported by the NT +//! console subsystem. +STRUCT!{struct COORD { + X: ::SHORT, + Y: ::SHORT, +}} +pub type PCOORD = *mut COORD; +STRUCT!{struct SMALL_RECT { + Left: ::SHORT, + Top: ::SHORT, + Right: ::SHORT, + Bottom: ::SHORT, +}} +pub type PSMALL_RECT = *mut SMALL_RECT; +STRUCT!{struct KEY_EVENT_RECORD { + bKeyDown: ::BOOL, + wRepeatCount: ::WORD, + wVirtualKeyCode: ::WORD, + wVirtualScanCode: ::WORD, + UnicodeChar: ::WCHAR, + dwControlKeyState: ::DWORD, +}} +UNION!{KEY_EVENT_RECORD, UnicodeChar, AsciiChar, AsciiChar_mut, ::CHAR} +pub type PKEY_EVENT_RECORD = *mut KEY_EVENT_RECORD; +pub const RIGHT_ALT_PRESSED: ::DWORD = 0x0001; +pub const LEFT_ALT_PRESSED: ::DWORD = 0x0002; +pub const RIGHT_CTRL_PRESSED: ::DWORD = 0x0004; +pub const LEFT_CTRL_PRESSED: ::DWORD = 0x0008; +pub const SHIFT_PRESSED: ::DWORD = 0x0010; +pub const NUMLOCK_ON: ::DWORD = 0x0020; +pub const SCROLLLOCK_ON: ::DWORD = 0x0040; +pub const CAPSLOCK_ON: ::DWORD = 0x0080; +pub const ENHANCED_KEY: ::DWORD = 0x0100; +pub const NLS_DBCSCHAR: ::DWORD = 0x00010000; +pub const NLS_ALPHANUMERIC: ::DWORD = 0x00000000; +pub const NLS_KATAKANA: ::DWORD = 0x00020000; +pub const NLS_HIRAGANA: ::DWORD = 0x00040000; +pub const NLS_ROMAN: ::DWORD = 0x00400000; +pub const NLS_IME_CONVERSION: ::DWORD = 0x00800000; +pub const NLS_IME_DISABLE: ::DWORD = 0x20000000; +STRUCT!{struct MOUSE_EVENT_RECORD { + dwMousePosition: COORD, + dwButtonState: ::DWORD, + dwControlKeyState: ::DWORD, + dwEventFlags: ::DWORD, +}} +pub type PMOUSE_EVENT_RECORD = *mut MOUSE_EVENT_RECORD; +pub const FROM_LEFT_1ST_BUTTON_PRESSED: ::DWORD = 0x0001; +pub const RIGHTMOST_BUTTON_PRESSED: ::DWORD = 0x0002; +pub const FROM_LEFT_2ND_BUTTON_PRESSED: ::DWORD = 0x0004; +pub const FROM_LEFT_3RD_BUTTON_PRESSED: ::DWORD = 0x0008; +pub const FROM_LEFT_4TH_BUTTON_PRESSED: ::DWORD = 0x0010; +pub const MOUSE_MOVED: ::DWORD = 0x0001; +pub const DOUBLE_CLICK: ::DWORD = 0x0002; +pub const MOUSE_WHEELED: ::DWORD = 0x0004; +pub const MOUSE_HWHEELED: ::DWORD = 0x0008; +STRUCT!{struct WINDOW_BUFFER_SIZE_RECORD { + dwSize: COORD, +}} +pub type PWINDOW_BUFFER_SIZE_RECORD = *mut WINDOW_BUFFER_SIZE_RECORD; +STRUCT!{struct MENU_EVENT_RECORD { + dwCommandId: ::UINT, +}} +pub type PMENU_EVENT_RECORD = *mut MENU_EVENT_RECORD; +STRUCT!{struct FOCUS_EVENT_RECORD { + bSetFocus: ::BOOL, +}} +pub type PFOCUS_EVENT_RECORD = *mut FOCUS_EVENT_RECORD; +STRUCT!{struct INPUT_RECORD { + EventType: ::WORD, + Event: [u32; 4], +}} +UNION!{INPUT_RECORD, Event, KeyEvent, KeyEvent_mut, KEY_EVENT_RECORD} +UNION!{INPUT_RECORD, Event, MouseEvent, MouseEvent_mut, MOUSE_EVENT_RECORD} +UNION!{INPUT_RECORD, Event, WindowBufferSizeEvent, WindowBufferSizeEvent_mut, + WINDOW_BUFFER_SIZE_RECORD} +UNION!{INPUT_RECORD, Event, MenuEvent, MenuEvent_mut, MENU_EVENT_RECORD} +UNION!{INPUT_RECORD, Event, FocusEvent, FocusEvent_mut, FOCUS_EVENT_RECORD} +pub type PINPUT_RECORD = *mut INPUT_RECORD; +pub const KEY_EVENT: ::WORD = 0x0001; +pub const MOUSE_EVENT: ::WORD = 0x0002; +pub const WINDOW_BUFFER_SIZE_EVENT: ::WORD = 0x0004; +pub const MENU_EVENT: ::WORD = 0x0008; +pub const FOCUS_EVENT: ::WORD = 0x0010; +STRUCT!{struct CHAR_INFO { + UnicodeChar: ::WCHAR, + Attributes: ::WORD, +}} +UNION!{CHAR_INFO, UnicodeChar, AsciiChar, AsciiChar_mut, ::CHAR} +pub type PCHAR_INFO = *mut CHAR_INFO; +pub const FOREGROUND_BLUE: ::DWORD = 0x0001; +pub const FOREGROUND_GREEN: ::DWORD = 0x0002; +pub const FOREGROUND_RED: ::DWORD = 0x0004; +pub const FOREGROUND_INTENSITY: ::DWORD = 0x0008; +pub const BACKGROUND_BLUE: ::DWORD = 0x0010; +pub const BACKGROUND_GREEN: ::DWORD = 0x0020; +pub const BACKGROUND_RED: ::DWORD = 0x0040; +pub const BACKGROUND_INTENSITY: ::DWORD = 0x0080; +pub const COMMON_LVB_LEADING_BYTE: ::DWORD = 0x0100; +pub const COMMON_LVB_TRAILING_BYTE: ::DWORD = 0x0200; +pub const COMMON_LVB_GRID_HORIZONTAL: ::DWORD = 0x0400; +pub const COMMON_LVB_GRID_LVERTICAL: ::DWORD = 0x0800; +pub const COMMON_LVB_GRID_RVERTICAL: ::DWORD = 0x1000; +pub const COMMON_LVB_REVERSE_VIDEO: ::DWORD = 0x4000; +pub const COMMON_LVB_UNDERSCORE: ::DWORD = 0x8000; +pub const COMMON_LVB_SBCSDBCS: ::DWORD = 0x0300; +STRUCT!{struct CONSOLE_SCREEN_BUFFER_INFO { + dwSize: COORD, + dwCursorPosition: COORD, + wAttributes: ::WORD, + srWindow: SMALL_RECT, + dwMaximumWindowSize: COORD, +}} +pub type PCONSOLE_SCREEN_BUFFER_INFO = *mut CONSOLE_SCREEN_BUFFER_INFO; +STRUCT!{struct CONSOLE_SCREEN_BUFFER_INFOEX { + cbSize: ::ULONG, + dwSize: COORD, + dwCursorPosition: COORD, + wAttributes: ::WORD, + srWindow: SMALL_RECT, + dwMaximumWindowSize: COORD, + wPopupAttributes: ::WORD, + bFullscreenSupported: ::BOOL, + ColorTable: [::COLORREF; 16], +}} +pub type PCONSOLE_SCREEN_BUFFER_INFOEX = *mut CONSOLE_SCREEN_BUFFER_INFOEX; +STRUCT!{struct CONSOLE_CURSOR_INFO { + dwSize: ::DWORD, + bVisible: ::BOOL, +}} +pub type PCONSOLE_CURSOR_INFO = *mut CONSOLE_CURSOR_INFO; +STRUCT!{struct CONSOLE_FONT_INFO { + nFont: ::DWORD, + dwFontSize: ::COORD, +}} +pub type PCONSOLE_FONT_INFO = *mut CONSOLE_FONT_INFO; +STRUCT!{struct CONSOLE_FONT_INFOEX { + cbSize: ::ULONG, + nFont: ::DWORD, + dwFontSize: COORD, + FontFamily: ::UINT, + FontWeight: ::UINT, + FaceName: [::WCHAR; ::LF_FACESIZE], +}} +pub type PCONSOLE_FONT_INFOEX = *mut CONSOLE_FONT_INFOEX; +pub const HISTORY_NO_DUP_FLAG: ::DWORD = 0x1; +STRUCT!{struct CONSOLE_HISTORY_INFO { + cbSize: ::UINT, + HistoryBufferSize: ::UINT, + NumberOfHistoryBuffers: ::UINT, + dwFlags: ::DWORD, +}} +pub type PCONSOLE_HISTORY_INFO = *mut CONSOLE_HISTORY_INFO; +STRUCT!{struct CONSOLE_SELECTION_INFO { + dwFlags: ::DWORD, + dwSelectionAnchor: COORD, + srSelection: SMALL_RECT, +}} +pub type PCONSOLE_SELECTION_INFO = *mut CONSOLE_SELECTION_INFO; +pub const CONSOLE_NO_SELECTION: ::DWORD = 0x0000; +pub const CONSOLE_SELECTION_IN_PROGRESS: ::DWORD = 0x0001; +pub const CONSOLE_SELECTION_NOT_EMPTY: ::DWORD = 0x0002; +pub const CONSOLE_MOUSE_SELECTION: ::DWORD = 0x0004; +pub const CONSOLE_MOUSE_DOWN: ::DWORD = 0x0008; +pub type PHANDLER_ROUTINE = Option<unsafe extern "system" fn(CtrlType: ::DWORD) -> ::BOOL>; +pub const CTRL_C_EVENT: ::DWORD = 0; +pub const CTRL_BREAK_EVENT: ::DWORD = 1; +pub const CTRL_CLOSE_EVENT: ::DWORD = 2; +pub const CTRL_LOGOFF_EVENT: ::DWORD = 5; +pub const CTRL_SHUTDOWN_EVENT: ::DWORD = 6; +pub const ENABLE_PROCESSED_INPUT: ::DWORD = 0x0001; +pub const ENABLE_LINE_INPUT: ::DWORD = 0x0002; +pub const ENABLE_ECHO_INPUT: ::DWORD = 0x0004; +pub const ENABLE_WINDOW_INPUT: ::DWORD = 0x0008; +pub const ENABLE_MOUSE_INPUT: ::DWORD = 0x0010; +pub const ENABLE_INSERT_MODE: ::DWORD = 0x0020; +pub const ENABLE_QUICK_EDIT_MODE: ::DWORD = 0x0040; +pub const ENABLE_EXTENDED_FLAGS: ::DWORD = 0x0080; +pub const ENABLE_AUTO_POSITION: ::DWORD = 0x0100; +pub const ENABLE_PROCESSED_OUTPUT: ::DWORD = 0x0001; +pub const ENABLE_WRAP_AT_EOL_OUTPUT: ::DWORD = 0x0002; +pub const CONSOLE_REAL_OUTPUT_HANDLE: *mut ::c_void = -2isize as *mut ::c_void; +pub const CONSOLE_REAL_INPUT_HANDLE: *mut ::c_void = -3isize as *mut ::c_void; +pub const ATTACH_PARENT_PROCESS: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct CONSOLE_READCONSOLE_CONTROL { + nLength: ::ULONG, + nInitialChars: ::ULONG, + dwCtrlWakeupMask: ::ULONG, + dwControlKeyState: ::ULONG, +}} +pub type PCONSOLE_READCONSOLE_CONTROL = *mut CONSOLE_READCONSOLE_CONTROL; +pub const CONSOLE_TEXTMODE_BUFFER: ::DWORD = 1; +pub const CONSOLE_FULLSCREEN: ::DWORD = 1; +pub const CONSOLE_FULLSCREEN_HARDWARE: ::DWORD = 2; +pub const CONSOLE_FULLSCREEN_MODE: ::DWORD = 1; +pub const CONSOLE_WINDOWED_MODE: ::DWORD = 2; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/wincred.rs b/bash-5.1/vendor/winapi-0.2.8/src/wincred.rs new file mode 100644 index 0000000..af98bd9 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/wincred.rs @@ -0,0 +1,209 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Authentication API Prototypes and Definitions +pub const NERR_BASE: ::DWORD = 2100; +pub const NERR_PasswordExpired: ::DWORD = NERR_BASE+142; +pub const CRED_MAX_STRING_LENGTH: ::DWORD = 256; +pub const CRED_MAX_USERNAME_LENGTH: ::DWORD = 256+1+256; +pub const CRED_MAX_GENERIC_TARGET_NAME_LENGTH: ::DWORD = 32767; +pub const CRED_MAX_DOMAIN_TARGET_NAME_LENGTH: ::DWORD = 256+1+80; +pub const CRED_MAX_TARGETNAME_NAMESPACE_LENGTH: ::DWORD = 256; +pub const CRED_MAX_TARGETNAME_ATTRIBUTE_LENGTH: ::DWORD = 256; +pub const CRED_MAX_VALUE_SIZE: ::DWORD = 256; +pub const CRED_MAX_ATTRIBUTES: ::DWORD = 64; +pub const CRED_LOGON_TYPES_MASK: ::DWORD = 0xF000; +pub const CRED_FLAGS_PASSWORD_FOR_CERT: ::DWORD = 0x0001; +pub const CRED_FLAGS_PROMPT_NOW: ::DWORD = 0x0002; +pub const CRED_FLAGS_USERNAME_TARGET: ::DWORD = 0x0004; +pub const CRED_FLAGS_OWF_CRED_BLOB: ::DWORD = 0x0008; +pub const CRED_FLAGS_REQUIRE_CONFIRMATION: ::DWORD = 0x0010; +pub const CRED_FLAGS_WILDCARD_MATCH: ::DWORD = 0x0020; +pub const CRED_FLAGS_VALID_FLAGS: ::DWORD = 0xF03F; +pub const CRED_FLAGS_VALID_INPUT_FLAGS: ::DWORD = 0xF01F; +pub const CRED_TYPE_GENERIC: ::DWORD = 1; +pub const CRED_TYPE_DOMAIN_PASSWORD: ::DWORD = 2; +pub const CRED_TYPE_DOMAIN_CERTIFICATE: ::DWORD = 3; +pub const CRED_TYPE_DOMAIN_VISIBLE_PASSWORD: ::DWORD = 4; +pub const CRED_TYPE_GENERIC_CERTIFICATE: ::DWORD = 5; +pub const CRED_TYPE_DOMAIN_EXTENDED: ::DWORD = 6; +pub const CRED_TYPE_MAXIMUM: ::DWORD = 7; +pub const CRED_TYPE_MAXIMUM_EX: ::DWORD = CRED_TYPE_MAXIMUM+1000; +pub const CRED_MAX_CREDENTIAL_BLOB_SIZE: ::DWORD = 5*512; +pub const CRED_PERSIST_NONE: ::DWORD = 0; +pub const CRED_PERSIST_SESSION: ::DWORD = 1; +pub const CRED_PERSIST_LOCAL_MACHINE: ::DWORD = 2; +pub const CRED_PERSIST_ENTERPRISE: ::DWORD = 3; +STRUCT!{struct CREDENTIAL_ATTRIBUTEA { + Keyword: ::LPSTR, + Flags: ::DWORD, + ValueSize: ::DWORD, + Value: ::LPBYTE, +}} +pub type PCREDENTIAL_ATTRIBUTEA = *mut CREDENTIAL_ATTRIBUTEA; +STRUCT!{struct CREDENTIAL_ATTRIBUTEW { + Keyword: ::LPWSTR, + Flags: ::DWORD, + ValueSize: ::DWORD, + Value: ::LPBYTE, +}} +pub type PCREDENTIAL_ATTRIBUTEW = *mut CREDENTIAL_ATTRIBUTEW; +STRUCT!{struct CREDENTIALA { + Flags: ::DWORD, + Type: ::DWORD, + TargetName: ::LPSTR, + Comment: ::LPSTR, + LastWritten: ::FILETIME, + CredentialBlobSize: ::DWORD, + CredentialBlob: ::LPBYTE, + Persist: ::DWORD, + AttributeCount: ::DWORD, + Attributes: PCREDENTIAL_ATTRIBUTEA, + TargetAlias: ::LPSTR, + UserName: ::LPSTR, +}} +pub type PCREDENTIALA = *mut CREDENTIALA; +STRUCT!{struct CREDENTIALW { + Flags: ::DWORD, + Type: ::DWORD, + TargetName: ::LPWSTR, + Comment: ::LPWSTR, + LastWritten: ::FILETIME, + CredentialBlobSize: ::DWORD, + CredentialBlob: ::LPBYTE, + Persist: ::DWORD, + AttributeCount: ::DWORD, + Attributes: PCREDENTIAL_ATTRIBUTEW, + TargetAlias: ::LPWSTR, + UserName: ::LPWSTR, +}} +pub type PCREDENTIALW = *mut CREDENTIALW; +pub const CRED_TI_SERVER_FORMAT_UNKNOWN: ::ULONG = 0x0001; +pub const CRED_TI_DOMAIN_FORMAT_UNKNOWN: ::ULONG = 0x0002; +pub const CRED_TI_ONLY_PASSWORD_REQUIRED: ::ULONG = 0x0004; +pub const CRED_TI_USERNAME_TARGET: ::ULONG = 0x0008; +pub const CRED_TI_CREATE_EXPLICIT_CRED: ::ULONG = 0x0010; +pub const CRED_TI_WORKGROUP_MEMBER: ::ULONG = 0x0020; +pub const CRED_TI_VALID_FLAGS: ::ULONG = 0xF07F; +STRUCT!{struct CREDENTIAL_TARGET_INFORMATIONA { + TargetName: ::LPSTR, + NetbiosServerName: ::LPSTR, + DnsServerName: ::LPSTR, + NetbiosDomainName: ::LPSTR, + DnsDomainName: ::LPSTR, + DnsTreeName: ::LPSTR, + PackageName: ::LPSTR, + Flags: ::ULONG, + CredTypeCount: ::DWORD, + CredTypes: ::LPDWORD, +}} +pub type PCREDENTIAL_TARGET_INFORMATIONA = *mut CREDENTIAL_TARGET_INFORMATIONA; +STRUCT!{struct CREDENTIAL_TARGET_INFORMATIONW { + TargetName: ::LPWSTR, + NetbiosServerName: ::LPWSTR, + DnsServerName: ::LPWSTR, + NetbiosDomainName: ::LPWSTR, + DnsDomainName: ::LPWSTR, + DnsTreeName: ::LPWSTR, + PackageName: ::LPWSTR, + Flags: ::ULONG, + CredTypeCount: ::DWORD, + CredTypes: ::LPDWORD, +}} +pub type PCREDENTIAL_TARGET_INFORMATIONW = *mut CREDENTIAL_TARGET_INFORMATIONW; +pub const CERT_HASH_LENGTH: usize = 20; +STRUCT!{struct CERT_CREDENTIAL_INFO { + cbSize: ::ULONG, + rgbHashOfCert: [::UCHAR; CERT_HASH_LENGTH], +}} +pub type PCERT_CREDENTIAL_INFO = *mut CERT_CREDENTIAL_INFO; +STRUCT!{struct USERNAME_TARGET_CREDENTIAL_INFO { + UserName: ::LPWSTR, +}} +pub type PUSERNAME_TARGET_CREDENTIAL_INFO = *mut USERNAME_TARGET_CREDENTIAL_INFO; +STRUCT!{struct BINARY_BLOB_CREDENTIAL_INFO { + cbBlob: ::ULONG, + pbBlob: ::LPBYTE, +}} +pub type PBINARY_BLOB_CREDENTIAL_INFO = *mut BINARY_BLOB_CREDENTIAL_INFO; +ENUM!{enum CRED_MARSHAL_TYPE { + CertCredential = 1, + UsernameTargetCredential, + BinaryBlobCredential, + UsernameForPackedCredentials, +}} +pub type PCRED_MARSHAL_TYPE = *mut CRED_MARSHAL_TYPE; +ENUM!{enum CRED_PROTECTION_TYPE { + CredUnprotected, + CredUserProtection, + CredTrustedProtection, +}} +pub type PCRED_PROTECTION_TYPE = *mut CRED_PROTECTION_TYPE; +pub const CRED_PACK_PROTECTED_CREDENTIALS: ::DWORD = 0x1; +pub const CRED_PACK_WOW_BUFFER: ::DWORD = 0x2; +pub const CRED_PACK_GENERIC_CREDENTIALS: ::DWORD = 0x4; +pub const CRED_PACK_ID_PROVIDER_CREDENTIALS: ::DWORD = 0x8; +STRUCT!{struct CREDUI_INFOA { + cbSize: ::DWORD, + hwndParent: ::HWND, + pszMessageText: ::PCSTR, + pszCaptionText: ::PCSTR, + hbmBanner: ::HBITMAP, +}} +pub type PCREDUI_INFOA = *mut CREDUI_INFOA; +STRUCT!{struct CREDUI_INFOW { + cbSize: ::DWORD, + hwndParent: ::HWND, + pszMessageText: ::PCWSTR, + pszCaptionText: ::PCWSTR, + hbmBanner: ::HBITMAP, +}} +pub type PCREDUI_INFOW = *mut CREDUI_INFOW; +pub const CREDUI_MAX_MESSAGE_LENGTH: ::DWORD = 1024; +pub const CREDUI_MAX_CAPTION_LENGTH: ::DWORD = 128; +pub const CREDUI_MAX_GENERIC_TARGET_LENGTH: ::DWORD = CRED_MAX_GENERIC_TARGET_NAME_LENGTH; +pub const CREDUI_MAX_DOMAIN_TARGET_LENGTH: ::DWORD = CRED_MAX_DOMAIN_TARGET_NAME_LENGTH; +pub const CREDUI_MAX_USERNAME_LENGTH: ::DWORD = CRED_MAX_USERNAME_LENGTH; +pub const CREDUI_MAX_PASSWORD_LENGTH: ::DWORD = 512 / 2; +pub const CREDUI_FLAGS_INCORRECT_PASSWORD: ::DWORD = 0x00001; +pub const CREDUI_FLAGS_DO_NOT_PERSIST: ::DWORD = 0x00002; +pub const CREDUI_FLAGS_REQUEST_ADMINISTRATOR: ::DWORD = 0x00004; +pub const CREDUI_FLAGS_EXCLUDE_CERTIFICATES: ::DWORD = 0x00008; +pub const CREDUI_FLAGS_REQUIRE_CERTIFICATE: ::DWORD = 0x00010; +pub const CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX: ::DWORD = 0x00040; +pub const CREDUI_FLAGS_ALWAYS_SHOW_UI: ::DWORD = 0x00080; +pub const CREDUI_FLAGS_REQUIRE_SMARTCARD: ::DWORD = 0x00100; +pub const CREDUI_FLAGS_PASSWORD_ONLY_OK: ::DWORD = 0x00200; +pub const CREDUI_FLAGS_VALIDATE_USERNAME: ::DWORD = 0x00400; +pub const CREDUI_FLAGS_COMPLETE_USERNAME: ::DWORD = 0x00800; +pub const CREDUI_FLAGS_PERSIST: ::DWORD = 0x01000; +pub const CREDUI_FLAGS_SERVER_CREDENTIAL: ::DWORD = 0x04000; +pub const CREDUI_FLAGS_EXPECT_CONFIRMATION: ::DWORD = 0x20000; +pub const CREDUI_FLAGS_GENERIC_CREDENTIALS: ::DWORD = 0x40000; +pub const CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS: ::DWORD = 0x80000; +pub const CREDUI_FLAGS_KEEP_USERNAME: ::DWORD = 0x100000; +pub const CREDUI_FLAGS_PROMPT_VALID: ::DWORD = CREDUI_FLAGS_INCORRECT_PASSWORD + | CREDUI_FLAGS_DO_NOT_PERSIST | CREDUI_FLAGS_REQUEST_ADMINISTRATOR + | CREDUI_FLAGS_EXCLUDE_CERTIFICATES | CREDUI_FLAGS_REQUIRE_CERTIFICATE + | CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX | CREDUI_FLAGS_ALWAYS_SHOW_UI + | CREDUI_FLAGS_REQUIRE_SMARTCARD | CREDUI_FLAGS_PASSWORD_ONLY_OK + | CREDUI_FLAGS_VALIDATE_USERNAME | CREDUI_FLAGS_COMPLETE_USERNAME | CREDUI_FLAGS_PERSIST + | CREDUI_FLAGS_SERVER_CREDENTIAL | CREDUI_FLAGS_EXPECT_CONFIRMATION + | CREDUI_FLAGS_GENERIC_CREDENTIALS | CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS + | CREDUI_FLAGS_KEEP_USERNAME; +pub const CREDUIWIN_GENERIC: ::DWORD = 0x00000001; +pub const CREDUIWIN_CHECKBOX: ::DWORD = 0x00000002; +pub const CREDUIWIN_AUTHPACKAGE_ONLY: ::DWORD = 0x00000010; +pub const CREDUIWIN_IN_CRED_ONLY: ::DWORD = 0x00000020; +pub const CREDUIWIN_ENUMERATE_ADMINS: ::DWORD = 0x00000100; +pub const CREDUIWIN_ENUMERATE_CURRENT_USER: ::DWORD = 0x00000200; +pub const CREDUIWIN_SECURE_PROMPT: ::DWORD = 0x00001000; +pub const CREDUIWIN_PREPROMPTING: ::DWORD = 0x00002000; +pub const CREDUIWIN_PACK_32_WOW: ::DWORD = 0x10000000; +pub const CREDUIWIN_VALID_FLAGS: ::DWORD = CREDUIWIN_GENERIC | CREDUIWIN_CHECKBOX + | CREDUIWIN_AUTHPACKAGE_ONLY | CREDUIWIN_IN_CRED_ONLY | CREDUIWIN_ENUMERATE_ADMINS + | CREDUIWIN_ENUMERATE_CURRENT_USER | CREDUIWIN_SECURE_PROMPT | CREDUIWIN_PREPROMPTING + | CREDUIWIN_PACK_32_WOW; +pub const CRED_PRESERVE_CREDENTIAL_BLOB: ::DWORD = 0x1; +pub const CRED_ENUMERATE_ALL_CREDENTIALS: ::DWORD = 0x1; +pub const CRED_CACHE_TARGET_INFORMATION: ::DWORD = 0x1; +pub const CRED_ALLOW_NAME_RESOLUTION: ::DWORD = 0x1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/wincrypt.rs b/bash-5.1/vendor/winapi-0.2.8/src/wincrypt.rs new file mode 100644 index 0000000..5b3e748 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/wincrypt.rs @@ -0,0 +1,2206 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Cryptographic API Prototypes and Definitions +//108 +pub const ALG_CLASS_ANY: ALG_ID = 0; +pub const ALG_CLASS_SIGNATURE: ALG_ID = 1 << 13; +pub const ALG_CLASS_MSG_ENCRYPT: ALG_ID = 2 << 13; +pub const ALG_CLASS_DATA_ENCRYPT: ALG_ID = 3 << 13; +pub const ALG_CLASS_HASH: ALG_ID = 4 << 13; +pub const ALG_CLASS_KEY_EXCHANGE: ALG_ID = 5 << 13; +pub const ALG_CLASS_ALL: ALG_ID = 7 << 13; +pub const ALG_TYPE_ANY: ALG_ID = 0; +pub const ALG_TYPE_DSS: ALG_ID = 1 << 9; +pub const ALG_TYPE_RSA: ALG_ID = 2 << 9; +pub const ALG_TYPE_BLOCK: ALG_ID = 3 << 9; +pub const ALG_TYPE_STREAM: ALG_ID = 4 << 9; +pub const ALG_TYPE_DH: ALG_ID = 5 << 9; +pub const ALG_TYPE_SECURECHANNEL: ALG_ID = 6 << 9; +pub const ALG_SID_ANY: ALG_ID = 0; +pub const ALG_SID_RSA_ANY: ALG_ID = 0; +pub const ALG_SID_RSA_PKCS: ALG_ID = 1; +pub const ALG_SID_RSA_MSATWORK: ALG_ID = 2; +pub const ALG_SID_RSA_ENTRUST: ALG_ID = 3; +pub const ALG_SID_RSA_PGP: ALG_ID = 4; +pub const ALG_SID_DSS_ANY: ALG_ID = 0; +pub const ALG_SID_DSS_PKCS: ALG_ID = 1; +pub const ALG_SID_DSS_DMS: ALG_ID = 2; +pub const ALG_SID_ECDSA: ALG_ID = 3; +pub const ALG_SID_DES: ALG_ID = 1; +pub const ALG_SID_3DES: ALG_ID = 3; +pub const ALG_SID_DESX: ALG_ID = 4; +pub const ALG_SID_IDEA: ALG_ID = 5; +pub const ALG_SID_CAST: ALG_ID = 6; +pub const ALG_SID_SAFERSK64: ALG_ID = 7; +pub const ALG_SID_SAFERSK128: ALG_ID = 8; +pub const ALG_SID_3DES_112: ALG_ID = 9; +pub const ALG_SID_CYLINK_MEK: ALG_ID = 12; +pub const ALG_SID_RC5: ALG_ID = 13; +pub const ALG_SID_AES_128: ALG_ID = 14; +pub const ALG_SID_AES_192: ALG_ID = 15; +pub const ALG_SID_AES_256: ALG_ID = 16; +pub const ALG_SID_AES: ALG_ID = 17; +pub const ALG_SID_SKIPJACK: ALG_ID = 10; +pub const ALG_SID_TEK: ALG_ID = 11; +pub const CRYPT_MODE_CBCI: ALG_ID = 6; +pub const CRYPT_MODE_CFBP: ALG_ID = 7; +pub const CRYPT_MODE_OFBP: ALG_ID = 8; +pub const CRYPT_MODE_CBCOFM: ALG_ID = 9; +pub const CRYPT_MODE_CBCOFMI: ALG_ID = 10; +pub const ALG_SID_RC2: ALG_ID = 2; +pub const ALG_SID_RC4: ALG_ID = 1; +pub const ALG_SID_SEAL: ALG_ID = 2; +pub const ALG_SID_DH_SANDF: ALG_ID = 1; +pub const ALG_SID_DH_EPHEM: ALG_ID = 2; +pub const ALG_SID_AGREED_KEY_ANY: ALG_ID = 3; +pub const ALG_SID_KEA: ALG_ID = 4; +pub const ALG_SID_ECDH: ALG_ID = 5; +pub const ALG_SID_MD2: ALG_ID = 1; +pub const ALG_SID_MD4: ALG_ID = 2; +pub const ALG_SID_MD5: ALG_ID = 3; +pub const ALG_SID_SHA: ALG_ID = 4; +pub const ALG_SID_SHA1: ALG_ID = 4; +pub const ALG_SID_MAC: ALG_ID = 5; +pub const ALG_SID_RIPEMD: ALG_ID = 6; +pub const ALG_SID_RIPEMD160: ALG_ID = 7; +pub const ALG_SID_SSL3SHAMD5: ALG_ID = 8; +pub const ALG_SID_HMAC: ALG_ID = 9; +pub const ALG_SID_TLS1PRF: ALG_ID = 10; +pub const ALG_SID_HASH_REPLACE_OWF: ALG_ID = 11; +pub const ALG_SID_SHA_256: ALG_ID = 12; +pub const ALG_SID_SHA_384: ALG_ID = 13; +pub const ALG_SID_SHA_512: ALG_ID = 14; +pub const ALG_SID_SSL3_MASTER: ALG_ID = 1; +pub const ALG_SID_SCHANNEL_MASTER_HASH: ALG_ID = 2; +pub const ALG_SID_SCHANNEL_MAC_KEY: ALG_ID = 3; +pub const ALG_SID_PCT1_MASTER: ALG_ID = 4; +pub const ALG_SID_SSL2_MASTER: ALG_ID = 5; +pub const ALG_SID_TLS1_MASTER: ALG_ID = 6; +pub const ALG_SID_SCHANNEL_ENC_KEY: ALG_ID = 7; +pub const ALG_SID_ECMQV: ALG_ID = 1; +pub const ALG_SID_EXAMPLE: ALG_ID = 80; +pub type ALG_ID = ::c_uint; +pub const CALG_MD2: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2; +pub const CALG_MD4: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4; +pub const CALG_MD5: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5; +pub const CALG_SHA: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA; +pub const CALG_SHA1: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1; +pub const CALG_MAC: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MAC; +pub const CALG_RSA_SIGN: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | ALG_SID_RSA_ANY; +pub const CALG_DSS_SIGN: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_DSS_ANY; +pub const CALG_NO_SIGN: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_ANY | ALG_SID_ANY; +pub const CALG_RSA_KEYX: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RSA | ALG_SID_RSA_ANY; +pub const CALG_DES: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_DES; +pub const CALG_3DES_112: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_3DES_112; +pub const CALG_3DES: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_3DES; +pub const CALG_DESX: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_DESX; +pub const CALG_RC2: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC2; +pub const CALG_RC4: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_RC4; +pub const CALG_SEAL: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_SEAL; +pub const CALG_DH_SF: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_DH_SANDF; +pub const CALG_DH_EPHEM: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_DH_EPHEM; +pub const CALG_AGREEDKEY_ANY: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH + | ALG_SID_AGREED_KEY_ANY; +pub const CALG_KEA_KEYX: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_KEA; +pub const CALG_HUGHES_MD5: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_MD5; +pub const CALG_SKIPJACK: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_SKIPJACK; +pub const CALG_TEK: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_TEK; +pub const CALG_CYLINK_MEK: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_CYLINK_MEK; +pub const CALG_SSL3_SHAMD5: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5; +pub const CALG_SSL3_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SSL3_MASTER; +pub const CALG_SCHANNEL_MASTER_HASH: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SCHANNEL_MASTER_HASH; +pub const CALG_SCHANNEL_MAC_KEY: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SCHANNEL_MAC_KEY; +pub const CALG_SCHANNEL_ENC_KEY: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SCHANNEL_ENC_KEY; +pub const CALG_PCT1_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_PCT1_MASTER; +pub const CALG_SSL2_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SSL2_MASTER; +pub const CALG_TLS1_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_TLS1_MASTER; +pub const CALG_RC5: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC5; +pub const CALG_HMAC: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HMAC; +pub const CALG_TLS1PRF: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_TLS1PRF; +pub const CALG_HASH_REPLACE_OWF: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HASH_REPLACE_OWF; +pub const CALG_AES_128: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_128; +pub const CALG_AES_192: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_192; +pub const CALG_AES_256: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_256; +pub const CALG_AES: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES; +pub const CALG_SHA_256: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256; +pub const CALG_SHA_384: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384; +pub const CALG_SHA_512: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512; +pub const CALG_ECDH: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_ECDH; +pub const CALG_ECMQV: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_ECMQV; +pub const CALG_ECDSA: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_ECDSA; +pub type HCRYPTPROV = ::ULONG_PTR; +pub type HCRYPTKEY = ::ULONG_PTR; +pub type HCRYPTHASH = ::ULONG_PTR; +pub const CRYPT_VERIFYCONTEXT: ::DWORD = 0xF0000000; +pub const CRYPT_NEWKEYSET: ::DWORD = 0x00000008; +pub const CRYPT_DELETEKEYSET: ::DWORD = 0x00000010; +pub const CRYPT_MACHINE_KEYSET: ::DWORD = 0x00000020; +pub const CRYPT_SILENT: ::DWORD = 0x00000040; +pub const CRYPT_DEFAULT_CONTAINER_OPTIONAL: ::DWORD = 0x00000080; +pub const CRYPT_EXPORTABLE: ::DWORD = 0x00000001; +pub const CRYPT_USER_PROTECTED: ::DWORD = 0x00000002; +pub const CRYPT_CREATE_SALT: ::DWORD = 0x00000004; +pub const CRYPT_UPDATE_KEY: ::DWORD = 0x00000008; +pub const CRYPT_NO_SALT: ::DWORD = 0x00000010; +pub const CRYPT_PREGEN: ::DWORD = 0x00000040; +pub const CRYPT_RECIPIENT: ::DWORD = 0x00000010; +pub const CRYPT_INITIATOR: ::DWORD = 0x00000040; +pub const CRYPT_ONLINE: ::DWORD = 0x00000080; +pub const CRYPT_SF: ::DWORD = 0x00000100; +pub const CRYPT_CREATE_IV: ::DWORD = 0x00000200; +pub const CRYPT_KEK: ::DWORD = 0x00000400; +pub const CRYPT_DATA_KEY: ::DWORD = 0x00000800; +pub const CRYPT_VOLATILE: ::DWORD = 0x00001000; +pub const CRYPT_SGCKEY: ::DWORD = 0x00002000; +pub const CRYPT_USER_PROTECTED_STRONG: ::DWORD = 0x00100000; +pub const CRYPT_ARCHIVABLE: ::DWORD = 0x00004000; +pub const CRYPT_FORCE_KEY_PROTECTION_HIGH: ::DWORD = 0x00008000; +pub const RSA1024BIT_KEY: ::DWORD = 0x04000000; +pub const CRYPT_SERVER: ::DWORD = 0x00000400; +pub const KEY_LENGTH_MASK: ::DWORD = 0xFFFF0000; +pub const CRYPT_Y_ONLY: ::DWORD = 0x00000001; +pub const CRYPT_SSL2_FALLBACK: ::DWORD = 0x00000002; +pub const CRYPT_DESTROYKEY: ::DWORD = 0x00000004; +pub const CRYPT_OAEP: ::DWORD = 0x00000040; +pub const CRYPT_BLOB_VER3: ::DWORD = 0x00000080; +pub const CRYPT_IPSEC_HMAC_KEY: ::DWORD = 0x00000100; +pub const CRYPT_DECRYPT_RSA_NO_PADDING_CHECK: ::DWORD = 0x00000020; +pub const CRYPT_SECRETDIGEST: ::DWORD = 0x00000001; +pub const CRYPT_OWF_REPL_LM_HASH: ::DWORD = 0x00000001; +pub const CRYPT_LITTLE_ENDIAN: ::DWORD = 0x00000001; +pub const CRYPT_NOHASHOID: ::DWORD = 0x00000001; +pub const CRYPT_TYPE2_FORMAT: ::DWORD = 0x00000002; +pub const CRYPT_X931_FORMAT: ::DWORD = 0x00000004; +pub const CRYPT_MACHINE_DEFAULT: ::DWORD = 0x00000001; +pub const CRYPT_USER_DEFAULT: ::DWORD = 0x00000002; +pub const CRYPT_DELETE_DEFAULT: ::DWORD = 0x00000004; +pub const SIMPLEBLOB: ::DWORD = 0x1; +pub const PUBLICKEYBLOB: ::DWORD = 0x6; +pub const PRIVATEKEYBLOB: ::DWORD = 0x7; +pub const PLAINTEXTKEYBLOB: ::DWORD = 0x8; +pub const OPAQUEKEYBLOB: ::DWORD = 0x9; +pub const PUBLICKEYBLOBEX: ::DWORD = 0xA; +pub const SYMMETRICWRAPKEYBLOB: ::DWORD = 0xB; +pub const KEYSTATEBLOB: ::DWORD = 0xC; +pub const AT_KEYEXCHANGE: ::DWORD = 1; +pub const AT_SIGNATURE: ::DWORD = 2; +pub const CRYPT_USERDATA: ::DWORD = 1; +pub const KP_IV: ::DWORD = 1; +pub const KP_SALT: ::DWORD = 2; +pub const KP_PADDING: ::DWORD = 3; +pub const KP_MODE: ::DWORD = 4; +pub const KP_MODE_BITS: ::DWORD = 5; +pub const KP_PERMISSIONS: ::DWORD = 6; +pub const KP_ALGID: ::DWORD = 7; +pub const KP_BLOCKLEN: ::DWORD = 8; +pub const KP_KEYLEN: ::DWORD = 9; +pub const KP_SALT_EX: ::DWORD = 10; +pub const KP_P: ::DWORD = 11; +pub const KP_G: ::DWORD = 12; +pub const KP_Q: ::DWORD = 13; +pub const KP_X: ::DWORD = 14; +pub const KP_Y: ::DWORD = 15; +pub const KP_RA: ::DWORD = 16; +pub const KP_RB: ::DWORD = 17; +pub const KP_INFO: ::DWORD = 18; +pub const KP_EFFECTIVE_KEYLEN: ::DWORD = 19; +pub const KP_SCHANNEL_ALG: ::DWORD = 20; +pub const KP_CLIENT_RANDOM: ::DWORD = 21; +pub const KP_SERVER_RANDOM: ::DWORD = 22; +pub const KP_RP: ::DWORD = 23; +pub const KP_PRECOMP_MD5: ::DWORD = 24; +pub const KP_PRECOMP_SHA: ::DWORD = 25; +pub const KP_CERTIFICATE: ::DWORD = 26; +pub const KP_CLEAR_KEY: ::DWORD = 27; +pub const KP_PUB_EX_LEN: ::DWORD = 28; +pub const KP_PUB_EX_VAL: ::DWORD = 29; +pub const KP_KEYVAL: ::DWORD = 30; +pub const KP_ADMIN_PIN: ::DWORD = 31; +pub const KP_KEYEXCHANGE_PIN: ::DWORD = 32; +pub const KP_SIGNATURE_PIN: ::DWORD = 33; +pub const KP_PREHASH: ::DWORD = 34; +pub const KP_ROUNDS: ::DWORD = 35; +pub const KP_OAEP_PARAMS: ::DWORD = 36; +pub const KP_CMS_KEY_INFO: ::DWORD = 37; +pub const KP_CMS_DH_KEY_INFO: ::DWORD = 38; +pub const KP_PUB_PARAMS: ::DWORD = 39; +pub const KP_VERIFY_PARAMS: ::DWORD = 40; +pub const KP_HIGHEST_VERSION: ::DWORD = 41; +pub const KP_GET_USE_COUNT: ::DWORD = 42; +pub const KP_PIN_ID: ::DWORD = 43; +pub const KP_PIN_INFO: ::DWORD = 44; +pub const PKCS5_PADDING: ::DWORD = 1; +pub const RANDOM_PADDING: ::DWORD = 2; +pub const ZERO_PADDING: ::DWORD = 3; +pub const CRYPT_MODE_CBC: ::DWORD = 1; +pub const CRYPT_MODE_ECB: ::DWORD = 2; +pub const CRYPT_MODE_OFB: ::DWORD = 3; +pub const CRYPT_MODE_CFB: ::DWORD = 4; +pub const CRYPT_MODE_CTS: ::DWORD = 5; +pub const CRYPT_ENCRYPT: ::DWORD = 0x0001; +pub const CRYPT_DECRYPT: ::DWORD = 0x0002; +pub const CRYPT_EXPORT: ::DWORD = 0x0004; +pub const CRYPT_READ: ::DWORD = 0x0008; +pub const CRYPT_WRITE: ::DWORD = 0x0010; +pub const CRYPT_MAC: ::DWORD = 0x0020; +pub const CRYPT_EXPORT_KEY: ::DWORD = 0x0040; +pub const CRYPT_IMPORT_KEY: ::DWORD = 0x0080; +pub const CRYPT_ARCHIVE: ::DWORD = 0x0100; +pub const HP_ALGID: ::DWORD = 0x0001; +pub const HP_HASHVAL: ::DWORD = 0x0002; +pub const HP_HASHSIZE: ::DWORD = 0x0004; +pub const HP_HMAC_INFO: ::DWORD = 0x0005; +pub const HP_TLS1PRF_LABEL: ::DWORD = 0x0006; +pub const HP_TLS1PRF_SEED: ::DWORD = 0x0007; +pub const CRYPT_FAILED: ::BOOL = ::FALSE; +pub const CRYPT_SUCCEED: ::BOOL = ::TRUE; +pub const PP_ENUMALGS: ::DWORD = 1; +pub const PP_ENUMCONTAINERS: ::DWORD = 2; +pub const PP_IMPTYPE: ::DWORD = 3; +pub const PP_NAME: ::DWORD = 4; +pub const PP_VERSION: ::DWORD = 5; +pub const PP_CONTAINER: ::DWORD = 6; +pub const PP_CHANGE_PASSWORD: ::DWORD = 7; +pub const PP_KEYSET_SEC_DESCR: ::DWORD = 8; +pub const PP_CERTCHAIN: ::DWORD = 9; +pub const PP_KEY_TYPE_SUBTYPE: ::DWORD = 10; +pub const PP_PROVTYPE: ::DWORD = 16; +pub const PP_KEYSTORAGE: ::DWORD = 17; +pub const PP_APPLI_CERT: ::DWORD = 18; +pub const PP_SYM_KEYSIZE: ::DWORD = 19; +pub const PP_SESSION_KEYSIZE: ::DWORD = 20; +pub const PP_UI_PROMPT: ::DWORD = 21; +pub const PP_ENUMALGS_EX: ::DWORD = 22; +pub const PP_ENUMMANDROOTS: ::DWORD = 25; +pub const PP_ENUMELECTROOTS: ::DWORD = 26; +pub const PP_KEYSET_TYPE: ::DWORD = 27; +pub const PP_ADMIN_PIN: ::DWORD = 31; +pub const PP_KEYEXCHANGE_PIN: ::DWORD = 32; +pub const PP_SIGNATURE_PIN: ::DWORD = 33; +pub const PP_SIG_KEYSIZE_INC: ::DWORD = 34; +pub const PP_KEYX_KEYSIZE_INC: ::DWORD = 35; +pub const PP_UNIQUE_CONTAINER: ::DWORD = 36; +pub const PP_SGC_INFO: ::DWORD = 37; +pub const PP_USE_HARDWARE_RNG: ::DWORD = 38; +pub const PP_KEYSPEC: ::DWORD = 39; +pub const PP_ENUMEX_SIGNING_PROT: ::DWORD = 40; +pub const PP_CRYPT_COUNT_KEY_USE: ::DWORD = 41; +pub const PP_USER_CERTSTORE: ::DWORD = 42; +pub const PP_SMARTCARD_READER: ::DWORD = 43; +pub const PP_SMARTCARD_GUID: ::DWORD = 45; +pub const PP_ROOT_CERTSTORE: ::DWORD = 46; +pub const PP_SMARTCARD_READER_ICON: ::DWORD = 47; +pub const CRYPT_FIRST: ::DWORD = 1; +pub const CRYPT_NEXT: ::DWORD = 2; +pub const CRYPT_SGC_ENUM: ::DWORD = 4; +pub const CRYPT_IMPL_HARDWARE: ::DWORD = 1; +pub const CRYPT_IMPL_SOFTWARE: ::DWORD = 2; +pub const CRYPT_IMPL_MIXED: ::DWORD = 3; +pub const CRYPT_IMPL_UNKNOWN: ::DWORD = 4; +pub const CRYPT_IMPL_REMOVABLE: ::DWORD = 8; +pub const CRYPT_SEC_DESCR: ::DWORD = 0x00000001; +pub const CRYPT_PSTORE: ::DWORD = 0x00000002; +pub const CRYPT_UI_PROMPT: ::DWORD = 0x00000004; +pub const CRYPT_FLAG_PCT1: ::DWORD = 0x0001; +pub const CRYPT_FLAG_SSL2: ::DWORD = 0x0002; +pub const CRYPT_FLAG_SSL3: ::DWORD = 0x0004; +pub const CRYPT_FLAG_TLS1: ::DWORD = 0x0008; +pub const CRYPT_FLAG_IPSEC: ::DWORD = 0x0010; +pub const CRYPT_FLAG_SIGNING: ::DWORD = 0x0020; +pub const CRYPT_SGC: ::DWORD = 0x0001; +pub const CRYPT_FASTSGC: ::DWORD = 0x0002; +pub const PP_CLIENT_HWND: ::DWORD = 1; +pub const PP_CONTEXT_INFO: ::DWORD = 11; +pub const PP_KEYEXCHANGE_KEYSIZE: ::DWORD = 12; +pub const PP_SIGNATURE_KEYSIZE: ::DWORD = 13; +pub const PP_KEYEXCHANGE_ALG: ::DWORD = 14; +pub const PP_SIGNATURE_ALG: ::DWORD = 15; +pub const PP_DELETEKEY: ::DWORD = 24; +pub const PP_PIN_PROMPT_STRING: ::DWORD = 44; +pub const PP_SECURE_KEYEXCHANGE_PIN: ::DWORD = 47; +pub const PP_SECURE_SIGNATURE_PIN: ::DWORD = 48; +pub const PROV_RSA_FULL: ::DWORD = 1; +pub const PROV_RSA_SIG: ::DWORD = 2; +pub const PROV_DSS: ::DWORD = 3; +pub const PROV_FORTEZZA: ::DWORD = 4; +pub const PROV_MS_EXCHANGE: ::DWORD = 5; +pub const PROV_SSL: ::DWORD = 6; +pub const PROV_RSA_SCHANNEL: ::DWORD = 12; +pub const PROV_DSS_DH: ::DWORD = 13; +pub const PROV_EC_ECDSA_SIG: ::DWORD = 14; +pub const PROV_EC_ECNRA_SIG: ::DWORD = 15; +pub const PROV_EC_ECDSA_FULL: ::DWORD = 16; +pub const PROV_EC_ECNRA_FULL: ::DWORD = 17; +pub const PROV_DH_SCHANNEL: ::DWORD = 18; +pub const PROV_SPYRUS_LYNKS: ::DWORD = 20; +pub const PROV_RNG: ::DWORD = 21; +pub const PROV_INTEL_SEC: ::DWORD = 22; +pub const PROV_REPLACE_OWF: ::DWORD = 23; +pub const PROV_RSA_AES: ::DWORD = 24; +pub const MS_DEF_PROV: &'static str = "Microsoft Base Cryptographic Provider v1.0"; +pub const MS_ENHANCED_PROV: &'static str = "Microsoft Enhanced Cryptographic Provider v1.0"; +pub const MS_STRONG_PROV: &'static str = "Microsoft Strong Cryptographic Provider"; +pub const MS_DEF_RSA_SIG_PROV: &'static str = "Microsoft RSA Signature Cryptographic Provider"; +pub const MS_DEF_RSA_SCHANNEL_PROV: &'static str = "Microsoft RSA SChannel Cryptographic Provider"; +pub const MS_DEF_DSS_PROV: &'static str = "Microsoft Base DSS Cryptographic Provider"; +pub const MS_DEF_DSS_DH_PROV: &'static str = + "Microsoft Base DSS and Diffie-Hellman Cryptographic Provider"; +pub const MS_ENH_DSS_DH_PROV: &'static str = + "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"; +pub const MS_DEF_DH_SCHANNEL_PROV: &'static str = "Microsoft DH SChannel Cryptographic Provider"; +pub const MS_SCARD_PROV: &'static str = "Microsoft Base Smart Card Crypto Provider"; +pub const MS_ENH_RSA_AES_PROV: &'static str = + "Microsoft Enhanced RSA and AES Cryptographic Provider"; +pub const MS_ENH_RSA_AES_PROV_XP: &'static str = + "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"; +pub const MAXUIDLEN: usize = 64; +pub const EXPO_OFFLOAD_REG_VALUE: &'static str = "ExpoOffload"; +pub const EXPO_OFFLOAD_FUNC_NAME: &'static str = "OffloadModExpo"; +pub const szKEY_CRYPTOAPI_PRIVATE_KEY_OPTIONS: &'static str = + "Software\\Policies\\Microsoft\\Cryptography"; +pub const szKEY_CACHE_ENABLED: &'static str = "CachePrivateKeys"; +pub const szKEY_CACHE_SECONDS: &'static str = "PrivateKeyLifetimeSeconds"; +pub const szPRIV_KEY_CACHE_MAX_ITEMS: &'static str = "PrivKeyCacheMaxItems"; +pub const cPRIV_KEY_CACHE_MAX_ITEMS_DEFAULT: ::DWORD = 20; +pub const szPRIV_KEY_CACHE_PURGE_INTERVAL_SECONDS: &'static str = + "PrivKeyCachePurgeIntervalSeconds"; +pub const cPRIV_KEY_CACHE_PURGE_INTERVAL_SECONDS_DEFAULT: ::DWORD = 86400; +pub const CUR_BLOB_VERSION: ::DWORD = 2; +STRUCT!{struct CMS_KEY_INFO { + dwVersion: ::DWORD, + Algid: ALG_ID, + pbOID: *mut ::BYTE, + cbOID: ::DWORD, +}} +pub type PCMS_KEY_INFO = *mut CMS_KEY_INFO; +STRUCT!{struct HMAC_INFO { + HashAlgid: ALG_ID, + pbInnerString: *mut ::BYTE, + cbInnerString: ::DWORD, + pbOuterString: *mut ::BYTE, + cbOuterString: ::DWORD, +}} +pub type PHMAC_INFO = *mut HMAC_INFO; +STRUCT!{struct SCHANNEL_ALG { + dwUse: ::DWORD, + Algid: ALG_ID, + cBits: ::DWORD, + dwFlags: ::DWORD, + dwReserved: ::DWORD, +}} +pub type PSCHANNEL_ALG = *mut SCHANNEL_ALG; +pub const SCHANNEL_MAC_KEY: ::DWORD = 0x00000000; +pub const SCHANNEL_ENC_KEY: ::DWORD = 0x00000001; +pub const INTERNATIONAL_USAGE: ::DWORD = 0x00000001; +STRUCT!{struct PROV_ENUMALGS { + aiAlgid: ALG_ID, + dwBitLen: ::DWORD, + dwNameLen: ::DWORD, + szName: [::CHAR; 20], +}} +STRUCT!{nodebug struct PROV_ENUMALGS_EX { + aiAlgid: ALG_ID, + dwDefaultLen: ::DWORD, + dwMinLen: ::DWORD, + dwMaxLen: ::DWORD, + dwProtocols: ::DWORD, + dwNameLen: ::DWORD, + szName: [::CHAR; 20], + dwLongNameLen: ::DWORD, + szLongName: [::CHAR; 40], +}} +STRUCT!{struct BLOBHEADER { + bType: ::BYTE, + bVersion: ::BYTE, + reserved: ::WORD, + aiKeyAlg: ::ALG_ID, +}} +pub type PUBLICKEYSTRUC = BLOBHEADER; +STRUCT!{struct RSAPUBKEY { + magic: ::DWORD, + bitlen: ::DWORD, + pubexp: ::DWORD, +}} +STRUCT!{struct DHPUBKEY { + magic: ::DWORD, + bitlen: ::DWORD, +}} +pub type DSSPUBKEY = DHPUBKEY; +pub type KEAPUBKEY = DHPUBKEY; +pub type TEKPUBKEY = DHPUBKEY; +STRUCT!{struct DSSSEED { + counter: ::DWORD, + seed: [::BYTE; 20], +}} +STRUCT!{struct DHPUBKEY_VER3 { + magic: ::DWORD, + bitlenP: ::DWORD, + bitlenQ: ::DWORD, + bitlenJ: ::DWORD, + DSSSeed: DSSSEED, +}} +pub type DSSPUBKEY_VER3 = DHPUBKEY_VER3; +STRUCT!{struct DHPRIVKEY_VER3 { + magic: ::DWORD, + bitlenP: ::DWORD, + bitlenQ: ::DWORD, + bitlenJ: ::DWORD, + bitlenX: ::DWORD, + DSSSeed: DSSSEED, +}} +pub type DSSPRIVKEY_VER3 = DHPRIVKEY_VER3; +STRUCT!{struct KEY_TYPE_SUBTYPE { + dwKeySpec: ::DWORD, + Type: ::GUID, + Subtype: ::GUID, +}} +pub type PKEY_TYPE_SUBTYPE = *mut KEY_TYPE_SUBTYPE; +STRUCT!{nodebug struct CERT_FORTEZZA_DATA_PROP { + SerialNumber: [::c_uchar; 8], + CertIndex: ::c_int, + CertLabel: [::c_uchar; 36], +}} +STRUCT!{nodebug struct CRYPT_RC4_KEY_STATE { + Key: [::c_uchar; 16], + SBox: [::c_uchar; 256], + i: ::c_uchar, + j: ::c_uchar, +}} +pub type PCRYPT_RC4_KEY_STATE = *mut CRYPT_RC4_KEY_STATE; +STRUCT!{struct CRYPT_DES_KEY_STATE { + Key: [::c_uchar; 8], + IV: [::c_uchar; 8], + Feedback: [::c_uchar; 8], +}} +pub type PCRYPT_DES_KEY_STATE = *mut CRYPT_DES_KEY_STATE; +STRUCT!{struct CRYPT_3DES_KEY_STATE { + Key: [::c_uchar; 24], + IV: [::c_uchar; 8], + Feedback: [::c_uchar; 8], +}} +pub type PCRYPT_3DES_KEY_STATE = *mut CRYPT_3DES_KEY_STATE; +STRUCT!{struct CRYPT_AES_128_KEY_STATE { + Key: [::c_uchar; 16], + IV: [::c_uchar; 16], + EncryptionState: [[::c_uchar; 16]; 11], + DecryptionState: [[::c_uchar; 16]; 11], + Feedback: [::c_uchar; 16], +}} +pub type PCRYPT_AES_128_KEY_STATE = *mut CRYPT_AES_128_KEY_STATE; +STRUCT!{struct CRYPT_AES_256_KEY_STATE { + Key: [::c_uchar; 32], + IV: [::c_uchar; 16], + EncryptionState: [[::c_uchar; 16]; 15], + DecryptionState: [[::c_uchar; 16]; 15], + Feedback: [::c_uchar; 16], +}} +pub type PCRYPT_AES_256_KEY_STATE = *mut CRYPT_AES_256_KEY_STATE; +STRUCT!{struct CRYPTOAPI_BLOB { + cbData: ::DWORD, + pbData: *mut ::BYTE, +}} +pub type CRYPT_INTEGER_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_INTEGER_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_UINT_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_UINT_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_OBJID_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_OBJID_BLOB = *mut CRYPTOAPI_BLOB; +pub type CERT_NAME_BLOB = CRYPTOAPI_BLOB; +pub type PCERT_NAME_BLOB = *mut CRYPTOAPI_BLOB; +pub type CERT_RDN_VALUE_BLOB = CRYPTOAPI_BLOB; +pub type PCERT_RDN_VALUE_BLOB = *mut CRYPTOAPI_BLOB; +pub type CERT_BLOB = CRYPTOAPI_BLOB; +pub type PCERT_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRL_BLOB = CRYPTOAPI_BLOB; +pub type PCRL_BLOB = *mut CRYPTOAPI_BLOB; +pub type DATA_BLOB = CRYPTOAPI_BLOB; +pub type PDATA_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_DATA_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_DATA_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_HASH_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_HASH_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_DIGEST_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_DIGEST_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_DER_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_DER_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_ATTR_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_ATTR_BLOB = *mut CRYPTOAPI_BLOB; +STRUCT!{struct CMS_DH_KEY_INFO { + dwVersion: ::DWORD, + Algid: ALG_ID, + pszContentEncObjId: ::LPSTR, + PubInfo: CRYPT_DATA_BLOB, + pReserved: *mut ::c_void, +}} +pub type PCMS_DH_KEY_INFO = *mut CMS_DH_KEY_INFO; +pub type HCRYPTPROV_OR_NCRYPT_KEY_HANDLE = ::ULONG_PTR; +pub type HCRYPTPROV_LEGACY = ::ULONG_PTR; +STRUCT!{struct CRYPT_BIT_BLOB { + cbData: ::DWORD, + pbData: *mut ::BYTE, + cUnusedBits: ::DWORD, +}} +pub type PCRYPT_BIT_BLOB = *mut CRYPT_BIT_BLOB; +STRUCT!{struct CRYPT_ALGORITHM_IDENTIFIER { + pszObjId: ::LPSTR, + Parameters: CRYPT_OBJID_BLOB, +}} +pub type PCRYPT_ALGORITHM_IDENTIFIER = *mut CRYPT_ALGORITHM_IDENTIFIER; +pub const szOID_RSA: &'static str = "1.2.840.113549"; +pub const szOID_PKCS: &'static str = "1.2.840.113549.1"; +pub const szOID_RSA_HASH: &'static str = "1.2.840.113549.2"; +pub const szOID_RSA_ENCRYPT: &'static str = "1.2.840.113549.3"; +pub const szOID_PKCS_1: &'static str = "1.2.840.113549.1.1"; +pub const szOID_PKCS_2: &'static str = "1.2.840.113549.1.2"; +pub const szOID_PKCS_3: &'static str = "1.2.840.113549.1.3"; +pub const szOID_PKCS_4: &'static str = "1.2.840.113549.1.4"; +pub const szOID_PKCS_5: &'static str = "1.2.840.113549.1.5"; +pub const szOID_PKCS_6: &'static str = "1.2.840.113549.1.6"; +pub const szOID_PKCS_7: &'static str = "1.2.840.113549.1.7"; +pub const szOID_PKCS_8: &'static str = "1.2.840.113549.1.8"; +pub const szOID_PKCS_9: &'static str = "1.2.840.113549.1.9"; +pub const szOID_PKCS_10: &'static str = "1.2.840.113549.1.10"; +pub const szOID_PKCS_12: &'static str = "1.2.840.113549.1.12"; +pub const szOID_RSA_RSA: &'static str = "1.2.840.113549.1.1.1"; +pub const szOID_RSA_MD2RSA: &'static str = "1.2.840.113549.1.1.2"; +pub const szOID_RSA_MD4RSA: &'static str = "1.2.840.113549.1.1.3"; +pub const szOID_RSA_MD5RSA: &'static str = "1.2.840.113549.1.1.4"; +pub const szOID_RSA_SHA1RSA: &'static str = "1.2.840.113549.1.1.5"; +pub const szOID_RSA_SETOAEP_RSA: &'static str = "1.2.840.113549.1.1.6"; +pub const szOID_RSAES_OAEP: &'static str = "1.2.840.113549.1.1.7"; +pub const szOID_RSA_MGF1: &'static str = "1.2.840.113549.1.1.8"; +pub const szOID_RSA_PSPECIFIED: &'static str = "1.2.840.113549.1.1.9"; +pub const szOID_RSA_SSA_PSS: &'static str = "1.2.840.113549.1.1.10"; +pub const szOID_RSA_SHA256RSA: &'static str = "1.2.840.113549.1.1.11"; +pub const szOID_RSA_SHA384RSA: &'static str = "1.2.840.113549.1.1.12"; +pub const szOID_RSA_SHA512RSA: &'static str = "1.2.840.113549.1.1.13"; +pub const szOID_RSA_DH: &'static str = "1.2.840.113549.1.3.1"; +pub const szOID_RSA_data: &'static str = "1.2.840.113549.1.7.1"; +pub const szOID_RSA_signedData: &'static str = "1.2.840.113549.1.7.2"; +pub const szOID_RSA_envelopedData: &'static str = "1.2.840.113549.1.7.3"; +pub const szOID_RSA_signEnvData: &'static str = "1.2.840.113549.1.7.4"; +pub const szOID_RSA_digestedData: &'static str = "1.2.840.113549.1.7.5"; +pub const szOID_RSA_hashedData: &'static str = "1.2.840.113549.1.7.5"; +pub const szOID_RSA_encryptedData: &'static str = "1.2.840.113549.1.7.6"; +pub const szOID_RSA_emailAddr: &'static str = "1.2.840.113549.1.9.1"; +pub const szOID_RSA_unstructName: &'static str = "1.2.840.113549.1.9.2"; +pub const szOID_RSA_contentType: &'static str = "1.2.840.113549.1.9.3"; +pub const szOID_RSA_messageDigest: &'static str = "1.2.840.113549.1.9.4"; +pub const szOID_RSA_signingTime: &'static str = "1.2.840.113549.1.9.5"; +pub const szOID_RSA_counterSign: &'static str = "1.2.840.113549.1.9.6"; +pub const szOID_RSA_challengePwd: &'static str = "1.2.840.113549.1.9.7"; +pub const szOID_RSA_unstructAddr: &'static str = "1.2.840.113549.1.9.8"; +pub const szOID_RSA_extCertAttrs: &'static str = "1.2.840.113549.1.9.9"; +pub const szOID_RSA_certExtensions: &'static str = "1.2.840.113549.1.9.14"; +pub const szOID_RSA_SMIMECapabilities: &'static str = "1.2.840.113549.1.9.15"; +pub const szOID_RSA_preferSignedData: &'static str = "1.2.840.113549.1.9.15.1"; +pub const szOID_TIMESTAMP_TOKEN: &'static str = "1.2.840.113549.1.9.16.1.4"; +pub const szOID_RFC3161_counterSign: &'static str = "1.3.6.1.4.1.311.3.3.1"; +pub const szOID_RSA_SMIMEalg: &'static str = "1.2.840.113549.1.9.16.3"; +pub const szOID_RSA_SMIMEalgESDH: &'static str = "1.2.840.113549.1.9.16.3.5"; +pub const szOID_RSA_SMIMEalgCMS3DESwrap: &'static str = "1.2.840.113549.1.9.16.3.6"; +pub const szOID_RSA_SMIMEalgCMSRC2wrap: &'static str = "1.2.840.113549.1.9.16.3.7"; +pub const szOID_RSA_MD2: &'static str = "1.2.840.113549.2.2"; +pub const szOID_RSA_MD4: &'static str = "1.2.840.113549.2.4"; +pub const szOID_RSA_MD5: &'static str = "1.2.840.113549.2.5"; +pub const szOID_RSA_RC2CBC: &'static str = "1.2.840.113549.3.2"; +pub const szOID_RSA_RC4: &'static str = "1.2.840.113549.3.4"; +pub const szOID_RSA_DES_EDE3_CBC: &'static str = "1.2.840.113549.3.7"; +pub const szOID_RSA_RC5_CBCPad: &'static str = "1.2.840.113549.3.9"; +pub const szOID_ANSI_X942: &'static str = "1.2.840.10046"; +pub const szOID_ANSI_X942_DH: &'static str = "1.2.840.10046.2.1"; +pub const szOID_X957: &'static str = "1.2.840.10040"; +pub const szOID_X957_DSA: &'static str = "1.2.840.10040.4.1"; +pub const szOID_X957_SHA1DSA: &'static str = "1.2.840.10040.4.3"; +pub const szOID_ECC_PUBLIC_KEY: &'static str = "1.2.840.10045.2.1"; +pub const szOID_ECC_CURVE_P256: &'static str = "1.2.840.10045.3.1.7"; +pub const szOID_ECC_CURVE_P384: &'static str = "1.3.132.0.34"; +pub const szOID_ECC_CURVE_P521: &'static str = "1.3.132.0.35"; +pub const szOID_ECDSA_SHA1: &'static str = "1.2.840.10045.4.1"; +pub const szOID_ECDSA_SPECIFIED: &'static str = "1.2.840.10045.4.3"; +pub const szOID_ECDSA_SHA256: &'static str = "1.2.840.10045.4.3.2"; +pub const szOID_ECDSA_SHA384: &'static str = "1.2.840.10045.4.3.3"; +pub const szOID_ECDSA_SHA512: &'static str = "1.2.840.10045.4.3.4"; +pub const szOID_NIST_AES128_CBC: &'static str = "2.16.840.1.101.3.4.1.2"; +pub const szOID_NIST_AES192_CBC: &'static str = "2.16.840.1.101.3.4.1.22"; +pub const szOID_NIST_AES256_CBC: &'static str = "2.16.840.1.101.3.4.1.42"; +pub const szOID_NIST_AES128_WRAP: &'static str = "2.16.840.1.101.3.4.1.5"; +pub const szOID_NIST_AES192_WRAP: &'static str = "2.16.840.1.101.3.4.1.25"; +pub const szOID_NIST_AES256_WRAP: &'static str = "2.16.840.1.101.3.4.1.45"; +pub const szOID_DH_SINGLE_PASS_STDDH_SHA1_KDF: &'static str = "1.3.133.16.840.63.0.2"; +pub const szOID_DH_SINGLE_PASS_STDDH_SHA256_KDF: &'static str = "1.3.132.1.11.1"; +pub const szOID_DH_SINGLE_PASS_STDDH_SHA384_KDF: &'static str = "1.3.132.1.11.2"; +pub const szOID_DS: &'static str = "2.5"; +pub const szOID_DSALG: &'static str = "2.5.8"; +pub const szOID_DSALG_CRPT: &'static str = "2.5.8.1"; +pub const szOID_DSALG_HASH: &'static str = "2.5.8.2"; +pub const szOID_DSALG_SIGN: &'static str = "2.5.8.3"; +pub const szOID_DSALG_RSA: &'static str = "2.5.8.1.1"; +pub const szOID_OIW: &'static str = "1.3.14"; +pub const szOID_OIWSEC: &'static str = "1.3.14.3.2"; +pub const szOID_OIWSEC_md4RSA: &'static str = "1.3.14.3.2.2"; +pub const szOID_OIWSEC_md5RSA: &'static str = "1.3.14.3.2.3"; +pub const szOID_OIWSEC_md4RSA2: &'static str = "1.3.14.3.2.4"; +pub const szOID_OIWSEC_desECB: &'static str = "1.3.14.3.2.6"; +pub const szOID_OIWSEC_desCBC: &'static str = "1.3.14.3.2.7"; +pub const szOID_OIWSEC_desOFB: &'static str = "1.3.14.3.2.8"; +pub const szOID_OIWSEC_desCFB: &'static str = "1.3.14.3.2.9"; +pub const szOID_OIWSEC_desMAC: &'static str = "1.3.14.3.2.10"; +pub const szOID_OIWSEC_rsaSign: &'static str = "1.3.14.3.2.11"; +pub const szOID_OIWSEC_dsa: &'static str = "1.3.14.3.2.12"; +pub const szOID_OIWSEC_shaDSA: &'static str = "1.3.14.3.2.13"; +pub const szOID_OIWSEC_mdc2RSA: &'static str = "1.3.14.3.2.14"; +pub const szOID_OIWSEC_shaRSA: &'static str = "1.3.14.3.2.15"; +pub const szOID_OIWSEC_dhCommMod: &'static str = "1.3.14.3.2.16"; +pub const szOID_OIWSEC_desEDE: &'static str = "1.3.14.3.2.17"; +pub const szOID_OIWSEC_sha: &'static str = "1.3.14.3.2.18"; +pub const szOID_OIWSEC_mdc2: &'static str = "1.3.14.3.2.19"; +pub const szOID_OIWSEC_dsaComm: &'static str = "1.3.14.3.2.20"; +pub const szOID_OIWSEC_dsaCommSHA: &'static str = "1.3.14.3.2.21"; +pub const szOID_OIWSEC_rsaXchg: &'static str = "1.3.14.3.2.22"; +pub const szOID_OIWSEC_keyHashSeal: &'static str = "1.3.14.3.2.23"; +pub const szOID_OIWSEC_md2RSASign: &'static str = "1.3.14.3.2.24"; +pub const szOID_OIWSEC_md5RSASign: &'static str = "1.3.14.3.2.25"; +pub const szOID_OIWSEC_sha1: &'static str = "1.3.14.3.2.26"; +pub const szOID_OIWSEC_dsaSHA1: &'static str = "1.3.14.3.2.27"; +pub const szOID_OIWSEC_dsaCommSHA1: &'static str = "1.3.14.3.2.28"; +pub const szOID_OIWSEC_sha1RSASign: &'static str = "1.3.14.3.2.29"; +pub const szOID_OIWDIR: &'static str = "1.3.14.7.2"; +pub const szOID_OIWDIR_CRPT: &'static str = "1.3.14.7.2.1"; +pub const szOID_OIWDIR_HASH: &'static str = "1.3.14.7.2.2"; +pub const szOID_OIWDIR_SIGN: &'static str = "1.3.14.7.2.3"; +pub const szOID_OIWDIR_md2: &'static str = "1.3.14.7.2.2.1"; +pub const szOID_OIWDIR_md2RSA: &'static str = "1.3.14.7.2.3.1"; +pub const szOID_INFOSEC: &'static str = "2.16.840.1.101.2.1"; +pub const szOID_INFOSEC_sdnsSignature: &'static str = "2.16.840.1.101.2.1.1.1"; +pub const szOID_INFOSEC_mosaicSignature: &'static str = "2.16.840.1.101.2.1.1.2"; +pub const szOID_INFOSEC_sdnsConfidentiality: &'static str = "2.16.840.1.101.2.1.1.3"; +pub const szOID_INFOSEC_mosaicConfidentiality: &'static str = "2.16.840.1.101.2.1.1.4"; +pub const szOID_INFOSEC_sdnsIntegrity: &'static str = "2.16.840.1.101.2.1.1.5"; +pub const szOID_INFOSEC_mosaicIntegrity: &'static str = "2.16.840.1.101.2.1.1.6"; +pub const szOID_INFOSEC_sdnsTokenProtection: &'static str = "2.16.840.1.101.2.1.1.7"; +pub const szOID_INFOSEC_mosaicTokenProtection: &'static str = "2.16.840.1.101.2.1.1.8"; +pub const szOID_INFOSEC_sdnsKeyManagement: &'static str = "2.16.840.1.101.2.1.1.9"; +pub const szOID_INFOSEC_mosaicKeyManagement: &'static str = "2.16.840.1.101.2.1.1.10"; +pub const szOID_INFOSEC_sdnsKMandSig: &'static str = "2.16.840.1.101.2.1.1.11"; +pub const szOID_INFOSEC_mosaicKMandSig: &'static str = "2.16.840.1.101.2.1.1.12"; +pub const szOID_INFOSEC_SuiteASignature: &'static str = "2.16.840.1.101.2.1.1.13"; +pub const szOID_INFOSEC_SuiteAConfidentiality: &'static str = "2.16.840.1.101.2.1.1.14"; +pub const szOID_INFOSEC_SuiteAIntegrity: &'static str = "2.16.840.1.101.2.1.1.15"; +pub const szOID_INFOSEC_SuiteATokenProtection: &'static str = "2.16.840.1.101.2.1.1.16"; +pub const szOID_INFOSEC_SuiteAKeyManagement: &'static str = "2.16.840.1.101.2.1.1.17"; +pub const szOID_INFOSEC_SuiteAKMandSig: &'static str = "2.16.840.1.101.2.1.1.18"; +pub const szOID_INFOSEC_mosaicUpdatedSig: &'static str = "2.16.840.1.101.2.1.1.19"; +pub const szOID_INFOSEC_mosaicKMandUpdSig: &'static str = "2.16.840.1.101.2.1.1.20"; +pub const szOID_INFOSEC_mosaicUpdatedInteg: &'static str = "2.16.840.1.101.2.1.1.21"; +pub const szOID_NIST_sha256: &'static str = "2.16.840.1.101.3.4.2.1"; +pub const szOID_NIST_sha384: &'static str = "2.16.840.1.101.3.4.2.2"; +pub const szOID_NIST_sha512: &'static str = "2.16.840.1.101.3.4.2.3"; +STRUCT!{struct CRYPT_OBJID_TABLE { + dwAlgId: ::DWORD, + pszObjId: ::LPCSTR, +}} +pub type PCRYPT_OBJID_TABLE = *mut CRYPT_OBJID_TABLE; +STRUCT!{struct CRYPT_HASH_INFO { + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Hash: CRYPT_HASH_BLOB, +}} +pub type PCRYPT_HASH_INFO = *mut CRYPT_HASH_INFO; +STRUCT!{struct CERT_EXTENSION { + pszObjId: ::LPSTR, + fCritical: ::BOOL, + Value: CRYPT_OBJID_BLOB, +}} +pub type PCERT_EXTENSION = *mut CERT_EXTENSION; +pub type PCCERT_EXTENSION = *const CERT_EXTENSION; +STRUCT!{struct CRYPT_ATTRIBUTE_TYPE_VALUE { + pszObjId: ::LPSTR, + Value: CRYPT_OBJID_BLOB, +}} +pub type PCRYPT_ATTRIBUTE_TYPE_VALUE = *mut CRYPT_ATTRIBUTE_TYPE_VALUE; +STRUCT!{struct CRYPT_ATTRIBUTE { + pszObjId: ::LPSTR, + cValue: ::DWORD, + rgValue: PCRYPT_ATTR_BLOB, +}} +pub type PCRYPT_ATTRIBUTE = *mut CRYPT_ATTRIBUTE; +STRUCT!{struct CRYPT_ATTRIBUTES { + cAttr: ::DWORD, + rgAttr: PCRYPT_ATTRIBUTE, +}} +pub type PCRYPT_ATTRIBUTES = *mut CRYPT_ATTRIBUTES; +STRUCT!{struct CERT_RDN_ATTR { + pszObjId: ::LPSTR, + dwValueType: ::DWORD, + Value: CERT_RDN_VALUE_BLOB, +}} +pub type PCERT_RDN_ATTR = *mut CERT_RDN_ATTR; +pub const szOID_COMMON_NAME: &'static str = "2.5.4.3"; +pub const szOID_SUR_NAME: &'static str = "2.5.4.4"; +pub const szOID_DEVICE_SERIAL_NUMBER: &'static str = "2.5.4.5"; +pub const szOID_COUNTRY_NAME: &'static str = "2.5.4.6"; +pub const szOID_LOCALITY_NAME: &'static str = "2.5.4.7"; +pub const szOID_STATE_OR_PROVINCE_NAME: &'static str = "2.5.4.8"; +pub const szOID_STREET_ADDRESS: &'static str = "2.5.4.9"; +pub const szOID_ORGANIZATION_NAME: &'static str = "2.5.4.10"; +pub const szOID_ORGANIZATIONAL_UNIT_NAME: &'static str = "2.5.4.11"; +pub const szOID_TITLE: &'static str = "2.5.4.12"; +pub const szOID_DESCRIPTION: &'static str = "2.5.4.13"; +pub const szOID_SEARCH_GUIDE: &'static str = "2.5.4.14"; +pub const szOID_BUSINESS_CATEGORY: &'static str = "2.5.4.15"; +pub const szOID_POSTAL_ADDRESS: &'static str = "2.5.4.16"; +pub const szOID_POSTAL_CODE: &'static str = "2.5.4.17"; +pub const szOID_POST_OFFICE_BOX: &'static str = "2.5.4.18"; +pub const szOID_PHYSICAL_DELIVERY_OFFICE_NAME: &'static str = "2.5.4.19"; +pub const szOID_TELEPHONE_NUMBER: &'static str = "2.5.4.20"; +pub const szOID_TELEX_NUMBER: &'static str = "2.5.4.21"; +pub const szOID_TELETEXT_TERMINAL_IDENTIFIER: &'static str = "2.5.4.22"; +pub const szOID_FACSIMILE_TELEPHONE_NUMBER: &'static str = "2.5.4.23"; +pub const szOID_X21_ADDRESS: &'static str = "2.5.4.24"; +pub const szOID_INTERNATIONAL_ISDN_NUMBER: &'static str = "2.5.4.25"; +pub const szOID_REGISTERED_ADDRESS: &'static str = "2.5.4.26"; +pub const szOID_DESTINATION_INDICATOR: &'static str = "2.5.4.27"; +pub const szOID_PREFERRED_DELIVERY_METHOD: &'static str = "2.5.4.28"; +pub const szOID_PRESENTATION_ADDRESS: &'static str = "2.5.4.29"; +pub const szOID_SUPPORTED_APPLICATION_CONTEXT: &'static str = "2.5.4.30"; +pub const szOID_MEMBER: &'static str = "2.5.4.31"; +pub const szOID_OWNER: &'static str = "2.5.4.32"; +pub const szOID_ROLE_OCCUPANT: &'static str = "2.5.4.33"; +pub const szOID_SEE_ALSO: &'static str = "2.5.4.34"; +pub const szOID_USER_PASSWORD: &'static str = "2.5.4.35"; +pub const szOID_USER_CERTIFICATE: &'static str = "2.5.4.36"; +pub const szOID_CA_CERTIFICATE: &'static str = "2.5.4.37"; +pub const szOID_AUTHORITY_REVOCATION_LIST: &'static str = "2.5.4.38"; +pub const szOID_CERTIFICATE_REVOCATION_LIST: &'static str = "2.5.4.39"; +pub const szOID_CROSS_CERTIFICATE_PAIR: &'static str = "2.5.4.40"; +pub const szOID_GIVEN_NAME: &'static str = "2.5.4.42"; +pub const szOID_INITIALS: &'static str = "2.5.4.43"; +pub const szOID_DN_QUALIFIER: &'static str = "2.5.4.46"; +pub const szOID_DOMAIN_COMPONENT: &'static str = "0.9.2342.19200300.100.1.25"; +pub const szOID_PKCS_12_FRIENDLY_NAME_ATTR: &'static str = "1.2.840.113549.1.9.20"; +pub const szOID_PKCS_12_LOCAL_KEY_ID: &'static str = "1.2.840.113549.1.9.21"; +pub const szOID_PKCS_12_KEY_PROVIDER_NAME_ATTR: &'static str = "1.3.6.1.4.1.311.17.1"; +pub const szOID_LOCAL_MACHINE_KEYSET: &'static str = "1.3.6.1.4.1.311.17.2"; +pub const szOID_PKCS_12_EXTENDED_ATTRIBUTES: &'static str = "1.3.6.1.4.1.311.17.3"; +pub const szOID_PKCS_12_PROTECTED_PASSWORD_SECRET_BAG_TYPE_ID: &'static str = + "1.3.6.1.4.1.311.17.4"; +pub const szOID_KEYID_RDN: &'static str = "1.3.6.1.4.1.311.10.7.1"; +pub const szOID_EV_RDN_LOCALE: &'static str = "1.3.6.1.4.1.311.60.2.1.1"; +pub const szOID_EV_RDN_STATE_OR_PROVINCE: &'static str = "1.3.6.1.4.1.311.60.2.1.2"; +pub const szOID_EV_RDN_COUNTRY: &'static str = "1.3.6.1.4.1.311.60.2.1.3"; +pub const CERT_RDN_ANY_TYPE: ::DWORD = 0; +pub const CERT_RDN_ENCODED_BLOB: ::DWORD = 1; +pub const CERT_RDN_OCTET_STRING: ::DWORD = 2; +pub const CERT_RDN_NUMERIC_STRING: ::DWORD = 3; +pub const CERT_RDN_PRINTABLE_STRING: ::DWORD = 4; +pub const CERT_RDN_TELETEX_STRING: ::DWORD = 5; +pub const CERT_RDN_T61_STRING: ::DWORD = 5; +pub const CERT_RDN_VIDEOTEX_STRING: ::DWORD = 6; +pub const CERT_RDN_IA5_STRING: ::DWORD = 7; +pub const CERT_RDN_GRAPHIC_STRING: ::DWORD = 8; +pub const CERT_RDN_VISIBLE_STRING: ::DWORD = 9; +pub const CERT_RDN_ISO646_STRING: ::DWORD = 9; +pub const CERT_RDN_GENERAL_STRING: ::DWORD = 10; +pub const CERT_RDN_UNIVERSAL_STRING: ::DWORD = 11; +pub const CERT_RDN_INT4_STRING: ::DWORD = 11; +pub const CERT_RDN_BMP_STRING: ::DWORD = 12; +pub const CERT_RDN_UNICODE_STRING: ::DWORD = 12; +pub const CERT_RDN_UTF8_STRING: ::DWORD = 13; +pub const CERT_RDN_TYPE_MASK: ::DWORD = 0x000000FF; +pub const CERT_RDN_FLAGS_MASK: ::DWORD = 0xFF000000; +pub const CERT_RDN_ENABLE_T61_UNICODE_FLAG: ::DWORD = 0x80000000; +pub const CERT_RDN_ENABLE_UTF8_UNICODE_FLAG: ::DWORD = 0x20000000; +pub const CERT_RDN_FORCE_UTF8_UNICODE_FLAG: ::DWORD = 0x10000000; +pub const CERT_RDN_DISABLE_CHECK_TYPE_FLAG: ::DWORD = 0x40000000; +pub const CERT_RDN_DISABLE_IE4_UTF8_FLAG: ::DWORD = 0x01000000; +pub const CERT_RDN_ENABLE_PUNYCODE_FLAG: ::DWORD = 0x02000000; +STRUCT!{struct CERT_RDN { + cRDNAttr: ::DWORD, + rgRDNAttr: PCERT_RDN_ATTR, +}} +pub type PCERT_RDN = *mut CERT_RDN; +STRUCT!{struct CERT_NAME_INFO { + cRDN: ::DWORD, + rgRDN: PCERT_RDN, +}} +pub type PCERT_NAME_INFO = *mut CERT_NAME_INFO; +STRUCT!{struct CERT_NAME_VALUE { + dwValueType: ::DWORD, + Value: CERT_RDN_VALUE_BLOB, +}} +pub type PCERT_NAME_VALUE = *mut CERT_NAME_VALUE; +STRUCT!{struct CERT_PUBLIC_KEY_INFO { + Algorithm: CRYPT_ALGORITHM_IDENTIFIER, + PublicKey: CRYPT_BIT_BLOB, +}} +pub type PCERT_PUBLIC_KEY_INFO = *mut CERT_PUBLIC_KEY_INFO; +pub const CERT_RSA_PUBLIC_KEY_OBJID: &'static str = szOID_RSA_RSA; +pub const CERT_DEFAULT_OID_PUBLIC_KEY_SIGN: &'static str = szOID_RSA_RSA; +pub const CERT_DEFAULT_OID_PUBLIC_KEY_XCHG: &'static str = szOID_RSA_RSA; +STRUCT!{struct CRYPT_ECC_PRIVATE_KEY_INFO { + dwVersion: ::DWORD, + PrivateKey: CRYPT_DER_BLOB, + szCurveOid: ::LPSTR, + PublicKey: CRYPT_BIT_BLOB, +}} +pub type PCRYPT_ECC_PRIVATE_KEY_INFO = *mut CRYPT_ECC_PRIVATE_KEY_INFO; +pub const CRYPT_ECC_PRIVATE_KEY_INFO_v1: ::DWORD = 1; +STRUCT!{struct CRYPT_PRIVATE_KEY_INFO { + Version: ::DWORD, + Algorithm: CRYPT_ALGORITHM_IDENTIFIER, + PrivateKey: CRYPT_DER_BLOB, + pAttributes: PCRYPT_ATTRIBUTES, +}} +pub type PCRYPT_PRIVATE_KEY_INFO = *mut CRYPT_PRIVATE_KEY_INFO; +STRUCT!{struct CRYPT_ENCRYPTED_PRIVATE_KEY_INFO { + EncryptionAlgorithm: ::CRYPT_ALGORITHM_IDENTIFIER, + EncryptedPrivateKey: ::CRYPT_DATA_BLOB, +}} +pub type PCRYPT_ENCRYPTED_PRIVATE_KEY_INFO = *mut CRYPT_ENCRYPTED_PRIVATE_KEY_INFO; +pub type PCRYPT_DECRYPT_PRIVATE_KEY_FUNC = Option<unsafe extern "system" fn( + Algorithm: CRYPT_ALGORITHM_IDENTIFIER, EncryptedPrivateKey: CRYPT_DATA_BLOB, + pbClearTextKey: *mut ::BYTE, pcbClearTextKey: *mut ::DWORD, pVoidDecryptFunc: ::LPVOID, +) -> ::BOOL>; +pub type PCRYPT_ENCRYPT_PRIVATE_KEY_FUNC = Option<unsafe extern "system" fn( + Algorithm: *mut CRYPT_ALGORITHM_IDENTIFIER, pClearTextPrivateKey: *mut CRYPT_DATA_BLOB, + pbEncryptedKey: *mut ::BYTE, pcbEncryptedKey: *mut ::DWORD, pVoidEncryptFunc: ::LPVOID, +) -> ::BOOL>; +pub type PCRYPT_RESOLVE_HCRYPTPROV_FUNC = Option<unsafe extern "system" fn( + pPrivateKeyInfo: *mut CRYPT_PRIVATE_KEY_INFO, phCryptProv: *mut HCRYPTPROV, + pVoidResolveFunc: ::LPVOID, +) -> ::BOOL>; +STRUCT!{nodebug struct CRYPT_PKCS8_IMPORT_PARAMS { + PrivateKey: CRYPT_DIGEST_BLOB, + pResolvehCryptProvFunc: PCRYPT_RESOLVE_HCRYPTPROV_FUNC, + pVoidResolveFunc: ::LPVOID, + pDecryptPrivateKeyFunc: PCRYPT_DECRYPT_PRIVATE_KEY_FUNC, + pVoidDecryptFunc: ::LPVOID, +}} +pub type PCRYPT_PKCS8_IMPORT_PARAMS = *mut CRYPT_PKCS8_IMPORT_PARAMS; +pub type CRYPT_PRIVATE_KEY_BLOB_AND_PARAMS = CRYPT_PKCS8_IMPORT_PARAMS; +pub type PPCRYPT_PRIVATE_KEY_BLOB_AND_PARAMS = *mut CRYPT_PKCS8_IMPORT_PARAMS; +STRUCT!{nodebug struct CRYPT_PKCS8_EXPORT_PARAMS { + hCryptProv: HCRYPTPROV, + dwKeySpec: ::DWORD, + pszPrivateKeyObjId: ::LPSTR, + pEncryptPrivateKeyFunc: PCRYPT_ENCRYPT_PRIVATE_KEY_FUNC, + pVoidEncryptFunc: ::LPVOID, +}} +pub type PCRYPT_PKCS8_EXPORT_PARAMS = *mut CRYPT_PKCS8_EXPORT_PARAMS; +STRUCT!{struct CERT_INFO { + dwVersion: ::DWORD, + SerialNumber: CRYPT_INTEGER_BLOB, + SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Issuer: CERT_NAME_BLOB, + NotBefore: ::FILETIME, + NotAfter: ::FILETIME, + Subject: CERT_NAME_BLOB, + SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO, + IssuerUniqueId: CRYPT_BIT_BLOB, + SubjectUniqueId: CRYPT_BIT_BLOB, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCERT_INFO = *mut CERT_INFO; +pub const CERT_V1: ::DWORD = 0; +pub const CERT_V2: ::DWORD = 1; +pub const CERT_V3: ::DWORD = 2; +pub const CERT_INFO_VERSION_FLAG: ::DWORD = 1; +pub const CERT_INFO_SERIAL_NUMBER_FLAG: ::DWORD = 2; +pub const CERT_INFO_SIGNATURE_ALGORITHM_FLAG: ::DWORD = 3; +pub const CERT_INFO_ISSUER_FLAG: ::DWORD = 4; +pub const CERT_INFO_NOT_BEFORE_FLAG: ::DWORD = 5; +pub const CERT_INFO_NOT_AFTER_FLAG: ::DWORD = 6; +pub const CERT_INFO_SUBJECT_FLAG: ::DWORD = 7; +pub const CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG: ::DWORD = 8; +pub const CERT_INFO_ISSUER_UNIQUE_ID_FLAG: ::DWORD = 9; +pub const CERT_INFO_SUBJECT_UNIQUE_ID_FLAG: ::DWORD = 10; +pub const CERT_INFO_EXTENSION_FLAG: ::DWORD = 11; +STRUCT!{struct CRL_ENTRY { + SerialNumber: CRYPT_INTEGER_BLOB, + RevocationDate: ::FILETIME, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRL_ENTRY = *mut CRL_ENTRY; +STRUCT!{struct CRL_INFO { + dwVersion: ::DWORD, + SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Issuer: CERT_NAME_BLOB, + ThisUpdate: ::FILETIME, + NextUpdate: ::FILETIME, + cCRLEntry: ::DWORD, + rgCRLEntry: PCRL_ENTRY, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRL_INFO = *mut CRL_INFO; +pub const CRL_V1: ::DWORD = 0; +pub const CRL_V2: ::DWORD = 1; +pub const CERT_BUNDLE_CERTIFICATE: ::DWORD = 0; +pub const CERT_BUNDLE_CRL: ::DWORD = 1; +STRUCT!{struct CERT_OR_CRL_BLOB { + dwChoice: ::DWORD, + cbEncoded: ::DWORD, + pbEncoded: *mut ::BYTE, +}} +pub type PCERT_OR_CRL_BLOB = *mut CERT_OR_CRL_BLOB; +STRUCT!{struct CERT_OR_CRL_BUNDLE { + cItem: ::DWORD, + rgItem: PCERT_OR_CRL_BLOB, +}} +pub type PCERT_OR_CRL_BUNDLE = *mut CERT_OR_CRL_BUNDLE; +STRUCT!{struct CERT_REQUEST_INFO { + dwVersion: ::DWORD, + Subject: CERT_NAME_BLOB, + SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO, + cAttribute: ::DWORD, + rgAttribute: PCRYPT_ATTRIBUTE, +}} +pub type PCERT_REQUEST_INFO = *mut CERT_REQUEST_INFO; +pub const CERT_REQUEST_V1: ::DWORD = 0; +STRUCT!{struct CERT_KEYGEN_REQUEST_INFO { + dwVersion: ::DWORD, + SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO, + pwszChallengeString: ::LPWSTR, +}} +pub type PCERT_KEYGEN_REQUEST_INFO = *mut CERT_KEYGEN_REQUEST_INFO; +pub const CERT_KEYGEN_REQUEST_V1: ::DWORD = 0; +STRUCT!{struct CERT_SIGNED_CONTENT_INFO { + ToBeSigned: CRYPT_DER_BLOB, + SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Signature: CRYPT_BIT_BLOB, +}} +pub type PCERT_SIGNED_CONTENT_INFO = *mut CERT_SIGNED_CONTENT_INFO; +STRUCT!{struct CTL_USAGE { + cUsageIdentifier: ::DWORD, + rgpszUsageIdentifier: *mut ::LPSTR, +}} +pub type PCTL_USAGE = *mut CTL_USAGE; +pub type CERT_ENHKEY_USAGE = CTL_USAGE; +pub type PCERT_ENHKEY_USAGE = *mut CERT_ENHKEY_USAGE; +pub type PCCTL_USAGE = *const CTL_USAGE; +pub type PCCERT_ENHKEY_USAGE = *const CERT_ENHKEY_USAGE; +STRUCT!{struct CTL_ENTRY { + SubjectIdentifier: CRYPT_DATA_BLOB, + cAttribute: ::DWORD, + rgAttribute: PCRYPT_ATTRIBUTE, +}} +pub type PCTL_ENTRY = *mut CTL_ENTRY; +STRUCT!{struct CTL_INFO { + dwVersion: ::DWORD, + SubjectUsage: CTL_USAGE, + ListIdentifier: CRYPT_DATA_BLOB, + SequenceNumber: CRYPT_INTEGER_BLOB, + ThisUpdate: ::FILETIME, + NextUpdate: ::FILETIME, + SubjectAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + cCTLEntry: ::DWORD, + rgCTLEntry: PCTL_ENTRY, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCTL_INFO = *mut CTL_INFO; +pub const CTL_V1: ::DWORD = 0; +STRUCT!{struct CRYPT_TIME_STAMP_REQUEST_INFO { + pszTimeStampAlgorithm: ::LPSTR, + pszContentType: ::LPSTR, + Content: CRYPT_OBJID_BLOB, + cAttribute: ::DWORD, + rgAttribute: PCRYPT_ATTRIBUTE, +}} +pub type PCRYPT_TIME_STAMP_REQUEST_INFO = *mut CRYPT_TIME_STAMP_REQUEST_INFO; +STRUCT!{struct CRYPT_ENROLLMENT_NAME_VALUE_PAIR { + pwszName: ::LPWSTR, + pwszValue: ::LPWSTR, +}} +pub type PCRYPT_ENROLLMENT_NAME_VALUE_PAIR = *mut CRYPT_ENROLLMENT_NAME_VALUE_PAIR; +STRUCT!{struct CRYPT_CSP_PROVIDER { + dwKeySpec: ::DWORD, + pwszProviderName: ::LPWSTR, + Signature: CRYPT_BIT_BLOB, +}} +pub type PCRYPT_CSP_PROVIDER = *mut CRYPT_CSP_PROVIDER; +pub const CERT_ENCODING_TYPE_MASK: ::DWORD = 0x0000FFFF; +pub const CMSG_ENCODING_TYPE_MASK: ::DWORD = 0xFFFF0000; +pub const CRYPT_ASN_ENCODING: ::DWORD = 0x00000001; +pub const CRYPT_NDR_ENCODING: ::DWORD = 0x00000002; +pub const X509_ASN_ENCODING: ::DWORD = 0x00000001; +pub const X509_NDR_ENCODING: ::DWORD = 0x00000002; +pub const PKCS_7_ASN_ENCODING: ::DWORD = 0x00010000; +pub const PKCS_7_NDR_ENCODING: ::DWORD = 0x00020000; +pub const CRYPT_FORMAT_STR_MULTI_LINE: ::DWORD = 0x0001; +pub const CRYPT_FORMAT_STR_NO_HEX: ::DWORD = 0x0010; +pub const CRYPT_FORMAT_SIMPLE: ::DWORD = 0x0001; +pub const CRYPT_FORMAT_X509: ::DWORD = 0x0002; +pub const CRYPT_FORMAT_OID: ::DWORD = 0x0004; +pub const CRYPT_FORMAT_RDN_SEMICOLON: ::DWORD = 0x0100; +pub const CRYPT_FORMAT_RDN_CRLF: ::DWORD = 0x0200; +pub const CRYPT_FORMAT_RDN_UNQUOTE: ::DWORD = 0x0400; +pub const CRYPT_FORMAT_RDN_REVERSE: ::DWORD = 0x0800; +pub const CRYPT_FORMAT_COMMA: ::DWORD = 0x1000; +pub const CRYPT_FORMAT_SEMICOLON: ::DWORD = CRYPT_FORMAT_RDN_SEMICOLON; +pub const CRYPT_FORMAT_CRLF: ::DWORD = CRYPT_FORMAT_RDN_CRLF; +pub type PFN_CRYPT_ALLOC = Option<unsafe extern "system" fn(cbSize: ::size_t)>; +pub type PFN_CRYPT_FREE = Option<unsafe extern "system" fn(pv: ::LPVOID)>; +STRUCT!{nodebug struct CRYPT_ENCODE_PARA { + cbSize: ::DWORD, + pfnAlloc: PFN_CRYPT_ALLOC, + pfnFree: PFN_CRYPT_FREE, +}} +pub type PCRYPT_ENCODE_PARA = *mut CRYPT_ENCODE_PARA; +pub const CRYPT_ENCODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: ::DWORD = 0x8; +pub const CRYPT_ENCODE_ALLOC_FLAG: ::DWORD = 0x8000; +pub const CRYPT_UNICODE_NAME_ENCODE_ENABLE_T61_UNICODE_FLAG: ::DWORD = + CERT_RDN_ENABLE_T61_UNICODE_FLAG; +pub const CRYPT_UNICODE_NAME_ENCODE_ENABLE_UTF8_UNICODE_FLAG: ::DWORD = + CERT_RDN_ENABLE_UTF8_UNICODE_FLAG; +pub const CRYPT_UNICODE_NAME_ENCODE_FORCE_UTF8_UNICODE_FLAG: ::DWORD = + CERT_RDN_FORCE_UTF8_UNICODE_FLAG; +pub const CRYPT_UNICODE_NAME_ENCODE_DISABLE_CHECK_TYPE_FLAG: ::DWORD = + CERT_RDN_DISABLE_CHECK_TYPE_FLAG; +pub const CRYPT_SORTED_CTL_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: ::DWORD = 0x10000; +pub const CRYPT_ENCODE_ENABLE_PUNYCODE_FLAG: ::DWORD = 0x20000; +pub const CRYPT_ENCODE_ENABLE_UTF8PERCENT_FLAG: ::DWORD = 0x40000; +pub const CRYPT_ENCODE_ENABLE_IA5CONVERSION_FLAG: ::DWORD = CRYPT_ENCODE_ENABLE_PUNYCODE_FLAG + | CRYPT_ENCODE_ENABLE_UTF8PERCENT_FLAG; +STRUCT!{nodebug struct CRYPT_DECODE_PARA { + cbSize: ::DWORD, + pfnAlloc: PFN_CRYPT_ALLOC, + pfnFree: PFN_CRYPT_FREE, +}} +pub type PCRYPT_DECODE_PARA = *mut CRYPT_DECODE_PARA; +pub const CRYPT_DECODE_NOCOPY_FLAG: ::DWORD = 0x1; +pub const CRYPT_DECODE_TO_BE_SIGNED_FLAG: ::DWORD = 0x2; +pub const CRYPT_DECODE_SHARE_OID_STRING_FLAG: ::DWORD = 0x4; +pub const CRYPT_DECODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: ::DWORD = 0x8; +pub const CRYPT_DECODE_ALLOC_FLAG: ::DWORD = 0x8000; +pub const CRYPT_UNICODE_NAME_DECODE_DISABLE_IE4_UTF8_FLAG: ::DWORD = + CERT_RDN_DISABLE_IE4_UTF8_FLAG; +pub const CRYPT_DECODE_ENABLE_PUNYCODE_FLAG: ::DWORD = 0x02000000; +pub const CRYPT_DECODE_ENABLE_UTF8PERCENT_FLAG: ::DWORD = 0x04000000; +pub const CRYPT_DECODE_ENABLE_IA5CONVERSION_FLAG: ::DWORD = CRYPT_DECODE_ENABLE_PUNYCODE_FLAG + | CRYPT_DECODE_ENABLE_UTF8PERCENT_FLAG; +pub const CRYPT_ENCODE_DECODE_NONE: ::LPCSTR = 0 as ::LPCSTR; +pub const X509_CERT: ::LPCSTR = 1 as ::LPCSTR; +pub const X509_CERT_TO_BE_SIGNED: ::LPCSTR = 2 as ::LPCSTR; +pub const X509_CERT_CRL_TO_BE_SIGNED: ::LPCSTR = 3 as ::LPCSTR; +pub const X509_CERT_REQUEST_TO_BE_SIGNED: ::LPCSTR = 4 as ::LPCSTR; +pub const X509_EXTENSIONS: ::LPCSTR = 5 as ::LPCSTR; +pub const X509_NAME_VALUE: ::LPCSTR = 6 as ::LPCSTR; +pub const X509_NAME: ::LPCSTR = 7 as ::LPCSTR; +pub const X509_PUBLIC_KEY_INFO: ::LPCSTR = 8 as ::LPCSTR; +pub const X509_AUTHORITY_KEY_ID: ::LPCSTR = 9 as ::LPCSTR; +pub const X509_KEY_ATTRIBUTES: ::LPCSTR = 10 as ::LPCSTR; +pub const X509_KEY_USAGE_RESTRICTION: ::LPCSTR = 11 as ::LPCSTR; +pub const X509_ALTERNATE_NAME: ::LPCSTR = 12 as ::LPCSTR; +pub const X509_BASIC_CONSTRAINTS: ::LPCSTR = 13 as ::LPCSTR; +pub const X509_KEY_USAGE: ::LPCSTR = 14 as ::LPCSTR; +pub const X509_BASIC_CONSTRAINTS2: ::LPCSTR = 15 as ::LPCSTR; +pub const X509_CERT_POLICIES: ::LPCSTR = 16 as ::LPCSTR; +pub const PKCS_UTC_TIME: ::LPCSTR = 17 as ::LPCSTR; +pub const PKCS_TIME_REQUEST: ::LPCSTR = 18 as ::LPCSTR; +pub const RSA_CSP_PUBLICKEYBLOB: ::LPCSTR = 19 as ::LPCSTR; +pub const X509_UNICODE_NAME: ::LPCSTR = 20 as ::LPCSTR; +pub const X509_KEYGEN_REQUEST_TO_BE_SIGNED: ::LPCSTR = 21 as ::LPCSTR; +pub const PKCS_ATTRIBUTE: ::LPCSTR = 22 as ::LPCSTR; +pub const PKCS_CONTENT_INFO_SEQUENCE_OF_ANY: ::LPCSTR = 23 as ::LPCSTR; +pub const X509_UNICODE_NAME_VALUE: ::LPCSTR = 24 as ::LPCSTR; +pub const X509_ANY_STRING: ::LPCSTR = X509_NAME_VALUE; +pub const X509_UNICODE_ANY_STRING: ::LPCSTR = X509_UNICODE_NAME_VALUE; +pub const X509_OCTET_STRING: ::LPCSTR = 25 as ::LPCSTR; +pub const X509_BITS: ::LPCSTR = 26 as ::LPCSTR; +pub const X509_INTEGER: ::LPCSTR = 27 as ::LPCSTR; +pub const X509_MULTI_BYTE_INTEGER: ::LPCSTR = 28 as ::LPCSTR; +pub const X509_ENUMERATED: ::LPCSTR = 29 as ::LPCSTR; +pub const X509_CHOICE_OF_TIME: ::LPCSTR = 30 as ::LPCSTR; +pub const X509_AUTHORITY_KEY_ID2: ::LPCSTR = 31 as ::LPCSTR; +pub const X509_AUTHORITY_INFO_ACCESS: ::LPCSTR = 32 as ::LPCSTR; +pub const X509_SUBJECT_INFO_ACCESS: ::LPCSTR = X509_AUTHORITY_INFO_ACCESS; +pub const X509_CRL_REASON_CODE: ::LPCSTR = X509_ENUMERATED; +pub const PKCS_CONTENT_INFO: ::LPCSTR = 33 as ::LPCSTR; +pub const X509_SEQUENCE_OF_ANY: ::LPCSTR = 34 as ::LPCSTR; +pub const X509_CRL_DIST_POINTS: ::LPCSTR = 35 as ::LPCSTR; +pub const X509_ENHANCED_KEY_USAGE: ::LPCSTR = 36 as ::LPCSTR; +pub const PKCS_CTL: ::LPCSTR = 37 as ::LPCSTR; +pub const X509_MULTI_BYTE_UINT: ::LPCSTR = 38 as ::LPCSTR; +pub const X509_DSS_PUBLICKEY: ::LPCSTR = X509_MULTI_BYTE_UINT; +pub const X509_DSS_PARAMETERS: ::LPCSTR = 39 as ::LPCSTR; +pub const X509_DSS_SIGNATURE: ::LPCSTR = 40 as ::LPCSTR; +pub const PKCS_RC2_CBC_PARAMETERS: ::LPCSTR = 41 as ::LPCSTR; +pub const PKCS_SMIME_CAPABILITIES: ::LPCSTR = 42 as ::LPCSTR; +pub const X509_QC_STATEMENTS_EXT: ::LPCSTR = 42 as ::LPCSTR; +pub const PKCS_RSA_PRIVATE_KEY: ::LPCSTR = 43 as ::LPCSTR; +pub const PKCS_PRIVATE_KEY_INFO: ::LPCSTR = 44 as ::LPCSTR; +pub const PKCS_ENCRYPTED_PRIVATE_KEY_INFO: ::LPCSTR = 45 as ::LPCSTR; +pub const X509_PKIX_POLICY_QUALIFIER_USERNOTICE: ::LPCSTR = 46 as ::LPCSTR; +pub const X509_DH_PUBLICKEY: ::LPCSTR = X509_MULTI_BYTE_UINT; +pub const X509_DH_PARAMETERS: ::LPCSTR = 47 as ::LPCSTR; +pub const PKCS_ATTRIBUTES: ::LPCSTR = 48 as ::LPCSTR; +pub const PKCS_SORTED_CTL: ::LPCSTR = 49 as ::LPCSTR; +pub const X509_ECC_SIGNATURE: ::LPCSTR = 47 as ::LPCSTR; +pub const X942_DH_PARAMETERS: ::LPCSTR = 50 as ::LPCSTR; +pub const X509_BITS_WITHOUT_TRAILING_ZEROES: ::LPCSTR = 51 as ::LPCSTR; +pub const X942_OTHER_INFO: ::LPCSTR = 52 as ::LPCSTR; +pub const X509_CERT_PAIR: ::LPCSTR = 53 as ::LPCSTR; +pub const X509_ISSUING_DIST_POINT: ::LPCSTR = 54 as ::LPCSTR; +pub const X509_NAME_CONSTRAINTS: ::LPCSTR = 55 as ::LPCSTR; +pub const X509_POLICY_MAPPINGS: ::LPCSTR = 56 as ::LPCSTR; +pub const X509_POLICY_CONSTRAINTS: ::LPCSTR = 57 as ::LPCSTR; +pub const X509_CROSS_CERT_DIST_POINTS: ::LPCSTR = 58 as ::LPCSTR; +pub const CMC_DATA: ::LPCSTR = 59 as ::LPCSTR; +pub const CMC_RESPONSE: ::LPCSTR = 60 as ::LPCSTR; +pub const CMC_STATUS: ::LPCSTR = 61 as ::LPCSTR; +pub const CMC_ADD_EXTENSIONS: ::LPCSTR = 62 as ::LPCSTR; +pub const CMC_ADD_ATTRIBUTES: ::LPCSTR = 63 as ::LPCSTR; +pub const X509_CERTIFICATE_TEMPLATE: ::LPCSTR = 64 as ::LPCSTR; +pub const OCSP_SIGNED_REQUEST: ::LPCSTR = 65 as ::LPCSTR; +pub const OCSP_REQUEST: ::LPCSTR = 66 as ::LPCSTR; +pub const OCSP_RESPONSE: ::LPCSTR = 67 as ::LPCSTR; +pub const OCSP_BASIC_SIGNED_RESPONSE: ::LPCSTR = 68 as ::LPCSTR; +pub const OCSP_BASIC_RESPONSE: ::LPCSTR = 69 as ::LPCSTR; +pub const X509_LOGOTYPE_EXT: ::LPCSTR = 70 as ::LPCSTR; +pub const X509_BIOMETRIC_EXT: ::LPCSTR = 71 as ::LPCSTR; +pub const CNG_RSA_PUBLIC_KEY_BLOB: ::LPCSTR = 72 as ::LPCSTR; +pub const X509_OBJECT_IDENTIFIER: ::LPCSTR = 73 as ::LPCSTR; +pub const X509_ALGORITHM_IDENTIFIER: ::LPCSTR = 74 as ::LPCSTR; +pub const PKCS_RSA_SSA_PSS_PARAMETERS: ::LPCSTR = 75 as ::LPCSTR; +pub const PKCS_RSAES_OAEP_PARAMETERS: ::LPCSTR = 76 as ::LPCSTR; +pub const ECC_CMS_SHARED_INFO: ::LPCSTR = 77 as ::LPCSTR; +pub const TIMESTAMP_REQUEST: ::LPCSTR = 78 as ::LPCSTR; +pub const TIMESTAMP_RESPONSE: ::LPCSTR = 79 as ::LPCSTR; +pub const TIMESTAMP_INFO: ::LPCSTR = 80 as ::LPCSTR; +pub const X509_CERT_BUNDLE: ::LPCSTR = 81 as ::LPCSTR; +pub const X509_ECC_PRIVATE_KEY: ::LPCSTR = 82 as ::LPCSTR; +pub const CNG_RSA_PRIVATE_KEY_BLOB: ::LPCSTR = 83 as ::LPCSTR; +pub const X509_SUBJECT_DIR_ATTRS: ::LPCSTR = 84 as ::LPCSTR; +pub const PKCS7_SIGNER_INFO: ::LPCSTR = 500 as ::LPCSTR; +pub const CMS_SIGNER_INFO: ::LPCSTR = 501 as ::LPCSTR; +pub const szOID_AUTHORITY_KEY_IDENTIFIER: &'static str = "2.5.29.1"; +pub const szOID_KEY_ATTRIBUTES: &'static str = "2.5.29.2"; +pub const szOID_CERT_POLICIES_95: &'static str = "2.5.29.3"; +pub const szOID_KEY_USAGE_RESTRICTION: &'static str = "2.5.29.4"; +pub const szOID_SUBJECT_ALT_NAME: &'static str = "2.5.29.7"; +pub const szOID_ISSUER_ALT_NAME: &'static str = "2.5.29.8"; +pub const szOID_BASIC_CONSTRAINTS: &'static str = "2.5.29.10"; +pub const szOID_KEY_USAGE: &'static str = "2.5.29.15"; +pub const szOID_PRIVATEKEY_USAGE_PERIOD: &'static str = "2.5.29.16"; +pub const szOID_BASIC_CONSTRAINTS2: &'static str = "2.5.29.19"; +pub const szOID_CERT_POLICIES: &'static str = "2.5.29.32"; +pub const szOID_ANY_CERT_POLICY: &'static str = "2.5.29.32.0"; +pub const szOID_INHIBIT_ANY_POLICY: &'static str = "2.5.29.54"; +pub const szOID_AUTHORITY_KEY_IDENTIFIER2: &'static str = "2.5.29.35"; +pub const szOID_SUBJECT_KEY_IDENTIFIER: &'static str = "2.5.29.14"; +pub const szOID_SUBJECT_ALT_NAME2: &'static str = "2.5.29.17"; +pub const szOID_ISSUER_ALT_NAME2: &'static str = "2.5.29.18"; +pub const szOID_CRL_REASON_CODE: &'static str = "2.5.29.21"; +pub const szOID_REASON_CODE_HOLD: &'static str = "2.5.29.23"; +pub const szOID_CRL_DIST_POINTS: &'static str = "2.5.29.31"; +pub const szOID_ENHANCED_KEY_USAGE: &'static str = "2.5.29.37"; +pub const szOID_ANY_ENHANCED_KEY_USAGE: &'static str = "2.5.29.37.0"; +pub const szOID_CRL_NUMBER: &'static str = "2.5.29.20"; +pub const szOID_DELTA_CRL_INDICATOR: &'static str = "2.5.29.27"; +pub const szOID_ISSUING_DIST_POINT: &'static str = "2.5.29.28"; +pub const szOID_FRESHEST_CRL: &'static str = "2.5.29.46"; +pub const szOID_NAME_CONSTRAINTS: &'static str = "2.5.29.30"; +pub const szOID_POLICY_MAPPINGS: &'static str = "2.5.29.33"; +pub const szOID_LEGACY_POLICY_MAPPINGS: &'static str = "2.5.29.5"; +pub const szOID_POLICY_CONSTRAINTS: &'static str = "2.5.29.36"; +pub const szOID_RENEWAL_CERTIFICATE: &'static str = "1.3.6.1.4.1.311.13.1"; +pub const szOID_ENROLLMENT_NAME_VALUE_PAIR: &'static str = "1.3.6.1.4.1.311.13.2.1"; +pub const szOID_ENROLLMENT_CSP_PROVIDER: &'static str = "1.3.6.1.4.1.311.13.2.2"; +pub const szOID_OS_VERSION: &'static str = "1.3.6.1.4.1.311.13.2.3"; +pub const szOID_ENROLLMENT_AGENT: &'static str = "1.3.6.1.4.1.311.20.2.1"; +pub const szOID_PKIX: &'static str = "1.3.6.1.5.5.7"; +pub const szOID_PKIX_PE: &'static str = "1.3.6.1.5.5.7.1"; +pub const szOID_AUTHORITY_INFO_ACCESS: &'static str = "1.3.6.1.5.5.7.1.1"; +pub const szOID_SUBJECT_INFO_ACCESS: &'static str = "1.3.6.1.5.5.7.1.11"; +pub const szOID_BIOMETRIC_EXT: &'static str = "1.3.6.1.5.5.7.1.2"; +pub const szOID_QC_STATEMENTS_EXT: &'static str = "1.3.6.1.5.5.7.1.3"; +pub const szOID_LOGOTYPE_EXT: &'static str = "1.3.6.1.5.5.7.1.12"; +pub const szOID_CERT_EXTENSIONS: &'static str = "1.3.6.1.4.1.311.2.1.14"; +pub const szOID_NEXT_UPDATE_LOCATION: &'static str = "1.3.6.1.4.1.311.10.2"; +pub const szOID_REMOVE_CERTIFICATE: &'static str = "1.3.6.1.4.1.311.10.8.1"; +pub const szOID_CROSS_CERT_DIST_POINTS: &'static str = "1.3.6.1.4.1.311.10.9.1"; +pub const szOID_CTL: &'static str = "1.3.6.1.4.1.311.10.1"; +pub const szOID_SORTED_CTL: &'static str = "1.3.6.1.4.1.311.10.1.1"; +pub const szOID_SERIALIZED: &'static str = "1.3.6.1.4.1.311.10.3.3.1"; +pub const szOID_NT_PRINCIPAL_NAME: &'static str = "1.3.6.1.4.1.311.20.2.3"; +pub const szOID_INTERNATIONALIZED_EMAIL_ADDRESS: &'static str = "1.3.6.1.4.1.311.20.2.4"; +pub const szOID_PRODUCT_UPDATE: &'static str = "1.3.6.1.4.1.311.31.1"; +pub const szOID_ANY_APPLICATION_POLICY: &'static str = "1.3.6.1.4.1.311.10.12.1"; +pub const szOID_AUTO_ENROLL_CTL_USAGE: &'static str = "1.3.6.1.4.1.311.20.1"; +pub const szOID_ENROLL_CERTTYPE_EXTENSION: &'static str = "1.3.6.1.4.1.311.20.2"; +pub const szOID_CERT_MANIFOLD: &'static str = "1.3.6.1.4.1.311.20.3"; +pub const szOID_CERTSRV_CA_VERSION: &'static str = "1.3.6.1.4.1.311.21.1"; +pub const szOID_CERTSRV_PREVIOUS_CERT_HASH: &'static str = "1.3.6.1.4.1.311.21.2"; +pub const szOID_CRL_VIRTUAL_BASE: &'static str = "1.3.6.1.4.1.311.21.3"; +pub const szOID_CRL_NEXT_PUBLISH: &'static str = "1.3.6.1.4.1.311.21.4"; +pub const szOID_KP_CA_EXCHANGE: &'static str = "1.3.6.1.4.1.311.21.5"; +pub const szOID_KP_KEY_RECOVERY_AGENT: &'static str = "1.3.6.1.4.1.311.21.6"; +pub const szOID_CERTIFICATE_TEMPLATE: &'static str = "1.3.6.1.4.1.311.21.7"; +pub const szOID_ENTERPRISE_OID_ROOT: &'static str = "1.3.6.1.4.1.311.21.8"; +pub const szOID_RDN_DUMMY_SIGNER: &'static str = "1.3.6.1.4.1.311.21.9"; +pub const szOID_APPLICATION_CERT_POLICIES: &'static str = "1.3.6.1.4.1.311.21.10"; +pub const szOID_APPLICATION_POLICY_MAPPINGS: &'static str = "1.3.6.1.4.1.311.21.11"; +pub const szOID_APPLICATION_POLICY_CONSTRAINTS: &'static str = "1.3.6.1.4.1.311.21.12"; +pub const szOID_ARCHIVED_KEY_ATTR: &'static str = "1.3.6.1.4.1.311.21.13"; +pub const szOID_CRL_SELF_CDP: &'static str = "1.3.6.1.4.1.311.21.14"; +pub const szOID_REQUIRE_CERT_CHAIN_POLICY: &'static str = "1.3.6.1.4.1.311.21.15"; +pub const szOID_ARCHIVED_KEY_CERT_HASH: &'static str = "1.3.6.1.4.1.311.21.16"; +pub const szOID_ISSUED_CERT_HASH: &'static str = "1.3.6.1.4.1.311.21.17"; +pub const szOID_DS_EMAIL_REPLICATION: &'static str = "1.3.6.1.4.1.311.21.19"; +pub const szOID_REQUEST_CLIENT_INFO: &'static str = "1.3.6.1.4.1.311.21.20"; +pub const szOID_ENCRYPTED_KEY_HASH: &'static str = "1.3.6.1.4.1.311.21.21"; +pub const szOID_CERTSRV_CROSSCA_VERSION: &'static str = "1.3.6.1.4.1.311.21.22"; +pub const szOID_NTDS_REPLICATION: &'static str = "1.3.6.1.4.1.311.25.1"; +pub const szOID_SUBJECT_DIR_ATTRS: &'static str = "2.5.29.9"; +pub const szOID_PKIX_KP: &'static str = "1.3.6.1.5.5.7.3"; +pub const szOID_PKIX_KP_SERVER_AUTH: &'static str = "1.3.6.1.5.5.7.3.1"; +pub const szOID_PKIX_KP_CLIENT_AUTH: &'static str = "1.3.6.1.5.5.7.3.2"; +pub const szOID_PKIX_KP_CODE_SIGNING: &'static str = "1.3.6.1.5.5.7.3.3"; +pub const szOID_PKIX_KP_EMAIL_PROTECTION: &'static str = "1.3.6.1.5.5.7.3.4"; +pub const szOID_PKIX_KP_IPSEC_END_SYSTEM: &'static str = "1.3.6.1.5.5.7.3.5"; +pub const szOID_PKIX_KP_IPSEC_TUNNEL: &'static str = "1.3.6.1.5.5.7.3.6"; +pub const szOID_PKIX_KP_IPSEC_USER: &'static str = "1.3.6.1.5.5.7.3.7"; +pub const szOID_PKIX_KP_TIMESTAMP_SIGNING: &'static str = "1.3.6.1.5.5.7.3.8"; +pub const szOID_PKIX_KP_OCSP_SIGNING: &'static str = "1.3.6.1.5.5.7.3.9"; +pub const szOID_PKIX_OCSP_NOCHECK: &'static str = "1.3.6.1.5.5.7.48.1.5"; +pub const szOID_PKIX_OCSP_NONCE: &'static str = "1.3.6.1.5.5.7.48.1.2"; +pub const szOID_IPSEC_KP_IKE_INTERMEDIATE: &'static str = "1.3.6.1.5.5.8.2.2"; +pub const szOID_PKINIT_KP_KDC: &'static str = "1.3.6.1.5.2.3.5"; +pub const szOID_KP_CTL_USAGE_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.1"; +pub const szOID_KP_TIME_STAMP_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.2"; +pub const szOID_SERVER_GATED_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.3"; +pub const szOID_SGC_NETSCAPE: &'static str = "2.16.840.1.113730.4.1"; +pub const szOID_KP_EFS: &'static str = "1.3.6.1.4.1.311.10.3.4"; +pub const szOID_EFS_RECOVERY: &'static str = "1.3.6.1.4.1.311.10.3.4.1"; +pub const szOID_WHQL_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.5"; +pub const szOID_NT5_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.6"; +pub const szOID_OEM_WHQL_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.7"; +pub const szOID_EMBEDDED_NT_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.8"; +pub const szOID_ROOT_LIST_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.9"; +pub const szOID_KP_QUALIFIED_SUBORDINATION: &'static str = "1.3.6.1.4.1.311.10.3.10"; +pub const szOID_KP_KEY_RECOVERY: &'static str = "1.3.6.1.4.1.311.10.3.11"; +pub const szOID_KP_DOCUMENT_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.12"; +pub const szOID_KP_LIFETIME_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.13"; +pub const szOID_KP_MOBILE_DEVICE_SOFTWARE: &'static str = "1.3.6.1.4.1.311.10.3.14"; +pub const szOID_KP_SMART_DISPLAY: &'static str = "1.3.6.1.4.1.311.10.3.15"; +pub const szOID_KP_CSP_SIGNATURE: &'static str = "1.3.6.1.4.1.311.10.3.16"; +pub const szOID_DRM: &'static str = "1.3.6.1.4.1.311.10.5.1"; +pub const szOID_DRM_INDIVIDUALIZATION: &'static str = "1.3.6.1.4.1.311.10.5.2"; +pub const szOID_LICENSES: &'static str = "1.3.6.1.4.1.311.10.6.1"; +pub const szOID_LICENSE_SERVER: &'static str = "1.3.6.1.4.1.311.10.6.2"; +pub const szOID_KP_SMARTCARD_LOGON: &'static str = "1.3.6.1.4.1.311.20.2.2"; +pub const szOID_KP_KERNEL_MODE_CODE_SIGNING: &'static str = "1.3.6.1.4.1.311.61.1.1"; +pub const szOID_KP_KERNEL_MODE_TRUSTED_BOOT_SIGNING: &'static str = "1.3.6.1.4.1.311.61.4.1"; +pub const szOID_REVOKED_LIST_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.19"; +pub const szOID_WINDOWS_KITS_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.20"; +pub const szOID_WINDOWS_RT_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.21"; +pub const szOID_PROTECTED_PROCESS_LIGHT_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.22"; +pub const szOID_WINDOWS_TCB_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.23"; +pub const szOID_PROTECTED_PROCESS_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.24"; +pub const szOID_WINDOWS_THIRD_PARTY_COMPONENT_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.25"; +pub const szOID_WINDOWS_SOFTWARE_EXTENSION_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.26"; +pub const szOID_DISALLOWED_LIST: &'static str = "1.3.6.1.4.1.311.10.3.30"; +pub const szOID_SYNC_ROOT_CTL_EXT: &'static str = "1.3.6.1.4.1.311.10.3.50"; +pub const szOID_KP_KERNEL_MODE_HAL_EXTENSION_SIGNING: &'static str = "1.3.6.1.4.1.311.61.5.1"; +pub const szOID_WINDOWS_STORE_SIGNER: &'static str = "1.3.6.1.4.1.311.76.3.1"; +pub const szOID_DYNAMIC_CODE_GEN_SIGNER: &'static str = "1.3.6.1.4.1.311.76.5.1"; +pub const szOID_MICROSOFT_PUBLISHER_SIGNER: &'static str = "1.3.6.1.4.1.311.76.8.1"; +pub const szOID_YESNO_TRUST_ATTR: &'static str = "1.3.6.1.4.1.311.10.4.1"; +pub const szOID_PKIX_POLICY_QUALIFIER_CPS: &'static str = "1.3.6.1.5.5.7.2.1"; +pub const szOID_PKIX_POLICY_QUALIFIER_USERNOTICE: &'static str = "1.3.6.1.5.5.7.2.2"; +pub const szOID_ROOT_PROGRAM_FLAGS: &'static str = "1.3.6.1.4.1.311.60.1.1"; +//6992 +pub type HCRYPTMSG = *mut ::c_void; +//9353 +pub type HCERTSTORE = *mut ::c_void; +STRUCT!{struct CERT_CONTEXT { + dwCertEncodingType: ::DWORD, + pbCertEncoded: *mut ::BYTE, + cbCertEncoded: ::DWORD, + pCertInfo: ::PCERT_INFO, + hCertStore: HCERTSTORE, +}} +pub type PCERT_CONTEXT = *mut CERT_CONTEXT; +pub type PCCERT_CONTEXT = *const CERT_CONTEXT; +STRUCT!{struct CRL_CONTEXT { + dwCertEncodingType: ::DWORD, + pbCrlEncoded: *mut ::BYTE, + cbCrlEncoded: ::DWORD, + pCrlInfo: ::PCRL_INFO, + hCertStore: HCERTSTORE, +}} +pub type PCRL_CONTEXT = *mut CRL_CONTEXT; +pub type PCCRL_CONTEXT = *const CRL_CONTEXT; +STRUCT!{struct CTL_CONTEXT { + dwMsgAndCertEncodingType: ::DWORD, + pbCtlEncoded: *mut ::BYTE, + cbCtlEncoded: ::DWORD, + pCtlInfo: ::PCTL_INFO, + hCertStore: HCERTSTORE, + hCryptMsg: HCRYPTMSG, + pbCtlContent: *mut ::BYTE, + cbCtlContent: ::DWORD, +}} +pub type PCTL_CONTEXT = *mut CTL_CONTEXT; +pub type PCCTL_CONTEXT = *const CTL_CONTEXT; +pub const CERT_STORE_PROV_MSG: ::DWORD = 1; +pub const CERT_STORE_PROV_MEMORY: ::DWORD = 2; +pub const CERT_STORE_PROV_FILE: ::DWORD = 3; +pub const CERT_STORE_PROV_REG: ::DWORD = 4; +pub const CERT_STORE_PROV_PKCS7: ::DWORD = 5; +pub const CERT_STORE_PROV_SERIALIZED: ::DWORD = 6; +pub const CERT_STORE_PROV_FILENAME_A: ::DWORD = 7; +pub const CERT_STORE_PROV_FILENAME_W: ::DWORD = 8; +pub const CERT_STORE_PROV_FILENAME: ::DWORD = CERT_STORE_PROV_FILENAME_W; +pub const CERT_STORE_PROV_SYSTEM_A: ::DWORD = 9; +pub const CERT_STORE_PROV_SYSTEM_W: ::DWORD = 10; +pub const CERT_STORE_PROV_SYSTEM: ::DWORD = CERT_STORE_PROV_SYSTEM_W; +pub const CERT_STORE_PROV_COLLECTION: ::DWORD = 11; +pub const CERT_STORE_PROV_SYSTEM_REGISTRY_A: ::DWORD = 12; +pub const CERT_STORE_PROV_SYSTEM_REGISTRY_W: ::DWORD = 13; +pub const CERT_STORE_PROV_SYSTEM_REGISTRY: ::DWORD = CERT_STORE_PROV_SYSTEM_REGISTRY_W; +pub const CERT_STORE_PROV_PHYSICAL_W: ::DWORD = 14; +pub const CERT_STORE_PROV_PHYSICAL: ::DWORD = CERT_STORE_PROV_PHYSICAL_W; +pub const CERT_STORE_PROV_SMART_CARD_W: ::DWORD = 15; +pub const CERT_STORE_PROV_SMART_CARD: ::DWORD = CERT_STORE_PROV_SMART_CARD_W; +pub const CERT_STORE_PROV_LDAP_W: ::DWORD = 16; +pub const CERT_STORE_PROV_LDAP: ::DWORD = CERT_STORE_PROV_LDAP_W; +pub const CERT_STORE_NO_CRYPT_RELEASE_FLAG: ::DWORD = 0x00000001; +pub const CERT_STORE_SET_LOCALIZED_NAME_FLAG: ::DWORD = 0x00000002; +pub const CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG: ::DWORD = 0x00000004; +pub const CERT_STORE_DELETE_FLAG: ::DWORD = 0x00000010; +pub const CERT_STORE_SHARE_STORE_FLAG: ::DWORD = 0x00000040; +pub const CERT_STORE_SHARE_CONTEXT_FLAG: ::DWORD = 0x00000080; +pub const CERT_STORE_MANIFOLD_FLAG: ::DWORD = 0x00000100; +pub const CERT_STORE_ENUM_ARCHIVED_FLAG: ::DWORD = 0x00000200; +pub const CERT_STORE_UPDATE_KEYID_FLAG: ::DWORD = 0x00000400; +pub const CERT_STORE_BACKUP_RESTORE_FLAG: ::DWORD = 0x00000800; +pub const CERT_STORE_READONLY_FLAG: ::DWORD = 0x00008000; +pub const CERT_STORE_OPEN_EXISTING_FLAG: ::DWORD = 0x00004000; +pub const CERT_STORE_CREATE_NEW_FLAG: ::DWORD = 0x00002000; +pub const CERT_STORE_MAXIMUM_ALLOWED_FLAG: ::DWORD = 0x00001000; +pub const CERT_SYSTEM_STORE_UNPROTECTED_FLAG: ::DWORD = 0x40000000; +pub const CERT_SYSTEM_STORE_LOCATION_MASK: ::DWORD = 0x00FF0000; +pub const CERT_SYSTEM_STORE_LOCATION_SHIFT: ::DWORD = 16; +pub const CERT_SYSTEM_STORE_CURRENT_USER_ID: ::DWORD = 1; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_ID: ::DWORD = 2; +pub const CERT_SYSTEM_STORE_CURRENT_SERVICE_ID: ::DWORD = 4; +pub const CERT_SYSTEM_STORE_SERVICES_ID: ::DWORD = 5; +pub const CERT_SYSTEM_STORE_USERS_ID: ::DWORD = 6; +pub const CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID: ::DWORD = 7; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID: ::DWORD = 8; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID: ::DWORD = 9; +pub const CERT_SYSTEM_STORE_CURRENT_USER: ::DWORD = CERT_SYSTEM_STORE_CURRENT_USER_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE: ::DWORD = CERT_SYSTEM_STORE_LOCAL_MACHINE_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_CURRENT_SERVICE: ::DWORD = CERT_SYSTEM_STORE_CURRENT_SERVICE_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_SERVICES: ::DWORD = CERT_SYSTEM_STORE_SERVICES_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_USERS: ::DWORD = CERT_SYSTEM_STORE_USERS_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY: ::DWORD = + CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY: ::DWORD = + CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE: ::DWORD = + CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_NAME_EMAIL_TYPE: ::DWORD = 1; +pub const CERT_NAME_RDN_TYPE: ::DWORD = 2; +pub const CERT_NAME_ATTR_TYPE: ::DWORD = 3; +pub const CERT_NAME_SIMPLE_DISPLAY_TYPE: ::DWORD = 4; +pub const CERT_NAME_FRIENDLY_DISPLAY_TYPE: ::DWORD = 5; +pub const CERT_NAME_DNS_TYPE: ::DWORD = 6; +pub const CERT_NAME_URL_TYPE: ::DWORD = 7; +pub const CERT_NAME_UPN_TYPE: ::DWORD = 8; +pub const CERT_SIMPLE_NAME_STR: ::DWORD = 1; +pub const CERT_OID_NAME_STR: ::DWORD = 2; +pub const CERT_X500_NAME_STR: ::DWORD = 3; + +pub const CERT_NAME_STR_SEMICOLON_FLAG: ::DWORD = 0x40000000; +pub const CERT_NAME_STR_NO_PLUS_FLAG: ::DWORD = 0x20000000; +pub const CERT_NAME_STR_NO_QUOTING_FLAG: ::DWORD = 0x10000000; +pub const CERT_NAME_STR_CRLF_FLAG: ::DWORD = 0x08000000; +pub const CERT_NAME_STR_COMMA_FLAG: ::DWORD = 0x04000000; +pub const CERT_NAME_STR_REVERSE_FLAG: ::DWORD = 0x02000000; + +pub const CERT_NAME_ISSUER_FLAG: ::DWORD = 0x1; +pub const CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG: ::DWORD = 0x00010000; +pub const CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG: ::DWORD = 0x00020000; +pub const CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG: ::DWORD = 0x00040000; +pub const CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG: ::DWORD = 0x00080000; +pub const CERT_DELETE_KEYSET_PROP_ID: ::DWORD = 101; +pub const CERT_COMPARE_MASK: ::DWORD = 0xFFFF; +pub const CERT_COMPARE_SHIFT: ::DWORD = 16; +pub const CERT_COMPARE_ANY: ::DWORD = 0; +pub const CERT_COMPARE_SHA1_HASH: ::DWORD = 1; +pub const CERT_COMPARE_NAME: ::DWORD = 2; +pub const CERT_COMPARE_ATTR: ::DWORD = 3; +pub const CERT_COMPARE_MD5_HASH: ::DWORD = 4; +pub const CERT_COMPARE_PROPERTY: ::DWORD = 5; +pub const CERT_COMPARE_PUBLIC_KEY: ::DWORD = 6; +pub const CERT_COMPARE_HASH: ::DWORD = CERT_COMPARE_SHA1_HASH; +pub const CERT_COMPARE_NAME_STR_A: ::DWORD = 7; +pub const CERT_COMPARE_NAME_STR_W: ::DWORD = 8; +pub const CERT_COMPARE_KEY_SPEC: ::DWORD = 9; +pub const CERT_COMPARE_ENHKEY_USAGE: ::DWORD = 10; +pub const CERT_COMPARE_CTL_USAGE: ::DWORD = CERT_COMPARE_ENHKEY_USAGE; +pub const CERT_COMPARE_SUBJECT_CERT: ::DWORD = 11; +pub const CERT_COMPARE_ISSUER_OF: ::DWORD = 12; +pub const CERT_COMPARE_EXISTING: ::DWORD = 13; +pub const CERT_COMPARE_SIGNATURE_HASH: ::DWORD = 14; +pub const CERT_COMPARE_KEY_IDENTIFIER: ::DWORD = 15; +pub const CERT_COMPARE_CERT_ID: ::DWORD = 16; +pub const CERT_COMPARE_CROSS_CERT_DIST_POINTS: ::DWORD = 17; +pub const CERT_COMPARE_PUBKEY_MD5_HASH: ::DWORD = 18; +pub const CERT_FIND_ANY: ::DWORD = CERT_COMPARE_ANY << CERT_COMPARE_SHIFT; +pub const CERT_FIND_SHA1_HASH: ::DWORD = CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT; +pub const CERT_FIND_MD5_HASH: ::DWORD = CERT_COMPARE_MD5_HASH << CERT_COMPARE_SHIFT; +pub const CERT_FIND_SIGNATURE_HASH: ::DWORD = CERT_COMPARE_SIGNATURE_HASH << CERT_COMPARE_SHIFT; +pub const CERT_FIND_KEY_IDENTIFIER: ::DWORD = CERT_COMPARE_KEY_IDENTIFIER << CERT_COMPARE_SHIFT; +pub const CERT_FIND_HASH: ::DWORD = CERT_FIND_SHA1_HASH; +pub const CERT_FIND_PROPERTY: ::DWORD = CERT_COMPARE_PROPERTY << CERT_COMPARE_SHIFT; +pub const CERT_FIND_PUBLIC_KEY: ::DWORD = CERT_COMPARE_PUBLIC_KEY << CERT_COMPARE_SHIFT; +pub const CERT_FIND_SUBJECT_NAME: ::DWORD = (CERT_COMPARE_NAME << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_SUBJECT_ATTR: ::DWORD = (CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_ISSUER_NAME: ::DWORD = (CERT_COMPARE_NAME << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_ISSUER_ATTR: ::DWORD = (CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_SUBJECT_STR_A: ::DWORD = (CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_SUBJECT_STR_W: ::DWORD = (CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_SUBJECT_STR: ::DWORD = CERT_FIND_SUBJECT_STR_W; +pub const CERT_FIND_ISSUER_STR_A: ::DWORD = (CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_ISSUER_STR_W: ::DWORD = (CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_ISSUER_STR: ::DWORD = CERT_FIND_ISSUER_STR_W; +pub const CERT_FIND_KEY_SPEC: ::DWORD = CERT_COMPARE_KEY_SPEC << CERT_COMPARE_SHIFT; +pub const CERT_FIND_ENHKEY_USAGE: ::DWORD = CERT_COMPARE_ENHKEY_USAGE << CERT_COMPARE_SHIFT; +pub const CERT_FIND_CTL_USAGE: ::DWORD = CERT_FIND_ENHKEY_USAGE; +pub const CERT_FIND_SUBJECT_CERT: ::DWORD = CERT_COMPARE_SUBJECT_CERT << CERT_COMPARE_SHIFT; +pub const CERT_FIND_ISSUER_OF: ::DWORD = CERT_COMPARE_ISSUER_OF << CERT_COMPARE_SHIFT; +pub const CERT_FIND_EXISTING: ::DWORD = CERT_COMPARE_EXISTING << CERT_COMPARE_SHIFT; +pub const CERT_FIND_CERT_ID: ::DWORD = CERT_COMPARE_CERT_ID << CERT_COMPARE_SHIFT; +pub const CERT_FIND_CROSS_CERT_DIST_POINTS: ::DWORD = CERT_COMPARE_CROSS_CERT_DIST_POINTS + << CERT_COMPARE_SHIFT; +pub const CERT_FIND_PUBKEY_MD5_HASH: ::DWORD = CERT_COMPARE_PUBKEY_MD5_HASH << CERT_COMPARE_SHIFT; +pub const CERT_ENCIPHER_ONLY_KEY_USAGE: ::DWORD = 0x0001; +pub const CERT_CRL_SIGN_KEY_USAGE: ::DWORD = 0x0002; +pub const CERT_KEY_CERT_SIGN_KEY_USAGE: ::DWORD = 0x0004; +pub const CERT_KEY_AGREEMENT_KEY_USAGE: ::DWORD = 0x0008; +pub const CERT_DATA_ENCIPHERMENT_KEY_USAGE: ::DWORD = 0x0010; +pub const CERT_KEY_ENCIPHERMENT_KEY_USAGE: ::DWORD = 0x0020; +pub const CERT_NON_REPUDIATION_KEY_USAGE: ::DWORD = 0x0040; +pub const CERT_DIGITAL_SIGNATURE_KEY_USAGE: ::DWORD = 0x0080; +pub const CERT_DECIPHER_ONLY_KEY_USAGE: ::DWORD = 0x8000; +pub const CERT_STORE_ADD_NEW: ::DWORD = 1; +pub const CERT_STORE_ADD_USE_EXISTING: ::DWORD = 2; +pub const CERT_STORE_ADD_REPLACE_EXISTING: ::DWORD = 3; +pub const CERT_STORE_ADD_ALWAYS: ::DWORD = 4; +pub const CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: ::DWORD = 5; +pub const CERT_STORE_ADD_NEWER: ::DWORD = 6; +pub const CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES: ::DWORD = 7; +pub const CERT_STORE_SAVE_AS_STORE: ::DWORD = 1; +pub const CERT_STORE_SAVE_AS_PKCS7: ::DWORD = 2; +pub const CERT_STORE_SAVE_TO_FILE: ::DWORD = 1; +pub const CERT_STORE_SAVE_TO_MEMORY: ::DWORD = 2; +pub const CERT_STORE_SAVE_TO_FILENAME_A: ::DWORD = 3; +pub const CERT_STORE_SAVE_TO_FILENAME_W: ::DWORD = 4; +pub const CERT_STORE_SAVE_TO_FILENAME: ::DWORD = CERT_STORE_SAVE_TO_FILENAME_W; +pub const CERT_CA_SUBJECT_FLAG: ::DWORD = 0x80; +pub const CERT_END_ENTITY_SUBJECT_FLAG: ::DWORD = 0x40; +pub const CERT_CHAIN_POLICY_BASE: ::DWORD = 1; +pub const CERT_CHAIN_POLICY_AUTHENTICODE: ::DWORD = 2; +pub const CERT_CHAIN_POLICY_AUTHENTICODE_TS: ::DWORD = 3; +pub const CERT_CHAIN_POLICY_SSL: ::DWORD = 4; +pub const CERT_CHAIN_POLICY_BASIC_CONSTRAINTS: ::DWORD = 5; +pub const CERT_CHAIN_POLICY_NT_AUTH: ::DWORD = 6; +pub const CERT_CHAIN_POLICY_MICROSOFT_ROOT: ::DWORD = 7; +pub const CERT_CHAIN_REVOCATION_CHECK_END_CERT: ::DWORD = 0x10000000; +pub const CERT_CHAIN_REVOCATION_CHECK_CHAIN: ::DWORD = 0x20000000; +pub const CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT: ::DWORD = 0x40000000; +pub const CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY: ::DWORD = 0x80000000; +pub const CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT: ::DWORD = 0x08000000; +pub const CERT_TRUST_NO_ERROR: ::DWORD = 0x00000000; +pub const CERT_TRUST_IS_NOT_TIME_VALID: ::DWORD = 0x00000001; +pub const CERT_TRUST_IS_NOT_TIME_NESTED: ::DWORD = 0x00000002; +pub const CERT_TRUST_IS_REVOKED: ::DWORD = 0x00000004; +pub const CERT_TRUST_IS_NOT_SIGNATURE_VALID: ::DWORD = 0x00000008; +pub const CERT_TRUST_IS_NOT_VALID_FOR_USAGE: ::DWORD = 0x00000010; +pub const CERT_TRUST_IS_UNTRUSTED_ROOT: ::DWORD = 0x00000020; +pub const CERT_TRUST_REVOCATION_STATUS_UNKNOWN: ::DWORD = 0x00000040; +pub const CERT_TRUST_IS_CYCLIC: ::DWORD = 0x00000080; + +pub const CERT_TRUST_INVALID_EXTENSION: ::DWORD = 0x00000100; +pub const CERT_TRUST_INVALID_POLICY_CONSTRAINTS: ::DWORD = 0x00000200; +pub const CERT_TRUST_INVALID_BASIC_CONSTRAINTS: ::DWORD = 0x00000400; +pub const CERT_TRUST_INVALID_NAME_CONSTRAINTS: ::DWORD = 0x00000800; +pub const CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT: ::DWORD = 0x00001000; +pub const CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT: ::DWORD = 0x00002000; +pub const CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT: ::DWORD = 0x00004000; +pub const CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT: ::DWORD = 0x00008000; + +pub const CERT_TRUST_IS_OFFLINE_REVOCATION: ::DWORD = 0x01000000; +pub const CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY: ::DWORD = 0x02000000; +pub const CERT_TRUST_IS_PARTIAL_CHAIN: ::DWORD = 0x00010000; +pub const CERT_TRUST_CTL_IS_NOT_TIME_VALID: ::DWORD = 0x00020000; +pub const CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID: ::DWORD = 0x00040000; +pub const CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE: ::DWORD = 0x00080000; +pub const CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG: ::DWORD = 0x00000001; +pub const CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG: ::DWORD = 0x00000002; +pub const CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG: ::DWORD = 0x00000004; +pub const CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG: ::DWORD = 0x00000008; + +pub const CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG: ::DWORD = 0x00000010; +pub const CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG: ::DWORD = 0x00000020; +pub const CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG: ::DWORD = 0x00000040; +pub const CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG: ::DWORD = 0x00000080; + +pub const CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG: ::DWORD = 0x00000100; +pub const CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG: ::DWORD = 0x00000200; +pub const CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG: ::DWORD = 0x00000400; +pub const CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG: ::DWORD = 0x00000800; + +pub const CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS: ::DWORD = + CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG | + CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG | + CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG | + CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG; +pub const CERT_TRUST_HAS_EXACT_MATCH_ISSUER: ::DWORD = 0x00000001; +pub const CERT_TRUST_HAS_KEY_MATCH_ISSUER: ::DWORD = 0x00000002; +pub const CERT_TRUST_HAS_NAME_MATCH_ISSUER: ::DWORD = 0x00000004; +pub const CERT_TRUST_IS_SELF_SIGNED: ::DWORD = 0x00000008; +pub const CERT_TRUST_HAS_PREFERRED_ISSUER: ::DWORD = 0x00000100; +pub const CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY: ::DWORD = 0x00000200; +pub const CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS: ::DWORD = 0x00000400; +pub const CERT_TRUST_IS_COMPLEX_CHAIN: ::DWORD = 0x00010000; +pub const CERT_ALT_NAME_OTHER_NAME: ::DWORD = 1; +pub const CERT_ALT_NAME_RFC822_NAME: ::DWORD = 2; +pub const CERT_ALT_NAME_DNS_NAME: ::DWORD = 3; +pub const CERT_ALT_NAME_X400_ADDRESS: ::DWORD = 4; +pub const CERT_ALT_NAME_DIRECTORY_NAME: ::DWORD = 5; +pub const CERT_ALT_NAME_EDI_PARTY_NAME: ::DWORD = 6; +pub const CERT_ALT_NAME_URL: ::DWORD = 7; +pub const CERT_ALT_NAME_IP_ADDRESS: ::DWORD = 8; +pub const CERT_ALT_NAME_REGISTERED_ID: ::DWORD = 9; +pub const CERT_STORE_CTRL_RESYNC: ::DWORD = 1; +pub const CERT_STORE_CTRL_NOTIFY_CHANGE: ::DWORD = 2; +pub const CERT_STORE_CTRL_COMMIT: ::DWORD = 3; +pub const CERT_STORE_CTRL_AUTO_RESYNC: ::DWORD = 4; +pub const CERT_STORE_CTRL_CANCEL_NOTIFY: ::DWORD = 5; +pub const CERT_ID_ISSUER_SERIAL_NUMBER: ::DWORD = 1; +pub const CERT_ID_KEY_IDENTIFIER: ::DWORD = 2; +pub const CERT_ID_SHA1_HASH: ::DWORD = 3; +pub const CERT_KEY_PROV_HANDLE_PROP_ID: ::DWORD = 1; +pub const CERT_KEY_PROV_INFO_PROP_ID: ::DWORD = 2; +pub const CERT_SHA1_HASH_PROP_ID: ::DWORD = 3; +pub const CERT_MD5_HASH_PROP_ID: ::DWORD = 4; +pub const CERT_HASH_PROP_ID: ::DWORD = CERT_SHA1_HASH_PROP_ID; +pub const CERT_KEY_CONTEXT_PROP_ID: ::DWORD = 5; +pub const CERT_KEY_SPEC_PROP_ID: ::DWORD = 6; +pub const CERT_IE30_RESERVED_PROP_ID: ::DWORD = 7; +pub const CERT_PUBKEY_HASH_RESERVED_PROP_ID: ::DWORD = 8; +pub const CERT_ENHKEY_USAGE_PROP_ID: ::DWORD = 9; +pub const CERT_CTL_USAGE_PROP_ID: ::DWORD = CERT_ENHKEY_USAGE_PROP_ID; +pub const CERT_NEXT_UPDATE_LOCATION_PROP_ID: ::DWORD = 10; +pub const CERT_FRIENDLY_NAME_PROP_ID: ::DWORD = 11; +pub const CERT_PVK_FILE_PROP_ID: ::DWORD = 12; +pub const CERT_DESCRIPTION_PROP_ID: ::DWORD = 13; +pub const CERT_ACCESS_STATE_PROP_ID: ::DWORD = 14; +pub const CERT_SIGNATURE_HASH_PROP_ID: ::DWORD = 15; +pub const CERT_SMART_CARD_DATA_PROP_ID: ::DWORD = 16; +pub const CERT_EFS_PROP_ID: ::DWORD = 17; +pub const CERT_FORTEZZA_DATA_PROP_ID: ::DWORD = 18; +pub const CERT_ARCHIVED_PROP_ID: ::DWORD = 19; +pub const CERT_KEY_IDENTIFIER_PROP_ID: ::DWORD = 20; +pub const CERT_AUTO_ENROLL_PROP_ID: ::DWORD = 21; +pub const CERT_PUBKEY_ALG_PARA_PROP_ID: ::DWORD = 22; +pub const CERT_CROSS_CERT_DIST_POINTS_PROP_ID: ::DWORD = 23; +pub const CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID: ::DWORD = 24; +pub const CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID: ::DWORD = 25; +pub const CERT_ENROLLMENT_PROP_ID: ::DWORD = 26; +pub const CERT_DATE_STAMP_PROP_ID: ::DWORD = 27; +pub const CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: ::DWORD = 28; +pub const CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: ::DWORD = 29; +pub const CERT_EXTENDED_ERROR_INFO_PROP_ID: ::DWORD = 30; +pub const CERT_RENEWAL_PROP_ID: ::DWORD = 64; +pub const CERT_ARCHIVED_KEY_HASH_PROP_ID: ::DWORD = 65; +pub const CERT_AUTO_ENROLL_RETRY_PROP_ID: ::DWORD = 66; +pub const CERT_AIA_URL_RETRIEVED_PROP_ID: ::DWORD = 67; +pub const CERT_AUTHORITY_INFO_ACCESS_PROP_ID: ::DWORD = 68; +pub const CERT_BACKED_UP_PROP_ID: ::DWORD = 69; +pub const CERT_OCSP_RESPONSE_PROP_ID: ::DWORD = 70; +pub const CERT_REQUEST_ORIGINATOR_PROP_ID: ::DWORD = 71; +pub const CERT_SOURCE_LOCATION_PROP_ID: ::DWORD = 72; +pub const CERT_SOURCE_URL_PROP_ID: ::DWORD = 73; +pub const CERT_NEW_KEY_PROP_ID: ::DWORD = 74; +pub const CERT_OCSP_CACHE_PREFIX_PROP_ID: ::DWORD = 75; +pub const CERT_SMART_CARD_ROOT_INFO_PROP_ID: ::DWORD = 76; +pub const CERT_NO_AUTO_EXPIRE_CHECK_PROP_ID: ::DWORD = 77; +pub const CERT_NCRYPT_KEY_HANDLE_PROP_ID: ::DWORD = 78; +pub const CERT_HCRYPTPROV_OR_NCRYPT_KEY_HANDLE_PROP_ID: ::DWORD = 79; +pub const CERT_SUBJECT_INFO_ACCESS_PROP_ID: ::DWORD = 80; +pub const CERT_CA_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: ::DWORD = 81; +pub const CERT_CA_DISABLE_CRL_PROP_ID: ::DWORD = 82; +pub const CERT_ROOT_PROGRAM_CERT_POLICIES_PROP_ID: ::DWORD = 83; +pub const CERT_ROOT_PROGRAM_NAME_CONSTRAINTS_PROP_ID: ::DWORD = 84; +pub const CERT_SUBJECT_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: ::DWORD = 85; +pub const CERT_SUBJECT_DISABLE_CRL_PROP_ID: ::DWORD = 86; +pub const CERT_CEP_PROP_ID: ::DWORD = 87; +pub const CERT_SIGN_HASH_CNG_ALG_PROP_ID: ::DWORD = 89; +pub const CERT_SCARD_PIN_ID_PROP_ID: ::DWORD = 90; +pub const CERT_SCARD_PIN_INFO_PROP_ID: ::DWORD = 91; +pub const CERT_SUBJECT_PUB_KEY_BIT_LENGTH_PROP_ID: ::DWORD = 92; +pub const CERT_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID: ::DWORD = 93; +pub const CERT_ISSUER_PUB_KEY_BIT_LENGTH_PROP_ID: ::DWORD = 94; +pub const CERT_ISSUER_CHAIN_SIGN_HASH_CNG_ALG_PROP_ID: ::DWORD = 95; +pub const CERT_ISSUER_CHAIN_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID: ::DWORD = 96; +pub const CERT_NO_EXPIRE_NOTIFICATION_PROP_ID: ::DWORD = 97; +pub const CERT_AUTH_ROOT_SHA256_HASH_PROP_ID: ::DWORD = 98; +pub const CERT_NCRYPT_KEY_HANDLE_TRANSFER_PROP_ID: ::DWORD = 99; +pub const CERT_HCRYPTPROV_TRANSFER_PROP_ID: ::DWORD = 100; +pub const CERT_SMART_CARD_READER_PROP_ID: ::DWORD = 101; +pub const CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID: ::DWORD = 102; +pub const CERT_KEY_REPAIR_ATTEMPTED_PROP_ID: ::DWORD = 103; +pub const CERT_DISALLOWED_FILETIME_PROP_ID: ::DWORD = 104; +pub const CERT_ROOT_PROGRAM_CHAIN_POLICIES_PROP_ID: ::DWORD = 105; +pub const CERT_SMART_CARD_READER_NON_REMOVABLE_PROP_ID: ::DWORD = 106; +pub const CERT_SHA256_HASH_PROP_ID: ::DWORD = 107; +pub const CERT_SCEP_SERVER_CERTS_PROP_ID: ::DWORD = 108; +pub const CERT_SCEP_RA_SIGNATURE_CERT_PROP_ID: ::DWORD = 109; +pub const CERT_SCEP_RA_ENCRYPTION_CERT_PROP_ID: ::DWORD = 110; +pub const CERT_SCEP_CA_CERT_PROP_ID: ::DWORD = 111; +pub const CERT_SCEP_SIGNER_CERT_PROP_ID: ::DWORD = 112; +pub const CERT_SCEP_NONCE_PROP_ID: ::DWORD = 113; +pub const CERT_SCEP_ENCRYPT_HASH_CNG_ALG_PROP_ID: ::DWORD = 114; +pub const CERT_SCEP_FLAGS_PROP_ID: ::DWORD = 115; +pub const CERT_SCEP_GUID_PROP_ID: ::DWORD = 116; +pub const CERT_SERIALIZABLE_KEY_CONTEXT_PROP_ID: ::DWORD = 117; +pub const CERT_ISOLATED_KEY_PROP_ID: ::DWORD = 118; +pub const CERT_FIRST_RESERVED_PROP_ID: ::DWORD = 119; +pub const CERT_LAST_RESERVED_PROP_ID: ::DWORD = 0x00007FFF; +pub const CERT_FIRST_USER_PROP_ID: ::DWORD = 0x00008000; +pub const CERT_LAST_USER_PROP_ID: ::DWORD = 0x0000FFFF; +pub const szOID_CERT_PROP_ID_PREFIX: &'static str = "1.3.6.1.4.1.311.10.11."; +pub const szOID_CERT_KEY_IDENTIFIER_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.20"; +pub const szOID_CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: &'static str + = "1.3.6.1.4.1.311.10.11.28"; +pub const szOID_CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.29"; +pub const szOID_CERT_MD5_HASH_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.4"; +pub const szOID_CERT_SIGNATURE_HASH_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.15"; +pub const szOID_DISALLOWED_HASH: &'static str = szOID_CERT_SIGNATURE_HASH_PROP_ID; +pub const szOID_CERT_DISALLOWED_FILETIME_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.104"; +pub const CERT_ACCESS_STATE_WRITE_PERSIST_FLAG: ::DWORD = 0x1; +pub const CERT_ACCESS_STATE_SYSTEM_STORE_FLAG: ::DWORD = 0x2; +pub const CERT_ACCESS_STATE_LM_SYSTEM_STORE_FLAG: ::DWORD = 0x4; +pub const CERT_ACCESS_STATE_GP_SYSTEM_STORE_FLAG: ::DWORD = 0x8; +pub const CERT_ACCESS_STATE_SHARED_USER_FLAG: ::DWORD = 0x10; +pub const szOID_ROOT_PROGRAM_AUTO_UPDATE_CA_REVOCATION: &'static str = "1.3.6.1.4.1.311.60.3.1"; +pub const szOID_ROOT_PROGRAM_AUTO_UPDATE_END_REVOCATION: &'static str = "1.3.6.1.4.1.311.60.3.2"; +pub const szOID_ROOT_PROGRAM_NO_OCSP_FAILOVER_TO_CRL: &'static str = "1.3.6.1.4.1.311.60.3.3"; +STRUCT!{struct CRYPT_KEY_PROV_PARAM { + dwParam: ::DWORD, + pbData: *mut ::BYTE, + cbData: ::DWORD, + dwFlags: ::DWORD, +}} +pub type PCRYPT_KEY_PROV_PARAM = *mut CRYPT_KEY_PROV_PARAM; +STRUCT!{struct CRYPT_KEY_PROV_INFO { + pwszContainerName: ::LPWSTR, + pwszProvName: ::LPWSTR, + dwProvType: ::DWORD, + dwFlags: ::DWORD, + cProvParam: ::DWORD, + rgProvParam: PCRYPT_KEY_PROV_PARAM, + dwKeySpec: ::DWORD, +}} +pub type PCRYPT_KEY_PROV_INFO = *mut CRYPT_KEY_PROV_INFO; +pub const CERT_SET_KEY_PROV_HANDLE_PROP_ID: ::DWORD = 0x00000001; +pub const CERT_SET_KEY_CONTEXT_PROP_ID: ::DWORD = 0x00000001; +pub const CERT_NCRYPT_KEY_SPEC: ::DWORD = 0xFFFFFFFF; +//20213 +pub type HCERT_SERVER_OCSP_RESPONSE = *mut ::c_void; +STRUCT!{struct CERT_SERVER_OCSP_RESPONSE_CONTEXT { + cbSize: ::DWORD, + pbEncodedOcspResponse: *mut ::BYTE, + cbEncodedOcspResponse: ::DWORD, +}} +pub type PCERT_SERVER_OCSP_RESPONSE_CONTEXT = *mut CERT_SERVER_OCSP_RESPONSE_CONTEXT; +pub type PCCERT_SERVER_OCSP_RESPONSE_CONTEXT = *const CERT_SERVER_OCSP_RESPONSE_CONTEXT; + +pub const CERT_CHAIN_CACHE_END_CERT: ::DWORD = 0x00000001; +pub const CERT_CHAIN_THREAD_STORE_SYNC: ::DWORD = 0x00000002; +pub const CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL: ::DWORD = 0x00000004; +pub const CERT_CHAIN_USE_LOCAL_MACHINE_STORE: ::DWORD = 0x00000008; +pub const CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE: ::DWORD = 0x00000010; +pub const CERT_CHAIN_ENABLE_SHARE_STORE: ::DWORD = 0x00000020; + +STRUCT!{struct CERT_CHAIN_ENGINE_CONFIG { + cbSize: ::DWORD, + hRestrictedRoot: HCERTSTORE, + hRestrictedTrust: HCERTSTORE, + hRestrictedOther: HCERTSTORE, + cAdditionalStore: ::DWORD, + rghAdditionalStore: *mut HCERTSTORE, + dwFlags: ::DWORD, + dwUrlRetrievalTimeout: ::DWORD, + MaximumCachedCertificates: ::DWORD, + CycleDetectionModulus: ::DWORD, + // #if (NTDDI_VERSION >= NTDDI_WIN7) + hExclusiveRoot: HCERTSTORE, + hExclusiveTrustedPeople: HCERTSTORE, + // #if (NTDDI_VERSION >= NTDDI_WIN8) + dwExclusiveFlags: ::DWORD, +}} +pub type PCERT_CHAIN_ENGINE_CONFIG = *mut CERT_CHAIN_ENGINE_CONFIG; +// 18748 +pub type HCERTCHAINENGINE = ::HANDLE; +pub type PFN_CERT_CREATE_CONTEXT_SORT_FUNC = Option<unsafe extern "system" fn( + cbTotalEncoded: ::DWORD, cbRemainEncoded: ::DWORD, cEntry: ::DWORD, pvSort: *mut ::c_void +) -> ::BOOL>; +STRUCT!{nodebug struct CERT_CREATE_CONTEXT_PARA { + cbSize: ::DWORD, + pfnFree: PFN_CRYPT_FREE, + pvFree: *mut ::c_void, + pfnSort: PFN_CERT_CREATE_CONTEXT_SORT_FUNC, + pvSort: *mut ::c_void, +}} +pub type PCERT_CREATE_CONTEXT_PARA = *mut CERT_CREATE_CONTEXT_PARA; +STRUCT!{struct CERT_EXTENSIONS { + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCERT_EXTENSIONS = *mut CERT_EXTENSIONS; +STRUCT!{struct CERT_REVOCATION_CRL_INFO { + cbSize: ::DWORD, + pBaseCrlContext: PCCRL_CONTEXT, + pDeltaCrlContext: PCCRL_CONTEXT, + pCrlEntry: PCRL_ENTRY, + fDeltaCrlEntry: ::BOOL, +}} +pub type PCERT_REVOCATION_CRL_INFO = *mut CERT_REVOCATION_CRL_INFO; +STRUCT!{struct CERT_TRUST_STATUS { + dwErrorStatus: ::DWORD, + dwInfoStatus: ::DWORD, +}} +pub type PCERT_TRUST_STATUS = *mut CERT_TRUST_STATUS; +STRUCT!{struct CERT_REVOCATION_INFO { + cbSize: ::DWORD, + dwRevocationResult: ::DWORD, + pszRevocationOid: ::LPCSTR, + pvOidSpecificInfo: ::LPVOID, + fHasFreshnessTime: ::BOOL, + dwFreshnessTime: ::DWORD, + pCrlInfo: PCERT_REVOCATION_CRL_INFO, +}} +pub type PCERT_REVOCATION_INFO = *mut CERT_REVOCATION_INFO; +STRUCT!{struct CERT_TRUST_LIST_INFO { + cbSize: ::DWORD, + pCtlEntry: PCTL_ENTRY, + pCtlContext: PCCTL_CONTEXT, +}} +pub type PCERT_TRUST_LIST_INFO = *mut CERT_TRUST_LIST_INFO; +STRUCT!{struct CERT_CHAIN_ELEMENT { + cbSize: ::DWORD, + pCertContext: PCCERT_CONTEXT, + TrustStatus: CERT_TRUST_STATUS, + pRevocationInfo: PCERT_REVOCATION_INFO, + pIssuanceUsage: PCERT_ENHKEY_USAGE, + pApplicationUsage: PCERT_ENHKEY_USAGE, + pwszExtendedErrorInfo: ::LPWSTR, +}} +pub type PCERT_CHAIN_ELEMENT = *mut CERT_CHAIN_ELEMENT; +pub type PCCERT_CHAIN_ELEMENT = *const CERT_CHAIN_ELEMENT; +STRUCT!{struct CERT_SIMPLE_CHAIN { + cbSize: ::DWORD, + TrustStatus: CERT_TRUST_STATUS, + cElement: ::DWORD, + rgpElement: *mut PCERT_CHAIN_ELEMENT, + pTrustListInfo: PCERT_TRUST_LIST_INFO, + fHasRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, +}} +pub type PCERT_SIMPLE_CHAIN = *mut CERT_SIMPLE_CHAIN; +pub type PCCERT_SIMPLE_CHAIN = *const CERT_SIMPLE_CHAIN; +STRUCT!{struct CERT_CHAIN_CONTEXT { + cbSize: ::DWORD, + TrustStatus: CERT_TRUST_STATUS, + cChain: ::DWORD, + rgpChain: *mut PCERT_SIMPLE_CHAIN, + cLowerQualityChainContext: ::DWORD, + rgpLowerQualityChainContext: *mut PCCERT_CHAIN_CONTEXT, + fHasRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, + dwCreateFlags: ::DWORD, + ChainId: ::GUID, +}} +pub type PCERT_CHAIN_CONTEXT = *mut CERT_CHAIN_CONTEXT; +pub type PCCERT_CHAIN_CONTEXT = *const CERT_CHAIN_CONTEXT; +STRUCT!{struct CERT_PHYSICAL_STORE_INFO { + cbSize: ::DWORD, + pszOpenStoreProvider: ::LPSTR, + dwOpenEncodingType: ::DWORD, + dwOpenFlags: ::DWORD, + OpenParameters: CRYPT_DATA_BLOB, + dwFlags: ::DWORD, + dwPriority: ::DWORD, +}} +pub type PCERT_PHYSICAL_STORE_INFO = *mut CERT_PHYSICAL_STORE_INFO; +STRUCT!{struct CERT_SYSTEM_STORE_INFO { + cbSize: ::DWORD, +}} +pub type PCERT_SYSTEM_STORE_INFO = *mut CERT_SYSTEM_STORE_INFO; +//13401 +pub type PFN_CERT_ENUM_SYSTEM_STORE_LOCATION = Option<unsafe extern "system" fn( + pwszStoreLocation: ::LPCWSTR, dwFlags: ::DWORD, pvReserved: *mut ::c_void, pvArg: *mut ::c_void, +) -> ::BOOL>; +//13408 +pub type PFN_CERT_ENUM_SYSTEM_STORE = Option<unsafe extern "system" fn( + pvSystemStore: *const ::c_void, dwFlags: ::DWORD, pStoreInfo: PCERT_SYSTEM_STORE_INFO, + pvReserved: *mut ::c_void, pvArg: *mut ::c_void, +) -> ::BOOL>; +//13416 +pub type PFN_CERT_ENUM_PHYSICAL_STORE = Option<unsafe extern "system" fn( + pvSystemStore: *const ::c_void, dwFlags: ::DWORD, pwszStoreName: ::LPCWSTR, + pStoreInfo: PCERT_PHYSICAL_STORE_INFO, pvReserved: *mut ::c_void, pvArg: *mut ::c_void, +) -> ::BOOL>; +STRUCT!{struct CERT_STRONG_SIGN_SERIALIZED_INFO { + dwFlags: ::DWORD, + pwszCNGSignHashAlgids: ::LPWSTR, + pwszCNGPubKeyMinBitLengths: ::LPWSTR, +}} +pub type PCERT_STRONG_SIGN_SERIALIZED_INFO = *mut CERT_STRONG_SIGN_SERIALIZED_INFO; +STRUCT!{struct CERT_STRONG_SIGN_PARA { + cbSize: ::DWORD, + dwInfoChoice: ::DWORD, + pvInfo: *mut ::c_void, +}} +UNION!( + CERT_STRONG_SIGN_PARA, pvInfo, pSerializedInfo, pSerializedInfo_mut, + PCERT_STRONG_SIGN_SERIALIZED_INFO +); +UNION!(CERT_STRONG_SIGN_PARA, pvInfo, pszOID, pszOID_mut, ::LPSTR); +pub type PCERT_STRONG_SIGN_PARA = *mut CERT_STRONG_SIGN_PARA; +pub type PCCERT_STRONG_SIGN_PARA = *const CERT_STRONG_SIGN_PARA; +pub const USAGE_MATCH_TYPE_AND: ::DWORD = 0x00000000; +pub const USAGE_MATCH_TYPE_OR: ::DWORD = 0x00000001; +STRUCT!{struct CERT_USAGE_MATCH { + dwType: ::DWORD, + Usage: CERT_ENHKEY_USAGE, +}} +pub type PCERT_USAGE_MATCH = *mut CERT_USAGE_MATCH; +STRUCT!{struct CERT_CHAIN_PARA { + cbSize: ::DWORD, + RequestedUsage: CERT_USAGE_MATCH, + RequestedIssuancePolicy: CERT_USAGE_MATCH, + dwUrlRetrievalTimeout: ::DWORD, + fCheckRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, + pftCacheResync: ::LPFILETIME, + pStrongSignPara: PCCERT_STRONG_SIGN_PARA, + dwStrongSignFlags: ::DWORD, +}} +pub type PCERT_CHAIN_PARA = *mut CERT_CHAIN_PARA; +STRUCT!{struct CERT_SELECT_CHAIN_PARA { + hChainEngine: HCERTCHAINENGINE, + pTime: ::PFILETIME, + hAdditionalStore: HCERTSTORE, + pChainPara: PCERT_CHAIN_PARA, + dwFlags: ::DWORD, +}} +pub type PCERT_SELECT_CHAIN_PARA = *mut CERT_SELECT_CHAIN_PARA; +pub type PCCERT_SELECT_CHAIN_PARA = *const CERT_SELECT_CHAIN_PARA; +STRUCT!{struct CERT_SELECT_CRITERIA { + dwType: ::DWORD, + cPara: ::DWORD, + ppPara: *mut *mut ::c_void, +}} +pub type PCERT_SELECT_CRITERIA = *mut CERT_SELECT_CRITERIA; +pub type PCCERT_SELECT_CRITERIA = *const CERT_SELECT_CRITERIA; +STRUCT!{struct CTL_VERIFY_USAGE_PARA { + cbSize: ::DWORD, + ListIdentifier: CRYPT_DATA_BLOB, + cCtlStore: ::DWORD, + rghCtlStore: *mut HCERTSTORE, + cSignerStore: ::DWORD, + rghSignerStore: *mut HCERTSTORE, +}} +pub type PCTL_VERIFY_USAGE_PARA = *mut CTL_VERIFY_USAGE_PARA; +STRUCT!{struct CTL_VERIFY_USAGE_STATUS { + cbSize: ::DWORD, + dwError: ::DWORD, + dwFlags: ::DWORD, + ppCtl: *mut PCCTL_CONTEXT, + dwCtlEntryIndex: ::DWORD, + ppSigner: *mut PCCERT_CONTEXT, + dwSignerIndex: ::DWORD, +}} +pub type PCTL_VERIFY_USAGE_STATUS = *mut CTL_VERIFY_USAGE_STATUS; +STRUCT!{struct CERT_CHAIN_POLICY_PARA { + cbSize: ::DWORD, + dwFlags: ::DWORD, + pvExtraPolicyPara: *mut ::c_void, +}} +pub type PCERT_CHAIN_POLICY_PARA = *mut CERT_CHAIN_POLICY_PARA; +STRUCT!{struct CERT_CHAIN_POLICY_STATUS { + cbSize: ::DWORD, + dwError: ::DWORD, + lChainIndex: ::LONG, + lElementIndex: ::LONG, + pvExtraPolicyStatus: *mut ::c_void, +}} +pub type PCERT_CHAIN_POLICY_STATUS = *mut CERT_CHAIN_POLICY_STATUS; +STRUCT!{struct CERT_REVOCATION_CHAIN_PARA { + cbSize: ::DWORD, + hChainEngine: HCERTCHAINENGINE, + hAdditionalStore: HCERTSTORE, + dwChainFlags: ::DWORD, + dwUrlRetrievalTimeout: ::DWORD, + pftCurrentTime: ::LPFILETIME, + pftCacheResync: ::LPFILETIME, +}} +pub type PCERT_REVOCATION_CHAIN_PARA = *mut CERT_REVOCATION_CHAIN_PARA; +STRUCT!{struct CERT_REVOCATION_PARA { + cbSize: ::DWORD, + pIssuerCert: PCCERT_CONTEXT, + cCertStore: ::DWORD, + rgCertStore: *mut HCERTSTORE, + hCrlStore: HCERTSTORE, + pftTimeToUse: ::LPFILETIME, + dwUrlRetrievalTimeout: ::DWORD, + fCheckFreshnessTime: ::BOOL, + dwFreshnessTime: ::DWORD, + pftCurrentTime: ::LPFILETIME, + pCrlInfo: PCERT_REVOCATION_CRL_INFO, + pftCacheResync: ::LPFILETIME, + pChainPara: PCERT_REVOCATION_CHAIN_PARA, +}} +pub type PCERT_REVOCATION_PARA = *mut CERT_REVOCATION_PARA; +STRUCT!{struct CERT_REVOCATION_STATUS { + cbSize: ::DWORD, + dwIndex: ::DWORD, + dwError: ::DWORD, + dwReason: ::DWORD, + fHasFreshnessTime: ::BOOL, + dwFreshnessTime: ::DWORD, +}} +pub type PCERT_REVOCATION_STATUS = *mut CERT_REVOCATION_STATUS; +//16990 +pub type HCRYPTASYNC = ::HANDLE; +pub type PHCRYPTASYNC = *mut ::HANDLE; +STRUCT!{struct CRYPT_ENCRYPT_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, + ContentEncryptionAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvEncryptionAuxInfo: *mut ::c_void, + dwFlags: ::DWORD, + dwInnerContentType: ::DWORD, +}} +pub type PCRYPT_ENCRYPT_MESSAGE_PARA = *mut CRYPT_DECRYPT_MESSAGE_PARA; +STRUCT!{struct CRYPT_DECRYPT_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgAndCertEncodingType: ::DWORD, + cCertStore: ::DWORD, + rghCertStore: *mut HCERTSTORE, + dwFlags: ::DWORD, +}} +pub type PCRYPT_DECRYPT_MESSAGE_PARA = *mut CRYPT_DECRYPT_MESSAGE_PARA; +pub type PFN_CRYPT_GET_SIGNER_CERTIFICATE = Option<unsafe extern "system" fn( + pvGetArg: *mut ::c_void, dwCertEncodingType: ::DWORD, pSignerId: PCERT_INFO, + hMsgCertStore: HCERTSTORE, +) -> PCCERT_CONTEXT>; +STRUCT!{nodebug struct CRYPT_VERIFY_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgAndCertEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, + pfnGetSignerCertificate: PFN_CRYPT_GET_SIGNER_CERTIFICATE, + pvGetArg: *mut ::c_void, + pStrongSignPara: PCCERT_STRONG_SIGN_PARA, +}} +pub type PCRYPT_VERIFY_MESSAGE_PARA = *mut CRYPT_VERIFY_MESSAGE_PARA; +STRUCT!{struct CRYPT_OID_INFO { + cbSize: ::DWORD, + oszOID: ::LPCSTR, + pwszName: ::LPCWSTR, + dwGroupId: ::DWORD, + dwValue: ::DWORD, + ExtraInfo: CRYPT_DATA_BLOB, + pwszCNGAlgid: ::LPCWSTR, + pwszCNGExtraAlgid: ::LPCWSTR, +}} +UNION!(CRYPT_OID_INFO, dwValue, Algid, Algid_mut, ALG_ID); +UNION!(CRYPT_OID_INFO, dwValue, dwLength, dwLength_mut, ::DWORD); +pub type PCRYPT_OID_INFO = *mut CRYPT_OID_INFO; +pub type PCCRYPT_OID_INFO = *const CRYPT_OID_INFO; +//18004 +pub type PFN_CRYPT_ENUM_KEYID_PROP = Option<unsafe extern "system" fn( + pKeyIdentifier: *const CRYPT_HASH_BLOB, dwFlags: ::DWORD, pvReserved: *mut ::c_void, + pvArg: *mut ::c_void, cProp: ::DWORD, rgdwPropId: *mut ::DWORD, rgpvData: *mut *mut ::c_void, + rgcbData: *mut ::DWORD, +) -> ::BOOL>; +//6379 +pub type PFN_CRYPT_ENUM_OID_FUNC = Option<unsafe extern "system" fn( + dwEncodingType: ::DWORD, pszFuncName: ::LPCSTR, pszOID: ::LPCSTR, cValue: ::DWORD, + rgdwValueType: *const ::DWORD, rgpwszValueName: *const ::LPCWSTR, + rgpbValueData: *const *const ::BYTE, rgcbValueData: *const ::DWORD, pvArg: *mut ::c_void, +) -> ::BOOL>; +//6675 +pub type PFN_CRYPT_ENUM_OID_INFO = Option<unsafe extern "system" fn( + pInfo: PCCRYPT_OID_INFO, pvArg: *mut ::c_void, +) -> ::BOOL>; +//6022 +pub type HCRYPTOIDFUNCSET = *mut ::c_void; +pub type HCRYPTOIDFUNCADDR = *mut ::c_void; +pub type PFN_CRYPT_ASYNC_PARAM_FREE_FUNC = Option<unsafe extern "system" fn( + pszParamOid: ::LPSTR, pvParam: ::LPVOID, +)>; +STRUCT!{struct CRYPT_HASH_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, +}} +pub type PCRYPT_HASH_MESSAGE_PARA = *mut CRYPT_HASH_MESSAGE_PARA; +//14750 +pub type HCRYPTDEFAULTCONTEXT = *mut ::c_void; +STRUCT!{struct CRYPT_OID_FUNC_ENTRY { + pszOID: ::LPCSTR, + pvFuncAddr: *mut ::c_void, +}} +pub type PCRYPT_OID_FUNC_ENTRY = *mut CRYPT_OID_FUNC_ENTRY; +STRUCT!{struct CMSG_SIGNER_ENCODE_INFO { + cbSize: ::DWORD, + pCertInfo: PCERT_INFO, + hCryptProv: HCRYPTPROV, + dwKeySpec: ::DWORD, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, + cAuthAttr: ::DWORD, + rgAuthAttr: PCRYPT_ATTRIBUTE, + cUnauthAttr: ::DWORD, + rgUnauthAttr: PCRYPT_ATTRIBUTE, +}} +UNION!(CMSG_SIGNER_ENCODE_INFO, hCryptProv, hNCryptKey, hNCryptKey_mut, ::NCRYPT_KEY_HANDLE); +pub type PCMSG_SIGNER_ENCODE_INFO = *mut CMSG_SIGNER_ENCODE_INFO; +STRUCT!{struct CMSG_SIGNED_ENCODE_INFO { + cbSize: ::DWORD, + cSigners: ::DWORD, + rgSigners: PCMSG_SIGNER_ENCODE_INFO, + cCertEncoded: ::DWORD, + rgCertEncoded: PCERT_BLOB, + cCrlEncoded: ::DWORD, + rgCrlEncoded: PCRL_BLOB, +}} +pub type PCMSG_SIGNED_ENCODE_INFO = *mut CMSG_SIGNED_ENCODE_INFO; +//7393 +pub type PFN_CMSG_STREAM_OUTPUT = Option<unsafe extern "system" fn( + pvArg: *const ::c_void, pbData: *mut ::BYTE, cbData: ::DWORD, fFinal: ::BOOL, +) -> ::BOOL>; +STRUCT!{nodebug struct CMSG_STREAM_INFO { + cbContent: ::DWORD, + pfnStreamOutput: PFN_CMSG_STREAM_OUTPUT, + pvArg: *mut ::c_void, +}} +pub type PCMSG_STREAM_INFO = *mut CMSG_STREAM_INFO; +STRUCT!{struct CRYPT_TIMESTAMP_ACCURACY { + dwSeconds: ::DWORD, + dwMillis: ::DWORD, + dwMicros: ::DWORD, +}} +pub type PCRYPT_TIMESTAMP_ACCURACY = *mut CRYPT_TIMESTAMP_ACCURACY; +STRUCT!{struct CRYPT_TIMESTAMP_INFO { + dwVersion: ::DWORD, + pszTSAPolicyId: ::LPSTR, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + HashedMessage: CRYPT_DER_BLOB, + SerialNumber: CRYPT_INTEGER_BLOB, + ftTime: ::FILETIME, + pvAccuracy: PCRYPT_TIMESTAMP_ACCURACY, + fOrdering: ::BOOL, + Nonce: CRYPT_DER_BLOB, + Tsa: CRYPT_DER_BLOB, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRYPT_TIMESTAMP_INFO = *mut CRYPT_TIMESTAMP_INFO; +STRUCT!{struct CRYPT_TIMESTAMP_CONTEXT { + cbEncoded: ::DWORD, + pbEncoded: *mut ::BYTE, + pTimeStamp: PCRYPT_TIMESTAMP_INFO, +}} +pub type PCRYPT_TIMESTAMP_CONTEXT = *mut CRYPT_TIMESTAMP_CONTEXT; +STRUCT!{struct CRYPT_TIMESTAMP_PARA { + pszTSAPolicyId: ::LPCSTR, + fRequestCerts: ::BOOL, + Nonce: CRYPT_INTEGER_BLOB, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRYPT_TIMESTAMP_PARA = *mut CRYPT_TIMESTAMP_PARA; +STRUCT!{struct CRYPT_SIGN_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + pSigningCert: PCCERT_CONTEXT, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, + cMsgCert: ::DWORD, + rgpMsgCert: *mut PCCERT_CONTEXT, + cMsgCrl: ::DWORD, + rgpMsgCrl: *mut PCCRL_CONTEXT, + cAuthAttr: ::DWORD, + rgAuthAttr: PCRYPT_ATTRIBUTE, + cUnauthAttr: ::DWORD, + rgUnauthAttr: PCRYPT_ATTRIBUTE, + dwFlags: ::DWORD, + dwInnerContentType: ::DWORD, +}} +pub type PCRYPT_SIGN_MESSAGE_PARA = *mut CRYPT_SIGN_MESSAGE_PARA; +STRUCT!{struct CRYPT_KEY_SIGN_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgAndCertEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV, + dwKeySpec: ::DWORD, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, + PubKeyAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, +}} +UNION!(CRYPT_KEY_SIGN_MESSAGE_PARA, hCryptProv, hNCryptKey, hNCryptKey_mut, ::NCRYPT_KEY_HANDLE); +pub type PCRYPT_KEY_SIGN_MESSAGE_PARA = *mut CRYPT_KEY_SIGN_MESSAGE_PARA; +STRUCT!{struct CRYPT_KEY_VERIFY_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, +}} +pub type PCRYPT_KEY_VERIFY_MESSAGE_PARA = *mut CRYPT_KEY_VERIFY_MESSAGE_PARA; +STRUCT!{struct HTTPSPolicyCallbackData { + cbSize: ::DWORD, + dwAuthType: ::DWORD, + fdwChecks: ::DWORD, + pwszServerName: *mut ::WCHAR, +}} +pub type PHTTPSPolicyCallbackData = *mut HTTPSPolicyCallbackData; +pub type SSL_EXTRA_CERT_CHAIN_POLICY_PARA = HTTPSPolicyCallbackData; +pub type PSSL_EXTRA_CERT_CHAIN_POLICY_PARA = *mut HTTPSPolicyCallbackData; +pub const AUTHTYPE_CLIENT: ::DWORD = 1; +pub const AUTHTYPE_SERVER: ::DWORD = 2; +pub const CTL_ENTRY_FROM_PROP_CHAIN_FLAG: ::DWORD = 0x1; +pub const CMSG_ENCODE_SORTED_CTL_FLAG: ::DWORD = 0x1; +pub const CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: ::DWORD = 0x2; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/windef.rs b/bash-5.1/vendor/winapi-0.2.8/src/windef.rs new file mode 100644 index 0000000..6493b48 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/windef.rs @@ -0,0 +1,57 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Basic Windows Type Definitions +DECLARE_HANDLE!(HWND, HWND__); +DECLARE_HANDLE!(HHOOK, HHOOK__); +DECLARE_HANDLE!(HEVENT, HEVENT__); +pub type HGDIOBJ = *mut ::c_void; +DECLARE_HANDLE!(HACCEL, HACCEL__); +DECLARE_HANDLE!(HBITMAP, HBITMAP__); +DECLARE_HANDLE!(HBRUSH, HBRUSH__); +DECLARE_HANDLE!(HCOLORSPACE, HCOLORSPACE__); +DECLARE_HANDLE!(HDC, HDC__); +DECLARE_HANDLE!(HGLRC, HGLRC__); +DECLARE_HANDLE!(HDESK, HDESK__); +DECLARE_HANDLE!(HENHMETAFILE, HENHMETAFILE__); +DECLARE_HANDLE!(HFONT, HFONT__); +DECLARE_HANDLE!(HICON, HICON__); +DECLARE_HANDLE!(HMENU, HMENU__); +DECLARE_HANDLE!(HPALETTE, HPALETTE__); +DECLARE_HANDLE!(HPEN, HPEN__); +DECLARE_HANDLE!(HWINEVENTHOOK, HWINEVENTHOOK__); +DECLARE_HANDLE!(HMONITOR, HMONITOR__); +DECLARE_HANDLE!(HUMPD, HUMPD__); +pub type HCURSOR = HICON; +pub type COLORREF = ::DWORD; +pub type LPCOLORREF = *mut ::DWORD; +STRUCT!{struct RECT { + left: ::LONG, + top: ::LONG, + right: ::LONG, + bottom: ::LONG, +}} +pub type PRECT = *mut RECT; +pub type NPRECT = *mut RECT; +pub type LPRECT = *mut RECT; +pub type LPCRECT = *const RECT; +STRUCT!{struct RECTL { + left: ::LONG, + top: ::LONG, + right: ::LONG, + bottom: ::LONG, +}} +pub type PRECTL = *mut RECTL; +pub type LPRECTL = *mut RECTL; +pub type LPCRECTL = *const RECTL; +STRUCT!{struct POINT { + x: ::LONG, + y: ::LONG, +}} +pub type PPOINT = *mut POINT; +pub type NPPOINT = *mut POINT; +pub type LPPOINT = *mut POINT; +STRUCT!{struct POINTL { + x: ::LONG, + y: ::LONG, +}} +pub type PPOINTL = *mut POINTL; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/windowscodecs.rs b/bash-5.1/vendor/winapi-0.2.8/src/windowscodecs.rs new file mode 100644 index 0000000..3759626 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/windowscodecs.rs @@ -0,0 +1,363 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of wincodec.h +pub type WICColor = ::UINT32; +pub type WICInProcPointer = *mut ::BYTE; +pub type REFWICPixelFormatGUID = ::REFGUID; +pub type WICPixelFormatGUID = ::GUID; +STRUCT!{struct WICRect { + X: ::INT, + Y: ::INT, + Width: ::INT, + Height: ::INT, +}} +ENUM!{enum WICColorContextType { + WICColorContextUninitialized = 0, + WICColorContextProfile = 0x1, + WICColorContextExifColorSpace = 0x2, +}} +ENUM!{enum WICBitmapCreateCacheOption { + WICBitmapNoCache = 0, + WICBitmapCacheOnDemand = 0x1, + WICBitmapCacheOnLoad = 0x2, +}} +ENUM!{enum WICDecodeOptions { + WICDecodeMetadataCacheOnDemand = 0, + WICDecodeMetadataCacheOnLoad = 0x1, +}} +ENUM!{enum WICBitmapEncoderCacheOption { + WICBitmapEncoderCacheInMemory = 0, + WICBitmapEncoderCacheTempFile = 0x1, + WICBitmapEncoderNoCache = 0x2, +}} +FLAGS!{enum WICComponentType { + WICDecoder = 0x1, + WICEncoder = 0x2, + WICPixelFormatConverter = 0x4, + WICMetadataReader = 0x8, + WICMetadataWriter = 0x10, + WICPixelFormat = 0x20, + WICAllComponents = 0x3f, +}} +FLAGS!{enum WICComponentEnumerateOptions { + WICComponentEnumerateDefault = 0, + WICComponentEnumerateRefresh = 0x1, + WICComponentEnumerateDisabled = 0x80000000, + WICComponentEnumerateUnsigned = 0x40000000, + WICComponentEnumerateBuiltInOnly = 0x20000000, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICBitmapPattern { + Position: ::ULARGE_INTEGER, + Length: ::ULONG, + Pattern: *mut ::BYTE, + Mask: *mut ::BYTE, + EndOfStream: ::BOOL, +}} +ENUM!{enum WICBitmapInterpolationMode { + WICBitmapInterpolationModeNearestNeighbor = 0, + WICBitmapInterpolationModeLinear = 0x1, + WICBitmapInterpolationModeCubic = 0x2, + WICBitmapInterpolationModeFant = 0x3, +}} +ENUM!{enum WICBitmapPaletteType { + WICBitmapPaletteTypeCustom = 0, + WICBitmapPaletteTypeMedianCut = 0x1, + WICBitmapPaletteTypeFixedBW = 0x2, + WICBitmapPaletteTypeFixedHalftone8 = 0x3, + WICBitmapPaletteTypeFixedHalftone27 = 0x4, + WICBitmapPaletteTypeFixedHalftone64 = 0x5, + WICBitmapPaletteTypeFixedHalftone125 = 0x6, + WICBitmapPaletteTypeFixedHalftone216 = 0x7, + WICBitmapPaletteTypeFixedHalftone252 = 0x8, + WICBitmapPaletteTypeFixedHalftone256 = 0x9, + WICBitmapPaletteTypeFixedGray4 = 0xa, + WICBitmapPaletteTypeFixedGray16 = 0xb, + WICBitmapPaletteTypeFixedGray256 = 0xc, +}} +pub const WICBitmapPaletteTypeFixedWebPalette: WICBitmapPaletteType = + WICBitmapPaletteTypeFixedHalftone216; +ENUM!{enum WICBitmapDitherType { + WICBitmapDitherTypeSolid = 0, + WICBitmapDitherTypeOrdered4x4 = 0x1, + WICBitmapDitherTypeOrdered8x8 = 0x2, + WICBitmapDitherTypeOrdered16x16 = 0x3, + WICBitmapDitherTypeSpiral4x4 = 0x4, + WICBitmapDitherTypeSpiral8x8 = 0x5, + WICBitmapDitherTypeDualSpiral4x4 = 0x6, + WICBitmapDitherTypeDualSpiral8x8 = 0x7, + WICBitmapDitherTypeErrorDiffusion = 0x8, +}} +pub const WICBitmapDitherTypeNone: WICBitmapDitherType = WICBitmapDitherTypeSolid; +ENUM!{enum WICBitmapAlphaChannelOption { + WICBitmapUseAlpha = 0, + WICBitmapUsePremultipliedAlpha = 0x1, + WICBitmapIgnoreAlpha = 0x2, +}} +FLAGS!{enum WICBitmapTransformOptions { + WICBitmapTransformRotate0 = 0, + WICBitmapTransformRotate90 = 0x1, + WICBitmapTransformRotate180 = 0x2, + WICBitmapTransformRotate270 = 0x3, + WICBitmapTransformFlipHorizontal = 0x8, + WICBitmapTransformFlipVertical = 0x10, +}} +FLAGS!{enum WICBitmapLockFlags { + WICBitmapLockRead = 0x1, + WICBitmapLockWrite = 0x2, +}} +FLAGS!{enum WICBitmapDecoderCapabilities { + WICBitmapDecoderCapabilitySameEncoder = 0x1, + WICBitmapDecoderCapabilityCanDecodeAllImages = 0x2, + WICBitmapDecoderCapabilityCanDecodeSomeImages = 0x4, + WICBitmapDecoderCapabilityCanEnumerateMetadata = 0x8, + WICBitmapDecoderCapabilityCanDecodeThumbnail = 0x10, +}} +FLAGS!{enum WICProgressOperation { + WICProgressOperationCopyPixels = 0x1, + WICProgressOperationWritePixels = 0x2, + WICProgressOperationAll = 0xffff, +}} +FLAGS!{enum WICProgressNotification { + WICProgressNotificationBegin = 0x10000, + WICProgressNotificationEnd = 0x20000, + WICProgressNotificationFrequent = 0x40000, + WICProgressNotificationAll = 0xffff0000, +}} +FLAGS!{enum WICComponentSigning { + WICComponentSigned = 0x1, + WICComponentUnsigned = 0x2, + WICComponentSafe = 0x4, + WICComponentDisabled = 0x80000000, +}} +ENUM!{enum WICGifLogicalScreenDescriptorProperties { + WICGifLogicalScreenSignature = 0x1, + WICGifLogicalScreenDescriptorWidth = 0x2, + WICGifLogicalScreenDescriptorHeight = 0x3, + WICGifLogicalScreenDescriptorGlobalColorTableFlag = 0x4, + WICGifLogicalScreenDescriptorColorResolution = 0x5, + WICGifLogicalScreenDescriptorSortFlag = 0x6, + WICGifLogicalScreenDescriptorGlobalColorTableSize = 0x7, + WICGifLogicalScreenDescriptorBackgroundColorIndex = 0x8, + WICGifLogicalScreenDescriptorPixelAspectRatio = 0x9, +}} +ENUM!{enum WICGifImageDescriptorProperties { + WICGifImageDescriptorLeft = 0x1, + WICGifImageDescriptorTop = 0x2, + WICGifImageDescriptorWidth = 0x3, + WICGifImageDescriptorHeight = 0x4, + WICGifImageDescriptorLocalColorTableFlag = 0x5, + WICGifImageDescriptorInterlaceFlag = 0x6, + WICGifImageDescriptorSortFlag = 0x7, + WICGifImageDescriptorLocalColorTableSize = 0x8, +}} +ENUM!{enum WICGifGraphicControlExtensionProperties { + WICGifGraphicControlExtensionDisposal = 0x1, + WICGifGraphicControlExtensionUserInputFlag = 0x2, + WICGifGraphicControlExtensionTransparencyFlag = 0x3, + WICGifGraphicControlExtensionDelay = 0x4, + WICGifGraphicControlExtensionTransparentColorIndex = 0x5, +}} +ENUM!{enum WICGifApplicationExtensionProperties { + WICGifApplicationExtensionApplication = 0x1, + WICGifApplicationExtensionData = 0x2, +}} +ENUM!{enum WICGifCommentExtensionProperties { + WICGifCommentExtensionText = 0x1, +}} +ENUM!{enum WICJpegCommentProperties { + WICJpegCommentText = 0x1, +}} +ENUM!{enum WICJpegLuminanceProperties { + WICJpegLuminanceTable = 0x1, +}} +ENUM!{enum WICJpegChrominanceProperties { + WICJpegChrominanceTable = 0x1, +}} +ENUM!{enum WIC8BIMIptcProperties { + WIC8BIMIptcPString = 0, + WIC8BIMIptcEmbeddedIPTC = 0x1, +}} +ENUM!{enum WIC8BIMResolutionInfoProperties { + WIC8BIMResolutionInfoPString = 0x1, + WIC8BIMResolutionInfoHResolution = 0x2, + WIC8BIMResolutionInfoHResolutionUnit = 0x3, + WIC8BIMResolutionInfoWidthUnit = 0x4, + WIC8BIMResolutionInfoVResolution = 0x5, + WIC8BIMResolutionInfoVResolutionUnit = 0x6, + WIC8BIMResolutionInfoHeightUnit = 0x7, +}} +ENUM!{enum WIC8BIMIptcDigestProperties { + WIC8BIMIptcDigestPString = 0x1, + WIC8BIMIptcDigestIptcDigest = 0x2, +}} +ENUM!{enum WICPngGamaProperties { + WICPngGamaGamma = 0x1, +}} +ENUM!{enum WICPngBkgdProperties { + WICPngBkgdBackgroundColor = 0x1, +}} +ENUM!{enum WICPngItxtProperties { + WICPngItxtKeyword = 0x1, + WICPngItxtCompressionFlag = 0x2, + WICPngItxtLanguageTag = 0x3, + WICPngItxtTranslatedKeyword = 0x4, + WICPngItxtText = 0x5, +}} +ENUM!{enum WICPngChrmProperties { + WICPngChrmWhitePointX = 0x1, + WICPngChrmWhitePointY = 0x2, + WICPngChrmRedX = 0x3, + WICPngChrmRedY = 0x4, + WICPngChrmGreenX = 0x5, + WICPngChrmGreenY = 0x6, + WICPngChrmBlueX = 0x7, + WICPngChrmBlueY = 0x8, +}} +ENUM!{enum WICPngHistProperties { + WICPngHistFrequencies = 0x1, +}} +ENUM!{enum WICPngIccpProperties { + WICPngIccpProfileName = 0x1, + WICPngIccpProfileData = 0x2, +}} +ENUM!{enum WICPngSrgbProperties { + WICPngSrgbRenderingIntent = 0x1, +}} +ENUM!{enum WICPngTimeProperties { + WICPngTimeYear = 0x1, + WICPngTimeMonth = 0x2, + WICPngTimeDay = 0x3, + WICPngTimeHour = 0x4, + WICPngTimeMinute = 0x5, + WICPngTimeSecond = 0x6, +}} +ENUM!{enum WICSectionAccessLevel { + WICSectionAccessLevelRead = 0x1, + WICSectionAccessLevelReadWrite = 0x3, +}} +ENUM!{enum WICPixelFormatNumericRepresentation { + WICPixelFormatNumericRepresentationUnspecified = 0, + WICPixelFormatNumericRepresentationIndexed = 0x1, + WICPixelFormatNumericRepresentationUnsignedInteger = 0x2, + WICPixelFormatNumericRepresentationSignedInteger = 0x3, + WICPixelFormatNumericRepresentationFixed = 0x4, + WICPixelFormatNumericRepresentationFloat = 0x5, +}} +ENUM!{enum WICPlanarOptions { + WICPlanarOptionsDefault = 0, + WICPlanarOptionsPreserveSubsampling = 0x1, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICImageParameters { + PixelFormat: ::D2D1_PIXEL_FORMAT, + DpiX: ::FLOAT, + DpiY: ::FLOAT, + Top: ::FLOAT, + Left: ::FLOAT, + PixelWidth: ::FLOAT, + PixelHeight: ::FLOAT, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICBitmapPlaneDescription { + Format: WICPixelFormatGUID, + Width: ::UINT, + Height: ::UINT, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICBitmapPlane { + Format: WICPixelFormatGUID, + pbBuffer: *mut ::BYTE, + cbStride: ::UINT, + cbBufferSize: ::UINT, +}} +RIDL!( +interface IWICPalette(IWICPaletteVtbl): IUnknown(IUnknownVtbl) { + fn InitializePredefined( + &mut self, ePaletteType: WICBitmapPaletteType, fAddTransparentColor: ::BOOL + ) -> ::HRESULT, + fn InitializeCustom(&mut self, pColors: *mut WICColor, cCount: ::UINT) -> ::HRESULT, + fn InitializeFromBitmap( + &mut self, pISurface: *mut IWICBitmapSource, cCount: ::UINT, fAddTransparentColor: ::BOOL + ) -> ::HRESULT, + fn InitializeFromPalette(&mut self, pIPalette: *mut IWICPalette) -> ::HRESULT, + fn GetType(&mut self, pePaletteType: *mut WICBitmapPaletteType) -> ::HRESULT, + fn GetColorCount(&mut self, pcCount: *mut ::UINT) -> ::HRESULT, + fn GetColors( + &mut self, cCount: ::UINT, pColros: *mut WICColor, pcActualColors: *mut ::UINT + ) -> ::HRESULT, + fn IsBlackWhite(&mut self, pfIsBlackWhite: *mut ::BOOL) -> ::HRESULT, + fn IsGrayscale(&mut self, pfIsGrayscale: *mut ::BOOL) -> ::HRESULT, + fn HasAlpha(&mut self, pfHasAlpha: *mut ::BOOL) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapSource(IWICBitmapSourceVtbl): IUnknown(IUnknownVtbl) { + fn GetSize(&mut self, puiWidth: *mut ::UINT, puiHeight: ::UINT) -> ::HRESULT, + fn GetPixelFormat(&mut self, pPixelFormat: *mut WICPixelFormatGUID) -> ::HRESULT, + fn GetResolution(&mut self, pDpiX: *mut f64, pDpiY: *mut f64) -> ::HRESULT, + fn CopyPalette(&mut self, pIPalette: *mut IWICPalette) -> ::HRESULT, + fn CopyPixels( + &mut self, prc: *const WICRect, cbStride: ::UINT, cbBufferSize: ::UINT, + pbBuffer: *mut ::BYTE + ) -> ::HRESULT +}); +RIDL!( +interface IWICFormatConverter(IWICFormatConverterVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, pISource: *mut IWICBitmapSource, dstFormat: REFWICPixelFormatGUID, + dither: WICBitmapDitherType, pIPalette: *mut IWICPalette, alphaThreasholdPercent: f64, + paletteTranslate: WICBitmapPaletteType + ) -> ::HRESULT, + fn CanConvert( + &mut self, srcPixelFormat: REFWICPixelFormatGUID, dstPixelFormat: REFWICPixelFormatGUID, + pfCanConvert: *mut ::BOOL + ) -> ::HRESULT +}); +RIDL!( +interface IWICPlanarFormatConverter(IWICPlanarFormatConverterVtbl) + : IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, ppPlanes: *mut *mut IWICBitmapSource, cPlanes: ::UINT, + dstFormat: REFWICPixelFormatGUID, dither: WICBitmapDitherType, pIPalette: *mut IWICPalette, + alphaThreasholdPercent: f64, paletteTranslate: WICBitmapPaletteType + ) -> ::HRESULT, + fn CanConvert( + &mut self, pSrcPixelFormats: *const WICPixelFormatGUID, cSrcPlanes: ::UINT, + dstPixelFormat: REFWICPixelFormatGUID, pfCanConvert: *mut ::BOOL + ) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapScaler(IWICBitmapScalerVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, pISource: *mut IWICBitmapSource, uiWidth: ::UINT, uiHeight: ::UINT, + mode: WICBitmapInterpolationMode + ) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapClipper(IWICBitmapClipperVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize(&mut self, pISource: *mut IWICBitmapSource, prc: *const WICRect) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapFlipRotator(IWICBitmapFlipRotatorVtbl) + : IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, pISource: *mut IWICBitmapSource, options: WICBitmapTransformOptions + ) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapLock(IWICBitmapLockVtbl): IUnknown(IUnknownVtbl) { + fn GetSize(&mut self, puiWidth: *mut ::UINT, puiHeight: *mut ::UINT) -> ::HRESULT, + fn GetStride(&mut self, pcbStride: *mut ::UINT) -> ::HRESULT, + fn GetDataPointer( + &mut self, pcbBufferSize: *mut ::UINT, ppbData: *mut WICInProcPointer + ) -> ::HRESULT, + fn GetPixelFormat(&mut self, pPixelFormat: *mut WICPixelFormatGUID) -> ::HRESULT +}); +RIDL!( +interface IWICBitmap(IWICBitmapVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Lock( + &mut self, prcLock: *const WICRect, flags: ::DWORD, ppILock: *mut *mut IWICBitmapLock + ) -> ::HRESULT, + fn SetPalette(&mut self, pIPalette: *mut IWICPalette) -> ::HRESULT, + fn SetResolution(&mut self, dpiX: f64, dpiY: f64) -> ::HRESULT +}); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/windowsx.rs b/bash-5.1/vendor/winapi-0.2.8/src/windowsx.rs new file mode 100644 index 0000000..0441e63 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/windowsx.rs @@ -0,0 +1,22 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Macro APIs, window message crackers, and control APIs +//1233 +pub fn GET_X_LPARAM(lp: ::LPARAM) -> ::c_int { + ::LOWORD(lp as ::DWORD) as ::c_short as ::c_int +} +pub fn GET_Y_LPARAM(lp: ::LPARAM) -> ::c_int { + ::HIWORD(lp as ::DWORD) as ::c_short as ::c_int +} +#[test] +fn test_get_x_lparam() { + assert_eq!(GET_X_LPARAM(0xDEAD1234u32 as ::LPARAM), 0x1234); + assert_eq!(GET_X_LPARAM(0xBEEFffffu32 as ::LPARAM), -1); + assert_eq!(GET_X_LPARAM(0xCAFEFB2Eu32 as ::LPARAM), -1234); +} +#[test] +fn test_get_y_lparam() { + assert_eq!(GET_Y_LPARAM(0x1234DEADu32 as ::LPARAM), 0x1234); + assert_eq!(GET_Y_LPARAM(0xffffBEEFu32 as ::LPARAM), -1); + assert_eq!(GET_Y_LPARAM(0xFB2ECAFEu32 as ::LPARAM), -1234); +} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winerror.rs b/bash-5.1/vendor/winapi-0.2.8/src/winerror.rs new file mode 100644 index 0000000..6792cf8 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winerror.rs @@ -0,0 +1,6065 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! error code definitions for the Win32 API functions +#[inline] +pub fn SUCCEEDED(hr: HRESULT) -> bool { + hr >= 0 +} +pub const FACILITY_XPS: HRESULT = 82; +pub const FACILITY_XAML: HRESULT = 43; +pub const FACILITY_USN: HRESULT = 129; +pub const FACILITY_BLBUI: HRESULT = 128; +pub const FACILITY_SPP: HRESULT = 256; +pub const FACILITY_WSB_ONLINE: HRESULT = 133; +pub const FACILITY_DLS: HRESULT = 153; +pub const FACILITY_BLB_CLI: HRESULT = 121; +pub const FACILITY_BLB: HRESULT = 120; +pub const FACILITY_WSBAPP: HRESULT = 122; +pub const FACILITY_WPN: HRESULT = 62; +pub const FACILITY_WMAAECMA: HRESULT = 1996; +pub const FACILITY_WINRM: HRESULT = 51; +pub const FACILITY_WINPE: HRESULT = 61; +pub const FACILITY_WINDOWSUPDATE: HRESULT = 36; +pub const FACILITY_WINDOWS_STORE: HRESULT = 63; +pub const FACILITY_WINDOWS_SETUP: HRESULT = 48; +pub const FACILITY_WINDOWS_DEFENDER: HRESULT = 80; +pub const FACILITY_WINDOWS_CE: HRESULT = 24; +pub const FACILITY_WINDOWS: HRESULT = 8; +pub const FACILITY_WINCODEC_DWRITE_DWM: HRESULT = 2200; +pub const FACILITY_WIA: HRESULT = 33; +pub const FACILITY_WER: HRESULT = 27; +pub const FACILITY_WEP: HRESULT = 2049; +pub const FACILITY_WEB_SOCKET: HRESULT = 886; +pub const FACILITY_WEB: HRESULT = 885; +pub const FACILITY_USERMODE_VOLSNAP: HRESULT = 130; +pub const FACILITY_USERMODE_VOLMGR: HRESULT = 56; +pub const FACILITY_VISUALCPP: HRESULT = 109; +pub const FACILITY_USERMODE_VIRTUALIZATION: HRESULT = 55; +pub const FACILITY_USERMODE_VHD: HRESULT = 58; +pub const FACILITY_URT: HRESULT = 19; +pub const FACILITY_UMI: HRESULT = 22; +pub const FACILITY_UI: HRESULT = 42; +pub const FACILITY_TPM_SOFTWARE: HRESULT = 41; +pub const FACILITY_TPM_SERVICES: HRESULT = 40; +pub const FACILITY_TIERING: HRESULT = 131; +pub const FACILITY_SYNCENGINE: HRESULT = 2050; +pub const FACILITY_SXS: HRESULT = 23; +pub const FACILITY_STORAGE: HRESULT = 3; +pub const FACILITY_STATE_MANAGEMENT: HRESULT = 34; +pub const FACILITY_SSPI: HRESULT = 9; +pub const FACILITY_USERMODE_SPACES: HRESULT = 231; +pub const FACILITY_SOS: HRESULT = 160; +pub const FACILITY_SCARD: HRESULT = 16; +pub const FACILITY_SHELL: HRESULT = 39; +pub const FACILITY_SETUPAPI: HRESULT = 15; +pub const FACILITY_SECURITY: HRESULT = 9; +pub const FACILITY_SDIAG: HRESULT = 60; +pub const FACILITY_USERMODE_SDBUS: HRESULT = 2305; +pub const FACILITY_RPC: HRESULT = 1; +pub const FACILITY_RESTORE: HRESULT = 256; +pub const FACILITY_SCRIPT: HRESULT = 112; +pub const FACILITY_PARSE: HRESULT = 113; +pub const FACILITY_RAS: HRESULT = 83; +pub const FACILITY_POWERSHELL: HRESULT = 84; +pub const FACILITY_PLA: HRESULT = 48; +pub const FACILITY_PIDGENX: HRESULT = 2561; +pub const FACILITY_P2P_INT: HRESULT = 98; +pub const FACILITY_P2P: HRESULT = 99; +pub const FACILITY_OPC: HRESULT = 81; +pub const FACILITY_ONLINE_ID: HRESULT = 134; +pub const FACILITY_WIN32: HRESULT = 7; +pub const FACILITY_CONTROL: HRESULT = 10; +pub const FACILITY_WEBSERVICES: HRESULT = 61; +pub const FACILITY_NULL: HRESULT = 0; +pub const FACILITY_NDIS: HRESULT = 52; +pub const FACILITY_NAP: HRESULT = 39; +pub const FACILITY_MOBILE: HRESULT = 1793; +pub const FACILITY_METADIRECTORY: HRESULT = 35; +pub const FACILITY_MSMQ: HRESULT = 14; +pub const FACILITY_MEDIASERVER: HRESULT = 13; +pub const FACILITY_MBN: HRESULT = 84; +pub const FACILITY_LINGUISTIC_SERVICES: HRESULT = 305; +pub const FACILITY_LEAP: HRESULT = 2184; +pub const FACILITY_JSCRIPT: HRESULT = 2306; +pub const FACILITY_INTERNET: HRESULT = 12; +pub const FACILITY_ITF: HRESULT = 4; +pub const FACILITY_INPUT: HRESULT = 64; +pub const FACILITY_USERMODE_HYPERVISOR: HRESULT = 53; +pub const FACILITY_ACCELERATOR: HRESULT = 1536; +pub const FACILITY_HTTP: HRESULT = 25; +pub const FACILITY_GRAPHICS: HRESULT = 38; +pub const FACILITY_FWP: HRESULT = 50; +pub const FACILITY_FVE: HRESULT = 49; +pub const FACILITY_USERMODE_FILTER_MANAGER: HRESULT = 31; +pub const FACILITY_EAS: HRESULT = 85; +pub const FACILITY_EAP: HRESULT = 66; +pub const FACILITY_DXGI_DDI: HRESULT = 2171; +pub const FACILITY_DXGI: HRESULT = 2170; +pub const FACILITY_DPLAY: HRESULT = 21; +pub const FACILITY_DMSERVER: HRESULT = 256; +pub const FACILITY_DISPATCH: HRESULT = 2; +pub const FACILITY_DIRECTORYSERVICE: HRESULT = 37; +pub const FACILITY_DIRECTMUSIC: HRESULT = 2168; +pub const FACILITY_DIRECT3D11: HRESULT = 2172; +pub const FACILITY_DIRECT3D10: HRESULT = 2169; +pub const FACILITY_DIRECT2D: HRESULT = 2201; +pub const FACILITY_DAF: HRESULT = 100; +pub const FACILITY_DEPLOYMENT_SERVICES_UTIL: HRESULT = 260; +pub const FACILITY_DEPLOYMENT_SERVICES_TRANSPORT_MANAGEMENT: HRESULT = 272; +pub const FACILITY_DEPLOYMENT_SERVICES_TFTP: HRESULT = 264; +pub const FACILITY_DEPLOYMENT_SERVICES_PXE: HRESULT = 263; +pub const FACILITY_DEPLOYMENT_SERVICES_MULTICAST_SERVER: HRESULT = 289; +pub const FACILITY_DEPLOYMENT_SERVICES_MULTICAST_CLIENT: HRESULT = 290; +pub const FACILITY_DEPLOYMENT_SERVICES_MANAGEMENT: HRESULT = 259; +pub const FACILITY_DEPLOYMENT_SERVICES_IMAGING: HRESULT = 258; +pub const FACILITY_DEPLOYMENT_SERVICES_DRIVER_PROVISIONING: HRESULT = 278; +pub const FACILITY_DEPLOYMENT_SERVICES_SERVER: HRESULT = 257; +pub const FACILITY_DEPLOYMENT_SERVICES_CONTENT_PROVIDER: HRESULT = 293; +pub const FACILITY_DEPLOYMENT_SERVICES_BINLSVC: HRESULT = 261; +pub const FACILITY_DEFRAG: HRESULT = 2304; +pub const FACILITY_DEBUGGERS: HRESULT = 176; +pub const FACILITY_CONFIGURATION: HRESULT = 33; +pub const FACILITY_COMPLUS: HRESULT = 17; +pub const FACILITY_USERMODE_COMMONLOG: HRESULT = 26; +pub const FACILITY_CMI: HRESULT = 54; +pub const FACILITY_CERT: HRESULT = 11; +pub const FACILITY_BLUETOOTH_ATT: HRESULT = 101; +pub const FACILITY_BCD: HRESULT = 57; +pub const FACILITY_BACKGROUNDCOPY: HRESULT = 32; +pub const FACILITY_AUDIOSTREAMING: HRESULT = 1094; +pub const FACILITY_AUDCLNT: HRESULT = 2185; +pub const FACILITY_AUDIO: HRESULT = 102; +pub const FACILITY_ACTION_QUEUE: HRESULT = 44; +pub const FACILITY_ACS: HRESULT = 20; +pub const FACILITY_AAF: HRESULT = 18; +pub const ERROR_SUCCESS: ::DWORD = 0; +pub const NO_ERROR: ::DWORD = 0; +pub const SEC_E_OK: HRESULT = 0; +pub const ERROR_INVALID_FUNCTION: ::DWORD = 1; +pub const ERROR_FILE_NOT_FOUND: ::DWORD = 2; +pub const ERROR_PATH_NOT_FOUND: ::DWORD = 3; +pub const ERROR_TOO_MANY_OPEN_FILES: ::DWORD = 4; +pub const ERROR_ACCESS_DENIED: ::DWORD = 5; +pub const ERROR_INVALID_HANDLE: ::DWORD = 6; +pub const ERROR_ARENA_TRASHED: ::DWORD = 7; +pub const ERROR_NOT_ENOUGH_MEMORY: ::DWORD = 8; +pub const ERROR_INVALID_BLOCK: ::DWORD = 9; +pub const ERROR_BAD_ENVIRONMENT: ::DWORD = 10; +pub const ERROR_BAD_FORMAT: ::DWORD = 11; +pub const ERROR_INVALID_ACCESS: ::DWORD = 12; +pub const ERROR_INVALID_DATA: ::DWORD = 13; +pub const ERROR_OUTOFMEMORY: ::DWORD = 14; +pub const ERROR_INVALID_DRIVE: ::DWORD = 15; +pub const ERROR_CURRENT_DIRECTORY: ::DWORD = 16; +pub const ERROR_NOT_SAME_DEVICE: ::DWORD = 17; +pub const ERROR_NO_MORE_FILES: ::DWORD = 18; +pub const ERROR_WRITE_PROTECT: ::DWORD = 19; +pub const ERROR_BAD_UNIT: ::DWORD = 20; +pub const ERROR_NOT_READY: ::DWORD = 21; +pub const ERROR_BAD_COMMAND: ::DWORD = 22; +pub const ERROR_CRC: ::DWORD = 23; +pub const ERROR_BAD_LENGTH: ::DWORD = 24; +pub const ERROR_SEEK: ::DWORD = 25; +pub const ERROR_NOT_DOS_DISK: ::DWORD = 26; +pub const ERROR_SECTOR_NOT_FOUND: ::DWORD = 27; +pub const ERROR_OUT_OF_PAPER: ::DWORD = 28; +pub const ERROR_WRITE_FAULT: ::DWORD = 29; +pub const ERROR_READ_FAULT: ::DWORD = 30; +pub const ERROR_GEN_FAILURE: ::DWORD = 31; +pub const ERROR_SHARING_VIOLATION: ::DWORD = 32; +pub const ERROR_LOCK_VIOLATION: ::DWORD = 33; +pub const ERROR_WRONG_DISK: ::DWORD = 34; +pub const ERROR_SHARING_BUFFER_EXCEEDED: ::DWORD = 36; +pub const ERROR_HANDLE_EOF: ::DWORD = 38; +pub const ERROR_HANDLE_DISK_FULL: ::DWORD = 39; +pub const ERROR_NOT_SUPPORTED: ::DWORD = 50; +pub const ERROR_REM_NOT_LIST: ::DWORD = 51; +pub const ERROR_DUP_NAME: ::DWORD = 52; +pub const ERROR_BAD_NETPATH: ::DWORD = 53; +pub const ERROR_NETWORK_BUSY: ::DWORD = 54; +pub const ERROR_DEV_NOT_EXIST: ::DWORD = 55; +pub const ERROR_TOO_MANY_CMDS: ::DWORD = 56; +pub const ERROR_ADAP_HDW_ERR: ::DWORD = 57; +pub const ERROR_BAD_NET_RESP: ::DWORD = 58; +pub const ERROR_UNEXP_NET_ERR: ::DWORD = 59; +pub const ERROR_BAD_REM_ADAP: ::DWORD = 60; +pub const ERROR_PRINTQ_FULL: ::DWORD = 61; +pub const ERROR_NO_SPOOL_SPACE: ::DWORD = 62; +pub const ERROR_PRINT_CANCELLED: ::DWORD = 63; +pub const ERROR_NETNAME_DELETED: ::DWORD = 64; +pub const ERROR_NETWORK_ACCESS_DENIED: ::DWORD = 65; +pub const ERROR_BAD_DEV_TYPE: ::DWORD = 66; +pub const ERROR_BAD_NET_NAME: ::DWORD = 67; +pub const ERROR_TOO_MANY_NAMES: ::DWORD = 68; +pub const ERROR_TOO_MANY_SESS: ::DWORD = 69; +pub const ERROR_SHARING_PAUSED: ::DWORD = 70; +pub const ERROR_REQ_NOT_ACCEP: ::DWORD = 71; +pub const ERROR_REDIR_PAUSED: ::DWORD = 72; +pub const ERROR_FILE_EXISTS: ::DWORD = 80; +pub const ERROR_CANNOT_MAKE: ::DWORD = 82; +pub const ERROR_FAIL_I24: ::DWORD = 83; +pub const ERROR_OUT_OF_STRUCTURES: ::DWORD = 84; +pub const ERROR_ALREADY_ASSIGNED: ::DWORD = 85; +pub const ERROR_INVALID_PASSWORD: ::DWORD = 86; +pub const ERROR_INVALID_PARAMETER: ::DWORD = 87; +pub const ERROR_NET_WRITE_FAULT: ::DWORD = 88; +pub const ERROR_NO_PROC_SLOTS: ::DWORD = 89; +pub const ERROR_TOO_MANY_SEMAPHORES: ::DWORD = 100; +pub const ERROR_EXCL_SEM_ALREADY_OWNED: ::DWORD = 101; +pub const ERROR_SEM_IS_SET: ::DWORD = 102; +pub const ERROR_TOO_MANY_SEM_REQUESTS: ::DWORD = 103; +pub const ERROR_INVALID_AT_INTERRUPT_TIME: ::DWORD = 104; +pub const ERROR_SEM_OWNER_DIED: ::DWORD = 105; +pub const ERROR_SEM_USER_LIMIT: ::DWORD = 106; +pub const ERROR_DISK_CHANGE: ::DWORD = 107; +pub const ERROR_DRIVE_LOCKED: ::DWORD = 108; +pub const ERROR_BROKEN_PIPE: ::DWORD = 109; +pub const ERROR_OPEN_FAILED: ::DWORD = 110; +pub const ERROR_BUFFER_OVERFLOW: ::DWORD = 111; +pub const ERROR_DISK_FULL: ::DWORD = 112; +pub const ERROR_NO_MORE_SEARCH_HANDLES: ::DWORD = 113; +pub const ERROR_INVALID_TARGET_HANDLE: ::DWORD = 114; +pub const ERROR_INVALID_CATEGORY: ::DWORD = 117; +pub const ERROR_INVALID_VERIFY_SWITCH: ::DWORD = 118; +pub const ERROR_BAD_DRIVER_LEVEL: ::DWORD = 119; +pub const ERROR_CALL_NOT_IMPLEMENTED: ::DWORD = 120; +pub const ERROR_SEM_TIMEOUT: ::DWORD = 121; +pub const ERROR_INSUFFICIENT_BUFFER: ::DWORD = 122; +pub const ERROR_INVALID_NAME: ::DWORD = 123; +pub const ERROR_INVALID_LEVEL: ::DWORD = 124; +pub const ERROR_NO_VOLUME_LABEL: ::DWORD = 125; +pub const ERROR_MOD_NOT_FOUND: ::DWORD = 126; +pub const ERROR_PROC_NOT_FOUND: ::DWORD = 127; +pub const ERROR_WAIT_NO_CHILDREN: ::DWORD = 128; +pub const ERROR_CHILD_NOT_COMPLETE: ::DWORD = 129; +pub const ERROR_DIRECT_ACCESS_HANDLE: ::DWORD = 130; +pub const ERROR_NEGATIVE_SEEK: ::DWORD = 131; +pub const ERROR_SEEK_ON_DEVICE: ::DWORD = 132; +pub const ERROR_IS_JOIN_TARGET: ::DWORD = 133; +pub const ERROR_IS_JOINED: ::DWORD = 134; +pub const ERROR_IS_SUBSTED: ::DWORD = 135; +pub const ERROR_NOT_JOINED: ::DWORD = 136; +pub const ERROR_NOT_SUBSTED: ::DWORD = 137; +pub const ERROR_JOIN_TO_JOIN: ::DWORD = 138; +pub const ERROR_SUBST_TO_SUBST: ::DWORD = 139; +pub const ERROR_JOIN_TO_SUBST: ::DWORD = 140; +pub const ERROR_SUBST_TO_JOIN: ::DWORD = 141; +pub const ERROR_BUSY_DRIVE: ::DWORD = 142; +pub const ERROR_SAME_DRIVE: ::DWORD = 143; +pub const ERROR_DIR_NOT_ROOT: ::DWORD = 144; +pub const ERROR_DIR_NOT_EMPTY: ::DWORD = 145; +pub const ERROR_IS_SUBST_PATH: ::DWORD = 146; +pub const ERROR_IS_JOIN_PATH: ::DWORD = 147; +pub const ERROR_PATH_BUSY: ::DWORD = 148; +pub const ERROR_IS_SUBST_TARGET: ::DWORD = 149; +pub const ERROR_SYSTEM_TRACE: ::DWORD = 150; +pub const ERROR_INVALID_EVENT_COUNT: ::DWORD = 151; +pub const ERROR_TOO_MANY_MUXWAITERS: ::DWORD = 152; +pub const ERROR_INVALID_LIST_FORMAT: ::DWORD = 153; +pub const ERROR_LABEL_TOO_LONG: ::DWORD = 154; +pub const ERROR_TOO_MANY_TCBS: ::DWORD = 155; +pub const ERROR_SIGNAL_REFUSED: ::DWORD = 156; +pub const ERROR_DISCARDED: ::DWORD = 157; +pub const ERROR_NOT_LOCKED: ::DWORD = 158; +pub const ERROR_BAD_THREADID_ADDR: ::DWORD = 159; +pub const ERROR_BAD_ARGUMENTS: ::DWORD = 160; +pub const ERROR_BAD_PATHNAME: ::DWORD = 161; +pub const ERROR_SIGNAL_PENDING: ::DWORD = 162; +pub const ERROR_MAX_THRDS_REACHED: ::DWORD = 164; +pub const ERROR_LOCK_FAILED: ::DWORD = 167; +pub const ERROR_BUSY: ::DWORD = 170; +pub const ERROR_DEVICE_SUPPORT_IN_PROGRESS: ::DWORD = 171; +pub const ERROR_CANCEL_VIOLATION: ::DWORD = 173; +pub const ERROR_ATOMIC_LOCKS_NOT_SUPPORTED: ::DWORD = 174; +pub const ERROR_INVALID_SEGMENT_NUMBER: ::DWORD = 180; +pub const ERROR_INVALID_ORDINAL: ::DWORD = 182; +pub const ERROR_ALREADY_EXISTS: ::DWORD = 183; +pub const ERROR_INVALID_FLAG_NUMBER: ::DWORD = 186; +pub const ERROR_SEM_NOT_FOUND: ::DWORD = 187; +pub const ERROR_INVALID_STARTING_CODESEG: ::DWORD = 188; +pub const ERROR_INVALID_STACKSEG: ::DWORD = 189; +pub const ERROR_INVALID_MODULETYPE: ::DWORD = 190; +pub const ERROR_INVALID_EXE_SIGNATURE: ::DWORD = 191; +pub const ERROR_EXE_MARKED_INVALID: ::DWORD = 192; +pub const ERROR_BAD_EXE_FORMAT: ::DWORD = 193; +pub const ERROR_ITERATED_DATA_EXCEEDS_64k: ::DWORD = 194; +pub const ERROR_INVALID_MINALLOCSIZE: ::DWORD = 195; +pub const ERROR_DYNLINK_FROM_INVALID_RING: ::DWORD = 196; +pub const ERROR_IOPL_NOT_ENABLED: ::DWORD = 197; +pub const ERROR_INVALID_SEGDPL: ::DWORD = 198; +pub const ERROR_AUTODATASEG_EXCEEDS_64k: ::DWORD = 199; +pub const ERROR_RING2SEG_MUST_BE_MOVABLE: ::DWORD = 200; +pub const ERROR_RELOC_CHAIN_XEEDS_SEGLIM: ::DWORD = 201; +pub const ERROR_INFLOOP_IN_RELOC_CHAIN: ::DWORD = 202; +pub const ERROR_ENVVAR_NOT_FOUND: ::DWORD = 203; +pub const ERROR_NO_SIGNAL_SENT: ::DWORD = 205; +pub const ERROR_FILENAME_EXCED_RANGE: ::DWORD = 206; +pub const ERROR_RING2_STACK_IN_USE: ::DWORD = 207; +pub const ERROR_META_EXPANSION_TOO_LONG: ::DWORD = 208; +pub const ERROR_INVALID_SIGNAL_NUMBER: ::DWORD = 209; +pub const ERROR_THREAD_1_INACTIVE: ::DWORD = 210; +pub const ERROR_LOCKED: ::DWORD = 212; +pub const ERROR_TOO_MANY_MODULES: ::DWORD = 214; +pub const ERROR_NESTING_NOT_ALLOWED: ::DWORD = 215; +pub const ERROR_EXE_MACHINE_TYPE_MISMATCH: ::DWORD = 216; +pub const ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY: ::DWORD = 217; +pub const ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY: ::DWORD = 218; +pub const ERROR_FILE_CHECKED_OUT: ::DWORD = 220; +pub const ERROR_CHECKOUT_REQUIRED: ::DWORD = 221; +pub const ERROR_BAD_FILE_TYPE: ::DWORD = 222; +pub const ERROR_FILE_TOO_LARGE: ::DWORD = 223; +pub const ERROR_FORMS_AUTH_REQUIRED: ::DWORD = 224; +pub const ERROR_VIRUS_INFECTED: ::DWORD = 225; +pub const ERROR_VIRUS_DELETED: ::DWORD = 226; +pub const ERROR_PIPE_LOCAL: ::DWORD = 229; +pub const ERROR_BAD_PIPE: ::DWORD = 230; +pub const ERROR_PIPE_BUSY: ::DWORD = 231; +pub const ERROR_NO_DATA: ::DWORD = 232; +pub const ERROR_PIPE_NOT_CONNECTED: ::DWORD = 233; +pub const ERROR_MORE_DATA: ::DWORD = 234; +pub const ERROR_VC_DISCONNECTED: ::DWORD = 240; +pub const ERROR_INVALID_EA_NAME: ::DWORD = 254; +pub const ERROR_EA_LIST_INCONSISTENT: ::DWORD = 255; +pub const WAIT_TIMEOUT: ::DWORD = 258; +pub const ERROR_NO_MORE_ITEMS: ::DWORD = 259; +pub const ERROR_CANNOT_COPY: ::DWORD = 266; +pub const ERROR_DIRECTORY: ::DWORD = 267; +pub const ERROR_EAS_DIDNT_FIT: ::DWORD = 275; +pub const ERROR_EA_FILE_CORRUPT: ::DWORD = 276; +pub const ERROR_EA_TABLE_FULL: ::DWORD = 277; +pub const ERROR_INVALID_EA_HANDLE: ::DWORD = 278; +pub const ERROR_EAS_NOT_SUPPORTED: ::DWORD = 282; +pub const ERROR_NOT_OWNER: ::DWORD = 288; +pub const ERROR_TOO_MANY_POSTS: ::DWORD = 298; +pub const ERROR_PARTIAL_COPY: ::DWORD = 299; +pub const ERROR_OPLOCK_NOT_GRANTED: ::DWORD = 300; +pub const ERROR_INVALID_OPLOCK_PROTOCOL: ::DWORD = 301; +pub const ERROR_DISK_TOO_FRAGMENTED: ::DWORD = 302; +pub const ERROR_DELETE_PENDING: ::DWORD = 303; +pub const ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING: ::DWORD = 304; +pub const ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME: ::DWORD = 305; +pub const ERROR_SECURITY_STREAM_IS_INCONSISTENT: ::DWORD = 306; +pub const ERROR_INVALID_LOCK_RANGE: ::DWORD = 307; +pub const ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT: ::DWORD = 308; +pub const ERROR_NOTIFICATION_GUID_ALREADY_DEFINED: ::DWORD = 309; +pub const ERROR_INVALID_EXCEPTION_HANDLER: ::DWORD = 310; +pub const ERROR_DUPLICATE_PRIVILEGES: ::DWORD = 311; +pub const ERROR_NO_RANGES_PROCESSED: ::DWORD = 312; +pub const ERROR_NOT_ALLOWED_ON_SYSTEM_FILE: ::DWORD = 313; +pub const ERROR_DISK_RESOURCES_EXHAUSTED: ::DWORD = 314; +pub const ERROR_INVALID_TOKEN: ::DWORD = 315; +pub const ERROR_DEVICE_FEATURE_NOT_SUPPORTED: ::DWORD = 316; +pub const ERROR_MR_MID_NOT_FOUND: ::DWORD = 317; +pub const ERROR_SCOPE_NOT_FOUND: ::DWORD = 318; +pub const ERROR_UNDEFINED_SCOPE: ::DWORD = 319; +pub const ERROR_INVALID_CAP: ::DWORD = 320; +pub const ERROR_DEVICE_UNREACHABLE: ::DWORD = 321; +pub const ERROR_DEVICE_NO_RESOURCES: ::DWORD = 322; +pub const ERROR_DATA_CHECKSUM_ERROR: ::DWORD = 323; +pub const ERROR_INTERMIXED_KERNEL_EA_OPERATION: ::DWORD = 324; +pub const ERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED: ::DWORD = 326; +pub const ERROR_OFFSET_ALIGNMENT_VIOLATION: ::DWORD = 327; +pub const ERROR_INVALID_FIELD_IN_PARAMETER_LIST: ::DWORD = 328; +pub const ERROR_OPERATION_IN_PROGRESS: ::DWORD = 329; +pub const ERROR_BAD_DEVICE_PATH: ::DWORD = 330; +pub const ERROR_TOO_MANY_DESCRIPTORS: ::DWORD = 331; +pub const ERROR_SCRUB_DATA_DISABLED: ::DWORD = 332; +pub const ERROR_NOT_REDUNDANT_STORAGE: ::DWORD = 333; +pub const ERROR_RESIDENT_FILE_NOT_SUPPORTED: ::DWORD = 334; +pub const ERROR_COMPRESSED_FILE_NOT_SUPPORTED: ::DWORD = 335; +pub const ERROR_DIRECTORY_NOT_SUPPORTED: ::DWORD = 336; +pub const ERROR_NOT_READ_FROM_COPY: ::DWORD = 337; +pub const ERROR_FT_WRITE_FAILURE: ::DWORD = 338; +pub const ERROR_FT_DI_SCAN_REQUIRED: ::DWORD = 339; +pub const ERROR_INVALID_KERNEL_INFO_VERSION: ::DWORD = 340; +pub const ERROR_INVALID_PEP_INFO_VERSION: ::DWORD = 341; +pub const ERROR_OBJECT_NOT_EXTERNALLY_BACKED: ::DWORD = 342; +pub const ERROR_EXTERNAL_BACKING_PROVIDER_UNKNOWN: ::DWORD = 343; +pub const ERROR_FAIL_NOACTION_REBOOT: ::DWORD = 350; +pub const ERROR_FAIL_SHUTDOWN: ::DWORD = 351; +pub const ERROR_FAIL_RESTART: ::DWORD = 352; +pub const ERROR_MAX_SESSIONS_REACHED: ::DWORD = 353; +pub const ERROR_THREAD_MODE_ALREADY_BACKGROUND: ::DWORD = 400; +pub const ERROR_THREAD_MODE_NOT_BACKGROUND: ::DWORD = 401; +pub const ERROR_PROCESS_MODE_ALREADY_BACKGROUND: ::DWORD = 402; +pub const ERROR_PROCESS_MODE_NOT_BACKGROUND: ::DWORD = 403; +pub const ERROR_DEVICE_HARDWARE_ERROR: ::DWORD = 483; +pub const ERROR_INVALID_ADDRESS: ::DWORD = 487; +pub const ERROR_USER_PROFILE_LOAD: ::DWORD = 500; +pub const ERROR_ARITHMETIC_OVERFLOW: ::DWORD = 534; +pub const ERROR_PIPE_CONNECTED: ::DWORD = 535; +pub const ERROR_PIPE_LISTENING: ::DWORD = 536; +pub const ERROR_VERIFIER_STOP: ::DWORD = 537; +pub const ERROR_ABIOS_ERROR: ::DWORD = 538; +pub const ERROR_WX86_WARNING: ::DWORD = 539; +pub const ERROR_WX86_ERROR: ::DWORD = 540; +pub const ERROR_TIMER_NOT_CANCELED: ::DWORD = 541; +pub const ERROR_UNWIND: ::DWORD = 542; +pub const ERROR_BAD_STACK: ::DWORD = 543; +pub const ERROR_INVALID_UNWIND_TARGET: ::DWORD = 544; +pub const ERROR_INVALID_PORT_ATTRIBUTES: ::DWORD = 545; +pub const ERROR_PORT_MESSAGE_TOO_LONG: ::DWORD = 546; +pub const ERROR_INVALID_QUOTA_LOWER: ::DWORD = 547; +pub const ERROR_DEVICE_ALREADY_ATTACHED: ::DWORD = 548; +pub const ERROR_INSTRUCTION_MISALIGNMENT: ::DWORD = 549; +pub const ERROR_PROFILING_NOT_STARTED: ::DWORD = 550; +pub const ERROR_PROFILING_NOT_STOPPED: ::DWORD = 551; +pub const ERROR_COULD_NOT_INTERPRET: ::DWORD = 552; +pub const ERROR_PROFILING_AT_LIMIT: ::DWORD = 553; +pub const ERROR_CANT_WAIT: ::DWORD = 554; +pub const ERROR_CANT_TERMINATE_SELF: ::DWORD = 555; +pub const ERROR_UNEXPECTED_MM_CREATE_ERR: ::DWORD = 556; +pub const ERROR_UNEXPECTED_MM_MAP_ERROR: ::DWORD = 557; +pub const ERROR_UNEXPECTED_MM_EXTEND_ERR: ::DWORD = 558; +pub const ERROR_BAD_FUNCTION_TABLE: ::DWORD = 559; +pub const ERROR_NO_GUID_TRANSLATION: ::DWORD = 560; +pub const ERROR_INVALID_LDT_SIZE: ::DWORD = 561; +pub const ERROR_INVALID_LDT_OFFSET: ::DWORD = 563; +pub const ERROR_INVALID_LDT_DESCRIPTOR: ::DWORD = 564; +pub const ERROR_TOO_MANY_THREADS: ::DWORD = 565; +pub const ERROR_THREAD_NOT_IN_PROCESS: ::DWORD = 566; +pub const ERROR_PAGEFILE_QUOTA_EXCEEDED: ::DWORD = 567; +pub const ERROR_LOGON_SERVER_CONFLICT: ::DWORD = 568; +pub const ERROR_SYNCHRONIZATION_REQUIRED: ::DWORD = 569; +pub const ERROR_NET_OPEN_FAILED: ::DWORD = 570; +pub const ERROR_IO_PRIVILEGE_FAILED: ::DWORD = 571; +pub const ERROR_CONTROL_C_EXIT: ::DWORD = 572; +pub const ERROR_MISSING_SYSTEMFILE: ::DWORD = 573; +pub const ERROR_UNHANDLED_EXCEPTION: ::DWORD = 574; +pub const ERROR_APP_INIT_FAILURE: ::DWORD = 575; +pub const ERROR_PAGEFILE_CREATE_FAILED: ::DWORD = 576; +pub const ERROR_INVALID_IMAGE_HASH: ::DWORD = 577; +pub const ERROR_NO_PAGEFILE: ::DWORD = 578; +pub const ERROR_ILLEGAL_FLOAT_CONTEXT: ::DWORD = 579; +pub const ERROR_NO_EVENT_PAIR: ::DWORD = 580; +pub const ERROR_DOMAIN_CTRLR_CONFIG_ERROR: ::DWORD = 581; +pub const ERROR_ILLEGAL_CHARACTER: ::DWORD = 582; +pub const ERROR_UNDEFINED_CHARACTER: ::DWORD = 583; +pub const ERROR_FLOPPY_VOLUME: ::DWORD = 584; +pub const ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT: ::DWORD = 585; +pub const ERROR_BACKUP_CONTROLLER: ::DWORD = 586; +pub const ERROR_MUTANT_LIMIT_EXCEEDED: ::DWORD = 587; +pub const ERROR_FS_DRIVER_REQUIRED: ::DWORD = 588; +pub const ERROR_CANNOT_LOAD_REGISTRY_FILE: ::DWORD = 589; +pub const ERROR_DEBUG_ATTACH_FAILED: ::DWORD = 590; +pub const ERROR_SYSTEM_PROCESS_TERMINATED: ::DWORD = 591; +pub const ERROR_DATA_NOT_ACCEPTED: ::DWORD = 592; +pub const ERROR_VDM_HARD_ERROR: ::DWORD = 593; +pub const ERROR_DRIVER_CANCEL_TIMEOUT: ::DWORD = 594; +pub const ERROR_REPLY_MESSAGE_MISMATCH: ::DWORD = 595; +pub const ERROR_LOST_WRITEBEHIND_DATA: ::DWORD = 596; +pub const ERROR_CLIENT_SERVER_PARAMETERS_INVALID: ::DWORD = 597; +pub const ERROR_NOT_TINY_STREAM: ::DWORD = 598; +pub const ERROR_STACK_OVERFLOW_READ: ::DWORD = 599; +pub const ERROR_CONVERT_TO_LARGE: ::DWORD = 600; +pub const ERROR_FOUND_OUT_OF_SCOPE: ::DWORD = 601; +pub const ERROR_ALLOCATE_BUCKET: ::DWORD = 602; +pub const ERROR_MARSHALL_OVERFLOW: ::DWORD = 603; +pub const ERROR_INVALID_VARIANT: ::DWORD = 604; +pub const ERROR_BAD_COMPRESSION_BUFFER: ::DWORD = 605; +pub const ERROR_AUDIT_FAILED: ::DWORD = 606; +pub const ERROR_TIMER_RESOLUTION_NOT_SET: ::DWORD = 607; +pub const ERROR_INSUFFICIENT_LOGON_INFO: ::DWORD = 608; +pub const ERROR_BAD_DLL_ENTRYPOINT: ::DWORD = 609; +pub const ERROR_BAD_SERVICE_ENTRYPOINT: ::DWORD = 610; +pub const ERROR_IP_ADDRESS_CONFLICT1: ::DWORD = 611; +pub const ERROR_IP_ADDRESS_CONFLICT2: ::DWORD = 612; +pub const ERROR_REGISTRY_QUOTA_LIMIT: ::DWORD = 613; +pub const ERROR_NO_CALLBACK_ACTIVE: ::DWORD = 614; +pub const ERROR_PWD_TOO_SHORT: ::DWORD = 615; +pub const ERROR_PWD_TOO_RECENT: ::DWORD = 616; +pub const ERROR_PWD_HISTORY_CONFLICT: ::DWORD = 617; +pub const ERROR_UNSUPPORTED_COMPRESSION: ::DWORD = 618; +pub const ERROR_INVALID_HW_PROFILE: ::DWORD = 619; +pub const ERROR_INVALID_PLUGPLAY_DEVICE_PATH: ::DWORD = 620; +pub const ERROR_QUOTA_LIST_INCONSISTENT: ::DWORD = 621; +pub const ERROR_EVALUATION_EXPIRATION: ::DWORD = 622; +pub const ERROR_ILLEGAL_DLL_RELOCATION: ::DWORD = 623; +pub const ERROR_DLL_INIT_FAILED_LOGOFF: ::DWORD = 624; +pub const ERROR_VALIDATE_CONTINUE: ::DWORD = 625; +pub const ERROR_NO_MORE_MATCHES: ::DWORD = 626; +pub const ERROR_RANGE_LIST_CONFLICT: ::DWORD = 627; +pub const ERROR_SERVER_SID_MISMATCH: ::DWORD = 628; +pub const ERROR_CANT_ENABLE_DENY_ONLY: ::DWORD = 629; +pub const ERROR_FLOAT_MULTIPLE_FAULTS: ::DWORD = 630; +pub const ERROR_FLOAT_MULTIPLE_TRAPS: ::DWORD = 631; +pub const ERROR_NOINTERFACE: ::DWORD = 632; +pub const ERROR_DRIVER_FAILED_SLEEP: ::DWORD = 633; +pub const ERROR_CORRUPT_SYSTEM_FILE: ::DWORD = 634; +pub const ERROR_COMMITMENT_MINIMUM: ::DWORD = 635; +pub const ERROR_PNP_RESTART_ENUMERATION: ::DWORD = 636; +pub const ERROR_SYSTEM_IMAGE_BAD_SIGNATURE: ::DWORD = 637; +pub const ERROR_PNP_REBOOT_REQUIRED: ::DWORD = 638; +pub const ERROR_INSUFFICIENT_POWER: ::DWORD = 639; +pub const ERROR_MULTIPLE_FAULT_VIOLATION: ::DWORD = 640; +pub const ERROR_SYSTEM_SHUTDOWN: ::DWORD = 641; +pub const ERROR_PORT_NOT_SET: ::DWORD = 642; +pub const ERROR_DS_VERSION_CHECK_FAILURE: ::DWORD = 643; +pub const ERROR_RANGE_NOT_FOUND: ::DWORD = 644; +pub const ERROR_NOT_SAFE_MODE_DRIVER: ::DWORD = 646; +pub const ERROR_FAILED_DRIVER_ENTRY: ::DWORD = 647; +pub const ERROR_DEVICE_ENUMERATION_ERROR: ::DWORD = 648; +pub const ERROR_MOUNT_POINT_NOT_RESOLVED: ::DWORD = 649; +pub const ERROR_INVALID_DEVICE_OBJECT_PARAMETER: ::DWORD = 650; +pub const ERROR_MCA_OCCURED: ::DWORD = 651; +pub const ERROR_DRIVER_DATABASE_ERROR: ::DWORD = 652; +pub const ERROR_SYSTEM_HIVE_TOO_LARGE: ::DWORD = 653; +pub const ERROR_DRIVER_FAILED_PRIOR_UNLOAD: ::DWORD = 654; +pub const ERROR_VOLSNAP_PREPARE_HIBERNATE: ::DWORD = 655; +pub const ERROR_HIBERNATION_FAILURE: ::DWORD = 656; +pub const ERROR_PWD_TOO_LONG: ::DWORD = 657; +pub const ERROR_FILE_SYSTEM_LIMITATION: ::DWORD = 665; +pub const ERROR_ASSERTION_FAILURE: ::DWORD = 668; +pub const ERROR_ACPI_ERROR: ::DWORD = 669; +pub const ERROR_WOW_ASSERTION: ::DWORD = 670; +pub const ERROR_PNP_BAD_MPS_TABLE: ::DWORD = 671; +pub const ERROR_PNP_TRANSLATION_FAILED: ::DWORD = 672; +pub const ERROR_PNP_IRQ_TRANSLATION_FAILED: ::DWORD = 673; +pub const ERROR_PNP_INVALID_ID: ::DWORD = 674; +pub const ERROR_WAKE_SYSTEM_DEBUGGER: ::DWORD = 675; +pub const ERROR_HANDLES_CLOSED: ::DWORD = 676; +pub const ERROR_EXTRANEOUS_INFORMATION: ::DWORD = 677; +pub const ERROR_RXACT_COMMIT_NECESSARY: ::DWORD = 678; +pub const ERROR_MEDIA_CHECK: ::DWORD = 679; +pub const ERROR_GUID_SUBSTITUTION_MADE: ::DWORD = 680; +pub const ERROR_STOPPED_ON_SYMLINK: ::DWORD = 681; +pub const ERROR_LONGJUMP: ::DWORD = 682; +pub const ERROR_PLUGPLAY_QUERY_VETOED: ::DWORD = 683; +pub const ERROR_UNWIND_CONSOLIDATE: ::DWORD = 684; +pub const ERROR_REGISTRY_HIVE_RECOVERED: ::DWORD = 685; +pub const ERROR_DLL_MIGHT_BE_INSECURE: ::DWORD = 686; +pub const ERROR_DLL_MIGHT_BE_INCOMPATIBLE: ::DWORD = 687; +pub const ERROR_DBG_EXCEPTION_NOT_HANDLED: ::DWORD = 688; +pub const ERROR_DBG_REPLY_LATER: ::DWORD = 689; +pub const ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE: ::DWORD = 690; +pub const ERROR_DBG_TERMINATE_THREAD: ::DWORD = 691; +pub const ERROR_DBG_TERMINATE_PROCESS: ::DWORD = 692; +pub const ERROR_DBG_CONTROL_C: ::DWORD = 693; +pub const ERROR_DBG_PRINTEXCEPTION_C: ::DWORD = 694; +pub const ERROR_DBG_RIPEXCEPTION: ::DWORD = 695; +pub const ERROR_DBG_CONTROL_BREAK: ::DWORD = 696; +pub const ERROR_DBG_COMMAND_EXCEPTION: ::DWORD = 697; +pub const ERROR_OBJECT_NAME_EXISTS: ::DWORD = 698; +pub const ERROR_THREAD_WAS_SUSPENDED: ::DWORD = 699; +pub const ERROR_IMAGE_NOT_AT_BASE: ::DWORD = 700; +pub const ERROR_RXACT_STATE_CREATED: ::DWORD = 701; +pub const ERROR_SEGMENT_NOTIFICATION: ::DWORD = 702; +pub const ERROR_BAD_CURRENT_DIRECTORY: ::DWORD = 703; +pub const ERROR_FT_READ_RECOVERY_FROM_BACKUP: ::DWORD = 704; +pub const ERROR_FT_WRITE_RECOVERY: ::DWORD = 705; +pub const ERROR_IMAGE_MACHINE_TYPE_MISMATCH: ::DWORD = 706; +pub const ERROR_RECEIVE_PARTIAL: ::DWORD = 707; +pub const ERROR_RECEIVE_EXPEDITED: ::DWORD = 708; +pub const ERROR_RECEIVE_PARTIAL_EXPEDITED: ::DWORD = 709; +pub const ERROR_EVENT_DONE: ::DWORD = 710; +pub const ERROR_EVENT_PENDING: ::DWORD = 711; +pub const ERROR_CHECKING_FILE_SYSTEM: ::DWORD = 712; +pub const ERROR_FATAL_APP_EXIT: ::DWORD = 713; +pub const ERROR_PREDEFINED_HANDLE: ::DWORD = 714; +pub const ERROR_WAS_UNLOCKED: ::DWORD = 715; +pub const ERROR_SERVICE_NOTIFICATION: ::DWORD = 716; +pub const ERROR_WAS_LOCKED: ::DWORD = 717; +pub const ERROR_LOG_HARD_ERROR: ::DWORD = 718; +pub const ERROR_ALREADY_WIN32: ::DWORD = 719; +pub const ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE: ::DWORD = 720; +pub const ERROR_NO_YIELD_PERFORMED: ::DWORD = 721; +pub const ERROR_TIMER_RESUME_IGNORED: ::DWORD = 722; +pub const ERROR_ARBITRATION_UNHANDLED: ::DWORD = 723; +pub const ERROR_CARDBUS_NOT_SUPPORTED: ::DWORD = 724; +pub const ERROR_MP_PROCESSOR_MISMATCH: ::DWORD = 725; +pub const ERROR_HIBERNATED: ::DWORD = 726; +pub const ERROR_RESUME_HIBERNATION: ::DWORD = 727; +pub const ERROR_FIRMWARE_UPDATED: ::DWORD = 728; +pub const ERROR_DRIVERS_LEAKING_LOCKED_PAGES: ::DWORD = 729; +pub const ERROR_WAKE_SYSTEM: ::DWORD = 730; +pub const ERROR_WAIT_1: ::DWORD = 731; +pub const ERROR_WAIT_2: ::DWORD = 732; +pub const ERROR_WAIT_3: ::DWORD = 733; +pub const ERROR_WAIT_63: ::DWORD = 734; +pub const ERROR_ABANDONED_WAIT_0: ::DWORD = 735; +pub const ERROR_ABANDONED_WAIT_63: ::DWORD = 736; +pub const ERROR_USER_APC: ::DWORD = 737; +pub const ERROR_KERNEL_APC: ::DWORD = 738; +pub const ERROR_ALERTED: ::DWORD = 739; +pub const ERROR_ELEVATION_REQUIRED: ::DWORD = 740; +pub const ERROR_REPARSE: ::DWORD = 741; +pub const ERROR_OPLOCK_BREAK_IN_PROGRESS: ::DWORD = 742; +pub const ERROR_VOLUME_MOUNTED: ::DWORD = 743; +pub const ERROR_RXACT_COMMITTED: ::DWORD = 744; +pub const ERROR_NOTIFY_CLEANUP: ::DWORD = 745; +pub const ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED: ::DWORD = 746; +pub const ERROR_PAGE_FAULT_TRANSITION: ::DWORD = 747; +pub const ERROR_PAGE_FAULT_DEMAND_ZERO: ::DWORD = 748; +pub const ERROR_PAGE_FAULT_COPY_ON_WRITE: ::DWORD = 749; +pub const ERROR_PAGE_FAULT_GUARD_PAGE: ::DWORD = 750; +pub const ERROR_PAGE_FAULT_PAGING_FILE: ::DWORD = 751; +pub const ERROR_CACHE_PAGE_LOCKED: ::DWORD = 752; +pub const ERROR_CRASH_DUMP: ::DWORD = 753; +pub const ERROR_BUFFER_ALL_ZEROS: ::DWORD = 754; +pub const ERROR_REPARSE_OBJECT: ::DWORD = 755; +pub const ERROR_RESOURCE_REQUIREMENTS_CHANGED: ::DWORD = 756; +pub const ERROR_TRANSLATION_COMPLETE: ::DWORD = 757; +pub const ERROR_NOTHING_TO_TERMINATE: ::DWORD = 758; +pub const ERROR_PROCESS_NOT_IN_JOB: ::DWORD = 759; +pub const ERROR_PROCESS_IN_JOB: ::DWORD = 760; +pub const ERROR_VOLSNAP_HIBERNATE_READY: ::DWORD = 761; +pub const ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY: ::DWORD = 762; +pub const ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED: ::DWORD = 763; +pub const ERROR_INTERRUPT_STILL_CONNECTED: ::DWORD = 764; +pub const ERROR_WAIT_FOR_OPLOCK: ::DWORD = 765; +pub const ERROR_DBG_EXCEPTION_HANDLED: ::DWORD = 766; +pub const ERROR_DBG_CONTINUE: ::DWORD = 767; +pub const ERROR_CALLBACK_POP_STACK: ::DWORD = 768; +pub const ERROR_COMPRESSION_DISABLED: ::DWORD = 769; +pub const ERROR_CANTFETCHBACKWARDS: ::DWORD = 770; +pub const ERROR_CANTSCROLLBACKWARDS: ::DWORD = 771; +pub const ERROR_ROWSNOTRELEASED: ::DWORD = 772; +pub const ERROR_BAD_ACCESSOR_FLAGS: ::DWORD = 773; +pub const ERROR_ERRORS_ENCOUNTERED: ::DWORD = 774; +pub const ERROR_NOT_CAPABLE: ::DWORD = 775; +pub const ERROR_REQUEST_OUT_OF_SEQUENCE: ::DWORD = 776; +pub const ERROR_VERSION_PARSE_ERROR: ::DWORD = 777; +pub const ERROR_BADSTARTPOSITION: ::DWORD = 778; +pub const ERROR_MEMORY_HARDWARE: ::DWORD = 779; +pub const ERROR_DISK_REPAIR_DISABLED: ::DWORD = 780; +pub const ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE: ::DWORD = 781; +pub const ERROR_SYSTEM_POWERSTATE_TRANSITION: ::DWORD = 782; +pub const ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION: ::DWORD = 783; +pub const ERROR_MCA_EXCEPTION: ::DWORD = 784; +pub const ERROR_ACCESS_AUDIT_BY_POLICY: ::DWORD = 785; +pub const ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY: ::DWORD = 786; +pub const ERROR_ABANDON_HIBERFILE: ::DWORD = 787; +pub const ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED: ::DWORD = 788; +pub const ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR: ::DWORD = 789; +pub const ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR: ::DWORD = 790; +pub const ERROR_BAD_MCFG_TABLE: ::DWORD = 791; +pub const ERROR_DISK_REPAIR_REDIRECTED: ::DWORD = 792; +pub const ERROR_DISK_REPAIR_UNSUCCESSFUL: ::DWORD = 793; +pub const ERROR_CORRUPT_LOG_OVERFULL: ::DWORD = 794; +pub const ERROR_CORRUPT_LOG_CORRUPTED: ::DWORD = 795; +pub const ERROR_CORRUPT_LOG_UNAVAILABLE: ::DWORD = 796; +pub const ERROR_CORRUPT_LOG_DELETED_FULL: ::DWORD = 797; +pub const ERROR_CORRUPT_LOG_CLEARED: ::DWORD = 798; +pub const ERROR_ORPHAN_NAME_EXHAUSTED: ::DWORD = 799; +pub const ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE: ::DWORD = 800; +pub const ERROR_CANNOT_GRANT_REQUESTED_OPLOCK: ::DWORD = 801; +pub const ERROR_CANNOT_BREAK_OPLOCK: ::DWORD = 802; +pub const ERROR_OPLOCK_HANDLE_CLOSED: ::DWORD = 803; +pub const ERROR_NO_ACE_CONDITION: ::DWORD = 804; +pub const ERROR_INVALID_ACE_CONDITION: ::DWORD = 805; +pub const ERROR_FILE_HANDLE_REVOKED: ::DWORD = 806; +pub const ERROR_IMAGE_AT_DIFFERENT_BASE: ::DWORD = 807; +pub const ERROR_ENCRYPTED_IO_NOT_POSSIBLE: ::DWORD = 808; +pub const ERROR_EA_ACCESS_DENIED: ::DWORD = 994; +pub const ERROR_OPERATION_ABORTED: ::DWORD = 995; +pub const ERROR_IO_INCOMPLETE: ::DWORD = 996; +pub const ERROR_IO_PENDING: ::DWORD = 997; +pub const ERROR_NOACCESS: ::DWORD = 998; +pub const ERROR_SWAPERROR: ::DWORD = 999; +pub const ERROR_STACK_OVERFLOW: ::DWORD = 1001; +pub const ERROR_INVALID_MESSAGE: ::DWORD = 1002; +pub const ERROR_CAN_NOT_COMPLETE: ::DWORD = 1003; +pub const ERROR_INVALID_FLAGS: ::DWORD = 1004; +pub const ERROR_UNRECOGNIZED_VOLUME: ::DWORD = 1005; +pub const ERROR_FILE_INVALID: ::DWORD = 1006; +pub const ERROR_FULLSCREEN_MODE: ::DWORD = 1007; +pub const ERROR_NO_TOKEN: ::DWORD = 1008; +pub const ERROR_BADDB: ::DWORD = 1009; +pub const ERROR_BADKEY: ::DWORD = 1010; +pub const ERROR_CANTOPEN: ::DWORD = 1011; +pub const ERROR_CANTREAD: ::DWORD = 1012; +pub const ERROR_CANTWRITE: ::DWORD = 1013; +pub const ERROR_REGISTRY_RECOVERED: ::DWORD = 1014; +pub const ERROR_REGISTRY_CORRUPT: ::DWORD = 1015; +pub const ERROR_REGISTRY_IO_FAILED: ::DWORD = 1016; +pub const ERROR_NOT_REGISTRY_FILE: ::DWORD = 1017; +pub const ERROR_KEY_DELETED: ::DWORD = 1018; +pub const ERROR_NO_LOG_SPACE: ::DWORD = 1019; +pub const ERROR_KEY_HAS_CHILDREN: ::DWORD = 1020; +pub const ERROR_CHILD_MUST_BE_VOLATILE: ::DWORD = 1021; +pub const ERROR_NOTIFY_ENUM_DIR: ::DWORD = 1022; +pub const ERROR_DEPENDENT_SERVICES_RUNNING: ::DWORD = 1051; +pub const ERROR_INVALID_SERVICE_CONTROL: ::DWORD = 1052; +pub const ERROR_SERVICE_REQUEST_TIMEOUT: ::DWORD = 1053; +pub const ERROR_SERVICE_NO_THREAD: ::DWORD = 1054; +pub const ERROR_SERVICE_DATABASE_LOCKED: ::DWORD = 1055; +pub const ERROR_SERVICE_ALREADY_RUNNING: ::DWORD = 1056; +pub const ERROR_INVALID_SERVICE_ACCOUNT: ::DWORD = 1057; +pub const ERROR_SERVICE_DISABLED: ::DWORD = 1058; +pub const ERROR_CIRCULAR_DEPENDENCY: ::DWORD = 1059; +pub const ERROR_SERVICE_DOES_NOT_EXIST: ::DWORD = 1060; +pub const ERROR_SERVICE_CANNOT_ACCEPT_CTRL: ::DWORD = 1061; +pub const ERROR_SERVICE_NOT_ACTIVE: ::DWORD = 1062; +pub const ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: ::DWORD = 1063; +pub const ERROR_EXCEPTION_IN_SERVICE: ::DWORD = 1064; +pub const ERROR_DATABASE_DOES_NOT_EXIST: ::DWORD = 1065; +pub const ERROR_SERVICE_SPECIFIC_ERROR: ::DWORD = 1066; +pub const ERROR_PROCESS_ABORTED: ::DWORD = 1067; +pub const ERROR_SERVICE_DEPENDENCY_FAIL: ::DWORD = 1068; +pub const ERROR_SERVICE_LOGON_FAILED: ::DWORD = 1069; +pub const ERROR_SERVICE_START_HANG: ::DWORD = 1070; +pub const ERROR_INVALID_SERVICE_LOCK: ::DWORD = 1071; +pub const ERROR_SERVICE_MARKED_FOR_DELETE: ::DWORD = 1072; +pub const ERROR_SERVICE_EXISTS: ::DWORD = 1073; +pub const ERROR_ALREADY_RUNNING_LKG: ::DWORD = 1074; +pub const ERROR_SERVICE_DEPENDENCY_DELETED: ::DWORD = 1075; +pub const ERROR_BOOT_ALREADY_ACCEPTED: ::DWORD = 1076; +pub const ERROR_SERVICE_NEVER_STARTED: ::DWORD = 1077; +pub const ERROR_DUPLICATE_SERVICE_NAME: ::DWORD = 1078; +pub const ERROR_DIFFERENT_SERVICE_ACCOUNT: ::DWORD = 1079; +pub const ERROR_CANNOT_DETECT_DRIVER_FAILURE: ::DWORD = 1080; +pub const ERROR_CANNOT_DETECT_PROCESS_ABORT: ::DWORD = 1081; +pub const ERROR_NO_RECOVERY_PROGRAM: ::DWORD = 1082; +pub const ERROR_SERVICE_NOT_IN_EXE: ::DWORD = 1083; +pub const ERROR_NOT_SAFEBOOT_SERVICE: ::DWORD = 1084; +pub const ERROR_END_OF_MEDIA: ::DWORD = 1100; +pub const ERROR_FILEMARK_DETECTED: ::DWORD = 1101; +pub const ERROR_BEGINNING_OF_MEDIA: ::DWORD = 1102; +pub const ERROR_SETMARK_DETECTED: ::DWORD = 1103; +pub const ERROR_NO_DATA_DETECTED: ::DWORD = 1104; +pub const ERROR_PARTITION_FAILURE: ::DWORD = 1105; +pub const ERROR_INVALID_BLOCK_LENGTH: ::DWORD = 1106; +pub const ERROR_DEVICE_NOT_PARTITIONED: ::DWORD = 1107; +pub const ERROR_UNABLE_TO_LOCK_MEDIA: ::DWORD = 1108; +pub const ERROR_UNABLE_TO_UNLOAD_MEDIA: ::DWORD = 1109; +pub const ERROR_MEDIA_CHANGED: ::DWORD = 1110; +pub const ERROR_BUS_RESET: ::DWORD = 1111; +pub const ERROR_NO_MEDIA_IN_DRIVE: ::DWORD = 1112; +pub const ERROR_NO_UNICODE_TRANSLATION: ::DWORD = 1113; +pub const ERROR_DLL_INIT_FAILED: ::DWORD = 1114; +pub const ERROR_SHUTDOWN_IN_PROGRESS: ::DWORD = 1115; +pub const ERROR_NO_SHUTDOWN_IN_PROGRESS: ::DWORD = 1116; +pub const ERROR_IO_DEVICE: ::DWORD = 1117; +pub const ERROR_SERIAL_NO_DEVICE: ::DWORD = 1118; +pub const ERROR_IRQ_BUSY: ::DWORD = 1119; +pub const ERROR_MORE_WRITES: ::DWORD = 1120; +pub const ERROR_COUNTER_TIMEOUT: ::DWORD = 1121; +pub const ERROR_FLOPPY_ID_MARK_NOT_FOUND: ::DWORD = 1122; +pub const ERROR_FLOPPY_WRONG_CYLINDER: ::DWORD = 1123; +pub const ERROR_FLOPPY_UNKNOWN_ERROR: ::DWORD = 1124; +pub const ERROR_FLOPPY_BAD_REGISTERS: ::DWORD = 1125; +pub const ERROR_DISK_RECALIBRATE_FAILED: ::DWORD = 1126; +pub const ERROR_DISK_OPERATION_FAILED: ::DWORD = 1127; +pub const ERROR_DISK_RESET_FAILED: ::DWORD = 1128; +pub const ERROR_EOM_OVERFLOW: ::DWORD = 1129; +pub const ERROR_NOT_ENOUGH_SERVER_MEMORY: ::DWORD = 1130; +pub const ERROR_POSSIBLE_DEADLOCK: ::DWORD = 1131; +pub const ERROR_MAPPED_ALIGNMENT: ::DWORD = 1132; +pub const ERROR_SET_POWER_STATE_VETOED: ::DWORD = 1140; +pub const ERROR_SET_POWER_STATE_FAILED: ::DWORD = 1141; +pub const ERROR_TOO_MANY_LINKS: ::DWORD = 1142; +pub const ERROR_OLD_WIN_VERSION: ::DWORD = 1150; +pub const ERROR_APP_WRONG_OS: ::DWORD = 1151; +pub const ERROR_SINGLE_INSTANCE_APP: ::DWORD = 1152; +pub const ERROR_RMODE_APP: ::DWORD = 1153; +pub const ERROR_INVALID_DLL: ::DWORD = 1154; +pub const ERROR_NO_ASSOCIATION: ::DWORD = 1155; +pub const ERROR_DDE_FAIL: ::DWORD = 1156; +pub const ERROR_DLL_NOT_FOUND: ::DWORD = 1157; +pub const ERROR_NO_MORE_USER_HANDLES: ::DWORD = 1158; +pub const ERROR_MESSAGE_SYNC_ONLY: ::DWORD = 1159; +pub const ERROR_SOURCE_ELEMENT_EMPTY: ::DWORD = 1160; +pub const ERROR_DESTINATION_ELEMENT_FULL: ::DWORD = 1161; +pub const ERROR_ILLEGAL_ELEMENT_ADDRESS: ::DWORD = 1162; +pub const ERROR_MAGAZINE_NOT_PRESENT: ::DWORD = 1163; +pub const ERROR_DEVICE_REINITIALIZATION_NEEDED: ::DWORD = 1164; +pub const ERROR_DEVICE_REQUIRES_CLEANING: ::DWORD = 1165; +pub const ERROR_DEVICE_DOOR_OPEN: ::DWORD = 1166; +pub const ERROR_DEVICE_NOT_CONNECTED: ::DWORD = 1167; +pub const ERROR_NOT_FOUND: ::DWORD = 1168; +pub const ERROR_NO_MATCH: ::DWORD = 1169; +pub const ERROR_SET_NOT_FOUND: ::DWORD = 1170; +pub const ERROR_POINT_NOT_FOUND: ::DWORD = 1171; +pub const ERROR_NO_TRACKING_SERVICE: ::DWORD = 1172; +pub const ERROR_NO_VOLUME_ID: ::DWORD = 1173; +pub const ERROR_UNABLE_TO_REMOVE_REPLACED: ::DWORD = 1175; +pub const ERROR_UNABLE_TO_MOVE_REPLACEMENT: ::DWORD = 1176; +pub const ERROR_UNABLE_TO_MOVE_REPLACEMENT_2: ::DWORD = 1177; +pub const ERROR_JOURNAL_DELETE_IN_PROGRESS: ::DWORD = 1178; +pub const ERROR_JOURNAL_NOT_ACTIVE: ::DWORD = 1179; +pub const ERROR_POTENTIAL_FILE_FOUND: ::DWORD = 1180; +pub const ERROR_JOURNAL_ENTRY_DELETED: ::DWORD = 1181; +pub const ERROR_SHUTDOWN_IS_SCHEDULED: ::DWORD = 1190; +pub const ERROR_SHUTDOWN_USERS_LOGGED_ON: ::DWORD = 1191; +pub const ERROR_BAD_DEVICE: ::DWORD = 1200; +pub const ERROR_CONNECTION_UNAVAIL: ::DWORD = 1201; +pub const ERROR_DEVICE_ALREADY_REMEMBERED: ::DWORD = 1202; +pub const ERROR_NO_NET_OR_BAD_PATH: ::DWORD = 1203; +pub const ERROR_BAD_PROVIDER: ::DWORD = 1204; +pub const ERROR_CANNOT_OPEN_PROFILE: ::DWORD = 1205; +pub const ERROR_BAD_PROFILE: ::DWORD = 1206; +pub const ERROR_NOT_CONTAINER: ::DWORD = 1207; +pub const ERROR_EXTENDED_ERROR: ::DWORD = 1208; +pub const ERROR_INVALID_GROUPNAME: ::DWORD = 1209; +pub const ERROR_INVALID_COMPUTERNAME: ::DWORD = 1210; +pub const ERROR_INVALID_EVENTNAME: ::DWORD = 1211; +pub const ERROR_INVALID_DOMAINNAME: ::DWORD = 1212; +pub const ERROR_INVALID_SERVICENAME: ::DWORD = 1213; +pub const ERROR_INVALID_NETNAME: ::DWORD = 1214; +pub const ERROR_INVALID_SHARENAME: ::DWORD = 1215; +pub const ERROR_INVALID_PASSWORDNAME: ::DWORD = 1216; +pub const ERROR_INVALID_MESSAGENAME: ::DWORD = 1217; +pub const ERROR_INVALID_MESSAGEDEST: ::DWORD = 1218; +pub const ERROR_SESSION_CREDENTIAL_CONFLICT: ::DWORD = 1219; +pub const ERROR_REMOTE_SESSION_LIMIT_EXCEEDED: ::DWORD = 1220; +pub const ERROR_DUP_DOMAINNAME: ::DWORD = 1221; +pub const ERROR_NO_NETWORK: ::DWORD = 1222; +pub const ERROR_CANCELLED: ::DWORD = 1223; +pub const ERROR_USER_MAPPED_FILE: ::DWORD = 1224; +pub const ERROR_CONNECTION_REFUSED: ::DWORD = 1225; +pub const ERROR_GRACEFUL_DISCONNECT: ::DWORD = 1226; +pub const ERROR_ADDRESS_ALREADY_ASSOCIATED: ::DWORD = 1227; +pub const ERROR_ADDRESS_NOT_ASSOCIATED: ::DWORD = 1228; +pub const ERROR_CONNECTION_INVALID: ::DWORD = 1229; +pub const ERROR_CONNECTION_ACTIVE: ::DWORD = 1230; +pub const ERROR_NETWORK_UNREACHABLE: ::DWORD = 1231; +pub const ERROR_HOST_UNREACHABLE: ::DWORD = 1232; +pub const ERROR_PROTOCOL_UNREACHABLE: ::DWORD = 1233; +pub const ERROR_PORT_UNREACHABLE: ::DWORD = 1234; +pub const ERROR_REQUEST_ABORTED: ::DWORD = 1235; +pub const ERROR_CONNECTION_ABORTED: ::DWORD = 1236; +pub const ERROR_RETRY: ::DWORD = 1237; +pub const ERROR_CONNECTION_COUNT_LIMIT: ::DWORD = 1238; +pub const ERROR_LOGIN_TIME_RESTRICTION: ::DWORD = 1239; +pub const ERROR_LOGIN_WKSTA_RESTRICTION: ::DWORD = 1240; +pub const ERROR_INCORRECT_ADDRESS: ::DWORD = 1241; +pub const ERROR_ALREADY_REGISTERED: ::DWORD = 1242; +pub const ERROR_SERVICE_NOT_FOUND: ::DWORD = 1243; +pub const ERROR_NOT_AUTHENTICATED: ::DWORD = 1244; +pub const ERROR_NOT_LOGGED_ON: ::DWORD = 1245; +pub const ERROR_CONTINUE: ::DWORD = 1246; +pub const ERROR_ALREADY_INITIALIZED: ::DWORD = 1247; +pub const ERROR_NO_MORE_DEVICES: ::DWORD = 1248; +pub const ERROR_NO_SUCH_SITE: ::DWORD = 1249; +pub const ERROR_DOMAIN_CONTROLLER_EXISTS: ::DWORD = 1250; +pub const ERROR_ONLY_IF_CONNECTED: ::DWORD = 1251; +pub const ERROR_OVERRIDE_NOCHANGES: ::DWORD = 1252; +pub const ERROR_BAD_USER_PROFILE: ::DWORD = 1253; +pub const ERROR_NOT_SUPPORTED_ON_SBS: ::DWORD = 1254; +pub const ERROR_SERVER_SHUTDOWN_IN_PROGRESS: ::DWORD = 1255; +pub const ERROR_HOST_DOWN: ::DWORD = 1256; +pub const ERROR_NON_ACCOUNT_SID: ::DWORD = 1257; +pub const ERROR_NON_DOMAIN_SID: ::DWORD = 1258; +pub const ERROR_APPHELP_BLOCK: ::DWORD = 1259; +pub const ERROR_ACCESS_DISABLED_BY_POLICY: ::DWORD = 1260; +pub const ERROR_REG_NAT_CONSUMPTION: ::DWORD = 1261; +pub const ERROR_CSCSHARE_OFFLINE: ::DWORD = 1262; +pub const ERROR_PKINIT_FAILURE: ::DWORD = 1263; +pub const ERROR_SMARTCARD_SUBSYSTEM_FAILURE: ::DWORD = 1264; +pub const ERROR_DOWNGRADE_DETECTED: ::DWORD = 1265; +pub const ERROR_MACHINE_LOCKED: ::DWORD = 1271; +pub const ERROR_CALLBACK_SUPPLIED_INVALID_DATA: ::DWORD = 1273; +pub const ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED: ::DWORD = 1274; +pub const ERROR_DRIVER_BLOCKED: ::DWORD = 1275; +pub const ERROR_INVALID_IMPORT_OF_NON_DLL: ::DWORD = 1276; +pub const ERROR_ACCESS_DISABLED_WEBBLADE: ::DWORD = 1277; +pub const ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER: ::DWORD = 1278; +pub const ERROR_RECOVERY_FAILURE: ::DWORD = 1279; +pub const ERROR_ALREADY_FIBER: ::DWORD = 1280; +pub const ERROR_ALREADY_THREAD: ::DWORD = 1281; +pub const ERROR_STACK_BUFFER_OVERRUN: ::DWORD = 1282; +pub const ERROR_PARAMETER_QUOTA_EXCEEDED: ::DWORD = 1283; +pub const ERROR_DEBUGGER_INACTIVE: ::DWORD = 1284; +pub const ERROR_DELAY_LOAD_FAILED: ::DWORD = 1285; +pub const ERROR_VDM_DISALLOWED: ::DWORD = 1286; +pub const ERROR_UNIDENTIFIED_ERROR: ::DWORD = 1287; +pub const ERROR_INVALID_CRUNTIME_PARAMETER: ::DWORD = 1288; +pub const ERROR_BEYOND_VDL: ::DWORD = 1289; +pub const ERROR_INCOMPATIBLE_SERVICE_SID_TYPE: ::DWORD = 1290; +pub const ERROR_DRIVER_PROCESS_TERMINATED: ::DWORD = 1291; +pub const ERROR_IMPLEMENTATION_LIMIT: ::DWORD = 1292; +pub const ERROR_PROCESS_IS_PROTECTED: ::DWORD = 1293; +pub const ERROR_SERVICE_NOTIFY_CLIENT_LAGGING: ::DWORD = 1294; +pub const ERROR_DISK_QUOTA_EXCEEDED: ::DWORD = 1295; +pub const ERROR_CONTENT_BLOCKED: ::DWORD = 1296; +pub const ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE: ::DWORD = 1297; +pub const ERROR_APP_HANG: ::DWORD = 1298; +pub const ERROR_INVALID_LABEL: ::DWORD = 1299; +pub const ERROR_NOT_ALL_ASSIGNED: ::DWORD = 1300; +pub const ERROR_SOME_NOT_MAPPED: ::DWORD = 1301; +pub const ERROR_NO_QUOTAS_FOR_ACCOUNT: ::DWORD = 1302; +pub const ERROR_LOCAL_USER_SESSION_KEY: ::DWORD = 1303; +pub const ERROR_NULL_LM_PASSWORD: ::DWORD = 1304; +pub const ERROR_UNKNOWN_REVISION: ::DWORD = 1305; +pub const ERROR_REVISION_MISMATCH: ::DWORD = 1306; +pub const ERROR_INVALID_OWNER: ::DWORD = 1307; +pub const ERROR_INVALID_PRIMARY_GROUP: ::DWORD = 1308; +pub const ERROR_NO_IMPERSONATION_TOKEN: ::DWORD = 1309; +pub const ERROR_CANT_DISABLE_MANDATORY: ::DWORD = 1310; +pub const ERROR_NO_LOGON_SERVERS: ::DWORD = 1311; +pub const ERROR_NO_SUCH_LOGON_SESSION: ::DWORD = 1312; +pub const ERROR_NO_SUCH_PRIVILEGE: ::DWORD = 1313; +pub const ERROR_PRIVILEGE_NOT_HELD: ::DWORD = 1314; +pub const ERROR_INVALID_ACCOUNT_NAME: ::DWORD = 1315; +pub const ERROR_USER_EXISTS: ::DWORD = 1316; +pub const ERROR_NO_SUCH_USER: ::DWORD = 1317; +pub const ERROR_GROUP_EXISTS: ::DWORD = 1318; +pub const ERROR_NO_SUCH_GROUP: ::DWORD = 1319; +pub const ERROR_MEMBER_IN_GROUP: ::DWORD = 1320; +pub const ERROR_MEMBER_NOT_IN_GROUP: ::DWORD = 1321; +pub const ERROR_LAST_ADMIN: ::DWORD = 1322; +pub const ERROR_WRONG_PASSWORD: ::DWORD = 1323; +pub const ERROR_ILL_FORMED_PASSWORD: ::DWORD = 1324; +pub const ERROR_PASSWORD_RESTRICTION: ::DWORD = 1325; +pub const ERROR_LOGON_FAILURE: ::DWORD = 1326; +pub const ERROR_ACCOUNT_RESTRICTION: ::DWORD = 1327; +pub const ERROR_INVALID_LOGON_HOURS: ::DWORD = 1328; +pub const ERROR_INVALID_WORKSTATION: ::DWORD = 1329; +pub const ERROR_PASSWORD_EXPIRED: ::DWORD = 1330; +pub const ERROR_ACCOUNT_DISABLED: ::DWORD = 1331; +pub const ERROR_NONE_MAPPED: ::DWORD = 1332; +pub const ERROR_TOO_MANY_LUIDS_REQUESTED: ::DWORD = 1333; +pub const ERROR_LUIDS_EXHAUSTED: ::DWORD = 1334; +pub const ERROR_INVALID_SUB_AUTHORITY: ::DWORD = 1335; +pub const ERROR_INVALID_ACL: ::DWORD = 1336; +pub const ERROR_INVALID_SID: ::DWORD = 1337; +pub const ERROR_INVALID_SECURITY_DESCR: ::DWORD = 1338; +pub const ERROR_BAD_INHERITANCE_ACL: ::DWORD = 1340; +pub const ERROR_SERVER_DISABLED: ::DWORD = 1341; +pub const ERROR_SERVER_NOT_DISABLED: ::DWORD = 1342; +pub const ERROR_INVALID_ID_AUTHORITY: ::DWORD = 1343; +pub const ERROR_ALLOTTED_SPACE_EXCEEDED: ::DWORD = 1344; +pub const ERROR_INVALID_GROUP_ATTRIBUTES: ::DWORD = 1345; +pub const ERROR_BAD_IMPERSONATION_LEVEL: ::DWORD = 1346; +pub const ERROR_CANT_OPEN_ANONYMOUS: ::DWORD = 1347; +pub const ERROR_BAD_VALIDATION_CLASS: ::DWORD = 1348; +pub const ERROR_BAD_TOKEN_TYPE: ::DWORD = 1349; +pub const ERROR_NO_SECURITY_ON_OBJECT: ::DWORD = 1350; +pub const ERROR_CANT_ACCESS_DOMAIN_INFO: ::DWORD = 1351; +pub const ERROR_INVALID_SERVER_STATE: ::DWORD = 1352; +pub const ERROR_INVALID_DOMAIN_STATE: ::DWORD = 1353; +pub const ERROR_INVALID_DOMAIN_ROLE: ::DWORD = 1354; +pub const ERROR_NO_SUCH_DOMAIN: ::DWORD = 1355; +pub const ERROR_DOMAIN_EXISTS: ::DWORD = 1356; +pub const ERROR_DOMAIN_LIMIT_EXCEEDED: ::DWORD = 1357; +pub const ERROR_INTERNAL_DB_CORRUPTION: ::DWORD = 1358; +pub const ERROR_INTERNAL_ERROR: ::DWORD = 1359; +pub const ERROR_GENERIC_NOT_MAPPED: ::DWORD = 1360; +pub const ERROR_BAD_DESCRIPTOR_FORMAT: ::DWORD = 1361; +pub const ERROR_NOT_LOGON_PROCESS: ::DWORD = 1362; +pub const ERROR_LOGON_SESSION_EXISTS: ::DWORD = 1363; +pub const ERROR_NO_SUCH_PACKAGE: ::DWORD = 1364; +pub const ERROR_BAD_LOGON_SESSION_STATE: ::DWORD = 1365; +pub const ERROR_LOGON_SESSION_COLLISION: ::DWORD = 1366; +pub const ERROR_INVALID_LOGON_TYPE: ::DWORD = 1367; +pub const ERROR_CANNOT_IMPERSONATE: ::DWORD = 1368; +pub const ERROR_RXACT_INVALID_STATE: ::DWORD = 1369; +pub const ERROR_RXACT_COMMIT_FAILURE: ::DWORD = 1370; +pub const ERROR_SPECIAL_ACCOUNT: ::DWORD = 1371; +pub const ERROR_SPECIAL_GROUP: ::DWORD = 1372; +pub const ERROR_SPECIAL_USER: ::DWORD = 1373; +pub const ERROR_MEMBERS_PRIMARY_GROUP: ::DWORD = 1374; +pub const ERROR_TOKEN_ALREADY_IN_USE: ::DWORD = 1375; +pub const ERROR_NO_SUCH_ALIAS: ::DWORD = 1376; +pub const ERROR_MEMBER_NOT_IN_ALIAS: ::DWORD = 1377; +pub const ERROR_MEMBER_IN_ALIAS: ::DWORD = 1378; +pub const ERROR_ALIAS_EXISTS: ::DWORD = 1379; +pub const ERROR_LOGON_NOT_GRANTED: ::DWORD = 1380; +pub const ERROR_TOO_MANY_SECRETS: ::DWORD = 1381; +pub const ERROR_SECRET_TOO_LONG: ::DWORD = 1382; +pub const ERROR_INTERNAL_DB_ERROR: ::DWORD = 1383; +pub const ERROR_TOO_MANY_CONTEXT_IDS: ::DWORD = 1384; +pub const ERROR_LOGON_TYPE_NOT_GRANTED: ::DWORD = 1385; +pub const ERROR_NT_CROSS_ENCRYPTION_REQUIRED: ::DWORD = 1386; +pub const ERROR_NO_SUCH_MEMBER: ::DWORD = 1387; +pub const ERROR_INVALID_MEMBER: ::DWORD = 1388; +pub const ERROR_TOO_MANY_SIDS: ::DWORD = 1389; +pub const ERROR_LM_CROSS_ENCRYPTION_REQUIRED: ::DWORD = 1390; +pub const ERROR_NO_INHERITANCE: ::DWORD = 1391; +pub const ERROR_FILE_CORRUPT: ::DWORD = 1392; +pub const ERROR_DISK_CORRUPT: ::DWORD = 1393; +pub const ERROR_NO_USER_SESSION_KEY: ::DWORD = 1394; +pub const ERROR_LICENSE_QUOTA_EXCEEDED: ::DWORD = 1395; +pub const ERROR_WRONG_TARGET_NAME: ::DWORD = 1396; +pub const ERROR_MUTUAL_AUTH_FAILED: ::DWORD = 1397; +pub const ERROR_TIME_SKEW: ::DWORD = 1398; +pub const ERROR_CURRENT_DOMAIN_NOT_ALLOWED: ::DWORD = 1399; +pub const ERROR_INVALID_WINDOW_HANDLE: ::DWORD = 1400; +pub const ERROR_INVALID_MENU_HANDLE: ::DWORD = 1401; +pub const ERROR_INVALID_CURSOR_HANDLE: ::DWORD = 1402; +pub const ERROR_INVALID_ACCEL_HANDLE: ::DWORD = 1403; +pub const ERROR_INVALID_HOOK_HANDLE: ::DWORD = 1404; +pub const ERROR_INVALID_DWP_HANDLE: ::DWORD = 1405; +pub const ERROR_TLW_WITH_WSCHILD: ::DWORD = 1406; +pub const ERROR_CANNOT_FIND_WND_CLASS: ::DWORD = 1407; +pub const ERROR_WINDOW_OF_OTHER_THREAD: ::DWORD = 1408; +pub const ERROR_HOTKEY_ALREADY_REGISTERED: ::DWORD = 1409; +pub const ERROR_CLASS_ALREADY_EXISTS: ::DWORD = 1410; +pub const ERROR_CLASS_DOES_NOT_EXIST: ::DWORD = 1411; +pub const ERROR_CLASS_HAS_WINDOWS: ::DWORD = 1412; +pub const ERROR_INVALID_INDEX: ::DWORD = 1413; +pub const ERROR_INVALID_ICON_HANDLE: ::DWORD = 1414; +pub const ERROR_PRIVATE_DIALOG_INDEX: ::DWORD = 1415; +pub const ERROR_LISTBOX_ID_NOT_FOUND: ::DWORD = 1416; +pub const ERROR_NO_WILDCARD_CHARACTERS: ::DWORD = 1417; +pub const ERROR_CLIPBOARD_NOT_OPEN: ::DWORD = 1418; +pub const ERROR_HOTKEY_NOT_REGISTERED: ::DWORD = 1419; +pub const ERROR_WINDOW_NOT_DIALOG: ::DWORD = 1420; +pub const ERROR_CONTROL_ID_NOT_FOUND: ::DWORD = 1421; +pub const ERROR_INVALID_COMBOBOX_MESSAGE: ::DWORD = 1422; +pub const ERROR_WINDOW_NOT_COMBOBOX: ::DWORD = 1423; +pub const ERROR_INVALID_EDIT_HEIGHT: ::DWORD = 1424; +pub const ERROR_DC_NOT_FOUND: ::DWORD = 1425; +pub const ERROR_INVALID_HOOK_FILTER: ::DWORD = 1426; +pub const ERROR_INVALID_FILTER_PROC: ::DWORD = 1427; +pub const ERROR_HOOK_NEEDS_HMOD: ::DWORD = 1428; +pub const ERROR_GLOBAL_ONLY_HOOK: ::DWORD = 1429; +pub const ERROR_JOURNAL_HOOK_SET: ::DWORD = 1430; +pub const ERROR_HOOK_NOT_INSTALLED: ::DWORD = 1431; +pub const ERROR_INVALID_LB_MESSAGE: ::DWORD = 1432; +pub const ERROR_SETCOUNT_ON_BAD_LB: ::DWORD = 1433; +pub const ERROR_LB_WITHOUT_TABSTOPS: ::DWORD = 1434; +pub const ERROR_DESTROY_OBJECT_OF_OTHER_THREAD: ::DWORD = 1435; +pub const ERROR_CHILD_WINDOW_MENU: ::DWORD = 1436; +pub const ERROR_NO_SYSTEM_MENU: ::DWORD = 1437; +pub const ERROR_INVALID_MSGBOX_STYLE: ::DWORD = 1438; +pub const ERROR_INVALID_SPI_VALUE: ::DWORD = 1439; +pub const ERROR_SCREEN_ALREADY_LOCKED: ::DWORD = 1440; +pub const ERROR_HWNDS_HAVE_DIFF_PARENT: ::DWORD = 1441; +pub const ERROR_NOT_CHILD_WINDOW: ::DWORD = 1442; +pub const ERROR_INVALID_GW_COMMAND: ::DWORD = 1443; +pub const ERROR_INVALID_THREAD_ID: ::DWORD = 1444; +pub const ERROR_NON_MDICHILD_WINDOW: ::DWORD = 1445; +pub const ERROR_POPUP_ALREADY_ACTIVE: ::DWORD = 1446; +pub const ERROR_NO_SCROLLBARS: ::DWORD = 1447; +pub const ERROR_INVALID_SCROLLBAR_RANGE: ::DWORD = 1448; +pub const ERROR_INVALID_SHOWWIN_COMMAND: ::DWORD = 1449; +pub const ERROR_NO_SYSTEM_RESOURCES: ::DWORD = 1450; +pub const ERROR_NONPAGED_SYSTEM_RESOURCES: ::DWORD = 1451; +pub const ERROR_PAGED_SYSTEM_RESOURCES: ::DWORD = 1452; +pub const ERROR_WORKING_SET_QUOTA: ::DWORD = 1453; +pub const ERROR_PAGEFILE_QUOTA: ::DWORD = 1454; +pub const ERROR_COMMITMENT_LIMIT: ::DWORD = 1455; +pub const ERROR_MENU_ITEM_NOT_FOUND: ::DWORD = 1456; +pub const ERROR_INVALID_KEYBOARD_HANDLE: ::DWORD = 1457; +pub const ERROR_HOOK_TYPE_NOT_ALLOWED: ::DWORD = 1458; +pub const ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION: ::DWORD = 1459; +pub const ERROR_TIMEOUT: ::DWORD = 1460; +pub const ERROR_INVALID_MONITOR_HANDLE: ::DWORD = 1461; +pub const ERROR_INCORRECT_SIZE: ::DWORD = 1462; +pub const ERROR_SYMLINK_CLASS_DISABLED: ::DWORD = 1463; +pub const ERROR_SYMLINK_NOT_SUPPORTED: ::DWORD = 1464; +pub const ERROR_XML_PARSE_ERROR: ::DWORD = 1465; +pub const ERROR_XMLDSIG_ERROR: ::DWORD = 1466; +pub const ERROR_RESTART_APPLICATION: ::DWORD = 1467; +pub const ERROR_WRONG_COMPARTMENT: ::DWORD = 1468; +pub const ERROR_AUTHIP_FAILURE: ::DWORD = 1469; +pub const ERROR_NO_NVRAM_RESOURCES: ::DWORD = 1470; +pub const ERROR_NOT_GUI_PROCESS: ::DWORD = 1471; +pub const ERROR_EVENTLOG_FILE_CORRUPT: ::DWORD = 1500; +pub const ERROR_EVENTLOG_CANT_START: ::DWORD = 1501; +pub const ERROR_LOG_FILE_FULL: ::DWORD = 1502; +pub const ERROR_EVENTLOG_FILE_CHANGED: ::DWORD = 1503; +pub const ERROR_INVALID_TASK_NAME: ::DWORD = 1550; +pub const ERROR_INVALID_TASK_INDEX: ::DWORD = 1551; +pub const ERROR_THREAD_ALREADY_IN_TASK: ::DWORD = 1552; +pub const ERROR_INSTALL_SERVICE_FAILURE: ::DWORD = 1601; +pub const ERROR_INSTALL_USEREXIT: ::DWORD = 1602; +pub const ERROR_INSTALL_FAILURE: ::DWORD = 1603; +pub const ERROR_INSTALL_SUSPEND: ::DWORD = 1604; +pub const ERROR_UNKNOWN_PRODUCT: ::DWORD = 1605; +pub const ERROR_UNKNOWN_FEATURE: ::DWORD = 1606; +pub const ERROR_UNKNOWN_COMPONENT: ::DWORD = 1607; +pub const ERROR_UNKNOWN_PROPERTY: ::DWORD = 1608; +pub const ERROR_INVALID_HANDLE_STATE: ::DWORD = 1609; +pub const ERROR_BAD_CONFIGURATION: ::DWORD = 1610; +pub const ERROR_INDEX_ABSENT: ::DWORD = 1611; +pub const ERROR_INSTALL_SOURCE_ABSENT: ::DWORD = 1612; +pub const ERROR_INSTALL_PACKAGE_VERSION: ::DWORD = 1613; +pub const ERROR_PRODUCT_UNINSTALLED: ::DWORD = 1614; +pub const ERROR_BAD_QUERY_SYNTAX: ::DWORD = 1615; +pub const ERROR_INVALID_FIELD: ::DWORD = 1616; +pub const ERROR_DEVICE_REMOVED: ::DWORD = 1617; +pub const ERROR_INSTALL_ALREADY_RUNNING: ::DWORD = 1618; +pub const ERROR_INSTALL_PACKAGE_OPEN_FAILED: ::DWORD = 1619; +pub const ERROR_INSTALL_PACKAGE_INVALID: ::DWORD = 1620; +pub const ERROR_INSTALL_UI_FAILURE: ::DWORD = 1621; +pub const ERROR_INSTALL_LOG_FAILURE: ::DWORD = 1622; +pub const ERROR_INSTALL_LANGUAGE_UNSUPPORTED: ::DWORD = 1623; +pub const ERROR_INSTALL_TRANSFORM_FAILURE: ::DWORD = 1624; +pub const ERROR_INSTALL_PACKAGE_REJECTED: ::DWORD = 1625; +pub const ERROR_FUNCTION_NOT_CALLED: ::DWORD = 1626; +pub const ERROR_FUNCTION_FAILED: ::DWORD = 1627; +pub const ERROR_INVALID_TABLE: ::DWORD = 1628; +pub const ERROR_DATATYPE_MISMATCH: ::DWORD = 1629; +pub const ERROR_UNSUPPORTED_TYPE: ::DWORD = 1630; +pub const ERROR_CREATE_FAILED: ::DWORD = 1631; +pub const ERROR_INSTALL_TEMP_UNWRITABLE: ::DWORD = 1632; +pub const ERROR_INSTALL_PLATFORM_UNSUPPORTED: ::DWORD = 1633; +pub const ERROR_INSTALL_NOTUSED: ::DWORD = 1634; +pub const ERROR_PATCH_PACKAGE_OPEN_FAILED: ::DWORD = 1635; +pub const ERROR_PATCH_PACKAGE_INVALID: ::DWORD = 1636; +pub const ERROR_PATCH_PACKAGE_UNSUPPORTED: ::DWORD = 1637; +pub const ERROR_PRODUCT_VERSION: ::DWORD = 1638; +pub const ERROR_INVALID_COMMAND_LINE: ::DWORD = 1639; +pub const ERROR_INSTALL_REMOTE_DISALLOWED: ::DWORD = 1640; +pub const ERROR_SUCCESS_REBOOT_INITIATED: ::DWORD = 1641; +pub const ERROR_PATCH_TARGET_NOT_FOUND: ::DWORD = 1642; +pub const ERROR_PATCH_PACKAGE_REJECTED: ::DWORD = 1643; +pub const ERROR_INSTALL_TRANSFORM_REJECTED: ::DWORD = 1644; +pub const ERROR_INSTALL_REMOTE_PROHIBITED: ::DWORD = 1645; +pub const ERROR_PATCH_REMOVAL_UNSUPPORTED: ::DWORD = 1646; +pub const ERROR_UNKNOWN_PATCH: ::DWORD = 1647; +pub const ERROR_PATCH_NO_SEQUENCE: ::DWORD = 1648; +pub const ERROR_PATCH_REMOVAL_DISALLOWED: ::DWORD = 1649; +pub const ERROR_INVALID_PATCH_XML: ::DWORD = 1650; +pub const ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT: ::DWORD = 1651; +pub const ERROR_INSTALL_SERVICE_SAFEBOOT: ::DWORD = 1652; +pub const ERROR_FAIL_FAST_EXCEPTION: ::DWORD = 1653; +pub const ERROR_INSTALL_REJECTED: ::DWORD = 1654; +pub const ERROR_DYNAMIC_CODE_BLOCKED: ::DWORD = 1655; +pub const RPC_S_INVALID_STRING_BINDING: ::DWORD = 1700; +pub const RPC_S_WRONG_KIND_OF_BINDING: ::DWORD = 1701; +pub const RPC_S_INVALID_BINDING: ::DWORD = 1702; +pub const RPC_S_PROTSEQ_NOT_SUPPORTED: ::DWORD = 1703; +pub const RPC_S_INVALID_RPC_PROTSEQ: ::DWORD = 1704; +pub const RPC_S_INVALID_STRING_UUID: ::DWORD = 1705; +pub const RPC_S_INVALID_ENDPOINT_FORMAT: ::DWORD = 1706; +pub const RPC_S_INVALID_NET_ADDR: ::DWORD = 1707; +pub const RPC_S_NO_ENDPOINT_FOUND: ::DWORD = 1708; +pub const RPC_S_INVALID_TIMEOUT: ::DWORD = 1709; +pub const RPC_S_OBJECT_NOT_FOUND: ::DWORD = 1710; +pub const RPC_S_ALREADY_REGISTERED: ::DWORD = 1711; +pub const RPC_S_TYPE_ALREADY_REGISTERED: ::DWORD = 1712; +pub const RPC_S_ALREADY_LISTENING: ::DWORD = 1713; +pub const RPC_S_NO_PROTSEQS_REGISTERED: ::DWORD = 1714; +pub const RPC_S_NOT_LISTENING: ::DWORD = 1715; +pub const RPC_S_UNKNOWN_MGR_TYPE: ::DWORD = 1716; +pub const RPC_S_UNKNOWN_IF: ::DWORD = 1717; +pub const RPC_S_NO_BINDINGS: ::DWORD = 1718; +pub const RPC_S_NO_PROTSEQS: ::DWORD = 1719; +pub const RPC_S_CANT_CREATE_ENDPOINT: ::DWORD = 1720; +pub const RPC_S_OUT_OF_RESOURCES: ::DWORD = 1721; +pub const RPC_S_SERVER_UNAVAILABLE: ::DWORD = 1722; +pub const RPC_S_SERVER_TOO_BUSY: ::DWORD = 1723; +pub const RPC_S_INVALID_NETWORK_OPTIONS: ::DWORD = 1724; +pub const RPC_S_NO_CALL_ACTIVE: ::DWORD = 1725; +pub const RPC_S_CALL_FAILED: ::DWORD = 1726; +pub const RPC_S_CALL_FAILED_DNE: ::DWORD = 1727; +pub const RPC_S_PROTOCOL_ERROR: ::DWORD = 1728; +pub const RPC_S_PROXY_ACCESS_DENIED: ::DWORD = 1729; +pub const RPC_S_UNSUPPORTED_TRANS_SYN: ::DWORD = 1730; +pub const RPC_S_UNSUPPORTED_TYPE: ::DWORD = 1732; +pub const RPC_S_INVALID_TAG: ::DWORD = 1733; +pub const RPC_S_INVALID_BOUND: ::DWORD = 1734; +pub const RPC_S_NO_ENTRY_NAME: ::DWORD = 1735; +pub const RPC_S_INVALID_NAME_SYNTAX: ::DWORD = 1736; +pub const RPC_S_UNSUPPORTED_NAME_SYNTAX: ::DWORD = 1737; +pub const RPC_S_UUID_NO_ADDRESS: ::DWORD = 1739; +pub const RPC_S_DUPLICATE_ENDPOINT: ::DWORD = 1740; +pub const RPC_S_UNKNOWN_AUTHN_TYPE: ::DWORD = 1741; +pub const RPC_S_MAX_CALLS_TOO_SMALL: ::DWORD = 1742; +pub const RPC_S_STRING_TOO_LONG: ::DWORD = 1743; +pub const RPC_S_PROTSEQ_NOT_FOUND: ::DWORD = 1744; +pub const RPC_S_PROCNUM_OUT_OF_RANGE: ::DWORD = 1745; +pub const RPC_S_BINDING_HAS_NO_AUTH: ::DWORD = 1746; +pub const RPC_S_UNKNOWN_AUTHN_SERVICE: ::DWORD = 1747; +pub const RPC_S_UNKNOWN_AUTHN_LEVEL: ::DWORD = 1748; +pub const RPC_S_INVALID_AUTH_IDENTITY: ::DWORD = 1749; +pub const RPC_S_UNKNOWN_AUTHZ_SERVICE: ::DWORD = 1750; +pub const EPT_S_INVALID_ENTRY: ::DWORD = 1751; +pub const EPT_S_CANT_PERFORM_OP: ::DWORD = 1752; +pub const EPT_S_NOT_REGISTERED: ::DWORD = 1753; +pub const RPC_S_NOTHING_TO_EXPORT: ::DWORD = 1754; +pub const RPC_S_INCOMPLETE_NAME: ::DWORD = 1755; +pub const RPC_S_INVALID_VERS_OPTION: ::DWORD = 1756; +pub const RPC_S_NO_MORE_MEMBERS: ::DWORD = 1757; +pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED: ::DWORD = 1758; +pub const RPC_S_INTERFACE_NOT_FOUND: ::DWORD = 1759; +pub const RPC_S_ENTRY_ALREADY_EXISTS: ::DWORD = 1760; +pub const RPC_S_ENTRY_NOT_FOUND: ::DWORD = 1761; +pub const RPC_S_NAME_SERVICE_UNAVAILABLE: ::DWORD = 1762; +pub const RPC_S_INVALID_NAF_ID: ::DWORD = 1763; +pub const RPC_S_CANNOT_SUPPORT: ::DWORD = 1764; +pub const RPC_S_NO_CONTEXT_AVAILABLE: ::DWORD = 1765; +pub const RPC_S_INTERNAL_ERROR: ::DWORD = 1766; +pub const RPC_S_ZERO_DIVIDE: ::DWORD = 1767; +pub const RPC_S_ADDRESS_ERROR: ::DWORD = 1768; +pub const RPC_S_FP_DIV_ZERO: ::DWORD = 1769; +pub const RPC_S_FP_UNDERFLOW: ::DWORD = 1770; +pub const RPC_S_FP_OVERFLOW: ::DWORD = 1771; +pub const RPC_X_NO_MORE_ENTRIES: ::DWORD = 1772; +pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL: ::DWORD = 1773; +pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE: ::DWORD = 1774; +pub const RPC_X_SS_IN_NULL_CONTEXT: ::DWORD = 1775; +pub const RPC_X_SS_CONTEXT_DAMAGED: ::DWORD = 1777; +pub const RPC_X_SS_HANDLES_MISMATCH: ::DWORD = 1778; +pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE: ::DWORD = 1779; +pub const RPC_X_NULL_REF_POINTER: ::DWORD = 1780; +pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE: ::DWORD = 1781; +pub const RPC_X_BYTE_COUNT_TOO_SMALL: ::DWORD = 1782; +pub const RPC_X_BAD_STUB_DATA: ::DWORD = 1783; +pub const ERROR_INVALID_USER_BUFFER: ::DWORD = 1784; +pub const ERROR_UNRECOGNIZED_MEDIA: ::DWORD = 1785; +pub const ERROR_NO_TRUST_LSA_SECRET: ::DWORD = 1786; +pub const ERROR_NO_TRUST_SAM_ACCOUNT: ::DWORD = 1787; +pub const ERROR_TRUSTED_DOMAIN_FAILURE: ::DWORD = 1788; +pub const ERROR_TRUSTED_RELATIONSHIP_FAILURE: ::DWORD = 1789; +pub const ERROR_TRUST_FAILURE: ::DWORD = 1790; +pub const RPC_S_CALL_IN_PROGRESS: ::DWORD = 1791; +pub const ERROR_NETLOGON_NOT_STARTED: ::DWORD = 1792; +pub const ERROR_ACCOUNT_EXPIRED: ::DWORD = 1793; +pub const ERROR_REDIRECTOR_HAS_OPEN_HANDLES: ::DWORD = 1794; +pub const ERROR_PRINTER_DRIVER_ALREADY_INSTALLED: ::DWORD = 1795; +pub const ERROR_UNKNOWN_PORT: ::DWORD = 1796; +pub const ERROR_UNKNOWN_PRINTER_DRIVER: ::DWORD = 1797; +pub const ERROR_UNKNOWN_PRINTPROCESSOR: ::DWORD = 1798; +pub const ERROR_INVALID_SEPARATOR_FILE: ::DWORD = 1799; +pub const ERROR_INVALID_PRIORITY: ::DWORD = 1800; +pub const ERROR_INVALID_PRINTER_NAME: ::DWORD = 1801; +pub const ERROR_PRINTER_ALREADY_EXISTS: ::DWORD = 1802; +pub const ERROR_INVALID_PRINTER_COMMAND: ::DWORD = 1803; +pub const ERROR_INVALID_DATATYPE: ::DWORD = 1804; +pub const ERROR_INVALID_ENVIRONMENT: ::DWORD = 1805; +pub const RPC_S_NO_MORE_BINDINGS: ::DWORD = 1806; +pub const ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: ::DWORD = 1807; +pub const ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT: ::DWORD = 1808; +pub const ERROR_NOLOGON_SERVER_TRUST_ACCOUNT: ::DWORD = 1809; +pub const ERROR_DOMAIN_TRUST_INCONSISTENT: ::DWORD = 1810; +pub const ERROR_SERVER_HAS_OPEN_HANDLES: ::DWORD = 1811; +pub const ERROR_RESOURCE_DATA_NOT_FOUND: ::DWORD = 1812; +pub const ERROR_RESOURCE_TYPE_NOT_FOUND: ::DWORD = 1813; +pub const ERROR_RESOURCE_NAME_NOT_FOUND: ::DWORD = 1814; +pub const ERROR_RESOURCE_LANG_NOT_FOUND: ::DWORD = 1815; +pub const ERROR_NOT_ENOUGH_QUOTA: ::DWORD = 1816; +pub const RPC_S_NO_INTERFACES: ::DWORD = 1817; +pub const RPC_S_CALL_CANCELLED: ::DWORD = 1818; +pub const RPC_S_BINDING_INCOMPLETE: ::DWORD = 1819; +pub const RPC_S_COMM_FAILURE: ::DWORD = 1820; +pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL: ::DWORD = 1821; +pub const RPC_S_NO_PRINC_NAME: ::DWORD = 1822; +pub const RPC_S_NOT_RPC_ERROR: ::DWORD = 1823; +pub const RPC_S_UUID_LOCAL_ONLY: ::DWORD = 1824; +pub const RPC_S_SEC_PKG_ERROR: ::DWORD = 1825; +pub const RPC_S_NOT_CANCELLED: ::DWORD = 1826; +pub const RPC_X_INVALID_ES_ACTION: ::DWORD = 1827; +pub const RPC_X_WRONG_ES_VERSION: ::DWORD = 1828; +pub const RPC_X_WRONG_STUB_VERSION: ::DWORD = 1829; +pub const RPC_X_INVALID_PIPE_OBJECT: ::DWORD = 1830; +pub const RPC_X_WRONG_PIPE_ORDER: ::DWORD = 1831; +pub const RPC_X_WRONG_PIPE_VERSION: ::DWORD = 1832; +pub const RPC_S_COOKIE_AUTH_FAILED: ::DWORD = 1833; +pub const RPC_S_GROUP_MEMBER_NOT_FOUND: ::DWORD = 1898; +pub const EPT_S_CANT_CREATE: ::DWORD = 1899; +pub const RPC_S_INVALID_OBJECT: ::DWORD = 1900; +pub const ERROR_INVALID_TIME: ::DWORD = 1901; +pub const ERROR_INVALID_FORM_NAME: ::DWORD = 1902; +pub const ERROR_INVALID_FORM_SIZE: ::DWORD = 1903; +pub const ERROR_ALREADY_WAITING: ::DWORD = 1904; +pub const ERROR_PRINTER_DELETED: ::DWORD = 1905; +pub const ERROR_INVALID_PRINTER_STATE: ::DWORD = 1906; +pub const ERROR_PASSWORD_MUST_CHANGE: ::DWORD = 1907; +pub const ERROR_DOMAIN_CONTROLLER_NOT_FOUND: ::DWORD = 1908; +pub const ERROR_ACCOUNT_LOCKED_OUT: ::DWORD = 1909; +pub const OR_INVALID_OXID: ::DWORD = 1910; +pub const OR_INVALID_OID: ::DWORD = 1911; +pub const OR_INVALID_SET: ::DWORD = 1912; +pub const RPC_S_SEND_INCOMPLETE: ::DWORD = 1913; +pub const RPC_S_INVALID_ASYNC_HANDLE: ::DWORD = 1914; +pub const RPC_S_INVALID_ASYNC_CALL: ::DWORD = 1915; +pub const RPC_X_PIPE_CLOSED: ::DWORD = 1916; +pub const RPC_X_PIPE_DISCIPLINE_ERROR: ::DWORD = 1917; +pub const RPC_X_PIPE_EMPTY: ::DWORD = 1918; +pub const ERROR_NO_SITENAME: ::DWORD = 1919; +pub const ERROR_CANT_ACCESS_FILE: ::DWORD = 1920; +pub const ERROR_CANT_RESOLVE_FILENAME: ::DWORD = 1921; +pub const RPC_S_ENTRY_TYPE_MISMATCH: ::DWORD = 1922; +pub const RPC_S_NOT_ALL_OBJS_EXPORTED: ::DWORD = 1923; +pub const RPC_S_INTERFACE_NOT_EXPORTED: ::DWORD = 1924; +pub const RPC_S_PROFILE_NOT_ADDED: ::DWORD = 1925; +pub const RPC_S_PRF_ELT_NOT_ADDED: ::DWORD = 1926; +pub const RPC_S_PRF_ELT_NOT_REMOVED: ::DWORD = 1927; +pub const RPC_S_GRP_ELT_NOT_ADDED: ::DWORD = 1928; +pub const RPC_S_GRP_ELT_NOT_REMOVED: ::DWORD = 1929; +pub const ERROR_KM_DRIVER_BLOCKED: ::DWORD = 1930; +pub const ERROR_CONTEXT_EXPIRED: ::DWORD = 1931; +pub const ERROR_PER_USER_TRUST_QUOTA_EXCEEDED: ::DWORD = 1932; +pub const ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED: ::DWORD = 1933; +pub const ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED: ::DWORD = 1934; +pub const ERROR_AUTHENTICATION_FIREWALL_FAILED: ::DWORD = 1935; +pub const ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED: ::DWORD = 1936; +pub const ERROR_NTLM_BLOCKED: ::DWORD = 1937; +pub const ERROR_PASSWORD_CHANGE_REQUIRED: ::DWORD = 1938; +pub const ERROR_INVALID_PIXEL_FORMAT: ::DWORD = 2000; +pub const ERROR_BAD_DRIVER: ::DWORD = 2001; +pub const ERROR_INVALID_WINDOW_STYLE: ::DWORD = 2002; +pub const ERROR_METAFILE_NOT_SUPPORTED: ::DWORD = 2003; +pub const ERROR_TRANSFORM_NOT_SUPPORTED: ::DWORD = 2004; +pub const ERROR_CLIPPING_NOT_SUPPORTED: ::DWORD = 2005; +pub const ERROR_INVALID_CMM: ::DWORD = 2010; +pub const ERROR_INVALID_PROFILE: ::DWORD = 2011; +pub const ERROR_TAG_NOT_FOUND: ::DWORD = 2012; +pub const ERROR_TAG_NOT_PRESENT: ::DWORD = 2013; +pub const ERROR_DUPLICATE_TAG: ::DWORD = 2014; +pub const ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE: ::DWORD = 2015; +pub const ERROR_PROFILE_NOT_FOUND: ::DWORD = 2016; +pub const ERROR_INVALID_COLORSPACE: ::DWORD = 2017; +pub const ERROR_ICM_NOT_ENABLED: ::DWORD = 2018; +pub const ERROR_DELETING_ICM_XFORM: ::DWORD = 2019; +pub const ERROR_INVALID_TRANSFORM: ::DWORD = 2020; +pub const ERROR_COLORSPACE_MISMATCH: ::DWORD = 2021; +pub const ERROR_INVALID_COLORINDEX: ::DWORD = 2022; +pub const ERROR_PROFILE_DOES_NOT_MATCH_DEVICE: ::DWORD = 2023; +pub const ERROR_CONNECTED_OTHER_PASSWORD: ::DWORD = 2108; +pub const ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT: ::DWORD = 2109; +pub const ERROR_BAD_USERNAME: ::DWORD = 2202; +pub const ERROR_NOT_CONNECTED: ::DWORD = 2250; +pub const ERROR_OPEN_FILES: ::DWORD = 2401; +pub const ERROR_ACTIVE_CONNECTIONS: ::DWORD = 2402; +pub const ERROR_DEVICE_IN_USE: ::DWORD = 2404; +pub const ERROR_UNKNOWN_PRINT_MONITOR: ::DWORD = 3000; +pub const ERROR_PRINTER_DRIVER_IN_USE: ::DWORD = 3001; +pub const ERROR_SPOOL_FILE_NOT_FOUND: ::DWORD = 3002; +pub const ERROR_SPL_NO_STARTDOC: ::DWORD = 3003; +pub const ERROR_SPL_NO_ADDJOB: ::DWORD = 3004; +pub const ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED: ::DWORD = 3005; +pub const ERROR_PRINT_MONITOR_ALREADY_INSTALLED: ::DWORD = 3006; +pub const ERROR_INVALID_PRINT_MONITOR: ::DWORD = 3007; +pub const ERROR_PRINT_MONITOR_IN_USE: ::DWORD = 3008; +pub const ERROR_PRINTER_HAS_JOBS_QUEUED: ::DWORD = 3009; +pub const ERROR_SUCCESS_REBOOT_REQUIRED: ::DWORD = 3010; +pub const ERROR_SUCCESS_RESTART_REQUIRED: ::DWORD = 3011; +pub const ERROR_PRINTER_NOT_FOUND: ::DWORD = 3012; +pub const ERROR_PRINTER_DRIVER_WARNED: ::DWORD = 3013; +pub const ERROR_PRINTER_DRIVER_BLOCKED: ::DWORD = 3014; +pub const ERROR_PRINTER_DRIVER_PACKAGE_IN_USE: ::DWORD = 3015; +pub const ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND: ::DWORD = 3016; +pub const ERROR_FAIL_REBOOT_REQUIRED: ::DWORD = 3017; +pub const ERROR_FAIL_REBOOT_INITIATED: ::DWORD = 3018; +pub const ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED: ::DWORD = 3019; +pub const ERROR_PRINT_JOB_RESTART_REQUIRED: ::DWORD = 3020; +pub const ERROR_INVALID_PRINTER_DRIVER_MANIFEST: ::DWORD = 3021; +pub const ERROR_PRINTER_NOT_SHAREABLE: ::DWORD = 3022; +pub const ERROR_REQUEST_PAUSED: ::DWORD = 3050; +pub const ERROR_IO_REISSUE_AS_CACHED: ::DWORD = 3950; +pub const ERROR_WINS_INTERNAL: ::DWORD = 4000; +pub const ERROR_CAN_NOT_DEL_LOCAL_WINS: ::DWORD = 4001; +pub const ERROR_STATIC_INIT: ::DWORD = 4002; +pub const ERROR_INC_BACKUP: ::DWORD = 4003; +pub const ERROR_FULL_BACKUP: ::DWORD = 4004; +pub const ERROR_REC_NON_EXISTENT: ::DWORD = 4005; +pub const ERROR_RPL_NOT_ALLOWED: ::DWORD = 4006; +pub const PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED: ::DWORD = 4050; +pub const PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO: ::DWORD = 4051; +pub const PEERDIST_ERROR_MISSING_DATA: ::DWORD = 4052; +pub const PEERDIST_ERROR_NO_MORE: ::DWORD = 4053; +pub const PEERDIST_ERROR_NOT_INITIALIZED: ::DWORD = 4054; +pub const PEERDIST_ERROR_ALREADY_INITIALIZED: ::DWORD = 4055; +pub const PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS: ::DWORD = 4056; +pub const PEERDIST_ERROR_INVALIDATED: ::DWORD = 4057; +pub const PEERDIST_ERROR_ALREADY_EXISTS: ::DWORD = 4058; +pub const PEERDIST_ERROR_OPERATION_NOTFOUND: ::DWORD = 4059; +pub const PEERDIST_ERROR_ALREADY_COMPLETED: ::DWORD = 4060; +pub const PEERDIST_ERROR_OUT_OF_BOUNDS: ::DWORD = 4061; +pub const PEERDIST_ERROR_VERSION_UNSUPPORTED: ::DWORD = 4062; +pub const PEERDIST_ERROR_INVALID_CONFIGURATION: ::DWORD = 4063; +pub const PEERDIST_ERROR_NOT_LICENSED: ::DWORD = 4064; +pub const PEERDIST_ERROR_SERVICE_UNAVAILABLE: ::DWORD = 4065; +pub const PEERDIST_ERROR_TRUST_FAILURE: ::DWORD = 4066; +pub const ERROR_DHCP_ADDRESS_CONFLICT: ::DWORD = 4100; +pub const ERROR_WMI_GUID_NOT_FOUND: ::DWORD = 4200; +pub const ERROR_WMI_INSTANCE_NOT_FOUND: ::DWORD = 4201; +pub const ERROR_WMI_ITEMID_NOT_FOUND: ::DWORD = 4202; +pub const ERROR_WMI_TRY_AGAIN: ::DWORD = 4203; +pub const ERROR_WMI_DP_NOT_FOUND: ::DWORD = 4204; +pub const ERROR_WMI_UNRESOLVED_INSTANCE_REF: ::DWORD = 4205; +pub const ERROR_WMI_ALREADY_ENABLED: ::DWORD = 4206; +pub const ERROR_WMI_GUID_DISCONNECTED: ::DWORD = 4207; +pub const ERROR_WMI_SERVER_UNAVAILABLE: ::DWORD = 4208; +pub const ERROR_WMI_DP_FAILED: ::DWORD = 4209; +pub const ERROR_WMI_INVALID_MOF: ::DWORD = 4210; +pub const ERROR_WMI_INVALID_REGINFO: ::DWORD = 4211; +pub const ERROR_WMI_ALREADY_DISABLED: ::DWORD = 4212; +pub const ERROR_WMI_READ_ONLY: ::DWORD = 4213; +pub const ERROR_WMI_SET_FAILURE: ::DWORD = 4214; +pub const ERROR_NOT_APPCONTAINER: ::DWORD = 4250; +pub const ERROR_APPCONTAINER_REQUIRED: ::DWORD = 4251; +pub const ERROR_NOT_SUPPORTED_IN_APPCONTAINER: ::DWORD = 4252; +pub const ERROR_INVALID_PACKAGE_SID_LENGTH: ::DWORD = 4253; +pub const ERROR_INVALID_MEDIA: ::DWORD = 4300; +pub const ERROR_INVALID_LIBRARY: ::DWORD = 4301; +pub const ERROR_INVALID_MEDIA_POOL: ::DWORD = 4302; +pub const ERROR_DRIVE_MEDIA_MISMATCH: ::DWORD = 4303; +pub const ERROR_MEDIA_OFFLINE: ::DWORD = 4304; +pub const ERROR_LIBRARY_OFFLINE: ::DWORD = 4305; +pub const ERROR_EMPTY: ::DWORD = 4306; +pub const ERROR_NOT_EMPTY: ::DWORD = 4307; +pub const ERROR_MEDIA_UNAVAILABLE: ::DWORD = 4308; +pub const ERROR_RESOURCE_DISABLED: ::DWORD = 4309; +pub const ERROR_INVALID_CLEANER: ::DWORD = 4310; +pub const ERROR_UNABLE_TO_CLEAN: ::DWORD = 4311; +pub const ERROR_OBJECT_NOT_FOUND: ::DWORD = 4312; +pub const ERROR_DATABASE_FAILURE: ::DWORD = 4313; +pub const ERROR_DATABASE_FULL: ::DWORD = 4314; +pub const ERROR_MEDIA_INCOMPATIBLE: ::DWORD = 4315; +pub const ERROR_RESOURCE_NOT_PRESENT: ::DWORD = 4316; +pub const ERROR_INVALID_OPERATION: ::DWORD = 4317; +pub const ERROR_MEDIA_NOT_AVAILABLE: ::DWORD = 4318; +pub const ERROR_DEVICE_NOT_AVAILABLE: ::DWORD = 4319; +pub const ERROR_REQUEST_REFUSED: ::DWORD = 4320; +pub const ERROR_INVALID_DRIVE_OBJECT: ::DWORD = 4321; +pub const ERROR_LIBRARY_FULL: ::DWORD = 4322; +pub const ERROR_MEDIUM_NOT_ACCESSIBLE: ::DWORD = 4323; +pub const ERROR_UNABLE_TO_LOAD_MEDIUM: ::DWORD = 4324; +pub const ERROR_UNABLE_TO_INVENTORY_DRIVE: ::DWORD = 4325; +pub const ERROR_UNABLE_TO_INVENTORY_SLOT: ::DWORD = 4326; +pub const ERROR_UNABLE_TO_INVENTORY_TRANSPORT: ::DWORD = 4327; +pub const ERROR_TRANSPORT_FULL: ::DWORD = 4328; +pub const ERROR_CONTROLLING_IEPORT: ::DWORD = 4329; +pub const ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA: ::DWORD = 4330; +pub const ERROR_CLEANER_SLOT_SET: ::DWORD = 4331; +pub const ERROR_CLEANER_SLOT_NOT_SET: ::DWORD = 4332; +pub const ERROR_CLEANER_CARTRIDGE_SPENT: ::DWORD = 4333; +pub const ERROR_UNEXPECTED_OMID: ::DWORD = 4334; +pub const ERROR_CANT_DELETE_LAST_ITEM: ::DWORD = 4335; +pub const ERROR_MESSAGE_EXCEEDS_MAX_SIZE: ::DWORD = 4336; +pub const ERROR_VOLUME_CONTAINS_SYS_FILES: ::DWORD = 4337; +pub const ERROR_INDIGENOUS_TYPE: ::DWORD = 4338; +pub const ERROR_NO_SUPPORTING_DRIVES: ::DWORD = 4339; +pub const ERROR_CLEANER_CARTRIDGE_INSTALLED: ::DWORD = 4340; +pub const ERROR_IEPORT_FULL: ::DWORD = 4341; +pub const ERROR_FILE_OFFLINE: ::DWORD = 4350; +pub const ERROR_REMOTE_STORAGE_NOT_ACTIVE: ::DWORD = 4351; +pub const ERROR_REMOTE_STORAGE_MEDIA_ERROR: ::DWORD = 4352; +pub const ERROR_NOT_A_REPARSE_POINT: ::DWORD = 4390; +pub const ERROR_REPARSE_ATTRIBUTE_CONFLICT: ::DWORD = 4391; +pub const ERROR_INVALID_REPARSE_DATA: ::DWORD = 4392; +pub const ERROR_REPARSE_TAG_INVALID: ::DWORD = 4393; +pub const ERROR_REPARSE_TAG_MISMATCH: ::DWORD = 4394; +pub const ERROR_APP_DATA_NOT_FOUND: ::DWORD = 4400; +pub const ERROR_APP_DATA_EXPIRED: ::DWORD = 4401; +pub const ERROR_APP_DATA_CORRUPT: ::DWORD = 4402; +pub const ERROR_APP_DATA_LIMIT_EXCEEDED: ::DWORD = 4403; +pub const ERROR_APP_DATA_REBOOT_REQUIRED: ::DWORD = 4404; +pub const ERROR_SECUREBOOT_ROLLBACK_DETECTED: ::DWORD = 4420; +pub const ERROR_SECUREBOOT_POLICY_VIOLATION: ::DWORD = 4421; +pub const ERROR_SECUREBOOT_INVALID_POLICY: ::DWORD = 4422; +pub const ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND: ::DWORD = 4423; +pub const ERROR_SECUREBOOT_POLICY_NOT_SIGNED: ::DWORD = 4424; +pub const ERROR_SECUREBOOT_NOT_ENABLED: ::DWORD = 4425; +pub const ERROR_SECUREBOOT_FILE_REPLACED: ::DWORD = 4426; +pub const ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED: ::DWORD = 4440; +pub const ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED: ::DWORD = 4441; +pub const ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED: ::DWORD = 4442; +pub const ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED: ::DWORD = 4443; +pub const ERROR_VOLUME_NOT_SIS_ENABLED: ::DWORD = 4500; +pub const ERROR_DEPENDENT_RESOURCE_EXISTS: ::DWORD = 5001; +pub const ERROR_DEPENDENCY_NOT_FOUND: ::DWORD = 5002; +pub const ERROR_DEPENDENCY_ALREADY_EXISTS: ::DWORD = 5003; +pub const ERROR_RESOURCE_NOT_ONLINE: ::DWORD = 5004; +pub const ERROR_HOST_NODE_NOT_AVAILABLE: ::DWORD = 5005; +pub const ERROR_RESOURCE_NOT_AVAILABLE: ::DWORD = 5006; +pub const ERROR_RESOURCE_NOT_FOUND: ::DWORD = 5007; +pub const ERROR_SHUTDOWN_CLUSTER: ::DWORD = 5008; +pub const ERROR_CANT_EVICT_ACTIVE_NODE: ::DWORD = 5009; +pub const ERROR_OBJECT_ALREADY_EXISTS: ::DWORD = 5010; +pub const ERROR_OBJECT_IN_LIST: ::DWORD = 5011; +pub const ERROR_GROUP_NOT_AVAILABLE: ::DWORD = 5012; +pub const ERROR_GROUP_NOT_FOUND: ::DWORD = 5013; +pub const ERROR_GROUP_NOT_ONLINE: ::DWORD = 5014; +pub const ERROR_HOST_NODE_NOT_RESOURCE_OWNER: ::DWORD = 5015; +pub const ERROR_HOST_NODE_NOT_GROUP_OWNER: ::DWORD = 5016; +pub const ERROR_RESMON_CREATE_FAILED: ::DWORD = 5017; +pub const ERROR_RESMON_ONLINE_FAILED: ::DWORD = 5018; +pub const ERROR_RESOURCE_ONLINE: ::DWORD = 5019; +pub const ERROR_QUORUM_RESOURCE: ::DWORD = 5020; +pub const ERROR_NOT_QUORUM_CAPABLE: ::DWORD = 5021; +pub const ERROR_CLUSTER_SHUTTING_DOWN: ::DWORD = 5022; +pub const ERROR_INVALID_STATE: ::DWORD = 5023; +pub const ERROR_RESOURCE_PROPERTIES_STORED: ::DWORD = 5024; +pub const ERROR_NOT_QUORUM_CLASS: ::DWORD = 5025; +pub const ERROR_CORE_RESOURCE: ::DWORD = 5026; +pub const ERROR_QUORUM_RESOURCE_ONLINE_FAILED: ::DWORD = 5027; +pub const ERROR_QUORUMLOG_OPEN_FAILED: ::DWORD = 5028; +pub const ERROR_CLUSTERLOG_CORRUPT: ::DWORD = 5029; +pub const ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE: ::DWORD = 5030; +pub const ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE: ::DWORD = 5031; +pub const ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND: ::DWORD = 5032; +pub const ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE: ::DWORD = 5033; +pub const ERROR_QUORUM_OWNER_ALIVE: ::DWORD = 5034; +pub const ERROR_NETWORK_NOT_AVAILABLE: ::DWORD = 5035; +pub const ERROR_NODE_NOT_AVAILABLE: ::DWORD = 5036; +pub const ERROR_ALL_NODES_NOT_AVAILABLE: ::DWORD = 5037; +pub const ERROR_RESOURCE_FAILED: ::DWORD = 5038; +pub const ERROR_CLUSTER_INVALID_NODE: ::DWORD = 5039; +pub const ERROR_CLUSTER_NODE_EXISTS: ::DWORD = 5040; +pub const ERROR_CLUSTER_JOIN_IN_PROGRESS: ::DWORD = 5041; +pub const ERROR_CLUSTER_NODE_NOT_FOUND: ::DWORD = 5042; +pub const ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND: ::DWORD = 5043; +pub const ERROR_CLUSTER_NETWORK_EXISTS: ::DWORD = 5044; +pub const ERROR_CLUSTER_NETWORK_NOT_FOUND: ::DWORD = 5045; +pub const ERROR_CLUSTER_NETINTERFACE_EXISTS: ::DWORD = 5046; +pub const ERROR_CLUSTER_NETINTERFACE_NOT_FOUND: ::DWORD = 5047; +pub const ERROR_CLUSTER_INVALID_REQUEST: ::DWORD = 5048; +pub const ERROR_CLUSTER_INVALID_NETWORK_PROVIDER: ::DWORD = 5049; +pub const ERROR_CLUSTER_NODE_DOWN: ::DWORD = 5050; +pub const ERROR_CLUSTER_NODE_UNREACHABLE: ::DWORD = 5051; +pub const ERROR_CLUSTER_NODE_NOT_MEMBER: ::DWORD = 5052; +pub const ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS: ::DWORD = 5053; +pub const ERROR_CLUSTER_INVALID_NETWORK: ::DWORD = 5054; +pub const ERROR_CLUSTER_NODE_UP: ::DWORD = 5056; +pub const ERROR_CLUSTER_IPADDR_IN_USE: ::DWORD = 5057; +pub const ERROR_CLUSTER_NODE_NOT_PAUSED: ::DWORD = 5058; +pub const ERROR_CLUSTER_NO_SECURITY_CONTEXT: ::DWORD = 5059; +pub const ERROR_CLUSTER_NETWORK_NOT_INTERNAL: ::DWORD = 5060; +pub const ERROR_CLUSTER_NODE_ALREADY_UP: ::DWORD = 5061; +pub const ERROR_CLUSTER_NODE_ALREADY_DOWN: ::DWORD = 5062; +pub const ERROR_CLUSTER_NETWORK_ALREADY_ONLINE: ::DWORD = 5063; +pub const ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE: ::DWORD = 5064; +pub const ERROR_CLUSTER_NODE_ALREADY_MEMBER: ::DWORD = 5065; +pub const ERROR_CLUSTER_LAST_INTERNAL_NETWORK: ::DWORD = 5066; +pub const ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS: ::DWORD = 5067; +pub const ERROR_INVALID_OPERATION_ON_QUORUM: ::DWORD = 5068; +pub const ERROR_DEPENDENCY_NOT_ALLOWED: ::DWORD = 5069; +pub const ERROR_CLUSTER_NODE_PAUSED: ::DWORD = 5070; +pub const ERROR_NODE_CANT_HOST_RESOURCE: ::DWORD = 5071; +pub const ERROR_CLUSTER_NODE_NOT_READY: ::DWORD = 5072; +pub const ERROR_CLUSTER_NODE_SHUTTING_DOWN: ::DWORD = 5073; +pub const ERROR_CLUSTER_JOIN_ABORTED: ::DWORD = 5074; +pub const ERROR_CLUSTER_INCOMPATIBLE_VERSIONS: ::DWORD = 5075; +pub const ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED: ::DWORD = 5076; +pub const ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED: ::DWORD = 5077; +pub const ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND: ::DWORD = 5078; +pub const ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED: ::DWORD = 5079; +pub const ERROR_CLUSTER_RESNAME_NOT_FOUND: ::DWORD = 5080; +pub const ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED: ::DWORD = 5081; +pub const ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST: ::DWORD = 5082; +pub const ERROR_CLUSTER_DATABASE_SEQMISMATCH: ::DWORD = 5083; +pub const ERROR_RESMON_INVALID_STATE: ::DWORD = 5084; +pub const ERROR_CLUSTER_GUM_NOT_LOCKER: ::DWORD = 5085; +pub const ERROR_QUORUM_DISK_NOT_FOUND: ::DWORD = 5086; +pub const ERROR_DATABASE_BACKUP_CORRUPT: ::DWORD = 5087; +pub const ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT: ::DWORD = 5088; +pub const ERROR_RESOURCE_PROPERTY_UNCHANGEABLE: ::DWORD = 5089; +pub const ERROR_NO_ADMIN_ACCESS_POINT: ::DWORD = 5090; +pub const ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE: ::DWORD = 5890; +pub const ERROR_CLUSTER_QUORUMLOG_NOT_FOUND: ::DWORD = 5891; +pub const ERROR_CLUSTER_MEMBERSHIP_HALT: ::DWORD = 5892; +pub const ERROR_CLUSTER_INSTANCE_ID_MISMATCH: ::DWORD = 5893; +pub const ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP: ::DWORD = 5894; +pub const ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH: ::DWORD = 5895; +pub const ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP: ::DWORD = 5896; +pub const ERROR_CLUSTER_PARAMETER_MISMATCH: ::DWORD = 5897; +pub const ERROR_NODE_CANNOT_BE_CLUSTERED: ::DWORD = 5898; +pub const ERROR_CLUSTER_WRONG_OS_VERSION: ::DWORD = 5899; +pub const ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME: ::DWORD = 5900; +pub const ERROR_CLUSCFG_ALREADY_COMMITTED: ::DWORD = 5901; +pub const ERROR_CLUSCFG_ROLLBACK_FAILED: ::DWORD = 5902; +pub const ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT: ::DWORD = 5903; +pub const ERROR_CLUSTER_OLD_VERSION: ::DWORD = 5904; +pub const ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME: ::DWORD = 5905; +pub const ERROR_CLUSTER_NO_NET_ADAPTERS: ::DWORD = 5906; +pub const ERROR_CLUSTER_POISONED: ::DWORD = 5907; +pub const ERROR_CLUSTER_GROUP_MOVING: ::DWORD = 5908; +pub const ERROR_CLUSTER_RESOURCE_TYPE_BUSY: ::DWORD = 5909; +pub const ERROR_RESOURCE_CALL_TIMED_OUT: ::DWORD = 5910; +pub const ERROR_INVALID_CLUSTER_IPV6_ADDRESS: ::DWORD = 5911; +pub const ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION: ::DWORD = 5912; +pub const ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS: ::DWORD = 5913; +pub const ERROR_CLUSTER_PARTIAL_SEND: ::DWORD = 5914; +pub const ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION: ::DWORD = 5915; +pub const ERROR_CLUSTER_INVALID_STRING_TERMINATION: ::DWORD = 5916; +pub const ERROR_CLUSTER_INVALID_STRING_FORMAT: ::DWORD = 5917; +pub const ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS: ::DWORD = 5918; +pub const ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS: ::DWORD = 5919; +pub const ERROR_CLUSTER_NULL_DATA: ::DWORD = 5920; +pub const ERROR_CLUSTER_PARTIAL_READ: ::DWORD = 5921; +pub const ERROR_CLUSTER_PARTIAL_WRITE: ::DWORD = 5922; +pub const ERROR_CLUSTER_CANT_DESERIALIZE_DATA: ::DWORD = 5923; +pub const ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT: ::DWORD = 5924; +pub const ERROR_CLUSTER_NO_QUORUM: ::DWORD = 5925; +pub const ERROR_CLUSTER_INVALID_IPV6_NETWORK: ::DWORD = 5926; +pub const ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK: ::DWORD = 5927; +pub const ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP: ::DWORD = 5928; +pub const ERROR_DEPENDENCY_TREE_TOO_COMPLEX: ::DWORD = 5929; +pub const ERROR_EXCEPTION_IN_RESOURCE_CALL: ::DWORD = 5930; +pub const ERROR_CLUSTER_RHS_FAILED_INITIALIZATION: ::DWORD = 5931; +pub const ERROR_CLUSTER_NOT_INSTALLED: ::DWORD = 5932; +pub const ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE: ::DWORD = 5933; +pub const ERROR_CLUSTER_MAX_NODES_IN_CLUSTER: ::DWORD = 5934; +pub const ERROR_CLUSTER_TOO_MANY_NODES: ::DWORD = 5935; +pub const ERROR_CLUSTER_OBJECT_ALREADY_USED: ::DWORD = 5936; +pub const ERROR_NONCORE_GROUPS_FOUND: ::DWORD = 5937; +pub const ERROR_FILE_SHARE_RESOURCE_CONFLICT: ::DWORD = 5938; +pub const ERROR_CLUSTER_EVICT_INVALID_REQUEST: ::DWORD = 5939; +pub const ERROR_CLUSTER_SINGLETON_RESOURCE: ::DWORD = 5940; +pub const ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE: ::DWORD = 5941; +pub const ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED: ::DWORD = 5942; +pub const ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR: ::DWORD = 5943; +pub const ERROR_CLUSTER_GROUP_BUSY: ::DWORD = 5944; +pub const ERROR_CLUSTER_NOT_SHARED_VOLUME: ::DWORD = 5945; +pub const ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR: ::DWORD = 5946; +pub const ERROR_CLUSTER_SHARED_VOLUMES_IN_USE: ::DWORD = 5947; +pub const ERROR_CLUSTER_USE_SHARED_VOLUMES_API: ::DWORD = 5948; +pub const ERROR_CLUSTER_BACKUP_IN_PROGRESS: ::DWORD = 5949; +pub const ERROR_NON_CSV_PATH: ::DWORD = 5950; +pub const ERROR_CSV_VOLUME_NOT_LOCAL: ::DWORD = 5951; +pub const ERROR_CLUSTER_WATCHDOG_TERMINATING: ::DWORD = 5952; +pub const ERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES: ::DWORD = 5953; +pub const ERROR_CLUSTER_INVALID_NODE_WEIGHT: ::DWORD = 5954; +pub const ERROR_CLUSTER_RESOURCE_VETOED_CALL: ::DWORD = 5955; +pub const ERROR_RESMON_SYSTEM_RESOURCES_LACKING: ::DWORD = 5956; +pub const ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION: ::DWORD = 5957; +pub const ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE: ::DWORD = 5958; +pub const ERROR_CLUSTER_GROUP_QUEUED: ::DWORD = 5959; +pub const ERROR_CLUSTER_RESOURCE_LOCKED_STATUS: ::DWORD = 5960; +pub const ERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED: ::DWORD = 5961; +pub const ERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS: ::DWORD = 5962; +pub const ERROR_CLUSTER_DISK_NOT_CONNECTED: ::DWORD = 5963; +pub const ERROR_DISK_NOT_CSV_CAPABLE: ::DWORD = 5964; +pub const ERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE: ::DWORD = 5965; +pub const ERROR_CLUSTER_SHARED_VOLUME_REDIRECTED: ::DWORD = 5966; +pub const ERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED: ::DWORD = 5967; +pub const ERROR_CLUSTER_CANNOT_RETURN_PROPERTIES: ::DWORD = 5968; +pub const ERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES: ::DWORD = 5969; +pub const ERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE: ::DWORD = 5970; +pub const ERROR_CLUSTER_AFFINITY_CONFLICT: ::DWORD = 5971; +pub const ERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE: ::DWORD = 5972; +pub const ERROR_ENCRYPTION_FAILED: ::DWORD = 6000; +pub const ERROR_DECRYPTION_FAILED: ::DWORD = 6001; +pub const ERROR_FILE_ENCRYPTED: ::DWORD = 6002; +pub const ERROR_NO_RECOVERY_POLICY: ::DWORD = 6003; +pub const ERROR_NO_EFS: ::DWORD = 6004; +pub const ERROR_WRONG_EFS: ::DWORD = 6005; +pub const ERROR_NO_USER_KEYS: ::DWORD = 6006; +pub const ERROR_FILE_NOT_ENCRYPTED: ::DWORD = 6007; +pub const ERROR_NOT_EXPORT_FORMAT: ::DWORD = 6008; +pub const ERROR_FILE_READ_ONLY: ::DWORD = 6009; +pub const ERROR_DIR_EFS_DISALLOWED: ::DWORD = 6010; +pub const ERROR_EFS_SERVER_NOT_TRUSTED: ::DWORD = 6011; +pub const ERROR_BAD_RECOVERY_POLICY: ::DWORD = 6012; +pub const ERROR_EFS_ALG_BLOB_TOO_BIG: ::DWORD = 6013; +pub const ERROR_VOLUME_NOT_SUPPORT_EFS: ::DWORD = 6014; +pub const ERROR_EFS_DISABLED: ::DWORD = 6015; +pub const ERROR_EFS_VERSION_NOT_SUPPORT: ::DWORD = 6016; +pub const ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE: ::DWORD = 6017; +pub const ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER: ::DWORD = 6018; +pub const ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE: ::DWORD = 6019; +pub const ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE: ::DWORD = 6020; +pub const ERROR_CS_ENCRYPTION_FILE_NOT_CSE: ::DWORD = 6021; +pub const ERROR_ENCRYPTION_POLICY_DENIES_OPERATION: ::DWORD = 6022; +pub const ERROR_NO_BROWSER_SERVERS_FOUND: ::DWORD = 6118; +pub const SCHED_E_SERVICE_NOT_LOCALSYSTEM: ::DWORD = 6200; +pub const ERROR_LOG_SECTOR_INVALID: ::DWORD = 6600; +pub const ERROR_LOG_SECTOR_PARITY_INVALID: ::DWORD = 6601; +pub const ERROR_LOG_SECTOR_REMAPPED: ::DWORD = 6602; +pub const ERROR_LOG_BLOCK_INCOMPLETE: ::DWORD = 6603; +pub const ERROR_LOG_INVALID_RANGE: ::DWORD = 6604; +pub const ERROR_LOG_BLOCKS_EXHAUSTED: ::DWORD = 6605; +pub const ERROR_LOG_READ_CONTEXT_INVALID: ::DWORD = 6606; +pub const ERROR_LOG_RESTART_INVALID: ::DWORD = 6607; +pub const ERROR_LOG_BLOCK_VERSION: ::DWORD = 6608; +pub const ERROR_LOG_BLOCK_INVALID: ::DWORD = 6609; +pub const ERROR_LOG_READ_MODE_INVALID: ::DWORD = 6610; +pub const ERROR_LOG_NO_RESTART: ::DWORD = 6611; +pub const ERROR_LOG_METADATA_CORRUPT: ::DWORD = 6612; +pub const ERROR_LOG_METADATA_INVALID: ::DWORD = 6613; +pub const ERROR_LOG_METADATA_INCONSISTENT: ::DWORD = 6614; +pub const ERROR_LOG_RESERVATION_INVALID: ::DWORD = 6615; +pub const ERROR_LOG_CANT_DELETE: ::DWORD = 6616; +pub const ERROR_LOG_CONTAINER_LIMIT_EXCEEDED: ::DWORD = 6617; +pub const ERROR_LOG_START_OF_LOG: ::DWORD = 6618; +pub const ERROR_LOG_POLICY_ALREADY_INSTALLED: ::DWORD = 6619; +pub const ERROR_LOG_POLICY_NOT_INSTALLED: ::DWORD = 6620; +pub const ERROR_LOG_POLICY_INVALID: ::DWORD = 6621; +pub const ERROR_LOG_POLICY_CONFLICT: ::DWORD = 6622; +pub const ERROR_LOG_PINNED_ARCHIVE_TAIL: ::DWORD = 6623; +pub const ERROR_LOG_RECORD_NONEXISTENT: ::DWORD = 6624; +pub const ERROR_LOG_RECORDS_RESERVED_INVALID: ::DWORD = 6625; +pub const ERROR_LOG_SPACE_RESERVED_INVALID: ::DWORD = 6626; +pub const ERROR_LOG_TAIL_INVALID: ::DWORD = 6627; +pub const ERROR_LOG_FULL: ::DWORD = 6628; +pub const ERROR_COULD_NOT_RESIZE_LOG: ::DWORD = 6629; +pub const ERROR_LOG_MULTIPLEXED: ::DWORD = 6630; +pub const ERROR_LOG_DEDICATED: ::DWORD = 6631; +pub const ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS: ::DWORD = 6632; +pub const ERROR_LOG_ARCHIVE_IN_PROGRESS: ::DWORD = 6633; +pub const ERROR_LOG_EPHEMERAL: ::DWORD = 6634; +pub const ERROR_LOG_NOT_ENOUGH_CONTAINERS: ::DWORD = 6635; +pub const ERROR_LOG_CLIENT_ALREADY_REGISTERED: ::DWORD = 6636; +pub const ERROR_LOG_CLIENT_NOT_REGISTERED: ::DWORD = 6637; +pub const ERROR_LOG_FULL_HANDLER_IN_PROGRESS: ::DWORD = 6638; +pub const ERROR_LOG_CONTAINER_READ_FAILED: ::DWORD = 6639; +pub const ERROR_LOG_CONTAINER_WRITE_FAILED: ::DWORD = 6640; +pub const ERROR_LOG_CONTAINER_OPEN_FAILED: ::DWORD = 6641; +pub const ERROR_LOG_CONTAINER_STATE_INVALID: ::DWORD = 6642; +pub const ERROR_LOG_STATE_INVALID: ::DWORD = 6643; +pub const ERROR_LOG_PINNED: ::DWORD = 6644; +pub const ERROR_LOG_METADATA_FLUSH_FAILED: ::DWORD = 6645; +pub const ERROR_LOG_INCONSISTENT_SECURITY: ::DWORD = 6646; +pub const ERROR_LOG_APPENDED_FLUSH_FAILED: ::DWORD = 6647; +pub const ERROR_LOG_PINNED_RESERVATION: ::DWORD = 6648; +pub const ERROR_INVALID_TRANSACTION: ::DWORD = 6700; +pub const ERROR_TRANSACTION_NOT_ACTIVE: ::DWORD = 6701; +pub const ERROR_TRANSACTION_REQUEST_NOT_VALID: ::DWORD = 6702; +pub const ERROR_TRANSACTION_NOT_REQUESTED: ::DWORD = 6703; +pub const ERROR_TRANSACTION_ALREADY_ABORTED: ::DWORD = 6704; +pub const ERROR_TRANSACTION_ALREADY_COMMITTED: ::DWORD = 6705; +pub const ERROR_TM_INITIALIZATION_FAILED: ::DWORD = 6706; +pub const ERROR_RESOURCEMANAGER_READ_ONLY: ::DWORD = 6707; +pub const ERROR_TRANSACTION_NOT_JOINED: ::DWORD = 6708; +pub const ERROR_TRANSACTION_SUPERIOR_EXISTS: ::DWORD = 6709; +pub const ERROR_CRM_PROTOCOL_ALREADY_EXISTS: ::DWORD = 6710; +pub const ERROR_TRANSACTION_PROPAGATION_FAILED: ::DWORD = 6711; +pub const ERROR_CRM_PROTOCOL_NOT_FOUND: ::DWORD = 6712; +pub const ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER: ::DWORD = 6713; +pub const ERROR_CURRENT_TRANSACTION_NOT_VALID: ::DWORD = 6714; +pub const ERROR_TRANSACTION_NOT_FOUND: ::DWORD = 6715; +pub const ERROR_RESOURCEMANAGER_NOT_FOUND: ::DWORD = 6716; +pub const ERROR_ENLISTMENT_NOT_FOUND: ::DWORD = 6717; +pub const ERROR_TRANSACTIONMANAGER_NOT_FOUND: ::DWORD = 6718; +pub const ERROR_TRANSACTIONMANAGER_NOT_ONLINE: ::DWORD = 6719; +pub const ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION: ::DWORD = 6720; +pub const ERROR_TRANSACTION_NOT_ROOT: ::DWORD = 6721; +pub const ERROR_TRANSACTION_OBJECT_EXPIRED: ::DWORD = 6722; +pub const ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED: ::DWORD = 6723; +pub const ERROR_TRANSACTION_RECORD_TOO_LONG: ::DWORD = 6724; +pub const ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED: ::DWORD = 6725; +pub const ERROR_TRANSACTION_INTEGRITY_VIOLATED: ::DWORD = 6726; +pub const ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH: ::DWORD = 6727; +pub const ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT: ::DWORD = 6728; +pub const ERROR_TRANSACTION_MUST_WRITETHROUGH: ::DWORD = 6729; +pub const ERROR_TRANSACTION_NO_SUPERIOR: ::DWORD = 6730; +pub const ERROR_HEURISTIC_DAMAGE_POSSIBLE: ::DWORD = 6731; +pub const ERROR_TRANSACTIONAL_CONFLICT: ::DWORD = 6800; +pub const ERROR_RM_NOT_ACTIVE: ::DWORD = 6801; +pub const ERROR_RM_METADATA_CORRUPT: ::DWORD = 6802; +pub const ERROR_DIRECTORY_NOT_RM: ::DWORD = 6803; +pub const ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE: ::DWORD = 6805; +pub const ERROR_LOG_RESIZE_INVALID_SIZE: ::DWORD = 6806; +pub const ERROR_OBJECT_NO_LONGER_EXISTS: ::DWORD = 6807; +pub const ERROR_STREAM_MINIVERSION_NOT_FOUND: ::DWORD = 6808; +pub const ERROR_STREAM_MINIVERSION_NOT_VALID: ::DWORD = 6809; +pub const ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION: ::DWORD = 6810; +pub const ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT: ::DWORD = 6811; +pub const ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS: ::DWORD = 6812; +pub const ERROR_REMOTE_FILE_VERSION_MISMATCH: ::DWORD = 6814; +pub const ERROR_HANDLE_NO_LONGER_VALID: ::DWORD = 6815; +pub const ERROR_NO_TXF_METADATA: ::DWORD = 6816; +pub const ERROR_LOG_CORRUPTION_DETECTED: ::DWORD = 6817; +pub const ERROR_CANT_RECOVER_WITH_HANDLE_OPEN: ::DWORD = 6818; +pub const ERROR_RM_DISCONNECTED: ::DWORD = 6819; +pub const ERROR_ENLISTMENT_NOT_SUPERIOR: ::DWORD = 6820; +pub const ERROR_RECOVERY_NOT_NEEDED: ::DWORD = 6821; +pub const ERROR_RM_ALREADY_STARTED: ::DWORD = 6822; +pub const ERROR_FILE_IDENTITY_NOT_PERSISTENT: ::DWORD = 6823; +pub const ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY: ::DWORD = 6824; +pub const ERROR_CANT_CROSS_RM_BOUNDARY: ::DWORD = 6825; +pub const ERROR_TXF_DIR_NOT_EMPTY: ::DWORD = 6826; +pub const ERROR_INDOUBT_TRANSACTIONS_EXIST: ::DWORD = 6827; +pub const ERROR_TM_VOLATILE: ::DWORD = 6828; +pub const ERROR_ROLLBACK_TIMER_EXPIRED: ::DWORD = 6829; +pub const ERROR_TXF_ATTRIBUTE_CORRUPT: ::DWORD = 6830; +pub const ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION: ::DWORD = 6831; +pub const ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED: ::DWORD = 6832; +pub const ERROR_LOG_GROWTH_FAILED: ::DWORD = 6833; +pub const ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE: ::DWORD = 6834; +pub const ERROR_TXF_METADATA_ALREADY_PRESENT: ::DWORD = 6835; +pub const ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET: ::DWORD = 6836; +pub const ERROR_TRANSACTION_REQUIRED_PROMOTION: ::DWORD = 6837; +pub const ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION: ::DWORD = 6838; +pub const ERROR_TRANSACTIONS_NOT_FROZEN: ::DWORD = 6839; +pub const ERROR_TRANSACTION_FREEZE_IN_PROGRESS: ::DWORD = 6840; +pub const ERROR_NOT_SNAPSHOT_VOLUME: ::DWORD = 6841; +pub const ERROR_NO_SAVEPOINT_WITH_OPEN_FILES: ::DWORD = 6842; +pub const ERROR_DATA_LOST_REPAIR: ::DWORD = 6843; +pub const ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION: ::DWORD = 6844; +pub const ERROR_TM_IDENTITY_MISMATCH: ::DWORD = 6845; +pub const ERROR_FLOATED_SECTION: ::DWORD = 6846; +pub const ERROR_CANNOT_ACCEPT_TRANSACTED_WORK: ::DWORD = 6847; +pub const ERROR_CANNOT_ABORT_TRANSACTIONS: ::DWORD = 6848; +pub const ERROR_BAD_CLUSTERS: ::DWORD = 6849; +pub const ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION: ::DWORD = 6850; +pub const ERROR_VOLUME_DIRTY: ::DWORD = 6851; +pub const ERROR_NO_LINK_TRACKING_IN_TRANSACTION: ::DWORD = 6852; +pub const ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION: ::DWORD = 6853; +pub const ERROR_EXPIRED_HANDLE: ::DWORD = 6854; +pub const ERROR_TRANSACTION_NOT_ENLISTED: ::DWORD = 6855; +pub const ERROR_CTX_WINSTATION_NAME_INVALID: ::DWORD = 7001; +pub const ERROR_CTX_INVALID_PD: ::DWORD = 7002; +pub const ERROR_CTX_PD_NOT_FOUND: ::DWORD = 7003; +pub const ERROR_CTX_WD_NOT_FOUND: ::DWORD = 7004; +pub const ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY: ::DWORD = 7005; +pub const ERROR_CTX_SERVICE_NAME_COLLISION: ::DWORD = 7006; +pub const ERROR_CTX_CLOSE_PENDING: ::DWORD = 7007; +pub const ERROR_CTX_NO_OUTBUF: ::DWORD = 7008; +pub const ERROR_CTX_MODEM_INF_NOT_FOUND: ::DWORD = 7009; +pub const ERROR_CTX_INVALID_MODEMNAME: ::DWORD = 7010; +pub const ERROR_CTX_MODEM_RESPONSE_ERROR: ::DWORD = 7011; +pub const ERROR_CTX_MODEM_RESPONSE_TIMEOUT: ::DWORD = 7012; +pub const ERROR_CTX_MODEM_RESPONSE_NO_CARRIER: ::DWORD = 7013; +pub const ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE: ::DWORD = 7014; +pub const ERROR_CTX_MODEM_RESPONSE_BUSY: ::DWORD = 7015; +pub const ERROR_CTX_MODEM_RESPONSE_VOICE: ::DWORD = 7016; +pub const ERROR_CTX_TD_ERROR: ::DWORD = 7017; +pub const ERROR_CTX_WINSTATION_NOT_FOUND: ::DWORD = 7022; +pub const ERROR_CTX_WINSTATION_ALREADY_EXISTS: ::DWORD = 7023; +pub const ERROR_CTX_WINSTATION_BUSY: ::DWORD = 7024; +pub const ERROR_CTX_BAD_VIDEO_MODE: ::DWORD = 7025; +pub const ERROR_CTX_GRAPHICS_INVALID: ::DWORD = 7035; +pub const ERROR_CTX_LOGON_DISABLED: ::DWORD = 7037; +pub const ERROR_CTX_NOT_CONSOLE: ::DWORD = 7038; +pub const ERROR_CTX_CLIENT_QUERY_TIMEOUT: ::DWORD = 7040; +pub const ERROR_CTX_CONSOLE_DISCONNECT: ::DWORD = 7041; +pub const ERROR_CTX_CONSOLE_CONNECT: ::DWORD = 7042; +pub const ERROR_CTX_SHADOW_DENIED: ::DWORD = 7044; +pub const ERROR_CTX_WINSTATION_ACCESS_DENIED: ::DWORD = 7045; +pub const ERROR_CTX_INVALID_WD: ::DWORD = 7049; +pub const ERROR_CTX_SHADOW_INVALID: ::DWORD = 7050; +pub const ERROR_CTX_SHADOW_DISABLED: ::DWORD = 7051; +pub const ERROR_CTX_CLIENT_LICENSE_IN_USE: ::DWORD = 7052; +pub const ERROR_CTX_CLIENT_LICENSE_NOT_SET: ::DWORD = 7053; +pub const ERROR_CTX_LICENSE_NOT_AVAILABLE: ::DWORD = 7054; +pub const ERROR_CTX_LICENSE_CLIENT_INVALID: ::DWORD = 7055; +pub const ERROR_CTX_LICENSE_EXPIRED: ::DWORD = 7056; +pub const ERROR_CTX_SHADOW_NOT_RUNNING: ::DWORD = 7057; +pub const ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE: ::DWORD = 7058; +pub const ERROR_ACTIVATION_COUNT_EXCEEDED: ::DWORD = 7059; +pub const ERROR_CTX_WINSTATIONS_DISABLED: ::DWORD = 7060; +pub const ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED: ::DWORD = 7061; +pub const ERROR_CTX_SESSION_IN_USE: ::DWORD = 7062; +pub const ERROR_CTX_NO_FORCE_LOGOFF: ::DWORD = 7063; +pub const ERROR_CTX_ACCOUNT_RESTRICTION: ::DWORD = 7064; +pub const ERROR_RDP_PROTOCOL_ERROR: ::DWORD = 7065; +pub const ERROR_CTX_CDM_CONNECT: ::DWORD = 7066; +pub const ERROR_CTX_CDM_DISCONNECT: ::DWORD = 7067; +pub const ERROR_CTX_SECURITY_LAYER_ERROR: ::DWORD = 7068; +pub const ERROR_TS_INCOMPATIBLE_SESSIONS: ::DWORD = 7069; +pub const ERROR_TS_VIDEO_SUBSYSTEM_ERROR: ::DWORD = 7070; +pub const FRS_ERR_INVALID_API_SEQUENCE: ::DWORD = 8001; +pub const FRS_ERR_STARTING_SERVICE: ::DWORD = 8002; +pub const FRS_ERR_STOPPING_SERVICE: ::DWORD = 8003; +pub const FRS_ERR_INTERNAL_API: ::DWORD = 8004; +pub const FRS_ERR_INTERNAL: ::DWORD = 8005; +pub const FRS_ERR_SERVICE_COMM: ::DWORD = 8006; +pub const FRS_ERR_INSUFFICIENT_PRIV: ::DWORD = 8007; +pub const FRS_ERR_AUTHENTICATION: ::DWORD = 8008; +pub const FRS_ERR_PARENT_INSUFFICIENT_PRIV: ::DWORD = 8009; +pub const FRS_ERR_PARENT_AUTHENTICATION: ::DWORD = 8010; +pub const FRS_ERR_CHILD_TO_PARENT_COMM: ::DWORD = 8011; +pub const FRS_ERR_PARENT_TO_CHILD_COMM: ::DWORD = 8012; +pub const FRS_ERR_SYSVOL_POPULATE: ::DWORD = 8013; +pub const FRS_ERR_SYSVOL_POPULATE_TIMEOUT: ::DWORD = 8014; +pub const FRS_ERR_SYSVOL_IS_BUSY: ::DWORD = 8015; +pub const FRS_ERR_SYSVOL_DEMOTE: ::DWORD = 8016; +pub const FRS_ERR_INVALID_SERVICE_PARAMETER: ::DWORD = 8017; +pub const DS_S_SUCCESS: ::DWORD = NO_ERROR; +pub const ERROR_DS_NOT_INSTALLED: ::DWORD = 8200; +pub const ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY: ::DWORD = 8201; +pub const ERROR_DS_NO_ATTRIBUTE_OR_VALUE: ::DWORD = 8202; +pub const ERROR_DS_INVALID_ATTRIBUTE_SYNTAX: ::DWORD = 8203; +pub const ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED: ::DWORD = 8204; +pub const ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS: ::DWORD = 8205; +pub const ERROR_DS_BUSY: ::DWORD = 8206; +pub const ERROR_DS_UNAVAILABLE: ::DWORD = 8207; +pub const ERROR_DS_NO_RIDS_ALLOCATED: ::DWORD = 8208; +pub const ERROR_DS_NO_MORE_RIDS: ::DWORD = 8209; +pub const ERROR_DS_INCORRECT_ROLE_OWNER: ::DWORD = 8210; +pub const ERROR_DS_RIDMGR_INIT_ERROR: ::DWORD = 8211; +pub const ERROR_DS_OBJ_CLASS_VIOLATION: ::DWORD = 8212; +pub const ERROR_DS_CANT_ON_NON_LEAF: ::DWORD = 8213; +pub const ERROR_DS_CANT_ON_RDN: ::DWORD = 8214; +pub const ERROR_DS_CANT_MOD_OBJ_CLASS: ::DWORD = 8215; +pub const ERROR_DS_CROSS_DOM_MOVE_ERROR: ::DWORD = 8216; +pub const ERROR_DS_GC_NOT_AVAILABLE: ::DWORD = 8217; +pub const ERROR_SHARED_POLICY: ::DWORD = 8218; +pub const ERROR_POLICY_OBJECT_NOT_FOUND: ::DWORD = 8219; +pub const ERROR_POLICY_ONLY_IN_DS: ::DWORD = 8220; +pub const ERROR_PROMOTION_ACTIVE: ::DWORD = 8221; +pub const ERROR_NO_PROMOTION_ACTIVE: ::DWORD = 8222; +pub const ERROR_DS_OPERATIONS_ERROR: ::DWORD = 8224; +pub const ERROR_DS_PROTOCOL_ERROR: ::DWORD = 8225; +pub const ERROR_DS_TIMELIMIT_EXCEEDED: ::DWORD = 8226; +pub const ERROR_DS_SIZELIMIT_EXCEEDED: ::DWORD = 8227; +pub const ERROR_DS_ADMIN_LIMIT_EXCEEDED: ::DWORD = 8228; +pub const ERROR_DS_COMPARE_FALSE: ::DWORD = 8229; +pub const ERROR_DS_COMPARE_TRUE: ::DWORD = 8230; +pub const ERROR_DS_AUTH_METHOD_NOT_SUPPORTED: ::DWORD = 8231; +pub const ERROR_DS_STRONG_AUTH_REQUIRED: ::DWORD = 8232; +pub const ERROR_DS_INAPPROPRIATE_AUTH: ::DWORD = 8233; +pub const ERROR_DS_AUTH_UNKNOWN: ::DWORD = 8234; +pub const ERROR_DS_REFERRAL: ::DWORD = 8235; +pub const ERROR_DS_UNAVAILABLE_CRIT_EXTENSION: ::DWORD = 8236; +pub const ERROR_DS_CONFIDENTIALITY_REQUIRED: ::DWORD = 8237; +pub const ERROR_DS_INAPPROPRIATE_MATCHING: ::DWORD = 8238; +pub const ERROR_DS_CONSTRAINT_VIOLATION: ::DWORD = 8239; +pub const ERROR_DS_NO_SUCH_OBJECT: ::DWORD = 8240; +pub const ERROR_DS_ALIAS_PROBLEM: ::DWORD = 8241; +pub const ERROR_DS_INVALID_DN_SYNTAX: ::DWORD = 8242; +pub const ERROR_DS_IS_LEAF: ::DWORD = 8243; +pub const ERROR_DS_ALIAS_DEREF_PROBLEM: ::DWORD = 8244; +pub const ERROR_DS_UNWILLING_TO_PERFORM: ::DWORD = 8245; +pub const ERROR_DS_LOOP_DETECT: ::DWORD = 8246; +pub const ERROR_DS_NAMING_VIOLATION: ::DWORD = 8247; +pub const ERROR_DS_OBJECT_RESULTS_TOO_LARGE: ::DWORD = 8248; +pub const ERROR_DS_AFFECTS_MULTIPLE_DSAS: ::DWORD = 8249; +pub const ERROR_DS_SERVER_DOWN: ::DWORD = 8250; +pub const ERROR_DS_LOCAL_ERROR: ::DWORD = 8251; +pub const ERROR_DS_ENCODING_ERROR: ::DWORD = 8252; +pub const ERROR_DS_DECODING_ERROR: ::DWORD = 8253; +pub const ERROR_DS_FILTER_UNKNOWN: ::DWORD = 8254; +pub const ERROR_DS_PARAM_ERROR: ::DWORD = 8255; +pub const ERROR_DS_NOT_SUPPORTED: ::DWORD = 8256; +pub const ERROR_DS_NO_RESULTS_RETURNED: ::DWORD = 8257; +pub const ERROR_DS_CONTROL_NOT_FOUND: ::DWORD = 8258; +pub const ERROR_DS_CLIENT_LOOP: ::DWORD = 8259; +pub const ERROR_DS_REFERRAL_LIMIT_EXCEEDED: ::DWORD = 8260; +pub const ERROR_DS_SORT_CONTROL_MISSING: ::DWORD = 8261; +pub const ERROR_DS_OFFSET_RANGE_ERROR: ::DWORD = 8262; +pub const ERROR_DS_RIDMGR_DISABLED: ::DWORD = 8263; +pub const ERROR_DS_ROOT_MUST_BE_NC: ::DWORD = 8301; +pub const ERROR_DS_ADD_REPLICA_INHIBITED: ::DWORD = 8302; +pub const ERROR_DS_ATT_NOT_DEF_IN_SCHEMA: ::DWORD = 8303; +pub const ERROR_DS_MAX_OBJ_SIZE_EXCEEDED: ::DWORD = 8304; +pub const ERROR_DS_OBJ_STRING_NAME_EXISTS: ::DWORD = 8305; +pub const ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA: ::DWORD = 8306; +pub const ERROR_DS_RDN_DOESNT_MATCH_SCHEMA: ::DWORD = 8307; +pub const ERROR_DS_NO_REQUESTED_ATTS_FOUND: ::DWORD = 8308; +pub const ERROR_DS_USER_BUFFER_TO_SMALL: ::DWORD = 8309; +pub const ERROR_DS_ATT_IS_NOT_ON_OBJ: ::DWORD = 8310; +pub const ERROR_DS_ILLEGAL_MOD_OPERATION: ::DWORD = 8311; +pub const ERROR_DS_OBJ_TOO_LARGE: ::DWORD = 8312; +pub const ERROR_DS_BAD_INSTANCE_TYPE: ::DWORD = 8313; +pub const ERROR_DS_MASTERDSA_REQUIRED: ::DWORD = 8314; +pub const ERROR_DS_OBJECT_CLASS_REQUIRED: ::DWORD = 8315; +pub const ERROR_DS_MISSING_REQUIRED_ATT: ::DWORD = 8316; +pub const ERROR_DS_ATT_NOT_DEF_FOR_CLASS: ::DWORD = 8317; +pub const ERROR_DS_ATT_ALREADY_EXISTS: ::DWORD = 8318; +pub const ERROR_DS_CANT_ADD_ATT_VALUES: ::DWORD = 8320; +pub const ERROR_DS_SINGLE_VALUE_CONSTRAINT: ::DWORD = 8321; +pub const ERROR_DS_RANGE_CONSTRAINT: ::DWORD = 8322; +pub const ERROR_DS_ATT_VAL_ALREADY_EXISTS: ::DWORD = 8323; +pub const ERROR_DS_CANT_REM_MISSING_ATT: ::DWORD = 8324; +pub const ERROR_DS_CANT_REM_MISSING_ATT_VAL: ::DWORD = 8325; +pub const ERROR_DS_ROOT_CANT_BE_SUBREF: ::DWORD = 8326; +pub const ERROR_DS_NO_CHAINING: ::DWORD = 8327; +pub const ERROR_DS_NO_CHAINED_EVAL: ::DWORD = 8328; +pub const ERROR_DS_NO_PARENT_OBJECT: ::DWORD = 8329; +pub const ERROR_DS_PARENT_IS_AN_ALIAS: ::DWORD = 8330; +pub const ERROR_DS_CANT_MIX_MASTER_AND_REPS: ::DWORD = 8331; +pub const ERROR_DS_CHILDREN_EXIST: ::DWORD = 8332; +pub const ERROR_DS_OBJ_NOT_FOUND: ::DWORD = 8333; +pub const ERROR_DS_ALIASED_OBJ_MISSING: ::DWORD = 8334; +pub const ERROR_DS_BAD_NAME_SYNTAX: ::DWORD = 8335; +pub const ERROR_DS_ALIAS_POINTS_TO_ALIAS: ::DWORD = 8336; +pub const ERROR_DS_CANT_DEREF_ALIAS: ::DWORD = 8337; +pub const ERROR_DS_OUT_OF_SCOPE: ::DWORD = 8338; +pub const ERROR_DS_OBJECT_BEING_REMOVED: ::DWORD = 8339; +pub const ERROR_DS_CANT_DELETE_DSA_OBJ: ::DWORD = 8340; +pub const ERROR_DS_GENERIC_ERROR: ::DWORD = 8341; +pub const ERROR_DS_DSA_MUST_BE_INT_MASTER: ::DWORD = 8342; +pub const ERROR_DS_CLASS_NOT_DSA: ::DWORD = 8343; +pub const ERROR_DS_INSUFF_ACCESS_RIGHTS: ::DWORD = 8344; +pub const ERROR_DS_ILLEGAL_SUPERIOR: ::DWORD = 8345; +pub const ERROR_DS_ATTRIBUTE_OWNED_BY_SAM: ::DWORD = 8346; +pub const ERROR_DS_NAME_TOO_MANY_PARTS: ::DWORD = 8347; +pub const ERROR_DS_NAME_TOO_LONG: ::DWORD = 8348; +pub const ERROR_DS_NAME_VALUE_TOO_LONG: ::DWORD = 8349; +pub const ERROR_DS_NAME_UNPARSEABLE: ::DWORD = 8350; +pub const ERROR_DS_NAME_TYPE_UNKNOWN: ::DWORD = 8351; +pub const ERROR_DS_NOT_AN_OBJECT: ::DWORD = 8352; +pub const ERROR_DS_SEC_DESC_TOO_SHORT: ::DWORD = 8353; +pub const ERROR_DS_SEC_DESC_INVALID: ::DWORD = 8354; +pub const ERROR_DS_NO_DELETED_NAME: ::DWORD = 8355; +pub const ERROR_DS_SUBREF_MUST_HAVE_PARENT: ::DWORD = 8356; +pub const ERROR_DS_NCNAME_MUST_BE_NC: ::DWORD = 8357; +pub const ERROR_DS_CANT_ADD_SYSTEM_ONLY: ::DWORD = 8358; +pub const ERROR_DS_CLASS_MUST_BE_CONCRETE: ::DWORD = 8359; +pub const ERROR_DS_INVALID_DMD: ::DWORD = 8360; +pub const ERROR_DS_OBJ_GUID_EXISTS: ::DWORD = 8361; +pub const ERROR_DS_NOT_ON_BACKLINK: ::DWORD = 8362; +pub const ERROR_DS_NO_CROSSREF_FOR_NC: ::DWORD = 8363; +pub const ERROR_DS_SHUTTING_DOWN: ::DWORD = 8364; +pub const ERROR_DS_UNKNOWN_OPERATION: ::DWORD = 8365; +pub const ERROR_DS_INVALID_ROLE_OWNER: ::DWORD = 8366; +pub const ERROR_DS_COULDNT_CONTACT_FSMO: ::DWORD = 8367; +pub const ERROR_DS_CROSS_NC_DN_RENAME: ::DWORD = 8368; +pub const ERROR_DS_CANT_MOD_SYSTEM_ONLY: ::DWORD = 8369; +pub const ERROR_DS_REPLICATOR_ONLY: ::DWORD = 8370; +pub const ERROR_DS_OBJ_CLASS_NOT_DEFINED: ::DWORD = 8371; +pub const ERROR_DS_OBJ_CLASS_NOT_SUBCLASS: ::DWORD = 8372; +pub const ERROR_DS_NAME_REFERENCE_INVALID: ::DWORD = 8373; +pub const ERROR_DS_CROSS_REF_EXISTS: ::DWORD = 8374; +pub const ERROR_DS_CANT_DEL_MASTER_CROSSREF: ::DWORD = 8375; +pub const ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD: ::DWORD = 8376; +pub const ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX: ::DWORD = 8377; +pub const ERROR_DS_DUP_RDN: ::DWORD = 8378; +pub const ERROR_DS_DUP_OID: ::DWORD = 8379; +pub const ERROR_DS_DUP_MAPI_ID: ::DWORD = 8380; +pub const ERROR_DS_DUP_SCHEMA_ID_GUID: ::DWORD = 8381; +pub const ERROR_DS_DUP_LDAP_DISPLAY_NAME: ::DWORD = 8382; +pub const ERROR_DS_SEMANTIC_ATT_TEST: ::DWORD = 8383; +pub const ERROR_DS_SYNTAX_MISMATCH: ::DWORD = 8384; +pub const ERROR_DS_EXISTS_IN_MUST_HAVE: ::DWORD = 8385; +pub const ERROR_DS_EXISTS_IN_MAY_HAVE: ::DWORD = 8386; +pub const ERROR_DS_NONEXISTENT_MAY_HAVE: ::DWORD = 8387; +pub const ERROR_DS_NONEXISTENT_MUST_HAVE: ::DWORD = 8388; +pub const ERROR_DS_AUX_CLS_TEST_FAIL: ::DWORD = 8389; +pub const ERROR_DS_NONEXISTENT_POSS_SUP: ::DWORD = 8390; +pub const ERROR_DS_SUB_CLS_TEST_FAIL: ::DWORD = 8391; +pub const ERROR_DS_BAD_RDN_ATT_ID_SYNTAX: ::DWORD = 8392; +pub const ERROR_DS_EXISTS_IN_AUX_CLS: ::DWORD = 8393; +pub const ERROR_DS_EXISTS_IN_SUB_CLS: ::DWORD = 8394; +pub const ERROR_DS_EXISTS_IN_POSS_SUP: ::DWORD = 8395; +pub const ERROR_DS_RECALCSCHEMA_FAILED: ::DWORD = 8396; +pub const ERROR_DS_TREE_DELETE_NOT_FINISHED: ::DWORD = 8397; +pub const ERROR_DS_CANT_DELETE: ::DWORD = 8398; +pub const ERROR_DS_ATT_SCHEMA_REQ_ID: ::DWORD = 8399; +pub const ERROR_DS_BAD_ATT_SCHEMA_SYNTAX: ::DWORD = 8400; +pub const ERROR_DS_CANT_CACHE_ATT: ::DWORD = 8401; +pub const ERROR_DS_CANT_CACHE_CLASS: ::DWORD = 8402; +pub const ERROR_DS_CANT_REMOVE_ATT_CACHE: ::DWORD = 8403; +pub const ERROR_DS_CANT_REMOVE_CLASS_CACHE: ::DWORD = 8404; +pub const ERROR_DS_CANT_RETRIEVE_DN: ::DWORD = 8405; +pub const ERROR_DS_MISSING_SUPREF: ::DWORD = 8406; +pub const ERROR_DS_CANT_RETRIEVE_INSTANCE: ::DWORD = 8407; +pub const ERROR_DS_CODE_INCONSISTENCY: ::DWORD = 8408; +pub const ERROR_DS_DATABASE_ERROR: ::DWORD = 8409; +pub const ERROR_DS_GOVERNSID_MISSING: ::DWORD = 8410; +pub const ERROR_DS_MISSING_EXPECTED_ATT: ::DWORD = 8411; +pub const ERROR_DS_NCNAME_MISSING_CR_REF: ::DWORD = 8412; +pub const ERROR_DS_SECURITY_CHECKING_ERROR: ::DWORD = 8413; +pub const ERROR_DS_SCHEMA_NOT_LOADED: ::DWORD = 8414; +pub const ERROR_DS_SCHEMA_ALLOC_FAILED: ::DWORD = 8415; +pub const ERROR_DS_ATT_SCHEMA_REQ_SYNTAX: ::DWORD = 8416; +pub const ERROR_DS_GCVERIFY_ERROR: ::DWORD = 8417; +pub const ERROR_DS_DRA_SCHEMA_MISMATCH: ::DWORD = 8418; +pub const ERROR_DS_CANT_FIND_DSA_OBJ: ::DWORD = 8419; +pub const ERROR_DS_CANT_FIND_EXPECTED_NC: ::DWORD = 8420; +pub const ERROR_DS_CANT_FIND_NC_IN_CACHE: ::DWORD = 8421; +pub const ERROR_DS_CANT_RETRIEVE_CHILD: ::DWORD = 8422; +pub const ERROR_DS_SECURITY_ILLEGAL_MODIFY: ::DWORD = 8423; +pub const ERROR_DS_CANT_REPLACE_HIDDEN_REC: ::DWORD = 8424; +pub const ERROR_DS_BAD_HIERARCHY_FILE: ::DWORD = 8425; +pub const ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED: ::DWORD = 8426; +pub const ERROR_DS_CONFIG_PARAM_MISSING: ::DWORD = 8427; +pub const ERROR_DS_COUNTING_AB_INDICES_FAILED: ::DWORD = 8428; +pub const ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED: ::DWORD = 8429; +pub const ERROR_DS_INTERNAL_FAILURE: ::DWORD = 8430; +pub const ERROR_DS_UNKNOWN_ERROR: ::DWORD = 8431; +pub const ERROR_DS_ROOT_REQUIRES_CLASS_TOP: ::DWORD = 8432; +pub const ERROR_DS_REFUSING_FSMO_ROLES: ::DWORD = 8433; +pub const ERROR_DS_MISSING_FSMO_SETTINGS: ::DWORD = 8434; +pub const ERROR_DS_UNABLE_TO_SURRENDER_ROLES: ::DWORD = 8435; +pub const ERROR_DS_DRA_GENERIC: ::DWORD = 8436; +pub const ERROR_DS_DRA_INVALID_PARAMETER: ::DWORD = 8437; +pub const ERROR_DS_DRA_BUSY: ::DWORD = 8438; +pub const ERROR_DS_DRA_BAD_DN: ::DWORD = 8439; +pub const ERROR_DS_DRA_BAD_NC: ::DWORD = 8440; +pub const ERROR_DS_DRA_DN_EXISTS: ::DWORD = 8441; +pub const ERROR_DS_DRA_INTERNAL_ERROR: ::DWORD = 8442; +pub const ERROR_DS_DRA_INCONSISTENT_DIT: ::DWORD = 8443; +pub const ERROR_DS_DRA_CONNECTION_FAILED: ::DWORD = 8444; +pub const ERROR_DS_DRA_BAD_INSTANCE_TYPE: ::DWORD = 8445; +pub const ERROR_DS_DRA_OUT_OF_MEM: ::DWORD = 8446; +pub const ERROR_DS_DRA_MAIL_PROBLEM: ::DWORD = 8447; +pub const ERROR_DS_DRA_REF_ALREADY_EXISTS: ::DWORD = 8448; +pub const ERROR_DS_DRA_REF_NOT_FOUND: ::DWORD = 8449; +pub const ERROR_DS_DRA_OBJ_IS_REP_SOURCE: ::DWORD = 8450; +pub const ERROR_DS_DRA_DB_ERROR: ::DWORD = 8451; +pub const ERROR_DS_DRA_NO_REPLICA: ::DWORD = 8452; +pub const ERROR_DS_DRA_ACCESS_DENIED: ::DWORD = 8453; +pub const ERROR_DS_DRA_NOT_SUPPORTED: ::DWORD = 8454; +pub const ERROR_DS_DRA_RPC_CANCELLED: ::DWORD = 8455; +pub const ERROR_DS_DRA_SOURCE_DISABLED: ::DWORD = 8456; +pub const ERROR_DS_DRA_SINK_DISABLED: ::DWORD = 8457; +pub const ERROR_DS_DRA_NAME_COLLISION: ::DWORD = 8458; +pub const ERROR_DS_DRA_SOURCE_REINSTALLED: ::DWORD = 8459; +pub const ERROR_DS_DRA_MISSING_PARENT: ::DWORD = 8460; +pub const ERROR_DS_DRA_PREEMPTED: ::DWORD = 8461; +pub const ERROR_DS_DRA_ABANDON_SYNC: ::DWORD = 8462; +pub const ERROR_DS_DRA_SHUTDOWN: ::DWORD = 8463; +pub const ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET: ::DWORD = 8464; +pub const ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA: ::DWORD = 8465; +pub const ERROR_DS_DRA_EXTN_CONNECTION_FAILED: ::DWORD = 8466; +pub const ERROR_DS_INSTALL_SCHEMA_MISMATCH: ::DWORD = 8467; +pub const ERROR_DS_DUP_LINK_ID: ::DWORD = 8468; +pub const ERROR_DS_NAME_ERROR_RESOLVING: ::DWORD = 8469; +pub const ERROR_DS_NAME_ERROR_NOT_FOUND: ::DWORD = 8470; +pub const ERROR_DS_NAME_ERROR_NOT_UNIQUE: ::DWORD = 8471; +pub const ERROR_DS_NAME_ERROR_NO_MAPPING: ::DWORD = 8472; +pub const ERROR_DS_NAME_ERROR_DOMAIN_ONLY: ::DWORD = 8473; +pub const ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: ::DWORD = 8474; +pub const ERROR_DS_CONSTRUCTED_ATT_MOD: ::DWORD = 8475; +pub const ERROR_DS_WRONG_OM_OBJ_CLASS: ::DWORD = 8476; +pub const ERROR_DS_DRA_REPL_PENDING: ::DWORD = 8477; +pub const ERROR_DS_DS_REQUIRED: ::DWORD = 8478; +pub const ERROR_DS_INVALID_LDAP_DISPLAY_NAME: ::DWORD = 8479; +pub const ERROR_DS_NON_BASE_SEARCH: ::DWORD = 8480; +pub const ERROR_DS_CANT_RETRIEVE_ATTS: ::DWORD = 8481; +pub const ERROR_DS_BACKLINK_WITHOUT_LINK: ::DWORD = 8482; +pub const ERROR_DS_EPOCH_MISMATCH: ::DWORD = 8483; +pub const ERROR_DS_SRC_NAME_MISMATCH: ::DWORD = 8484; +pub const ERROR_DS_SRC_AND_DST_NC_IDENTICAL: ::DWORD = 8485; +pub const ERROR_DS_DST_NC_MISMATCH: ::DWORD = 8486; +pub const ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC: ::DWORD = 8487; +pub const ERROR_DS_SRC_GUID_MISMATCH: ::DWORD = 8488; +pub const ERROR_DS_CANT_MOVE_DELETED_OBJECT: ::DWORD = 8489; +pub const ERROR_DS_PDC_OPERATION_IN_PROGRESS: ::DWORD = 8490; +pub const ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD: ::DWORD = 8491; +pub const ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION: ::DWORD = 8492; +pub const ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS: ::DWORD = 8493; +pub const ERROR_DS_NC_MUST_HAVE_NC_PARENT: ::DWORD = 8494; +pub const ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE: ::DWORD = 8495; +pub const ERROR_DS_DST_DOMAIN_NOT_NATIVE: ::DWORD = 8496; +pub const ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER: ::DWORD = 8497; +pub const ERROR_DS_CANT_MOVE_ACCOUNT_GROUP: ::DWORD = 8498; +pub const ERROR_DS_CANT_MOVE_RESOURCE_GROUP: ::DWORD = 8499; +pub const ERROR_DS_INVALID_SEARCH_FLAG: ::DWORD = 8500; +pub const ERROR_DS_NO_TREE_DELETE_ABOVE_NC: ::DWORD = 8501; +pub const ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE: ::DWORD = 8502; +pub const ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE: ::DWORD = 8503; +pub const ERROR_DS_SAM_INIT_FAILURE: ::DWORD = 8504; +pub const ERROR_DS_SENSITIVE_GROUP_VIOLATION: ::DWORD = 8505; +pub const ERROR_DS_CANT_MOD_PRIMARYGROUPID: ::DWORD = 8506; +pub const ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD: ::DWORD = 8507; +pub const ERROR_DS_NONSAFE_SCHEMA_CHANGE: ::DWORD = 8508; +pub const ERROR_DS_SCHEMA_UPDATE_DISALLOWED: ::DWORD = 8509; +pub const ERROR_DS_CANT_CREATE_UNDER_SCHEMA: ::DWORD = 8510; +pub const ERROR_DS_INSTALL_NO_SRC_SCH_VERSION: ::DWORD = 8511; +pub const ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE: ::DWORD = 8512; +pub const ERROR_DS_INVALID_GROUP_TYPE: ::DWORD = 8513; +pub const ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: ::DWORD = 8514; +pub const ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: ::DWORD = 8515; +pub const ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: ::DWORD = 8516; +pub const ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: ::DWORD = 8517; +pub const ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: ::DWORD = 8518; +pub const ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: ::DWORD = 8519; +pub const ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: ::DWORD = 8520; +pub const ERROR_DS_HAVE_PRIMARY_MEMBERS: ::DWORD = 8521; +pub const ERROR_DS_STRING_SD_CONVERSION_FAILED: ::DWORD = 8522; +pub const ERROR_DS_NAMING_MASTER_GC: ::DWORD = 8523; +pub const ERROR_DS_DNS_LOOKUP_FAILURE: ::DWORD = 8524; +pub const ERROR_DS_COULDNT_UPDATE_SPNS: ::DWORD = 8525; +pub const ERROR_DS_CANT_RETRIEVE_SD: ::DWORD = 8526; +pub const ERROR_DS_KEY_NOT_UNIQUE: ::DWORD = 8527; +pub const ERROR_DS_WRONG_LINKED_ATT_SYNTAX: ::DWORD = 8528; +pub const ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD: ::DWORD = 8529; +pub const ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY: ::DWORD = 8530; +pub const ERROR_DS_CANT_START: ::DWORD = 8531; +pub const ERROR_DS_INIT_FAILURE: ::DWORD = 8532; +pub const ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: ::DWORD = 8533; +pub const ERROR_DS_SOURCE_DOMAIN_IN_FOREST: ::DWORD = 8534; +pub const ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: ::DWORD = 8535; +pub const ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: ::DWORD = 8536; +pub const ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: ::DWORD = 8537; +pub const ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: ::DWORD = 8538; +pub const ERROR_DS_SRC_SID_EXISTS_IN_FOREST: ::DWORD = 8539; +pub const ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: ::DWORD = 8540; +pub const ERROR_SAM_INIT_FAILURE: ::DWORD = 8541; +pub const ERROR_DS_DRA_SCHEMA_INFO_SHIP: ::DWORD = 8542; +pub const ERROR_DS_DRA_SCHEMA_CONFLICT: ::DWORD = 8543; +pub const ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT: ::DWORD = 8544; +pub const ERROR_DS_DRA_OBJ_NC_MISMATCH: ::DWORD = 8545; +pub const ERROR_DS_NC_STILL_HAS_DSAS: ::DWORD = 8546; +pub const ERROR_DS_GC_REQUIRED: ::DWORD = 8547; +pub const ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: ::DWORD = 8548; +pub const ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS: ::DWORD = 8549; +pub const ERROR_DS_CANT_ADD_TO_GC: ::DWORD = 8550; +pub const ERROR_DS_NO_CHECKPOINT_WITH_PDC: ::DWORD = 8551; +pub const ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: ::DWORD = 8552; +pub const ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC: ::DWORD = 8553; +pub const ERROR_DS_INVALID_NAME_FOR_SPN: ::DWORD = 8554; +pub const ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS: ::DWORD = 8555; +pub const ERROR_DS_UNICODEPWD_NOT_IN_QUOTES: ::DWORD = 8556; +pub const ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: ::DWORD = 8557; +pub const ERROR_DS_MUST_BE_RUN_ON_DST_DC: ::DWORD = 8558; +pub const ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: ::DWORD = 8559; +pub const ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ: ::DWORD = 8560; +pub const ERROR_DS_INIT_FAILURE_CONSOLE: ::DWORD = 8561; +pub const ERROR_DS_SAM_INIT_FAILURE_CONSOLE: ::DWORD = 8562; +pub const ERROR_DS_FOREST_VERSION_TOO_HIGH: ::DWORD = 8563; +pub const ERROR_DS_DOMAIN_VERSION_TOO_HIGH: ::DWORD = 8564; +pub const ERROR_DS_FOREST_VERSION_TOO_LOW: ::DWORD = 8565; +pub const ERROR_DS_DOMAIN_VERSION_TOO_LOW: ::DWORD = 8566; +pub const ERROR_DS_INCOMPATIBLE_VERSION: ::DWORD = 8567; +pub const ERROR_DS_LOW_DSA_VERSION: ::DWORD = 8568; +pub const ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN: ::DWORD = 8569; +pub const ERROR_DS_NOT_SUPPORTED_SORT_ORDER: ::DWORD = 8570; +pub const ERROR_DS_NAME_NOT_UNIQUE: ::DWORD = 8571; +pub const ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4: ::DWORD = 8572; +pub const ERROR_DS_OUT_OF_VERSION_STORE: ::DWORD = 8573; +pub const ERROR_DS_INCOMPATIBLE_CONTROLS_USED: ::DWORD = 8574; +pub const ERROR_DS_NO_REF_DOMAIN: ::DWORD = 8575; +pub const ERROR_DS_RESERVED_LINK_ID: ::DWORD = 8576; +pub const ERROR_DS_LINK_ID_NOT_AVAILABLE: ::DWORD = 8577; +pub const ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: ::DWORD = 8578; +pub const ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE: ::DWORD = 8579; +pub const ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC: ::DWORD = 8580; +pub const ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG: ::DWORD = 8581; +pub const ERROR_DS_MODIFYDN_WRONG_GRANDPARENT: ::DWORD = 8582; +pub const ERROR_DS_NAME_ERROR_TRUST_REFERRAL: ::DWORD = 8583; +pub const ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER: ::DWORD = 8584; +pub const ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD: ::DWORD = 8585; +pub const ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2: ::DWORD = 8586; +pub const ERROR_DS_THREAD_LIMIT_EXCEEDED: ::DWORD = 8587; +pub const ERROR_DS_NOT_CLOSEST: ::DWORD = 8588; +pub const ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF: ::DWORD = 8589; +pub const ERROR_DS_SINGLE_USER_MODE_FAILED: ::DWORD = 8590; +pub const ERROR_DS_NTDSCRIPT_SYNTAX_ERROR: ::DWORD = 8591; +pub const ERROR_DS_NTDSCRIPT_PROCESS_ERROR: ::DWORD = 8592; +pub const ERROR_DS_DIFFERENT_REPL_EPOCHS: ::DWORD = 8593; +pub const ERROR_DS_DRS_EXTENSIONS_CHANGED: ::DWORD = 8594; +pub const ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR: ::DWORD = 8595; +pub const ERROR_DS_NO_MSDS_INTID: ::DWORD = 8596; +pub const ERROR_DS_DUP_MSDS_INTID: ::DWORD = 8597; +pub const ERROR_DS_EXISTS_IN_RDNATTID: ::DWORD = 8598; +pub const ERROR_DS_AUTHORIZATION_FAILED: ::DWORD = 8599; +pub const ERROR_DS_INVALID_SCRIPT: ::DWORD = 8600; +pub const ERROR_DS_REMOTE_CROSSREF_OP_FAILED: ::DWORD = 8601; +pub const ERROR_DS_CROSS_REF_BUSY: ::DWORD = 8602; +pub const ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN: ::DWORD = 8603; +pub const ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC: ::DWORD = 8604; +pub const ERROR_DS_DUPLICATE_ID_FOUND: ::DWORD = 8605; +pub const ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT: ::DWORD = 8606; +pub const ERROR_DS_GROUP_CONVERSION_ERROR: ::DWORD = 8607; +pub const ERROR_DS_CANT_MOVE_APP_BASIC_GROUP: ::DWORD = 8608; +pub const ERROR_DS_CANT_MOVE_APP_QUERY_GROUP: ::DWORD = 8609; +pub const ERROR_DS_ROLE_NOT_VERIFIED: ::DWORD = 8610; +pub const ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL: ::DWORD = 8611; +pub const ERROR_DS_DOMAIN_RENAME_IN_PROGRESS: ::DWORD = 8612; +pub const ERROR_DS_EXISTING_AD_CHILD_NC: ::DWORD = 8613; +pub const ERROR_DS_REPL_LIFETIME_EXCEEDED: ::DWORD = 8614; +pub const ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER: ::DWORD = 8615; +pub const ERROR_DS_LDAP_SEND_QUEUE_FULL: ::DWORD = 8616; +pub const ERROR_DS_DRA_OUT_SCHEDULE_WINDOW: ::DWORD = 8617; +pub const ERROR_DS_POLICY_NOT_KNOWN: ::DWORD = 8618; +pub const ERROR_NO_SITE_SETTINGS_OBJECT: ::DWORD = 8619; +pub const ERROR_NO_SECRETS: ::DWORD = 8620; +pub const ERROR_NO_WRITABLE_DC_FOUND: ::DWORD = 8621; +pub const ERROR_DS_NO_SERVER_OBJECT: ::DWORD = 8622; +pub const ERROR_DS_NO_NTDSA_OBJECT: ::DWORD = 8623; +pub const ERROR_DS_NON_ASQ_SEARCH: ::DWORD = 8624; +pub const ERROR_DS_AUDIT_FAILURE: ::DWORD = 8625; +pub const ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE: ::DWORD = 8626; +pub const ERROR_DS_INVALID_SEARCH_FLAG_TUPLE: ::DWORD = 8627; +pub const ERROR_DS_HIERARCHY_TABLE_TOO_DEEP: ::DWORD = 8628; +pub const ERROR_DS_DRA_CORRUPT_UTD_VECTOR: ::DWORD = 8629; +pub const ERROR_DS_DRA_SECRETS_DENIED: ::DWORD = 8630; +pub const ERROR_DS_RESERVED_MAPI_ID: ::DWORD = 8631; +pub const ERROR_DS_MAPI_ID_NOT_AVAILABLE: ::DWORD = 8632; +pub const ERROR_DS_DRA_MISSING_KRBTGT_SECRET: ::DWORD = 8633; +pub const ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST: ::DWORD = 8634; +pub const ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST: ::DWORD = 8635; +pub const ERROR_INVALID_USER_PRINCIPAL_NAME: ::DWORD = 8636; +pub const ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS: ::DWORD = 8637; +pub const ERROR_DS_OID_NOT_FOUND: ::DWORD = 8638; +pub const ERROR_DS_DRA_RECYCLED_TARGET: ::DWORD = 8639; +pub const ERROR_DS_DISALLOWED_NC_REDIRECT: ::DWORD = 8640; +pub const ERROR_DS_HIGH_ADLDS_FFL: ::DWORD = 8641; +pub const ERROR_DS_HIGH_DSA_VERSION: ::DWORD = 8642; +pub const ERROR_DS_LOW_ADLDS_FFL: ::DWORD = 8643; +pub const ERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION: ::DWORD = 8644; +pub const ERROR_DS_UNDELETE_SAM_VALIDATION_FAILED: ::DWORD = 8645; +pub const ERROR_INCORRECT_ACCOUNT_TYPE: ::DWORD = 8646; +pub const ERROR_DS_SPN_VALUE_NOT_UNIQUE_IN_FOREST: ::DWORD = 8647; +pub const ERROR_DS_UPN_VALUE_NOT_UNIQUE_IN_FOREST: ::DWORD = 8648; +pub const DNS_ERROR_RESPONSE_CODES_BASE: ::DWORD = 9000; +pub const DNS_ERROR_RCODE_NO_ERROR: ::DWORD = NO_ERROR; +pub const DNS_ERROR_MASK: ::DWORD = 0x00002328; +pub const DNS_ERROR_RCODE_FORMAT_ERROR: ::DWORD = 9001; +pub const DNS_ERROR_RCODE_SERVER_FAILURE: ::DWORD = 9002; +pub const DNS_ERROR_RCODE_NAME_ERROR: ::DWORD = 9003; +pub const DNS_ERROR_RCODE_NOT_IMPLEMENTED: ::DWORD = 9004; +pub const DNS_ERROR_RCODE_REFUSED: ::DWORD = 9005; +pub const DNS_ERROR_RCODE_YXDOMAIN: ::DWORD = 9006; +pub const DNS_ERROR_RCODE_YXRRSET: ::DWORD = 9007; +pub const DNS_ERROR_RCODE_NXRRSET: ::DWORD = 9008; +pub const DNS_ERROR_RCODE_NOTAUTH: ::DWORD = 9009; +pub const DNS_ERROR_RCODE_NOTZONE: ::DWORD = 9010; +pub const DNS_ERROR_RCODE_BADSIG: ::DWORD = 9016; +pub const DNS_ERROR_RCODE_BADKEY: ::DWORD = 9017; +pub const DNS_ERROR_RCODE_BADTIME: ::DWORD = 9018; +pub const DNS_ERROR_RCODE_LAST: ::DWORD = DNS_ERROR_RCODE_BADTIME; +pub const DNS_ERROR_DNSSEC_BASE: ::DWORD = 9100; +pub const DNS_ERROR_KEYMASTER_REQUIRED: ::DWORD = 9101; +pub const DNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE: ::DWORD = 9102; +pub const DNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1: ::DWORD = 9103; +pub const DNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS: ::DWORD = 9104; +pub const DNS_ERROR_UNSUPPORTED_ALGORITHM: ::DWORD = 9105; +pub const DNS_ERROR_INVALID_KEY_SIZE: ::DWORD = 9106; +pub const DNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE: ::DWORD = 9107; +pub const DNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION: ::DWORD = 9108; +pub const DNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR: ::DWORD = 9109; +pub const DNS_ERROR_UNEXPECTED_CNG_ERROR: ::DWORD = 9110; +pub const DNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION: ::DWORD = 9111; +pub const DNS_ERROR_KSP_NOT_ACCESSIBLE: ::DWORD = 9112; +pub const DNS_ERROR_TOO_MANY_SKDS: ::DWORD = 9113; +pub const DNS_ERROR_INVALID_ROLLOVER_PERIOD: ::DWORD = 9114; +pub const DNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET: ::DWORD = 9115; +pub const DNS_ERROR_ROLLOVER_IN_PROGRESS: ::DWORD = 9116; +pub const DNS_ERROR_STANDBY_KEY_NOT_PRESENT: ::DWORD = 9117; +pub const DNS_ERROR_NOT_ALLOWED_ON_ZSK: ::DWORD = 9118; +pub const DNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD: ::DWORD = 9119; +pub const DNS_ERROR_ROLLOVER_ALREADY_QUEUED: ::DWORD = 9120; +pub const DNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE: ::DWORD = 9121; +pub const DNS_ERROR_BAD_KEYMASTER: ::DWORD = 9122; +pub const DNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD: ::DWORD = 9123; +pub const DNS_ERROR_INVALID_NSEC3_ITERATION_COUNT: ::DWORD = 9124; +pub const DNS_ERROR_DNSSEC_IS_DISABLED: ::DWORD = 9125; +pub const DNS_ERROR_INVALID_XML: ::DWORD = 9126; +pub const DNS_ERROR_NO_VALID_TRUST_ANCHORS: ::DWORD = 9127; +pub const DNS_ERROR_ROLLOVER_NOT_POKEABLE: ::DWORD = 9128; +pub const DNS_ERROR_NSEC3_NAME_COLLISION: ::DWORD = 9129; +pub const DNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1: ::DWORD = 9130; +pub const DNS_ERROR_PACKET_FMT_BASE: ::DWORD = 9500; +pub const DNS_INFO_NO_RECORDS: ::DWORD = 9501; +pub const DNS_ERROR_BAD_PACKET: ::DWORD = 9502; +pub const DNS_ERROR_NO_PACKET: ::DWORD = 9503; +pub const DNS_ERROR_RCODE: ::DWORD = 9504; +pub const DNS_ERROR_UNSECURE_PACKET: ::DWORD = 9505; +pub const DNS_STATUS_PACKET_UNSECURE: ::DWORD = DNS_ERROR_UNSECURE_PACKET; +pub const DNS_REQUEST_PENDING: ::DWORD = 9506; +pub const DNS_ERROR_NO_MEMORY: ::DWORD = ERROR_OUTOFMEMORY; +pub const DNS_ERROR_INVALID_NAME: ::DWORD = ERROR_INVALID_NAME; +pub const DNS_ERROR_INVALID_DATA: ::DWORD = ERROR_INVALID_DATA; +pub const DNS_ERROR_GENERAL_API_BASE: ::DWORD = 9550; +pub const DNS_ERROR_INVALID_TYPE: ::DWORD = 9551; +pub const DNS_ERROR_INVALID_IP_ADDRESS: ::DWORD = 9552; +pub const DNS_ERROR_INVALID_PROPERTY: ::DWORD = 9553; +pub const DNS_ERROR_TRY_AGAIN_LATER: ::DWORD = 9554; +pub const DNS_ERROR_NOT_UNIQUE: ::DWORD = 9555; +pub const DNS_ERROR_NON_RFC_NAME: ::DWORD = 9556; +pub const DNS_STATUS_FQDN: ::DWORD = 9557; +pub const DNS_STATUS_DOTTED_NAME: ::DWORD = 9558; +pub const DNS_STATUS_SINGLE_PART_NAME: ::DWORD = 9559; +pub const DNS_ERROR_INVALID_NAME_CHAR: ::DWORD = 9560; +pub const DNS_ERROR_NUMERIC_NAME: ::DWORD = 9561; +pub const DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER: ::DWORD = 9562; +pub const DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION: ::DWORD = 9563; +pub const DNS_ERROR_CANNOT_FIND_ROOT_HINTS: ::DWORD = 9564; +pub const DNS_ERROR_INCONSISTENT_ROOT_HINTS: ::DWORD = 9565; +pub const DNS_ERROR_DWORD_VALUE_TOO_SMALL: ::DWORD = 9566; +pub const DNS_ERROR_DWORD_VALUE_TOO_LARGE: ::DWORD = 9567; +pub const DNS_ERROR_BACKGROUND_LOADING: ::DWORD = 9568; +pub const DNS_ERROR_NOT_ALLOWED_ON_RODC: ::DWORD = 9569; +pub const DNS_ERROR_NOT_ALLOWED_UNDER_DNAME: ::DWORD = 9570; +pub const DNS_ERROR_DELEGATION_REQUIRED: ::DWORD = 9571; +pub const DNS_ERROR_INVALID_POLICY_TABLE: ::DWORD = 9572; +pub const DNS_ERROR_ZONE_BASE: ::DWORD = 9600; +pub const DNS_ERROR_ZONE_DOES_NOT_EXIST: ::DWORD = 9601; +pub const DNS_ERROR_NO_ZONE_INFO: ::DWORD = 9602; +pub const DNS_ERROR_INVALID_ZONE_OPERATION: ::DWORD = 9603; +pub const DNS_ERROR_ZONE_CONFIGURATION_ERROR: ::DWORD = 9604; +pub const DNS_ERROR_ZONE_HAS_NO_SOA_RECORD: ::DWORD = 9605; +pub const DNS_ERROR_ZONE_HAS_NO_NS_RECORDS: ::DWORD = 9606; +pub const DNS_ERROR_ZONE_LOCKED: ::DWORD = 9607; +pub const DNS_ERROR_ZONE_CREATION_FAILED: ::DWORD = 9608; +pub const DNS_ERROR_ZONE_ALREADY_EXISTS: ::DWORD = 9609; +pub const DNS_ERROR_AUTOZONE_ALREADY_EXISTS: ::DWORD = 9610; +pub const DNS_ERROR_INVALID_ZONE_TYPE: ::DWORD = 9611; +pub const DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP: ::DWORD = 9612; +pub const DNS_ERROR_ZONE_NOT_SECONDARY: ::DWORD = 9613; +pub const DNS_ERROR_NEED_SECONDARY_ADDRESSES: ::DWORD = 9614; +pub const DNS_ERROR_WINS_INIT_FAILED: ::DWORD = 9615; +pub const DNS_ERROR_NEED_WINS_SERVERS: ::DWORD = 9616; +pub const DNS_ERROR_NBSTAT_INIT_FAILED: ::DWORD = 9617; +pub const DNS_ERROR_SOA_DELETE_INVALID: ::DWORD = 9618; +pub const DNS_ERROR_FORWARDER_ALREADY_EXISTS: ::DWORD = 9619; +pub const DNS_ERROR_ZONE_REQUIRES_MASTER_IP: ::DWORD = 9620; +pub const DNS_ERROR_ZONE_IS_SHUTDOWN: ::DWORD = 9621; +pub const DNS_ERROR_ZONE_LOCKED_FOR_SIGNING: ::DWORD = 9622; +pub const DNS_ERROR_DATAFILE_BASE: ::DWORD = 9650; +pub const DNS_ERROR_PRIMARY_REQUIRES_DATAFILE: ::DWORD = 9651; +pub const DNS_ERROR_INVALID_DATAFILE_NAME: ::DWORD = 9652; +pub const DNS_ERROR_DATAFILE_OPEN_FAILURE: ::DWORD = 9653; +pub const DNS_ERROR_FILE_WRITEBACK_FAILED: ::DWORD = 9654; +pub const DNS_ERROR_DATAFILE_PARSING: ::DWORD = 9655; +pub const DNS_ERROR_DATABASE_BASE: ::DWORD = 9700; +pub const DNS_ERROR_RECORD_DOES_NOT_EXIST: ::DWORD = 9701; +pub const DNS_ERROR_RECORD_FORMAT: ::DWORD = 9702; +pub const DNS_ERROR_NODE_CREATION_FAILED: ::DWORD = 9703; +pub const DNS_ERROR_UNKNOWN_RECORD_TYPE: ::DWORD = 9704; +pub const DNS_ERROR_RECORD_TIMED_OUT: ::DWORD = 9705; +pub const DNS_ERROR_NAME_NOT_IN_ZONE: ::DWORD = 9706; +pub const DNS_ERROR_CNAME_LOOP: ::DWORD = 9707; +pub const DNS_ERROR_NODE_IS_CNAME: ::DWORD = 9708; +pub const DNS_ERROR_CNAME_COLLISION: ::DWORD = 9709; +pub const DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT: ::DWORD = 9710; +pub const DNS_ERROR_RECORD_ALREADY_EXISTS: ::DWORD = 9711; +pub const DNS_ERROR_SECONDARY_DATA: ::DWORD = 9712; +pub const DNS_ERROR_NO_CREATE_CACHE_DATA: ::DWORD = 9713; +pub const DNS_ERROR_NAME_DOES_NOT_EXIST: ::DWORD = 9714; +pub const DNS_WARNING_PTR_CREATE_FAILED: ::DWORD = 9715; +pub const DNS_WARNING_DOMAIN_UNDELETED: ::DWORD = 9716; +pub const DNS_ERROR_DS_UNAVAILABLE: ::DWORD = 9717; +pub const DNS_ERROR_DS_ZONE_ALREADY_EXISTS: ::DWORD = 9718; +pub const DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE: ::DWORD = 9719; +pub const DNS_ERROR_NODE_IS_DNAME: ::DWORD = 9720; +pub const DNS_ERROR_DNAME_COLLISION: ::DWORD = 9721; +pub const DNS_ERROR_ALIAS_LOOP: ::DWORD = 9722; +pub const DNS_ERROR_OPERATION_BASE: ::DWORD = 9750; +pub const DNS_INFO_AXFR_COMPLETE: ::DWORD = 9751; +pub const DNS_ERROR_AXFR: ::DWORD = 9752; +pub const DNS_INFO_ADDED_LOCAL_WINS: ::DWORD = 9753; +pub const DNS_ERROR_SECURE_BASE: ::DWORD = 9800; +pub const DNS_STATUS_CONTINUE_NEEDED: ::DWORD = 9801; +pub const DNS_ERROR_SETUP_BASE: ::DWORD = 9850; +pub const DNS_ERROR_NO_TCPIP: ::DWORD = 9851; +pub const DNS_ERROR_NO_DNS_SERVERS: ::DWORD = 9852; +pub const DNS_ERROR_DP_BASE: ::DWORD = 9900; +pub const DNS_ERROR_DP_DOES_NOT_EXIST: ::DWORD = 9901; +pub const DNS_ERROR_DP_ALREADY_EXISTS: ::DWORD = 9902; +pub const DNS_ERROR_DP_NOT_ENLISTED: ::DWORD = 9903; +pub const DNS_ERROR_DP_ALREADY_ENLISTED: ::DWORD = 9904; +pub const DNS_ERROR_DP_NOT_AVAILABLE: ::DWORD = 9905; +pub const DNS_ERROR_DP_FSMO_ERROR: ::DWORD = 9906; +pub const DNS_ERROR_ZONESCOPE_ALREADY_EXISTS: ::DWORD = 9951; +pub const DNS_ERROR_ZONESCOPE_DOES_NOT_EXIST: ::DWORD = 9952; +pub const DNS_ERROR_DEFAULT_ZONESCOPE: ::DWORD = 9953; +pub const DNS_ERROR_INVALID_ZONESCOPE_NAME: ::DWORD = 9954; +pub const DNS_ERROR_NOT_ALLOWED_WITH_ZONESCOPES: ::DWORD = 9955; +pub const DNS_ERROR_LOAD_ZONESCOPE_FAILED: ::DWORD = 9956; +pub const DNS_ERROR_ZONESCOPE_FILE_WRITEBACK_FAILED: ::DWORD = 9957; +pub const DNS_ERROR_INVALID_SCOPE_NAME: ::DWORD = 9958; +pub const DNS_ERROR_SCOPE_DOES_NOT_EXIST: ::DWORD = 9959; +pub const DNS_ERROR_DEFAULT_SCOPE: ::DWORD = 9960; +pub const DNS_ERROR_INVALID_SCOPE_OPERATION: ::DWORD = 9961; +pub const DNS_ERROR_SCOPE_LOCKED: ::DWORD = 9962; +pub const DNS_ERROR_SCOPE_ALREADY_EXISTS: ::DWORD = 9963; +pub const WSABASEERR: ::DWORD = 10000; +pub const WSAEINTR: ::DWORD = 10004; +pub const WSAEBADF: ::DWORD = 10009; +pub const WSAEACCES: ::DWORD = 10013; +pub const WSAEFAULT: ::DWORD = 10014; +pub const WSAEINVAL: ::DWORD = 10022; +pub const WSAEMFILE: ::DWORD = 10024; +pub const WSAEWOULDBLOCK: ::DWORD = 10035; +pub const WSAEINPROGRESS: ::DWORD = 10036; +pub const WSAEALREADY: ::DWORD = 10037; +pub const WSAENOTSOCK: ::DWORD = 10038; +pub const WSAEDESTADDRREQ: ::DWORD = 10039; +pub const WSAEMSGSIZE: ::DWORD = 10040; +pub const WSAEPROTOTYPE: ::DWORD = 10041; +pub const WSAENOPROTOOPT: ::DWORD = 10042; +pub const WSAEPROTONOSUPPORT: ::DWORD = 10043; +pub const WSAESOCKTNOSUPPORT: ::DWORD = 10044; +pub const WSAEOPNOTSUPP: ::DWORD = 10045; +pub const WSAEPFNOSUPPORT: ::DWORD = 10046; +pub const WSAEAFNOSUPPORT: ::DWORD = 10047; +pub const WSAEADDRINUSE: ::DWORD = 10048; +pub const WSAEADDRNOTAVAIL: ::DWORD = 10049; +pub const WSAENETDOWN: ::DWORD = 10050; +pub const WSAENETUNREACH: ::DWORD = 10051; +pub const WSAENETRESET: ::DWORD = 10052; +pub const WSAECONNABORTED: ::DWORD = 10053; +pub const WSAECONNRESET: ::DWORD = 10054; +pub const WSAENOBUFS: ::DWORD = 10055; +pub const WSAEISCONN: ::DWORD = 10056; +pub const WSAENOTCONN: ::DWORD = 10057; +pub const WSAESHUTDOWN: ::DWORD = 10058; +pub const WSAETOOMANYREFS: ::DWORD = 10059; +pub const WSAETIMEDOUT: ::DWORD = 10060; +pub const WSAECONNREFUSED: ::DWORD = 10061; +pub const WSAELOOP: ::DWORD = 10062; +pub const WSAENAMETOOLONG: ::DWORD = 10063; +pub const WSAEHOSTDOWN: ::DWORD = 10064; +pub const WSAEHOSTUNREACH: ::DWORD = 10065; +pub const WSAENOTEMPTY: ::DWORD = 10066; +pub const WSAEPROCLIM: ::DWORD = 10067; +pub const WSAEUSERS: ::DWORD = 10068; +pub const WSAEDQUOT: ::DWORD = 10069; +pub const WSAESTALE: ::DWORD = 10070; +pub const WSAEREMOTE: ::DWORD = 10071; +pub const WSASYSNOTREADY: ::DWORD = 10091; +pub const WSAVERNOTSUPPORTED: ::DWORD = 10092; +pub const WSANOTINITIALISED: ::DWORD = 10093; +pub const WSAEDISCON: ::DWORD = 10101; +pub const WSAENOMORE: ::DWORD = 10102; +pub const WSAECANCELLED: ::DWORD = 10103; +pub const WSAEINVALIDPROCTABLE: ::DWORD = 10104; +pub const WSAEINVALIDPROVIDER: ::DWORD = 10105; +pub const WSAEPROVIDERFAILEDINIT: ::DWORD = 10106; +pub const WSASYSCALLFAILURE: ::DWORD = 10107; +pub const WSASERVICE_NOT_FOUND: ::DWORD = 10108; +pub const WSATYPE_NOT_FOUND: ::DWORD = 10109; +pub const WSA_E_NO_MORE: ::DWORD = 10110; +pub const WSA_E_CANCELLED: ::DWORD = 10111; +pub const WSAEREFUSED: ::DWORD = 10112; +pub const WSAHOST_NOT_FOUND: ::DWORD = 11001; +pub const WSATRY_AGAIN: ::DWORD = 11002; +pub const WSANO_RECOVERY: ::DWORD = 11003; +pub const WSANO_DATA: ::DWORD = 11004; +pub const WSA_QOS_RECEIVERS: ::DWORD = 11005; +pub const WSA_QOS_SENDERS: ::DWORD = 11006; +pub const WSA_QOS_NO_SENDERS: ::DWORD = 11007; +pub const WSA_QOS_NO_RECEIVERS: ::DWORD = 11008; +pub const WSA_QOS_REQUEST_CONFIRMED: ::DWORD = 11009; +pub const WSA_QOS_ADMISSION_FAILURE: ::DWORD = 11010; +pub const WSA_QOS_POLICY_FAILURE: ::DWORD = 11011; +pub const WSA_QOS_BAD_STYLE: ::DWORD = 11012; +pub const WSA_QOS_BAD_OBJECT: ::DWORD = 11013; +pub const WSA_QOS_TRAFFIC_CTRL_ERROR: ::DWORD = 11014; +pub const WSA_QOS_GENERIC_ERROR: ::DWORD = 11015; +pub const WSA_QOS_ESERVICETYPE: ::DWORD = 11016; +pub const WSA_QOS_EFLOWSPEC: ::DWORD = 11017; +pub const WSA_QOS_EPROVSPECBUF: ::DWORD = 11018; +pub const WSA_QOS_EFILTERSTYLE: ::DWORD = 11019; +pub const WSA_QOS_EFILTERTYPE: ::DWORD = 11020; +pub const WSA_QOS_EFILTERCOUNT: ::DWORD = 11021; +pub const WSA_QOS_EOBJLENGTH: ::DWORD = 11022; +pub const WSA_QOS_EFLOWCOUNT: ::DWORD = 11023; +pub const WSA_QOS_EUNKOWNPSOBJ: ::DWORD = 11024; +pub const WSA_QOS_EPOLICYOBJ: ::DWORD = 11025; +pub const WSA_QOS_EFLOWDESC: ::DWORD = 11026; +pub const WSA_QOS_EPSFLOWSPEC: ::DWORD = 11027; +pub const WSA_QOS_EPSFILTERSPEC: ::DWORD = 11028; +pub const WSA_QOS_ESDMODEOBJ: ::DWORD = 11029; +pub const WSA_QOS_ESHAPERATEOBJ: ::DWORD = 11030; +pub const WSA_QOS_RESERVED_PETYPE: ::DWORD = 11031; +pub const WSA_SECURE_HOST_NOT_FOUND: ::DWORD = 11032; +pub const WSA_IPSEC_NAME_POLICY_ERROR: ::DWORD = 11033; +pub const ERROR_IPSEC_QM_POLICY_EXISTS: ::DWORD = 13000; +pub const ERROR_IPSEC_QM_POLICY_NOT_FOUND: ::DWORD = 13001; +pub const ERROR_IPSEC_QM_POLICY_IN_USE: ::DWORD = 13002; +pub const ERROR_IPSEC_MM_POLICY_EXISTS: ::DWORD = 13003; +pub const ERROR_IPSEC_MM_POLICY_NOT_FOUND: ::DWORD = 13004; +pub const ERROR_IPSEC_MM_POLICY_IN_USE: ::DWORD = 13005; +pub const ERROR_IPSEC_MM_FILTER_EXISTS: ::DWORD = 13006; +pub const ERROR_IPSEC_MM_FILTER_NOT_FOUND: ::DWORD = 13007; +pub const ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: ::DWORD = 13008; +pub const ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: ::DWORD = 13009; +pub const ERROR_IPSEC_MM_AUTH_EXISTS: ::DWORD = 13010; +pub const ERROR_IPSEC_MM_AUTH_NOT_FOUND: ::DWORD = 13011; +pub const ERROR_IPSEC_MM_AUTH_IN_USE: ::DWORD = 13012; +pub const ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: ::DWORD = 13013; +pub const ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: ::DWORD = 13014; +pub const ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: ::DWORD = 13015; +pub const ERROR_IPSEC_TUNNEL_FILTER_EXISTS: ::DWORD = 13016; +pub const ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: ::DWORD = 13017; +pub const ERROR_IPSEC_MM_FILTER_PENDING_DELETION: ::DWORD = 13018; +pub const ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: ::DWORD = 13019; +pub const ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: ::DWORD = 13020; +pub const ERROR_IPSEC_MM_POLICY_PENDING_DELETION: ::DWORD = 13021; +pub const ERROR_IPSEC_MM_AUTH_PENDING_DELETION: ::DWORD = 13022; +pub const ERROR_IPSEC_QM_POLICY_PENDING_DELETION: ::DWORD = 13023; +pub const WARNING_IPSEC_MM_POLICY_PRUNED: ::DWORD = 13024; +pub const WARNING_IPSEC_QM_POLICY_PRUNED: ::DWORD = 13025; +pub const ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: ::DWORD = 13800; +pub const ERROR_IPSEC_IKE_AUTH_FAIL: ::DWORD = 13801; +pub const ERROR_IPSEC_IKE_ATTRIB_FAIL: ::DWORD = 13802; +pub const ERROR_IPSEC_IKE_NEGOTIATION_PENDING: ::DWORD = 13803; +pub const ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: ::DWORD = 13804; +pub const ERROR_IPSEC_IKE_TIMED_OUT: ::DWORD = 13805; +pub const ERROR_IPSEC_IKE_NO_CERT: ::DWORD = 13806; +pub const ERROR_IPSEC_IKE_SA_DELETED: ::DWORD = 13807; +pub const ERROR_IPSEC_IKE_SA_REAPED: ::DWORD = 13808; +pub const ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: ::DWORD = 13809; +pub const ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: ::DWORD = 13810; +pub const ERROR_IPSEC_IKE_QUEUE_DROP_MM: ::DWORD = 13811; +pub const ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: ::DWORD = 13812; +pub const ERROR_IPSEC_IKE_DROP_NO_RESPONSE: ::DWORD = 13813; +pub const ERROR_IPSEC_IKE_MM_DELAY_DROP: ::DWORD = 13814; +pub const ERROR_IPSEC_IKE_QM_DELAY_DROP: ::DWORD = 13815; +pub const ERROR_IPSEC_IKE_ERROR: ::DWORD = 13816; +pub const ERROR_IPSEC_IKE_CRL_FAILED: ::DWORD = 13817; +pub const ERROR_IPSEC_IKE_INVALID_KEY_USAGE: ::DWORD = 13818; +pub const ERROR_IPSEC_IKE_INVALID_CERT_TYPE: ::DWORD = 13819; +pub const ERROR_IPSEC_IKE_NO_PRIVATE_KEY: ::DWORD = 13820; +pub const ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY: ::DWORD = 13821; +pub const ERROR_IPSEC_IKE_DH_FAIL: ::DWORD = 13822; +pub const ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED: ::DWORD = 13823; +pub const ERROR_IPSEC_IKE_INVALID_HEADER: ::DWORD = 13824; +pub const ERROR_IPSEC_IKE_NO_POLICY: ::DWORD = 13825; +pub const ERROR_IPSEC_IKE_INVALID_SIGNATURE: ::DWORD = 13826; +pub const ERROR_IPSEC_IKE_KERBEROS_ERROR: ::DWORD = 13827; +pub const ERROR_IPSEC_IKE_NO_PUBLIC_KEY: ::DWORD = 13828; +pub const ERROR_IPSEC_IKE_PROCESS_ERR: ::DWORD = 13829; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_SA: ::DWORD = 13830; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_PROP: ::DWORD = 13831; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: ::DWORD = 13832; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_KE: ::DWORD = 13833; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_ID: ::DWORD = 13834; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_CERT: ::DWORD = 13835; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: ::DWORD = 13836; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_HASH: ::DWORD = 13837; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_SIG: ::DWORD = 13838; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: ::DWORD = 13839; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: ::DWORD = 13840; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: ::DWORD = 13841; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: ::DWORD = 13842; +pub const ERROR_IPSEC_IKE_INVALID_PAYLOAD: ::DWORD = 13843; +pub const ERROR_IPSEC_IKE_LOAD_SOFT_SA: ::DWORD = 13844; +pub const ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: ::DWORD = 13845; +pub const ERROR_IPSEC_IKE_INVALID_COOKIE: ::DWORD = 13846; +pub const ERROR_IPSEC_IKE_NO_PEER_CERT: ::DWORD = 13847; +pub const ERROR_IPSEC_IKE_PEER_CRL_FAILED: ::DWORD = 13848; +pub const ERROR_IPSEC_IKE_POLICY_CHANGE: ::DWORD = 13849; +pub const ERROR_IPSEC_IKE_NO_MM_POLICY: ::DWORD = 13850; +pub const ERROR_IPSEC_IKE_NOTCBPRIV: ::DWORD = 13851; +pub const ERROR_IPSEC_IKE_SECLOADFAIL: ::DWORD = 13852; +pub const ERROR_IPSEC_IKE_FAILSSPINIT: ::DWORD = 13853; +pub const ERROR_IPSEC_IKE_FAILQUERYSSP: ::DWORD = 13854; +pub const ERROR_IPSEC_IKE_SRVACQFAIL: ::DWORD = 13855; +pub const ERROR_IPSEC_IKE_SRVQUERYCRED: ::DWORD = 13856; +pub const ERROR_IPSEC_IKE_GETSPIFAIL: ::DWORD = 13857; +pub const ERROR_IPSEC_IKE_INVALID_FILTER: ::DWORD = 13858; +pub const ERROR_IPSEC_IKE_OUT_OF_MEMORY: ::DWORD = 13859; +pub const ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: ::DWORD = 13860; +pub const ERROR_IPSEC_IKE_INVALID_POLICY: ::DWORD = 13861; +pub const ERROR_IPSEC_IKE_UNKNOWN_DOI: ::DWORD = 13862; +pub const ERROR_IPSEC_IKE_INVALID_SITUATION: ::DWORD = 13863; +pub const ERROR_IPSEC_IKE_DH_FAILURE: ::DWORD = 13864; +pub const ERROR_IPSEC_IKE_INVALID_GROUP: ::DWORD = 13865; +pub const ERROR_IPSEC_IKE_ENCRYPT: ::DWORD = 13866; +pub const ERROR_IPSEC_IKE_DECRYPT: ::DWORD = 13867; +pub const ERROR_IPSEC_IKE_POLICY_MATCH: ::DWORD = 13868; +pub const ERROR_IPSEC_IKE_UNSUPPORTED_ID: ::DWORD = 13869; +pub const ERROR_IPSEC_IKE_INVALID_HASH: ::DWORD = 13870; +pub const ERROR_IPSEC_IKE_INVALID_HASH_ALG: ::DWORD = 13871; +pub const ERROR_IPSEC_IKE_INVALID_HASH_SIZE: ::DWORD = 13872; +pub const ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: ::DWORD = 13873; +pub const ERROR_IPSEC_IKE_INVALID_AUTH_ALG: ::DWORD = 13874; +pub const ERROR_IPSEC_IKE_INVALID_SIG: ::DWORD = 13875; +pub const ERROR_IPSEC_IKE_LOAD_FAILED: ::DWORD = 13876; +pub const ERROR_IPSEC_IKE_RPC_DELETE: ::DWORD = 13877; +pub const ERROR_IPSEC_IKE_BENIGN_REINIT: ::DWORD = 13878; +pub const ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: ::DWORD = 13879; +pub const ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION: ::DWORD = 13880; +pub const ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: ::DWORD = 13881; +pub const ERROR_IPSEC_IKE_MM_LIMIT: ::DWORD = 13882; +pub const ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: ::DWORD = 13883; +pub const ERROR_IPSEC_IKE_QM_LIMIT: ::DWORD = 13884; +pub const ERROR_IPSEC_IKE_MM_EXPIRED: ::DWORD = 13885; +pub const ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID: ::DWORD = 13886; +pub const ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH: ::DWORD = 13887; +pub const ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID: ::DWORD = 13888; +pub const ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD: ::DWORD = 13889; +pub const ERROR_IPSEC_IKE_DOS_COOKIE_SENT: ::DWORD = 13890; +pub const ERROR_IPSEC_IKE_SHUTTING_DOWN: ::DWORD = 13891; +pub const ERROR_IPSEC_IKE_CGA_AUTH_FAILED: ::DWORD = 13892; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_NATOA: ::DWORD = 13893; +pub const ERROR_IPSEC_IKE_INVALID_MM_FOR_QM: ::DWORD = 13894; +pub const ERROR_IPSEC_IKE_QM_EXPIRED: ::DWORD = 13895; +pub const ERROR_IPSEC_IKE_TOO_MANY_FILTERS: ::DWORD = 13896; +pub const ERROR_IPSEC_IKE_NEG_STATUS_END: ::DWORD = 13897; +pub const ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL: ::DWORD = 13898; +pub const ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE: ::DWORD = 13899; +pub const ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING: ::DWORD = 13900; +pub const ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING: ::DWORD = 13901; +pub const ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS: ::DWORD = 13902; +pub const ERROR_IPSEC_IKE_RATELIMIT_DROP: ::DWORD = 13903; +pub const ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE: ::DWORD = 13904; +pub const ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE: ::DWORD = 13905; +pub const ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE: ::DWORD = 13906; +pub const ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY: ::DWORD = 13907; +pub const ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE: ::DWORD = 13908; +pub const ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END: ::DWORD = 13909; +pub const ERROR_IPSEC_BAD_SPI: ::DWORD = 13910; +pub const ERROR_IPSEC_SA_LIFETIME_EXPIRED: ::DWORD = 13911; +pub const ERROR_IPSEC_WRONG_SA: ::DWORD = 13912; +pub const ERROR_IPSEC_REPLAY_CHECK_FAILED: ::DWORD = 13913; +pub const ERROR_IPSEC_INVALID_PACKET: ::DWORD = 13914; +pub const ERROR_IPSEC_INTEGRITY_CHECK_FAILED: ::DWORD = 13915; +pub const ERROR_IPSEC_CLEAR_TEXT_DROP: ::DWORD = 13916; +pub const ERROR_IPSEC_AUTH_FIREWALL_DROP: ::DWORD = 13917; +pub const ERROR_IPSEC_THROTTLE_DROP: ::DWORD = 13918; +pub const ERROR_IPSEC_DOSP_BLOCK: ::DWORD = 13925; +pub const ERROR_IPSEC_DOSP_RECEIVED_MULTICAST: ::DWORD = 13926; +pub const ERROR_IPSEC_DOSP_INVALID_PACKET: ::DWORD = 13927; +pub const ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED: ::DWORD = 13928; +pub const ERROR_IPSEC_DOSP_MAX_ENTRIES: ::DWORD = 13929; +pub const ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: ::DWORD = 13930; +pub const ERROR_IPSEC_DOSP_NOT_INSTALLED: ::DWORD = 13931; +pub const ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: ::DWORD = 13932; +pub const ERROR_SXS_SECTION_NOT_FOUND: ::DWORD = 14000; +pub const ERROR_SXS_CANT_GEN_ACTCTX: ::DWORD = 14001; +pub const ERROR_SXS_INVALID_ACTCTXDATA_FORMAT: ::DWORD = 14002; +pub const ERROR_SXS_ASSEMBLY_NOT_FOUND: ::DWORD = 14003; +pub const ERROR_SXS_MANIFEST_FORMAT_ERROR: ::DWORD = 14004; +pub const ERROR_SXS_MANIFEST_PARSE_ERROR: ::DWORD = 14005; +pub const ERROR_SXS_ACTIVATION_CONTEXT_DISABLED: ::DWORD = 14006; +pub const ERROR_SXS_KEY_NOT_FOUND: ::DWORD = 14007; +pub const ERROR_SXS_VERSION_CONFLICT: ::DWORD = 14008; +pub const ERROR_SXS_WRONG_SECTION_TYPE: ::DWORD = 14009; +pub const ERROR_SXS_THREAD_QUERIES_DISABLED: ::DWORD = 14010; +pub const ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET: ::DWORD = 14011; +pub const ERROR_SXS_UNKNOWN_ENCODING_GROUP: ::DWORD = 14012; +pub const ERROR_SXS_UNKNOWN_ENCODING: ::DWORD = 14013; +pub const ERROR_SXS_INVALID_XML_NAMESPACE_URI: ::DWORD = 14014; +pub const ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED: ::DWORD = 14015; +pub const ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED: ::DWORD = 14016; +pub const ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE: ::DWORD = 14017; +pub const ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE: ::DWORD = 14018; +pub const ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE: ::DWORD = 14019; +pub const ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT: ::DWORD = 14020; +pub const ERROR_SXS_DUPLICATE_DLL_NAME: ::DWORD = 14021; +pub const ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME: ::DWORD = 14022; +pub const ERROR_SXS_DUPLICATE_CLSID: ::DWORD = 14023; +pub const ERROR_SXS_DUPLICATE_IID: ::DWORD = 14024; +pub const ERROR_SXS_DUPLICATE_TLBID: ::DWORD = 14025; +pub const ERROR_SXS_DUPLICATE_PROGID: ::DWORD = 14026; +pub const ERROR_SXS_DUPLICATE_ASSEMBLY_NAME: ::DWORD = 14027; +pub const ERROR_SXS_FILE_HASH_MISMATCH: ::DWORD = 14028; +pub const ERROR_SXS_POLICY_PARSE_ERROR: ::DWORD = 14029; +pub const ERROR_SXS_XML_E_MISSINGQUOTE: ::DWORD = 14030; +pub const ERROR_SXS_XML_E_COMMENTSYNTAX: ::DWORD = 14031; +pub const ERROR_SXS_XML_E_BADSTARTNAMECHAR: ::DWORD = 14032; +pub const ERROR_SXS_XML_E_BADNAMECHAR: ::DWORD = 14033; +pub const ERROR_SXS_XML_E_BADCHARINSTRING: ::DWORD = 14034; +pub const ERROR_SXS_XML_E_XMLDECLSYNTAX: ::DWORD = 14035; +pub const ERROR_SXS_XML_E_BADCHARDATA: ::DWORD = 14036; +pub const ERROR_SXS_XML_E_MISSINGWHITESPACE: ::DWORD = 14037; +pub const ERROR_SXS_XML_E_EXPECTINGTAGEND: ::DWORD = 14038; +pub const ERROR_SXS_XML_E_MISSINGSEMICOLON: ::DWORD = 14039; +pub const ERROR_SXS_XML_E_UNBALANCEDPAREN: ::DWORD = 14040; +pub const ERROR_SXS_XML_E_INTERNALERROR: ::DWORD = 14041; +pub const ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE: ::DWORD = 14042; +pub const ERROR_SXS_XML_E_INCOMPLETE_ENCODING: ::DWORD = 14043; +pub const ERROR_SXS_XML_E_MISSING_PAREN: ::DWORD = 14044; +pub const ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE: ::DWORD = 14045; +pub const ERROR_SXS_XML_E_MULTIPLE_COLONS: ::DWORD = 14046; +pub const ERROR_SXS_XML_E_INVALID_DECIMAL: ::DWORD = 14047; +pub const ERROR_SXS_XML_E_INVALID_HEXIDECIMAL: ::DWORD = 14048; +pub const ERROR_SXS_XML_E_INVALID_UNICODE: ::DWORD = 14049; +pub const ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK: ::DWORD = 14050; +pub const ERROR_SXS_XML_E_UNEXPECTEDENDTAG: ::DWORD = 14051; +pub const ERROR_SXS_XML_E_UNCLOSEDTAG: ::DWORD = 14052; +pub const ERROR_SXS_XML_E_DUPLICATEATTRIBUTE: ::DWORD = 14053; +pub const ERROR_SXS_XML_E_MULTIPLEROOTS: ::DWORD = 14054; +pub const ERROR_SXS_XML_E_INVALIDATROOTLEVEL: ::DWORD = 14055; +pub const ERROR_SXS_XML_E_BADXMLDECL: ::DWORD = 14056; +pub const ERROR_SXS_XML_E_MISSINGROOT: ::DWORD = 14057; +pub const ERROR_SXS_XML_E_UNEXPECTEDEOF: ::DWORD = 14058; +pub const ERROR_SXS_XML_E_BADPEREFINSUBSET: ::DWORD = 14059; +pub const ERROR_SXS_XML_E_UNCLOSEDSTARTTAG: ::DWORD = 14060; +pub const ERROR_SXS_XML_E_UNCLOSEDENDTAG: ::DWORD = 14061; +pub const ERROR_SXS_XML_E_UNCLOSEDSTRING: ::DWORD = 14062; +pub const ERROR_SXS_XML_E_UNCLOSEDCOMMENT: ::DWORD = 14063; +pub const ERROR_SXS_XML_E_UNCLOSEDDECL: ::DWORD = 14064; +pub const ERROR_SXS_XML_E_UNCLOSEDCDATA: ::DWORD = 14065; +pub const ERROR_SXS_XML_E_RESERVEDNAMESPACE: ::DWORD = 14066; +pub const ERROR_SXS_XML_E_INVALIDENCODING: ::DWORD = 14067; +pub const ERROR_SXS_XML_E_INVALIDSWITCH: ::DWORD = 14068; +pub const ERROR_SXS_XML_E_BADXMLCASE: ::DWORD = 14069; +pub const ERROR_SXS_XML_E_INVALID_STANDALONE: ::DWORD = 14070; +pub const ERROR_SXS_XML_E_UNEXPECTED_STANDALONE: ::DWORD = 14071; +pub const ERROR_SXS_XML_E_INVALID_VERSION: ::DWORD = 14072; +pub const ERROR_SXS_XML_E_MISSINGEQUALS: ::DWORD = 14073; +pub const ERROR_SXS_PROTECTION_RECOVERY_FAILED: ::DWORD = 14074; +pub const ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT: ::DWORD = 14075; +pub const ERROR_SXS_PROTECTION_CATALOG_NOT_VALID: ::DWORD = 14076; +pub const ERROR_SXS_UNTRANSLATABLE_HRESULT: ::DWORD = 14077; +pub const ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING: ::DWORD = 14078; +pub const ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE: ::DWORD = 14079; +pub const ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME: ::DWORD = 14080; +pub const ERROR_SXS_ASSEMBLY_MISSING: ::DWORD = 14081; +pub const ERROR_SXS_CORRUPT_ACTIVATION_STACK: ::DWORD = 14082; +pub const ERROR_SXS_CORRUPTION: ::DWORD = 14083; +pub const ERROR_SXS_EARLY_DEACTIVATION: ::DWORD = 14084; +pub const ERROR_SXS_INVALID_DEACTIVATION: ::DWORD = 14085; +pub const ERROR_SXS_MULTIPLE_DEACTIVATION: ::DWORD = 14086; +pub const ERROR_SXS_PROCESS_TERMINATION_REQUESTED: ::DWORD = 14087; +pub const ERROR_SXS_RELEASE_ACTIVATION_CONTEXT: ::DWORD = 14088; +pub const ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: ::DWORD = 14089; +pub const ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: ::DWORD = 14090; +pub const ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: ::DWORD = 14091; +pub const ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: ::DWORD = 14092; +pub const ERROR_SXS_IDENTITY_PARSE_ERROR: ::DWORD = 14093; +pub const ERROR_MALFORMED_SUBSTITUTION_STRING: ::DWORD = 14094; +pub const ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN: ::DWORD = 14095; +pub const ERROR_UNMAPPED_SUBSTITUTION_STRING: ::DWORD = 14096; +pub const ERROR_SXS_ASSEMBLY_NOT_LOCKED: ::DWORD = 14097; +pub const ERROR_SXS_COMPONENT_STORE_CORRUPT: ::DWORD = 14098; +pub const ERROR_ADVANCED_INSTALLER_FAILED: ::DWORD = 14099; +pub const ERROR_XML_ENCODING_MISMATCH: ::DWORD = 14100; +pub const ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: ::DWORD = 14101; +pub const ERROR_SXS_IDENTITIES_DIFFERENT: ::DWORD = 14102; +pub const ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: ::DWORD = 14103; +pub const ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY: ::DWORD = 14104; +pub const ERROR_SXS_MANIFEST_TOO_BIG: ::DWORD = 14105; +pub const ERROR_SXS_SETTING_NOT_REGISTERED: ::DWORD = 14106; +pub const ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE: ::DWORD = 14107; +pub const ERROR_SMI_PRIMITIVE_INSTALLER_FAILED: ::DWORD = 14108; +pub const ERROR_GENERIC_COMMAND_FAILED: ::DWORD = 14109; +pub const ERROR_SXS_FILE_HASH_MISSING: ::DWORD = 14110; +pub const ERROR_EVT_INVALID_CHANNEL_PATH: ::DWORD = 15000; +pub const ERROR_EVT_INVALID_QUERY: ::DWORD = 15001; +pub const ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND: ::DWORD = 15002; +pub const ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND: ::DWORD = 15003; +pub const ERROR_EVT_INVALID_PUBLISHER_NAME: ::DWORD = 15004; +pub const ERROR_EVT_INVALID_EVENT_DATA: ::DWORD = 15005; +pub const ERROR_EVT_CHANNEL_NOT_FOUND: ::DWORD = 15007; +pub const ERROR_EVT_MALFORMED_XML_TEXT: ::DWORD = 15008; +pub const ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL: ::DWORD = 15009; +pub const ERROR_EVT_CONFIGURATION_ERROR: ::DWORD = 15010; +pub const ERROR_EVT_QUERY_RESULT_STALE: ::DWORD = 15011; +pub const ERROR_EVT_QUERY_RESULT_INVALID_POSITION: ::DWORD = 15012; +pub const ERROR_EVT_NON_VALIDATING_MSXML: ::DWORD = 15013; +pub const ERROR_EVT_FILTER_ALREADYSCOPED: ::DWORD = 15014; +pub const ERROR_EVT_FILTER_NOTELTSET: ::DWORD = 15015; +pub const ERROR_EVT_FILTER_INVARG: ::DWORD = 15016; +pub const ERROR_EVT_FILTER_INVTEST: ::DWORD = 15017; +pub const ERROR_EVT_FILTER_INVTYPE: ::DWORD = 15018; +pub const ERROR_EVT_FILTER_PARSEERR: ::DWORD = 15019; +pub const ERROR_EVT_FILTER_UNSUPPORTEDOP: ::DWORD = 15020; +pub const ERROR_EVT_FILTER_UNEXPECTEDTOKEN: ::DWORD = 15021; +pub const ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL: ::DWORD = 15022; +pub const ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE: ::DWORD = 15023; +pub const ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE: ::DWORD = 15024; +pub const ERROR_EVT_CHANNEL_CANNOT_ACTIVATE: ::DWORD = 15025; +pub const ERROR_EVT_FILTER_TOO_COMPLEX: ::DWORD = 15026; +pub const ERROR_EVT_MESSAGE_NOT_FOUND: ::DWORD = 15027; +pub const ERROR_EVT_MESSAGE_ID_NOT_FOUND: ::DWORD = 15028; +pub const ERROR_EVT_UNRESOLVED_VALUE_INSERT: ::DWORD = 15029; +pub const ERROR_EVT_UNRESOLVED_PARAMETER_INSERT: ::DWORD = 15030; +pub const ERROR_EVT_MAX_INSERTS_REACHED: ::DWORD = 15031; +pub const ERROR_EVT_EVENT_DEFINITION_NOT_FOUND: ::DWORD = 15032; +pub const ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: ::DWORD = 15033; +pub const ERROR_EVT_VERSION_TOO_OLD: ::DWORD = 15034; +pub const ERROR_EVT_VERSION_TOO_NEW: ::DWORD = 15035; +pub const ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY: ::DWORD = 15036; +pub const ERROR_EVT_PUBLISHER_DISABLED: ::DWORD = 15037; +pub const ERROR_EVT_FILTER_OUT_OF_RANGE: ::DWORD = 15038; +pub const ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE: ::DWORD = 15080; +pub const ERROR_EC_LOG_DISABLED: ::DWORD = 15081; +pub const ERROR_EC_CIRCULAR_FORWARDING: ::DWORD = 15082; +pub const ERROR_EC_CREDSTORE_FULL: ::DWORD = 15083; +pub const ERROR_EC_CRED_NOT_FOUND: ::DWORD = 15084; +pub const ERROR_EC_NO_ACTIVE_CHANNEL: ::DWORD = 15085; +pub const ERROR_MUI_FILE_NOT_FOUND: ::DWORD = 15100; +pub const ERROR_MUI_INVALID_FILE: ::DWORD = 15101; +pub const ERROR_MUI_INVALID_RC_CONFIG: ::DWORD = 15102; +pub const ERROR_MUI_INVALID_LOCALE_NAME: ::DWORD = 15103; +pub const ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME: ::DWORD = 15104; +pub const ERROR_MUI_FILE_NOT_LOADED: ::DWORD = 15105; +pub const ERROR_RESOURCE_ENUM_USER_STOP: ::DWORD = 15106; +pub const ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED: ::DWORD = 15107; +pub const ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME: ::DWORD = 15108; +pub const ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE: ::DWORD = 15110; +pub const ERROR_MRM_INVALID_PRICONFIG: ::DWORD = 15111; +pub const ERROR_MRM_INVALID_FILE_TYPE: ::DWORD = 15112; +pub const ERROR_MRM_UNKNOWN_QUALIFIER: ::DWORD = 15113; +pub const ERROR_MRM_INVALID_QUALIFIER_VALUE: ::DWORD = 15114; +pub const ERROR_MRM_NO_CANDIDATE: ::DWORD = 15115; +pub const ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE: ::DWORD = 15116; +pub const ERROR_MRM_RESOURCE_TYPE_MISMATCH: ::DWORD = 15117; +pub const ERROR_MRM_DUPLICATE_MAP_NAME: ::DWORD = 15118; +pub const ERROR_MRM_DUPLICATE_ENTRY: ::DWORD = 15119; +pub const ERROR_MRM_INVALID_RESOURCE_IDENTIFIER: ::DWORD = 15120; +pub const ERROR_MRM_FILEPATH_TOO_LONG: ::DWORD = 15121; +pub const ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE: ::DWORD = 15122; +pub const ERROR_MRM_INVALID_PRI_FILE: ::DWORD = 15126; +pub const ERROR_MRM_NAMED_RESOURCE_NOT_FOUND: ::DWORD = 15127; +pub const ERROR_MRM_MAP_NOT_FOUND: ::DWORD = 15135; +pub const ERROR_MRM_UNSUPPORTED_PROFILE_TYPE: ::DWORD = 15136; +pub const ERROR_MRM_INVALID_QUALIFIER_OPERATOR: ::DWORD = 15137; +pub const ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE: ::DWORD = 15138; +pub const ERROR_MRM_AUTOMERGE_ENABLED: ::DWORD = 15139; +pub const ERROR_MRM_TOO_MANY_RESOURCES: ::DWORD = 15140; +pub const ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_MERGE: ::DWORD = 15141; +pub const ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_LOAD_UNLOAD_PRI_FILE: ::DWORD = 15142; +pub const ERROR_MRM_NO_CURRENT_VIEW_ON_THREAD: ::DWORD = 15143; +pub const ERROR_DIFFERENT_PROFILE_RESOURCE_MANAGER_EXIST: ::DWORD = 15144; +pub const ERROR_OPERATION_NOT_ALLOWED_FROM_SYSTEM_COMPONENT: ::DWORD = 15145; +pub const ERROR_MRM_DIRECT_REF_TO_NON_DEFAULT_RESOURCE: ::DWORD = 15146; +pub const ERROR_MRM_GENERATION_COUNT_MISMATCH: ::DWORD = 15147; +pub const ERROR_MCA_INVALID_CAPABILITIES_STRING: ::DWORD = 15200; +pub const ERROR_MCA_INVALID_VCP_VERSION: ::DWORD = 15201; +pub const ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: ::DWORD = 15202; +pub const ERROR_MCA_MCCS_VERSION_MISMATCH: ::DWORD = 15203; +pub const ERROR_MCA_UNSUPPORTED_MCCS_VERSION: ::DWORD = 15204; +pub const ERROR_MCA_INTERNAL_ERROR: ::DWORD = 15205; +pub const ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: ::DWORD = 15206; +pub const ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE: ::DWORD = 15207; +pub const ERROR_AMBIGUOUS_SYSTEM_DEVICE: ::DWORD = 15250; +pub const ERROR_SYSTEM_DEVICE_NOT_FOUND: ::DWORD = 15299; +pub const ERROR_HASH_NOT_SUPPORTED: ::DWORD = 15300; +pub const ERROR_HASH_NOT_PRESENT: ::DWORD = 15301; +pub const ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED: ::DWORD = 15321; +pub const ERROR_GPIO_CLIENT_INFORMATION_INVALID: ::DWORD = 15322; +pub const ERROR_GPIO_VERSION_NOT_SUPPORTED: ::DWORD = 15323; +pub const ERROR_GPIO_INVALID_REGISTRATION_PACKET: ::DWORD = 15324; +pub const ERROR_GPIO_OPERATION_DENIED: ::DWORD = 15325; +pub const ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE: ::DWORD = 15326; +pub const ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED: ::DWORD = 15327; +pub const ERROR_CANNOT_SWITCH_RUNLEVEL: ::DWORD = 15400; +pub const ERROR_INVALID_RUNLEVEL_SETTING: ::DWORD = 15401; +pub const ERROR_RUNLEVEL_SWITCH_TIMEOUT: ::DWORD = 15402; +pub const ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT: ::DWORD = 15403; +pub const ERROR_RUNLEVEL_SWITCH_IN_PROGRESS: ::DWORD = 15404; +pub const ERROR_SERVICES_FAILED_AUTOSTART: ::DWORD = 15405; +pub const ERROR_COM_TASK_STOP_PENDING: ::DWORD = 15501; +pub const ERROR_INSTALL_OPEN_PACKAGE_FAILED: ::DWORD = 15600; +pub const ERROR_INSTALL_PACKAGE_NOT_FOUND: ::DWORD = 15601; +pub const ERROR_INSTALL_INVALID_PACKAGE: ::DWORD = 15602; +pub const ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED: ::DWORD = 15603; +pub const ERROR_INSTALL_OUT_OF_DISK_SPACE: ::DWORD = 15604; +pub const ERROR_INSTALL_NETWORK_FAILURE: ::DWORD = 15605; +pub const ERROR_INSTALL_REGISTRATION_FAILURE: ::DWORD = 15606; +pub const ERROR_INSTALL_DEREGISTRATION_FAILURE: ::DWORD = 15607; +pub const ERROR_INSTALL_CANCEL: ::DWORD = 15608; +pub const ERROR_INSTALL_FAILED: ::DWORD = 15609; +pub const ERROR_REMOVE_FAILED: ::DWORD = 15610; +pub const ERROR_PACKAGE_ALREADY_EXISTS: ::DWORD = 15611; +pub const ERROR_NEEDS_REMEDIATION: ::DWORD = 15612; +pub const ERROR_INSTALL_PREREQUISITE_FAILED: ::DWORD = 15613; +pub const ERROR_PACKAGE_REPOSITORY_CORRUPTED: ::DWORD = 15614; +pub const ERROR_INSTALL_POLICY_FAILURE: ::DWORD = 15615; +pub const ERROR_PACKAGE_UPDATING: ::DWORD = 15616; +pub const ERROR_DEPLOYMENT_BLOCKED_BY_POLICY: ::DWORD = 15617; +pub const ERROR_PACKAGES_IN_USE: ::DWORD = 15618; +pub const ERROR_RECOVERY_FILE_CORRUPT: ::DWORD = 15619; +pub const ERROR_INVALID_STAGED_SIGNATURE: ::DWORD = 15620; +pub const ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED: ::DWORD = 15621; +pub const ERROR_INSTALL_PACKAGE_DOWNGRADE: ::DWORD = 15622; +pub const ERROR_SYSTEM_NEEDS_REMEDIATION: ::DWORD = 15623; +pub const ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN: ::DWORD = 15624; +pub const ERROR_RESILIENCY_FILE_CORRUPT: ::DWORD = 15625; +pub const ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING: ::DWORD = 15626; +pub const APPMODEL_ERROR_NO_PACKAGE: ::DWORD = 15700; +pub const APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT: ::DWORD = 15701; +pub const APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT: ::DWORD = 15702; +pub const APPMODEL_ERROR_NO_APPLICATION: ::DWORD = 15703; +pub const APPMODEL_ERROR_DYNAMIC_PROPERTY_READ_FAILED: ::DWORD = 15704; +pub const APPMODEL_ERROR_DYNAMIC_PROPERTY_INVALID: ::DWORD = 15705; +pub const ERROR_STATE_LOAD_STORE_FAILED: ::DWORD = 15800; +pub const ERROR_STATE_GET_VERSION_FAILED: ::DWORD = 15801; +pub const ERROR_STATE_SET_VERSION_FAILED: ::DWORD = 15802; +pub const ERROR_STATE_STRUCTURED_RESET_FAILED: ::DWORD = 15803; +pub const ERROR_STATE_OPEN_CONTAINER_FAILED: ::DWORD = 15804; +pub const ERROR_STATE_CREATE_CONTAINER_FAILED: ::DWORD = 15805; +pub const ERROR_STATE_DELETE_CONTAINER_FAILED: ::DWORD = 15806; +pub const ERROR_STATE_READ_SETTING_FAILED: ::DWORD = 15807; +pub const ERROR_STATE_WRITE_SETTING_FAILED: ::DWORD = 15808; +pub const ERROR_STATE_DELETE_SETTING_FAILED: ::DWORD = 15809; +pub const ERROR_STATE_QUERY_SETTING_FAILED: ::DWORD = 15810; +pub const ERROR_STATE_READ_COMPOSITE_SETTING_FAILED: ::DWORD = 15811; +pub const ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED: ::DWORD = 15812; +pub const ERROR_STATE_ENUMERATE_CONTAINER_FAILED: ::DWORD = 15813; +pub const ERROR_STATE_ENUMERATE_SETTINGS_FAILED: ::DWORD = 15814; +pub const ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: ::DWORD = 15815; +pub const ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: ::DWORD = 15816; +pub const ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED: ::DWORD = 15817; +pub const ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED: ::DWORD = 15818; +pub const ERROR_API_UNAVAILABLE: ::DWORD = 15841; +pub const STORE_ERROR_UNLICENSED: ::DWORD = 15861; +pub const STORE_ERROR_UNLICENSED_USER: ::DWORD = 15862; +pub const STORE_ERROR_PENDING_COM_TRANSACTION: ::DWORD = 15863; +pub const STORE_ERROR_LICENSE_REVOKED: ::DWORD = 15864; +pub const SEVERITY_SUCCESS: HRESULT = 0; +pub const SEVERITY_ERROR: HRESULT = 1; +#[inline] +pub fn MAKE_HRESULT(sev: HRESULT, fac: HRESULT, code: HRESULT) -> HRESULT { + (sev << 31) | (fac << 16) | code +} +pub type HRESULT = ::c_long; +pub const NOERROR: HRESULT = 0; +pub const E_UNEXPECTED: HRESULT = 0x8000FFFFu32 as HRESULT; +pub const E_NOTIMPL: HRESULT = 0x80004001u32 as HRESULT; +pub const E_OUTOFMEMORY: HRESULT = 0x8007000Eu32 as HRESULT; +pub const E_INVALIDARG: HRESULT = 0x80070057u32 as HRESULT; +pub const E_NOINTERFACE: HRESULT = 0x80004002u32 as HRESULT; +pub const E_POINTER: HRESULT = 0x80004003u32 as HRESULT; +pub const E_HANDLE: HRESULT = 0x80070006u32 as HRESULT; +pub const E_ABORT: HRESULT = 0x80004004u32 as HRESULT; +pub const E_FAIL: HRESULT = 0x80004005u32 as HRESULT; +pub const E_ACCESSDENIED: HRESULT = 0x80070005u32 as HRESULT; +pub const E_PENDING: HRESULT = 0x8000000Au32 as HRESULT; +pub const E_BOUNDS: HRESULT = 0x8000000Bu32 as HRESULT; +pub const E_CHANGED_STATE: HRESULT = 0x8000000Cu32 as HRESULT; +pub const E_ILLEGAL_STATE_CHANGE: HRESULT = 0x8000000Du32 as HRESULT; +pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000000Eu32 as HRESULT; +pub const RO_E_METADATA_NAME_NOT_FOUND: HRESULT = 0x8000000Fu32 as HRESULT; +pub const RO_E_METADATA_NAME_IS_NAMESPACE: HRESULT = 0x80000010u32 as HRESULT; +pub const RO_E_METADATA_INVALID_TYPE_FORMAT: HRESULT = 0x80000011u32 as HRESULT; +pub const RO_E_INVALID_METADATA_FILE: HRESULT = 0x80000012u32 as HRESULT; +pub const RO_E_CLOSED: HRESULT = 0x80000013u32 as HRESULT; +pub const RO_E_EXCLUSIVE_WRITE: HRESULT = 0x80000014u32 as HRESULT; +pub const RO_E_CHANGE_NOTIFICATION_IN_PROGRESS: HRESULT = 0x80000015u32 as HRESULT; +pub const RO_E_ERROR_STRING_NOT_FOUND: HRESULT = 0x80000016u32 as HRESULT; +pub const E_STRING_NOT_NULL_TERMINATED: HRESULT = 0x80000017u32 as HRESULT; +pub const E_ILLEGAL_DELEGATE_ASSIGNMENT: HRESULT = 0x80000018u32 as HRESULT; +pub const E_ASYNC_OPERATION_NOT_STARTED: HRESULT = 0x80000019u32 as HRESULT; +pub const E_APPLICATION_EXITING: HRESULT = 0x8000001Au32 as HRESULT; +pub const E_APPLICATION_VIEW_EXITING: HRESULT = 0x8000001Bu32 as HRESULT; +pub const RO_E_MUST_BE_AGILE: HRESULT = 0x8000001Cu32 as HRESULT; +pub const RO_E_UNSUPPORTED_FROM_MTA: HRESULT = 0x8000001Du32 as HRESULT; +pub const RO_E_COMMITTED: HRESULT = 0x8000001Eu32 as HRESULT; +pub const RO_E_BLOCKED_CROSS_ASTA_CALL: HRESULT = 0x8000001Fu32 as HRESULT; +pub const CO_E_INIT_TLS: HRESULT = 0x80004006u32 as HRESULT; +pub const CO_E_INIT_SHARED_ALLOCATOR: HRESULT = 0x80004007u32 as HRESULT; +pub const CO_E_INIT_MEMORY_ALLOCATOR: HRESULT = 0x80004008u32 as HRESULT; +pub const CO_E_INIT_CLASS_CACHE: HRESULT = 0x80004009u32 as HRESULT; +pub const CO_E_INIT_RPC_CHANNEL: HRESULT = 0x8000400Au32 as HRESULT; +pub const CO_E_INIT_TLS_SET_CHANNEL_CONTROL: HRESULT = 0x8000400Bu32 as HRESULT; +pub const CO_E_INIT_TLS_CHANNEL_CONTROL: HRESULT = 0x8000400Cu32 as HRESULT; +pub const CO_E_INIT_UNACCEPTED_USER_ALLOCATOR: HRESULT = 0x8000400Du32 as HRESULT; +pub const CO_E_INIT_SCM_MUTEX_EXISTS: HRESULT = 0x8000400Eu32 as HRESULT; +pub const CO_E_INIT_SCM_FILE_MAPPING_EXISTS: HRESULT = 0x8000400Fu32 as HRESULT; +pub const CO_E_INIT_SCM_MAP_VIEW_OF_FILE: HRESULT = 0x80004010u32 as HRESULT; +pub const CO_E_INIT_SCM_EXEC_FAILURE: HRESULT = 0x80004011u32 as HRESULT; +pub const CO_E_INIT_ONLY_SINGLE_THREADED: HRESULT = 0x80004012u32 as HRESULT; +pub const CO_E_CANT_REMOTE: HRESULT = 0x80004013u32 as HRESULT; +pub const CO_E_BAD_SERVER_NAME: HRESULT = 0x80004014u32 as HRESULT; +pub const CO_E_WRONG_SERVER_IDENTITY: HRESULT = 0x80004015u32 as HRESULT; +pub const CO_E_OLE1DDE_DISABLED: HRESULT = 0x80004016u32 as HRESULT; +pub const CO_E_RUNAS_SYNTAX: HRESULT = 0x80004017u32 as HRESULT; +pub const CO_E_CREATEPROCESS_FAILURE: HRESULT = 0x80004018u32 as HRESULT; +pub const CO_E_RUNAS_CREATEPROCESS_FAILURE: HRESULT = 0x80004019u32 as HRESULT; +pub const CO_E_RUNAS_LOGON_FAILURE: HRESULT = 0x8000401Au32 as HRESULT; +pub const CO_E_LAUNCH_PERMSSION_DENIED: HRESULT = 0x8000401Bu32 as HRESULT; +pub const CO_E_START_SERVICE_FAILURE: HRESULT = 0x8000401Cu32 as HRESULT; +pub const CO_E_REMOTE_COMMUNICATION_FAILURE: HRESULT = 0x8000401Du32 as HRESULT; +pub const CO_E_SERVER_START_TIMEOUT: HRESULT = 0x8000401Eu32 as HRESULT; +pub const CO_E_CLSREG_INCONSISTENT: HRESULT = 0x8000401Fu32 as HRESULT; +pub const CO_E_IIDREG_INCONSISTENT: HRESULT = 0x80004020u32 as HRESULT; +pub const CO_E_NOT_SUPPORTED: HRESULT = 0x80004021u32 as HRESULT; +pub const CO_E_RELOAD_DLL: HRESULT = 0x80004022u32 as HRESULT; +pub const CO_E_MSI_ERROR: HRESULT = 0x80004023u32 as HRESULT; +pub const CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT: HRESULT = 0x80004024u32 as HRESULT; +pub const CO_E_SERVER_PAUSED: HRESULT = 0x80004025u32 as HRESULT; +pub const CO_E_SERVER_NOT_PAUSED: HRESULT = 0x80004026u32 as HRESULT; +pub const CO_E_CLASS_DISABLED: HRESULT = 0x80004027u32 as HRESULT; +pub const CO_E_CLRNOTAVAILABLE: HRESULT = 0x80004028u32 as HRESULT; +pub const CO_E_ASYNC_WORK_REJECTED: HRESULT = 0x80004029u32 as HRESULT; +pub const CO_E_SERVER_INIT_TIMEOUT: HRESULT = 0x8000402Au32 as HRESULT; +pub const CO_E_NO_SECCTX_IN_ACTIVATE: HRESULT = 0x8000402Bu32 as HRESULT; +pub const CO_E_TRACKER_CONFIG: HRESULT = 0x80004030u32 as HRESULT; +pub const CO_E_THREADPOOL_CONFIG: HRESULT = 0x80004031u32 as HRESULT; +pub const CO_E_SXS_CONFIG: HRESULT = 0x80004032u32 as HRESULT; +pub const CO_E_MALFORMED_SPN: HRESULT = 0x80004033u32 as HRESULT; +pub const CO_E_UNREVOKED_REGISTRATION_ON_APARTMENT_SHUTDOWN: HRESULT = 0x80004034u32 as HRESULT; +pub const CO_E_PREMATURE_STUB_RUNDOWN: HRESULT = 0x80004035u32 as HRESULT; +pub const S_OK: HRESULT = 0; +pub const S_FALSE: HRESULT = 1; +pub const OLE_E_FIRST: HRESULT = 0x80040000u32 as HRESULT; +pub const OLE_E_LAST: HRESULT = 0x800400FFu32 as HRESULT; +pub const OLE_S_FIRST: HRESULT = 0x00040000; +pub const OLE_S_LAST: HRESULT = 0x000400FF; +pub const OLE_E_OLEVERB: HRESULT = 0x80040000u32 as HRESULT; +pub const OLE_E_ADVF: HRESULT = 0x80040001u32 as HRESULT; +pub const OLE_E_ENUM_NOMORE: HRESULT = 0x80040002u32 as HRESULT; +pub const OLE_E_ADVISENOTSUPPORTED: HRESULT = 0x80040003u32 as HRESULT; +pub const OLE_E_NOCONNECTION: HRESULT = 0x80040004u32 as HRESULT; +pub const OLE_E_NOTRUNNING: HRESULT = 0x80040005u32 as HRESULT; +pub const OLE_E_NOCACHE: HRESULT = 0x80040006u32 as HRESULT; +pub const OLE_E_BLANK: HRESULT = 0x80040007u32 as HRESULT; +pub const OLE_E_CLASSDIFF: HRESULT = 0x80040008u32 as HRESULT; +pub const OLE_E_CANT_GETMONIKER: HRESULT = 0x80040009u32 as HRESULT; +pub const OLE_E_CANT_BINDTOSOURCE: HRESULT = 0x8004000Au32 as HRESULT; +pub const OLE_E_STATIC: HRESULT = 0x8004000Bu32 as HRESULT; +pub const OLE_E_PROMPTSAVECANCELLED: HRESULT = 0x8004000Cu32 as HRESULT; +pub const OLE_E_INVALIDRECT: HRESULT = 0x8004000Du32 as HRESULT; +pub const OLE_E_WRONGCOMPOBJ: HRESULT = 0x8004000Eu32 as HRESULT; +pub const OLE_E_INVALIDHWND: HRESULT = 0x8004000Fu32 as HRESULT; +pub const OLE_E_NOT_INPLACEACTIVE: HRESULT = 0x80040010u32 as HRESULT; +pub const OLE_E_CANTCONVERT: HRESULT = 0x80040011u32 as HRESULT; +pub const OLE_E_NOSTORAGE: HRESULT = 0x80040012u32 as HRESULT; +pub const DV_E_FORMATETC: HRESULT = 0x80040064u32 as HRESULT; +pub const DV_E_DVTARGETDEVICE: HRESULT = 0x80040065u32 as HRESULT; +pub const DV_E_STGMEDIUM: HRESULT = 0x80040066u32 as HRESULT; +pub const DV_E_STATDATA: HRESULT = 0x80040067u32 as HRESULT; +pub const DV_E_LINDEX: HRESULT = 0x80040068u32 as HRESULT; +pub const DV_E_TYMED: HRESULT = 0x80040069u32 as HRESULT; +pub const DV_E_CLIPFORMAT: HRESULT = 0x8004006Au32 as HRESULT; +pub const DV_E_DVASPECT: HRESULT = 0x8004006Bu32 as HRESULT; +pub const DV_E_DVTARGETDEVICE_SIZE: HRESULT = 0x8004006Cu32 as HRESULT; +pub const DV_E_NOIVIEWOBJECT: HRESULT = 0x8004006Du32 as HRESULT; +pub const DRAGDROP_E_FIRST: HRESULT = 0x80040100u32 as HRESULT; +pub const DRAGDROP_E_LAST: HRESULT = 0x8004010Fu32 as HRESULT; +pub const DRAGDROP_S_FIRST: HRESULT = 0x00040100; +pub const DRAGDROP_S_LAST: HRESULT = 0x0004010F; +pub const DRAGDROP_E_NOTREGISTERED: HRESULT = 0x80040100u32 as HRESULT; +pub const DRAGDROP_E_ALREADYREGISTERED: HRESULT = 0x80040101u32 as HRESULT; +pub const DRAGDROP_E_INVALIDHWND: HRESULT = 0x80040102u32 as HRESULT; +pub const DRAGDROP_E_CONCURRENT_DRAG_ATTEMPTED: HRESULT = 0x80040103u32 as HRESULT; +pub const CLASSFACTORY_E_FIRST: HRESULT = 0x80040110u32 as HRESULT; +pub const CLASSFACTORY_E_LAST: HRESULT = 0x8004011Fu32 as HRESULT; +pub const CLASSFACTORY_S_FIRST: HRESULT = 0x00040110; +pub const CLASSFACTORY_S_LAST: HRESULT = 0x0004011F; +pub const CLASS_E_NOAGGREGATION: HRESULT = 0x80040110u32 as HRESULT; +pub const CLASS_E_CLASSNOTAVAILABLE: HRESULT = 0x80040111u32 as HRESULT; +pub const CLASS_E_NOTLICENSED: HRESULT = 0x80040112u32 as HRESULT; +pub const MARSHAL_E_FIRST: HRESULT = 0x80040120u32 as HRESULT; +pub const MARSHAL_E_LAST: HRESULT = 0x8004012Fu32 as HRESULT; +pub const MARSHAL_S_FIRST: HRESULT = 0x00040120; +pub const MARSHAL_S_LAST: HRESULT = 0x0004012F; +pub const DATA_E_FIRST: HRESULT = 0x80040130u32 as HRESULT; +pub const DATA_E_LAST: HRESULT = 0x8004013Fu32 as HRESULT; +pub const DATA_S_FIRST: HRESULT = 0x00040130; +pub const DATA_S_LAST: HRESULT = 0x0004013F; +pub const VIEW_E_FIRST: HRESULT = 0x80040140u32 as HRESULT; +pub const VIEW_E_LAST: HRESULT = 0x8004014Fu32 as HRESULT; +pub const VIEW_S_FIRST: HRESULT = 0x00040140; +pub const VIEW_S_LAST: HRESULT = 0x0004014F; +pub const VIEW_E_DRAW: HRESULT = 0x80040140u32 as HRESULT; +pub const REGDB_E_FIRST: HRESULT = 0x80040150u32 as HRESULT; +pub const REGDB_E_LAST: HRESULT = 0x8004015Fu32 as HRESULT; +pub const REGDB_S_FIRST: HRESULT = 0x00040150; +pub const REGDB_S_LAST: HRESULT = 0x0004015F; +pub const REGDB_E_READREGDB: HRESULT = 0x80040150u32 as HRESULT; +pub const REGDB_E_WRITEREGDB: HRESULT = 0x80040151u32 as HRESULT; +pub const REGDB_E_KEYMISSING: HRESULT = 0x80040152u32 as HRESULT; +pub const REGDB_E_INVALIDVALUE: HRESULT = 0x80040153u32 as HRESULT; +pub const REGDB_E_CLASSNOTREG: HRESULT = 0x80040154u32 as HRESULT; +pub const REGDB_E_IIDNOTREG: HRESULT = 0x80040155u32 as HRESULT; +pub const REGDB_E_BADTHREADINGMODEL: HRESULT = 0x80040156u32 as HRESULT; +pub const CAT_E_FIRST: HRESULT = 0x80040160u32 as HRESULT; +pub const CAT_E_LAST: HRESULT = 0x80040161u32 as HRESULT; +pub const CAT_E_CATIDNOEXIST: HRESULT = 0x80040160u32 as HRESULT; +pub const CAT_E_NODESCRIPTION: HRESULT = 0x80040161u32 as HRESULT; +pub const CS_E_FIRST: HRESULT = 0x80040164u32 as HRESULT; +pub const CS_E_LAST: HRESULT = 0x8004016Fu32 as HRESULT; +pub const CS_E_PACKAGE_NOTFOUND: HRESULT = 0x80040164u32 as HRESULT; +pub const CS_E_NOT_DELETABLE: HRESULT = 0x80040165u32 as HRESULT; +pub const CS_E_CLASS_NOTFOUND: HRESULT = 0x80040166u32 as HRESULT; +pub const CS_E_INVALID_VERSION: HRESULT = 0x80040167u32 as HRESULT; +pub const CS_E_NO_CLASSSTORE: HRESULT = 0x80040168u32 as HRESULT; +pub const CS_E_OBJECT_NOTFOUND: HRESULT = 0x80040169u32 as HRESULT; +pub const CS_E_OBJECT_ALREADY_EXISTS: HRESULT = 0x8004016Au32 as HRESULT; +pub const CS_E_INVALID_PATH: HRESULT = 0x8004016Bu32 as HRESULT; +pub const CS_E_NETWORK_ERROR: HRESULT = 0x8004016Cu32 as HRESULT; +pub const CS_E_ADMIN_LIMIT_EXCEEDED: HRESULT = 0x8004016Du32 as HRESULT; +pub const CS_E_SCHEMA_MISMATCH: HRESULT = 0x8004016Eu32 as HRESULT; +pub const CS_E_INTERNAL_ERROR: HRESULT = 0x8004016Fu32 as HRESULT; +pub const CACHE_E_FIRST: HRESULT = 0x80040170u32 as HRESULT; +pub const CACHE_E_LAST: HRESULT = 0x8004017Fu32 as HRESULT; +pub const CACHE_S_FIRST: HRESULT = 0x00040170; +pub const CACHE_S_LAST: HRESULT = 0x0004017F; +pub const CACHE_E_NOCACHE_UPDATED: HRESULT = 0x80040170u32 as HRESULT; +pub const OLEOBJ_E_FIRST: HRESULT = 0x80040180u32 as HRESULT; +pub const OLEOBJ_E_LAST: HRESULT = 0x8004018Fu32 as HRESULT; +pub const OLEOBJ_S_FIRST: HRESULT = 0x00040180; +pub const OLEOBJ_S_LAST: HRESULT = 0x0004018F; +pub const OLEOBJ_E_NOVERBS: HRESULT = 0x80040180u32 as HRESULT; +pub const OLEOBJ_E_INVALIDVERB: HRESULT = 0x80040181u32 as HRESULT; +pub const CLIENTSITE_E_FIRST: HRESULT = 0x80040190u32 as HRESULT; +pub const CLIENTSITE_E_LAST: HRESULT = 0x8004019Fu32 as HRESULT; +pub const CLIENTSITE_S_FIRST: HRESULT = 0x00040190; +pub const CLIENTSITE_S_LAST: HRESULT = 0x0004019F; +pub const INPLACE_E_NOTUNDOABLE: HRESULT = 0x800401A0u32 as HRESULT; +pub const INPLACE_E_NOTOOLSPACE: HRESULT = 0x800401A1u32 as HRESULT; +pub const INPLACE_E_FIRST: HRESULT = 0x800401A0u32 as HRESULT; +pub const INPLACE_E_LAST: HRESULT = 0x800401AFu32 as HRESULT; +pub const INPLACE_S_FIRST: HRESULT = 0x000401A0; +pub const INPLACE_S_LAST: HRESULT = 0x000401AF; +pub const ENUM_E_FIRST: HRESULT = 0x800401B0u32 as HRESULT; +pub const ENUM_E_LAST: HRESULT = 0x800401BFu32 as HRESULT; +pub const ENUM_S_FIRST: HRESULT = 0x000401B0; +pub const ENUM_S_LAST: HRESULT = 0x000401BF; +pub const CONVERT10_E_FIRST: HRESULT = 0x800401C0u32 as HRESULT; +pub const CONVERT10_E_LAST: HRESULT = 0x800401CFu32 as HRESULT; +pub const CONVERT10_S_FIRST: HRESULT = 0x000401C0; +pub const CONVERT10_S_LAST: HRESULT = 0x000401CF; +pub const CONVERT10_E_OLESTREAM_GET: HRESULT = 0x800401C0u32 as HRESULT; +pub const CONVERT10_E_OLESTREAM_PUT: HRESULT = 0x800401C1u32 as HRESULT; +pub const CONVERT10_E_OLESTREAM_FMT: HRESULT = 0x800401C2u32 as HRESULT; +pub const CONVERT10_E_OLESTREAM_BITMAP_TO_DIB: HRESULT = 0x800401C3u32 as HRESULT; +pub const CONVERT10_E_STG_FMT: HRESULT = 0x800401C4u32 as HRESULT; +pub const CONVERT10_E_STG_NO_STD_STREAM: HRESULT = 0x800401C5u32 as HRESULT; +pub const CONVERT10_E_STG_DIB_TO_BITMAP: HRESULT = 0x800401C6u32 as HRESULT; +pub const CLIPBRD_E_FIRST: HRESULT = 0x800401D0u32 as HRESULT; +pub const CLIPBRD_E_LAST: HRESULT = 0x800401DFu32 as HRESULT; +pub const CLIPBRD_S_FIRST: HRESULT = 0x000401D0; +pub const CLIPBRD_S_LAST: HRESULT = 0x000401DF; +pub const CLIPBRD_E_CANT_OPEN: HRESULT = 0x800401D0u32 as HRESULT; +pub const CLIPBRD_E_CANT_EMPTY: HRESULT = 0x800401D1u32 as HRESULT; +pub const CLIPBRD_E_CANT_SET: HRESULT = 0x800401D2u32 as HRESULT; +pub const CLIPBRD_E_BAD_DATA: HRESULT = 0x800401D3u32 as HRESULT; +pub const CLIPBRD_E_CANT_CLOSE: HRESULT = 0x800401D4u32 as HRESULT; +pub const MK_E_FIRST: HRESULT = 0x800401E0u32 as HRESULT; +pub const MK_E_LAST: HRESULT = 0x800401EFu32 as HRESULT; +pub const MK_S_FIRST: HRESULT = 0x000401E0; +pub const MK_S_LAST: HRESULT = 0x000401EF; +pub const MK_E_CONNECTMANUALLY: HRESULT = 0x800401E0u32 as HRESULT; +pub const MK_E_EXCEEDEDDEADLINE: HRESULT = 0x800401E1u32 as HRESULT; +pub const MK_E_NEEDGENERIC: HRESULT = 0x800401E2u32 as HRESULT; +pub const MK_E_UNAVAILABLE: HRESULT = 0x800401E3u32 as HRESULT; +pub const MK_E_SYNTAX: HRESULT = 0x800401E4u32 as HRESULT; +pub const MK_E_NOOBJECT: HRESULT = 0x800401E5u32 as HRESULT; +pub const MK_E_INVALIDEXTENSION: HRESULT = 0x800401E6u32 as HRESULT; +pub const MK_E_INTERMEDIATEINTERFACENOTSUPPORTED: HRESULT = 0x800401E7u32 as HRESULT; +pub const MK_E_NOTBINDABLE: HRESULT = 0x800401E8u32 as HRESULT; +pub const MK_E_NOTBOUND: HRESULT = 0x800401E9u32 as HRESULT; +pub const MK_E_CANTOPENFILE: HRESULT = 0x800401EAu32 as HRESULT; +pub const MK_E_MUSTBOTHERUSER: HRESULT = 0x800401EBu32 as HRESULT; +pub const MK_E_NOINVERSE: HRESULT = 0x800401ECu32 as HRESULT; +pub const MK_E_NOSTORAGE: HRESULT = 0x800401EDu32 as HRESULT; +pub const MK_E_NOPREFIX: HRESULT = 0x800401EEu32 as HRESULT; +pub const MK_E_ENUMERATION_FAILED: HRESULT = 0x800401EFu32 as HRESULT; +pub const CO_E_FIRST: HRESULT = 0x800401F0u32 as HRESULT; +pub const CO_E_LAST: HRESULT = 0x800401FFu32 as HRESULT; +pub const CO_S_FIRST: HRESULT = 0x000401F0; +pub const CO_S_LAST: HRESULT = 0x000401FF; +pub const CO_E_NOTINITIALIZED: HRESULT = 0x800401F0u32 as HRESULT; +pub const CO_E_ALREADYINITIALIZED: HRESULT = 0x800401F1u32 as HRESULT; +pub const CO_E_CANTDETERMINECLASS: HRESULT = 0x800401F2u32 as HRESULT; +pub const CO_E_CLASSSTRING: HRESULT = 0x800401F3u32 as HRESULT; +pub const CO_E_IIDSTRING: HRESULT = 0x800401F4u32 as HRESULT; +pub const CO_E_APPNOTFOUND: HRESULT = 0x800401F5u32 as HRESULT; +pub const CO_E_APPSINGLEUSE: HRESULT = 0x800401F6u32 as HRESULT; +pub const CO_E_ERRORINAPP: HRESULT = 0x800401F7u32 as HRESULT; +pub const CO_E_DLLNOTFOUND: HRESULT = 0x800401F8u32 as HRESULT; +pub const CO_E_ERRORINDLL: HRESULT = 0x800401F9u32 as HRESULT; +pub const CO_E_WRONGOSFORAPP: HRESULT = 0x800401FAu32 as HRESULT; +pub const CO_E_OBJNOTREG: HRESULT = 0x800401FBu32 as HRESULT; +pub const CO_E_OBJISREG: HRESULT = 0x800401FCu32 as HRESULT; +pub const CO_E_OBJNOTCONNECTED: HRESULT = 0x800401FDu32 as HRESULT; +pub const CO_E_APPDIDNTREG: HRESULT = 0x800401FEu32 as HRESULT; +pub const CO_E_RELEASED: HRESULT = 0x800401FFu32 as HRESULT; +pub const EVENT_E_FIRST: HRESULT = 0x80040200u32 as HRESULT; +pub const EVENT_E_LAST: HRESULT = 0x8004021Fu32 as HRESULT; +pub const EVENT_S_FIRST: HRESULT = 0x00040200; +pub const EVENT_S_LAST: HRESULT = 0x0004021F; +pub const EVENT_S_SOME_SUBSCRIBERS_FAILED: HRESULT = 0x00040200; +pub const EVENT_E_ALL_SUBSCRIBERS_FAILED: HRESULT = 0x80040201u32 as HRESULT; +pub const EVENT_S_NOSUBSCRIBERS: HRESULT = 0x00040202; +pub const EVENT_E_QUERYSYNTAX: HRESULT = 0x80040203u32 as HRESULT; +pub const EVENT_E_QUERYFIELD: HRESULT = 0x80040204u32 as HRESULT; +pub const EVENT_E_INTERNALEXCEPTION: HRESULT = 0x80040205u32 as HRESULT; +pub const EVENT_E_INTERNALERROR: HRESULT = 0x80040206u32 as HRESULT; +pub const EVENT_E_INVALID_PER_USER_SID: HRESULT = 0x80040207u32 as HRESULT; +pub const EVENT_E_USER_EXCEPTION: HRESULT = 0x80040208u32 as HRESULT; +pub const EVENT_E_TOO_MANY_METHODS: HRESULT = 0x80040209u32 as HRESULT; +pub const EVENT_E_MISSING_EVENTCLASS: HRESULT = 0x8004020Au32 as HRESULT; +pub const EVENT_E_NOT_ALL_REMOVED: HRESULT = 0x8004020Bu32 as HRESULT; +pub const EVENT_E_COMPLUS_NOT_INSTALLED: HRESULT = 0x8004020Cu32 as HRESULT; +pub const EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT: HRESULT = 0x8004020Du32 as HRESULT; +pub const EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT: HRESULT = 0x8004020Eu32 as HRESULT; +pub const EVENT_E_INVALID_EVENT_CLASS_PARTITION: HRESULT = 0x8004020Fu32 as HRESULT; +pub const EVENT_E_PER_USER_SID_NOT_LOGGED_ON: HRESULT = 0x80040210u32 as HRESULT; +pub const TPC_E_INVALID_PROPERTY: HRESULT = 0x80040241u32 as HRESULT; +pub const TPC_E_NO_DEFAULT_TABLET: HRESULT = 0x80040212u32 as HRESULT; +pub const TPC_E_UNKNOWN_PROPERTY: HRESULT = 0x8004021Bu32 as HRESULT; +pub const TPC_E_INVALID_INPUT_RECT: HRESULT = 0x80040219u32 as HRESULT; +pub const TPC_E_INVALID_STROKE: HRESULT = 0x80040222u32 as HRESULT; +pub const TPC_E_INITIALIZE_FAIL: HRESULT = 0x80040223u32 as HRESULT; +pub const TPC_E_NOT_RELEVANT: HRESULT = 0x80040232u32 as HRESULT; +pub const TPC_E_INVALID_PACKET_DESCRIPTION: HRESULT = 0x80040233u32 as HRESULT; +pub const TPC_E_RECOGNIZER_NOT_REGISTERED: HRESULT = 0x80040235u32 as HRESULT; +pub const TPC_E_INVALID_RIGHTS: HRESULT = 0x80040236u32 as HRESULT; +pub const TPC_E_OUT_OF_ORDER_CALL: HRESULT = 0x80040237u32 as HRESULT; +pub const TPC_E_QUEUE_FULL: HRESULT = 0x80040238u32 as HRESULT; +pub const TPC_E_INVALID_CONFIGURATION: HRESULT = 0x80040239u32 as HRESULT; +pub const TPC_E_INVALID_DATA_FROM_RECOGNIZER: HRESULT = 0x8004023Au32 as HRESULT; +pub const TPC_S_TRUNCATED: HRESULT = 0x00040252; +pub const TPC_S_INTERRUPTED: HRESULT = 0x00040253; +pub const TPC_S_NO_DATA_TO_PROCESS: HRESULT = 0x00040254; +pub const XACT_E_FIRST: HRESULT = 0x8004D000u32 as HRESULT; +pub const XACT_E_LAST: HRESULT = 0x8004D02Bu32 as HRESULT; +pub const XACT_S_FIRST: HRESULT = 0x0004D000; +pub const XACT_S_LAST: HRESULT = 0x0004D010; +pub const XACT_E_ALREADYOTHERSINGLEPHASE: HRESULT = 0x8004D000u32 as HRESULT; +pub const XACT_E_CANTRETAIN: HRESULT = 0x8004D001u32 as HRESULT; +pub const XACT_E_COMMITFAILED: HRESULT = 0x8004D002u32 as HRESULT; +pub const XACT_E_COMMITPREVENTED: HRESULT = 0x8004D003u32 as HRESULT; +pub const XACT_E_HEURISTICABORT: HRESULT = 0x8004D004u32 as HRESULT; +pub const XACT_E_HEURISTICCOMMIT: HRESULT = 0x8004D005u32 as HRESULT; +pub const XACT_E_HEURISTICDAMAGE: HRESULT = 0x8004D006u32 as HRESULT; +pub const XACT_E_HEURISTICDANGER: HRESULT = 0x8004D007u32 as HRESULT; +pub const XACT_E_ISOLATIONLEVEL: HRESULT = 0x8004D008u32 as HRESULT; +pub const XACT_E_NOASYNC: HRESULT = 0x8004D009u32 as HRESULT; +pub const XACT_E_NOENLIST: HRESULT = 0x8004D00Au32 as HRESULT; +pub const XACT_E_NOISORETAIN: HRESULT = 0x8004D00Bu32 as HRESULT; +pub const XACT_E_NORESOURCE: HRESULT = 0x8004D00Cu32 as HRESULT; +pub const XACT_E_NOTCURRENT: HRESULT = 0x8004D00Du32 as HRESULT; +pub const XACT_E_NOTRANSACTION: HRESULT = 0x8004D00Eu32 as HRESULT; +pub const XACT_E_NOTSUPPORTED: HRESULT = 0x8004D00Fu32 as HRESULT; +pub const XACT_E_UNKNOWNRMGRID: HRESULT = 0x8004D010u32 as HRESULT; +pub const XACT_E_WRONGSTATE: HRESULT = 0x8004D011u32 as HRESULT; +pub const XACT_E_WRONGUOW: HRESULT = 0x8004D012u32 as HRESULT; +pub const XACT_E_XTIONEXISTS: HRESULT = 0x8004D013u32 as HRESULT; +pub const XACT_E_NOIMPORTOBJECT: HRESULT = 0x8004D014u32 as HRESULT; +pub const XACT_E_INVALIDCOOKIE: HRESULT = 0x8004D015u32 as HRESULT; +pub const XACT_E_INDOUBT: HRESULT = 0x8004D016u32 as HRESULT; +pub const XACT_E_NOTIMEOUT: HRESULT = 0x8004D017u32 as HRESULT; +pub const XACT_E_ALREADYINPROGRESS: HRESULT = 0x8004D018u32 as HRESULT; +pub const XACT_E_ABORTED: HRESULT = 0x8004D019u32 as HRESULT; +pub const XACT_E_LOGFULL: HRESULT = 0x8004D01Au32 as HRESULT; +pub const XACT_E_TMNOTAVAILABLE: HRESULT = 0x8004D01Bu32 as HRESULT; +pub const XACT_E_CONNECTION_DOWN: HRESULT = 0x8004D01Cu32 as HRESULT; +pub const XACT_E_CONNECTION_DENIED: HRESULT = 0x8004D01Du32 as HRESULT; +pub const XACT_E_REENLISTTIMEOUT: HRESULT = 0x8004D01Eu32 as HRESULT; +pub const XACT_E_TIP_CONNECT_FAILED: HRESULT = 0x8004D01Fu32 as HRESULT; +pub const XACT_E_TIP_PROTOCOL_ERROR: HRESULT = 0x8004D020u32 as HRESULT; +pub const XACT_E_TIP_PULL_FAILED: HRESULT = 0x8004D021u32 as HRESULT; +pub const XACT_E_DEST_TMNOTAVAILABLE: HRESULT = 0x8004D022u32 as HRESULT; +pub const XACT_E_TIP_DISABLED: HRESULT = 0x8004D023u32 as HRESULT; +pub const XACT_E_NETWORK_TX_DISABLED: HRESULT = 0x8004D024u32 as HRESULT; +pub const XACT_E_PARTNER_NETWORK_TX_DISABLED: HRESULT = 0x8004D025u32 as HRESULT; +pub const XACT_E_XA_TX_DISABLED: HRESULT = 0x8004D026u32 as HRESULT; +pub const XACT_E_UNABLE_TO_READ_DTC_CONFIG: HRESULT = 0x8004D027u32 as HRESULT; +pub const XACT_E_UNABLE_TO_LOAD_DTC_PROXY: HRESULT = 0x8004D028u32 as HRESULT; +pub const XACT_E_ABORTING: HRESULT = 0x8004D029u32 as HRESULT; +pub const XACT_E_PUSH_COMM_FAILURE: HRESULT = 0x8004D02Au32 as HRESULT; +pub const XACT_E_PULL_COMM_FAILURE: HRESULT = 0x8004D02Bu32 as HRESULT; +pub const XACT_E_LU_TX_DISABLED: HRESULT = 0x8004D02Cu32 as HRESULT; +pub const XACT_E_CLERKNOTFOUND: HRESULT = 0x8004D080u32 as HRESULT; +pub const XACT_E_CLERKEXISTS: HRESULT = 0x8004D081u32 as HRESULT; +pub const XACT_E_RECOVERYINPROGRESS: HRESULT = 0x8004D082u32 as HRESULT; +pub const XACT_E_TRANSACTIONCLOSED: HRESULT = 0x8004D083u32 as HRESULT; +pub const XACT_E_INVALIDLSN: HRESULT = 0x8004D084u32 as HRESULT; +pub const XACT_E_REPLAYREQUEST: HRESULT = 0x8004D085u32 as HRESULT; +pub const XACT_S_ASYNC: HRESULT = 0x0004D000; +pub const XACT_S_DEFECT: HRESULT = 0x0004D001; +pub const XACT_S_READONLY: HRESULT = 0x0004D002; +pub const XACT_S_SOMENORETAIN: HRESULT = 0x0004D003; +pub const XACT_S_OKINFORM: HRESULT = 0x0004D004; +pub const XACT_S_MADECHANGESCONTENT: HRESULT = 0x0004D005; +pub const XACT_S_MADECHANGESINFORM: HRESULT = 0x0004D006; +pub const XACT_S_ALLNORETAIN: HRESULT = 0x0004D007; +pub const XACT_S_ABORTING: HRESULT = 0x0004D008; +pub const XACT_S_SINGLEPHASE: HRESULT = 0x0004D009; +pub const XACT_S_LOCALLY_OK: HRESULT = 0x0004D00A; +pub const XACT_S_LASTRESOURCEMANAGER: HRESULT = 0x0004D010; +pub const CONTEXT_E_FIRST: HRESULT = 0x8004E000u32 as HRESULT; +pub const CONTEXT_E_LAST: HRESULT = 0x8004E02Fu32 as HRESULT; +pub const CONTEXT_S_FIRST: HRESULT = 0x0004E000; +pub const CONTEXT_S_LAST: HRESULT = 0x0004E02F; +pub const CONTEXT_E_ABORTED: HRESULT = 0x8004E002u32 as HRESULT; +pub const CONTEXT_E_ABORTING: HRESULT = 0x8004E003u32 as HRESULT; +pub const CONTEXT_E_NOCONTEXT: HRESULT = 0x8004E004u32 as HRESULT; +pub const CONTEXT_E_WOULD_DEADLOCK: HRESULT = 0x8004E005u32 as HRESULT; +pub const CONTEXT_E_SYNCH_TIMEOUT: HRESULT = 0x8004E006u32 as HRESULT; +pub const CONTEXT_E_OLDREF: HRESULT = 0x8004E007u32 as HRESULT; +pub const CONTEXT_E_ROLENOTFOUND: HRESULT = 0x8004E00Cu32 as HRESULT; +pub const CONTEXT_E_TMNOTAVAILABLE: HRESULT = 0x8004E00Fu32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED: HRESULT = 0x8004E021u32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED_EVENTLOGGED: HRESULT = 0x8004E022u32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED_CATALOGERROR: HRESULT = 0x8004E023u32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED_TIMEOUT: HRESULT = 0x8004E024u32 as HRESULT; +pub const CO_E_INITIALIZATIONFAILED: HRESULT = 0x8004E025u32 as HRESULT; +pub const CONTEXT_E_NOJIT: HRESULT = 0x8004E026u32 as HRESULT; +pub const CONTEXT_E_NOTRANSACTION: HRESULT = 0x8004E027u32 as HRESULT; +pub const CO_E_THREADINGMODEL_CHANGED: HRESULT = 0x8004E028u32 as HRESULT; +pub const CO_E_NOIISINTRINSICS: HRESULT = 0x8004E029u32 as HRESULT; +pub const CO_E_NOCOOKIES: HRESULT = 0x8004E02Au32 as HRESULT; +pub const CO_E_DBERROR: HRESULT = 0x8004E02Bu32 as HRESULT; +pub const CO_E_NOTPOOLED: HRESULT = 0x8004E02Cu32 as HRESULT; +pub const CO_E_NOTCONSTRUCTED: HRESULT = 0x8004E02Du32 as HRESULT; +pub const CO_E_NOSYNCHRONIZATION: HRESULT = 0x8004E02Eu32 as HRESULT; +pub const CO_E_ISOLEVELMISMATCH: HRESULT = 0x8004E02Fu32 as HRESULT; +pub const CO_E_CALL_OUT_OF_TX_SCOPE_NOT_ALLOWED: HRESULT = 0x8004E030u32 as HRESULT; +pub const CO_E_EXIT_TRANSACTION_SCOPE_NOT_CALLED: HRESULT = 0x8004E031u32 as HRESULT; +pub const OLE_S_USEREG: HRESULT = 0x00040000; +pub const OLE_S_STATIC: HRESULT = 0x00040001; +pub const OLE_S_MAC_CLIPFORMAT: HRESULT = 0x00040002; +pub const DRAGDROP_S_DROP: HRESULT = 0x00040100; +pub const DRAGDROP_S_CANCEL: HRESULT = 0x00040101; +pub const DRAGDROP_S_USEDEFAULTCURSORS: HRESULT = 0x00040102; +pub const DATA_S_SAMEFORMATETC: HRESULT = 0x00040130; +pub const VIEW_S_ALREADY_FROZEN: HRESULT = 0x00040140; +pub const CACHE_S_FORMATETC_NOTSUPPORTED: HRESULT = 0x00040170; +pub const CACHE_S_SAMECACHE: HRESULT = 0x00040171; +pub const CACHE_S_SOMECACHES_NOTUPDATED: HRESULT = 0x00040172; +pub const OLEOBJ_S_INVALIDVERB: HRESULT = 0x00040180; +pub const OLEOBJ_S_CANNOT_DOVERB_NOW: HRESULT = 0x00040181; +pub const OLEOBJ_S_INVALIDHWND: HRESULT = 0x00040182; +pub const INPLACE_S_TRUNCATED: HRESULT = 0x000401A0; +pub const CONVERT10_S_NO_PRESENTATION: HRESULT = 0x000401C0; +pub const MK_S_REDUCED_TO_SELF: HRESULT = 0x000401E2; +pub const MK_S_ME: HRESULT = 0x000401E4; +pub const MK_S_HIM: HRESULT = 0x000401E5; +pub const MK_S_US: HRESULT = 0x000401E6; +pub const MK_S_MONIKERALREADYREGISTERED: HRESULT = 0x000401E7; +pub const SCHED_S_TASK_READY: HRESULT = 0x00041300; +pub const SCHED_S_TASK_RUNNING: HRESULT = 0x00041301; +pub const SCHED_S_TASK_DISABLED: HRESULT = 0x00041302; +pub const SCHED_S_TASK_HAS_NOT_RUN: HRESULT = 0x00041303; +pub const SCHED_S_TASK_NO_MORE_RUNS: HRESULT = 0x00041304; +pub const SCHED_S_TASK_NOT_SCHEDULED: HRESULT = 0x00041305; +pub const SCHED_S_TASK_TERMINATED: HRESULT = 0x00041306; +pub const SCHED_S_TASK_NO_VALID_TRIGGERS: HRESULT = 0x00041307; +pub const SCHED_S_EVENT_TRIGGER: HRESULT = 0x00041308; +pub const SCHED_E_TRIGGER_NOT_FOUND: HRESULT = 0x80041309u32 as HRESULT; +pub const SCHED_E_TASK_NOT_READY: HRESULT = 0x8004130Au32 as HRESULT; +pub const SCHED_E_TASK_NOT_RUNNING: HRESULT = 0x8004130Bu32 as HRESULT; +pub const SCHED_E_SERVICE_NOT_INSTALLED: HRESULT = 0x8004130Cu32 as HRESULT; +pub const SCHED_E_CANNOT_OPEN_TASK: HRESULT = 0x8004130Du32 as HRESULT; +pub const SCHED_E_INVALID_TASK: HRESULT = 0x8004130Eu32 as HRESULT; +pub const SCHED_E_ACCOUNT_INFORMATION_NOT_SET: HRESULT = 0x8004130Fu32 as HRESULT; +pub const SCHED_E_ACCOUNT_NAME_NOT_FOUND: HRESULT = 0x80041310u32 as HRESULT; +pub const SCHED_E_ACCOUNT_DBASE_CORRUPT: HRESULT = 0x80041311u32 as HRESULT; +pub const SCHED_E_NO_SECURITY_SERVICES: HRESULT = 0x80041312u32 as HRESULT; +pub const SCHED_E_UNKNOWN_OBJECT_VERSION: HRESULT = 0x80041313u32 as HRESULT; +pub const SCHED_E_UNSUPPORTED_ACCOUNT_OPTION: HRESULT = 0x80041314u32 as HRESULT; +pub const SCHED_E_SERVICE_NOT_RUNNING: HRESULT = 0x80041315u32 as HRESULT; +pub const SCHED_E_UNEXPECTEDNODE: HRESULT = 0x80041316u32 as HRESULT; +pub const SCHED_E_NAMESPACE: HRESULT = 0x80041317u32 as HRESULT; +pub const SCHED_E_INVALIDVALUE: HRESULT = 0x80041318u32 as HRESULT; +pub const SCHED_E_MISSINGNODE: HRESULT = 0x80041319u32 as HRESULT; +pub const SCHED_E_MALFORMEDXML: HRESULT = 0x8004131Au32 as HRESULT; +pub const SCHED_S_SOME_TRIGGERS_FAILED: HRESULT = 0x0004131B; +pub const SCHED_S_BATCH_LOGON_PROBLEM: HRESULT = 0x0004131C; +pub const SCHED_E_TOO_MANY_NODES: HRESULT = 0x8004131Du32 as HRESULT; +pub const SCHED_E_PAST_END_BOUNDARY: HRESULT = 0x8004131Eu32 as HRESULT; +pub const SCHED_E_ALREADY_RUNNING: HRESULT = 0x8004131Fu32 as HRESULT; +pub const SCHED_E_USER_NOT_LOGGED_ON: HRESULT = 0x80041320u32 as HRESULT; +pub const SCHED_E_INVALID_TASK_HASH: HRESULT = 0x80041321u32 as HRESULT; +pub const SCHED_E_SERVICE_NOT_AVAILABLE: HRESULT = 0x80041322u32 as HRESULT; +pub const SCHED_E_SERVICE_TOO_BUSY: HRESULT = 0x80041323u32 as HRESULT; +pub const SCHED_E_TASK_ATTEMPTED: HRESULT = 0x80041324u32 as HRESULT; +pub const SCHED_S_TASK_QUEUED: HRESULT = 0x00041325; +pub const SCHED_E_TASK_DISABLED: HRESULT = 0x80041326u32 as HRESULT; +pub const SCHED_E_TASK_NOT_V1_COMPAT: HRESULT = 0x80041327u32 as HRESULT; +pub const SCHED_E_START_ON_DEMAND: HRESULT = 0x80041328u32 as HRESULT; +pub const SCHED_E_TASK_NOT_UBPM_COMPAT: HRESULT = 0x80041329u32 as HRESULT; +pub const SCHED_E_DEPRECATED_FEATURE_USED: HRESULT = 0x80041330u32 as HRESULT; +pub const CO_E_CLASS_CREATE_FAILED: HRESULT = 0x80080001u32 as HRESULT; +pub const CO_E_SCM_ERROR: HRESULT = 0x80080002u32 as HRESULT; +pub const CO_E_SCM_RPC_FAILURE: HRESULT = 0x80080003u32 as HRESULT; +pub const CO_E_BAD_PATH: HRESULT = 0x80080004u32 as HRESULT; +pub const CO_E_SERVER_EXEC_FAILURE: HRESULT = 0x80080005u32 as HRESULT; +pub const CO_E_OBJSRV_RPC_FAILURE: HRESULT = 0x80080006u32 as HRESULT; +pub const MK_E_NO_NORMALIZED: HRESULT = 0x80080007u32 as HRESULT; +pub const CO_E_SERVER_STOPPING: HRESULT = 0x80080008u32 as HRESULT; +pub const MEM_E_INVALID_ROOT: HRESULT = 0x80080009u32 as HRESULT; +pub const MEM_E_INVALID_LINK: HRESULT = 0x80080010u32 as HRESULT; +pub const MEM_E_INVALID_SIZE: HRESULT = 0x80080011u32 as HRESULT; +pub const CO_S_NOTALLINTERFACES: HRESULT = 0x00080012; +pub const CO_S_MACHINENAMENOTFOUND: HRESULT = 0x00080013; +pub const CO_E_MISSING_DISPLAYNAME: HRESULT = 0x80080015u32 as HRESULT; +pub const CO_E_RUNAS_VALUE_MUST_BE_AAA: HRESULT = 0x80080016u32 as HRESULT; +pub const CO_E_ELEVATION_DISABLED: HRESULT = 0x80080017u32 as HRESULT; +pub const APPX_E_PACKAGING_INTERNAL: HRESULT = 0x80080200u32 as HRESULT; +pub const APPX_E_INTERLEAVING_NOT_ALLOWED: HRESULT = 0x80080201u32 as HRESULT; +pub const APPX_E_RELATIONSHIPS_NOT_ALLOWED: HRESULT = 0x80080202u32 as HRESULT; +pub const APPX_E_MISSING_REQUIRED_FILE: HRESULT = 0x80080203u32 as HRESULT; +pub const APPX_E_INVALID_MANIFEST: HRESULT = 0x80080204u32 as HRESULT; +pub const APPX_E_INVALID_BLOCKMAP: HRESULT = 0x80080205u32 as HRESULT; +pub const APPX_E_CORRUPT_CONTENT: HRESULT = 0x80080206u32 as HRESULT; +pub const APPX_E_BLOCK_HASH_INVALID: HRESULT = 0x80080207u32 as HRESULT; +pub const APPX_E_REQUESTED_RANGE_TOO_LARGE: HRESULT = 0x80080208u32 as HRESULT; +pub const APPX_E_INVALID_SIP_CLIENT_DATA: HRESULT = 0x80080209u32 as HRESULT; +pub const BT_E_SPURIOUS_ACTIVATION: HRESULT = 0x80080300u32 as HRESULT; +pub const DISP_E_UNKNOWNINTERFACE: HRESULT = 0x80020001u32 as HRESULT; +pub const DISP_E_MEMBERNOTFOUND: HRESULT = 0x80020003u32 as HRESULT; +pub const DISP_E_PARAMNOTFOUND: HRESULT = 0x80020004u32 as HRESULT; +pub const DISP_E_TYPEMISMATCH: HRESULT = 0x80020005u32 as HRESULT; +pub const DISP_E_UNKNOWNNAME: HRESULT = 0x80020006u32 as HRESULT; +pub const DISP_E_NONAMEDARGS: HRESULT = 0x80020007u32 as HRESULT; +pub const DISP_E_BADVARTYPE: HRESULT = 0x80020008u32 as HRESULT; +pub const DISP_E_EXCEPTION: HRESULT = 0x80020009u32 as HRESULT; +pub const DISP_E_OVERFLOW: HRESULT = 0x8002000Au32 as HRESULT; +pub const DISP_E_BADINDEX: HRESULT = 0x8002000Bu32 as HRESULT; +pub const DISP_E_UNKNOWNLCID: HRESULT = 0x8002000Cu32 as HRESULT; +pub const DISP_E_ARRAYISLOCKED: HRESULT = 0x8002000Du32 as HRESULT; +pub const DISP_E_BADPARAMCOUNT: HRESULT = 0x8002000Eu32 as HRESULT; +pub const DISP_E_PARAMNOTOPTIONAL: HRESULT = 0x8002000Fu32 as HRESULT; +pub const DISP_E_BADCALLEE: HRESULT = 0x80020010u32 as HRESULT; +pub const DISP_E_NOTACOLLECTION: HRESULT = 0x80020011u32 as HRESULT; +pub const DISP_E_DIVBYZERO: HRESULT = 0x80020012u32 as HRESULT; +pub const DISP_E_BUFFERTOOSMALL: HRESULT = 0x80020013u32 as HRESULT; +pub const TYPE_E_BUFFERTOOSMALL: HRESULT = 0x80028016u32 as HRESULT; +pub const TYPE_E_FIELDNOTFOUND: HRESULT = 0x80028017u32 as HRESULT; +pub const TYPE_E_INVDATAREAD: HRESULT = 0x80028018u32 as HRESULT; +pub const TYPE_E_UNSUPFORMAT: HRESULT = 0x80028019u32 as HRESULT; +pub const TYPE_E_REGISTRYACCESS: HRESULT = 0x8002801Cu32 as HRESULT; +pub const TYPE_E_LIBNOTREGISTERED: HRESULT = 0x8002801Du32 as HRESULT; +pub const TYPE_E_UNDEFINEDTYPE: HRESULT = 0x80028027u32 as HRESULT; +pub const TYPE_E_QUALIFIEDNAMEDISALLOWED: HRESULT = 0x80028028u32 as HRESULT; +pub const TYPE_E_INVALIDSTATE: HRESULT = 0x80028029u32 as HRESULT; +pub const TYPE_E_WRONGTYPEKIND: HRESULT = 0x8002802Au32 as HRESULT; +pub const TYPE_E_ELEMENTNOTFOUND: HRESULT = 0x8002802Bu32 as HRESULT; +pub const TYPE_E_AMBIGUOUSNAME: HRESULT = 0x8002802Cu32 as HRESULT; +pub const TYPE_E_NAMECONFLICT: HRESULT = 0x8002802Du32 as HRESULT; +pub const TYPE_E_UNKNOWNLCID: HRESULT = 0x8002802Eu32 as HRESULT; +pub const TYPE_E_DLLFUNCTIONNOTFOUND: HRESULT = 0x8002802Fu32 as HRESULT; +pub const TYPE_E_BADMODULEKIND: HRESULT = 0x800288BDu32 as HRESULT; +pub const TYPE_E_SIZETOOBIG: HRESULT = 0x800288C5u32 as HRESULT; +pub const TYPE_E_DUPLICATEID: HRESULT = 0x800288C6u32 as HRESULT; +pub const TYPE_E_INVALIDID: HRESULT = 0x800288CFu32 as HRESULT; +pub const TYPE_E_TYPEMISMATCH: HRESULT = 0x80028CA0u32 as HRESULT; +pub const TYPE_E_OUTOFBOUNDS: HRESULT = 0x80028CA1u32 as HRESULT; +pub const TYPE_E_IOERROR: HRESULT = 0x80028CA2u32 as HRESULT; +pub const TYPE_E_CANTCREATETMPFILE: HRESULT = 0x80028CA3u32 as HRESULT; +pub const TYPE_E_CANTLOADLIBRARY: HRESULT = 0x80029C4Au32 as HRESULT; +pub const TYPE_E_INCONSISTENTPROPFUNCS: HRESULT = 0x80029C83u32 as HRESULT; +pub const TYPE_E_CIRCULARTYPE: HRESULT = 0x80029C84u32 as HRESULT; +pub const STG_E_INVALIDFUNCTION: HRESULT = 0x80030001u32 as HRESULT; +pub const STG_E_FILENOTFOUND: HRESULT = 0x80030002u32 as HRESULT; +pub const STG_E_PATHNOTFOUND: HRESULT = 0x80030003u32 as HRESULT; +pub const STG_E_TOOMANYOPENFILES: HRESULT = 0x80030004u32 as HRESULT; +pub const STG_E_ACCESSDENIED: HRESULT = 0x80030005u32 as HRESULT; +pub const STG_E_INVALIDHANDLE: HRESULT = 0x80030006u32 as HRESULT; +pub const STG_E_INSUFFICIENTMEMORY: HRESULT = 0x80030008u32 as HRESULT; +pub const STG_E_INVALIDPOINTER: HRESULT = 0x80030009u32 as HRESULT; +pub const STG_E_NOMOREFILES: HRESULT = 0x80030012u32 as HRESULT; +pub const STG_E_DISKISWRITEPROTECTED: HRESULT = 0x80030013u32 as HRESULT; +pub const STG_E_SEEKERROR: HRESULT = 0x80030019u32 as HRESULT; +pub const STG_E_WRITEFAULT: HRESULT = 0x8003001Du32 as HRESULT; +pub const STG_E_READFAULT: HRESULT = 0x8003001Eu32 as HRESULT; +pub const STG_E_SHAREVIOLATION: HRESULT = 0x80030020u32 as HRESULT; +pub const STG_E_LOCKVIOLATION: HRESULT = 0x80030021u32 as HRESULT; +pub const STG_E_FILEALREADYEXISTS: HRESULT = 0x80030050u32 as HRESULT; +pub const STG_E_INVALIDPARAMETER: HRESULT = 0x80030057u32 as HRESULT; +pub const STG_E_MEDIUMFULL: HRESULT = 0x80030070u32 as HRESULT; +pub const STG_E_PROPSETMISMATCHED: HRESULT = 0x800300F0u32 as HRESULT; +pub const STG_E_ABNORMALAPIEXIT: HRESULT = 0x800300FAu32 as HRESULT; +pub const STG_E_INVALIDHEADER: HRESULT = 0x800300FBu32 as HRESULT; +pub const STG_E_INVALIDNAME: HRESULT = 0x800300FCu32 as HRESULT; +pub const STG_E_UNKNOWN: HRESULT = 0x800300FDu32 as HRESULT; +pub const STG_E_UNIMPLEMENTEDFUNCTION: HRESULT = 0x800300FEu32 as HRESULT; +pub const STG_E_INVALIDFLAG: HRESULT = 0x800300FFu32 as HRESULT; +pub const STG_E_INUSE: HRESULT = 0x80030100u32 as HRESULT; +pub const STG_E_NOTCURRENT: HRESULT = 0x80030101u32 as HRESULT; +pub const STG_E_REVERTED: HRESULT = 0x80030102u32 as HRESULT; +pub const STG_E_CANTSAVE: HRESULT = 0x80030103u32 as HRESULT; +pub const STG_E_OLDFORMAT: HRESULT = 0x80030104u32 as HRESULT; +pub const STG_E_OLDDLL: HRESULT = 0x80030105u32 as HRESULT; +pub const STG_E_SHAREREQUIRED: HRESULT = 0x80030106u32 as HRESULT; +pub const STG_E_NOTFILEBASEDSTORAGE: HRESULT = 0x80030107u32 as HRESULT; +pub const STG_E_EXTANTMARSHALLINGS: HRESULT = 0x80030108u32 as HRESULT; +pub const STG_E_DOCFILECORRUPT: HRESULT = 0x80030109u32 as HRESULT; +pub const STG_E_BADBASEADDRESS: HRESULT = 0x80030110u32 as HRESULT; +pub const STG_E_DOCFILETOOLARGE: HRESULT = 0x80030111u32 as HRESULT; +pub const STG_E_NOTSIMPLEFORMAT: HRESULT = 0x80030112u32 as HRESULT; +pub const STG_E_INCOMPLETE: HRESULT = 0x80030201u32 as HRESULT; +pub const STG_E_TERMINATED: HRESULT = 0x80030202u32 as HRESULT; +pub const STG_S_CONVERTED: HRESULT = 0x00030200; +pub const STG_S_BLOCK: HRESULT = 0x00030201; +pub const STG_S_RETRYNOW: HRESULT = 0x00030202; +pub const STG_S_MONITORING: HRESULT = 0x00030203; +pub const STG_S_MULTIPLEOPENS: HRESULT = 0x00030204; +pub const STG_S_CONSOLIDATIONFAILED: HRESULT = 0x00030205; +pub const STG_S_CANNOTCONSOLIDATE: HRESULT = 0x00030206; +pub const STG_E_STATUS_COPY_PROTECTION_FAILURE: HRESULT = 0x80030305u32 as HRESULT; +pub const STG_E_CSS_AUTHENTICATION_FAILURE: HRESULT = 0x80030306u32 as HRESULT; +pub const STG_E_CSS_KEY_NOT_PRESENT: HRESULT = 0x80030307u32 as HRESULT; +pub const STG_E_CSS_KEY_NOT_ESTABLISHED: HRESULT = 0x80030308u32 as HRESULT; +pub const STG_E_CSS_SCRAMBLED_SECTOR: HRESULT = 0x80030309u32 as HRESULT; +pub const STG_E_CSS_REGION_MISMATCH: HRESULT = 0x8003030Au32 as HRESULT; +pub const STG_E_RESETS_EXHAUSTED: HRESULT = 0x8003030Bu32 as HRESULT; +pub const RPC_E_CALL_REJECTED: HRESULT = 0x80010001u32 as HRESULT; +pub const RPC_E_CALL_CANCELED: HRESULT = 0x80010002u32 as HRESULT; +pub const RPC_E_CANTPOST_INSENDCALL: HRESULT = 0x80010003u32 as HRESULT; +pub const RPC_E_CANTCALLOUT_INASYNCCALL: HRESULT = 0x80010004u32 as HRESULT; +pub const RPC_E_CANTCALLOUT_INEXTERNALCALL: HRESULT = 0x80010005u32 as HRESULT; +pub const RPC_E_CONNECTION_TERMINATED: HRESULT = 0x80010006u32 as HRESULT; +pub const RPC_E_SERVER_DIED: HRESULT = 0x80010007u32 as HRESULT; +pub const RPC_E_CLIENT_DIED: HRESULT = 0x80010008u32 as HRESULT; +pub const RPC_E_INVALID_DATAPACKET: HRESULT = 0x80010009u32 as HRESULT; +pub const RPC_E_CANTTRANSMIT_CALL: HRESULT = 0x8001000Au32 as HRESULT; +pub const RPC_E_CLIENT_CANTMARSHAL_DATA: HRESULT = 0x8001000Bu32 as HRESULT; +pub const RPC_E_CLIENT_CANTUNMARSHAL_DATA: HRESULT = 0x8001000Cu32 as HRESULT; +pub const RPC_E_SERVER_CANTMARSHAL_DATA: HRESULT = 0x8001000Du32 as HRESULT; +pub const RPC_E_SERVER_CANTUNMARSHAL_DATA: HRESULT = 0x8001000Eu32 as HRESULT; +pub const RPC_E_INVALID_DATA: HRESULT = 0x8001000Fu32 as HRESULT; +pub const RPC_E_INVALID_PARAMETER: HRESULT = 0x80010010u32 as HRESULT; +pub const RPC_E_CANTCALLOUT_AGAIN: HRESULT = 0x80010011u32 as HRESULT; +pub const RPC_E_SERVER_DIED_DNE: HRESULT = 0x80010012u32 as HRESULT; +pub const RPC_E_SYS_CALL_FAILED: HRESULT = 0x80010100u32 as HRESULT; +pub const RPC_E_OUT_OF_RESOURCES: HRESULT = 0x80010101u32 as HRESULT; +pub const RPC_E_ATTEMPTED_MULTITHREAD: HRESULT = 0x80010102u32 as HRESULT; +pub const RPC_E_NOT_REGISTERED: HRESULT = 0x80010103u32 as HRESULT; +pub const RPC_E_FAULT: HRESULT = 0x80010104u32 as HRESULT; +pub const RPC_E_SERVERFAULT: HRESULT = 0x80010105u32 as HRESULT; +pub const RPC_E_CHANGED_MODE: HRESULT = 0x80010106u32 as HRESULT; +pub const RPC_E_INVALIDMETHOD: HRESULT = 0x80010107u32 as HRESULT; +pub const RPC_E_DISCONNECTED: HRESULT = 0x80010108u32 as HRESULT; +pub const RPC_E_RETRY: HRESULT = 0x80010109u32 as HRESULT; +pub const RPC_E_SERVERCALL_RETRYLATER: HRESULT = 0x8001010Au32 as HRESULT; +pub const RPC_E_SERVERCALL_REJECTED: HRESULT = 0x8001010Bu32 as HRESULT; +pub const RPC_E_INVALID_CALLDATA: HRESULT = 0x8001010Cu32 as HRESULT; +pub const RPC_E_CANTCALLOUT_ININPUTSYNCCALL: HRESULT = 0x8001010Du32 as HRESULT; +pub const RPC_E_WRONG_THREAD: HRESULT = 0x8001010Eu32 as HRESULT; +pub const RPC_E_THREAD_NOT_INIT: HRESULT = 0x8001010Fu32 as HRESULT; +pub const RPC_E_VERSION_MISMATCH: HRESULT = 0x80010110u32 as HRESULT; +pub const RPC_E_INVALID_HEADER: HRESULT = 0x80010111u32 as HRESULT; +pub const RPC_E_INVALID_EXTENSION: HRESULT = 0x80010112u32 as HRESULT; +pub const RPC_E_INVALID_IPID: HRESULT = 0x80010113u32 as HRESULT; +pub const RPC_E_INVALID_OBJECT: HRESULT = 0x80010114u32 as HRESULT; +pub const RPC_S_CALLPENDING: HRESULT = 0x80010115u32 as HRESULT; +pub const RPC_S_WAITONTIMER: HRESULT = 0x80010116u32 as HRESULT; +pub const RPC_E_CALL_COMPLETE: HRESULT = 0x80010117u32 as HRESULT; +pub const RPC_E_UNSECURE_CALL: HRESULT = 0x80010118u32 as HRESULT; +pub const RPC_E_TOO_LATE: HRESULT = 0x80010119u32 as HRESULT; +pub const RPC_E_NO_GOOD_SECURITY_PACKAGES: HRESULT = 0x8001011Au32 as HRESULT; +pub const RPC_E_ACCESS_DENIED: HRESULT = 0x8001011Bu32 as HRESULT; +pub const RPC_E_REMOTE_DISABLED: HRESULT = 0x8001011Cu32 as HRESULT; +pub const RPC_E_INVALID_OBJREF: HRESULT = 0x8001011Du32 as HRESULT; +pub const RPC_E_NO_CONTEXT: HRESULT = 0x8001011Eu32 as HRESULT; +pub const RPC_E_TIMEOUT: HRESULT = 0x8001011Fu32 as HRESULT; +pub const RPC_E_NO_SYNC: HRESULT = 0x80010120u32 as HRESULT; +pub const RPC_E_FULLSIC_REQUIRED: HRESULT = 0x80010121u32 as HRESULT; +pub const RPC_E_INVALID_STD_NAME: HRESULT = 0x80010122u32 as HRESULT; +pub const CO_E_FAILEDTOIMPERSONATE: HRESULT = 0x80010123u32 as HRESULT; +pub const CO_E_FAILEDTOGETSECCTX: HRESULT = 0x80010124u32 as HRESULT; +pub const CO_E_FAILEDTOOPENTHREADTOKEN: HRESULT = 0x80010125u32 as HRESULT; +pub const CO_E_FAILEDTOGETTOKENINFO: HRESULT = 0x80010126u32 as HRESULT; +pub const CO_E_TRUSTEEDOESNTMATCHCLIENT: HRESULT = 0x80010127u32 as HRESULT; +pub const CO_E_FAILEDTOQUERYCLIENTBLANKET: HRESULT = 0x80010128u32 as HRESULT; +pub const CO_E_FAILEDTOSETDACL: HRESULT = 0x80010129u32 as HRESULT; +pub const CO_E_ACCESSCHECKFAILED: HRESULT = 0x8001012Au32 as HRESULT; +pub const CO_E_NETACCESSAPIFAILED: HRESULT = 0x8001012Bu32 as HRESULT; +pub const CO_E_WRONGTRUSTEENAMESYNTAX: HRESULT = 0x8001012Cu32 as HRESULT; +pub const CO_E_INVALIDSID: HRESULT = 0x8001012Du32 as HRESULT; +pub const CO_E_CONVERSIONFAILED: HRESULT = 0x8001012Eu32 as HRESULT; +pub const CO_E_NOMATCHINGSIDFOUND: HRESULT = 0x8001012Fu32 as HRESULT; +pub const CO_E_LOOKUPACCSIDFAILED: HRESULT = 0x80010130u32 as HRESULT; +pub const CO_E_NOMATCHINGNAMEFOUND: HRESULT = 0x80010131u32 as HRESULT; +pub const CO_E_LOOKUPACCNAMEFAILED: HRESULT = 0x80010132u32 as HRESULT; +pub const CO_E_SETSERLHNDLFAILED: HRESULT = 0x80010133u32 as HRESULT; +pub const CO_E_FAILEDTOGETWINDIR: HRESULT = 0x80010134u32 as HRESULT; +pub const CO_E_PATHTOOLONG: HRESULT = 0x80010135u32 as HRESULT; +pub const CO_E_FAILEDTOGENUUID: HRESULT = 0x80010136u32 as HRESULT; +pub const CO_E_FAILEDTOCREATEFILE: HRESULT = 0x80010137u32 as HRESULT; +pub const CO_E_FAILEDTOCLOSEHANDLE: HRESULT = 0x80010138u32 as HRESULT; +pub const CO_E_EXCEEDSYSACLLIMIT: HRESULT = 0x80010139u32 as HRESULT; +pub const CO_E_ACESINWRONGORDER: HRESULT = 0x8001013Au32 as HRESULT; +pub const CO_E_INCOMPATIBLESTREAMVERSION: HRESULT = 0x8001013Bu32 as HRESULT; +pub const CO_E_FAILEDTOOPENPROCESSTOKEN: HRESULT = 0x8001013Cu32 as HRESULT; +pub const CO_E_DECODEFAILED: HRESULT = 0x8001013Du32 as HRESULT; +pub const CO_E_ACNOTINITIALIZED: HRESULT = 0x8001013Fu32 as HRESULT; +pub const CO_E_CANCEL_DISABLED: HRESULT = 0x80010140u32 as HRESULT; +pub const RPC_E_UNEXPECTED: HRESULT = 0x8001FFFFu32 as HRESULT; +pub const ERROR_AUDITING_DISABLED: HRESULT = 0xC0090001u32 as HRESULT; +pub const ERROR_ALL_SIDS_FILTERED: HRESULT = 0xC0090002u32 as HRESULT; +pub const ERROR_BIZRULES_NOT_ENABLED: HRESULT = 0xC0090003u32 as HRESULT; +pub const NTE_BAD_UID: HRESULT = 0x80090001u32 as HRESULT; +pub const NTE_BAD_HASH: HRESULT = 0x80090002u32 as HRESULT; +pub const NTE_BAD_KEY: HRESULT = 0x80090003u32 as HRESULT; +pub const NTE_BAD_LEN: HRESULT = 0x80090004u32 as HRESULT; +pub const NTE_BAD_DATA: HRESULT = 0x80090005u32 as HRESULT; +pub const NTE_BAD_SIGNATURE: HRESULT = 0x80090006u32 as HRESULT; +pub const NTE_BAD_VER: HRESULT = 0x80090007u32 as HRESULT; +pub const NTE_BAD_ALGID: HRESULT = 0x80090008u32 as HRESULT; +pub const NTE_BAD_FLAGS: HRESULT = 0x80090009u32 as HRESULT; +pub const NTE_BAD_TYPE: HRESULT = 0x8009000Au32 as HRESULT; +pub const NTE_BAD_KEY_STATE: HRESULT = 0x8009000Bu32 as HRESULT; +pub const NTE_BAD_HASH_STATE: HRESULT = 0x8009000Cu32 as HRESULT; +pub const NTE_NO_KEY: HRESULT = 0x8009000Du32 as HRESULT; +pub const NTE_NO_MEMORY: HRESULT = 0x8009000Eu32 as HRESULT; +pub const NTE_EXISTS: HRESULT = 0x8009000Fu32 as HRESULT; +pub const NTE_PERM: HRESULT = 0x80090010u32 as HRESULT; +pub const NTE_NOT_FOUND: HRESULT = 0x80090011u32 as HRESULT; +pub const NTE_DOUBLE_ENCRYPT: HRESULT = 0x80090012u32 as HRESULT; +pub const NTE_BAD_PROVIDER: HRESULT = 0x80090013u32 as HRESULT; +pub const NTE_BAD_PROV_TYPE: HRESULT = 0x80090014u32 as HRESULT; +pub const NTE_BAD_PUBLIC_KEY: HRESULT = 0x80090015u32 as HRESULT; +pub const NTE_BAD_KEYSET: HRESULT = 0x80090016u32 as HRESULT; +pub const NTE_PROV_TYPE_NOT_DEF: HRESULT = 0x80090017u32 as HRESULT; +pub const NTE_PROV_TYPE_ENTRY_BAD: HRESULT = 0x80090018u32 as HRESULT; +pub const NTE_KEYSET_NOT_DEF: HRESULT = 0x80090019u32 as HRESULT; +pub const NTE_KEYSET_ENTRY_BAD: HRESULT = 0x8009001Au32 as HRESULT; +pub const NTE_PROV_TYPE_NO_MATCH: HRESULT = 0x8009001Bu32 as HRESULT; +pub const NTE_SIGNATURE_FILE_BAD: HRESULT = 0x8009001Cu32 as HRESULT; +pub const NTE_PROVIDER_DLL_FAIL: HRESULT = 0x8009001Du32 as HRESULT; +pub const NTE_PROV_DLL_NOT_FOUND: HRESULT = 0x8009001Eu32 as HRESULT; +pub const NTE_BAD_KEYSET_PARAM: HRESULT = 0x8009001Fu32 as HRESULT; +pub const NTE_FAIL: HRESULT = 0x80090020u32 as HRESULT; +pub const NTE_SYS_ERR: HRESULT = 0x80090021u32 as HRESULT; +pub const NTE_SILENT_CONTEXT: HRESULT = 0x80090022u32 as HRESULT; +pub const NTE_TOKEN_KEYSET_STORAGE_FULL: HRESULT = 0x80090023u32 as HRESULT; +pub const NTE_TEMPORARY_PROFILE: HRESULT = 0x80090024u32 as HRESULT; +pub const NTE_FIXEDPARAMETER: HRESULT = 0x80090025u32 as HRESULT; +pub const NTE_INVALID_HANDLE: HRESULT = 0x80090026u32 as HRESULT; +pub const NTE_INVALID_PARAMETER: HRESULT = 0x80090027u32 as HRESULT; +pub const NTE_BUFFER_TOO_SMALL: HRESULT = 0x80090028u32 as HRESULT; +pub const NTE_NOT_SUPPORTED: HRESULT = 0x80090029u32 as HRESULT; +pub const NTE_NO_MORE_ITEMS: HRESULT = 0x8009002Au32 as HRESULT; +pub const NTE_BUFFERS_OVERLAP: HRESULT = 0x8009002Bu32 as HRESULT; +pub const NTE_DECRYPTION_FAILURE: HRESULT = 0x8009002Cu32 as HRESULT; +pub const NTE_INTERNAL_ERROR: HRESULT = 0x8009002Du32 as HRESULT; +pub const NTE_UI_REQUIRED: HRESULT = 0x8009002Eu32 as HRESULT; +pub const NTE_HMAC_NOT_SUPPORTED: HRESULT = 0x8009002Fu32 as HRESULT; +pub const NTE_DEVICE_NOT_READY: HRESULT = 0x80090030u32 as HRESULT; +pub const NTE_AUTHENTICATION_IGNORED: HRESULT = 0x80090031u32 as HRESULT; +pub const NTE_VALIDATION_FAILED: HRESULT = 0x80090032u32 as HRESULT; +pub const NTE_INCORRECT_PASSWORD: HRESULT = 0x80090033u32 as HRESULT; +pub const NTE_ENCRYPTION_FAILURE: HRESULT = 0x80090034u32 as HRESULT; +pub const NTE_DEVICE_NOT_FOUND: HRESULT = 0x80090035u32 as HRESULT; +pub const SEC_E_INSUFFICIENT_MEMORY: HRESULT = 0x80090300u32 as HRESULT; +pub const SEC_E_INVALID_HANDLE: HRESULT = 0x80090301u32 as HRESULT; +pub const SEC_E_UNSUPPORTED_FUNCTION: HRESULT = 0x80090302u32 as HRESULT; +pub const SEC_E_TARGET_UNKNOWN: HRESULT = 0x80090303u32 as HRESULT; +pub const SEC_E_INTERNAL_ERROR: HRESULT = 0x80090304u32 as HRESULT; +pub const SEC_E_SECPKG_NOT_FOUND: HRESULT = 0x80090305u32 as HRESULT; +pub const SEC_E_NOT_OWNER: HRESULT = 0x80090306u32 as HRESULT; +pub const SEC_E_CANNOT_INSTALL: HRESULT = 0x80090307u32 as HRESULT; +pub const SEC_E_INVALID_TOKEN: HRESULT = 0x80090308u32 as HRESULT; +pub const SEC_E_CANNOT_PACK: HRESULT = 0x80090309u32 as HRESULT; +pub const SEC_E_QOP_NOT_SUPPORTED: HRESULT = 0x8009030Au32 as HRESULT; +pub const SEC_E_NO_IMPERSONATION: HRESULT = 0x8009030Bu32 as HRESULT; +pub const SEC_E_LOGON_DENIED: HRESULT = 0x8009030Cu32 as HRESULT; +pub const SEC_E_UNKNOWN_CREDENTIALS: HRESULT = 0x8009030Du32 as HRESULT; +pub const SEC_E_NO_CREDENTIALS: HRESULT = 0x8009030Eu32 as HRESULT; +pub const SEC_E_MESSAGE_ALTERED: HRESULT = 0x8009030Fu32 as HRESULT; +pub const SEC_E_OUT_OF_SEQUENCE: HRESULT = 0x80090310u32 as HRESULT; +pub const SEC_E_NO_AUTHENTICATING_AUTHORITY: HRESULT = 0x80090311u32 as HRESULT; +pub const SEC_I_CONTINUE_NEEDED: HRESULT = 0x00090312; +pub const SEC_I_COMPLETE_NEEDED: HRESULT = 0x00090313; +pub const SEC_I_COMPLETE_AND_CONTINUE: HRESULT = 0x00090314; +pub const SEC_I_LOCAL_LOGON: HRESULT = 0x00090315; +pub const SEC_E_BAD_PKGID: HRESULT = 0x80090316u32 as HRESULT; +pub const SEC_E_CONTEXT_EXPIRED: HRESULT = 0x80090317u32 as HRESULT; +pub const SEC_I_CONTEXT_EXPIRED: HRESULT = 0x00090317; +pub const SEC_E_INCOMPLETE_MESSAGE: HRESULT = 0x80090318u32 as HRESULT; +pub const SEC_E_INCOMPLETE_CREDENTIALS: HRESULT = 0x80090320u32 as HRESULT; +pub const SEC_E_BUFFER_TOO_SMALL: HRESULT = 0x80090321u32 as HRESULT; +pub const SEC_I_INCOMPLETE_CREDENTIALS: HRESULT = 0x00090320; +pub const SEC_I_RENEGOTIATE: HRESULT = 0x00090321; +pub const SEC_E_WRONG_PRINCIPAL: HRESULT = 0x80090322u32 as HRESULT; +pub const SEC_I_NO_LSA_CONTEXT: HRESULT = 0x00090323; +pub const SEC_E_TIME_SKEW: HRESULT = 0x80090324u32 as HRESULT; +pub const SEC_E_UNTRUSTED_ROOT: HRESULT = 0x80090325u32 as HRESULT; +pub const SEC_E_ILLEGAL_MESSAGE: HRESULT = 0x80090326u32 as HRESULT; +pub const SEC_E_CERT_UNKNOWN: HRESULT = 0x80090327u32 as HRESULT; +pub const SEC_E_CERT_EXPIRED: HRESULT = 0x80090328u32 as HRESULT; +pub const SEC_E_ENCRYPT_FAILURE: HRESULT = 0x80090329u32 as HRESULT; +pub const SEC_E_DECRYPT_FAILURE: HRESULT = 0x80090330u32 as HRESULT; +pub const SEC_E_ALGORITHM_MISMATCH: HRESULT = 0x80090331u32 as HRESULT; +pub const SEC_E_SECURITY_QOS_FAILED: HRESULT = 0x80090332u32 as HRESULT; +pub const SEC_E_UNFINISHED_CONTEXT_DELETED: HRESULT = 0x80090333u32 as HRESULT; +pub const SEC_E_NO_TGT_REPLY: HRESULT = 0x80090334u32 as HRESULT; +pub const SEC_E_NO_IP_ADDRESSES: HRESULT = 0x80090335u32 as HRESULT; +pub const SEC_E_WRONG_CREDENTIAL_HANDLE: HRESULT = 0x80090336u32 as HRESULT; +pub const SEC_E_CRYPTO_SYSTEM_INVALID: HRESULT = 0x80090337u32 as HRESULT; +pub const SEC_E_MAX_REFERRALS_EXCEEDED: HRESULT = 0x80090338u32 as HRESULT; +pub const SEC_E_MUST_BE_KDC: HRESULT = 0x80090339u32 as HRESULT; +pub const SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: HRESULT = 0x8009033Au32 as HRESULT; +pub const SEC_E_TOO_MANY_PRINCIPALS: HRESULT = 0x8009033Bu32 as HRESULT; +pub const SEC_E_NO_PA_DATA: HRESULT = 0x8009033Cu32 as HRESULT; +pub const SEC_E_PKINIT_NAME_MISMATCH: HRESULT = 0x8009033Du32 as HRESULT; +pub const SEC_E_SMARTCARD_LOGON_REQUIRED: HRESULT = 0x8009033Eu32 as HRESULT; +pub const SEC_E_SHUTDOWN_IN_PROGRESS: HRESULT = 0x8009033Fu32 as HRESULT; +pub const SEC_E_KDC_INVALID_REQUEST: HRESULT = 0x80090340u32 as HRESULT; +pub const SEC_E_KDC_UNABLE_TO_REFER: HRESULT = 0x80090341u32 as HRESULT; +pub const SEC_E_KDC_UNKNOWN_ETYPE: HRESULT = 0x80090342u32 as HRESULT; +pub const SEC_E_UNSUPPORTED_PREAUTH: HRESULT = 0x80090343u32 as HRESULT; +pub const SEC_E_DELEGATION_REQUIRED: HRESULT = 0x80090345u32 as HRESULT; +pub const SEC_E_BAD_BINDINGS: HRESULT = 0x80090346u32 as HRESULT; +pub const SEC_E_MULTIPLE_ACCOUNTS: HRESULT = 0x80090347u32 as HRESULT; +pub const SEC_E_NO_KERB_KEY: HRESULT = 0x80090348u32 as HRESULT; +pub const SEC_E_CERT_WRONG_USAGE: HRESULT = 0x80090349u32 as HRESULT; +pub const SEC_E_DOWNGRADE_DETECTED: HRESULT = 0x80090350u32 as HRESULT; +pub const SEC_E_SMARTCARD_CERT_REVOKED: HRESULT = 0x80090351u32 as HRESULT; +pub const SEC_E_ISSUING_CA_UNTRUSTED: HRESULT = 0x80090352u32 as HRESULT; +pub const SEC_E_REVOCATION_OFFLINE_C: HRESULT = 0x80090353u32 as HRESULT; +pub const SEC_E_PKINIT_CLIENT_FAILURE: HRESULT = 0x80090354u32 as HRESULT; +pub const SEC_E_SMARTCARD_CERT_EXPIRED: HRESULT = 0x80090355u32 as HRESULT; +pub const SEC_E_NO_S4U_PROT_SUPPORT: HRESULT = 0x80090356u32 as HRESULT; +pub const SEC_E_CROSSREALM_DELEGATION_FAILURE: HRESULT = 0x80090357u32 as HRESULT; +pub const SEC_E_REVOCATION_OFFLINE_KDC: HRESULT = 0x80090358u32 as HRESULT; +pub const SEC_E_ISSUING_CA_UNTRUSTED_KDC: HRESULT = 0x80090359u32 as HRESULT; +pub const SEC_E_KDC_CERT_EXPIRED: HRESULT = 0x8009035Au32 as HRESULT; +pub const SEC_E_KDC_CERT_REVOKED: HRESULT = 0x8009035Bu32 as HRESULT; +pub const SEC_I_SIGNATURE_NEEDED: HRESULT = 0x0009035C; +pub const SEC_E_INVALID_PARAMETER: HRESULT = 0x8009035Du32 as HRESULT; +pub const SEC_E_DELEGATION_POLICY: HRESULT = 0x8009035Eu32 as HRESULT; +pub const SEC_E_POLICY_NLTM_ONLY: HRESULT = 0x8009035Fu32 as HRESULT; +pub const SEC_I_NO_RENEGOTIATION: HRESULT = 0x00090360; +pub const SEC_E_NO_CONTEXT: HRESULT = 0x80090361u32 as HRESULT; +pub const SEC_E_PKU2U_CERT_FAILURE: HRESULT = 0x80090362u32 as HRESULT; +pub const SEC_E_MUTUAL_AUTH_FAILED: HRESULT = 0x80090363u32 as HRESULT; +pub const SEC_I_MESSAGE_FRAGMENT: HRESULT = 0x00090364; +pub const SEC_E_ONLY_HTTPS_ALLOWED: HRESULT = 0x80090365u32 as HRESULT; +pub const SEC_I_CONTINUE_NEEDED_MESSAGE_OK: HRESULT = 0x00090366; +pub const SEC_E_APPLICATION_PROTOCOL_MISMATCH: HRESULT = 0x80090367u32 as HRESULT; +pub const SEC_E_NO_SPM: HRESULT = SEC_E_INTERNAL_ERROR; +pub const SEC_E_NOT_SUPPORTED: HRESULT = SEC_E_UNSUPPORTED_FUNCTION; +pub const CRYPT_E_MSG_ERROR: HRESULT = 0x80091001u32 as HRESULT; +pub const CRYPT_E_UNKNOWN_ALGO: HRESULT = 0x80091002u32 as HRESULT; +pub const CRYPT_E_OID_FORMAT: HRESULT = 0x80091003u32 as HRESULT; +pub const CRYPT_E_INVALID_MSG_TYPE: HRESULT = 0x80091004u32 as HRESULT; +pub const CRYPT_E_UNEXPECTED_ENCODING: HRESULT = 0x80091005u32 as HRESULT; +pub const CRYPT_E_AUTH_ATTR_MISSING: HRESULT = 0x80091006u32 as HRESULT; +pub const CRYPT_E_HASH_VALUE: HRESULT = 0x80091007u32 as HRESULT; +pub const CRYPT_E_INVALID_INDEX: HRESULT = 0x80091008u32 as HRESULT; +pub const CRYPT_E_ALREADY_DECRYPTED: HRESULT = 0x80091009u32 as HRESULT; +pub const CRYPT_E_NOT_DECRYPTED: HRESULT = 0x8009100Au32 as HRESULT; +pub const CRYPT_E_RECIPIENT_NOT_FOUND: HRESULT = 0x8009100Bu32 as HRESULT; +pub const CRYPT_E_CONTROL_TYPE: HRESULT = 0x8009100Cu32 as HRESULT; +pub const CRYPT_E_ISSUER_SERIALNUMBER: HRESULT = 0x8009100Du32 as HRESULT; +pub const CRYPT_E_SIGNER_NOT_FOUND: HRESULT = 0x8009100Eu32 as HRESULT; +pub const CRYPT_E_ATTRIBUTES_MISSING: HRESULT = 0x8009100Fu32 as HRESULT; +pub const CRYPT_E_STREAM_MSG_NOT_READY: HRESULT = 0x80091010u32 as HRESULT; +pub const CRYPT_E_STREAM_INSUFFICIENT_DATA: HRESULT = 0x80091011u32 as HRESULT; +pub const CRYPT_I_NEW_PROTECTION_REQUIRED: HRESULT = 0x00091012; +pub const CRYPT_E_BAD_LEN: HRESULT = 0x80092001u32 as HRESULT; +pub const CRYPT_E_BAD_ENCODE: HRESULT = 0x80092002u32 as HRESULT; +pub const CRYPT_E_FILE_ERROR: HRESULT = 0x80092003u32 as HRESULT; +pub const CRYPT_E_NOT_FOUND: HRESULT = 0x80092004u32 as HRESULT; +pub const CRYPT_E_EXISTS: HRESULT = 0x80092005u32 as HRESULT; +pub const CRYPT_E_NO_PROVIDER: HRESULT = 0x80092006u32 as HRESULT; +pub const CRYPT_E_SELF_SIGNED: HRESULT = 0x80092007u32 as HRESULT; +pub const CRYPT_E_DELETED_PREV: HRESULT = 0x80092008u32 as HRESULT; +pub const CRYPT_E_NO_MATCH: HRESULT = 0x80092009u32 as HRESULT; +pub const CRYPT_E_UNEXPECTED_MSG_TYPE: HRESULT = 0x8009200Au32 as HRESULT; +pub const CRYPT_E_NO_KEY_PROPERTY: HRESULT = 0x8009200Bu32 as HRESULT; +pub const CRYPT_E_NO_DECRYPT_CERT: HRESULT = 0x8009200Cu32 as HRESULT; +pub const CRYPT_E_BAD_MSG: HRESULT = 0x8009200Du32 as HRESULT; +pub const CRYPT_E_NO_SIGNER: HRESULT = 0x8009200Eu32 as HRESULT; +pub const CRYPT_E_PENDING_CLOSE: HRESULT = 0x8009200Fu32 as HRESULT; +pub const CRYPT_E_REVOKED: HRESULT = 0x80092010u32 as HRESULT; +pub const CRYPT_E_NO_REVOCATION_DLL: HRESULT = 0x80092011u32 as HRESULT; +pub const CRYPT_E_NO_REVOCATION_CHECK: HRESULT = 0x80092012u32 as HRESULT; +pub const CRYPT_E_REVOCATION_OFFLINE: HRESULT = 0x80092013u32 as HRESULT; +pub const CRYPT_E_NOT_IN_REVOCATION_DATABASE: HRESULT = 0x80092014u32 as HRESULT; +pub const CRYPT_E_INVALID_NUMERIC_STRING: HRESULT = 0x80092020u32 as HRESULT; +pub const CRYPT_E_INVALID_PRINTABLE_STRING: HRESULT = 0x80092021u32 as HRESULT; +pub const CRYPT_E_INVALID_IA5_STRING: HRESULT = 0x80092022u32 as HRESULT; +pub const CRYPT_E_INVALID_X500_STRING: HRESULT = 0x80092023u32 as HRESULT; +pub const CRYPT_E_NOT_CHAR_STRING: HRESULT = 0x80092024u32 as HRESULT; +pub const CRYPT_E_FILERESIZED: HRESULT = 0x80092025u32 as HRESULT; +pub const CRYPT_E_SECURITY_SETTINGS: HRESULT = 0x80092026u32 as HRESULT; +pub const CRYPT_E_NO_VERIFY_USAGE_DLL: HRESULT = 0x80092027u32 as HRESULT; +pub const CRYPT_E_NO_VERIFY_USAGE_CHECK: HRESULT = 0x80092028u32 as HRESULT; +pub const CRYPT_E_VERIFY_USAGE_OFFLINE: HRESULT = 0x80092029u32 as HRESULT; +pub const CRYPT_E_NOT_IN_CTL: HRESULT = 0x8009202Au32 as HRESULT; +pub const CRYPT_E_NO_TRUSTED_SIGNER: HRESULT = 0x8009202Bu32 as HRESULT; +pub const CRYPT_E_MISSING_PUBKEY_PARA: HRESULT = 0x8009202Cu32 as HRESULT; +pub const CRYPT_E_OBJECT_LOCATOR_OBJECT_NOT_FOUND: HRESULT = 0x8009202Du32 as HRESULT; +pub const CRYPT_E_OSS_ERROR: HRESULT = 0x80093000u32 as HRESULT; +pub const OSS_MORE_BUF: HRESULT = 0x80093001u32 as HRESULT; +pub const OSS_NEGATIVE_UINTEGER: HRESULT = 0x80093002u32 as HRESULT; +pub const OSS_PDU_RANGE: HRESULT = 0x80093003u32 as HRESULT; +pub const OSS_MORE_INPUT: HRESULT = 0x80093004u32 as HRESULT; +pub const OSS_DATA_ERROR: HRESULT = 0x80093005u32 as HRESULT; +pub const OSS_BAD_ARG: HRESULT = 0x80093006u32 as HRESULT; +pub const OSS_BAD_VERSION: HRESULT = 0x80093007u32 as HRESULT; +pub const OSS_OUT_MEMORY: HRESULT = 0x80093008u32 as HRESULT; +pub const OSS_PDU_MISMATCH: HRESULT = 0x80093009u32 as HRESULT; +pub const OSS_LIMITED: HRESULT = 0x8009300Au32 as HRESULT; +pub const OSS_BAD_PTR: HRESULT = 0x8009300Bu32 as HRESULT; +pub const OSS_BAD_TIME: HRESULT = 0x8009300Cu32 as HRESULT; +pub const OSS_INDEFINITE_NOT_SUPPORTED: HRESULT = 0x8009300Du32 as HRESULT; +pub const OSS_MEM_ERROR: HRESULT = 0x8009300Eu32 as HRESULT; +pub const OSS_BAD_TABLE: HRESULT = 0x8009300Fu32 as HRESULT; +pub const OSS_TOO_LONG: HRESULT = 0x80093010u32 as HRESULT; +pub const OSS_CONSTRAINT_VIOLATED: HRESULT = 0x80093011u32 as HRESULT; +pub const OSS_FATAL_ERROR: HRESULT = 0x80093012u32 as HRESULT; +pub const OSS_ACCESS_SERIALIZATION_ERROR: HRESULT = 0x80093013u32 as HRESULT; +pub const OSS_NULL_TBL: HRESULT = 0x80093014u32 as HRESULT; +pub const OSS_NULL_FCN: HRESULT = 0x80093015u32 as HRESULT; +pub const OSS_BAD_ENCRULES: HRESULT = 0x80093016u32 as HRESULT; +pub const OSS_UNAVAIL_ENCRULES: HRESULT = 0x80093017u32 as HRESULT; +pub const OSS_CANT_OPEN_TRACE_WINDOW: HRESULT = 0x80093018u32 as HRESULT; +pub const OSS_UNIMPLEMENTED: HRESULT = 0x80093019u32 as HRESULT; +pub const OSS_OID_DLL_NOT_LINKED: HRESULT = 0x8009301Au32 as HRESULT; +pub const OSS_CANT_OPEN_TRACE_FILE: HRESULT = 0x8009301Bu32 as HRESULT; +pub const OSS_TRACE_FILE_ALREADY_OPEN: HRESULT = 0x8009301Cu32 as HRESULT; +pub const OSS_TABLE_MISMATCH: HRESULT = 0x8009301Du32 as HRESULT; +pub const OSS_TYPE_NOT_SUPPORTED: HRESULT = 0x8009301Eu32 as HRESULT; +pub const OSS_REAL_DLL_NOT_LINKED: HRESULT = 0x8009301Fu32 as HRESULT; +pub const OSS_REAL_CODE_NOT_LINKED: HRESULT = 0x80093020u32 as HRESULT; +pub const OSS_OUT_OF_RANGE: HRESULT = 0x80093021u32 as HRESULT; +pub const OSS_COPIER_DLL_NOT_LINKED: HRESULT = 0x80093022u32 as HRESULT; +pub const OSS_CONSTRAINT_DLL_NOT_LINKED: HRESULT = 0x80093023u32 as HRESULT; +pub const OSS_COMPARATOR_DLL_NOT_LINKED: HRESULT = 0x80093024u32 as HRESULT; +pub const OSS_COMPARATOR_CODE_NOT_LINKED: HRESULT = 0x80093025u32 as HRESULT; +pub const OSS_MEM_MGR_DLL_NOT_LINKED: HRESULT = 0x80093026u32 as HRESULT; +pub const OSS_PDV_DLL_NOT_LINKED: HRESULT = 0x80093027u32 as HRESULT; +pub const OSS_PDV_CODE_NOT_LINKED: HRESULT = 0x80093028u32 as HRESULT; +pub const OSS_API_DLL_NOT_LINKED: HRESULT = 0x80093029u32 as HRESULT; +pub const OSS_BERDER_DLL_NOT_LINKED: HRESULT = 0x8009302Au32 as HRESULT; +pub const OSS_PER_DLL_NOT_LINKED: HRESULT = 0x8009302Bu32 as HRESULT; +pub const OSS_OPEN_TYPE_ERROR: HRESULT = 0x8009302Cu32 as HRESULT; +pub const OSS_MUTEX_NOT_CREATED: HRESULT = 0x8009302Du32 as HRESULT; +pub const OSS_CANT_CLOSE_TRACE_FILE: HRESULT = 0x8009302Eu32 as HRESULT; +pub const CRYPT_E_ASN1_ERROR: HRESULT = 0x80093100u32 as HRESULT; +pub const CRYPT_E_ASN1_INTERNAL: HRESULT = 0x80093101u32 as HRESULT; +pub const CRYPT_E_ASN1_EOD: HRESULT = 0x80093102u32 as HRESULT; +pub const CRYPT_E_ASN1_CORRUPT: HRESULT = 0x80093103u32 as HRESULT; +pub const CRYPT_E_ASN1_LARGE: HRESULT = 0x80093104u32 as HRESULT; +pub const CRYPT_E_ASN1_CONSTRAINT: HRESULT = 0x80093105u32 as HRESULT; +pub const CRYPT_E_ASN1_MEMORY: HRESULT = 0x80093106u32 as HRESULT; +pub const CRYPT_E_ASN1_OVERFLOW: HRESULT = 0x80093107u32 as HRESULT; +pub const CRYPT_E_ASN1_BADPDU: HRESULT = 0x80093108u32 as HRESULT; +pub const CRYPT_E_ASN1_BADARGS: HRESULT = 0x80093109u32 as HRESULT; +pub const CRYPT_E_ASN1_BADREAL: HRESULT = 0x8009310Au32 as HRESULT; +pub const CRYPT_E_ASN1_BADTAG: HRESULT = 0x8009310Bu32 as HRESULT; +pub const CRYPT_E_ASN1_CHOICE: HRESULT = 0x8009310Cu32 as HRESULT; +pub const CRYPT_E_ASN1_RULE: HRESULT = 0x8009310Du32 as HRESULT; +pub const CRYPT_E_ASN1_UTF8: HRESULT = 0x8009310Eu32 as HRESULT; +pub const CRYPT_E_ASN1_PDU_TYPE: HRESULT = 0x80093133u32 as HRESULT; +pub const CRYPT_E_ASN1_NYI: HRESULT = 0x80093134u32 as HRESULT; +pub const CRYPT_E_ASN1_EXTENDED: HRESULT = 0x80093201u32 as HRESULT; +pub const CRYPT_E_ASN1_NOEOD: HRESULT = 0x80093202u32 as HRESULT; +pub const CERTSRV_E_BAD_REQUESTSUBJECT: HRESULT = 0x80094001u32 as HRESULT; +pub const CERTSRV_E_NO_REQUEST: HRESULT = 0x80094002u32 as HRESULT; +pub const CERTSRV_E_BAD_REQUESTSTATUS: HRESULT = 0x80094003u32 as HRESULT; +pub const CERTSRV_E_PROPERTY_EMPTY: HRESULT = 0x80094004u32 as HRESULT; +pub const CERTSRV_E_INVALID_CA_CERTIFICATE: HRESULT = 0x80094005u32 as HRESULT; +pub const CERTSRV_E_SERVER_SUSPENDED: HRESULT = 0x80094006u32 as HRESULT; +pub const CERTSRV_E_ENCODING_LENGTH: HRESULT = 0x80094007u32 as HRESULT; +pub const CERTSRV_E_ROLECONFLICT: HRESULT = 0x80094008u32 as HRESULT; +pub const CERTSRV_E_RESTRICTEDOFFICER: HRESULT = 0x80094009u32 as HRESULT; +pub const CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED: HRESULT = 0x8009400Au32 as HRESULT; +pub const CERTSRV_E_NO_VALID_KRA: HRESULT = 0x8009400Bu32 as HRESULT; +pub const CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL: HRESULT = 0x8009400Cu32 as HRESULT; +pub const CERTSRV_E_NO_CAADMIN_DEFINED: HRESULT = 0x8009400Du32 as HRESULT; +pub const CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE: HRESULT = 0x8009400Eu32 as HRESULT; +pub const CERTSRV_E_NO_DB_SESSIONS: HRESULT = 0x8009400Fu32 as HRESULT; +pub const CERTSRV_E_ALIGNMENT_FAULT: HRESULT = 0x80094010u32 as HRESULT; +pub const CERTSRV_E_ENROLL_DENIED: HRESULT = 0x80094011u32 as HRESULT; +pub const CERTSRV_E_TEMPLATE_DENIED: HRESULT = 0x80094012u32 as HRESULT; +pub const CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE: HRESULT = 0x80094013u32 as HRESULT; +pub const CERTSRV_E_ADMIN_DENIED_REQUEST: HRESULT = 0x80094014u32 as HRESULT; +pub const CERTSRV_E_NO_POLICY_SERVER: HRESULT = 0x80094015u32 as HRESULT; +pub const CERTSRV_E_WEAK_SIGNATURE_OR_KEY: HRESULT = 0x80094016u32 as HRESULT; +pub const CERTSRV_E_KEY_ATTESTATION_NOT_SUPPORTED: HRESULT = 0x80094017u32 as HRESULT; +pub const CERTSRV_E_ENCRYPTION_CERT_REQUIRED: HRESULT = 0x80094018u32 as HRESULT; +pub const CERTSRV_E_UNSUPPORTED_CERT_TYPE: HRESULT = 0x80094800u32 as HRESULT; +pub const CERTSRV_E_NO_CERT_TYPE: HRESULT = 0x80094801u32 as HRESULT; +pub const CERTSRV_E_TEMPLATE_CONFLICT: HRESULT = 0x80094802u32 as HRESULT; +pub const CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED: HRESULT = 0x80094803u32 as HRESULT; +pub const CERTSRV_E_ARCHIVED_KEY_REQUIRED: HRESULT = 0x80094804u32 as HRESULT; +pub const CERTSRV_E_SMIME_REQUIRED: HRESULT = 0x80094805u32 as HRESULT; +pub const CERTSRV_E_BAD_RENEWAL_SUBJECT: HRESULT = 0x80094806u32 as HRESULT; +pub const CERTSRV_E_BAD_TEMPLATE_VERSION: HRESULT = 0x80094807u32 as HRESULT; +pub const CERTSRV_E_TEMPLATE_POLICY_REQUIRED: HRESULT = 0x80094808u32 as HRESULT; +pub const CERTSRV_E_SIGNATURE_POLICY_REQUIRED: HRESULT = 0x80094809u32 as HRESULT; +pub const CERTSRV_E_SIGNATURE_COUNT: HRESULT = 0x8009480Au32 as HRESULT; +pub const CERTSRV_E_SIGNATURE_REJECTED: HRESULT = 0x8009480Bu32 as HRESULT; +pub const CERTSRV_E_ISSUANCE_POLICY_REQUIRED: HRESULT = 0x8009480Cu32 as HRESULT; +pub const CERTSRV_E_SUBJECT_UPN_REQUIRED: HRESULT = 0x8009480Du32 as HRESULT; +pub const CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED: HRESULT = 0x8009480Eu32 as HRESULT; +pub const CERTSRV_E_SUBJECT_DNS_REQUIRED: HRESULT = 0x8009480Fu32 as HRESULT; +pub const CERTSRV_E_ARCHIVED_KEY_UNEXPECTED: HRESULT = 0x80094810u32 as HRESULT; +pub const CERTSRV_E_KEY_LENGTH: HRESULT = 0x80094811u32 as HRESULT; +pub const CERTSRV_E_SUBJECT_EMAIL_REQUIRED: HRESULT = 0x80094812u32 as HRESULT; +pub const CERTSRV_E_UNKNOWN_CERT_TYPE: HRESULT = 0x80094813u32 as HRESULT; +pub const CERTSRV_E_CERT_TYPE_OVERLAP: HRESULT = 0x80094814u32 as HRESULT; +pub const CERTSRV_E_TOO_MANY_SIGNATURES: HRESULT = 0x80094815u32 as HRESULT; +pub const CERTSRV_E_RENEWAL_BAD_PUBLIC_KEY: HRESULT = 0x80094816u32 as HRESULT; +pub const CERTSRV_E_INVALID_EK: HRESULT = 0x80094817u32 as HRESULT; +pub const CERTSRV_E_INVALID_IDBINDING: HRESULT = 0x80094818u32 as HRESULT; +pub const CERTSRV_E_INVALID_ATTESTATION: HRESULT = 0x80094819u32 as HRESULT; +pub const CERTSRV_E_KEY_ATTESTATION: HRESULT = 0x8009481Au32 as HRESULT; +pub const CERTSRV_E_CORRUPT_KEY_ATTESTATION: HRESULT = 0x8009481Bu32 as HRESULT; +pub const CERTSRV_E_EXPIRED_CHALLENGE: HRESULT = 0x8009481Cu32 as HRESULT; +pub const CERTSRV_E_INVALID_RESPONSE: HRESULT = 0x8009481Du32 as HRESULT; +pub const CERTSRV_E_INVALID_REQUESTID: HRESULT = 0x8009481Eu32 as HRESULT; +pub const XENROLL_E_KEY_NOT_EXPORTABLE: HRESULT = 0x80095000u32 as HRESULT; +pub const XENROLL_E_CANNOT_ADD_ROOT_CERT: HRESULT = 0x80095001u32 as HRESULT; +pub const XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND: HRESULT = 0x80095002u32 as HRESULT; +pub const XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH: HRESULT = 0x80095003u32 as HRESULT; +pub const XENROLL_E_RESPONSE_KA_HASH_MISMATCH: HRESULT = 0x80095004u32 as HRESULT; +pub const XENROLL_E_KEYSPEC_SMIME_MISMATCH: HRESULT = 0x80095005u32 as HRESULT; +pub const TRUST_E_SYSTEM_ERROR: HRESULT = 0x80096001u32 as HRESULT; +pub const TRUST_E_NO_SIGNER_CERT: HRESULT = 0x80096002u32 as HRESULT; +pub const TRUST_E_COUNTER_SIGNER: HRESULT = 0x80096003u32 as HRESULT; +pub const TRUST_E_CERT_SIGNATURE: HRESULT = 0x80096004u32 as HRESULT; +pub const TRUST_E_TIME_STAMP: HRESULT = 0x80096005u32 as HRESULT; +pub const TRUST_E_BAD_DIGEST: HRESULT = 0x80096010u32 as HRESULT; +pub const TRUST_E_BASIC_CONSTRAINTS: HRESULT = 0x80096019u32 as HRESULT; +pub const TRUST_E_FINANCIAL_CRITERIA: HRESULT = 0x8009601Eu32 as HRESULT; +pub const MSSIPOTF_E_OUTOFMEMRANGE: HRESULT = 0x80097001u32 as HRESULT; +pub const MSSIPOTF_E_CANTGETOBJECT: HRESULT = 0x80097002u32 as HRESULT; +pub const MSSIPOTF_E_NOHEADTABLE: HRESULT = 0x80097003u32 as HRESULT; +pub const MSSIPOTF_E_BAD_MAGICNUMBER: HRESULT = 0x80097004u32 as HRESULT; +pub const MSSIPOTF_E_BAD_OFFSET_TABLE: HRESULT = 0x80097005u32 as HRESULT; +pub const MSSIPOTF_E_TABLE_TAGORDER: HRESULT = 0x80097006u32 as HRESULT; +pub const MSSIPOTF_E_TABLE_LONGWORD: HRESULT = 0x80097007u32 as HRESULT; +pub const MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT: HRESULT = 0x80097008u32 as HRESULT; +pub const MSSIPOTF_E_TABLES_OVERLAP: HRESULT = 0x80097009u32 as HRESULT; +pub const MSSIPOTF_E_TABLE_PADBYTES: HRESULT = 0x8009700Au32 as HRESULT; +pub const MSSIPOTF_E_FILETOOSMALL: HRESULT = 0x8009700Bu32 as HRESULT; +pub const MSSIPOTF_E_TABLE_CHECKSUM: HRESULT = 0x8009700Cu32 as HRESULT; +pub const MSSIPOTF_E_FILE_CHECKSUM: HRESULT = 0x8009700Du32 as HRESULT; +pub const MSSIPOTF_E_FAILED_POLICY: HRESULT = 0x80097010u32 as HRESULT; +pub const MSSIPOTF_E_FAILED_HINTS_CHECK: HRESULT = 0x80097011u32 as HRESULT; +pub const MSSIPOTF_E_NOT_OPENTYPE: HRESULT = 0x80097012u32 as HRESULT; +pub const MSSIPOTF_E_FILE: HRESULT = 0x80097013u32 as HRESULT; +pub const MSSIPOTF_E_CRYPT: HRESULT = 0x80097014u32 as HRESULT; +pub const MSSIPOTF_E_BADVERSION: HRESULT = 0x80097015u32 as HRESULT; +pub const MSSIPOTF_E_DSIG_STRUCTURE: HRESULT = 0x80097016u32 as HRESULT; +pub const MSSIPOTF_E_PCONST_CHECK: HRESULT = 0x80097017u32 as HRESULT; +pub const MSSIPOTF_E_STRUCTURE: HRESULT = 0x80097018u32 as HRESULT; +pub const ERROR_CRED_REQUIRES_CONFIRMATION: HRESULT = 0x80097019u32 as HRESULT; +pub const NTE_OP_OK: HRESULT = 0; +pub const TRUST_E_PROVIDER_UNKNOWN: HRESULT = 0x800B0001u32 as HRESULT; +pub const TRUST_E_ACTION_UNKNOWN: HRESULT = 0x800B0002u32 as HRESULT; +pub const TRUST_E_SUBJECT_FORM_UNKNOWN: HRESULT = 0x800B0003u32 as HRESULT; +pub const TRUST_E_SUBJECT_NOT_TRUSTED: HRESULT = 0x800B0004u32 as HRESULT; +pub const DIGSIG_E_ENCODE: HRESULT = 0x800B0005u32 as HRESULT; +pub const DIGSIG_E_DECODE: HRESULT = 0x800B0006u32 as HRESULT; +pub const DIGSIG_E_EXTENSIBILITY: HRESULT = 0x800B0007u32 as HRESULT; +pub const DIGSIG_E_CRYPTO: HRESULT = 0x800B0008u32 as HRESULT; +pub const PERSIST_E_SIZEDEFINITE: HRESULT = 0x800B0009u32 as HRESULT; +pub const PERSIST_E_SIZEINDEFINITE: HRESULT = 0x800B000Au32 as HRESULT; +pub const PERSIST_E_NOTSELFSIZING: HRESULT = 0x800B000Bu32 as HRESULT; +pub const TRUST_E_NOSIGNATURE: HRESULT = 0x800B0100u32 as HRESULT; +pub const CERT_E_EXPIRED: HRESULT = 0x800B0101u32 as HRESULT; +pub const CERT_E_VALIDITYPERIODNESTING: HRESULT = 0x800B0102u32 as HRESULT; +pub const CERT_E_ROLE: HRESULT = 0x800B0103u32 as HRESULT; +pub const CERT_E_PATHLENCONST: HRESULT = 0x800B0104u32 as HRESULT; +pub const CERT_E_CRITICAL: HRESULT = 0x800B0105u32 as HRESULT; +pub const CERT_E_PURPOSE: HRESULT = 0x800B0106u32 as HRESULT; +pub const CERT_E_ISSUERCHAINING: HRESULT = 0x800B0107u32 as HRESULT; +pub const CERT_E_MALFORMED: HRESULT = 0x800B0108u32 as HRESULT; +pub const CERT_E_UNTRUSTEDROOT: HRESULT = 0x800B0109u32 as HRESULT; +pub const CERT_E_CHAINING: HRESULT = 0x800B010Au32 as HRESULT; +pub const TRUST_E_FAIL: HRESULT = 0x800B010Bu32 as HRESULT; +pub const CERT_E_REVOKED: HRESULT = 0x800B010Cu32 as HRESULT; +pub const CERT_E_UNTRUSTEDTESTROOT: HRESULT = 0x800B010Du32 as HRESULT; +pub const CERT_E_REVOCATION_FAILURE: HRESULT = 0x800B010Eu32 as HRESULT; +pub const CERT_E_CN_NO_MATCH: HRESULT = 0x800B010Fu32 as HRESULT; +pub const CERT_E_WRONG_USAGE: HRESULT = 0x800B0110u32 as HRESULT; +pub const TRUST_E_EXPLICIT_DISTRUST: HRESULT = 0x800B0111u32 as HRESULT; +pub const CERT_E_UNTRUSTEDCA: HRESULT = 0x800B0112u32 as HRESULT; +pub const CERT_E_INVALID_POLICY: HRESULT = 0x800B0113u32 as HRESULT; +pub const CERT_E_INVALID_NAME: HRESULT = 0x800B0114u32 as HRESULT; +pub const SPAPI_E_EXPECTED_SECTION_NAME: HRESULT = 0x800F0000u32 as HRESULT; +pub const SPAPI_E_BAD_SECTION_NAME_LINE: HRESULT = 0x800F0001u32 as HRESULT; +pub const SPAPI_E_SECTION_NAME_TOO_LONG: HRESULT = 0x800F0002u32 as HRESULT; +pub const SPAPI_E_GENERAL_SYNTAX: HRESULT = 0x800F0003u32 as HRESULT; +pub const SPAPI_E_WRONG_INF_STYLE: HRESULT = 0x800F0100u32 as HRESULT; +pub const SPAPI_E_SECTION_NOT_FOUND: HRESULT = 0x800F0101u32 as HRESULT; +pub const SPAPI_E_LINE_NOT_FOUND: HRESULT = 0x800F0102u32 as HRESULT; +pub const SPAPI_E_NO_BACKUP: HRESULT = 0x800F0103u32 as HRESULT; +pub const SPAPI_E_NO_ASSOCIATED_CLASS: HRESULT = 0x800F0200u32 as HRESULT; +pub const SPAPI_E_CLASS_MISMATCH: HRESULT = 0x800F0201u32 as HRESULT; +pub const SPAPI_E_DUPLICATE_FOUND: HRESULT = 0x800F0202u32 as HRESULT; +pub const SPAPI_E_NO_DRIVER_SELECTED: HRESULT = 0x800F0203u32 as HRESULT; +pub const SPAPI_E_KEY_DOES_NOT_EXIST: HRESULT = 0x800F0204u32 as HRESULT; +pub const SPAPI_E_INVALID_DEVINST_NAME: HRESULT = 0x800F0205u32 as HRESULT; +pub const SPAPI_E_INVALID_CLASS: HRESULT = 0x800F0206u32 as HRESULT; +pub const SPAPI_E_DEVINST_ALREADY_EXISTS: HRESULT = 0x800F0207u32 as HRESULT; +pub const SPAPI_E_DEVINFO_NOT_REGISTERED: HRESULT = 0x800F0208u32 as HRESULT; +pub const SPAPI_E_INVALID_REG_PROPERTY: HRESULT = 0x800F0209u32 as HRESULT; +pub const SPAPI_E_NO_INF: HRESULT = 0x800F020Au32 as HRESULT; +pub const SPAPI_E_NO_SUCH_DEVINST: HRESULT = 0x800F020Bu32 as HRESULT; +pub const SPAPI_E_CANT_LOAD_CLASS_ICON: HRESULT = 0x800F020Cu32 as HRESULT; +pub const SPAPI_E_INVALID_CLASS_INSTALLER: HRESULT = 0x800F020Du32 as HRESULT; +pub const SPAPI_E_DI_DO_DEFAULT: HRESULT = 0x800F020Eu32 as HRESULT; +pub const SPAPI_E_DI_NOFILECOPY: HRESULT = 0x800F020Fu32 as HRESULT; +pub const SPAPI_E_INVALID_HWPROFILE: HRESULT = 0x800F0210u32 as HRESULT; +pub const SPAPI_E_NO_DEVICE_SELECTED: HRESULT = 0x800F0211u32 as HRESULT; +pub const SPAPI_E_DEVINFO_LIST_LOCKED: HRESULT = 0x800F0212u32 as HRESULT; +pub const SPAPI_E_DEVINFO_DATA_LOCKED: HRESULT = 0x800F0213u32 as HRESULT; +pub const SPAPI_E_DI_BAD_PATH: HRESULT = 0x800F0214u32 as HRESULT; +pub const SPAPI_E_NO_CLASSINSTALL_PARAMS: HRESULT = 0x800F0215u32 as HRESULT; +pub const SPAPI_E_FILEQUEUE_LOCKED: HRESULT = 0x800F0216u32 as HRESULT; +pub const SPAPI_E_BAD_SERVICE_INSTALLSECT: HRESULT = 0x800F0217u32 as HRESULT; +pub const SPAPI_E_NO_CLASS_DRIVER_LIST: HRESULT = 0x800F0218u32 as HRESULT; +pub const SPAPI_E_NO_ASSOCIATED_SERVICE: HRESULT = 0x800F0219u32 as HRESULT; +pub const SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE: HRESULT = 0x800F021Au32 as HRESULT; +pub const SPAPI_E_DEVICE_INTERFACE_ACTIVE: HRESULT = 0x800F021Bu32 as HRESULT; +pub const SPAPI_E_DEVICE_INTERFACE_REMOVED: HRESULT = 0x800F021Cu32 as HRESULT; +pub const SPAPI_E_BAD_INTERFACE_INSTALLSECT: HRESULT = 0x800F021Du32 as HRESULT; +pub const SPAPI_E_NO_SUCH_INTERFACE_CLASS: HRESULT = 0x800F021Eu32 as HRESULT; +pub const SPAPI_E_INVALID_REFERENCE_STRING: HRESULT = 0x800F021Fu32 as HRESULT; +pub const SPAPI_E_INVALID_MACHINENAME: HRESULT = 0x800F0220u32 as HRESULT; +pub const SPAPI_E_REMOTE_COMM_FAILURE: HRESULT = 0x800F0221u32 as HRESULT; +pub const SPAPI_E_MACHINE_UNAVAILABLE: HRESULT = 0x800F0222u32 as HRESULT; +pub const SPAPI_E_NO_CONFIGMGR_SERVICES: HRESULT = 0x800F0223u32 as HRESULT; +pub const SPAPI_E_INVALID_PROPPAGE_PROVIDER: HRESULT = 0x800F0224u32 as HRESULT; +pub const SPAPI_E_NO_SUCH_DEVICE_INTERFACE: HRESULT = 0x800F0225u32 as HRESULT; +pub const SPAPI_E_DI_POSTPROCESSING_REQUIRED: HRESULT = 0x800F0226u32 as HRESULT; +pub const SPAPI_E_INVALID_COINSTALLER: HRESULT = 0x800F0227u32 as HRESULT; +pub const SPAPI_E_NO_COMPAT_DRIVERS: HRESULT = 0x800F0228u32 as HRESULT; +pub const SPAPI_E_NO_DEVICE_ICON: HRESULT = 0x800F0229u32 as HRESULT; +pub const SPAPI_E_INVALID_INF_LOGCONFIG: HRESULT = 0x800F022Au32 as HRESULT; +pub const SPAPI_E_DI_DONT_INSTALL: HRESULT = 0x800F022Bu32 as HRESULT; +pub const SPAPI_E_INVALID_FILTER_DRIVER: HRESULT = 0x800F022Cu32 as HRESULT; +pub const SPAPI_E_NON_WINDOWS_NT_DRIVER: HRESULT = 0x800F022Du32 as HRESULT; +pub const SPAPI_E_NON_WINDOWS_DRIVER: HRESULT = 0x800F022Eu32 as HRESULT; +pub const SPAPI_E_NO_CATALOG_FOR_OEM_INF: HRESULT = 0x800F022Fu32 as HRESULT; +pub const SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE: HRESULT = 0x800F0230u32 as HRESULT; +pub const SPAPI_E_NOT_DISABLEABLE: HRESULT = 0x800F0231u32 as HRESULT; +pub const SPAPI_E_CANT_REMOVE_DEVINST: HRESULT = 0x800F0232u32 as HRESULT; +pub const SPAPI_E_INVALID_TARGET: HRESULT = 0x800F0233u32 as HRESULT; +pub const SPAPI_E_DRIVER_NONNATIVE: HRESULT = 0x800F0234u32 as HRESULT; +pub const SPAPI_E_IN_WOW64: HRESULT = 0x800F0235u32 as HRESULT; +pub const SPAPI_E_SET_SYSTEM_RESTORE_POINT: HRESULT = 0x800F0236u32 as HRESULT; +pub const SPAPI_E_INCORRECTLY_COPIED_INF: HRESULT = 0x800F0237u32 as HRESULT; +pub const SPAPI_E_SCE_DISABLED: HRESULT = 0x800F0238u32 as HRESULT; +pub const SPAPI_E_UNKNOWN_EXCEPTION: HRESULT = 0x800F0239u32 as HRESULT; +pub const SPAPI_E_PNP_REGISTRY_ERROR: HRESULT = 0x800F023Au32 as HRESULT; +pub const SPAPI_E_REMOTE_REQUEST_UNSUPPORTED: HRESULT = 0x800F023Bu32 as HRESULT; +pub const SPAPI_E_NOT_AN_INSTALLED_OEM_INF: HRESULT = 0x800F023Cu32 as HRESULT; +pub const SPAPI_E_INF_IN_USE_BY_DEVICES: HRESULT = 0x800F023Du32 as HRESULT; +pub const SPAPI_E_DI_FUNCTION_OBSOLETE: HRESULT = 0x800F023Eu32 as HRESULT; +pub const SPAPI_E_NO_AUTHENTICODE_CATALOG: HRESULT = 0x800F023Fu32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_DISALLOWED: HRESULT = 0x800F0240u32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER: HRESULT = 0x800F0241u32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED: HRESULT = 0x800F0242u32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED: HRESULT = 0x800F0243u32 as HRESULT; +pub const SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH: HRESULT = 0x800F0244u32 as HRESULT; +pub const SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE: HRESULT = 0x800F0245u32 as HRESULT; +pub const SPAPI_E_DEVICE_INSTALLER_NOT_READY: HRESULT = 0x800F0246u32 as HRESULT; +pub const SPAPI_E_DRIVER_STORE_ADD_FAILED: HRESULT = 0x800F0247u32 as HRESULT; +pub const SPAPI_E_DEVICE_INSTALL_BLOCKED: HRESULT = 0x800F0248u32 as HRESULT; +pub const SPAPI_E_DRIVER_INSTALL_BLOCKED: HRESULT = 0x800F0249u32 as HRESULT; +pub const SPAPI_E_WRONG_INF_TYPE: HRESULT = 0x800F024Au32 as HRESULT; +pub const SPAPI_E_FILE_HASH_NOT_IN_CATALOG: HRESULT = 0x800F024Bu32 as HRESULT; +pub const SPAPI_E_DRIVER_STORE_DELETE_FAILED: HRESULT = 0x800F024Cu32 as HRESULT; +pub const SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW: HRESULT = 0x800F0300u32 as HRESULT; +pub const SPAPI_E_ERROR_NOT_INSTALLED: HRESULT = 0x800F1000u32 as HRESULT; +pub const SCARD_S_SUCCESS: HRESULT = NO_ERROR as HRESULT; +pub const SCARD_F_INTERNAL_ERROR: HRESULT = 0x80100001u32 as HRESULT; +pub const SCARD_E_CANCELLED: HRESULT = 0x80100002u32 as HRESULT; +pub const SCARD_E_INVALID_HANDLE: HRESULT = 0x80100003u32 as HRESULT; +pub const SCARD_E_INVALID_PARAMETER: HRESULT = 0x80100004u32 as HRESULT; +pub const SCARD_E_INVALID_TARGET: HRESULT = 0x80100005u32 as HRESULT; +pub const SCARD_E_NO_MEMORY: HRESULT = 0x80100006u32 as HRESULT; +pub const SCARD_F_WAITED_TOO_LONG: HRESULT = 0x80100007u32 as HRESULT; +pub const SCARD_E_INSUFFICIENT_BUFFER: HRESULT = 0x80100008u32 as HRESULT; +pub const SCARD_E_UNKNOWN_READER: HRESULT = 0x80100009u32 as HRESULT; +pub const SCARD_E_TIMEOUT: HRESULT = 0x8010000Au32 as HRESULT; +pub const SCARD_E_SHARING_VIOLATION: HRESULT = 0x8010000Bu32 as HRESULT; +pub const SCARD_E_NO_SMARTCARD: HRESULT = 0x8010000Cu32 as HRESULT; +pub const SCARD_E_UNKNOWN_CARD: HRESULT = 0x8010000Du32 as HRESULT; +pub const SCARD_E_CANT_DISPOSE: HRESULT = 0x8010000Eu32 as HRESULT; +pub const SCARD_E_PROTO_MISMATCH: HRESULT = 0x8010000Fu32 as HRESULT; +pub const SCARD_E_NOT_READY: HRESULT = 0x80100010u32 as HRESULT; +pub const SCARD_E_INVALID_VALUE: HRESULT = 0x80100011u32 as HRESULT; +pub const SCARD_E_SYSTEM_CANCELLED: HRESULT = 0x80100012u32 as HRESULT; +pub const SCARD_F_COMM_ERROR: HRESULT = 0x80100013u32 as HRESULT; +pub const SCARD_F_UNKNOWN_ERROR: HRESULT = 0x80100014u32 as HRESULT; +pub const SCARD_E_INVALID_ATR: HRESULT = 0x80100015u32 as HRESULT; +pub const SCARD_E_NOT_TRANSACTED: HRESULT = 0x80100016u32 as HRESULT; +pub const SCARD_E_READER_UNAVAILABLE: HRESULT = 0x80100017u32 as HRESULT; +pub const SCARD_P_SHUTDOWN: HRESULT = 0x80100018u32 as HRESULT; +pub const SCARD_E_PCI_TOO_SMALL: HRESULT = 0x80100019u32 as HRESULT; +pub const SCARD_E_READER_UNSUPPORTED: HRESULT = 0x8010001Au32 as HRESULT; +pub const SCARD_E_DUPLICATE_READER: HRESULT = 0x8010001Bu32 as HRESULT; +pub const SCARD_E_CARD_UNSUPPORTED: HRESULT = 0x8010001Cu32 as HRESULT; +pub const SCARD_E_NO_SERVICE: HRESULT = 0x8010001Du32 as HRESULT; +pub const SCARD_E_SERVICE_STOPPED: HRESULT = 0x8010001Eu32 as HRESULT; +pub const SCARD_E_UNEXPECTED: HRESULT = 0x8010001Fu32 as HRESULT; +pub const SCARD_E_ICC_INSTALLATION: HRESULT = 0x80100020u32 as HRESULT; +pub const SCARD_E_ICC_CREATEORDER: HRESULT = 0x80100021u32 as HRESULT; +pub const SCARD_E_UNSUPPORTED_FEATURE: HRESULT = 0x80100022u32 as HRESULT; +pub const SCARD_E_DIR_NOT_FOUND: HRESULT = 0x80100023u32 as HRESULT; +pub const SCARD_E_FILE_NOT_FOUND: HRESULT = 0x80100024u32 as HRESULT; +pub const SCARD_E_NO_DIR: HRESULT = 0x80100025u32 as HRESULT; +pub const SCARD_E_NO_FILE: HRESULT = 0x80100026u32 as HRESULT; +pub const SCARD_E_NO_ACCESS: HRESULT = 0x80100027u32 as HRESULT; +pub const SCARD_E_WRITE_TOO_MANY: HRESULT = 0x80100028u32 as HRESULT; +pub const SCARD_E_BAD_SEEK: HRESULT = 0x80100029u32 as HRESULT; +pub const SCARD_E_INVALID_CHV: HRESULT = 0x8010002Au32 as HRESULT; +pub const SCARD_E_UNKNOWN_RES_MNG: HRESULT = 0x8010002Bu32 as HRESULT; +pub const SCARD_E_NO_SUCH_CERTIFICATE: HRESULT = 0x8010002Cu32 as HRESULT; +pub const SCARD_E_CERTIFICATE_UNAVAILABLE: HRESULT = 0x8010002Du32 as HRESULT; +pub const SCARD_E_NO_READERS_AVAILABLE: HRESULT = 0x8010002Eu32 as HRESULT; +pub const SCARD_E_COMM_DATA_LOST: HRESULT = 0x8010002Fu32 as HRESULT; +pub const SCARD_E_NO_KEY_CONTAINER: HRESULT = 0x80100030u32 as HRESULT; +pub const SCARD_E_SERVER_TOO_BUSY: HRESULT = 0x80100031u32 as HRESULT; +pub const SCARD_E_PIN_CACHE_EXPIRED: HRESULT = 0x80100032u32 as HRESULT; +pub const SCARD_E_NO_PIN_CACHE: HRESULT = 0x80100033u32 as HRESULT; +pub const SCARD_E_READ_ONLY_CARD: HRESULT = 0x80100034u32 as HRESULT; +pub const SCARD_W_UNSUPPORTED_CARD: HRESULT = 0x80100065u32 as HRESULT; +pub const SCARD_W_UNRESPONSIVE_CARD: HRESULT = 0x80100066u32 as HRESULT; +pub const SCARD_W_UNPOWERED_CARD: HRESULT = 0x80100067u32 as HRESULT; +pub const SCARD_W_RESET_CARD: HRESULT = 0x80100068u32 as HRESULT; +pub const SCARD_W_REMOVED_CARD: HRESULT = 0x80100069u32 as HRESULT; +pub const SCARD_W_SECURITY_VIOLATION: HRESULT = 0x8010006Au32 as HRESULT; +pub const SCARD_W_WRONG_CHV: HRESULT = 0x8010006Bu32 as HRESULT; +pub const SCARD_W_CHV_BLOCKED: HRESULT = 0x8010006Cu32 as HRESULT; +pub const SCARD_W_EOF: HRESULT = 0x8010006Du32 as HRESULT; +pub const SCARD_W_CANCELLED_BY_USER: HRESULT = 0x8010006Eu32 as HRESULT; +pub const SCARD_W_CARD_NOT_AUTHENTICATED: HRESULT = 0x8010006Fu32 as HRESULT; +pub const SCARD_W_CACHE_ITEM_NOT_FOUND: HRESULT = 0x80100070u32 as HRESULT; +pub const SCARD_W_CACHE_ITEM_STALE: HRESULT = 0x80100071u32 as HRESULT; +pub const SCARD_W_CACHE_ITEM_TOO_BIG: HRESULT = 0x80100072u32 as HRESULT; +pub const COMADMIN_E_OBJECTERRORS: HRESULT = 0x80110401u32 as HRESULT; +pub const COMADMIN_E_OBJECTINVALID: HRESULT = 0x80110402u32 as HRESULT; +pub const COMADMIN_E_KEYMISSING: HRESULT = 0x80110403u32 as HRESULT; +pub const COMADMIN_E_ALREADYINSTALLED: HRESULT = 0x80110404u32 as HRESULT; +pub const COMADMIN_E_APP_FILE_WRITEFAIL: HRESULT = 0x80110407u32 as HRESULT; +pub const COMADMIN_E_APP_FILE_READFAIL: HRESULT = 0x80110408u32 as HRESULT; +pub const COMADMIN_E_APP_FILE_VERSION: HRESULT = 0x80110409u32 as HRESULT; +pub const COMADMIN_E_BADPATH: HRESULT = 0x8011040Au32 as HRESULT; +pub const COMADMIN_E_APPLICATIONEXISTS: HRESULT = 0x8011040Bu32 as HRESULT; +pub const COMADMIN_E_ROLEEXISTS: HRESULT = 0x8011040Cu32 as HRESULT; +pub const COMADMIN_E_CANTCOPYFILE: HRESULT = 0x8011040Du32 as HRESULT; +pub const COMADMIN_E_NOUSER: HRESULT = 0x8011040Fu32 as HRESULT; +pub const COMADMIN_E_INVALIDUSERIDS: HRESULT = 0x80110410u32 as HRESULT; +pub const COMADMIN_E_NOREGISTRYCLSID: HRESULT = 0x80110411u32 as HRESULT; +pub const COMADMIN_E_BADREGISTRYPROGID: HRESULT = 0x80110412u32 as HRESULT; +pub const COMADMIN_E_AUTHENTICATIONLEVEL: HRESULT = 0x80110413u32 as HRESULT; +pub const COMADMIN_E_USERPASSWDNOTVALID: HRESULT = 0x80110414u32 as HRESULT; +pub const COMADMIN_E_CLSIDORIIDMISMATCH: HRESULT = 0x80110418u32 as HRESULT; +pub const COMADMIN_E_REMOTEINTERFACE: HRESULT = 0x80110419u32 as HRESULT; +pub const COMADMIN_E_DLLREGISTERSERVER: HRESULT = 0x8011041Au32 as HRESULT; +pub const COMADMIN_E_NOSERVERSHARE: HRESULT = 0x8011041Bu32 as HRESULT; +pub const COMADMIN_E_DLLLOADFAILED: HRESULT = 0x8011041Du32 as HRESULT; +pub const COMADMIN_E_BADREGISTRYLIBID: HRESULT = 0x8011041Eu32 as HRESULT; +pub const COMADMIN_E_APPDIRNOTFOUND: HRESULT = 0x8011041Fu32 as HRESULT; +pub const COMADMIN_E_REGISTRARFAILED: HRESULT = 0x80110423u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_DOESNOTEXIST: HRESULT = 0x80110424u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_LOADDLLFAIL: HRESULT = 0x80110425u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_GETCLASSOBJ: HRESULT = 0x80110426u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_CLASSNOTAVAIL: HRESULT = 0x80110427u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_BADTLB: HRESULT = 0x80110428u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_NOTINSTALLABLE: HRESULT = 0x80110429u32 as HRESULT; +pub const COMADMIN_E_NOTCHANGEABLE: HRESULT = 0x8011042Au32 as HRESULT; +pub const COMADMIN_E_NOTDELETEABLE: HRESULT = 0x8011042Bu32 as HRESULT; +pub const COMADMIN_E_SESSION: HRESULT = 0x8011042Cu32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_LOCKED: HRESULT = 0x8011042Du32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_BAD_DEST: HRESULT = 0x8011042Eu32 as HRESULT; +pub const COMADMIN_E_REGISTERTLB: HRESULT = 0x80110430u32 as HRESULT; +pub const COMADMIN_E_SYSTEMAPP: HRESULT = 0x80110433u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_NOREGISTRAR: HRESULT = 0x80110434u32 as HRESULT; +pub const COMADMIN_E_COREQCOMPINSTALLED: HRESULT = 0x80110435u32 as HRESULT; +pub const COMADMIN_E_SERVICENOTINSTALLED: HRESULT = 0x80110436u32 as HRESULT; +pub const COMADMIN_E_PROPERTYSAVEFAILED: HRESULT = 0x80110437u32 as HRESULT; +pub const COMADMIN_E_OBJECTEXISTS: HRESULT = 0x80110438u32 as HRESULT; +pub const COMADMIN_E_COMPONENTEXISTS: HRESULT = 0x80110439u32 as HRESULT; +pub const COMADMIN_E_REGFILE_CORRUPT: HRESULT = 0x8011043Bu32 as HRESULT; +pub const COMADMIN_E_PROPERTY_OVERFLOW: HRESULT = 0x8011043Cu32 as HRESULT; +pub const COMADMIN_E_NOTINREGISTRY: HRESULT = 0x8011043Eu32 as HRESULT; +pub const COMADMIN_E_OBJECTNOTPOOLABLE: HRESULT = 0x8011043Fu32 as HRESULT; +pub const COMADMIN_E_APPLID_MATCHES_CLSID: HRESULT = 0x80110446u32 as HRESULT; +pub const COMADMIN_E_ROLE_DOES_NOT_EXIST: HRESULT = 0x80110447u32 as HRESULT; +pub const COMADMIN_E_START_APP_NEEDS_COMPONENTS: HRESULT = 0x80110448u32 as HRESULT; +pub const COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM: HRESULT = 0x80110449u32 as HRESULT; +pub const COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY: HRESULT = 0x8011044Au32 as HRESULT; +pub const COMADMIN_E_CAN_NOT_START_APP: HRESULT = 0x8011044Bu32 as HRESULT; +pub const COMADMIN_E_CAN_NOT_EXPORT_SYS_APP: HRESULT = 0x8011044Cu32 as HRESULT; +pub const COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT: HRESULT = 0x8011044Du32 as HRESULT; +pub const COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER: HRESULT = 0x8011044Eu32 as HRESULT; +pub const COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE: HRESULT = 0x8011044Fu32 as HRESULT; +pub const COMADMIN_E_BASE_PARTITION_ONLY: HRESULT = 0x80110450u32 as HRESULT; +pub const COMADMIN_E_START_APP_DISABLED: HRESULT = 0x80110451u32 as HRESULT; +pub const COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME: HRESULT = 0x80110457u32 as HRESULT; +pub const COMADMIN_E_CAT_INVALID_PARTITION_NAME: HRESULT = 0x80110458u32 as HRESULT; +pub const COMADMIN_E_CAT_PARTITION_IN_USE: HRESULT = 0x80110459u32 as HRESULT; +pub const COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES: HRESULT = 0x8011045Au32 as HRESULT; +pub const COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED: HRESULT = 0x8011045Bu32 as HRESULT; +pub const COMADMIN_E_AMBIGUOUS_APPLICATION_NAME: HRESULT = 0x8011045Cu32 as HRESULT; +pub const COMADMIN_E_AMBIGUOUS_PARTITION_NAME: HRESULT = 0x8011045Du32 as HRESULT; +pub const COMADMIN_E_REGDB_NOTINITIALIZED: HRESULT = 0x80110472u32 as HRESULT; +pub const COMADMIN_E_REGDB_NOTOPEN: HRESULT = 0x80110473u32 as HRESULT; +pub const COMADMIN_E_REGDB_SYSTEMERR: HRESULT = 0x80110474u32 as HRESULT; +pub const COMADMIN_E_REGDB_ALREADYRUNNING: HRESULT = 0x80110475u32 as HRESULT; +pub const COMADMIN_E_MIG_VERSIONNOTSUPPORTED: HRESULT = 0x80110480u32 as HRESULT; +pub const COMADMIN_E_MIG_SCHEMANOTFOUND: HRESULT = 0x80110481u32 as HRESULT; +pub const COMADMIN_E_CAT_BITNESSMISMATCH: HRESULT = 0x80110482u32 as HRESULT; +pub const COMADMIN_E_CAT_UNACCEPTABLEBITNESS: HRESULT = 0x80110483u32 as HRESULT; +pub const COMADMIN_E_CAT_WRONGAPPBITNESS: HRESULT = 0x80110484u32 as HRESULT; +pub const COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED: HRESULT = 0x80110485u32 as HRESULT; +pub const COMADMIN_E_CAT_SERVERFAULT: HRESULT = 0x80110486u32 as HRESULT; +pub const COMQC_E_APPLICATION_NOT_QUEUED: HRESULT = 0x80110600u32 as HRESULT; +pub const COMQC_E_NO_QUEUEABLE_INTERFACES: HRESULT = 0x80110601u32 as HRESULT; +pub const COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE: HRESULT = 0x80110602u32 as HRESULT; +pub const COMQC_E_NO_IPERSISTSTREAM: HRESULT = 0x80110603u32 as HRESULT; +pub const COMQC_E_BAD_MESSAGE: HRESULT = 0x80110604u32 as HRESULT; +pub const COMQC_E_UNAUTHENTICATED: HRESULT = 0x80110605u32 as HRESULT; +pub const COMQC_E_UNTRUSTED_ENQUEUER: HRESULT = 0x80110606u32 as HRESULT; +pub const MSDTC_E_DUPLICATE_RESOURCE: HRESULT = 0x80110701u32 as HRESULT; +pub const COMADMIN_E_OBJECT_PARENT_MISSING: HRESULT = 0x80110808u32 as HRESULT; +pub const COMADMIN_E_OBJECT_DOES_NOT_EXIST: HRESULT = 0x80110809u32 as HRESULT; +pub const COMADMIN_E_APP_NOT_RUNNING: HRESULT = 0x8011080Au32 as HRESULT; +pub const COMADMIN_E_INVALID_PARTITION: HRESULT = 0x8011080Bu32 as HRESULT; +pub const COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE: HRESULT = 0x8011080Du32 as HRESULT; +pub const COMADMIN_E_USER_IN_SET: HRESULT = 0x8011080Eu32 as HRESULT; +pub const COMADMIN_E_CANTRECYCLELIBRARYAPPS: HRESULT = 0x8011080Fu32 as HRESULT; +pub const COMADMIN_E_CANTRECYCLESERVICEAPPS: HRESULT = 0x80110811u32 as HRESULT; +pub const COMADMIN_E_PROCESSALREADYRECYCLED: HRESULT = 0x80110812u32 as HRESULT; +pub const COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED: HRESULT = 0x80110813u32 as HRESULT; +pub const COMADMIN_E_CANTMAKEINPROCSERVICE: HRESULT = 0x80110814u32 as HRESULT; +pub const COMADMIN_E_PROGIDINUSEBYCLSID: HRESULT = 0x80110815u32 as HRESULT; +pub const COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET: HRESULT = 0x80110816u32 as HRESULT; +pub const COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED: HRESULT = 0x80110817u32 as HRESULT; +pub const COMADMIN_E_PARTITION_ACCESSDENIED: HRESULT = 0x80110818u32 as HRESULT; +pub const COMADMIN_E_PARTITION_MSI_ONLY: HRESULT = 0x80110819u32 as HRESULT; +pub const COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT: HRESULT = 0x8011081Au32 as HRESULT; +pub const COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS: HRESULT = 0x8011081Bu32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_SOURCE: HRESULT = 0x8011081Cu32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_DEST: HRESULT = 0x8011081Du32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_PRIVATE: HRESULT = 0x8011081Eu32 as HRESULT; +pub const COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET: HRESULT = 0x8011081Fu32 as HRESULT; +pub const COMADMIN_E_CANNOT_ALIAS_EVENTCLASS: HRESULT = 0x80110820u32 as HRESULT; +pub const COMADMIN_E_PRIVATE_ACCESSDENIED: HRESULT = 0x80110821u32 as HRESULT; +pub const COMADMIN_E_SAFERINVALID: HRESULT = 0x80110822u32 as HRESULT; +pub const COMADMIN_E_REGISTRY_ACCESSDENIED: HRESULT = 0x80110823u32 as HRESULT; +pub const COMADMIN_E_PARTITIONS_DISABLED: HRESULT = 0x80110824u32 as HRESULT; +pub const WER_S_REPORT_DEBUG: HRESULT = 0x001B0000; +pub const WER_S_REPORT_UPLOADED: HRESULT = 0x001B0001; +pub const WER_S_REPORT_QUEUED: HRESULT = 0x001B0002; +pub const WER_S_DISABLED: HRESULT = 0x001B0003; +pub const WER_S_SUSPENDED_UPLOAD: HRESULT = 0x001B0004; +pub const WER_S_DISABLED_QUEUE: HRESULT = 0x001B0005; +pub const WER_S_DISABLED_ARCHIVE: HRESULT = 0x001B0006; +pub const WER_S_REPORT_ASYNC: HRESULT = 0x001B0007; +pub const WER_S_IGNORE_ASSERT_INSTANCE: HRESULT = 0x001B0008; +pub const WER_S_IGNORE_ALL_ASSERTS: HRESULT = 0x001B0009; +pub const WER_S_ASSERT_CONTINUE: HRESULT = 0x001B000A; +pub const WER_S_THROTTLED: HRESULT = 0x001B000B; +pub const WER_E_CRASH_FAILURE: HRESULT = 0x801B8000u32 as HRESULT; +pub const WER_E_CANCELED: HRESULT = 0x801B8001u32 as HRESULT; +pub const WER_E_NETWORK_FAILURE: HRESULT = 0x801B8002u32 as HRESULT; +pub const WER_E_NOT_INITIALIZED: HRESULT = 0x801B8003u32 as HRESULT; +pub const WER_E_ALREADY_REPORTING: HRESULT = 0x801B8004u32 as HRESULT; +pub const WER_E_DUMP_THROTTLED: HRESULT = 0x801B8005u32 as HRESULT; +pub const ERROR_FLT_IO_COMPLETE: HRESULT = 0x001F0001; +pub const ERROR_FLT_NO_HANDLER_DEFINED: HRESULT = 0x801F0001u32 as HRESULT; +pub const ERROR_FLT_CONTEXT_ALREADY_DEFINED: HRESULT = 0x801F0002u32 as HRESULT; +pub const ERROR_FLT_INVALID_ASYNCHRONOUS_REQUEST: HRESULT = 0x801F0003u32 as HRESULT; +pub const ERROR_FLT_DISALLOW_FAST_IO: HRESULT = 0x801F0004u32 as HRESULT; +pub const ERROR_FLT_INVALID_NAME_REQUEST: HRESULT = 0x801F0005u32 as HRESULT; +pub const ERROR_FLT_NOT_SAFE_TO_POST_OPERATION: HRESULT = 0x801F0006u32 as HRESULT; +pub const ERROR_FLT_NOT_INITIALIZED: HRESULT = 0x801F0007u32 as HRESULT; +pub const ERROR_FLT_FILTER_NOT_READY: HRESULT = 0x801F0008u32 as HRESULT; +pub const ERROR_FLT_POST_OPERATION_CLEANUP: HRESULT = 0x801F0009u32 as HRESULT; +pub const ERROR_FLT_INTERNAL_ERROR: HRESULT = 0x801F000Au32 as HRESULT; +pub const ERROR_FLT_DELETING_OBJECT: HRESULT = 0x801F000Bu32 as HRESULT; +pub const ERROR_FLT_MUST_BE_NONPAGED_POOL: HRESULT = 0x801F000Cu32 as HRESULT; +pub const ERROR_FLT_DUPLICATE_ENTRY: HRESULT = 0x801F000Du32 as HRESULT; +pub const ERROR_FLT_CBDQ_DISABLED: HRESULT = 0x801F000Eu32 as HRESULT; +pub const ERROR_FLT_DO_NOT_ATTACH: HRESULT = 0x801F000Fu32 as HRESULT; +pub const ERROR_FLT_DO_NOT_DETACH: HRESULT = 0x801F0010u32 as HRESULT; +pub const ERROR_FLT_INSTANCE_ALTITUDE_COLLISION: HRESULT = 0x801F0011u32 as HRESULT; +pub const ERROR_FLT_INSTANCE_NAME_COLLISION: HRESULT = 0x801F0012u32 as HRESULT; +pub const ERROR_FLT_FILTER_NOT_FOUND: HRESULT = 0x801F0013u32 as HRESULT; +pub const ERROR_FLT_VOLUME_NOT_FOUND: HRESULT = 0x801F0014u32 as HRESULT; +pub const ERROR_FLT_INSTANCE_NOT_FOUND: HRESULT = 0x801F0015u32 as HRESULT; +pub const ERROR_FLT_CONTEXT_ALLOCATION_NOT_FOUND: HRESULT = 0x801F0016u32 as HRESULT; +pub const ERROR_FLT_INVALID_CONTEXT_REGISTRATION: HRESULT = 0x801F0017u32 as HRESULT; +pub const ERROR_FLT_NAME_CACHE_MISS: HRESULT = 0x801F0018u32 as HRESULT; +pub const ERROR_FLT_NO_DEVICE_OBJECT: HRESULT = 0x801F0019u32 as HRESULT; +pub const ERROR_FLT_VOLUME_ALREADY_MOUNTED: HRESULT = 0x801F001Au32 as HRESULT; +pub const ERROR_FLT_ALREADY_ENLISTED: HRESULT = 0x801F001Bu32 as HRESULT; +pub const ERROR_FLT_CONTEXT_ALREADY_LINKED: HRESULT = 0x801F001Cu32 as HRESULT; +pub const ERROR_FLT_NO_WAITER_FOR_REPLY: HRESULT = 0x801F0020u32 as HRESULT; +pub const ERROR_FLT_REGISTRATION_BUSY: HRESULT = 0x801F0023u32 as HRESULT; +pub const ERROR_HUNG_DISPLAY_DRIVER_THREAD: HRESULT = 0x80260001u32 as HRESULT; +pub const DWM_E_COMPOSITIONDISABLED: HRESULT = 0x80263001u32 as HRESULT; +pub const DWM_E_REMOTING_NOT_SUPPORTED: HRESULT = 0x80263002u32 as HRESULT; +pub const DWM_E_NO_REDIRECTION_SURFACE_AVAILABLE: HRESULT = 0x80263003u32 as HRESULT; +pub const DWM_E_NOT_QUEUING_PRESENTS: HRESULT = 0x80263004u32 as HRESULT; +pub const DWM_E_ADAPTER_NOT_FOUND: HRESULT = 0x80263005u32 as HRESULT; +pub const DWM_S_GDI_REDIRECTION_SURFACE: HRESULT = 0x00263005; +pub const DWM_E_TEXTURE_TOO_LARGE: HRESULT = 0x80263007u32 as HRESULT; +pub const ERROR_MONITOR_NO_DESCRIPTOR: HRESULT = 0x80261001u32 as HRESULT; +pub const ERROR_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT: HRESULT = 0x80261002u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_DESCRIPTOR_CHECKSUM: HRESULT = 0xC0261003u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_STANDARD_TIMING_BLOCK: HRESULT = 0xC0261004u32 as HRESULT; +pub const ERROR_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED: HRESULT = 0xC0261005u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK: HRESULT = 0xC0261006u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK: HRESULT = 0xC0261007u32 as HRESULT; +pub const ERROR_MONITOR_NO_MORE_DESCRIPTOR_DATA: HRESULT = 0xC0261008u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_DETAILED_TIMING_BLOCK: HRESULT = 0xC0261009u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_MANUFACTURE_DATE: HRESULT = 0xC026100Au32 as HRESULT; +pub const ERROR_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER: HRESULT = 0xC0262000u32 as HRESULT; +pub const ERROR_GRAPHICS_INSUFFICIENT_DMA_BUFFER: HRESULT = 0xC0262001u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_DISPLAY_ADAPTER: HRESULT = 0xC0262002u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_WAS_RESET: HRESULT = 0xC0262003u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_DRIVER_MODEL: HRESULT = 0xC0262004u32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_MODE_CHANGED: HRESULT = 0xC0262005u32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_OCCLUDED: HRESULT = 0xC0262006u32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_DENIED: HRESULT = 0xC0262007u32 as HRESULT; +pub const ERROR_GRAPHICS_CANNOTCOLORCONVERT: HRESULT = 0xC0262008u32 as HRESULT; +pub const ERROR_GRAPHICS_DRIVER_MISMATCH: HRESULT = 0xC0262009u32 as HRESULT; +pub const ERROR_GRAPHICS_PARTIAL_DATA_POPULATED: HRESULT = 0x4026200A; +pub const ERROR_GRAPHICS_PRESENT_REDIRECTION_DISABLED: HRESULT = 0xC026200Bu32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_UNOCCLUDED: HRESULT = 0xC026200Cu32 as HRESULT; +pub const ERROR_GRAPHICS_WINDOWDC_NOT_AVAILABLE: HRESULT = 0xC026200Du32 as HRESULT; +pub const ERROR_GRAPHICS_WINDOWLESS_PRESENT_DISABLED: HRESULT = 0xC026200Eu32 as HRESULT; +pub const ERROR_GRAPHICS_NO_VIDEO_MEMORY: HRESULT = 0xC0262100u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_LOCK_MEMORY: HRESULT = 0xC0262101u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_BUSY: HRESULT = 0xC0262102u32 as HRESULT; +pub const ERROR_GRAPHICS_TOO_MANY_REFERENCES: HRESULT = 0xC0262103u32 as HRESULT; +pub const ERROR_GRAPHICS_TRY_AGAIN_LATER: HRESULT = 0xC0262104u32 as HRESULT; +pub const ERROR_GRAPHICS_TRY_AGAIN_NOW: HRESULT = 0xC0262105u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_INVALID: HRESULT = 0xC0262106u32 as HRESULT; +pub const ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE: HRESULT = 0xC0262107u32 as HRESULT; +pub const ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED: HRESULT = 0xC0262108u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION: HRESULT = 0xC0262109u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ALLOCATION_USAGE: HRESULT = 0xC0262110u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION: HRESULT = 0xC0262111u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_CLOSED: HRESULT = 0xC0262112u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ALLOCATION_INSTANCE: HRESULT = 0xC0262113u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ALLOCATION_HANDLE: HRESULT = 0xC0262114u32 as HRESULT; +pub const ERROR_GRAPHICS_WRONG_ALLOCATION_DEVICE: HRESULT = 0xC0262115u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_CONTENT_LOST: HRESULT = 0xC0262116u32 as HRESULT; +pub const ERROR_GRAPHICS_GPU_EXCEPTION_ON_DEVICE: HRESULT = 0xC0262200u32 as HRESULT; +pub const ERROR_GRAPHICS_SKIP_ALLOCATION_PREPARATION: HRESULT = 0x40262201; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY: HRESULT = 0xC0262300u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED: HRESULT = 0xC0262301u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED: HRESULT = 0xC0262302u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN: HRESULT = 0xC0262303u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE: HRESULT = 0xC0262304u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET: HRESULT = 0xC0262305u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED: HRESULT = 0xC0262306u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_NOT_PINNED: HRESULT = 0x00262307; +pub const ERROR_GRAPHICS_INVALID_VIDPN_SOURCEMODESET: HRESULT = 0xC0262308u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TARGETMODESET: HRESULT = 0xC0262309u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_FREQUENCY: HRESULT = 0xC026230Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ACTIVE_REGION: HRESULT = 0xC026230Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_TOTAL_REGION: HRESULT = 0xC026230Cu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE: HRESULT = 0xC0262310u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE: HRESULT = 0xC0262311u32 as HRESULT; +pub const ERROR_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET: HRESULT = 0xC0262312u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY: HRESULT = 0xC0262313u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_ALREADY_IN_MODESET: HRESULT = 0xC0262314u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET: HRESULT = 0xC0262315u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET: HRESULT = 0xC0262316u32 as HRESULT; +pub const ERROR_GRAPHICS_SOURCE_ALREADY_IN_SET: HRESULT = 0xC0262317u32 as HRESULT; +pub const ERROR_GRAPHICS_TARGET_ALREADY_IN_SET: HRESULT = 0xC0262318u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN_PRESENT_PATH: HRESULT = 0xC0262319u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY: HRESULT = 0xC026231Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET: HRESULT = 0xC026231Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE: HRESULT = 0xC026231Cu32 as HRESULT; +pub const ERROR_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET: HRESULT = 0xC026231Du32 as HRESULT; +pub const ERROR_GRAPHICS_NO_PREFERRED_MODE: HRESULT = 0x0026231E; +pub const ERROR_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET: HRESULT = 0xC026231Fu32 as HRESULT; +pub const ERROR_GRAPHICS_STALE_MODESET: HRESULT = 0xC0262320u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_SOURCEMODESET: HRESULT = 0xC0262321u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_SOURCE_MODE: HRESULT = 0xC0262322u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN: HRESULT = 0xC0262323u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_ID_MUST_BE_UNIQUE: HRESULT = 0xC0262324u32 as HRESULT; +pub const ERROR_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION: HRESULT = 0xC0262325u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES: HRESULT = 0xC0262326u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_NOT_IN_TOPOLOGY: HRESULT = 0xC0262327u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE: HRESULT = 0xC0262328u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET: HRESULT = 0xC0262329u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITORDESCRIPTORSET: HRESULT = 0xC026232Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITORDESCRIPTOR: HRESULT = 0xC026232Bu32 as HRESULT; +pub const ERROR_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET: HRESULT = 0xC026232Cu32 as HRESULT; +pub const ERROR_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET: HRESULT = 0xC026232Du32 as HRESULT; +pub const ERROR_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE: HRESULT = 0xC026232Eu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE: HRESULT = 0xC026232Fu32 as HRESULT; +pub const ERROR_GRAPHICS_RESOURCES_NOT_RELATED: HRESULT = 0xC0262330u32 as HRESULT; +pub const ERROR_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE: HRESULT = 0xC0262331u32 as HRESULT; +pub const ERROR_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE: HRESULT = 0xC0262332u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET: HRESULT = 0xC0262333u32 as HRESULT; +pub const ERROR_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER: HRESULT = 0xC0262334u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_VIDPNMGR: HRESULT = 0xC0262335u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_ACTIVE_VIDPN: HRESULT = 0xC0262336u32 as HRESULT; +pub const ERROR_GRAPHICS_STALE_VIDPN_TOPOLOGY: HRESULT = 0xC0262337u32 as HRESULT; +pub const ERROR_GRAPHICS_MONITOR_NOT_CONNECTED: HRESULT = 0xC0262338u32 as HRESULT; +pub const ERROR_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY: HRESULT = 0xC0262339u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE: HRESULT = 0xC026233Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VISIBLEREGION_SIZE: HRESULT = 0xC026233Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_STRIDE: HRESULT = 0xC026233Cu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PIXELFORMAT: HRESULT = 0xC026233Du32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_COLORBASIS: HRESULT = 0xC026233Eu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PIXELVALUEACCESSMODE: HRESULT = 0xC026233Fu32 as HRESULT; +pub const ERROR_GRAPHICS_TARGET_NOT_IN_TOPOLOGY: HRESULT = 0xC0262340u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT: HRESULT = 0xC0262341u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: HRESULT = 0xC0262342u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN: HRESULT = 0xC0262343u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL: HRESULT = 0xC0262344u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION: HRESULT = 0xC0262345u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED: HRESULT = 0xC0262346u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_GAMMA_RAMP: HRESULT = 0xC0262347u32 as HRESULT; +pub const ERROR_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED: HRESULT = 0xC0262348u32 as HRESULT; +pub const ERROR_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED: HRESULT = 0xC0262349u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_NOT_IN_MODESET: HRESULT = 0xC026234Au32 as HRESULT; +pub const ERROR_GRAPHICS_DATASET_IS_EMPTY: HRESULT = 0x0026234B; +pub const ERROR_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET: HRESULT = 0x0026234C; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON: HRESULT = 0xC026234Du32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PATH_CONTENT_TYPE: HRESULT = 0xC026234Eu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_COPYPROTECTION_TYPE: HRESULT = 0xC026234Fu32 as HRESULT; +pub const ERROR_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS: HRESULT = 0xC0262350u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED: HRESULT = 0x00262351; +pub const ERROR_GRAPHICS_INVALID_SCANLINE_ORDERING: HRESULT = 0xC0262352u32 as HRESULT; +pub const ERROR_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED: HRESULT = 0xC0262353u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS: HRESULT = 0xC0262354u32 as HRESULT; +pub const ERROR_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT: HRESULT = 0xC0262355u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM: HRESULT = 0xC0262356u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN: HRESULT = 0xC0262357u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT: HRESULT = 0xC0262358u32 as HRESULT; +pub const ERROR_GRAPHICS_MAX_NUM_PATHS_REACHED: HRESULT = 0xC0262359u32 as HRESULT; +pub const ERROR_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION: HRESULT = 0xC026235Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_CLIENT_TYPE: HRESULT = 0xC026235Bu32 as HRESULT; +pub const ERROR_GRAPHICS_CLIENTVIDPN_NOT_SET: HRESULT = 0xC026235Cu32 as HRESULT; +pub const ERROR_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED: HRESULT = 0xC0262400u32 as HRESULT; +pub const ERROR_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED: HRESULT = 0xC0262401u32 as HRESULT; +pub const ERROR_GRAPHICS_UNKNOWN_CHILD_STATUS: HRESULT = 0x4026242F; +pub const ERROR_GRAPHICS_NOT_A_LINKED_ADAPTER: HRESULT = 0xC0262430u32 as HRESULT; +pub const ERROR_GRAPHICS_LEADLINK_NOT_ENUMERATED: HRESULT = 0xC0262431u32 as HRESULT; +pub const ERROR_GRAPHICS_CHAINLINKS_NOT_ENUMERATED: HRESULT = 0xC0262432u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_CHAIN_NOT_READY: HRESULT = 0xC0262433u32 as HRESULT; +pub const ERROR_GRAPHICS_CHAINLINKS_NOT_STARTED: HRESULT = 0xC0262434u32 as HRESULT; +pub const ERROR_GRAPHICS_CHAINLINKS_NOT_POWERED_ON: HRESULT = 0xC0262435u32 as HRESULT; +pub const ERROR_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE: HRESULT = 0xC0262436u32 as HRESULT; +pub const ERROR_GRAPHICS_LEADLINK_START_DEFERRED: HRESULT = 0x40262437; +pub const ERROR_GRAPHICS_NOT_POST_DEVICE_DRIVER: HRESULT = 0xC0262438u32 as HRESULT; +pub const ERROR_GRAPHICS_POLLING_TOO_FREQUENTLY: HRESULT = 0x40262439; +pub const ERROR_GRAPHICS_START_DEFERRED: HRESULT = 0x4026243A; +pub const ERROR_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED: HRESULT = 0xC026243Bu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_NOT_SUPPORTED: HRESULT = 0xC0262500u32 as HRESULT; +pub const ERROR_GRAPHICS_COPP_NOT_SUPPORTED: HRESULT = 0xC0262501u32 as HRESULT; +pub const ERROR_GRAPHICS_UAB_NOT_SUPPORTED: HRESULT = 0xC0262502u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS: HRESULT = 0xC0262503u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_NO_VIDEO_OUTPUTS_EXIST: HRESULT = 0xC0262505u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INTERNAL_ERROR: HRESULT = 0xC026250Bu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_HANDLE: HRESULT = 0xC026250Cu32 as HRESULT; +pub const ERROR_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH: HRESULT = 0xC026250Eu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_SPANNING_MODE_ENABLED: HRESULT = 0xC026250Fu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_THEATER_MODE_ENABLED: HRESULT = 0xC0262510u32 as HRESULT; +pub const ERROR_GRAPHICS_PVP_HFS_FAILED: HRESULT = 0xC0262511u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_SRM: HRESULT = 0xC0262512u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP: HRESULT = 0xC0262513u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP: HRESULT = 0xC0262514u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA: HRESULT = 0xC0262515u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_HDCP_SRM_NEVER_SET: HRESULT = 0xC0262516u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_RESOLUTION_TOO_HIGH: HRESULT = 0xC0262517u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE: HRESULT = 0xC0262518u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_NO_LONGER_EXISTS: HRESULT = 0xC026251Au32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS: HRESULT = 0xC026251Bu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS: HRESULT = 0xC026251Cu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST: HRESULT = 0xC026251Du32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR: HRESULT = 0xC026251Eu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS: HRESULT = 0xC026251Fu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED: HRESULT = 0xC0262520u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST: HRESULT = 0xC0262521u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_NOT_SUPPORTED: HRESULT = 0xC0262580u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST: HRESULT = 0xC0262581u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA: HRESULT = 0xC0262582u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_ERROR_RECEIVING_DATA: HRESULT = 0xC0262583u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED: HRESULT = 0xC0262584u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_DATA: HRESULT = 0xC0262585u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE: HRESULT = 0xC0262586u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INVALID_CAPABILITIES_STRING: HRESULT = 0xC0262587u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INTERNAL_ERROR: HRESULT = 0xC0262588u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND: HRESULT = 0xC0262589u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH: HRESULT = 0xC026258Au32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM: HRESULT = 0xC026258Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE: HRESULT = 0xC026258Cu32 as HRESULT; +pub const ERROR_GRAPHICS_MONITOR_NO_LONGER_EXISTS: HRESULT = 0xC026258Du32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_CURRENT_CURRENT_VALUE_GREATER_THAN_MAXIMUM_VALUE: HRESULT = 0xC02625D8u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INVALID_VCP_VERSION: HRESULT = 0xC02625D9u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: HRESULT = 0xC02625DAu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_MCCS_VERSION_MISMATCH: HRESULT = 0xC02625DBu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_UNSUPPORTED_MCCS_VERSION: HRESULT = 0xC02625DCu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: HRESULT = 0xC02625DEu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_UNSUPPORTED_COLOR_TEMPERATURE: HRESULT = 0xC02625DFu32 as HRESULT; +pub const ERROR_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED: HRESULT = 0xC02625E0u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME: HRESULT = 0xC02625E1u32 as HRESULT; +pub const ERROR_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP: HRESULT = 0xC02625E2u32 as HRESULT; +pub const ERROR_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED: HRESULT = 0xC02625E3u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_POINTER: HRESULT = 0xC02625E4u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE: HRESULT = 0xC02625E5u32 as HRESULT; +pub const ERROR_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL: HRESULT = 0xC02625E6u32 as HRESULT; +pub const ERROR_GRAPHICS_INTERNAL_ERROR: HRESULT = 0xC02625E7u32 as HRESULT; +pub const ERROR_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS: HRESULT = 0xC02605E8u32 as HRESULT; +pub const NAP_E_INVALID_PACKET: HRESULT = 0x80270001u32 as HRESULT; +pub const NAP_E_MISSING_SOH: HRESULT = 0x80270002u32 as HRESULT; +pub const NAP_E_CONFLICTING_ID: HRESULT = 0x80270003u32 as HRESULT; +pub const NAP_E_NO_CACHED_SOH: HRESULT = 0x80270004u32 as HRESULT; +pub const NAP_E_STILL_BOUND: HRESULT = 0x80270005u32 as HRESULT; +pub const NAP_E_NOT_REGISTERED: HRESULT = 0x80270006u32 as HRESULT; +pub const NAP_E_NOT_INITIALIZED: HRESULT = 0x80270007u32 as HRESULT; +pub const NAP_E_MISMATCHED_ID: HRESULT = 0x80270008u32 as HRESULT; +pub const NAP_E_NOT_PENDING: HRESULT = 0x80270009u32 as HRESULT; +pub const NAP_E_ID_NOT_FOUND: HRESULT = 0x8027000Au32 as HRESULT; +pub const NAP_E_MAXSIZE_TOO_SMALL: HRESULT = 0x8027000Bu32 as HRESULT; +pub const NAP_E_SERVICE_NOT_RUNNING: HRESULT = 0x8027000Cu32 as HRESULT; +pub const NAP_S_CERT_ALREADY_PRESENT: HRESULT = 0x0027000D; +pub const NAP_E_ENTITY_DISABLED: HRESULT = 0x8027000Eu32 as HRESULT; +pub const NAP_E_NETSH_GROUPPOLICY_ERROR: HRESULT = 0x8027000Fu32 as HRESULT; +pub const NAP_E_TOO_MANY_CALLS: HRESULT = 0x80270010u32 as HRESULT; +pub const NAP_E_SHV_CONFIG_EXISTED: HRESULT = 0x80270011u32 as HRESULT; +pub const NAP_E_SHV_CONFIG_NOT_FOUND: HRESULT = 0x80270012u32 as HRESULT; +pub const NAP_E_SHV_TIMEOUT: HRESULT = 0x80270013u32 as HRESULT; +pub const TPM_E_ERROR_MASK: HRESULT = 0x80280000u32 as HRESULT; +pub const TPM_E_AUTHFAIL: HRESULT = 0x80280001u32 as HRESULT; +pub const TPM_E_BADINDEX: HRESULT = 0x80280002u32 as HRESULT; +pub const TPM_E_BAD_PARAMETER: HRESULT = 0x80280003u32 as HRESULT; +pub const TPM_E_AUDITFAILURE: HRESULT = 0x80280004u32 as HRESULT; +pub const TPM_E_CLEAR_DISABLED: HRESULT = 0x80280005u32 as HRESULT; +pub const TPM_E_DEACTIVATED: HRESULT = 0x80280006u32 as HRESULT; +pub const TPM_E_DISABLED: HRESULT = 0x80280007u32 as HRESULT; +pub const TPM_E_DISABLED_CMD: HRESULT = 0x80280008u32 as HRESULT; +pub const TPM_E_FAIL: HRESULT = 0x80280009u32 as HRESULT; +pub const TPM_E_BAD_ORDINAL: HRESULT = 0x8028000Au32 as HRESULT; +pub const TPM_E_INSTALL_DISABLED: HRESULT = 0x8028000Bu32 as HRESULT; +pub const TPM_E_INVALID_KEYHANDLE: HRESULT = 0x8028000Cu32 as HRESULT; +pub const TPM_E_KEYNOTFOUND: HRESULT = 0x8028000Du32 as HRESULT; +pub const TPM_E_INAPPROPRIATE_ENC: HRESULT = 0x8028000Eu32 as HRESULT; +pub const TPM_E_MIGRATEFAIL: HRESULT = 0x8028000Fu32 as HRESULT; +pub const TPM_E_INVALID_PCR_INFO: HRESULT = 0x80280010u32 as HRESULT; +pub const TPM_E_NOSPACE: HRESULT = 0x80280011u32 as HRESULT; +pub const TPM_E_NOSRK: HRESULT = 0x80280012u32 as HRESULT; +pub const TPM_E_NOTSEALED_BLOB: HRESULT = 0x80280013u32 as HRESULT; +pub const TPM_E_OWNER_SET: HRESULT = 0x80280014u32 as HRESULT; +pub const TPM_E_RESOURCES: HRESULT = 0x80280015u32 as HRESULT; +pub const TPM_E_SHORTRANDOM: HRESULT = 0x80280016u32 as HRESULT; +pub const TPM_E_SIZE: HRESULT = 0x80280017u32 as HRESULT; +pub const TPM_E_WRONGPCRVAL: HRESULT = 0x80280018u32 as HRESULT; +pub const TPM_E_BAD_PARAM_SIZE: HRESULT = 0x80280019u32 as HRESULT; +pub const TPM_E_SHA_THREAD: HRESULT = 0x8028001Au32 as HRESULT; +pub const TPM_E_SHA_ERROR: HRESULT = 0x8028001Bu32 as HRESULT; +pub const TPM_E_FAILEDSELFTEST: HRESULT = 0x8028001Cu32 as HRESULT; +pub const TPM_E_AUTH2FAIL: HRESULT = 0x8028001Du32 as HRESULT; +pub const TPM_E_BADTAG: HRESULT = 0x8028001Eu32 as HRESULT; +pub const TPM_E_IOERROR: HRESULT = 0x8028001Fu32 as HRESULT; +pub const TPM_E_ENCRYPT_ERROR: HRESULT = 0x80280020u32 as HRESULT; +pub const TPM_E_DECRYPT_ERROR: HRESULT = 0x80280021u32 as HRESULT; +pub const TPM_E_INVALID_AUTHHANDLE: HRESULT = 0x80280022u32 as HRESULT; +pub const TPM_E_NO_ENDORSEMENT: HRESULT = 0x80280023u32 as HRESULT; +pub const TPM_E_INVALID_KEYUSAGE: HRESULT = 0x80280024u32 as HRESULT; +pub const TPM_E_WRONG_ENTITYTYPE: HRESULT = 0x80280025u32 as HRESULT; +pub const TPM_E_INVALID_POSTINIT: HRESULT = 0x80280026u32 as HRESULT; +pub const TPM_E_INAPPROPRIATE_SIG: HRESULT = 0x80280027u32 as HRESULT; +pub const TPM_E_BAD_KEY_PROPERTY: HRESULT = 0x80280028u32 as HRESULT; +pub const TPM_E_BAD_MIGRATION: HRESULT = 0x80280029u32 as HRESULT; +pub const TPM_E_BAD_SCHEME: HRESULT = 0x8028002Au32 as HRESULT; +pub const TPM_E_BAD_DATASIZE: HRESULT = 0x8028002Bu32 as HRESULT; +pub const TPM_E_BAD_MODE: HRESULT = 0x8028002Cu32 as HRESULT; +pub const TPM_E_BAD_PRESENCE: HRESULT = 0x8028002Du32 as HRESULT; +pub const TPM_E_BAD_VERSION: HRESULT = 0x8028002Eu32 as HRESULT; +pub const TPM_E_NO_WRAP_TRANSPORT: HRESULT = 0x8028002Fu32 as HRESULT; +pub const TPM_E_AUDITFAIL_UNSUCCESSFUL: HRESULT = 0x80280030u32 as HRESULT; +pub const TPM_E_AUDITFAIL_SUCCESSFUL: HRESULT = 0x80280031u32 as HRESULT; +pub const TPM_E_NOTRESETABLE: HRESULT = 0x80280032u32 as HRESULT; +pub const TPM_E_NOTLOCAL: HRESULT = 0x80280033u32 as HRESULT; +pub const TPM_E_BAD_TYPE: HRESULT = 0x80280034u32 as HRESULT; +pub const TPM_E_INVALID_RESOURCE: HRESULT = 0x80280035u32 as HRESULT; +pub const TPM_E_NOTFIPS: HRESULT = 0x80280036u32 as HRESULT; +pub const TPM_E_INVALID_FAMILY: HRESULT = 0x80280037u32 as HRESULT; +pub const TPM_E_NO_NV_PERMISSION: HRESULT = 0x80280038u32 as HRESULT; +pub const TPM_E_REQUIRES_SIGN: HRESULT = 0x80280039u32 as HRESULT; +pub const TPM_E_KEY_NOTSUPPORTED: HRESULT = 0x8028003Au32 as HRESULT; +pub const TPM_E_AUTH_CONFLICT: HRESULT = 0x8028003Bu32 as HRESULT; +pub const TPM_E_AREA_LOCKED: HRESULT = 0x8028003Cu32 as HRESULT; +pub const TPM_E_BAD_LOCALITY: HRESULT = 0x8028003Du32 as HRESULT; +pub const TPM_E_READ_ONLY: HRESULT = 0x8028003Eu32 as HRESULT; +pub const TPM_E_PER_NOWRITE: HRESULT = 0x8028003Fu32 as HRESULT; +pub const TPM_E_FAMILYCOUNT: HRESULT = 0x80280040u32 as HRESULT; +pub const TPM_E_WRITE_LOCKED: HRESULT = 0x80280041u32 as HRESULT; +pub const TPM_E_BAD_ATTRIBUTES: HRESULT = 0x80280042u32 as HRESULT; +pub const TPM_E_INVALID_STRUCTURE: HRESULT = 0x80280043u32 as HRESULT; +pub const TPM_E_KEY_OWNER_CONTROL: HRESULT = 0x80280044u32 as HRESULT; +pub const TPM_E_BAD_COUNTER: HRESULT = 0x80280045u32 as HRESULT; +pub const TPM_E_NOT_FULLWRITE: HRESULT = 0x80280046u32 as HRESULT; +pub const TPM_E_CONTEXT_GAP: HRESULT = 0x80280047u32 as HRESULT; +pub const TPM_E_MAXNVWRITES: HRESULT = 0x80280048u32 as HRESULT; +pub const TPM_E_NOOPERATOR: HRESULT = 0x80280049u32 as HRESULT; +pub const TPM_E_RESOURCEMISSING: HRESULT = 0x8028004Au32 as HRESULT; +pub const TPM_E_DELEGATE_LOCK: HRESULT = 0x8028004Bu32 as HRESULT; +pub const TPM_E_DELEGATE_FAMILY: HRESULT = 0x8028004Cu32 as HRESULT; +pub const TPM_E_DELEGATE_ADMIN: HRESULT = 0x8028004Du32 as HRESULT; +pub const TPM_E_TRANSPORT_NOTEXCLUSIVE: HRESULT = 0x8028004Eu32 as HRESULT; +pub const TPM_E_OWNER_CONTROL: HRESULT = 0x8028004Fu32 as HRESULT; +pub const TPM_E_DAA_RESOURCES: HRESULT = 0x80280050u32 as HRESULT; +pub const TPM_E_DAA_INPUT_DATA0: HRESULT = 0x80280051u32 as HRESULT; +pub const TPM_E_DAA_INPUT_DATA1: HRESULT = 0x80280052u32 as HRESULT; +pub const TPM_E_DAA_ISSUER_SETTINGS: HRESULT = 0x80280053u32 as HRESULT; +pub const TPM_E_DAA_TPM_SETTINGS: HRESULT = 0x80280054u32 as HRESULT; +pub const TPM_E_DAA_STAGE: HRESULT = 0x80280055u32 as HRESULT; +pub const TPM_E_DAA_ISSUER_VALIDITY: HRESULT = 0x80280056u32 as HRESULT; +pub const TPM_E_DAA_WRONG_W: HRESULT = 0x80280057u32 as HRESULT; +pub const TPM_E_BAD_HANDLE: HRESULT = 0x80280058u32 as HRESULT; +pub const TPM_E_BAD_DELEGATE: HRESULT = 0x80280059u32 as HRESULT; +pub const TPM_E_BADCONTEXT: HRESULT = 0x8028005Au32 as HRESULT; +pub const TPM_E_TOOMANYCONTEXTS: HRESULT = 0x8028005Bu32 as HRESULT; +pub const TPM_E_MA_TICKET_SIGNATURE: HRESULT = 0x8028005Cu32 as HRESULT; +pub const TPM_E_MA_DESTINATION: HRESULT = 0x8028005Du32 as HRESULT; +pub const TPM_E_MA_SOURCE: HRESULT = 0x8028005Eu32 as HRESULT; +pub const TPM_E_MA_AUTHORITY: HRESULT = 0x8028005Fu32 as HRESULT; +pub const TPM_E_PERMANENTEK: HRESULT = 0x80280061u32 as HRESULT; +pub const TPM_E_BAD_SIGNATURE: HRESULT = 0x80280062u32 as HRESULT; +pub const TPM_E_NOCONTEXTSPACE: HRESULT = 0x80280063u32 as HRESULT; +pub const TPM_E_COMMAND_BLOCKED: HRESULT = 0x80280400u32 as HRESULT; +pub const TPM_E_INVALID_HANDLE: HRESULT = 0x80280401u32 as HRESULT; +pub const TPM_E_DUPLICATE_VHANDLE: HRESULT = 0x80280402u32 as HRESULT; +pub const TPM_E_EMBEDDED_COMMAND_BLOCKED: HRESULT = 0x80280403u32 as HRESULT; +pub const TPM_E_EMBEDDED_COMMAND_UNSUPPORTED: HRESULT = 0x80280404u32 as HRESULT; +pub const TPM_E_RETRY: HRESULT = 0x80280800u32 as HRESULT; +pub const TPM_E_NEEDS_SELFTEST: HRESULT = 0x80280801u32 as HRESULT; +pub const TPM_E_DOING_SELFTEST: HRESULT = 0x80280802u32 as HRESULT; +pub const TPM_E_DEFEND_LOCK_RUNNING: HRESULT = 0x80280803u32 as HRESULT; +pub const TBS_E_INTERNAL_ERROR: HRESULT = 0x80284001u32 as HRESULT; +pub const TBS_E_BAD_PARAMETER: HRESULT = 0x80284002u32 as HRESULT; +pub const TBS_E_INVALID_OUTPUT_POINTER: HRESULT = 0x80284003u32 as HRESULT; +pub const TBS_E_INVALID_CONTEXT: HRESULT = 0x80284004u32 as HRESULT; +pub const TBS_E_INSUFFICIENT_BUFFER: HRESULT = 0x80284005u32 as HRESULT; +pub const TBS_E_IOERROR: HRESULT = 0x80284006u32 as HRESULT; +pub const TBS_E_INVALID_CONTEXT_PARAM: HRESULT = 0x80284007u32 as HRESULT; +pub const TBS_E_SERVICE_NOT_RUNNING: HRESULT = 0x80284008u32 as HRESULT; +pub const TBS_E_TOO_MANY_TBS_CONTEXTS: HRESULT = 0x80284009u32 as HRESULT; +pub const TBS_E_TOO_MANY_RESOURCES: HRESULT = 0x8028400Au32 as HRESULT; +pub const TBS_E_SERVICE_START_PENDING: HRESULT = 0x8028400Bu32 as HRESULT; +pub const TBS_E_PPI_NOT_SUPPORTED: HRESULT = 0x8028400Cu32 as HRESULT; +pub const TBS_E_COMMAND_CANCELED: HRESULT = 0x8028400Du32 as HRESULT; +pub const TBS_E_BUFFER_TOO_LARGE: HRESULT = 0x8028400Eu32 as HRESULT; +pub const TBS_E_TPM_NOT_FOUND: HRESULT = 0x8028400Fu32 as HRESULT; +pub const TBS_E_SERVICE_DISABLED: HRESULT = 0x80284010u32 as HRESULT; +pub const TBS_E_NO_EVENT_LOG: HRESULT = 0x80284011u32 as HRESULT; +pub const TBS_E_ACCESS_DENIED: HRESULT = 0x80284012u32 as HRESULT; +pub const TBS_E_PROVISIONING_NOT_ALLOWED: HRESULT = 0x80284013u32 as HRESULT; +pub const TBS_E_PPI_FUNCTION_UNSUPPORTED: HRESULT = 0x80284014u32 as HRESULT; +pub const TBS_E_OWNERAUTH_NOT_FOUND: HRESULT = 0x80284015u32 as HRESULT; +pub const TBS_E_PROVISIONING_INCOMPLETE: HRESULT = 0x80284016u32 as HRESULT; +pub const TPMAPI_E_INVALID_STATE: HRESULT = 0x80290100u32 as HRESULT; +pub const TPMAPI_E_NOT_ENOUGH_DATA: HRESULT = 0x80290101u32 as HRESULT; +pub const TPMAPI_E_TOO_MUCH_DATA: HRESULT = 0x80290102u32 as HRESULT; +pub const TPMAPI_E_INVALID_OUTPUT_POINTER: HRESULT = 0x80290103u32 as HRESULT; +pub const TPMAPI_E_INVALID_PARAMETER: HRESULT = 0x80290104u32 as HRESULT; +pub const TPMAPI_E_OUT_OF_MEMORY: HRESULT = 0x80290105u32 as HRESULT; +pub const TPMAPI_E_BUFFER_TOO_SMALL: HRESULT = 0x80290106u32 as HRESULT; +pub const TPMAPI_E_INTERNAL_ERROR: HRESULT = 0x80290107u32 as HRESULT; +pub const TPMAPI_E_ACCESS_DENIED: HRESULT = 0x80290108u32 as HRESULT; +pub const TPMAPI_E_AUTHORIZATION_FAILED: HRESULT = 0x80290109u32 as HRESULT; +pub const TPMAPI_E_INVALID_CONTEXT_HANDLE: HRESULT = 0x8029010Au32 as HRESULT; +pub const TPMAPI_E_TBS_COMMUNICATION_ERROR: HRESULT = 0x8029010Bu32 as HRESULT; +pub const TPMAPI_E_TPM_COMMAND_ERROR: HRESULT = 0x8029010Cu32 as HRESULT; +pub const TPMAPI_E_MESSAGE_TOO_LARGE: HRESULT = 0x8029010Du32 as HRESULT; +pub const TPMAPI_E_INVALID_ENCODING: HRESULT = 0x8029010Eu32 as HRESULT; +pub const TPMAPI_E_INVALID_KEY_SIZE: HRESULT = 0x8029010Fu32 as HRESULT; +pub const TPMAPI_E_ENCRYPTION_FAILED: HRESULT = 0x80290110u32 as HRESULT; +pub const TPMAPI_E_INVALID_KEY_PARAMS: HRESULT = 0x80290111u32 as HRESULT; +pub const TPMAPI_E_INVALID_MIGRATION_AUTHORIZATION_BLOB: HRESULT = 0x80290112u32 as HRESULT; +pub const TPMAPI_E_INVALID_PCR_INDEX: HRESULT = 0x80290113u32 as HRESULT; +pub const TPMAPI_E_INVALID_DELEGATE_BLOB: HRESULT = 0x80290114u32 as HRESULT; +pub const TPMAPI_E_INVALID_CONTEXT_PARAMS: HRESULT = 0x80290115u32 as HRESULT; +pub const TPMAPI_E_INVALID_KEY_BLOB: HRESULT = 0x80290116u32 as HRESULT; +pub const TPMAPI_E_INVALID_PCR_DATA: HRESULT = 0x80290117u32 as HRESULT; +pub const TPMAPI_E_INVALID_OWNER_AUTH: HRESULT = 0x80290118u32 as HRESULT; +pub const TPMAPI_E_FIPS_RNG_CHECK_FAILED: HRESULT = 0x80290119u32 as HRESULT; +pub const TPMAPI_E_EMPTY_TCG_LOG: HRESULT = 0x8029011Au32 as HRESULT; +pub const TPMAPI_E_INVALID_TCG_LOG_ENTRY: HRESULT = 0x8029011Bu32 as HRESULT; +pub const TPMAPI_E_TCG_SEPARATOR_ABSENT: HRESULT = 0x8029011Cu32 as HRESULT; +pub const TPMAPI_E_TCG_INVALID_DIGEST_ENTRY: HRESULT = 0x8029011Du32 as HRESULT; +pub const TPMAPI_E_POLICY_DENIES_OPERATION: HRESULT = 0x8029011Eu32 as HRESULT; +pub const TBSIMP_E_BUFFER_TOO_SMALL: HRESULT = 0x80290200u32 as HRESULT; +pub const TBSIMP_E_CLEANUP_FAILED: HRESULT = 0x80290201u32 as HRESULT; +pub const TBSIMP_E_INVALID_CONTEXT_HANDLE: HRESULT = 0x80290202u32 as HRESULT; +pub const TBSIMP_E_INVALID_CONTEXT_PARAM: HRESULT = 0x80290203u32 as HRESULT; +pub const TBSIMP_E_TPM_ERROR: HRESULT = 0x80290204u32 as HRESULT; +pub const TBSIMP_E_HASH_BAD_KEY: HRESULT = 0x80290205u32 as HRESULT; +pub const TBSIMP_E_DUPLICATE_VHANDLE: HRESULT = 0x80290206u32 as HRESULT; +pub const TBSIMP_E_INVALID_OUTPUT_POINTER: HRESULT = 0x80290207u32 as HRESULT; +pub const TBSIMP_E_INVALID_PARAMETER: HRESULT = 0x80290208u32 as HRESULT; +pub const TBSIMP_E_RPC_INIT_FAILED: HRESULT = 0x80290209u32 as HRESULT; +pub const TBSIMP_E_SCHEDULER_NOT_RUNNING: HRESULT = 0x8029020Au32 as HRESULT; +pub const TBSIMP_E_COMMAND_CANCELED: HRESULT = 0x8029020Bu32 as HRESULT; +pub const TBSIMP_E_OUT_OF_MEMORY: HRESULT = 0x8029020Cu32 as HRESULT; +pub const TBSIMP_E_LIST_NO_MORE_ITEMS: HRESULT = 0x8029020Du32 as HRESULT; +pub const TBSIMP_E_LIST_NOT_FOUND: HRESULT = 0x8029020Eu32 as HRESULT; +pub const TBSIMP_E_NOT_ENOUGH_SPACE: HRESULT = 0x8029020Fu32 as HRESULT; +pub const TBSIMP_E_NOT_ENOUGH_TPM_CONTEXTS: HRESULT = 0x80290210u32 as HRESULT; +pub const TBSIMP_E_COMMAND_FAILED: HRESULT = 0x80290211u32 as HRESULT; +pub const TBSIMP_E_UNKNOWN_ORDINAL: HRESULT = 0x80290212u32 as HRESULT; +pub const TBSIMP_E_RESOURCE_EXPIRED: HRESULT = 0x80290213u32 as HRESULT; +pub const TBSIMP_E_INVALID_RESOURCE: HRESULT = 0x80290214u32 as HRESULT; +pub const TBSIMP_E_NOTHING_TO_UNLOAD: HRESULT = 0x80290215u32 as HRESULT; +pub const TBSIMP_E_HASH_TABLE_FULL: HRESULT = 0x80290216u32 as HRESULT; +pub const TBSIMP_E_TOO_MANY_TBS_CONTEXTS: HRESULT = 0x80290217u32 as HRESULT; +pub const TBSIMP_E_TOO_MANY_RESOURCES: HRESULT = 0x80290218u32 as HRESULT; +pub const TBSIMP_E_PPI_NOT_SUPPORTED: HRESULT = 0x80290219u32 as HRESULT; +pub const TBSIMP_E_TPM_INCOMPATIBLE: HRESULT = 0x8029021Au32 as HRESULT; +pub const TBSIMP_E_NO_EVENT_LOG: HRESULT = 0x8029021Bu32 as HRESULT; +pub const TPM_E_PPI_ACPI_FAILURE: HRESULT = 0x80290300u32 as HRESULT; +pub const TPM_E_PPI_USER_ABORT: HRESULT = 0x80290301u32 as HRESULT; +pub const TPM_E_PPI_BIOS_FAILURE: HRESULT = 0x80290302u32 as HRESULT; +pub const TPM_E_PPI_NOT_SUPPORTED: HRESULT = 0x80290303u32 as HRESULT; +pub const TPM_E_PPI_BLOCKED_IN_BIOS: HRESULT = 0x80290304u32 as HRESULT; +pub const TPM_E_PCP_ERROR_MASK: HRESULT = 0x80290400u32 as HRESULT; +pub const TPM_E_PCP_DEVICE_NOT_READY: HRESULT = 0x80290401u32 as HRESULT; +pub const TPM_E_PCP_INVALID_HANDLE: HRESULT = 0x80290402u32 as HRESULT; +pub const TPM_E_PCP_INVALID_PARAMETER: HRESULT = 0x80290403u32 as HRESULT; +pub const TPM_E_PCP_FLAG_NOT_SUPPORTED: HRESULT = 0x80290404u32 as HRESULT; +pub const TPM_E_PCP_NOT_SUPPORTED: HRESULT = 0x80290405u32 as HRESULT; +pub const TPM_E_PCP_BUFFER_TOO_SMALL: HRESULT = 0x80290406u32 as HRESULT; +pub const TPM_E_PCP_INTERNAL_ERROR: HRESULT = 0x80290407u32 as HRESULT; +pub const TPM_E_PCP_AUTHENTICATION_FAILED: HRESULT = 0x80290408u32 as HRESULT; +pub const TPM_E_PCP_AUTHENTICATION_IGNORED: HRESULT = 0x80290409u32 as HRESULT; +pub const TPM_E_PCP_POLICY_NOT_FOUND: HRESULT = 0x8029040Au32 as HRESULT; +pub const TPM_E_PCP_PROFILE_NOT_FOUND: HRESULT = 0x8029040Bu32 as HRESULT; +pub const TPM_E_PCP_VALIDATION_FAILED: HRESULT = 0x8029040Cu32 as HRESULT; +pub const PLA_E_DCS_NOT_FOUND: HRESULT = 0x80300002u32 as HRESULT; +pub const PLA_E_DCS_IN_USE: HRESULT = 0x803000AAu32 as HRESULT; +pub const PLA_E_TOO_MANY_FOLDERS: HRESULT = 0x80300045u32 as HRESULT; +pub const PLA_E_NO_MIN_DISK: HRESULT = 0x80300070u32 as HRESULT; +pub const PLA_E_DCS_ALREADY_EXISTS: HRESULT = 0x803000B7u32 as HRESULT; +pub const PLA_S_PROPERTY_IGNORED: HRESULT = 0x00300100; +pub const PLA_E_PROPERTY_CONFLICT: HRESULT = 0x80300101u32 as HRESULT; +pub const PLA_E_DCS_SINGLETON_REQUIRED: HRESULT = 0x80300102u32 as HRESULT; +pub const PLA_E_CREDENTIALS_REQUIRED: HRESULT = 0x80300103u32 as HRESULT; +pub const PLA_E_DCS_NOT_RUNNING: HRESULT = 0x80300104u32 as HRESULT; +pub const PLA_E_CONFLICT_INCL_EXCL_API: HRESULT = 0x80300105u32 as HRESULT; +pub const PLA_E_NETWORK_EXE_NOT_VALID: HRESULT = 0x80300106u32 as HRESULT; +pub const PLA_E_EXE_ALREADY_CONFIGURED: HRESULT = 0x80300107u32 as HRESULT; +pub const PLA_E_EXE_PATH_NOT_VALID: HRESULT = 0x80300108u32 as HRESULT; +pub const PLA_E_DC_ALREADY_EXISTS: HRESULT = 0x80300109u32 as HRESULT; +pub const PLA_E_DCS_START_WAIT_TIMEOUT: HRESULT = 0x8030010Au32 as HRESULT; +pub const PLA_E_DC_START_WAIT_TIMEOUT: HRESULT = 0x8030010Bu32 as HRESULT; +pub const PLA_E_REPORT_WAIT_TIMEOUT: HRESULT = 0x8030010Cu32 as HRESULT; +pub const PLA_E_NO_DUPLICATES: HRESULT = 0x8030010Du32 as HRESULT; +pub const PLA_E_EXE_FULL_PATH_REQUIRED: HRESULT = 0x8030010Eu32 as HRESULT; +pub const PLA_E_INVALID_SESSION_NAME: HRESULT = 0x8030010Fu32 as HRESULT; +pub const PLA_E_PLA_CHANNEL_NOT_ENABLED: HRESULT = 0x80300110u32 as HRESULT; +pub const PLA_E_TASKSCHED_CHANNEL_NOT_ENABLED: HRESULT = 0x80300111u32 as HRESULT; +pub const PLA_E_RULES_MANAGER_FAILED: HRESULT = 0x80300112u32 as HRESULT; +pub const PLA_E_CABAPI_FAILURE: HRESULT = 0x80300113u32 as HRESULT; +pub const FVE_E_LOCKED_VOLUME: HRESULT = 0x80310000u32 as HRESULT; +pub const FVE_E_NOT_ENCRYPTED: HRESULT = 0x80310001u32 as HRESULT; +pub const FVE_E_NO_TPM_BIOS: HRESULT = 0x80310002u32 as HRESULT; +pub const FVE_E_NO_MBR_METRIC: HRESULT = 0x80310003u32 as HRESULT; +pub const FVE_E_NO_BOOTSECTOR_METRIC: HRESULT = 0x80310004u32 as HRESULT; +pub const FVE_E_NO_BOOTMGR_METRIC: HRESULT = 0x80310005u32 as HRESULT; +pub const FVE_E_WRONG_BOOTMGR: HRESULT = 0x80310006u32 as HRESULT; +pub const FVE_E_SECURE_KEY_REQUIRED: HRESULT = 0x80310007u32 as HRESULT; +pub const FVE_E_NOT_ACTIVATED: HRESULT = 0x80310008u32 as HRESULT; +pub const FVE_E_ACTION_NOT_ALLOWED: HRESULT = 0x80310009u32 as HRESULT; +pub const FVE_E_AD_SCHEMA_NOT_INSTALLED: HRESULT = 0x8031000Au32 as HRESULT; +pub const FVE_E_AD_INVALID_DATATYPE: HRESULT = 0x8031000Bu32 as HRESULT; +pub const FVE_E_AD_INVALID_DATASIZE: HRESULT = 0x8031000Cu32 as HRESULT; +pub const FVE_E_AD_NO_VALUES: HRESULT = 0x8031000Du32 as HRESULT; +pub const FVE_E_AD_ATTR_NOT_SET: HRESULT = 0x8031000Eu32 as HRESULT; +pub const FVE_E_AD_GUID_NOT_FOUND: HRESULT = 0x8031000Fu32 as HRESULT; +pub const FVE_E_BAD_INFORMATION: HRESULT = 0x80310010u32 as HRESULT; +pub const FVE_E_TOO_SMALL: HRESULT = 0x80310011u32 as HRESULT; +pub const FVE_E_SYSTEM_VOLUME: HRESULT = 0x80310012u32 as HRESULT; +pub const FVE_E_FAILED_WRONG_FS: HRESULT = 0x80310013u32 as HRESULT; +pub const FVE_E_BAD_PARTITION_SIZE: HRESULT = 0x80310014u32 as HRESULT; +pub const FVE_E_NOT_SUPPORTED: HRESULT = 0x80310015u32 as HRESULT; +pub const FVE_E_BAD_DATA: HRESULT = 0x80310016u32 as HRESULT; +pub const FVE_E_VOLUME_NOT_BOUND: HRESULT = 0x80310017u32 as HRESULT; +pub const FVE_E_TPM_NOT_OWNED: HRESULT = 0x80310018u32 as HRESULT; +pub const FVE_E_NOT_DATA_VOLUME: HRESULT = 0x80310019u32 as HRESULT; +pub const FVE_E_AD_INSUFFICIENT_BUFFER: HRESULT = 0x8031001Au32 as HRESULT; +pub const FVE_E_CONV_READ: HRESULT = 0x8031001Bu32 as HRESULT; +pub const FVE_E_CONV_WRITE: HRESULT = 0x8031001Cu32 as HRESULT; +pub const FVE_E_KEY_REQUIRED: HRESULT = 0x8031001Du32 as HRESULT; +pub const FVE_E_CLUSTERING_NOT_SUPPORTED: HRESULT = 0x8031001Eu32 as HRESULT; +pub const FVE_E_VOLUME_BOUND_ALREADY: HRESULT = 0x8031001Fu32 as HRESULT; +pub const FVE_E_OS_NOT_PROTECTED: HRESULT = 0x80310020u32 as HRESULT; +pub const FVE_E_PROTECTION_DISABLED: HRESULT = 0x80310021u32 as HRESULT; +pub const FVE_E_RECOVERY_KEY_REQUIRED: HRESULT = 0x80310022u32 as HRESULT; +pub const FVE_E_FOREIGN_VOLUME: HRESULT = 0x80310023u32 as HRESULT; +pub const FVE_E_OVERLAPPED_UPDATE: HRESULT = 0x80310024u32 as HRESULT; +pub const FVE_E_TPM_SRK_AUTH_NOT_ZERO: HRESULT = 0x80310025u32 as HRESULT; +pub const FVE_E_FAILED_SECTOR_SIZE: HRESULT = 0x80310026u32 as HRESULT; +pub const FVE_E_FAILED_AUTHENTICATION: HRESULT = 0x80310027u32 as HRESULT; +pub const FVE_E_NOT_OS_VOLUME: HRESULT = 0x80310028u32 as HRESULT; +pub const FVE_E_AUTOUNLOCK_ENABLED: HRESULT = 0x80310029u32 as HRESULT; +pub const FVE_E_WRONG_BOOTSECTOR: HRESULT = 0x8031002Au32 as HRESULT; +pub const FVE_E_WRONG_SYSTEM_FS: HRESULT = 0x8031002Bu32 as HRESULT; +pub const FVE_E_POLICY_PASSWORD_REQUIRED: HRESULT = 0x8031002Cu32 as HRESULT; +pub const FVE_E_CANNOT_SET_FVEK_ENCRYPTED: HRESULT = 0x8031002Du32 as HRESULT; +pub const FVE_E_CANNOT_ENCRYPT_NO_KEY: HRESULT = 0x8031002Eu32 as HRESULT; +pub const FVE_E_BOOTABLE_CDDVD: HRESULT = 0x80310030u32 as HRESULT; +pub const FVE_E_PROTECTOR_EXISTS: HRESULT = 0x80310031u32 as HRESULT; +pub const FVE_E_RELATIVE_PATH: HRESULT = 0x80310032u32 as HRESULT; +pub const FVE_E_PROTECTOR_NOT_FOUND: HRESULT = 0x80310033u32 as HRESULT; +pub const FVE_E_INVALID_KEY_FORMAT: HRESULT = 0x80310034u32 as HRESULT; +pub const FVE_E_INVALID_PASSWORD_FORMAT: HRESULT = 0x80310035u32 as HRESULT; +pub const FVE_E_FIPS_RNG_CHECK_FAILED: HRESULT = 0x80310036u32 as HRESULT; +pub const FVE_E_FIPS_PREVENTS_RECOVERY_PASSWORD: HRESULT = 0x80310037u32 as HRESULT; +pub const FVE_E_FIPS_PREVENTS_EXTERNAL_KEY_EXPORT: HRESULT = 0x80310038u32 as HRESULT; +pub const FVE_E_NOT_DECRYPTED: HRESULT = 0x80310039u32 as HRESULT; +pub const FVE_E_INVALID_PROTECTOR_TYPE: HRESULT = 0x8031003Au32 as HRESULT; +pub const FVE_E_NO_PROTECTORS_TO_TEST: HRESULT = 0x8031003Bu32 as HRESULT; +pub const FVE_E_KEYFILE_NOT_FOUND: HRESULT = 0x8031003Cu32 as HRESULT; +pub const FVE_E_KEYFILE_INVALID: HRESULT = 0x8031003Du32 as HRESULT; +pub const FVE_E_KEYFILE_NO_VMK: HRESULT = 0x8031003Eu32 as HRESULT; +pub const FVE_E_TPM_DISABLED: HRESULT = 0x8031003Fu32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_IN_SAFE_MODE: HRESULT = 0x80310040u32 as HRESULT; +pub const FVE_E_TPM_INVALID_PCR: HRESULT = 0x80310041u32 as HRESULT; +pub const FVE_E_TPM_NO_VMK: HRESULT = 0x80310042u32 as HRESULT; +pub const FVE_E_PIN_INVALID: HRESULT = 0x80310043u32 as HRESULT; +pub const FVE_E_AUTH_INVALID_APPLICATION: HRESULT = 0x80310044u32 as HRESULT; +pub const FVE_E_AUTH_INVALID_CONFIG: HRESULT = 0x80310045u32 as HRESULT; +pub const FVE_E_FIPS_DISABLE_PROTECTION_NOT_ALLOWED: HRESULT = 0x80310046u32 as HRESULT; +pub const FVE_E_FS_NOT_EXTENDED: HRESULT = 0x80310047u32 as HRESULT; +pub const FVE_E_FIRMWARE_TYPE_NOT_SUPPORTED: HRESULT = 0x80310048u32 as HRESULT; +pub const FVE_E_NO_LICENSE: HRESULT = 0x80310049u32 as HRESULT; +pub const FVE_E_NOT_ON_STACK: HRESULT = 0x8031004Au32 as HRESULT; +pub const FVE_E_FS_MOUNTED: HRESULT = 0x8031004Bu32 as HRESULT; +pub const FVE_E_TOKEN_NOT_IMPERSONATED: HRESULT = 0x8031004Cu32 as HRESULT; +pub const FVE_E_DRY_RUN_FAILED: HRESULT = 0x8031004Du32 as HRESULT; +pub const FVE_E_REBOOT_REQUIRED: HRESULT = 0x8031004Eu32 as HRESULT; +pub const FVE_E_DEBUGGER_ENABLED: HRESULT = 0x8031004Fu32 as HRESULT; +pub const FVE_E_RAW_ACCESS: HRESULT = 0x80310050u32 as HRESULT; +pub const FVE_E_RAW_BLOCKED: HRESULT = 0x80310051u32 as HRESULT; +pub const FVE_E_BCD_APPLICATIONS_PATH_INCORRECT: HRESULT = 0x80310052u32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_IN_VERSION: HRESULT = 0x80310053u32 as HRESULT; +pub const FVE_E_NO_AUTOUNLOCK_MASTER_KEY: HRESULT = 0x80310054u32 as HRESULT; +pub const FVE_E_MOR_FAILED: HRESULT = 0x80310055u32 as HRESULT; +pub const FVE_E_HIDDEN_VOLUME: HRESULT = 0x80310056u32 as HRESULT; +pub const FVE_E_TRANSIENT_STATE: HRESULT = 0x80310057u32 as HRESULT; +pub const FVE_E_PUBKEY_NOT_ALLOWED: HRESULT = 0x80310058u32 as HRESULT; +pub const FVE_E_VOLUME_HANDLE_OPEN: HRESULT = 0x80310059u32 as HRESULT; +pub const FVE_E_NO_FEATURE_LICENSE: HRESULT = 0x8031005Au32 as HRESULT; +pub const FVE_E_INVALID_STARTUP_OPTIONS: HRESULT = 0x8031005Bu32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_PASSWORD_NOT_ALLOWED: HRESULT = 0x8031005Cu32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_PASSWORD_REQUIRED: HRESULT = 0x8031005Du32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_KEY_NOT_ALLOWED: HRESULT = 0x8031005Eu32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_KEY_REQUIRED: HRESULT = 0x8031005Fu32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_NOT_ALLOWED: HRESULT = 0x80310060u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_REQUIRED: HRESULT = 0x80310061u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_KEY_NOT_ALLOWED: HRESULT = 0x80310062u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_KEY_REQUIRED: HRESULT = 0x80310063u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_KEY_NOT_ALLOWED: HRESULT = 0x80310064u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_KEY_REQUIRED: HRESULT = 0x80310065u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_TPM_NOT_ALLOWED: HRESULT = 0x80310066u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_TPM_REQUIRED: HRESULT = 0x80310067u32 as HRESULT; +pub const FVE_E_POLICY_INVALID_PIN_LENGTH: HRESULT = 0x80310068u32 as HRESULT; +pub const FVE_E_KEY_PROTECTOR_NOT_SUPPORTED: HRESULT = 0x80310069u32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_NOT_ALLOWED: HRESULT = 0x8031006Au32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_REQUIRED: HRESULT = 0x8031006Bu32 as HRESULT; +pub const FVE_E_FIPS_PREVENTS_PASSPHRASE: HRESULT = 0x8031006Cu32 as HRESULT; +pub const FVE_E_OS_VOLUME_PASSPHRASE_NOT_ALLOWED: HRESULT = 0x8031006Du32 as HRESULT; +pub const FVE_E_INVALID_BITLOCKER_OID: HRESULT = 0x8031006Eu32 as HRESULT; +pub const FVE_E_VOLUME_TOO_SMALL: HRESULT = 0x8031006Fu32 as HRESULT; +pub const FVE_E_DV_NOT_SUPPORTED_ON_FS: HRESULT = 0x80310070u32 as HRESULT; +pub const FVE_E_DV_NOT_ALLOWED_BY_GP: HRESULT = 0x80310071u32 as HRESULT; +pub const FVE_E_POLICY_USER_CERTIFICATE_NOT_ALLOWED: HRESULT = 0x80310072u32 as HRESULT; +pub const FVE_E_POLICY_USER_CERTIFICATE_REQUIRED: HRESULT = 0x80310073u32 as HRESULT; +pub const FVE_E_POLICY_USER_CERT_MUST_BE_HW: HRESULT = 0x80310074u32 as HRESULT; +pub const FVE_E_POLICY_USER_CONFIGURE_FDV_AUTOUNLOCK_NOT_ALLOWED: HRESULT = 0x80310075u32 as HRESULT; +pub const FVE_E_POLICY_USER_CONFIGURE_RDV_AUTOUNLOCK_NOT_ALLOWED: HRESULT = 0x80310076u32 as HRESULT; +pub const FVE_E_POLICY_USER_CONFIGURE_RDV_NOT_ALLOWED: HRESULT = 0x80310077u32 as HRESULT; +pub const FVE_E_POLICY_USER_ENABLE_RDV_NOT_ALLOWED: HRESULT = 0x80310078u32 as HRESULT; +pub const FVE_E_POLICY_USER_DISABLE_RDV_NOT_ALLOWED: HRESULT = 0x80310079u32 as HRESULT; +pub const FVE_E_POLICY_INVALID_PASSPHRASE_LENGTH: HRESULT = 0x80310080u32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_TOO_SIMPLE: HRESULT = 0x80310081u32 as HRESULT; +pub const FVE_E_RECOVERY_PARTITION: HRESULT = 0x80310082u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_FDV_RK_OFF_AUK_ON: HRESULT = 0x80310083u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_RDV_RK_OFF_AUK_ON: HRESULT = 0x80310084u32 as HRESULT; +pub const FVE_E_NON_BITLOCKER_OID: HRESULT = 0x80310085u32 as HRESULT; +pub const FVE_E_POLICY_PROHIBITS_SELFSIGNED: HRESULT = 0x80310086u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_RO_AND_STARTUP_KEY_REQUIRED: HRESULT = 0x80310087u32 as HRESULT; +pub const FVE_E_CONV_RECOVERY_FAILED: HRESULT = 0x80310088u32 as HRESULT; +pub const FVE_E_VIRTUALIZED_SPACE_TOO_BIG: HRESULT = 0x80310089u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_OSV_RP_OFF_ADB_ON: HRESULT = 0x80310090u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_FDV_RP_OFF_ADB_ON: HRESULT = 0x80310091u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_RDV_RP_OFF_ADB_ON: HRESULT = 0x80310092u32 as HRESULT; +pub const FVE_E_NON_BITLOCKER_KU: HRESULT = 0x80310093u32 as HRESULT; +pub const FVE_E_PRIVATEKEY_AUTH_FAILED: HRESULT = 0x80310094u32 as HRESULT; +pub const FVE_E_REMOVAL_OF_DRA_FAILED: HRESULT = 0x80310095u32 as HRESULT; +pub const FVE_E_OPERATION_NOT_SUPPORTED_ON_VISTA_VOLUME: HRESULT = 0x80310096u32 as HRESULT; +pub const FVE_E_CANT_LOCK_AUTOUNLOCK_ENABLED_VOLUME: HRESULT = 0x80310097u32 as HRESULT; +pub const FVE_E_FIPS_HASH_KDF_NOT_ALLOWED: HRESULT = 0x80310098u32 as HRESULT; +pub const FVE_E_ENH_PIN_INVALID: HRESULT = 0x80310099u32 as HRESULT; +pub const FVE_E_INVALID_PIN_CHARS: HRESULT = 0x8031009Au32 as HRESULT; +pub const FVE_E_INVALID_DATUM_TYPE: HRESULT = 0x8031009Bu32 as HRESULT; +pub const FVE_E_EFI_ONLY: HRESULT = 0x8031009Cu32 as HRESULT; +pub const FVE_E_MULTIPLE_NKP_CERTS: HRESULT = 0x8031009Du32 as HRESULT; +pub const FVE_E_REMOVAL_OF_NKP_FAILED: HRESULT = 0x8031009Eu32 as HRESULT; +pub const FVE_E_INVALID_NKP_CERT: HRESULT = 0x8031009Fu32 as HRESULT; +pub const FVE_E_NO_EXISTING_PIN: HRESULT = 0x803100A0u32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_PIN_MISMATCH: HRESULT = 0x803100A1u32 as HRESULT; +pub const FVE_E_PIN_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: HRESULT = 0x803100A2u32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_MAX_PIN_CHANGE_ATTEMPTS_REACHED: HRESULT = 0x803100A3u32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_REQUIRES_ASCII: HRESULT = 0x803100A4u32 as HRESULT; +pub const FVE_E_FULL_ENCRYPTION_NOT_ALLOWED_ON_TP_STORAGE: HRESULT = 0x803100A5u32 as HRESULT; +pub const FVE_E_WIPE_NOT_ALLOWED_ON_TP_STORAGE: HRESULT = 0x803100A6u32 as HRESULT; +pub const FVE_E_KEY_LENGTH_NOT_SUPPORTED_BY_EDRIVE: HRESULT = 0x803100A7u32 as HRESULT; +pub const FVE_E_NO_EXISTING_PASSPHRASE: HRESULT = 0x803100A8u32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_PASSPHRASE_MISMATCH: HRESULT = 0x803100A9u32 as HRESULT; +pub const FVE_E_PASSPHRASE_TOO_LONG: HRESULT = 0x803100AAu32 as HRESULT; +pub const FVE_E_NO_PASSPHRASE_WITH_TPM: HRESULT = 0x803100ABu32 as HRESULT; +pub const FVE_E_NO_TPM_WITH_PASSPHRASE: HRESULT = 0x803100ACu32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_ON_CSV_STACK: HRESULT = 0x803100ADu32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_ON_CLUSTER: HRESULT = 0x803100AEu32 as HRESULT; +pub const FVE_E_EDRIVE_NO_FAILOVER_TO_SW: HRESULT = 0x803100AFu32 as HRESULT; +pub const FVE_E_EDRIVE_BAND_IN_USE: HRESULT = 0x803100B0u32 as HRESULT; +pub const FVE_E_EDRIVE_DISALLOWED_BY_GP: HRESULT = 0x803100B1u32 as HRESULT; +pub const FVE_E_EDRIVE_INCOMPATIBLE_VOLUME: HRESULT = 0x803100B2u32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_TO_UPGRADE_WHILE_CONVERTING: HRESULT = 0x803100B3u32 as HRESULT; +pub const FVE_E_EDRIVE_DV_NOT_SUPPORTED: HRESULT = 0x803100B4u32 as HRESULT; +pub const FVE_E_NO_PREBOOT_KEYBOARD_DETECTED: HRESULT = 0x803100B5u32 as HRESULT; +pub const FVE_E_NO_PREBOOT_KEYBOARD_OR_WINRE_DETECTED: HRESULT = 0x803100B6u32 as HRESULT; +pub const FVE_E_POLICY_REQUIRES_STARTUP_PIN_ON_TOUCH_DEVICE: HRESULT = 0x803100B7u32 as HRESULT; +pub const FVE_E_POLICY_REQUIRES_RECOVERY_PASSWORD_ON_TOUCH_DEVICE: HRESULT = 0x803100B8u32 as HRESULT; +pub const FVE_E_WIPE_CANCEL_NOT_APPLICABLE: HRESULT = 0x803100B9u32 as HRESULT; +pub const FVE_E_SECUREBOOT_DISABLED: HRESULT = 0x803100BAu32 as HRESULT; +pub const FVE_E_SECUREBOOT_CONFIGURATION_INVALID: HRESULT = 0x803100BBu32 as HRESULT; +pub const FVE_E_EDRIVE_DRY_RUN_FAILED: HRESULT = 0x803100BCu32 as HRESULT; +pub const FVE_E_SHADOW_COPY_PRESENT: HRESULT = 0x803100BDu32 as HRESULT; +pub const FVE_E_POLICY_INVALID_ENHANCED_BCD_SETTINGS: HRESULT = 0x803100BEu32 as HRESULT; +pub const FVE_E_EDRIVE_INCOMPATIBLE_FIRMWARE: HRESULT = 0x803100BFu32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_MAX_PASSPHRASE_CHANGE_ATTEMPTS_REACHED: HRESULT = 0x803100C0u32 as HRESULT; +pub const FVE_E_PASSPHRASE_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: HRESULT = 0x803100C1u32 as HRESULT; +pub const FVE_E_LIVEID_ACCOUNT_SUSPENDED: HRESULT = 0x803100C2u32 as HRESULT; +pub const FVE_E_LIVEID_ACCOUNT_BLOCKED: HRESULT = 0x803100C3u32 as HRESULT; +pub const FVE_E_NOT_PROVISIONED_ON_ALL_VOLUMES: HRESULT = 0x803100C4u32 as HRESULT; +pub const FVE_E_DE_FIXED_DATA_NOT_SUPPORTED: HRESULT = 0x803100C5u32 as HRESULT; +pub const FVE_E_DE_HARDWARE_NOT_COMPLIANT: HRESULT = 0x803100C6u32 as HRESULT; +pub const FVE_E_DE_WINRE_NOT_CONFIGURED: HRESULT = 0x803100C7u32 as HRESULT; +pub const FVE_E_DE_PROTECTION_SUSPENDED: HRESULT = 0x803100C8u32 as HRESULT; +pub const FVE_E_DE_OS_VOLUME_NOT_PROTECTED: HRESULT = 0x803100C9u32 as HRESULT; +pub const FVE_E_DE_DEVICE_LOCKEDOUT: HRESULT = 0x803100CAu32 as HRESULT; +pub const FVE_E_DE_PROTECTION_NOT_YET_ENABLED: HRESULT = 0x803100CBu32 as HRESULT; +pub const FVE_E_INVALID_PIN_CHARS_DETAILED: HRESULT = 0x803100CCu32 as HRESULT; +pub const FVE_E_DEVICE_LOCKOUT_COUNTER_UNAVAILABLE: HRESULT = 0x803100CDu32 as HRESULT; +pub const FVE_E_DEVICELOCKOUT_COUNTER_MISMATCH: HRESULT = 0x803100CEu32 as HRESULT; +pub const FVE_E_BUFFER_TOO_LARGE: HRESULT = 0x803100CFu32 as HRESULT; +pub const FVE_E_NO_SUCH_CAPABILITY_ON_TARGET: HRESULT = 0x803100D0u32 as HRESULT; +pub const FVE_E_DE_PREVENTED_FOR_OS: HRESULT = 0x803100D1u32 as HRESULT; +pub const FVE_E_DE_VOLUME_OPTED_OUT: HRESULT = 0x803100D2u32 as HRESULT; +pub const FVE_E_DE_VOLUME_NOT_SUPPORTED: HRESULT = 0x803100D3u32 as HRESULT; +pub const FVE_E_EOW_NOT_SUPPORTED_IN_VERSION: HRESULT = 0x803100D4u32 as HRESULT; +pub const FVE_E_ADBACKUP_NOT_ENABLED: HRESULT = 0x803100D5u32 as HRESULT; +pub const FVE_E_VOLUME_EXTEND_PREVENTS_EOW_DECRYPT: HRESULT = 0x803100D6u32 as HRESULT; +pub const FVE_E_NOT_DE_VOLUME: HRESULT = 0x803100D7u32 as HRESULT; +pub const FVE_E_PROTECTION_CANNOT_BE_DISABLED: HRESULT = 0x803100D8u32 as HRESULT; +pub const FWP_E_CALLOUT_NOT_FOUND: HRESULT = 0x80320001u32 as HRESULT; +pub const FWP_E_CONDITION_NOT_FOUND: HRESULT = 0x80320002u32 as HRESULT; +pub const FWP_E_FILTER_NOT_FOUND: HRESULT = 0x80320003u32 as HRESULT; +pub const FWP_E_LAYER_NOT_FOUND: HRESULT = 0x80320004u32 as HRESULT; +pub const FWP_E_PROVIDER_NOT_FOUND: HRESULT = 0x80320005u32 as HRESULT; +pub const FWP_E_PROVIDER_CONTEXT_NOT_FOUND: HRESULT = 0x80320006u32 as HRESULT; +pub const FWP_E_SUBLAYER_NOT_FOUND: HRESULT = 0x80320007u32 as HRESULT; +pub const FWP_E_NOT_FOUND: HRESULT = 0x80320008u32 as HRESULT; +pub const FWP_E_ALREADY_EXISTS: HRESULT = 0x80320009u32 as HRESULT; +pub const FWP_E_IN_USE: HRESULT = 0x8032000Au32 as HRESULT; +pub const FWP_E_DYNAMIC_SESSION_IN_PROGRESS: HRESULT = 0x8032000Bu32 as HRESULT; +pub const FWP_E_WRONG_SESSION: HRESULT = 0x8032000Cu32 as HRESULT; +pub const FWP_E_NO_TXN_IN_PROGRESS: HRESULT = 0x8032000Du32 as HRESULT; +pub const FWP_E_TXN_IN_PROGRESS: HRESULT = 0x8032000Eu32 as HRESULT; +pub const FWP_E_TXN_ABORTED: HRESULT = 0x8032000Fu32 as HRESULT; +pub const FWP_E_SESSION_ABORTED: HRESULT = 0x80320010u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_TXN: HRESULT = 0x80320011u32 as HRESULT; +pub const FWP_E_TIMEOUT: HRESULT = 0x80320012u32 as HRESULT; +pub const FWP_E_NET_EVENTS_DISABLED: HRESULT = 0x80320013u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_LAYER: HRESULT = 0x80320014u32 as HRESULT; +pub const FWP_E_KM_CLIENTS_ONLY: HRESULT = 0x80320015u32 as HRESULT; +pub const FWP_E_LIFETIME_MISMATCH: HRESULT = 0x80320016u32 as HRESULT; +pub const FWP_E_BUILTIN_OBJECT: HRESULT = 0x80320017u32 as HRESULT; +pub const FWP_E_TOO_MANY_CALLOUTS: HRESULT = 0x80320018u32 as HRESULT; +pub const FWP_E_NOTIFICATION_DROPPED: HRESULT = 0x80320019u32 as HRESULT; +pub const FWP_E_TRAFFIC_MISMATCH: HRESULT = 0x8032001Au32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_SA_STATE: HRESULT = 0x8032001Bu32 as HRESULT; +pub const FWP_E_NULL_POINTER: HRESULT = 0x8032001Cu32 as HRESULT; +pub const FWP_E_INVALID_ENUMERATOR: HRESULT = 0x8032001Du32 as HRESULT; +pub const FWP_E_INVALID_FLAGS: HRESULT = 0x8032001Eu32 as HRESULT; +pub const FWP_E_INVALID_NET_MASK: HRESULT = 0x8032001Fu32 as HRESULT; +pub const FWP_E_INVALID_RANGE: HRESULT = 0x80320020u32 as HRESULT; +pub const FWP_E_INVALID_INTERVAL: HRESULT = 0x80320021u32 as HRESULT; +pub const FWP_E_ZERO_LENGTH_ARRAY: HRESULT = 0x80320022u32 as HRESULT; +pub const FWP_E_NULL_DISPLAY_NAME: HRESULT = 0x80320023u32 as HRESULT; +pub const FWP_E_INVALID_ACTION_TYPE: HRESULT = 0x80320024u32 as HRESULT; +pub const FWP_E_INVALID_WEIGHT: HRESULT = 0x80320025u32 as HRESULT; +pub const FWP_E_MATCH_TYPE_MISMATCH: HRESULT = 0x80320026u32 as HRESULT; +pub const FWP_E_TYPE_MISMATCH: HRESULT = 0x80320027u32 as HRESULT; +pub const FWP_E_OUT_OF_BOUNDS: HRESULT = 0x80320028u32 as HRESULT; +pub const FWP_E_RESERVED: HRESULT = 0x80320029u32 as HRESULT; +pub const FWP_E_DUPLICATE_CONDITION: HRESULT = 0x8032002Au32 as HRESULT; +pub const FWP_E_DUPLICATE_KEYMOD: HRESULT = 0x8032002Bu32 as HRESULT; +pub const FWP_E_ACTION_INCOMPATIBLE_WITH_LAYER: HRESULT = 0x8032002Cu32 as HRESULT; +pub const FWP_E_ACTION_INCOMPATIBLE_WITH_SUBLAYER: HRESULT = 0x8032002Du32 as HRESULT; +pub const FWP_E_CONTEXT_INCOMPATIBLE_WITH_LAYER: HRESULT = 0x8032002Eu32 as HRESULT; +pub const FWP_E_CONTEXT_INCOMPATIBLE_WITH_CALLOUT: HRESULT = 0x8032002Fu32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_AUTH_METHOD: HRESULT = 0x80320030u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_DH_GROUP: HRESULT = 0x80320031u32 as HRESULT; +pub const FWP_E_EM_NOT_SUPPORTED: HRESULT = 0x80320032u32 as HRESULT; +pub const FWP_E_NEVER_MATCH: HRESULT = 0x80320033u32 as HRESULT; +pub const FWP_E_PROVIDER_CONTEXT_MISMATCH: HRESULT = 0x80320034u32 as HRESULT; +pub const FWP_E_INVALID_PARAMETER: HRESULT = 0x80320035u32 as HRESULT; +pub const FWP_E_TOO_MANY_SUBLAYERS: HRESULT = 0x80320036u32 as HRESULT; +pub const FWP_E_CALLOUT_NOTIFICATION_FAILED: HRESULT = 0x80320037u32 as HRESULT; +pub const FWP_E_INVALID_AUTH_TRANSFORM: HRESULT = 0x80320038u32 as HRESULT; +pub const FWP_E_INVALID_CIPHER_TRANSFORM: HRESULT = 0x80320039u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_CIPHER_TRANSFORM: HRESULT = 0x8032003Au32 as HRESULT; +pub const FWP_E_INVALID_TRANSFORM_COMBINATION: HRESULT = 0x8032003Bu32 as HRESULT; +pub const FWP_E_DUPLICATE_AUTH_METHOD: HRESULT = 0x8032003Cu32 as HRESULT; +pub const FWP_E_INVALID_TUNNEL_ENDPOINT: HRESULT = 0x8032003Du32 as HRESULT; +pub const FWP_E_L2_DRIVER_NOT_READY: HRESULT = 0x8032003Eu32 as HRESULT; +pub const FWP_E_KEY_DICTATOR_ALREADY_REGISTERED: HRESULT = 0x8032003Fu32 as HRESULT; +pub const FWP_E_KEY_DICTATION_INVALID_KEYING_MATERIAL: HRESULT = 0x80320040u32 as HRESULT; +pub const FWP_E_CONNECTIONS_DISABLED: HRESULT = 0x80320041u32 as HRESULT; +pub const FWP_E_INVALID_DNS_NAME: HRESULT = 0x80320042u32 as HRESULT; +pub const FWP_E_STILL_ON: HRESULT = 0x80320043u32 as HRESULT; +pub const FWP_E_IKEEXT_NOT_RUNNING: HRESULT = 0x80320044u32 as HRESULT; +pub const FWP_E_DROP_NOICMP: HRESULT = 0x80320104u32 as HRESULT; +pub const WS_S_ASYNC: HRESULT = 0x003D0000; +pub const WS_S_END: HRESULT = 0x003D0001; +pub const WS_E_INVALID_FORMAT: HRESULT = 0x803D0000u32 as HRESULT; +pub const WS_E_OBJECT_FAULTED: HRESULT = 0x803D0001u32 as HRESULT; +pub const WS_E_NUMERIC_OVERFLOW: HRESULT = 0x803D0002u32 as HRESULT; +pub const WS_E_INVALID_OPERATION: HRESULT = 0x803D0003u32 as HRESULT; +pub const WS_E_OPERATION_ABORTED: HRESULT = 0x803D0004u32 as HRESULT; +pub const WS_E_ENDPOINT_ACCESS_DENIED: HRESULT = 0x803D0005u32 as HRESULT; +pub const WS_E_OPERATION_TIMED_OUT: HRESULT = 0x803D0006u32 as HRESULT; +pub const WS_E_OPERATION_ABANDONED: HRESULT = 0x803D0007u32 as HRESULT; +pub const WS_E_QUOTA_EXCEEDED: HRESULT = 0x803D0008u32 as HRESULT; +pub const WS_E_NO_TRANSLATION_AVAILABLE: HRESULT = 0x803D0009u32 as HRESULT; +pub const WS_E_SECURITY_VERIFICATION_FAILURE: HRESULT = 0x803D000Au32 as HRESULT; +pub const WS_E_ADDRESS_IN_USE: HRESULT = 0x803D000Bu32 as HRESULT; +pub const WS_E_ADDRESS_NOT_AVAILABLE: HRESULT = 0x803D000Cu32 as HRESULT; +pub const WS_E_ENDPOINT_NOT_FOUND: HRESULT = 0x803D000Du32 as HRESULT; +pub const WS_E_ENDPOINT_NOT_AVAILABLE: HRESULT = 0x803D000Eu32 as HRESULT; +pub const WS_E_ENDPOINT_FAILURE: HRESULT = 0x803D000Fu32 as HRESULT; +pub const WS_E_ENDPOINT_UNREACHABLE: HRESULT = 0x803D0010u32 as HRESULT; +pub const WS_E_ENDPOINT_ACTION_NOT_SUPPORTED: HRESULT = 0x803D0011u32 as HRESULT; +pub const WS_E_ENDPOINT_TOO_BUSY: HRESULT = 0x803D0012u32 as HRESULT; +pub const WS_E_ENDPOINT_FAULT_RECEIVED: HRESULT = 0x803D0013u32 as HRESULT; +pub const WS_E_ENDPOINT_DISCONNECTED: HRESULT = 0x803D0014u32 as HRESULT; +pub const WS_E_PROXY_FAILURE: HRESULT = 0x803D0015u32 as HRESULT; +pub const WS_E_PROXY_ACCESS_DENIED: HRESULT = 0x803D0016u32 as HRESULT; +pub const WS_E_NOT_SUPPORTED: HRESULT = 0x803D0017u32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_BASIC_AUTH: HRESULT = 0x803D0018u32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_DIGEST_AUTH: HRESULT = 0x803D0019u32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_NTLM_AUTH: HRESULT = 0x803D001Au32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_NEGOTIATE_AUTH: HRESULT = 0x803D001Bu32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_BASIC_AUTH: HRESULT = 0x803D001Cu32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_DIGEST_AUTH: HRESULT = 0x803D001Du32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_NTLM_AUTH: HRESULT = 0x803D001Eu32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_NEGOTIATE_AUTH: HRESULT = 0x803D001Fu32 as HRESULT; +pub const WS_E_INVALID_ENDPOINT_URL: HRESULT = 0x803D0020u32 as HRESULT; +pub const WS_E_OTHER: HRESULT = 0x803D0021u32 as HRESULT; +pub const WS_E_SECURITY_TOKEN_EXPIRED: HRESULT = 0x803D0022u32 as HRESULT; +pub const WS_E_SECURITY_SYSTEM_FAILURE: HRESULT = 0x803D0023u32 as HRESULT; +pub const ERROR_NDIS_INTERFACE_CLOSING: HRESULT = 0x80340002u32 as HRESULT; +pub const ERROR_NDIS_BAD_VERSION: HRESULT = 0x80340004u32 as HRESULT; +pub const ERROR_NDIS_BAD_CHARACTERISTICS: HRESULT = 0x80340005u32 as HRESULT; +pub const ERROR_NDIS_ADAPTER_NOT_FOUND: HRESULT = 0x80340006u32 as HRESULT; +pub const ERROR_NDIS_OPEN_FAILED: HRESULT = 0x80340007u32 as HRESULT; +pub const ERROR_NDIS_DEVICE_FAILED: HRESULT = 0x80340008u32 as HRESULT; +pub const ERROR_NDIS_MULTICAST_FULL: HRESULT = 0x80340009u32 as HRESULT; +pub const ERROR_NDIS_MULTICAST_EXISTS: HRESULT = 0x8034000Au32 as HRESULT; +pub const ERROR_NDIS_MULTICAST_NOT_FOUND: HRESULT = 0x8034000Bu32 as HRESULT; +pub const ERROR_NDIS_REQUEST_ABORTED: HRESULT = 0x8034000Cu32 as HRESULT; +pub const ERROR_NDIS_RESET_IN_PROGRESS: HRESULT = 0x8034000Du32 as HRESULT; +pub const ERROR_NDIS_NOT_SUPPORTED: HRESULT = 0x803400BBu32 as HRESULT; +pub const ERROR_NDIS_INVALID_PACKET: HRESULT = 0x8034000Fu32 as HRESULT; +pub const ERROR_NDIS_ADAPTER_NOT_READY: HRESULT = 0x80340011u32 as HRESULT; +pub const ERROR_NDIS_INVALID_LENGTH: HRESULT = 0x80340014u32 as HRESULT; +pub const ERROR_NDIS_INVALID_DATA: HRESULT = 0x80340015u32 as HRESULT; +pub const ERROR_NDIS_BUFFER_TOO_SHORT: HRESULT = 0x80340016u32 as HRESULT; +pub const ERROR_NDIS_INVALID_OID: HRESULT = 0x80340017u32 as HRESULT; +pub const ERROR_NDIS_ADAPTER_REMOVED: HRESULT = 0x80340018u32 as HRESULT; +pub const ERROR_NDIS_UNSUPPORTED_MEDIA: HRESULT = 0x80340019u32 as HRESULT; +pub const ERROR_NDIS_GROUP_ADDRESS_IN_USE: HRESULT = 0x8034001Au32 as HRESULT; +pub const ERROR_NDIS_FILE_NOT_FOUND: HRESULT = 0x8034001Bu32 as HRESULT; +pub const ERROR_NDIS_ERROR_READING_FILE: HRESULT = 0x8034001Cu32 as HRESULT; +pub const ERROR_NDIS_ALREADY_MAPPED: HRESULT = 0x8034001Du32 as HRESULT; +pub const ERROR_NDIS_RESOURCE_CONFLICT: HRESULT = 0x8034001Eu32 as HRESULT; +pub const ERROR_NDIS_MEDIA_DISCONNECTED: HRESULT = 0x8034001Fu32 as HRESULT; +pub const ERROR_NDIS_INVALID_ADDRESS: HRESULT = 0x80340022u32 as HRESULT; +pub const ERROR_NDIS_INVALID_DEVICE_REQUEST: HRESULT = 0x80340010u32 as HRESULT; +pub const ERROR_NDIS_PAUSED: HRESULT = 0x8034002Au32 as HRESULT; +pub const ERROR_NDIS_INTERFACE_NOT_FOUND: HRESULT = 0x8034002Bu32 as HRESULT; +pub const ERROR_NDIS_UNSUPPORTED_REVISION: HRESULT = 0x8034002Cu32 as HRESULT; +pub const ERROR_NDIS_INVALID_PORT: HRESULT = 0x8034002Du32 as HRESULT; +pub const ERROR_NDIS_INVALID_PORT_STATE: HRESULT = 0x8034002Eu32 as HRESULT; +pub const ERROR_NDIS_LOW_POWER_STATE: HRESULT = 0x8034002Fu32 as HRESULT; +pub const ERROR_NDIS_REINIT_REQUIRED: HRESULT = 0x80340030u32 as HRESULT; +pub const ERROR_NDIS_DOT11_AUTO_CONFIG_ENABLED: HRESULT = 0x80342000u32 as HRESULT; +pub const ERROR_NDIS_DOT11_MEDIA_IN_USE: HRESULT = 0x80342001u32 as HRESULT; +pub const ERROR_NDIS_DOT11_POWER_STATE_INVALID: HRESULT = 0x80342002u32 as HRESULT; +pub const ERROR_NDIS_PM_WOL_PATTERN_LIST_FULL: HRESULT = 0x80342003u32 as HRESULT; +pub const ERROR_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL: HRESULT = 0x80342004u32 as HRESULT; +pub const ERROR_NDIS_INDICATION_REQUIRED: HRESULT = 0x00340001; +pub const ERROR_NDIS_OFFLOAD_POLICY: HRESULT = 0xC034100Fu32 as HRESULT; +pub const ERROR_NDIS_OFFLOAD_CONNECTION_REJECTED: HRESULT = 0xC0341012u32 as HRESULT; +pub const ERROR_NDIS_OFFLOAD_PATH_REJECTED: HRESULT = 0xC0341013u32 as HRESULT; +pub const ERROR_HV_INVALID_HYPERCALL_CODE: HRESULT = 0xC0350002u32 as HRESULT; +pub const ERROR_HV_INVALID_HYPERCALL_INPUT: HRESULT = 0xC0350003u32 as HRESULT; +pub const ERROR_HV_INVALID_ALIGNMENT: HRESULT = 0xC0350004u32 as HRESULT; +pub const ERROR_HV_INVALID_PARAMETER: HRESULT = 0xC0350005u32 as HRESULT; +pub const ERROR_HV_ACCESS_DENIED: HRESULT = 0xC0350006u32 as HRESULT; +pub const ERROR_HV_INVALID_PARTITION_STATE: HRESULT = 0xC0350007u32 as HRESULT; +pub const ERROR_HV_OPERATION_DENIED: HRESULT = 0xC0350008u32 as HRESULT; +pub const ERROR_HV_UNKNOWN_PROPERTY: HRESULT = 0xC0350009u32 as HRESULT; +pub const ERROR_HV_PROPERTY_VALUE_OUT_OF_RANGE: HRESULT = 0xC035000Au32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_MEMORY: HRESULT = 0xC035000Bu32 as HRESULT; +pub const ERROR_HV_PARTITION_TOO_DEEP: HRESULT = 0xC035000Cu32 as HRESULT; +pub const ERROR_HV_INVALID_PARTITION_ID: HRESULT = 0xC035000Du32 as HRESULT; +pub const ERROR_HV_INVALID_VP_INDEX: HRESULT = 0xC035000Eu32 as HRESULT; +pub const ERROR_HV_INVALID_PORT_ID: HRESULT = 0xC0350011u32 as HRESULT; +pub const ERROR_HV_INVALID_CONNECTION_ID: HRESULT = 0xC0350012u32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_BUFFERS: HRESULT = 0xC0350013u32 as HRESULT; +pub const ERROR_HV_NOT_ACKNOWLEDGED: HRESULT = 0xC0350014u32 as HRESULT; +pub const ERROR_HV_ACKNOWLEDGED: HRESULT = 0xC0350016u32 as HRESULT; +pub const ERROR_HV_INVALID_SAVE_RESTORE_STATE: HRESULT = 0xC0350017u32 as HRESULT; +pub const ERROR_HV_INVALID_SYNIC_STATE: HRESULT = 0xC0350018u32 as HRESULT; +pub const ERROR_HV_OBJECT_IN_USE: HRESULT = 0xC0350019u32 as HRESULT; +pub const ERROR_HV_INVALID_PROXIMITY_DOMAIN_INFO: HRESULT = 0xC035001Au32 as HRESULT; +pub const ERROR_HV_NO_DATA: HRESULT = 0xC035001Bu32 as HRESULT; +pub const ERROR_HV_INACTIVE: HRESULT = 0xC035001Cu32 as HRESULT; +pub const ERROR_HV_NO_RESOURCES: HRESULT = 0xC035001Du32 as HRESULT; +pub const ERROR_HV_FEATURE_UNAVAILABLE: HRESULT = 0xC035001Eu32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_BUFFER: HRESULT = 0xC0350033u32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_DEVICE_DOMAINS: HRESULT = 0xC0350038u32 as HRESULT; +pub const ERROR_HV_INVALID_LP_INDEX: HRESULT = 0xC0350041u32 as HRESULT; +pub const ERROR_HV_NOT_PRESENT: HRESULT = 0xC0351000u32 as HRESULT; +pub const ERROR_VID_DUPLICATE_HANDLER: HRESULT = 0xC0370001u32 as HRESULT; +pub const ERROR_VID_TOO_MANY_HANDLERS: HRESULT = 0xC0370002u32 as HRESULT; +pub const ERROR_VID_QUEUE_FULL: HRESULT = 0xC0370003u32 as HRESULT; +pub const ERROR_VID_HANDLER_NOT_PRESENT: HRESULT = 0xC0370004u32 as HRESULT; +pub const ERROR_VID_INVALID_OBJECT_NAME: HRESULT = 0xC0370005u32 as HRESULT; +pub const ERROR_VID_PARTITION_NAME_TOO_LONG: HRESULT = 0xC0370006u32 as HRESULT; +pub const ERROR_VID_MESSAGE_QUEUE_NAME_TOO_LONG: HRESULT = 0xC0370007u32 as HRESULT; +pub const ERROR_VID_PARTITION_ALREADY_EXISTS: HRESULT = 0xC0370008u32 as HRESULT; +pub const ERROR_VID_PARTITION_DOES_NOT_EXIST: HRESULT = 0xC0370009u32 as HRESULT; +pub const ERROR_VID_PARTITION_NAME_NOT_FOUND: HRESULT = 0xC037000Au32 as HRESULT; +pub const ERROR_VID_MESSAGE_QUEUE_ALREADY_EXISTS: HRESULT = 0xC037000Bu32 as HRESULT; +pub const ERROR_VID_EXCEEDED_MBP_ENTRY_MAP_LIMIT: HRESULT = 0xC037000Cu32 as HRESULT; +pub const ERROR_VID_MB_STILL_REFERENCED: HRESULT = 0xC037000Du32 as HRESULT; +pub const ERROR_VID_CHILD_GPA_PAGE_SET_CORRUPTED: HRESULT = 0xC037000Eu32 as HRESULT; +pub const ERROR_VID_INVALID_NUMA_SETTINGS: HRESULT = 0xC037000Fu32 as HRESULT; +pub const ERROR_VID_INVALID_NUMA_NODE_INDEX: HRESULT = 0xC0370010u32 as HRESULT; +pub const ERROR_VID_NOTIFICATION_QUEUE_ALREADY_ASSOCIATED: HRESULT = 0xC0370011u32 as HRESULT; +pub const ERROR_VID_INVALID_MEMORY_BLOCK_HANDLE: HRESULT = 0xC0370012u32 as HRESULT; +pub const ERROR_VID_PAGE_RANGE_OVERFLOW: HRESULT = 0xC0370013u32 as HRESULT; +pub const ERROR_VID_INVALID_MESSAGE_QUEUE_HANDLE: HRESULT = 0xC0370014u32 as HRESULT; +pub const ERROR_VID_INVALID_GPA_RANGE_HANDLE: HRESULT = 0xC0370015u32 as HRESULT; +pub const ERROR_VID_NO_MEMORY_BLOCK_NOTIFICATION_QUEUE: HRESULT = 0xC0370016u32 as HRESULT; +pub const ERROR_VID_MEMORY_BLOCK_LOCK_COUNT_EXCEEDED: HRESULT = 0xC0370017u32 as HRESULT; +pub const ERROR_VID_INVALID_PPM_HANDLE: HRESULT = 0xC0370018u32 as HRESULT; +pub const ERROR_VID_MBPS_ARE_LOCKED: HRESULT = 0xC0370019u32 as HRESULT; +pub const ERROR_VID_MESSAGE_QUEUE_CLOSED: HRESULT = 0xC037001Au32 as HRESULT; +pub const ERROR_VID_VIRTUAL_PROCESSOR_LIMIT_EXCEEDED: HRESULT = 0xC037001Bu32 as HRESULT; +pub const ERROR_VID_STOP_PENDING: HRESULT = 0xC037001Cu32 as HRESULT; +pub const ERROR_VID_INVALID_PROCESSOR_STATE: HRESULT = 0xC037001Du32 as HRESULT; +pub const ERROR_VID_EXCEEDED_KM_CONTEXT_COUNT_LIMIT: HRESULT = 0xC037001Eu32 as HRESULT; +pub const ERROR_VID_KM_INTERFACE_ALREADY_INITIALIZED: HRESULT = 0xC037001Fu32 as HRESULT; +pub const ERROR_VID_MB_PROPERTY_ALREADY_SET_RESET: HRESULT = 0xC0370020u32 as HRESULT; +pub const ERROR_VID_MMIO_RANGE_DESTROYED: HRESULT = 0xC0370021u32 as HRESULT; +pub const ERROR_VID_INVALID_CHILD_GPA_PAGE_SET: HRESULT = 0xC0370022u32 as HRESULT; +pub const ERROR_VID_RESERVE_PAGE_SET_IS_BEING_USED: HRESULT = 0xC0370023u32 as HRESULT; +pub const ERROR_VID_RESERVE_PAGE_SET_TOO_SMALL: HRESULT = 0xC0370024u32 as HRESULT; +pub const ERROR_VID_MBP_ALREADY_LOCKED_USING_RESERVED_PAGE: HRESULT = 0xC0370025u32 as HRESULT; +pub const ERROR_VID_MBP_COUNT_EXCEEDED_LIMIT: HRESULT = 0xC0370026u32 as HRESULT; +pub const ERROR_VID_SAVED_STATE_CORRUPT: HRESULT = 0xC0370027u32 as HRESULT; +pub const ERROR_VID_SAVED_STATE_UNRECOGNIZED_ITEM: HRESULT = 0xC0370028u32 as HRESULT; +pub const ERROR_VID_SAVED_STATE_INCOMPATIBLE: HRESULT = 0xC0370029u32 as HRESULT; +pub const ERROR_VID_REMOTE_NODE_PARENT_GPA_PAGES_USED: HRESULT = 0x80370001u32 as HRESULT; +pub const ERROR_VOLMGR_INCOMPLETE_REGENERATION: HRESULT = 0x80380001u32 as HRESULT; +pub const ERROR_VOLMGR_INCOMPLETE_DISK_MIGRATION: HRESULT = 0x80380002u32 as HRESULT; +pub const ERROR_VOLMGR_DATABASE_FULL: HRESULT = 0xC0380001u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_CONFIGURATION_CORRUPTED: HRESULT = 0xC0380002u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_CONFIGURATION_NOT_IN_SYNC: HRESULT = 0xC0380003u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_CONFIG_UPDATE_FAILED: HRESULT = 0xC0380004u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_CONTAINS_NON_SIMPLE_VOLUME: HRESULT = 0xC0380005u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_DUPLICATE: HRESULT = 0xC0380006u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_DYNAMIC: HRESULT = 0xC0380007u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_ID_INVALID: HRESULT = 0xC0380008u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_INVALID: HRESULT = 0xC0380009u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAST_VOTER: HRESULT = 0xC038000Au32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_INVALID: HRESULT = 0xC038000Bu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_NON_BASIC_BETWEEN_BASIC_PARTITIONS: HRESULT = 0xC038000Cu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_NOT_CYLINDER_ALIGNED: HRESULT = 0xC038000Du32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_PARTITIONS_TOO_SMALL: HRESULT = 0xC038000Eu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_PRIMARY_BETWEEN_LOGICAL_PARTITIONS: HRESULT = 0xC038000Fu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_TOO_MANY_PARTITIONS: HRESULT = 0xC0380010u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_MISSING: HRESULT = 0xC0380011u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_NOT_EMPTY: HRESULT = 0xC0380012u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_NOT_ENOUGH_SPACE: HRESULT = 0xC0380013u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_REVECTORING_FAILED: HRESULT = 0xC0380014u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_SECTOR_SIZE_INVALID: HRESULT = 0xC0380015u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_SET_NOT_CONTAINED: HRESULT = 0xC0380016u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_MEMBERS: HRESULT = 0xC0380017u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_PLEXES: HRESULT = 0xC0380018u32 as HRESULT; +pub const ERROR_VOLMGR_DYNAMIC_DISK_NOT_SUPPORTED: HRESULT = 0xC0380019u32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_ALREADY_USED: HRESULT = 0xC038001Au32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_NOT_CONTIGUOUS: HRESULT = 0xC038001Bu32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_NOT_IN_PUBLIC_REGION: HRESULT = 0xC038001Cu32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_NOT_SECTOR_ALIGNED: HRESULT = 0xC038001Du32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_OVERLAPS_EBR_PARTITION: HRESULT = 0xC038001Eu32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_VOLUME_LENGTHS_DO_NOT_MATCH: HRESULT = 0xC038001Fu32 as HRESULT; +pub const ERROR_VOLMGR_FAULT_TOLERANT_NOT_SUPPORTED: HRESULT = 0xC0380020u32 as HRESULT; +pub const ERROR_VOLMGR_INTERLEAVE_LENGTH_INVALID: HRESULT = 0xC0380021u32 as HRESULT; +pub const ERROR_VOLMGR_MAXIMUM_REGISTERED_USERS: HRESULT = 0xC0380022u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_IN_SYNC: HRESULT = 0xC0380023u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_INDEX_DUPLICATE: HRESULT = 0xC0380024u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_INDEX_INVALID: HRESULT = 0xC0380025u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_MISSING: HRESULT = 0xC0380026u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_NOT_DETACHED: HRESULT = 0xC0380027u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_REGENERATING: HRESULT = 0xC0380028u32 as HRESULT; +pub const ERROR_VOLMGR_ALL_DISKS_FAILED: HRESULT = 0xC0380029u32 as HRESULT; +pub const ERROR_VOLMGR_NO_REGISTERED_USERS: HRESULT = 0xC038002Au32 as HRESULT; +pub const ERROR_VOLMGR_NO_SUCH_USER: HRESULT = 0xC038002Bu32 as HRESULT; +pub const ERROR_VOLMGR_NOTIFICATION_RESET: HRESULT = 0xC038002Cu32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_MEMBERS_INVALID: HRESULT = 0xC038002Du32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_PLEXES_INVALID: HRESULT = 0xC038002Eu32 as HRESULT; +pub const ERROR_VOLMGR_PACK_DUPLICATE: HRESULT = 0xC038002Fu32 as HRESULT; +pub const ERROR_VOLMGR_PACK_ID_INVALID: HRESULT = 0xC0380030u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_INVALID: HRESULT = 0xC0380031u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_NAME_INVALID: HRESULT = 0xC0380032u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_OFFLINE: HRESULT = 0xC0380033u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_HAS_QUORUM: HRESULT = 0xC0380034u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_WITHOUT_QUORUM: HRESULT = 0xC0380035u32 as HRESULT; +pub const ERROR_VOLMGR_PARTITION_STYLE_INVALID: HRESULT = 0xC0380036u32 as HRESULT; +pub const ERROR_VOLMGR_PARTITION_UPDATE_FAILED: HRESULT = 0xC0380037u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_IN_SYNC: HRESULT = 0xC0380038u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_INDEX_DUPLICATE: HRESULT = 0xC0380039u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_INDEX_INVALID: HRESULT = 0xC038003Au32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_LAST_ACTIVE: HRESULT = 0xC038003Bu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_MISSING: HRESULT = 0xC038003Cu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_REGENERATING: HRESULT = 0xC038003Du32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_TYPE_INVALID: HRESULT = 0xC038003Eu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_NOT_RAID5: HRESULT = 0xC038003Fu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_NOT_SIMPLE: HRESULT = 0xC0380040u32 as HRESULT; +pub const ERROR_VOLMGR_STRUCTURE_SIZE_INVALID: HRESULT = 0xC0380041u32 as HRESULT; +pub const ERROR_VOLMGR_TOO_MANY_NOTIFICATION_REQUESTS: HRESULT = 0xC0380042u32 as HRESULT; +pub const ERROR_VOLMGR_TRANSACTION_IN_PROGRESS: HRESULT = 0xC0380043u32 as HRESULT; +pub const ERROR_VOLMGR_UNEXPECTED_DISK_LAYOUT_CHANGE: HRESULT = 0xC0380044u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_CONTAINS_MISSING_DISK: HRESULT = 0xC0380045u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_ID_INVALID: HRESULT = 0xC0380046u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_LENGTH_INVALID: HRESULT = 0xC0380047u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: HRESULT = 0xC0380048u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_NOT_MIRRORED: HRESULT = 0xC0380049u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_NOT_RETAINED: HRESULT = 0xC038004Au32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_OFFLINE: HRESULT = 0xC038004Bu32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_RETAINED: HRESULT = 0xC038004Cu32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_EXTENTS_INVALID: HRESULT = 0xC038004Du32 as HRESULT; +pub const ERROR_VOLMGR_DIFFERENT_SECTOR_SIZE: HRESULT = 0xC038004Eu32 as HRESULT; +pub const ERROR_VOLMGR_BAD_BOOT_DISK: HRESULT = 0xC038004Fu32 as HRESULT; +pub const ERROR_VOLMGR_PACK_CONFIG_OFFLINE: HRESULT = 0xC0380050u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_CONFIG_ONLINE: HRESULT = 0xC0380051u32 as HRESULT; +pub const ERROR_VOLMGR_NOT_PRIMARY_PACK: HRESULT = 0xC0380052u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_LOG_UPDATE_FAILED: HRESULT = 0xC0380053u32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_DISKS_IN_PLEX_INVALID: HRESULT = 0xC0380054u32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_DISKS_IN_MEMBER_INVALID: HRESULT = 0xC0380055u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_MIRRORED: HRESULT = 0xC0380056u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_NOT_SIMPLE_SPANNED: HRESULT = 0xC0380057u32 as HRESULT; +pub const ERROR_VOLMGR_NO_VALID_LOG_COPIES: HRESULT = 0xC0380058u32 as HRESULT; +pub const ERROR_VOLMGR_PRIMARY_PACK_PRESENT: HRESULT = 0xC0380059u32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_DISKS_INVALID: HRESULT = 0xC038005Au32 as HRESULT; +pub const ERROR_VOLMGR_MIRROR_NOT_SUPPORTED: HRESULT = 0xC038005Bu32 as HRESULT; +pub const ERROR_VOLMGR_RAID5_NOT_SUPPORTED: HRESULT = 0xC038005Cu32 as HRESULT; +pub const ERROR_BCD_NOT_ALL_ENTRIES_IMPORTED: HRESULT = 0x80390001u32 as HRESULT; +pub const ERROR_BCD_TOO_MANY_ELEMENTS: HRESULT = 0xC0390002u32 as HRESULT; +pub const ERROR_BCD_NOT_ALL_ENTRIES_SYNCHRONIZED: HRESULT = 0x80390003u32 as HRESULT; +pub const ERROR_VHD_DRIVE_FOOTER_MISSING: HRESULT = 0xC03A0001u32 as HRESULT; +pub const ERROR_VHD_DRIVE_FOOTER_CHECKSUM_MISMATCH: HRESULT = 0xC03A0002u32 as HRESULT; +pub const ERROR_VHD_DRIVE_FOOTER_CORRUPT: HRESULT = 0xC03A0003u32 as HRESULT; +pub const ERROR_VHD_FORMAT_UNKNOWN: HRESULT = 0xC03A0004u32 as HRESULT; +pub const ERROR_VHD_FORMAT_UNSUPPORTED_VERSION: HRESULT = 0xC03A0005u32 as HRESULT; +pub const ERROR_VHD_SPARSE_HEADER_CHECKSUM_MISMATCH: HRESULT = 0xC03A0006u32 as HRESULT; +pub const ERROR_VHD_SPARSE_HEADER_UNSUPPORTED_VERSION: HRESULT = 0xC03A0007u32 as HRESULT; +pub const ERROR_VHD_SPARSE_HEADER_CORRUPT: HRESULT = 0xC03A0008u32 as HRESULT; +pub const ERROR_VHD_BLOCK_ALLOCATION_FAILURE: HRESULT = 0xC03A0009u32 as HRESULT; +pub const ERROR_VHD_BLOCK_ALLOCATION_TABLE_CORRUPT: HRESULT = 0xC03A000Au32 as HRESULT; +pub const ERROR_VHD_INVALID_BLOCK_SIZE: HRESULT = 0xC03A000Bu32 as HRESULT; +pub const ERROR_VHD_BITMAP_MISMATCH: HRESULT = 0xC03A000Cu32 as HRESULT; +pub const ERROR_VHD_PARENT_VHD_NOT_FOUND: HRESULT = 0xC03A000Du32 as HRESULT; +pub const ERROR_VHD_CHILD_PARENT_ID_MISMATCH: HRESULT = 0xC03A000Eu32 as HRESULT; +pub const ERROR_VHD_CHILD_PARENT_TIMESTAMP_MISMATCH: HRESULT = 0xC03A000Fu32 as HRESULT; +pub const ERROR_VHD_METADATA_READ_FAILURE: HRESULT = 0xC03A0010u32 as HRESULT; +pub const ERROR_VHD_METADATA_WRITE_FAILURE: HRESULT = 0xC03A0011u32 as HRESULT; +pub const ERROR_VHD_INVALID_SIZE: HRESULT = 0xC03A0012u32 as HRESULT; +pub const ERROR_VHD_INVALID_FILE_SIZE: HRESULT = 0xC03A0013u32 as HRESULT; +pub const ERROR_VIRTDISK_PROVIDER_NOT_FOUND: HRESULT = 0xC03A0014u32 as HRESULT; +pub const ERROR_VIRTDISK_NOT_VIRTUAL_DISK: HRESULT = 0xC03A0015u32 as HRESULT; +pub const ERROR_VHD_PARENT_VHD_ACCESS_DENIED: HRESULT = 0xC03A0016u32 as HRESULT; +pub const ERROR_VHD_CHILD_PARENT_SIZE_MISMATCH: HRESULT = 0xC03A0017u32 as HRESULT; +pub const ERROR_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED: HRESULT = 0xC03A0018u32 as HRESULT; +pub const ERROR_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT: HRESULT = 0xC03A0019u32 as HRESULT; +pub const ERROR_VIRTUAL_DISK_LIMITATION: HRESULT = 0xC03A001Au32 as HRESULT; +pub const ERROR_VHD_INVALID_TYPE: HRESULT = 0xC03A001Bu32 as HRESULT; +pub const ERROR_VHD_INVALID_STATE: HRESULT = 0xC03A001Cu32 as HRESULT; +pub const ERROR_VIRTDISK_UNSUPPORTED_DISK_SECTOR_SIZE: HRESULT = 0xC03A001Du32 as HRESULT; +pub const ERROR_VIRTDISK_DISK_ALREADY_OWNED: HRESULT = 0xC03A001Eu32 as HRESULT; +pub const ERROR_VIRTDISK_DISK_ONLINE_AND_WRITABLE: HRESULT = 0xC03A001Fu32 as HRESULT; +pub const ERROR_CTLOG_TRACKING_NOT_INITIALIZED: HRESULT = 0xC03A0020u32 as HRESULT; +pub const ERROR_CTLOG_LOGFILE_SIZE_EXCEEDED_MAXSIZE: HRESULT = 0xC03A0021u32 as HRESULT; +pub const ERROR_CTLOG_VHD_CHANGED_OFFLINE: HRESULT = 0xC03A0022u32 as HRESULT; +pub const ERROR_CTLOG_INVALID_TRACKING_STATE: HRESULT = 0xC03A0023u32 as HRESULT; +pub const ERROR_CTLOG_INCONSISTENT_TRACKING_FILE: HRESULT = 0xC03A0024u32 as HRESULT; +pub const ERROR_VHD_RESIZE_WOULD_TRUNCATE_DATA: HRESULT = 0xC03A0025u32 as HRESULT; +pub const ERROR_VHD_COULD_NOT_COMPUTE_MINIMUM_VIRTUAL_SIZE: HRESULT = 0xC03A0026u32 as HRESULT; +pub const ERROR_VHD_ALREADY_AT_OR_BELOW_MINIMUM_VIRTUAL_SIZE: HRESULT = 0xC03A0027u32 as HRESULT; +pub const ERROR_VHD_METADATA_FULL: HRESULT = 0xC03A0028u32 as HRESULT; +pub const ERROR_QUERY_STORAGE_ERROR: HRESULT = 0x803A0001u32 as HRESULT; +pub const SDIAG_E_CANCELLED: HRESULT = 0x803C0100u32 as HRESULT; +pub const SDIAG_E_SCRIPT: HRESULT = 0x803C0101u32 as HRESULT; +pub const SDIAG_E_POWERSHELL: HRESULT = 0x803C0102u32 as HRESULT; +pub const SDIAG_E_MANAGEDHOST: HRESULT = 0x803C0103u32 as HRESULT; +pub const SDIAG_E_NOVERIFIER: HRESULT = 0x803C0104u32 as HRESULT; +pub const SDIAG_S_CANNOTRUN: HRESULT = 0x003C0105; +pub const SDIAG_E_DISABLED: HRESULT = 0x803C0106u32 as HRESULT; +pub const SDIAG_E_TRUST: HRESULT = 0x803C0107u32 as HRESULT; +pub const SDIAG_E_CANNOTRUN: HRESULT = 0x803C0108u32 as HRESULT; +pub const SDIAG_E_VERSION: HRESULT = 0x803C0109u32 as HRESULT; +pub const SDIAG_E_RESOURCE: HRESULT = 0x803C010Au32 as HRESULT; +pub const SDIAG_E_ROOTCAUSE: HRESULT = 0x803C010Bu32 as HRESULT; +pub const WPN_E_CHANNEL_CLOSED: HRESULT = 0x803E0100u32 as HRESULT; +pub const WPN_E_CHANNEL_REQUEST_NOT_COMPLETE: HRESULT = 0x803E0101u32 as HRESULT; +pub const WPN_E_INVALID_APP: HRESULT = 0x803E0102u32 as HRESULT; +pub const WPN_E_OUTSTANDING_CHANNEL_REQUEST: HRESULT = 0x803E0103u32 as HRESULT; +pub const WPN_E_DUPLICATE_CHANNEL: HRESULT = 0x803E0104u32 as HRESULT; +pub const WPN_E_PLATFORM_UNAVAILABLE: HRESULT = 0x803E0105u32 as HRESULT; +pub const WPN_E_NOTIFICATION_POSTED: HRESULT = 0x803E0106u32 as HRESULT; +pub const WPN_E_NOTIFICATION_HIDDEN: HRESULT = 0x803E0107u32 as HRESULT; +pub const WPN_E_NOTIFICATION_NOT_POSTED: HRESULT = 0x803E0108u32 as HRESULT; +pub const WPN_E_CLOUD_DISABLED: HRESULT = 0x803E0109u32 as HRESULT; +pub const WPN_E_CLOUD_INCAPABLE: HRESULT = 0x803E0110u32 as HRESULT; +pub const WPN_E_CLOUD_AUTH_UNAVAILABLE: HRESULT = 0x803E011Au32 as HRESULT; +pub const WPN_E_CLOUD_SERVICE_UNAVAILABLE: HRESULT = 0x803E011Bu32 as HRESULT; +pub const WPN_E_FAILED_LOCK_SCREEN_UPDATE_INTIALIZATION: HRESULT = 0x803E011Cu32 as HRESULT; +pub const WPN_E_NOTIFICATION_DISABLED: HRESULT = 0x803E0111u32 as HRESULT; +pub const WPN_E_NOTIFICATION_INCAPABLE: HRESULT = 0x803E0112u32 as HRESULT; +pub const WPN_E_INTERNET_INCAPABLE: HRESULT = 0x803E0113u32 as HRESULT; +pub const WPN_E_NOTIFICATION_TYPE_DISABLED: HRESULT = 0x803E0114u32 as HRESULT; +pub const WPN_E_NOTIFICATION_SIZE: HRESULT = 0x803E0115u32 as HRESULT; +pub const WPN_E_TAG_SIZE: HRESULT = 0x803E0116u32 as HRESULT; +pub const WPN_E_ACCESS_DENIED: HRESULT = 0x803E0117u32 as HRESULT; +pub const WPN_E_DUPLICATE_REGISTRATION: HRESULT = 0x803E0118u32 as HRESULT; +pub const WPN_E_PUSH_NOTIFICATION_INCAPABLE: HRESULT = 0x803E0119u32 as HRESULT; +pub const WPN_E_DEV_ID_SIZE: HRESULT = 0x803E0120u32 as HRESULT; +pub const WPN_E_TAG_ALPHANUMERIC: HRESULT = 0x803E012Au32 as HRESULT; +pub const WPN_E_INVALID_HTTP_STATUS_CODE: HRESULT = 0x803E012Bu32 as HRESULT; +pub const WPN_E_OUT_OF_SESSION: HRESULT = 0x803E0200u32 as HRESULT; +pub const WPN_E_POWER_SAVE: HRESULT = 0x803E0201u32 as HRESULT; +pub const WPN_E_IMAGE_NOT_FOUND_IN_CACHE: HRESULT = 0x803E0202u32 as HRESULT; +pub const WPN_E_ALL_URL_NOT_COMPLETED: HRESULT = 0x803E0203u32 as HRESULT; +pub const WPN_E_INVALID_CLOUD_IMAGE: HRESULT = 0x803E0204u32 as HRESULT; +pub const WPN_E_NOTIFICATION_ID_MATCHED: HRESULT = 0x803E0205u32 as HRESULT; +pub const WPN_E_CALLBACK_ALREADY_REGISTERED: HRESULT = 0x803E0206u32 as HRESULT; +pub const WPN_E_TOAST_NOTIFICATION_DROPPED: HRESULT = 0x803E0207u32 as HRESULT; +pub const WPN_E_STORAGE_LOCKED: HRESULT = 0x803E0208u32 as HRESULT; +pub const E_MBN_CONTEXT_NOT_ACTIVATED: HRESULT = 0x80548201u32 as HRESULT; +pub const E_MBN_BAD_SIM: HRESULT = 0x80548202u32 as HRESULT; +pub const E_MBN_DATA_CLASS_NOT_AVAILABLE: HRESULT = 0x80548203u32 as HRESULT; +pub const E_MBN_INVALID_ACCESS_STRING: HRESULT = 0x80548204u32 as HRESULT; +pub const E_MBN_MAX_ACTIVATED_CONTEXTS: HRESULT = 0x80548205u32 as HRESULT; +pub const E_MBN_PACKET_SVC_DETACHED: HRESULT = 0x80548206u32 as HRESULT; +pub const E_MBN_PROVIDER_NOT_VISIBLE: HRESULT = 0x80548207u32 as HRESULT; +pub const E_MBN_RADIO_POWER_OFF: HRESULT = 0x80548208u32 as HRESULT; +pub const E_MBN_SERVICE_NOT_ACTIVATED: HRESULT = 0x80548209u32 as HRESULT; +pub const E_MBN_SIM_NOT_INSERTED: HRESULT = 0x8054820Au32 as HRESULT; +pub const E_MBN_VOICE_CALL_IN_PROGRESS: HRESULT = 0x8054820Bu32 as HRESULT; +pub const E_MBN_INVALID_CACHE: HRESULT = 0x8054820Cu32 as HRESULT; +pub const E_MBN_NOT_REGISTERED: HRESULT = 0x8054820Du32 as HRESULT; +pub const E_MBN_PROVIDERS_NOT_FOUND: HRESULT = 0x8054820Eu32 as HRESULT; +pub const E_MBN_PIN_NOT_SUPPORTED: HRESULT = 0x8054820Fu32 as HRESULT; +pub const E_MBN_PIN_REQUIRED: HRESULT = 0x80548210u32 as HRESULT; +pub const E_MBN_PIN_DISABLED: HRESULT = 0x80548211u32 as HRESULT; +pub const E_MBN_FAILURE: HRESULT = 0x80548212u32 as HRESULT; +pub const E_MBN_INVALID_PROFILE: HRESULT = 0x80548218u32 as HRESULT; +pub const E_MBN_DEFAULT_PROFILE_EXIST: HRESULT = 0x80548219u32 as HRESULT; +pub const E_MBN_SMS_ENCODING_NOT_SUPPORTED: HRESULT = 0x80548220u32 as HRESULT; +pub const E_MBN_SMS_FILTER_NOT_SUPPORTED: HRESULT = 0x80548221u32 as HRESULT; +pub const E_MBN_SMS_INVALID_MEMORY_INDEX: HRESULT = 0x80548222u32 as HRESULT; +pub const E_MBN_SMS_LANG_NOT_SUPPORTED: HRESULT = 0x80548223u32 as HRESULT; +pub const E_MBN_SMS_MEMORY_FAILURE: HRESULT = 0x80548224u32 as HRESULT; +pub const E_MBN_SMS_NETWORK_TIMEOUT: HRESULT = 0x80548225u32 as HRESULT; +pub const E_MBN_SMS_UNKNOWN_SMSC_ADDRESS: HRESULT = 0x80548226u32 as HRESULT; +pub const E_MBN_SMS_FORMAT_NOT_SUPPORTED: HRESULT = 0x80548227u32 as HRESULT; +pub const E_MBN_SMS_OPERATION_NOT_ALLOWED: HRESULT = 0x80548228u32 as HRESULT; +pub const E_MBN_SMS_MEMORY_FULL: HRESULT = 0x80548229u32 as HRESULT; +pub const PEER_E_IPV6_NOT_INSTALLED: HRESULT = 0x80630001u32 as HRESULT; +pub const PEER_E_NOT_INITIALIZED: HRESULT = 0x80630002u32 as HRESULT; +pub const PEER_E_CANNOT_START_SERVICE: HRESULT = 0x80630003u32 as HRESULT; +pub const PEER_E_NOT_LICENSED: HRESULT = 0x80630004u32 as HRESULT; +pub const PEER_E_INVALID_GRAPH: HRESULT = 0x80630010u32 as HRESULT; +pub const PEER_E_DBNAME_CHANGED: HRESULT = 0x80630011u32 as HRESULT; +pub const PEER_E_DUPLICATE_GRAPH: HRESULT = 0x80630012u32 as HRESULT; +pub const PEER_E_GRAPH_NOT_READY: HRESULT = 0x80630013u32 as HRESULT; +pub const PEER_E_GRAPH_SHUTTING_DOWN: HRESULT = 0x80630014u32 as HRESULT; +pub const PEER_E_GRAPH_IN_USE: HRESULT = 0x80630015u32 as HRESULT; +pub const PEER_E_INVALID_DATABASE: HRESULT = 0x80630016u32 as HRESULT; +pub const PEER_E_TOO_MANY_ATTRIBUTES: HRESULT = 0x80630017u32 as HRESULT; +pub const PEER_E_CONNECTION_NOT_FOUND: HRESULT = 0x80630103u32 as HRESULT; +pub const PEER_E_CONNECT_SELF: HRESULT = 0x80630106u32 as HRESULT; +pub const PEER_E_ALREADY_LISTENING: HRESULT = 0x80630107u32 as HRESULT; +pub const PEER_E_NODE_NOT_FOUND: HRESULT = 0x80630108u32 as HRESULT; +pub const PEER_E_CONNECTION_FAILED: HRESULT = 0x80630109u32 as HRESULT; +pub const PEER_E_CONNECTION_NOT_AUTHENTICATED: HRESULT = 0x8063010Au32 as HRESULT; +pub const PEER_E_CONNECTION_REFUSED: HRESULT = 0x8063010Bu32 as HRESULT; +pub const PEER_E_CLASSIFIER_TOO_LONG: HRESULT = 0x80630201u32 as HRESULT; +pub const PEER_E_TOO_MANY_IDENTITIES: HRESULT = 0x80630202u32 as HRESULT; +pub const PEER_E_NO_KEY_ACCESS: HRESULT = 0x80630203u32 as HRESULT; +pub const PEER_E_GROUPS_EXIST: HRESULT = 0x80630204u32 as HRESULT; +pub const PEER_E_RECORD_NOT_FOUND: HRESULT = 0x80630301u32 as HRESULT; +pub const PEER_E_DATABASE_ACCESSDENIED: HRESULT = 0x80630302u32 as HRESULT; +pub const PEER_E_DBINITIALIZATION_FAILED: HRESULT = 0x80630303u32 as HRESULT; +pub const PEER_E_MAX_RECORD_SIZE_EXCEEDED: HRESULT = 0x80630304u32 as HRESULT; +pub const PEER_E_DATABASE_ALREADY_PRESENT: HRESULT = 0x80630305u32 as HRESULT; +pub const PEER_E_DATABASE_NOT_PRESENT: HRESULT = 0x80630306u32 as HRESULT; +pub const PEER_E_IDENTITY_NOT_FOUND: HRESULT = 0x80630401u32 as HRESULT; +pub const PEER_E_EVENT_HANDLE_NOT_FOUND: HRESULT = 0x80630501u32 as HRESULT; +pub const PEER_E_INVALID_SEARCH: HRESULT = 0x80630601u32 as HRESULT; +pub const PEER_E_INVALID_ATTRIBUTES: HRESULT = 0x80630602u32 as HRESULT; +pub const PEER_E_INVITATION_NOT_TRUSTED: HRESULT = 0x80630701u32 as HRESULT; +pub const PEER_E_CHAIN_TOO_LONG: HRESULT = 0x80630703u32 as HRESULT; +pub const PEER_E_INVALID_TIME_PERIOD: HRESULT = 0x80630705u32 as HRESULT; +pub const PEER_E_CIRCULAR_CHAIN_DETECTED: HRESULT = 0x80630706u32 as HRESULT; +pub const PEER_E_CERT_STORE_CORRUPTED: HRESULT = 0x80630801u32 as HRESULT; +pub const PEER_E_NO_CLOUD: HRESULT = 0x80631001u32 as HRESULT; +pub const PEER_E_CLOUD_NAME_AMBIGUOUS: HRESULT = 0x80631005u32 as HRESULT; +pub const PEER_E_INVALID_RECORD: HRESULT = 0x80632010u32 as HRESULT; +pub const PEER_E_NOT_AUTHORIZED: HRESULT = 0x80632020u32 as HRESULT; +pub const PEER_E_PASSWORD_DOES_NOT_MEET_POLICY: HRESULT = 0x80632021u32 as HRESULT; +pub const PEER_E_DEFERRED_VALIDATION: HRESULT = 0x80632030u32 as HRESULT; +pub const PEER_E_INVALID_GROUP_PROPERTIES: HRESULT = 0x80632040u32 as HRESULT; +pub const PEER_E_INVALID_PEER_NAME: HRESULT = 0x80632050u32 as HRESULT; +pub const PEER_E_INVALID_CLASSIFIER: HRESULT = 0x80632060u32 as HRESULT; +pub const PEER_E_INVALID_FRIENDLY_NAME: HRESULT = 0x80632070u32 as HRESULT; +pub const PEER_E_INVALID_ROLE_PROPERTY: HRESULT = 0x80632071u32 as HRESULT; +pub const PEER_E_INVALID_CLASSIFIER_PROPERTY: HRESULT = 0x80632072u32 as HRESULT; +pub const PEER_E_INVALID_RECORD_EXPIRATION: HRESULT = 0x80632080u32 as HRESULT; +pub const PEER_E_INVALID_CREDENTIAL_INFO: HRESULT = 0x80632081u32 as HRESULT; +pub const PEER_E_INVALID_CREDENTIAL: HRESULT = 0x80632082u32 as HRESULT; +pub const PEER_E_INVALID_RECORD_SIZE: HRESULT = 0x80632083u32 as HRESULT; +pub const PEER_E_UNSUPPORTED_VERSION: HRESULT = 0x80632090u32 as HRESULT; +pub const PEER_E_GROUP_NOT_READY: HRESULT = 0x80632091u32 as HRESULT; +pub const PEER_E_GROUP_IN_USE: HRESULT = 0x80632092u32 as HRESULT; +pub const PEER_E_INVALID_GROUP: HRESULT = 0x80632093u32 as HRESULT; +pub const PEER_E_NO_MEMBERS_FOUND: HRESULT = 0x80632094u32 as HRESULT; +pub const PEER_E_NO_MEMBER_CONNECTIONS: HRESULT = 0x80632095u32 as HRESULT; +pub const PEER_E_UNABLE_TO_LISTEN: HRESULT = 0x80632096u32 as HRESULT; +pub const PEER_E_IDENTITY_DELETED: HRESULT = 0x806320A0u32 as HRESULT; +pub const PEER_E_SERVICE_NOT_AVAILABLE: HRESULT = 0x806320A1u32 as HRESULT; +pub const PEER_E_CONTACT_NOT_FOUND: HRESULT = 0x80636001u32 as HRESULT; +pub const PEER_S_GRAPH_DATA_CREATED: HRESULT = 0x00630001; +pub const PEER_S_NO_EVENT_DATA: HRESULT = 0x00630002; +pub const PEER_S_ALREADY_CONNECTED: HRESULT = 0x00632000; +pub const PEER_S_SUBSCRIPTION_EXISTS: HRESULT = 0x00636000; +pub const PEER_S_NO_CONNECTIVITY: HRESULT = 0x00630005; +pub const PEER_S_ALREADY_A_MEMBER: HRESULT = 0x00630006; +pub const PEER_E_CANNOT_CONVERT_PEER_NAME: HRESULT = 0x80634001u32 as HRESULT; +pub const PEER_E_INVALID_PEER_HOST_NAME: HRESULT = 0x80634002u32 as HRESULT; +pub const PEER_E_NO_MORE: HRESULT = 0x80634003u32 as HRESULT; +pub const PEER_E_PNRP_DUPLICATE_PEER_NAME: HRESULT = 0x80634005u32 as HRESULT; +pub const PEER_E_INVITE_CANCELLED: HRESULT = 0x80637000u32 as HRESULT; +pub const PEER_E_INVITE_RESPONSE_NOT_AVAILABLE: HRESULT = 0x80637001u32 as HRESULT; +pub const PEER_E_NOT_SIGNED_IN: HRESULT = 0x80637003u32 as HRESULT; +pub const PEER_E_PRIVACY_DECLINED: HRESULT = 0x80637004u32 as HRESULT; +pub const PEER_E_TIMEOUT: HRESULT = 0x80637005u32 as HRESULT; +pub const PEER_E_INVALID_ADDRESS: HRESULT = 0x80637007u32 as HRESULT; +pub const PEER_E_FW_EXCEPTION_DISABLED: HRESULT = 0x80637008u32 as HRESULT; +pub const PEER_E_FW_BLOCKED_BY_POLICY: HRESULT = 0x80637009u32 as HRESULT; +pub const PEER_E_FW_BLOCKED_BY_SHIELDS_UP: HRESULT = 0x8063700Au32 as HRESULT; +pub const PEER_E_FW_DECLINED: HRESULT = 0x8063700Bu32 as HRESULT; +pub const UI_E_CREATE_FAILED: HRESULT = 0x802A0001u32 as HRESULT; +pub const UI_E_SHUTDOWN_CALLED: HRESULT = 0x802A0002u32 as HRESULT; +pub const UI_E_ILLEGAL_REENTRANCY: HRESULT = 0x802A0003u32 as HRESULT; +pub const UI_E_OBJECT_SEALED: HRESULT = 0x802A0004u32 as HRESULT; +pub const UI_E_VALUE_NOT_SET: HRESULT = 0x802A0005u32 as HRESULT; +pub const UI_E_VALUE_NOT_DETERMINED: HRESULT = 0x802A0006u32 as HRESULT; +pub const UI_E_INVALID_OUTPUT: HRESULT = 0x802A0007u32 as HRESULT; +pub const UI_E_BOOLEAN_EXPECTED: HRESULT = 0x802A0008u32 as HRESULT; +pub const UI_E_DIFFERENT_OWNER: HRESULT = 0x802A0009u32 as HRESULT; +pub const UI_E_AMBIGUOUS_MATCH: HRESULT = 0x802A000Au32 as HRESULT; +pub const UI_E_FP_OVERFLOW: HRESULT = 0x802A000Bu32 as HRESULT; +pub const UI_E_WRONG_THREAD: HRESULT = 0x802A000Cu32 as HRESULT; +pub const UI_E_STORYBOARD_ACTIVE: HRESULT = 0x802A0101u32 as HRESULT; +pub const UI_E_STORYBOARD_NOT_PLAYING: HRESULT = 0x802A0102u32 as HRESULT; +pub const UI_E_START_KEYFRAME_AFTER_END: HRESULT = 0x802A0103u32 as HRESULT; +pub const UI_E_END_KEYFRAME_NOT_DETERMINED: HRESULT = 0x802A0104u32 as HRESULT; +pub const UI_E_LOOPS_OVERLAP: HRESULT = 0x802A0105u32 as HRESULT; +pub const UI_E_TRANSITION_ALREADY_USED: HRESULT = 0x802A0106u32 as HRESULT; +pub const UI_E_TRANSITION_NOT_IN_STORYBOARD: HRESULT = 0x802A0107u32 as HRESULT; +pub const UI_E_TRANSITION_ECLIPSED: HRESULT = 0x802A0108u32 as HRESULT; +pub const UI_E_TIME_BEFORE_LAST_UPDATE: HRESULT = 0x802A0109u32 as HRESULT; +pub const UI_E_TIMER_CLIENT_ALREADY_CONNECTED: HRESULT = 0x802A010Au32 as HRESULT; +pub const UI_E_INVALID_DIMENSION: HRESULT = 0x802A010Bu32 as HRESULT; +pub const UI_E_PRIMITIVE_OUT_OF_BOUNDS: HRESULT = 0x802A010Cu32 as HRESULT; +pub const UI_E_WINDOW_CLOSED: HRESULT = 0x802A0201u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_HANDLE: HRESULT = 0x80650001u32 as HRESULT; +pub const E_BLUETOOTH_ATT_READ_NOT_PERMITTED: HRESULT = 0x80650002u32 as HRESULT; +pub const E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED: HRESULT = 0x80650003u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_PDU: HRESULT = 0x80650004u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_AUTHENTICATION: HRESULT = 0x80650005u32 as HRESULT; +pub const E_BLUETOOTH_ATT_REQUEST_NOT_SUPPORTED: HRESULT = 0x80650006u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_OFFSET: HRESULT = 0x80650007u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_AUTHORIZATION: HRESULT = 0x80650008u32 as HRESULT; +pub const E_BLUETOOTH_ATT_PREPARE_QUEUE_FULL: HRESULT = 0x80650009u32 as HRESULT; +pub const E_BLUETOOTH_ATT_ATTRIBUTE_NOT_FOUND: HRESULT = 0x8065000Au32 as HRESULT; +pub const E_BLUETOOTH_ATT_ATTRIBUTE_NOT_LONG: HRESULT = 0x8065000Bu32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION_KEY_SIZE: HRESULT = 0x8065000Cu32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH: HRESULT = 0x8065000Du32 as HRESULT; +pub const E_BLUETOOTH_ATT_UNLIKELY: HRESULT = 0x8065000Eu32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION: HRESULT = 0x8065000Fu32 as HRESULT; +pub const E_BLUETOOTH_ATT_UNSUPPORTED_GROUP_TYPE: HRESULT = 0x80650010u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_RESOURCES: HRESULT = 0x80650011u32 as HRESULT; +pub const E_BLUETOOTH_ATT_UNKNOWN_ERROR: HRESULT = 0x80651000u32 as HRESULT; +pub const E_AUDIO_ENGINE_NODE_NOT_FOUND: HRESULT = 0x80660001u32 as HRESULT; +pub const E_HDAUDIO_EMPTY_CONNECTION_LIST: HRESULT = 0x80660002u32 as HRESULT; +pub const E_HDAUDIO_CONNECTION_LIST_NOT_SUPPORTED: HRESULT = 0x80660003u32 as HRESULT; +pub const E_HDAUDIO_NO_LOGICAL_DEVICES_CREATED: HRESULT = 0x80660004u32 as HRESULT; +pub const E_HDAUDIO_NULL_LINKED_LIST_ENTRY: HRESULT = 0x80660005u32 as HRESULT; +pub const ERROR_SPACES_POOL_WAS_DELETED: HRESULT = 0x00E70001; +pub const ERROR_SPACES_RESILIENCY_TYPE_INVALID: HRESULT = 0x80E70003u32 as HRESULT; +pub const ERROR_SPACES_DRIVE_SECTOR_SIZE_INVALID: HRESULT = 0x80E70004u32 as HRESULT; +pub const ERROR_SPACES_DRIVE_REDUNDANCY_INVALID: HRESULT = 0x80E70006u32 as HRESULT; +pub const ERROR_SPACES_NUMBER_OF_DATA_COPIES_INVALID: HRESULT = 0x80E70007u32 as HRESULT; +pub const ERROR_SPACES_PARITY_LAYOUT_INVALID: HRESULT = 0x80E70008u32 as HRESULT; +pub const ERROR_SPACES_INTERLEAVE_LENGTH_INVALID: HRESULT = 0x80E70009u32 as HRESULT; +pub const ERROR_SPACES_NUMBER_OF_COLUMNS_INVALID: HRESULT = 0x80E7000Au32 as HRESULT; +pub const ERROR_SPACES_NOT_ENOUGH_DRIVES: HRESULT = 0x80E7000Bu32 as HRESULT; +pub const ERROR_VOLSNAP_BOOTFILE_NOT_VALID: HRESULT = 0x80820001u32 as HRESULT; +pub const ERROR_TIERING_NOT_SUPPORTED_ON_VOLUME: HRESULT = 0x80830001u32 as HRESULT; +pub const ERROR_TIERING_VOLUME_DISMOUNT_IN_PROGRESS: HRESULT = 0x80830002u32 as HRESULT; +pub const ERROR_TIERING_STORAGE_TIER_NOT_FOUND: HRESULT = 0x80830003u32 as HRESULT; +pub const ERROR_TIERING_INVALID_FILE_ID: HRESULT = 0x80830004u32 as HRESULT; +pub const ERROR_TIERING_WRONG_CLUSTER_NODE: HRESULT = 0x80830005u32 as HRESULT; +pub const ERROR_TIERING_ALREADY_PROCESSING: HRESULT = 0x80830006u32 as HRESULT; +pub const ERROR_TIERING_CANNOT_PIN_OBJECT: HRESULT = 0x80830007u32 as HRESULT; +pub const DXGI_STATUS_OCCLUDED: HRESULT = 0x087A0001; +pub const DXGI_STATUS_CLIPPED: HRESULT = 0x087A0002; +pub const DXGI_STATUS_NO_REDIRECTION: HRESULT = 0x087A0004; +pub const DXGI_STATUS_NO_DESKTOP_ACCESS: HRESULT = 0x087A0005; +pub const DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: HRESULT = 0x087A0006; +pub const DXGI_STATUS_MODE_CHANGED: HRESULT = 0x087A0007; +pub const DXGI_STATUS_MODE_CHANGE_IN_PROGRESS: HRESULT = 0x087A0008; +pub const DXGI_ERROR_INVALID_CALL: HRESULT = 0x887A0001u32 as HRESULT; +pub const DXGI_ERROR_NOT_FOUND: HRESULT = 0x887A0002u32 as HRESULT; +pub const DXGI_ERROR_MORE_DATA: HRESULT = 0x887A0003u32 as HRESULT; +pub const DXGI_ERROR_UNSUPPORTED: HRESULT = 0x887A0004u32 as HRESULT; +pub const DXGI_ERROR_DEVICE_REMOVED: HRESULT = 0x887A0005u32 as HRESULT; +pub const DXGI_ERROR_DEVICE_HUNG: HRESULT = 0x887A0006u32 as HRESULT; +pub const DXGI_ERROR_DEVICE_RESET: HRESULT = 0x887A0007u32 as HRESULT; +pub const DXGI_ERROR_WAS_STILL_DRAWING: HRESULT = 0x887A000Au32 as HRESULT; +pub const DXGI_ERROR_FRAME_STATISTICS_DISJOINT: HRESULT = 0x887A000Bu32 as HRESULT; +pub const DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: HRESULT = 0x887A000Cu32 as HRESULT; +pub const DXGI_ERROR_DRIVER_INTERNAL_ERROR: HRESULT = 0x887A0020u32 as HRESULT; +pub const DXGI_ERROR_NONEXCLUSIVE: HRESULT = 0x887A0021u32 as HRESULT; +pub const DXGI_ERROR_NOT_CURRENTLY_AVAILABLE: HRESULT = 0x887A0022u32 as HRESULT; +pub const DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED: HRESULT = 0x887A0023u32 as HRESULT; +pub const DXGI_ERROR_REMOTE_OUTOFMEMORY: HRESULT = 0x887A0024u32 as HRESULT; +pub const DXGI_ERROR_ACCESS_LOST: HRESULT = 0x887A0026u32 as HRESULT; +pub const DXGI_ERROR_WAIT_TIMEOUT: HRESULT = 0x887A0027u32 as HRESULT; +pub const DXGI_ERROR_SESSION_DISCONNECTED: HRESULT = 0x887A0028u32 as HRESULT; +pub const DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE: HRESULT = 0x887A0029u32 as HRESULT; +pub const DXGI_ERROR_CANNOT_PROTECT_CONTENT: HRESULT = 0x887A002Au32 as HRESULT; +pub const DXGI_ERROR_ACCESS_DENIED: HRESULT = 0x887A002Bu32 as HRESULT; +pub const DXGI_ERROR_NAME_ALREADY_EXISTS: HRESULT = 0x887A002Cu32 as HRESULT; +pub const DXGI_ERROR_SDK_COMPONENT_MISSING: HRESULT = 0x887A002Du32 as HRESULT; +pub const DXGI_STATUS_UNOCCLUDED: HRESULT = 0x087A0009; +pub const DXGI_STATUS_DDA_WAS_STILL_DRAWING: HRESULT = 0x087A000A; +pub const DXGI_ERROR_MODE_CHANGE_IN_PROGRESS: HRESULT = 0x887A0025u32 as HRESULT; +pub const DXGI_DDI_ERR_WASSTILLDRAWING: HRESULT = 0x887B0001u32 as HRESULT; +pub const DXGI_DDI_ERR_UNSUPPORTED: HRESULT = 0x887B0002u32 as HRESULT; +pub const DXGI_DDI_ERR_NONEXCLUSIVE: HRESULT = 0x887B0003u32 as HRESULT; +pub const D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: HRESULT = 0x88790001u32 as HRESULT; +pub const D3D10_ERROR_FILE_NOT_FOUND: HRESULT = 0x88790002u32 as HRESULT; +pub const D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: HRESULT = 0x887C0001u32 as HRESULT; +pub const D3D11_ERROR_FILE_NOT_FOUND: HRESULT = 0x887C0002u32 as HRESULT; +pub const D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS: HRESULT = 0x887C0003u32 as HRESULT; +pub const D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD: HRESULT = 0x887C0004u32 as HRESULT; +pub const D2DERR_WRONG_STATE: HRESULT = 0x88990001u32 as HRESULT; +pub const D2DERR_NOT_INITIALIZED: HRESULT = 0x88990002u32 as HRESULT; +pub const D2DERR_UNSUPPORTED_OPERATION: HRESULT = 0x88990003u32 as HRESULT; +pub const D2DERR_SCANNER_FAILED: HRESULT = 0x88990004u32 as HRESULT; +pub const D2DERR_SCREEN_ACCESS_DENIED: HRESULT = 0x88990005u32 as HRESULT; +pub const D2DERR_DISPLAY_STATE_INVALID: HRESULT = 0x88990006u32 as HRESULT; +pub const D2DERR_ZERO_VECTOR: HRESULT = 0x88990007u32 as HRESULT; +pub const D2DERR_INTERNAL_ERROR: HRESULT = 0x88990008u32 as HRESULT; +pub const D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED: HRESULT = 0x88990009u32 as HRESULT; +pub const D2DERR_INVALID_CALL: HRESULT = 0x8899000Au32 as HRESULT; +pub const D2DERR_NO_HARDWARE_DEVICE: HRESULT = 0x8899000Bu32 as HRESULT; +pub const D2DERR_RECREATE_TARGET: HRESULT = 0x8899000Cu32 as HRESULT; +pub const D2DERR_TOO_MANY_SHADER_ELEMENTS: HRESULT = 0x8899000Du32 as HRESULT; +pub const D2DERR_SHADER_COMPILE_FAILED: HRESULT = 0x8899000Eu32 as HRESULT; +pub const D2DERR_MAX_TEXTURE_SIZE_EXCEEDED: HRESULT = 0x8899000Fu32 as HRESULT; +pub const D2DERR_UNSUPPORTED_VERSION: HRESULT = 0x88990010u32 as HRESULT; +pub const D2DERR_BAD_NUMBER: HRESULT = 0x88990011u32 as HRESULT; +pub const D2DERR_WRONG_FACTORY: HRESULT = 0x88990012u32 as HRESULT; +pub const D2DERR_LAYER_ALREADY_IN_USE: HRESULT = 0x88990013u32 as HRESULT; +pub const D2DERR_POP_CALL_DID_NOT_MATCH_PUSH: HRESULT = 0x88990014u32 as HRESULT; +pub const D2DERR_WRONG_RESOURCE_DOMAIN: HRESULT = 0x88990015u32 as HRESULT; +pub const D2DERR_PUSH_POP_UNBALANCED: HRESULT = 0x88990016u32 as HRESULT; +pub const D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT: HRESULT = 0x88990017u32 as HRESULT; +pub const D2DERR_INCOMPATIBLE_BRUSH_TYPES: HRESULT = 0x88990018u32 as HRESULT; +pub const D2DERR_WIN32_ERROR: HRESULT = 0x88990019u32 as HRESULT; +pub const D2DERR_TARGET_NOT_GDI_COMPATIBLE: HRESULT = 0x8899001Au32 as HRESULT; +pub const D2DERR_TEXT_EFFECT_IS_WRONG_TYPE: HRESULT = 0x8899001Bu32 as HRESULT; +pub const D2DERR_TEXT_RENDERER_NOT_RELEASED: HRESULT = 0x8899001Cu32 as HRESULT; +pub const D2DERR_EXCEEDS_MAX_BITMAP_SIZE: HRESULT = 0x8899001Du32 as HRESULT; +pub const D2DERR_INVALID_GRAPH_CONFIGURATION: HRESULT = 0x8899001Eu32 as HRESULT; +pub const D2DERR_INVALID_INTERNAL_GRAPH_CONFIGURATION: HRESULT = 0x8899001Fu32 as HRESULT; +pub const D2DERR_CYCLIC_GRAPH: HRESULT = 0x88990020u32 as HRESULT; +pub const D2DERR_BITMAP_CANNOT_DRAW: HRESULT = 0x88990021u32 as HRESULT; +pub const D2DERR_OUTSTANDING_BITMAP_REFERENCES: HRESULT = 0x88990022u32 as HRESULT; +pub const D2DERR_ORIGINAL_TARGET_NOT_BOUND: HRESULT = 0x88990023u32 as HRESULT; +pub const D2DERR_INVALID_TARGET: HRESULT = 0x88990024u32 as HRESULT; +pub const D2DERR_BITMAP_BOUND_AS_TARGET: HRESULT = 0x88990025u32 as HRESULT; +pub const D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES: HRESULT = 0x88990026u32 as HRESULT; +pub const D2DERR_INTERMEDIATE_TOO_LARGE: HRESULT = 0x88990027u32 as HRESULT; +pub const D2DERR_EFFECT_IS_NOT_REGISTERED: HRESULT = 0x88990028u32 as HRESULT; +pub const D2DERR_INVALID_PROPERTY: HRESULT = 0x88990029u32 as HRESULT; +pub const D2DERR_NO_SUBPROPERTIES: HRESULT = 0x8899002Au32 as HRESULT; +pub const D2DERR_PRINT_JOB_CLOSED: HRESULT = 0x8899002Bu32 as HRESULT; +pub const D2DERR_PRINT_FORMAT_NOT_SUPPORTED: HRESULT = 0x8899002Cu32 as HRESULT; +pub const D2DERR_TOO_MANY_TRANSFORM_INPUTS: HRESULT = 0x8899002Du32 as HRESULT; +pub const DWRITE_E_FILEFORMAT: HRESULT = 0x88985000u32 as HRESULT; +pub const DWRITE_E_UNEXPECTED: HRESULT = 0x88985001u32 as HRESULT; +pub const DWRITE_E_NOFONT: HRESULT = 0x88985002u32 as HRESULT; +pub const DWRITE_E_FILENOTFOUND: HRESULT = 0x88985003u32 as HRESULT; +pub const DWRITE_E_FILEACCESS: HRESULT = 0x88985004u32 as HRESULT; +pub const DWRITE_E_FONTCOLLECTIONOBSOLETE: HRESULT = 0x88985005u32 as HRESULT; +pub const DWRITE_E_ALREADYREGISTERED: HRESULT = 0x88985006u32 as HRESULT; +pub const DWRITE_E_CACHEFORMAT: HRESULT = 0x88985007u32 as HRESULT; +pub const DWRITE_E_CACHEVERSION: HRESULT = 0x88985008u32 as HRESULT; +pub const DWRITE_E_UNSUPPORTEDOPERATION: HRESULT = 0x88985009u32 as HRESULT; +pub const DWRITE_E_TEXTRENDERERINCOMPATIBLE: HRESULT = 0x8898500Au32 as HRESULT; +pub const DWRITE_E_FLOWDIRECTIONCONFLICTS: HRESULT = 0x8898500Bu32 as HRESULT; +pub const DWRITE_E_NOCOLOR: HRESULT = 0x8898500Cu32 as HRESULT; +pub const WINCODEC_ERR_WRONGSTATE: HRESULT = 0x88982F04u32 as HRESULT; +pub const WINCODEC_ERR_VALUEOUTOFRANGE: HRESULT = 0x88982F05u32 as HRESULT; +pub const WINCODEC_ERR_UNKNOWNIMAGEFORMAT: HRESULT = 0x88982F07u32 as HRESULT; +pub const WINCODEC_ERR_UNSUPPORTEDVERSION: HRESULT = 0x88982F0Bu32 as HRESULT; +pub const WINCODEC_ERR_NOTINITIALIZED: HRESULT = 0x88982F0Cu32 as HRESULT; +pub const WINCODEC_ERR_ALREADYLOCKED: HRESULT = 0x88982F0Du32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYNOTFOUND: HRESULT = 0x88982F40u32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYNOTSUPPORTED: HRESULT = 0x88982F41u32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYSIZE: HRESULT = 0x88982F42u32 as HRESULT; +pub const WINCODEC_ERR_CODECPRESENT: HRESULT = 0x88982F43u32 as HRESULT; +pub const WINCODEC_ERR_CODECNOTHUMBNAIL: HRESULT = 0x88982F44u32 as HRESULT; +pub const WINCODEC_ERR_PALETTEUNAVAILABLE: HRESULT = 0x88982F45u32 as HRESULT; +pub const WINCODEC_ERR_CODECTOOMANYSCANLINES: HRESULT = 0x88982F46u32 as HRESULT; +pub const WINCODEC_ERR_INTERNALERROR: HRESULT = 0x88982F48u32 as HRESULT; +pub const WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS: HRESULT = 0x88982F49u32 as HRESULT; +pub const WINCODEC_ERR_COMPONENTNOTFOUND: HRESULT = 0x88982F50u32 as HRESULT; +pub const WINCODEC_ERR_IMAGESIZEOUTOFRANGE: HRESULT = 0x88982F51u32 as HRESULT; +pub const WINCODEC_ERR_TOOMUCHMETADATA: HRESULT = 0x88982F52u32 as HRESULT; +pub const WINCODEC_ERR_BADIMAGE: HRESULT = 0x88982F60u32 as HRESULT; +pub const WINCODEC_ERR_BADHEADER: HRESULT = 0x88982F61u32 as HRESULT; +pub const WINCODEC_ERR_FRAMEMISSING: HRESULT = 0x88982F62u32 as HRESULT; +pub const WINCODEC_ERR_BADMETADATAHEADER: HRESULT = 0x88982F63u32 as HRESULT; +pub const WINCODEC_ERR_BADSTREAMDATA: HRESULT = 0x88982F70u32 as HRESULT; +pub const WINCODEC_ERR_STREAMWRITE: HRESULT = 0x88982F71u32 as HRESULT; +pub const WINCODEC_ERR_STREAMREAD: HRESULT = 0x88982F72u32 as HRESULT; +pub const WINCODEC_ERR_STREAMNOTAVAILABLE: HRESULT = 0x88982F73u32 as HRESULT; +pub const WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT: HRESULT = 0x88982F80u32 as HRESULT; +pub const WINCODEC_ERR_UNSUPPORTEDOPERATION: HRESULT = 0x88982F81u32 as HRESULT; +pub const WINCODEC_ERR_INVALIDREGISTRATION: HRESULT = 0x88982F8Au32 as HRESULT; +pub const WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: HRESULT = 0x88982F8Bu32 as HRESULT; +pub const WINCODEC_ERR_INSUFFICIENTBUFFER: HRESULT = 0x88982F8Cu32 as HRESULT; +pub const WINCODEC_ERR_DUPLICATEMETADATAPRESENT: HRESULT = 0x88982F8Du32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE: HRESULT = 0x88982F8Eu32 as HRESULT; +pub const WINCODEC_ERR_UNEXPECTEDSIZE: HRESULT = 0x88982F8Fu32 as HRESULT; +pub const WINCODEC_ERR_INVALIDQUERYREQUEST: HRESULT = 0x88982F90u32 as HRESULT; +pub const WINCODEC_ERR_UNEXPECTEDMETADATATYPE: HRESULT = 0x88982F91u32 as HRESULT; +pub const WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT: HRESULT = 0x88982F92u32 as HRESULT; +pub const WINCODEC_ERR_INVALIDQUERYCHARACTER: HRESULT = 0x88982F93u32 as HRESULT; +pub const WINCODEC_ERR_WIN32ERROR: HRESULT = 0x88982F94u32 as HRESULT; +pub const WINCODEC_ERR_INVALIDPROGRESSIVELEVEL: HRESULT = 0x88982F95u32 as HRESULT; +pub const MILERR_OBJECTBUSY: HRESULT = 0x88980001u32 as HRESULT; +pub const MILERR_INSUFFICIENTBUFFER: HRESULT = 0x88980002u32 as HRESULT; +pub const MILERR_WIN32ERROR: HRESULT = 0x88980003u32 as HRESULT; +pub const MILERR_SCANNER_FAILED: HRESULT = 0x88980004u32 as HRESULT; +pub const MILERR_SCREENACCESSDENIED: HRESULT = 0x88980005u32 as HRESULT; +pub const MILERR_DISPLAYSTATEINVALID: HRESULT = 0x88980006u32 as HRESULT; +pub const MILERR_NONINVERTIBLEMATRIX: HRESULT = 0x88980007u32 as HRESULT; +pub const MILERR_ZEROVECTOR: HRESULT = 0x88980008u32 as HRESULT; +pub const MILERR_TERMINATED: HRESULT = 0x88980009u32 as HRESULT; +pub const MILERR_BADNUMBER: HRESULT = 0x8898000Au32 as HRESULT; +pub const MILERR_INTERNALERROR: HRESULT = 0x88980080u32 as HRESULT; +pub const MILERR_DISPLAYFORMATNOTSUPPORTED: HRESULT = 0x88980084u32 as HRESULT; +pub const MILERR_INVALIDCALL: HRESULT = 0x88980085u32 as HRESULT; +pub const MILERR_ALREADYLOCKED: HRESULT = 0x88980086u32 as HRESULT; +pub const MILERR_NOTLOCKED: HRESULT = 0x88980087u32 as HRESULT; +pub const MILERR_DEVICECANNOTRENDERTEXT: HRESULT = 0x88980088u32 as HRESULT; +pub const MILERR_GLYPHBITMAPMISSED: HRESULT = 0x88980089u32 as HRESULT; +pub const MILERR_MALFORMEDGLYPHCACHE: HRESULT = 0x8898008Au32 as HRESULT; +pub const MILERR_GENERIC_IGNORE: HRESULT = 0x8898008Bu32 as HRESULT; +pub const MILERR_MALFORMED_GUIDELINE_DATA: HRESULT = 0x8898008Cu32 as HRESULT; +pub const MILERR_NO_HARDWARE_DEVICE: HRESULT = 0x8898008Du32 as HRESULT; +pub const MILERR_NEED_RECREATE_AND_PRESENT: HRESULT = 0x8898008Eu32 as HRESULT; +pub const MILERR_ALREADY_INITIALIZED: HRESULT = 0x8898008Fu32 as HRESULT; +pub const MILERR_MISMATCHED_SIZE: HRESULT = 0x88980090u32 as HRESULT; +pub const MILERR_NO_REDIRECTION_SURFACE_AVAILABLE: HRESULT = 0x88980091u32 as HRESULT; +pub const MILERR_REMOTING_NOT_SUPPORTED: HRESULT = 0x88980092u32 as HRESULT; +pub const MILERR_QUEUED_PRESENT_NOT_SUPPORTED: HRESULT = 0x88980093u32 as HRESULT; +pub const MILERR_NOT_QUEUING_PRESENTS: HRESULT = 0x88980094u32 as HRESULT; +pub const MILERR_NO_REDIRECTION_SURFACE_RETRY_LATER: HRESULT = 0x88980095u32 as HRESULT; +pub const MILERR_TOOMANYSHADERELEMNTS: HRESULT = 0x88980096u32 as HRESULT; +pub const MILERR_MROW_READLOCK_FAILED: HRESULT = 0x88980097u32 as HRESULT; +pub const MILERR_MROW_UPDATE_FAILED: HRESULT = 0x88980098u32 as HRESULT; +pub const MILERR_SHADER_COMPILE_FAILED: HRESULT = 0x88980099u32 as HRESULT; +pub const MILERR_MAX_TEXTURE_SIZE_EXCEEDED: HRESULT = 0x8898009Au32 as HRESULT; +pub const MILERR_QPC_TIME_WENT_BACKWARD: HRESULT = 0x8898009Bu32 as HRESULT; +pub const MILERR_DXGI_ENUMERATION_OUT_OF_SYNC: HRESULT = 0x8898009Du32 as HRESULT; +pub const MILERR_ADAPTER_NOT_FOUND: HRESULT = 0x8898009Eu32 as HRESULT; +pub const MILERR_COLORSPACE_NOT_SUPPORTED: HRESULT = 0x8898009Fu32 as HRESULT; +pub const MILERR_PREFILTER_NOT_SUPPORTED: HRESULT = 0x889800A0u32 as HRESULT; +pub const MILERR_DISPLAYID_ACCESS_DENIED: HRESULT = 0x889800A1u32 as HRESULT; +pub const UCEERR_INVALIDPACKETHEADER: HRESULT = 0x88980400u32 as HRESULT; +pub const UCEERR_UNKNOWNPACKET: HRESULT = 0x88980401u32 as HRESULT; +pub const UCEERR_ILLEGALPACKET: HRESULT = 0x88980402u32 as HRESULT; +pub const UCEERR_MALFORMEDPACKET: HRESULT = 0x88980403u32 as HRESULT; +pub const UCEERR_ILLEGALHANDLE: HRESULT = 0x88980404u32 as HRESULT; +pub const UCEERR_HANDLELOOKUPFAILED: HRESULT = 0x88980405u32 as HRESULT; +pub const UCEERR_RENDERTHREADFAILURE: HRESULT = 0x88980406u32 as HRESULT; +pub const UCEERR_CTXSTACKFRSTTARGETNULL: HRESULT = 0x88980407u32 as HRESULT; +pub const UCEERR_CONNECTIONIDLOOKUPFAILED: HRESULT = 0x88980408u32 as HRESULT; +pub const UCEERR_BLOCKSFULL: HRESULT = 0x88980409u32 as HRESULT; +pub const UCEERR_MEMORYFAILURE: HRESULT = 0x8898040Au32 as HRESULT; +pub const UCEERR_PACKETRECORDOUTOFRANGE: HRESULT = 0x8898040Bu32 as HRESULT; +pub const UCEERR_ILLEGALRECORDTYPE: HRESULT = 0x8898040Cu32 as HRESULT; +pub const UCEERR_OUTOFHANDLES: HRESULT = 0x8898040Du32 as HRESULT; +pub const UCEERR_UNCHANGABLE_UPDATE_ATTEMPTED: HRESULT = 0x8898040Eu32 as HRESULT; +pub const UCEERR_NO_MULTIPLE_WORKER_THREADS: HRESULT = 0x8898040Fu32 as HRESULT; +pub const UCEERR_REMOTINGNOTSUPPORTED: HRESULT = 0x88980410u32 as HRESULT; +pub const UCEERR_MISSINGENDCOMMAND: HRESULT = 0x88980411u32 as HRESULT; +pub const UCEERR_MISSINGBEGINCOMMAND: HRESULT = 0x88980412u32 as HRESULT; +pub const UCEERR_CHANNELSYNCTIMEDOUT: HRESULT = 0x88980413u32 as HRESULT; +pub const UCEERR_CHANNELSYNCABANDONED: HRESULT = 0x88980414u32 as HRESULT; +pub const UCEERR_UNSUPPORTEDTRANSPORTVERSION: HRESULT = 0x88980415u32 as HRESULT; +pub const UCEERR_TRANSPORTUNAVAILABLE: HRESULT = 0x88980416u32 as HRESULT; +pub const UCEERR_FEEDBACK_UNSUPPORTED: HRESULT = 0x88980417u32 as HRESULT; +pub const UCEERR_COMMANDTRANSPORTDENIED: HRESULT = 0x88980418u32 as HRESULT; +pub const UCEERR_GRAPHICSSTREAMUNAVAILABLE: HRESULT = 0x88980419u32 as HRESULT; +pub const UCEERR_GRAPHICSSTREAMALREADYOPEN: HRESULT = 0x88980420u32 as HRESULT; +pub const UCEERR_TRANSPORTDISCONNECTED: HRESULT = 0x88980421u32 as HRESULT; +pub const UCEERR_TRANSPORTOVERLOADED: HRESULT = 0x88980422u32 as HRESULT; +pub const UCEERR_PARTITION_ZOMBIED: HRESULT = 0x88980423u32 as HRESULT; +pub const MILAVERR_NOCLOCK: HRESULT = 0x88980500u32 as HRESULT; +pub const MILAVERR_NOMEDIATYPE: HRESULT = 0x88980501u32 as HRESULT; +pub const MILAVERR_NOVIDEOMIXER: HRESULT = 0x88980502u32 as HRESULT; +pub const MILAVERR_NOVIDEOPRESENTER: HRESULT = 0x88980503u32 as HRESULT; +pub const MILAVERR_NOREADYFRAMES: HRESULT = 0x88980504u32 as HRESULT; +pub const MILAVERR_MODULENOTLOADED: HRESULT = 0x88980505u32 as HRESULT; +pub const MILAVERR_WMPFACTORYNOTREGISTERED: HRESULT = 0x88980506u32 as HRESULT; +pub const MILAVERR_INVALIDWMPVERSION: HRESULT = 0x88980507u32 as HRESULT; +pub const MILAVERR_INSUFFICIENTVIDEORESOURCES: HRESULT = 0x88980508u32 as HRESULT; +pub const MILAVERR_VIDEOACCELERATIONNOTAVAILABLE: HRESULT = 0x88980509u32 as HRESULT; +pub const MILAVERR_REQUESTEDTEXTURETOOBIG: HRESULT = 0x8898050Au32 as HRESULT; +pub const MILAVERR_SEEKFAILED: HRESULT = 0x8898050Bu32 as HRESULT; +pub const MILAVERR_UNEXPECTEDWMPFAILURE: HRESULT = 0x8898050Cu32 as HRESULT; +pub const MILAVERR_MEDIAPLAYERCLOSED: HRESULT = 0x8898050Du32 as HRESULT; +pub const MILAVERR_UNKNOWNHARDWAREERROR: HRESULT = 0x8898050Eu32 as HRESULT; +pub const MILEFFECTSERR_UNKNOWNPROPERTY: HRESULT = 0x8898060Eu32 as HRESULT; +pub const MILEFFECTSERR_EFFECTNOTPARTOFGROUP: HRESULT = 0x8898060Fu32 as HRESULT; +pub const MILEFFECTSERR_NOINPUTSOURCEATTACHED: HRESULT = 0x88980610u32 as HRESULT; +pub const MILEFFECTSERR_CONNECTORNOTCONNECTED: HRESULT = 0x88980611u32 as HRESULT; +pub const MILEFFECTSERR_CONNECTORNOTASSOCIATEDWITHEFFECT: HRESULT = 0x88980612u32 as HRESULT; +pub const MILEFFECTSERR_RESERVED: HRESULT = 0x88980613u32 as HRESULT; +pub const MILEFFECTSERR_CYCLEDETECTED: HRESULT = 0x88980614u32 as HRESULT; +pub const MILEFFECTSERR_EFFECTINMORETHANONEGRAPH: HRESULT = 0x88980615u32 as HRESULT; +pub const MILEFFECTSERR_EFFECTALREADYINAGRAPH: HRESULT = 0x88980616u32 as HRESULT; +pub const MILEFFECTSERR_EFFECTHASNOCHILDREN: HRESULT = 0x88980617u32 as HRESULT; +pub const MILEFFECTSERR_ALREADYATTACHEDTOLISTENER: HRESULT = 0x88980618u32 as HRESULT; +pub const MILEFFECTSERR_NOTAFFINETRANSFORM: HRESULT = 0x88980619u32 as HRESULT; +pub const MILEFFECTSERR_EMPTYBOUNDS: HRESULT = 0x8898061Au32 as HRESULT; +pub const MILEFFECTSERR_OUTPUTSIZETOOLARGE: HRESULT = 0x8898061Bu32 as HRESULT; +pub const DWMERR_STATE_TRANSITION_FAILED: HRESULT = 0x88980700u32 as HRESULT; +pub const DWMERR_THEME_FAILED: HRESULT = 0x88980701u32 as HRESULT; +pub const DWMERR_CATASTROPHIC_FAILURE: HRESULT = 0x88980702u32 as HRESULT; +pub const DCOMPOSITION_ERROR_WINDOW_ALREADY_COMPOSED: HRESULT = 0x88980800u32 as HRESULT; +pub const DCOMPOSITION_ERROR_SURFACE_BEING_RENDERED: HRESULT = 0x88980801u32 as HRESULT; +pub const DCOMPOSITION_ERROR_SURFACE_NOT_BEING_RENDERED: HRESULT = 0x88980802u32 as HRESULT; +pub const ONL_E_INVALID_AUTHENTICATION_TARGET: HRESULT = 0x80860001u32 as HRESULT; +pub const ONL_E_ACCESS_DENIED_BY_TOU: HRESULT = 0x80860002u32 as HRESULT; +pub const ONL_E_INVALID_APPLICATION: HRESULT = 0x80860003u32 as HRESULT; +pub const ONL_E_PASSWORD_UPDATE_REQUIRED: HRESULT = 0x80860004u32 as HRESULT; +pub const ONL_E_ACCOUNT_UPDATE_REQUIRED: HRESULT = 0x80860005u32 as HRESULT; +pub const ONL_E_FORCESIGNIN: HRESULT = 0x80860006u32 as HRESULT; +pub const ONL_E_ACCOUNT_LOCKED: HRESULT = 0x80860007u32 as HRESULT; +pub const ONL_E_PARENTAL_CONSENT_REQUIRED: HRESULT = 0x80860008u32 as HRESULT; +pub const ONL_E_EMAIL_VERIFICATION_REQUIRED: HRESULT = 0x80860009u32 as HRESULT; +pub const ONL_E_ACCOUNT_SUSPENDED_COMPROIMISE: HRESULT = 0x8086000Au32 as HRESULT; +pub const ONL_E_ACCOUNT_SUSPENDED_ABUSE: HRESULT = 0x8086000Bu32 as HRESULT; +pub const ONL_E_ACTION_REQUIRED: HRESULT = 0x8086000Cu32 as HRESULT; +pub const ONL_CONNECTION_COUNT_LIMIT: HRESULT = 0x8086000Du32 as HRESULT; +pub const ONL_E_CONNECTED_ACCOUNT_CAN_NOT_SIGNOUT: HRESULT = 0x8086000Eu32 as HRESULT; +pub const ONL_E_USER_AUTHENTICATION_REQUIRED: HRESULT = 0x8086000Fu32 as HRESULT; +pub const ONL_E_REQUEST_THROTTLED: HRESULT = 0x80860010u32 as HRESULT; +pub const FA_E_MAX_PERSISTED_ITEMS_REACHED: HRESULT = 0x80270220u32 as HRESULT; +pub const FA_E_HOMEGROUP_NOT_AVAILABLE: HRESULT = 0x80270222u32 as HRESULT; +pub const E_MONITOR_RESOLUTION_TOO_LOW: HRESULT = 0x80270250u32 as HRESULT; +pub const E_ELEVATED_ACTIVATION_NOT_SUPPORTED: HRESULT = 0x80270251u32 as HRESULT; +pub const E_UAC_DISABLED: HRESULT = 0x80270252u32 as HRESULT; +pub const E_FULL_ADMIN_NOT_SUPPORTED: HRESULT = 0x80270253u32 as HRESULT; +pub const E_APPLICATION_NOT_REGISTERED: HRESULT = 0x80270254u32 as HRESULT; +pub const E_MULTIPLE_EXTENSIONS_FOR_APPLICATION: HRESULT = 0x80270255u32 as HRESULT; +pub const E_MULTIPLE_PACKAGES_FOR_FAMILY: HRESULT = 0x80270256u32 as HRESULT; +pub const E_APPLICATION_MANAGER_NOT_RUNNING: HRESULT = 0x80270257u32 as HRESULT; +pub const S_STORE_LAUNCHED_FOR_REMEDIATION: HRESULT = 0x00270258; +pub const S_APPLICATION_ACTIVATION_ERROR_HANDLED_BY_DIALOG: HRESULT = 0x00270259; +pub const E_APPLICATION_ACTIVATION_TIMED_OUT: HRESULT = 0x8027025Au32 as HRESULT; +pub const E_APPLICATION_ACTIVATION_EXEC_FAILURE: HRESULT = 0x8027025Bu32 as HRESULT; +pub const E_APPLICATION_TEMPORARY_LICENSE_ERROR: HRESULT = 0x8027025Cu32 as HRESULT; +pub const E_APPLICATION_TRIAL_LICENSE_EXPIRED: HRESULT = 0x8027025Du32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_FILE_SYSTEM_NOT_SUPPORTED: HRESULT = 0x80270260u32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_OVERLAP: HRESULT = 0x80270261u32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_CANNOT_INDEX: HRESULT = 0x80270262u32 as HRESULT; +pub const E_SKYDRIVE_FILE_NOT_UPLOADED: HRESULT = 0x80270263u32 as HRESULT; +pub const E_SKYDRIVE_UPDATE_AVAILABILITY_FAIL: HRESULT = 0x80270264u32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_VOLUME_ROOT_NOT_SUPPORTED: HRESULT = 0x80270265u32 as HRESULT; +pub const E_SYNCENGINE_FILE_SIZE_OVER_LIMIT: HRESULT = 0x8802B001u32 as HRESULT; +pub const E_SYNCENGINE_FILE_SIZE_EXCEEDS_REMAINING_QUOTA: HRESULT = 0x8802B002u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_FILE_NAME: HRESULT = 0x8802B003u32 as HRESULT; +pub const E_SYNCENGINE_FOLDER_ITEM_COUNT_LIMIT_EXCEEDED: HRESULT = 0x8802B004u32 as HRESULT; +pub const E_SYNCENGINE_FILE_SYNC_PARTNER_ERROR: HRESULT = 0x8802B005u32 as HRESULT; +pub const E_SYNCENGINE_SYNC_PAUSED_BY_SERVICE: HRESULT = 0x8802B006u32 as HRESULT; +pub const E_SYNCENGINE_FILE_IDENTIFIER_UNKNOWN: HRESULT = 0x8802C002u32 as HRESULT; +pub const E_SYNCENGINE_SERVICE_AUTHENTICATION_FAILED: HRESULT = 0x8802C003u32 as HRESULT; +pub const E_SYNCENGINE_UNKNOWN_SERVICE_ERROR: HRESULT = 0x8802C004u32 as HRESULT; +pub const E_SYNCENGINE_SERVICE_RETURNED_UNEXPECTED_SIZE: HRESULT = 0x8802C005u32 as HRESULT; +pub const E_SYNCENGINE_REQUEST_BLOCKED_BY_SERVICE: HRESULT = 0x8802C006u32 as HRESULT; +pub const E_SYNCENGINE_REQUEST_BLOCKED_DUE_TO_CLIENT_ERROR: HRESULT = 0x8802C007u32 as HRESULT; +pub const E_SYNCENGINE_FOLDER_INACCESSIBLE: HRESULT = 0x8802D001u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_FOLDER_NAME: HRESULT = 0x8802D002u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_MARKET: HRESULT = 0x8802D003u32 as HRESULT; +pub const E_SYNCENGINE_PATH_LENGTH_LIMIT_EXCEEDED: HRESULT = 0x8802D004u32 as HRESULT; +pub const E_SYNCENGINE_REMOTE_PATH_LENGTH_LIMIT_EXCEEDED: HRESULT = 0x8802D005u32 as HRESULT; +pub const E_SYNCENGINE_CLIENT_UPDATE_NEEDED: HRESULT = 0x8802D006u32 as HRESULT; +pub const E_SYNCENGINE_PROXY_AUTHENTICATION_REQUIRED: HRESULT = 0x8802D007u32 as HRESULT; +pub const E_SYNCENGINE_STORAGE_SERVICE_PROVISIONING_FAILED: HRESULT = 0x8802D008u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_REPARSE_POINT: HRESULT = 0x8802D009u32 as HRESULT; +pub const E_SYNCENGINE_STORAGE_SERVICE_BLOCKED: HRESULT = 0x8802D00Au32 as HRESULT; +pub const E_SYNCENGINE_FOLDER_IN_REDIRECTION: HRESULT = 0x8802D00Bu32 as HRESULT; +pub const EAS_E_POLICY_NOT_MANAGED_BY_OS: HRESULT = 0x80550001u32 as HRESULT; +pub const EAS_E_POLICY_COMPLIANT_WITH_ACTIONS: HRESULT = 0x80550002u32 as HRESULT; +pub const EAS_E_REQUESTED_POLICY_NOT_ENFORCEABLE: HRESULT = 0x80550003u32 as HRESULT; +pub const EAS_E_CURRENT_USER_HAS_BLANK_PASSWORD: HRESULT = 0x80550004u32 as HRESULT; +pub const EAS_E_REQUESTED_POLICY_PASSWORD_EXPIRATION_INCOMPATIBLE: HRESULT = 0x80550005u32 as HRESULT; +pub const EAS_E_USER_CANNOT_CHANGE_PASSWORD: HRESULT = 0x80550006u32 as HRESULT; +pub const EAS_E_ADMINS_HAVE_BLANK_PASSWORD: HRESULT = 0x80550007u32 as HRESULT; +pub const EAS_E_ADMINS_CANNOT_CHANGE_PASSWORD: HRESULT = 0x80550008u32 as HRESULT; +pub const EAS_E_LOCAL_CONTROLLED_USERS_CANNOT_CHANGE_PASSWORD: HRESULT = 0x80550009u32 as HRESULT; +pub const EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CONNECTED_ADMINS: HRESULT = 0x8055000Au32 as HRESULT; +pub const EAS_E_CONNECTED_ADMINS_NEED_TO_CHANGE_PASSWORD: HRESULT = 0x8055000Bu32 as HRESULT; +pub const EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CURRENT_CONNECTED_USER: HRESULT = 0x8055000Cu32 as HRESULT; +pub const EAS_E_CURRENT_CONNECTED_USER_NEED_TO_CHANGE_PASSWORD: HRESULT = 0x8055000Du32 as HRESULT; +pub const WEB_E_UNSUPPORTED_FORMAT: HRESULT = 0x83750001u32 as HRESULT; +pub const WEB_E_INVALID_XML: HRESULT = 0x83750002u32 as HRESULT; +pub const WEB_E_MISSING_REQUIRED_ELEMENT: HRESULT = 0x83750003u32 as HRESULT; +pub const WEB_E_MISSING_REQUIRED_ATTRIBUTE: HRESULT = 0x83750004u32 as HRESULT; +pub const WEB_E_UNEXPECTED_CONTENT: HRESULT = 0x83750005u32 as HRESULT; +pub const WEB_E_RESOURCE_TOO_LARGE: HRESULT = 0x83750006u32 as HRESULT; +pub const WEB_E_INVALID_JSON_STRING: HRESULT = 0x83750007u32 as HRESULT; +pub const WEB_E_INVALID_JSON_NUMBER: HRESULT = 0x83750008u32 as HRESULT; +pub const WEB_E_JSON_VALUE_NOT_FOUND: HRESULT = 0x83750009u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED: HRESULT = 0x80190001u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED_REDIRECTION: HRESULT = 0x80190003u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED_CLIENT_ERROR: HRESULT = 0x80190004u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED_SERVER_ERROR: HRESULT = 0x80190005u32 as HRESULT; +pub const HTTP_E_STATUS_AMBIGUOUS: HRESULT = 0x8019012Cu32 as HRESULT; +pub const HTTP_E_STATUS_MOVED: HRESULT = 0x8019012Du32 as HRESULT; +pub const HTTP_E_STATUS_REDIRECT: HRESULT = 0x8019012Eu32 as HRESULT; +pub const HTTP_E_STATUS_REDIRECT_METHOD: HRESULT = 0x8019012Fu32 as HRESULT; +pub const HTTP_E_STATUS_NOT_MODIFIED: HRESULT = 0x80190130u32 as HRESULT; +pub const HTTP_E_STATUS_USE_PROXY: HRESULT = 0x80190131u32 as HRESULT; +pub const HTTP_E_STATUS_REDIRECT_KEEP_VERB: HRESULT = 0x80190133u32 as HRESULT; +pub const HTTP_E_STATUS_BAD_REQUEST: HRESULT = 0x80190190u32 as HRESULT; +pub const HTTP_E_STATUS_DENIED: HRESULT = 0x80190191u32 as HRESULT; +pub const HTTP_E_STATUS_PAYMENT_REQ: HRESULT = 0x80190192u32 as HRESULT; +pub const HTTP_E_STATUS_FORBIDDEN: HRESULT = 0x80190193u32 as HRESULT; +pub const HTTP_E_STATUS_NOT_FOUND: HRESULT = 0x80190194u32 as HRESULT; +pub const HTTP_E_STATUS_BAD_METHOD: HRESULT = 0x80190195u32 as HRESULT; +pub const HTTP_E_STATUS_NONE_ACCEPTABLE: HRESULT = 0x80190196u32 as HRESULT; +pub const HTTP_E_STATUS_PROXY_AUTH_REQ: HRESULT = 0x80190197u32 as HRESULT; +pub const HTTP_E_STATUS_REQUEST_TIMEOUT: HRESULT = 0x80190198u32 as HRESULT; +pub const HTTP_E_STATUS_CONFLICT: HRESULT = 0x80190199u32 as HRESULT; +pub const HTTP_E_STATUS_GONE: HRESULT = 0x8019019Au32 as HRESULT; +pub const HTTP_E_STATUS_LENGTH_REQUIRED: HRESULT = 0x8019019Bu32 as HRESULT; +pub const HTTP_E_STATUS_PRECOND_FAILED: HRESULT = 0x8019019Cu32 as HRESULT; +pub const HTTP_E_STATUS_REQUEST_TOO_LARGE: HRESULT = 0x8019019Du32 as HRESULT; +pub const HTTP_E_STATUS_URI_TOO_LONG: HRESULT = 0x8019019Eu32 as HRESULT; +pub const HTTP_E_STATUS_UNSUPPORTED_MEDIA: HRESULT = 0x8019019Fu32 as HRESULT; +pub const HTTP_E_STATUS_RANGE_NOT_SATISFIABLE: HRESULT = 0x801901A0u32 as HRESULT; +pub const HTTP_E_STATUS_EXPECTATION_FAILED: HRESULT = 0x801901A1u32 as HRESULT; +pub const HTTP_E_STATUS_SERVER_ERROR: HRESULT = 0x801901F4u32 as HRESULT; +pub const HTTP_E_STATUS_NOT_SUPPORTED: HRESULT = 0x801901F5u32 as HRESULT; +pub const HTTP_E_STATUS_BAD_GATEWAY: HRESULT = 0x801901F6u32 as HRESULT; +pub const HTTP_E_STATUS_SERVICE_UNAVAIL: HRESULT = 0x801901F7u32 as HRESULT; +pub const HTTP_E_STATUS_GATEWAY_TIMEOUT: HRESULT = 0x801901F8u32 as HRESULT; +pub const HTTP_E_STATUS_VERSION_NOT_SUP: HRESULT = 0x801901F9u32 as HRESULT; +pub const E_INVALID_PROTOCOL_OPERATION: HRESULT = 0x83760001u32 as HRESULT; +pub const E_INVALID_PROTOCOL_FORMAT: HRESULT = 0x83760002u32 as HRESULT; +pub const E_PROTOCOL_EXTENSIONS_NOT_SUPPORTED: HRESULT = 0x83760003u32 as HRESULT; +pub const E_SUBPROTOCOL_NOT_SUPPORTED: HRESULT = 0x83760004u32 as HRESULT; +pub const E_PROTOCOL_VERSION_NOT_SUPPORTED: HRESULT = 0x83760005u32 as HRESULT; +pub const INPUT_E_OUT_OF_ORDER: HRESULT = 0x80400000u32 as HRESULT; +pub const INPUT_E_REENTRANCY: HRESULT = 0x80400001u32 as HRESULT; +pub const INPUT_E_MULTIMODAL: HRESULT = 0x80400002u32 as HRESULT; +pub const INPUT_E_PACKET: HRESULT = 0x80400003u32 as HRESULT; +pub const INPUT_E_FRAME: HRESULT = 0x80400004u32 as HRESULT; +pub const INPUT_E_HISTORY: HRESULT = 0x80400005u32 as HRESULT; +pub const INPUT_E_DEVICE_INFO: HRESULT = 0x80400006u32 as HRESULT; +pub const INPUT_E_TRANSFORM: HRESULT = 0x80400007u32 as HRESULT; +pub const INPUT_E_DEVICE_PROPERTY: HRESULT = 0x80400008u32 as HRESULT; +pub const INET_E_INVALID_URL: HRESULT = 0x800C0002u32 as HRESULT; +pub const INET_E_NO_SESSION: HRESULT = 0x800C0003u32 as HRESULT; +pub const INET_E_CANNOT_CONNECT: HRESULT = 0x800C0004u32 as HRESULT; +pub const INET_E_RESOURCE_NOT_FOUND: HRESULT = 0x800C0005u32 as HRESULT; +pub const INET_E_OBJECT_NOT_FOUND: HRESULT = 0x800C0006u32 as HRESULT; +pub const INET_E_DATA_NOT_AVAILABLE: HRESULT = 0x800C0007u32 as HRESULT; +pub const INET_E_DOWNLOAD_FAILURE: HRESULT = 0x800C0008u32 as HRESULT; +pub const INET_E_AUTHENTICATION_REQUIRED: HRESULT = 0x800C0009u32 as HRESULT; +pub const INET_E_NO_VALID_MEDIA: HRESULT = 0x800C000Au32 as HRESULT; +pub const INET_E_CONNECTION_TIMEOUT: HRESULT = 0x800C000Bu32 as HRESULT; +pub const INET_E_INVALID_REQUEST: HRESULT = 0x800C000Cu32 as HRESULT; +pub const INET_E_UNKNOWN_PROTOCOL: HRESULT = 0x800C000Du32 as HRESULT; +pub const INET_E_SECURITY_PROBLEM: HRESULT = 0x800C000Eu32 as HRESULT; +pub const INET_E_CANNOT_LOAD_DATA: HRESULT = 0x800C000Fu32 as HRESULT; +pub const INET_E_CANNOT_INSTANTIATE_OBJECT: HRESULT = 0x800C0010u32 as HRESULT; +pub const INET_E_INVALID_CERTIFICATE: HRESULT = 0x800C0019u32 as HRESULT; +pub const INET_E_REDIRECT_FAILED: HRESULT = 0x800C0014u32 as HRESULT; +pub const INET_E_REDIRECT_TO_DIR: HRESULT = 0x800C0015u32 as HRESULT; +pub const ERROR_DBG_CREATE_PROCESS_FAILURE_LOCKDOWN: HRESULT = 0x80B00001u32 as HRESULT; +pub const ERROR_DBG_ATTACH_PROCESS_FAILURE_LOCKDOWN: HRESULT = 0x80B00002u32 as HRESULT; +pub const ERROR_DBG_CONNECT_SERVER_FAILURE_LOCKDOWN: HRESULT = 0x80B00003u32 as HRESULT; +pub const ERROR_DBG_START_SERVER_FAILURE_LOCKDOWN: HRESULT = 0x80B00004u32 as HRESULT; +pub const ERROR_IO_PREEMPTED: HRESULT = 0x89010001u32 as HRESULT; +pub const JSCRIPT_E_CANTEXECUTE: HRESULT = 0x89020001u32 as HRESULT; +pub const WEP_E_NOT_PROVISIONED_ON_ALL_VOLUMES: HRESULT = 0x88010001u32 as HRESULT; +pub const WEP_E_FIXED_DATA_NOT_SUPPORTED: HRESULT = 0x88010002u32 as HRESULT; +pub const WEP_E_HARDWARE_NOT_COMPLIANT: HRESULT = 0x88010003u32 as HRESULT; +pub const WEP_E_LOCK_NOT_CONFIGURED: HRESULT = 0x88010004u32 as HRESULT; +pub const WEP_E_PROTECTION_SUSPENDED: HRESULT = 0x88010005u32 as HRESULT; +pub const WEP_E_NO_LICENSE: HRESULT = 0x88010006u32 as HRESULT; +pub const WEP_E_OS_NOT_PROTECTED: HRESULT = 0x88010007u32 as HRESULT; +pub const WEP_E_UNEXPECTED_FAIL: HRESULT = 0x88010008u32 as HRESULT; +pub const WEP_E_BUFFER_TOO_LARGE: HRESULT = 0x88010009u32 as HRESULT; +pub const ERROR_SVHDX_ERROR_STORED: HRESULT = 0xC05C0000u32 as HRESULT; +pub const ERROR_SVHDX_ERROR_NOT_AVAILABLE: HRESULT = 0xC05CFF00u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_AVAILABLE: HRESULT = 0xC05CFF01u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_CAPACITY_DATA_CHANGED: HRESULT = 0xC05CFF02u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_PREEMPTED: HRESULT = 0xC05CFF03u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_RELEASED: HRESULT = 0xC05CFF04u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_REGISTRATIONS_PREEMPTED: HRESULT = 0xC05CFF05u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_OPERATING_DEFINITION_CHANGED: HRESULT = 0xC05CFF06u32 as HRESULT; +pub const ERROR_SVHDX_RESERVATION_CONFLICT: HRESULT = 0xC05CFF07u32 as HRESULT; +pub const ERROR_SVHDX_WRONG_FILE_TYPE: HRESULT = 0xC05CFF08u32 as HRESULT; +pub const ERROR_SVHDX_VERSION_MISMATCH: HRESULT = 0xC05CFF09u32 as HRESULT; +pub const ERROR_VHD_SHARED: HRESULT = 0xC05CFF0Au32 as HRESULT; +pub const WININET_E_OUT_OF_HANDLES: HRESULT = 0x80072EE1u32 as HRESULT; +pub const WININET_E_TIMEOUT: HRESULT = 0x80072EE2u32 as HRESULT; +pub const WININET_E_EXTENDED_ERROR: HRESULT = 0x80072EE3u32 as HRESULT; +pub const WININET_E_INTERNAL_ERROR: HRESULT = 0x80072EE4u32 as HRESULT; +pub const WININET_E_INVALID_URL: HRESULT = 0x80072EE5u32 as HRESULT; +pub const WININET_E_UNRECOGNIZED_SCHEME: HRESULT = 0x80072EE6u32 as HRESULT; +pub const WININET_E_NAME_NOT_RESOLVED: HRESULT = 0x80072EE7u32 as HRESULT; +pub const WININET_E_PROTOCOL_NOT_FOUND: HRESULT = 0x80072EE8u32 as HRESULT; +pub const WININET_E_INVALID_OPTION: HRESULT = 0x80072EE9u32 as HRESULT; +pub const WININET_E_BAD_OPTION_LENGTH: HRESULT = 0x80072EEAu32 as HRESULT; +pub const WININET_E_OPTION_NOT_SETTABLE: HRESULT = 0x80072EEBu32 as HRESULT; +pub const WININET_E_SHUTDOWN: HRESULT = 0x80072EECu32 as HRESULT; +pub const WININET_E_INCORRECT_USER_NAME: HRESULT = 0x80072EEDu32 as HRESULT; +pub const WININET_E_INCORRECT_PASSWORD: HRESULT = 0x80072EEEu32 as HRESULT; +pub const WININET_E_LOGIN_FAILURE: HRESULT = 0x80072EEFu32 as HRESULT; +pub const WININET_E_INVALID_OPERATION: HRESULT = 0x80072EF0u32 as HRESULT; +pub const WININET_E_OPERATION_CANCELLED: HRESULT = 0x80072EF1u32 as HRESULT; +pub const WININET_E_INCORRECT_HANDLE_TYPE: HRESULT = 0x80072EF2u32 as HRESULT; +pub const WININET_E_INCORRECT_HANDLE_STATE: HRESULT = 0x80072EF3u32 as HRESULT; +pub const WININET_E_NOT_PROXY_REQUEST: HRESULT = 0x80072EF4u32 as HRESULT; +pub const WININET_E_REGISTRY_VALUE_NOT_FOUND: HRESULT = 0x80072EF5u32 as HRESULT; +pub const WININET_E_BAD_REGISTRY_PARAMETER: HRESULT = 0x80072EF6u32 as HRESULT; +pub const WININET_E_NO_DIRECT_ACCESS: HRESULT = 0x80072EF7u32 as HRESULT; +pub const WININET_E_NO_CONTEXT: HRESULT = 0x80072EF8u32 as HRESULT; +pub const WININET_E_NO_CALLBACK: HRESULT = 0x80072EF9u32 as HRESULT; +pub const WININET_E_REQUEST_PENDING: HRESULT = 0x80072EFAu32 as HRESULT; +pub const WININET_E_INCORRECT_FORMAT: HRESULT = 0x80072EFBu32 as HRESULT; +pub const WININET_E_ITEM_NOT_FOUND: HRESULT = 0x80072EFCu32 as HRESULT; +pub const WININET_E_CANNOT_CONNECT: HRESULT = 0x80072EFDu32 as HRESULT; +pub const WININET_E_CONNECTION_ABORTED: HRESULT = 0x80072EFEu32 as HRESULT; +pub const WININET_E_CONNECTION_RESET: HRESULT = 0x80072EFFu32 as HRESULT; +pub const WININET_E_FORCE_RETRY: HRESULT = 0x80072F00u32 as HRESULT; +pub const WININET_E_INVALID_PROXY_REQUEST: HRESULT = 0x80072F01u32 as HRESULT; +pub const WININET_E_NEED_UI: HRESULT = 0x80072F02u32 as HRESULT; +pub const WININET_E_HANDLE_EXISTS: HRESULT = 0x80072F04u32 as HRESULT; +pub const WININET_E_SEC_CERT_DATE_INVALID: HRESULT = 0x80072F05u32 as HRESULT; +pub const WININET_E_SEC_CERT_CN_INVALID: HRESULT = 0x80072F06u32 as HRESULT; +pub const WININET_E_HTTP_TO_HTTPS_ON_REDIR: HRESULT = 0x80072F07u32 as HRESULT; +pub const WININET_E_HTTPS_TO_HTTP_ON_REDIR: HRESULT = 0x80072F08u32 as HRESULT; +pub const WININET_E_MIXED_SECURITY: HRESULT = 0x80072F09u32 as HRESULT; +pub const WININET_E_CHG_POST_IS_NON_SECURE: HRESULT = 0x80072F0Au32 as HRESULT; +pub const WININET_E_POST_IS_NON_SECURE: HRESULT = 0x80072F0Bu32 as HRESULT; +pub const WININET_E_CLIENT_AUTH_CERT_NEEDED: HRESULT = 0x80072F0Cu32 as HRESULT; +pub const WININET_E_INVALID_CA: HRESULT = 0x80072F0Du32 as HRESULT; +pub const WININET_E_CLIENT_AUTH_NOT_SETUP: HRESULT = 0x80072F0Eu32 as HRESULT; +pub const WININET_E_ASYNC_THREAD_FAILED: HRESULT = 0x80072F0Fu32 as HRESULT; +pub const WININET_E_REDIRECT_SCHEME_CHANGE: HRESULT = 0x80072F10u32 as HRESULT; +pub const WININET_E_DIALOG_PENDING: HRESULT = 0x80072F11u32 as HRESULT; +pub const WININET_E_RETRY_DIALOG: HRESULT = 0x80072F12u32 as HRESULT; +pub const WININET_E_NO_NEW_CONTAINERS: HRESULT = 0x80072F13u32 as HRESULT; +pub const WININET_E_HTTPS_HTTP_SUBMIT_REDIR: HRESULT = 0x80072F14u32 as HRESULT; +pub const WININET_E_SEC_CERT_ERRORS: HRESULT = 0x80072F17u32 as HRESULT; +pub const WININET_E_SEC_CERT_REV_FAILED: HRESULT = 0x80072F19u32 as HRESULT; +pub const WININET_E_HEADER_NOT_FOUND: HRESULT = 0x80072F76u32 as HRESULT; +pub const WININET_E_DOWNLEVEL_SERVER: HRESULT = 0x80072F77u32 as HRESULT; +pub const WININET_E_INVALID_SERVER_RESPONSE: HRESULT = 0x80072F78u32 as HRESULT; +pub const WININET_E_INVALID_HEADER: HRESULT = 0x80072F79u32 as HRESULT; +pub const WININET_E_INVALID_QUERY_REQUEST: HRESULT = 0x80072F7Au32 as HRESULT; +pub const WININET_E_HEADER_ALREADY_EXISTS: HRESULT = 0x80072F7Bu32 as HRESULT; +pub const WININET_E_REDIRECT_FAILED: HRESULT = 0x80072F7Cu32 as HRESULT; +pub const WININET_E_SECURITY_CHANNEL_ERROR: HRESULT = 0x80072F7Du32 as HRESULT; +pub const WININET_E_UNABLE_TO_CACHE_FILE: HRESULT = 0x80072F7Eu32 as HRESULT; +pub const WININET_E_TCPIP_NOT_INSTALLED: HRESULT = 0x80072F7Fu32 as HRESULT; +pub const WININET_E_DISCONNECTED: HRESULT = 0x80072F83u32 as HRESULT; +pub const WININET_E_SERVER_UNREACHABLE: HRESULT = 0x80072F84u32 as HRESULT; +pub const WININET_E_PROXY_SERVER_UNREACHABLE: HRESULT = 0x80072F85u32 as HRESULT; +pub const WININET_E_BAD_AUTO_PROXY_SCRIPT: HRESULT = 0x80072F86u32 as HRESULT; +pub const WININET_E_UNABLE_TO_DOWNLOAD_SCRIPT: HRESULT = 0x80072F87u32 as HRESULT; +pub const WININET_E_SEC_INVALID_CERT: HRESULT = 0x80072F89u32 as HRESULT; +pub const WININET_E_SEC_CERT_REVOKED: HRESULT = 0x80072F8Au32 as HRESULT; +pub const WININET_E_FAILED_DUETOSECURITYCHECK: HRESULT = 0x80072F8Bu32 as HRESULT; +pub const WININET_E_NOT_INITIALIZED: HRESULT = 0x80072F8Cu32 as HRESULT; +pub const WININET_E_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: HRESULT = 0x80072F8Eu32 as HRESULT; +pub const WININET_E_DECODING_FAILED: HRESULT = 0x80072F8Fu32 as HRESULT; +pub const WININET_E_NOT_REDIRECTED: HRESULT = 0x80072F80u32 as HRESULT; +pub const WININET_E_COOKIE_NEEDS_CONFIRMATION: HRESULT = 0x80072F81u32 as HRESULT; +pub const WININET_E_COOKIE_DECLINED: HRESULT = 0x80072F82u32 as HRESULT; +pub const WININET_E_REDIRECT_NEEDS_CONFIRMATION: HRESULT = 0x80072F88u32 as HRESULT; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winevt.rs b/bash-5.1/vendor/winapi-0.2.8/src/winevt.rs new file mode 100644 index 0000000..3f2d6a0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winevt.rs @@ -0,0 +1,40 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Windows Events API +pub type EVT_HANDLE = ::HANDLE; +pub type PEVT_HANDLE = *mut ::HANDLE; +ENUM!{enum EVT_VARIANT_TYPE { + EvtVarTypeNull = 0, + EvtVarTypeString = 1, + EvtVarTypeAnsiString = 2, + EvtVarTypeSByte = 3, + EvtVarTypeByte = 4, + EvtVarTypeInt16 = 5, + EvtVarTypeUInt16 = 6, + EvtVarTypeInt32 = 7, + EvtVarTypeUInt32 = 8, + EvtVarTypeInt64 = 9, + EvtVarTypeUInt64 = 10, + EvtVarTypeSingle = 11, + EvtVarTypeDouble = 12, + EvtVarTypeBoolean = 13, + EvtVarTypeBinary = 14, + EvtVarTypeGuid = 15, + EvtVarTypeSizeT = 16, + EvtVarTypeFileTime = 17, + EvtVarTypeSysTime = 18, + EvtVarTypeSid = 19, + EvtVarTypeHexInt32 = 20, + EvtVarTypeHexInt64 = 21, + EvtVarTypeEvtHandle = 32, + EvtVarTypeEvtXml = 35, +}} +pub const EVT_VARIANT_TYPE_MASK: ::DWORD = 0x7f; +pub const EVT_VARIANT_TYPE_ARRAY: ::DWORD = 128; +STRUCT!{struct EVT_VARIANT { + u: u64, + Count: ::DWORD, + Type: ::DWORD, +}} +// TODO - All the UNION! for each variant +// TODO - The rest of this header diff --git a/bash-5.1/vendor/winapi-0.2.8/src/wingdi.rs b/bash-5.1/vendor/winapi-0.2.8/src/wingdi.rs new file mode 100644 index 0000000..edc5850 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/wingdi.rs @@ -0,0 +1,1238 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! GDI procedure declarations, constant definitions and macros +pub const DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: ::DWORD = 0x00000001; +pub const DISPLAY_DEVICE_MULTI_DRIVER: ::DWORD = 0x00000002; +pub const DISPLAY_DEVICE_PRIMARY_DEVICE: ::DWORD = 0x00000004; +pub const DISPLAY_DEVICE_MIRRORING_DRIVER: ::DWORD = 0x00000008; +pub const DISPLAY_DEVICE_VGA_COMPATIBLE: ::DWORD = 0x00000010; +pub const DISPLAY_DEVICE_REMOVABLE: ::DWORD = 0x00000020; +pub const DISPLAY_DEVICE_ACC_DRIVER: ::DWORD = 0x00000040; +pub const DISPLAY_DEVICE_MODESPRUNED: ::DWORD = 0x08000000; +pub const DISPLAY_DEVICE_REMOTE: ::DWORD = 0x04000000; +pub const DISPLAY_DEVICE_DISCONNECT: ::DWORD = 0x02000000; +pub const DISPLAY_DEVICE_TS_COMPATIBLE: ::DWORD = 0x00200000; +pub const DISPLAY_DEVICE_UNSAFE_MODES_ON: ::DWORD = 0x00080000; +pub const DISPLAY_DEVICE_ACTIVE: ::DWORD = 0x00000001; +pub const DISPLAY_DEVICE_ATTACHED: ::DWORD = 0x00000002; +pub const DM_ORIENTATION: ::DWORD = 0x00000001; +pub const DM_PAPERSIZE: ::DWORD = 0x00000002; +pub const DM_PAPERLENGTH: ::DWORD = 0x00000004; +pub const DM_PAPERWIDTH: ::DWORD = 0x00000008; +pub const DM_SCALE: ::DWORD = 0x00000010; +pub const DM_POSITION: ::DWORD = 0x00000020; +pub const DM_NUP: ::DWORD = 0x00000040; +pub const DM_DISPLAYORIENTATION: ::DWORD = 0x00000080; +pub const DM_COPIES: ::DWORD = 0x00000100; +pub const DM_DEFAULTSOURCE: ::DWORD = 0x00000200; +pub const DM_PRINTQUALITY: ::DWORD = 0x00000400; +pub const DM_COLOR: ::DWORD = 0x00000800; +pub const DM_DUPLEX: ::DWORD = 0x00001000; +pub const DM_YRESOLUTION: ::DWORD = 0x00002000; +pub const DM_TTOPTION: ::DWORD = 0x00004000; +pub const DM_COLLATE: ::DWORD = 0x00008000; +pub const DM_FORMNAME: ::DWORD = 0x00010000; +pub const DM_LOGPIXELS: ::DWORD = 0x00020000; +pub const DM_BITSPERPEL: ::DWORD = 0x00040000; +pub const DM_PELSWIDTH: ::DWORD = 0x00080000; +pub const DM_PELSHEIGHT: ::DWORD = 0x00100000; +pub const DM_DISPLAYFLAGS: ::DWORD = 0x00200000; +pub const DM_DISPLAYFREQUENCY: ::DWORD = 0x00400000; +pub const DM_ICMMETHOD: ::DWORD = 0x00800000; +pub const DM_ICMINTENT: ::DWORD = 0x01000000; +pub const DM_MEDIATYPE: ::DWORD = 0x02000000; +pub const DM_DITHERTYPE: ::DWORD = 0x04000000; +pub const DM_PANNINGWIDTH: ::DWORD = 0x08000000; +pub const DM_PANNINGHEIGHT: ::DWORD = 0x10000000; +pub const DM_DISPLAYFIXEDOUTPUT: ::DWORD = 0x20000000; +pub const PFD_TYPE_RGBA: ::BYTE = 0; +pub const PFD_TYPE_COLORINDEX: ::BYTE = 1; +pub const PFD_MAIN_PLANE: ::BYTE = 0; +pub const PFD_OVERLAY_PLANE: ::BYTE = 1; +pub const PFD_UNDERLAY_PLANE: ::BYTE = 0xFF; +pub const PFD_DOUBLEBUFFER: ::DWORD = 0x00000001; +pub const PFD_STEREO: ::DWORD = 0x00000002; +pub const PFD_DRAW_TO_WINDOW: ::DWORD = 0x00000004; +pub const PFD_DRAW_TO_BITMAP: ::DWORD = 0x00000008; +pub const PFD_SUPPORT_GDI: ::DWORD = 0x00000010; +pub const PFD_SUPPORT_OPENGL: ::DWORD = 0x00000020; +pub const PFD_GENERIC_FORMAT: ::DWORD = 0x00000040; +pub const PFD_NEED_PALETTE: ::DWORD = 0x00000080; +pub const PFD_NEED_SYSTEM_PALETTE: ::DWORD = 0x00000100; +pub const PFD_SWAP_EXCHANGE: ::DWORD = 0x00000200; +pub const PFD_SWAP_COPY: ::DWORD = 0x00000400; +pub const PFD_SWAP_LAYER_BUFFERS: ::DWORD = 0x00000800; +pub const PFD_GENERIC_ACCELERATED: ::DWORD = 0x00001000; +pub const PFD_SUPPORT_DIRECTDRAW: ::DWORD = 0x00002000; +pub const PFD_DIRECT3D_ACCELERATED: ::DWORD = 0x00004000; +pub const PFD_SUPPORT_COMPOSITION: ::DWORD = 0x00008000; +pub const PFD_DEPTH_DONTCARE: ::DWORD = 0x20000000; +pub const PFD_DOUBLEBUFFER_DONTCARE: ::DWORD = 0x40000000; +pub const PFD_STEREO_DONTCARE: ::DWORD = 0x80000000; +pub const CCHFORMNAME: usize = 32; +STRUCT!{struct DEVMODEA { + dmDeviceName: [::CHAR; ::CCHDEVICENAME], + dmSpecVersion: ::WORD, + dmDriverVersion: ::WORD, + dmSize: ::WORD, + dmDriverExtra: ::WORD, + dmFields: ::DWORD, + union1: [u8; 16], + dmColor: ::c_short, + dmDuplex: ::c_short, + dmYResolution: ::c_short, + dmTTOption: ::c_short, + dmCollate: ::c_short, + dmFormName: [::CHAR; CCHFORMNAME], + dmLogPixels: ::WORD, + dmBitsPerPel: ::DWORD, + dmPelsWidth: ::DWORD, + dmPelsHeight: ::DWORD, + dmDisplayFlags: ::DWORD, + dmDisplayFrequency: ::DWORD, + dmICMMethod: ::DWORD, + dmICMIntent: ::DWORD, + dmMediaType: ::DWORD, + dmDitherType: ::DWORD, + dmReserved1: ::DWORD, + dmReserved2: ::DWORD, + dmPanningWidth: ::DWORD, + dmPanningHeight: ::DWORD, +}} +pub type PDEVMODEA = *mut DEVMODEA; +pub type NPDEVMODEA = *mut DEVMODEA; +pub type LPDEVMODEA = *mut DEVMODEA; +STRUCT!{struct DEVMODEW { + dmDeviceName: [::WCHAR; ::CCHDEVICENAME], + dmSpecVersion: ::WORD, + dmDriverVersion: ::WORD, + dmSize: ::WORD, + dmDriverExtra: ::WORD, + dmFields: ::DWORD, + union1: [u8; 16], + dmColor: ::c_short, + dmDuplex: ::c_short, + dmYResolution: ::c_short, + dmTTOption: ::c_short, + dmCollate: ::c_short, + dmFormName: [::WCHAR; CCHFORMNAME], + dmLogPixels: ::WORD, + dmBitsPerPel: ::DWORD, + dmPelsWidth: ::DWORD, + dmPelsHeight: ::DWORD, + dmDisplayFlags: ::DWORD, + dmDisplayFrequency: ::DWORD, + dmICMMethod: ::DWORD, + dmICMIntent: ::DWORD, + dmMediaType: ::DWORD, + dmDitherType: ::DWORD, + dmReserved1: ::DWORD, + dmReserved2: ::DWORD, + dmPanningWidth: ::DWORD, + dmPanningHeight: ::DWORD, +}} +pub type PDEVMODEW = *mut DEVMODEW; +pub type NPDEVMODEW = *mut DEVMODEW; +pub type LPDEVMODEW = *mut DEVMODEW; +STRUCT!{nodebug struct DISPLAY_DEVICEW { + cb: ::DWORD, + DeviceName: [::WCHAR; 32], + DeviceString: [::WCHAR; 128], + StateFlags: ::DWORD, + DeviceID: [::WCHAR; 128], + DeviceKey: [::WCHAR; 128], +}} +pub type PDISPLAY_DEVICEW = *mut DISPLAY_DEVICEW; +pub type LPDISPLAY_DEVICEW = *mut DISPLAY_DEVICEW; +STRUCT!{nodebug struct DISPLAY_DEVICEA { + cb: ::DWORD, + DeviceName: [::CHAR; 32], + DeviceString: [::CHAR; 128], + StateFlags: ::DWORD, + DeviceID: [::CHAR; 128], + DeviceKey: [::CHAR; 128], +}} +pub type PDISPLAY_DEVICEA = *mut DISPLAY_DEVICEA; +pub type LPDISPLAY_DEVICEA = *mut DISPLAY_DEVICEA; +STRUCT!{struct PIXELFORMATDESCRIPTOR { + nSize: ::WORD, + nVersion: ::WORD, + dwFlags: ::DWORD, + iPixelType: ::BYTE, + cColorBits: ::BYTE, + cRedBits: ::BYTE, + cRedShift: ::BYTE, + cGreenBits: ::BYTE, + cGreenShift: ::BYTE, + cBlueBits: ::BYTE, + cBlueShift: ::BYTE, + cAlphaBits: ::BYTE, + cAlphaShift: ::BYTE, + cAccumBits: ::BYTE, + cAccumRedBits: ::BYTE, + cAccumGreenBits: ::BYTE, + cAccumBlueBits: ::BYTE, + cAccumAlphaBits: ::BYTE, + cDepthBits: ::BYTE, + cStencilBits: ::BYTE, + cAuxBuffers: ::BYTE, + iLayerType: ::BYTE, + bReserved: ::BYTE, + dwLayerMask: ::DWORD, + dwVisibleMask: ::DWORD, + dwDamageMask: ::DWORD, +}} +pub type PPIXELFORMATDESCRIPTOR = *mut PIXELFORMATDESCRIPTOR; +pub type LPPIXELFORMATDESCRIPTOR = *mut PIXELFORMATDESCRIPTOR; +pub const R2_BLACK: ::c_int = 1; +pub const R2_NOTMERGEPEN: ::c_int = 2; +pub const R2_MASKNOTPEN: ::c_int = 3; +pub const R2_NOTCOPYPEN: ::c_int = 4; +pub const R2_MASKPENNOT: ::c_int = 5; +pub const R2_NOT: ::c_int = 6; +pub const R2_XORPEN: ::c_int = 7; +pub const R2_NOTMASKPEN: ::c_int = 8; +pub const R2_MASKPEN: ::c_int = 9; +pub const R2_NOTXORPEN: ::c_int = 10; +pub const R2_NOP: ::c_int = 11; +pub const R2_MERGENOTPEN: ::c_int = 12; +pub const R2_COPYPEN: ::c_int = 13; +pub const R2_MERGEPENNOT: ::c_int = 14; +pub const R2_MERGEPEN: ::c_int = 15; +pub const R2_WHITE: ::c_int = 16; +pub const R2_LAST: ::c_int = 16; +//83 +pub const SRCCOPY: ::DWORD = 0x00CC0020; +pub const SRCPAINT: ::DWORD = 0x00EE0086; +pub const SRCAND: ::DWORD = 0x008800C6; +pub const SRCINVERT: ::DWORD = 0x00660046; +pub const SRCERASE: ::DWORD = 0x00440328; +pub const NOTSRCCOPY: ::DWORD = 0x00330008; +pub const NOTSRCERASE: ::DWORD = 0x001100A6; +pub const MERGECOPY: ::DWORD = 0x00C000CA; +pub const MERGEPAINT: ::DWORD = 0x00BB0226; +pub const PATCOPY: ::DWORD = 0x00F00021; +pub const PATPAINT: ::DWORD = 0x00FB0A09; +pub const PATINVERT: ::DWORD = 0x005A0049; +pub const DSTINVERT: ::DWORD = 0x00550009; +pub const BLACKNESS: ::DWORD = 0x00000042; +pub const WHITENESS: ::DWORD = 0x00FF0062; +//121 +// fnCombineMode values for CombineRgn +pub const RGN_AND: ::c_int = 1; +pub const RGN_OR: ::c_int = 2; +pub const RGN_XOR: ::c_int = 3; +pub const RGN_DIFF: ::c_int = 4; +pub const RGN_COPY: ::c_int = 5; +pub const RGN_MIN: ::c_int = RGN_AND; +pub const RGN_MAX: ::c_int = RGN_COPY; +//572 (Win 7 SDK) +STRUCT!{struct BITMAP { + bmType: ::LONG, + bmWidth: ::LONG, + bmHeight: ::LONG, + bmWidthBytes: ::LONG, + bmPlanes: ::WORD, + bmBitsPixel: ::WORD, + bmBits: ::LPVOID, +}} +pub type PBITMAP = *mut BITMAP; +pub type NPBITMAP = *mut BITMAP; +pub type LPBITMAP = *mut BITMAP; +STRUCT!{struct RGBQUAD { + rgbBlue: ::BYTE, + rgbGreen: ::BYTE, + rgbRed: ::BYTE, + rgbReserved: ::BYTE, +}} +pub type LPRGBQUAD = *mut RGBQUAD; +pub const CS_ENABLE: ::DWORD = 0x00000001; +pub const CS_DISABLE: ::DWORD = 0x00000002; +pub const CS_DELETE_TRANSFORM: ::DWORD = 0x00000003; +pub const LCS_SIGNATURE: ::DWORD = 0x5053_4F43; // 'PSOC' +pub const LCS_sRGB: LCSCSTYPE = 0x7352_4742; // 'sRGB' +pub const LCS_WINDOWS_COLOR_SPACE: LCSCSTYPE = 0x5769_6E20; // 'Win ' +pub type LCSCSTYPE = ::LONG; +pub const LCS_CALIBRATED_RGB: LCSCSTYPE = 0x00000000; +pub type LCSGAMUTMATCH = ::LONG; +pub const LCS_GM_BUSINESS: LCSGAMUTMATCH = 0x00000001; +pub const LCS_GM_GRAPHICS: LCSGAMUTMATCH = 0x00000002; +pub const LCS_GM_IMAGES: LCSGAMUTMATCH = 0x00000004; +pub const LCS_GM_ABS_COLORIMETRIC: LCSGAMUTMATCH = 0x00000008; +pub const CM_OUT_OF_GAMUT: ::BYTE = 255; +pub const CM_IN_GAMUT: ::BYTE = 0; +pub const ICM_ADDPROFILE: ::UINT = 1; +pub const ICM_DELETEPROFILE: ::UINT = 2; +pub const ICM_QUERYPROFILE: ::UINT = 3; +pub const ICM_SETDEFAULTPROFILE: ::UINT = 4; +pub const ICM_REGISTERICMATCHER: ::UINT = 5; +pub const ICM_UNREGISTERICMATCHER: ::UINT = 6; +pub const ICM_QUERYMATCH: ::UINT = 7; +pub type FXPT16DOT16 = ::c_long; +pub type LPFXPT16DOT16 = *mut ::c_long; +pub type FXPT2DOT30 = ::c_long; +pub type LPFXPT2DOT30 = *mut ::c_long; +STRUCT!{struct CIEXYZ { + ciexyzX: FXPT2DOT30, + ciexyzY: FXPT2DOT30, + ciexyzZ: FXPT2DOT30, +}} +pub type LPCIEXYZ = *mut CIEXYZ; +STRUCT!{struct CIEXYZTRIPLE { + ciexyzRed: CIEXYZ, + ciexyzGreen: CIEXYZ, + ciexyzBlue: CIEXYZ, +}} +pub type LPCIEXYZTRIPLE = *mut CIEXYZTRIPLE; +//716 (Win 7 SDK) +STRUCT!{struct BITMAPINFOHEADER { + biSize: ::DWORD, + biWidth: ::LONG, + biHeight: ::LONG, + biPlanes: ::WORD, + biBitCount: ::WORD, + biCompression: ::DWORD, + biSizeImage: ::DWORD, + biXPelsPerMeter: ::LONG, + biYPelsPerMeter: ::LONG, + biClrUsed: ::DWORD, + biClrImportant: ::DWORD, +}} +pub type LPBITMAPINFOHEADER = *mut BITMAPINFOHEADER; +pub type PBITMAPINFOHEADER = *mut BITMAPINFOHEADER; +STRUCT!{struct BITMAPV5HEADER { + bV5Size: ::DWORD, + bV5Width: ::LONG, + bV5Height: ::LONG, + bV5Planes: ::WORD, + bV5BitCount: ::WORD, + bV5Compression: ::DWORD, + bV5SizeImage: ::DWORD, + bV5XPelsPerMeter: ::LONG, + bV5YPelsPerMeter: ::LONG, + bV5ClrUsed: ::DWORD, + bV5ClrImportant: ::DWORD, + bV5RedMask: ::DWORD, + bV5GreenMask: ::DWORD, + bV5BlueMask: ::DWORD, + bV5AlphaMask: ::DWORD, + bV5CSType: ::LONG, // LONG to match LOGCOLORSPACE + bV5Endpoints: CIEXYZTRIPLE, + bV5GammaRed: ::DWORD, + bV5GammaGreen: ::DWORD, + bV5GammaBlue: ::DWORD, + bV5Intent: ::LONG, // LONG to match LOGCOLORSPACE + bV5ProfileData: ::DWORD, + bV5ProfileSize: ::DWORD, + bV5Reserved: ::DWORD, +}} +pub type LPBITMAPV5HEADER = *mut BITMAPV5HEADER; +pub type PBITMAPV5HEADER = *mut BITMAPV5HEADER; +pub const PROFILE_LINKED: ::LONG = 0x4C49_4E4B; // 'LINK' +pub const PROFILE_EMBEDDED: ::LONG = 0x4D42_4544; // 'MBED' +pub const BI_RGB: ::DWORD = 0; +pub const BI_RLE8: ::DWORD = 1; +pub const BI_RLE4: ::DWORD = 2; +pub const BI_BITFIELDS: ::DWORD = 3; +pub const BI_JPEG: ::DWORD = 4; +pub const BI_PNG: ::DWORD = 5; +STRUCT!{struct BITMAPINFO { + bmiHeader: BITMAPINFOHEADER, + bmiColors: [RGBQUAD; 0], +}} +pub type LPBITMAPINFO = *mut BITMAPINFO; +pub type PBITMAPINFO = *mut BITMAPINFO; +//1438 +pub const LF_FACESIZE: usize = 32; +STRUCT!{nodebug struct LOGFONTA { + lfHeight: ::LONG, + lfWidth: ::LONG, + lfEscapement: ::LONG, + lfOrientation: ::LONG, + lfWeight: ::LONG, + lfItalic: ::BYTE, + lfUnderline: ::BYTE, + lfStrikeOut: ::BYTE, + lfCharSet: ::BYTE, + lfOutPrecision: ::BYTE, + lfClipPrecision: ::BYTE, + lfQuality: ::BYTE, + lfPitchAndFamily: ::BYTE, + lfFaceName: [::CHAR; LF_FACESIZE], +}} +pub type LPLOGFONTA = *mut LOGFONTA; +STRUCT!{nodebug struct LOGFONTW { + lfHeight: ::LONG, + lfWidth: ::LONG, + lfEscapement: ::LONG, + lfOrientation: ::LONG, + lfWeight: ::LONG, + lfItalic: ::BYTE, + lfUnderline: ::BYTE, + lfStrikeOut: ::BYTE, + lfCharSet: ::BYTE, + lfOutPrecision: ::BYTE, + lfClipPrecision: ::BYTE, + lfQuality: ::BYTE, + lfPitchAndFamily: ::BYTE, + lfFaceName: [::WCHAR; LF_FACESIZE], +}} +pub type LPLOGFONTW = *mut LOGFONTW; +//1595 +#[inline] +pub fn RGB (r: ::BYTE, g: ::BYTE, b: ::BYTE) -> ::COLORREF { + r as ::COLORREF | ((g as ::COLORREF) << 8) | ((b as ::COLORREF) << 16) +} +// +pub const DRIVERVERSION: ::c_int = 0; +pub const TECHNOLOGY: ::c_int = 2; +pub const HORZSIZE: ::c_int = 4; +pub const VERTSIZE: ::c_int = 6; +pub const HORZRES: ::c_int = 8; +pub const VERTRES: ::c_int = 10; +pub const BITSPIXEL: ::c_int = 12; +pub const PLANES: ::c_int = 14; +pub const NUMBRUSHES: ::c_int = 16; +pub const NUMPENS: ::c_int = 18; +pub const NUMMARKERS: ::c_int = 20; +pub const NUMFONTS: ::c_int = 22; +pub const NUMCOLORS: ::c_int = 24; +pub const PDEVICESIZE: ::c_int = 26; +pub const CURVECAPS: ::c_int = 28; +pub const LINECAPS: ::c_int = 30; +pub const POLYGONALCAPS: ::c_int = 32; +pub const TEXTCAPS: ::c_int = 34; +pub const CLIPCAPS: ::c_int = 36; +pub const RASTERCAPS: ::c_int = 38; +pub const ASPECTX: ::c_int = 40; +pub const ASPECTY: ::c_int = 42; +pub const ASPECTXY: ::c_int = 44; +pub const LOGPIXELSX: ::c_int = 88; +pub const LOGPIXELSY: ::c_int = 90; +pub const SIZEPALETTE: ::c_int = 104; +pub const NUMRESERVED: ::c_int = 106; +pub const COLORRES: ::c_int = 108; +pub const PHYSICALWIDTH: ::c_int = 110; +pub const PHYSICALHEIGHT: ::c_int = 111; +pub const PHYSICALOFFSETX: ::c_int = 112; +pub const PHYSICALOFFSETY: ::c_int = 113; +pub const SCALINGFACTORX: ::c_int = 114; +pub const SCALINGFACTORY: ::c_int = 115; +pub const VREFRESH: ::c_int = 116; +pub const DESKTOPVERTRES: ::c_int = 117; +pub const DESKTOPHORZRES: ::c_int = 118; +pub const BLTALIGNMENT: ::c_int = 119; +pub const SHADEBLENDCAPS: ::c_int = 120; +pub const COLORMGMTCAPS: ::c_int = 121; +//1906 +pub const DIB_RGB_COLORS: ::UINT = 0; +pub const DIB_PAL_COLORS: ::UINT = 1; +pub const CBM_INIT: ::DWORD = 4; +STRUCT!{struct RGNDATAHEADER { + dwSize: ::DWORD, + iType: ::DWORD, + nCount: ::DWORD, + nRgnSize: ::DWORD, + rcBound: ::RECT, +}} +pub type PRGNDATAHEADER = *mut RGNDATAHEADER; +STRUCT!{nodebug struct RGNDATA { + rdh: RGNDATAHEADER, + Buffer: [::c_char; 0], +}} +pub type PRGNDATA = *mut RGNDATA; +pub type NPRGNDATA = *mut RGNDATA; +pub type LPRGNDATA = *mut RGNDATA; +STRUCT!{struct PALETTEENTRY { + peRed: ::BYTE, + peGreen: ::BYTE, + peBlue: ::BYTE, + peFlags: ::BYTE, +}} +pub type PPALETTEENTRY = *mut PALETTEENTRY; +pub type LPPALETTEENTRY = *mut PALETTEENTRY; +//2824 (Win 7 SDK) +STRUCT!{struct ABC { + abcA: ::c_int, + abcB: ::UINT, + abcC: ::c_int, +}} +pub type PABC = *mut ABC; +pub type NPABC = *mut ABC; +pub type LPABC = *mut ABC; +STRUCT!{struct ABCFLOAT { + abcfA: ::FLOAT, + abcfB: ::FLOAT, + abcfC: ::FLOAT, +}} +pub type PABCFLOAT = *mut ABCFLOAT; +pub type NPABCFLOAT = *mut ABCFLOAT; +pub type LPABCFLOAT = *mut ABCFLOAT; +//3581 +pub type LINEDDAPROC = Option<unsafe extern "system" fn(::c_int, ::c_int, ::LPARAM)>; +STRUCT!{struct XFORM { + eM11: ::FLOAT, + eM12: ::FLOAT, + eM21: ::FLOAT, + eM22: ::FLOAT, + eDx: ::FLOAT, + eDy: ::FLOAT, +}} +pub type PXFORM = *mut XFORM; +pub type LPXFORM = *mut XFORM; +STRUCT!{struct LOGBRUSH { + lbStyle: ::UINT, + lbColor: ::COLORREF, + lbHatch: ::ULONG_PTR, +}} +pub type PLOGBRUSH = *mut LOGBRUSH; +STRUCT!{nodebug struct LOGCOLORSPACEA { + lcsSignature: ::DWORD, + lcsVersion: ::DWORD, + lcsSize: ::DWORD, + lcsCSType: LCSCSTYPE, + lcsIntent: LCSGAMUTMATCH, + lcsEndpoints: CIEXYZTRIPLE, + lcsGammaRed: ::DWORD, + lcsGammaGreen: ::DWORD, + lcsGammaBlue: ::DWORD, + lcsFilename: [::CHAR; ::MAX_PATH], +}} +pub type LPLOGCOLORSPACEA = *mut LOGCOLORSPACEA; +STRUCT!{nodebug struct LOGCOLORSPACEW { + lcsSignature: ::DWORD, + lcsVersion: ::DWORD, + lcsSize: ::DWORD, + lcsCSType: LCSCSTYPE, + lcsIntent: LCSGAMUTMATCH, + lcsEndpoints: CIEXYZTRIPLE, + lcsGammaRed: ::DWORD, + lcsGammaGreen: ::DWORD, + lcsGammaBlue: ::DWORD, + lcsFilename: [::WCHAR; ::MAX_PATH], +}} +pub type LPLOGCOLORSPACEW = *mut LOGCOLORSPACEW; +pub const LF_FULLFACESIZE: usize = 64; +STRUCT!{nodebug struct ENUMLOGFONTEXA { + elfLogFont: LOGFONTA, + elfFullName: [::BYTE; LF_FULLFACESIZE], + elfStyle: [::BYTE; LF_FACESIZE], + elfScript: [::BYTE; LF_FACESIZE], +}} +pub type LPENUMLOGFONTEXA = *mut ENUMLOGFONTEXA; +STRUCT!{nodebug struct ENUMLOGFONTEXW { + elfLogFont: LOGFONTW, + elfFullName: [::WCHAR; LF_FULLFACESIZE], + elfStyle: [::WCHAR; LF_FACESIZE], + elfScript: [::WCHAR; LF_FACESIZE], +}} +pub type LPENUMLOGFONTEXW = *mut ENUMLOGFONTEXW; +pub const MM_MAX_NUMAXES: usize = 16; +STRUCT!{struct DESIGNVECTOR { + dvReserved: ::DWORD, + dvNumAxes: ::DWORD, + dvValues: [::LONG; MM_MAX_NUMAXES], +}} +pub type PDESIGNVECTOR = *mut DESIGNVECTOR; +pub type LPDESIGNVECTOR = *mut DESIGNVECTOR; +STRUCT!{nodebug struct ENUMLOGFONTEXDVA { + elfEnumLogfontEx: ENUMLOGFONTEXA, + elfDesignVector: DESIGNVECTOR, +}} +pub type PENUMLOGFONTEXDVA = *mut ENUMLOGFONTEXDVA; +pub type LPENUMLOGFONTEXDVA = *mut ENUMLOGFONTEXDVA; +STRUCT!{nodebug struct ENUMLOGFONTEXDVW { + elfEnumLogfontEx: ENUMLOGFONTEXW, + elfDesignVector: DESIGNVECTOR, +}} +pub type PENUMLOGFONTEXDVW = *mut ENUMLOGFONTEXDVW; +pub type LPENUMLOGFONTEXDVW = *mut ENUMLOGFONTEXDVW; +STRUCT!{struct LOGPALETTE { + palVersion: ::WORD, + palNumEntries: ::WORD, + palPalEntry: [PALETTEENTRY; 1], +}} +pub type PLOGPALETTE = *mut LOGPALETTE; +pub type NPLOGPALETTE = *mut LOGPALETTE; +pub type LPLOGPALETTE = *mut LOGPALETTE; +STRUCT!{struct LOGPEN { + lopnStyle: ::UINT, + lopnWidth: ::POINT, + lopnColor: ::COLORREF, +}} +pub type PLOGPEN = *mut LOGPEN; +pub type NPLOGPEN = *mut LOGPEN; +pub type LPLOGPEN = *mut LOGPEN; +STRUCT!{struct BLENDFUNCTION { + BlendOp: ::BYTE, + BlendFlags: ::BYTE, + SourceConstantAlpha: ::BYTE, + AlphaFormat: ::BYTE, +}} +pub type PBLENDFUNCTION = *mut BLENDFUNCTION; +pub const TMPF_FIXED_PITCH: ::BYTE = 0x01; +pub const TMPF_VECTOR: ::BYTE = 0x02; +pub const TMPF_DEVICE: ::BYTE = 0x08; +pub const TMPF_TRUETYPE: ::BYTE = 0x04; +STRUCT!{struct TEXTMETRICA { + tmHeight: ::LONG, + tmAscent: ::LONG, + tmDescent: ::LONG, + tmInternalLeading: ::LONG, + tmExternalLeading: ::LONG, + tmAveCharWidth: ::LONG, + tmMaxCharWidth: ::LONG, + tmWeight: ::LONG, + tmOverhang: ::LONG, + tmDigitizedAspectX: ::LONG, + tmDigitizedAspectY: ::LONG, + tmFirstChar: ::BYTE, + tmLastChar: ::BYTE, + tmDefaultChar: ::BYTE, + tmBreakChar: ::BYTE, + tmItalic: ::BYTE, + tmUnderlined: ::BYTE, + tmStruckOut: ::BYTE, + tmPitchAndFamily: ::BYTE, + tmCharSet: ::BYTE, +}} +pub type PTEXTMETRICA = *mut TEXTMETRICA; +pub type NPTEXTMETRICA = *mut TEXTMETRICA; +pub type LPTEXTMETRICA = *mut TEXTMETRICA; +STRUCT!{struct TEXTMETRICW { + tmHeight: ::LONG, + tmAscent: ::LONG, + tmDescent: ::LONG, + tmInternalLeading: ::LONG, + tmExternalLeading: ::LONG, + tmAveCharWidth: ::LONG, + tmMaxCharWidth: ::LONG, + tmWeight: ::LONG, + tmOverhang: ::LONG, + tmDigitizedAspectX: ::LONG, + tmDigitizedAspectY: ::LONG, + tmFirstChar: ::WCHAR, + tmLastChar: ::WCHAR, + tmDefaultChar: ::WCHAR, + tmBreakChar: ::WCHAR, + tmItalic: ::BYTE, + tmUnderlined: ::BYTE, + tmStruckOut: ::BYTE, + tmPitchAndFamily: ::BYTE, + tmCharSet: ::BYTE, +}} +pub type PTEXTMETRICW = *mut TEXTMETRICW; +pub type NPTEXTMETRICW = *mut TEXTMETRICW; +pub type LPTEXTMETRICW = *mut TEXTMETRICW; +pub const TA_NOUPDATECP: ::UINT = 0; +pub const TA_UPDATECP: ::UINT = 1; +pub const TA_LEFT: ::UINT = 0; +pub const TA_RIGHT: ::UINT = 2; +pub const TA_CENTER: ::UINT = 6; +pub const TA_TOP: ::UINT = 0; +pub const TA_BOTTOM: ::UINT = 8; +pub const TA_BASELINE: ::UINT = 24; +pub const TA_RTLREADING: ::UINT = 256; +pub const TA_MASK: ::UINT = TA_BASELINE + TA_CENTER + TA_UPDATECP + TA_RTLREADING; +pub const WHITE_BRUSH: ::c_int = 0; +pub const LTGRAY_BRUSH: ::c_int = 1; +pub const GRAY_BRUSH: ::c_int = 2; +pub const DKGRAY_BRUSH: ::c_int = 3; +pub const BLACK_BRUSH: ::c_int = 4; +pub const NULL_BRUSH: ::c_int = 5; +pub const HOLLOW_BRUSH: ::c_int = 5; +pub const WHITE_PEN: ::c_int = 6; +pub const BLACK_PEN: ::c_int = 7; +pub const NULL_PEN: ::c_int = 8; +pub const OEM_FIXED_FONT: ::c_int = 10; +pub const ANSI_FIXED_FONT: ::c_int = 11; +pub const ANSI_VAR_FONT: ::c_int = 12; +pub const SYSTEM_FONT: ::c_int = 13; +pub const DEVICE_DEFAULT_FONT: ::c_int = 14; +pub const DEFAULT_PALETTE: ::c_int = 15; +pub const SYSTEM_FIXED_FONT: ::c_int = 16; +pub const DEFAULT_GUI_FONT: ::c_int = 17; +pub const DC_BRUSH: ::c_int = 18; +pub const DC_PEN: ::c_int = 19; +pub const STOCK_LAST: ::c_int = 19;pub const PS_SOLID: ::c_int = 0; +pub const PS_DASH: ::c_int = 1; +pub const PS_DOT: ::c_int = 2; +pub const PS_DASHDOT: ::c_int = 3; +pub const PS_DASHDOTDOT: ::c_int = 4; +pub const PS_NULL: ::c_int = 5; +pub const PS_INSIDEFRAME: ::c_int = 6; +pub const PS_USERSTYLE: ::c_int = 7; +pub const PS_ALTERNATE: ::c_int = 8; +pub const TRANSPARENT: ::c_int = 1; +pub const OPAQUE: ::c_int = 2; +pub const BKMODE_LAST: ::c_int = 2; +pub const MM_TEXT: ::c_int = 1; +pub const MM_LOMETRIC: ::c_int = 2; +pub const MM_HIMETRIC: ::c_int = 3; +pub const MM_LOENGLISH: ::c_int = 4; +pub const MM_HIENGLISH: ::c_int = 5; +pub const MM_TWIPS: ::c_int = 6; +pub const MM_ISOTROPIC: ::c_int = 7; +pub const MM_ANISOTROPIC: ::c_int = 8; +pub const ALTERNATE: ::c_int = 1; +pub const WINDING: ::c_int = 2; +pub const POLYFILL_LAST: ::c_int = 2; +pub const OUT_DEFAULT_PRECIS: ::DWORD = 0; +pub const OUT_STRING_PRECIS: ::DWORD = 1; +pub const OUT_CHARACTER_PRECIS: ::DWORD = 2; +pub const OUT_STROKE_PRECIS: ::DWORD = 3; +pub const OUT_TT_PRECIS: ::DWORD = 4; +pub const OUT_DEVICE_PRECIS: ::DWORD = 5; +pub const OUT_RASTER_PRECIS: ::DWORD = 6; +pub const OUT_TT_ONLY_PRECIS: ::DWORD = 7; +pub const OUT_OUTLINE_PRECIS: ::DWORD = 8; +pub const OUT_SCREEN_OUTLINE_PRECIS: ::DWORD = 9; +pub const OUT_PS_ONLY_PRECIS: ::DWORD = 10; +pub const CLIP_DEFAULT_PRECIS: ::DWORD = 0; +pub const CLIP_CHARACTER_PRECIS: ::DWORD = 1; +pub const CLIP_STROKE_PRECIS: ::DWORD = 2; +pub const CLIP_MASK: ::DWORD = 0xf; +pub const CLIP_LH_ANGLES: ::DWORD = 1 << 4; +pub const CLIP_TT_ALWAYS: ::DWORD = 2 << 4; +pub const CLIP_DFA_DISABLE: ::DWORD = 4 << 4; +pub const CLIP_EMBEDDED: ::DWORD = 8 << 4; +pub const DEFAULT_QUALITY: ::DWORD = 0; +pub const DRAFT_QUALITY: ::DWORD = 1; +pub const PROOF_QUALITY: ::DWORD = 2; +pub const NONANTIALIASED_QUALITY: ::DWORD = 3; +pub const ANTIALIASED_QUALITY: ::DWORD = 4; +pub const CLEARTYPE_QUALITY: ::DWORD = 5; +pub const CLEARTYPE_NATURAL_QUALITY: ::DWORD = 6; +pub const DEFAULT_PITCH: ::DWORD = 0; +pub const FIXED_PITCH: ::DWORD = 1; +pub const VARIABLE_PITCH: ::DWORD = 2; +pub const FF_DONTCARE: ::DWORD = 0 << 4; +pub const FF_ROMAN: ::DWORD = 1 << 4; +pub const FF_SWISS: ::DWORD = 2 << 4; +pub const FF_MODERN: ::DWORD = 3 << 4; +pub const FF_SCRIPT: ::DWORD = 4 << 4; +pub const FF_DECORATIVE: ::DWORD = 5 << 4; +pub const MONO_FONT: ::DWORD = 8; +pub const ANSI_CHARSET: ::DWORD = 0; +pub const DEFAULT_CHARSET: ::DWORD = 1; +pub const SYMBOL_CHARSET: ::DWORD = 2; +pub const SHIFTJIS_CHARSET: ::DWORD = 128; +pub const HANGEUL_CHARSET: ::DWORD = 129; +pub const HANGUL_CHARSET: ::DWORD = 129; +pub const GB2312_CHARSET: ::DWORD = 134; +pub const CHINESEBIG5_CHARSET: ::DWORD = 136; +pub const OEM_CHARSET: ::DWORD = 255; +pub const JOHAB_CHARSET: ::DWORD = 130; +pub const HEBREW_CHARSET: ::DWORD = 177; +pub const ARABIC_CHARSET: ::DWORD = 178; +pub const GREEK_CHARSET: ::DWORD = 161; +pub const TURKISH_CHARSET: ::DWORD = 162; +pub const VIETNAMESE_CHARSET: ::DWORD = 163; +pub const THAI_CHARSET: ::DWORD = 222; +pub const EASTEUROPE_CHARSET: ::DWORD = 238; +pub const RUSSIAN_CHARSET: ::DWORD = 204; +pub const MAC_CHARSET: ::DWORD = 77; +pub const BALTIC_CHARSET: ::DWORD = 186; +pub const FS_LATIN1: ::DWORD = 0x00000001; +pub const FS_LATIN2: ::DWORD = 0x00000002; +pub const FS_CYRILLIC: ::DWORD = 0x00000004; +pub const FS_GREEK: ::DWORD = 0x00000008; +pub const FS_TURKISH: ::DWORD = 0x00000010; +pub const FS_HEBREW: ::DWORD = 0x00000020; +pub const FS_ARABIC: ::DWORD = 0x00000040; +pub const FS_BALTIC: ::DWORD = 0x00000080; +pub const FS_VIETNAMESE: ::DWORD = 0x00000100; +pub const FS_THAI: ::DWORD = 0x00010000; +pub const FS_JISJAPAN: ::DWORD = 0x00020000; +pub const FS_CHINESESIMP: ::DWORD = 0x00040000; +pub const FS_WANSUNG: ::DWORD = 0x00080000; +pub const FS_CHINESETRAD: ::DWORD = 0x00100000; +pub const FS_JOHAB: ::DWORD = 0x00200000; +pub const FS_SYMBOL: ::DWORD = 0x80000000; +pub const FW_DONTCARE: ::c_int = 0; +pub const FW_THIN: ::c_int = 100; +pub const FW_EXTRALIGHT: ::c_int = 200; +pub const FW_LIGHT: ::c_int = 300; +pub const FW_NORMAL: ::c_int = 400; +pub const FW_MEDIUM: ::c_int = 500; +pub const FW_SEMIBOLD: ::c_int = 600; +pub const FW_BOLD: ::c_int = 700; +pub const FW_EXTRABOLD: ::c_int = 800; +pub const FW_HEAVY: ::c_int = 900; +pub const FW_ULTRALIGHT: ::c_int = FW_EXTRALIGHT; +pub const FW_REGULAR: ::c_int = FW_NORMAL; +pub const FW_DEMIBOLD: ::c_int = FW_SEMIBOLD; +pub const FW_ULTRABOLD: ::c_int = FW_EXTRABOLD; +pub const FW_BLACK: ::c_int = FW_HEAVY; +pub type COLOR16 = ::c_ushort; +STRUCT!{struct TRIVERTEX { + x: ::LONG, + y: ::LONG, + Red: COLOR16, + Green: COLOR16, + Blue: COLOR16, + Alpha: COLOR16, +}} +pub type PTRIVERTEX = *mut TRIVERTEX; +pub type LPTRIVERTEX = *mut TRIVERTEX; +STRUCT!{struct GRADIENT_RECT { + UpperLeft: ::ULONG, + LowerRight: ::ULONG, +}} +pub type PGRADIENT_RECT = *mut GRADIENT_RECT; +pub type LPGRADIENT_RECT = *mut GRADIENT_RECT; +/* Object Definitions for EnumObjects() */ +pub const OBJ_PEN: ::UINT = 1; +pub const OBJ_BRUSH: ::UINT = 2; +pub const OBJ_DC: ::UINT = 3; +pub const OBJ_METADC: ::UINT = 4; +pub const OBJ_PAL: ::UINT = 5; +pub const OBJ_FONT: ::UINT = 6; +pub const OBJ_BITMAP: ::UINT = 7; +pub const OBJ_REGION: ::UINT = 8; +pub const OBJ_METAFILE: ::UINT = 9; +pub const OBJ_MEMDC: ::UINT = 10; +pub const OBJ_EXTPEN: ::UINT = 11; +pub const OBJ_ENHMETADC: ::UINT = 12; +pub const OBJ_ENHMETAFILE: ::UINT = 13; +pub const OBJ_COLORSPACE: ::UINT = 14; +pub const GDI_OBJ_LAST: ::UINT = OBJ_COLORSPACE; +STRUCT!{struct COLORADJUSTMENT { + caSize: ::WORD, + caFlags: ::WORD, + caIlluminantIndex: ::WORD, + caRedGamma: ::WORD, + caGreenGamma: ::WORD, + caBlueGamma: ::WORD, + caReferenceBlack: ::WORD, + caReferenceWhite: ::WORD, + caContrast: ::SHORT, + caBrightness: ::SHORT, + caColorfulness: ::SHORT, + caRedGreenTint: ::SHORT, +}} +pub type PCOLORADJUSTMENT = *mut COLORADJUSTMENT; +pub type LPCOLORADJUSTMENT = *mut COLORADJUSTMENT; +pub type OLDFONTENUMPROCA = Option<unsafe extern "system" fn( + *const LOGFONTA, *const ::VOID, ::DWORD, ::LPARAM +) -> ::c_int>; +pub type OLDFONTENUMPROCW = Option<unsafe extern "system" fn( + *const LOGFONTW, *const ::VOID, ::DWORD, ::LPARAM +) -> ::c_int>; +pub type FONTENUMPROCA = OLDFONTENUMPROCA; +pub type FONTENUMPROCW = OLDFONTENUMPROCW; +STRUCT!{struct WCRANGE { + wcLow: ::WCHAR, + cGlyphs: ::USHORT, +}} +pub type PWCRANGE = *mut WCRANGE; +pub type LPWCRANGE = *mut WCRANGE; +STRUCT!{struct GLYPHSET { + cbThis: ::DWORD, + flAccel: ::DWORD, + cGlyphsSupported: ::DWORD, + cRanges: ::DWORD, + ranges: [WCRANGE;1], +}} +pub type PGLYPHSET = *mut GLYPHSET; +pub type LPGLYPHSET = *mut GLYPHSET; +pub type ABORTPROC = Option<unsafe extern "system" fn(::HDC, ::c_int) -> ::BOOL>; +STRUCT!{struct DOCINFOA { + cbSize: ::c_int, + lpszDocName: ::LPCSTR, + lpszOutput: ::LPCSTR, + lpszDatatype: ::LPCSTR, + fwType: ::DWORD, +}} +pub type LPDOCINFOA = *mut DOCINFOA; +STRUCT!{struct DOCINFOW { + cbSize: ::c_int, + lpszDocName: ::LPCWSTR, + lpszOutput: ::LPCWSTR, + lpszDatatype: ::LPCWSTR, + fwType: ::DWORD, +}} +pub type LPDOCINFOW = *mut DOCINFOW; +pub type ICMENUMPROCA = Option<unsafe extern "system" fn(::LPSTR, ::LPARAM) -> ::c_int>; +pub type ICMENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR, ::LPARAM) -> ::c_int>; +STRUCT!{struct HANDLETABLE { + objectHandle: [::HGDIOBJ; 1], +}} +pub type LPHANDLETABLE = *mut HANDLETABLE; +pub type PHANDLETABLE = *mut HANDLETABLE; +STRUCT!{struct METARECORD { + rdSize: ::DWORD, + rdFunction: ::WORD, + rdParm: [::WORD; 1], +}} +pub type PMETARECORD = *mut METARECORD; +pub type LPMETARECORD = *mut METARECORD; +pub type MFENUMPROC = Option<unsafe extern "system" fn( + hdc: ::HDC, lpht: *mut ::HANDLETABLE, lpMR: *mut ::METARECORD, nObj: ::c_int, param: ::LPARAM +) -> ::c_int>; +pub type GOBJENUMPROC = Option<unsafe extern "system" fn(::LPVOID, ::LPARAM) -> ::c_int>; +STRUCT!{struct GCP_RESULTSA { + lStructSize: ::DWORD, + lpOutString: ::LPSTR, + lpOrder: *const ::UINT, + lpDx: *const ::c_int, + lpCaretPos: *const ::c_int, + lpClass: ::LPSTR, + lpGlyphs: ::LPWSTR, + nGlyphs: ::UINT, + nMaxFit: ::c_int, +}} +pub type LPGCP_RESULTSA = *mut GCP_RESULTSA; +STRUCT!{struct GCP_RESULTSW { + lStructSize: ::DWORD, + lpOutString: ::LPWSTR, + lpOrder: *const ::UINT, + lpDx: *const ::c_int, + lpCaretPos: *const ::c_int, + lpClass: ::LPSTR, + lpGlyphs: ::LPWSTR, + nGlyphs: ::UINT, + nMaxFit: ::c_int, +}} +pub type LPGCP_RESULTSW = *mut GCP_RESULTSW; +STRUCT!{struct FONTSIGNATURE { + fsUsb: [::DWORD; 4], + fsCsb: [::DWORD; 2], +}} +pub type LPFONTSIGNATURE = *mut FONTSIGNATURE; +pub type PFONTSIGNATURE = *mut FONTSIGNATURE; +STRUCT!{struct POLYTEXTA { + x: ::c_int, + y: ::c_int, + n: ::UINT, + lpstr: ::LPCSTR, + uiFlags: ::UINT, + rcl: ::RECT, + pdx: *const ::c_int, +}} +pub type PPOLYTEXTA = *mut POLYTEXTA; +pub type NPPOLYTEXTA = *mut POLYTEXTA; +pub type LPPOLYTEXTA = *mut POLYTEXTA; +STRUCT!{struct POLYTEXTW { + x: ::c_int, + y: ::c_int, + n: ::UINT, + lpstr: ::LPCWSTR, + uiFlags: ::UINT, + rcl: ::RECT, + pdx: *const ::c_int, +}} +pub type PPOLYTEXTW = *mut POLYTEXTW; +pub type NPPOLYTEXTW = *mut POLYTEXTW; +pub type LPPOLYTEXTW = *mut POLYTEXTW; +STRUCT!{struct CHARSETINFO { + ciCharset: ::UINT, + ciACP: ::UINT, + fs: ::FONTSIGNATURE, +}} +pub type PCHARSETINFO = *mut CHARSETINFO; +pub type NPCHARSETINFO = *mut CHARSETINFO; +pub type LPCHARSETINFO = *mut CHARSETINFO; +pub const GRADIENT_FILL_RECT_H: ::ULONG = 0x00000000; +pub const GRADIENT_FILL_RECT_V: ::ULONG = 0x00000001; +pub const GRADIENT_FILL_TRIANGLE: ::ULONG = 0x00000002; +pub const GRADIENT_FILL_OP_FLAG: ::ULONG = 0x000000ff; +STRUCT!{struct LAYERPLANEDESCRIPTOR { + nSize: ::WORD, + nVersion: ::WORD, + dwFlags: ::DWORD, + iPixelType: ::BYTE, + cColorBits: ::BYTE, + cRedBits: ::BYTE, + cRedShift: ::BYTE, + cGreenBits: ::BYTE, + cGreenShift: ::BYTE, + cBlueBits: ::BYTE, + cBlueShift: ::BYTE, + cAlphaBits: ::BYTE, + cAlphaShift: ::BYTE, + cAccumBits: ::BYTE, + cAccumRedBits: ::BYTE, + cAccumGreenBits: ::BYTE, + cAccumBlueBits: ::BYTE, + cAccumAlphaBits: ::BYTE, + cDepthBits: ::BYTE, + cStencilBits: ::BYTE, + cAuxBuffers: ::BYTE, + iLayerPlane: ::BYTE, + bReserved: ::BYTE, + crTransparent: ::COLORREF, +}} +pub type PLAYERPLANEDESCRIPTOR = *mut LAYERPLANEDESCRIPTOR; +pub type LPLAYERPLANEDESCRIPTOR = *mut LAYERPLANEDESCRIPTOR; +STRUCT!{struct ENHMETAHEADER { + iType: ::DWORD, + nSize: ::DWORD, + rclBounds: ::RECTL, + rclFrame: ::RECTL, + dSignature: ::DWORD, + nVersion: ::DWORD, + nBytes: ::DWORD, + nRecords: ::DWORD, + nHandles: ::WORD, + sReserved: ::WORD, + nDescription: ::DWORD, + offDescription: ::DWORD, + nPalEntries: ::DWORD, + szlDevice: ::SIZEL, + szlMillimeters: ::SIZEL, + cbPixelFormat: ::DWORD, + offPixelFormat: ::DWORD, + bOpenGL: ::DWORD, + szlMicrometers: ::SIZEL, +}} +pub type PENHMETAHEADER = *mut ENHMETAHEADER; +pub type LPENHMETAHEADER = *mut ENHMETAHEADER; +STRUCT!{struct FIXED { + fract: ::WORD, + value: ::c_short, +}} +STRUCT!{struct MAT2 { + eM11: FIXED, + eM12: FIXED, + eM21: FIXED, + eM22: FIXED, +}} +pub type LPMAT2 = *mut MAT2; +STRUCT!{struct GLYPHMETRICS { + gmBlackBoxX: ::UINT, + gmBlackBoxY: ::UINT, + gmptGlyphOrigin: ::POINT, + gmCellIncX: ::c_short, + gmCellIncY: ::c_short, +}} +pub type LPGLYPHMETRICS = *mut GLYPHMETRICS; +STRUCT!{struct KERNINGPAIR { + wFirst: ::WORD, + wSecond: ::WORD, + iKernAmount: ::c_int, +}} +pub type LPKERNINGPAIR = *mut KERNINGPAIR; +STRUCT!{struct PANOSE { + bFamilyType: ::BYTE, + bSerifStyle: ::BYTE, + bWeight: ::BYTE, + bProportion: ::BYTE, + bContrast: ::BYTE, + bStrokeVariation: ::BYTE, + bArmStyle: ::BYTE, + bLetterform: ::BYTE, + bMidline: ::BYTE, + bXHeight: ::BYTE, +}} +pub type LPPANOSE = *mut PANOSE; +STRUCT!{struct OUTLINETEXTMETRICA { + otmSize: ::UINT, + otmTextMetrics: TEXTMETRICA, + otmFiller: ::BYTE, + otmPanoseNumber: ::PANOSE, + otmfsSelection: ::UINT, + otmfsType: ::UINT, + otmsCharSlopeRise: ::c_int, + otmsCharSlopeRun: ::c_int, + otmItalicAngle: ::c_int, + otmEMSquare: ::UINT, + otmAscent: ::c_int, + otmDescent: ::c_int, + otmLineGap: ::UINT, + otmsCapEmHeight: ::UINT, + otmsXHeight: ::UINT, + otmrcFontBox: ::RECT, + otmMacAscent: ::c_int, + otmMacDescent: ::c_int, + otmMacLineGap: ::UINT, + otmusMinimumPPEM: ::UINT, + otmptSubscriptSize: ::POINT, + otmptSubscriptOffset: ::POINT, + otmptSuperscriptSize: ::POINT, + otmptSuperscriptOffset: ::POINT, + otmsStrikeoutSize: ::UINT, + otmsStrikeoutPosition: ::c_int, + otmsUnderscoreSize: ::c_int, + otmsUnderscorePosition: ::c_int, + otmpFamilyName: ::PSTR, + otmpFaceName: ::PSTR, + otmpStyleName: ::PSTR, + otmpFullName: ::PSTR, +}} +pub type POUTLINETEXTMETRICA = *mut OUTLINETEXTMETRICA; +pub type NPOUTLINETEXTMETRICA = *mut OUTLINETEXTMETRICA; +pub type LPOUTLINETEXTMETRICA = *mut OUTLINETEXTMETRICA; +STRUCT!{struct OUTLINETEXTMETRICW { + otmSize: ::UINT, + otmTextMetrics: TEXTMETRICW, + otmFiller: ::BYTE, + otmPanoseNumber: ::PANOSE, + otmfsSelection: ::UINT, + otmfsType: ::UINT, + otmsCharSlopeRise: ::c_int, + otmsCharSlopeRun: ::c_int, + otmItalicAngle: ::c_int, + otmEMSquare: ::UINT, + otmAscent: ::c_int, + otmDescent: ::c_int, + otmLineGap: ::UINT, + otmsCapEmHeight: ::UINT, + otmsXHeight: ::UINT, + otmrcFontBox: ::RECT, + otmMacAscent: ::c_int, + otmMacDescent: ::c_int, + otmMacLineGap: ::UINT, + otmusMinimumPPEM: ::UINT, + otmptSubscriptSize: ::POINT, + otmptSubscriptOffset: ::POINT, + otmptSuperscriptSize: ::POINT, + otmptSuperscriptOffset: ::POINT, + otmsStrikeoutSize: ::UINT, + otmsStrikeoutPosition: ::c_int, + otmsUnderscoreSize: ::c_int, + otmsUnderscorePosition: ::c_int, + otmpFamilyName: ::PSTR, + otmpFaceName: ::PSTR, + otmpStyleName: ::PSTR, + otmpFullName: ::PSTR, +}} +pub type POUTLINETEXTMETRICW = *mut OUTLINETEXTMETRICW; +pub type NPOUTLINETEXTMETRICW = *mut OUTLINETEXTMETRICW; +pub type LPOUTLINETEXTMETRICW = *mut OUTLINETEXTMETRICW; +STRUCT!{struct RASTERIZER_STATUS { + nSize: ::c_short, + wFlags: ::c_short, + nLanguageID: ::c_short, +}} +pub type LPRASTERIZER_STATUS = *mut RASTERIZER_STATUS; +STRUCT!{struct ENHMETARECORD { + iType: ::DWORD, + nSize: ::DWORD, + dParm: [::DWORD; 1], +}} +pub type PENHMETARECORD = *mut ENHMETARECORD; +pub type LPENHMETARECORD = *mut ENHMETARECORD; +STRUCT!{struct METAFILEPICT { + mm: ::LONG, + xExt: ::LONG, + yExt: ::LONG, + hMF: ::HMETAFILE, +}} +pub type LPMETAFILEPICT = *mut METAFILEPICT; +STRUCT!{struct POINTFLOAT { + x: ::FLOAT, + y: ::FLOAT, +}} +pub type PPOINTFLOAT = *mut POINTFLOAT; +STRUCT!{struct GLYPHMETRICSFLOAT { + gmfBlackBoxX: ::FLOAT, + gmfBlackBoxY: ::FLOAT, + gmfptGlyphOrigin: POINTFLOAT, + gmfCellIncX: ::FLOAT, + gmfCellIncY: ::FLOAT, +}} +pub type PGLYPHMETRICSFLOAT = *mut GLYPHMETRICSFLOAT; +pub type LPGLYPHMETRICSFLOAT = *mut GLYPHMETRICSFLOAT; +pub const DT_PLOTTER: ::c_int = 0; +pub const DT_RASDISPLAY: ::c_int = 1; +pub const DT_RASPRINTER: ::c_int = 2; +pub const DT_RASCAMERA: ::c_int = 3; +pub const DT_CHARSTREAM: ::c_int = 4; +pub const DT_METAFILE: ::c_int = 5; +pub const DT_DISPFILE: ::c_int = 6; +pub const CLR_INVALID: ::COLORREF = 0xFFFFFFFF; +pub const ETO_OPAQUE: ::UINT = 0x0002; +pub const ETO_CLIPPED: ::UINT = 0x0004; +pub const ETO_GLYPH_INDEX: ::UINT = 0x0010; +pub const ETO_RTLREADING: ::UINT = 0x0080; +pub const ETO_NUMERICSLOCAL: ::UINT = 0x0400; +pub const ETO_NUMERICSLATIN: ::UINT = 0x0800; +pub const ETO_IGNORELANGUAGE: ::UINT = 0x1000; +pub const ETO_PDY: ::UINT = 0x2000; +pub const ETO_REVERSE_INDEX_MAP: ::UINT = 0x10000; +STRUCT!{struct EXTLOGPEN { + elpPenStyle: ::DWORD, + elpWidth: ::DWORD, + elpBrushStyle: ::UINT, + elpColor: ::COLORREF, + elpHatch: ::ULONG_PTR, + elpNumEntries: ::DWORD, + elpStyleEntry: [::DWORD; 1], +}} +pub type PEXTLOGPEN = *mut EXTLOGPEN; +pub type NPEXTLOGPEN = *mut EXTLOGPEN; +pub type LPEXTLOGPEN = *mut EXTLOGPEN; +pub type ENHMFENUMPROC = Option<unsafe extern "system" fn( + hdc: ::HDC, lpht: HANDLETABLE, lpmr: *const ENHMETARECORD, nHandles: ::c_int, data: ::LPARAM +) -> ::c_int>; +/* Metafile Functions */ +pub const META_SETBKCOLOR: ::WORD = 0x0201; +pub const META_SETBKMODE: ::WORD = 0x0102; +pub const META_SETMAPMODE: ::WORD = 0x0103; +pub const META_SETROP2: ::WORD = 0x0104; +pub const META_SETRELABS: ::WORD = 0x0105; +pub const META_SETPOLYFILLMODE: ::WORD = 0x0106; +pub const META_SETSTRETCHBLTMODE: ::WORD = 0x0107; +pub const META_SETTEXTCHAREXTRA: ::WORD = 0x0108; +pub const META_SETTEXTCOLOR: ::WORD = 0x0209; +pub const META_SETTEXTJUSTIFICATION: ::WORD = 0x020A; +pub const META_SETWINDOWORG: ::WORD = 0x020B; +pub const META_SETWINDOWEXT: ::WORD = 0x020C; +pub const META_SETVIEWPORTORG: ::WORD = 0x020D; +pub const META_SETVIEWPORTEXT: ::WORD = 0x020E; +pub const META_OFFSETWINDOWORG: ::WORD = 0x020F; +pub const META_SCALEWINDOWEXT: ::WORD = 0x0410; +pub const META_OFFSETVIEWPORTORG: ::WORD = 0x0211; +pub const META_SCALEVIEWPORTEXT: ::WORD = 0x0412; +pub const META_LINETO: ::WORD = 0x0213; +pub const META_MOVETO: ::WORD = 0x0214; +pub const META_EXCLUDECLIPRECT: ::WORD = 0x0415; +pub const META_INTERSECTCLIPRECT: ::WORD = 0x0416; +pub const META_ARC: ::WORD = 0x0817; +pub const META_ELLIPSE: ::WORD = 0x0418; +pub const META_FLOODFILL: ::WORD = 0x0419; +pub const META_PIE: ::WORD = 0x081A; +pub const META_RECTANGLE: ::WORD = 0x041B; +pub const META_ROUNDRECT: ::WORD = 0x061C; +pub const META_PATBLT: ::WORD = 0x061D; +pub const META_SAVEDC: ::WORD = 0x001E; +pub const META_SETPIXEL: ::WORD = 0x041F; +pub const META_OFFSETCLIPRGN: ::WORD = 0x0220; +pub const META_TEXTOUT: ::WORD = 0x0521; +pub const META_BITBLT: ::WORD = 0x0922; +pub const META_STRETCHBLT: ::WORD = 0x0B23; +pub const META_POLYGON: ::WORD = 0x0324; +pub const META_POLYLINE: ::WORD = 0x0325; +pub const META_ESCAPE: ::WORD = 0x0626; +pub const META_RESTOREDC: ::WORD = 0x0127; +pub const META_FILLREGION: ::WORD = 0x0228; +pub const META_FRAMEREGION: ::WORD = 0x0429; +pub const META_INVERTREGION: ::WORD = 0x012A; +pub const META_PAINTREGION: ::WORD = 0x012B; +pub const META_SELECTCLIPREGION: ::WORD = 0x012C; +pub const META_SELECTOBJECT: ::WORD = 0x012D; +pub const META_SETTEXTALIGN: ::WORD = 0x012E; +pub const META_CHORD: ::WORD = 0x0830; +pub const META_SETMAPPERFLAGS: ::WORD = 0x0231; +pub const META_EXTTEXTOUT: ::WORD = 0x0a32; +pub const META_SETDIBTODEV: ::WORD = 0x0d33; +pub const META_SELECTPALETTE: ::WORD = 0x0234; +pub const META_REALIZEPALETTE: ::WORD = 0x0035; +pub const META_ANIMATEPALETTE: ::WORD = 0x0436; +pub const META_SETPALENTRIES: ::WORD = 0x0037; +pub const META_POLYPOLYGON: ::WORD = 0x0538; +pub const META_RESIZEPALETTE: ::WORD = 0x0139; +pub const META_DIBBITBLT: ::WORD = 0x0940; +pub const META_DIBSTRETCHBLT: ::WORD = 0x0b41; +pub const META_DIBCREATEPATTERNBRUSH: ::WORD = 0x0142; +pub const META_STRETCHDIB: ::WORD = 0x0f43; +pub const META_EXTFLOODFILL: ::WORD = 0x0548; +pub const META_SETLAYOUT: ::WORD = 0x0149; +pub const META_DELETEOBJECT: ::WORD = 0x01f0; +pub const META_CREATEPALETTE: ::WORD = 0x00f7; +pub const META_CREATEPATTERNBRUSH: ::WORD = 0x01F9; +pub const META_CREATEPENINDIRECT: ::WORD = 0x02FA; +pub const META_CREATEFONTINDIRECT: ::WORD = 0x02FB; +pub const META_CREATEBRUSHINDIRECT: ::WORD = 0x02FC; +pub const META_CREATEREGION: ::WORD = 0x06FF; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winhttp.rs b/bash-5.1/vendor/winapi-0.2.8/src/winhttp.rs new file mode 100644 index 0000000..e8ca6f6 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winhttp.rs @@ -0,0 +1,441 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Windows HTTP Services API constant definitions and macros +//54 +pub type HINTERNET = ::LPVOID; +pub type LPHINTERNET = *mut HINTERNET; +pub type INTERNET_PORT = ::WORD; +pub type LPINTERNET_PORT = *mut INTERNET_PORT; +pub const INTERNET_DEFAULT_PORT: INTERNET_PORT = 0; +pub const INTERNET_DEFAULT_HTTP_PORT: INTERNET_PORT = 80; +pub const INTERNET_DEFAULT_HTTPS_PORT: INTERNET_PORT = 443; +pub const WINHTTP_FLAG_ASYNC: ::DWORD = 0x10000000; +pub const WINHTTP_FLAG_SECURE: ::DWORD = 0x00800000; +pub const WINHTTP_FLAG_ESCAPE_PERCENT: ::DWORD = 0x00000004; +pub const WINHTTP_FLAG_NULL_CODEPAGE: ::DWORD = 0x00000008; +pub const WINHTTP_FLAG_BYPASS_PROXY_CACHE: ::DWORD = 0x00000100; +pub const WINHTTP_FLAG_REFRESH: ::DWORD = WINHTTP_FLAG_BYPASS_PROXY_CACHE; +pub const WINHTTP_FLAG_ESCAPE_DISABLE: ::DWORD = 0x00000040; +pub const WINHTTP_FLAG_ESCAPE_DISABLE_QUERY: ::DWORD = 0x00000080; +STRUCT!{struct WINHTTP_ASYNC_RESULT { + dwResult: ::DWORD_PTR, + dwError: ::DWORD, +}} +pub type LPWINHTTP_ASYNC_RESULT = *mut WINHTTP_ASYNC_RESULT; +pub type INTERNET_SCHEME = ::c_int; +pub type LPINTERNET_SCHEME = *mut ::c_int; +pub const INTERNET_SCHEME_HTTP: INTERNET_SCHEME = 1; +pub const INTERNET_SCHEME_HTTPS: INTERNET_SCHEME = 2; +pub const INTERNET_SCHEME_FTP: INTERNET_SCHEME = 3; +pub const INTERNET_SCHEME_SOCKS: INTERNET_SCHEME = 4; +STRUCT!{struct URL_COMPONENTS { + dwStructSize: ::DWORD, + lpszScheme: ::LPWSTR, + dwSchemeLength: ::DWORD, + nScheme: INTERNET_SCHEME, + lpszHostName: ::LPWSTR, + dwHostNameLength: ::DWORD, + nPort: INTERNET_PORT, + lpszUserName: ::LPWSTR, + dwUserNameLength: ::DWORD, + lpszPassword: ::LPWSTR, + dwPasswordLength: ::DWORD, + lpszUrlPath: ::LPWSTR, + dwUrlPathLength: ::DWORD, + lpszExtraInfo: ::LPWSTR, + dwExtraInfoLength: ::DWORD, +}} +pub type LPURL_COMPONENTS = *mut URL_COMPONENTS; +pub type URL_COMPONENTSW = URL_COMPONENTS; +pub type LPURL_COMPONENTSW = LPURL_COMPONENTS; +STRUCT!{struct WINHTTP_PROXY_INFO { + dwAccessType: ::DWORD, + lpszProxy: ::LPWSTR, + lpszProxyBypass: ::LPWSTR, +}} +pub type LPWINHTTP_PROXY_INFO = *mut WINHTTP_PROXY_INFO; +pub type WINHTTP_PROXY_INFOW = WINHTTP_PROXY_INFO; +pub type LPWINHTTP_PROXY_INFOW = LPWINHTTP_PROXY_INFO; +STRUCT!{struct WINHTTP_AUTOPROXY_OPTIONS { + dwFlags: ::DWORD, + dwAutoDetectFlags: ::DWORD, + lpszAutoConfigUrl: ::LPCWSTR, + lpvReserved: ::LPVOID, + dwReserved: ::DWORD, + fAutoLogonIfChallenged: ::BOOL, +}} +pub const WINHTTP_AUTOPROXY_AUTO_DETECT: ::DWORD = 0x00000001; +pub const WINHTTP_AUTOPROXY_CONFIG_URL: ::DWORD = 0x00000002; +pub const WINHTTP_AUTOPROXY_HOST_KEEPCASE: ::DWORD = 0x00000004; +pub const WINHTTP_AUTOPROXY_HOST_LOWERCASE: ::DWORD = 0x00000008; +pub const WINHTTP_AUTOPROXY_RUN_INPROCESS: ::DWORD = 0x00010000; +pub const WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY: ::DWORD = 0x00020000; +pub const WINHTTP_AUTOPROXY_NO_DIRECTACCESS: ::DWORD = 0x00040000; +pub const WINHTTP_AUTOPROXY_NO_CACHE_CLIENT: ::DWORD = 0x00080000; +pub const WINHTTP_AUTOPROXY_NO_CACHE_SVC: ::DWORD = 0x00100000; +pub const WINHTTP_AUTOPROXY_SORT_RESULTS: ::DWORD = 0x00400000; +pub const WINHTTP_AUTO_DETECT_TYPE_DHCP: ::DWORD = 0x00000001; +pub const WINHTTP_AUTO_DETECT_TYPE_DNS_A: ::DWORD = 0x00000002; +STRUCT!{struct WINHTTP_PROXY_RESULT_ENTRY { + fProxy: ::BOOL, + fBypass: ::BOOL, + ProxyScheme: INTERNET_SCHEME, + pwszProxy: ::PWSTR, + ProxyPort: INTERNET_PORT, +}} +STRUCT!{struct WINHTTP_PROXY_RESULT { + cEntries: ::DWORD, + pEntries: *mut WINHTTP_PROXY_RESULT_ENTRY, +}} +pub const WINHTTP_FIRST_OPTION: ::DWORD = WINHTTP_OPTION_CALLBACK; +pub const WINHTTP_OPTION_CALLBACK: ::DWORD = 1; +pub const WINHTTP_OPTION_RESOLVE_TIMEOUT: ::DWORD = 2; +pub const WINHTTP_OPTION_CONNECT_TIMEOUT: ::DWORD = 3; +pub const WINHTTP_OPTION_CONNECT_RETRIES: ::DWORD = 4; +pub const WINHTTP_OPTION_SEND_TIMEOUT: ::DWORD = 5; +pub const WINHTTP_OPTION_RECEIVE_TIMEOUT: ::DWORD = 6; +pub const WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT: ::DWORD = 7; +pub const WINHTTP_OPTION_HANDLE_TYPE: ::DWORD = 9; +pub const WINHTTP_OPTION_READ_BUFFER_SIZE: ::DWORD = 12; +pub const WINHTTP_OPTION_WRITE_BUFFER_SIZE: ::DWORD = 13; +pub const WINHTTP_OPTION_PARENT_HANDLE: ::DWORD = 21; +pub const WINHTTP_OPTION_EXTENDED_ERROR: ::DWORD = 24; +pub const WINHTTP_OPTION_SECURITY_FLAGS: ::DWORD = 31; +pub const WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT: ::DWORD = 32; +pub const WINHTTP_OPTION_URL: ::DWORD = 34; +pub const WINHTTP_OPTION_SECURITY_KEY_BITNESS: ::DWORD = 36; +pub const WINHTTP_OPTION_PROXY: ::DWORD = 38; +pub const WINHTTP_OPTION_PROXY_RESULT_ENTRY: ::DWORD = 39; +pub const WINHTTP_OPTION_USER_AGENT: ::DWORD = 41; +pub const WINHTTP_OPTION_CONTEXT_VALUE: ::DWORD = 45; +pub const WINHTTP_OPTION_CLIENT_CERT_CONTEXT: ::DWORD = 47; +pub const WINHTTP_OPTION_REQUEST_PRIORITY: ::DWORD = 58; +pub const WINHTTP_OPTION_HTTP_VERSION: ::DWORD = 59; +pub const WINHTTP_OPTION_DISABLE_FEATURE: ::DWORD = 63; +pub const WINHTTP_OPTION_CODEPAGE: ::DWORD = 68; +pub const WINHTTP_OPTION_MAX_CONNS_PER_SERVER: ::DWORD = 73; +pub const WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER: ::DWORD = 74; +pub const WINHTTP_OPTION_AUTOLOGON_POLICY: ::DWORD = 77; +pub const WINHTTP_OPTION_SERVER_CERT_CONTEXT: ::DWORD = 78; +pub const WINHTTP_OPTION_ENABLE_FEATURE: ::DWORD = 79; +pub const WINHTTP_OPTION_WORKER_THREAD_COUNT: ::DWORD = 80; +pub const WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT: ::DWORD = 81; +pub const WINHTTP_OPTION_PASSPORT_COBRANDING_URL: ::DWORD = 82; +pub const WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH: ::DWORD = 83; +pub const WINHTTP_OPTION_SECURE_PROTOCOLS: ::DWORD = 84; +pub const WINHTTP_OPTION_ENABLETRACING: ::DWORD = 85; +pub const WINHTTP_OPTION_PASSPORT_SIGN_OUT: ::DWORD = 86; +pub const WINHTTP_OPTION_PASSPORT_RETURN_URL: ::DWORD = 87; +pub const WINHTTP_OPTION_REDIRECT_POLICY: ::DWORD = 88; +pub const WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS: ::DWORD = 89; +pub const WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE: ::DWORD = 90; +pub const WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE: ::DWORD = 91; +pub const WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE: ::DWORD = 92; +pub const WINHTTP_OPTION_CONNECTION_INFO: ::DWORD = 93; +pub const WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST: ::DWORD = 94; +pub const WINHTTP_OPTION_SPN: ::DWORD = 96; +pub const WINHTTP_OPTION_GLOBAL_PROXY_CREDS: ::DWORD = 97; +pub const WINHTTP_OPTION_GLOBAL_SERVER_CREDS: ::DWORD = 98; +pub const WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT: ::DWORD = 99; +pub const WINHTTP_OPTION_REJECT_USERPWD_IN_URL: ::DWORD = 100; +pub const WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS: ::DWORD = 101; +pub const WINHTTP_OPTION_RECEIVE_PROXY_CONNECT_RESPONSE: ::DWORD = 103; +pub const WINHTTP_OPTION_IS_PROXY_CONNECT_RESPONSE: ::DWORD = 104; +pub const WINHTTP_OPTION_SERVER_SPN_USED: ::DWORD = 106; +pub const WINHTTP_OPTION_PROXY_SPN_USED: ::DWORD = 107; +pub const WINHTTP_OPTION_SERVER_CBT: ::DWORD = 108; +pub const WINHTTP_OPTION_UNSAFE_HEADER_PARSING: ::DWORD = 110; +pub const WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS: ::DWORD = 111; +pub const WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET: ::DWORD = 114; +pub const WINHTTP_OPTION_WEB_SOCKET_CLOSE_TIMEOUT: ::DWORD = 115; +pub const WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL: ::DWORD = 116; +pub const WINHTTP_OPTION_DECOMPRESSION: ::DWORD = 118; +pub const WINHTTP_OPTION_WEB_SOCKET_RECEIVE_BUFFER_SIZE: ::DWORD = 122; +pub const WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE: ::DWORD = 123; +pub const WINHTTP_LAST_OPTION: ::DWORD = WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE; +pub const WINHTTP_OPTION_USERNAME: ::DWORD = 0x1000; +pub const WINHTTP_OPTION_PASSWORD: ::DWORD = 0x1001; +pub const WINHTTP_OPTION_PROXY_USERNAME: ::DWORD = 0x1002; +pub const WINHTTP_OPTION_PROXY_PASSWORD: ::DWORD = 0x1003; +//552 +pub type WINHTTP_STATUS_CALLBACK = Option<unsafe extern "system" fn( + hInternet: HINTERNET, dwContext: ::DWORD_PTR, dwInternetStatus: ::DWORD, + lpvStatusInformation: ::LPVOID, dwStatusInformationLength: ::DWORD, +)>; +pub type LPWINHTTP_STATUS_CALLBACK = *mut WINHTTP_STATUS_CALLBACK; +pub const WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: ::DWORD = 0x00000001; +pub const WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: ::DWORD = 0x00000002; +pub const WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: ::DWORD = 0x00000004; +pub const WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: ::DWORD = 0x00000008; +pub const WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: ::DWORD = 0x00000010; +pub const WINHTTP_CALLBACK_STATUS_REQUEST_SENT: ::DWORD = 0x00000020; +pub const WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: ::DWORD = 0x00000040; +pub const WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: ::DWORD = 0x00000080; +pub const WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: ::DWORD = 0x00000100; +pub const WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: ::DWORD = 0x00000200; +pub const WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: ::DWORD = 0x00000400; +pub const WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: ::DWORD = 0x00000800; +pub const WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: ::DWORD = 0x00001000; +pub const WINHTTP_CALLBACK_STATUS_REDIRECT: ::DWORD = 0x00004000; +pub const WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: ::DWORD = 0x00008000; +pub const WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: ::DWORD = 0x00010000; +pub const WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: ::DWORD = 0x00020000; +pub const WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: ::DWORD = 0x00040000; +pub const WINHTTP_CALLBACK_STATUS_READ_COMPLETE: ::DWORD = 0x00080000; +pub const WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: ::DWORD = 0x00100000; +pub const WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: ::DWORD = 0x00200000; +pub const WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: ::DWORD = 0x00400000; +pub const WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE: ::DWORD = 0x01000000; +pub const WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE: ::DWORD = 0x02000000; +pub const WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE: ::DWORD = 0x04000000; +pub const WINHTTP_CALLBACK_FLAG_RESOLVE_NAME: ::DWORD = WINHTTP_CALLBACK_STATUS_RESOLVING_NAME + | WINHTTP_CALLBACK_STATUS_NAME_RESOLVED; +pub const WINHTTP_CALLBACK_FLAG_CONNECT_TO_SERVER: ::DWORD = + WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER | WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER; +pub const WINHTTP_CALLBACK_FLAG_SEND_REQUEST: ::DWORD = + WINHTTP_CALLBACK_STATUS_SENDING_REQUEST | WINHTTP_CALLBACK_STATUS_REQUEST_SENT; +pub const WINHTTP_CALLBACK_FLAG_RECEIVE_RESPONSE: ::DWORD = + WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE | WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED; +pub const WINHTTP_CALLBACK_FLAG_CLOSE_CONNECTION: ::DWORD = + WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION | WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED; +pub const WINHTTP_CALLBACK_FLAG_HANDLES: ::DWORD = + WINHTTP_CALLBACK_STATUS_HANDLE_CREATED | WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING; +pub const WINHTTP_CALLBACK_FLAG_DETECTING_PROXY: ::DWORD = WINHTTP_CALLBACK_STATUS_DETECTING_PROXY; +pub const WINHTTP_CALLBACK_FLAG_REDIRECT: ::DWORD = WINHTTP_CALLBACK_STATUS_REDIRECT; +pub const WINHTTP_CALLBACK_FLAG_INTERMEDIATE_RESPONSE: ::DWORD = + WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE; +pub const WINHTTP_CALLBACK_FLAG_SECURE_FAILURE: ::DWORD = WINHTTP_CALLBACK_STATUS_SECURE_FAILURE; +pub const WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE: ::DWORD = + WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE: ::DWORD = + WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE; +pub const WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE: ::DWORD = WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE; +pub const WINHTTP_CALLBACK_FLAG_READ_COMPLETE: ::DWORD = WINHTTP_CALLBACK_STATUS_READ_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE: ::DWORD = WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_REQUEST_ERROR: ::DWORD = WINHTTP_CALLBACK_STATUS_REQUEST_ERROR; +pub const WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE: ::DWORD = + WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS: ::DWORD = + WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE | WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE + | WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE | WINHTTP_CALLBACK_STATUS_READ_COMPLETE + | WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE | WINHTTP_CALLBACK_STATUS_REQUEST_ERROR + | WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS: ::DWORD = 0xffffffff; +pub const WINHTTP_QUERY_MIME_VERSION: ::DWORD = 0; +pub const WINHTTP_QUERY_CONTENT_TYPE: ::DWORD = 1; +pub const WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING: ::DWORD = 2; +pub const WINHTTP_QUERY_CONTENT_ID: ::DWORD = 3; +pub const WINHTTP_QUERY_CONTENT_DESCRIPTION: ::DWORD = 4; +pub const WINHTTP_QUERY_CONTENT_LENGTH: ::DWORD = 5; +pub const WINHTTP_QUERY_CONTENT_LANGUAGE: ::DWORD = 6; +pub const WINHTTP_QUERY_ALLOW: ::DWORD = 7; +pub const WINHTTP_QUERY_PUBLIC: ::DWORD = 8; +pub const WINHTTP_QUERY_DATE: ::DWORD = 9; +pub const WINHTTP_QUERY_EXPIRES: ::DWORD = 10; +pub const WINHTTP_QUERY_LAST_MODIFIED: ::DWORD = 11; +pub const WINHTTP_QUERY_MESSAGE_ID: ::DWORD = 12; +pub const WINHTTP_QUERY_URI: ::DWORD = 13; +pub const WINHTTP_QUERY_DERIVED_FROM: ::DWORD = 14; +pub const WINHTTP_QUERY_COST: ::DWORD = 15; +pub const WINHTTP_QUERY_LINK: ::DWORD = 16; +pub const WINHTTP_QUERY_PRAGMA: ::DWORD = 17; +pub const WINHTTP_QUERY_VERSION: ::DWORD = 18; +pub const WINHTTP_QUERY_STATUS_CODE: ::DWORD = 19; +pub const WINHTTP_QUERY_STATUS_TEXT: ::DWORD = 20; +pub const WINHTTP_QUERY_RAW_HEADERS: ::DWORD = 21; +pub const WINHTTP_QUERY_RAW_HEADERS_CRLF: ::DWORD = 22; +pub const WINHTTP_QUERY_CONNECTION: ::DWORD = 23; +pub const WINHTTP_QUERY_ACCEPT: ::DWORD = 24; +pub const WINHTTP_QUERY_ACCEPT_CHARSET: ::DWORD = 25; +pub const WINHTTP_QUERY_ACCEPT_ENCODING: ::DWORD = 26; +pub const WINHTTP_QUERY_ACCEPT_LANGUAGE: ::DWORD = 27; +pub const WINHTTP_QUERY_AUTHORIZATION: ::DWORD = 28; +pub const WINHTTP_QUERY_CONTENT_ENCODING: ::DWORD = 29; +pub const WINHTTP_QUERY_FORWARDED: ::DWORD = 30; +pub const WINHTTP_QUERY_FROM: ::DWORD = 31; +pub const WINHTTP_QUERY_IF_MODIFIED_SINCE: ::DWORD = 32; +pub const WINHTTP_QUERY_LOCATION: ::DWORD = 33; +pub const WINHTTP_QUERY_ORIG_URI: ::DWORD = 34; +pub const WINHTTP_QUERY_REFERER: ::DWORD = 35; +pub const WINHTTP_QUERY_RETRY_AFTER: ::DWORD = 36; +pub const WINHTTP_QUERY_SERVER: ::DWORD = 37; +pub const WINHTTP_QUERY_TITLE: ::DWORD = 38; +pub const WINHTTP_QUERY_USER_AGENT: ::DWORD = 39; +pub const WINHTTP_QUERY_WWW_AUTHENTICATE: ::DWORD = 40; +pub const WINHTTP_QUERY_PROXY_AUTHENTICATE: ::DWORD = 41; +pub const WINHTTP_QUERY_ACCEPT_RANGES: ::DWORD = 42; +pub const WINHTTP_QUERY_SET_COOKIE: ::DWORD = 43; +pub const WINHTTP_QUERY_COOKIE: ::DWORD = 44; +pub const WINHTTP_QUERY_REQUEST_METHOD: ::DWORD = 45; +pub const WINHTTP_QUERY_REFRESH: ::DWORD = 46; +pub const WINHTTP_QUERY_CONTENT_DISPOSITION: ::DWORD = 47; +pub const WINHTTP_QUERY_AGE: ::DWORD = 48; +pub const WINHTTP_QUERY_CACHE_CONTROL: ::DWORD = 49; +pub const WINHTTP_QUERY_CONTENT_BASE: ::DWORD = 50; +pub const WINHTTP_QUERY_CONTENT_LOCATION: ::DWORD = 51; +pub const WINHTTP_QUERY_CONTENT_MD5: ::DWORD = 52; +pub const WINHTTP_QUERY_CONTENT_RANGE: ::DWORD = 53; +pub const WINHTTP_QUERY_ETAG: ::DWORD = 54; +pub const WINHTTP_QUERY_HOST: ::DWORD = 55; +pub const WINHTTP_QUERY_IF_MATCH: ::DWORD = 56; +pub const WINHTTP_QUERY_IF_NONE_MATCH: ::DWORD = 57; +pub const WINHTTP_QUERY_IF_RANGE: ::DWORD = 58; +pub const WINHTTP_QUERY_IF_UNMODIFIED_SINCE: ::DWORD = 59; +pub const WINHTTP_QUERY_MAX_FORWARDS: ::DWORD = 60; +pub const WINHTTP_QUERY_PROXY_AUTHORIZATION: ::DWORD = 61; +pub const WINHTTP_QUERY_RANGE: ::DWORD = 62; +pub const WINHTTP_QUERY_TRANSFER_ENCODING: ::DWORD = 63; +pub const WINHTTP_QUERY_UPGRADE: ::DWORD = 64; +pub const WINHTTP_QUERY_VARY: ::DWORD = 65; +pub const WINHTTP_QUERY_VIA: ::DWORD = 66; +pub const WINHTTP_QUERY_WARNING: ::DWORD = 67; +pub const WINHTTP_QUERY_EXPECT: ::DWORD = 68; +pub const WINHTTP_QUERY_PROXY_CONNECTION: ::DWORD = 69; +pub const WINHTTP_QUERY_UNLESS_MODIFIED_SINCE: ::DWORD = 70; +pub const WINHTTP_QUERY_PROXY_SUPPORT: ::DWORD = 75; +pub const WINHTTP_QUERY_AUTHENTICATION_INFO: ::DWORD = 76; +pub const WINHTTP_QUERY_PASSPORT_URLS: ::DWORD = 77; +pub const WINHTTP_QUERY_PASSPORT_CONFIG: ::DWORD = 78; +pub const WINHTTP_QUERY_MAX: ::DWORD = 78; +pub const WINHTTP_QUERY_CUSTOM: ::DWORD = 65535; +pub const WINHTTP_QUERY_FLAG_REQUEST_HEADERS: ::DWORD = 0x80000000; +pub const WINHTTP_QUERY_FLAG_SYSTEMTIME: ::DWORD = 0x40000000; +pub const WINHTTP_QUERY_FLAG_NUMBER: ::DWORD = 0x20000000; +pub const HTTP_STATUS_CONTINUE: ::DWORD = 100; +pub const HTTP_STATUS_SWITCH_PROTOCOLS: ::DWORD = 101; +pub const HTTP_STATUS_OK: ::DWORD = 200; +pub const HTTP_STATUS_CREATED: ::DWORD = 201; +pub const HTTP_STATUS_ACCEPTED: ::DWORD = 202; +pub const HTTP_STATUS_PARTIAL: ::DWORD = 203; +pub const HTTP_STATUS_NO_CONTENT: ::DWORD = 204; +pub const HTTP_STATUS_RESET_CONTENT: ::DWORD = 205; +pub const HTTP_STATUS_PARTIAL_CONTENT: ::DWORD = 206; +pub const HTTP_STATUS_WEBDAV_MULTI_STATUS: ::DWORD = 207; +pub const HTTP_STATUS_AMBIGUOUS: ::DWORD = 300; +pub const HTTP_STATUS_MOVED: ::DWORD = 301; +pub const HTTP_STATUS_REDIRECT: ::DWORD = 302; +pub const HTTP_STATUS_REDIRECT_METHOD: ::DWORD = 303; +pub const HTTP_STATUS_NOT_MODIFIED: ::DWORD = 304; +pub const HTTP_STATUS_USE_PROXY: ::DWORD = 305; +pub const HTTP_STATUS_REDIRECT_KEEP_VERB: ::DWORD = 307; +pub const HTTP_STATUS_BAD_REQUEST: ::DWORD = 400; +pub const HTTP_STATUS_DENIED: ::DWORD = 401; +pub const HTTP_STATUS_PAYMENT_REQ: ::DWORD = 402; +pub const HTTP_STATUS_FORBIDDEN: ::DWORD = 403; +pub const HTTP_STATUS_NOT_FOUND: ::DWORD = 404; +pub const HTTP_STATUS_BAD_METHOD: ::DWORD = 405; +pub const HTTP_STATUS_NONE_ACCEPTABLE: ::DWORD = 406; +pub const HTTP_STATUS_PROXY_AUTH_REQ: ::DWORD = 407; +pub const HTTP_STATUS_REQUEST_TIMEOUT: ::DWORD = 408; +pub const HTTP_STATUS_CONFLICT: ::DWORD = 409; +pub const HTTP_STATUS_GONE: ::DWORD = 410; +pub const HTTP_STATUS_LENGTH_REQUIRED: ::DWORD = 411; +pub const HTTP_STATUS_PRECOND_FAILED: ::DWORD = 412; +pub const HTTP_STATUS_REQUEST_TOO_LARGE: ::DWORD = 413; +pub const HTTP_STATUS_URI_TOO_LONG: ::DWORD = 414; +pub const HTTP_STATUS_UNSUPPORTED_MEDIA: ::DWORD = 415; +pub const HTTP_STATUS_RETRY_WITH: ::DWORD = 449; +pub const HTTP_STATUS_SERVER_ERROR: ::DWORD = 500; +pub const HTTP_STATUS_NOT_SUPPORTED: ::DWORD = 501; +pub const HTTP_STATUS_BAD_GATEWAY: ::DWORD = 502; +pub const HTTP_STATUS_SERVICE_UNAVAIL: ::DWORD = 503; +pub const HTTP_STATUS_GATEWAY_TIMEOUT: ::DWORD = 504; +pub const HTTP_STATUS_VERSION_NOT_SUP: ::DWORD = 505; +pub const HTTP_STATUS_FIRST: ::DWORD = HTTP_STATUS_CONTINUE; +pub const HTTP_STATUS_LAST: ::DWORD = HTTP_STATUS_VERSION_NOT_SUP; +pub const WINHTTP_ACCESS_TYPE_DEFAULT_PROXY: ::DWORD = 0; +pub const WINHTTP_ACCESS_TYPE_NO_PROXY: ::DWORD = 1; +pub const WINHTTP_ACCESS_TYPE_NAMED_PROXY: ::DWORD = 3; +pub const WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY: ::DWORD = 4; +pub const WINHTTP_ERROR_BASE: ::DWORD = 12000; +pub const ERROR_WINHTTP_OUT_OF_HANDLES: ::DWORD = WINHTTP_ERROR_BASE + 1; +pub const ERROR_WINHTTP_TIMEOUT: ::DWORD = WINHTTP_ERROR_BASE + 2; +pub const ERROR_WINHTTP_INTERNAL_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 4; +pub const ERROR_WINHTTP_INVALID_URL: ::DWORD = WINHTTP_ERROR_BASE + 5; +pub const ERROR_WINHTTP_UNRECOGNIZED_SCHEME: ::DWORD = WINHTTP_ERROR_BASE + 6; +pub const ERROR_WINHTTP_NAME_NOT_RESOLVED: ::DWORD = WINHTTP_ERROR_BASE + 7; +pub const ERROR_WINHTTP_INVALID_OPTION: ::DWORD = WINHTTP_ERROR_BASE + 9; +pub const ERROR_WINHTTP_OPTION_NOT_SETTABLE: ::DWORD = WINHTTP_ERROR_BASE + 11; +pub const ERROR_WINHTTP_SHUTDOWN: ::DWORD = WINHTTP_ERROR_BASE + 12; +pub const ERROR_WINHTTP_LOGIN_FAILURE: ::DWORD = WINHTTP_ERROR_BASE + 15; +pub const ERROR_WINHTTP_OPERATION_CANCELLED: ::DWORD = WINHTTP_ERROR_BASE + 17; +pub const ERROR_WINHTTP_INCORRECT_HANDLE_TYPE: ::DWORD = WINHTTP_ERROR_BASE + 18; +pub const ERROR_WINHTTP_INCORRECT_HANDLE_STATE: ::DWORD = WINHTTP_ERROR_BASE + 19; +pub const ERROR_WINHTTP_CANNOT_CONNECT: ::DWORD = WINHTTP_ERROR_BASE + 29; +pub const ERROR_WINHTTP_CONNECTION_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 30; +pub const ERROR_WINHTTP_RESEND_REQUEST: ::DWORD = WINHTTP_ERROR_BASE + 32; +pub const ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: ::DWORD = WINHTTP_ERROR_BASE + 44; +pub const ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN: ::DWORD = WINHTTP_ERROR_BASE + 100; +pub const ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND: ::DWORD = WINHTTP_ERROR_BASE + 101; +pub const ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND: ::DWORD = WINHTTP_ERROR_BASE + 102; +pub const ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN: ::DWORD = WINHTTP_ERROR_BASE + 103; +pub const ERROR_WINHTTP_HEADER_NOT_FOUND: ::DWORD = WINHTTP_ERROR_BASE + 150; +pub const ERROR_WINHTTP_INVALID_SERVER_RESPONSE: ::DWORD = WINHTTP_ERROR_BASE + 152; +pub const ERROR_WINHTTP_INVALID_HEADER: ::DWORD = WINHTTP_ERROR_BASE + 153; +pub const ERROR_WINHTTP_INVALID_QUERY_REQUEST: ::DWORD = WINHTTP_ERROR_BASE + 154; +pub const ERROR_WINHTTP_HEADER_ALREADY_EXISTS: ::DWORD = WINHTTP_ERROR_BASE + 155; +pub const ERROR_WINHTTP_REDIRECT_FAILED: ::DWORD = WINHTTP_ERROR_BASE + 156; +pub const ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 178; +pub const ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT: ::DWORD = WINHTTP_ERROR_BASE + 166; +pub const ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: ::DWORD = WINHTTP_ERROR_BASE + 167; +pub const ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE: ::DWORD = WINHTTP_ERROR_BASE + 176; +pub const ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 177; +pub const ERROR_WINHTTP_NOT_INITIALIZED: ::DWORD = WINHTTP_ERROR_BASE + 172; +pub const ERROR_WINHTTP_SECURE_FAILURE: ::DWORD = WINHTTP_ERROR_BASE + 175; +pub const ERROR_WINHTTP_SECURE_CERT_DATE_INVALID: ::DWORD = WINHTTP_ERROR_BASE + 37; +pub const ERROR_WINHTTP_SECURE_CERT_CN_INVALID: ::DWORD = WINHTTP_ERROR_BASE + 38; +pub const ERROR_WINHTTP_SECURE_INVALID_CA: ::DWORD = WINHTTP_ERROR_BASE + 45; +pub const ERROR_WINHTTP_SECURE_CERT_REV_FAILED: ::DWORD = WINHTTP_ERROR_BASE + 57; +pub const ERROR_WINHTTP_SECURE_CHANNEL_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 157; +pub const ERROR_WINHTTP_SECURE_INVALID_CERT: ::DWORD = WINHTTP_ERROR_BASE + 169; +pub const ERROR_WINHTTP_SECURE_CERT_REVOKED: ::DWORD = WINHTTP_ERROR_BASE + 170; +pub const ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE: ::DWORD = WINHTTP_ERROR_BASE + 179; +pub const ERROR_WINHTTP_AUTODETECTION_FAILED: ::DWORD = WINHTTP_ERROR_BASE + 180; +pub const ERROR_WINHTTP_HEADER_COUNT_EXCEEDED: ::DWORD = WINHTTP_ERROR_BASE + 181; +pub const ERROR_WINHTTP_HEADER_SIZE_OVERFLOW: ::DWORD = WINHTTP_ERROR_BASE + 182; +pub const ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW: ::DWORD = WINHTTP_ERROR_BASE + 183; +pub const ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW: ::DWORD = WINHTTP_ERROR_BASE + 184; +pub const ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY: ::DWORD = WINHTTP_ERROR_BASE + 185; +pub const ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY: ::DWORD = WINHTTP_ERROR_BASE + 186; +pub const WINHTTP_ERROR_LAST: ::DWORD = WINHTTP_ERROR_BASE + 186; +pub const WINHTTP_RESET_STATE: ::DWORD = 0x00000001; +pub const WINHTTP_RESET_SWPAD_CURRENT_NETWORK: ::DWORD = 0x00000002; +pub const WINHTTP_RESET_SWPAD_ALL: ::DWORD = 0x00000004; +pub const WINHTTP_RESET_SCRIPT_CACHE: ::DWORD = 0x00000008; +pub const WINHTTP_RESET_ALL: ::DWORD = 0x0000FFFF; +pub const WINHTTP_RESET_NOTIFY_NETWORK_CHANGED: ::DWORD = 0x00010000; +pub const WINHTTP_RESET_OUT_OF_PROC: ::DWORD = 0x00020000; +STRUCT!{struct WINHTTP_CURRENT_USER_IE_PROXY_CONFIG { + fAutoDetect: ::BOOL, + lpszAutoConfigUrl: ::LPWSTR, + lpszProxy: ::LPWSTR, + lpszProxyBypass: ::LPWSTR, +}} +//1370 +ENUM!{enum WINHTTP_WEB_SOCKET_OPERATION { + WINHTTP_WEB_SOCKET_SEND_OPERATION = 0, + WINHTTP_WEB_SOCKET_RECEIVE_OPERATION = 1, + WINHTTP_WEB_SOCKET_CLOSE_OPERATION = 2, + WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION = 3, +}} +ENUM!{enum WINHTTP_WEB_SOCKET_BUFFER_TYPE { + WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE = 0, + WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE = 1, + WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE = 2, + WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE = 3, + WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE = 4, +}} +ENUM!{enum WINHTTP_WEB_SOCKET_CLOSE_STATUS { + WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS = 1000, + WINHTTP_WEB_SOCKET_ENDPOINT_TERMINATED_CLOSE_STATUS = 1001, + WINHTTP_WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS = 1002, + WINHTTP_WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS = 1003, + WINHTTP_WEB_SOCKET_EMPTY_CLOSE_STATUS = 1005, + WINHTTP_WEB_SOCKET_ABORTED_CLOSE_STATUS = 1006, + WINHTTP_WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS = 1007, + WINHTTP_WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS = 1008, + WINHTTP_WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS = 1009, + WINHTTP_WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS = 1010, + WINHTTP_WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS = 1011, + WINHTTP_WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS = 1015, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winioctl.rs b/bash-5.1/vendor/winapi-0.2.8/src/winioctl.rs new file mode 100644 index 0000000..de3b961 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winioctl.rs @@ -0,0 +1,754 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This module defines the 32-Bit Windows Device I/O control codes. +//123 +pub const FILE_DEVICE_BEEP: ::DWORD = 0x00000001; +pub const FILE_DEVICE_CD_ROM: ::DWORD = 0x00000002; +pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM: ::DWORD = 0x00000003; +pub const FILE_DEVICE_CONTROLLER: ::DWORD = 0x00000004; +pub const FILE_DEVICE_DATALINK: ::DWORD = 0x00000005; +pub const FILE_DEVICE_DFS: ::DWORD = 0x00000006; +pub const FILE_DEVICE_DISK: ::DWORD = 0x00000007; +pub const FILE_DEVICE_DISK_FILE_SYSTEM: ::DWORD = 0x00000008; +pub const FILE_DEVICE_FILE_SYSTEM: ::DWORD = 0x00000009; +pub const FILE_DEVICE_INPORT_PORT: ::DWORD = 0x0000000a; +pub const FILE_DEVICE_KEYBOARD: ::DWORD = 0x0000000b; +pub const FILE_DEVICE_MAILSLOT: ::DWORD = 0x0000000c; +pub const FILE_DEVICE_MIDI_IN: ::DWORD = 0x0000000d; +pub const FILE_DEVICE_MIDI_OUT: ::DWORD = 0x0000000e; +pub const FILE_DEVICE_MOUSE: ::DWORD = 0x0000000f; +pub const FILE_DEVICE_MULTI_UNC_PROVIDER: ::DWORD = 0x00000010; +pub const FILE_DEVICE_NAMED_PIPE: ::DWORD = 0x00000011; +pub const FILE_DEVICE_NETWORK: ::DWORD = 0x00000012; +pub const FILE_DEVICE_NETWORK_BROWSER: ::DWORD = 0x00000013; +pub const FILE_DEVICE_NETWORK_FILE_SYSTEM: ::DWORD = 0x00000014; +pub const FILE_DEVICE_NULL: ::DWORD = 0x00000015; +pub const FILE_DEVICE_PARALLEL_PORT: ::DWORD = 0x00000016; +pub const FILE_DEVICE_PHYSICAL_NETCARD: ::DWORD = 0x00000017; +pub const FILE_DEVICE_PRINTER: ::DWORD = 0x00000018; +pub const FILE_DEVICE_SCANNER: ::DWORD = 0x00000019; +pub const FILE_DEVICE_SERIAL_MOUSE_PORT: ::DWORD = 0x0000001a; +pub const FILE_DEVICE_SERIAL_PORT: ::DWORD = 0x0000001b; +pub const FILE_DEVICE_SCREEN: ::DWORD = 0x0000001c; +pub const FILE_DEVICE_SOUND: ::DWORD = 0x0000001d; +pub const FILE_DEVICE_STREAMS: ::DWORD = 0x0000001e; +pub const FILE_DEVICE_TAPE: ::DWORD = 0x0000001f; +pub const FILE_DEVICE_TAPE_FILE_SYSTEM: ::DWORD = 0x00000020; +pub const FILE_DEVICE_TRANSPORT: ::DWORD = 0x00000021; +pub const FILE_DEVICE_UNKNOWN: ::DWORD = 0x00000022; +pub const FILE_DEVICE_VIDEO: ::DWORD = 0x00000023; +pub const FILE_DEVICE_VIRTUAL_DISK: ::DWORD = 0x00000024; +pub const FILE_DEVICE_WAVE_IN: ::DWORD = 0x00000025; +pub const FILE_DEVICE_WAVE_OUT: ::DWORD = 0x00000026; +pub const FILE_DEVICE_8042_PORT: ::DWORD = 0x00000027; +pub const FILE_DEVICE_NETWORK_REDIRECTOR: ::DWORD = 0x00000028; +pub const FILE_DEVICE_BATTERY: ::DWORD = 0x00000029; +pub const FILE_DEVICE_BUS_EXTENDER: ::DWORD = 0x0000002a; +pub const FILE_DEVICE_MODEM: ::DWORD = 0x0000002b; +pub const FILE_DEVICE_VDM: ::DWORD = 0x0000002c; +pub const FILE_DEVICE_MASS_STORAGE: ::DWORD = 0x0000002d; +pub const FILE_DEVICE_SMB: ::DWORD = 0x0000002e; +pub const FILE_DEVICE_KS: ::DWORD = 0x0000002f; +pub const FILE_DEVICE_CHANGER: ::DWORD = 0x00000030; +pub const FILE_DEVICE_SMARTCARD: ::DWORD = 0x00000031; +pub const FILE_DEVICE_ACPI: ::DWORD = 0x00000032; +pub const FILE_DEVICE_DVD: ::DWORD = 0x00000033; +pub const FILE_DEVICE_FULLSCREEN_VIDEO: ::DWORD = 0x00000034; +pub const FILE_DEVICE_DFS_FILE_SYSTEM: ::DWORD = 0x00000035; +pub const FILE_DEVICE_DFS_VOLUME: ::DWORD = 0x00000036; +pub const FILE_DEVICE_SERENUM: ::DWORD = 0x00000037; +pub const FILE_DEVICE_TERMSRV: ::DWORD = 0x00000038; +pub const FILE_DEVICE_KSEC: ::DWORD = 0x00000039; +pub const FILE_DEVICE_FIPS: ::DWORD = 0x0000003A; +pub const FILE_DEVICE_INFINIBAND: ::DWORD = 0x0000003B; +pub const FILE_DEVICE_VMBUS: ::DWORD = 0x0000003E; +pub const FILE_DEVICE_CRYPT_PROVIDER: ::DWORD = 0x0000003F; +pub const FILE_DEVICE_WPD: ::DWORD = 0x00000040; +pub const FILE_DEVICE_BLUETOOTH: ::DWORD = 0x00000041; +pub const FILE_DEVICE_MT_COMPOSITE: ::DWORD = 0x00000042; +pub const FILE_DEVICE_MT_TRANSPORT: ::DWORD = 0x00000043; +pub const FILE_DEVICE_BIOMETRIC: ::DWORD = 0x00000044; +pub const FILE_DEVICE_PMI: ::DWORD = 0x00000045; +pub const FILE_DEVICE_EHSTOR: ::DWORD = 0x00000046; +pub const FILE_DEVICE_DEVAPI: ::DWORD = 0x00000047; +pub const FILE_DEVICE_GPIO: ::DWORD = 0x00000048; +pub const FILE_DEVICE_USBEX: ::DWORD = 0x00000049; +pub const FILE_DEVICE_CONSOLE: ::DWORD = 0x00000050; +pub const FILE_DEVICE_NFP: ::DWORD = 0x00000051; +pub const FILE_DEVICE_SYSENV: ::DWORD = 0x00000052; +pub const FILE_DEVICE_VIRTUAL_BLOCK: ::DWORD = 0x00000053; +pub const FILE_DEVICE_POINT_OF_SERVICE: ::DWORD = 0x00000054; +//224 +pub const METHOD_BUFFERED: ::DWORD = 0; +pub const METHOD_IN_DIRECT: ::DWORD = 1; +pub const METHOD_OUT_DIRECT: ::DWORD = 2; +pub const METHOD_NEITHER: ::DWORD = 3; +//253 +pub const FILE_ANY_ACCESS: ::DWORD = 0; +pub const FILE_SPECIAL_ACCESS: ::DWORD = FILE_ANY_ACCESS; +pub const FILE_READ_ACCESS: ::DWORD = 0x0001; +pub const FILE_WRITE_ACCESS: ::DWORD = 0x0002; +//281 +pub const IOCTL_STORAGE_BASE: ::DWORD = FILE_DEVICE_MASS_STORAGE; +pub const IOCTL_STORAGE_CHECK_VERIFY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0200, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_CHECK_VERIFY2: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0200, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_MEDIA_REMOVAL: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0201, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_EJECT_MEDIA: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0202, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_LOAD_MEDIA: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0203, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_LOAD_MEDIA2: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0203, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_RESERVE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0204, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_STORAGE_RELEASE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0205, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_STORAGE_FIND_NEW_DEVICES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0206, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_EJECTION_CONTROL: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0250, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_MCN_CONTROL: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0251, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_MEDIA_TYPES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0300, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_MEDIA_TYPES_EX: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0301, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0304, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_HOTPLUG_INFO: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0305, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_SET_HOTPLUG_INFO: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0306, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_RESET_BUS: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0400, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_STORAGE_RESET_DEVICE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0401, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_BREAK_RESERVATION: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0405, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_PERSISTENT_RESERVE_IN: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0406, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_PERSISTENT_RESERVE_OUT: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0407, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_GET_DEVICE_NUMBER: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0420, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_PREDICT_FAILURE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0440, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_FAILURE_PREDICTION_CONFIG: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0441, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_READ_CAPACITY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0450, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0470, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_DEVICE_TELEMETRY_NOTIFY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0471, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_DEVICE_TELEMETRY_QUERY_CAPS: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, + 0x0472, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY_RAW: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0473, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_QUERY_PROPERTY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0500, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0501, + METHOD_BUFFERED, FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_GET_LB_PROVISIONING_MAP_RESOURCES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, + 0x0502, METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_GET_BC_PROPERTIES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0600, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_ALLOCATE_BC_STREAM: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0601, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_FREE_BC_STREAM: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0602, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, + 0x0620, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_START_DATA_INTEGRITY_CHECK: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0621, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_STOP_DATA_INTEGRITY_CHECK: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0622, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const OBSOLETE_IOCTL_STORAGE_RESET_BUS: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0400, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const OBSOLETE_IOCTL_STORAGE_RESET_DEVICE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0401, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_ENABLE_IDLE_POWER: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0720, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_IDLE_POWERUP_REASON: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0721, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_POWER_ACTIVE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0722, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_POWER_IDLE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0723, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_EVENT_NOTIFICATION: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0724, + METHOD_BUFFERED, FILE_ANY_ACCESS); +//2627 +pub const IOCTL_DISK_BASE: ::DWORD = FILE_DEVICE_DISK; +pub const IOCTL_DISK_GET_DRIVE_GEOMETRY: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0000, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_GET_PARTITION_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0001, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_SET_PARTITION_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0002, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_DRIVE_LAYOUT: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0003, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_SET_DRIVE_LAYOUT: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0004, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_VERIFY: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0005, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_FORMAT_TRACKS: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0006, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_REASSIGN_BLOCKS: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0007, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_PERFORMANCE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0008, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_IS_WRITABLE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0009, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_LOGGING: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000a, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_FORMAT_TRACKS_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000b, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_HISTOGRAM_STRUCTURE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000c, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_HISTOGRAM_DATA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000d, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_HISTOGRAM_RESET: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000e, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_REQUEST_STRUCTURE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000f, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_REQUEST_DATA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0010, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_PERFORMANCE_OFF: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0018, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_CONTROLLER_NUMBER: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0011, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const SMART_GET_VERSION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const SMART_SEND_DRIVE_COMMAND: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0021, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const SMART_RCV_DRIVE_DATA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0022, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_PARTITION_INFO_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0012, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_SET_PARTITION_INFO_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0013, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_DRIVE_LAYOUT_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0014, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_SET_DRIVE_LAYOUT_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0015, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_CREATE_DISK: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0016, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_LENGTH_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0017, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0028, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_REASSIGN_BLOCKS_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0029, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_UPDATE_DRIVE_SIZE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0032, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GROW_PARTITION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0034, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_CACHE_INFORMATION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0035, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_SET_CACHE_INFORMATION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0036, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_WRITE_CACHE_STATE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0037, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const OBSOLETE_DISK_GET_WRITE_CACHE_STATE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0037, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_DELETE_DRIVE_LAYOUT: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0040, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_UPDATE_PROPERTIES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0050, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_FORMAT_DRIVE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x00f3, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_SENSE_DEVICE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x00f8, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_CHECK_VERIFY: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0200, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_MEDIA_REMOVAL: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0201, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_EJECT_MEDIA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0202, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_LOAD_MEDIA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0203, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_RESERVE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0204, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_RELEASE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0205, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_FIND_NEW_DEVICES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0206, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_GET_MEDIA_TYPES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0300, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_GET_DISK_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x003c, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_SET_DISK_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x003d, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_RESET_SNAPSHOT_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0084, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +//3907 +pub const IOCTL_CHANGER_BASE: ::DWORD = FILE_DEVICE_CHANGER; +pub const IOCTL_CHANGER_GET_PARAMETERS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0000, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_GET_STATUS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0001, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_GET_PRODUCT_DATA: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0002, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_SET_ACCESS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0004, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_CHANGER_GET_ELEMENT_STATUS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0005, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0006, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_SET_POSITION: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0007, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_EXCHANGE_MEDIUM: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0008, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_MOVE_MEDIUM: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0009, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_REINITIALIZE_TRANSPORT: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x000A, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_QUERY_VOLUME_TAGS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x000B, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_SERIAL_LSRMST_INSERT: ::DWORD = CTL_CODE!(FILE_DEVICE_SERIAL_PORT, 31, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_EXPOSE_HARDWARE: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 128, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_REMOVE_HARDWARE: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 129, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_PORT_DESC: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 130, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_GET_PORT_NAME: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 131, + METHOD_BUFFERED,FILE_ANY_ACCESS); +//4690 +pub const FSCTL_REQUEST_OPLOCK_LEVEL_1: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 0, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_OPLOCK_LEVEL_2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 1, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_BATCH_OPLOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 2, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OPLOCK_BREAK_ACKNOWLEDGE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 3, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OPBATCH_ACK_CLOSE_PENDING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 4, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OPLOCK_BREAK_NOTIFY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 5, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_LOCK_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_UNLOCK_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_DISMOUNT_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_IS_VOLUME_MOUNTED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 10, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_IS_PATHNAME_VALID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 11, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_MARK_VOLUME_DIRTY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 12, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_RETRIEVAL_POINTERS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 14, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_GET_COMPRESSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 15, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SET_COMPRESSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 16, METHOD_BUFFERED, + ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_SET_BOOTLOADER_ACCESSED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 19, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_MARK_AS_SYSTEM_HIVE: ::DWORD = FSCTL_SET_BOOTLOADER_ACCESSED; +pub const FSCTL_OPLOCK_BREAK_ACK_NO_2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 20, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_INVALIDATE_VOLUMES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 21, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_FAT_BPB: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 22, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_FILTER_OPLOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 23, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_FILESYSTEM_GET_STATISTICS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 24, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_NTFS_VOLUME_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 25, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_NTFS_FILE_RECORD: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 26, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_VOLUME_BITMAP: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 27, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_GET_RETRIEVAL_POINTERS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 28, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_MOVE_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 29, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_IS_VOLUME_DIRTY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 30, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_ALLOW_EXTENDED_DASD_IO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 32, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_FIND_FILES_BY_SID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 35, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SET_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 38, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_GET_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 39, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_DELETE_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 40, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_REPARSE_POINT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 41, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_GET_REPARSE_POINT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 42, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DELETE_REPARSE_POINT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 43, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_ENUM_USN_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 44, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_SECURITY_ID_CHECK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 45, METHOD_NEITHER, + ::FILE_READ_DATA); +pub const FSCTL_READ_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 46, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SET_OBJECT_ID_EXTENDED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 47, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_CREATE_OR_GET_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 48, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_SPARSE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 49, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_ZERO_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 50, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_QUERY_ALLOCATED_RANGES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 51, + METHOD_NEITHER, ::FILE_READ_DATA); +pub const FSCTL_ENABLE_UPGRADE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 52, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_SET_ENCRYPTION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 53, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_ENCRYPTION_FSCTL_IO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 54, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_WRITE_RAW_ENCRYPTED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 55, + METHOD_NEITHER, FILE_SPECIAL_ACCESS); +pub const FSCTL_READ_RAW_ENCRYPTED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 56, + METHOD_NEITHER, FILE_SPECIAL_ACCESS); +pub const FSCTL_CREATE_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 57, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_READ_FILE_USN_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 58, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_WRITE_USN_CLOSE_RECORD: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 59, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_EXTEND_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 60, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_QUERY_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 61, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DELETE_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 62, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_MARK_HANDLE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 63, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SIS_COPYFILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 64, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SIS_LINK_FILES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 65, METHOD_BUFFERED, + ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_RECALL_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 69, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_READ_FROM_PLEX: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 71, METHOD_OUT_DIRECT, + ::FILE_READ_DATA); +pub const FSCTL_FILE_PREFETCH: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 72, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_MAKE_MEDIA_COMPATIBLE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 76, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_SET_DEFECT_MANAGEMENT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 77, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_QUERY_SPARING_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 78, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_ON_DISK_VOLUME_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 79, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_VOLUME_COMPRESSION_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 80, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_TXFS_MODIFY_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 81, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_QUERY_RM_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 82, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_ROLLFORWARD_REDO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 84, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_ROLLFORWARD_UNDO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 85, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_START_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 86, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_SHUTDOWN_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 87, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_READ_BACKUP_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 88, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 89, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_CREATE_SECONDARY_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 90, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_GET_METADATA_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 91, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_GET_TRANSACTED_VERSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 92, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_SAVEPOINT_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 94, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_CREATE_MINIVERSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 95, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_TRANSACTION_ACTIVE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 99, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_SET_ZERO_ON_DEALLOCATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 101, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 102, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_GET_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 103, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_WAIT_FOR_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 104, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_INITIATE_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 106, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSC_INTERNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 107, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SHRINK_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 108, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_SHORT_NAME_BEHAVIOR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 109, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DFSR_SET_GHOST_HANDLE_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 110, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, + 120, METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_LIST_TRANSACTIONS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 121, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_QUERY_PAGEFILE_ENCRYPTION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 122, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_RESET_VOLUME_ALLOCATION_HINTS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 123, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_DEPENDENT_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 124, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SD_GLOBAL_CHANGE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 125, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_TXFS_READ_BACKUP_INFORMATION2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 126, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_LOOKUP_STREAM_FROM_CLUSTER: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 127, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 128, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_FILE_TYPE_NOTIFICATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 129, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_FILE_LEVEL_TRIM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 130, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_GET_BOOT_AREA_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 140, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_RETRIEVAL_POINTER_BASE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 141, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_PERSISTENT_VOLUME_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 142, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_PERSISTENT_VOLUME_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 143, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_OPLOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 144, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSV_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 145, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_IS_CSV_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 146, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_QUERY_FILE_SYSTEM_RECOGNITION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 147, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_GET_VOLUME_PATH_NAME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 148, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_GET_VOLUME_NAME_FOR_VOLUME_MOUNT_POINT: ::DWORD = CTL_CODE!( + FILE_DEVICE_FILE_SYSTEM, 149, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_GET_VOLUME_PATH_NAMES_FOR_VOLUME_NAME: ::DWORD = CTL_CODE!( + FILE_DEVICE_FILE_SYSTEM, 150, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_IS_FILE_ON_CSV_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 151, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CORRUPTION_HANDLING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 152, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OFFLOAD_READ: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 153, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const FSCTL_OFFLOAD_WRITE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 154, METHOD_BUFFERED, + FILE_WRITE_ACCESS); +pub const FSCTL_CSV_INTERNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 155, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SET_PURGE_FAILURE_MODE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 156, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_FILE_LAYOUT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 157, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_IS_VOLUME_OWNED_BYCSVFS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 158, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_INTEGRITY_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 159, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_INTEGRITY_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 160, + METHOD_BUFFERED, ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_QUERY_FILE_REGIONS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 161, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DEDUP_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 165, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_DEDUP_QUERY_FILE_HASHES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 166, + METHOD_NEITHER, ::FILE_READ_DATA); +pub const FSCTL_DEDUP_QUERY_RANGE_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 167, + METHOD_NEITHER, ::FILE_READ_DATA); +pub const FSCTL_DEDUP_QUERY_REPARSE_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 168, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_RKF_INTERNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 171, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SCRUB_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 172, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_REPAIR_COPIES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 173, METHOD_BUFFERED, + ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_DISABLE_LOCAL_BUFFERING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 174, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_MGMT_LOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 175, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSV_QUERY_DOWN_LEVEL_FILE_SYSTEM_CHARACTERISTICS: ::DWORD = CTL_CODE!( + FILE_DEVICE_FILE_SYSTEM, 176, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_ADVANCE_FILE_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 177, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSV_SYNC_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 178, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_QUERY_VETO_FILE_DIRECT_IO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 179, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_WRITE_USN_REASON: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 180, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_CONTROL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 181, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_GET_REFS_VOLUME_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 182, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_H_BREAKING_SYNC_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, + 185, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_STORAGE_CLASSES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 187, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_REGION_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 188, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_USN_TRACK_MODIFIED_RANGES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 189, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, + 192, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SVHDX_SYNC_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 193, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SVHDX_SET_INITIATOR_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 194, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 195, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_GET_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 196, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DELETE_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 197, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_ENUM_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 198, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_ENUM_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 199, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_ADD_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 204, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_REMOVE_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 205, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_UPDATE_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 206, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +// FILE_DEVICE_AVIO is defined nowhere +//pub const IOCTL_AVIO_ALLOCATE_STREAM: ::DWORD = CTL_CODE!(FILE_DEVICE_AVIO, 1, METHOD_BUFFERED, +// FILE_SPECIAL_ACCESS); +//pub const IOCTL_AVIO_FREE_STREAM: ::DWORD = CTL_CODE!(FILE_DEVICE_AVIO, 2, METHOD_BUFFERED, +// FILE_SPECIAL_ACCESS); +//pub const IOCTL_AVIO_MODIFY_STREAM: ::DWORD = CTL_CODE!(FILE_DEVICE_AVIO, 3, METHOD_BUFFERED, +// FILE_SPECIAL_ACCESS); +STRUCT!{struct PATHNAME_BUFFER { + PathNameLength: ::DWORD, + Name: [::WCHAR; 1], +}} +pub type PPATHNAME_BUFFER = *mut PATHNAME_BUFFER; +STRUCT!{nodebug struct FSCTL_QUERY_FAT_BPB_BUFFER { + First0x24BytesOfBootSector: [::BYTE; 0x24], +}} +pub type PFSCTL_QUERY_FAT_BPB_BUFFER = *mut FSCTL_QUERY_FAT_BPB_BUFFER; +STRUCT!{struct NTFS_VOLUME_DATA_BUFFER { + VolumeSerialNumber: ::LARGE_INTEGER, + NumberSectors: ::LARGE_INTEGER, + TotalClusters: ::LARGE_INTEGER, + FreeClusters: ::LARGE_INTEGER, + TotalReserved: ::LARGE_INTEGER, + BytesPerSector: ::DWORD, + BytesPerCluster: ::DWORD, + BytesPerFileRecordSegment: ::DWORD, + ClustersPerFileRecordSegment: ::DWORD, + MftValidDataLength: ::LARGE_INTEGER, + MftStartLcn: ::LARGE_INTEGER, + Mft2StartLcn: ::LARGE_INTEGER, + MftZoneStart: ::LARGE_INTEGER, + MftZoneEnd: ::LARGE_INTEGER, +}} +pub type PNTFS_VOLUME_DATA_BUFFER = *mut NTFS_VOLUME_DATA_BUFFER; +STRUCT!{struct NTFS_EXTENDED_VOLUME_DATA { + ByteCount: ::DWORD, + MajorVersion: ::WORD, + MinorVersion: ::WORD, + BytesPerPhysicalSector: ::DWORD, + LfsMajorVersion: ::WORD, + LfsMinorVersion: ::WORD, +}} +pub type PNTFS_EXTENDED_VOLUME_DATA = *mut NTFS_EXTENDED_VOLUME_DATA; +STRUCT!{struct REFS_VOLUME_DATA_BUFFER { + ByteCount: ::DWORD, + MajorVersion: ::DWORD, + MinorVersion: ::DWORD, + BytesPerPhysicalSector: ::DWORD, + VolumeSerialNumber: ::LARGE_INTEGER, + NumberSectors: ::LARGE_INTEGER, + TotalClusters: ::LARGE_INTEGER, + FreeClusters: ::LARGE_INTEGER, + TotalReserved: ::LARGE_INTEGER, + BytesPerSector: ::DWORD, + BytesPerCluster: ::DWORD, + MaximumSizeOfResidentFile: ::LARGE_INTEGER, + Reserved: [::LARGE_INTEGER; 10], +}} +pub type PREFS_VOLUME_DATA_BUFFER = *mut REFS_VOLUME_DATA_BUFFER; +STRUCT!{struct STARTING_LCN_INPUT_BUFFER { + StartingLcn: ::LARGE_INTEGER, +}} +pub type PSTARTING_LCN_INPUT_BUFFER = *mut STARTING_LCN_INPUT_BUFFER; +STRUCT!{struct VOLUME_BITMAP_BUFFER { + StartingLcn: ::LARGE_INTEGER, + BitmapSize: ::LARGE_INTEGER, + Buffer: [::BYTE; 1], +}} +pub type PVOLUME_BITMAP_BUFFER = *mut VOLUME_BITMAP_BUFFER; +STRUCT!{struct STARTING_VCN_INPUT_BUFFER { + StartingVcn: ::LARGE_INTEGER, +}} +pub type PSTARTING_VCN_INPUT_BUFFER = *mut STARTING_VCN_INPUT_BUFFER; +STRUCT!{struct RETRIEVAL_POINTERS_BUFFER_INTERNAL { + NextVcn: ::LARGE_INTEGER, + Lcn: ::LARGE_INTEGER, +}} +STRUCT!{struct RETRIEVAL_POINTERS_BUFFER { + ExtentCount: ::DWORD, + StartingVcn: ::LARGE_INTEGER, + Extents: [RETRIEVAL_POINTERS_BUFFER_INTERNAL; 1], +}} +pub type PRETRIEVAL_POINTERS_BUFFER = *mut RETRIEVAL_POINTERS_BUFFER; +STRUCT!{struct NTFS_FILE_RECORD_INPUT_BUFFER { + FileReferenceNumber: ::LARGE_INTEGER, +}} +pub type PNTFS_FILE_RECORD_INPUT_BUFFER = *mut NTFS_FILE_RECORD_INPUT_BUFFER; +STRUCT!{struct NTFS_FILE_RECORD_OUTPUT_BUFFER { + FileReferenceNumber: ::LARGE_INTEGER, + FileRecordLength: ::DWORD, + FileRecordBuffer: [::BYTE; 1], +}} +pub type PNTFS_FILE_RECORD_OUTPUT_BUFFER = *mut NTFS_FILE_RECORD_OUTPUT_BUFFER; +STRUCT!{struct MOVE_FILE_DATA { + FileHandle: ::HANDLE, + StartingVcn: ::LARGE_INTEGER, + StartingLcn: ::LARGE_INTEGER, + ClusterCount: ::DWORD, +}} +pub type PMOVE_FILE_DATA = *mut MOVE_FILE_DATA; +STRUCT!{struct MOVE_FILE_RECORD_DATA { + FileHandle: ::HANDLE, + SourceFileRecord: ::LARGE_INTEGER, + TargetFileRecord: ::LARGE_INTEGER, +}} +pub type PMOVE_FILE_RECORD_DATA = *mut MOVE_FILE_RECORD_DATA; +//9207 +pub const IOCTL_VOLUME_BASE: ::DWORD = 0x00000056; +pub const IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 0, + METHOD_BUFFERED, FILE_ANY_ACCESS); +STRUCT!{struct DISK_EXTENT { + DiskNumber: ::DWORD, + StartingOffset: ::LARGE_INTEGER, + ExtentLength: ::LARGE_INTEGER, +}} +pub type PDISK_EXTENT = *mut DISK_EXTENT; +STRUCT!{struct VOLUME_DISK_EXTENTS { + NumberOfDiskExtents: ::DWORD, + Extents: [DISK_EXTENT; ::ANYSIZE_ARRAY], +}} +pub type PVOLUME_DISK_EXTENTS = *mut VOLUME_DISK_EXTENTS; +pub const IOCTL_VOLUME_ONLINE: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 2, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_VOLUME_OFFLINE: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 3, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_VOLUME_IS_CLUSTERED: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 12, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_VOLUME_GET_GPT_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 14, + METHOD_BUFFERED, FILE_ANY_ACCESS); diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winnetwk.rs b/bash-5.1/vendor/winapi-0.2.8/src/winnetwk.rs new file mode 100644 index 0000000..665d283 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winnetwk.rs @@ -0,0 +1,275 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Standard WINNET Header File for WIN32 +pub const WNNC_NET_MSNET: ::DWORD = 0x00010000; +pub const WNNC_NET_SMB: ::DWORD = 0x00020000; +pub const WNNC_NET_NETWARE: ::DWORD = 0x00030000; +pub const WNNC_NET_VINES: ::DWORD = 0x00040000; +pub const WNNC_NET_10NET: ::DWORD = 0x00050000; +pub const WNNC_NET_LOCUS: ::DWORD = 0x00060000; +pub const WNNC_NET_SUN_PC_NFS: ::DWORD = 0x00070000; +pub const WNNC_NET_LANSTEP: ::DWORD = 0x00080000; +pub const WNNC_NET_9TILES: ::DWORD = 0x00090000; +pub const WNNC_NET_LANTASTIC: ::DWORD = 0x000A0000; +pub const WNNC_NET_AS400: ::DWORD = 0x000B0000; +pub const WNNC_NET_FTP_NFS: ::DWORD = 0x000C0000; +pub const WNNC_NET_PATHWORKS: ::DWORD = 0x000D0000; +pub const WNNC_NET_LIFENET: ::DWORD = 0x000E0000; +pub const WNNC_NET_POWERLAN: ::DWORD = 0x000F0000; +pub const WNNC_NET_BWNFS: ::DWORD = 0x00100000; +pub const WNNC_NET_COGENT: ::DWORD = 0x00110000; +pub const WNNC_NET_FARALLON: ::DWORD = 0x00120000; +pub const WNNC_NET_APPLETALK: ::DWORD = 0x00130000; +pub const WNNC_NET_INTERGRAPH: ::DWORD = 0x00140000; +pub const WNNC_NET_SYMFONET: ::DWORD = 0x00150000; +pub const WNNC_NET_CLEARCASE: ::DWORD = 0x00160000; +pub const WNNC_NET_FRONTIER: ::DWORD = 0x00170000; +pub const WNNC_NET_BMC: ::DWORD = 0x00180000; +pub const WNNC_NET_DCE: ::DWORD = 0x00190000; +pub const WNNC_NET_AVID: ::DWORD = 0x001A0000; +pub const WNNC_NET_DOCUSPACE: ::DWORD = 0x001B0000; +pub const WNNC_NET_MANGOSOFT: ::DWORD = 0x001C0000; +pub const WNNC_NET_SERNET: ::DWORD = 0x001D0000; +pub const WNNC_NET_RIVERFRONT1: ::DWORD = 0x001E0000; +pub const WNNC_NET_RIVERFRONT2: ::DWORD = 0x001F0000; +pub const WNNC_NET_DECORB: ::DWORD = 0x00200000; +pub const WNNC_NET_PROTSTOR: ::DWORD = 0x00210000; +pub const WNNC_NET_FJ_REDIR: ::DWORD = 0x00220000; +pub const WNNC_NET_DISTINCT: ::DWORD = 0x00230000; +pub const WNNC_NET_TWINS: ::DWORD = 0x00240000; +pub const WNNC_NET_RDR2SAMPLE: ::DWORD = 0x00250000; +pub const WNNC_NET_CSC: ::DWORD = 0x00260000; +pub const WNNC_NET_3IN1: ::DWORD = 0x00270000; +pub const WNNC_NET_EXTENDNET: ::DWORD = 0x00290000; +pub const WNNC_NET_STAC: ::DWORD = 0x002A0000; +pub const WNNC_NET_FOXBAT: ::DWORD = 0x002B0000; +pub const WNNC_NET_YAHOO: ::DWORD = 0x002C0000; +pub const WNNC_NET_EXIFS: ::DWORD = 0x002D0000; +pub const WNNC_NET_DAV: ::DWORD = 0x002E0000; +pub const WNNC_NET_KNOWARE: ::DWORD = 0x002F0000; +pub const WNNC_NET_OBJECT_DIRE: ::DWORD = 0x00300000; +pub const WNNC_NET_MASFAX: ::DWORD = 0x00310000; +pub const WNNC_NET_HOB_NFS: ::DWORD = 0x00320000; +pub const WNNC_NET_SHIVA: ::DWORD = 0x00330000; +pub const WNNC_NET_IBMAL: ::DWORD = 0x00340000; +pub const WNNC_NET_LOCK: ::DWORD = 0x00350000; +pub const WNNC_NET_TERMSRV: ::DWORD = 0x00360000; +pub const WNNC_NET_SRT: ::DWORD = 0x00370000; +pub const WNNC_NET_QUINCY: ::DWORD = 0x00380000; +pub const WNNC_NET_OPENAFS: ::DWORD = 0x00390000; +pub const WNNC_NET_AVID1: ::DWORD = 0x003A0000; +pub const WNNC_NET_DFS: ::DWORD = 0x003B0000; +pub const WNNC_NET_KWNP: ::DWORD = 0x003C0000; +pub const WNNC_NET_ZENWORKS: ::DWORD = 0x003D0000; +pub const WNNC_NET_DRIVEONWEB: ::DWORD = 0x003E0000; +pub const WNNC_NET_VMWARE: ::DWORD = 0x003F0000; +pub const WNNC_NET_RSFX: ::DWORD = 0x00400000; +pub const WNNC_NET_MFILES: ::DWORD = 0x00410000; +pub const WNNC_NET_MS_NFS: ::DWORD = 0x00420000; +pub const WNNC_NET_GOOGLE: ::DWORD = 0x00430000; +pub const WNNC_NET_NDFS: ::DWORD = 0x00440000; +pub const WNNC_NET_DOCUSHARE: ::DWORD = 0x00450000; +pub const WNNC_CRED_MANAGER: ::DWORD = 0xFFFF0000; +pub const WNNC_NET_LANMAN: ::DWORD = WNNC_NET_SMB; +pub const RESOURCE_CONNECTED: ::DWORD = 0x00000001; +pub const RESOURCE_GLOBALNET: ::DWORD = 0x00000002; +pub const RESOURCE_REMEMBERED: ::DWORD = 0x00000003; +pub const RESOURCE_RECENT: ::DWORD = 0x00000004; +pub const RESOURCE_CONTEXT: ::DWORD = 0x00000005; +pub const RESOURCETYPE_ANY: ::DWORD = 0x00000000; +pub const RESOURCETYPE_DISK: ::DWORD = 0x00000001; +pub const RESOURCETYPE_PRINT: ::DWORD = 0x00000002; +pub const RESOURCETYPE_RESERVED: ::DWORD = 0x00000008; +pub const RESOURCETYPE_UNKNOWN: ::DWORD = 0xFFFFFFFF; +pub const RESOURCEUSAGE_CONNECTABLE: ::DWORD = 0x00000001; +pub const RESOURCEUSAGE_CONTAINER: ::DWORD = 0x00000002; +pub const RESOURCEUSAGE_NOLOCALDEVICE: ::DWORD = 0x00000004; +pub const RESOURCEUSAGE_SIBLING: ::DWORD = 0x00000008; +pub const RESOURCEUSAGE_ATTACHED: ::DWORD = 0x00000010; +pub const RESOURCEUSAGE_ALL: ::DWORD = RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER + | RESOURCEUSAGE_ATTACHED; +pub const RESOURCEUSAGE_RESERVED: ::DWORD = 0x80000000; +pub const RESOURCEDISPLAYTYPE_GENERIC: ::DWORD = 0x00000000; +pub const RESOURCEDISPLAYTYPE_DOMAIN: ::DWORD = 0x00000001; +pub const RESOURCEDISPLAYTYPE_SERVER: ::DWORD = 0x00000002; +pub const RESOURCEDISPLAYTYPE_SHARE: ::DWORD = 0x00000003; +pub const RESOURCEDISPLAYTYPE_FILE: ::DWORD = 0x00000004; +pub const RESOURCEDISPLAYTYPE_GROUP: ::DWORD = 0x00000005; +pub const RESOURCEDISPLAYTYPE_NETWORK: ::DWORD = 0x00000006; +pub const RESOURCEDISPLAYTYPE_ROOT: ::DWORD = 0x00000007; +pub const RESOURCEDISPLAYTYPE_SHAREADMIN: ::DWORD = 0x00000008; +pub const RESOURCEDISPLAYTYPE_DIRECTORY: ::DWORD = 0x00000009; +pub const RESOURCEDISPLAYTYPE_TREE: ::DWORD = 0x0000000A; +pub const RESOURCEDISPLAYTYPE_NDSCONTAINER: ::DWORD = 0x0000000B; +STRUCT!{struct NETRESOURCEA { + dwScope: ::DWORD, + dwType: ::DWORD, + dwDisplayType: ::DWORD, + dwUsage: ::DWORD, + lpLocalName: ::LPSTR, + lpRemoteName: ::LPSTR, + lpComment: ::LPSTR, + lpProvider: ::LPSTR, +}} +pub type LPNETRESOURCEA = *mut NETRESOURCEA; +STRUCT!{struct NETRESOURCEW { + dwScope: ::DWORD, + dwType: ::DWORD, + dwDisplayType: ::DWORD, + dwUsage: ::DWORD, + lpLocalName: ::LPWSTR, + lpRemoteName: ::LPWSTR, + lpComment: ::LPWSTR, + lpProvider: ::LPWSTR, +}} +pub type LPNETRESOURCEW = *mut NETRESOURCEW; +pub const NETPROPERTY_PERSISTENT: ::DWORD = 1; +pub const CONNECT_UPDATE_PROFILE: ::DWORD = 0x00000001; +pub const CONNECT_UPDATE_RECENT: ::DWORD = 0x00000002; +pub const CONNECT_TEMPORARY: ::DWORD = 0x00000004; +pub const CONNECT_INTERACTIVE: ::DWORD = 0x00000008; +pub const CONNECT_PROMPT: ::DWORD = 0x00000010; +pub const CONNECT_NEED_DRIVE: ::DWORD = 0x00000020; +pub const CONNECT_REFCOUNT: ::DWORD = 0x00000040; +pub const CONNECT_REDIRECT: ::DWORD = 0x00000080; +pub const CONNECT_LOCALDRIVE: ::DWORD = 0x00000100; +pub const CONNECT_CURRENT_MEDIA: ::DWORD = 0x00000200; +pub const CONNECT_DEFERRED: ::DWORD = 0x00000400; +pub const CONNECT_RESERVED: ::DWORD = 0xFF000000; +pub const CONNECT_COMMANDLINE: ::DWORD = 0x00000800; +pub const CONNECT_CMD_SAVECRED: ::DWORD = 0x00001000; +pub const CONNECT_CRED_RESET: ::DWORD = 0x00002000; +STRUCT!{struct CONNECTDLGSTRUCTA { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpConnRes: ::LPNETRESOURCEA, + dwFlags: ::DWORD, + dwDevNum: ::DWORD, +}} +pub type LPCONNECTDLGSTRUCTA = *mut CONNECTDLGSTRUCTA; +STRUCT!{struct CONNECTDLGSTRUCTW { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpConnRes: ::LPNETRESOURCEW, + dwFlags: ::DWORD, + dwDevNum: ::DWORD, +}} +pub type LPCONNECTDLGSTRUCTW = *mut CONNECTDLGSTRUCTW; +pub const CONNDLG_RO_PATH: ::DWORD = 0x00000001; +pub const CONNDLG_CONN_POINT: ::DWORD = 0x00000002; +pub const CONNDLG_USE_MRU: ::DWORD = 0x00000004; +pub const CONNDLG_HIDE_BOX: ::DWORD = 0x00000008; +pub const CONNDLG_PERSIST: ::DWORD = 0x00000010; +pub const CONNDLG_NOT_PERSIST: ::DWORD = 0x00000020; +STRUCT!{struct DISCDLGSTRUCTA { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpLocalName: ::LPSTR, + lpRemoteName: ::LPSTR, + dwFlags: ::DWORD, +}} +pub type LPDISCDLGSTRUCTA = *mut DISCDLGSTRUCTA; +STRUCT!{struct DISCDLGSTRUCTW { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpLocalName: ::LPWSTR, + lpRemoteName: ::LPWSTR, + dwFlags: ::DWORD, +}} +pub type LPDISCDLGSTRUCTW = *mut DISCDLGSTRUCTW; +pub const DISC_UPDATE_PROFILE: ::DWORD = 0x00000001; +pub const DISC_NO_FORCE: ::DWORD = 0x00000040; +pub const UNIVERSAL_NAME_INFO_LEVEL: ::DWORD = 0x00000001; +pub const REMOTE_NAME_INFO_LEVEL: ::DWORD = 0x00000002; +STRUCT!{struct UNIVERSAL_NAME_INFOA { + lpUniversalName: ::LPSTR, +}} +pub type LPUNIVERSAL_NAME_INFOA = *mut UNIVERSAL_NAME_INFOA; +STRUCT!{struct UNIVERSAL_NAME_INFOW { + lpUniversalName: ::LPWSTR, +}} +pub type LPUNIVERSAL_NAME_INFOW = *mut UNIVERSAL_NAME_INFOW; +STRUCT!{struct REMOTE_NAME_INFOA { + lpUniversalName: ::LPSTR, + lpConnectionName: ::LPSTR, + lpRemainingPath: ::LPSTR, +}} +pub type LPREMOTE_NAME_INFOA = *mut REMOTE_NAME_INFOA; +STRUCT!{struct REMOTE_NAME_INFOW { + lpUniversalName: ::LPWSTR, + lpConnectionName: ::LPWSTR, + lpRemainingPath: ::LPWSTR, +}} +pub type LPREMOTE_NAME_INFOW = *mut REMOTE_NAME_INFOW; +pub const WNFMT_MULTILINE: ::DWORD = 0x01; +pub const WNFMT_ABBREVIATED: ::DWORD = 0x02; +pub const WNFMT_INENUM: ::DWORD = 0x10; +pub const WNFMT_CONNECTION: ::DWORD = 0x20; +STRUCT!{struct NETINFOSTRUCT { + cbStructure: ::DWORD, + dwProviderVersion: ::DWORD, + dwStatus: ::DWORD, + dwCharacteristics: ::DWORD, + dwHandle: ::ULONG_PTR, + wNetType: ::WORD, + dwPrinters: ::DWORD, + dwDrives: ::DWORD, +}} +pub type LPNETINFOSTRUCT = *mut NETINFOSTRUCT; +pub const NETINFO_DLL16: ::DWORD = 0x00000001; +pub const NETINFO_DISKRED: ::DWORD = 0x00000004; +pub const NETINFO_PRINTERRED: ::DWORD = 0x00000008; +pub const WN_SUCCESS: ::DWORD = ::NO_ERROR; +pub const WN_NO_ERROR: ::DWORD = ::NO_ERROR; +pub const WN_NOT_SUPPORTED: ::DWORD = ::ERROR_NOT_SUPPORTED; +pub const WN_CANCEL: ::DWORD = ::ERROR_CANCELLED; +pub const WN_RETRY: ::DWORD = ::ERROR_RETRY; +pub const WN_NET_ERROR: ::DWORD = ::ERROR_UNEXP_NET_ERR; +pub const WN_MORE_DATA: ::DWORD = ::ERROR_MORE_DATA; +pub const WN_BAD_POINTER: ::DWORD = ::ERROR_INVALID_ADDRESS; +pub const WN_BAD_VALUE: ::DWORD = ::ERROR_INVALID_PARAMETER; +pub const WN_BAD_USER: ::DWORD = ::ERROR_BAD_USERNAME; +pub const WN_BAD_PASSWORD: ::DWORD = ::ERROR_INVALID_PASSWORD; +pub const WN_ACCESS_DENIED: ::DWORD = ::ERROR_ACCESS_DENIED; +pub const WN_FUNCTION_BUSY: ::DWORD = ::ERROR_BUSY; +pub const WN_WINDOWS_ERROR: ::DWORD = ::ERROR_UNEXP_NET_ERR; +pub const WN_OUT_OF_MEMORY: ::DWORD = ::ERROR_NOT_ENOUGH_MEMORY; +pub const WN_NO_NETWORK: ::DWORD = ::ERROR_NO_NETWORK; +pub const WN_EXTENDED_ERROR: ::DWORD = ::ERROR_EXTENDED_ERROR; +pub const WN_BAD_LEVEL: ::DWORD = ::ERROR_INVALID_LEVEL; +pub const WN_BAD_HANDLE: ::DWORD = ::ERROR_INVALID_HANDLE; +pub const WN_NOT_INITIALIZING: ::DWORD = ::ERROR_ALREADY_INITIALIZED; +pub const WN_NO_MORE_DEVICES: ::DWORD = ::ERROR_NO_MORE_DEVICES; +pub const WN_NOT_CONNECTED: ::DWORD = ::ERROR_NOT_CONNECTED; +pub const WN_OPEN_FILES: ::DWORD = ::ERROR_OPEN_FILES; +pub const WN_DEVICE_IN_USE: ::DWORD = ::ERROR_DEVICE_IN_USE; +pub const WN_BAD_NETNAME: ::DWORD = ::ERROR_BAD_NET_NAME; +pub const WN_BAD_LOCALNAME: ::DWORD = ::ERROR_BAD_DEVICE; +pub const WN_ALREADY_CONNECTED: ::DWORD = ::ERROR_ALREADY_ASSIGNED; +pub const WN_DEVICE_ERROR: ::DWORD = ::ERROR_GEN_FAILURE; +pub const WN_CONNECTION_CLOSED: ::DWORD = ::ERROR_CONNECTION_UNAVAIL; +pub const WN_NO_NET_OR_BAD_PATH: ::DWORD = ::ERROR_NO_NET_OR_BAD_PATH; +pub const WN_BAD_PROVIDER: ::DWORD = ::ERROR_BAD_PROVIDER; +pub const WN_CANNOT_OPEN_PROFILE: ::DWORD = ::ERROR_CANNOT_OPEN_PROFILE; +pub const WN_BAD_PROFILE: ::DWORD = ::ERROR_BAD_PROFILE; +pub const WN_BAD_DEV_TYPE: ::DWORD = ::ERROR_BAD_DEV_TYPE; +pub const WN_DEVICE_ALREADY_REMEMBERED: ::DWORD = ::ERROR_DEVICE_ALREADY_REMEMBERED; +pub const WN_CONNECTED_OTHER_PASSWORD: ::DWORD = ::ERROR_CONNECTED_OTHER_PASSWORD; +pub const WN_CONNECTED_OTHER_PASSWORD_DEFAULT: ::DWORD = ::ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT; +pub const WN_NO_MORE_ENTRIES: ::DWORD = ::ERROR_NO_MORE_ITEMS; +pub const WN_NOT_CONTAINER: ::DWORD = ::ERROR_NOT_CONTAINER; +pub const WN_NOT_AUTHENTICATED: ::DWORD = ::ERROR_NOT_AUTHENTICATED; +pub const WN_NOT_LOGGED_ON: ::DWORD = ::ERROR_NOT_LOGGED_ON; +pub const WN_NOT_VALIDATED: ::DWORD = ::ERROR_NO_LOGON_SERVERS; +STRUCT!{struct NETCONNECTINFOSTRUCT { + cbStructure: ::DWORD, + dwFlags: ::DWORD, + dwSpeed: ::DWORD, + dwDelay: ::DWORD, + dwOptDataSize: ::DWORD, +}} +pub type LPNETCONNECTINFOSTRUCT = *mut NETCONNECTINFOSTRUCT; +pub const WNCON_FORNETCARD: ::DWORD = 0x00000001; +pub const WNCON_NOTROUTED: ::DWORD = 0x00000002; +pub const WNCON_SLOWLINK: ::DWORD = 0x00000004; +pub const WNCON_DYNAMIC: ::DWORD = 0x00000008; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winnls.rs b/bash-5.1/vendor/winapi-0.2.8/src/winnls.rs new file mode 100644 index 0000000..b27e2f0 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winnls.rs @@ -0,0 +1,164 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Procedure declarations, constant definitions, and macros for the NLS component. +pub const CP_ACP: ::DWORD = 0; +pub const CP_OEMCP: ::DWORD = 1; +pub const CP_MACCP: ::DWORD = 2; +pub const CP_THREAD_ACP: ::DWORD = 3; +pub const CP_SYMBOL: ::DWORD = 42; +pub const CP_UTF7: ::DWORD = 65000; +pub const CP_UTF8: ::DWORD = 65001; +pub const MAX_LEADBYTES: usize = 12; +pub const MAX_DEFAULTCHAR: usize = 2; +pub type LGRPID = ::DWORD; +pub type LCTYPE = ::DWORD; +pub type CALTYPE = ::DWORD; +pub type CALID = ::DWORD; +pub type GEOID = ::LONG; +pub type GEOTYPE = ::DWORD; +pub type GEOCLASS = ::DWORD; +STRUCT!{struct NLSVERSIONINFO { + dwNLSVersionInfoSize: ::DWORD, + dwNLSVersion: ::DWORD, + dwDefinedVersion: ::DWORD, + dwEffectiveId: ::DWORD, + guidCustomVersion: ::GUID, +}} +pub type LPNLSVERSIONINFO = *mut NLSVERSIONINFO; +STRUCT!{struct NLSVERSIONINFOEX { + dwNLSVersionInfoSize: ::DWORD, + dwNLSVersion: ::DWORD, + dwDefinedVersion: ::DWORD, + dwEffectiveId: ::DWORD, + guidCustomVersion: ::GUID, +}} +pub type LPNLSVERSIONINFOEX = *mut NLSVERSIONINFOEX; +ENUM!{enum NORM_FORM { + NormalizationOther = 0, + NormalizationC = 0x1, + NormalizationD = 0x2, + NormalizationKC = 0x5, + NormalizationKD = 0x6, +}} +pub type LANGUAGEGROUP_ENUMPROCA = Option<unsafe extern "system" fn( + ::LGRPID, ::LPSTR, ::LPSTR, ::DWORD, ::LONG_PTR, +) -> ::BOOL>; +pub type LANGGROUPLOCALE_ENUMPROCA = Option<unsafe extern "system" fn( + ::LGRPID, ::LCID, ::LPSTR, ::LONG_PTR, +) -> ::BOOL>; +pub type UILANGUAGE_ENUMPROCA = Option<unsafe extern "system" fn(::LPSTR, ::LONG_PTR) -> ::BOOL>; +pub type CODEPAGE_ENUMPROCA = Option<unsafe extern "system" fn(::LPSTR) -> ::BOOL>; +pub type DATEFMT_ENUMPROCA = Option<unsafe extern "system" fn(::LPSTR) -> ::BOOL>; +pub type DATEFMT_ENUMPROCEXA = Option<unsafe extern "system" fn(::LPSTR, ::CALID) -> ::BOOL>; +pub type TIMEFMT_ENUMPROCA = Option<unsafe extern "system" fn(::LPSTR) -> ::BOOL>; +pub type CALINFO_ENUMPROCA = Option<unsafe extern "system" fn(::LPSTR) -> ::BOOL>; +pub type CALINFO_ENUMPROCEXA = Option<unsafe extern "system" fn(::LPSTR, ::CALID) -> ::BOOL>; +pub type LOCALE_ENUMPROCA = Option<unsafe extern "system" fn(::LPSTR) -> ::BOOL>; +pub type LOCALE_ENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR) -> ::BOOL>; +pub type LANGUAGEGROUP_ENUMPROCW = Option<unsafe extern "system" fn( + ::LGRPID, ::LPWSTR, ::LPWSTR, ::DWORD, ::LONG_PTR, +) -> ::BOOL>; +pub type LANGGROUPLOCALE_ENUMPROCW = Option<unsafe extern "system" fn( + ::LGRPID, ::LCID, ::LPWSTR, ::LONG_PTR, +) -> ::BOOL>; +pub type UILANGUAGE_ENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR, ::LONG_PTR) -> ::BOOL>; +pub type CODEPAGE_ENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR) -> ::BOOL>; +pub type DATEFMT_ENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR) -> ::BOOL>; +pub type DATEFMT_ENUMPROCEXW = Option<unsafe extern "system" fn(::LPWSTR, ::CALID) -> ::BOOL>; +pub type TIMEFMT_ENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR) -> ::BOOL>; +pub type CALINFO_ENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR) -> ::BOOL>; +pub type CALINFO_ENUMPROCEXW = Option<unsafe extern "system" fn(::LPWSTR, ::CALID) -> ::BOOL>; +pub type GEO_ENUMPROC = Option<unsafe extern "system" fn(GEOID) -> ::BOOL>; +STRUCT!{struct CPINFO { + MaxCharSize: ::UINT, + DefaultChar: [::BYTE; MAX_DEFAULTCHAR], + LeadByte: [::BYTE; MAX_LEADBYTES], +}} +pub type LPCPINFO = *mut CPINFO; +STRUCT!{nodebug struct CPINFOEXA { + MaxCharSize: ::UINT, + DefaultChar: [::BYTE; MAX_DEFAULTCHAR], + LeadByte: [::BYTE; MAX_LEADBYTES], + UnicodeDefaultChar: ::WCHAR, + CodePage: ::UINT, + CodePageName: [::CHAR; ::MAX_PATH], +}} +pub type LPCPINFOEXA = *mut CPINFOEXA; +STRUCT!{nodebug struct CPINFOEXW { + MaxCharSize: ::UINT, + DefaultChar: [::BYTE; MAX_DEFAULTCHAR], + LeadByte: [::BYTE; MAX_LEADBYTES], + UnicodeDefaultChar: ::WCHAR, + CodePage: ::UINT, + CodePageName: [::WCHAR; ::MAX_PATH], +}} +pub type LPCPINFOEXW = *mut CPINFOEXW; +STRUCT!{struct NUMBERFMTA { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPSTR, + lpThousandSep: ::LPSTR, + NegativeOrder: ::UINT, +}} +pub type LPNUMBERFMTA = *mut NUMBERFMTA; +STRUCT!{struct NUMBERFMTW { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPWSTR, + lpThousandSep: ::LPWSTR, + NegativeOrder: ::UINT, +}} +pub type LPNUMBERFMTW = *mut NUMBERFMTW; +STRUCT!{struct CURRENCYFMTA { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPSTR, + lpThousandSep: ::LPSTR, + NegativeOrder: ::UINT, + PositiveOrder: ::UINT, + lpCurrencySymbol: ::LPSTR, +}} +pub type LPCURRENCYFMTA = *mut CURRENCYFMTA; +STRUCT!{struct CURRENCYFMTW { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPWSTR, + lpThousandSep: ::LPWSTR, + NegativeOrder: ::UINT, + PositiveOrder: ::UINT, + lpCurrencySymbol: ::LPWSTR, +}} +pub type LPCURRENCYFMTW = *mut CURRENCYFMTW; +pub type NLS_FUNCTION = ::DWORD; +STRUCT!{struct FILEMUIINFO { + dwSize: ::DWORD, + dwVersion: ::DWORD, + dwFileType: ::DWORD, + pChecksum: [::BYTE; 16], + pServiceChecksum: [::BYTE; 16], + dwLanguageNameOffset: ::DWORD, + dwTypeIDMainSize: ::DWORD, + dwTypeIDMainOffset: ::DWORD, + dwTypeNameMainOffset: ::DWORD, + dwTypeIDMUISize: ::DWORD, + dwTypeIDMUIOffset: ::DWORD, + dwTypeNameMUIOffset: ::DWORD, + abBuffer: [::BYTE; 8], +}} +pub type PFILEMUIINFO = *mut FILEMUIINFO; +pub type CALINFO_ENUMPROCEXEX = Option<unsafe extern "system" fn( + ::LPWSTR, ::CALID, ::LPWSTR, ::LPARAM, +) -> ::BOOL>; +pub type DATEFMT_ENUMPROCEXEX = Option<unsafe extern "system" fn( + ::LPWSTR, ::CALID, ::LPARAM, +) -> ::BOOL>; +pub type TIMEFMT_ENUMPROCEX = Option<unsafe extern "system" fn( + ::LPWSTR, ::LPARAM, +) -> ::BOOL>; +pub type LOCALE_ENUMPROCEX = Option<unsafe extern "system" fn( + ::LPWSTR, ::DWORD, ::LPARAM, +) -> ::BOOL>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winnt.rs b/bash-5.1/vendor/winapi-0.2.8/src/winnt.rs new file mode 100644 index 0000000..cce242e --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winnt.rs @@ -0,0 +1,2368 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This module defines the 32-Bit Windows types and constants that are defined by NT, but exposed +//! through the Win32 API. +pub const ANYSIZE_ARRAY: usize = 1; +//341 +pub type PVOID = *mut ::c_void; +pub type PVOID64 = u64; // This is a 64-bit pointer, even when in 32-bit +//382 +pub type VOID = ::c_void; +pub type CHAR = ::c_char; +pub type SHORT = ::c_short; +pub type LONG = ::c_long; +// pub type INT = ::c_int; // Already defined by minwindef.h +pub type WCHAR = ::wchar_t; +pub type PWCHAR = *mut WCHAR; +pub type LPWCH = *mut WCHAR; +pub type PWCH = *mut WCHAR; +pub type LPCWCH = *const WCHAR; +pub type PCWCH = *const WCHAR; +pub type NWPSTR = *mut WCHAR; +pub type LPWSTR = *mut WCHAR; +pub type PWSTR = *mut WCHAR; +pub type PZPWSTR = *mut PWSTR; +pub type PCZPWSTR = *const PWSTR; +pub type LPUWSTR = *mut WCHAR; +pub type PUWSTR = *mut WCHAR; +pub type LPCWSTR = *const WCHAR; +pub type PCWSTR = *const WCHAR; +pub type PZPCWSTR= *mut PCWSTR; +pub type PCZPCWSTR = *const PCWSTR; +pub type LPCUWSTR = *const WCHAR; +pub type PCUWSTR = *const WCHAR; +pub type PZZWSTR= *mut WCHAR; +pub type PCZZWSTR = *const WCHAR; +pub type PUZZWSTR = *mut WCHAR; +pub type PCUZZWSTR = *const WCHAR; +pub type PNZWCH = *mut WCHAR; +pub type PCNZWCH = *const WCHAR; +pub type PUNZWCH = *mut WCHAR; +pub type PCUNZWCH = *const WCHAR; +pub type LPCWCHAR = *const WCHAR; +pub type PCWCHAR = *const WCHAR; +pub type LPCUWCHAR = *const WCHAR; +pub type PCUWCHAR = *const WCHAR; +pub type UCSCHAR = ::c_ulong; +pub type PUCSCHAR = *mut UCSCHAR; +pub type PCUCSCHAR = *const UCSCHAR; +pub type PUCSSTR = *mut UCSCHAR; +pub type PUUCSSTR = *mut UCSCHAR; +pub type PCUCSSTR = *const UCSCHAR; +pub type PCUUCSSTR = *const UCSCHAR; +pub type PUUCSCHAR = *mut UCSCHAR; +pub type PCUUCSCHAR = *const UCSCHAR; +pub type PCHAR = *mut CHAR; +pub type LPCH = *mut CHAR; +pub type PCH = *mut CHAR; +pub type LPCCH = *const CHAR; +pub type PCCH = *const CHAR; +pub type NPSTR = *mut CHAR; +pub type LPSTR = *mut CHAR; +pub type PSTR = *mut CHAR; +pub type PZPSTR = *mut PSTR; +pub type PCZPSTR = *const PSTR; +pub type LPCSTR = *const CHAR; +pub type PCSTR = *const CHAR; +pub type PZPCSTR = *mut PCSTR; +pub type PCZPCSTR = *const PCSTR; +pub type PZZSTR = *mut CHAR; +pub type PCZZSTR = *const CHAR; +pub type PNZCH = *mut CHAR; +pub type PCNZCH = *const CHAR; +// Skipping TCHAR things +pub type PSHORT = *mut SHORT; +pub type PLONG = *mut LONG; +STRUCT!{struct PROCESSOR_NUMBER { + Group: ::WORD, + Number: ::BYTE, + Reserved: ::BYTE, +}} +pub type PPROCESSOR_NUMBER = *mut PROCESSOR_NUMBER; +STRUCT!{struct GROUP_AFFINITY { + Mask: ::KAFFINITY, + Group: ::WORD, + Reserved: [::WORD; 3], +}} +pub type PGROUP_AFFINITY = *mut GROUP_AFFINITY; +pub type HANDLE = *mut ::c_void; +pub type PHANDLE = *mut HANDLE; +pub type FCHAR = ::BYTE; +pub type FSHORT = ::WORD; +pub type FLONG = ::DWORD; +//667 +pub type CCHAR = ::c_char; +pub type LCID = ::DWORD; +pub type PLCID = ::PDWORD; +pub type LANGID = ::WORD; +ENUM!{enum COMPARTMENT_ID { + UNSPECIFIED_COMPARTMENT_ID = 0, + DEFAULT_COMPARTMENT_ID = 1, +}} +pub type PCOMPARTMENT_ID = *mut COMPARTMENT_ID; +pub const APPLICATION_ERROR_MASK: ::DWORD = 0x20000000; +pub const ERROR_SEVERITY_SUCCESS: ::DWORD = 0x00000000; +pub const ERROR_SEVERITY_INFORMATIONAL: ::DWORD = 0x40000000; +pub const ERROR_SEVERITY_WARNING: ::DWORD = 0x80000000; +pub const ERROR_SEVERITY_ERROR: ::DWORD = 0xC0000000; +//710 +STRUCT!{struct FLOAT128 { + LowPart: ::__int64, + HighPart: ::__int64, +}} +pub type PFLOAT128 = *mut FLOAT128; +pub type LONGLONG = ::__int64; +pub type ULONGLONG = ::__uint64; +pub type PLONGLONG = *mut LONGLONG; +pub type PULONGLONG = *mut ULONGLONG; +pub type USN = LONGLONG; +pub type LARGE_INTEGER = LONGLONG; +pub type PLARGE_INTEGER = *mut LARGE_INTEGER; +pub type ULARGE_INTEGER = ULONGLONG; +pub type PULARGE_INTEGER= *mut ULARGE_INTEGER; +pub type RTL_REFERENCE_COUNT = ::LONG_PTR; +pub type PRTL_REFERENCE_COUNT = *mut ::LONG_PTR; +STRUCT!{struct LUID { + LowPart: ::DWORD, + HighPart: LONG, +}} +pub type PLUID = *mut LUID; +pub type DWORDLONG = ULONGLONG; +pub type PDWORDLONG = *mut DWORDLONG; +//1042 +pub type BOOLEAN = ::BYTE; +pub type PBOOLEAN = *mut BOOLEAN; +STRUCT!{struct LIST_ENTRY { + Flink: *mut LIST_ENTRY, + Blink: *mut LIST_ENTRY, +}} +pub type PLIST_ENTRY = *mut LIST_ENTRY; +STRUCT!{struct SINGLE_LIST_ENTRY { + Next: *mut SINGLE_LIST_ENTRY, +}} +pub type PSINGLE_LIST_ENTRY = *mut SINGLE_LIST_ENTRY; +STRUCT!{struct LIST_ENTRY32 { + Flink: ::DWORD, + Blink: ::DWORD, +}} +pub type PLIST_ENTRY32 = *mut LIST_ENTRY32; +STRUCT!{struct LIST_ENTRY64 { + Flink: ULONGLONG, + Blink: ULONGLONG, +}} +pub type PLIST_ENTRY64 = *mut LIST_ENTRY64; +STRUCT!{struct OBJECTID { + Lineage: ::GUID, + Uniquifier: ::DWORD, +}} +pub const MINCHAR: ::CHAR = 0x80u8 as ::CHAR; +pub const MAXCHAR: ::CHAR = 0x7f; +pub const MINSHORT: ::SHORT = 0x8000u16 as ::SHORT; +pub const MAXSHORT: ::SHORT = 0x7fff; +pub const MINLONG: ::LONG = 0x80000000u32 as ::LONG; +pub const MAXLONG: ::LONG = 0x7fffffff; +pub const MAXBYTE: ::BYTE = 0xff; +pub const MAXWORD: ::WORD = 0xffff; +pub const MAXDWORD: ::DWORD = 0xffffffff; +//1300 +pub type PEXCEPTION_ROUTINE = Option<unsafe extern "system" fn( + ExceptionRecord: *mut EXCEPTION_RECORD, EstablisherFrame: PVOID, ContextRecord: *mut CONTEXT, + DispatcherContext: PVOID, +) -> ::EXCEPTION_DISPOSITION>; +//1498 +pub const LANG_NEUTRAL: ::WORD = 0x00; +pub const LANG_INVARIANT: ::WORD = 0x7f; +pub const LANG_AFRIKAANS: ::WORD = 0x36; +pub const LANG_ALBANIAN: ::WORD = 0x1c; +pub const LANG_ALSATIAN: ::WORD = 0x84; +pub const LANG_AMHARIC: ::WORD = 0x5e; +pub const LANG_ARABIC: ::WORD = 0x01; +pub const LANG_ARMENIAN: ::WORD = 0x2b; +pub const LANG_ASSAMESE: ::WORD = 0x4d; +pub const LANG_AZERI: ::WORD = 0x2c; +pub const LANG_AZERBAIJANI: ::WORD = 0x2c; +pub const LANG_BANGLA: ::WORD = 0x45; +pub const LANG_BASHKIR: ::WORD = 0x6d; +pub const LANG_BASQUE: ::WORD = 0x2d; +pub const LANG_BELARUSIAN: ::WORD = 0x23; +pub const LANG_BENGALI: ::WORD = 0x45; +pub const LANG_BRETON: ::WORD = 0x7e; +pub const LANG_BOSNIAN: ::WORD = 0x1a; +pub const LANG_BOSNIAN_NEUTRAL: ::WORD = 0x781a; +pub const LANG_BULGARIAN: ::WORD = 0x02; +pub const LANG_CATALAN: ::WORD = 0x03; +pub const LANG_CENTRAL_KURDISH: ::WORD = 0x92; +pub const LANG_CHEROKEE: ::WORD = 0x5c; +pub const LANG_CHINESE: ::WORD = 0x04; +pub const LANG_CHINESE_SIMPLIFIED: ::WORD = 0x04; +pub const LANG_CHINESE_TRADITIONAL: ::WORD = 0x7c04; +pub const LANG_CORSICAN: ::WORD = 0x83; +pub const LANG_CROATIAN: ::WORD = 0x1a; +pub const LANG_CZECH: ::WORD = 0x05; +pub const LANG_DANISH: ::WORD = 0x06; +pub const LANG_DARI: ::WORD = 0x8c; +pub const LANG_DIVEHI: ::WORD = 0x65; +pub const LANG_DUTCH: ::WORD = 0x13; +pub const LANG_ENGLISH: ::WORD = 0x09; +pub const LANG_ESTONIAN: ::WORD = 0x25; +pub const LANG_FAEROESE: ::WORD = 0x38; +pub const LANG_FARSI: ::WORD = 0x29; +pub const LANG_FILIPINO: ::WORD = 0x64; +pub const LANG_FINNISH: ::WORD = 0x0b; +pub const LANG_FRENCH: ::WORD = 0x0c; +pub const LANG_FRISIAN: ::WORD = 0x62; +pub const LANG_FULAH: ::WORD = 0x67; +pub const LANG_GALICIAN: ::WORD = 0x56; +pub const LANG_GEORGIAN: ::WORD = 0x37; +pub const LANG_GERMAN: ::WORD = 0x07; +pub const LANG_GREEK: ::WORD = 0x08; +pub const LANG_GREENLANDIC: ::WORD = 0x6f; +pub const LANG_GUJARATI: ::WORD = 0x47; +pub const LANG_HAUSA: ::WORD = 0x68; +pub const LANG_HAWAIIAN: ::WORD = 0x75; +pub const LANG_HEBREW: ::WORD = 0x0d; +pub const LANG_HINDI: ::WORD = 0x39; +pub const LANG_HUNGARIAN: ::WORD = 0x0e; +pub const LANG_ICELANDIC: ::WORD = 0x0f; +pub const LANG_IGBO: ::WORD = 0x70; +pub const LANG_INDONESIAN: ::WORD = 0x21; +pub const LANG_INUKTITUT: ::WORD = 0x5d; +pub const LANG_IRISH: ::WORD = 0x3c; +pub const LANG_ITALIAN: ::WORD = 0x10; +pub const LANG_JAPANESE: ::WORD = 0x11; +pub const LANG_KANNADA: ::WORD = 0x4b; +pub const LANG_KASHMIRI: ::WORD = 0x60; +pub const LANG_KAZAK: ::WORD = 0x3f; +pub const LANG_KHMER: ::WORD = 0x53; +pub const LANG_KICHE: ::WORD = 0x86; +pub const LANG_KINYARWANDA: ::WORD = 0x87; +pub const LANG_KONKANI: ::WORD = 0x57; +pub const LANG_KOREAN: ::WORD = 0x12; +pub const LANG_KYRGYZ: ::WORD = 0x40; +pub const LANG_LAO: ::WORD = 0x54; +pub const LANG_LATVIAN: ::WORD = 0x26; +pub const LANG_LITHUANIAN: ::WORD = 0x27; +pub const LANG_LOWER_SORBIAN: ::WORD = 0x2e; +pub const LANG_LUXEMBOURGISH: ::WORD = 0x6e; +pub const LANG_MACEDONIAN: ::WORD = 0x2f; +pub const LANG_MALAY: ::WORD = 0x3e; +pub const LANG_MALAYALAM: ::WORD = 0x4c; +pub const LANG_MALTESE: ::WORD = 0x3a; +pub const LANG_MANIPURI: ::WORD = 0x58; +pub const LANG_MAORI: ::WORD = 0x81; +pub const LANG_MAPUDUNGUN: ::WORD = 0x7a; +pub const LANG_MARATHI: ::WORD = 0x4e; +pub const LANG_MOHAWK: ::WORD = 0x7c; +pub const LANG_MONGOLIAN: ::WORD = 0x50; +pub const LANG_NEPALI: ::WORD = 0x61; +pub const LANG_NORWEGIAN: ::WORD = 0x14; +pub const LANG_OCCITAN: ::WORD = 0x82; +pub const LANG_ODIA: ::WORD = 0x48; +pub const LANG_ORIYA: ::WORD = 0x48; +pub const LANG_PASHTO: ::WORD = 0x63; +pub const LANG_PERSIAN: ::WORD = 0x29; +pub const LANG_POLISH: ::WORD = 0x15; +pub const LANG_PORTUGUESE: ::WORD = 0x16; +pub const LANG_PULAR: ::WORD = 0x67; +pub const LANG_PUNJABI: ::WORD = 0x46; +pub const LANG_QUECHUA: ::WORD = 0x6b; +pub const LANG_ROMANIAN: ::WORD = 0x18; +pub const LANG_ROMANSH: ::WORD = 0x17; +pub const LANG_RUSSIAN: ::WORD = 0x19; +pub const LANG_SAKHA: ::WORD = 0x85; +pub const LANG_SAMI: ::WORD = 0x3b; +pub const LANG_SANSKRIT: ::WORD = 0x4f; +pub const LANG_SCOTTISH_GAELIC: ::WORD = 0x91; +pub const LANG_SERBIAN: ::WORD = 0x1a; +pub const LANG_SERBIAN_NEUTRAL: ::WORD = 0x7c1a; +pub const LANG_SINDHI: ::WORD = 0x59; +pub const LANG_SINHALESE: ::WORD = 0x5b; +pub const LANG_SLOVAK: ::WORD = 0x1b; +pub const LANG_SLOVENIAN: ::WORD = 0x24; +pub const LANG_SOTHO: ::WORD = 0x6c; +pub const LANG_SPANISH: ::WORD = 0x0a; +pub const LANG_SWAHILI: ::WORD = 0x41; +pub const LANG_SWEDISH: ::WORD = 0x1d; +pub const LANG_SYRIAC: ::WORD = 0x5a; +pub const LANG_TAJIK: ::WORD = 0x28; +pub const LANG_TAMAZIGHT: ::WORD = 0x5f; +pub const LANG_TAMIL: ::WORD = 0x49; +pub const LANG_TATAR: ::WORD = 0x44; +pub const LANG_TELUGU: ::WORD = 0x4a; +pub const LANG_THAI: ::WORD = 0x1e; +pub const LANG_TIBETAN: ::WORD = 0x51; +pub const LANG_TIGRIGNA: ::WORD = 0x73; +pub const LANG_TIGRINYA: ::WORD = 0x73; +pub const LANG_TSWANA: ::WORD = 0x32; +pub const LANG_TURKISH: ::WORD = 0x1f; +pub const LANG_TURKMEN: ::WORD = 0x42; +pub const LANG_UIGHUR: ::WORD = 0x80; +pub const LANG_UKRAINIAN: ::WORD = 0x22; +pub const LANG_UPPER_SORBIAN: ::WORD = 0x2e; +pub const LANG_URDU: ::WORD = 0x20; +pub const LANG_UZBEK: ::WORD = 0x43; +pub const LANG_VALENCIAN: ::WORD = 0x03; +pub const LANG_VIETNAMESE: ::WORD = 0x2a; +pub const LANG_WELSH: ::WORD = 0x52; +pub const LANG_WOLOF: ::WORD = 0x88; +pub const LANG_XHOSA: ::WORD = 0x34; +pub const LANG_YAKUT: ::WORD = 0x85; +pub const LANG_YI: ::WORD = 0x78; +pub const LANG_YORUBA: ::WORD = 0x6a; +pub const LANG_ZULU: ::WORD = 0x35; +//1651 +pub const SUBLANG_NEUTRAL: ::WORD = 0x00; +pub const SUBLANG_DEFAULT: ::WORD = 0x01; +pub const SUBLANG_SYS_DEFAULT: ::WORD = 0x02; +pub const SUBLANG_CUSTOM_DEFAULT: ::WORD = 0x03; +pub const SUBLANG_CUSTOM_UNSPECIFIED: ::WORD = 0x04; +pub const SUBLANG_UI_CUSTOM_DEFAULT: ::WORD = 0x05; +pub const SUBLANG_AFRIKAANS_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_ALBANIAN_ALBANIA: ::WORD = 0x01; +pub const SUBLANG_ALSATIAN_FRANCE: ::WORD = 0x01; +pub const SUBLANG_AMHARIC_ETHIOPIA: ::WORD = 0x01; +pub const SUBLANG_ARABIC_SAUDI_ARABIA: ::WORD = 0x01; +pub const SUBLANG_ARABIC_IRAQ: ::WORD = 0x02; +pub const SUBLANG_ARABIC_EGYPT: ::WORD = 0x03; +pub const SUBLANG_ARABIC_LIBYA: ::WORD = 0x04; +pub const SUBLANG_ARABIC_ALGERIA: ::WORD = 0x05; +pub const SUBLANG_ARABIC_MOROCCO: ::WORD = 0x06; +pub const SUBLANG_ARABIC_TUNISIA: ::WORD = 0x07; +pub const SUBLANG_ARABIC_OMAN: ::WORD = 0x08; +pub const SUBLANG_ARABIC_YEMEN: ::WORD = 0x09; +pub const SUBLANG_ARABIC_SYRIA: ::WORD = 0x0a; +pub const SUBLANG_ARABIC_JORDAN: ::WORD = 0x0b; +pub const SUBLANG_ARABIC_LEBANON: ::WORD = 0x0c; +pub const SUBLANG_ARABIC_KUWAIT: ::WORD = 0x0d; +pub const SUBLANG_ARABIC_UAE: ::WORD = 0x0e; +pub const SUBLANG_ARABIC_BAHRAIN: ::WORD = 0x0f; +pub const SUBLANG_ARABIC_QATAR: ::WORD = 0x10; +pub const SUBLANG_ARMENIAN_ARMENIA: ::WORD = 0x01; +pub const SUBLANG_ASSAMESE_INDIA: ::WORD = 0x01; +pub const SUBLANG_AZERI_LATIN: ::WORD = 0x01; +pub const SUBLANG_AZERI_CYRILLIC: ::WORD = 0x02; +pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_LATIN: ::WORD = 0x01; +pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_CYRILLIC: ::WORD = 0x02; +pub const SUBLANG_BANGLA_INDIA: ::WORD = 0x01; +pub const SUBLANG_BANGLA_BANGLADESH: ::WORD = 0x02; +pub const SUBLANG_BASHKIR_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_BASQUE_BASQUE: ::WORD = 0x01; +pub const SUBLANG_BELARUSIAN_BELARUS: ::WORD = 0x01; +pub const SUBLANG_BENGALI_INDIA: ::WORD = 0x01; +pub const SUBLANG_BENGALI_BANGLADESH: ::WORD = 0x02; +pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN: ::WORD = 0x05; +pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC: ::WORD = 0x08; +pub const SUBLANG_BRETON_FRANCE: ::WORD = 0x01; +pub const SUBLANG_BULGARIAN_BULGARIA: ::WORD = 0x01; +pub const SUBLANG_CATALAN_CATALAN: ::WORD = 0x01; +pub const SUBLANG_CENTRAL_KURDISH_IRAQ: ::WORD = 0x01; +pub const SUBLANG_CHEROKEE_CHEROKEE: ::WORD = 0x01; +pub const SUBLANG_CHINESE_TRADITIONAL: ::WORD = 0x01; +pub const SUBLANG_CHINESE_SIMPLIFIED: ::WORD = 0x02; +pub const SUBLANG_CHINESE_HONGKONG: ::WORD = 0x03; +pub const SUBLANG_CHINESE_SINGAPORE: ::WORD = 0x04; +pub const SUBLANG_CHINESE_MACAU: ::WORD = 0x05; +pub const SUBLANG_CORSICAN_FRANCE: ::WORD = 0x01; +pub const SUBLANG_CZECH_CZECH_REPUBLIC: ::WORD = 0x01; +pub const SUBLANG_CROATIAN_CROATIA: ::WORD = 0x01; +pub const SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN: ::WORD = 0x04; +pub const SUBLANG_DANISH_DENMARK: ::WORD = 0x01; +pub const SUBLANG_DARI_AFGHANISTAN: ::WORD = 0x01; +pub const SUBLANG_DIVEHI_MALDIVES: ::WORD = 0x01; +pub const SUBLANG_DUTCH: ::WORD = 0x01; +pub const SUBLANG_DUTCH_BELGIAN: ::WORD = 0x02; +pub const SUBLANG_ENGLISH_US: ::WORD = 0x01; +pub const SUBLANG_ENGLISH_UK: ::WORD = 0x02; +pub const SUBLANG_ENGLISH_AUS: ::WORD = 0x03; +pub const SUBLANG_ENGLISH_CAN: ::WORD = 0x04; +pub const SUBLANG_ENGLISH_NZ: ::WORD = 0x05; +pub const SUBLANG_ENGLISH_EIRE: ::WORD = 0x06; +pub const SUBLANG_ENGLISH_SOUTH_AFRICA: ::WORD = 0x07; +pub const SUBLANG_ENGLISH_JAMAICA: ::WORD = 0x08; +pub const SUBLANG_ENGLISH_CARIBBEAN: ::WORD = 0x09; +pub const SUBLANG_ENGLISH_BELIZE: ::WORD = 0x0a; +pub const SUBLANG_ENGLISH_TRINIDAD: ::WORD = 0x0b; +pub const SUBLANG_ENGLISH_ZIMBABWE: ::WORD = 0x0c; +pub const SUBLANG_ENGLISH_PHILIPPINES: ::WORD = 0x0d; +pub const SUBLANG_ENGLISH_INDIA: ::WORD = 0x10; +pub const SUBLANG_ENGLISH_MALAYSIA: ::WORD = 0x11; +pub const SUBLANG_ENGLISH_SINGAPORE: ::WORD = 0x12; +pub const SUBLANG_ESTONIAN_ESTONIA: ::WORD = 0x01; +pub const SUBLANG_FAEROESE_FAROE_ISLANDS: ::WORD = 0x01; +pub const SUBLANG_FILIPINO_PHILIPPINES: ::WORD = 0x01; +pub const SUBLANG_FINNISH_FINLAND: ::WORD = 0x01; +pub const SUBLANG_FRENCH: ::WORD = 0x01; +pub const SUBLANG_FRENCH_BELGIAN: ::WORD = 0x02; +pub const SUBLANG_FRENCH_CANADIAN: ::WORD = 0x03; +pub const SUBLANG_FRENCH_SWISS: ::WORD = 0x04; +pub const SUBLANG_FRENCH_LUXEMBOURG: ::WORD = 0x05; +pub const SUBLANG_FRENCH_MONACO: ::WORD = 0x06; +pub const SUBLANG_FRISIAN_NETHERLANDS: ::WORD = 0x01; +pub const SUBLANG_FULAH_SENEGAL: ::WORD = 0x02; +pub const SUBLANG_GALICIAN_GALICIAN: ::WORD = 0x01; +pub const SUBLANG_GEORGIAN_GEORGIA: ::WORD = 0x01; +pub const SUBLANG_GERMAN: ::WORD = 0x01; +pub const SUBLANG_GERMAN_SWISS: ::WORD = 0x02; +pub const SUBLANG_GERMAN_AUSTRIAN: ::WORD = 0x03; +pub const SUBLANG_GERMAN_LUXEMBOURG: ::WORD = 0x04; +pub const SUBLANG_GERMAN_LIECHTENSTEIN: ::WORD = 0x05; +pub const SUBLANG_GREEK_GREECE: ::WORD = 0x01; +pub const SUBLANG_GREENLANDIC_GREENLAND: ::WORD = 0x01; +pub const SUBLANG_GUJARATI_INDIA: ::WORD = 0x01; +pub const SUBLANG_HAUSA_NIGERIA_LATIN: ::WORD = 0x01; +pub const SUBLANG_HAWAIIAN_US: ::WORD = 0x01; +pub const SUBLANG_HEBREW_ISRAEL: ::WORD = 0x01; +pub const SUBLANG_HINDI_INDIA: ::WORD = 0x01; +pub const SUBLANG_HUNGARIAN_HUNGARY: ::WORD = 0x01; +pub const SUBLANG_ICELANDIC_ICELAND: ::WORD = 0x01; +pub const SUBLANG_IGBO_NIGERIA: ::WORD = 0x01; +pub const SUBLANG_INDONESIAN_INDONESIA: ::WORD = 0x01; +pub const SUBLANG_INUKTITUT_CANADA: ::WORD = 0x01; +pub const SUBLANG_INUKTITUT_CANADA_LATIN: ::WORD = 0x02; +pub const SUBLANG_IRISH_IRELAND: ::WORD = 0x02; +pub const SUBLANG_ITALIAN: ::WORD = 0x01; +pub const SUBLANG_ITALIAN_SWISS: ::WORD = 0x02; +pub const SUBLANG_JAPANESE_JAPAN: ::WORD = 0x01; +pub const SUBLANG_KANNADA_INDIA: ::WORD = 0x01; +pub const SUBLANG_KASHMIRI_SASIA: ::WORD = 0x02; +pub const SUBLANG_KASHMIRI_INDIA: ::WORD = 0x02; +pub const SUBLANG_KAZAK_KAZAKHSTAN: ::WORD = 0x01; +pub const SUBLANG_KHMER_CAMBODIA: ::WORD = 0x01; +pub const SUBLANG_KICHE_GUATEMALA: ::WORD = 0x01; +pub const SUBLANG_KINYARWANDA_RWANDA: ::WORD = 0x01; +pub const SUBLANG_KONKANI_INDIA: ::WORD = 0x01; +pub const SUBLANG_KOREAN: ::WORD = 0x01; +pub const SUBLANG_KYRGYZ_KYRGYZSTAN: ::WORD = 0x01; +pub const SUBLANG_LAO_LAO: ::WORD = 0x01; +pub const SUBLANG_LATVIAN_LATVIA: ::WORD = 0x01; +pub const SUBLANG_LITHUANIAN: ::WORD = 0x01; +pub const SUBLANG_LOWER_SORBIAN_GERMANY: ::WORD = 0x02; +pub const SUBLANG_LUXEMBOURGISH_LUXEMBOURG: ::WORD = 0x01; +pub const SUBLANG_MACEDONIAN_MACEDONIA: ::WORD = 0x01; +pub const SUBLANG_MALAY_MALAYSIA: ::WORD = 0x01; +pub const SUBLANG_MALAY_BRUNEI_DARUSSALAM: ::WORD = 0x02; +pub const SUBLANG_MALAYALAM_INDIA: ::WORD = 0x01; +pub const SUBLANG_MALTESE_MALTA: ::WORD = 0x01; +pub const SUBLANG_MAORI_NEW_ZEALAND: ::WORD = 0x01; +pub const SUBLANG_MAPUDUNGUN_CHILE: ::WORD = 0x01; +pub const SUBLANG_MARATHI_INDIA: ::WORD = 0x01; +pub const SUBLANG_MOHAWK_MOHAWK: ::WORD = 0x01; +pub const SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA: ::WORD = 0x01; +pub const SUBLANG_MONGOLIAN_PRC: ::WORD = 0x02; +pub const SUBLANG_NEPALI_INDIA: ::WORD = 0x02; +pub const SUBLANG_NEPALI_NEPAL: ::WORD = 0x01; +pub const SUBLANG_NORWEGIAN_BOKMAL: ::WORD = 0x01; +pub const SUBLANG_NORWEGIAN_NYNORSK: ::WORD = 0x02; +pub const SUBLANG_OCCITAN_FRANCE: ::WORD = 0x01; +pub const SUBLANG_ODIA_INDIA: ::WORD = 0x01; +pub const SUBLANG_ORIYA_INDIA: ::WORD = 0x01; +pub const SUBLANG_PASHTO_AFGHANISTAN: ::WORD = 0x01; +pub const SUBLANG_PERSIAN_IRAN: ::WORD = 0x01; +pub const SUBLANG_POLISH_POLAND: ::WORD = 0x01; +pub const SUBLANG_PORTUGUESE: ::WORD = 0x02; +pub const SUBLANG_PORTUGUESE_BRAZILIAN: ::WORD = 0x01; +pub const SUBLANG_PULAR_SENEGAL: ::WORD = 0x02; +pub const SUBLANG_PUNJABI_INDIA: ::WORD = 0x01; +pub const SUBLANG_PUNJABI_PAKISTAN: ::WORD = 0x02; +pub const SUBLANG_QUECHUA_BOLIVIA: ::WORD = 0x01; +pub const SUBLANG_QUECHUA_ECUADOR: ::WORD = 0x02; +pub const SUBLANG_QUECHUA_PERU: ::WORD = 0x03; +pub const SUBLANG_ROMANIAN_ROMANIA: ::WORD = 0x01; +pub const SUBLANG_ROMANSH_SWITZERLAND: ::WORD = 0x01; +pub const SUBLANG_RUSSIAN_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_SAKHA_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_SAMI_NORTHERN_NORWAY: ::WORD = 0x01; +pub const SUBLANG_SAMI_NORTHERN_SWEDEN: ::WORD = 0x02; +pub const SUBLANG_SAMI_NORTHERN_FINLAND: ::WORD = 0x03; +pub const SUBLANG_SAMI_LULE_NORWAY: ::WORD = 0x04; +pub const SUBLANG_SAMI_LULE_SWEDEN: ::WORD = 0x05; +pub const SUBLANG_SAMI_SOUTHERN_NORWAY: ::WORD = 0x06; +pub const SUBLANG_SAMI_SOUTHERN_SWEDEN: ::WORD = 0x07; +pub const SUBLANG_SAMI_SKOLT_FINLAND: ::WORD = 0x08; +pub const SUBLANG_SAMI_INARI_FINLAND: ::WORD = 0x09; +pub const SUBLANG_SANSKRIT_INDIA: ::WORD = 0x01; +pub const SUBLANG_SCOTTISH_GAELIC: ::WORD = 0x01; +pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN: ::WORD = 0x06; +pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC: ::WORD = 0x07; +pub const SUBLANG_SERBIAN_MONTENEGRO_LATIN: ::WORD = 0x0b; +pub const SUBLANG_SERBIAN_MONTENEGRO_CYRILLIC: ::WORD = 0x0c; +pub const SUBLANG_SERBIAN_SERBIA_LATIN: ::WORD = 0x09; +pub const SUBLANG_SERBIAN_SERBIA_CYRILLIC: ::WORD = 0x0a; +pub const SUBLANG_SERBIAN_CROATIA: ::WORD = 0x01; +pub const SUBLANG_SERBIAN_LATIN: ::WORD = 0x02; +pub const SUBLANG_SERBIAN_CYRILLIC: ::WORD = 0x03; +pub const SUBLANG_SINDHI_INDIA: ::WORD = 0x01; +pub const SUBLANG_SINDHI_PAKISTAN: ::WORD = 0x02; +pub const SUBLANG_SINDHI_AFGHANISTAN: ::WORD = 0x02; +pub const SUBLANG_SINHALESE_SRI_LANKA: ::WORD = 0x01; +pub const SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_SLOVAK_SLOVAKIA: ::WORD = 0x01; +pub const SUBLANG_SLOVENIAN_SLOVENIA: ::WORD = 0x01; +pub const SUBLANG_SPANISH: ::WORD = 0x01; +pub const SUBLANG_SPANISH_MEXICAN: ::WORD = 0x02; +pub const SUBLANG_SPANISH_MODERN: ::WORD = 0x03; +pub const SUBLANG_SPANISH_GUATEMALA: ::WORD = 0x04; +pub const SUBLANG_SPANISH_COSTA_RICA: ::WORD = 0x05; +pub const SUBLANG_SPANISH_PANAMA: ::WORD = 0x06; +pub const SUBLANG_SPANISH_DOMINICAN_REPUBLIC: ::WORD = 0x07; +pub const SUBLANG_SPANISH_VENEZUELA: ::WORD = 0x08; +pub const SUBLANG_SPANISH_COLOMBIA: ::WORD = 0x09; +pub const SUBLANG_SPANISH_PERU: ::WORD = 0x0a; +pub const SUBLANG_SPANISH_ARGENTINA: ::WORD = 0x0b; +pub const SUBLANG_SPANISH_ECUADOR: ::WORD = 0x0c; +pub const SUBLANG_SPANISH_CHILE: ::WORD = 0x0d; +pub const SUBLANG_SPANISH_URUGUAY: ::WORD = 0x0e; +pub const SUBLANG_SPANISH_PARAGUAY: ::WORD = 0x0f; +pub const SUBLANG_SPANISH_BOLIVIA: ::WORD = 0x10; +pub const SUBLANG_SPANISH_EL_SALVADOR: ::WORD = 0x11; +pub const SUBLANG_SPANISH_HONDURAS: ::WORD = 0x12; +pub const SUBLANG_SPANISH_NICARAGUA: ::WORD = 0x13; +pub const SUBLANG_SPANISH_PUERTO_RICO: ::WORD = 0x14; +pub const SUBLANG_SPANISH_US: ::WORD = 0x15; +pub const SUBLANG_SWAHILI_KENYA: ::WORD = 0x01; +pub const SUBLANG_SWEDISH: ::WORD = 0x01; +pub const SUBLANG_SWEDISH_FINLAND: ::WORD = 0x02; +pub const SUBLANG_SYRIAC_SYRIA: ::WORD = 0x01; +pub const SUBLANG_TAJIK_TAJIKISTAN: ::WORD = 0x01; +pub const SUBLANG_TAMAZIGHT_ALGERIA_LATIN: ::WORD = 0x02; +pub const SUBLANG_TAMAZIGHT_MOROCCO_TIFINAGH: ::WORD = 0x04; +pub const SUBLANG_TAMIL_INDIA: ::WORD = 0x01; +pub const SUBLANG_TAMIL_SRI_LANKA: ::WORD = 0x02; +pub const SUBLANG_TATAR_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_TELUGU_INDIA: ::WORD = 0x01; +pub const SUBLANG_THAI_THAILAND: ::WORD = 0x01; +pub const SUBLANG_TIBETAN_PRC: ::WORD = 0x01; +pub const SUBLANG_TIGRIGNA_ERITREA: ::WORD = 0x02; +pub const SUBLANG_TIGRINYA_ERITREA: ::WORD = 0x02; +pub const SUBLANG_TIGRINYA_ETHIOPIA: ::WORD = 0x01; +pub const SUBLANG_TSWANA_BOTSWANA: ::WORD = 0x02; +pub const SUBLANG_TSWANA_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_TURKISH_TURKEY: ::WORD = 0x01; +pub const SUBLANG_TURKMEN_TURKMENISTAN: ::WORD = 0x01; +pub const SUBLANG_UIGHUR_PRC: ::WORD = 0x01; +pub const SUBLANG_UKRAINIAN_UKRAINE: ::WORD = 0x01; +pub const SUBLANG_UPPER_SORBIAN_GERMANY: ::WORD = 0x01; +pub const SUBLANG_URDU_PAKISTAN: ::WORD = 0x01; +pub const SUBLANG_URDU_INDIA: ::WORD = 0x02; +pub const SUBLANG_UZBEK_LATIN: ::WORD = 0x01; +pub const SUBLANG_UZBEK_CYRILLIC: ::WORD = 0x02; +pub const SUBLANG_VALENCIAN_VALENCIA: ::WORD = 0x02; +pub const SUBLANG_VIETNAMESE_VIETNAM: ::WORD = 0x01; +pub const SUBLANG_WELSH_UNITED_KINGDOM: ::WORD = 0x01; +pub const SUBLANG_WOLOF_SENEGAL: ::WORD = 0x01; +pub const SUBLANG_XHOSA_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_YAKUT_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_YI_PRC: ::WORD = 0x01; +pub const SUBLANG_YORUBA_NIGERIA: ::WORD = 0x01; +pub const SUBLANG_ZULU_SOUTH_AFRICA: ::WORD = 0x01; +//1962 +// FIXME: Once feature(const_fn) or some CTFE alternative becomes stable, MAKELANGID! can go +// unless we want to #[macro_export] it ... +macro_rules! MAKELANGID { ($p:expr, $s:expr) => ($s << 10 | $p) } +pub fn MAKELANGID(p: ::WORD, s: ::WORD) -> ::LANGID { MAKELANGID!(p, s) } +pub fn PRIMARYLANGID(lgid: ::LANGID) -> ::WORD { lgid & 0x3ff } +pub fn SUBLANGID(lgid: ::LANGID) -> ::WORD { lgid >> 10 } +//2019 +pub const LANG_SYSTEM_DEFAULT: LANGID = MAKELANGID!(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT); +pub const LANG_USER_DEFAULT: LANGID = MAKELANGID!(LANG_NEUTRAL, SUBLANG_DEFAULT); +//2214 +pub const MAXIMUM_WAIT_OBJECTS: ::DWORD = 64; +pub const MAXIMUM_SUSPEND_COUNT: ::CHAR = MAXCHAR; +//2277 +pub type KSPIN_LOCK = ::ULONG_PTR; +pub type PKSPIN_LOCK = *mut KSPIN_LOCK; +STRUCT!{struct M128A { // FIXME align 16 + Low: ULONGLONG, + High: LONGLONG, +}} +pub type PM128A = *mut M128A; +#[cfg(target_arch = "x86")] +STRUCT!{nodebug struct XSAVE_FORMAT { // FIXME align 16 + ControlWord: ::WORD, + StatusWord: ::WORD, + TagWord: ::BYTE, + Reserved1: ::BYTE, + ErrorOpcode: ::WORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::WORD, + Reserved2: ::WORD, + DataOffset: ::DWORD, + DataSelector: ::WORD, + Reserved3: ::WORD, + MxCsr: ::DWORD, + MxCsr_Mask: ::DWORD, + FloatRegisters: [M128A; 8], + XmmRegisters: [M128A; 8], + Reserved4: [::BYTE; 224], +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{nodebug struct XSAVE_FORMAT { // FIXME align 16 + ControlWord: ::WORD, + StatusWord: ::WORD, + TagWord: ::BYTE, + Reserved1: ::BYTE, + ErrorOpcode: ::WORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::WORD, + Reserved2: ::WORD, + DataOffset: ::DWORD, + DataSelector: ::WORD, + Reserved3: ::WORD, + MxCsr: ::DWORD, + MxCsr_Mask: ::DWORD, + FloatRegisters: [M128A; 8], + XmmRegisters: [M128A; 16], + Reserved4: [::BYTE; 96], +}} +//3563 +#[cfg(target_arch = "x86")] +pub const SIZE_OF_80387_REGISTERS: usize = 80; +#[cfg(target_arch = "x86")] +STRUCT!{nodebug struct FLOATING_SAVE_AREA { + ControlWord: ::DWORD, + StatusWord: ::DWORD, + TagWord: ::DWORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::DWORD, + DataOffset: ::DWORD, + DataSelector: ::DWORD, + RegisterArea: [::BYTE; SIZE_OF_80387_REGISTERS], + Spare0: ::DWORD, +}} +#[cfg(target_arch = "x86")] +pub type PFLOATING_SAVE_AREA = *mut FLOATING_SAVE_AREA; +#[cfg(target_arch = "x86")] +pub const MAXIMUM_SUPPORTED_EXTENSION: usize = 512; +#[cfg(target_arch = "x86")] +STRUCT!{nodebug struct CONTEXT { + ContextFlags: ::DWORD, + Dr0: ::DWORD, + Dr1: ::DWORD, + Dr2: ::DWORD, + Dr3: ::DWORD, + Dr6: ::DWORD, + Dr7: ::DWORD, + FloatSave: FLOATING_SAVE_AREA, + SegGs: ::DWORD, + SegFs: ::DWORD, + SegEs: ::DWORD, + SegDs: ::DWORD, + Edi: ::DWORD, + Esi: ::DWORD, + Ebx: ::DWORD, + Edx: ::DWORD, + Ecx: ::DWORD, + Eax: ::DWORD, + Ebp: ::DWORD, + Eip: ::DWORD, + SegCs: ::DWORD, + EFlags: ::DWORD, + Esp: ::DWORD, + SegSs: ::DWORD, + ExtendedRegisters: [::BYTE; MAXIMUM_SUPPORTED_EXTENSION], +}} +#[cfg(target_arch = "x86_64")] +pub type XMM_SAVE_AREA32 = XSAVE_FORMAT; +pub type PXMM_SAVE_AREA32 = *mut XSAVE_FORMAT; +// FIXME - Align 16 +#[cfg(target_arch = "x86_64")] +STRUCT!{nodebug struct CONTEXT { + P1Home: ::DWORD64, + P2Home: ::DWORD64, + P3Home: ::DWORD64, + P4Home: ::DWORD64, + P5Home: ::DWORD64, + P6Home: ::DWORD64, + ContextFlags: ::DWORD, + MxCsr: ::DWORD, + SegCs: ::WORD, + SegDs: ::WORD, + SegEs: ::WORD, + SegFs: ::WORD, + SegGs: ::WORD, + SegSs: ::WORD, + EFlags: ::DWORD, + Dr0: ::DWORD64, + Dr1: ::DWORD64, + Dr2: ::DWORD64, + Dr3: ::DWORD64, + Dr6: ::DWORD64, + Dr7: ::DWORD64, + Rax: ::DWORD64, + Rcx: ::DWORD64, + Rdx: ::DWORD64, + Rbx: ::DWORD64, + Rsp: ::DWORD64, + Rbp: ::DWORD64, + Rsi: ::DWORD64, + Rdi: ::DWORD64, + R8: ::DWORD64, + R9: ::DWORD64, + R10: ::DWORD64, + R11: ::DWORD64, + R12: ::DWORD64, + R13: ::DWORD64, + R14: ::DWORD64, + R15: ::DWORD64, + Rip: ::DWORD64, + FltSave: XMM_SAVE_AREA32, + VectorRegister: [::M128A; 26], + VectorControl: ::DWORD64, + DebugControl: ::DWORD64, + LastBranchToRip: ::DWORD64, + LastBranchFromRip: ::DWORD64, + LastExceptionToRip: ::DWORD64, + LastExceptionFromRip: ::DWORD64, +}} +pub type PCONTEXT = *mut CONTEXT; +#[test] +fn test_CONTEXT_size() { + use std::mem::size_of; + if cfg!(target_arch = "x86_64") { + assert_eq!(size_of::<CONTEXT>(), 1232) + } else if cfg!(target_arch = "x86") { + assert_eq!(size_of::<CONTEXT>(), 716) + } +} +pub type RUNTIME_FUNCTION = IMAGE_RUNTIME_FUNCTION_ENTRY; +pub type PRUNTIME_FUNCTION = *mut RUNTIME_FUNCTION; +pub const UNWIND_HISTORY_TABLE_SIZE: usize = 12; +STRUCT!{struct UNWIND_HISTORY_TABLE_ENTRY { + ImageBase: ::DWORD64, + FunctionEntry: PRUNTIME_FUNCTION, +}} +pub type PUNWIND_HISTORY_TABLE_ENTRY = *mut UNWIND_HISTORY_TABLE_ENTRY; +STRUCT!{struct UNWIND_HISTORY_TABLE { + Count: ::DWORD, + LocalHint: ::BYTE, + GlobalHint: ::BYTE, + Search: ::BYTE, + Once: ::BYTE, + LowAddress: ::DWORD64, + HighAddress: ::DWORD64, + Entry: [UNWIND_HISTORY_TABLE_ENTRY; UNWIND_HISTORY_TABLE_SIZE], +}} +pub type PUNWIND_HISTORY_TABLE = *mut UNWIND_HISTORY_TABLE; +pub type PGET_RUNTIME_FUNCTION_CALLBACK = Option<unsafe extern "system" fn( + ControlPc: ::DWORD64, Context: ::PVOID, +) -> PRUNTIME_FUNCTION>; +STRUCT!{struct KNONVOLATILE_CONTEXT_POINTERS_u1 { + Xmm0: PM128A, + Xmm1: PM128A, + Xmm2: PM128A, + Xmm3: PM128A, + Xmm4: PM128A, + Xmm5: PM128A, + Xmm6: PM128A, + Xmm7: PM128A, + Xmm8: PM128A, + Xmm9: PM128A, + Xmm10: PM128A, + Xmm11: PM128A, + Xmm12: PM128A, + Xmm14: PM128A, + Xmm15: PM128A, +}} +STRUCT!{struct KNONVOLATILE_CONTEXT_POINTERS_u2 { + Rax: ::DWORD64, + Rcx: ::DWORD64, + Rdx: ::DWORD64, + Rbx: ::DWORD64, + Rsp: ::DWORD64, + Rbp: ::DWORD64, + Rsi: ::DWORD64, + Rdi: ::DWORD64, + R8: ::DWORD64, + R9: ::DWORD64, + R10: ::DWORD64, + R11: ::DWORD64, + R12: ::DWORD64, + R13: ::DWORD64, + R14: ::DWORD64, + R15: ::DWORD64, +}} +STRUCT!{struct KNONVOLATILE_CONTEXT_POINTERS { + FloatingContext: [PM128A; 16], + IntegerContext: [::PDWORD64; 16], +}} +// FIXME: all unions are untagged +UNION!( + KNONVOLATILE_CONTEXT_POINTERS, FloatingContext, Xmms, Xmms_mut, + KNONVOLATILE_CONTEXT_POINTERS_u1 +); +UNION!( + KNONVOLATILE_CONTEXT_POINTERS, IntegerContext, Regs, Regs_mut, + KNONVOLATILE_CONTEXT_POINTERS_u2 +); +pub type PKNONVOLATILE_CONTEXT_POINTERS = *mut KNONVOLATILE_CONTEXT_POINTERS; +//8983 +pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; +STRUCT!{struct EXCEPTION_RECORD { + ExceptionCode: ::DWORD, + ExceptionFlags: ::DWORD, + ExceptionRecord: *mut EXCEPTION_RECORD, + ExceptionAddress: ::PVOID, + NumberParameters: ::DWORD, + ExceptionInformation: [::ULONG_PTR; EXCEPTION_MAXIMUM_PARAMETERS], +}} +pub type PEXCEPTION_RECORD = *mut EXCEPTION_RECORD; +//9023 +STRUCT!{struct EXCEPTION_POINTERS { + ExceptionRecord: PEXCEPTION_RECORD, + ContextRecord: PCONTEXT, +}} +pub type PEXCEPTION_POINTERS = *mut EXCEPTION_POINTERS; +pub type PACCESS_TOKEN = ::PVOID; +pub type PSECURITY_DESCRIPTOR = ::PVOID; +pub type PSID = ::PVOID; +pub type PCLAIMS_BLOB = ::PVOID; +//9091 +pub type ACCESS_MASK = ::DWORD; +pub type PACCESS_MASK = *mut ACCESS_MASK; +pub const DELETE: ::DWORD = 0x00010000; +pub const READ_CONTROL: ::DWORD = 0x00020000; +pub const WRITE_DAC: ::DWORD = 0x00040000; +pub const WRITE_OWNER: ::DWORD = 0x00080000; +pub const SYNCHRONIZE: ::DWORD = 0x00100000; +pub const STANDARD_RIGHTS_REQUIRED: ::DWORD = 0x000F0000; +pub const STANDARD_RIGHTS_READ: ::DWORD = READ_CONTROL; +pub const STANDARD_RIGHTS_WRITE: ::DWORD = READ_CONTROL; +pub const STANDARD_RIGHTS_EXECUTE: ::DWORD = READ_CONTROL; +pub const STANDARD_RIGHTS_ALL: ::DWORD = 0x001F0000; +pub const SPECIFIC_RIGHTS_ALL: ::DWORD = 0x0000FFFF; +pub const ACCESS_SYSTEM_SECURITY: ::DWORD = 0x01000000; +pub const MAXIMUM_ALLOWED: ::DWORD = 0x02000000; +pub const GENERIC_READ: ::DWORD = 0x80000000; +pub const GENERIC_WRITE: ::DWORD = 0x40000000; +pub const GENERIC_EXECUTE: ::DWORD = 0x20000000; +pub const GENERIC_ALL: ::DWORD = 0x10000000; +//9170 +STRUCT!{struct LUID_AND_ATTRIBUTES { + Luid: LUID, + Attributes: ::DWORD, +}} +pub type PLUID_AND_ATTRIBUTES = *mut LUID_AND_ATTRIBUTES; +//9243 +ENUM!{enum SID_NAME_USE { + SidTypeUser = 1, + SidTypeGroup, + SidTypeDomain, + SidTypeAlias, + SidTypeWellKnownGroup, + SidTypeDeletedAccount, + SidTypeInvalid, + SidTypeUnknown, + SidTypeComputer, + SidTypeLabel, +}} +pub type PSID_NAME_USE = *mut SID_NAME_USE; +STRUCT!{struct SID_AND_ATTRIBUTES { + Sid: PSID, + Attributes: ::DWORD, +}} +pub type PSID_AND_ATTRIBUTES = *mut SID_AND_ATTRIBUTES; +//9802 +pub const ACL_REVISION: ::BYTE = 2; +pub const ACL_REVISION_DS: ::BYTE = 4; +pub const ACL_REVISION1: ::BYTE = 1; +pub const MIN_ACL_REVISION: ::BYTE = ACL_REVISION2; +pub const ACL_REVISION2: ::BYTE = 2; +pub const ACL_REVISION3: ::BYTE = 3; +pub const ACL_REVISION4: ::BYTE = 4; +pub const MAX_ACL_REVISION: ::BYTE = ACL_REVISION4; +STRUCT!{struct ACL { + AclRevision: ::BYTE, + Sbz1: ::BYTE, + AclSize: ::WORD, + AceCount: ::WORD, + Sbz2: ::WORD, +}} +pub type PACL = *mut ACL; +//9888 +pub const SE_PRIVILEGE_ENABLED_BY_DEFAULT: ::DWORD = 0x00000001; +pub const SE_PRIVILEGE_ENABLED: ::DWORD = 0x00000002; +pub const SE_PRIVILEGE_REMOVED: ::DWORD = 0x00000004; +pub const SE_PRIVILEGE_USED_FOR_ACCESS: ::DWORD = 0x80000000; +pub const SE_PRIVILEGE_VALID_ATTRIBUTES: ::DWORD = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS; +pub const PRIVILEGE_SET_ALL_NECESSARY: ::DWORD = 1; +//10689 +pub const TOKEN_ASSIGN_PRIMARY: ::DWORD = 0x0001; +pub const TOKEN_DUPLICATE: ::DWORD = 0x0002; +pub const TOKEN_IMPERSONATE: ::DWORD = 0x0004; +pub const TOKEN_QUERY: ::DWORD = 0x0008; +pub const TOKEN_QUERY_SOURCE: ::DWORD = 0x0010; +pub const TOKEN_ADJUST_PRIVILEGES: ::DWORD = 0x0020; +pub const TOKEN_ADJUST_GROUPS: ::DWORD = 0x0040; +pub const TOKEN_ADJUST_DEFAULT: ::DWORD = 0x0080; +pub const TOKEN_ADJUST_SESSIONID: ::DWORD = 0x0100; +pub const TOKEN_ALL_ACCESS_P: ::DWORD = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY + | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE + | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT; +pub const TOKEN_ALL_ACCESS: ::DWORD = TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID; +pub const TOKEN_READ: ::DWORD = STANDARD_RIGHTS_READ | TOKEN_QUERY; +pub const TOKEN_WRITE: ::DWORD = STANDARD_RIGHTS_WRITE | TOKEN_ADJUST_PRIVILEGES + | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT; +pub const TOKEN_EXECUTE: ::DWORD = STANDARD_RIGHTS_EXECUTE; +//10823 +STRUCT!{nodebug struct TOKEN_PRIVILEGES { + PrivilegeCount: ::DWORD, + Privileges: [LUID_AND_ATTRIBUTES; 0], +}} +pub type PTOKEN_PRIVILEGES = *mut TOKEN_PRIVILEGES; +//10965 +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID: ::WORD = 0x00; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64: ::WORD = 0x01; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64: ::WORD = 0x02; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING: ::WORD = 0x03; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE { + Version: ::DWORD64, + Name: ::PWSTR, +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE = *mut CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN: ::WORD = 0x04; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_SID: ::WORD = 0x05; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN: ::WORD = 0x06; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE { + pValue: ::PVOID, + ValueLength: ::DWORD, +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE = + *mut CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING: ::WORD = 0x10; +pub const CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE: ::DWORD = 0x0001; +pub const CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE: ::DWORD = 0x0002; +pub const CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY: ::DWORD = 0x0004; +pub const CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT: ::DWORD = 0x0008; +pub const CLAIM_SECURITY_ATTRIBUTE_DISABLED: ::DWORD = 0x0010; +pub const CLAIM_SECURITY_ATTRIBUTE_MANDATORY: ::DWORD = 0x0020; +pub const CLAIM_SECURITY_ATTRIBUTE_VALID_FLAGS: ::DWORD = CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE + | CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE | CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY + | CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT | CLAIM_SECURITY_ATTRIBUTE_DISABLED + | CLAIM_SECURITY_ATTRIBUTE_MANDATORY; +pub const CLAIM_SECURITY_ATTRIBUTE_CUSTOM_FLAGS: ::DWORD = 0xFFFF0000; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_V1 { + Name: ::PWSTR, + ValueType: ::WORD, + Reserved: ::WORD, + Flags: ::DWORD, + ValueCount: ::DWORD, + // Put data here +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_V1 = *mut CLAIM_SECURITY_ATTRIBUTE_V1; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 { + Name: ::DWORD, + ValueType: ::WORD, + Reserved: ::WORD, + Flags: ::DWORD, + ValueCount: ::DWORD, + // Put array here +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 = *mut CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1; +pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1: ::WORD = 1; +pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION: ::WORD = + CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTES_INFORMATION { + Version: ::WORD, + Reserved: ::WORD, + AttributeCount: ::DWORD, + pAttributeV1: PCLAIM_SECURITY_ATTRIBUTE_V1, +}} +pub type PCLAIM_SECURITY_ATTRIBUTES_INFORMATION = *mut CLAIM_SECURITY_ATTRIBUTES_INFORMATION; +//11257 +pub type SECURITY_INFORMATION = ::DWORD; +pub type PSECURITY_INFORMATION = *mut ::DWORD; +pub const OWNER_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000001; +pub const GROUP_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000002; +pub const DACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000004; +pub const SACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000008; +pub const LABEL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000010; +pub const ATTRIBUTE_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000020; +pub const SCOPE_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000040; +pub const PROCESS_TRUST_LABEL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000080; +pub const BACKUP_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00010000; +pub const PROTECTED_DACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x80000000; +pub const PROTECTED_SACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x40000000; +pub const UNPROTECTED_DACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x20000000; +pub const UNPROTECTED_SACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x10000000; +ENUM!{enum SE_LEARNING_MODE_DATA_TYPE { + SeLearningModeInvalidType = 0, + SeLearningModeSettings, + SeLearningModeMax, +}} +STRUCT!{struct SECURITY_CAPABILITIES { + AppContainerSid: PSID, + Capabilities: PSID_AND_ATTRIBUTES, + CapabilityCount: ::DWORD, + Reserved: ::DWORD, +}} +pub type PSECURITY_CAPABILITIES = *mut SECURITY_CAPABILITIES; +pub type LPSECURITY_CAPABILITIES = *mut SECURITY_CAPABILITIES; +pub const PROCESS_TERMINATE: ::DWORD = 0x0001; +pub const PROCESS_CREATE_THREAD: ::DWORD = 0x0002; +pub const PROCESS_SET_SESSIONID: ::DWORD = 0x0004; +pub const PROCESS_VM_OPERATION: ::DWORD = 0x0008; +pub const PROCESS_VM_READ: ::DWORD = 0x0010; +pub const PROCESS_VM_WRITE: ::DWORD = 0x0020; +pub const PROCESS_DUP_HANDLE: ::DWORD = 0x0040; +pub const PROCESS_CREATE_PROCESS: ::DWORD = 0x0080; +pub const PROCESS_SET_QUOTA: ::DWORD = 0x0100; +pub const PROCESS_SET_INFORMATION: ::DWORD = 0x0200; +pub const PROCESS_QUERY_INFORMATION: ::DWORD = 0x0400; +pub const PROCESS_SUSPEND_RESUME: ::DWORD = 0x0800; +pub const PROCESS_QUERY_LIMITED_INFORMATION: ::DWORD = 0x1000; +pub const PROCESS_SET_LIMITED_INFORMATION: ::DWORD = 0x2000; +pub const PROCESS_ALL_ACCESS: ::DWORD = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF; +//11007 +pub const THREAD_BASE_PRIORITY_LOWRT: ::DWORD = 15; +pub const THREAD_BASE_PRIORITY_MAX: ::DWORD = 2; +pub const THREAD_BASE_PRIORITY_MIN: ::DWORD = -2i32 as ::DWORD; +pub const THREAD_BASE_PRIORITY_IDLE: ::DWORD = -15i32 as ::DWORD; +//11018 +STRUCT!{struct QUOTA_LIMITS { + PagedPoolLimit: ::SIZE_T, + NonPagedPoolLimit: ::SIZE_T, + MinimumWorkingSetSize: ::SIZE_T, + MaximumWorkingSetSize: ::SIZE_T, + PagefileLimit: ::SIZE_T, + TimeLimit: ::LARGE_INTEGER, +}} +pub type PQUOTA_LIMITS = *mut QUOTA_LIMITS; +pub const QUOTA_LIMITS_HARDWS_MIN_ENABLE: ::DWORD = 0x00000001; +pub const QUOTA_LIMITS_HARDWS_MIN_DISABLE: ::DWORD = 0x00000002; +pub const QUOTA_LIMITS_HARDWS_MAX_ENABLE: ::DWORD = 0x00000004; +pub const QUOTA_LIMITS_HARDWS_MAX_DISABLE: ::DWORD = 0x00000008; +pub const QUOTA_LIMITS_USE_DEFAULT_LIMITS: ::DWORD = 0x00000010; +STRUCT!{struct RATE_QUOTA_LIMIT { + RateData: ::DWORD, + BitFields: ::DWORD, +}} +BITFIELD!(RATE_QUOTA_LIMIT BitFields: ::DWORD [ + RatePercent set_RatePercent[0..7], + Reserved0 set_Reserved0[7..32], +]); +pub type PRATE_QUOTA_LIMIT = *mut RATE_QUOTA_LIMIT; +STRUCT!{struct QUOTA_LIMITS_EX { + PagedPoolLimit: ::SIZE_T, + NonPagedPoolLimit: ::SIZE_T, + MinimumWorkingSetSize: ::SIZE_T, + MaximumWorkingSetSize: ::SIZE_T, + PagefileLimit: ::SIZE_T, + TimeLimit: ::LARGE_INTEGER, + WorkingSetLimit: ::SIZE_T, + Reserved2: ::SIZE_T, + Reserved3: ::SIZE_T, + Reserved4: ::SIZE_T, + Flags: ::DWORD, + CpuRateLimit: RATE_QUOTA_LIMIT, +}} +pub type PQUOTA_LIMITS_EX = *mut QUOTA_LIMITS_EX; +STRUCT!{struct IO_COUNTERS { + ReadOperationCount: ::ULONGLONG, + WriteOperationCount: ::ULONGLONG, + OtherOperationCount: ::ULONGLONG, + ReadTransferCount: ::ULONGLONG, + WriteTransferCount: ::ULONGLONG, + OtherTransferCount: ::ULONGLONG, +}} +pub type PIO_COUNTERS = *mut IO_COUNTERS; +//11192 +STRUCT!{struct JOBOBJECT_BASIC_LIMIT_INFORMATION { + PerProcessUserTimeLimit: ::LARGE_INTEGER, + PerJobUserTimeLimit: ::LARGE_INTEGER, + LimitFlags: ::DWORD, + MinimumWorkingSetSize: ::SIZE_T, + MaximumWorkingSetSize: ::SIZE_T, + ActiveProcessLimit: ::DWORD, + Affinity: ::ULONG_PTR, + PriorityClass: ::DWORD, + SchedulingClass: ::DWORD, +}} +pub type PJOBOBJECT_BASIC_LIMIT_INFORMATION = *mut JOBOBJECT_BASIC_LIMIT_INFORMATION; +STRUCT!{struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { + BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION, + IoInfo: IO_COUNTERS, + ProcessMemoryLimit: ::SIZE_T, + JobMemoryLimit: ::SIZE_T, + PeakProcessMemoryUsed: ::SIZE_T, + PeakJobMemoryUsed: ::SIZE_T, +}} +pub type PJOBOBJECT_EXTENDED_LIMIT_INFORMATION = *mut JOBOBJECT_EXTENDED_LIMIT_INFORMATION; +STRUCT!{struct JOBOBJECT_BASIC_PROCESS_ID_LIST { + NumberOfAssignedProcesses: ::DWORD, + NumberOfProcessIdsInList: ::DWORD, + ProcessIdList: [::ULONG_PTR; 0], +}} +//11712 +pub const JOB_OBJECT_TERMINATE_AT_END_OF_JOB: ::DWORD = 0; +pub const JOB_OBJECT_POST_AT_END_OF_JOB: ::DWORD = 1; +pub const JOB_OBJECT_MSG_END_OF_JOB_TIME: ::DWORD = 1; +pub const JOB_OBJECT_MSG_END_OF_PROCESS_TIME: ::DWORD = 2; +pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: ::DWORD = 3; +pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: ::DWORD = 4; +pub const JOB_OBJECT_MSG_NEW_PROCESS: ::DWORD = 6; +pub const JOB_OBJECT_MSG_EXIT_PROCESS: ::DWORD = 7; +pub const JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: ::DWORD = 8; +pub const JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT: ::DWORD = 9; +pub const JOB_OBJECT_MSG_JOB_MEMORY_LIMIT: ::DWORD = 10; +pub const JOB_OBJECT_MSG_NOTIFICATION_LIMIT: ::DWORD = 11; +pub const JOB_OBJECT_MSG_JOB_CYCLE_TIME_LIMIT: ::DWORD = 12; +pub const JOB_OBJECT_MSG_MINIMUM: ::DWORD = 1; +pub const JOB_OBJECT_MSG_MAXIMUM: ::DWORD = 12; +pub const JOB_OBJECT_VALID_COMPLETION_FILTER: ::DWORD = ((1 << (JOB_OBJECT_MSG_MAXIMUM + 1)) - 1) + - ((1 << JOB_OBJECT_MSG_MINIMUM) - 1); +pub const JOB_OBJECT_LIMIT_WORKINGSET: ::DWORD = 0x00000001; +pub const JOB_OBJECT_LIMIT_PROCESS_TIME: ::DWORD = 0x00000002; +pub const JOB_OBJECT_LIMIT_JOB_TIME: ::DWORD = 0x00000004; +pub const JOB_OBJECT_LIMIT_ACTIVE_PROCESS: ::DWORD = 0x00000008; +pub const JOB_OBJECT_LIMIT_AFFINITY: ::DWORD = 0x00000010; +pub const JOB_OBJECT_LIMIT_PRIORITY_CLASS: ::DWORD = 0x00000020; +pub const JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME: ::DWORD = 0x00000040; +pub const JOB_OBJECT_LIMIT_SCHEDULING_CLASS: ::DWORD = 0x00000080; +pub const JOB_OBJECT_LIMIT_PROCESS_MEMORY: ::DWORD = 0x00000100; +pub const JOB_OBJECT_LIMIT_JOB_MEMORY: ::DWORD = 0x00000200; +pub const JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: ::DWORD = 0x00000400; +pub const JOB_OBJECT_LIMIT_BREAKAWAY_OK: ::DWORD = 0x00000800; +pub const JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK: ::DWORD = 0x00001000; +pub const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: ::DWORD = 0x00002000; +pub const JOB_OBJECT_LIMIT_SUBSET_AFFINITY: ::DWORD = 0x00004000; +pub const JOB_OBJECT_LIMIT_JOB_READ_BYTES: ::DWORD = 0x00010000; +pub const JOB_OBJECT_LIMIT_JOB_WRITE_BYTES: ::DWORD = 0x00020000; +pub const JOB_OBJECT_LIMIT_RATE_CONTROL: ::DWORD = 0x00040000; +pub const JOB_OBJECT_LIMIT_RESERVED3: ::DWORD = 0x00008000; +pub const JOB_OBJECT_LIMIT_VALID_FLAGS: ::DWORD = 0x0007ffff; +pub const JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS: ::DWORD = 0x000000ff; +pub const JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS: ::DWORD = 0x00007fff; +pub const JOB_OBJECT_NOTIFICATION_LIMIT_VALID_FLAGS: ::DWORD = 0x00070204; +pub const JOB_OBJECT_RESERVED_LIMIT_VALID_FLAGS: ::DWORD = 0x0007ffff; +pub const JOB_OBJECT_UILIMIT_NONE: ::DWORD = 0x00000000; +pub const JOB_OBJECT_UILIMIT_HANDLES: ::DWORD = 0x00000001; +pub const JOB_OBJECT_UILIMIT_READCLIPBOARD: ::DWORD = 0x00000002; +pub const JOB_OBJECT_UILIMIT_WRITECLIPBOARD: ::DWORD = 0x00000004; +pub const JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: ::DWORD = 0x00000008; +pub const JOB_OBJECT_UILIMIT_DISPLAYSETTINGS: ::DWORD = 0x00000010; +pub const JOB_OBJECT_UILIMIT_GLOBALATOMS: ::DWORD = 0x00000020; +pub const JOB_OBJECT_UILIMIT_DESKTOP: ::DWORD = 0x00000040; +pub const JOB_OBJECT_UILIMIT_EXITWINDOWS: ::DWORD = 0x00000080; +pub const JOB_OBJECT_UILIMIT_ALL: ::DWORD = 0x000000FF; +pub const JOB_OBJECT_UI_VALID_FLAGS: ::DWORD = 0x000000FF; +pub const JOB_OBJECT_SECURITY_NO_ADMIN: ::DWORD = 0x00000001; +pub const JOB_OBJECT_SECURITY_RESTRICTED_TOKEN: ::DWORD = 0x00000002; +pub const JOB_OBJECT_SECURITY_ONLY_TOKEN: ::DWORD = 0x00000004; +pub const JOB_OBJECT_SECURITY_FILTER_TOKENS: ::DWORD = 0x00000008; +pub const JOB_OBJECT_SECURITY_VALID_FLAGS: ::DWORD = 0x0000000f; +pub const JOB_OBJECT_CPU_RATE_CONTROL_ENABLE: ::DWORD = 0x1; +pub const JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED: ::DWORD = 0x2; +pub const JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP: ::DWORD = 0x4; +pub const JOB_OBJECT_CPU_RATE_CONTROL_NOTIFY: ::DWORD = 0x8; +pub const JOB_OBJECT_CPU_RATE_CONTROL_VALID_FLAGS: ::DWORD = 0xf; +ENUM!{enum JOBOBJECTINFOCLASS { + JobObjectBasicAccountingInformation = 1, + JobObjectBasicLimitInformation, + JobObjectBasicProcessIdList, + JobObjectBasicUIRestrictions, + JobObjectSecurityLimitInformation, + JobObjectEndOfJobTimeInformation, + JobObjectAssociateCompletionPortInformation, + JobObjectBasicAndIoAccountingInformation, + JobObjectExtendedLimitInformation, + JobObjectJobSetInformation, + JobObjectGroupInformation, + JobObjectNotificationLimitInformation, + JobObjectLimitViolationInformation, + JobObjectGroupInformationEx, + JobObjectCpuRateControlInformation, + JobObjectCompletionFilter, + JobObjectCompletionCounter, + JobObjectReserved1Information = 18, + JobObjectReserved2Information, + JobObjectReserved3Information, + JobObjectReserved4Information, + JobObjectReserved5Information, + JobObjectReserved6Information, + JobObjectReserved7Information, + JobObjectReserved8Information, + JobObjectReserved9Information, + MaxJobObjectInfoClass, +}} +//12063 +pub const SECTION_QUERY: ::DWORD = 0x0001; +pub const SECTION_MAP_WRITE: ::DWORD = 0x0002; +pub const SECTION_MAP_READ: ::DWORD = 0x0004; +pub const SECTION_MAP_EXECUTE: ::DWORD = 0x0008; +pub const SECTION_EXTEND_SIZE: ::DWORD = 0x0010; +pub const SECTION_MAP_EXECUTE_EXPLICIT: ::DWORD = 0x0020; +pub const SECTION_ALL_ACCESS: ::DWORD = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY + | SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE; +//12100 +pub const PAGE_NOACCESS: ::DWORD = 0x01; +pub const PAGE_READONLY: ::DWORD = 0x02; +pub const PAGE_READWRITE: ::DWORD = 0x04; +pub const PAGE_WRITECOPY: ::DWORD = 0x08; +pub const PAGE_EXECUTE: ::DWORD = 0x10; +pub const PAGE_EXECUTE_READ: ::DWORD = 0x20; +pub const PAGE_EXECUTE_READWRITE: ::DWORD = 0x40; +pub const PAGE_EXECUTE_WRITECOPY: ::DWORD = 0x80; +pub const PAGE_GUARD: ::DWORD = 0x100; +pub const PAGE_NOCACHE: ::DWORD = 0x200; +pub const PAGE_WRITECOMBINE: ::DWORD = 0x400; +pub const PAGE_REVERT_TO_FILE_MAP: ::DWORD = 0x80000000; +pub const PAGE_TARGETS_NO_UPDATE: ::DWORD = 0x40000000; +pub const PAGE_TARGETS_INVALID: ::DWORD = 0x40000000; +pub const MEM_COMMIT: ::DWORD = 0x1000; +pub const MEM_RESERVE: ::DWORD = 0x2000; +pub const MEM_DECOMMIT: ::DWORD = 0x4000; +pub const MEM_RELEASE: ::DWORD = 0x8000; +pub const MEM_FREE: ::DWORD = 0x10000; +pub const MEM_PRIVATE: ::DWORD = 0x20000; +pub const MEM_MAPPED: ::DWORD = 0x40000; +pub const MEM_RESET: ::DWORD = 0x80000; +pub const MEM_TOP_DOWN: ::DWORD = 0x100000; +pub const MEM_WRITE_WATCH: ::DWORD = 0x200000; +pub const MEM_PHYSICAL: ::DWORD = 0x400000; +pub const MEM_ROTATE: ::DWORD = 0x800000; +pub const MEM_DIFFERENT_IMAGE_BASE_OK: ::DWORD = 0x800000; +pub const MEM_RESET_UNDO: ::DWORD = 0x1000000; +pub const MEM_LARGE_PAGES: ::DWORD = 0x20000000; +pub const MEM_4MB_PAGES: ::DWORD = 0x80000000; +pub const SEC_FILE: ::DWORD = 0x800000; +pub const SEC_IMAGE: ::DWORD = 0x1000000; +pub const SEC_PROTECTED_IMAGE: ::DWORD = 0x2000000; +pub const SEC_RESERVE: ::DWORD = 0x4000000; +pub const SEC_COMMIT: ::DWORD = 0x8000000; +pub const SEC_NOCACHE: ::DWORD = 0x10000000; +pub const SEC_WRITECOMBINE: ::DWORD = 0x40000000; +pub const SEC_LARGE_PAGES: ::DWORD = 0x80000000; +pub const SEC_IMAGE_NO_EXECUTE: ::DWORD = (SEC_IMAGE | SEC_NOCACHE); +pub const MEM_IMAGE: ::DWORD = SEC_IMAGE; +pub const WRITE_WATCH_FLAG_RESET: ::DWORD = 0x01; +pub const MEM_UNMAP_WITH_TRANSIENT_BOOST: ::DWORD = 0x01; +//12217 +pub const FILE_READ_DATA: ::DWORD = 0x0001; +pub const FILE_LIST_DIRECTORY: ::DWORD = 0x0001; +pub const FILE_WRITE_DATA: ::DWORD = 0x0002; +pub const FILE_ADD_FILE: ::DWORD = 0x0002; +pub const FILE_APPEND_DATA: ::DWORD = 0x0004; +pub const FILE_ADD_SUBDIRECTORY: ::DWORD = 0x0004; +pub const FILE_CREATE_PIPE_INSTANCE: ::DWORD = 0x0004; +pub const FILE_READ_EA: ::DWORD = 0x0008; +pub const FILE_WRITE_EA: ::DWORD = 0x0010; +pub const FILE_EXECUTE: ::DWORD = 0x0020; +pub const FILE_TRAVERSE: ::DWORD = 0x0020; +pub const FILE_DELETE_CHILD: ::DWORD = 0x0040; +pub const FILE_READ_ATTRIBUTES: ::DWORD = 0x0080; +pub const FILE_WRITE_ATTRIBUTES: ::DWORD = 0x0100; +pub const FILE_ALL_ACCESS: ::DWORD = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF; +pub const FILE_GENERIC_READ: ::DWORD = STANDARD_RIGHTS_READ | FILE_READ_DATA + | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE; +pub const FILE_GENERIC_WRITE: ::DWORD = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA + | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE; +pub const FILE_GENERIC_EXECUTE: ::DWORD = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES + | FILE_EXECUTE | SYNCHRONIZE; +pub const FILE_SHARE_READ: ::DWORD = 0x00000001; +pub const FILE_SHARE_WRITE: ::DWORD = 0x00000002; +pub const FILE_SHARE_DELETE: ::DWORD = 0x00000004; +pub const FILE_ATTRIBUTE_READONLY: ::DWORD = 0x00000001; +pub const FILE_ATTRIBUTE_HIDDEN: ::DWORD = 0x00000002; +pub const FILE_ATTRIBUTE_SYSTEM: ::DWORD = 0x00000004; +pub const FILE_ATTRIBUTE_DIRECTORY: ::DWORD = 0x00000010; +pub const FILE_ATTRIBUTE_ARCHIVE: ::DWORD = 0x00000020; +pub const FILE_ATTRIBUTE_DEVICE: ::DWORD = 0x00000040; +pub const FILE_ATTRIBUTE_NORMAL: ::DWORD = 0x00000080; +pub const FILE_ATTRIBUTE_TEMPORARY: ::DWORD = 0x00000100; +pub const FILE_ATTRIBUTE_SPARSE_FILE: ::DWORD = 0x00000200; +pub const FILE_ATTRIBUTE_REPARSE_POINT: ::DWORD = 0x00000400; +pub const FILE_ATTRIBUTE_COMPRESSED: ::DWORD = 0x00000800; +pub const FILE_ATTRIBUTE_OFFLINE: ::DWORD = 0x00001000; +pub const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: ::DWORD = 0x00002000; +pub const FILE_ATTRIBUTE_ENCRYPTED: ::DWORD = 0x00004000; +pub const FILE_ATTRIBUTE_INTEGRITY_STREAM: ::DWORD = 0x00008000; +pub const FILE_ATTRIBUTE_VIRTUAL: ::DWORD = 0x00010000; +pub const FILE_ATTRIBUTE_NO_SCRUB_DATA: ::DWORD = 0x00020000; +pub const FILE_ATTRIBUTE_EA: ::DWORD = 0x00040000; +pub const FILE_NOTIFY_CHANGE_FILE_NAME: ::DWORD = 0x00000001; +pub const FILE_NOTIFY_CHANGE_DIR_NAME: ::DWORD = 0x00000002; +pub const FILE_NOTIFY_CHANGE_ATTRIBUTES: ::DWORD = 0x00000004; +pub const FILE_NOTIFY_CHANGE_SIZE: ::DWORD = 0x00000008; +pub const FILE_NOTIFY_CHANGE_LAST_WRITE: ::DWORD = 0x00000010; +pub const FILE_NOTIFY_CHANGE_LAST_ACCESS: ::DWORD = 0x00000020; +pub const FILE_NOTIFY_CHANGE_CREATION: ::DWORD = 0x00000040; +pub const FILE_NOTIFY_CHANGE_SECURITY: ::DWORD = 0x00000100; +pub const FILE_ACTION_ADDED: ::DWORD = 0x00000001; +pub const FILE_ACTION_REMOVED: ::DWORD = 0x00000002; +pub const FILE_ACTION_MODIFIED: ::DWORD = 0x00000003; +pub const FILE_ACTION_RENAMED_OLD_NAME: ::DWORD = 0x00000004; +pub const FILE_ACTION_RENAMED_NEW_NAME: ::DWORD = 0x00000005; +pub const MAILSLOT_NO_MESSAGE: ::DWORD = 0xFFFFFFFF; +pub const MAILSLOT_WAIT_FOREVER: ::DWORD = 0xFFFFFFFF; +pub const FILE_CASE_SENSITIVE_SEARCH: ::DWORD = 0x00000001; +pub const FILE_CASE_PRESERVED_NAMES: ::DWORD = 0x00000002; +pub const FILE_UNICODE_ON_DISK: ::DWORD = 0x00000004; +pub const FILE_PERSISTENT_ACLS: ::DWORD = 0x00000008; +pub const FILE_FILE_COMPRESSION: ::DWORD = 0x00000010; +pub const FILE_VOLUME_QUOTAS: ::DWORD = 0x00000020; +pub const FILE_SUPPORTS_SPARSE_FILES: ::DWORD = 0x00000040; +pub const FILE_SUPPORTS_REPARSE_POINTS: ::DWORD = 0x00000080; +pub const FILE_SUPPORTS_REMOTE_STORAGE: ::DWORD = 0x00000100; +pub const FILE_VOLUME_IS_COMPRESSED: ::DWORD = 0x00008000; +pub const FILE_SUPPORTS_OBJECT_IDS: ::DWORD = 0x00010000; +pub const FILE_SUPPORTS_ENCRYPTION: ::DWORD = 0x00020000; +pub const FILE_NAMED_STREAMS: ::DWORD = 0x00040000; +pub const FILE_READ_ONLY_VOLUME: ::DWORD = 0x00080000; +pub const FILE_SEQUENTIAL_WRITE_ONCE: ::DWORD = 0x00100000; +pub const FILE_SUPPORTS_TRANSACTIONS: ::DWORD = 0x00200000; +pub const FILE_SUPPORTS_HARD_LINKS: ::DWORD = 0x00400000; +pub const FILE_SUPPORTS_EXTENDED_ATTRIBUTES: ::DWORD = 0x00800000; +pub const FILE_SUPPORTS_OPEN_BY_FILE_ID: ::DWORD = 0x01000000; +pub const FILE_SUPPORTS_USN_JOURNAL: ::DWORD = 0x02000000; +pub const FILE_SUPPORTS_INTEGRITY_STREAMS: ::DWORD = 0x04000000; +pub const FILE_INVALID_FILE_ID: ::LONGLONG = -1; +STRUCT!{struct FILE_ID_128 { + Identifier: [::BYTE; 16], +}} +pub type PFILE_ID_128 = *mut FILE_ID_128; +STRUCT!{struct FILE_NOTIFY_INFORMATION { + NextEntryOffset: ::DWORD, + Action: ::DWORD, + FileNameLength: ::DWORD, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_SEGMENT_ELEMENT { + Buffer: ::PVOID64, + Alignment: ::ULONGLONG, +}} +pub type PFILE_SEGMENT_ELEMENT = *mut FILE_SEGMENT_ELEMENT; +//12475 +pub const IO_REPARSE_TAG_MOUNT_POINT: ::DWORD = 0xA0000003; +pub const IO_REPARSE_TAG_HSM: ::DWORD = 0xC0000004; +pub const IO_REPARSE_TAG_HSM2: ::DWORD = 0x80000006; +pub const IO_REPARSE_TAG_SIS: ::DWORD = 0x80000007; +pub const IO_REPARSE_TAG_WIM: ::DWORD = 0x80000008; +pub const IO_REPARSE_TAG_CSV: ::DWORD = 0x80000009; +pub const IO_REPARSE_TAG_DFS: ::DWORD = 0x8000000A; +pub const IO_REPARSE_TAG_SYMLINK: ::DWORD = 0xA000000C; +pub const IO_REPARSE_TAG_DFSR: ::DWORD = 0x80000012; +pub const IO_REPARSE_TAG_DEDUP: ::DWORD = 0x80000013; +pub const IO_REPARSE_TAG_NFS: ::DWORD = 0x80000014; +pub const IO_REPARSE_TAG_FILE_PLACEHOLDER: ::DWORD = 0x80000015; +pub const IO_REPARSE_TAG_WOF: ::DWORD = 0x80000017; +//12788 +pub const DUPLICATE_CLOSE_SOURCE: ::DWORD = 0x00000001; +pub const DUPLICATE_SAME_ACCESS: ::DWORD = 0x00000002; +//14708 +STRUCT!{struct PROCESSOR_POWER_POLICY_INFO { + TimeCheck: ::DWORD, + DemoteLimit: ::DWORD, + PromoteLimit: ::DWORD, + DemotePercent: ::BYTE, + PromotePercent: ::BYTE, + Spare: [::BYTE; 2], + Reserved: ::DWORD, +}} +BITFIELD!(PROCESSOR_POWER_POLICY_INFO Reserved: ::DWORD [ + AllowDemotion set_AllowDemotion[0..1], + AllowPromotion set_AllowPromotion[1..2], +]); +pub type PPROCESSOR_POWER_POLICY_INFO = *mut PROCESSOR_POWER_POLICY_INFO; +//15000 +STRUCT!{struct IMAGE_FILE_HEADER { + Machine: ::WORD, + NumberOfSections: ::WORD, + TimeDateStamp: ::DWORD, + PointerToSymbolTable: ::DWORD, + NumberOfSymbols: ::DWORD, + SizeOfOptionalHeader: ::WORD, + Characteristics: ::WORD, +}} +pub type PIMAGE_FILE_HEADER = *mut IMAGE_FILE_HEADER; +pub const IMAGE_SIZEOF_FILE_HEADER: usize = 20; +pub const IMAGE_FILE_RELOCS_STRIPPED: ::WORD = 0x0001; +pub const IMAGE_FILE_EXECUTABLE_IMAGE: ::WORD = 0x0002; +pub const IMAGE_FILE_LINE_NUMS_STRIPPED: ::WORD = 0x0004; +pub const IMAGE_FILE_LOCAL_SYMS_STRIPPED: ::WORD = 0x0008; +pub const IMAGE_FILE_AGGRESIVE_WS_TRIM: ::WORD = 0x0010; +pub const IMAGE_FILE_LARGE_ADDRESS_AWARE: ::WORD = 0x0020; +pub const IMAGE_FILE_BYTES_REVERSED_LO: ::WORD = 0x0080; +pub const IMAGE_FILE_32BIT_MACHINE: ::WORD = 0x0100; +pub const IMAGE_FILE_DEBUG_STRIPPED: ::WORD = 0x0200; +pub const IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP: ::WORD = 0x0400; +pub const IMAGE_FILE_NET_RUN_FROM_SWAP: ::WORD = 0x0800; +pub const IMAGE_FILE_SYSTEM: ::WORD = 0x1000; +pub const IMAGE_FILE_DLL: ::WORD = 0x2000; +pub const IMAGE_FILE_UP_SYSTEM_ONLY: ::WORD = 0x4000; +pub const IMAGE_FILE_BYTES_REVERSED_HI: ::WORD = 0x8000; +pub const IMAGE_FILE_MACHINE_UNKNOWN: ::WORD = 0; +pub const IMAGE_FILE_MACHINE_I386: ::WORD = 0x014c; +pub const IMAGE_FILE_MACHINE_R3000: ::WORD = 0x0162; +pub const IMAGE_FILE_MACHINE_R4000: ::WORD = 0x0166; +pub const IMAGE_FILE_MACHINE_R10000: ::WORD = 0x0168; +pub const IMAGE_FILE_MACHINE_WCEMIPSV2: ::WORD = 0x0169; +pub const IMAGE_FILE_MACHINE_ALPHA: ::WORD = 0x0184; +pub const IMAGE_FILE_MACHINE_SH3: ::WORD = 0x01a2; +pub const IMAGE_FILE_MACHINE_SH3DSP: ::WORD = 0x01a3; +pub const IMAGE_FILE_MACHINE_SH3E: ::WORD = 0x01a4; +pub const IMAGE_FILE_MACHINE_SH4: ::WORD = 0x01a6; +pub const IMAGE_FILE_MACHINE_SH5: ::WORD = 0x01a8; +pub const IMAGE_FILE_MACHINE_ARM: ::WORD = 0x01c0; +pub const IMAGE_FILE_MACHINE_THUMB: ::WORD = 0x01c2; +pub const IMAGE_FILE_MACHINE_ARMNT: ::WORD = 0x01c4; +pub const IMAGE_FILE_MACHINE_AM33: ::WORD = 0x01d3; +pub const IMAGE_FILE_MACHINE_POWERPC: ::WORD = 0x01F0; +pub const IMAGE_FILE_MACHINE_POWERPCFP: ::WORD = 0x01f1; +pub const IMAGE_FILE_MACHINE_IA64: ::WORD = 0x0200; +pub const IMAGE_FILE_MACHINE_MIPS16: ::WORD = 0x0266; +pub const IMAGE_FILE_MACHINE_ALPHA64: ::WORD = 0x0284; +pub const IMAGE_FILE_MACHINE_MIPSFPU: ::WORD = 0x0366; +pub const IMAGE_FILE_MACHINE_MIPSFPU16: ::WORD = 0x0466; +pub const IMAGE_FILE_MACHINE_AXP64: ::WORD = IMAGE_FILE_MACHINE_ALPHA64; +pub const IMAGE_FILE_MACHINE_TRICORE: ::WORD = 0x0520; +pub const IMAGE_FILE_MACHINE_CEF: ::WORD = 0x0CEF; +pub const IMAGE_FILE_MACHINE_EBC: ::WORD = 0x0EBC; +pub const IMAGE_FILE_MACHINE_AMD64: ::WORD = 0x8664; +pub const IMAGE_FILE_MACHINE_M32R: ::WORD = 0x9041; +pub const IMAGE_FILE_MACHINE_CEE: ::WORD = 0xC0EE; +STRUCT!{struct IMAGE_DATA_DIRECTORY { + VirtualAddress: ::DWORD, + Size: ::DWORD, +}} +pub type PIMAGE_DATA_DIRECTORY = *mut IMAGE_DATA_DIRECTORY; +pub const IMAGE_NUMBEROF_DIRECTORY_ENTRIES: usize = 16; +STRUCT!{struct IMAGE_OPTIONAL_HEADER32 { + Magic: ::WORD, + MajorLinkerVersion: ::BYTE, + MinorLinkerVersion: ::BYTE, + SizeOfCode: ::DWORD, + SizeOfInitializedData: ::DWORD, + SizeOfUninitializedData: ::DWORD, + AddressOfEntryPoint: ::DWORD, + BaseOfCode: ::DWORD, + BaseOfData: ::DWORD, + ImageBase: ::DWORD, + SectionAlignment: ::DWORD, + FileAlignment: ::DWORD, + MajorOperatingSystemVersion: ::WORD, + MinorOperatingSystemVersion: ::WORD, + MajorImageVersion: ::WORD, + MinorImageVersion: ::WORD, + MajorSubsystemVersion: ::WORD, + MinorSubsystemVersion: ::WORD, + Win32VersionValue: ::DWORD, + SizeOfImage: ::DWORD, + SizeOfHeaders: ::DWORD, + CheckSum: ::DWORD, + Subsystem: ::WORD, + DllCharacteristics: ::WORD, + SizeOfStackReserve: ::DWORD, + SizeOfStackCommit: ::DWORD, + SizeOfHeapReserve: ::DWORD, + SizeOfHeapCommit: ::DWORD, + LoaderFlags: ::DWORD, + NumberOfRvaAndSizes: ::DWORD, + DataDirectory: [IMAGE_DATA_DIRECTORY; IMAGE_NUMBEROF_DIRECTORY_ENTRIES], +}} +pub type PIMAGE_OPTIONAL_HEADER32 = *mut IMAGE_OPTIONAL_HEADER32; +STRUCT!{struct IMAGE_ROM_OPTIONAL_HEADER { + Magic: ::WORD, + MajorLinkerVersion: ::BYTE, + MinorLinkerVersion: ::BYTE, + SizeOfCode: ::DWORD, + SizeOfInitializedData: ::DWORD, + SizeOfUninitializedData: ::DWORD, + AddressOfEntryPoint: ::DWORD, + BaseOfCode: ::DWORD, + BaseOfData: ::DWORD, + BaseOfBss: ::DWORD, + GprMask: ::DWORD, + CprMask: [::DWORD; 4], + GpValue: ::DWORD, +}} +pub type PIMAGE_ROM_OPTIONAL_HEADER = *mut IMAGE_ROM_OPTIONAL_HEADER; +STRUCT!{struct IMAGE_OPTIONAL_HEADER64 { + Magic: ::WORD, + MajorLinkerVersion: ::BYTE, + MinorLinkerVersion: ::BYTE, + SizeOfCode: ::DWORD, + SizeOfInitializedData: ::DWORD, + SizeOfUninitializedData: ::DWORD, + AddressOfEntryPoint: ::DWORD, + BaseOfCode: ::DWORD, + ImageBase: ::ULONGLONG, + SectionAlignment: ::DWORD, + FileAlignment: ::DWORD, + MajorOperatingSystemVersion: ::WORD, + MinorOperatingSystemVersion: ::WORD, + MajorImageVersion: ::WORD, + MinorImageVersion: ::WORD, + MajorSubsystemVersion: ::WORD, + MinorSubsystemVersion: ::WORD, + Win32VersionValue: ::DWORD, + SizeOfImage: ::DWORD, + SizeOfHeaders: ::DWORD, + CheckSum: ::DWORD, + Subsystem: ::WORD, + DllCharacteristics: ::WORD, + SizeOfStackReserve: ULONGLONG, + SizeOfStackCommit: ULONGLONG, + SizeOfHeapReserve: ULONGLONG, + SizeOfHeapCommit: ULONGLONG, + LoaderFlags: ::DWORD, + NumberOfRvaAndSizes: ::DWORD, + DataDirectory: [IMAGE_DATA_DIRECTORY; IMAGE_NUMBEROF_DIRECTORY_ENTRIES], +}} +pub type PIMAGE_OPTIONAL_HEADER64 = *mut IMAGE_OPTIONAL_HEADER64; +pub const IMAGE_NT_OPTIONAL_HDR32_MAGIC: ::WORD = 0x10b; +pub const IMAGE_NT_OPTIONAL_HDR64_MAGIC: ::WORD = 0x20b; +pub const IMAGE_ROM_OPTIONAL_HDR_MAGIC: ::WORD = 0x107; +#[cfg(target_arch = "x86_64")] +pub type IMAGE_OPTIONAL_HEADER = IMAGE_OPTIONAL_HEADER64; +#[cfg(target_arch = "x86_64")] +pub type PIMAGE_OPTIONAL_HEADER = PIMAGE_OPTIONAL_HEADER64; +#[cfg(target_arch = "x86")] +pub type IMAGE_OPTIONAL_HEADER = IMAGE_OPTIONAL_HEADER32; +#[cfg(target_arch = "x86")] +pub type PIMAGE_OPTIONAL_HEADER = PIMAGE_OPTIONAL_HEADER32; +STRUCT!{struct IMAGE_NT_HEADERS64 { + Signature: ::DWORD, + FileHeader: IMAGE_FILE_HEADER, + OptionalHeader: IMAGE_OPTIONAL_HEADER64, +}} +pub type PIMAGE_NT_HEADERS64 = *mut IMAGE_NT_HEADERS64; +STRUCT!{struct IMAGE_NT_HEADERS32 { + Signature: ::DWORD, + FileHeader: IMAGE_FILE_HEADER, + OptionalHeader: IMAGE_OPTIONAL_HEADER32, +}} +pub type PIMAGE_NT_HEADERS32 = *mut IMAGE_NT_HEADERS32; +STRUCT!{struct IMAGE_ROM_HEADERS { + FileHeader: IMAGE_FILE_HEADER, + OptionalHeader: IMAGE_ROM_OPTIONAL_HEADER, +}} +pub type PIMAGE_ROM_HEADERS = *mut IMAGE_ROM_HEADERS; +#[cfg(target_arch = "x86_64")] +pub type IMAGE_NT_HEADERS = IMAGE_NT_HEADERS64; +#[cfg(target_arch = "x86_64")] +pub type PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS64; +#[cfg(target_arch = "x86")] +pub type IMAGE_NT_HEADERS = IMAGE_NT_HEADERS32; +#[cfg(target_arch = "x86")] +pub type PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS32; +pub const IMAGE_SUBSYSTEM_UNKNOWN: ::WORD = 0; +pub const IMAGE_SUBSYSTEM_NATIVE: ::WORD = 1; +pub const IMAGE_SUBSYSTEM_WINDOWS_GUI: ::WORD = 2; +pub const IMAGE_SUBSYSTEM_WINDOWS_CUI: ::WORD = 3; +pub const IMAGE_SUBSYSTEM_OS2_CUI: ::WORD = 5; +pub const IMAGE_SUBSYSTEM_POSIX_CUI: ::WORD = 7; +pub const IMAGE_SUBSYSTEM_NATIVE_WINDOWS: ::WORD = 8; +pub const IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: ::WORD = 9; +pub const IMAGE_SUBSYSTEM_EFI_APPLICATION: ::WORD = 10; +pub const IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: ::WORD = 11; +pub const IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: ::WORD = 12; +pub const IMAGE_SUBSYSTEM_EFI_ROM: ::WORD = 13; +pub const IMAGE_SUBSYSTEM_XBOX: ::WORD = 14; +pub const IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION: ::WORD = 16; +pub const IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA: ::WORD = 0x0020; +pub const IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE: ::WORD = 0x0040; +pub const IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY: ::WORD = 0x0080; +pub const IMAGE_DLLCHARACTERISTICS_NX_COMPAT: ::WORD = 0x0100; +pub const IMAGE_DLLCHARACTERISTICS_NO_ISOLATION: ::WORD = 0x0200; +pub const IMAGE_DLLCHARACTERISTICS_NO_SEH: ::WORD = 0x0400; +pub const IMAGE_DLLCHARACTERISTICS_NO_BIND: ::WORD = 0x0800; +pub const IMAGE_DLLCHARACTERISTICS_APPCONTAINER: ::WORD = 0x1000; +pub const IMAGE_DLLCHARACTERISTICS_WDM_DRIVER: ::WORD = 0x2000; +pub const IMAGE_DLLCHARACTERISTICS_GUARD_CF: ::WORD = 0x4000; +pub const IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE: ::WORD = 0x8000; +pub const IMAGE_DIRECTORY_ENTRY_EXPORT: ::WORD = 0; +pub const IMAGE_DIRECTORY_ENTRY_IMPORT: ::WORD = 1; +pub const IMAGE_DIRECTORY_ENTRY_RESOURCE: ::WORD = 2; +pub const IMAGE_DIRECTORY_ENTRY_EXCEPTION: ::WORD = 3; +pub const IMAGE_DIRECTORY_ENTRY_SECURITY: ::WORD = 4; +pub const IMAGE_DIRECTORY_ENTRY_BASERELOC: ::WORD = 5; +pub const IMAGE_DIRECTORY_ENTRY_DEBUG: ::WORD = 6; +pub const IMAGE_DIRECTORY_ENTRY_ARCHITECTURE: ::WORD = 7; +pub const IMAGE_DIRECTORY_ENTRY_GLOBALPTR: ::WORD = 8; +pub const IMAGE_DIRECTORY_ENTRY_TLS: ::WORD = 9; +pub const IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: ::WORD = 10; +pub const IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: ::WORD = 11; +pub const IMAGE_DIRECTORY_ENTRY_IAT: ::WORD = 12; +pub const IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT: ::WORD = 13; +pub const IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR: ::WORD = 14; +STRUCT!{struct ANON_OBJECT_HEADER { + Sig1: ::WORD, + Sig2: ::WORD, + Version: ::WORD, + Machine: ::WORD, + TimeDateStamp: ::DWORD, + ClassID: ::CLSID, + SizeOfData: ::DWORD, +}} +STRUCT!{struct ANON_OBJECT_HEADER_V2 { + Sig1: ::WORD, + Sig2: ::WORD, + Version: ::WORD, + Machine: ::WORD, + TimeDateStamp: ::DWORD, + ClassID: ::CLSID, + SizeOfData: ::DWORD, + Flags: ::DWORD, + MetaDataSize: ::DWORD, + MetaDataOffset: ::DWORD, +}} +STRUCT!{struct ANON_OBJECT_HEADER_BIGOBJ { + Sig1: ::WORD, + Sig2: ::WORD, + Version: ::WORD, + Machine: ::WORD, + TimeDateStamp: ::DWORD, + ClassID: ::CLSID, + SizeOfData: ::DWORD, + Flags: ::DWORD, + MetaDataSize: ::DWORD, + MetaDataOffset: ::DWORD, + NumberOfSections: ::DWORD, + PointerToSymbolTable: ::DWORD, + NumberOfSymbols: ::DWORD, +}} +pub const IMAGE_SIZEOF_SHORT_NAME: usize = 8; +STRUCT!{struct IMAGE_SECTION_HEADER { + Name: [::BYTE; IMAGE_SIZEOF_SHORT_NAME], + PhysicalAddressOrVirtualSize: ::DWORD, + VirtualAddress: ::DWORD, + SizeOfRawData: ::DWORD, + PointerToRawData: ::DWORD, + PointerToRelocations: ::DWORD, + PointerToLinenumbers: ::DWORD, + NumberOfRelocations: ::WORD, + NumberOfLinenumbers: ::WORD, + Characteristics: ::DWORD, +}} +pub type PIMAGE_SECTION_HEADER = *mut IMAGE_SECTION_HEADER; +pub const IMAGE_SIZEOF_SECTION_HEADER: usize = 40; +pub const IMAGE_SCN_TYPE_NO_PAD: ::DWORD = 0x00000008; +pub const IMAGE_SCN_CNT_CODE: ::DWORD = 0x00000020; +pub const IMAGE_SCN_CNT_INITIALIZED_DATA: ::DWORD = 0x00000040; +pub const IMAGE_SCN_CNT_UNINITIALIZED_DATA: ::DWORD = 0x00000080; +pub const IMAGE_SCN_LNK_OTHER: ::DWORD = 0x00000100; +pub const IMAGE_SCN_LNK_INFO: ::DWORD = 0x00000200; +pub const IMAGE_SCN_LNK_REMOVE: ::DWORD = 0x00000800; +pub const IMAGE_SCN_LNK_COMDAT: ::DWORD = 0x00001000; +pub const IMAGE_SCN_NO_DEFER_SPEC_EXC: ::DWORD = 0x00004000; +pub const IMAGE_SCN_GPREL: ::DWORD = 0x00008000; +pub const IMAGE_SCN_MEM_FARDATA: ::DWORD = 0x00008000; +pub const IMAGE_SCN_MEM_PURGEABLE: ::DWORD = 0x00020000; +pub const IMAGE_SCN_MEM_16BIT: ::DWORD = 0x00020000; +pub const IMAGE_SCN_MEM_LOCKED: ::DWORD = 0x00040000; +pub const IMAGE_SCN_MEM_PRELOAD: ::DWORD = 0x00080000; +pub const IMAGE_SCN_ALIGN_1BYTES: ::DWORD = 0x00100000; +pub const IMAGE_SCN_ALIGN_2BYTES: ::DWORD = 0x00200000; +pub const IMAGE_SCN_ALIGN_4BYTES: ::DWORD = 0x00300000; +pub const IMAGE_SCN_ALIGN_8BYTES: ::DWORD = 0x00400000; +pub const IMAGE_SCN_ALIGN_16BYTES: ::DWORD = 0x00500000; +pub const IMAGE_SCN_ALIGN_32BYTES: ::DWORD = 0x00600000; +pub const IMAGE_SCN_ALIGN_64BYTES: ::DWORD = 0x00700000; +pub const IMAGE_SCN_ALIGN_128BYTES: ::DWORD = 0x00800000; +pub const IMAGE_SCN_ALIGN_256BYTES: ::DWORD = 0x00900000; +pub const IMAGE_SCN_ALIGN_512BYTES: ::DWORD = 0x00A00000; +pub const IMAGE_SCN_ALIGN_1024BYTES: ::DWORD = 0x00B00000; +pub const IMAGE_SCN_ALIGN_2048BYTES: ::DWORD = 0x00C00000; +pub const IMAGE_SCN_ALIGN_4096BYTES: ::DWORD = 0x00D00000; +pub const IMAGE_SCN_ALIGN_8192BYTES: ::DWORD = 0x00E00000; +pub const IMAGE_SCN_ALIGN_MASK: ::DWORD = 0x00F00000; +pub const IMAGE_SCN_LNK_NRELOC_OVFL: ::DWORD = 0x01000000; +pub const IMAGE_SCN_MEM_DISCARDABLE: ::DWORD = 0x02000000; +pub const IMAGE_SCN_MEM_NOT_CACHED: ::DWORD = 0x04000000; +pub const IMAGE_SCN_MEM_NOT_PAGED: ::DWORD = 0x08000000; +pub const IMAGE_SCN_MEM_SHARED: ::DWORD = 0x10000000; +pub const IMAGE_SCN_MEM_EXECUTE: ::DWORD = 0x20000000; +pub const IMAGE_SCN_MEM_READ: ::DWORD = 0x40000000; +pub const IMAGE_SCN_MEM_WRITE: ::DWORD = 0x80000000; +pub const IMAGE_SCN_SCALE_INDEX: ::DWORD = 0x00000001; +//16590 +STRUCT!{struct IMAGE_DEBUG_DIRECTORY { + Characteristics: ::DWORD, + TimeDateStamp: ::DWORD, + MajorVersion: ::WORD, + MinorVersion: ::WORD, + Type: ::DWORD, + SizeOfData: ::DWORD, + AddressOfRawData: ::DWORD, + PointerToRawData: ::DWORD, +}} +pub type PIMAGE_DEBUG_DIRECTORY = *mut IMAGE_DEBUG_DIRECTORY; +pub const IMAGE_DEBUG_TYPE_UNKNOWN: ::DWORD = 0; +pub const IMAGE_DEBUG_TYPE_COFF: ::DWORD = 1; +pub const IMAGE_DEBUG_TYPE_CODEVIEW: ::DWORD = 2; +pub const IMAGE_DEBUG_TYPE_FPO: ::DWORD = 3; +pub const IMAGE_DEBUG_TYPE_MISC: ::DWORD = 4; +pub const IMAGE_DEBUG_TYPE_EXCEPTION: ::DWORD = 5; +pub const IMAGE_DEBUG_TYPE_FIXUP: ::DWORD = 6; +pub const IMAGE_DEBUG_TYPE_OMAP_TO_SRC: ::DWORD = 7; +pub const IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: ::DWORD = 8; +pub const IMAGE_DEBUG_TYPE_BORLAND: ::DWORD = 9; +pub const IMAGE_DEBUG_TYPE_RESERVED10: ::DWORD = 10; +pub const IMAGE_DEBUG_TYPE_CLSID: ::DWORD = 11; +STRUCT!{struct IMAGE_COFF_SYMBOLS_HEADER { + NumberOfSymbols: ::DWORD, + LvaToFirstSymbol: ::DWORD, + NumberOfLinenumbers: ::DWORD, + LvaToFirstLinenumber: ::DWORD, + RvaToFirstByteOfCode: ::DWORD, + RvaToLastByteOfCode: ::DWORD, + RvaToFirstByteOfData: ::DWORD, + RvaToLastByteOfData: ::DWORD, +}} +pub type PIMAGE_COFF_SYMBOLS_HEADER = *mut IMAGE_COFF_SYMBOLS_HEADER; +STRUCT!{struct IMAGE_RUNTIME_FUNCTION_ENTRY { + BeginAddress: ::DWORD, + EndAddress: ::DWORD, + UnwindInfoAddress: ::DWORD, +}} +UNION!(IMAGE_RUNTIME_FUNCTION_ENTRY, UnwindInfoAddress, UnwindData, UnwindData_mut, ::DWORD); +pub type PIMAGE_RUNTIME_FUNCTION_ENTRY = *mut IMAGE_RUNTIME_FUNCTION_ENTRY; +pub const FRAME_FPO: ::WORD = 0; +pub const FRAME_TRAP: ::WORD = 1; +pub const FRAME_TSS: ::WORD = 2; +pub const FRAME_NONFPO: ::WORD = 3; +STRUCT!{struct FPO_DATA { + ulOffStart: ::DWORD, + cbProcSize: ::DWORD, + cdwLocals: ::DWORD, + cdwParams: ::WORD, + bitfield: ::WORD, +}} +pub type PFPO_DATA = *mut FPO_DATA; +pub const SIZEOF_RFPO_DATA: usize = 16; +pub const IMAGE_DEBUG_MISC_EXENAME: ::DWORD = 1; +STRUCT!{struct IMAGE_DEBUG_MISC { + DataType: ::DWORD, + Length: ::DWORD, + Unicode: ::BOOLEAN, + Reserved: [::BYTE; 3], + Data: [::BYTE; 0], +}} +pub type PIMAGE_DEBUG_MISC = *mut IMAGE_DEBUG_MISC; +STRUCT!{struct IMAGE_FUNCTION_ENTRY { + StartingAddress: ::DWORD, + EndingAddress: ::DWORD, + EndOfPrologue: ::DWORD, +}} +pub type PIMAGE_FUNCTION_ENTRY = *mut IMAGE_FUNCTION_ENTRY; +STRUCT!{struct IMAGE_FUNCTION_ENTRY64 { + StartingAddress: ::ULONGLONG, + EndingAddress: ::ULONGLONG, + EndOfPrologueOrUnwindInfoAddress: ::ULONGLONG, +}} +pub type PIMAGE_FUNCTION_ENTRY64 = *mut IMAGE_FUNCTION_ENTRY64; +//18245 +pub const HEAP_NO_SERIALIZE: ::DWORD = 0x00000001; +pub const HEAP_GROWABLE: ::DWORD = 0x00000002; +pub const HEAP_GENERATE_EXCEPTIONS: ::DWORD = 0x00000004; +pub const HEAP_ZERO_MEMORY: ::DWORD = 0x00000008; +pub const HEAP_REALLOC_IN_PLACE_ONLY: ::DWORD = 0x00000010; +pub const HEAP_TAIL_CHECKING_ENABLED: ::DWORD = 0x00000020; +pub const HEAP_FREE_CHECKING_ENABLED: ::DWORD = 0x00000040; +pub const HEAP_DISABLE_COALESCE_ON_FREE: ::DWORD = 0x00000080; +pub const HEAP_CREATE_ALIGN_16: ::DWORD = 0x00010000; +pub const HEAP_CREATE_ENABLE_TRACING: ::DWORD = 0x00020000; +pub const HEAP_CREATE_ENABLE_EXECUTE: ::DWORD = 0x00040000; +pub const HEAP_MAXIMUM_TAG: ::DWORD = 0x0FFF; +pub const HEAP_PSEUDO_TAG_FLAG: ::DWORD = 0x8000; +pub const HEAP_TAG_SHIFT: ::DWORD = 18; +//18145 +STRUCT!{struct RTL_CRITICAL_SECTION_DEBUG { + Type: ::WORD, + CreatorBackTraceIndex: ::WORD, + CriticalSection: *mut ::RTL_CRITICAL_SECTION, + ProcessLocksList: ::LIST_ENTRY, + EntryCount: ::DWORD, + ContentionCount: ::DWORD, + Flags: ::DWORD, + CreatorBackTraceIndexHigh: ::WORD, + SpareWORD: ::WORD, +}} +pub type PRTL_CRITICAL_SECTION_DEBUG = *mut RTL_CRITICAL_SECTION_DEBUG; +pub type RTL_RESOURCE_DEBUG = RTL_CRITICAL_SECTION_DEBUG; +pub type PRTL_RESOURCE_DEBUG = *mut RTL_CRITICAL_SECTION_DEBUG; +pub const RTL_CRITSECT_TYPE: ::WORD = 0; +pub const RTL_RESOURCE_TYPE: ::WORD = 1; +pub const RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO: ::ULONG_PTR = 0x01000000; +pub const RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN: ::ULONG_PTR = 0x02000000; +pub const RTL_CRITICAL_SECTION_FLAG_STATIC_INIT: ::ULONG_PTR = 0x04000000; +pub const RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE: ::ULONG_PTR = 0x08000000; +pub const RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO: ::ULONG_PTR = 0x10000000; +pub const RTL_CRITICAL_SECTION_ALL_FLAG_BITS: ::ULONG_PTR = 0xFF000000; +pub const RTL_CRITICAL_SECTION_FLAG_RESERVED: ::ULONG_PTR = RTL_CRITICAL_SECTION_ALL_FLAG_BITS & !(RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO | RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN | RTL_CRITICAL_SECTION_FLAG_STATIC_INIT | RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE | RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO); +pub const RTL_CRITICAL_SECTION_DEBUG_FLAG_STATIC_INIT: ::DWORD = 0x00000001; +STRUCT!{struct RTL_CRITICAL_SECTION { + DebugInfo: ::PRTL_CRITICAL_SECTION_DEBUG, + LockCount: ::LONG, + RecursionCount: ::LONG, + OwningThread: ::HANDLE, + LockSemaphore: ::HANDLE, + SpinCount: ::ULONG_PTR, +}} +pub type PRTL_CRITICAL_SECTION = *mut RTL_CRITICAL_SECTION; +STRUCT!{struct RTL_SRWLOCK { + Ptr: ::PVOID, +}} +pub type PRTL_SRWLOCK = *mut RTL_SRWLOCK; +pub const RTL_SRWLOCK_INIT: RTL_SRWLOCK = RTL_SRWLOCK { Ptr: 0 as PVOID }; +STRUCT!{struct RTL_CONDITION_VARIABLE { + Ptr: ::PVOID, +}} +pub type PRTL_CONDITION_VARIABLE = *mut RTL_CONDITION_VARIABLE; +pub const RTL_CONDITION_VARIABLE_INIT: RTL_CONDITION_VARIABLE = RTL_CONDITION_VARIABLE { + Ptr: 0 as PVOID +}; +//18204 +pub type PAPCFUNC = Option<unsafe extern "system" fn(Parameter: ::ULONG_PTR)>; +pub type PVECTORED_EXCEPTION_HANDLER = Option<unsafe extern "system" fn( + ExceptionInfo: *mut EXCEPTION_POINTERS, +) -> ::LONG>; +ENUM!{enum HEAP_INFORMATION_CLASS { + HeapCompatibilityInformation = 0, + HeapEnableTerminationOnCorruption = 1, + HeapOptimizeResources = 3, +}} +//pub use self::HEAP_INFORMATION_CLASS::*; +pub const HEAP_OPTIMIZE_RESOURCES_CURRENT_VERSION: ::DWORD = 1; +STRUCT!{struct HEAP_OPTIMIZE_RESOURCES_INFORMATION { + Version: ::DWORD, + Flags: ::DWORD, +}} +pub type PHEAP_OPTIMIZE_RESOURCES_INFORMATION = *mut HEAP_OPTIMIZE_RESOURCES_INFORMATION; +pub const WT_EXECUTEDEFAULT: ::ULONG = 0x00000000; +pub const WT_EXECUTEINIOTHREAD: ::ULONG = 0x00000001; +pub const WT_EXECUTEINUITHREAD: ::ULONG = 0x00000002; +pub const WT_EXECUTEINWAITTHREAD: ::ULONG = 0x00000004; +pub const WT_EXECUTEONLYONCE: ::ULONG = 0x00000008; +pub const WT_EXECUTEINTIMERTHREAD: ::ULONG = 0x00000020; +pub const WT_EXECUTELONGFUNCTION: ::ULONG = 0x00000010; +pub const WT_EXECUTEINPERSISTENTIOTHREAD: ::ULONG = 0x00000040; +pub const WT_EXECUTEINPERSISTENTTHREAD: ::ULONG = 0x00000080; +pub const WT_TRANSFER_IMPERSONATION: ::ULONG = 0x00000100; +pub type WAITORTIMERCALLBACKFUNC = Option<unsafe extern "system" fn(::PVOID, ::BOOLEAN)>; +pub type WORKERCALLBACKFUNC = Option<unsafe extern "system" fn(::PVOID)>; +pub type APC_CALLBACK_FUNCTION = Option<unsafe extern "system" fn(::DWORD, ::PVOID, ::PVOID)>; +pub type WAITORTIMERCALLBACK = WAITORTIMERCALLBACKFUNC; +pub type PFLS_CALLBACK_FUNCTION = Option<unsafe extern "system" fn(lpFlsData: ::PVOID)>; +pub type PSECURE_MEMORY_CACHE_CALLBACK = Option<unsafe extern "system" fn( + Addr: ::PVOID, Range: ::SIZE_T, +) -> ::BOOLEAN>; +pub const WT_EXECUTEINLONGTHREAD: ::ULONG = 0x00000010; +pub const WT_EXECUTEDELETEWAIT: ::ULONG = 0x00000008; +//18570 +pub const KEY_QUERY_VALUE: ::REGSAM = 0x0001; +pub const KEY_SET_VALUE: ::REGSAM = 0x0002; +pub const KEY_CREATE_SUB_KEY: ::REGSAM = 0x0004; +pub const KEY_ENUMERATE_SUB_KEYS: ::REGSAM = 0x0008; +pub const KEY_NOTIFY: ::REGSAM = 0x0010; +pub const KEY_CREATE_LINK: ::REGSAM = 0x0020; +pub const KEY_WOW64_32KEY: ::REGSAM = 0x0200; +pub const KEY_WOW64_64KEY: ::REGSAM = 0x0100; +pub const KEY_WOW64_RES: ::REGSAM = 0x0300; +pub const KEY_READ: ::REGSAM = ( + STANDARD_RIGHTS_READ | + KEY_QUERY_VALUE | + KEY_ENUMERATE_SUB_KEYS | + KEY_NOTIFY + ) & (!SYNCHRONIZE); +pub const KEY_WRITE: ::REGSAM = (STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (!SYNCHRONIZE); +pub const KEY_EXECUTE: ::REGSAM = KEY_READ & (!SYNCHRONIZE); +pub const KEY_ALL_ACCESS: ::REGSAM = ( + STANDARD_RIGHTS_ALL | + KEY_QUERY_VALUE | + KEY_SET_VALUE | + KEY_CREATE_SUB_KEY | + KEY_ENUMERATE_SUB_KEYS | + KEY_NOTIFY | + KEY_CREATE_LINK + ) & (!SYNCHRONIZE); +pub const REG_CREATED_NEW_KEY: ::DWORD = 0x00000001; +pub const REG_OPENED_EXISTING_KEY: ::DWORD = 0x00000002; +pub const REG_NOTIFY_CHANGE_NAME: ::DWORD = 0x00000001; +pub const REG_NOTIFY_CHANGE_ATTRIBUTES: ::DWORD = 0x00000002; +pub const REG_NOTIFY_CHANGE_LAST_SET: ::DWORD = 0x00000004; +pub const REG_NOTIFY_CHANGE_SECURITY: ::DWORD = 0x00000008; +pub const REG_LEGAL_CHANGE_FILTER: ::DWORD = REG_NOTIFY_CHANGE_NAME | + REG_NOTIFY_CHANGE_ATTRIBUTES | + REG_NOTIFY_CHANGE_LAST_SET | + REG_NOTIFY_CHANGE_SECURITY; +pub const REG_NOTIFY_THREAD_AGNOSTIC: ::DWORD = 0x10000000; //supported only on Windows 8 and later +pub const REG_OPTION_RESERVED: ::DWORD = 0x00000000; +pub const REG_OPTION_NON_VOLATILE: ::DWORD = 0x00000000; +pub const REG_OPTION_VOLATILE: ::DWORD = 0x00000001; +pub const REG_OPTION_CREATE_LINK: ::DWORD = 0x00000002; +pub const REG_OPTION_BACKUP_RESTORE: ::DWORD = 0x00000004; +pub const REG_OPTION_OPEN_LINK: ::DWORD = 0x00000008; +pub const REG_NONE: ::DWORD = 0; +pub const REG_SZ: ::DWORD = 1; +pub const REG_EXPAND_SZ: ::DWORD = 2; +pub const REG_BINARY: ::DWORD = 3; +pub const REG_DWORD: ::DWORD = 4; +pub const REG_DWORD_LITTLE_ENDIAN: ::DWORD = 4; +pub const REG_DWORD_BIG_ENDIAN: ::DWORD = 5; +pub const REG_LINK: ::DWORD = 6; +pub const REG_MULTI_SZ: ::DWORD = 7; +pub const REG_RESOURCE_LIST: ::DWORD = 8; +pub const REG_FULL_RESOURCE_DESCRIPTOR: ::DWORD = 9; +pub const REG_RESOURCE_REQUIREMENTS_LIST: ::DWORD = 10; +pub const REG_QWORD: ::DWORD = 11; +pub const REG_QWORD_LITTLE_ENDIAN: ::DWORD = 11; +//18720 +pub const SERVICE_KERNEL_DRIVER: ::DWORD = 0x00000001; +pub const SERVICE_FILE_SYSTEM_DRIVER: ::DWORD = 0x00000002; +pub const SERVICE_ADAPTER: ::DWORD = 0x00000004; +pub const SERVICE_RECOGNIZER_DRIVER: ::DWORD = 0x00000008; +pub const SERVICE_DRIVER: ::DWORD = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER + | SERVICE_RECOGNIZER_DRIVER; +pub const SERVICE_WIN32_OWN_PROCESS: ::DWORD = 0x00000010; +pub const SERVICE_WIN32_SHARE_PROCESS: ::DWORD = 0x00000020; +pub const SERVICE_WIN32: ::DWORD = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS; +pub const SERVICE_INTERACTIVE_PROCESS: ::DWORD = 0x00000100; +pub const SERVICE_TYPE_ALL: ::DWORD = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER + | SERVICE_INTERACTIVE_PROCESS; +STRUCT!{struct TP_CALLBACK_INSTANCE { + dummy: *mut ::c_void, +}} +pub type PTP_CALLBACK_INSTANCE = *mut TP_CALLBACK_INSTANCE; +STRUCT!{struct TP_IO { + dummy: *mut ::c_void, +}} +pub type PTP_IO = *mut TP_IO; +STRUCT!{struct TP_POOL { + dummy: *mut ::c_void, +}} +pub type PTP_POOL = *mut TP_POOL; +STRUCT!{struct TP_CLEANUP_GROUP { + dummy: *mut ::c_void, +}} +pub type PTP_CLEANUP_GROUP = *mut TP_CLEANUP_GROUP; +STRUCT!{struct TP_TIMER { + dummy: *mut ::c_void, +}} +pub type PTP_TIMER = *mut TP_TIMER; +STRUCT!{struct TP_WAIT { + dummy: *mut ::c_void, +}} +pub type PTP_WAIT = *mut TP_WAIT; +STRUCT!{struct TP_WORK { + dummy: *mut ::c_void, +}} +pub type PTP_WORK = *mut TP_WORK; +STRUCT!{struct ACTIVATION_CONTEXT { + dummy: *mut ::c_void, +}} +ENUM!{enum TP_CALLBACK_PRIORITY { + TP_CALLBACK_PRIORITY_HIGH, + TP_CALLBACK_PRIORITY_NORMAL, + TP_CALLBACK_PRIORITY_LOW, + TP_CALLBACK_PRIORITY_INVALID, + TP_CALLBACK_PRIORITY_COUNT = 4, +}} +pub type PTP_CLEANUP_GROUP_CANCEL_CALLBACK = Option<unsafe extern "system" fn( + ObjectContext: ::PVOID, CleanupContext: ::PVOID, +)>; +pub type PTP_SIMPLE_CALLBACK = Option<unsafe extern "system" fn( + Instance: PTP_CALLBACK_INSTANCE, Context: ::PVOID, +)>; +pub type PTP_WORK_CALLBACK = Option<unsafe extern "system" fn( + Instance: PTP_CALLBACK_INSTANCE, Context: ::PVOID, Work: PTP_WORK, +)>; +pub type PTP_TIMER_CALLBACK = Option<unsafe extern "system" fn( + Instance: PTP_CALLBACK_INSTANCE, Context: ::PVOID, Timer: PTP_TIMER, +)>; +pub type TP_WAIT_RESULT = ::DWORD; +pub type PTP_WAIT_CALLBACK = Option<unsafe extern "system" fn( + Instance: PTP_CALLBACK_INSTANCE, Context: ::PVOID, Wait: PTP_WAIT, WaitResult: TP_WAIT_RESULT, +)>; +pub type TP_VERSION = ::DWORD; +pub type PTP_VERSION = *mut ::DWORD; +STRUCT!{struct TP_POOL_STACK_INFORMATION { + StackReserve: ::SIZE_T, + StackCommit: ::SIZE_T, +}} +pub type PTP_POOL_STACK_INFORMATION = *mut TP_POOL_STACK_INFORMATION; +STRUCT!{struct TP_CALLBACK_ENVIRON_V3_s { + BitFields: ::DWORD, +}} +BITFIELD!(TP_CALLBACK_ENVIRON_V3_s BitFields: ::DWORD [ + LongFunction set_LongFunction[0..1], + Persistent set_Persistent[1..2], + Private set_Private[2..32], +]); +STRUCT!{nodebug struct TP_CALLBACK_ENVIRON_V3 { + Version: TP_VERSION, + Pool: PTP_POOL, + CleanupGroup: PTP_CLEANUP_GROUP, + CleanupGroupCancelCallback: PTP_CLEANUP_GROUP_CANCEL_CALLBACK, + RaceDll: ::PVOID, + ActivationContext: *mut ACTIVATION_CONTEXT, + FinalizationCallback: PTP_SIMPLE_CALLBACK, + u: ::DWORD, + CallbackPriority: TP_CALLBACK_PRIORITY, + Size: ::DWORD, +}} +UNION!(TP_CALLBACK_ENVIRON_V3, u, Flags, Flags_mut, ::DWORD); +UNION!(TP_CALLBACK_ENVIRON_V3, u, s, s_mut, TP_CALLBACK_ENVIRON_V3_s); +pub type TP_CALLBACK_ENVIRON = TP_CALLBACK_ENVIRON_V3; +pub type PTP_CALLBACK_ENVIRON = *mut TP_CALLBACK_ENVIRON_V3; +STRUCT!{struct JOB_SET_ARRAY { + JobHandle: ::HANDLE, + MemberLevel: ::DWORD, + Flags: ::DWORD, +}} +pub type PJOB_SET_ARRAY = *mut JOB_SET_ARRAY; +STRUCT!{struct RTL_BARRIER { + Reserved1: ::DWORD, + Reserved2: ::DWORD, + Reserved3: [::ULONG_PTR; 2], + Reserved4: ::DWORD, + Reserved5: ::DWORD, +}} +pub type PRTL_BARRIER = *mut RTL_BARRIER; +STRUCT!{struct RTL_RUN_ONCE { + Ptr: ::PVOID, +}} +pub type PRTL_RUN_ONCE = *mut RTL_RUN_ONCE; +ENUM!{enum RTL_UMS_THREAD_INFO_CLASS { + UmsThreadInvalidInfoClass = 0, + UmsThreadUserContext, + UmsThreadPriority, // Reserved + UmsThreadAffinity, // Reserved + UmsThreadTeb, + UmsThreadIsSuspended, + UmsThreadIsTerminated, + UmsThreadMaxInfoClass, +}} +ENUM!{enum RTL_UMS_SCHEDULER_REASON { + UmsSchedulerStartup = 0, + UmsSchedulerThreadBlocked, + UmsSchedulerThreadYield, +}} +pub type PRTL_UMS_SCHEDULER_ENTRY_POINT = Option<unsafe extern "system" fn( + Reason: RTL_UMS_SCHEDULER_REASON, ActivationPayload: ::ULONG_PTR, SchedulerParam: ::PVOID, +)>; +ENUM!{enum FIRMWARE_TYPE { + FirmwareTypeUnknown, + FirmwareTypeBios, + FirmwareTypeUefi, + FirmwareTypeMax, +}} +pub type PFIRMWARE_TYPE = *mut FIRMWARE_TYPE; +ENUM!{enum LOGICAL_PROCESSOR_RELATIONSHIP { + RelationProcessorCore, + RelationNumaNode, + RelationCache, + RelationProcessorPackage, + RelationGroup, + RelationAll = 0xffff, +}} +ENUM!{enum PROCESSOR_CACHE_TYPE { + CacheUnified, + CacheInstruction, + CacheData, + CacheTrace, +}} +STRUCT!{struct CACHE_DESCRIPTOR { + Level: ::BYTE, + Associativity: ::BYTE, + LineSize: ::WORD, + Size: ::DWORD, + Type: PROCESSOR_CACHE_TYPE, +}} +pub type PCACHE_DESCRIPTOR = *mut CACHE_DESCRIPTOR; +STRUCT!{struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_ProcessorCore { + Flags: ::BYTE, +}} +STRUCT!{struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_NumaNode { + NodeNumber: ::DWORD, +}} +STRUCT!{struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION { + ProcessorMask: ::ULONG_PTR, + Relationship: LOGICAL_PROCESSOR_RELATIONSHIP, + Reserved: [::ULONGLONG; 2], +}} +UNION!( + SYSTEM_LOGICAL_PROCESSOR_INFORMATION, Reserved, ProcessorCore, ProcessorCore_mut, + SYSTEM_LOGICAL_PROCESSOR_INFORMATION_ProcessorCore +); +UNION!( + SYSTEM_LOGICAL_PROCESSOR_INFORMATION, Reserved, NumaNode, NumaNode_mut, + SYSTEM_LOGICAL_PROCESSOR_INFORMATION_NumaNode +); +UNION!(SYSTEM_LOGICAL_PROCESSOR_INFORMATION, Reserved, Cache, Cache_mut, CACHE_DESCRIPTOR); +pub type PSYSTEM_LOGICAL_PROCESSOR_INFORMATION = *mut SYSTEM_LOGICAL_PROCESSOR_INFORMATION; +STRUCT!{struct SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION { + CycleTime: ::DWORD64, +}} +pub type PSYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION = *mut SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION; +ENUM!{enum HARDWARE_COUNTER_TYPE { + PMCCounter, + MaxHardwareCounterType, +}} +pub type PHARDWARE_COUNTER_TYPE = *mut HARDWARE_COUNTER_TYPE; +ENUM!{enum PROCESS_MITIGATION_POLICY { + ProcessDEPPolicy, + ProcessASLRPolicy, + ProcessDynamicCodePolicy, + ProcessStrictHandleCheckPolicy, + ProcessSystemCallDisablePolicy, + ProcessMitigationOptionsMask, + ProcessExtensionPointDisablePolicy, + ProcessReserved1Policy, + ProcessSignaturePolicy, + MaxProcessMitigationPolicy, +}} +STRUCT!{nodebug struct OSVERSIONINFOA { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::CHAR; 128], +}} +pub type POSVERSIONINFOA = *mut OSVERSIONINFOA; +pub type LPOSVERSIONINFOA = *mut OSVERSIONINFOA; +STRUCT!{nodebug struct OSVERSIONINFOW { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::WCHAR; 128], +}} +pub type POSVERSIONINFOW = *mut OSVERSIONINFOW; +pub type LPOSVERSIONINFOW = *mut OSVERSIONINFOW; +STRUCT!{nodebug struct OSVERSIONINFOEXA { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::CHAR; 128], + wServicePackMajor: ::WORD, + wServicePackMinor: ::WORD, + wSuiteMask: ::WORD, + wProductType: ::BYTE, + wReserved: ::BYTE, +}} +pub type POSVERSIONINFOEXA = *mut OSVERSIONINFOEXA; +pub type LPOSVERSIONINFOEXA = *mut OSVERSIONINFOEXA; +STRUCT!{nodebug struct OSVERSIONINFOEXW { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::WCHAR; 128], + wServicePackMajor: ::WORD, + wServicePackMinor: ::WORD, + wSuiteMask: ::WORD, + wProductType: ::BYTE, + wReserved: ::BYTE, +}} +pub type POSVERSIONINFOEXW = *mut OSVERSIONINFOEXW; +pub type LPOSVERSIONINFOEXW = *mut OSVERSIONINFOEXW; +STRUCT!{struct SLIST_ENTRY { + Next: *mut SLIST_ENTRY, +}} +pub type PSLIST_ENTRY = *mut SLIST_ENTRY; +STRUCT!{struct SLIST_HEADER_HeaderX64 { + BitFields1: ::ULONGLONG, + BitFields2: ::ULONGLONG, +}} +BITFIELD!(SLIST_HEADER_HeaderX64 BitFields1: ::ULONGLONG [ + Depth set_Depth[0..16], + Sequence set_Sequence[16..64], +]); +BITFIELD!(SLIST_HEADER_HeaderX64 BitFields2: ::ULONGLONG [ + Reserved set_Reserved[0..4], + NextEntry set_NextEntry[4..64], +]); +STRUCT!{struct SLIST_HEADER { + Alignment: ::ULONGLONG, + Region: ::ULONGLONG, +}} +UNION!(SLIST_HEADER, Alignment, HeaderX64, HeaderX64_mut, SLIST_HEADER_HeaderX64); +pub type PSLIST_HEADER = *mut SLIST_HEADER; +ENUM!{enum SYSTEM_POWER_STATE { + PowerSystemUnspecified = 0, + PowerSystemWorking = 1, + PowerSystemSleeping1 = 2, + PowerSystemSleeping2 = 3, + PowerSystemSleeping3 = 4, + PowerSystemHibernate = 5, + PowerSystemShutdown = 6, + PowerSystemMaximum = 7, +}} +pub type PSYSTEM_POWER_STATE = *mut SYSTEM_POWER_STATE; +ENUM!{enum POWER_ACTION { + PowerActionNone = 0, + PowerActionReserved, + PowerActionSleep, + PowerActionHibernate, + PowerActionShutdown, + PowerActionShutdownReset, + PowerActionShutdownOff, + PowerActionWarmEject, +}} +pub type PPOWER_ACTION = *mut POWER_ACTION; +ENUM!{enum DEVICE_POWER_STATE { + PowerDeviceUnspecified = 0, + PowerDeviceD0, + PowerDeviceD1, + PowerDeviceD2, + PowerDeviceD3, + PowerDeviceMaximum, +}} +pub type PDEVICE_POWER_STATE = *mut DEVICE_POWER_STATE; +ENUM!{enum MONITOR_DISPLAY_STATE { + PowerMonitorOff = 0, + PowerMonitorOn, + PowerMonitorDim, +}} +pub type PMONITOR_DISPLAY_STATE = *mut MONITOR_DISPLAY_STATE; +ENUM!{enum USER_ACTIVITY_PRESENCE { + PowerUserPresent = 0, + PowerUserNotPresent, + PowerUserInactive, + PowerUserMaximum, + //PowerUserInvalid = 3, +}} +pub type PUSER_ACTIVITY_PRESENCE = *mut USER_ACTIVITY_PRESENCE; +pub type EXECUTION_STATE = ::DWORD; +pub type PEXECUTION_STATE = *mut ::DWORD; +ENUM!{enum LATENCY_TIME { + LT_DONT_CARE, + LT_LOWEST_LATENCY, +}} +ENUM!{enum POWER_REQUEST_TYPE { + PowerRequestDisplayRequired, + PowerRequestSystemRequired, + PowerRequestAwayModeRequired, + PowerRequestExecutionRequired, +}} +pub type PPOWER_REQUEST_TYPE = *mut POWER_REQUEST_TYPE; +pub const MAX_HW_COUNTERS: usize = 16; +STRUCT!{struct HARDWARE_COUNTER_DATA { + Type: HARDWARE_COUNTER_TYPE, + Reserved: ::DWORD, + Value: ::DWORD64, +}} +pub type PHARDWARE_COUNTER_DATA = *mut HARDWARE_COUNTER_DATA; +STRUCT!{struct PERFORMANCE_DATA { + Size: ::WORD, + Version: ::BYTE, + HwCountersCount: ::BYTE, + ContextSwitchCount: ::DWORD, + WaitReasonBitMap: ::DWORD64, + CycleTime: ::DWORD64, + RetryCount: ::DWORD, + Reserved: ::DWORD, + HwCounters: [HARDWARE_COUNTER_DATA; MAX_HW_COUNTERS], +}} +pub type PPERFORMANCE_DATA = *mut PERFORMANCE_DATA; +STRUCT!{struct MEMORY_BASIC_INFORMATION { + BaseAddress: ::PVOID, + AllocationBase: ::PVOID, + AllocationProtect: ::DWORD, + RegionSize: ::SIZE_T, + State: ::DWORD, + Protect: ::DWORD, + Type: ::DWORD, +}} +pub type PMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; +STRUCT!{struct MEMORY_BASIC_INFORMATION32 { + BaseAddress: ::DWORD, + AllocationBase: ::DWORD, + AllocationProtect: ::DWORD, + RegionSize: ::DWORD, + State: ::DWORD, + Protect: ::DWORD, + Type: ::DWORD, +}} +pub type PMEMORY_BASIC_INFORMATION32 = *mut MEMORY_BASIC_INFORMATION32; +STRUCT!{struct MEMORY_BASIC_INFORMATION64 { // FIXME: align 16 + BaseAddress: ::ULONGLONG, + AllocationBase: ::ULONGLONG, + AllocationProtect: ::DWORD, + __alignment1: ::DWORD, + RegionSize: ::ULONGLONG, + State: ::DWORD, + Protect: ::DWORD, + Type: ::DWORD, + __alignment2: ::DWORD, +}} +pub type PMEMORY_BASIC_INFORMATION64 = *mut MEMORY_BASIC_INFORMATION64; +pub const WOW64_SIZE_OF_80387_REGISTERS: usize = 80; +pub const WOW64_MAXIMUM_SUPPORTED_EXTENSION: usize = 512; +STRUCT!{nodebug struct WOW64_FLOATING_SAVE_AREA { + ControlWord: ::DWORD, + StatusWord: ::DWORD, + TagWord: ::DWORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::DWORD, + DataOffset: ::DWORD, + DataSelector: ::DWORD, + RegisterArea: [::BYTE; WOW64_SIZE_OF_80387_REGISTERS], + Cr0NpxState: ::DWORD, +}} +pub type PWOW64_FLOATING_SAVE_AREA = *mut WOW64_FLOATING_SAVE_AREA; +STRUCT!{nodebug struct WOW64_CONTEXT { + ContextFlags: ::DWORD, + Dr0: ::DWORD, + Dr1: ::DWORD, + Dr2: ::DWORD, + Dr3: ::DWORD, + Dr4: ::DWORD, + Dr5: ::DWORD, + Dr6: ::DWORD, + Dr7: ::DWORD, + FloatSave: WOW64_FLOATING_SAVE_AREA, + SegGs: ::DWORD, + SegFs: ::DWORD, + SegEs: ::DWORD, + SegDs: ::DWORD, + Edi: ::DWORD, + Esi: ::DWORD, + Ebx: ::DWORD, + Edx: ::DWORD, + Ecx: ::DWORD, + Eax: ::DWORD, + Ebp: ::DWORD, + Eip: ::DWORD, + SegCs: ::DWORD, + EFlags: ::DWORD, + Esp: ::DWORD, + SegSs: ::DWORD, + ExtendedRegisters: [::BYTE; WOW64_MAXIMUM_SUPPORTED_EXTENSION], +}} +pub type PWOW64_CONTEXT = *mut WOW64_CONTEXT; +STRUCT!{struct WOW64_LDT_ENTRY_Bytes { + BaseMid: ::BYTE, + Flags1: ::BYTE, + Flags2: ::BYTE, + BaseHi: ::BYTE, +}} +STRUCT!{struct WOW64_LDT_ENTRY_Bits { + BitFields: ::DWORD, +}} +BITFIELD!(WOW64_LDT_ENTRY_Bits BitFields: ::DWORD [ + BaseMid set_BaseMid[0..8], + Type set_Type[8..13], + Dpl set_Dpl[13..15], + Pres set_Pres[15..16], + LimitHi set_LimitHi[16..20], + Sys set_Sys[20..21], + Reserved_0 set_Reserved_0[21..22], + Default_Big set_Default_Big[22..23], + Granularity set_Granularity[23..24], + BaseHi set_BaseHi[24..32], +]); +STRUCT!{struct WOW64_LDT_ENTRY { + LimitLow: ::WORD, + BaseLow: ::WORD, + HighWord: ::DWORD, +}} +UNION!(WOW64_LDT_ENTRY, HighWord, Bytes, Bytes_mut, WOW64_LDT_ENTRY_Bytes); +UNION!(WOW64_LDT_ENTRY, HighWord, Bits, Bits_mut, WOW64_LDT_ENTRY_Bits); +pub type PWOW64_LDT_ENTRY = *mut WOW64_LDT_ENTRY; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winreg.rs b/bash-5.1/vendor/winapi-0.2.8/src/winreg.rs new file mode 100644 index 0000000..91ef168 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winreg.rs @@ -0,0 +1,41 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +use super::*; +pub type REGSAM = ACCESS_MASK; +STRUCT!{struct VALENTA { + ve_valuename: LPSTR, + ve_valuelen: DWORD, + ve_valueptr: DWORD_PTR, + ve_type: DWORD, +}} +pub type PVALENTA = *mut VALENTA; +STRUCT!{struct VALENTW { + ve_valuename: LPWSTR, + ve_valuelen: DWORD, + ve_valueptr: DWORD_PTR, + ve_type: DWORD, +}} +pub type PVALENTW = *mut VALENTW; +pub const HKEY_CLASSES_ROOT: HKEY = 0x80000000 as HKEY; +pub const HKEY_CURRENT_USER: HKEY = 0x80000001 as HKEY; +pub const HKEY_LOCAL_MACHINE: HKEY = 0x80000002 as HKEY; +pub const HKEY_USERS: HKEY = 0x80000003 as HKEY; +pub const HKEY_PERFORMANCE_DATA: HKEY = 0x80000004 as HKEY; +pub const HKEY_PERFORMANCE_TEXT: HKEY = 0x80000050 as HKEY; +pub const HKEY_PERFORMANCE_NLSTEXT: HKEY = 0x80000060 as HKEY; +pub const HKEY_CURRENT_CONFIG: HKEY = 0x80000005 as HKEY; +pub const HKEY_DYN_DATA: HKEY = 0x80000006 as HKEY; +pub const HKEY_CURRENT_USER_LOCAL_SETTINGS: HKEY = 0x80000007 as HKEY; +pub const REG_MUI_STRING_TRUNCATE: DWORD = 0x00000001; +pub const RRF_RT_REG_NONE: DWORD = 0x00000001; +pub const RRF_RT_REG_SZ: DWORD = 0x00000002; +pub const RRF_RT_REG_EXPAND_SZ: DWORD = 0x00000004; +pub const RRF_RT_REG_BINARY: DWORD = 0x00000008; +pub const RRF_RT_REG_DWORD: DWORD = 0x00000010; +pub const RRF_RT_REG_MULTI_SZ: DWORD = 0x00000020; +pub const RRF_RT_REG_QWORD: DWORD = 0x00000040; +pub const RRF_RT_DWORD: DWORD = RRF_RT_REG_BINARY|RRF_RT_REG_DWORD; +pub const RRF_RT_QWORD: DWORD = RRF_RT_REG_BINARY|RRF_RT_REG_QWORD; +pub const RRF_RT_ANY: DWORD = 0x0000ffff; +pub const RRF_NOEXPAND: DWORD = 0x10000000; +pub const RRF_ZEROONFAILURE: DWORD = 0x20000000; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winscard.rs b/bash-5.1/vendor/winapi-0.2.8/src/winscard.rs new file mode 100644 index 0000000..7d20c2d --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winscard.rs @@ -0,0 +1,269 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Data Protection API Prototypes and Definitions +// This header file provides the definitions and symbols necessary for an +// Application or Smart Card Service Provider to access the Smartcard Subsystem. +pub type LPCBYTE = *const ::BYTE; +pub type SCARDCONTEXT = ::ULONG_PTR; +pub type PSCARDCONTEXT = *mut SCARDCONTEXT; +pub type LPSCARDCONTEXT = *mut SCARDCONTEXT; +pub type SCARDHANDLE = ::ULONG_PTR; +pub type PSCARDHANDLE = *mut SCARDHANDLE; +pub type LPSCARDHANDLE = *mut SCARDHANDLE; +pub const SCARD_AUTOALLOCATE: ::DWORD = -1i32 as ::DWORD; +pub const SCARD_SCOPE_USER: ::DWORD = 0; +pub const SCARD_SCOPE_TERMINAL: ::DWORD = 1; +pub const SCARD_SCOPE_SYSTEM: ::DWORD = 2; +pub const SCARD_PROVIDER_PRIMARY: ::DWORD = 1; +pub const SCARD_PROVIDER_CSP: ::DWORD = 2; +pub const SCARD_PROVIDER_KSP: ::DWORD = 3; +STRUCT!{nodebug struct SCARD_READERSTATEA { + szReader: ::LPCSTR, + pvUserData: ::LPVOID, + dwCurrentState: ::DWORD, + dwEventState: ::DWORD, + cbAtr: ::DWORD, + rgbAtr: [::BYTE; 36], +}} +pub type PSCARD_READERSTATEA = *mut SCARD_READERSTATEA; +pub type LPSCARD_READERSTATEA = *mut SCARD_READERSTATEA; +STRUCT!{nodebug struct SCARD_READERSTATEW { + szReader: ::LPCWSTR, + pvUserData: ::LPVOID, + dwCurrentState: ::DWORD, + dwEventState: ::DWORD, + cbAtr: ::DWORD, + rgbAtr: [::BYTE; 36], +}} +pub type PSCARD_READERSTATEW = *mut SCARD_READERSTATEW; +pub type LPSCARD_READERSTATEW = *mut SCARD_READERSTATEW; +pub type SCARD_READERSTATE_A = SCARD_READERSTATEA; +pub type SCARD_READERSTATE_W = SCARD_READERSTATEW; +pub type PSCARD_READERSTATE_A = PSCARD_READERSTATEA; +pub type PSCARD_READERSTATE_W = PSCARD_READERSTATEW; +pub type LPSCARD_READERSTATE_A = LPSCARD_READERSTATEA; +pub type LPSCARD_READERSTATE_W = LPSCARD_READERSTATEW; +pub const SCARD_STATE_UNAWARE: ::DWORD = 0x00000000; +pub const SCARD_STATE_IGNORE: ::DWORD = 0x00000001; +pub const SCARD_STATE_CHANGED: ::DWORD = 0x00000002; +pub const SCARD_STATE_UNKNOWN: ::DWORD = 0x00000004; +pub const SCARD_STATE_UNAVAILABLE: ::DWORD = 0x00000008; +pub const SCARD_STATE_EMPTY: ::DWORD = 0x00000010; +pub const SCARD_STATE_PRESENT: ::DWORD = 0x00000020; +pub const SCARD_STATE_ATRMATCH: ::DWORD = 0x00000040; +pub const SCARD_STATE_EXCLUSIVE: ::DWORD = 0x00000080; +pub const SCARD_STATE_INUSE: ::DWORD = 0x00000100; +pub const SCARD_STATE_MUTE: ::DWORD = 0x00000200; +pub const SCARD_STATE_UNPOWERED: ::DWORD = 0x00000400; +STRUCT!{nodebug struct SCARD_ATRMASK { + cbAtr: ::DWORD, + rgbAtr: [::BYTE; 36], + rgbMask: [::BYTE; 36], +}} +pub type PSCARD_ATRMASK = *mut SCARD_ATRMASK; +pub type LPSCARD_ATRMASK = *mut SCARD_ATRMASK; +pub const SCARD_SHARE_EXCLUSIVE: ::DWORD = 1; +pub const SCARD_SHARE_SHARED: ::DWORD = 2; +pub const SCARD_SHARE_DIRECT: ::DWORD = 3; +pub const SCARD_LEAVE_CARD: ::DWORD = 0; +pub const SCARD_RESET_CARD: ::DWORD = 1; +pub const SCARD_UNPOWER_CARD: ::DWORD = 2; +pub const SCARD_EJECT_CARD: ::DWORD = 3; +pub const SC_DLG_MINIMAL_UI: ::DWORD = 0x01; +pub const SC_DLG_NO_UI: ::DWORD = 0x02; +pub const SC_DLG_FORCE_UI: ::DWORD = 0x04; +pub const SCERR_NOCARDNAME: ::DWORD = 0x4000; +pub const SCERR_NOGUIDS: ::DWORD = 0x8000; +pub type LPOCNCONNPROCA = Option<unsafe extern "system" fn( + SCARDCONTEXT, ::LPSTR, ::LPSTR, ::PVOID, +) -> SCARDHANDLE>; +pub type LPOCNCONNPROCW = Option<unsafe extern "system" fn( + SCARDCONTEXT, ::LPWSTR, ::LPWSTR, ::PVOID, +) -> SCARDHANDLE>; +pub type LPOCNCHKPROC = Option<unsafe extern "system" fn( + SCARDCONTEXT, SCARDHANDLE, ::PVOID, +) -> ::BOOL>; +pub type LPOCNDSCPROC = Option<unsafe extern "system" fn(SCARDCONTEXT, SCARDHANDLE, ::PVOID)>; +STRUCT!{nodebug struct OPENCARD_SEARCH_CRITERIAA { + dwStructSize: ::DWORD, + lpstrGroupNames: ::LPSTR, + nMaxGroupNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrCardNames: ::LPSTR, + nMaxCardNames: ::DWORD, + lpfnCheck: LPOCNCHKPROC, + lpfnConnect: LPOCNCONNPROCA, + lpfnDisconnect: LPOCNDSCPROC, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, +}} +pub type POPENCARD_SEARCH_CRITERIAA = *mut OPENCARD_SEARCH_CRITERIAA; +pub type LPOPENCARD_SEARCH_CRITERIAA = *mut OPENCARD_SEARCH_CRITERIAA; +STRUCT!{nodebug struct OPENCARD_SEARCH_CRITERIAW { + dwStructSize: ::DWORD, + lpstrGroupNames: ::LPWSTR, + nMaxGroupNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrCardNames: ::LPWSTR, + nMaxCardNames: ::DWORD, + lpfnCheck: LPOCNCHKPROC, + lpfnConnect: LPOCNCONNPROCW, + lpfnDisconnect: LPOCNDSCPROC, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, +}} +pub type POPENCARD_SEARCH_CRITERIAW = *mut OPENCARD_SEARCH_CRITERIAW; +pub type LPOPENCARD_SEARCH_CRITERIAW = *mut OPENCARD_SEARCH_CRITERIAW; +STRUCT!{nodebug struct OPENCARDNAME_EXA { + dwStructSize: ::DWORD, + hSCardContext: SCARDCONTEXT, + hwndOwner: ::HWND, + dwFlags: ::DWORD, + lpstrTitle: ::LPCSTR, + lpstrSearchDesc: ::LPCSTR, + hIcon: ::HICON, + pOpenCardSearchCriteria: POPENCARD_SEARCH_CRITERIAA, + lpfnConnect: LPOCNCONNPROCA, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + lpstrRdr: ::LPSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPSTR, + nMaxCard: ::DWORD, + dwActiveProtocol: ::DWORD, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAME_EXA = *mut OPENCARDNAME_EXA; +pub type LPOPENCARDNAME_EXA = *mut OPENCARDNAME_EXA; +STRUCT!{nodebug struct OPENCARDNAME_EXW { + dwStructSize: ::DWORD, + hSCardContext: SCARDCONTEXT, + hwndOwner: ::HWND, + dwFlags: ::DWORD, + lpstrTitle: ::LPCWSTR, + lpstrSearchDesc: ::LPCWSTR, + hIcon: ::HICON, + pOpenCardSearchCriteria: POPENCARD_SEARCH_CRITERIAW, + lpfnConnect: LPOCNCONNPROCW, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + lpstrRdr: ::LPWSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPWSTR, + nMaxCard: ::DWORD, + dwActiveProtocol: ::DWORD, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAME_EXW = *mut OPENCARDNAME_EXW; +pub type LPOPENCARDNAME_EXW = *mut OPENCARDNAME_EXW; +pub type OPENCARDNAMEA_EX = OPENCARDNAME_EXA; +pub type OPENCARDNAMEW_EX = OPENCARDNAME_EXW; +pub type POPENCARDNAMEA_EX = POPENCARDNAME_EXA; +pub type POPENCARDNAMEW_EX = POPENCARDNAME_EXW; +pub type LPOPENCARDNAMEA_EX = LPOPENCARDNAME_EXA; +pub type LPOPENCARDNAMEW_EX = LPOPENCARDNAME_EXW; +pub const SCARD_READER_SEL_AUTH_PACKAGE: ::DWORD = -629i32 as ::DWORD; +ENUM!{enum READER_SEL_REQUEST_MATCH_TYPE { + RSR_MATCH_TYPE_READER_AND_CONTAINER = 1, + RSR_MATCH_TYPE_SERIAL_NUMBER, + RSR_MATCH_TYPE_ALL_CARDS, +}} +STRUCT!{struct READER_SEL_REQUEST_ReaderAndContainerParameter { + cbReaderNameOffset: ::DWORD, + cchReaderNameLength: ::DWORD, + cbContainerNameOffset: ::DWORD, + cchContainerNameLength: ::DWORD, + dwDesiredCardModuleVersion: ::DWORD, + dwCspFlags: ::DWORD, +}} +STRUCT!{struct READER_SEL_REQUEST_SerialNumberParameter { + cbSerialNumberOffset: ::DWORD, + cbSerialNumberLength: ::DWORD, + dwDesiredCardModuleVersion: ::DWORD, +}} +STRUCT!{struct READER_SEL_REQUEST { + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + MatchType: READER_SEL_REQUEST_MATCH_TYPE, + ReaderAndContainerParameter: READER_SEL_REQUEST_ReaderAndContainerParameter, +}} +UNION!( + READER_SEL_REQUEST, ReaderAndContainerParameter, SerialNumberParameter, + SerialNumberParameter_mut, READER_SEL_REQUEST_SerialNumberParameter +); +pub type PREADER_SEL_REQUEST = *mut READER_SEL_REQUEST; +STRUCT!{struct READER_SEL_RESPONSE { + cbReaderNameOffset: ::DWORD, + cchReaderNameLength: ::DWORD, + cbCardNameOffset: ::DWORD, + cchCardNameLength: ::DWORD, +}} +pub type PREADER_SEL_RESPONSE = *mut READER_SEL_RESPONSE; +STRUCT!{nodebug struct OPENCARDNAMEA { + dwStructSize: ::DWORD, + hwndOwner: ::HWND, + hSCardContext: SCARDCONTEXT, + lpstrGroupNames: ::LPSTR, + nMaxGroupNames: ::DWORD, + lpstrCardNames: ::LPSTR, + nMaxCardNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrRdr: ::LPSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPSTR, + nMaxCard: ::DWORD, + lpstrTitle: ::LPCSTR, + dwFlags: ::DWORD, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + dwActiveProtocol: ::DWORD, + lpfnConnect: LPOCNCONNPROCA, + lpfnCheck: LPOCNCHKPROC, + lpfnDisconnect: LPOCNDSCPROC, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAMEA = *mut OPENCARDNAMEA; +pub type LPOPENCARDNAMEA = *mut OPENCARDNAMEA; +STRUCT!{nodebug struct OPENCARDNAMEW { + dwStructSize: ::DWORD, + hwndOwner: ::HWND, + hSCardContext: SCARDCONTEXT, + lpstrGroupNames: ::LPWSTR, + nMaxGroupNames: ::DWORD, + lpstrCardNames: ::LPWSTR, + nMaxCardNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrRdr: ::LPWSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPWSTR, + nMaxCard: ::DWORD, + lpstrTitle: ::LPCWSTR, + dwFlags: ::DWORD, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + dwActiveProtocol: ::DWORD, + lpfnConnect: LPOCNCONNPROCW, + lpfnCheck: LPOCNCHKPROC, + lpfnDisconnect: LPOCNDSCPROC, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAMEW = *mut OPENCARDNAMEW; +pub type LPOPENCARDNAMEW = *mut OPENCARDNAMEW; +pub type OPENCARDNAME_A = OPENCARDNAMEA; +pub type OPENCARDNAME_W = OPENCARDNAMEW; +pub type POPENCARDNAME_A = POPENCARDNAMEA; +pub type POPENCARDNAME_W = POPENCARDNAMEW; +pub type LPOPENCARDNAME_A = LPOPENCARDNAMEA; +pub type LPOPENCARDNAME_W = LPOPENCARDNAMEW; +pub const SCARD_AUDIT_CHV_FAILURE: ::DWORD = 0x0; +pub const SCARD_AUDIT_CHV_SUCCESS: ::DWORD = 0x1; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winsmcrd.rs b/bash-5.1/vendor/winapi-0.2.8/src/winsmcrd.rs new file mode 100644 index 0000000..28f3474 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winsmcrd.rs @@ -0,0 +1,157 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +// Smart Card class/port IOCTL codes. +pub type UWORD = ::WORD; +DEFINE_GUID!(GUID_DEVINTERFACE_SMARTCARD_READER, 0x50DD5230, 0xBA8A, 0x11D1, + 0xBF, 0x5D, 0x00, 0x00, 0xF8, 0x05, 0xF5, 0x30); +pub const SCARD_ATR_LENGTHL: ::DWORD = 33; +pub const SCARD_PROTOCOL_UNDEFINED: ::DWORD = 0x00000000; +pub const SCARD_PROTOCOL_T0: ::DWORD = 0x00000001; +pub const SCARD_PROTOCOL_T1: ::DWORD = 0x00000002; +pub const SCARD_PROTOCOL_RAW: ::DWORD = 0x00010000; +pub const SCARD_PROTOCOL_Tx: ::DWORD = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1; +pub const SCARD_PROTOCOL_DEFAULT: ::DWORD = 0x80000000; +pub const SCARD_PROTOCOL_OPTIMAL: ::DWORD = 0x00000000; +pub const SCARD_POWER_DOWN: ::DWORD = 0; +pub const SCARD_COLD_RESET: ::DWORD = 1; +pub const SCARD_WARM_RESET: ::DWORD = 2; +pub const IOCTL_SMARTCARD_POWER: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 1, ::METHOD_BUFFERED, + ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_ATTRIBUTE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 2, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_SET_ATTRIBUTE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 3, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_CONFISCATE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 4, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_TRANSMIT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 5, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_EJECT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 6, ::METHOD_BUFFERED, + ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_SWALLOW: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 7, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_IS_PRESENT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 10, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_IS_ABSENT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 11, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_SET_PROTOCOL: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 12, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_STATE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 14, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_LAST_ERROR: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 15, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_PERF_CNTR: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 16, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const MAXIMUM_ATTR_STRING_LENGTH: ::DWORD = 32; +pub const MAXIMUM_SMARTCARD_READERS: ::DWORD = 10; +pub const SCARD_CLASS_VENDOR_INFO: ::ULONG = 1; +pub const SCARD_CLASS_COMMUNICATIONS: ::ULONG = 2; +pub const SCARD_CLASS_PROTOCOL: ::ULONG = 3; +pub const SCARD_CLASS_POWER_MGMT: ::ULONG = 4; +pub const SCARD_CLASS_SECURITY: ::ULONG = 5; +pub const SCARD_CLASS_MECHANICAL: ::ULONG = 6; +pub const SCARD_CLASS_VENDOR_DEFINED: ::ULONG = 7; +pub const SCARD_CLASS_IFD_PROTOCOL: ::ULONG = 8; +pub const SCARD_CLASS_ICC_STATE: ::ULONG = 9; +pub const SCARD_CLASS_PERF: ::ULONG = 0x7ffe; +pub const SCARD_CLASS_SYSTEM: ::ULONG = 0x7fff; +pub const SCARD_ATTR_VENDOR_NAME: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0100; +pub const SCARD_ATTR_VENDOR_IFD_TYPE: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0101; +pub const SCARD_ATTR_VENDOR_IFD_VERSION: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0102; +pub const SCARD_ATTR_VENDOR_IFD_SERIAL_NO: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0103; +pub const SCARD_ATTR_CHANNEL_ID: ::ULONG = SCARD_CLASS_COMMUNICATIONS << 16 | 0x0110; +pub const SCARD_ATTR_PROTOCOL_TYPES: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0120; +pub const SCARD_ATTR_DEFAULT_CLK: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0121; +pub const SCARD_ATTR_MAX_CLK: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0122; +pub const SCARD_ATTR_DEFAULT_DATA_RATE: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0123; +pub const SCARD_ATTR_MAX_DATA_RATE: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0124; +pub const SCARD_ATTR_MAX_IFSD: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0125; +pub const SCARD_ATTR_POWER_MGMT_SUPPORT: ::ULONG = SCARD_CLASS_POWER_MGMT << 16 | 0x0131; +pub const SCARD_ATTR_USER_TO_CARD_AUTH_DEVICE: ::ULONG = SCARD_CLASS_SECURITY << 16 | 0x0140; +pub const SCARD_ATTR_USER_AUTH_INPUT_DEVICE: ::ULONG = SCARD_CLASS_SECURITY << 16 | 0x0142; +pub const SCARD_ATTR_CHARACTERISTICS: ::ULONG = SCARD_CLASS_MECHANICAL << 16 | 0x0150; +pub const SCARD_ATTR_CURRENT_PROTOCOL_TYPE: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0201; +pub const SCARD_ATTR_CURRENT_CLK: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0202; +pub const SCARD_ATTR_CURRENT_F: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0203; +pub const SCARD_ATTR_CURRENT_D: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0204; +pub const SCARD_ATTR_CURRENT_N: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0205; +pub const SCARD_ATTR_CURRENT_W: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0206; +pub const SCARD_ATTR_CURRENT_IFSC: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0207; +pub const SCARD_ATTR_CURRENT_IFSD: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0208; +pub const SCARD_ATTR_CURRENT_BWT: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0209; +pub const SCARD_ATTR_CURRENT_CWT: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x020a; +pub const SCARD_ATTR_CURRENT_EBC_ENCODING: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x020b; +pub const SCARD_ATTR_EXTENDED_BWT: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x020c; +pub const SCARD_ATTR_ICC_PRESENCE: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0300; +pub const SCARD_ATTR_ICC_INTERFACE_STATUS: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0301; +pub const SCARD_ATTR_CURRENT_IO_STATE: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0302; +pub const SCARD_ATTR_ATR_STRING: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0303; +pub const SCARD_ATTR_ICC_TYPE_PER_ATR: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0304; +pub const SCARD_ATTR_ESC_RESET: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA000; +pub const SCARD_ATTR_ESC_CANCEL: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA003; +pub const SCARD_ATTR_ESC_AUTHREQUEST: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA005; +pub const SCARD_ATTR_MAXINPUT: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA007; +pub const SCARD_ATTR_DEVICE_UNIT: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0001; +pub const SCARD_ATTR_DEVICE_IN_USE: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0002; +pub const SCARD_ATTR_DEVICE_FRIENDLY_NAME_A: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0003; +pub const SCARD_ATTR_DEVICE_SYSTEM_NAME_A: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0004; +pub const SCARD_ATTR_DEVICE_FRIENDLY_NAME_W: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0005; +pub const SCARD_ATTR_DEVICE_SYSTEM_NAME_W: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0006; +pub const SCARD_ATTR_SUPRESS_T1_IFS_REQUEST: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0007; +pub const SCARD_PERF_NUM_TRANSMISSIONS: ::ULONG = SCARD_CLASS_PERF << 16 | 0x0001; +pub const SCARD_PERF_BYTES_TRANSMITTED: ::ULONG = SCARD_CLASS_PERF << 16 | 0x0002; +pub const SCARD_PERF_TRANSMISSION_TIME: ::ULONG = SCARD_CLASS_PERF << 16 | 0x0003; +pub const SCARD_T0_HEADER_LENGTH: ::DWORD = 7; +pub const SCARD_T0_CMD_LENGTH: ::DWORD = 5; +pub const SCARD_T1_PROLOGUE_LENGTH: ::DWORD = 3; +pub const SCARD_T1_EPILOGUE_LENGTH: ::DWORD = 2; +pub const SCARD_T1_MAX_IFS: ::DWORD = 254; +pub const SCARD_UNKNOWN: ::ULONG = 0; +pub const SCARD_ABSENT: ::ULONG = 1; +pub const SCARD_PRESENT: ::ULONG = 2; +pub const SCARD_SWALLOWED: ::ULONG = 3; +pub const SCARD_POWERED: ::ULONG = 4; +pub const SCARD_NEGOTIABLE: ::ULONG = 5; +pub const SCARD_SPECIFIC: ::ULONG = 6; +STRUCT!{struct SCARD_IO_REQUEST { + dwProtocol: ::DWORD, + cbPciLength: ::DWORD, +}} +pub type PSCARD_IO_REQUEST = *mut SCARD_IO_REQUEST; +pub type LPSCARD_IO_REQUEST = *mut SCARD_IO_REQUEST; +pub type LPCSCARD_IO_REQUEST = *const SCARD_IO_REQUEST; +STRUCT!{struct SCARD_T0_COMMAND { + bCla: ::BYTE, + bIns: ::BYTE, + bP1: ::BYTE, + bP2: ::BYTE, + bP3: ::BYTE, +}} +pub type LPSCARD_T0_COMMAND = *mut SCARD_T0_COMMAND; +STRUCT!{struct SCARD_T0_REQUEST { + ioRequest: SCARD_IO_REQUEST, + bSw1: ::BYTE, + bSw2: ::BYTE, + CmdBytes: SCARD_T0_COMMAND, +}} +UNION!(SCARD_T0_REQUEST, CmdBytes, rgbHeader, rgbHeader_mut, [::BYTE; 5]); +pub type PSCARD_T0_REQUEST = *mut SCARD_T0_REQUEST; +pub type LPSCARD_T0_REQUEST = *mut SCARD_T0_REQUEST; +STRUCT!{struct SCARD_T1_REQUEST { + ioRequest: SCARD_IO_REQUEST, +}} +pub type PSCARD_T1_REQUEST = *mut SCARD_T1_REQUEST; +pub type LPSCARD_T1_REQUEST = *mut SCARD_T1_REQUEST; +pub const SCARD_READER_SWALLOWS: ::ULONG = 0x00000001; +pub const SCARD_READER_EJECTS: ::ULONG = 0x00000002; +pub const SCARD_READER_CONFISCATES: ::ULONG = 0x00000004; +pub const SCARD_READER_TYPE_SERIAL: ::ULONG = 0x01; +pub const SCARD_READER_TYPE_PARALELL: ::ULONG = 0x02; +pub const SCARD_READER_TYPE_KEYBOARD: ::ULONG = 0x04; +pub const SCARD_READER_TYPE_SCSI: ::ULONG = 0x08; +pub const SCARD_READER_TYPE_IDE: ::ULONG = 0x10; +pub const SCARD_READER_TYPE_USB: ::ULONG = 0x20; +pub const SCARD_READER_TYPE_PCMCIA: ::ULONG = 0x40; +pub const SCARD_READER_TYPE_TPM: ::ULONG = 0x80; +pub const SCARD_READER_TYPE_NFC: ::ULONG = 0x100; +pub const SCARD_READER_TYPE_UICC: ::ULONG = 0x200; +pub const SCARD_READER_TYPE_VENDOR: ::ULONG = 0xF0; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winsock2.rs b/bash-5.1/vendor/winapi-0.2.8/src/winsock2.rs new file mode 100644 index 0000000..05b62f2 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winsock2.rs @@ -0,0 +1,429 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! definitions to be used with the WinSock 2 DLL and WinSock 2 applications. +//! +//! This header file corresponds to version 2.2.x of the WinSock API specification. +pub const WINSOCK_VERSION: ::WORD = 2 | (2 << 8); +pub type u_char = ::c_uchar; +pub type u_short = ::c_ushort; +pub type u_int = ::c_uint; +pub type u_long = ::c_ulong; +pub type u_int64 = ::__uint64; +pub type SOCKET = ::UINT_PTR; +pub type GROUP = ::c_uint; +pub const FD_SETSIZE: usize = 64; +pub const FD_MAX_EVENTS: usize = 10; +STRUCT!{nodebug struct fd_set { + fd_count: u_int, + fd_array: [SOCKET; FD_SETSIZE], +}} +STRUCT!{struct timeval { + tv_sec: ::c_long, + tv_usec: ::c_long, +}} +STRUCT!{struct hostent { + h_name: *mut ::c_char, + h_aliases: *mut *mut ::c_char, + h_addrtype: ::c_short, + h_length: ::c_short, + h_addr_list: *mut *mut ::c_char, +}} +STRUCT!{struct netent { + n_name: *mut ::c_char, + n_aliases: *mut *mut ::c_char, + n_addrtype: ::c_short, + n_net: u_long, +}} +#[cfg(target_arch="x86")] +STRUCT!{struct servent { + s_name: *mut ::c_char, + s_aliases: *mut *mut ::c_char, + s_port: ::c_short, + s_proto: *mut ::c_char, +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct servent { + s_name: *mut ::c_char, + s_aliases: *mut *mut ::c_char, + s_proto: *mut ::c_char, + s_port: ::c_short, +}} +STRUCT!{struct protoent { + p_name: *mut ::c_char, + p_aliases: *mut *mut ::c_char, + p_proto: ::c_short, +}} +pub const WSADESCRIPTION_LEN: usize = 256; +pub const WSASYS_STATUS_LEN: usize = 128; +#[cfg(target_arch="x86")] +STRUCT!{nodebug struct WSADATA { + wVersion: ::WORD, + wHighVersion: ::WORD, + szDescription: [::c_char; WSADESCRIPTION_LEN + 1], + szSystemStatus: [::c_char; WSASYS_STATUS_LEN + 1], + iMaxSockets: ::c_ushort, + iMaxUdpDg: ::c_ushort, + lpVendorInfo: *mut ::c_char, +}} +#[cfg(target_arch="x86_64")] +STRUCT!{nodebug struct WSADATA { + wVersion: ::WORD, + wHighVersion: ::WORD, + iMaxSockets: ::c_ushort, + iMaxUdpDg: ::c_ushort, + lpVendorInfo: *mut ::c_char, + szDescription: [::c_char; WSADESCRIPTION_LEN + 1], + szSystemStatus: [::c_char; WSASYS_STATUS_LEN + 1], +}} +pub type LPWSADATA = *mut WSADATA; +//391 +pub const INVALID_SOCKET: SOCKET = !0; +pub const SOCKET_ERROR: ::c_int = -1; +STRUCT!{struct sockproto { + sp_family: u_short, + sp_protocol: u_short, +}} +pub const PF_UNSPEC: ::c_int = ::AF_UNSPEC; +pub const PF_UNIX: ::c_int = ::AF_UNIX; +pub const PF_INET: ::c_int = ::AF_INET; +pub const PF_IMPLINK: ::c_int = ::AF_IMPLINK; +pub const PF_PUP: ::c_int = ::AF_PUP; +pub const PF_CHAOS: ::c_int = ::AF_CHAOS; +pub const PF_NS: ::c_int = ::AF_NS; +pub const PF_IPX: ::c_int = ::AF_IPX; +pub const PF_ISO: ::c_int = ::AF_ISO; +pub const PF_OSI: ::c_int = ::AF_OSI; +pub const PF_ECMA: ::c_int = ::AF_ECMA; +pub const PF_DATAKIT: ::c_int = ::AF_DATAKIT; +pub const PF_CCITT: ::c_int = ::AF_CCITT; +pub const PF_SNA: ::c_int = ::AF_SNA; +pub const PF_DECnet: ::c_int = ::AF_DECnet; +pub const PF_DLI: ::c_int = ::AF_DLI; +pub const PF_LAT: ::c_int = ::AF_LAT; +pub const PF_HYLINK: ::c_int = ::AF_HYLINK; +pub const PF_APPLETALK: ::c_int = ::AF_APPLETALK; +pub const PF_VOICEVIEW: ::c_int = ::AF_VOICEVIEW; +pub const PF_FIREFOX: ::c_int = ::AF_FIREFOX; +pub const PF_UNKNOWN1: ::c_int = ::AF_UNKNOWN1; +pub const PF_BAN: ::c_int = ::AF_BAN; +pub const PF_ATM: ::c_int = ::AF_ATM; +pub const PF_INET6: ::c_int = ::AF_INET6; +pub const PF_BTH: ::c_int = ::AF_BTH; +pub const PF_MAX: ::c_int = ::AF_MAX; +STRUCT!{struct linger { + l_onoff: u_short, + l_linger: u_short, +}} +pub const SOMAXCONN: ::c_int = 0x7fffffff; +pub type WSAEVENT = ::HANDLE; +pub type LPWSAEVENT = ::LPHANDLE; +pub type WSAOVERLAPPED = ::OVERLAPPED; +pub type LPWSAOVERLAPPED = *mut ::OVERLAPPED; +pub const WSA_IO_PENDING: ::DWORD = ::ERROR_IO_PENDING; +pub const WSA_IO_INCOMPLETE: ::DWORD = ::ERROR_IO_INCOMPLETE; +pub const WSA_INVALID_HANDLE: ::DWORD = ::ERROR_INVALID_HANDLE; +pub const WSA_INVALID_PARAMETER: ::DWORD = ::ERROR_INVALID_PARAMETER; +pub const WSA_NOT_ENOUGH_MEMORY: ::DWORD = ::ERROR_NOT_ENOUGH_MEMORY; +pub const WSA_OPERATION_ABORTED: ::DWORD = ::ERROR_OPERATION_ABORTED; +STRUCT!{struct QOS { + SendingFlowspec: ::FLOWSPEC, + FLOWSPEC: ::FLOWSPEC, + ProviderSpecific: ::WSABUF, +}} +pub type LPQOS = *mut QOS; +STRUCT!{struct WSANETWORKEVENTS { + lNetworkEvents: ::c_long, + iErrorCode: [::c_int; FD_MAX_EVENTS], +}} +pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; +pub const MAX_PROTOCOL_CHAIN: usize = 7; +STRUCT!{struct WSAPROTOCOLCHAIN { + ChainLen: ::c_int, + ChainEntries: [::DWORD; MAX_PROTOCOL_CHAIN], +}} +pub type LPWSAPROTOCOLCHAIN = *mut WSAPROTOCOLCHAIN; +pub const WSAPROTOCOL_LEN: usize = 255; +STRUCT!{nodebug struct WSAPROTOCOL_INFOA { + dwServiceFlags1: ::DWORD, + dwServiceFlags2: ::DWORD, + dwServiceFlags3: ::DWORD, + dwServiceFlags4: ::DWORD, + dwServiceFlags5: ::DWORD, + ProviderId: ::GUID, + dwCatalogEntryId: ::DWORD, + ProtocolChain: WSAPROTOCOLCHAIN, + iVersion: ::c_int, + iAddressFamily: ::c_int, + iMaxSockAddr: ::c_int, + iMinSockAddr: ::c_int, + iSocketType: ::c_int, + iProtocol: ::c_int, + iProtocolMaxOffset: ::c_int, + iNetworkByteOrder: ::c_int, + iSecurityScheme: ::c_int, + dwMessageSize: ::DWORD, + dwProviderReserved: ::DWORD, + szProtocol: [::CHAR; WSAPROTOCOL_LEN + 1], +}} +pub type LPWSAPROTOCOL_INFOA = *mut WSAPROTOCOL_INFOA; +STRUCT!{nodebug struct WSAPROTOCOL_INFOW { + dwServiceFlags1: ::DWORD, + dwServiceFlags2: ::DWORD, + dwServiceFlags3: ::DWORD, + dwServiceFlags4: ::DWORD, + dwServiceFlags5: ::DWORD, + ProviderId: ::GUID, + dwCatalogEntryId: ::DWORD, + ProtocolChain: WSAPROTOCOLCHAIN, + iVersion: ::c_int, + iAddressFamily: ::c_int, + iMaxSockAddr: ::c_int, + iMinSockAddr: ::c_int, + iSocketType: ::c_int, + iProtocol: ::c_int, + iProtocolMaxOffset: ::c_int, + iNetworkByteOrder: ::c_int, + iSecurityScheme: ::c_int, + dwMessageSize: ::DWORD, + dwProviderReserved: ::DWORD, + szProtocol: [::WCHAR; WSAPROTOCOL_LEN + 1], +}} +pub type LPWSAPROTOCOL_INFOW = *mut WSAPROTOCOL_INFOW; +pub type LPCONDITIONPROC = Option<unsafe extern "system" fn( + lpCallerId: ::LPWSABUF, lpCallerData: ::LPWSABUF, lpSQOS: LPQOS, lpGQOS: LPQOS, + lpCalleeId: ::LPWSABUF, lpCalleeData: ::LPWSABUF, g: *mut GROUP, dwCallbackData: ::DWORD, +) -> ::c_int>; +pub type LPWSAOVERLAPPED_COMPLETION_ROUTINE = Option<unsafe extern "system" fn( + dwError: ::DWORD, cbTransferred: ::DWORD, lpOverlapped: LPWSAOVERLAPPED, dwFlags: ::DWORD, +)>; +ENUM!{enum WSACOMPLETIONTYPE { + NSP_NOTIFY_IMMEDIATELY = 0, + NSP_NOTIFY_HWND, + NSP_NOTIFY_EVENT, + NSP_NOTIFY_PORT, + NSP_NOTIFY_APC, +}} +pub type PWSACOMPLETIONTYPE = *mut WSACOMPLETIONTYPE; +pub type LPWSACOMPLETIONTYPE = *mut WSACOMPLETIONTYPE; +STRUCT!{struct WSACOMPLETION_WindowMessage { + hWnd: ::HWND, + uMsg: ::UINT, + context: ::WPARAM, +}} +STRUCT!{struct WSACOMPLETION_Event { + lpOverlapped: LPWSAOVERLAPPED, +}} +STRUCT!{nodebug struct WSACOMPLETION_Apc { + lpOverlapped: LPWSAOVERLAPPED, + lpfnCompletionProc: LPWSAOVERLAPPED_COMPLETION_ROUTINE, +}} +STRUCT!{struct WSACOMPLETION_Port { + lpOverlapped: LPWSAOVERLAPPED, + hPort: ::HANDLE, + Key: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +STRUCT!{struct WSACOMPLETION { + Type: WSACOMPLETIONTYPE, + Parameters: [u8; 12], +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct WSACOMPLETION { + Type: WSACOMPLETIONTYPE, + Parameters: [u8; 24], +}} +UNION!(WSACOMPLETION, Parameters, WindowMessage, WindowMessage_mut, WSACOMPLETION_WindowMessage); +UNION!(WSACOMPLETION, Parameters, Event, Event_mut, WSACOMPLETION_Event); +UNION!(WSACOMPLETION, Parameters, Apc, Apc_mut, WSACOMPLETION_Apc); +UNION!(WSACOMPLETION, Parameters, Port, Port_mut, WSACOMPLETION_Port); +pub type PWSACOMPLETION = *mut WSACOMPLETION; +pub type LPWSACOMPLETION = *mut WSACOMPLETION; +STRUCT!{struct AFPROTOCOLS { + iAddressFamily: ::INT, + iProtocol: ::INT, +}} +pub type PAFPROTOCOLS = *mut AFPROTOCOLS; +pub type LPAFPROTOCOLS = *mut AFPROTOCOLS; +ENUM!{enum WSAECOMPARATOR { + COMP_EQUAL = 0, + COMP_NOTLESS, +}} +pub type PWSAECOMPARATOR = *mut WSAECOMPARATOR; +pub type LPWSAECOMPARATOR = *mut WSAECOMPARATOR; +STRUCT!{struct WSAVERSION { + dwVersion: ::DWORD, + ecHow: WSAECOMPARATOR, +}} +pub type PWSAVERSION = *mut WSAVERSION; +pub type LPWSAVERSION = *mut WSAVERSION; +STRUCT!{struct WSAQUERYSETA { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPSTR, + lpServiceClassId: ::LPGUID, + lpVersion: LPWSAVERSION, + lpszComment: ::LPSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSETA = *mut WSAQUERYSETA; +pub type LPWSAQUERYSETA = *mut WSAQUERYSETA; +STRUCT!{struct WSAQUERYSETW { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPWSTR, + lpServiceClassId: ::LPGUID, + lpVersion: LPWSAVERSION, + lpszComment: ::LPWSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPWSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPWSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSETW = *mut WSAQUERYSETW; +pub type LPWSAQUERYSETW = *mut WSAQUERYSETW; +STRUCT!{struct WSAQUERYSET2A { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPSTR, + lpVersion: LPWSAVERSION, + lpszComment: ::LPSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSET2A = *mut WSAQUERYSET2A; +pub type LPWSAQUERYSET2A = *mut WSAQUERYSET2A; +STRUCT!{struct WSAQUERYSET2W { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPWSTR, + lpVersion: LPWSAVERSION, + lpszComment: ::LPWSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPWSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPWSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSET2W = *mut WSAQUERYSET2W; +pub type LPWSAQUERYSET2W = *mut WSAQUERYSET2W; +ENUM!{enum WSAESETSERVICEOP { + RNRSERVICE_REGISTER = 0, + RNRSERVICE_DEREGISTER, + RNRSERVICE_DELETE, +}} +pub type PWSAESETSERVICEOP = *mut WSAESETSERVICEOP; +pub type LPWSAESETSERVICEOP = *mut WSAESETSERVICEOP; +STRUCT!{struct WSANSCLASSINFOA { + lpszName: ::LPSTR, + dwNameSpace: ::DWORD, + dwValueType: ::DWORD, + dwValueSize: ::DWORD, + lpValue: ::LPVOID, +}} +pub type PWSANSCLASSINFOA = *mut WSANSCLASSINFOA; +pub type LPWSANSCLASSINFOA = *mut WSANSCLASSINFOA; +STRUCT!{struct WSANSCLASSINFOW { + lpszName: ::LPWSTR, + dwNameSpace: ::DWORD, + dwValueType: ::DWORD, + dwValueSize: ::DWORD, + lpValue: ::LPVOID, +}} +pub type PWSANSCLASSINFOW = *mut WSANSCLASSINFOW; +pub type LPWSANSCLASSINFOW = *mut WSANSCLASSINFOW; +STRUCT!{struct WSASERVICECLASSINFOA { + lpServiceClassId: ::LPGUID, + lpszServiceClassName: ::LPSTR, + dwCount: ::DWORD, + lpClassInfos: LPWSANSCLASSINFOA, +}} +pub type PWSASERVICECLASSINFOA = *mut WSASERVICECLASSINFOA; +pub type LPWSASERVICECLASSINFOA = *mut WSASERVICECLASSINFOA; +STRUCT!{struct WSASERVICECLASSINFOW { + lpServiceClassId: ::LPGUID, + lpszServiceClassName: ::LPWSTR, + dwCount: ::DWORD, + lpClassInfos: LPWSANSCLASSINFOW, +}} +pub type PWSASERVICECLASSINFOW = *mut WSASERVICECLASSINFOW; +pub type LPWSASERVICECLASSINFOW = *mut WSASERVICECLASSINFOW; +STRUCT!{struct WSANAMESPACE_INFOA { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPSTR, +}} +pub type PWSANAMESPACE_INFOA = *mut WSANAMESPACE_INFOA; +pub type LPWSANAMESPACE_INFOA = *mut WSANAMESPACE_INFOA; +STRUCT!{struct WSANAMESPACE_INFOW { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPWSTR, +}} +pub type PWSANAMESPACE_INFOW = *mut WSANAMESPACE_INFOW; +pub type LPWSANAMESPACE_INFOW = *mut WSANAMESPACE_INFOW; +STRUCT!{struct WSANAMESPACE_INFOEXA { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPSTR, + ProviderSpecific: ::BLOB, +}} +pub type PWSANAMESPACE_INFOEXA = *mut WSANAMESPACE_INFOEXA; +pub type LPWSANAMESPACE_INFOEXA = *mut WSANAMESPACE_INFOEXA; +STRUCT!{struct WSANAMESPACE_INFOEXW { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPWSTR, + ProviderSpecific: ::BLOB, +}} +pub type PWSANAMESPACE_INFOEXW = *mut WSANAMESPACE_INFOEXW; +pub type LPWSANAMESPACE_INFOEXW = *mut WSANAMESPACE_INFOEXW; +pub const POLLRDNORM: ::SHORT = 0x0100; +pub const POLLRDBAND: ::SHORT = 0x0200; +pub const POLLIN: ::SHORT = POLLRDNORM | POLLRDBAND; +pub const POLLPRI: ::SHORT = 0x0400; +pub const POLLWRNORM: ::SHORT = 0x0010; +pub const POLLOUT: ::SHORT = POLLWRNORM; +pub const POLLWRBAND: ::SHORT = 0x0020; +pub const POLLERR: ::SHORT = 0x0001; +pub const POLLHUP: ::SHORT = 0x0002; +pub const POLLNVAL: ::SHORT = 0x0004; +STRUCT!{struct WSAPOLLFD { + fd: ::SOCKET, + events: ::SHORT, + revents: ::SHORT, +}} +pub type PWSAPOLLFD = *mut WSAPOLLFD; +pub type LPWSAPOLLFD = *mut WSAPOLLFD; +pub const FIONBIO: ::c_ulong = 0x8004667e; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winspool.rs b/bash-5.1/vendor/winapi-0.2.8/src/winspool.rs new file mode 100644 index 0000000..eec339c --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winspool.rs @@ -0,0 +1,29 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Winspool header file +STRUCT!{struct PRINTER_DEFAULTSA { + pDataType: ::LPSTR, + pDevMode: ::LPDEVMODEA, + DesiredAccess: ::ACCESS_MASK, +}} +pub type PPRINTER_DEFAULTSA = *mut PRINTER_DEFAULTSA; +pub type LPPRINTER_DEFAULTSA = *mut PRINTER_DEFAULTSA; +STRUCT!{struct PRINTER_DEFAULTSW { + pDataType: ::LPWSTR, + pDevMode: ::LPDEVMODEW, + DesiredAccess: ::ACCESS_MASK, +}} +pub type PPRINTER_DEFAULTSW = *mut PRINTER_DEFAULTSW; +pub type LPPRINTER_DEFAULTSW = *mut PRINTER_DEFAULTSW; +STRUCT!{struct PRINTER_OPTIONSA { + cbSize: ::UINT, + dwFlags: ::DWORD, +}} +pub type PPRINTER_OPTIONSA = *mut PRINTER_OPTIONSA; +pub type LPPRINTER_OPTIONSA = *mut PRINTER_OPTIONSA; +STRUCT!{struct PRINTER_OPTIONSW { + cbSize: ::UINT, + dwFlags: ::DWORD, +}} +pub type PPRINTER_OPTIONSW = *mut PRINTER_OPTIONSW; +pub type LPPRINTER_OPTIONSW = *mut PRINTER_OPTIONSW; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winstring.rs b/bash-5.1/vendor/winapi-0.2.8/src/winstring.rs new file mode 100644 index 0000000..74053d4 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winstring.rs @@ -0,0 +1,3 @@ +pub type PINSPECT_HSTRING_CALLBACK = Option<unsafe extern "system" fn( + *const ::VOID, ::UINT_PTR, ::UINT32, *mut ::BYTE, +) -> ::HRESULT>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winsvc.rs b/bash-5.1/vendor/winapi-0.2.8/src/winsvc.rs new file mode 100644 index 0000000..9351366 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winsvc.rs @@ -0,0 +1,200 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! Header file for the Service Control Manager +//80 +pub const SERVICE_NO_CHANGE: ::DWORD = 0xffffffff; +pub const SERVICE_ACTIVE: ::DWORD = 0x00000001; +pub const SERVICE_INACTIVE: ::DWORD = 0x00000002; +pub const SERVICE_STATE_ALL: ::DWORD = SERVICE_ACTIVE | SERVICE_INACTIVE; +pub const SERVICE_CONTROL_STOP: ::DWORD = 0x00000001; +pub const SERVICE_CONTROL_PAUSE: ::DWORD = 0x00000002; +pub const SERVICE_CONTROL_CONTINUE: ::DWORD = 0x00000003; +pub const SERVICE_CONTROL_INTERROGATE: ::DWORD = 0x00000004; +pub const SERVICE_CONTROL_SHUTDOWN: ::DWORD = 0x00000005; +pub const SERVICE_CONTROL_PARAMCHANGE: ::DWORD = 0x00000006; +pub const SERVICE_CONTROL_NETBINDADD: ::DWORD = 0x00000007; +pub const SERVICE_CONTROL_NETBINDREMOVE: ::DWORD = 0x00000008; +pub const SERVICE_CONTROL_NETBINDENABLE: ::DWORD = 0x00000009; +pub const SERVICE_CONTROL_NETBINDDISABLE: ::DWORD = 0x0000000A; +pub const SERVICE_CONTROL_DEVICEEVENT: ::DWORD = 0x0000000B; +pub const SERVICE_CONTROL_HARDWAREPROFILECHANGE: ::DWORD = 0x0000000C; +pub const SERVICE_CONTROL_POWEREVENT: ::DWORD = 0x0000000D; +pub const SERVICE_CONTROL_SESSIONCHANGE: ::DWORD = 0x0000000E; +pub const SERVICE_CONTROL_PRESHUTDOWN: ::DWORD = 0x0000000F; +pub const SERVICE_CONTROL_TIMECHANGE: ::DWORD = 0x00000010; +pub const SERVICE_CONTROL_TRIGGEREVENT: ::DWORD = 0x00000020; +pub const SERVICE_STOPPED: ::DWORD = 0x00000001; +pub const SERVICE_START_PENDING: ::DWORD = 0x00000002; +pub const SERVICE_STOP_PENDING: ::DWORD = 0x00000003; +pub const SERVICE_RUNNING: ::DWORD = 0x00000004; +pub const SERVICE_CONTINUE_PENDING: ::DWORD = 0x00000005; +pub const SERVICE_PAUSE_PENDING: ::DWORD = 0x00000006; +pub const SERVICE_PAUSED: ::DWORD = 0x00000007; +pub const SERVICE_ACCEPT_STOP: ::DWORD = 0x00000001; +pub const SERVICE_ACCEPT_PAUSE_CONTINUE: ::DWORD = 0x00000002; +pub const SERVICE_ACCEPT_SHUTDOWN: ::DWORD = 0x00000004; +pub const SERVICE_ACCEPT_PARAMCHANGE: ::DWORD = 0x00000008; +pub const SERVICE_ACCEPT_NETBINDCHANGE: ::DWORD = 0x00000010; +pub const SERVICE_ACCEPT_HARDWAREPROFILECHANGE: ::DWORD = 0x00000020; +pub const SERVICE_ACCEPT_POWEREVENT: ::DWORD = 0x00000040; +pub const SERVICE_ACCEPT_SESSIONCHANGE: ::DWORD = 0x00000080; +pub const SERVICE_ACCEPT_PRESHUTDOWN: ::DWORD = 0x00000100; +pub const SERVICE_ACCEPT_TIMECHANGE: ::DWORD = 0x00000200; +pub const SERVICE_ACCEPT_TRIGGEREVENT: ::DWORD = 0x00000400; +pub const SC_MANAGER_CONNECT: ::DWORD = 0x0001; +pub const SC_MANAGER_CREATE_SERVICE: ::DWORD = 0x0002; +pub const SC_MANAGER_ENUMERATE_SERVICE: ::DWORD = 0x0004; +pub const SC_MANAGER_LOCK: ::DWORD = 0x0008; +pub const SC_MANAGER_QUERY_LOCK_STATUS: ::DWORD = 0x0010; +pub const SC_MANAGER_MODIFY_BOOT_CONFIG: ::DWORD = 0x0020; +pub const SC_MANAGER_ALL_ACCESS: ::DWORD = ::STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT + | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK + | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG; +pub const SERVICE_QUERY_CONFIG: ::DWORD = 0x0001; +pub const SERVICE_CHANGE_CONFIG: ::DWORD = 0x0002; +pub const SERVICE_QUERY_STATUS: ::DWORD = 0x0004; +pub const SERVICE_ENUMERATE_DEPENDENTS: ::DWORD = 0x0008; +pub const SERVICE_START: ::DWORD = 0x0010; +pub const SERVICE_STOP: ::DWORD = 0x0020; +pub const SERVICE_PAUSE_CONTINUE: ::DWORD = 0x0040; +pub const SERVICE_INTERROGATE: ::DWORD = 0x0080; +pub const SERVICE_USER_DEFINED_CONTROL: ::DWORD = 0x0100; +pub const SERVICE_ALL_ACCESS: ::DWORD = ::STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG + | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START + | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL; +pub const SERVICE_RUNS_IN_SYSTEM_PROCESS: ::DWORD = 0x00000001; +pub const SERVICE_CONFIG_DESCRIPTION: ::DWORD = 1; +pub const SERVICE_CONFIG_FAILURE_ACTIONS: ::DWORD = 2; +pub const SERVICE_CONFIG_DELAYED_AUTO_START_INFO: ::DWORD = 3; +pub const SERVICE_CONFIG_FAILURE_ACTIONS_FLAG: ::DWORD = 4; +pub const SERVICE_CONFIG_SERVICE_SID_INFO: ::DWORD = 5; +pub const SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO: ::DWORD = 6; +pub const SERVICE_CONFIG_PRESHUTDOWN_INFO: ::DWORD = 7; +pub const SERVICE_CONFIG_TRIGGER_INFO: ::DWORD = 8; +pub const SERVICE_CONFIG_PREFERRED_NODE: ::DWORD = 9; +pub const SERVICE_CONFIG_LAUNCH_PROTECTED: ::DWORD = 12; +pub const SERVICE_NOTIFY_STATUS_CHANGE_1: ::DWORD = 1; +pub const SERVICE_NOTIFY_STATUS_CHANGE_2: ::DWORD = 2; +pub const SERVICE_NOTIFY_STATUS_CHANGE: ::DWORD = SERVICE_NOTIFY_STATUS_CHANGE_2; +pub const SERVICE_NOTIFY_STOPPED: ::DWORD = 0x00000001; +pub const SERVICE_NOTIFY_START_PENDING: ::DWORD = 0x00000002; +pub const SERVICE_NOTIFY_STOP_PENDING: ::DWORD = 0x00000004; +pub const SERVICE_NOTIFY_RUNNING: ::DWORD = 0x00000008; +pub const SERVICE_NOTIFY_CONTINUE_PENDING: ::DWORD = 0x00000010; +pub const SERVICE_NOTIFY_PAUSE_PENDING: ::DWORD = 0x00000020; +pub const SERVICE_NOTIFY_PAUSED: ::DWORD = 0x00000040; +pub const SERVICE_NOTIFY_CREATED: ::DWORD = 0x00000080; +pub const SERVICE_NOTIFY_DELETED: ::DWORD = 0x00000100; +pub const SERVICE_NOTIFY_DELETE_PENDING: ::DWORD = 0x00000200; +pub const SERVICE_STOP_REASON_FLAG_MIN: ::DWORD = 0x00000000; +pub const SERVICE_STOP_REASON_FLAG_UNPLANNED: ::DWORD = 0x10000000; +pub const SERVICE_STOP_REASON_FLAG_CUSTOM: ::DWORD = 0x20000000; +pub const SERVICE_STOP_REASON_FLAG_PLANNED: ::DWORD = 0x40000000; +pub const SERVICE_STOP_REASON_FLAG_MAX: ::DWORD = 0x80000000; +pub const SERVICE_STOP_REASON_MAJOR_MIN: ::DWORD = 0x00000000; +pub const SERVICE_STOP_REASON_MAJOR_OTHER: ::DWORD = 0x00010000; +pub const SERVICE_STOP_REASON_MAJOR_HARDWARE: ::DWORD = 0x00020000; +pub const SERVICE_STOP_REASON_MAJOR_OPERATINGSYSTEM: ::DWORD = 0x00030000; +pub const SERVICE_STOP_REASON_MAJOR_SOFTWARE: ::DWORD = 0x00040000; +pub const SERVICE_STOP_REASON_MAJOR_APPLICATION: ::DWORD = 0x00050000; +pub const SERVICE_STOP_REASON_MAJOR_NONE: ::DWORD = 0x00060000; +pub const SERVICE_STOP_REASON_MAJOR_MAX: ::DWORD = 0x00070000; +pub const SERVICE_STOP_REASON_MAJOR_MIN_CUSTOM: ::DWORD = 0x00400000; +pub const SERVICE_STOP_REASON_MAJOR_MAX_CUSTOM: ::DWORD = 0x00ff0000; +pub const SERVICE_STOP_REASON_MINOR_MIN: ::DWORD = 0x00000000; +pub const SERVICE_STOP_REASON_MINOR_OTHER: ::DWORD = 0x00000001; +pub const SERVICE_STOP_REASON_MINOR_MAINTENANCE: ::DWORD = 0x00000002; +pub const SERVICE_STOP_REASON_MINOR_INSTALLATION: ::DWORD = 0x00000003; +pub const SERVICE_STOP_REASON_MINOR_UPGRADE: ::DWORD = 0x00000004; +pub const SERVICE_STOP_REASON_MINOR_RECONFIG: ::DWORD = 0x00000005; +pub const SERVICE_STOP_REASON_MINOR_HUNG: ::DWORD = 0x00000006; +pub const SERVICE_STOP_REASON_MINOR_UNSTABLE: ::DWORD = 0x00000007; +pub const SERVICE_STOP_REASON_MINOR_DISK: ::DWORD = 0x00000008; +pub const SERVICE_STOP_REASON_MINOR_NETWORKCARD: ::DWORD = 0x00000009; +pub const SERVICE_STOP_REASON_MINOR_ENVIRONMENT: ::DWORD = 0x0000000a; +pub const SERVICE_STOP_REASON_MINOR_HARDWARE_DRIVER: ::DWORD = 0x0000000b; +pub const SERVICE_STOP_REASON_MINOR_OTHERDRIVER: ::DWORD = 0x0000000c; +pub const SERVICE_STOP_REASON_MINOR_SERVICEPACK: ::DWORD = 0x0000000d; +pub const SERVICE_STOP_REASON_MINOR_SOFTWARE_UPDATE: ::DWORD = 0x0000000e; +pub const SERVICE_STOP_REASON_MINOR_SECURITYFIX: ::DWORD = 0x0000000f; +pub const SERVICE_STOP_REASON_MINOR_SECURITY: ::DWORD = 0x00000010; +pub const SERVICE_STOP_REASON_MINOR_NETWORK_CONNECTIVITY: ::DWORD = 0x00000011; +pub const SERVICE_STOP_REASON_MINOR_WMI: ::DWORD = 0x00000012; +pub const SERVICE_STOP_REASON_MINOR_SERVICEPACK_UNINSTALL: ::DWORD = 0x00000013; +pub const SERVICE_STOP_REASON_MINOR_SOFTWARE_UPDATE_UNINSTALL: ::DWORD = 0x00000014; +pub const SERVICE_STOP_REASON_MINOR_SECURITYFIX_UNINSTALL: ::DWORD = 0x00000015; +pub const SERVICE_STOP_REASON_MINOR_MMC: ::DWORD = 0x00000016; +pub const SERVICE_STOP_REASON_MINOR_NONE: ::DWORD = 0x00000017; +pub const SERVICE_STOP_REASON_MINOR_MAX: ::DWORD = 0x00000018; +pub const SERVICE_STOP_REASON_MINOR_MIN_CUSTOM: ::DWORD = 0x00000100; +pub const SERVICE_STOP_REASON_MINOR_MAX_CUSTOM: ::DWORD = 0x0000FFFF; +pub const SERVICE_CONTROL_STATUS_REASON_INFO: ::DWORD = 1; +pub const SERVICE_SID_TYPE_NONE: ::DWORD = 0x00000000; +pub const SERVICE_SID_TYPE_UNRESTRICTED: ::DWORD = 0x00000001; +pub const SERVICE_SID_TYPE_RESTRICTED: ::DWORD = 0x00000002 | SERVICE_SID_TYPE_UNRESTRICTED; +pub const SERVICE_TRIGGER_TYPE_DEVICE_INTERFACE_ARRIVAL: ::DWORD = 1; +pub const SERVICE_TRIGGER_TYPE_IP_ADDRESS_AVAILABILITY: ::DWORD = 2; +pub const SERVICE_TRIGGER_TYPE_DOMAIN_JOIN: ::DWORD = 3; +pub const SERVICE_TRIGGER_TYPE_FIREWALL_PORT_EVENT: ::DWORD = 4; +pub const SERVICE_TRIGGER_TYPE_GROUP_POLICY: ::DWORD = 5; +pub const SERVICE_TRIGGER_TYPE_NETWORK_ENDPOINT: ::DWORD = 6; +pub const SERVICE_TRIGGER_TYPE_CUSTOM_SYSTEM_STATE_CHANGE: ::DWORD = 7; +pub const SERVICE_TRIGGER_TYPE_CUSTOM: ::DWORD = 20; +pub const SERVICE_TRIGGER_DATA_TYPE_BINARY: ::DWORD = 1; +pub const SERVICE_TRIGGER_DATA_TYPE_STRING: ::DWORD = 2; +pub const SERVICE_TRIGGER_DATA_TYPE_LEVEL: ::DWORD = 3; +pub const SERVICE_TRIGGER_DATA_TYPE_KEYWORD_ANY: ::DWORD = 4; +pub const SERVICE_TRIGGER_DATA_TYPE_KEYWORD_ALL: ::DWORD = 5; +pub const SERVICE_START_REASON_DEMAND: ::DWORD = 0x00000001; +pub const SERVICE_START_REASON_AUTO: ::DWORD = 0x00000002; +pub const SERVICE_START_REASON_TRIGGER: ::DWORD = 0x00000004; +pub const SERVICE_START_REASON_RESTART_ON_FAILURE: ::DWORD = 0x00000008; +pub const SERVICE_START_REASON_DELAYEDAUTO: ::DWORD = 0x00000010; +pub const SERVICE_DYNAMIC_INFORMATION_LEVEL_START_REASON: ::DWORD = 1; +pub const SERVICE_LAUNCH_PROTECTED_NONE: ::DWORD = 0; +pub const SERVICE_LAUNCH_PROTECTED_WINDOWS: ::DWORD = 1; +pub const SERVICE_LAUNCH_PROTECTED_WINDOWS_LIGHT: ::DWORD = 2; +pub const SERVICE_LAUNCH_PROTECTED_ANTIMALWARE_LIGHT: ::DWORD = 3; +//678 +DECLARE_HANDLE!(SC_HANDLE, SC_HANDLE__); +pub type LPSC_HANDLE = *mut SC_HANDLE; +DECLARE_HANDLE!(SERVICE_STATUS_HANDLE, SERVICE_STATUS_HANDLE__); +ENUM!{enum SC_STATUS_TYPE { + SC_STATUS_PROCESS_INFO = 0, +}} +ENUM!{enum _SC_ENUM_TYPE { + SC_ENUM_PROCESS_INFO = 0, +}} +//700 +STRUCT!{struct SERVICE_STATUS { + dwServiceType: ::DWORD, + dwCurrentState: ::DWORD, + dwControlsAccepted: ::DWORD, + dwWin32ExitCode: ::DWORD, + dwServiceSpecificExitCode: ::DWORD, + dwCheckPoint: ::DWORD, + dwWaitHint: ::DWORD, +}} +pub type LPSERVICE_STATUS = *mut SERVICE_STATUS; +//848 +pub type LPSERVICE_MAIN_FUNCTIONW = Option<unsafe extern "system" fn( + dwNumServicesArgs: ::DWORD, lpServiceArgVectors: *mut ::LPWSTR, +)>; +pub type LPSERVICE_MAIN_FUNCTIONA = Option<unsafe extern "system" fn( + dwNumServicesArgs: ::DWORD, lpServiceArgVectors: *mut ::LPSTR, +)>; +STRUCT!{nodebug struct SERVICE_TABLE_ENTRYA { + lpServiceName: ::LPCSTR, + lpServiceProc: LPSERVICE_MAIN_FUNCTIONA, +}} +pub type LPSERVICE_TABLE_ENTRYA = *mut SERVICE_TABLE_ENTRYA; +STRUCT!{nodebug struct SERVICE_TABLE_ENTRYW { + lpServiceName: ::LPCWSTR, + lpServiceProc: LPSERVICE_MAIN_FUNCTIONW, +}} +pub type LPSERVICE_TABLE_ENTRYW = *mut SERVICE_TABLE_ENTRYW; +//900 +pub type LPHANDLER_FUNCTION = Option<unsafe extern "system" fn(dwControl: ::DWORD)>; +pub type LPHANDLER_FUNCTION_EX = Option<unsafe extern "system" fn( + dwControl: ::DWORD, dwEventType: ::DWORD, lpEventData: ::LPVOID, lpContext: ::LPVOID, +) -> ::DWORD>; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winusb.rs b/bash-5.1/vendor/winapi-0.2.8/src/winusb.rs new file mode 100644 index 0000000..2fbb619 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winusb.rs @@ -0,0 +1,33 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License <LICENSE.md> +//! FFI bindings to winusb. +pub type WINUSB_INTERFACE_HANDLE = ::PVOID; +pub type PWINUSB_INTERFACE_HANDLE = *mut ::PVOID; +pub type WINUSB_ISOCH_BUFFER_HANDLE = ::PVOID; +pub type PWINUSB_ISOCH_BUFFER_HANDLE = *mut ::PVOID; +STRUCT!{#[repr(packed)] struct WINUSB_SETUP_PACKET { + RequestType: ::UCHAR, + Request: ::UCHAR, + Value: ::USHORT, + Index: ::USHORT, + Length: ::USHORT, +}} +pub type PWINUSB_SETUP_PACKET = *mut WINUSB_SETUP_PACKET; + +STRUCT!{struct USB_INTERFACE_DESCRIPTOR { + bLength: ::UCHAR, + bDescriptorType: ::UCHAR, + bInterfaceNumber: ::UCHAR, + bAlternateSetting: ::UCHAR, + bNumEndpoints: ::UCHAR, + bInterfaceClass: ::UCHAR, + bInterfaceSubClass: ::UCHAR, + bInterfaceProtocol: ::UCHAR, + iInterface: ::UCHAR, +}} +pub type PUSB_INTERFACE_DESCRIPTOR = *mut USB_INTERFACE_DESCRIPTOR; +#[test] +fn test_USB_INTERFACE_DESCRIPTOR_size() { + use std::mem::size_of; + assert_eq!(size_of::<USB_INTERFACE_DESCRIPTOR>(), 9) +} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winusbio.rs b/bash-5.1/vendor/winapi-0.2.8/src/winusbio.rs new file mode 100644 index 0000000..3dedf22 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winusbio.rs @@ -0,0 +1,18 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License <LICENSE.md> +//! USBIO Definitions. +STRUCT!{struct WINUSB_PIPE_INFORMATION { + PipeType: ::USBD_PIPE_TYPE, + PipeId: ::UCHAR, + MaximumPacketSize: ::USHORT, + Interval: ::UCHAR, +}} +pub type PWINUSB_PIPE_INFORMATION = *mut WINUSB_PIPE_INFORMATION; +STRUCT!{struct WINUSB_PIPE_INFORMATION_EX { + PipeType: ::USBD_PIPE_TYPE, + PipeId: ::UCHAR, + MaximumPacketSize: ::USHORT, + Interval: ::UCHAR, + MaximumBytesPerInterval: ::ULONG, +}} +pub type PWINUSB_PIPE_INFORMATION_EX = *mut WINUSB_PIPE_INFORMATION_EX; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/winuser.rs b/bash-5.1/vendor/winapi-0.2.8/src/winuser.rs new file mode 100644 index 0000000..5769489 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/winuser.rs @@ -0,0 +1,2334 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! USER procedure declarations, constant definitions and macros + +// Edit Control Styles +// +pub const ES_LEFT: ::DWORD = 0x0000; +pub const ES_CENTER: ::DWORD = 0x0001; +pub const ES_RIGHT: ::DWORD = 0x0002; +pub const ES_MULTILINE: ::DWORD = 0x0004; +pub const ES_UPPERCASE: ::DWORD = 0x0008; +pub const ES_LOWERCASE: ::DWORD = 0x0010; +pub const ES_PASSWORD: ::DWORD = 0x0020; +pub const ES_AUTOVSCROLL: ::DWORD = 0x0040; +pub const ES_AUTOHSCROLL: ::DWORD = 0x0080; +pub const ES_NOHIDESEL: ::DWORD = 0x0100; +pub const ES_OEMCONVERT: ::DWORD = 0x0400; +pub const ES_READONLY: ::DWORD = 0x0800; +pub const ES_WANTRETURN: ::DWORD = 0x1000; +pub const ES_NUMBER: ::DWORD = 0x2000; + +// Edit Control Notification Codes +// +pub const EN_SETFOCUS: ::WORD = 0x0100; +pub const EN_KILLFOCUS: ::WORD = 0x0200; +pub const EN_CHANGE: ::WORD = 0x0300; +pub const EN_UPDATE: ::WORD = 0x0400; +pub const EN_ERRSPACE: ::WORD = 0x0500; +pub const EN_MAXTEXT: ::WORD = 0x0501; +pub const EN_HSCROLL: ::WORD = 0x0601; +pub const EN_VSCROLL: ::WORD = 0x0602; + +pub const EN_ALIGN_LTR_EC: ::WORD = 0x0700; +pub const EN_ALIGN_RTL_EC: ::WORD = 0x0701; + +// Edit control EM_SETMARGIN parameters +pub const EC_LEFTMARGIN: ::WORD = 0x0001; +pub const EC_RIGHTMARGIN: ::WORD = 0x0002; +pub const EC_USEFONTINFO: ::WORD = 0xffff; + +// wParam of EM_GET/SETIMESTATUS +pub const EMSIS_COMPOSITIONSTRING: ::WORD = 0x0001; + +// lParam for EMSIS_COMPOSITIONSTRING +pub const EIMES_GETCOMPSTRATONCE: ::WORD = 0x0001; +pub const EIMES_CANCELCOMPSTRINFOCUS: ::WORD = 0x0002; +pub const EIMES_COMPLETECOMPSTRKILLFOCUS: ::WORD = 0x0004; + +// Edit Control Messages +// +pub const EM_GETSEL: ::WORD = 0x00B0; +pub const EM_SETSEL: ::WORD = 0x00B1; +pub const EM_GETRECT: ::WORD = 0x00B2; +pub const EM_SETRECT: ::WORD = 0x00B3; +pub const EM_SETRECTNP: ::WORD = 0x00B4; +pub const EM_SCROLL: ::WORD = 0x00B5; +pub const EM_LINESCROLL: ::WORD = 0x00B6; +pub const EM_SCROLLCARET: ::WORD = 0x00B7; +pub const EM_GETMODIFY: ::WORD = 0x00B8; +pub const EM_SETMODIFY: ::WORD = 0x00B9; +pub const EM_GETLINECOUNT: ::WORD = 0x00BA; +pub const EM_LINEINDEX: ::WORD = 0x00BB; +pub const EM_SETHANDLE: ::WORD = 0x00BC; +pub const EM_GETHANDLE: ::WORD = 0x00BD; +pub const EM_GETTHUMB: ::WORD = 0x00BE; +pub const EM_LINELENGTH: ::WORD = 0x00C1; +pub const EM_REPLACESEL: ::WORD = 0x00C2; +pub const EM_GETLINE: ::WORD = 0x00C4; +pub const EM_LIMITTEXT: ::WORD = 0x00C5; +pub const EM_CANUNDO: ::WORD = 0x00C6; +pub const EM_UNDO: ::WORD = 0x00C7; +pub const EM_FMTLINES: ::WORD = 0x00C8; +pub const EM_LINEFROMCHAR: ::WORD = 0x00C9; +pub const EM_SETTABSTOPS: ::WORD = 0x00CB; +pub const EM_SETPASSWORDCHAR: ::WORD = 0x00CC; +pub const EM_EMPTYUNDOBUFFER: ::WORD = 0x00CD; +pub const EM_GETFIRSTVISIBLELINE: ::WORD = 0x00CE; +pub const EM_SETREADONLY: ::WORD = 0x00CF; +pub const EM_SETWORDBREAKPROC: ::WORD = 0x00D0; +pub const EM_GETWORDBREAKPROC: ::WORD = 0x00D1; +pub const EM_GETPASSWORDCHAR: ::WORD = 0x00D2; + +pub const EM_SETMARGINS: ::WORD = 0x00D3; +pub const EM_GETMARGINS: ::WORD = 0x00D4; +pub const EM_SETLIMITTEXT: ::WORD = EM_LIMITTEXT; +pub const EM_GETLIMITTEXT: ::WORD = 0x00D5; +pub const EM_POSFROMCHAR: ::WORD = 0x00D6; +pub const EM_CHARFROMPOS: ::WORD = 0x00D7; + +pub const EM_SETIMESTATUS: ::WORD = 0x00D8; +pub const EM_GETIMESTATUS: ::WORD = 0x00D9; + +// EDITWORDBREAKPROC code values +// +pub const WB_LEFT: ::WORD = 0; +pub const WB_RIGHT: ::WORD = 1; +pub const WB_ISDELIMITER: ::WORD = 2; + +pub const BN_CLICKED: ::WORD = 0; +pub const BN_PAINT: ::WORD = 1; +pub const BN_HILITE: ::WORD = 2; +pub const BN_UNHILITE: ::WORD = 3; +pub const BN_DISABLE: ::WORD = 4; +pub const BN_DOUBLECLICKED: ::WORD = 5; +pub const BN_PUSHED: ::WORD = BN_HILITE; +pub const BN_UNPUSHED: ::WORD = BN_UNHILITE; +pub const BN_DBLCLK: ::WORD = BN_DOUBLECLICKED; +pub const BN_SETFOCUS: ::WORD = 6; +pub const BN_KILLFOCUS: ::WORD = 7; +pub const BS_PUSHBUTTON: ::DWORD = 0x00000000; +pub const BS_DEFPUSHBUTTON: ::DWORD = 0x00000001; +pub const BS_CHECKBOX: ::DWORD = 0x00000002; +pub const BS_AUTOCHECKBOX: ::DWORD = 0x00000003; +pub const BS_RADIOBUTTON: ::DWORD = 0x00000004; +pub const BS_3STATE: ::DWORD = 0x00000005; +pub const BS_AUTO3STATE: ::DWORD = 0x00000006; +pub const BS_GROUPBOX: ::DWORD = 0x00000007; +pub const BS_USERBUTTON: ::DWORD = 0x00000008; +pub const BS_AUTORADIOBUTTON: ::DWORD = 0x00000009; +pub const BS_PUSHBOX: ::DWORD = 0x0000000A; +pub const BS_OWNERDRAW: ::DWORD = 0x0000000B; +pub const BS_TYPEMASK: ::DWORD = 0x0000000F; +pub const BS_LEFTTEXT: ::DWORD = 0x00000020; +pub const BS_TEXT: ::DWORD = 0x00000000; +pub const BS_ICON: ::DWORD = 0x00000040; +pub const BS_BITMAP: ::DWORD = 0x00000080; +pub const BS_LEFT: ::DWORD = 0x00000100; +pub const BS_RIGHT: ::DWORD = 0x00000200; +pub const BS_CENTER: ::DWORD = 0x00000300; +pub const BS_TOP: ::DWORD = 0x00000400; +pub const BS_BOTTOM: ::DWORD = 0x00000800; +pub const BS_VCENTER: ::DWORD = 0x00000C00; +pub const BS_PUSHLIKE: ::DWORD = 0x00001000; +pub const BS_MULTILINE: ::DWORD = 0x00002000; +pub const BS_NOTIFY: ::DWORD = 0x00004000; +pub const BS_FLAT: ::DWORD = 0x00008000; +pub const BS_RIGHTBUTTON: ::DWORD = BS_LEFTTEXT; +pub const CCHILDREN_SCROLLBAR: usize = 5; +pub const CDS_UPDATEREGISTRY: ::DWORD = 0x00000001; +pub const CDS_TEST: ::DWORD = 0x00000002; +pub const CDS_FULLSCREEN: ::DWORD = 0x00000004; +pub const CDS_GLOBAL: ::DWORD = 0x00000008; +pub const CDS_SET_PRIMARY: ::DWORD = 0x00000010; +pub const CDS_VIDEOPARAMETERS: ::DWORD = 0x00000020; +pub const CDS_ENABLE_UNSAFE_MODES: ::DWORD = 0x00000100; +pub const CDS_DISABLE_UNSAFE_MODES: ::DWORD = 0x00000200; +pub const CDS_RESET: ::DWORD = 0x40000000; +pub const CDS_RESET_EX: ::DWORD = 0x20000000; +pub const CDS_NORESET: ::DWORD = 0x10000000; +pub const CF_TEXT: ::UINT = 1; +pub const CF_BITMAP: ::UINT = 2; +pub const CF_METAFILEPICT: ::UINT = 3; +pub const CF_SYLK: ::UINT = 4; +pub const CF_DIF: ::UINT = 5; +pub const CF_TIFF: ::UINT = 6; +pub const CF_OEMTEXT: ::UINT = 7; +pub const CF_DIB: ::UINT = 8; +pub const CF_PALETTE: ::UINT = 9; +pub const CF_PENDATA: ::UINT = 10; +pub const CF_RIFF: ::UINT = 11; +pub const CF_WAVE: ::UINT = 12; +pub const CF_UNICODETEXT: ::UINT = 13; +pub const CF_ENHMETAFILE: ::UINT = 14; +pub const CF_HDROP: ::UINT = 15; +pub const CF_LOCALE: ::UINT = 16; +pub const CF_DIBV5: ::UINT = 17; +pub const CF_OWNERDISPLAY: ::UINT = 0x0080; +pub const CF_DSPTEXT: ::UINT = 0x0081; +pub const CF_DSPBITMAP: ::UINT = 0x0082; +pub const CF_DSPENHMETAFILE: ::UINT = 0x008E; +pub const CF_DSPMETAFILEPICT: ::UINT = 0x0083; +pub const CF_PRIVATEFIRST: ::UINT = 0x0200; +pub const CF_PRIVATELAST: ::UINT = 0x02FF; +pub const CF_GDIOBJFIRST: ::UINT = 0x0300; +pub const CF_GDIOBJLAST: ::UINT = 0x03FF; +pub const CS_VREDRAW: ::DWORD = 0x0001; +pub const CS_HREDRAW: ::DWORD = 0x0002; +pub const CS_DBLCLKS: ::DWORD = 0x0008; +pub const CS_OWNDC: ::DWORD = 0x0020; +pub const CS_CLASSDC: ::DWORD = 0x0040; +pub const CS_PARENTDC: ::DWORD = 0x0080; +pub const CS_NOCLOSE: ::DWORD = 0x0200; +pub const CS_SAVEBITS: ::DWORD = 0x0800; +pub const CS_BYTEALIGNCLIENT: ::DWORD = 0x1000; +pub const CS_BYTEALIGNWINDOW: ::DWORD = 0x2000; +pub const CS_GLOBALCLASS: ::DWORD = 0x4000; +pub const CS_IME: ::DWORD = 0x00010000; +pub const CS_DROPSHADOW: ::DWORD = 0x00020000; +pub const DFC_CAPTION: ::UINT = 1; +pub const DFC_MENU: ::UINT = 2; +pub const DFC_SCROLL: ::UINT = 3; +pub const DFC_BUTTON: ::UINT = 4; +pub const DFCS_CAPTIONCLOSE: ::UINT = 0x0000; +pub const DFCS_CAPTIONMIN: ::UINT = 0x0001; +pub const DFCS_CAPTIONMAX: ::UINT = 0x0002; +pub const DFCS_CAPTIONRESTORE: ::UINT = 0x0003; +pub const DFCS_CAPTIONHELP: ::UINT = 0x0004; +pub const DFCS_MENUARROW: ::UINT = 0x0000; +pub const DFCS_MENUCHECK: ::UINT = 0x0001; +pub const DFCS_MENUBULLET: ::UINT = 0x0002; +pub const DFCS_MENUARROWRIGHT: ::UINT = 0x0004; +pub const DFCS_SCROLLUP: ::UINT = 0x0000; +pub const DFCS_SCROLLDOWN: ::UINT = 0x0001; +pub const DFCS_SCROLLLEFT: ::UINT = 0x0002; +pub const DFCS_SCROLLRIGHT: ::UINT = 0x0003; +pub const DFCS_SCROLLCOMBOBOX: ::UINT = 0x0005; +pub const DFCS_SCROLLSIZEGRIP: ::UINT = 0x0008; +pub const DFCS_SCROLLSIZEGRIPRIGHT: ::UINT = 0x0010; +pub const DFCS_BUTTONCHECK: ::UINT = 0x0000; +pub const DFCS_BUTTONRADIOIMAGE: ::UINT = 0x0001; +pub const DFCS_BUTTONRADIOMASK: ::UINT = 0x0002; +pub const DFCS_BUTTONRADIO: ::UINT = 0x0004; +pub const DFCS_BUTTON3STATE: ::UINT = 0x0008; +pub const DFCS_BUTTONPUSH: ::UINT = 0x0010; +pub const DFCS_INACTIVE: ::UINT = 0x0100; +pub const DFCS_PUSHED: ::UINT = 0x0200; +pub const DFCS_CHECKED: ::UINT = 0x0400; +// if WINVER >= 0x0500 +pub const DFCS_TRANSPARENT: ::UINT = 0x0800; +pub const DFCS_HOT: ::UINT = 0x1000; +// end if WINVER >= 0x0500 +pub const DFCS_ADJUSTRECT: ::UINT = 0x2000; +pub const DFCS_FLAT: ::UINT = 0x4000; +pub const DFCS_MONO: ::UINT = 0x8000; +pub const CW_USEDEFAULT: ::c_int = 0x80000000u32 as ::c_int; +pub const DISP_CHANGE_SUCCESSFUL: ::LONG = 0; +pub const DISP_CHANGE_RESTART: ::LONG = 1; +pub const DISP_CHANGE_FAILED: ::LONG = -1; +pub const DISP_CHANGE_BADMODE: ::LONG = -2; +pub const DISP_CHANGE_NOTUPDATED: ::LONG = -3; +pub const DISP_CHANGE_BADFLAGS: ::LONG = -4; +pub const DISP_CHANGE_BADPARAM: ::LONG = -5; +pub const DISP_CHANGE_BADDUALVIEW: ::LONG = -6; +pub const EDD_GET_DEVICE_INTERFACE_NAME: ::DWORD = 0x00000001; +pub const ENUM_CURRENT_SETTINGS: ::DWORD = 0xFFFFFFFF; +pub const ENUM_REGISTRY_SETTINGS: ::DWORD = 0xFFFFFFFE; +pub const GW_HWNDFIRST: ::UINT = 0; +pub const GW_HWNDLAST: ::UINT = 1; +pub const GW_HWNDNEXT: ::UINT = 2; +pub const GW_HWNDPREV: ::UINT = 3; +pub const GW_OWNER: ::UINT = 4; +pub const GW_CHILD: ::UINT = 5; +pub const GW_ENABLEDPOPUP: ::UINT = 6; +pub const GW_MAX: ::UINT = 6; +pub const HTERROR: ::c_int = -2; +pub const HTTRANSPARENT: ::c_int = -1; +pub const HTNOWHERE: ::c_int = 0; +pub const HTCLIENT: ::c_int = 1; +pub const HTCAPTION: ::c_int = 2; +pub const HTSYSMENU: ::c_int = 3; +pub const HTGROWBOX: ::c_int = 4; +pub const HTSIZE: ::c_int = HTGROWBOX; +pub const HTMENU: ::c_int = 5; +pub const HTHSCROLL: ::c_int = 6; +pub const HTVSCROLL: ::c_int = 7; +pub const HTMINBUTTON: ::c_int = 8; +pub const HTMAXBUTTON: ::c_int = 9; +pub const HTLEFT: ::c_int = 10; +pub const HTRIGHT: ::c_int = 11; +pub const HTTOP: ::c_int = 12; +pub const HTTOPLEFT: ::c_int = 13; +pub const HTTOPRIGHT: ::c_int = 14; +pub const HTBOTTOM: ::c_int = 15; +pub const HTBOTTOMLEFT: ::c_int = 16; +pub const HTBOTTOMRIGHT: ::c_int = 17; +pub const HTBORDER: ::c_int = 18; +pub const HTREDUCE: ::c_int = HTMINBUTTON; +pub const HTZOOM: ::c_int = HTMAXBUTTON; +pub const HTSIZEFIRST: ::c_int = HTLEFT; +pub const HTSIZELAST: ::c_int = HTBOTTOMRIGHT; +pub const HTOBJECT: ::c_int = 19; +pub const HTCLOSE: ::c_int = 20; +pub const HTHELP: ::c_int = 21; +pub const LSFW_LOCK: ::UINT = 1; +pub const LSFW_UNLOCK: ::UINT = 2; +pub const MDITILE_VERTICAL: ::UINT = 0x0000; +pub const MDITILE_HORIZONTAL: ::UINT = 0x0001; +pub const MDITILE_SKIPDISABLED: ::UINT = 0x0002; +pub const MDITILE_ZORDER: ::UINT = 0x0004; +pub const MB_OK: ::DWORD = 0x00000000; +pub const MB_OKCANCEL: ::DWORD = 0x00000001; +pub const MB_ABORTRETRYIGNORE: ::DWORD = 0x00000002; +pub const MB_YESNOCANCEL: ::DWORD = 0x00000003; +pub const MB_YESNO: ::DWORD = 0x00000004; +pub const MB_RETRYCANCEL: ::DWORD = 0x00000005; +pub const MB_CANCELTRYCONTINUE: ::DWORD = 0x00000006; +pub const MB_ICONHAND: ::DWORD = 0x00000010; +pub const MB_ICONQUESTION: ::DWORD = 0x00000020; +pub const MB_ICONEXCLAMATION: ::DWORD = 0x00000030; +pub const MB_ICONASTERISK: ::DWORD = 0x00000040; +pub const MB_USERICON: ::DWORD = 0x00000080; +pub const MB_ICONWARNING: ::DWORD = MB_ICONEXCLAMATION; +pub const MB_ICONERROR: ::DWORD = MB_ICONHAND; +pub const MB_ICONINFORMATION: ::DWORD = MB_ICONASTERISK; +pub const MB_ICONSTOP: ::DWORD = MB_ICONHAND; +pub const MB_DEFBUTTON1: ::DWORD = 0x00000000; +pub const MB_DEFBUTTON2: ::DWORD = 0x00000100; +pub const MB_DEFBUTTON3: ::DWORD = 0x00000200; +pub const MB_DEFBUTTON4: ::DWORD = 0x00000300; +pub const MB_APPLMODAL: ::DWORD = 0x00000000; +pub const MB_SYSTEMMODAL: ::DWORD = 0x00001000; +pub const MB_TASKMODAL: ::DWORD = 0x00002000; +pub const MB_HELP: ::DWORD = 0x00004000; +pub const MB_NOFOCUS: ::DWORD = 0x00008000; +pub const MB_SETFOREGROUND: ::DWORD = 0x00010000; +pub const MB_DEFAULT_DESKTOP_ONLY: ::DWORD = 0x00020000; +pub const MB_TOPMOST: ::DWORD = 0x00040000; +pub const MB_RIGHT: ::DWORD = 0x00080000; +pub const MB_RTLREADING: ::DWORD = 0x00100000; +pub const MB_SERVICE_NOTIFICATION: ::DWORD = 0x00200000; +pub const MB_SERVICE_NOTIFICATION_NT3X: ::DWORD = 0x00040000; +pub const MB_TYPEMASK: ::DWORD = 0x0000000F; +pub const MB_ICONMASK: ::DWORD = 0x000000F0; +pub const MB_DEFMASK: ::DWORD = 0x00000F00; +pub const MB_MODEMASK: ::DWORD = 0x00003000; +pub const MB_MISCMASK: ::DWORD = 0x0000C000; +pub const MF_BITMAP: ::UINT = 0x00000004; +pub const MF_CHECKED: ::UINT = 0x00000008; +pub const MF_DISABLED: ::UINT = 0x00000002; +pub const MF_ENABLED: ::UINT = 0x00000000; +pub const MF_GRAYED: ::UINT = 0x00000001; +pub const MF_MENUBARBREAK: ::UINT = 0x00000020; +pub const MF_MENUBREAK: ::UINT = 0x00000040; +pub const MF_OWNERDRAW: ::UINT = 0x00000100; +pub const MF_POPUP: ::UINT = 0x00000010; +pub const MF_SEPARATOR: ::UINT = 0x00000800; +pub const MF_STRING: ::UINT = 0x00000000; +pub const MF_UNCHECKED: ::UINT = 0x00000000; +pub const SB_HORZ: ::c_int = 0; +pub const SB_VERT: ::c_int = 1; +pub const SB_CTL: ::c_int = 2; +pub const SB_BOTH: ::c_int = 3; +pub const SW_HIDE: ::c_int = 0; +pub const SW_SHOWNORMAL: ::c_int = 1; +pub const SW_NORMAL: ::c_int = 1; +pub const SW_SHOWMINIMIZED: ::c_int = 2; +pub const SW_SHOWMAXIMIZED: ::c_int = 3; +pub const SW_MAXIMIZE: ::c_int = 3; +pub const SW_SHOWNOACTIVATE: ::c_int = 4; +pub const SW_SHOW: ::c_int = 5; +pub const SW_MINIMIZE: ::c_int = 6; +pub const SW_SHOWMINNOACTIVE: ::c_int = 7; +pub const SW_SHOWNA: ::c_int = 8; +pub const SW_RESTORE: ::c_int = 9; +pub const SW_SHOWDEFAULT: ::c_int = 10; +pub const SW_FORCEMINIMIZE: ::c_int = 11; +pub const SW_MAX: ::c_int = 11; +pub const SWP_NOSIZE: ::UINT = 0x0001; +pub const SWP_NOMOVE: ::UINT = 0x0002; +pub const SWP_NOZORDER: ::UINT = 0x0004; +pub const SWP_NOREDRAW: ::UINT = 0x0008; +pub const SWP_NOACTIVATE: ::UINT = 0x0010; +pub const SWP_FRAMECHANGED: ::UINT = 0x0020; +pub const SWP_SHOWWINDOW: ::UINT = 0x0040; +pub const SWP_HIDEWINDOW: ::UINT = 0x0080; +pub const SWP_NOCOPYBITS: ::UINT = 0x0100; +pub const SWP_NOOWNERZORDER: ::UINT = 0x0200; +pub const SWP_NOSENDCHANGING: ::UINT = 0x0400; +pub const SWP_DRAWFRAME: ::UINT = SWP_FRAMECHANGED; +pub const SWP_NOREPOSITION: ::UINT = SWP_NOOWNERZORDER; +pub const SWP_DEFERERASE: ::UINT = 0x2000; +pub const SWP_ASYNCWINDOWPOS: ::UINT = 0x4000; +pub const VK_LBUTTON: ::c_int = 0x01; +pub const VK_RBUTTON: ::c_int = 0x02; +pub const VK_CANCEL: ::c_int = 0x03; +pub const VK_MBUTTON: ::c_int = 0x04; +pub const VK_XBUTTON1: ::c_int = 0x05; +pub const VK_XBUTTON2: ::c_int = 0x06; +pub const VK_BACK: ::c_int = 0x08; +pub const VK_TAB: ::c_int = 0x09; +pub const VK_CLEAR: ::c_int = 0x0C; +pub const VK_RETURN: ::c_int = 0x0D; +pub const VK_SHIFT: ::c_int = 0x10; +pub const VK_CONTROL: ::c_int = 0x11; +pub const VK_MENU: ::c_int = 0x12; +pub const VK_PAUSE: ::c_int = 0x13; +pub const VK_CAPITAL: ::c_int = 0x14; +pub const VK_KANA: ::c_int = 0x15; +pub const VK_HANGUEL: ::c_int = 0x15; +pub const VK_HANGUL: ::c_int = 0x15; +pub const VK_JUNJA: ::c_int = 0x17; +pub const VK_FINAL: ::c_int = 0x18; +pub const VK_HANJA: ::c_int = 0x19; +pub const VK_KANJI: ::c_int = 0x19; +pub const VK_ESCAPE: ::c_int = 0x1B; +pub const VK_CONVERT: ::c_int = 0x1C; +pub const VK_NONCONVERT: ::c_int = 0x1D; +pub const VK_ACCEPT: ::c_int = 0x1E; +pub const VK_MODECHANGE: ::c_int = 0x1F; +pub const VK_SPACE: ::c_int = 0x20; +pub const VK_PRIOR: ::c_int = 0x21; +pub const VK_NEXT: ::c_int = 0x22; +pub const VK_END: ::c_int = 0x23; +pub const VK_HOME: ::c_int = 0x24; +pub const VK_LEFT: ::c_int = 0x25; +pub const VK_UP: ::c_int = 0x26; +pub const VK_RIGHT: ::c_int = 0x27; +pub const VK_DOWN: ::c_int = 0x28; +pub const VK_SELECT: ::c_int = 0x29; +pub const VK_PRINT: ::c_int = 0x2A; +pub const VK_EXECUTE: ::c_int = 0x2B; +pub const VK_SNAPSHOT: ::c_int = 0x2C; +pub const VK_INSERT: ::c_int = 0x2D; +pub const VK_DELETE: ::c_int = 0x2E; +pub const VK_HELP: ::c_int = 0x2F; +pub const VK_LWIN: ::c_int = 0x5B; +pub const VK_RWIN: ::c_int = 0x5C; +pub const VK_APPS: ::c_int = 0x5D; +pub const VK_SLEEP: ::c_int = 0x5F; +pub const VK_NUMPAD0: ::c_int = 0x60; +pub const VK_NUMPAD1: ::c_int = 0x61; +pub const VK_NUMPAD2: ::c_int = 0x62; +pub const VK_NUMPAD3: ::c_int = 0x63; +pub const VK_NUMPAD4: ::c_int = 0x64; +pub const VK_NUMPAD5: ::c_int = 0x65; +pub const VK_NUMPAD6: ::c_int = 0x66; +pub const VK_NUMPAD7: ::c_int = 0x67; +pub const VK_NUMPAD8: ::c_int = 0x68; +pub const VK_NUMPAD9: ::c_int = 0x69; +pub const VK_MULTIPLY: ::c_int = 0x6A; +pub const VK_ADD: ::c_int = 0x6B; +pub const VK_SEPARATOR: ::c_int = 0x6C; +pub const VK_SUBTRACT: ::c_int = 0x6D; +pub const VK_DECIMAL: ::c_int = 0x6E; +pub const VK_DIVIDE: ::c_int = 0x6F; +pub const VK_F1: ::c_int = 0x70; +pub const VK_F2: ::c_int = 0x71; +pub const VK_F3: ::c_int = 0x72; +pub const VK_F4: ::c_int = 0x73; +pub const VK_F5: ::c_int = 0x74; +pub const VK_F6: ::c_int = 0x75; +pub const VK_F7: ::c_int = 0x76; +pub const VK_F8: ::c_int = 0x77; +pub const VK_F9: ::c_int = 0x78; +pub const VK_F10: ::c_int = 0x79; +pub const VK_F11: ::c_int = 0x7A; +pub const VK_F12: ::c_int = 0x7B; +pub const VK_F13: ::c_int = 0x7C; +pub const VK_F14: ::c_int = 0x7D; +pub const VK_F15: ::c_int = 0x7E; +pub const VK_F16: ::c_int = 0x7F; +pub const VK_F17: ::c_int = 0x80; +pub const VK_F18: ::c_int = 0x81; +pub const VK_F19: ::c_int = 0x82; +pub const VK_F20: ::c_int = 0x83; +pub const VK_F21: ::c_int = 0x84; +pub const VK_F22: ::c_int = 0x85; +pub const VK_F23: ::c_int = 0x86; +pub const VK_F24: ::c_int = 0x87; +pub const VK_NUMLOCK: ::c_int = 0x90; +pub const VK_SCROLL: ::c_int = 0x91; +pub const VK_OEM_NEC_EQUAL: ::c_int = 0x92; +pub const VK_OEM_FJ_JISHO: ::c_int = 0x92; +pub const VK_OEM_FJ_MASSHOU: ::c_int = 0x93; +pub const VK_OEM_FJ_TOUROKU: ::c_int = 0x94; +pub const VK_OEM_FJ_LOYA: ::c_int = 0x95; +pub const VK_OEM_FJ_ROYA: ::c_int = 0x96; +pub const VK_LSHIFT: ::c_int = 0xA0; +pub const VK_RSHIFT: ::c_int = 0xA1; +pub const VK_LCONTROL: ::c_int = 0xA2; +pub const VK_RCONTROL: ::c_int = 0xA3; +pub const VK_LMENU: ::c_int = 0xA4; +pub const VK_RMENU: ::c_int = 0xA5; +pub const VK_BROWSER_BACK: ::c_int = 0xA6; +pub const VK_BROWSER_FORWARD: ::c_int = 0xA7; +pub const VK_BROWSER_REFRESH: ::c_int = 0xA8; +pub const VK_BROWSER_STOP: ::c_int = 0xA9; +pub const VK_BROWSER_SEARCH: ::c_int = 0xAA; +pub const VK_BROWSER_FAVORITES: ::c_int = 0xAB; +pub const VK_BROWSER_HOME: ::c_int = 0xAC; +pub const VK_VOLUME_MUTE: ::c_int = 0xAD; +pub const VK_VOLUME_DOWN: ::c_int = 0xAE; +pub const VK_VOLUME_UP: ::c_int = 0xAF; +pub const VK_MEDIA_NEXT_TRACK: ::c_int = 0xB0; +pub const VK_MEDIA_PREV_TRACK: ::c_int = 0xB1; +pub const VK_MEDIA_STOP: ::c_int = 0xB2; +pub const VK_MEDIA_PLAY_PAUSE: ::c_int = 0xB3; +pub const VK_LAUNCH_MAIL: ::c_int = 0xB4; +pub const VK_LAUNCH_MEDIA_SELECT: ::c_int = 0xB5; +pub const VK_LAUNCH_APP1: ::c_int = 0xB6; +pub const VK_LAUNCH_APP2: ::c_int = 0xB7; +pub const VK_OEM_1: ::c_int = 0xBA; +pub const VK_OEM_PLUS: ::c_int = 0xBB; +pub const VK_OEM_COMMA: ::c_int = 0xBC; +pub const VK_OEM_MINUS: ::c_int = 0xBD; +pub const VK_OEM_PERIOD: ::c_int = 0xBE; +pub const VK_OEM_2: ::c_int = 0xBF; +pub const VK_OEM_3: ::c_int = 0xC0; +pub const VK_OEM_4: ::c_int = 0xDB; +pub const VK_OEM_5: ::c_int = 0xDC; +pub const VK_OEM_6: ::c_int = 0xDD; +pub const VK_OEM_7: ::c_int = 0xDE; +pub const VK_OEM_8: ::c_int = 0xDF; +pub const VK_OEM_AX: ::c_int = 0xE1; +pub const VK_OEM_102: ::c_int = 0xE2; +pub const VK_ICO_HELP: ::c_int = 0xE3; +pub const VK_ICO_00: ::c_int = 0xE4; +pub const VK_PROCESSKEY: ::c_int = 0xE5; +pub const VK_ICO_CLEAR: ::c_int = 0xE6; +pub const VK_PACKET: ::c_int = 0xE7; +pub const VK_OEM_RESET: ::c_int = 0xE9; +pub const VK_OEM_JUMP: ::c_int = 0xEA; +pub const VK_OEM_PA1: ::c_int = 0xEB; +pub const VK_OEM_PA2: ::c_int = 0xEC; +pub const VK_OEM_PA3: ::c_int = 0xED; +pub const VK_OEM_WSCTRL: ::c_int = 0xEE; +pub const VK_OEM_CUSEL: ::c_int = 0xEF; +pub const VK_OEM_ATTN: ::c_int = 0xF0; +pub const VK_OEM_FINISH: ::c_int = 0xF1; +pub const VK_OEM_COPY: ::c_int = 0xF2; +pub const VK_OEM_AUTO: ::c_int = 0xF3; +pub const VK_OEM_ENLW: ::c_int = 0xF4; +pub const VK_OEM_BACKTAB: ::c_int = 0xF5; +pub const VK_ATTN: ::c_int = 0xF6; +pub const VK_CRSEL: ::c_int = 0xF7; +pub const VK_EXSEL: ::c_int = 0xF8; +pub const VK_EREOF: ::c_int = 0xF9; +pub const VK_PLAY: ::c_int = 0xFA; +pub const VK_ZOOM: ::c_int = 0xFB; +pub const VK_NONAME: ::c_int = 0xFC; +pub const VK_PA1: ::c_int = 0xFD; +pub const VK_OEM_CLEAR: ::c_int = 0xFE; +// if _WIN32_WINNT >= 0x0500 +pub const APPCOMMAND_BROWSER_BACKWARD: ::c_short = 1; +pub const APPCOMMAND_BROWSER_FORWARD: ::c_short = 2; +pub const APPCOMMAND_BROWSER_REFRESH: ::c_short = 3; +pub const APPCOMMAND_BROWSER_STOP: ::c_short = 4; +pub const APPCOMMAND_BROWSER_SEARCH: ::c_short = 5; +pub const APPCOMMAND_BROWSER_FAVORITES: ::c_short = 6; +pub const APPCOMMAND_BROWSER_HOME: ::c_short = 7; +pub const APPCOMMAND_VOLUME_MUTE: ::c_short = 8; +pub const APPCOMMAND_VOLUME_DOWN: ::c_short = 9; +pub const APPCOMMAND_VOLUME_UP: ::c_short = 10; +pub const APPCOMMAND_MEDIA_NEXTTRACK: ::c_short = 11; +pub const APPCOMMAND_MEDIA_PREVIOUSTRACK: ::c_short = 12; +pub const APPCOMMAND_MEDIA_STOP: ::c_short = 13; +pub const APPCOMMAND_MEDIA_PLAY_PAUSE: ::c_short = 14; +pub const APPCOMMAND_LAUNCH_MAIL: ::c_short = 15; +pub const APPCOMMAND_LAUNCH_MEDIA_SELECT: ::c_short = 16; +pub const APPCOMMAND_LAUNCH_APP1: ::c_short = 17; +pub const APPCOMMAND_LAUNCH_APP2: ::c_short = 18; +pub const APPCOMMAND_BASS_DOWN: ::c_short = 19; +pub const APPCOMMAND_BASS_BOOST: ::c_short = 20; +pub const APPCOMMAND_BASS_UP: ::c_short = 21; +pub const APPCOMMAND_TREBLE_DOWN: ::c_short = 22; +pub const APPCOMMAND_TREBLE_UP: ::c_short = 23; +// if _WIN32_WINNT >= 0x0501 +pub const APPCOMMAND_MICROPHONE_VOLUME_MUTE: ::c_short = 24; +pub const APPCOMMAND_MICROPHONE_VOLUME_DOWN: ::c_short = 25; +pub const APPCOMMAND_MICROPHONE_VOLUME_UP: ::c_short = 26; +pub const APPCOMMAND_HELP: ::c_short = 27; +pub const APPCOMMAND_FIND: ::c_short = 28; +pub const APPCOMMAND_NEW: ::c_short = 29; +pub const APPCOMMAND_OPEN: ::c_short = 30; +pub const APPCOMMAND_CLOSE: ::c_short = 31; +pub const APPCOMMAND_SAVE: ::c_short = 32; +pub const APPCOMMAND_PRINT: ::c_short = 33; +pub const APPCOMMAND_UNDO: ::c_short = 34; +pub const APPCOMMAND_REDO: ::c_short = 35; +pub const APPCOMMAND_COPY: ::c_short = 36; +pub const APPCOMMAND_CUT: ::c_short = 37; +pub const APPCOMMAND_PASTE: ::c_short = 38; +pub const APPCOMMAND_REPLY_TO_MAIL: ::c_short = 39; +pub const APPCOMMAND_FORWARD_MAIL: ::c_short = 40; +pub const APPCOMMAND_SEND_MAIL: ::c_short = 41; +pub const APPCOMMAND_SPELL_CHECK: ::c_short = 42; +pub const APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: ::c_short = 43; +pub const APPCOMMAND_MIC_ON_OFF_TOGGLE: ::c_short = 44; +pub const APPCOMMAND_CORRECTION_LIST: ::c_short = 45; +pub const APPCOMMAND_MEDIA_PLAY: ::c_short = 46; +pub const APPCOMMAND_MEDIA_PAUSE: ::c_short = 47; +pub const APPCOMMAND_MEDIA_RECORD: ::c_short = 48; +pub const APPCOMMAND_MEDIA_FAST_FORWARD: ::c_short = 49; +pub const APPCOMMAND_MEDIA_REWIND: ::c_short = 50; +pub const APPCOMMAND_MEDIA_CHANNEL_UP: ::c_short = 51; +pub const APPCOMMAND_MEDIA_CHANNEL_DOWN: ::c_short = 52; +// end if _WIN32_WINNT >= 0x0501 +// if _WIN32_WINNT >= 0x0600 +pub const APPCOMMAND_DELETE: ::c_short = 53; +pub const APPCOMMAND_DWM_FLIP3D: ::c_short = 54; +// end if _WIN32_WINNT >= 0x0600 +pub const WM_NULL: ::UINT = 0x0000; +pub const WM_CREATE: ::UINT = 0x0001; +pub const WM_DESTROY: ::UINT = 0x0002; +pub const WM_MOVE: ::UINT = 0x0003; +pub const WM_SIZE: ::UINT = 0x0005; +pub const WM_ACTIVATE: ::UINT = 0x0006; +pub const WM_SETFOCUS: ::UINT = 0x0007; +pub const WM_KILLFOCUS: ::UINT = 0x0008; +pub const WM_ENABLE: ::UINT = 0x000A; +pub const WM_SETREDRAW: ::UINT = 0x000B; +pub const WM_SETTEXT: ::UINT = 0x000C; +pub const WM_GETTEXT: ::UINT = 0x000D; +pub const WM_GETTEXTLENGTH: ::UINT = 0x000E; +pub const WM_PAINT: ::UINT = 0x000F; +pub const WM_CLOSE: ::UINT = 0x0010; +pub const WM_QUERYENDSESSION: ::UINT = 0x0011; +pub const WM_QUERYOPEN: ::UINT = 0x0013; +pub const WM_ENDSESSION: ::UINT = 0x0016; +pub const WM_QUIT: ::UINT = 0x0012; +pub const WM_ERASEBKGND: ::UINT = 0x0014; +pub const WM_SYSCOLORCHANGE: ::UINT = 0x0015; +pub const WM_SHOWWINDOW: ::UINT = 0x0018; +pub const WM_WININICHANGE: ::UINT = 0x001A; +pub const WM_SETTINGCHANGE: ::UINT = WM_WININICHANGE; +pub const WM_DEVMODECHANGE: ::UINT = 0x001B; +pub const WM_ACTIVATEAPP: ::UINT = 0x001C; +pub const WM_FONTCHANGE: ::UINT = 0x001D; +pub const WM_TIMECHANGE: ::UINT = 0x001E; +pub const WM_CANCELMODE: ::UINT = 0x001F; +pub const WM_SETCURSOR: ::UINT = 0x0020; +pub const WM_MOUSEACTIVATE: ::UINT = 0x0021; +pub const WM_CHILDACTIVATE: ::UINT = 0x0022; +pub const WM_QUEUESYNC: ::UINT = 0x0023; +pub const WM_GETMINMAXINFO: ::UINT = 0x0024; +pub const WM_PAINTICON: ::UINT = 0x0026; +pub const WM_ICONERASEBKGND: ::UINT = 0x0027; +pub const WM_NEXTDLGCTL: ::UINT = 0x0028; +pub const WM_SPOOLERSTATUS: ::UINT = 0x002A; +pub const WM_DRAWITEM: ::UINT = 0x002B; +pub const WM_MEASUREITEM: ::UINT = 0x002C; +pub const WM_DELETEITEM: ::UINT = 0x002D; +pub const WM_VKEYTOITEM: ::UINT = 0x002E; +pub const WM_CHARTOITEM: ::UINT = 0x002F; +pub const WM_SETFONT: ::UINT = 0x0030; +pub const WM_GETFONT: ::UINT = 0x0031; +pub const WM_SETHOTKEY: ::UINT = 0x0032; +pub const WM_GETHOTKEY: ::UINT = 0x0033; +pub const WM_QUERYDRAGICON: ::UINT = 0x0037; +pub const WM_COMPAREITEM: ::UINT = 0x0039; +pub const WM_GETOBJECT: ::UINT = 0x003D; +pub const WM_COMPACTING: ::UINT = 0x0041; +pub const WM_COMMNOTIFY: ::UINT = 0x0044; +pub const WM_WINDOWPOSCHANGING: ::UINT = 0x0046; +pub const WM_WINDOWPOSCHANGED: ::UINT = 0x0047; +pub const WM_POWER: ::UINT = 0x0048; +pub const WM_COPYDATA: ::UINT = 0x004A; +pub const WM_CANCELJOURNAL: ::UINT = 0x004B; +pub const WM_NOTIFY: ::UINT = 0x004E; +pub const WM_INPUTLANGCHANGEREQUEST: ::UINT = 0x0050; +pub const WM_INPUTLANGCHANGE: ::UINT = 0x0051; +pub const WM_TCARD: ::UINT = 0x0052; +pub const WM_HELP: ::UINT = 0x0053; +pub const WM_USERCHANGED: ::UINT = 0x0054; +pub const WM_NOTIFYFORMAT: ::UINT = 0x0055; +pub const WM_CONTEXTMENU: ::UINT = 0x007B; +pub const WM_STYLECHANGING: ::UINT = 0x007C; +pub const WM_STYLECHANGED: ::UINT = 0x007D; +pub const WM_DISPLAYCHANGE: ::UINT = 0x007E; +pub const WM_GETICON: ::UINT = 0x007F; +pub const WM_SETICON: ::UINT = 0x0080; +pub const WM_NCCREATE: ::UINT = 0x0081; +pub const WM_NCDESTROY: ::UINT = 0x0082; +pub const WM_NCCALCSIZE: ::UINT = 0x0083; +pub const WM_NCHITTEST: ::UINT = 0x0084; +pub const WM_NCPAINT: ::UINT = 0x0085; +pub const WM_NCACTIVATE: ::UINT = 0x0086; +pub const WM_GETDLGCODE: ::UINT = 0x0087; +pub const WM_SYNCPAINT: ::UINT = 0x0088; +pub const WM_NCMOUSEMOVE: ::UINT = 0x00A0; +pub const WM_NCLBUTTONDOWN: ::UINT = 0x00A1; +pub const WM_NCLBUTTONUP: ::UINT = 0x00A2; +pub const WM_NCLBUTTONDBLCLK: ::UINT = 0x00A3; +pub const WM_NCRBUTTONDOWN: ::UINT = 0x00A4; +pub const WM_NCRBUTTONUP: ::UINT = 0x00A5; +pub const WM_NCRBUTTONDBLCLK: ::UINT = 0x00A6; +pub const WM_NCMBUTTONDOWN: ::UINT = 0x00A7; +pub const WM_NCMBUTTONUP: ::UINT = 0x00A8; +pub const WM_NCMBUTTONDBLCLK: ::UINT = 0x00A9; +pub const WM_NCXBUTTONDOWN: ::UINT = 0x00AB; +pub const WM_NCXBUTTONUP: ::UINT = 0x00AC; +pub const WM_NCXBUTTONDBLCLK: ::UINT = 0x00AD; +pub const WM_INPUT_DEVICE_CHANGE: ::UINT = 0x00FE; +pub const WM_INPUT: ::UINT = 0x00FF; +pub const WM_KEYFIRST: ::UINT = 0x0100; +pub const WM_KEYDOWN: ::UINT = 0x0100; +pub const WM_KEYUP: ::UINT = 0x0101; +pub const WM_CHAR: ::UINT = 0x0102; +pub const WM_DEADCHAR: ::UINT = 0x0103; +pub const WM_SYSKEYDOWN: ::UINT = 0x0104; +pub const WM_SYSKEYUP: ::UINT = 0x0105; +pub const WM_SYSCHAR: ::UINT = 0x0106; +pub const WM_SYSDEADCHAR: ::UINT = 0x0107; +pub const WM_UNICHAR: ::UINT = 0x0109; +pub const WM_KEYLAST: ::UINT = 0x0109; +pub const WM_IME_STARTCOMPOSITION: ::UINT = 0x010D; +pub const WM_IME_ENDCOMPOSITION: ::UINT = 0x010E; +pub const WM_IME_COMPOSITION: ::UINT = 0x010F; +pub const WM_IME_KEYLAST: ::UINT = 0x010F; +pub const WM_INITDIALOG: ::UINT = 0x0110; +pub const WM_COMMAND: ::UINT = 0x0111; +pub const WM_SYSCOMMAND: ::UINT = 0x0112; +pub const WM_TIMER: ::UINT = 0x0113; +pub const WM_HSCROLL: ::UINT = 0x0114; +pub const WM_VSCROLL: ::UINT = 0x0115; +pub const WM_INITMENU: ::UINT = 0x0116; +pub const WM_INITMENUPOPUP: ::UINT = 0x0117; +pub const WM_GESTURE: ::UINT = 0x0119; +pub const WM_GESTURENOTIFY: ::UINT = 0x011A; +pub const WM_MENUSELECT: ::UINT = 0x011F; +pub const WM_MENUCHAR: ::UINT = 0x0120; +pub const WM_ENTERIDLE: ::UINT = 0x0121; +pub const WM_MENURBUTTONUP: ::UINT = 0x0122; +pub const WM_MENUDRAG: ::UINT = 0x0123; +pub const WM_MENUGETOBJECT: ::UINT = 0x0124; +pub const WM_UNINITMENUPOPUP: ::UINT = 0x0125; +pub const WM_MENUCOMMAND: ::UINT = 0x0126; +pub const WM_CHANGEUISTATE: ::UINT = 0x0127; +pub const WM_UPDATEUISTATE: ::UINT = 0x0128; +pub const WM_QUERYUISTATE: ::UINT = 0x0129; +pub const WM_CTLCOLORMSGBOX: ::UINT = 0x0132; +pub const WM_CTLCOLOREDIT: ::UINT = 0x0133; +pub const WM_CTLCOLORLISTBOX: ::UINT = 0x0134; +pub const WM_CTLCOLORBTN: ::UINT = 0x0135; +pub const WM_CTLCOLORDLG: ::UINT = 0x0136; +pub const WM_CTLCOLORSCROLLBAR: ::UINT = 0x0137; +pub const WM_CTLCOLORSTATIC: ::UINT = 0x0138; +pub const WM_MOUSEFIRST: ::UINT = 0x0200; +pub const WM_MOUSEMOVE: ::UINT = 0x0200; +pub const WM_LBUTTONDOWN: ::UINT = 0x0201; +pub const WM_LBUTTONUP: ::UINT = 0x0202; +pub const WM_LBUTTONDBLCLK: ::UINT = 0x0203; +pub const WM_RBUTTONDOWN: ::UINT = 0x0204; +pub const WM_RBUTTONUP: ::UINT = 0x0205; +pub const WM_RBUTTONDBLCLK: ::UINT = 0x0206; +pub const WM_MBUTTONDOWN: ::UINT = 0x0207; +pub const WM_MBUTTONUP: ::UINT = 0x0208; +pub const WM_MBUTTONDBLCLK: ::UINT = 0x0209; +pub const WM_MOUSEWHEEL: ::UINT = 0x020A; +pub const WM_XBUTTONDOWN: ::UINT = 0x020B; +pub const WM_XBUTTONUP: ::UINT = 0x020C; +pub const WM_XBUTTONDBLCLK: ::UINT = 0x020D; +pub const WM_MOUSEHWHEEL: ::UINT = 0x020E; +pub const WM_MOUSELAST: ::UINT = 0x020E; +pub const WM_PARENTNOTIFY: ::UINT = 0x0210; +pub const WM_ENTERMENULOOP: ::UINT = 0x0211; +pub const WM_EXITMENULOOP: ::UINT = 0x0212; +pub const WM_NEXTMENU: ::UINT = 0x0213; +pub const WM_SIZING: ::UINT = 0x0214; +pub const WM_CAPTURECHANGED: ::UINT = 0x0215; +pub const WM_MOVING: ::UINT = 0x0216; +pub const WM_POWERBROADCAST: ::UINT = 0x0218; +pub const WM_DEVICECHANGE: ::UINT = 0x0219; +pub const WM_MDICREATE: ::UINT = 0x0220; +pub const WM_MDIDESTROY: ::UINT = 0x0221; +pub const WM_MDIACTIVATE: ::UINT = 0x0222; +pub const WM_MDIRESTORE: ::UINT = 0x0223; +pub const WM_MDINEXT: ::UINT = 0x0224; +pub const WM_MDIMAXIMIZE: ::UINT = 0x0225; +pub const WM_MDITILE: ::UINT = 0x0226; +pub const WM_MDICASCADE: ::UINT = 0x0227; +pub const WM_MDIICONARRANGE: ::UINT = 0x0228; +pub const WM_MDIGETACTIVE: ::UINT = 0x0229; +pub const WM_MDISETMENU: ::UINT = 0x0230; +pub const WM_ENTERSIZEMOVE: ::UINT = 0x0231; +pub const WM_EXITSIZEMOVE: ::UINT = 0x0232; +pub const WM_DROPFILES: ::UINT = 0x0233; +pub const WM_MDIREFRESHMENU: ::UINT = 0x0234; +pub const WM_POINTERDEVICECHANGE: ::UINT = 0x238; +pub const WM_POINTERDEVICEINRANGE: ::UINT = 0x239; +pub const WM_POINTERDEVICEOUTOFRANGE: ::UINT = 0x23A; +pub const WM_TOUCH: ::UINT = 0x0240; +pub const WM_NCPOINTERUPDATE: ::UINT = 0x0241; +pub const WM_NCPOINTERDOWN: ::UINT = 0x0242; +pub const WM_NCPOINTERUP: ::UINT = 0x0243; +pub const WM_POINTERUPDATE: ::UINT = 0x0245; +pub const WM_POINTERDOWN: ::UINT = 0x0246; +pub const WM_POINTERUP: ::UINT = 0x0247; +pub const WM_POINTERENTER: ::UINT = 0x0249; +pub const WM_POINTERLEAVE: ::UINT = 0x024A; +pub const WM_POINTERACTIVATE: ::UINT = 0x024B; +pub const WM_POINTERCAPTURECHANGED: ::UINT = 0x024C; +pub const WM_TOUCHHITTESTING: ::UINT = 0x024D; +pub const WM_POINTERWHEEL: ::UINT = 0x024E; +pub const WM_POINTERHWHEEL: ::UINT = 0x024F; +pub const WM_IME_SETCONTEXT: ::UINT = 0x0281; +pub const WM_IME_NOTIFY: ::UINT = 0x0282; +pub const WM_IME_CONTROL: ::UINT = 0x0283; +pub const WM_IME_COMPOSITIONFULL: ::UINT = 0x0284; +pub const WM_IME_SELECT: ::UINT = 0x0285; +pub const WM_IME_CHAR: ::UINT = 0x0286; +pub const WM_IME_REQUEST: ::UINT = 0x0288; +pub const WM_IME_KEYDOWN: ::UINT = 0x0290; +pub const WM_IME_KEYUP: ::UINT = 0x0291; +pub const WM_MOUSEHOVER: ::UINT = 0x02A1; +pub const WM_MOUSELEAVE: ::UINT = 0x02A3; +pub const WM_NCMOUSEHOVER: ::UINT = 0x02A0; +pub const WM_NCMOUSELEAVE: ::UINT = 0x02A2; +pub const WM_WTSSESSION_CHANGE: ::UINT = 0x02B1; +pub const WM_TABLET_FIRST: ::UINT = 0x02c0; +pub const WM_TABLET_LAST: ::UINT = 0x02df; +pub const WM_DPICHANGED: ::UINT = 0x02E0; +pub const WM_CUT: ::UINT = 0x0300; +pub const WM_COPY: ::UINT = 0x0301; +pub const WM_PASTE: ::UINT = 0x0302; +pub const WM_CLEAR: ::UINT = 0x0303; +pub const WM_UNDO: ::UINT = 0x0304; +pub const WM_RENDERFORMAT: ::UINT = 0x0305; +pub const WM_RENDERALLFORMATS: ::UINT = 0x0306; +pub const WM_DESTROYCLIPBOARD: ::UINT = 0x0307; +pub const WM_DRAWCLIPBOARD: ::UINT = 0x0308; +pub const WM_PAINTCLIPBOARD: ::UINT = 0x0309; +pub const WM_VSCROLLCLIPBOARD: ::UINT = 0x030A; +pub const WM_SIZECLIPBOARD: ::UINT = 0x030B; +pub const WM_ASKCBFORMATNAME: ::UINT = 0x030C; +pub const WM_CHANGECBCHAIN: ::UINT = 0x030D; +pub const WM_HSCROLLCLIPBOARD: ::UINT = 0x030E; +pub const WM_QUERYNEWPALETTE: ::UINT = 0x030F; +pub const WM_PALETTEISCHANGING: ::UINT = 0x0310; +pub const WM_PALETTECHANGED: ::UINT = 0x0311; +pub const WM_HOTKEY: ::UINT = 0x0312; +pub const WM_PRINT: ::UINT = 0x0317; +pub const WM_PRINTCLIENT: ::UINT = 0x0318; +pub const WM_APPCOMMAND: ::UINT = 0x0319; +pub const WM_THEMECHANGED: ::UINT = 0x031A; +pub const WM_CLIPBOARDUPDATE: ::UINT = 0x031D; +pub const WM_DWMCOMPOSITIONCHANGED: ::UINT = 0x031E; +pub const WM_DWMNCRENDERINGCHANGED: ::UINT = 0x031F; +pub const WM_DWMCOLORIZATIONCOLORCHANGED: ::UINT = 0x0320; +pub const WM_DWMWINDOWMAXIMIZEDCHANGE: ::UINT = 0x0321; +pub const WM_DWMSENDICONICTHUMBNAIL: ::UINT = 0x0323; +pub const WM_DWMSENDICONICLIVEPREVIEWBITMAP: ::UINT = 0x0326; +pub const WM_GETTITLEBARINFOEX: ::UINT = 0x033F; +pub const WM_HANDHELDFIRST: ::UINT = 0x0358; +pub const WM_HANDHELDLAST: ::UINT = 0x035F; +pub const WM_AFXFIRST: ::UINT = 0x0360; +pub const WM_AFXLAST: ::UINT = 0x037F; +pub const WM_PENWINFIRST: ::UINT = 0x0380; +pub const WM_PENWINLAST: ::UINT = 0x038F; +pub const WM_APP: ::UINT = 0x8000; +pub const WM_USER: ::UINT = 0x0400; +pub const WMSZ_LEFT: ::UINT = 1; +pub const WMSZ_RIGHT: ::UINT = 2; +pub const WMSZ_TOP: ::UINT = 3; +pub const WMSZ_TOPLEFT: ::UINT = 4; +pub const WMSZ_TOPRIGHT: ::UINT = 5; +pub const WMSZ_BOTTOM: ::UINT = 6; +pub const WMSZ_BOTTOMLEFT: ::UINT = 7; +pub const WMSZ_BOTTOMRIGHT: ::UINT = 8; +pub const SMTO_NORMAL: ::UINT = 0x0000; +pub const SMTO_BLOCK: ::UINT = 0x0001; +pub const SMTO_ABORTIFHUNG: ::UINT = 0x0002; +pub const SMTO_NOTIMEOUTIFNOTHUNG: ::UINT = 0x0008; +pub const SMTO_ERRORONEXIT: ::UINT = 0x0020; +pub const MA_ACTIVATE: ::UINT = 1; +pub const MA_ACTIVATEANDEAT: ::UINT = 2; +pub const MA_NOACTIVATE: ::UINT = 3; +pub const MA_NOACTIVATEANDEAT: ::UINT = 4; +pub const ICON_SMALL: ::UINT = 0; +pub const ICON_BIG: ::UINT = 1; +pub const ICON_SMALL2: ::UINT = 2; +pub const SIZE_RESTORED: ::UINT = 0; +pub const SIZE_MINIMIZED: ::UINT = 1; +pub const SIZE_MAXIMIZED: ::UINT = 2; +pub const SIZE_MAXSHOW: ::UINT = 3; +pub const SIZE_MAXHIDE: ::UINT = 4; +pub const SIZENORMAL: ::UINT = SIZE_RESTORED; +pub const SIZEICONIC: ::UINT = SIZE_MINIMIZED; +pub const SIZEFULLSCREEN: ::UINT = SIZE_MAXIMIZED; +pub const SIZEZOOMSHOW: ::UINT = SIZE_MAXSHOW; +pub const SIZEZOOMHIDE: ::UINT = SIZE_MAXHIDE; +STRUCT!{struct NCCALCSIZE_PARAMS { + rgrc: [::RECT; 3], + lppos: PWINDOWPOS, +}} +pub type PNCCALCSIZE_PARAMS = *mut NCCALCSIZE_PARAMS; +pub type NPNCCALCSIZE_PARAMS = *mut NCCALCSIZE_PARAMS; +pub type LPNCCALCSIZE_PARAMS = *mut NCCALCSIZE_PARAMS; +pub const WVR_ALIGNTOP: ::UINT = 0x0010; +pub const WVR_ALIGNLEFT: ::UINT = 0x0020; +pub const WVR_ALIGNBOTTOM: ::UINT = 0x0040; +pub const WVR_ALIGNRIGHT: ::UINT = 0x0080; +pub const WVR_HREDRAW: ::UINT = 0x0100; +pub const WVR_VREDRAW: ::UINT = 0x0200; +pub const WVR_REDRAW: ::UINT = WVR_HREDRAW | WVR_VREDRAW; +pub const WVR_VALIDRECTS: ::UINT = 0x0400; +pub const HOVER_DEFAULT: ::UINT = 0xFFFFFFFF; +pub const WS_OVERLAPPED: ::DWORD = 0x00000000; +pub const WS_POPUP: ::DWORD = 0x80000000; +pub const WS_CHILD: ::DWORD = 0x40000000; +pub const WS_MINIMIZE: ::DWORD = 0x20000000; +pub const WS_VISIBLE: ::DWORD = 0x10000000; +pub const WS_DISABLED: ::DWORD = 0x08000000; +pub const WS_CLIPSIBLINGS: ::DWORD = 0x04000000; +pub const WS_CLIPCHILDREN: ::DWORD = 0x02000000; +pub const WS_MAXIMIZE: ::DWORD = 0x01000000; +pub const WS_CAPTION: ::DWORD = 0x00C00000; +pub const WS_BORDER: ::DWORD = 0x00800000; +pub const WS_DLGFRAME: ::DWORD = 0x00400000; +pub const WS_VSCROLL: ::DWORD = 0x00200000; +pub const WS_HSCROLL: ::DWORD = 0x00100000; +pub const WS_SYSMENU: ::DWORD = 0x00080000; +pub const WS_THICKFRAME: ::DWORD = 0x00040000; +pub const WS_GROUP: ::DWORD = 0x00020000; +pub const WS_TABSTOP: ::DWORD = 0x00010000; +pub const WS_MINIMIZEBOX: ::DWORD = 0x00020000; +pub const WS_MAXIMIZEBOX: ::DWORD = 0x00010000; +pub const WS_TILED: ::DWORD = WS_OVERLAPPED; +pub const WS_ICONIC: ::DWORD = WS_MINIMIZE; +pub const WS_SIZEBOX: ::DWORD = WS_THICKFRAME; +pub const WS_TILEDWINDOW: ::DWORD = WS_OVERLAPPEDWINDOW; +pub const WS_OVERLAPPEDWINDOW: ::DWORD = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX; +pub const WS_POPUPWINDOW: ::DWORD = WS_POPUP | WS_BORDER | WS_SYSMENU; +pub const WS_CHILDWINDOW: ::DWORD = WS_CHILD; +pub const WS_EX_DLGMODALFRAME: ::DWORD = 0x00000001; +pub const WS_EX_NOPARENTNOTIFY: ::DWORD = 0x00000004; +pub const WS_EX_TOPMOST: ::DWORD = 0x00000008; +pub const WS_EX_ACCEPTFILES: ::DWORD = 0x00000010; +pub const WS_EX_TRANSPARENT: ::DWORD = 0x00000020; +pub const WS_EX_MDICHILD: ::DWORD = 0x00000040; +pub const WS_EX_TOOLWINDOW: ::DWORD = 0x00000080; +pub const WS_EX_WINDOWEDGE: ::DWORD = 0x00000100; +pub const WS_EX_CLIENTEDGE: ::DWORD = 0x00000200; +pub const WS_EX_CONTEXTHELP: ::DWORD = 0x00000400; +pub const WS_EX_RIGHT: ::DWORD = 0x00001000; +pub const WS_EX_LEFT: ::DWORD = 0x00000000; +pub const WS_EX_RTLREADING: ::DWORD = 0x00002000; +pub const WS_EX_LTRREADING: ::DWORD = 0x00000000; +pub const WS_EX_LEFTSCROLLBAR: ::DWORD = 0x00004000; +pub const WS_EX_RIGHTSCROLLBAR: ::DWORD = 0x00000000; +pub const WS_EX_CONTROLPARENT: ::DWORD = 0x00010000; +pub const WS_EX_STATICEDGE: ::DWORD = 0x00020000; +pub const WS_EX_APPWINDOW: ::DWORD = 0x00040000; +pub const WS_EX_OVERLAPPEDWINDOW: ::DWORD = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE; +pub const WS_EX_PALETTEWINDOW: ::DWORD = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST; +pub const WS_EX_LAYERED: ::DWORD = 0x00080000; +pub const WS_EX_NOINHERITLAYOUT: ::DWORD = 0x00100000; +pub const WS_EX_NOREDIRECTIONBITMAP: ::DWORD = 0x00200000; +pub const WS_EX_LAYOUTRTL: ::DWORD = 0x00400000; +pub const WS_EX_COMPOSITED: ::DWORD = 0x02000000; +pub const WS_EX_NOACTIVATE: ::DWORD = 0x08000000; +pub type NAMEENUMPROCA = Option<unsafe extern "system" fn(::LPSTR, ::LPARAM) -> ::BOOL>; +pub type NAMEENUMPROCW = Option<unsafe extern "system" fn(::LPWSTR, ::LPARAM) -> ::BOOL>; +pub type DESKTOPENUMPROCA = NAMEENUMPROCA; +pub type DESKTOPENUMPROCW = NAMEENUMPROCW; +pub type WINSTAENUMPROCA = NAMEENUMPROCA; +pub type WINSTAENUMPROCW = NAMEENUMPROCW; +pub type WNDENUMPROC = Option<unsafe extern "system" fn(::HWND, ::LPARAM) -> ::BOOL>; +pub type WNDPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::LRESULT>; +pub type DLGPROC = Option<unsafe extern "system" fn( + ::HWND, ::UINT, ::WPARAM, ::LPARAM, +) -> ::INT_PTR>; +pub type HOOKPROC = Option<unsafe extern "system" fn( + code: ::c_int, wParam: ::WPARAM, lParam: ::LPARAM, +) -> ::LRESULT>; +pub type TimerProc = Option<unsafe extern "system" fn( + hwnd: ::HWND, uMsg: ::UINT, idEvent: ::UINT_PTR, dwTime: ::DWORD, +)>; +pub type DRAWSTATEPROC = Option<unsafe extern "system" fn( + ::HDC, ::LPARAM, ::WPARAM, ::c_int, ::c_int, +) -> ::BOOL>; +pub type PROPENUMPROCA = Option<unsafe extern "system" fn(::HWND, ::LPCSTR, ::HANDLE) -> ::BOOL>; +pub type PROPENUMPROCW = Option<unsafe extern "system" fn(::HWND, ::LPCWSTR, ::HANDLE) -> ::BOOL>; +pub type GRAYSTRINGPROC = Option<unsafe extern "system" fn(::HDC, ::LPARAM, ::c_int) -> ::BOOL>; +pub type MSGBOXCALLBACK = Option<unsafe extern "system" fn(LPHELPINFO)>; +pub type WINEVENTPROC = Option<unsafe extern "system" fn( + ::HWINEVENTHOOK, ::DWORD, ::HWND, ::LONG, ::LONG, ::DWORD, ::DWORD, +)>; +pub type HDEVNOTIFY = ::PVOID; +pub type MENUTEMPLATEA = ::VOID; +pub type MENUTEMPLATEW = ::VOID; +STRUCT!{struct MSG { + hwnd: ::HWND, + message: ::UINT, + wParam: ::WPARAM, + lParam: ::LPARAM, + time: ::DWORD, + pt: ::POINT, +}} +pub type PMSG = *mut MSG; +pub type NPMSG = *mut MSG; +pub type LPMSG = *mut MSG; +STRUCT!{struct PAINTSTRUCT { + hdc: ::HDC, + fErase: ::BOOL, + rcPaint: ::RECT, + fRestore: ::BOOL, + fIncUpdate: ::BOOL, + rgbReserved: [::BYTE; 32], +}} +pub type PPAINTSTRUCT = *mut PAINTSTRUCT; +pub type NPPAINTSTRUCT = *mut PAINTSTRUCT; +pub type LPPAINTSTRUCT = *mut PAINTSTRUCT; +STRUCT!{struct WINDOWPLACEMENT { + length: ::UINT, + flags: ::UINT, + showCmd: ::UINT, + ptMinPosition: ::POINT, + ptMaxPosition: ::POINT, + rcNormalPosition: ::RECT, +}} +pub type PWINDOWPLACEMENT = *mut WINDOWPLACEMENT; +pub type LPWINDOWPLACEMENT = *mut WINDOWPLACEMENT; +STRUCT!{nodebug struct WNDCLASSEXW { + cbSize: ::UINT, + style: ::UINT, + lpfnWndProc: WNDPROC, + cbClsExtra: ::c_int, + cbWndExtra: ::c_int, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + hCursor: ::HCURSOR, + hbrBackground: ::HBRUSH, + lpszMenuName: ::LPCWSTR, + lpszClassName: ::LPCWSTR, + hIconSm: ::HICON, +}} +pub type PWNDCLASSEXW = *mut WNDCLASSEXW; +pub type NPWNDCLASSEXW = *mut WNDCLASSEXW; +pub type LPWNDCLASSEXW = *mut WNDCLASSEXW; +STRUCT!{nodebug struct WNDCLASSW { + style: ::UINT, + lpfnWndProc: WNDPROC, + cbClsExtra: ::c_int, + cbWndExtra: ::c_int, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + hCursor: ::HCURSOR, + hbrBackground: ::HBRUSH, + lpszMenuName: ::LPCWSTR, + lpszClassName: ::LPCWSTR, +}} +pub type PWNDCLASSW = *mut WNDCLASSW; +pub type NPWNDCLASSW = *mut WNDCLASSW; +pub type LPWNDCLASSW = *mut WNDCLASSW; +STRUCT!{struct MINMAXINFO { + ptReserved: ::POINT, + ptMaxSize: ::POINT, + ptMaxPosition: ::POINT, + ptMinTrackSize: ::POINT, + ptMaxTrackSize: ::POINT, +}} +STRUCT!{struct SCROLLBARINFO { + cbSize: ::DWORD, + rcScrollBar: ::RECT, + dxyLineButton: ::c_int, + xyThumbTop: ::c_int, + xyThumbBottom: ::c_int, + reserved: ::c_int, + rgstate: [::DWORD; CCHILDREN_SCROLLBAR + 1], +}} +pub type PSCROLLBARINFO = *mut SCROLLBARINFO; +pub type LPSCROLLBARINFO = *mut SCROLLBARINFO; +STRUCT!{struct SCROLLINFO { + cbSize: ::UINT, + fMask: ::UINT, + nMin: ::c_int, + nMax: ::c_int, + nPage: ::UINT, + nPos: ::c_int, + nTrackPos: ::c_int, +}} +pub type LPSCROLLINFO = *mut SCROLLINFO; +pub type LPCSCROLLINFO = *const SCROLLINFO; +STRUCT!{struct SIZE { + cx: ::LONG, + cy: ::LONG, +}} +pub type PSIZE = *mut SIZE; +pub type LPSIZE = *mut SIZE; +pub type SIZEL = SIZE; +pub type PSIZEL = *mut SIZEL; +pub type LPSIZEL = *mut SIZEL; +//1913 +pub const UNICODE_NOCHAR: ::WPARAM = 0xffff; +pub type HDWP = *mut ::HANDLE; +//2193 +pub const WHEEL_DELTA: ::DWORD = 120; +//2206 +pub const XBUTTON1: ::DWORD = 0x0001; +pub const XBUTTON2: ::DWORD = 0x0002; +//2392 +pub const MK_LBUTTON: ::WPARAM = 0x0001; +pub const MK_RBUTTON: ::WPARAM = 0x0002; +pub const MK_SHIFT: ::WPARAM = 0x0004; +pub const MK_CONTROL: ::WPARAM = 0x0008; +pub const MK_MBUTTON: ::WPARAM = 0x0010; +pub const MK_XBUTTON1: ::WPARAM = 0x0020; +pub const MK_XBUTTON2: ::WPARAM = 0x0040; +//2408 +pub const TME_HOVER: ::DWORD = 0x0000_0001; +pub const TME_LEAVE: ::DWORD = 0x0000_0002; +pub const TME_NONCLIENT: ::DWORD = 0x0000_0010; +pub const TME_QUERY: ::DWORD = 0x4000_0000; +pub const TME_CANCEL: ::DWORD = 0x8000_0000; +pub const HWND_BROADCAST: ::HWND = 0xFFFF as ::HWND; +pub const HWND_MESSAGE: ::HWND = -3isize as ::HWND; +STRUCT!{struct TRACKMOUSEEVENT { + cbSize: ::DWORD, + dwFlags: ::DWORD, + hwndTrack: ::HWND, + dwHoverTime: ::DWORD, +}} +pub type LPTRACKMOUSEEVENT = *mut TRACKMOUSEEVENT; +//2575 +STRUCT!{nodebug struct WINDOWPOS { + hwnd: ::HWND, + hwndInsertAfter: ::HWND, + x: ::c_int, + y: ::c_int, + cx: ::c_int, + cy: ::c_int, + flags: ::UINT, +}} +pub type LPWINDOWPOS = *mut WINDOWPOS; +pub type PWINDOWPOS = *mut WINDOWPOS; +//3082 +STRUCT!{struct CREATESTRUCTA { + lpCreateParams: ::LPVOID, + hInstance: ::HINSTANCE, + hMenu: ::HMENU, + hwndParent: ::HWND, + cy: ::c_int, + cx: ::c_int, + y: ::c_int, + x: ::c_int, + style: ::LONG, + lpszName: ::LPCSTR, + lpszClass: ::LPCSTR, + dwExStyle: ::DWORD, +}} +pub type LPCREATESTRUCTA = *mut CREATESTRUCTA; +STRUCT!{struct CREATESTRUCTW { + lpCreateParams: ::LPVOID, + hInstance: ::HINSTANCE, + hMenu: ::HMENU, + hwndParent: ::HWND, + cy: ::c_int, + cx: ::c_int, + y: ::c_int, + x: ::c_int, + style: ::LONG, + lpszName: ::LPCWSTR, + lpszClass: ::LPCWSTR, + dwExStyle: ::DWORD, +}} +pub type LPCREATESTRUCTW = *mut CREATESTRUCTW; +//3145 +STRUCT!{struct NMHDR { + hwndFrom: ::HWND, + idFrom: ::UINT_PTR, + code: ::UINT, // NM_ code +}} +pub type LPNMHDR = *mut NMHDR; +//3400 +pub const PM_NOREMOVE: ::UINT = 0x0000; +pub const PM_REMOVE: ::UINT = 0x0001; +pub const PM_NOYIELD: ::UINT = 0x0002; +pub const PM_QS_INPUT: ::UINT = QS_INPUT << 16; +pub const PM_QS_POSTMESSAGE: ::UINT = (QS_POSTMESSAGE | QS_HOTKEY | QS_TIMER) << 16; +pub const PM_QS_PAINT: ::UINT = QS_PAINT << 16; +pub const PM_QS_SENDMESSAGE: ::UINT = QS_SENDMESSAGE << 16; +// +pub const LWA_COLORKEY: ::DWORD = 0x00000001; +pub const LWA_ALPHA: ::DWORD = 0x00000002; +//3469 +pub const EWX_LOGOFF: ::UINT = 0x00000000; +pub const EWX_SHUTDOWN: ::UINT = 0x00000001; +pub const EWX_REBOOT: ::UINT = 0x00000002; +pub const EWX_FORCE: ::UINT = 0x00000004; +pub const EWX_POWEROFF: ::UINT = 0x00000008; +pub const EWX_FORCEIFHUNG: ::UINT = 0x00000010; +pub const EWX_QUICKRESOLVE: ::UINT = 0x00000020; +pub const EWX_RESTARTAPPS: ::UINT = 0x00000040; +pub const EWX_HYBRID_SHUTDOWN: ::UINT = 0x00400000; +pub const EWX_BOOTOPTIONS: ::UINT = 0x01000000; +//4054 (Win 7 SDK) +STRUCT!{struct FLASHWINFO { + cbSize: ::UINT, + hwnd: ::HWND, + dwFlags: ::DWORD, + uCount: ::UINT, + dwTimeout: ::DWORD, +}} +pub type PFLASHWINFO = *mut FLASHWINFO; +pub const FLASHW_STOP: ::DWORD = 0; +pub const FLASHW_CAPTION: ::DWORD = 0x00000001; +pub const FLASHW_TRAY: ::DWORD = 0x00000002; +pub const FLASHW_ALL: ::DWORD = FLASHW_CAPTION | FLASHW_TRAY; +pub const FLASHW_TIMER: ::DWORD = 0x00000004; +pub const FLASHW_TIMERNOFG: ::DWORD = 0x0000000C; +// 4674 +pub const HWND_TOP: ::HWND = 0 as ::HWND; +pub const HWND_BOTTOM: ::HWND = 1 as ::HWND; +pub const HWND_TOPMOST: ::HWND = -1isize as ::HWND; +pub const HWND_NOTOPMOST: ::HWND = -2isize as ::HWND; +//5499 +pub const MAPVK_VK_TO_VSC: ::UINT = 0; +pub const MAPVK_VSC_TO_VK: ::UINT = 1; +pub const MAPVK_VK_TO_CHAR: ::UINT = 2; +pub const MAPVK_VSC_TO_VK_EX: ::UINT = 3; +pub const MAPVK_VK_TO_VSC_EX: ::UINT = 4; +//5741 +pub const KEYEVENTF_EXTENDEDKEY: ::DWORD = 0x0001; +pub const KEYEVENTF_KEYUP: ::DWORD = 0x0002; +pub const KEYEVENTF_UNICODE: ::DWORD = 0x0004; +pub const KEYEVENTF_SCANCODE: ::DWORD = 0x0008; +pub const MOUSEEVENTF_MOVE: ::DWORD = 0x0001; +pub const MOUSEEVENTF_LEFTDOWN: ::DWORD = 0x0002; +pub const MOUSEEVENTF_LEFTUP: ::DWORD = 0x0004; +pub const MOUSEEVENTF_RIGHTDOWN: ::DWORD = 0x0008; +pub const MOUSEEVENTF_RIGHTUP: ::DWORD = 0x0010; +pub const MOUSEEVENTF_MIDDLEDOWN: ::DWORD = 0x0020; +pub const MOUSEEVENTF_MIDDLEUP: ::DWORD = 0x0040; +pub const MOUSEEVENTF_XDOWN: ::DWORD = 0x0080; +pub const MOUSEEVENTF_XUP: ::DWORD = 0x0100; +pub const MOUSEEVENTF_WHEEL: ::DWORD = 0x0800; +pub const MOUSEEVENTF_HWHEEL: ::DWORD = 0x01000; +pub const MOUSEEVENTF_MOVE_NOCOALESCE: ::DWORD = 0x2000; +pub const MOUSEEVENTF_VIRTUALDESK: ::DWORD = 0x4000; +pub const MOUSEEVENTF_ABSOLUTE: ::DWORD = 0x8000; +STRUCT!{struct MOUSEINPUT { + dx: ::LONG, + dy: ::LONG, + mouseData: ::DWORD, + dwFlags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PMOUSEINPUT = *mut MOUSEINPUT; +pub type LPMOUSEINPUT = *mut MOUSEINPUT; +STRUCT!{struct KEYBDINPUT { + wVk: ::WORD, + wScan: ::WORD, + dwFlags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PKEYBDINPUT = *mut KEYBDINPUT; +pub type LPKEYBDINPUT = *mut KEYBDINPUT; +STRUCT!{struct HARDWAREINPUT { + uMsg: ::DWORD, + wParamL: ::WORD, + wParamH: ::WORD, +}} +pub type PHARDWAREINPUT = *mut HARDWAREINPUT; +pub type LPHARDWAREINPUT= *mut HARDWAREINPUT; +pub const INPUT_MOUSE: ::DWORD = 0; +pub const INPUT_KEYBOARD: ::DWORD = 1; +pub const INPUT_HARDWARE: ::DWORD = 2; +#[cfg(target_arch = "x86")] +STRUCT!{struct INPUT { + type_: ::DWORD, + u: [u32; 6], +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{struct INPUT { + type_: ::DWORD, + u: [u64; 4], +}} +UNION!{INPUT, u, mi, mi_mut, MOUSEINPUT} +UNION!{INPUT, u, ki, ki_mut, KEYBDINPUT} +UNION!{INPUT, u, hi, hi_mut, HARDWAREINPUT} +pub type PINPUT = *mut INPUT; +pub type LPINPUT = *mut INPUT; +// if WINVER >= 0x0601 +DECLARE_HANDLE!(HTOUCHINPUT, HTOUCHINPUT__); +STRUCT!{struct TOUCHINPUT { + x: ::LONG, + y: ::LONG, + hSource: ::HANDLE, + dwID: ::DWORD, + dwFlags: ::DWORD, + dwMask: ::DWORD, + dwTime: ::DWORD, + dwExtraInfo: ::ULONG_PTR, + cxContact: ::DWORD, + cyContact: ::DWORD, +}} +pub type PTOUCHINPUT = *mut TOUCHINPUT; +pub type PCTOUCHINPUT = *const TOUCHINPUT; +//Touch input flag values (TOUCHINPUT.dwFlags) +pub const TOUCHEVENTF_MOVE: ::DWORD = 0x0001; +pub const TOUCHEVENTF_DOWN: ::DWORD = 0x0002; +pub const TOUCHEVENTF_UP: ::DWORD = 0x0004; +pub const TOUCHEVENTF_INRANGE: ::DWORD = 0x0008; +pub const TOUCHEVENTF_PRIMARY: ::DWORD = 0x0010; +pub const TOUCHEVENTF_NOCOALESCE: ::DWORD = 0x0020; +pub const TOUCHEVENTF_PEN: ::DWORD = 0x0040; +pub const TOUCHEVENTF_PALM: ::DWORD = 0x0080; +//Touch input mask values (TOUCHINPUT.dwMask) +pub const TOUCHINPUTMASKF_TIMEFROMSYSTEM: ::DWORD = 0x0001; +pub const TOUCHINPUTMASKF_EXTRAINFO: ::DWORD = 0x0002; +pub const TOUCHINPUTMASKF_CONTACTAREA: ::DWORD = 0x0004; +//RegisterTouchWindow flag values +pub const TWF_FINETOUCH: ::ULONG = 0x00000001; +pub const TWF_WANTPALM: ::ULONG = 0x00000002; +// end if WINVER >= 0x0601 +//Indices for GetWindowLong etc. +pub const GWL_EXSTYLE: ::c_int = -20; +pub const GWL_STYLE: ::c_int = -16; +pub const GWL_WNDPROC: ::c_int = -4; +pub const GWLP_WNDPROC: ::c_int = -4; +pub const GWL_HINSTANCE: ::c_int = -6; +pub const GWLP_HINSTANCE: ::c_int = -6; +pub const GWL_HWNDPARENT: ::c_int = -8; +pub const GWLP_HWNDPARENT: ::c_int = -8; +pub const GWL_ID: ::c_int = -12; +pub const GWLP_ID: ::c_int = -12; +pub const GWL_USERDATA: ::c_int = -21; +pub const GWLP_USERDATA: ::c_int = -21; +//5976 +ENUM!{enum POINTER_INPUT_TYPE { + PT_POINTER = 0x00000001, + PT_TOUCH = 0x00000002, + PT_PEN = 0x00000003, + PT_MOUSE = 0x00000004, + PT_TOUCHPAD = 0x00000005, +}} +//6566 +// flags for MsgWaitForMultipleObjectsEx +pub const MWMO_WAITALL: ::DWORD = 0x0001; +pub const MWMO_ALERTABLE: ::DWORD = 0x0002; +pub const MWMO_INPUTAVAILABLE: ::DWORD = 0x0004; +//6573 +pub const QS_KEY: ::UINT = 0x0001; +pub const QS_MOUSEMOVE: ::UINT = 0x0002; +pub const QS_MOUSEBUTTON: ::UINT = 0x0004; +pub const QS_POSTMESSAGE: ::UINT = 0x0008; +pub const QS_TIMER: ::UINT = 0x0010; +pub const QS_PAINT: ::UINT = 0x0020; +pub const QS_SENDMESSAGE: ::UINT = 0x0040; +pub const QS_HOTKEY: ::UINT = 0x0080; +pub const QS_ALLPOSTMESSAGE: ::UINT = 0x0100; +pub const QS_RAWINPUT: ::UINT = 0x0400; +pub const QS_TOUCH: ::UINT = 0x0800; +pub const QS_POINTER: ::UINT = 0x1000; +pub const QS_MOUSE: ::UINT = QS_MOUSEMOVE | QS_MOUSEBUTTON; +pub const QS_INPUT: ::UINT = QS_MOUSE | QS_KEY | QS_RAWINPUT | QS_TOUCH | QS_POINTER; +pub const QS_ALLEVENTS: ::UINT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY; +pub const QS_ALLINPUT: ::UINT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER + | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE; +//6789 +pub const SM_CXSCREEN: ::c_int = 0; +pub const SM_CYSCREEN: ::c_int = 1; +pub const SM_CXVSCROLL: ::c_int = 2; +pub const SM_CYHSCROLL: ::c_int = 3; +pub const SM_CYCAPTION: ::c_int = 4; +pub const SM_CXBORDER: ::c_int = 5; +pub const SM_CYBORDER: ::c_int = 6; +pub const SM_CXDLGFRAME: ::c_int = 7; +pub const SM_CYDLGFRAME: ::c_int = 8; +pub const SM_CYVTHUMB: ::c_int = 9; +pub const SM_CXHTHUMB: ::c_int = 10; +pub const SM_CXICON: ::c_int = 11; +pub const SM_CYICON: ::c_int = 12; +pub const SM_CXCURSOR: ::c_int = 13; +pub const SM_CYCURSOR: ::c_int = 14; +pub const SM_CYMENU: ::c_int = 15; +pub const SM_CXFULLSCREEN: ::c_int = 16; +pub const SM_CYFULLSCREEN: ::c_int = 17; +pub const SM_CYKANJIWINDOW: ::c_int = 18; +pub const SM_MOUSEPRESENT: ::c_int = 19; +pub const SM_CYVSCROLL: ::c_int = 20; +pub const SM_CXHSCROLL: ::c_int = 21; +pub const SM_DEBUG: ::c_int = 22; +pub const SM_SWAPBUTTON: ::c_int = 23; +pub const SM_RESERVED1: ::c_int = 24; +pub const SM_RESERVED2: ::c_int = 25; +pub const SM_RESERVED3: ::c_int = 26; +pub const SM_RESERVED4: ::c_int = 27; +pub const SM_CXMIN: ::c_int = 28; +pub const SM_CYMIN: ::c_int = 29; +pub const SM_CXSIZE: ::c_int = 30; +pub const SM_CYSIZE: ::c_int = 31; +pub const SM_CXFRAME: ::c_int = 32; +pub const SM_CYFRAME: ::c_int = 33; +pub const SM_CXMINTRACK: ::c_int = 34; +pub const SM_CYMINTRACK: ::c_int = 35; +pub const SM_CXDOUBLECLK: ::c_int = 36; +pub const SM_CYDOUBLECLK: ::c_int = 37; +pub const SM_CXICONSPACING: ::c_int = 38; +pub const SM_CYICONSPACING: ::c_int = 39; +pub const SM_MENUDROPALIGNMENT: ::c_int = 40; +pub const SM_PENWINDOWS: ::c_int = 41; +pub const SM_DBCSENABLED: ::c_int = 42; +pub const SM_CMOUSEBUTTONS: ::c_int = 43; +pub const SM_CXFIXEDFRAME: ::c_int = SM_CXDLGFRAME; +pub const SM_CYFIXEDFRAME: ::c_int = SM_CYDLGFRAME; +pub const SM_CXSIZEFRAME: ::c_int = SM_CXFRAME; +pub const SM_CYSIZEFRAME: ::c_int = SM_CYFRAME; +pub const SM_SECURE: ::c_int = 44; +pub const SM_CXEDGE: ::c_int = 45; +pub const SM_CYEDGE: ::c_int = 46; +pub const SM_CXMINSPACING: ::c_int = 47; +pub const SM_CYMINSPACING: ::c_int = 48; +pub const SM_CXSMICON: ::c_int = 49; +pub const SM_CYSMICON: ::c_int = 50; +pub const SM_CYSMCAPTION: ::c_int = 51; +pub const SM_CXSMSIZE: ::c_int = 52; +pub const SM_CYSMSIZE: ::c_int = 53; +pub const SM_CXMENUSIZE: ::c_int = 54; +pub const SM_CYMENUSIZE: ::c_int = 55; +pub const SM_ARRANGE: ::c_int = 56; +pub const SM_CXMINIMIZED: ::c_int = 57; +pub const SM_CYMINIMIZED: ::c_int = 58; +pub const SM_CXMAXTRACK: ::c_int = 59; +pub const SM_CYMAXTRACK: ::c_int = 60; +pub const SM_CXMAXIMIZED: ::c_int = 61; +pub const SM_CYMAXIMIZED: ::c_int = 62; +pub const SM_NETWORK: ::c_int = 63; +pub const SM_CLEANBOOT: ::c_int = 67; +pub const SM_CXDRAG: ::c_int = 68; +pub const SM_CYDRAG: ::c_int = 69; +pub const SM_SHOWSOUNDS: ::c_int = 70; +pub const SM_CXMENUCHECK: ::c_int = 71; +pub const SM_CYMENUCHECK: ::c_int = 72; +pub const SM_SLOWMACHINE: ::c_int = 73; +pub const SM_MIDEASTENABLED: ::c_int = 74; +pub const SM_MOUSEWHEELPRESENT: ::c_int = 75; +pub const SM_XVIRTUALSCREEN: ::c_int = 76; +pub const SM_YVIRTUALSCREEN: ::c_int = 77; +pub const SM_CXVIRTUALSCREEN: ::c_int = 78; +pub const SM_CYVIRTUALSCREEN: ::c_int = 79; +pub const SM_CMONITORS: ::c_int = 80; +pub const SM_SAMEDISPLAYFORMAT: ::c_int = 81; +pub const SM_IMMENABLED: ::c_int = 82; +pub const SM_CXFOCUSBORDER: ::c_int = 83; +pub const SM_CYFOCUSBORDER: ::c_int = 84; +pub const SM_TABLETPC: ::c_int = 86; +pub const SM_MEDIACENTER: ::c_int = 87; +pub const SM_STARTER: ::c_int = 88; +pub const SM_SERVERR2: ::c_int = 89; +pub const SM_MOUSEHORIZONTALWHEELPRESENT: ::c_int = 91; +pub const SM_CXPADDEDBORDER: ::c_int = 92; +pub const SM_DIGITIZER: ::c_int = 94; +pub const SM_MAXIMUMTOUCHES: ::c_int = 95; +pub const SM_CMETRICS: ::c_int = 97; +pub const SM_REMOTESESSION: ::c_int = 0x1000; +pub const SM_SHUTTINGDOWN: ::c_int = 0x2000; +pub const SM_REMOTECONTROL: ::c_int = 0x2001; +pub const SM_CARETBLINKINGENABLED: ::c_int = 0x2002; +pub const SM_CONVERTIBLESLATEMODE: ::c_int = 0x2003; +pub const SM_SYSTEMDOCKED: ::c_int = 0x2004; +//8855 (Win 7 SDK) +STRUCT!{struct ICONINFO { + fIcon: ::BOOL, + xHotspot: ::DWORD, + yHotspot: ::DWORD, + hbmMask: ::HBITMAP, + hbmColor: ::HBITMAP, +}} +pub type PICONINFO = *mut ICONINFO; +//9066 +// Color indexes for use in GetSysColor and SetSysColor +// 0-18 (after incrementing) are also valid in RegisterClass's WNDCLASS +pub const COLOR_SCROLLBAR: ::c_int = 0; +pub const COLOR_BACKGROUND: ::c_int = 1; +pub const COLOR_ACTIVECAPTION: ::c_int = 2; +pub const COLOR_INACTIVECAPTION: ::c_int = 3; +pub const COLOR_MENU: ::c_int = 4; +pub const COLOR_WINDOW: ::c_int = 5; +pub const COLOR_WINDOWFRAME: ::c_int = 6; +pub const COLOR_MENUTEXT: ::c_int = 7; +pub const COLOR_WINDOWTEXT: ::c_int = 8; +pub const COLOR_CAPTIONTEXT: ::c_int = 9; +pub const COLOR_ACTIVEBORDER: ::c_int = 10; +pub const COLOR_INACTIVEBORDER: ::c_int = 11; +pub const COLOR_APPWORKSPACE: ::c_int = 12; +pub const COLOR_HIGHLIGHT: ::c_int = 13; +pub const COLOR_HIGHLIGHTTEXT: ::c_int = 14; +pub const COLOR_BTNFACE: ::c_int = 15; +pub const COLOR_BTNSHADOW: ::c_int = 16; +pub const COLOR_GRAYTEXT: ::c_int = 17; +pub const COLOR_BTNTEXT: ::c_int = 18; +pub const COLOR_INACTIVECAPTIONTEXT: ::c_int = 19; +pub const COLOR_BTNHIGHLIGHT: ::c_int = 20; +// Introduced in Windows 95 (winver 0x0400): +pub const COLOR_3DDKSHADOW: ::c_int = 21; +pub const COLOR_3DLIGHT: ::c_int = 22; +pub const COLOR_INFOTEXT: ::c_int = 23; +pub const COLOR_INFOBK: ::c_int = 24; +pub const COLOR_DESKTOP: ::c_int = COLOR_BACKGROUND; +pub const COLOR_3DFACE: ::c_int = COLOR_BTNFACE; +pub const COLOR_3DSHADOW: ::c_int = COLOR_BTNSHADOW; +pub const COLOR_3DHIGHLIGHT: ::c_int = COLOR_BTNHIGHLIGHT; +pub const COLOR_3DHILIGHT: ::c_int = COLOR_BTNHIGHLIGHT; +pub const COLOR_BTNHILIGHT: ::c_int = COLOR_BTNHIGHLIGHT; +// Introduced in Windows 2000 (winver 0x0500) +pub const COLOR_HOTLIGHT: ::c_int = 26; +pub const COLOR_GRADIENTACTIVECAPTION: ::c_int = 27; +pub const COLOR_GRADIENTINACTIVECAPTION: ::c_int = 28; +// Introduced in Windows XP (winver 0x0501) +pub const COLOR_MENUHILIGHT: ::c_int = 29; +pub const COLOR_MENUBAR: ::c_int = 30; +//10069 +pub const IDC_ARROW: ::LPCWSTR = 32512 as ::LPCWSTR; +pub const IDC_IBEAM: ::LPCWSTR = 32513 as ::LPCWSTR; +pub const IDC_WAIT: ::LPCWSTR = 32514 as ::LPCWSTR; +pub const IDC_CROSS: ::LPCWSTR = 32515 as ::LPCWSTR; +pub const IDC_UPARROW: ::LPCWSTR = 32516 as ::LPCWSTR; +pub const IDC_SIZE: ::LPCWSTR = 32640 as ::LPCWSTR; +pub const IDC_ICON: ::LPCWSTR = 32641 as ::LPCWSTR; +pub const IDC_SIZENWSE: ::LPCWSTR = 32642 as ::LPCWSTR; +pub const IDC_SIZENESW: ::LPCWSTR = 32643 as ::LPCWSTR; +pub const IDC_SIZEWE: ::LPCWSTR = 32644 as ::LPCWSTR; +pub const IDC_SIZENS: ::LPCWSTR = 32645 as ::LPCWSTR; +pub const IDC_SIZEALL: ::LPCWSTR = 32646 as ::LPCWSTR; +pub const IDC_NO: ::LPCWSTR = 32648 as ::LPCWSTR; +pub const IDC_HAND: ::LPCWSTR = 32649 as ::LPCWSTR; +pub const IDC_APPSTARTING: ::LPCWSTR = 32650 as ::LPCWSTR; +pub const IDC_HELP: ::LPCWSTR = 32651 as ::LPCWSTR; +//10492 +pub const IDI_APPLICATION: ::LPCWSTR = 32512 as ::LPCWSTR; +pub const IDI_HAND: ::LPCWSTR = 32513 as ::LPCWSTR; +pub const IDI_QUESTION: ::LPCWSTR = 32514 as ::LPCWSTR; +pub const IDI_EXCLAMATION: ::LPCWSTR = 32515 as ::LPCWSTR; +pub const IDI_ASTERISK: ::LPCWSTR = 32516 as ::LPCWSTR; +pub const IDI_WINLOGO: ::LPCWSTR = 32517 as ::LPCWSTR; +pub const IDI_SHIELD: ::LPCWSTR = 32518 as ::LPCWSTR; +pub const IDI_WARNING: ::LPCWSTR = IDI_EXCLAMATION; +pub const IDI_ERROR: ::LPCWSTR = IDI_HAND; +pub const IDI_INFORMATION: ::LPCWSTR = IDI_ASTERISK; +pub const SPI_GETBEEP: ::UINT = 0x0001; +pub const SPI_SETBEEP: ::UINT = 0x0002; +pub const SPI_GETMOUSE: ::UINT = 0x0003; +pub const SPI_SETMOUSE: ::UINT = 0x0004; +pub const SPI_GETBORDER: ::UINT = 0x0005; +pub const SPI_SETBORDER: ::UINT = 0x0006; +pub const SPI_GETKEYBOARDSPEED: ::UINT = 0x000A; +pub const SPI_SETKEYBOARDSPEED: ::UINT = 0x000B; +pub const SPI_LANGDRIVER: ::UINT = 0x000C; +pub const SPI_ICONHORIZONTALSPACING: ::UINT = 0x000D; +pub const SPI_GETSCREENSAVETIMEOUT: ::UINT = 0x000E; +pub const SPI_SETSCREENSAVETIMEOUT: ::UINT = 0x000F; +pub const SPI_GETSCREENSAVEACTIVE: ::UINT = 0x0010; +pub const SPI_SETSCREENSAVEACTIVE: ::UINT = 0x0011; +pub const SPI_GETGRIDGRANULARITY: ::UINT = 0x0012; +pub const SPI_SETGRIDGRANULARITY: ::UINT = 0x0013; +pub const SPI_SETDESKWALLPAPER: ::UINT = 0x0014; +pub const SPI_SETDESKPATTERN: ::UINT = 0x0015; +pub const SPI_GETKEYBOARDDELAY: ::UINT = 0x0016; +pub const SPI_SETKEYBOARDDELAY: ::UINT = 0x0017; +pub const SPI_ICONVERTICALSPACING: ::UINT = 0x0018; +pub const SPI_GETICONTITLEWRAP: ::UINT = 0x0019; +pub const SPI_SETICONTITLEWRAP: ::UINT = 0x001A; +pub const SPI_GETMENUDROPALIGNMENT: ::UINT = 0x001B; +pub const SPI_SETMENUDROPALIGNMENT: ::UINT = 0x001C; +pub const SPI_SETDOUBLECLKWIDTH: ::UINT = 0x001D; +pub const SPI_SETDOUBLECLKHEIGHT: ::UINT = 0x001E; +pub const SPI_GETICONTITLELOGFONT: ::UINT = 0x001F; +pub const SPI_SETDOUBLECLICKTIME: ::UINT = 0x0020; +pub const SPI_SETMOUSEBUTTONSWAP: ::UINT = 0x0021; +pub const SPI_SETICONTITLELOGFONT: ::UINT = 0x0022; +pub const SPI_GETFASTTASKSWITCH: ::UINT = 0x0023; +pub const SPI_SETFASTTASKSWITCH: ::UINT = 0x0024; +pub const SPI_SETDRAGFULLWINDOWS: ::UINT = 0x0025; +pub const SPI_GETDRAGFULLWINDOWS: ::UINT = 0x0026; +pub const SPI_GETNONCLIENTMETRICS: ::UINT = 0x0029; +pub const SPI_SETNONCLIENTMETRICS: ::UINT = 0x002A; +pub const SPI_GETMINIMIZEDMETRICS: ::UINT = 0x002B; +pub const SPI_SETMINIMIZEDMETRICS: ::UINT = 0x002C; +pub const SPI_GETICONMETRICS: ::UINT = 0x002D; +pub const SPI_SETICONMETRICS: ::UINT = 0x002E; +pub const SPI_SETWORKAREA: ::UINT = 0x002F; +pub const SPI_GETWORKAREA: ::UINT = 0x0030; +pub const SPI_SETPENWINDOWS: ::UINT = 0x0031; +pub const SPI_GETHIGHCONTRAST: ::UINT = 0x0042; +pub const SPI_SETHIGHCONTRAST: ::UINT = 0x0043; +pub const SPI_GETKEYBOARDPREF: ::UINT = 0x0044; +pub const SPI_SETKEYBOARDPREF: ::UINT = 0x0045; +pub const SPI_GETSCREENREADER: ::UINT = 0x0046; +pub const SPI_SETSCREENREADER: ::UINT = 0x0047; +pub const SPI_GETANIMATION: ::UINT = 0x0048; +pub const SPI_SETANIMATION: ::UINT = 0x0049; +pub const SPI_GETFONTSMOOTHING: ::UINT = 0x004A; +pub const SPI_SETFONTSMOOTHING: ::UINT = 0x004B; +pub const SPI_SETDRAGWIDTH: ::UINT = 0x004C; +pub const SPI_SETDRAGHEIGHT: ::UINT = 0x004D; +pub const SPI_SETHANDHELD: ::UINT = 0x004E; +pub const SPI_GETLOWPOWERTIMEOUT: ::UINT = 0x004F; +pub const SPI_GETPOWEROFFTIMEOUT: ::UINT = 0x0050; +pub const SPI_SETLOWPOWERTIMEOUT: ::UINT = 0x0051; +pub const SPI_SETPOWEROFFTIMEOUT: ::UINT = 0x0052; +pub const SPI_GETLOWPOWERACTIVE: ::UINT = 0x0053; +pub const SPI_GETPOWEROFFACTIVE: ::UINT = 0x0054; +pub const SPI_SETLOWPOWERACTIVE: ::UINT = 0x0055; +pub const SPI_SETPOWEROFFACTIVE: ::UINT = 0x0056; +pub const SPI_SETCURSORS: ::UINT = 0x0057; +pub const SPI_SETICONS: ::UINT = 0x0058; +pub const SPI_GETDEFAULTINPUTLANG: ::UINT = 0x0059; +pub const SPI_SETDEFAULTINPUTLANG: ::UINT = 0x005A; +pub const SPI_SETLANGTOGGLE: ::UINT = 0x005B; +pub const SPI_GETWINDOWSEXTENSION: ::UINT = 0x005C; +pub const SPI_SETMOUSETRAILS: ::UINT = 0x005D; +pub const SPI_GETMOUSETRAILS: ::UINT = 0x005E; +pub const SPI_SETSCREENSAVERRUNNING: ::UINT = 0x0061; +pub const SPI_SCREENSAVERRUNNING: ::UINT = SPI_SETSCREENSAVERRUNNING; +pub const SPI_GETFILTERKEYS: ::UINT = 0x0032; +pub const SPI_SETFILTERKEYS: ::UINT = 0x0033; +pub const SPI_GETTOGGLEKEYS: ::UINT = 0x0034; +pub const SPI_SETTOGGLEKEYS: ::UINT = 0x0035; +pub const SPI_GETMOUSEKEYS: ::UINT = 0x0036; +pub const SPI_SETMOUSEKEYS: ::UINT = 0x0037; +pub const SPI_GETSHOWSOUNDS: ::UINT = 0x0038; +pub const SPI_SETSHOWSOUNDS: ::UINT = 0x0039; +pub const SPI_GETSTICKYKEYS: ::UINT = 0x003A; +pub const SPI_SETSTICKYKEYS: ::UINT = 0x003B; +pub const SPI_GETACCESSTIMEOUT: ::UINT = 0x003C; +pub const SPI_SETACCESSTIMEOUT: ::UINT = 0x003D; +pub const SPI_GETSERIALKEYS: ::UINT = 0x003E; +pub const SPI_SETSERIALKEYS: ::UINT = 0x003F; +pub const SPI_GETSOUNDSENTRY: ::UINT = 0x0040; +pub const SPI_SETSOUNDSENTRY: ::UINT = 0x0041; +pub const SPI_GETSNAPTODEFBUTTON: ::UINT = 0x005F; +pub const SPI_SETSNAPTODEFBUTTON: ::UINT = 0x0060; +pub const SPI_GETMOUSEHOVERWIDTH: ::UINT = 0x0062; +pub const SPI_SETMOUSEHOVERWIDTH: ::UINT = 0x0063; +pub const SPI_GETMOUSEHOVERHEIGHT: ::UINT = 0x0064; +pub const SPI_SETMOUSEHOVERHEIGHT: ::UINT = 0x0065; +pub const SPI_GETMOUSEHOVERTIME: ::UINT = 0x0066; +pub const SPI_SETMOUSEHOVERTIME: ::UINT = 0x0067; +pub const SPI_GETWHEELSCROLLLINES: ::UINT = 0x0068; +pub const SPI_SETWHEELSCROLLLINES: ::UINT = 0x0069; +pub const SPI_GETMENUSHOWDELAY: ::UINT = 0x006A; +pub const SPI_SETMENUSHOWDELAY: ::UINT = 0x006B; +pub const SPI_GETWHEELSCROLLCHARS: ::UINT = 0x006C; +pub const SPI_SETWHEELSCROLLCHARS: ::UINT = 0x006D; +pub const SPI_GETSHOWIMEUI: ::UINT = 0x006E; +pub const SPI_SETSHOWIMEUI: ::UINT = 0x006F; +pub const SPI_GETMOUSESPEED: ::UINT = 0x0070; +pub const SPI_SETMOUSESPEED: ::UINT = 0x0071; +pub const SPI_GETSCREENSAVERRUNNING: ::UINT = 0x0072; +pub const SPI_GETDESKWALLPAPER: ::UINT = 0x0073; +pub const SPI_GETAUDIODESCRIPTION: ::UINT = 0x0074; +pub const SPI_SETAUDIODESCRIPTION: ::UINT = 0x0075; +pub const SPI_GETSCREENSAVESECURE: ::UINT = 0x0076; +pub const SPI_SETSCREENSAVESECURE: ::UINT = 0x0077; +pub const SPI_GETHUNGAPPTIMEOUT: ::UINT = 0x0078; +pub const SPI_SETHUNGAPPTIMEOUT: ::UINT = 0x0079; +pub const SPI_GETWAITTOKILLTIMEOUT: ::UINT = 0x007A; +pub const SPI_SETWAITTOKILLTIMEOUT: ::UINT = 0x007B; +pub const SPI_GETWAITTOKILLSERVICETIMEOUT: ::UINT = 0x007C; +pub const SPI_SETWAITTOKILLSERVICETIMEOUT: ::UINT = 0x007D; +pub const SPI_GETMOUSEDOCKTHRESHOLD: ::UINT = 0x007E; +pub const SPI_SETMOUSEDOCKTHRESHOLD: ::UINT = 0x007F; +pub const SPI_GETPENDOCKTHRESHOLD: ::UINT = 0x0080; +pub const SPI_SETPENDOCKTHRESHOLD: ::UINT = 0x0081; +pub const SPI_GETWINARRANGING: ::UINT = 0x0082; +pub const SPI_SETWINARRANGING: ::UINT = 0x0083; +pub const SPI_GETMOUSEDRAGOUTTHRESHOLD: ::UINT = 0x0084; +pub const SPI_SETMOUSEDRAGOUTTHRESHOLD: ::UINT = 0x0085; +pub const SPI_GETPENDRAGOUTTHRESHOLD: ::UINT = 0x0086; +pub const SPI_SETPENDRAGOUTTHRESHOLD: ::UINT = 0x0087; +pub const SPI_GETMOUSESIDEMOVETHRESHOLD: ::UINT = 0x0088; +pub const SPI_SETMOUSESIDEMOVETHRESHOLD: ::UINT = 0x0089; +pub const SPI_GETPENSIDEMOVETHRESHOLD: ::UINT = 0x008A; +pub const SPI_SETPENSIDEMOVETHRESHOLD: ::UINT = 0x008B; +pub const SPI_GETDRAGFROMMAXIMIZE: ::UINT = 0x008C; +pub const SPI_SETDRAGFROMMAXIMIZE: ::UINT = 0x008D; +pub const SPI_GETSNAPSIZING: ::UINT = 0x008E; +pub const SPI_SETSNAPSIZING: ::UINT = 0x008F; +pub const SPI_GETDOCKMOVING: ::UINT = 0x0090; +pub const SPI_SETDOCKMOVING: ::UINT = 0x0091; +pub const SPI_GETACTIVEWINDOWTRACKING: ::UINT = 0x1000; +pub const SPI_SETACTIVEWINDOWTRACKING: ::UINT = 0x1001; +pub const SPI_GETMENUANIMATION: ::UINT = 0x1002; +pub const SPI_SETMENUANIMATION: ::UINT = 0x1003; +pub const SPI_GETCOMBOBOXANIMATION: ::UINT = 0x1004; +pub const SPI_SETCOMBOBOXANIMATION: ::UINT = 0x1005; +pub const SPI_GETLISTBOXSMOOTHSCROLLING: ::UINT = 0x1006; +pub const SPI_SETLISTBOXSMOOTHSCROLLING: ::UINT = 0x1007; +pub const SPI_GETGRADIENTCAPTIONS: ::UINT = 0x1008; +pub const SPI_SETGRADIENTCAPTIONS: ::UINT = 0x1009; +pub const SPI_GETKEYBOARDCUES: ::UINT = 0x100A; +pub const SPI_SETKEYBOARDCUES: ::UINT = 0x100B; +pub const SPI_GETMENUUNDERLINES: ::UINT = SPI_GETKEYBOARDCUES; +pub const SPI_SETMENUUNDERLINES: ::UINT = SPI_SETKEYBOARDCUES; +pub const SPI_GETACTIVEWNDTRKZORDER: ::UINT = 0x100C; +pub const SPI_SETACTIVEWNDTRKZORDER: ::UINT = 0x100D; +pub const SPI_GETHOTTRACKING: ::UINT = 0x100E; +pub const SPI_SETHOTTRACKING: ::UINT = 0x100F; +pub const SPI_GETMENUFADE: ::UINT = 0x1012; +pub const SPI_SETMENUFADE: ::UINT = 0x1013; +pub const SPI_GETSELECTIONFADE: ::UINT = 0x1014; +pub const SPI_SETSELECTIONFADE: ::UINT = 0x1015; +pub const SPI_GETTOOLTIPANIMATION: ::UINT = 0x1016; +pub const SPI_SETTOOLTIPANIMATION: ::UINT = 0x1017; +pub const SPI_GETTOOLTIPFADE: ::UINT = 0x1018; +pub const SPI_SETTOOLTIPFADE: ::UINT = 0x1019; +pub const SPI_GETCURSORSHADOW: ::UINT = 0x101A; +pub const SPI_SETCURSORSHADOW: ::UINT = 0x101B; +pub const SPI_GETMOUSESONAR: ::UINT = 0x101C; +pub const SPI_SETMOUSESONAR: ::UINT = 0x101D; +pub const SPI_GETMOUSECLICKLOCK: ::UINT = 0x101E; +pub const SPI_SETMOUSECLICKLOCK: ::UINT = 0x101F; +pub const SPI_GETMOUSEVANISH: ::UINT = 0x1020; +pub const SPI_SETMOUSEVANISH: ::UINT = 0x1021; +pub const SPI_GETFLATMENU: ::UINT = 0x1022; +pub const SPI_SETFLATMENU: ::UINT = 0x1023; +pub const SPI_GETDROPSHADOW: ::UINT = 0x1024; +pub const SPI_SETDROPSHADOW: ::UINT = 0x1025; +pub const SPI_GETBLOCKSENDINPUTRESETS: ::UINT = 0x1026; +pub const SPI_SETBLOCKSENDINPUTRESETS: ::UINT = 0x1027; +pub const SPI_GETUIEFFECTS: ::UINT = 0x103E; +pub const SPI_SETUIEFFECTS: ::UINT = 0x103F; +pub const SPI_GETDISABLEOVERLAPPEDCONTENT: ::UINT = 0x1040; +pub const SPI_SETDISABLEOVERLAPPEDCONTENT: ::UINT = 0x1041; +pub const SPI_GETCLIENTAREAANIMATION: ::UINT = 0x1042; +pub const SPI_SETCLIENTAREAANIMATION: ::UINT = 0x1043; +pub const SPI_GETCLEARTYPE: ::UINT = 0x1048; +pub const SPI_SETCLEARTYPE: ::UINT = 0x1049; +pub const SPI_GETSPEECHRECOGNITION: ::UINT = 0x104A; +pub const SPI_SETSPEECHRECOGNITION: ::UINT = 0x104B; +pub const SPI_GETFOREGROUNDLOCKTIMEOUT: ::UINT = 0x2000; +pub const SPI_SETFOREGROUNDLOCKTIMEOUT: ::UINT = 0x2001; +pub const SPI_GETACTIVEWNDTRKTIMEOUT: ::UINT = 0x2002; +pub const SPI_SETACTIVEWNDTRKTIMEOUT: ::UINT = 0x2003; +pub const SPI_GETFOREGROUNDFLASHCOUNT: ::UINT = 0x2004; +pub const SPI_SETFOREGROUNDFLASHCOUNT: ::UINT = 0x2005; +pub const SPI_GETCARETWIDTH: ::UINT = 0x2006; +pub const SPI_SETCARETWIDTH: ::UINT = 0x2007; +pub const SPI_GETMOUSECLICKLOCKTIME: ::UINT = 0x2008; +pub const SPI_SETMOUSECLICKLOCKTIME: ::UINT = 0x2009; +pub const SPI_GETFONTSMOOTHINGTYPE: ::UINT = 0x200A; +pub const SPI_SETFONTSMOOTHINGTYPE: ::UINT = 0x200B; +pub const FE_FONTSMOOTHINGSTANDARD: ::UINT = 0x0001; +pub const FE_FONTSMOOTHINGCLEARTYPE: ::UINT = 0x0002; +pub const SPI_GETFONTSMOOTHINGCONTRAST: ::UINT = 0x200C; +pub const SPI_SETFONTSMOOTHINGCONTRAST: ::UINT = 0x200D; +pub const SPI_GETFOCUSBORDERWIDTH: ::UINT = 0x200E; +pub const SPI_SETFOCUSBORDERWIDTH: ::UINT = 0x200F; +pub const SPI_GETFOCUSBORDERHEIGHT: ::UINT = 0x2010; +pub const SPI_SETFOCUSBORDERHEIGHT: ::UINT = 0x2011; +pub const SPI_GETFONTSMOOTHINGORIENTATION: ::UINT = 0x2012; +pub const SPI_SETFONTSMOOTHINGORIENTATION: ::UINT = 0x2013; +pub const FE_FONTSMOOTHINGORIENTATIONBGR: ::UINT = 0x0000; +pub const FE_FONTSMOOTHINGORIENTATIONRGB: ::UINT = 0x0001; +pub const SPI_GETMINIMUMHITRADIUS: ::UINT = 0x2014; +pub const SPI_SETMINIMUMHITRADIUS: ::UINT = 0x2015; +pub const SPI_GETMESSAGEDURATION: ::UINT = 0x2016; +pub const SPI_SETMESSAGEDURATION: ::UINT = 0x2017; +//11264 +pub const CB_GETEDITSEL: ::UINT = 0x0140; +pub const CB_LIMITTEXT: ::UINT = 0x0141; +pub const CB_SETEDITSEL: ::UINT = 0x0142; +pub const CB_ADDSTRING: ::UINT = 0x0143; +pub const CB_DELETESTRING: ::UINT = 0x0144; +pub const CB_DIR: ::UINT = 0x0145; +pub const CB_GETCOUNT: ::UINT = 0x0146; +pub const CB_GETCURSEL: ::UINT = 0x0147; +pub const CB_GETLBTEXT: ::UINT = 0x0148; +pub const CB_GETLBTEXTLEN: ::UINT = 0x0149; +pub const CB_INSERTSTRING: ::UINT = 0x014A; +pub const CB_RESETCONTENT: ::UINT = 0x014B; +pub const CB_FINDSTRING: ::UINT = 0x014C; +pub const CB_SELECTSTRING: ::UINT = 0x014D; +pub const CB_SETCURSEL: ::UINT = 0x014E; +pub const CB_SHOWDROPDOWN: ::UINT = 0x014F; +pub const CB_GETITEMDATA: ::UINT = 0x0150; +pub const CB_SETITEMDATA: ::UINT = 0x0151; +pub const CB_GETDROPPEDCONTROLRECT: ::UINT = 0x0152; +pub const CB_SETITEMHEIGHT: ::UINT = 0x0153; +pub const CB_GETITEMHEIGHT: ::UINT = 0x0154; +pub const CB_SETEXTENDEDUI: ::UINT = 0x0155; +pub const CB_GETEXTENDEDUI: ::UINT = 0x0156; +pub const CB_GETDROPPEDSTATE: ::UINT = 0x0157; +pub const CB_FINDSTRINGEXACT: ::UINT = 0x0158; +pub const CB_SETLOCALE: ::UINT = 0x0159; +pub const CB_GETLOCALE: ::UINT = 0x015A; +pub const CB_GETTOPINDEX: ::UINT = 0x015b; +pub const CB_SETTOPINDEX: ::UINT = 0x015c; +pub const CB_GETHORIZONTALEXTENT: ::UINT = 0x015d; +pub const CB_SETHORIZONTALEXTENT: ::UINT = 0x015e; +pub const CB_GETDROPPEDWIDTH: ::UINT = 0x015f; +pub const CB_SETDROPPEDWIDTH: ::UINT = 0x0160; +pub const CB_INITSTORAGE: ::UINT = 0x0161; +//12141 +STRUCT!{nodebug struct NONCLIENTMETRICSA { + cbSize: ::UINT, + iBorderWidth: ::c_int, + iScrollWidth: ::c_int, + iScrollHeight: ::c_int, + iCaptionWidth: ::c_int, + iCaptionHeight: ::c_int, + lfCaptionFont: ::LOGFONTA, + iSmCaptionWidth: ::c_int, + iSmCaptionHeight: ::c_int, + lfSmCaptionFont: ::LOGFONTA, + iMenuWidth: ::c_int, + iMenuHeight: ::c_int, + lfMenuFont: ::LOGFONTA, + lfStatusFont: ::LOGFONTA, + lfMessageFont: ::LOGFONTA, + iPaddedBorderWidth: ::c_int, +}} +pub type LPNONCLIENTMETRICSA = *mut NONCLIENTMETRICSA; +STRUCT!{nodebug struct NONCLIENTMETRICSW { + cbSize: ::UINT, + iBorderWidth: ::c_int, + iScrollWidth: ::c_int, + iScrollHeight: ::c_int, + iCaptionWidth: ::c_int, + iCaptionHeight: ::c_int, + lfCaptionFont: ::LOGFONTW, + iSmCaptionWidth: ::c_int, + iSmCaptionHeight: ::c_int, + lfSmCaptionFont: ::LOGFONTW, + iMenuWidth: ::c_int, + iMenuHeight: ::c_int, + lfMenuFont: ::LOGFONTW, + lfStatusFont: ::LOGFONTW, + lfMessageFont: ::LOGFONTW, + iPaddedBorderWidth: ::c_int, +}} +pub type LPNONCLIENTMETRICSW = *mut NONCLIENTMETRICSW; +//12869 +pub const MONITOR_DEFAULTTONULL: ::DWORD = 0x00000000; +pub const MONITOR_DEFAULTTOPRIMARY: ::DWORD = 0x00000001; +pub const MONITOR_DEFAULTTONEAREST: ::DWORD = 0x00000002; +//12900 +pub const MONITORINFOF_PRIMARY: ::DWORD = 1; +pub const CCHDEVICENAME: usize = 32; +STRUCT!{struct MONITORINFO { + cbSize: ::DWORD, + rcMonitor: ::RECT, + rcWork: ::RECT, + dwFlags: ::DWORD, +}} +pub type LPMONITORINFO = *mut MONITORINFO; +STRUCT!{struct MONITORINFOEXA { + cbSize: ::DWORD, + rcMonitor: ::RECT, + rcWork: ::RECT, + dwFlags: ::DWORD, + szDevice: [::CHAR; ::CCHDEVICENAME], +}} +pub type LPMONITORINFOEXA = *mut MONITORINFOEXA; +STRUCT!{struct MONITORINFOEXW { + cbSize: ::DWORD, + rcMonitor: ::RECT, + rcWork: ::RECT, + dwFlags: ::DWORD, + szDevice: [::WCHAR; ::CCHDEVICENAME], +}} +pub type LPMONITORINFOEXW = *mut MONITORINFOEXW; +//12971 +pub type MONITORENUMPROC = Option<unsafe extern "system" fn( + ::HMONITOR, ::HDC, ::LPRECT, ::LPARAM, +) -> ::BOOL>; +//14098 +DECLARE_HANDLE!(HRAWINPUT, HRAWINPUT__); +pub fn GET_RAWINPUT_CODE_WPARAM(wParam: ::WPARAM) -> ::WPARAM { wParam & 0xff } +pub const RIM_INPUT: ::WPARAM = 0; +pub const RIM_INPUTSINK: ::WPARAM = 1; +STRUCT!{struct RAWINPUTHEADER { + dwType: ::DWORD, + dwSize: ::DWORD, + hDevice: ::HANDLE, + wParam: ::WPARAM, +}} +pub type PRAWINPUTHEADER = *mut RAWINPUTHEADER; +pub type LPRAWINPUTHEADER = *mut RAWINPUTHEADER; +pub const RIM_TYPEMOUSE: ::DWORD = 0; +pub const RIM_TYPEKEYBOARD: ::DWORD = 1; +pub const RIM_TYPEHID: ::DWORD = 2; +STRUCT!{struct RAWMOUSE { + usFlags: ::USHORT, + memory_padding: ::USHORT, // 16bit Padding for 32bit align in following union + usButtonFlags: ::USHORT, + usButtonData: ::USHORT, + ulRawButtons: ::ULONG, + lLastX: ::LONG, + lLastY: ::LONG, + ulExtraInformation: ::ULONG, +}} +pub type PRAWMOUSE = *mut RAWMOUSE; +pub type LPRAWMOUSE = *mut RAWMOUSE; +pub const RI_MOUSE_LEFT_BUTTON_DOWN: ::USHORT = 0x0001; +pub const RI_MOUSE_LEFT_BUTTON_UP: ::USHORT = 0x0002; +pub const RI_MOUSE_RIGHT_BUTTON_DOWN: ::USHORT = 0x0004; +pub const RI_MOUSE_RIGHT_BUTTON_UP: ::USHORT = 0x0008; +pub const RI_MOUSE_MIDDLE_BUTTON_DOWN: ::USHORT = 0x0010; +pub const RI_MOUSE_MIDDLE_BUTTON_UP: ::USHORT = 0x0020; +pub const RI_MOUSE_BUTTON_1_DOWN: ::USHORT = RI_MOUSE_LEFT_BUTTON_DOWN; +pub const RI_MOUSE_BUTTON_1_UP: ::USHORT = RI_MOUSE_LEFT_BUTTON_UP; +pub const RI_MOUSE_BUTTON_2_DOWN: ::USHORT = RI_MOUSE_RIGHT_BUTTON_DOWN; +pub const RI_MOUSE_BUTTON_2_UP: ::USHORT = RI_MOUSE_RIGHT_BUTTON_UP; +pub const RI_MOUSE_BUTTON_3_DOWN: ::USHORT = RI_MOUSE_MIDDLE_BUTTON_DOWN; +pub const RI_MOUSE_BUTTON_3_UP: ::USHORT = RI_MOUSE_MIDDLE_BUTTON_UP; +pub const RI_MOUSE_BUTTON_4_DOWN: ::USHORT = 0x0040; +pub const RI_MOUSE_BUTTON_4_UP: ::USHORT = 0x0080; +pub const RI_MOUSE_BUTTON_5_DOWN: ::USHORT = 0x0100; +pub const RI_MOUSE_BUTTON_5_UP: ::USHORT = 0x0200; +pub const RI_MOUSE_WHEEL: ::USHORT = 0x0400; +pub const MOUSE_MOVE_RELATIVE: ::USHORT = 0; +pub const MOUSE_MOVE_ABSOLUTE: ::USHORT = 1; +pub const MOUSE_VIRTUAL_DESKTOP: ::USHORT = 0x02; +pub const MOUSE_ATTRIBUTES_CHANGED: ::USHORT = 0x04; +pub const MOUSE_MOVE_NOCOALESCE: ::USHORT = 0x08; +STRUCT!{struct RAWKEYBOARD { + MakeCode: ::USHORT, + Flags: ::USHORT, + Reserved: ::USHORT, + VKey: ::USHORT, + Message: ::UINT, + ExtraInformation: ::ULONG, +}} +pub type PRAWKEYBOARD = *mut RAWKEYBOARD; +pub type LPRAWKEYBOARD = *mut RAWKEYBOARD; +pub const KEYBOARD_OVERRUN_MAKE_CODE: ::DWORD = 0xFF; +pub const RI_KEY_MAKE: ::DWORD = 0; +pub const RI_KEY_BREAK: ::DWORD = 1; +pub const RI_KEY_E0: ::DWORD = 2; +pub const RI_KEY_E1: ::DWORD = 4; +pub const RI_KEY_TERMSRV_SET_LED: ::DWORD = 8; +pub const RI_KEY_TERMSRV_SHADOW: ::DWORD = 0x10; +STRUCT!{struct RAWHID { + dwSizeHid: ::DWORD, + dwCount: ::DWORD, + bRawData: [::BYTE; 0], +}} +pub type PRAWHID = *mut RAWHID; +pub type LPRAWHID = *mut RAWHID; +STRUCT!{struct RAWINPUT { + header: RAWINPUTHEADER, + mouse: RAWMOUSE, +}} +UNION!(RAWINPUT, mouse, mouse, mouse_mut, RAWMOUSE); +UNION!(RAWINPUT, mouse, keyboard, keyboard_mut, RAWKEYBOARD); +UNION!(RAWINPUT, mouse, hid, hid_mut, RAWHID); +#[test] +fn test_RAWINPUT() { + use std::mem::{size_of, align_of}; + assert!(size_of::<RAWMOUSE>() >= size_of::<RAWMOUSE>()); + assert!(size_of::<RAWMOUSE>() >= size_of::<RAWKEYBOARD>()); + assert!(size_of::<RAWMOUSE>() >= size_of::<RAWHID>()); + assert!(align_of::<RAWMOUSE>() >= align_of::<RAWMOUSE>()); + assert!(align_of::<RAWMOUSE>() >= align_of::<RAWKEYBOARD>()); + assert!(align_of::<RAWMOUSE>() >= align_of::<RAWHID>()); +} +pub type PRAWINPUT = *mut RAWINPUT; +pub type LPRAWINPUT = *mut RAWINPUT; +pub const RID_INPUT: ::DWORD = 0x10000003; +pub const RID_HEADER: ::DWORD = 0x10000005; +pub const RIDI_PREPARSEDDATA: ::DWORD = 0x20000005; +pub const RIDI_DEVICENAME: ::DWORD = 0x20000007; +pub const RIDI_DEVICEINFO: ::DWORD = 0x2000000b; +STRUCT!{struct RID_DEVICE_INFO_MOUSE { + dwId: ::DWORD, + dwNumberOfButtons: ::DWORD, + dwSampleRate: ::DWORD, + fHasHorizontalWheel: ::BOOL, +}} +pub type PRID_DEVICE_INFO_MOUSE = *mut RID_DEVICE_INFO_MOUSE; +STRUCT!{struct RID_DEVICE_INFO_KEYBOARD { + dwType: ::DWORD, + dwSubType: ::DWORD, + dwKeyboardMode: ::DWORD, + dwNumberOfFunctionKeys: ::DWORD, + dwNumberOfIndicators: ::DWORD, + dwNumberOfKeysTotal: ::DWORD, +}} +pub type PRID_DEVICE_INFO_KEYBOARD = *mut RID_DEVICE_INFO_KEYBOARD; +STRUCT!{struct RID_DEVICE_INFO_HID { + dwVendorId: ::DWORD, + dwProductId: ::DWORD, + dwVersionNumber: ::DWORD, + usUsagePage: ::USHORT, + usUsage: ::USHORT, +}} +pub type PRID_DEVICE_INFO_HID = *mut RID_DEVICE_INFO_HID; +STRUCT!{struct RID_DEVICE_INFO { + cbSize: ::DWORD, + dwType: ::DWORD, + keyboard: RID_DEVICE_INFO_KEYBOARD, +}} +UNION!(RID_DEVICE_INFO, keyboard, mouse, mouse_mut, RID_DEVICE_INFO_MOUSE); +UNION!(RID_DEVICE_INFO, keyboard, keyboard, keyboard_mut, RID_DEVICE_INFO_KEYBOARD); +UNION!(RID_DEVICE_INFO, keyboard, hid, hid_mut, RID_DEVICE_INFO_HID); +#[test] +fn test_RID_DEVICE_INFO() { + use std::mem::{size_of, align_of}; + assert!(size_of::<RID_DEVICE_INFO_KEYBOARD>() >= size_of::<RID_DEVICE_INFO_MOUSE>()); + assert!(size_of::<RID_DEVICE_INFO_KEYBOARD>() >= size_of::<RID_DEVICE_INFO_KEYBOARD>()); + assert!(size_of::<RID_DEVICE_INFO_KEYBOARD>() >= size_of::<RID_DEVICE_INFO_HID>()); + assert!(align_of::<RID_DEVICE_INFO_KEYBOARD>() >= align_of::<RID_DEVICE_INFO_MOUSE>()); + assert!(align_of::<RID_DEVICE_INFO_KEYBOARD>() + >= align_of::<RID_DEVICE_INFO_KEYBOARD>()); + assert!(align_of::<RID_DEVICE_INFO_KEYBOARD>() >= align_of::<RID_DEVICE_INFO_HID>()); +} +pub type PRID_DEVICE_INFO = *mut RID_DEVICE_INFO; +pub type LPRID_DEVICE_INFO = *mut RID_DEVICE_INFO; +STRUCT!{struct RAWINPUTDEVICE { + usUsagePage: ::USHORT, + usUsage: ::USHORT, + dwFlags: ::DWORD, + hwndTarget: ::HWND, +}} +pub type PRAWINPUTDEVICE = *mut RAWINPUTDEVICE; +pub type LPRAWINPUTDEVICE = *mut RAWINPUTDEVICE; +pub type PCRAWINPUTDEVICE = *const RAWINPUTDEVICE; +pub const RIDEV_REMOVE: ::DWORD = 0x00000001; +pub const RIDEV_EXCLUDE: ::DWORD = 0x00000010; +pub const RIDEV_PAGEONLY: ::DWORD = 0x00000020; +pub const RIDEV_NOLEGACY: ::DWORD = 0x00000030; +pub const RIDEV_INPUTSINK: ::DWORD = 0x00000100; +pub const RIDEV_CAPTUREMOUSE: ::DWORD = 0x00000200; +pub const RIDEV_NOHOTKEYS: ::DWORD = 0x00000200; +pub const RIDEV_APPKEYS: ::DWORD = 0x00000400; +pub const RIDEV_EXINPUTSINK: ::DWORD = 0x00001000; +pub const RIDEV_DEVNOTIFY: ::DWORD = 0x00002000; +pub const RIDEV_EXMODEMASK: ::DWORD = 0x000000F0; +pub const GIDC_ARRIVAL: ::DWORD = 1; +pub const GIDC_REMOVAL: ::DWORD = 2; +STRUCT!{struct RAWINPUTDEVICELIST { + hDevice: ::HANDLE, + dwType: ::DWORD, +}} +pub type PRAWINPUTDEVICELIST = *mut RAWINPUTDEVICELIST; +STRUCT!{struct CHANGEFILTERSTRUCT { + cbSize: ::DWORD, + ExtStatus: ::DWORD, +}} +pub type PCHANGEFILTERSTRUCT = *mut CHANGEFILTERSTRUCT; +STRUCT!{struct DLGTEMPLATE { + style: ::DWORD, + dwExtendedStyle: ::DWORD, + cdit: ::WORD, + x: ::c_short, + y: ::c_short, + cx: ::c_short, + cy: ::c_short, +}} +pub type LPDLGTEMPLATEA = *mut DLGTEMPLATE; +pub type LPDLGTEMPLATEW = *mut DLGTEMPLATE; +pub type LPCDLGTEMPLATEA = *const DLGTEMPLATE; +pub type LPCDLGTEMPLATEW = *const DLGTEMPLATE; +STRUCT!{struct DRAWTEXTPARAMS { + cbSize: ::UINT, + iTabLength: ::c_int, + iLeftMargin: ::c_int, + iRightMargin: ::c_int, + uiLengthDrawn: ::UINT, +}} +pub type LPDRAWTEXTPARAMS = *mut DRAWTEXTPARAMS; +STRUCT!{struct ACCEL { + fVirt: ::BYTE, + key: ::WORD, + cmd: ::WORD, +}} +pub type LPACCEL = *mut ACCEL; +STRUCT!{struct MENUITEMINFOA { + cbSize: ::UINT, + fMask: ::UINT, + fType: ::UINT, + fState: ::UINT, + wID: ::UINT, + hSubMenu: ::HMENU, + hbmpChecked: ::HBITMAP, + hbmpUnchecked: ::HBITMAP, + dwItemData: ::ULONG_PTR, + dwTypeData: ::LPSTR, + cch: ::UINT, + hbmpItem: ::HBITMAP, +}} +pub type LPMENUITEMINFOA = *mut MENUITEMINFOA; +pub type LPCMENUITEMINFOA = *const MENUITEMINFOA; +STRUCT!{struct MENUITEMINFOW { + cbSize: ::UINT, + fMask: ::UINT, + fType: ::UINT, + fState: ::UINT, + wID: ::UINT, + hSubMenu: ::HMENU, + hbmpChecked: ::HBITMAP, + hbmpUnchecked: ::HBITMAP, + dwItemData: ::ULONG_PTR, + dwTypeData: ::LPWSTR, + cch: ::UINT, + hbmpItem: ::HBITMAP, +}} +pub type LPMENUITEMINFOW = *mut MENUITEMINFOW; +pub type LPCMENUITEMINFOW = *const MENUITEMINFOW; +STRUCT!{nodebug struct MSGBOXPARAMSA { + cbSize: ::UINT, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpszText: ::LPCSTR, + lpszCaption: ::LPCSTR, + dwStyle: ::DWORD, + lpszIcon: ::LPCSTR, + dwContextHelpId: ::DWORD_PTR, + lpfnMsgBoxCallback: ::MSGBOXCALLBACK, + dwLanguageId: ::DWORD, +}} +pub type PMSGBOXPARAMSA = *mut MSGBOXPARAMSA; +pub type LPMSGBOXPARAMSA = *mut MSGBOXPARAMSA; +STRUCT!{nodebug struct MSGBOXPARAMSW { + cbSize: ::UINT, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpszText: ::LPCWSTR, + lpszCaption: ::LPCWSTR, + dwStyle: ::DWORD, + lpszIcon: ::LPCWSTR, + dwContextHelpId: ::DWORD_PTR, + lpfnMsgBoxCallback: ::MSGBOXCALLBACK, + dwLanguageId: ::DWORD, +}} +pub type PMSGBOXPARAMSW = *mut MSGBOXPARAMSW; +pub type LPMSGBOXPARAMSW = *mut MSGBOXPARAMSW; +STRUCT!{struct HELPINFO { + cbSize: ::UINT, + iContextType: ::c_int, + iCtrlId: ::c_int, + hItemHandle: ::HANDLE, + dwContextId: ::DWORD, + MousePos: ::POINT, +}} +pub type LPHELPINFO = *mut HELPINFO; +#[allow(trivial_numeric_casts)] +pub fn GET_WHEEL_DELTA_WPARAM(wParam: ::WPARAM) -> ::c_short { + ::HIWORD(wParam as ::DWORD) as ::c_short +} +#[allow(trivial_numeric_casts)] +pub fn GET_KEYSTATE_WPARAM(wparam: ::WPARAM) -> ::c_int { + ::LOWORD(wparam as ::DWORD) as ::c_short as ::c_int +} +#[allow(trivial_numeric_casts)] +pub fn GET_XBUTTON_WPARAM(wparam: ::WPARAM) -> ::c_int { + ::HIWORD(wparam as ::DWORD) as ::c_int +} +pub const SIF_RANGE: ::UINT = 0x0001; +pub const SIF_PAGE: ::UINT = 0x0002; +pub const SIF_POS: ::UINT = 0x0004; +pub const SIF_DISABLENOSCROLL: ::UINT = 0x0008; +pub const SIF_TRACKPOS: ::UINT = 0x0010; +pub const SIF_ALL: ::UINT = SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS; +pub const SW_SCROLLCHILDREN: ::UINT = 0x0001; +pub const SW_INVALIDATE: ::UINT = 0x0002; +pub const SW_ERASE: ::UINT = 0x0004; +pub const SW_SMOOTHSCROLL: ::UINT = 0x0010; +pub const SB_LINEUP: ::c_int = 0; +pub const SB_LINELEFT: ::c_int = 0; +pub const SB_LINEDOWN: ::c_int = 1; +pub const SB_LINERIGHT: ::c_int = 1; +pub const SB_PAGEUP: ::c_int = 2; +pub const SB_PAGELEFT: ::c_int = 2; +pub const SB_PAGEDOWN: ::c_int = 3; +pub const SB_PAGERIGHT: ::c_int = 3; +pub const SB_THUMBPOSITION: ::c_int = 4; +pub const SB_THUMBTRACK: ::c_int = 5; +pub const SB_TOP: ::c_int = 6; +pub const SB_LEFT: ::c_int = 6; +pub const SB_BOTTOM: ::c_int = 7; +pub const SB_RIGHT: ::c_int = 7; +pub const SB_ENDSCROLL: ::c_int = 8; +pub const LR_DEFAULTCOLOR: ::UINT = 0x00000000; +pub const LR_MONOCHROME: ::UINT = 0x00000001; +pub const LR_COLOR: ::UINT = 0x00000002; +pub const LR_COPYRETURNORG: ::UINT = 0x00000004; +pub const LR_COPYDELETEORG: ::UINT = 0x00000008; +pub const LR_LOADFROMFILE: ::UINT = 0x00000010; +pub const LR_LOADTRANSPARENT: ::UINT = 0x00000020; +pub const LR_DEFAULTSIZE: ::UINT = 0x00000040; +pub const LR_VGACOLOR: ::UINT = 0x00000080; +pub const LR_LOADMAP3DCOLORS: ::UINT = 0x00001000; +pub const LR_CREATEDIBSECTION: ::UINT = 0x00002000; +pub const LR_COPYFROMRESOURCE: ::UINT = 0x00004000; +pub const LR_SHARED: ::UINT = 0x00008000; +pub const IMAGE_BITMAP: ::UINT = 0; +pub const IMAGE_ICON: ::UINT = 1; +pub const IMAGE_CURSOR: ::UINT = 2; +pub const IMAGE_ENHMETAFILE: ::UINT = 3; +pub const DT_TOP: ::UINT = 0x00000000; +pub const DT_LEFT: ::UINT = 0x00000000; +pub const DT_CENTER: ::UINT = 0x00000001; +pub const DT_RIGHT: ::UINT = 0x00000002; +pub const DT_VCENTER: ::UINT = 0x00000004; +pub const DT_BOTTOM: ::UINT = 0x00000008; +pub const DT_WORDBREAK: ::UINT = 0x00000010; +pub const DT_SINGLELINE: ::UINT = 0x00000020; +pub const DT_EXPANDTABS: ::UINT = 0x00000040; +pub const DT_TABSTOP: ::UINT = 0x00000080; +pub const DT_NOCLIP: ::UINT = 0x00000100; +pub const DT_EXTERNALLEADING: ::UINT = 0x00000200; +pub const DT_CALCRECT: ::UINT = 0x00000400; +pub const DT_NOPREFIX: ::UINT = 0x00000800; +pub const DT_INTERNAL: ::UINT = 0x00001000; +pub const DT_EDITCONTROL: ::UINT = 0x00002000; +pub const DT_PATH_ELLIPSIS: ::UINT = 0x00004000; +pub const DT_END_ELLIPSIS: ::UINT = 0x00008000; +pub const DT_MODIFYSTRING: ::UINT = 0x00010000; +pub const DT_RTLREADING: ::UINT = 0x00020000; +pub const DT_WORD_ELLIPSIS: ::UINT = 0x00040000; +pub const DT_NOFULLWIDTHCHARBREAK: ::UINT = 0x00080000; +pub const DT_HIDEPREFIX: ::UINT = 0x00100000; +pub const DT_PREFIXONLY: ::UINT = 0x00200000; +STRUCT!{struct KBDLLHOOKSTRUCT { + vkCode: ::DWORD, + scanCode: ::DWORD, + flags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PKBDLLHOOKSTRUCT = *mut KBDLLHOOKSTRUCT; +pub type LPKBDLLHOOKSTRUCT = *mut KBDLLHOOKSTRUCT; +STRUCT!{struct MSLLHOOKSTRUCT { + pt: ::POINT, + mouseData: ::DWORD, + flags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PMSLLHOOKSTRUCT = *mut MSLLHOOKSTRUCT; +pub type LPMSLLHOOKSTRUCT = *mut MSLLHOOKSTRUCT; +pub const WH_MIN: ::c_int = -1; +pub const WH_MSGFILTER: ::c_int = -1; +pub const WH_JOURNALRECORD: ::c_int = 0; +pub const WH_JOURNALPLAYBACK: ::c_int = 1; +pub const WH_KEYBOARD: ::c_int = 2; +pub const WH_GETMESSAGE: ::c_int = 3; +pub const WH_CALLWNDPROC: ::c_int = 4; +pub const WH_CBT: ::c_int = 5; +pub const WH_SYSMSGFILTER: ::c_int = 6; +pub const WH_MOUSE: ::c_int = 7; +pub const WH_HARDWARE: ::c_int = 8; +pub const WH_DEBUG: ::c_int = 9; +pub const WH_SHELL: ::c_int = 10; +pub const WH_FOREGROUNDIDLE: ::c_int = 11; +pub const WH_CALLWNDPROCRET: ::c_int = 12; +pub const WH_KEYBOARD_LL: ::c_int = 13; +pub const WH_MOUSE_LL: ::c_int = 14; +pub const WH_MAX: ::c_int = 14; +pub const WH_MINHOOK: ::c_int = WH_MIN; +pub const WH_MAXHOOK: ::c_int = WH_MAX; +pub const KLF_ACTIVATE: ::UINT = 1; +pub const KLF_SUBSTITUTE_OK: ::UINT = 2; +pub const KLF_UNLOADPREVIOUS: ::UINT = 4; +pub const KLF_REORDER: ::UINT = 8; +pub const KLF_REPLACELANG: ::UINT = 16; +pub const KLF_NOTELLSHELL: ::UINT = 128; +pub const KLF_SETFORPROCESS: ::UINT = 256; +//RedrawWindow() flags +pub const RDW_INVALIDATE: ::UINT = 0x0001; +pub const RDW_INTERNALPAINT: ::UINT = 0x0002; +pub const RDW_ERASE: ::UINT = 0x0004; +pub const RDW_VALIDATE: ::UINT = 0x0008; +pub const RDW_NOINTERNALPAINT: ::UINT = 0x0010; +pub const RDW_NOERASE: ::UINT = 0x0020; +pub const RDW_NOCHILDREN: ::UINT = 0x0040; +pub const RDW_ALLCHILDREN: ::UINT = 0x0080; +pub const RDW_UPDATENOW: ::UINT = 0x0100; +pub const RDW_ERASENOW: ::UINT = 0x0200; +pub const RDW_FRAME: ::UINT = 0x0400; +pub const RDW_NOFRAME: ::UINT = 0x0800; +STRUCT!{struct MEASUREITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + itemID: ::UINT, + itemWidth: ::UINT, + itemHeight: ::UINT, + itemData: ::ULONG_PTR, +}} +pub type LPMEASUREITEMSTRUCT = *mut MEASUREITEMSTRUCT; +STRUCT!{struct DRAWITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + itemID: ::UINT, + itemAction: ::UINT, + itemState: ::UINT, + hwndItem: ::HWND, + hDC: ::HDC, + rcItem: ::RECT, + itemData: ::ULONG_PTR, +}} +pub type LPDRAWITEMSTRUCT = *mut DRAWITEMSTRUCT; +STRUCT!{struct DELETEITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + itemID: ::UINT, + hwndItem: ::HWND, + itemData: ::ULONG_PTR, +}} +pub type LPDELETEITEMSTRUCT = *mut DELETEITEMSTRUCT; +STRUCT!{struct COMPAREITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + hwndItem: ::HWND, + itemID1: ::UINT, + itemData1: ::ULONG_PTR, + itemID2: ::UINT, + itemData2: ::ULONG_PTR, + dwLocaleId: ::DWORD, +}} +pub type LPCOMPAREITEMSTRUCT = *mut COMPAREITEMSTRUCT; +/* Image type */ +pub const DST_COMPLEX: ::UINT = 0x0000; +pub const DST_TEXT: ::UINT = 0x0001; +pub const DST_PREFIXTEXT: ::UINT = 0x0002; +pub const DST_ICON: ::UINT = 0x0003; +pub const DST_BITMAP: ::UINT = 0x0004; +pub const DI_MASK: ::UINT = 0x0001; +pub const DI_IMAGE: ::UINT = 0x0002; +pub const DI_NORMAL: ::UINT = 0x0003; +pub const DI_COMPAT: ::UINT = 0x0004; +pub const DI_DEFAULTSIZE: ::UINT = 0x0008; +// if WINVER >= 0x0601 +// GetSystemMetrics(SM_DIGITIZER) flag values +pub const NID_INTEGRATED_TOUCH: ::UINT = 0x00000001; +pub const NID_EXTERNAL_TOUCH: ::UINT = 0x00000002; +pub const NID_INTEGRATED_PEN: ::UINT = 0x00000004; +pub const NID_EXTERNAL_PEN: ::UINT = 0x00000008; +pub const NID_MULTI_INPUT: ::UINT = 0x00000040; +pub const NID_READY: ::UINT = 0x00000080; +// end if WINVER >= 0x0601 + +// System Menu Command Values +// +pub const SC_SIZE: ::WPARAM = 0xF000; +pub const SC_MOVE: ::WPARAM = 0xF010; +pub const SC_MINIMIZE: ::WPARAM = 0xF020; +pub const SC_MAXIMIZE: ::WPARAM = 0xF030; +pub const SC_NEXTWINDOW: ::WPARAM = 0xF040; +pub const SC_PREVWINDOW: ::WPARAM = 0xF050; +pub const SC_CLOSE: ::WPARAM = 0xF060; +pub const SC_VSCROLL: ::WPARAM = 0xF070; +pub const SC_HSCROLL: ::WPARAM = 0xF080; +pub const SC_MOUSEMENU: ::WPARAM = 0xF090; +pub const SC_KEYMENU: ::WPARAM = 0xF100; +pub const SC_ARRANGE: ::WPARAM = 0xF110; +pub const SC_RESTORE: ::WPARAM = 0xF120; +pub const SC_TASKLIST: ::WPARAM = 0xF130; +pub const SC_SCREENSAVE: ::WPARAM = 0xF140; +pub const SC_HOTKEY: ::WPARAM = 0xF150; +// if WINVER >= 0x0400 +pub const SC_DEFAULT: ::WPARAM = 0xF160; +pub const SC_MONITORPOWER: ::WPARAM = 0xF170; +pub const SC_CONTEXTHELP: ::WPARAM = 0xF180; +pub const SC_SEPARATOR: ::WPARAM = 0xF00F; +// endif WINVER >= 0x0400 diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ws2def.rs b/bash-5.1/vendor/winapi-0.2.8/src/ws2def.rs new file mode 100644 index 0000000..dcc4aaa --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ws2def.rs @@ -0,0 +1,279 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! This file contains the core definitions for the Winsock2 specification that can be used by +//! both user-mode and kernel mode modules. +pub type ADDRESS_FAMILY = ::USHORT; +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_PUP: ::c_int = 4; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_NS: ::c_int = 6; +pub const AF_IPX: ::c_int = AF_NS; +pub const AF_ISO: ::c_int = 7; +pub const AF_OSI: ::c_int = AF_ISO; +pub const AF_ECMA: ::c_int = 8; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_CCITT: ::c_int = 10; +pub const AF_SNA: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_LAT: ::c_int = 14; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_NETBIOS: ::c_int = 17; +pub const AF_VOICEVIEW: ::c_int = 18; +pub const AF_FIREFOX: ::c_int = 19; +pub const AF_UNKNOWN1: ::c_int = 20; +pub const AF_BAN: ::c_int = 21; +pub const AF_ATM: ::c_int = 22; +pub const AF_INET6: ::c_int = 23; +pub const AF_CLUSTER: ::c_int = 24; +pub const AF_12844: ::c_int = 25; +pub const AF_IRDA: ::c_int = 26; +pub const AF_NETDES: ::c_int = 28; +pub const AF_TCNPROCESS: ::c_int = 29; +pub const AF_TCNMESSAGE: ::c_int = 30; +pub const AF_ICLFXBM: ::c_int = 31; +pub const AF_BTH: ::c_int = 32; +pub const AF_LINK: ::c_int = 33; +pub const AF_MAX: ::c_int = 34; +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOL_SOCKET: ::c_int = 0xffff; +pub const SO_DEBUG: ::c_int = 0x0001; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_DONTLINGER: ::c_int = !SO_LINGER; +pub const SO_EXCLUSIVEADDRUSE: ::c_int = !SO_REUSEADDR; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_BSP_STATE: ::c_int = 0x1009; +pub const SO_GROUP_ID: ::c_int = 0x2001; +pub const SO_GROUP_PRIORITY: ::c_int = 0x2002; +pub const SO_MAX_MSG_SIZE: ::c_int = 0x2003; +pub const SO_CONDITIONAL_ACCEPT: ::c_int = 0x3002; +pub const SO_PAUSE_ACCEPT: ::c_int = 0x3003; +pub const SO_COMPARTMENT_ID: ::c_int = 0x3004; +pub const SO_RANDOMIZE_PORT: ::c_int = 0x3005; +pub const SO_PORT_SCALABILITY: ::c_int = 0x3006; +pub const WSK_SO_BASE: ::c_int = 0x4000; +pub const TCP_NODELAY: ::c_int = 0x0001; +STRUCT!{struct SOCKADDR { + sa_family: ADDRESS_FAMILY, + sa_data: [::CHAR; 14], +}} +pub type PSOCKADDR = *mut SOCKADDR; +pub type LPSOCKADDR = *mut SOCKADDR; +STRUCT!{struct SOCKET_ADDRESS { + lpSockaddr: LPSOCKADDR, + iSockaddrLength: ::INT, +}} +pub type PSOCKET_ADDRESS = *mut SOCKET_ADDRESS; +pub type LPSOCKET_ADDRESS = *mut SOCKET_ADDRESS; +STRUCT!{nodebug struct SOCKET_ADDRESS_LIST { + iAddressCount: ::INT, + Address: [SOCKET_ADDRESS; 0], +}} +pub type PSOCKET_ADDRESS_LIST = *mut SOCKET_ADDRESS_LIST; +pub type LPSOCKET_ADDRESS_LIST = *mut SOCKET_ADDRESS_LIST; +STRUCT!{struct CSADDR_INFO { + LocalAddr: SOCKET_ADDRESS, + RemoteAddr: SOCKET_ADDRESS, + iSocketType: ::INT, + iProtocol: ::INT, +}} +pub type PCSADDR_INFO = *mut CSADDR_INFO; +pub type LPCSADDR_INFO = *mut CSADDR_INFO; +STRUCT!{nodebug struct SOCKADDR_STORAGE_LH { + ss_family: ADDRESS_FAMILY, + __ss_pad1: [::CHAR; 6], + __ss_align: ::__int64, + __ss_pad2: [::CHAR; 112], +}} +pub type PSOCKADDR_STORAGE_LH = *mut SOCKADDR_STORAGE_LH; +pub type LPSOCKADDR_STORAGE_LH = *mut SOCKADDR_STORAGE_LH; +STRUCT!{nodebug struct SOCKADDR_STORAGE_XP { + ss_family: ::c_short, + __ss_pad1: [::CHAR; 6], + __ss_align: ::__int64, + __ss_pad2: [::CHAR; 112], +}} +pub type PSOCKADDR_STORAGE_XP = *mut SOCKADDR_STORAGE_XP; +pub type LPSOCKADDR_STORAGE_XP = *mut SOCKADDR_STORAGE_XP; +pub type SOCKADDR_STORAGE = SOCKADDR_STORAGE_LH; +pub type PSOCKADDR_STORAGE = *mut SOCKADDR_STORAGE; +pub type LPSOCKADDR_STORAGE = *mut SOCKADDR_STORAGE; +STRUCT!{struct SOCKET_PROCESSOR_AFFINITY { + Processor: ::PROCESSOR_NUMBER, + NumaNodeId: ::USHORT, + Reserved: ::USHORT, +}} +pub type PSOCKET_PROCESSOR_AFFINITY = *mut SOCKET_PROCESSOR_AFFINITY; +pub const IOC_UNIX: ::DWORD = 0x00000000; +pub const IOC_WS2: ::DWORD = 0x08000000; +pub const IOC_PROTOCOL: ::DWORD = 0x10000000; +pub const IOC_VENDOR: ::DWORD = 0x18000000; +pub const IOC_WSK: ::DWORD = IOC_WS2 | 0x07000000; +macro_rules! _WSAIO { ($x:expr, $y:expr) => { IOC_VOID | $x | $y } } +macro_rules! _WSAIOR { ($x:expr, $y:expr) => { IOC_OUT | $x | $y } } +macro_rules! _WSAIOW { ($x:expr, $y:expr) => { IOC_IN | $x | $y } } +macro_rules! _WSAIORW { ($x:expr, $y:expr) => { IOC_INOUT | $x | $y } } +pub const SIO_ASSOCIATE_HANDLE: ::DWORD = _WSAIOW!(IOC_WS2, 1); +pub const SIO_ENABLE_CIRCULAR_QUEUEING: ::DWORD = _WSAIO!(IOC_WS2, 2); +pub const SIO_FIND_ROUTE: ::DWORD = _WSAIOR!(IOC_WS2, 3); +pub const SIO_FLUSH: ::DWORD = _WSAIO!(IOC_WS2, 4); +pub const SIO_GET_BROADCAST_ADDRESS: ::DWORD = _WSAIOR!(IOC_WS2, 5); +pub const SIO_GET_EXTENSION_FUNCTION_POINTER: ::DWORD = _WSAIORW!(IOC_WS2, 6); +pub const SIO_GET_QOS: ::DWORD = _WSAIORW!(IOC_WS2, 7); +pub const SIO_GET_GROUP_QOS: ::DWORD = _WSAIORW!(IOC_WS2, 8); +pub const SIO_MULTIPOINT_LOOPBACK: ::DWORD = _WSAIOW!(IOC_WS2, 9); +pub const SIO_MULTICAST_SCOPE: ::DWORD = _WSAIOW!(IOC_WS2, 10); +pub const SIO_SET_QOS: ::DWORD = _WSAIOW!(IOC_WS2, 11); +pub const SIO_SET_GROUP_QOS: ::DWORD = _WSAIOW!(IOC_WS2, 12); +pub const SIO_TRANSLATE_HANDLE: ::DWORD = _WSAIORW!(IOC_WS2, 13); +pub const SIO_ROUTING_INTERFACE_QUERY: ::DWORD = _WSAIORW!(IOC_WS2, 20); +pub const SIO_ROUTING_INTERFACE_CHANGE: ::DWORD = _WSAIOW!(IOC_WS2, 21); +pub const SIO_ADDRESS_LIST_QUERY: ::DWORD = _WSAIOR!(IOC_WS2, 22); +pub const SIO_ADDRESS_LIST_CHANGE: ::DWORD = _WSAIO!(IOC_WS2, 23); +pub const SIO_QUERY_TARGET_PNP_HANDLE: ::DWORD = _WSAIOR!(IOC_WS2, 24); +pub const SIO_QUERY_RSS_PROCESSOR_INFO: ::DWORD = _WSAIOR!(IOC_WS2, 37); +pub const SIO_ADDRESS_LIST_SORT: ::DWORD = _WSAIORW!(IOC_WS2, 25); +pub const SIO_RESERVED_1: ::DWORD = _WSAIOW!(IOC_WS2, 26); +pub const SIO_RESERVED_2: ::DWORD = _WSAIOW!(IOC_WS2, 33); +pub const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: ::DWORD = _WSAIORW!(IOC_WS2, 36); +pub const IPPROTO_IP: ::c_int = 0; +ENUM!{enum IPPROTO { + IPPROTO_HOPOPTS = 0, // IPv6 Hop-by-Hop options + IPPROTO_ICMP = 1, + IPPROTO_IGMP = 2, + IPPROTO_GGP = 3, + IPPROTO_IPV4 = 4, + IPPROTO_ST = 5, + IPPROTO_TCP = 6, + IPPROTO_CBT = 7, + IPPROTO_EGP = 8, + IPPROTO_IGP = 9, + IPPROTO_PUP = 12, + IPPROTO_UDP = 17, + IPPROTO_IDP = 22, + IPPROTO_RDP = 27, + IPPROTO_IPV6 = 41, // IPv6 header + IPPROTO_ROUTING = 43, // IPv6 Routing header + IPPROTO_FRAGMENT = 44, // IPv6 fragmentation header + IPPROTO_ESP = 50, // encapsulating security payload + IPPROTO_AH = 51, // authentication header + IPPROTO_ICMPV6 = 58, // ICMPv6 + IPPROTO_NONE = 59, // IPv6 no next header + IPPROTO_DSTOPTS = 60, // IPv6 Destination options + IPPROTO_ND = 77, + IPPROTO_ICLFXBM = 78, + IPPROTO_PIM = 103, + IPPROTO_PGM = 113, + IPPROTO_L2TP = 115, + IPPROTO_SCTP = 132, + IPPROTO_RAW = 255, + IPPROTO_MAX = 256, + IPPROTO_RESERVED_RAW = 257, + IPPROTO_RESERVED_IPSEC = 258, + IPPROTO_RESERVED_IPSECOFFLOAD = 259, + IPPROTO_RESERVED_WNV = 260, + IPPROTO_RESERVED_MAX = 261, +}} +pub type PIPPROTO = *mut IPPROTO; +STRUCT!{struct SOCKADDR_IN { + sin_family: ADDRESS_FAMILY, + sin_port: ::USHORT, + sin_addr: ::IN_ADDR, + sin_zero: [::CHAR; 8], +}} +pub type PSOCKADDR_IN = *mut SOCKADDR_IN; +//645 +pub const IOCPARM_MASK: ::DWORD = 0x7f; +pub const IOC_VOID: ::DWORD = 0x20000000; +pub const IOC_OUT: ::DWORD = 0x40000000; +pub const IOC_IN: ::DWORD = 0x80000000; +pub const IOC_INOUT: ::DWORD = IOC_IN | IOC_OUT; +STRUCT!{struct WSABUF { + len: ::ULONG, + buf: *mut ::CHAR, +}} +pub type LPWSABUF = *mut WSABUF; +STRUCT!{struct WSAMSG { + name: LPSOCKADDR, + namelen: ::INT, + lpBuffers: LPWSABUF, + dwBufferCount: ::ULONG, + Control: WSABUF, + dwFlags: ::ULONG, +}} +pub type PWSAMSG = *mut WSAMSG; +pub type LPWSAMSG = *mut WSAMSG; +STRUCT!{struct ADDRINFOA { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: *mut ::c_char, + ai_addr: *mut SOCKADDR, + ai_next: *mut ADDRINFOA, +}} +pub type PADDRINFOA = *mut ADDRINFOA; +STRUCT!{struct ADDRINFOW { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: ::PWSTR, + ai_addr: *mut SOCKADDR, + ai_next: *mut ADDRINFOW, +}} +pub type PADDRINFOW = *mut ADDRINFOW; +STRUCT!{struct ADDRINFOEXA { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: *mut ::c_char, + ai_addr: *mut SOCKADDR, + ai_blob: *mut ::c_void, + ai_bloblen: ::size_t, + ai_provider: ::LPGUID, + ai_next: *mut ADDRINFOEXW, +}} +pub type PADDRINFOEXA = *mut ADDRINFOEXA; +pub type LPADDRINFOEXA = *mut ADDRINFOEXA; +STRUCT!{struct ADDRINFOEXW { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: ::PWSTR, + ai_addr: *mut SOCKADDR, + ai_blob: *mut ::c_void, + ai_bloblen: ::size_t, + ai_provider: ::LPGUID, + ai_next: *mut ADDRINFOEXW, +}} +pub type PADDRINFOEXW = *mut ADDRINFOEXW; +pub type LPADDRINFOEXW = *mut ADDRINFOEXW; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ws2ipdef.rs b/bash-5.1/vendor/winapi-0.2.8/src/ws2ipdef.rs new file mode 100644 index 0000000..86d3ffa --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ws2ipdef.rs @@ -0,0 +1,42 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub const IPV6_HOPOPTS: ::c_int = 1; +pub const IPV6_HDRINCL: ::c_int = 2; +pub const IPV6_UNICAST_HOPS: ::c_int = 4; +pub const IPV6_MULTICAST_IF: ::c_int = 9; +pub const IPV6_MULTICAST_HOPS: ::c_int = 10; +pub const IPV6_MULTICAST_LOOP: ::c_int = 11; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = 12; +pub const IPV6_JOIN_GROUP: ::c_int = IPV6_ADD_MEMBERSHIP; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = 13; +pub const IPV6_LEAVE_GROUP: ::c_int = IPV6_DROP_MEMBERSHIP; +pub const IPV6_DONTFRAG: ::c_int = 14; +pub const IPV6_PKTINFO: ::c_int = 19; +pub const IPV6_HOPLIMIT: ::c_int = 21; +pub const IPV6_PROTECTION_LEVEL: ::c_int = 23; +pub const IPV6_RECVIF: ::c_int = 24; +pub const IPV6_RECVDSTADDR: ::c_int = 25; +pub const IPV6_CHECKSUM: ::c_int = 26; +pub const IPV6_V6ONLY: ::c_int = 27; +pub const IPV6_IFLIST: ::c_int = 28; +pub const IPV6_ADD_IFLIST: ::c_int = 29; +pub const IPV6_DEL_IFLIST: ::c_int = 30; +pub const IPV6_UNICAST_IF: ::c_int = 31; +pub const IPV6_RTHDR: ::c_int = 32; +pub const IPV6_RECVRTHDR: ::c_int = 38; +pub const IPV6_TCLASS: ::c_int = 39; +pub const IPV6_RECVTCLASS: ::c_int = 40; +STRUCT!{struct ipv6_mreq { + ipv6mr_multiaddr: in6_addr, + ipv6mr_interface: ::c_uint, +}} +STRUCT!{struct in6_addr { + s6_addr: [u8; 16], +}} +STRUCT!{struct sockaddr_in6 { + sin6_family: ::c_short, + sin6_port: ::c_ushort, + sin6_flowinfo: ::c_ulong, + sin6_addr: in6_addr, + sin6_scope_id: ::c_ulong, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ws2spi.rs b/bash-5.1/vendor/winapi-0.2.8/src/ws2spi.rs new file mode 100644 index 0000000..9df67c1 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ws2spi.rs @@ -0,0 +1,57 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! Definitions to be used with the WinSock service provider +pub const WSPDESCRIPTION_LEN: usize = 255; +STRUCT!{nodebug struct WSPDATA { + wVersion: ::WORD, + wHighVersion: ::WORD, + szDescription: [::WCHAR; WSPDESCRIPTION_LEN + 1], +}} +pub type LPWSPDATA = *mut WSPDATA; +STRUCT!{struct WSATHREADID { + ThreadHandle: ::HANDLE, + Reserved: ::DWORD_PTR, +}} +pub type LPWSATHREADID = *mut WSATHREADID; +pub type LPNSPV2STARTUP = Option<unsafe extern "system" fn( + lpProviderId: ::LPGUID, ppvClientSessionArg: *mut ::LPVOID, +) -> ::INT>; +pub type LPNSPV2CLEANUP = Option<unsafe extern "system" fn( + lpProviderId: ::LPGUID, pvClientSessionArg: ::LPVOID, +) -> ::INT>; +pub type LPNSPV2LOOKUPSERVICEBEGIN = Option<unsafe extern "system" fn( + lpProviderId: ::LPGUID, lpqsRestrictions: ::LPWSAQUERYSET2W, dwControlFlags: ::DWORD, + lpvClientSessionArg: ::LPVOID, lphLookup: ::LPHANDLE, +) -> ::INT>; +pub type LPNSPV2LOOKUPSERVICENEXTEX = Option<unsafe extern "system" fn( + hAsyncCall: ::HANDLE, hLookup: ::HANDLE, dwControlFlags: ::DWORD, lpdwBufferLength: ::LPDWORD, + lpqsResults: ::LPWSAQUERYSET2W +)>; +pub type LPNSPV2LOOKUPSERVICEEND = Option<unsafe extern "system" fn(hLookup: ::HANDLE) -> ::INT>; +pub type LPNSPV2SETSERVICEEX = Option<unsafe extern "system" fn( + hAsyncCall: ::HANDLE, lpProviderId: ::LPGUID, lpqsRegInfo: ::LPWSAQUERYSET2W, + essOperation: ::WSAESETSERVICEOP, dwControlFlags: ::DWORD, lpvClientSessionArg: ::LPVOID, +)>; +pub type LPNSPV2CLIENTSESSIONRUNDOWN = Option<unsafe extern "system" fn( + lpProviderId: ::LPGUID, pvClientSessionArg: ::LPVOID, +)>; +STRUCT!{nodebug struct NSPV2_ROUTINE { + cbSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + NSPv2Startup: LPNSPV2STARTUP, + NSPv2Cleanup: LPNSPV2CLEANUP, + NSPv2LookupServiceBegin: LPNSPV2LOOKUPSERVICEBEGIN, + NSPv2LookupServiceNextEx: LPNSPV2LOOKUPSERVICENEXTEX, + NSPv2LookupServiceEnd: LPNSPV2LOOKUPSERVICEEND, + NSPv2SetServiceEx: LPNSPV2SETSERVICEEX, + NSPv2ClientSessionRundown: LPNSPV2CLIENTSESSIONRUNDOWN, +}} +pub type PNSPV2_ROUTINE = *mut NSPV2_ROUTINE; +pub type LPNSPV2_ROUTINE = *mut NSPV2_ROUTINE; +pub type PCNSPV2_ROUTINE = *const NSPV2_ROUTINE; +pub type LPCNSPV2_ROUTINE = *const NSPV2_ROUTINE; +ENUM!{enum WSC_PROVIDER_INFO_TYPE { + ProviderInfoLspCategories, + ProviderInfoAudit, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/ws2tcpip.rs b/bash-5.1/vendor/winapi-0.2.8/src/ws2tcpip.rs new file mode 100644 index 0000000..d60c841 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/ws2tcpip.rs @@ -0,0 +1,27 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License <LICENSE.md> +//! WinSock2 Extension for TCP/IP protocols +pub type LPLOOKUPSERVICE_COMPLETION_ROUTINE = Option<unsafe extern "system" fn( + dwError: ::DWORD, dwBytes: ::DWORD, lpOverlapped: ::LPWSAOVERLAPPED, +)>; +pub type socklen_t = ::c_int; +STRUCT!{struct ip_mreq { + imr_multiaddr: ::in_addr, + imr_interface: ::in_addr, +}} +pub const IP_OPTIONS: ::c_int = 1; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_TOS: ::c_int = 3; +pub const IP_TTL: ::c_int = 4; +pub const IP_MULTICAST_IF: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_MULTICAST_LOOP: ::c_int = 11; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; +pub const IP_DONTFRAGMENT: ::c_int = 14; +pub const IP_ADD_SOURCE_MEMBERSHIP: ::c_int = 15; +pub const IP_DROP_SOURCE_MEMBERSHIP: ::c_int = 16; +pub const IP_BLOCK_SOURCE: ::c_int = 17; +pub const IP_UNBLOCK_SOURCE: ::c_int = 18; +pub const IP_PKTINFO: ::c_int = 19; +pub const IP_RECEIVE_BROADCAST: ::c_int = 22; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/wtypes.rs b/bash-5.1/vendor/winapi-0.2.8/src/wtypes.rs new file mode 100644 index 0000000..36c8059 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/wtypes.rs @@ -0,0 +1,75 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License <LICENSE.md> +//! Mappings for the contents of wstypes.h +ENUM!{enum VARENUM { + VT_EMPTY = 0, + VT_NULL = 1, + VT_I2 = 2, + VT_I4 = 3, + VT_R4 = 4, + VT_R8 = 5, + VT_CY = 6, + VT_DATE = 7, + VT_BSTR = 8, + VT_DISPATCH = 9, + VT_ERROR = 10, + VT_BOOL = 11, + VT_VARIANT = 12, + VT_UNKNOWN = 13, + VT_DECIMAL = 14, + VT_I1 = 16, + VT_UI1 = 17, + VT_UI2 = 18, + VT_UI4 = 19, + VT_I8 = 20, + VT_UI8 = 21, + VT_INT = 22, + VT_UINT = 23, + VT_VOID = 24, + VT_HRESULT = 25, + VT_PTR = 26, + VT_SAFEARRAY = 27, + VT_CARRAY = 28, + VT_USERDEFINED = 29, + VT_LPSTR = 30, + VT_LPWSTR = 31, + VT_RECORD = 36, + VT_INT_PTR = 37, + VT_UINT_PTR = 38, + VT_FILETIME = 64, + VT_BLOB = 65, + VT_STREAM = 66, + VT_STORAGE = 67, + VT_STREAMED_OBJECT = 68, + VT_STORED_OBJECT = 69, + VT_BLOB_OBJECT = 70, + VT_CF = 71, + VT_CLSID = 72, + VT_VERSIONED_STREAM = 73, + VT_BSTR_BLOB = 0xfff, + VT_VECTOR = 0x1000, + VT_ARRAY = 0x2000, + VT_BYREF = 0x4000, + VT_RESERVED = 0x8000, + VT_ILLEGAL = 0xffff, +}} +pub const VT_ILLEGALMASKED: VARENUM = VT_BSTR_BLOB; +pub const VT_TYPEMASK: VARENUM = VT_BSTR_BLOB; +pub type DATE = ::c_double; +STRUCT!{struct CY { + int64: ::LONGLONG, +}} +STRUCT!{struct DECIMAL { + wReserved: ::USHORT, + scale: ::BYTE, + sign: ::BYTE, + Hi32: ::ULONG, + Lo64: ::ULONGLONG, +}} +pub const DECIMAL_NEG: ::BYTE = 0x80; +pub type LPDECIMAL = *mut DECIMAL; +pub type VARTYPE = ::c_ushort; +pub type wireBSTR = *mut ::FLAGGED_WORD_BLOB; +pub type BSTR = *mut ::OLECHAR; +pub type LPBSTR = *mut BSTR; +pub type VARIANT_BOOL = ::c_short; diff --git a/bash-5.1/vendor/winapi-0.2.8/src/wtypesbase.rs b/bash-5.1/vendor/winapi-0.2.8/src/wtypesbase.rs new file mode 100644 index 0000000..8683c53 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/wtypesbase.rs @@ -0,0 +1,37 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//114 +pub type OLECHAR = ::WCHAR; +pub type LPOLESTR = *mut OLECHAR; +pub type LPCOLESTR = *const OLECHAR; +//147 +pub type DOUBLE = ::c_double; +//281 +pub type SCODE = ::LONG; +pub type PSCODE = *mut SCODE; +STRUCT!{struct BLOB { + cbSize: ::ULONG, + pBlobData: *mut ::BYTE, +}} +pub type LPBLOB = *mut BLOB; +STRUCT!{struct FLAGGED_WORD_BLOB { + fFlags: ::ULONG, + clSize: ::ULONG, + asData: [::c_ushort; 1], +}} +STRUCT!{struct BYTE_SIZEDARR { + clSize: ::ULONG, + pData: *mut ::BYTE, +}} +STRUCT!{struct WORD_SIZEDARR { + clSize: ::ULONG, + pData: *mut ::c_ushort, +}} +STRUCT!{struct DWORD_SIZEDARR { + clSize: ::ULONG, + pData: *mut ::ULONG, +}} +STRUCT!{struct HYPER_SIZEDARR { + clSize: ::ULONG, + pData: *mut i64, +}} diff --git a/bash-5.1/vendor/winapi-0.2.8/src/xinput.rs b/bash-5.1/vendor/winapi-0.2.8/src/xinput.rs new file mode 100644 index 0000000..d18d465 --- /dev/null +++ b/bash-5.1/vendor/winapi-0.2.8/src/xinput.rs @@ -0,0 +1,118 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +//! XInput procedure declarations, constant definitions and macros +pub const XINPUT_DEVTYPE_GAMEPAD: ::BYTE = 0x01; +pub const XINPUT_DEVSUBTYPE_GAMEPAD: ::BYTE = 0x01; +pub const XINPUT_DEVSUBTYPE_WHEEL: ::BYTE = 0x02; +pub const XINPUT_DEVSUBTYPE_ARCADE_STICK: ::BYTE = 0x03; +pub const XINPUT_DEVSUBTYPE_FLIGHT_SICK: ::BYTE = 0x04; +pub const XINPUT_DEVSUBTYPE_DANCE_PAD: ::BYTE = 0x05; +pub const XINPUT_DEVSUBTYPE_GUITAR: ::BYTE = 0x06; +pub const XINPUT_DEVSUBTYPE_DRUM_KIT: ::BYTE = 0x08; +pub const XINPUT_CAPS_VOICE_SUPPORTED: ::WORD = 0x0004; +pub const XINPUT_GAMEPAD_DPAD_UP: ::WORD = 0x0001; +pub const XINPUT_GAMEPAD_DPAD_DOWN: ::WORD = 0x0002; +pub const XINPUT_GAMEPAD_DPAD_LEFT: ::WORD = 0x0004; +pub const XINPUT_GAMEPAD_DPAD_RIGHT: ::WORD = 0x0008; +pub const XINPUT_GAMEPAD_START: ::WORD = 0x0010; +pub const XINPUT_GAMEPAD_BACK: ::WORD = 0x0020; +pub const XINPUT_GAMEPAD_LEFT_THUMB: ::WORD = 0x0040; +pub const XINPUT_GAMEPAD_RIGHT_THUMB: ::WORD = 0x0080; +pub const XINPUT_GAMEPAD_LEFT_SHOULDER: ::WORD = 0x0100; +pub const XINPUT_GAMEPAD_RIGHT_SHOULDER: ::WORD = 0x0200; +pub const XINPUT_GAMEPAD_A: ::WORD = 0x1000; +pub const XINPUT_GAMEPAD_B: ::WORD = 0x2000; +pub const XINPUT_GAMEPAD_X: ::WORD = 0x4000; +pub const XINPUT_GAMEPAD_Y: ::WORD = 0x8000; +pub const XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE: ::SHORT = 7849; +pub const XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE: ::SHORT = 8689; +pub const XINPUT_GAMEPAD_TRIGGER_THRESHOLD: ::BYTE = 30; +pub const XINPUT_FLAG_GAMEPAD: ::DWORD = 0x00000001; +pub const BATTERY_DEVTYPE_GAMEPAD: ::BYTE = 0x00; +pub const BATTERY_DEVTYPE_HEADSET: ::BYTE = 0x01; +pub const BATTERY_TYPE_DISCONNECTED: ::BYTE = 0x00; +pub const BATTERY_TYPE_WIRED: ::BYTE = 0x01; +pub const BATTERY_TYPE_ALKALINE: ::BYTE = 0x02; +pub const BATTERY_TYPE_NIMH: ::BYTE = 0x03; +pub const BATTERY_TYPE_UNKNOWN: ::BYTE = 0xFF; +pub const BATTERY_LEVEL_EMPTY: ::BYTE = 0x00; +pub const BATTERY_LEVEL_LOW: ::BYTE = 0x01; +pub const BATTERY_LEVEL_MEDIUM: ::BYTE = 0x02; +pub const BATTERY_LEVEL_FULL: ::BYTE = 0x03; +pub const XUSER_MAX_COUNT: ::DWORD = 4; +pub const XUSER_INDEX_ANY: ::DWORD = 0x000000FF; +pub const VK_PAD_A: ::WORD = 0x5800; +pub const VK_PAD_B: ::WORD = 0x5801; +pub const VK_PAD_X: ::WORD = 0x5802; +pub const VK_PAD_Y: ::WORD = 0x5803; +pub const VK_PAD_RSHOULDER: ::WORD = 0x5804; +pub const VK_PAD_LSHOULDER: ::WORD = 0x5805; +pub const VK_PAD_LTRIGGER: ::WORD = 0x5806; +pub const VK_PAD_RTRIGGER: ::WORD = 0x5807; +pub const VK_PAD_DPAD_UP: ::WORD = 0x5810; +pub const VK_PAD_DPAD_DOWN: ::WORD = 0x5811; +pub const VK_PAD_DPAD_LEFT: ::WORD = 0x5812; +pub const VK_PAD_DPAD_RIGHT: ::WORD = 0x5813; +pub const VK_PAD_START: ::WORD = 0x5814; +pub const VK_PAD_BACK: ::WORD = 0x5815; +pub const VK_PAD_LTHUMB_PRESS: ::WORD = 0x5816; +pub const VK_PAD_RTHUMB_PRESS: ::WORD = 0x5817; +pub const VK_PAD_LTHUMB_UP: ::WORD = 0x5820; +pub const VK_PAD_LTHUMB_DOWN: ::WORD = 0x5821; +pub const VK_PAD_LTHUMB_RIGHT: ::WORD = 0x5822; +pub const VK_PAD_LTHUMB_LEFT: ::WORD = 0x5823; +pub const VK_PAD_LTHUMB_UPLEFT: ::WORD = 0x5824; +pub const VK_PAD_LTHUMB_UPRIGHT: ::WORD = 0x5825; +pub const VK_PAD_LTHUMB_DOWNRIGHT: ::WORD = 0x5826; +pub const VK_PAD_LTHUMB_DOWNLEFT: ::WORD = 0x5827; +pub const VK_PAD_RTHUMB_UP: ::WORD = 0x5830; +pub const VK_PAD_RTHUMB_DOWN: ::WORD = 0x5831; +pub const VK_PAD_RTHUMB_RIGHT: ::WORD = 0x5832; +pub const VK_PAD_RTHUMB_LEFT: ::WORD = 0x5833; +pub const VK_PAD_RTHUMB_UPLEFT: ::WORD = 0x5834; +pub const VK_PAD_RTHUMB_UPRIGHT: ::WORD = 0x5835; +pub const VK_PAD_RTHUMB_DOWNRIGHT: ::WORD = 0x5836; +pub const VK_PAD_RTHUMB_DOWNLEFT: ::WORD = 0x5837; +pub const XINPUT_KEYSTROKE_KEYDOWN: ::WORD = 0x0001; +pub const XINPUT_KEYSTROKE_KEYUP: ::WORD = 0x0002; +pub const XINPUT_KEYSTROKE_REPEAT: ::WORD = 0x0004; +STRUCT!{struct XINPUT_GAMEPAD { + wButtons: ::WORD, + bLeftTrigger: ::BYTE, + bRightTrigger: ::BYTE, + sThumbLX: ::SHORT, + sThumbLY: ::SHORT, + sThumbRX: ::SHORT, + sThumbRY: ::SHORT, +}} +pub type PXINPUT_GAMEPAD = *mut XINPUT_GAMEPAD; +STRUCT!{struct XINPUT_STATE { + dwPacketNumber: ::DWORD, + Gamepad: ::XINPUT_GAMEPAD, +}} +pub type PXINPUT_STATE = *mut XINPUT_STATE; +STRUCT!{struct XINPUT_VIBRATION { + wLeftMotorSpeed: ::WORD, + wRightMotorSpeed: ::WORD, +}} +pub type PXINPUT_VIBRATION = *mut XINPUT_VIBRATION; +STRUCT!{struct XINPUT_CAPABILITIES { + Type: ::BYTE, + SubType: ::BYTE, + Flags: ::WORD, + Gamepad: ::XINPUT_GAMEPAD, + Vibration: ::XINPUT_VIBRATION, +}} +pub type PXINPUT_CAPABILITIES = *mut XINPUT_CAPABILITIES; +STRUCT!{struct XINPUT_BATTERY_INFORMATION { + BatteryType: ::BYTE, + BatteryLevel: ::BYTE, +}} +pub type PXINPUT_BATTERY_INFORMATION = *mut XINPUT_BATTERY_INFORMATION; +STRUCT!{struct XINPUT_KEYSTROKE { + VirtualKey: ::WORD, + Unicode: ::WCHAR, + UserIndex: ::BYTE, + HidCode: ::BYTE, +}} +pub type PXINPUT_KEYSTROKE = *mut XINPUT_KEYSTROKE; diff --git a/bash-5.1/vendor/winapi-build/.cargo-checksum.json b/bash-5.1/vendor/winapi-build/.cargo-checksum.json new file mode 100644 index 0000000..4d5fc4c --- /dev/null +++ b/bash-5.1/vendor/winapi-build/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"982633c62ba05c95429b1768896a54c9a032a40fbd1e11049a9b087e9fd89176","src/lib.rs":"1d88932534b784973d3d87ac18cd8f2a0294ce5166cf30488c68ca90443e1750"},"package":"2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"} \ No newline at end of file diff --git a/bash-5.1/vendor/winapi-build/Cargo.toml b/bash-5.1/vendor/winapi-build/Cargo.toml new file mode 100644 index 0000000..e1be0b1 --- /dev/null +++ b/bash-5.1/vendor/winapi-build/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "winapi-build" +version = "0.1.1" +authors = ["Peter Atashian <retep998@gmail.com>"] +description = "Common code for build.rs in WinAPI -sys crates." +repository = "https://github.com/retep998/winapi-rs" +keywords = ["Windows", "FFI", "WinSDK"] +license = "MIT" + +[lib] +name = "build" diff --git a/bash-5.1/vendor/winapi-build/src/lib.rs b/bash-5.1/vendor/winapi-build/src/lib.rs new file mode 100644 index 0000000..fab0c6c --- /dev/null +++ b/bash-5.1/vendor/winapi-build/src/lib.rs @@ -0,0 +1,14 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License <LICENSE.md> +pub fn link(name: &str, bundled: bool) { + use std::env::var; + let target = var("TARGET").unwrap(); + let target: Vec<_> = target.split('-').collect(); + if target.get(2) == Some(&"windows") { + println!("cargo:rustc-link-lib=dylib={}", name); + if bundled && target.get(3) == Some(&"gnu") { + let dir = var("CARGO_MANIFEST_DIR").unwrap(); + println!("cargo:rustc-link-search=native={}/{}", dir, target[0]); + } + } +} diff --git a/record.txt b/record.txt index 0c58efb..51f635a 100644 --- a/record.txt +++ b/record.txt @@ -117,3 +117,4 @@ 116 117 118 +119 -- Gitee